Make MessagePack [Key] the slot authority and pin generic resolvers

.cc is MessagePack-based, so the core no longer pretends to be
serializer-independent. GameCult.Caching references
MessagePack.Annotations 3.1.7 and reads KeyAttribute and
IgnoreMemberAttribute by type instead of matching their names. The
benchmark's own MessagePack.Annotations reference is dropped; it arrives
through GameCult.Caching.

A generic document's options come from its generic definition's
assembly: Doc<X> uses Doc's declared resolvers, never X's.
GenericDocumentUsesItsOwnAssemblyResolvers compiles GenericHolder<T>
into an assembly whose resolver writes Pair as [B, A] and checks the
payload uses it rather than Pair's own assembly resolver.

Contracts: schema-compatibility states the slot rule and its
rejections; store-composition states the generic resolver rule.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-13 22:06:17 +02:00
commit 30bf7fd267
6 changed files with 82 additions and 24 deletions

View file

@ -8,6 +8,5 @@
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\GameCult.Caching\GameCult.Caching.csproj" />
<PackageReference Include="MessagePack.Annotations" Version="3.1.7" />
</ItemGroup>
</Project>

View file

@ -26,6 +26,17 @@ The canonical fixtures currently exercised in C# are:
See `GameCult.Caching.Tests/BackingStoreTests.cs` for the canonical fixture
documents and the expected receipts.
## Slots
A member's slot is its MessagePack `[Key(n)]` integer. MessagePack's `[Key]` and
`[IgnoreMember]` are the single slot authority, so `GameCult.Caching` depends on
`MessagePack.Annotations`. The registry and the generator (diagnostic GCC001)
refuse, with the same message: a persisted member without `[Key]`, a string
`[Key]`, two members sharing a slot (including `new`-hidden members), a hidden
persisted member, an override whose `[Key]` or `[IgnoreMember]` differs from its
base declaration's (MessagePack reads the base declaration), and a persisted
member without a public or internal setter.
## Which schema a record carries
A record is written under the schema of its runtime type. Writing a derived

View file

@ -216,6 +216,9 @@ another runtime need not obey the `storedAt` rule.
generated and reflective serializers resolve options from the document's
assembly. There is no mutable static, no registration call, and no load-order
rule.
- A generic document's options come from the generic definition's assembly:
`Doc<X>` uses the resolvers `Doc`'s assembly declares, never `X`'s. A formatter
for `X` that `Doc<X>` needs is declared in `Doc`'s assembly.
- An assembly that declares nothing, and the store envelope, use the base
options.
- Deserialization runs under untrusted-data security. `CultRecordRef<T>` is a

View file

@ -1021,32 +1021,13 @@ namespace GameCult.Caching
private static string HiddenMemberMessage(string documentTypeName, string first, string second) =>
$"Cult document {documentTypeName} member {first} hides persisted member {second}; persisted member names must be unique.";
private static bool IsIgnored(MemberInfo member)
{
return member.GetCustomAttributes().Any(attribute =>
{
var name = attribute.GetType().FullName;
return name == "MessagePack.IgnoreMemberAttribute";
});
}
private static bool IsIgnored(MemberInfo member) =>
member.GetCustomAttribute<global::MessagePack.IgnoreMemberAttribute>() != null;
private static object? GetKeyValue(MemberInfo member)
{
foreach (var attribute in member.GetCustomAttributes())
{
var name = attribute.GetType().FullName;
if (name == "MessagePack.KeyAttribute")
{
if (attribute.GetType().GetProperty("IntKey")?.GetValue(attribute) is int intKey)
{
return intKey;
}
return attribute.GetType().GetProperty("StringKey")?.GetValue(attribute) as string;
}
}
return null;
var key = member.GetCustomAttribute<global::MessagePack.KeyAttribute>();
return key?.IntKey is int slot ? slot : key?.StringKey;
}
private static string Sha256(string input)

View file

@ -5,6 +5,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MessagePack.Annotations" Version="3.1.7" />
<PackageReference Include="R3" Version="1.3.0" />
<PackageReference Include="ConcurrentHashSet " Version="1.3.0" />
<InternalsVisibleTo Include="GameCult.Caching.Tests" />

