fix(worker): honor RunCancellationRegistry.Register's return value at both dispatch sites

Register(taskId, cts) already refuses (and logs) a double-registration, but
both call sites discarded the bool and dispatched anyway under an
unregistered CTS. If the loser then unregistered the winner's CTS during
its own cleanup, TryCancel could silently no-op against a live process.

- OverrideSlotService.StartInSlot now fails RunNow/ContinueTask loudly
  (throws) when it loses the registration race instead of registering
  over — or silently proceeding despite losing to — the queue picker.
- QueueService's picker loop retries registration briefly (the loser's own
  claim-attempt-then-unregister resolves fast) before dispatching; if
  registration never resolves it marks the already-claimed row Failed
  instead of running it unregistered.
- RunCancellationRegistry.Unregister already had compare-and-remove
  semantics (TryRemove(KeyValuePair)), so a loser's cleanup could not have
  removed the winner's CTS once registration correctly failed.

Added regression tests exercising the real registry through both dispatch
paths: RunNow losing the registration race throws without disturbing the
winner, the picker's retry succeeds and TryCancel reaches the live run when
the loser unregisters in time, and the picker fails the task instead of
running unregistered when it never does.
This commit is contained in:
mika kuns
2026-08-06 14:34:48 +02:00
parent bac8387069
commit 109e85da83
4 changed files with 180 additions and 15 deletions
@@ -31,7 +31,7 @@ public sealed class OverrideSlotServiceTests : IDisposable
public void Dispose() { _db.Dispose(); try { Directory.Delete(_tempDir, true); } catch { } }
private OverrideSlotService BuildService()
private OverrideSlotService BuildService(RunCancellationRegistry? runCancels = null)
{
var dbFactory = _db.CreateFactory();
var state = TaskStateServiceBuilder.Build(dbFactory).State;
@@ -39,7 +39,7 @@ public sealed class OverrideSlotServiceTests : IDisposable
var runner = new TaskRunner(new FakeClaudeProcess(), dbFactory, new HubBroadcaster(new CapturingHubContext()), wt,
new ClaudeArgsBuilder(), _cfg, NullLogger<TaskRunner>.Instance, state, new TaskRunTokenRegistry(),
new AttachmentStore(), new FakeSessionSkillSeeder(), new FakeTranscriptUsageReader());
var runCancels = new RunCancellationRegistry(NullLogger<RunCancellationRegistry>.Instance);
runCancels ??= new RunCancellationRegistry(NullLogger<RunCancellationRegistry>.Instance);
return new OverrideSlotService(dbFactory, runner, NullLogger<OverrideSlotService>.Instance, runCancels);
}
@@ -86,4 +86,41 @@ public sealed class OverrideSlotServiceTests : IDisposable
// background, so this only asserts the precheck doesn't reject a claimable task.
await service.RunNow(taskId);
}
// Regression for the RunCancellationRegistry.Register-return double-dispatch bug: the
// queue picker's atomic Queued->Running claim can land between RunNow's DB precheck and
// its registry registration. If the queue side already holds the registration, RunNow
// must fail loudly instead of silently registering over it (or being ignored and then
// unregistering the winner's CTS during its own cleanup).
[Fact]
public async Task RunNow_LosesRegistrationRaceToQueue_ThrowsAndLeavesWinnersCtsUntouched()
{
string listId = Guid.NewGuid().ToString(), taskId = Guid.NewGuid().ToString();
using (var ctx = _db.CreateContext())
{
ctx.Lists.Add(new ListEntity { Id = listId, Name = "L", CreatedAt = DateTime.UtcNow });
ctx.Tasks.Add(new TaskEntity
{
Id = taskId, ListId = listId, Title = "T", Status = TaskStatus.Queued,
CreatedAt = DateTime.UtcNow,
});
await ctx.SaveChangesAsync();
}
var runCancels = new RunCancellationRegistry(NullLogger<RunCancellationRegistry>.Instance);
var service = BuildService(runCancels);
// Simulate the queue picker having already won the registration race for this task id.
using var winnerCts = new CancellationTokenSource();
Assert.True(runCancels.Register(taskId, winnerCts));
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => service.RunNow(taskId));
Assert.Contains("lost the double-dispatch race", ex.Message);
Assert.Null(service.CurrentSlot);
// The loser must not have cancelled or displaced the winner's registration.
Assert.False(winnerCts.IsCancellationRequested);
Assert.True(runCancels.TryCancel(taskId));
Assert.True(winnerCts.IsCancellationRequested);
}
}