Merge main at cultlib-unity-v2.0.0 (42dce361) into C2a: one owner per collision

Identity: C2a's StoredSchemaId/StoredVersion owns; main's PersistedSchemaId, PersistedIdentity and both MarkWritten are deleted. Stamp rule: ReadStore judges the stamp before the body. Flush over damage refuses (merge-r1-precedence). Mesh single-file writes route through SingleFileMessagePackBackingStore. TS: store-file.ts commits, C2a's header handling kept. Rust: C2a's readable_store_format in front of the grown decoder. Build not yet verified at this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-22 20:21:31 +02:00
commit f2b3569822
210 changed files with 27332 additions and 899 deletions

View file

@ -17,7 +17,7 @@ static async Task<int> ProgramMainAsync(string[] args)
{
if (args.Length == 0)
{
throw new InvalidOperationException("Expected mode: write | read | rewrite | write-routed <catalog.cc> <run.cc>");
throw new InvalidOperationException("Expected mode: write | read | rewrite | hold-lock | write-routed <catalog.cc> <run.cc>");
}
var mode = args[0];
@ -51,6 +51,9 @@ static async Task<int> ProgramMainAsync(string[] args)
case "edit-in-place":
await EditInPlaceAsync(file, RequireArg(options, "kind"));
return 0;
case "hold-lock":
HoldLock(file, int.Parse(RequireArg(options, "ms"), CultureInfo.InvariantCulture));
return 0;
default:
throw new InvalidOperationException($"Unknown mode {mode}.");
}
@ -62,6 +65,20 @@ static async Task<int> ProgramMainAsync(string[] args)
}
}
// Holds the store lock exactly as CultCache.AcquireLock opens it, for --ms, then releases it.
static void HoldLock(string file, int milliseconds)
{
using var held = new System.IO.FileStream(
file + ".lock",
System.IO.FileMode.OpenOrCreate,
System.IO.FileAccess.ReadWrite,
System.IO.FileShare.None,
bufferSize: 1);
Console.WriteLine("{\"held\":true}");
Console.Out.Flush();
System.Threading.Thread.Sleep(milliseconds);
}
static async Task WriteAsync(string file, string runtimeId)
{
var cache = BuildCache(file);

View file

@ -53,6 +53,136 @@ namespace GameCult.Caching.Tests
UnrelatedInsert(DirectoryStore(PathOf("insert.cc")));
}
// ---- a record loaded under compatible schema drift: written under v1, read by a cache that knows only v2 ----
[TestCase(false)]
[TestCase(true)]
public void UnchangedDriftedRecordSatisfiesExpect(bool directory)
{
SeedDrift(directory);
using var cache = Drift(directory, NarrowDrift).Open();
Assert.That(DriftCommit(cache, cache.Get(DriftKey)!, 2), Is.True, "an unchanged drifted record failed Expect");
using var reader = Drift(directory, NarrowDrift).Open();
Assert.That(reader.Get<ConditionalDriftNarrow>(DriftKey)!.Value, Is.EqualTo(2));
}
[TestCase(false)]
[TestCase(true)]
public void ValueChangedDriftedRecordFailsExpect(bool directory)
{
SeedDrift(directory);
using var cache = Drift(directory, NarrowDrift).Open();
var observed = cache.Get(DriftKey)!;
using (var other = Drift(directory, NarrowDrift).Open())
Assert.That(other.Commit(batch => batch.Upsert(new ConditionalDriftNarrow { Name = "drift", Value = 9 }, new CultRecordHandle<ConditionalDriftNarrow>(DriftKey))), Is.True);
Assert.That(DriftCommit(cache, observed, 2), Is.False, "a value another writer changed passed Expect");
using var reader = Drift(directory, NarrowDrift).Open();
Assert.That(reader.Get<ConditionalDriftNarrow>(DriftKey)!.Value, Is.EqualTo(9));
}
[Test]
public void RecordRewrittenUnderAnotherSchemaWithItsStoredAtFailsExpect()
{
SeedDrift(directory: false);
using var cache = Drift(false, NarrowDrift).Open();
var observed = cache.Get(DriftKey)!;
var storedAt = cache.GetStored(DriftKey)!.StoredAt;
using (var other = Drift(false, ReusedDrift).Open())
other.BackingStores[0].PushAll();
using (var reader = Drift(false, ReusedDrift).Open())
Assert.That(reader.GetStored(DriftKey)!.StoredAt, Is.EqualTo(storedAt), "the rewrite kept storedAt");
Assert.That(DriftCommit(cache, observed, 2), Is.False, "a record rewritten under another schema passed Expect on storedAt alone");
}
// The directory store rewrites only what is pushed to it, so the other writer pushes the record it read unchanged.
[TestCase(false)]
[TestCase(true)]
public void AnotherWritersNormalisingFlushFailsExpectUntilReRead(bool directory)
{
SeedDrift(directory);
using var cache = Drift(directory, NarrowDrift).Open();
var observed = cache.Get(DriftKey)!;
using (var other = Drift(directory, NarrowDrift).Open())
{
other.BackingStores[0].Push(other.GetStored(DriftKey)!);
other.BackingStores[0].PushAll();
}
Assert.That(DriftCommit(cache, observed, 2), Is.False, "Expect held across a rewrite under a schema id this cache did not read");
cache.BackingStores[0].PullAll();
Assert.That(DriftCommit(cache, cache.Get(DriftKey)!, 3), Is.True, "a re-read did not refresh the persisted schema id");
}
[Test]
public void OwnFlushKeepsDriftedExpectHolding()
{
SeedDrift(directory: false);
using var cache = Drift(false, NarrowDrift).Open();
cache.BackingStores[0].PushAll();
Assert.That(DriftCommit(cache, cache.Get(DriftKey)!, 2), Is.True, "Expect failed after this cache's own flush rewrote the record");
}
// A store rewrites what is pushed to it under the entry's descriptor; the entry then names that schema id.
[TestCase(false)]
[TestCase(true)]
public void OwnPushOfALoadedDriftedEntryKeepsExpectHolding(bool directory)
{
SeedDrift(directory);
using var cache = Drift(directory, NarrowDrift).Open();
cache.BackingStores[0].Push(cache.GetStored(DriftKey)!);
cache.BackingStores[0].PushAll();
var stored = cache.GetStored(DriftKey)!;
Assert.That(stored.StoredSchemaId, Is.EqualTo(stored.Descriptor.SchemaId), "the rewrite was not recorded");
Assert.That(DriftCommit(cache, cache.Get(DriftKey)!, 2), Is.True, "Expect failed after this cache's own push rewrote the record");
}
[Test]
public void OwnUnconditionalCommitKeepsDriftedExpectHolding()
{
SeedDrift(directory: false);
using var cache = Drift(false, NarrowDrift).Open();
Assert.That(cache.Commit(batch => batch.Upsert(new ConditionalDriftNarrow { Name = "other" }, new CultRecordHandle<ConditionalDriftNarrow>(new CultRecordKey("other")))), Is.True);
Assert.That(DriftCommit(cache, cache.Get(DriftKey)!, 2), Is.True, "Expect failed after this cache's own whole-file commit rewrote the record");
}
[TestCase(false)]
[TestCase(true)]
public void ExpectUnchangedHoldsOnAnUntouchedDriftedStore(bool directory)
{
SeedDrift(directory);
using var cache = Drift(directory, NarrowDrift).Open();
Assert.That(cache.Commit(batch =>
{
batch.ExpectUnchanged();
batch.Upsert(new ConditionalDriftNarrow { Name = "other" }, new CultRecordHandle<ConditionalDriftNarrow>(new CultRecordKey("other")));
}), Is.True, "ExpectUnchanged failed on a store nobody touched");
}
[Test]
public void UpsertUnderTheCurrentSchemaMovesThePersistedId()
{
SeedDrift(directory: false);
string wide;
using (var writer = Drift(false, WideDrift).Open())
wide = writer.GetStored(DriftKey)!.Descriptor.SchemaId;
using var cache = Drift(false, NarrowDrift).Open();
var loaded = cache.GetStored(DriftKey)!;
Assert.That(loaded.StoredSchemaId, Is.EqualTo(wide), "the entry carries the schema id its record is stored under");
Assert.That(loaded.Descriptor.SchemaId, Is.Not.EqualTo(wide));
Assert.That(DriftCommit(cache, cache.Get(DriftKey)!, 2), Is.True);
var written = cache.GetStored(DriftKey)!;
Assert.That(written.StoredSchemaId, Is.EqualTo(written.Descriptor.SchemaId));
Assert.That(DriftCommit(cache, cache.Get(DriftKey)!, 3), Is.True, "Expect failed on the record this cache just wrote");
}
// The lock is a FileShare.None handle, which excludes another handle in this process exactly as it does one in
// another process, so two store instances on two threads prove the property without a process boundary.
[Test]
@ -872,9 +1002,34 @@ namespace GameCult.Caching.Tests
private static readonly CultDocumentRegistry Registry = CultDocumentRegistry.ForTypes(new[] { typeof(Counter), typeof(Tally), typeof(Slow) });
private static StoreFactory SingleFile(string path) => new(path, () => new SingleFileMessagePackBackingStore(path));
private static StoreFactory SingleFile(string path, CultDocumentRegistry? registry = null) =>
new(path, () => new SingleFileMessagePackBackingStore(path), registry);
private static StoreFactory DirectoryStore(string path) => new(path, () => new DirectoryMessagePackBackingStore(path));
private static StoreFactory DirectoryStore(string path, CultDocumentRegistry? registry = null) =>
new(path, () => new DirectoryMessagePackBackingStore(path), registry);
private static readonly CultRecordKey DriftKey = new("drift");
private static readonly CultDocumentRegistry WideDrift = CultDocumentRegistry.ForTypes(new[] { typeof(ConditionalDriftWide) });
private static readonly CultDocumentRegistry NarrowDrift = CultDocumentRegistry.ForTypes(new[] { typeof(ConditionalDriftNarrow) });
private static readonly CultDocumentRegistry ReusedDrift = CultDocumentRegistry.ForTypes(new[] { typeof(ConditionalDriftReused) });
private StoreFactory Drift(bool directory, CultDocumentRegistry registry) =>
directory ? DirectoryStore(PathOf("drift.cc"), registry) : SingleFile(PathOf("drift.cc"), registry);
// The record at DriftKey, written under v1.
private void SeedDrift(bool directory)
{
using var cache = Drift(directory, WideDrift).Open();
Assert.That(cache.Commit(batch => batch.Upsert(
new ConditionalDriftWide { Name = "drift", Value = 1, Extra = "extra" },
new CultRecordHandle<ConditionalDriftWide>(DriftKey))), Is.True);
}
private static bool DriftCommit(CultCache cache, object observed, int value) => cache.Commit(batch =>
{
batch.Expect(DriftKey, observed);
batch.Upsert(new ConditionalDriftNarrow { Name = "drift", Value = value }, new CultRecordHandle<ConditionalDriftNarrow>(DriftKey));
});
// Pauses a pull between reading the file and handing the records to the cache.
private sealed class PausingStore : SingleFileMessagePackBackingStore
@ -914,17 +1069,20 @@ namespace GameCult.Caching.Tests
{
private readonly Func<CacheBackingStore> _create;
public StoreFactory(string path, Func<CacheBackingStore> create)
private readonly CultDocumentRegistry _registry;
public StoreFactory(string path, Func<CacheBackingStore> create, CultDocumentRegistry? registry = null)
{
Path = path;
_create = create;
_registry = registry ?? Registry;
}
public string Path { get; }
public CultCache Open()
{
var cache = new CultCache(Registry);
var cache = new CultCache(_registry);
cache.AddBackingStore(_create());
return cache;
}
@ -942,6 +1100,49 @@ namespace GameCult.Caching.Tests
public int Value;
}
// One schema at three versions of its type: Narrow dropped Wide's Extra, and Reused put Colour in that slot.
[CultDocument("tests.conditional_drift", "tests.conditional_drift.v1")]
[MessagePackObject(AllowPrivate = true)]
internal sealed class ConditionalDriftWide
{
[Key(0)]
[CultName]
public string Name = string.Empty;
[Key(1)]
public int Value;
[Key(2)]
public string Extra = string.Empty;
}
[CultDocument("tests.conditional_drift", "tests.conditional_drift.v2")]
[MessagePackObject(AllowPrivate = true)]
internal sealed class ConditionalDriftNarrow
{
[Key(0)]
[CultName]
public string Name = string.Empty;
[Key(1)]
public int Value;
}
[CultDocument("tests.conditional_drift", "tests.conditional_drift.v3")]
[MessagePackObject(AllowPrivate = true)]
internal sealed class ConditionalDriftReused
{
[Key(0)]
[CultName]
public string Name = string.Empty;
[Key(1)]
public int Value;
[Key(2)]
public string Colour = string.Empty;
}
[CultDocument("tests.conditional_tally", "tests.conditional_tally.v1")]
[MessagePackObject(AllowPrivate = true)]
internal sealed class Tally

