From 8267ab8ffcbf4c2165897efa3b8b53a088d2335d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 12:22:31 -0500 Subject: [PATCH] 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. --- .../Component-ExternalSystemGateway.md | 2 + .../requirements/Component-StoreAndForward.md | 10 +- .../DatabaseGateway.cs | 74 +++++++---- .../ExternalSystemClient.cs | 125 ++++++++++++------ .../StoreAndForwardService.cs | 50 +++++++ .../StoreAndForwardStorage.cs | 30 +++++ .../DatabaseGatewayTests.cs | 67 ++++++++++ .../ExternalSystemClientTests.cs | 68 ++++++++++ .../StoreAndForwardServiceTests.cs | 83 ++++++++++++ .../StoreAndForwardStorageTests.cs | 49 +++++++ 10 files changed, 484 insertions(+), 74 deletions(-) diff --git a/docs/requirements/Component-ExternalSystemGateway.md b/docs/requirements/Component-ExternalSystemGateway.md index f0e85574..98a1b92d 100644 --- a/docs/requirements/Component-ExternalSystemGateway.md +++ b/docs/requirements/Component-ExternalSystemGateway.md @@ -69,6 +69,7 @@ Each database connection definition includes: - Script calls `Database.CachedWrite("name", "sql", parameters)`. This is **deferred delivery**: the call returns a `TrackedOperationId` tracking handle immediately rather than the write result. - Payload includes: connection name, SQL statement, serialized parameter values. - The write is attempted immediately. On immediate success it is recorded as a terminal `Delivered` tracking record. On **transient failure** (database unavailable) it is buffered (`Pending`/`Retrying`) and retried per the connection's retry settings by the Store-and-Forward Engine. +- **Per-connection order (2026-12-02 review, decision B):** when writes to the same connection are already buffered, the new write is **not** attempted immediately — it is buffered behind them (`Pending`) and the Store-and-Forward sweep applies them in enqueue order, so a recovered database never sees a newer write before an older one. See [Component-StoreAndForward.md](Component-StoreAndForward.md) → Message Lifecycle. - On **permanent failure** (e.g. a SQL syntax or constraint error — a request that will never succeed), the error is returned **synchronously** to the calling script and the write is **not** buffered. The call is also recorded as a terminal `Failed` tracking record capturing the error. - Cached-write status is observable to scripts via `Tracking.Status(id)` (answered site-locally and authoritatively) and centrally via the Site Call Audit component. - **Audit emission**: each lifecycle transition (`CachedEnqueued`, `CachedAttempt`, `CachedTerminal`) emits an audit row via the combined cached-operation telemetry packet — one packet carries both the audit row and the SiteCalls upsert (see [Component-AuditLog.md](Component-AuditLog.md), Cached Operations — Combined Telemetry, and [Component-SiteCallAudit.md](Component-SiteCallAudit.md)). Audit-write failure never aborts the script. @@ -96,6 +97,7 @@ Scripts choose between two call modes per invocation, mirroring the dual-mode da ### Cached (Store-and-Forward) - Script calls `ExternalSystem.CachedCall("systemName", "methodName", params)`. This is **deferred delivery**: the call returns a `TrackedOperationId` tracking handle immediately rather than the response body. - The call is attempted immediately. If it succeeds, the response is discarded and the call is recorded as a terminal `Delivered` tracking record. +- **Per-system order (2026-12-02 review, decision B):** when calls to the same external system are already buffered, the new call makes **no** immediate HTTP request — it is buffered behind them (`Pending`) and delivered by the Store-and-Forward sweep in enqueue order, so a recovered system never receives a newer call before an older one. See [Component-StoreAndForward.md](Component-StoreAndForward.md) → Message Lifecycle. - On **transient failure** (connection refused, timeout, HTTP 5xx), the call is routed to the Store-and-Forward Engine for retry per the system's retry settings. The script does **not** block — the call is buffered (`Pending`/`Retrying`) and the script continues. - On **permanent failure** (HTTP 4xx), the error is returned **synchronously** to the calling script. No retry — the request itself is wrong. The call is also recorded as a terminal `Failed` tracking record capturing the error. - Cached-call status is observable to scripts via `Tracking.Status(id)` (answered site-locally and authoritatively) and centrally via the Site Call Audit component. diff --git a/docs/requirements/Component-StoreAndForward.md b/docs/requirements/Component-StoreAndForward.md index f69c95ac..eb966204 100644 --- a/docs/requirements/Component-StoreAndForward.md +++ b/docs/requirements/Component-StoreAndForward.md @@ -28,7 +28,9 @@ Site clusters only. The central cluster does not buffer messages. ```mermaid %%{init: {'theme':'base', 'themeVariables': {'textColor':'#111111','lineColor':'#555555','edgeLabelBackground':'#ffffff','fontSize':'15px'}}}%% flowchart TD - A([Script submits message]) --> B[Attempt immediate delivery] + A([Script submits message]) --> L{Lane already
holds a pending row?} + L -->|Yes| E + L -->|No| B[Attempt immediate delivery] B --> C{Delivered?} C -->|Success| D([Remove from buffer]) C -->|Failure| E[Buffer message] @@ -44,16 +46,18 @@ flowchart TD classDef bad fill:#f8cecc,stroke:#b85450,color:#111111; class A,D,H ok class B,F proc - class C,G dec + class C,G,L dec class E buf class I bad ``` +**A new message never overtakes buffered messages of its own lane (2026-12-02 review, decision B).** A lane is the `(category, target)` pair the sweep orders by (target = external system name, database connection name, or notification list name). The immediate attempt is made only when that lane holds **no `Pending` row**; otherwise the message is buffered behind the older rows without any delivery attempt (due-immediately, `last_attempt_at` null) and the sweep — which never passes a lane's backing-off head (SF-1, below) — delivers it right after them, in enqueue order. Before this, a target that had recovered while an older row was still backing off received the new message inline first, and the older row's later retry then overwrote it (e.g. two `Database.CachedWrite` updates to one row applied B-then-A). The check covers every path that could attempt inline: `EnqueueAsync`'s own immediate attempt, and the two callers that make their own first attempt before handing a transient failure to S&F — `ExternalSystem.CachedCall` (`ExternalSystemClient`, lane `ExternalSystem`/system name) and `Database.CachedWrite` (`DatabaseGateway`, lane `CachedDbWrite`/connection name), which make no HTTP request / SQL write at all when the lane is occupied and enqueue with `deferToSweep: true`. `Notify.Send` already never attempts inline (`deferToSweep`, below), so the sweep's per-lane ordering alone keeps notifications in order. The return contract is unchanged: the caller still gets its handle at once (`NotificationId` / `TrackedOperationId`) with an ordinary *buffered* result (`WasBuffered = true`), so a cached call's tracking row reads `Pending` until the sweep's attempt — exactly like a transiently-failed one — and its retry-loop telemetry flows as for any buffered call. An empty lane (or one holding only `Parked` rows, which never hold a lane) keeps the immediate attempt. The lane probe is a single `SELECT EXISTS` seek on the covering `idx_sf_messages_lane` leading `(status, category, target)` columns (no table or payload read, pinned by an `EXPLAIN QUERY PLAN` test), so it is cheap on every enqueue regardless of backlog size; it fails open — a probe that throws is logged and treated as an empty lane, i.e. the pre-existing behaviour. Ordering is guaranteed between calls whose enqueue completed before the next call started (e.g. sequential calls in one script); two calls racing concurrently from different scripts have no defined order, as before. A message buffered behind a lane counts its first sweep attempt as retry 1 (no inline attempt 0 was made), so a bounded `MaxRetries` grants it one attempt fewer than a transiently-failed call. + For notifications, "delivery" means forwarding the message to the central cluster via Central–Site Communication; "success" is central's ack, on which the message is cleared. `Notify.Send` is **enqueue-only**: it buffers the notification into the local SQLite S&F store and returns the `NotificationId` immediately — it never runs the forwarder's central Ask inline on the script thread (it passes `deferToSweep: true`, which buffers the row due-immediately and kicks a background sweep). Its worst-case latency is therefore the local SQLite insert, whether central is up or down; the actual forward happens on the sweep. `Notify.Send` also enqueues with `maxRetries: 0` — the documented "no limit" escape hatch (`StoreAndForward-015`) — so notifications are retried at the fixed forward interval until central acks and are **never parked for retry exhaustion**: a sustained central outage can no longer strand a notification behind per-message operator unparking. ("do not park" is thus the real behaviour for retry-exhaustion, not merely a happy-path aspiration — but see the two remaining parking causes below.) There are now exactly two ways a notification parks. First, a **corrupt buffered payload** (a row whose stored JSON no longer deserialises to a `NotificationSubmit`, or deserialises to null): the forwarder returns the delivery-handler contract's permanent-failure signal (`false`) so the engine parks the row, preserving the payload for operator forensics. This **supersedes `StoreAndForward-018`**, which discarded such rows by reporting them as delivered — a silent data loss with no parked row, no central `Notifications` row, and no audit trail. Retrying a corrupt payload is pointless (it can never deserialise), so parking, not retrying, is the correct home for it. Second, retry exhaustion under the `DefaultMaxRetries` cap — but because `Notify.Send` enqueues with `maxRetries: 0` (its unbounded-retry contract, above), that second cause is **off for script-produced notifications**, leaving corrupt payload as their only parking cause. (Retry-exhaustion parking remains reachable only for a hypothetical notification enqueued with a positive `maxRetries`.) -For the cached-call categories (`ExternalCall` and `DatabaseWrite`), the operation tracking table is the status record and the S&F buffer is purely the retry mechanism. A cached call that succeeds on its first immediate attempt is written directly as a terminal `Delivered` tracking row and never enters the S&F buffer. When immediate delivery fails transiently, the message is buffered and its tracking row moves to `Pending`/`Retrying`; the buffered message carries its `TrackedOperationId` so the tracking row and the retry record stay linked. When immediate delivery fails **permanently** (e.g. HTTP 4xx), the message is not buffered — the error is returned synchronously to the calling script as before — but the tracking row is written directly as a terminal `Failed` row capturing the error. On every tracking-table status transition the site emits `CachedCallTelemetry` to central. Neither the audit row nor the tracking row of that telemetry is awaited to commit on the script thread (Site Runtime, 2026-09-06): the audit row is enqueued on the site writer and its completion observed off-thread, and the tracking row goes through a single-writer queue whose reads wait for earlier queued writes so `Tracking.Status` stays read-your-writes — see `Component-SiteRuntime.md` → *Operation Tracking*. +For the cached-call categories (`ExternalCall` and `DatabaseWrite`), the operation tracking table is the status record and the S&F buffer is purely the retry mechanism. A cached call that succeeds on its first immediate attempt is written directly as a terminal `Delivered` tracking row and never enters the S&F buffer. A cached call issued while its lane already holds buffered calls makes no immediate attempt (above) and is buffered like a transient failure (`Pending`). When immediate delivery fails transiently, the message is buffered and its tracking row moves to `Pending`/`Retrying`; the buffered message carries its `TrackedOperationId` so the tracking row and the retry record stay linked. When immediate delivery fails **permanently** (e.g. HTTP 4xx), the message is not buffered — the error is returned synchronously to the calling script as before — but the tracking row is written directly as a terminal `Failed` row capturing the error. On every tracking-table status transition the site emits `CachedCallTelemetry` to central. Neither the audit row nor the tracking row of that telemetry is awaited to commit on the script thread (Site Runtime, 2026-09-06): the audit row is enqueued on the site writer and its completion observed off-thread, and the tracking row goes through a single-writer queue whose reads wait for earlier queued writes so `Tracking.Status` stays read-your-writes — see `Component-SiteRuntime.md` → *Operation Tracking*. Every cached-call outcome maps to a tracking-table state: immediate success → `Delivered`; transient failure → `Pending`/`Retrying`, eventually `Delivered` or `Parked`; permanent failure → terminal `Failed`; operator discard of a parked row → terminal `Discarded`. diff --git a/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/DatabaseGateway.cs b/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/DatabaseGateway.cs index 03a0597c..3f7a28e8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/DatabaseGateway.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/DatabaseGateway.cs @@ -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 + diff --git a/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs b/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs index c6f9a8e2..d489a079 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway/ExternalSystemClient.cs @@ -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); } } + /// + /// Buffers a cached call into store-and-forward. + /// false: this method already made the HTTP attempt and it failed transiently + /// (attemptImmediateDelivery: false — letting EnqueueAsync re-invoke the handler + /// would dispatch the same request a second time). true: no attempt was made + /// because the lane already holds buffered calls; the row is queued due-immediately + /// behind them (deferToSweep: true). + /// + private async Task EnqueueCachedCallAsync( + ExternalSystemDefinition system, + string systemName, + string methodName, + IReadOnlyDictionary? 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); + } + /// /// Delivers a buffered ExternalSystem call during a store-and-forward /// retry sweep. Returns true on success, false on permanent failure (the message diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs index 769c4116..51719554 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardService.cs @@ -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 + /// (category, target) lane holds no Pending row. Otherwise the message is buffered + /// behind the older rows (WasBuffered = true, 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 /// 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); } + /// + /// Returns whether the (category, target) lane already holds a Pending (buffered, + /// not yet delivered) row. Callers that make their own first delivery attempt + /// (ExternalSystem.CachedCall, Database.CachedWrite) consult it first: when + /// the lane is occupied they must not attempt inline — that would overtake the older + /// rows — and instead enqueue with deferToSweep: true so the sweep delivers the new + /// message behind them, in order. One covering-index seek on idx_sf_messages_lane. + /// + /// The lane's message category. + /// The lane's target (as passed to ). + /// true when the lane holds at least one Pending row. + /// + /// Fails OPEN: a probe that throws (e.g. a storage error on the shared LocalDb file) is + /// logged and answered false, 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. + /// + public async Task 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; + } + } + /// /// 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. diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs index d208298f..8dbbf1b1 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs @@ -186,6 +186,36 @@ public class StoreAndForwardStorage await cmd.ExecuteNonQueryAsync(); } + /// + /// Lane-existence probe for the immediate-delivery paths (2026-12-02 review, decision B): + /// 1 when the (category, target) lane holds at least one Pending row. An + /// EXISTS over the leading (status, category, target) columns of + /// idx_sf_messages_lane — one covering-index seek, no table or payload read + /// (pinned by an EXPLAIN QUERY PLAN test). + /// + internal const string LaneHasPendingSql = @" + SELECT EXISTS ( + SELECT 1 FROM sf_messages + WHERE status = @pending AND category = @category AND target = @target)"; + + /// + /// Returns whether the (category, target) lane already holds a Pending row. Parked + /// rows do not count — like the sweep, only pending rows hold a lane. + /// + /// The lane's message category. + /// The lane's target. + /// true when at least one Pending row exists for the lane. + public async Task 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; + } + /// /// Gets the messages that are due for retry (Pending status, last attempt older than retry /// interval), restricted per (category, target) lane to the due rows that are not diff --git a/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/DatabaseGatewayTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/DatabaseGatewayTests.cs index 38c802f3..2e339039 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/DatabaseGatewayTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/DatabaseGatewayTests.cs @@ -332,6 +332,73 @@ public class DatabaseGatewayTests : IDisposable Assert.Equal(0, ReadBufferDepth(sfDb)); } + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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 + } + + /// + /// Decision B: an empty lane is unchanged — a CachedWrite to a connection with nothing + /// buffered (only another connection's backlog) still executes inline. + /// + /// A task that represents the asynchronous operation. + [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)); + } + /// Verifies that a transient SQL error during buffered delivery is rethrown so the engine retries. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs index c2162454..a5faf4af 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ExternalSystemGateway.Tests/ExternalSystemClientTests.cs @@ -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 ── + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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()).Returns(_ => new HttpClient(new CallbackHttpMessageHandler(() => + { + Interlocked.Increment(ref requests); + return status; + }))); + + var localDb = CreateLocalDb("EsgLaneOrder"); + var storage = new StoreAndForwardStorage(localDb.Db, NullLogger.Instance); + await storage.InitializeAsync(); + var sf = new StoreAndForwardService(storage, new StoreAndForwardOptions + { + DefaultRetryInterval = TimeSpan.FromMinutes(10), + RetryTimerInterval = TimeSpan.FromMinutes(10), + }, NullLogger.Instance); + var client = new ExternalSystemClient( + _httpClientFactory, _repository, NullLogger.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); + } + + /// Test helper: answers every request with the status the callback returns. + private sealed class CallbackHttpMessageHandler(Func respond) : HttpMessageHandler + { + /// + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + => Task.FromResult(new HttpResponseMessage(respond()) { Content = new StringContent("{}") }); + } + // ── per-system call timeout ── /// Verifies that a call to a slow system times out as a transient error within the configured window. diff --git a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardServiceTests.cs index 9dca8b06..5de67aab 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardServiceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardServiceTests.cs @@ -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 ── + + /// + /// The immediate-delivery path must not overtake an older buffered row of the same + /// (category, target) 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. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task EnqueueAsync_LaneHasPendingRow_BuffersBehindItInsteadOfDeliveringImmediately() + { + var delivered = new List(); + 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); + } + + /// + /// The lane check is per (category, target) 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. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task EnqueueAsync_OtherLaneOrParkedRow_StillDeliversImmediately() + { + var delivered = new List(); + _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 ── /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs index 7d9d79bc..edfe5759 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs @@ -942,6 +942,55 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE") && !p.Contains("LAST TERM")); } + /// + /// Decision B (2026-12-02 review follow-up): the immediate-delivery lane probe is answered + /// by a seek on the covering idx_sf_messages_lane (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. + /// + /// A task that represents the asynchronous operation. + [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(); + 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")); + } + + /// + /// Decision B: the lane probe is true only for a Pending row of the exact + /// (category, target); Parked rows and other lanes do not count. + /// + /// A task that represents the asynchronous operation. + [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