Skip to content

fix(company-database): count open company connections, not pool maxima - #993

Merged
allisonmahmood merged 1 commit into
mainfrom
t3/dynamic-company-backend-budget
Oct 29, 2026
Merged

allisonmahmood merged 1 commit into
mainfrom
t3/dynamic-company-backend-budget

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 28, 2026 •

Copy link
Copy Markdown
Owner

What changed

A host's company database budget (PATCHY_COMPANY_DB_MAX_BACKENDS, 64 per host in production) was spent on reservations: each company pool held its full maximum of four from the moment it opened, so the 17th company active within a minute got busy, even though most pools held one connection or none. The budget now counts the company connections a host actually has open, working or idle. A company still grows to its own maximum when the budget allows. When the budget is full, a lease closes another company's longest-idle connection; only when every connection is working does it queue, within the existing bounds, and then return the same busy.

Look at

Each lease now holds exactly one connection. This is a behaviour change. A company pool is now a set of one-connection slots, one per lease (withCompany admission or tier 2 lease), and each slot holds one host backend while it is open. Before, statements inside one admission could spread over several of the company's connections at once. Now they share the lease's session. No caller runs SQL concurrently inside one admission today; tier 2 already held one connection per lease. A lease's authority read is its own admission, so it still gets its own connection.

How many companies one host serves, budget 64. This drives the real PgCompanyDatabases layer against the local dev instance's Postgres, with the same script and data on the base and the head. The numbers are counts, not timings, so one run each:

base (2f9f7c1) head
80 companies, each holding one connection at the same moment 16 served, 64 busy hostBackends 64 served (64 backends open), 16 busy hostBackends after the 1 s wait
120 companies one after another, within a minute first refusal at 17th (hostBackends) first refusal at 101st (company.connections.pools)

Tests red on base, green on head (packages/company-database/src/CompanyDatabases.test.ts):

  • serves forty companies at once from a 64-backend budget
  • bursts each company to its maximum and refuses only true saturation (busy keeps resource: "backend budget", scope: "host", limitId: company.connections.hostBackends, value, retryAfterSeconds: 1)
  • closes other companies' idle connections for a company that needs one
  • admits a waiting company as soon as another company's connection idles
  • counts an evicted connection against its company until it has closed (eviction racing reacquisition)
  • drains an evicted connection before the next generation opens (eviction racing an override)

The last two hold the evicted connection open from outside, so the evicting company stays paused mid-close. On the previous head both fail with expected 'admitted' to equal 'queued': the owner opened a fifth connection over its maximum of four, or opened its next generation while the old connection was still live. Now a connection another company is closing stays counted against its own company's maximum, and blocks that company's generation change, until its close completes. That completion wakes the company's waiters.

  • never spends a backend its expiring company is still closing (eviction racing registry expiry)

Every path that closes a slot goes through one close: the registry's 60-second expiry, an override drain or another company's eviction. The first caller marks the slot closing and takes it out of the eviction candidates before yielding. Every caller then waits on the same completion, which settles only once the connection has closed and its backend is free. Before this, an expiring pool's slot stayed an eviction candidate mid-close, and a second Scope.close returned at once, so another company could open a connection while the original was still live, over the host budget.

  • leaves no connection open for an admission still opening one (service shutdown racing slot creation)

A slot's scope is a child of its company's registry scope, so company or service teardown reaches a slot that is still opening. A slot forked from a company that has already closed closes at once: it returns its backend without opening a connection, and the admission is refused.

Slot lifecycle. Each cell says what happens to a slot in that state when the event occurs. A slot counts against the host budget from the moment its company decides to open it until its last finalizer runs. The comment above closeSlot describes the same states.