View file

@ -44,7 +44,15 @@ namespace GameCult.Caching.Tests
Json(new CultCellular(new float4(1f, 2f, 3f, 4f), new float4(5f, 6f, 7f, 8f), 0.25f)).Should().Be(
"""{"nearest":{"x":1,"y":2,"z":3,"w":4},"edge":{"x":5,"y":6,"z":7,"w":8},"id":0.25}""");
Json(new CultPhasor(new float4(1f, 2f, 3f, 4f), new float4(5f, 6f, 7f, 8f))).Should().Be(
"""{"cos":{"x":1,"y":2,"z":3,"w":4},"sin":{"x":5,"y":6,"z":7,"w":8}}""");
"""{"cosine":{"x":1,"y":2,"z":3,"w":4},"sine":{"x":5,"y":6,"z":7,"w":8}}""");
Json(new SpanNoise(new float4(1f, 2f, 3f, 4f), 0.25f, 0.5f)).Should().Be(
"""{"field":{"x":1,"y":2,"z":3,"w":4},"curvature":0.25,"fold":0.5}""");
Json(new SpanPath { midpoint = new float3(1f, 2f, 3f), velocity = new float3(4f, 5f, 6f), speed = 7f, acceleration = 8f, halfLength = 9f }).Should().Be(
"""{"midpoint":{"x":1,"y":2,"z":3},"velocity":{"x":4,"y":5,"z":6},"speed":7,"acceleration":8,"halfLength":9}""");
Json(new SpanStage { frequency = 1f, stretch = 2f, axis = new float3(3f, 4f, 5f), shift = new float3(6f, 7f, 8f), offset = new float3(9f, 10f, 11f), octaveStep = new float3(12f, 13f, 14f) }).Should().Be(
"""{"frequency":1,"stretch":2,"axis":{"x":3,"y":4,"z":5},"shift":{"x":6,"y":7,"z":8},"offset":{"x":9,"y":10,"z":11},"octaveStep":{"x":12,"y":13,"z":14}}""");
Json(new CultSiteCells(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 9f, 10f)).Should().Be(
"""{"nearest":{"x":1,"y":2,"z":3,"w":4},"second":{"x":5,"y":6,"z":7,"w":8},"nearestSite":9,"secondSite":10}""");
}
[Test]
@ -69,6 +77,11 @@ namespace GameCult.Caching.Tests
RoundTrip(new rect(-1f, -2f, 5f, 7f));
RoundTrip(new CultCellular(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 0.25f));
RoundTrip(new CultPhasor(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8)));
RoundTrip(new SpanNoise(new float4(1, 2, 3, 4), 0.25f, 0.5f));
RoundTrip(new SpanPath { midpoint = new float3(1f, 2f, 3f), velocity = new float3(4f, 5f, 6f), speed = 7f, acceleration = 8f, halfLength = 9f });
RoundTrip(new SpanStage { frequency = 1f, stretch = 2f, axis = new float3(3f, 4f, 5f), shift = new float3(6f, 7f, 8f), offset = new float3(9f, 10f, 11f), octaveStep = new float3(12f, 13f, 14f) });
RoundTrip(new CultSiteCells(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 9f, 10f));
RoundTrip(new CultSiteCells(new float4(0, 0, 0, 1.0e30f), new float4(0, 0, 0, 1.0e30f), -1f, -1f));
}
[Test]
@ -79,6 +92,87 @@ namespace GameCult.Caching.Tests
Parse<float2?>("null").Should().BeNull();
}
[Test]
public void Reading_AcceptsTheLegacyPhasorNames()
{
// The fixture is what the 0.4.1-era encoder wrote: keys cos/sin.
var path = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "Fixtures", "cultphasor-json-legacy.json");
var legacy = Parse<CultPhasor[]>(System.IO.File.ReadAllText(path));
var current = new[]
{
new CultPhasor(new float4(1f, 2f, 3f, 4f), new float4(5f, 6f, 7f, 8f)),
math.phacelle(new float3(0.3f, 1.7f, -2.2f), new float3(6.2831853f, 0f, 0f), 0.25f, 0.5f),
};
legacy.Should().HaveCount(2);
for (var i = 0; i < 2; i++)
{
BitsOf(legacy[i]).Should().Equal(BitsOf(current[i]));
BitsOf(Parse<CultPhasor>(Json(current[i]))).Should().Equal(BitsOf(current[i]));
}
var caseInsensitive = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }.AddCultMathConverters();
BitsOf(JsonSerializer.Deserialize<CultPhasor>("""{"COS":{"x":1,"y":2,"z":3,"w":4},"Sin":{"x":5,"y":6,"z":7,"w":8}}""", caseInsensitive))
.Should().Equal(BitsOf(current[0]));
}
[Test]
public void Reading_RefusesALegacyAndCurrentNameTogether()
{
var property = typeof(JsonSerializerOptions).GetProperty("AllowDuplicateProperties");
Assert.That(property, Is.Not.Null, "the test runtime's System.Text.Json has AllowDuplicateProperties");
var strict = new JsonSerializerOptions().AddCultMathConverters();
property!.SetValue(strict, false);
Action both = () => JsonSerializer.Deserialize<CultPhasor>("""{"cos":{"x":1},"cosine":{"x":2}}""", strict);
both.Should().Throw<JsonException>().WithMessage("*appears more than once*");
Action reversed = () => JsonSerializer.Deserialize<CultPhasor>("""{"sine":{"x":1},"sin":{"x":2}}""", strict);
reversed.Should().Throw<JsonException>().WithMessage("*appears more than once*");
// With duplicates allowed the later property replaces the earlier one, as for any repeated name.
Parse<CultPhasor>("""{"cos":{"x":1,"y":9},"cosine":{"x":2}}""").cosine.Should().Be(new float4(2f, 0f, 0f, 0f));
}
[Test]
public void Reading_AcceptsTheLegacyPhasorNamesUnderDisallow()
{
var options = new JsonSerializerOptions { UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow }.AddCultMathConverters();
var phasor = JsonSerializer.Deserialize<CultPhasor>("""{"cos":{"x":1,"y":2,"z":3,"w":4},"sin":{"x":5,"y":6,"z":7,"w":8}}""", options);
BitsOf(phasor).Should().Equal(BitsOf(new CultPhasor(new float4(1f, 2f, 3f, 4f), new float4(5f, 6f, 7f, 8f))));
Action unknown = () => JsonSerializer.Deserialize<CultPhasor>("""{"cos":{"x":1},"coss":{"x":2}}""", options);
unknown.Should().Throw<JsonException>().WithMessage("*not a component*");
}
[Test]
public void Reading_TreatsAThirdOccurrenceOfAPhasorNameAsADuplicate()
{
var property = typeof(JsonSerializerOptions).GetProperty("AllowDuplicateProperties");
Assert.That(property, Is.Not.Null, "the test runtime's System.Text.Json has AllowDuplicateProperties");
var strict = new JsonSerializerOptions().AddCultMathConverters();
property!.SetValue(strict, false);
Action thrice = () => JsonSerializer.Deserialize<CultPhasor>("""{"cos":{"x":1},"cosine":{"x":2},"cos":{"x":3}}""", strict);
thrice.Should().Throw<JsonException>().WithMessage("*appears more than once*");
// Allowed, the last occurrence replaces the whole value, including after a third.
Parse<CultPhasor>("""{"cos":{"x":1,"y":9},"cosine":{"x":2},"cos":{"z":3}}""").cosine.Should().Be(new float4(0f, 0f, 3f, 0f));
}
[Test]
public void Reading_SkipsUnknownNamesWhenCaseInsensitive()
{
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }.AddCultMathConverters();
JsonSerializer.Deserialize<CultPhasor>("""{"extra":[1,2],"COSINE":{"x":3},"coss":{"x":4}}""", options).cosine.x.Should().Be(3f);
JsonSerializer.Deserialize<float2>("""{"X":1,"q":2,"Y":3}""", options).Should().Be(new float2(1f, 3f));
}
[Test]
public void Writing_NeverEmitsLegacyNames()
{
using var document = JsonDocument.Parse(Json(new CultPhasor(new float4(1f, 1f, 1f, 1f), new float4(2f, 2f, 2f, 2f))));
document.RootElement.EnumerateObject().Select(p => p.Name).Should().Equal("cosine", "sine");
}
private static int[] BitsOf(CultPhasor v) => new[] { v.cosine.x, v.cosine.y, v.cosine.z, v.cosine.w, v.sine.x, v.sine.y, v.sine.z, v.sine.w }
.Select(BitConverter.SingleToInt32Bits).ToArray();
[Test]
public void Reading_RefusesShapesThatAreNotTheType()
{

View file

@ -102,6 +102,11 @@ namespace GameCult.Caching.Tests
RoundTrip(new rect(-1f, -2f, 5f, 7f));
RoundTrip(new CultCellular(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 0.25f));
RoundTrip(new CultPhasor(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8)));
RoundTrip(new SpanNoise(new float4(1, 2, 3, 4), 0.25f, 0.5f));
RoundTrip(new SpanPath { midpoint = new float3(1f, 2f, 3f), velocity = new float3(4f, 5f, 6f), speed = 7f, acceleration = 8f, halfLength = 9f });
RoundTrip(new SpanStage { frequency = 1f, stretch = 2f, axis = new float3(3f, 4f, 5f), shift = new float3(6f, 7f, 8f), offset = new float3(9f, 10f, 11f), octaveStep = new float3(12f, 13f, 14f) });
RoundTrip(new CultSiteCells(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 9f, 10f));
RoundTrip(new CultSiteCells(new float4(0, 0, 0, 1.0e30f), new float4(0, 0, 0, 1.0e30f), -1f, -1f));
}
[Test]
@ -137,6 +142,30 @@ namespace GameCult.Caching.Tests
"92" +
"94CA3F800000CA40000000CA40400000CA40800000" +
"94CA40A00000CA40C00000CA40E00000CA41000000");
Hex(new SpanNoise(new float4(1f, 2f, 3f, 4f), 0.25f, 0.5f)).Should().Be(
"93" +
"94CA3F800000CA40000000CA40400000CA40800000" +
"CA3E800000" +
"CA3F000000");
Hex(new SpanPath { midpoint = new float3(1f, 2f, 3f), velocity = new float3(4f, 5f, 6f), speed = 7f, acceleration = 8f, halfLength = 9f }).Should().Be(
"95" +
"93CA3F800000CA40000000CA40400000" +
"93CA40800000CA40A00000CA40C00000" +
"CA40E00000CA41000000CA41100000");
Hex(new SpanStage { frequency = 1f, stretch = 2f, axis = new float3(3f, 4f, 5f), shift = new float3(6f, 7f, 8f), offset = new float3(9f, 10f, 11f), octaveStep = new float3(12f, 13f, 14f) }).Should().Be(
"96" +
"CA3F800000" +
"CA40000000" +
"93CA40400000CA40800000CA40A00000" +
"93CA40C00000CA40E00000CA41000000" +
"93CA41100000CA41200000CA41300000" +
"93CA41400000CA41500000CA41600000");
Hex(new CultSiteCells(new float4(1, 2, 3, 4), new float4(5, 6, 7, 8), 9f, 10f)).Should().Be(
"94" +
"94CA3F800000CA40000000CA40400000CA40800000" +
"94CA40A00000CA40C00000CA40E00000CA41000000" +
"CA41100000" +
"CA41200000");
}
[Test]

