Add geometry serialization and SoA foundations
This commit is contained in:
parent
c83ce2e7e6
commit
9698805588
6 changed files with 321 additions and 23 deletions
|
|
@ -92,6 +92,25 @@ a broader stage gate.
|
|||
geometry store. Execution therefore uses v2 plus retained test witnesses,
|
||||
with no live v1 runtime migrator.
|
||||
|
||||
### Stage 1 receipts
|
||||
|
||||
- CultCache MessagePack now resolves external member values through a
|
||||
document-owner assembly declaration. Resolver precedence is core CultCache,
|
||||
owner-declared resolvers, then MessagePack standard fallback; the options are
|
||||
cached per owner assembly and generated document codecs use that same path.
|
||||
CultCache does not reference Geometry or CultMath.
|
||||
- CultCache SoA discovery now admits direct reference-free value types as one
|
||||
exact typed column. It rejects managed-reference and byref-like values and
|
||||
does not synthesize component columns from nested struct fields.
|
||||
- `dotnet test tests/GameCult.Caching.Tests/GameCult.Caching.Tests.csproj
|
||||
--no-restore --filter
|
||||
"FullyQualifiedName~DocumentAssemblyResolverTests|FullyQualifiedName~SoaValueColumnTests"
|
||||
--verbosity minimal -m:1 -nodeReuse:false` passed 4/4 after a full rebuild.
|
||||
- The initial SoA reflection probe used `Type.IsFunctionPointer`, which is not
|
||||
available on the library's `netstandard2.1` target. It was removed rather
|
||||
than papered over; structural managed-reference inspection is the owning
|
||||
eligibility rule.
|
||||
|
||||
## Decisions and Deviations
|
||||
|
||||
- Licensing: no relicensing is assumed. Moved CultMath files retain MPL-2.0
|
||||
|
|
@ -108,8 +127,8 @@ a broader stage gate.
|
|||
|
||||
## Next Actions
|
||||
|
||||
1. Implement the owner-assembly MessagePack resolver seam and its isolation tests.
|
||||
2. Establish the Geometry -> CultMath dependency and exact vector formatter
|
||||
fixtures.
|
||||
3. Cut the scalar-only SoA whitelist so intact unmanaged vectors can exist as
|
||||
columns before v2 document fields adopt them.
|
||||
1. Establish the Geometry -> CultMath dependency through an explicit candidate
|
||||
package/local-feed workflow rather than an implicit sibling checkout.
|
||||
2. Add Geometry-owned exact vector/quaternion formatters and byte fixtures.
|
||||
3. Prove actual `Column<float2>` and `Column<float3>` access from Geometry, then
|
||||
inspect the NuGet and UPM artifacts before adopting vectors in v2 schemas.
|
||||
|
|
|
|||
|
|
@ -274,7 +274,7 @@ public sealed class CultDocumentMessagePackGenerator : IIncrementalGenerator
|
|||
builder.AppendLine($" private static byte[] {document.PayloadSerializerMethodName}(object document)");
|
||||
builder.AppendLine(" {");
|
||||
builder.AppendLine($" var typed = ({document.DocumentTypeName})document;");
|
||||
builder.AppendLine(" var options = global::GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.Options;");
|
||||
builder.AppendLine($" var options = global::GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.OptionsFor(typeof({document.DocumentTypeName}));");
|
||||
builder.AppendLine(" var buffer = new global::System.Buffers.ArrayBufferWriter<byte>();");
|
||||
builder.AppendLine(" var writer = new global::MessagePack.MessagePackWriter(buffer);");
|
||||
builder.AppendLine($" writer.WriteArrayHeader({document.Members.Length});");
|
||||
|
|
@ -292,7 +292,7 @@ public sealed class CultDocumentMessagePackGenerator : IIncrementalGenerator
|
|||
{
|
||||
builder.AppendLine($" private static object {document.PayloadDeserializerMethodName}(byte[] payload)");
|
||||
builder.AppendLine(" {");
|
||||
builder.AppendLine(" var options = global::GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.Options;");
|
||||
builder.AppendLine($" var options = global::GameCult.Caching.MessagePack.CultDocumentMessagePackSerialization.OptionsFor(typeof({document.DocumentTypeName}));");
|
||||
builder.AppendLine(" var reader = new global::MessagePack.MessagePackReader(payload);");
|
||||
builder.AppendLine(" var count = reader.ReadArrayHeader();");
|
||||
builder.AppendLine($" var value = new {document.DocumentTypeName}();");
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
|
|
@ -7,6 +10,27 @@ using MessagePack.Resolvers;
|
|||
|
||||
namespace GameCult.Caching.MessagePack;
|
||||
|
||||
/// <summary>
|
||||
/// Declares MessagePack resolvers owned by the assembly that defines a Cult document.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
|
||||
public sealed class CultDocumentMessagePackResolversAttribute : Attribute
|
||||
{
|
||||
/// <summary>Creates a resolver declaration in precedence order.</summary>
|
||||
public CultDocumentMessagePackResolversAttribute(params Type[] resolverTypes)
|
||||
{
|
||||
if (resolverTypes == null || resolverTypes.Length == 0)
|
||||
{
|
||||
throw new ArgumentException("At least one resolver type is required.", nameof(resolverTypes));
|
||||
}
|
||||
|
||||
ResolverTypes = resolverTypes;
|
||||
}
|
||||
|
||||
/// <summary>Gets the declared resolver types in precedence order.</summary>
|
||||
public Type[] ResolverTypes { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MessagePack resolver for CultCache-specific value types.
|
||||
/// </summary>
|
||||
|
|
@ -43,6 +67,7 @@ public static class CultDocumentMessagePackSerialization
|
|||
private const int SchemaCatalogEntryFieldCount = 7;
|
||||
private const int SchemaCatalogMemberFieldCount = 8;
|
||||
private const int StoreSnapshotFieldCount = 3;
|
||||
private static readonly ConcurrentDictionary<Assembly, MessagePackSerializerOptions> DocumentAssemblyOptions = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shared MessagePack serializer options for CultCache payloads.
|
||||
|
|
@ -54,12 +79,29 @@ public static class CultDocumentMessagePackSerialization
|
|||
StandardResolver.Instance))
|
||||
.WithSecurity(MessagePackSecurity.UntrustedData);
|
||||
|
||||
/// <summary>
|
||||
/// Gets serializer options for documents owned by an assembly. CultCache formatters
|
||||
/// take precedence, followed by assembly-declared resolvers and the standard resolver.
|
||||
/// </summary>
|
||||
public static MessagePackSerializerOptions OptionsFor(Assembly documentAssembly)
|
||||
{
|
||||
if (documentAssembly == null) throw new ArgumentNullException(nameof(documentAssembly));
|
||||
return DocumentAssemblyOptions.GetOrAdd(documentAssembly, CreateDocumentAssemblyOptions);
|
||||
}
|
||||
|
||||
/// <summary>Gets serializer options for the assembly that owns a document type.</summary>
|
||||
public static MessagePackSerializerOptions OptionsFor(Type documentType)
|
||||
{
|
||||
if (documentType == null) throw new ArgumentNullException(nameof(documentType));
|
||||
return OptionsFor(documentType.Assembly);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serializes a typed value with the CultCache MessagePack options.
|
||||
/// </summary>
|
||||
public static byte[] Serialize<T>(T value)
|
||||
{
|
||||
return MessagePackSerializer.Serialize(value, Options);
|
||||
return MessagePackSerializer.Serialize(value, OptionsFor(typeof(T)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -67,7 +109,7 @@ public static class CultDocumentMessagePackSerialization
|
|||
/// </summary>
|
||||
public static T Deserialize<T>(byte[] payload)
|
||||
{
|
||||
return MessagePackSerializer.Deserialize<T>(payload, Options);
|
||||
return MessagePackSerializer.Deserialize<T>(payload, OptionsFor(typeof(T)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -84,7 +126,7 @@ public static class CultDocumentMessagePackSerialization
|
|||
}
|
||||
}
|
||||
|
||||
return MessagePackSerializer.Serialize(type, value, Options);
|
||||
return MessagePackSerializer.Serialize(type, value, OptionsFor(type));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -98,10 +140,43 @@ public static class CultDocumentMessagePackSerialization
|
|||
return descriptor.GeneratedPayloadDeserializer(payload);
|
||||
}
|
||||
|
||||
return MessagePackSerializer.Deserialize(type, payload, Options)
|
||||
return MessagePackSerializer.Deserialize(type, payload, OptionsFor(type))
|
||||
?? throw new InvalidOperationException($"MessagePack returned null for Cult document type {type.FullName}.");
|
||||
}
|
||||
|
||||
private static MessagePackSerializerOptions CreateDocumentAssemblyOptions(Assembly documentAssembly)
|
||||
{
|
||||
var ownerResolvers = documentAssembly
|
||||
.GetCustomAttributes<CultDocumentMessagePackResolversAttribute>()
|
||||
.SelectMany(attribute => attribute.ResolverTypes)
|
||||
.Select(CreateOwnerResolver)
|
||||
.ToArray();
|
||||
|
||||
if (ownerResolvers.Length == 0)
|
||||
{
|
||||
return Options;
|
||||
}
|
||||
|
||||
var resolvers = new IFormatterResolver[ownerResolvers.Length + 2];
|
||||
resolvers[0] = CultDocumentResolver.Instance;
|
||||
Array.Copy(ownerResolvers, 0, resolvers, 1, ownerResolvers.Length);
|
||||
resolvers[resolvers.Length - 1] = StandardResolver.Instance;
|
||||
return Options.WithResolver(CompositeResolver.Create(resolvers));
|
||||
}
|
||||
|
||||
private static IFormatterResolver CreateOwnerResolver(Type resolverType)
|
||||
{
|
||||
if (resolverType == null || !typeof(IFormatterResolver).IsAssignableFrom(resolverType))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Cult document MessagePack resolver '{resolverType?.FullName ?? "<null>"}' must implement {typeof(IFormatterResolver).FullName}.");
|
||||
}
|
||||
|
||||
return Activator.CreateInstance(resolverType) as IFormatterResolver
|
||||
?? throw new InvalidOperationException(
|
||||
$"Cult document MessagePack resolver '{resolverType.FullName}' must have a public parameterless constructor.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serializes one persisted store record.
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -398,18 +398,30 @@ namespace GameCult.Caching
|
|||
|
||||
private static bool IsColumnType(Type type)
|
||||
{
|
||||
return type.IsEnum ||
|
||||
type == typeof(byte) ||
|
||||
type == typeof(sbyte) ||
|
||||
type == typeof(short) ||
|
||||
type == typeof(ushort) ||
|
||||
type == typeof(int) ||
|
||||
type == typeof(uint) ||
|
||||
type == typeof(long) ||
|
||||
type == typeof(ulong) ||
|
||||
type == typeof(float) ||
|
||||
type == typeof(double) ||
|
||||
type == typeof(bool);
|
||||
return type.IsValueType &&
|
||||
!type.IsByRefLike &&
|
||||
!ContainsManagedReferences(type, new HashSet<Type>());
|
||||
}
|
||||
|
||||
private static bool ContainsManagedReferences(Type type, HashSet<Type> visited)
|
||||
{
|
||||
if (type.IsPointer)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!type.IsValueType)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type.IsPrimitive || type.IsEnum || !visited.Add(type))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
||||
return type.GetFields(flags).Any(field => ContainsManagedReferences(field.FieldType, visited));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,88 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
using NUnit.Framework;
|
||||
|
||||
[assembly: CultDocumentMessagePackResolvers(typeof(GameCult.Caching.Tests.FirstOwnerResolver), typeof(GameCult.Caching.Tests.SecondOwnerResolver))]
|
||||
|
||||
namespace GameCult.Caching.Tests;
|
||||
|
||||
public sealed class DocumentAssemblyResolverTests
|
||||
{
|
||||
[Test]
|
||||
public void OptionsFor_CachesOptionsByDocumentAssembly()
|
||||
{
|
||||
var first = CultDocumentMessagePackSerialization.OptionsFor(typeof(ResolverDocument));
|
||||
var second = CultDocumentMessagePackSerialization.OptionsFor(typeof(ResolverDocument).Assembly);
|
||||
|
||||
Assert.That(second, Is.SameAs(first));
|
||||
Assert.That(first, Is.Not.SameAs(CultDocumentMessagePackSerialization.Options));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GeneratedDocumentSerialization_UsesOwnerResolversInDeclaredOrder()
|
||||
{
|
||||
FirstOwnerResolver.SerializeCount = 0;
|
||||
SecondOwnerResolver.FormatterRequestCount = 0;
|
||||
var original = new ResolverDocument { Name = "probe", Value = new ExternalValue(41) };
|
||||
|
||||
var payload = CultDocumentMessagePackSerialization.SerializeUntyped(original, typeof(ResolverDocument));
|
||||
var decoded = (ResolverDocument)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(ResolverDocument), payload);
|
||||
|
||||
Assert.That(decoded.Name, Is.EqualTo("probe"));
|
||||
Assert.That(decoded.Value.Number, Is.EqualTo(42));
|
||||
Assert.That(FirstOwnerResolver.SerializeCount, Is.EqualTo(1));
|
||||
Assert.That(SecondOwnerResolver.FormatterRequestCount, Is.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
[CultDocument("tests.assembly_resolver", "tests.assembly_resolver.v1")]
|
||||
public sealed class ResolverDocument
|
||||
{
|
||||
[Key(0)] public string Name { get; set; } = string.Empty;
|
||||
[Key(1)] public ExternalValue Value { get; set; }
|
||||
}
|
||||
|
||||
public readonly struct ExternalValue
|
||||
{
|
||||
public ExternalValue(int number) => Number = number;
|
||||
public int Number { get; }
|
||||
}
|
||||
|
||||
public sealed class FirstOwnerResolver : IFormatterResolver
|
||||
{
|
||||
public static int SerializeCount;
|
||||
|
||||
public IMessagePackFormatter<T>? GetFormatter<T>()
|
||||
{
|
||||
return typeof(T) == typeof(ExternalValue)
|
||||
? (IMessagePackFormatter<T>)(object)new FirstExternalValueFormatter()
|
||||
: null;
|
||||
}
|
||||
|
||||
public sealed class FirstExternalValueFormatter : IMessagePackFormatter<ExternalValue>
|
||||
{
|
||||
public void Serialize(ref MessagePackWriter writer, ExternalValue value, MessagePackSerializerOptions options)
|
||||
{
|
||||
SerializeCount++;
|
||||
writer.Write(value.Number + 1);
|
||||
}
|
||||
|
||||
public ExternalValue Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
|
||||
=> new(reader.ReadInt32());
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SecondOwnerResolver : IFormatterResolver
|
||||
{
|
||||
public static int FormatterRequestCount;
|
||||
|
||||
public IMessagePackFormatter<T>? GetFormatter<T>()
|
||||
{
|
||||
if (typeof(T) == typeof(ExternalValue)) FormatterRequestCount++;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
104
tests/GameCult.Caching.Tests/SoaValueColumnTests.cs
Normal file
104
tests/GameCult.Caching.Tests/SoaValueColumnTests.cs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
#nullable enable
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace GameCult.Caching.Tests
|
||||
{
|
||||
public sealed class SoaValueColumnTests
|
||||
{
|
||||
[Test]
|
||||
public async Task Soa_Preserves_Unmanaged_Value_Members_As_Intact_Columns()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var first = new CultRecordHandle<VectorDocument>(new CultRecordKey("vector:first"));
|
||||
var second = new CultRecordHandle<VectorDocument>(new CultRecordKey("vector:second"));
|
||||
|
||||
await cache.UpsertAsync(new VectorDocument
|
||||
{
|
||||
Name = "first",
|
||||
Position = new TestFloat3(1, 2, 3),
|
||||
Health = 10,
|
||||
}, first);
|
||||
await cache.UpsertAsync(new VectorDocument
|
||||
{
|
||||
Name = "second",
|
||||
Position = new TestFloat3(4, 5, 6),
|
||||
Health = 20,
|
||||
}, second);
|
||||
await cache.UpsertAsync(new VectorDocument
|
||||
{
|
||||
Name = "first-updated",
|
||||
Position = new TestFloat3(7, 8, 9),
|
||||
Health = 30,
|
||||
}, first);
|
||||
|
||||
var table = cache.Soa<VectorDocument>();
|
||||
|
||||
Assert.That(table.Column<TestFloat3>(nameof(VectorDocument.Position)).Span.ToArray(), Is.EqualTo(new[]
|
||||
{
|
||||
new TestFloat3(7, 8, 9),
|
||||
new TestFloat3(4, 5, 6),
|
||||
}));
|
||||
Assert.That(table.Column<int>(nameof(VectorDocument.Health)).Span.ToArray(), Is.EqualTo(new[] { 30, 20 }));
|
||||
Assert.That(() => table.Column<float>("Position.x"), Throws.TypeOf<KeyNotFoundException>());
|
||||
Assert.That(() => table.Column<float>("x"), Throws.TypeOf<KeyNotFoundException>());
|
||||
|
||||
Assert.That(cache.Remove(first.Key), Is.True);
|
||||
var afterRemoval = cache.Soa<VectorDocument>();
|
||||
Assert.That(afterRemoval.Keys.Select(key => key.Value).ToArray(), Is.EqualTo(new[] { "vector:second" }));
|
||||
Assert.That(
|
||||
afterRemoval.Column<TestFloat3>(nameof(VectorDocument.Position)).Span.ToArray(),
|
||||
Is.EqualTo(new[] { new TestFloat3(4, 5, 6) }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Soa_Rejects_Value_Members_Containing_Managed_References()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
await cache.UpsertAsync(new VectorDocument
|
||||
{
|
||||
Name = "managed",
|
||||
Position = new TestFloat3(1, 2, 3),
|
||||
ManagedValue = new ManagedValue(42, "not a column"),
|
||||
});
|
||||
|
||||
var table = cache.Soa<VectorDocument>();
|
||||
|
||||
Assert.That(
|
||||
() => table.Column<int>(nameof(VectorDocument.ManagedValue)),
|
||||
Throws.TypeOf<KeyNotFoundException>());
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public readonly record struct TestFloat3(
|
||||
[property: Key(0)] float x,
|
||||
[property: Key(1)] float y,
|
||||
[property: Key(2)] float z);
|
||||
|
||||
[MessagePackObject]
|
||||
public readonly record struct ManagedValue(
|
||||
[property: Key(0)] int Code,
|
||||
[property: Key(1)] string Label);
|
||||
|
||||
[CultDocument("tests.soa_value_column", "tests.soa_value_column.v1")]
|
||||
internal sealed class VectorDocument
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string Name = string.Empty;
|
||||
|
||||
[Key(1)]
|
||||
public TestFloat3 Position;
|
||||
|
||||
[Key(2)]
|
||||
public int Health;
|
||||
|
||||
[Key(3)]
|
||||
public ManagedValue ManagedValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue