diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 497e1ab39..3ce2dfd88 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -359,14 +359,17 @@ An origin streams its alarm condition state to a peer that negotiated `condition arrive as delta records. The consumer reconnects and takes a complete snapshot of the new catalog. (Corrected in the A2 review, S1. Earlier text here said a deploy's adds/removes arrive as deltas; only a fixture could do that.) - **Priority and overflow.** A control or ack at the head of the stream goes first, then condition frames, then queued - values. Condition production is pull-based: a slow consumer leaves records in the bounded condition-state hub; if the hub - evicts records the item has not read, the item takes a fresh snapshot, and if that happens while its previous snapshot - is still undelivered the stream is `Reset` ("Condition stream overflow; retry later."). + values. Condition production is pull-based: a slow consumer leaves records in the bounded condition-state hub. The item + notices an eviction of records it has not read the next time it reads the hub. If its previous snapshot's last chunk is + still undelivered at that moment, the stream is `Reset` ("Condition stream overflow; retry later."). Otherwise the item + takes a fresh snapshot on the same stream (a new snapshot begin, counted as a resync). Which of the two happens for an + eviction during a long snapshot delivery depends on scheduling. Both are correct and neither loses a change: the consumer + replaces its set with the next complete snapshot, either on a reconnect or by swapping the buffered re-snapshot at + `snapshot_complete` (#928). - **Revocation** (grant, catalog or authority change) ends the stream like a revoked v1 value item; no further condition frame is delivered. - **Limits** (`AddDataConnectionConditions`): `DataExport.MaxConditions` (1000, ≤ 5000) and `RemoteNamespaceMapping.MaxConditions`. - The consumer-side timeouts are under "Limits and defaults" below. Metrics: `otopcua.dataconn.conditions.items`, `…resyncs`, - `…capacity_rejections`. + The consumer-side timeouts are under "Limits and defaults" below. Metrics: see "Diagnostics and troubleshooting". ## Condition forwarding end to end (A1–A3) @@ -406,9 +409,25 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar `ConditionSnapshotTimeoutMilliseconds` has passed. - A mapping that is incomplete at the barrier is `Unavailable`. The others proceed, and clients get `RefreshRequired`. - A mapping that completes late is merged in. - - A mapping still `Unavailable` after the barrier ends the stream after a bounded wait - (`ConditionSnapshotTimeoutMilliseconds` × 1, 2, 4, 8 backoff). - - TODO(A4 #930 reconcile): describe the refused-mapping backoff and the in-stream `ConditionCapacity` recovery as merged. + - An `Unavailable` mapping (item refused, root metadata failed, snapshot timed out) or a `ConditionCapacity` mapping is + **retried on the open stream** (#930). Its root is re-resolved if it never resolved, any item it still holds is removed, + and a new item is added. The stream is not ended for it, so the healthy mappings are never re-snapshotted and their + methods are never answered `BadNoCommunication` because of it. + - Retry delay, per mapping. A **definitive** refusal (`Denied`, `NotFound` or `Unsupported`, for the item or the root + metadata) or `ConditionCapacity` waits `LongRetryDelay` (5 min) × 2ⁿ, capped at 4× (20 min). Any other refusal or a + snapshot timeout waits `ConditionSnapshotTimeoutMilliseconds` × 2ⁿ, capped at 8×. A retry whose snapshot has not + completed by its deadline goes back to `Unavailable` and releases its claim; a late completion is still taken. A + completed snapshot resets the count. While a retry runs the mapping is `Pending` (unknown), so nothing it might list is + removed or marked known-inactive (T2). + - `ConditionCapacity` therefore recovers in-stream: after the origin's listing shrinks (or the limit is raised) the next + retry's snapshot is admitted and swapped in. + - `RefreshRequired` is sent at an incomplete barrier only when its set of incomplete mappings differs from the previous + barrier's. A mapping that stays refused across stream restarts does not cause a refresh storm. A mapping that completes + leaves the set, so a later relapse is announced again. + - A stream that ends before its barrier (every root failing, no Primary) reconnects after `ReconnectDelay` (1 s) × 2ⁿ⁻¹, + capped at `MaxReconnectDelay` (60 s). The count resets when a barrier passes. Repeated ends log at Debug after the first. + `LongRetryDelay`, `ReconnectDelay` and `MaxReconnectDelay` are fixed `ProjectedConditionOptions` defaults, not host + configuration. 6. **Lifetime rule.** The end of a stream means "re-snapshot", never "removed". - During a disconnect, imported conditions keep their last state. After `ConditionStaleTimeoutMilliseconds` their `Quality` becomes `BadNoCommunication`: one event per condition, with Active/Acked unchanged. @@ -544,11 +563,36 @@ when Σ `MaxConditions` × 49 of a consumer node's mappings exceeds `MaxImported ### Diagnostics and troubleshooting -TODO(A4 diagnostics reconcile): list the condition metrics (consumer stream state, snapshot time, condition count vs limit -with the 80 % warning, capacity state, `state_known = false` count, RefreshRequired count, method outcomes) and the -**Data connections** page fields here, with their exact names, once the A4 diagnostics branch merges. Today's metrics: -`otopcua.dataconn.conditions.items`, `…resyncs`, `…capacity_rejections`, `…unsignalled`, `…partition_overflows`, -`…marks_discarded` and `otopcua.dataconn.condition_methods` (tags `method`, `outcome`; origin). +Metrics, on the `ZB.MOM.WW.OtOpcUa` meter, never carry a connection, node, mapping or principal id in a label. The shared +ones carry `side` = origin | consumer, because a node can be both: + +| Instrument | Type | Labels | Meaning | +|---|---|---|---| +| `otopcua.dataconn.conditions.items` | up/down counter `{item}` | `side` | Origin: root-scoped condition items open for peers. Consumer: the items its condition streams hold open (one per acked mapping item). | +| `otopcua.dataconn.conditions.resyncs` | counter `{resync}` | `side` | Origin: an item re-snapshotted after a hub reader reset. Consumer: a condition stream that ended (the next one re-snapshots). | +| `otopcua.dataconn.conditions.capacity_rejections` | counter `{item}` | `side` | Origin: an item snapshot over its `MaxConditions` (or refused by the snapshot memory budget). Consumer: a mapping reset to `ConditionCapacity` (over its `MaxConditions` or the host caps). | +| `otopcua.dataconn.condition_methods` | counter `{call}` | `method`, `outcome` (the `DataWriteState`), `side` | Origin: calls served. Consumer: calls forwarded (a call the local node manager refuses before forwarding is not counted). | +| `otopcua.dataconn.conditions.refresh_required` | counter `{request}` | `side` = consumer | RefreshRequired requests the consumer runtime made: an incomplete barrier with a changed incomplete set, a capacity reset that removed nothing, each removal batch. Not per client item. | +| `otopcua.dataconn.conditions.unsignalled` | counter `{condition}` | — | Origin: native conditions whose initial state was not signalled within the signal timeout. | +| `otopcua.dataconn.conditions.partition_overflows` | counter `{overflow}` | — | Origin: condition-state hub partition overflows. | +| `otopcua.dataconn.conditions.marks_discarded` | counter `{mark}` | — | Origin: deferred condition-known marks discarded after their alarm projection was dropped. | + +The AdminUI **Data connections** page (`/clusters/{id}/data-connections`) shows, per connection on a consumer node, an +"Imported conditions" line. It reads "no condition-bearing mapping (or evidence unavailable)" when there is none, or when the +node is older than A4. Otherwise it shows: + +- `stream` state (idle, connecting, snapshotting or live) and `last snapshot` (UTC, or "none since start"); +- `conditions` materialised, with the `state unknown` count (`state_known = false`); +- `node budget` charged against the host condition limit; +- `RefreshRequired`, `resyncs` and `capacity rejections` counts; +- `methods`, as succeeded / rejected / failed / unknown. Succeeded is DriverConfirmedSuccess, rejected is + RejectedBeforeDispatch, failed is DriverConfirmedFailure, and unknown is AcceptedUnconfirmed or OutcomeUnknown; +- `mappings`, one entry per mapping: id, status, observed count against its `MaxConditions`, and the refusal when refused. + +The line takes the notice style when a mapping is `Unavailable` or `ConditionCapacity`, or when a mapping's count or the node +budget reaches 80 % of its limit ("≥ 80% of MaxConditions" / "≥ 80% of the host caps"). Each node's origin panel adds a +served-conditions segment: `condition items open`, `largest listing` against its limit (with the same 80 % note), `last +snapshot`, `resyncs`, `capacity rejections`, `state unknown (unsignalled)` and `methods served`. Consumer logs (Information unless noted) record each condition stream it opens, each item the origin refuses (Warning, with status and diagnostic), and each snapshot barrier (per-mapping status, record count, whether it timed out). @@ -564,9 +608,9 @@ status and diagnostic), and each snapshot barrier (per-mapping status, record co | Ack answers "OutcomeUnknown" | Check the origin's audit log (`ZB.MOM.WW.OtOpcUa.DataConnections.Audit`) for the operation and watch the condition's events. Never replay blindly. | | All `ConditionId`s changed | `ConditionKeySecret` was rotated or differs between the origin pair members, or the connection was re-created under a new id. | -Open follow-ups: #927 (live-gate the driver-failure ack revert), #928 (an overflow test fails under load), #929 (re-measure -the per-condition memory figures in the plan), #930 (a refused mapping causes a refresh storm; `ConditionCapacity` never -recovers in-stream; A4 work in progress) and #931 (review nits). +Open follow-ups: #927 (live-gate the driver-failure ack revert) and #929 (re-measure the per-condition memory figures in +the plan). #928 (overflow test timing), #930 (refresh storm, in-stream `ConditionCapacity` recovery) and #931 (review nits) +are addressed in A4. ## Feature boundary diff --git a/docs/plans/evidence/grpc-data-ext/A4.md b/docs/plans/evidence/grpc-data-ext/A4.md index 991c1f842..4c831fbc2 100644 --- a/docs/plans/evidence/grpc-data-ext/A4.md +++ b/docs/plans/evidence/grpc-data-ext/A4.md @@ -138,18 +138,73 @@ p99 ≤ 10 ms and no publish delayed > 50 ms: **pass**. In-process, not on docke | `git diff master -- '*Goldens.cs'` | empty | | Configuration.Tests | not touched | -### `GrpcDataConditionStreamTests.Overflow_before_the_snapshot_is_drained_resets_the_stream` — pre-existing, not caused by A4 +## #928 — `Overflow_before_the_snapshot_is_drained_resets_the_stream`: a test asserting one of two legal outcomes (b) -Reproduced on a clean detached worktree of master `91438049`: **fails 2/2 when run alone** (`No DataSubscriptionControl.` after the -10 s read timeout); in this branch also 4/4 alone, and with master's `ConditionItemStream.cs` + `DataSubscriptionSession.Conditions.cs` -swapped in 2/2 alone. It passed in the A4 manifest run and the A2 re-run, failed in the first A2 run and the full Runtime suite here, and A3 recorded one full-suite failure. -So it is an A2 test-timing defect, not an A4 regression, and not called a flake. Likely mechanism (from the code, not yet proven by -instrumentation): the item raises a Reset **control** only when its hub read finds the eviction while the last snapshot chunk is -still undelivered (`_deliveredSnapshot < Snapshots` ⇒ `Overflowed`); if that chunk's delivery is recorded before the item's next -read, the item silently re-snapshots (`ResetSnapshot`) and no control is sent — which the test then waits for in vain. To be filed -with that hypothesis. +**Classification (b): test defect, no product change.** The origin item notices a hub eviction only when it next reads the hub, +which it does not do while it is producing snapshot chunks. At that read it takes one of two paths +(`ConditionItemStream.ReadDeltas`): + +- the previous snapshot's last chunk is still undelivered (`_deliveredSnapshot < Snapshots`) ⇒ `Overflowed` ⇒ the session sends a + stream `Reset` ("Condition stream overflow; retry later."); +- otherwise ⇒ `ResetSnapshot`: a fresh snapshot (new begin) on the same stream, counted as a resync. + +Both are what A2 specified (A2.md "Overflow" item 3: "a hub reader reset ⇒ the item re-snapshots … a reset while the item's previous +snapshot is still undelivered ⇒ stream `Reset`"). Which one an eviction **during** a long delivery gets depends on whether the pump +reads the hub before the session commits the last chunk (`DirectReader.MoveNextAsync` commits before returning the frame, so a +consumer that has caught up commits it first). Neither loses a change. The Reset path makes the consumer reconnect and take a +complete snapshot. The silent path's new snapshot is taken from the source, so it includes every evicted change. The A3 consumer +(`ProjectedConditionAccess.Runner.cs`, the `IsSnapshot && Total` branch and the `SnapshotComplete` swap) buffers any snapshot begin into +a new `ConditionSet`, keeps applying live deltas to both, and at `snapshot_complete` swaps it in as a **full replacement**: old ∪ new +keys are re-merged and a key only the old set listed is removed. So a silent re-snapshot is safe, and the Overflowed rule protects the +snapshot memory lease and back-pressure (no snapshot is taken behind an undelivered one). It is not a correctness signal the consumer +depends on. + +**Evidence (instrumented copy of the test, alone, a4-code):** 3,000 records came in chunks of **51** records, not the 24 × ~125 the +test comment assumed: since A2 review S5 (`20bf9372`) the chunk budget is min(256 KiB, `MaxPendingBytes` = 200,000 in the fixture, +`MaxMessageBytes`), and a record with info estimates ≈ 3.9 KB. Frames #1–#59 were snapshot 1 (`complete` on #59). #60 was a new +begin (`total=3000`), then snapshot 2 was complete at #120, with `Snapshots=2, Resets=1, Overflowed=false` and no Reset control. So the +test waited for a Reset that the legal silent path never sends. The original contract test, with its outcome instrumented, took the +silent path **10/10** alone. + +**Why it "started" failing:** it did not. Neither `ConditionItemStream.cs`, `DataSubscriptionSession.Conditions.cs` nor the test changed +between the A2 merge (`83c7e586`) and master `91438049` (A3 touched only consumer files). At `83c7e586` (detached worktree, built +clean) the test **fails 3/3 alone** but its class (22 tests) passes. It has been order- and JIT-warmth-dependent since S5 made +the snapshot 59 chunks. A2 gated it only inside the class or suite. A3 and A4 add tests and change the scheduling of suite runs, so +full-suite failures became more frequent. + +**Fix (tests only, `GrpcDataConditionStreamTests.cs`):** + +1. `Overflow_before_the_snapshot_is_drained_resets_the_stream` is now **deterministic**. 300 records (begin + 6 chunks) fit the + 16-frame condition queue. The consumer reads nothing after the ack. The test waits until the snapshot is taken and charged + (`ChargedBytes > 0`, so the start cursor precedes the raises), raises 6 times (capacity 2 ⇒ eviction above the cursor), ticks + until `Overflowed`, and then asserts the `Reset` ("overflow") and `Snapshots == 1`. +2. New `An_eviction_during_a_long_snapshot_delivery_resets_or_resnapshots_without_losing_a_change` keeps the 3,000-record race and + asserts the contract for **either** outcome. On Reset ⇒ `Overflowed`, and a reconnected stream's complete snapshot (3,000) holds the + source's final state for the raised condition. On re-snapshot ⇒ begin `total=3000`, only snapshot chunks until `snapshot_complete`, + 3,000 records with the final state, `Resets == 1`, `Snapshots == 2`, `Overflowed == false`, and the stream not ended. Any other + outcome fails. + +**Red/green (mutations of `ConditionItemStream.ReadDeltas`, each restored):** + +| Mutation | Deterministic Overflow test | Contract test | +|---|---|---| +| none | green 10/10 alone | green 10/10 alone (silent path 10/10) | +| M1: Overflowed rule disabled (`false && …`) | **red** (`Condition not reached` — no Reset) | green (silent path, which is legal) | +| M2: eviction swallowed (`_cursors[p] = read.Floor; continue`), Overflowed kept | green (Overflowed still set) | green (took the Reset path) | +| M3: eviction swallowed **and** no Overflowed (a lost change) | **red** | **red** ("Neither a Reset nor a fresh snapshot.") | + +**Gates after the #928 fix + docs reconcile** (tests + docs, and one XML doc comment in `RemoteNamespaceMapping.cs`; no +behaviour change, so OpcUaServer.Tests full and the live smoke were not re-run): + +| Gate | Result | +|---|---| +| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors | +| The two #928 tests alone, 10× | 10/10 green | +| `run-unit-phase.py A2` / `A3` / `A4` | passed (`20261125T050036…`, `20261125T050157…`, `20261125T050252…`) | +| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2068 passed, 3 skipped, 1 failed: `GrpcDataConfiguredDiscoveryWireTests.Two_sdk_cadences_…` (#920), which passed when re-run alone | +| Host.Tests `.DataConnections.` | 207 passed | ## Left over -- File: production L5 count (blocked, above); the `Overflow_before_…` test-timing defect (above). +- File: production L5 count (blocked, above). #928 resolved above (test defect, tests fixed). - Not done here: A01–A08, reviewer approval, the ScadaBridge consumer-impact record, docs (other worktree). diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/RemoteNamespaceMapping.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/RemoteNamespaceMapping.cs index 040471a12..a4e61de58 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/RemoteNamespaceMapping.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/RemoteNamespaceMapping.cs @@ -38,7 +38,7 @@ public sealed class RemoteNamespaceMapping public int MaxConditions { get; set; } = 1000; /// A2: after a disconnect lasting this long, imported conditions report BadNoCommunication. public int ConditionStaleTimeoutMilliseconds { get; set; } = 30000; - /// A2 (used by A2b): ceiling of one remote condition method call (ack/confirm/shelve). + /// A2 (used by A2b): ceiling of one remote condition method call (Acknowledge, AddComment, Confirm; Shelve is not forwarded). public int ConditionMethodTimeoutMilliseconds { get; set; } = 5000; /// A2: how long a condition snapshot may take before the incomplete mapping is Unavailable. public int ConditionSnapshotTimeoutMilliseconds { get; set; } = 30000; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs index 0136008dd..0dbd5cff2 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionStreamTests.cs @@ -106,18 +106,91 @@ public sealed class GrpcDataConditionStreamTests f.StreamOf(stream)!.Resets.ShouldBe(1); } + /// + /// #928: an eviction the item detects while its last snapshot chunk is still undelivered ⇒ stream Reset + /// ("overflow"). Deterministic: the whole snapshot (begin + 6 chunks) fits the 16-frame condition queue, and the + /// consumer reads nothing after the ack, so the last chunk is still queued when the session tick makes the item read + /// the hub. (The former version raced a 3,000-record delivery against the producer — see the contract test below.) + /// [Fact] public async Task Overflow_before_the_snapshot_is_drained_resets_the_stream() { - // 3,000 records = 24 chunks, more than the 16-frame condition queue: the last chunk is produced only after the - // consumer drained most of them, and the item reads the hub right after producing it — still undelivered. + using var f = new ConditionFixture(conditions: 300, maxConditions: 5000, partitionCapacity: 2); + await using var stream = await f.OpenAsync(); + await stream.ReadAckAsync(); // the ack's delivery activates the item; nothing after it is read until the Reset + var item = await WaitForAsync(() => f.StreamOf(stream, allowMissing: true) is { ChargedBytes: > 0 } s ? s : null); + // The snapshot is taken (its start cursor precedes the raises) and charged, so its last chunk is undelivered. + for (var i = 0; i < 6; i++) f.Source.Raise(0, active: i % 2 == 0); // the hub evicts above the item's start cursor + await WaitForAsync(() => { f.Tick(); return item.Overflowed ? item : null; }); // the session tick runs the pump + var reset = await stream.ReadUntilAsync(f, c => c.Kind == DataStreamControlKind.Reset); + reset.Diagnostic.ShouldNotBeNull().ShouldContain("overflow"); + item.Snapshots.ShouldBe(1, "an overflow resets the stream; the item does not re-snapshot behind an undelivered snapshot"); + } + + /// + /// #928 contract: an eviction during a long snapshot delivery that the consumer is draining has TWO legal outcomes, + /// decided by whether the item reads the hub before or after the session commits the snapshot's last chunk — a + /// stream Reset (the consumer reconnects and re-snapshots) or a silent fresh snapshot on the same stream (a new + /// begin; A3 buffers it and swaps at snapshot_complete). Either way no change is lost: the state the consumer + /// ends with matches the source. + /// + [Fact] + public async Task An_eviction_during_a_long_snapshot_delivery_resets_or_resnapshots_without_losing_a_change() + { using var f = new ConditionFixture(conditions: 3000, maxConditions: 5000, partitionCapacity: 2); await using var stream = await f.OpenAsync(); await stream.ReadAckAsync(); (await stream.ReadConditionsAsync(f)).Total.ShouldBe(3000); - for (var i = 0; i < 6; i++) f.Source.Raise(0, active: i % 2 == 0); // the hub evicts above the item's start cursor - var reset = await stream.ReadUntilAsync(f, c => c.Kind == DataStreamControlKind.Reset); - reset.Diagnostic.ShouldNotBeNull().ShouldContain("overflow"); + var item = f.StreamOf(stream)!; + for (var i = 0; i < 6; i++) f.Source.Raise(0, active: i % 2 == 0); // evicts above the item's start cursor + var expected = f.Source.IsActive(0); + while (true) + { + var frame = await stream.NextAsync() ?? throw new InvalidOperationException("Neither a Reset nor a fresh snapshot."); + if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset } reset) + { + reset.Diagnostic.ShouldNotBeNull().ShouldContain("overflow"); + item.Overflowed.ShouldBeTrue(); + await using var fresh = await f.OpenAsync(); // what the consumer does next: reconnect and re-snapshot + var snapshot = await fresh.ReadSnapshotAsync(); + snapshot.Complete.ShouldBeTrue(); + snapshot.Records.Count.ShouldBe(3000); + snapshot.Records.Single(r => r.ConditionKey == f.KeyOf(0)).Active.ShouldBe(expected); + return; + } + if (frame is DataSubscriptionConditions { IsSnapshot: true, Total: { } total }) + { + // The silent path: a hub reader reset after the last chunk was delivered ⇒ a complete fresh snapshot. + total.ShouldBe(3000); + var records = new List(); + var complete = false; + while (!complete) + { + var chunk = await stream.ReadConditionsAsync(f); + chunk.IsSnapshot.ShouldBeTrue("no delta interleaves a snapshot"); + records.AddRange(chunk.Items); + complete = chunk.SnapshotComplete; + } + records.Count.ShouldBe(3000); + records.Single(r => r.ConditionKey == f.KeyOf(0)).Active.ShouldBe(expected); + item.Overflowed.ShouldBeFalse(); + item.Resets.ShouldBe(1); + item.Snapshots.ShouldBe(2); + stream.Ended.ShouldBeFalse("a re-snapshot is not a stream reset"); + return; + } + } + } + + private static async Task WaitForAsync(Func probe) where T : class + { + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); + while (DateTime.UtcNow < deadline) + { + if (probe() is { } value) return value; + await Task.Delay(10, Ct); + } + throw new TimeoutException("Condition not reached."); } [Fact]