CultCache: element ids on every object-list element (C2a)

[CultElementId] marks a string member; the registry refuses a document type
whose list element type (union bases included) lacks one, naming the type and
member. A write mints a random 12-hex id for each unset id and refuses a
duplicate within one list. A store written before ids loads with ids minted in
memory from SHA-256(record key, element path), so every reader and every reload
agrees; they persist on the store's first write. CultCache.MintElementIds()
rewrites the records whose ids exist only in memory.

CultLib's own list-element types gain an id (Geometry, Mesh body, discovery,
entity prefab). CultMeshCdnChunkRef and the CultWitness* elements are pinned by
cross-runtime vectors and are left alone; see the C2a report.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
x 2026-09-29 12:31:12 +02:00
commit 0d2645d056
7 changed files with 646 additions and 0 deletions

View file

@ -632,6 +632,8 @@ namespace GameCult.Caching
?? throw new InvalidOperationException(
$"Type {type.FullName} is not marked with {nameof(CultDocumentAttribute)}.");
var members = DiscoverMembers(type);
if (CultElementIds.Problems(type) is { Count: > 0 } idProblems)
throw new InvalidOperationException(idProblems[0]);
var nameMember = members.FirstOrDefault(member => member.IsName);
var indexAccessors = members
.Where(member => member.IndexAlias != null)
@ -1798,6 +1800,8 @@ namespace GameCult.Caching
private readonly CultDocumentRegistry _registry;
private readonly List<(CacheBackingStore Store, Type[] Homes)> _stores = new();
private readonly Dictionary<string, CultStoredDocument> _entries = new(StringComparer.Ordinal);
// Keys whose element ids were minted at load and not yet written (see MintElementIds).
private readonly HashSet<string> _mintedOnLoad = new(StringComparer.Ordinal);
private readonly Dictionary<Type, Dictionary<string, string>> _names = new();
// Every key holding a value (unordered): the index is truthful about duplicates, so removing one holder never hides another.
private readonly Dictionary<(Type Type, string Alias), Dictionary<string, List<string>>> _indexes = new();
@ -1834,6 +1838,8 @@ namespace GameCult.Caching
if (_codec == null) throw new InvalidOperationException("This cache has no codec; create it with CultCacheMessagePack.Create.");
var found = _registry.GetRequired(documentType).RichMembers.FirstOrDefault(entry => entry.Member.Name == member)
?? throw new ArgumentException($"{documentType.Name} has no persisted member '{member}'.", nameof(member));
if (value != null)
CultElementIds.Assign(value, string.Empty, deterministic: false, refuseDuplicates: true);
return CultVariantOverride.Set(
found.Slot,
_codec.Serialize(value!, found.MemberType, documentType));
@ -1841,6 +1847,29 @@ namespace GameCult.Caching
public CultVariantOverride Override<T>(string member, object? value) where T : class => Override(typeof(T), member, value);
// The one-shot rewrite for stores written before element ids existed: upserts every record whose ids exist only in
// memory (minted when it loaded), through the normal write path, one commit per home store. Returns how many records
// it rewrote; a second call finds none.
public int MintElementIds()
{
var groups = Held(() => _mintedOnLoad
.Select(key => _entries.TryGetValue(key, out var entry) ? entry : null)
.Where(entry => entry is { Variant: null })
.GroupBy(entry => Home(entry!.Descriptor.DocumentType))
.Select(group => group.Select(entry => entry!).ToArray())
.ToArray());
foreach (var group in groups)
{
Commit(batch =>
{
foreach (var entry in group)
batch.Upsert(entry.Descriptor.DocumentType, entry.Document, entry.Key);
});
}
return groups.Sum(group => group.Length);
}
public bool IsDirty
{
get
@ -2319,12 +2348,30 @@ namespace GameCult.Caching
if (_held == null)
throw new InvalidOperationException("An admission reached the cache under a plain lock on its gate; every admission runs in a hold.");
var home = Validate(admitted, evicted, source);
// Ids are filled before anything lands: a write mints random ids and refuses a duplicate in one list; a load of a
// record written before ids existed mints the ids its reload will mint again, and lands in memory only.
var mintedOnLoad = new List<string>();
foreach (var stored in admitted)
{
if (stored.Variant == null && stored.IsResolved &&
CultElementIds.Assign(stored.Document, stored.Key.Value, deterministic: source != null, refuseDuplicates: source == null) > 0 &&
source != null)
mintedOnLoad.Add(stored.Key.Value);
}
// The one resolution: a variant admitted, a base admitted or evicted, all resolved here against the post-batch
// set, before land and before memory. land receives the admitted records with variants resolved.
var plan = Resolve(admitted, evicted, source);
var outcome = land(home, plan.Admitted);
if (outcome != CultCommitOutcome.Committed)
return outcome;
// A record whose ids exist only in memory stays listed until a write persists them or the record goes.
foreach (var stored in admitted)
_mintedOnLoad.Remove(stored.Key.Value);
foreach (var stored in evicted)
_mintedOnLoad.Remove(stored.Key.Value);
foreach (var key in mintedOnLoad)
_mintedOnLoad.Add(key);
foreach (var change in Apply(plan, evicted, source))
_held.Add((change, source != null));
return CultCommitOutcome.Committed;

View file

@ -0,0 +1,273 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using MessagePack;
namespace GameCult.Caching
{
// The identity of one element of an object list. A string member, keyed like any other, on every object type that
// sits in a list of a registered document type (union bases included: subclasses inherit the member).
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class CultElementIdAttribute : Attribute
{
}
// The one owner of element identity: which types need an id, and how unset ids are filled.
// An id is 12 lowercase hex characters (48 bits); it need only be unique within one list. A write mints a random id; a
// load of a store written before ids existed mints from SHA-256(record key, element path), so every reader of the same
// store mints the same id and a reload is identical to what was read.
internal static class CultElementIds
{
private const int IdBytes = 6;
private sealed class Shape
{
public Func<object, string?>? GetId;
public Action<object, string>? SetId;
public (int Slot, Func<object, object?> Get)[] Walk = Array.Empty<(int, Func<object, object?>)>();
}
private static readonly ConcurrentDictionary<Type, Shape> Shapes = new();
// ---- registration: which element types must carry an id ----
// Every reason this document type cannot be registered under the id rule, one per offending element type.
internal static List<string> Problems(Type documentType)
{
var problems = new List<string>();
VisitObject(documentType, documentType, new HashSet<Type>(), problems);
return problems;
}
private static void VisitObject(Type documentType, Type type, HashSet<Type> seen, List<string> problems)
{
if (!seen.Add(type))
return;
foreach (var (member, memberType) in KeyedMembers(type))
VisitMemberType(documentType, type, member, memberType, seen, problems);
foreach (var union in type.GetCustomAttributes<UnionAttribute>(true))
VisitObject(documentType, union.SubType, seen, problems);
}
private static void VisitMemberType(Type documentType, Type owner, MemberInfo member, Type memberType, HashSet<Type> seen, List<string> problems)
{
memberType = Nullable.GetUnderlyingType(memberType) ?? memberType;
if (IsLeaf(memberType))
return;
if (DictionaryValueType(memberType) is { } valueType)
{
VisitMemberType(documentType, owner, member, valueType, seen, problems);
return;
}
if (ElementTypeOf(memberType) is { } element)
{
if (IsObjectType(element))
{
var problem = IdProblem(element);
if (problem != null)
problems.Add($"Cult document {documentType.Name}: list element type {element.Name} (in {owner.Name}.{member.Name}) {problem}");
VisitObject(documentType, element, seen, problems);
}
else
VisitMemberType(documentType, owner, member, element, seen, problems);
return;
}
if (IsObjectType(memberType))
VisitObject(documentType, memberType, seen, problems);
}
private static string? IdProblem(Type element)
{
var ids = MembersOf(element).Where(member => member.IsDefined(typeof(CultElementIdAttribute), true)).ToArray();
if (ids.Length == 0)
return "has no [CultElementId] member; add a public string member with [Key] and [CultElementId] so each element has an identity.";
if (ids.Length > 1)
return $"has two [CultElementId] members ({ids[0].Name}, {ids[1].Name}); an element has one identity.";
var id = ids[0];
if (TypeOf(id) != typeof(string))
return $"declares [CultElementId] on {id.Name}, which is not a string.";
if (KeyOf(id) == null)
return $"declares [CultElementId] on {id.Name}, which has no integer [Key], so it is never persisted.";
if (id is PropertyInfo { SetMethod: null } or FieldInfo { IsInitOnly: true })
return $"declares [CultElementId] on {id.Name}, which cannot be assigned; the cache mints into it.";
return null;
}
// ---- write and load: mint and check ----
// Fills every unset element id under root and returns how many were unset. Writes refuse a duplicate id within one
// list. dryRun counts and changes nothing. rootPath (the record key) seeds deterministic minting.
internal static int Assign(object root, string rootPath, bool deterministic, bool refuseDuplicates, bool dryRun = false)
{
var count = 0;
Visit(root, rootPath);
return count;
void Visit(object? value, string path)
{
if (value == null)
return;
var type = value.GetType();
if (IsLeaf(type))
return;
if (value is IDictionary dictionary)
{
foreach (DictionaryEntry entry in dictionary)
Visit(entry.Value, path + "{" + entry.Key + "}");
}
else if (value is IEnumerable list)
Elements(list, path);
else if (IsObjectType(type))
{
foreach (var (slot, get) in ShapeOf(type).Walk)
Visit(get(value), path + "." + slot);
}
}
void Elements(IEnumerable list, string path)
{
var items = list.Cast<object?>().ToArray();
var taken = new HashSet<string>(StringComparer.Ordinal);
foreach (var item in items)
{
var id = item != null && IsObjectType(item.GetType()) ? ShapeOf(item.GetType()).GetId?.Invoke(item) : null;
if (!string.IsNullOrEmpty(id) && !taken.Add(id!) && refuseDuplicates)
throw new InvalidOperationException(
$"Element id '{id}' appears twice in one list ({path}); an element id is unique within its list.");
}
for (var index = 0; index < items.Length; index++)
{
var item = items[index];
if (item == null)
continue;
var itemPath = path + "/" + index;
if (IsObjectType(item.GetType()) && ShapeOf(item.GetType()) is { SetId: { } set, GetId: { } get })
{
if (string.IsNullOrEmpty(get(item)))
{
count++;
if (!dryRun)
set(item, Mint(itemPath, deterministic, rootPath, taken));
}
}
Visit(item, itemPath);
}
}
}
private static string Mint(string itemPath, bool deterministic, string rootPath, HashSet<string> taken)
{
for (var attempt = 0; ; attempt++)
{
var bytes = new byte[IdBytes];
if (deterministic)
{
using var sha = SHA256.Create();
var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(rootPath + "|" + itemPath + "|" + attempt));
Array.Copy(hash, bytes, IdBytes);
}
else
RandomBytes(bytes);
var id = Hex(bytes);
if (taken.Add(id))
return id;
}
}
private static void RandomBytes(byte[] bytes)
{
using var random = RandomNumberGenerator.Create();
random.GetBytes(bytes);
}
private static string Hex(byte[] bytes)
{
var text = new StringBuilder(bytes.Length * 2);
foreach (var value in bytes)
text.Append(value.ToString("x2"));
return text.ToString();
}
// ---- shapes ----
private static Shape ShapeOf(Type type) => Shapes.GetOrAdd(type, Build);
private static Shape Build(Type type)
{
var shape = new Shape();
var idMember = MembersOf(type).FirstOrDefault(member => member.IsDefined(typeof(CultElementIdAttribute), true));
if (idMember != null)
{
shape.GetId = idMember is FieldInfo field ? o => (string?)field.GetValue(o) : o => (string?)((PropertyInfo)idMember).GetValue(o);
shape.SetId = idMember is FieldInfo f ? (o, v) => f.SetValue(o, v) : (o, v) => ((PropertyInfo)idMember).SetValue(o, v);
}
shape.Walk = KeyedMembers(type)
.Where(entry => !IsLeaf(Nullable.GetUnderlyingType(entry.Type) ?? entry.Type))
.Select(entry => (Slot: KeyOf(entry.Member)!.Value, Get: entry.Member is FieldInfo fi
? (Func<object, object?>)(o => fi.GetValue(o))
: o => ((PropertyInfo)entry.Member).GetValue(o)))
.ToArray();
return shape;
}
private static IEnumerable<MemberInfo> MembersOf(Type type) =>
type.GetFields(BindingFlags.Instance | BindingFlags.Public).Cast<MemberInfo>()
.Concat(type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(property => property.GetIndexParameters().Length == 0 && property.GetMethod != null));
private static IEnumerable<(MemberInfo Member, Type Type)> KeyedMembers(Type type) =>
MembersOf(type).Where(member => KeyOf(member) != null).Select(member => (member, TypeOf(member)));
private static int? KeyOf(MemberInfo member) => member.GetCustomAttribute<KeyAttribute>(true)?.IntKey;
private static Type TypeOf(MemberInfo member) => member is FieldInfo field ? field.FieldType : ((PropertyInfo)member).PropertyType;
// ---- type classification ----
// A value MessagePack writes whole and that cannot hold an element list. Structs are values: never elements, never walked.
private static bool IsLeaf(Type type)
{
if (type.IsPrimitive || type.IsEnum || type == typeof(string) || type.IsValueType)
return true;
return type.IsArray && IsLeaf(type.GetElementType()!);
}
// An object a store can hold an element list under, or hold as an element: a class MessagePack serializes by key.
private static bool IsObjectType(Type type) =>
(type.IsClass || type.IsInterface) && type != typeof(string) && type != typeof(object) &&
(type.IsDefined(typeof(MessagePackObjectAttribute), true) || type.IsDefined(typeof(UnionAttribute), true));
private static Type? ElementTypeOf(Type type)
{
if (type.IsArray)
return type.GetElementType();
foreach (var candidate in type.GetInterfaces().Append(type))
{
if (candidate.IsGenericType && candidate.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return candidate.GetGenericArguments()[0];
}
return null;
}
private static Type? DictionaryValueType(Type type)
{
foreach (var candidate in type.GetInterfaces().Append(type))
{
if (candidate.IsGenericType && candidate.GetGenericTypeDefinition() == typeof(IDictionary<,>))
return candidate.GetGenericArguments()[1];
}
return null;
}
}
}

View file

@ -60,6 +60,10 @@ namespace GameCult.Geometry
[MessagePackObject]
public sealed class CultGeometryDomainNode
{
[Key(7)]
[CultElementId]
public string Id { get; set; } = string.Empty;
[Key(0)]
public string Name { get; set; } = string.Empty;
@ -105,6 +109,10 @@ namespace GameCult.Geometry
[MessagePackObject]
public sealed class CultGeometryFeatureClaim
{
[Key(8)]
[CultElementId]
public string Id { get; set; } = string.Empty;
[Key(0)]
public string Name { get; set; } = string.Empty;
@ -261,6 +269,10 @@ namespace GameCult.Geometry
[MessagePackObject]
public sealed class CultGeometryContributionRow
{
[Key(13)]
[CultElementId]
public string Id { get; set; } = string.Empty;
[Key(0)]
public string DomainKey { get; set; } = string.Empty;

View file

@ -1,3 +1,4 @@
using GameCult.Caching;
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
@ -34,6 +35,10 @@ namespace GameCult.Mesh
[MessagePackObject]
public sealed class CultMeshBodyDescriptor
{
[Key(13)]
[CultElementId]
public string Id { get; set; } = string.Empty;
[Key(0)] public string BodyId { get; set; } = string.Empty;
[Key(1)] public string SchemaId { get; set; } = string.Empty;
[Key(2)] public int LayoutVersion { get; set; }

View file

@ -417,6 +417,10 @@ namespace GameCult.Mesh
[MessagePackObject]
public sealed class CultMeshDiscoveryCandidateDocument
{
[Key(5)]
[CultElementId]
public string Id { get; set; } = string.Empty;
[Key(0)] public CultMeshVerseDescriptorMessage Descriptor { get; set; } = new CultMeshVerseDescriptorMessage();
[Key(1)] public string SourceId { get; set; } = "";
[Key(2)] public string ObservedAtUtc { get; set; } = "";

View file

@ -80,6 +80,10 @@ namespace GameCult.Mesh
[MessagePackObject]
public sealed class CultMeshEntityPrefabComponent
{
[Key(2)]
[CultElementId]
public string Id { get; set; } = string.Empty;
/// <summary>Portable component kind or runtime adapter type.</summary>
[Key(0)]
public string Type { get; set; } = string.Empty;
@ -95,6 +99,10 @@ namespace GameCult.Mesh
[MessagePackObject]
public sealed class CultMeshEntityPrefabAssetRef
{
[Key(6)]
[CultElementId]
public string Id { get; set; } = string.Empty;
/// <summary>Stable source asset id inside the prefab package.</summary>
[Key(0)]
public string AssetId { get; set; } = string.Empty;
@ -126,6 +134,10 @@ namespace GameCult.Mesh
[MessagePackObject]
public sealed class CultMeshEntityPrefabNode
{
[Key(10)]
[CultElementId]
public string Id { get; set; } = string.Empty;
/// <summary>Stable node id inside the package.</summary>
[Key(0)]
public string NodeId { get; set; } = string.Empty;