Event ↓ / state → opening idle leased closing closed
acquire (same company) not visible; its admission is already counted in active taken back first, most recent first not available an eviction's or drain's close takes it out of the company's idle. After company or service teardown it stays in that closed company's idle, so a request that already held the registry entry can take it, run SQL until the pool shuts, then fail or be interrupted as closing: a discarded entry may still reference it; it holds no connection, so a request taking it fails
release — (a failed open undoes active and frees its backend through its scope) — back to idle, unless it was closed under the lease — —
evict (another company, host full) not a candidate retire: out of both idle lists at once; its company counts it in retiring until closed never if chosen before its first finalizer ran, the evictor waits on closed, not a second Scope.close —
owner expiry (60 s TTL) can't happen: the opener holds the registry entry the company closes its child scope; the slot's first finalizer marks it closing and drops it from the candidates can't happen: the lease holds the entry an eviction's close is already detached from the company and finishes it —
override drain can't happen: a drain needs active at 0 closeSlot on each, the company draining until all finish the drain waits for active to reach 0 the drain waits for retiring to reach 0 —
service shutdown the company closes its child scope; later finalizers run as they are added; openSlot refuses, no connection opened as owner expiry the pool waits for the checkout to return; release keeps it out of idle the evictor finishes it —
fatal error (connection dies) — the driver drops the connection; the slot stays counted and reconnects on next use the driver retires the connection. An ordinary admission's next statement outside a transaction gets a new one. A retained tier 2 lease pins its connection, so its later statements fail too, and only a later admission reconnects. Nothing reconnects or replays inside a retained transaction — —
interruption tryAcquire is uninterruptible — the admission's finalizer releases it finalizers run uninterruptibly —

closed is terminal: the backend is free, closed has settled, and the slot is in no list.

Follow-up, filed as #1014: the same company can briefly hold connections from two registry entries if it comes back while its expired entry is still closing. RcMap drops the key before closing the entry. This predates this PR, and the host budget holds either way.

These existing tests are unchanged and still pass:

  • "drains old pools before applying an override to one company": override changes still never overlap generations; old leases drain and old connections close before new ones open.
  • The queue, waiter, interruption and metering tests.

Follow-up, the next wall: company.connections.pools still caps a host at 100 companies active within a minute (the second row above). Raising it is now cheap, since a retained pool with no open connection holds no backend. It's a separate concern, so it isn't in this PR.

The counted number can be a little high, never low: a slot whose connection the driver closed after 60 idle seconds stays counted until the company's pool goes. Those slots are the longest idle, so they are the first to go when someone needs a backend.

How it was verified

  • pnpm verify (locked):
    • format, typecheck, synth, postgres-concurrency, cli-smoke, install and tier2-smoke passed.
    • browser failed once on a tier 1 navigation test, then passed 81/81 on a rerun.
    • lint failed only on the throwaway measurement script, which was deleted.
    • test failed in the packages/patchy CLI suites. Those fail the same way on origin/main on this machine (8 of 28 in cliPublish.test.ts) and don't touch this code.
    • test also caught one real failure: packages/patches/src/Content.test.ts assumed a zero budget refuses at once. It now runs that check on the live clock, through the one-second wait. This is the only edit outside packages/company-database, packages/limits and docs.
  • packages/company-database suites: 45 passed. pnpm test:postgres-concurrency: 28 passed.
  • The review's two scheduler-controlled reproductions, run on copies pointed at this head, pass across all 160 interleavings. At interleavings 24–28, where the previous head overlapped, the owner now waits; because the harness never resumes the evicting fiber, that wait ends in busy, and no replacement opens. The round-2 scheduler probe for registry expiry racing eviction passes on this head; its same-company case fails on base too and is Company pool can exceed its maximum when its registry entry expires mid-close #1014. The round-3 service-shutdown scheduler probe passes all its interleavings on this head; the round-1 probes still refuse rather than overlap, at interleavings 24–29.
  • Docs: ADR-0009 "Pools and locks", docs/OPERATIONS.md, the company-database glossary and the company.connections.hostBackends registry text, with docs/limits.md, the generated snapshot and the patchy-server skill table regenerated by render-docs.

Release impact

Tick exactly one.

  • Breaking — requires action from anyone already running this
  • Not breaking — no action required

In-process admission only. No schema, API, CLI or configuration format changes. PATCHY_COMPANY_DB_MAX_BACKENDS keeps its name and production value. It still bounds a host's company connections, so the Neon arithmetic in OPERATIONS is unchanged. One difference people may notice: a full host now queues for up to a second before busy instead of refusing at once.

  • What does a revert leave behind? Nothing: no rows, schema or external state.
  • Does the release before it still work with that? Yes.

Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.

