CultNet: schema_catalog_request includeMembers; the subscription server answers cache types with their member rows

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 05:21:19 +01:00
commit b573c6ac2e
7 changed files with 371 additions and 1 deletions

View file

@ -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

View file

@ -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 }

View file

@ -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"] }
}
}
}
}
}

View file

@ -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 }

View file

@ -24,6 +24,7 @@ namespace GameCult.Networking
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, Task> _subscribe;
private readonly Func<CultNetDatabaseSubscribeV1Message, ICultNetSchemaServerPeer, Task> _subscribeV1;
private readonly Func<CultNetDatabaseUnsubscribeMessage, ICultNetSchemaServerPeer, Task> _unsubscribe;
private readonly Func<CultNetSchemaCatalogRequestMessage, ICultNetSchemaServerPeer, Task> _catalog;
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, bool>? _authorizeRequest;
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, string, string, bool>? _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<CultNetDatabaseSubscribeMessage>(_subscribe);
_server.RemoveCultNetMessageListener<CultNetDatabaseSubscribeV1Message>(_subscribeV1);
_server.RemoveCultNetMessageListener<CultNetDatabaseUnsubscribeMessage>(_unsubscribe);
_server.RemoveCultNetMessageListener<CultNetSchemaCatalogRequestMessage>(_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<string>(request.SchemaIds, StringComparer.Ordinal) : null;
var kinds = request.Kinds != null ? new HashSet<string>(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

View file

@ -1876,6 +1876,38 @@ namespace GameCult.Networking
/// Gets or sets the schema json.
/// </summary>
[Key("schemaJson")] public string? SchemaJson { get; set; }
/// <summary>
/// Gets or sets the member rows a document-payload schema declares, sent only to a request that asked for them
/// (<see cref="CultNetSchemaCatalogRequestMessage.IncludeMembers"/>). A descriptor without rows leaves the key off the wire.
/// </summary>
[Key("members")] public CultNetSchemaMember[]? Members { get; set; }
/// <summary>Whether <see cref="Members"/> is written; a peer that did not ask never sees the key.</summary>
public bool ShouldSerializeMembers() => Members != null;
}
/// <summary>
/// One member row of a document-payload schema: the row every store catalog writes for a member, in slot order.
/// </summary>
[MessagePackObject]
public class CultNetSchemaMember
{
/// <summary>Gets or sets the member's slot.</summary>
[Key("slot")] public int Slot { get; set; }
/// <summary>Gets or sets the member's name.</summary>
[Key("name")] public string Name { get; set; } = string.Empty;
/// <summary>Gets or sets the member's schema type name.</summary>
[Key("type")] public string Type { get; set; } = string.Empty;
/// <summary>Gets or sets whether the member is a reference to another record.</summary>
[Key("isReference")] public bool IsReference { get; set; }
/// <summary>Gets or sets whether the member holds many references.</summary>
[Key("isMany")] public bool IsMany { get; set; }
/// <summary>Gets or sets the schema name a reference targets.</summary>
[Key("targetSchemaName")] public string? TargetSchemaName { get; set; }
/// <summary>Gets or sets whether the member is the record's name.</summary>
[Key("isName")] public bool IsName { get; set; }
/// <summary>Gets or sets the member's unique-index alias.</summary>
[Key("indexAlias")] public string? IndexAlias { get; set; }
}
/// <summary>
@ -1904,6 +1936,13 @@ namespace GameCult.Networking
/// Gets or sets the kinds.
/// </summary>
[Key("kinds")] public string[]? Kinds { get; set; }
/// <summary>
/// Gets or sets whether document-payload descriptors carry their member rows. False leaves the key off the wire.
/// </summary>
[Key("includeMembers")] public bool IncludeMembers { get; set; }
/// <summary>Whether <see cref="IncludeMembers"/> is written; a request that does not ask keeps its older bytes.</summary>
public bool ShouldSerializeIncludeMembers() => IncludeMembers;
}
/// <summary>

View file

@ -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<string>();
[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<LegacyDescriptor>();
}
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<CultNetSchemaCatalogResponseMessage> Catalogs { get; } = new();
public ConcurrentQueue<CultNetSnapshotResponseRawMessage> 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<CultNetSchemaCatalogResponseMessage>(Catalogs.Enqueue);
_client.OnCultNet<CultNetSnapshotResponseRawMessage>(Snapshots.Enqueue);
_client.Connect("127.0.0.1", _server.LocalEndPoint.Port);
}
public async Task<CultNetSchemaCatalogResponseMessage> 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<CultNetSnapshotResponseRawMessage> 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<bool> 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<NetworkSchemaNote>();
cache.Commit(batch => batch.Upsert(
new NetworkSchemaNote { Schema = "tests.networking_note.v1", Text = "row" },
new CultRecordHandle<NetworkSchemaNote>(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<CultNetSchemaMember>()
}
}
};
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<CultNetSchemaCatalogResponseMessage>(committed);
Assert.That(decoded.Schemas[0].Members!.Select(m => m.Name), Is.EqualTo(new[] { "Id", "Targets", "Mass" }));
}
}
}