Skip to content

feat(patches): make publishing replay-safe - #210

Merged
allisonmahmood merged 4 commits into
mainfrom
sdk/194-publish
Sep 12, 2026
Merged

allisonmahmood merged 4 commits into
mainfrom
sdk/194-publish

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Publishing needs a manifest and version record that can carry every runtime tier, and retrying after a lost response must not create another version.

Replace upload with manifest-based publish and durable CLI recovery. Store the original response for replay, stamp each version, and reclaim failed publish objects without deleting committed content. This change admits only tier 0 with no provisioned resources and updates the CLI, docs, skills, and baseline migration together.

Stacked directly on main; the PR base is main.

Validation: pnpm lint, pnpm typecheck, pnpm test (345 tests), and pnpm test:packed-cli-e2e passed. Standards and specification review findings are resolved.

Closes #194.

Implemented with GPT-6 Astra in the Oh My Pi coding 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 10, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 343da28 against origin/main (fb17d6d), with #194 as the spec. One pass, no subagents; merge-blockers only.

Standards

No merge-blocking method or YAGNI findings.

Spec

  1. [P1 · intent] Keep the pending attempt when authentication prevents replay. commands.ts:334–338

    feat(patches): patchy publish replaces upload, with a manifest and a version record for every tier #194 requires the attempt to be “cleared after the response is applied.” Every RejectedError instead deletes it, including a 401. If the first create commits but its reply is lost, an invalid/revoked credential on the next invocation erases the only recovery key. After signing in again, publishing creates another patch. Authentication runs before replay lookup, so this refusal cannot establish the original attempt's outcome. Preserve the attempt on authentication failures; distinguish them from refusals that actually settle publication.

  2. [P1 · intent] Bind recovery to the original owning user. State.ts:66–71, commands.ts:325–330

    feat(patches): patchy publish replaces upload, with a manifest and a version record for every tier #194 specifies “replay lookup by user and publish key.” The saved attempt remembers only the instance, request and file; replay uses whichever credential resolves today. After a lost reply, switching accounts and publishing a different file sends the original HTML with the new user's bearer. The server correctly treats that user/key pair as a new create, potentially publishing company A's content into company B. Persist the original owner identity and refuse cross-user recovery without deleting the attempt; allow replacement tokens belonging to that same owner.

  3. [P1 · intent] Serialize access to the per-instance pending attempt. State.ts:385–387

    feat(patches): patchy publish replaces upload, with a manifest and a version record for every tier #194 requires “the whole attempt … persisted … before the call” and cleared only after applying its response. Two CLI processes can both read no pending attempt, then overwrite the same attempt.json. A's successful response subsequently deletes B's saved attempt while B remains in flight. If B loses its reply, retrying creates a duplicate. Atomic rename prevents partial JSON, not this ownership race. Serialize the entire read/persist/send/apply/clear section per instance, or reject a competing invocation; one invocation must never overwrite or clear another's unresolved attempt.

Verification

Exercised the source CLI with a loopback HTTP stub and disposable state:

  • Lost reply → 401 → valid-token retry: pending attempt removed; two creates.
  • Lost reply → different user publishing another file: original HTML and key sent under the new bearer.
  • Concurrent A/B → A succeeds → B loses reply → retry B: B's attempt removed; three creates for two intended publications.

These reproduce CLI behavior, not live-server E2E. No source files changed; temporary state and probe removed.

Summary: Standards: 0 blockers. Spec: 3 blockers; worst is replay publishing saved content under a different user/company.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review — PR 210 vs issue #194

Reviewed along two axes (Standards, Spec) plus method, YAGNI, and replay-safety, because #194's job is a prefactor: one publish verb, a version record that can carry every later tier, and a lost acknowledgement that must not mint a second version.

Intent match. The ticket asked for file-mode POST /api/publish + patchy publish, a full Manifest schema that later tickets can implement against, empty tables/files/uses only, replay-by-(owner, publishKey), GET /api/release, CLI persist-and-resent, and 0003_patches_baseline rewritten in place. That is what landed. Repo mode, --name, name/address, provisioning, and has_primitives are correctly left for later tickets. upload is gone, not aliased.


Standards

