feat(auditlog): NotifyDeliver rows carry the originating ParentExecutionId

This commit is contained in:
Joseph Doherty
2026-05-21 18:11:04 -04:00
parent c00603e2a4
commit d35551efc2
16 changed files with 2056 additions and 9 deletions

View File

@@ -36,6 +36,15 @@ public class Notification
/// submitted before the column existed, or raised outside a script-execution context.
/// </summary>
public Guid? OriginExecutionId { get; set; }
/// <summary>
/// The originating routed script execution's <c>ParentExecutionId</c> (Audit Log #23).
/// Carried from the site on the <see cref="Commons.Messages.Notification.NotificationSubmit"/>
/// so the central dispatcher can stamp the same parent id onto its <c>NotifyDeliver</c>
/// audit rows, correlating them with the site-emitted <c>NotifySend</c> row. Null for
/// non-routed runs, or for notifications submitted before the column existed.
/// </summary>
public Guid? OriginParentExecutionId { get; set; }
public DateTimeOffset SiteEnqueuedAt { get; set; }
/// <summary>Central ingest time.</summary>

View File

@@ -11,6 +11,13 @@ namespace ScadaLink.Commons.Messages.Notification;
/// <c>NotifyDeliver</c> audit rows. Additive trailing member — null for messages built
/// before the field existed, or for notifications raised outside a script execution.
/// </param>
/// <param name="OriginParentExecutionId">
/// The originating routed script execution's <c>ParentExecutionId</c> (Audit Log #23).
/// Stamped at <c>Notify.Send</c> time and carried, inside the serialized payload, through
/// the site store-and-forward buffer so the central dispatcher can echo it onto the
/// <c>NotifyDeliver</c> audit rows. Additive trailing member — null for messages built
/// before the field existed, or for non-routed runs.
/// </param>
public record NotificationSubmit(
string NotificationId,
string ListName,
@@ -20,7 +27,8 @@ public record NotificationSubmit(
string? SourceInstanceId,
string? SourceScript,
DateTimeOffset SiteEnqueuedAt,
Guid? OriginExecutionId = null);
Guid? OriginExecutionId = null,
Guid? OriginParentExecutionId = null);
/// <summary>
/// Central -> Site: ack sent after the notification row is persisted.

View File

@@ -51,6 +51,10 @@ public class NotificationOutboxConfiguration : IEntityTypeConfiguration<Notifica
// site so the dispatcher can echo it onto NotifyDeliver audit rows. No index —
// it is never a query predicate on this table, only copied onto audit events.
// OriginParentExecutionId (Audit Log #23): nullable uniqueidentifier carried from
// the site — the routed run's parent ExecutionId — so the dispatcher can echo it
// onto NotifyDeliver audit rows. No index — same rationale as OriginExecutionId.
builder.HasIndex(n => new { n.Status, n.NextAttemptAt });
builder.HasIndex(n => new { n.SourceSiteId, n.CreatedAt });

View File

@@ -0,0 +1,42 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ScadaLink.ConfigurationDatabase.Migrations
{
/// <summary>
/// Adds the <c>OriginParentExecutionId</c> correlation column to the central
/// <c>Notifications</c> table (#21). It carries the originating routed script
/// execution's <c>ParentExecutionId</c> from the site so the dispatcher can echo it
/// onto the <c>NotifyDeliver</c> audit rows (#23), linking them to the routed run's
/// parent. Sibling of <c>OriginExecutionId</c>.
///
/// The change is purely additive: <c>OriginParentExecutionId uniqueidentifier NULL</c>
/// is added with no default, so the operation is a metadata-only
/// <c>ALTER TABLE … ADD</c>. Unlike <c>AuditLog</c>, the <c>Notifications</c> table is
/// NOT partitioned, so a plain <c>ADD</c> is fine. No index is created — the column is
/// never a query predicate, only copied onto audit events. Historical rows stay
/// <c>NULL</c>.
/// </summary>
public partial class AddNotificationOriginParentExecutionId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "OriginParentExecutionId",
table: "Notifications",
type: "uniqueidentifier",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "OriginParentExecutionId",
table: "Notifications");
}
}
}

View File

@@ -797,6 +797,9 @@ namespace ScadaLink.ConfigurationDatabase.Migrations
b.Property<Guid?>("OriginExecutionId")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("OriginParentExecutionId")
.HasColumnType("uniqueidentifier");
b.Property<string>("ResolvedTargets")
.HasColumnType("nvarchar(max)");

