Skip to content

feat(company-database): give each company its own resource database - #212

Merged
allisonmahmood merged 3 commits into
mainfrom
sdk/196-company-database
Sep 12, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
sdk/196-company-database

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Patch-owned resources need a durable home separate from platform records, without creating databases for companies that only publish primitive-free patches.

Add lazy, resumable company-database provisioning with bounded connection pools and transactional patch locks. Keep resource inventory consistent with schema changes, reclaim orphaned namespaces and files, and provide the same inventory services through a directory-backed PGlite development layer. Wire migrations and configuration through the server, dev runner and test harnesses.

Stacked on #211 (sdk/195-addresses); this PR intentionally targets that branch and contains only the company-database work.

Uses 0005_company_database_baseline because 0004_invites_expiry already occupies the issue's proposed migration number.

Closes #196.

Verification

  • pnpm lint — passed.
  • pnpm typecheck — passed.
  • pnpm test — 395 tests passed across 41 files.
  • Postgres and PGlite coverage includes provisioning recovery, capacity exhaustion, inventory consistency and orphan reclamation.

Implemented with GPT-6 Astra in the Oh My Pi harness.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 10, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

One-pass review, no subagents. Compared b010710a2791a48c8645adbbed648b30d7b94791 against origin/sdk/195-addresses (5f8d0933e839223ded94ce7b2a89e6f97bb0bdff), using #196 as the spec. Merge blockers only.

Standards

No additional merge-blocking method or YAGNI findings.

Spec

[P1] Placement queries deadlock against the caller's platform pool

PgCompanyDatabases.ts:114–121, reached by withCompany:291–303.

#196 requires “the platform patch-row lock always” and company-pool “exhaustion fails with busy.” The new independent SqlClient uses platformPool.reserve, so every withCompany → claim → placements lookup borrows another connection from the same platform pool, even for an already-ready company. If concurrent callers hold all ten default platform connections in their required patch-row transactions, each waits for an additional connection while retaining its first. None reaches company-pool admission or returns busy; increasing the pool merely moves the deadlock threshold.

Verified on disposable real Postgres: held ten distinct patch-row locks, with nine transactions calling withCompany and the tenth held behind a release gate. After one second, zero company bodies had entered. Releasing the tenth platform connection allowed all waiting calls to settle. The company was already ready and its company pool idle, isolating this to platform connection acquisition rather than provisioning or a contested patch lock.

Required change: remove the circular acquisition: placement/provisioning work must not require another connection from the pool whose connections its callers are holding. Preserve independently committed claims and the specified lock order. Cover this saturation case with real platform transactions, not only concurrent company transactions.

Verification

  • pnpm exec vitest run packages/company-database packages/content-store — 27 tests passed.
  • pnpm exec vitest run apps/server/src/start.test.ts — 8 tests passed.
  • Separate disposable-Postgres reproduction confirmed the blocker above; no repository files changed.

Summary: Standards: 0 blockers. Spec: 1 blocker; worst: P1 platform connection-pool deadlock.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Two-axis review of this PR against issue #196, plus a method / YAGNI pass. Six read-only reviewers; Standards and Spec were isolated from each other.

Issue 196 intent vs this PR. The ticket asked to birth @patchy/company-database: lazy claim → create → ready, bounded RcMap pools, withPatchLock, cumulative patchy inventory (including files), orphan namespace/file sweep on the existing hourly schedule, a PGlite adapter, and the docs/ADR surfaces. That kernel is here. Migration 0005_company_database_baseline is the allowed substitute for the occupied 0004. Primitive-free publish still does not touch this path. The remaining gaps are caller-facing seams and a few glossary lines, not a missing package.

Standards

Hard violations

packages/company-database/src/Inventory.ts — make = Effect.sync(() => Inventory.of({...})) then layer = Layer.effect(Inventory, make). Nothing is acquired; methods resolve SqlClient per call. Contrasts Analytics.layerNoop (Layer.succeed).
Cite: .agents/skills/effect-service-conventions/SKILL.md (Service definition: do not use Effect.succeed/sync make only to force Layer.effect; use Layer.succeed when that matches).
Fix: hoist the methods and Layer.succeed(Inventory, Inventory.of({...})).

