From e8b2322420a3900842f3e1187e92b93b342aa1c4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 19 May 2026 18:05:51 +0100 Subject: [PATCH] Apply CultNet shard logs on replicas --- .../cultnet-distributed-database/summary.md | 6 +- .../Contracts/cultnet-distributed-database.md | 19 +- src/GameCult.Networking/CultNetDatabase.cs | 223 +++++++++++++++++- src/GameCult.Networking/README.md | 4 +- .../NetworkingTests.cs | 123 ++++++++++ 5 files changed, 354 insertions(+), 21 deletions(-) diff --git a/research/cultnet-distributed-database/summary.md b/research/cultnet-distributed-database/summary.md index 22199224..febfa8a1 100644 --- a/research/cultnet-distributed-database/summary.md +++ b/research/cultnet-distributed-database/summary.md @@ -166,14 +166,16 @@ Shard catalog exchange now exists: endpoints - in-memory per-shard mutation logs and catch-up by last seen sequence - wire-level shard mutation log catch-up with raw put/delete entries +- replica-side application of shard log responses with epoch checks, gap + rejection, and idempotent replay ## Next Cut -Build durable replica catch-up: +Build durable replica catch-up loops: - persist per-shard logs and last-applied replica sequence - define the snapshot fallback boundary for compacted history -- add a replica-side apply loop for shard log responses +- add a background pull loop from catalog-advertised primary endpoints That is the next foundation needed before membership, Raft-style failover, or CRDT policy work can be honest. diff --git a/src/GameCult.Networking/Contracts/cultnet-distributed-database.md b/src/GameCult.Networking/Contracts/cultnet-distributed-database.md index 9f9afd4f..e69f49f9 100644 --- a/src/GameCult.Networking/Contracts/cultnet-distributed-database.md +++ b/src/GameCult.Networking/Contracts/cultnet-distributed-database.md @@ -52,13 +52,15 @@ Implemented: - mutation-log catch-up by last seen sequence - wire-level shard log request/response messages - raw put/delete representation for accepted mutation-log entries +- replica-side shard log application with epoch checks, gap rejection, and + idempotent replay Not implemented yet: - membership/failure detection - leader election or automatic shard failover - durable log persistence and compaction -- replica-side log application loop +- background replica pull loops - declared CRDT merge policies ## Live Invariants @@ -75,15 +77,14 @@ Not implemented yet: ## Next Coherent Slice -Add durable log storage and replica application: +Add durable log storage and background replica pull loops: - persist per-shard mutation logs instead of keeping them only in memory - define the compaction boundary that turns old log reads into snapshot reads -- apply `cultnet.shard_log_response.v0` entries on replicas through - `CultNetDatabase` -- track last applied sequence per shard +- store last applied sequence per shard across restarts +- let replicas periodically pull from primary endpoints in the shard catalog -The log is now wire-readable. The next useful layer is making a replica consume -that stream durably enough that restart/reconnect behavior can be explained -without hand waving. Membership and leader election should wait until basic -replica catch-up is boring. +The log is now wire-readable and replicas can apply it explicitly. The next +useful layer is making that state survive restart and giving replicas a pull +loop. Membership and leader election should wait until basic replica catch-up is +boring. diff --git a/src/GameCult.Networking/CultNetDatabase.cs b/src/GameCult.Networking/CultNetDatabase.cs index 8887bf65..6e8631e2 100644 --- a/src/GameCult.Networking/CultNetDatabase.cs +++ b/src/GameCult.Networking/CultNetDatabase.cs @@ -332,6 +332,7 @@ namespace GameCult.Networking private readonly Dictionary> _mutationLogs = new(StringComparer.Ordinal); private readonly Dictionary _nextLogSequences = new(StringComparer.Ordinal); + private readonly Dictionary _appliedShardSequences = new(StringComparer.Ordinal); private readonly Subject _changes = new(); private bool _disposed; @@ -387,6 +388,18 @@ namespace GameCult.Networking return query.ToArray(); } + /// + /// Gets the last replicated sequence applied for a shard. + /// + public long GetAppliedShardSequence(string shardId) + { + ThrowIfDisposed(); + if (string.IsNullOrWhiteSpace(shardId)) throw new ArgumentException("Value must be non-empty.", nameof(shardId)); + return _appliedShardSequences.TryGetValue(shardId, out var sequence) + ? sequence + : 0; + } + /// /// Creates a shard catalog response for optional schema/key filters. /// @@ -575,6 +588,57 @@ namespace GameCult.Networking return Task.CompletedTask; } + /// + /// Applies committed shard-log entries from an authoritative peer. + /// + public async Task ApplyShardLogResponseAsync(CultNetShardLogResponseMessage response) + { + ThrowIfDisposed(); + if (response == null) throw new ArgumentNullException(nameof(response)); + if (response.ResyncRequired) + { + throw new InvalidOperationException( + $"Shard '{response.ShardId}' requires snapshot resync before log application: {response.Reason ?? "unspecified"}."); + } + + var shard = _shards.FirstOrDefault(candidate => + string.Equals(candidate.ShardId, response.ShardId, StringComparison.Ordinal)); + if (shard == null) + { + throw new InvalidOperationException($"Shard '{response.ShardId}' is not known by this database."); + } + + if (response.ShardEpoch != shard.Epoch) + { + throw new CultNetShardAuthorityException( + shard, + $"Shard '{shard.ShardId}' is at epoch {shard.Epoch}, not response epoch {response.ShardEpoch}.", + "stale_epoch"); + } + + var lastApplied = GetAppliedShardSequence(response.ShardId); + var orderedEntries = response.Entries.OrderBy(entry => entry.Sequence).ToArray(); + foreach (var entry in orderedEntries) + { + if (entry.Sequence <= lastApplied) + { + continue; + } + + if (entry.Sequence != lastApplied + 1) + { + throw new InvalidOperationException( + $"Shard '{response.ShardId}' log has a gap. Expected sequence {lastApplied + 1}, received {entry.Sequence}."); + } + + await ApplyCommittedShardLogEntryAsync(shard, entry).ConfigureAwait(false); + lastApplied = entry.Sequence; + _appliedShardSequences[response.ShardId] = lastApplied; + } + + return lastApplied; + } + /// /// Watches all changes assignable to the requested document type. /// @@ -711,12 +775,8 @@ namespace GameCult.Networking object? document, object? previousDocument) { - var sequence = _nextLogSequences.TryGetValue(shard.ShardId, out var next) - ? next - : 1; - _nextLogSequences[shard.ShardId] = sequence + 1; - - var entry = new CultNetShardMutationLogEntry( + var sequence = NextMutationLogSequence(shard.ShardId); + RecordMutationLogEntry(new CultNetShardMutationLogEntry( shard.ShardId, shard.Epoch, sequence, @@ -725,15 +785,160 @@ namespace GameCult.Networking schemaId, key, document, - previousDocument); + previousDocument)); + } - if (!_mutationLogs.TryGetValue(shard.ShardId, out var entries)) + private void RecordMutationLogEntry(CultNetShardMutationLogEntry entry) + { + if (!_mutationLogs.TryGetValue(entry.ShardId, out var entries)) { entries = new List(); - _mutationLogs[shard.ShardId] = entries; + _mutationLogs[entry.ShardId] = entries; } entries.Add(entry); + if (!_nextLogSequences.TryGetValue(entry.ShardId, out var next) || + next <= entry.Sequence) + { + _nextLogSequences[entry.ShardId] = entry.Sequence + 1; + } + } + + private long NextMutationLogSequence(string shardId) + { + var sequence = _nextLogSequences.TryGetValue(shardId, out var next) + ? next + : 1; + _nextLogSequences[shardId] = sequence + 1; + return sequence; + } + + private async Task ApplyCommittedShardLogEntryAsync( + CultNetShardDescriptor shard, + CultNetShardLogEntryMessage entry) + { + if (entry.Put != null) + { + await ApplyCommittedPutAsync(shard, entry).ConfigureAwait(false); + return; + } + + if (entry.Delete != null) + { + ApplyCommittedDelete(shard, entry); + return; + } + + throw new InvalidOperationException( + $"Shard '{shard.ShardId}' log entry {entry.Sequence} has no put or delete payload."); + } + + private async Task ApplyCommittedPutAsync( + CultNetShardDescriptor shard, + CultNetShardLogEntryMessage entry) + { + var message = entry.Put!; + if (message.Document == null) + { + throw new InvalidOperationException( + $"Shard '{shard.ShardId}' log entry {entry.Sequence} put is missing its document payload."); + } + + if (!string.Equals(message.ShardId, shard.ShardId, StringComparison.Ordinal) || + message.ShardEpoch != shard.Epoch) + { + throw new CultNetShardAuthorityException( + shard, + $"Shard '{shard.ShardId}' log entry {entry.Sequence} targets a different shard or epoch.", + "stale_epoch"); + } + + var key = new CultRecordKey(message.Document.RecordKey); + var descriptor = _cache.Registry.GetRequiredBySchemaId(message.Document.SchemaId); + var previous = _cache.Get(key); + var document = await _documents.ApplyRawDocumentPutMessageAsync(_cache, message).ConfigureAwait(false); + var kind = ChangeKindFromWire(entry.ChangeKind); + if (kind == CultNetDatabaseChangeKind.Removed) + { + throw new InvalidOperationException( + $"Shard '{shard.ShardId}' log entry {entry.Sequence} has a removed kind with a put payload."); + } + + RecordMutationLogEntry(new CultNetShardMutationLogEntry( + shard.ShardId, + shard.Epoch, + entry.Sequence, + entry.CommittedAt, + kind, + descriptor.SchemaId, + key, + document, + previous)); + PublishUntyped( + descriptor.DocumentType, + kind, + key, + descriptor.SchemaId, + shard, + document, + previous); + } + + private void ApplyCommittedDelete( + CultNetShardDescriptor shard, + CultNetShardLogEntryMessage entry) + { + var message = entry.Delete!; + if (!string.Equals(message.ShardId, shard.ShardId, StringComparison.Ordinal) || + message.ShardEpoch != shard.Epoch) + { + throw new CultNetShardAuthorityException( + shard, + $"Shard '{shard.ShardId}' log entry {entry.Sequence} targets a different shard or epoch.", + "stale_epoch"); + } + + var key = new CultRecordKey(message.RecordKey); + var descriptor = _cache.Registry.GetRequiredBySchemaId(message.SchemaId); + var previous = _cache.Get(key); + if (previous != null) + { + var removeMethod = typeof(CultCache).GetMethod(nameof(CultCache.Remove))! + .MakeGenericMethod(descriptor.DocumentType); + var handleType = typeof(CultRecordHandle<>).MakeGenericType(descriptor.DocumentType); + var handle = Activator.CreateInstance(handleType, new object[] { key }); + removeMethod.Invoke(_cache, new[] { handle }); + } + + RecordMutationLogEntry(new CultNetShardMutationLogEntry( + shard.ShardId, + shard.Epoch, + entry.Sequence, + entry.CommittedAt, + CultNetDatabaseChangeKind.Removed, + descriptor.SchemaId, + key, + document: null, + previousDocument: previous)); + PublishUntyped( + descriptor.DocumentType, + CultNetDatabaseChangeKind.Removed, + key, + descriptor.SchemaId, + shard, + document: null, + previousDocument: previous); + } + + private static CultNetDatabaseChangeKind ChangeKindFromWire(string changeKind) + { + return changeKind switch + { + "added" => CultNetDatabaseChangeKind.Added, + "updated" => CultNetDatabaseChangeKind.Updated, + "removed" => CultNetDatabaseChangeKind.Removed, + _ => throw new InvalidOperationException($"Unsupported shard log change kind '{changeKind}'.") + }; } private void PublishUntyped( diff --git a/src/GameCult.Networking/README.md b/src/GameCult.Networking/README.md index 10168ee9..38741618 100644 --- a/src/GameCult.Networking/README.md +++ b/src/GameCult.Networking/README.md @@ -138,7 +138,9 @@ write rejection. Non-primary write forwarding is available behind an injectable schema-v0 `cultnet://host:port` endpoint dialer. It also records accepted mutations in per-shard ordered logs and exposes those logs over `cultnet.shard_log_request.v0` / `cultnet.shard_log_response.v0` for replica -catch-up. +catch-up. Replicas apply those committed entries through +`CultNetDatabase.ApplyShardLogResponseAsync`, which checks shard epoch, rejects +sequence gaps, and treats replayed entries as already applied. The first coherent shard policy is primary ownership. Each shard has one authoritative writer at a time. Clients may connect to any node; a non-owner diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index f044f787..5af57b71 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -849,6 +849,129 @@ namespace GameCult.Networking.Tests Assert.That(response.Entries[0].Delete!.ShardEpoch, Is.EqualTo(6)); } + [Test] + public async Task CultNetDatabase_Applies_ShardLogResponse_ToReplica() + { + var sourceCache = new CultCache(); + var targetCache = new CultCache(); + var sourceRegistry = new CultNetDocumentRegistry(sourceCache.Registry) + .Register(CultNetDocumentBinding.ForDocument( + sourceCache.Registry, + payloadSerializer: SerializePlayerDataPayload, + payloadDeserializer: DeserializePlayerDataPayload)); + var targetRegistry = new CultNetDocumentRegistry(targetCache.Registry) + .Register(CultNetDocumentBinding.ForDocument( + targetCache.Registry, + payloadSerializer: SerializePlayerDataPayload, + payloadDeserializer: DeserializePlayerDataPayload)); + var schemaId = sourceCache.Registry.GetRequired().SchemaId; + var sourceDatabase = new CultNetDatabase(sourceCache, new CultNetDatabaseOptions + { + DocumentRegistry = sourceRegistry, + Shards = + [ + new CultNetShardDescriptor( + "players-replica", + "runtime-a", + epoch: 10, + isPrimary: true, + schemaIds: [schemaId], + keyPrefix: "player:") + ] + }); + var targetDatabase = new CultNetDatabase(targetCache, new CultNetDatabaseOptions + { + DocumentRegistry = targetRegistry, + Shards = + [ + new CultNetShardDescriptor( + "players-replica", + "runtime-a", + epoch: 10, + isPrimary: false, + schemaIds: [schemaId], + keyPrefix: "player:") + ] + }); + using var server = new Server(sourceCache, DevelopmentServerSecurity); + using var databaseServer = new CultNetDatabaseServer(server, sourceDatabase); + var key = new CultRecordKey("player:replica"); + var player = new PlayerData + { + PlayerId = Guid.NewGuid(), + Email = "replica@example.test", + PasswordHash = "hash", + Username = "Replica" + }; + + await sourceDatabase.PutAsync(key, player); + var response = databaseServer.CreateShardLogResponse(new CultNetShardLogRequestMessage + { + ShardId = "players-replica", + ShardEpoch = 10 + }); + + var sequence = await targetDatabase.ApplyShardLogResponseAsync(response); + var replicated = targetCache.Get(key); + var replayedSequence = await targetDatabase.ApplyShardLogResponseAsync(response); + + Assert.That(sequence, Is.EqualTo(1)); + Assert.That(replayedSequence, Is.EqualTo(1)); + Assert.That(targetDatabase.GetAppliedShardSequence("players-replica"), Is.EqualTo(1)); + Assert.That(replicated, Is.Not.Null); + Assert.That(replicated!.Username, Is.EqualTo("Replica")); + Assert.That(targetDatabase.GetMutationLog("players-replica"), Has.Count.EqualTo(1)); + } + + [Test] + public void CultNetDatabase_Rejects_ShardLogGap() + { + var cache = new CultCache(); + var registry = new CultNetDocumentRegistry(cache.Registry) + .Register(CultNetDocumentBinding.ForDocument( + cache.Registry, + payloadSerializer: SerializePlayerDataPayload, + payloadDeserializer: DeserializePlayerDataPayload)); + var schemaId = cache.Registry.GetRequired().SchemaId; + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions + { + DocumentRegistry = registry, + Shards = + [ + new CultNetShardDescriptor( + "players-gap", + "runtime-a", + epoch: 1, + isPrimary: false, + schemaIds: [schemaId], + keyPrefix: "player:") + ] + }); + + Assert.That( + async () => await database.ApplyShardLogResponseAsync(new CultNetShardLogResponseMessage + { + ShardId = "players-gap", + ShardEpoch = 1, + Entries = + [ + new CultNetShardLogEntryMessage + { + Sequence = 2, + ChangeKind = "removed", + Delete = new CultNetDocumentDeleteMessage + { + SchemaId = schemaId, + RecordKey = "player:gap", + ShardId = "players-gap", + ShardEpoch = 1 + } + } + ] + }), + Throws.TypeOf().With.Message.Contains("log has a gap")); + } + [Test] public void CultNetDatabaseServer_Creates_Filtered_SubscriptionChange() {