fix(localdb): apply upserts on the primary key, not INSERT OR REPLACE (scadaproj#38)

INSERT OR REPLACE resolved a secondary UNIQUE conflict by deleting a
different row (another PK) with capture suppressed and its ledger left live,
so a pair diverged silently (LocalDb-003). The applier now uses
INSERT ... ON CONFLICT(<pk>) DO UPDATE (DO NOTHING when every column is PK):
a clash on another unique key aborts the entry, which is dead-lettered, and
each node keeps its own row. Side effect: a remote update of a parent with
ON DELETE RESTRICT children now applies instead of being dead-lettered.

Also waits for the snapshot watermark in WipedPeer_SnapshotLiftsItsWatermark,
which raced SnapshotComplete under full-suite load.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 14:58:34 -05:00
parent 4af0ea8152
commit 15a6c7c710
10 changed files with 250 additions and 22 deletions
@@ -362,11 +362,27 @@ internal sealed class LwwApplier(SqliteLocalDb db, Func<DateTimeOffset>? utcNow
return $"DELETE FROM {Ident(table.Name)} WHERE {pkMatch}";
}
/// <summary>
/// An upsert keyed on the PRIMARY KEY only (LocalDb-003). <c>INSERT OR REPLACE</c> resolved
/// a conflict on ANY unique constraint by deleting the conflicting row — on a secondary
/// <c>UNIQUE</c> that is a different row (another primary key), removed with capture
/// suppressed, its ledger row left saying "live", and nothing shipped to the peer: silent
/// divergence. <c>ON CONFLICT(pk) DO UPDATE</c> touches only the row this entry names; a
/// clash on any other unique key aborts the statement, which the caller dead-letters, so it
/// is visible. Updating in place also stops a parent's update from deleting it first, which
/// an <c>ON DELETE RESTRICT</c> child refused.
/// </summary>
private static string BuildUpsert(ReplicatedTable table)
{
var columns = string.Join(", ", table.Columns.Select(c => Ident(c.Name)));
var values = string.Join(", ", table.Columns.Select(c => $"json_extract(@row, {JsonPath(c.Name)})"));
return $"INSERT OR REPLACE INTO {Ident(table.Name)} ({columns}) VALUES ({values})";
var pk = string.Join(", ", table.PkColumns.Select(Ident));
var nonPk = table.Columns
.Where(c => !table.PkColumns.Contains(c.Name, StringComparer.OrdinalIgnoreCase))
.Select(c => $"{Ident(c.Name)} = excluded.{Ident(c.Name)}")
.ToList();
var action = nonPk.Count == 0 ? "DO NOTHING" : "DO UPDATE SET " + string.Join(", ", nonPk);
return $"INSERT INTO {Ident(table.Name)} ({columns}) VALUES ({values}) ON CONFLICT ({pk}) {action}";
}
// Local copy of TriggerSqlGenerator's convention (that helper lives in the core assembly).