42 KiB
CultCache Persistence Format
This document is the canonical design receipt for the next CultCache storage
format. GameCult.Caching in C# is the source of truth for this contract. Rust,
TypeScript, and other siblings should follow once the shape stabilizes here.
The goal is to preserve CultCache's best property: application code should work with domain data, not with a little parade of storage metadata stapled onto every object until the object forgets what it was for.
Why This Exists
The current stack has two conflicting virtues:
- domain ergonomics: users want plain typed objects
- interop durability: caches in different languages need enough persisted information to read each other's data, compare schemas, and perform soft migration when shapes drift
The old C# shape leaned hard toward ergonomics by exposing DatabaseEntry.ID
directly and letting backing stores carry a lot of implicit responsibility. The
newer Rust draft leaned hard toward persistence machinery by wrapping payloads
in a heavier envelope. Both capture part of the truth. Neither is the final
machine.
The intended format keeps storage metadata out of domain objects while making the persisted store self-describing enough for cross-language readers and training-data archaeology.
Core Rule
Domain payloads contain domain truth only.
These are not domain fields and should not be exposed on app-facing types:
- CultCache record key / GUID
- persistence schema id
- storage timestamp
Those belong to the CultCache persistence layer.
Transaction Visibility
A multi-record commit is an explicit batch of records that resolve to one home store. The store commits the batch as one durable step. Nothing in the batch is visible, to the committing flow or to observers, until the store has accepted it; a failed commit changes nothing on disk or in memory.
A batch may carry conditions: per-record version, or the whole store unchanged
since it was last loaded. A record's version is the SHA-256 of the exact bytes the
record is stored as: in a single file the record's own slice of the file, the array
[key, schemaId, storedAt, payload(, variant)] exactly as the file holds it, in
whatever legal MessagePack encoding its writer chose (never a re-encoding of the
decoded record); in a directory store the page the manifest indexes. A record being
written has the version of the bytes it is written as. It names the schema id and
storedAt as well as the payload. storedAt is metadata and decides no condition.
Conditions are evaluated
under the store's exclusive lock against what is durably on disk. A failed
condition is a lost race, not an error: the commit reports it and writes
nothing.
A flush, a commit and a single-file document write apply a write set. Under the store's exclusive lock the writer reads what is durably in the store now, applies only what it staged (writes and removals) and, for a commit, its batch, and replaces the store with the result. Every other record, and every catalog entry the result references, is copied forward as stored: a record's exact bytes and a catalog entry's exact bytes, unknown fields included, so a copied record keeps its version. No type interprets a copied record: a write may hash another record's bytes to compare versions, and reads its header (key, schema id, variant slot), but never decodes its payload. A record is encoded from the object the writer hands in, and every other record is copied as the store holds it. The store that read a file owns that file's bytes: for each stored record, its exact slice of the file and the SHA-256 of that slice, which is the record's version; likewise each catalog entry's slice. A decoded record or snapshot object carries no bytes, so an object a caller edited in place is never mistaken for what the file holds. Consequently a record the writer staged is re-encoded canonically and has the version of its new encoding, even when its content is unchanged, and a record nobody staged keeps its bytes and its version for as long as no writer stages it. The public snapshot and record serializers encode every record from its fields. A record written over one the store holds gets a storedAt later than the one it replaces. A document changed in place and not staged is not written.
In a store that holds no variant, a plain flush and an unconditional commit write the same bytes and are last-writer-wins only per staged key. An unconditional commit also persists writes staged earlier and leaves the store clean. Conditional commit is how such a writer learns that another writer moved the keys it depends on.
A store that holds a variant, or would after the write, is written only from what its writer last read. A variant resolves against other records (its base chain, and the index values it shares the store with). So before writing, the writer compares every record's version with the version it last read or wrote. If any record moved, appeared or disappeared, the whole write is refused with the typed write conflict, naming the keys it would have written and the keys that moved, and nothing is written. A writer that has read nothing, such as CultMesh's single-file document write, never writes into a store holding a variant.
A refused write reloads what it refused. A refusal (a foreign record at a key the write names, or a write conflict) reloads the durable view of every refused and moved key into the cache, as a pull would, and only then forgets the staged changes at those keys. The cache then serves what the store holds, and a retry is judged against that. If the reload is itself refused (the store holds a record this cache cannot load), nothing changes and the refusal carries that cause. A writer refuses a file whose header it cannot read (truncated, or a format it does not read) and leaves the file as it was. C# applies this to single-file stores, directory stores and CultMesh's single-file document writes; Rust, TypeScript and Python rewrite the store from their own copy until their parity cuts land.
A store that fails to hydrate on open (corrupt bytes, unresolvable schema) makes the open throw and is left byte-identical; it is never silently overwritten. Within one process the lock order is the cache's gate, then the store's gate, then the file lock; nothing under a store's gate enters a cache's gate. A store's I/O blocks its cache's readers.
C# implements batch and conditional commit (CultCache.Commit, TryCommit,
CultCacheBatch). Rust implements both. TypeScript and Python implement
neither yet. Routing, batches and conditions are specified in
cultcache-store-composition.md.
Canonical Store Shape
A persisted CultCache file should contain:
- store header
- embedded schema catalog
- record set
High-level shape:
{
"formatVersion": "cultcache.store.v1",
"catalog": {
"catalogVersion": "cultcache.schema_catalog.v1",
"schemas": []
},
"records": []
}
The on-disk encoding does not have to be JSON. MessagePack is the expected default. The shape above is explanatory.
Store Header
Required header fields:
formatVersioncatalogrecords
Optional header fields:
createdAtupdatedAtstoreIdproducernotes
These are store-level bookkeeping fields, not per-record domain metadata.
Embedded Schema Catalog
The store must embed a catalog entry for every schema referenced by the records it contains.
A reader never recovers a schema from a record's payload: a record whose schema id the catalog does not publish (by id or as a compatible id) makes the store unreadable, whatever the payload's first field says. The catalog is the store's own description of itself.
A writer keeps the same invariant: every record it writes carries a schema id that some catalog entry it writes publishes, as that entry's id or as one of its compatible ids. A cache stamps a record it puts with its registered schema's id, and a record it loads under an id its type owns or declares compatible (see below for one it does not). The cache is the only owner of that stamp: a store writer never changes the identity of a record it did not receive from its caller, so a record another writer changed since this cache read it is written back as that writer left it.
A schema type declares the older ids its records may sit under: CultDocumentAttribute.CompatibleSchemaIds
(C#), compatibleSchemaIds (TypeScript, Python). The registered catalog entry lists them after its own id, and
the cache restamps a record loaded under one to the type's own id, so the next write of that record carries the
registered id. A record another writer left under a declared id, and that a commit does not rewrite, stays under it
and the registered entry publishes it. Without the declaration such a record is read-only to the cache (see
ownership by declaration, below). Rust has no such declaration.
A cache resolves a record to a local type by the record's schema id: the registered type that owns the id, else one that lists it as compatible. The name the catalog entry carries is metadata. It names a local type only when no local type has the id, and then only to read with: a record so resolved is read-only (below). That serves a store written by a runtime whose schema ids this one cannot know (a Rust type's schema id is its entry type). A schema renamed under a stable id therefore opens in every runtime that holds the id.
A cache owns a record when it declares the record's schema id, or when the type that reads it reads it whole. A type declares an id by registering it or listing it compatible. A type reads a record whole when the catalog entry that publishes the id has the same content hash as the type's entry, or compares compatible with it and leaves no persisted slot unread. An owned record is writable: a write, relabel or removal is accepted and the write stores it under the writing type's own id (restamp on write; only a record the cache writes is restamped, the rest is copied forward as stored). A record stored under any other id that a type can read, through the catalog's schema name or an entry listing a local id, only by dropping persisted slots is loaded read-only: Get and queries serve it, a write of another record copies it as stored, and a staged write or removal of it (upsert, variant upsert, flatten, remove, commit) is refused with the typed schema conflict before anything is staged. Declaring its id compatible on any registered type makes it writable and is the consent to the loss: the next write stores it under the writing type's own id and sheds the slots.
A record whose payload carries a slot past the slots its reader declares, at any depth (nested object, list
element, union arm, unit arm), is read-only the same way, whatever id it is stored under. The one consent
is the declaration above, and it reaches only depth-0 slots the schema comparison reports ignored under a
listed compatible id, up to the highest slot it reports: a mark anywhere else, past that slot, or at depth 0
under the reader's own id, is not consented to. Declared slots are what the type's own formatter writes; only
a type MessagePack writes by its [Key] layout is checked, and one no instance of which can be written is not
(cultlib-gaps:ruling:slot-unmeasurable-type; see the schema-compatibility contract for both exemptions and
for the user code the measure runs).
A flatten of a variant whose base chain holds a record that is not owned is refused with that record's
refusal, because it would write the base's decoded view; the variant's own writes persist only its delta and
stay allowed. A plain write to another key of a value read from a read-only record is a copy this rule does
not police. CultCache.IsWritable(key) answers what the staging refusal answers for a removal or a write of
the record's type, read-only and missing home stores included; it does not predict that flatten.
The rule is checked again where the write lands, under the store's lock: a write or removal at a key
whose durable record is not owned, because another writer rewrote it after this cache
loaded, is refused typed, and the record is reloaded as the store holds it, read-only when a type can
read it. This holds for every write through the store, the store's own Push, Delete and
CommitBatch included. Whether a write may replace the record at a key is decided per key by the type it writes there, for a cache
and for a CultMesh single-file write (WriteDocument, WriteRecord, or PushAll on an unattached store) alike, in a single-file store and
a directory store alike: the written type owns the stored record when its entry declares the stored id (its own id, or one it lists
compatible), or when it is the type that reads the stored record's published entry and reads it whole (no persisted slot unread), so an older
id of its own schema name that it reads whole is its own and is restamped. Anything else is refused, another registered type's record
included, and so is a record the written type would read only by dropping persisted slots. No registry enters the decision, Shared included:
the answer for a given written entry, stored id and catalog is the same lent a registry or not, and a cache's registered types do not make
each other's records writable. Retyping a key is a removal and an add: in one batch (the removal called before the add) or staged apart, with or without a backing store. The removal half is judged as a removal, so the key is retyped only when the removal rule allows it. A one-batch retype is staged as the held record's eviction and then the add: a watcher of the old type sees Removed and a watcher of the new type sees Added, a global's slot is freed, and every check, validator and store judge sees what it sees when the two are staged apart; this holds for plain records, variants and flattens alike (a Flatten after a Remove in the same batch flattens nothing and is refused). A one-batch retype across two home stores is refused, by the rule that a commit lands in one home store: the removal is in the first store and the add in the second, so the batch spans both. Stage the removal and the add apart, as two commits (not atomic); the key is then in exactly one store. A variant rebased onto a base of another type follows the plain-write rule: where a plain write of the new type would own the variant's record (the new type declares the old id) the rebase commits and the variant becomes that type, and where a plain write would be refused the rebase is refused. A removal or check of a key goes to the
registry's removal rule (a record a registered type declares, or reads whole, may be removed), and a cacheless call, which has no registry,
removes a record only when an entry it writes owns it; a call that writes no entry removes nothing.
A record that resolves to no local type is a foreign record, for example one of a type this build does not
have, or one renamed under a new schema name without declaring its old id. A store never destroys or relabels it: the store carries it
byte for byte under its own id and its own catalog entry, lists it as foreign (CacheBackingStore.ForeignRecords
in C#), and the cache never holds it. Writes of other records proceed and copy it forward as the file holds it. A write that would replace or remove it is refused with the typed schema conflict
naming its key and id, and nothing is written. A removal of a key the cache does not hold removes nothing and is free; the store judges the key at its next flush or commit, under its lock, with the keys that write writes, and refuses the write if it holds a record there under an undeclared id, also when that record arrived after the load. A commit judges such a key in every writable store its cache attaches, each under its own lock: the stores it does not write first, then the store it writes, and a refusal in any of them writes nothing. A judged key is never removed. A read-only store answers at the removal, from its last load. The refused keys are reloaded as the store holds them (a foreign record is not held, and is listed as foreign from then on, so its next write is refused before staging), and their staged changes are forgotten. A write that carries a record forward keeps a marked header marked. Declaring its id on a type claims it at the next load.
A reader resolves a record's schema id to the entry that owns it, that entry's own schemaId, and
only when no entry owns the id to an entry that lists it as a compatible id (the first such entry
in catalog order).
A writer derives the catalog from the records it writes, and from nothing else. For each distinct
schema id a record carries it chooses exactly one entry that publishes it. For an id the write stages
a record under, that is the entry the writer registered or passed, and a rename or a stale content hash
takes the descriptor's name, hash, members and compatible ids as they are. For every other id it is
the durable entry that owns the id, else one that lists it as compatible, carried as its exact bytes,
unknown trailing fields included. A registered entry never publishes an id the write stages nothing
under. Entries are written as chosen, deduplicated by own id, with
no union of compatible ids and no dependence on the order records arrive in; an entry no record needs
is not written. A write is refused, and the store left as it was, when two entries of one tier share
an own id and disagree on the schema name, when records of different types share a schema id, when a
write would change which type an existing record resolves to (the schema names of the records already
in the store and of the records written differ), or when a record's id is published by no chosen entry.
The retyping refusal has one exception, a rename: when the entries of both the existing records and
the written ones own the id, the registered descriptor wins. (A C# cache stamps every record it
writes with its descriptor's own id, so the retyping refusal cannot arise there.) Each runtime refuses with one typed error naming the id, the
schema names and a record key: CultSchemaConflictException (C#), SchemaConflictError
(Rust, TypeScript, Python).
This is not decorative paperwork. It is what allows another CultCache implementation to inspect an old store, resolve the schema for each record, and decide whether it can:
- read directly
- soft-migrate with warnings
- or refuse the data honestly
Schema Catalog Entry
Each schema descriptor should contain at least:
schemaIdschemaNameschemaVersioncontentHashcanonicalSchema
Recommended optional fields:
migrationFamilysupersedesSchemaIdscompatibleReaderFamiliespersistenceEncodingnotes
Example:
{
"schemaId": "sha256:8b52c6...",
"schemaName": "gamecult.player-data",
"schemaVersion": "1.2.0",
"contentHash": "sha256:52ff9c...",
"migrationFamily": "player-data",
"supersedesSchemaIds": ["sha256:0ce41a..."],
"persistenceEncoding": "messagepack-array-v1",
"canonicalSchema": {
"kind": "messagepack-array-object",
"fields": [
{ "slot": 0, "name": "Name", "type": "string", "required": true },
{ "slot": 1, "name": "Email", "type": "string", "required": true },
{ "slot": 2, "name": "Level", "type": "int32", "required": false, "default": 0 }
]
}
}
schemaId
schemaId is the stable machine key. It should be derived from the canonical
semantic persistence schema, not from:
- repo path
- C# type name
- Rust type name
- TypeScript interface name
- generated file name
If two implementations describe the same persisted shape, they should derive
the same schemaId regardless of origin language.
contentHash
contentHash is separate from schemaId.
schemaIdanswers: "is this the same semantic persistence shape?"contentHashanswers: "is this the exact same canonical schema document?"
This distinction matters because descriptions, examples, and other non-semantic surface details may change without changing the actual persisted shape.
Record Shape
Each persisted record should carry only the storage metadata needed to route and reconstruct the domain object:
keyschemaIdstoredAtpayload
Example:
{
"key": "e1439d7e-8da8-4b63-a0b1-238c815a8a17",
"schemaId": "sha256:8b52c6...",
"storedAt": "2026-05-08T12:00:00Z",
"payload": "<messagepack bytes>"
}
The payload is the domain object only. It does not repeat the key, schema id, or stored timestamp.
Under cultcache.store.v1 and cultcache.store.v3 a record has exactly these four slots.
A reader refuses any cultcache.store.* header it does not know and any record with more
slots than its header allows, naming the version or the record's key and schema id. It
never skips a slot it does not understand.
The headers are v1 (no variant, no element ids), v2 (holds a variant) and v3 (holds
an element id, variants or not). A single-file store declares v3 when any record it
holds carries an element id: a non-empty [CultElementId] value in a record's document,
or in a variant's override values. A store that cannot read a variant's override values
(no codec attached) counts the variant as holding one. An element id is an ordinary keyed
string in the payload, so only a reader with the record's type can tell; a C# write
decides for the records it encodes and, while the header it found is unmarked, for every
plain record it copies forward that its registry can read, decoding the bytes the file
holds under the store's lock. A copied record it cannot read, and a raw CultMesh payload,
decide nothing. A write that copies any record forward
therefore keeps a v3 header it found. Only a write that encodes every record the store
will hold decides by content, and drops to v1 (or v2 with a variant) when none holds
an id. A directory store's manifest says
cultcache.store.v5.directory-content-addressed-pages under the same rule, and v4
otherwise.
A single-file store is exactly one MessagePack array of three slots: the header, the schema
catalog and the records. Every runtime refuses a file that is truncated, has bytes after the
array (a second store appended included), is not an array, has fewer or more than three slots
(a header alone included), whose first slot is not a header it reads, or whose catalog or
records it cannot decode (a record with more slots than its header allows, a variant record
it does not read). A runtime never skips a slot it does not understand. It refuses on open
and on rewrite alike, because the rewrite asks the same full reader as the open. Only nothing at the path is a missing
file, and a missing file and an empty array are an empty store; a zero-byte file is not a store and is refused as unreadable.
In C#, a link whose target is gone and a directory at the path are I/O errors, never an empty store. Within a runtime, every
reader and writer of a single-file store shares that one reader, lock and replace (in C#, CultMesh's single-file document
helpers included), and a catalog entry has one layout. A flush or a commit replaces a file only when the
runtime's own reader opens it, so one verdict covers open, flush and commit, and a file the
runtime cannot read is left as it is. Each runtime refuses with one typed error:
CultStoreUnreadableException (C#), CultCacheStoreUnreadable{path, kind} (Rust, its kind
telling an undecodable store from an unsupported format), StoreUnreadableError (TypeScript,
Python), with the underlying cause attached. Rust, TypeScript and Python also open the legacy envelope
array (an array of key/type/payload/storedAt maps) and replace it; C# has no legacy
reader and refuses it. The shared byte vectors and each runtime's verdict are
tests/vectors/document-variants-c2a/readability/manifest.txt.
A record's payload nests at most 256 MessagePack containers. Every array and map
counts, whether a reader decodes it or skips past it, and the outermost array is
depth 1: a payload of depth 256 is accepted and one of depth 257 is refused. Every
runtime enforces the same bound on read and on write, and the refusal names the type,
the depth and the limit, never payload bytes. The vectors are in
tests/vectors/union-parity (bounds-outcomes.msgpack).
A record's payload is exactly one MessagePack value: every runtime refuses a payload with bytes after its first value wherever it reads a payload under the nesting bound, and on write where a write takes bytes the library did not encode itself (a C# type's own formatter, a Rust raw envelope), without walking those bytes, so a tail past the limit is refused as bytes after the value and not as depth; the refusal names the type and the count of bytes after the value, never the bytes (vectors: tests/vectors/union-parity/bytes-after-outcomes.msgpack). A CDN manifest is stored and keyed as a record and follows the same rule (contracts/cultmesh/content-acceptance-vectors.json: trailing_nil, trailing_reserved_code and trailing_truncated_array are refused). Streams of values (CultNet frames, a store's record array) are different contracts and are not covered.
Variant Records
A variant record is a record whose document is a base record's document with some members replaced. It stores the difference, never the resolved document. It carries a fifth slot:
[key, schemaId, storedAt, payload, [baseKey, overrides[]]]
payloadis empty. An older reader that ignores the fifth slot reads an empty payload as a corrupt document and refuses, which is why the delta lives outside it.schemaIdis the type's schema id, the same as the base's. A variant has its base's concrete type, and lives in the same store (one home store per type).- An override is
[op, path[], id, value].opis0Set,1Insert or2Remove. A path step is[slot, elementId]:slotis the member's MessagePack[Key]andelementIdis""unless the step enters an object-list element.valueis the member's own MessagePack encoding, inline. A top-level Set has one step andid""; a reader that resolves only that shape refuses the others, naming the variant. - A store holding at least one variant declares
cultcache.store.v2(v3when it holds an element id); a store holding none declarescultcache.store.v1(orv3) and is byte-identical to what a runtime without variants writes. Av1header over a variant record is refused. - A variant's resolved document is derived in memory when the cache admits the record
or any record on its base chain, and is never written back. A plain write at a
variant's key is refused;
Flattenreplaces a variant with a plain record holding its resolved document. - The C# runtime resolves variants. Every other runtime refuses a
v2store by name, and refuses a variant record inside av3store by its record key. CultMesh single-file reads, the directory store and CultNet refuse a variant record by name until each has its own cut.
Element Ids
Every object that sits in a list, array or dictionary value of a shape the element-id walk
owns carries an id: one string member with an integer [Key] and [CultElementId]. The
owned shapes are arrays, IEnumerable<T> classes and interfaces, IDictionary<,> and
IReadOnlyDictionary<,> values, and [MessagePackObject] or [Union] types with integer
keys (a keyed struct included), read through the members MessagePack writes. Union subtypes
are included. The id identifies the element inside its list, so an override can name it (a
path step is [slot, elementId]) and a base edit that reorders or inserts elements
retargets nothing.
Any other shape is one whole value. Its elements carry no element ids: a [CultElementId]
member inside it is a plain string, never minted or checked and never counted for v3. A
variant replaces it whole (operator, 2026-10-16).
- A random id is 12 lowercase hex characters. A derived id
(
[CultElementId(nameof(Source))], for content-addressed elements) is the invariant-culture text of its source member, which must be non-empty; it needs no other format. An id is unique within its list. - A write mints random ids for unset elements, including inside variant override
values, and refuses a duplicate, a malformed random id or an empty derived source. A
load refuses the same things, naming the record, the list and the id. A record
written before ids existed loads, and its ids are minted from SHA-256 of the record
key and the element's path, so every reader mints the same ids; they reach disk with
the record's next write, or
CultCache.MintElementIds(). - A store that holds an id declares the
v3header (above), so a reader older than ids refuses it instead of skipping the id slot and rewriting the elements without ids. A C# write also marks the store when a record it copies forward holds an id, judged from the file's bytes at the write (above). TypeScript, Python and Rust readv3and keep av3header they found when they rewrite a store; they carry ids and do not decide when a document carries them. - An object list's elements are written by their
[Key]layout, because the id is a keyed member of the element. Value lists are replaced whole: a list of a non-keyed class or struct, or of primitives. So is a list of keyed structs, since a struct is a value and never an element, but an object list inside a keyed struct is walked like any other. The walk follows declared member types: a member declaredobjectis untyped on disk, and a subclass's extra members under a non-union base-typed member are not written, so neither is walked. Whole values areImmutableArray<T>,ArraySegment<T>,Memory<T>,KeyValuePair, tuples,Lazy<T>, a class or struct without[MessagePackObject], a[DataContract]type, a string-keyed type, a type or member declaring[MessagePackFormatter], and a non-public member of a type withoutAllowPrivate. The members read are an integer[Key]with no[IgnoreMember]: a public field or a property whose getter is public, or any visibility up the base chain under the most derived[MessagePackObject(AllowPrivate = true)]declaration. An id member needs a setter MessagePack calls (public orinit; any underAllowPrivate), so the id MessagePack writes is read back. Still refused: a bad id member (missing, duplicate, not a string, no integer[Key],[MessagePackFormatter]on it, one MessagePack does not write or cannot assign, a key shared with another member, a bad derived source), a concrete union arm that is not keyed, a keyed type that is also a collection (ICollection<T>,IList,IDictionary: MessagePack writes it as a collection, so C# refuses it at the first encode or decode when it is on the path to an object list), a type MessagePack has no formatter for, and a formatter resolver that claims a type on the path. A formatter MessagePack's source generator emits is not refused.
Canonical Semantic Schema Hash
schemaId should be derived from a canonical semantic schema hash.
The canonicalization step must ignore noise that should not change storage identity, such as:
- whitespace
- key ordering
- documentation prose
- examples
- source-generator quirks
It must preserve the parts that do define persistence compatibility:
- field slot numbers
- field types
- required versus defaulted presence
- nullability
- collection/container semantics
- enum/value constraints when those affect stored meaning
- persistence encoding shape, such as MessagePack array layout
The output should be a stable string such as:
sha256:<hex>
This is the value persisted in each record's schemaId.
Soft Migration
Soft migration is a first-class requirement. The format must support a reader encountering a record whose embedded schema is not byte-identical to its local native schema while still consuming the record safely when the slot contract is compatible enough.
Reader flow:
- Read record header.
- Resolve
schemaIdagainst the embedded catalog. - Resolve the local registered schema for the requested native type.
- Compare embedded versus local canonical persistence schemas.
- Choose one:
exact_matchsoft_migratereject
Exact Match
Read directly when:
- schema ids match exactly
- or equivalent schema comparison says the persisted and local canonical shapes are identical
Soft Migration
Allowed when:
- persisted schema has missing slots that the local schema can default
- slot meanings remain compatible
A persisted schema with extra slots the local reader lacks is not soft: the record is read-only (see the ownership rule above). Soft migration should emit warnings, not silent shrugs.
Typical warnings:
- missing slot defaulted
- nullable/default behavior widened
- field preserved but not surfaced natively
Reject
Reject when:
- slot meanings conflict
- required local data cannot be reconstructed
- stored type and local expected type are incompatible
- persistence encoding families differ in a non-compatible way
Do not bluff here. A false clean read is worse than a refusal.
API Ergonomics
The public CultCache API should hide persistence metadata by default.
Desired feel:
- callers work with
PlayerData, notPlayerDataplus storage sludge - cache methods own key generation or key routing
- global and named-entry flows stay ergonomic
- advanced callers can still inspect raw records and catalogs when needed
This implies a split between:
- domain-facing API
- raw persistence/interop API
Domain-Facing Surface
Domain callers should interact with:
- typed adds/puts
- typed gets
- named lookups
- index lookups
- global entry helpers
They should not have to care about schemaId, storedAt, or raw payload bytes
unless they are explicitly doing migration, tooling, or replication work.
Raw Persistence Surface
The lower-level API should still expose:
- record inspection
- schema catalog inspection
- raw record import/export
- migration diagnostics
- exact payload preservation for bit-compatible neighbors
That is the cache's responsibility, not the domain model's.
Concurrent Store Policy
CultCache files are expected to become shared state, not private save blobs.
Once multiple runtimes can read and write the same .cc file, the persistence
contract must protect both durability and observation.
The store header should declare the write policy a runtime must obey before it mutates the file:
generation: monotonic store generation, incremented on each committed snapshotcontentHash: hash of the committed snapshot bodyconcurrency.policy: stable policy id, such ascultcache.concurrent.snapshot-lock.v1concurrency.lockName: how to derive the sidecar lock pathconcurrency.commit: commit primitive, such asatomic-replace
The header negotiates the protocol. It does not enforce the protocol by magic. Writers still need an external coordination primitive because replacing the main file also replaces whatever identity a platform may attach to that file handle.
The v1 concurrent single-file policy is:
- Readers may read lock-free when they can tolerate a stale-but-complete snapshot. Readers that need a stable read boundary take a shared sidecar lock.
- Writers take an exclusive sidecar lock derived from the
.ccpath. - Writers re-read the current snapshot after taking the lock.
- Writers using conditional commit evaluate their conditions against the latest snapshot and write nothing if one fails. In a store with no variant, a plain flush and an unconditional commit compare nothing: they apply their staged writes onto the current snapshot, last-writer-wins per staged key. A write into a store that holds or would hold a variant compares every record's version with what the writer last read, and is refused if any moved. One whose header they cannot read is refused untouched.
- Writers write a temp file, flush it, atomically replace the
.ccfile, and release the lock.
This preserves the key invariant: every reader sees a complete snapshot. Only a conditional commit is protected against committing over unseen data.
Live Change Observation
A shared CultCache file is also a low-ceremony realtime database for local applications. The filesystem is the transport. CultCache is the typed database surface. The cache should therefore expose domain-level change streams, not force applications to subscribe to raw storage envelopes.
Recommended C# surface:
Observable<CultCacheChange<T>> Watch<T>();
Observable<T> WatchRecord<T>(CultRecordKey key);
Observable<T> WatchGlobal<T>();
Observable<T> WatchByName<T>(string name);
Change events should be emitted after a pulled or locally committed snapshot has
been reconciled into the in-memory cache. Subscribers should see domain objects
and cache-owned handles, not raw schemaId, storedAt, or MessagePack payload
bytes unless they explicitly subscribe to the raw persistence lane.
The event model should distinguish at least:
addedupdatedremovedschema_migratedrejected
Local and remote-looking writes use the same reconciliation path. A write from another process is just a new committed generation discovered through file watching or polling, pulled into the cache, diffed against the current domain view, and published.
R3 Alignment
The C# reactive surface should align with R3, Cysharp/neuecc's modern Reactive Extensions implementation and successor line to UniRx. CultCache should not invent a bespoke observer API when the .NET ecosystem already has a well-understood shape for composable streams.
R3 should own the C# subscription ergonomics:
Observable<T>for public domain streamsSubject<T>or internal equivalents only at ownership boundaries- disposable subscriptions for lifecycle control
- debounce/throttle operators for bursty filesystem notifications
- scheduler hooks where Unity, desktop UI, or server callers need thread affinity
The invariant is simple: the persistence layer owns bytes and generations; the cache owns domain identity and diffing; R3 owns composition of observed changes.
CultNet Alignment
CultCache and CultNet should not grow rival schema religions.
The schema descriptor shape used by the CultCache embedded catalog should align with the CultNet schema catalog as closely as practical. In particular:
schemaIdschemaVersioncontentHash- canonical schema body
should mean the same thing across persistence and wire discovery.
Where CultNet needs additional wire-oriented metadata, extend around the shared core instead of redefining the core.
CultNet As A Sharding Layer
CultNet should be able to initialize directly as a CultCache distribution layer. The goal is a single distributed realtime database surface: clients work with typed CultCache documents, while CultNet decides which node owns the relevant shard and how committed changes reach subscribers.
This is closer to the application experience of RethinkDB or Firebase than a traditional request/response game protocol. CultNet should still keep its own shape: explicit schemas, MessagePack payloads, local-first operation where useful, and honest rejection when compatibility or authority is unclear.
The ownership split is:
- CultCache owns document identity, schema compatibility, local indexing, persistence, and domain-level change diffing.
- CultNet owns peer membership, shard routing, mutation transport, authorization, remote subscription fanout, and resynchronization after reconnect.
- R3 owns C# stream composition for observed domain changes.
A distributed CultCache cluster should expose:
- shard descriptors: which schema/key ranges or named partitions a node owns
- shard epochs: monotonic authority versions for ownership changes
- mutation messages: raw document put/delete records with source generation and shard epoch
- snapshot messages: bounded catch-up from a known generation or empty local state
- subscription messages: schema/key/index/global queries that stream matching domain changes
- conflict reports: explicit outcomes when a mutation cannot be applied cleanly
Client-facing APIs should preserve the database illusion:
var db = await CultNetDatabase.ConnectAsync("localhost", 3075);
var player = await db.GetAsync<PlayerData>(playerKey);
await db.PutAsync(playerKey, player);
using var subscription = db
.WatchByIndex<PlayerData>("Region", "eu-west")
.Subscribe(change => Render(change.Document));
The illusion has limits and those limits should be visible in the contract. CultNet is not allowed to pretend that arbitrary split-brain writes merged cleanly. Each shard needs one current write authority, or a declared conflict strategy that can be explained without ritual smoke. If neither exists, the write is rejected and surfaced as a domain-visible failure.
The simplest coherent first implementation is primary-shard ownership:
- Each shard has one authoritative writer at a time.
- Followers subscribe to that shard's committed mutation stream.
- Clients may connect to any node; non-owner nodes forward writes to the shard owner or reject when forwarding is unavailable.
- Reconnect performs schema discovery, shard epoch comparison, then snapshot catch-up before live events resume.
More advanced replicated or offline-first conflict policies can come later, but they must be explicit shard policies rather than accidental behavior leaking out of transport retries.
Migration From Current C# Shape
The current C# DatabaseEntry base type exposes ID directly. That is useful
today but not the desired long-term boundary.
Planned direction:
- define the v1 persistence format here
- implement store header, catalog, and record shape in C#
- move storage identity out of the domain-facing
DatabaseEntrycontract - keep compatibility shims long enough to read older stores
- let Rust, TypeScript, and other siblings follow the stabilized C# contract
The transition should preserve the existing soft-migration advantage rather than trading it for fake purity.
Near-Term Rules
Until this format is implemented:
- treat this document as the canonical target
- do not add new storage metadata to domain payloads
- prefer schema catalogs over repeated per-document metadata
- preserve the distinction between semantic schema identity and exact schema document hash
- keep cross-language interop as a first-class design constraint, not a later apology