Commit Graph

1130 Commits

Author SHA1 Message Date
Joseph Doherty d17e736942 Merge branch 'review/wp6' into review/integration
# Conflicts:
#	docs/requirements/Component-StoreAndForward.md
#	src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs
#	src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs
#	src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs
#	tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs
2026-12-03 11:03:44 -05:00
Joseph Doherty 9a574746dc feat(config-db): migration AuditLogChannelOccurredIndex — partition-aligned IX_AuditLog_Channel_Occurred (AUD-5, WP6 task 6.5)
Adds IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc) ON
ps_AuditLog_Month(OccurredAtUtc) via raw SQL (EF CreateIndex cannot express
the partition scheme), like ReviewRemediationIndexes. Idempotent QA/DEV
script: docs/plans/sql/AuditLogChannelOccurredIndex.sql (sqlcmd -I). Kept in
its own commit so the integrator can regenerate it on merge with the other
WPs' migrations.

Index-name pins updated: AuditLogEntityTypeConfigurationTests and
FlipAuditLogClusteredKeyMigrationTests (head shape asserts the new index is
partition-aligned on ps_AuditLog_Month; the pre-flip round-trip shape does
not carry it).
2026-12-03 10:59:03 -05:00
Joseph Doherty c8f2321a32 Merge branch 'review/wp4' into review/integration 2026-12-03 10:49:54 -05:00
Joseph Doherty 116db008fb Merge branch 'review/wp7' into review/integration 2026-12-03 10:41:19 -05:00
Joseph Doherty 2303f7a56c Merge branch 'review/wp5' into review/integration 2026-12-03 10:41:19 -05:00
Joseph Doherty 1073a8eea4 Merge branch 'review/wp3' into review/integration 2026-12-03 10:41:19 -05:00
Joseph Doherty 21243727d6 Merge branch 'review/wp2' into review/integration 2026-12-03 10:41:17 -05:00
Joseph Doherty d4e13d3aa4 fix(config-db): encrypt deployment configuration JSON at rest (CDB-1, WP1 task 1.8)
The flattened config embeds each bound data connection's decrypted
protocol JSON, and PendingDeployments / DeployedConfigSnapshots stored
it verbatim - the credentials dp:protocol:v1 protects on DataConnections
sat in plaintext in two more tables and every backup.

- DeploymentConfigSecretConverter (own DP purpose, dp:config:v1: prefix)
  on both ConfigurationJson columns: every write protected, reads accept
  legacy plaintext so un-migrated rows keep working. Schema-only
  contexts refuse the write.
- DeploymentConfigSecretUpgrade: one-time startup re-protect from
  MigrationHelper (after the protocol upgrade). A startup backfill, not
  an EF migration, because the Data Protection key ring is not reachable
  from a SQL migration script. Plaintext-detecting (NOT LIKE prefix),
  paged by Id, binary compare-and-swap (both centrals may run it),
  idempotent, and not a startup gate (logged + retried next start).
- No EF model change (has-pending-model-changes: none); no migration.

Tests: SQLite round-trip (raw column has no secret, EF read equals
original) for both tables, legacy plaintext readable then re-protected
idempotently, schema-only write refused, and the upgrade on real SQL
Server. PendingDeploymentRepositoryIntegrationTests now supplies a key
ring.

Deploy gate: upgrade both central nodes together (old binaries cannot
read protected rows).
2026-12-03 10:28:39 -05:00
Joseph Doherty f9af013982 migration: AddKpiRollupBackfillState (KPI-1, WP4 task 4.10) 2026-12-03 10:26:08 -05:00
Joseph Doherty e719e9027e fix(audit): purge/archive also cover partition 1 (rows before the first boundary) (AUD-6, WP4 task 4.11) 2026-12-03 10:26:08 -05:00
Joseph Doherty 2ef2d751cb perf(inbound-api): cached schema library snapshot, Content-Length-sized audit buffer, time-based replay prune (INB-2, INB-3, INB-4, WP6 task 6.9)
INB-2: new SharedSchemaLibraryCache (singleton, ApiMethodCacheTtl) serves the
shared-schema library to SchemaRefResolver for both the parameter and the
return validation; previously each $ref-using request read the whole library
twice (two scopes/DbContexts). No shared-schema invalidation bus exists, so
the snapshot self-heals on the TTL — the same bound the ApiMethod row itself
is already cached for (documented in Component-InboundAPI). Parsed-schema
caching was not added (parse is cheap next to the DB reads).
  50 req/s on a $ref method: 100 library reads/s -> <=1 per 5 s per node
  (test: 100 resolutions -> 1 ListAsync; reload after TTL).

