CultLib/src/GameCult.Caching/Contracts/cultcache-store-composition.md
Libby c72bb435d6
Some checks failed
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Docs: pair backup is per-store consistent only; atomic restore; hold the lock to delete temps; cite the read path
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:05:21 +00:00

40 KiB

CultCache Store Composition

How one cache composes its backing stores: where a record lives, when a store is read or written, what a global is, how a multi-record commit lands, and who owns serialization options. GameCult.Caching in C# is the reference; the runtime table at the end says which runtime implements what.

None of this changes bytes on disk. Every store file is a complete cultcache.store.v1 snapshot (single file) or a v4 directory manifest, exactly as cultcache-persistence-format.md describes. No file records which cache or which route wrote it.

One home store per document type

  • A document type has exactly one home store. A cache attaches stores with an optional list of home types: AddBackingStore(store, params Type[] homes).
  • The home of a document is chosen from its runtime type (document.GetType()), never from a generic type parameter at the call site. Among routed stores whose home types are assignable from the runtime type, the most derived home type wins; otherwise the untyped store; otherwise none.
  • C# routes by assignable CLR type. TypeScript, Rust and Python route by the exact type string they already use.
  • A second untyped store is a registration error. A home type already claimed by another store, by exact type equality, is a registration error. Routes to a base type and a derived type may coexist; the most derived wins.
  • A write whose document has no home, once any store is attached, is an error. A cache with zero stores is an in-memory cache and needs no home.
  • Nothing is mirrored or replicated. A write touches exactly one store.
  • This is the contract in every runtime. A runtime that still mirrors is non-conforming until it deletes its mirrors.

