From 06293b3f6e3e4fc65c21a2d2f38b1e6f13986792 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 20 May 2026 01:58:36 +0100 Subject: [PATCH] Commit simulation facts from witness quorum --- src/GameCult.Mesh/CultMesh.cs | 8 + src/GameCult.Mesh/CultMeshSimulationFacts.cs | 188 ++++++++++++++++++ src/GameCult.Mesh/README.md | 12 +- src/GameCult.Mesh/docs/public-api.md | 6 +- .../Contracts/cultnet-distributed-database.md | 5 + .../NetworkingTests.cs | 83 ++++++++ 6 files changed, 299 insertions(+), 3 deletions(-) create mode 100644 src/GameCult.Mesh/CultMeshSimulationFacts.cs diff --git a/src/GameCult.Mesh/CultMesh.cs b/src/GameCult.Mesh/CultMesh.cs index c8693d68..70899b28 100644 --- a/src/GameCult.Mesh/CultMesh.cs +++ b/src/GameCult.Mesh/CultMesh.cs @@ -212,6 +212,14 @@ namespace GameCult.Mesh return new CultMeshAuthorityLeaseCatalog(); } + /// + /// Creates a committer for writing quorum simulation facts to a mesh database. + /// + public static CultMeshSimulationFactCommitter CreateSimulationFactCommitter(CultNetDatabase database) + { + return new CultMeshSimulationFactCommitter(database); + } + /// /// Attaches Verse discovery responses to a CultMesh node. /// diff --git a/src/GameCult.Mesh/CultMeshSimulationFacts.cs b/src/GameCult.Mesh/CultMeshSimulationFacts.cs new file mode 100644 index 00000000..6efa8711 --- /dev/null +++ b/src/GameCult.Mesh/CultMeshSimulationFacts.cs @@ -0,0 +1,188 @@ +using System; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Networking; +using MessagePack; + +namespace GameCult.Mesh +{ + /// + /// Committed simulation fact derived from witness consensus. + /// + [CultDocument("gamecult.mesh.simulation_fact", "gamecult.mesh.simulation_fact.v1")] + public sealed class CultMeshSimulationFact + { + /// + /// Stable fact identifier. + /// + [Key(0)] + [CultIndex] + public string FactId { get; set; } = string.Empty; + + /// + /// Shard containing the simulation. + /// + [Key(1)] + [CultIndex] + public string ShardId { get; set; } = string.Empty; + + /// + /// Shard authority epoch observed by witnesses. + /// + [Key(2)] + public long ShardEpoch { get; set; } + + /// + /// Simulation frame or tick. + /// + [Key(3)] + [CultIndex] + public long Frame { get; set; } + + /// + /// Subject the fact is about. + /// + [Key(4)] + [CultIndex] + public string SubjectId { get; set; } = string.Empty; + + /// + /// Fact kind, such as hit, collision, or ownership. + /// + [Key(5)] + [CultIndex] + public string ClaimKind { get; set; } = string.Empty; + + /// + /// Hash of the accepted claim. + /// + [Key(6)] + public string ClaimHash { get; set; } = string.Empty; + + /// + /// Optional readable or app-specific claim detail. + /// + [Key(7)] + public string? ClaimSummary { get; set; } + + /// + /// Number of distinct witnesses supporting the fact. + /// + [Key(8)] + public int WitnessCount { get; set; } + + /// + /// Supporting witness weight. + /// + [Key(9)] + public double SupportWeight { get; set; } + + /// + /// Total observed weight for the same subject/frame/kind. + /// + [Key(10)] + public double TotalWeight { get; set; } + + /// + /// Support divided by total observed weight. + /// + [Key(11)] + public double Confidence { get; set; } + + /// + /// Commit timestamp. + /// + [Key(12)] + public string CommittedAt { get; set; } = string.Empty; + + /// + /// Builds a deterministic record key for a simulation fact. + /// + public static CultRecordKey CreateRecordKey(CultNetSimulationConsensusCandidate candidate) + { + if (candidate == null) throw new ArgumentNullException(nameof(candidate)); + return new CultRecordKey("simulation:" + ComputeFactId(candidate)); + } + + /// + /// Builds a stable fact id for a consensus candidate. + /// + public static string ComputeFactId(CultNetSimulationConsensusCandidate candidate) + { + if (candidate == null) throw new ArgumentNullException(nameof(candidate)); + var canonical = string.Join("\u001F", + candidate.ShardId, + candidate.ShardEpoch, + candidate.Frame, + candidate.SubjectId, + candidate.ClaimKind); + using var sha = SHA256.Create(); + var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(canonical)); + return string.Concat(bytes.Select(value => value.ToString("x2"))); + } + + /// + /// Creates a committed fact document from a quorum candidate. + /// + public static CultMeshSimulationFact FromCandidate( + CultNetSimulationConsensusCandidate candidate, + string? committedAt = null) + { + if (candidate == null) throw new ArgumentNullException(nameof(candidate)); + return new CultMeshSimulationFact + { + FactId = ComputeFactId(candidate), + ShardId = candidate.ShardId, + ShardEpoch = candidate.ShardEpoch, + Frame = candidate.Frame, + SubjectId = candidate.SubjectId, + ClaimKind = candidate.ClaimKind, + ClaimHash = candidate.ClaimHash, + ClaimSummary = candidate.ClaimSummary, + WitnessCount = candidate.WitnessCount, + SupportWeight = candidate.SupportWeight, + TotalWeight = candidate.TotalWeight, + Confidence = candidate.Confidence, + CommittedAt = string.IsNullOrWhiteSpace(committedAt) + ? DateTimeOffset.UtcNow.ToString("O") + : committedAt! + }; + } + } + + /// + /// Commits quorum simulation candidates into the CultMesh database. + /// + public sealed class CultMeshSimulationFactCommitter + { + private readonly CultNetDatabase _database; + + /// + /// Creates a simulation fact committer. + /// + public CultMeshSimulationFactCommitter(CultNetDatabase database) + { + _database = database ?? throw new ArgumentNullException(nameof(database)); + } + + /// + /// Commits a quorum candidate as a simulation fact document. + /// + public async Task> CommitAsync( + CultNetSimulationConsensusCandidate candidate) + { + if (candidate == null) throw new ArgumentNullException(nameof(candidate)); + if (!candidate.HasQuorum) + { + throw new InvalidOperationException("Simulation candidate cannot be committed before quorum."); + } + + var fact = CultMeshSimulationFact.FromCandidate(candidate); + return await _database.PutAsync(CultMeshSimulationFact.CreateRecordKey(candidate), fact) + .ConfigureAwait(false); + } + } +} diff --git a/src/GameCult.Mesh/README.md b/src/GameCult.Mesh/README.md index 18271cd1..b3baf9fa 100644 --- a/src/GameCult.Mesh/README.md +++ b/src/GameCult.Mesh/README.md @@ -144,7 +144,17 @@ aggregates those observations deterministically into candidate facts with support weight, total observed weight, confidence, and quorum status. Those candidates are not committed world state by themselves. They are the fast -mesh opinion layer that can feed an authoritative shard commit path. +mesh opinion layer that can feed an authoritative shard commit path. Once a +candidate has quorum, a shard-authoritative node can commit it as a +`CultMeshSimulationFact`. + +```csharp +var committer = CultMesh.CreateSimulationFactCommitter(node.Database); +await committer.CommitAsync(candidate); +``` + +The central server does not need to decide what every witness saw. It only +needs to accept the quorum result through the shard log. ## Durable Catch-Up diff --git a/src/GameCult.Mesh/docs/public-api.md b/src/GameCult.Mesh/docs/public-api.md index 1a3dc076..5ad699c0 100644 --- a/src/GameCult.Mesh/docs/public-api.md +++ b/src/GameCult.Mesh/docs/public-api.md @@ -15,6 +15,7 @@ Namespace: `GameCult.Mesh` - `CultMesh.CreateVerseDiscoveryClient(...)` - `CultMesh.CreatePeerExchangeClient(...)` - `CultMesh.CreateAuthorityLeaseCatalog()` +- `CultMesh.CreateSimulationFactCommitter(...)` - `CultMesh.CreateClient(...)` - `CultMesh.ConnectClient(...)` @@ -108,5 +109,6 @@ replica cursor to the snapshot's represented log sequence. `CultNetSimulationObservationHub` collects those observations and emits `CultNetSimulationConsensusCandidate` updates. -Candidates are opinions. Final world state still belongs in the authoritative -shard log. +Candidates are opinions. `CultMeshSimulationFactCommitter` commits quorum +candidates as `CultMeshSimulationFact` documents through `CultNetDatabase`, so +final world state still belongs in the authoritative shard log. diff --git a/src/GameCult.Networking/Contracts/cultnet-distributed-database.md b/src/GameCult.Networking/Contracts/cultnet-distributed-database.md index ddbe3498..68b1ef92 100644 --- a/src/GameCult.Networking/Contracts/cultnet-distributed-database.md +++ b/src/GameCult.Networking/Contracts/cultnet-distributed-database.md @@ -80,6 +80,8 @@ Implemented: - predicted and reconciled database change kinds for client-side prediction - simulation witness observations for mesh-side opinions about frame facts - deterministic consensus candidates derived from witness observations +- committed CultMesh simulation fact documents written from quorum candidates + through shard authority - schema-v0 simulation observation and consensus candidate messages - reactive simulation observation hub that receives witness gossip and emits consensus candidates @@ -123,6 +125,9 @@ Not implemented yet: - Consensus candidates are derived from observations. They may inform the authoritative commit path, but they are not themselves committed world state until a shard owner writes them into the log. +- `CultMeshSimulationFact` is the committed form of a quorum candidate. It is + written through `CultNetDatabase`, so normal shard authority and replication + rules still apply. - Peer cards are contact candidates. They can advertise roles and authority lease ids, but they do not grant authority without Verse-specific validation. - Authority leases bind peer id, Verse id, roles, optional shard scope, issuer, diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index 3d59346a..a58b694d 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -2051,6 +2051,89 @@ namespace GameCult.Networking.Tests Assert.That(candidates[0].HasQuorum, Is.True); } + [Test] + public async Task CultMeshSimulationFactCommitter_Commits_QuorumCandidate_ToShardLog() + { + var cache = new CultCache(); + var schemaId = cache.Registry.GetRequired().SchemaId; + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions + { + Shards = + [ + new CultNetShardDescriptor( + "arena", + "runtime-a", + epoch: 4, + isPrimary: true, + schemaIds: [schemaId], + keyPrefix: "simulation:") + ] + }); + var claimHash = CultNetSimulationObservation.ComputeClaimHash("hit", "alice", "bob", "frame:100"); + var candidate = new CultNetSimulationConsensusCandidate( + "arena", + 4, + 100, + "bob", + "hit", + claimHash, + "alice shot bob first", + witnessCount: 3, + supportWeight: 3d, + totalWeight: 3d, + hasQuorum: true); + var committer = CultMesh.CreateSimulationFactCommitter(database); + + var handle = await committer.CommitAsync(candidate); + var fact = cache.Get(handle.Key); + var log = database.GetMutationLog("arena"); + + Assert.That(handle.Key, Is.EqualTo(CultMeshSimulationFact.CreateRecordKey(candidate))); + Assert.That(fact, Is.Not.Null); + Assert.That(fact!.ClaimHash, Is.EqualTo(claimHash)); + Assert.That(fact.ClaimSummary, Is.EqualTo("alice shot bob first")); + Assert.That(fact.Confidence, Is.EqualTo(1d)); + Assert.That(log, Has.Count.EqualTo(1)); + Assert.That(log[0].Kind, Is.EqualTo(CultNetDatabaseChangeKind.Added)); + } + + [Test] + public void CultMeshSimulationFactCommitter_Rejects_CandidateWithoutQuorum() + { + var cache = new CultCache(); + var schemaId = cache.Registry.GetRequired().SchemaId; + var database = new CultNetDatabase(cache, new CultNetDatabaseOptions + { + Shards = + [ + new CultNetShardDescriptor( + "arena", + "runtime-a", + epoch: 4, + isPrimary: true, + schemaIds: [schemaId], + keyPrefix: "simulation:") + ] + }); + var candidate = new CultNetSimulationConsensusCandidate( + "arena", + 4, + 100, + "bob", + "hit", + CultNetSimulationObservation.ComputeClaimHash("hit", "alice", "bob", "frame:100"), + null, + witnessCount: 1, + supportWeight: 1d, + totalWeight: 3d, + hasQuorum: false); + var committer = CultMesh.CreateSimulationFactCommitter(database); + + Assert.That( + async () => await committer.CommitAsync(candidate), + Throws.TypeOf().With.Message.Contains("before quorum")); + } + [Test] public void CultNetDatabaseServer_Creates_Filtered_SubscriptionChange() {