Skip to content

feat(patches): packages/patches owns records, uploads, retention and the sweep - #87

Merged
allisonmahmood merged 4 commits into
mainfrom
feat/patches-package
Aug 29, 2026
Merged

allisonmahmood merged 4 commits into
mainfrom
feat/patches-package

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Problem

Everything about a patch — its record and versions, the upload contract, visits and the retention clock, pins, moderation, the quota — lived in packages/db behind a two-driver PatchyDb port, with the expiry sweep bolted onto the Fastify app. Every rule existed twice (SQL and TypeScript) with a 1,300-line contract suite holding them equal, and the tables and code still said draft a ticket after the wire stopped.

Solution

packages/patches is the capability on Effect: Patches (every row, decoded through SqlSchema in one module — the retention clock, the visit top-up and the revocation freeze are SQL fragments read on the Effect clock), Content (the one place bytes are touched: put, insert, rollback on a refused row; the read a served page is built from), ExpirySweep (one sweep the server forks with Effect.repeat(…, Schedule.spaced("1 hour"))), and the patches HttpApiBuilder group. Migration 3 is the baseline with patches / patch_versions; draft is gone from tables and code.

The JSON driver and the PatchyDb port are deleted (ADR-0003, Postgres only); packages/db keeps only the migrateDatabase seam. The Fastify app serves both API groups through one runtime seam, reads pages through Content, and its tests run on a Postgres clone per app. Tests: it.layer on a migrated database, HttpApiTest.groups(PatchyApi, ["patches"]), the sweep driven by TestClock, the rollback with a failing ContentStore layer. pnpm dev serves uploads end to end through patches → content-store.

