2.4 — ArtifactDiff:
- TRN-2: secret-bearing values (data-connection primary/backup config, DB
connection string, external-system auth, SMTP credentials, SMS token) are
compared by SHA-256 and reported value-free as <present> -> <changed>, so a
changed endpoint no longer reads Identical and is force-skipped.
- TRN-6: the instance diff resolves each existing binding's DataConnectionId to
its name and compares it (a rebind OPC1 -> OPC2 is Modified); State is no
longer compared (the import never carries a live state).
2.5 — BundleImporter / ManagementActor / Central UI:
- TRN-3: PreviewAsync takes an optional BundleNameMap (additive optional param);
under a MapToExisting redirect the connection/instance diffs, connection
auto-match and unresolved-connection blocker run against the mapped target.
The CLI import path passes its explicit --map-site/--map-connection redirects
to the preview before the blocker gate; the Central UI re-runs the preview
under the Map-step choices at Confirm. Apply binds a CreateNew site/connection
whose identifier/name already exists to that row instead of inserting a
duplicate the unique index rejects.
- TRN-7: connection, instance, instance-template and composition/base-template
lookups match exact spelling first, then case-insensitively.
- TRN-8: InstanceDto gains the additive AreaPath (root->leaf); the exporter
fills it and the importer resolves/creates areas level by level under their
real parent. A legacy leaf-only bundle with an ambiguous leaf resolves
deterministically and adds an ImportResult warning.
- TRN-9: Rename is rejected by ApplyAsync for Site, DataConnection,
SmtpConfiguration and SmsConfiguration (ImportRenameSupport); the UI does not
offer it there and the CLI rename policy falls back to Skip with a warning.
Also moves a doc comment misplaced by the 2.6 commit. Reflection round-trip
guard (RoundTripEquivalenceTests) re-run: green.
TRN-4: the composition rewire skipped any bundle template with zero
compositions before the clear ran, so an Overwrite never removed the target's
slots although the preview reported the removals. It now skips only an
Add/Rename (nothing to clear).
TRN-5: a slot the bundle removes is deleted through
TemplateService.DeleteCompositionAsync, which cascades the slot-owned derived
template (no DB relationship on OwnerCompositionId, so the row-only delete
orphaned it and blocked deleting its base). A slot the bundle re-composes keeps
the row-only delete so a pre-#118 bundle that re-composes the slot onto its
derived template by name still resolves. Tests run the real importer against
an EF context and fail on the previous importer.
Alarm -> on-trigger script links went through one flatten-wide
'TemplateScript.Id -> canonical name' map. Slot-derived templates hold only
IsInherited placeholders, so every slot of a module composed twice resolved to
the base script row id and the LAST slot's canonical name won: pump 1's alarm
ran pump 2's script in pump 2's scope (TPL-1). A derived script override has a
different row id, so the base alarm's link resolved to null (TPL-2). And the
base pass over a nested slot overwrote a slot-level on-trigger override (TPL-5).
ResolveInheritedAlarms now looks the id up among the script rows of the
alarm's own chain, takes the row's NAME and path-qualifies it with the alarm's
prefix, carrying it on the ResolvedAlarm, so only the pass that actually adds
the alarm decides it. An id outside the alarm's chain keeps the old flatten-wide
fallback; a name with no resolved script is still nulled.
BY DESIGN this changes the revision hash of multi-slot compositions (and of
derived templates that override an alarm's on-trigger script, and nested slot
overrides): affected instances read Out of date once and redeploy with the
corrected on-trigger script.
Decision 2.8: preserve-if-null on the server. UpdateSiteCommand,
UpdateDataConnectionCommand and UpdateApiMethodCommand fields (except the id)
are now nullable; the ManagementActor handlers apply only non-null values and
treat an empty string as 'clear this optional field'. The CLI update commands
no longer require --name/--protocol/--script and drop the --failover-retry-count
(3) and --timeout (30) defaults, so an omitted option travels as null instead of
overwriting the stored value (site update --name used to null both gRPC
addresses). The site gRPC-address validation now runs on the merged values.
Additive/compatible: the fields only became nullable, so an older CLI that
always sends every field still deserializes (pinned by a test) and now simply
updates every field as before. The Central UI full-entity forms send "" for a
field the operator cleared (description/addresses, removed backup endpoint,
cleared parameter/return definitions) so clearing keeps working.
BundleSecretEncryptor.Decrypt now refuses an iteration count outside
[MinPbkdf2Iterations, MaxPbkdf2Iterations] before PBKDF2 runs. The manifest
JSON path was already guarded by the EncryptionMetadata constructor (pinned by
a new test), but a record 'with' (or any non-ctor path) bypassed it and
derived with int.MaxValue iterations; the encryptor no longer relies on it.
GetListByNameAsync now eager-loads Recipients, so the importer's Overwrite
Clear() removes the target's rows before the bundle's are re-added. Fixed in
the repository method (decision 2.1) so every caller gets the recipients.
Regression: target {A,B} + bundle {A,C} -> {A,C}, stable on re-import.
Mirror of mxaccessgw#237 (659bb831). DEV vd03 showed 229k context switches
in ZB.MOM.WW.ScadaBridge.Host at ~240 MxGateway events/s. Akka's default
dispatcher, gRPC/Kestrel and async continuations all run on the .NET thread
pool, so a trickle of small work items makes idle pool workers spin with
Sleep(0) (default limit 70) before parking.
- Host csproj: RuntimeHostConfigurationOption
System.Threading.ThreadPool.UnfairSemaphoreSpinLimit=10, written into
ZB.MOM.WW.ScadaBridge.Host.runtimeconfig.json (verified in the publish
output, which docker/Dockerfile copies into the image).
- RuntimeConfigTests pins the value in the built runtimeconfig.
- Component-Host.md: new "Runtime thread-pool settings" section (what, why,
override/revert via DOTNET_ThreadPool_UnfairSemaphoreSpinLimit).
Local synthetic trickle bench (macOS, ~185 chains/s): involuntary context
switches 17-28k -> 6-13k, CPU 430-560 -> 200-295 ms per 20 s. The vd03
before/after WPR measurement is pending the next vd03 deploy.
OtOpcUa now exposes conditions imported over gRPC data connections in the
namespace https://zb.com/otopcua/mapped/conditions. Their ConditionId is
an opaque c1. NodeId stable for the life of the connection, but their
SourceName (<anchor>/<placement path>) moves when the primary placement
mapping changes. ScadaBridge keyed every condition on
SourceName.ConditionName, so a mapping change read as one alarm clearing
and a new one raising.
- Event filter selects ConditionId (select clause 19: ConditionType,
empty browse path, AttributeId = NodeId).
- When the ConditionId (or SourceNode, which OtOpcUa sets to it) is in the
mapped/conditions namespace, the per-condition key is its durable
nsu=... string (index-proof across an OtOpcUa pair / upgrade). Every
other OPC UA condition keeps the SourceName.ConditionName key, so no
existing persisted row, MES script or operator view is re-keyed.
- The old SourceName.ConditionName text becomes an additive, display-only
DisplayName: NativeAlarmTransition -> AlarmStateChanged ->
AlarmStateUpdate.display_name (26) / DebugAlarmStateDto.display_name
(22) -> ScriptAlarm.DisplayName. Persisted in native_alarm_state
metadata_json (no column, no CDC trigger change); updates in place on
every transition under the fixed key. Protos regenerated.
- Alarm Summary and Debug View show DisplayName (key as tooltip) and
filter on it; site event log writes "label [key]".
- Upgrade: a pre-#147 row for an imported condition is retired by the
first completed refresh snapshot (one return-to-normal + drop), then the
condition continues under its ConditionId.
Tests: RealOpcUaImportedConditionKeyTests, OpcUaAlarmMapperTests,
NativeAlarmActorTests (DisplayName, rehydration, legacy-row retirement),
StreamRelayActorTests, SiteCommand golden sample, AlarmsAccessorTests,
DebugTreeBuilderTests; filter select-clause count 19 -> 20.
Docs: Component-DataConnectionLayer/Commons/Communication/SiteRuntime.
OtOpcUa now emits RefreshRequiredEventType (SourceNode = Server, no
condition fields) on an incomplete condition snapshot, a removed imported
condition, or a resync that leaves pre-failover EventIds answering
BadEventIdUnknown. RealOpcUaClient had no branch for it: the event fell
through HandleAlarmEvent as a phantom condition keyed "Server" and no
refresh was issued, so the mirror could hold stale / un-ackable state.
- HandleAlarmEvent recognises RefreshRequiredEventType, emits nothing, and
hands the item's handle to the new ConditionRefreshCoalescer.
- The coalescer runs off the SDK publish thread, debounces 500 ms so a
burst (one event per affected item) costs one refresh, never overlaps
refreshes (a request during an in-flight refresh is served by the next),
logs and swallows failures, and is cleared on disconnect.
- Execution: targeted ConditionRefresh2(eventSubscription, item) per asking
item; one subscription-wide ConditionRefresh when every live alarm item
asked, an item has no server id, or ConditionRefresh2 fails. The replay is
the usual RefreshStart/End frame, so NativeAlarmActor's snapshot swap
clears conditions the refreshed snapshot no longer lists.
- The server-side OfType WhereClause built from a condition filter now ORs
in OfType(RefreshRequiredEventType): the server queues RefreshRequired
through the item's filter, so a bare condition-type clause dropped it.
Tests: RealOpcUaRefreshRequiredTests (branch, no-session tolerance, burst
coalescing, no overlap, failure tolerance, Clear, framing intact);
RealOpcUaClientAlarmFilterTests updated for the added operand.
Component-DataConnectionLayer.md documents the behaviour.
The Test Run banner in TemplateScriptDialog and SharedScriptForm claimed
External, Database and Notify all fire for real ("real emails"). Notify
is SandboxNotifyTarget, which returns a random GUID and sends nothing.
The banner now says External/Database are real and Notify is simulated,
pointing at Flow Debugger on a deployed instance for a real send. The
sandbox Send also writes a [sandbox] ... not delivered line to the
console pane. Notify.Status is unchanged (reports Unknown). Tests pin
the banner wording and the console line; Component-CentralUI.md notes
the simulated Notify.
The semantic validator treated each comma-separated argument after the
script name as a positional parameter and required the count to equal the
declared ParameterDefinitions. The runtime has no positional form: both
calls take ONE parameters object that ScriptArgs.Normalize turns into a
name -> value dictionary, so every Scripts.CallShared("X", new { ... })
was rejected unless exactly one parameter was declared, blocking deploy.
Call sites are now found with a Roslyn script-mode syntax parse (named
arguments and a trailing CancellationToken handled; calls in comments or
strings ignored). The parameters argument is classified as:
- anonymous object: validated by name (ordinal) - missing required
parameter = error, undeclared member = warning, clear literal type
mismatch per member = error (same conservative inference as before);
- any other expression (variable, dictionary, call, null): not checked;
- absent: error only if the target declares required parameters.
Required-ness comes from the shared InboundApiSchema parser (JSON Schema
'required' list; legacy array entries required unless required:false).
Positional-argument tests replaced by by-name CallShared/CallScript tests;
Component-TemplateEngine.md updated.
SmtpConfiguration.MaxRetries/RetryDelay (and ConnectionTimeoutSeconds/
MaxConcurrentConnections) drive the outbox Email policy but had no write
path, so every row sat at 0/0 and was clamped with a Warning; DEV vd03 had
to be fixed by direct SQL.
- Update/CreateSmtpConfigCommand: four trailing additive nullable fields
(null = preserve on update / entity default on create; 0 = fallback).
- ManagementActor: preserve-if-null, negatives refused.
- CLI notification smtp create|update: --max-retries, --retry-delay-seconds,
--connection-timeout-seconds, --max-concurrent-connections (>= 0).
- Central UI /notifications/smtp: fields on the form + read-only panel;
new rows pre-fill 10 retries / 60 s.
- README + Component-NotificationService; tests for apply/preserve/reject.
ManagementAuthenticator — the only identity source for POST /management, the
audit REST endpoints and the debug-stream hub — now enforces "no role, no
login" the way #144 does for /auth/login and /auth/token:
- HTTP Basic: a bind whose groups map to zero roles, or whose role mapping
throws, answers the bad-password 401 AUTH_FAILED body and counts as a
LoginThrottle failure. RecordSuccess moved after the mapping, so a refusal
no longer clears earlier failures. Request cancellation still propagates.
- Bearer: a token with no role claim (minted before #144 shipped) gets the
invalid-token 401; no throttle, as for every bearer failure.
- Each refusal is logged at Warning (category ManagementAuthenticator) with
the request path, the username and the reason.
Before this, a zero-role Basic caller reached every command that
ManagementActor.GetRequiredRoles opens to any authenticated user.
DisableLogin is unchanged.
Tests: ManagementZeroRoleRefusalTests — zero roles / mapper throws / one role
over Basic and Bearer for /management (ListSites), /api/audit/query and the
debug-stream hub; every null-role command is unreachable by a zero-role
principal; throttle accounting. 47 of the 58 fail against the old
authenticator (the 11 that pass are the one-role/bypass regression guards).
Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
The integration factory's in-memory configuration database is never seeded, so
it holds no LdapGroupMappings and the live GLAuth users mapped to zero roles.
LoginEndpoint_WithValidLdapCredentials_SetsCookieAndRedirects and
ActiveSession_GroupsAreReReadFromTheDirectory_AndAnUnknownUserIsEnded were
passing only because zero-role sign-in and zero-role sessions were allowed.
They now run against a factory variant whose IGroupRoleMapper mirrors the
seeded mappings (SecurityConfiguration.HasData).
Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
The mid-session refresh ended a session only when the directory returned no
groups (or the user was gone/disabled/ambiguous). A user still in some groups
but in no mapped one, or whose DB mappings were all revoked, kept a signed-in,
role-less session that could read the bare-[Authorize] pages. CookieSessionValidator
now rejects when the re-map yields zero roles, on ordinary and fail-closed paths.
A mapper fault keeps its existing policy (keep grants; fail closed when asked).
Docs: Component-Security "No role, no login" (incl. the HTTP Basic gap left as a
follow-up), Component-CentralUI, CLAUDE.md.
Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
A successful LDAP bind whose groups map to no ScadaBridge role, or whose role
mapping throws, is now refused at both sign-in endpoints exactly like a bad
password: the same redirect/401 body, no cookie, no token, and a login-throttle
failure (so the throttle is not an oracle). The reason is logged server-side at
Warning with the endpoint and username. Family standard: scadaproj NAM AD
cutover plan §3.2 (Phase A2, §2A).
Tests: zero roles, mapper throws, and one role for both endpoints, plus the
throttle accounting; RoutePolicyCoverageTests now notes that the two bare
[Authorize] pages rely on this rule.
Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
SplitBrainResolverStrategy now defaults to leader-auto-down (the in-repo
LeaderAutoDowningProvider, #106, with the #132 shut-out restart on). auto-down and
keep-oldest stay supported. Drilled on the docker rig, docker-env2 and the QA pair
(central + site, kill and stop-and-hold) before the flip.
- ClusterOptions default + validator/HOCON comments updated.
- Shipped Host appsettings.Central/Site.json and every docker/ and docker-env2/
node appsettings now say leader-auto-down. The leader-auto-down overlays are
kept as no-ops (drill records reference them); new docker-compose.auto-down.yml
overlays keep Akka AutoDowning available for comparison drills.
- Tests: default asserts leader-auto-down; new HOCON test for an unset strategy;
TwoNodeClusterFixture defaults to the production posture.
- Docs: CLAUDE.md, Component-ClusterInfrastructure, components/Host + Cluster,
README, failover procedures, Traefik, docker + env2 READMEs; register row 70 closed.
No deploy needed: DEV, QA and both rigs set the key explicitly.
Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
Owner decision 2026-11-15, at IT security's request, pending a family-wide general solution.
Removed: the chaining service, hasher, verifier, chain head/tombstone entities and store, the #139
chain-start cutoff, AuditLog:HashChain (incl. ChainBacklog and HeadExport with its File/Syslog sinks
and export service), the audit-chain-head-export health check, the VerifyAuditChain /
VerifyAuditChainHeads management commands and the `audit verify-chain` / `audit verify-heads` CLI
commands, and the two-login plumbing (AuditLog:MaintenanceConnectionString, AuditMaintenanceContext,
the keyed audit-maintenance repository/archive). Purge, archive, retention, partition roll-forward
and backfill-source-node all run on the runtime connection again, as before #107.
Parquet archive (#42) kept, chain-free: format v2 (ten stored columns, no tombstone file, manifest
without chain state), the switch guard is the row count only (51003 gone), verify = data-file size,
SHA-256 and row count, and superseded-stale cleanup proves coverage by EventId. Format-v1 archives
still list, verify and are cleaned up (their tombstone file too).
Migration RemoveAuditLogHashChain drops the chain indexes, the scadabridge_audit_chainer role
(members first), both chain tables, ChainSeq/RowHash and the purger's AuditMaintenanceGrants grants;
writer/purger roles stay. Down restores them. Every chain-column reference is EXEC-deferred for the
idempotent script (#126); FlipAuditLogClusteredKey's two chain index statements get the same
deferral, behaviour unchanged, so re-running the idempotent script on a migrated database works.
The partition-switch staging table adds the chain columns only when the live table has them, so the
new binary purges either schema. Deploy gate: old binaries map the chain columns, so the migration
ships with the new binaries, both centrals stopped.
A leftover AuditLog:HashChain section or MaintenanceConnectionString (DEV/QA still carry
AuditLog__HashChain__Enabled=true) is ignored with one startup warning (RetiredAuditSettingsWarning).
Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
QA Warm gate (lmxopcua#907, 2026-11-13): a graceful stop of the Warm Primary
reported ServiceLevel 0 for ~6 s - shorter than the 10 s degraded window - the
next unreadable sample cleared the streak, and the connection retried the stopped
node FailoverRetryCount times: Good on the peer after 66 s, peer Active in 0.2 s.
Two going-away triggers on top of #138, both still requiring a Healthy (>= 200),
higher level on the other endpoint and honouring the minimum dwell:
- ServiceLevel 0 (Part 4 Maintenance) probes the other endpoint at once instead
of waiting out the window - once per degraded streak, so a non-Healthy peer is
re-probed once per window, not every poll. Other Degraded levels (standby 90/50,
booting 1) still wait the window.
- A lost link whose session's last KNOWN ServiceLevel was < 200 (unreadable
samples don't overwrite it) probes the other endpoint before the first
reconnect attempt, holding the reconnect timer. Healthy -> switch and reconnect
at zero delay, the stopped node is never retried; otherwise the ordinary retry
cycle runs (less the probe's time). After only Healthy levels (250/240, Unset),
inside the dwell, or with the feature off: unchanged retry-then-failover.
Tests: DataConnectionGoingAwayFailoverTests (10 cases, each trigger and
non-trigger with positive controls, connect-order artifact assertions) and a real
in-process OPC UA server pair graceful-stop e2e on production defaults: 1.1 s
(lost-link trigger alone 12.1 s, neither 33.1 s -> fails the 10 s bound).
13 mutants, all killed. DCL tests 608/608 (3 full runs); solution 0 warnings.
Docs: Component-DataConnectionLayer, components/DataConnectionLayer.
Not deployed; QA live re-check pending.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
Removes the #96 compatibility path that the unified central-cache-invalidation
topic (#100 item 3, 153609ef; compat 3a31dd2d) carried for one release:
- CentralCacheInvalidationBus no longer publishes a bare SitePskInvalidated
on site-psk-invalidation; LegacySitePskTopic constant deleted.
- CentralCacheInvalidationSubscriber no longer subscribes to that topic or
handles a bare SitePskInvalidated; it applies envelopes only.
central-cache-invalidation behaviour is unchanged (one envelope per
invalidation, origin filtering, per-handler fault isolation).
Gate met: 8e32f353 (carries 153609ef and 3a31dd2d) runs on every central
node - DEV vd03 (record 581e25ca) and QA vq03/vq04 (record 8ba5d5d7).
Mixed-version / rolling-upgrade constraint: a central node built before
153609ef listens only on site-psk-invalidation and no longer receives PSK
invalidations from a newer peer (only its TTL and the site-rejection refresh
bound the staleness). Mixed pairs across that boundary are no longer
supported; central pairs are stopped and started together anyway.
Documented in Component-Host.md and Component-Communication.md.
Tests: the legacy publish/subscribe tests are replaced by
PskRotation_OnOneNode_ReachesThePeersCaches_ThroughTheUnifiedTopic (node A
publishes, node B's PSK cache and secret-resolver cache are invalidated, and
nothing else is published) and a bare-message-ignored test with an envelope
positive control. The two-node cluster test now asserts the PSK invalidation
arrives exactly once and the publisher applies nothing.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
LocalDb 0.3.8 ends open sync streams on ApplicationStopping and refuses
new ones Unavailable while stopping (lmxopcua#906, library side). The
host-side ShutdownStreamCancellationInterceptor (#140) stays.
GracefulStopWithOpenSyncStreamTests' positive control passed the stop
in ~900 ms under 0.3.8, because the library alone now ends the stream.
The control registers LocalDbSyncService without the host lifetime (the
0.3.7 behaviour), so it still reproduces the 8 s drain; verified it
fails on 0.3.8 without that change.
Release build 0 warnings. Host.Tests 733/733, IntegrationTests 133/133
(incl. the LocalDb site-pair convergence tests), Communication.Tests
843/843, HealthMonitoring.Tests 131/131, SiteEventLogging.Tests 118/118.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
A graceful stop of a site node whose peer holds an open LocalDb sync stream
left the Akka cluster ~30 s late (the ScadaBridge half of lmxopcua#906,
scadaproj#57). WebApplication stops the web server before AkkaHostedService,
whose StopAsync ran CoordinatedShutdown, and Kestrel's graceful drain waited
the whole ShutdownTimeout for /localdb_sync.v1.LocalDbSync/Sync: LocalDb 0.3.7
observes only the call token, which Kestrel cancels at the END of the drain.
CancelAllStreams only covered SiteStreamGrpcServer's own streams.
- AkkaHostedService is now an IHostedLifecycleService. StoppingAsync runs
before any hosted service's StopAsync (Kestrel's included): marks the stop
intentional, raises ApplicationStopping (so CancelAllStreams still precedes
actor teardown), then runs and awaits CoordinatedShutdown(ClrExitReason),
bounded by the host shutdown token. StopAsync returns the same completed
shutdown. Exit codes unchanged: planned stop exits 0; only a termination
outside host shutdown (self-down / #132 shut-out) exits 75. No Akka.Hosting
here, so no ClusterLeavingReason/-1 exit-code path is involved.
- ShutdownStreamCancellationInterceptor, innermost on both the central and the
site AddGrpc pipelines: every streaming call's token is linked with
ApplicationStopping; new streams are refused Unavailable while stopping.
Covers the LocalDb sync stream until LocalDb 0.3.8 is pinned.
Evidence (IntegrationTests/GracefulStopWithOpenSyncStreamTests: real
WebApplication + Kestrel h2c + MapZbLocalDbSync behind LocalDbSyncAuthInterceptor
+ a real LocalDb SyncBackgroundService peer + the production AkkaHostedService
forming a single-member cluster, 8 s drain budget, IServer wrapped to timestamp
the drain): before 8859 ms stop, member removed at 8834 ms, drain began at 0 ms;
after 960 ms stop, member removed at 950 ms, drain began at 959 ms.
Mutations (all killed): StoppingAsync skips CoordinatedShutdown; interceptor
passes the original context (stop 8003 ms); no Unavailable refusal; StoppingAsync
does not raise ApplicationStopping; lifecycle interface dropped; site pipeline
loses the interceptor.
Release build of the solution: 0 warnings. Host.Tests 733/733,
IntegrationTests 133/133, Communication.Tests 843/843.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
Owner decision on #107 (2026-11-13): enabling AuditLog:HashChain must not
chain the historical backlog. main chained every unchained row oldest-first.
- The first chaining pass on a pristine database (no head, no chained row)
writes a chain-start anchor: AuditLogChainTombstone (cutoff month,
ChainSeq 0), PurgedAtUtc = DB SYSUTCDATETIME(), RowHash =
SHA-256("ScadaBridge.AuditLog.ChainCutoff.v1" || YYYY-MM || ticks).
Written once under the exclusive chain lock, so both centrals agree
whatever their clocks/config. No migration: existing table + grants.
- Only rows with OccurredAtUtc >= cutoff are chained. The anchor hash is
the cutoff month's genesis, binding the cutoff into the chain.
- AuditLog:HashChain:ChainBacklog (default false) restores chain-everything,
read only on the very first enablement. Legacy chains (heads, no anchor)
keep chaining everything.
- verify-chain splits unchained rows into UnchainedRows vs PreCutoffRows
(+ ChainFromUtc); new breaks ChainedBeforeCutoff (row re-dated before the
cutoff, or cutoff moved forward) and CutoffAnchorInvalid (anchor hash /
month / multiplicity). Archive verify uses the anchor from its own
tombstone file or the DB.
- Partition switch-out keeps the anchor (deletes ChainSeq > 0 only); the
head store / export / verify-heads tombstone count excludes it.
- CLI verify-chain table prints Chain from + Pre-cutoff rows.
Tests: AuditLogHashChainCutoffTests (7, MSSQL), 6 verifier unit tests,
service/CLI/management wire tests; 9 mutations all killed.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
Prerequisite for OtOpcUa Warm redundancy (lmxopcua#717): a Warm standby keeps a
healthy session but serves BadOutOfService at a standby ServiceLevel (90/50, boot 1),
so a connection that lands there sat on Bad quality forever.
- OPC UA connections with a backup poll Server_ServiceLevel (i=2267) on the connected
endpoint (IServiceLevelReadable, implemented by OpcUaDataConnection; never raises
Disconnected). A level < 200 sustained for the degraded window (default 10 s), or
the first sample after any (re)connect, triggers a probe of the other endpoint
(short-lived session: connect, read, dispose). Switch only when it reports a
Healthy (>= 200) higher level, and not within the minimum dwell (default 60 s) of
the previous ServiceLevel switch. Both degraded, other unreachable or level
unknown: stay put. 250/240 (today's OtOpcUa) never starts a streak.
- The switch reuses the failover path: SwitchToOtherEndpoint() now shared by all
three triggers, then BecomeReconnecting(ReconnectCause.ServiceLevelFailover) -
zero delay, no unstable accounting, ReSubscribeAll on the new endpoint.
- Config: OpcUaEndpointConfig.ServiceLevelFailover {enabled, degradedWindowSeconds,
minDwellSeconds}, read from the PRIMARY endpoint's JSON only; null = defaults
(enabled, 10, 60). Inside the encrypted protocol JSON, so no schema change or
migration. Central UI: fields in the Backup card next to Failover Retry Count.
Global: ScadaBridge:DataConnection:ServiceLevelPollInterval (2 s) and
ServiceLevelProbeTimeout (15 s).
- Tests: actor tests per trigger/non-trigger with positive controls, an unsolicited
promotion RefreshStart/RefreshEnd test at client and actor level, adapter tests,
and a real in-process OPC UA server pair end to end. All 15 mutants killed.
- Docs: Component-DataConnectionLayer, components/DataConnectionLayer, Component-CLI.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
Re-verified #105 item 2 on the real write paths: ManagementActor bulk attribute
overrides (CLI set-overrides / management API) and InstanceService.SetAttributeOverrideAsync
(Central UI single editor) both match the template member ordinally and refuse a
case-variant name, so nothing is stored for the flattener to drop. Native-source
overrides already validate against the flattener's own output.
- New theory tests drive each path, feed whatever it stored into the real
FlatteningService, and assert every stored override is applied (exact-case row is
the positive control). Mutation: accepting case variants (OrdinalIgnoreCase) fails
them with "stored ... but the flattener dropped it as unresolved".
- The did-you-mean hint moves to TemplateEngine.OverrideNameMatching and is now also
on the UI single-attribute path; ambiguous matches get no hint.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
Every CLI option that can carry a secret gets a `--<name>-file <path|->`
sibling ('-' reads stdin), so the value stays out of the process list and
shell history: --password-file (global), --primary-config-file /
--backup-config-file (data-connection create|update), --auth-config-file
(external-system create|update), --connection-string-file (db-connection
create|update), --credentials-file (notification smtp create|update) and
--auth-token-file (notification sms create|update). Follows the existing
--config-file convention; `@path` is avoided because System.CommandLine
expands @-tokens as response files.
The value is read at parse time; a missing/unreadable/empty source, or '-'
on a terminal stdin, is a parse error naming option + path only, never the
content. Inline and file forms are mutually exclusive, at most one option
may read stdin, and one trailing line break is stripped. Inline forms keep
working.
docker/seed-sites.sh and docker-env2/seed-sites.sh now write the MxGateway
config (windev gateway key) to a mode-600 temp file removed by an EXIT trap
and pass --primary-config-file; seed-flow-outbound-demo.sh pipes its rig
connection string via --connection-string-file -. CLI README (new "Secrets
from a file or stdin" section + per-command tables), Component-CLI.md and
both docker READMEs updated.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
The first mutation (instance deploy) to a site pair whose sticky node was down
returned OUTCOME_UNKNOWN: SitePairChannelProvider.ExecuteAsync treated every
Unavailable on a non-retry-safe command as possibly-applied unless the server
sent the not-dispatched trailer, flipped stickiness, and threw. The retry then
succeeded on the live peer.
A connect-phase failure provably never sent the request, so it is now treated
like the pre-dispatch rejection: GrpcRetrySafety.WasNeverSent recognises
Grpc.Net.Client's subchannel connect failure ("Error connecting to subchannel."
with a SocketException cause) and an HttpRequestException name-resolution /
connection error with a connect-only socket error. Anything that may have been
delivered (reset, premature end, GOAWAY, server Unavailable) stays
OUTCOME_UNKNOWN and is not replayed. The site->central reconcile path uses the
same ProvablyNotApplied rule.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
When a replicated site pair cold-starts together, the node that wins the
Deployment Manager singleton loads its own (stale) store, and the peer's
rows arrive by LocalDb sync about a second later. The boot load has already
run and the startup reconcile rightly reports no gap (the rows are in the
store by the time it asks central), so only the instance sweep starts those
instances - at its plain 60 s cadence. Reproduced on the primary rig: boot
load without the instance at 05:03:16, sweep start at 05:04:16.
The env2 drill read this as "never started" because the operator
redeployed at +49 s, before the first sweep tick at +60 s.
Fix: when boot-time Instance Actor creation finishes, the singleton runs
one sweep at once, then sweeps every InstanceSweepSettleIntervalSeconds
(default 5) for InstanceSweepSettleWindowSeconds (default 120), then falls
back to InstanceSweepIntervalSeconds. Startup never waits for the peer, so
a site whose peer is down for good still starts alone from its own store.
LocalDb 0.3.7 exposes no "snapshot applied" signal, so the fix rides the
arrival-path-agnostic sweep with all its existing guards.
Tests: PostBootSettleSweepTests (4) + validator theory. The two positive
tests fail with the fix disabled; the window-close test fails when the
settle timer is never cancelled.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
OPCFoundation.NetStandard.Opc.Ua.Client and the test-only .Server move
1.5.378.182 -> 2.0.1, the version OtOpcUa master runs (lmxopcua#782; #799
and #801 closed). Transitive Core/Core.Types/Types/Configuration/
Security.Certificates resolve to 2.0.1.
API breaks fixed in the DCL adapter:
- Built-in types are immutable structs (Variant, DataValue, NodeId,
LocalizedText, StatusCode, ArrayOf<T>). New OpcUaValueBoundary restores
the SDK 1.5 CLR shapes for every read, subscription and alarm-event
value (byte[], UTC DateTime with no-timestamp = MinValue, Guid,
detached arrays) and builds write variants with SDK 1.5's
new Variant(object) semantics (byte[] = ByteString scalar).
- StatusCodes members are no longer constants: switches/patterns over
them (verify-outcome mapping, connection-level classification,
BadResourceUnavailable) match by value.
- CertificateIdentifier no longer caches a certificate and the
CertificateValidator/CertificateValidation event is gone: the
configuration's CertificateManager owns trust lists and the loaded
application certificate and is disposed with the session; auto-accept
and the verify probe's capture-and-reject use AcceptError.
- new UserIdentity(X509Certificate2) is gone: X509 user identities use
X509IdentityTokenHandler with an on-demand PFX provider (still fails
fast on a missing file/key).
- DefaultSessionFactory takes the telemetry context; collections are
ArrayOf<T>; EventFilter select clauses and ContentFilter operands are
built immutably.
UserName identity (lmxopcua#880): SDK 2's default handler sends a
password over 64 bytes - every 65-character OtOpcUa API key - as an
RsaEncryptedSecret that SDK 1.5 servers reject with BadIdentityTokenInvalid
and SDK 2 servers accept only within a 5-minute clock window (#873). The
DCL now always uses LegacyRsaUserNameIdentityTokenHandler (ported from
OtOpcUa be28aa44), i.e. exactly what it sent on SDK 1.5, so it logs in to
both server generations during a mixed rollout.
Tests: the in-process secured test server is ported to SDK 2 and can
admit an API key; new tests cover the handler (mutation-checked: 5 of 7
fail with the SDK default handler), the value boundary, and a 65-char key
end to end over None/Sign/SignAndEncrypt with a wrong key reaching the
key check (BadIdentityTokenRejected).
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
A node frozen past failure detection + StableAfter, or both sides of a partition
that heals after each downed the other, used to stay a second active node until an
operator restarted one: the peer quarantines the removed UID and Akka.Cluster
1.5.62 never acts on ThisActorSystemQuarantinedEvent.
ShutOutRestart (child of the LeaderAutoDown downing actor; opt-out via
ScadaBridge:Cluster:LeaderAutoDown:RestartWhenShutOut, default on for
leader-auto-down only) watches two signals:
- S1 ThisActorSystemQuarantinedEvent: the peer quarantined this node. If the peer
is still a live member here, only this side can be shut out -> restart now.
- S2 AssociationErrorEvent 'has a UID that has been quarantined': the peer still
runs the incarnation this node removed. A healed partition yields only S2, on
both sides. Wait ShutOutGrace (60s) for a frozen peer to restart itself, then
tiebreak.
Tiebreak: the higher address (Akka Member.AddressOrdering) restarts, the lower
stays and restarts only if still split one grace later. Removed peers are probed
(Identify, 5s -> 60s back-off) since nothing else contacts them after mutual
removal. Restart = Cluster.Down(self) -> existing self-down path.
The Host now exits 75 after an unplanned ActorSystem termination (and sets it on
the Windows service before it reports stopped): SCM recovery with failureflag 1
only restarts a service that stops with a non-zero code, and the watchdog used
to exit 0. Shipped default strategy stays auto-down.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
Pins ZB.MOM.WW.Telemetry(.Serilog) 0.2.0 -> 0.3.0. ScadaBridgeTelemetryConfig is now
the one place both the AddZbTelemetry registration and the pre-host AddZbSerilog
logger fill their options, so ScadaBridge:Telemetry:Exporter=Otlp sends logs to the
same collector as metrics and traces, with the same Resource. The pre-host container
has no AddZbTelemetry registration for the library's log sink to follow, which is
why the exporter is passed to the logger explicitly. site.id / node.role are
unchanged (still ScadaBridge:Node:SiteId ?? central / ScadaBridge:Node:Role, applied
last so a Telemetry-section key cannot make them diverge from the log enrichers);
service.version now defaults to the entry assembly's informational version.
Host.Tests 699/699 incl. ScadaBridgeTelemetryConfigTests.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
Auth 0.5.0 (all five packages) adds the passwordless ILdapGroupLookup. A new
singleton DirectoryGroupRefresher asks it for a session's current groups once
the new zb:lastgrouprefresh anchor (stamped at login) is older than
ScadaBridge:Security:LdapGroupRefresh:IntervalMinutes (default 15, Enabled
default true, CacheSeconds 60 per-node answer reuse). CookieSessionValidator
replaces the stored groups and re-maps roles; this reaches HTTP and live
circuits (once per interval, independent of the 10 s circuit refresh).
Failure policy: directory unavailable keeps the stored groups (warn, all paths
incl. fail-closed mutation checks); user not found / disabled / ambiguous /
no groups ends the session. Inert under BindMode=User (NotSupported),
LDAP disabled, or DisableLogin.
Auth 0.4.4 ApiKeyFailure.StoreUnavailable now answers 503 SERVICE_UNAVAILABLE
on the inbound API instead of a misleading 401.
Docs: Component-Security.md, components/Security.md, Component-Host.md,
register row 23 closed.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
Switch ScadaBridge from its own LoggerConfigurationFactory to AddZbSerilog
(ZB.MOM.WW.Telemetry(.Serilog) 0.1.0 -> 0.2.0) using the two 0.2.0 hooks:
- MinimumLevelGovernor: ScadaBridge:Logging:MinimumLevel, applied after
ReadFrom.Configuration so it outranks Serilog:MinimumLevel (never null, so the
floor never defers to the Serilog key; Override:* namespace entries still apply;
the one-shot conflict / unparseable-value warnings are unchanged).
- ConfigureLogger: the standby active-node exclusion filter (register row 71),
the configured node identity (the shared bootstrap stamps NodeHostname from
the machine name and skips empty values; an overwriting enricher keeps the
configured ScadaBridge:Node values verbatim), Enrich.FromLogContext and the
ExecutionLogCaptureSink.
ScadaBridgeLogging runs AddZbSerilog on a small pre-host builder and Program
installs the result as the static Log.Logger; both web hosts keep UseSerilog()
over it. One logger and one file-sink handle per process, usable before the
host is built (startup banner, warnings, pre-host Fatal), by SerilogAkkaLogger,
and after the host is disposed (shutdown line, unexpected-termination Fatal) —
AddZbSerilog's own DI registration would leave Log.Logger alone and have the
host dispose the logger.
LoggerConfigurationFactory is deleted (nothing else used it). Tests: existing
logging/standby/sink tests now run through the new pipeline, plus
ScadaBridgeLoggingParityTests (level precedence, Override:* still applies,
one-shot warning, configured identity incl. NodeHostname != MachineName and empty
SiteId, exact property set of a plain line, trace_id/span_id). Mutation-checked:
governor deferring, filter removed, identity enricher removed, FromLogContext
removed, capture sink removed each fail tests.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
AlarmConditionState.Severity mixed two conventions: OPC UA rows carried Part 9
Severity (higher = more severe) while MxGateway native alarms and computed
alarms carried a raw AVEVA-style priority (1 = most urgent). Every consumer
ranks higher as worse, so Worst Severity, the severity filter/sort and the
site event-log Error threshold picked the LEAST urgent MxGateway/computed
alarms.
- AlarmPriorityBands: the OtOpcUa GalaxyAlarmPriority table (lmxopcua#887,
b61f3e05), value for value: 1-250 -> 1000, 251-500 -> 750, 501-750 -> 500,
751-999 -> 250; <= 0 clamps to Critical, > 999 to Low.
- MxGatewayAlarmMapper bands the gateway severity (= AVEVA priority);
AlarmConditionStateFactory.ForComputed bands PriorityLevel. OPC UA unchanged.
- AlarmConditionState gains trailing Priority (int?): the raw source number,
exactly the pre-#129 Severity. AlarmStateChanged.Priority and the wire
AlarmStateUpdate.priority keep that meaning (no proto change); central derives
Severity by kind (SeverityFromPriority), so an older site decodes correctly.
- ScriptAlarm gains trailing Priority. The native MES 900-999 band and the MES
API Severity/MinSeverity/MaxSeverity key off Priority; rig seed scripts moved
from a.Severity to a.Priority, so MES output is unchanged.
- AlarmActor raise logs Error when the banded severity >= 700 (same threshold
as NativeAlarmActor): priority 1-500 Error, 501+ Warning (was raw >= 700).
- NativeAlarmActor upgrades pre-#129 native_alarm_state rows on rehydrate.
- Debug snapshot decode restores Condition.Priority from the row's priority.
- Docs: Commons, DCL, SiteRuntime, Communication, CentralUI, InboundAPI,
HighLevelReqs, MES alarm-status plan, CLAUDE.md.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
Bump ZB.MOM.WW.Theme 0.5.0 -> 0.5.3, set ThemeShell ScrollNav=true, drop
NavMenu's own .rail-scroll wrapper and the site.css rail scroll block
(keeps .rail-updates*). NavMenu test now asserts no local wrapper.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
RealMxGatewayClient.RunEventLoopAsync stored every streamed MxEvent's
WorkerSequence as its StreamEvents resume cursor before filtering by family.
The gateway's control sentinels (ReplayGap on a resume that hit evicted
events; the opt-in StreamAttached ack) carry worker_sequence 0, so a gap
reset the cursor to 0 and the next resume became a fresh stream: no replay,
no gap signal, silent loss.
Cursor rule: advance-only (max), from real worker events (sequence > 0) only.
A ReplayGap anchors the cursor at oldest_available_sequence - 1 (the gateway's
documented gap-free resume point, valid for an empty ring too) and is logged
as a warning naming the lost interval. Sentinels never reach the value
callback.
The loop body is split into internal RunEventLoopCoreAsync(IAsyncEnumerable)
so tests drive a scripted stream; 4 of the 7 new tests fail on the old loop.
Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
`dotnet ef migrations script --idempotent` from migration 0 stopped at
AddSiteIdToDataConnections (Msg 207 'SiteId') and, past it, hit Msg 156/178/137
on MigrateParametersToJsonSchema's CREATE FUNCTIONs and Msg 207 on the
ExecutionId / ParentExecutionId filtered indexes. Same root cause as #126: the
script compiles a whole migration as one batch behind IF ... BEGIN guards.
(The Msg 1911 'Category' / later @legacy errors in the issue were cascades of
those failures and disappear once they are fixed.)
- New MigrationSql.Deferred(sql): wraps a body in EXEC(N'...') with quotes
doubled, so it compiles at execution time as its own batch. Migrate() runs
the identical text.
- Deferred: AddSiteIdToDataConnections step 3 (data move + cursor, DECLAREs kept
in the same body); MigrateParametersToJsonSchema's three CREATE FUNCTIONs and
the UPDATE that calls them; AddAuditLogExecutionId / AddAuditLogParentExecutionId
filtered partition-aligned indexes. No model/snapshot change.
- IdempotentMigrationScriptTests: new IdempotentScript_FromEmpty_RunsClean_AndMatchesMigrate
runs the full script on an empty DB batch by batch, re-runs it as a no-op, and
compares a schema snapshot (columns, defaults, indexes incl. filter + data space,
FKs, checks, modules, principals, permissions, partitioning, per-table row
count + checksum) against a Migrate()-built DB. Fails on the unfixed
migrations with Msg 207 'SiteId'. Batch failures now name the migration.
Schema equivalence: Migrate() before vs after this change, and the fixed
from-empty script, all produce byte-identical snapshots (939 lines); the
57->head script still runs clean and lands on the same snapshot; the seeded
data path through AddSiteIdToDataConnections + MigrateParametersToJsonSchema
gives identical rows via the fixed script and the unfixed Migrate().
Co-Authored-By: Claude <noreply@anthropic.com>
AuditMaintenanceGrants (migration 64) landed after the flip and adds
GRANT UPDATE (SourceNode) to the purger, but the tests still migrated "back
up" only to the flip and asserted the pre-64 grant list, so the class failed
in either test order (the grant missing after DownUp, or unexpected before).
Restore to head and compare the down state against the pre-64 grant set.
Co-Authored-By: Claude <noreply@anthropic.com>
`dotnet ef migrations script --idempotent` puts each migration in ONE batch
behind IF NOT EXISTS guards, and SQL Server compiles the whole batch before any
guard runs. AddAuditLogHashChain adds ChainSeq and then creates two filtered
indexes whose WHERE clause references it in the same batch, so the script
failed with Msg 207 "Invalid column name 'ChainSeq'" on any DB at migration
<= 60 (the 2026-11-11 vd03 deploy hand-inserted GO separators instead).
- AddAuditLogHashChain: the two CREATE INDEX statements go through EXEC(N'...')
so they compile at execution time. Same indexes, same snapshot; Migrate() /
database update unaffected; DBs that already ran the migration never run it
again. The column-level GRANT compiles fine (checked at execution).
- Audit of 58-64: no other migration hits the pattern (the idempotent script
from 57 now runs clean end to end; AddConfigGraphRowVersions' plain CREATE
INDEX on a new column is not compile-checked).
- docs/plans/sql/AddAuditLogHashChain.sql: same EXEC wrap. It, and
PrefixSearchIndexes.sql / AddConfigGraphRowVersions.sql, also carried a
stray UTF-8 BOM after the prepended header comment that made sqlcmd fail
with Msg 102 on line 1 of the batch; removed.
- New IdempotentMigrationScriptTests: migrates the fixture DB to 57, runs the
generated idempotent script batch by batch, asserts every migration applied,
then re-runs it as a no-op. Fails with Msg 207 without the migration fix.
Co-Authored-By: Claude <noreply@anthropic.com>
#122: the Notification Outbox KPI snapshots ORed every status in one
aggregation, which scanned the clustered index once the table held ~1 M
Parked rows (0.7-2.6 s; Health dashboard up to 5 s). Each snapshot now runs
three status-equality legs that seek their own index (~0.12 s); a cold Health
load on the rig is 0.12-0.52 s.
#123: site_events event_type/severity indexes are now composites with
timestamp, so a filtered page is read in order and stops at the limit
(severity=Error over 1 GB: 2,287 -> 15 ms cold, 115 -> 1.6 ms warm). Costs
454 -> 530 B/row, ~14 % fewer rows under the same cap. The schema apply drops
the old indexes in place; the cap size model samples timestamp three times
and re-scores inside its band with unchanged constants.
#124: the set-based AuditLog insert's NOT EXISTS probe scanned the EventId
index and concurrent writers deadlocked on S/IX page locks. WITH (FORCESEEK):
4 writers 775 rows/s + 76 deadlocks in 30 s -> 5,214 rows/s + 0. New
concurrent-writer regression test fails 4/4 without the hint.