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
@@ -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);