Skip to content

Compose preserved reservation adapters with current accounting source - #1257

Merged
sidneyswift merged 6 commits into
mainfrom
codex/reservation-adapters-current-main
Nov 17, 2026
Merged

sidneyswift merged 6 commits into
mainfrom
codex/reservation-adapters-current-main

Conversation

@sidneyswift

@sidneyswift sidneyswift commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Result

Preserve the reviewed opt-in reservation adapters from #1249 while normally composing current main aca47f23e38c924e4d5e2fa8b1cc7d417dc6507f. Normal merge 4fda79203a1052537704fd9ab1f3fca616b0494b retains both histories; final head c8828d93c0058b30f4f13aebacef1c00d06b2e39 adds the reviewed README correction. All adapter/validator/test files remain byte-identical to #1249; the README now corrects duplicate receipts to report the hold’s current status and explicitly requires independent dispatch ownership/reconciliation; original #1026 and #1249 remain untouched.

The adapters remain unused by production callers. Actual Context accounting ports accept their real function signatures and receipt variants in a compile-only fixture. Incoming Context strict CI, Packs lifecycle/replay, package scripts and workflows match main exactly. No wallet or behavior changes.

Qualification

Independent exact-head composition review: PASS, no actionable findings. 73 focused reservation/receipt tests, production/contract types and real-function port compatibility passed. Independent README/contract correction review passed; runtime bytes remain unchanged. Final head c8828d9 passes all reported checks: full suite 9,713 passed / 53 skipped, Context strict types, offline Packs replay, production/contract types, format/lint and compatibility. Cubic correction review reports zero issues; CodeRabbit is a review skip. Preview success is not production acceptance. Final qualification is recorded in the coordinator handoff.

Release boundary

Ready for source review only; coordinator owns final merge/release decision after Sites repairs. Database #134/#135 remain draft with no apply. No production wiring, paid execution, provider calls or migration authorization. Source compatibility does not establish durable Context service wiring or deployed settlement.

