Land fix batch 3's R-O and R-Q: keyed length-prefixed cursors, replica-apply sequence gap

R-O: CultNetSelectionCursorKey is a per-process (per-CultNetDatabase-instance) 32-byte
random key. CultNetSelectionCursor.ComputeDigest is now an HMAC-SHA256 under that key
instead of an unkeyed SHA-256, so a cursor cannot be forged without the key and does not
verify across a restart (a fresh CultNetDatabase mints a fresh key). The cursor body
(asOf/ordinal/schemaId/recordKey/digest) is length-prefixed (<byte length>:<value>, no
delimiter) instead of joined with a bare "\x01"-separated string, so a record key
carrying any character, U+241F included, round-trips. CultNetSelectionEvaluator.Select/
Page/ComputeDigest take an optional CultNetSelectionCursorKey, defaulting to a
process-wide key generated once so existing callers that never wire up a database still
get a keyed digest. CultNetDatabase gets a CursorKey property (random unless
CultNetDatabaseOptions.CursorKey is supplied) and passes it through
CultNetDatabaseServer.CreateSelectionResponse.

Rust already landed R-O (5aac120) under its own algorithm, deliberately not byte-matching
the reference: its own doc comment says a cursor is never handed across runtimes, so only
collision-freedom and keying are load-bearing, not the wire bytes. That is a real
divergence from this pass's instruction to match Rust's wire encoding exactly - reported
in full in the batch report.

R-Q: the two replica-apply paths (ApplyCommittedPutAsync, ApplyCommittedDelete) recorded
the mutation-log entry but never set _lastWriteSequence, so a row's order/cursor position
looked like "never written" until it was written again locally. Both now set it from the
entry's own sequence, matching AppendMutationLogEntry's local-commit path.
InitializeLogSequencesFromStore rebuilt only _nextLogSequences at startup; it now also
rebuilds _lastWriteSequence by replaying the durable log's Put/Delete entries in sequence
order. CultNetDatabase.ResolveShard is a new public wrapper over the existing shard
resolution; CultNetDocumentRegistry.SelectPage/CreateSelectionResponse take an optional
shardIdOf callback and refuse (reusing CultNetSelectionInvalidException/selection_invalid,
R-N) when a selection's matched rows resolve to more than one shard's log, because asOf is
a single watermark and is not exact for a shard-spanning page.
CultNetDatabaseServer.CreateSelectionResponse wires shardIdOf/cursorKey through from the
database.

Also fixes a defect the Rust Hands found while matching wire bytes:
CultNetErrorMessage.ForReferenceOutsideTarget double-prefixed "reference_outside_target: "
- the exception's own message already carries it. Now prefixed once, matching Rust's
ForReferenceOutsideTarget.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-22 20:04:22 +02:00
commit a4cf54f4a9
8 changed files with 541 additions and 41 deletions

View file