@github-actions github-actions Bot added area:server Touches the server area area:docs Touches the docs area size:l 501-1,000 changed lines labels Oct 28, 2026
Rebased onto main after the TypeScript 7 stack (#985).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood force-pushed the t3/dynamic-company-backend-budget branch from c4bbbfd to 9842a4f Compare October 29, 2026 15:57
@allisonmahmood
allisonmahmood merged commit fa2f498 into main Oct 29, 2026
24 checks passed
@allisonmahmood
allisonmahmood deleted the t3/dynamic-company-backend-budget branch October 29, 2026 16:09
allisonmahmood added a commit that referenced this pull request Oct 29, 2026
## What changed

This adds release 23's What's new entry, written from `ed80fc7`. It
covers everything merged since release 22's `through` (`a2d1331`), and
sets the `patchy` release to `0.23.0` in `packages/patchy/package.json`
and `CURRENT_RELEASE`. This is the speed and capacity release: patches
that run server code open faster, and the fleet has room for more
companies at once.

| Change | PRs |
| --- | --- |
| Improved: Patches with server code open faster. Landing on Home or All
patches readies the company's server and its three most-opened patches,
a patch stays ready for ten minutes after use instead of one, loading a
patch takes a third of the time, and each company server has twice the
CPU | #991, #992, #997, #999, #984 |
| Behind the scenes: Patchy can run patches for more companies at the
same time (24 company boxes instead of 15, and 64 companies per host
instead of 16) | #984, #993 |

Two merged PRs get no line, because nobody using Patchy would notice
them: #990 (a second AWS cost alert, at $600) is operations tooling, and
#1049 (a test fix for flake #1012) is test churn. #1046 is release 22's
own entry.

## Look at

- **The entry**, at the top of `releases` in
`packages/core/src/whatsNew.ts`.
- **Rollback safety, from the live commit `eb414ed` (release 22) to
`ed80fc7`:**
  - No PR in the range is labelled `one-way`, and none adds a migration.
- #984 and #990 change infrastructure. A rollback redeploys release 22's
stacks: 0.5 vCPU tasks, a fleet budget of 15 with two spares, and no
`patchy-monthly-600` budget (the base stack deletes it; `patchy-monthly`
is untouched). Exec task definitions are retained, so release 22's hosts
can still manage this release's boxes until promotion.
- #984's one rollback hazard: once this release holds 14 or more spare
boxes, release 22 can't fit its two spares inside its budget of 15, and
its promote step times out. The fix is the runbook in
`docs/OPERATIONS.md` › Freeing budget for a promotion.
- #999 leaves binding history rows with release cause `unused`, which
release 22 reads as text. #999's new `speculative` bind field is refused
by release 22's supervisors before they act, so prewarms on those boxes
are skipped during a rolling deploy.
- Neither `execution.process.load` (#992) nor `execution.prewarm.window`
(#999) is set in production's `PATCHY_LIMITS_JSON`, so release 22 loads
the configuration unchanged.

**Rollback line:** If this release misbehaves, roll back to `eb414ed`
(release 22). If that rollback's promote step times out short of two
spares, follow `docs/OPERATIONS.md` › Freeing budget for a promotion,
then re-run it.

## How it was verified

- **Tests.** `whatsNew.test.ts`, `WhatsNewPages.test.ts` and
`schemas.test.ts` pass (21 tests), and prettier passes on the changed
files.
- **The range.** Each PR was Sol-reviewed with every finding fixed.
After the TypeScript 7 stack (#985), all seven were rebuilt on one
integration branch, with each conflict and each TypeScript 7 fix kept in
the PR it belongs to. `pnpm check` passed there, apart from local-only
CLI and supervisor test failures caused by T3 probing this machine's
ports. Each PR then landed with all 12 required checks green on its
rebased head, and main's tree after #990 equals the integration tip.
Re-runs: `clerk-live` once on #984 (a sign-in handshake flake). On #992,
flake #1012 failed twice and was fixed by #1049 instead of re-running.
- **Deploy state.** The live commit, pinned from `/healthz/deep`, is
`eb414ed` (release 22). The Deploy run updated last succeeded, and none
is unfinished.
- **Quota.** #984 peaks at 29 vCPUs during a deploy (24 boxes, 4 rolling
hosts, the promote task), inside the account's current 30.

## Release impact

- [ ] **Breaking** — requires action from anyone already running this
- [x] **Not breaking** — no action required

Text and version numbers only. The `0.23.0` bump tells CLIs and patch
repos installed before this deploy to upgrade, as every release does.

- **What does a revert leave behind?** Nothing.
- **Does the release before it still work with that?** Yes.

Made by Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, running in
T3 Code.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant