Commit simulation facts from witness quorum

This commit is contained in:
Meta Vens 2026-05-20 01:58:36 +01:00
commit 06293b3f6e
6 changed files with 299 additions and 3 deletions

View file

@ -212,6 +212,14 @@ namespace GameCult.Mesh
return new CultMeshAuthorityLeaseCatalog();
}
/// <summary>
/// Creates a committer for writing quorum simulation facts to a mesh database.
/// </summary>
public static CultMeshSimulationFactCommitter CreateSimulationFactCommitter(CultNetDatabase database)
{
return new CultMeshSimulationFactCommitter(database);
}
/// <summary>
/// Attaches Verse discovery responses to a CultMesh node.
/// </summary>

View file

@ -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
{
/// <summary>
/// Committed simulation fact derived from witness consensus.
/// </summary>
[CultDocument("gamecult.mesh.simulation_fact", "gamecult.mesh.simulation_fact.v1")]
public sealed class CultMeshSimulationFact
{
/// <summary>
/// Stable fact identifier.
/// </summary>
[Key(0)]
[CultIndex]
public string FactId { get; set; } = string.Empty;
/// <summary>
/// Shard containing the simulation.
/// </summary>
[Key(1)]
[CultIndex]
public string ShardId { get; set; } = string.Empty;
/// <summary>
/// Shard authority epoch observed by witnesses.
/// </summary>
[Key(2)]
public long ShardEpoch { get; set; }
/// <summary>
/// Simulation frame or tick.
/// </summary>
[Key(3)]
[CultIndex]
public long Frame { get; set; }
/// <summary>
/// Subject the fact is about.
/// </summary>
[Key(4)]
[CultIndex]
public string SubjectId { get; set; } = string.Empty;
/// <summary>
/// Fact kind, such as hit, collision, or ownership.
/// </summary>
[Key(5)]
[CultIndex]
public string ClaimKind { get; set; } = string.Empty;
/// <summary>
/// Hash of the accepted claim.
/// </summary>
[Key(6)]
public string ClaimHash { get; set; } = string.Empty;
/// <summary>
/// Optional readable or app-specific claim detail.
/// </summary>
[Key(7)]
public string? ClaimSummary { get; set; }
/// <summary>
/// Number of distinct witnesses supporting the fact.
/// </summary>
[Key(8)]
public int WitnessCount { get; set; }
/// <summary>
/// Supporting witness weight.
/// </summary>
[Key(9)]
public double SupportWeight { get; set; }
/// <summary>
/// Total observed weight for the same subject/frame/kind.
/// </summary>
[Key(10)]
public double TotalWeight { get; set; }
/// <summary>
/// Support divided by total observed weight.
/// </summary>
[Key(11)]
public double Confidence { get; set; }
/// <summary>
/// Commit timestamp.
/// </summary>
[Key(12)]
public string CommittedAt { get; set; } = string.Empty;
/// <summary>
/// Builds a deterministic record key for a simulation fact.
/// </summary>
public static CultRecordKey CreateRecordKey(CultNetSimulationConsensusCandidate candidate)
{
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
return new CultRecordKey("simulation:" + ComputeFactId(candidate));
}
/// <summary>
/// Builds a stable fact id for a consensus candidate.
/// </summary>
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")));
}
/// <summary>
/// Creates a committed fact document from a quorum candidate.
/// </summary>
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!
};
}
}
/// <summary>
/// Commits quorum simulation candidates into the CultMesh database.
/// </summary>
public sealed class CultMeshSimulationFactCommitter
{
private readonly CultNetDatabase _database;
/// <summary>
/// Creates a simulation fact committer.
/// </summary>
public CultMeshSimulationFactCommitter(CultNetDatabase database)
{
_database = database ?? throw new ArgumentNullException(nameof(database));
}
/// <summary>
/// Commits a quorum candidate as a simulation fact document.
/// </summary>
public async Task<CultRecordHandle<CultMeshSimulationFact>> 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);
}
}
}

View file

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

View file

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

View file

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

View file

@ -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<CultMeshSimulationFact>().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<CultMeshSimulationFact>(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<CultMeshSimulationFact>().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<InvalidOperationException>().With.Message.Contains("before quorum"));
}
[Test]
public void CultNetDatabaseServer_Creates_Filtered_SubscriptionChange()
{