Skip to content

refactor(patches): avoid unused inventory reads and broad row locks - #281

Merged
allisonmahmood merged 3 commits into
mainfrom
portal/cleanup-read-path
Sep 16, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
portal/cleanup-read-path

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Patch lists loaded inventory they never display, and user lifecycle commits locked every patch in the company. Lifecycle API refusals repeated the same response construction.

Fetch inventory only for detail routes. Keep the dependency advisory lock and transaction owned by Patches, and change selected patches in ID order before changing the user. Share the refusal mapping without changing wire bodies or unavailable-inventory semantics. The rollback regression still proves patch and user changes commit together.

Stacked on #272, with base branch portal/259-e2e-docs. This PR contains only the cleanup commit above that stack.

Verification

  • pnpm lint
  • pnpm typecheck
  • pnpm test:postgres-concurrency — 7 passed
  • pnpm exec vitest run packages/portal/src/PortalPages.test.ts — 47 passed

Implemented with openai-codex/gpt-6-astra using Oh My Pi.

@github-actions github-actions Bot added area:server Touches the server area size:m 100-500 changed lines labels Sep 16, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 8026f6d against origin/portal/259-e2e-docs using the cleanup brief in this PR description. One pass, no subagents. Merge blockers only.

Standards

No merge-blocking method or YAGNI findings.

Spec

P1 · Intent: revalidate ownership under the selected patch locks

UserLifecyclePage.ts:220–227, following the lock removal in Patches.ts:1107–1113.

The brief asks to “change selected patches in ID order before changing the user.” The narrower locking loses the existing exact-selection protection against reassignment. The handler reads ownership before acquiring patch-row locks. reassign does not take the dependency advisory lock, and retire accepts the admin without checking that the patch still belongs to the user being deactivated.

Reproduced with real Postgres and the HTTP handler, without replacing service implementations:

  1. Reassign a selected patch to another member inside a transaction, leaving it uncommitted.
  2. Submit the original owner's deactivation confirmation. It reads the old owner, then blocks on the patch's FOR UPDATE.
  3. Commit the reassignment.

The confirmation returns 303, retires the new owner's patch, and deactivates the original user. It should refuse with 409 and leave both lifecycle states unchanged. The retained exact-confirmation test covers reassignment before the request, not this interleaving.

Keep the narrower lock scope, but acquire the submitted patch IDs' row locks in ID order inside Patches before re-reading and validating the selection. Reject ownership changes under those locks and roll back the whole operation.

Verification

  • pnpm exec vitest run packages/portal/src/PortalPages.test.ts packages/patches/src/PatchesApi.test.ts packages/patches/src/Patches.test.ts: 119 passed.
  • Temporary isolated concurrency reproduction: failed, expected 409, received 303; the resulting patch was retired under its new owner and the original user was deactivated.

Summary: Standards 0 blockers; Spec 1, worst P1: concurrent reassignment lets deactivation retire another user's patch.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

First-reviewer pass standing in for grok build. Fixed point origin/portal/259-e2e-docs, three-dot diff, one commit (8026f6d). Two axes run separately: Standards (CLAUDE.md + .agents/skills/effect-service-conventions/SKILL.md) and Spec (the brief in the PR body). Line numbers are from the files as they stand on this branch.

Verdict: net simplification, ship it after the one judgement call below gets a decision. 179 lines out, 132 in, and the deletions are the expensive ones: a per-read company lease with an N-iteration inventory loop, and a FOR UPDATE over every patch row in the company. Nothing removed was load-bearing for correctness. One guarantee narrowed (selection staleness, item S3) and one lock was dropped further than the brief asked (item S1); both are defensible, neither is free.

Verification asked for

