65fd71de7a
Tracked as #971-#1002.
54 KiB
54 KiB
Review 01 — Runtime (src/Server/ZB.MOM.WW.OtOpcUa.Runtime/)
- Slice:
src/Server/ZB.MOM.WW.OtOpcUa.Runtime/(~44k lines): driver host / instance actors, value fan-out, deploy apply, OPC UA publish actor, scripted alarms host, virtual tags + dependency mux, historian recorder, redundancy, gRPC data (DataConnections/), health, telemetry. - Commit:
708a4889c(master). Read-only review; no source was changed. - Method: read by one reviewer plus four scoped sub-reviews; every finding from a sub-review was then re-checked against the code by the lead reviewer unless its Verification line says otherwise.
- Nothing was built or executed. Every finding is from reading code and its callers. Cost figures are estimates derived
from the code (limits, loop bounds), not measurements. Line numbers are for
708a4889c. - Prior review:
docs/reviews/2026-10-21/02-runtime-cluster.mditems L1–L4, U1–U5, P1–P7, H1–H5 were checked where they were encountered; L2, L3, H1, H2, H3, H5, P2 (writes), P3, P4, P7 are remediated. Only R-14 touches a prior item (P5), and says so. Tracked issues #969, #959, #932, #924, #915, #755, #616, #614, #592 are not re-reported.
Coverage and its limits
| Area | Depth |
|---|---|
Drivers/DriverInstanceActor.cs |
read in full |
Drivers/DriverHostActor.cs (+ .ConditionSignals), DeploymentArtifact*.cs, NativeAlarmProjector, small Drivers/*, Communication/*, Deployment/* |
read in full by a sub-review; findings re-verified |
OpcUa/OpcUaPublishActor.cs, ScriptedAlarms/*, VirtualTags/*, Scripting/* |
read in full by a sub-review; findings re-verified (DependencyMuxActor also read by the lead) |
Historian/*, Redundancy/*, Health/*, Telemetry/* |
read in full |
DataConnections/ serving side (session, partitions, hub, publisher, local services, write path, history sessions) |
read in full by a sub-review; findings re-verified |
DataConnections/ projected side: ProjectedDataAccess, GrpcDataConnection*, ActorProjectedValuePublisher, DataConnectionDeploymentRuntime, GrpcDataDriverAdapter, ConfiguredProjectedInterestOwner |
read in full by a sub-review; findings re-verified |
Not reviewed line by line: RemoteNamespaceResolver, ProjectedCatalogCache, ProjectedHistoryAccess, ProjectedConditionAccess (+ .Methods; .Runner only skimmed), ProjectedMappingDeploymentRuntime, ProjectedNamespaceApplier, ProjectedCoalescingMailbox, ProjectedAdapterRouteSource, DataConnectionManager, FederatedBrowseService, MetadataAuthorityLease, CatalogActivation, ConditionKeys, ConditionPlacements, the two *Diagnostics files, DataConnectionWarmRoleView, LocalDataConnection, ClusterEndpointSelector, UnknownOperationDrops, ServiceCollectionExtensions.cs |
"no finding" here means not reviewed, not clean. The first three deserve a second pass. |
Finding index
| ID | Sev | Cat | Title |
|---|---|---|---|
| R-1 | High | bug | Direct-mode boot with a Failed newest node row starts an empty node |
| R-2 | High | bug | Projected cohort sends one command per item; origin kills the stream at 128 commands/s |
| R-3 | High | bug/perf | Subscription session scans ≤ 32 partition changes per tick; a quiet stream on a busy node resets forever |
| R-4 | Medium | bug | A clean surgical deploy after a degraded rebuild clears the degraded flag without repairing |
| R-5 | Medium | bug | One VirtualTag with an illegal name crashes VirtualTagHostActor; nothing re-applies |
| R-6 | Medium | bug | Dependents of a removed/renamed input keep computing from its last Good value |
| R-7 | Medium | bug | Full cohort event channel turns one item removal into teardown of every sibling demand |
| R-8 | Medium | bug | QueryAsync treats a per-call failure/cancel as endpoint failure → connection-wide backoff |
| R-9 | Medium | bug | One source's invalidation (incl. lock contention) resets every stream on its partition |
| R-10 | Medium | bug | Publisher capacity refusal is handled as evidence invalidation and retires the route |
| R-11 | Medium | perf | Every apply re-subscribes every kept driver's whole data set |
| R-12 | Medium | perf | Per delivered frame: full authorization walk 3–4×, with allocations, once under the session lock |
| R-13 | Medium | perf | RemoteSubscription copies whole handle tables per frame/ack; O(N²) on open |
| R-14 | Medium | perf | Apply-time artifact work repeated: data projection ×3–7, pinned-thread parse + hashes |
| R-15 | Low | bug | Revision advances before the last throwing steps of an apply; same-revision re-dispatch acks clean |
| R-16 | Low | bug | StopChild leaves comms-latch state and its audit timer; health ledger can be resurrected |
| R-17 | Low | bug/perf | VirtualTag source-binding-retry replays the whole apply every 250 ms |
| R-18 | Low | bug | Deferred "known" marks discarded for conditions whose live mark landed |
| R-19 | Low | perf | VirtualTagActor stash is uncoalesced; array results never dedup |
| R-20 | Low | bug | OpcUaPublishActor restart resets _lastApplied while the sink keeps the address space (latent) |
| R-21 | Low | perf | WriteOperationRegistry.Prune copies the whole table under the lock on every claim |
| R-22 | Low | bug | History remainder bytes leak when a session is cleared mid-request |
| R-23 | Low | bug | Command barrier can be armed after its only release |
| R-24 | Low | bug | Condition stream teardown can mask its real failure |
| R-25 | Low | perf | Smaller costs: publisher per-driver scans, hub fed with no subscribers, recorder drain cadence |
High
R-1 — Direct-mode boot with a Failed newest node row starts an empty node
- Severity: High · Category: bug · Confidence: High
- Location:
Drivers/DriverHostActor.cs:1463-1506(Bootstrap); Failed-row writers at:3144,:3260,:3330. - Verification: re-verified by reading.
- Description:
Bootstrap()reads only the newestNodeDeploymentStaterow for the node (OrderByDescending(s => s.StartedAtUtc)…FirstOrDefault()) and switches on its status.AppliedcallsRestoreApplied;Applyingreplays. TheFailed/default arm is:There is no "last known rev" at that point:_log.Info("DriverHost {Node}: prior deployment {Id} failed; entering Steady at last known rev", …); BecomeSteady();_currentRevisionis null, nothing is restored, andTryBootFromCache()is not consulted. The same applies to an orphanApplyingrow whose deployment row is gone (revision is null→BecomeSteady()). - Failure scenario: node applies deployment A (row Applied, serving). Deployment B fails on this node — unreadable
artifact (
:3260), an exception in the apply (:3330), a FetchAndCache misconfiguration (:3144). The log says "Staying on revision A and continuing to serve it", which is true in memory. Nobody redeploys. The service later restarts (patch reboot, crash). Newest row is B/Failed → Steady with zero drivers and an empty address space, logged at Info. Nothing heals it: the coordinator re-dispatches only its own in-flight deployments. FetchAndCache nodes are unaffected (they boot from the LocalDb pointer). - Suggested fix: in the
Failed/default arm (and therevision is nullarm), query the newest row withStatus == Appliedfor this node, set_currentRevisionfrom it and callRestoreApplied; if there is none, fall back toTryBootFromCache(), then Steady-with-no-revision. Log at Warning. - Test to add: seed A (Applied, older
StartedAtUtc) and B (Failed, newer); start the host; assert children are spawned from A andRebuildAddressSpacecarries A's blob. Second case: only a Failed row + a populated cache. - Existing tests: would not catch it — no Runtime test seeds a
Failednode row.
R-2 — Projected cohort sends one command per item; the origin kills the stream at 128 commands/s
- Severity: High · Category: bug · Confidence: High on the mechanism, Medium on the exact threshold (not run)
- Location: consumer
DataConnections/ProjectedDataAccess.cs:1625-1637(initial open loop),:1640-1660(AddEvent), renewal Remove+Add per item; originDataConnections/DataSubscriptionSession.cs:224and:235;DataConnections/SubscriptionTransportCapacity.cs:59,69-88; limits atHost/Configuration/DataConnectionRegistration.cs:199-201. - Verification: re-verified by reading both sides and the production limit wiring.
- Description: the cohort always sends exactly one item per command, back to back, never waiting for an ack:
The origin admits at most
foreach (var demand in initial) { … DataSubscriptionCommand command = !opened ? new OpenSubscription(…, [Item(registration)], …) : new AddSubscriptionItems(…, [Item(registration)]); await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true; }maxCommandsPerSecond = 128commands per principal in a fixed 1 s window (the default is not overridden inLocalDataRuntimeComposition.cs:40) and stops the session on the first excess:if (!_capacity.TryAdmitCommand(_context.PrincipalId)) { Stop(); throw … "Principal command rate exceeded." }. The same burst also hits_ackByCommand.Count >= _limits.MaxCommands(128) on the origin, and nothing reads the cohort's_eventsduring the open loop (see R-7). - Failure scenario: a cohort (connection + serving + publishing interval) holds 300 projected monitored items and
its stream drops (origin restart, failover, a designed stream reset, credential rotation). The next attempt sends 300
commands in milliseconds; the origin stops the session at command 129; the attempt ends, backs off 100 ms–5 s and
repeats identically. The cohort never re-establishes; values go stale/Bad and the retry loop keeps hammering the
origin.
MaxMonitoredItemsdefaults to 10 000, so the configured ceiling is far above what the protocol use allows. Same root, other triggers: oneCreateMonitoredItemswith > 128 projected items; synchronized lease renewals (2 commands per item). - Suggested fix: batch items per command — the protocol already takes item lists up to
MaxBatchItems— for open, add, remove and the renewal re-add; window outstanding commands tomin(local pending limit, origin limit); consume_eventswhile opening. - Test to add: wire test with a real
SubscriptionTransportCapacity(default rate) and a cohort of 300 items: assert the stream opens and every item reaches its first value; repeat after a forced stream drop. - Existing tests: would not catch it — no Runtime/wire test puts more than a handful of value items in one cohort;
the only rate test (
GrpcDataDeliveryFairnessTests,maxCommandsPerSecond: 2) is origin-side.
R-3 — A session scans at most 32 partition changes per tick; a quiet stream on a busy node resets forever
- Severity: High · Category: bug/perf · Confidence: High on the code path, Medium on field frequency (not run)
- Location:
DataConnections/DataSubscriptionSession.cs:863-890(esp.:879),:431-432(100 ms tick),:808-812;DataConnections/SourceInterestLease.cs:65-84;DataConnections/SamplePartition.cs:447-454,:601-622; defaultsDataConnections/DataResourceBudget.cs:8,16. - Verification: re-verified by reading.
- Description: each tick takes at most 32 interest groups and calls
group.Lease.TryReadChanges(32, …)once per group.ReadInterestChangescountsscanned++for every change recorded in the partition, whether or not the key is one of the lease's tickets, and the 32 is shared across all of the lease's partition cursors. A tick is queued only by the 100 ms timer or by a dequeued delivery — there is no re-queue when the budget ran out with changes still unread.RecordChangeruns for every applied publish (SamplePartition.cs:432) and keeps onlyMaxSnapshotCatchUpItems(default 1024) entries per partition; a cursor that falls off the end fails_changeIndex.TryGetValue(position + 1)and the session is closed with"Source change history expired.". With DataConnections enabled every driver value tag feeds the hub regardless of gRPC demand (DriverHostActor.cs:4133registers a shape per value tag;DriverInstanceActor.cs:2049/2068→PublishSource). - Failure scenario: node publishing 2 000 value changes/s (4 partitions, ~500 each). A consumer subscribes to 20
slow-changing items. Its scan capacity is ≈ 32 × (10 timer ticks + delivered frames per second) ≈ a few hundred
changes/s against 2 000 produced. The cursors lose ground continuously, the 1024-entry history rolls off in seconds,
and the stream resets; the consumer re-opens, snapshots, and it repeats. Raising
MaxSnapshotCatchUpItemsonly delays it because the lag is unbounded. - Suggested fix: drain each group until
position == watermarkunder a per-tick work budget andQueueTick()when work remains; or keep a per-source dirty version so a lease checks only its own tickets instead of walking the partition-wide change list. - Test to add: session with a few interests on sources A; publish ≥ 5 000 changes to unrelated sources B in the same partitions over a few seconds on a fake clock; assert no reset and that A's later change is still delivered.
- Existing tests: unlikely to catch it — fixtures use tiny source counts and no off-interest traffic.
Medium
R-4 — A clean surgical deploy after a degraded rebuild clears the degraded flag without repairing anything
- Severity: Medium · Category: bug · Confidence: High
- Location:
OpcUa/OpcUaPublishActor.cs:1554-1576(empty-plan repair) vs:1581-1627. - Verification: re-verified by reading.
- Description:
_lastAppliedDegradedis honoured only on the empty-plan path (which re-ensures the full composition). On a non-empty plan the code runs the delta (MaterialiseNodes(plan, composition, fullComposition: outcome.RebuildCalled)) and then overwrites the flag unconditionally:if (outcome.RebuildCalled || failedNodes == 0) { _lastApplied = composition; … _lastAppliedDegraded = outcome.RebuildFailed || failedNodes > 0; - Failure scenario: deploy A triggers a rebuild and one
EnsureVariablefaults → degraded,_lastAppliedadvances (by design), flag = true. The operator then deploys B, an unrelated one-tag add: surgical plan, clean delta → flag = false andRebuildCompleted(Degraded: false)seals green. The node A failed to place is inside_lastApplied, never appears in a diff again, and a re-deploy of B is an empty plan that short-circuits clean. The address space is partial and reported clean indefinitely — the exact outcome the CLAUDE.md "degraded apply" invariant exists to prevent. - Suggested fix: when
_lastAppliedDegradedis set, run the non-rebuild apply withfullComposition: trueand clear the flag only when that full pass returns 0 (otherwise keep it set and report degraded). - Test to add: degraded rebuild of composition A (sink throws for node X), then composition B = A + one raw tag with a healthy sink; assert X is ensured again, or the reply stays degraded.
- Existing tests: would not catch it —
Redeploying_the_same_composition_after_a_degraded_REBUILD_repairs_it…covers the identical-composition case only.
R-5 — One VirtualTag with an illegal name crashes VirtualTagHostActor on every apply; nothing re-applies
- Severity: Medium · Category: bug · Confidence: High
- Location:
VirtualTags/VirtualTagHostActor.cs:193-197,:294,:400-403(NodeIdFor→V3NodeIds.Uns); missing gate inAdminUI/Uns/UnsTreeService.cs:1534-1552(CheckVirtualTagRules) andConfiguration/Validation/DraftValidator.cs:689-700,:853-861. - Verification: re-verified by reading (throw path, absence of a name rule, absence of a restart re-apply).
- Description:
NodeIdFor(p)callsV3NodeIds.Uns(p.EquipmentId, p.Name), which throwsArgumentExceptionfor a segment containing/or leading/trailing whitespace.OnApplycalls it unguarded. A VirtualTagNameis not charset-checked anywhere:CheckVirtualTagRuleschecks only script and triggers; the deploy gate'sRawNameInvalidcovers raw names andUnsSegmentInvalidcovers Area/Line/Equipment only. The host has noPostRestart, andDriverHostActorhas a re-apply hook for the scripted-alarm host (HandleScriptedAlarmHostRestarted) but none for the VirtualTag host. - Failure scenario: an operator saves a VirtualTag named
"Temp "or"Flow/Rate"and deploys.OnApplythrows at:196; default supervision restarts the host;PreRestartstops every child; the new incarnation is empty and nothing re-sendsApplyVirtualTags. Every VirtualTag on the node stops evaluating. On a surgical deploy their OPC UA nodes keep the last value at the last (Good) status. Every later deploy carrying that row repeats it. - Suggested fix: (1) compute NodeIds per plan in a try/catch before any child is stopped; skip and log the bad
plan; (2) add a
VirtualTagHostRestarted→ re-apply path mirroring the scripted-alarm one; (3) add a deploy-gate and authoring rule validating VirtualTag and ScriptedAlarm names withRawPaths.ValidateSegment. - Test to add: apply
[good, bad("A/B")]; assert the good child still bridges results and the host did not restart.DraftValidatortest for the new rule. - Existing tests: would not catch it.
R-6 — Dependents of a removed or renamed input keep computing from its last Good value
- Severity: Medium · Category: bug (wrong quality) · Confidence: High for VirtualTag→VirtualTag, Medium for raw tags
- Location:
VirtualTags/DependencyMuxActor.csOnVirtualTagOutputsRemovedandOnSourceRemoved(contrastOnProjectedReferenceRetired, which does fan a Bad);VirtualTags/VirtualTagActor.cs:135,333,358,382-403;VirtualTags/VirtualTagHostActor.cs:321;Drivers/DriverHostActor.cs:4769;ScriptedAlarms/DependencyMuxTagUpstreamSource.cs(RetainOnly). - Verification: re-verified by reading the mux and the actor's
_dependenciesuse. - Description: removal only
Forgets the mux entry, which protects future replays. Nothing is sent to current subscribers. A survivingVirtualTagActor(plan unchanged, so not respawned) keeps_dependencies[removedKey]and the scripted-alarm upstream keeps its cached value while it is still referenced. - Failure scenario: VirtualTag B reads
ctx.GetTag("…/A")by absolute literal (no deploy gate rejects an unresolved absolute literal; a raw rename only warns). The operator deletes or renames A. B keeps publishing Good, computed from A's final value, on every timer tick or other-input change; a scripted alarm reading A is frozen on its last input. After a process restart the same configuration behaves differently (the input never arrives, so B never evaluates). Disabling A is handled (BadOutOfServiceis routed); removing it is not. This contradicts the R3-02 quality contract ("a value consumer never reports a quality better than its source's"). - Suggested fix: in
OnVirtualTagOutputsRemovedandOnSourceRemoved, send eachentry.Subscribersa batch carrying null + a Bad status (BadNodeIdUnknownorBadNoCommunication) before forgetting; do the same for raw refs dropped from the driver ref index on apply. - Test to add: A→B chain; apply without A; assert B publishes Bad and the alarm upstream
ReadTaggoes Bad. Replay the identical value afterwards to prove the (value, status) dedup does not swallow the transition. - Existing tests: would not catch it — the existing removal test asserts only the key release.
R-7 — A full cohort event channel turns one item removal into teardown of every sibling demand
- Severity: Medium · Category: bug · Confidence: Medium (needs a frame backlog)
- Location:
DataConnections/ProjectedDataAccess.cs:1279-1285,:1297-1313(pump),:1351-1370(RunAsyncfinally); single acquire siteOpcUaServer/OtOpcUaNodeManager.cs:4658. - Verification: re-verified by reading.
- Description:
_eventsis one bounded channel (Math.Clamp(MaxDemands * 2, 4, 128)) shared by value frames (the pump usesWriteAsync, so backpressure deliberately keeps it full under load) and by control events:internal bool Add(Demand demand) => _events.Writer.TryWrite(new AddEvent(demand)); internal void Remove(Demand demand) { if (!_events.Writer.TryWrite(new RemoveEvent(demand))) Stop(); }Stop()endsRunAsync, whose finally disposes every demand the cohort owns. - Failure scenario: the channel is full (burst/snapshot backlog, or the initial-open loop of a large cohort, during
which nothing reads
_events). A client deletes one monitored item →Demand.Dispose→Remove→TryWritefails →Stop()→ all sibling demands disposed. A projected monitored item acquires its demand once at creation and has no re-acquire path, so the siblings are dead until the client recreates them. Related:Addfails the same way (StartSubscriptionreturns false) and renewal ticks are dropped on a failedTryWrite, so leases can lapse under backlog. - Suggested fix: give control events their own unbounded or demand-bounded channel (or a per-demand flag set the
loop scans). Never tear the cohort down on a failed Remove enqueue — the next attempt already reconciles disposed
demands via
ReleaseDemand. - Test to add: fill
_eventswith frames (blocked consumer hook), dispose one demand, assert the other demands stay live and keep delivering. - Existing tests: unlikely to catch it.
R-8 — QueryAsync treats caller cancellation and per-call faults as endpoint failure → connection-wide backoff
- Severity: Medium · Category: bug · Confidence: High
- Location:
DataConnections/GrpcDataConnection.cs:331-361,:158-169; gated paths at:469,:610,GrpcDataConnection.History.cs:85. - Verification: re-verified by reading.
- Description: after a successful
SelectAsync(which callsProbeSucceeded()), a failure of the call itself is caught by the same handler as a discovery failure:catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException) { failure = ex; RecordFailure(ex); }and after the loopProbeFailed(); throw new InvalidOperationException("No ready authenticated data endpoint.", failure);. A caller cancel or deadline surfaces asRpcException(Cancelled/DeadlineExceeded)and lands there. The history and condition-method paths already filter this; the unary path (Read, GetMetadata, Browse, GetCapabilities) does not. - Failure scenario: single-endpoint connection; one projected read is cancelled by its OPC UA client or times out.
ProbeFailed()arms_nextProbeTimestamp(~250 ms ±20 %). During that window every other operation on the connection is refused unsent: subscribe throws "Data endpoint discovery is backing off" (costing the cohort an attempt), writes are rejected before dispatch, fresh history reads returnBadNoCommunication; diagnostics flip tobackoff; and the caller seesInvalidOperationExceptioninstead of a cancellation. Any per-request fault (InvalidArgument,ResourceExhausted) does the same, so a client polling one bad node id degrades the whole connection on every poll. - Suggested fix: rethrow as
OperationCanceledExceptionwhenct.IsCancellationRequested; callProbeFailed()only whenSelectAsyncitself failed for every endpoint, not when the post-select call failed. - Test to add: cancel one unary read after selection; assert a concurrent subscribe/write on the same connection is
not refused and the caller observes
OperationCanceledException. - Existing tests: would not catch it — cancel tests exist for the history path only.
R-9 — Any single source's invalidation resets every stream on its partition; lock contention is a trigger
- Severity: Medium · Category: bug (robustness) · Confidence: Medium (the quiet fence is deliberate; the blast radius and trigger set may not be)
- Location:
DataConnections/SamplePartition.cs:137-156(Signal),:308,:317,:334;DataConnections/PartitionControlSignal.cs;DataConnections/SourceInterestLease.cs:55-62;DataConnections/SourceSamplePublisher.cs:328-334,:464-481. - Verification: re-verified by reading.
- Description:
Signal()always runsControl.BeginQuiet(); … Control.EndQuiet();on the partition-wide signal, bumping its generation. Every interest lease checks!cursor.Partition.Control.Quiet.Matches(cursor.QuietControl)and reports reset, and the session closes with"Source change history expired.".Signalis reached from ordinary contention:TryStatus:if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; };TryPublish:if (!Monitor.TryEnter(slot.Gate)) { _hub.Invalidate(ticket, "source serialization contention"); … }; plus every other_hub.Invalidatereason (ingress capacity, commit rejected, status overtook an in-flight sample). - Failure scenario: a device with a few hundred tags goes offline. The driver emits a burst of Bad statuses; each
schedules the partition drain, which holds
_gate. OneTryEntermiss callsSignal. Every session with a cursor on that partition — with 4 partitions, effectively every multi-item stream on the node, including ones not subscribed to that driver — resets and re-snapshots. The tag whose status lost the race endsInvalidatedrather than carrying its Bad status. Combined with R-2 on the consumer side, a reset can become a permanent outage for a large cohort. - Suggested fix: scope the quiet fence per source (compare
gate.Invalidated/InvalidationVersionfor the lease's own tickets, as the read path already does) and keep the partition-wide bump forInvalidatePartitionand dispose only. Independently, queue a contended status instead of invalidating. - Test to add: two sessions on disjoint sources in one partition; invalidate a source of the first; assert the second is not reset.
- Existing tests: contention-driven cross-source resets are probably not covered.
R-10 — Publisher capacity refusal is handled as evidence invalidation and retires the source route
- Severity: Medium · Category: bug (robustness) · Confidence: Medium (may be a deliberate fail-closed choice)
- Location:
DataConnections/ActorProjectedValuePublisher.cs:175-183,:193-252(esp.:214,:223,:252);DataConnections/ProjectedDataAccess.cs:1990; defaultHost/Configuration/DataConnectionOptions.cs:26(MaxPendingBytes= 1 MiB). - Verification:
TryPublish/Invalidatere-verified by reading; the downstream effect on the source state was not fully traced. - Description:
TryPublishrefuses whencharge > _maximumBytes - _pendingBytesand goes through the sameRefused()as an invalid proof:Invalidate(captured)→update.SourceProof.Invalidate(); Retire(update.Route)(unless the evidence is droppable and the route current). The caller then runssource.Invalidate()when the proof cannot be dropped. - Failure scenario: the node-manager lock is held for a few hundred ms (a deploy apply, a large
CreateMonitoredItems— exactly when projected subscriptions start) while samples arrive at several thousand per second. At ~800 B charged per sample the 1 MiB pending cap is ~1 300 samples. The next sample is refused for capacity, its healthy proof is invalidated and the route retired; deltas are rejected until the next freshness snapshot (50 ms–5 s); it repeats for each refused sample while the stall lasts. Clients see gaps caused purely by local backpressure. - Suggested fix: distinguish "no capacity" from "invalid evidence" in
TryPublish: on capacity, coalesce to the latest value per route (or apply backpressure to the cohort loop) without invalidating the proof or the route. - Test to add: stall the sink, publish past
MaxPendingBytes, release; assert the route was not retired and the latest value is delivered without a re-snapshot. - Existing tests: capacity refusal is probably tested as a refusal; this consequence is not.
R-11 — Every apply re-subscribes every kept driver's whole data set, even when its set is unchanged
- Severity: Medium · Category: perf · Confidence: High on the behaviour (documented), cost not measured
- Location:
Drivers/DriverHostActor.cs:4202-4206→SendDesiredSubscriptions(:4262-4269); receiverDrivers/DriverInstanceActor.cs:982-987,:1947-1951,:1995-2002. - Verification: re-verified by reading both ends.
- Description: the bulk push Tells
SetDesiredSubscriptionsto every child on every apply with no equality check. The Connected handler unconditionally doesSelf.Tell(new Subscribe(_desiredRefs, _desiredInterval)), andHandleSubscribeAsyncawaitsUnsubscribeAsync()and then a freshSubscribeAsyncof the full set inside aReceiveAsync(mailbox suspended for both round-trips, up to 5 s + 10 s). This is documented behaviour (.claude/rules/drivers.md#662; the forced initial push is what seeds rebuilt nodes and new UNS mirrors), so it is reported as a cost, not a defect. - Cost: an ACL-only, script-only or single-reference deploy tears down and rebuilds every driver subscription on every node: OpcUaClient monitored-item delete/create upstream, Galaxy unadvise/advise of all items through mxaccessgw, a forced full re-read on every poll driver, plus a data gap per driver. It scales with total tag count, not the delta, which undercuts the surgical-deploy goal on the device side.
- Suggested fix: skip the push for a driver when its
DesiredSubscriptionSetis sequence-equal to the previous one, the apply is not a rebuild, and no node was added to that driver's fan-out sets; or seed new UNS mirrors from the raw node in the sink so the re-subscribe is no longer needed for seeding. - Test to add: non-rebuild deploy that leaves driver X untouched, with a counting
ISubscribable; assert zero unsubscribe/subscribe calls on X and that a newly added mirror of X's tag still receives a value. - Existing tests: currently assert that the re-subscribe happens.
R-12 — Each delivered value frame runs the full authorization walk 3–4 times, once under the session lock
- Severity: Medium · Category: perf · Confidence: Medium on magnitude
- Location:
DataConnections/DataSubscriptionSession.cs:1083-1100,:1240-1246,:1302-1308;DataConnections/LocalDataServices.cs:120-142,:187-192;DataConnections/LocalExportCatalog.cs:139-149,:185-195,:209-219;DataConnections/LocalCatalogCoordinator.cs:80-110. - Verification: not independently re-read by the lead; reported from the sub-review's full read.
- Description:
Gate()is called beforeTake, after it, and again insideCommit()underlock (_gate); the sink path adds one more. Each call runsitem.View.CanPublish():_catalog()→Current(invokes_serving()twice, each allocating aServingIdentity),TryResolve(allocates two records per call viawith, even when equal),AllowsExport→IsAncestor(oneTryResolveper ancestor level per export rule), then_policy.AuthorizeLocal. - Cost: for a tag five levels under its export root, an estimated 60–100 allocations and several µs per delivered
sample; at 10k samples/s roughly a million allocations/s, and a longer
_gatehold that the worker tick contends on (which also reduces the scan capacity in R-3). - Suggested fix: make
TryResolveallocation-free; memoise the per-(principal, node, operation) export verdict in the immutable catalog; cache theCanPublishverdict keyed on (catalog reference, authority/policy generation); do the full gate once outside the lock and keep only cheap identity checks insideCommit. - Test to add: allocation-budget test (
GC.GetAllocatedBytesForCurrentThread) around N deliveries of one item. - Existing tests: no perf harness on this path.
R-13 — RemoteSubscription copies whole handle tables per frame and per ack; O(N²) on open
- Severity: Medium · Category: perf · Confidence: High for (a); Medium for (b), unmeasured
- Location: (a)
DataConnections/GrpcDataConnection.cs:881-884,:943,:983; (b)DataConnections/ProjectedDataAccess.cs:829,:1816-1857,:1899-1937. - Verification: not independently re-read by the lead; reported from the sub-review's full read.
- Description: (a) every value frame runs
new Dictionary<ulong, long>(_versions)plus a newHashSet<ulong>; every ack copies four collections (_handles,_clientHandles,_usedHandles,_versions); each frame also callswire.CalculateSize()(a full re-walk). The copy-then-commit atomicity buys nothing, because any throw in that block terminates the stream. (b) per sample in the cohort:Demand.IsValid3–4× (each a node lookup, proof check and a full_policy.AuthorizeMapped),GetSourceunder the global_syncshared by all cohorts with aToUpperInvariant()and aSourceKeyrecord allocation,EvidenceFor(Where(…).ToArray()+ closure),TryPublish([update])(array +Distinct()+Select), a deep copy inCacheLocked; and after each item ack_registrations.Values.Min(…)— O(N²) across an open. - Cost: at 10k items the versions dictionary is ~280 KB (LOH) reallocated per frame, ~10×/s per stream at a 100 ms interval. With one ack per item (R-2) an open is ~10k × 4 × ~5k entry copies ≈ 2×10⁸ — seconds of CPU and gigabytes of garbage per reconnect.
- Suggested fix: mutate in place for (a). For (b) cache the
SourceStateon theRegistrationand revalidate on events (binding swap, catalog invalidation) instead of per sample; pre-uppercase the connection id once; publish per frame as a batch. - Test to add: allocation budget per frame at N = 5 000 handles; open-time budget for N items.
- Existing tests: none for performance.
R-14 — Apply-time artifact work is repeated: data projection ×3–7, pinned-thread parse and hashes
- Severity: Medium · Category: perf · Confidence: High on the repetition; cost estimated
- Location:
Drivers/DeploymentArtifact.cs:1019-1026,:273-278,:580,:833-848;Drivers/DeploymentArtifact.DataConnections.cs:71-112,:120-206,:331-339;Drivers/DriverHostActor.cs:3701-3741;OpcUa/OpcUaPublishActor.cs:853-863,:917,:1832,:2327-2334. - Verification: re-verified by reading (the
InjectScriptSourceper-tag parse was not re-read). - Description:
ParseDataPlaneAuthoritycallsParseDataConnections,ParseDataExportsandParseRemoteNamespaceMappings; each calls the un-memoisedReadDataProjection(nodeId), which deserialises Clusters, Nodes, RawFolders, DriverInstances, Devices, TagGroups, Tags, the UNS tables, VirtualTags, ScriptedAlarms and Scripts into entities, thenValidateRowsrunsDataConnectionValidator.ValidateDeployed(snapshot). The only early-out is "none of the three properties exist", andConfigComposer.cs:99-107always emits them — so a node with zero data connections still pays three full passes per apply (off-thread in the publish actor's plan task). With DataConnections enabled,DriverHostActor.StageCatalogadds up to four more on the host mailbox.OpcUaPublishActor.HandleRebuildruns on the pinned OPC UA thread: SHA-256 of the whole artifact when a catalog coordinator exists, and — whenOpcUa:Redundancy:ModeisNone/Warm—CheckRedundancyMode→ReadClusterRedundancyMode, which doesblob.ToArray()and a fullOpen(inflate + JSON parse) just to read one cluster field. The artifact is hashed again inStartRebuildandFeedDataPlaneAuthority. This is a partial regression of prior item P5 (the plan itself moved off-thread; these did not).- (Sub-review, not re-read)
InjectScriptSourcerunsJsonNode.Parse(tagConfig)for every tag whenever the artifact has anyScriptsrow, only to look forscriptId.
- Cost: at 50k tags, an estimated 50–100 ms per projection pass → 150–700 ms of avoidable work per deploy and per bootstrap, part of it on the two actors that carry all value fan-out and write routing; plus one extra full parse and up to three hashes of a tens-of-MB artifact on the pinned thread per rebuild in Warm/None mode.
- Suggested fix: memoise
ReadDataProjection(including its validation result) perParsedDeploymentArtifactand short-circuit to an empty projection when all three arrays are empty; do the redundancy-mode check inside the existing planTask.Runagainst the already-openparsed; hash once off-thread and carry the hex inPlanReady/PlanFailed; pre-checktagConfig.Contains("scriptId", Ordinal)before parsing. - Test to add: counting seam showing one projection build per
ParsedDeploymentArtifactacrossParseDataPlaneAuthority+StageCatalog, and none for an artifact with empty data arrays; assertReadClusterRedundancyModeis not called on the actor thread. - Existing tests: functional only (
GrpcDataCatalogStagingTests,OpcUaPublishActorOffThreadPlanTests).
Low
R-15 — The revision advances before the last throwing steps of an apply; a same-revision re-dispatch acks clean
- Severity: Low (latent) · Category: bug · Confidence: Medium (no concrete thrower found today)
- Location:
Drivers/DriverHostActor.cs:3272-3283, catch:3324-3340, short-circuit:3086-3099. - Verification: re-verified by reading.
- Description:
_currentRevision = msg.Revision;is set beforePushDesiredSubscriptionsFromParsed, the catalogCompleteandAwaitAddressSpaceOutcomeThenAck. The catch sends a Failed ack but neither restores the previous revision nor sets_currentRevisionUnconfirmed.ApplyDesiredSubscriptionsclears all routing maps before repopulating, so a mid-pass throw also leaves value and write routing empty. - Failure scenario: any exception after
:3272→ Failed ack. The operator re-deploys the same configuration (sameRevisionHash);HandleDispatchFromSteadytakes "matches current rev; immediate ACK" and reports a clean Applied althoughRebuildAddressSpacewas never sent for that revision. Combined with R-1, a restart then boots empty. - Suggested fix: capture the previous revision and restore it in the catch, or set
_currentRevisionUnconfirmed = truethere. - Test to add: make
BeforeSubscriptionApplyForTeststhrow; assert a Failed ack, then that re-dispatching the same revision re-applies instead of acking immediately. - Existing tests:
DriverHostActorUnconfirmedRevisionTestscovers degraded/cache/restore paths, not this one.
R-16 — StopChild leaves comms-latch state and its audit timer; the health ledger can be resurrected
- Severity: Low · Category: bug/leak · Confidence: High for the latch, Medium for the ledger
- Location:
Drivers/DriverHostActor.cs:4717-4749(no_commsLatched.Remove, no audit-timer cancel) vs:2143-2153,:2204-2226;Drivers/ChildHealthLedger.cs:33-45. - Verification: latch re-verified by reading; ledger not re-read.
- Description / scenario: a driver removed or disabled while comms-lost keeps its full RawPath set in
_commsLatchedforever. Removed within 30 s of a reconnect, the audit still fires: a false Warning ("N ref(s) still BadNoCommunication") and anotopcua.driver.comms_latched_refsincrement — the counter whose non-zero value is documented as meaning "a driver reconnects without re-publishing". A disable → re-enable of the same id inherits the stale latch.ChildHealthLedger.Forgetis undone by the stopped child's late health publish (the hub and tracker are tombstoned against exactly this; the ledger is not). - Suggested fix: in
StopChild,_commsLatched.Remove(id)and cancelCommsAuditTimerKey(id); tombstone the ledger like the hub. - Test to add: disconnect a driver, remove it by deploy, advance past the audit delay; assert no Warning/metric and an empty latch.
- Existing tests: none for the removal case.
R-17 — VirtualTag source-binding-retry replays the whole apply every 250 ms while a binding fails
- Severity: Low · Category: bug/perf · Confidence: Medium
- Location:
VirtualTags/VirtualTagHostActor.cs:118,:223-227,:291-293. - Verification: the retry-replays-
OnApplystructure re-verified; the side effects per replay are from the sub-review. - Description / scenario:
Timers.StartSingleTimer("source-binding-retry", msg, 250ms)re-delivers the originalApplyVirtualTags. WhileEnsureVirtualBindingkeeps failing (one persistent cause: the hub'sMaxTrackedSourcescap), four times a second with no backoff or cap: quarantines are reset (a runaway script is re-run),ReassertValuegoes to every surviving child (N value updates and sink-lock acquisitions), every disabled tag'sBadOutOfServiceis republished, and the cycle graph is recomputed. Only when DataConnections is wired. - Suggested fix: a dedicated retry message that only re-attempts binding and spawning for the still-unbound ids, with backoff and one degraded log line.
- Test to add: fake publisher whose
EnsureVirtualBindingfails for one id; assert no repeatedResetQuarantines/ReassertValueacross 1 s. - Existing tests: would not catch it.
R-18 — Deferred "known" marks are discarded for conditions whose live mark actually landed
- Severity: Low · Category: bug (false diagnostic) · Confidence: Medium
- Location:
OpcUa/OpcUaPublishActor.cs:812-816,:1171-1172,:1212-1219. - Verification: not independently re-read by the lead.
- Description / scenario:
HandleMarkConditionsKnownapplies the mark live and also defers it. At replay any deferred alarm outsidescope.Conditions— the normal state of every kept condition on a surgical or no-artifact apply — callsNoteAlarmLoss(source), the source's deferred Known marks are "discarded" and the sender getsConditionMarksDiscarded. A driver that reconnects during a plan window has its conditions put back in the F5 window with a Warning and later a false "not signalled" diagnostic; the sink and the host tracker disagree. - Suggested fix: note a loss only when the alarm's node is in scope but was dropped (overflow) or is absent from both the previous and the applied composition.
- Test to add: plan in flight; send
AlarmStateUpdate+MarkConditionsKnownfor an existing condition; finish a non-rebuild apply; assert noConditionMarksDiscarded.
R-19 — VirtualTagActor evaluation backlog is uncoalesced, and array results never dedup
- Severity: Low · Category: perf · Confidence: Medium
- Location:
VirtualTags/VirtualTagActor.cs:427-445(stash/unstash),:545(dedup),:447-458. - Verification: the
Equals(_lastValue, result.Value)dedup and theReceiveAny(_ => Stash.Stash())shape re-verified; the rest from the sub-review. - Description / cost: every evaluation is asynchronous; while one runs everything is stashed, and
UnstashAllre-queues M messages of which the first starts a new evaluation and M−1 are re-stashed — O(M²) message hops and one script run per stashed batch, unbounded if arrivals outpace evaluation (out-of-process runner under load). Per-trigger evaluation is deliberate per the class doc, so this is a cost note. Separately,Equalson arrays is reference equality and the value is copied each time, so an array-typed VirtualTag publishes, routes to the mux (re-evaluating dependents) and historizes on every trigger — up to 20/s on a 50 ms timer. - Suggested fix: fold consecutive stashed
DependencyValueBatches into the dependency map and evaluate once; structural comparison for arrays. - Test to add: slow evaluator + 100 batches → evaluation count far below 100; array VirtualTag with unchanged output → one publish.
R-20 — A supervision restart of OpcUaPublishActor resets _lastApplied while the sink keeps the address space
- Severity: Low (latent) · Category: bug · Confidence: Medium on the consequence; no concrete trigger found
- Location:
OpcUa/OpcUaPublishActor.cs:313-318and the unguarded handlers at:593-594,:701-714,:812-816,:853-863,:919,:1465-1473,:1484,:2261-2311. - Verification: not independently re-read by the lead.
- Description / scenario: if any unguarded handler ever throws, the new incarnation diffs the next deploy against
an empty composition: everything looks added, so it is a non-rebuild apply of idempotent ensures; nodes the deploy
removed are never removed, in-place attribute edits are skipped (
EnsureVariableearly-returns), and the apply reports clean._warmRolealso resets to Standby without closing an open projection. - Suggested fix: on restart mark the baseline unknown and force the first apply to be a full rebuild.
- Test to add: restart the actor after an apply; deploy a composition that removes a node; assert the node is gone.
R-21 — WriteOperationRegistry.Prune() copies and scans the whole table under the lock on every claim
- Severity: Low · Category: perf · Confidence: High
- Location:
DataConnections/WriteOperationRegistry.cs:53-55,:104-112. - Verification: re-verified by reading.
- Description / cost:
foreach (var pair in _entries.ToArray()) { if (!pair.Value.Claim.CanRetire(now, _retention)) continue; … }runs insidelock (_gate)on everyClaim. Entries live for the retention window after completion, so at W writes/s the table holds ~retention × W entries: at 100 writes/s with a 30 s retention that is a ~3 000-entry array copy and 3 000CanRetirecalls per write item, crossing the LOH threshold a little above that rate. The condition-method registry uses the same class with a longer retention. - Suggested fix: keep a completion-ordered queue and pop expired heads, or prune only at capacity / every N ms.
- Test to add: allocation budget for a claim against a table of 5 000 unexpired entries.
R-22 — History remainder bytes leak when a session is cleared while one of its requests is in flight
- Severity: Low · Category: bug/leak · Confidence: Medium (narrow window)
- Location:
DataConnections/OriginHistorySessions.cs:80-95(SaveChunk),:124-131(Clear);DataConnections/LocalDataServices.History.cs:203,:224-225. - Verification:
SaveChunk/Clearre-verified by reading; the request-side window is from the sub-review. - Description / scenario:
Clear()(channel close, per-principal LRU eviction, capacity change) empties the session and removes it from the owner but sets no closed flag. A request already holding the session reference then callsSaveChunk→_owner.TryReserve(Principal, bytes, …)and stores the chunk in the orphan. Nothing sweeps the orphan, so the bytes stay charged to the principal for the life of the process; after a few such events every chunked history answer for that principal returnsBadTooManyOperationsuntil restart. - Suggested fix: set a
_clearedflag under_gateinClear();SaveChunkreleases the bytes and returns null when it is set. - Test to add: hook between the last cancellation check and
SaveChunk; clear the session there; assert the principal's retained bytes return to zero.
R-23 — The command barrier can be armed after the only event that releases it
- Severity: Low · Category: bug (race) · Confidence: Medium (narrow window)
- Location:
DataConnections/DataSubscriptionSession.cs:346-348,:392-407,:986-999. - Verification: the check-then-CAS shape and
ReleaseBarrierre-verified by reading; the delivery-side ordering is from the sub-review. - Description / scenario: the worker evaluates
HasIncompleteSnapshot()(under_gate), releases the lock, then doesInterlocked.CompareExchange(ref _barrier, 1, 0). If the delivery thread commits the lastSnapshotEndin between, itsReleaseBarrier(1)finds 0 and is a no-op; the worker then arms the barrier. Nothing releases it unless another snapshot completes, every command defers, and the stream stops at the command's ack timeout. - Suggested fix: arm first, then re-check and self-release; or do check-and-set and the release decision under the same lock.
- Test to add: hook between the check and the CAS that completes the snapshot; assert the deferred Modify runs.
R-24 — Condition stream teardown can mask its real failure with NotSupportedException
- Severity: Low · Category: bug (diagnostics) · Confidence: Medium
- Location:
DataConnections/ProjectedConditionAccess.Runner.cs,RunStreamAsync(await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token);withnext ??= frames.MoveNextAsync().AsTask();left pending across iterations). - Verification: not independently re-read by the lead.
- Description / scenario: when
ApplyResolvedAsyncorRetryDueAsyncthrows whilenextis in flight, theawait usingdisposes an async iterator mid-MoveNextAsync, which throwsNotSupportedException; that replaces the original exception in the "stream ended" log andnextlater faults unobserved. The reconnect still happens. - Suggested fix: cancel a per-stream token and await/observe
nextin the finally before disposing.
R-25 — Smaller costs worth a note
- Severity: Low · Category: perf · Confidence: High on the code, impact small
- Verification: read by the lead.
DataConnections/SourceSamplePublisher.cs:220-238:RetireDriverandPublishDriverStatusfind a driver's refs with_drivers.Where(x => x.Key.Driver == driver)— a scan of every bound ref of every driver, under the global_gate, per connectivity edge and per child stop. A deploy that respawns D drivers over N total tags is O(D·N) under the lock thatEnsureDriverBindingonlyTryEnters (so bindings silently fail and go to the 250 ms retry while it is held). A per-driver index removes it.Drivers/DriverInstanceActor.cs:2049,:2068,:2923-2945: with DataConnections enabled, every driver data change paysPublishSourceon the driver's callback thread (1–2 dictionary probes, a size estimate, an ingress reservation and a value copy) and enters the hub's change history whether or not any gRPC consumer exists. This is what makes R-3 reachable on a node with a single small subscription; publishing only for sources with interest would remove both the cost and the trigger.Historian/ContinuousHistorizationRecorder.csOnDrainResult: a successful full batch re-arms the 2 s timer rather than draining again immediately, so with no ingest a backlog drains atdrainBatchSize / drainInterval(default 512 entries/s — ~33 minutes for a 1M-entry outage backlog). Appends do trigger extra drains, so this only limits catch-up during quiet periods. Re-tick immediately whenAcked == _drainBatchSize.DataConnections/ConfiguredProjectedInterestOwner.SweepAsync(sub-review, not re-read): re-queues every desired entry every second with no backoff; an unresolvable configured reference re-runs discovery each second indefinitely.
Areas reviewed with no findings
DriverInstanceActor: connect/reconnect state machine and single-flight init (H2 remediated); comms-loss watchdog conjunction and per-connection grace; write slots, per-tag ordering, queue budget, abandon path and rich-write settlement (#964/#967); native-alarm subscribe/reconcile/backoff and data-vs-alarm independence (#662); ack confirmation off-mailbox (#869);PostStopbounded shutdown + dispose (P4/L1 remediated); handler detach on every exit; health fingerprint dedup.DriverHostActor: value fan-out hot path (ForwardBatchToMux— struct items, one list per burst, guarded debug log); comms-loss fans; write routing and Primary gate; Steady/Applying/Stale receive tables (H5 remediated); ack holding and degraded/timeout paths (other than R-15); child spawn/restart/reprovision incarnation checks (L2 remediated);ConditionSignals,NativeAlarmProjector,DriverSpawnPlan,DriverWriteBounds,ActorNodeWriteGateway,AkkaDriverHealthPublisher,NativeAlarmAckPreflightView.Communication/*,Deployment/*: ack sender, artifact fetcher (bounded, validated timeout), LocalDb artifact cache and schema.OpcUaPublishActor: value/status/alarm handlers, deferred writes and replay ordering, the degraded non-rebuild no-advance rule,RebuildCompletedon every path, incarnation fencing, ServiceLevel/Warm ordering.ScriptedAlarmHostActorand stores: load-generation fencing, readiness, command dedup bounds, Sender capture across awaits, engine ownership across restart (H1/H3 remediated), re-assert ordering, Primary gate;LocalDbAlarmConditionStateStore;DependencyMuxTagUpstreamSource(L3 remediated).DependencyMuxActor: registration/detach/grace/sweep bookkeeping and the hot ingress path (lazy allocation, indexed loop).DependencyConsumerMuxAdapter,DpsScriptLogPublisher.Historian/*: recorder ingest → bounded append channel → off-mailbox drain (P3/H3 remediated), partial-failure head-of-line logic, backoff, status off-mailbox;HistorianAdapterActorbounded queue (H4 remediated); retention.Redundancy/*,Health/*,Telemetry/*:RedundancyRoleViewverdict/generation fencing,WarmRoleAuthority,OpcUaEndpointStepDownActor, peer probes,DbHealthProbeActor(P7 remediated),TelemetryLocalHubtombstones (L4 remediated).DataConnections/(serving side):PartitionedSampleHub,ConditionItemStream,ConditionStateHub,SubscriptionTransportCapacity,DataWriteExecutor,WriteAdmissionTicket,LateWriteObserver,DataWriteDispatchGate,DataWriteRuntime,SnapshotAdmissionScheduler,SnapshotLease,DeliveryScheduler,OwnedDataSample,UpstreamDemandRegistry,SubscriptionItemHandleTable,BrowseContinuationRegistry,ClientFilterState,LocalExportCatalog.Compilation,LocalDataServices.ConditionMethods/.Conditions.DataConnections/(projected side):GrpcDataConnection.History/.ConditionMethods/.Diagnostics,DataConnectionDeploymentRuntime,GrpcDataDriverAdapter.