Commit Graph

402 Commits

Author SHA1 Message Date
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
Joseph Doherty e66f072121 fix(grpc-data): an unknown value/element kind or per-item metadata status from a newer origin fails one item, not the whole browse/metadata response (#956)
DataProtoMapper.DecodeMetadata decodes an undefined ValueKind / ArrayElementKind number to an unknown-kind
marker (DataMetadata.HasUnknownKind, ValidateDecoded) instead of throwing; Validate/Encode still refuse it.
The resolver's #941 IsMaterialisable skips the marker whatever its node kind (a Folder included); a remote
root carrying it is refused. An undefined per-item metadata status decodes to Unavailable (no value, no lease).
Unspecified (0), bad array shape, unknown realm and unknown branch status still fail closed.
2026-12-01 20:20:15 -05:00
Joseph Doherty e3a3f70c78 Merge #950: AdminUI /alerts scripted-alarm ack/shelve report the engine verdict (ExecuteAck.alarm_verdict / DPS replies collected per request, Applied/Refused/Outcome unknown)
# Conflicts:
#	docs/ScriptedAlarms.md
#	src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/AlarmCommand.cs
2026-12-01 19:46:28 -05:00
Joseph Doherty 09aaabbeef fix(alarms): AdminUI /alerts ack/shelve reports the scripted engine's verdict (#950)
The /alerts buttons went central->node fire-and-forget and always showed
"Ack sent". AdminOperationsActor now spawns a per-request
AlarmCommandVerdictCollector (7 s window, under the client's 10 s ask) that
sends the command with AlarmCommand.VerdictRequested and gathers each node's
answer, finishing early once every node it sent to has answered.

- gRPC plane: CentralCommunicationActor tells the collector the dialled
  ClusterNode set and one verdict per node. A node handles a
  verdict_requested AlarmCommandMessage by asking its driver host
  (ScriptedAlarmHostActor.ExecuteAlarmCommand, the #937 path, no ask deadline,
  bounded 5 s) and returns it in the ADDITIVE ExecuteAck.alarm_verdict.
  Transport failure / timeout / empty ack (pre-#950 node) => that node unknown.
- DPS: published with the collector as sender; each ScriptedAlarmHostActor
  answers (non-owners NotOwned); expected set = Up driver members.
- Aggregation: any owner applied => Applied (partial noted); else any
  unknown/silent node => Outcome unknown (never "refused"); else owner
  refusal => Refused: <reason>; else no owner => Not applied.
- UI: green Applied / red Refused (reason) / amber Outcome unknown, per-node
  detail in the details pane; a verdict-less reply (validation, server fault,
  pre-#950 singleton) renders as before.

Wire is back-compatible both ways (new proto fields only; VerdictRequested and
NotOwned default false). Real-wire test through the real router, dialer,
interceptor and NodeCommandGrpcService (red without the node change).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 19:45:17 -05:00
Joseph Doherty bc4d44f7da Merge #951/#952/#953: scripted-alarm late refusal reverted via kept-alive ask (LateOutcome); pre-gate cancellation -> NotApplied; superseded load-generation failures ignored 2026-12-01 19:42:43 -05:00
Joseph Doherty 068124d1ae fix(alarms): #951 #952 #953 — late refusal reverts, never-started command is NotApplied, superseded load failure ignored
#951: the hosted-service Ask lives LateVerdictWindow (30 s) past the caller's bound
(ExecuteAlarmCommand deadline unchanged); the OutcomeUnknown it returns carries the
still-running ask as AlarmCommandOutcome.LateOutcome (process-local). The node manager
watches it (or the asker task itself when its backstop expired, following unknown
chains) and reverts the node on a late NotApplied, under the existing per-condition
mutation-counter guard. Both CallAsync and remote ExecuteConditionMethodAsync paths.

#952: ScriptedAlarmEngine throws ScriptedAlarmCommandNotStartedException (an OCE) when a
command is cancelled before it acquires _evalGate; a cancellation inside SaveAsync stays
a plain OCE (unknown). The host maps not-started to NotApplied and remembers it, except on
the direct ask once its asker's deadline passed (asker already answered unknown and
broadcast): then unknown + not remembered, so the broadcast copy decides (as review r2 M2).

#953: a faulted load pipes back AlarmsLoadFailed(cause, generation); a failure from a
generation a newer apply superseded publishes no readiness (it would refuse every command
while the newer load is in flight).

Red/green: each fix reverted individually turns its tests red (Core 1, Runtime 3,
Host 1, OpcUaServer.IntegrationTests 4).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 19:42:24 -05:00
Joseph Doherty bddf3724f8 fix(dataconn): #941 #942 #943 consumer skips unmaterialisable browse items, gate refuses alarm-bearing export roots, no existence oracle
#941: RemoteNamespaceResolver now skips an origin browse item this build cannot
materialise (NodeKind not Folder/Variable/Tag, or a value/array-element kind with no
OPC UA built-in type: Guid, Bytes) instead of failing the whole page, so one
UnsupportedVariable no longer makes the folder BadNoCommunication. Malformed items of a
supported kind still fail closed. New real-SDK wire tests: an injected unmaterialisable
child (4 kinds) is skipped across BrowseNext pages, and an empty Complete=false origin
page is paged through.

#942: DataConnectionValidator (authoring + DraftValidator deploy gate, not node-side
ValidateDeployed) refuses DataExportRootAlarmBearing: an export rooted at an
alarm-bearing RawTag (grants nothing) or at a UnsTagReference to one (no UNS node, so
the node's catalog compile throws and refuses the whole export set).

#943: GetMetadata, Read, Subscribe and condition-item admission answer an address
outside every export of the principal as NotFound, identical to a missing one
(LocalExportCatalog.DisclosesAddress replaces ContainsAddress). Denied stays for
addresses inside a grant. Browse, Write, HistoryRead and condition methods were
already uniform.
2026-12-01 19:32:14 -05:00
Joseph Doherty 6004a5a565 fix(alarms): #937 review r1 — revert a refused scripted method, broadcast to the peer only after the local verdict, settle a batch per request, in-flight cap
1. A post-dispatch refusal now puts the node back to its captured pre-call state
   with one corrective event (skipped when the node changed since) — the SDK had
   already applied and reported the change. Blank scripted AddComment is refused
   in the handler before the SDK runs.
2. ScriptedAlarmCommandDispatch: ask the local engine first, broadcast to the peer
   only on Applied/OutcomeUnknown — a refusal now reached no engine anywhere.
3. ApplyAsync no longer checks 'loaded' before _evalGate: a command racing the
   first load queues behind it; never loaded => refusal (nothing applied).
4. One Call's requests are settled sequentially (no request runs against a node
   state the engine refused); <= 64 asks in flight node-wide, else
   BadTooManyOperations before anything applies; per-request bound starts at send.
   Measured 300 acks through one host + LocalDb: 59 ms sequential, max 24 ms/ask
   with 64 outstanding.
5. Mixed-batch wire test (scripted refused + native + imported + scripted applied
   + core-manager method): per-item status in order, one scripted ask at a time.
L6: readiness from the engine's HasCompleteGeneration on a load fault.
L7: the verdict slot is closed when its SDK call returns (timer-captured
AsyncLocal can no longer park an ask). L10: remote budget never stretched.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-28 11:51:28 -05:00
Joseph Doherty 053c69f1c8 fix(grpc-data): #916/#917 review r1 — mapper never encodes/decodes stable_source_id (proto field deprecated); browse skip does not consume the scan bound (no empty incomplete pages); unsupported nodes never writable; comment fixes 2026-11-28 10:43:32 -05:00
Joseph Doherty 02d227cc32 fix(scripted-alarms): #935 review round 1 — commands look up under the gate, a restatement writes nothing, a failed load ends the generation
S1: ApplyAsync looked its alarm up before taking _evalGate, so a command racing a
LoadAsync applied to the load's interim Fresh entry (an ack no-op that then saved Fresh
over the carried Active condition — the #935 re-Activate on the next push) or wrote an
old-generation state over the new one. The lookup is now under the gate: a command
queued behind a load applies to the generation that load produced. A command that
changes nothing (value-equal result) writes nothing.

S2: a load re-saved every alarm's post-predicate state, so a node that missed an
operator command upserted its stale carried state over the LocalDb last-writer-wins row
on every deploy. A held seed (carried or persisted) left value-equal is not written.
The push path's ReferenceEquals check (always false: ApplyPredicate returns a clone)
is now value equality too, so a no-op re-evaluation no longer writes/replicates.

S3: a failed load ends the generation. The engine is blind until the next good load,
so (decision, same rule as removed/disabled alarms) that load reads the store — a
still-true alarm is a new occurrence — instead of restating the pre-failure snapshot.
While blind, operator commands throw ScriptedAlarmCommandRejectedException (the host
logs it distinctly; the command topic is fire-and-forget, so that Warning is the
record) and queued re-evaluations / shelving checks are dropped.

N5: a timed shelve that expired before a load is unshelved through the shelving check
(AutoUnshelve audit + Unshelved emission), not silently by ApplyPredicate.

Tests (each red on revert, verified): ack racing a held load (S1), idempotent command
(S1), restatement vs real change saves (S2), no-op push saves (S2), command rejected
after failed load (S3), re-evaluation after failed load (S3), failed load -> new
occurrence + store fault mid-seed -> one Activated (S3/S4), runner Unavailable at
reload freezes carried state (S4), expired timed shelve at load (N5). N4: the Bad-input
reload test now waits on a Good-bucket QualityChanged.
2026-11-25 11:44:20 -05:00
Joseph Doherty ec245b84a9 fix(scripted-alarms): a same-process reload restates a surviving alarm from its in-memory condition (#935)
ScriptedAlarmEngine.LoadAsync runs on every deploy and used to seed each alarm
from IAlarmStateStore, which in production does not persist Active. A
still-true predicate then made every deploy an Inactive->Active transition:
Acked reset, Activated emission (duplicate alerts row), LastTransitionUtc moved.

Seed is now previous ?? persisted ?? Fresh: the last COMPLETED generation's
in-memory condition is captured under _evalGate before the clear and kept
across a failed load. Process restart is unchanged.
2026-11-25 10:54:45 -05:00
Joseph Doherty 8d5077c07d test(grpc-data): A2b F — method bits authorable, shelve reserved, Galaxy opt-in rule, deploy-gate capacity warning 2026-11-24 13:41:51 -05:00
Joseph Doherty 9444044540 test(grpc-data): A2b tolerance pins — method bits understood, AlarmShelve the only reserved bit 2026-11-24 13:40:23 -05:00
Joseph Doherty ef91b4d28f test(grpc-data): A2b codec pins — CallConditionMethod 8th RPC with §4.2 numbers, method codecs, method bits need field 17 2026-11-24 13:39:29 -05:00
Joseph Doherty 6bb8fa6914 test(grpc-data): A2a — condition codecs pin 17/4/9 with their real types (replaces the X0 tripwire) 2026-11-24 12:15:52 -05:00
Joseph Doherty ac9455634d feat(grpc-data): A2a AddDataConnectionConditions schema; authoring accepts AlarmSubscribe
Migration per plan 6: DataExport.MaxConditions (1000), AllowGalaxyServiceAck (false); RemoteNamespaceMapping.MaxConditions
(1000), ConditionStaleTimeoutMilliseconds (30000), ConditionMethodTimeoutMilliseconds (5000),
ConditionSnapshotTimeoutMilliseconds (30000); NOT NULL with SQL defaults, check constraints widened. Validator known set
grows by AlarmSubscribe (method bits stay rejected); condition limits bounded (MaxConditions <= 5000 = the node manager's
per-hold clamp, timeouts <= 1 h); AllowGalaxyServiceAck only with AlarmAcknowledge; non-blocking
ConditionCapacityWarnings when a consumer node's alarm mappings' MaxConditions x 49 exceed MaxImportedConditionNodes.
2026-11-24 12:05:09 -05:00
Joseph Doherty a74a1aeef9 feat(grpc-data): A2a — AlarmSubscribe joins DataOperationSets.Understood; A2 progress log 2026-11-24 11:59:20 -05:00
Joseph Doherty 6ba5185f10 fix(grpc-data): A1 review S1 — a scripted condition is established only by a completed predicate
NoteInputsEstablishment raised 'established' before AreInputsReady, the evidence check and the predicate, so a
pushed-but-Bad input (driver down), a runner that was not up or a predicate timeout produced a known-inactive
record though no predicate had completed. The flip is now raised after the first predicate evaluation that
completes since the load or a revert; reverting an input to never-pushed still withdraws it.
2026-11-24 10:19:03 -05:00
Joseph Doherty eb688a4ee0 Merge A1 keys/placements/ids into A1 core 2026-11-24 10:02:34 -05:00
Joseph Doherty a248616761 feat(grpc-data): A1 scripted OnInputsEstablished — engine flip queued last in pending, host holds flips during a load until after the re-assert, MarkConditionsKnown on the alarm chain 2026-11-24 09:38:51 -05:00
Joseph Doherty 066372ce41 test(grpc-data): A1 — condition ids, condition_key (m-T6), secret validation, UNS-only no-RawPath property test; A1 manifest key 2026-11-24 09:23:06 -05:00
Joseph Doherty fc8154289d fix(grpc-data): H2 review2-7c - MaxHistoryResponseBytes minimum 256 KiB (validator + AdminUI min)
Wire tests that relied on a 1-byte response cap now exercise chunking with wide string values at the minimum.
2026-11-23 23:18:08 -05:00
Joseph Doherty 82d34b84a8 fix(grpc-data): H2 review 9 - upper bounds on the history limits (validator + AdminUI max) 2026-11-23 21:54:38 -05:00
Joseph Doherty 6a621423f4 fix(grpc-data): H2 review 8 - history timeout rides the artifact, not the trust-scope fingerprint
DataConnectionScopeRevision covers consumer/connection/secret scope only; limits (TimeoutMilliseconds and now
HistoryTimeoutMilliseconds) reach DB-less nodes and the LocalDb cache in the artifact's entity JSON. Dropping the field
also avoids a one-time scope-version bump on upgrade. Plan 6 corrected.
2026-11-23 21:53:58 -05:00
Joseph Doherty b6895c19d4 feat(grpc-data): H2 AddDataConnectionHistory schema; authoring accepts HistoryRead
Migration per plan 6 (HistoryTimeoutMilliseconds 30000; MaxConcurrentHistoryReads 4, MaxHistoryValuesPerPage
10000, MaxHistoryResponseBytes 4 MiB; MaxHistoryAssemblyBytesPerRequest 16 MiB) with non-null defaults and widened
check constraints. Validator known set grows by HistoryRead (mapping bits still subset of connection bits; history
limits positive); scope revision includes the history timeout.
2026-11-23 20:38:31 -05:00
Joseph Doherty 619b0c378d feat(grpc-data): H2 history wire contract and codecs; HistoryRead understood
HistoryRead rpc + HistoryCapabilities (16) / HistoryInfo (14) per plan 4.2; DataHistoryProtoMapper keeps the full
uint32 status, ns Timestamps, absent start/end/sample timestamps, verbatim aggregate configuration, and BadTypeMismatch
for a value kind disagreeing with the catalog. DataOperationSets.Understood gains HistoryRead; X0 tripwire replaced.
2026-11-23 20:33:26 -05:00