fix(audit): maintenance-login roll-forward/backfill, archive orphan cleanup, head-export health (ScadaBridge#113 #114 #115)

#113: AuditLogPartitionMaintenance (monthly SPLIT RANGE) and the
backfill-source-node endpoint now use the AuditLog:MaintenanceConnectionString
login when set (unset = unchanged). Migration AuditMaintenanceGrants gives
scadabridge_audit_purger ALTER ANY DATASPACE and column-level UPDATE (SourceNode).
#114: archive cleanup deletes the writer's own *.tmp files and manifest-less
data files older than 24 h inside {Directory}/{YYYY} (DeletedOrphan, dry-run aware).
#115: head-export failures bump scadabridge.audit.chain_head_export.failures and
Degrade the /health/ready entry audit-chain-head-export (failing or stale > 2 intervals).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 23:47:47 -05:00
parent b95ee5a658
commit 533414a16d
19 changed files with 2943 additions and 16 deletions
@@ -127,6 +127,8 @@ public sealed partial class AuditLogPartitionArchive
}
}
SweepOrphans(dryRun, items);
foreach (var item in items.Where(i => i.Action != AuditArchiveCleanupAction.KeptStale))
{
_logger.LogInformation("AuditLog archive cleanup{DryRun}: {Action} {Archive} — {Detail}",
@@ -136,6 +138,92 @@ public sealed partial class AuditLogPartitionArchive
return new AuditArchiveCleanupResult(dryRun, _options.RetentionDays, items);
}
/// <summary>
/// Files younger than this are never treated as orphans: a running archive write may still be
/// producing them (ScadaBridge#114).
/// </summary>
internal static readonly TimeSpan OrphanMinAge = TimeSpan.FromHours(24);
// Longest suffix first. A file is only ever considered through one of these exact suffixes
// on a well-formed archive name, so nothing foreign in the directory can match.
private static readonly string[] TempSuffixes = [".manifest.json.tmp", ".tombstones.parquet.tmp", ".parquet.tmp"];
private static readonly string[] DataSuffixes = [".tombstones.parquet", ".parquet"];
/// <summary>
/// Removes the leftovers of an interrupted archive write (ScadaBridge#114): the writer's own
/// temp files, and data files whose manifest — the commit marker — was never written. Only
/// files named exactly like the writer names them, directly inside a four-digit
/// <c>{Directory}/{YYYY}</c> folder whose year matches the file's, and last written longer ago
/// than <see cref="OrphanMinAge"/>. Reparse points are skipped.
/// </summary>
private void SweepOrphans(bool dryRun, List<AuditArchiveCleanupItem> items)
{
var root = _options.Directory!;
if (!Directory.Exists(root))
{
return;
}
var cutoff = _time.GetUtcNow().UtcDateTime - OrphanMinAge;
foreach (var yearDir in Directory.EnumerateDirectories(root))
{
var year = Path.GetFileName(yearDir);
if (year.Length != 4 || !year.All(char.IsAsciiDigit) || IsReparsePoint(yearDir))
{
continue;
}
foreach (var path in Directory.EnumerateFiles(yearDir))
{
var file = Path.GetFileName(path);
var tmpSuffix = TempSuffixes.FirstOrDefault(x => file.EndsWith(x, StringComparison.Ordinal));
var isTemp = tmpSuffix is not null;
var suffix = tmpSuffix ?? DataSuffixes.FirstOrDefault(x => file.EndsWith(x, StringComparison.Ordinal));
if (suffix is null)
{
continue;
}
var stem = file[..^suffix.Length];
if (!IsValidName(stem) || stem.Substring("auditlog-".Length, 4) != year || IsReparsePoint(path))
{
continue;
}
if (!isTemp && File.Exists(Path.Combine(yearDir, stem + ".manifest.json")))
{
continue; // a committed archive's file
}
if (File.GetLastWriteTimeUtc(path) > cutoff)
{
continue; // possibly still being written
}
if (!dryRun)
{
try
{
File.Delete(path);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
_logger.LogWarning(ex, "AuditLog archive cleanup could not delete orphan {File}.", file);
continue;
}
}
items.Add(new AuditArchiveCleanupItem(stem, stem.Substring("auditlog-".Length, 7), AuditArchiveCleanupAction.DeletedOrphan,
isTemp
? $"{file}: temp file of an interrupted archive write, older than {OrphanMinAge.TotalHours:0} h."
: $"{file}: no {stem}.manifest.json (the archive write never committed), older than {OrphanMinAge.TotalHours:0} h."));
}
}
}
private static bool IsReparsePoint(string path)
=> (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0;
/// <summary>
/// Proves <paramref name="later"/> holds every row of <paramref name="stale"/>; returns null
/// when it does, else why not.
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
@@ -23,7 +24,7 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Maintenance;
public sealed class AuditMaintenanceContext : IAsyncDisposable, IDisposable
{
/// <summary>DI key of the maintenance-login <c>IAuditLogRepository</c> and <c>IAuditLogArchive</c>.</summary>
public const string ServiceKey = "audit-maintenance";
public const string ServiceKey = AuditLogServiceKeys.Maintenance;
private readonly bool _owned;
@@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
{
/// <summary>
/// Grants for the two AuditLog maintenance paths that now run on the maintenance login
/// (<c>AuditLog:MaintenanceConnectionString</c>, ScadaBridge#113). Permission DDL only.
/// <list type="bullet">
/// <item><c>ALTER ANY DATASPACE</c> to <c>scadabridge_audit_purger</c> — the monthly
/// roll-forward's <c>ALTER PARTITION FUNCTION … SPLIT RANGE</c> / <c>ALTER PARTITION SCHEME
/// … NEXT USED</c>; <c>ALTER ON SCHEMA::dbo</c> does not confer it.</item>
/// <item>column-level <c>UPDATE (SourceNode)</c> to the same role — the one-time
/// <c>audit backfill-source-node</c>. Column-scoped on purpose: no other AuditLog column
/// becomes updatable.</item>
/// </list>
/// </summary>
public partial class AuditMaintenanceGrants : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(@"
IF DATABASE_PRINCIPAL_ID('scadabridge_audit_purger') IS NULL
EXEC sp_executesql N'CREATE ROLE scadabridge_audit_purger';
GRANT ALTER ANY DATASPACE TO scadabridge_audit_purger;
GRANT UPDATE (SourceNode) ON dbo.AuditLog TO scadabridge_audit_purger;"); // AUDIT-PURGE-ALLOWED: role grant for the maintenance principal (SourceNode backfill)
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(@"
IF DATABASE_PRINCIPAL_ID('scadabridge_audit_purger') IS NOT NULL
BEGIN
REVOKE ALTER ANY DATASPACE FROM scadabridge_audit_purger;
REVOKE UPDATE (SourceNode) ON dbo.AuditLog FROM scadabridge_audit_purger;
END"); // AUDIT-PURGE-ALLOWED: role grant reversal for the maintenance principal
}
}
}
@@ -115,7 +115,11 @@ public static class ServiceCollectionExtensions
// hosted service. Scoped because the implementation reuses the per-scope
// ScadaBridgeDbContext for raw-SQL execution; the hosted service opens a
// fresh scope on each tick (mirrors AuditLogPurgeActor / AuditLogIngestActor).
services.AddScoped<IPartitionMaintenance, AuditLogPartitionMaintenance>();
// Runs on the maintenance connection when AuditLog:MaintenanceConnectionString is set
// (ScadaBridge#113), else on the scope's own context as before.
services.AddScoped<IPartitionMaintenance>(sp => new AuditLogPartitionMaintenance(
sp.GetRequiredService<AuditMaintenanceContext>().Context,
sp.GetService<Microsoft.Extensions.Logging.ILogger<AuditLogPartitionMaintenance>>()));
// AuditLog maintenance connection (ScadaBridge#107 item 3): the chain job and both purge
// paths run on AuditMaintenanceContext — the scope's own context unless a separate