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
@@ -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,