packages/company-database/src/CompanyDatabases.ts — Busy already has _tag: "Busy" plus readonly code = "busy" (tests assert both). No wire mapping yet; handlers should map _tag, not a parallel literal.
Cite: same skill, Errors: do not encode the same distinction with a tagged error and a single-value code/kind/reason.
Fix: drop code.

Judgement calls

PgliteCompanyDatabases.ts — constructs CompanyIdentityMismatch then wraps it as CompanyDatabaseError { operation: "claim", cause }. Structured fields leave the typed channel (claim is only CompanyDatabaseError | Busy). Skill: wrap unknown/lower-level failures; do not manufacture a tagged error just to fill cause. Widen the port, or put expected/actual on CompanyDatabaseError.

packages/sql/CONTEXT.md — glossary still says “Companies owns baseline 1, Auth 2 and Patches 3”. 0005_company_database_baseline is on the three migrator spreads and in DEVELOPMENT.md, not here.
Cite: AGENTS.md / CLAUDE.md Hit every surface (vocabulary); docs/agents/domain.md (use the glossary; keep it current).

Duplicated Code — in-memory ContentStore.list/put with { html, lastModified } is copied in packages/patches/src/PatchesApi.test.ts, packages/serving/src/Pages.test.ts, and packages/patches/src/Content.test.ts. Extract one test double.

Mysterious Name — listReady maps failures with companyId: "*" (PgCompanyDatabases.ts). "*" is not a company id; omit it or use a list-specific error.

CompanyDatabaseError.operation matches existing StoreUnavailable.operation (generic message from a multi-value discriminator) — not flagged. catchIf on Postgres 42P04 is the allowed structural-predicate case. Port/adapter split matches ContentStore. Inventory.layer unwired in the server is fine until a production consumer exists. Migrations hit server, scripts/dev, and test/postgres.ts. UI consistency N/A.

Spec

(a) Missing / partial

None. Required services, migration 0005 (allowed 0004 substitute) on all three migrators, PGlite /dev layer, pnpm dev URLs, startup config, inventory schema + patchy.files, pools/Busy, advisory lock, namespace+file sweep on the hourly sweeper, ADR-0009, CONTEXT-MAP, AGENTS.md, DEVELOPMENT.md, README, patchy-dev-loop are present.

(b) Not asked for

  • Busy retry queues. Spec: “exhaustion fails with busy, never queues.” OrphanSweep.ts retries withCompany once after 61s. Pools still fail fast; the sweep waits. (ADR-0009, written in this PR, does specify that one retry.)
  • PGlite directory identity. Spec: “a PGlite layer of the same services (PgliteClient, one directory, one connection…)”. PgliteCompanyDatabases.ts adds local_company + CompanyIdentityMismatch (patchy-dev binding this ticket was not to build).
  • Inventory.read always locks. Spec Inventory bullet is read/write/bump. Inventory.ts wraps every read in withPatchLock, including a null read. ADR-0009 added this; issue feat(company-database): one Postgres database per company, its registry, pools and inventory #196 did not.

(c) Looks implemented, wrong vs spec

  • Creation is not “as its own step outside any transaction.” Spec: “creates the database through the provisioning login … outside any transaction”; SDK §3: “Creation runs as its own step outside any transaction.” PgCompanyDatabases.ensureReady runs CREATE DATABASE, grants, ALTER DATABASE, and Inventory.initialize inside platform.withTransaction while holding FOR UPDATE. AdminClient is a second connection (so CREATE is not in a PG transaction block), but create/configure/init are not a separate step; the platform row lock is held for the whole provision.
  • withCompany claims before admission. Spec: placement “inserted as a claim on the first publish that needs company-database resources”; “Nothing is created at company creation.” PgCompanyDatabases.withCompany always claim()s, then opens a pool, then ensureReady if not ready. A Busy lease still leaves a claimed row (CompanyDatabases.test.ts asserts that). Sweep uses listReady so it does not provision; the lease API still will.

Method

Verdict: sound with caveats.

The birth cut is right: lazy one-DB-per-company, two-phase claim/ready, bounded pools, cumulative inventory, reverse path for orphans. Dual-login is the smallest model that does not hand CREATEDB to the data role. RcMap + fail-fast Busy belongs in this package — the sweep already leases. ContentStore.list is the right reclamation seam and does not widen put to bytes.