@ -246,6 +246,11 @@ namespace GameCult.Networking.Tests
Assert.That(decoded.Code, Is.EqualTo("reference_outside_target"));
Assert.That(decoded.Details, Is.Null);
// ForReferenceOutsideTarget used to prefix "reference_outside_target: " a second time on
// top of the exception's own message, which already carries it - a peer received the code
// name twice. One prefix only, on the wire bytes a peer actually decodes.
Assert.That(decoded.Error, Does.StartWith("reference_outside_target: "));
Assert.That(decoded.Error, Does.Not.Contain("reference_outside_target: reference_outside_target:"));
}
// S6: the hop follows one declared reference by role; a second role is not followed.
@ -441,6 +446,46 @@ namespace GameCult.Networking.Tests
Assert.That(evaluation.Rows.Select(r => r.Key.Value).OrderBy(k => k, StringComparer.Ordinal), Is.EqualTo(new[] { "1", "2", "3" }));
}
// S1-Loose (docs/cultnet-selection-cut.md, "Self's rulings for fix batch 3" -> "Surviving
// mutants"): ReachableSchemas narrows to the schemas selection.schemas actually names; a mutant
// that widens it back to every registered descriptor lets a predicate on an index only an
// EXCLUDED schema declares reach the door silently (matching nothing, never refusing), instead
// of the typed "not declared by any schema this selection can reach" refusal. "kind" is declared
// on SelLeafA/SelLeafB, not on SelCiter; Schemas here names only SelCiter.
[Test]
public void ValidationRefusesAnIndexDeclaredOnlyOnASchemaTheSelectionDoesNotReach()
{
var registry = Registry();
var descriptors = registry.AllDescriptors.ToArray();
var selection = new CultNetSelection
{
Schemas = new[] { registry.GetRequired<SelCiter>().SchemaId },
Fields = new[] { new CultNetFieldPredicate { Index = "kind", Op = "any_of", Values = new[] { "x" } } }
};
var ex = Assert.Throws<CultNetSelectionInvalidException>(() => selection.Validate(descriptors));
Assert.That(ex!.Field, Is.EqualTo("fields[0].index"));
}
// S2-AllOf (fix batch 3 "Surviving mutants"): any_of matches when the row's declared value
// equals ANY one of the predicate's values, not when it equals every one of them - impossible
// for a single-valued index whenever Values carries more than one entry, so a mutant that
// requires all of them makes a real multi-value any_of predicate match nothing.
[Test]
public void EvaluatorAnyOfMatchesWhenTheRowsValueIsAnyOneOfSeveralPredicateValues()
{
var registry = Registry();
var row = Row(registry, new SelLeafA { Name = "a", Kind = "weapon", Mass = 1 }, "a", 1);
var selection = new CultNetSelection
{
Fields = new[] { new CultNetFieldPredicate { Index = "kind", Op = "any_of", Values = new[] { "armor", "weapon" } } }
};
var evaluation = CultNetSelectionEvaluator.Select(registry, new[] { row }, selection, asOf: 1);
Assert.That(evaluation.Rows.Select(r => r.Key.Value), Is.EqualTo(new[] { "a" }));
}
public abstract class SelFixtureMiddle
{
[Key(0)]

View file

@ -190,6 +190,95 @@ namespace GameCult.Networking.Tests
Assert.That(CultNetSelectionCursor.ComputeDigest(valuesOne), Is.Not.EqualTo(CultNetSelectionCursor.ComputeDigest(valuesTwo)));
}
// S5-DigestNoFields (fix batch 3 "Surviving mutants"): the digest reads selection.Fields - a
// mutant that drops the fields loop would digest two selections identically as long as their
// schemas/keys/hop/projection agree, letting a cursor minted for one selection page a
// differently-fielded one.
[Test]
public void ComputeDigest_DiffersWhenOnlyFieldsDiffer()
{
var withFieldA = new CultNetSelection { Fields = new[] { new CultNetFieldPredicate { Index = "kind", Op = "any_of", Values = new[] { "a" } } } };
var withFieldB = new CultNetSelection { Fields = new[] { new CultNetFieldPredicate { Index = "kind", Op = "any_of", Values = new[] { "b" } } } };
var noFields = new CultNetSelection();
Assert.That(CultNetSelectionCursor.ComputeDigest(withFieldA), Is.Not.EqualTo(CultNetSelectionCursor.ComputeDigest(withFieldB)));
Assert.That(CultNetSelectionCursor.ComputeDigest(withFieldA), Is.Not.EqualTo(CultNetSelectionCursor.ComputeDigest(noFields)));
}
// R-O (fix batch 3, F6 "cursors are keyed"): a cursor's digest is an HMAC under the answering
// process's key - a page request carrying a cursor minted under a different key (forged, or
// minted by a different process) is refused cursor_invalid, never answered.
[Test]
public void Page_RefusesACursorMintedUnderADifferentKey()
{
var registry = Registry();
var rows = Enumerable.Range(0, 3)
.Select(i => Row(registry, new CultNetSelectionEvaluatorTests.SelLeafA { Name = $"n{i}", Kind = "k", Mass = i }, $"k{i}", i))
.ToArray();
var selection = new CultNetSelection { Limit = 1 };
var mintingKey = CultNetSelectionCursorKey.Random();
var otherKey = CultNetSelectionCursorKey.Random();
var first = CultNetSelectionEvaluator.Select(registry, rows, selection, asOf: 1, cursorKey: mintingKey);
Assert.That(first.NextCursor, Is.Not.Null);
selection.Cursor = first.NextCursor;
var ex = Assert.Throws<CultNetSelectionCursorException>(
() => CultNetSelectionEvaluator.Select(registry, rows, selection, asOf: 1, cursorKey: otherKey));
Assert.That(ex!.Code, Is.EqualTo("cursor_invalid"));
}
// R-O: a cursor minted before a (simulated) restart does not verify against the restarted
// process's fresh key - the same refusal as a forged cursor, because from the answering
// process's point of view they are indistinguishable (F6: "not surviving a restart is the
// accepted cost, not a bug").
[Test]
public void Page_RefusesACursorMintedBeforeARestart()
{
var registry = Registry();
var rows = Enumerable.Range(0, 3)
.Select(i => Row(registry, new CultNetSelectionEvaluatorTests.SelLeafA { Name = $"n{i}", Kind = "k", Mass = i }, $"k{i}", i))
.ToArray();
var selection = new CultNetSelection { Limit = 1 };
var preRestartKey = CultNetSelectionCursorKey.Random();
var first = CultNetSelectionEvaluator.Select(registry, rows, selection, asOf: 1, cursorKey: preRestartKey);
Assert.That(first.NextCursor, Is.Not.Null);
// A restart is a fresh process key, exactly as CultNetDatabase's constructor mints a fresh
// CursorKey per instance unless one is supplied.
var postRestartKey = CultNetSelectionCursorKey.Random();
selection.Cursor = first.NextCursor;
var ex = Assert.Throws<CultNetSelectionCursorException>(
() => CultNetSelectionEvaluator.Select(registry, rows, selection, asOf: 1, cursorKey: postRestartKey));
Assert.That(ex!.Code, Is.EqualTo("cursor_invalid"));
}
// R-O: the cursor body is length-prefixed, not delimiter-joined, so a record key carrying any
// character at all - including U+241F, which broke the pre-fix delimiter-split parse - round-trips.
[Test]
public void Cursor_RoundTripsARecordKeyContainingU241F()
{
var registry = Registry();
var weirdKey = "row-␟-two";
var rows = new[]
{
Row(registry, new CultNetSelectionEvaluatorTests.SelLeafA { Name = "a", Kind = "k", Mass = 0 }, "a-first", 0),
Row(registry, new CultNetSelectionEvaluatorTests.SelLeafA { Name = "b", Kind = "k", Mass = 1 }, weirdKey, 1)
};
var selection = new CultNetSelection { Limit = 1 };
var key = CultNetSelectionCursorKey.Random();
var first = CultNetSelectionEvaluator.Select(registry, rows, selection, asOf: 1, cursorKey: key);
Assert.That(first.Rows.Select(r => r.Key.Value), Is.EqualTo(new[] { "a-first" }));
Assert.That(first.NextCursor, Is.Not.Null);
selection.Cursor = first.NextCursor;
var second = CultNetSelectionEvaluator.Select(registry, rows, selection, asOf: 1, cursorKey: key);
Assert.That(second.Rows.Select(r => r.Key.Value), Is.EqualTo(new[] { weirdKey }));
Assert.That(second.NextCursor, Is.Null);
}
// R-J: any_of on a numeric alias compares TryGetIndexNumber's canonical rendering, not the
// string getter's culture-dependent ToString() - a float large enough that .NET's default
// ToString() renders exponent notation ("1E+21") must still match its canonical decimal form.

