Files
Joseph Doherty 727fa48cba 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
2026-07-19 03:15:17 -04:00

134 lines
4.5 KiB
C#

using Microsoft.Data.Sqlite;
namespace ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests;
/// <summary>
/// LocalDb Phase 1 (Task 2) — the <c>site_events</c> DDL is extracted out of
/// <see cref="SiteEventLogger"/> so the Host's <c>AddZbLocalDb</c> onReady callback can
/// create it in the consolidated site database.
/// <para>
/// The extraction also carries the one deliberate schema CHANGE of Phase 1: the primary
/// key moves from <c>INTEGER PRIMARY KEY AUTOINCREMENT</c> to a TEXT GUID. Under the
/// library's last-writer-wins replication, two site nodes each minting autoincrement id 1
/// would be treated as the same row and silently overwrite one another. GUID keys make
/// the event log a pure union across the pair instead.
/// </para>
/// </summary>
public class SiteEventLogSchemaTests
{
private static SqliteConnection OpenConnection()
{
var conn = new SqliteConnection("Data Source=:memory:");
conn.Open();
return conn;
}
private static List<(string Name, string Type, bool NotNull, bool Pk)> TableInfo(
SqliteConnection conn, string table)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = $"PRAGMA table_info('{table}')";
using var reader = cmd.ExecuteReader();
var cols = new List<(string, string, bool, bool)>();
while (reader.Read())
{
cols.Add((reader.GetString(1), reader.GetString(2), reader.GetInt32(3) == 1,
reader.GetInt32(5) > 0));
}
return cols;
}
[Fact]
public void Apply_CreatesTableWithExpectedColumns()
{
using var conn = OpenConnection();
SiteEventLogSchema.Apply(conn);
Assert.Equal(
["id", "timestamp", "event_type", "severity", "instance_id", "source", "message", "details"],
TableInfo(conn, "site_events").Select(c => c.Name));
}
[Fact]
public void Apply_IdIsTextPrimaryKey_NotAutoincrement()
{
using var conn = OpenConnection();
SiteEventLogSchema.Apply(conn);
var pk = Assert.Single(TableInfo(conn, "site_events"), c => c.Pk);
Assert.Equal("id", pk.Name);
Assert.Equal("TEXT", pk.Type);
// AUTOINCREMENT creates the sqlite_sequence bookkeeping table. Its absence
// is the load-bearing assertion: ids must be application-minted GUIDs, not
// server-minted integers that collide across the replicating pair.
using var cmd = conn.CreateCommand();
cmd.CommandText =
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'sqlite_sequence'";
Assert.Equal(0L, Convert.ToInt64(cmd.ExecuteScalar()));
}
[Fact]
public void Apply_RejectsIntegerIdInserts()
{
using var conn = OpenConnection();
SiteEventLogSchema.Apply(conn);
// A TEXT PK with no AUTOINCREMENT means an INSERT omitting id is an error,
// which is what forces the writer to mint one (Task 5a).
using var cmd = conn.CreateCommand();
cmd.CommandText = """
INSERT INTO site_events (timestamp, event_type, severity, source, message)
VALUES ('2026-07-19T00:00:00Z', 'Test', 'Info', 'test', 'no id supplied')
""";
Assert.Throws<SqliteException>(() => cmd.ExecuteNonQuery());
}
[Fact]
public void Apply_HasNoBlobColumns()
{
using var conn = OpenConnection();
SiteEventLogSchema.Apply(conn);
Assert.DoesNotContain(
TableInfo(conn, "site_events"),
c => c.Type.Contains("BLOB", StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void Apply_CreatesExpectedIndexes()
{
using var conn = OpenConnection();
SiteEventLogSchema.Apply(conn);
using var cmd = conn.CreateCommand();
cmd.CommandText =
"SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'site_events' " +
"AND name NOT LIKE 'sqlite_%' ORDER BY name";
using var reader = cmd.ExecuteReader();
var indexes = new List<string>();
while (reader.Read()) indexes.Add(reader.GetString(0));
Assert.Equal(
["idx_events_instance", "idx_events_severity", "idx_events_timestamp", "idx_events_type"],
indexes);
}
[Fact]
public void Apply_IsIdempotent()
{
using var conn = OpenConnection();
SiteEventLogSchema.Apply(conn);
SiteEventLogSchema.Apply(conn);
Assert.Equal(8, TableInfo(conn, "site_events").Count);
}
}