Merge origin/main into hands/variants-c2a (docs and research only)
This commit is contained in:
commit
3157d4b325
17 changed files with 2059 additions and 0 deletions
|
|
@ -31,6 +31,79 @@ copy of the solver and the warm/cold sweep, `suite` a scratch copy of `packages/
|
|||
conditional commit compares that (ruling `aetheria-release:ruling:expect-fix-in-cultcache`). C# only. The
|
||||
release that carries it to Aetheria follows question `cultlib-gaps:question:expect-fix-release-lane`; the
|
||||
Aetheria pin bump is an Aetheria follow-on, not this cut.
|
||||
9. `aot-record-ref-generator` (section A, AOT cut 1): a consumer with MessagePack's source generator on can declare
|
||||
`CultRecordRef<T>` members and dictionary keys. Base: the C2a branch head `a768b821`; Hands starts after C2a merges
|
||||
to main or rebases onto it. Serves `record-ref-breaks-msgpack-generator`, the first cut of
|
||||
`cs-aot-safe-registration` (operator 2026-10-27: "I'm not a fan of requiring reflection. ... AoT is a nice thing to
|
||||
support anyway.").
|
||||
10. Not mapped (AOT cut 2): the generator reaches consumers that reference only `GameCult.Caching.MessagePack` (today its
|
||||
analyzer is `PrivateAssets="all"`, so they run every document on Reflection.Emit).
|
||||
11. Not mapped (AOT cut 3): registration descriptors are generated instead of reflected (`BuildDescriptor`,
|
||||
`DiscoverMembers`, `CultDocumentResolver`, `CultMessagePackSecurity`), and C2a's element-id walk stops reflecting
|
||||
(A6), so a NativeAOT consumer round-trips a ref-keyed dictionary.
|
||||
|
||||
## A. AOT cut 1: CultRecordRef under MessagePack's source generator (cut `aot-record-ref-generator`)
|
||||
|
||||
Imagination pass `imagination-aot-cut1`, session `self-2026-10-27-eureka`, pinned to `origin/hands/variants-c2a` at
|
||||
`a768b821` (C2a's head; merge base with main `02cf04b5`). Starting evidence: `research/cultmesh-garden-path/cultcache-aot-probe-2026-10-27.md`
|
||||
(main `eb6a8f2c`). Probes: the scratch console from that note, copied to the session scratchpad
|
||||
`imagination-aot-cut1/aot-probe/` and committed only as dangling commits on top of `a768b821` (`a0f06b2c`, `6d382961`,
|
||||
`dc6cf9dc`, `99cae039`, `07b89982`), run on Yggdrasil in `mcr.microsoft.com/dotnet/sdk:10.0` (MessagePack 3.1.7, .NET
|
||||
10.0.12). Logs `job1.log` to `job5.log` beside the probe. Variants: G = `CultRecordRef<T>` member only, H = ref-keyed
|
||||
`Dictionary<CultRecordRef<T>, float>` only, B = both. Every variant references `MessagePack` directly (generator on).
|
||||
|
||||
### Body facts
|
||||
|
||||
- A1. The generator does not discover `CultRecordRefFormatter<T>`. For a generic type it does not know, it collects
|
||||
the type's definition as an object and names the formatter it would generate, `<Type>Formatter<T>`, nested in
|
||||
`GeneratedMessagePackResolver`. For a type from another assembly it then generates nothing, so the resolver names
|
||||
`GeneratedMessagePackResolver.GameCult.Caching.CultRecordRefFormatter<T>`, which does not exist (CS0426). The match
|
||||
with our formatter's name is a coincidence. Evidence (job1): `[ExcludeFormatterFromSourceGeneratedResolver]` on the
|
||||
formatter, and an `internal` formatter, both still fail G, H and B with the same line. Upstream issue
|
||||
MessagePack-CSharp#2133 (open, no maintainer reply) reports the same failure for any open-generic type with a
|
||||
formatter in another package.
|
||||
- A2. Consumer MessagePack 3.1.12, the newest stable, fails G, H and B the same way (job1). Upgrading does not fix it.
|
||||
- A3. `[MessagePackFormatter(typeof(CultRecordRefFormatter<>))]` on the `CultRecordRef<T>` struct stops the
|
||||
generator naming a formatter for it (the mangled line is gone), but the generator then reports `MsgPack006` (error)
|
||||
in every consumer: it checks `typeof(X<>)`'s interfaces, which an unbound generic does not list. Adding the
|
||||
non-generic `IMessagePackFormatter` marker to the formatter does not help (job2 `ta2`). With `MsgPack006`
|
||||
suppressed by the consumer, G, H and B build and run (job2). Rejected: it needs the formatter moved into
|
||||
`GameCult.Caching`, which then needs the whole `MessagePack` package instead of `MessagePack.Annotations`, and every
|
||||
generator consumer still has to suppress an error.
|
||||
- A4. `[assembly: MessagePackAssumedFormattable(typeof(CultRecordRef<>))]` in the consumer assembly fixes G, H and B
|
||||
with no library change (job2 `base@ASSUMED`). The generator stops collecting `CultRecordRef<T>`; the generated
|
||||
document formatter asks the resolver, and `CultDocumentResolver` serves the ref. This is the attribute MessagePack
|
||||
documents for "a formatter added through a custom resolver at runtime". The same attribute as an MSBuild
|
||||
`AssemblyAttribute` item in the consumer project (`_Parameter1_IsLiteral`), which is what a package's
|
||||
`buildTransitive` targets injects, does the same (job3 MG, MH, MB). The attribute declared in the library assembly
|
||||
does not reach the consumer's generator (job4 LIBATTR: CS0426).
|
||||
- A5. Generated and dynamic formatters write the same bytes. RefDoc (B) payload is `93A172A17081A170CA3F000000` from
|
||||
the Reflection.Emit fallback with no generator (job3 BASE) and from the generated formatter (job3 MB). The document
|
||||
formatter is `GeneratedMessagePackResolver+Probe+RefDocFormatter` (`dynamic=False`); the ref formatter is the
|
||||
library's `CultRecordRefFormatter<PlainDoc>` through `CultDocumentResolver`.
|
||||
- A6. NativeAOT (`PublishAot`, probe assembly rooted, linux-x64): G round-trips (payload, upsert, flush, reopen) with
|
||||
payload `92A172A170`, identical to JIT (job4 G0). B fails, in C2a code, not in the generator path: upsert fails in
|
||||
`CultElementIds.MapEntries`, whose `MakeGenericMethod(key, value)` has no native code for a struct key (job4 B0). With
|
||||
that walk reading the map through non-generic `IDictionary` instead, upsert passes under AOT and JIT is unchanged
|
||||
(job5 B1), but the payload and flush still throw `TargetInvocationException` from a second reflective call on the
|
||||
serialize path. By source read the candidate is `ResolverClaim`'s `GetFormatterMethod.MakeGenericMethod(type)`
|
||||
(`CultDocumentMessagePackSerialization.cs:84`), not proven. Both are runtime reflection over element-id paths, which is
|
||||
AOT cut 3's ground, so cut 1 proves AOT on the member shape and leaves the key shape's AOT round trip to cut 3.
|
||||
- A7. `GameCult.Geometry` already runs the generator (it references `MessagePack` directly) and carries the per-member
|
||||
workaround on three members (`CultGeometryDocuments.cs:164,239,328`). Under A4 those attributes are redundant.
|
||||
|
||||
### Shape the cut lands, and why
|
||||
|
||||
`GameCult.Caching.MessagePack` ships `buildTransitive/GameCult.Caching.MessagePack.targets`, which adds the A4 assembly
|
||||
attribute to every project that consumes the package. NuGet consumers need no line of their own, which is what a
|
||||
consumer expects from a library whose type breaks the generator. Unity consumers and in-repo `ProjectReference`
|
||||
consumers do not get `buildTransitive`: Unity consumers write the one attribute line (README), and in-repo consumers
|
||||
import the targets file, so they exercise the file that ships. The attribute type comes from `MessagePack.Annotations`,
|
||||
which `GameCult.Caching` already brings, so the injection compiles in a consumer with or without the generator. Wire
|
||||
bytes do not change: no formatter changes, only which code path asks for it (A5).
|
||||
|
||||
Rejected: a type-level formatter attribute (A3); excluding or hiding the formatter (A1); upgrading MessagePack (A2);
|
||||
declaring the attribute in the library (A4); keeping per-member attributes, which cannot reach dictionary keys.
|
||||
|
||||
## B. BoundedLeastSquares stopping
|
||||
|
||||
|
|
|
|||
76
docs/cultmesh-garden-path-map.md
Normal file
76
docs/cultmesh-garden-path-map.md
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
# CultMesh garden path: map
|
||||
|
||||
Campaign `cultmesh-garden-path`, stage 1 (server-authoritative garden path for the
|
||||
orbs .io game). Target: `docs/cultmesh-garden-path-target.md` (typed as
|
||||
`cultmesh-garden-path:target:r1`). Rulings, questions and follow-ups are documents
|
||||
in the mind; this page holds the model page, body facts and the stage 1 cut lines.
|
||||
|
||||
Written by Imagination (`imagination-gp-0b`, session `self-2026-10-27-eureka`)
|
||||
against CultLib `d1bf21b3`.
|
||||
|
||||
## Model page
|
||||
|
||||
One row per kind. "Store" says where it lives: a CultCache document in the room's
|
||||
store, or transient per-tick data that never enters a store. Proposed values are
|
||||
marked as such; they are the design this page offers for the cuts, not landed
|
||||
behaviour. A cell that waits on an operator question names it.
|
||||
|
||||
The governing split, from `state-is-cultcache` and the CultCache scope restraint:
|
||||
every value that crosses a boundary is CultCache-encoded (one serialisation model,
|
||||
no JSON), but only state that outlives a tick is a record in a store. Inputs, ticks
|
||||
and snapshots are typed CultNet message payloads, not store records. The store
|
||||
receives at most one write set per tick (question `tick-state-commit`).
|
||||
|
||||
| Kind | Store | Identity (what names it) | Lifecycle (what happens to it) | Authority (who decides; forbidden writers) |
|
||||
|---|---|---|---|---|
|
||||
| **Game definition** (documents, systems, authority declaration, tick rate) | Proposed: one CultCache document per server process (`gamecult.mesh.game_definition`), read-only to everyone but the server's startup. | Game id string from code (`"orbs"`), namespaced by Verse id. The id alone is not injective (two builds share it), so proposed identity is `(game id, definition hash)`, the hash derived from the lowered definition: document schema ids and versions, system ids, order and marks (`[Predicted]`, later `[Adjudicable]`), tick rate, authority declaration. Schema ids (`orbs.player`) are global strings; the game prefix is convention, not enforced (body fact F9). | Created at server startup from code; never revised at runtime; a new build supersedes it with a new hash. Clients carry their own compiled hash (C# in wasm, ruling `browser-sim-runtime`) and are refused at join on mismatch. A declaration a mode cannot honour is refused at startup (`modes-do-not-leak`). Never replayed. | The game's code, through the builder, at startup; the runtime validates. Forbidden: clients, any runtime mutation, Odin (Odin may read and index it, never write it). |
|
||||
| **Game document** (Player, Pellet, Shot) | CultCache documents in the room store. | `(schema id, record key)`. Today the key is a free string the caller picks; `[CultIndex] Id` in the illustration is an index, not the key. Proposed: the runtime mints keys. Player key derives from the session principal (one Player per principal per room). Spawned documents (Shot, Pellet) key on `(spawner key, tick, spawn ordinal within that tick)`, so a client's predicted spawn and the server's authoritative spawn derive the same key and reconcile instead of duplicating. That is injective as long as spawn order within a system step is deterministic for the predicting client, which the predicted system's own code gives under one runtime (C# both sides). The developer's `Id` field becomes redundant; whether to keep it as a mirror of the key is an API call for the cut, not an operator fork. | Created by a system during a tick, or by the join system (Player). Revised at most once per tick, in that tick's commit. Deleted by a system (pellet eaten) or by the game's leave system after a session ends. Across reconnect within the grace window the Player record is unchanged; only the session's connection binding moves. Across a server restart: waits on `room-durability`. Replayed only on the client, during reconciliation; the server never replays in stage 1. | The server tick runner on the room's primary is the one writer of committed state, and systems write only through the tick's working set. Forbidden writers: client document puts through `CultNetDatabaseServer.HandlePutAsync` (today accepted from any peer, F1); `PutPredictedAsync` and `CultMeshGameSession.PredictAsync` on any networked store; game code calling database APIs; the simulation-fact committer (F7). |
|
||||
| **Player input** | Transient. A CultCache-encoded payload on a CultNet message; never a store record in stage 1. | `(session principal, input sequence)`, the sequence monotonic per session; each input also carries the tick it targets. Namespace: the room. Injective given the principal. The input type is a schema'd CultCache type, so the schema catalog publishes it like any document. | Sampled each client tick (devices read by the TS shell, handed to wasm); sent with the last few unacknowledged inputs repeated, so one loss is absorbed; buffered by the server per session against its target tick; consumed exactly once by the matching tick (proposed policy for late inputs: applied to the next tick and counted); acknowledged in the snapshot as "last processed sequence"; kept by the client until acknowledged, for replay; then discarded. Stage 4 changes this: inputs become signed, hash-chained and retained for a dispute window. | The client's principal authors the content; the tick runner decides which tick consumes it. Forbidden: server code altering input content; other clients; any input that arrives without a bound session. |
|
||||
| **Tick** | Transient counter; proposed: the last committed tick is written into the room record in each tick's batch, so a snapshot or checkpoint knows it. | `(room id, room epoch, tick number)`, the number starting at 0 when the room epoch starts. Injective with the epoch. | Advanced only by the server tick runner at the declared rate (waits on `tick-model`); never revised. The client estimates the server tick from snapshots and runs its predicted tick ahead by its round trip plus a buffer; on reconnect it re-syncs from the next full snapshot. | Server tick runner. Forbidden: client clocks, transport arrival time, wall-clock reads inside systems (systems receive the tick, not the time). Today no tick scheduler exists anywhere in the C# body (F6). |
|
||||
| **Predicted state and reconciliation** | Client-side only. Where its documents live in the browser waits on `browser-client-store`. | Same `(schema id, record key)` as the authoritative document, plus the client tick it was predicted for. | Each client tick: predicted systems run over owned documents and the client's own spawns. On a snapshot for tick T acknowledging input sequence S: predicted documents are replaced by the authoritative ones at T, then inputs after S are replayed through the predicted systems up to the current client tick; predicted spawns are matched by derived key, and an unmatched one is removed once the acknowledgement passes its tick. Today `Reconciled` means "the authoritative put replaced the predicted copy" with no replay (F3); the replay loop does not exist. | Predicted state owns nothing outside the client. It is derived from the last authoritative snapshot plus unacknowledged inputs plus the predicted systems. The snapshot owns truth. Forbidden: sending predicted documents to the server; `CultNetClientAuthorityScope` in server mode (F4); the renderer writing. |
|
||||
| **Session and the player's identity** | Proposed: session membership as a small CultCache document in the room store (`gamecult.mesh.game_session`, low churn, readable by systems and present in snapshots). The connection handle is transient process state. | Principal: waits on `player-identity`. Connection: a server-minted id per transport connection (ephemeral). Logical session: `(principal, room)`, bound across reconnects. Today the client's identity is a self-asserted `runtimeId` string (browser client options; `SourceRuntimeId` on operation envelopes); CultMesh's session identity proves the server to the client and not the reverse (F5). **This cell is empty in the body: there is no authenticated client principal.** | Connect, then join (definition hash check, principal proof), then the session record is created and the join system spawns the Player. Disconnect suspends the session for a grace window; resume binds a new connection to the same session; expiry ends the session, systems see the leave, and the game's leave system removes the Player. On server restart sessions end (unless `room-durability` says otherwise). | The server's join and leave handler on the room primary decides membership; the principal proves itself (how depends on `player-identity`). Forbidden: a client-asserted `runtimeId` as identity; transport peer address; peer catalogs. |
|
||||
| **Authority declaration and the lease it lowers to** | Declaration: inside the game definition. Lease: proposed as a CultCache document (`gamecult.mesh.authority_lease`); today a plain class in an in-memory dictionary (F2). | Declaration: per document type, `(writer, checker, arbiter)`. Lease: `LeaseId`, carrying Verse, peer, roles, shard ids, issuer, validity window, epoch and signature (`CultMeshAuthorityLease`). Namespace: the Verse. | Declaration fixed per build. At startup `Authority.Server` lowers to: the server holds a `ShardPrimary` lease on the room shard, and clients hold no write scope at all. Renewed before expiry; revocation or expiry stops the tick runner from committing; a new primary takes a new epoch. Proposed issuer in stage 1: the server's own deployment key, which clients pin through the browser trust policy, so an indie deployment needs no Odin. Odin-issued leases stay possible. | The game definition decides the declaration; the issuer issues leases; `CultMeshAuthorityResolver` decides whether a peer holds a role on a shard. Today the database's write gate (`CultNetShardDescriptor.IsPrimary`, `CultNetClientAuthorityScope`, both set from options) never consults the resolver: two authority structures (F2, F4). Proposed: the write gate is derived from lease resolution. `CultNetClientAuthorityScope` is no longer an owner; it is derived from the declaration, and in stage 1 it is empty. |
|
||||
| **Shard / room** (stage 1: one) | `CultNetShardDescriptor` (configuration); the room's state is its CultCache store. | Room id `(Verse, game id, room name)`, for example `orbs/main`, carried as the shard id plus the shard epoch. | Created at server start (epoch 1; on restart a new epoch, or a resumed one if `room-durability` says so); never moved in stage 1; ended at shutdown. Join means "join the one room"; matchmaking is out of scope. Interest management is stage 5 per the target, so in stage 1 every client receives the whole room. | The runtime holding the `ShardPrimary` lease. Forbidden: a second primary; clients. |
|
||||
| **Snapshot sent to clients** | Transient. A CultNet message whose payload is CultCache-encoded documents; never stored. The server keeps per-client baselines in memory for deltas. | `(room, epoch, tick, recipient session, baseline tick)`. | Derived after a tick commit at the send rate; a delta against the recipient's last acknowledged snapshot, or a full snapshot on join and resume; carries the last processed input sequence for that session. Discarded once sent; a baseline is dropped when a newer one is acknowledged. Today the nearest things are per-record change pushes from `CultNetDatabaseSubscriptionServer` (no tick, no acknowledgement, no input sequence) and shard catch-up snapshots in `CultMeshSnapshots.cs` (F8). | The snapshot builder decides nothing; it is derived from the committed tick. Forbidden: the per-record subscription stream acting as a second game replication path. That stream stays for non-game observers. |
|
||||
| **Simulation fact / witness observation** (found) | `CultMeshSimulationFact` is a CultCache document; observations are hub memory. | `(shard, epoch, frame, subject, kind)`. | Stage 1: not used. The target replaces it at stage 4. | Today `CultMeshGameSession` serves observations by default (`ServeSimulationObservations = true`) and commits quorum facts through the primary (F7). In server mode there is no checker, so the observation server and the committer must not be wired. Forbidden writer in stage 1. |
|
||||
| **Shard mutation log entry** (found) | `CultNetDatabase` in-memory `SortedList` per shard, plus an optional durable store. | `(shard id, sequence)`. | Today every primary write appends one entry, and the in-memory list is never trimmed (F10). Per-record writes at tick rate would grow it without bound. In stage 1 the tick's write set either bypasses the per-record log or lands as one bounded entry per tick. Waits on `tick-state-commit` and `room-durability`. | `CultNetDatabase` on the primary. Forbidden: per-system-write appends from the tick runner. |
|
||||
|
||||
### Cells not filled
|
||||
|
||||
- Session principal: no authenticated client identity exists (F5). The question is `player-identity`.
|
||||
- Where the browser's predicted and decoded documents live, and what the renderer reads: `browser-client-store`.
|
||||
- Room state across restarts: `room-durability`.
|
||||
- Tick rate model: `tick-model`.
|
||||
- How a tick reaches the store: `tick-state-commit`.
|
||||
- Stage 1 transport: `browser-transport`.
|
||||
- Unknown and not probed here: whether `CultCacheBatch` commit cost holds at tick rate for about 50 players plus pellets. The first cut's measuring probe should include it.
|
||||
|
||||
## Body facts
|
||||
|
||||
All are source reads at CultLib `d1bf21b3` on 2026-10-27 by `imagination-gp-0b`. No
|
||||
runtime probe was run in this pass. Each fact names the read that would falsify it.
|
||||
|
||||
- **F1. The primary applies any peer's document put.** `CultNetDatabaseServer.HandlePutAsync(message, peer)` (`src/GameCult.Networking/CultNetDatabaseServer.cs:307`) calls `ApplyPutAsync(message)` (`CultNetDatabase.cs:1022`), which checks only that this runtime is primary for the shard and the epoch matches (`EnsurePrimary`, `:2003`). `peer` is used only to send errors. Any connected client can overwrite any game document on the server.
|
||||
- **F2. Leases are not typed state and do not gate writes.** `CultMeshAuthorityLease` is a plain class (no `[CultDocument]`); `CultMeshAuthorityLeaseCatalog` is a `Dictionary` (`CultMeshAuthority.cs:242`). The only `[CultDocument]` types in `GameCult.Mesh` are body publication, CDN chunk and manifest, content transfer state, discovery state, entity prefab package and simulation fact. `GameCult.Networking` (the database) references no lease type; the one Networking file naming `Lease` is `CultNetSchemaMessages.cs`.
|
||||
- **F3. Reconciliation is replacement, not replay.** `CultNetDatabase.cs:1247-1252`: a predicted put records a prediction key; the next non-predicting write to that key turns the change into `Reconciled`. No code re-applies inputs after an authoritative state.
|
||||
- **F4. Client write scope is a runtime-id string match from options.** `CultNetClientAuthorityScope.Matches` compares `OwnerRuntimeId` with the database's own `_runtimeId` (`CultNetDatabase.cs:111-153`, `EnsureClientAuthority` `:1934`). It gates local prediction only and has no relation to leases.
|
||||
- **F5. No authenticated client principal.** `CultMeshSessionIdentity.cs` verifies transports for `(verse, authorityRuntimeId, protocol, routeGeneration)`, which proves the server to the client. The browser client's `runtimeId` (`packages/cultmesh-browser/src/index.ts:182`) and the operation envelope's `SourceRuntimeId` (`CultNetOperationServer.cs:39`) are self-asserted.
|
||||
- **F6. No tick scheduler.** A grep of `GameCult.Networking` and `GameCult.Mesh` for tick or timestep names finds none. `Frame` exists only as a witness-asserted number in `CultNetSimulationConsensus` and `CultMeshSimulationFact`.
|
||||
- **F7. The game session serves the witness path by default.** `CultMeshGameSession` constructs `CultNetSimulationObservationServer` when `ServeSimulationObservations` (default `true`) and always constructs a `CultMeshSimulationFactCommitter` (`CultMeshGameSession.cs:70-104`). `PredictAsync` is `PutPredictedAsync` (`:161`).
|
||||
- **F8. The browser can watch and invoke, not put.** The `cultmesh-browser` README says it "does not expose direct document writes". The client offers `leaseRawDocument` (`index.ts:349`) and `invoke` of typed operations (`:370`), over one WebSocket. On C#: `CultNetDatabaseSubscriptionServer` and `CultNetOperationServer` take `ICultNetSchemaServer`, so they run over `CultNetWebSocketSchemaServer`; `CultNetDatabaseServer` (puts) takes the concrete UDP `Server` (`CultNetDatabaseServer.cs:36`). Operations are request and response with receipts and idempotency keys, which is a poor fit for an input stream at tick rate.
|
||||
- **F9. Schema-id namespacing is convention.** `[CultDocument("orbs.player", ...)]` ids are global strings; nothing ties a schema id to a game id.
|
||||
- **F10. The in-memory mutation log is never trimmed.** `RecordMutationLogEntry` (`CultNetDatabase.cs:1610`) inserts into a per-shard `SortedList`; no `Remove` or trim on that list exists in the file. Compaction applies to the durable store and to burned sequences only.
|
||||
- **F11. CultCache has a write-set batch; CultNetDatabase does not expose one.** `CultCacheBatch` with `Commit` and `TryCommit` (`GameCult.Caching/CultCache.cs:1796`, `:2212`) is the 2.0.0 write set (`variants:ruling:write-set-content-version-declared-ownership`). `CultNetDatabase` has no batch method: every write is a per-record door.
|
||||
- **F12. A reflection site on the mesh put path.** `CultMesh.cs:3502` `PutDatabaseDocumentAsync` picks `PutAsync` or `PutPredictedAsync` by `GetMethods` and `MakeGenericMethod`, which matters to the AOT prerequisite (`cultlib-gaps:follow_up:cs-aot-safe-registration`; probe in `research/cultmesh-garden-path/cultcache-aot-probe-2026-10-27.md`).
|
||||
|
||||
## Cut sequence (stage 1)
|
||||
|
||||
One line per cut not yet mapped. None is mapped until the model page has no empty cell.
|
||||
|
||||
- **Wasm runtime measuring probe.** Download size, startup and 60 Hz tick cost of a stub orbs tick under Mono browser-wasm and NetWasm, including `CultCacheBatch` commit cost at tick rate. This is the first cut named by ruling `browser-sim-runtime`, which it can overturn. Its NetWasm and AOT variant waits on `cultlib-gaps:follow_up:cs-aot-safe-registration`.
|
||||
- **Authority collapse.** Leases become CultCache documents, the database write gate derives from lease resolution, the put handler refuses peers without authority (F1), `CultNetClientAuthorityScope` is demoted, and witness services are not wired in server mode (F7). Waits on nothing.
|
||||
- **Game definition and server tick runner.** Builder, document and system registration, definition document and hash, fixed tick, tick-boundary commit. Waits on `tick-model`, `tick-state-commit` and `room-durability`.
|
||||
- **Session and principal.** Join, resume and leave; principal proof; session document. Waits on `player-identity`.
|
||||
- **Input and snapshot path.** Input messages with redundancy, a server input buffer, acknowledgements, delta snapshots. Waits on `browser-transport`.
|
||||
- **Browser client runtime.** Wasm simulation host, TypeScript shell for transport and rendering, prediction with replay reconciliation. Waits on the measuring probe and `browser-client-store`.
|
||||
- **Orbs reference game and garden-path proof.** The game written with no networking code (`garden-path-needs-no-networking`), and a browser client that writes (`browser-is-first-class`). Waits on all of the above.
|
||||
153
docs/cultmesh-garden-path-target.md
Normal file
153
docs/cultmesh-garden-path-target.md
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
# CultMesh garden path: target
|
||||
|
||||
Status: draft target for campaign `cultmesh-garden-path`, 2026-10-27. It holds the
|
||||
ends, not the means. The code below is illustrative: it shows what a developer
|
||||
should have to write, and no name in it is decided.
|
||||
|
||||
## The problem
|
||||
|
||||
Operator, 2026-10-27: "the value is in solving the multiplayer scaling problem
|
||||
for indie developers in an ergonomic fashion. Having one authoritative server is
|
||||
fine, up to a point, but there's no real open source playbook on how to ship an
|
||||
MMO, and existing solutions like SpacetimeDB have a huge ergonomics gap. I want
|
||||
CultMesh to feel like magic: as a garden path, you annotate your domain POCOs and
|
||||
simulation code and declare your authority structure ... and it'll all just work
|
||||
without the developer needing to understand networking deeply."
|
||||
|
||||
Prior art: `research/cultmesh-garden-path/prior-art-2026-10-27.md` (frameworks,
|
||||
ergonomics, scale-out) and `research/witness-authoritative-networking/` (consensus
|
||||
and P2P anti-cheat). What the field shows, in short:
|
||||
|
||||
- One API over several authority modes ships today (Photon Fusion: Server, Host,
|
||||
Shared; Unity NGO: client-server and distributed authority), and in both the
|
||||
modes leak into the developer's code (`IsServer` against `HasAuthority`,
|
||||
features missing in one mode).
|
||||
- SpacetimeDB gives one machine per database. Scaling past it, client
|
||||
prediction, and the reducer-shaped rewrite of game code are left to the
|
||||
developer.
|
||||
- Determinism, where it is required at all, is required of the whole simulation
|
||||
(Croquet/Multisynq, Photon Quantum), and that tax is the main ergonomic cost.
|
||||
- Shipped world-scale designs treat a spatial unit as indivisible and move
|
||||
players between units (EVE, Pax Dei, Folia); nobody publishes an open,
|
||||
end-to-end playbook (Astron, the nearest, is discontinued).
|
||||
|
||||
## What a developer writes (illustrative)
|
||||
|
||||
The reference game is a small browser .io game (operator, 2026-10-27: "the .io
|
||||
game, Aetheria later"): players steer orbs, eat pellets, and shoot.
|
||||
|
||||
```csharp
|
||||
[CultDocument("orbs.player", "orbs.player.v1")]
|
||||
public sealed class Player
|
||||
{
|
||||
[CultIndex] public string Id { get; set; } = "";
|
||||
public Fix2 Position { get; set; }
|
||||
public Fix2 Velocity { get; set; }
|
||||
public int Mass { get; set; }
|
||||
}
|
||||
|
||||
[CultDocument("orbs.shot", "orbs.shot.v1")]
|
||||
public sealed class Shot
|
||||
{
|
||||
[CultIndex] public string Id { get; set; } = "";
|
||||
public string Shooter { get; set; } = "";
|
||||
public Fix2 Origin { get; set; }
|
||||
public Fix2 Direction { get; set; }
|
||||
}
|
||||
|
||||
// Runs every tick. Predicted on the owning client, corrected by authority.
|
||||
public sealed class Movement : CultSystem
|
||||
{
|
||||
[Predicted]
|
||||
public void Step(Player player, PlayerInput input, Tick tick) { /* ... */ }
|
||||
}
|
||||
|
||||
// A non-owner may re-run this to settle a dispute, so it must be
|
||||
// deterministic. The analyzer enforces that on this system only.
|
||||
[Adjudicable]
|
||||
public sealed class Hits : CultSystem
|
||||
{
|
||||
public HitResult Resolve(Shot shot, Rewind<Player> target) { /* ... */ }
|
||||
}
|
||||
|
||||
var game = CultMesh.Game("orbs")
|
||||
.Documents<Player, Pellet, Shot>()
|
||||
.Systems<Movement, Eating, Hits>()
|
||||
.Authority(Authority.Server);
|
||||
// .Authority(Authority.TrustedCoop);
|
||||
// .Authority(Authority.Witnessed(w => w.Challenger(Party.Victim).Quorum(3).Arbiter(Party.Server)));
|
||||
// .Authority(Authority.Regions(r => r.Grid(512).Handoff())); // later: past one server
|
||||
```
|
||||
|
||||
Changing the authority line is the whole migration between modes, unless the new
|
||||
mode re-executes a system on a non-owner and that system is not yet
|
||||
deterministic. Then the analyzer names exactly those systems.
|
||||
|
||||
## Invariants
|
||||
|
||||
- `one-model`: server-authoritative, trusted co-op, witnessed and regioned
|
||||
authority are configurations of one authority declaration, answering per
|
||||
document: who writes, who checks, who arbitrates. No mode has its own API for
|
||||
state, systems or queries.
|
||||
- `modes-do-not-leak`: game code does not branch on the authority mode or ask
|
||||
"am I the server"; a system states what it does and the runtime decides where
|
||||
it runs. Where a mode cannot offer a capability, the declaration is refused at
|
||||
startup with a reason, never degraded silently at runtime.
|
||||
- `determinism-is-per-system`: only code a non-owner may re-execute must be
|
||||
deterministic. That requirement is marked on the system and checked by an
|
||||
analyzer at build time, not by documentation or by desync in production.
|
||||
- `state-is-cultcache`: game state is ordinary CultCache documents; the
|
||||
framework adds no second state model and no JSON on the load-bearing path.
|
||||
- `authority-is-typed-state`: who holds authority over what is CultMesh state
|
||||
(leases, shard primaries), inspectable and revocable, never inferred from
|
||||
transport success or peer catalogs.
|
||||
- `garden-path-needs-no-networking`: the reference game is written without the
|
||||
developer touching sockets, serialisation, tick scheduling, prediction or
|
||||
reconciliation code.
|
||||
- `honest-guarantees`: each mode states its fault model (trusted server, trusted
|
||||
peers, honest-majority sampled witnesses with server arbitration) and its
|
||||
documentation and tests claim nothing past it.
|
||||
- `browser-is-first-class`: the reference game's client runs in a browser and can
|
||||
write (submit inputs, own predicted state), not only watch.
|
||||
- `built-for-load`: what the garden path ships that is database-shaped (the
|
||||
tick commit, the batch door, logs, subscriptions) is architected for
|
||||
unreasonable load from the start (operator 2026-10-27,
|
||||
`cultlib-gaps:ruling:database-shaped-built-for-load`): "if what we're shipping
|
||||
is database shaped, people will use it as such".
|
||||
|
||||
## Sequence (each a campaign or stage of its own; one foundation at a time)
|
||||
|
||||
1. Server-authoritative garden path for the .io game: documents, systems,
|
||||
ticked scheduling, client prediction and reconciliation, browser client that
|
||||
writes. This is the proof of ergonomics.
|
||||
2. Trusted co-op: authority moves to the owning peer; same game code.
|
||||
3. Deterministic dispute kernel (CultMath fixed-point hit tests, cross-runtime
|
||||
vectors) and the `[Adjudicable]` analyzer.
|
||||
4. Witnessed authority: signed, hash-chained inputs; victim challenge; sampled
|
||||
network-near witnesses; server arbitration; browser-to-browser channels.
|
||||
Demonstration: a cheating client caught and corrected.
|
||||
5. Regions: spatial authority handoff and interest management past one server.
|
||||
6. Aetheria on the same declaration.
|
||||
|
||||
## Not in scope
|
||||
|
||||
- Aetheria until stage 6. Eve and Gjallar (deprecated).
|
||||
- A new CultCache storage engine (the paged single-file store stays postponed,
|
||||
`variants:ruling:page-tree-store-postponed`). The garden path fills gaps in
|
||||
their owners, built for load.
|
||||
- Asynchronous Byzantine total ordering, zero-knowledge proofs, and chains of
|
||||
any kind.
|
||||
- The existing witness aggregator (`CultNetSimulationConsensus`, unsigned and
|
||||
weighted by observed votes) as a base for stage 4: it is the trusted co-op
|
||||
first stage by design and will be replaced, not extended.
|
||||
|
||||
## Open forks (to the Fork Desk, each with prior art first)
|
||||
|
||||
1. Where simulation code runs in the browser: C# compiled to WebAssembly (one
|
||||
implementation everywhere, which also shrinks the determinism problem to
|
||||
fixed-point maths, at the cost of runtime download size), C# on the server
|
||||
with TypeScript systems in the browser (two implementations of each predicted
|
||||
system), or another arrangement.
|
||||
2. Server transport for the browser: WebSocket as today, or WebTransport
|
||||
(QUIC datagrams) on the provider side.
|
||||
3. Tick model: fixed tick with a declared rate, or per-system rates.
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
Serves the C2a fork on finding variants:finding:cut-land-c2a-gate.s1.reflist-record-read-only-at-head (campaign variants), 2026-10-23.
|
||||
|
||||
# Prior art: read with an old writer schema, then write back
|
||||
|
||||
Facts only. Pages were fetched 2026-10-23 through a summarising fetcher; "not stated" means the fetched page did not say it, not that no source does. Items marked (memory) are my background knowledge, not verified from a fetched page.
|
||||
|
||||
## 1. Apache Avro
|
||||
- Source: https://avro.apache.org/docs/current/specification/ (Schema Resolution; summarised via apache/avro doc source), Java `DataFileWriter` javadoc (1.11.1).
|
||||
- Model: the writer schema travels with the data. The reader resolves it against its own reader schema. Resolution is a read-time projection; the spec defines no write-back.
|
||||
- Data loss on projection: "the writer's value for that field is ignored" when the reader schema lacks the field. A reader-only field takes its default, or the read errors if it has none.
|
||||
- Write-back: the spec states no rule. Object container files store one schema in the header ("Each datum in a file is of the same schema"). `appendTo` is documented only as "Open a writer appending to an existing file"; it does not say which schema the append uses. (memory: Java `appendTo` reuses the file's header schema, so an append never restamps.)
|
||||
- Stated reason for the read-time design: readers and writers evolve separately (fields added or removed in a different software version).
|
||||
|
||||
## 2. Protocol Buffers (proto3)
|
||||
- Source: https://protobuf.dev/programming-guides/proto3/ (Unknown Fields).
|
||||
- On write: unknown fields are "included during parsing and in the serialized output" (matches proto2). Round-trip keeps fields the current type does not know.
|
||||
- Loss cases the page lists: serializing to JSON, and copying a message field by field into a new message (it recommends `CopyFrom`/`MergeFrom`).
|
||||
- No schema id or version is written. The wire format carries only field numbers, so "restamp" has no meaning here.
|
||||
- Not stated: behaviour in versions before 3.5 (memory: proto3 dropped unknown fields before 3.5, then reversed). The Java reference page says nothing on preservation.
|
||||
- Stated reason: preserve data across a mixed-version fleet.
|
||||
|
||||
## 3. Confluent Schema Registry
|
||||
- Source: https://docs.confluent.io/platform/current/schema-registry/fundamentals/schema-evolution.html
|
||||
- BACKWARD (default): consumers on the new schema read data written with the new or the previous version. FORWARD: data written with the new schema is readable by consumers on the old one. FULL: both.
|
||||
- Write: "Each schema version gets a unique ID and an incremented version number." A producer writes under the schema it holds (its own current version). The id is stamped per message at serialisation, from the producer's schema.
|
||||
- Upgrade order is how the rules prevent loss. BACKWARD means upgrade consumers before producers. FORWARD means upgrade producers first, and keep old-schema data away from consumers until they are upgraded.
|
||||
- Not stated on the page: what a consume-modify-produce app writes. (memory: it re-serialises under its own latest schema, so fields it does not model are lost unless a compatibility rule kept them.)
|
||||
- The registry gates registration. It does not gate individual rewrites.
|
||||
|
||||
## 4. Document DBs and ORMs with stored versions
|
||||
### MongoDB schema-versioning pattern
|
||||
- Sources: https://www.mongodb.com/blog/post/building-with-patterns-the-schema-versioning-pattern ; https://www.mongodb.com/docs/manual/data-modeling/design-patterns/data-versioning/schema-versioning/
|
||||
- Documents carry `schema_version` (absent means 1). The app keeps a handler per version and writes new documents at the current version.
|
||||
- Migration strategy is the app's choice: migrate all, migrate "when accessed" (lazy), or never.
|
||||
- Not stated: whether an update of an old document restamps it. The manual's update example branches on `schemaVersion` and writes into each version's own shape. It notes its `else: null` branch adds stray null fields to the other shape.
|
||||
- Stated reasons: no downtime, failed migrations easier to handle, timing flexibility. Cost: handler code per live version.
|
||||
|
||||
### Realm (Atlas Device SDKs, now deprecated)
|
||||
- Source: https://www.mongodb.com/docs/atlas/device-sdks/sdk/swift/model-data/change-an-object-model.md
|
||||
- Per-file schema version. A changed schema needs an incremented `schemaVersion`, plus a `migrationBlock` for non-trivial changes. The file is migrated whole at open, before any read or write, and Realm "will throw an error" if the version is lower or the same but the schema differs.
|
||||
- No lazy per-object restamp. Writes happen only on a migrated file.
|
||||
- Data loss: the manual says "Deleting a property will not impact existing objects", i.e. removal is automatic and needs no developer step. Required new properties and renames need a manual block. (memory: removed-property values are dropped from the file.)
|
||||
|
||||
### Core Data
|
||||
- Source: web search results only (Apple forum threads 745114 and 785427, WWDC22-10120, "staged migrations" doc). The Apple docs URL I tried returned 404.
|
||||
- A store whose model hash differs from the current model fails to open with an incompatible-version error. Opening migrates the whole store when `NSMigratePersistentStoresAutomaticallyOption` and `NSInferMappingModelAutomaticallyOption` are set. Lightweight migration covers only obvious patterns (add entity, remove relationship, required to optional, rename). Anything else needs a staged or custom migration.
|
||||
- Migration is store-wide at open. It does not happen per record on write.
|
||||
|
||||
### EF Core
|
||||
- Not fetched. (memory: no per-row schema stamp. Migrations are explicit, ordered DDL, tracked in a `__EFMigrationsHistory` table.)
|
||||
|
||||
## 5. Old-schema data held read-only until explicit migration
|
||||
### Elasticsearch archive indices
|
||||
- Sources: https://www.elastic.co/docs/deploy-manage/upgrade/deployment-or-cluster/reading-indices-from-older-elasticsearch-versions ; https://www.elastic.co/guide/en/elasticsearch/reference/current/archive-indices.html ; 8.0 migration notes (7.0+ indices readable, 6.x or earlier must be reindexed).
|
||||
- Indices from an older major are readable through search and field-caps. "They do not support the Get API or any write APIs."
|
||||
- The route to a writable copy is reindex into a new index that is "fully compatible with the current Elasticsearch version". `_source` is readable, so no data is lost on reindex.
|
||||
- Stated reason: the page does not say why they are read-only. It describes archive access as "slower read-only access", with limited query capability. Some legacy mappings cannot be imported (the original is kept in `_meta`), and that is the one place the page shows a lossy translation.
|
||||
- Third-party (Search Guard blog, unverified against Elastic): in 9.x a plain `index.blocks.write` does not satisfy the boot check; `index.verified_read_only` is needed.
|
||||
- This is the closest match to option (b) in the fetched set: an old format, readable but not writable, left until the owner reindexes it.
|
||||
|
||||
## Where restamp-on-write loses data (from the sources above)
|
||||
- Avro: a field present in the writer schema and absent from the reader schema is dropped at read, "ignored". Any rewrite from the resolved value would omit it.
|
||||
- Protobuf: unknown fields survive a binary round trip. They are lost via JSON, or when copied field by field.
|
||||
- Realm: removed properties are deleted by the automatic migration.
|
||||
- MongoDB: a handler that writes only the current shape can lose or relocate old-shape fields (the manual's example adds nulls).
|
||||
- Confluent: loss is prevented by compatibility rules at registration time, not at each write.
|
||||
|
||||
## Pattern across the set
|
||||
- No fetched system restamps a single record on write when the record's writer schema differs from the application's type, on an app-visible, per-record basis.
|
||||
- Avro, protobuf and Confluent carry the schema per file or message.
|
||||
- Realm, Core Data and Elasticsearch move or block the whole store or index at open.
|
||||
- MongoDB leaves it to the app.
|
||||
- Whole-store migration at open is the usual explicit step (Realm, Core Data). Elasticsearch is the one case of read-only-until-reindex.
|
||||
- Not found: a system that declares per-schema-id compatibility, as in option (b). Avro schema resolution and Confluent compatibility rules are the nearest analogues. Both are read-side or registration-side declarations.
|
||||
53
docs/research/2026-10-23-store-lock-user-code-prior-art.md
Normal file
53
docs/research/2026-10-23-store-lock-user-code-prior-art.md
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
Serves question variants:question:store-hold-user-code (campaign variants), 2026-10-23.
|
||||
|
||||
# Prior-art check: user code under a lock
|
||||
|
||||
Facts and pointers only. Each source was fetched or searched this session; what was not reachable is marked.
|
||||
|
||||
## 1. Goetz et al., Java Concurrency in Practice (Addison-Wesley, 2006), ch. 10 "Avoiding Liveness Hazards"
|
||||
Status: EXISTS, SECTION NUMBER CORRECTED.
|
||||
- "Open Calls" is **10.1.4**, not 10.1.3. 10.1.3 is "Deadlocks Between Cooperating Objects"; 10.1.2 is "Dynamic Lock Order Deadlocks"; 10.1.5 is "Resource Deadlocks". Source: text extracted from a PDF copy of the book (its TOC lists Listing 10.6 "Using Open Calls to Avoiding Deadlock Between Cooperating Objects", p. 133). The copy is an unofficial one at library.megu.edu.ua; a publisher link was not checked.
|
||||
- (a) 10.1.3 gives the warning sign: an "alien method" (defined p. 40 as a method whose behavior the calling class does not fully specify) called while holding a lock. Paraphrase: such a call may take other locks (deadlock risk) or block a long time, stalling threads that need the lock you hold. 10.1.4 defines an open call as a call made with no locks held (credited to Lea, CPJ 2.4.1.3) and says programs restricted to open calls are far easier to analyze for deadlock-freedom than ones that allow alien calls under lock.
|
||||
- Cost it names: moving a call out of a synchronized block makes an atomic operation non-atomic (its getImage example stops being a snapshot). Where atomicity is needed it suggests structuring so only one thread can run the code path after the open call (service shutdown example).
|
||||
- (b), (c): not addressed in this section.
|
||||
- Pointer: JCIP 10.1.3 and 10.1.4, pp. ~132-134 (chapter 10 starts p. 128).
|
||||
|
||||
## 2. Sutter, "Effective Concurrency: Avoid Calling Unknown Code While Inside a Critical Section"
|
||||
Status: VERIFIED, with date caveat.
|
||||
- Dr. Dobb's column in the "Effective Concurrency" series. Sutter's blog teaser is dated 2007-11-06: https://herbsutter.com/2007/11/06/effective-concurrency-avoid-calling-unknown-code-while-inside-a-critical-section/ . Original link ddj.com/architect/202802983; Dr. Dobb's mirror https://drdobbs.com/cpp/avoid-calling-unknown-code-while-inside/202802983 (4 pages). The Dr. Dobb's issue date was not shown in anything fetched; the blog date is the only date confirmed. www.drdobbs.com did not resolve from this machine, so the column body comes from search-result summaries and the blog teaser, not a full first-hand read.
|
||||
- (a) Core claim: locks do not compose; two separately correct modules can deadlock when combined. Trigger: caller inside a critical section, callee enters another critical section or blocks, another thread can take the same two in the opposite order. "Unknown code" listed as: library functions, plug-ins, callbacks/function pointers, virtual methods, generic types.
|
||||
- Mitigations listed: move the call outside the critical section; pass copies instead of shared data; narrow the critical section (finer locks, reader-writer); require callees not to block (documentation/discipline only).
|
||||
- (b), (c): not addressed.
|
||||
|
||||
## 3. Linux lockdep
|
||||
Status: VERIFIED, with a nuance.
|
||||
- Source: kernel docs "Runtime locking correctness validator", https://docs.kernel.org/locking/lockdep-design.html .
|
||||
- (b) Lockdep tracks lock classes, not instances, and records dependencies between classes as sequences are observed. It reports a circular order as a potential deadlock even if the deadlock never happened. Its "Proof of 100% correctness" section says that once each simple single-task locking sequence has occurred at least once, no timing of them can deadlock. Each new lock chain is validated once and hashed; repeats skip validation.
|
||||
- Nuance: it flags the dependency edge that closes a cycle, so both orders must have been exercised at some point (possibly by different, non-concurrent runs). A lone nesting is flagged only if it breaks a single-lock rule (IRQ-safe vs unsafe, same-class recursion). "Refuses on first sight" fits the closing edge or a single-lock rule violation only. It warns; it does not block the acquisition.
|
||||
|
||||
## 4. ConcurrentHashMap re-check after locking
|
||||
Status: VERIFIED.
|
||||
- Source: OpenJDK java/util/concurrent/ConcurrentHashMap.java, `putVal` and `computeIfAbsent`: head node `f` is read unlocked, `synchronized (f)` is taken, then `tabAt(tab, i) == f` is re-checked; on failure nothing is done and the loop retries. The overview comment gives the reason: the locked node can be replaced, so first-in-bin must be confirmed after locking. (Only the first 100k of 269k chars were read; both methods were reported found there.) Empty-bin `computeIfAbsent` uses a ReservationNode plus CAS instead.
|
||||
- (c) This is the pattern: choose the lock from an unlocked read, validate the read after acquiring.
|
||||
|
||||
## 5. LMDB
|
||||
Status: VERIFIED (paraphrase). Not about alien code or lock order.
|
||||
- Source: lmdb.h, `mdb_txn_begin` and `mdb_env_open` (https://github.com/LMDB/lmdb, libraries/liblmdb/lmdb.h). A thread may hold one transaction at a time (plus children); a transaction and its cursors belong to one thread; one write transaction at a time, so writers cannot deadlock each other; MDB_NOTLS ties reader slots to the txn object instead of the thread, and the application must then serialize writers itself because write locking is unaware of user threads.
|
||||
- Relevance: "one hold per thread" as a deliberate rule, parallel to CultCache's one-cache-gate-per-thread.
|
||||
|
||||
## 6. SQLite btmutex.c
|
||||
Status: VERIFIED (summary of trunk source).
|
||||
- Source: https://github.com/sqlite/sqlite/blob/master/src/btmutex.c (read via raw.githubusercontent.com; sqlite.org served a bot check).
|
||||
- (b) Prevention by ordering, not detection: sharable B-trees on a connection sit in a list sorted by BtShared address and are always locked ascending (`sqlite3BtreeEnterAll`). `sqlite3BtreeEnter` try-locks first; on failure it releases later-ordered locks, waits, then reacquires in order. `wantToLock` is a count that makes a non-recursive mutex behave recursively.
|
||||
- No alien-code or callback discussion in these comments.
|
||||
|
||||
## Counter-positions and how they stay safe
|
||||
- Callbacks under lock, documented: Java `ConcurrentHashMap.compute`/`computeIfAbsent`. Javadoc (Java 21): the function should be short and simple because other threads' updates may block meanwhile, and must not modify the map. The javadoc does not say "internal lock"; that it runs under the bin lock is inferred from the source in item 4. Safety rests on documented restrictions, not enforcement.
|
||||
- Opposite choice: .NET `ConcurrentDictionary.GetOrAdd(key, valueFactory)`. Writes use fine-grained locks but valueFactory runs outside them, "to avoid the problems that can arise from executing unknown code under a lock" (doc remarks). Price: not atomic; the factory may run more than once; a recheck decides the winner (another thread's insert wins). https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.getoradd . Same shape as option `encode-first` (user code outside the lock, then recheck and commit) and as item 4.
|
||||
- JCIP and Sutter both name the cost of leaving the lock: lost atomicity. Sutter also offers "pass copies" and "callee must not block" as alternatives to leaving.
|
||||
- Not researched (no source fetched): Linux notifier chains, Java `synchronized` event listeners, other systems that call back under lock by design. No verified citation for them.
|
||||
|
||||
## Unverified / not done
|
||||
- JCIP: section numbers and text come from one PDF copy, not the publisher edition.
|
||||
- Sutter: full column body not read first-hand.
|
||||
- No Discord or voidbot content read.
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
# Prior art: a process-global default registry deciding write ownership
|
||||
|
||||
Serves `variants:question:registryless-write-reads-shared` (campaign `variants`). Eyes pass, session `self-2026-10-27b-eureka`, 2026-10-27. Facts only; items marked "summary" rest on search summaries not opened.
|
||||
|
||||
# Prior art: process-global type registries and write/overwrite ownership
|
||||
|
||||
Fork: `variants:question:registryless-write-reads-shared` (viewed in full via eureka-state, status InForce, options `shared-decides` / `written-type-only`, recommended `shared-decides` at ~65%).
|
||||
Facts only. No conclusion. Date 2026-10-27.
|
||||
|
||||
Method note: web pages were read through WebFetch (a small model summarises the page) and WebSearch summaries. Quotes below are what those tools returned; where only a summary was available it is marked "summary". Nothing was run.
|
||||
|
||||
## A. Local mechanics (CultLib, read-only, `C:\cl-wt\c2a-land\src\GameCult.Caching\CultCache.cs`)
|
||||
|
||||
- `CultDocumentRegistry.Shared` is `Lazy<CultDocumentRegistry>` (line 639-645). Its public constructor calls `Refresh()` (647-650), which scans `ReflectionExtensions.GetAttributedDocumentTypes()` (688; defined in `ReflectionExtensions.cs:10`) and rebuilds the indexes under `_registrationGate`. So Shared's initial content is whatever `[CultDocument]` types are in loaded assemblies at first touch of `Shared`.
|
||||
- `GetRequired(Type)` (697-711) registers an unregistered `[CultDocument]` type on demand. So Shared also grows whenever any caller asks for a type. `Refresh()` is public and rebuilds the index from currently loaded assemblies.
|
||||
- `ForTypes(IEnumerable<Type>)` (658-669) builds a registry with `discoverLoadedDocuments:false`, containing only the given types (plus those `GetRequired` pulls in).
|
||||
- `CultCache(registry = null, ...)` sets `_registry = registry ?? CultDocumentRegistry.Shared` (2202-2205).
|
||||
- `WriteDocument<TDocument>(key, doc, storedAt, registry = null)` (4515-4545): `resolvedRegistry = registry ?? Shared`; `catalogEntry = resolvedRegistry.GetRequired<TDocument>().ToCatalogEntry()`; then `Cacheless(resolvedRegistry, ...)` lends that registry to the store for the call. XML doc (4510) says Shared "can only refuse more".
|
||||
- `WriteRecord(..., registry = null)` (4491-4497): XML doc (4489) says that with registry omitted "it decides nothing for copied records and the one entry is the only claimant".
|
||||
- `OwnsOnDisk(upserts)` (4741-4759): when the store is cacheless and upserts are given, ownership of an on-disk record is decided by `CultDocumentRegistry.Owns(id, catalog, declared, new CatalogEntryLookup(writes, AttachedRegistry), ..., claimant => writes.Any(entry => entry.SchemaId == claimant.SchemaId))`. The comment (4731-4735, 4738-4740) says written entries shadow the lent registry's type for their ids, the registry adds other claimants, and the record is owned only when the claimant is a written entry, "a registry can only refuse more". `CatalogEntryLookup` ctor at 604 takes `(entries, CultDocumentRegistry? others)`.
|
||||
- Net: with `registry == null` the lent registry's claimant set is Shared's current contents, which depend on assemblies loaded and on every prior `GetRequired` call in the process.
|
||||
|
||||
## B. Q1. Process-global, lazily filled registries in established libraries
|
||||
|
||||
### MongoDB C# driver, `BsonClassMap`
|
||||
- Global: yes. `BsonClassMap.RegisterClassMap` is process-wide static; unregistered types are auto-mapped on first use. Docs: "You must register a class map _before_ it's needed in your code." and "We recommend registering class maps before initializing a connection with MongoDB." https://www.mongodb.com/docs/drivers/csharp/current/serialization/class-mapping/ (WebFetch; the page itself says nothing on freezing or late-registration errors).
|
||||
- Behaviour depends on what has been touched: EF Core provider issue EF-88 reports "Unknown discriminator value 'List`1'" when the first operation after startup is a read; reporter links it to a class map that is created only on write. Status Closed/Fixed in 8.0.0; page has no maintainer comment. https://jira.mongodb.org/browse/EF-88 (WebFetch). Reporter says explicit `RegisterClassMap` at startup did not fix it for them.
|
||||
- A MongoDB community answer (via search summary, not opened): discriminator mappings persist once registered, so a read after an insert works; fix offered is `[BsonKnownTypes]`. https://mongodb.com/community/forums/t/c-driver-why-is-bsonknowntypes-attribute-needed-for-polymorphism/2183 (summary only).
|
||||
- Register-once contract: CSHARP-4424 states the three `RegisterClassMap` methods are "meant to only be called once for a given type"; requested because several libraries share data models and do not control init order. Closed Done, fix version 2.19.0; the page does not say which API shipped. https://jira.mongodb.org/browse/CSHARP-4424 (WebFetch). Community workaround named in search summary: `BsonClassMap.IsClassMapRegistered`.
|
||||
- CSHARP-1879 (search summary): `RegisterClassMap` accepted an unfrozen map and failed later on use; fixed 2.4.2. https://jira.mongodb.com/browse/CSHARP-1879 (not opened).
|
||||
- CSHARP-5597 (search summary): `BsonSerializer.RegisterDiscriminator` has no effect; discriminator dictionary populated at class-map registration. https://jira.mongodb.org/browse/CSHARP-5597 (not opened).
|
||||
- Polymorphic docs: "You must specify hierarchical discriminators in root-to-leaf order." and the relationship of all classes in a hierarchy must be documented before deserialization. https://www.mongodb.com/docs/drivers/csharp/current/serialization/polymorphic-objects/ (WebFetch).
|
||||
- Particular docs report an order-dependent GuidSerializer failure ("incorrect order of class mappings"). https://docs.particular.net/persistence/upgrades/mongodb-4to5 (search summary, not opened).
|
||||
- Did they move away: not found. Class maps remain global static; mitigation is documentation plus the IfNotRegistered API.
|
||||
|
||||
### protobuf-net `RuntimeTypeModel.Default`
|
||||
- Global: yes. README: "The Serializer.* methods are basically just shortcuts to RuntimeTypeModel.Default.*". https://cdn.jsdelivr.net/gh/protobuf-net/protobuf-net@main/README.md (WebFetch).
|
||||
- Lazy fill, freezing, order-dependent bugs: NOT verified. README is silent; a direct docs fetch (docs.protobuf-net.dev/runtime) was redirected and not followed. No issue found.
|
||||
|
||||
### MessagePack-CSharp
|
||||
- Global mutable default exists: `MessagePackSerializer.DefaultOptions`. README (WebFetch): labelled "Global state; Not recommended when writing library code." Safe if you control all MessagePack code; libraries should pass options explicitly because others "may change this static property." Libraries "must not use StaticCompositeResolver - as it is global state". https://github.com/MessagePack-CSharp/MessagePack-CSharp/blob/master/README.md
|
||||
- Resolvers are an ordered list (`CompositeResolver`): order matters by construction.
|
||||
- Whether it moved away from the global: not found.
|
||||
|
||||
### System.Text.Json
|
||||
- `JsonSerializerOptions.Default`: "Gets a read-only, singleton instance"; remarks give a performance reason: shared instance avoids "redundant recomputation of converters". https://learn.microsoft.com/dotnet/api/system.text.json.jsonserializeroptions.default (WebFetch). The page states no rationale about cross-component interference; any such reading is inference. Design-discussion issue in dotnet/runtime: searched, not found. Whether Default was ever mutable: not verified.
|
||||
- Type-info resolvers: not researched beyond the above.
|
||||
|
||||
### Json.NET
|
||||
- `TypeNameHandling` is a security concern, not an order concern: CA2326 says "An attacker could modify the serialized data to include unexpected types"; mitigation is a custom `ISerializationBinder` restricting types. https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2326 (WebFetch).
|
||||
- `JsonConvert.DefaultSettings` global behaviour/guidance: the Newtonsoft page fetched says nothing about global effects. Not verified.
|
||||
|
||||
### Orleans
|
||||
- Serializer discovery is build-time source generation (`[GenerateSerializer]`, `[Id]`), not a runtime scan; the docs' older code-generation section lists scan of assemblies referencing the core library plus `KnownType`/`KnownAssembly` attributes. Aliases: "Type aliases are globally scoped, and you cannot have two aliases with the same value in an application." https://learn.microsoft.com/en-us/dotnet/orleans/host/configuration-guide/serialization (saved locally: `C:\Users\Meta\.claude\projects\F--Projects-CultLib\0840c7c7-0e31-410e-9012-afb79c3c0742\tool-results\toolu_0148m7no1AbrJzWmNLicn6N9.txt`, lines 134, 839-841).
|
||||
- Type manifest / codec registry runtime behaviour, issues: not researched.
|
||||
|
||||
### EF Core
|
||||
- Model is built per `DbContext` type and cached (IMemoryCache; "the built model has a cache size of 100"); initialised at first operation: "just creating a DbContext instance does not cause the EF model to be initialized." https://learn.microsoft.com/en-us/ef/core/performance/advanced-performance-topics
|
||||
- Assembly scan: `ApplyConfigurationsFromAssembly` — "The order in which the configurations will be applied is undefined, therefore this method should only be used when the order doesn't matter." https://learn.microsoft.com/en-us/ef/core/modeling/ ; and "`EntityTypeConfigurationAttribute` types will not be automatically discovered in an assembly."
|
||||
- So EF's registry is per context type, not process-global; assembly scan is opt-in and documented as order-undefined.
|
||||
|
||||
### Marten
|
||||
- Storage is a table and upsert function per document type, alias `mt_doc_<alias>`; alias collisions are resolved with `DocumentAlias`. https://martendb.io/schema/storage (WebFetch). Hierarchies share one table via `AddSubClass<T>()`; subclass docs are "stored as the parent type" in the identity map. https://www.martendb.io/documents/hierarchies (WebFetch). Schema is configured in `StoreOptions` per store, not a process-global.
|
||||
|
||||
### Java ServiceLoader
|
||||
- "Service providers are loaded and instantiated lazily, that is, on demand." Providers on the class path load in the order `getResources` finds config files; "The ordering of modules in a module layer is not defined." "Instances of this class are not safe for use by multiple concurrent threads." Caches cleared by `reload`. https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/ServiceLoader.html (WebFetch). Visibility is class-loader dependent ("must be visible to the class loader").
|
||||
|
||||
## C. Q2. Write/overwrite decisions against an existing record of another type
|
||||
|
||||
- RavenDB: REST put docs, request body section: updates must "include its collection name in the metadata" and "A document's collection cannot be modified." Server error code for mismatch: the first fetch summary said HTTP 500; not confirmed on a second fetch. https://docs.ravendb.net/7.1/client-api/rest-api/document-commands/put-documents (WebFetch twice). Ayende, RavenDB 4.0 storage: document key namespace is global, same key cannot exist in two collections (summary). https://ayende.com/blog/173954/the-design-of-ravendb-4-0-physically-segregating-collections The check is against the collection named in the write (derived from the writer's type by the client), not a registry; the "client maps entity type to collection" part is inference from the search summary, not a quoted source. `PutDocumentCommand` page: a missing collection means `@empty`; concurrency via `changeVector`, null "to skip the check". https://docs.ravendb.net/client-api/commands/documents/put
|
||||
- Marten: per-type tables, so the same id under two types are two rows in two tables; no cross-type check. Same id across subclasses of one hierarchy table: not covered by docs fetched; unverified. Marten docs: upsert is used so users "don't have to check whether a document is new or existing" (search summary of https://www.martendb.io/documents/storing, not opened).
|
||||
- MongoDB: the server has no type; `_id` unique per collection; the C# driver writes a `_t` discriminator from the written object's class map. Whether the driver checks an existing document's `_t` on replace: not researched; nothing found stating it does.
|
||||
- Couchbase: key unique within a collection; upsert replaces; no server-side type field enforcement; guidance is one type per collection. https://docs.couchbase.com/server/7.0/learn/data/scopes-and-collections.html (search summary, not opened).
|
||||
- Orleans: grain identity is type plus key ("type/key"), so same key under two grain classes is two identities, not a conflict. https://learn.microsoft.com/en-ca/%20dotnet/orleans/grains/grain-identity (search summary, not opened). How storage providers key state: not found.
|
||||
- Result of this pass: no store found in which a process-global type registry decides whether a write may replace an existing record of another type. Found: collection/type fixed by metadata of the writer (RavenDB), type as part of the key (Orleans, Marten tables), or no check (Couchbase upsert). This is a negative search result, not proof of absence. Not searched: Cosmos DB, DynamoDB, EF Core TPH update of an existing row with another discriminator, Realm, LiteDB, Akka.Persistence.
|
||||
|
||||
## D. Q3. Guidance on ambient/global registries and determinism
|
||||
|
||||
- Mark Seemann (ploeh, 2019): after discussion with co-author van Deursen, "Ambient Context really is an anti-pattern." Reasons given: he has never used it and superior alternatives exist; he says the claim is unproven. https://blog.ploeh.dk/2019/01/21/some-thoughts-on-anti-patterns/ (WebFetch). Examples he cites as found in the BCL (search summary, not verified on page): `Thread.CurrentPrincipal`, `CultureInfo.CurrentCulture`, `HttpContext.Current`. DI book 2nd ed. chapter 5 lists it among DI anti-patterns: https://www.oreilly.com/library/view/dependency-injection-principles/9781617294730/OEBPS/Text/c05.xhtml (not opened).
|
||||
- MessagePack README (above) is itself a library-author statement on global mutable defaults. MongoDB CSHARP-4424 (above) states the shared-library init-order problem. EF Core docs (above) state assembly-scan order is undefined.
|
||||
- No .NET guidance specifically about AppDomain-wide/assembly-scan registries and write decisions found.
|
||||
|
||||
## E. Not verified / gaps
|
||||
- protobuf-net lazy registration, freezing and bug history.
|
||||
- Why System.Text.Json made Default immutable; no maintainer statement found.
|
||||
- Json.NET DefaultSettings guidance.
|
||||
- RavenDB exact error text and HTTP status; whether the stored document is unchanged after refusal.
|
||||
- Marten same-id-across-subclasses behaviour.
|
||||
- MongoDB driver behaviour on replacing a document whose `_t` differs.
|
||||
- Several items above rest on WebSearch summaries I did not open (marked "summary").
|
||||
90
docs/research/2026-10-27-structural-schema-ids-prior-art.md
Normal file
90
docs/research/2026-10-27-structural-schema-ids-prior-art.md
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
# Prior art: structural versus name-inclusive schema ids
|
||||
|
||||
Serves the store-identity question raised 2026-10-27 in campaign `variants` (operator: member and declared names vary with runtime naming conventions). Eyes pass, session `self-2026-10-27b-eureka`. Facts only; items marked "summary" rest on search summaries not opened.
|
||||
|
||||
# Prior art: structural vs name-inclusive schema identity (campaign variants)
|
||||
|
||||
Eyes pass, 2026-10-27. Facts and evidence pointers only. "(fetched)" = page opened via WebFetch (the answer is a small-model extraction of the page, not raw text). "(summary)" = WebSearch result summary, page not opened.
|
||||
|
||||
## 0. Local facts (read-only)
|
||||
|
||||
- `F:\Projects\CultLib\src\GameCult.Caching\CultCache.cs:717-718` schemaId = Sha256(BuildSemanticFingerprint(...)). `:735-761` fingerprint = `schemaName|schemaVersion` then per member ordered by Slot: `slot:MemberName:TypeName:ref|value:TargetSchemaName:one|many`. `contentHash` (`:716`) is a separate Sha256 of canonical JSON (`:763+`).
|
||||
- `TypeName` = `CultSchemaTypeNames.FromType`: CLR `Type.FullName` (namespace-qualified), generics as `Name<args>`, arrays `T[]` (`src\GameCult.Caching\CultSchemaTypeNames.cs:9-31`). So the fingerprint contains .NET type names as well as member names.
|
||||
- Contract `Contracts\cultcache-persistence-format.md:257-284` lists what canonicalization must preserve: slots, types, required/default, nullability, collection semantics, enum constraints, encoding shape. Member names and declared schema name are not in that list. `:171-179` says the id is not derived from C#/Rust/TS type names and the same shape should give the same id "regardless of origin language". `:180-190` defines schemaId = "same semantic persistence shape?" vs contentHash = "exact same canonical schema document?". Example catalog entry (`:140-170`) carries optional `supersedesSchemaIds`, `migrationFamily`; its example canonicalSchema fields do carry `"name": "Name"` (PascalCase). Soft-migration reader flow `:286-345` (exact_match / soft_migrate / reject).
|
||||
- Runtimes do not derive ids; they emulate C# names:
|
||||
- Python: `packages\cultcache-py\src\cultcache_py\documents.py:326` `member_name=_pascal_case(field.name)`; `:516-517` splits on `_` and capitalises. `schema_id` defaults to `self.type` (`:218`); `compatible_schema_ids` field (`:188,242`).
|
||||
- TypeScript: `packages\cultcache-ts\src\codec.ts:226-232` `pascalCase` (splits on non-alphanumerics), `:267` `memberName: pascalCase(field.name)`; throws if a codec has no C# type name (`:~262`).
|
||||
- Rust: `packages\cultcache-rs\src\lib.rs:295,308` `serde(rename_all = "camelCase")` on envelope structs; `schema_id: Some(T::TYPE.to_string())` at `:2856`. I did not trace how Rust document types obtain a sha256 id.
|
||||
- Python test pins a literal id from shared vectors: `packages\cultcache-py\tests\test_cultcache.py:808` (`tests\vectors\document-variants-c0`).
|
||||
- C# also has `CompatibleSchemaIds` (`CultCache.cs:28,313,570`): a record whose persisted id is in the list is accepted (an alias-list mechanism; I saw only the grep lines, not the logic).
|
||||
- Ruling `variants:ruling:wire-id-is-version` (eureka-state, InForce, ruled 2026-09-30, operator quote "Agreed on schema identity"): wire schema id = declared version string `<name>.vN`; every runtime stamps/resolves it exactly; a wire binding without `.v<digits>` is refused; "Store ids are unchanged." Cited source: document-variants-cut.md:552-555 (not opened).
|
||||
|
||||
## 1. How established formats define identity/compatibility, and whether names participate
|
||||
|
||||
Protocol Buffers (fetched https://protobuf.dev/programming-guides/proto3/ and /json/)
|
||||
- Field number identifies the field in the binary wire; changing it = delete + add. Field names appear only in TextProto/JSON encodings; reserve deleted numbers and, for JSON/text, names. The proto3 page has no explicit safe/unsafe entry for renaming; names matter only for JSON/text.
|
||||
- JSON mapping: names become lowerCamelCase unless `json_name` is set; "Parsers accept both the lowerCamelCase name" and the original proto name (/programming-guides/json/).
|
||||
- Message type identity in `Any` is by name: default type URL `type.googleapis.com/<package>.<message>`, "a globally unique identifier" (proto3 page, #any). Type identity is nominal; compatibility is by field numbers.
|
||||
|
||||
Apache Avro (fetched https://avro.apache.org/docs/1.11.1/specification/)
|
||||
- Parsing Canonical Form (PCF): STRIP keeps only attributes relevant to parsing (type, name, fields, symbols, items, values, size); doc and aliases dropped; FULLNAMES replaces short names with fullnames and drops namespace attributes. Textually equal PCF means "the same" for any reader. Names ARE in the canonical form (record and field names), as is field declaration order. Defaults are absent from the kept list (extractor's inference; spec text not confirmed).
|
||||
- Fingerprints: CRC-64-AVRO in single-object encoding (marker C3 01 + 8-byte LE fingerprint); spec recommends at least a 64-bit Rabin, with SHA-256 / MD5 options for larger sets.
|
||||
- Name rules: `[A-Za-z_][A-Za-z0-9_]*`, dot-separated namespaces, equality on case-sensitive fullname.
|
||||
- Resolution: records match on same unqualified name; "Named types and fields may have aliases"; implementations "may optionally" use aliases to map writer to reader. So in Avro names participate in identity (fingerprint) and resolution; aliases are the rename mechanism and are excluded from the fingerprint.
|
||||
|
||||
Cap'n Proto (fetched https://capnproto.org/language.html)
|
||||
- Files and types carry 64-bit IDs; `capnp id` generates them randomly. Default ID for a declaration without one = first 8 bytes of MD5 of (parent scope ID, declaration name). "You cannot change the name of a type that doesn't have an explicit ID"; symbolic names can change if ID/ordinals stay. Stated rationale for IDs: short, unambiguous, full names waste wire space. The page does not say why structural hashes were rejected; I found no Varda statement (search pointed at a mailing-list thread "Schema Refactoring and Unique IDs", Aug 2023, unopened).
|
||||
- Encoding page (https://capnproto.org/encoding.html, fetched): adding fields is backward compatible because field positions depend only on lower-numbered fields; nothing on type identity.
|
||||
|
||||
FlatBuffers (fetched https://flatbuffers.dev/evolution/ and /schema/)
|
||||
- Field positions by declaration order or explicit `id: n` (contiguous from 0, on all fields if used). Renaming "generally OK" because names are not in the binary. `file_identifier` is exactly 4 chars at bytes 4-7; docs frame it as a file-level check and recommend unions for distinguishing messages.
|
||||
|
||||
Thrift (fetched https://raw.githubusercontent.com/apache/thrift/master/doc/specs/thrift-binary-protocol.md)
|
||||
- Binary protocol: field header = type + field id; "the field name is not encoded". (IDL page gave nothing on omitted ids.)
|
||||
|
||||
MessagePack-CSharp (fetched https://github.com/MessagePack-CSharp/MessagePack-CSharp, first 100k of 105k chars)
|
||||
- `[Key(int)]` on all members => array encoding; string keys => map. Keys should be sequential from 0 (gaps cost nulls); do not reuse indexes of removed members; keep obsolete members until clients update. Union keys are ints, unique, serialized as [key, object]. No type identity in the payload.
|
||||
|
||||
Microsoft Bond (fetched https://microsoft.github.io/bond/manual/bond_cpp.html)
|
||||
- Changing field ordinals breaks wire compat; no explicit versioning; Simple JSON matches by field name so a rename breaks it. No schema hash/GUID documented there. Bebop: wiki page empty (points to docs.bebop.sh, not opened).
|
||||
|
||||
Unison (fetched https://www.unison-lang.org/docs/the-big-idea/ and /docs/language-reference/unique-types; hash size from search summary)
|
||||
- Definitions identified by hash of syntax tree; names are "separately stored metadata"; hash excludes names (512-bit SHA3 per search summary, unopened).
|
||||
- Structural types: "Unison does not uniquely identify a type by its name"; same-shape types are the same type (Suit/Direction, four nullary constructors, interchangeable). `unique` types: compiler generates a UUID that feeds the hash, so identity becomes nominal. Which is the default keyword was not confirmed.
|
||||
|
||||
IPLD (fetched https://ipld.io/docs/schemas/)
|
||||
- Matching is structural: "the names of types aren't expected to be found in the serialized data"; match is by structural outline. The page does not say schemas are themselves content-addressed. Versioning is left to developers; "Migrations" subpage not opened.
|
||||
|
||||
## 2. Failure modes of purely structural identity
|
||||
|
||||
- Unison documents it directly: structurally identical enums are one type unless declared `unique` (unison-lang.org/docs/language-reference/unique-types, fetched). Its mitigation is a per-declaration UUID mixed into the hash (identity re-nominalised).
|
||||
- Language literature (summary, pages not opened): structural typing is prone to accidental conformance/type equivalence; nominal typing prevents it at the cost of rigidity (Wikipedia "Nominal type system"; arXiv 1007.2123 lecture notes; Erlang nominals doc https://www.erlang.org/doc/system/nominals.html says nominal types exist to prevent misuse of same-structure types). TypeScript "brand" = phantom discriminator field. No serialization-specific source found.
|
||||
- Formats that avoid the collision by carrying a name or tag outside the shape: protobuf Any type URL (full name), Avro fullname in PCF, Cap'n Proto explicit IDs, Unison `unique`, MessagePack-CSharp union key ints, FlatBuffers file_identifier/unions.
|
||||
- Not found: a documented incident of two same-shape serialized types colliding under a structural id (one search, nothing).
|
||||
|
||||
## 3. Failure modes of name-inclusive identity across languages
|
||||
|
||||
- Protobuf: default camelCase conversion is "always valid but not necessarily unique"; proto3 compiler rejects JSON-name conflicts; serialized duplicate keys parse differently by runtime (Edition Zero design doc, summary: https://flutter.googlesource.com/third_party/protobuf/+/HEAD/docs/design/editions/edition-zero-json-handling.md). Snake_case vs camelCase JSON mismatches in practice: https://github.com/fullstorydev/grpcurl/issues/105 (summary); https://github.com/open-telemetry/opentelemetry-proto/issues/476 (summary: spec contradicted itself on camelCase vs original names). Protobuf's mitigation: parsers accept both forms.
|
||||
- Serde (fetched https://serde.rs/container-attrs.html): `rename_all` accepts lowercase, UPPERCASE, PascalCase, camelCase, snake_case; per-field `rename`.
|
||||
- Avro restricts names to `[A-Za-z_][A-Za-z0-9_]*` with case-sensitive fullname equality, so snake_case and PascalCase spellings are distinct names; renames go through aliases, which PCF drops.
|
||||
- Cap'n Proto: auto-derived IDs depend on the declaration name, so a rename without an explicit ID changes the ID.
|
||||
- Bond Simple JSON: rename breaks compatibility (name matching).
|
||||
- Local: Python/TS already convert to PascalCase to reproduce C#'s fingerprint (section 0); the fingerprint's TypeName is the CLR full name (`CultSchemaTypeNames.cs:30`) and TS throws when a codec lacks a C# type name.
|
||||
- Registry normalisation (summary): Confluent Schema Registry `normalize.schemas=true` maps semantically-equal schemas to one id (https://www.confluent.io/blog/best-practices-for-confluent-schema-registry/); sources disagree on whether JSON Schema property order is normalised.
|
||||
|
||||
## 4. Migration precedents for changing identity derivation
|
||||
|
||||
- Git SHA-1 -> SHA-256 (fetched https://git-scm.com/docs/hash-function-transition): per-repo format marker (`extensions.objectFormat`, `compatObjectFormat`, `repositoryFormatVersion=1` makes old git refuse); bidirectional SHA-256<->SHA-1 mapping (pack idx v3, `loose-object-idx`); four transition modes (dark launch, early, late, post); conversion at the network boundary. It is a design doc, not a statement of what has shipped.
|
||||
- IPFS CIDv0 -> CIDv1 (fetched https://docs.ipfs.tech/concepts/content-addressing/): v0 (46 chars, "Qm") and v1 (self-describing version/codec/multihash) coexist; `ipfs cid format -v 1` converts; v1->v0 only for dag-pb.
|
||||
- Docker manifest schema 1 -> 2 (summary, mirror pages unopened): digests differ per manifest format; pull-by-digest gets no translation, pull-by-tag may be translated; repush converts. https://pulp.plan.io/issues/2099.
|
||||
- Warpcast API hash v1 -> v2 (summary, https://warpcast.notion.site/Warpcast-API-Hash-Migration-Public-ccdd6de8ac604783b9596cfd623ddbac): two-week dual-hash period, then only v2.
|
||||
- Cap'n Proto explicit-ID escape hatch for renamed/moved declarations; Avro aliases as the rename bridge in resolution; MessagePack-CSharp keep-obsolete-members (all fetched, above).
|
||||
- Local: contract `supersedesSchemaIds` / `migrationFamily` (`cultcache-persistence-format.md:~140-170`) and C#/Py `CompatibleSchemaIds` exist as alias lists.
|
||||
- Not found: Unison changing its hash derivation (one search, no docs); any serialization store that switched from name-inclusive to structural ids.
|
||||
|
||||
## Could not verify / not done
|
||||
- Cap'n Proto designer's rationale against structural hashing (not in docs; mailing list unopened).
|
||||
- Avro: whether PCF drops defaults (spec text) and any JIRA on it; spec page was summarised by the fetch model.
|
||||
- Bebop, Thrift IDL id-omission rule, Unison default struct/unique keyword, IPLD Migrations page, Edition Zero doc (summary only), Confluent blog (summary only), nominal/structural papers (titles only).
|
||||
- Rust runtime's sha256 derivation path; `document-variants-cut.md:552-555` not opened; `CompatibleSchemaIds` logic not read.
|
||||
- eureka-state worked (whoami ok); only the one ruling was queried.
|
||||
Loading…
Reference in a new issue