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.
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).
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.
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
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.
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.
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.
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.
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
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.
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.
Deploy/Disable/Enable/Delete now acquire the per-instance lock first, then reload the instance
(new IDeploymentManagerRepository.ReloadInstanceAsync) and validate on the fresh state, so a
Delete queued behind a deploy no longer takes the NotDeployed shortcut and orphans the running instance.
AppDomain's assembly-loading members (ExecuteAssembly[ByName], Load,
CreateInstanceFrom[AndUnwrap], CreateInstanceAndUnwrap) were neither a
forbidden scope nor exact gateway names, so a script could load and run
an external assembly (even from a UNC path) in the host process. The
whole type is now a forbidden scope, like System.Environment and
System.GC. AppContext/Debugger were considered and left alone (no
assembly-load surface).
Tests: every AppDomain loading spelling (member access, ?., using static,
alias) is flagged; the ban is exact-type.