Caveats for the next caller (primitives / publish):

  1. withCompany always provisions. Looking is creating. Primitive-free publish stays safe only as long as it never calls this. Platform patch-row lock first is an AGENTS.md comment, not an API.
  2. withPatchLock is a free function on whatever SqlClient is in scope; inventory methods leak SqlClient on purpose. The next publish path can write patchy.* into the platform database without a type error. Inventory.layer is in testing.ts and not in apps/server/src/Server.ts.
  3. Inventory putTable / putColumn / putIndex / putStore plus the kind CHECK lock the table primitive before that ticket exists. The physical schema had to be born complete (no company-DB migrator). patchy.files exists for the sweep, with no putFile; tests insert via raw SQL. Reverse path without a way in.
  4. PGlite is early (no patchy-dev consumer; @electric-sql/pglite is a production-package dependency). The shared inventoryContract is the value; the second adapter could have waited for ticket 14.
  5. Holding the platform row lock across CREATE on the admin connection is how concurrent ensureReady serialises. That is the right method even though issue feat(company-database): one Postgres database per company, its registry, pools and inventory #196 said “outside any transaction” (CREATE itself is not in a Postgres transaction block).

YAGNI

The ticket asked for a fairly complete kernel. Not flagged: RcMap/budget, idle TTL, inventory schema including files, PGlite layer, placement_version on the pool key, ContentStore list/lastModified.

Must cut (small)

  • Inventory.ts — File is decoded only in inventoryContract. No putFile; Snapshot correctly omits files. Keep the table; inline the test struct.
  • Inventory.ts — the class comment and the make comment say the same thing about not capturing SqlClient.

Judgement

  • putTable / putColumn / putIndex / putStore are a primitives write API (typed kinds, defaults, additive ON CONFLICT). Issue 196 said “write rows, bump revision.” A smaller kernel would be ensurePatch, read, bumpRevision, and sql\INSERT`— tests already insertfiles` that way. Conflict policy belongs in primitives. Leaving them is defensible so ticket 198 does not invent the write shape.
  • CompanyDatabaseError’s seven operation literals: nothing catches them; message is "${operation} failed". Fine for provisioning-stage logs.
  • PoolKey.serverId is move-prep beyond recording placementVersion. Harmless with one primary.
  • Busy.resource / limit distinguish three exhaustion sites. Spec only said busy.

What is simple

  • Inventory never captures SqlClient; the company lease is the transaction.
  • files table + SQL for the sweep; ContentStore.list without widening put.
  • Pool key records placementVersion and stops — no move command. PGlite is one local_company row, not a fake cluster.

Surfaces

Surface Status
Wire contract / CLI N/A
Dev loop Applied (scripts/dev, docs/DEVELOPMENT.md, patchy-dev-loop, test/postgres.ts)
Vocabulary / ADR Applied (CONTEXT.md, CONTEXT-MAP, ADR-0009, ADR-0003 updated)
Migrations Applied (server, dev runner, vitest template)
Company resources Applied (no production resource caller yet; lock rule documented)
Served pages N/A
Reverse states Applied (orphan sweep); drop/move deferred by ADR-0009
Repo layout Applied (README.md package list)

Misses

  1. packages/sql/CONTEXT.md still says “Companies owns baseline 1, Auth 2 and Patches 3”.
  2. README.md still says the runner “applies the three baselines.”
  3. apps/server/CONTEXT.md still names only the expiry sweep; hosting now also runs OrphanSweep.

Orphan sweep is on the existing hourly schedule (Server.ts runs expiry then orphan, once on boot and hourly).

Correctness

Claim/create is serialized on FOR UPDATE after an idempotent insert; CREATE runs on the admin client; resume is 42P04 on the claimed name; pool keys include placementVersion; the advisory key is a string ::bigint. Content-store list("files/") is prefix-safe. Secrets stay off Config failure output.

risk — inventory writes are unlocked. Only read takes withPatchLock. Advisory locks are cooperative: an unlocked writer can commit between a locked reader’s component queries. Tests only prove the protocol when both sides lock. Keep the outer lock for DDL+inventory, but fail writes that are not already in a patch-lock xact, or document a required wrapper type.

