Skip to content

feat(runtime): bound company load and database waits - #421

Merged
allisonmahmood merged 2 commits into
mainfrom
tier2/390-admission
Oct 1, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
tier2/390-admission

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Runtime requests need company-wide admission even when they do not use SQL, and saturated company pools need a bounded wait rather than immediate rejection.

Add a per-company token bucket at 100 calls/second with a burst of 200. Company pools default to four connections with up to 32 waiters for at most one second within the caller deadline. Effective overrides, retained-backend budgeting, structured refusals, and wait metrics keep those bounds explicit.

Inventory initialization now applies idempotent upgrades. Neon provisioning uses template0 to avoid the observed template1 scheduler conflict. Updated the API, operating-limit documentation, and generated server skill.

Stacked on tier2/389-tier2-contract; this PR targets that branch and contains only the issue #390 changes. Implements the admission requirements from #384.

Closes #390.

Verification

  • pnpm typecheck and pnpm lint passed.
  • pnpm test --maxWorkers=4: 95 files and 1,067 tests passed.
  • After the final capacity-edge fixes, typecheck, lint, and 28 focused tests passed.
  • Disposable Neon smoke verified restricted-role provisioning, repeat inventory upgrades, bounded waiting, protocol cancellation in 251 ms, idle-connection replacement, and owner-role deletion. Temporary resources were removed.
  • Standards and spec reviews have no outstanding findings.

Implemented with openai-codex/gpt-6-astra in the omp harness.

@github-actions github-actions Bot added area:server Touches the server area area:docs Touches the docs area area:primitives Patch tables and files area:integrations Company connections and integration implementations size:xl Over 1,000 changed lines; review in multiple passes labels Sep 28, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 6a632234cf207128478afe43f90ed765ff37fb32 against origin/tier2/389-tier2-contract at 22df82f4af6fc9368026a6761e237c870659470d, using the three-dot diff. Spec: #390 and the relevant sections of #384. One pass, no subagents; merge blockers only.

Standards

No blocking method or YAGNI findings. The pool drain-and-replace logic supports the requested live per-company overrides without overlapping retained backend budgets. The token bucket and inventory upgrade hook are explicitly requested by #390.

Spec

No blocking intent findings. The change covers the bounded connection queue, structured refusals, per-company pool overrides, company admission for operations without a database connection, and repeatable inventory upgrades. The API documentation, ADR-0009, development notes, glossary, and generated limits tables reflect those changes. Tier 2 execution remains assigned to later tickets, not missing work for this PR.

Verification:

  • Six focused suites passed, 43 tests covering company pools, PostgreSQL/PGlite inventory, token buckets, operating configuration and overrides, and Runtime admission.
  • A standalone smoke run against disposable local PostgreSQL held all four connections. Another acquisition returned HTTP 503 after 1,003 ms with company.connections.wait, scope company, value 1000, and Retry-After: 1. Releasing one holder let a queued query complete against the correct company database.
  • I did not rerun Neon acceptance. The PR description reports that run; the local checks do not independently establish Neon behavior.

Standards: 0 blocking findings, worst issue none. Spec: 0 blocking findings, worst issue none.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Reviewed origin/tier2/389-tier2-contract...HEAD against #390 and spec #384 §5/§14 (plus the r304 admission table). The focused suites pass locally (CompanyDatabases.test.ts, RuntimeAdmission.test.ts, TokenBucket.test.ts, 28 tests). Findings, most severe first:

1. Anonymous public traffic spends the company's admission bucket (correctness). packages/runtime/src/Runtime.ts:510
admitCompany(version.companyId) runs for public-scope versions too. The broker always sends me first, "including for anonymous public shells" (packages/serving/src/broker.ts:420). Each anonymous page load of a public tier 1 patch therefore takes one company token, and the only per-caller bound is 300/min per remote address per patch. About 20 addresses loading a public page (or one popular link) drain the 200-call burst, and every internal tool in that company then gets limit_exceeded. People outside the company can take down its tools. Public me touches no company resource, so skip company admission when version.scope === "public". If counting public load is intended, that is a product decision to state in the ADR and the API docs, and it still needs its own bucket so outsiders cannot starve insiders.

