Repository navigation
Add disabled Context request and pilot accounting fixtures - #1250
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Solid & Clean Code | The PR adds the lib/context/accounting/ module, so the code under review is new. The current HEAD (0063d05, which follows b1fa993) still breaks the explicit SRP rule that functions must not exceed 2… | 1. Split runContextAccountingAttempt into small single-purpose functions, each in its own file named after the function. Keep the orchestrator under 20 lines. Suggested units: prior-attempt replay, reservation-hold parsing, dispatch-and-c… |
Full details: Solid & Clean Code
-
Explanation
The PR adds the lib/context/accounting/ module, so the code under review is new. The current HEAD (0063d05, which follows b1fa993) still breaks the explicit SRP rule that functions must not exceed 20 lines. - SRP and function length:
runContextAccountingAttemptspans lines 11-112 in runContextAccountingAttempt.ts, about 100 lines. The function validates input, authorizes, replays prior attempts, looks up reuse, admits, parses reservation receipts, branches on reservation state, dispatches, validates completions, journals updates, and finishes. This is one function with several reasons to change. The prior run measured 145 lines. The function is shorter now but still far over the limit. - DRY: the terminal-phase array["settled", "released", "insufficient", "reused"]still appears three times (run lines 25 and 51; reconcile line 19). The reservation regex/^hold-v1-[a-f0-9]{64}$/still appears in run line 76, finish lines 19 and 34, and validateContextReservationReceipt lines 8 and 14. The same-termsJSON.stringifycomparison still appears in admit line 16, reconcile line 15, and run line 19. The "reused" result shape is still built inline in run (lines 30 and 43-48) and reconcile. - Clean code and error handling: barecatch {}blocks remain at run lines 82 and 108 and finish line 66. They turn every failure intopending_reconciliationwith no classification or logging. Non-null assertions (!) remain on journal lookups (run lines 68, 86, 101; finish lines 43-56; admit line 35). ThecustomerCredits || 1fallback remains at validateContextAccountingCompletion.ts line 29. - Passing points: each accounting file exports one function whose name matches the file name. Dependencies are injected throughContextAccountingServices. The prior FAIL claims still hold on the current code. No priorFailureDisposition is given because the concern is not resolved.Resolution
- Split
runContextAccountingAttemptinto small single-purpose functions, each in its own file named after the function. Keep the orchestrator under 20 lines. Suggested units: prior-attempt replay, reservation-hold parsing, dispatch-and-complete, and reused-result mapping. 2. Move shared constants into one module: the terminal-phase set, thehold-v1-reservation regex, and the same-terms comparison. 3. Build the "reused" result in one helper. Use it from the run and reconcile paths. 4. Split the release and settlement branches offinishContextAccountingAttemptinto separate functions, each with its own schema and receipt validator. 5. Replace barecatch {}with a narrow catch. Classify expected ambiguity separately from unexpected programming errors. Log or rethrow the unexpected ones. 6. Remove the non-null assertions. Check each journal entry and throw a named error when it is missing. 7. Name or remove the|| 1fallback in the charge amount. 8. Have the test fixture reuse the exported exposure helper instead of duplicating it.
- Split
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
There was a problem hiding this comment.
7 issues found across 11 files
Confidence score: 3/5
- In
runContextAccountingAttempt.ts, the secondauthorizecan throw after the journal is markeddispatching, leaving the fullmaximumCreditsheld with no release path. Add a failure path that releases the hold or resets the attempt. - In
admitContextAccountingAttempt.ts, denied attempts leave request and pilot ceilings unpinned, so a retry can change the terms and still be admitted. Pin the terms on the first attempt or reject mismatches. - In
validateContextAccountingInput.ts, case variants of the samerequestIdcan create separate request ceilings. Canonicalize the ID before using it as an identity. - In
finishContextAccountingAttempt.ts, swallowing every error makes a receipt mismatch—and possible ledger divergence—look like a transient lost reply. Log the error with the operation key before returning.
Prompt for AI agents (unresolved issues)
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="lib/context/accounting/finishContextAccountingAttempt.ts">
<violation number="1" location="lib/context/accounting/finishContextAccountingAttempt.ts:66">
P2: The `catch` swallows every error without logging, so a receipt mismatch (which can indicate a ledger divergence) looks identical to a transient lost reply. Log the error server-side with the operation key before returning `pending_reconciliation`, and keep the raw message out of the returned object.</violation>
</file>
<file name="lib/context/accounting/admitContextAccountingAttempt.ts">
<violation number="1" location="lib/context/accounting/admitContextAccountingAttempt.ts:45">
P2: Policies are only pinned on successful admission, so a denied attempt leaves request and pilot ceilings unpinned. A retry for the same request can then change pilot or ceiling terms and still be admitted. If terms should be fixed on first sight, record the policies before the denial return.</violation>
</file>
<file name="lib/context/accounting/__tests__/contextAccounting.test.ts">
<violation number="1" location="lib/context/accounting/__tests__/contextAccounting.test.ts:218">
P3: This test cannot detect a missing atomic reuse recheck. The delayed admission always finds the attempt the second delivery already created, so it returns 'settled' either way. Use a different reuse-triggering scenario, such as a cached result that appears while no attempt exists yet, and assert the reused outcome.</violation>
</file>
<file name="lib/context/accounting/runContextAccountingAttempt.ts">
<violation number="1" location="lib/context/accounting/runContextAccountingAttempt.ts:10">
P2: Custom agent: **Enforce Clear Code Style and Maintainability Practices**
This 145-line module exceeds the rule’s 100-line limit; extract the inline schemas or cohesive workflow stages into focused modules.</violation>
<violation number="2" location="lib/context/accounting/runContextAccountingAttempt.ts:15">
P1: The second `authorize` runs after the journal is already marked `dispatching`. If it throws, nothing dispatched, but the attempt stays `dispatching` and its full `maximumCredits` stays held with no release path. Call `authorize` before the dispatch-intent transaction so a failed check never reaches `dispatching`.</violation>
</file>
<file name="lib/context/accounting/validateContextAccountingInput.ts">
<violation number="1" location="lib/context/accounting/validateContextAccountingInput.ts:11">
P2: `requestId` only gets `.trim()`, so case variants of the same request (e.g. upper- vs lowercase UUID) become separate request ceilings. `payerId` is lowercased for this reason, but the other identities are not. Validate `requestId` as a UUID and canonicalize it. Note that the fixtures use `"request"`, so they need UUID request IDs too.</violation>
</file>
<file name="tsconfig.context-accounting.json">
<violation number="1" location="tsconfig.context-accounting.json:4">
P2: This strict config is not wired into `package.json` or any workflow, so nothing enforces it. Add a `typecheck:context-accounting` script (`tsc --noEmit --project tsconfig.context-accounting.json`) and run it from CI, as the sibling typecheck configs are. Otherwise the strict-mode guarantee claimed in the PR validation will silently rot.</violation>
</file>
Architecture diagram
sequenceDiagram
participant Caller as Context Scheduler (future)
participant Run as runContextAccountingAttempt
participant Val as validateContextAccountingInput
participant Auth as services.authorize
participant Tx as services.transact
participant Ledger as Payer Ledger (in-memory fixture)
participant Reuse as services.findAcceptedReuse
participant Reserve as services.reserveCreditsOnce
participant Dispatch as services.dispatch
participant Finish as finishContextAccountingAttempt
participant Settle as services.settleCreditReservation
participant Release as services.releaseCreditReservation
participant Reconcile as reconcileContextAccountingAttempt
Note over Caller,Reconcile: Fixture-only, dependency-injected accounting adapter (no production wiring)
Caller->>Run: runContextAccountingAttempt(input, services)
Run->>Val: validate input (mode=fixture, billing=context_owned)
Val-->>Run: normalized input
Run->>Auth: authorize(input)
Auth-->>Run: ok
Run->>Tx: check existing attempt
Tx->>Ledger: get attempt by operationKey
Ledger-->>Tx: attempt or null
Tx-->>Run: prior attempt (cloned)
alt Prior attempt exists
Run-->>Caller: return phase (settled/released/insufficient/reused/pending_reconciliation)
else No prior attempt
Run->>Reuse: findAcceptedReuse(input)
Reuse-->>Run: { resultId } or null
Run->>Tx: admit attempt (atomic)
Tx->>Ledger: admitContextAccountingAttempt (payer-scoped ceiling check)
Ledger-->>Tx: admission result
Tx-->>Run: attempt
alt Reused verified analysis
Run-->>Caller: return "reused" (zero debit, no dispatch)
else Denied by ceiling
Run-->>Caller: return "denied"
else Fresh admission
Run->>Reserve: reserveCreditsOnce(operationKey, maximumCredits)
alt Insufficient funds
Reserve-->>Run: { state: "insufficient" }
Run->>Tx: mark attempt insufficient
Tx->>Ledger: set phase = insufficient
Run-->>Caller: return "insufficient"
else Held reservation
Reserve-->>Run: { state: "held", reservationId }
Run->>Tx: mark dispatching (atomic cancel check)
Tx->>Ledger: set phase = dispatching or cancelled
Tx-->>Run: attempt
alt Cancelled before dispatch intent
Run->>Finish: finishContextAccountingAttempt
Finish->>Release: releaseCreditReservation
Release-->>Finish: receipt
Finish->>Tx: mark released
Finish-->>Run: "released"
Run-->>Caller: return "released"
else Dispatch intent won
Run->>Auth: authorize again
Run->>Dispatch: dispatch(input)
alt Dispatch success
Dispatch-->>Run: completion
Run->>Finish: finishContextAccountingAttempt
alt Zero customer credits
Finish->>Release: releaseCreditReservation
Release-->>Finish: receipt
Finish->>Tx: mark released
Finish-->>Run: "released"
else Customer credits > 0
Finish->>Settle: settleCreditReservation(charge)
Settle-->>Finish: receipt (validated)
Finish->>Tx: mark settled
Finish-->>Run: "settled"
end
Run-->>Caller: return final state
else Dispatch failure/unknown
Dispatch-->>Run: error
Run-->>Caller: return "pending_reconciliation" (max exposure retained)
end
end
else Reused hold (not a dispatch lease)
Reserve-->>Run: { state: "reused" }
Run-->>Caller: return "pending_reconciliation" (no dispatch)
end
end
end
Note over Reconcile: Reconciliation path (repeats only saved settlement/release)
Caller->>Reconcile: reconcileContextAccountingAttempt(raw, services)
Reconcile->>Val: validate input
Reconcile->>Auth: authorize
Reconcile->>Tx: fetch attempt by operationKey
Tx->>Ledger: get attempt
Ledger-->>Tx: cloned attempt
Tx-->>Reconcile: attempt
alt Already terminal (settled/released/insufficient/reused)
Reconcile-->>Caller: return terminal state
else Completed/Cancelled unknown
Reconcile->>Finish: finishContextAccountingAttempt
Finish->>Release: repeat saved release (if cancelled/zero)
Finish->>Settle: repeat exact saved settlement (if customer credits)
Finish-->>Reconcile: final state
Reconcile-->>Caller: return final state
end
Note over Ledger: Exposure = settled credits + maximum for all unresolved attempts (BigInt-safe)
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| services: ContextAccountingServices, | ||
| ) { | ||
| const input = validateContextAccountingInput(raw); | ||
| await services.authorize(input); |
There was a problem hiding this comment.
P1: The second authorize runs after the journal is already marked dispatching. If it throws, nothing dispatched, but the attempt stays dispatching and its full maximumCredits stays held with no release path. Call authorize before the dispatch-intent transaction so a failed check never reaches dispatching.
Prompt for AI agents
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 lib/context/accounting/runContextAccountingAttempt.ts, line 15:
<comment>The second `authorize` runs after the journal is already marked `dispatching`. If it throws, nothing dispatched, but the attempt stays `dispatching` and its full `maximumCredits` stays held with no release path. Call `authorize` before the dispatch-intent transaction so a failed check never reaches `dispatching`.</comment>
<file context>
@@ -0,0 +1,145 @@
+ services: ContextAccountingServices,
+) {
+ const input = validateContextAccountingInput(raw);
+ await services.authorize(input);
+ const prior = await services.transact(input.payerId, ledger => {
+ const current = ledger.attempts.get(getContextAccountingKey(input));
</file context>
| @@ -0,0 +1,145 @@ | |||
| import { z } from "zod"; | |||
There was a problem hiding this comment.
P2: Custom agent: Enforce Clear Code Style and Maintainability Practices
This 145-line module exceeds the rule’s 100-line limit; extract the inline schemas or cohesive workflow stages into focused modules.
Prompt for AI agents
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 lib/context/accounting/runContextAccountingAttempt.ts, line 10:
<comment>This 145-line module exceeds the rule’s 100-line limit; extract the inline schemas or cohesive workflow stages into focused modules.</comment>
<file context>
@@ -0,0 +1,145 @@
+import type { ContextAccountingServices } from "./types";
+
+/** Disabled consumer: all effects injected; no production caller, wallet, provider or policy defaults. */
+export async function runContextAccountingAttempt(
+ raw: unknown,
+ services: ContextAccountingServices,
</file context>
| operationKey, | ||
| completion, | ||
| }; | ||
| } catch { |
There was a problem hiding this comment.
P2: The catch swallows every error without logging, so a receipt mismatch (which can indicate a ledger divergence) looks identical to a transient lost reply. Log the error server-side with the operation key before returning pending_reconciliation, and keep the raw message out of the returned object.
Prompt for AI agents
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 lib/context/accounting/finishContextAccountingAttempt.ts, line 66:
<comment>The `catch` swallows every error without logging, so a receipt mismatch (which can indicate a ledger divergence) looks identical to a transient lost reply. Log the error server-side with the operation key before returning `pending_reconciliation`, and keep the raw message out of the returned object.</comment>
<file context>
@@ -0,0 +1,69 @@
+ operationKey,
+ completion,
+ };
+ } catch {
+ return { state: "pending_reconciliation" as const, operationKey };
+ }
</file context>
| (request + BigInt(input.maximumCredits) > BigInt(input.requestCeiling) || | ||
| pilot + BigInt(input.maximumCredits) > BigInt(input.pilotCeiling)) | ||
| ) | ||
| return { created: false, attempt: null }; |
There was a problem hiding this comment.
P2: Policies are only pinned on successful admission, so a denied attempt leaves request and pilot ceilings unpinned. A retry for the same request can then change pilot or ceiling terms and still be admitted. If terms should be fixed on first sight, record the policies before the denial return.
Prompt for AI agents
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 lib/context/accounting/admitContextAccountingAttempt.ts, line 45:
<comment>Policies are only pinned on successful admission, so a denied attempt leaves request and pilot ceilings unpinned. A retry for the same request can then change pilot or ceiling terms and still be admitted. If terms should be fixed on first sight, record the policies before the denial return.</comment>
<file context>
@@ -0,0 +1,59 @@
+ (request + BigInt(input.maximumCredits) > BigInt(input.requestCeiling) ||
+ pilot + BigInt(input.maximumCredits) > BigInt(input.pilotCeiling))
+ )
+ return { created: false, attempt: null };
+ ledger.requestPolicies.set(input.requestId, {
+ pilotId: input.pilotId,
</file context>
| mode: z.literal("fixture"), | ||
| billing: z.literal("context_owned"), | ||
| payerId: z.uuid(), | ||
| requestId: id, |
There was a problem hiding this comment.
P2: requestId only gets .trim(), so case variants of the same request (e.g. upper- vs lowercase UUID) become separate request ceilings. payerId is lowercased for this reason, but the other identities are not. Validate requestId as a UUID and canonicalize it. Note that the fixtures use "request", so they need UUID request IDs too.
Prompt for AI agents
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 lib/context/accounting/validateContextAccountingInput.ts, line 11:
<comment>`requestId` only gets `.trim()`, so case variants of the same request (e.g. upper- vs lowercase UUID) become separate request ceilings. `payerId` is lowercased for this reason, but the other identities are not. Validate `requestId` as a UUID and canonicalize it. Note that the fixtures use `"request"`, so they need UUID request IDs too.</comment>
<file context>
@@ -0,0 +1,22 @@
+ mode: z.literal("fixture"),
+ billing: z.literal("context_owned"),
+ payerId: z.uuid(),
+ requestId: id,
+ pilotId: id,
+ moduleId: id,
</file context>
| expect(f.services.settleCreditReservation).not.toHaveBeenCalled(); | ||
| expect(f.exposure()).toBe(6); | ||
| }); | ||
| it("rechecks reuse atomically after another delivery starts or completes", async () => { |
There was a problem hiding this comment.
P3: This test cannot detect a missing atomic reuse recheck. The delayed admission always finds the attempt the second delivery already created, so it returns 'settled' either way. Use a different reuse-triggering scenario, such as a cached result that appears while no attempt exists yet, and assert the reused outcome.
Prompt for AI agents
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 lib/context/accounting/__tests__/contextAccounting.test.ts, line 218:
<comment>This test cannot detect a missing atomic reuse recheck. The delayed admission always finds the attempt the second delivery already created, so it returns 'settled' either way. Use a different reuse-triggering scenario, such as a cached result that appears while no attempt exists yet, and assert the reused outcome.</comment>
<file context>
@@ -0,0 +1,291 @@
+ expect(f.services.settleCreditReservation).not.toHaveBeenCalled();
+ expect(f.exposure()).toBe(6);
+});
+it("rechecks reuse atomically after another delivery starts or completes", async () => {
+ const f = createAccountingFixture();
+ let resume!: (value: { resultId: string }) => void;
</file context>
There was a problem hiding this comment.
1 existing issue remains and 1 new issue found across 7 files (changes from recent commits).
Confidence score: 3/5
- In
runContextAccountingAttempt.ts, a transientauthorizefailure can cancel the attempt and permanently release its hold. Only treat definitive denials as revocations, and preserve other errors. - In
README.md, calling the IDs “opaque” misses that validation trims whitespace before hashing them into the operation key. Clarify that whitespace is trimmed.
Prompt for AI agents (unresolved issues)
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="lib/context/accounting/runContextAccountingAttempt.ts">
<violation number="1" location="lib/context/accounting/runContextAccountingAttempt.ts:82">
P2: This catch-all treats every `authorize` rejection as a revocation. A transient outage or timeout cancels the attempt and releases the hold permanently, and the error is discarded. Catch only a definitive denial, or rethrow and let the outer catch return `pending_reconciliation`, and log the underlying error.</violation>
</file>
Requires human review: Auto-approval blocked because this review re-detected 2 unresolved issues already reported by Cubic.
View guided diff | Turn on auto-fix | Re-trigger cubic
| let authorizationFailed = false; | ||
| try { | ||
| await services.authorize(input); | ||
| } catch { |
There was a problem hiding this comment.
P2: This catch-all treats every authorize rejection as a revocation. A transient outage or timeout cancels the attempt and releases the hold permanently, and the error is discarded. Catch only a definitive denial, or rethrow and let the outer catch return pending_reconciliation, and log the underlying error.
Prompt for AI agents
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 lib/context/accounting/runContextAccountingAttempt.ts, line 82:
<comment>This catch-all treats every `authorize` rejection as a revocation. A transient outage or timeout cancels the attempt and releases the hold permanently, and the error is discarded. Catch only a definitive denial, or rethrow and let the outer catch return `pending_reconciliation`, and log the underlying error.</comment>
<file context>
@@ -94,46 +76,31 @@ export async function runContextAccountingAttempt(
+ let authorizationFailed = false;
+ try {
+ await services.authorize(input);
+ } catch {
+ authorizationFailed = true;
+ }
</file context>
There was a problem hiding this comment.
0 issues found across 3 files (changes from recent commits).
Confidence score: 5/5
- Automated review surfaced no issues in the provided summaries.
- No files require special attention.
Requires human review: Auto-approval blocked by 8 unresolved issues from previous reviews.
View guided diff | Turn on auto-fix | Re-trigger cubic
Problem and behavior
Context module scheduling does not yet coordinate request/pilot credit ceilings. This adds a disabled, dependency-injected accounting adapter with synthetic fixtures: payer-scoped atomic admission, stable attempt identity, reserve/settle/release ports, durable reuse receipts, cancellation before dispatch intent, and retained uncertainty after lost replies. Duplicate delivery never redispatches providers; reconciliation repeats only a saved settlement or known-safe release.
No live caller, wallet, provider, policy default, migration, or song-analysis debit is added. Existing endpoint-owned billing is explicitly rejected. The structural contract is pinned to API #1026 and database #115; shared reservation/Packs/refill composition remains separately owned. This is a partial fixture-only contribution toward recoupable/app#2123, not production acceptance.
Validation
Merge and activation remain held for explicit approval.
Summary by cubic
Adds a disabled, dependency-injected accounting adapter with synthetic fixtures that models request and pilot credit ceilings for context module scheduling. Nothing is wired into production: no live caller, wallet, provider, policy default, migration, or song-analysis debit, and endpoint-owned billing is explicitly rejected. Transaction callbacks must be synchronous; promise-returning callbacks are rejected at the type boundary.
Behavior
Validation
Written for commit 229f301. Summary will update on new commits.
Coordinator disposition: this source candidate is superseded by merged #1254, which preserves its history and adds the qualified review/composition fixes. Closing this PR avoids competing source candidates; its branch/history remain preserved. Owning-epic authenticated/native/provider/database and business acceptance remain open as separately recorded; source merge does not close those gates.