Skip to content

fix(billing): unify sandbox payer on the SESSION; retire page-keyed payer helper - #2273

Merged
2witstudios merged 1 commit into
masterfrom
pu/audit-billing-payer
Jul 30, 2026
Merged

2witstudios merged 1 commit into
masterfrom
pu/audit-billing-payer

Conversation

@2witstudios

Copy link
Copy Markdown
Owner

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 own driveId/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 (withMachineBilling in tool-runners.ts): added a cheap resolveBillingSession seam (session-row read, no provisioning) so the payer resolves from the ACQUIRED session's driveId/ownerId before gating — preserving the "credit-exhausted never wakes the sandbox" property. SandboxBillingDeps.resolvePayerId now 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 rule storageBillingTarget already applied for storage. Deleted resolveSandboxPayerId, lookupPageOwnerId, and the dead resolveAgentSessionPayerId (the wrong-shaped page-keyed twin), and fixed the now-false "resolves correctly BY CONSTRUCTION" comments this invalidated across sandbox-billing.ts, sandbox-storage-attribution.ts, sandbox-storage-reconcile.ts, and usage-breakdown-query.ts.

  • no_session added to AUTHZ_DENY_REASONS so the expected "conversation predates sessions" refusal logs at warn, not error.

  • Reconcile totals accounting fix: 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 (Terminal Epic 3 usage-breakdown fix): added a sessionId field alongside the existing driveId 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 fix(realtime): hoist cross-tier tenant/membership resolution into lib; dead-code sweep; retire machine vocabulary in live identifiers [MED] #2265: the new sessionId field on AIUsageData/writeAiUsage is the seam to consume for realtime shell-usage attribution — it's self-contained in packages/lib (schema column already existed, just unused).

  • Corrected stale conversation≡session comments (tool-runners.ts, sandbox-tools-runtime.ts, shell-handler.ts's ShellSandboxResult) and test-hygiene copy-paste leftovers.

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. The storage stream already had equivalent coverage in sandbox-storage-reconcile.test.ts.

Test plan

  • bun run typecheck (root) — 16/16 tasks pass
  • bun run lint (root) — 14/14 tasks pass
  • cd packages/lib && bun run typecheck — clean
  • bun 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.ts midnight/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)
  • New/updated tests: 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.ts

Closes #2260

🤖 Generated with Claude Code

https://claude.ai/code/session_01ExHmbFs9zbegha2bQDuL2b

…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
@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@2witstudios, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 23 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 6df0a566-3742-46a7-a1a6-e7b676f4498c

📥 Commits

Reviewing files that changed from the base of the PR and between 4720452 and 3abaf6b.

📒 Files selected for processing (21)
  • apps/realtime/src/terminal/__tests__/shell-handler.test.ts
  • apps/realtime/src/terminal/shell-handler.ts
  • apps/realtime/src/terminal/terminal-session-map.ts
  • apps/web/src/app/api/cron/reconcile-machine-storage/__tests__/route.test.ts
  • apps/web/src/app/api/cron/reconcile-machine-storage/route.ts
  • apps/web/src/lib/ai/tools/__tests__/sandbox-tools-runtime.test.ts
  • apps/web/src/lib/ai/tools/sandbox-tools-runtime.ts
  • apps/web/src/lib/subscription/usage-breakdown-query.ts
  • packages/lib/src/billing/__tests__/sandbox-payer.test.ts
  • packages/lib/src/billing/sandbox-payer.ts
  • packages/lib/src/logging/logger-database.ts
  • packages/lib/src/monitoring/ai-monitoring.ts
  • packages/lib/src/services/sandbox/__tests__/sandbox-billing.test.ts
  • packages/lib/src/services/sandbox/__tests__/sandbox-storage-billing.test.ts
  • packages/lib/src/services/sandbox/__tests__/sandbox-storage-reconcile.test.ts
  • packages/lib/src/services/sandbox/__tests__/tool-runners.test.ts
  • packages/lib/src/services/sandbox/sandbox-billing.ts
  • packages/lib/src/services/sandbox/sandbox-storage-attribution.ts
  • packages/lib/src/services/sandbox/sandbox-storage-billing.ts
  • packages/lib/src/services/sandbox/sandbox-storage-reconcile.ts
  • packages/lib/src/services/sandbox/tool-runners.ts

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

Comment @coderabbitai help to get the list of available commands.

@2witstudios
2witstudios merged commit bd70ad2 into master Jul 30, 2026
1 check passed
@2witstudios
2witstudios deleted the pu/audit-billing-payer branch July 30, 2026 08:47
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.

fix(billing): unify sandbox payer on the SESSION; retire page-keyed payer helper; first-class storage attribution [HIGH]

1 participant