INB-3: the audit body copy rents ExpectedCaptureBytes(Content-Length, cap)+1
instead of cap+1, and anything read past the declared length still reports
truncated.
  200-byte body: 1 MiB+1 rent (2 MiB LOH pool bucket) -> 201 bytes (256 B bucket).

INB-4: the replay cache's full prune scan runs at most once per 5 s (one
CAS winner) instead of on every relayed request once over 4,096 entries.
  Throwaway Stopwatch, ~15k live entries, 2,000 relayed requests:
  old per-request scan 214 us -> new 31 us (one amortised scan).
2026-12-03 10:23:50 -05:00
Joseph Doherty 2a41122a39 fix(kpi): rollup backfill plans from its own persisted watermark, not the periodic fold's MAX (KPI-1, WP4 task 4.10) 2026-12-03 10:23:13 -05:00
Joseph Doherty 5a052c6327 fix(ui): apply site scope and the history status filter in the server query, before paging (UI-7, UI-9, UI-10, WP1 task 1.7)
UI-7: Site Calls and the Notification report sent an unscoped query and
dropped other sites' rows client-side after paging - Site Calls pages
went short (Next disabled, own rows hidden), Notifications showed other
sites' counts and empty pages. New additive SourceSitesFilter on
SiteCallQueryRequest / NotificationOutboxQueryRequest (+ SourceSites /
SourceSiteIds on the repository filters; OPENJSON IN-list in the
SiteCalls keyset SQL, Contains in EF) carries the permitted identifiers;
an empty set matches nothing. Next is gated on the server page size.

UI-9: Secured Writes history paged over every status and filtered
terminal rows client-side. Additive ListSecuredWritesCommand.Statuses
reaches the repository query and count.

UI-10: Notification KPIs per-site table is narrowed to the caller's
sites (SiteScopeService.Resolve on the principal).

Tests: MSSQL mixed-site keyset/offset paging + count for both repos and
the secured-write status set; handler forwards Statuses; UI pages send
the permitted set (scoped) / none (system-wide); history requests the
terminal statuses; KPI per-site rows narrowed.
2026-12-03 10:21:01 -05:00
Joseph Doherty c5cd280739 perf(central-ui): save only changed overrides in one transaction; authorise once per action; split Test Run deadline (UI-6, UI-12, UI-13, WP6 task 6.8)
UI-6: Save overrides diffs the working values against the stored rows
(OverrideSaveDiff) and applies only the changed ones inside ONE
ExecuteInstanceAsync transaction; any row failure throws inside it so nothing
commits (no partial apply). InstanceService.SetAttributeOverrideAsync skips
the write and the UpdateOverride audit row when the value is unchanged.
  ~260 overrides, one edited: 260 transactions / ~1,300 round trips / 260
  audit rows -> 1 transaction / 1 SetAttributeOverride / 1 audit row.

UI-12: ParkedMessages bulk retry/discard authorise once per action (role +
site scope + site list) instead of per message (bunit: 5 messages -> 1 site
read, was 5; each also saved two forced session revalidations).
Deployments.LoadDataAsync resolves the scope once (new
SiteScopeService.ResolveScopeAsync) instead of IsSystemWide + PermittedSiteIds
(2 -> 1 revalidation per 500 ms reload). SecuredWrites loads connections with
one GetAllDataConnectionsAsync instead of one query per site.
Not changed: ConnectionHealthQueryService's per-tick site/connection reads.