2. An override swap stalls the whole company until every old lease ends (correctness/method). packages/company-database/src/PgCompanyDatabases.ts:405
When company.connections changes, tryAcquire refuses every new lease while active > 0 on the old generation. Reads have no Runtime deadline (Runtime.ts: if (operation.kind === "read") return yield* execute), so one slow read holds the old pool for up to the company database's 30 s statement_timeout. Mutations hold it for up to their deadline. During that time every new operation waits its 1 s and gets busy. Operators raise the pool when a company is saturated, which is exactly when leases are in flight, so the fix itself causes a company-wide busy window. This drain rule is also what requires the hand-rolled state machine (current/target/opening/failed/invalidated/active/waiters/changed, BigInt revision ordering, samePool, about 200 lines at 311-519). The previous shape was simpler. Put connections.value into the PoolKey beside placementVersion, and let the old generation drain while its reservation stays counted in the backend budget, as placement changes already do. The bounded wait then becomes a waiter counter plus semaphore.take(1) under Effect.timeoutOrElse.

3. Four sequential platform round trips per company operation, ahead of the bounded wait and not bounded by it (method/perf). PgCompanyDatabases.ts:539, packages/runtime/src/RuntimeProduction.ts:55-61
withCompany now does the placement read plus three separate OperatingLimits.get queries. Effect.all over an array runs them sequentially, and each query joins companies/limits_revisions/limits_overrides. They run on the host-wide 2-connection PlacementClient pool (:135), and that pool has no acquire timeout. Runtime admission adds two more sequential reads on the main pool. So a tier 1 table op costs 6 platform round trips where it used to cost 1. On Neon latency, the 2-slot placement pool becomes the host's throughput ceiling for all company operations, and waits there sit outside company.connections.wait. That breaks the "at most 1 s, then busy" promise under load. Read the needed limits in one statement (a getMany/struct read on OperatingLimits), and use Effect.all({ connections, waiters, wait }) so the result is typed instead of destructured with connections!/waiters!/wait!.

4. Docs carry a work record and a misleading role name (convention). docs/DEVELOPMENT.md:874-878, docs/adr/ADR-0009-one-postgres-database-per-company.md:16
The "Issue #390 acceptance ran against the designated Neon spike project..." paragraph is a verification record. CLAUDE.md puts that in the PR ("A merged PR is the implementation record"), not in durable docs. ADR-0009 also prints GRANT company_x TO patchy_admin, which suggests per-company roles, while the design has one operator-provisioned data role. Name it as the data role (the PATCHY_COMPANY_DB_URL login), as DEVELOPMENT.md already half-does.

Checked with no findings: the token bucket (burst/refill, override changes, clock skew, fail-closed capacity), the queue bound (32 waiters then busy, 1 s expiry, interrupted waiters release their slot), backend-budget reservation across resizes, Busy wire fields through TableBusy/FileBusy/RuntimeApi.failure, the registry limit_exceeded change and the regenerated limits tables, the template0 change, the protocol CancelRequest claim (verified in the pinned @effect/sql-pg rc.117), and the inventory reinit test.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Reviewed 6a63223 against tier2/389-tier2-contract at 22df82f4. The spec is issue #384, sections 2, 3, 5, 14 and 16. The ticket is #390.

The structure matches the ticket. Runtime spends one token bucket per incoming operation. The company pool queues acquisitions. Inventory upgrades are idempotent. Neon role grants stay an operator step, and cancellation stays in the Effect driver. The problems are places where a bound the code claims is not the bound it holds.

Standards

Hard.

The frame drops retryAfter on limit_exceeded. RuntimeApi.failure sends it, and docs/API.md promises it. packages/serving/src/broker.ts around lines 371-376 keeps retryAfter only for rate_limited, too_many_requests and busy. The generated broker script has the same filter. limitRefusal in packages/api/src/limits.ts lines 29-34 uses that same allow-list, so the helper would strip the field too. CLAUDE.md, Hit every surface: the api package is the wire source and the shell broker has to mirror it. A company that hits the admission rate gets a 429 the page cannot back off from.

The project skills that tell an agent how to handle a refusal were not updated with the table. packages/sdk/skills/patchy-loop/SKILL.md line 113 still says to respect too_large, rate_limited, too_many_requests and busy. packages/sdk/skills/patchy-server/SKILL.md lines 69-70 still says busy means admission. The generated limits table in that skill is right. The handling paragraph is not.

