fix(grpc-data): A4 review r2 S1–S4 — the deploy hold reads one (placements, undecided) set, settles on any completion, is bounded (stale + MaxHold, reported as held), and its takeover sends RefreshRequired once

- S1: ProjectedMappingDeploymentRuntime publishes ProjectedMappingSet (placements + undecided + sequence) captured under
  its lock; DeployedConditionMappings keeps it as one volatile value (highest sequence wins); ReconcileRunners reads
  IProjectedConditionMappings.Snapshot. Deterministic window test via a Changed handler registered before the adapter.
- S2: a separate _undecided flag clears on ANY completion (failed/degraded/throwing build ⇒ settled empty ⇒ release);
  browse-anchor Suspended semantics unchanged. A held set goes BadNoCommunication on the stale timeout and is released
  past ProjectedConditionOptions.MaxHold (5 min); diagnostics report "held" and keep its counters; Dispose clears _held.
- S3: a runner that took over a non-empty held set sends RequireRefresh once at its first barrier.
- S4/NITs: runtime-level Began/Completed tests, F1 must-arrive control, linger-expiry-while-held.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-25 04:04:07 -05:00
parent 5752243724
commit d72f2d966d
5 changed files with 480 additions and 30 deletions
@@ -255,10 +255,23 @@ public sealed partial class ProjectedConditionAccess
/// <summary>A4 review r1 S4: per materialised key, the mapping that chose its SourceName and that name. Owned by the loop.</summary>
private Dictionary<string, (string MappingId, string SourceName)> _sourceNames = new(StringComparer.Ordinal);
/// <summary>
/// A4 review r2 S3: this runner took over a set HELD across an undecided deploy. During the hold nothing imported was
/// visible (no mapping), so an event queued then was dropped and a ConditionRefresh replayed nothing; the takeover
/// re-snapshot reports no event for an unchanged marker. Its first barrier therefore sends RefreshRequired once
/// (visibility-gated, EventIds kept) — not a condition event. Loop-owned after construction.
/// </summary>
private bool _refreshAfterHold;
/// <summary>A4 review r2 S2: while held, the bound's timers (under <see cref="_staleGate"/>).</summary>
private bool _holding;
private ITimer? _holdRelease;
private ITimer? _holdStale;
public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature,
ConnectionRunner? predecessor)
ConnectionRunner? predecessor, bool tookOverHeld = false)
{
_owner = owner; ConnectionId = connectionId; _mappings = mappings; Signature = signature; _predecessor = predecessor;
_refreshAfterHold = tookOverHeld;
}
public string ConnectionId { get; }
@@ -330,6 +343,8 @@ public sealed partial class ProjectedConditionAccess
Volatile.Write(ref _materialisedCount, _materialised.Count);
Volatile.Write(ref _unknownCount, _unknownKeys.Count);
_predecessor = null;
// A4 review r2 S3: nothing held ⇒ nothing a client could have missed.
if (_materialised.Count == 0) _refreshAfterHold = false;
}
public void Stop(bool removeConditions)
@@ -351,10 +366,47 @@ public sealed partial class ProjectedConditionAccess
/// </summary>
public void ReleaseHeld()
{
EndHold();
var stopped = _stopped;
_stopped = stopped.ContinueWith(_ => RemoveMaterialised(), TaskScheduler.Default);
}
/// <summary>
/// A4 review r2 S2 (under the owner's _gate, right after <see cref="Stop"/> without removal): the hold is bounded.
/// <paramref name="release"/> fires at <c>MaxHold</c> (the owner releases); after the loop has stopped, the held
/// conditions go <c>BadNoCommunication</c> on the connection's stale timeout — a hold is a stream gap (§5.1 T2: unknown,
/// never known-inactive). <see cref="EndHold"/> (takeover / release) disarms both.
/// </summary>
public void Hold(ITimer release)
{
lock (_staleGate) { _holding = true; _holdRelease = release; }
_ = _stopped.ContinueWith(_ =>
{
lock (_staleGate)
{
if (!_holding || _materialised.Count == 0) return;
var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds)));
_holdStale = _owner._clock.CreateTimer(_ =>
{
// Under the same gate EndHold takes before any takeover, so a mark never lands after the successor began.
lock (_staleGate)
if (_holding) _owner._sink()?.MarkConnectionStale(ConnectionId);
}, null, timeout, Timeout.InfiniteTimeSpan);
}
}, TaskScheduler.Default);
}
/// <summary>A4 review r2 S2: the hold ended (taken over, released, disposed) — no stale mark or release fires after this.</summary>
public void EndHold()
{
lock (_staleGate)
{
_holding = false;
_holdRelease?.Dispose(); _holdRelease = null;
_holdStale?.Dispose(); _holdStale = null;
}
}
private void RemoveMaterialised()
{
var keys = _materialised.ToArray();
@@ -713,8 +765,11 @@ public sealed partial class ProjectedConditionAccess
ConnectionId, string.Join(", ", states.Select(x => x.MappingId + "=" + x.Status)), states.Where(x => x.Contributes).Sum(x => x.Live!.Records.Count),
timedOut ? "; snapshot timed out" : "");
Reconcile(states, states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal), full: true);
// A4 review r2 S3: the first barrier after taking over a held set — once, after the re-snapshot applied.
var afterHold = _refreshAfterHold;
_refreshAfterHold = false;
// S7: an incomplete (re)snapshot — a timeout OR a refused item — tells clients to refresh.
if (incomplete && !alreadyTold) RequireRefresh();
if ((incomplete && !alreadyTold) || afterHold) RequireRefresh();
else if (incomplete)
_owner._log.LogDebug("Imported conditions: connection {Connection} incomplete set unchanged ({Mappings}) — no RefreshRequired",
ConnectionId, string.Join(", ", incompleteSet));
@@ -27,25 +27,57 @@ public interface IProjectedConditionMappings
/// removed only if the settled set no longer has that connection.
/// </summary>
bool Suspended => false;
/// <summary>
/// A4 review r2 S1: <see cref="Current"/> and <see cref="Suspended"/> as ONE consistent pair. A reader that pairs a live
/// "settled" flag with a placement list copied earlier (still the deploy's empty set) would release held conditions.
/// </summary>
(IReadOnlyList<ProjectedMappingPlacement> Current, bool Suspended) Snapshot => (Current, Suspended);
}
/// <summary>The production adapter over <see cref="ProjectedMappingDeploymentRuntime"/>.</summary>
/// <remarks>
/// A4 review r2 S1: the placements and the "attempt undecided" flag arrive TOGETHER in one
/// <see cref="ProjectedMappingSet"/> captured under the runtime's transition lock, and are kept as one volatile reference —
/// never the runtime's live flag next to a list copied by an earlier notification. Sets delivered out of order (two
/// transitions notifying concurrently) are ordered by <see cref="ProjectedMappingSet.Sequence"/>; an older one is ignored.
/// </remarks>
public sealed class DeployedConditionMappings : IProjectedConditionMappings
{
private readonly ProjectedMappingDeploymentRuntime _runtime;
private volatile IReadOnlyList<ProjectedMappingPlacement> _current;
private ProjectedMappingSet _set = null!;
public DeployedConditionMappings(ProjectedMappingDeploymentRuntime runtime)
{
_runtime = runtime ?? throw new ArgumentNullException(nameof(runtime));
_current = runtime.Active;
runtime.Changed += placements => { _current = placements; Changed?.Invoke(); };
ArgumentNullException.ThrowIfNull(runtime);
runtime.SetChanged += OnSetChanged;
// After subscribing: a transition racing the constructor is either in this read or delivered to the handler.
Publish(runtime.Set);
}
public IReadOnlyList<ProjectedMappingPlacement> Current => _current;
private void OnSetChanged(ProjectedMappingSet set)
{
if (Publish(set)) Changed?.Invoke();
}
private bool Publish(ProjectedMappingSet set)
{
while (true)
{
var seen = Volatile.Read(ref _set);
if (seen is not null && seen.Sequence >= set.Sequence) return false;
if (ReferenceEquals(Interlocked.CompareExchange(ref _set, set, seen), seen)) return true;
}
}
public IReadOnlyList<ProjectedMappingPlacement> Current => Volatile.Read(ref _set).Placements;
public event Action? Changed;
/// <inheritdoc />
public bool Suspended => _runtime.Suspended;
public bool Suspended => Volatile.Read(ref _set).Suspended;
/// <inheritdoc />
public (IReadOnlyList<ProjectedMappingPlacement> Current, bool Suspended) Snapshot
{
get { var set = Volatile.Read(ref _set); return (set.Placements, set.Suspended); }
}
}
/// <summary>A3 host limits (§5.5 "Budget").</summary>
@@ -83,6 +115,15 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC
/// <summary>#931 (N4): the ceiling of the exponential reconnect backoff after streams that end before their barrier.</summary>
public TimeSpan MaxReconnectDelay { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>
/// A4 review r2 S2: the longest a connection's conditions are HELD for an undecided deploy (a catalog attempt that
/// began and has not completed). Past it they are released (removed) as if the attempt had settled without the
/// connection. Any completion settles sooner; this bounds an attempt that never completes. The default is 2.5× the
/// deploy apply deadline (<c>DeployTimings.ApplyDeadline</c>, 120 s): an attempt still open by then is not finishing.
/// Before it, the held conditions go <c>BadNoCommunication</c> on the connection's stale timeout, as for any stream gap.
/// </summary>
public TimeSpan MaxHold { get; init; } = TimeSpan.FromMinutes(5);
public static ProjectedConditionOptions Default { get; } =
new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1));
}
@@ -131,7 +172,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
/// set. The connection's next runner takes their materialised set over (same conditions, same EventIds, no re-create);
/// a settled set without the connection releases them (removal). Under <see cref="_gate"/>.
/// </summary>
private readonly Dictionary<string, ConnectionRunner> _held = new(StringComparer.OrdinalIgnoreCase);
/// <remarks>A4 review r2 S2: concurrent (mutated under <see cref="_gate"/> only) so a diagnostics poll reports a held
/// connection as <c>held</c> without taking <c>_gate</c>.</remarks>
private readonly ConcurrentDictionary<string, ConnectionRunner> _held = new(StringComparer.OrdinalIgnoreCase);
private readonly ConditionLedger _ledger;
private int _demand;
private long _mappingVersion = 1;
@@ -163,6 +206,13 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
{
var mappings = _mappings.Current.Where(x => string.Equals(x.Mapping.DataConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)
&& x.Authority.IsActive && IsConditionBearing(x.Mapping)).ToArray();
// A4 review r2 S2: a connection held for an undecided deploy has no current mapping, but its conditions exist and are
// charged — report them as "held" instead of hiding them.
if (!_runners.ContainsKey(connectionId) && _held.TryGetValue(connectionId, out var held))
{
var (_, heldAt, heldCount, heldUnknown, _) = held.Capture();
return new("held", heldAt, heldCount, heldUnknown, [], _ledger.Total, _ledger.ConditionLimit);
}
if (mappings.Length == 0) return null;
// #931 N6 spirit: a diagnostics poll never takes _gate either.
if (!_runners.TryGetValue(connectionId, out var runner))
@@ -277,12 +327,24 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
}
}
/// <summary>A4 review r2 S2: the hold bound — a still-held runner (the same one) is released once <see cref="ProjectedConditionOptions.MaxHold"/> passes.</summary>
private void OnHoldExpired(string connectionId, ConnectionRunner runner)
{
lock (_gate)
{
if (_disposed || !_held.TryGetValue(connectionId, out var held) || !ReferenceEquals(held, runner)) return;
_log.LogWarning("Imported conditions: connection {Connection} held for an undecided deploy longer than {MaxHold}; releasing its conditions",
connectionId, _options.MaxHold);
ReleaseHeld(id => string.Equals(id, connectionId, StringComparison.OrdinalIgnoreCase));
}
}
/// <summary>A4 F1–F3, under _gate: releases (removes the conditions of) the held runners <paramref name="release"/> selects.</summary>
private void ReleaseHeld(Func<string, bool> release)
{
foreach (var id in _held.Keys.Where(release).ToList())
{
_held.Remove(id, out var held);
_held.TryRemove(id, out var held);
held!.ReleaseHeld();
Park(held);
}
@@ -291,19 +353,23 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
private void OnMappingsChanged()
{
Interlocked.Increment(ref _mappingVersion);
Diagnostics.RetainConsumers(_mappings.Current.Select(x => x.Mapping.DataConnectionId).ToHashSet(StringComparer.OrdinalIgnoreCase));
lock (_gate)
{
if (_disposed) return;
ReconcileRunners();
// A4 review r2 S2: a held connection keeps its counters (it is still reported, as "held").
var retained = _mappings.Current.Select(x => x.Mapping.DataConnectionId).ToHashSet(StringComparer.OrdinalIgnoreCase);
retained.UnionWith(_held.Keys);
Diagnostics.RetainConsumers(retained);
}
}
/// <summary>Starts a runner per condition-bearing connection while demand exists; restarts one whose mapping set changed. Under _gate.</summary>
private void ReconcileRunners()
{
var suspended = _mappings.Suspended;
var byConnection = _mappings.Current.Where(x => x.Authority.IsActive && IsConditionBearing(x.Mapping))
// A4 review r2 S1: ONE consistent (placements, suspended) pair — a live flag next to an older list would release.
var (current, suspended) = _mappings.Snapshot;
var byConnection = current.Where(x => x.Authority.IsActive && IsConditionBearing(x.Mapping))
.GroupBy(x => x.Mapping.DataConnectionId, StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.Key, x => OrderMappings(x).ToArray(), StringComparer.OrdinalIgnoreCase);
// A4 F1–F3: only a SETTLED set that no longer has the connection removes its held conditions.
@@ -319,6 +385,8 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
// BadEventIdUnknown, and the removal's RefreshRequired gated away because nothing was visible any more). Hold:
// the next runner of this connection takes the conditions over and re-snapshots onto them.
gone!.Stop(removeConditions: false);
// A4 review r2 S2: bounded — stale on the connection's stale timeout, released past MaxHold.
gone.Hold(_clock.CreateTimer(_ => OnHoldExpired(id, gone), null, _options.MaxHold, Timeout.InfiniteTimeSpan));
_held[id] = gone;
continue;
}
@@ -336,8 +404,11 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
running.Stop(removeConditions: false);
}
// S3/S4: the predecessor (still running or still removing) hands over only after it has fully stopped.
var predecessor = running ?? (_held.Remove(id, out var held) ? held : null) ?? (_stopping.Remove(id, out var stopping) ? stopping : null);
var runner = new ConnectionRunner(this, id, mappings, signature, predecessor);
ConnectionRunner? held = null;
if (running is null && _held.TryRemove(id, out held)) held.EndHold(); // under _gate: no stale mark lands after this
var predecessor = running ?? held ?? (_stopping.Remove(id, out var stopping) ? stopping : null);
// A4 review r2 S3: a runner that takes a HELD set over tells clients to refresh once at its first barrier.
var runner = new ConnectionRunner(this, id, mappings, signature, predecessor, tookOverHeld: held is not null);
_runners[id] = runner;
runner.Start();
}
@@ -410,6 +481,9 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
_linger?.Dispose();
runners = _runners.Values.ToList();
_runners.Clear();
// Review r2 NIT: the held runners are already stopped; end their hold timers and drop them.
foreach (var held in _held.Values) held.EndHold();
_held.Clear();
}
_mappings.Changed -= OnMappingsChanged;
foreach (var runner in runners) runner.Stop(removeConditions: false);
@@ -9,6 +9,13 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed record ProjectedMappingPlacement(RemoteNamespaceMapping Mapping, DataView Parent, DataView Anchor,
NodeScope Scope, IReadOnlyList<string> LocalAncestry, IDataMappedCatalogAuthority Authority);
/// <summary>
/// A4 review r2 S1: one published mapping set — the placements AND whether a catalog attempt is still undecided — as a
/// single immutable value, so a reader never pairs a settled flag with a stale (empty) placement list. <paramref name="Sequence"/>
/// orders sets published by concurrent transitions (a reader keeps the highest).
/// </summary>
public sealed record ProjectedMappingSet(IReadOnlyList<ProjectedMappingPlacement> Placements, bool Suspended, long Sequence);
/// <summary>Owns mapping placements tied to one activated catalog attempt.</summary>
public sealed class ProjectedMappingDeploymentRuntime : IDisposable
{
@@ -17,7 +24,18 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
// the catalog gate across SDK calls or introducing SDK -> transition lock ordering.
internal object TransitionGate { get; } = new();
private bool _suspended;
/// <summary>
/// Browse-anchor retention: set when an attempt begins and cleared only by a SUCCESSFUL activation (an unsuccessful one
/// keeps the old anchors' SDK lifetime so an identical placement can be reauthorized later).
/// </summary>
internal bool Suspended => Volatile.Read(ref _suspended);
/// <summary>
/// A4 review r2 S2: a catalog attempt has begun and not completed — its empty set is "not decided yet". Unlike
/// <see cref="Suspended"/> it clears on ANY completion. Under <see cref="_gate"/>; published in <see cref="ProjectedMappingSet"/>.
/// </summary>
private bool _undecided;
/// <summary>A4 review r2 S1: bumped under <see cref="_gate"/> with every published (placements, suspended) pair.</summary>
private long _setSequence;
private readonly LocalCatalogCoordinator _coordinator;
private readonly RemoteNamespaceResolver _resolver;
private CatalogAttempt? _attempt;
@@ -107,6 +125,23 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
}
}
public event Action<IReadOnlyList<ProjectedMappingPlacement>>? Changed;
/// <summary>
/// A4 review r2 S1: raised after EVERY transition (including a suspend/settle that leaves the placements unchanged)
/// with the placements and the suspended flag captured together under the transition lock.
/// </summary>
public event Action<ProjectedMappingSet>? SetChanged;
/// <summary>A4 review r2 S1: the current published set (placements + suspended, one consistent pair).</summary>
public ProjectedMappingSet Set
{
get
{
lock (_gate)
return new(_active.All(x => x.Authority.IsActive) ? CopyPlacements(_active) : Array.Empty<ProjectedMappingPlacement>(),
_undecided, _setSequence);
}
}
/// <summary>Resolve a mapping only while its original activated authority remains current.</summary>
public bool TryGetConnectionId(string mappingId, out string? connectionId)
{
@@ -187,12 +222,14 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
internal void AttemptBegan(CatalogAttempt attempt)
{
bool changed;
long sequence;
lock (TransitionGate)
lock (_gate)
{
if (_disposed || _attempt is not null && attempt.Epoch <= _attempt.Epoch) return;
_attempt = attempt;
Volatile.Write(ref _suspended, true);
_undecided = true;
Volatile.Write(ref _configuredStamp, new object());
_configuredCapabilities.Clear();
_staged = []; _connections = [];
@@ -201,13 +238,16 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
_byMapping.Clear();
_resolver.ApplyMappings([]);
sequence = ++_setSequence;
}
if (changed) Notify([]);
Notify([], changed, suspended: true, sequence);
}
internal void AttemptCompleted(CatalogAttempt attempt, bool completed)
{
IReadOnlyList<ProjectedMappingPlacement> published;
long sequence;
bool undecided;
lock (TransitionGate)
lock (_gate)
{
@@ -241,11 +281,19 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
}
}
// The browse anchors stay retained after an unsuccessful attempt (an identical placement can be reauthorized).
Volatile.Write(ref _suspended, !success);
// A4 review r2 S2: for imported conditions, a COMPLETED attempt is settled whatever its outcome. A failed, degraded
// (the coordinator did not activate the catalog) or throwing activation publishes the empty set as the DECIDED
// one — the consumer releases the conditions it held for the deploy instead of holding them, invisible and
// charged, until some later good deploy.
_undecided = false;
_byMapping = _active.ToDictionary(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.OrdinalIgnoreCase);
published = CopyPlacements(_active);
sequence = ++_setSequence;
undecided = _undecided;
}
Notify(published);
Notify(published, changed: true, undecided, sequence);
}
private static ProjectedMappingPlacement[] Build(LocalExportCatalog catalog, IReadOnlyList<RemoteNamespaceMapping> mappings,
@@ -287,29 +335,34 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
return placements.ToArray();
}
private void Notify(IReadOnlyList<ProjectedMappingPlacement> placements)
private void Notify(IReadOnlyList<ProjectedMappingPlacement> placements, bool changed, bool suspended, long sequence)
{
var handlers = Changed;
if (handlers is null) return;
foreach (Action<IReadOnlyList<ProjectedMappingPlacement>> handler in handlers.GetInvocationList())
try { handler(CopyPlacements(placements)); } catch (Exception) { }
if (changed && Changed is { } handlers)
foreach (Action<IReadOnlyList<ProjectedMappingPlacement>> handler in handlers.GetInvocationList())
try { handler(CopyPlacements(placements)); } catch (Exception) { }
if (SetChanged is { } sets)
foreach (Action<ProjectedMappingSet> handler in sets.GetInvocationList())
try { handler(new ProjectedMappingSet(CopyPlacements(placements), suspended, sequence)); } catch (Exception) { }
}
public void Dispose()
{
long sequence;
lock (TransitionGate)
lock (_gate)
{
if (_disposed) return;
_disposed = true;
Volatile.Write(ref _suspended, false);
_undecided = false;
Volatile.Write(ref _configuredStamp, new object());
_configuredCapabilities.Clear();
Volatile.Write(ref _active, Array.Empty<ProjectedMappingPlacement>());
_byMapping.Clear();
_resolver.ApplyMappings([]);
_coordinator.DetachProjectedMappings(this);
sequence = ++_setSequence;
}
Notify([]);
Notify([], changed: true, suspended: false, sequence);
}
}
@@ -152,6 +152,75 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
runtime.Active.ShouldBeEmpty();
}
/// <summary>
/// A4 review r2 S2/S4: the production switch behind the consumer's condition hold. The published set (placements +
/// "undecided", one value) is undecided from <c>AttemptBegan</c> until ANY completion — success, an unactivated catalog
/// (a failed or degraded apply: <c>Complete(attempt, false)</c>), or a throwing placement build — while the browse-anchor
/// <c>Suspended</c> flag still clears only on success. <see cref="DeployedConditionMappings"/> follows each transition.
/// </summary>
[Fact, Trait("Phase", "A4")]
public void R2_S4_the_published_set_is_undecided_only_between_AttemptBegan_and_any_completion()
{
var authority = new DataPlaneAuthorityState();
var coordinator = NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2);
using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
var deployed = new DeployedConditionMappings(runtime);
var notified = 0;
deployed.Changed += () => notified++;
var mapping = TestMapping();
mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe;
deployed.Snapshot.Suspended.ShouldBeFalse("no attempt yet");
// Success.
var first = Prepare(coordinator, Artifact());
runtime.Set.Suspended.ShouldBeTrue(); runtime.Suspended.ShouldBeTrue();
EmptySet(deployed, suspended: true); // an AttemptBegan with nothing active still publishes the undecided flag
runtime.Stage(first, [mapping], [TestConnection()]);
coordinator.Complete(first, true).ShouldBeTrue();
runtime.Set.Suspended.ShouldBeFalse(); runtime.Suspended.ShouldBeFalse();
deployed.Snapshot.Suspended.ShouldBeFalse();
deployed.Snapshot.Current.ShouldHaveSingleItem().Mapping.RemoteNamespaceMappingId.ShouldBe("map");
// Began: the placements empty AND undecided, in one value.
var failing = Prepare(coordinator, Artifact());
var (began, beganSuspended) = deployed.Snapshot;
began.ShouldBeEmpty(); beganSuspended.ShouldBeTrue();
// A failed / degraded apply: the coordinator does not activate the catalog. Settled (empty) for conditions; the
// browse anchors stay retained.
runtime.Stage(failing, [mapping], [TestConnection()]);
coordinator.Complete(failing, false).ShouldBeFalse();
runtime.Set.Suspended.ShouldBeFalse("a completed attempt is decided, whatever its outcome");
runtime.Set.Placements.ShouldBeEmpty();
runtime.Suspended.ShouldBeTrue("browse-anchor retention is unchanged: cleared only by a successful activation");
EmptySet(deployed, suspended: false);
// A throwing placement build (an invalid parent) on an activated catalog: settled, empty.
var throwing = Prepare(coordinator, Artifact());
deployed.Snapshot.Suspended.ShouldBeTrue();
var invalid = TestMapping(); invalid.LocalParentId = "missing";
runtime.Stage(throwing, [invalid], [TestConnection()]);
coordinator.Complete(throwing, true).ShouldBeTrue();
runtime.Set.Suspended.ShouldBeFalse(); runtime.Set.Placements.ShouldBeEmpty();
EmptySet(deployed, suspended: false);
// A begun attempt that never completes stays undecided (the consumer bounds that hold itself: MaxHold).
var sequence = runtime.Set.Sequence;
Prepare(coordinator, Artifact());
deployed.Snapshot.Suspended.ShouldBeTrue();
runtime.Set.Sequence.ShouldBeGreaterThan(sequence);
notified.ShouldBe(7, "one notification per transition (began + completed × 3, then began)");
static void EmptySet(DeployedConditionMappings deployed, bool suspended)
{
var (current, undecided) = deployed.Snapshot;
current.ShouldBeEmpty();
undecided.ShouldBe(suspended);
}
}
/// <summary>
/// X0 end to end (plan §4.3): an operation bit no build defines (1 &lt;&lt; 30) on one connection, one export and one mapping
/// flows through the REAL artifact parse, origin catalog compile, mapping stage and consumer runtime. Every other
@@ -258,12 +327,12 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
public Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken) => Task.CompletedTask;
}
private static RemoteNamespaceMapping TestMapping() => new() { RemoteNamespaceMappingId = "map", ClusterId = "cluster",
internal static RemoteNamespaceMapping TestMapping() => new() { RemoteNamespaceMappingId = "map", ClusterId = "cluster",
DataConnectionId = "link", Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
LocalParentKind = "RawFolder", LocalParentId = "folder", BranchName = "Remote", RemoteRootEntityId = "remote-root",
RemoteNamespaceUri = "urn:raw", RemoteIdentifierKind = "string", RemoteIdentifier = "remote-root", AllowedOperations = DataOperations.Browse };
private static DataConnection TestConnection() => new() { DataConnectionId = "link", ClusterId = "cluster", Enabled = true, ExpectedClusterId = "remote-cluster" };
private sealed class MissingProjectionSource : IGrpcDataAdapterConnectionSource
internal static DataConnection TestConnection() => new() { DataConnectionId = "link", ClusterId = "cluster", Enabled = true, ExpectedClusterId = "remote-cluster" };
internal sealed class MissingProjectionSource : IGrpcDataAdapterConnectionSource
{
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) => ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
}
@@ -1213,10 +1282,10 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}
private static LocalCatalogCoordinator NewCoordinator(DataPlaneAuthorityState authority, CatalogActivation activation) =>
internal static LocalCatalogCoordinator NewCoordinator(DataPlaneAuthorityState authority, CatalogActivation activation) =>
new(activation, authority, () => BootIdentity);
private static CatalogAttempt Prepare(LocalCatalogCoordinator coordinator, byte[] bytes)
internal static CatalogAttempt Prepare(LocalCatalogCoordinator coordinator, byte[] bytes)
{
var attempt = coordinator.BeginAttempt(Hash(bytes));
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, Node.Value)).ShouldBeTrue();
@@ -1238,7 +1307,7 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
private static string Hash(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
private static RevisionHash Revision(byte[] bytes) => RevisionHash.Parse(Hash(bytes));
private static byte[] Artifact(bool revoked = false, bool includeDriver = false, bool invalidExport = false, bool includeTag = false)
internal static byte[] Artifact(bool revoked = false, bool includeDriver = false, bool invalidExport = false, bool includeTag = false)
{
var root = JsonNode.Parse("""
{
@@ -887,6 +887,9 @@ public sealed class GrpcDataProjectedConditionAccessTests
// A deploy whose settled set no longer has the connection DOES remove (after the hold).
list.Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
await f.WaitAsync(() => !f.Access.IsRunning(Connection));
// Review r2 NIT: must-arrive control. A removal would run as a continuation of the held runner's stop; the hold's stale
// mark (100 ms stale timeout) is chained AFTER that stop, so once it arrived any removal would already have run.
await f.WaitAsync(() => f.Sink.Stale.Contains(Connection));
f.Sink.Removed.ShouldBeEmpty();
f.Mappings.Suspended = false; f.Mappings.Raise();
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
@@ -907,6 +910,193 @@ public sealed class GrpcDataProjectedConditionAccessTests
f.Access.Diagnostics.HasConsumerCounters(Connection).ShouldBeFalse();
}
// ---------------------------------------------------------------------------------------------------------------------
// A4 review round 2 (a4-review-round2.md): S1–S4 and NITs
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>The real deploy switch: a <see cref="LocalCatalogCoordinator"/> + <see cref="ProjectedMappingDeploymentRuntime"/>
/// publishing one condition-bearing mapping "map" on connection "link".</summary>
private sealed class DeployRig : IDisposable
{
private readonly RemoteNamespaceResolver _resolver;
private readonly byte[] _artifact = GrpcDataCatalogStagingTests.Artifact();
public const string Link = "link";
public LocalCatalogCoordinator Coordinator { get; }
public ProjectedMappingDeploymentRuntime Runtime { get; }
public RemoteNamespaceMapping Mapping { get; } = GrpcDataCatalogStagingTests.TestMapping();
public DeployRig()
{
var authority = new DataPlaneAuthorityState();
Coordinator = GrpcDataCatalogStagingTests.NewCoordinator(authority, new CatalogActivation());
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System);
_resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy),
new BrowseContinuationRegistry(8, TimeProvider.System), new GrpcDataCatalogStagingTests.MissingProjectionSource(), policy, 8, 2);
Runtime = new ProjectedMappingDeploymentRuntime(Coordinator, _resolver);
Mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe;
Complete(Begin(), success: true).ShouldBeTrue();
}
/// <summary>AttemptBegan: the published set goes empty and undecided.</summary>
public CatalogAttempt Begin() => GrpcDataCatalogStagingTests.Prepare(Coordinator, _artifact);
/// <summary>AttemptCompleted; <paramref name="success"/> false = a failed/degraded apply (catalog not activated).</summary>
public bool Complete(CatalogAttempt attempt, bool success)
{
Runtime.Stage(attempt, [Mapping], [GrpcDataCatalogStagingTests.TestConnection()]);
return Coordinator.Complete(attempt, success);
}
public void Dispose() { Runtime.Dispose(); _resolver.Dispose(); }
}
private static async Task<FakeStream> SnapshotAsync(Fixture f, string connection, int barriers, params DataConditionState[] records)
{
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map", records.Length);
stream.SnapshotRecords("map", records);
stream.Complete("map");
await f.WaitAsync(() => f.Access.BarriersCompleted(connection) >= barriers);
return stream;
}
/// <summary>
/// S1: <c>AttemptCompleted</c> clears the undecided flag and THEN notifies. A demand acquired in between (a client
/// creating an event item) used to read the runtime's live flag ("settled") next to the adapter's still-empty copy of
/// the placements, and released — removed — every held condition (F1–F3 again). The window is opened deterministically:
/// a <c>Changed</c> handler registered BEFORE the adapter runs inside it. Also S3: the takeover's first barrier sends
/// exactly one RefreshRequired.
/// </summary>
[Fact]
public async Task R2_S1_a_demand_acquired_between_the_settle_and_its_notification_keeps_the_held_set()
{
using var rig = new DeployRig();
ProjectedConditionAccess? access = null;
IDisposable? windowDemand = null;
var armed = false;
rig.Runtime.Changed += placements =>
{
// Runs after _gate is released and before the adapter has seen this transition.
if (armed && placements.Count > 0) windowDemand = access!.AcquireEventDemand(null);
};
await using var f = new Fixture(new DeployedConditionMappings(rig.Runtime));
access = f.Access;
using var demand = f.Access.AcquireEventDemand(null);
await SnapshotAsync(f, DeployRig.Link, 1, Record(Key("x"), 3));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
f.Sink.RefreshRequired.ShouldBe(0, "a complete first barrier tells nobody to refresh");
var attempt = rig.Begin();
await f.WaitAsync(() => !f.Access.IsRunning(DeployRig.Link));
armed = true;
rig.Complete(attempt, success: true).ShouldBeTrue();
using var _ = windowDemand.ShouldNotBeNull("the window demand ran");
await SnapshotAsync(f, DeployRig.Link, 1, Record(Key("x"), 3)); // the takeover re-snapshot
await f.WaitAsync(() => f.Sink.Applied.Count >= 2); // positive control: the re-snapshot applied
f.Sink.Removed.ShouldBeEmpty("a demand inside the settle window must not release the held set");
f.Sink.Live.ShouldBe([Key("x")]);
await f.WaitAsync(() => f.Sink.RefreshRequired >= 1);
f.Sink.RefreshRequired.ShouldBe(1, "S3: one RefreshRequired at the takeover's first barrier");
}
/// <summary>
/// S2: a deploy that completes UNSUCCESSFULLY (failed or degraded apply ⇒ catalog not activated) settles the set as
/// empty: the held conditions are released at once — not held, invisible and charged, until some later good deploy.
/// </summary>
[Fact]
public async Task R2_S2_an_unsuccessful_deploy_completion_releases_the_held_conditions()
{
using var rig = new DeployRig();
await using var f = new Fixture(new DeployedConditionMappings(rig.Runtime));
using var demand = f.Access.AcquireEventDemand(null);
await SnapshotAsync(f, DeployRig.Link, 1, Record(Key("x"), 3));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
var attempt = rig.Begin();
await f.WaitAsync(() => !f.Access.IsRunning(DeployRig.Link));
f.Access.Diagnostics.CaptureConsumer(DeployRig.Link)!.StreamState.ShouldBe("held");
f.Access.ChargedConditions.ShouldBe(1, "held conditions exist, so they stay charged");
rig.Complete(attempt, success: false).ShouldBeFalse();
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
f.Sink.Live.ShouldBeEmpty();
await f.WaitAsync(() => f.Access.ChargedConditions == 0);
f.Access.Diagnostics.CaptureConsumer(DeployRig.Link).ShouldBeNull();
}
/// <summary>
/// S2: an attempt that never completes is bounded — the held conditions go stale (BadNoCommunication, the stream-gap
/// rule) on the connection's stale timeout, are reported as "held" and stay charged, and are released past MaxHold.
/// </summary>
[Fact]
public async Task R2_S2_a_hold_that_never_settles_goes_stale_then_is_released_past_MaxHold()
{
await using var f = new Fixture(Fixture.DefaultOptions with { MaxHold = TimeSpan.FromMilliseconds(600) }, ("map-a", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
((List<ProjectedMappingPlacement>)f.Mappings.Current).Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
await f.WaitAsync(() => !f.Access.IsRunning(Connection));
var held = f.Access.Diagnostics.CaptureConsumer(Connection)!;
held.StreamState.ShouldBe("held");
held.Materialised.ShouldBe(1);
f.Access.ChargedConditions.ShouldBe(1);
await f.WaitAsync(() => f.Sink.Stale.Contains(Connection)); // stale timeout 100 ms
f.Sink.Removed.ShouldBeEmpty("stale, not removed, before MaxHold");
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
f.Sink.Live.ShouldBeEmpty();
await f.WaitAsync(() => f.Access.ChargedConditions == 0);
f.Access.Diagnostics.CaptureConsumer(Connection).ShouldBeNull();
}
/// <summary>S3: the takeover's RefreshRequired is sent once — a later stream end with a complete re-snapshot sends none.</summary>
[Fact]
public async Task R2_S3_a_runner_taking_over_a_held_set_sends_RefreshRequired_once_at_its_first_barrier()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
var list = (List<ProjectedMappingPlacement>)f.Mappings.Current;
var placements = list.ToList();
list.Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
await f.WaitAsync(() => !f.Access.IsRunning(Connection));
list.AddRange(placements); f.Mappings.Suspended = false; f.Mappings.Raise();
var stream = await f.NextStreamAsync();
stream.Ack();
f.Sink.RefreshRequired.ShouldBe(0, "not before the barrier");
stream.Begin("map-a", 1); stream.SnapshotRecords("map-a", Record(Key("x"), 3)); stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.RefreshRequired == 1);
var applied = f.Sink.Applied.Count;
stream.End(); // a later resync of the same runner: complete barrier ⇒ no RefreshRequired
var next = await f.NextStreamAsync();
next.Ack(); next.Begin("map-a", 1); next.SnapshotRecords("map-a", Record(Key("x"), 3)); next.Complete("map-a");
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 2 && f.Sink.Applied.Count > applied); // must-arrive
f.Sink.RefreshRequired.ShouldBe(1);
f.Sink.Removed.ShouldBeEmpty();
}
/// <summary>Review r2 NIT: demand lingering out WHILE a set is held (the deploy still undecided) releases it.</summary>
[Fact]
public async Task R2_NIT_linger_expiry_while_held_releases_the_held_conditions()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var demand = f.Access.AcquireEventDemand(null);
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
((List<ProjectedMappingPlacement>)f.Mappings.Current).Clear(); f.Mappings.Suspended = true; f.Mappings.Raise();
await f.WaitAsync(() => !f.Access.IsRunning(Connection));
f.Sink.Removed.ShouldBeEmpty();
demand!.Dispose(); // linger 200 ms; the set stays undecided throughout
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
f.Sink.Live.ShouldBeEmpty();
await f.WaitAsync(() => f.Access.ChargedConditions == 0);
}
private sealed class Fixture : IAsyncDisposable
{
internal static readonly DataView DefaultRawPlacement =
@@ -939,6 +1129,15 @@ public sealed class GrpcDataProjectedConditionAccessTests
Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance);
}
/// <summary>A4 review r2: over a real mapping source (e.g. <see cref="DeployedConditionMappings"/>); <see cref="Mappings"/> is unset.</summary>
public Fixture(IProjectedConditionMappings mappings, ProjectedConditionOptions? options = null)
{
Grant(NodePermissions.Browse | NodePermissions.Subscribe);
Mappings = null!;
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
Access = new ProjectedConditionAccess(mappings, Connections, policy, () => Sink, TimeProvider.System, options ?? DefaultOptions, NullLogger.Instance);
}
public void Grant(NodePermissions permissions) =>
_state.Apply("c1", "rev-" + (int)permissions, [_key],
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder,