Repository navigation
fix(billing): unify sandbox payer on the SESSION; retire page-keyed payer helper - #2273
Conversation
…ayer helper
Runtime billing (withMachineBilling) resolved payerId from the caller's
SURFACE (ctx.tenantId/ctx.agentPageId, client-influenceable), while storage
billing already resolved it from the SESSION's own driveId/ownerId. One
sandbox, two different payers depending on charge type — invalidated by the
M5 fix, which made a session's drive able to differ from the surface's.
- Add SandboxRunDeps.resolveBillingSession: a cheap session-row read (no
provisioning) so withMachineBilling can resolve the payer from the
ACQUIRED SESSION before gating, preserving "credit-exhausted never wakes
the sandbox" without waiting on full acquire/provision.
- Change SandboxBillingDeps.resolvePayerId to {driveId, ownerId} (the
session's own facts) instead of {tenantId, agentPageId} (the surface's).
- Add resolveSessionPayerId (packages/lib/src/billing/sandbox-payer.ts):
drive owner else session owner, the same rule storageBillingTarget
applies for storage — now written once and shared by both charge streams.
- Delete resolveSandboxPayerId, lookupPageOwnerId, and the dead
resolveAgentSessionPayerId (page-keyed twin that was never the right
shape); fix the "resolves correctly BY CONSTRUCTION" comments this
invalidated in sandbox-billing.ts, sandbox-storage-attribution.ts,
sandbox-storage-reconcile.ts, and usage-breakdown-query.ts.
- Add no_session to AUTHZ_DENY_REASONS (tool-runners.ts) so the expected
"conversation predates sessions" refusal logs at warn, not error.
- Fix sandbox-storage-reconcile.ts's totals accounting: a chargeStorage
success followed by a throwing advanceAgentSessionWatermark now counts
toward `charged`/`totalCostDollars` (the money DID move) with a new
`chargedButUnadvanced` counter, instead of silently under-reporting it
as `failed`.
- First-class drive/session attribution on trackUsage/AIMonitoring
(Terminal Epic 3 usage-breakdown fix): added `sessionId` alongside the
existing `driveId` field on AIUsageData/writeAiUsage/ai_usage_logs.
sandbox-storage-billing.ts's chargeStorage now passes driveId/sessionId
top-level (previously JSON-forensics-only in metadata). The realtime
shell-handler's three trackUsage call sites now pass the session's real
driveId/agentSessionId instead of a permanently-undefined pageId.
NOTE for #2265: the new `sessionId` field on AIUsageData/writeAiUsage is
the seam to consume for realtime shell-usage attribution.
- Corrected stale conversation≡session comments (tool-runners.ts,
sandbox-tools-runtime.ts, shell-handler.ts's ShellSandboxResult) and
test-hygiene copy-paste leftovers (sandbox-storage-billing.test.ts's
schema-mock sentinel, sandbox-storage-reconcile.test.ts's page-keyed
prose).
Key acceptance test (tool-runners.test.ts): a session whose driveId
differs from the caller's surface drive bills the SESSION's payer for the
runtime stream — fails on master's withMachineBilling, passes after this
fix. Storage-stream coverage already existed in sandbox-storage-reconcile.test.ts.
Closes #2260
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ExHmbFs9zbegha2bQDuL2b
|
Warning Review limit reached
Next review available in: 23 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (21)
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. Comment |
Summary
Follow-up from the post-merge audit of #2258 (billing slice, issue #2260). One sandbox was billing through two different payer-resolution rules depending on charge type — runtime billing resolved from the caller's client-influenceable surface (
ctx.tenantId/ctx.agentPageId), storage billing already resolved from the session's owndriveId/ownerId. The M5 fix (session un-conflation) made those diverge for real: one session can host conversations from a different drive than the one it was spawned in.Unify payer resolution on the session (
withMachineBillingintool-runners.ts): added a cheapresolveBillingSessionseam (session-row read, no provisioning) so the payer resolves from the ACQUIRED session'sdriveId/ownerIdbefore gating — preserving the "credit-exhausted never wakes the sandbox" property.SandboxBillingDeps.resolvePayerIdnow takes{driveId, ownerId}instead of{tenantId, agentPageId}.One rule, written once: added
resolveSessionPayerId(packages/lib/src/billing/sandbox-payer.ts) — drive owner else session owner, the same rulestorageBillingTargetalready applied for storage. DeletedresolveSandboxPayerId,lookupPageOwnerId, and the deadresolveAgentSessionPayerId(the wrong-shaped page-keyed twin), and fixed the now-false "resolves correctly BY CONSTRUCTION" comments this invalidated acrosssandbox-billing.ts,sandbox-storage-attribution.ts,sandbox-storage-reconcile.ts, andusage-breakdown-query.ts.no_sessionadded toAUTHZ_DENY_REASONSso the expected "conversation predates sessions" refusal logs at warn, not error.Reconcile totals accounting fix: a
chargeStoragesuccess followed by a throwingadvanceAgentSessionWatermarknow counts towardcharged/totalCostDollars(the money DID move) with a newchargedButUnadvancedcounter, instead of silently under-reporting it asfailed.First-class drive/session attribution on
trackUsage(Terminal Epic 3 usage-breakdown fix): added asessionIdfield alongside the existingdriveIdonAIUsageData/writeAiUsage/ai_usage_logs.sandbox-storage-billing.ts'schargeStoragenow passesdriveId/sessionIdtop-level (previously JSON-forensics-only in metadata). The realtime shell-handler's threetrackUsagecall sites now pass the session's realdriveId/agentSessionIdinstead of a permanently-undefinedpageId.Note for fix(realtime): hoist cross-tier tenant/membership resolution into lib; dead-code sweep; retire machine vocabulary in live identifiers [MED] #2265: the new
sessionIdfield onAIUsageData/writeAiUsageis the seam to consume for realtime shell-usage attribution — it's self-contained inpackages/lib(schema column already existed, just unused).Corrected stale conversation≡session comments (
tool-runners.ts,sandbox-tools-runtime.ts,shell-handler.ts'sShellSandboxResult) and test-hygiene copy-paste leftovers.Key acceptance test (
tool-runners.test.ts): a session whosedriveIddiffers from the caller's surface drive bills the SESSION's payer for the runtime stream — fails on master'swithMachineBilling, passes after this fix. The storage stream already had equivalent coverage insandbox-storage-reconcile.test.ts.Test plan
bun run typecheck(root) — 16/16 tasks passbun run lint(root) — 14/14 tasks passcd packages/lib && bun run typecheck— cleanbun run knip:check— 4 issues, all within baseline (no new dead exports)bun run test:unit— lib: 8632 passed / 11 skipped, 0 failed. web: 15057 passed, 1 failed (grouping.test.tsmidnight/TZ test — pre-existing, documented env-only flake, unrelated file untouched by this diff)bun run test:security— 44/50 suites pass; the 6 failures (Session Service, Device Auth Utilities, Permissions, Login Route, Signup Route, Mobile Login) are pre-existing stale suites unrelated to this change (deleted routes / excluded configs)packages/lib/src/billing/__tests__/sandbox-payer.test.ts,packages/lib/src/services/sandbox/__tests__/{tool-runners,sandbox-billing,sandbox-storage-billing,sandbox-storage-reconcile}.test.ts,apps/web/src/lib/ai/tools/__tests__/sandbox-tools-runtime.test.ts,apps/realtime/src/terminal/__tests__/shell-handler.test.ts,apps/web/src/app/api/cron/reconcile-machine-storage/__tests__/route.test.tsCloses #2260
🤖 Generated with Claude Code
https://claude.ai/code/session_01ExHmbFs9zbegha2bQDuL2b