fix(store-and-forward): immediate delivery never overtakes buffered rows of its lane (SF-1 follow-up, decision B)

SF-1 kept the retry sweep per-(category,target) FIFO, but a NEW message could
still be delivered inline while older rows of the same lane were buffered and
backing off: EnqueueAsync's immediate attempt, and the first attempt that
ExternalSystem.CachedCall / Database.CachedWrite make themselves before handing
a transient failure to S&F. A recovered target then received B before A, and
A's later retry overwrote B.

Now each of those paths first probes the lane (StoreAndForwardService.
LaneHasPendingAsync: SELECT EXISTS seek on the covering idx_sf_messages_lane,
pinned by an EXPLAIN QUERY PLAN test; fails open to the old behaviour). An
occupied lane gets no inline attempt: the message is buffered due-immediately
(LastAttemptAt null, deferToSweep) behind the older rows and the sweep delivers
in order. Empty lanes (or parked-only) are unchanged. Notify.Send already
deferred to the sweep. Return contract unchanged: handle/TrackedOperationId at
once, WasBuffered=true, tracking reads Pending.

Regression tests (fail before, pass after): service, CachedCall, CachedWrite;
plus lane-probe + query-plan storage tests. Component-StoreAndForward.md and
Component-ExternalSystemGateway.md updated.
This commit is contained in:
Joseph Doherty
2026-12-03 12:22:31 -05:00
parent 3f98d40fa4
commit 8267ab8ffc
10 changed files with 484 additions and 74 deletions
@@ -332,6 +332,73 @@ public class DatabaseGatewayTests : IDisposable
Assert.Equal(0, ReadBufferDepth(sfDb));
}
/// <summary>
/// Decision B (2026-12-02 review follow-up): a CachedWrite must not overtake an older
/// buffered write to the same connection. Write A fails transiently and is buffered; the
/// database recovers; write B arrives. Pre-fix B executed inline at once, ahead of A —
/// A's later retry then overwrote B's newer value. B must NOT execute inline: it is
/// buffered behind A (Success + WasBuffered, so the script's TrackedOperationId reads as
/// buffered) and the sweep delivers A then B.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CachedWrite_LaneHasBufferedWrite_BuffersBehindItWithoutExecutingInline()
{
var conn = new DatabaseConnectionDefinition("testDb", "Server=localhost;Database=test") { Id = 1 };
StubConnection(conn);
var (sf, sfDb) = NewStoreAndForward();
var dbUp = false;
var executions = 0;
var gateway = new ExecuteStubGateway(_repository, sf, onExecute: () =>
{
if (!dbUp) throw new TransientDatabaseException("Timeout expired", errorNumber: -2);
executions++;
});
var a = await gateway.CachedWriteAsync("testDb", "UPDATE t SET v = 1",
trackedOperationId: ZB.MOM.WW.ScadaBridge.Commons.Types.TrackedOperationId.New());
Assert.True(a.WasBuffered);
dbUp = true;
var bId = ZB.MOM.WW.ScadaBridge.Commons.Types.TrackedOperationId.New();
var b = await gateway.CachedWriteAsync("testDb", "UPDATE t SET v = 2", trackedOperationId: bId);
Assert.True(b.Success);
Assert.True(b.WasBuffered); // pre-fix: false (executed inline, overtaking A)
Assert.Equal(0, executions); // pre-fix: 1
Assert.Equal(2, ReadBufferDepth(sfDb));
var bRow = await sf.GetMessageByIdAsync(bId.ToString());
Assert.NotNull(bRow);
Assert.Equal(ZB.MOM.WW.ScadaBridge.Commons.Types.Enums.StoreAndForwardMessageStatus.Pending, bRow!.Status);
Assert.Null(bRow.LastAttemptAt); // no attempt made — due as soon as A is gone
}
/// <summary>
/// Decision B: an empty lane is unchanged — a CachedWrite to a connection with nothing
/// buffered (only another connection's backlog) still executes inline.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CachedWrite_OtherConnectionBuffered_StillExecutesInline()
{
StubConnection(new DatabaseConnectionDefinition("downDb", "Server=down;Database=x") { Id = 1 });
StubConnection(new DatabaseConnectionDefinition("upDb", "Server=up;Database=y") { Id = 2 });
var (sf, sfDb) = NewStoreAndForward();
var executions = 0;
var down = new ExecuteStubGateway(_repository, sf,
onExecute: () => throw new TransientDatabaseException("Timeout expired", errorNumber: -2));
var up = new ExecuteStubGateway(_repository, sf, onExecute: () => executions++);
Assert.True((await down.CachedWriteAsync("downDb", "UPDATE t SET v = 1")).WasBuffered);
var result = await up.CachedWriteAsync("upDb", "UPDATE t SET v = 1");
Assert.False(result.WasBuffered);
Assert.Equal(1, executions);
Assert.Equal(1, ReadBufferDepth(sfDb));
}
/// <summary>Verifies that a transient SQL error during buffered delivery is rethrown so the engine retries.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -412,6 +412,74 @@ public class ExternalSystemClientTests : IDisposable
Assert.Equal(0, handlerInvocations);
}
// ── Decision B (2026-12-02 review follow-up): a CachedCall never overtakes its lane ──
/// <summary>
/// A CachedCall must not overtake an older buffered call to the same external system.
/// Call A fails transiently and is buffered; the system recovers; call B arrives. Pre-fix B
/// made its HTTP request inline at once, ahead of A. B must make NO inline request: it is
/// buffered behind A (WasBuffered, the TrackedOperationId pinned as the message id) for
/// the sweep to deliver in order. A different system's lane is unaffected.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CachedCall_LaneHasBufferedCall_BuffersBehindItWithoutHttpRequest()
{
var system = new ExternalSystemDefinition("TestAPI", "https://api.example.com", "none") { Id = 1 };
var method = new ExternalSystemMethod("postData", "POST", "/post") { Id = 1, ExternalSystemDefinitionId = 1 };
var other = new ExternalSystemDefinition("OtherAPI", "https://other.example.com", "none") { Id = 2 };
var otherMethod = new ExternalSystemMethod("postData", "POST", "/post") { Id = 2, ExternalSystemDefinitionId = 2 };
StubResolution(system, method);
StubResolution(other, otherMethod);
var status = HttpStatusCode.InternalServerError;
var requests = 0;
_httpClientFactory.CreateClient(Arg.Any<string>()).Returns(_ => new HttpClient(new CallbackHttpMessageHandler(() =>
{
Interlocked.Increment(ref requests);
return status;
})));
var localDb = CreateLocalDb("EsgLaneOrder");
var storage = new StoreAndForwardStorage(localDb.Db, NullLogger<StoreAndForwardStorage>.Instance);
await storage.InitializeAsync();
var sf = new StoreAndForwardService(storage, new StoreAndForwardOptions
{
DefaultRetryInterval = TimeSpan.FromMinutes(10),
RetryTimerInterval = TimeSpan.FromMinutes(10),
}, NullLogger<StoreAndForwardService>.Instance);
var client = new ExternalSystemClient(
_httpClientFactory, _repository, NullLogger<ExternalSystemClient>.Instance, storeAndForward: sf);
var a = await client.CachedCallAsync("TestAPI", "postData");
Assert.True(a.WasBuffered);
Assert.Equal(1, requests);
status = HttpStatusCode.OK;
var bId = ZB.MOM.WW.ScadaBridge.Commons.Types.TrackedOperationId.New();
var b = await client.CachedCallAsync("TestAPI", "postData", trackedOperationId: bId);
Assert.True(b.Success);
Assert.True(b.WasBuffered); // pre-fix: false (HTTP request made inline, overtaking A)
Assert.Equal(1, requests); // pre-fix: 2
var bRow = await sf.GetMessageByIdAsync(bId.ToString());
Assert.NotNull(bRow);
Assert.Null(bRow!.LastAttemptAt);
// Another system's lane is empty — its call still goes out inline.
var c = await client.CachedCallAsync("OtherAPI", "postData");
Assert.False(c.WasBuffered);
Assert.Equal(2, requests);
}
/// <summary>Test helper: answers every request with the status the callback returns.</summary>
private sealed class CallbackHttpMessageHandler(Func<HttpStatusCode> respond) : HttpMessageHandler
{
/// <inheritdoc />
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
=> Task.FromResult(new HttpResponseMessage(respond()) { Content = new StringContent("{}") });
}
// ── per-system call timeout ──
/// <summary>Verifies that a call to a slow system times out as a transient error within the configured window.</summary>
@@ -897,6 +897,89 @@ public class StoreAndForwardServiceTests : IAsyncLifetime, IDisposable
Assert.Equal(new[] { "A", "B" }, delivered);
}
// ── Decision B (2026-12-02 review follow-up): immediate delivery never overtakes its lane ──
/// <summary>
/// The immediate-delivery path must not overtake an older buffered row of the same
/// <c>(category, target)</c> lane. A is buffered after a transient failure and is backing
/// off; the target recovers; B arrives. Pre-fix B was delivered inline at once, ahead of
/// A — A's later delivery then overwrote B's newer value. B must be buffered behind A
/// (handle returned, row Pending, handler not invoked) and the sweep delivers A then B.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task EnqueueAsync_LaneHasPendingRow_BuffersBehindItInsteadOfDeliveringImmediately()
{
var delivered = new List<string>();
var targetUp = false;
_service.RegisterDeliveryHandler(StoreAndForwardCategory.CachedDbWrite, msg =>
{
if (!targetUp) throw new TimeoutException("Mes down");
delivered.Add(msg.Id);
return Task.FromResult(true);
});
var a = await _service.EnqueueAsync(StoreAndForwardCategory.CachedDbWrite, "Mes", "{}",
retryInterval: TimeSpan.FromSeconds(30), messageId: "A");
Assert.True(a.WasBuffered); // transient failure: A is backing off
targetUp = true;
var b = await _service.EnqueueAsync(StoreAndForwardCategory.CachedDbWrite, "Mes", "{}",
retryInterval: TimeSpan.FromSeconds(30), messageId: "B");
Assert.True(b.Accepted);
Assert.Equal("B", b.MessageId);
Assert.True(b.WasBuffered); // pre-fix: false (delivered inline)
Assert.Empty(delivered); // pre-fix: ["B"]
var bRow = await _service.GetMessageByIdAsync("B");
Assert.NotNull(bRow);
Assert.Equal(StoreAndForwardMessageStatus.Pending, bRow!.Status);
Assert.Equal(0, bRow.RetryCount);
Assert.Null(bRow.LastAttemptAt); // no attempt was made — due as soon as its head is gone
// A is not due yet, so the lane holds B back too.
await _service.RetryPendingMessagesAsync();
Assert.Empty(delivered);
await MakeDueAsync("A");
await _service.RetryPendingMessagesAsync();
Assert.Equal(new[] { "A", "B" }, delivered);
}
/// <summary>
/// The lane check is per <c>(category, target)</c> and counts only Pending rows: a backing-off
/// row of ANOTHER target, or a Parked row of the same target, does not stop an immediate
/// delivery — the empty-lane path is unchanged.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task EnqueueAsync_OtherLaneOrParkedRow_StillDeliversImmediately()
{
var delivered = new List<string>();
_service.RegisterDeliveryHandler(StoreAndForwardCategory.ExternalSystem, msg =>
{
delivered.Add(msg.Id);
return Task.FromResult(true);
});
// A pending row on a different target, and one in a different category on the same target.
await _service.EnqueueAsync(StoreAndForwardCategory.ExternalSystem, "other", "{}",
attemptImmediateDelivery: false, retryInterval: TimeSpan.FromMinutes(5), messageId: "other-target");
await _service.EnqueueAsync(StoreAndForwardCategory.CachedDbWrite, "api", "{}",
attemptImmediateDelivery: false, retryInterval: TimeSpan.FromMinutes(5), messageId: "other-category");
// A parked row on the same lane.
await _service.EnqueueAsync(StoreAndForwardCategory.ExternalSystem, "api", "{}",
attemptImmediateDelivery: false, retryInterval: TimeSpan.FromMinutes(5), messageId: "parked");
await ExecSqlAsync($"UPDATE sf_messages SET status = {(int)StoreAndForwardMessageStatus.Parked} WHERE id = 'parked'");
var result = await _service.EnqueueAsync(StoreAndForwardCategory.ExternalSystem, "api", "{}", messageId: "fresh");
Assert.False(result.WasBuffered);
Assert.Equal(new[] { "fresh" }, delivered);
Assert.True(await _service.LaneHasPendingAsync(StoreAndForwardCategory.ExternalSystem, "other"));
Assert.False(await _service.LaneHasPendingAsync(StoreAndForwardCategory.ExternalSystem, "api"));
}
// ── SF-2: storage failure after a successful delivery ──
/// <summary>
@@ -942,6 +942,55 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable
Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE") && !p.Contains("LAST TERM"));
}
/// <summary>
/// Decision B (2026-12-02 review follow-up): the immediate-delivery lane probe is answered
/// by a seek on the covering <c>idx_sf_messages_lane</c> (leading status, category, target)
/// — no table scan, no payload read, no sort — so it is cheap on every enqueue even with a
/// large backlog. Runs the production SQL verbatim.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LaneHasPending_SeeksTheCoveringLaneIndex()
{
await using var connection = _localDb.Db.CreateConnection();
await using var cmd = connection.CreateCommand();
cmd.CommandText = "EXPLAIN QUERY PLAN " + StoreAndForwardStorage.LaneHasPendingSql;
cmd.Parameters.AddWithValue("@pending", 0);
cmd.Parameters.AddWithValue("@category", 0);
cmd.Parameters.AddWithValue("@target", "t");
var plan = new List<string>();
await using (var reader = await cmd.ExecuteReaderAsync())
while (await reader.ReadAsync())
plan.Add(reader.GetString(3));
Assert.Contains(plan, p => p.Contains("SEARCH")
&& p.Contains("COVERING INDEX idx_sf_messages_lane")
&& p.Contains("status=? AND category=? AND target=?"));
// The only scan is the EXISTS wrapper's "SCAN CONSTANT ROW"; sf_messages is never scanned.
Assert.DoesNotContain(plan, p => p.StartsWith("SCAN sf_messages", StringComparison.Ordinal));
Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE"));
}
/// <summary>
/// Decision B: the lane probe is true only for a Pending row of the exact
/// <c>(category, target)</c>; Parked rows and other lanes do not count.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LaneHasPending_CountsOnlyPendingRowsOfThatLane()
{
// NewMsg rows are ExternalSystem / "t".
Assert.False(await _storage.LaneHasPendingAsync(StoreAndForwardCategory.ExternalSystem, "t"));
await _storage.EnqueueAsync(NewMsg("parked", StoreAndForwardMessageStatus.Parked, DateTimeOffset.UtcNow));
Assert.False(await _storage.LaneHasPendingAsync(StoreAndForwardCategory.ExternalSystem, "t"));
await _storage.EnqueueAsync(NewMsg("pending", StoreAndForwardMessageStatus.Pending, DateTimeOffset.UtcNow));
Assert.True(await _storage.LaneHasPendingAsync(StoreAndForwardCategory.ExternalSystem, "t"));
Assert.False(await _storage.LaneHasPendingAsync(StoreAndForwardCategory.ExternalSystem, "t-other"));
Assert.False(await _storage.LaneHasPendingAsync(StoreAndForwardCategory.CachedDbWrite, "t"));
}
// ReplaceAll_SwapsTheEntireBuffer_Atomically was DELETED with ReplaceAllAsync in
// LocalDb Phase 2, and deliberately not replaced. It asserted a destructive
// delete-all-then-insert-all, which was the standby's anti-entropy apply: a resync