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:
@@ -118,33 +118,48 @@ public class DatabaseGateway : IDatabaseGateway, ISandboxDatabaseConnectionSourc
|
||||
// * success -> Delivered, NOT buffered;
|
||||
// * PermanentDatabaseException -> Failed synchronously, NOT buffered;
|
||||
// * TransientDatabaseException -> buffered to S&F for retry.
|
||||
try
|
||||
{
|
||||
await ExecuteWriteAsync(
|
||||
connectionName, definition.ConnectionString, sql, parameters ?? EmptyParameters, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
//
|
||||
// Per-lane FIFO (2026-12-02 review, decision B): when this connection's S&F lane
|
||||
// already holds buffered writes, an inline attempt would overtake them — a recovered
|
||||
// database would apply the newer write first and the older retry would then overwrite
|
||||
// it. Make no attempt; buffer behind the lane (deferToSweep: LastAttemptAt stays null,
|
||||
// no attempt was made) so the sweep, which never passes a lane's backing-off head,
|
||||
// applies this write right after the older ones. The result is the ordinary buffered
|
||||
// result, so the TrackedOperationId reads as buffered.
|
||||
var behindPendingLane = await _storeAndForward
|
||||
.LaneHasPendingAsync(StoreAndForwardCategory.CachedDbWrite, connectionName)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Immediate success — the write is done; do not buffer.
|
||||
return new ExternalCallResult(Success: true, ResponseJson: null, ErrorMessage: null, WasBuffered: false);
|
||||
}
|
||||
catch (PermanentDatabaseException ex)
|
||||
if (!behindPendingLane)
|
||||
{
|
||||
// Permanent failures are returned to the script and never buffered —
|
||||
// mirrors the PermanentExternalSystemException branch on the API path.
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"CachedWrite to '{Connection}' failed permanently (SQL error {Number}); returning Failed without buffering.",
|
||||
connectionName, ex.SqlErrorNumber);
|
||||
return new ExternalCallResult(
|
||||
Success: false, ResponseJson: null, ErrorMessage: $"Permanent database error: {ex.Message}", WasBuffered: false);
|
||||
}
|
||||
catch (TransientDatabaseException ex)
|
||||
{
|
||||
// Transient failure — hand to S&F so the retry sweep delivers it.
|
||||
_logger.LogDebug(
|
||||
ex,
|
||||
"CachedWrite to '{Connection}' failed transiently (SQL error {Number}); buffering for retry.",
|
||||
connectionName, ex.SqlErrorNumber);
|
||||
try
|
||||
{
|
||||
await ExecuteWriteAsync(
|
||||
connectionName, definition.ConnectionString, sql, parameters ?? EmptyParameters, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Immediate success — the write is done; do not buffer.
|
||||
return new ExternalCallResult(Success: true, ResponseJson: null, ErrorMessage: null, WasBuffered: false);
|
||||
}
|
||||
catch (PermanentDatabaseException ex)
|
||||
{
|
||||
// Permanent failures are returned to the script and never buffered —
|
||||
// mirrors the PermanentExternalSystemException branch on the API path.
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"CachedWrite to '{Connection}' failed permanently (SQL error {Number}); returning Failed without buffering.",
|
||||
connectionName, ex.SqlErrorNumber);
|
||||
return new ExternalCallResult(
|
||||
Success: false, ResponseJson: null, ErrorMessage: $"Permanent database error: {ex.Message}", WasBuffered: false);
|
||||
}
|
||||
catch (TransientDatabaseException ex)
|
||||
{
|
||||
// Transient failure — hand to S&F so the retry sweep delivers it.
|
||||
_logger.LogDebug(
|
||||
ex,
|
||||
"CachedWrite to '{Connection}' failed transiently (SQL error {Number}); buffering for retry.",
|
||||
connectionName, ex.SqlErrorNumber);
|
||||
}
|
||||
}
|
||||
|
||||
var payload = JsonSerializer.Serialize(new
|
||||
@@ -171,10 +186,15 @@ public class DatabaseGateway : IDatabaseGateway, ISandboxDatabaseConnectionSourc
|
||||
definition.RetryDelay > TimeSpan.Zero ? definition.RetryDelay : null,
|
||||
// attemptImmediateDelivery: false — this method already
|
||||
// made the write attempt above (the transient-classified failure is
|
||||
// exactly why we are buffering). Letting EnqueueAsync re-invoke the
|
||||
// delivery handler would execute the same write a second time —
|
||||
// exactly why we are buffering), or deliberately made none because the
|
||||
// lane is occupied. Letting EnqueueAsync re-invoke the delivery handler
|
||||
// would execute the same write a second time / overtake the lane —
|
||||
// mirrors ExternalSystemClient.CachedCallAsync.
|
||||
attemptImmediateDelivery: false,
|
||||
// Behind an occupied lane no attempt was made, so the row is due
|
||||
// immediately (LastAttemptAt null) — the sweep still holds it behind
|
||||
// the older rows.
|
||||
deferToSweep: behindPendingLane,
|
||||
// Pin the S&F message id to the
|
||||
// TrackedOperationId so the retry loop can
|
||||
// read it back via StoreAndForwardMessage.Id and emit per-attempt +
|
||||
|
||||
@@ -108,6 +108,21 @@ public class ExternalSystemClient : IExternalSystemClient
|
||||
return new ExternalCallResult(false, null, $"External system '{systemName}' or method '{methodName}' not found");
|
||||
}
|
||||
|
||||
// Per-lane FIFO (2026-12-02 review, decision B): when this system's S&F lane already
|
||||
// holds buffered calls, an inline attempt would overtake them (a recovered target would
|
||||
// receive the newer call first). Make no HTTP request; buffer behind the lane instead —
|
||||
// deferToSweep leaves LastAttemptAt null (no attempt was made), so the sweep, which never
|
||||
// passes a lane's backing-off head, delivers this call right after the older ones. The
|
||||
// result is the ordinary buffered result, so the TrackedOperationId reads as buffered.
|
||||
if (_storeAndForward != null
|
||||
&& await _storeAndForward.LaneHasPendingAsync(StoreAndForwardCategory.ExternalSystem, systemName))
|
||||
{
|
||||
await EnqueueCachedCallAsync(
|
||||
system, systemName, methodName, parameters, originInstanceName,
|
||||
trackedOperationId, executionId, sourceScript, parentExecutionId, behindPendingLane: true);
|
||||
return new ExternalCallResult(true, null, null, WasBuffered: true);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var response = await InvokeHttpAsync(system, method, parameters, cancellationToken);
|
||||
@@ -126,55 +141,77 @@ public class ExternalSystemClient : IExternalSystemClient
|
||||
return new ExternalCallResult(false, null, "Transient error and store-and-forward not available");
|
||||
}
|
||||
|
||||
var payload = JsonSerializer.Serialize(new
|
||||
{
|
||||
SystemName = systemName,
|
||||
MethodName = methodName,
|
||||
Parameters = parameters
|
||||
});
|
||||
|
||||
// attemptImmediateDelivery: false — this method already made the HTTP
|
||||
// attempt above; letting EnqueueAsync re-invoke the handler would
|
||||
// dispatch the same request a second time.
|
||||
//
|
||||
// The entity's MaxRetries is a non-nullable
|
||||
// int whose default is 0, and the Store-and-Forward engine interprets a
|
||||
// stored MaxRetries of 0 as "no limit" (retry forever) — see
|
||||
// StoreAndForwardMessage.MaxRetries ("0 = no limit") and the retry-sweep
|
||||
// guard `MaxRetries > 0 && ...`. Passing 0 verbatim would therefore turn
|
||||
// every unconfigured cached call into an unbounded retry loop. A 0 is
|
||||
// treated as "unset" and passed as null so the bounded S&F default
|
||||
// applies; the RetryDelay default of TimeSpan.Zero is likewise unset.
|
||||
await _storeAndForward.EnqueueAsync(
|
||||
StoreAndForwardCategory.ExternalSystem,
|
||||
systemName,
|
||||
payload,
|
||||
originInstanceName,
|
||||
system.MaxRetries > 0 ? system.MaxRetries : null,
|
||||
system.RetryDelay > TimeSpan.Zero ? system.RetryDelay : null,
|
||||
attemptImmediateDelivery: false,
|
||||
// Pin the S&F message id to the
|
||||
// TrackedOperationId so the retry loop can read it back via
|
||||
// StoreAndForwardMessage.Id and emit per-attempt + terminal
|
||||
// cached-call telemetry. Null -> S&F
|
||||
// mints its own GUID (legacy behaviour).
|
||||
messageId: trackedOperationId?.ToString(),
|
||||
// Thread the originating
|
||||
// script execution's ExecutionId + SourceScript onto the
|
||||
// buffered row so the retry-loop cached-call audit rows carry
|
||||
// the same provenance the script-side cached rows do.
|
||||
executionId: executionId,
|
||||
sourceScript: sourceScript,
|
||||
// Thread the spawning
|
||||
// inbound-API request's ExecutionId onto the buffered row so
|
||||
// the retry-loop cached-call audit rows correlate back to the
|
||||
// cross-execution chain. Null for a non-routed run.
|
||||
parentExecutionId: parentExecutionId);
|
||||
await EnqueueCachedCallAsync(
|
||||
system, systemName, methodName, parameters, originInstanceName,
|
||||
trackedOperationId, executionId, sourceScript, parentExecutionId, behindPendingLane: false);
|
||||
|
||||
return new ExternalCallResult(true, null, null, WasBuffered: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Buffers a cached call into store-and-forward. <paramref name="behindPendingLane"/>
|
||||
/// <c>false</c>: this method already made the HTTP attempt and it failed transiently
|
||||
/// (<c>attemptImmediateDelivery: false</c> — letting EnqueueAsync re-invoke the handler
|
||||
/// would dispatch the same request a second time). <c>true</c>: no attempt was made
|
||||
/// because the lane already holds buffered calls; the row is queued due-immediately
|
||||
/// behind them (<c>deferToSweep: true</c>).
|
||||
/// </summary>
|
||||
private async Task EnqueueCachedCallAsync(
|
||||
ExternalSystemDefinition system,
|
||||
string systemName,
|
||||
string methodName,
|
||||
IReadOnlyDictionary<string, object?>? parameters,
|
||||
string? originInstanceName,
|
||||
TrackedOperationId? trackedOperationId,
|
||||
Guid? executionId,
|
||||
string? sourceScript,
|
||||
Guid? parentExecutionId,
|
||||
bool behindPendingLane)
|
||||
{
|
||||
var payload = JsonSerializer.Serialize(new
|
||||
{
|
||||
SystemName = systemName,
|
||||
MethodName = methodName,
|
||||
Parameters = parameters
|
||||
});
|
||||
|
||||
// The entity's MaxRetries is a non-nullable
|
||||
// int whose default is 0, and the Store-and-Forward engine interprets a
|
||||
// stored MaxRetries of 0 as "no limit" (retry forever) — see
|
||||
// StoreAndForwardMessage.MaxRetries ("0 = no limit") and the retry-sweep
|
||||
// guard `MaxRetries > 0 && ...`. Passing 0 verbatim would therefore turn
|
||||
// every unconfigured cached call into an unbounded retry loop. A 0 is
|
||||
// treated as "unset" and passed as null so the bounded S&F default
|
||||
// applies; the RetryDelay default of TimeSpan.Zero is likewise unset.
|
||||
await _storeAndForward!.EnqueueAsync(
|
||||
StoreAndForwardCategory.ExternalSystem,
|
||||
systemName,
|
||||
payload,
|
||||
originInstanceName,
|
||||
system.MaxRetries > 0 ? system.MaxRetries : null,
|
||||
system.RetryDelay > TimeSpan.Zero ? system.RetryDelay : null,
|
||||
attemptImmediateDelivery: false,
|
||||
deferToSweep: behindPendingLane,
|
||||
// Pin the S&F message id to the
|
||||
// TrackedOperationId so the retry loop can read it back via
|
||||
// StoreAndForwardMessage.Id and emit per-attempt + terminal
|
||||
// cached-call telemetry. Null -> S&F
|
||||
// mints its own GUID (legacy behaviour).
|
||||
messageId: trackedOperationId?.ToString(),
|
||||
// Thread the originating
|
||||
// script execution's ExecutionId + SourceScript onto the
|
||||
// buffered row so the retry-loop cached-call audit rows carry
|
||||
// the same provenance the script-side cached rows do.
|
||||
executionId: executionId,
|
||||
sourceScript: sourceScript,
|
||||
// Thread the spawning
|
||||
// inbound-API request's ExecutionId onto the buffered row so
|
||||
// the retry-loop cached-call audit rows correlate back to the
|
||||
// cross-execution chain. Null for a non-routed run.
|
||||
parentExecutionId: parentExecutionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delivers a buffered ExternalSystem call during a store-and-forward
|
||||
/// retry sweep. Returns true on success, false on permanent failure (the message
|
||||
|
||||
@@ -611,6 +611,11 @@ public class StoreAndForwardService
|
||||
/// Attempts immediate delivery first. On transient failure, buffers for retry.
|
||||
/// On permanent failure (handler returns false), returns false immediately.
|
||||
///
|
||||
/// Per-lane FIFO: the immediate attempt is made only when the message's
|
||||
/// <c>(category, target)</c> lane holds no Pending row. Otherwise the message is buffered
|
||||
/// behind the older rows (<c>WasBuffered = true</c>, no handler call) and the sweep
|
||||
/// delivers the lane in enqueue order — a new message never overtakes buffered ones.
|
||||
///
|
||||
/// Retry-count lifecycle — the immediate (or caller-made) delivery attempt
|
||||
/// is attempt 0 and is not counted; the background retry sweep increments
|
||||
/// <see cref="StoreAndForwardMessage.RetryCount"/> on each retry. A buffered
|
||||
@@ -727,6 +732,19 @@ public class StoreAndForwardService
|
||||
// case re-invoking the handler here would dispatch the request twice.
|
||||
if (attemptImmediateDelivery && _deliveryHandlers.TryGetValue(category, out var handler))
|
||||
{
|
||||
// Per-lane FIFO (2026-12-02 review, decision B): when the (category, target)
|
||||
// lane already holds a buffered row, an inline attempt would overtake it. Buffer
|
||||
// behind it instead — due-immediately (LastAttemptAt null, no attempt was made),
|
||||
// so the sweep, which never passes a lane's backing-off head (SF-1), delivers it
|
||||
// right after the older rows. An empty lane keeps the immediate attempt.
|
||||
if (await LaneHasPendingAsync(category, target))
|
||||
{
|
||||
await BufferAsync(message);
|
||||
RaiseActivity("Queued", category, $"Buffered behind pending lane: {target}");
|
||||
TriggerSweep();
|
||||
return new StoreAndForwardResult(true, message.Id, true);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var success = await handler(message);
|
||||
@@ -773,6 +791,38 @@ public class StoreAndForwardService
|
||||
return new StoreAndForwardResult(true, message.Id, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether the <c>(category, target)</c> lane already holds a Pending (buffered,
|
||||
/// not yet delivered) row. Callers that make their own first delivery attempt
|
||||
/// (<c>ExternalSystem.CachedCall</c>, <c>Database.CachedWrite</c>) consult it first: when
|
||||
/// the lane is occupied they must not attempt inline — that would overtake the older
|
||||
/// rows — and instead enqueue with <c>deferToSweep: true</c> so the sweep delivers the new
|
||||
/// message behind them, in order. One covering-index seek on <c>idx_sf_messages_lane</c>.
|
||||
/// </summary>
|
||||
/// <param name="category">The lane's message category.</param>
|
||||
/// <param name="target">The lane's target (as passed to <see cref="EnqueueAsync"/>).</param>
|
||||
/// <returns><c>true</c> when the lane holds at least one Pending row.</returns>
|
||||
/// <remarks>
|
||||
/// Fails OPEN: a probe that throws (e.g. a storage error on the shared LocalDb file) is
|
||||
/// logged and answered <c>false</c>, so the caller keeps its pre-existing immediate
|
||||
/// attempt rather than turning a healthy call into an exception — the same behaviour the
|
||||
/// paths had before the lane check existed.
|
||||
/// </remarks>
|
||||
public async Task<bool> LaneHasPendingAsync(StoreAndForwardCategory category, string target)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _storage.LaneHasPendingAsync(category, target);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"S&F lane probe for {Category}/{Target} failed; assuming the lane is empty (immediate attempt allowed)",
|
||||
category, target);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists a message to the local SQLite buffer and replicates the
|
||||
/// add to the standby node so a failover does not lose the buffered message.
|
||||
|
||||
@@ -186,6 +186,36 @@ public class StoreAndForwardStorage
|
||||
await cmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lane-existence probe for the immediate-delivery paths (2026-12-02 review, decision B):
|
||||
/// <c>1</c> when the <c>(category, target)</c> lane holds at least one Pending row. An
|
||||
/// <c>EXISTS</c> over the leading <c>(status, category, target)</c> columns of
|
||||
/// <c>idx_sf_messages_lane</c> — one covering-index seek, no table or payload read
|
||||
/// (pinned by an <c>EXPLAIN QUERY PLAN</c> test).
|
||||
/// </summary>
|
||||
internal const string LaneHasPendingSql = @"
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM sf_messages
|
||||
WHERE status = @pending AND category = @category AND target = @target)";
|
||||
|
||||
/// <summary>
|
||||
/// Returns whether the <c>(category, target)</c> lane already holds a Pending row. Parked
|
||||
/// rows do not count — like the sweep, only pending rows hold a lane.
|
||||
/// </summary>
|
||||
/// <param name="category">The lane's message category.</param>
|
||||
/// <param name="target">The lane's target.</param>
|
||||
/// <returns><c>true</c> when at least one Pending row exists for the lane.</returns>
|
||||
public async Task<bool> LaneHasPendingAsync(StoreAndForwardCategory category, string target)
|
||||
{
|
||||
await using var connection = OpenConnection();
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = LaneHasPendingSql;
|
||||
cmd.Parameters.AddWithValue("@pending", (int)StoreAndForwardMessageStatus.Pending);
|
||||
cmd.Parameters.AddWithValue("@category", (int)category);
|
||||
cmd.Parameters.AddWithValue("@target", target);
|
||||
return Convert.ToInt64(await cmd.ExecuteScalarAsync()) != 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the messages that are due for retry (Pending status, last attempt older than retry
|
||||
/// interval), restricted per <c>(category, target)</c> lane to the due rows that are not
|
||||
|
||||
Reference in New Issue
Block a user