No wire body changed — confirmed. git diff origin/portal/259-e2e-docs...HEAD -- docs/API.md is empty, and it should be: refuse (packages/api/src/respond.ts:24) encodes through Schema.encodeSync(schema)(schema.make(body)), so field order and shape come from the schema AST, not from the object literal the new lifecycleFailure builds. The eleven bodies are byte-identical. PatchesApi.test.ts is untouched and still covers both inventory contracts in "reports unavailable inventory without inventing an empty database" (packages/patches/src/PatchesApi.test.ts:996): assert.isNull(detail.inventory) at :1011 and 503 / source_unavailable at :1016-1017. Both match docs/API.md:96 ("An unavailable company database means null inventory, never fabricated empty arrays") and docs/API.md:110.

Inventory is still null, never [] — confirmed. Patches.ts:1228 maps the inner SqlError to null; Patches.ts:1231-1236 maps Busy, CompanyDatabaseNotReady and CompanyDatabaseError to null and dies on CompanyIdentityMismatch. Both new call sites (PatchesApi.ts:550, :597) add only PatchUnavailable → 404 and SqlError → die. Patches.test.ts:803-805 and :1135/:1149 still assert the null outcome for every one of those tags. packages/patches/CONTEXT.md:92 ("Unavailable inventory is unknown, not empty") still describes the code.

Deadlock freedom — the argument holds. ADR-0009:30 fixes the order as "dependency lock, platform patch row, then company patch lock". record (publish) takes the advisory lock at Patches.ts:1652 before publishable → manageable → lockOpenable's patch row (:1091), then the owner row FOR UPDATE on creates (:1700). retire/restore/delete take it first too (:1865, :1881, :1899). Every one of those paths is therefore mutually excluded from the portal commit by the same company-keyed advisory lock, so no cycle is reachable between them. reassign (:1947) is the one mutation that does not take the advisory lock, and it goes patch row FOR UPDATE → target user FOR SHARE; the portal commit now goes patch rows → companies row → user row (Users.ts:162, :117). Same direction, so no ABBA. I checked every FOR UPDATE/FOR SHARE in packages/*/src: nothing anywhere takes a user or company row before a patch row, so the invariant the new comment claims is real and global.

Rollback-together regression still proves one transaction — yes, and slightly better. PortalPages.test.ts:2045 now fails inside users.deactivate after the real call, asserting from inside the transaction that the user reads deactivated and both patches read retired (:2062-2075), then asserts all three reverted (:2091-2093). The old version only ever observed one uncommitted write. What it no longer covers: a failure between the two retire calls. That path is untestable in the same shape now that the user change moved last, and the nested sql.withTransaction savepoints make it uninteresting; acceptable.

Standards

