Skip to content

feat(primitives): add persistent files to patches - #215

Merged
allisonmahmood merged 4 commits into
mainfrom
sdk/199-files
Sep 12, 2026
Merged

allisonmahmood merged 4 commits into
mainfrom
sdk/199-files

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Patches can persist table rows, but cannot yet store named files independently of published versions.

Extend the existing additive provisioning path with file stores and add put/get/list/delete operations. Immutable objects and serialized index updates preserve previous files on failed writes; authenticated byte routes enforce size limits and no-store responses. Omitting a store or cleaning up a version keeps its files intact.

Stacked on #214 (sdk/198-tables). This PR targets that branch and should merge after it.

Closes #199.

Verification

  • Full offline suite: 477 tests passed; post-review focused checks: 108 tests passed.
  • Typecheck, lint, and formatting passed.
  • Real-server smoke covered a 20 MiB binary round-trip, overflow refusal, authorization, retention, and logging.
  • Independent standards and spec reviews have no remaining findings.

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: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 origin/sdk/198-tables...HEAD at ac146714a998912bdc083b99e9715e2aa43f3640 against #199 and its linked SDK spec. One pass, no subagents; merge blockers only.

Standards

No independent merge-blocking standards or YAGNI findings.

Spec

Blocker — intent/method: keep file operations usable over the PGlite adapter

packages/primitives/src/Files.ts:108–115 captures a platform SQL client and queries patches for every operation through withStore. The existing PGlite adapter supplies the company inventory, not the platform's patches table. Consequently, stores provision locally but their file operations cannot run using the same capability implementation.

This breaks the parent SDK spec #193, §2: “the dev runtime can compose the same services over PGlite without importing the server,” and its test strategy: “the same suites run once more over the PGlite layer for the dev runtime.” Unlike the existing table-operation contract, the new file-operation tests exercise only Postgres; the PGlite provisioning test does not catch this dependency.

Reproduced: composed the existing PgliteCompanyDatabases, Tables, and filesystem content-store implementations in a disposable directory. Provisioning files: { docs: {} } succeeded. Constructing Files.make inside the company SQL context and calling files.list({ store: "docs" }) returned source_unavailable, caused by relation "patches" does not exist.

Required change: keep platform-only liveness/locking coordination outside the reusable file capability, preserving production lock order, and exercise the file-operation contract over both adapters. Do not make local files require a replica of the cloud platform schema.

Verification

92 tests passed across nine focused suites covering file operations, raw HTTP, provisioning, publishing/retention, runtime dispatch, and both content-store adapters. The separate PGlite probe reproduced the blocker above; its temporary state was scoped and removed.

Summary: Standards: 0 blockers; Spec: 1 blocker — file operations require platform persistence and fail over the required local adapter.

@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.