View file

@ -2,10 +2,14 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using NUnit.Framework;
namespace GameCult.Caching.Tests
@ -105,6 +109,65 @@ namespace GameCult.Caching.Tests
Assert.That(CultDocumentMessagePackSerialization.OptionsFor(typeof(Pair).Assembly).Resolver.GetFormatter<Pair>(), Is.Not.Null);
}
// GenericHolder<Pair> lives in an assembly that declares a resolver writing Pair as [B, A]; Pair's own assembly writes [A, B].
[Test]
public void GenericDocumentUsesItsOwnAssemblyResolvers()
{
const string source = @"
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using GameCult.Caching.Tests;
using MessagePack;
using MessagePack.Formatters;
[assembly: CultCacheFormatterResolver(typeof(ReversedPairResolver))]
[CultDocument(""tests.generic_holder"", ""tests.generic_holder.v1"")]
[MessagePackObject]
public sealed class GenericHolder<T> { [Key(0)] public T Value; }
public sealed class ReversedPairResolver : IFormatterResolver
{
public static readonly IFormatterResolver Instance = new ReversedPairResolver();
public IMessagePackFormatter<T> GetFormatter<T>() => typeof(T) == typeof(Pair) ? (IMessagePackFormatter<T>)(object)new ReversedPairFormatter() : null;
}
public sealed class ReversedPairFormatter : IMessagePackFormatter<Pair>
{
public void Serialize(ref MessagePackWriter writer, Pair value, MessagePackSerializerOptions options) { writer.WriteArrayHeader(2); writer.Write(value.B); writer.Write(value.A); }
public Pair Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { reader.ReadArrayHeader(); var b = reader.ReadSingle(); return new Pair { A = reader.ReadSingle(), B = b }; }
}";
var references = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
.Split(Path.PathSeparator)
.Append(typeof(CultDocumentAttribute).Assembly.Location)
.Append(typeof(CultDocumentMessagePackSerialization).Assembly.Location)
.Append(typeof(KeyAttribute).Assembly.Location)
.Append(typeof(MessagePackSerializer).Assembly.Location)
.Append(typeof(Pair).Assembly.Location)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(path => MetadataReference.CreateFromFile(path));
var compilation = CSharpCompilation.Create(
"GenericHolders_" + Guid.NewGuid().ToString("N"),
new[] { CSharpSyntaxTree.ParseText(source) },
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using var stream = new MemoryStream();
var emitted = compilation.Emit(stream);
Assert.That(emitted.Diagnostics.Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error).Select(diagnostic => diagnostic.ToString()), Is.Empty);
var assembly = Assembly.Load(stream.ToArray());
var type = assembly.GetType("GenericHolder`1")!.MakeGenericType(typeof(Pair));
var registry = CultDocumentRegistry.ForTypes(new[] { type });
var holder = Activator.CreateInstance(type)!;
type.GetField("Value")!.SetValue(holder, new Pair { A = 1.5f, B = -2f });
var payload = CultDocumentMessagePackSerialization.SerializeUntyped(holder, type, registry);
Assert.That(type.Assembly, Is.SameAs(assembly));
var reader = new MessagePackReader(payload);
Assert.That(reader.ReadArrayHeader(), Is.EqualTo(1));
Assert.That(reader.ReadArrayHeader(), Is.EqualTo(2));
Assert.That(reader.ReadSingle(), Is.EqualTo(-2f), "Pair's own assembly resolver was used instead of the document's");
Assert.That(reader.ReadSingle(), Is.EqualTo(1.5f));
var decoded = CultDocumentMessagePackSerialization.DeserializeUntyped(type, payload, registry);
Assert.That(type.GetField("Value")!.GetValue(decoded), Is.EqualTo(new Pair { A = 1.5f, B = -2f }));
}
[CultDocument("tests.pair_holder", "tests.pair_holder.v1")]
[MessagePackObject]
public sealed class PairHolder