Commit Graph

427 Commits

Author SHA1 Message Date
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 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 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 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 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 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 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 49213e52e4 test(config): #1049 real-DB DanglingReference race + snapshot isolation; NodeEdit/ClusterEdit stale-token and delete against SQL Server
DanglingReferenceSqlServerTests: the review's emptiness-check/add/delete race interleaved on two
real connections commits both and the deploy snapshot names the orphan; a consistent device+tag
commit landing mid-read (after Devices, before Tags) is invisible under the factory's SNAPSHOT
transaction, while the same interleave read READ COMMITTED produces exactly the false
DanglingReference (positive control).

ClusterNodeEditConcurrencySqlServerTests (bUnit on the AdminUI SQL fixture — InMemory generates no
rowversion and has no FKs): stale-token saves on NodeEdit/ClusterEdit are refused and the other
user's edit survives, current-token saves succeed, a deployed node deletes with its
NodeDeploymentState rows, a cluster with nodes is not deleted and the page says why.
2026-12-03 15:18:16 -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 8225aaa18c test(scripting): #1038 hold the 2x-overrun orphan on a signal instead of a 200 ms wall-clock spin (a 150 ms test-thread stall reproduced the flake) 2026-12-03 15:12:07 -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 09f11999a5 test(cluster): allow-list the shipped conditions.unsignalled metric's "driver" tag key in the role-literal guard 2026-12-03 12:28:11 -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 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 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 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 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 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 c42eeb3c69 fix(codecs): #999 K-9 malformed wire values fail as each codec's documented exception (ArgumentException / ScriptWorkerProtocolException) 2026-12-03 10:49:44 -05:00
Joseph Doherty 22610df296 fix(drivers): #999 K-10 a backoff cap below the poll interval never polls a failing device faster than a healthy one 2026-12-03 10:47:52 -05:00
Joseph Doherty be4f4f8f94 fix(resilience): #999 K-8 a wrong-shaped ResilienceConfig falls back to tier defaults instead of throwing out of driver spawn 2026-12-03 10:46:17 -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 ef782c29ae fix(scripting): #999 K-7 a script-thrown TimeoutException propagates as itself, not as a disposed-CTS fault or a guard timeout 2026-12-03 10:40:44 -05:00
Joseph Doherty 626d0b33c5 fix(alarms): #999 K-4 a timed shelve expiring on a predicate evaluation emits Unshelved + AutoUnshelve audit 2026-12-03 10:39:17 -05:00
Joseph Doherty eef278fc3b Merge #978: one UNS leaf-name authority (modal = service = deploy gate), script-existence gate + in-use delete guard, VirtualTagHost skips invalid tags 2026-12-03 10:28:50 -05:00
Joseph Doherty d2818e2ef2 fix(uns): #978 one UNS name authority and a script-reference gate — an illegal VirtualTag name or override is refused in the editor and at publish, and an in-use script cannot be deleted
- V3NodeIds.ValidateSegment is the single rule Uns()/UnsChild() enforce; the VirtualTag modal
  ([UnsLeafName]), UnsTreeService (VirtualTag create/update, SetReferenceOverrideAsync) and the
  deploy gate (VirtualTagNameInvalid, UnsEffectiveNameInvalid) all call it (C-1, C-4).
- Effective name is stated once (EquipmentReferenceMap.EffectiveName): an empty override falls
  back to the tag name in the gate and the Monaco catalog, as at both compose seams (C-4).
- UnsSegment patterns anchored \A..\z, so a trailing newline is rejected (C-7).
- VirtualTagScriptNotFound / ScriptedAlarmScriptNotFound deploy-gate rules; ScriptEdit refuses to
  delete a script used by a VirtualTag, ScriptedAlarm or Calculation tag and names them (C-2).
- R-5 backstop: VirtualTagHostActor skips (Error log) a plan whose NodeId cannot be built instead
  of crashing on every apply; AddressSpaceApplier counts it as a failed node instead of aborting
  the VirtualTag materialise pass.
2026-12-03 10:28:27 -05:00
Joseph Doherty d82d0ff1f3 Merge #971: script sandbox is an allow-list; narrowed BCL reference set (K-1 closed) 2026-12-03 10:18:28 -05:00
Joseph Doherty c00ebf1320 fix(scripting): #971 the script sandbox is an allow-list — the K-1 bypasses (CreateDelegate, Expressions, XML/Tar I/O, X509Store, Timers/BackgroundWorker/AsParallel, Serilog.Log) are refused
ForbiddenTypeAnalyzer inverted from a BCL deny-list to an allow-list of types/members (ctx API, value/time/maths
types, collections, LINQ-to-objects, string/Regex/formatting; System.Type and CancellationToken with member
allow-lists). Every named type, expression type and used member (incl. return type and generic args) is checked;
__makeref/__arglist, lock and extern local functions refused syntactically. ScriptSandbox references only eight BCL
assemblies (defence in depth). The Monaco editor and the publish gate share both, so parity holds.

Tests: theory over the K-1 snippets (publish gate + analyzer alone against the full host), every-public-type
enumeration, shipped-sample + idiom regression, editor/publish parity. Differential over every script-shaped literal
in src/tests: all 511 previously-compiling scripts still compile (one expression-tree test intentionally refused).
PE cache signing by the host (option 4) deferred as a follow-up.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 10:09:39 -05:00
Joseph Doherty 07ee9e4888 fix(historian): #976 a historian outage no longer dead-letters alarm history, and an outbox ack never truncates an un-indexed value
G-16 / K-2 (LocalDbStoreAndForwardSink): a RetryPlease counts toward MaxAttempts only on a
drain where some event was Ack'd. A drain with no Ack is an outage: RetryPlease rows are left
untouched (no attempt, no dead letter), the backoff climbs to its 60 s cap, LastError reports
the deferral; PermanentFail rows still dead-letter. An outage longer than ~6.5 min used to
dead-letter the oldest queued alarm events, 100 more every ~10 min.

G-8 (GatewayAlarmHistorianWriter): only InvalidArgument/FailedPrecondition/OutOfRange/
NotFound/AlreadyExists/Unimplemented and unmappable events are PermanentFail; Cancelled,
Unknown, DataLoss, every unlisted code and every non-RPC transport exception retry (the
default used to be dead-letter, so a gateway restart dead-lettered a whole drained batch).

G-16 secondary (AlarmBatchWrite, both SQL writers): a multi-event chunk failing with an
error that is neither a recognised data error nor a known transient is re-sent event by
event, so one unrecognised poison event no longer drags its chunk-mates with it.

G-7 (FasterLogHistorizationOutbox): RemoveAsync of the newest indexed entry truncates to
that record's own end (recorded by the peek, else a one-record scan), never to the live
tail that may already hold an enqueued-but-unindexed append; peeks return only indexed
records so every peeked entry can be acked.

Tests: simulated multi-hour outage (fake clock, 200 drain cycles) loses 0 events and
drains in order on reconnect; positive controls for PermanentFail and a RetryPlease-forever
poison row getting exactly its MaxAttempts budget; gRPC/transport classification theory;
AlarmBatchWrite isolation + known-outage control; G-7 parked-append race + peek-only-indexed.
2026-12-03 10:03:25 -05:00