Minor bumps mark additive fields (1.1 sites/connections/instances, 1.2 #118
Derivation). TRN-8 added InstanceDto.AreaPath without a bump. Exporter now
stamps 1.3; ManifestValidator still gates only on bundleFormatVersion, so
1.0-1.2 bundles import unchanged and older importers accept a 1.3 bundle
(ignoring AreaPath, leaf-name fallback). Theory pins 1.0-1.4 validating Ok;
version-pinning tests read the constant. Component-Transport.md + CLAUDE.md.
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).
PendingDeployments.ConfigurationJson is now encrypted at rest; the
harness built a fresh EphemeralDataProtectionProvider per context, so
the endpoint could not decrypt what the staging context wrote. Central
nodes share one key ring; the fixture now does too.
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).
COMM-8: the failback sweep collects the due sites and probes them through
Parallel.ForEachAsync (FailbackProbeParallelism = 8) instead of awaiting each
probe (up to its 5 s deadline) in turn; per-site state stays under each
pair's own gate. The graveyard sweep still runs at the start of each pass,
which now ends after ceil(due/8) probe rounds instead of due rounds.
Test: 16 failed-over sites, 400 ms probe each: serial 6.4 s -> one pass
< 3 s asserted (~0.8 s, 2 rounds), max 8 in flight. 30 black-holed NodeAs:
~150 s -> ~20 s per pass.
DCL-10: MapQuality takes IReadOnlyList<MxStatusProxy> (the RepeatedField),
index-loops the statuses and maps the quality byte through a static
256-entry table (negatives Bad, >255 Good, as before).
Throwaway Stopwatch, Release, 1M calls with one Ok status:
old 40 B + 34.3 ns per event -> new 0 B + 0.8 ns (test pins zero allocation).
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).
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.
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.
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.
PerSiteStatus carries one serialized SiteArtifactResult per site (~155 chars
for a clean site, more with error text). The 4000-char cap made Deploy
Artifacts over ~25 sites throw on the final save, after every site had applied,
so no site was stamped and every retry failed the same way. Mapping is now
nvarchar(max); the migration + SQL script follow in their own commit.
MGT-5: HandleExportBundle resolves template names against
GetTemplateStubsAsync (untracked Id/Name projection) and instance names
against the new ITemplateEngineRepository.GetInstanceNamesAsync (Id,
UniqueName) instead of GetAllTemplatesAsync (tracked full graph incl. script
bodies) + GetAllInstancesAsync (every instance with 4 child collections).
The exporter still loads the selected rows itself.
Per export: 1 tracked multi-Include template query + 5 instance split
queries (whole tables, tracked) -> 2 narrow untracked projections.
TRN-11 (narrow subset, BundleImporter is also WP2's file):
- Derived-template apply: owner/base root names were each a
query (unindexable), twice per derived template;
now one (Id, Name, IsDerived) projection into a case-insensitive index,
falling back to the live query only when a name has no base row (the loop
only creates/deletes derived templates, so a base hit is always current).
N derived templates: 2N full-scan queries -> 1 projection (+ misses).
- Preview validation: the referenced-connection check memoises each target
site's connection names (one read per site instead of per reference).
Not done here (left for the integrator / WP2 overlap): bulk-loading the
per-row by-name lookups in the main apply loops (BI:3789-4449) and the
DependencyResolver per-id seed loads.
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.
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.
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).
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.
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).
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.
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
A navigation while an awaited load was still running disposed the component
first; the continuation then created a timer / added a singleton handler that
nothing ever disposed, rooting the dead circuit for the life of the process.
- Health: refresh timer created under _timerLock only if not disposed.
- DataConnections: same for the health-poll timer; also stops before touching
the disposed CTS when disposed during the first load.
- Deployments: subscribe to IDeploymentStatusNotifier BEFORE the first load
(the handler only schedules a reload; the generation guard orders flights).
- PendingUpdatesHealthTiles: the Invalidated subscription and the poll timer are
both created under a lifetime lock after a disposed check; Dispose unsubscribes
only what was subscribed (covers a dispose during the auth-state await too).
- AlarmSummary: StartTimer/StopTimer/Dispose atomic under _timerLock; StartTimer
refuses after dispose (Topology.StartLiveUpdatesTimer idiom).
Tests (each fails on the pre-fix component): HealthPageTests, DataConnectionsPageTests,
DeploymentsPerFlightScopeTests, PendingUpdatesHealthTilesTests (x2),
AlarmSummaryRenderTests - dispose mid-load, release the load, assert no timer and
no handler left.
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.
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).
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.
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.