risk — file reclaim is check-then-delete, unlocked. fileReferences runs without withPatchLock. A day-old blob that gains an index row during the sweep can be deleted. New uploads are saved by lastModified < cutoff. Re-check the candidate under the patch lock (or skip delete unless updated_at is also older than the cutoff).

risk — SchemaError die kills expiry too. Orphan sweep Effect.dies on decode faults. Server.ts runs expiry then orphan on one forkScoped fiber, then repeat. A decode fault stops both hourly sweeps until restart. Isolate orphan with catchCause / a second fiber.

test-gap — interrupted CREATE. The interrupt test taps after execute succeeds. It proves resume after a finished CREATE, not that Effect.uninterruptible prevents pg_cancel_backend mid-CREATE.

test-gap — sweep Busy retry. The one 61s retry has no test. Foreground Busy is covered.


Summary: Standards 6 findings (worst: Inventory make forced through Layer.effect, plus Busy.code duplicating _tag). Spec 5 findings, 0 missing requirements (worst: withCompany claims/provisions before admission, so a Busy lease still leaves a claimed row). Method: sound with caveats (worst: lease API is a provision API). YAGNI: small cuts only; the kernel matches the ticket. Surfaces 3 stale glossary lines (worst: README.md “three baselines”). Correctness 3 risks / 2 test-gaps (worst: one sweeper fiber, so an orphan die takes expiry down with it).

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Reviewed both PR comments, the Reviews tab, and inline review comments. Fixes are in 079fda404a76918bca217372cafdcd2de7ab61af.

Fixed

  • Astra: platform-pool deadlock. Placement work now has an independent, bounded two-connection pool using the platform credentials; it never borrows connections held by callers' platform transactions. Claims still commit independently. The real-Postgres regression holds ten distinct patch-row transactions and attempts nine company leases without releasing any platform connection: the old acquisition path times out at two seconds; the fix settles the leases before release. The tenth transaction is only a cleanup escape hatch after the verdict.
  • Lease/provisioning boundary. withCompany is lease-only in PostgreSQL and PGlite. Missing/claimed placements return CompanyDatabaseNotReady; leasing neither inserts a claim nor provisions. Callers explicitly ensureReady when introducing resources. Tests verify both rejected states and successful explicit provisioning.
  • Unlocked inventory writes / wrong database. Company leases supply CompanyConnection; withPatchLock requires it and supplies a patch-id-bound PatchLock. Every inventory mutation requires that lock and rejects mismatched patch ids before writing. Shared PostgreSQL/PGlite tests exercise missing/wrong locks, unchanged inventory, absent namespaces, and rollback. Raw DDL still belongs inside the caller's outer patch-lock transaction; feat(primitives): tables, provisioned additively at publish #198 must take the platform row lock first.
  • File check/delete race. For an existing patch, final reclamation locks the platform row, then the owning company patch, rereads the index, and holds both through deletion. A real-Postgres regression publishes a reference to an old object after the batch scan and proves the object survives. Missing/unavailable indexes remain fail-closed.
  • Shared sweeper failure domain. Expiry and orphan sweeps have independent scoped fibers and per-pass defect containment. A deterministic test covers orphan failure, its next pass, continuing expiry during a hung orphan pass, shutdown interruption, and secret-free logs.
  • Service/error cleanup. Inventory uses Layer.succeed, not a synthetic synchronous acquisition. Removed redundant Busy.code, the duplicated comment, and the production-only-for-tests File schema. CompanyIdentityMismatch now remains directly in the typed error channel. List failures no longer invent company id "*".
  • Stale surfaces. Updated the SQL glossary, README migration wording, hosting glossary, development connection budget, and ADR lock/provisioning/sweep contracts.
  • Busy retry test gap. Added TestClock coverage using actual retained-pool pressure, plus persistent exhaustion, proving the 61-second boundary and at most one retry per company. Final file retries release the platform transaction before waiting.

