Skip to content

feat(patches): make patch deletion recoverable - #261

Merged
allisonmahmood merged 2 commits into
mainfrom
portal/248-lifecycle
Sep 16, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
portal/248-lifecycle

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Patches currently expire or disappear on deletion, with no recovery path. Replace automatic expiry with explicit live, retired and deleted states: retirement keeps a patch indefinitely, deletion starts a 30-day recovery window, and restore brings it back before reclamation.

Adds owner-checked lifecycle APIs and admin-only reassignment. Dependency checks serialize with publish and restore, preventing a source from going offline behind a consumer's commit. Migration, sweep, existing CLI compatibility and documentation follow the new lifecycle.

Stacked on main; this PR targets main.

Closes #248.

Verification:

  • pnpm lint passed.
  • pnpm typecheck passed (34 tasks).
  • pnpm test passed (750 tests across 76 files), including dependency-race and recovery-boundary regressions.

Implemented with OpenAI GPT-6 Astra using 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:cli Touches the cli area area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 15, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 25874b5 against origin/main at 05db5ad, using #248 and its referenced sections of #247. Single pass, no subagents. I would block merge on these three findings.

Standards

  1. Method: preserve recovery of pre-change publish responses. The two new required response fields break the unchanged CLI recovery decoder. The server deliberately replays stored JSON unchanged, so a publish committed before this change has neither field. The new CLI rejects that successful replay as unreachable, exits 3 and retains the pending attempt, blocking subsequent publishing. I reproduced this with the real source CLI after a lost acknowledgement. Adding just those two fields to the response made the same pending attempt recover successfully. ADR-0004, “Publish recovery”, requires recovery across release changes. Keep the new fields on fresh responses, but decode and apply retained responses without requiring today's complete response shape. Cover the upgrade case rather than updating every success fixture to the new shape.

  2. Method: use the existing bounded body reader for the new JSON routes. The description handler, like retire, restore and rollback, uses automatic payload decoding instead of the bounded readBody path used by share and publish. Effect's default MaxBodySize is undefined, and ApiGuard imposes no byte limit. The 500-code-point check runs only after Node has buffered and parsed the entire body. Against the real server, a description padded with 4 MiB of spaces returned 200; sharing rejected equivalent padding with 413. This makes request memory consumption unbounded. Reuse readBody/decodeBody with a finite cap and declare the 413 response, including enforcement for chunked bodies.

Spec

  1. Intent: migrate the name invariant before admitting restore of existing deleted patches. Migration 0008 leaves legacy deleted rows untouched. On origin/main, delete removes their patch_names entries immediately, and another patch can claim that name. The new restore only clears lifecycle stamps. Reproducing that legacy state, I restored the old patch with HTTP 200 and state: live, but it had zero name claims and its advertised address served the replacement patch. feat(patches): the lifecycle model: expiry goes; retire, delete with a recovery window, restore, rollback; the owner verbs on the wire; the deletion sweep #248 requires “names stay reserved”; Portal: finding and managing patches in the deployed stage #247 §3 says “restore always gets its address back”. Handle pre-existing deleted rows and already-claimed names in the migration/restore policy. Do not report successful restoration at another patch's address or steal that patch's claim.

No merge-blocking YAGNI findings. The deferred portal, discovery and new CLI verbs are explicitly outside this ticket's admitted scope.

Verification used disposable local state: one real-CLI replay reproduction and two real-server checks over isolated Postgres. The checks confirmed the failures described above; no product source changes were made.

Standards: 2 blockers, worst is unbounded request-body buffering. Spec: 1 blocker, restoration can report success at another patch's address.

@allisonmahmood allisonmahmood left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Issue 248 asked for the lifecycle prefactor: drop patch expiry, derive live/retired/deleted from stamps, put the owner verbs on the wire, and replace the expiry sweep with a 30-day deletion sweep. That is what this PR is. The list/detail schemas, portal admin UI, address notices, and lifecycle CLI verbs were correctly left to later tickets.

