Merge #964: late-write observer releases its physical slot before the write reply / WriteCompleted (real race: next same-tag write falsely rejected as capacity exhausted)

This commit is contained in:
Joseph Doherty
2026-12-02 13:10:36 -05:00
5 changed files with 69 additions and 26 deletions
@@ -87,13 +87,22 @@ public sealed class LateWriteReservation : IDisposable
(string Driver, string Reference)? target)
{ _owner = owner; _retention = retention; _clock = clock; _target = target; }
public void Observe(Task<DataWriteOutcome> actualDriverTask, WriteClaim claim, IDisposable? lifetime = null)
/// <summary>
/// Transfers the reservation to <paramref name="actualDriverTask"/>. The returned task completes only after
/// the observation has fully settled: the late outcome recorded, <paramref name="lifetime"/> disposed, and
/// the physical slot (and target) released back to the observer. Anything that reacts to the physical
/// write finishing and may then reserve again — the actor replying to its caller or draining its write
/// queue — must wait for this task, not for <paramref name="actualDriverTask"/>; the two complete on
/// different continuations, so the driver task finishing does not mean the slot is free yet (#964).
/// The task can fault only if <paramref name="lifetime"/>'s dispose throws (the slot is still released).
/// </summary>
public Task Observe(Task<DataWriteOutcome> actualDriverTask, WriteClaim claim, IDisposable? lifetime = null)
{
ArgumentNullException.ThrowIfNull(actualDriverTask);
ArgumentNullException.ThrowIfNull(claim);
if (Interlocked.CompareExchange(ref _state, 1, 0) != 0) throw new InvalidOperationException("Reservation already consumed.");
var started = _clock.GetTimestamp();
_ = ObserveCore(actualDriverTask, claim, lifetime, started);
return ObserveCore(actualDriverTask, claim, lifetime, started);
}
private async Task ObserveCore(Task<DataWriteOutcome> task, WriteClaim claim, IDisposable? lifetime, long started)
@@ -1482,7 +1482,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
var cancellation = new CancellationTokenSource(timeout, clock);
// This task represents the entire physical invocation, including synchronous work before a driver
// returns its task. Its permit and payload live until that invocation really exits.
reservation.Observe(physical.Task, msg.Claim, new WriteLifetime(msg.Ticket, cancellation));
var settled = reservation.Observe(physical.Task, msg.Claim, new WriteLifetime(msg.Ticket, cancellation));
var attempt = Task.Run(async () =>
{
try
@@ -1527,14 +1527,25 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
});
try
{
var outcome = await attempt.WaitAsync(timeout + WriteAbandonGrace(timeout), clock).ConfigureAwait(false);
replyTo.Tell(outcome);
}
catch
{
var outcome = msg.Claim.Complete(RichRejected) ? RichRejected : RichUnknown;
if (outcome == RichRejected) physical.TrySetResult(outcome);
else msg.Claim.Complete(outcome);
DataWriteOutcome outcome;
try
{
outcome = await attempt.WaitAsync(timeout + WriteAbandonGrace(timeout), clock).ConfigureAwait(false);
}
catch
{
outcome = msg.Claim.Complete(RichRejected) ? RichRejected : RichUnknown;
if (outcome == RichRejected) physical.TrySetResult(outcome);
else msg.Claim.Complete(outcome);
}
// #964: when the physical write has finished, its late-write slot must be back BEFORE the caller
// hears the outcome or the actor frees the tag — both let a next write to the same target reach
// TryReserve, which otherwise could still see this write's slot (the observer releases it on its
// own continuation) and spuriously reject with "Outstanding driver write capacity exhausted".
// Settling after physical completion is short and bounded (record outcome, dispose, release). An
// abandoned, still-running physical write is deliberately NOT awaited: it keeps its slot and target.
if (physical.Task.IsCompleted)
await settled.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
replyTo.Tell(outcome);
}
finally { self.Tell(new WriteCompleted(msg.Ticket.Proof.DriverReference, incarnation)); }
@@ -256,6 +256,24 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
secondClaim.IsDispatched.ShouldBeFalse();
}
[Fact]
public async Task Sequential_writes_to_one_target_never_see_the_previous_writes_physical_slot()
{
// #964: the reply and WriteCompleted used to race the late-write observer's slot release, so a
// caller that wrote the same tag again right after its previous reply could be rejected with
// "Outstanding driver write capacity exhausted" although nothing was outstanding any more.
var driver = new RichDriver();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)), maxWrites: 1);
for (var i = 0; i < 200; i++)
{
var (ticket, claim) = NewWrite($"seq-{i}", i);
var outcome = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess, $"write {i}: {outcome.Diagnostic}");
}
driver.Calls.ShouldBe(200);
}
[Fact]
public async Task Legacy_good_without_an_explicit_completion_guarantee_is_unconfirmed()
{
@@ -30,10 +30,14 @@ public sealed class GrpcDataLateWriteTests
var source = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
var lifetime = new CountingLifetime();
observer.TryReserve(out var reservation).ShouldBeTrue();
reservation!.Observe(source.Task, claim, lifetime);
var settled = reservation!.Observe(source.Task, claim, lifetime);
observer.TryReserve(out _).ShouldBeFalse();
source.SetResult(Success);
await WaitUntil(() => claim.CurrentOutcome == Success && lifetime.Count == 1);
// #964: the settled task, not the lifetime, is the "slot is free" signal — the slot is released after
// the lifetime, on the same continuation.
await settled.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
claim.CurrentOutcome.ShouldBe(Success);
lifetime.Count.ShouldBe(1);
(await claim.Completion).ShouldBe(Unknown);
observer.TryReserve(out var next).ShouldBeTrue();
next!.Dispose();
@@ -48,12 +52,14 @@ public sealed class GrpcDataLateWriteTests
var source = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
var lifetime = new CountingLifetime();
observer.TryReserve(out var reservation).ShouldBeTrue();
reservation!.Observe(source.Task, claim, lifetime);
var settled = reservation!.Observe(source.Task, claim, lifetime);
clock.Advance(TimeSpan.FromSeconds(11));
observer.TryReserve(out _).ShouldBeFalse();
lifetime.Count.ShouldBe(0);
settled.IsCompleted.ShouldBeFalse();
source.SetResult(Success);
await WaitUntil(() => lifetime.Count == 1);
await settled.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
lifetime.Count.ShouldBe(1);
claim.CurrentOutcome.ShouldBe(Unknown);
observer.TryReserve(out var next).ShouldBeTrue();
next!.Dispose();
@@ -66,9 +72,11 @@ public sealed class GrpcDataLateWriteTests
var claim = DispatchedClaim();
var lifetime = new CountingLifetime();
observer.TryReserve(out var reservation).ShouldBeTrue();
reservation!.Observe(Task.FromResult(Success), claim, lifetime);
var settled = reservation!.Observe(Task.FromResult(Success), claim, lifetime);
reservation.Dispose();
await WaitUntil(() => lifetime.Count == 1 && claim.CurrentOutcome == Success);
await settled.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
lifetime.Count.ShouldBe(1);
claim.CurrentOutcome.ShouldBe(Success);
observer.TryReserve(out var next).ShouldBeTrue();
next!.Dispose();
next.Dispose();
@@ -86,22 +94,17 @@ public sealed class GrpcDataLateWriteTests
var source = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
var lifetime = new CountingLifetime();
observer.TryReserve(out var reservation).ShouldBeTrue();
reservation!.Observe(source.Task, claim, lifetime);
var settled = reservation!.Observe(source.Task, claim, lifetime);
clock.Advance(TimeSpan.FromMinutes(2));
source.SetResult(Success);
await WaitUntil(() => lifetime.Count == 1);
await settled.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
lifetime.Count.ShouldBe(1);
var duplicate = registry.Claim("p", "op", "inc", new byte[32]);
duplicate.Kind.ShouldBe(WriteClaimKind.Existing);
duplicate.Claim!.CurrentOutcome.ShouldBe(Success);
(await duplicate.Claim.Completion).ShouldBe(Unknown);
}
private static async Task WaitUntil(Func<bool> condition)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
while (!condition()) await Task.Delay(1, timeout.Token);
}
private sealed class CountingLifetime : IDisposable
{
private int _count;
@@ -541,7 +541,7 @@ public sealed class GrpcDataWriteAdmissionTests
var operation = ticket.Proof.Admission.OperationId;
_observer.TryReserve(out var reservation).ShouldBeTrue();
var physical = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
reservation.ShouldNotBeNull().Observe(physical.Task, claim, ticket);
var settled = reservation.ShouldNotBeNull().Observe(physical.Task, claim, ticket);
_dispatched.Enqueue(operation);
claim.TryMarkDispatched().ShouldBeTrue();
Entered.TrySetResult();
@@ -550,6 +550,8 @@ public sealed class GrpcDataWriteAdmissionTests
? new DataWriteOutcome(DataWriteState.DriverConfirmedFailure, 0x80000000u, "device rejected")
: new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null);
physical.TrySetResult(outcome);
// As the driver host does (#964): the slot is back before the outcome is returned.
await settled;
return outcome;
}
}