Push: Land pinned against a concurrent write, empty request and corrupt model end as outcomes

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-27 23:58:16 +01:00
commit 9b29992baa
2 changed files with 106 additions and 16 deletions

View file

@ -276,4 +276,80 @@ public sealed class ShipAuthoringPushTests : IDisposable
Assert.Equal(5f, hull2.Hardpoints.Single(hardpoint => hardpoint.Transform == "gun").Armor);
Assert.Equal("port-row", hull2.Hardpoints.Single(hardpoint => hardpoint.Transform == "thruster.port").Row);
}
// The Expect half of the compare-exchange: a write that lands between the load and the commit, through whatever
// path, replaces the instance the commit expects. The commit is refused and the concurrent write is what the store holds.
[Fact]
public void ConcurrentWriteBetweenLoadAndCommitIsRefused()
{
var path = Package();
using (var cache = ShipAuthoringStore.Open(path, writable: true))
{
var (hull, _, _) = ShipAuthoringStore.Load(cache, path);
var key = ShipModCatalog.HullKey("mod.skiff");
var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly);
HullData Mutated(float mass)
{
var copy = MessagePackSerializer.Deserialize<HullData>(MessagePackSerializer.Serialize(hull, options), options);
copy.Mass = mass;
return copy;
}
var mine = Mutated(111);
var concurrent = Mutated(222);
cache.UpsertAsync(typeof(HullData), concurrent, key).GetAwaiter().GetResult();
var writes = new[] { new ShipAuthoringPush.Write(key, typeof(HullData), hull, mine) };
Assert.False(ShipAuthoringPush.Land(cache, writes));
Assert.Same(concurrent, cache.Get(key));
cache.FlushAsync().Wait();
}
Assert.Equal(222f, ShipAuthoringStore.Load(path).Hull.Mass);
}
[Theory]
[InlineData("")]
[InlineData("null")]
[InlineData(" ")]
public void EmptyRequestIsRefusedWithAnOutcome(string body)
{
var path = Package();
var before = File.ReadAllBytes(path);
var files = Listing(path);
foreach (var apply in new[] { false, true })
{
var (code, _, outcome) = Push(path, body, apply);
Assert.Equal(1, code);
Assert.Equal("refused", (string)outcome["outcome"]);
Assert.Contains("request", (string)outcome["message"]);
Assert.Equal(before, File.ReadAllBytes(path));
Assert.Equal(files, Listing(path));
}
}
// A model file that does not read as a GLB is the package's fault, not the request's: the verdict reports it, the
// draft still applies, and nothing escapes.
[Theory]
[InlineData("badjson")]
[InlineData("truncated")]
[InlineData("notglb")]
public void CorruptModelIsAVerdictNotACrash(string kind)
{
var path = Path.Combine(ShipFixture.WritePackage(Mods, "mod.skiff", tweak: ship => ship.Hull.Roles = new List<ItemRole> { new ItemRole { Name = "frame" } }), "ship.cc");
var model = Path.Combine(Path.GetDirectoryName(path), "skiff.glb");
var good = File.ReadAllBytes(model);
// Control: the same request on the intact package is accepted, so the refusal below is the model's.
var intact = Push(path, Edit(Open(path), json => Hardpoint(json, "gun")["armor"] = 6), apply: false);
Assert.True(((string)intact.Outcome["verdict"]).StartsWith("accepted: records and model"), (string)intact.Outcome["verdict"]);
File.WriteAllBytes(model, kind switch
{
"badjson" => ShipFixture.Glb("{not json"),
"truncated" => good.Take(30).ToArray(),
_ => new byte[] { 1, 2, 3 }
});
var request = Edit(Open(path), json => Hardpoint(json, "gun")["armor"] = 7);
var (code, _, outcome) = Push(path, request, apply: true);
Assert.Equal(0, code);
Assert.Equal("applied", (string)outcome["outcome"]);
Assert.StartsWith("refused: ", (string)outcome["verdict"]);
Assert.Equal(7f, ShipAuthoringStore.Load(path).Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "gun").Armor);
}
}

