From 5157c647afc3c5a048d222ce582c913feb35015c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 15 Oct 2026 02:53:28 +0200 Subject: [PATCH] Codec: confirm MessagePack writes every id-path type the way the walk reads it CultElementIds is the walk's model of a type; MessagePack's StandardResolver owns how a type is written, and nothing checked that the two agree. ResolverClaim now asks, for each id-path type, whether StandardResolver's formatter is the object or union resolver's (a type read by key) or a collection resolver's (a collection), and refuses the document at first encode or decode when it is not, naming the type. A keyed type that enumerates objects goes on the path so a keyed List subclass is caught. A type MessagePack cannot build a formatter for, and a resolver ahead that throws, are typed refusals; the AllowPrivate catch is pinned (s4: keyed-enumerable-misclassified, allowprivate-catch-unpinned). Co-Authored-By: Claude Sonnet 5.5 --- .../CultDocumentMessagePackSerialization.cs | 55 ++++++++- src/GameCult.Caching/CultElementIds.cs | 16 +++ .../UnionArmGuardTests.cs | 107 ++++++++++++++++++ 3 files changed, 176 insertions(+), 2 deletions(-) diff --git a/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs b/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs index ec0326fb..8faab41e 100644 --- a/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs +++ b/src/GameCult.Caching.MessagePack/CultDocumentMessagePackSerialization.cs @@ -8,6 +8,7 @@ using System.Reflection; using GameCult.Caching; using MessagePack; using MessagePack.Formatters; +using MessagePack.ImmutableCollection; using MessagePack.Resolvers; namespace GameCult.Caching.MessagePack; @@ -86,12 +87,36 @@ public static class CultDocumentMessagePackSerialization // composite stops there, so no later resolver is asked. StandardResolverAllowPrivate's formatter writes the same layout // plus non-public [Key] members, and registration refuses a non-public member on the way to an object list, so it // claims nothing either. - var standard = generic.Invoke(StandardResolver.Instance, null); + object? standard; + try + { + standard = generic.Invoke(StandardResolver.Instance, null); + } + catch (Exception exception) + { + return $"Cult document {documentType.Name}: MessagePack cannot build a formatter for {type.Name}, which is on the path to a list whose elements carry ids ({(exception.InnerException ?? exception).Message})."; + } + + if (!WrittenAsWalked(type, generic, standard)) + { + var owner = CultElementIds.WalksAsOwner(type); + return $"Cult document {documentType.Name}: MessagePack writes {type.Name} {(owner ? "as a collection" : "by its [Key] layout")}, but the element-id walk reads it {(owner ? "by its [Key] layout" : "as a collection")}, so element ids would be lost or invented. A [MessagePackObject] type that is also a collection (ICollection, IList, IDictionary) is written as a collection; make it one or the other."; + } + var allowPrivateAsked = false; object? allowPrivate = null; foreach (var resolver in ahead) { - var formatter = generic.Invoke(resolver, null); + object? formatter; + try + { + formatter = generic.Invoke(resolver, null); + } + catch (Exception exception) + { + return $"Cult document {documentType.Name}: formatter resolver {resolver.GetType().FullName} failed to build a formatter for {type.Name}, which is on the path to a list whose elements carry ids ({(exception.InnerException ?? exception).Message}); a resolver may not throw for such a type."; + } + if (formatter == null) continue; if (ReferenceEquals(formatter, standard)) @@ -118,6 +143,32 @@ public static class CultDocumentMessagePackSerialization return null; } + // The walk's kind for a type on the id path, checked against the resolver MessagePack actually delegates to. The public + // singletons hand out the same cached formatter instances StandardResolver does, so a reference match names the family. A + // type the walk reads by key must be written by the object or union resolver, and one it reads as a collection by a + // collection resolver; a keyed class that is also an ICollection is written as a collection and its [Key] layout dropped. + private static bool WrittenAsWalked(Type type, MethodInfo generic, object? standard) + { + if (standard == null) + return true; + var families = CultElementIds.WalksAsOwner(type) + ? new IFormatterResolver[] { DynamicUnionResolver.Instance, DynamicObjectResolver.Instance } + : new IFormatterResolver[] { DynamicGenericResolver.Instance, ImmutableCollectionResolver.Instance, BuiltinResolver.Instance }; + return families.Any(family => ReferenceEquals(Formatter(family, generic), standard)); + } + + private static object? Formatter(IFormatterResolver resolver, MethodInfo generic) + { + try + { + return generic.Invoke(resolver, null); + } + catch (Exception) + { + return null; + } + } + 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 diff --git a/src/GameCult.Caching/CultElementIds.cs b/src/GameCult.Caching/CultElementIds.cs index 34541f34..eb6fb815 100644 --- a/src/GameCult.Caching/CultElementIds.cs +++ b/src/GameCult.Caching/CultElementIds.cs @@ -113,6 +113,9 @@ namespace GameCult.Caching // and the walk reads public members only. public List<(Type Owner, MemberInfo? Member, Type Child, Type[] Through, bool Hidden)> Edges { get; } = new(); public List<(Type Owner, MemberInfo Member, Type Element, List Concrete, Type[] Through, bool Hidden)> Lists { get; } = new(); + + // Keyed types that also enumerate objects: the walk reads them by key, so the codec must confirm MessagePack does too. + public List Enumerating { get; } = new(); } private static readonly ConcurrentDictionary IdCapable = new(); @@ -134,6 +137,8 @@ namespace GameCult.Caching { if (!seen.Add(type)) return; + if (EnumeratesObjects(type)) + graph.Enumerating.Add(type); foreach (var (member, memberType) in KeyedMembers(type)) VisitMemberType(documentType, type, member, memberType, Array.Empty(), false, seen, survey, graph); foreach (var (member, memberType) in UnreadKeyedMembers(type)) @@ -229,6 +234,11 @@ namespace GameCult.Caching Add(concrete); } + // A keyed type the walk reads by key but whose enumeration holds objects is on the path: the codec asks whether + // MessagePack writes it by key too. + foreach (var type in graph.Enumerating) + Add(type); + foreach (var type in path) { survey.IdPath.Add(type); @@ -593,6 +603,12 @@ namespace GameCult.Caching } } + // True when the walk reads the type by its [Key] members: the codec compares this with how MessagePack writes it. + internal static bool WalksAsOwner(Type type) => Classify(Nullable.GetUnderlyingType(type) ?? type).Kind == Kind.Owner; + + private static bool EnumeratesObjects(Type type) => + (ElementTypeOf(type) ?? MapTypes(type)?.Value) is { } inner && Classify(inner).Kind != Kind.Leaf; + private static int? KeyOf(MemberInfo member) => member.GetCustomAttribute(true)?.IntKey; private static Type TypeOf(MemberInfo member) => member is FieldInfo field ? field.FieldType : ((PropertyInfo)member).PropertyType; diff --git a/tests/GameCult.Caching.Tests/UnionArmGuardTests.cs b/tests/GameCult.Caching.Tests/UnionArmGuardTests.cs index 7c98927b..3735239f 100644 --- a/tests/GameCult.Caching.Tests/UnionArmGuardTests.cs +++ b/tests/GameCult.Caching.Tests/UnionArmGuardTests.cs @@ -357,6 +357,111 @@ namespace GameCult.Caching.Tests Assert.That(Convert.ToHexString(plainBytes), Is.EqualTo(Convert.ToHexString(MessagePackSerializer.Serialize(plain, CultDocumentMessagePackSerialization.Options)))); } + // The walk reads a [MessagePackObject] type by its keys, but MessagePack writes one that is also an ICollection as a + // collection and drops the keys. The codec compares the two for every type on the id path and refuses the document. + [Test] + public void AKeyedTypeMessagePackWritesAsACollectionIsRefused() + { + var registry = CultDocumentRegistry.ForTypes(new[] { typeof(KCollDoc), typeof(KBagDoc) }); + Assert.That(CultElementIds.Inspect(typeof(KCollDoc)).IdPath, Does.Contain(typeof(KColl))); + + var coll = new KCollDoc { Id = "k1" }; + coll.Items.Add(new FbArm { Id = "00000000000c" }); + var thrown = Assert.Throws(() => CultDocumentMessagePackSerialization.SerializeUntyped(coll, typeof(KCollDoc), registry))!; + Assert.That(thrown.Message, Does.Contain(nameof(KColl)).And.Contain("as a collection")); + + var bag = new KBagDoc { Id = "b1", Bag = new KBagE { Items = { new FbArm { Id = "00000000000d" } } } }; + var bytes = CultDocumentMessagePackSerialization.SerializeUntyped(bag, typeof(KBagDoc), registry); + var back = (KBagDoc)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(KBagDoc), bytes, registry); + Assert.That(back.Bag.Items.Single().Id, Is.EqualTo("00000000000d")); + } + + // Every collection shape the walk reads is one MessagePack writes through a collection formatter, so none is refused. + [Test] + public void EveryCollectionShapeTheWalkReadsIsWrittenByACollectionFormatter() + { + foreach (var holder in new[] + { + typeof(G>), typeof(G), typeof(G), typeof(G>), typeof(G>), + typeof(G>), typeof(G>), typeof(G>), typeof(G>), + typeof(G>), typeof(G>), typeof(G>), + typeof(G>), typeof(G>), + typeof(G>), typeof(G>), typeof(G>>), + typeof(G>), typeof(G>), typeof(G>), + typeof(G>), typeof(G>), + typeof(G>), typeof(G>), + typeof(G>), typeof(G), typeof(G), typeof(G), + }) + { + if (holder != typeof(G)) + Assert.That(CultElementIds.Inspect(holder).IdPath, Is.Not.Empty, holder.Name); + Assert.DoesNotThrow(() => CultDocumentMessagePackSerialization.OptionsForDocument(holder), holder.ToString()); + } + } + + // A resolver that throws while asked about an id-path type is a typed refusal, whether it is the AllowPrivate formatter + // the claim check asks about (the claim stands) or a resolver ahead (it fails to build). + [Test] + public void AResolverThatThrowsIsATypedRefusal() + { + var first = Assert.Throws(() => CultDocumentMessagePackSerialization.OptionsForDocument(typeof(DkDoc)))!; + Assert.That(first.Message, Does.Contain(nameof(ListClaimResolver)).And.Contain(nameof(DkEl))); + var second = Assert.Throws(() => CultDocumentMessagePackSerialization.OptionsForDocument(typeof(DkDoc2)))!; + Assert.That(second.Message, Does.Contain(nameof(ListClaimResolver)).And.Contain(nameof(DkEl2)).And.Contain("failed to build")); + } + + [MessagePackObject] + public sealed class KColl : List + { + [Key(0)] public int N; + } + + [CultDocument("tests.kcoll_doc", "tests.kcoll_doc.v1")] + [MessagePackObject] + public sealed class KCollDoc + { + [Key(0)] [CultName] public string Id = string.Empty; + [Key(1)] public KColl Items = new(); + } + + [MessagePackObject] + public sealed class KBagE : IEnumerable + { + [Key(0)] public List Items = new(); + public IEnumerator GetEnumerator() { yield break; } + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + [CultDocument("tests.kbag_doc", "tests.kbag_doc.v1")] + [MessagePackObject] + public sealed class KBagDoc + { + [Key(0)] [CultName] public string Id = string.Empty; + [Key(1)] public KBagE Bag = new(); + } + + [MessagePackObject] public sealed class G { [Key(0)] public T? Value; } + [Union(0, typeof(GuArm))] public interface IGu { } + [MessagePackObject] public sealed class GuArm : IGu { [Key(0)] [CultElementId] public string Id = string.Empty; [Key(1)] public List Items = new(); } + [MessagePackObject] public struct GStruct { [Key(0)] public List Items; } + +#pragma warning disable CS0169, CS0414, CS0649 + [MessagePackObject] public sealed class DkEl { [Key(0)] [CultElementId] public string Id = string.Empty; [Key(1)] public int N; [Key(1)] private int shadow; } + [MessagePackObject] public sealed class DkEl2 { [Key(0)] [CultElementId] public string Id = string.Empty; [Key(1)] public int N; [Key(1)] private int shadow; } +#pragma warning restore CS0169, CS0414, CS0649 + [CultDocument("tests.dk_doc", "tests.dk_doc.v1")] + [MessagePackObject] + public sealed class DkDoc { [Key(0)] [CultName] public string Id = string.Empty; [Key(1)] public List Items = new(); } + [CultDocument("tests.dk_doc2", "tests.dk_doc2.v1")] + [MessagePackObject] + public sealed class DkDoc2 { [Key(0)] [CultName] public string Id = string.Empty; [Key(1)] public List Items = new(); } + + public sealed class DkFormatter : IMessagePackFormatter + { + public void Serialize(ref MessagePackWriter writer, DkEl value, MessagePackSerializerOptions options) => writer.Write(value.N); + public DkEl Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => new DkEl { N = reader.ReadInt32() }; + } + [MessagePackObject] public sealed class ApArm { @@ -457,6 +562,8 @@ namespace GameCult.Caching.Tests if (typeof(T) == typeof(List)) return (IMessagePackFormatter)(object)new ValuesFormatter(); if (typeof(T) == typeof(List)) return (IMessagePackFormatter)(object)new PointsFormatter(); if (typeof(T) == typeof(FbArm)) return global::MessagePack.Resolvers.StandardResolver.Instance.GetFormatter(); + if (typeof(T) == typeof(DkEl)) return (IMessagePackFormatter)(object)new DkFormatter(); + if (typeof(T) == typeof(DkEl2)) return global::MessagePack.Resolvers.StandardResolverAllowPrivate.Instance.GetFormatter(); if (typeof(T) == typeof(ApArm) || typeof(T) == typeof(ApDoc) || typeof(T) == typeof(List) || typeof(T) == typeof(ApPlainArm) || typeof(T) == typeof(ApPlainDoc) || typeof(T) == typeof(List)) return global::MessagePack.Resolvers.StandardResolverAllowPrivate.Instance.GetFormatter();