View file

@ -5493,6 +5493,148 @@ namespace GameCult.Networking.Tests
Assert.That(replicated, Is.Not.Null);
Assert.That(replicated!.Username, Is.EqualTo("Replica"));
Assert.That(targetDatabase.GetMutationLog("players-replica"), Has.Count.EqualTo(1));
// R-Q (docs/cultnet-selection-cut.md, fix batch 3): a replica apply is a commit path too -
// it must set LastWriteSequence exactly like a local commit does (CultNetDatabase.cs, the
// ApplyCommittedPutAsync/ApplyCommittedDelete gap), or the selection evaluator's order and
// cursor treat a replicated row as never written.
Assert.That(targetDatabase.LastWriteSequence(schemaId, key), Is.EqualTo(1));
}
[Test]
public async Task CultNetDatabase_ReplicaApply_DeleteSetsLastWriteSequence()
{
var sourceCache = new CultCache();
var targetCache = new CultCache();
var sourceRegistry = new CultNetDocumentRegistry(sourceCache.Registry)
.Register(CultNetDocumentBinding.ForDocument<PlayerData>(
sourceCache.Registry,
payloadSerializer: SerializePlayerDataPayload,
payloadDeserializer: DeserializePlayerDataPayload));
var targetRegistry = new CultNetDocumentRegistry(targetCache.Registry)
.Register(CultNetDocumentBinding.ForDocument<PlayerData>(
targetCache.Registry,
payloadSerializer: SerializePlayerDataPayload,
payloadDeserializer: DeserializePlayerDataPayload));
var schemaId = sourceCache.Registry.GetRequired<PlayerData>().SchemaId;
CultNetShardDescriptor Shard(bool isPrimary) => new(
"players-replica-delete",
"runtime-a",
epoch: 1,
isPrimary: isPrimary,
schemaIds: [schemaId],
keyPrefix: "player:");
var sourceDatabase = new CultNetDatabase(sourceCache, new CultNetDatabaseOptions
{
DocumentRegistry = sourceRegistry,
Shards = [Shard(true)]
});
var targetDatabase = new CultNetDatabase(targetCache, new CultNetDatabaseOptions
{
DocumentRegistry = targetRegistry,
Shards = [Shard(false)]
});
using var server = new Server(sourceCache, DevelopmentServerSecurity);
using var databaseServer = new CultNetDatabaseServer(server, sourceDatabase);
var key = new CultRecordKey("player:replica-delete");
var player = new PlayerData { PlayerId = Guid.NewGuid(), Email = "d@example.test", PasswordHash = "hash", Username = "D" };
await sourceDatabase.PutAsync(key, player);
await sourceDatabase.DeleteAsync<PlayerData>(key);
var response = databaseServer.CreateShardLogResponse(new CultNetShardLogRequestMessage
{
ShardId = "players-replica-delete",
ShardEpoch = 1
});
await targetDatabase.ApplyShardLogResponseAsync(response);
Assert.That(targetCache.Get<PlayerData>(key), Is.Null);
Assert.That(targetDatabase.LastWriteSequence(schemaId, key), Is.EqualTo(2));
}
[Test]
public async Task CultNetDatabase_RebuildsLastWriteSequence_FromTheDurableLogAfterRestart()
{
var rootPath = Path.Combine(TestContext.CurrentContext.WorkDirectory, "shard-logs", Guid.NewGuid().ToString("N"));
var schemaId = new CultCache().Registry.GetRequired<PlayerData>().SchemaId;
var shard = new CultNetShardDescriptor(
"players-durable-sequence",
"runtime-a",
epoch: 1,
isPrimary: true,
schemaIds: [schemaId],
keyPrefix: "player:");
var sourceCache = new CultCache();
var sourceRegistry = new CultNetDocumentRegistry(sourceCache.Registry)
.Register(CultNetDocumentBinding.ForDocument<PlayerData>(
sourceCache.Registry,
payloadSerializer: SerializePlayerDataPayload,
payloadDeserializer: DeserializePlayerDataPayload));
var sourceDatabase = new CultNetDatabase(sourceCache, new CultNetDatabaseOptions
{
DocumentRegistry = sourceRegistry,
MutationLogStore = new CultNetFileShardMutationLogStore(rootPath),
Shards = [shard]
});
var key = new CultRecordKey("player:durable-sequence");
var player = new PlayerData { PlayerId = Guid.NewGuid(), Email = "r@example.test", PasswordHash = "hash", Username = "R" };
await sourceDatabase.PutAsync(key, player);
Assert.That(sourceDatabase.LastWriteSequence(schemaId, key), Is.EqualTo(1));
sourceDatabase.Dispose();
// R-Q: a restart is a fresh CultNetDatabase instance over the same durable log - the
// sequence InitializeLogSequencesFromStore used to rebuild only _nextLogSequences
// (what the next local commit gets), never _lastWriteSequence (what a row's own last
// write was), so a selection evaluated right after restart would order/page the row as
// "never written" until it was written again.
var restartedCache = new CultCache();
var restartedDatabase = new CultNetDatabase(restartedCache, new CultNetDatabaseOptions
{
MutationLogStore = new CultNetFileShardMutationLogStore(rootPath),
Shards = [shard]
});
Assert.That(restartedDatabase.LastWriteSequence(schemaId, key), Is.EqualTo(1));
}
[Test]
public async Task CultNetDatabaseServer_RefusesASelectionSpanningMoreThanOneShardsLog()
{
var cache = new CultCache();
var registry = new CultNetDocumentRegistry(cache.Registry)
.Register(CultNetDocumentBinding.ForDocument<PlayerData>(
cache.Registry,
payloadSerializer: SerializePlayerDataPayload,
payloadDeserializer: DeserializePlayerDataPayload));
var schemaId = cache.Registry.GetRequired<PlayerData>().SchemaId;
var database = new CultNetDatabase(cache, new CultNetDatabaseOptions
{
DocumentRegistry = registry,
Shards =
[
new CultNetShardDescriptor("shard-a", "runtime-a", epoch: 1, isPrimary: true, schemaIds: [schemaId], keyPrefix: "a:"),
new CultNetShardDescriptor("shard-b", "runtime-a", epoch: 1, isPrimary: true, schemaIds: [schemaId], keyPrefix: "b:")
]
});
using var server = new Server(cache, DevelopmentServerSecurity);
using var databaseServer = new CultNetDatabaseServer(server, database);
await database.PutAsync(
new CultRecordKey("a:one"),
new PlayerData { PlayerId = Guid.NewGuid(), Email = "a@example.test", PasswordHash = "hash", Username = "A" });
await database.PutAsync(
new CultRecordKey("b:one"),
new PlayerData { PlayerId = Guid.NewGuid(), Email = "b@example.test", PasswordHash = "hash", Username = "B" });
// R-Q: asOf is one shard-log watermark - a selection whose matched rows span shard-a's log
// and shard-b's log cannot honestly claim to be exact as of it, so it is refused rather than
// answered, reusing the selection_invalid door refusal (R-N) rather than a second shape.
var ex = Assert.Throws<CultNetSelectionInvalidException>(() => databaseServer.CreateSelectionResponse(new CultNetSnapshotRequestV1Message
{
Selection = new CultNetSelection { Schemas = [schemaId] }
}));
Assert.That(ex!.Field, Is.EqualTo("asOf"));
}
[Test]