Commit Graph

671 Commits

Author SHA1 Message Date
Joseph Doherty d81990bcbf fix(scripting): #1104 a jagged-array script result is refused identically in both runners
int[][] / byte[][] used to be the one result divergence left after #1100: in process
ScriptResultMaterializer passed it (SdkValueBoundary.FromClr carries it as an array of Variants),
while the worker's wire has no nested-array tag and answered "unsupported type". A script-fed node
has a scalar DataType, so a Variant-of-arrays value is not what it declares either; not documented as
a feature anywhere (only noted as the known divergence). Decision: refuse, via the shared rule.

- IsPublishable: a 1-D array's element must be a PublishableScalarTypes scalar (no recursion).
- EnsurePublishable: a nested array gets its own reason, still "... which an OPC UA node cannot
  carry: an array of arrays ...", with a flatten hint (SelectMany). Same "script threw: ..." text in
  both runners.
- SdkValueBoundaryScriptResultTests: int[][] leaves the rule==FromClr theory; a separate fact pins
  the one deliberate difference (FromClr takes it, the rule refuses).
- ParityTests: "jagged array" + "jagged byte array" rows. ShadowModeTests census: the jagged script
  now MATCHES; the unsupported_type mismatch is exercised by a decimal INPUT (design §14 #11), the
  real remaining worker-only refusal.
- ContainmentTests.Unsupported_input_and_result_types: jagged now expects the materializer reason.

Mutation: restoring the recursive element check fails 4 tests (2 parity rows, shadow census,
containment unsupported-type).

Behaviour change: a value script returning a jagged array now fails (Bad + script log) in process
too, instead of publishing a Variant array onto a scalar-typed node.
2026-12-04 20:31:25 -05:00
Joseph Doherty ce0133b03c Merge gRPC data publish-path follow-up (#1098): ~2.2 -> ~1.7 KB/value — hub read hands its sample to the delivery, FrameSlotWindow + single-waiter re-arm fix, scalar latest-sample cache keeps the update, alloc-free frame sizing/dispose; pooling declined (ownership leaves the session) 2026-12-04 17:48:39 -05:00
Joseph Doherty 1523a97708 perf(grpc-data): #1098 cut ~0.55 KB per projected value without pooling
Release, 10k cohort, 5 runs each: 2.21-2.31 KB -> 1.68-1.72 KB per delivered value, process-wide.

- A live value takes over its hub read's sample lease and charge (CachedSourceRead.TryTransferSample:
  same amount, same budget; the read keeps its source guard until disposed) instead of retaining a
  second copy and reserving a second charge. Re-stamped with the item's serving only when it differs.
- ValueLease holds a reference on the item's SharedSessionLease directly (no Hold per value); the
  release order (charge, item, snapshot) and once-only guard are unchanged.
- The latest-sample cache keeps the published update itself for a scalar payload (arrays still copied).
- The cohort's frame window is a FrameSlotWindow (SemaphoreSlim semantics: over-release throws, a
  cancelled wait takes no slot) on one reused SlotWaiter and one registration per attempt; the pump
  waited for nearly every frame, each wait allocating a task, state machine and registration.
- SlotWaiter (moved out of the session) now makes a re-arm wait out a signaller still inside SetResult,
  so the old signal cannot complete the next wait; it is hot now (one wait per frame under load).
- Indexed loops for the pump's frame sizing and DataSubscriptionValues.Dispose (no boxed enumerators).
- ClientFilterState keeps its baseline's compared fields and value lease, not a re-wrapped sample.

Pooling ValueLease/ValueDelivery (~150 B) is declined: the lease escapes as the public
DataSubscriptionValues.ResourceLease and a delivery's Gate is handed to the gRPC sink as a publication
guard, so a recycled object could release or authorize for another value.

Tests (GrpcData1098OwnershipTests) fail on a read releasing a transferred sample, a lease not holding
its item, a frame-window double release / lost wakeup, and a re-arm racing a completing signal.
2026-12-04 17:48:12 -05:00
Joseph Doherty d28ea4a66a refactor(scripted-alarms): #1101 the alarm load refuses a predicate's tag paths through ScriptCompileRules, not its own copy of the rule
ScriptedAlarmEngine.PreparePredicates called DependencyExtractor and refused on !IsValid — a second copy of
the rule ScriptCompileRules owns since #1083 (RefusesNonLiteralTagPaths / TagPathFindings), which the deploy
gate and the editor read. Now ScriptCompileRules.PathRefusals(kind, source, extraction?) is the one verdict
and text ("dependency extraction rejected — …") for both the gate (RoslynDeployScriptChecker) and the engine.
TagPathFindings takes an optional extraction so the engine, which still needs the extraction's Reads, parses
once. Behaviour identical: for AlarmPredicate every rejection refuses with its extractor message, joined "; ".