The method is the one the issue named: stamps, not a status column; Effect.fn moves on Patches with { userId, admin } under the patch-row lock; packages/api as the wire source. Two places diverge, and they matter. There is no first-class openable gate, and dependant/source checks are serialized by a company-wide advisory lock rather than the patch-row lock the issue named.

Standards

Documented-standard violations (hard)

Caller-visible messages name a CLI command that does not exist. PatchRetired / PatchDeleted tell agents to run `patchy restore`, and PatchesApi copies error.message onto the HTTP error field.

export class PatchRetired ...
    return "This patch is retired. Restore it (`patchy restore`) or ask an admin.";
...
    return `This patch is deleted ... Restore it (\`patchy restore\`) before then ...`;

.agents/skills/effect-service-conventions/SKILL.md (Errors: caller-visible messages are behavior). ADR-0004 lists no restore command. skills/patchy/SKILL.md and packages/patchy/README.md say lifecycle CLI verbs are later work; restore exists only as POST /api/patches/:patchId/restore. Agents following the refusal will invent a command. Drop the backtick command, or add the CLI verb and ADR-0004/--json row.

API restore, delete JSON { ok, patchId, state, deletedAt, purgeAt }, 0008 in the three migrator sites, catchTags, and ADR-0009 lock order (dependency → platform row; purge: platform FOR UPDATE then withPatchLock; reclaim after platform commit) look correct. No catchTag/catchIf. No UI consistency findings (Pages.ts comment-only).

Judgement calls (smells)

Mysterious Name. packages/company-database/src/OrphanSweep.ts aliases reclaimNamespace as dropNamespace to dodge a local function of the same name. Prefer Reclamation.reclaimNamespace() as DeletionSweep.ts does.

Duplicated Code. lifecycleFailures in PatchesApi.ts (around lines 71 to 149) is eleven near-copies of refuse(Wire, { code, error: error.message, … }). One mapper that copies structured fields would do.

Speculative Generality. LifecycleError is a kitchen-sink union on setScope/retire/delete/… so ownerFailures must InvalidOwner: Effect.die. reassign is service-only (no HTTP/CLI). Tighten per-operation channels; map InvalidOwner if that route lands.

Spec

Most of the lifecycle prefactor is present: 0008_patches_lifecycle (drop expires_at, actor/description/last_changed columns, partial deleted_at index) is applied at all three migrators, on ADR-0003, and after 0007 in Runtime’s replay test. serving / derived state / publishable, owner verbs, 30-day DeletionSweep, wire routes, and the listed tests match the issue. Ticket 3/8/11 work is correctly left out.

(a) Missing or partial