View file

@ -157,10 +157,10 @@ public static class ShipAuthoringPush
Request request;
try
{
request = JsonConvert.DeserializeObject<Request>(requestText.ReadToEnd(), Strict) ??
throw new InvalidOperationException("The request is empty.");
request = JsonConvert.DeserializeObject<Request>(requestText.ReadToEnd(), Strict);
}
catch (JsonException error) { return Refused(output, "request: " + error.Message); }
if (request == null) return Refused(output, "request: the request is empty.");
try
{
using var cache = ShipAuthoringStore.Open(path, writable: apply);
@ -176,9 +176,9 @@ public static class ShipAuthoringPush
if (request.Visual != null) DeriveVisual(request.Visual, ship, newShip, shipKey.Value, lines);
if (request.Lines != null) DeriveLines(request.Lines, ship, newShip, shipKey.Value, lines);
var writes = new List<(CultRecordKey Key, Type Type, object Held, object Derived)>();
if (!Pack(newHull).AsSpan().SequenceEqual(Pack(hull))) writes.Add((hullKey, typeof(HullData), hull, newHull));
if (!Pack(newShip).AsSpan().SequenceEqual(Pack(ship))) writes.Add((shipKey, typeof(ShipAuthoring), ship, newShip));
var writes = new List<Write>();
if (!Pack(newHull).AsSpan().SequenceEqual(Pack(hull))) writes.Add(new Write(hullKey, typeof(HullData), hull, newHull));
if (!Pack(newShip).AsSpan().SequenceEqual(Pack(ship))) writes.Add(new Write(shipKey, typeof(ShipAuthoring), ship, newShip));
foreach (var held in request.Versions.Keys)
if (held != hullKey.Value && held != shipKey.Value)
@ -195,16 +195,7 @@ public static class ShipAuthoringPush
.Select(write => write.Key.Value).ToList();
if (stale.Count == 0 && apply && writes.Count > 0)
{
// One commit, every record expected to still be the instance it was loaded as: a write that lands between this
// load and the commit is refused by the cache, whatever its storedAt said.
var landed = cache.Commit(batch =>
{
foreach (var write in writes)
{
batch.Expect(write.Key, write.Held);
batch.Upsert(write.Type, write.Derived, write.Key);
}
});
var landed = Land(cache, writes);
if (landed) cache.FlushAsync().Wait();
else stale = writes.Select(write => write.Key.Value).ToList();
}
@ -214,10 +205,33 @@ public static class ShipAuthoringPush
catch (InvalidOperationException error) { return Refused(output, error.Message); }
}
// A record to write: the instance the cache holds, and the copy derived from it.
internal readonly record struct Write(CultRecordKey Key, Type Type, object Held, object Derived);
// One commit, every record expected to still be the instance it was loaded as: a write that lands between the load and
// this commit replaces that instance and is refused here (false), never overwritten.
internal static bool Land(CultCache cache, IReadOnlyList<Write> writes)
{
try
{
return cache.Commit(batch =>
{
foreach (var write in writes)
{
batch.Expect(write.Key, write.Held);
batch.Upsert(write.Type, write.Derived, write.Key);
}
});
}
// Expect refuses an instance the cache no longer holds at the key: that write landed after the load.
catch (ArgumentException error) when (error.ParamName == "current") { return false; }
}
private static string Verdict(string path, HullData hull, ShipAuthoring ship, FactionProductData[] products)
{
try { return "accepted: " + ShipAuthoringCommands.Judge(path, hull, ship, products); }
catch (InvalidOperationException error) { return "refused: " + error.Message; }
// The judgment's own refusals, and a model whose JSON chunk does not parse; anything else is a fault and surfaces.
catch (Exception error) when (error is InvalidOperationException or JsonException) { return "refused: " + error.Message; }
}
private static int Outcome(TextWriter output, string outcome, List<string> changed, List<string> stale, string verdict,