Sources: CLAUDE.md, .agents/skills/effect-service-conventions/SKILL.md, plus the Fowler smell baseline. No hard violations. Everything below is a judgement call.

  • N1 PatchesApi.ts:126-130, the code parameter is redundant. The helper mirrors refuse's S extends Schema.Top & Schema.Codec<…> + S["~type.make.in"] idiom exactly, and type safety holds (code stays the schema's literal, a wrong code or field still errors). But code is already part of ~type.make.in and fully determined by the schema. fields: Omit<S["~type.make.in"], "ok"> with refuse(schema, { ok: false, ...fields }) drops the parameter and the Codec<{readonly code: string}, unknown> constraint, and eleven call sites stop restating a literal the schema already owns.
  • N2 PatchesApi.ts:165-177, one copy survived. readFailures.WrongState still inlines the shape the new helper exists to delete, and fits it verbatim.
  • N3 PatchesApi.ts:550-562 and :597-609, duplicated code plus a data clump. Twelve identical lines, including a third restatement of the { companyId, userId, canOpen } clump that readOne (:269-276) already builds. A small inventoryFor(row, identity) next to readOne collapses both.
  • N4 Patches.ts:1214-1229 duplicates Patches.ts:1557-1569. The snapshot → PatchInventory construction, including the { schemaRevision: 0, tables: {}, files: {} } default, is now written twice, in companyInventory and inventory. One toInventory(snapshot) helper.
  • N5 Patches.ts:605 vs :625, two neighbours named alike behave differently. inventory fails on an unavailable company database; companyInventory returns null. Only one of them has a doc comment. Say so on companyInventory.
  • N6 UserLifecyclePage.ts:9, 109, 237, the page reaches past Patches for the SQL client. Allowed by the port shape and precedented (PortalPages.ts:440 already carries SqlClient in R), but the PR body says "Keep the dependency advisory lock and transaction owned by Patches", and the keep branch does the opposite of that sentence. See S1.
  • N7 UserLifecyclePage.ts:233-238, the three-way ternary hides the change. Nested in the return expression, it is easy to miss that keep now takes no advisory lock at all. Hoist it to a named wrap.
  • N8 UserLifecyclePage.ts:222, the sort is in a loop header and the comment above it explains something else. selected.sort(...) mutates in place (legal — selected is a fresh filter result — and it discards the name ordering from :161-163, which no longer matters here). The comment explains patch-before-user ordering; the thing that actually needs explaining is why deterministic id order replaced the deleted ORDER BY id FOR UPDATE. const ordered = [...selected].sort(...) plus a sentence.
  • N9 PortalPages.test.ts:2057-2073, fault injection is right, assertion placement is a trap. Layer.succeed(Users.Users, {...users, deactivate}) is an alternate layer, per CLAUDE.md ("Inject faults with an alternate layer, not a mock"), and asserting inside the injected function is the only way to see uncommitted state. But a failed assertion there becomes a defect, surfaces as a 500, and reports as expected 500 to equal 404 at :2090. Capture the three observed values into lets and assert them after the request, beside reachedDeactivation.
  • N10 Patches.test.ts:1135-1139, the surviving read call now proves something else. With inventory gone from ReadPatch, that call proves read no longer touches the company database at all — a genuine property of this change, and worth keeping. It just needs a word saying that, or the reader sees a stray id assertion in a test named "recovers company operational errors".

Spec

Brief: (1) read stops loading inventory, detail and primitive routes fetch it through companyInventory, null preserved; (2) withCompanyLifecycleLock → withDependencyLock, patch moves before the user change; (3) eleven-copy mapper → one mapper, identical bodies.

Nothing from the brief is missing. Clause 3 is fully met. Clause 1 is met and its coverage is not lost: the deleted assert.deepStrictEqual(detail.inventory, before) is already covered at Patches.test.ts:817 through companyInventory, and the unavailable-database-returns-null case is still proven at :803-805, :1135 and :1149.

  • S1 (scope) UserLifecyclePage.ts:233-238: keep lost the advisory lock, which the brief did not ask for. The brief replaces the lock; it does not say the user-only path stops taking one. On keep, selectedIds is empty (:169), so the loop at :222 is a no-op and the only write is users.deactivate/reactivate, which already runs its own transaction and lockUser FOR UPDATE (Users.ts:193-210). So the new bare sql.withTransaction buys almost nothing, while dropping the serialisation the old path had against concurrent retire/restore/publish. Practical impact is small — keep touches no patch rows, so ADR-0009:30's order is not violated, and a dependant admitted concurrently against a source whose owner is deactivating lands in exactly the state the confirm page already warns about ("will lose access on their next read"). Two clean exits, both simpler than what is there: either choice === "keep" || choice === "confirm" ? patches.withDependencyLock(...) : run, restoring the old guarantee for the price of one uncontended advisory lock; or drop the wrapper entirely for keep and let Users own its transaction. Either one deletes the SqlClient import (N6) and the three-way ternary (N7). I would take the first.
  • S2 (scope, minor) UserLifecyclePage.ts:222. The id sort was not requested. It is the right instinct, but the advisory lock already serialises every other multi-patch taker, so it is defence against backfillNames (Patches.ts:864, which orders by created_at, id and takes no advisory lock) more than against anything else — a pre-existing mismatch, not one this PR creates.
  • S3 (behaviour) selection staleness narrowed, and this is the one real cost. Previously withCompanyLifecycleLock locked every company patch row before run executed, so the rows.filter(row => row.owner.id === id) read (:161-163) and the selected.length !== selectedIds.size recheck (:187) ran against a frozen set. Now the read is unlocked and reassign — the one mutation that skips the advisory lock — can commit between the read and the retire. Result: an admin confirms a deactivation and a patch that just moved to another owner gets retired anyway (the retire is force/admin, so manageable will not refuse it). Reassign to the user is still blocked, by FOR SHARE against lockUser's FOR UPDATE; that case just means a patch is missed, which is benign. The damage is recoverable (restore exists) and the window is admin-vs-admin, so accepting it is reasonable — but it is the guarantee the deleted lock was actually buying, and it deserves a sentence in the code or the PR body rather than silence. If you want it back cheaply, have the retire loop assert the owner it read is the owner it locked.
  • S4 (behaviour, minor) new TOCTOU in the detail and primitive routes. readOne and companyInventory are two separate untransacted platform reads, each running the patch query and re-applying openability. A retire or delete landing between them turns a request that would have succeeded into a 404 PatchUnavailable. The wire shape is unchanged and the window is tiny; noting it so nobody is surprised by a flake. Cost is one extra indexed row query per detail request, against a company lease and an N-row inventory loop saved on every list request — a clear win.