Attachment is hydration

  • Attaching a store reads it. There is no interval in which a store is attached but unread, and no push of existing records into a newly attached store.
  • A store must be clean (IsDirty false) when attached.
  • A record's home cannot change after it is admitted. Attaching a store that would move the home of a record already in the cache is an error. The consequence is the attach order: routed stores first, the untyped store last.
  • A record loaded from a store that is not its home is refused at load, naming the key and both stores.
  • Pulling again after attach is a re-pull. It does not erase mutations staged in a dirty store. A dirty single-file store skips the re-pull entirely; a missing single file keeps staged writes dirty and does not drop loaded records.
  • A load publishes changes to Watch subscribers and fires OnUpdate. A local write or commit publishes to Watch only; OnUpdate fires for loads alone.
  • Changes published through Watch/WatchRecord carry a Sequence: a per-cache, in-memory number assigned when the cache admits the change, under its gate. It increases in admission order and is not persisted. OnUpdate(previous, current) carries none. CultNet derives its streams (CultNetDatabase.WatchAllChanges, the subscription server, database-backed Mesh handles) from Watch plus one journal (AddJournal), so a load, a commit and a variant dependent's re-resolution all reach subscribers and the mutation log. The journal runs under the gate in Sequence order, so the shard log is written in cache order; the Watch observer publishes what the journal decided. A database write door only hands the journal the wire message or replicated entry for the change it admitted. A replica publishes but never mints log sequences. A primary logs every change it admits, loads and pulls included; a store attached after the database exists has its hydration logged too. A primary that cannot log a change compacts through that change's sequence and throws CultNetShardLogException to the writer after publication: the commit stands, and a replica behind it resynchronizes from a snapshot. The streams carry no Sequence and have no stale protection.
  • GetWithSequence(key) returns the document and the cache's current Sequence, read together under the gate: every change with a Sequence at or below it is reflected in the document.
  • Adding the optional sequence constructor argument to CultCacheDocumentChange<T> changed its binary signature; no external constructor is known.
  • Observers and OnUpdate run after the cache releases its gate, never under it: an observer may read or write the cache from any thread. Each call publishes exactly its own changes, on its own thread, after releasing the gate and before it returns; no call publishes another call's changes or waits on another call's delivery. A write made by an observer is its own call and publishes its own changes before that write returns. A direct PullAll on an attached store is such a call.
  • Cross-thread delivery order is not guaranteed. A consumer that keeps a latest value per record ignores a change whose Sequence is not above the one it already applied for that record. It subscribes first, then takes GetWithSequence and adopts that Sequence as applied; a change delivered after subscribing with a Sequence at or below the read is already in the document and is dropped. CultMesh cache-record mirrors (ObserveAsync, ReactiveAsync, and RefreshAsync on both) do this.
  • Not stale-protected: removals do not advance a mirror's applied Sequence, and the mirrors do not surface removals.
  • AddJournal registers an ordered admission journal, for audit, replication or a derived index. The cache calls each journal under its gate, right after an admission is applied and before that admission is published, once per admission that changed something, with that admission's changes (a variant re-resolved by a base edit included) in Sequence order. Journals of one cache run in registration order, and reading the cache from one sees the new state. Because the gate serializes admissions, the calls of one cache see contiguous, strictly increasing Sequence values: a journal is the one place where cache order is a fact, and delivery order is not. A refused admission, or one a store declines, is not journaled. Disposing the registration removes the journal.
  • A journal that throws does not undo the admission: the remaining journals still run, the change is published, and the exception is rethrown to the writer after publication, with the same aggregation as an observer's. The journal stays registered. Any hold on the cache while a journal runs throws InvalidOperationException: a journal must not write to the cache or register another journal.
  • An OnUpdate handler exception is rethrown to that caller after all of that call's changes are delivered (an AggregateException if several threw). If the call itself failed, its own exception is rethrown and handler exceptions are dropped. Every Watch subscriber receives every change: R3 routes a subscriber's exception to its unhandled-exception handler, and if that handler rethrows (fail-fast), the exception is treated as an OnUpdate handler exception. The subscriber stays subscribed and the commit stands. A throwing handler cannot undo the store's adoption of a load; the store and cache already agree when publication starts.
  • An admission runs a record's [CultName] and [CultIndex] getters once per landing record, before the store is written and before any Sequence is minted. An admission is refused when it would leave two records of one type holding one [CultIndex] value (blank is no value), and a load of a store holding such a pair refuses naming both keys and the index. Concurrent writers on a directory store are not covered by this rule. A conditional commit on a clean file store is judged a second time against the file it merges onto whenever the cache holds variants in any store, the batch lands a variant, or the file holds one. That second read runs the getters again for the records the batch lands, for any variant it re-resolves, and for the records other writers put in the file (the arriving set); that judgement is also before the store is written. A getter that throws refuses the whole change set, loads included: nothing is written, minted or left in memory.
  • Pulling all stores pulls every attached store even if a handler throws during one store's load, then rethrows.
  • Hydration failure on open is loud: a corrupt store file, or a record whose schema the registry cannot resolve or whose name or index getter throws, makes the open throw and leaves the file byte-identical. Consumers never delete and rewrite a store they failed to open.

