crbench//

← all cases

Handlers are now built once per context instead of per event, so the PayoutFees the fee schedule keeps for each payout.paid handler, which charges each seller once, stops charging the payout fee after a seller's first payout

Tier 1 easy typescript · cross-file · authored, execution-grounded case

Ground-truth defects

d1 · correctness · high · payout-paid.handler.ts:12
The diff changes how handlers are built and called: ingestEvents (ingest.ts) used to call createHandler, which built a new handler for every event, and now calls handlerFor (registry.ts), which builds one handler per event type and HandlerContext on first use and hands every later event of that type to the same instance; it updates the lifetime in the Handler doc comment and docs/handlers.md. Handler.run() already started every event with an empty postings list and a new copy of the event, and no hook's signature or contract changes. PayoutPaidHandler (payout-paid.handler.ts), which the diff doesn't touch, charges the flat payout fee through `this.ctx.fees.payout(this).charge(line.account, line.currency)`. The fee schedule (FeeSchedule in fees.ts), also untouched, keeps one PayoutFees per owner in a WeakMap, so the PayoutFees payout.paid asks for lives exactly as long as the handler. PayoutFees (payout-fees.ts) remembers the accounts it has charged in a Set and returns the flat fee only the first time it sees an account, which implemented the pricing rule "once per seller in a payout" (FeeTable's payoutFlat in fees.ts, and the payout test) while each payout got a new handler and so a new owner. With one handler for every payout.paid event, a seller is charged on their first payout after the process starts and never again: every later payout posts no payout fee, with no error or reject, and the platform's payout fee revenue and the sellers' balances are off by the fee on every repeat payout. Nothing in the class is wrong on its own, and the repo's payout tests pass (each ingests a single payout). Nothing else a shared handler holds changes behaviour: InstantPayoutHandler asks the fee schedule for the event's PayoutFees (`payout(event, speed)`), so its sellers are charged once per payout either way; the 48 rule handlers' WarnOnce and charge.captured's and transfer.created's LineDedupe hold Sets of keys but clear them when they see a new event object, which run() makes for every event; and the rate cache is the context's, which ingest shared before the change too. The handlers are reached only through the HANDLERS table in registry.ts. The project's history shows the habit the diff breaks: each earlier change to how the base class calls the hooks (a finish() hook after the last line, currencies lower-cased before the hooks) changed, in the same commit, the handlers that depended on the old calling behaviour (dispute.lost and payout.failed, which detected the last line themselves; tax.collected and climate.contribution, which compared upper-case codes).

The change under review

diff
diff --git a/docs/handlers.md b/docs/handlers.md
index 3cf4fcd..53048d2 100644
--- a/docs/handlers.md
+++ b/docs/handlers.md
@@ -5,7 +5,8 @@ A handler posts one type of settlement event to the ledger. Each is a subclass o
 
 ## Lifetime
 
-`ingestEvents` builds a new handler for every event.
+The registry builds one handler of each type per context, the first time an event of
+that type arrives, and that handler handles every later event of its type.
 
 ## Hooks
 
diff --git a/handler.ts b/handler.ts
index 569de73..c8b30d1 100644
--- a/handler.ts
+++ b/handler.ts
@@ -5,7 +5,8 @@ import type { Posting } from "./posting";
 /**
  * A handler posts one type of settlement event to the ledger.
  *
- * ingest builds a new handler for every event.
+ * The registry builds one handler of each type per context, the first time an event of
+ * that type arrives, and that handler handles every later event of its type.
  *
  * run() calls the hooks prepare(event) once, then handle(line, event) for each of the
  * event's lines, and finish(event) once after the last line.
diff --git a/ingest.ts b/ingest.ts
index cf44cb6..4c615e0 100644
--- a/ingest.ts
+++ b/ingest.ts
@@ -1,7 +1,7 @@
 import type { HandlerContext } from "./context";
 import { InvalidEvent, type SettlementEvent } from "./event";
 import type { Ledger } from "./ledger";
-import { createHandler } from "./registry";
+import { handlerFor } from "./registry";
 
 export interface IngestReport {
   posted: number;
@@ -23,7 +23,7 @@ export function ingestEvents(
       report.duplicates += 1;
       continue;
     }
-    const handler = createHandler(event.type, ctx);
+    const handler = handlerFor(event.type, ctx);
     if (!handler) {
       report.unknown[event.type] = (report.unknown[event.type] ?? 0) + 1;
       continue;
diff --git a/registry.ts b/registry.ts
index 7531b6d..541bbfa 100644
--- a/registry.ts
+++ b/registry.ts
@@ -175,8 +175,22 @@ export const HANDLERS: Record<string, HandlerClass> = {
   "financing.repaid": FinancingRepaidHandler,
 };
 
-/** A new handler for `type`, or undefined for a type we don't handle. */
-export function createHandler(type: string, ctx: HandlerContext): Handler | undefined {
-  const cls = HANDLERS[type];
-  return cls && new cls(ctx);
+const built = new WeakMap<HandlerContext, Map<string, Handler>>();
+
+/** The handler for `type`, built the first time it is asked for and kept for every later
+ * event of that type with the same context; undefined for a type we don't handle. */
+export function handlerFor(type: string, ctx: HandlerContext): Handler | undefined {
+  let handlers = built.get(ctx);
+  if (!handlers) {
+    handlers = new Map();
+    built.set(ctx, handlers);
+  }
+  let handler = handlers.get(type);
+  if (!handler) {
+    const cls = HANDLERS[type];
+    if (!cls) return undefined;
+    handler = new cls(ctx);
+    handlers.set(type, handler);
+  }
+  return handler;
 }
diff --git a/test/ingest.test.ts b/test/ingest.test.ts
index 5115223..2fc7880 100644
--- a/test/ingest.test.ts
+++ b/test/ingest.test.ts
@@ -5,6 +5,7 @@ import { createContext } from "../context";
 import type { SettlementEvent } from "../event";
 import { ingestEvents } from "../ingest";
 import { Ledger } from "../ledger";
+import { handlerFor } from "../registry";
 
 function charge(id: string, amount: number): SettlementEvent {
   return {
@@ -50,3 +51,26 @@ test("skips an event the ledger already has", () => {
   assert.equal(report.duplicates, 1);
   assert.equal(ledger.entries().length, 1);
 });
+
+test("builds one handler per type and context", () => {
+  const ctx = createContext(loadConfig({}));
+  assert.equal(handlerFor("charge.succeeded", ctx), handlerFor("charge.succeeded", ctx));
+  assert.notEqual(
+    handlerFor("charge.succeeded", ctx),
+    handlerFor("charge.succeeded", createContext(loadConfig({}))),
+  );
+  assert.equal(handlerFor("account.updated", ctx), undefined);
+});
+
+test("each event gets its own postings", () => {
+  const ledger = new Ledger();
+  const ctx = createContext(loadConfig({}));
+  ingestEvents([charge("evt_1", 1250), charge("evt_2", 300)], ledger, ctx);
+  assert.deepEqual(
+    ledger.entries().map((row) => [row.eventId, row.amount]),
+    [
+      ["evt_1", 1250],
+      ["evt_2", 300],
+    ],
+  );
+});

Leaderboard for this case

easy · 9 of 9 bots fully caught it (100% solve rate) · 100% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 Claude Code (Opus 5.5) solved 1/1 100.0% 2 0
2 Cubic solved 1/1 100.0% 1 0
3 cursor solved 1/1 100.0% 1 0
4 Drape (Deep Review) solved 1/1 100.0% 1 0
5 Drape (Review) solved 1/1 100.0% 1 0
6 greptile solved 1/1 100.0% 1 0
7 Mjolnir (Opus 5.5) solved 1/1 100.0% 2 0
8 Mjolnir (Sonnet 5.5) solved 1/1 100.0% 2 0
9 qodo solved 1/1 100.0% 1 0

Bot results

Claude Code (Opus 5.5) · cross-file engine bifrost 0.11.0
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
valid · impact high
`FeeSchedule.payout(owner)` keeps one PayoutFees per owner in a WeakMap, and PayoutPaidHandler passes `this` as the owner. PayoutFees.charge returns the flat fee only the first time it sees an account and 0 after that. Before this change every event got a fresh handler, so the set of charged accounts reset per payout. Now `handlerFor` caches the handler for each context, and main.ts builds one context for the whole process. So after a seller's first payout, every later payout.paid event charges that seller no fee. [grounded: tree payout-paid.handler.ts] [consensus 3/3: valid=3]
raw comments (2)
payout-paid.handler.ts:12
PayoutPaidHandler gets its fees from `this.ctx.fees.payout(this)`, which caches one `PayoutFees` per handler object (`fees.ts` `payout()`, using a WeakMap keyed by owner). `PayoutFees.charge` adds the flat fee only the first time it sees an account. Before this change a new handler was built for every event, so each payout started with a fresh `PayoutFees` and every seller paid the flat fee once per payout. `handlerFor` now reuses one handler per context, and `main.ts` creates a single context for the whole server process. So after a seller's first `payout.paid` event, every later payout to them posts a fee of 0 (`post()` skips zero amounts). The platform silently stops collecting payout fees until the process restarts. The new 'each event gets its own postings' test only covers `charge.succeeded`, so it doesn't catch this.
registry.ts:182
`handlerFor` keeps handler instances for the life of the context, which in production is the whole process (`main.ts` builds one context for the webhook server). Every handler was written for the old rule that `ingestEvents` builds a new handler for every event, and nothing checks that they keep no per-event state on the instance. `PayoutPaidHandler` already breaks because of this, and any future handler that keeps state in `prepare` will too. Either make the handlers stateless (for example, key `PayoutFees` by the event, as `InstantPayoutHandler` does) or keep building a new handler for each event.
Cubic · cross-file engine bifrost 0.11.0
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
raw comments (2)
registry.ts:193
<!-- cubic:v=17c41e60-d6ea-4ee1-b19f-68982d2fa803 --> <!-- cubic:review-run=40122534-868e-5876-9b3c-8d231e003076 --> <!-- metadata:{"confidence":9} --> P1: Reusing handlers breaks payout.paid fee charging. PayoutPaidHandler passes `this` to `fees.payout()`, and that PayoutFees remembers every seller account it has already charged. Now that the handler persists per context, only the first payout.paid for each seller since startup gets the flat fee, and later payouts get 0. Scope the fees to the event instead, as InstantPayoutHandler does: change `this.ctx.fees.payout(this)` to `this.ctx.fees.payout(event)` in payout-paid.handler.ts. Also add a test with two payout.paid events for the same account in one context. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At registry.ts, line 193: <comment>Reusing handlers breaks payout.paid fee charging. PayoutPaidHandler passes `this` to `fees.payout()`, and that PayoutFees remembers every seller account it has already charged. Now that the handler persists per context, only the first payout.paid for each seller since startup gets the flat fee, and later payouts get 0. Scope the fees to the event instead, as InstantPayoutHandler does: change `this.ctx.fees.payout(this)` to `this.ctx.fees.payout(event)` in payout-paid.handler.ts. Also add a test with two payout.paid events for the same account in one context.</comment> <file context> @@ -175,8 +175,22 @@ export const HANDLERS: Record<string, HandlerClass> = { + const cls = HANDLERS[type]; + if (!cls) return undefined; + handler = new cls(ctx); + handlers.set(type, handler); + } + return handler; </file context> ``` </details>
PR-level
<!-- cubic:review-summary:start --> **1 issue found** across 5 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="registry.ts"> <violation number="1" location="registry.ts:193"> P1: Reusing handlers breaks payout.paid fee charging. PayoutPaidHandler passes `this` to `fees.payout()`, and that PayoutFees remembers every seller account it has already charged. Now that the handler persists per context, only the first payout.paid for each seller since startup gets the flat fee, and later payouts get 0. Scope the fees to the event instead, as InstantPayoutHandler does: change `this.ctx.fees.payout(this)` to `this.ctx.fees.payout(event)` in payout-paid.handler.ts. Also add a test with two payout.paid events for the same account in one context.</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[View guided diff](https://www.cubic.dev/pr/drape-io/crbench-cubic-2026-09/pull/148?utm_source=github&utm_medium=review_footer) | [Turn on auto-fix](https://www.cubic.dev/action/auto-fix/pr/drape-io/crbench-cubic-2026-09/148?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F148) | [Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/148/ai_pr_review_github_delivery_ec19cfd1d191ea407e248485e1e1397e01234da5d477762d8d822e27b89a1dea?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F148)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_ec19cfd1d191ea407e248485e1e1397e01234da5d477762d8d822e27b89a1dea:5a2feb6305b6acdfb1fe876678b862b4babaa260:40122534-868e-5876-9b3c-8d231e003076 -->
cursor · cross-file engine bifrost 0.11.0
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
raw comments (2)
registry.ts:195
### Reused handler skips later payout fees **High Severity** <!-- DESCRIPTION START --> Reusing one `PayoutPaidHandler` per context keeps the `PayoutFees` object that `payout(this)` keys on that handler, so `charge` still treats a seller as already billed. Later `payout.paid` events for the same seller skip the flat fee and understate fee revenue and seller balances. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: fa837181-4471-4559-b62b-6a8adf468c75 --> <!-- LOCATIONS START registry.ts#L177-L196 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjU4NDU2NWZmLTFlZTItNGRlYS1iMzVlLWFlNzM1M2JmMmUzMyIsImVuY3J5cHRpb25LZXkiOiJ2S0VQNVdCeDhiWmZ4SXZPWG1wU0xieXdtcl9VU1U5VUlvazJfMkhhYTdFIiwiYnJhbmNoIjoicHItZjYzZmY3NjY2ZSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjU4NDU2NWZmLTFlZTItNGRlYS1iMzVlLWFlNzM1M2JmMmUzMyIsImVuY3J5cHRpb25LZXkiOiJ2S0VQNVdCeDhiWmZ4SXZPWG1wU0xieXdtcl9VU1U5VUlvazJfMkhhYTdFIiwiYnJhbmNoIjoicHItZjYzZmY3NjY2ZSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE0OCwiY29tbWl0U2hhIjoiMGFkODMzMjQwZDNkMzNiYjA2ZmJkYzdlMTRhNDczMzU0NmQxN2FmYSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 0ad833240d3d33bb06fbdc7e14a4733546d17afa. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aToyMzgxOTRjNy1jYzk4LTQzMmEtOWJjMi02ZDJjYjFkZDZmMjQiLCJlbmNyeXB0aW9uS2V5IjoiSjZ6S2hUcjQxaTg3eU9OTnN3T0k0NTJuSkxWSnNEUmZaelNxY21rbHhkbyIsImJyYW5jaCI6InByLWY2M2ZmNzY2NmUiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 0ad833240d3d33bb06fbdc7e14a4733546d17afa. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
raw comments (1)
registry.ts:188
**Payout fee charged only on first payout** `PayoutPaidHandler` gets its per-account fee tracker with `fees.payout(this)`, which assumes a fresh handler for each event. Since `handlerFor` now reuses one handler per context, every later `payout.paid` for that seller finds the account already charged and posts no fee. Key the tracker on the event, `fees.payout(event)`, as `InstantPayoutHandler` does. ``` registry.ts:178 const built = new WeakMap<HandlerContext, Map<string, Handler>>(); registry.ts:180 /** The handler for `type`, built the first time it is asked for and kept for every later registry.ts:181 * event of that type with the same context; undefined for a type we don't handle. */ registry.ts:182 export function handlerFor(type: string, ctx: HandlerContext): Handler | undefined { payout-paid.handler.ts:12 const fee = this.ctx.fees.payout(this).charge(line.account, line.currency); fees.ts:31 payout(owner: object, speed = "standard"): PayoutFees { fees.ts:32 let fees = this.payouts.get(owner); fees.ts:33 if (!fees) { fees.ts:34 fees = new PayoutFees(this, speed); fees.ts:35 this.payouts.set(owner, fees); ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
raw comments (1)
payout-paid.handler.ts:12
**Payout fee charged only once per seller, ever** `PayoutPaidHandler` keys `fees.payout(this)` on the handler. `handlerFor` now reuses one handler per context, so the charged-account set persists across events and later payouts for the same seller get a fee of 0. Key it on the event, as `InstantPayoutHandler` does: `payout(event)`. ``` registry.ts:178 const built = new WeakMap<HandlerContext, Map<string, Handler>>(); registry.ts:180 /** The handler for `type`, built the first time it is asked for and kept for every later registry.ts:181 * event of that type with the same context; undefined for a type we don't handle. */ registry.ts:182 export function handlerFor(type: string, ctx: HandlerContext): Handler | undefined { fees.ts:26 private readonly payouts = new WeakMap<object, PayoutFees>(); fees.ts:28 constructor(private readonly table: FeeTable = DEFAULT_FEES) {} fees.ts:30 /** The PayoutFees that `owner` charges the flat payout fee through, at `speed`. */ fees.ts:31 payout(owner: object, speed = "standard"): PayoutFees { fees.ts:32 let fees = this.payouts.get(owner); fees.ts:33 if (!fees) { ```
greptile · cross-file engine bifrost 0.11.0
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
raw comments (2)
registry.ts:193
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Later payouts skip fees** Reusing `PayoutPaidHandler` makes distinct `payout.paid` events for the same seller and context share their fee state. The handler passes `this` to `FeeSchedule.payout()`, which keeps one `PayoutFees` per owner. That object remembers every seller already charged. Under the default settings, the first payout charges 25 cents and the second charges nothing, leaving required fee revenue out of the ledger. Keep the fee state tied to each event, as `InstantPayoutHandler` does, and add a test with two payouts for the same seller.
PR-level
<!-- greptile_summary --> <h2><a href="https://app.greptile.com/api/retrigger?id=87707573"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img alt="Retrigger" src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2" align="right"></picture></a><a href="https://app.greptile.com/drape/github/drape-io/crbench-greptile-2026-09/-/pull/148"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptileDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"><img alt="View in Greptile" src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2" align="right"></picture></a>Confidence Score: 4/5</h2> **[Medium impact]** The change reaches the shared settlement\-ingestion path\. Fix the missing fees on later standard payouts before merging. <h2>Findings</h2> 1. <img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top">&nbsp;**Later payouts skip fees** <a href="https://github.com/drape-io/crbench-greptile-2026-09/pull/148#discussion_r4371631036">▶</a> <h3>Summary</h3> The PR builds each handler once per context and reuses it for later events of the same type. - Settlement ingestion reuses one handler for each event type and context. <details open><summary><h3>Diagram</h3></summary> ```mermaid %%{init: {'theme': 'neutral'}}%% flowchart TD A[Two distinct standard payout events] --> B[Same context and cached handler] B --> C[Handler is the fee owner] C --> D[Same saved set of charged sellers] D --> E[First payout charges the flat fee] D --> F[Later payout for that seller charges zero] ``` </details> <!-- greptile_confidence_score:4 --> <sub>Reviews (1) · Last reviewed commit: ["Build each settlement handler once inste..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/72cf424f3e2ef15e83c1b1729006276b70e4d5ec) · [Reviewed by Greptile](https://www.greptile.com/?utm_source=greptile_review&utm_medium=github&utm_campaign=review_private)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
valid · impact high
FeeSchedule.payout caches one PayoutFees per owner (`this.payouts.get(owner)`), and PayoutFees.charge returns 0 once it has charged an account. The handler passes `this` as the owner, and handlerFor now reuses one handler per context (main.ts creates a single context). So every later payout.paid event for a seller posts a zero fee. Before this change each event got a new handler, so fees were only deduplicated within one payout. [grounded: tree payout-paid.handler.ts] [consensus 3/3: valid=3]
raw comments (2)
registry.ts:188
[P1] Reused payout.paid handler charges each seller's flat payout fee only once per context instead of once per payout `PayoutPaidHandler.handle` gets its fee tracker with `this.ctx.fees.payout(this)` (payout-paid.handler.ts:12). `FeeSchedule.payout` caches one `PayoutFees` per owner object, and `PayoutFees.charge` returns the flat fee only the first time it sees an account. Before this change a new handler was built for every event, so each payout got a fresh tracker and the fee was charged once per seller per payout. Now `handlerFor` keeps one `PayoutPaidHandler` for each context. `main.ts:10` creates a single context for the whole lifetime of the webhook server, so every `payout.paid` event goes through the same handler and the same `PayoutFees`. After a seller's first payout, every later payout to that seller posts a fee of 0 (`post` skips zero amounts), so payout fee revenue silently stops being collected. The `charged` set also keeps growing for as long as the process runs. The new tests only cover `charge.succeeded`, so they don't catch this.
registry.ts:189
[P1] Reusing the payout.paid handler stops the flat payout fee after a seller's first payout `PayoutPaidHandler.handle` gets its fee tracker with `this.ctx.fees.payout(this)` (payout-paid.handler.ts:12). `FeeSchedule.payout` caches one `PayoutFees` per owner object, and `PayoutFees.charge` returns 0 for any account it has already charged. Before this change every event got a new handler, so that dedupe only applied within one payout. Now `handlerFor` keeps one handler per context, and main.ts creates a single context for the whole life of the webhook server. As a result every `payout.paid` event in that process shares one `PayoutFees`, and a seller pays the flat fee on their first payout only; every later payout posts a fee of 0, which quietly loses fee revenue. The existing payout test sends a single event, so it doesn't catch this. Two `payout.paid` events for `acct_1` in one context would show the second fee missing. `payout.instant` is not affected because it keys on the per-run event object.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
valid · impact high
PayoutPaidHandler calls `this.ctx.fees.payout(this)`, so its PayoutFees is keyed by the handler instance. PayoutFees.charge returns 0 once the account is already in its `charged` set. Now that handlerFor caches one handler per type and context, that set carries over across payout.paid events, so a later payout for the same seller posts no fee. [grounded: tree fees.ts] [consensus 3/3: valid=3]
raw comments (2)
payout-paid.handler.ts:12
[P1] Shared handler makes the flat payout fee charge once per seller for the whole context, not once per payout The new `handlerFor` caches one handler per type and context, so a single `PayoutPaidHandler` now handles every `payout.paid` event. This handler calls `this.ctx.fees.payout(this)`. `FeeSchedule.payout` (fees.ts:30-37) caches the `PayoutFees` in a WeakMap keyed by that owner, and `PayoutFees.charge` returns 0 for any account it has already seen (payout-fees.ts:12-14). Before this change `ingestEvents` built a new handler per event, so each payout got a fresh `PayoutFees` and each seller paid the flat fee once per payout. Now the `PayoutFees` lives as long as the handler. If seller A appears in `payout.paid` event 1 and again in event 2 (a later payout, same context), event 2 posts a zero fee. The fee is silently under-posted for every payout after a seller's first, and the zero posting is skipped, so there is no error. The fix is probably to key the owner by event (as `InstantPayoutHandler` does with `fees.payout(event, speed)`) in this handler. The new tests only cover `charge.succeeded`, so they don't catch it. Any other handler that relies on per-handler-instance state should also be checked against the new lifetime.
registry.ts:190
[P1] Payout fee now charged once per seller across all payout.paid events Caching one handler per type and context breaks `PayoutPaidHandler`. It calls `this.ctx.fees.payout(this)`, and `FeeSchedule.payout` (fees.ts) keys its `PayoutFees` instance by the owner object, here the handler itself. Before this change each event got a fresh handler, so the flat payout fee was charged once per seller per payout event. Now the same handler, and so the same `PayoutFees.charged` set, is reused for every `payout.paid` event in a context. The first payout posts the fee for a seller. Every later `payout.paid` event for that seller posts a 0 fee, because `charge()` returns 0 once the account is in the set. Any ingest batch, or any reused context, with more than one `payout.paid` event for the same seller account under-charges `PAYOUT_FEE_REVENUE`. The new tests only cover charge events, so they don't catch this. The other per-instance state is safe to share. `LineDedupe` and `WarnOnce` reset when the event object changes, and `instant-payout` keys its fee by the event.
qodo · cross-file engine bifrost 0.11.0
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
raw comments (3)
registry.ts:193
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Later payouts omit sellers' flat fees <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>handlerFor</i></b> reuses <b><i>PayoutPaidHandler</i></b>, which passes itself to <b><i>FeeSchedule.payout()</i></b> as the owner of a fee object that permanently records charged sellers. When distinct <b><i>payout.paid</i></b> events for the same seller share a context, the second event&#x27;s flat fee is zero even though its payout is new. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Cached payout handlers keep the seller-fee deduplication state across distinct payout events, suppressing later flat fees. ## Fix Focus Areas - payout-paid.handler.ts[9-15] - registry.ts[182-195] - test/payouts.test.ts[25-31] ## Recommended Fix Use a fresh fee owner for each payout event rather than the cached handler, while retaining the once-per-seller behavior within that event. Add a test ingesting two distinct payouts for the same seller under one context and asserting that both receive the flat fee. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details> [Dismiss ↗](https://app.qodo.ai/findings/e8c4fdb9-3946-4ae5-9744-99437bff5e27?action=dismiss&origin=git) | [View ↗](https://app.qodo.ai/findings/e8c4fdb9-3946-4ae5-9744-99437bff5e27)
PR-level
<h3>PR Summary by Qodo</h3> Reuse settlement handlers by event type and context <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>📝 Documentation</code> <code>🕐 20-40 Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Cache handlers per event type and context to avoid rebuilding them during settlement replays. >• Keep unknown-event reporting and per-event postings intact, with tests for both behaviors. >• Document the new handler lifetime. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD Ingest["Event ingest"] --> Registry["Handler registry"] --> Cache{"Cached for context?"} Cache -->|hit| Handler["Reusable handler"] --> Ledger["Ledger postings"] Cache -->|miss| Classes["Handler classes"] --> Handler Classes -->|unsupported| Unknown["Unknown report"] ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Cache only within each ingest call</b></summary> <dl> <dd> - ➕ Limits handler state and lifetime to one ingestion batch. - ➕ Avoids a module-level cache. - ➖ Rebuilds handlers when multiple batches share a context. - ➖ Does not provide the documented per-context lifetime. </dd> </dl> </details> >**Recommendation:** The context-scoped cache best matches the goal of reusing handlers across a replay, including across ingest calls. Review event-reset behavior in stateful subclasses before relying on the longer lifetime. </dd> </dl> </details> <details> <summary> Files changed (5) <code> +48 / -8 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (2) <code> +20 / -6 </code></summary> <dl> <dd> <details> <summary>ingest.ts<code>Resolve cached handlers during ingestion</code> <code>+2/-2</code></summary> <br/> >Resolve cached handlers during ingestion > ><pre> >• Uses the registry&#x27;s cached handler lookup instead of constructing a handler for every nonduplicate event. Unknown-type reporting and posting flow remain unchanged. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/148/files#diff-9daa830937212369ed3def5186ba74b5e397b4d62f323ff2e17403f6b672b196'>ingest.ts</a> </details> <details> <summary>registry.ts<code>Cache handlers by context and event type</code> <code>+18/-4</code></summary> <br/> >Cache handlers by context and event type > ><pre> >• Replaces per-call construction with lazy lookup in a WeakMap of context-specific type maps. Unsupported event types still return undefined. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/148/files#diff-58f42611a053bb45add25a11c10ed01c89fa3d17a917ecea2de4fad160568ff8'>registry.ts</a> </details> </dd> </dl> </details> <details> <summary>Tests (1) <code> +24 / -0 </code></summary> <dl> <dd> <details> <summary>ingest.test.ts<code>Test handler reuse and posting isolation</code> <code>+24/-0</code></summary> <br/> >Test handler reuse and posting isolation > ><pre> >• Checks identity reuse within a context, separation across contexts, and unsupported-type lookup. Also verifies that successive events handled by the same instance produce separate postings. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/148/files#diff-32b87323e952007ec9a74573eeaaad6f0e719ed7150ae28f4a2c3d63f0855933'>test/ingest.test.ts</a> </details> </dd> </dl> </details> <details> <summary>Documentation (2) <code> +4 / -2 </code></summary> <dl> <dd> <details> <summary>handlers.md<code>Document context-scoped handler lifetime</code> <code>+2/-1</code></summary> <br/> >Document context-scoped handler lifetime > ><pre> >• Explains that the registry constructs a handler on the first event of each type and reuses it for later events with the same context. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/148/files#diff-12e6db27e83873fe76287d1db2ea4bd66744b63031c890d5b3fecc6900adf807'>docs/handlers.md</a> </details> <details> <summary>handler.ts<code>Clarify the handler lifecycle contract</code> <code>+2/-1</code></summary> <br/> >Clarify the handler lifecycle contract > ><pre> >• Updates the base handler comment to describe reuse by type and context. Handler execution code is unchanged. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/148/files#diff-9884c069eddb59e8287651fd0c8b33c1b211b2ef39e411c3317357289a9c00f8'>handler.ts</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (1)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. Later payouts omit sellers&#x27; flat fees <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>handlerFor</i></b> reuses <b><i>PayoutPaidHandler</i></b>, which passes itself to <b><i>FeeSchedule.payout()</i></b> as the owner >of a fee object that permanently records charged sellers. When distinct <b><i>payout.paid</i></b> events for the >same seller share a context, the second event&#x27;s flat fee is zero even though its payout is new. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[registry.ts[R192-193]](https://github.com/drape-io/crbench-qodo-2026-09/pull/148/files#diff-58f42611a053bb45add25a11c10ed01c89fa3d17a917ecea2de4fad160568ff8R192-R193)</code> > >```diff >+ handler = new cls(ctx); >+ handlers.set(type, handler); >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >Ingestion now retrieves the same handler for a type and context. The payout handler uses its own >identity as the fee owner; the fee schedule caches by owner, and the resulting fee object returns >zero for an account it has previously charged. The existing payout test covers repeated seller lines >within one event, not separate events. ></pre> > > <code>[ingest.ts\[20-32\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/e01a4a6f85b79a777bd8f24bb19addb669ec835b/ingest.ts/#L20-L32)</code> > <code>[registry.ts\[178-195\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/e01a4a6f85b79a777bd8f24bb19addb669ec835b/registry.ts/#L178-L195)</code> > <code>[payout-paid.handler.ts\[9-15\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/e01a4a6f85b79a777bd8f24bb19addb669ec835b/payout-paid.handler.ts/#L9-L15)</code> > <code>[fees.ts\[26-37\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/e01a4a6f85b79a777bd8f24bb19addb669ec835b/fees.ts/#L26-L37)</code> > <code>[payout-fees.ts\[4-16\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/e01a4a6f85b79a777bd8f24bb19addb669ec835b/payout-fees.ts/#L4-L16)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >Cached payout handlers keep the seller-fee deduplication state across distinct payout events, suppressing later flat fees. >## Fix Focus Areas >- payout-paid.handler.ts[9-15] >- registry.ts[182-195] >- test/payouts.test.ts[25-31] >## Recommended Fix >Use a fresh fee owner for each payout event rather than the cached handler, while retaining the once-per-seller behavior within that event. Add a test ingesting two distinct payouts for the same seller under one context and asserting that both receive the flat fee. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> [Dismiss ↗](https://app.qodo.ai/findings/e8c4fdb9-3946-4ae5-9744-99437bff5e27?action=dismiss&origin=git) | [View ↗](https://app.qodo.ai/findings/e8c4fdb9-3946-4ae5-9744-99437bff5e27) <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-self-review-slot --> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>Auto: ⚖️ Balanced</code>: Handler reuse changes runtime lifecycle semantics across multiple settlement paths.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can enable the Remediation agent and Qodo fixes findings in a dedicated fix PR</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/e01a4a6f85b79a777bd8f24bb19addb669ec835b --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>