View File

@@ -492,7 +492,8 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
/// <see cref="AuditEvent.ExecutionId"/> is copied straight from
/// <see cref="Notification.OriginExecutionId"/> so the dispatcher's
/// <c>NotifyDeliver</c> rows carry the same per-run id as the site's
/// <c>NotifySend</c> row (Audit Log #23).
/// <c>NotifySend</c> row (Audit Log #23); <see cref="AuditEvent.ParentExecutionId"/>
/// is likewise copied from <see cref="Notification.OriginParentExecutionId"/>.
/// </summary>
private static AuditEvent BuildNotifyDeliverEvent(
Notification notification,
@@ -525,6 +526,11 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
// rows to the site-emitted NotifySend row for the same run. Null when
// the notification was raised outside a script execution.
ExecutionId = notification.OriginExecutionId,
// ParentExecutionId (Audit Log #23): the originating routed run's
// parent ExecutionId, carried from the site on NotificationSubmit and
// persisted on the Notification row. Echoing it here links the central
// NotifyDeliver rows to the routed run's parent. Null for non-routed runs.
ParentExecutionId = notification.OriginParentExecutionId,
Target = notification.ListName,
Status = status,
ErrorMessage = errorMessage,
@@ -954,6 +960,10 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
// OriginExecutionId (Audit Log #23): the originating script execution's id,
// carried from the site so the dispatcher can echo it onto NotifyDeliver rows.
OriginExecutionId = msg.OriginExecutionId,
// OriginParentExecutionId (Audit Log #23): the originating routed run's parent
// ExecutionId, carried from the site so the dispatcher can echo it onto
// NotifyDeliver rows.
OriginParentExecutionId = msg.OriginParentExecutionId,
SiteEnqueuedAt = msg.SiteEnqueuedAt,
CreatedAt = DateTimeOffset.UtcNow,
// Status stays at its Pending default for the dispatch sweep to claim.

View File

@@ -1521,7 +1521,13 @@ public class ScriptRuntimeContext
// onto this run's NotifySend audit row. It rides inside the serialized
// payload through the S&F buffer to central, where the dispatcher echoes
// it onto the NotifyDeliver rows so all rows for one run share an id.
OriginExecutionId: _executionId);
OriginExecutionId: _executionId,
// OriginParentExecutionId (Audit Log #23): the SAME parent-execution id
// stamped onto this run's NotifySend audit row — the spawning run's id
// for an inbound-API-routed execution, null otherwise. It rides through
// the S&F buffer to central, where the dispatcher echoes it onto the
// NotifyDeliver rows so the central rows carry the routed run's parent id.
OriginParentExecutionId: _parentExecutionId);
var payloadJson = JsonSerializer.Serialize(payload);

View File