Locking

  • One lock order: the cache's gate, then the store's gate, then the file lock. A store's gate may be taken inside a cache's gate (the attach; a journal writing a cacheless file), never the reverse. What the code enforces, at run time and by InvalidOperationException: a thread holds at most one store's gate; while it holds a store's gate it enters no cache gate it does not already hold, reads included; a cacheless write made while the thread already holds that store's gate is refused; and a cache's hold (a write, a flush, an attach) entered inside another cache's hold is refused. What it does not enforce: a cache read made inside another cache's hold takes that cache's gate without a check, so two threads each holding one cache and reading the other can deadlock. That is open as variants:follow_up:cross-cache-read-lock-order; until it lands, a journal or a getter must not read a second cache. User code a cacheless call or an attach runs under the store's gate (a document's getter, a constructor while a copied record is read) is the way into the refused cases.
  • One owner picks the gate a store call holds. A store attached to a cache takes that cache's gate as its own lock, so a store's load callback into the cache cannot take the two out of order; a cacheless store takes its own gate. The store reads which one applies, takes it, and checks the answer again under it: Cache is written only by the attach, holding both gates: it publishes Cache before its pull and takes it back in the same hold if the pull fails. Another thread's unlocked guess may read the tentative cache, but none runs a body against it: the guess is checked under that cache's gate, which the attach holds, and fails once the pull retracts it. Under the store's gate Cache is settled, and a settled cache never changes, because nothing detaches. A call takes at most three gates: the guessed cache's, the store's, the settled cache's. The pull reads the registry the attach lent, not Cache; a variant it loads carries no codec, and the cache resolves it with its own. During an attach the store is attached, so a journal the pull runs that calls the store is refused as it would be afterwards; a cacheless write that finds a cache published, during an attach or after it, is refused with the same text. A store must not call Loaded while holding its own lock outside the cache's hold.
  • A journal runs under the cache's gate, so a slow journal slows every writer of that cache. It must not enter the cache, and must not wait for anything that needs the cache or its gate: another thread's write, a lock a writer holds. Its own leaf locks, taken only inside the journal, are the only locks that may nest under the gate.
  • A shard mutation log store (ICultNetShardMutationLogStore) runs inside the CultNet journal, under the cache's gate: it must not call the cache or wait for a thread that does. A store that writes its own cache throws through the journal's reentry guard, and the admission stands.
  • A store doing I/O on behalf of its cache (pull, flush, commit) holds the gate, so that cache's readers wait for the I/O. The file lock (<path>.lock or the directory commit lease) is always taken inside the gate and released before a load is handed to the cache.
  • Direct calls on an attached store (Push, Delete, PushAll, CommitBatch, PullAll) take the same gate, so they wait for that cache's pull, flush or commit, and the cache's flush on dispose runs under it.
  • In every runtime, a store call must not wait for a write to its own cache to finish: that write queues behind the operation that is waiting for it, a cycle. A handler or subscriber that writes back without the store waiting for it is fine; its write queues and lands after the operation. Python refuses a mutation started on a thread already inside one of that cache's mutations with an error; no runtime detects a wait that escapes to another thread or async context.

Dirtiness: loading never writes

  • A store's IsDirty derives only from its own writes and deletes. Pulling sets it false.
  • A cache's IsDirty is whether any attached store is dirty, or, with no stores, whether it has been mutated in memory.
  • Opening a store and flushing without a mutation leaves every file byte-identical.
  • A mutation reaches the home store before the cache's in-memory view changes. If the store refuses the write, the cache holds nothing new and publishes no change.

Read-only stores

  • A store can be opened read-only. Writes, deletes and full pushes on it throw and name the store.
  • A write whose home is a read-only store throws before anything changes.
  • Flushing skips read-only stores.

Lookups and watches honor inheritance

Get<T>, GetAll<T>, GetByName<T>, GetByIndex<T>, GetGlobal<T> and Watch<T> match every document whose runtime type is assignable to T. A lookup that returns one document and finds several candidates throws, naming them. Indexes stay keyed by concrete type; lookups enumerate assignable keys.

Globals

  • [CultGlobal] means: at most one record of the type per cache, GetGlobal<T>() returns it or null, and a write without a handle keys it global:{schemaId}.
  • The cache never creates a global. Constructing a cache, attaching a store and pulling produce no record the store did not contain. The code path that begins a global's lifecycle creates it with an ordinary upsert.
  • A second record of a global type, through a write or a load, is refused before any store is touched.
  • TypeScript and Python key the single record __global__; C# keys it global:{schemaId}. The divergence is recorded, not changed, because changing it changes bytes. Rust has no global concept.

Atomic commit: an explicit batch

  • A multi-record commit is an explicit batch value staged by the caller and committed with Commit. Every record in the batch must resolve to one home store; a batch spanning two homes throws before any store is touched.
  • The store commits the batch as one durable step: one atomic replace for a single file, pages then manifest for a directory store. A failed commit restores the store's staging and changes nothing in memory.
  • Nothing in a batch is visible, to the staging code or to observers, until the store has accepted it. Reads during staging see committed state. There is no ambient transaction and no in-flight overlay.
  • After the store accepts, each record is admitted through the same path as a single write (home, read-only and global checks included) and one change is published per record.
  • A cache with no stores admits a batch in memory.

Conditional commit (compare-exchange)

A batch may carry conditions, evaluated under the home store's exclusive lock against what is durably on disk at that moment:

  • Expect(key, current): the record at key must still be the one this cache observed, or, with current null, must be absent. Only named keys are constrained; unrelated concurrent writes do not fail the commit. Passing any instance other than the one the cache holds throws.
  • ExpectUnchanged(): the store's persisted record set must equal what this cache last loaded from it, compared as the ordered list of (key, version). Any insert, delete or replace fails it.

Record identity for conditions is the record's version, the SHA-256 of its stored bytes (cultcache-persistence-format.md). Any write that changes a record changes its version, whatever storedAt it carries.

  • A failed condition is a lost race, not an error: Commit returns false and nothing is written, changed in memory, or published. TryCommit makes one non-blocking lock attempt and reports Contended instead of waiting. On a directory store the lock is the commit lease that pulls also take, so Contended can mean another cache or process is reading or committing. The attempt itself runs inside the cache gate, so TryCommit may first block behind a pull or flush of the same cache, for up to that operation's lease wait bound (30 seconds).
  • A conditional commit on a store with staged single-record writes throws: flush first.
  • Single-file stores lock a sidecar <path>.lock: C# by an exclusive (share-none) open, Rust and TypeScript by an exclusive LockFileEx on a shared open on Windows, and every runtime by flock(LOCK_EX) on Unix. Each excludes the others (TypeScript tests: "a TypeScript write waits while a C# writer holds the store lock", "... a Rust writer ...", "a C# writer waits while a TypeScript writer holds the store lock", "a Rust writer waits ..."). Directory stores use their existing commit lease.
  • A directory store with no .commit.lock (no writer has created it yet, or the store was copied without it) gives a pull no lease, and opening it creates none. Such a pull re-reads the manifest after loading its pages and reloads when the manifest changed or a page it named was missing or did not match its content address, at most five times; a pull that has not settled by then throws.

In a store holding no variant, a plain flush and an unconditional commit are last-writer-wins per staged key, in both store kinds. Both run under the same lock, so two writers never interleave bytes, but they compare nothing. Only a conditional commit (Expect or ExpectUnchanged) tells a writer another writer moved the keys it depends on. A writer wins only over a file it can read: a single-file store refuses to replace a file whose header it cannot read, and leaves it as it was.

  • A single-file store and a directory store apply this cache's staged writes and removals onto what the store holds now: another writer's unrelated records survive as stored, a key both wrote holds the last write.
  • In both store kinds, a write or removal at a key whose durable record is under an id the writer does not declare is refused with the typed schema conflict before anything is written, and that record is reloaded as the store holds it: dropped when foreign, held read-only when a type reads it (cultcache-persistence-format.md, ownership by declaration).
  • A removal of a key the cache does not hold travels as a check-only key: a commit carries it in the request, a flush stages it, and either store kind judges it under its lock with the keys it writes, never removing it. Every writable store judges a batch's checks under its own lock: the stores the batch does not commit through first (JudgeChecks), the home last. A batch that only checks keys writes no file. ExpectUnchanged compares the foreign records a store carries at the versions it read them; a store kind lists a foreign record through Foreign with the version it read.
  • A single-file store holding a variant (the directory store refuses variants) is written only from what its writer last read. A record that moved refuses the whole write with the typed write conflict, and the refused and moved keys are reloaded (cultcache-persistence-format.md).
  • An unconditional commit writes exactly what a flush of the same staged state plus the batch would write. It also persists any single writes staged earlier in that store, and leaves the store clean.
  • A conditional commit lands the batch onto the file as it is under the lock.

C#, Rust, TypeScript and Python single-file writers exclude each other on the shared lock file. Another runtime need not obey the storedAt rule.

Operating a single-file store

What the lock guarantees, per runtime. Every claim cites the code.

  • Scope. The lock is the sidecar <path>.lock, taken by every write of a single-file store, never by a read except in Rust. It is advisory: it excludes only openers that also take it, in this process and others. C# opens it share-none (CultCache.cs:5166-5183; .NET emulates that with flock(LOCK_EX) on Unix, switched off by DOTNET_SYSTEM_IO_DISABLEFILELOCKING, see docs/research/cross-process-file-locking-prior-art.md); Rust takes fs2 exclusive (cultcache-rs/src/lib.rs:1721-1726); TypeScript flock or LockFileEx (cultcache-ts/src/store-file.ts:340-382); Python the same (cultcache-py/src/cultcache_py/stores.py:342-389). A tool that opens and writes the .cc file without the lock is not excluded. flock is not reliable on every network filesystem; keep stores on a local one.
  • What a second writer sees. It waits. C# polls every 10 ms for 30 seconds, then the IOException propagates (CultCache.cs:5166-5183); with wait: false (TryCommit) it returns Contended (CultCache.cs:2052, 2897, 4691-4693). TypeScript times out after 30 s (store-file.ts:173-195), Python raises TimeoutError after lock_timeout, 30 s by default (stores.py:342-354). Rust waits without a timeout on its write paths (lib.rs:1721-1726); only its try_with_exclusive_lock returns without waiting (lib.rs:1832-1843). Each write re-reads the file after taking the lock and applies its staged keys onto it (CultCache.cs:4659-4676), so waiting writers merge rather than overwrite. The in-memory cache of a writer is not refreshed by another's write until its next PullAll, which does nothing while that cache is dirty (CultCache.cs:4582-4588).
  • What a reader sees. C#, TypeScript and Python read without the lock (CultCache.cs:5139, 5227; single-file-messagepack-backing-store.ts:200; stores.py:144-152). The store file is only ever replaced by rename of a fully written, fsynced temp file (CultCache.cs:5191-5213, lib.rs:1693-1712, store-file.ts:70-95, stores.py:316-326), so a read gets one complete generation, old or new, never a mix. Rust pull_all takes the lock shared and so waits behind a writer (lib.rs:1926-1930); it creates the .lock file if absent, so on a read-only directory use pull_all_read_only_snapshot (lib.rs:1667-1669), which takes no lock and relies on the producer's atomic replace.
  • Not covered. A unique-index check or condition spanning two stores, or any invariant between two files: each store has its own lock and no store carries a generation counter (the file is [formatVersion, schemaCatalog, records]); a record's identity is its version, the SHA-256 of its stored bytes. No library writer holds two store locks at once (CultCache.cs:2917-2926 judges one store, releases, then commits the home). Python's JsonLinesBackingStore takes only an in-process lock (stores.py:73-80) and is not a single-file store in this sense.
  • The .lock file is not a stale-lock marker. It is never written or deleted by a library writer (store-file.ts:167-172, stores.py:342-345), and the lock is released when the holding process exits. A .lock file left on disk is normal. Do not delete it while any process may open the store: a new opener would create a second file and take a second, independent lock on it.

A leftover temp file

A write stages its bytes in a temp file beside the store and renames it over the store. The name is consumed by the rename, so a temp file that still exists is a write that was never applied. The store file itself is never partial because of it.

Runtime Temp name Source
C# .<store file name>.<32 hex>.tmp CultCache.cs:5191
Rust <store file name>.<uuid>.tmp lib.rs:4268-4275
TypeScript <path>.tmp-<pid>-<ms>-<random> store-file.ts:70
Python <path>.tmp-<pid>-<uuid hex> stores.py:316
  • Which temp files are safe to delete. One that no writer is writing: delete only while you hold <path>.lock yourself (flock <path>.lock rm <temp file>, Linux, util-linux) or with every writer of the store stopped. Merely testing that the lock is free is not enough: a writer can take it and stage a new temp file the moment after the test. While you hold the lock, every temp file of that store is abandoned. Deleting one a writer is still writing destroys that write.
  • How to know the write was incomplete. The temp file existing is the proof. Its content may be partial (killed during the write) or whole (killed between the fsync and the rename); either way it was not applied, and the writer that made it never saw its flush succeed. The store holds the last completed write. Do not rename a temp file over the store by hand. Rust additionally reports a rename that landed but whose directory fsync failed as ReplacedNotDurable (lib.rs:1685-1688; TypeScript StoreReplacedNotDurableError, store-file.ts:88-92): after a power loss the store may still be the earlier generation.
  • What the store does about it. Opening and reading ignore temp files and never delete them. A writer removes only its own temp file when its write throws (CultCache.cs:5216-5222, store-file.ts:82-84, stores.py:327-331, lib.rs:1707-1710); a killed process skips that. Rust alone sweeps: its next write, under the exclusive lock, deletes every regular file named <store file name>.<uuid>.tmp (lib.rs:1698, 4318-4352). C#, TypeScript and Python never sweep, and their unique names mean leftovers accumulate until an operator deletes them. A store file that cannot be read (truncated, wrong header) is refused at open and left byte-identical (the open reads through ReadSnapshot, CultCache.cs:4590, 5104-5118, whose ReadStore must throw CultStoreUnreadableException for anything that is not exactly one store, 4510-4516); that is the store, not a temp file, and is restored from a copy, never deleted and rewritten.

Backing up a pair of stores

Each store is whole on its own: copying one .cc file is safe at any moment, because the file is only ever replaced whole, and a copy of the path is one complete generation. Two stores have two independent locks and no shared generation, so copying them one after the other can capture store A at one moment and store B at a later one. If an application invariant spans the pair, that copy may violate it. Back up the pair at one point in time:

  1. Preferred, quiesce. Stop (or have flush and close) every process that writes either store. Flush staged writes first; PullAll and the dispose flush do not capture unflushed state of a still-running cache. Copy both .cc files. Do not copy .lock files or temp files. Start the writers again.
  2. Without stopping (Unix): per-store consistency only. Take both locks in one fixed order (sorted by full path), copy while holding both, release: flock A.cc.lock flock B.cc.lock cp A.cc B.cc /backup/dir/. This does not make the pair consistent. A writer holds one store lock at a time, so it can land A and then B with a gap between; holding both locks cannot pause a writer that has landed A and not yet B, so the copy can hold A after and B before that pair of writes. It guarantees each copy is one complete generation of its store and nothing more. Any invariant spanning the pair requires step 1. Cooperating writers wait (30 s in C#, TypeScript and Python; Rust waits indefinitely), so keep the hold short. Unflushed state of live caches is not in it. On Windows, no shipped tool holds the C# share-none lock for you: quiesce.
  3. Verify. Open each copy read-only with the runtime that will use it (for Rust, pull_all_read_only_snapshot); an unreadable copy is refused, not repaired (CultCache.cs:4510-4516, 5104-5118).
  4. Restore both files together from the same backup, with every writer stopped, then restart so each cache loads fresh. Copy each file to a temp name in the store's own directory and mv it over the store: a plain cp over the store is not atomic, and C#, TypeScript and Python readers take no lock, so they can read a torn file. Restoring one half of a pair from a different backup recreates the skew. Leave the .lock files as they are.

Serialization options

  • Options belong to the assembly that declares a document. That assembly names its formatter resolvers with [assembly: CultCacheFormatterResolver(typeof(R))]; the payload serializer resolves options from the document's assembly. There is no mutable static, no registration call, and no load-order rule.
  • A generic document's options come from the generic definition's assembly: Doc<X> uses the resolvers Doc's assembly declares, never X's. A formatter for X that Doc<X> needs is declared in Doc's assembly.
  • An assembly that declares nothing, and the store envelope, use the base options.
  • A resolver may not claim a type a document's element lists pass through: the list's element types, the types and members on the way to them, and the collection types the walk passes (List<T>, T[], a collection class, a dictionary on the way). Those are written by their [Key] layout so each element's id reaches disk, and the codec refuses the document on first encode or decode, naming the resolver and the type. The formatter StandardResolver or StandardResolverAllowPrivate hands out for a type does not claim it: the extra non-public members the AllowPrivate formatter writes are whole values the walk does not own. A type or member declaring [MessagePackFormatter] is a whole value off the path, the supported way to give a type its own formatter. A value list (List<float2>, a list of a non-keyed class) is not on the path, so a resolver may claim it.
  • The codec also checks, for every type on that path, that StandardResolver does not write it against the walk. A type read by key may not be written by the generic collection resolver (a [MessagePackObject] class that is also an ICollection<T> or dictionary); it is refused on first encode or decode, naming the type. Any other formatter, such as one MessagePack's source generator emits, passes: the walk decides which types carry ids and the door only verifies. It also refuses, typed, a type MessagePack cannot build a formatter for (it throws, or StandardResolver returns none), and a resolver that throws while asked about one.
  • Deserialization runs under untrusted-data security. CultRecordRef<T> is a permitted dictionary key, compared by its key string.

Record references

A record reference is its target's key string. An unset reference, the empty key, is "" on the wire in value and map-key position alike. Nil cannot be the form: msgpack readers in other runtimes (Python under strict_map_key) refuse nil map keys. Readers must also accept nil as unset, because C# 1.0.58 stores wrote it; the writer always writes "", so such a record converts on its next save and is byte-stable after that. In C# the unset reference is default(CultRecordRef<T>), equal to one built from ""; CultRecordKey.Value is never null. Rust, TypeScript and Python have no reference type: a reference member is a string in the consumer's own payload, and a consumer writes an unset one as "".

Value-type encoding

Vector-like value types (Unity.Mathematics, consumer structs) encode as fixed-length positional arrays of primitive components: a two-component float vector is [f32, f32], a three-component one [f32, f32, f32], an integer pair [int, int]. No ext types, no maps, no names. The persisted member type name is the CLR full name, the same rule as System.Int32. A reader in another runtime needs only the component count and primitive type. CultMath has no serialization; a CultMath encoding, if added, uses this shape.

Cacheless single-file access

A single-file store file can be read and written without a cache, through public members of SingleFileBackingStore (for example SingleFileMessagePackBackingStore): ReadStoreSnapshot(), WriteRecord(record, catalogEntry, holdsIds, registry), and WriteDocument<T>(key, document, storedAt, registry). Decoding a stored payload needs no file, so it is on the codec, not the store: CultCodec.DecodeDocument<T>(key, payload) (CultCacheMessagePack.CreateCodec(registry) makes the codec).

  • ReadStoreSnapshot() reads the file once, under the store's gate (or its cache's gate when attached, validated after it is taken), and returns the durable snapshot (records, schema catalog, format stamp), or null when nothing is at the path. It throws CultStoreUnreadableException for a file the reader refuses.
  • WriteRecord writes one record under the store's lock: the record replaces the one at its key, every other record and catalog entry is copied forward as stored, and the file is replaced atomically. It takes a payload the caller already encoded, so a payload it cannot read leaves the header as the file has it (holdsIds null).
  • WriteDocument<T> writes one typed document as a cache write does: it plans element ids, encodes the document as T (the type its schema id and ids are taken from; a derived instance is stored as T) with the registry, and stores it as WriteRecord does. A failed write gives the minted ids back.
  • CultCodec.DecodeDocument<T> decodes a payload read from the store as a cache load does: it mints the ids a load mints and refuses what a cache load refuses. It reads no file and holds no state.

The registry argument of WriteRecord and WriteDocument serves that one call: the store attaches it under its gate for the call and keeps none, so the same call decides the same header on a fresh instance and on one that has served other calls.

They share everything with a cache's store and nothing is re-implemented beside it: one reader (the stamp is judged before the body, and a file the reader refuses is refused by a read and by a write alike), the store's lock, the atomic replace, and the header rule (holdsIds true marks a v3 store; false leaves it as the rule decides; null, for a payload the caller cannot read, keeps whatever the file already says). Ownership by declaration binds a cacheless write too: a record at the key under a schema id the written catalog entry does not own or list as compatible is refused with CultSchemaConflictException, and the file is left as it was. Element-id planning (CultElementIds) is internal to the library: a caller never plans or marks ids, the store does. A store attached to a cache refuses WriteRecord and WriteDocument (write through the cache, whose staged writes land through the same private write) with InvalidOperationException. CultMesh's single-file document helpers (CultMesh.WriteSingleFileDocument, ReadSingleFileDocument and their payload forms) are built on these members and nothing else of the store.

Runtime status

Rule C# Rust TypeScript Python
One home store, no mirrors implemented implemented (exact type ids; add_backing_store returns Err on a second generic store or a claimed type; an empty type list is the generic store) implemented (exact type ids; addBackingStore throws on a second generic store or a claimed type; no types is the generic store) implemented (exact type ids; add_backing_store/add_generic_store raise on a claimed type or a second generic store; an empty type list is the generic store)
Zero stores is in memory implemented implemented implemented implemented
Home cannot move after admission implemented implemented (add_backing_store returns Err and attaches nothing) implemented (addBackingStore rejects and attaches nothing; it runs in the cache's serial queue, so it cannot move a write that is in flight) implemented (add_backing_store/add_generic_store raise and attach nothing; they hold the cache's lock, so they cannot move a write that is in flight)
Refused at load when not home implemented implemented (pull_all_backing_stores returns Err naming key and both stores; load_soa returns Err for a type with no home once a store is attached; both admit nothing and leave the prior view intact) implemented (pullAllBackingStores throws naming key and both stores; admits nothing) implemented (pull_all_backing_stores raises naming key and both stores; admits nothing)
Refused write changes neither store nor cache implemented implemented (put, put_envelope, put_raw_envelope, put_prepared_batch and delete validate before the store call and apply infallibly after it; there are no user accessors) implemented (home, __global__ key and name and index accessors run before the store call; overwrite and delete use lookup values stored at admission; attach, pull, registration, writes and deletes run through one per-cache promise queue; one of those started from inside an operation queues behind it, so a store that waits for it never finishes (see Locking)) implemented (same validation order and stored lookup keys as TypeScript; attach, pull, registration, writes, deletes, name and index resolution and snapshots hold one lock per cache; a mutation started on a thread already inside one of that cache's mutations raises, reads stay reentrant; a wait on another thread is not detected (see Locking))
Attach hydrates; loading never writes implemented attach does not read (call pull_all_backing_stores); pull loads without writing attach does not read (call pullAllBackingStores); pull loads without writing attach does not read (call pull_all_backing_stores); pull loads without writing
Runtime type decides schema implemented n/a (explicit type ids) n/a n/a
Assignable lookups and watches implemented exact type ids exact type ids exact type ids
Globals never invented, singleton implemented no globals single __global__; a write under any other key is refused before any store is touched; replacing writes __global__ in place; a second persisted global (any keys) is refused on pull; invents nothing; load compatibility: a pull adopts a global stored under another key as __global__ without writing, and the first write of it pushes __global__, then deletes the legacy record, deleting __global__ again if that delete fails (a delete of it removes only the legacy record). A crash between the two steps, or a failed compensation, leaves both records on disk, and the next pull refuses them loudly as a second global. Removed once no store holds a non-__global__ global single __global__; put, put_envelope and put_envelopes refuse any other key before any store is touched; a second persisted global (any keys) is refused on pull; invents nothing; load compatibility: a pull adopts a global stored under another key as __global__ without writing, and the first write of it pushes __global__, then deletes the legacy record, deleting __global__ again if that delete fails (a delete of it removes only the legacy record). A crash between the two steps, or a failed compensation, leaves both records on disk, and the next pull refuses them loudly as a second global. Removed once no store holds a non-__global__ global
Explicit batch commit implemented put_prepared_batch: staged records must share one home; that store receives one push_all of its own held records plus the batch; empty key or stored_at refused first; all-or-nothing on stores whose push_all is atomic, which the trait requires of every store: push_all has no default, and the bundled single-file and redb stores replace in one step not implemented put_envelopes, one type per call; every record validated before one push_all, applied only after the store accepts; atomicity on disk is the store's push_all
Conditional commit implemented store-level compare_exchange family not implemented not implemented
Per-assembly options, value-type arrays contract n/a n/a n/a

A "contract" cell means this document is ahead of the C# code.

Opening a store always hydrates it. A consumer that wants a store to hold only what it writes removes the records it does not keep, upserts, and flushes. On a single-file store the flush replaces the file in one atomic step. On a directory store the flush writes pages, then the manifest, under the commit lease, merging its staged keys and removals onto the current manifest; a key another writer added since the pull survives. There is no open-without-reading option.