feat(audit): flip AuditLog clustered key to (OccurredAtUtc, EventId) (ScadaBridge#111)

Variant B2 of the #78 benchmark: migration FlipAuditLogClusteredKey drops the
twelve non-clustered indexes, re-adds PK_AuditLog as (OccurredAtUtc, EventId)
on ps_AuditLog_Month, adds the aligned unique UX_AuditLog_EventId_Occurred
(EventId, OccurredAtUtc) for the idempotency probe, and rebuilds the twelve
indexes unchanged. Guarded (re-runnable) Up, inverse-rebuild Down; production
scripts docs/plans/sql/FlipAuditLogClusteredKey{,.rollback}.sql.

The partition-switch purge staging table now reads the live clustered key
order from sys.index_columns, so it switches either shape (old binaries
hard-code the old order: ship with the binaries, both centrals stopped).

Evidence: 300k rows, page 1 90,532 -> 34 logical reads (ordered backward
clustered scan under Top), keyset page 90,532 -> 46, probe 14 -> 14;
FlipAuditLogClusteredKeyMigrationTests pins indexes, grants, Down/Up, the
staging key (mutation: hard-coded old key fails SWITCH) and the read ratio.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 22:50:35 -05:00
parent 559e02f5c8
commit 5e7d5389d4
14 changed files with 3032 additions and 43 deletions
@@ -118,11 +118,14 @@ public interface IAuditLogRepository
/// <remarks>
/// <para>
/// <b>Partition-aligned uniqueness — no index drop.</b> EventId uniqueness is
/// enforced by the clustered <c>PK_AuditLog (EventId, OccurredAtUtc)</c>,
/// which is aligned on <c>ps_AuditLog_Month(OccurredAtUtc)</c>, so
/// enforced by the clustered <c>PK_AuditLog (OccurredAtUtc, EventId)</c> and the
/// unique <c>UX_AuditLog_EventId_Occurred (EventId, OccurredAtUtc)</c> (ScadaBridge#111;
/// before that migration the PK alone, keyed <c>(EventId, OccurredAtUtc)</c>), all
/// aligned on <c>ps_AuditLog_Month(OccurredAtUtc)</c>, so
/// <c>ALTER TABLE … SWITCH PARTITION</c> has no non-aligned unique index to
/// object to. The implementation creates a staging table with byte-identical
/// schema, switches the partition's data into staging, and drops staging
/// schema and the same clustered key order as the live table (read at run time, so
/// either key shape purges), switches the partition's data into staging, and drops staging
/// (discarding the rows). Nothing is dropped from the live table, so there is
/// no window in which the idempotency enforcement is absent and no offline
/// index rebuild inside the switch transaction.