ScriptedAlarmEngineTagPathRuleParityTests runs 8 predicates (literal, two literals, variable, concatenated,
interpolated, empty, two refusals, dynamic beside a literal) through the gate and a real engine load and
asserts refused <=> refused with the gate's exact text; plus a control that the table holds both outcomes.
Mutation: an engine rule that refuses only empty paths fails 6 of 8 rows.
2026-12-04 17:38:16 -05:00
Joseph Doherty 9dbccf231e fix(scripting): #1100 a script result is what an OPC UA node can carry, in both runners — Guid crosses the wire, unpublishable types are refused alike
Where an in-process result really ends up: VirtualTagActor -> VirtualTagHostActor -> OpcUaPublishActor ->
OtOpcUaNodeManager.WriteValueLocked -> SdkValueBoundary.FromClr (VariantHelper.TryCastFrom). Probed against
SDK 2.0.1: Guid / Guid[] become an OPC UA Guid scalar/array; KeyValuePair<,>[] (a returned Dictionary),
decimal, enum, TimeSpan, char, DateTimeOffset, tuples, Nullable<T>[] and rank>1 arrays are refused, so the
node write threw, OpcUaPublishActor logged a Warning, and the node kept its PREVIOUS value and status (a
silent freeze, possibly under Good) while the worker answered "unsupported type".

Decision, per type, by what a client can see:
- Guid (scalar + 1-D array): representable -> the wire gains an additive GUID tag (15, `bytes g = 10`,
  16 ToByteArray bytes; a wrong length is a protocol fault). Guid INPUTS cross too. protocol_version stays 1:
  the worker ships in the host's script-worker/ folder, and an unknown tag already fails closed.
