C#: a record no registered type claims is carried untouched, and a write over it is refused

C2a F2, operator: "CultCache never destroys or relabels a record it doesn't
understand; keeps it byte-for-byte, refuses writes that would overwrite it."

- The registry's claim decision (Claimant) is split out of resolution. It
  never decodes or compares shapes, so a store classifies a record from its
  header. The last branch, "No local CultCache schema matches", now means
  foreign instead of a refused load.
- Both store kinds keep a foreign record out of the cache and list it in
  CacheBackingStore.ForeignRecords (key, schema id, catalog name, storedAt).
- Single-file store: a whole-view write lays back every foreign record the
  file holds now, with its catalog entry, and keeps a marked header while it
  carries one (it cannot see their ids). A staged write, a commit (onto the
  file or whole view) and a whole view over a key the file holds as foreign
  refuse with CultSchemaConflictException naming the key and id. A merge
  judgement never decodes a foreign record, and one that replaced a held
  record takes it away.
- Directory store: a foreign record's page is never read; a generation that
  would replace or remove one refuses before any page is written.
- Contracts: hard rejection no longer lists "no compatible local schema
  candidate"; the persistence format says what a foreign record is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-30 20:50:15 +02:00
commit 05221dae74
7 changed files with 535 additions and 33 deletions

View file

