feat(localdb): move site_events to application-minted GUID ids

Tasks 2 + 5a-writer + 5b of the LocalDb Phase 1 plan, landed together because
they are one indivisible change: the schema, the writer that fills it, and every
consumer that assumed the old id semantics.

WHY the id changes. Site pairs will replicate site_events with last-writer-wins on
the primary key. With INTEGER PRIMARY KEY AUTOINCREMENT both nodes independently
mint 1, 2, 3... for unrelated events, so sync would treat them as the same row and
silently overwrite. A GUID makes the event log a pure union across the pair.

Task 2 - schema extracted so the Host's AddZbLocalDb onReady can create the tables
before RegisterReplicated installs capture triggers (pre-registration rows are
never captured):
  - new OperationTrackingSchema.Apply / SiteEventLogSchema.Apply, plain
    Microsoft.Data.Sqlite, no LocalDb dependency
  - both stores delegate their InitializeSchema to them (idempotent, so a
    directly-constructed store still works)
  - OperationTracking is unchanged - it already had a TEXT PK and replicates as-is

Task 5a - SiteEventLogger mints Guid.NewGuid("N") per event and inserts it.

Task 5b - three consumers assumed a monotonic integer id. All three move to
timestamp ordering; leaving any one behind would be a live bug:
  - EventLogQueryService: "id > $afterId" would return an ARBITRARY subset of a
    GUID-keyed table and SILENTLY DROP ROWS from page-through. Now a composite
    (timestamp, id) keyset cursor with an opaque string token; timestamps are not
    unique, so id is the tie-break that guarantees exactly-once paging.
  - EventLogPurgeService: "ORDER BY id ASC LIMIT 1000" would delete a RANDOM batch
    instead of the oldest. Now orders by timestamp.
  - EventLogEntry.Id and both ContinuationTokens: long -> string.

WIRE COMPATIBILITY. Those DTOs cross the site<->central Akka boundary
(SiteCommunicationActor -> CommunicationService -> ManagementActor / CentralUI).
No rolling-upgrade shim is needed because both sides ship in the same deployable
and the rig redeploys as a unit. Checked: no Akka serializer binding pins these
types by name. A stale numeric token degrades to "start from the beginning"
(a visible repeat) rather than throwing or losing rows.

Tests: the two that encoded the old semantics were rewritten to guard the new
invariant rather than deleted - uniqueness instead of monotonicity, and
oldest-purged-first keyed on timestamp. That second test also exposed a latent
weakness: the bulk seed stamped every row with the same UtcNow, so "oldest" was
never actually well-defined; rows now get distinct increasing timestamps, kept
inside the retention window so the retention purge does not eat them first.

Verified:
  dotnet build ZB.MOM.WW.ScadaBridge.slnx -> 0 Error(s), 0 Warning(s)
  SiteEventLogging.Tests -> 70 passed (12 new schema tests, red-first)
  CentralUI.Tests        -> 925 passed
  Commons.Tests          -> 684 passed
  SiteRuntime.Tests      -> 529 passed, 1 pre-existing flaky failure
                            (InstanceActorChildAttributeRaceTests - passes 3/3 in
                            isolation with and without this change)

Claude-Session: https://claude.ai/code/session_01BL2Vu1ESDQ9SCN4gVKkdts
This commit is contained in:
Joseph Doherty
2026-07-19 03:15:17 -04:00
parent f056b67e9a
commit 727fa48cba
14 changed files with 659 additions and 147 deletions
@@ -3,13 +3,19 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.RemoteQuery;
/// <summary>
/// Request to query site event logs from central.
/// Supports filtering by event type, severity, instance, time range, and keyword search.
/// Uses keyset pagination via continuation token (last event ID).
/// Uses keyset pagination via an opaque continuation token.
/// </summary>
/// <param name="InstanceId">
/// Instance filter matched against the site event log's <c>instance_id</c> column,
/// which stores the instance <b>UniqueName</b> (InstanceActor.LogLifecycleEvent passes
/// <c>_instanceUniqueName</c>; EventLogQueryService matches <c>instance_id = $instanceId</c>).
/// </param>
/// <param name="ContinuationToken">
/// Opaque cursor from the previous response's <c>ContinuationToken</c>, or
/// <see langword="null"/> to start from the oldest matching event. Treat as opaque —
/// it encodes timestamp and id together and its format is not part of the contract.
/// An unparseable token is treated as "start from the beginning" rather than an error.
/// </param>
public record EventLogQueryRequest(
string CorrelationId,
string SiteId,
@@ -19,6 +25,6 @@ public record EventLogQueryRequest(
string? Severity,
string? InstanceId,
string? KeywordFilter,
long? ContinuationToken,
string? ContinuationToken,
int PageSize,
DateTimeOffset Timestamp);
@@ -3,8 +3,18 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.RemoteQuery;
/// <summary>
/// A single event log entry returned from a site query.
/// </summary>
/// <param name="Id">
/// The event's primary key: a GUID string minted by the recording site node.
/// <para>
/// This was a <c>long</c> autoincrement id until LocalDb Phase 1. Site pairs now
/// replicate <c>site_events</c> with last-writer-wins on this key, so a
/// server-minted integer would have both nodes issuing the same ids for unrelated
/// events and silently overwriting each other on sync. Consumers must treat it as
/// an opaque identifier — it carries no ordering.
/// </para>
/// </param>
public record EventLogEntry(
long Id,
string Id,
DateTimeOffset Timestamp,
string EventType,
string Severity,
@@ -15,13 +25,18 @@ public record EventLogEntry(
/// <summary>
/// Response containing paginated event log entries from a site.
/// Uses keyset pagination: ContinuationToken is the last event ID in the result set.
/// </summary>
/// <param name="ContinuationToken">
/// Opaque keyset-pagination cursor: pass it back verbatim on the next request to
/// continue after the last returned row, or <see langword="null"/> to start from the
/// beginning. Encodes <c>timestamp</c> and <c>id</c> together, because GUID ids do not
/// sort chronologically and timestamps alone are not unique. Do not parse it.
/// </param>
public record EventLogQueryResponse(
string CorrelationId,
string SiteId,
IReadOnlyList<EventLogEntry> Entries,
long? ContinuationToken,
string? ContinuationToken,
bool HasMore,
bool Success,
string? ErrorMessage,