CultCache: a record whose payload carries slots past its reader's, at any depth, is held read-only

The guard formatter counts each int-keyed object's slots into a thread-bound scope opened around the one payload decode;
ToStoredDocument turns the finding into CultStoredDocument.UnreadSlots (explained only for depth-0 slots the catalog comparison
reports ignored); HeldOwned refuses an unexplained mark whatever is declared; RefuseUndeclared throws the one refusal with
UnreadSlots; CultCache.IsWritable asks the same predicate. Vectors: extra-slot-unit-arm, extra-slot-store.cc.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-10 14:35:10 +00:00 • committed by Libby
commit c55d34fb32
14 changed files with 642 additions and 30 deletions

View file

@ -166,7 +166,7 @@ public static class CultDocumentMessagePackSerialization
private static (MessagePackSerializerOptions Options, IFormatterResolver[] Ahead) Compose(IFormatterResolver[] consumerResolvers)
{
// The guard goes first and wraps whatever formatter the rest of the composite would hand out, so a consumer
// The guard goes first and wraps whatever formatter the rest of the composite would hand out (a union, or a concrete int-keyed object for its slot count), so a consumer
// resolver still encodes an arm while the key check runs.
var ahead = consumerResolvers.Append(CultDocumentResolver.Instance).Append(CultMathResolver.Instance).Append(CultMathExprResolver.Instance).ToArray();
var inner = CompositeResolver.Create(ahead.Append(StandardResolver.Instance).ToArray());
@ -214,6 +214,19 @@ public static class CultDocumentMessagePackSerialization
?? throw new InvalidOperationException($"MessagePack returned null for Cult document type {type.FullName}.");
}
// The same decode, with the slots it read past noted (CultSlotScope). Opened around the one decode and after the depth check,
// so a payload past the nesting limit is refused, never marked.
internal static CultDecoded DeserializeMarked(Type type, byte[] payload, CultDocumentRegistry registry)
{
if (registry == null) throw new ArgumentNullException(nameof(registry));
registry.GetRequired(type);
CultPayloadDepth.Check(payload, type, PayloadDirection.Read);
using var scope = CultSlotScope.Open();
var document = MessagePackSerializer.Deserialize(type, payload, OptionsForDocument(type))
?? throw new InvalidOperationException($"MessagePack returned null for Cult document type {type.FullName}.");
return new CultDecoded(document, scope.Finding());
}
/// <summary>
/// Replaces slots of a serialized document payload (a MessagePack array indexed by slot) with already-encoded member
/// values, leaving every other slot byte for byte as it was. A slot past the end extends the array with nil.
@ -823,4 +836,7 @@ public class SingleFileMessagePackBackingStore : SingleFileBackingStore
{
return CultDocumentMessagePackSerialization.DeserializeUntyped(documentType, payload, Registry);
}
internal override CultDecoded DeserializeMarked(Type documentType, byte[] payload) =>
CultDocumentMessagePackSerialization.DeserializeMarked(documentType, payload, Registry);
}

View file

@ -0,0 +1,47 @@
using System;
using GameCult.Caching;
namespace GameCult.Caching.MessagePack;
/// <summary>
/// The marks one payload decode noted: the guard's slot formatter reports every object whose array held more slots than its type
/// declares, with the nesting depth it sat at, and DeserializeMarked reads the finding out. Thread-bound and open only around the one
/// decode, so a decode outside it (a CultMesh read, a codec) notes nothing.
/// </summary>
internal sealed class CultSlotScope : IDisposable
{
[ThreadStatic] private static CultSlotScope? current;
private readonly CultSlotScope? previous;
private string? typeName;
private int slotCount;
private int declaredCount;
private int occurrences;
private bool allAtDepthZero = true;
private CultSlotScope() => previous = current;
internal static CultSlotScope? Current => current;
internal static CultSlotScope Open() => current = new CultSlotScope();
// 0 for the document's own object; each object nested inside it adds one (a union adds none, its arm is the object).
internal int Depth { get; set; }
internal void Note(string name, int slots, int declared)
{
if (occurrences++ == 0)
{
typeName = name;
slotCount = slots;
declaredCount = declared;
}
if (Depth > 0) allAtDepthZero = false;
}
internal CultUnreadSlots? Finding() =>
occurrences == 0 ? null : new CultUnreadSlots(typeName!, slotCount, declaredCount, occurrences, allAtDepthZero, explained: false);
public void Dispose() => current = previous;
}