@ -63,10 +63,12 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
var reports = new List<CultSchemaMigrationReport>();
var loaded = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
var foreign = new List<CultForeignRecord>();
for (var attempt = 1; ; attempt++)
{
loaded.Clear();
reports.Clear();
foreign.Clear();
// Only pages named by the manifest read under the lease are loaded; orphaned pages are never loaded. With no
// lock to lease (none created yet, or a store copied without it) a writer may commit mid-load, so an unleased
// load stands only if its manifest is still current; if the manifest moved it reloads, under the lease the
@ -83,7 +85,8 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
manifest.Records.OrderBy(record => record.Key, StringComparer.Ordinal).ToArray(),
manifest.SchemaCatalog,
loaded,
reports);
reports,
foreign);
if (lease != null || !ManifestMoved(manifestBytes))
{
Trace($"indexed-pages loaded={loaded.Count}");
@ -129,6 +132,7 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
_hydratedKeys.Add(key);
SetLastSchemaMigrationReports(reports);
SetForeignRecords(foreign);
IsDirty = !_dirtyKeys.IsEmpty || !_deletedKeys.IsEmpty;
Trace("publish");
}
@ -147,6 +151,7 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
RefuseVariant(entry);
Held(() =>
{
RefuseOverwrite(entry.Key.Value);
Entries[entry.Key.Value] = entry;
_dirtyKeys[entry.Key.Value] = true;
_deletedKeys.TryRemove(entry.Key.Value, out _);
@ -239,6 +244,14 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
{
Directory.CreateDirectory(_recordDirectory.FullName);
var currentIndex = currentManifest.Records.ToDictionary(record => record.Key, record => record, StringComparer.Ordinal);
// The manifest's other records stay as they are, foreign ones included; a write that would replace or remove a foreign
// record is refused before any page is written.
foreach (var key in _deletedKeys.Keys.Concat(_dirtyKeys.Keys))
{
if (currentIndex.TryGetValue(key, out var held) && Foreign(held, currentManifest.SchemaCatalog) is { } carried)
throw Overwrites(carried);
}
foreach (var key in _deletedKeys.Keys)
currentIndex.Remove(key);
foreach (var key in _dirtyKeys.Keys)
@ -310,8 +323,20 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
CultPersistedRecord[] records,
IReadOnlyCollection<CultSchemaCatalogEntry> catalogEntries,
Dictionary<string, CultStoredDocument> loaded,
List<CultSchemaMigrationReport> reports)
List<CultSchemaMigrationReport> reports,
List<CultForeignRecord> foreign)
{
// A record no registered type claims stays as the manifest names it: its page is never read, and a commit keeps it.
var claimed = new List<CultPersistedRecord>(records.Length);
foreach (var metadata in records)
{
if (Foreign(metadata, catalogEntries) is { } carried)
foreign.Add(carried);
else
claimed.Add(metadata);
}
records = claimed.ToArray();
var tracePages = string.Equals(
Environment.GetEnvironmentVariable("CULTCACHE_TRACE_STARTUP_PHASES"),
"1",

View file

@ -142,6 +142,14 @@ names a local type only when no local type has the id, for a store written by a
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 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 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 lay it back as the file holds it, a
whole-view write included. 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 marked header stays marked while a store carries one, because
the writer cannot see whether it holds element ids. 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).

View file

@ -102,10 +102,15 @@ lie about the payload:
- target schema change
- name/index lookup semantics change
- missing embedded catalog entry
- no compatible local schema candidate
This is not negotiable. Better a loud refusal than quiet bit-rot.
## Foreign records
A record with no local schema candidate is not rejected: the store carries it untouched as a
foreign record and refuses any write that would replace or remove it. See "foreign record" in
`cultcache-persistence-format.md`.
## Variant overrides
A variant's override follows the same outcome as the same member on a plain record; there

View file

@ -136,6 +136,32 @@ namespace GameCult.Caching
public CultVariantDelta? Variant { get; set; }
}
/// <summary>
/// A record a store carries untouched because no registered type owns its schema id or lists it as compatible, for example a
/// record of a type this build does not have, or one renamed without declaring its old id. The store keeps its bytes as the
/// file holds them, a write of another record keeps it, and a write that would replace or remove it is refused with a
/// <see cref="CultSchemaConflictException"/>. The cache never holds it. Declaring its schema id on a type claims it at the next load.
/// </summary>
public sealed class CultForeignRecord
{
internal CultForeignRecord(string key, string schemaId, string schemaName, string storedAt)
{
Key = key;
SchemaId = schemaId;
SchemaName = schemaName;
StoredAt = storedAt;
}
public string Key { get; }
public string SchemaId { get; }
// The name the store's catalog gives the schema.
public string SchemaName { get; }
public string StoredAt { get; }
}
public sealed class CultPersistedStoreSnapshot
{
public const string FormatV1 = "cultcache.store.v1";
@ -605,24 +631,44 @@ namespace GameCult.Caching
internal CultSchemaResolutionResult ResolvePersistedSchemaDetailed(string schemaId, IReadOnlyCollection<CultSchemaCatalogEntry> catalog)
{
var indexes = _indexes;
if (indexes.BySchemaId.TryGetValue(schemaId, out var exact))
var local = Claimant(schemaId, catalog, out var persisted);
if (local == null)
throw new InvalidOperationException(
$"No local CultCache schema matches persisted schema '{persisted!.SchemaName}' ({schemaId}).");
if (persisted == null)
{
return new CultSchemaResolutionResult(
exact,
local,
new CultSchemaMigrationReport
{
PersistedSchemaId = schemaId,
LocalSchemaId = exact.SchemaId,
PersistedSchemaName = exact.SchemaName,
LocalSchemaName = exact.SchemaName,
LocalSchemaId = local.SchemaId,
PersistedSchemaName = local.SchemaName,
LocalSchemaName = local.SchemaName,
Kind = CultSchemaMigrationKind.Exact
});
}
return BuildCompatibleResolutionResult(persisted, local);
}
// The registered type a record under this schema id belongs to, or null when no registered type claims it: a foreign record,
// which a store carries untouched. Deciding this never decodes the record or compares shapes, so a store can classify what a
// file holds without reading a payload. persisted is the catalog entry the record resolves through, and null when a
// registered type owns the id. Claimants that cannot be told apart refuse.
internal CultDocumentDescriptor? Claimant(
string schemaId,
IReadOnlyCollection<CultSchemaCatalogEntry> catalog,
out CultSchemaCatalogEntry? persisted)
{
var indexes = _indexes;
persisted = null;
if (indexes.BySchemaId.TryGetValue(schemaId, out var exact))
return exact;
// A schema is published by its id or as a compatible id.
var persisted = catalog.FirstOrDefault(entry => string.Equals(entry.SchemaId, schemaId, StringComparison.Ordinal))
?? catalog.FirstOrDefault(entry => entry.CompatibleSchemaIds.Contains(schemaId, StringComparer.Ordinal));
persisted = catalog.FirstOrDefault(entry => string.Equals(entry.SchemaId, schemaId, StringComparison.Ordinal))
?? catalog.FirstOrDefault(entry => entry.CompatibleSchemaIds.Contains(schemaId, StringComparer.Ordinal));
if (persisted == null)
{
throw new InvalidOperationException($"Persisted schema '{schemaId}' is not present in the embedded catalog.");
@ -639,23 +685,19 @@ namespace GameCult.Caching
schemaId,
listers.Select(lister => lister.SchemaName).ToArray(),
string.Empty);
return BuildCompatibleResolutionResult(persisted, listers[0]);
return listers[0];
}
foreach (var compatibleSchemaId in persisted.CompatibleSchemaIds.Where(candidate => !string.IsNullOrWhiteSpace(candidate)))
{
if (indexes.BySchemaId.TryGetValue(compatibleSchemaId, out var compatibleLocal))
{
return BuildCompatibleResolutionResult(persisted, compatibleLocal);
}
return compatibleLocal;
}
if (indexes.BySchemaName.TryGetValue(persisted.SchemaName, out var localVersions))
{
if (localVersions.Length == 1)
{
return BuildCompatibleResolutionResult(persisted, localVersions[0]);
}
return localVersions[0];
throw new InvalidOperationException(
$"CultCache schema name '{persisted.SchemaName}' is ambiguous across local versions " +
@ -663,8 +705,7 @@ namespace GameCult.Caching
"Persisted schema compatibility must identify an explicit schema id.");
}
throw new InvalidOperationException(
$"No local CultCache schema matches persisted schema '{persisted.SchemaName}' ({schemaId}).");
return null;
}
private CultDocumentDescriptor RegisterDescriptor(CultDocumentDescriptor descriptor)
@ -3349,6 +3390,14 @@ namespace GameCult.Caching
public IReadOnlyList<CultSchemaMigrationReport> LastSchemaMigrationReports => _lastSchemaMigrationReports;
/// <summary>
/// The records this store's last load found and carries untouched, ordered by key: no registered type owns their schema id or
/// lists it as compatible. See <see cref="CultForeignRecord"/>.
/// </summary>
public IReadOnlyList<CultForeignRecord> ForeignRecords => _foreignRecords;
private CultForeignRecord[] _foreignRecords = Array.Empty<CultForeignRecord>();
// Set by the cache at attach. A pull hands over everything it loaded and dropped in one call before it adopts
// any of it; if the cache refuses a record the call throws and the store keeps its previous view.
protected internal Action<IReadOnlyList<CultStoredDocument>, IReadOnlyList<CultStoredDocument>>? Loaded;
@ -3505,6 +3554,34 @@ namespace GameCult.Caching
_lastSchemaMigrationReports = reports?.ToArray() ?? Array.Empty<CultSchemaMigrationReport>();
}
// The one test of whether a stored record is foreign: no registered type claims its schema id through the catalog it was
// stored with. It reads the record's header only, never its payload. Null for a record the registry resolves.
protected CultForeignRecord? Foreign(CultPersistedRecord record, IReadOnlyCollection<CultSchemaCatalogEntry> catalog) =>
Registry.Claimant(record.SchemaId, catalog, out var persisted) == null
? new CultForeignRecord(record.Key, record.SchemaId, persisted!.SchemaName, record.StoredAt)
: null;
protected void SetForeignRecords(IEnumerable<CultForeignRecord> foreign)
{
_foreignRecords = foreign.OrderBy(record => record.Key, StringComparer.Ordinal).ToArray();
}
// A write never replaces or removes a record this store carries for a schema it does not know.
protected void RefuseOverwrite(string key)
{
var foreign = _foreignRecords.FirstOrDefault(record => string.Equals(record.Key, key, StringComparison.Ordinal));
if (foreign != null)
throw Overwrites(foreign);
}
protected CultSchemaConflictException Overwrites(CultForeignRecord foreign) => new(
$"Record '{foreign.Key}' in {this} is stored under schema id '{foreign.SchemaId}' ('{foreign.SchemaName}'), which " +
"no registered type owns or lists as compatible. The store carries it untouched and refuses a write that would replace or remove it; " +
"declare the id on a type to claim it.",
foreign.SchemaId,
new[] { foreign.SchemaName },
foreign.Key);
protected void MarkFlushSucceeded()
{
IsDirty = false;
@ -3548,13 +3625,21 @@ namespace GameCult.Caching
if (snapshot == null)
{
SetLastSchemaMigrationReports(Array.Empty<CultSchemaMigrationReport>());
SetForeignRecords(Array.Empty<CultForeignRecord>());
return;
}
var reports = new List<CultSchemaMigrationReport>(snapshot.Records.Length);
var persisted = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
var foreign = new List<CultForeignRecord>();
foreach (var record in snapshot.Records)
{
if (Foreign(record, snapshot.SchemaCatalog) is { } carried)
{
foreign.Add(carried);
continue;
}
var stored = ToStoredDocument(record, snapshot.SchemaCatalog, DeserializePayload, out var report);
reports.Add(report);
persisted[stored.Key.Value] = stored;
@ -3574,6 +3659,7 @@ namespace GameCult.Caching
foreach (var stored in loaded)
Entries[stored.Key.Value] = stored;
SetLastSchemaMigrationReports(reports);
SetForeignRecords(foreign);
}
public override void Push(CultStoredDocument entry)
@ -3581,6 +3667,7 @@ namespace GameCult.Caching
ThrowIfReadOnly();
Held(() =>
{
RefuseOverwrite(entry.Key.Value);
Entries[entry.Key.Value] = entry;
IsDirty = true;
});
@ -3606,14 +3693,16 @@ namespace GameCult.Caching
{
using (AcquireLock(wait: true))
{
var records = WholeView(Entries.Values, ReadSnapshot());
var disk = ReadSnapshot();
var foreign = ForeignOnDisk(disk);
var records = WholeView(Entries.Values, disk, foreign);
WriteSnapshot(
records,
Entries.Values.Select(entry => entry.Descriptor.ToCatalogEntry()).ToArray(),
Array.Empty<CultSchemaCatalogEntry>(),
disk?.SchemaCatalog ?? Array.Empty<CultSchemaCatalogEntry>(),
Entries.Values.Any(entry => entry.HoldsIds),
existingHeader: null,
wholeStore: true);
disk?.FormatVersion,
wholeStore: foreign.Count == 0);
WroteWholeView(records);
}
@ -3640,7 +3729,14 @@ namespace GameCult.Caching
// An unconditional commit writes what a flush would, this store's whole view plus the batch: last-writer-wins,
// and staged single writes land with it. A conditional commit (store clean) lands the batch onto the file as it is.
var ontoDisk = request.HasConditions && !IsDirty;
var records = (ontoDisk ? disk.Records : WholeView(Entries.Values, disk)).ToDictionary(record => record.Key, StringComparer.Ordinal);
var foreign = ForeignOnDisk(disk);
foreach (var entry in request.Upserts.Concat(request.Deletes))
{
if (foreign.TryGetValue(entry.Key.Value, out var carried))
throw Overwrites(carried.Foreign);
}
var records = (ontoDisk ? disk.Records : WholeView(Entries.Values, disk, foreign)).ToDictionary(record => record.Key, StringComparer.Ordinal);
// The committer judged the batch against its own view; the file may have moved since. A merge is judged on the
// set the file will hold, exactly as that set would be judged loading: what other processes wrote (arriving),
// what they removed (departing), and this batch.
@ -3660,7 +3756,7 @@ namespace GameCult.Caching
var registered = Entries.Values.Select(entry => entry.Descriptor.ToCatalogEntry())
.Concat(request.Upserts.Select(entry => entry.Descriptor.ToCatalogEntry()))
.ToArray();
WriteSnapshot(records.Values, registered, ontoDisk ? disk.SchemaCatalog : Array.Empty<CultSchemaCatalogEntry>(), holdsIds, disk.FormatVersion, wholeStore: !ontoDisk);
WriteSnapshot(records.Values, registered, disk.SchemaCatalog, holdsIds, disk.FormatVersion, wholeStore: !ontoDisk && foreign.Count == 0);
foreach (var entry in request.Deletes)
Entries.TryRemove(entry.Key.Value, out _);
foreach (var entry in request.Upserts)
@ -3675,8 +3771,20 @@ namespace GameCult.Caching
// that stores a record differently is a new store of it and mints it a later storedAt: under another id than it was loaded
// under (a type re-encoding a record it read through an older or foreign schema, shedding what it lacks), or with other
// bytes than the file holds at that storedAt. A record written exactly as it is stored keeps its storedAt.
private CultPersistedRecord[] WholeView(IEnumerable<CultStoredDocument> entries, CultPersistedStoreSnapshot? disk)
// The whole view also lays back every foreign record the file holds now, as the file holds it, and refuses an entry whose key
// the file holds as a foreign record.
private CultPersistedRecord[] WholeView(
IEnumerable<CultStoredDocument> view,
CultPersistedStoreSnapshot? disk,
IReadOnlyDictionary<string, (CultForeignRecord Foreign, CultPersistedRecord Record)> foreign)
{
var entries = view.ToArray();
foreach (var entry in entries)
{
if (foreign.TryGetValue(entry.Key.Value, out var carried))
throw Overwrites(carried.Foreign);
}
var onDisk = (disk?.Records ?? Array.Empty<CultPersistedRecord>()).ToDictionary(record => record.Key, StringComparer.Ordinal);
return entries.Select(entry =>
{
@ -3687,7 +3795,20 @@ namespace GameCult.Caching
if (!unchanged)
record.StoredAt = CultCache.MintStoredAt(record.StoredAt);
return record;
}).ToArray();
}).Concat(foreign.Values.Select(carried => carried.Record)).ToArray();
}
// The records the file holds that no registered type claims, by key.
private Dictionary<string, (CultForeignRecord Foreign, CultPersistedRecord Record)> ForeignOnDisk(CultPersistedStoreSnapshot? disk)
{
var foreign = new Dictionary<string, (CultForeignRecord, CultPersistedRecord)>(StringComparer.Ordinal);
foreach (var record in disk?.Records ?? Array.Empty<CultPersistedRecord>())
{
if (Foreign(record, disk!.SchemaCatalog) is { } carried)
foreign[record.Key] = (carried, record);
}
return foreign;
}
private static bool SameStoredBytes(CultPersistedRecord stored, CultPersistedRecord written) =>
@ -3732,16 +3853,24 @@ namespace GameCult.Caching
var removing = request.Deletes.Select(entry => entry.Key.Value).ToHashSet(StringComparer.Ordinal);
var onDisk = disk.Records.Select(record => record.Key).ToHashSet(StringComparer.Ordinal);
var arriving = new List<CultStoredDocument>(request.Upserts);
var departing = new List<CultStoredDocument>(request.Deletes);
foreach (var record in disk.Records)
{
if (landing.Contains(record.Key) || removing.Contains(record.Key))
continue;
// A foreign record is not part of what the cache judges; one that replaced a record this store holds takes it away.
if (Foreign(record, disk.SchemaCatalog) != null)
{
if (Entries.TryGetValue(record.Key, out var replaced))
departing.Add(replaced);
continue;
}
if (Entries.TryGetValue(record.Key, out var known) && known.StoredAt == record.StoredAt && known.StoredSchemaId == record.SchemaId)
continue;
arriving.Add(ToStoredDocument(record, disk.SchemaCatalog, DeserializePayload, out _));
}
var departing = new List<CultStoredDocument>(request.Deletes);
departing.AddRange(Entries.Values.Where(known =>
!onDisk.Contains(known.Key.Value) && !landing.Contains(known.Key.Value) && !removing.Contains(known.Key.Value)));
Judging!(arriving, departing);

View file

@ -4,8 +4,9 @@ namespace GameCult.Caching
{
/// <summary>
/// A write the catalog cannot describe: two schemas that share a schema id and disagree on the schema name (both arrived with the
/// records, neither registered), or a record whose schema id no chosen entry publishes. Nothing is written, so the store stays as
/// it was. It names the id, the schema names involved and a record key.
/// records, neither registered), a record whose schema id no chosen entry publishes, or a write that would replace or remove a
/// <see cref="CultForeignRecord"/>. Nothing is written, so the store stays as it was. It names the id, the schema names involved
/// and a record key.
/// </summary>
public sealed class CultSchemaConflictException : InvalidOperationException
{