From b573c6ac2e9b0da62eacea4eb196393f86d065ce Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:21:19 +0100 Subject: [PATCH] CultNet: schema_catalog_request includeMembers; the subscription server answers cache types with their member rows Co-Authored-By: Claude Sonnet 5.5 --- .../cultnet/cultnet-distributed-database.md | 7 + ...cultnet.schema-catalog-request.schema.json | 1 + .../cultnet.schema-descriptor.schema.json | 27 +- ...cultnet.schema-catalog-request.schema.json | 1 + .../CultNetDatabaseSubscriptionServer.cs | 43 +++ .../CultNetSchemaMessages.cs | 39 +++ .../CultNetSchemaCatalogMembersTests.cs | 254 ++++++++++++++++++ 7 files changed, 371 insertions(+), 1 deletion(-) create mode 100644 tests/GameCult.Networking.Tests/CultNetSchemaCatalogMembersTests.cs diff --git a/contracts/cultnet/cultnet-distributed-database.md b/contracts/cultnet/cultnet-distributed-database.md index 0ed19837..e8f60559 100644 --- a/contracts/cultnet/cultnet-distributed-database.md +++ b/contracts/cultnet/cultnet-distributed-database.md @@ -154,6 +154,13 @@ A malformed put or delete is `message_invalid`, not a per-operation code: the pe - The C# writer sets every key of a `database_change_raw` message, nil where unset: a removed change carries `document` nil, an added or updated one `recordKey` and `schemaId` nil. The schema accepts those nils; an added or updated change still needs a document, and a removed one a `recordKey` and `schemaId`. +- A database or subscription server answers `schema_catalog_request` for each document type its cache registers: kind + `document_payload`, `contentHash` equal to the `schemaContentHash` that type's records carry, `schemaJson` left to + contract schemas and never filled with cache schema JSON. A request that sets `includeMembers` (optional, default false) + gets each descriptor's `members`, the rows every store catalog writes for the type (`slot`, `name`, `type`, + `isReference`, `isMany`, `targetSchemaName`, `isName`, `indexAlias`), in slot order; a peer that did not ask never sees the key. + A subscriber caches rows by `schemaId` plus `schemaContentHash`, and a record whose hash it has no rows for is decoded only after a + catalog request. Both fields are additive within `cultnet.schema_catalog_*.v0`; the C# subscription server serves them first. - Client-owned input documents may be predicted locally only inside explicit `CultNetClientAuthorityScope` declarations. - Predicted input state is not authoritative shared state. The shard log still diff --git a/contracts/cultnet/cultnet.schema-catalog-request.schema.json b/contracts/cultnet/cultnet.schema-catalog-request.schema.json index 5459129b..38fd7fcf 100644 --- a/contracts/cultnet/cultnet.schema-catalog-request.schema.json +++ b/contracts/cultnet/cultnet.schema-catalog-request.schema.json @@ -12,6 +12,7 @@ "schemaVersion": { "const": "cultnet.schema_catalog_request.v0" }, "messageId": { "type": "string", "minLength": 1 }, "includeSchemaJson": { "type": "boolean" }, + "includeMembers": { "type": "boolean" }, "schemaIds": { "type": "array", "items": { "type": "string", "minLength": 1 } diff --git a/contracts/cultnet/cultnet.schema-descriptor.schema.json b/contracts/cultnet/cultnet.schema-descriptor.schema.json index 77b6648c..4118e671 100644 --- a/contracts/cultnet/cultnet.schema-descriptor.schema.json +++ b/contracts/cultnet/cultnet.schema-descriptor.schema.json @@ -34,6 +34,31 @@ } }, "contentHash": { "type": "string", "minLength": 1 }, - "schemaJson": { "type": "string", "minLength": 1 } + "schemaJson": { "type": "string", "minLength": 1 }, + "members": { + "type": "array", + "items": { + "type": "object", + "required": [ + "slot", + "name", + "type", + "isReference", + "isMany", + "isName" + ], + "additionalProperties": false, + "properties": { + "slot": { "type": "integer", "minimum": 0 }, + "name": { "type": "string", "minLength": 1 }, + "type": { "type": "string", "minLength": 1 }, + "isReference": { "type": "boolean" }, + "isMany": { "type": "boolean" }, + "targetSchemaName": { "type": ["string", "null"] }, + "isName": { "type": "boolean" }, + "indexAlias": { "type": ["string", "null"] } + } + } + } } } diff --git a/packages/cultnet-rs/contracts/cultnet/cultnet.schema-catalog-request.schema.json b/packages/cultnet-rs/contracts/cultnet/cultnet.schema-catalog-request.schema.json index 5459129b..38fd7fcf 100644 --- a/packages/cultnet-rs/contracts/cultnet/cultnet.schema-catalog-request.schema.json +++ b/packages/cultnet-rs/contracts/cultnet/cultnet.schema-catalog-request.schema.json @@ -12,6 +12,7 @@ "schemaVersion": { "const": "cultnet.schema_catalog_request.v0" }, "messageId": { "type": "string", "minLength": 1 }, "includeSchemaJson": { "type": "boolean" }, + "includeMembers": { "type": "boolean" }, "schemaIds": { "type": "array", "items": { "type": "string", "minLength": 1 } diff --git a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs index 051cb050..91e5fb94 100644 --- a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs @@ -24,6 +24,7 @@ namespace GameCult.Networking private readonly Func _subscribe; private readonly Func _subscribeV1; private readonly Func _unsubscribe; + private readonly Func _catalog; private readonly Func? _authorizeRequest; private readonly Func? _authorizeRecord; private readonly ICultNetSchemaServerPeerLifecycle? _peerLifecycle; @@ -50,9 +51,11 @@ namespace GameCult.Networking _subscribe = HandleSubscribeAsync; _subscribeV1 = HandleSubscribeV1Async; _unsubscribe = HandleUnsubscribeAsync; + _catalog = HandleCatalogAsync; _server.OnCultNet(_subscribe); _server.OnCultNet(_subscribeV1); _server.OnCultNet(_unsubscribe); + _server.OnCultNet(_catalog); _peerLifecycle = server as ICultNetSchemaServerPeerLifecycle; if (_peerLifecycle != null) _peerLifecycle.PeerDisconnected += HandlePeerDisconnected; @@ -97,6 +100,7 @@ namespace GameCult.Networking _server.RemoveCultNetMessageListener(_subscribe); _server.RemoveCultNetMessageListener(_subscribeV1); _server.RemoveCultNetMessageListener(_unsubscribe); + _server.RemoveCultNetMessageListener(_catalog); if (_peerLifecycle != null) _peerLifecycle.PeerDisconnected -= HandlePeerDisconnected; foreach (var entry in _subscriptions.ToArray()) @@ -117,6 +121,45 @@ namespace GameCult.Networking } } + // Answers a catalog request with the document types this database's cache registers: kind document_payload, contentHash the + // schemaContentHash its records carry. The cache's descriptor owns the member rows and the hash; nothing is kept here, and + // schemaJson stays the contract-schema field, never filled with cache schema JSON. Members leave only for a request that asked. + private Task HandleCatalogAsync(CultNetSchemaCatalogRequestMessage request, ICultNetSchemaServerPeer peer) + { + var schemaIds = request.SchemaIds != null ? new HashSet(request.SchemaIds, StringComparer.Ordinal) : null; + var kinds = request.Kinds != null ? new HashSet(request.Kinds, StringComparer.Ordinal) : null; + var schemas = _database.Cache.Registry.AllDescriptors + .Where(descriptor => + (schemaIds == null || schemaIds.Contains(descriptor.SchemaId)) && + (kinds == null || kinds.Contains("document_payload"))) + .Select(descriptor => new CultNetSchemaDescriptor + { + SchemaId = descriptor.SchemaId, + Kind = "document_payload", + SchemaVersion = descriptor.SchemaVersion, + DocumentType = descriptor.SchemaName, + Title = descriptor.SchemaName, + WireContracts = new[] { CultNetWireContracts.SchemaV0 }, + ContentHash = descriptor.ContentHash, + Members = request.IncludeMembers + ? descriptor.ToCatalogEntry().Members.Select(member => new CultNetSchemaMember + { + Slot = member.Slot, + Name = member.MemberName, + Type = member.TypeName, + IsReference = member.IsReference, + IsMany = member.IsMany, + TargetSchemaName = member.TargetSchemaName, + IsName = member.IsName, + IndexAlias = member.IndexAlias + }).ToArray() + : null + }) + .ToArray(); + peer.SendCultNet(new CultNetSchemaCatalogResponseMessage { MessageId = request.MessageId, Schemas = schemas }); + return Task.CompletedTask; + } + private Task HandleSubscribeAsync(CultNetDatabaseSubscribeMessage request, ICultNetSchemaServerPeer peer) { // v0 has no engine of its own (docs/cultnet-selection-cut.md, D3/D4): it lowers into a diff --git a/src/GameCult.Networking/CultNetSchemaMessages.cs b/src/GameCult.Networking/CultNetSchemaMessages.cs index bc59b007..d75320d6 100644 --- a/src/GameCult.Networking/CultNetSchemaMessages.cs +++ b/src/GameCult.Networking/CultNetSchemaMessages.cs @@ -1876,6 +1876,38 @@ namespace GameCult.Networking /// Gets or sets the schema json. /// [Key("schemaJson")] public string? SchemaJson { get; set; } + /// + /// Gets or sets the member rows a document-payload schema declares, sent only to a request that asked for them + /// (). A descriptor without rows leaves the key off the wire. + /// + [Key("members")] public CultNetSchemaMember[]? Members { get; set; } + + /// Whether is written; a peer that did not ask never sees the key. + public bool ShouldSerializeMembers() => Members != null; + } + + /// + /// One member row of a document-payload schema: the row every store catalog writes for a member, in slot order. + /// + [MessagePackObject] + public class CultNetSchemaMember + { + /// Gets or sets the member's slot. + [Key("slot")] public int Slot { get; set; } + /// Gets or sets the member's name. + [Key("name")] public string Name { get; set; } = string.Empty; + /// Gets or sets the member's schema type name. + [Key("type")] public string Type { get; set; } = string.Empty; + /// Gets or sets whether the member is a reference to another record. + [Key("isReference")] public bool IsReference { get; set; } + /// Gets or sets whether the member holds many references. + [Key("isMany")] public bool IsMany { get; set; } + /// Gets or sets the schema name a reference targets. + [Key("targetSchemaName")] public string? TargetSchemaName { get; set; } + /// Gets or sets whether the member is the record's name. + [Key("isName")] public bool IsName { get; set; } + /// Gets or sets the member's unique-index alias. + [Key("indexAlias")] public string? IndexAlias { get; set; } } /// @@ -1904,6 +1936,13 @@ namespace GameCult.Networking /// Gets or sets the kinds. /// [Key("kinds")] public string[]? Kinds { get; set; } + /// + /// Gets or sets whether document-payload descriptors carry their member rows. False leaves the key off the wire. + /// + [Key("includeMembers")] public bool IncludeMembers { get; set; } + + /// Whether is written; a request that does not ask keeps its older bytes. + public bool ShouldSerializeIncludeMembers() => IncludeMembers; } /// diff --git a/tests/GameCult.Networking.Tests/CultNetSchemaCatalogMembersTests.cs b/tests/GameCult.Networking.Tests/CultNetSchemaCatalogMembersTests.cs new file mode 100644 index 00000000..a3194acd --- /dev/null +++ b/tests/GameCult.Networking.Tests/CultNetSchemaCatalogMembersTests.cs @@ -0,0 +1,254 @@ +#nullable enable +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; +using NUnit.Framework; +using static GameCult.Networking.Tests.NetworkingTests; + +namespace GameCult.Networking.Tests +{ + // schema_catalog_request answered by the subscription server from its cache's registry: the cache owns each type's member rows and + // content hash, a request opts into the rows with includeMembers, and a peer that did not ask gets the bytes it always got. + public sealed class CultNetSchemaCatalogMembersTests + { + // The descriptor and request as they were written before members: the bytes an older peer must still be sent. + [MessagePackObject] + public sealed class LegacyDescriptor + { + [Key("schemaId")] public string SchemaId { get; set; } = string.Empty; + [Key("kind")] public string Kind { get; set; } = string.Empty; + [Key("schemaVersion")] public string? SchemaVersion { get; set; } + [Key("documentType")] public string? DocumentType { get; set; } + [Key("title")] public string? Title { get; set; } + [Key("wireContracts")] public string[] WireContracts { get; set; } = Array.Empty(); + [Key("contentHash")] public string ContentHash { get; set; } = string.Empty; + [Key("schemaJson")] public string? SchemaJson { get; set; } + } + + [MessagePackObject] + public sealed class LegacyCatalogRequest + { + [Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SchemaCatalogRequest; + [Key("messageId")] public string MessageId { get; set; } = string.Empty; + [Key("includeSchemaJson")] public bool IncludeSchemaJson { get; set; } + [Key("schemaIds")] public string[]? SchemaIds { get; set; } + [Key("kinds")] public string[]? Kinds { get; set; } + } + + [MessagePackObject] + public sealed class LegacyCatalogResponse + { + [Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SchemaCatalogResponse; + [Key("messageId")] public string MessageId { get; set; } = string.Empty; + [Key("schemas")] public LegacyDescriptor[] Schemas { get; set; } = Array.Empty(); + } + + private sealed class Wire : IDisposable + { + private readonly CancellationTokenSource _cancellation = new(); + private readonly Thread _thread; + private readonly RudpCultNetSchemaServer _server; + private readonly CultNetDatabaseSubscriptionServer _subscriptions; + private readonly ICultNetSchemaClient _client; + public ConcurrentQueue Catalogs { get; } = new(); + public ConcurrentQueue Snapshots { get; } = new(); + + public Wire(CultNetDatabase database) + { + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); + socket.ReceiveTimeout = 20; + _server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions { RuntimeId = "catalog-server", Socket = socket }); + _subscriptions = new CultNetDatabaseSubscriptionServer(_server, database); + _thread = new Thread(() => + { + while (!_cancellation.IsCancellationRequested) + { + _ = _server.PollOnceAsync().GetAwaiter().GetResult(); + Thread.Sleep(1); + } + }) { IsBackground = true }; + _thread.Start(); + _client = CultNetSchemaClients.CreateRudp("catalog-client"); + _client.OnCultNet(Catalogs.Enqueue); + _client.OnCultNet(Snapshots.Enqueue); + _client.Connect("127.0.0.1", _server.LocalEndPoint.Port); + } + + public async Task AskAsync(CultNetSchemaCatalogRequestMessage request) + { + await Until(() => _client.Connected); + var before = Catalogs.Count; + _client.SendCultNet(request); + await Until(() => Catalogs.Count > before); + return Catalogs.ToArray()[before]; + } + + public async Task SnapshotAsync(string schemaId) + { + await Until(() => _client.Connected); + _client.SendCultNet(new CultNetDatabaseSubscribeMessage + { + MessageId = "subscribe", + SubscriptionId = "all", + SchemaIds = new[] { schemaId }, + IncludeSnapshot = true + }); + await Until(() => !Snapshots.IsEmpty); + return Snapshots.First(); + } + + public void Dispose() + { + _cancellation.Cancel(); + _thread.Join(); + _client.Dispose(); + _subscriptions.Dispose(); + _server.Dispose(); + } + } + + private static async Task Until(Func condition) + { + var deadline = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(5); + while (!condition()) + { + if (DateTimeOffset.UtcNow > deadline) + Assert.Fail("Condition was not satisfied before timeout."); + await Task.Delay(5); + } + } + + private static CultNetDatabase DatabaseWithANote(out CultDocumentDescriptor descriptor) + { + var cache = new CultCache(); + descriptor = cache.Registry.GetRequired(); + cache.Commit(batch => batch.Upsert( + new NetworkSchemaNote { Schema = "tests.networking_note.v1", Text = "row" }, + new CultRecordHandle(new CultRecordKey("tests:catalog:row")))); + return new CultNetDatabase(cache); + } + + [Test] + public async Task SchemaCatalogMembersAreTheCacheCatalogRowsUnderTheHashItsRecordsCarry() + { + var database = DatabaseWithANote(out var descriptor); + using var wire = new Wire(database); + + var response = await wire.AskAsync(new CultNetSchemaCatalogRequestMessage + { + MessageId = "catalog-members", + IncludeMembers = true, + SchemaIds = new[] { descriptor.SchemaId } + }); + + var served = response.Schemas.Single(); + Assert.That(served.Kind, Is.EqualTo("document_payload")); + Assert.That(served.SchemaJson, Is.Null, "schemaJson keeps its contract-schema meaning"); + var rows = descriptor.ToCatalogEntry().Members; + Assert.That(rows, Is.Not.Empty); + Assert.That(served.Members!.Select(m => (m.Slot, m.Name, m.Type, m.IsReference, m.IsMany, m.TargetSchemaName, m.IsName, m.IndexAlias)), + Is.EqualTo(rows.Select(m => (m.Slot, m.MemberName, m.TypeName, m.IsReference, m.IsMany, m.TargetSchemaName, m.IsName, m.IndexAlias)))); + + var snapshot = await wire.SnapshotAsync(descriptor.SchemaId); + Assert.That(snapshot.Documents, Is.Not.Empty); + Assert.That(snapshot.Documents.Select(d => d.SchemaContentHash).Distinct(), Is.EqualTo(new[] { served.ContentHash })); + } + + [Test] + public async Task SchemaCatalogWithoutIncludeMembersIsExactlyTheOldBytes() + { + var database = DatabaseWithANote(out var descriptor); + using var wire = new Wire(database); + + var request = new CultNetSchemaCatalogRequestMessage { MessageId = "old-client", SchemaIds = new[] { descriptor.SchemaId } }; + var oldRequestBytes = MessagePackSerializer.Serialize( + new LegacyCatalogRequest { MessageId = "old-client", SchemaIds = new[] { descriptor.SchemaId } }, CultNetSchemaMessageSerialization.Options); + Assert.That(CultNetSchemaMessageSerialization.Serialize(request), Is.EqualTo(oldRequestBytes), "a request that does not ask keeps its older bytes"); + + var response = await wire.AskAsync(request); + var legacy = new LegacyCatalogResponse + { + MessageId = "old-client", + Schemas = response.Schemas.Select(s => new LegacyDescriptor + { + SchemaId = s.SchemaId, Kind = s.Kind, SchemaVersion = s.SchemaVersion, DocumentType = s.DocumentType, Title = s.Title, + WireContracts = s.WireContracts, ContentHash = s.ContentHash, SchemaJson = s.SchemaJson + }).ToArray() + }; + Assert.That(response.Schemas.Single().Members, Is.Null); + Assert.That(CultNetSchemaMessageSerialization.Serialize(response), + Is.EqualTo(MessagePackSerializer.Serialize(legacy, CultNetSchemaMessageSerialization.Options))); + } + + private static CultNetSchemaCatalogResponseMessage VectorResponse() => new() + { + MessageId = "catalog-members-vector", + Schemas = new[] + { + new CultNetSchemaDescriptor + { + SchemaId = "sha256:9d0bc9aebc3619b07aabf564f98667afde41444c1b866661d777687d443608dc", + Kind = "document_payload", + SchemaVersion = "tests.citer.v1", + DocumentType = "tests.citer", + Title = "tests.citer", + WireContracts = new[] { CultNetWireContracts.SchemaV0 }, + ContentHash = "sha256:ff35f3d9d6de3f1066b9369e73fe6c7648e88368d18efc2275c994730cd84cff", + Members = new[] + { + new CultNetSchemaMember { Slot = 0, Name = "Id", Type = "string", IsName = true, IndexAlias = "id" }, + new CultNetSchemaMember { Slot = 1, Name = "Targets", Type = "ref[]", IsReference = true, IsMany = true, TargetSchemaName = "tests.leaf" }, + new CultNetSchemaMember { Slot = 7, Name = "Mass", Type = "double" } + } + }, + new CultNetSchemaDescriptor + { + SchemaId = "sha256:ff35f3d9d6de3f1066b9369e73fe6c7648e88368d18efc2275c994730cd84cff", + Kind = "document_payload", + SchemaVersion = "tests.leaf.v1", + DocumentType = "tests.leaf", + Title = "tests.leaf", + WireContracts = new[] { CultNetWireContracts.SchemaV0 }, + ContentHash = "sha256:abc", + Members = Array.Empty() + } + } + }; + + private static string VectorPath() + { + var directory = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); + while (directory != null && !File.Exists(Path.Combine(directory.FullName, "CultLib.sln"))) + directory = directory.Parent; + var root = directory?.FullName ?? throw new InvalidOperationException("CultLib.sln was not found above the test directory."); + return Path.Combine(root, "contracts", "cultnet", "interop", "schema-catalog-members.cs-written.msgpack"); + } + + [Test] + public void WriteSchemaCatalogMembersVector() + { + if (Environment.GetEnvironmentVariable("CULTNET_WRITE_VECTORS") != "1") + Assert.Ignore("Set CULTNET_WRITE_VECTORS=1 to (re)write the committed vector file."); + File.WriteAllBytes(VectorPath(), CultNetSchemaMessageSerialization.Serialize(VectorResponse())); + } + + [Test] + public void CommittedSchemaCatalogMembersVectorMatchesAFreshSerialization() + { + var committed = File.ReadAllBytes(VectorPath()); + Assert.That(committed, Is.EqualTo(CultNetSchemaMessageSerialization.Serialize(VectorResponse())), + "the committed bytes drifted from the reference serializer"); + var decoded = CultNetSchemaMessageSerialization.Deserialize(committed); + Assert.That(decoded.Schemas[0].Members!.Select(m => m.Name), Is.EqualTo(new[] { "Id", "Targets", "Mass" })); + } + } +}