fix(grpc-data): A4 F1-F3 — a deploy's undecided empty mapping set holds imported conditions instead of removing and re-creating them

Every deploy begins a catalog attempt whose published mapping set is empty
(ProjectedMappingDeploymentRuntime.AttemptBegan → Notify([])). The consumer read
that as 'connection removed': runner Stop(removeConditions: true) tore down every
imported condition, and the post-deploy runner re-created them on fresh nodes —
one phantom event per condition (F2), an origin transition delivered twice (F3),
and every outstanding consumer EventId BadEventIdUnknown with no RefreshRequired
(F1; the removal's RefreshRequired was gated away because nothing was visible).
Root-caused live on a4dbg-1 (consumer applies a fresh-node 'marker null->M' record
right after its own deploy).

IProjectedConditionMappings.Suspended (DeployedConditionMappings → runtime
Suspended): while suspended a dropped connection's runner is stopped WITHOUT
removal and held; the next runner takes its materialised set over and
re-snapshots onto the same nodes (same marker ⇒ no event, EventIds kept). Only a
SETTLED set without the connection (or demand linger) releases the held runner,
which removes its conditions then.

Test: F1_a_deploys_empty_suspended_mapping_set_holds_the_conditions_… (red with
the hold disabled: removal on the suspended set).
This commit is contained in:
Joseph Doherty
2026-11-25 03:08:03 -05:00
parent 688cff5812
commit 1b7c69c6ec
3 changed files with 108 additions and 13 deletions
@@ -341,20 +341,34 @@ public sealed partial class ProjectedConditionAccess
{
// Verification r2 N1: a stopped runner keeps no stream's record sets (it may sit in _stopping until the next demand).
lock (_statusGate) _states = [];
if (!removeConditions) return;
var keys = _materialised.ToArray();
if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys);
_materialised.Clear();
_unknownKeys.Clear();
_lastListed.Clear();
_sourceNames.Clear();
Volatile.Write(ref _materialisedCount, 0);
Volatile.Write(ref _unknownCount, 0);
_owner._ledger.ResetClaims(ConnectionId);
_owner._ledger.SetMaterialised(ConnectionId, 0);
if (removeConditions) RemoveMaterialised();
}, TaskScheduler.Default);
}
/// <summary>
/// A4 F1–F3: a runner stopped WITHOUT removal (held across a deploy) whose connection the settled mapping set no
/// longer has — remove what it still holds, after its stop. <see cref="Stopped"/> then covers the removal too.
/// </summary>
public void ReleaseHeld()
{
var stopped = _stopped;
_stopped = stopped.ContinueWith(_ => RemoveMaterialised(), TaskScheduler.Default);
}
private void RemoveMaterialised()
{
var keys = _materialised.ToArray();
if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys);
_materialised.Clear();
_unknownKeys.Clear();
_lastListed.Clear();
_sourceNames.Clear();
Volatile.Write(ref _materialisedCount, 0);
Volatile.Write(ref _unknownCount, 0);
_owner._ledger.ResetClaims(ConnectionId);
_owner._ledger.SetMaterialised(ConnectionId, 0);
}
private async Task RunAsync(CancellationToken ct)
{
var epoch = 0L;
@@ -20,6 +20,13 @@ public interface IProjectedConditionMappings
/// <summary>Raised after the published placement set changes.</summary>
event Action? Changed;
/// <summary>
/// A4 F1–F3: a catalog attempt (a deploy) is in progress. Its <see cref="Current"/> is an empty set that says "not
/// decided yet", not "every mapping removed" — the conditions of a connection that drops out now are HELD, and
/// removed only if the settled set no longer has that connection.
/// </summary>
bool Suspended => false;
}
/// <summary>The production adapter over <see cref="ProjectedMappingDeploymentRuntime"/>.</summary>
@@ -37,6 +44,8 @@ public sealed class DeployedConditionMappings : IProjectedConditionMappings
public IReadOnlyList<ProjectedMappingPlacement> Current => _current;
public event Action? Changed;
/// <inheritdoc />
public bool Suspended => _runtime.Suspended;
}
/// <summary>A3 host limits (§5.5 "Budget").</summary>
@@ -117,6 +126,12 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
/// <summary>Review r1 S3/S4: a stopped runner's completion (its loop AND its removal) per connection; the next runner of
/// that connection awaits it before opening a stream or taking the materialised set, so the two never overlap.</summary>
private readonly Dictionary<string, ConnectionRunner> _stopping = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// A4 F1–F3: runners stopped WITHOUT removal because their connection dropped out of a suspended (deploying) mapping
/// 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);
private readonly ConditionLedger _ledger;
private int _demand;
private long _mappingVersion = 1;
@@ -258,6 +273,18 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
stopped = _runners.Values.ToList();
_runners.Clear();
foreach (var runner in stopped) { runner.Stop(removeConditions: true); Park(runner); }
ReleaseHeld(_ => true);
}
}
/// <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!.ReleaseHeld();
Park(held);
}
}
@@ -275,13 +302,26 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess
/// <summary>Starts a runner per condition-bearing connection while demand exists; restarts one whose mapping set changed. Under _gate.</summary>
private void ReconcileRunners()
{
if (_demand <= 0) return;
var suspended = _mappings.Suspended;
var byConnection = _mappings.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.
if (!suspended) ReleaseHeld(id => !byConnection.ContainsKey(id) || _demand <= 0);
if (_demand <= 0) return;
foreach (var id in _runners.Keys.Where(id => !byConnection.ContainsKey(id)).ToList())
{
_runners.TryRemove(id, out var gone);
if (suspended)
{
// A4 F1–F3: every deploy begins with an empty, undecided set. Removing here tore down every imported condition
// and re-created it after the deploy (a fresh node ⇒ a phantom event per condition, new EventIds, the old ones
// 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);
_held[id] = gone;
continue;
}
gone!.Stop(removeConditions: true);
Park(gone);
}
@@ -296,7 +336,7 @@ 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 ?? (_stopping.Remove(id, out var stopping) ? stopping : null);
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);
_runners[id] = runner;
runner.Start();
@@ -854,6 +854,45 @@ public sealed class GrpcDataProjectedConditionAccessTests
await g.WaitAsync(() => g.Access.Diagnostics.CaptureConsumer(Connection)!.Resyncs >= 1);
}
/// <summary>
/// A4 F1–F3 (live gate): every deploy begins a catalog attempt whose mapping set is EMPTY until it completes. The consumer
/// used to treat that as "connection removed": every imported condition was removed and re-created after the deploy (a
/// fresh node ⇒ a phantom event per condition, an origin transition delivered twice, new EventIds with the old ones
/// BadEventIdUnknown). The conditions are now held across the attempt and handed to the next runner; only a SETTLED set
/// without the connection removes them.
/// </summary>
[Fact]
public async Task F1_a_deploys_empty_suspended_mapping_set_holds_the_conditions_and_only_a_settled_set_without_the_connection_removes_them()
{
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)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
var placements = f.Mappings.Current.ToList();
var list = (List<ProjectedMappingPlacement>)f.Mappings.Current;
// A deploy: AttemptBegan (empty + suspended) … AttemptCompleted (the same placements, settled).
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();
stream.Begin("map-a", 1);
stream.SnapshotRecords("map-a", Record(Key("x"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 1 && f.Sink.Applied.Count >= 2); // positive control: re-snapshot applied
f.Sink.Removed.ShouldBeEmpty("a deploy's undecided empty set is not a removal");
f.Sink.Live.ShouldBe([Key("x")]);
// 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));
f.Sink.Removed.ShouldBeEmpty();
f.Mappings.Suspended = false; f.Mappings.Raise();
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
f.Sink.Live.ShouldBeEmpty();
}
[Fact]
public async Task R1_NIT_consumer_counters_of_a_removed_connection_are_pruned()
{
@@ -963,6 +1002,8 @@ public sealed class GrpcDataProjectedConditionAccessTests
public IReadOnlyList<ProjectedMappingPlacement> Current { get; } = current;
public event Action? Changed;
public void Raise() => Changed?.Invoke();
/// <summary>A4 F1–F3: a catalog attempt in progress (its Current is the undecided empty set).</summary>
public bool Suspended { get; set; }
}
internal sealed class FakeSink : IProjectedConditionSink