View file

@ -8,7 +8,7 @@ using MessagePack.Formatters;
namespace GameCult.Caching.MessagePack;
/// <summary>
/// The one place an unknown union arm or an unnamed subtype is decided. A union is an abstract class or interface carrying
/// The one sensor of an unknown union arm, an unnamed subtype and a slot past the reader's declared slots. A union is an abstract class or interface carrying
/// its own [Union] attributes (never inherited: a union whose arms are also a union has its own key set). MessagePack-CSharp
/// still encodes the [key, armSlots] shape; this wraps its formatter so that a key the union does not declare is refused on
/// read, and a value whose runtime type is not a declared arm is refused on write, where MessagePack alone yields null and nil.
@ -18,7 +18,58 @@ internal sealed class CultUnionGuard(IFormatterResolver inner) : IFormatterResol
public IMessagePackFormatter<T>? GetFormatter<T>()
{
var arms = typeof(T).GetCustomAttributes<UnionAttribute>(inherit: false).ToArray();
return arms.Length == 0 || inner.GetFormatter<T>() is not { } formatter ? null : new Formatter<T>(formatter, arms);
if (arms.Length == 0)
return DeclaredSlots(typeof(T)) is { } declared && inner.GetFormatter<T>() is { } objectFormatter
? new SlotFormatter<T>(objectFormatter, declared)
: null;
return inner.GetFormatter<T>() is not { } formatter ? null : new Formatter<T>(formatter, arms);
}
// The slots a concrete int-keyed [MessagePackObject] type declares (highest [Key] plus one), by MessagePack's member rule: public
// instance properties and fields, base keys included, [IgnoreMember] excluded. Null for any other type, which the guard leaves alone.
private static int? DeclaredSlots(Type type)
{
if (type.IsAbstract || type.IsInterface || type.IsGenericTypeDefinition) return null;
if (type.GetCustomAttribute<MessagePackObjectAttribute>(inherit: true) is not { KeyAsPropertyName: false }) return null;
var highest = -1;
const BindingFlags members = BindingFlags.Public | BindingFlags.Instance;
foreach (var member in type.GetFields(members).Cast<MemberInfo>().Concat(type.GetProperties(members)))
{
if (member.GetCustomAttribute<IgnoreMemberAttribute>(inherit: true) != null) continue;
if (member.GetCustomAttribute<KeyAttribute>(inherit: true)?.IntKey is { } key) highest = Math.Max(highest, key);
}
return highest + 1;
}
// Counts a concrete object's array header against its declared slots and notes the excess into the open CultSlotScope, then lets the
// inner formatter read it unchanged: no byte scan, no second decode. With no scope open it is a depth-free pass-through.
private sealed class SlotFormatter<T>(IMessagePackFormatter<T> inner, int declared) : IMessagePackFormatter<T>
{
public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options) =>
inner.Serialize(ref writer, value, options);
public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
var scope = CultSlotScope.Current;
if (scope == null) return inner.Deserialize(ref reader, options);
var peek = reader.CreatePeekReader();
if (!peek.TryReadNil() && peek.NextMessagePackType == MessagePackType.Array)
{
var count = peek.ReadArrayHeader();
if (count > declared) scope.Note(typeof(T).Name, count, declared);
}
scope.Depth++;
try
{
return inner.Deserialize(ref reader, options);
}
finally
{
scope.Depth--;
}
}
}
private sealed class Formatter<T>(IMessagePackFormatter<T> inner, UnionAttribute[] arms) : IMessagePackFormatter<T>

View file

@ -636,7 +636,7 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
record,
VersionOf(metadata.Payload),
catalog,
(type, payload) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, payload, Registry),
(type, payload) => CultDocumentMessagePackSerialization.DeserializeMarked(type, payload, Registry),
out report);
// The manifest is this store's record of what is on disk: the stored id and the version a commit condition compares with.
stored.StoredSchemaId = metadata.SchemaId;