feat(audit): archive retention and superseded stale-archive cleanup (ScadaBridge#109)

Owner decisions recorded: the archive destination stays a directory/UNC
(no object-storage client; share + permissions named at enablement),
parquet-tools-only reading (no re-import), unsigned like the chain (#107).

AuditLog:Archive:RetentionDays (default 0 = never delete; else must exceed
AuditLog:RetentionDays, counted from the archived month's end) and
DeleteSupersededStaleArchives (default true) run after every purge tick.
A retried purge's stale Archived archive is deleted only when a later,
verifying, Purged archive of the same partition provably holds every row:
same prior anchor and the stale chain-end hash at its chain-end sequence
(row or tombstone), every unchained row present by EventId; otherwise it is
reported KeptStale. A sole copy left at Archived is never touched. Deletion
removes only the archive name's own three files in its folder, manifest
first, never a manifest-supplied path. `audit archive cleanup [--dry-run]`
= CleanupAuditArchives (Administrator).

AuditLogArchiveCleanupTests (MSSQL) cover retried purge, kept stale copy,
sole copy, retention and the path guard; each safety rule mutation-checked.
Follow-ups filed: #113, #114, #115.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 23:32:53 -05:00
parent c4d7ec9b96
commit b95ee5a658
26 changed files with 1099 additions and 26 deletions
@@ -43,4 +43,19 @@ public sealed class AuditLogArchiveOptions
/// the hash-chain lock before giving up for this tick (default 300).
/// </summary>
public int ChainLockTimeoutSeconds { get; set; } = 300;
/// <summary>
/// Archive retention in days, counted from the END of the archived month (ScadaBridge#109).
/// <c>0</c> (the default) = archives are never deleted — until compliance names a period.
/// When set it must exceed <c>AuditLog:RetentionDays</c>, so an archive always outlives the
/// rows' time in the database. Applied by the purge actor after each tick's partition purge.
/// </summary>
public int RetentionDays { get; set; }
/// <summary>
/// Delete stale archives a retried purge left behind (status <c>Archived</c>) once a later,
/// verified, purged archive of the same partition provably holds all their rows (default
/// true; ScadaBridge#109). A stale archive that cannot be proven redundant is kept.
/// </summary>
public bool DeleteSupersededStaleArchives { get; set; } = true;
}
@@ -0,0 +1,290 @@
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
/// <summary>
/// Archive cleanup (ScadaBridge#109): retention and superseded-stale-archive deletion.
/// </summary>
/// <remarks>
/// <para>
/// <b>Superseded stale archives.</b> A purge whose guard finds the partition changed after it
/// was archived (51002/51003) purges nothing and leaves its archive at status
/// <see cref="AuditArchiveStatus.Archived"/>; the next tick writes a fresh archive and purges
/// with it. The stale one is redundant only if a LATER archive B of the same partition, which
/// is <see cref="AuditArchiveStatus.Purged"/> and verifies, holds everything the stale archive A
/// holds. That is proven, not assumed: for every chain month of A, B starts from the same
/// earlier purge anchor and carries A's chain-end hash at A's chain-end sequence (as a row or a
/// tombstone) — so, the chain being a hash chain B itself verifies, every chained row of A is
/// in B; and every UNCHAINED row of A is found in B (row or tombstone) by EventId. Anything
/// else — notably an unchained row a per-channel purge removed in between, which leaves no
/// tombstone — keeps A (<see cref="AuditArchiveCleanupAction.KeptStale"/>). An archive left at
/// <c>Archived</c> because the node stopped between the switch and the manifest update has no
/// later purged archive and is kept: it is the only copy.
/// </para>
/// <para>
/// <b>Retention.</b> With <see cref="AuditLogArchiveOptions.RetentionDays"/> &gt; 0, an archive
/// whose month ended more than that many days ago is deleted when it is <c>Purged</c>, or —
/// an <c>Archived</c> one — when its partition no longer holds rows in <c>dbo.AuditLog</c>.
/// </para>
/// <para>
/// <b>Safe deletion.</b> Only the three files a well-formed archive name implies
/// (<c>{name}.manifest.json</c>, <c>{name}.parquet</c>, <c>{name}.tombstones.parquet</c>) in the
/// archive's own <c>{Directory}/{YYYY}</c> folder are deleted — never a path read from the
/// manifest — and the manifest goes FIRST, so an interrupted deletion leaves leftovers that are
/// no longer an archive rather than a manifest naming missing files.
/// </para>
/// </remarks>
public sealed partial class AuditLogPartitionArchive
{
/// <summary>
/// Upper bound on unchained rows compared by EventId when proving a stale archive redundant;
/// a larger set keeps the archive rather than spend the memory.
/// </summary>
internal const long MaxUnchainedRowsCompared = 5_000_000;
/// <inheritdoc />
public async Task<AuditArchiveCleanupResult> CleanupAsync(bool dryRun, CancellationToken ct = default)
{
RequireConfigured();
var items = new List<AuditArchiveCleanupItem>();
var manifests = await ListAsync(ct).ConfigureAwait(false);
var deleted = new HashSet<string>(StringComparer.Ordinal);
if (_options.DeleteSupersededStaleArchives)
{
foreach (var stale in manifests.Where(m => m.Status == AuditArchiveStatus.Archived))
{
var later = manifests
.Where(m => m.PartitionBoundaryUtc == stale.PartitionBoundaryUtc
&& m.Status == AuditArchiveStatus.Purged
&& m.ArchivedAtUtc > stale.ArchivedAtUtc)
.OrderBy(m => m.ArchivedAtUtc)
.ToList();
if (later.Count == 0)
{
continue; // not superseded (e.g. the node stopped before marking it Purged) — keep
}
string? reason = null;
AuditArchiveManifest? coveredBy = null;
foreach (var candidate in later)
{
reason = await ProveCoveredAsync(stale, candidate, ct).ConfigureAwait(false);
if (reason is null)
{
coveredBy = candidate;
break;
}
}
if (coveredBy is null)
{
items.Add(new AuditArchiveCleanupItem(stale.Name, stale.Partition, AuditArchiveCleanupAction.KeptStale,
$"No later purged archive provably covers it: {reason}"));
continue;
}
if (!dryRun)
{
DeleteArchiveFiles(stale);
}
deleted.Add(stale.Name);
items.Add(new AuditArchiveCleanupItem(stale.Name, stale.Partition, AuditArchiveCleanupAction.DeletedSuperseded,
$"Superseded by {coveredBy.Name}, which is purged, verifies and holds every row of this archive."));
}
}
if (_options.RetentionDays > 0)
{
var now = _time.GetUtcNow().UtcDateTime;
foreach (var manifest in manifests.Where(m => !deleted.Contains(m.Name)))
{
var monthEnd = AuditChainHasher.MonthOf(manifest.PartitionBoundaryUtc).AddMonths(1);
if (monthEnd.AddDays(_options.RetentionDays) > now)
{
continue;
}
if (manifest.Status != AuditArchiveStatus.Purged
&& await PartitionHasRowsAsync(manifest.PartitionBoundaryUtc, ct).ConfigureAwait(false))
{
continue; // the partition was never switched out; this archive is not a sole copy, nor expired data gone
}
if (!dryRun)
{
DeleteArchiveFiles(manifest);
}
deleted.Add(manifest.Name);
items.Add(new AuditArchiveCleanupItem(manifest.Name, manifest.Partition, AuditArchiveCleanupAction.DeletedExpired,
$"{manifest.Partition} ended {monthEnd:yyyy-MM-dd}, more than {_options.RetentionDays} days ago (AuditLog:Archive:RetentionDays)."));
}
}
foreach (var item in items.Where(i => i.Action != AuditArchiveCleanupAction.KeptStale))
{
_logger.LogInformation("AuditLog archive cleanup{DryRun}: {Action} {Archive} — {Detail}",
dryRun ? " (dry run)" : "", item.Action, item.Name, item.Detail);
}
return new AuditArchiveCleanupResult(dryRun, _options.RetentionDays, items);
}
/// <summary>
/// Proves <paramref name="later"/> holds every row of <paramref name="stale"/>; returns null
/// when it does, else why not.
/// </summary>
private async Task<string?> ProveCoveredAsync(AuditArchiveManifest stale, AuditArchiveManifest later, CancellationToken ct)
{
// Same chain generation and at least as far, for every chain month the stale archive has.
var laterChains = later.Chains.ToDictionary(c => c.Partition, StringComparer.Ordinal);
var targets = new Dictionary<(DateTime Month, long Seq), string>();
foreach (var chain in stale.Chains)
{
if (!laterChains.TryGetValue(chain.Partition, out var next))
{
return $"{later.Name} has no chain for {chain.Partition}.";
}
if (next.PriorPurgedThroughSeq != chain.PriorPurgedThroughSeq || next.LastSeq < chain.LastSeq)
{
return $"{later.Name}'s chain for {chain.Partition} does not extend this archive's (prior anchor or end differs).";
}
if (chain.LastSeq > (chain.PriorPurgedThroughSeq ?? 0))
{
targets[(AuditArchiveParquet.ParseMonth(chain.Partition), chain.LastSeq)] = chain.LastHash.ToLowerInvariant();
}
}
if (stale.UnchainedRowCount > MaxUnchainedRowsCompared)
{
return $"{stale.UnchainedRowCount} unchained rows exceed the {MaxUnchainedRowsCompared} compared by EventId.";
}
// The later archive must itself be intact and tied to the database.
var verification = await VerifyAsync(later.Name, ct).ConfigureAwait(false);
if (!verification.Verified)
{
return $"{later.Name} does not verify ({verification.FileProblem ?? "chain or anchor problem"}).";
}
var directory = ArchiveDirectory(stale);
var unchained = new HashSet<Guid>();
await using (var input = File.OpenRead(Path.Combine(directory, stale.Name + ".parquet")))
{
await foreach (var row in AuditArchiveParquet.ReadRowsAsync(input, ct).ConfigureAwait(false))
{
if (row.ChainSeq is null)
{
unchained.Add(row.EventId);
}
}
}
var laterDirectory = ArchiveDirectory(later);
await using (var input = File.OpenRead(Path.Combine(laterDirectory, later.Name + ".parquet")))
{
await foreach (var row in AuditArchiveParquet.ReadRowsAsync(input, ct).ConfigureAwait(false))
{
unchained.Remove(row.EventId);
if (row.ChainSeq is { } seq
&& targets.TryGetValue((AuditChainHasher.MonthOf(row.OccurredAtUtc), seq), out var expected))
{
if (row.RowHash is null || !string.Equals(Convert.ToHexStringLower(row.RowHash), expected, StringComparison.Ordinal))
{
return $"{later.Name} carries a different hash at the stale archive's chain end.";
}
targets.Remove((AuditChainHasher.MonthOf(row.OccurredAtUtc), seq));
}
}
}
await using (var input = File.OpenRead(Path.Combine(laterDirectory, later.Name + ".tombstones.parquet")))
{
await foreach (var tombstone in AuditArchiveParquet.ReadTombstonesAsync(input, ct).ConfigureAwait(false))
{
unchained.Remove(tombstone.EventId);
if (targets.TryGetValue((tombstone.ChainMonth, tombstone.ChainSeq), out var expected))
{
if (!string.Equals(Convert.ToHexStringLower(tombstone.RowHash), expected, StringComparison.Ordinal))
{
return $"{later.Name} carries a different hash at the stale archive's chain end.";
}
targets.Remove((tombstone.ChainMonth, tombstone.ChainSeq));
}
}
}
if (targets.Count > 0)
{
return $"{later.Name} does not contain the stale archive's chain end.";
}
return unchained.Count == 0
? null
: $"{unchained.Count} unchained row(s) of this archive are not in {later.Name} (e.g. removed by a per-channel purge, which leaves no tombstone for an unchained row).";
}
private async Task<bool> PartitionHasRowsAsync(DateTime boundary, CancellationToken ct)
{
var conn = _context.Database.GetDbConnection();
var openedHere = await AuditLogHashChain.OpenAsync(conn, ct).ConfigureAwait(false);
try
{
await using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CASE WHEN EXISTS (SELECT 1 FROM dbo.AuditLog " +
"WHERE $partition.pf_AuditLog_Month(OccurredAtUtc) = $partition.pf_AuditLog_Month(@boundary)) THEN 1 ELSE 0 END;";
cmd.Parameters.Add(new SqlParameter("@boundary", SqlDbType.DateTime2) { Scale = 7, Value = boundary });
return Convert.ToInt32(await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false)) == 1;
}
finally
{
if (openedHere)
{
await conn.CloseAsync().ConfigureAwait(false);
}
}
}
private string ArchiveDirectory(AuditArchiveManifest manifest)
{
if (!IsValidName(manifest.Name))
{
throw new InvalidOperationException($"'{manifest.Name}' is not an archive name.");
}
return Path.Combine(_options.Directory!, manifest.Name.Substring("auditlog-".Length, 4));
}
/// <summary>
/// Deletes exactly the archive's three files, manifest first. File names are derived from
/// the validated archive name, never taken from the manifest.
/// </summary>
private void DeleteArchiveFiles(AuditArchiveManifest manifest)
{
var directory = Path.GetFullPath(ArchiveDirectory(manifest));
var root = Path.GetFullPath(_options.Directory!);
if (!directory.StartsWith(root, StringComparison.Ordinal))
{
throw new InvalidOperationException($"Archive {manifest.Name} resolves outside {root}.");
}
foreach (var file in new[] { ".manifest.json", ".parquet", ".tombstones.parquet" })
{
var path = Path.Combine(directory, manifest.Name + file);
if (File.Exists(path))
{
File.Delete(path);
}
}
}
}