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 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 · 8 of 9 bots fully caught it (89% solve rate) · 89% avg coverage.

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

Bot results

Claude Code (Opus 5.5) · cross-file engine bifrost 0.11.0
DefectSeverityFoundGrade
d1 high ✓ exact
valid · matches d1 · impact high
raw comments (1)
registry.ts:180
`handlerFor` now reuses one handler per (context, type) for every event, but `PayoutPaidHandler` (payout-paid.handler.ts:12) gets its flat-fee tracker with `this.ctx.fees.payout(this)`. `FeeSchedule.payout` keys a `PayoutFees` by that owner object, and `PayoutFees` remembers every seller it has already charged. Before this change the owner was a new handler for each event, so the 'once per seller' rule applied to each payout. Now the same handler is the owner for every `payout.paid` event in the context, so a seller pays the flat fee only on their first payout. Later payouts post a fee of 0, the fee is silently skipped, and payout fee revenue is under-booked. The new test only covers charges, so it misses this. Either keep building a new handler for each event, or key the fee tracker by `event`, as `InstantPayoutHandler` does.
Cubic · cross-file engine bifrost 0.11.0
DefectSeverityFoundGrade
d1 high ✗ —
raw comments (1)
PR-level
<!-- cubic:review-summary:start --> **No issues found** across 5 files <!-- cubic:review-summary:end --> <sub>[View guided diff](https://www.cubic.dev/pr/drape-io/crbench-cubic-2026-09/pull/149?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/149?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F149) | [Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/149/ai_pr_review_github_delivery_d9bbca5fe1a4a878fb0b541dfe19925c0fcbfc7bd1eb46a7257368b4bdf89dda?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F149)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_d9bbca5fe1a4a878fb0b541dfe19925c0fcbfc7bd1eb46a7257368b4bdf89dda:4adddee36ab80fd1a1f30bb2eb6eef4e5753b8f4:27daf996-9dae-548d-9782-4174811b9c7a -->
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 --> `PayoutPaidHandler` keys `FeeSchedule.payout` on the handler instance, so the cached handler reuses one `PayoutFees` across events. Flat fees then fire only the first time each seller appears, and later `payout.paid` events post no fee. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: bd8d69cb-5b48-4475-bb8a-f96d2535960b --> <!-- LOCATIONS START registry.ts#L181-L195 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjAyNDM1YjdkLTgzYTEtNDJiYi1iNjUxLWQ2YTVhZjEzYWVkNCIsImVuY3J5cHRpb25LZXkiOiJFV3NqSG1jUzlPMTFQa1dnaTA5a2Q3QlV3WVF4bWpIQVQ0SVdCV0EtY0dzIiwiYnJhbmNoIjoicHItNzMwYzVjZWFkNiIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" 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=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjAyNDM1YjdkLTgzYTEtNDJiYi1iNjUxLWQ2YTVhZjEzYWVkNCIsImVuY3J5cHRpb25LZXkiOiJFV3NqSG1jUzlPMTFQa1dnaTA5a2Q3QlV3WVF4bWpIQVQ0SVdCV0EtY0dzIiwiYnJhbmNoIjoicHItNzMwYzVjZWFkNiIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjE0OSwiY29tbWl0U2hhIjoiYmYwMjlhYzM1YjA4ODM2Njg3YzFkOGFiMjU1ZmU2NGQzMTk0YjU3NyIsInByb3ZpZGVyIjoiZ2l0aHViIn19" 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 bf029ac35b08836687c1d8ab255fe64d3194b577. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTplMWVhMTA5NC1iNzI0LTRlZGEtYjg2Ny1jMGMzYzI2ZWU3ZTEiLCJlbmNyeXB0aW9uS2V5IjoiQ183TFQzdGRUSmx1N3pKTEVXOHhIc25rQWhhUGxUQ0RMRElrMEthX1VfWSIsImJyYW5jaCI6InByLTczMGM1Y2VhZDYiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" 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 bf029ac35b08836687c1d8ab255fe64d3194b577. 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
**Repeat payouts to a seller skip fee** `PayoutPaidHandler` tracks charged sellers via `fees.payout(this)`, i.e. per handler. Now that `handlerFor` reuses one handler across events, a seller's second payout gets a fee of 0. Key the fee tracker on the 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: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); ```
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 once per account, ever** `PayoutPaidHandler` keys its `PayoutFees` by `this`. Handlers are now cached per context, so the 'first time' memory in `PayoutFees.charge` outlives each event. A seller who appears in a second `payout.paid` event gets no flat fee. Key the PayoutFees by the event, as `InstantPayoutHandler` does: `this.ctx.fees.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 { payout-paid.handler.ts:12 const fee = this.ctx.fees.payout(this).charge(line.account, line.currency); 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); ```
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 flat fees** Reusing `PayoutPaidHandler` also reuses its payout fee state. The handler calls `ctx.fees.payout(this)`, which returns the same `PayoutFees` each time, and its `charged` set never resets. Two distinct `payout.paid` events for `acct_1` in one context therefore charge the flat fee only on the first event. Later ledger entries record too little fee revenue. Use the event as the fee owner, as `InstantPayoutHandler` does, and add a two-event payout test.
PR-level
<!-- greptile_summary --> <h2><a href="https://app.greptile.com/api/retrigger?id=87707584"><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/149"><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 affects the settlement event ingestion workflow\. Fix the skipped flat 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 flat fees** <a href="https://github.com/drape-io/crbench-greptile-2026-09/pull/149#discussion_r4371632241">▶</a> <h3>Summary</h3> The PR builds each handler once per context and event type instead of once per event. - Settlement ingestion reuses one handler for each event type and context. <details open><summary><h3>Diagram</h3></summary> ```mermaid sequenceDiagram participant I as ingestEvents participant R as Registry participant H as Cached PayoutPaidHandler participant F as PayoutFees I->>R: First payout for acct_1 R->>H: Build and run H->>F: charge(acct_1), owner is handler F-->>H: Flat fee I->>R: Later payout for acct_1 R->>H: Reuse and run H->>F: charge(acct_1), same owner F-->>H: Zero fee ``` </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/ae574010a16c782416edfb99802ebff2a512bd88) · [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 a PayoutFees per owner object, and PayoutFees.charge returns 0 for any account it has already seen. PayoutPaidHandler passes `this` as the owner, so once handlerFor reuses a single handler per context (and main.ts/server.ts use one context for the whole process), each seller pays the flat payout fee only on their first payout.paid event and gets 0 after that. Before this change each event got a new handler, so the fee was charged once per seller per payout. [grounded: tree payout-paid.handler.ts] [consensus 3/3: valid=3]
raw comments (2)
registry.ts:188
[P1] Reused PayoutPaidHandler stops charging the flat payout fee after a seller's first payout `PayoutPaidHandler.handle` gets its fee tracker with `this.ctx.fees.payout(this)`. `FeeSchedule.payout` caches one `PayoutFees` per owner object, and `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 new handler, so every `payout.paid` event got a fresh tracker and each seller was charged once per payout. `handlerFor` now keeps one handler per type and context, so the same `PayoutFees` set is carried from one event to the next. `main.ts` creates one context for the whole webhook server, which means a seller pays the flat fee on their first `payout.paid` event and then posts a 0 fee on every later payout until the process restarts. That loses payout fee revenue without any error. The new test only uses `charge.succeeded`, so it doesn't catch this. The fix is either to key the fee tracker on the event, as `InstantPayoutHandler` does with `payout(event, speed)`, or to not reuse handlers that keep state across events.
registry.ts:182
[P1] Reusing handlers makes `payout.paid` charge each seller's payout fee only once per process `PayoutPaidHandler.handle` (payout-paid.handler.ts:12) gets its fee tracker with `this.ctx.fees.payout(this)`. `FeeSchedule.payout` caches one `PayoutFees` per owner object, and `PayoutFees.charge` returns the flat fee only the first time it sees an account and 0 after that. Before this change, each event got a new handler, so the owner was new and the fee was charged once per seller per payout. Now `handlerFor` keeps a single `PayoutPaidHandler` for each context. The server builds one context for the whole process (main.ts:10, server.ts:36), so a seller pays the flat payout fee on their first `payout.paid` event and then posts a fee of 0 on every later payout. That is silent revenue loss on the ledger. `instant-payout.handler.ts` is not affected because it keys on the per-run event object. The new "each event gets its own postings" test only covers `charge.succeeded`, so it doesn't catch this.
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
FeeSchedule.payout caches a PayoutFees per owner object in a WeakMap, and PayoutFees.charge returns 0 for any account it has already seen. Before this change each event got a new handler and so a fresh PayoutFees. Now the handler is cached per context, so later payout.paid events for the same seller get a fee of 0 and PAYOUT_FEE_REVENUE is under-posted. [grounded: tree payout-paid.handler.ts] [consensus 3/3: valid=3]
raw comments (2)
payout-paid.handler.ts:12
[P1] Reused handler stops charging the payout fee after the first event (triggered by the change at registry.ts:178-195) `PayoutPaidHandler` calls `this.ctx.fees.payout(this)`, and `FeeSchedule.payout` caches one `PayoutFees` per owner object, so the "once per account" state is keyed on the handler instance. `PayoutFees.charge` returns 0 for an account it has already seen. Before this change `ingestEvents` built a new handler for every event, so the dedupe was per event. `handlerFor` now keeps one `PayoutPaidHandler` per context, so the `PayoutFees` persists across events. For example, two `payout.paid` events that both pay acct_1 give the first the flat fee and the second a fee of 0, and `post()` skips zero amounts. Sellers are therefore undercharged on every `payout.paid` event after the first in a context, and the loss is silent. The other handlers either key on the per-run lower-cased event copy (`InstantPayoutHandler`, `WarnOnce`, `LineDedupe`) or keep no per-event state. `PayoutPaidHandler` is the one that keys on `this`. The new test only covers `charge.succeeded`, so it doesn't catch this, and the existing `handlers.test.ts` ingests a single event per context.
registry.ts:188
[P1] Cached handlers break per-event payout fee dedup — Handlers are now reused across events, but `PayoutPaidHandler` (payout-paid.handler.ts:12) calls `this.ctx.fees.payout(this).charge(...)`, and `FeeSchedule.payout` (fees.ts:31-37) keys a stateful `PayoutFees` (a per-account "already charged" Set) on that handler instance. Before this change a new handler was built per event, so each `payout.paid` event charged the flat fee once per seller. With the cached handler, the `PayoutFees` persists for the whole context. The first `payout.paid` event charges seller A the fee, and every later `payout.paid` event for seller A gets 0. This silently under-posts `PAYOUT_FEE_REVENUE` whenever one `ingestEvents` call or context sees more than one payout.paid event for the same seller. The new tests only cover charge.succeeded and don't catch it. The fee owner needs to be per event, as `InstantPayoutHandler` does by passing `event`. Alternatively, handler state must be reset per run
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 skip the seller fee <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>PayoutPaidHandler</i></b> passes its handler instance to <b><i>FeeSchedule.payout()</i></b>, so caching that instance also preserves the set of sellers already charged. When another <b><i>payout.paid</i></b> event for the same seller arrives under the same context, <b><i>PayoutFees.charge()</i></b> returns zero instead of charging the flat fee for that payout. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description Reusing the payout handler makes its fee-owner identity persist across payout events, suppressing the flat fee for sellers charged by an earlier payout. ## Fix Focus Areas - registry.ts[188-193] - payout-paid.handler.ts[10-14] - fees.ts[26-34] ## Recommended Fix Keep handler reuse, but use an event-specific owner for payout fee tracking so lines within one payout share the charged-seller set and separate payout events do not. Add a regression test with two distinct payouts for the same seller. ``` <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/219338ed-0c1f-4f95-b64f-7c692bf4aa5f?action=dismiss&origin=git) | [View ↗](https://app.qodo.ai/findings/219338ed-0c1f-4f95-b64f-7c692bf4aa5f)
PR-level
<h3>PR Summary by Qodo</h3> Reuse settlement handlers per event type and context <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>📝 Documentation</code> <code>🕐 10-20 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 by event type and context to avoid rebuilding them during settlement replays. >• Reuse cached handlers across events while keeping each event’s postings separate. >• Document the new lifetime and test reuse, context isolation, and posting behavior. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid graph TD E["Settlement events"] --> I["Event ingestion"] --> R["Handler registry"] --> H["Reusable handler"] --> L[("Ledger")] R -- "cache by context and type" --> H ``` </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 handlers within each ingest call</b></summary> <dl> <dd> - ➕ Keeps cache lifetime explicit and limited to one batch. - ➖ Rebuilds handlers when separate ingest calls reuse the same context. </dd> </dl> </details> >**Recommendation:** Keep the context-keyed WeakMap: it supports reuse across ingest calls without retaining contexts solely for the cache. Review stateful handlers for assumptions about per-event construction; the base handler resets postings for each run. </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>Retrieve reusable handlers during ingestion</code> <code>+2/-2</code></summary> <br/> >Retrieve reusable handlers during ingestion > ><pre> >• Switches ingestion from creating a handler for each event to requesting the context’s cached handler. Duplicate and unknown-event handling remain in place. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/149/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 the construction function with a lazy lookup backed by a WeakMap of per-context handler maps. Unsupported event types still return undefined. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/149/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> >• Verifies reuse within a context, distinct instances across contexts, and undefined results for unsupported types. Also checks that successive events retain their own posting IDs and amounts. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/149/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 per-context handler lifetime</code> <code>+2/-1</code></summary> <br/> >Document per-context handler lifetime > ><pre> >• Replaces the per-event construction description with the registry’s lazy, per-type and per-context reuse behavior. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/149/files#diff-12e6db27e83873fe76287d1db2ea4bd66744b63031c890d5b3fecc6900adf807'>docs/handlers.md</a> </details> <details> <summary>handler.ts<code>Clarify handler lifetime in the API comment</code> <code>+2/-1</code></summary> <br/> >Clarify handler lifetime in the API comment > ><pre> >• Updates the Handler class documentation to describe instances being reused for later events of the same type and context. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/149/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 skip the seller fee <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>PayoutPaidHandler</i></b> passes its handler instance to <b><i>FeeSchedule.payout()</i></b>, so caching that instance >also preserves the set of sellers already charged. When another <b><i>payout.paid</i></b> event for the same >seller arrives under the same context, <b><i>PayoutFees.charge()</i></b> returns zero instead of charging the >flat fee for that payout. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[registry.ts[R188-193]](https://github.com/drape-io/crbench-qodo-2026-09/pull/149/files#diff-58f42611a053bb45add25a11c10ed01c89fa3d17a917ecea2de4fad160568ff8R188-R193)</code> > >```diff >+ let handler = handlers.get(type); >+ if (!handler) { >+ const cls = HANDLERS[type]; >+ if (!cls) return undefined; >+ handler = new cls(ctx); >+ handlers.set(type, handler); >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The new cache returns the same handler for later events of a type and context. The payout handler >uses itself as the fee owner; the fee schedule caches fee trackers by owner, and each tracker >permanently records charged seller accounts. ></pre> > > <code>[registry.ts\[178-195\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/316fd19d08367e25eb0e7d7854361749a497481f/registry.ts/#L178-L195)</code> > <code>[payout-paid.handler.ts\[10-14\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/316fd19d08367e25eb0e7d7854361749a497481f/payout-paid.handler.ts/#L10-L14)</code> > <code>[fees.ts\[23-34\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/316fd19d08367e25eb0e7d7854361749a497481f/fees.ts/#L23-L34)</code> > <code>[payout-fees.ts\[3-17\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/316fd19d08367e25eb0e7d7854361749a497481f/payout-fees.ts/#L3-L17)</code> > <code>[ingest.ts\[20-35\]](https://github.com/drape-io/crbench-qodo-2026-09/blob/316fd19d08367e25eb0e7d7854361749a497481f/ingest.ts/#L20-L35)</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 >Reusing the payout handler makes its fee-owner identity persist across payout events, suppressing the flat fee for sellers charged by an earlier payout. >## Fix Focus Areas >- registry.ts[188-193] >- payout-paid.handler.ts[10-14] >- fees.ts[26-34] >## Recommended Fix >Keep handler reuse, but use an event-specific owner for payout fee tracking so lines within one payout share the charged-seller set and separate payout events do not. Add a regression test with two distinct payouts for the same seller. >``` > <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/219338ed-0c1f-4f95-b64f-7c692bf4aa5f?action=dismiss&origin=git) | [View ↗](https://app.qodo.ai/findings/219338ed-0c1f-4f95-b64f-7c692bf4aa5f) <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 lifecycle semantics and may expose stateful-handler defects.</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/316fd19d08367e25eb0e7d7854361749a497481f --> <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>