@@ -36,6 +36,21 @@ public class NotificationEntityTests
Assert.Equal(executionId, n.OriginExecutionId);
}
[Fact]
public void OriginParentExecutionId_DefaultsToNull_AndIsSettable()
{
// Audit Log ParentExecutionId: OriginParentExecutionId carries the
// routed run's parent ExecutionId from the site so the dispatcher can
// echo it onto NotifyDeliver rows. Null for non-routed runs, or for
// notifications submitted before the column existed.
var n = new Notification("id-1", NotificationType.Email, "ops-team", "subj", "body", "SiteA");
Assert.Null(n.OriginParentExecutionId);
var parentExecutionId = Guid.NewGuid();
n.OriginParentExecutionId = parentExecutionId;
Assert.Equal(parentExecutionId, n.OriginParentExecutionId);
}
[Fact]
public void Constructor_NullArguments_Throw()
{

View File

@@ -81,6 +81,51 @@ public class NotificationMessagesTests
Assert.Equal(executionId, roundTripped!.OriginExecutionId);
}
[Fact]
public void NotificationSubmit_OriginParentExecutionId_DefaultsToNull()
{
// Audit Log ParentExecutionId: OriginParentExecutionId is an additive
// trailing member — a submit built without it (old call sites / old
// serialized payloads, or non-routed runs) leaves the id null.
var msg = new NotificationSubmit(
"notif-6", "Operators", "Subject", "Body",
"site-01", "inst-1", "OnAlarm", DateTimeOffset.UtcNow);
Assert.Null(msg.OriginParentExecutionId);
}
[Fact]
public void NotificationSubmit_OriginParentExecutionId_RoundTripsWhenSupplied()
{
var executionId = Guid.NewGuid();
var parentExecutionId = Guid.NewGuid();
var msg = new NotificationSubmit(
"notif-7", "Operators", "Subject", "Body",
"site-01", "inst-1", "OnAlarm", DateTimeOffset.UtcNow,
executionId, parentExecutionId);
Assert.Equal(parentExecutionId, msg.OriginParentExecutionId);
}
[Fact]
public void NotificationSubmit_OriginParentExecutionId_SurvivesJsonRoundTrip()
{
// The buffered S&F payload IS a serialized NotificationSubmit; the
// forwarder deserializes it, so OriginParentExecutionId must survive JSON.
var executionId = Guid.NewGuid();
var parentExecutionId = Guid.NewGuid();
var msg = new NotificationSubmit(
"notif-8", "Operators", "Subject", "Body",
"site-01", "inst-1", "OnAlarm", DateTimeOffset.UtcNow,
executionId, parentExecutionId);
var json = System.Text.Json.JsonSerializer.Serialize(msg);
var roundTripped = System.Text.Json.JsonSerializer.Deserialize<NotificationSubmit>(json);
Assert.NotNull(roundTripped);
Assert.Equal(parentExecutionId, roundTripped!.OriginParentExecutionId);
}
[Fact]
public void NotificationSubmit_ValueEquality_EqualWhenAllFieldsMatch()
{

View File

@@ -0,0 +1,71 @@
using Xunit;
namespace ScadaLink.ConfigurationDatabase.Tests.Migrations;
/// <summary>
/// Audit Log ParentExecutionId integration test for the
/// <c>AddNotificationOriginParentExecutionId</c> migration: applies the EF
/// migrations to a freshly-created MSSQL test database on the running
/// infra/mssql container and asserts that the <c>Notifications</c> table carries
/// the new <c>OriginParentExecutionId</c> column as a nullable
/// <c>uniqueidentifier</c>.
/// </summary>
/// <remarks>
/// Unlike <c>AuditLog</c>, the <c>Notifications</c> table is not partitioned, so
/// the column is a plain metadata-only <c>ALTER TABLE … ADD</c> with no index.
/// Tests pair <see cref="SkippableFactAttribute"/> with <c>Skip.IfNot(...)</c> so
/// the runner reports them as Skipped (not Passed) when MSSQL is unreachable. The
/// fixture applies the migrations once at construction time.
/// </remarks>
public class AddNotificationOriginParentExecutionIdMigrationTests : IClassFixture<MsSqlMigrationFixture>
{
private readonly MsSqlMigrationFixture _fixture;
public AddNotificationOriginParentExecutionIdMigrationTests(MsSqlMigrationFixture fixture)
{
_fixture = fixture;
}
[SkippableFact]
public async Task AppliesMigration_AddsOriginParentExecutionIdColumn_ToNotifications()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var present = await ScalarAsync<int>(
"SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = 'Notifications' AND COLUMN_NAME = 'OriginParentExecutionId' " +
"AND TABLE_SCHEMA = 'dbo';");
Assert.Equal(1, present);
}
[SkippableFact]
public async Task OriginParentExecutionIdColumn_IsNullableUniqueIdentifier()
{
Skip.IfNot(_fixture.Available, _fixture.SkipReason);
var dataType = await ScalarAsync<string?>(
"SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = 'Notifications' AND COLUMN_NAME = 'OriginParentExecutionId';");
Assert.Equal("uniqueidentifier", dataType);
var isNullable = await ScalarAsync<string?>(
"SELECT IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = 'Notifications' AND COLUMN_NAME = 'OriginParentExecutionId';");
Assert.Equal("YES", isNullable);
}
// --- helpers ------------------------------------------------------------
private async Task<T> ScalarAsync<T>(string sql)
{
await using var conn = _fixture.OpenConnection();
await using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
var result = await cmd.ExecuteScalarAsync();
if (result is null || result is DBNull)
{
return default!;
}
return (T)Convert.ChangeType(result, typeof(T) == typeof(string) ? typeof(string) : Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T))!;
}
}

View File