Coverage gap worth one test

Nothing proves the headline claim of clause 2 — that a deactivation commit no longer blocks unrelated patches. PortalPages.test.ts:1491 still proves the preview takes no locks (and correctly now holds the lock through withDependencyLock), but there is no test that an unrelated patch's operation proceeds while a commit is in flight. One case in the postgres-concurrency suite would pin the behaviour this PR exists to create. Judgement call; skip it if you think the advisory lock speaks for itself.

Summary

Standards: 10 findings, all judgement calls, no hard violations; worst is N3 (the twelve duplicated lines across the two new call sites, carrying a third copy of the access clump). Spec: 4 findings; worst is S1 (the keep path dropping the advisory lock, beyond the brief and replaceable with strictly simpler code), with S3 close behind as the deliberate-accept item.

Reviewed with claude-opus-5[1m] in Claude Code.

@allisonmahmood

allisonmahmood commented Sep 16, 2026 •

Copy link
Copy Markdown
Owner Author

Addressed the Astra and Opus reviews in 5b74b28; CI test repair is in 01f9737.

Fixed

  • Astra P1 / Opus S3: retire and restore now accept an optional expectedOwnerUserId, checked after manageable locks and refreshes the patch row. User lifecycle confirmation passes the affected user's ID. Concurrent reassignment therefore reaches the existing StaleAction → 409 response instead of moving the new owner's patch. No broad row lock was added.
  • Opus S1, N6, N7: both keep and confirm use Patches.withDependencyLock. Removed the portal's SqlClient dependency and nested ternary; previews remain unlocked.
  • Opus N5: documented companyInventory's null-for-unavailable contract.
  • Opus N8 (comment): clarified deterministic patch-ID ordering and patch-before-user locking.
  • Concurrency coverage: added real-Postgres HTTP regressions for both deactivation and reactivation. Each holds an uncommitted reassignment, observes confirmation waiting on that backend's row lock, commits the reassignment, and requires 409. They check that the user and an earlier selected patch remain unchanged, the committed reassignment survives, and an unrelated patch's description can be edited while confirmation waits.
  • CI test repair: Node 22 twice timed out an existing test that ran eight CLI subprocesses under one five-second deadline. Split rejected-description inputs from successful clear/normalize updates, retaining every case and assertion. No timeout increases, skipped tests, or automatic retries. Node 24's separate startup subprocess failure passed unchanged on rerun.