ADR-0009 says a queued acquisition waits at most 1 second and still inside the caller deadline. tryAcquire is Effect.uninterruptible and calls pool() with a 5 second connect timeout, and the first attempt sits outside timeoutOrElse. A parent deadline cannot cancel that connect. docs/agents/domain.md: an ADR the change contradicts has to be updated, or the code has to match it.

Judgement.

Files.ts and TableOperations.ts each copy every Busy field into a local error. A shared translation would be shorter. Not a behavior bug.

InvalidOverride's message says a positive finite value and an actor. LimitSetting also rejects a fractional connection, waiter or burst count. A value of 4.5 fails the integer check and is reported as the finite-value error. Effect service conventions want message to come from the fields that actually failed.

Spec

Partial.

Issue #384 section 2 replaces fail-at-once with a bounded wait: at most 32 waiters, at most 1 second inside the call's deadline, then busy with retryAfter. Overflow and the 1 second timer do return busy with scope, limit id, value and retryAfter. A shorter caller deadline does not. The wait timer is always company.connections.wait. The new test treats an outer Effect.timeout as a caller deadline and expects TimeoutError, not busy. Tier 1 reads have no outer deadline at all. Tier 1 mutations time out as timeout for runtime.mutation.deadline, which is 30 seconds, so the 1 second queue bound wins unless the call is already near that deadline.

Not asked for.

PgCompanyDatabases.ts lines 495-502 writes the queue delay into queueWaitMs, connectionWaitMs and a company.connections.wait peak. Issue #390 asks for the queue wait on the request event, and that field already existed. Connection-hold time is a different metric in the limits decision. A waiter who never got a connection is recorded as if they held one.

Wrong.

Cold open can lend one connection past the pool size. open sets opening false and completes the waiter deferred in ensuring, before tryAcquire increments active. Deferred.doneUnsafe runs each waiter inside that call, and Effect resumes those fibers synchronously. Each waiter takes a slot, up to the maximum, and then the opener takes one more. The extra lease blocks inside the driver pool, which has no 1 second cap. The 33-waiter test does not see this. It holds four connections before anyone queues, so open has already finished.

A resize that does not fit PATCHY_COMPANY_DB_MAX_BACKENDS closes the live pool before the budget check. open drops current and closes its scope, then fails the reservation. The company stays busy until the override shrinks. ADR-0009 says that variable budgets retained maxima. It should not spend the working pool to discover the new size does not fit.

A burst refusal is named company.admission.rate with value equal to the rate. The 201st call exhausted company.admission.burst. Section 14 says a refusal carries the limit id and the value. Both registry rows use limit_exceeded. The wide-event peak on that path is burst + 1, because a refusal has remaining === 0 and the formula adds one.

Issue #390

Met. The queue cap, the 1 second busy refusal, the token bucket beside the fixed window, the 201st burst call, idempotent ref_table on an already-initialized database, and the docs the ticket names. Queue wait is written onto the current request event. Runtime calls already run inside that event.

Partial, and the partial matches "admitted at merge". Tier 2 has no caller yet. server.call and tier 1 operations share admitCompany when production runtime is wired. RuntimeDev does not pass it. Operating limits are deployment config, and dev already says it does not reproduce connection contention. Neon GRANT ... WITH SET and DROP DATABASE under SET ROLE are the operator procedure in ADR-0009, with a local restricted-role test. Product code creates databases with TEMPLATE template0. Protocol CancelRequest and dead-session replacement are @effect/sql-pg, which is the right place. There is no in-repo spike test. The PR body is the only record of the Neon smoke.

The override test raises one company from 4 to 6. It does not assert the other company is still capped at 4. The lookup is per company, so the behavior is there.

Method

Per-company active and waiters counters plus a generation deferred are enough. A semaphore does not cover a waiter cap, a host backend budget and drain-before-resize together. The token bucket is a closure in packages/limits, not a service, and only production runtime holds it. After the clock read, consume does not yield, so two fibers cannot spend the last token. Refill is capped at burst.

