Commit Graph

1814 Commits

Author SHA1 Message Date
Joseph Doherty 6b19f4add6 feat(resilience): #1047 non-retrying AcquisitionSubscribe capability wraps SubscribeAcquisitionAsync (breaker + /hosts telemetry), OTOPCUA0001 suppression removed
New DriverCapability.AcquisitionSubscribe (appended): RetryCount 0 in every tier and forced 0 by the parser, 30 s timeout
(outlasts the actor's 10 s acquisition timeout), breaker 5 (Tier C none). PendingAcquisition.Start routes through the
invoker keyed on the driver instance; an open breaker fails fast and the capacity reservation is released.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 15:20:02 -05:00
Joseph Doherty 79235bf593 fix(resilience): #1052 every failed attempt counts toward ConsecutiveFailures, no-retry capabilities included; non-idempotent write telemetry on the caller's host
Decided: an innermost recorder counts each attempt ending in a handled failure (not caller cancellation, not a
refusal; the pipeline timeout stays counted once by OnTimeout). OnRetry only logs now. Write/AlarmAcknowledge/
Initialize failures used to never raise the /hosts count, and a retried call's last attempt was never counted.
The ::non-idempotent write pipeline records failures + breaker under the caller's host (trackerHostName).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 15:10:21 -05:00
Joseph Doherty 69f475392c fix(controlplane): #1051 coordinator dispatch seed + terminal writes off the actor thread; driver-operation audit write retried
H-6 remainder: ConfigPublishCoordinator runs the dispatch guard/seed (incl. the #977 superseded close) and the
Sealed/PartiallyFailed/TimedOut writes through RunDbWork - a pool-thread task whose outcome is applied on the actor
thread while a Busy behaviour stashes everything else. A failed write is rethrown when it reports back (same
restart-and-recover contract as before); recovery runs the same work inline (failure = failed load).
H-3 remainder: a transient Restart/Reconnect ConfigEdit audit failure is retried (1 s doubling, 30 s cap, 6 attempts);
a ConfigDb rejection (poison allowlist) is not.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 15:07:25 -05:00
Joseph Doherty 763ca0eedd Merge security review fixes: sandbox refuses async/stackalloc/MethodImpl, unwinding-overflow guard, deep-data types (#971); T-SQL ScriptDom single-SELECT guard (#974); Auth 0.5.0 directory re-query on revalidation (#975); fleet-diagnostics target check (#973) 2026-12-03 12:27:35 -05:00
Joseph Doherty 81cf44cb90 fix(security): #975 review — re-read directory groups at each AdminUI session re-validation (Auth 0.5.0)
AdminSessionRevalidator re-mapped the groups frozen into the cookie at sign-in,
so removing a user from a directory group changed nothing until
MaxSessionMinutes ended the session.

Bump ZB.MOM.WW.Auth.{Abstractions,Ldap,AspNetCore} 0.4.1 -> 0.5.0 (additive
ILdapGroupLookup; 0.4.2-0.4.4 changes only affect BindMode=User / API-key SQL
stores, unused here; solution builds clean). OtOpcUaLdapAuthService now
implements ILdapGroupLookup with the same Enabled / DevStubMode / insecure-
transport rules as sign-in, registered as the same singleton (a stub
ILdapAuthService gets a NotSupported lookup).

At each re-validation interval the revalidator looks the user up: Found ->
fresh groups replace the session's otopcua:group claims and are mapped;
UserNotFound / UserDisabled / AmbiguousUser / Found-with-no-groups -> reject;
DirectoryUnavailable (or a lookup fault) -> fail-soft on the last known groups
(still re-mapped), bounded by MaxSessionMinutes; NotSupported / ProviderDisabled
-> previous behaviour. Never queried under DisableLogin.

Tests (directory rows failed first): group removal / addition picked up after
the window, unchanged membership kept (positive control), four end-the-session
statuses, outage keeps the session until the absolute cap, DisableLogin issues
no lookup (control: one lookup otherwise); wrapper lookup rules + DI
registration. docs/security.md drops the 'no password-less lookup' claim.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:25:41 -05:00
Joseph Doherty 35d14936ac fix(sql): #974 review — parse SqlServer/Odbc named queries as T-SQL; ';' is not a statement boundary
The named-query guard's only statement boundary was ';', but T-SQL runs
';'-less batches: 'SELECT 1 COMMIT KILL 55', '... COMMIT DISABLE TRIGGER ALL ON
DATABASE', '... COMMIT SHUTDOWN WITH NOWAIT' and a TEXTPTR/WRITETEXT write were
all accepted for SqlServer AND Odbc — a COMMIT ending the rolled-back
transaction, then anything not on the keyword list.

For SqlServer, and for Odbc / no provider (backend unknown: strictest reading),
SqlReadOnlyStatement now also parses the statement with
Microsoft.SqlServer.TransactSql.ScriptDom 180.154.0 (central package pin; both
QUOTED_IDENTIFIER settings) and requires exactly one batch holding exactly one
SelectStatement, no INTO, and no OPENQUERY/OPENROWSET/OPENDATASOURCE. Odbc '?'
markers are read as variables for the parse. The lexical guard stays as a
second layer.

Tests: SqlReadOnlyStatementTransactSqlTests (11 batch strings x SqlServer/Odbc/
none, pass-through rowsets — all failed first; CTE/subquery/window/param/UNION/
FOR XML/OPTION and ODBC '?' positive controls). SqlNamedQueryTests' SQLite-backed
Odbc stand-in used the T-SQL reserved word 'top' as an alias (renamed).
Live (SQL Server 10.100.0.35,14330): SqlServerNamedQueryBatchLiveTests proves
'SELECT 1 AS v COMMIT UPDATE ...' commits the old way, the guard refuses it,
and a CTE+window+subquery+@param query reads Good; SqlServerReadTests /
write-mode / trigger suites unchanged (30/30). Class comment and
docs/drivers/Sql.md corrected.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:21:23 -05:00
Joseph Doherty 31bf883e09 fix(scripting): #971 review — refuse script-built deep/cyclic data that BCL or host code recurses over
Sibling hunt for the #779 stack guard: recursion with NO script frame. A BCL or
compiler-synthesized ToString/Equals/GetHashCode/CompareTo/Message recursing
over a structure the script nested a million deep in a loop (or made cyclic)
terminated the host with 'Stack overflow.' — Tuple/ValueTuple/KeyValuePair/
anonymous-type chains, a self-referencing Lazy, StructuralComparisons over a
self-containing array, DictionaryEntry, FormattableString holes, inner-exception
/ AggregateException / ArgumentOutOfRange(actualValue) chains, DataValueSnapshot
built or with-copied around itself. Host code does the same to a returned value:
OwnedDataSample.CopyLegacy and VirtualTagActor.SameValue recurse over nested /
self-containing object[] results.

The analyzer now refuses what builds such a structure: holders with an open
element type (object / ValueType / interface / type parameter; a tuple literal
that is only deconstructed stays legal), arrays whose element can be an array,
Array.CreateInstance, Lazy, the structural comparers, DictionaryEntry,
AggregateException, exception constructors taking an inner exception or an
object, FormattableString outside FormattableString.Invariant/CurrentCulture,
and host-record construction / 'with' when the record has an open member.
System.Comparison is dropped: Array/List Sort and BinarySearch rethrow a
comparer's exception from a BCL catch block, so a comparer recursing through
Sort overflowed while unwinding (use OrderBy/ThenBy).

Regression rows for every vector (all failed first), plus closed-neighbour rows
that must keep compiling. The script-literal differential over src/tests/docs/
scripts (238 accepted before) and the reviewer's 35 legit probes are unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:13:58 -05:00
Joseph Doherty 568d466303 Merge driver review fixes: MQTT deterministic host claim + re-assert (#988), Galaxy secured-write refusal + re-advise session guard (#991), Heidenhain host-status/dispose (#990), MicroLogix L files (#984), Modbus DI<n> (#981), AbCip latch + probe init bound (#983) 2026-12-03 12:09:42 -05:00
Joseph Doherty eb78875c24 fix(galaxy): #991 review — a re-advise pass never dials on a swapped session; dropped-event resync is rate-limited and coalesced
- ReadviseSubscriptionAsync: a reconnect completing between two subscriptions of a pass
  (dropped-event resync loop had no per-iteration check) sent the next SubscribeBulk to the
  NEW gateway session under the OLD session number; TryRebind refused it (SessionChanged)
  and the live new-session advises were never bound or released, then duplicated by the
  replay. The pass now refuses to dial once its session moved. Releasing afterwards was
  rejected: once the session moved, which session issued the reply's handles is ambiguous and
  old numbers are reused (#861); not dialling is the unambiguous fix.
- Dropped-event resync passes are at least 5 s apart (DropResyncMinInterval); drops reported
  meanwhile coalesce into the next pass, so repeated overflow bursts no longer churn
  re-advises into the overflowing channel.
- Test seams: ResyncDroppedHandlesForTestsAsync, NotifyEventsDroppedForTests,
  DropResyncMinIntervalForTests; AdvisingSubscriber gained after-subscribe/unsubscribe hooks.
2026-12-03 12:07:28 -05:00
Joseph Doherty 052fdf0769 fix(scripting): #971 review — guard script catch/finally handlers so unwinding cannot overflow the stack
Sibling hunt for the #779 stack guard: a catch or finally runs as a funclet on
top of the frames being unwound, so a handler that throws starts a nested
dispatch deeper still (~6 KB/level). 'catch { throw; }' on every frame killed
the host while unwinding from the guard's own exception, and 300 frames that
each rethrow (or whose finally throws) killed it with no guard involvement.

The stack-guard rewrite now gives every script catch the filter
'when (ScriptStackGuard.CanHandle() && (filter))' and wraps every finally body
in 'if (ScriptStackGuard.CanHandle())'. Once the stack is low, script handlers
are skipped and the in-flight exception reaches the host in one dispatch.
Verified on 1.5 MB / 1 MB / 512 KB / 256 KB threads. Seven new child-process
scenarios in ScriptRecursionContainmentTests (all crashed before), plus
semantics-preservation rows for filters, declaration-less catch, pattern
variables and finally on both paths.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:05:33 -05:00
Joseph Doherty 5dcb766fd1 fix(abcip): #983 review — probe timeout bounds only the probe read, not the cold initialisation
P-22 moved the probe's own short timeout (default 2 s) onto the probe runtime's cold
InitializeAsync too — on the native transport the TCP connect + RegisterSession + Forward
Open, which the pooled connection bounds with the driver's Timeout. A slow-but-healthy open
longer than the probe timeout never completed: the probe re-created and timed out every
tick and the host stayed Stopped. Initialisation now runs under the loop token only; the
probe timeout bounds the read.
2026-12-03 12:03:49 -05:00
Joseph Doherty 84a0226bfa fix(abcip): #983 review — per-call device latch only on real connection failures; never evict handles that were not attempted
- On libplctag each tag is its own request with its own timeout: one tag's Timeout latched
  the whole device for the call, failing (and evicting) every later sibling. The latch now
  fires on BadConnection/Abort/socket-IO failures always, and on Timeout only on the native
  transport, where a reply timeout faults the device's one shared channel
  (AbCipRefusals.LatchesDevice).
- Items latched out were never attempted: their handles are kept (evicting re-created, and
  for a sole lease holder re-Forward-Opened, each one next poll). The failed item's handle is
  still evicted, and a throttled cold create now latches the device so kept warm handles
  fail fast instead of each paying a timeout.
- AbCipDeadDeviceBatchTests recovery leg: the device's kept warm handles answer again.
2026-12-03 12:03:14 -05:00
Joseph Doherty ec9c0f2eb6 Merge review fixes: termination watchdog exits 1 on cluster leave/down under Akka.Hosting (#980, windev SCM gate passed); Gateway alarm writer isolates poison events (#976) 2026-12-03 12:01:50 -05:00
Joseph Doherty 7ecaeea82e fix(scripting): #971 review — refuse async lambdas/local functions, stackalloc and runtime-binding [MethodImpl] flags
Three scripts passed the allow-list and the deploy gate and then terminated the
host (exit 134): an async void local function / async lambda (the compiler's
AsyncVoidMethodBuilder rethrows on the thread pool) and an over-sized stackalloc
(overflows in one frame, before the #779 guard). IsForbiddenSyntax now refuses
every async form (await included) and both stackalloc forms.

Siblings: [MethodImpl] may set only the JIT-hint bits (InternalCall passed the
gate then failed to load; Synchronized is a lock; numeric casts are checked by
constant value), and a collection initializer's compiler-called Add is checked
like a named member. Regression rows for each, plus rows pinning the lowered
constructs that stay safe (iterators, goto, checked, filters, collection
expressions, interpolation handlers, params Span, using/deconstruction) and the
declarations the wrapper already refuses (records, local types, finalizers,
static ctors, unsafe/fixed, SkipLocalsInit, ThreadStatic).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:01:25 -05:00
Joseph Doherty 1c7e06502f fix(historian): #976 review — Gateway alarm writer isolates an unrecognised batch failure per event
#976 made StatusCode.Unknown (the gateway's handler threw) and non-RPC non-transport exceptions
RetryPlease. On the SendEvents path a RetryPlease marked the whole chunk and every later chunk
RetryPlease; with no Ack the sink treats the drain as an outage and counts nothing, so ONE such
event at the queue head stalled all Gateway alarm history until the 1,000,000-row capacity evicted
it silently. The SQL writers already isolate unrecognised failures (AlarmBatchWrite); the Gateway
writer had no equivalent.

Gateway: a RetryPlease failure that is not a known outage (IsSystemicFailure: Unavailable,
DeadlineExceeded, Cancelled, ResourceExhausted, Aborted, auth codes, typed Unavailable/auth client
exceptions, or a socket/IO/HTTP/disposed/timeout/cancellation cause) re-sends the chunk singly at
once: siblings Ack, the culprit keeps RetryPlease and dead-letters via MaxAttempts. If no single
Acks it is treated as systemic (later chunks not sent) — bounded to one chunk of singles per drain.

SQL (LOW): AlarmBatchWrite stops isolating at the first single that fails with a known outage
error; the SQL Server alarm writer passes the wider SqlHistorianConnection.IsOutage (login failed
18456/18452, unreachable/refused 2/40/53/64/121/10061/10065/-1, severity >= 20, pool timeout) —
IsTransient is unchanged for its retry callers. Fixes the false claim in docs/AlarmHistorian.md.

Tests: GatewayAlarmPoisonDrainTests (real LocalDb sink + real writer: poison at the queue head ⇒
siblings Ack on the first drain, poison dead-letters via MaxAttempts; positive control: Unavailable
outage ⇒ no single sends, nothing dead-lettered), writer-level isolation + bounded fan-out tests,
AlarmBatchWrite early-stop + no-stop-on-adjacent-poison control, SqlOutageClassificationTests.
2026-12-03 12:01:24 -05:00
Joseph Doherty b8fadac80e Merge review fixes: superseded deployment's ack write no longer drops successor's ack (#996); degraded-apply repair re-pushes drivers (#995) 2026-12-03 12:01:14 -05:00
Joseph Doherty d40dd83517 Merge #994: projected cohorts batch + pace commands (multi-item cohorts work; 10k opens), per-source change scans/invalidations, backpressure not teardown, memoised per-frame authz, node-indexed publish, O(1) eviction 2026-12-03 12:01:14 -05:00
Joseph Doherty 48b5f9c466 fix(runtime): #995 review — a repair of a degraded apply re-pushes the drivers whose nodes it creates
OpcUaPublishActor reported AddressSpaceRebuilt only after a real full rebuild, so the empty-plan repair of a degraded
composition, the #977 R-4 whole-composition re-ensure, and the re-diff after a degraded non-rebuild all reported a
clean non-rebuild. The degraded apply's own re-push had run while the node it failed to place was missing; the apply
that finally created it skipped the node's driver (fingerprint unchanged), so the node stayed
BadWaitingForInitialData until its value changed — forever for a constant.

- The publish actor now reports AddressSpaceRebuilt=true when the apply ran a repair pass (either branch) or when the
  previous apply of any kind ended degraded (final outcome, completion + catalog included); DriverHostActor re-pushes
  the deploy's skipped drivers on it. A clean apply after the repair reports false again.
- DriverLifecycle.md / rules note the widened signal.

Tests: DriverHostActorDegradedRepairReseedTests (REAL publish actor: degraded add, degraded rebuild + empty-plan
repair, degraded rebuild + R-4 repair; skip still works afterwards) and OpcUaPublishActorApplyOutcomeTests (outcome
on both repair branches + after a degraded non-rebuild, with clean-no-op controls) — all six failed before the fix.
2026-12-03 12:00:32 -05:00
Joseph Doherty 5cccfd75ce fix(grpc-data): #994 projected cohorts batch, pace and scale past one item; busy origins no longer reset quiet streams
Wave 3 of the 2026-12-02 review (docs/reviews/2026-12-02/01-runtime.md R-2/3/7/8/9/10/12/13/21/22/23/24,
02-opcuaserver.md U-10/11/12/13).

Consumer (ProjectedDataAccess cohort):
- R-2: a cohort's OpenSubscription declared a snapshot budget of 1 item, which the origin uses to size the stream's
  handle table, so the 2nd item was refused LimitExceeded and the cohort re-opened in a loop (two projected items of
  one interval broke each other). Opens/adds/removes are now batched (IDataSubscriptionCommandLimits, <=256 items,
  bounded by estimated snapshot bytes) and paced (32 burst, 32/s, <=4 commands or snapshots outstanding).
- R-7: control events no longer share the bounded frame queue; a failed Remove can no longer Stop() the cohort.
- R-10: a local capacity refusal (TryPublishOrBackpressure -> CapacityExhausted) is retried for up to 2 s instead of
  invalidating healthy evidence and retiring the route.
- R-13: RemoteSubscription mutates its handle/version tables in place; the cohort caches the source per binding and
  drops the per-sample LINQ in EvidenceFor.
- R-8: only an unselectable endpoint arms the discovery backoff; a caller cancel is OperationCanceledException.
- R-24: the condition stream cancels and observes a pending frame read before disposing the enumerator.

Origin (DataSubscriptionSession / SamplePartition / SourceInterestLease):
- R-2 (found by the perf harness): the delivery index was sized MaxPendingFrames x 16 = 1024, so the 1025th item of a
  stream stopped the session after its ack; it now covers MaxMonitoredItems.
- R-3: interest reads count only own-ticket matches (scan budget separate), re-queue a lagging tick, and catch up from
  per-source last-change versions when the bounded history rolled off - no more "Source change history expired".
- R-9: a partition quiet bump resets a lease only when one of ITS sources was invalidated (per-source quiet version)
  or its binding retired; partition-wide invalidation still resets all.
- R-12: the per-item publish verdict is memoised per (catalog instance, authority generation) for <=1 s; Commit
  under the session lock re-checks identity only.
- R-21/R-22/R-23: registry prune is interval/capacity driven; a cleared history session refuses chunks; the snapshot
  barrier is decided and armed under the same gate its release is decided under.

Node manager: U-10 projected live items indexed by node; U-11 anchor removal / root-leaf swap tombstone the anchor's
own monitored node; U-12 per-parent child count; U-13 per-condition verdict index.

Also: Issue934_r1_N1 test clears its metadata failure before ending the stream (test-only sequencing race,
reproduced with a 200 ms delay; production behaviour correct).

Perf (Category=Perf, OTOPCUA_GRPCDATA_PERF=1): 10k-item cohort opens in 3.3 s / 80 commands / 1 stream (before: never
opens); 100 source versions at 1k/s -> 11,036 item values in 569 ms.
2026-12-03 11:59:26 -05:00
Joseph Doherty 7374fdd0e4 fix(modbus): #981 review — MELSEC no longer claims the generic DI<n> discrete-input mnemonic
The S-8 gate (no generic mnemonic fallback once a family grammar claimed the address) made
the MELSEC D-register grammar, which claimed every D prefix, reject DI100 as a malformed
D-register. MELSEC has no DI device, so DI... is no longer claimed; every other D... stays
native and DL205's non-octal C rejection is untouched.
2026-12-03 11:58:15 -05:00
Joseph Doherty b74b5162d2 fix(ablegacy): #984 review — MicroLogix profile supports L files
MicroLogix 1100/1200/1400/1500 all have L (32-bit integer) files (only the ML 1000 lacks
them, and the family flag cannot tell it apart — an ML 1000 refuses an L read itself, per
tag). SupportsLongFile: false made the P-5 per-tag rule refuse every Long tag on the family
the parser, coalescer and L-bit RMW already handle. The per-tag rejection tests now pin
PLC-5, the one family without L files. Pending hardware confirmation: one L-tag read on an
ML 1400 (Vitamine press fleet).
2026-12-03 11:57:09 -05:00
Joseph Doherty 2d28f5ea8a fix(heidenhain): #990 review — host-facing state keyed by host:port survives re-init; dispose cancels before closing the session
- _facing was keyed by runtime instance: it grew one entry per re-init (watchdog every ~90 s
  while a control is down) and each new runtime restarted at Unknown, so a down control's
  status flapped Stopped -> Unknown -> Stopped across every re-init. Now keyed by host:port,
  pruned to the configured hosts at init and cleared at shutdown; a runtime no longer in
  _devices (being stopped by re-init/shutdown) announces nothing.
- DeviceRuntime.DisposeAsync cancels the loop BEFORE closing the session: closing first woke
  an in-flight read while the token was live, and the loop's normal tail set Backoff (host
  Stopped) for a plain stop. Seam AfterSessionCloseForTests makes the race deterministic.
2026-12-03 11:55:28 -05:00
Joseph Doherty 645a8b9209 fix(host): #980 review — termination watchdog exits on a cluster leave/down under Akka.Hosting
The first #980 fix stayed quiet whenever ApplicationStopping was already cancelled. Akka.Hosting
1.5.62's AkkaHostedService hooks WhenTerminated earlier and, for ClusterLeavingReason /
ClusterDowningReason, sets Environment.ExitCode = -1 and calls StopApplication() BEFORE the
watchdog's continuation — so manual failover, endpoint step-down and auto-down all still ended in a
graceful stop (SERVICE_STOPPED, win32 exit 0 — SCM reads ServiceBase.ExitCode, not the -1) that
Windows SCM never restarts.

"Expected" is now decided from signals Akka.Hosting never produces: a host stop requested while
the ActorSystem still runs (SCM stop / Ctrl-C / GracefulClusterLeaveService), the watchdog's own
StopAsync before termination, or CoordinatedShutdown reason ClrExitReason. Everything else exits 1.
After an unexpected termination the watchdog's StopAsync holds host shutdown until the exit is
issued, so the service host cannot report SERVICE_STOPPED first. Registration moved to
AddOtOpcUaTerminationWatchdog (shared with tests).

Tests: TerminationWatchdogAkkaHostingTests — real AddAkka host + production cluster bootstrap +
GracefulClusterLeave: Leave(self)/Down(self) => exit 1 (both fail on the old logic); host StopAsync
and StopApplication-while-running => no exit. Live gate on windev SCM passed (7031 + restart; old
logic => Stopped, exit -1, no recovery; sc stop => clean stop).
2026-12-03 11:53:42 -05:00
Joseph Doherty 7a6e623485 fix(galaxy): #991 review — refuse SecuredWrite/VerifiedWrite locally with BadUserAccessDenied; gateway caller refusals are access refusals
G-1 routed secured/verified writes to WriteSecured, which cannot succeed (no AuthenticateUser
identity, no supervisory advise for it, the key needs invoke:secure), and the gateway's
refusal surfaced as BadCommunicationError.

- WriteOneAsync refuses SecuredWrite/VerifiedWrite BadUserAccessDenied before AddItem/advise/
  Write (one Warning per attribute, no health impact). InvokeWriteSecuredAsync removed until a
  real per-caller identity flow exists.
- gRPC PermissionDenied/Unauthenticated on the write or its supervisory advise ->
  BadUserAccessDenied (handle still forgotten; not counted as advise_failed).
- The classification seed is KEPT: it is what makes the refusal local. Unseeded, a secured
  attribute takes the supervisory raw path and the refusal would rest on MXAccess answering
  MX_E_SecuredWrite (1012) to a supervisory write, a code no live capture has shown.
- docs/drivers/Galaxy.md + Configuration.md updated.
2026-12-03 11:52:22 -05:00
Joseph Doherty f7a0dad7e3 fix(mqtt): #988 review — deterministic primary-host claim id per (hostId, group) + re-assert over a foreign OFFLINE
The M-3 fix made the blank-clientId claim id random per instance, breaking single-claim
exclusivity on a redundant pair: a Secondary cold-starting before its cluster join claimed
alongside the Primary, and its stand-down OFFLINE was left retained, newer than the
Primary's ONLINE, with nothing to correct it.

- Claim id = spbhost-<12 hex of SHA-256(hostId, groupId)>: a pair shares one id (broker
  takeover keeps the claim single; the evicted Primary reconnects and re-asserts), distinct
  groups/hosts differ; 20 chars.
- The claim subscribes to its own STATE topic. An OFFLINE seen while the claim is held (its
  own stand-down detaches first, so the echo is ignored) is re-asserted: ts <= session ts ->
  republish the session's ONLINE; newer ts -> fresh claim whose timestamp out-dates it
  (Sparkplug 3.0 edges ignore older STATE). Coalesced, <= 1 per 2 s. Reconnect re-subscribes
  before republishing so the takeover's leftover is seen.
- MiniBroker can inject a PUBLISH and records SUBSCRIBE filters; live pair test against the
  Mosquitto fixture.
2026-12-03 11:49:06 -05:00
Joseph Doherty ee9aa30ec0 fix(scripting): {{equip}} substitution escapes the RawPath it pastes into the string literal
A RawPath segment may contain backslash, quote, braces, line breaks or non-ASCII text.
SubstituteEquipmentToken pasted it raw into a regular C# string literal, so a device named
de\qv failed to compile and x\vy silently read a different tag path (\v became a vertical tab).

The paste is now encoded (EscapeForRegularLiteral) and the <RefName> / dependency refs are
decoded (TryDecodeRegularLiteral), so GetTag receives the exact RawPath at both compose seams
and the mux subscribes to the real key. The path-literal regex is escape-aware. The Monaco
OTSCRIPT_EQUIPREF diagnostic and completion share the same scan/escape. The deploy gate's
SubstitutionPreservesCompilation is now a verified round trip, so its pinned device-name case
flips from rejected to accepted.
2026-12-03 11:40:17 -05:00
Joseph Doherty 84789b33f3 Merge #971 follow-up: deploy-time script compile gate (allow-list refusals block the deploy, Error mode default) 2026-12-03 11:29:56 -05:00
Joseph Doherty 6e912bb070 feat(deploy): #971 follow-up deploy-time script compile gate
The deploy gate never compiled scripts, so a stored script the #971 allow-list
now refuses only failed after the deploy (VirtualTag/Calculation Bad "sandbox
violation", scripted-alarm load failing for every alarm on the node).

- Core.Scripting.Abstractions: IDeployScriptChecker (Roslyn-free) + request/result
  records; ScriptContextKind moved here (same namespace).
- Core.Scripting: ScriptEvaluator.Verify shares a private BuildCheckedCompilation
  factory with CompileToImage (wrap, injection guard, sandbox compile,
  ForbiddenTypeAnalyzer; no stack-guard rewrite, no emit). RoslynDeployScriptChecker
  checks per seam (VT/Calc as VirtualTagContext->object?, passthrough/blank skipped;
  predicates DependencyExtractor first then AlarmPredicateContext->bool), caches by
  (compile identity, SHA-256), parallel, bounded.
- ControlPlane: DeployScriptGate collects enabled VTs / enabled alarm predicates /
  Calculation tags, resolves {{equip}} through EquipmentReferenceMap exactly as the
  compose seams do (template compiled once when SubstitutionPreservesCompilation,
  else the resolved source), groups findings per script naming its users.
  AdminOperationsActor warms the cache before the snapshot transaction and runs the
  authoritative pass on the same snapshot; Deployment:ScriptCompileGateMode =
  Error (default) | Warn | Off; an absent checker or an internal failure never blocks.
- Host binds RoslynDeployScriptChecker on admin nodes.
- Docs: VirtualTags.md (gate + upgrade note), ScriptEditor.md, security.md, CLAUDE.md.

Found while testing: {{equip}} substitution pastes RawPaths into C# literals
unescaped, so a segment containing \ or " breaks (or silently alters) the
script; the gate now reports it at deploy.
2026-12-03 11:29:32 -05:00
Joseph Doherty f111d14bfb Merge #995: alarm predicates compiled once outside the gate, node-indexed stood-down items, kept drivers not re-subscribed, artifact parsed once, VirtualTag/Calculation evaluation coalesced 2026-12-03 11:16:21 -05:00
Joseph Doherty e6bfbdb6e5 fix(runtime): #995 a deploy no longer re-subscribes untouched drivers, and apply-time artifact work runs once off the pinned thread
R-11: DriverHostActor skips the deploy bulk push for a kept child whose seeding
fingerprint (value refs + raw/UNS fan-out + historization + alarm refs) is unchanged
and none of whose refs gained a mux consumer (VirtualTag / scripted alarm /
IDependencyConsumer driver). Skipped drivers are re-pushed when the address-space
outcome reports a rebuild (new additive RebuildCompleted.AddressSpaceRebuilt,
default true), degraded, timed out, or the apply threw. Boot/restore still push all.

R-14: ParsedDeploymentArtifact memoises the data projection + its validation per node
id (a throw re-thrown to every caller), and the row parsers skip it when the three data
arrays are empty. OpcUaPublishActor hashes the artifact once (RebuildAddressSpace.
ArtifactRevision) and reads the cluster redundancy mode from the plan step's parse
instead of a second parse on the pinned thread. InjectScriptSource skips JsonNode.Parse
for tag configs without a scriptId.
2026-12-03 11:09:59 -05:00
Joseph Doherty 58b26b5fd0 Merge #1002: StopChild clears comms latch + timer, kept alarm marks replayed, recorder catch-up uncapped, HistoryRead bad interval refused, VirtualTag host re-applied after restart, EffectiveName everywhere 2026-12-03 11:08:24 -05:00
Joseph Doherty 070fd493f9 fix(runtime): #1002 StopChild drops comms latch/audit + holds health ledger; deferred known marks kept for kept conditions; backlog drain re-ticks; per-driver source index; unconvertible ProcessingInterval is BadInvalidArgument; VirtualTagHost re-applied after restart; empty DisplayNameOverride = tag name
Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 11:08:07 -05:00
Joseph Doherty 9279078885 Merge #999: shelve expiry emits Unshelved first, script-owned timeouts surface as themselves, pipeline timeout visible to breaker, resilience config fallback, backoff floor, codec exceptions, worker frame cap split 2026-12-03 11:07:19 -05:00
Joseph Doherty 2827a4c3bf fix(calculation): #995 change-triggered evaluations coalesce latest-wins per calc tag, so a poll cycle evaluates once against all its new inputs and the queue is bounded by the tag count
At most one evaluation is pending per calc tag; a re-trigger only moves its
timestamp forward and the dependency snapshot is taken when the pump dequeues
it. Previously every dependency arrival enqueued a separate evaluation per
dependent with a trigger-time snapshot: k inputs of one cycle ran k times
(publishing intermediates computed from mixed old/new inputs) and the queue had
no bound when triggers outpaced the pump. The out-of-process batch pump now
dequeues every pending tag once per batch.
2026-12-03 11:05:32 -05:00
Joseph Doherty a1b8312ea4 fix(virtualtags): #995 inputs held behind a slow run coalesce into one evaluation, array outputs dedup by value, and a failed source binding retries only the unbound tag with backoff
R-19: VirtualTagActor folds inputs that arrive during an in-flight evaluation
(latest value per input) and evaluates once when it completes, instead of
stashing one message per trigger and replaying one script run each (unbounded,
O(M^2) re-stash hops). One-dimensional array results compare element-wise in
the value dedup, so an unchanged array output is not republished, re-routed or
historized on every evaluation.

R-17: VirtualTagHostActor's source-binding retry re-attempts only the tags whose
binding failed (spawning the child / publishing the disabled status on
success), 250 ms doubling to 5 s, instead of re-delivering the whole
ApplyVirtualTags every 250 ms (quarantine reset, re-assert of every child,
BadOutOfService republish, cycle-graph recompute each time).
2026-12-03 11:05:32 -05:00
Joseph Doherty 677a680178 fix(opcua): #995 U-5 removing a node sweeps only that node's stood-down items, not every tracked item
Whenever any monitored item was stood down, each TombstoneMonitoredNode ended with a full scan of
_liveItems + _eventItems, and the rebuild ran it once per monitored node plus once more: removals were
O(nodes x items) under the node-manager Lock. Tracked items are now indexed by NodeId (a superset index
added on track, dropped on client delete, re-validated and pruned by the sweep, so it never has to
follow the Suppressed flips); a per-node sweep is a lookup, and TombstoneAllMonitoredNodes skips the
per-node sweep in favour of its single unfiltered one.

Measured (counter): removing 200 stood-down nodes one by one visited 20,300 tracked items before,
~201 after.
2026-12-03 11:02:44 -05:00
Joseph Doherty de185802d7 Merge #996: Deployment reads skip ArtifactBlob, narrow data-connections loader, coordinator ack writes off-thread, AdminOps I/O off mailbox, HistoryReadEvents page cap, reservations page bounded 2026-12-03 10:59:06 -05:00
Joseph Doherty ea976ffa81 fix(perf): #996 Wave 4 — blob-free health probes, narrow data-connections load, off-thread coordinator acks + AdminOps audit, events page cap, capped reservations page
C-6: DeploymentQueries projects Deployment without ArtifactBlob (DbHealthProbe, readiness, ClusterOverview, DriverHost boot).
C-11/A-5: DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync + one-parse-per-artifact LoadAppliedAsync + capped pickers.
H-6: ConfigPublishCoordinator persists acks off the actor thread (AckPersisted); deadline backlog kicked in parallel.
H-3: Restart/Reconnect reply = dispatch; ConfigEdit audit written off-mailbox, failure logged not surfaced.
U-6: ServerHistorian:MaxEventsPerRead (default 10000) pages HistoryReadEvents; advertised as MaxReturnEventValues.
A-8: /reservations active-only by default, projected, capped at 200.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 10:58:50 -05:00
Joseph Doherty 8e91d6503d fix(script-runner): #999 K-5 script-worker frames are cut at the frame cap; one oversized evaluation fails alone instead of killing the worker 2026-12-03 10:56:40 -05:00
Joseph Doherty e99df14665 fix(scripted-alarms): #995 K-3 a deploy reuses unchanged alarm predicates and compiles new ones outside the engine gate
Every LoadAsync cleared the compile cache and recompiled every predicate serially while holding _evalGate
(and, uncontended, on the ScriptedAlarmHostActor thread). Now the compile phase runs first on the thread
pool (bounded parallelism) without the gate, reusing source-hash-cached compiles; only the swap holds the
gate, and CompiledScriptCache.RetainOnly disposes just the retired predicates' ALCs. Out of process the
host's validation compile is remembered per source too.

Measured, 500 alarms (distinct predicates, in process, Release): reload of unchanged defs 1303 ms -> 15 ms;
one edited 1040 -> 16 ms; all-new reload 1002 -> 748 ms; ack issued during that reload waited 800 -> 1 ms.
2026-12-03 10:54:15 -05:00
Joseph Doherty 9d3d0f3ae9 Merge #997: UNS duplicate sibling names friendly + race-safe, Galaxy ack password kept on blank, reaper drains on stop, silent node telemetry not redialled, key delete reloads 2026-12-03 10:52:36 -05:00
Joseph Doherty 3773509888 fix(adminui): #997 duplicate sibling names, Galaxy ack password blanking, browse reaper drain, silent-node telemetry dial, key-delete cleanup now behave correctly
A-3: UnsTreeService pre-checks sibling (cluster,area,line) names on create/update/import, catches DbUpdateException, validates column lengths.
A-4: blank ack password keeps the stored one; first-time blank refused.
A-6: BrowseSessionReaper drains sessions in a finally on shutdown.
A-7: node flushes response headers; central treats them as established; deadline warning throttled.
A-9: key delete always reloads and names leftover ack secrets when cleanup fails.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 10:52:19 -05:00
Joseph Doherty 3cc05b92c1 Merge #998: ZTag/SAPID + historian-tagname duplicate gate rules, DanglingReference rule, filtered unique indexes fixed, RowVersion on ClusterNode/ServerCluster 2026-12-03 10:50:14 -05:00
Joseph Doherty 486628cf0a fix(config): #998 deploy gate rejects duplicate ZTag/SAPID, duplicate owned historian tagnames and dangling parent links; NULL-keyed unique indexes enforced; node/cluster edits carry a RowVersion
C-3 ZTag/SAPID uniqueness enforced from the draft (reservation ledger has no writer); UI/doc claim corrected.
C-5 HistorianTagnameDuplicate (owned tags, per cluster, case-insensitive; readOnly exempt).
C-8 UX_NodeAcl_PrincipalScope / UX_LdapGroupRoleMapping_Group_Cluster unfiltered (migration with duplicate pre-check) + friendly service/page checks.
C-9 RowVersion on ClusterNode/ServerCluster, edit pages use it; node delete removes its NodeDeploymentState rows.
C-10 DanglingReference rule; dead PathTooLong/EquipmentUuidImmutable rules + PriorEquipment/Enterprise/Site inputs deleted.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 10:49:57 -05:00
Joseph Doherty 6822fd3f5c Merge #977: restart restores last Applied deployment, planner covers every composition field, degraded/revision/restart bookkeeping, superseded deployment closed 2026-12-03 10:47:07 -05:00
Joseph Doherty a0f41a30d8 fix(deploy): #977 deploy/apply bookkeeping — planner sees every composition field, degraded/restarted applies repair, failed deploys restore the last applied revision, superseded deployments close
- U-2: planner diffs the rich scripted-alarm plans; an Enabled flip is a surgical add/remove of the one
  condition, a Name/AlarmType/Severity edit on an enabled alarm rebuilds.
- U-3: planner diffs UNS Areas/Lines in full; a Line moved to another Area rebuilds, added/removed
  Areas/Lines are surgical.
- U-9: removing the last VirtualTag in a FolderPath removes the sub-folder in place.
- AddressSpacePlannerFieldCoverageTests reflects over every composition list + record field.
- R-4: while the last applied composition is degraded, a non-rebuild apply re-ensures the full composition.
- R-20: a supervision restart of OpcUaPublishActor forces its first apply to rebuild.
- R-1: Direct boot with a Failed/orphan newest row restores the newest Applied deployment, then the cache.
- R-15: the revision advances after the last throwing apply step; a throw marks it unconfirmed.
- H-4: ConfigPublishCoordinator closes a superseded in-flight deployment (TimedOut + reason).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 10:46:47 -05:00
Joseph Doherty 209dd955b0 Merge #1000 + #1001: Client.Shared failover keeps retrying + map reset + batched subscribe; OTOPCUA0001 covers acquisition + write-outcome capabilities 2026-12-03 10:46:28 -05:00
Joseph Doherty 291be3c55c fix(client): #1000 failover retries with backoff, reconnect clears the subscription map, subscriptions batch into one round trip
S-4: a failover that finds every endpoint down stays Reconnecting and cycles the endpoints with a
1s..15s capped backoff until it connects or the connection epoch moves on; the backoff is woken by
the epoch so it never pins the failover slot. S-3: ConnectAsync/DisconnectAsync/landing Disconnected
clear the recorded subscriptions, so a re-subscribe of the same node creates a monitored item.
S-12: SubscribeManyAsync + ISubscriptionAdapter batch add (one CreateMonitoredItems), used by the CLI
subscribe and the failover replay. CLI subscribe/alarms print connection transitions.
2026-12-03 10:46:13 -05:00
Joseph Doherty 3795cd5f21 fix(resilience): #999 K-6 a pipeline timeout counts toward the circuit breaker and the status tracker 2026-12-03 10:43:35 -05:00
Joseph Doherty 8e57311f97 Merge #993: Gateway read refusals keep historian healthy, QuestDB capped reverse events read finds its cut first, allocation-free time-weighted aggregate, QuestDB fixture visibility wait 2026-12-03 10:40:49 -05:00