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:
@@ -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.
|
||||
|
||||
@@ -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<br/>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`.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user