Code review (PR 215 × issue #199)

Nine parallel reviews: Standards, Spec, Effect conventions, YAGNI, implementation method, hit-every-surface, done-when tests, runtime bytes path, and issue intent. Diff is origin/sdk/198-tables...HEAD (3 commits).


Standards

Effect services (.agents/skills/effect-service-conventions/SKILL.md): no findings. Files.make without a Context.Service tag matches TableOperations.make: a one-consumer handler module wired in Server.ts into Runtime.layer. A Files tag consumed by Runtime would cycle packages. Skill: “A capability with one consumer stays a module.” Tables is the wrong analog (multi-consumer provisioner). catchTags, tagged errors, and message getters follow the error rules.

ADR-0009 lock order is correct (Files.ts 118–157): platform FOR UPDATE, then withCompany / withPatchLock. Primitive-free publish still skips this path.

Hard — inventory writes skip the patch-id guard. ADR-0009: inventory (including the file index) must “reject a mismatched patch id before writing.” Inventory.lockedClient and Tables.provision both check lock.patchId. Files INSERT/DELETE/SELECT (Files.ts 170–288) use PatchLock.sql and binding.patchId with no lock.patchId check. withStore happens to match today. Fix: assert PatchLock.patchId (or file-index helpers on Inventory) before index writes.

Holding both locks across putBytes/getBytes (20 MiB) is a judgement call, not an ADR breach; sweep already holds them through delete.

Fowler (judgement only)

  • Feature Envy — bounded-rows.ts 7–15: still decodes TableRow; Files.list re-decodes FileMetadata. Decode unknown JSON objects (or take a row schema).
  • Duplicated Code — AzureContentStore.ts 43–46 and FilesystemContentStore.ts 64–67: identical TextEncoder/TextDecoder put/get wrappers. One helper on ContentStore is enough.

Busy/InvalidCursor copies vs TableOperations are not duplication: distinct tags are required. Tables also provisioning stores is Divergent Change, suppressed by YAGNI (existing additive provisioner). Shotgun-looking doc edits are Hit every surface, not a smell.

No UI consistency findings. ADR-0004 does not apply.


Spec

Quoted against issue #199.

(a) Missing / partial

Done-when “Fetching with a session that cannot open the patch is refused”: shared Runtime.dispatch maps wrong-company viewers to access_denied, but FilesApi.test.ts never uses a signed-in viewer who cannot open. It covers empty cookie (session_expired), public (not_available_on_public), bad Origin / Sec-Fetch-Site, and principal_changed.

files.delete logging of store/name is wired (Files.ts resource) but only files.put is HTTP-asserted.

SDK url(name) / envelope ArrayBuffer / unnamed-object sweep correctly deferred (tickets 12 / 3).

(b) Not asked

  • ContentStore.putBytes/getBytes; Azure/FS blobs stored as application/octet-stream (needed for binary; also changes HTML object metadata).
  • GET adds Content-Disposition: attachment and X-Content-Type-Options: nosniff (helps “HTML and SVG remain bytes, never a navigable page,” not in the ticket).
  • File list 8 MiB / 100–1000 caps (tables bounds, not §5).
  • GET/list/delete take platform FOR UPDATE + company advisory lock (table ops only withCompany).

(c) Looks implemented, looks wrong

Spec: “put writes a new object then upserts the row under per-name serialisation.” withStore holds a patch-wide advisory lock (and the platform row) across the content-store write/read, not a per-name upsert lock after a lock-free put. Concurrent-name tests pass because of this coarser lock.

Files is make() returning handlers (like TableOperations), not a Context.Service. That matches the ticket’s “Files in packages/primitives.”

Done-when vs tests

Item Verdict
Store provisions on publish Yes
Omitted store reported; bytes stay Yes
20 MiB put/get; +1 too_large Yes (handler test; HTTP overflow is 1 KiB)
Concurrent puts: one matching object Yes
put vs delete: no dangling row Yes
.. → invalid_request Yes
list by prefix + cursor Yes (handlers, not HTTP)
delete twice Yes
cannot-open session refused Code yes; files HTTP test no
no-store Yes
mutations log store/name put HTTP yes; delete untested
rollback/version cleanup never touch files Yes — Content.test.ts

Admission: PUT requires exact Origin; GET requires Sec-Fetch-Site: same-origin; both require wire and principal headers. Covered. JSON files.put/files.get refused.

Surfaces named by the ticket (wire, File store, docs/product.md § Files) are present.


Intent vs #199

Intent. Give a patch a named, version-independent file home so internal tools can put/get/list/delete files for company viewers — not a bucket, not a public URL.

Shipped. Server-side stores: inventory row, immutable content-store objects, company-DB index, four runtime ops plus authorised bytes GET/PUT, additive publish. No SDK client.

That is the right slice for this ticket (Admitted at merge: Manifests with files). Ticket 12 owns url() / ArrayBuffer; ticket 3 owns the sweep. Product.md is honest about the deferrals (“Frame-local blob URLs and ArrayBuffer transfer arrive with the browser broker”).

It reads more like an object-store contract than a builder primitive, because §5 specified that contract and this PR implemented it. The missing builder surface (url(), patchy client) is out of scope, not a miss.


Method

The data model is the one the spec asked for: reuse the content store, files/<patchId>/<store>/<objectId> never versioned, patchy.files as the pointer, stores as inventory rows through the existing additive diff. No parallel blob store, no signed URLs, nothing under files/ served as a page. Bytes routes share Runtime.dispatch with JSON calls (Origin / Sec-Fetch-Site / session / log). That split is correct; ArrayBuffer-on-envelope stays ticket 12.

Provisioning stores through Tables.diff (newStores) is the right place. A second Files provision path would split the publish lock, revision, and report. The name “Tables” now lies a little; the machine is the right one.

The lock is the method problem. Spec asked per-name serialisation of the pointer. Code takes platform FOR UPDATE then withPatchLock for every file op, then does 20 MiB of blob I/O inside both write transactions (Files.ts 129–177). That does satisfy the race tests (one matching object; put vs delete never dangles). It is stronger than asked: unrelated names serialize; get holds the write lock for the blob read; publish/provision/sweep wait on the same locks. Company statement_timeout does not cover idle-in-transaction Azure I/O.

Smaller method, still correct given immutable object ids:

  1. putBytes outside the lock (unique objectId).
  2. Lock only for the upsert (per-name advisory, or even INSERT ON CONFLICT under the existing patch lock without the blob).
  3. Get: read object_id under lock, getBytes after release. Sweep grace is a day; object ids are never reused.

Failed putBytes before upsert already leaves the previous row. Crash after write, before upsert: unnamed object, old row intact; ticket 3 sweeps it. That failure method is right.


YAGNI

Verdict: mostly small, with extra lock scope.

Keep: immutable object then pointer upsert; Files.make as a handler map; putBytes/getBytes on the content-store port (string put/get were UTF-8 lies); dispatch extraction for shared admission; delayed readFile after log.begin; forEachBodyChunk (a stream runner’s inner scope killed the socket before 413); cursor {version, patchId, store, prefix, after} (prefix-binding is a real list invariant); boundedRows extraction (tables list/getMany + files list is a real second consumer); tests mapped to done-when.

Don’t grow: the JsonHandler | BytesPutHandler | BytesGetHandler union is enough for two routes — don’t turn it into a bytes framework. Don’t genericise boundedRows; decode Unknown (or the caller’s row schema) instead of TableRow. InvalidCursor / PageLimit / Busy are earned copies of the tables error model.

Docs churn (CONTEXT-MAP, product, API, ADR-0009, README) is required surface, not noise.


Standards: 1 hard finding (file-index writes skip lock.patchId), 2 judgement smells (bounded-rows typed as TableRow; duplicated encoder wrappers). Worst: the patch-id guard.
Spec: 2 partials (cannot-open HTTP test; delete log untested) and 1 wrong-shape implementation (patch-wide lock across blob I/O vs per-name serialisation). Worst: I/O inside two write transactions.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Addressed both Astra's comment and Grok's review in c00628b (fix(primitives): keep file operations company-local).

Fixed

  • Astra's PGlite blocker / Grok's lock-scope blocker: one defect, fixed together. Files.make no longer acquires a platform SQL client, queries patches, or takes its row lock. Runtime's admitted LoadedVersions binding remains the liveness/authorization authority. Put writes a unique immutable object before acquiring a company lease; only the index operation takes the patch/store/name advisory lock. Get reads its pointer under that lock, releases the transaction and lease, then fetches bytes. List is lease-only; delete changes only the index. Blob I/O cannot hold either database transaction or a company lease.
  • Missing lock identity guard: index access checks lock.patchId, store, and name before SQL. Mismatched-lock put/delete tests prove the existing pointer and bytes remain unchanged.
  • Missing adapter coverage: the same nine file-operation contracts now run over PostgreSQL and PGlite, with no platform schema in the local setup. Deferred blob-I/O tests prove other operations progress while transfers are paused. A PostgreSQL cross-session test observes a genuinely blocked same-name writer while unrelated names and list continue.
  • HTTP coverage gaps: added signed-in wrong-company and unenrolled-viewer refusals, plus canonical files.delete success/idempotency, retained bytes, and attributed store/name logs for both deletes.
  • bounded-rows ownership: it now decodes JSON records directly rather than importing the table-specific wire schema. Callers retain their own result validation; no generic query framework added.
  • Updated ADR-0009, domain/product docs, and agent guidance to distinguish platform-first provisioning/reclamation from company-only file-index operations.

Kept, with reasons

  • The two short UTF-8 wrappers in Azure/Filesystem adapters: no behavioral defect; four explicit lines per adapter keep encoding and backend error handling easy to inspect. Existing binary and UTF-8/BOM tests cover both. A shared adapter-construction helper is unnecessary for this correction.
  • Binary ContentStore methods, inert object metadata, and GET attachment/nosniff headers: needed to preserve arbitrary bytes and prevent active HTML/SVG from becoming navigable content.
  • File-list byte/count bounds: the 8 MiB result cap follows parent spec §12; bounded pagination prevents unbounded metadata work. The shared bounds remain tested on both adapters.
  • Existing Tables additive provisioner and Files handler-map module: reuse the established provisioning/runtime seams rather than adding a second provisioner or service cycle. SDK blob URLs/ArrayBuffer transport remain outside feat(primitives): file stores #199; the existing immutable-object grace-period sweep is unchanged.

Verification on this commit

  • Focused Files + FilesApi: 22 passed.
  • Full offline suite: 492 passed across 50 files.
  • Typecheck: 29 tasks passed; lint and formatting passed.
  • CI run 34519599280 completed successfully for the exact commit above: test (22), test (24), lint/typecheck/format, cli-smoke, clerk-live, dependency-review. The separate label check also passed.
  • GitHub reports MERGEABLE / CLEAN against sdk/198-tables. GitHub reports no configured required checks for this stacked PR; all seven available checks are successful. No newer review findings appeared after the push.

No unresolved code or CI blockers. This remains stacked on #214; I have not merged it.

@allisonmahmood
allisonmahmood merged commit 879b2d7 into main Sep 12, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the sdk/199-files branch September 12, 2026 11:53
allisonmahmood added a commit that referenced this pull request Sep 12, 2026
Patches can own tables, but cannot yet read another patch's shared data
without copying it.

Admit shared-table declarations and resolve them to stable source
identities. Shared reads reuse the source's inventory definitions and
indexes, checking access and sharing on every call. Publishing warns
about older schema stamps, refuses unavailable sources, and reports
affected consumers when a table is unshared. Omitting a table or rolling
back its source does not change sharing, and deleting/recreating a patch
never rebinds consumers.

**Stacked on #215 (`sdk/199-files`).** This PR targets that branch and
should merge after it.

Closes #200.

### Verification
- Full offline suite: 498 tests passed across 50 files; post-review
focused suites: 127 tests passed.
- Typecheck, lint, and formatting passed.
- Actual PGlite smoke covered indexed pagination, ordered dangling IDs,
source omission, unshare denial, rollback immunity, preserved consumer
rows, and stable source identity.
- Standards and Spec reviews completed; all three findings addressed,
including CLI refusal recovery and the file-mode inventory guard.

Implemented with GPT-6 Astra in Oh My Pi.
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(primitives): file stores

1 participant