UI-13 (decided: split deadline): the script deadline is armed when the worker
sends a new 'running' frame (RunInWorkerAsync's userCodeStarting hook, after
compile + trust check + gate); admission, process start-up and compile are
bounded by a separate StartupCeiling (30 s + the script budget) with its own
message.
  Test QueuedAndColdStartTime_IsNotChargedToTheScriptBudget (TimeoutSeconds=1,
  queued ~2 s behind four busy workers + a cold worker start):
  before: 'Script execution exceeded the 1-second sandbox timeout'
  after:  succeeds, returns 7.
2026-12-03 10:20:13 -05:00
Joseph Doherty 5c67559a25 fix(sitecalls): Parked is re-openable end to end — operator Retry/Discard reach the site tracking row and central SiteCalls (SCA-1, WP4 task 4.9) 2026-12-03 10:18:43 -05:00
Joseph Doherty d639bd67ff fix(site-runtime): static write refreshes quality/timestamp; redeploy reset gates native rehydration and the first flush (SRT-11, SRT-12, WP3 task 3.10) 2026-12-03 10:18:08 -05:00
Joseph Doherty b0c40deefb fix(site-runtime): script Asks honour the run deadline, Notify.Status checks the buffer first, routed calls wait for the script's own timeout (SRT-8, SRT-9, SRT-13, WP3 task 3.9) 2026-12-03 10:15:23 -05:00
Joseph Doherty 937fec1c4b feat(config-db): migration WidenSystemArtifactPerSiteStatus (DEP-3, WP2 task 2.9)
AlterColumn SystemArtifactDeploymentRecords.PerSiteStatus nvarchar(4000) ->
nvarchar(max), plus docs/plans/sql/WidenSystemArtifactPerSiteStatus.sql for
manual production application (not yet applied to QA/DEV). Kept in its own
commit so the integrator can regenerate it on merge.
2026-12-03 10:12:45 -05:00
Joseph Doherty bc7fae2652 fix(site-runtime): failed trigger evaluation keeps state, RateOfChange clears when flat, WhileTrue re-fires after seed adoption (SRT-2, SRT-3, SRT-4, WP3 task 3.7) 2026-12-03 10:11:15 -05:00
Joseph Doherty baecf10fea fix(transport): import diff compares secrets and bindings; preview honours the name map; CI lookups; area paths; no Rename where unsupported (TRN-2, TRN-3, TRN-6, TRN-7, TRN-8, TRN-9, WP2 tasks 2.4+2.5)
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.
2026-12-03 10:11:07 -05:00
Joseph Doherty 2162fad8e9 fix(audit): scope audit reads by site identifier, not numeric site id (MGT-2, UI-5, WP1 task 1.6)
PermittedSiteIds / SiteId claims are numeric Site.Id values while
AuditLog.SourceSiteId holds the site identifier. /api/audit/query and
/export compared the two (a scoped query was always empty, an explicit
--site of one's own site was a 403), /api/audit/tree and Flow Debugger
Replay dropped every site-side node, and the Central UI Audit Log grid
applied no scope at all.

New Commons AuditSiteScope: translate permitted ids to identifiers
(Administrator / no claims = unscoped; unresolvable = fail closed) and
apply them to a filter (never an empty SourceSiteIds, which the
repository reads as unfiltered). Used by AuditEndpoints (query, export,
tree), FlowDebugRunner.ReplayAsync, and AuditLogQueryService (grid
QueryAsync - pushed into the query before paging - and the tree).
ApplySiteScope gains the Administrator exemption.

Tests: scoped query filters by identifier, own-site explicit filter
allowed and foreign one 403, admin with claims unscoped, tree/replay get
identifiers, UI grid scoped/out-of-scope/unscoped, tree per-call scope.
2026-12-03 10:10:58 -05:00
Joseph Doherty 59817f5017 perf(deployment,template-engine): batched untracked staleness loads, staging-failure detach, lock-held Disabled re-check, targeted single-entity loads (DEP-4, DEP-5, DEP-6, TPL-4, WP6 task 6.6)
DEP-4: new ITemplateEngineRepository.GetInstancesByIdsUntrackedAsync (one
AsNoTracking split query per 500-id chunk). GetInstanceStalenessAsync preloads
each chunk into its FlattenSession; FlattenCoreAsync takes a preloaded
instance (consumed once) before falling back to the tracked per-instance load.
Deploy sessions never preload, so prepare keeps its tracked load.
  Throwaway harness, SQLite, 1,000 instances x 50 overrides:
  before: 5,000 reader commands, 51,000 tracked entities
  after:  10 reader commands, 0 tracked entities
  (wall time on in-process SQLite 2.7 s -> 2.3 s; the win on SQL Server is
  the 4,990 saved round-trips and the change tracker staying empty)

DEP-5: AddPendingDeploymentAsync supersedes prior rows with a set-based
delete (DeletePendingWhereAsync) instead of tracked key stubs, and a failed
staging save calls DetachPendingChanges under dbGate so it cannot poison the
next instance's staging save on the shared bulk context.
  Regression: prior row purged between supersede and save -> before:
  DbUpdateConcurrencyException; after: stages cleanly.

DEP-6: bulk prepare (reconcileGate != null) re-reads the instance state
untracked (new IDeploymentManagerRepository.GetInstanceStateAsync) once the
operation lock is held; Disabled -> reported in SkippedInstances with the
Disabled reason, never flattened/sent/re-enabled. Placed at the top of
PrepareUnderLockAsync so it is independent of WP7's lock-ordering change.

TPL-4: area delete uses the new shallow untracked GetInstancesBySiteIdShallowAsync;
SetAlarmOverride and Delete{Attribute,Alarm,Script} read the analysis closure
instead of the whole template table; MoveTemplate's collision check is the new
TemplateNameExistsInFolderAsync (one folder's names). SiteService already used
the include-free ISiteRepository read (unchanged).
2026-12-03 10:09:41 -05:00
Joseph Doherty 4070f7efca fix(audit): reconciliation pulls every site node with a per-(site, node) cursor (AUD-1, WP4 task 4.8) 2026-12-03 10:08:20 -05:00
Joseph Doherty a730bc0558 fix(site-runtime): watchdog follows the run across awaits; only the run's own deadline is a timeout (SRT-1, SRT-10, WP3 task 3.6) 2026-12-03 10:06:01 -05:00
Joseph Doherty 8c5d70f687 fix(transport): secret-bearing bundle export needs Administrator; scrub data-connection move reply (MGT-3, MGT-4, WP1 task 1.5)
MGT-3: a Designer could read SMTP/SMS credentials, external-system auth,
DB connection strings and data-connection configuration through bundle
export, values the management API returns to no one. Both export
surfaces now resolve the selection (dependencies included) via the new
IBundleExporter.CountSecretsAsync / ExportSecretPolicy and require
Administrator when it carries any secret; a secret-free export stays a
Designer operation. The ExportBundle gate becomes any-of [Designer,
Administrator] - a deliberate change to the frozen authz matrix. A new
ManagementAuthorizationException maps to ManagementUnauthorized.

MGT-4: data-connection move replies with DataConnectionPublicShape like
its siblings (the audit after-state switched with task 1.4).

Tests: matrix entry, Designer+secrets refused (nothing exported), Admin
and secret-free Designer succeed, UI wizard refuses a Designer, policy
counts every SecretsBlock field, move reply carries no secret.
2026-12-03 10:04:28 -05:00
Joseph Doherty c000ee3203 fix(dcl): separator-aware alarm routing, typed reply for browse/search while disconnected, server-timestamp fallback (DCL-5, DCL-6, DCL-7, WP3 task 3.4) 2026-12-03 10:04:02 -05:00
Joseph Doherty 2421a4e445 fix(centralui): system-wide users can Retry/Discard rows from a deleted site (UI-11, WP5 task 5.4)
IsRowSiteAllowedAsync on the Notification Outbox and Site Calls pages returned
'resolved is not null && ...', so a parked row whose source site no longer
resolves (deleted / renamed) - which the grid deliberately keeps listing - was
refused for everyone, Administrator included, and could not be cleared.

Now a system-wide user short-circuits to allowed before the site lookup; a
site-scoped user is still denied an unresolvable row (no Site.Id to authorize
against). Deletes NotificationReport's unused IsRowSiteAllowedSync, whose
'unresolvable defaults to allowed' contract contradicted the async check.
Design doc updated (Notification Outbox, Site Calls).

Tests: NotificationReportPageTests / SiteCallsReportPageTests
Retry_OnRowFromADeletedSite_AllowedSystemWide_DeniedScoped (system-wide case fails
pre-fix; scoped denial pinned).
2026-12-03 10:03:12 -05:00
Joseph Doherty 6dd6c50e6f fix(security): remember an unchanged passive-request role refresh per session instead of re-issuing the cookie (SEC-1, WP7 task 7.6)
The first attempt (renew the cookie on a passive Replace) contradicted the documented rule that passive requests never re-issue the cookie and was reverted; the per-session anchor record in SessionActivityTracker honours it.
2026-12-03 10:02:42 -05:00
Joseph Doherty c15bd210f7 fix(delmia,inbound): a connect-phase failure (unreachable host, connect timeout) fails over to the next URL/peer instead of OUTCOME_UNKNOWN (DLM-1, WP4 task 4.7) 2026-12-03 10:01:59 -05:00
Joseph Doherty 0a62f33ab5 fix(inbound): bound the sync prefix of inbound scripts by the method timeout (INB-1, WP7 task 7.6) 2026-12-03 10:01:06 -05:00
Joseph Doherty 6019335ba9 Revert "fix(inbound,security): bound the sync prefix of inbound scripts by the method timeout; persist a role refresh done on a passive request (INB-1, SEC-1, WP7 task 7.6)"
This reverts commit f7d3c69071.
2026-12-03 10:01:01 -05:00
Joseph Doherty 04e3969071 perf(audit-log,site-event-log): channel+age purge index with varchar binding; instance+timestamp event index (AUD-5, SEL-1, WP6 task 6.5)
AUD-5: PurgeChannelOlderThanAsync binds @channel as varchar(32) and the model
gains IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc). The migration +
partition-aligned SQL script land in the WP's final migration commit
(AuditLogChannelOccurredIndex).
  sqlcmd -I, SQL_Latin1_General_CP1_CI_AS, scratch DB with 1M AuditLog rows
  (6 channels, clustered (OccurredAtUtc, EventId), ScriptTrace override 30 d),
  steady-state per-channel tick (nothing left to purge):
  before (nvarchar, old indexes): 5,858 logical reads, 124 ms
  after  (varchar + new index):   6 logical reads, 0 ms
  new index but nvarchar param:   4,747 logical reads, 114 ms (binding matters)

SEL-1: site_events idx_events_instance -> idx_events_instance_timestamp
(instance_id, timestamp), dropped/rebuilt in place by SiteEventLogSchema.Apply
like #123; the storage-cap size model now charges 4 x timestamp per row.
  sqlite3, 2.7M rows / 20 instances, instance-filtered 501-row page:
  before: SEARCH idx_events_instance + USE TEMP B-TREE FOR ORDER BY; 396 ms
  after:  SEARCH idx_events_instance_timestamp (temp b-tree for id tiebreak only); 0.7 ms
2026-12-03 10:00:42 -05:00
Joseph Doherty 5ca998dc56 fix(audit): persist config audit rows written after the final save (DEP-1, MGT-1, TPL-3, WP1 task 1.4)
IAuditService.LogAsync only stages the row; every caller that audited
after its last SaveChangesAsync, outside the configuration-command
transaction, lost the row with the DI scope (rig: zero Disable/Enable/
Delete/DeployArtifacts rows, 16 Deploy rows for 62 deployments, one
Create/Instance row for ids up to 3876).

- New IAuditService.LogAndSaveAsync: stage + save, best-effort (logs and
  swallows any failure incl. cancellation, detaches the unsaved row).
- DeploymentService (deploy/failed/reconciled/lifecycle + timeouts),
  ArtifactDeploymentService (DeployArtifacts now before the best-effort
  stamp, RetryArtifactDeployment, DeploySiteSecrets), InstanceService,
  AreaService, SiteService: post-save LogAsync -> LogAndSaveAsync.
- ManagementActor: AuditAndSaveAsync for the non-configuration handlers
  (API keys, shared schemas, ES methods, data-connection move); move now
  audits the scrubbed public shape (MGT-4) so the fix does not start
  writing protocol credentials into AuditLogEntries.
- HandleCreateInstance no longer stages a second Create row on top of
  InstanceService's own.

Tests: real-context (SQLite) tests per family read the row back through
a second context - DeploymentService, ArtifactDeploymentService,
InstanceService, ManagementActor; each fails against the old code.
Test projects gain a ConfigurationDatabase + EF Sqlite reference.
2026-12-03 09:59:19 -05:00
Joseph Doherty 9f03726fc7 perf(audit-log): private-cache connections, owed-range pull index, age-seekable purge, batched tracking reads (AUD-2, AUD-3, AUD-4, AUD-7, WP6 task 6.4)
AUD-2: drop Cache=Shared from the file-backed site audit connection string
(kept only by the in-memory test override). Two private WAL connections no
longer share table-level locks.
  Test OpenReadTransaction_DoesNotStallTheWriter (deferred read txn open on a
  connection with the writer's connection string): with Cache=Shared the
  write timed out (>5 s; would retry to the 30 s command timeout and fault);
  without it the write completes in well under 1 s.

AUD-3: new partial index IX_fwd_owed (OccurredAtUtc, EventId) WHERE
ForwardState IN (owed states); ReadPendingSinceAsync names it (INDEXED BY),
repeats the literal state list (bound parameters never satisfy a partial
index's WHERE), and orders/keysets on fs.EventId (same value, no join for
the sort).
  sqlite3 3.54, 1,000,000 audit rows (90% Pending), no ANALYZE stats, 256-row page:
  before: SEARCH fs USING INDEX IX_fwd (ForwardState=?) + TEMP B-TREE FOR ORDER BY; 2.6-3.5 s
  after:  SEARCH fs USING INDEX IX_fwd_owed (OccurredAtUtc>?), no sort; 0.6-0.7 ms
          (keyset page with afterId: 3.6 s -> 0.6 ms)

AUD-4: purge page adds IsCachedKind IN (0, 1) so IX_fwd seeks
(state, kind, age).
  same DB, 100k Forwarded rows, nothing expiring (the final short page):
  before: SEARCH IX_fwd (ForwardState=?) 16.9 ms (linear in retained rows)
  after:  SEARCH IX_fwd (ForwardState=? AND IsCachedKind=? AND OccurredAtUtc<?) 0.06 ms

AUD-7: new optional Commons IOperationTrackingBatchReader (separate interface
so test doubles/implementations are untouched); OperationTrackingStore
implements GetStatusManyAsync (one writer-queue barrier, chunked IN reads on
one connection). SiteAuditTelemetryActor resolves a drain's distinct ids with
one batched read when available, else memoises per-id reads per drain.
  A BatchSize-256 drain: 256 sequential barriers + 256 connections -> 1 barrier,
  1 connection, 1 query (ids sharing an operation are read once).
2026-12-03 09:58:29 -05:00
Joseph Doherty 11992075e8 fix(notify,esg): classify dropped SMTP connections, OAuth2 token-endpoint outages and body-read connection loss as transient (NTF-2, ESG-1, WP4 task 4.6) 2026-12-03 09:58:10 -05:00
Joseph Doherty d52aff1bee fix(dcl): bind the reconnect re-subscribe loop to its session; shared supervisory advise ignores the first caller's token (DCL-4, DCL-9, WP3 task 3.3) 2026-12-03 09:57:13 -05:00
Joseph Doherty cbdd9fc40b fix(transport): template Overwrite clears compositions and cascades removed slots' derived templates (TRN-4, TRN-5, WP2 task 2.6)
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.
2026-12-03 09:55:53 -05:00
Joseph Doherty 5f7b850af2 fix(outbox): persist a delivery outcome on its own token, not the shutdown token (NTF-1, WP4 task 4.5) 2026-12-03 09:54:37 -05:00
Joseph Doherty 2e8bede3b2 fix(dcl): retry failed alarm re-subscribes, check alarm item create status, retry connection-level re-subscribe rows (DCL-2, DCL-3, DCL-8, WP3 task 3.2) 2026-12-03 09:53:44 -05:00
Joseph Doherty 2969ee44e5 fix(centralui): no-tracking default on the circuit DbContext; mutations on their own scope (UI-1, WP5 task 5.1)
The circuit-lifetime ScadaBridgeDbContext tracked every entity a page ever
loaded, so a reload returned the first-loaded instance and never saw changes
made in another scope (Move to Site, Topology area renames, a template script
edited by the CLI/import - which a later save then silently reverted).

- CircuitDbContextTrackingHandler (CircuitHandler, registered by AddCentralUI)
  sets QueryTrackingBehavior.NoTracking on the circuit scope's context only,
  when the circuit host is built (before any component). Management-actor,
  command-transaction, HTTP-request and hosted-service scopes keep TrackAll.
- Every remaining page mutation that ran a load-modify-save service on the
  circuit context now runs it via ScopeFactory.InNewScopeAsync (fresh tracking
  context): TemplateEdit (17 TemplateService calls), Templates (5 TemplateService
  + 5 TemplateFolderService), TemplateCreate, SharedScripts, SharedScriptForm,
  TransportImport.ApplyAsync. (Sites/Topology moved in 5.2.)
- Design doc: Component-CentralUI.md 'Circuit DbContext lifetime'.

Tests: CircuitDbContextTrackingTests - handler scoping + registration, the three
finding scenarios against a real SQLite context (moved connection also asserts
the pre-fix staleness without the handler), and a source-scan guard that fails
on any mutating call through a circuit-injected load-modify-save service.
2026-12-03 09:52:56 -05:00
Joseph Doherty f02fe9d696 fix(comm): key site liveness on central receive time; gRPC connect timeout + connect-phase deadline failover (COMM-4, COMM-5, WP4 task 4.4) 2026-12-03 09:52:54 -05:00
Joseph Doherty fe60c4a1dc fix(template-engine): resolve alarm on-trigger scripts by name per composition chain (TPL-1, TPL-2, TPL-5, WP2 tasks 2.2+2.3)
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.
2026-12-03 09:51:00 -05:00
Joseph Doherty 6adfc9f449 fix(dcl): seeds never overwrite a newer live value; Good on reconnect resets only the subscribe backoff (DCL-1, SRT-6, WP3 tasks 3.1 + 3.8)
3.1: seed values are flagged on TagValueReceived; a reconnect/resolution
re-seed for a tag that already delivered a live value in the current
adapter generation is dropped, an initial-subscribe seed is replaced by the
latest live value (a joining instance may have missed earlier live values).
3.8: the connection actor tells subscribers ConnectionQualityChanged(Good)
on re-entering Connected; InstanceActor's Good branch only resets the
Lever-1 backoff and no longer stamps bound attributes Good.
2026-12-03 09:49:57 -05:00
Joseph Doherty f7d3c69071 fix(inbound,security): bound the sync prefix of inbound scripts by the method timeout; persist a role refresh done on a passive request (INB-1, SEC-1, WP7 task 7.6) 2026-12-03 09:49:51 -05:00
Joseph Doherty 76c50a29c2 fix(commons): flow fold ranks lifecycle before time, schema required/legacy-type checks, CSV trailing comma, case-insensitive audit enum parse (CMN-6,7,8,9,12, WP7 task 7.5) 2026-12-03 09:48:24 -05:00
Joseph Doherty 61c6278bd0 fix(cli): site/data-connection/api-method update are preserve-if-null partial updates (CLI-2, WP2 task 2.8)
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.
2026-12-03 09:48:00 -05:00
Joseph Doherty 54416e33bf perf(store-and-forward): rank sweep lanes over a covering narrow index, join payloads for the page only (SF-3, WP6 task 6.3)
The fair-paging sweep computed ROW_NUMBER() over every column of every due
row, so each sweep sorted the whole due backlog with payloads into temp
storage. The ranking now projects only id + lane keys over the new covering
idx_sf_messages_lane (status, category, target, created_at,
last_attempt_at_ms, retry_interval_ms, id), takes the page of ids, and joins
back by primary key. The index is created in place by StoreAndForwardSchema
(idempotent, local only — not part of CDC capture). idx_sf_messages_category
is kept (still used by parked-count filters).

EXPLAIN QUERY PLAN + timing, sqlite3 3.54, 200,000 due rows x ~1 KB payload,
20 targets x 3 categories, LIMIT 500:
  before: SEARCH idx_sf_messages_status_created (status=?) + USE TEMP B-TREE
          FOR ORDER BY (window over full rows) + outer temp b-tree; 1.29 s
  after:  SEARCH USING COVERING INDEX idx_sf_messages_lane (no window sort),
          outer temp b-tree over (id, rank, created_at) only, PK join of 500
          rows; 0.15 s
2026-12-03 09:47:29 -05:00
Joseph Doherty c1db7094eb fix(comm): fold post-snapshot debug events into the snapshot and fail fast on a snapshot-request failure (COMM-3, COMM-7, WP4 task 4.3) 2026-12-03 09:47:29 -05:00
Joseph Doherty 5469ece012 fix(script-analysis): key the trust verdict cache on every verdict input (CMN-5, WP1 task 1.3)
TrustVerdictCache keyed on the code hash alone while the verdict also
depends on the analysis reference set (and its degraded-fallback mode).
The key is now (code SHA-256, degraded flag, base-reference fingerprint,
extra-reference digest), length-prefixed. File-backed extra references
are digested (path/size/mtime/kind/aliases/embed) so the Central UI run
gate's calls are cached under their own key; an extra reference with no
stable identity stays uncacheable.

The old extras test passed a PortableExecutableReference[] positionally,
which binds to the explicit-base overload, so it never exercised the
extras path; the tests now use the named argument.
2026-12-03 09:46:32 -05:00
Joseph Doherty d3c6295670 perf(site-runtime): route expression triggers by referenced keys; heap cap eviction; O(1) predictor lane (SRT-7, SRT-14, CMN-11, WP6 task 6.2)
SRT-7: TriggerExpressionKeys extracts the literal Attributes["k"] /
Children["c"].Attributes["k"] reads of an Expression trigger; the Instance
Actor routes the child only those attributes (new MonitoredAttributes routing
kind). Anything not pinnable (non-literal key, alias/member access of the
globals, Parent, parse error, zero reads) falls back to all-changes. Child
actors are unchanged (narrow: WP3 edits ScriptActor/AlarmActor).
  Evidence: instance with 250 attributes at 1 Hz and 10 expression children
  each reading 2 attributes — child mailbox deliveries (and per-eval snapshot
  copies + CTS allocations) go from 2,500/s to 20/s (routing-map test pins
  that a non-read attribute has no route).

SRT-14: EnforceCap selects the oldest conditions with a bounded max-heap and
rate-limits the eviction Warning (1/min with an eviction count).
  Stopwatch, n=1001 k=1 per transition at the cap: OrderBy 13.0-18.2 us -> heap 1.2 us.

CMN-11: FlowShapePredictor looks up a node by the index encoded in its
append-only id (O(1)) instead of a linear scan per AddNode/Annotate.
  Stopwatch PredictSiteScript, Release: 5,000 nodes 125.5 -> 54.9 ms,
  20,000 nodes 434.2 -> 83.3 ms.
2026-12-03 09:45:50 -05:00