View file

@ -0,0 +1 @@
[{"cos":{"x":1,"y":2,"z":3,"w":4},"sin":{"x":5,"y":6,"z":7,"w":8}},{"cos":{"x":-5.849812,"y":0.051139403,"z":0.14261721,"w":-0.087419346},"sin":{"x":-2.0218675,"y":0.7666904,"z":-0.22879826,"w":0.9240916}}]

View file

@ -134,6 +134,404 @@ namespace GameCult.Caching.Tests
Assert.That(Refusal(vector), Is.Not.Empty);
}
// The release-now-c2a-bumps-format ruling rests on this: a store stamped with a newer format version is refused at
// open, so this runtime cannot rewrite it. The file stays byte-identical through the refusal and through later
// writes to the cache, whose refused store was never attached.
[TestCase("cultcache.store.v4")]
[TestCase("cultcache.store.v9")]
public async Task SingleFileStampedWithANewerFormatIsRefusedAndNeverRewritten(string newerFormat)
{
var root = CopyFixture("single-file-v1");
try
{
var file = Path.Combine(root, "store.msgpack");
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(file));
snapshot.FormatVersion = newerFormat;
File.WriteAllBytes(file, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
var before = File.ReadAllBytes(file);
using var cache = new CultCache();
var error = Assert.Throws<NotSupportedException>(() =>
cache.AddBackingStore(new SingleFileMessagePackBackingStore(file)))!;
Assert.That(error.Message, Does.Contain(newerFormat));
Assert.That(cache.BackingStores, Is.Empty);
await cache.AddAsync(new PreCut2FixtureNote { Text = "written after the refusal" });
await cache.FlushAsync();
Assert.That(File.ReadAllBytes(file), Is.EqualTo(before));
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
// Two processes: this one attached a v1 store, then a later build rewrote it as v4. A plain flush, a staged write
// and a staged delete must each refuse to downgrade it, leaving the file as the other process wrote it.
[Test]
public async Task SingleFileFlushRefusesAStoreAnotherProcessStampedNewerSinceAttach()
{
var root = CopyFixture("single-file-v1");
try
{
var file = Path.Combine(root, "store.msgpack");
using var cache = new CultCache();
cache.AddBackingStore(new SingleFileMessagePackBackingStore(file));
await cache.PullAllBackingStoresAsync();
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(file));
snapshot.FormatVersion = "cultcache.store.v4";
File.WriteAllBytes(file, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
var before = File.ReadAllBytes(file);
await cache.AddAsync(new PreCut2FixtureNote { Text = "staged after the other process wrote v4" });
Assert.Throws<NotSupportedException>(() => cache.FlushAllBackingStores());
Assert.That(File.ReadAllBytes(file), Is.EqualTo(before));
cache.Remove(new CultRecordKey("item:anvil"));
Assert.Throws<NotSupportedException>(() => cache.BackingStores.Single().PushAll());
Assert.That(File.ReadAllBytes(file), Is.EqualTo(before));
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
// A write set cannot merge with a disk it cannot read: a flush refuses a store whose stamp is unreadable and leaves it
// as it is.
[Test]
public async Task SingleFileFlushRefusesAStoreWhoseStampIsUnreadable()
{
var root = CopyFixture("single-file-v1");
try
{
var file = Path.Combine(root, "store.msgpack");
using var cache = new CultCache();
cache.AddBackingStore(new SingleFileMessagePackBackingStore(file));
await cache.PullAllBackingStoresAsync();
var damaged = new byte[] { 0xc1, 0xc1 };
File.WriteAllBytes(file, damaged);
await cache.AddAsync(new PreCut2FixtureNote { Text = "refused" });
Assert.Throws<CultStoreUnreadableException>(() => cache.FlushAllBackingStores());
Assert.That(File.ReadAllBytes(file), Is.EqualTo(damaged));
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
private static byte[] Raw(params object[] parts)
{
var bytes = new System.Collections.Generic.List<byte>();
foreach (var part in parts)
{
switch (part)
{
case byte single: bytes.Add(single); break;
case string text:
var encoded = System.Text.Encoding.UTF8.GetBytes(text);
bytes.Add(0xd9); bytes.Add((byte)encoded.Length); bytes.AddRange(encoded); break;
case byte[] binary:
bytes.Add(0xc4); bytes.Add((byte)binary.Length); bytes.AddRange(binary); break;
default: throw new ArgumentException(part.GetType().Name);
}
}
return bytes.ToArray();
}
// The format decision comes from the header alone. A stamp this runtime does not read refuses whatever follows it,
// so a body that will not parse can never make a newer store look like damage a flush may heal.
private static System.Collections.Generic.IEnumerable<TestCaseData> NewerStampOverUnreadableBody()
{
byte garbage = 0xc1;
yield return new TestCaseData(Raw((byte)0x93, "cultcache.store.v4", garbage, garbage)).SetName("v4 header over a bad body");
yield return new TestCaseData(Raw((byte)0x93, System.Text.Encoding.UTF8.GetBytes("cultcache.store.v3"), garbage, garbage)).SetName("bin header v3 over a bad body");
yield return new TestCaseData(Raw((byte)0x93, System.Text.Encoding.UTF8.GetBytes("cultcache.store.v9"), garbage, garbage)).SetName("bin header v9 over a bad body");
yield return new TestCaseData(Raw((byte)0x93, "cultcache.store.v4", (byte)0x91, garbage, (byte)0x90)).SetName("v4 header over a bad catalog");
yield return new TestCaseData(Raw((byte)0x92, "cultcache.store.v4", garbage)).SetName("v4 header over garbage");
yield return new TestCaseData(Raw((byte)0x93, "cultcache.store.v5", garbage, garbage)).SetName("v5 header over a bad body");
}
[TestCaseSource(nameof(NewerStampOverUnreadableBody))]
public async Task SingleFileFlushRefusesANewerStampWhateverItsBodyHolds(byte[] swapped)
{
var root = CopyFixture("single-file-v1");
try
{
var file = Path.Combine(root, "store.msgpack");
using var cache = new CultCache();
cache.AddBackingStore(new SingleFileMessagePackBackingStore(file));
await cache.PullAllBackingStoresAsync();
File.WriteAllBytes(file, swapped);
await cache.AddAsync(new PreCut2FixtureNote { Text = "must not overwrite" });
Assert.Throws<NotSupportedException>(() => cache.FlushAllBackingStores());
Assert.That(File.ReadAllBytes(file), Is.EqualTo(swapped));
Assert.Throws<NotSupportedException>(() => new SingleFileMessagePackBackingStore(file).PullAll());
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
[Test]
public async Task DirectoryWritesRefuseANewerStampWhateverTheManifestBodyHolds()
{
var root = CopyFixture("directory-v4");
try
{
var manifest = Path.Combine(root, "store.cc");
using var cache = new CultCache();
cache.AddBackingStore(new DirectoryMessagePackBackingStore(manifest));
await cache.PullAllBackingStoresAsync();
var swapped = Raw((byte)0x93, "cultcache.store.v6.directory-content-addressed-pages", (byte)0xc1, (byte)0xc1);
File.WriteAllBytes(manifest, swapped);
await cache.AddAsync(new PreCut2FixtureNote { Text = "must not overwrite" });
Assert.Throws<NotSupportedException>(() => cache.FlushAllBackingStores());
Assert.That(File.ReadAllBytes(manifest), Is.EqualTo(swapped));
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
// A file that is read but carries no readable stamp (empty, or cut off) is not a store: a flush refuses it, whatever its
// length, and leaves it as it is.
[TestCase(0)]
[TestCase(1)]
[TestCase(10)]
[TestCase(-1)]
public async Task SingleFileFlushRefusesAnEmptyOrTruncatedFile(int keep)
{
var root = CopyFixture("single-file-v1");
try
{
var file = Path.Combine(root, "store.msgpack");
using var cache = new CultCache();
cache.AddBackingStore(new SingleFileMessagePackBackingStore(file));
await cache.PullAllBackingStoresAsync();
var whole = File.ReadAllBytes(file);
var damaged = whole.Take(keep < 0 ? whole.Length / 2 : keep).ToArray();
File.WriteAllBytes(file, damaged);
await cache.AddAsync(new PreCut2FixtureNote { Text = "refused" });
Assert.Throws<CultStoreUnreadableException>(() => cache.FlushAllBackingStores());
Assert.That(File.ReadAllBytes(file), Is.EqualTo(damaged));
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
// A store subclass that overrides nothing beyond its abstract members is guarded by the base, not by an opt-in.
private sealed class PlainCustomStore : SingleFileBackingStore
{
public PlainCustomStore(string path) : base(path) { }
protected override byte[] SerializeStore(string formatVersion, System.Collections.Generic.IReadOnlyList<byte[]> catalogEntries, System.Collections.Generic.IReadOnlyList<byte[]> records) =>
CultDocumentMessagePackSerialization.SerializeStore(formatVersion, catalogEntries, records);
protected override byte[] SerializeRecord(CultPersistedRecord record) =>
CultDocumentMessagePackSerialization.SerializePersistedRecord(record);
protected override byte[] SerializeCatalogEntry(CultSchemaCatalogEntry entry) =>
CultDocumentMessagePackSerialization.SerializeCatalogEntry(entry);
protected override (CultPersistedStoreSnapshot Snapshot, byte[][] CatalogBytes, byte[][] RecordBytes) ReadStore(byte[] data)
{
var store = CultDocumentMessagePackSerialization.ReadStore(data);
CultDocumentMessagePackSerialization.RequireSingleFileFormat(store.Snapshot);
return store;
}
protected override byte[] SerializePayload(object document) =>
CultDocumentMessagePackSerialization.SerializeUntyped(document, document.GetType(), Registry);
protected override object DeserializePayload(Type documentType, byte[] payload) =>
CultDocumentMessagePackSerialization.DeserializeUntyped(documentType, payload, Registry);
}
private static void StampHeader(string file, string header)
{
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(file));
snapshot.FormatVersion = header;
File.WriteAllBytes(file, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
}
[Test]
public async Task CustomSingleFileStoreThatOverridesNothingIsRefusedAtFlushOfANewerStore()
{
var root = CopyFixture("single-file-v1");
try
{
var file = Path.Combine(root, "store.msgpack");
using var cache = new CultCache();
cache.AddBackingStore(new PlainCustomStore(file));
await cache.PullAllBackingStoresAsync();
StampHeader(file, "cultcache.store.v4");
var before = File.ReadAllBytes(file);
await cache.AddAsync(new PreCut2FixtureNote { Text = "staged" });
Assert.Throws<NotSupportedException>(() => cache.FlushAllBackingStores());
Assert.That(File.ReadAllBytes(file), Is.EqualTo(before));
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
// Attach, commit and flush share one rule for which formats are readable: a header the reader refuses at attach is
// refused at flush, whatever its spelling.
[TestCase("cultcache.store.v3-ids")]
[TestCase("cultcache.store.v1000000")]
[TestCase("cultcache.v3")]
[TestCase("cultcache.store.v3")]
[TestCase("cultcache.store.v2")]
[TestCase("cultcache.store.v1")]
public async Task FlushRefusesExactlyTheHeadersAttachRefuses(string header)
{
var root = CopyFixture("single-file-v1");
try
{
var file = Path.Combine(root, "store.msgpack");
using var cache = new CultCache();
cache.AddBackingStore(new SingleFileMessagePackBackingStore(file));
await cache.PullAllBackingStoresAsync();
StampHeader(file, header);
var before = File.ReadAllBytes(file);
bool attachRefuses;
using (var fresh = new CultCache())
{
try { fresh.AddBackingStore(new SingleFileMessagePackBackingStore(file)); attachRefuses = false; }
catch (NotSupportedException) { attachRefuses = true; }
}
await cache.AddAsync(new PreCut2FixtureNote { Text = "staged" });
var flushRefuses = false;
try { cache.FlushAllBackingStores(); }
catch (NotSupportedException) { flushRefuses = true; }
Assert.That(flushRefuses, Is.EqualTo(attachRefuses), header);
if (attachRefuses) Assert.That(File.ReadAllBytes(file), Is.EqualTo(before), header);
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
// The refusal comes from the read, not from a failed write onto the held file: the store never reaches serialising.
private sealed class WriteCountingStore : SingleFileMessagePackBackingStore
{
public int Serialisations;
public WriteCountingStore(string path) : base(path) { }
protected override byte[] SerializeStore(string formatVersion, System.Collections.Generic.IReadOnlyList<byte[]> catalogEntries, System.Collections.Generic.IReadOnlyList<byte[]> records)
{
Serialisations++;
return base.SerializeStore(formatVersion, catalogEntries, records);
}
}
// The public parser judges no stamp, as in 1.0.61: a v4 directory manifest and a v3 header both parse.
[Test]
public void PublicParserReadsAnyStampAsEveryReleaseHas()
{
var root = CopyFixture("directory-v4");
try
{
var manifest = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(Path.Combine(root, "store.cc")));
Assert.That(manifest.FormatVersion, Is.EqualTo("cultcache.store.v4.directory-content-addressed-pages"));
var v3 = new CultPersistedStoreSnapshot { FormatVersion = "cultcache.store.v3", SchemaCatalog = Array.Empty<CultSchemaCatalogEntry>(), Records = Array.Empty<CultPersistedRecord>() };
var parsed = CultDocumentMessagePackSerialization.DeserializeSnapshot(CultDocumentMessagePackSerialization.SerializeSnapshot(v3));
Assert.That(parsed.FormatVersion, Is.EqualTo("cultcache.store.v3"));
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
// A read that fails on I/O is not an unreadable stamp to heal over: the flush refuses and the file is untouched.
[Test]
public async Task SingleFileFlushRefusesWhenReadingTheDiskFailsOnIO()
{
var root = CopyFixture("single-file-v1");
try
{
var file = Path.Combine(root, "store.msgpack");
using var cache = new CultCache();
var store = new WriteCountingStore(file);
cache.AddBackingStore(store);
await cache.PullAllBackingStoresAsync();
var before = File.ReadAllBytes(file);
await cache.AddAsync(new PreCut2FixtureNote { Text = "staged" });
store.Serialisations = 0;
using (new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
Assert.Throws<IOException>(() => cache.FlushAllBackingStores());
}
Assert.That(store.Serialisations, Is.Zero, "the refusal is the read failing, not the write onto the held file failing");
Assert.That(File.ReadAllBytes(file), Is.EqualTo(before));
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
[TestCase("cultcache.store.v6.directory-content-addressed-pages")]
[TestCase("cultcache.store.v9")]
public async Task DirectoryWritesRefuseAStoreAnotherProcessStampedNewerSinceAttach(string newer)
{
var root = CopyFixture("directory-v4");
try
{
var manifest = Path.Combine(root, "store.cc");
using var cache = new CultCache();
cache.AddBackingStore(new DirectoryMessagePackBackingStore(manifest));
await cache.PullAllBackingStoresAsync();
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(manifest));
snapshot.FormatVersion = newer;
File.WriteAllBytes(manifest, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
Func<System.Collections.Generic.Dictionary<string, byte[]>> files = () => Directory
.GetFiles(root, "*", SearchOption.AllDirectories)
.Where(path => !path.EndsWith(".lock", StringComparison.Ordinal))
.ToDictionary(path => path, File.ReadAllBytes);
var before = files();
await cache.AddAsync(new PreCut2FixtureNote { Text = "staged after the other process wrote the newer format" });
Assert.Throws<NotSupportedException>(() => cache.FlushAllBackingStores());
Assert.That(files().Keys, Is.EquivalentTo(before.Keys));
foreach (var pair in before) Assert.That(File.ReadAllBytes(pair.Key), Is.EqualTo(pair.Value), pair.Key);
cache.Remove(new CultRecordKey("item:anvil"));
Assert.Throws<NotSupportedException>(() => cache.FlushAllBackingStores());
Assert.That(files().Keys, Is.EquivalentTo(before.Keys));
foreach (var pair in before) Assert.That(File.ReadAllBytes(pair.Key), Is.EqualTo(pair.Value), pair.Key);
}
finally
{
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
}
}
[Test]
public void SingleFileRefusesExtraRecordSlotNamingTheRecord()
{
@ -234,6 +632,28 @@ namespace GameCult.Caching.Tests
}
}
// The stamp decides readability and the body never does: a newer stamp is named whatever follows it, without the body parsed.
[Test]
public void ReadStoreNamesANewerSingleFileStampWithoutParsingTheBody()
{
var garbage = (byte)0xc1;
var bytes = Raw((byte)0x93, "cultcache.store.v4", garbage, garbage);
var error = Assert.Throws<CultStoreUnreadableException>(() =>
CultDocumentMessagePackSerialization.ReadStore(bytes, CultDocumentMessagePackSerialization.RequireReadableSingleFileStamp))!;
Assert.That(error.Message, Does.Contain("format cultcache.store.v4 is not readable"));
}
// A snapshot with no format version has no stamp to write, so serialising it is refused rather than writing a nil slot 0.
[Test]
public void SerializeSnapshotRefusesASnapshotWithNoFormatVersion()
{
var snapshot = new CultPersistedStoreSnapshot { FormatVersion = null! };
Assert.Throws<ArgumentException>(() => CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
}
[Test]
public void V1StoreWrittenAtTheBaseCommitStillDecodesByteForByte()
{

View file

@ -971,6 +971,52 @@ namespace GameCult.Caching.Tests
Assert.That(ReadStore(path).Records.Single(record => record.Key == DriftBase.Value).SchemaId, Is.EqualTo(DriftWideId));
}
[Test]
public void ADriftedVariantSatisfiesExpectUnchanged()
{
var path = PathOf("drift.cc");
WriteWideVariant(path);
using var narrow = Open(path, registry: CultDocumentRegistry.ForTypes(new[] { typeof(DriftNarrow) }));
Assert.That(ExpectVariantCommit(narrow), Is.True, "an unchanged drifted variant failed Expect and ExpectUnchanged");
}
[Test]
public void AnOwnFlushKeepsADriftedVariantsExpectHolding()
{
var path = PathOf("drift.cc");
WriteWideVariant(path);
using var narrow = Open(path, registry: CultDocumentRegistry.ForTypes(new[] { typeof(DriftNarrow) }));
narrow.BackingStores[0].PushAll();
Assert.That(ExpectVariantCommit(narrow), Is.True, "Expect on a drifted variant failed after this cache's own flush rewrote it");
}
private static void WriteWideVariant(string path)
{
using var writer = Open(path, registry: CultDocumentRegistry.ForTypes(new[] { typeof(DriftWide) }));
writer.Commit(batch =>
{
batch.Upsert(typeof(DriftWide), new DriftWide { Name = "drift", Power = 1, Wing = "base wing" }, new CultRecordKey("drift-base"));
batch.UpsertVariant(new CultRecordKey("drift-variant"), new CultRecordKey("drift-base"), new[]
{
writer.Override<DriftWide>(nameof(DriftWide.Name), "drift variant"),
writer.Override<DriftWide>(nameof(DriftWide.Wing), "stale wing")
});
});
}
private static bool ExpectVariantCommit(CultCache cache)
{
var variant = new CultRecordKey("drift-variant");
return cache.Commit(batch =>
{
batch.Expect(variant, cache.Get(variant));
batch.ExpectUnchanged();
batch.Upsert(typeof(DriftNarrow), new DriftNarrow { Name = "other", Power = 2 }, new CultRecordKey("other"));
});
}
[Test]
public void AnOverrideOfASlotTheTypeNeverHadIsReportedOnEveryLoadAndStaysStoredUntilTheVariantIsWritten()
{
@ -1192,6 +1238,40 @@ namespace GameCult.Caching.Tests
Assert.That(reopened.Get<VariantGear>(BigKey)!.Name, Is.EqualTo("laser big"));
}
// The cache holds a copy of the base another writer has since renamed; the merge is judged on the renamed base.
[Test]
public void AConditionalCommitIsJudgedOnAnotherWritersChangeToARecordThisCacheHolds()
{
var path = PathOf("gear.cc");
var other = new CultRecordKey("other");
using (var seed = Open(path))
Assert.That(seed.Commit(batch =>
{
batch.Upsert(typeof(VariantGear), Laser(), BaseKey);
batch.Upsert(typeof(VariantGear), Named("other", "o1"), other);
}), Is.True);
using (var a = Open(path))
{
using (var w = Open(path))
Assert.That(w.Commit(batch => batch.Upsert(typeof(VariantGear), Named("x", "l1"), BaseKey)), Is.True);
var refused = Refused(() => a.Commit(batch =>
{
batch.Expect(other, a.Get(other));
batch.UpsertVariant(BigKey, BaseKey, new[]
{
a.Override<VariantGear>(nameof(VariantGear.Name), "x"),
a.Override<VariantGear>(nameof(VariantGear.Code), "big")
});
}));
Assert.That(refused.Message, Does.Contain(BigKey.Value).And.Contain(BaseKey.Value).And.Contain("x"));
}
using var reopened = Open(path, readOnly: true);
Assert.That(reopened.GetStored(BigKey), Is.Null, "nothing landed on the file");
}
[Test]
public void AConditionalCommitThatIsSoundOntoAVariantStoreAnotherWriterChangedIsRefusedThenLandsOnRetry()
{

View file

@ -2,10 +2,12 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using FluentAssertions;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using GameCult.Networking;
using MessagePack;
using NUnit.Framework;
@ -34,6 +36,8 @@ public sealed class CultMeshContentVectorTests
if (Environment.GetEnvironmentVariable("CULTNET_WRITE_VECTORS") != "1")
Assert.Ignore("Set CULTNET_WRITE_VECTORS=1 to (re)write the committed vector file.");
File.WriteAllText(VectorPath("content-vectors.cs-written.json"), ToJson(BuildVectors(out _, out _)));
File.WriteAllText(VectorPath("cdn-record-key-vectors.json"), RecordKeyVectorsToJson(BuildRecordKeyVectors()));
File.WriteAllText(VectorPath("content-acceptance-vectors.json"), AcceptanceVectorsToJson(BuildAcceptanceVectors()));
}
[Test]
@ -69,7 +73,7 @@ public sealed class CultMeshContentVectorTests
Reencode(response).Should().Equal(vector.Bytes, vector.Label);
break;
case "manifest":
var manifest = MessagePackSerializer.Deserialize<CultMeshCdnArtifactManifest>(vector.Bytes, CultNetSchemaMessageSerialization.Options);
var manifest = ReadManifest(vector.Bytes);
manifest.Should().BeEquivalentTo((CultMeshCdnArtifactManifest)expected);
Reencode(manifest).Should().Equal(vector.Bytes, vector.Label);
break;
@ -98,6 +102,344 @@ public sealed class CultMeshContentVectorTests
rust.Bytes.Should().Equal(committed.Bytes, "Rust's pack_content and the reference pack the same bytes to the same manifest");
}
[Test]
public void CommittedRecordKeyVectorsEqualAFreshDerivation()
{
var path = VectorPath("cdn-record-key-vectors.json");
File.Exists(path).Should().BeTrue($"{path} is written by this fixture under CULTNET_WRITE_VECTORS=1");
Lines(File.ReadAllText(path)).Should().Be(Lines(RecordKeyVectorsToJson(BuildRecordKeyVectors())), "the key grammar drifted from the committed vectors");
}
[Test]
public void TypeScriptManifestVectorsMatchTheReference()
{
var path = VectorPath("content-vectors.ts-written.json");
File.Exists(path).Should().BeTrue($"{path} is written by scripts/write-cultmesh-content-vectors.mjs");
using var document = JsonDocument.Parse(File.ReadAllText(path));
var vectors = document.RootElement.GetProperty("vectors").EnumerateArray().ToList();
vectors.Should().NotBeEmpty();
foreach (var vector in vectors)
{
var label = vector.GetProperty("label").GetString()!;
var bytes = Convert.FromBase64String(vector.GetProperty("messagePackBase64").GetString()!);
var manifest = ReadManifest(bytes);
Reencode(manifest).Should().Equal(bytes, $"{label}: the reference reads and rewrites the TypeScript bytes unchanged");
CultMeshCdnArtifactManifest.CreateRecordKey(manifest).Value.Should().Be(vector.GetProperty("recordKey").GetString(), label);
var input = vector.GetProperty("input");
var body = input.GetProperty("body");
var multiplier = body.GetProperty("multiplier").GetInt64();
var modulus = body.GetProperty("modulus").GetInt64();
var packed = CultMeshCdn.PackArtifact(
input.GetProperty("artifactId").GetString()!,
Enumerable.Range(0, body.GetProperty("length").GetInt32()).Select(i => (byte)(i * multiplier % modulus)).ToArray(),
new CultMeshCdnPackOptions
{
Kind = input.GetProperty("kind").GetString()!,
Version = input.GetProperty("version").GetString()!,
MimeType = input.GetProperty("mimeType").GetString()!,
CreatedAtUtc = input.GetProperty("createdAtUtc").GetString()!,
ChunkSizeBytes = input.GetProperty("chunkSizeBytes").GetInt32(),
Tags = input.GetProperty("tags").EnumerateArray().Select(t => t.GetString()!).ToArray(),
Metadata = input.GetProperty("metadata").EnumerateArray()
.Aggregate(new Dictionary<string, string>(), (map, pair) =>
{
map[pair[0].GetString()!] = pair[1].GetString()!;
return map;
})
});
Reencode(packed.Manifest).Should().Equal(bytes, $"{label}: the reference packs the declared input to the TypeScript bytes");
}
}
[Test]
public void CommittedAcceptanceVectorsEqualAFreshRun()
{
var path = VectorPath("content-acceptance-vectors.json");
File.Exists(path).Should().BeTrue($"{path} is written by this fixture under CULTNET_WRITE_VECTORS=1");
var fresh = BuildAcceptanceVectors();
fresh.Select(c => c.Label).Should().OnlyHaveUniqueItems();
fresh.Count(c => c.Accepted).Should().BeGreaterThan(30);
fresh.Count(c => !c.Accepted).Should().BeGreaterThan(30);
Lines(File.ReadAllText(path)).Should().Be(Lines(AcceptanceVectorsToJson(fresh)), "the reference's acceptance drifted from the committed vectors");
}
private sealed record Acceptance(string Label, byte[] Input, bool Accepted, byte[]? Reencoded, string? RecordKey);
/// <summary>What the reference does with these bytes: deserialise, then <c>ValidateManifest</c>; accepted bytes are rewritten and keyed.</summary>
private static Acceptance Judge(string label, byte[] input)
{
CultMeshCdnArtifactManifest manifest;
try
{
manifest = ReadManifest(input);
CultMeshCdn.ValidateManifest(manifest);
}
catch (Exception)
{
return new Acceptance(label, input, false, null, null);
}
string? key = null;
try { key = CultMeshCdnArtifactManifest.CreateRecordKey(manifest).Value; }
catch (ArgumentException) { }
return new Acceptance(label, input, true, Reencode(manifest), key);
}
private static byte[] Deep(int depth) => Cat(Enumerable.Repeat((byte)0x91, depth).ToArray(), Nil);
private static byte[] Cat(params byte[][] parts) => parts.SelectMany(p => p).ToArray();
private static byte[] Raw(params byte[] bytes) => bytes;
private static readonly byte[] Nil = { 0xc0 };
private static byte[] Str(string text)
{
var bytes = Encoding.UTF8.GetBytes(text);
return Cat(bytes.Length < 32 ? Raw((byte)(0xa0 | bytes.Length)) : Raw(0xd9, (byte)bytes.Length), bytes);
}
private static byte[] StrRaw(params byte[] bytes) => Cat(Raw((byte)(0xa0 | bytes.Length)), bytes);
private static byte[] Arr(params byte[][] items) => Cat(Raw((byte)(0x90 | items.Length)), Cat(items));
private static byte[] MapOf(params byte[][] pairs) => Cat(Raw((byte)(0x80 | (pairs.Length / 2))), Cat(pairs));
private static byte[] Be(byte code, long value, int width)
{
var bytes = new byte[width];
for (var i = 0; i < width; i++) bytes[width - 1 - i] = (byte)(value >> (8 * i));
return Cat(Raw(code), bytes);
}
private static byte[] F64(long bits) => Be(0xcb, bits, 8);
private static byte[] F32(int bits) => Be(0xca, bits, 4);
private static byte[][] BaseFields() => new[]
{
Str("a/b"), Str("asset"), Str("1"), Str(EmptyHash), Raw(0x00), Str("application/x-t"), Str("t"),
Arr(Chunk(Raw(0x00), Raw(0x00))), Arr(Str("x")), MapOf(Str("k"), Str("v"))
};
private const string EmptyHash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
private static byte[] Chunk(byte[] offset, byte[] size) => Arr(Str(EmptyHash), offset, size, Str("k"));
private static byte[] Doc(IEnumerable<byte[]> fields)
{
var list = fields.ToArray();
return Cat(Raw((byte)(0x90 | list.Length)), Cat(list));
}
private static byte[][] With(params (int Index, byte[] Value)[] edits)
{
var fields = BaseFields();
foreach (var (index, value) in edits) fields[index] = value;
return fields;
}
/// <summary>
/// Byte shapes at the edge of what MessagePack-CSharp reads: nil in reference slots, missing and extra slots,
/// trailing bytes, integer and float families, string families and invalid UTF-8. The reference judges each one;
/// the TypeScript decoder is held to the verdict and to the bytes the reference writes back.
/// </summary>
private static List<Acceptance> BuildAcceptanceVectors()
{
var cases = new List<Acceptance>();
void Add(string label, byte[] input) => cases.Add(Judge(label, input));
void AddFields(string label, params (int Index, byte[] Value)[] edits) => Add(label, Doc(With(edits)));
var fields = BaseFields();
Add("base", Doc(fields));
for (var count = 0; count <= 9; count++) Add($"short_{count}", Doc(fields.Take(count)));
Add("array16_header", Cat(Raw(0xdc, 0, 10), Cat(fields)));
Add("array32_header", Cat(Raw(0xdd, 0, 0, 0, 10), Cat(fields)));
Add("extra_11_nil", Doc(fields.Append(Nil)));
Add("extra_11_str", Doc(fields.Append(Str("x"))));
Add("extra_11_nested", Doc(fields.Append(Arr(Arr(Str("x")), MapOf(Str("a"), F64(0))))));
Add("extra_11_ext", Doc(fields.Append(Raw(0xd4, 1, 2))));
Add("extra_11_ext8", Doc(fields.Append(Raw(0xc7, 2, 1, 7, 7))));
Add("extra_11_bin", Doc(fields.Append(Raw(0xc4, 2, 1, 2))));
Add("extra_11_float", Doc(fields.Append(F32(0))));
Add("extra_11_uint64", Doc(fields.Append(Be(0xcf, 7, 8))));
Add("extra_11_array16", Doc(fields.Append(Cat(Raw(0xdc, 0, 2), Raw(1), Raw(2)))));
Add("extra_11_map16", Doc(fields.Append(Cat(Raw(0xde, 0, 1), Raw(1), Raw(2)))));
Add("extra_11_str8", Doc(fields.Append(Raw(0xd9, 1, 0x41))));
Add("extra_12", Doc(fields.Append(Nil).Append(Str("y"))));
Add("extra_11_reserved_code", Doc(fields.Append(Raw(0xc1))));
Add("extra_11_truncated", Doc(fields.Append(Raw(0x92, 1))));
// The production reader refuses payloads nested past CultPayloadDepth (256); the extra slot is skipped, so only that rule can refuse it.
foreach (var depth in new[] { 250, 253, 254, 255, 256, 257, 300 })
{
Add($"deep_extra_{depth}", Doc(fields.Append(Deep(depth))));
AddFields($"deep_chunkextra_{depth}", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Str("k"), Deep(depth)))));
}
AddFields("chunk_3", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0)))));
AddFields("chunk_5", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Str("k"), Nil))));
AddFields("chunk_5_nested", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Str("k"), Arr(Raw(1), Raw(2))))));
// An extra slot inside a chunk reference is followed by more bytes, so a skip that stops short shows.
var extras = new (string Name, byte[] Value)[]
{
("map", MapOf(Str("a"), Str("b"), Str("c"), Str("d"))), ("map16", Cat(Raw(0xde, 0, 2), Raw(1), Raw(2), Raw(3), Raw(4))),
("map32", Cat(Raw(0xdf, 0, 0, 0, 1), Raw(1), Raw(2))), ("array", Arr(Raw(1), Raw(2), Raw(3))),
("array16", Cat(Raw(0xdc, 0, 2), Raw(1), Raw(2))), ("array32", Cat(Raw(0xdd, 0, 0, 0, 1), Raw(1))),
("fixext1", Raw(0xd4, 1, 2)), ("fixext2", Raw(0xd5, 1, 2, 3)), ("fixext4", Raw(0xd6, 1, 2, 3, 4, 5)),
("fixext8", Raw(0xd7, 1, 2, 3, 4, 5, 6, 7, 8, 9)), ("fixext16", Cat(Raw(0xd8, 1), new byte[16])),
("ext8", Raw(0xc7, 2, 1, 7, 7)), ("ext16", Raw(0xc8, 0, 2, 1, 7, 7)), ("ext32", Raw(0xc9, 0, 0, 0, 2, 1, 7, 7)),
("bin8", Raw(0xc4, 2, 1, 2)), ("bin16", Raw(0xc5, 0, 2, 1, 2)), ("bin32", Raw(0xc6, 0, 0, 0, 2, 1, 2)),
("str8", Raw(0xd9, 2, 0x41, 0x42)), ("str16", Raw(0xda, 0, 2, 0x41, 0x42)), ("str32", Raw(0xdb, 0, 0, 0, 2, 0x41, 0x42)),
("fixstr", Str("ab")), ("f32", F32(1)), ("f64", F64(1)), ("u8", Raw(0xcc, 1)), ("u16", Be(0xcd, 1, 2)), ("u32", Be(0xce, 1, 4)),
("u64", Be(0xcf, 1, 8)), ("i8", Raw(0xd0, 1)), ("i16", Be(0xd1, 1, 2)), ("i32", Be(0xd2, 1, 4)), ("i64", Be(0xd3, 1, 8)),
("true", Raw(0xc3)), ("false", Raw(0xc2)), ("nil", Nil), ("negfixint", Raw(0xff)), ("reserved", Raw(0xc1)),
("fixint_max", Raw(0x7f)), ("negfixint_min", Raw(0xe0)), ("fixstr_31", Cat(Raw(0xbf), new byte[31])),
("fixmap_15", Cat(Raw(0x8f), Cat(Enumerable.Range(0, 15).Select(_ => Raw(1, 2)).ToArray()))), ("fixarray_15", Cat(Raw(0x9f), new byte[15])),
("nested", Arr(MapOf(Str("a"), Arr(Raw(1), Raw(2))), Arr()))
};
foreach (var (name, value) in extras)
AddFields($"chunk_extra_{name}", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Str("k"), value))));
AddFields("chunk_1", (7, Arr(Arr(Str(EmptyHash)))));
AddFields("chunk_0", (7, Arr(Arr())));
AddFields("chunk_is_map", (7, Arr(MapOf(Str("a"), Str("b")))));
AddFields("chunk_is_str", (7, Arr(Str("a"))));
AddFields("chunks_empty_with_size", (7, Arr()));
AddFields("chunks_empty_size_zero", (7, Arr()), (4, Raw(0)));
AddFields("chunks_is_str", (7, Str("a")));
AddFields("chunks_is_map", (7, MapOf()));
AddFields("chunks_gap", (7, Arr(Chunk(Raw(1), Raw(0)))));
foreach (var (index, name) in new[] { (0, "artifactId"), (1, "kind"), (2, "version"), (3, "contentHash"), (5, "mimeType"), (6, "createdAtUtc") })
AddFields($"nil_{name}", (index, Nil));
AddFields("nil_chunks", (7, Nil));
AddFields("nil_chunk_element", (7, Arr(Nil)));
AddFields("nil_chunk_hash", (7, Arr(Arr(Nil, Raw(0), Raw(0), Str("k")))));
AddFields("nil_chunk_recordKey", (7, Arr(Arr(Str(EmptyHash), Raw(0), Raw(0), Nil))));
AddFields("nil_tags", (8, Nil));
AddFields("nil_tag_element", (8, Arr(Nil, Str("x"))));
AddFields("nil_metadata", (9, Nil));
AddFields("nil_metadata_value", (9, MapOf(Str("k"), Nil)));
AddFields("nil_metadata_key", (9, MapOf(Nil, Str("v"))));
AddFields("nil_size", (4, Nil));
AddFields("metadata_duplicate_key", (9, MapOf(Str("k"), Str("1"), Str("k"), Str("2"))));
AddFields("metadata_integer_like_keys", (9, MapOf(Str("10"), Str("a"), Str("alpha"), Str("b"), Str("2"), Str("c"))));
AddFields("metadata_int_key", (9, MapOf(Raw(5), Str("v"))));
AddFields("metadata_int_value", (9, MapOf(Str("k"), Raw(5))));
AddFields("metadata_empty_key", (9, MapOf(Str(""), Str("v"))));
AddFields("metadata_proto_key", (9, MapOf(Str("__proto__"), Str("v"))));
AddFields("metadata_map16", (9, Cat(Raw(0xde, 0, 1), Str("k"), Str("v"))));
AddFields("metadata_map32", (9, Cat(Raw(0xdf, 0, 0, 0, 1), Str("k"), Str("v"))));
AddFields("metadata_is_array", (9, Arr()));
AddFields("metadata_is_str", (9, Str("k")));
AddFields("tags_is_map", (8, MapOf()));
AddFields("tags_int_element", (8, Arr(Raw(5))));
AddFields("tags_array16", (8, Cat(Raw(0xdc, 0, 1), Str("x"))));
Add("trailing_nil", Cat(Doc(fields), Nil));
Add("trailing_reserved_code", Cat(Doc(fields), Raw(0xc1)));
Add("trailing_truncated_array", Cat(Doc(fields), Raw(0x92)));
Add("top_nil", Nil);
Add("top_empty", Array.Empty<byte>());
Add("top_map", MapOf(Str("a"), Str("b")));
Add("top_str", Str("a"));
Add("top_int", Raw(5));
Add("top_truncated", Doc(fields)[..^3]);
foreach (var (name, zero) in new (string, byte[])[]
{
("u8", Raw(0xcc, 0)), ("u16", Be(0xcd, 0, 2)), ("u32", Be(0xce, 0, 4)), ("u64", Be(0xcf, 0, 8)),
("i8", Raw(0xd0, 0)), ("i16", Be(0xd1, 0, 2)), ("i32", Be(0xd2, 0, 4)), ("i64", Be(0xd3, 0, 8)),
("f32", F32(0)), ("f32_negzero", F32(int.MinValue)), ("f64", F64(0)), ("f64_negzero", F64(long.MinValue)),
("f64_one", F64(0x3FF0000000000000)),
("true", Raw(0xc3)), ("false", Raw(0xc2)), ("str", Str("0")), ("bin", Raw(0xc4, 1, 0)), ("array", Arr()), ("ext", Raw(0xd4, 1, 0)),
// Zero-filled so that a reader which took them for an int32 would read 0.
("fixext4", Cat(Raw(0xd6), new byte[5])), ("fixext8", Cat(Raw(0xd7), new byte[9])), ("fixext16", Cat(Raw(0xd8), new byte[17]))
})
{
AddFields($"size_{name}", (4, zero));
AddFields($"offset_{name}", (7, Arr(Chunk(zero, Raw(0)))));
AddFields($"chunksize_{name}", (7, Arr(Chunk(Raw(0), zero))));
}
AddFields("size_negative", (4, Raw(0xff)), (7, Arr()));
AddFields("size_u64_over_long", (4, Be(0xcf, -1, 8)), (7, Arr()));
AddFields("size_i64_min", (4, Be(0xd3, long.MinValue, 8)), (7, Arr()));
AddFields("size_2p53_minus_1", (4, Be(0xcf, (1L << 53) - 1, 8)), (7, Arr()));
AddFields("chunksize_int_max", (4, Be(0xce, int.MaxValue, 4)), (7, Arr(Chunk(Raw(0), Be(0xce, int.MaxValue, 4)))));
AddFields("chunksize_2p31", (4, Be(0xce, 1L << 31, 4)), (7, Arr(Chunk(Raw(0), Be(0xce, 1L << 31, 4)))));
AddFields("chunksize_i32_min", (4, Raw(0)), (7, Arr(Chunk(Raw(0), Be(0xd2, int.MinValue, 4)))));
AddFields("chunksize_i64_below_i32", (4, Raw(0)), (7, Arr(Chunk(Raw(0), Be(0xd3, (long)int.MinValue - 1, 8)))));
AddFields("offset_beyond_int32",
(4, Be(0xcf, 3L * int.MaxValue, 8)),
(7, Arr(Chunk(Raw(0), Be(0xce, int.MaxValue, 4)), Chunk(Be(0xce, int.MaxValue, 4), Be(0xce, int.MaxValue, 4)),
Chunk(Be(0xce, 2L * int.MaxValue, 4), Be(0xce, int.MaxValue, 4)))));
AddFields("chunks_out_of_order",
(4, Raw(2)), (7, Arr(Chunk(Raw(1), Raw(1)), Chunk(Raw(0), Raw(1)))));
AddFields("chunks_overlap", (4, Raw(2)), (7, Arr(Chunk(Raw(0), Raw(2)), Chunk(Raw(1), Raw(1)))));
AddFields("chunk_negative_size", (4, Raw(0)), (7, Arr(Chunk(Raw(0), Raw(0xff)))));
AddFields("str_bin", (1, Raw(0xc4, 1, 0x41)));
AddFields("str_ext", (1, Raw(0xd4, 1, 0x41)));
AddFields("str_int", (1, Raw(0x41)));
AddFields("str_str16", (1, Raw(0xda, 0, 1, 0x41)));
AddFields("str_str32", (1, Raw(0xdb, 0, 0, 0, 1, 0x41)));
AddFields("str_empty", (1, Str("")));
AddFields("str_invalid_utf8", (1, StrRaw(0xFF, 0xFE)));
AddFields("str_lone_surrogate_cesu", (1, StrRaw(0xED, 0xA0, 0x80)));
AddFields("str_overlong", (1, StrRaw(0xC0, 0xAF)));
AddFields("str_truncated_sequence", (1, StrRaw(0xE2, 0x82)));
AddFields("str_bom", (0, Str("bom")));
AddFields("str_nul", (0, StrRaw(0x61, 0x00, 0x62)));
AddFields("id_invalid_utf8", (0, StrRaw(0xFF)));
AddFields("hash_invalid_utf8", (3, StrRaw(0xFF)));
AddFields("version_invalid_utf8", (2, StrRaw(0xFF, 0xFE)));
AddFields("id_blank", (0, Str(" ")));
AddFields("hash_blank", (3, Str(" ")));
AddFields("hash_prefix_upper_long_s", (3, Str("ſha256:abc")));
// Shapes that end early, and header families a lenient reader would take for another.
var whole = Doc(fields);
Add("truncated_string_body", whole[..^1]);
Add("truncated_str8_length", Raw(0x91, 0xd9));
Add("truncated_u16", Cat(Raw(0x95), Str("a"), Str("k"), Str("v"), Str(EmptyHash), Raw(0xcd, 0)));
Add("truncated_u64", Cat(Raw(0x95), Str("a"), Str("k"), Str("v"), Str(EmptyHash), Raw(0xcf, 0, 0, 0)));
Add("truncated_array16", Raw(0xdc, 0));
Add("extra_11_truncated_string", Doc(fields.Append(Raw(0xa5, 0x41))));
Add("extra_11_truncated_str8_length", Doc(fields.Append(Raw(0xd9))));
Add("array_15", Doc(fields.Concat(Enumerable.Repeat(Nil, 5))));
AddFields("metadata_15_entries", (9, Cat(Raw(0x8f), Cat(Enumerable.Range(0, 15).Select(i => Cat(Str($"k{i}"), Str("v"))).ToArray()))));
Add("tags_fixint_then_trailing", Cat(Raw(0x99), Cat(fields[..8]), Raw(1), Str("a")));
Add("tags_fixmap", Cat(Raw(0x99), Cat(fields[..8]), MapOf(Str("a"), Str("b"))));
Add("metadata_fixint_then_trailing", Cat(Raw(0x9a), Cat(fields[..9]), Raw(1), Str("a"), Str("b")));
Add("metadata_array_then_trailing", Cat(Raw(0x9a), Cat(fields[..9]), Arr(Str("a"), Str("b")), Str("c"), Str("d")));
// Every integer family at a value that needs its full width and its own signedness: as the sizes, then as an offset.
foreach (var (name, value, n) in new (string, byte[], long)[]
{
("u8_200", Raw(0xcc, 200), 200), ("u16_258", Be(0xcd, 258, 2), 258), ("u16_40000", Be(0xcd, 40000, 2), 40000),
("u32_258", Be(0xce, 258, 4), 258), ("u64_258", Be(0xcf, 258, 8), 258), ("i8_100", Raw(0xd0, 100), 100),
("i16_258", Be(0xd1, 258, 2), 258), ("i32_258", Be(0xd2, 258, 4), 258), ("i64_258", Be(0xd3, 258, 8), 258),
("fixint_127", Raw(0x7f), 127)
})
{
AddFields($"width_{name}", (4, value), (7, Arr(Chunk(Raw(0), value))));
AddFields($"width_{name}_offset", (4, Be(0xcd, n + 1, 2)), (7, Arr(Chunk(Raw(0), Be(0xcd, n, 2)), Chunk(value, Raw(1)))));
}
AddFields("width_u32_over_int32", (4, Be(0xce, 3_000_000_000, 4)),
(7, Arr(Chunk(Raw(0), Be(0xce, int.MaxValue, 4)), Chunk(Be(0xce, int.MaxValue, 4), Be(0xce, 3_000_000_000 - int.MaxValue, 4)))));
AddFields("width_negative_fixint", (4, Raw(0xff)));
AddFields("width_negative_fixint_min", (4, Raw(0xe0)));
AddFields("width_negative_i64_safe", (4, Be(0xd3, -((1L << 53) - 1), 8)));
AddFields("width_negative_i64_unsafe", (4, Be(0xd3, -(1L << 53), 8)));
return cases;
}
private static string AcceptanceVectorsToJson(List<Acceptance> cases) =>
JsonSerializer.Serialize(
new
{
cases = cases.Select(c => new
{
label = c.Label,
inputBase64 = Convert.ToBase64String(c.Input),
accepted = c.Accepted,
reencodedBase64 = c.Reencoded == null ? null : Convert.ToBase64String(c.Reencoded),
recordKey = c.RecordKey
})
},
new JsonSerializerOptions { WriteIndented = true });
private static byte[] Body() =>
Enumerable.Range(0, BodyLength).Select(i => (byte)(i % 251)).ToArray();
@ -115,8 +457,12 @@ public sealed class CultMeshContentVectorTests
private static byte[] Reencode(CultMeshContentChunkResponseMessage message) =>
CultNetSchemaMessageSerialization.Serialize(message);
/// <summary>The one reader of manifest bytes: the document reader production stores and reads manifests with (CultPayloadDepth 256 included).</summary>
private static CultMeshCdnArtifactManifest ReadManifest(byte[] bytes) =>
(CultMeshCdnArtifactManifest)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(CultMeshCdnArtifactManifest), bytes);
private static byte[] Reencode(CultMeshCdnArtifactManifest manifest) =>
MessagePackSerializer.Serialize(manifest, CultNetSchemaMessageSerialization.Options);
CultDocumentMessagePackSerialization.SerializeUntyped(manifest, typeof(CultMeshCdnArtifactManifest));
private static CultMeshContentChunkRequestMessage Request(string id, string hash, string key, int size) => new()
{
@ -272,6 +618,61 @@ public sealed class CultMeshContentVectorTests
.ToList();
}
private static string Lines(string text) => text.Replace("\r\n", "\n").TrimEnd('\n');
private static string[] KeyHashes()
{
var empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
return new[]
{
empty, "SHA256:" + empty.ToUpperInvariant(), " " + empty + " ", " sha256:" + empty,
"sha256:sha256:" + empty, "Sha256:\u0130\u03A3\U00010400", "sha256:",
// U+017F uppercases to 'S': a prefix fold by upper case would strip it, the reference's ordinal-ignore-case does not.
"\u017Fha256:abc"
};
}
private sealed record KeyVectors(
List<(string Id, string Version, string Hash, string Key)> Artifacts,
List<(string Hash, string Key)> Chunks);
/// <summary>Every key is derived by the reference's public CreateRecordKey, never spelled by hand.</summary>
private static KeyVectors BuildRecordKeyVectors()
{
var ids = new[]
{
"eureka/content-vector", " Mixed Case/Path ", "\u0130stanbul", "\u0391\u03A3", "\uFEFFbom", "\u0085nel\u0085",
"\u65E5\u672C\u8A9E/\u8CC7\u7523", "\U0001F642 smile", "---", "a\uD800b", "\uD800", "x\u00B2y", "\u0663d", "\U00010400A",
// Tokens that are empty after the trim: the fallback hashes the original, neither trimmed nor lower-cased.
" --- ", "\u24B6", "\u216B"
};
var versions = new[] { string.Empty, " ", "1.0.0", "V2 Beta", "\u00FC" };
var hashes = KeyHashes();
var artifacts = ids.Select((id, i) => (id, versions[i % versions.Length], hashes[i % hashes.Length]))
.Concat(versions.Select(version => (ids[0], version, hashes[0])))
.Concat(hashes.Select(hash => (ids[0], versions[0], hash)))
.Select(t => (t.Item1, t.Item2, t.Item3, CultMeshCdnArtifactManifest.CreateRecordKey(t.Item1, t.Item2, t.Item3).Value))
.ToList();
var chunks = hashes.Select(hash => (hash, CultMeshCdnArtifactChunk.CreateRecordKey(hash).Value)).ToList();
return new KeyVectors(artifacts, chunks);
}
/// <summary>String inputs are stored as UTF-16 code-unit arrays, so a lone surrogate survives the JSON file.</summary>
private static string RecordKeyVectorsToJson(KeyVectors vectors) =>
JsonSerializer.Serialize(
new
{
artifacts = vectors.Artifacts.Select(a => new
{
artifactIdUnits = a.Id.Select(c => (int)c),
versionUnits = a.Version.Select(c => (int)c),
contentHash = a.Hash,
recordKey = a.Key
}),
chunks = vectors.Chunks.Select(c => new { chunkHash = c.Hash, recordKey = c.Key })
},
new JsonSerializerOptions { WriteIndented = true });
private static string VectorPath(string name) => Path.Combine(RepoRoot(), "contracts", "cultmesh", name);
private static string RepoRoot()

View file

@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using NUnit.Framework;
namespace GameCult.Mesh.Tests;
/// <summary>
/// The C# half of the cross-process HTTPS content parity. The provider is the TypeScript one, in another process; it is
/// started, and these tests are run, by packages/cultmesh-browser/test/interop/content-https.test.ts. Trust is the
/// fixture certificate through CustomRootTrust: chain and name validation stay on, and no other certificate is accepted.
/// </summary>
[TestFixture]
public sealed class CultMeshHttpsContentInteropTests
{
private const string Prefix = "CULTMESH_HTTPS_CONTENT_";
private string _dir = null!;
private string _manifests = null!;
private string _honest = null!, _tampered = null!, _corrupt = null!;
private X509Certificate2 _anchor = null!;
[SetUp]
public void SetUp()
{
string? Var(string name) => Environment.GetEnvironmentVariable(Prefix + name);
var values = new[] { "ENDPOINT", "TAMPERED_ENDPOINT", "CORRUPT_ENDPOINT", "MANIFESTS", "CA_PEM" }.Select(Var).ToArray();
if (values.Any(string.IsNullOrEmpty))
Assert.Ignore("Run by packages/cultmesh-browser/test/interop/content-https.test.ts, which starts the TypeScript provider and sets " + Prefix + "*.");
(_honest, _tampered, _corrupt, _manifests) = (values[0]!, values[1]!, values[2]!, values[3]!);
_anchor = X509Certificate2.CreateFromPem(File.ReadAllText(values[4]!));
_dir = Path.Combine(Path.GetTempPath(), "cultmesh-https-interop", Guid.NewGuid().ToString("N"));
}
[TearDown]
public void TearDown()
{
if (_dir != null && Directory.Exists(_dir)) Directory.Delete(_dir, true);
}
private CultMeshCdnArtifactManifest Manifest(string name) =>
(CultMeshCdnArtifactManifest)CultDocumentMessagePackSerialization.DeserializeUntyped(
typeof(CultMeshCdnArtifactManifest), File.ReadAllBytes(Path.Combine(_manifests, name + ".manifest")));
private static readonly CultMeshSessionTarget Target = new("aetheria", "aetheria.daemon");
private sealed class Rig : IDisposable
{
public CultMeshDiscoveryService Discovery = null!;
public CultMeshSessionManager Sessions = null!;
public CultCache State = null!;
public CultMeshContentTransferService Transfer = null!;
public void Dispose() { State.Dispose(); Sessions.Dispose(); Discovery.Dispose(); }
}
/// <summary>The production path: discovery, session manager with the unmodified HTTPS connector, session provider, transfer service.</summary>
private Rig Build(string endpoint, X509Certificate2 anchor, string cacheDir)
{
var rig = new Rig { Discovery = new CultMeshDiscoveryService(new[] { new RouteSource(endpoint) }) };
rig.Sessions = new CultMeshSessionManager(rig.Discovery, Array.Empty<ICultMeshTransportConnector>(),
new ICultMeshContentTransportConnector[]
{
new CultMeshHttpsContentTransportConnector(() => new SocketsHttpHandler
{
SslOptions = new SslClientAuthenticationOptions
{
CertificateChainPolicy = new X509ChainPolicy
{
TrustMode = X509ChainTrustMode.CustomRootTrust,
CustomTrustStore = { anchor },
RevocationMode = X509RevocationMode.NoCheck
}
}
})
}, CultMeshTestTrust.LocalSessions);
var provider = new CultMeshSessionContentProvider("ts-https", rig.Sessions, Target);
rig.State = new CultCache(CultMesh.CreateCultCacheDocumentRegistry(typeof(CultMeshContentTransferStateDocument)));
rig.Transfer = new CultMeshContentTransferService(rig.State, new[] { provider }, new CultMeshContentTransferOptions(cacheDir));
return rig;
}
private static IEnumerable<Exception> Chain(Exception e)
{
for (var current = e; current != null; current = current.InnerException) yield return current;
}
private static string Sha(string path) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))).ToLowerInvariant();
[Test]
public async Task HttpsTransferFetchesFromExternalTypeScriptProvider()
{
using var rig = Build(_honest, _anchor, _dir);
foreach (var name in new[] { "multi", "single", "empty", "escape" })
{
var manifest = Manifest(name);
var path = await rig.Transfer.FetchAsync(manifest);
Sha(path).Should().Be(manifest.ContentHash.Replace("sha256:", ""), name);
if (name == "multi") manifest.Chunks.Should().HaveCount(4);
if (name == "empty") manifest.SizeBytes.Should().Be(0);
}
var session = await rig.Sessions.ConnectContentAsync(Target);
var unknown = new CultMeshCdnChunkRef { ChunkHash = new string('0', 64), SizeBytes = 1 };
var missing = async () => await session.CopyChunkToAsync(unknown, new MemoryStream());
(await missing.Should().ThrowAsync<HttpRequestException>()).Which.StatusCode.Should().Be(HttpStatusCode.NotFound);
// The anchor is scoped: a different self-signed certificate does not validate the same server.
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
var request = new CertificateRequest("CN=someone-else", key, HashAlgorithmName.SHA256);
using var stranger = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
using var other = Build(_honest, stranger, Path.Combine(_dir, "other"));
var refused = async () => await other.Transfer.FetchAsync(Manifest("single"));
var thrown = (await refused.Should().ThrowAsync<Exception>()).Which;
Chain(thrown).Should().Contain(e => e is AuthenticationException);
}
[Test]
public async Task HttpsTransferRefusesTamperedBytesFromExternalTypeScriptProvider()
{
using var rig = Build(_tampered, _anchor, _dir);
var multi = Manifest("multi");
var fetch = async () => await rig.Transfer.FetchAsync(multi);
var thrown = (await fetch.Should().ThrowAsync<AggregateException>()).Which;
Chain(thrown).Should().Contain(e => e is InvalidDataException && e.Message == "CDN artifact chunk hash does not match its manifest.");
(Directory.Exists(_dir) ? Directory.GetFiles(_dir, "*.body", SearchOption.AllDirectories) : Array.Empty<string>()).Should().BeEmpty();
// The connector alone passes the wrong bytes: verification lives in the transfer owner.
var session = await rig.Sessions.ConnectContentAsync(Target);
using var bytes = new MemoryStream();
await session.CopyChunkToAsync(multi.Chunks[0], bytes);
Convert.ToHexString(SHA256.HashData(bytes.ToArray())).ToLowerInvariant().Should().NotBe(multi.Chunks[0].ChunkHash.Replace("sha256:", ""));
}
[Test]
public async Task HttpsTransferRefusesCorruptStoreFromExternalTypeScriptProvider()
{
using var rig = Build(_corrupt, _anchor, _dir);
var fetch = async () => await rig.Transfer.FetchAsync(Manifest("single"));
var thrown = (await fetch.Should().ThrowAsync<Exception>()).Which;
Chain(thrown).OfType<HttpRequestException>().Should().Contain(e => e.StatusCode == HttpStatusCode.InternalServerError);
(Directory.Exists(_dir) ? Directory.GetFiles(_dir, "*.body", SearchOption.AllDirectories) : Array.Empty<string>()).Should().BeEmpty();
}
private sealed class RouteSource(string endpoint) : ICultMeshLookupSource
{
public string SourceId => "test";
public Task<IReadOnlyList<CultMeshDiscoveryObservation>> LookupAsync(CultMeshDiscoveryQuery query, CancellationToken cancellationToken = default)
{
var now = DateTimeOffset.UtcNow;
return Task.FromResult<IReadOnlyList<CultMeshDiscoveryObservation>>(new[]
{
new CultMeshDiscoveryObservation(new CultMeshVerseDescriptor("aetheria", "Aetheria",
CultMeshVerseAuthorityModel.OperatorCluster, new CultMeshVerseCompatibility("cultmesh.v1", "rules"),
new[] { endpoint }, new[] { "aetheria.daemon" }), SourceId, now, now.AddMinutes(1), CultMeshDiscoveryTrust.Signed)
});
}
}
}

