fix(sitecalls): Parked is re-openable end to end — operator Retry/Discard reach the site tracking row and central SiteCalls (SCA-1, WP4 task 4.9)

This commit is contained in:
Joseph Doherty
2026-12-03 10:18:43 -05:00
parent 4070f7efca
commit 5c67559a25
12 changed files with 578 additions and 15 deletions
+20 -2
View File
@@ -101,10 +101,19 @@ never regresses. Within an equal *non-terminal* rank (the `Attempted`/`Skipped`
retry phase), the packet with the newest `UpdatedAtUtc` wins — so a retrying retry phase), the packet with the newest `UpdatedAtUtc` wins — so a retrying
call's `RetryCount`/`LastError`/`HttpStatus` stay live instead of freezing at the call's `RetryCount`/`LastError`/`HttpStatus` stay live instead of freezing at the
first `Attempted` write. Equal *terminal* rank stays immutable (a later first `Attempted` write. Equal *terminal* rank stays immutable (a later
`Delivered` never overwrites an earlier `Parked`), equal stamps are an idempotent `Failed` never overwrites an earlier `Delivered`), equal stamps are an idempotent
no-op, and a lower rank is always a no-op — so at-least-once and out-of-order no-op, and a lower rank is always a no-op — so at-least-once and out-of-order
telemetry remain harmless. telemetry remain harmless.
**`Parked` is the one re-openable state (SCA-1, 2026-12).** A **strictly newer**
`Attempted`, `Delivered`, `Failed` or `Discarded` packet replaces a `Parked` row
(operator Retry re-opens the call, then its retried outcome arrives; operator
Discard closes it). Only strictly newer — a stale pre-park packet replayed late,
or any `Submitted`/`Forwarded`, leaves it `Parked`; `Delivered`/`Failed`/`Discarded`
stay immutable. Before this a relayed Retry or Discard could never land: the row
stayed `Parked` until the 365-day purge, the Parked KPI counted it forever and the
page kept offering Retry/Discard on it.
From v1.x onward, the `CachedCallTelemetry` message additively carries the From v1.x onward, the `CachedCallTelemetry` message additively carries the
`AuditEvent` content alongside the existing operational fields. Central's `AuditEvent` content alongside the existing operational fields. Central's
`AuditLogIngestActor` (Audit Log #23) performs both the immutable `AuditLog` `AuditLogIngestActor` (Audit Log #23) performs both the immutable `AuditLog`
@@ -217,7 +226,16 @@ Parked cached calls live in the owning site's S&F buffer. Operator Retry/Discard
from the Central UI is relayed to that site as a `RetryParkedOperation` / from the Central UI is relayed to that site as a `RetryParkedOperation` /
`DiscardParkedOperation` command over the command/control channel. The site `DiscardParkedOperation` command over the command/control channel. The site
applies the change and emits telemetry reflecting the new state; central never applies the change and emits telemetry reflecting the new state; central never
mutates the `SiteCalls` row directly. If the site is offline the command fails mutates the `SiteCalls` row directly. Concretely (SCA-1): the S&F service notifies
the cached-call observer with `OperatorRetried` / `OperatorDiscarded`; the
lifecycle bridge writes one `CachedSubmit`/`Submitted` row (operational status
`Attempted`, no terminal stamp, RetryCount 0) for a Retry or one
`CachedResolve`/`Discarded` row for a Discard; the forwarder re-opens the
site tracking row (`ReopenParkedAsync`: `Attempted`, `TerminalAtUtc` cleared) or
closes it (`RecordDiscardedAsync`), so `Tracking.Status(id)` follows too; the
cached-telemetry drain and the reconciliation pull then carry the newer row to
central, whose guard accepts it over `Parked`. A retried call's later attempts and
outcome land normally because the row is no longer terminal. If the site is offline the command fails
fast and the UI surfaces a "site unreachable" message. fast and the UI surfaces a "site unreachable" message.
On a **successful** relay (the site acks `Applied`), `SiteCallAuditActor` emits On a **successful** relay (the site acks `Applied`), `SiteCallAuditActor` emits
@@ -36,6 +36,19 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Site.Telemetry;
/// </remarks> /// </remarks>
public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver
{ {
/// <summary>
/// Operational status a re-opened (operator-retried) Parked call carries (SCA-1). A
/// <see cref="AuditKind.CachedSubmit"/> packet whose operational status is this value — rather
/// than the initial submit's <c>"Submitted"</c> — tells
/// <see cref="CachedCallTelemetryForwarder"/> to re-open the tracking row instead of
/// inserting one. <c>Attempted</c> is also what central's <c>SiteCalls</c> guard accepts over
/// <c>Parked</c> when newer.
/// </summary>
public const string ReopenedOperationalStatus = "Attempted";
/// <summary>Operational status of an operator-discarded call (SCA-1).</summary>
public const string DiscardedOperationalStatus = "Discarded";
private readonly ICachedCallTelemetryForwarder _forwarder; private readonly ICachedCallTelemetryForwarder _forwarder;
private readonly ILogger<CachedCallLifecycleBridge> _logger; private readonly ILogger<CachedCallLifecycleBridge> _logger;
@@ -70,6 +83,19 @@ public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver
try try
{ {
// SCA-1: operator transitions out of Parked are not attempts — one row each.
if (context.Outcome == CachedCallAttemptOutcome.OperatorRetried)
{
await EmitReopenAsync(context, ct).ConfigureAwait(false);
return;
}
if (context.Outcome == CachedCallAttemptOutcome.OperatorDiscarded)
{
await EmitResolveAsync(context, ct).ConfigureAwait(false);
return;
}
await EmitAttemptedAsync(context, ct).ConfigureAwait(false); await EmitAttemptedAsync(context, ct).ConfigureAwait(false);
if (IsTerminal(context.Outcome)) if (IsTerminal(context.Outcome))
@@ -113,6 +139,27 @@ public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver
await _forwarder.ForwardAsync(packet, ct).ConfigureAwait(false); await _forwarder.ForwardAsync(packet, ct).ConfigureAwait(false);
} }
/// <summary>
/// Operator Retry of a Parked call (SCA-1): one <see cref="AuditKind.CachedSubmit"/> /
/// <see cref="AuditStatus.Submitted"/> row — the call was re-submitted to the retry loop —
/// whose operational half is <see cref="ReopenedOperationalStatus"/> with no terminal
/// stamp, RetryCount 0 and no error. The forwarder re-opens the tracking row from it, and
/// the cached-telemetry drain carries the re-opened state to central.
/// </summary>
private async Task EmitReopenAsync(CachedCallAttemptContext context, CancellationToken ct)
{
var packet = BuildPacket(
context,
kind: AuditKind.CachedSubmit,
status: AuditStatus.Submitted,
operationalStatus: ReopenedOperationalStatus,
terminalAtUtc: null,
lastError: null,
httpStatus: null);
await _forwarder.ForwardAsync(packet, ct).ConfigureAwait(false);
}
private async Task EmitResolveAsync(CachedCallAttemptContext context, CancellationToken ct) private async Task EmitResolveAsync(CachedCallAttemptContext context, CancellationToken ct)
{ {
var (auditStatus, operationalStatus) = TerminalOutcomeToStatuses(context.Outcome); var (auditStatus, operationalStatus) = TerminalOutcomeToStatuses(context.Outcome);
@@ -214,6 +261,8 @@ public sealed class CachedCallLifecycleBridge : ICachedCallLifecycleObserver
(AuditStatus.Parked, "Parked"), (AuditStatus.Parked, "Parked"),
CachedCallAttemptOutcome.ParkedMaxRetries => CachedCallAttemptOutcome.ParkedMaxRetries =>
(AuditStatus.Parked, "Parked"), (AuditStatus.Parked, "Parked"),
CachedCallAttemptOutcome.OperatorDiscarded =>
(AuditStatus.Discarded, DiscardedOperationalStatus),
// TransientFailure isn't terminal — see IsTerminal — but the switch // TransientFailure isn't terminal — see IsTerminal — but the switch
// is exhaustive so we route it through Failed for safety. // is exhaustive so we route it through Failed for safety.
CachedCallAttemptOutcome.TransientFailure => CachedCallAttemptOutcome.TransientFailure =>
@@ -174,6 +174,14 @@ public sealed class CachedCallTelemetryForwarder : ICachedCallTelemetryForwarder
{ {
switch (audit.Kind) switch (audit.Kind)
{ {
case AuditKind.CachedSubmit
when telemetry.Operational.Status == CachedCallLifecycleBridge.ReopenedOperationalStatus:
// SCA-1: an operator re-queued a Parked call — re-open the row
// (clears TerminalAtUtc) so the retried attempts and outcome land.
await _trackingStore.ReopenParkedAsync(
telemetry.Operational.TrackedOperationId, ct).ConfigureAwait(false);
break;
case AuditKind.CachedSubmit: case AuditKind.CachedSubmit:
// Enqueue — insert-if-not-exists with the operational // Enqueue — insert-if-not-exists with the operational
// channel as the kind discriminator. RetryCount is fixed // channel as the kind discriminator. RetryCount is fixed
@@ -205,6 +213,16 @@ public sealed class CachedCallTelemetryForwarder : ICachedCallTelemetryForwarder
ct).ConfigureAwait(false); ct).ConfigureAwait(false);
break; break;
case AuditKind.CachedResolve
when telemetry.Operational.Status == CachedCallLifecycleBridge.DiscardedOperationalStatus:
// SCA-1: an operator discard closes a Parked row as Discarded (the
// first-write-wins terminal flip below would leave it Parked).
await _trackingStore.RecordDiscardedAsync(
telemetry.Operational.TrackedOperationId,
telemetry.Operational.LastError,
ct).ConfigureAwait(false);
break;
case AuditKind.CachedResolve: case AuditKind.CachedResolve:
// Terminal — first-write-wins on the resolve flip. // Terminal — first-write-wins on the resolve flip.
await _trackingStore.RecordTerminalAsync( await _trackingStore.RecordTerminalAsync(
@@ -120,4 +120,17 @@ public enum CachedCallAttemptOutcome
/// <summary>Retry budget exhausted — terminal Parked state.</summary> /// <summary>Retry budget exhausted — terminal Parked state.</summary>
ParkedMaxRetries, ParkedMaxRetries,
/// <summary>
/// An operator re-queued a PARKED cached call (Retry on the Site Calls / Parked Messages
/// page). Not an attempt: the call is back in the retry loop, so its tracking row leaves
/// <c>Parked</c> (SCA-1, 2026-12). Additive.
/// </summary>
OperatorRetried,
/// <summary>
/// An operator discarded a PARKED cached call — terminal <c>Discarded</c> state (SCA-1,
/// 2026-12). Not an attempt. Additive.
/// </summary>
OperatorDiscarded,
} }
@@ -96,6 +96,30 @@ public interface IOperationTrackingStore
int? httpStatus, int? httpStatus,
CancellationToken ct = default); CancellationToken ct = default);
/// <summary>
/// Re-opens a <c>Parked</c> row after an operator Retry re-queued the call (SCA-1): sets
/// <c>Status = Attempted</c>, <c>RetryCount = 0</c>, clears <c>LastError</c>/<c>HttpStatus</c>
/// and <c>TerminalAtUtc</c>, and stamps <c>UpdatedAtUtc</c>, so the attempts and terminal
/// outcome of the retried delivery land on the row again. A row that is not <c>Parked</c>
/// is left untouched.
/// </summary>
/// <param name="id">Operation ID to re-open.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task ReopenParkedAsync(TrackedOperationId id, CancellationToken ct = default);
/// <summary>
/// Records an operator Discard (SCA-1): sets <c>Status = Discarded</c> and stamps
/// <c>TerminalAtUtc</c>/<c>UpdatedAtUtc</c> on a row that is <c>Parked</c> or not yet
/// terminal. Any other terminal row (Delivered, Failed, an earlier Discarded) is left
/// untouched.
/// </summary>
/// <param name="id">Operation ID that was discarded.</param>
/// <param name="lastError">Optional note recorded as the row's last error.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task RecordDiscardedAsync(TrackedOperationId id, string? lastError, CancellationToken ct = default);
/// <summary> /// <summary>
/// Return the latest snapshot for the supplied id, or <c>null</c> when no /// Return the latest snapshot for the supplied id, or <c>null</c> when no
/// tracking row exists (purged or never recorded). /// tracking row exists (purged or never recorded).
@@ -27,6 +27,9 @@ public class SiteCallAuditRepository : ISiteCallAuditRepository
// Monotonic status ordering: // Monotonic status ordering:
// Submitted < Forwarded < Attempted == Skipped < Delivered == Failed == Parked == Discarded. // Submitted < Forwarded < Attempted == Skipped < Delivered == Failed == Parked == Discarded.
// One deliberate exception (SCA-1, 2026-12): Parked is re-openable — a STRICTLY NEWER
// Attempted / Delivered / Failed / Discarded replaces a Parked row (operator Retry or
// Discard at the site); see the last clause of MonotonicUpdateSql.
// A higher incoming rank always wins. WITHIN an equal NON-terminal rank // A higher incoming rank always wins. WITHIN an equal NON-terminal rank
// (Attempted/Skipped, rank 2 — and the transient Submitted/Forwarded ranks), // (Attempted/Skipped, rank 2 — and the transient Submitted/Forwarded ranks),
// the newest UpdatedAtUtc wins so a retrying call's live RetryCount/LastError // the newest UpdatedAtUtc wins so a retrying call's live RetryCount/LastError
@@ -324,6 +327,14 @@ WHERE TrackedOperationId = @Id
ELSE -1 ELSE -1
END) END)
AND @Rank < @TerminalRank AND @Rank < @TerminalRank
AND UpdatedAtUtc < @UpdatedAtUtc )
-- SCA-1: Parked is re-openable. An operator Retry re-queues a parked call at the
-- site (Attempted, then the retried outcome) and a Discard closes it (Discarded);
-- both reach central as NEWER packets. Accept them over Parked only — Delivered,
-- Failed and Discarded stay immutable — and only when strictly newer, so a stale
-- pre-park packet replayed late can never reopen the row.
OR ( Status = 'Parked'
AND @Status IN ('Attempted', 'Delivered', 'Failed', 'Discarded')
AND UpdatedAtUtc < @UpdatedAtUtc ) );"; AND UpdatedAtUtc < @UpdatedAtUtc ) );";
/// <summary> /// <summary>
@@ -259,6 +259,65 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable,
}, ct).ConfigureAwait(false); }, ct).ConfigureAwait(false);
} }
/// <inheritdoc/>
public async Task ReopenParkedAsync(TrackedOperationId id, CancellationToken ct = default)
{
var now = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);
var idText = id.ToString();
await EnqueueAsync($"reopen {idText}", (conn, tx) =>
{
using var cmd = conn.CreateCommand();
cmd.Transaction = tx;
// SCA-1: Parked is re-openable. Only a Parked row moves — every other terminal
// state stays immutable, and a non-terminal row is already in the loop.
cmd.CommandText = """
UPDATE OperationTracking
SET Status = 'Attempted',
RetryCount = 0,
LastError = NULL,
HttpStatus = NULL,
UpdatedAtUtc = $now,
TerminalAtUtc = NULL
WHERE TrackedOperationId = $id
AND Status = 'Parked';
""";
cmd.Parameters.AddWithValue("$id", idText);
cmd.Parameters.AddWithValue("$now", now);
cmd.ExecuteNonQuery();
}, ct).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task RecordDiscardedAsync(TrackedOperationId id, string? lastError, CancellationToken ct = default)
{
var now = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);
var idText = id.ToString();
await EnqueueAsync($"discard {idText}", (conn, tx) =>
{
using var cmd = conn.CreateCommand();
cmd.Transaction = tx;
// SCA-1: an operator discard closes a Parked (or still-open) row as Discarded;
// Delivered/Failed/Discarded stay immutable.
cmd.CommandText = """
UPDATE OperationTracking
SET Status = 'Discarded',
LastError = COALESCE($lastError, LastError),
UpdatedAtUtc = $now,
TerminalAtUtc = $now
WHERE TrackedOperationId = $id
AND (TerminalAtUtc IS NULL OR Status = 'Parked');
""";
cmd.Parameters.AddWithValue("$id", idText);
cmd.Parameters.AddWithValue("$lastError", (object?)lastError ?? DBNull.Value);
cmd.Parameters.AddWithValue("$now", now);
cmd.ExecuteNonQuery();
}, ct).ConfigureAwait(false);
}
/// <inheritdoc/> /// <inheritdoc/>
public async Task RecordTerminalAsync( public async Task RecordTerminalAsync(
TrackedOperationId id, TrackedOperationId id,
@@ -1274,6 +1274,17 @@ public class StoreAndForwardService
RaiseActivity("Retry", captured.Category, RaiseActivity("Retry", captured.Category,
$"Parked message {messageId} moved back to queue"); $"Parked message {messageId} moved back to queue");
// SCA-1: a re-queued cached call leaves Parked end to end — the observer re-opens the
// site tracking row and emits telemetry so central's SiteCalls row follows. Without it
// the row stayed Parked forever (later attempts were no-ops on a terminal row).
await PostObserverNotification(
captured,
CachedCallAttemptOutcome.OperatorRetried,
lastError: null,
httpStatus: null,
occurredAtUtc: DateTime.UtcNow,
durationMs: null);
return true; return true;
} }
@@ -1299,6 +1310,19 @@ public class StoreAndForwardService
{ {
RaiseActivity("Discard", message?.Category ?? StoreAndForwardCategory.ExternalSystem, RaiseActivity("Discard", message?.Category ?? StoreAndForwardCategory.ExternalSystem,
$"Parked message {messageId} discarded"); $"Parked message {messageId} discarded");
// SCA-1: record the discard on the tracking row (Parked → Discarded) and emit
// telemetry, so Tracking.Status and central's SiteCalls row stop reporting Parked.
if (message is not null)
{
await PostObserverNotification(
message,
CachedCallAttemptOutcome.OperatorDiscarded,
lastError: "Discarded by operator",
httpStatus: null,
occurredAtUtc: DateTime.UtcNow,
durationMs: null);
}
} }
return success; return success;
} }
@@ -0,0 +1,137 @@
using Akka.TestKit.Xunit2;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Integration.Infrastructure;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Integration;
using ZB.MOM.WW.ScadaBridge.Commons.Types;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Entities;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Migrations;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Integration;
/// <summary>
/// SCA-1 end to end: <c>Parked</c> is re-openable. An operator Retry of a parked cached call
/// re-opens the site tracking row and the central <c>SiteCalls</c> row, so the retried delivery's
/// outcome lands on both; an operator Discard closes both as <c>Discarded</c>. Before the fix both
/// stayed <c>Parked</c> forever (site: later writes were no-ops on a terminal row; central: equal
/// terminal rank was immutable).
/// </summary>
public class ParkedReopenCombinedTelemetryTests : TestKit, IClassFixture<MsSqlMigrationFixture>
{
private readonly MsSqlMigrationFixture _fixture;
/// <summary>Initializes the test with the shared SQL Server migration fixture.</summary>
/// <param name="fixture">The shared MS SQL migration fixture.</param>
public ParkedReopenCombinedTelemetryTests(MsSqlMigrationFixture fixture) => _fixture = fixture;
private static string NewSiteId() => "test-sca1-" + Guid.NewGuid().ToString("N")[..8];
private static CachedCallTelemetry SubmitPacket(TrackedOperationId id, string siteId, DateTime nowUtc) =>
new(
Audit: ScadaBridgeAuditEventFactory.Create(
eventId: Guid.NewGuid(),
occurredAtUtc: nowUtc,
channel: AuditChannel.ApiOutbound,
kind: AuditKind.CachedSubmit,
correlationId: id.Value,
sourceSiteId: siteId,
target: "ERP.GetOrder",
status: AuditStatus.Submitted),
Operational: new SiteCallOperational(
id, "ApiOutbound", "ERP.GetOrder", siteId, null, "Submitted", 0, null, null,
nowUtc, nowUtc, null));
private static CachedCallAttemptContext Ctx(
TrackedOperationId id, string siteId, CachedCallAttemptOutcome outcome, int retryCount,
string? lastError, DateTime createdUtc, DateTime occurredUtc) =>
new(id, "ApiOutbound", "ERP.GetOrder", siteId, outcome, retryCount, lastError, null,
createdUtc, occurredUtc, null, "Plant.Pump42");
private static async Task ParkAsync(CombinedTelemetryHarness harness, TrackedOperationId id, string siteId, DateTime t0)
{
await harness.EmitSubmitAsync(SubmitPacket(id, siteId, t0));
await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.ParkedMaxRetries, 3, "HTTP 500", t0, t0.AddSeconds(30)));
Assert.Equal("Parked", (await harness.TrackingStore.GetStatusAsync(id))!.Status);
}
/// <summary>Retry of a parked call, then a successful delivery: site and central both end Delivered.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task ParkedThenOperatorRetryThenDelivered_SiteAndCentral_EndDelivered()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var siteId = NewSiteId();
var id = TrackedOperationId.New();
var t0 = new DateTime(2026, 12, 1, 9, 0, 0, DateTimeKind.Utc);
await using var harness = new CombinedTelemetryHarness(_fixture, this);
await ParkAsync(harness, id, siteId, t0);
await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.OperatorRetried, 0, null, t0, t0.AddMinutes(5)));
await harness.TrackingStore.FlushAsync();
var reopened = await harness.TrackingStore.GetStatusAsync(id);
Assert.Equal("Attempted", reopened!.Status);
Assert.Null(reopened.TerminalAtUtc);
await using (var read = harness.CreateReadContext())
{
var row = await read.Set<SiteCall>().SingleAsync(s => s.TrackedOperationId == id);
Assert.Equal("Attempted", row.Status);
Assert.Null(row.TerminalAtUtc);
}
await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.Delivered, 1, null, t0, t0.AddMinutes(6)));
var delivered = await harness.TrackingStore.GetStatusAsync(id);
Assert.Equal("Delivered", delivered!.Status);
Assert.NotNull(delivered.TerminalAtUtc);
await using (var read = harness.CreateReadContext())
{
var row = await read.Set<SiteCall>().SingleAsync(s => s.TrackedOperationId == id);
Assert.Equal("Delivered", row.Status);
Assert.NotNull(row.TerminalAtUtc);
// The re-queue is recorded as a second CachedSubmit (Submitted) row.
var submits = await read.Set<AuditLogRow>()
.Where(e => e.SourceSiteId == siteId && e.Kind == AuditKind.CachedSubmit)
.CountAsync();
Assert.Equal(2, submits);
}
}
/// <summary>Discard of a parked call: site and central both end Discarded.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task ParkedThenOperatorDiscard_SiteAndCentral_EndDiscarded()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var siteId = NewSiteId();
var id = TrackedOperationId.New();
var t0 = new DateTime(2026, 12, 1, 10, 0, 0, DateTimeKind.Utc);
await using var harness = new CombinedTelemetryHarness(_fixture, this);
await ParkAsync(harness, id, siteId, t0);
await harness.EmitAttemptAsync(Ctx(id, siteId, CachedCallAttemptOutcome.OperatorDiscarded, 3, "Discarded by operator", t0, t0.AddMinutes(5)));
var site = await harness.TrackingStore.GetStatusAsync(id);
Assert.Equal("Discarded", site!.Status);
Assert.NotNull(site.TerminalAtUtc);
await using var read = harness.CreateReadContext();
var row = await read.Set<SiteCall>().SingleAsync(s => s.TrackedOperationId == id);
Assert.Equal("Discarded", row.Status);
var resolves = await read.Set<AuditLogRow>()
.Where(e => e.SourceSiteId == siteId && e.Kind == AuditKind.CachedResolve)
.Select(e => e.Status)
.ToListAsync();
Assert.Contains(AuditStatus.Discarded, resolves);
}
}
@@ -372,33 +372,111 @@ public class SiteCallAuditRepositoryTests : IClassFixture<MsSqlMigrationFixture>
Assert.Equal(0, row.RetryCount); Assert.Equal(0, row.RetryCount);
} }
/// <summary>Verifies that one terminal status cannot overwrite another terminal status.</summary> /// <summary>
/// Verifies that one terminal status cannot overwrite another terminal status — except
/// <c>Parked</c>, which is re-openable (SCA-1; see the Parked tests below).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns> /// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact] [SkippableFact]
public async Task UpsertAsync_TerminalOverTerminal_IsNoOp() public async Task UpsertAsync_TerminalOverTerminal_IsNoOp()
{ {
Skip.IfNot(_fixture.Available, _fixture.SkipReason); Skip.IfNot(_fixture.Available, _fixture.SkipReason);
// Terminal statuses share rank 3 and are mutually // Delivered/Failed/Discarded share rank 3 and are mutually exclusive: a later
// exclusive — Delivered cannot overwrite Parked. Note that the // Failed (STRICTLY-NEWER UpdatedAtUtc) cannot overwrite Delivered. The same-rank
// Delivered packet carries a STRICTLY-NEWER UpdatedAtUtc, yet the row // freshness tiebreaker is scoped to NON-terminal ranks (< 3).
// stays Parked — the same-rank freshness tiebreaker is scoped to var id = TrackedOperationId.New();
// NON-terminal ranks (< 3), so terminal immutability is preserved. var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc);
await using var context = CreateContext();
var repo = new SiteCallAuditRepository(context);
await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 3, lastError: null, updatedAtUtc: t0, terminal: true, terminalAtUtc: t0));
var afterDelivered = await repo.GetAsync(id);
await repo.UpsertAsync(NewRow(id, status: "Failed", retryCount: 4, lastError: "late", updatedAtUtc: t0.AddMinutes(5), terminal: true, terminalAtUtc: t0.AddMinutes(5)));
await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 4, lastError: "late", updatedAtUtc: t0.AddMinutes(6), terminal: true, terminalAtUtc: t0.AddMinutes(6)));
var after = await repo.GetAsync(id);
Assert.NotNull(after);
Assert.Equal("Delivered", after!.Status);
Assert.Equal(afterDelivered!.UpdatedAtUtc, after.UpdatedAtUtc);
}
/// <summary>
/// SCA-1 regression: an operator Retry of a Parked call re-opens it at the site, so a
/// NEWER Attempted and then Delivered must replace the Parked row (it used to stay Parked
/// until the 365-day purge).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task UpsertAsync_ParkedThenNewerAttemptedThenDelivered_Reopens()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var id = TrackedOperationId.New(); var id = TrackedOperationId.New();
var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc); var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc);
await using var context = CreateContext(); await using var context = CreateContext();
var repo = new SiteCallAuditRepository(context); var repo = new SiteCallAuditRepository(context);
await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0)); await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0));
var afterPark = await repo.GetAsync(id);
await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 4, lastError: null, updatedAtUtc: t0.AddMinutes(5), terminal: true, terminalAtUtc: t0.AddMinutes(5))); await repo.UpsertAsync(NewRow(id, status: "Attempted", retryCount: 0, lastError: null, updatedAtUtc: t0.AddMinutes(5)));
var afterDeliveredAttempt = await repo.GetAsync(id); var reopened = await repo.GetAsync(id);
Assert.Equal("Attempted", reopened!.Status);
Assert.Null(reopened.TerminalAtUtc);
Assert.Null(reopened.LastError);
Assert.NotNull(afterDeliveredAttempt); await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 1, lastError: null, updatedAtUtc: t0.AddMinutes(6), terminal: true, terminalAtUtc: t0.AddMinutes(6)));
Assert.Equal("Parked", afterDeliveredAttempt!.Status); // Fresh context: the first GetAsync left the row tracked, and a raw-SQL upsert does
Assert.Equal("parked-reason", afterDeliveredAttempt.LastError); // not refresh a tracked entity.
Assert.Equal(afterPark!.UpdatedAtUtc, afterDeliveredAttempt.UpdatedAtUtc); await using var readContext = CreateContext();
var delivered = await new SiteCallAuditRepository(readContext).GetAsync(id);
Assert.Equal("Delivered", delivered!.Status);
Assert.NotNull(delivered.TerminalAtUtc);
}
/// <summary>SCA-1: an operator Discard of a Parked call (newer) closes it as Discarded.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task UpsertAsync_ParkedThenNewerDiscarded_IsDiscarded()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var id = TrackedOperationId.New();
var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc);
await using var context = CreateContext();
var repo = new SiteCallAuditRepository(context);
await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0));
await repo.UpsertAsync(NewRow(id, status: "Discarded", retryCount: 3, lastError: "Discarded by operator", updatedAtUtc: t0.AddMinutes(5), terminal: true, terminalAtUtc: t0.AddMinutes(5)));
var row = await repo.GetAsync(id);
Assert.Equal("Discarded", row!.Status);
}
/// <summary>
/// SCA-1: Parked is re-opened only by a STRICTLY NEWER Attempted/Delivered/Failed/Discarded — a
/// stale pre-park packet replayed late, or a newer Submitted/Forwarded, leaves it Parked.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[SkippableFact]
public async Task UpsertAsync_Parked_StaleOrLowRankPacket_StaysParked()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var id = TrackedOperationId.New();
var t0 = new DateTime(2026, 6, 1, 13, 0, 0, DateTimeKind.Utc);
await using var context = CreateContext();
var repo = new SiteCallAuditRepository(context);
await repo.UpsertAsync(NewRow(id, status: "Parked", retryCount: 3, lastError: "parked-reason", updatedAtUtc: t0, terminal: true, terminalAtUtc: t0));
await repo.UpsertAsync(NewRow(id, status: "Attempted", retryCount: 2, lastError: "old", updatedAtUtc: t0.AddMinutes(-5)));
await repo.UpsertAsync(NewRow(id, status: "Delivered", retryCount: 2, updatedAtUtc: t0, terminal: true, terminalAtUtc: t0));
await repo.UpsertAsync(NewRow(id, status: "Submitted", retryCount: 0, updatedAtUtc: t0.AddMinutes(5)));
var row = await repo.GetAsync(id);
Assert.Equal("Parked", row!.Status);
Assert.Equal("parked-reason", row.LastError);
} }
/// <summary>Verifies that concurrent inserts of the same id leave only one row.</summary> /// <summary>Verifies that concurrent inserts of the same id leave only one row.</summary>
@@ -389,6 +389,81 @@ public class OperationTrackingStoreTests : IDisposable
Assert.True(snapshot.UpdatedAtUtc >= snapshot.CreatedAtUtc); Assert.True(snapshot.UpdatedAtUtc >= snapshot.CreatedAtUtc);
} }
/// <summary>
/// SCA-1: a Parked row re-opens on an operator Retry — TerminalAtUtc cleared, RetryCount and
/// error reset — so the retried attempts and outcome land on it again.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReopenParkedAsync_ReopensParkedRow_SoTheRetriedOutcomeLands()
{
var (store, _) = CreateStore(nameof(ReopenParkedAsync_ReopensParkedRow_SoTheRetriedOutcomeLands));
await using var _store = store;
var id = TrackedOperationId.New();
await store.RecordEnqueueAsync(id, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null);
await store.RecordAttemptAsync(id, nameof(AuditStatus.Attempted), 3, "HTTP 500", 500);
await store.RecordTerminalAsync(id, nameof(AuditStatus.Parked), "HTTP 500", 500);
var parked = await store.GetStatusAsync(id);
await store.ReopenParkedAsync(id);
var reopened = await store.GetStatusAsync(id);
Assert.Equal(nameof(AuditStatus.Attempted), reopened!.Status);
Assert.Null(reopened.TerminalAtUtc);
Assert.Equal(0, reopened.RetryCount);
Assert.Null(reopened.LastError);
Assert.True(reopened.UpdatedAtUtc >= parked!.UpdatedAtUtc);
await store.RecordAttemptAsync(id, nameof(AuditStatus.Attempted), 1, null, 200);
await store.RecordTerminalAsync(id, nameof(AuditStatus.Delivered), null, 200);
var delivered = await store.GetStatusAsync(id);
Assert.Equal(nameof(AuditStatus.Delivered), delivered!.Status);
Assert.NotNull(delivered.TerminalAtUtc);
}
/// <summary>SCA-1: re-open touches only a Parked row — a Delivered row stays Delivered.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReopenParkedAsync_OnNonParkedTerminalRow_IsNoOp()
{
var (store, _) = CreateStore(nameof(ReopenParkedAsync_OnNonParkedTerminalRow_IsNoOp));
await using var _store = store;
var id = TrackedOperationId.New();
await store.RecordEnqueueAsync(id, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null);
await store.RecordTerminalAsync(id, nameof(AuditStatus.Delivered), null, 200);
await store.ReopenParkedAsync(id);
var row = await store.GetStatusAsync(id);
Assert.Equal(nameof(AuditStatus.Delivered), row!.Status);
Assert.NotNull(row.TerminalAtUtc);
}
/// <summary>SCA-1: an operator Discard closes a Parked row as Discarded; Delivered stays immutable.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RecordDiscardedAsync_ClosesParkedRow_ButNotADeliveredOne()
{
var (store, _) = CreateStore(nameof(RecordDiscardedAsync_ClosesParkedRow_ButNotADeliveredOne));
await using var _store = store;
var parkedId = TrackedOperationId.New();
await store.RecordEnqueueAsync(parkedId, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null);
await store.RecordTerminalAsync(parkedId, nameof(AuditStatus.Parked), "HTTP 500", 500);
await store.RecordDiscardedAsync(parkedId, "Discarded by operator");
var discarded = await store.GetStatusAsync(parkedId);
Assert.Equal(nameof(AuditStatus.Discarded), discarded!.Status);
Assert.NotNull(discarded.TerminalAtUtc);
Assert.Equal("Discarded by operator", discarded.LastError);
var deliveredId = TrackedOperationId.New();
await store.RecordEnqueueAsync(deliveredId, "ApiCallCached", "ERP.GetOrder", null, null, sourceNode: null);
await store.RecordTerminalAsync(deliveredId, nameof(AuditStatus.Delivered), null, 200);
await store.RecordDiscardedAsync(deliveredId, "Discarded by operator");
Assert.Equal(nameof(AuditStatus.Delivered), (await store.GetStatusAsync(deliveredId))!.Status);
}
/// <summary>Verifies that recording an attempt on a terminal row is a no-op.</summary> /// <summary>Verifies that recording an attempt on a terminal row is a no-op.</summary>
/// <returns>A task that represents the asynchronous operation.</returns> /// <returns>A task that represents the asynchronous operation.</returns>
[Fact] [Fact]
@@ -113,6 +113,63 @@ public class CachedCallAttemptEmissionTests : IAsyncLifetime, IDisposable
return trackedId; return trackedId;
} }
// ── SCA-1: operator transitions out of Parked ──
private async Task<TrackedOperationId> ParkAsync()
{
_service.RegisterDeliveryHandler(StoreAndForwardCategory.ExternalSystem, _ => Task.FromResult(false));
var id = await EnqueueBufferedAsync(StoreAndForwardCategory.ExternalSystem, "ERP", maxRetries: 5);
await _service.RetryPendingMessagesAsync();
Assert.Equal(CachedCallAttemptOutcome.PermanentFailure, Assert.Single(_observer.Notifications).Outcome);
_observer.Notifications.Clear();
return id;
}
/// <summary>
/// SCA-1 regression: an operator Retry of a parked cached call notifies the observer with
/// <see cref="CachedCallAttemptOutcome.OperatorRetried"/>, so the tracking row re-opens and
/// telemetry carries the change to central (it used to raise an activity only).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OperatorRetryOfParkedCall_NotifiesOperatorRetried()
{
var id = await ParkAsync();
Assert.True(await _service.RetryParkedMessageAsync(id.ToString()));
var n = Assert.Single(_observer.Notifications);
Assert.Equal(id, n.TrackedOperationId);
Assert.Equal(CachedCallAttemptOutcome.OperatorRetried, n.Outcome);
Assert.Equal(0, n.RetryCount);
Assert.Null(n.LastError);
}
/// <summary>SCA-1 regression: an operator Discard notifies <see cref="CachedCallAttemptOutcome.OperatorDiscarded"/>.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OperatorDiscardOfParkedCall_NotifiesOperatorDiscarded()
{
var id = await ParkAsync();
Assert.True(await _service.DiscardParkedMessageAsync(id.ToString()));
var n = Assert.Single(_observer.Notifications);
Assert.Equal(id, n.TrackedOperationId);
Assert.Equal(CachedCallAttemptOutcome.OperatorDiscarded, n.Outcome);
}
/// <summary>A retry/discard of a message that is not parked notifies nothing.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OperatorRetryOfNonParkedCall_NotifiesNothing()
{
var id = await EnqueueBufferedAsync(StoreAndForwardCategory.ExternalSystem, "ERP", maxRetries: 5);
Assert.False(await _service.RetryParkedMessageAsync(id.ToString()));
Assert.Empty(_observer.Notifications);
}
// ── Per-attempt observer notifications ── // ── Per-attempt observer notifications ──
/// <summary>Verifies that a failed attempt with an HTTP 500 emits attempted telemetry.</summary> /// <summary>Verifies that a failed attempt with an HTTP 500 emits attempted telemetry.</summary>