diff --git a/doc/2026-11-08_design_id5803.md b/doc/2026-11-08_design_id5803.md new file mode 100644 index 0000000000..c5c7af8ac5 --- /dev/null +++ b/doc/2026-11-08_design_id5803.md @@ -0,0 +1,406 @@ +# Design: shared foreign data-store adapter contract for ID + +- **Date:** 2026-11-08 +- **Status:** decision record; no adapter implementation is included. +- **Issue:** [#5803](https://github.com/developing-today/code/issues/5803), + “id: design: foreign data-store adapter contract (from #5672)”. +- **Parent:** [#5672](https://github.com/developing-today/code/issues/5672), + “ID selective sharing and foreign data-store adapters v1”. +- **Programme:** [#2056](https://github.com/developing-today/code/issues/2056). +- **Related adapter decisions:** [IndexedDB #5804](2026-11-08_design_id5804.md) + (merged in PR #7579); [Turso/libsql HTTP #5806](https://github.com/developing-today/code/issues/5806#issuecomment-6719146085) + (decision recorded on the issue). +- **Evidence baseline:** `origin/main` at `722fbe8aa2811a9254212e14f738b3dce427ac64`. + On 2026-11-08, #5803 and parent #5672 were OPEN; #5804 was CLOSED after + PR #7579 merged. No competing PR for #5803 existed. + +## Decision summary + +| Contract question | Decision | +| --- | --- | +| What is an adapter? | A named, versioned boundary that binds one configured endpoint to a set of explicitly selected foreign collections and advertises its capabilities. A collection is the unit the ID grant model can name. | +| Addressing | ID-level references use the registered form `id://foreign///`. The alias resolves only in local endpoint configuration. Adapter-native locators (for example, an IndexedDB origin/database/store or an HTTPS URL) are local connection details, not credentials and not a substitute for the ID-level reference. | +| Type mapping | Adapters map through the closed ID value vocabulary in §3, publish a versioned per-resource mapping, and either preserve a value or report/reject the loss explicitly. No implicit stringification, numeric coercion, or dropped fields. | +| Live/materialized | The adapter declares which modes it supports. The owner chooses an allowed mode per collection; any default is adapter-specific and must be recorded in that adapter's decision/configuration. Query hints may narrow the owner's choice, never widen it. No automatic stale-snapshot fallback for a failed live read. | +| Direction | Read-only against the foreign store in v1. Materialization writes a copy into ID; it does not write back to the source. | +| Credentials | A local, opaque credential reference may be stored in endpoint configuration. Raw secrets and secret-bearing locators never enter ID data, shared references, snapshots, logs, or error text. | +| Errors and latency | Stable machine-readable outcomes, bounded calls, explicit freshness/completeness metadata, no silent empty result on failure, and caller-visible error collapsing wherever the parent’s existence-privacy rule requires it. | +| p2panda | Not a first-class foreign-store adapter in this v1 contract. Keep it as a possible future interop/export target, pending a concrete shared-schema and consumer use case; do not imply equivalence with ID’s native journal. | + +## 1. Parent decisions this record applies, not re-decides + +Issue #5672 is the authority for the selective-sharing and foreign-adapter +programme. This record applies its Part B framing: each adapter answers how a +foreign collection is addressed, what type mapping is promised, whether reads +are live or materialized, whether source writes exist, how credentials are +handled, and what happens when the source is slow or gone. + +It also takes the parent’s selective-grant and existence-privacy constraints as +fixed. In particular: + +1. An adapter collection is a grantable resource; an adapter must not expand a + collection grant to unrelated collections. +2. Reads are evaluated within the caller’s grant. The adapter must push the + restriction into the source query where possible; if it cannot enforce the + restriction safely, it refuses the query rather than fetching excess rows + and filtering them after the fact. +3. Ungranted objects, their IDs, counts, schema details, and existence are not + disclosed. **Conservative adapter assumption:** for grantee results, + “not granted”, “does not exist”, and “unavailable” collapse to the same + externally observable outcome. The body of #5672 states the shape privacy + rule but leaves this exact error question open (“useful errors” versus + distinguishing “no such object” from “not granted”). This record adopts the + privacy-preserving side for foreign adapters pending explicit parent-level + resolution; it does not claim that #5672 already closed that question or + change the parent’s grant, revocation, or delegation semantics. +4. Revocation and delegation keep the parent’s semantics. This record adds no + promise that ID can erase plaintext already copied by a peer, and does not + make delegation implicit. +5. Foreign adapters are read/materialize-first in v1; REDB remains ID’s native + store. This record proposes **no change** to a parent decision. If a future + adapter cannot meet one of these constraints, it must return to #5672 for an + explicit decision rather than forking the rule locally. + +## 2. Adapter boundary and addressing + +### 2.1 Two address layers + +An endpoint is a locally configured connection context (for example, one +browser profile/bridge, one remote database account, or one Redis connection). +An endpoint may expose multiple collections, but only those explicitly +selected by its owner. A foreign collection maps to one ID collection and is +the smallest addressable/grantable unit unless a parent-level grant shorthand +expands to it. + +The **ID-level reference** is a stable, adapter-registered URI: + +```text +id://foreign/// +``` + +- `` is a registered, versioned adapter name, not a free-form + driver string. +- `` identifies a locally configured endpoint. It is not a + hostname, database URL, username, token, or other locator/secret. Rebinding + an alias to a different endpoint is a source-identity change: it requires a + new alias or an explicit migration that invalidates old provenance. +- `` is canonicalized by the adapter and identifies a + collection. Its path grammar and escaping are declared by that adapter; + names are never normalized in a way that merges distinct source resources. +- The URI contains no user-info, password, bearer token, API key, or secret + query parameter. Parsers reject such components rather than redact them + after logging. +- The registry records the URI grammar and adapter capability/version. An + unknown adapter or unsupported URI version is a named configuration error, + not a best-effort guess. + +The adapter’s **native locator** stays in local endpoint configuration and +owner-only provenance; it is resolved only by the adapter. Shareable +provenance uses the ID-level reference and never carries the physical locator +unless the owner explicitly discloses it under a grant. This separates a +stable ID resource identity from connection details that may be private, +change, or contain secrets. For example, IndexedDB’s +`idb:////` from #5804 is the native locator; +an owner-local alias maps the ID-level collection reference to that locator +and its browser profile/bridge. The full locator that #5804 records in +snapshot provenance remains owner-only; grantee-visible provenance uses the +canonical alias reference. The libsql decision on #5806 already uses +`id://foreign/libsql/` for its local alias. These are compatible +layers, not competing rules for putting physical locators in shared ID data. + +An adapter must not offer general source enumeration to grantees. Owner-only +setup may discover local resources, but the exposed collection set is an +explicit allowlist. A query that names an unselected resource is +indistinguishable to a grantee from one that names a nonexistent resource. + +### 2.2 Scope, queries, and capabilities + +At registration an adapter declares, per endpoint and collection: + +- read modes it supports (`live`, `materialized`, or both); +- query shapes and ordering guarantees it supports; +- consistency boundary (single transaction/snapshot, per-resource, or weaker); +- schema/type-mapping version and source version information it can report; +- finite limits (row/byte caps, concurrency, and deadlines); and +- whether it can enforce the caller’s grant at the source. + +The query interface is typed and adapter-scoped, not unrestricted source +execution. An adapter may expose native query forms to an owner, but grantee +queries must be translated/validated so they cannot escape the granted +collection or expose withheld rows through counts, errors, schema discovery, +or timing-sensitive fallback. Unsupported query shapes are refused by name; +they are never silently broadened into an unbounded scan or raw SQL pass-through. + +## 3. Canonical value and type-mapping contract + +An adapter publishes a versioned mapping from its source schema to this +logical ID value vocabulary: + +| ID value | Contract meaning | +| --- | --- | +| `null` | Explicit null; distinct from an absent field. | +| `boolean` | `true` or `false`. | +| `integer` | Signed 64-bit integer. | +| `float64` | Finite IEEE-754 binary64 value; NaN and infinities are not values in v1. | +| `string` | Valid UTF-8 text. | +| `bytes` | Opaque byte sequence; never implicitly decoded as text. | +| `timestamp` | UTC instant represented as signed epoch microseconds; source precision and any rounding/loss must be stated. | +| `list` | Ordered sequence of mapped values. | +| `record` | String-keyed map of mapped values; key ordering is not semantically significant. | +| `tagged` | A namespaced, versioned adapter value envelope `{type_id, payload}` for a source type that must remain distinguishable from ordinary ID values (for example, a `BigInt` outside signed 64-bit range). Generic operations treat it as opaque unless the adapter declares a safe operation. | + +Record keys are a separate typed boundary from data values. An adapter states +which mapped key types it accepts, how compound keys are represented, and the +source’s ordering/equality rules. ID must not assume that two adapters order +or compare a key identically merely because both call it a string, number, or +bytes value. The existing ID tuple encoding supports null, bytes, UTF-8 string, +tuple, booleans, signed integers, and finite float64 as key components; it does +not by itself define the foreign-record value schema. + +Mapping rules: + +1. Mapping is deterministic for a declared mapping version and is validated + on both reads and materialization. A type mismatch is an error, not an + invitation to coerce. +2. Absence, explicit null, empty string, and empty bytes remain distinct. + Integer overflow never falls back to float64. Non-finite floats never + silently become strings or nulls. +3. If an adapter can preserve a source value only through a documented tagged + representation (for example, an out-of-range integer whose payload is + decimal text), it uses `tagged` or an equivalently unambiguous + schema-declared representation. The type tag, loss of native query/order + semantics, and affected operations are explicit in schema and provenance. + An untagged decimal string is not a lossless substitute for a `BigInt`. + Otherwise the value is rejected by a stable `type_mapping_failed` outcome. +4. Unsupported types, lossy conversions, truncation, and skipped records are + reported by kind and location, never by copying the sensitive value into + an error. A materialized result includes a loss report. No partial result + is presented as complete. +5. Mapping changes are versioned. A snapshot made with one mapping version is + not silently reinterpreted under another; re-materialization records the + new version and provenance. + +This is a logical boundary format, not a claim that every current ID storage +component already persists every value type. Implementation must establish +the on-disk/wire representation before consuming an adapter, and may narrow a +specific adapter’s supported subset without changing the common vocabulary. + +## 4. Live reads and materialized snapshots + +The contract allows **both** modes as capabilities; it does not require every +adapter to implement both. The adapter declares its supported set, and the +owner configures the permitted mode per collection. The adapter’s own decision +must choose a default for an unconfigured collection or, preferably, refuse +until the owner explicitly chooses. A query freshness hint may narrow the +configured behavior (for example, require live data or pin a snapshot), but +cannot widen grants, expose another collection, or enable a mode the owner or +adapter has not allowed. + +- **Live read:** the query runs against the source at request time. The result + reports observation time and the adapter’s consistency boundary. Calls have + a configured deadline and concurrency/resource bounds. Source failure or a + deadline expiry returns an error; it does not become an empty result and + does not fall back to an older snapshot. +- **Materialized read:** the adapter copies a bounded source result into ID. + Refresh is explicit or scheduled by owner configuration. A snapshot is + atomically replaced; interruption leaves the prior complete snapshot + intact. Results report snapshot time, source and schema identity, mapping + version, completeness/loss report, and any known source version/digest. + Enforce row and byte caps before copying or refuse with a named outcome. +- **Consistency:** an adapter states whether one live read/snapshot is atomic + for one collection and whether multi-collection reads can observe different + source times. Cross-source atomicity is never implied. Stale snapshots are + visibly stale; a query requiring fresher data fails if that freshness cannot + be met. + +The contract intentionally leaves defaults to adapter-specific records: +IndexedDB #5804 selects both modes with owner choice and a snapshot default; +libsql #5806 selects live by default and defers materialized caching. Both +conform because the adapter advertises its allowed modes and the owner-facing +policy is explicit. A universal default would contradict these concrete +decisions without improving safety. + +## 5. Read-only boundary and credential handling + +In v1, adapters do not mutate a foreign source. A materialization is a local +ID-side copy and must not be described as write-back or bidirectional sync. +Any write-back capability requires a separate design for consent, conflict, +partial failure, retries/idempotency, and revocation; it is not enabled by +implementing a read interface. + +Credentials are resolved outside replicated ID data: + +- Endpoint configuration may hold an opaque `credential_ref` to a local secret + provider (OS keychain, secret service, or runtime-injected reference). The + reference is not the credential itself and is not a bearer capability for + a grantee. +- The raw credential is fetched just in time by the adapter, scoped to one + endpoint and least privilege (read-only where the source supports it), and + is never serialized into ID objects, grant records, source references, + materialized rows, logs, traces, task payloads, or errors. +- A connection URL containing user-info or a token is treated as secret + material and is not used as the ID resource URI. Logs and error details + redact physical locators when those locators disclose private infrastructure. +- Rotation/revocation changes the local reference resolution; it does not + rewrite replicated records. Access failure is surfaced under the error + policy below. A grant conveys access to selected ID data, not the source + credential or a right to reuse it against the source. +- Adapters with no separate credential still state the access authority and + consent boundary. IndexedDB’s browser profile plus per-origin bridge consent + is such a case; the adapter records a consent reference, not a secret. + +## 6. Failure, privacy, and observability contract + +The common machine-readable outcome set is: + +| Code | Meaning | +| --- | --- | +| `adapter_unavailable` | No live endpoint/bridge, source gone, or endpoint cannot presently serve the requested mode. | +| `credential_unavailable` | Local credential reference cannot be resolved, is expired, or was revoked. | +| `timeout` | The bounded operation exceeded its deadline. | +| `query_shape_refused` | The adapter cannot execute the requested shape without violating its declared guarantees or access scope. | +| `type_mapping_failed` | The source value/schema is outside the declared mapping or fails validation. | +| `snapshot_too_large` | A configured preflight row/byte limit would be exceeded. | +| `source_changed` | Source identity/schema changed such that a prior mapping or snapshot cannot safely be reused. | +| `rate_limited` | The source or adapter’s declared capacity limit is active. | + +Adapters may add stable codes in a namespaced extension, but must not replace +these with success-shaped empty data. Owner diagnostics may distinguish +authorization, missing-resource, and transport causes. At a grantee boundary, +the response is collapsed to `not_available` whenever it would otherwise +reveal “not granted” versus “not found” versus “adapter unavailable”. The +collapse applies to status, result shape, schema/metadata, and error text; no +physical endpoint detail is exposed to an unauthorized caller. + +Every response identifies the selected mode, freshness/observation time, and +whether it is complete. A truncated scan has an explicit truncation marker; +a failed page or partial batch is an error or a typed partial outcome, never +an unmarked success. Adapters expose bounded latency and retry behavior in +their own records. Retrying must not change read semantics or silently repeat +a future write. + +## 7. Candidate disposition, including p2panda + +The parent’s adapter candidates are not all the same shape, so they use this +contract without being forced into one protocol: + +- **IndexedDB:** one browser endpoint with selected object stores. The merged + #5804 record remains the browser-specific decision; its live bridge, + materialization, origin consent, and structured-clone rules are adapter + details constrained by this contract. +- **Postgres over HTTP:** #5805 remains the adapter-specific design. It must + declare its supported HTTP surface and query translation/enforcement scope; + unsupported shapes are refused, not run as unrestricted SQL. +- **Turso/libsql over HTTP:** the #5806 decision is adapter-specific and + conforms: local endpoint alias and credential reference, live-first + read-only operation, explicit type mapping, bounded failure, and no secret + in ID data. Its live default is not generalized to other adapters. +- **Redis / Redis→SQLite:** #5807 owns whether the operation is a bounded + snapshot/export or a live query producing a SQLite artifact. Export + artifacts are materializations with their own mapping/loss report; they do + not imply a writable Redis adapter. +- **p2panda:** **not accepted as a v1 foreign-store adapter.** The routed + candidate asks whether ID data should interoperate with p2panda-shaped data + or whether p2panda is only a conversion target. The available primary + material describes p2panda as a modular local-first/P2P protocol ecosystem + with append-only-log sync, schema tooling, and its own identity, networking, + and access-control components; this is a protocol/log integration, not + merely connecting to another table store. ID also has its own journal, and + the old iroh-docs motivation in the source conversation is historical. No + shared schema, concrete p2panda consumer, or required interop workflow is + established by #5672/#5803. Therefore v1 does not promise native p2panda + replication, query compatibility, identity mapping, or grant equivalence. + A one-shot conversion/export remains possible in principle, but is also + deferred until it has a named consumer and a loss/identity mapping. Reopen + this disposition only with that evidence; do not silently call ID’s journal + “p2panda-compatible”. + +This is a scope disposition, not a claim that p2panda lacks value. The official +p2panda repository describes modular, offline-first building blocks and an +append-only-log sync crate; its Tauri example uses deployed schemas, a node +GraphQL API, and a separate node identity. Those semantics make a real +interop design possible, but also show why it needs an explicit mapping and +consumer rather than an adapter-shaped name alone. + +## 8. Alternatives considered and rejected + +1. **Let each adapter invent its own exposed ID reference.** Rejected: source + identity, grant scope, privacy checks, and credential exclusion would vary + at the shared boundary. Adapters keep native locators internally, but + register one ID-level URI form and canonicalization rules. +2. **Put physical URLs or credentials in the ID URI.** Rejected: ID references + and data can replicate; credentials and private infrastructure locators + must remain local. An opaque alias resolves through local configuration. +3. **Use one universal source schema and silently coerce every backend into + it.** Rejected: backend types and ordering differ. The closed ID vocabulary + is common, while each adapter publishes a versioned, explicit mapping and + unsupported/lossy cases. +4. **Require every adapter to be live-only or materialize-only.** Rejected: + concrete sources differ. The contract declares capabilities and owner + policy; adapters may select different defaults. A failed live read never + silently returns stale materialized data. +5. **Allow arbitrary raw queries or writes through the adapter.** Rejected: + raw execution can bypass collection grants, type guarantees, and limits; + write-back adds conflict and revocation semantics outside the parent’s v1 + scope. Typed supported shapes are enforced; unsupported ones fail closed. +6. **Treat p2panda as an ordinary foreign table adapter now.** Rejected: + append-only log replication, identity, schema deployment, and offline + synchronization are not the same contract as querying/materializing a + selected foreign collection, and no concrete cross-ecosystem schema or + consumer has been identified. A future interop or export design can make + that case if the evidence appears. + +## 9. Invariants implementation must hold + +1. Every exposed collection has one registered adapter identity, one stable + ID-level source reference, and an explicit owner-selected grant boundary. +2. An alias never silently rebinds to a different endpoint; a physical-source + change invalidates old snapshot provenance. +3. Grantee queries cannot enumerate unselected collections or infer withheld + objects from counts, IDs, schemas, result shape, or errors. +4. No query reads outside its grant. If the adapter cannot enforce that + constraint, it refuses the query before returning source rows. +5. Source credentials and secret-bearing locators never enter ID data, + replicated records, snapshots, logs, traces, or errors. +6. Every value is checked against the declared mapping version. Unsupported + and lossy cases are named and reported; no implicit coercion or unreported + drop occurs. +7. Live reads have a deadline and declared consistency; timeout/source-down + is never an empty result or an automatic stale-snapshot fallback. +8. Materialized snapshots are bounded before copy, atomically replaced, + provenance-bearing, and visibly stale or incomplete when appropriate. +9. Error codes are stable and machine-readable; grantee-visible outcomes + collapse whenever distinctions would violate the parent’s + existence-privacy rule. +10. Read-only v1 adapters never mutate a foreign source. No API shape or + credential reference smuggles in source write capability. + +## 10. Conformance and explicit reconciliation + +| Existing decision / parent rule | Conformance to this record | +| --- | --- | +| #5672 selective grants and existence privacy | Applied as constraints in §§1, 2.2, and 6. No change proposed to grants, delegation, revocation, or privacy. | +| #5804 IndexedDB (`doc/2026-11-08_design_id5804.md`) | Its owner-configured dual modes conform. Its native `idb:////` locator resolves locally to the registered ID-level alias/resource reference in §2. The record’s full locator may remain in owner-only snapshot provenance; grantee-visible provenance uses the alias and omits the physical origin unless explicitly disclosed by the owner under a grant. Its `timestamp` is the common UTC-microsecond semantic type, preserving millisecond source precision. Its out-of-range `BigInt` decimal payload must be distinguished from an ordinary string by a tag or schema-declared representation; otherwise the adapter rejects that value. Other unsupported/lossy cases remain explicit per that record. | +| #5806 libsql (`#issuecomment-6719146085`) | Its `id://foreign/libsql/` follows the ID-level reference and local-resolution rule. Live-first is an allowed adapter default; its HTTP value mapping and read-only boundary remain adapter-specific. | +| #5805 Postgres HTTP; #5807 Redis/SQLite | Still their own open design work as of this baseline. They must fill in concrete query shapes, mode/default, mapping/loss, and failure limits; this record does not predetermine their transport or schema. | +| p2panda candidate routed from #5672 | Dispositioned as deferred interop/export, not a v1 generic adapter. No parent decision is changed. | + +**No further design split is required for #5803.** The remaining concrete +adapter choices belong to their existing tickets; implementation timing and +any p2panda interop work remain separate decisions. + +## Sources checked + +- Parent issue #5672, including Part B and the WS-F2 p2panda cross-link: + . +- IndexedDB decision, merged PR #7579: + and + [`doc/2026-11-08_design_id5804.md`](2026-11-08_design_id5804.md). +- Turso/libsql decision comment on #5806 (2026-11-08): + . +- ID sort-preserving key type tags in the baseline: + [`pkgs/id/crates/id-core/src/tuple.rs`](../pkgs/id/crates/id-core/src/tuple.rs). +- p2panda project overview and API stability statement: + . +- p2panda Tauri example (schema deployment, GraphQL query surface, and node + identity): .