Fix the notify order. Increment active for the opener before waking waiters, or wake them after that increment. Today the saturated path is fine and the cold path is not.

Check the host budget, including the reservation you are about to release, before closing the live pool.

Keep the counter updates uninterruptible. Do not hold the fiber uninterruptible across pool().

Every admitCompany reads rate and burst as two platform queries, and every lease reads three more for connections, waiters and wait. Overrides stay correct. A 200-call burst spends about 400 platform reads before the bucket refuses, and the pair can tear across two snapshots. I would not add a cache in this change. If this stays, one statement for the pair removes the tear.

ensureReady on an already-ready database opens a one-connection pool for Inventory.upgrade that reservedBackends does not count.

YAGNI

Delete the connectionWaitMs write and the burst-peak enrich in RuntimeProduction.ts lines 66-75. Neither number is the thing it is named. queueWaitMs is the measurement #390 asked for.

Leave Inventory.upgrade as one catalog probe. A version ledger is the deferral ADR-0009 already names.

Leave cancellation and idle-client disposal in the driver. retireFailed only drops a failed open. A second pool here would duplicate @effect/sql-pg.

The monotonic clock and the full-map eviction in TokenBucket.ts repeat Limits.ts. The bucket math is different and should stay. The capacity refusal could be one helper later. Not this PR's bug.

company.connections.pools marked configuration: "legacy" exists so the override controller rejects the id. Nothing older reads that flag.

Summary

Standards: 3 hard, 2 judgement. Worst: the shell drops retryAfter on limit_exceeded.
Spec: 1 partial, 1 extra field, 3 wrong. Worst: a cold open lends one connection past the pool cap, outside the 1 second wait.

@github-actions github-actions Bot added the area:ci CI, shared testing infrastructure, development scripts and tooling label Sep 28, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Reviewed Astra, Opus, and Grok Build's conversation comments, plus both GitHub review-body and inline-comment endpoints. The latter two were empty. Astra reported no blockers.

Fixed

  • Opus 1, public traffic spending company tokens: public me now uses only its per-caller limiter. Anonymous public requests cannot exhaust the company's internal-tool allowance. Public data/server operations remain refused, and public callers retain their existing rate bound.
  • Opus 3 and Grok's snapshot concern: added typed OperatingLimits.getMany. Runtime reads rate/burst in one statement; company pooling reads connections/waiters/wait in one statement. Each related set sees one override revision, without a cache. This reduces a normal company database operation's placement/configuration work from six platform statements to three.
  • Grok, cold-open oversubscription: register the opener's lease before notifying waiters. A standalone PostgreSQL reproduction admitted five callers through a four-slot pool before the fix and four afterward. Added the cold-concurrency regression.
  • Grok, refused resize destroys a working pool: check and reserve the replacement budget before closing the previous pool, discounting its existing reservation. A budget refusal leaves the backend and its reservation intact. The smoke and regression verify that removing the oversized override reuses the same backend PID.
  • Grok, lost retry timing: both the API helper and actual shell broker retain retryAfter for limit_exceeded. Timeout and unknown-outcome failures still strip it; mutations are not automatically replayed. Added API and browser regressions.
  • Grok, burst peak: refused calls no longer add an imaginary token to the usage peak. Host tracked-key refusals no longer report fictitious company consumption.
  • Grok, override diagnostic: integer settings now report the positive-safe-integer requirement rather than claiming a fractional value failed the finite-number check.
  • Opus 4 and Grok, documentation/skills: removed the Neon execution record from DEVELOPMENT, named the shared data-role login explicitly, and corrected both project skills' limit_exceeded versus busy retry guidance. Updated the API, ADR, glossary, and generated limit references for public-call isolation.