Kept, with reasons

  • Placement lock through creation. CREATE DATABASE itself is autocommit on the independent admin connection, never inside a PostgreSQL transaction block. Holding the separate placement-row transaction serializes replicas and protects interrupted creation; removing it would lose that guarantee. Clarified the distinction in ADR-0009.
  • One background Busy retry. Foreground admission still never queues. A background scan must get past retained idle pools when there are more companies than the budget can retain (50 at the default budget); otherwise later companies can be repeatedly skipped. The bounded retry is now tested.
  • Locked inventory reads, including absent inventory. The lock prevents revision/component queries from straddling a provisioning commit. An absent read creates no resource. Writers now enforce the same protocol rather than relying solely on convention.
  • PGlite and its directory identity. PGlite is explicitly requested by feat(company-database): one Postgres database per company, its registry, pools and inventory #196. The one-row identity check prevents accidentally reopening another company's local data; it is not the future patchy-dev binding workflow. Its error is now directly typed.
  • Typed cumulative inventory writes and schema kinds. feat(company-database): one Postgres database per company, its registry, pools and inventory #196 requests inventory row writes and the complete physical inventory, and feat(primitives): tables, provisioned additively at publish #198 consumes this seam. Keep those methods rather than forcing its callers back to untyped inserts. File-index storage/reclamation stays; a file mutation API belongs to the file primitive ticket, not this change.
  • Small suite-local content-store doubles. Two simple doubles overlap, while the Content suite has different state/fault controls. Left them local rather than adding a shared exported testing surface solely for this cleanup; no production correctness depends on consolidating them.
  • Placement key fields, error stages, and Busy diagnostics. serverId/placement version identify the retained pool; operation stages preserve actionable failure context; resource/limit distinguish exhaustion boundaries. These do not add a move protocol or a wire error alias. Inventory remains unwired into production until it has a consumer. Migration 0005 remains necessary because 0004 is occupied.
  • Interrupted-CREATE test scope. Retained the deterministic recovery test for a completed CREATE interrupted before readiness commits. It does not claim to simulate wire-level cancellation during an in-flight CREATE. The production CREATE critical section remains uninterruptible; no separate template/driver fault infrastructure was added for that non-blocking coverage gap.

Verification

  • pnpm lint — passed.
  • pnpm typecheck — passed.
  • pnpm test — 401 passed across 42 files.
  • Focused database/scheduling run — 28 passed; final persistent-Busy regression passed after lint cleanup.
  • Saturation regression explicitly failed with the original shared-pool acquisition and passed with the independent placement pool.

All seven reported checks passed on 079fda404a76918bca217372cafdcd2de7ab61af: test (22), test (24), lint, clerk-live, cli-smoke, dependency-review, and label. CI run. The stacked base has no configured required checks (gh pr checks --required reports none); all reported checks were treated as the gate. GitHub reports this PR mergeable and clean against sdk/195-addresses. No unresolved merge blockers; the limited interrupted-CREATE coverage above is explicit. This PR has not been merged.

@allisonmahmood
allisonmahmood force-pushed the sdk/196-company-database branch from 079fda4 to ec83a86 Compare September 12, 2026 11:35
@allisonmahmood
allisonmahmood merged commit e26b622 into main Sep 12, 2026
7 of 14 checks passed
@allisonmahmood
allisonmahmood deleted the sdk/196-company-database branch September 12, 2026 11:40
allisonmahmood added a commit that referenced this pull request Sep 12, 2026
Patches need a browser-only operation path that cannot switch acting
users mid-page and records mutations before execution.

Adds runtime admission, loaded-version binding, host-supplied dispatch
and durable runtime logging. Only `me` is admitted now; file routes are
reserved for the Files ticket. Includes `0006_runtime_baseline`,
migration wiring, admission/outcome coverage and updated API/domain
documentation.

Stacked on #212 (`sdk/196-company-database`), which is the base branch
for this PR.

Closes #197.

## Verification
- Full offline suite: 428 tests passed across 46 files.
- Focused runtime, migration and real-server checks: 47 tests passed.
- `pnpm typecheck`, `pnpm lint` and `pnpm format:check` passed.
- Grok/Astra review findings addressed or explicitly dispositioned in
the PR review follow-up comment.

Implemented with OpenAI GPT-6 Astra in the Oh My Pi harness.
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: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.

feat(company-database): one Postgres database per company, its registry, pools and inventory

1 participant