Merge #920/#929: a demand disposed mid-publish no longer republishes a fresh baseline (retained proof-candidate leak); SDK async delivery race in test; memory figures re-measured with GC memory info (~79 KB/condition node tree)
v2-ci / unit-tests (push) Waiting to run
v2-ci / unit-tests (push) Waiting to run
This commit is contained in:
@@ -65,7 +65,7 @@ found while verifying M1 (row M1).
|
||||
| N8 G0 deferral consequences | Accepted | Recorded-v1-client gate repeated at H2, A2 and A3 exits; §1.1: #915's soak should run on an X0-or-later build |
|
||||
| **Revision 4 (settled offline)** | | |
|
||||
| B5 interception point | Settled: works | §5.6 step 1 — NM implements `ICallAsyncNodeManager`; SDK 2.0.1 dispatch traced (validation's `FindMethodState` holds `Lock` only for the lookup; per-manager `CallAsync` awaited with `ConfigureAwait(false)`); A3 not blocked |
|
||||
| N5 node count | Settled: 48–49 nodes, ≈ 157 KiB each (was "~21") | §5.5 recomputed: 10,000 / 49 ≈ 204; `MaxConditions` 1,000; host caps 122,500 nodes / 400 MiB |
|
||||
| N5 node count | Settled: 48–49 nodes, ≈ 157 KiB each (was "~21"; the bytes were a `GC.GetTotalMemory` artifact — #929 re-measured ≈ 77 KiB node-only, see §5.5) | §5.5 recomputed: 10,000 / 49 ≈ 204; `MaxConditions` 1,000; host caps 122,500 nodes / 400 MiB |
|
||||
| `state_known` field | Settled: does not exist; named additions (revised in revision 5 by T1/T2) | §5.1: `_conditionStateKnown`, `MarkConditionsKnown`, driver signal / per-driver timer, scripted inputs-established |
|
||||
| Event re-gating, Galaxy keying, build reporting, opc-plc alarms, alarm-tag export | Settled from code/SDK | §5.4, §6, §4.3, A02, §5.2 (+ second pre-existing v1 defect) |
|
||||
| Remaining live items | Listed | §9.3 L1–L5 with pass criteria |
|
||||
@@ -191,7 +191,7 @@ has accepted the call.
|
||||
| Namespaces (N4) | `NM:117-118` `RegisteredNamespaceUris` (Raw, UNS, mapped/raw, mapped/uns); `NM:283-284` `RealmOf` folds every index but 0/2 into Uns | A fifth URI `mapped/conditions` is a registration change; it must be classified before `RealmOf` |
|
||||
| Stable source id (N3) | `SourceSamplePublisher.cs:32-33` (`"<len>:<driverId><RawPath>"`), emitted in `Metadata.stable_source_id` at `LocalExportCatalog.Compilation.cs:92,123` | Not usable as a condition dedupe key (discloses RawPath); pre-existing disclosure on UNS reference variables (#916) |
|
||||
| SDK Call dispatch (B5) | Decompiled SDK 2.0.1: `StandardServer.CallAsync` → `MasterNodeManager.CallAsync` → `NodeManagerServiceDispatcher.CallAsync` (validation via `FindMethodState`, short `lock (Lock)`, then per-manager `IAsyncNodeManager.CallAsync`); `AsyncNodeManagerAdapter.CallAsync` forwards to `ICallAsyncNodeManager` when the wrapped manager implements it; `CustomNodeManager2` (NM's base) implements `INodeManager3` only and its sync `Call`/`GetMethodCalls` skip `Processed` items | NM implements `ICallAsyncNodeManager`; imported-condition calls are claimed and awaited with no `Lock` held (§5.6) |
|
||||
| Condition subtree (N5) | `NM:2461-2475` (optional `ConfirmedState`/`Confirm`/`ShelvingState`/`MaxTimeShelved` before `Create`), `ApplicationAlarmConditions.cs:7-11` (Alarm / OffNormal / Discrete) | Counted with SDK 2.0.1: 48 / 49 / 48 nodes, ≈ 157 KiB retained each (§5.5) |
|
||||
| Condition subtree (N5) | `NM:2461-2475` (optional `ConfirmedState`/`Confirm`/`ShelvingState`/`MaxTimeShelved` before `Create`), `ApplicationAlarmConditions.cs:7-11` (Alarm / OffNormal / Discrete) | Counted with SDK 2.0.1: 48 / 49 / 48 nodes, ≈ 157 KiB retained each (§5.5; corrected by #929 to ≈ 77 KiB node-only) |
|
||||
| Event delivery path (§5.4) | Decompiled SDK 2.0.1 `MonitoredItem.QueueEvent(EventFieldList)` enqueues by reference; `Subscription.ConstructMessage` moves queued lists into `EventNotificationList` by reference; a select-clause modify rebuilds queued lists via `GetEventFields` with `Handle` = the original event; `OtOpcUaSdkServer.cs:746,768` already rewrites every Publish/Republish via `ProjectedNotificationRewriter` (`WarmStandby.cs:917`), which today passes event payloads through untouched | A marked `EventFieldList` subclass survives to Publish/Republish; the rewriter is extended to events |
|
||||
| Native/scripted state signals (N1) | Native `Quality = BadWaitingForInitialData` at materialise (`NM:2527`), driven Good via `WriteAlarmQuality` (`NM:1480`); `RestoreCarryOver` (`NM:2727`); scripted re-assert only for non-normal conditions (`ScriptedAlarmHostActor.cs:491`); scripted cold start re-derives Active from a `ReadTag`-seeded cache (`ScriptedAlarmEngine.cs:440-461`, `StatusNeverPushed` `:58-67`, `WorstInputStatus` `:1325`); existing driver signals: Galaxy `IGalaxyAlarmFeed.InitialSnapshotCompleted` (`:38`), OpcUaClient ConditionRefresh sweep (`OpcUaClientDriver.cs:2552`); `IAlarmSource` implementers: Galaxy, OpcUaClient, MTConnect, FOCAS, AbCip, Heidenhain; SDK `SetActiveState` stamps `TransitionTime = Now` on every call (`NM:1364` calls it per projection) | `_conditionStateKnown` + `MarkConditionsKnown` deltas + driver signal / per-driver timer + inputs-established; origin-owned activation marker (§5.1, §5.6) |
|
||||
| Alarm-bearing tags (N3, §5.2) | `AddressSpaceComposer.cs:978-985` (#896: no UNS value Variable for an alarm-bearing backing tag); `AddressSpaceComposer.cs:835-850` (alarm tags are in `RawTags`); `LocalExportCatalog.Compilation.cs:120-130` (no Alarm filter) | UNS placement address is a reserved reference id with no node; v1 exports alarm-bearing raw tags as dead Variables (pre-existing defect) |
|
||||
@@ -793,23 +793,28 @@ SDK 2.0.1 (scratch harness, §9.3) gives:
|
||||
| `OffNormalAlarmType` | **49** | 2 objects, 39 variables, 8 methods |
|
||||
| `DiscreteAlarmType` | **48** | 2 objects, 38 variables, 8 methods |
|
||||
|
||||
`Quality`, `BranchId` and `Comment` are present. The retained managed size measured **≈ 157 KiB per condition** (160,997 B
|
||||
for `OffNormal`, 2,000 instances, `GC.GetTotalMemory(true)` delta, excluding NM's own indexes). **Memory, not node count, is
|
||||
the binding limit.** The origin already pays the same per condition for its own local copy.
|
||||
`Quality`, `BranchId` and `Comment` are present. The retained managed size of the node tree alone is **≈ 77 KiB per
|
||||
condition** (79,085 B for `OffNormal`, 2,000 instances, retained heap `HeapSizeBytes − FragmentedBytes` after a full blocking
|
||||
GC; ≈ 90 KB of settled working set; excluding NM's own indexes; re-measured for #929, X0 evidence). Revision 4's
|
||||
"≈ 157 KiB (160,997 B)" was a `GC.GetTotalMemory(true)` delta, which on .NET 10 also counts committed-but-free GC regions
|
||||
(the same harness still reports 158,169 B that way) — it was inflated ≈ 2×. The in-server worst case measured by L2
|
||||
(node tree + NM indexes + identifiers + EventId registry + placements + runner records) is **111,715 B heap / 158,629 B working
|
||||
set**, and `BytesPerCondition` = **160,000 B** is set from that (A3 evidence, "L2 worst-case memory"). **Memory, not node
|
||||
count, is the binding limit.** The origin already pays the same node-tree cost per condition for its own local copy.
|
||||
|
||||
Arithmetic:
|
||||
|
||||
- with v1's `MaxProjectionNodes` default of 10,000 (`RemoteNamespaceMapping.cs:29`), 10,000 / 49 ≈ **204** conditions would
|
||||
exhaust a mapping (revision 3's "≈ 476 at 21 nodes" was wrong);
|
||||
- 10,000 imported conditions would retain ≈ 1.5 GiB.
|
||||
- 10,000 imported conditions would retain ≈ 1.5 GiB (at the L2 160,000 B each).
|
||||
|
||||
Defaults (conditions get their **own** budget; worst case is 49 nodes):
|
||||
|
||||
| Setting | Default | Nodes | Memory (≈ 157 KiB each) |
|
||||
| Setting | Default | Nodes | Memory (L2 `BytesPerCondition` 160,000 B each) |
|
||||
|---|---|---|---|
|
||||
| `RemoteNamespaceMapping.MaxConditions` | **1,000** per mapping | 49,000 | ≈ 153 MiB |
|
||||
| `DataConnections:MaxImportedConditionNodes` (host) | **122,500** per consumer node (= 2,500 × 49) | 122,500 | — |
|
||||
| `DataConnections:MaxImportedConditionBytes` (host) | **400 MiB** per consumer node (≈ 2,500 × 157 KiB = 384 MiB, rounded) | — | 400 MiB |
|
||||
| `DataConnections:MaxImportedConditionBytes` (host) | **400,000,000 B** per consumer node (= 2,500 × 160,000 B ≈ 381 MiB) | — | ≈ 381 MiB |
|
||||
|
||||
- Conditions are charged **once per `condition_key`**, not per placement. They do **not** consume `MaxProjectionNodes`, which
|
||||
stays for folders and variables; placement folders charge it as ordinary projected folders.
|
||||
@@ -825,14 +830,16 @@ Defaults (conditions get their **own** budget; worst case is 49 nodes):
|
||||
node's mappings exceeds `MaxImportedConditionNodes`.
|
||||
- Whether 1,000 per mapping / 2,500 per node covers real exports is live measurement L5 (§9.3). The defaults are tunable and
|
||||
sized from the measured memory cost, not from a guessed plant size.
|
||||
- **What the 157 KiB excludes (m-T7):**
|
||||
- **What the node-only figure (≈ 77 KiB; "157 KiB" before #929) excludes (m-T7):**
|
||||
- NM's indexes;
|
||||
- the `c1.<base64url JSON>/<browse path>` identifier strings on 48–49 nodes;
|
||||
- the per-condition EventId registry;
|
||||
- placement sets.
|
||||
|
||||
**L2 is the authority:** `MaxImportedConditionBytes` is set from the L2 measurement (per-condition in-server bytes × 2,500),
|
||||
and the 400 MiB above is a provisional default until L2 passes.
|
||||
**L2 is the authority:** `MaxImportedConditionBytes` is set from the L2 measurement (per-condition in-server bytes × 2,500).
|
||||
L2 passed at the A3 exit: the larger of its heap and settled-working-set figures, max of three runs, rounded up, is
|
||||
160,000 B, so the default is 400,000,000 B. The ≈ 40 KiB gap between the node-only heap (≈ 77 KiB) and L2's heap
|
||||
(≈ 109 KiB) is the excluded state above plus the worst-case placements, EventId slots and event-queue entries.
|
||||
|
||||
**Stream mechanics.**
|
||||
|
||||
@@ -1420,7 +1427,7 @@ Use two-state id selection via `SimpleAttributeOperand(type, [X, Id])`, as the C
|
||||
| Acks fail on busy alarms because the precondition moves | A2 | Origin-owned activation marker, bumped only on a new occurrence (T3) |
|
||||
| RawPath disclosure to UNS-only principals | A1 | Realm-local placements; keyed `condition_key`; property test; pre-existing `stable_source_id` disclosure is #916 |
|
||||
| Imported-condition method path regresses local methods | A3 | Claimed items only (`Processed`), `base.Call` unchanged for the rest; lock-freedom gate; existing `ConditionMethodEventTests` stay green |
|
||||
| Imported-condition memory (≈ 157 KiB each) | A3 | Own budget sized from the counted cost; byte cap 400 MiB per consumer node; L2 confirms in-server |
|
||||
| Imported-condition memory (≈ 77 KiB node-only, 160,000 B in-server worst case) | A3 | Own budget sized from the counted cost; byte cap 400,000,000 B (≈ 381 MiB) per consumer node; L2 confirmed in-server |
|
||||
| v1 unsoaked in service (G0 deferred, #915) | all | Per-phase live gates; deploy notes record the risk until #915 passes |
|
||||
|
||||
### 9.3 Settled offline vs. needs a live run
|
||||
@@ -1428,7 +1435,7 @@ Use two-state id selection via `SimpleAttributeOperand(type, [X, Id])`, as the C
|
||||
**Settled offline in revision 4** (no server needed):
|
||||
- the SDK 2.0.1 Call dispatch trace (decompiled with `ilspycmd` from the pinned package);
|
||||
- the event-delivery path;
|
||||
- condition node counts (48/49/48) and retained bytes (≈ 157 KiB);
|
||||
- condition node counts (48/49/48) and retained bytes (≈ 157 KiB in revision 4; ≈ 77 KiB after the #929 re-measure);
|
||||
- snapshot-copy cost (≈ 1.7–2.9 µs per condition);
|
||||
- the Galaxy ack-identity keying;
|
||||
- the absence of node build reporting;
|
||||
@@ -1436,8 +1443,10 @@ Use two-state id selection via `SimpleAttributeOperand(type, [X, Id])`, as the C
|
||||
- alarm-bearing tag export shape (#896).
|
||||
|
||||
The counts, bytes and copy timing come from a scratch harness: a console project referencing `OPCFoundation.NetStandard.Opc.Ua.Server`
|
||||
2.0.1 that builds each condition type with NM's optional children, walks `GetChildren`, measures a `GC.GetTotalMemory(true)`
|
||||
delta over 2,000 instances, and times the snapshot field copy. It is not in the repo; X0 task 4 commits it as evidence.
|
||||
2.0.1 that builds each condition type with NM's optional children, walks `GetChildren`, measures the retained heap over
|
||||
2,000 instances, and times the snapshot field copy. X0 task 4 committed it as evidence (`docs/plans/evidence/grpc-data-ext/harness/`).
|
||||
It first measured a `GC.GetTotalMemory(true)` delta; #929 switched it to the L2 method (full blocking GC,
|
||||
`HeapSizeBytes − FragmentedBytes`, settled working set) and the figure halved.
|
||||
|
||||
**Live measurements** — each runs on docker-dev unless stated, and each has a pass criterion:
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# #920 — `GrpcDataConfiguredDiscoveryWireTests` flake: root causes
|
||||
|
||||
2026-11-28. Two unrelated causes, one in production and one in a test. Neither is a timeout, and nothing was widened or
|
||||
skipped.
|
||||
|
||||
## 1. `Failed_sdk_item_construction_releases_candidate_and_fanout_ownership` — production race (fixed)
|
||||
|
||||
**Symptom.** The node manager's shared `ProjectedCandidateBudget` held 1 entry, expected 0.
|
||||
|
||||
**Cause.** Trace instrumentation (temporary, removed) showed that the extra entry was not the failed item's. It was a
|
||||
proof candidate on the *existing* item 1, for the acquisition it had already delivered (`v=1 complete=True`, same proof).
|
||||
The sequence:
|
||||
|
||||
1. Item 2's `CreateMonitoredItems` acquires a demand. Its stream registration gets the fake origin's snapshot, which
|
||||
repeats item 1's acquisition (same version, still fresh).
|
||||
2. The test's injected proof throws, so construction fails. The catch disposes the demand on the SDK thread.
|
||||
3. That disposal raced the stream pump's `Publish` for the registration. The pump had passed the top check
|
||||
(`!registration.Demand.IsValid`). The duplicate-baseline check `HasFreshCachedLocked(registration.Demand)` then read the
|
||||
dying demand's `IsValid == false` as "the cache is not fresh". The trace shows `Publish v=1 complete=True last=1
|
||||
fresh=False`.
|
||||
4. So the same acquisition was published again as a new complete baseline to every item on the node. Item 1 kept a
|
||||
candidate that no SDK notification will ever consume, because the node's value did not change. The candidate also
|
||||
kept its shared budget charge.
|
||||
|
||||
In production this applies to any subscription whose demand is disposed while its snapshot is being published: a failed
|
||||
item construction, a client deleting an item, or a session closing. Each such event re-baselines every other item on
|
||||
the node and leaves one orphan candidate on each, until that item's binding changes.
|
||||
|
||||
**Fix** (`ProjectedDataAccess`):
|
||||
|
||||
- `HasFreshCachedLocked` no longer depends on the demand's validity. Whether the cached acquisition is fresh does not
|
||||
depend on it.
|
||||
- After the duplicate check, `Publish` re-checks the demand. A demand disposed since the top check publishes nothing
|
||||
(`PublishDemand`).
|
||||
- `AfterPublishDemandCheckForTests` is an internal seam on the pump.
|
||||
|
||||
**Regression test.** `A_demand_disposed_mid_publish_does_not_republish_a_fresh_baseline`:
|
||||
|
||||
- It disposes the second item's demand at the seam.
|
||||
- Its positive control is a third item whose snapshot carries a new acquisition (v2) through the same in-order publisher.
|
||||
- It asserts that no v1 baseline arrived before v2, and that item 1 holds exactly one candidate.
|
||||
- **Red** with the two production lines reverted: `seen.Count(x => x.SourceVersion == 1) should be 0 but was 1`.
|
||||
- **Green** with the fix.
|
||||
|
||||
## 2. `Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence("different_timestamp")` — test race (fixed)
|
||||
|
||||
**Symptom.** `BadNoCommunication` was delivered where `BadUserAccessDenied` was expected.
|
||||
|
||||
**Cause.** SDK 2.0.1 delivers a node change to its items asynchronously, from `MonitoredNode2.ProcessChannelAsync`. A
|
||||
`QueueValue` stack trace confirmed this. Under load, the change for the sample the test had just published reached the
|
||||
item *after* the test's `Disabled → Reporting` cycle and after its injected notification. At queue size 1 it overwrote
|
||||
the injected notification (source timestamp T+1). The proven sample (T) that took its place correctly matched its
|
||||
candidate and was correctly delivered.
|
||||
|
||||
So the production fence held, and the test's assumption that delivery is synchronous was wrong. The `different_status`
|
||||
case already tolerates this ordering.
|
||||
|
||||
**Fix.** Before the mode cycle, the test waits until the SDK has queued the published sample. It checks the item's
|
||||
`m_lastValue` for source timestamp T and `BadNoCommunication`, with a 10 s bounded wait that fails with a message.
|
||||
|
||||
The other scenarios were already robust:
|
||||
|
||||
- `ambiguous` and `missing_timestamp`: a late second sample is ambiguous against both candidates, so it is denied anyway.
|
||||
- `expired_proof`: the proof is invalid, so the notification is denied anyway.
|
||||
|
||||
## Numbers (macOS, Release, shared host, load average 25–100 from parallel agents)
|
||||
|
||||
| | Before | After |
|
||||
|---|---|---|
|
||||
| Class runs (`--filter FullyQualifiedName~GrpcDataConfiguredDiscoveryWireTests`) | **5 / 16 failed** (4 × failed-construction, 1 × different_timestamp) | **30 / 30 consecutive passed** (111 tests each, incl. the new one) |
|
||||
| `different_timestamp` stressed in-process (100 ×) | 16 / 100, 6 / 40 | 0 / 100 |
|
||||
| failed-construction stressed in-process | 2 / 150 | 0 / 100 |
|
||||
| New regression test (25 ×) | red, deterministic | 0 / 25 |
|
||||
|
||||
Other gates at `4cf06261`: `dotnet build ZB.MOM.WW.OtOpcUa.slnx -c Release` 0 warnings / 0 errors; Runtime.Tests (rest of the
|
||||
suite, `Category!=E2E&Category!=LiveIntegration`) 1982 passed, 3 skipped; Host.Tests `.DataConnections.` (incl. the v1
|
||||
compatibility gate) 207 passed.
|
||||
@@ -300,6 +300,8 @@ regions at baseline). Per the plan, `MaxImportedConditionBytes` is now set from
|
||||
**205,665** (the managed-heap figure, the larger of the two) and the default `DataConnections:MaxImportedConditionBytes` =
|
||||
205,665 × 2,500 = **514,162,500 B (≈ 490 MiB)** (was 400 MiB). `MaxConditions` (1,000 per mapping) needs no lowering.
|
||||
Nearly all of it is the SDK condition node + children (X0's node-only figure was 160,997); the A3b EventId registry adds ~1 KB.
|
||||
(Superseded: these figures and X0's were `GC.GetTotalMemory` deltas — see round 2's L2 below and #929, which re-measured the
|
||||
node-only retained heap at 79,085 B.)
|
||||
|
||||
## Live — run `a3b-cond-3` (build `82ecc116`, clean tree) — PASS
|
||||
|
||||
@@ -658,7 +660,7 @@ Worst case (2 placements per condition, all 8 EventId slots filled, 3 event item
|
||||
**L2: PASS** (both ≤ 200 MiB in every run). `BytesPerCondition` = the larger of the two per-condition figures, max of three runs,
|
||||
rounded up: 158,629 → **160,000** (was 230,000); `MaxImportedConditionBytes` default = 160,000 × 2,500 = **400,000,000 B
|
||||
(≈ 381 MiB)** (was ≈ 548 MiB). The X0 node-only figure (160,997) and A3b's 197.4 MiB were taken with `GetTotalMemory` too and are
|
||||
likely inflated the same way (not re-measured here).
|
||||
likely inflated the same way (not re-measured here; #929 re-measured X0: 79,085 B node-only heap, X0 evidence).
|
||||
|
||||
## Gates (round 2, at `b884db5f`)
|
||||
|
||||
@@ -693,7 +695,8 @@ Active/Acknowledged; `passed: true`. Teardown: no run-labelled containers or net
|
||||
|
||||
- File: the `GrpcDataConditionStreamTests.Overflow_before_the_snapshot_is_drained_resets_the_stream` load sensitivity (above).
|
||||
- The plan's L2 / X0 figures (≈ 157–161 KiB per condition node, §5.5 table) came from `GC.GetTotalMemory` and are likely
|
||||
inflated by the same region accounting; the plan's §5.5 table was not edited (evidence only).
|
||||
inflated by the same region accounting; the plan's §5.5 table was not edited (evidence only). Done in #929: the X0 harness
|
||||
now uses the L2 method (79,085 B node-only heap vs 158,169 B by `GetTotalMemory`), and §5.5 cites L2's 160,000 B.
|
||||
|
||||
# A3 — Verification review round 2
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ The sources were the code at `91438049` and the evidence logs X0–A3. The plan
|
||||
| # | Plan says | Code does (evidence) |
|
||||
|---|---|---|
|
||||
| D1 | §5.6 step 2(c): one per-node semaphore (default 8) bounds remote method calls. | 8 per node **and** 4 per connection inside them. A dispatch with < 250 ms of budget left is `BadTimeout`, unsent (`ImportedConditionMethods.cs:63-79`, `:247`, `:270`; A3b review S4). |
|
||||
| D2 | §5.5 / §6: `MaxImportedConditionBytes` 400 MiB, ≈ 157 KiB (160,997 B) per condition. | `BytesPerCondition` = 160,000. The default is 400,000,000 B ≈ 381 MiB (`ProjectedConditionAccess.cs:58-61`, `DataConnectionOptions.cs:25`; A3 round-2 L2 measured the retained heap, not `GC.GetTotalMemory`). #929 re-measures the plan's figures. |
|
||||
| D2 | §5.5 / §6: `MaxImportedConditionBytes` 400 MiB, ≈ 157 KiB (160,997 B) per condition. | `BytesPerCondition` = 160,000. The default is 400,000,000 B ≈ 381 MiB (`ProjectedConditionAccess.cs:58-61`, `DataConnectionOptions.cs:25`; A3 round-2 L2 measured the retained heap, not `GC.GetTotalMemory`). #929 re-measured the plan's figures: node-only 79,085 B heap (X0 harness, now on the L2 method); §5.5 corrected, default unchanged. |
|
||||
| D3 | §6 metrics list `…conditions.refresh_required`. | Not present (`OtOpcUaTelemetry.cs:233-265` has `unsignalled`, `partition_overflows`, `items`, `resyncs`, `capacity_rejections`, `condition_methods`, `marks_discarded`). A4 diagnostics work; TODO 2. |
|
||||
| D4 | §5.4/§5.5: demand per connection the caller could see. | Demand is node-wide: the first admitted event item opens every condition-bearing connection, and the per-event gate still decides visibility (A3a deviation 2). |
|
||||
| D5 | §6: local visibility uses "the Subscribe grant on the `RemoteNamespaceMapping` scope". | `Subscribe` on the **placement folder's** scope, within a current mapping of the placement's realm that grants `AlarmSubscribe`, not `AlarmRead` (`ProjectedConditionAccess.cs:170-190`; A3 Runtime gate tests). Narrower than the mapping scope, and consistent with it. |
|
||||
|
||||
@@ -51,8 +51,16 @@ optional children NM adds before `Create()`: `ConfirmedState`, `Confirm`, `Shelv
|
||||
|
||||
`Quality`, `BranchId` and `Comment` are present.
|
||||
|
||||
Retained size is ≈ 157 KiB per condition (160,997 B). It was measured on 2,000 `OffNormal` instances as a
|
||||
`GC.GetTotalMemory(true)` delta.
|
||||
Retained size is ≈ 77 KiB per condition: **79,085 B** managed heap, ≈ 90 KB settled working set (re-measured 2026-11-28 for
|
||||
#929, three runs: heap 79,085 / 79,085 / 79,085 B, working set 90,284 / 90,144 / 90,038 B). It is measured on 2,000
|
||||
`OffNormal` instances as the change in `HeapSizeBytes − FragmentedBytes` of the last full blocking GC (after forced
|
||||
compacting collections), with the working set sampled until it settles — the same `Measure()` as the L2 harness.
|
||||
|
||||
- **Correction (#929).** X0 originally reported ≈ 157 KiB (160,997 B), a `GC.GetTotalMemory(true)` delta. On .NET 10 (GC
|
||||
regions) that call also counts committed-but-free region space (A3 round 2 showed +92 vs +218 MiB for the same state); the
|
||||
harness still logs it for comparison and it reads 158,169 B, i.e. ≈ 2× the retained heap.
|
||||
- `BytesPerCondition` (160,000 B) is unaffected: it comes from the L2 in-server worst case (111,715 B heap / 158,629 B
|
||||
working set, A3 round 2), which already used this method. Node-only ≈ 77 KiB of L2's ≈ 109 KiB heap is the SDK node tree.
|
||||
|
||||
- It excludes NM's indexes, the `c1.` identifier strings, the EventId registry and placement sets (m-T7).
|
||||
- L2 (A3 exit) is the authority for `MaxImportedConditionBytes`.
|
||||
|
||||
@@ -18,18 +18,33 @@ static class P {
|
||||
int total = Count(ctx, alarm, kinds);
|
||||
Console.WriteLine($"{name}: total={total} ({string.Join(", ", kinds.Select(k => k.Key + "=" + k.Value))}); Quality={(alarm.Quality!=null)} BranchId={(alarm.BranchId!=null)} Comment={(alarm.Comment!=null)}");
|
||||
}
|
||||
// #929: GC.GetTotalMemory counts committed-but-free regions on .NET 10. Use the last full blocking GC's
|
||||
// HeapSizeBytes - FragmentedBytes plus a settled working set: the same method as the L2 harness's Measure()
|
||||
// (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionMemoryMeasurementTests.cs).
|
||||
static (long Heap, long WorkingSet) Measure() {
|
||||
for (int i = 0; i < 3; i++) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true); GC.WaitForPendingFinalizers(); }
|
||||
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
|
||||
var info = GC.GetGCMemoryInfo(GCKind.FullBlocking);
|
||||
using var p = System.Diagnostics.Process.GetCurrentProcess(); p.Refresh(); long ws = p.WorkingSet64;
|
||||
var settle = System.Diagnostics.Stopwatch.StartNew();
|
||||
while (settle.Elapsed < TimeSpan.FromSeconds(10)) {
|
||||
Thread.Sleep(500); p.Refresh(); long next = p.WorkingSet64; bool stable = Math.Abs(next - ws) < 1024 * 1024; ws = next; if (stable) break; }
|
||||
return (info.HeapSizeBytes - info.FragmentedBytes, ws);
|
||||
}
|
||||
static void Main() {
|
||||
var ctx = new SystemContext((ITelemetryContext)null) { NodeIdFactory = new Ids(), NamespaceUris = new NamespaceTable() };
|
||||
ctx.NamespaceUris.Append("urn:a"); ctx.NamespaceUris.Append("urn:b");
|
||||
Run("AlarmConditionState", p => new AlarmConditionState(p), ctx);
|
||||
Run("OffNormalAlarmState", p => new OffNormalAlarmState(p), ctx);
|
||||
Run("DiscreteAlarmState", p => new DiscreteAlarmState(p), ctx);
|
||||
var keep = new List<object>(); long before = GC.GetTotalMemory(true);
|
||||
var keep = new List<object>(); var (heap0, ws0) = Measure(); long before = GC.GetTotalMemory(true);
|
||||
for (int i = 0; i < 2000; i++) { var parent = new FolderState(null); var a = new OffNormalAlarmState(parent);
|
||||
a.ConfirmedState = new TwoStateVariableState(a); a.Confirm = new AddCommentMethodState(a); a.ShelvingState = new ShelvedStateMachineState(a);
|
||||
a.MaxTimeShelved = new PropertyState<double>.Implementation<VariantBuilder>(a);
|
||||
a.Create(ctx, new NodeId("c"+i, 2), new QualifiedName("c"+i, 2), new LocalizedText("c"+i), true); keep.Add(a); }
|
||||
long after = GC.GetTotalMemory(true); Console.WriteLine($"retained bytes/condition (2000, OffNormal, no address-space indexes): {(after-before)/2000}"); GC.KeepAlive(keep);
|
||||
var (heap1, ws1) = Measure(); long after = GC.GetTotalMemory(true);
|
||||
Console.WriteLine($"retained bytes/condition (2000, OffNormal, no address-space indexes): heap {(heap1-heap0)/2000} (GCMemoryInfo), " +
|
||||
$"working set {(ws1-ws0)/2000} (settled); GC.GetTotalMemory delta {(after-before)/2000} (not used, #929)"); GC.KeepAlive(keep);
|
||||
var conds = keep.Cast<OffNormalAlarmState>().ToArray(); var recs = new object[conds.Length];
|
||||
for (int w = 0; w < 3; w++) { var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
for (int i = 0; i < conds.Length; i++) { var c = conds[i]; recs[i] = (c.NodeId, c.ActiveState?.Id?.Value, c.AckedState?.Id?.Value, c.ConfirmedState?.Id?.Value,
|
||||
|
||||
@@ -93,7 +93,7 @@ public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedC
|
||||
/// <summary>
|
||||
/// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a
|
||||
/// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's
|
||||
/// node-only harness measured 160,997). A3b review S5: the WORST case — two placements, every EventId slot, three
|
||||
/// node-only harness retains 79,085 B on the same method, #929 — its original 160,997 was a <c>GC.GetTotalMemory</c> delta). A3b review S5: the WORST case — two placements, every EventId slot, three
|
||||
/// event items, the runner's Live + Buffer records. A3 review round 2: measured with the retained heap
|
||||
/// (<c>GCMemoryInfo</c>, not <c>GC.GetTotalMemory</c>, which counted ~125 MiB of committed-but-free regions) and the
|
||||
/// settled working set, 8 EventId slots (§5.6): max of three runs = 158,629 B (working set; heap 111,715 B), rounded up.
|
||||
|
||||
@@ -19,6 +19,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
public TimeProvider Clock { get; }
|
||||
internal Func<TimeSpan, TimeSpan>? RetryJitterForTests { get; set; }
|
||||
internal Action? BeforeSuccessorAdoptionForTests { get; set; }
|
||||
/// <summary>#920: runs on the stream pump after a publish passed its demand check, before the duplicate-baseline check.</summary>
|
||||
internal Action<IProjectedDemandLease>? AfterPublishDemandCheckForTests { get; set; }
|
||||
private readonly IFederatedProjectionCatalog _catalog;
|
||||
private readonly IProjectedNodeLookup _nodes;
|
||||
private readonly Func<string, string?> _connectionForMapping;
|
||||
@@ -685,7 +687,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
internal bool HasFreshCachedLocked(Demand demand)
|
||||
{
|
||||
var sample = _cachedSample;
|
||||
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !demand.IsValid || !IsValid) return false;
|
||||
// #920: deliberately NOT gated on demand.IsValid. This answers "is the sample already published for this version
|
||||
// still fresh at this demand's age limit" — the duplicate-baseline suppression in Publish. A demand disposed
|
||||
// concurrently (a failed SDK item construction) used to turn the answer into "not fresh", so a dying
|
||||
// registration re-published the same acquisition as a new complete baseline to every item on the node.
|
||||
if (sample is null || _cachedVersion != LastVersion || !sample.SourceProof.IsValid || !IsValid) return false;
|
||||
try
|
||||
{
|
||||
return sample.OriginAgeBounds.Advance(_owner.Clock.GetElapsedTime(sample.ReceivedTimestamp,
|
||||
@@ -1775,6 +1781,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
{
|
||||
validated = false;
|
||||
if (registration.Removed || !registration.Demand.IsValid || update.SourceProof is not AttemptProof proof) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
|
||||
_owner.AfterPublishDemandCheckForTests?.Invoke(registration.Demand);
|
||||
var source = proof.Source;
|
||||
if (!source.TryPrepareSuccessor(registration.Demand, out var successor)) return false;
|
||||
try
|
||||
@@ -1792,6 +1799,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
validated = update.IsCompleteSnapshot;
|
||||
if (version == source.LastVersion && update.IsCompleteSnapshot && !registration.Recovery &&
|
||||
source.HasFreshCachedLocked(registration.Demand)) return false;
|
||||
// A demand disposed since the check above publishes nothing (it is no longer anyone's subscription).
|
||||
if (!registration.Demand.IsValid) { validated = false; ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.PublishDemand); return false; }
|
||||
if (_owner._publisher.TryPublish([update]))
|
||||
{
|
||||
if (successor is not null)
|
||||
|
||||
+15
@@ -56,6 +56,21 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
||||
var candidates = (System.Collections.IEnumerable)item.GetType().GetField("_candidates", flags)!.GetValue(item)!;
|
||||
candidates.Cast<object>().Count().ShouldBe(scenario is "ambiguous" or "missing_timestamp" ? 2 : 1);
|
||||
// #920: SDK 2.0.1 delivers a node change to its items asynchronously (MonitoredNode2's channel), so the
|
||||
// sample published above can reach this item AFTER the mode cycle below — and, at queue size 1, overwrite
|
||||
// the injected notification with the genuinely proven sample. Wait until the SDK has queued it, so the
|
||||
// mode cycle discards it and the injected notification is the one delivered. (With two publishes the
|
||||
// second may still be in flight; it is ambiguous against both candidates and denied either way.)
|
||||
var lastValue = typeof(Opc.Ua.Server.MonitoredItem).GetField("m_lastValue", flags).ShouldNotBeNull();
|
||||
var delivered = System.Diagnostics.Stopwatch.StartNew();
|
||||
// The baseline sample shares the fake clock's timestamp, so match the status too.
|
||||
static bool IsPublishedSample(Opc.Ua.DataValue value, DateTime at) =>
|
||||
value.SourceTimestamp == (DateTimeUtc)at && value.StatusCode == StatusCodes.BadNoCommunication;
|
||||
while (!IsPublishedSample((Opc.Ua.DataValue)lastValue.GetValue(item)!, timestamp))
|
||||
{
|
||||
delivered.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10), "the SDK never queued the published sample");
|
||||
await Task.Delay(10, ct);
|
||||
}
|
||||
item.SetMonitoringMode(MonitoringMode.Disabled);
|
||||
if (scenario == "different_status")
|
||||
{
|
||||
|
||||
+69
@@ -111,6 +111,75 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #920: a subscription demand disposed while its stream pump is publishing the snapshot it asked for (a failed
|
||||
/// SDK item construction disposes it on the SDK thread) must not re-publish the already-published, still-fresh
|
||||
/// acquisition as a new complete baseline. It did: the duplicate-baseline check read the dying demand's validity
|
||||
/// as "the cache is not fresh", so the same acquisition reached every existing item on the node again and left an
|
||||
/// orphan proof candidate (and its shared budget charge) on each — no SDK notification ever consumes it, because
|
||||
/// the node's value did not change.
|
||||
/// </summary>
|
||||
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
||||
public async Task A_demand_disposed_mid_publish_does_not_republish_a_fresh_baseline()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
LocalDataFixture? peer = null;
|
||||
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
||||
peer = origin; subscriptions.SampleClock = origin.Clock;
|
||||
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
||||
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, access, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
IProjectedDemandLease? first = null;
|
||||
var armed = 0;
|
||||
var disposed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
access.AfterPublishDemandCheckForTests = demand =>
|
||||
{
|
||||
first ??= demand;
|
||||
if (ReferenceEquals(demand, first) || Interlocked.Exchange(ref armed, 0) != 1) return;
|
||||
demand.Dispose();
|
||||
disposed.TrySetResult();
|
||||
};
|
||||
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
||||
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
||||
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
(await NextPublished(published.Reader, x => x.IsCompleteSnapshot && x.SourceVersion == 1, ct)).Snapshot.Value.ShouldBe(7);
|
||||
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
||||
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
||||
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
||||
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
||||
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
||||
var existing = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
||||
int Candidates() => ((System.Collections.IEnumerable)existing.GetType().GetField("_candidates", flags)!.GetValue(existing)!).Cast<object>().Count();
|
||||
Candidates().ShouldBe(0, "the delivered baseline consumed its candidate");
|
||||
|
||||
// A second item on the same node: its stream snapshot repeats the same (still fresh) acquisition, and its
|
||||
// demand is disposed on the pump right after the publish passed its demand check.
|
||||
Volatile.Write(ref armed, 1);
|
||||
await AddComposedItem(client, sub, anchor, 2, 100, ct);
|
||||
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
await disposed.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
// The pump handles the removal only after it finished that publish, so the publish is over once it is sent.
|
||||
var removed = System.Diagnostics.Stopwatch.StartNew();
|
||||
while (stream.RemoveCommands == 0)
|
||||
{
|
||||
removed.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(10), "the disposed demand's item was never removed");
|
||||
await Task.Delay(10, ct);
|
||||
}
|
||||
|
||||
// Positive control: a third item's snapshot carries a NEW acquisition (v2) through the same in-order publisher.
|
||||
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
|
||||
await AddComposedItem(client, sub, anchor, 3, 100, ct);
|
||||
var seen = new List<ProjectedValueUpdate>();
|
||||
ProjectedValueUpdate next;
|
||||
do { next = await NextPublished(published.Reader, _ => true, ct); seen.Add(next); } while (next.SourceVersion != 2);
|
||||
seen.Count(x => x.SourceVersion == 1).ShouldBe(0, "the disposed demand re-published the fresh v1 baseline");
|
||||
Candidates().ShouldBe(1, "only the v2 baseline holds a candidate on the existing item");
|
||||
}, onPublished: update => published.Writer.TryWrite(update));
|
||||
}
|
||||
|
||||
private sealed class ThrowingSourceProof(IProjectedSamplePublicationProof inner) : IProjectedSamplePublicationProof
|
||||
{
|
||||
public bool IsValid => inner.IsValid;
|
||||
|
||||
Reference in New Issue
Block a user