openable is not a real gate. Spec: “Three gates replace the one write predicate … openable (same company, disabled_at IS NULL, within the credential's sharing reach, any state) for reads; publishable (openable, owner, live) for publish.” serving and publishable exist. Reads other than inventory (find, resolveName) use serving only. The any-state path is lockTarget (FOR UPDATE, same company, not disabled) with no sharing-reach check.

(b) Not asked for

  • visit_count on 0008 is not in the column list (“add retired_at/by, deleted_by, reassigned_at/by, description … last_changed_at/by”). It does make “recordVisit keeps counting visits only” persist.
  • Company-wide lockDependencies (patchy:dependencies:) is extra. Spec: ownership/admin “in the same transaction under the patch-row lock.”

No ticket 3 list/detail schemas, ticket 8 portal UI, ticket 11 address notices, or new CLI verbs (--force deferred in product copy).

(c) Looks implemented, wrong

Restore sources_off classifies operator-disabled sources as gone with no name. Spec: restore “fails sources_off unless force, with each source's patch id, name when it exists, table and state (gone included)” and “restore lists a retired, a deleted and a gone source.” offSources joins source.disabled_at IS NULL, so a still-present disabled row is source.id IS NULL → gone. Disable is a separate take-down, not reclamation.

Otherwise the checklist holds: not_owner 403 first then 409 patch_retired/patch_deleted with purgeAt, checks before bytes and at commit, unshare force, other-company 404, reserved_name 422, retire/delete-from-live has_dependants unless force, restore now < purgeAt under the sweep’s row lock, delete reserves names, retired/deleted addresses 404, machine-token owners / admin via service only, expires_at gone from product/seed/docs this ticket owns.

Standards: 1 hard, 3 judgement. Worst: refusals tell agents to run patchy restore, which does not exist.
Spec: 1 partial, 2 unasked, 1 wrong. Worst: a disabled source is reported as gone.

Method

They followed the specified model, not a different one. State is derived from stamps (stateOf: deleted if deleted_at, else retired if retired_at, else live). Migration 0008 drops expires_at and adds the named stamp columns. Moves are Effect.fns on Patches with Actor { userId, admin }. Wire lives in packages/api. DeletionSweep replaces ExpirySweep on the same hourly schedule. Retire and delete-in-window only stamp; purge is what queues keys, drops versions/names/row, then reclaims.

The unjustified piece is the company-wide mutex:

  const lockDependencies = Effect.fn("Patches.lockDependencies")(
    (userId: string) =>
      sql`SELECT pg_advisory_xact_lock(hashtextextended('patchy:dependencies:' || company_id, 0))
      FROM users WHERE id = ${userId}`
  );

record, retire, delete, and restore take it before the row lock. refuseDependants / offSources are unlocked SELECTs. ADR-0009 was rewritten to bless the order (dependency lock → platform row → company patch lock). That is sound against write-skew (retire A while B publishes a declaration of A cannot serialize on A’s row alone), but it is not “under the patch-row lock,” and it serializes every publish/retire/delete/restore in the company.

Races that are under the row lock: publishable re-checks owner/state on FOR UPDATE at commit, so a publish authorized before reassign cannot commit after it. Restore and purgeDeleted both FOR UPDATE the same row.

Method match: mostly. Most important concern: dependant/source checks are unlocked reads serialized by a company-wide advisory lock, not by the patch-row lock the spec named.

YAGNI

YAGNI mixed.

State is derived, not stored. Gates match the spec without a Gate type. No status enum, no extra package, no retire/restore/rollback/describe CLI. DeletionSweep is the expiry sweep renamed. Reclamation.reclaimNamespace has two consumers. Patches.ts at 1683 lines is the repo’s one-service-one-file rule, not a split we should demand. Description, reserved names, and reassign are as specified.

Honest duplication to leave: per-act UPDATE stamp lists (the spec named per-act columns); SQL CASE in offSources vs TS stateOf. refuseDependants is the extract the spec named and has three callers.

Judgement, not blocking: afterChange re-reads the full patch after every verb when the locked row plus new stamps would do; reservedName is checked twice inside record on top of preflight. Do not add a Lifecycle module or a stamp helper. That would be the opposite of YAGNI.

Surfaces

Wire, migrations (three call sites plus Runtime after 0007), ADR-0003 ledger, ADR-0009 sweep paragraph, Patches glossary, docs/product.md section Updating, retiring, deleting (turned from decided to built), docs/DEVELOPMENT.md, reverse states on the API, and serving 404s are hit. CLI restore/retire/rollback/--force are deferred in product copy. skills-lock.json matches the skill hash.

Leftover: packages/auth/CONTEXT.md still says “patch retention is unchanged.”

Recover retained publish receipts without inventing metadata, bound lifecycle JSON bodies, and finalize legacy irreversible deletions without reclaiming replacement names. Observe real PostgreSQL waiter identities instead of truncated query text.
@allisonmahmood

allisonmahmood commented Sep 15, 2026 •

Copy link
Copy Markdown
Owner Author

Addressed the conversation review and the Reviews-tab review in 94cf67f.

Fixed

  • Publish recovery across upgrades: saved attempts can decode receipts without description metadata. Fresh publishes still require today's schema. Recovery preserves the retained JSON, reapplies the original identity and clears the attempt only after successful application. Added real-CLI regression coverage.
  • Unbounded lifecycle bodies: retire, restore, rollback and description now use the existing bounded readBody/decodeBody path and declare 413. Socket tests cover oversized declared bodies, chunked overflow, no mutation, malformed input and valid owner actions. Chunked overflow retains the existing Node transport-disconnect behavior; it is bounded rather than buffered indefinitely.
  • Legacy deleted names and resources: migration 0008 finalizes pre-lifecycle irreversible deletions, durably queuing their version objects before removing tombstones. It does not steal a replacement patch's name or offer restoration of resources the old orphan sweep could already have removed. The new 30-day recovery contract applies after migration. The upgrade regression preserves live names and receipts and checks cleanup eligibility.
  • Required PostgreSQL CI: replaced query-text probes with actual blocker/waiter backend identities. One waiter now stops at the dependency fence; the other SQL statement exceeded PostgreSQL's default activity-query capture length. The tests still verify blocking, version order, cumulative resources and lost-update protection. No timeout increase or production-lock removal.
  • Guidance and naming: removed the nonexistent patchy restore command from refusals, named/documented the existing any-state gate lockOpenable, switched orphan reclamation to its namespace import, and corrected the revocation glossary's retention wording.

Kept, with reasons

  • Company dependency fence: a source's patch-row lock alone cannot serialize a different consumer patch's commit. The four race regressions demonstrate the write-skew this fence prevents. Patch-row locks still protect ownership/state and restore/purge. Company-wide mutation serialization is the documented tradeoff; uploads and ordinary reads remain outside it.
  • Current openability and disabled-source masking: company/public sharing admits every member of the same company today. Inventory uses that any-state gate; address/runtime lookups correctly remain serving-only. Disabled patches must remain hidden under Portal: finding and managing patches in the deployed stage #247, so source warnings continue to omit their names and project them as unavailable/gone rather than disclose an operator-hidden patch or introduce an unrequested lifecycle state.
  • visit_count: needed to implement the ticket's requirement that visits continue counting after expiry top-ups disappear.
  • Explicit refusal mappings/shared error union, per-act stamp SQL, post-act rereads and preflight/commit name checks: retained as typed, explicit boundaries. The service-only InvalidOwner cannot be reached through an owner HTTP verb. These style suggestions did not identify another behavioral defect; generic field copying or a broader refactor is not needed for this fix.
  • Portal/discovery/new CLI verbs remain outside feat(patches): the lifecycle model: expiry goes; retire, delete with a recovery window, restore, rollback; the owner verbs on the wire; the deletion sweep #248.

Verification

On 94cf67f: pnpm lint passed; pnpm typecheck passed all 34 tasks; pnpm test:postgres-concurrency passed all 3 tests; pnpm test passed 757 tests across 77 files.

All seven required checks passed on 94cf67f: clerk-live, cli-smoke, dependency-review, lint, postgres-concurrency, test (22), and test (24). Evidence: https://github.com/allisonmahmood/patchy-cloud/actions/runs/34922503048. GitHub reports MERGEABLE and CLEAN. No new conversation, inline or submitted-review findings arrived after the fixes. No unresolved blockers; ready to merge, not merged.

@allisonmahmood
allisonmahmood merged commit aec0d70 into main Sep 16, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the portal/248-lifecycle branch September 16, 2026 15:52
@allisonmahmood
allisonmahmood restored the portal/248-lifecycle branch September 16, 2026 15:59
@allisonmahmood
allisonmahmood deleted the portal/248-lifecycle branch September 16, 2026 15:59
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:cli Touches the cli area area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

1 participant