Skip to content

fix(gateway): restore spend limits with incremental member accounting - #5133

Merged
benjaminshafii merged 1 commit into
devfrom
gateway-incremental-usage
Sep 18, 2026
Merged

benjaminshafii merged 1 commit into
devfrom
gateway-incremental-usage

Conversation

@OmarMcAdam

@OmarMcAdam OmarMcAdam commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

Database-first dependency

Merge #5135 and confirm its migration workflow succeeds before rebasing or merging this implementation. Auto-merge is paused until that sequence is complete.

Purpose

Replacement for #5056, which was merged and then reverted by #5124 after the usage path caused database lock contention. This restores the requested spend-policy UI and APIs, but replaces the accounting design rather than reinstating the organization-wide mutex.

Ready for human review; auto-merge requested by the author. Verification remains incomplete. Do not activate in production solely because the original tables already exist.

Request-path changes

  • Admission and usage/status queries are indexed, nonlocking reads. They do not initialize history, reconcile charges, or SUM request history.
  • No organization-row or global rollup lock in quota admission, status, or settlement.
  • The existing canonical usage logger carries the server-owned admission timestamp and window attribution. Finalized cost is reused, not priced a second time.
  • Consumption receipts and atomic additive member-period counters are persisted in short ACID transactions. Duplicate finalization is idempotent; late known-cost promotion uses the receipt delta.
  • Unrestricted responses maintain the same small period counters, so a later policy assignment includes already-tracked same-period spend. This does not impose a limit on unassigned members.
  • Member-scoped lifecycle fences prevent erasure resurrection without creating an organization-wide request barrier. Ordinary offboarding locks only its target rather than every active member.
  • Starts have bounded per-member/global queues, cancellation, and enqueue deadlines. Admitted work reserves settlement capacity; start overload does not discard its costs. A separate writer pool prevents one member's blocked writes exhausting the read pool.
  • Pending identity and attribution survive raw-log retention. Bounded operator recovery records abandoned work as unknown/incomplete, never silently free.
  • Historical uncertainty and pending settlement are distinct in the UI, avoiding endless retries for history that a short refresh cannot repair.

The agreed semantics remain settled-estimate enforcement, not pre-dispatch reservations: already-admitted work may overshoot an allowance.

Preserved functionality

Policy day/week/month limits in integer micro-USD; per-person direct/team assignments; highest allowance per timeframe; 05:00 UTC calendar boundaries; hard/soft limits; one reviewed 25% increase per bucket; Den management and request review; Desktop usage controls, direct increase requests, pending/approved indications. Legacy OpenWork Models allowances remain separate.

Migration and rollout requirements

  1. Restored 0102–0104 SQL, snapshots, and journal identities remain byte-identical to the original merge 9b0adb849. Restoring files is not evidence that a particular database has matching receipts or complete physical schema.
  2. New forward migrations 0105–0107 are required. They add lookup indexes, small coverage/lifecycle counters, durable request attribution, and capture-version state. Existing spend, extensions, and event/charge identities are preserved.
  3. Verify migration receipts/schema. Do not re-stamp a partially applied database or rerun CREATE statements blindly.
  4. Stop/drain legacy writers and retention workers before cutover. Existing tracking rows are capture-disabled by 0107; use the reviewed suspend/resume procedure where applicable. New writers must not run concurrently with binaries that ignore the capture protocol.
  5. Review the added read/write connection-pool budget before deployment.
  6. Recover/reconcile only explicit bounded identities outside the hot path. Ambiguous aggregate-backed history is refused rather than guessed or double-charged.

Operator CLI and procedure: ee/packages/den-db/scripts/gateway-usage-operations.md. Preview is the default; apply requires explicit reviewed input. No production database was queried or migrated during development.

Most of this PR's line count is generated migration snapshots and restoration of files deleted by #5124.

Verification on aa8223d

312 focused tests passed, zero skips: 195 backend tests and 117 UI tests. Scoped/app typechecks, generated SDK consistency, and API lint passed (0 errors, 39 warnings).

Real MySQL 8.4.10 tests cover:

  • Held organization/global rollup locks do not block usage operations.
  • Different members remain independent during settlement and actual offboarding.
  • Duplicate/additive settlement, all three windows, actual admission boundaries, unknown-to-known promotion, existing legacy counters, and increase/auth races.
  • Permanent erasure, crashed starts, real raw compaction, idempotent abandoned recovery and late cost promotion.
  • Bounded queued starts, cancellation without DB writes, enqueue deadline, fairness, and reserved settlement capacity under overload.
  • Fresh migrations and upgrade from the already-migrated schema.

Final-head latency measurements