sidneyswift and others added 5 commits October 10, 2026 16:44
Paid AI work needs a before-call hold and an exactly-once settlement on
the existing wallet (app#2105 milestone 1, reused by Context accounting
app#2123). The current preflight only reads the balance, so concurrent
requests can each pass it.

reserveCreditsOnce, settleCreditReservation and releaseCreditReservation
wrap the new database functions. Inputs are validated before the wallet
is touched; insufficient capacity is a definite receipt so a caller can
return a machine-readable 402. Lost replies and invalid receipts raise
reconciliation errors that keep the operation key; settlement reuses
the charge receipt identity and its CreditChargeNeedsReconciliation.
No caller, price, ceiling, auto-top-up or provider call is added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up for the credit reservation adapters. A returned database
error with SQLSTATE 22023 is raised inside the RPC transaction, which
rolls back, so the call wrote nothing. The adapters now throw
CreditReservationRejected with the fixed database reason in that case,
so a future caller can return a definite 402/409 instead of replaying an
identical call forever. Every other error, lost reply or invalid receipt
still raises the reconciliation error.

The README now says a held receipt is not an execution lease (duplicate
deliveries must be deduplicated by the caller's attempt identity) and
that connecting any caller requires database#101, api#1009 and
database#88.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
api Ready Ready Preview Nov 17, 2026 8:45pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Pre-merge checks: Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Solid & Clean Code Warning Summary: PR #1257 (author login sidneyswift, head c8828d93, base aca47f23) adds three new adapter functions. The three adapters repeat the same code. All three functions are longer than the … Refactor the three adapters so the check passes. Keep the public signatures and receipt variants unchanged. 1. Move the reservation-ID regex and the credits schema into one shared module, for example `lib/credits/reservations/reservationS…
Full details: Solid & Clean Code

Explanation

Summary: PR #1257 (author login sidneyswift, head c8828d93, base aca47f23) adds three new adapter functions. The three adapters repeat the same code. All three functions are longer than the 20-line limit in the SOLID & Clean Code check. The prior FAIL is still valid because the head has not changed. I found no code change that resolves it. Evidence (files read at c8828d93; the diff from base adds 645 lines, all new files): 1. Functions over 20 lines (SRP). The check says to look for functions longer than 20 lines. - reserveCreditsOnce (lib/supabase/credit_reservations/reserveCreditsOnce.ts, lines 41–65) spans 25 lines. Its body is lines 44–64. - settleCreditReservation (settleCreditReservation.ts, lines 30–58) spans 29 lines. Its body is lines 33–58. - releaseCreditReservation (releaseCreditReservation.ts, lines 25–48) spans 24 lines. - Each function validates input, builds the RPC call, maps errors, parses the receipt, checks amounts, and maps failures. This is more than one responsibility. 2. Duplication (DRY). The same blocks appear in all three adapters. - The regex /^hold-v1-[a-f0-9]{64}$/ is an inline literal in reserveCreditsOnce.ts (line 11), settleCreditReservation.ts (line 15) and releaseCreditReservation.ts (line 14). It is not a shared constant. - The const credits = z.number().int().positive(); schema is repeated in all three files (lines 12, 12 and 11). - The supabase.rpc.bind(supabase) as unknown as (...) =&gt; PromiseLike&lt;...&gt; cast and its comment appear three times (lines 45–49, 34–38, 29–33). - The error-mapping line if (error) throw toCreditReservationRejection(error) ?? error; and the catch that rethrows CreditReservationRejected or wraps the cause are repeated almost verbatim (lines 56 and 62–65; 46 and 55–58; 39 and 45–48). 3. Passing items. Each file exports one primary function, and its name matches the file name. validateCreditReservation.ts also exports a schema constant, which is secondary. Nesting stays at three levels or fewer. toCreditReservationRejection.ts is a single-function file with a matching name. Scope note on the byte-identical constraint: The PR description says the adapter, validator and test files are byte-identical to #1249. These files are new in this PR, so the diff is the code under review. The check has no exception for code that was reviewed in an earlier PR. The byte-identical rationale does not remove the findings.

Resolution

Refactor the three adapters so the check passes. Keep the public signatures and receipt variants unchanged. 1. Move the reservation-ID regex and the credits schema into one shared module, for example lib/credits/reservations/reservationSchemas.ts. Import them in each adapter. 2. Extract one typed RPC helper, for example callCreditReservationRpc(name, params), so the cast and bind appear once. 3. Extract the shared error-mapping step into one function, for example toReservationFailure(cause, ReconciliationError). 4. Move the receipt amount checks into named helpers, for example assertReservationReceiptAmount. After this, each adapter body should be 20 lines or fewer. If the PR must stay byte-identical to #1249, do not treat that as an exception. Instead, record the duplication and the length findings as a tracked follow-up with an owner. The check still applies to this diff.

  • 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.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T20:41:23.570838Z 4fda792 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 12 files

Architecture diagram
sequenceDiagram
    participant Caller as Trusted Server Caller
    participant Adapter as Reservation Adapter
    participant Validator as Zod Validator
    participant Supabase as Supabase RPC Client
    participant DB as Database (Postgres RPC)

    Note over Caller,DB: Opt-in credit reservation adapters (no production callers yet)

    Caller->>Adapter: reserveCreditsOnce(accountId, operationKey, creditsToReserve)
    Adapter->>Validator: validateCreditReservation()
    Validator-->>Adapter: Validated input
    
    Adapter->>Supabase: rpc("reserve_credits_once", params)
    Supabase->>DB: reserve_credits_once RPC
    
    alt Hold created
        DB-->>Supabase: { state: "held", reservationId, creditsHeld, spendableCredits }
        Supabase-->>Adapter: Receipt data
        Adapter->>Validator: Parse & validate receipt
        Validator-->>Adapter: Valid receipt
        Adapter-->>Caller: CreditReservationReceipt (held)
    else Duplicate delivery
        DB-->>Supabase: { state: "reused", status: "held"|"settled"|"released" }
        Supabase-->>Adapter: Receipt data
        Adapter-->>Caller: CreditReservationReceipt (reused)
    else Insufficient credits
        DB-->>Supabase: { state: "insufficient", creditsRequested, spendableCredits }
        Supabase-->>Adapter: Receipt data
        Adapter-->>Caller: CreditReservationReceipt (insufficient)
    else SQLSTATE 22023 rejection
        DB-->>Supabase: { code: "22023", message }
        Supabase-->>Adapter: Error object
        Adapter->>Adapter: toCreditReservationRejection(error)
        Adapter-->>Caller: throw CreditReservationRejected (definite, nothing written)
    else Transport/invalid receipt failure
        DB-->>Supabase: Other error, lost response, or invalid receipt
        Supabase-->>Adapter: Error/null data
        Adapter-->>Caller: throw CreditReservationNeedsReconciliation (retain same key)
    end

    Note over Caller,DB: After work completes - settlement
    Caller->>Adapter: settleCreditReservation(accountId, operationKey, creditsToDeduct, event)
    Adapter->>Validator: validateCreditCharge()
    Validator-->>Adapter: Validated input
    
    Adapter->>Supabase: rpc("settle_credit_reservation", params)
    Supabase->>DB: settle_credit_reservation RPC
    
    alt Settlement successful
        DB-->>Supabase: { state: "settled", eventId, creditsCharged, creditsReleased }
        Supabase-->>Adapter: Receipt data
        Adapter->>Validator: Parse & validate receipt & invariant check
        Adapter-->>Caller: CreditSettlementReceipt
    else Duplicate settlement
        DB-->>Supabase: { state: "reused", ... }
        Supabase-->>Adapter: Receipt data
        Adapter-->>Caller: CreditSettlementReceipt (reused)
    else SQLSTATE 22023 rejection
        DB-->>Supabase: { code: "22023", message }
        Supabase-->>Adapter: Error object
        Adapter->>Adapter: toCreditReservationRejection(error)
        Adapter-->>Caller: throw CreditReservationRejected (nothing written)
    else Uncertain outcome (may have committed)
        DB-->>Supabase: Other error/lost response/invalid receipt
        Supabase-->>Adapter: Error/null data
        Adapter-->>Caller: throw CreditChargeNeedsReconciliation (keep same key)
    end

    Note over Caller,DB: Cancellation - release hold without charge
    Caller->>Adapter: releaseCreditReservation(accountId, operationKey)
    Adapter->>Validator: validateCreditReservationRelease()
    Validator-->>Adapter: Validated input
    
    Adapter->>Supabase: rpc("release_credit_reservation", params)
    Supabase->>DB: release_credit_reservation RPC
    
    alt Release successful
        DB-->>Supabase: { state: "released", creditsHeld, creditsReleased }
        Supabase-->>Adapter: Receipt data
        Adapter->>Validator: Parse & validate receipt & equality check
        Adapter-->>Caller: CreditReleaseReceipt
    else SQLSTATE 22023 rejection
        DB-->>Supabase: { code: "22023", message }
        Supabase-->>Adapter: Error object
        Adapter->>Adapter: toCreditReservationRejection(error)
        Adapter-->>Caller: throw CreditReservationRejected
    else Uncertain outcome
        DB-->>Supabase: Other error/lost response/invalid receipt
        Supabase-->>Adapter: Error/null data
        Adapter-->>Caller: throw CreditReservationNeedsReconciliation
    end

    Note over Caller,DB: All adapters: no retry, no fresh key, no provider calls, no auto-top-up. Operation key stable across replays.
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread lib/credits/reservations/README.md Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Auto-approved: Adds opt-in credit reservation adapters, validators, error types, tests, and README as new inert modules; no existing production code or callers change, so the change is bounded and adds no runtime behavior until explicitly wired.

View guided diff | Turn on auto-fix | Re-trigger cubic

@sidneyswift
sidneyswift merged commit 5a4ce3b into main Nov 17, 2026
8 checks passed

This branch was successfully deployed

1 active deployment
Preview — c8828d93 Deployed Nov 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant