Two things landed on this branch while commit 3 was in flight, both addressed
here rather than left for the vectors to paper over:
**Self's ruling, 2026-09-22 (commit 2 fix batch, 568e8e3/021e3f1): empty
lists, blank entries, and v0's own cleaning.** Rust already refused an empty
schemas/keys list (inherited from before the ruling); it now also matches
the reference's three further decisions exactly, not just in spirit:
- The door's refusal field is the plain list name ("schemas"/"keys"), not an
indexed "schemas[i]" - selection::validate's SelectionInvalid.field now
matches CultNetSelectionInvalidException("schemas", schema, ...) literally,
because the parity vectors compare this string across runtimes.
- snapshot_query.rs's lower_v0_list now deduplicates a mixed list the same
way CultNetV0SelectionLowering.Lower does (Distinct(StringComparer.Ordinal)
- order-preserving, first occurrence wins), not just blank-filters it.
A new test (serve_read_only_raw_snapshot_lowers_an_empty_or_blank_v0_schema_list_to_no_filter,
extended) pins the dedup case directly.
- Two mutation entries (RS-EmptySchemas-Revert, RS-EmptyKeys-Revert) added
for the door's original empty-list refusal, which had tests but no
mutation coverage before this commit.
**S12: the two-way parity vectors**, contracts/cultnet/interop/selection-vectors.{cs,rs}-written.json,
eight vectors each: the six evaluated selections from commit 3 (any_of+ge
conjunction, descending+limit, gt boundary, cited exists true/false, three
rows sharing one index value) plus two door-refusal vectors added for this
ruling - `refuses_empty_schemas_list` (schemas: []) and `refuses_blank_key_entry`
(keys: ["a-eq", " "]) - which decode their selection bytes and assert
`validate`/`Validate` refuses at exactly the named field, never evaluating.
The blank-key vector could not be generated before this commit: the door
rule it exercises did not exist in the reference until 568e8e3 landed.
`cites`-based hop vectors are deliberately absent (documented in both test
files): MatchesCitation compares Citation.Target.SchemaId against the
reference's real SHA-256 schema id exactly, with no SchemaName fallback,
and this fixture pair has no way to agree on that hash across runtimes;
`cited` (role/existence, matched by record key alone) is the hop direction
both sides can cross-check, so incoming_exists_true/incoming_negation carry
that coverage instead. Both reader tests pass:
SelectionVectorsWrittenByRustDecodeAndEvaluateIdenticallyInTheReference (C#)
and selection_vectors_written_by_the_reference_decode_and_evaluate_identically_in_rust
(Rust), each judging the other runtime's file.
**The remaining mutation matrix.** Of the coordinator's named set (S1, S2,
S6, S9-S15, S17, S20, S23): S1 was already covered (RS-EmptySchemas/Keys,
RS-BlankSchema/Key); S2 (any_of matches membership, RS-S2-Revert) and S6
(cites.role filters the hop, RS-S6-Revert) are newly covered - S6 needed a
new fixture (cites_role_excludes_a_second_reference_at_the_same_target)
because base_rows()'s citer-1 only ever carries one reference, so a mutant
dropping the role filter had nothing else to wrongly match and survived
against the original hops_one_edge_by_declared_role test; that finding is
recorded in-line as a comment, not silently swapped for an easier mutant.
S9-S15 (subscription reconcile, v0-lowering-of-subscribe) do not apply:
D7 - no Rust caller subscribes in this cut, so there is no subscription
client to mutate. S17 (inherited alias reaches every leaf) does not apply
either: Rust's toy Row/RowSet has no inheritance to begin with - both
leaves in the fixture declare "mass" independently, which is the Rust
spelling of the same guarantee, already exercised throughout the suite
without a dedicated mutant (there is no shared base-type discovery path to
revert). S20 (edges only for a hopping selection) was investigated and
found structurally vacuous in Rust as built: `edges` is only ever populated
inside the cites/cited branches, so a mutant on the has_hop() gate cannot
produce a different observable result for a non-hopping selection - no
entry added; a real gap would need the evaluator's structure to change
first. S23 (matches every row sharing an index value, never a cache's
unique-index winner) has no revertable bug surface: Rust's Row/RowSet
never had a unique-index map to begin with (D7), so this is pinned by
construction, not by a mutation-testable rule; matches_every_row_sharing_an_index_value
still exists as a positive test naming it.
**A pre-existing, unrelated flaky test, found and worked around, not
fixed.** tests/cultnet.rs's reactive_document_coalesces_direct_same_schema_alias_member_writes
fails consistently when the mutation harness runs the full tests/cultnet.rs
binary (both default-parallel and RUST_TEST_THREADS=1), but passes 5/5 in
isolation and passes in a plain `cargo test -p cultnet-rs` run - state
pollution from another test in that binary under the harness's specific
invocation path, not a race this campaign's code participates in (nothing
here touches reactive_document machinery). RS-V0Lowering-Revert's Command
is narrowed to `cargo test --test cultnet serve_read_only_raw_snapshot`
(filtering both M0 and the entry's own run to this campaign's test) so the
suite does not depend on that unrelated test's health; the flake itself is
reported here as a finding, not patched.
Tests: cultnet-rs 174 passed, 0 failed (default parallel run).
GameCult.Networking.Tests 196 passed, 1 skipped (WriteSelectionVectors,
env-gated), 0 failed.
Mutation harness: 24 entries (was 22 in commit 3; +RS-S2-Revert, +RS-S6-Revert;
RS-BlankSchema/BlankKey and RS-V0Lowering-Revert's anchors and field-name
assertions updated to match the landed fix batch's exact spelling), all
KILLED, M0 green.
Negative grep: `rg -n "untagged" packages/cultnet-rs/src packages/cultcache-rs/src` empty.
Structural delta, this commit only: 6 files changed, +108/-23 (selection.rs
+15/-9 field-name fix; snapshot_query.rs +25/-14 dedup; tests/cultnet.rs +21
dedup test; tests/selection.rs +35/-2 S6 fixture and field-name fixes;
scripts/mutate-cultnet-selection-rust.entries.ps1 +33/-4 two new entries
plus three corrected anchors/commands; SelectionParityVectorTests.cs +2/-1
field name), plus the two committed vector JSON files (~90 lines each, new).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
273 lines
15 KiB
C#
273 lines
15 KiB
C#
#nullable enable
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text.Json;
|
|
using GameCult.Caching;
|
|
using MessagePack;
|
|
using NUnit.Framework;
|
|
|
|
namespace GameCult.Networking.Tests
|
|
{
|
|
// CultNet typed selection, Cut 1 commit 3/4 (docs/cultnet-selection-cut.md section 6/10, S12):
|
|
// the C#<->Rust parity vectors. New file; no existing C# source is modified.
|
|
//
|
|
// "schemaId" inside the committed vector files is each fixture document's *SchemaName*
|
|
// ("leaf_a", "leaf_b", "citer"), never CultDocumentDescriptor.SchemaId - a SHA-256 content
|
|
// hash over the type's canonical shape that Rust has no way to reproduce independently, and
|
|
// that the reference itself does not run through alias matching everywhere (MatchesCitation
|
|
// compares Citation.Target.SchemaId against the real hash exactly, with no SchemaName
|
|
// fallback). The vectors below therefore only exercise `cited` (role/existence, matched by
|
|
// record key alone - no schema id comparison at all) for the hop, never `cites` (which would
|
|
// need a real cross-runtime-agreed schema id this fixture pair cannot produce). This is a
|
|
// fixture-identity convention local to these vectors, not a claim about the real wire.
|
|
public sealed class SelectionParityVectorTests
|
|
{
|
|
private static CultDocumentRegistry Registry() => CultDocumentRegistry.ForTypes(new[]
|
|
{
|
|
typeof(ParityLeafA), typeof(ParityLeafB), typeof(ParityCiter)
|
|
});
|
|
|
|
private static CultNetSelectionEvaluator.Row Row(CultDocumentRegistry registry, object document, string key, long ordinal) =>
|
|
new(registry.GetRequired(document.GetType()), new CultRecordKey(key), document, ordinal);
|
|
|
|
private static (CultDocumentRegistry registry, CultNetSelectionEvaluator.Row[] rows) BuildFixture()
|
|
{
|
|
var registry = Registry();
|
|
var rows = new[]
|
|
{
|
|
Row(registry, new ParityLeafA { Name = "a-lo", Kind = "weapon", Mass = 4 }, "a-lo", 1),
|
|
Row(registry, new ParityLeafA { Name = "a-eq", Kind = "weapon", Mass = 5 }, "a-eq", 2),
|
|
Row(registry, new ParityLeafB { Name = "b-hi", Kind = "armor", Mass = 6 }, "b-hi", 3),
|
|
Row(registry, new ParityLeafA { Name = "shared-1", Kind = "shared", Mass = 1 }, "shared-1", 4),
|
|
Row(registry, new ParityLeafB { Name = "shared-2", Kind = "shared", Mass = 1 }, "shared-2", 5),
|
|
Row(registry, new ParityLeafA { Name = "shared-3", Kind = "shared", Mass = 1 }, "shared-3", 6),
|
|
Row(registry, new ParityCiter { Name = "citer-1", Design = new CultRecordRef<ParityMiddle>(new CultRecordKey("a-eq")) }, "citer-1", 7)
|
|
};
|
|
return (registry, rows);
|
|
}
|
|
|
|
// The same six selections packages/cultnet-rs/tests/selection.rs's
|
|
// write_selection_vectors_for_the_reference builds against its own fixture rows (which
|
|
// carry the same schema names, record keys, ordinals and declared values as BuildFixture
|
|
// above, independently constructed - a within-runtime round trip pins nothing, section 10).
|
|
private static IEnumerable<(string Name, CultNetSelection Selection)> Cases()
|
|
{
|
|
yield return ("any_of_plus_ge_conjunction", new CultNetSelection
|
|
{
|
|
Fields = new[]
|
|
{
|
|
new CultNetFieldPredicate { Index = "kind", Op = "any_of", Values = new[] { "weapon" } },
|
|
new CultNetFieldPredicate { Index = "mass", Op = "ge", Number = "5" }
|
|
}
|
|
});
|
|
yield return ("descending_with_limit", new CultNetSelection { Descending = true, Limit = 3 });
|
|
yield return ("gt_numeric_boundary", new CultNetSelection
|
|
{
|
|
Fields = new[] { new CultNetFieldPredicate { Index = "mass", Op = "gt", Number = "1" } }
|
|
});
|
|
yield return ("incoming_exists_true", new CultNetSelection
|
|
{
|
|
Schemas = new[] { "leaf_a" },
|
|
Cited = new CultNetIncoming { Role = "Design", Exists = true }
|
|
});
|
|
yield return ("incoming_negation", new CultNetSelection
|
|
{
|
|
Schemas = new[] { "leaf_a" },
|
|
Cited = new CultNetIncoming { Role = "Design", Exists = false }
|
|
});
|
|
yield return ("shared_index_value_three_rows", new CultNetSelection
|
|
{
|
|
Fields = new[] { new CultNetFieldPredicate { Index = "kind", Op = "any_of", Values = new[] { "shared" } } }
|
|
});
|
|
}
|
|
|
|
// Self's ruling, 2026-09-22 (commit 2 fix batch): door-refusal vectors. Never evaluated on
|
|
// either side - only decoded and handed to Validate/validate, which must refuse at exactly
|
|
// the named field. Mirrors packages/cultnet-rs/tests/selection.rs's refusal_cases.
|
|
private static IEnumerable<(string Name, CultNetSelection Selection, string ExpectedField)> RefusalCases()
|
|
{
|
|
yield return ("refuses_empty_schemas_list", new CultNetSelection { Schemas = Array.Empty<string>() }, "schemas");
|
|
yield return ("refuses_blank_key_entry", new CultNetSelection { Keys = new[] { "a-eq", " " } }, "keys");
|
|
}
|
|
|
|
private static string RowId(CultNetSelectionEvaluator.Row row) => $"{row.Descriptor.SchemaName}/{row.Key.Value}";
|
|
|
|
// Vectors written by Rust (packages/cultnet-rs/tests/selection.rs,
|
|
// write_selection_vectors_for_the_reference) decode and evaluate identically here.
|
|
[Test]
|
|
public void SelectionVectorsWrittenByRustDecodeAndEvaluateIdenticallyInTheReference()
|
|
{
|
|
var path = Path.Combine(RepoRoot(), "contracts", "cultnet", "interop", "selection-vectors.rs-written.json");
|
|
if (!File.Exists(path))
|
|
Assert.Inconclusive($"{path} is missing - run cargo test -p cultnet-rs --test selection with CULTNET_WRITE_VECTORS=1 first.");
|
|
|
|
var (registry, rows) = BuildFixture();
|
|
using var document = JsonDocument.Parse(File.ReadAllText(path));
|
|
var vectors = document.RootElement.GetProperty("vectors");
|
|
Assert.That(vectors.GetArrayLength(), Is.GreaterThan(0), "the vector file must carry at least one vector");
|
|
|
|
foreach (var vector in vectors.EnumerateArray())
|
|
{
|
|
var name = vector.GetProperty("name").GetString();
|
|
var selectionBytes = Convert.FromBase64String(vector.GetProperty("selectionMessagePackBase64").GetString()!);
|
|
var selection = MessagePackSerializer.Deserialize<CultNetSelection>(selectionBytes, CultNetSchemaMessageSerialization.Options);
|
|
var asOf = vector.GetProperty("asOf").GetUInt64();
|
|
|
|
if (vector.TryGetProperty("expectedRefusalField", out var refusalField) && refusalField.ValueKind != JsonValueKind.Null)
|
|
{
|
|
var error = Assert.Throws<CultNetSelectionInvalidException>(() => selection.Validate(registry.AllDescriptors.ToArray()), $"vector {name} must be refused");
|
|
Assert.That(error!.Field, Is.EqualTo(refusalField.GetString()), $"vector {name}: refusal field");
|
|
continue;
|
|
}
|
|
|
|
var evaluation = CultNetSelectionEvaluator.Select(registry, rows, selection, asOf);
|
|
|
|
var expectedIds = vector.GetProperty("expectedIds").EnumerateArray().Select(e => e.GetString()).ToArray();
|
|
Assert.That(evaluation.Rows.Select(RowId).ToArray(), Is.EqualTo(expectedIds), $"vector {name}: row ids");
|
|
Assert.That((uint)evaluation.Rows.Count, Is.EqualTo(vector.GetProperty("matched").GetUInt32()), $"vector {name}: matched");
|
|
Assert.That(evaluation.NextCursor != null, Is.EqualTo(vector.GetProperty("hasNext").GetBoolean()), $"vector {name}: hasNext");
|
|
|
|
var expectedEdges = vector.GetProperty("expectedEdges").EnumerateArray().ToArray();
|
|
Assert.That(evaluation.Edges.Count, Is.EqualTo(expectedEdges.Length), $"vector {name}: edge count");
|
|
for (var i = 0; i < expectedEdges.Length; i++)
|
|
{
|
|
var edge = evaluation.Edges[i];
|
|
var expectedEdge = expectedEdges[i];
|
|
Assert.That(RowId(edge.From), Is.EqualTo(expectedEdge.GetProperty("fromId").GetString()), $"vector {name}: edge[{i}].from");
|
|
Assert.That(edge.Role, Is.EqualTo(expectedEdge.GetProperty("role").GetString()), $"vector {name}: edge[{i}].role");
|
|
Assert.That(RowId(edge.To), Is.EqualTo(expectedEdge.GetProperty("toId").GetString()), $"vector {name}: edge[{i}].to");
|
|
var expectedPayload = expectedEdge.GetProperty("payloadBase64");
|
|
if (expectedPayload.ValueKind == JsonValueKind.Null)
|
|
Assert.That(edge.Payload, Is.Null, $"vector {name}: edge[{i}].payload");
|
|
else
|
|
Assert.That(Convert.ToBase64String((byte[])edge.Payload!), Is.EqualTo(expectedPayload.GetString()), $"vector {name}: edge[{i}].payload");
|
|
}
|
|
}
|
|
}
|
|
|
|
// Writes contracts/cultnet/interop/selection-vectors.cs-written.json for Rust's
|
|
// selection_vectors_written_by_the_reference_decode_and_evaluate_identically_in_rust to
|
|
// judge. Gated the same way the QUIC campaign's C#-written vectors are
|
|
// (docs/typescript-quic-realtime-cut.md:15-21): committed, not regenerated on every run.
|
|
[Test]
|
|
public void WriteSelectionVectors()
|
|
{
|
|
if (Environment.GetEnvironmentVariable("CULTNET_WRITE_VECTORS") != "1")
|
|
Assert.Ignore("Set CULTNET_WRITE_VECTORS=1 to (re)write the committed vector file.");
|
|
|
|
var (registry, rows) = BuildFixture();
|
|
var vectors = new List<object>();
|
|
foreach (var (name, selection) in Cases())
|
|
{
|
|
var evaluation = CultNetSelectionEvaluator.Select(registry, rows, selection, asOf: 1);
|
|
var selectionBytes = MessagePackSerializer.Serialize(selection, CultNetSchemaMessageSerialization.Options);
|
|
|
|
vectors.Add(new
|
|
{
|
|
name,
|
|
selectionMessagePackBase64 = Convert.ToBase64String(selectionBytes),
|
|
asOf = 1UL,
|
|
expectedRefusalField = (string?)null,
|
|
expectedIds = evaluation.Rows.Select(RowId).ToArray(),
|
|
matched = (uint)evaluation.Rows.Count,
|
|
hasNext = evaluation.NextCursor != null,
|
|
expectedEdges = evaluation.Edges.Select(edge => new
|
|
{
|
|
fromId = RowId(edge.From),
|
|
role = edge.Role,
|
|
toId = RowId(edge.To),
|
|
// None of this file's six vectors hop through a many-dictionary reference
|
|
// (the only shape D11 gives a non-null payload), so this is always null
|
|
// here; packages/cultnet-rs/tests/selection.rs's
|
|
// dictionary_reference_entries_keep_distinct_payload_bytes pins the
|
|
// payload-carrying case directly against Row::references() instead.
|
|
payloadBase64 = edge.Payload == null ? null : Convert.ToBase64String((byte[])edge.Payload)
|
|
}).ToArray()
|
|
});
|
|
}
|
|
|
|
// Self's ruling, 2026-09-22 (commit 2 fix batch): door-refusal vectors. Never
|
|
// evaluated on either side - only decoded and handed to Validate, which must refuse
|
|
// at exactly the named field.
|
|
foreach (var (name, selection, expectedField) in RefusalCases())
|
|
{
|
|
var error = Assert.Throws<CultNetSelectionInvalidException>(
|
|
() => selection.Validate(registry.AllDescriptors.ToArray()),
|
|
$"{name} must be refused by the reference before it can be committed as a refusal vector");
|
|
Assert.That(error!.Field, Is.EqualTo(expectedField), $"{name}: refusal field");
|
|
|
|
var selectionBytes = MessagePackSerializer.Serialize(selection, CultNetSchemaMessageSerialization.Options);
|
|
vectors.Add(new
|
|
{
|
|
name,
|
|
selectionMessagePackBase64 = Convert.ToBase64String(selectionBytes),
|
|
asOf = 1UL,
|
|
expectedRefusalField = (string?)expectedField,
|
|
expectedIds = Array.Empty<string>(),
|
|
matched = 0U,
|
|
hasNext = false,
|
|
expectedEdges = Array.Empty<object>()
|
|
});
|
|
}
|
|
|
|
var directory = Path.Combine(RepoRoot(), "contracts", "cultnet", "interop");
|
|
Directory.CreateDirectory(directory);
|
|
var json = JsonSerializer.Serialize(new { vectors }, new JsonSerializerOptions { WriteIndented = true });
|
|
File.WriteAllText(Path.Combine(directory, "selection-vectors.cs-written.json"), json);
|
|
}
|
|
|
|
private static string RepoRoot()
|
|
{
|
|
var directory = new DirectoryInfo(TestContext.CurrentContext.TestDirectory);
|
|
while (directory != null && !File.Exists(Path.Combine(directory.FullName, "CultLib.sln")))
|
|
directory = directory.Parent;
|
|
return directory?.FullName ?? throw new InvalidOperationException("CultLib.sln was not found above the test directory.");
|
|
}
|
|
|
|
// A conceptual abstract middle (no [CultDocument]), matching Design's declared target so
|
|
// D9's leaf-set resolution reaches both ParityLeafA and ParityLeafB. SchemaName is the
|
|
// literal fixture-identity string ("leaf_a", "leaf_b", "citer") the vectors compare by -
|
|
// see this file's header comment.
|
|
public abstract class ParityMiddle
|
|
{
|
|
[Key(0)]
|
|
[CultName]
|
|
public string Name = string.Empty;
|
|
|
|
[Key(1)]
|
|
[CultIndex("kind")]
|
|
public string Kind = string.Empty;
|
|
|
|
[Key(2)]
|
|
[CultIndex("mass")]
|
|
public float Mass;
|
|
}
|
|
|
|
[CultDocument("leaf_a", "cultnet.selection-parity.leaf_a.v1")]
|
|
[MessagePackObject(AllowPrivate = true)]
|
|
public sealed class ParityLeafA : ParityMiddle
|
|
{
|
|
}
|
|
|
|
[CultDocument("leaf_b", "cultnet.selection-parity.leaf_b.v1")]
|
|
[MessagePackObject(AllowPrivate = true)]
|
|
public sealed class ParityLeafB : ParityMiddle
|
|
{
|
|
}
|
|
|
|
[CultDocument("citer", "cultnet.selection-parity.citer.v1")]
|
|
[MessagePackObject(AllowPrivate = true)]
|
|
public sealed class ParityCiter
|
|
{
|
|
[Key(0)]
|
|
[CultName]
|
|
public string Name = string.Empty;
|
|
|
|
[Key(1)]
|
|
[CultReference(typeof(ParityMiddle))]
|
|
public CultRecordRef<ParityMiddle> Design;
|
|
}
|
|
}
|
|
}
|