Kept as-is

  • N1: retained the requested (schema, code, fields) mapper signature; folding code into fields changes no behavior.
  • N2: retained the discovery-specific WrongState response and its guidance separately from lifecycle failures.
  • N3, N4: retained the explicit route lookups and inventory projections rather than adding helpers solely to deduplicate these small blocks.
  • N8 (array copy), S2: sorting selected patches by ID was explicitly requested. filter already produces a fresh array, so sorting it in place avoids an unnecessary copy.
  • N9: retained the rollback test's assertions inside the injected user mutation: they observe the uncommitted changes before the forced failure. An assertion failure still fails the test through the expected response/reached-mutation checks; moving them would improve diagnostics, not correctness.
  • N10: retained the platform-read assertion in the inventory-error test: discovery must remain available when company inventory is unavailable.
  • S4: retirement/deletion does not itself make the separate inventory read return 404: companyPatchRow excludes disabled rows, not retired/deleted rows, and default openability allows them. A later disable, purge, or access revocation should fail the fresh access check rather than return stale inventory.

Verification

  • Both reassignment regressions failed before the fix with 303 instead of 409, then passed.
  • pnpm format:check, pnpm lint, pnpm typecheck: passed.
  • Focused portal, patches, API, and startup suites: 130 passed.
  • pnpm test:postgres-concurrency: 7 passed.
  • pnpm test --maxWorkers=2: 937 passed across 80 files on 5b74b28.
  • After splitting the existing CLI scenario in 01f9737: both resulting tests, file lint, and formatting passed locally.
  • Final CI on 01f9737: all eight checks passed: Node 22 and 24 full suites, Postgres concurrency, live Clerk, packed CLI smoke, lint/typecheck/formatting, dependency review, and labels.

These are internal locking/precondition changes. Wire schemas, CLI output, migrations, dev-loop contracts, product vocabulary, and served-page markup are unchanged. Both lifecycle directions are covered. No review-body or inline threads were present; this comment records the disposition of both conversation reviews.

Rechecked conversation comments, review bodies, and inline comments after the final push: no new review findings. PR is open and mergeable; not merged.

@github-actions github-actions Bot added the area:cli Touches the cli area label Sep 16, 2026
@allisonmahmood
allisonmahmood force-pushed the portal/cleanup-read-path branch from 01f9737 to 99bc99c Compare September 16, 2026 16:00
Base automatically changed from portal/259-e2e-docs to main September 16, 2026 18:25
@allisonmahmood
allisonmahmood force-pushed the portal/cleanup-read-path branch from 99bc99c to 65905d1 Compare September 16, 2026 18:25
@allisonmahmood
allisonmahmood merged commit 3527c3f into main Sep 16, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the portal/cleanup-read-path branch September 16, 2026 18:34
allisonmahmood added a commit that referenced this pull request Sep 16, 2026
)

Portal rendering mixed confirmations with the index, card and versions
pages through one mutable options bag. The API guard also depended on
portal rendering and browser-session services just to answer
hand-crafted overlong names.

Split confirmation handling into `confirmationPage`, preserving the
existing refusal precedence, copy and form state. Leave portal name
bounds to its routes and remove the portal branch from the API guard.
Unroutable overlong POSTs and encoded-slash GETs now use the existing
404 responses; API behavior stays unchanged.

Stacked on `portal/cleanup-read-path` (#281). This PR contains only the
next cleanup commit and should merge after that branch.

## Verification
- `pnpm lint` passed.
- `pnpm typecheck` passed.
- `pnpm exec vitest run apps/server packages/portal` passed: 86 tests
across 5 files.
- Earlier full-suite runs each passed 936 of 938 tests, with 5-second
timeouts in different untouched Postgres or CLI tests. All timed-out
cases passed in isolation; no assertions or timeouts were relaxed.

Model: `openai-codex/gpt-6-astra`. Harness: Oh My Pi.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Touches the cli area area:server Touches the server area size:m 100-500 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant