From a40d74e38171e842b37d9b1616488f515e1fbf83 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 06:58:15 -0600 Subject: [PATCH 1/5] docs(fleet-kv): reconciled sole design prose + human-review for #10359 Compat: threshold subordinate to shared partition policy (#9084 16KiB), Part A preserved, hosted data-plane refusal, F12.5 not-this-surface, Turso embedded-replica vs Sync distinguished, fixture figures labelled. --- .../2026-11-23T12-45-00Z_design_fleet_kv.md | 191 ++++++++++++++++++ .../human-review.md | 45 +++++ 2 files changed, 236 insertions(+) create mode 100644 doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md create mode 100644 doc/2026-11-23T12-45-00Z_design_fleet_kv/human-review.md diff --git a/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md new file mode 100644 index 0000000000..fb6714543b --- /dev/null +++ b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md @@ -0,0 +1,191 @@ +# Design: `fleet kv` — namespaced key-value store (local + global), blob offload to content-addressed R2 + +- Status: draft (agent-preliminary; no human confirmation claimed) +- Date: 2026-11-23T12:45:00Z +- Roadmap item: none +- Issues: https://github.com/developing-today/code/issues/10359 (design owner), https://github.com/developing-today/code/issues/9107 (ID core epic: namespaces/ID shapes), https://github.com/developing-today/code/issues/9120 (content-addressed namespace core), https://github.com/developing-today/code/issues/9084 (content-addressed media/data plane), tracking https://github.com/developing-today/code/issues/12892 +- Standalone design: there is no workflow research package for this item (no S0–S5 intake/lease state exists); this record is the decision record #10359 acceptance asks for, adapted honestly to that fact. + +## Intent + +Drew (2026-11-14, #10359) asked for a `fleet kv get/set/list` verb family in the `fleet` multicall binary for arbitrary bytes, explicitly not the secrets store. Each host has a local store (backed up); there is also a central store. Reads resolve local first and fall back to global; a local value overrides the same key in global. An explicit global operation (`fleet kv --global …`, exact surface TBD) always addresses central. Keys live in namespaces; a "global namespace" is a namespace designated global, not a second mechanism. Namespaces map to the ID project's namespace concept (#9107 / #9120), not a fleet-private reinvention. A session's local partition must survive disconnect: a sweeper pushes it into the central store keyed under the owning user id (+ context id). Every fleet-launched session — and other partitions (a repo, the fleet project itself, the mcpx namespace) — can be handed its own small database, likely Turso, with the embedded-replica attraction (fast local reads, automatic sync). The design must answer, with a workload sketch, what five agents concurrently pulling (and writing) a shared mid-size namespace actually get: replica sync semantics, writer topology, conflict behaviour — stated, not assumed. Values are arbitrary bytes; above a configurable threshold (Drew named 250 KB / 500 KB / 1 MB / 1 GB as the knob shape), a push keeps bytes local-working but routes them on central sync through a trusted Cloudflare endpoint into the content-addressed R2 bucket, storing key/namespace/name plus content hash + bucket link (#9084's reference pattern). Later, lists and tables ride the same substrate — design the KV layer so they are additive. + +Today nothing of this exists: fresh greps find no `fleet kv` surface in the fleet crates (`pkgs/fleet/crates/`, command reference `pkgs/fleet/docs/verbs.md`) and no fleet-kv design under `doc/` (confirmed by the 2026-11-17 triage note on #10359). The fleet pieces that do exist and bound this design: the multicall/registry surface (`pkgs/fleet/docs/verbs.md`, `pkgs/fleet/crates/fleet-registry`), broker-token credential resolution by name (`pkgs/fleet/docs/fleet-gh-credentials.md`, `pkgs/fleet/crates/fleet-secrets/src/lib.rs:1-46`, `pkgs/fleet/crates/fleet/src/gh.rs:497-502`), the single front door for agents (`doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md`), and Turso-backed queue state over the libSQL HTTP pipeline (`pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs:1-81,532-770`). + +## Design + +### D-anchored summary + +Local stores are plain per-host SQLite files (WAL) in v1 (D001). The central store is one Turso-hosted libSQL database (the fleet-kv primary), addressed over the same HTTP pipeline pattern the queue already uses — not a per-session Turso DB and not libSQL embedded replicas in v1 (D002). Namespaces are a small registry table whose global flag is designation only, and whose content-blob identity reuses the settled #9120 profile byte-for-byte (D003, D010). Reads are local-first with local-override; `--global` pins central; deletes are tombstones with revert (D004, D005). Disconnect sweep is an explicit, idempotent, CAS-guarded merge keyed under `(owner_user_id, context_id, session_id)` (D006, D007). The five-agent shared-namespace answer is single-writer-per-key by CAS against the central primary, short-TTL reads, and no offline fork in v1 (D008). Blobs cross a per-namespace threshold (default 256 KiB, agent-preliminary) with a per-push override flag; large bytes go staged → verified → published through the trusted Cloudflare endpoint and are stored as references, never bearer hashes (D009–D012). Lists/tables are typed compositions over keys, additive (D013). + +### 1. Store layout + +```text +host local (SQLite file, WAL) central (Turso libSQL primary) ++----------------------------+ +----------------------------------+ +| kv_local | | kv_namespaces | +| (ns, key, value|ref, ver, | sweep | (ns, global_flag, threshold, | +| tombstone, origin, ts) | ---------> | policy_epoch, owner_scope) | +| kv_namespaces (cache copy) | CAS merge | kv_central | +| outbox (sweep/upload queue) | | (ns, key, value|ref, ver, | +| backup manifest | | tombstone, owner, ctx, ts) | ++----------------------------+ | kv_blobs (references only) | + ^ file backup | (content_id, bytes_len, locator, | + | (snapshot + WAL, §7) | partition, state) | + +----------------------------------+ + | staged → verified → published + v object plane (R2/RustFS adapter) +``` + +Tables above are logical names for the phased build issues, not a claim that schema already exists. No `fleet kv` schema exists on main today. + +**Local (D001).** One SQLite file per host, e.g. `~/.local/share/fleet/kv/local.db`, WAL mode, with `kv_local`, a cached copy of `kv_namespaces`, and a durable `outbox` for sweep/upload work. Rationale: the local store must accept writes while offline, survive process death, and back up as a file — plain SQLite does all three with zero network dependency. Two Turso products are distinguished and neither is the v1 path: (a) legacy embedded replicas — reads local, default writes remote to the cloud primary then reflected back, explicit `sync()` pulls, per-writing-replica read-your-writes (https://docs.turso.tech/features/embedded-replicas/introduction; docs now recommend new Turso Sync for new projects); (b) new Turso Sync — local-first writes with explicit `push()`/`pull()`, logical CDC, and last-push-wins on conflict (https://docs.turso.tech/sync/usage, https://docs.turso.tech/sync/conflict-resolution) — which collides with the CAS-per-key rule §5 requires. So: SQLite locally in v1 with a conservative outbox + central transaction sequencer; revisit embedded replicas or Turso Sync only as a named follow-up with a convergence proof, not as the v1 path. Do not conflate the two products/APIs or assume automatic multi-master CAS. + +**Central (D002).** One fleet-kv Turso database as the libSQL primary for KV rows and blob *references*; bytes live in the object plane (§6). Clients that need central access use the same transport shape the queue already proves: libSQL HTTP pipeline from Rust (`pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs:81,671-770`, `DEFAULT_TURSO_URL` at `core.rs:10` shows the pattern, not the kv database). Central writes serialize per key on the primary's transactions (conservative outbox + central transaction sequencer, §5); this design assumes no automatic multi-master CAS from any sync product. Per-user Turso DB credentials (component-E data-plane tokens) are not service authentication and are refused at the hosted front door by rule (`pkgs/fleet/hosted-worker/src/auth.ts:20-33,134-159` `data_plane_credential_refused`); central KV access goes through the broker/pipeline path, never by presenting a data-plane token. Per-group "small databases" from the issue (one per session/repo/project/mcpx namespace) are a provisioning option *behind* this primary — either separate Turso DBs reached over the same pipeline, or row-partitioned scopes inside the one primary — but they are not separate sync topologies in v1. The v1 topology is exactly: many SQLite locals → one central primary → one object plane. + +**Backup/restore (§7, D001 detail).** The local file is backed up as a file: periodic SQLite backup API or filesystem snapshot of file + WAL, plus a `backup manifest` row (host, file hash, WAL frame, timestamp) kept in the outbox so restore can prove which snapshot it holds. Restore is: fetch latest snapshot, open read-only to verify, then either adopt (fresh host) or three-way merge through the §5 sweep path (returning host with divergent local rows). Backup never writes bytes into the KV row space; large local working bytes above threshold stay local-working until §6 publishes them. + +### 2. Namespaces (coordinate with #9107 / #9116, not parallel) + +Namespaces reuse the ID local-namespace-registry concept: a namespace definition binds `{namespace_id, core_id, handler/encoding profile, read/write policy, shorthand policy, schema version}`, server-local, versioned and audited (`doc/2026-11-13T03-40-00Z_design_id-atlas-summit/part-a-addressing/versioned-design.md`, §#9116). Fleet-kv does not mint a second namespace grammar: + +- `kv_namespaces` rows carry `(namespace_id, core_binding, global_flag, blob_threshold, policy_epoch, owner_scope)`. +- `global_flag` is designation only (D003): "global namespace" = a namespace whose reads/writes default to central. No second registry, no second lookup path. +- Content-blob identity inside any namespace is exactly the settled #9120 initial profile: unkeyed BLAKE3-256 over exact bytes, 32-byte digest (A-9120.1; research `part-a-addressing/research.md` #9120 row; implementation slices `part-a-addressing/implementation-slices.json` A9120-content-id). Fleet-kv neither redefines the hash nor invents a parallel digest (binding constraint shared with #9120's "neither this spec nor §3's may redefine the hash"). +- Parse/URI transport, if ever exposed as `id://`, follows #9117 syntax transport only; this design mints no IDs and establishes no authority beyond the namespace's own write policy. + +Coordination boundary: #9116 owns the registry model; #9117 owns URI syntax; #9118 owns the array core; #9120 owns the immutable content core. Fleet-kv is a consumer of all four and defines only the KV row envelope, the override/sweep rules, and the blob reference row below. It preserves Part A untouched: no redefinition of the hash, no new core, no parallel namespace grammar. Not this surface: the F12.5 in-world `kv`/`blob` providers (#1062: `kv.get/set/delete` with 8 KiB values / 1024 entries / 64 KiB per world, `doc/2026-11-22_design_id1062-kv-provider.md`) are world-sandbox ceilings, not the fleet CLI store — this design neither implements nor changes them. + +### 3. Read/list/set/delete/tombstone/revert semantics + +Verbs: `fleet kv get|set|list` plus `delete` and `revert` (delete without revert is a half-design; the sweep needs tombstones to converge). `--global` pins central for the verb it modifies; `--namespace NS` selects scope; `--as-bytes-ok` style escape hatches are out of scope for v1. + +- **Read path:** local first; on miss, fall back to global/central. A live local row *overrides* the same key in global (D004). `--global get` skips local entirely. `list` merges both scopes with origin marks (`local|central|both`, local winning display) and never silently hides the shadowed central row — show it as `shadowed-by-local` in verbose output. +- **Set path:** default writes local + enqueues outbox work; `--global set` writes central directly (authenticated; §6 for large values). Local sets carry `(key, namespace, value-or-ref, base_version, writer_session, ts)`. +- **Delete:** writes a tombstone row `(key, namespace, tombstone_epoch, deleter, ts)`, never a physical row removal (D005). Reads treat tombstoned keys as absent but `list --include-tombstones` and `revert` can see them. Tombstones sweep exactly like values (§5), which is what makes two-session delete/write converge instead of resurrecting. +- **Revert:** `fleet kv revert NS KEY --to ` writes a new version whose value equals the named prior version (new version number, full provenance) — history is append-only; there is no in-place rollback. Reverting a tombstone re-lives the key at a new version. +- **Freshness:** local reads are immediate; central reads are bounded-stale only by explicit `sync`/`pull` in v1 (no background sync promise). Whatever freshness knob ships must be a documented flag, not ambient behaviour. + +### 4. Durable session-partition sweep + +A session's local partition does not evaporate at disconnect (D006). On session end (and on explicit `fleet kv sync`), a sweeper merges the session's dirty rows into central under `(owner_user_id, context_id, session_id)` provenance: + +1. Read session dirty set from `outbox` (durable, so a dead session still sweeps on next host run). +2. For each key: `central_CAS(key, expected=base_version, new=row)` against `kv_central`. +3. On success: mark outbox row done. On conflict: run the §5 rule (versioned conflict, never silent last-writer-wins across sessions), record the conflict row, and leave both versions retrievable. +4. Tombstones sweep through the same CAS path. +5. Large values sweep by reference: the sweeper uploads through §6 first, then CASes the reference row. Central never accepts an unpublished blob reference. + +Sweep is idempotent (outbox row ids + CAS make re-runs safe) and recoverable (crash between upload and CAS leaves a staged blob that staging TTL reaps, per #9084 component-F staging rules; crash between CAS and outbox-ack re-runs CAS harmlessly). "Two sessions sweeping the same key" is therefore a routine CAS conflict, not a special case. + +### 5. CAS/versioned conflicts, retry, idempotence, recovery + +Every mutable head uses compare-and-swap on `(key, namespace, version)` (D007), following the #9114 sidecar-head precedent (CAS on prior `(generation, snapshot_id)`; generation increments exactly once). There is no timestamp-only last-writer-wins anywhere in v1: + +- Each row carries `version` (monotonic per key) + `parent_version` + writer identity. A writer that did not read the current version fails CAS with `conflict {key, expected, actual}` and retries by re-reading, re-applying intent, and re-CASing — or surfaces the conflict to the user for genuinely incompatible intents. +- Retries are bounded with jitter and carry idempotency keys (outbox row id = the idempotency key; re-sending the same CAS is a no-op once applied). +- Recovery order is fixed: outbox → upload (§6) → CAS → ack. Any crash restarts at the oldest unacked outbox row. Staged-but-unpublished blobs are never referenced by any read path, so they are safe to reap by TTL. +- `concurrency_unsupported` is a typed error if some future adapter cannot CAS: fail closed, never degrade to silent overwrite (same posture as the V2 store seam in `part-a-addressing/versioned-design.md`). + +### 6. Five agents on one shared mid-size namespace (workload sketch + topology) + +Workload assumed (agent-preliminary planning fixture, stated so a later measurement can replace it — not a measured or free-tier guarantee): namespace holds ~10k–100k small keys (hundreds of bytes to a few KiB each; larger values are references per §8), five agents each holding the namespace open for minutes, read-heavy with intermittent writes (each agent writes ~1–10 keys/min, occasionally the same key family, e.g. status/claim rows). A "five agents × ~100 MiB" shape, where named, is the same kind of planning fixture, not a throughput promise. + +- **Writer topology (D008): single-writer-per-key by CAS against the central primary.** There is no multi-master convergence in v1: all writers serialize per key on `kv_central`'s CAS. The "shared mid-size namespace" is therefore N readers of a locally cached copy plus M writers arbitrated centrally per key — the same shape as the fleet queue's claim path (atomic claim over Turso in `pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs`), not a mesh sync. +- **Replica sync semantics:** no embedded replicas in v1 (D002 rationale). Agents read central directly (short-TTL client cache, TTL documented per namespace) or read a snapshot pulled at task start; there is no background replica convergence to reason about, and therefore no divergence window beyond the stated cache TTL. Offline writes in v1 are local-only and unsynced — they become visible only through the §4 sweep, and conflicts there follow §5. +- **Freshness:** reads state their source (`local|central@version|cache@ttl-expiry`); claim/status keys that need linearizability use `--global` reads + CAS writes. Nothing else gets linearizability, and the CLI says so. +- **Contention:** same-key write contention fails CAS fast; hot keys should be claim/checkpoint-shaped (queue pattern) rather than counter-shaped. No counters in v1 KV rows — a stored counter is a second copy of the truth and drifts (same argument as `doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md` §6 against reference counting). +- **Cost:** central rows are small (values inline only at/below threshold; §8). Five agents polling `list` at 1 Hz against Turso HTTP is the abuse case: mitigate with the documented cache TTL, snapshot reads, and (if needed) a per-namespace read budget owned by the same policy epoch as the threshold. No per-request billing claim is made here — measure on the fleet-kv Turso DB once Phase 2 lands. + +Why not embedded replicas for the five-agent case: embedded-replica writes go to the cloud primary anyway (https://docs.turso.tech/features/embedded-replicas/introduction), so five replica-holders writing the same key still serialize centrally — replicas add a divergence/catch-up window without removing the central serialization point. v1 keeps that serialization explicit and auditable. + +### 7. Host-local technology choice: SQLite vs embedded libSQL/Turso + +D001/D002 decide: **plain SQLite (WAL) per host for local; Turso-hosted libSQL primary for central; no embedded-replica mode in v1.** Backup story: local = file snapshot + WAL + backup-manifest row (§1); central = Turso's own durability plus the tombstoned, versioned row history (point-in-time story is the provider's, not a second log we maintain). Sandbox hosts ("sandbox has their own local store that maybe we back up and merge") get exactly the §4 sweep: their partition merges on session end, and a dead sandbox's outbox merges on next host run — "merge" always means CAS merge, never file copy. + +### 8. Arbitrary bytes, streaming, blob threshold knob + +Values are arbitrary bytes with a streaming interface (no full-buffer requirement on push/pull above a small in-memory cap). The threshold knob (D009): + +- **Per-namespace policy value** (`kv_namespaces.blob_threshold`, bytes), default **256 KiB (agent-preliminary)** — inside Drew's named shape (250 KB / 500 KB / 1 MB / 1 GB) at its low end. This default is subordinate to the shared per-partition placement policy, not a competing protocol: where KV bytes and #9084 component-F content share a partition, component E owns the threshold and the 16 KiB conservative starting default (`doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/...md` §Recommendation) governs placement until #9098 measurements move it. The KV per-namespace knob may only narrow (force-blob sooner), never widen past the partition policy, and changing either changes placement of new content only, never identity or access (policy, never protocol). +- **Per-push override flag** (`--inline-max BYTES` / `--blob-threshold BYTES`, exact flag name owned by Phase 1): both directions supported — force-inline a just-over-threshold value or force-blob a small value that should not live in the row store. +- At or below the effective threshold: bytes inline in the row. Above: §6 reference path. Promotion (inline → referenced) is a new version with identical read semantics; no client-visible change. + +### 9. Trusted Cloudflare endpoint, broker-token auth, reference-based read (no bearer hash) + +Auth reuses the fleet's existing shape, not a new credential (D011): + +- **Push path:** the pusher authenticates to the trusted Cloudflare endpoint with its **existing fleet broker token** (same family as the secrets-broker token file pattern: `fleet-secrets` resolves by name, broker-first; `pkgs/fleet/docs/fleet-gh-credentials.md`, `pkgs/fleet/crates/fleet-secrets/src/lib.rs:15-28`). The endpoint verifies the token, checks the namespace write policy for `(user, context, namespace)`, and only then accepts staged bytes. The content hash travels as an *assertion to be verified*, never as authority. +- **Read path:** a bearer hash grants nothing (binding rule shared with `doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md` §5 "the hash is not a capability"). Readers resolve their KV row authorization first (local or central, per namespace policy + authenticated context), then receive a **short-lived, object+operation-scoped capability** minted from live reference state; the adapter serves bytes only under that capability, with replica fallback during placement movement (same contract as component I's object adapter: `doc/2026-11-21T21-40-00Z_design_self_hosted-tier-adapters/2026-11-21T21-40-00Z_design_self_hosted-tier-adapters.md`, object adapter contract). +- **Upload safety:** `put_staged → verify (length + BLAKE3-256 recomputed on receipt, streaming) → publish`. Partial uploads are staging state, never accepted objects (same invariant as A-9120.1 and component-F staging). Multipart completion is not publication; only the service verification step makes the reference row writable. +- **GC safety:** mark-and-sweep per partition exactly as component F §6 (references are the rows; derived index is a cache; re-verify at grace expiry; epoch-fenced delete; audit event per delete). Fleet-kv blob references are rows in `kv_central`/`kv_blobs`, so they slot into that protocol as one more reference source; per-jurisdiction dedup partitions from #3401 bound every sweep (D012). + +### 10. Per-jurisdiction dedup and reference format (using existing ID hash shapes) + +- Dedup partitions are `(jurisdiction, sensitivity tier)` per #3401, applied inside the object plane per component F §4. Cross-partition "dedup" is prohibited, not a missed saving (existence leak). Fleet-kv rows carry the partition on the blob reference; a reference resolving across partitions refuses (typed `partition_mismatch`), mirroring component F's cross-partition refusal. +- Reference format (D010) reuses existing shapes only: + +```text +KvBlobRefV1 { + profile: "raw-blake3-256", // the #9120 initial profile token, no new token + digest: 64lower-hexdig, // 32-byte BLAKE3-256 over exact bytes + bytes_len: uint64, + partition: { jurisdiction, tier }, // #3401 / component-F §4 + locator: opaque adapter locator, // R2/RustFS key private to the adapter; never a stable API + state: staged | verified | published +} +``` + +No new hash, no new multicodec, no bearer URL persisted as identity. The locator is adapter-private (component-I peer principle: no client-visible branch on backend kind). + +### 11. Additive lists and tables (D013) + +Lists and tables are typed compositions over keys, never a second storage engine: + +- **List:** a key whose value is a signed manifest of member references (ordered member key names or blob refs + generation). Append = CAS on the manifest head (same rule as #9127 append-list user attributes: `doc/2026-11-17_design_id9127_append_list_user_attributes.md`, and #9118 array-address ordering where order matters). +- **Table:** a namespace-scoped prefix convention (`//` keys) plus a schema manifest key (column types per #9122 numeric kinds where numerics are keys: `Integer|Decimal|BinaryFloat`, no implicit coercion). Reads compose from point gets; no SQL surface (explicit non-goal of #10359). +- Both inherit namespaces, CAS, tombstones, sweep, thresholds, and GC unchanged — they add client-side composition and one manifest schema, nothing else. + +## Decisions + +All `agent-preliminary`: work may proceed on these defaults; only a human moves one to confirmed or reversed (see `human-review.md` for the genuine toss-ups). + +- **D001 — Local store is plain per-host SQLite (WAL), not embedded libSQL/Turso, in v1.** Source: issue #10359 item 2 + backup question; evidence: offline-write and file-backup needs (§1, §7); Turso embedded-replica write path (writes to cloud primary; https://docs.turso.tech/features/embedded-replicas/introduction). Status: agent-preliminary. Reversal cost: medium (replaces local engine + backup story; central protocol unchanged). Human review: needed only if v1 must survive host disk loss without sweep (then embedded replicas don't help either — say so). +- **D002 — Central store is one Turso-hosted libSQL primary; per-group DBs are provisioning scopes, not sync topologies, in v1.** Source: #10359 items 2/5; evidence: queue's Turso HTTP pipeline precedent (`pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs:81,671-770`); embedded-replica central-serialization argument (§6, Turso docs). Status: agent-preliminary. Reversal: high (splits the primary). Human review: needed (cost + tenancy shape). +- **D003 — Global namespace = designation flag on the shared registry, no second mechanism.** Source: #10359 item 3; aligns #9116 registry (versioned-design §#9116). Status: agent-preliminary. Reversal: low. Human review: not needed (directly what the issue asks). +- **D004 — Local-first reads with local-override; `--global` pins central; merged list shows shadowed rows.** Source: #10359 item 2 read path. Status: agent-preliminary. Reversal: low. Human review: not needed. +- **D005 — Deletes are tombstones; `revert` appends a restoring version.** Source: sweep-merge need (#10359 item 4) + #9115 tombstone reconciliation precedent. Status: agent-preliminary. Reversal: medium (resurrection bugs if dropped). Human review: not needed unless true-delete has a compliance deadline (then see #9130 true-delete coordination). +- **D006 — Sweep merges under `(owner_user_id, context_id, session_id)` via durable outbox + CAS.** Source: #10359 item 4 + context-propagation note filed the same day. Status: agent-preliminary. Reversal: medium. Human review: needed on keying (user+context vs session-only expiry). +- **D007 — All mutable heads are CAS-versioned; no timestamp LWW; bounded-jitter retry with outbox idempotency keys.** Source: #9114 head rule (CAS on prior generation); store-seam `concurrency_unsupported` posture. Status: agent-preliminary. Reversal: high (correctness invariant). Human review: not needed (invariant, not a toss-up). +- **D008 — Five-agent shared namespace: single-writer-per-key CAS on central; short-TTL reads; no offline fork in v1.** Source: #10359 item 5 question; evidence: claim-path precedent (`fleet-queue/.../claim.rs`); legacy embedded-replica write path (writes to cloud primary; https://docs.turso.tech/features/embedded-replicas/introduction) and Turso Sync last-push-wins (https://docs.turso.tech/sync/usage, https://docs.turso.tech/sync/conflict-resolution) both noted and rejected as the v1 conflict rule. Status: agent-preliminary. Reversal: medium. Human review: needed (freshness/cost tolerance is a product call). +- **D009 — Blob threshold is per-namespace policy (default 256 KiB agent-preliminary) with a per-push override flag, subordinate to the shared partition policy.** Source: #10359 threshold question; precedent: component-F "threshold is policy, never protocol" with 16 KiB conservative start. Status: agent-preliminary. Reversal: low (policy value). Human review: needed (default + flag shape). +- **D010 — Blob identity is exactly #9120 `raw-blake3-256` over exact bytes; reference row format `KvBlobRefV1` reuses that profile.** Source: #9120 A-9120.1 + #9113 shape dispatch; research `part-a-addressing/research.md` #9120 row. Status: agent-preliminary. Reversal: high (identity change). Human review: not needed (follows settled profile). +- **D011 — Broker-token auth to the trusted Cloudflare endpoint; hash is never a bearer credential; reads mint short-lived scoped capabilities.** Source: fleet credential shape (`fleet-gh-credentials.md`, `fleet-secrets`); component-F §5 access rule. Status: agent-preliminary. Reversal: high (auth architecture). Human review: needed (endpoint trust + capability TTL are product/security calls). +- **D012 — Blob GC is component-F mark-and-sweep per `(jurisdiction, tier)` partition; kv references are rows the sweep reads.** Source: component-F §6 + #3401 partitions + #9137 priority note. Status: agent-preliminary. Reversal: medium. Human review: not needed unless grace defaults change. +- **D013 — Lists/tables are manifest compositions over keys; no SQL surface.** Source: #10359 item 6 expansion note; precedents #9118/#9122/#9127. Status: agent-preliminary. Reversal: low. Human review: not needed. + +## Alternatives considered + +- **Embedded libSQL replica as the local store.** Lost: writes still serialize on the cloud primary (Turso docs), so it buys a divergence window without removing central arbitration, and it needs network for the write path that session partitions need most. Revisit only with a convergence proof and an offline story. +- **Turso Sync (`push`/`pull`) as the sync substrate.** Lost for v1: local-first and explicit, but conflict strategy is last-push-wins (Turso docs, https://docs.turso.tech/sync/usage), which contradicts the CAS-per-key invariant §5 needs for sweep/claim correctness. Possible later as a transport under CAS, not as the conflict rule. +- **Per-session (or per-group) Turso DB as the unit of sync.** Deferred, not rejected: matches Drew's "handed its own small database" intuition and may become the provisioning story, but in v1 it multiplies primaries without settling the per-key arbitration question. D002 keeps one primary; D006 keeps group scoping at the row/namespace level. +- **Reference-only-everything (no inline threshold).** Lost: for small KV values the reference machinery (staging, capability mint, GC sweep) costs more than the bytes it saves — the same argument component F makes for inline small content, applied one tier down in size. +- **Copy-bytes-into-central-DB (no object plane).** Lost: prices media as database, abandons dedup, and makes publication a divergent copy — component F's evaluation already rejects this for content above threshold, and KV values above threshold are the same case. +- **Bearer-hash reads (hash grants bytes).** Rejected outright: hashes are enumerable and leak by design (sidecars, location index #9115); serving on hash presentation alone fails the access-control soundness axis of #9084. Never the default; not even a flag. +- **Timestamp last-writer-wins for sweep conflicts.** Rejected: loses concurrent sessions' work silently and reintroduces ABA the #9114 head rule already forbids. CAS conflict with both versions retrievable is the floor. + +## Consequences + +- Gets easier: session work product survives disconnect by construction; namespaces stay one system with ID (#9107 family) instead of a fleet-private dialect; large values stop pricing as database rows; lists/tables arrive without a second engine; every conflict is a retrievable record, not silent loss. +- Gets harder: every writer implements CAS retry; every large push does staged→verified→published instead of a single write; reads that need linearizability must say `--global` explicitly; GC/tombstone literacy becomes operator knowledge. +- Must stay compatible: #9120 hash profile bytes (never rehash/reinterpret); legacy local state (adopt-or-CAS-merge, never overwrite); broker-token auth shape (no new credential); adapter neutrality (R2 vs RustFS invisible above the adapter, per component I). + +## Open questions + +- **O1 — `--global` surface exactness:** flag on every verb vs `fleet kv global ` subcommand. Default in effect: flag (`--global`), matching the issue's sketch. Settles: Phase 1 build (human-review H3). +- **O2 — Sweep keying:** `(owner_user_id, context_id)` with session provenance vs session-expiry alternative. Default: owner+context keying (D006). Settles: Drew/product (human-review H1). +- **O3 — Threshold default + flag name.** Default: 256 KiB per namespace + per-push override (D009). Settles: measurement (#9098-style KV workload) + Phase 1 UX (human-review H2). +- **O4 — Capability TTL + revocation expectations.** Default: short-lived (minutes), revocation = reference removal + TTL-bounded lag (component-F posture). Settles: security/product (human-review H4). +- **O5 — Central tenancy billing/placement:** one primary vs per-group DBs at scale. Default: one primary in v1 (D002); deferred to measurement. Settles: Phase 2 load evidence. +- **O6 — List/table manifest schema versioning.** Deferred to plan: Phase 3 details manifest v1 + upgrade rule; no default needed before then. +- **O7 — True-delete/retention interplay** with #9130-versioning/#3401 erasure flows for tombstoned KV rows. Deferred to plan; D005 tombstones are compatible with either outcome. diff --git a/doc/2026-11-23T12-45-00Z_design_fleet_kv/human-review.md b/doc/2026-11-23T12-45-00Z_design_fleet_kv/human-review.md new file mode 100644 index 0000000000..523a8a2e74 --- /dev/null +++ b/doc/2026-11-23T12-45-00Z_design_fleet_kv/human-review.md @@ -0,0 +1,45 @@ +# Human review — `fleet kv` design (#10359) + +- Status: agent-preliminary; no human confirmation claimed. Work may proceed on the stated defaults; only a human moves one to confirmed or reversed. +- Scope: this sheet exists so a human can ratify or reverse the toss-ups without re-reading the full design. The full record is `2026-11-23T12-45-00Z_design_fleet_kv.md` in this folder. + +## H1 — Sweep keying: owner+context vs session-expiry + +- Default (D006): merge under `(owner_user_id, context_id, session_id)` provenance via durable outbox + CAS; sessions never evaporate silently. +- Alternative: session-scoped partitions that expire (simpler lifecycle, but a dead session's work product can vanish before anyone sweeps it). +- Why it needs a human: product call about whose work survives disconnect and for how long. +- Reversal cost: medium (re-key sweep + outbox provenance). + +## H2 — Blob threshold default + flag shape + +- Default (D009): per-namespace policy, 256 KiB agent-preliminary, per-push override flag; subordinate to the shared per-partition policy (component E owns the partition threshold; the 16 KiB conservative start in #9084 governs where both apply — the KV knob may only narrow, never widen). +- Alternative: lower default (16–64 KiB, closer to media plane) or higher (1 MiB, fewer references); flag as `--inline-max` vs `--blob-threshold`. +- Why it needs a human: default prices every large value (DB rows vs reference machinery); flag name is CLI UX. +- Reversal cost: low (policy value + flag alias). + +## H3 — `--global` surface exactness (O1) + +- Default: flag (`fleet kv get --global`), matching the issue sketch; exactness settles in Phase 1 build. +- Alternative: `fleet kv global ` subcommand. +- Agent recommendation: flag (smaller surface, composes with `--namespace`). +- Reversal cost: low. + +## H4 — Capability TTL + revocation expectations (O4) + +- Default (D011): short-lived capabilities (minutes); revocation = reference removal + TTL-bounded lag (component-F posture). +- Alternative: longer TTLs (fewer mints, slower revocation) or instant-revocation machinery. +- Why it needs a human: security/product call; tier docs must not promise instant byte-level revocation. +- Reversal cost: high (auth architecture). + +## H5 — Central tenancy at scale (O5, D002) + +- Default: one fleet-kv Turso primary in v1; per-group DBs are provisioning scopes, not sync topologies. +- Alternative: per-session/per-group Turso DBs as the unit of sync (matches the issue's "own small database" intuition, multiplies primaries without settling per-key arbitration). +- Why it needs a human: cost + tenancy shape; needs Phase 2 load evidence. +- Reversal cost: high (splits the primary). + +## Explicitly not asking + +- D003/D004/D005/D007/D010/D012/D013: direct readings of the issue or settled ID/plane contracts; reversing one means reopening that contract, not this design. +- F12.5 `kv`/`blob` provider small caps (#1062) are a different surface (in-world sandbox ceilings) and are not ratified or changed here. +- Workload figures (five agents, key counts, write rates) are planning fixtures, not measured or free-tier guarantees. From 774920df844a30fe230292257a992c5d7e887b09 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 07:06:53 -0600 Subject: [PATCH 2/5] docs(fleet-kv): challenge outcomes D014/D015, reverse D002/D013, minimal human-review Adopts readonly investigator outcomes dated 2026-11-23: D001 retained (standalone Turso local-only steelmanned/rejected), D002 reversed/superseded by D014 hybrid placement (shared primary default + explicit-grant group DBs, fail-closed policy, v1 ops integration required), D008 retained (5 attempts/jitter cap 1s, ordinary cache age 1s, --global bypass, KV != queue lease), D013 reversed/superseded by D015 (blob-only phase 3, versionable envelope seam). Human-review reduced to None per minimal policy. Phase drafts (tmp/opencode) updated: standalone #10359 links, decision IDs, #13294 prereq, blob-only phase 3. --- .../2026-11-23T12-45-00Z_design_fleet_kv.md | 250 +++++++++++------- .../human-review.md | 45 +--- 2 files changed, 155 insertions(+), 140 deletions(-) diff --git a/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md index fb6714543b..fd06dfcfab 100644 --- a/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md +++ b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md @@ -1,124 +1,166 @@ # Design: `fleet kv` — namespaced key-value store (local + global), blob offload to content-addressed R2 -- Status: draft (agent-preliminary; no human confirmation claimed) -- Date: 2026-11-23T12:45:00Z +- Source: agent-preliminary (all defaults below are the writer's defaults; no human confirmed them) +- Status: preliminary +- Date: 2026-11-23T12:45:00Z (reconciled 2026-11-23 after read-only review; challenge outcomes 2026-11-23 integrated) - Roadmap item: none - Issues: https://github.com/developing-today/code/issues/10359 (design owner), https://github.com/developing-today/code/issues/9107 (ID core epic: namespaces/ID shapes), https://github.com/developing-today/code/issues/9120 (content-addressed namespace core), https://github.com/developing-today/code/issues/9084 (content-addressed media/data plane), tracking https://github.com/developing-today/code/issues/12892 +- Design PR: https://github.com/developing-today/code/pull/13294 — must merge before any phase build starts. - Standalone design: there is no workflow research package for this item (no S0–S5 intake/lease state exists); this record is the decision record #10359 acceptance asks for, adapted honestly to that fact. +- Pre-change snapshot (not "no design exists"): as of the 2026-11-14 triage note on #10359, greps found no `fleet kv` surface in the fleet crates and no fleet-kv schema on main. This document, created 2026-11-23, is the first such record; "nothing exists" below means no implementation, not the absence of this doc. ## Intent -Drew (2026-11-14, #10359) asked for a `fleet kv get/set/list` verb family in the `fleet` multicall binary for arbitrary bytes, explicitly not the secrets store. Each host has a local store (backed up); there is also a central store. Reads resolve local first and fall back to global; a local value overrides the same key in global. An explicit global operation (`fleet kv --global …`, exact surface TBD) always addresses central. Keys live in namespaces; a "global namespace" is a namespace designated global, not a second mechanism. Namespaces map to the ID project's namespace concept (#9107 / #9120), not a fleet-private reinvention. A session's local partition must survive disconnect: a sweeper pushes it into the central store keyed under the owning user id (+ context id). Every fleet-launched session — and other partitions (a repo, the fleet project itself, the mcpx namespace) — can be handed its own small database, likely Turso, with the embedded-replica attraction (fast local reads, automatic sync). The design must answer, with a workload sketch, what five agents concurrently pulling (and writing) a shared mid-size namespace actually get: replica sync semantics, writer topology, conflict behaviour — stated, not assumed. Values are arbitrary bytes; above a configurable threshold (Drew named 250 KB / 500 KB / 1 MB / 1 GB as the knob shape), a push keeps bytes local-working but routes them on central sync through a trusted Cloudflare endpoint into the content-addressed R2 bucket, storing key/namespace/name plus content hash + bucket link (#9084's reference pattern). Later, lists and tables ride the same substrate — design the KV layer so they are additive. +Drew (2026-11-14, #10359) asked for a `fleet kv get/set/list` verb family in the `fleet` multicall binary for arbitrary bytes, explicitly not the secrets store. Each host has a local store (backed up); there is also a central store. Reads resolve local first and fall back to global; a local value overrides the same key in global. An explicit global operation (`fleet kv --global …`, exact surface TBD) always addresses central. Keys live in namespaces; a "global namespace" is a namespace designated global, not a second mechanism. Namespaces map to the ID project's namespace concept (#9107 / #9120), not a fleet-private reinvention. A session's local partition must survive disconnect: a sweeper pushes it into the central store keyed under the owning user id (+ context id). Every fleet-launched session — and other partitions (a repo, the fleet project itself, the mcpx namespace) — can be handed its own small database, likely Turso, with the embedded-replica attraction (fast local reads, automatic sync). The design must answer, with a workload sketch, what five agents concurrently pulling (and writing) a shared mid-size namespace actually get: replica sync semantics, writer topology, conflict behaviour — stated, not assumed. Values are arbitrary bytes; above a configurable threshold (Drew named 250 KB / 500 KB / 1 MB / 1 GB as the knob shape), a push keeps bytes local-working but routes them on central sync through a trusted Cloudflare endpoint into the content-addressed R2 bucket, storing key/namespace/name plus content hash + bucket link (#9084's reference pattern). Later, lists and tables ride the same substrate — this design reserves only a versionable bytes/reference envelope for them (D015); list/table semantics are deferred, not designed here. -Today nothing of this exists: fresh greps find no `fleet kv` surface in the fleet crates (`pkgs/fleet/crates/`, command reference `pkgs/fleet/docs/verbs.md`) and no fleet-kv design under `doc/` (confirmed by the 2026-11-17 triage note on #10359). The fleet pieces that do exist and bound this design: the multicall/registry surface (`pkgs/fleet/docs/verbs.md`, `pkgs/fleet/crates/fleet-registry`), broker-token credential resolution by name (`pkgs/fleet/docs/fleet-gh-credentials.md`, `pkgs/fleet/crates/fleet-secrets/src/lib.rs:1-46`, `pkgs/fleet/crates/fleet/src/gh.rs:497-502`), the single front door for agents (`doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md`), and Turso-backed queue state over the libSQL HTTP pipeline (`pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs:1-81,532-770`). +Today no implementation exists (pre-change snapshot above). The fleet pieces that do exist and bound this design: the multicall/registry surface ([verbs.md](../../pkgs/fleet/docs/verbs.md), `pkgs/fleet/crates/fleet-registry`), named-secret resolution via the secrets broker ([fleet-secrets lib.rs](../../pkgs/fleet/crates/fleet-secrets/src/lib.rs), [fleet-gh-credentials.md](../../pkgs/fleet/docs/fleet-gh-credentials.md) — a secret-*fetch* protocol, not request authentication), the single front door for agents ([fleet-agent-front-door design](../../doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md)), hosted request authentication ([auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts): RP/agent JWTs or route-scoped service tokens; data-plane credentials refused), and Turso-backed queue state over the libSQL HTTP pipeline ([core.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs)). ## Design ### D-anchored summary -Local stores are plain per-host SQLite files (WAL) in v1 (D001). The central store is one Turso-hosted libSQL database (the fleet-kv primary), addressed over the same HTTP pipeline pattern the queue already uses — not a per-session Turso DB and not libSQL embedded replicas in v1 (D002). Namespaces are a small registry table whose global flag is designation only, and whose content-blob identity reuses the settled #9120 profile byte-for-byte (D003, D010). Reads are local-first with local-override; `--global` pins central; deletes are tombstones with revert (D004, D005). Disconnect sweep is an explicit, idempotent, CAS-guarded merge keyed under `(owner_user_id, context_id, session_id)` (D006, D007). The five-agent shared-namespace answer is single-writer-per-key by CAS against the central primary, short-TTL reads, and no offline fork in v1 (D008). Blobs cross a per-namespace threshold (default 256 KiB, agent-preliminary) with a per-push override flag; large bytes go staged → verified → published through the trusted Cloudflare endpoint and are stored as references, never bearer hashes (D009–D012). Lists/tables are typed compositions over keys, additive (D013). +Local stores are per-host SQLite files (WAL) in v1 (D001; standalone Turso local-only steelmanned and rejected, §7). The central plane is hybrid (D014, supersedes D002): one shared Turso primary for shared namespaces; a real group database exists only via an explicit fail-closed grant `(group, database, allowed namespaces/ops)` under an admission/provisioning policy — no default per-session proliferation, no unproved pricing. Namespace resolution always names an explicit registry: per-host server registries plus one distributed fleet registry whose identity and replication path are defined in §2; `global_flag` is designation only and never bypasses the local-first read rule (D003, D004). Local rows carry the complete logical identity `(owner_user_id, context_id, partition_id, namespace, key)` so no local read can cross users/sessions (§1, §3). Local deletion distinguishes three states: clear-override (drop the overlay, reveal central), masking tombstone (locally absent, sweeps as a mask), and history revert (append a restoring version) (D005, §3). Disconnect sweep is an explicit, idempotent, CAS-guarded merge with append-only version/conflict history and atomic idempotency receipts (D006, D007, §4–§5). The five-agent shared-namespace answer is single-writer-per-key by CAS against the central primary, ordinary cached reads at most 1 s old, `--global` as the authoritative bypass, and offline intents that are local-only until sweep CAS commits them; KV CAS is not a queue lease (D008, §6). Blobs cross an effective threshold that is a hard inline ceiling: the KV per-namespace knob (default 256 KiB) may only narrow, never widen past the shared partition ceiling; per-push override forces blob earlier only (D009, §8). Uploads go staged → verified → published through the trusted endpoint authenticated by RP/agent JWT or route-scoped service token — never the secrets-broker fetch path — and reads mint short-lived capabilities from live reference state, never bearer hashes (D011, §9). Blob GC is component-F mark-and-sweep per `(jurisdiction, tier)` with the KV published-row set as the authoritative reference state sharing the per-partition serialization point (D012, §9–§10). Lists/tables are deferred: Phase 3 is blob-only; this design reserves only a versionable envelope (D015, §11). -### 1. Store layout +### 1. Store layout and logical identity ```text -host local (SQLite file, WAL) central (Turso libSQL primary) +host local (SQLite file, WAL) central (shared Turso primary) +----------------------------+ +----------------------------------+ -| kv_local | | kv_namespaces | -| (ns, key, value|ref, ver, | sweep | (ns, global_flag, threshold, | -| tombstone, origin, ts) | ---------> | policy_epoch, owner_scope) | -| kv_namespaces (cache copy) | CAS merge | kv_central | -| outbox (sweep/upload queue) | | (ns, key, value|ref, ver, | -| backup manifest | | tombstone, owner, ctx, ts) | -+----------------------------+ | kv_blobs (references only) | - ^ file backup | (content_id, bytes_len, locator, | - | (snapshot + WAL, §7) | partition, state) | - +----------------------------------+ - | staged → verified → published - v object plane (R2/RustFS adapter) +| kv_local | | kv_namespaces | +| (owner, ctx, part, ns, key, | sweep | (ns, global_flag, threshold, | +| value|ref, ver, state, ts) | ---------> | policy_epoch, owner_scope) | +| kv_namespaces (cache copy) | CAS merge | kv_heads (per-key head) | +| outbox (sweep/upload queue) | | kv_versions (append-only history) | +| kv_conflicts (local copy) | | kv_conflicts (append-only) | +| idem_receipts (local copy) | | idem_receipts (outbox_id → result) | +| kv_grants (cache copy) | | kv_grants (group,db,ns,ops,epoch) | +| backup manifest | | kv_blobs (published refs only) | ++----------------------------+ +----------------------------------+ + ^ file backup | (content_id, bytes_len, locator, | + | (snapshot + WAL, §7) | partition, state=published) | + +----------------------------------+ + | staged → verified → published + v object plane (R2/RustFS adapter) ``` -Tables above are logical names for the phased build issues, not a claim that schema already exists. No `fleet kv` schema exists on main today. +Tables above are logical names for the phased build issues, not a claim that schema already exists. No `fleet kv` schema exists on main today (pre-change snapshot). + +**Complete logical identity.** Every local row is keyed by the full tuple `(owner_user_id, context_id, partition_id, namespace, key)`, where `partition_id` is the session id or the owning group (repo / fleet project / mcpx namespace). Central shared heads are keyed `(namespace, key)` with an `owner_scope` column; the survival archive (§7) retains the full tuple plus the sweep receipt. Consequences, stated as rules: + +- A local read filters by the caller's full identity: `(owner, ctx, partition)` from the authenticated context. A local read can never return another user/session/partition's row — there is no `(ns, key)`-only lookup path anywhere in v1. The `(ns, key)`-only shape from the earlier draft is withdrawn. +- Central shared heads are a different mapping: `(namespace, key) → head` with `owner_scope` authorizing which identities may read/write it. Row-level scope is authorization metadata on a shared head, not a grant: unless the build ships an explicit scoped-facade (per-scope views enforced at the pipeline layer), all central access goes through the single primary's CAS path with the namespace write policy checked per write. No claim is made that "rows equal database grants." +- The survival archive is the third mapping: full-identity rows plus sweep receipts, written only by the sweep path, read only for restore/audit. + +**Local (D001).** One SQLite file per host, e.g. `~/.local/share/fleet/kv/local.db`, WAL mode, holding `kv_local`, a cached copy of `kv_namespaces` and `kv_grants`, the durable `outbox`, and local copies of conflict/receipt rows for offline inspection. Rationale: the local store must accept writes while offline, survive process death, and back up as a file — plain SQLite does all three with zero network dependency. §7 records the investigated alternatives. + +**Central (D014; D002 reversed/superseded).** Hybrid placement: -**Local (D001).** One SQLite file per host, e.g. `~/.local/share/fleet/kv/local.db`, WAL mode, with `kv_local`, a cached copy of `kv_namespaces`, and a durable `outbox` for sweep/upload work. Rationale: the local store must accept writes while offline, survive process death, and back up as a file — plain SQLite does all three with zero network dependency. Two Turso products are distinguished and neither is the v1 path: (a) legacy embedded replicas — reads local, default writes remote to the cloud primary then reflected back, explicit `sync()` pulls, per-writing-replica read-your-writes (https://docs.turso.tech/features/embedded-replicas/introduction; docs now recommend new Turso Sync for new projects); (b) new Turso Sync — local-first writes with explicit `push()`/`pull()`, logical CDC, and last-push-wins on conflict (https://docs.turso.tech/sync/usage, https://docs.turso.tech/sync/conflict-resolution) — which collides with the CAS-per-key rule §5 requires. So: SQLite locally in v1 with a conservative outbox + central transaction sequencer; revisit embedded replicas or Turso Sync only as a named follow-up with a convergence proof, not as the v1 path. Do not conflate the two products/APIs or assume automatic multi-master CAS. +- **Shared namespaces (the v1 default):** one fleet-kv Turso database as the libSQL primary for KV heads, append-only version/conflict history, idempotency receipts, grant rows, and blob *references*; bytes live in the object plane (§6). Clients use the same transport shape the queue already proves: libSQL HTTP pipeline from Rust ([core.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs) lines 1–81 and 532–770; `DEFAULT_TURSO_URL` at line 10 shows the pattern, not the kv database). Central writes serialize per key on the primary's transactions (conservative outbox + central transaction sequencer, §5); this design assumes no automatic multi-master CAS from any sync product. +- **Group databases (explicit grant only):** a real per-group Turso DB exists iff a `kv_grants` row `(group, database, allowed namespaces, allowed ops, policy_epoch)` authorizes it, issued through a fail-closed admission/provisioning policy (admission checks group membership + namespace ownership; provisioning mints the DB, writes the grant row, and replicates the namespace subset; unknown group or namespace refuses). No default per-session proliferation: sessions do not get databases unless a grant says so. Not checked: per-database pricing and Turso org limits for grant-provisioned DBs — no cost claim is made; Phase 2 measures against the shared primary only. +- Per-user Turso DB credentials (component-E data-plane tokens) are not service authentication and are refused at the hosted front door by rule ([auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts) lines 20–33 and 134–159 `data_plane_credential_refused`); central KV access goes through the authenticated pipeline path, never by presenting a data-plane token. +- **v1 operational integration (required, not pretended-shipped):** the Phase 2 build must land migrations for all central tables above, the pipeline credential wiring, the grant/provisioning policy implementation, per-partition backup/restore runbook entries, and central health/readiness probes — a primary that none of this exists for is not a primary. Phase 2 acceptance (§4 of the phase-2 draft) gates on these, not on the row protocol alone. -**Central (D002).** One fleet-kv Turso database as the libSQL primary for KV rows and blob *references*; bytes live in the object plane (§6). Clients that need central access use the same transport shape the queue already proves: libSQL HTTP pipeline from Rust (`pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs:81,671-770`, `DEFAULT_TURSO_URL` at `core.rs:10` shows the pattern, not the kv database). Central writes serialize per key on the primary's transactions (conservative outbox + central transaction sequencer, §5); this design assumes no automatic multi-master CAS from any sync product. Per-user Turso DB credentials (component-E data-plane tokens) are not service authentication and are refused at the hosted front door by rule (`pkgs/fleet/hosted-worker/src/auth.ts:20-33,134-159` `data_plane_credential_refused`); central KV access goes through the broker/pipeline path, never by presenting a data-plane token. Per-group "small databases" from the issue (one per session/repo/project/mcpx namespace) are a provisioning option *behind* this primary — either separate Turso DBs reached over the same pipeline, or row-partitioned scopes inside the one primary — but they are not separate sync topologies in v1. The v1 topology is exactly: many SQLite locals → one central primary → one object plane. +**ID journal relationship (binding).** The ID serverless storage contract ([storage contract](../../doc/2026-11-17_decision_id5863_storage_contract.md)) fixes the signed journal as the system of record for ID world state; fleet-kv does not mint a competing journal. Scope boundary, stated exactly: KV row state is fleet-owned application state, not ID world state. Its durability contract is a bounded Fleet projection protocol — per-host outbox journal of *unsigned, fleet-scoped write intents* → central primary CAS transactions — which claims no ID-world authority, carries no ID signatures, and is never presented as an ID journal. Content blobs remain fully under the ID source-of-truth contract (content identity per #9120, admission per the signed gate); fleet-kv rows reference that content, they do not re-journal it. -**Backup/restore (§7, D001 detail).** The local file is backed up as a file: periodic SQLite backup API or filesystem snapshot of file + WAL, plus a `backup manifest` row (host, file hash, WAL frame, timestamp) kept in the outbox so restore can prove which snapshot it holds. Restore is: fetch latest snapshot, open read-only to verify, then either adopt (fresh host) or three-way merge through the §5 sweep path (returning host with divergent local rows). Backup never writes bytes into the KV row space; large local working bytes above threshold stay local-working until §6 publishes them. +**Backup/restore (§7, D001 detail; numbers are defaults in effect).** Two destinations, both concrete: -### 2. Namespaces (coordinate with #9107 / #9116, not parallel) +1. **Local file snapshot** (survives process death, not disk loss): SQLite backup API or filesystem snapshot of file + WAL into `~/.local/share/fleet/kv/backups/` every **6 h**, plus a `backup manifest` row (host, file hash, WAL frame, timestamp) in the outbox. RPO for process-death recovery: last write (WAL replay). +2. **Survival archive** (survives disk loss): the sweeper uploads the session dirty set — including large *working* bytes staged via §9, not inline — to the central archive scope on session end and every **15 min** during a live session (RPO ≤ 15 min for acknowledged local writes). Large working blobs are part of the snapshot: the manifest lists staged content ids, and restore re-publishes or re-links them. -Namespaces reuse the ID local-namespace-registry concept: a namespace definition binds `{namespace_id, core_id, handler/encoding profile, read/write policy, shorthand policy, schema version}`, server-local, versioned and audited (`doc/2026-11-13T03-40-00Z_design_id-atlas-summit/part-a-addressing/versioned-design.md`, §#9116). Fleet-kv does not mint a second namespace grammar: +Restore: fetch latest snapshot (local dir first, archive scope if the disk is gone), open read-only to verify, then adopt (fresh host) or three-way CAS-merge through §4 (returning host with divergent rows). **Durability boundary, stated plainly:** an acknowledged local write lost to disk destruction *before* the next 15-minute archive upload is unrecoverable — that is the loss window (≤ 15 min of local writes, plus any over-threshold working bytes not yet staged). Backup never writes bytes into the KV row space; large local working bytes stay local-working until staged. +### 2. Namespaces and registry identity (coordinate with #9107 / #9116, not parallel) + +Namespaces reuse the ID local-namespace-registry concept: a namespace definition binds `{namespace_id, core_id, handler/encoding profile, read/write policy, shorthand policy, schema version}`, server-local, versioned and audited (Part A versioned design, §#9116). The ID contract constrains this design ([namespace_definition.rs](../../pkgs/id/crates/id-core/src/namespace_definition.rs) lines 24–32 and 594–645): registries are local, resolution always names a registry (`Resolver::resolve(registry, namespace)`), and there is no global registry or fallback. Fleet-kv therefore defines its registry identity explicitly instead of a "shared registry": + +- **Fleet registry identity:** the central `kv_namespaces` table is the distribution source under registry handle `fleet-kv-central` (a `RegistryId::Handle`, [namespace_definition.rs](../../pkgs/id/crates/id-core/src/namespace_definition.rs) lines 424–440). Each host holds a server registry (`RegistryId::Server(host_id)`) whose fleet-namespace definitions are **replicas provisioned from** `fleet-kv-central`: on `fleet kv sync` (and at most every **1 h**, default in effect) the host pulls the central table at its watermark and replaces its cached definitionsassigning the central `policy_epoch`. Reads resolve in the host's server registry only; there is never a cross-registry fallback. - `kv_namespaces` rows carry `(namespace_id, core_binding, global_flag, blob_threshold, policy_epoch, owner_scope)`. -- `global_flag` is designation only (D003): "global namespace" = a namespace whose reads/writes default to central. No second registry, no second lookup path. -- Content-blob identity inside any namespace is exactly the settled #9120 initial profile: unkeyed BLAKE3-256 over exact bytes, 32-byte digest (A-9120.1; research `part-a-addressing/research.md` #9120 row; implementation slices `part-a-addressing/implementation-slices.json` A9120-content-id). Fleet-kv neither redefines the hash nor invents a parallel digest (binding constraint shared with #9120's "neither this spec nor §3's may redefine the hash"). -- Parse/URI transport, if ever exposed as `id://`, follows #9117 syntax transport only; this design mints no IDs and establishes no authority beyond the namespace's own write policy. +- `global_flag` is designation only (D003): "global namespace" = a namespace whose *default address scope* includes central. It does not change resolution (still the named registry), and it **must not bypass the local-first read rule**: even in a global-flagged namespace, plain `get` reads the caller's local overlay first and only falls through on miss; only `--global` pins central (§3). A flag that silently reordered reads would be a second lookup path, which this design forbids. +- Content-blob identity inside any namespace is exactly the settled #9120 initial profile: unkeyed BLAKE3-256 over exact bytes, 32-byte digest (A-9120.1; research `part-a-addressing/research.md` #9120 row; implementation slices `part-a-addressing/implementation-slices.json` A9120-content-id; profile code in [content_id.rs](../../pkgs/id/crates/id-core/src/content_id.rs)). Fleet-kv neither redefines the hash nor invents a parallel digest (binding constraint shared with #9120's "neither this spec nor §3's may redefine the hash"). +- Parse/URI transport, if ever exposed as `id://`, follows #9117 syntax transport only; this design mints no IDs and establishes no authority beyond the namespace's own write policy. Admission-gate semantics, if referenced, follow [admission_gate.rs](../../pkgs/id/crates/id-core/src/admission_gate.rs); fleet-kv defines its own grant rows (D014) and does not reinterpret the ID gate. + +Coordination boundary: #9116 owns the registry model; #9117 owns URI syntax; #9118 owns the array core; #9120 owns the immutable content core. Fleet-kv is a consumer of all four and defines only the KV row envelope, the override/sweep rules, and the blob reference row below. It preserves Part A untouched: no redefinition of the hash, no new core, no parallel namespace grammar. Not this surface: the F12.5 in-world `kv`/`blob` providers (#1062: `kv.get/set/delete` with 8 KiB values / 1024 entries / 64 KiB per world) are world-sandbox ceilings, not the fleet CLI store — this design neither implements nor changes them. -Coordination boundary: #9116 owns the registry model; #9117 owns URI syntax; #9118 owns the array core; #9120 owns the immutable content core. Fleet-kv is a consumer of all four and defines only the KV row envelope, the override/sweep rules, and the blob reference row below. It preserves Part A untouched: no redefinition of the hash, no new core, no parallel namespace grammar. Not this surface: the F12.5 in-world `kv`/`blob` providers (#1062: `kv.get/set/delete` with 8 KiB values / 1024 entries / 64 KiB per world, `doc/2026-11-22_design_id1062-kv-provider.md`) are world-sandbox ceilings, not the fleet CLI store — this design neither implements nor changes them. +**Key syntax and limits (explicit; the world-provider caps do not apply here).** Namespace names follow the `NamespaceId` rule (letter followed by letters/digits/hyphens, ≤ 63 bytes). Keys: 1–512 bytes, printable ASCII, `/` permitted as a hierarchy separator but no leading/trailing `/` and no empty segments. Inline value bytes: at most the effective threshold (§8). At most 1024 namespaces cached per host registry (policy, default in effect). Violations are typed refusals (`malformed_key`, `unknown_namespace`, `limit`), never silent truncation. ### 3. Read/list/set/delete/tombstone/revert semantics -Verbs: `fleet kv get|set|list` plus `delete` and `revert` (delete without revert is a half-design; the sweep needs tombstones to converge). `--global` pins central for the verb it modifies; `--namespace NS` selects scope; `--as-bytes-ok` style escape hatches are out of scope for v1. +Verbs: `fleet kv get|set|list` plus `delete`, `clear-override`, and `revert`. `--global` pins central for the verb it modifies; `--namespace NS` selects scope. -- **Read path:** local first; on miss, fall back to global/central. A live local row *overrides* the same key in global (D004). `--global get` skips local entirely. `list` merges both scopes with origin marks (`local|central|both`, local winning display) and never silently hides the shadowed central row — show it as `shadowed-by-local` in verbose output. -- **Set path:** default writes local + enqueues outbox work; `--global set` writes central directly (authenticated; §6 for large values). Local sets carry `(key, namespace, value-or-ref, base_version, writer_session, ts)`. -- **Delete:** writes a tombstone row `(key, namespace, tombstone_epoch, deleter, ts)`, never a physical row removal (D005). Reads treat tombstoned keys as absent but `list --include-tombstones` and `revert` can see them. Tombstones sweep exactly like values (§5), which is what makes two-session delete/write converge instead of resurrecting. -- **Revert:** `fleet kv revert NS KEY --to ` writes a new version whose value equals the named prior version (new version number, full provenance) — history is append-only; there is no in-place rollback. Reverting a tombstone re-lives the key at a new version. -- **Freshness:** local reads are immediate; central reads are bounded-stale only by explicit `sync`/`pull` in v1 (no background sync promise). Whatever freshness knob ships must be a documented flag, not ambient behaviour. +- **Read path (local-first, identity-scoped):** resolve the caller's `(owner, ctx, partition)` from the authenticated context; read the local overlay for the full tuple; on miss, fall through to the central head the caller's scope authorizes. A live local overlay row *overrides* the same key in central (D004). `--global get` skips local entirely and reads the central head at its current version — the authoritative bypass. `list` merges both scopes with origin marks (`local|central|both`, local winning display) and never silently hides the shadowed row — show it as `shadowed-by-local` / `shadowed-by-central` in verbose output. +- **Set path:** default writes the local overlay + enqueues outbox work; `--global set` writes central directly via CAS (authenticated; §9 for large values). Local sets carry the full identity tuple plus `(value-or-ref, base_version, writer_session, ts)`. +- **Delete — three distinct states, three distinct operations (D005):** + 1. `clear-override` — removes the local overlay row for the full identity tuple. Effect: the central value (if any) becomes visible again locally. Sweeps nothing (there is no overlay left to sweep). + 2. **Masking tombstone** (`delete`) — writes a local tombstone row for the tuple. Effect: the key reads absent locally and in merged `list` (shown with `masked` origin under `--include-tombstones`), while central is untouched until sweep. Sweeps as a mask: central records the tombstone under the sweeping identity's scope; other scopes' heads are unaffected. + 3. **History revert** (`fleet kv revert NS KEY --to `) — appends a new version whose value equals the named prior version (new version number, full provenance). Operates on version history, never on the overlay: it does not clear overrides and does not mask central. +- **Freshness (states exactly which read is authoritative):** `--global get` reads authoritative central state at the returned head version. Plain `get` reads the local overlay if present, else the freshest central snapshot the host has pulled (snapshot timestamp shown). `sync` refreshes two things only: the cached namespace definitions (≤ 1 h staleness) and the central snapshot the host caches per namespace. Ordinary cached reads are at most **1 s** old (default in effect); `--no-cache` forces a central read. There is no background sync promise in v1. ### 4. Durable session-partition sweep -A session's local partition does not evaporate at disconnect (D006). On session end (and on explicit `fleet kv sync`), a sweeper merges the session's dirty rows into central under `(owner_user_id, context_id, session_id)` provenance: +A session's local partition does not evaporate at disconnect (D006). On session end (and on explicit `fleet kv sync`), a sweeper merges the session's dirty rows into central under full-identity provenance: -1. Read session dirty set from `outbox` (durable, so a dead session still sweeps on next host run). -2. For each key: `central_CAS(key, expected=base_version, new=row)` against `kv_central`. -3. On success: mark outbox row done. On conflict: run the §5 rule (versioned conflict, never silent last-writer-wins across sessions), record the conflict row, and leave both versions retrievable. -4. Tombstones sweep through the same CAS path. -5. Large values sweep by reference: the sweeper uploads through §6 first, then CASes the reference row. Central never accepts an unpublished blob reference. +1. Read session dirty set from `outbox` (durable, so a dead session still sweeps on next host run; disk-destroyed sessions recover from the survival archive, §1/§7). +2. For each key: `central_CAS(namespace, key, expected=base_version, new=row)` against `kv_heads`. +3. On success: write the idempotency receipt, then mark the outbox row done (order fixed: CAS → receipt+ack, §5). On conflict: run the §5 rule (versioned conflict, never silent last-writer-wins across sessions), append the conflict record, and leave both versions retrievable. +4. Masking tombstones sweep through the same CAS path as masks scoped to the sweeping identity. +5. Large values sweep by reference: the sweeper uploads through §9 first, then CASes the reference row. Central never accepts an unpublished blob reference. -Sweep is idempotent (outbox row ids + CAS make re-runs safe) and recoverable (crash between upload and CAS leaves a staged blob that staging TTL reaps, per #9084 component-F staging rules; crash between CAS and outbox-ack re-runs CAS harmlessly). "Two sessions sweeping the same key" is therefore a routine CAS conflict, not a special case. +Sweep is idempotent (outbox row ids + receipts make re-runs safe) and recoverable (crash between upload and CAS leaves a staged blob that staging TTL reaps, per #9084 component-F staging rules; crash between CAS and ack re-runs CAS, and the atomic receipt returns the original result instead of a spurious new conflict). "Two sessions sweeping the same key" is therefore a routine CAS conflict, not a special case. ### 5. CAS/versioned conflicts, retry, idempotence, recovery -Every mutable head uses compare-and-swap on `(key, namespace, version)` (D007), following the #9114 sidecar-head precedent (CAS on prior `(generation, snapshot_id)`; generation increments exactly once). There is no timestamp-only last-writer-wins anywhere in v1: +Every mutable head uses compare-and-swap on `(namespace, key, version)` (D007), following the #9114 sidecar-head precedent (CAS on prior `(generation, snapshot_id)`; generation increments exactly once). There is no timestamp-only last-writer-wins anywhere in v1. Storage, not just assertions: -- Each row carries `version` (monotonic per key) + `parent_version` + writer identity. A writer that did not read the current version fails CAS with `conflict {key, expected, actual}` and retries by re-reading, re-applying intent, and re-CASing — or surfaces the conflict to the user for genuinely incompatible intents. -- Retries are bounded with jitter and carry idempotency keys (outbox row id = the idempotency key; re-sending the same CAS is a no-op once applied). -- Recovery order is fixed: outbox → upload (§6) → CAS → ack. Any crash restarts at the oldest unacked outbox row. Staged-but-unpublished blobs are never referenced by any read path, so they are safe to reap by TTL. -- `concurrency_unsupported` is a typed error if some future adapter cannot CAS: fail closed, never degrade to silent overwrite (same posture as the V2 store seam in `part-a-addressing/versioned-design.md`). +- `kv_heads`: one row per `(namespace, key)` — the current head `(version, value-or-published-ref, writer, ts)`. +- `kv_versions`: append-only; every CAS success appends `(namespace, key, version, parent_version, value-or-ref, writer, ts)`. Retention: full history while the key lives; tombstoned keys retain history (true-delete deferred to #9130 coordination). +- `kv_conflicts`: append-only; every failed CAS appends `(namespace, key, expected, actual, proposed_value, writer, ts)` and the loser receives the conflict id. "Both versions retrievable" reads: `kv get --version V` replays `kv_versions`; `kv conflicts NS KEY` lists conflict records. +- `idem_receipts`: `(outbox_id → {namespace, key, version, result})`, written **atomically with the CAS in one central transaction**. A replay of an already-applied `outbox_id` — even after the head has since advanced — returns the recorded result instead of attempting a new CAS (so it can never become a spurious new conflict). +- Retries are bounded with jitter: at most **5 attempts**, jittered exponential backoff capped at **1 s** per backoff (defaults in effect). Each attempt carries the outbox id as the idempotency key. +- Recovery order is fixed: outbox → upload (§9) → CAS+receipt (atomic) → ack. Any crash restarts at the oldest unacked outbox row. Staged-but-unpublished blobs are never referenced by any read path, so they are safe to reap by TTL. +- `concurrency_unsupported` is a typed error if some future adapter cannot CAS: fail closed, never degrade to silent overwrite (same posture as the V2 store seam in the Part A versioned design). ### 6. Five agents on one shared mid-size namespace (workload sketch + topology) -Workload assumed (agent-preliminary planning fixture, stated so a later measurement can replace it — not a measured or free-tier guarantee): namespace holds ~10k–100k small keys (hundreds of bytes to a few KiB each; larger values are references per §8), five agents each holding the namespace open for minutes, read-heavy with intermittent writes (each agent writes ~1–10 keys/min, occasionally the same key family, e.g. status/claim rows). A "five agents × ~100 MiB" shape, where named, is the same kind of planning fixture, not a throughput promise. +Workload assumed (planning fixture, stated so a later measurement can replace it — not a measured or free-tier guarantee): namespace holds ~10k–100k small keys (hundreds of bytes to a few KiB each; larger values are references per §8), five agents each holding the namespace open for minutes, read-heavy with intermittent writes (each agent writes ~1–10 keys/min, occasionally the same key family, e.g. status/claim rows). A "five agents × ~100 MiB" shape, where named, is the same kind of planning fixture, not a throughput promise. -- **Writer topology (D008): single-writer-per-key by CAS against the central primary.** There is no multi-master convergence in v1: all writers serialize per key on `kv_central`'s CAS. The "shared mid-size namespace" is therefore N readers of a locally cached copy plus M writers arbitrated centrally per key — the same shape as the fleet queue's claim path (atomic claim over Turso in `pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs`), not a mesh sync. -- **Replica sync semantics:** no embedded replicas in v1 (D002 rationale). Agents read central directly (short-TTL client cache, TTL documented per namespace) or read a snapshot pulled at task start; there is no background replica convergence to reason about, and therefore no divergence window beyond the stated cache TTL. Offline writes in v1 are local-only and unsynced — they become visible only through the §4 sweep, and conflicts there follow §5. -- **Freshness:** reads state their source (`local|central@version|cache@ttl-expiry`); claim/status keys that need linearizability use `--global` reads + CAS writes. Nothing else gets linearizability, and the CLI says so. -- **Contention:** same-key write contention fails CAS fast; hot keys should be claim/checkpoint-shaped (queue pattern) rather than counter-shaped. No counters in v1 KV rows — a stored counter is a second copy of the truth and drifts (same argument as `doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md` §6 against reference counting). -- **Cost:** central rows are small (values inline only at/below threshold; §8). Five agents polling `list` at 1 Hz against Turso HTTP is the abuse case: mitigate with the documented cache TTL, snapshot reads, and (if needed) a per-namespace read budget owned by the same policy epoch as the threshold. No per-request billing claim is made here — measure on the fleet-kv Turso DB once Phase 2 lands. +- **Writer topology (D008): single-writer-per-key by CAS against the central primary.** There is no multi-master convergence in v1: all writers serialize per key on `kv_heads` CAS. KV CAS is not a queue lease: unlike the fleet queue's claim path ([claim.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs)), there are no leases, no expiry, no steal — a failed CAS is a versioned conflict for a human or agent to resolve, never a grant that times out. Rows are not database grants: sharing a namespace grants nothing by itself; every write passes the namespace write policy at the pipeline layer. +- **Replica sync semantics:** no embedded replicas in v1 (D002 rationale, retained by D014 for shared namespaces). Agents read central directly (ordinary cached reads at most 1 s old, documented per namespace) or read a snapshot pulled at task start; `--global` bypasses the cache and reads the authoritative head. There is no background replica convergence to reason about, and therefore no divergence window beyond the stated cache age. Offline writes are permitted as **local intents**: they are ordinary overlay rows, fully usable locally, but they are not shared or committed until sweep CAS succeeds — "no offline fork" means no divergent shared history, not that offline work is forbidden. +- **Freshness:** reads state their source (`local|central@version|snapshot@age`); claim/status keys that need linearizability use `--global` reads + CAS writes. Nothing else gets linearizability, and the CLI says so. +- **Contention:** same-key write contention fails CAS fast (≤ 5 attempts, §5); hot keys should be claim/checkpoint-shaped rather than counter-shaped. No counters in v1 KV rows — a stored counter is a second copy of the truth and drifts (same argument as the [content-addressed media data-plane design](../../doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md) §6 against reference counting). +- **Cost:** central rows are small (values inline only at/below threshold; §8). Five agents polling `list` at 1 Hz against Turso HTTP is the abuse case: mitigate with the documented 1 s cache age, snapshot reads, and (if needed) a per-namespace read budget owned by the same policy epoch as the threshold. Not checked: per-request Turso billing for this workload — no billing claim is made here; measure on the fleet-kv Turso DB once Phase 2 lands. Why not embedded replicas for the five-agent case: embedded-replica writes go to the cloud primary anyway (https://docs.turso.tech/features/embedded-replicas/introduction), so five replica-holders writing the same key still serialize centrally — replicas add a divergence/catch-up window without removing the central serialization point. v1 keeps that serialization explicit and auditable. ### 7. Host-local technology choice: SQLite vs embedded libSQL/Turso -D001/D002 decide: **plain SQLite (WAL) per host for local; Turso-hosted libSQL primary for central; no embedded-replica mode in v1.** Backup story: local = file snapshot + WAL + backup-manifest row (§1); central = Turso's own durability plus the tombstoned, versioned row history (point-in-time story is the provider's, not a second log we maintain). Sandbox hosts ("sandbox has their own local store that maybe we back up and merge") get exactly the §4 sweep: their partition merges on session end, and a dead sandbox's outbox merges on next host run — "merge" always means CAS merge, never file copy. +D001/D014 decide: **plain SQLite (WAL) per host for local; Turso-hosted libSQL primary for shared central; no embedded-replica mode in v1.** Backup story: local = file snapshot + WAL + backup-manifest row (§1, numbers above); central = Turso's own durability plus the tombstoned, versioned row history (point-in-time story is the provider's, not a second log we maintain). Sandbox hosts ("sandbox has their own local store that maybe we back up and merge") get exactly the §4 sweep plus the §1 survival archive: their partition merges on session end, a dead sandbox's outbox merges on next host run, and a destroyed sandbox recovers from the archive — "merge" always means CAS merge, never file copy. + +Alternatives steelmanned (challenge 2026-11-23): + +- **Embedded libSQL replica as the local store.** Lost: writes still serialize on the cloud primary (Turso docs), so it buys a divergence window without removing central arbitration, and it needs network for the write path that session partitions need most. Revisit only with a convergence proof and an offline story. +- **Standalone Turso local-only (libSQL file, no sync) via the Rust SDK** (https://docs.turso.tech/sdk/rust/quickstart). Steelman: same-file durability as SQLite, libSQL API parity with the central primary (one driver, one SQL dialect), trivial later upgrade to a sync mode. Lost for v1 anyway: API sameness is not behavior sameness — the sync surface stays one connection flag away from silently becoming a replica, whereas plain SQLite (no sync primitives at all) makes "no sync" structural; and SQLite's backup API + WAL file story is the exact shape §1's snapshot needs. Cheapest to reason about wins for v1. +- **Turso Sync (`push`/`pull`) as the sync substrate.** Lost for v1: local-first and explicit, but conflict strategy is last-push-wins (https://docs.turso.tech/sync/usage, https://docs.turso.tech/sync/conflict-resolution), which contradicts the CAS-per-key invariant §5 needs for sweep/claim correctness. Possible later as a transport under CAS, not as the conflict rule. +- **Reference-only-everything (no inline threshold).** Lost: for small KV values the reference machinery (staging, capability mint, GC sweep) costs more than the bytes it saves — the same argument component F makes for inline small content, applied one tier down in size. +- **Copy-bytes-into-central-DB (no object plane).** Lost: prices media as database, abandons dedup, and makes publication a divergent copy — component F's evaluation already rejects this for content above threshold, and KV values above threshold are the same case. +- **Bearer-hash reads (hash grants bytes).** Rejected outright: hashes are enumerable and leak by design; serving on hash presentation alone fails the access-control soundness axis of #9084. Never the default; not even a flag. +- **Timestamp last-writer-wins for sweep conflicts.** Rejected: loses concurrent sessions' work silently and reintroduces ABA the #9114 head rule already forbids. CAS conflict with both versions retrievable is the floor. ### 8. Arbitrary bytes, streaming, blob threshold knob Values are arbitrary bytes with a streaming interface (no full-buffer requirement on push/pull above a small in-memory cap). The threshold knob (D009): -- **Per-namespace policy value** (`kv_namespaces.blob_threshold`, bytes), default **256 KiB (agent-preliminary)** — inside Drew's named shape (250 KB / 500 KB / 1 MB / 1 GB) at its low end. This default is subordinate to the shared per-partition placement policy, not a competing protocol: where KV bytes and #9084 component-F content share a partition, component E owns the threshold and the 16 KiB conservative starting default (`doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/...md` §Recommendation) governs placement until #9098 measurements move it. The KV per-namespace knob may only narrow (force-blob sooner), never widen past the partition policy, and changing either changes placement of new content only, never identity or access (policy, never protocol). -- **Per-push override flag** (`--inline-max BYTES` / `--blob-threshold BYTES`, exact flag name owned by Phase 1): both directions supported — force-inline a just-over-threshold value or force-blob a small value that should not live in the row store. -- At or below the effective threshold: bytes inline in the row. Above: §6 reference path. Promotion (inline → referenced) is a new version with identical read semantics; no client-visible change. +- **Per-namespace policy value** (`kv_namespaces.blob_threshold`, bytes), default **256 KiB** — inside Drew's named shape (250 KB / 500 KB / 1 MB / 1 GB) at its low end. This default is subordinate to the shared per-partition placement policy, not a competing protocol: where KV bytes and #9084 component-F content share a partition, component E owns the threshold and the 16 KiB conservative starting default ([media data-plane design](../../doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md) §Recommendation) governs placement until #9098 measurements move it. The **effective threshold is a hard inline ceiling**: `effective = min(namespace knob, partition ceiling)`. Changing either changes placement of new content only, never identity or access (policy, never protocol). +- **Per-push override** (`--force-blob`, exact flag name owned by Phase 1): one direction only — force blob treatment at or below the effective threshold (e.g. a small value that should not live in the row store). There is no force-inline override: nothing may place bytes inline above the effective ceiling. The earlier `--inline-max` both-directions sketch is withdrawn as a fatal ceiling conflict. +- At or below the effective threshold: bytes inline in the row. Above: §9 reference path. Promotion (inline → referenced) is a new version with identical read semantics; no client-visible change. -### 9. Trusted Cloudflare endpoint, broker-token auth, reference-based read (no bearer hash) +### 9. Trusted Cloudflare endpoint, supported credential path, reference-based read (no bearer hash) -Auth reuses the fleet's existing shape, not a new credential (D011): +Auth uses only credentials the hosted front door actually validates (D011, corrected after review — the earlier draft cited the secrets-broker fetch path, which is withdrawn): -- **Push path:** the pusher authenticates to the trusted Cloudflare endpoint with its **existing fleet broker token** (same family as the secrets-broker token file pattern: `fleet-secrets` resolves by name, broker-first; `pkgs/fleet/docs/fleet-gh-credentials.md`, `pkgs/fleet/crates/fleet-secrets/src/lib.rs:15-28`). The endpoint verifies the token, checks the namespace write policy for `(user, context, namespace)`, and only then accepts staged bytes. The content hash travels as an *assertion to be verified*, never as authority. -- **Read path:** a bearer hash grants nothing (binding rule shared with `doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md` §5 "the hash is not a capability"). Readers resolve their KV row authorization first (local or central, per namespace policy + authenticated context), then receive a **short-lived, object+operation-scoped capability** minted from live reference state; the adapter serves bytes only under that capability, with replica fallback during placement movement (same contract as component I's object adapter: `doc/2026-11-21T21-40-00Z_design_self_hosted-tier-adapters/2026-11-21T21-40-00Z_design_self_hosted-tier-adapters.md`, object adapter contract). +- **Push path:** the pusher authenticates to the trusted Cloudflare endpoint with either (a) an RP/agent JWT validated as in [auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts) lines 140–184 (issuer/audience check, subject mapped to a tenancy `bindingId`; agent credentials must carry lane/session claims), or (b) a route-scoped service token validated at lines 187–201 with `authorizeRoute` scoping it to the kv-upload door (lines 206–210). The endpoint then checks the namespace write policy for `(binding_id, context, namespace)` and only then accepts staged bytes. The content hash travels as an *assertion to be verified*, never as authority. The [fleet-secrets](../../pkgs/fleet/crates/fleet-secrets/src/lib.rs) broker-first resolution (lines 15–28) plus [fleet-gh-credentials.md](../../pkgs/fleet/docs/fleet-gh-credentials.md) is a named-secret *fetch* protocol and is not a request-authentication mechanism anywhere in this design. +- **Read path:** a bearer hash grants nothing (binding rule shared with the [media data-plane design](../../doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md) §5 "the hash is not a capability"). Readers resolve their KV row authorization first (local overlay or central head, per namespace policy + authenticated context), then receive a **short-lived (5 min, default in effect), object+operation-scoped capability** minted from live reference state; the adapter serves bytes only under that capability, with replica fallback during placement movement (same contract as the [self-hosted tier adapters design](../../doc/2026-11-21T21-40-00Z_design_self_hosted-tier-adapters/2026-11-21T21-40-00Z_design_self_hosted-tier-adapters.md) object adapter contract). - **Upload safety:** `put_staged → verify (length + BLAKE3-256 recomputed on receipt, streaming) → publish`. Partial uploads are staging state, never accepted objects (same invariant as A-9120.1 and component-F staging). Multipart completion is not publication; only the service verification step makes the reference row writable. -- **GC safety:** mark-and-sweep per partition exactly as component F §6 (references are the rows; derived index is a cache; re-verify at grace expiry; epoch-fenced delete; audit event per delete). Fleet-kv blob references are rows in `kv_central`/`kv_blobs`, so they slot into that protocol as one more reference source; per-jurisdiction dedup partitions from #3401 bound every sweep (D012). +- **GC safety:** mark-and-sweep per partition exactly as component F §6. The authoritative reference state the sweep reads is the set of **published** rows in `kv_heads`/`kv_blobs` (intermediate `staged`/`verified` states live only in the endpoint's staging area, never in central rows — central accepts `published` only). The sweep shares component F's per-partition serialization point concretely: KV reference creation (publish-CAS) and the GC delete fence are transactions against the same central primary, ordered by the per-partition sequence the primary assigns. A reference created during candidate/grace/re-verify races is thereby ordered: a publish-CAS landing before the fence's re-verify is seen and clears candidacy; one landing after finds no verified replica under the fence and the writer re-stages from its held bytes (a re-upload, not data loss). Per-jurisdiction dedup partitions from #3401 bound every sweep (D012); the derived index is a cache; re-verify at grace expiry; epoch-fenced delete; audit event per delete. ### 10. Per-jurisdiction dedup and reference format (using existing ID hash shapes) @@ -132,60 +174,70 @@ KvBlobRefV1 { bytes_len: uint64, partition: { jurisdiction, tier }, // #3401 / component-F §4 locator: opaque adapter locator, // R2/RustFS key private to the adapter; never a stable API - state: staged | verified | published + state: published // central rows accept published only (§9) } ``` No new hash, no new multicodec, no bearer URL persisted as identity. The locator is adapter-private (component-I peer principle: no client-visible branch on backend kind). -### 11. Additive lists and tables (D013) +### 11. Lists and tables: deferred (D015; D013 reversed/superseded) -Lists and tables are typed compositions over keys, never a second storage engine: +Phase 3 is blob-only. List/table semantics are not designed here and no manifest/table implementation ships in this plan. What this design reserves — so a later shapes proposal arrives without a second engine — is a versionable envelope only: -- **List:** a key whose value is a signed manifest of member references (ordered member key names or blob refs + generation). Append = CAS on the manifest head (same rule as #9127 append-list user attributes: `doc/2026-11-17_design_id9127_append_list_user_attributes.md`, and #9118 array-address ordering where order matters). -- **Table:** a namespace-scoped prefix convention (`
//` keys) plus a schema manifest key (column types per #9122 numeric kinds where numerics are keys: `Integer|Decimal|BinaryFloat`, no implicit coercion). Reads compose from point gets; no SQL surface (explicit non-goal of #10359). -- Both inherit namespaces, CAS, tombstones, sweep, thresholds, and GC unchanged — they add client-side composition and one manifest schema, nothing else. +- The KV row envelope carries an envelope version (`kv:raw-v1` for inline bytes, `kv:ref-v1` for a `KvBlobRefV1` row). Unknown envelope versions are refused, not ignored. +- Any future list/table shape must be a new envelope version (or a new key convention) proposed with its own versioning/upgrade rule, CAS/tombstone/sweep inheritance statement, and threshold/GC interaction — none of which is fixed here. +- Explicit non-goal restated: no SQL surface (#10359); when lists/tables are later proposed, composition precedents they must address include append semantics, ordering, and column types — deferred, not decided. ## Decisions -All `agent-preliminary`: work may proceed on these defaults; only a human moves one to confirmed or reversed (see `human-review.md` for the genuine toss-ups). - -- **D001 — Local store is plain per-host SQLite (WAL), not embedded libSQL/Turso, in v1.** Source: issue #10359 item 2 + backup question; evidence: offline-write and file-backup needs (§1, §7); Turso embedded-replica write path (writes to cloud primary; https://docs.turso.tech/features/embedded-replicas/introduction). Status: agent-preliminary. Reversal cost: medium (replaces local engine + backup story; central protocol unchanged). Human review: needed only if v1 must survive host disk loss without sweep (then embedded replicas don't help either — say so). -- **D002 — Central store is one Turso-hosted libSQL primary; per-group DBs are provisioning scopes, not sync topologies, in v1.** Source: #10359 items 2/5; evidence: queue's Turso HTTP pipeline precedent (`pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs:81,671-770`); embedded-replica central-serialization argument (§6, Turso docs). Status: agent-preliminary. Reversal: high (splits the primary). Human review: needed (cost + tenancy shape). -- **D003 — Global namespace = designation flag on the shared registry, no second mechanism.** Source: #10359 item 3; aligns #9116 registry (versioned-design §#9116). Status: agent-preliminary. Reversal: low. Human review: not needed (directly what the issue asks). -- **D004 — Local-first reads with local-override; `--global` pins central; merged list shows shadowed rows.** Source: #10359 item 2 read path. Status: agent-preliminary. Reversal: low. Human review: not needed. -- **D005 — Deletes are tombstones; `revert` appends a restoring version.** Source: sweep-merge need (#10359 item 4) + #9115 tombstone reconciliation precedent. Status: agent-preliminary. Reversal: medium (resurrection bugs if dropped). Human review: not needed unless true-delete has a compliance deadline (then see #9130 true-delete coordination). -- **D006 — Sweep merges under `(owner_user_id, context_id, session_id)` via durable outbox + CAS.** Source: #10359 item 4 + context-propagation note filed the same day. Status: agent-preliminary. Reversal: medium. Human review: needed on keying (user+context vs session-only expiry). -- **D007 — All mutable heads are CAS-versioned; no timestamp LWW; bounded-jitter retry with outbox idempotency keys.** Source: #9114 head rule (CAS on prior generation); store-seam `concurrency_unsupported` posture. Status: agent-preliminary. Reversal: high (correctness invariant). Human review: not needed (invariant, not a toss-up). -- **D008 — Five-agent shared namespace: single-writer-per-key CAS on central; short-TTL reads; no offline fork in v1.** Source: #10359 item 5 question; evidence: claim-path precedent (`fleet-queue/.../claim.rs`); legacy embedded-replica write path (writes to cloud primary; https://docs.turso.tech/features/embedded-replicas/introduction) and Turso Sync last-push-wins (https://docs.turso.tech/sync/usage, https://docs.turso.tech/sync/conflict-resolution) both noted and rejected as the v1 conflict rule. Status: agent-preliminary. Reversal: medium. Human review: needed (freshness/cost tolerance is a product call). -- **D009 — Blob threshold is per-namespace policy (default 256 KiB agent-preliminary) with a per-push override flag, subordinate to the shared partition policy.** Source: #10359 threshold question; precedent: component-F "threshold is policy, never protocol" with 16 KiB conservative start. Status: agent-preliminary. Reversal: low (policy value). Human review: needed (default + flag shape). -- **D010 — Blob identity is exactly #9120 `raw-blake3-256` over exact bytes; reference row format `KvBlobRefV1` reuses that profile.** Source: #9120 A-9120.1 + #9113 shape dispatch; research `part-a-addressing/research.md` #9120 row. Status: agent-preliminary. Reversal: high (identity change). Human review: not needed (follows settled profile). -- **D011 — Broker-token auth to the trusted Cloudflare endpoint; hash is never a bearer credential; reads mint short-lived scoped capabilities.** Source: fleet credential shape (`fleet-gh-credentials.md`, `fleet-secrets`); component-F §5 access rule. Status: agent-preliminary. Reversal: high (auth architecture). Human review: needed (endpoint trust + capability TTL are product/security calls). -- **D012 — Blob GC is component-F mark-and-sweep per `(jurisdiction, tier)` partition; kv references are rows the sweep reads.** Source: component-F §6 + #3401 partitions + #9137 priority note. Status: agent-preliminary. Reversal: medium. Human review: not needed unless grace defaults change. -- **D013 — Lists/tables are manifest compositions over keys; no SQL surface.** Source: #10359 item 6 expansion note; precedents #9118/#9122/#9127. Status: agent-preliminary. Reversal: low. Human review: not needed. +Source of every entry below is agent-preliminary; status of the record is preliminary. Work proceeds on these defaults; implementation evidence (not a gate) owns tuning — see `human-review.md`. + +- **D001 — Local store is plain per-host SQLite (WAL), not embedded libSQL/Turso or libSQL-file, in v1.** Source: issue #10359 item 2 + backup question; evidence: offline-write and file-backup needs (§1, §7); Turso embedded-replica write path (writes to cloud primary; https://docs.turso.tech/features/embedded-replicas/introduction); standalone local-only steelman via Rust SDK (https://docs.turso.tech/sdk/rust/quickstart), rejected §7. Status: preliminary (retained with challenge refinement 2026-11-23). Reversal cost: medium (replaces local engine + backup story; central protocol unchanged). +- **D002 — [REVERSED 2026-11-23, superseded by D014] Central store is one Turso-hosted libSQL primary; per-group scopes are row-level in v1.** Reversal reason: read as either/or vagueness ("provisioning scopes") and an unproved rows-equal-grants posture. Retained content moved into D014 with an explicit grant mechanism and fail-closed policy. Do not cite D002 as active. +- **D003 — Global namespace = designation flag on the distributed registry; resolution always names a registry; the flag never bypasses local-first reads.** Source: #10359 item 3; aligns #9116 registry under the [namespace_definition.rs](../../pkgs/id/crates/id-core/src/namespace_definition.rs) local-registry constraint. Status: preliminary. Reversal: low. +- **D004 — Local-first, identity-scoped reads with local-override; `--global` pins central; merged list shows shadowed rows.** Source: #10359 item 2 read path. Status: preliminary. Reversal: low. +- **D005 — Three delete-related states: clear-override, masking tombstone, history revert.** Source: sweep-merge need (#10359 item 4) + #9115 tombstone reconciliation precedent. Status: preliminary. Reversal: medium (resurrection bugs if collapsed). +- **D006 — Sweep merges full-identity partitions via durable outbox + CAS, with a 15-minute survival archive.** Source: #10359 item 4 + context-propagation note filed the same day. Status: preliminary. Reversal: medium. +- **D007 — All mutable heads are CAS-versioned with append-only version/conflict history and atomic idempotency receipts; no timestamp LWW.** Source: #9114 head rule (CAS on prior generation); store-seam `concurrency_unsupported` posture. Status: preliminary. Reversal: high (correctness invariant). +- **D008 — Five-agent shared namespace: single-writer-per-key CAS on central; ordinary cached reads at most 1 s old; `--global` authoritative bypass; offline work is local intent until sweep commits; KV CAS is not a queue lease.** Source: #10359 item 5 question; evidence: claim-path precedent ([claim.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs)) distinguished, not inherited; legacy embedded-replica write path (writes to cloud primary; https://docs.turso.tech/features/embedded-replicas/introduction) and Turso Sync last-push-wins (https://docs.turso.tech/sync/usage, https://docs.turso.tech/sync/conflict-resolution) both noted and rejected as the v1 conflict rule. Retry: ≤ 5 attempts, jittered exponential backoff capped at 1 s. Status: preliminary (retained with challenge refinement 2026-11-23). Reversal: medium. +- **D009 — Effective blob threshold is a hard inline ceiling (`min` of the KV per-namespace knob, default 256 KiB, and the shared partition ceiling); per-push override forces blob earlier only.** Source: #10359 threshold question; precedent: component-F "threshold is policy, never protocol" with 16 KiB conservative start. Status: preliminary. Reversal: low (policy value). +- **D010 — Blob identity is exactly #9120 `raw-blake3-256` over exact bytes; reference row format `KvBlobRefV1` reuses that profile; central accepts `published` only.** Source: #9120 A-9120.1; profile code in [content_id.rs](../../pkgs/id/crates/id-core/src/content_id.rs). Status: preliminary. Reversal: high (identity change). +- **D011 — Endpoint auth is RP/agent JWT or route-scoped service token per [auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts); the secrets-broker fetch path is not request auth; hash is never a bearer credential; reads mint 5-minute scoped capabilities.** Source: hosted auth ([auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts) lines 140–210); component-F §5 access rule. Status: preliminary. Reversal: high (auth architecture). +- **D012 — Blob GC is component-F mark-and-sweep per `(jurisdiction, tier)` partition sharing the central per-partition serialization point; kv published rows are the authoritative reference set.** Source: component-F §6 + #3401 partitions + #9137 priority note. Status: preliminary. Reversal: medium. +- **D013 — [REVERSED 2026-11-23, superseded by D015] Lists/tables as typed manifest compositions.** Reversal reason: over-designed ahead of the shapes it depends on; Phase 3 is blob-only. Do not cite D013 as active. +- **D014 — Hybrid central placement: shared primary by default; group databases by explicit grant only.** Shared namespaces live on the one fleet-kv primary. A group database exists iff a `kv_grants` row `(group, database, allowed namespaces, allowed ops, policy_epoch)` authorizes it under a fail-closed admission/provisioning policy; no default per-session proliferation. v1 operational integration (migrations, credential wiring, grant policy implementation, backup/restore runbook, health probes) is required Phase 2 scope, not assumed. Source: challenge outcome 2026-11-23 (investigator `ses_e5df780c496ffe06q0f9UZRHmj`) + #10359 "own small database" note bounded by tenancy. Status: preliminary. Reversal: high (splits the primary where grants exist). +- **D015 — Versionable envelope only; list/table semantics deferred.** The KV row envelope is versioned (`kv:raw-v1`, `kv:ref-v1`); future shapes arrive as new envelope versions with their own proposals. No manifests or tables in this plan; Phase 3 is blob-only. Source: challenge outcome 2026-11-23. Status: preliminary. Reversal: low. + +## Challenge record (2026-11-23) + +D001/D002/D008/D013 were reopened under readonly investigator `ses_e5df780c496ffe06q0f9UZRHmj`, whose final read was adopted via the parent session. Outcomes (this revision): + +- D001: retained with refinement — standalone Turso local-only steelmanned (one driver/dialect, trivial sync upgrade) and rejected (one flag from silent replica; SQLite makes no-sync structural). No false dichotomy: three local options are now on record. +- D002: reversed, superseded by D014 — the either/or ("provisioning scopes") is replaced by the hybrid: shared primary default + explicit-grant group DBs under fail-closed policy. Rows-are-not-grants stated explicitly. No default per-session proliferation; no pricing claims (Not checked: Turso per-DB pricing/org limits). +- D008: retained with refinement — retry bounded (≤ 5 attempts, jittered exp backoff, 1 s cap), ordinary cache age ≤ 1 s, `--global` authoritative bypass stated, KV≠queue-lease distinction recorded. Not checked: Turso per-request billing under the five-agent probe. +- D013: reversed, superseded by D015 — Phase 3 blob-only; envelope versions only, no manifests/tables now. +- None of the four outcomes needed a human tossup; all proceed as defaults with implementation evidence owning tuning. +- Re-challenge of the reopened choices is expected after this repair; outcomes will be recorded here with dates. ## Alternatives considered -- **Embedded libSQL replica as the local store.** Lost: writes still serialize on the cloud primary (Turso docs), so it buys a divergence window without removing central arbitration, and it needs network for the write path that session partitions need most. Revisit only with a convergence proof and an offline story. -- **Turso Sync (`push`/`pull`) as the sync substrate.** Lost for v1: local-first and explicit, but conflict strategy is last-push-wins (Turso docs, https://docs.turso.tech/sync/usage), which contradicts the CAS-per-key invariant §5 needs for sweep/claim correctness. Possible later as a transport under CAS, not as the conflict rule. -- **Per-session (or per-group) Turso DB as the unit of sync.** Deferred, not rejected: matches Drew's "handed its own small database" intuition and may become the provisioning story, but in v1 it multiplies primaries without settling the per-key arbitration question. D002 keeps one primary; D006 keeps group scoping at the row/namespace level. -- **Reference-only-everything (no inline threshold).** Lost: for small KV values the reference machinery (staging, capability mint, GC sweep) costs more than the bytes it saves — the same argument component F makes for inline small content, applied one tier down in size. -- **Copy-bytes-into-central-DB (no object plane).** Lost: prices media as database, abandons dedup, and makes publication a divergent copy — component F's evaluation already rejects this for content above threshold, and KV values above threshold are the same case. -- **Bearer-hash reads (hash grants bytes).** Rejected outright: hashes are enumerable and leak by design (sidecars, location index #9115); serving on hash presentation alone fails the access-control soundness axis of #9084. Never the default; not even a flag. -- **Timestamp last-writer-wins for sweep conflicts.** Rejected: loses concurrent sessions' work silently and reintroduces ABA the #9114 head rule already forbids. CAS conflict with both versions retrievable is the floor. +See §7 for the local-store alternatives (embedded replica, standalone local-only, Turso Sync). Remaining: + +- **Per-session Turso DB as the default unit of sync.** Rejected: matches Drew's "handed its own small database" intuition but multiplies primaries without settling per-key arbitration and with unproved pricing/ops cost. D014 keeps the shared primary default; grants are the only path to a real group DB. +- **Reference-only-everything (no inline threshold).** Lost: for small KV values the reference machinery costs more than the bytes it saves. +- **Copy-bytes-into-central-DB (no object plane).** Lost: prices media as database, abandons dedup, makes publication a divergent copy. +- **Bearer-hash reads.** Rejected outright: enumerable, leak-by-design hashes as capabilities fail #9084 soundness. Never the default; not even a flag. +- **Timestamp last-writer-wins for sweep conflicts.** Rejected: silent loss + ABA. CAS conflict with both versions retrievable is the floor. ## Consequences -- Gets easier: session work product survives disconnect by construction; namespaces stay one system with ID (#9107 family) instead of a fleet-private dialect; large values stop pricing as database rows; lists/tables arrive without a second engine; every conflict is a retrievable record, not silent loss. +- Gets easier: session work product survives disconnect by construction (15-minute archive bound); namespaces stay one system with ID (#9107 family) instead of a fleet-private dialect; large values stop pricing as database rows; every conflict is a retrievable record, not silent loss. - Gets harder: every writer implements CAS retry; every large push does staged→verified→published instead of a single write; reads that need linearizability must say `--global` explicitly; GC/tombstone literacy becomes operator knowledge. -- Must stay compatible: #9120 hash profile bytes (never rehash/reinterpret); legacy local state (adopt-or-CAS-merge, never overwrite); broker-token auth shape (no new credential); adapter neutrality (R2 vs RustFS invisible above the adapter, per component I). +- Must stay compatible: #9120 hash profile bytes (never rehash/reinterpret); legacy local state (adopt-or-CAS-merge, never overwrite); supported-credential auth only (no new mechanism smuggled in via the secrets path); adapter neutrality (R2 vs RustFS invisible above the adapter, per component I); the ID signed-journal source-of-truth contract (fleet outbox claims no ID-world authority). ## Open questions -- **O1 — `--global` surface exactness:** flag on every verb vs `fleet kv global ` subcommand. Default in effect: flag (`--global`), matching the issue's sketch. Settles: Phase 1 build (human-review H3). -- **O2 — Sweep keying:** `(owner_user_id, context_id)` with session provenance vs session-expiry alternative. Default: owner+context keying (D006). Settles: Drew/product (human-review H1). -- **O3 — Threshold default + flag name.** Default: 256 KiB per namespace + per-push override (D009). Settles: measurement (#9098-style KV workload) + Phase 1 UX (human-review H2). -- **O4 — Capability TTL + revocation expectations.** Default: short-lived (minutes), revocation = reference removal + TTL-bounded lag (component-F posture). Settles: security/product (human-review H4). -- **O5 — Central tenancy billing/placement:** one primary vs per-group DBs at scale. Default: one primary in v1 (D002); deferred to measurement. Settles: Phase 2 load evidence. -- **O6 — List/table manifest schema versioning.** Deferred to plan: Phase 3 details manifest v1 + upgrade rule; no default needed before then. -- **O7 — True-delete/retention interplay** with #9130-versioning/#3401 erasure flows for tombstoned KV rows. Deferred to plan; D005 tombstones are compatible with either outcome. +- **O1 — `--global` surface exactness:** flag on every verb vs `fleet kv global ` subcommand. Default in effect: flag (`--global`), matching the issue's sketch. Settles: Phase 1 build. +- **O2 — Threshold/ceiling measurement.** Defaults in effect (256 KiB knob, 16 KiB partition start). Settles: measurement (#9098-style KV workload) — evidence, not a gate. +- **O3 — List/table shapes.** Deferred to a later proposal (D015); the envelope versions here are the only seam fixed. +- **O4 — True-delete/retention interplay** with #9130-versioning/#3401 erasure flows for tombstoned KV rows. Deferred to plan; masking tombstones are compatible with either outcome. diff --git a/doc/2026-11-23T12-45-00Z_design_fleet_kv/human-review.md b/doc/2026-11-23T12-45-00Z_design_fleet_kv/human-review.md index 523a8a2e74..f62fc60e33 100644 --- a/doc/2026-11-23T12-45-00Z_design_fleet_kv/human-review.md +++ b/doc/2026-11-23T12-45-00Z_design_fleet_kv/human-review.md @@ -1,45 +1,8 @@ # Human review — `fleet kv` design (#10359) -- Status: agent-preliminary; no human confirmation claimed. Work may proceed on the stated defaults; only a human moves one to confirmed or reversed. -- Scope: this sheet exists so a human can ratify or reverse the toss-ups without re-reading the full design. The full record is `2026-11-23T12-45-00Z_design_fleet_kv.md` in this folder. +- Source: agent-preliminary; status: preliminary. Work proceeds on the stated defaults; implementation evidence owns tuning. +- Scope: this sheet records that no human decision gate blocks the build. The full record is `2026-11-23T12-45-00Z_design_fleet_kv.md` in this folder; design PR https://github.com/developing-today/code/pull/13294 must merge before any phase build. -## H1 — Sweep keying: owner+context vs session-expiry +## None -- Default (D006): merge under `(owner_user_id, context_id, session_id)` provenance via durable outbox + CAS; sessions never evaporate silently. -- Alternative: session-scoped partitions that expire (simpler lifecycle, but a dead session's work product can vanish before anyone sweeps it). -- Why it needs a human: product call about whose work survives disconnect and for how long. -- Reversal cost: medium (re-key sweep + outbox provenance). - -## H2 — Blob threshold default + flag shape - -- Default (D009): per-namespace policy, 256 KiB agent-preliminary, per-push override flag; subordinate to the shared per-partition policy (component E owns the partition threshold; the 16 KiB conservative start in #9084 governs where both apply — the KV knob may only narrow, never widen). -- Alternative: lower default (16–64 KiB, closer to media plane) or higher (1 MiB, fewer references); flag as `--inline-max` vs `--blob-threshold`. -- Why it needs a human: default prices every large value (DB rows vs reference machinery); flag name is CLI UX. -- Reversal cost: low (policy value + flag alias). - -## H3 — `--global` surface exactness (O1) - -- Default: flag (`fleet kv get --global`), matching the issue sketch; exactness settles in Phase 1 build. -- Alternative: `fleet kv global ` subcommand. -- Agent recommendation: flag (smaller surface, composes with `--namespace`). -- Reversal cost: low. - -## H4 — Capability TTL + revocation expectations (O4) - -- Default (D011): short-lived capabilities (minutes); revocation = reference removal + TTL-bounded lag (component-F posture). -- Alternative: longer TTLs (fewer mints, slower revocation) or instant-revocation machinery. -- Why it needs a human: security/product call; tier docs must not promise instant byte-level revocation. -- Reversal cost: high (auth architecture). - -## H5 — Central tenancy at scale (O5, D002) - -- Default: one fleet-kv Turso primary in v1; per-group DBs are provisioning scopes, not sync topologies. -- Alternative: per-session/per-group Turso DBs as the unit of sync (matches the issue's "own small database" intuition, multiplies primaries without settling per-key arbitration). -- Why it needs a human: cost + tenancy shape; needs Phase 2 load evidence. -- Reversal cost: high (splits the primary). - -## Explicitly not asking - -- D003/D004/D005/D007/D010/D012/D013: direct readings of the issue or settled ID/plane contracts; reversing one means reopening that contract, not this design. -- F12.5 `kv`/`blob` provider small caps (#1062) are a different surface (in-world sandbox ceilings) and are not ratified or changed here. -- Workload figures (five agents, key counts, write rates) are planning fixtures, not measured or free-tier guarantees. +No open tossup requires a human call before implementation. Prior H1–H5 (sweep keying, threshold default, `--global` surface, capability TTL, central tenancy) are resolved as defaults in effect in the record (D006/D009/O1/D011/D014); each names the evidence that will tune it. A human may still ratify or reverse any D-entry at any time, but nothing waits on one. From 612607787e4fe2654de147b75d7bf7297acc2620 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 07:13:35 -0600 Subject: [PATCH 3/5] =?UTF-8?q?docs(fleet-kv):=20round2=20correctness=20re?= =?UTF-8?q?pairs=20=E2=80=94=20ScopeId,=20fence,=20idem=20keys,=20publicat?= =?UTF-8?q?ion=3D=20CAS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit (1) Central key is (scope_id, registry_id, ns, key); shared scope per shared namespace, private scopes separate, plain read checks overlay then one selected scope only. (2) clear-override advances a generation fence cancelling pending intents; in-flight CAS states linearization. (3) 15m is a checkpoint TARGET; Phase 2 archives inline-only, over-threshold reports protection_unavailable_needs_phase3; local working files streamed + atomic ref. (4) cache miss/expiry refreshes or typed stale; --allow-stale opt-in. (5) GC roots incl. versions/conflicts/ archive refs/pins. (6) group DBs inline-only; blob_requires_shared_primary. (7) idem key (writer, incarnation, outbox UUID) + fingerprint; rebase is new intent. Final re-challenge recorded (D001/D008/D014/D015 sound). --- .../2026-11-23T12-45-00Z_design_fleet_kv.md | 58 ++++++++++--------- 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md index fd06dfcfab..1e54192b88 100644 --- a/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md +++ b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md @@ -7,13 +7,13 @@ - Issues: https://github.com/developing-today/code/issues/10359 (design owner), https://github.com/developing-today/code/issues/9107 (ID core epic: namespaces/ID shapes), https://github.com/developing-today/code/issues/9120 (content-addressed namespace core), https://github.com/developing-today/code/issues/9084 (content-addressed media/data plane), tracking https://github.com/developing-today/code/issues/12892 - Design PR: https://github.com/developing-today/code/pull/13294 — must merge before any phase build starts. - Standalone design: there is no workflow research package for this item (no S0–S5 intake/lease state exists); this record is the decision record #10359 acceptance asks for, adapted honestly to that fact. -- Pre-change snapshot (not "no design exists"): as of the 2026-11-14 triage note on #10359, greps found no `fleet kv` surface in the fleet crates and no fleet-kv schema on main. This document, created 2026-11-23, is the first such record; "nothing exists" below means no implementation, not the absence of this doc. +- Pre-change snapshot (not "no design exists"): as of the 2026-11-17 triage note on #10359, greps found no `fleet kv` surface in the fleet crates and no fleet-kv schema on main. This document, created 2026-11-23, is the first such record; "nothing exists" below means no implementation, not the absence of this doc. ## Intent Drew (2026-11-14, #10359) asked for a `fleet kv get/set/list` verb family in the `fleet` multicall binary for arbitrary bytes, explicitly not the secrets store. Each host has a local store (backed up); there is also a central store. Reads resolve local first and fall back to global; a local value overrides the same key in global. An explicit global operation (`fleet kv --global …`, exact surface TBD) always addresses central. Keys live in namespaces; a "global namespace" is a namespace designated global, not a second mechanism. Namespaces map to the ID project's namespace concept (#9107 / #9120), not a fleet-private reinvention. A session's local partition must survive disconnect: a sweeper pushes it into the central store keyed under the owning user id (+ context id). Every fleet-launched session — and other partitions (a repo, the fleet project itself, the mcpx namespace) — can be handed its own small database, likely Turso, with the embedded-replica attraction (fast local reads, automatic sync). The design must answer, with a workload sketch, what five agents concurrently pulling (and writing) a shared mid-size namespace actually get: replica sync semantics, writer topology, conflict behaviour — stated, not assumed. Values are arbitrary bytes; above a configurable threshold (Drew named 250 KB / 500 KB / 1 MB / 1 GB as the knob shape), a push keeps bytes local-working but routes them on central sync through a trusted Cloudflare endpoint into the content-addressed R2 bucket, storing key/namespace/name plus content hash + bucket link (#9084's reference pattern). Later, lists and tables ride the same substrate — this design reserves only a versionable bytes/reference envelope for them (D015); list/table semantics are deferred, not designed here. -Today no implementation exists (pre-change snapshot above). The fleet pieces that do exist and bound this design: the multicall/registry surface ([verbs.md](../../pkgs/fleet/docs/verbs.md), `pkgs/fleet/crates/fleet-registry`), named-secret resolution via the secrets broker ([fleet-secrets lib.rs](../../pkgs/fleet/crates/fleet-secrets/src/lib.rs), [fleet-gh-credentials.md](../../pkgs/fleet/docs/fleet-gh-credentials.md) — a secret-*fetch* protocol, not request authentication), the single front door for agents ([fleet-agent-front-door design](../../doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md)), hosted request authentication ([auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts): RP/agent JWTs or route-scoped service tokens; data-plane credentials refused), and Turso-backed queue state over the libSQL HTTP pipeline ([core.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs)). +Today no implementation exists (pre-change snapshot above). The fleet pieces that do exist and bound this design: the multicall/registry surface ([verbs.md](../../pkgs/fleet/docs/verbs.md), `pkgs/fleet/crates/fleet-registry`), named-secret resolution via the secrets broker ([fleet-secrets lib.rs](../../pkgs/fleet/crates/fleet-secrets/src/lib.rs), [fleet-gh-credentials.md](../../pkgs/fleet/docs/fleet-gh-credentials.md) — a secret-_fetch_ protocol, not request authentication), the single front door for agents ([fleet-agent-front-door design](../../doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md)), hosted request authentication ([auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts): RP/agent JWTs or route-scoped service tokens; data-plane credentials refused), and Turso-backed queue state over the libSQL HTTP pipeline ([core.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs)). ## Design @@ -45,37 +45,38 @@ host local (SQLite file, WAL) central (shared Turso primary) Tables above are logical names for the phased build issues, not a claim that schema already exists. No `fleet kv` schema exists on main today (pre-change snapshot). -**Complete logical identity.** Every local row is keyed by the full tuple `(owner_user_id, context_id, partition_id, namespace, key)`, where `partition_id` is the session id or the owning group (repo / fleet project / mcpx namespace). Central shared heads are keyed `(namespace, key)` with an `owner_scope` column; the survival archive (§7) retains the full tuple plus the sweep receipt. Consequences, stated as rules: +**Complete logical identity.** Every local row is keyed by the full tuple `(owner_user_id, context_id, partition_id, namespace, key)`, where `partition_id` is the session id or the owning group (repo / fleet project / mcpx namespace). Central addressing adds two coordinates: the central key is `(scope_id, registry_id, namespace, key)`, where `registry_id` is the fleet registry handle (`fleet-kv-central`, §2) and `scope_id` selects exactly one central scope. The survival archive (§7) retains the full local tuple plus the sweep receipt. Consequences, stated as rules: - A local read filters by the caller's full identity: `(owner, ctx, partition)` from the authenticated context. A local read can never return another user/session/partition's row — there is no `(ns, key)`-only lookup path anywhere in v1. The `(ns, key)`-only shape from the earlier draft is withdrawn. -- Central shared heads are a different mapping: `(namespace, key) → head` with `owner_scope` authorizing which identities may read/write it. Row-level scope is authorization metadata on a shared head, not a grant: unless the build ships an explicit scoped-facade (per-scope views enforced at the pipeline layer), all central access goes through the single primary's CAS path with the namespace write policy checked per write. No claim is made that "rows equal database grants." -- The survival archive is the third mapping: full-identity rows plus sweep receipts, written only by the sweep path, read only for restore/audit. +- Central scope selection is explicit, with no extra fallthrough: a plain read checks the local overlay for the full identity tuple, then exactly one selected central scope — the namespace's scope for the caller's context (shared scope for shared namespaces, private scope for user/context-private namespaces). There is no second fallthrough scope beyond that. +- A shared namespace resolves to one shared `scope_id` for all authorized agents: one head per `(shared_scope, registry, ns, key)`, so a tombstone written in the shared scope affects all shared readers. A user/context-private namespace resolves to a private `scope_id`; its rows never intersect another identity's reads. The archive is the third mapping (full-identity rows + receipts, restore/audit only). +- Row-level scope is authorization metadata on a shared head, not a grant: unless the build ships an explicit scoped-facade (per-scope views enforced at the pipeline layer), all central access goes through the single primary's CAS path with the namespace write policy checked per write. No claim is made that "rows equal database grants." **Local (D001).** One SQLite file per host, e.g. `~/.local/share/fleet/kv/local.db`, WAL mode, holding `kv_local`, a cached copy of `kv_namespaces` and `kv_grants`, the durable `outbox`, and local copies of conflict/receipt rows for offline inspection. Rationale: the local store must accept writes while offline, survive process death, and back up as a file — plain SQLite does all three with zero network dependency. §7 records the investigated alternatives. **Central (D014; D002 reversed/superseded).** Hybrid placement: -- **Shared namespaces (the v1 default):** one fleet-kv Turso database as the libSQL primary for KV heads, append-only version/conflict history, idempotency receipts, grant rows, and blob *references*; bytes live in the object plane (§6). Clients use the same transport shape the queue already proves: libSQL HTTP pipeline from Rust ([core.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs) lines 1–81 and 532–770; `DEFAULT_TURSO_URL` at line 10 shows the pattern, not the kv database). Central writes serialize per key on the primary's transactions (conservative outbox + central transaction sequencer, §5); this design assumes no automatic multi-master CAS from any sync product. -- **Group databases (explicit grant only):** a real per-group Turso DB exists iff a `kv_grants` row `(group, database, allowed namespaces, allowed ops, policy_epoch)` authorizes it, issued through a fail-closed admission/provisioning policy (admission checks group membership + namespace ownership; provisioning mints the DB, writes the grant row, and replicates the namespace subset; unknown group or namespace refuses). No default per-session proliferation: sessions do not get databases unless a grant says so. Not checked: per-database pricing and Turso org limits for grant-provisioned DBs — no cost claim is made; Phase 2 measures against the shared primary only. +- **Shared namespaces (the v1 default):** one fleet-kv Turso database as the libSQL primary for KV heads, append-only version/conflict history, idempotency receipts, grant rows, and blob _references_; bytes live in the object plane (§6). Clients use the same transport shape the queue already proves: libSQL HTTP pipeline from Rust ([core.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs) lines 1–81 and 532–770; `DEFAULT_TURSO_URL` at line 10 shows the pattern, not the kv database). Central writes serialize per key on the primary's transactions (conservative outbox + central transaction sequencer, §5); this design assumes no automatic multi-master CAS from any sync product. +- **Group databases (explicit grant only):** a real per-group Turso DB exists iff a `kv_grants` row `(group, database, allowed namespaces, allowed ops, policy_epoch)` authorizes it, issued through a fail-closed admission/provisioning policy (admission checks group membership + namespace ownership; provisioning mints the DB, writes the grant row, and replicates the namespace subset; unknown group or namespace refuses). No default per-session proliferation: sessions do not get databases unless a grant says so. Simplest v1 rule: group DBs are **inline-only** — they store no blob references and no grant covers blob placement. Reference writes land on the shared primary only (one GC fence, §9–§10); a blob-needing write addressed to a group scope fails with a typed refusal requiring shared-primary placement (`blob_requires_shared_primary`), never an automatic move. Group blob support is deferred to a common partition service with shared outbox watermarks, not designed here. Phase 2 must not accept unrestricted bytes into a group DB past the effective ceiling: the ceiling check runs before any group-DB write. Not checked: per-database pricing and Turso org limits for grant-provisioned DBs — no cost claim is made; Phase 2 measures against the shared primary only. - Per-user Turso DB credentials (component-E data-plane tokens) are not service authentication and are refused at the hosted front door by rule ([auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts) lines 20–33 and 134–159 `data_plane_credential_refused`); central KV access goes through the authenticated pipeline path, never by presenting a data-plane token. - **v1 operational integration (required, not pretended-shipped):** the Phase 2 build must land migrations for all central tables above, the pipeline credential wiring, the grant/provisioning policy implementation, per-partition backup/restore runbook entries, and central health/readiness probes — a primary that none of this exists for is not a primary. Phase 2 acceptance (§4 of the phase-2 draft) gates on these, not on the row protocol alone. -**ID journal relationship (binding).** The ID serverless storage contract ([storage contract](../../doc/2026-11-17_decision_id5863_storage_contract.md)) fixes the signed journal as the system of record for ID world state; fleet-kv does not mint a competing journal. Scope boundary, stated exactly: KV row state is fleet-owned application state, not ID world state. Its durability contract is a bounded Fleet projection protocol — per-host outbox journal of *unsigned, fleet-scoped write intents* → central primary CAS transactions — which claims no ID-world authority, carries no ID signatures, and is never presented as an ID journal. Content blobs remain fully under the ID source-of-truth contract (content identity per #9120, admission per the signed gate); fleet-kv rows reference that content, they do not re-journal it. +**ID journal relationship (binding).** The ID serverless storage contract ([storage contract](../../doc/2026-11-17_decision_id5863_storage_contract.md)) fixes the signed journal as the system of record for ID world state; fleet-kv does not mint a competing journal. Scope boundary, stated exactly: KV row state is fleet-owned application state, not ID world state. Its durability contract is a bounded Fleet projection protocol — per-host outbox journal of _unsigned, fleet-scoped write intents_ → central primary CAS transactions — which claims no ID-world authority, carries no ID signatures, and is never presented as an ID journal. Content blobs remain fully under the ID source-of-truth contract (content identity per #9120, admission per the signed gate); fleet-kv rows reference that content, they do not re-journal it. **Backup/restore (§7, D001 detail; numbers are defaults in effect).** Two destinations, both concrete: 1. **Local file snapshot** (survives process death, not disk loss): SQLite backup API or filesystem snapshot of file + WAL into `~/.local/share/fleet/kv/backups/` every **6 h**, plus a `backup manifest` row (host, file hash, WAL frame, timestamp) in the outbox. RPO for process-death recovery: last write (WAL replay). -2. **Survival archive** (survives disk loss): the sweeper uploads the session dirty set — including large *working* bytes staged via §9, not inline — to the central archive scope on session end and every **15 min** during a live session (RPO ≤ 15 min for acknowledged local writes). Large working blobs are part of the snapshot: the manifest lists staged content ids, and restore re-publishes or re-links them. +2. **Survival archive** (survives disk loss when reachable): the sweeper uploads the session dirty set to the central archive scope on session end and every **15 min** during a live session. The 15-minute figure is an online successful-checkpoint TARGET, not an unconditional RPO: with no network, no successful checkpoint, or disk destruction before the next upload, the loss window for unarchived writes is unbounded, and the CLI must report that plainly. The Phase 2 archive carries inline payloads only, up to the effective threshold (§8); over-threshold bytes stay local-working (§8) until Phase 3 exists, and the archiver explicitly reports them as `protection_unavailable_needs_phase3` instead of pretending they are archived. Large working blobs are part of the snapshot only once reference placement exists: the manifest lists staged content ids, and restore re-publishes or re-links them. -Restore: fetch latest snapshot (local dir first, archive scope if the disk is gone), open read-only to verify, then adopt (fresh host) or three-way CAS-merge through §4 (returning host with divergent rows). **Durability boundary, stated plainly:** an acknowledged local write lost to disk destruction *before* the next 15-minute archive upload is unrecoverable — that is the loss window (≤ 15 min of local writes, plus any over-threshold working bytes not yet staged). Backup never writes bytes into the KV row space; large local working bytes stay local-working until staged. +Restore: fetch latest snapshot (local dir first, archive scope if the disk is gone), open read-only to verify, then adopt (fresh host) or three-way CAS-merge through §4 (returning host with divergent rows). **Durability boundary, stated plainly:** an acknowledged local write lost to disk destruction _before_ the next 15-minute archive upload is unrecoverable — that is the loss window (≤ 15 min of local writes, plus any over-threshold working bytes not yet staged). Backup never writes bytes into the KV row space; large local working bytes stay local-working until staged. ### 2. Namespaces and registry identity (coordinate with #9107 / #9116, not parallel) Namespaces reuse the ID local-namespace-registry concept: a namespace definition binds `{namespace_id, core_id, handler/encoding profile, read/write policy, shorthand policy, schema version}`, server-local, versioned and audited (Part A versioned design, §#9116). The ID contract constrains this design ([namespace_definition.rs](../../pkgs/id/crates/id-core/src/namespace_definition.rs) lines 24–32 and 594–645): registries are local, resolution always names a registry (`Resolver::resolve(registry, namespace)`), and there is no global registry or fallback. Fleet-kv therefore defines its registry identity explicitly instead of a "shared registry": -- **Fleet registry identity:** the central `kv_namespaces` table is the distribution source under registry handle `fleet-kv-central` (a `RegistryId::Handle`, [namespace_definition.rs](../../pkgs/id/crates/id-core/src/namespace_definition.rs) lines 424–440). Each host holds a server registry (`RegistryId::Server(host_id)`) whose fleet-namespace definitions are **replicas provisioned from** `fleet-kv-central`: on `fleet kv sync` (and at most every **1 h**, default in effect) the host pulls the central table at its watermark and replaces its cached definitionsassigning the central `policy_epoch`. Reads resolve in the host's server registry only; there is never a cross-registry fallback. -- `kv_namespaces` rows carry `(namespace_id, core_binding, global_flag, blob_threshold, policy_epoch, owner_scope)`. -- `global_flag` is designation only (D003): "global namespace" = a namespace whose *default address scope* includes central. It does not change resolution (still the named registry), and it **must not bypass the local-first read rule**: even in a global-flagged namespace, plain `get` reads the caller's local overlay first and only falls through on miss; only `--global` pins central (§3). A flag that silently reordered reads would be a second lookup path, which this design forbids. +- **Fleet registry identity:** the central `kv_namespaces` table is the distribution source under registry handle `fleet-kv-central` (a `RegistryId::Handle`, [namespace_definition.rs](../../pkgs/id/crates/id-core/src/namespace_definition.rs) lines 424–440). Each host holds a server registry (`RegistryId::Server(host_id)`) whose fleet-namespace definitions are **replicas provisioned from** `fleet-kv-central`: on `fleet kv sync` (and at most every **1 h**, default in effect) the host pulls the central table at its watermark and replaces its cached definitions assigning the central `policy_epoch`. Reads resolve in the host's server registry only; there is never a cross-registry fallback. +- `kv_namespaces` rows carry `(namespace_id, scope_id, core_binding, global_flag, blob_threshold, policy_epoch)`. +- `global_flag` is designation only (D003): "global namespace" = a namespace whose _default address scope_ includes central. It does not change resolution (still the named registry), and it **must not bypass the local-first read rule**: even in a global-flagged namespace, plain `get` reads the caller's local overlay first and only falls through on miss; only `--global` pins central (§3). A flag that silently reordered reads would be a second lookup path, which this design forbids. - Content-blob identity inside any namespace is exactly the settled #9120 initial profile: unkeyed BLAKE3-256 over exact bytes, 32-byte digest (A-9120.1; research `part-a-addressing/research.md` #9120 row; implementation slices `part-a-addressing/implementation-slices.json` A9120-content-id; profile code in [content_id.rs](../../pkgs/id/crates/id-core/src/content_id.rs)). Fleet-kv neither redefines the hash nor invents a parallel digest (binding constraint shared with #9120's "neither this spec nor §3's may redefine the hash"). - Parse/URI transport, if ever exposed as `id://`, follows #9117 syntax transport only; this design mints no IDs and establishes no authority beyond the namespace's own write policy. Admission-gate semantics, if referenced, follow [admission_gate.rs](../../pkgs/id/crates/id-core/src/admission_gate.rs); fleet-kv defines its own grant rows (D014) and does not reinterpret the ID gate. @@ -87,13 +88,13 @@ Coordination boundary: #9116 owns the registry model; #9117 owns URI syntax; #91 Verbs: `fleet kv get|set|list` plus `delete`, `clear-override`, and `revert`. `--global` pins central for the verb it modifies; `--namespace NS` selects scope. -- **Read path (local-first, identity-scoped):** resolve the caller's `(owner, ctx, partition)` from the authenticated context; read the local overlay for the full tuple; on miss, fall through to the central head the caller's scope authorizes. A live local overlay row *overrides* the same key in central (D004). `--global get` skips local entirely and reads the central head at its current version — the authoritative bypass. `list` merges both scopes with origin marks (`local|central|both`, local winning display) and never silently hides the shadowed row — show it as `shadowed-by-local` / `shadowed-by-central` in verbose output. +- **Read path (local-first, identity-scoped):** resolve the caller's `(owner, ctx, partition)` from the authenticated context; read the local overlay for the full tuple; on miss, fall through to the central head the caller's scope authorizes. A live local overlay row _overrides_ the same key in central (D004). `--global get` skips local entirely and reads the central head at its current version — the authoritative bypass. `list` merges both scopes with origin marks (`local|central|both`, local winning display) and never silently hides the shadowed row — show it as `shadowed-by-local` / `shadowed-by-central` in verbose output. - **Set path:** default writes the local overlay + enqueues outbox work; `--global set` writes central directly via CAS (authenticated; §9 for large values). Local sets carry the full identity tuple plus `(value-or-ref, base_version, writer_session, ts)`. - **Delete — three distinct states, three distinct operations (D005):** - 1. `clear-override` — removes the local overlay row for the full identity tuple. Effect: the central value (if any) becomes visible again locally. Sweeps nothing (there is no overlay left to sweep). + 1. `clear-override` — removes the local overlay row for the full identity tuple **and** advances that tuple's local generation fence, which atomically cancels/supersedes every pending local intent (unacked outbox rows) for the same key/identity: cancelled intents never sweep. Effect: the central value (if any) becomes visible again locally. Already-committed central state is unaffected — there is no overlay left to sweep and nothing committed is uncommitted. A sweep CAS already in flight for a cancelled intent cannot uncommit the clear: the sweeper checks the fence before ack, and if the CAS landed first the receipt is returned as-is with the linearization stated (CAS linearized before clear; the next sweep carries no intent, so central keeps the swept value while local reads show central — the operator is told exactly this). Sweeps nothing new. 2. **Masking tombstone** (`delete`) — writes a local tombstone row for the tuple. Effect: the key reads absent locally and in merged `list` (shown with `masked` origin under `--include-tombstones`), while central is untouched until sweep. Sweeps as a mask: central records the tombstone under the sweeping identity's scope; other scopes' heads are unaffected. 3. **History revert** (`fleet kv revert NS KEY --to `) — appends a new version whose value equals the named prior version (new version number, full provenance). Operates on version history, never on the overlay: it does not clear overrides and does not mask central. -- **Freshness (states exactly which read is authoritative):** `--global get` reads authoritative central state at the returned head version. Plain `get` reads the local overlay if present, else the freshest central snapshot the host has pulled (snapshot timestamp shown). `sync` refreshes two things only: the cached namespace definitions (≤ 1 h staleness) and the central snapshot the host caches per namespace. Ordinary cached reads are at most **1 s** old (default in effect); `--no-cache` forces a central read. There is no background sync promise in v1. +- **Freshness (states exactly which read is authoritative):** `--global get` reads authoritative central state at the returned head version. Plain `get` reads the local overlay if present (immediate, works offline — overlay reads never block on network), else the freshest central snapshot the host has pulled (snapshot timestamp shown). Ordinary central cache entries are at most **1 s** old (default in effect): on miss or expiry the reader refreshes, and if refresh fails it returns a typed `unavailable`/`stale` error — never a silently old value. `--allow-stale` is the explicit opt-in to read the expired snapshot, always labelled with its age. There is no background sync promise in v1. ### 4. Durable session-partition sweep @@ -103,7 +104,7 @@ A session's local partition does not evaporate at disconnect (D006). On session 2. For each key: `central_CAS(namespace, key, expected=base_version, new=row)` against `kv_heads`. 3. On success: write the idempotency receipt, then mark the outbox row done (order fixed: CAS → receipt+ack, §5). On conflict: run the §5 rule (versioned conflict, never silent last-writer-wins across sessions), append the conflict record, and leave both versions retrievable. 4. Masking tombstones sweep through the same CAS path as masks scoped to the sweeping identity. -5. Large values sweep by reference: the sweeper uploads through §9 first, then CASes the reference row. Central never accepts an unpublished blob reference. +5. Large values sweep by reference only once Phase 3 exists: in Phase 2 the sweeper uploads nothing — over-threshold keys stay queued as local-working and are reported `protection_unavailable_needs_phase3`; the Phase 3 sweeper uploads through §9 first, then CASes the reference row. Central never accepts an unpublished blob reference. Sweep is idempotent (outbox row ids + receipts make re-runs safe) and recoverable (crash between upload and CAS leaves a staged blob that staging TTL reaps, per #9084 component-F staging rules; crash between CAS and ack re-runs CAS, and the atomic receipt returns the original result instead of a spurious new conflict). "Two sessions sweeping the same key" is therefore a routine CAS conflict, not a special case. @@ -114,7 +115,7 @@ Every mutable head uses compare-and-swap on `(namespace, key, version)` (D007), - `kv_heads`: one row per `(namespace, key)` — the current head `(version, value-or-published-ref, writer, ts)`. - `kv_versions`: append-only; every CAS success appends `(namespace, key, version, parent_version, value-or-ref, writer, ts)`. Retention: full history while the key lives; tombstoned keys retain history (true-delete deferred to #9130 coordination). - `kv_conflicts`: append-only; every failed CAS appends `(namespace, key, expected, actual, proposed_value, writer, ts)` and the loser receives the conflict id. "Both versions retrievable" reads: `kv get --version V` replays `kv_versions`; `kv conflicts NS KEY` lists conflict records. -- `idem_receipts`: `(outbox_id → {namespace, key, version, result})`, written **atomically with the CAS in one central transaction**. A replay of an already-applied `outbox_id` — even after the head has since advanced — returns the recorded result instead of attempting a new CAS (so it can never become a spurious new conflict). +- `idem_receipts`: key `(authenticated_writer, host_incarnation_UUID, outbox_UUID)` → `{request_fingerprint, namespace, key, version, result}`, written **atomically with the CAS in one central transaction**. The fingerprint is an immutable hash of the intent body (namespace, key, expected version, value-or-ref, op); the host incarnation UUID is generated once per durable host identity and survives process death (stored beside the local DB), so a reborn sweeper never reuses another incarnation's keys. An exact retransmit (same key, same fingerprint) — even after the head has since advanced — returns the recorded result instead of attempting a new CAS (so it can never become a spurious new conflict). A reused key with a different fingerprint is a typed `idempotency_key_reuse` error, never a silent overwrite. Rebasing after a conflict is an explicit new intent with a new outbox UUID (carrying `supersedes: `), never a silent re-read plus opaque-byte overwrite. Local dirty revisions keep ancestry links; the outbox is a queue that resolves dependency order (a revert names its base version; a tombstone supersedes its generation), not a bag of latest-writes. - Retries are bounded with jitter: at most **5 attempts**, jittered exponential backoff capped at **1 s** per backoff (defaults in effect). Each attempt carries the outbox id as the idempotency key. - Recovery order is fixed: outbox → upload (§9) → CAS+receipt (atomic) → ack. Any crash restarts at the oldest unacked outbox row. Staged-but-unpublished blobs are never referenced by any read path, so they are safe to reap by TTL. - `concurrency_unsupported` is a typed error if some future adapter cannot CAS: fail closed, never degrade to silent overwrite (same posture as the V2 store seam in the Part A versioned design). @@ -126,7 +127,7 @@ Workload assumed (planning fixture, stated so a later measurement can replace it - **Writer topology (D008): single-writer-per-key by CAS against the central primary.** There is no multi-master convergence in v1: all writers serialize per key on `kv_heads` CAS. KV CAS is not a queue lease: unlike the fleet queue's claim path ([claim.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs)), there are no leases, no expiry, no steal — a failed CAS is a versioned conflict for a human or agent to resolve, never a grant that times out. Rows are not database grants: sharing a namespace grants nothing by itself; every write passes the namespace write policy at the pipeline layer. - **Replica sync semantics:** no embedded replicas in v1 (D002 rationale, retained by D014 for shared namespaces). Agents read central directly (ordinary cached reads at most 1 s old, documented per namespace) or read a snapshot pulled at task start; `--global` bypasses the cache and reads the authoritative head. There is no background replica convergence to reason about, and therefore no divergence window beyond the stated cache age. Offline writes are permitted as **local intents**: they are ordinary overlay rows, fully usable locally, but they are not shared or committed until sweep CAS succeeds — "no offline fork" means no divergent shared history, not that offline work is forbidden. - **Freshness:** reads state their source (`local|central@version|snapshot@age`); claim/status keys that need linearizability use `--global` reads + CAS writes. Nothing else gets linearizability, and the CLI says so. -- **Contention:** same-key write contention fails CAS fast (≤ 5 attempts, §5); hot keys should be claim/checkpoint-shaped rather than counter-shaped. No counters in v1 KV rows — a stored counter is a second copy of the truth and drifts (same argument as the [content-addressed media data-plane design](../../doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md) §6 against reference counting). +- **Contention:** same-key write contention fails CAS fast (≤ 5 attempts, §5); hot keys should be claim/checkpoint-shaped rather than counter-shaped. No atomic increment/counter semantic verb exists in v1: values are arbitrary bytes and may well encode counters, but a client read-modify-write must go through CAS (or use an existing queue/ID primitive) — the store offers no inc/dec operation and no metadata field bans any encoding. - **Cost:** central rows are small (values inline only at/below threshold; §8). Five agents polling `list` at 1 Hz against Turso HTTP is the abuse case: mitigate with the documented 1 s cache age, snapshot reads, and (if needed) a per-namespace read budget owned by the same policy epoch as the threshold. Not checked: per-request Turso billing for this workload — no billing claim is made here; measure on the fleet-kv Turso DB once Phase 2 lands. Why not embedded replicas for the five-agent case: embedded-replica writes go to the cloud primary anyway (https://docs.turso.tech/features/embedded-replicas/introduction), so five replica-holders writing the same key still serialize centrally — replicas add a divergence/catch-up window without removing the central serialization point. v1 keeps that serialization explicit and auditable. @@ -151,16 +152,17 @@ Values are arbitrary bytes with a streaming interface (no full-buffer requiremen - **Per-namespace policy value** (`kv_namespaces.blob_threshold`, bytes), default **256 KiB** — inside Drew's named shape (250 KB / 500 KB / 1 MB / 1 GB) at its low end. This default is subordinate to the shared per-partition placement policy, not a competing protocol: where KV bytes and #9084 component-F content share a partition, component E owns the threshold and the 16 KiB conservative starting default ([media data-plane design](../../doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md) §Recommendation) governs placement until #9098 measurements move it. The **effective threshold is a hard inline ceiling**: `effective = min(namespace knob, partition ceiling)`. Changing either changes placement of new content only, never identity or access (policy, never protocol). - **Per-push override** (`--force-blob`, exact flag name owned by Phase 1): one direction only — force blob treatment at or below the effective threshold (e.g. a small value that should not live in the row store). There is no force-inline override: nothing may place bytes inline above the effective ceiling. The earlier `--inline-max` both-directions sketch is withdrawn as a fatal ceiling conflict. -- At or below the effective threshold: bytes inline in the row. Above: §9 reference path. Promotion (inline → referenced) is a new version with identical read semantics; no client-visible change. +- At or below the effective threshold: bytes inline in the row. Above: §9 reference path. **Local vs central placement distinguished:** the threshold governs central rows. Locally, over-threshold bytes live as local-working bytes — a streamed working file under `~/.local/share/fleet/kv/working/` plus an atomic local DB ref row (write file, fsync, then commit ref; readers never see a half-file). A 100 KiB local value is therefore fine even where a 16 KiB partition ceiling applies: the ceiling bans central _inline_ placement, not local working storage. Promotion (inline → referenced) is a new version with identical read semantics; no client-visible change. +- Streaming budget (defaults in effect): push/pull I/O moves in ≤ 64 KiB chunks with resident working set ≤ 1 MiB; values above the in-memory cap are never fully buffered. ### 9. Trusted Cloudflare endpoint, supported credential path, reference-based read (no bearer hash) Auth uses only credentials the hosted front door actually validates (D011, corrected after review — the earlier draft cited the secrets-broker fetch path, which is withdrawn): -- **Push path:** the pusher authenticates to the trusted Cloudflare endpoint with either (a) an RP/agent JWT validated as in [auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts) lines 140–184 (issuer/audience check, subject mapped to a tenancy `bindingId`; agent credentials must carry lane/session claims), or (b) a route-scoped service token validated at lines 187–201 with `authorizeRoute` scoping it to the kv-upload door (lines 206–210). The endpoint then checks the namespace write policy for `(binding_id, context, namespace)` and only then accepts staged bytes. The content hash travels as an *assertion to be verified*, never as authority. The [fleet-secrets](../../pkgs/fleet/crates/fleet-secrets/src/lib.rs) broker-first resolution (lines 15–28) plus [fleet-gh-credentials.md](../../pkgs/fleet/docs/fleet-gh-credentials.md) is a named-secret *fetch* protocol and is not a request-authentication mechanism anywhere in this design. +- **Push path:** the pusher authenticates to the trusted Cloudflare endpoint with either (a) an RP/agent JWT validated as in [auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts) lines 140–184 (issuer/audience check, subject mapped to a tenancy `bindingId`; agent credentials must carry lane/session claims), or (b) a route-scoped service token validated at lines 187–201 with `authorizeRoute` scoping it to the kv-upload door (lines 206–210). The endpoint then checks the namespace write policy for `(binding_id, context, namespace)` and only then accepts staged bytes. The content hash travels as an _assertion to be verified_, never as authority. The [fleet-secrets](../../pkgs/fleet/crates/fleet-secrets/src/lib.rs) broker-first resolution (lines 15–28) plus [fleet-gh-credentials.md](../../pkgs/fleet/docs/fleet-gh-credentials.md) is a named-secret _fetch_ protocol and is not a request-authentication mechanism anywhere in this design. - **Read path:** a bearer hash grants nothing (binding rule shared with the [media data-plane design](../../doc/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane/2026-11-23T03-04-00Z_design_content-addressed-media-data-plane.md) §5 "the hash is not a capability"). Readers resolve their KV row authorization first (local overlay or central head, per namespace policy + authenticated context), then receive a **short-lived (5 min, default in effect), object+operation-scoped capability** minted from live reference state; the adapter serves bytes only under that capability, with replica fallback during placement movement (same contract as the [self-hosted tier adapters design](../../doc/2026-11-21T21-40-00Z_design_self_hosted-tier-adapters/2026-11-21T21-40-00Z_design_self_hosted-tier-adapters.md) object adapter contract). -- **Upload safety:** `put_staged → verify (length + BLAKE3-256 recomputed on receipt, streaming) → publish`. Partial uploads are staging state, never accepted objects (same invariant as A-9120.1 and component-F staging). Multipart completion is not publication; only the service verification step makes the reference row writable. -- **GC safety:** mark-and-sweep per partition exactly as component F §6. The authoritative reference state the sweep reads is the set of **published** rows in `kv_heads`/`kv_blobs` (intermediate `staged`/`verified` states live only in the endpoint's staging area, never in central rows — central accepts `published` only). The sweep shares component F's per-partition serialization point concretely: KV reference creation (publish-CAS) and the GC delete fence are transactions against the same central primary, ordered by the per-partition sequence the primary assigns. A reference created during candidate/grace/re-verify races is thereby ordered: a publish-CAS landing before the fence's re-verify is seen and clears candidacy; one landing after finds no verified replica under the fence and the writer re-stages from its held bytes (a re-upload, not data loss). Per-jurisdiction dedup partitions from #3401 bound every sweep (D012); the derived index is a cache; re-verify at grace expiry; epoch-fenced delete; audit event per delete. +- **Upload safety:** `put_staged → verify (length + BLAKE3-256 recomputed on receipt, streaming) → publish`. Upload→verify yields a staged/verified object held only by a temporary staging pin/lease — staging state, never an accepted object (same invariant as A-9120.1 and component-F staging). **Publication is the CAS + authoritative ref-registration transaction** (publish-CAS, §4–§5): only that transaction makes the reference row writable/readable. Crash before CAS leaves a staging-pinned object that staging TTL may safely reap (no read path can reference it). Crash after CAS leaves a retained ref root that only grace/GC may retire. An object marked "published" anywhere before its CAS is an orphan: it is retained under grace/GC rules, never reaped by staging TTL — there is no gap between the ref check and the deletion fence because both run against the same primary (§10 ordering below). Multipart completion is not publication; only the service verification step plus the publish-CAS makes the reference row writable. +- **GC safety:** mark-and-sweep per partition exactly as component F §6. GC roots are the full retained set: **published** rows in `kv_heads`/`kv_blobs`, plus retained `kv_versions` rows, proposed refs recorded in `kv_conflicts`, archive/snapshot refs until their actual expiry, dedup active pins, and every other DB root that names a content id. Intermediate `staged`/`verified` states live only in the endpoint's staging area under the staging pin, never in central rows — central accepts `published` only, and only via publish-CAS. The sweep shares component F's per-partition serialization point concretely: KV reference creation (publish-CAS) and the GC delete fence are transactions against the same central primary, ordered by the per-partition sequence the primary assigns. A reference created during candidate/grace/re-verify races is thereby ordered: a publish-CAS landing before the fence's re-verify is seen and clears candidacy; one landing after finds no verified replica under the fence and the writer re-stages from its held bytes (a re-upload, not data loss). Per-jurisdiction dedup partitions from #3401 bound every sweep (D012); the derived index is a cache; re-verify at grace expiry; epoch-fenced delete; audit event per delete. ### 10. Per-jurisdiction dedup and reference format (using existing ID hash shapes) @@ -198,14 +200,14 @@ Source of every entry below is agent-preliminary; status of the record is prelim - **D004 — Local-first, identity-scoped reads with local-override; `--global` pins central; merged list shows shadowed rows.** Source: #10359 item 2 read path. Status: preliminary. Reversal: low. - **D005 — Three delete-related states: clear-override, masking tombstone, history revert.** Source: sweep-merge need (#10359 item 4) + #9115 tombstone reconciliation precedent. Status: preliminary. Reversal: medium (resurrection bugs if collapsed). - **D006 — Sweep merges full-identity partitions via durable outbox + CAS, with a 15-minute survival archive.** Source: #10359 item 4 + context-propagation note filed the same day. Status: preliminary. Reversal: medium. -- **D007 — All mutable heads are CAS-versioned with append-only version/conflict history and atomic idempotency receipts; no timestamp LWW.** Source: #9114 head rule (CAS on prior generation); store-seam `concurrency_unsupported` posture. Status: preliminary. Reversal: high (correctness invariant). +- **D007 — All mutable heads are CAS-versioned with append-only version/conflict history and atomic idempotency receipts keyed `(authenticated_writer, host_incarnation_UUID, outbox_UUID)` plus an immutable request fingerprint; no timestamp LWW; rebase is a new intent, never silent overwrite.** Source: #9114 head rule (CAS on prior generation); store-seam `concurrency_unsupported` posture. Status: preliminary. Reversal: high (correctness invariant). - **D008 — Five-agent shared namespace: single-writer-per-key CAS on central; ordinary cached reads at most 1 s old; `--global` authoritative bypass; offline work is local intent until sweep commits; KV CAS is not a queue lease.** Source: #10359 item 5 question; evidence: claim-path precedent ([claim.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs)) distinguished, not inherited; legacy embedded-replica write path (writes to cloud primary; https://docs.turso.tech/features/embedded-replicas/introduction) and Turso Sync last-push-wins (https://docs.turso.tech/sync/usage, https://docs.turso.tech/sync/conflict-resolution) both noted and rejected as the v1 conflict rule. Retry: ≤ 5 attempts, jittered exponential backoff capped at 1 s. Status: preliminary (retained with challenge refinement 2026-11-23). Reversal: medium. - **D009 — Effective blob threshold is a hard inline ceiling (`min` of the KV per-namespace knob, default 256 KiB, and the shared partition ceiling); per-push override forces blob earlier only.** Source: #10359 threshold question; precedent: component-F "threshold is policy, never protocol" with 16 KiB conservative start. Status: preliminary. Reversal: low (policy value). - **D010 — Blob identity is exactly #9120 `raw-blake3-256` over exact bytes; reference row format `KvBlobRefV1` reuses that profile; central accepts `published` only.** Source: #9120 A-9120.1; profile code in [content_id.rs](../../pkgs/id/crates/id-core/src/content_id.rs). Status: preliminary. Reversal: high (identity change). - **D011 — Endpoint auth is RP/agent JWT or route-scoped service token per [auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts); the secrets-broker fetch path is not request auth; hash is never a bearer credential; reads mint 5-minute scoped capabilities.** Source: hosted auth ([auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts) lines 140–210); component-F §5 access rule. Status: preliminary. Reversal: high (auth architecture). - **D012 — Blob GC is component-F mark-and-sweep per `(jurisdiction, tier)` partition sharing the central per-partition serialization point; kv published rows are the authoritative reference set.** Source: component-F §6 + #3401 partitions + #9137 priority note. Status: preliminary. Reversal: medium. - **D013 — [REVERSED 2026-11-23, superseded by D015] Lists/tables as typed manifest compositions.** Reversal reason: over-designed ahead of the shapes it depends on; Phase 3 is blob-only. Do not cite D013 as active. -- **D014 — Hybrid central placement: shared primary by default; group databases by explicit grant only.** Shared namespaces live on the one fleet-kv primary. A group database exists iff a `kv_grants` row `(group, database, allowed namespaces, allowed ops, policy_epoch)` authorizes it under a fail-closed admission/provisioning policy; no default per-session proliferation. v1 operational integration (migrations, credential wiring, grant policy implementation, backup/restore runbook, health probes) is required Phase 2 scope, not assumed. Source: challenge outcome 2026-11-23 (investigator `ses_e5df780c496ffe06q0f9UZRHmj`) + #10359 "own small database" note bounded by tenancy. Status: preliminary. Reversal: high (splits the primary where grants exist). +- **D014 — Hybrid central placement: shared primary by default; group databases by explicit grant only, inline-only in v1.** Shared namespaces live on the one fleet-kv primary under central key `(scope_id, registry_id, namespace, key)` with one shared scope per shared namespace. A group database exists iff a `kv_grants` row `(group, database, allowed namespaces, allowed ops, policy_epoch)` authorizes it under a fail-closed admission/provisioning policy; no default per-session proliferation; group DBs store inline bytes only, and blob-needing writes there refuse with `blob_requires_shared_primary` (no auto-move). v1 operational integration (migrations, credential wiring, grant policy implementation, backup/restore runbook, health probes) is required Phase 2 scope, not assumed. Source: challenge outcome 2026-11-23 (investigator `ses_e5df780c496ffe06q0f9UZRHmj`) + #10359 "own small database" note bounded by tenancy; round-2 review scoping. Status: preliminary. Reversal: high (splits the primary where grants exist). - **D015 — Versionable envelope only; list/table semantics deferred.** The KV row envelope is versioned (`kv:raw-v1`, `kv:ref-v1`); future shapes arrive as new envelope versions with their own proposals. No manifests or tables in this plan; Phase 3 is blob-only. Source: challenge outcome 2026-11-23. Status: preliminary. Reversal: low. ## Challenge record (2026-11-23) @@ -219,6 +221,10 @@ D001/D002/D008/D013 were reopened under readonly investigator `ses_e5df780c496ff - None of the four outcomes needed a human tossup; all proceed as defaults with implementation evidence owning tuning. - Re-challenge of the reopened choices is expected after this repair; outcomes will be recorded here with dates. +## Re-challenge final (2026-11-23, `ses_e5df7827a0affeeqHwO8DuGAvB`) + +D001, D008, D014, D015 all marked sound; no tossup; human-review None appropriate. Not checked (carried, not resolved): per-DB pricing, Turso org limits, per-request billing under load, provisioning/admission implementation readiness, future envelope-version sufficiency for deferred shapes. This is the final challenge round; no further rounds are scheduled — remaining work is the correctness repairs in this revision plus implementation evidence. + ## Alternatives considered See §7 for the local-store alternatives (embedded replica, standalone local-only, Turso Sync). Remaining: @@ -238,6 +244,6 @@ See §7 for the local-store alternatives (embedded replica, standalone local-onl ## Open questions - **O1 — `--global` surface exactness:** flag on every verb vs `fleet kv global ` subcommand. Default in effect: flag (`--global`), matching the issue's sketch. Settles: Phase 1 build. -- **O2 — Threshold/ceiling measurement.** Defaults in effect (256 KiB knob, 16 KiB partition start). Settles: measurement (#9098-style KV workload) — evidence, not a gate. +- **O2 — Threshold/ceiling measurement + streaming budget.** Defaults in effect (256 KiB knob, 16 KiB partition start; ≤ 64 KiB chunks, ≤ 1 MiB resident). Settles: measurement (#9098-style KV workload) — evidence, not a gate. - **O3 — List/table shapes.** Deferred to a later proposal (D015); the envelope versions here are the only seam fixed. - **O4 — True-delete/retention interplay** with #9130-versioning/#3401 erasure flows for tombstoned KV rows. Deferred to plan; masking tombstones are compatible with either outcome. From 5ac3ddcec60017b05b655b8fe665b06c61369ec3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 07:19:12 -0600 Subject: [PATCH 4/5] =?UTF-8?q?docs(fleet-kv):=20closure=20repairs=20?= =?UTF-8?q?=E2=80=94=20full=20central=20key,=20clear=20serialization,=20RP?= =?UTF-8?q?O=20wording?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Full (scope_id, registry_id, namespace, key) in every CAS/history/ conflict/receipt/fingerprint/schema reference. clear-override holds the per-key local lock against sweeper network submission (5s bounded wait, typed busy); in-flight = irrevocably submitted only. 15-min is an online checkpoint target; unarchived offline loss unbounded (line71, Consequences, D006). Phase drafts: pinned design URL, Phase1 identity accessor/session_state.rs bound, --to version ID, terminal cancellation, working-file backup, proposed fleet-kv test crate + nonzero-count done checks; Phase2 FLEET_KV_URL, scope-derived central key, backup/archive command, REQUIRED correctness-only probe, pending_needs_phase3; Phase3 effective=min formula, scope-policy jurisdiction/tier, shared-primary partition_fences, no lists/tables. --- .../2026-11-23T12-45-00Z_design_fleet_kv.md | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md index 1e54192b88..5a1e182f51 100644 --- a/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md +++ b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md @@ -68,7 +68,7 @@ Tables above are logical names for the phased build issues, not a claim that sch 1. **Local file snapshot** (survives process death, not disk loss): SQLite backup API or filesystem snapshot of file + WAL into `~/.local/share/fleet/kv/backups/` every **6 h**, plus a `backup manifest` row (host, file hash, WAL frame, timestamp) in the outbox. RPO for process-death recovery: last write (WAL replay). 2. **Survival archive** (survives disk loss when reachable): the sweeper uploads the session dirty set to the central archive scope on session end and every **15 min** during a live session. The 15-minute figure is an online successful-checkpoint TARGET, not an unconditional RPO: with no network, no successful checkpoint, or disk destruction before the next upload, the loss window for unarchived writes is unbounded, and the CLI must report that plainly. The Phase 2 archive carries inline payloads only, up to the effective threshold (§8); over-threshold bytes stay local-working (§8) until Phase 3 exists, and the archiver explicitly reports them as `protection_unavailable_needs_phase3` instead of pretending they are archived. Large working blobs are part of the snapshot only once reference placement exists: the manifest lists staged content ids, and restore re-publishes or re-links them. -Restore: fetch latest snapshot (local dir first, archive scope if the disk is gone), open read-only to verify, then adopt (fresh host) or three-way CAS-merge through §4 (returning host with divergent rows). **Durability boundary, stated plainly:** an acknowledged local write lost to disk destruction _before_ the next 15-minute archive upload is unrecoverable — that is the loss window (≤ 15 min of local writes, plus any over-threshold working bytes not yet staged). Backup never writes bytes into the KV row space; large local working bytes stay local-working until staged. +Restore: fetch latest snapshot (local dir first, archive scope if the disk is gone), open read-only to verify, then adopt (fresh host) or three-way CAS-merge through §4 (returning host with divergent rows). **Durability boundary, stated plainly:** the 15-minute figure is an online successful-checkpoint target, not an RPO — unarchived offline writes lost to disk destruction or never checkpointed for lack of network have an unbounded loss window. Backup never writes bytes into the KV row space; large local working bytes stay local-working until staged. ### 2. Namespaces and registry identity (coordinate with #9107 / #9116, not parallel) @@ -91,7 +91,7 @@ Verbs: `fleet kv get|set|list` plus `delete`, `clear-override`, and `revert`. `- - **Read path (local-first, identity-scoped):** resolve the caller's `(owner, ctx, partition)` from the authenticated context; read the local overlay for the full tuple; on miss, fall through to the central head the caller's scope authorizes. A live local overlay row _overrides_ the same key in central (D004). `--global get` skips local entirely and reads the central head at its current version — the authoritative bypass. `list` merges both scopes with origin marks (`local|central|both`, local winning display) and never silently hides the shadowed row — show it as `shadowed-by-local` / `shadowed-by-central` in verbose output. - **Set path:** default writes the local overlay + enqueues outbox work; `--global set` writes central directly via CAS (authenticated; §9 for large values). Local sets carry the full identity tuple plus `(value-or-ref, base_version, writer_session, ts)`. - **Delete — three distinct states, three distinct operations (D005):** - 1. `clear-override` — removes the local overlay row for the full identity tuple **and** advances that tuple's local generation fence, which atomically cancels/supersedes every pending local intent (unacked outbox rows) for the same key/identity: cancelled intents never sweep. Effect: the central value (if any) becomes visible again locally. Already-committed central state is unaffected — there is no overlay left to sweep and nothing committed is uncommitted. A sweep CAS already in flight for a cancelled intent cannot uncommit the clear: the sweeper checks the fence before ack, and if the CAS landed first the receipt is returned as-is with the linearization stated (CAS linearized before clear; the next sweep carries no intent, so central keeps the swept value while local reads show central — the operator is told exactly this). Sweeps nothing new. + 1. `clear-override` — removes the local overlay row for the full identity tuple **and** advances that tuple's local generation fence under the per-key local lock shared with the sweeper's network-submission path. The clear holds the lock while (a) marking every unsent intent for the key/identity cancelled and (b) claiming cancellation; the sweeper may only submit a network CAS while holding the same lock and only for intents not claimed cancelled. Bounded wait: a clear waits at most 5 s (default in effect) for an in-progress submission handshake, then returns typed `clear_busy_try_again` without touching the fence. In-flight is therefore defined as irrevocably submitted (bytes on the wire): only unsent intents are cancellable, and a fence check before ack cannot — and does not claim to — uncommit a CAS that lands after the clear. If a submitted CAS lands, its receipt is returned as-is with the linearization stated (CAS linearized before clear took effect; the next sweep carries no intent, so central keeps the swept value while local reads show central — the operator is told exactly this). Already-committed central state is unaffected. Sweeps nothing new. 2. **Masking tombstone** (`delete`) — writes a local tombstone row for the tuple. Effect: the key reads absent locally and in merged `list` (shown with `masked` origin under `--include-tombstones`), while central is untouched until sweep. Sweeps as a mask: central records the tombstone under the sweeping identity's scope; other scopes' heads are unaffected. 3. **History revert** (`fleet kv revert NS KEY --to `) — appends a new version whose value equals the named prior version (new version number, full provenance). Operates on version history, never on the overlay: it does not clear overrides and does not mask central. - **Freshness (states exactly which read is authoritative):** `--global get` reads authoritative central state at the returned head version. Plain `get` reads the local overlay if present (immediate, works offline — overlay reads never block on network), else the freshest central snapshot the host has pulled (snapshot timestamp shown). Ordinary central cache entries are at most **1 s** old (default in effect): on miss or expiry the reader refreshes, and if refresh fails it returns a typed `unavailable`/`stale` error — never a silently old value. `--allow-stale` is the explicit opt-in to read the expired snapshot, always labelled with its age. There is no background sync promise in v1. @@ -101,7 +101,7 @@ Verbs: `fleet kv get|set|list` plus `delete`, `clear-override`, and `revert`. `- A session's local partition does not evaporate at disconnect (D006). On session end (and on explicit `fleet kv sync`), a sweeper merges the session's dirty rows into central under full-identity provenance: 1. Read session dirty set from `outbox` (durable, so a dead session still sweeps on next host run; disk-destroyed sessions recover from the survival archive, §1/§7). -2. For each key: `central_CAS(namespace, key, expected=base_version, new=row)` against `kv_heads`. +2. For each key: `central_CAS(scope_id, registry_id, namespace, key, expected=base_version, new=row)` against `kv_heads`. 3. On success: write the idempotency receipt, then mark the outbox row done (order fixed: CAS → receipt+ack, §5). On conflict: run the §5 rule (versioned conflict, never silent last-writer-wins across sessions), append the conflict record, and leave both versions retrievable. 4. Masking tombstones sweep through the same CAS path as masks scoped to the sweeping identity. 5. Large values sweep by reference only once Phase 3 exists: in Phase 2 the sweeper uploads nothing — over-threshold keys stay queued as local-working and are reported `protection_unavailable_needs_phase3`; the Phase 3 sweeper uploads through §9 first, then CASes the reference row. Central never accepts an unpublished blob reference. @@ -110,12 +110,12 @@ Sweep is idempotent (outbox row ids + receipts make re-runs safe) and recoverabl ### 5. CAS/versioned conflicts, retry, idempotence, recovery -Every mutable head uses compare-and-swap on `(namespace, key, version)` (D007), following the #9114 sidecar-head precedent (CAS on prior `(generation, snapshot_id)`; generation increments exactly once). There is no timestamp-only last-writer-wins anywhere in v1. Storage, not just assertions: +Every mutable head uses compare-and-swap on the full central key plus version, `(scope_id, registry_id, namespace, key, version)` (D007), following the #9114 sidecar-head precedent (CAS on prior `(generation, snapshot_id)`; generation increments exactly once). There is no timestamp-only last-writer-wins anywhere in v1. Storage, not just assertions: -- `kv_heads`: one row per `(namespace, key)` — the current head `(version, value-or-published-ref, writer, ts)`. -- `kv_versions`: append-only; every CAS success appends `(namespace, key, version, parent_version, value-or-ref, writer, ts)`. Retention: full history while the key lives; tombstoned keys retain history (true-delete deferred to #9130 coordination). -- `kv_conflicts`: append-only; every failed CAS appends `(namespace, key, expected, actual, proposed_value, writer, ts)` and the loser receives the conflict id. "Both versions retrievable" reads: `kv get --version V` replays `kv_versions`; `kv conflicts NS KEY` lists conflict records. -- `idem_receipts`: key `(authenticated_writer, host_incarnation_UUID, outbox_UUID)` → `{request_fingerprint, namespace, key, version, result}`, written **atomically with the CAS in one central transaction**. The fingerprint is an immutable hash of the intent body (namespace, key, expected version, value-or-ref, op); the host incarnation UUID is generated once per durable host identity and survives process death (stored beside the local DB), so a reborn sweeper never reuses another incarnation's keys. An exact retransmit (same key, same fingerprint) — even after the head has since advanced — returns the recorded result instead of attempting a new CAS (so it can never become a spurious new conflict). A reused key with a different fingerprint is a typed `idempotency_key_reuse` error, never a silent overwrite. Rebasing after a conflict is an explicit new intent with a new outbox UUID (carrying `supersedes: `), never a silent re-read plus opaque-byte overwrite. Local dirty revisions keep ancestry links; the outbox is a queue that resolves dependency order (a revert names its base version; a tombstone supersedes its generation), not a bag of latest-writes. +- `kv_heads`: one row per `(scope_id, registry_id, namespace, key)` — the current head `(version, value-or-published-ref, writer, ts)`. +- `kv_versions`: append-only; every CAS success appends `(scope_id, registry_id, namespace, key, version, parent_version, value-or-ref, writer, ts)`. Retention: full history while the key lives; tombstoned keys retain history (true-delete deferred to #9130 coordination). +- `kv_conflicts`: append-only; every failed CAS appends `(scope_id, registry_id, namespace, key, expected, actual, proposed_value, writer, ts)` and the loser receives the conflict id. "Both versions retrievable" reads: `kv get --version V` replays `kv_versions`; `kv conflicts NS KEY` lists conflict records. +- `idem_receipts`: key `(authenticated_writer, host_incarnation_UUID, outbox_UUID)` → `{request_fingerprint, scope_id, registry_id, namespace, key, version, result}`, written **atomically with the CAS in one central transaction**. The fingerprint is an immutable hash of the intent body (scope_id, registry_id, namespace, key, expected version, value-or-ref, op); the host incarnation UUID is generated once per durable host identity and survives process death (stored beside the local DB), so a reborn sweeper never reuses another incarnation's keys. An exact retransmit (same key, same fingerprint) — even after the head has since advanced — returns the recorded result instead of attempting a new CAS (so it can never become a spurious new conflict). A reused key with a different fingerprint is a typed `idempotency_key_reuse` error, never a silent overwrite. Rebasing after a conflict is an explicit new intent with a new outbox UUID (carrying `supersedes: `), never a silent re-read plus opaque-byte overwrite. Local dirty revisions keep ancestry links; the outbox is a queue that resolves dependency order (a revert names its base version; a tombstone supersedes its generation), not a bag of latest-writes. - Retries are bounded with jitter: at most **5 attempts**, jittered exponential backoff capped at **1 s** per backoff (defaults in effect). Each attempt carries the outbox id as the idempotency key. - Recovery order is fixed: outbox → upload (§9) → CAS+receipt (atomic) → ack. Any crash restarts at the oldest unacked outbox row. Staged-but-unpublished blobs are never referenced by any read path, so they are safe to reap by TTL. - `concurrency_unsupported` is a typed error if some future adapter cannot CAS: fail closed, never degrade to silent overwrite (same posture as the V2 store seam in the Part A versioned design). @@ -199,7 +199,7 @@ Source of every entry below is agent-preliminary; status of the record is prelim - **D003 — Global namespace = designation flag on the distributed registry; resolution always names a registry; the flag never bypasses local-first reads.** Source: #10359 item 3; aligns #9116 registry under the [namespace_definition.rs](../../pkgs/id/crates/id-core/src/namespace_definition.rs) local-registry constraint. Status: preliminary. Reversal: low. - **D004 — Local-first, identity-scoped reads with local-override; `--global` pins central; merged list shows shadowed rows.** Source: #10359 item 2 read path. Status: preliminary. Reversal: low. - **D005 — Three delete-related states: clear-override, masking tombstone, history revert.** Source: sweep-merge need (#10359 item 4) + #9115 tombstone reconciliation precedent. Status: preliminary. Reversal: medium (resurrection bugs if collapsed). -- **D006 — Sweep merges full-identity partitions via durable outbox + CAS, with a 15-minute survival archive.** Source: #10359 item 4 + context-propagation note filed the same day. Status: preliminary. Reversal: medium. +- **D006 — Sweep merges full-identity partitions via durable outbox + CAS, with a 15-minute online-checkpoint-target survival archive (unbounded loss for unarchived offline writes).** Source: #10359 item 4 + context-propagation note filed the same day. Status: preliminary. Reversal: medium. - **D007 — All mutable heads are CAS-versioned with append-only version/conflict history and atomic idempotency receipts keyed `(authenticated_writer, host_incarnation_UUID, outbox_UUID)` plus an immutable request fingerprint; no timestamp LWW; rebase is a new intent, never silent overwrite.** Source: #9114 head rule (CAS on prior generation); store-seam `concurrency_unsupported` posture. Status: preliminary. Reversal: high (correctness invariant). - **D008 — Five-agent shared namespace: single-writer-per-key CAS on central; ordinary cached reads at most 1 s old; `--global` authoritative bypass; offline work is local intent until sweep commits; KV CAS is not a queue lease.** Source: #10359 item 5 question; evidence: claim-path precedent ([claim.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/claim.rs)) distinguished, not inherited; legacy embedded-replica write path (writes to cloud primary; https://docs.turso.tech/features/embedded-replicas/introduction) and Turso Sync last-push-wins (https://docs.turso.tech/sync/usage, https://docs.turso.tech/sync/conflict-resolution) both noted and rejected as the v1 conflict rule. Retry: ≤ 5 attempts, jittered exponential backoff capped at 1 s. Status: preliminary (retained with challenge refinement 2026-11-23). Reversal: medium. - **D009 — Effective blob threshold is a hard inline ceiling (`min` of the KV per-namespace knob, default 256 KiB, and the shared partition ceiling); per-push override forces blob earlier only.** Source: #10359 threshold question; precedent: component-F "threshold is policy, never protocol" with 16 KiB conservative start. Status: preliminary. Reversal: low (policy value). @@ -237,7 +237,7 @@ See §7 for the local-store alternatives (embedded replica, standalone local-onl ## Consequences -- Gets easier: session work product survives disconnect by construction (15-minute archive bound); namespaces stay one system with ID (#9107 family) instead of a fleet-private dialect; large values stop pricing as database rows; every conflict is a retrievable record, not silent loss. +- Gets easier: session work product survives disconnect by construction (online-checkpoint target with plainly unbounded unarchived-offline loss); namespaces stay one system with ID (#9107 family) instead of a fleet-private dialect; large values stop pricing as database rows; every conflict is a retrievable record, not silent loss. - Gets harder: every writer implements CAS retry; every large push does staged→verified→published instead of a single write; reads that need linearizability must say `--global` explicitly; GC/tombstone literacy becomes operator knowledge. - Must stay compatible: #9120 hash profile bytes (never rehash/reinterpret); legacy local state (adopt-or-CAS-merge, never overwrite); supported-credential auth only (no new mechanism smuggled in via the secrets path); adapter neutrality (R2 vs RustFS invisible above the adapter, per component I); the ID signed-journal source-of-truth contract (fleet outbox claims no ID-world authority). From ea76fc822a8010cd6b059b2c93cf5a75a152bf23 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 07:25:29 -0600 Subject: [PATCH 5/5] =?UTF-8?q?docs(fleet-kv):=20delivery=20update=20?= =?UTF-8?q?=E2=80=94=20phase=20issues,=20chain,=20signoff?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Append dated delivery section: build issues #13314/#13316/#13318 (subissues of #10359, pilot tasks 21316-21318, tier crucial, hard chain #13314 -> #13316 -> #13318, all gated on #13294), reviewer signoff (Mustfix NONE at 5ac3ddc), challenge final, truthful no-runtime-tests statement. Phase-2 draft ref -> live issue; human-review link clickable. Bookkeeping only, no arch change. --- .../2026-11-23T12-45-00Z_design_fleet_kv.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md index 5a1e182f51..835b3cb715 100644 --- a/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md +++ b/doc/2026-11-23T12-45-00Z_design_fleet_kv/2026-11-23T12-45-00Z_design_fleet_kv.md @@ -59,7 +59,7 @@ Tables above are logical names for the phased build issues, not a claim that sch - **Shared namespaces (the v1 default):** one fleet-kv Turso database as the libSQL primary for KV heads, append-only version/conflict history, idempotency receipts, grant rows, and blob _references_; bytes live in the object plane (§6). Clients use the same transport shape the queue already proves: libSQL HTTP pipeline from Rust ([core.rs](../../pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs) lines 1–81 and 532–770; `DEFAULT_TURSO_URL` at line 10 shows the pattern, not the kv database). Central writes serialize per key on the primary's transactions (conservative outbox + central transaction sequencer, §5); this design assumes no automatic multi-master CAS from any sync product. - **Group databases (explicit grant only):** a real per-group Turso DB exists iff a `kv_grants` row `(group, database, allowed namespaces, allowed ops, policy_epoch)` authorizes it, issued through a fail-closed admission/provisioning policy (admission checks group membership + namespace ownership; provisioning mints the DB, writes the grant row, and replicates the namespace subset; unknown group or namespace refuses). No default per-session proliferation: sessions do not get databases unless a grant says so. Simplest v1 rule: group DBs are **inline-only** — they store no blob references and no grant covers blob placement. Reference writes land on the shared primary only (one GC fence, §9–§10); a blob-needing write addressed to a group scope fails with a typed refusal requiring shared-primary placement (`blob_requires_shared_primary`), never an automatic move. Group blob support is deferred to a common partition service with shared outbox watermarks, not designed here. Phase 2 must not accept unrestricted bytes into a group DB past the effective ceiling: the ceiling check runs before any group-DB write. Not checked: per-database pricing and Turso org limits for grant-provisioned DBs — no cost claim is made; Phase 2 measures against the shared primary only. - Per-user Turso DB credentials (component-E data-plane tokens) are not service authentication and are refused at the hosted front door by rule ([auth.ts](../../pkgs/fleet/hosted-worker/src/auth.ts) lines 20–33 and 134–159 `data_plane_credential_refused`); central KV access goes through the authenticated pipeline path, never by presenting a data-plane token. -- **v1 operational integration (required, not pretended-shipped):** the Phase 2 build must land migrations for all central tables above, the pipeline credential wiring, the grant/provisioning policy implementation, per-partition backup/restore runbook entries, and central health/readiness probes — a primary that none of this exists for is not a primary. Phase 2 acceptance (§4 of the phase-2 draft) gates on these, not on the row protocol alone. +- **v1 operational integration (required, not pretended-shipped):** the Phase 2 build must land migrations for all central tables above, the pipeline credential wiring, the grant/provisioning policy implementation, per-partition backup/restore runbook entries, and central health/readiness probes — a primary that none of this exists for is not a primary. Phase 2 acceptance (build issue https://github.com/developing-today/code/issues/13316, §4 scope) gates on these, not on the row protocol alone. **ID journal relationship (binding).** The ID serverless storage contract ([storage contract](../../doc/2026-11-17_decision_id5863_storage_contract.md)) fixes the signed journal as the system of record for ID world state; fleet-kv does not mint a competing journal. Scope boundary, stated exactly: KV row state is fleet-owned application state, not ID world state. Its durability contract is a bounded Fleet projection protocol — per-host outbox journal of _unsigned, fleet-scoped write intents_ → central primary CAS transactions — which claims no ID-world authority, carries no ID signatures, and is never presented as an ID journal. Content blobs remain fully under the ID source-of-truth contract (content identity per #9120, admission per the signed gate); fleet-kv rows reference that content, they do not re-journal it. @@ -192,7 +192,7 @@ Phase 3 is blob-only. List/table semantics are not designed here and no manifest ## Decisions -Source of every entry below is agent-preliminary; status of the record is preliminary. Work proceeds on these defaults; implementation evidence (not a gate) owns tuning — see `human-review.md`. +Source of every entry below is agent-preliminary; status of the record is preliminary. Work proceeds on these defaults; implementation evidence (not a gate) owns tuning — see [human-review.md](human-review.md). - **D001 — Local store is plain per-host SQLite (WAL), not embedded libSQL/Turso or libSQL-file, in v1.** Source: issue #10359 item 2 + backup question; evidence: offline-write and file-backup needs (§1, §7); Turso embedded-replica write path (writes to cloud primary; https://docs.turso.tech/features/embedded-replicas/introduction); standalone local-only steelman via Rust SDK (https://docs.turso.tech/sdk/rust/quickstart), rejected §7. Status: preliminary (retained with challenge refinement 2026-11-23). Reversal cost: medium (replaces local engine + backup story; central protocol unchanged). - **D002 — [REVERSED 2026-11-23, superseded by D014] Central store is one Turso-hosted libSQL primary; per-group scopes are row-level in v1.** Reversal reason: read as either/or vagueness ("provisioning scopes") and an unproved rows-equal-grants posture. Retained content moved into D014 with an explicit grant mechanism and fail-closed policy. Do not cite D002 as active. @@ -247,3 +247,15 @@ See §7 for the local-store alternatives (embedded replica, standalone local-onl - **O2 — Threshold/ceiling measurement + streaming budget.** Defaults in effect (256 KiB knob, 16 KiB partition start; ≤ 64 KiB chunks, ≤ 1 MiB resident). Settles: measurement (#9098-style KV workload) — evidence, not a gate. - **O3 — List/table shapes.** Deferred to a later proposal (D015); the envelope versions here are the only seam fixed. - **O4 — True-delete/retention interplay** with #9130-versioning/#3401 erasure flows for tombstoned KV rows. Deferred to plan; masking tombstones are compatible with either outcome. + +## Delivery update (2026-11-23) + +- Reviewed source SHA for everything below: `5ac3ddcec60017b05b655b8fe665b06c61369ec3`. No architecture change in this section — bookkeeping only. +- Build issues (all subissues of https://github.com/developing-today/code/issues/10359, all tier **crucial**, all gated on design PR https://github.com/developing-today/code/pull/13294 merging first): + - Phase 1 — local verbs/backup/trusted identity accessor: https://github.com/developing-today/code/issues/13314 (pilot task 21316). Goal: local-only `fleet kv` verbs with full-identity overlays, durable outbox, snapshot + pinned-working-file backup, and the new trusted launch-identity accessor. Enables: offline-capable local KV with zero central dependency. + - Phase 2 — central CAS/scopes/grants/inline archive: https://github.com/developing-today/code/issues/13316 (pilot task 21317). Goal: shared Turso primary, explicit scope-derived central keys, explicit-grant group DBs (inline-only), durable sweep + archive. Enables: multi-session shared namespaces with CAS arbitration. Hard depends on Phase 1; blocked-by https://github.com/developing-today/code/issues/13314. + - Phase 3 — blobs/reference auth/fenced GC (no lists/tables): https://github.com/developing-today/code/issues/13318 (pilot task 21318). Goal: threshold placement, staged→verified→published upload, hash-never-bearer capabilities, fenced mark-and-sweep GC. Enables: large values as content references. Hard depends on Phase 2; blocked-by https://github.com/developing-today/code/issues/13316. +- Hard phase chain: #13314 → #13316 → #13318 (each blocked-by the previous; #13294 merges before any of them starts). +- Queue coverage: pilot tasks 21316/21317/21318 carry the three phases; #10359 holds the design record; this PR (`lane-any-n/12892-fleet-kv-design`) remains OPEN for the parent any-n merge — no merge by this writer. +- Reviewer signoff: `ses_e5df782bea1ffedFnShVEZKTcO` at the reviewed SHA — Mustfix NONE (full central key, per-key lock clear-vs-submit, RPO/target wording, terminal cancellation all verified). Challenge final: D001/D008/D014/D015 all sound, no tossup, human-review None appropriate (record: [human-review.md](human-review.md)). +- Truthful test statement: no runtime tests were executed in this design pass — no implementation exists, so there was nothing to run. Verification here is prose-level: focused re-reads, `git diff --check`, `research_workflow.py check` (`ok: true`), and prettier formatting. Executable done checks live in the build issues and run when the phases land.