Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Deployments/DeploymentDriftProbe.cs
T
Joseph Doherty 35576485b1
v2-ci / unit-tests (push) Has been cancelled
fix(adminui): deployments drift chip never serves a stale "In sync" (#903)
Root cause: DeploymentDriftProbe (a singleton shared by every circuit) cached its verdict until
the ConfigEdit audit watermark (MAX(EditedAtUtc), COUNT(*)) moved, assuming every configuration
write appends a ConfigEdit row. Only deployments and driver restart/reconnect do; the AdminUI
editors (RawTreeService, UnsTreeService, ScriptEdit, cluster/node/ACL pages) write the config
tables directly. So after a draft change the page kept showing the cached "In sync" until
something unrelated moved the watermark.

- DeploymentDriftProbe: the watermark cache is gone; every verdict comes from a composition that
  started after the caller asked. Compositions stay serialised behind the gate, and callers queued
  behind one share a verdict only when that composition started after they arrived (start
  sequence number) for the same sealed hash, so sharing is exact, never stale.
- Deployments page: the drift check runs in OnAfterRenderAsync (interactive render only, so a
  visit costs one composition, not two with prerender); the first render shows a neutral
  "Checking for changes..." chip, never a verdict; a failed check shows "Drift check failed" and
  logs a warning instead of crashing the page. A deploy re-runs the check.
- Tests: probe tests for an un-audited draft change (real ConfigComposer over InMemory), fresh
  composition per call, and queued callers not reusing an older composition; bUnit page tests that
  a second page load after a direct draft change shows "Configuration drift" and that the first
  render shows "Checking" until the comparison answers. All fail against the previous code.
  DeploymentDriftProbeSqlServerTests is removed: it pinned the SQL translation of the watermark
  query, which no longer exists.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-13 01:50:37 -05:00

105 lines
5.4 KiB
C#

using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Deployments;
/// <summary>
/// Answers the /deployments page's "Configuration drift" chip: does the live-edit state still hash to the
/// latest sealed revision?
/// </summary>
/// <remarks>
/// <para>
/// <b>Always a fresh composition (lmxopcua#903).</b> This probe used to cache its verdict until the
/// <c>ConfigEdit</c> audit watermark <c>(MAX(EditedAtUtc), COUNT(*))</c> moved, on the premise that every
/// configuration write appends a <c>ConfigEdit</c> row. That premise was false: the AdminUI's own editors
/// (<c>RawTreeService</c>, <c>UnsTreeService</c>, <c>ScriptEdit</c>, the cluster/node/ACL pages) write the
/// configuration tables directly and append no audit row — only deployments and driver restart/reconnect do.
/// So after a draft change the chip kept serving the cached "In sync" until something unrelated moved the
/// watermark: an operator could believe there was nothing to deploy. There is no cheap, provider-neutral
/// signal that moves on every write to the ~18 composed tables, so every verdict is now computed from a
/// composition that read the configuration AFTER the request arrived.
/// </para>
/// <para>
/// <b>Concurrency.</b> Compositions are serialised behind a <see cref="SemaphoreSlim"/>, so N circuits
/// opening the page at once never run N fleet snapshots in parallel. A caller queued behind a composition
/// reuses that verdict only when the composition <i>started after the caller arrived</i> (tracked by a
/// start sequence number) and was against the same sealed revision — such a composition has already seen
/// every edit committed before the caller asked, so sharing it is exact, not stale. A throw leaves the
/// previous verdict in place and propagates to its caller alone.
/// </para>
/// </remarks>
/// <param name="dbFactory">Factory for the configuration database context.</param>
/// <param name="composeRevisionHash">
/// The compose seam — returns the revision hash of a fresh snapshot of the supplied context.
/// Defaults to the real <c>ConfigComposer.SnapshotAndFlattenAsync(...).RevisionHash</c>; tests
/// inject a counting fake.
/// </param>
public sealed class DeploymentDriftProbe(
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
Func<OtOpcUaConfigDbContext, Task<string>>? composeRevisionHash = null)
{
private readonly Func<OtOpcUaConfigDbContext, Task<string>> _composeRevisionHash =
composeRevisionHash ?? ComposeRevisionHashAsync;
private readonly SemaphoreSlim _composeGate = new(1, 1);
/// <summary>How many compositions have started; incremented under the gate as each one begins.</summary>
private long _composesStarted;
/// <summary>The last computed verdict, or <see langword="null"/> before the first one. Read and written
/// only under the gate.</summary>
private Verdict? _verdict;
/// <summary>
/// Reports whether the live-edit configuration has drifted from the supplied sealed revision.
/// </summary>
/// <param name="latestSealedRevisionHash">
/// The revision hash of the most recent sealed deployment. Empty means there is nothing sealed to
/// compare against.
/// </param>
/// <param name="ct">Cancellation token.</param>
/// <returns>
/// <see langword="true"/> when the current configuration hashes to something other than
/// <paramref name="latestSealedRevisionHash"/>, <see langword="false"/> when it matches, and
/// <see langword="null"/> when no verdict applies (no sealed revision supplied).
/// </returns>
public async Task<bool?> GetDriftAsync(string latestSealedRevisionHash, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(latestSealedRevisionHash)) return null;
// Any composition numbered above this one starts after this point, so it reads every edit
// committed before this call.
var arrivedAfter = Interlocked.Read(ref _composesStarted);
await _composeGate.WaitAsync(ct);
try
{
var shared = _verdict;
if (shared is not null
&& shared.Sequence > arrivedAfter
&& string.Equals(shared.SealedRevisionHash, latestSealedRevisionHash, StringComparison.Ordinal))
{
return shared.Drift;
}
var sequence = Interlocked.Increment(ref _composesStarted);
await using var db = await dbFactory.CreateDbContextAsync(ct);
var current = await _composeRevisionHash(db);
var drift = !string.Equals(current, latestSealedRevisionHash, StringComparison.Ordinal);
_verdict = new Verdict(sequence, latestSealedRevisionHash, drift);
return drift;
}
finally
{
_composeGate.Release();
}
}
private static async Task<string> ComposeRevisionHashAsync(OtOpcUaConfigDbContext db) =>
(await ConfigComposer.SnapshotAndFlattenAsync(db)).RevisionHash;
/// <summary>A drift answer from the composition with start number <paramref name="Sequence"/>.</summary>
private sealed record Verdict(long Sequence, string SealedRevisionHash, bool Drift);
}