Kept as is

  • Opus 2, drain-before-resize: this prevents overlapping pool generations and preserves the retained-maxima budget. A requested increase can cause busy refusals until old leases finish; that tradeoff is now explicit in ADR-0009. Overlapping generations would need spare host capacity and would not remove the full-budget case.
  • Grok, alleged five-second uninterruptible connect: the native driver's zero-minimum pool is lazy. Constructing it against closed localhost port 1 completed in 1 ms with a five-second connect timeout configured. Socket checkout happens during subsequent SQL work, not inside the slot counter update. Kept the counter updates uninterruptible.
  • Opus 3/Grok, scope of the one-second bound: it bounds contention for occupied company slots, not placement lookup, network connection establishment, or SQL execution. Related lookup queries are now batched, but this change does not introduce a second platform-pool timeout.
  • Grok, shorter caller deadline: cancellation/deadline ends the wait earlier and retains the caller-owned timeout/interruption outcome. It should not be relabeled as a retryable busy. Existing cancellation/deadline regression retained; ADR wording clarified.
  • Grok, connectionWaitMs: it measures connection-slot waiting, including an unsuccessful wait. It is not the separate connection-held db ms metering described in spec section 14. Kept it alongside queueWaitMs.
  • Grok, rate versus burst refusal ID: one token bucket enforces the company admission rate with burst capacity. company.admission.rate identifies that policy and reports its effective refill rate; there are not separate burst/refill refusal paths. The 201st burst call still returns limit_exceeded, as feat(runtime): admission: the bounded connection wait, the company admission rate, pool overrides and the Neon provisioning amendments #390 requires.
  • Grok, Busy field copies: kept explicit translation at the TableBusy/FileBusy typed error boundaries, preserving the original cause. A constructor-only shared wrapper would add abstraction without fixing behavior.
  • Grok, override-isolation coverage: the existing test already holds four leases for the other company, proves its extra callers remain queued/refused, then releases exactly one holder and observes one success. No duplicate test added.
  • Grok, ready-inventory provisioning connection: this is temporary provisioning work, not a retained company pool. ADR-0009 already requires separate provisioning/admin/platform headroom. Kept the catalog-based idempotent upgrade and driver-owned cancellation/idle disposal.

Local verification

  • Full workspace typecheck and lint passed. After correcting the new regression's test-clock synchronization, the affected package typecheck and lint passed again.
  • Four focused suites passed, 46 tests covering company pools, effective limits, Runtime admission, and API schemas.
  • Chromium broker regression passed: admission retry timing survives the frame boundary, unsafe outcomes lose retry timing, and mutations are not replayed.
  • An isolated local server accepted 20 anonymous public calls without spending a two-token company allowance. Authenticated company calls remained available afterward. With the company allowance then exhausted, the real sandboxed client received limit_exceeded, scope company, company.admission.rate, value 0.001, and retryAfter: 907 from the server through the broker. The deliberately slow test refill rate made the delay observable.
  • The public page still loaded anonymously after company exhaustion and refused a data write with not_available_on_public. Temporary servers, databases, and smoke scripts were removed.
  • Full offline suite after the fixes: pnpm test --maxWorkers=4, 95 files and 1,075 tests passed.

Latest commit and merge readiness

Committed and pushed as 0c8c56716c8ab3511a61c4d4afddc2faf55b76ef.
CI run 36411224657
completed successfully for that exact commit. All eight PR checks passed:
test (22), test (24), postgres-concurrency, clerk-live, lint,
cli-smoke, dependency-review, and label.

GitHub reports MERGEABLE / CLEAN against tier2/389-tier2-contract.
This stacked target has no separately designated required checks; every check
that ran is green. Rechecked conversation comments, review bodies, and inline
comments after CI completed: no new findings. No unresolved merge blockers.

@allisonmahmood
allisonmahmood force-pushed the tier2/389-tier2-contract branch from 22df82f to 1f08b25 Compare October 1, 2026 00:36
Base automatically changed from tier2/389-tier2-contract to main October 1, 2026 00:48
Implement #390 against the tier-2 admission spec in #384. Bound company pool queues and retained backends, enforce company token buckets, and upgrade inventory idempotently. Verify restricted-role Neon lifecycle and use template0 for provisioning.
Isolate public calls from company tokens, batch effective limit reads, preserve retry timing through the broker, and fix cold-open and refused-resize pool races. Add focused coverage and clarify the reviewed admission contracts.
@allisonmahmood
allisonmahmood merged commit 1d3f9e6 into main Oct 1, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/390-admission branch October 1, 2026 01:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area area:integrations Company connections and integration implementations area:primitives Patch tables and files area:server Touches the server area size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(runtime): admission: the bounded connection wait, the company admission rate, pool overrides and the Neon provisioning amendments

1 participant