10,000 historical raw rows; eight members; 24 concurrent operations; read/write pools limited to 10. Values are p50 / p95 / p99 milliseconds. These are local measurements, not PlanetScale certification.

Operation Loopback +2 ms per TCP direction SQL statements including transaction boundaries
Admission 14.89 / 23.40 / 35.33 68.04 / 130.66 / 132.50 7
Status 19.09 / 31.08 / 38.12 93.46 / 158.20 / 181.86 10
Settlement 30.69 / 44.77 / 45.63 205.62 / 225.59 / 227.04 25

Actual offboarding remained 49 SQL statements with either 0 or 200 unrelated members. Overload tests separately verified queue bounds, cancellation, deadline and unrelated-member progress.

End-to-end gap — do not treat as passed

Both commands were run on this exact committed head, with placement local (--local):

pnpm evals:e2e gateway-usage-policy --local
pnpm evals:e2e gateway-usage-policy --local --engine v2

Each exited 1 with one failed test, zero passes/skips. Legacy stopped during local Chrome navigation; v2 completed policy creation/assignment but session creation did not return a session ID. Neither final-head run reached the required pre/post-increase composer flow. Earlier intermediate-tree successes are not substituted for current-head evidence.

Local diagnostic records:

  • evals/results/.testkit/cli-run-1789689161789.json
  • evals/results/.testkit/cli-run-1789689364246.json

Complete Desktop E2E, clean visual evidence, and controlled deployment validation remain required before production activation. Auto-merge is paused for the migration-first sequence. Production activation still requires the documented migration/cutover procedure and complete verification.

@mintlify

mintlify Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
differentai 🟢 Ready View Preview Sep 18, 2026, 12:04 AM

💡 Tip: Enable Automations to automatically generate PRs for you.

@vercel

vercel Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Deployment Actions Updated
openwork-app Ready Ready Preview Sep 18, 2026 12:04am UTC
openwork-den Ready Ready Preview Sep 18, 2026 12:04am UTC
openwork-diagnostics Ready Ready Preview Sep 18, 2026 12:04am UTC
openwork-landing Ready Ready Preview, v0 Sep 18, 2026 12:04am UTC

@OmarMcAdam

Copy link
Copy Markdown
Member Author

Verification status: Incomplete

Head: aa8223dbbac73765f79a1346e3c88f28daf29e9c.

  • 195 focused backend tests and 117 UI tests passed on this head, with zero skips; scoped typechecks, SDK consistency and API lint passed.
  • The real-MySQL suite tests 10,000-row history, concurrent members, held organization/rollup/bucket locks, actual offboarding, duplicate settlements, erasure, durable abandoned-request recovery, queue bounds and cancellation. Measured latency and migration compatibility are recorded in the PR body.
  • pnpm evals:e2e gateway-usage-policy --local: exit 1, 0 passed / 1 failed / 0 skipped; local Chrome navigation failed before the user journey. Local record: evals/results/.testkit/cli-run-1789689161789.json.
  • pnpm evals:e2e gateway-usage-policy --local --engine v2: exit 1, 0 passed / 1 failed / 0 skipped; Den policy creation/assignment passed, but Desktop session creation did not return a session ID. Local record: evals/results/.testkit/cli-run-1789689364246.json.

Both use placement: local (--local). The stronger post-approval native-composer assertion remains in the spec and has not passed on this final head. Earlier intermediate-tree successes are not current-head proof. Full visual and end-to-end evidence remain outstanding; no release-readiness claim is made.

@OmarMcAdam

Copy link
Copy Markdown
Member Author

Database changes have been split into #5135. It contains only SQL/Drizzle metadata, matching schema declarations, and the migration-validation support required for a consistent database package. Auto-merge here is paused. Please merge #5135 first and confirm Den DB Migrate succeeds; this implementation can then be rebased onto the updated dev branch. No implementation history was rewritten or force-pushed as part of the split.

@benjaminshafii
benjaminshafii enabled auto-merge (squash) September 18, 2026 00:33
@benjaminshafii
benjaminshafii merged commit 27c7527 into dev Sep 18, 2026
13 checks passed

This branch was successfully deployed

5 active deployments
Preview – openwork-landing — aa8223db Deployed Sep 18, 2026 by vercel[bot]
Preview – openwork-den — aa8223db Deployed Sep 18, 2026 by vercel[bot]
Preview – openwork-app — aa8223db Deployed Sep 18, 2026 by vercel[bot]
staging - packages/docs — aa8223db Deployed Sep 18, 2026 by mintlify[bot]
Preview – openwork-diagnostics — aa8223db Deployed Sep 18, 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.

2 participants