@@ -269,6 +269,7 @@ public class NotificationOutboxConfigurationTests : IDisposable
var nextAttemptAt = new DateTimeOffset(2026, 5, 19, 8, 2, 0, TimeSpan.Zero);
var deliveredAt = new DateTimeOffset(2026, 5, 19, 8, 3, 0, TimeSpan.Zero);
var originExecutionId = Guid.NewGuid();
var originParentExecutionId = Guid.NewGuid();
var notification = new Notification(id, NotificationType.Email, "Ops List",
"High Tank Level", "Tank 4 exceeded the high level threshold.", "site-north")
@@ -281,6 +282,7 @@ public class NotificationOutboxConfigurationTests : IDisposable
SourceInstanceId = "instance-42",
SourceScript = "TankLevelAlarm",
OriginExecutionId = originExecutionId,
OriginParentExecutionId = originParentExecutionId,
SiteEnqueuedAt = siteEnqueuedAt,
CreatedAt = createdAt,
LastAttemptAt = lastAttemptAt,
@@ -314,6 +316,7 @@ public class NotificationOutboxConfigurationTests : IDisposable
Assert.Equal(nextAttemptAt, loaded.NextAttemptAt);
Assert.Equal(deliveredAt, loaded.DeliveredAt);
Assert.Equal(originExecutionId, loaded.OriginExecutionId);
Assert.Equal(originParentExecutionId, loaded.OriginParentExecutionId);
}
[Fact]
@@ -336,6 +339,26 @@ public class NotificationOutboxConfigurationTests : IDisposable
Assert.Null(loaded!.OriginExecutionId);
}
[Fact]
public async Task Notification_NullOriginParentExecutionId_RoundTripsAsNull()
{
// Audit Log ParentExecutionId: OriginParentExecutionId is an additive
// nullable column — notifications from non-routed runs (or submitted
// before the column existed) persist and reload it as null.
var id = Guid.NewGuid().ToString();
var notification = new Notification(id, NotificationType.Email, "Ops List",
"Subject", "Body", "site-north");
_context.Notifications.Add(notification);
await _context.SaveChangesAsync();
_context.ChangeTracker.Clear();
var loaded = await _context.Notifications.FindAsync(id);
Assert.NotNull(loaded);
Assert.Null(loaded!.OriginParentExecutionId);
}
[Fact]
public async Task Notification_StatusPersistsAsString()
{

View File

@@ -95,7 +95,8 @@ public class NotificationOutboxActorAttemptEmissionTests : TestKit
Guid? notificationId = null,
string sourceSite = "site-1",
int retryCount = 0,
Guid? originExecutionId = null)
Guid? originExecutionId = null,
Guid? originParentExecutionId = null)
{
return new Notification(
(notificationId ?? Guid.NewGuid()).ToString("D"),
@@ -110,6 +111,7 @@ public class NotificationOutboxActorAttemptEmissionTests : TestKit
SourceInstanceId = "instance-42",
SourceScript = "AlarmScript",
OriginExecutionId = originExecutionId,
OriginParentExecutionId = originParentExecutionId,
};
}
@@ -207,6 +209,50 @@ public class NotificationOutboxActorAttemptEmissionTests : TestKit
});
}
[Fact]
public void Attempt_CarriesOriginParentExecutionId_AsParentExecutionId()
{
// Audit Log ParentExecutionId: the Attempted NotifyDeliver row must echo
// the notification's OriginParentExecutionId so the central dispatcher's
// rows carry the routed run's parent id.
SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
var parentExecutionId = Guid.NewGuid();
var notification = MakeNotification(originParentExecutionId: parentExecutionId);
_outboxRepository.GetDueAsync(Arg.Any<DateTimeOffset>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(new[] { notification });
var adapter = new StubAdapter(() => DeliveryOutcome.Success("ops@example.com"));
var actor = CreateActor([adapter]);
actor.Tell(InternalMessages.DispatchTick.Instance);
AwaitAssert(() =>
{
var attempted = EventsByStatus(AuditStatus.Attempted);
Assert.Single(attempted);
Assert.Equal(parentExecutionId, attempted[0].ParentExecutionId);
});
}
[Fact]
public void Attempt_NullOriginParentExecutionId_HasNullParentExecutionId()
{
SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
var notification = MakeNotification(originParentExecutionId: null);
_outboxRepository.GetDueAsync(Arg.Any<DateTimeOffset>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(new[] { notification });
var adapter = new StubAdapter(() => DeliveryOutcome.Success("ops@example.com"));
var actor = CreateActor([adapter]);
actor.Tell(InternalMessages.DispatchTick.Instance);
AwaitAssert(() =>
{
var attempted = EventsByStatus(AuditStatus.Attempted);
Assert.Single(attempted);
Assert.Null(attempted[0].ParentExecutionId);
});
}
[Fact]
public void Attempt_TransientFailure_EmitsEvent_StatusAttempted_ErrorMessageSet()
{

View File

@@ -40,7 +40,9 @@ public class NotificationOutboxActorIngestTests : TestKit
}
private static NotificationSubmit MakeSubmit(
string? notificationId = null, Guid? originExecutionId = null)
string? notificationId = null,
Guid? originExecutionId = null,
Guid? originParentExecutionId = null)
{
return new NotificationSubmit(
NotificationId: notificationId ?? Guid.NewGuid().ToString(),
@@ -51,7 +53,8 @@ public class NotificationOutboxActorIngestTests : TestKit
SourceInstanceId: "instance-42",
SourceScript: "AlarmScript",
SiteEnqueuedAt: new DateTimeOffset(2026, 5, 19, 8, 30, 0, TimeSpan.Zero),
OriginExecutionId: originExecutionId);
OriginExecutionId: originExecutionId,
OriginParentExecutionId: originParentExecutionId);
}
[Fact]
@@ -121,6 +124,42 @@ public class NotificationOutboxActorIngestTests : TestKit
Arg.Any<CancellationToken>());
}
[Fact]
public void NotificationSubmit_CopiesOriginParentExecutionId_OntoPersistedNotification()
{
// Audit Log ParentExecutionId: the routed run's parent ExecutionId rides
// on the NotificationSubmit and must be persisted on the Notification row
// so the dispatcher can later echo it onto NotifyDeliver audit rows.
_repository.InsertIfNotExistsAsync(Arg.Any<Notification>(), Arg.Any<CancellationToken>())
.Returns(true);
var parentExecutionId = Guid.NewGuid();
var submit = MakeSubmit(originParentExecutionId: parentExecutionId);
var actor = CreateActor();
actor.Tell(submit, TestActor);
ExpectMsg<NotificationSubmitAck>();
_repository.Received(1).InsertIfNotExistsAsync(
Arg.Is<Notification>(n => n.OriginParentExecutionId == parentExecutionId),
Arg.Any<CancellationToken>());
}
[Fact]
public void NotificationSubmit_NullOriginParentExecutionId_PersistsNull()
{
_repository.InsertIfNotExistsAsync(Arg.Any<Notification>(), Arg.Any<CancellationToken>())
.Returns(true);
var submit = MakeSubmit(originParentExecutionId: null);
var actor = CreateActor();
actor.Tell(submit, TestActor);
ExpectMsg<NotificationSubmitAck>();
_repository.Received(1).InsertIfNotExistsAsync(
Arg.Is<Notification>(n => n.OriginParentExecutionId == null),
Arg.Any<CancellationToken>());
}
[Fact]
public void DuplicateSubmit_RepositoryReturnsFalse_StillAcksAccepted()
{

View File

@@ -88,7 +88,8 @@ public class NotificationOutboxActorTerminalEmissionTests : TestKit
NotificationStatus status = NotificationStatus.Pending,
int retryCount = 0,
Guid? notificationId = null,
Guid? originExecutionId = null)
Guid? originExecutionId = null,
Guid? originParentExecutionId = null)
{
return new Notification(
(notificationId ?? Guid.NewGuid()).ToString("D"),
@@ -102,6 +103,7 @@ public class NotificationOutboxActorTerminalEmissionTests : TestKit
RetryCount = retryCount,
CreatedAt = DateTimeOffset.UtcNow,
OriginExecutionId = originExecutionId,
OriginParentExecutionId = originParentExecutionId,
};
}
@@ -191,6 +193,50 @@ public class NotificationOutboxActorTerminalEmissionTests : TestKit
});
}
[Fact]
public void Terminal_Delivered_CarriesOriginParentExecutionId_AsParentExecutionId()
{
// Audit Log ParentExecutionId: the terminal NotifyDeliver row must echo
// the notification's OriginParentExecutionId so the central dispatcher's
// rows carry the routed run's parent id.
SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
var parentExecutionId = Guid.NewGuid();
var notification = MakeNotification(originParentExecutionId: parentExecutionId);
_outboxRepository.GetDueAsync(Arg.Any<DateTimeOffset>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(new[] { notification });
var adapter = new StubAdapter(() => DeliveryOutcome.Success("ops@example.com"));
var actor = CreateActor([adapter]);
actor.Tell(InternalMessages.DispatchTick.Instance);
AwaitAssert(() =>
{
var delivered = EventsByStatus(AuditStatus.Delivered);
Assert.Single(delivered);
Assert.Equal(parentExecutionId, delivered[0].ParentExecutionId);
});
}
[Fact]
public void Terminal_Delivered_NullOriginParentExecutionId_HasNullParentExecutionId()
{
SetupSmtpRetryPolicy(maxRetries: 5, retryDelay: TimeSpan.FromMinutes(1));
var notification = MakeNotification(originParentExecutionId: null);
_outboxRepository.GetDueAsync(Arg.Any<DateTimeOffset>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(new[] { notification });
var adapter = new StubAdapter(() => DeliveryOutcome.Success("ops@example.com"));
var actor = CreateActor([adapter]);
actor.Tell(InternalMessages.DispatchTick.Instance);
AwaitAssert(() =>
{
var delivered = EventsByStatus(AuditStatus.Delivered);
Assert.Single(delivered);
Assert.Null(delivered[0].ParentExecutionId);
});
}
[Fact]
public void Terminal_Parked_OnPermanentFailure_EmitsEvent_StatusParked()
{

View File

@@ -61,7 +61,8 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable
private ScriptRuntimeContext.NotifyHelper CreateHelper(
IActorRef siteCommunicationActor,
string? sourceScript = null,
Guid? executionId = null)
Guid? executionId = null,
Guid? parentExecutionId = null)
{
return new ScriptRuntimeContext.NotifyHelper(
_saf,
@@ -71,7 +72,9 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable
sourceScript,
TimeSpan.FromSeconds(3),
NullLogger.Instance,
executionId ?? Guid.NewGuid());
executionId ?? Guid.NewGuid(),
auditWriter: null,
parentExecutionId: parentExecutionId);
}
[Fact]
@@ -156,6 +159,44 @@ public class NotifyHelperTests : TestKit, IAsyncLifetime, IDisposable
Assert.Equal(executionId, payload!.OriginExecutionId);
}
[Fact]
public async Task Send_StampsParentExecutionId_OnTheNotificationSubmitPayload()
{
// Audit Log ParentExecutionId (Task 7): for an inbound-API-routed run,
// Notify.Send must stamp the routed run's parent ExecutionId onto the
// NotificationSubmit so it rides inside the serialized S&F payload to
// central, where the dispatcher echoes it onto the NotifyDeliver rows.
// This is the SAME parent id stamped onto the site-emitted NotifySend row.
var parentExecutionId = Guid.NewGuid();
var commProbe = CreateTestProbe();
var notify = CreateHelper(commProbe.Ref, parentExecutionId: parentExecutionId);
var notificationId = await notify.To("Operators").Send("Pump alarm", "Pump 3 tripped");
var buffered = await _saf.GetMessageByIdAsync(notificationId);
Assert.NotNull(buffered);
var payload = JsonSerializer.Deserialize<NotificationSubmit>(buffered!.PayloadJson);
Assert.NotNull(payload);
Assert.Equal(parentExecutionId, payload!.OriginParentExecutionId);
}
[Fact]
public async Task Send_NonRoutedRun_LeavesOriginParentExecutionIdNull()
{
// Non-routed runs have no parent execution — OriginParentExecutionId
// stays null on the NotificationSubmit payload.
var commProbe = CreateTestProbe();
var notify = CreateHelper(commProbe.Ref, parentExecutionId: null);
var notificationId = await notify.To("Operators").Send("Pump alarm", "Pump 3 tripped");
var buffered = await _saf.GetMessageByIdAsync(notificationId);
Assert.NotNull(buffered);
var payload = JsonSerializer.Deserialize<NotificationSubmit>(buffered!.PayloadJson);
Assert.NotNull(payload);
Assert.Null(payload!.OriginParentExecutionId);
}
[Fact]
public async Task Send_WhenHelperHasNoSourceScript_LeavesSourceScriptNull()
{