Commit Graph

3413 Commits

Author SHA1 Message Date
Joseph Doherty 922021c476 docs(plans): record follow-up decisions and outcome of the 2026-12-02 review remediation 2026-12-03 12:27:43 -05:00
Joseph Doherty 6f51e7b4d3 Merge branch 'review/playwright' 2026-12-03 12:27:19 -05:00
Joseph Doherty 8267ab8ffc fix(store-and-forward): immediate delivery never overtakes buffered rows of its lane (SF-1 follow-up, decision B)
SF-1 kept the retry sweep per-(category,target) FIFO, but a NEW message could
still be delivered inline while older rows of the same lane were buffered and
backing off: EnqueueAsync's immediate attempt, and the first attempt that
ExternalSystem.CachedCall / Database.CachedWrite make themselves before handing
a transient failure to S&F. A recovered target then received B before A, and
A's later retry overwrote B.

Now each of those paths first probes the lane (StoreAndForwardService.
LaneHasPendingAsync: SELECT EXISTS seek on the covering idx_sf_messages_lane,
pinned by an EXPLAIN QUERY PLAN test; fails open to the old behaviour). An
occupied lane gets no inline attempt: the message is buffered due-immediately
(LastAttemptAt null, deferToSweep) behind the older rows and the sweep delivers
in order. Empty lanes (or parked-only) are unchanged. Notify.Send already
deferred to the sweep. Return contract unchanged: handle/TrackedOperationId at
once, WasBuffered=true, tracking reads Pending.

Regression tests (fail before, pass after): service, CachedCall, CachedWrite;
plus lane-probe + query-plan storage tests. Component-StoreAndForward.md and
Component-ExternalSystemGateway.md updated.
2026-12-03 12:22:31 -05:00
Joseph Doherty 5acb16ca07 test(playwright): fix stale selectors after UI refactor (h1 headings, collapsed Topology/Audit disclosures, ParameterValueForm ids, method-select race) 2026-12-03 12:14:28 -05:00
Joseph Doherty 3f98d40fa4 fix(transport): bump bundle schemaVersion 1.2 -> 1.3 for the additive instance AreaPath (TRN-8 follow-up, decision A)
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.
2026-12-03 12:06:01 -05:00
Joseph Doherty 18311eb385 test(deployment): WP7 race-delete test asserts the WP1 LogAndSaveAsync audit call (integration fix) 2026-12-03 11:13:59 -05:00
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 b3fba593a3 test(management): stub the analysis closure SetAlarmOverride now reads (TPL-4, WP6 task 6.6) 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 a621b5d659 Merge branch 'review/wp1' into review/integration 2026-12-03 10:41:17 -05:00
Joseph Doherty b065ffa93e test(integration): share one key ring across the fetch harness contexts (CDB-1, WP1 task 1.8)
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.
2026-12-03 10:38:00 -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 790db4ff94 perf(communication,dcl): bounded-parallel failback probes; allocation-free MxGateway quality map (COMM-8, DCL-10, WP6 task 6.10)
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).
2026-12-03 10:25:50 -05:00
Joseph Doherty 455f1ff2af test(site-runtime): starvation test asserts a timed-out eval resolves as unknown, not false (SRT-2, WP3 task 3.7) 2026-12-03 10:24:02 -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 7eabb82287 fix(config-db): unbound SystemArtifactDeploymentRecord.PerSiteStatus (DEP-3, WP2 task 2.9)
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.
2026-12-03 10:12:45 -05:00
Joseph Doherty 8966c54508 perf(transport,management): bundle export resolves names from projections; import memoises name and connection lookups (MGT-5, TRN-11, WP6 task 6.7)
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.
2026-12-03 10:12:37 -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 7addd846a1 fix(centralui): no timers/subscriptions created after a mid-load dispose (UI-4, WP5 task 5.3)
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.
2026-12-03 10:00:36 -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