packages/patches/src/PatchesApi.ts (live + replay success bodies) — ADR-0002 §Decision.1; CLAUDE.md wire contract. Success answers are HttpServerResponse.text(canonicalJson(...)), not PublishCreated/PublishUpdated encoded through @patchy/api. ADR-0002: every /api/* body is encoded through the schema; store that encoding and return it on both the first response and the replay. Sorting keys for request digest identity (unknown fields included) is fine and separate.

packages/patches/src/Patches.ts (PublishKeyTaken) — effect-service-conventions, errors. New empty TaggedError whose message is a constant. At the insert-conflict site the module already has input.publishKey (and owner). Same shape as PatchQuotaReached / PendingObjectExpired: structured attributes, message derived from them.

packages/patches/src/Content.ts (PendingObjectExpired → StoreUnavailable) — effect-service-conventions, pass-through. A known Patches error with objectKey is rewritten as StoreUnavailable({ operation: "put" }) after a successful put. The HTTP handler then Effect.dies on StoreUnavailable, so an untyped defect chooses 500. Put PendingObjectExpired on Content.publish's error channel and map (or die) that tag at the handler.

Vocabulary (patches CONTEXT.md). Avoid upload. Left in hunks this PR edited: Server.test.ts (“one upload”), schemas.test.ts (“upload request”), Content.test.ts / PatchesApi.test.ts helpers still named upload that call publish.

UI (packages/serving/src/render.ts). Copy-only. No UI consistency findings.

CLI / ADR-0004 shape. Pending persist, replay-before-file/release, --json wire success, code on failure, local release_mismatch look aligned. The 4xx-clearing behaviour is a spec/correctness issue, not a formatting one.

Smell (judgement): afterRace in PatchesApi.ts does not say it re-looks up after a concurrent commit.


Spec

Core contract is present: POST /api/publish replaces uploads; Manifest / PublishRequest / 201+200; GET /api/release; replay-before-limits; baseline rewrite; patchy publish (no upload alias); skill lock hash matches; glossary; packed e2e asserts tier=0, release, wire_version. Tests cover same-key replay after a release change, 409, tier_mismatch, and non-empty tables/files/uses as invalid_manifest.

(a) Missing or partial

None against ticket 194. name/address correctly deferred (“arrive with ticket 2”). --new is extra vs the listed publish <file> [--share] [--patch] signature but is existing create-or-update UX.

(b) Not asked for

Pending-object machinery. Ticket: “tier and content checks → the existing create-or-update path.” Diff adds pending_patch_objects, a 5-minute lease, unique object_key, and rewrites ExpirySweep instead of put-then-row with immediate rollback.

Extra version column. Spec §8 lists publish_response (JSON) so replay is verbatim; publish_status is additional (needed for 200 vs 201).

Config surface. PATCHY_RELEASE, PATCHY_MANIFEST_VERSION, PATCHY_WIRE_VERSION, PATCHY_PACKAGE_INTEGRITY are not in the ticket (GET /api/release only).

Wire leftover. Spec §8 success body has no title; it is still on PublishCreated/PublishUpdated.

(c) Implemented but wrong

Refused bytes are no longer rolled back immediately. Old path deleted the object on PatchUnavailable/PatchConflict. New path leaves an intent until lease/sweep. Spec §8: “Before the bytes: nothing happened. Company transaction fails: nothing happened, the object is swept.” Sweep eventually happens; it is not the existing path.

Replay is not the stored JSON bytes. Ticket: “same digest: the stored response verbatim.” Handler stores encodePublishResponse JSONB, then answers canonicalJson of the live object (and again on read). Tests compare first vs replay text, so it is equivalent if encode and live object match — not a byte-for-byte stored body.


Method

The model is the right smallest one for the real constraint (one version per attempt; a lost 201 must not mint another).

Storing the success body on the version row, unique on (owner_user_id, publish_key), ON CONFLICT DO NOTHING, then re-lookup, is better than HTTP idempotency-key middleware (which would freeze 422s), client-only retry (duplicates versions), or a pending-publication table (a second copy of the version). Reconstructing the wire from columns would couple replay to every future PublishUpdated field; the blob does not.

afterRace is correct for the races the ticket named: unique violation, quota, conflict, plus rate-limit and SqlError. Lookup runs before limits and release, so a stored success is not re-validated after an upgrade. Validation/InvalidHtml/tier_mismatch skip afterRace; same digest cannot both succeed and fail those checks.

wireVersion is stamped from config, never trusted from the client. Digest is contentHash(canonicalJson(raw body)) — unknown fields count, key order does not. Metadata-only change is 409. That is the right identity.

CLI persist-whole-attempt, resent first, clear after cache apply, keep on 5xx / failed cache write: smallest durable recovery, and the tests for lost 201 after a release change and failed cache write are the ones that matter.

The pending-object table is the heavier half. The old comment in Content.ts was already the constraint (“a referenced object that vanished costs the reader the page”). Extending that to a durable intent + claim/complete + unique object_key is a real design, not a wrong one. It is more machinery than “rollback on known refusal, keep on uncertain SqlError,” which is what #194’s “existing create-or-update path” pointed at.


YAGNI

Beautiful and small:

  • Replay-first, stored body/status, ON CONFLICT DO NOTHING then re-lookup.
  • One emptiness check for tables/files/uses; tier > 0 → tier_mismatch.
  • CLI: persist the whole attempt, resent first, keep on unknown outcome.
  • Shared publishFields; baseline rewritten in place; releaseLayer is a handful of lines.
  • Empty provisioned / unused as { tables, columns, indexes, stores } — that is spec §8’s shape, not dead weight. Later tickets fill the arrays.
  • GET /api/release pointing at /sdk/patchy-${release}.tgz with integrity: null is what the ticket allowed (“package may point at the tarball route ticket 10 builds”).

Heavier than this ticket needs:

  • pending_patch_objects.claimed, PENDING_OBJECT_LEASE, claimObjects/completeObject/PendingObjectExpired, unique patch_versions(object_key). The lease already fences record vs sweep; claimed and the object-key unique index (keys are already ver_*) are extra. If the durable-intent path stays, claimed is the part I would still drop.
  • PATCHY_MANIFEST_VERSION, PATCHY_WIRE_VERSION, PATCHY_PACKAGE_INTEGRITY. Replay-after-upgrade tests only need PATCHY_RELEASE. Stamp MANIFEST_VERSION / WIRE_VERSION; integrity: null.
  • FileStoreDefinition = Schema.Record(String, Never) — a non-empty files map fails schema as generic “Invalid manifest.” rather than the admitted “not provisioned yet.” Spec §5’s files() has no fields; Schema.Struct({}) plus the shared emptiness check is the prefactor later tickets can fill. Tables already work that way.

--new and PendingPublish.explicitPatch are existing upload UX, not speculative flags.


Replay-safety

Server invariant holds for lost 201/200 (including after a release change), digest mismatch → 409, identical concurrent creates (including quota=1), unreferenced-object reclaim, and committed bytes surviving a lost ack.

CLI hole in sendPublish. The comment says only a definitive refusal settles the attempt. The code then forgetPendingPublish on every RejectedError — every decoded 4xx, including rate_limited and 401.

Auth and body-read run before replay. A 401 on the retry never sees the stored success. 429 is not a settled outcome of this key: new attempts consume authenticated-publish / patch-create after lookup misses and before record. Window: persist, put (up to 60s), lookup still misses, a second publish (the recovery the CLI is built for) gets 429, drops key K, the original then commits. Next publish mints a new key → second version. Default 20/min makes this a boundary; PATCHY_AUTHENTICATED_PUBLISH_RATE_LIMIT_PER_MINUTE=1 (or a spent create bucket, or overlapping agent retries) makes it easy. Untested.

Clear only payload-definitive refusals (publish_key_conflict, invalid_manifest, tier_mismatch, release_mismatch, malformed 400, 413, 404 on an update). Keep the attempt on 401/429 the same way 5xx is kept.


Surfaces (#194 + hit-every-surface)

Hit: wire (packages/api → handler → CLI --json → docs/API.md), CLI README + ADR-0004 + skills/patchy/SKILL.md with matching skills-lock.json, all three migrator call sites on the rewritten baseline, Patches glossary (Publish contract, Manifest, Publish key, Bundle), packed e2e, seed-dev, patchy-dev-loop skill, docs/DEVELOPMENT.md, docs/product.md, ADR-0002.

Leftover upload as product language in files this PR already touched (examples/plan.html still says “Every upload…”, docs/product.md “single HTML upload”, docs/DEVELOPMENT.md “uploaded HTML”). Tests/fixtures named upload/uploader are noise, not a contract miss. No inspect-only view of a pending publish on status --json; persist/resent/clear is otherwise a closed loop.


Summary

  • Standards: 3 documented findings (worst: success bodies not schema-encoded, ADR-0002); 1 judgement smell (afterRace).
  • Spec: 0 missing requirements; 4 unasked pieces (worst: pending_patch_objects replacing the existing put/rollback path); 2 “implemented but not as specified” (worst: replay is re-canonicalised, not the stored bytes).
  • Method: right model. Stored success blob + unique owner key is the unsurprising one.
  • YAGNI: core publish path is small; pending-object claim/complete and extra version env knobs are the fat.
  • Replay-safety: server holds; CLI clearing pending on 429/401 can still mint a second version.

I would keep the stored-response design and the CLI persist-and-resent. I would fix the 4xx-clear before merge, encode the success body through the schema (and return that on replay), and treat pending_patch_objects.claimed / extra PATCHY_* knobs as optional slimming, not blockers.

@allisonmahmood

allisonmahmood commented Sep 10, 2026 •

Copy link
Copy Markdown
Owner Author

Addressed both review comments in f71264f, with the concurrency model corrected in 2282a57 (fix(cli): coordinate publishing through persisted attempts). My earlier justification for the native advisory lock and prebuild packaging was wrong: the persisted attempt supplies the coordination this CLI needs. Formal reviews and inline review comments remain empty.

Fixed

  • 401/403, throttling, quota and unknown refusals no longer erase recovery. The publish client retains the actual HTTP status before decoding. Only decoded, payload-definitive validation/conflict refusals and an update-only 404 clear the attempt; authentication/admission failures and unknown outcomes retain it. The existing update-404 --new guidance remains usable rather than stranding a deleted target forever.
  • Recovery is bound to the original owner. The saved attempt includes the authenticated user ID. The current credential must authenticate that same user before any saved HTML is sent. Replacement tokens work; another account or an ownerless old record fails closed and preserves the attempt.
  • Concurrent invocations share the persisted attempt. State.lockPublish(apiUrl, candidate) schema-encodes and creates attempt.json with exclusive wx. If it already exists, it returns that saved attempt instead of overwriting it. Both invocations send the same request/key; server replay is idempotent. The owner check applies to the selected attempt even after losing exclusive creation. Success and definitive-refusal cleanup check the saved publish key against the key sent. There is no separate lock file, native addon, or stale-PID recovery.
  • Invalid local requests cannot strand recovery. Pending state is schema-encoded before writing it. A malformed --patch leaves no attempt and a corrected invocation can proceed.
  • Success replies now come from the schema-encoded stored response. Create/update use their API schemas before persistence. Both first response and replay return PostgreSQL's publish_response::text and saved status, not a separately reconstructed object. JSONB does not preserve source whitespace; its persisted text representation is now what is sent in both cases. Historical replay bypasses today's schema, including missing current fields and unknown historical fields.
  • Structured errors stay structured. PublishKeyTaken carries owner and bounded key-length context without logging arbitrary client key text. PendingObjectExpired passes through Content.publish and is handled explicitly at the HTTP handler rather than masquerading as a failed object put.
  • Removed the extra manifest/wire/integrity environment knobs. Manifest and wire stamps use the API constants; package integrity stays null until the artifact-serving ticket supplies a real hash. PATCHY_RELEASE remains for the instance release and upgrade scenarios.
  • Terminology and helper clarity. Updated the cited docs/example/test descriptions and publish helpers, renamed afterRace to replayOrRespond, documented owner-safe shared-attempt recovery, and refreshed the public skill hash.

Kept, with reasons

  • Durable pending-object cleanup, its claimed flag, and the object-key index. Spec SDK: primitives, integrations, init and the dev loop on tier 1 #193 §8 explicitly requires failed objects to be swept. Immediate rollback alone cannot safely reclaim a write whose reply failed or a transaction whose commit result is unknown. The existing regressions prove reclamation, retry after deletion failure, and preservation of committed/in-flight bytes. The claimed flag fences a transaction using a pre-wait clock value after sweeping has begun; the index supports the reference check and enforces one version per object key. These are correctness mechanisms, not an optional cleanup framework.
  • Stored HTTP status and JSONB. Status preserves the original 201 versus 200 without reconstructing it from today's metadata. JSONB is explicitly required by feat(patches): patchy publish replaces upload, with a manifest and a version record for every tier #194; no second response-body column was added.
  • title and --new. Both retain existing file-publishing behavior, rather than adding speculative SDK surface. Human-readable names/addresses and repo mode remain deferred as specified.
  • FileStoreDefinition = Record(String, Never). An empty definition is valid: files: { avatars: {} } passes manifest decoding and reaches the required invalid_manifest / not-provisioned refusal. The claim that every nonempty files map fails decoding is incorrect. Fields inside an individual definition are correctly rejected because §5 defines none yet.
  • Fixture identities and no new pending-inspection command. Names such as uploader are test identity data, not a surviving upload command. A new status/discard surface was not requested; the state file and recovery behavior are documented, and an unknown outcome is not silently discarded.

Verification

  • pnpm lint and pnpm typecheck: passed.
  • pnpm format:check: passed.
  • pnpm test: 358 tests passed across 38 files.
  • pnpm test:packed-cli-e2e: passed against the real server and disposable Postgres, using offline installation with an empty npm cache and install scripts disabled.
  • Spawned-CLI regressions cover lost replies followed by 401/429/quota refusals, cross-account non-disclosure, same-owner token rotation, concurrent exclusive creation and exact-request replay, different-owner creation losers, delayed-response key checks, and SIGKILL recovery. Real-Postgres tests cover stored response bytes and historical schema-independent replay.
  • The example's corrected publish copy was visually checked in Chromium.

Packaging correction

CI on f71264f exposed a real packaging defect: clerk-live failed before its browser tests while installing the packed CLI offline. Commit 74e18ea bundles the native addon’s JavaScript loader and platform prebuilds into dist/native, without a registry runtime dependency. The existing packed e2e now installs with both --offline and an empty npm cache, preserving the browser fixture’s constraint. That complete real-server flow, lint, typecheck and formatting pass locally.

Final CI: all six required checks passed on latest head 74e18ead3df87433e57147edf7a0b68ac26fcc3d: dependency-review, lint, test (22), test (24), cli-smoke, and clerk-live. CI run. GitHub reports MERGEABLE and CLEAN. Rechecked PR comments, formal reviews and inline review comments after the checks completed; there is no new feedback. No merge has been performed.

@allisonmahmood
allisonmahmood merged commit 2c1624f into main Sep 12, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the sdk/194-publish branch September 12, 2026 11:31
allisonmahmood added a commit that referenced this pull request Sep 12, 2026
Patches still used opaque `/d/<id>` links. Every patch now has a
company-scoped name and a readable address, without changing who can
open it or how tier-0 pages render.

Publishing assigns names atomically, preserves them on file updates, and
supports explicit renames with `--name`. Old names redirect until
reclaimed; deletion frees them. Address, version and internal content
routes preserve the existing door and cache rules, and `/d/*` now
returns 404. The wire contract, seed backfill, CLI, docs and public
skill are updated together.

**Stacked on #210 (`sdk/194-publish`, issue #194).** This PR builds on
its existing `publish` flow and must land after it.

Closes #195.

## Verification
- 361 tests across 38 files; typecheck, lint, build and formatting
passed.
- Packed CLI end-to-end flow and isolated real-server/browser checks
passed.
- Standards and spec reviews completed. The opposing-rename deadlock was
reproduced on PostgreSQL, fixed and covered by a regression test.

Implemented with 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: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

Development

Successfully merging this pull request may close these issues.

feat(patches): patchy publish replaces upload, with a manifest and a version record for every tier

1 participant