Deviations from #76, named:

  • patches also depends on limits: the per-token create limit is spent inside the upload handler (same as auth's mint limit), so the 422 → 429 → 403 order stays.
  • upload_events and visibility are not in the baseline — nothing read them.
  • Two concurrent sweeps no longer share one run; the database re-check makes overlap safe and the test asserts the sum.
  • hasScope and refuse moved into @patchy/api so both groups share them; PatchQuotaExceeded is listed before Forbidden so a client decoding a 403 keeps code.
  • packages/db keeps the migration seam rather than a factory: with one driver the factory was the seam.
  • The CLI's draft identifiers, rendered copy (Live draft host, the <!-- draft:… --> marker) and the self-hosting/Docker e2e scripts that started the JSON driver are left for the CLI and clean-up tickets.

Stacked on #86.

Closes #76

Built by Claude Fable 5 via Claude Code.

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

Copy link
Copy Markdown
Owner Author

/code-review — PR 87 vs issue 76

Two-axis review of 8457bbb...899a49c (feat/content-store → feat/patches-package). Extra axes as asked: how it was built, and whether it is the smallest model.


Standards

Hard

packages/patches/src/Content.ts:122–124 — tapError recovers the upload refusals by error._tag === "SqlError". .agents/skills/effect-service-conventions/SKILL.md (Errors and predicates): catch known tags with Effect.catchTags, not _tag / catchTag / catchIf on tags. Patches.record’s channel is PatchUnavailable | PatchConflict | SqlError. Fix: catchTags (or tapErrorTags) on the two refusals and store.delete(key).pipe(Effect.orDie), leave SqlError alone.

packages/patches/src/PatchesApi.ts:180–192 — after catchTags for the dies, Effect.result then uploaded.failure._tag === "PatchUnavailable". Same rule. AuthApi already maps a domain tag with catchTags. Fix: add PatchUnavailable / PatchConflict to that catchTags and return notFound() / refuse(Conflict, …) there.

Judgement (smells / port shape)

packages/patches/src/Content.test.ts:25–49, 54, 113–151 — Inject faults with an alternate layer. One Layer.succeed store, Effect.runSync at import, then control.putError / deleteError mutation. ExpirySweep.test.ts:129–152 already uses an alternate layer. The afterPut race hook can stay; the fail-put/fail-delete cases should be extra layers.

packages/patches/src/PatchesApi.ts:49–69 — Duplicated Code with packages/auth/src/AuthApi.ts (forbidden, rateLimited, cleanText). Second consumer; not a new package. (Tiny helpers — YAGNI can reasonably leave them local.)

apps/server/src/render.ts:81, 101–117, 130–133 — Mysterious Name / incomplete rename. packages/patches/CONTEXT.md says draft is gone from code; wrapper fallback is still "Patchy draft", class draft-frame, comment draft:. Sandbox / srcdoc escaping unchanged. PR named the rendered copy as deferred.

No documented-standard breach in Patches.ts (tag/make/layer, yield* deps, SqlSchema + withTransaction, Postgres, structured TaggedError), ExpirySweep.ts (Effect.catch on the whole delete channel is allowed), PatchesConfig.ts, migrations.ts (id 3), packages/api/src/respond.ts, schemas.ts, apps/server/src/runtime.ts / start.ts, packages/db/src/migrate.ts (runPromise / ManagedRuntime at the Fastify/db seam). ADR-0003 holds: no JSON/PatchyDb.

No UI consistency findings.


Spec

(a) Missing / partial

“draft → patch rename in tables and code” / Done when: “no draft remains in tables or code.”
Tables and packages/patches are renamed. draft still lives in CLI (--draft, drafts.json), skills, and docs/SELF_HOSTING.md (still drafts / draft_versions / json driver). #68 tickets 10–11 defer that, but it fails the Done-when line. Copy this PR did touch is still draft: apps/server/src/render.ts (Live draft host, .draft-frame, <!-- draft:… -->), plus app.test.ts / analytics.test.ts names. The PR named the rendered copy and CLI identifiers as deferred; the Fastify test titles were not named.

“Delete everything left in packages/db except the factory the Fastify app still imports.”
Factory is gone (createApp no longer takes db). What remains is migrateDatabase (packages/db/src/migrate.ts), which start.ts still calls. Matches the leftover-seam intent, not the named factory. PR named this.

“Depends on content-store, sql, analytics, api; never auth.”
Runtime dependencies have no @patchy/auth. @patchy/auth is a devDependency; src/test/fixtures.ts imports auth migrations. Handlers still take CurrentIdentity from bearer middleware — intent held, literal “never” bent.

(b) Not asked for

hasScope / refuse moved into @patchy/api, and packages/auth/src/AuthApi.ts rewritten to use them. PatchQuotaExceeded listed before Forbidden on upload. Neither is in #76; both are named, and both have a second consumer / a real decode-order reason.

limits.consume on create is in-scope, not creep.
#76: “patch quota (a DB count, not limits)” — that quota is Patches.countLive, a DB count. The per-minute create bucket is the old Fastify draft-create limiter, moved into the handler (auth’s mint pattern). #68 §8 keeps limiter semantics; quotas stay out of limits. 422 → 429 → 403 is preserved.

Dropping upload_events / visibility matches ADR-0003 (cited). Concurrent sweeps no longer sharing a run is covered: app.test.ts asserts first.deleted + second.deleted === 1.

(c) Looks implemented, but off

Most of the checklist holds: HttpApiBuilder.group + Fastify seam; SqlSchema in Patches.ts with SchemaError → die; sql.withTransaction on record / deleteExpired; /d/* unchanged; language-service diagnostics error in packages/patches/tsconfig.json; expiry-sweep.ts / upload-contract.test.ts / app.postgres.test.ts gone; it.layer; HttpApiTest.groups(PatchyApi, ["patches"]); TestClock + Effect.repeat(..., Schedule.spaced("1 hour")) in ExpirySweep.test.ts.

Rollback vs “failing ContentStore layer”: rollback-on-refused-row is tested by disabling after put, then asserting the object is deleted. The failing store covers put-fail and delete-fail-during-rollback (Effect.orDie), not the happy rollback trigger. Contract (object then row, rollback on refusal) is right; the spec’s fault-layer wording is only half-matched. Keep-object-on-SqlError is untested.


Method

The cut is the one the ticket asked for, not an extra service zoo.

  • Patches / Content / ExpirySweep is the right three-way split. Rows never touch bytes. Content is the live contract (two consumers already: upload and Fastify readPatch). The sweep is the dead path: never-fail, count orphans, record-then-bytes. Folding either way would make row tests need a store, or mix the janitor into the live contract.
  • Create limit spent in PatchesApi is the right named deviation. Fastify’s pre-body hooks cannot see patchId === null without parsing the body. Same pattern as mint in AuthApi. The DB quota stays a count. Pre-body protected-api / authenticated-upload buckets correctly stay in the Fastify app.
  • Upload contract (checkTarget → put → record + rollback only on refusal) is the smallest correct model. record re-checks under FOR UPDATE / ON CONFLICT, so the TOCTOU is closed. Keep-on-SqlError is the same bias as the sweep: an orphan costs storage, a referenced object that vanished costs the reader the page. Rollback-delete orDie is right — a 404 that left an object would be a lie.
  • Sweep overlapping runs are safer than the old “share one run”. A process mutex does not help two hosts. listExpired + deleteExpired FOR UPDATE re-check does. The concurrent test in app.test.ts is the method.
  • Retention clock in SQL fragments on the Effect clock is the quality of this PR. One notExpired predicate, one visit UPDATE, created_at still on SQL now(). Computing in TS would be a read-modify-write race unless you also lock.
  • Fastify seam (readPatch / recordVisit / serveApi) is the port rule: runPromise only at the unported boundary. Visit stays in app.ts (best-effort after the page is in hand) — do not hide it in Content.read. getObject is the one leftover: serving no longer talks to the store; one Fastify test still does.

PatchRow (Date) → Patch (ISO string) is the current driver, not a future-proofing layer. Auth maps revokedAt the same way. The Stamp alias is the isolation the sql README asked for.


YAGNI

What is already the small model: one SqlSchema module, one notExpired predicate, pin/unpin as two WHEREs, Content as the upload contract rather than a Middle Man, refuse in @patchy/api because a second consumer exists, @patchy/db as the Fastify/dev migrator seam until serving.

What I would still cut:

  • getObject in apps/server/src/runtime.ts — one Fastify test, duplicates Content.test.ts.
  • Fastify suite still restating Content / ExpirySweep / retention cases after the package tests landed. app.postgres.test.ts was deleted; the leftover is app.test.ts (~1805–2128 and the upload-contract injects). Serving-header and visit-failure-on-the-socket cases belong there; the rest is the old contract suite in Fastify clothes.
  • sweepOne mutating a shared bag — return a delta and add. BATCH_SIZE + relist-while is leftover of unbounded SELECT; listExpired(MAX_PER_RUN) once is the same job at the cap.
  • File headers that reprint CONTEXT.md. Keep the invariants next to the SQL (writable, pin vs unpin, record-before-bytes, Effect clock vs now()).
  • ModerationOptions wrapping one boolean.

The two 15-field structs (UploadInput, RecordInput) are the columns, not invention. I would not extract a provenance type for one copy site.

toPatch / ISO strings: the YAGNI reading is “decode Date, ISO at the wire.” The method reading is “the driver returns Date today, the domain already speaks ISO, Auth does this.” I would not redo it in this PR.


Intent vs what landed

Issue 76 asked for the patches capability to own records, the upload contract, the clock, the sweep, and the group; for draft to leave tables and code; for Postgres-only; for tests on it.layer / HttpApiTest / TestClock / a failing store.

That is what landed, with the deviations the PR named (limits on create, no upload_events/visibility, overlapping sweeps, refuse/hasScope in api, migrator seam instead of factory, CLI/rendered draft deferred). The Fastify test titles and SELF_HOSTING.md still talking like the JSON driver exists are the incomplete edges of that deferral.


Standards: 2 hard, 3 judgement. Worst: Content.upload rollback branches on error._tag instead of catchTags.
Spec: 3 partial, 1 test-wording miss, 0 real scope creep. Worst: Done-when “no draft in tables or code” is tables-and-package only; Fastify copy/tests still say draft.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Went through the review. Pushed the fixes in the follow-up commit; here is what was taken and what was not.

Fixed

  • Content.upload rollback and the upload handler now recover the two refusals with Effect.catchTags (no _tag branch, no Effect.result).
  • Content.test.ts: the put-fails and delete-fails cases now come from alternate ContentStore layers over the same memory store; only the afterPut race hook stays a knob.
  • ExpirySweep.sweepOne returns a per-patch delta; the run sums them.
  • getObject seam removed from runtime.ts; the one Fastify test reads the store through the harness.
  • Fastify test titles in app.test.ts / analytics.test.ts say patch.

Left as is, with reasons

  • Rendered copy and markers (Patchy draft, .draft-frame, <!-- draft:… -->): reader-facing HTML. Changing copy is a UI change that gets mocks first, not a rename commit; the marker is something readers' tooling may grep. Named in the PR.
  • CLI --draft / drafts.json, skills, SELF_HOSTING.md prose: the CLI port (feat(cli): patchy on effect/unstable/cli with the agent contract #78) rewrites the CLI, and the self-hosting clean-up ticket wipes that doc; touching them here would be a second, conflicting rename.
  • @patchy/auth as a devDependency: test-only, for the accounts/api_tokens DDL the FK needs. Handlers still meet the principal only through CurrentIdentity.
  • forbidden / rateLimited / cleanText duplicated with AuthApi: three one-liners; refuse and hasScope were the ones worth sharing.
  • ModerationOptions, the batch loop, file headers: cosmetic; not worth churn on a PR this size.
  • Trimming the Fastify suite's retention/sweep cases: they are the only tests exercising the Fastify seam end to end until serving lands, and that ticket deletes the app anyway.
  • Keep-object-on-SqlError untested: injecting a mid-transaction SqlError through a layer needs a fake SqlClient; the behaviour is a two-line policy in Content.upload and I would rather not add a mock for it.

pnpm lint, typecheck, format:check and test (365) are green on the branch. Ready to merge from my side.

Patch records, versions, the upload contract, visits, retention, pins,
moderation and the patch quota lived in packages/db behind a two-driver
port, with the expiry sweep in apps/server. They become the `patches`
capability on Effect: `Patches` (rows, decoded through SqlSchema in one
module), `Content` (the one place bytes are touched: put, insert, rollback
on a refused row; the served read), `ExpirySweep` (one `sweep` the server
forks hourly on Schedule.spaced), and the `patches` HttpApi group. Migration
3 is the baseline with `patches` / `patch_versions` naming; `draft` is gone
from tables and code.

The JSON driver, the PatchyDb port and its contract suite are deleted
(ADR-0003, Postgres only); packages/db keeps only the migration seam. The
Fastify app serves both API groups through one runtime seam and reads pages
through `Content`; its tests run on a Postgres clone per app.
Catch the upload refusals with catchTags in Content.upload and the
handler instead of branching on _tag; inject the put and delete faults
in Content.test through alternate ContentStore layers; sweepOne answers
a delta rather than mutating a shared bag; drop the getObject seam; the
Fastify test titles say patch.
…ith it

verify-server-image.sh asserted PATCHY_DB_FILE and read the JSON-file
database, which this branch deletes. Remove it, the docker-save artifact
validator, the docker CI job, the docker turbo task and the root scripts
that ran them.
The server now requires DATABASE_URL, so the e2e starts an embedded
Postgres under its temp root and reads its assertions from SQL instead of
the deleted metadata.json. embedded-postgres is imported lazily and its
process-exiting signal handlers removed, so the harness's own cleanup runs.
@allisonmahmood
allisonmahmood merged commit 58d20b6 into main Aug 29, 2026
6 checks passed
@allisonmahmood
allisonmahmood deleted the feat/patches-package branch August 29, 2026 23:22
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:core Touches the core area 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(patches): packages/patches with the sweep and the patch rename

1 participant