View file

@ -0,0 +1,122 @@
using System;
using System.IO;
using FluentAssertions;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using NUnit.Framework;
#nullable enable
namespace GameCult.Mesh.Tests;
// A CultMesh single-file write goes through the cache's single-file store: it reads the file under the store lock, applies its
// one record, and keeps every other record. A store stamped with a newer format version or one it cannot read is refused and
// left byte-identical.
public sealed class CultMeshSingleFileWriteGuardTests
{
private static readonly CultMeshSingleFileDocumentSchema Schema = new("sha256:guard", "guard.item", "1");
private string _root = null!;
private string _path = null!;
[SetUp]
public void SetUp()
{
_root = Path.Combine(Path.GetTempPath(), "cultmesh-write-guard", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
_path = Path.Combine(_root, "store.cc");
}
[TearDown]
public void TearDown()
{
if (Directory.Exists(_root)) Directory.Delete(_root, true);
}
private void Write(string key, byte payload) =>
CultMesh.WriteSingleFileDocumentPayload(_path, new CultRecordKey(key), Schema, null, new[] { payload });
[TestCase("cultcache.store.v4")]
[TestCase("cultcache.store.v9")]
public void WriteRefusesAStoreStampedWithANewerFormat(string newer)
{
Write("item:a", 1);
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(_path));
snapshot.FormatVersion = newer;
File.WriteAllBytes(_path, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
var before = File.ReadAllBytes(_path);
var error = Assert.Throws<NotSupportedException>(() => Write("item:a", 2))!;
error.Message.Should().Contain(newer);
File.ReadAllBytes(_path).Should().Equal(before);
}
[Test]
public void WriteRefusesAFileItCannotRead()
{
var garbage = new byte[] { 0xc1, 0xc1, 0xc1, 0xc1 };
File.WriteAllBytes(_path, garbage);
Assert.Catch(() => Write("item:a", 1));
File.ReadAllBytes(_path).Should().Equal(garbage);
}
// Another writer's record, under a schema this write does not touch, is still in the file after the write.
[Test]
public void WriteKeepsAnotherWritersRecord()
{
var other = new CultMeshSingleFileDocumentSchema("sha256:other", "other.item", "1");
Write("item:a", 1);
CultMesh.WriteSingleFileDocumentPayload(_path, new CultRecordKey("item:b"), other, null, new byte[] { 7 });
Write("item:a", 2);
CultMesh.ReadSingleFileDocumentPayload(_path, new CultRecordKey("item:a"), Schema.SchemaId).Should().Equal(2);
CultMesh.ReadSingleFileDocumentPayload(_path, new CultRecordKey("item:b"), other.SchemaId).Should().Equal(7);
}
[Test]
public void WriteReplacesTheSameRecordAndCreatesAMissingFile()
{
Write("item:a", 1);
Write("item:a", 2);
CultMesh.ReadSingleFileDocumentPayload(_path, new CultRecordKey("item:a"), Schema.SchemaId).Should().Equal(2);
}
// The write takes the same <path>.lock a CultCache single-file store takes: while another holder has it, the write waits.
[Test]
public void WriteWaitsForTheStoreLockAnotherWriterHolds()
{
Write("item:a", 1);
var write = default(System.Threading.Tasks.Task);
using (new FileStream(_path + ".lock", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
write = System.Threading.Tasks.Task.Run(() => Write("item:a", 2));
write.Wait(TimeSpan.FromMilliseconds(750)).Should().BeFalse("the lock is held, so the write must wait");
CultMesh.ReadSingleFileDocumentPayload(_path, new CultRecordKey("item:a"), Schema.SchemaId).Should().Equal(1);
}
write.Wait(TimeSpan.FromSeconds(10)).Should().BeTrue();
CultMesh.ReadSingleFileDocumentPayload(_path, new CultRecordKey("item:a"), Schema.SchemaId).Should().Equal(2);
}
// A variant at the very key being written is still not this write's to replace: a plain record would flatten it.
[Test]
public void WriteRefusesToReplaceAVariantAtTheSameKey()
{
Write("item:a", 1);
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(_path));
snapshot.FormatVersion = CultPersistedStoreSnapshot.FormatV2;
snapshot.Records[0].Payload = Array.Empty<byte>();
snapshot.Records[0].Variant = new CultVariantDelta("item:base", Array.Empty<CultVariantOverride>());
File.WriteAllBytes(_path, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
var before = File.ReadAllBytes(_path);
Assert.Throws<InvalidOperationException>(() => Write("item:a", 2));
File.ReadAllBytes(_path).Should().Equal(before);
}
}