- Everything FromClr refuses: refused identically in both runners by ScriptResultMaterializer, inside the run,
  with one reason ("script threw: The script returned a value of type 'KeyValuePair<Int32, Double>[]', which
  an OPC UA node cannot carry; return ..."). A lazy unpublishable sequence is refused before it runs.
  ScriptResultMaterializer.PublishableScalarTypes / IsPublishable own the set.

Pins: SdkValueBoundaryScriptResultTests (OpcUaServer.Tests, new Core.Scripting ref) checks IsPublishable ==
"FromClr takes it" over 34 values; ProtocolTests checks the wire carries every publishable type scalar + array;
ParityTests gains guid / guid array / guid list / dictionary / KVP[] / lazy KVPs / KVP / decimal / decimal[] /
enum / TimeSpan / char[] / 2-D rows, a Guid unboxing row, and a positive+negative control. Mutations: with the
type check disabled 11 parity tests fail; with Guid not encoded 9 protocol/parity tests fail.

Behaviour change: a value script returning a Dictionary, decimal, enum, TimeSpan, char or tuple now fails
(Bad + script log) in process too, instead of "succeeding" and leaving its node frozen. Remaining divergence:
a jagged array (publish path carries it as Variant[], worker answers "unsupported type") — follow-up.
2026-12-04 17:27:22 -05:00
Joseph Doherty 50a2acb2be Merge scripting follow-ups: dynamic tag paths are editor warnings where the gate accepts them, one rule owns the split (#1083); returned collections materialised + capped identically in both runners, heartbeat tests sized for whole-process stalls (#1092); Calculation-mode {{equip}} hover (#1093) 2026-12-04 15:46:29 -05:00
Joseph Doherty 61546d5aab fix(scripting): #1092 a returned concrete collection (List<T>, HashSet<T>, ...) is materialised into the same typed array in both runners
ScriptResultMaterializer returned a non-array ICollection as-is (capped by Count only), so
in process the host got the List<double> itself while the out-of-process worker, whose wire
carries arrays but no collection type, answered "unsupported type" for the same script.
Every non-array, non-string sequence now goes through the one materialisation: a collection
is held to Scripting:MaxResultElements by its Count before it is copied, then becomes T[]
of its IEnumerable<T> element type; an open element type (List<object>, List<List<int>>) or
none (ArrayList) is refused like the lazy equivalent. Both runners give double[] for a
List<double>.

ParityTests.Result_materialisation_and_the_element_cap_agree gains list / at-cap / over-cap
/ hash set / queue / List<object> / nested-list rows plus a positive control (6 rows + the
control fail against the old materializer). ContainmentTests' "unsupported result type"
example moves from List<int> (now int[]) to KeyValuePair<int,int>.

Behaviour change: a script returning List<object> (or another open element type) now fails
the run (Bad + script log) in process too, as the lazy form already did.
2026-12-04 15:14:16 -05:00
Joseph Doherty bd4fff6444 fix(scripting): #1083 a dynamic tag path is an editor error only where the gate refuses it (predicate), a warning in value/Calculation mode; #1093 Calculation-mode {{equip}} hover says it is refused
#1083: OTSCRIPT_DYNPATH was an error in every editor mode while the deploy gate refuses a
non-literal tag path only for a scripted-alarm predicate (editor stricter than the gate).
Decision: do not make the gate stricter (it would reject configurations that deploy today).
ScriptCompileRules now owns the split — RefusesNonLiteralTagPaths(kind) and
TagPathFindings(kind, source), each finding carrying Refuses — the gate refuses on exactly
those findings and the editor draws them as errors (8) and the rest as warnings (4), whose
text says what the path does at runtime (not a declared input: not subscribed, does not
re-trigger, reads BadNodeIdUnknown unless also read literally). DependencyRejection gains
Kind + MethodName for that wording. EditorGateParityTests carries dynamic / concatenated /
interpolated / empty paths in all three modes (14 rows fail with the old always-error
severity).

#1093: hovering a {{equip}} path literal in Calculation mode showed the VirtualTag
"resolves ... when deployed" text, contradicting the OTSCRIPT_EQUIPCALC marker on the same
span. It now says the token is refused in a Calculation script and why (no owning
equipment, never substituted, the gate refuses it). The {{equip}} hover no longer needs a
tag catalog.
2026-12-04 15:02:41 -05:00
Joseph Doherty 8e2a793000 feat(grpc-data): #1084 secured writes over a data connection need an export-level opt-in; #1091 Galaxy reports gRPC write outcomes definitively
#1084 - DataExport.AllowSecuredWrites (default false; migration AddDataExportAllowSecuredWrites, a bit NOT NULL DEFAULT 0
column, no constraint => no MigrationPreChecks twin; the preflight's legacy-schema tolerance covers the missing column).
- Valid only with Write: validator code DataExportSecuredWriteInvalid at authoring, the deploy gate and on a deployed
  row (an artifact row breaking it fails closed), modelled on AllowGalaxyServiceAck.
- LocalExportCatalog keeps it per rule (counts only with Write) and answers AllowsSecuredWrite(principal, node): an
  export of the principal, in the node's realm, granting Write, opted in, whose root contains the node.
- DataWriteExecutor stamps DataWriteAdmission.AllowsSecuredWrite (new, default false) from the catalog generation that
  admitted the write (re-checked by the dispatch gate's commit), never from the request.
- DriverInstanceActor.RichCaller returns null without it, so the driver gets NO caller: the driver option
  MxAccess.SecuredWritesOverDataConnections alone no longer lets a forwarding consumer cluster's link key write
  SecuredWrite attributes. Fail closed by default.
- AdminUI export editor: "Allow secured writes under this peer's key identity" checkbox (enabled only with Write).

#1091 (a) - GalaxyDriver implements IWriteOutcomeCapability + ICallerAwareWriteOutcomeCapability. GalaxyWriteOutcomes
maps BadUserAccessDenied and the OnWriteComplete verdicts BadNotWritable/BadTypeMismatch/BadOutOfRange/
BadConfigurationError to DriverConfirmedFailure, Good to AcceptedUnconfirmed (a provisional Good is indistinguishable),
everything else to OutcomeUnknown. A refused secured write is now a definite BadUserAccessDenied, not OutcomeUnknown.
- RunRichWriteAsync precedence: caller-aware outcome overload (caller present) -> outcome overload -> ICallerAwareWritable
  (caller present) -> IWritable. Both earlier behaviours kept; the OPC UA path is unchanged.

Tests (each failed before its fix where applicable):
- End to end through the runtime path (artifact -> catalog -> DataWriteRuntime executor -> ActorDataWriteRoute ->
  DriverInstanceActor behind the real dispatch gate -> real GalaxyDriver): export opt-in x driver option matrix; only
  both commit as the key's identity, either alone refuses BadUserAccessDenied definitively with no identity lookup.
  Ignoring the flag in RichCaller fails 3 tests.
- Catalog scope (root containment, Write, principal), artifact round-trip + fail-closed row, validator, migration SQL +
  no pending model changes, AdminUI checkbox enable/save (bUnit), actor precedence, Galaxy outcome mapping.
- ScriptForeignKeysAndExternalIdUniquenessMigrationTests now migrate to THEIR migration, not the latest.

Docs: DataConnections.md (two-gate table), Galaxy.md, security.md, rules/drivers.md.
2026-12-04 14:58:16 -05:00
Joseph Doherty 2f22003061 feat(analyzers): #1091 OTOPCUA0001 guards the caller-aware write capabilities
- ICallerAwareWritable and the new ICallerAwareWriteOutcomeCapability join the guarded-interface list. Each derives
  from a guarded interface but declares its OWN member, which is not an implementation of the base's, so
  callerAware.WriteAsync(writes, caller, ct) on an interface or concrete receiver passed unflagged.
- ICallerAwareWriteOutcomeCapability (Core.Abstractions.DataConnections): IWriteOutcomeCapability on behalf of a
  WriteCaller, for the gRPC data-connection write path (used by the Galaxy driver, next commit).
- Tests: unwrapped caller-aware WriteAsync trips on interface AND concrete receivers; the caller-aware outcome
  overload trips unwrapped and passes wrapped (positive control). Both failed (0 diagnostics) with the two
  entries removed from the list.
2026-12-04 14:58:00 -05:00
Joseph Doherty 29ad36c028 feat(galaxy): #1074 secured writes over gRPC data connections are a separate opt-in, default off
- WriteCaller gains an additive Origin (WriteCallerOrigin: Unspecified (default) | OpcUaSession | DataConnection),
  stamped by the runtime at the receiving seam: OtOpcUaNodeManager -> OpcUaSession, the rich (gRPC data-connection)
  write path -> DataConnection. Never parsed from the principal/key.
- New driver-config option MxAccess.SecuredWritesOverDataConnections (default false; factory key
  mxAccess.securedWritesOverDataConnections; AdminUI "Also for gRPC data-connection writes", owned path). The
  Galaxy driver gives a caller an identity source only in ApiKeyIdentity mode AND for an allowed origin:
  OpcUaSession always, DataConnection only with the option, Unspecified never (fail closed). Off => a secured write
  over a data connection is refused exactly as before #1074 (local BadUserAccessDenied, no identity lookup; the gRPC
  caller sees the same OutcomeUnknown as before).
- Tests: option off refuses a gRPC write end to end into the real GalaxyDriver (with an OPC UA positive control on
  the same driver); option-on end-to-end kept; driver-level origin matrix incl. Unspecified; factory binding; AdminUI
  round-trip; node-manager callers now carry OpcUaSession.
- Docs: Galaxy.md (origin table, opt-in, forwarded-write delegation caveat, live-gate leg), security.md,
  DataConnections.md, Configuration.md, rules/drivers.md.
2026-12-03 16:51:26 -05:00
Joseph Doherty be58573822 feat(grpc-data): #1074 gRPC data-connection writes carry the connection's caller to a caller-aware driver (Galaxy SecuredWrite)
- DriverInstanceActor's rich write path (RouteRichWrite -> WriteAttributeWithOutcome) now hands an
  ICallerAwareWritable driver WriteCaller(principal, apiKeyId) taken from the DataWriteAdmission, i.e.
  the connection's authenticated DataAuthenticatedContext (never the request payload), re-checked by the
  dispatch gate's commit. Same caller shape as the OPC UA path (#1017). No proto change: the identity was
  already server-side. IWriteOutcomeCapability keeps precedence (no driver implements both today).
- Fail-closed unchanged: Galaxy resolves only the key's own identity (no fallback); no identity => refused.
- Tests: rich write reaches the caller-aware overload with the admitted principal/key (failed before: the
  caller-less overload was used); OPC UA WriteAttribute and gRPC rich write deliver equal WriteCallers; a
  real GalaxyDriver in ApiKeyIdentity mode resolves the connection key's identity end to end.
- Docs: Galaxy.md (gRPC path, federated writes run as the LINK key's identity, refusal reported as
  OutcomeUnknown on the legacy path), DataConnections.md, security.md, rules/drivers.md.
2026-12-03 16:51:26 -05:00
Joseph Doherty 00ac75e33a Merge scripting follow-ups: one shared compile rule for editor + gate, CS0161/injection now flagged in the editor (#1063), worker applies the result materialisation cap (#1064), {{equip}} in Calculation scripts refused at gate + editor (#1065) 2026-12-03 16:49:40 -05:00
Joseph Doherty 73f49eaf32 fix(scripting): #1063 one compile-refusal authority for editor and deploy gate (ScriptCompileRules + the runtime's own wrapper text) — CS0161 and wrapper injection are now flagged in the editor; #1065 {{equip}} in a Calculation script is refused by the gate and by a new Calculation editor mode
#1063: the Monaco diagnostics dropped every Roslyn error located in the synthesized
wrapper as 'phantom', so CS0161 (not all code paths return a value, pinned on Run)
passed the editor and failed the deploy gate. ScriptCompileRules (Core.Scripting) now
states which diagnostics refuse (every Error, wherever located; LMX001/002 injection)
and which sources skip the compile (blank/passthrough value scripts); ScriptEvaluator
and the editor both use it, and the editor wraps with ScriptEvaluator.WrapperPreamble/
WrapperSuffix instead of its own copy. Wrapper-located refusals are drawn on the
script's last line. EditorGateParityTests runs one corpus through editor and gate in
all three modes.

#1065: a Calculation tag is raw/device-level with no equipment and its seam never
substitutes {{equip}}, so such a script deployed clean and read Bad forever. Refused
rather than substituted: EquipTokenLiteralScanner.FindInCalculation is run by
RoslynDeployScriptChecker for every Calculation use (before the passthrough shortcut,
outside the shared VT/Calc cache) and by the editor in the new 'calculation' mode
(Calculation tag editor; ScriptEdit defaults to it when a Calculation tag uses the
script).
2026-12-03 16:47:14 -05:00
Joseph Doherty ed6531a0bc Merge historian follow-ups: QuestDB WaitAsync give-up seam + tests (#1072), stalled alarm S&F queue qualified by historian reachability (#1071), QuestDB fixture prefix registry + stale sweep, 134 leaked tables dropped (#1062) 2026-12-03 16:36:40 -05:00
Joseph Doherty a06dc8dd9f fix(scripting): #1064 the ScriptWorker applies the in-process result rule — a returned lazy sequence is materialised inside the run and held to Scripting:MaxResultElements (Hello.max_result_elements), same value and same failure text in both runners 2026-12-03 16:35:01 -05:00
Joseph Doherty 0ae5240341 feat(historian): #1071 alarm S&F stall is qualified by historian reachability: an outage is HistorianUnreachable, not a stuck queue 2026-12-03 16:31:16 -05:00
Joseph Doherty 98dc4c24a1 refactor(sql): #1076 one shared Sql DriverConfig JSON options (Sql.Contracts SqlDriverConfigJson) for driver factory and deploy gate; parity test 2026-12-03 16:28:04 -05:00
Joseph Doherty 7c78a4f456 Merge gRPC data follow-ups (#1057): refuse LimitExceeded before ack, sibling invalidation no longer resets a snapshot, per-stream snapshot slots, ~20% fewer bytes per projected value; R2_S2 hold-stale test timing 2026-12-03 16:05:03 -05:00
Joseph Doherty 50a4887d83 Merge ControlPlane/core/authz follow-ups: coordinator DB writes off-thread + audit retry (#1051), resilience counts every failed attempt + zero-alloc scoped keys (#1052), AcquisitionSubscribe capability (#1047), audit drop metric + SCM restart test script (#1030), zero-alloc warm UNS ACL + unresolvable-ref backoff (#1053), flag-off revalidation fast path (#1033)
# Conflicts:
#	src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs
2026-12-03 15:47:13 -05:00
Joseph Doherty 17dac6a536 Merge ConfigDb follow-ups: script FKs + ZTag/SAPID filtered unique indexes, ExternalIdReservation retired (#1040/#1049, migration ScriptForeignKeysAndExternalIdUniqueness with pre-check), SqlNamedQueryInvalid deploy rule (#1058), read-only otopcua-preflight upgrade tool (#1013/#1015/#1021)
# Conflicts:
#	docs/VirtualTags.md
2026-12-03 15:42:25 -05:00
Joseph Doherty 288ca70c4a fix(sql): #1058 deploy gate refuses a named query the Sql driver would refuse at start (SqlNamedQueryInvalid)
The driver runs SqlNamedQueryRules.Describe over every queries entry with its provider at
construction, and one refused query fails the whole driver (every tag BadNodeIdUnknown). Since #974
that includes a T-SQL parse for SqlServer/Odbc/no-provider, so an Odbc query written in another
dialect (LIMIT, ILIKE, 'a'::text) that used to pass is refused after the upgrade. The gate now runs
the same rule over the same merged config (factory-equivalent JSON options), naming the instance.
Noted: a bare col::type PARSES as T-SQL static-member syntax and is accepted by both.
2026-12-03 15:41:21 -05:00
Joseph Doherty 36b90dfa31 Merge security follow-ups: host-side PE-cache signing, worker no longer holds the HMAC key (#1014); Akka remoting untrusted-mode + trusted-selection-paths by default, opt-in mutual TLS (#1003) 2026-12-03 15:40:32 -05:00
Joseph Doherty ef4e1668de feat(cluster): #1003 Akka remoting hardening — untrusted-mode on by default, mutual TLS opt-in
Follow-up of #973 (review 2026-12-02 A-1). New Cluster:Remoting section (AkkaRemotingOptions):

- UntrustedMode (default ON): akka.remote.untrusted-mode with trusted-selection-paths =
  every path this code base reaches by ActorSelection across nodes, enumerated from the Akka
  1.5.62 sources + src/: cluster core daemon + heartbeat receiver, remote-watcher, the DPS
  mediator, /user/{s} + /user/{s}/{s} for each ControlPlane singleton, /user/driver-host.
  Remote deployment and peer PoisonPill/Kill are dropped. Receive-side only, so a mixed
  old/new pair keeps working through a rolling upgrade. Drops (Akka logs them at Debug)
  become a Warning per path + otopcua.cluster.remoting.untrusted_drops.
  AdditionalTrustedSelectionPaths / UntrustedMode=false are the escape hatches.
- Tls (default OFF): mutual TLS on the DotNetty transport (PFX or store cert, mutual auth
  on by default, thumbprint pinning or chain validation, optional hostname check). Seeds and
  the diagnostics selection follow the transport scheme (akka.ssl.tcp); the bootstrap guard
  parses it. Validated at boot.

Proven on real clusters: pair formation, singleton via proxy + hand-over on leave, DPS, zero
drops; untrusted selection dropped (and delivered with the mode off); pinned TLS peers form,
an unpinned node cannot join; full two-node Host harness (deploys from both nodes,
diagnostics, node restart) with zero drops + positive control. Guards fail when a new
singleton or ActorSelection appears without its trusted path.
2026-12-03 15:35:56 -05:00
Joseph Doherty 6ea0f09614 perf(acl,grpc-data): #1053 alloc-free warm UNS ACL decisions; unresolvable configured refs back off; restart keeps the comms latch (decided)
U-8: a warm cached decision on a UNS node allocated 416-680 B/call ahead of the cache (live id-chain list, identifier
split, LINQ, segment array, string.Join key, DataCallerIdentity). Now 0 B: the live chain is cached per folder instance
(re-verified against the live ancestry every call), the generation hands out one segment array per path, the authorizer
keys its resolved cache keys on that array, reference variables key on their own identifier (scope = its split), and
the caller identity is built once per session identity.

R-25: ConfiguredProjectedInterestOwner re-ran discovery for an unresolvable configured reference every 1 s sweep forever;
a failed resolve now backs off 1 s doubling to 30 s (60 s unreachable: 61 discoveries -> 6). Publishing into the source hub
only for sources with interest is DECLINED: that cache answers a new subscription's first snapshot and projected Reads.

Restart comms latch (decided: keep): the nodes stay Bad across an operator Restart and the respawned incarnation must
re-publish them; the stopped child's PostStop announcement already re-latches and cancels the old audit. Pinned by test.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 15:31:38 -05:00
Joseph Doherty a6e5ae8aa2 perf(grpc-data): #1057 trim the projected publish path's per-value allocation; allocation-free catalog/subject resolve
Measured with GrpcDataWave3PerfTests (10k-item cohort, 100 source versions at 1k/s; numbers in the issue report).
- Core: MappedSubjectResolver.Resolve returns shared immutable resolutions (built once per subject) and compares
  scope/ancestry by index (no MappedSubjectResolution + 2 enumerators per call, several calls per value);
  DataOperationPolicy checks segments by index and builds its local scope key with one exact-length string.Create.
- Origin: LocalExportCatalog.TryResolve compares the view field by field instead of building 'view with { Address }'
  (and LocalAddress no longer copies an exactly-spelled address); the frame Eligible check peeks the latest READY
  version (PartitionedSampleHub.TryPeekReadyVersion) instead of retaining a second sample per value; TickAsync reuses
  worker-owned lists (interest groups, changes via SourceInterestLease.TryReadChanges(into), delivery slice via
  DeliveryScheduler.TakeSlice(into), due items) and the delivery index reuses one ready-list node per source.
- Consumer: PublishPacedAsync is a ValueTask; the cohort and RemoteSubscription walk frame items by index; renewal
  prunes expired witnesses in place.
2026-12-03 15:31:31 -05:00
Joseph Doherty c64b5ec654 Merge Galaxy/AdminUI/Client follow-ups: opt-in SecuredWrite under the caller's API-key Galaxy identity, VerifiedWrite still refused (#1017), Galaxy form keeps KeepAlive keys (#1045), explicit empty ack password (#1050), Client.UI batched recursive subscribe + CLI --reconnect-timeout exit 3 (#1048) 2026-12-03 15:29:27 -05:00
Joseph Doherty 13521354cc feat(galaxy): #1017 SecuredWrite attributes can be written as the calling API key's Galaxy identity (opt-in); VerifiedWrite stays refused
- MxAccess.SecuredWrites = Refuse (default, unchanged #991 local BadUserAccessDenied) |
  ApiKeyIdentity. Opted in, a SecuredWrite runs as the calling key's own /api-keys Galaxy
  identity (ResolveKeyIdentityAsync: no fallback account; anonymous / no identity / broken
  identity refused before the wire): own plain-advised handle (apart from the raw path's
  supervisory handle) -> AuthenticateUser every write -> WriteSecured(userId, 0), the sequence
  mxaccessgw live-captured committing. Auth failure / user id 0 -> BadUserAccessDenied; password
  only in the AuthenticateUser command, scrubbed from every log. Identity resolved once per batch.
- VerifiedWrite is refused in every mode: an OPC UA Write carries no verifier (MXAccess refuses
  no verifier 1008 / self-verifier 8018), and a stored verifier would defeat the two-person rule.
- Caller plumbing: WriteCaller + optional ICallerAwareWritable (Core.Abstractions); node manager
  passes principal + key id -> IOpcUaNodeWriteGateway caller overload (default drops it) ->
  RouteNodeWrite.Caller -> WriteAttribute.Caller -> ICallerAwareWritable. The gRPC data-connection
  write path carries no caller yet (secured writes refused there).
- AdminUI Galaxy form 'Secured writes' select (owned path); enum serialises as its name; factory
  refuses an unknown value. Docs: Galaxy.md design + live-gate checklist. Not live-gated.
2026-12-03 15:29:02 -05:00
Joseph Doherty 9bdfe796f5 Merge driver follow-ups A: Modbus RTU response correlation + cancel redial + rebuild e2e (#1029/#1055), MTConnect malformed-item BadDecodingError + cross-chunk condition severity (#1055/#1037), TwinCAT write fail-fast + retired-client reads (#1035), OpcUaClient skipped-tag ledger append + zone-qualified IPv6 probe (#1039) 2026-12-03 15:25:42 -05:00
Joseph Doherty 152ae44174 Merge scripting follow-ups: deploy gate warm + 45 s deploy ask (#1024), editor predicate mode (#1025), {{equip}} in verbatim/raw/interpolated literal refused (#1056), ScriptRunGuardTests timing cause (#1038), returned sequences materialised + capped (#1059) 2026-12-03 15:23:46 -05:00
Joseph Doherty eff2b8e573 fix(opcuaclient): #1039 subscribe-time refusals ride the skipped-tag report (SkippedTagLedger.Append/Withdraw); probe preflight keeps an IPv6 zone
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-03 15:20:27 -05:00
Joseph Doherty a24071405a perf(script-runner): #1052 K-11 remainder — scoped keys cached per (kind, key); in-process compile-failure cache keyed by (kind, source) tuple
Every evaluation through the in-process, shadow and out-of-process runners built its
"{kind}:{key}" string afresh, and InProcessScriptRunner also concatenated the WHOLE script
source into its negative-cache key per evaluation. ScopedKeys.For returns a cached string
(bounded 65,536 keys per kind, cleared on overflow); the compile-failure map is keyed by a
(kind, source) tuple.

Measured: 10,000 scoped-key lookups 1,520,000 B -> 0 B (ScopedKeyCacheTests);
InProcessScriptRunner.RunAsync with a ~2 KB source 9,161 -> ~4,900-5,000 B per evaluation.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 15:20:06 -05:00
Joseph Doherty 2a8bac5bf5 feat(audit,install): #1030 audit overflow drops exported as otopcua.audit.dropped; scripted SCM-restart-after-cluster-exit gate
- AuditWriterActor: every buffer-full drop is added to OtOpcUaTelemetry.AuditDropped
  (otopcua.audit.dropped{reason=buffer_full, actor}) — the count used to be readable only
  through the actor's own property.
- scripts/install/tests/Test-ScmRestartAfterClusterExit.Windows.ps1: the windev manual gate
  of 2026-12-03 as a script (qfailure restart action; failover/command trigger => non-zero exit,
  7031, Running under a new pid; Stop-Service stays stopped; optional kill control). Parse-checked
  with pwsh on macOS; must be run elevated on a Windows box hosting OtOpcUaHost.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 15:20:06 -05:00
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 90de55535d fix(config): #1040 #1049 script FKs, unique ZTag/SAPID indexes, reservation ledger retired
One migration, ScriptForeignKeysAndExternalIdUniqueness:
- FK_VirtualTag_Script / FK_ScriptedAlarm_Script (Restrict) onto Script.ScriptId, which becomes
  NOT NULL and an alternate key (unique constraint UX_Script_LogicalId replaces the index).
- UX_Equipment_ZTag / UX_Equipment_SAPID filtered UNIQUE indexes (blank = no identifier, the
  deploy gate's reading) replace the non-unique IX_ ones.
- ExternalIdReservation + sp_ReleaseExternalIdReservation dropped (decision: retire — no writer
  since the generation model; uniqueness is gate + indexes). The /reservations page, query,
  ReservationKind, DraftSnapshot.ActiveReservations and the reservation pre-flight rule go too.
- A read-only pre-check THROWs 51049 naming every offending row class (NULL ScriptId, dangling
  VirtualTag/ScriptedAlarm script, duplicated ZTag/SAPID, any reservation row) and changes
  nothing; Down restores the previous shape.

Authoring mirrors so the constraints are never the first to say no: UnsTreeService refuses a
missing script for VirtualTag/ScriptedAlarm create/update, and a ZTag/SAPID another equipment
holds on create/update/import (owner named; import keeps the clean rows); values stored trimmed.
ScriptEdit maps a concurrent-bind FK refusal to a message. Migration pre-check, Down round-trip,
FK and index behaviour pinned against real SQL with positive controls.
2026-12-03 15:14:26 -05:00
Joseph Doherty f3f24f2984 fix(scripting): #1059 materialise a returned lazy sequence inside the guarded run with an element cap (Scripting:MaxResultElements); document the in-process sandbox boundary 2026-12-03 15:12:37 -05:00
Joseph Doherty bed9620e31 fix(scripting): #1014 host owns the compiled-PE cache; the worker never holds the HMAC key
Review 2026-12-02 K-1 option 4 (#971 follow-up). The ScriptWorker used to read, verify and
WRITE the PE cache with the key it received in Hello, and a verified image is loaded without
re-running the analyzer — so code that escaped inside a worker could sign an entry for any
script's source and persist across restarts and redeploys.

- Hello no longer carries pe_cache_dir / pe_cache_key (fields reserved).
- HostPeCache: the host verifies an entry under its host-only key and ships the image in
  ScriptSource.pe_image; on a miss the worker compiles as before and, only after that compile
  succeeded, the host queues its OWN compile (one background thread, de-duplicated) and writes
  the signed entry. The worker loads a supplied image or compiles; it never opens the directory.
- Images go only to a worker whose Ready.pe_image_abi equals ScriptSandbox.ImageAbi (runtime +
  pinned assembly names); pre-#1014 workers report none and just compile.
- Entry format v2: every worker-written (possibly forged) v1 entry is rejected and refilled.
- Scripting:Worker:PeCacheDir and the directory layout are unchanged.
2026-12-03 15:12:17 -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 e840ec1fbc fix(scripting): #1056 refuse a {{equip}} token in a verbatim/raw/interpolated path literal — editor diagnostic + deploy-gate refusal 2026-12-03 15:05:40 -05:00
Joseph Doherty 0ef9a31b28 feat(historian): #1007 one-time revival of 'max attempts' dead letters; #1034 stalled alarm S&F queue detection (status, log, gauge, Degraded health)
#1007: LocalDbStoreAndForwardSink.ReviveMaxAttemptsDeadLetters requeues only rows whose last_error is exactly the pre-#976 'max attempts (N) exceeded' (idempotent, replicates through LocalDb); driven by AlarmHistorian:ReviveMaxAttemptsDeadLetters for one restart. Runbook in docs/AlarmHistorian.md.
#1034: AlarmHistorian:StallThresholdHours (default 2, 0 disables) -> HistorianSinkStatus.Stalled/LastProgressUtc, transition logs, otopcua.alarm_historian.queue.* gauges, Degraded 'alarm-historian' readiness check.
Both touch the same sink/options/registration files, hence one commit.
2026-12-03 15:04:03 -05:00
Joseph Doherty 682ab34137 fix(uns): #1040 every effective-name computation goes through EquipmentReferenceMap.EffectiveName
The two sites the issue named (DataConnectionValidator, LocalExportCatalog line 56) were already
converted by #1002; the remaining inline copies were not. EquipmentReferenceMap.EffectiveNames itself
used '??', so an empty override dropped the reference instead of naming it after its tag; the
artifact-side ACL resolver used IsNullOrWhiteSpace. Both now agree with the one rule, as do the
UnsTreeService rows, the composer and the local-export alarm reservation.
2026-12-03 14:57:44 -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 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 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 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 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 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 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