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
This commit is contained in:
Joseph Doherty
2026-12-03 11:03:44 -05:00
84 changed files with 4722 additions and 233 deletions
@@ -102,8 +102,18 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi
_logger = logger;
_nodeIdentity = nodeIdentity;
// AUD-2: a PRIVATE cache per connection. With Cache=Shared both connections shared one
// cache and its table-level locks, so WAL snapshot isolation did not apply between them —
// a long backlog scan on the read connection stalled the batch writer (in 150 ms
// SQLITE_LOCKED retry sleeps, up to the command timeout) and vice versa. Two private WAL
// connections let reads run against a snapshot while the writer commits. The busy
// timeout stays Microsoft.Data.Sqlite's default command timeout (30 s), which only a
// second writer could ever hit — there is one write connection. (The in-memory test
// override still uses Mode=Memory;Cache=Shared, which needs the shared cache to share
// one database at all.)
var connectionString = connectionStringOverride
?? $"Data Source={_options.DatabasePath};Cache=Shared";
?? $"Data Source={_options.DatabasePath}";
ConnectionString = connectionString;
_connection = new SqliteConnection(connectionString);
_connection.Open();
@@ -227,7 +237,7 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi
}
using var cmd = _connection.CreateCommand();
cmd.CommandText = """
cmd.CommandText = $"""
-- Canonical, append-only / write-once: the 10 fields of the canonical
-- ZB.MOM.WW.Audit.AuditEvent stored directly (DetailsJson carries the
-- ScadaBridge domain fields). No forwarding state lives here — that is
@@ -268,6 +278,17 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi
CREATE INDEX IF NOT EXISTS IX_fwd
ON audit_forward_state (ForwardState, IsCachedKind, OccurredAtUtc);
-- AUD-3: the reconciliation pull reads the OWED states ordered by
-- (OccurredAtUtc, EventId); IX_fwd cannot serve that across an IN of three
-- states, so every page scanned + sorted the whole owed backlog. This partial
-- index is exactly the pull's range and order, so a page is an ordered range
-- read that stops at the limit. The query names it with INDEXED BY and repeats
-- the same literal state list (a partial index is only usable when the query's
-- WHERE implies the index's). Additive and idempotent.
CREATE INDEX IF NOT EXISTS IX_fwd_owed
ON audit_forward_state (OccurredAtUtc, EventId)
WHERE ForwardState IN ({OwedStatesSql});
-- Node-local key/value state that must survive a process restart. Holds the
-- reconciliation pull's served-rows high-water mark ('max_served_rowid'), so a
-- restart no longer resets the bound that lets a covering cursor retire rows the
@@ -866,7 +887,8 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi
? "fs.OccurredAtUtc >= $since"
// Composite keyset, lexicographic on (OccurredAtUtc, EventId) — the same
// ordering the query applies, so it is a strict "everything after this row".
: "(fs.OccurredAtUtc > $since OR (fs.OccurredAtUtc = $since AND ae.EventId > $afterId))";
// The OccurredAtUtc >= $since conjunct is implied but lets the index seek.
: "fs.OccurredAtUtc >= $since AND (fs.OccurredAtUtc > $since OR (fs.OccurredAtUtc = $since AND fs.EventId > $afterId))";
// fs.rowid rides along as an 11th column purely to maintain
// _maxServedRowId — the insertion-order high-water mark that bounds
@@ -876,14 +898,13 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi
SELECT ae.EventId, ae.OccurredAtUtc, ae.Actor, ae.Action, ae.Outcome,
ae.Category, ae.Target, ae.SourceNode, ae.CorrelationId, ae.DetailsJson,
fs.rowid
FROM audit_event ae
JOIN audit_forward_state fs ON fs.EventId = ae.EventId
WHERE fs.ForwardState IN ($pending, $pushAbandoned, $rejected)
FROM audit_forward_state fs INDEXED BY IX_fwd_owed
JOIN audit_event ae ON ae.EventId = fs.EventId
WHERE fs.ForwardState IN ({OwedStatesSql})
AND {cursorPredicate}
ORDER BY fs.OccurredAtUtc ASC, ae.EventId ASC
ORDER BY fs.OccurredAtUtc ASC, fs.EventId ASC
LIMIT $limit;
""";
AddOwedStateParameters(cmd);
// Normalise to UTC ISO-8601 round-trip format to match how OccurredAtUtc
// is stored on insert ("o" format) — string comparison is monotonic for
// that encoding so we can index-scan against it.
@@ -931,6 +952,17 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi
/// Binds the three "owed to central" states — <c>$pending</c>, <c>$pushAbandoned</c>,
/// <c>$rejected</c> — that the reconciliation pull serves and retires.
/// </summary>
/// <summary>
/// AUD-3: the owed states as SQL literals, shared by the <c>IX_fwd_owed</c> partial-index
/// definition and the pull query that uses it — SQLite only uses a partial index when the
/// query's WHERE implies the index's, which a bound parameter never does.
/// </summary>
internal static readonly string OwedStatesSql =
$"'{AuditForwardState.Pending}', '{SiteAuditForwardStates.PushAbandoned}', '{SiteAuditForwardStates.Rejected}'";
/// <summary>The connection string both connections were opened with (AUD-2 regression surface).</summary>
internal string ConnectionString { get; }
private static void AddOwedStateParameters(SqliteCommand cmd)
{
cmd.Parameters.AddWithValue("$pending", AuditForwardState.Pending.ToString());
@@ -1535,6 +1567,7 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi
CREATE TEMP TABLE purge_ids AS
SELECT EventId FROM audit_forward_state
WHERE ForwardState IN ($forwarded, $reconciled)
AND IsCachedKind IN (0, 1) -- AUD-4: lets IX_fwd seek (state, kind, age) instead of walking each state's whole range
AND OccurredAtUtc < $cutoff
LIMIT $limit;
""";
@@ -233,6 +233,44 @@ public class SiteAuditTelemetryActor : ReceiveActor
}
}
/// <summary>
/// AUD-7: builds the per-drain tracking lookup. With an <see cref="IOperationTrackingBatchReader"/>
/// the distinct ids are read in one batched call (a fault there surfaces per row, exactly as a
/// per-id fault did, so those rows stay Pending); otherwise each distinct id is read once and
/// memoised for the drain.
/// </summary>
private async Task<Func<TrackedOperationId, Task<TrackingStatusSnapshot?>>> PrefetchTrackingAsync(
IReadOnlyList<AuditEvent> pending, CancellationToken ct)
{
var store = _trackingStore!;
if (store is IOperationTrackingBatchReader batchReader)
{
var ids = pending
.Where(r => r.CorrelationId is not null)
.Select(r => new TrackedOperationId(r.CorrelationId!.Value))
.Distinct()
.ToList();
try
{
var found = await batchReader.GetStatusManyAsync(ids, ct).ConfigureAwait(false);
return id => Task.FromResult(found.TryGetValue(id, out var s) ? s : null);
}
catch (Exception ex)
{
return _ => Task.FromException<TrackingStatusSnapshot?>(ex);
}
}
var memo = new Dictionary<TrackedOperationId, TrackingStatusSnapshot?>();
return async id =>
{
if (memo.TryGetValue(id, out var cached)) return cached;
var snapshot = await store.GetStatusAsync(id, ct).ConfigureAwait(false);
memo[id] = snapshot;
return snapshot;
};
}
/// <summary>
/// Combined-telemetry drain. Reads cached-lifecycle audit
/// rows, joins each with the matching <see cref="IOperationTrackingStore"/>
@@ -287,6 +325,12 @@ public class SiteAuditTelemetryActor : ReceiveActor
var graceSeconds = Math.Max(0, _options.CachedTrackingGraceSeconds);
var abandonBefore = DateTime.UtcNow - TimeSpan.FromSeconds(graceSeconds);
// AUD-7: the tracking store is a single-writer queue whose every read waits behind
// all queued writes. Resolve the batch's distinct operation ids ONCE — one barrier
// for the drain when the store offers a batched read, and never the same id twice
// (several lifecycle rows of one operation share it) otherwise.
var lookup = await PrefetchTrackingAsync(pending, ct).ConfigureAwait(false);
foreach (var auditRow in pending)
{
if (auditRow.CorrelationId is null)
@@ -302,8 +346,7 @@ public class SiteAuditTelemetryActor : ReceiveActor
TrackingStatusSnapshot? snapshot;
try
{
snapshot = await _trackingStore
.GetStatusAsync(new TrackedOperationId(auditRow.CorrelationId.Value), ct)
snapshot = await lookup(new TrackedOperationId(auditRow.CorrelationId.Value))
.ConfigureAwait(false);
}
catch (Exception ex)
@@ -64,6 +64,14 @@ public sealed class SiteScopeService
public async Task<IReadOnlySet<int>> PermittedSiteIdsAsync()
=> (await ResolveAsync()).Sites;
/// <summary>
/// UI-12: the system-wide flag AND the permitted site ids from ONE authoritative resolve —
/// for callers that need both (calling <see cref="IsSystemWideAsync"/> then
/// <see cref="PermittedSiteIdsAsync"/> revalidates the session twice).
/// </summary>
/// <returns>Whether the user is unrestricted, and otherwise the permitted <c>Site.Id</c> set.</returns>
public Task<(bool IsSystemWide, IReadOnlySet<int> Sites)> ResolveScopeAsync() => ResolveAsync();
/// <summary>
/// Returns the subset of <paramref name="sites"/> the user is permitted to
/// see. A system-wide user gets the full list back unchanged.
@@ -609,10 +609,12 @@
// instance, rather than by loading every instance to build an
// InstanceId → SiteId map. A system-wide user passes null (no filter);
// a scoped user's EMPTY grant is a real filter that matches nothing.
var systemWide = await SiteScope.IsSystemWideAsync();
// UI-12: one authoritative resolve per reload (reloads arrive every 500 ms during a
// bulk deploy), not one for the flag and another for the id set.
var (systemWide, permittedSites) = await SiteScope.ResolveScopeAsync();
IReadOnlyCollection<int>? siteScope = systemWide
? null
: (await SiteScope.PermittedSiteIdsAsync()).ToArray();
: permittedSites.ToArray();
_appliedSearch = _searchInput.Trim();
var filter = new DeploymentListFilter(
@@ -1422,20 +1422,43 @@
return;
}
var failures = new List<string>();
foreach (var (attrName, value) in toSave)
// UI-6: send only the overrides that actually changed. _overrideValues is seeded
// with every existing override, so saving the whole map rewrote (and audited) all
// of them — ~260 transactions and audit rows to change one value.
var changed = OverrideSaveDiff.Changed(toSave, _existingOverrides);
if (changed.Count == 0)
{
var result = await MutationServices.GetRequiredService<ConfigurationCommandService>().ExecuteInstanceAsync(Id, null, (instanceService, currentUser) => instanceService.SetAttributeOverrideAsync(Id, attrName, value, currentUser));
if (result.IsSuccess)
_existingOverrides[attrName] = result.Value!;
else
failures.Add($"{attrName}: {result.Error}");
_toast.ShowInfo("No override changes to save.");
_saving = false;
return;
}
// ...and apply them in ONE configuration transaction: a failure on any row rolls
// the whole save back instead of leaving a partial apply reported only as a count.
try
{
var saved = await MutationServices.GetRequiredService<ConfigurationCommandService>().ExecuteInstanceAsync(Id, null, async (instanceService, currentUser) =>
{
var rows = new List<(string Name, InstanceAttributeOverride Row)>(changed.Count);
var failed = new List<string>();
foreach (var (attrName, value) in changed)
{
var result = await instanceService.SetAttributeOverrideAsync(Id, attrName, value, currentUser);
if (result.IsSuccess) rows.Add((attrName, result.Value!));
else failed.Add($"{attrName}: {result.Error}");
}
if (failed.Count > 0) throw new OverrideSaveDiff.BatchFailedException(failed);
return rows;
});
foreach (var (attrName, row) in saved)
_existingOverrides[attrName] = row;
_toast.ShowSuccess($"Saved {saved.Count} override(s).");
}
catch (OverrideSaveDiff.BatchFailedException batch)
{
_toast.ShowError(
$"No overrides were saved — {batch.Failures.Count} failed: {string.Join("; ", batch.Failures)}");
}
if (failures.Count > 0)
_toast.ShowError($"Failed to save {failures.Count} override(s): {string.Join("; ", failures)}");
var savedCount = toSave.Count - failures.Count;
if (savedCount > 0)
_toast.ShowSuccess($"Saved {savedCount} override(s).");
}
catch (Exception ex)
{
@@ -0,0 +1,35 @@
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment;
/// <summary>
/// UI-6: the Instance Configure "Save overrides" diff — which working values differ from the
/// stored override rows — and the failure that rolls a batched save back.
/// </summary>
internal static class OverrideSaveDiff
{
/// <summary>
/// The working values that are new or differ (ordinal) from the stored override; an
/// unchanged value is not re-saved (no transaction, no audit row).
/// </summary>
/// <param name="working">The page's working override values, by attribute name.</param>
/// <param name="existing">The stored override rows, by attribute name.</param>
/// <returns>The (attribute, value) pairs to save.</returns>
public static IReadOnlyList<(string Name, string? Value)> Changed(
IReadOnlyDictionary<string, string?> working,
IReadOnlyDictionary<string, InstanceAttributeOverride> existing) =>
working
.Where(kv => !existing.TryGetValue(kv.Key, out var row)
|| !string.Equals(row.OverrideValue, kv.Value, StringComparison.Ordinal))
.Select(kv => (kv.Key, kv.Value))
.ToList();
/// <summary>Thrown inside the save transaction when any row fails, so nothing commits.</summary>
/// <param name="failures">The per-attribute failure messages.</param>
public sealed class BatchFailedException(IReadOnlyList<string> failures)
: Exception($"{failures.Count} override(s) failed to save.")
{
/// <summary>Gets the per-attribute failure messages.</summary>
public IReadOnlyList<string> Failures { get; } = failures;
}
}
@@ -644,15 +644,21 @@
_bulkInProgress = true;
_bulkAction = "Retry";
int success = 0, failed = 0;
// UI-12: authorise ONCE per bulk action — the role check and the site-scope check each
// force an LDAP-group → role re-map against the database, and the site list is a full
// read; per message that was ~3 round trips × N before any relay was sent.
if (!await AuthorizeBulkMutationAsync())
{
_bulkInProgress = false;
_bulkAction = null;
return;
}
foreach (var id in ids)
{
try
{
var req = new ParkedMessageRetryRequest(Guid.NewGuid().ToString("N"), _selectedSiteId, id, DateTimeOffset.UtcNow);
await MutationAuth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Deployer);
var mutationSite = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == _selectedSiteId);
if (mutationSite is null || !await SiteScope.IsSiteAllowedAsync(mutationSite.Id)) throw new UnauthorizedAccessException("Site access was revoked.");
var resp = await CommunicationService.RetryParkedMessageAsync(_selectedSiteId, req);
var resp = await CommunicationService.RetryParkedMessageAsync(_selectedSiteId, req);
if (resp.Success) success++; else failed++;
}
catch { failed++; }
@@ -680,15 +686,21 @@
_bulkInProgress = true;
_bulkAction = "Discard";
int success = 0, failed = 0;
// UI-12: authorise ONCE per bulk action — the role check and the site-scope check each
// force an LDAP-group → role re-map against the database, and the site list is a full
// read; per message that was ~3 round trips × N before any relay was sent.
if (!await AuthorizeBulkMutationAsync())
{
_bulkInProgress = false;
_bulkAction = null;
return;
}
foreach (var id in ids)
{
try
{
var req = new ParkedMessageDiscardRequest(Guid.NewGuid().ToString("N"), _selectedSiteId, id, DateTimeOffset.UtcNow);
await MutationAuth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Deployer);
var mutationSite = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == _selectedSiteId);
if (mutationSite is null || !await SiteScope.IsSiteAllowedAsync(mutationSite.Id)) throw new UnauthorizedAccessException("Site access was revoked.");
var resp = await CommunicationService.DiscardParkedMessageAsync(_selectedSiteId, req);
var resp = await CommunicationService.DiscardParkedMessageAsync(_selectedSiteId, req);
if (resp.Success) success++; else failed++;
}
catch { failed++; }
@@ -700,6 +712,27 @@
await FetchPage();
}
/// <summary>
/// UI-12: the bulk actions' one-time authorisation — Deployer role and the selected site
/// still in scope — taken once before the per-message loop instead of per message.
/// </summary>
private async Task<bool> AuthorizeBulkMutationAsync()
{
try
{
await MutationAuth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Deployer);
var mutationSite = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == _selectedSiteId);
if (mutationSite is null || !await SiteScope.IsSiteAllowedAsync(mutationSite.Id))
throw new UnauthorizedAccessException("Site access was revoked.");
return true;
}
catch (Exception ex)
{
_toast.ShowError($"Not permitted: {ex.Message}");
return false;
}
}
// ── Single actions ──
private async Task RetrySingle(ParkedMessageEntry msg)
@@ -332,10 +332,15 @@
try
{
_sites = await SiteRepository.GetAllSitesAsync();
// UI-12: one connection read for every site, not one per site (the N+1 the Sites
// page removed under CentralUI-012).
var connectionsBySiteId = (await SiteRepository.GetAllDataConnectionsAsync())
.GroupBy(c => c.SiteId)
.ToDictionary(g => g.Key, g => (IReadOnlyList<DataConnection>)g.ToList());
foreach (var site in _sites)
{
_connectionsBySite[site.SiteIdentifier] =
await SiteRepository.GetDataConnectionsBySiteIdAsync(site.Id);
connectionsBySiteId.TryGetValue(site.Id, out var conns) ? conns : Array.Empty<DataConnection>();
}
}
catch (Exception ex)
@@ -20,6 +20,15 @@ public static class SandboxWorkerProtocol
private sealed record Start(SandboxRunRequest Request, bool External, bool Database, bool Bound);
private sealed record ConnectionInfo(string Provider, string ConnectionString, bool Open);
/// <summary>
/// UI-13: the generous ceiling on everything BEFORE user code runs — admission wait, worker
/// process start-up, runtime JIT and the first Roslyn compile — added on top of the
/// script's own budget. The script deadline (<c>TimeoutSeconds</c>) only starts when the
/// worker reports it is about to run user code, so a cold start or a queue behind other
/// Test Runs no longer eats the budget the operator set for the script. Settable for tests.
/// </summary>
internal static TimeSpan StartupCeiling { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>Runs one child under a deadline; a slot remains charged until confirmed process exit.</summary>
/// <param name="request">The sandbox run request to execute in the child process.</param>
/// <param name="services">The service provider supplying host services for the run.</param>
@@ -41,8 +50,14 @@ public static class SandboxWorkerProtocol
ISharedScriptCatalog catalog, CancellationToken caller, Action<int>? started = null)
{
var seconds = Math.Clamp(request.TimeoutSeconds ?? 5, 1, 10);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(caller);
deadline.CancelAfter(TimeSpan.FromSeconds(seconds));
// UI-13: two deadlines. The ceiling covers start-up + compile + the script budget and is
// armed now; the script deadline is armed only when the worker sends its "running" frame.
// Every wait below uses deadline.Token, which the ceiling (and the caller) also cancel.
var ceilingSpan = StartupCeiling + TimeSpan.FromSeconds(seconds);
using var ceiling = CancellationTokenSource.CreateLinkedTokenSource(caller);
ceiling.CancelAfter(ceilingSpan);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ceiling.Token);
var userCodeStarted = false;
var clock = Stopwatch.StartNew();
var acquired = false;
Process? process = null;
@@ -84,6 +99,16 @@ public static class SandboxWorkerProtocol
var frame = await ReadAsync(process.StandardOutput.BaseStream, deadline.Token);
if (frame.Kind == "result")
return frame.Data.Deserialize<SandboxRunResult>(Json) ?? throw new InvalidDataException("Missing sandbox result.");
if (frame.Kind == "running")
{
// UI-13: user code is about to run — start the script's own budget now.
if (!userCodeStarted)
{
userCodeStarted = true;
deadline.CancelAfter(TimeSpan.FromSeconds(seconds));
}
continue;
}
if (frame.Kind != "call") throw new InvalidDataException("Unexpected sandbox message.");
deadline.Token.ThrowIfCancellationRequested();
Frame reply;
@@ -98,6 +123,8 @@ public static class SandboxWorkerProtocol
await WriteAsync(process.StandardInput.BaseStream, reply, deadline.Token);
}
}
catch (OperationCanceledException) when (!userCodeStarted && ceiling.IsCancellationRequested && !caller.IsCancellationRequested)
{ return new(false, null, null, "", $"The sandbox did not start running the script within its {ceilingSpan.TotalSeconds:0}-second start-up ceiling (Test Runs queued or the node is busy); try again.", SandboxErrorKind.Timeout, clock.ElapsedMilliseconds, null); }
catch (OperationCanceledException)
{ return new(false, null, null, "", $"Script execution exceeded the {seconds}-second sandbox timeout or was canceled.", SandboxErrorKind.Timeout, clock.ElapsedMilliseconds, null); }
catch (ScriptSandboxException ex)
@@ -189,13 +216,23 @@ public static class SandboxWorkerProtocol
using var provider = services.BuildServiceProvider();
using var cache = new MemoryCache(new MemoryCacheOptions());
var runner = new ScriptAnalysisService(rpc, cache, provider);
var result = await runner.RunInWorkerAsync(start.Request, CancellationToken.None);
var result = await runner.RunInWorkerAsync(start.Request, CancellationToken.None, rpc.NotifyRunningAsync);
await WriteAsync(output, new Frame("result", null, Encode(result)), CancellationToken.None);
}
private sealed class Rpc(Stream input, Stream output) : ISharedScriptCatalog, IExternalSystemClient, IDatabaseGateway, ISandboxInstanceGateway
{
private readonly SemaphoreSlim _gate = new(1);
/// <summary>UI-13: tells the host user code is about to run, so it starts the script deadline.</summary>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task NotifyRunningAsync(CancellationToken ct)
{
await _gate.WaitAsync(ct);
try { await WriteAsync(output, new Frame("running", null, Encode(null)), ct); }
finally { _gate.Release(); }
}
private async Task<JsonElement> Call(string method, object?[] args, CancellationToken ct)
{
await _gate.WaitAsync(ct);
@@ -286,6 +286,18 @@ public class ScriptAnalysisService
/// <param name="ct">Cancellation token for the run.</param>
/// <returns>A <see cref="SandboxRunResult"/> describing the outcome, return value, console output, and any error.</returns>
public async Task<SandboxRunResult> RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct)
=> await RunInWorkerAsync(request, ct, userCodeStarting: null);
/// <summary>Execution core invoked only by the disposable worker executable.</summary>
/// <param name="request">The sandbox run request including code, kind, parameters, and optional instance binding.</param>
/// <param name="ct">Cancellation token for the run.</param>
/// <param name="userCodeStarting">
/// UI-13: invoked once compile, trust check and admission are done, immediately before the
/// root script runs — the worker reports it so the host starts the script deadline then.
/// </param>
/// <returns>A <see cref="SandboxRunResult"/> describing the outcome, return value, console output, and any error.</returns>
public async Task<SandboxRunResult> RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct,
Func<CancellationToken, Task>? userCodeStarting)
{
if (string.IsNullOrWhiteSpace(request.Code))
{
@@ -513,6 +525,8 @@ public class ScriptAnalysisService
// and a queued run reports Timeout rather than hanging.
await SandboxRunGate.WaitAsync(linkedCts.Token).ConfigureAwait(false);
gateAcquired = true;
if (userCodeStarting is not null)
await userCodeStarting(linkedCts.Token).ConfigureAwait(false);
// Run on a thread-pool thread with no SynchronizationContext: a
// bound script's Instance.SetAttribute / Attributes[...] block
@@ -413,6 +413,16 @@ public interface IDeploymentManagerRepository
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
/// <returns>The instance, or null if not found.</returns>
Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
/// <summary>
/// DEP-6: reads an instance's CURRENT lifecycle state straight from the database,
/// untracked — bypassing EF identity resolution, which would otherwise answer with the
/// state of an entity this unit of work loaded earlier.
/// </summary>
/// <param name="instanceId">The instance id.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The state, or <see langword="null"/> when the instance does not exist.</returns>
Task<InstanceState?> GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default);
/// <summary>
/// Refreshes <paramref name="instance"/> in place from the database so a caller that
/// waited for the per-instance operation lock can validate the state the command ahead
@@ -286,6 +286,18 @@ public interface ITemplateEngineRepository
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task that resolves to the matching instance, or <see langword="null"/> if not found.</returns>
Task<Instance?> GetInstanceByIdAsync(int id, CancellationToken cancellationToken = default);
/// <summary>
/// DEP-4: loads several instances with the same child collections as
/// <see cref="GetInstanceByIdAsync"/>, <b>untracked</b>, in one split query per chunk of
/// ids — for read-only paths (fleet staleness) that must not fill the scoped change
/// tracker with every deployed instance's overrides and bindings.
/// </summary>
/// <param name="ids">The instance ids; missing ids are absent from the result.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The instances found.</returns>
Task<IReadOnlyList<Instance>> GetInstancesByIdsUntrackedAsync(
IReadOnlyCollection<int> ids, CancellationToken cancellationToken = default);
/// <summary>Retrieves all instances.</summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task that resolves to a read-only list of all instances.</returns>
@@ -301,6 +313,38 @@ public interface ITemplateEngineRepository
/// <returns>A task that resolves to a read-only list of instances for the specified site.</returns>
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default);
/// <summary>
/// TPL-4: a site's instances WITHOUT their child collections, untracked — for checks
/// that only need identity, name and area (area/site delete guards), which used to load
/// and track every instance's overrides and bindings.
/// </summary>
/// <param name="siteId">The site ID.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The site's instances, shallow and untracked.</returns>
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default);
/// <summary>
/// MGT-5: every instance's (Id, UniqueName) — the name index bundle export resolves
/// <c>--instances</c> against, instead of loading every instance with its child collections.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>One (Id, UniqueName) pair per instance.</returns>
Task<IReadOnlyList<(int Id, string UniqueName)>> GetInstanceNamesAsync(CancellationToken cancellationToken = default);
/// <summary>
/// TPL-4: whether a template other than <paramref name="excludeTemplateId"/> named
/// <paramref name="name"/> (case-insensitively) already sits in <paramref name="folderId"/>
/// (<see langword="null"/> = the root) — the folder-move collision check, which used to load
/// the whole template table.
/// </summary>
/// <param name="folderId">The destination folder, or null for the root.</param>
/// <param name="name">The template name.</param>
/// <param name="excludeTemplateId">The template being moved.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns><see langword="true"/> when a sibling with that name exists.</returns>
Task<bool> TemplateNameExistsInFolderAsync(
int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default);
/// <summary>Reads one bounded, untracked page of topology instance rows for a site/area.</summary>
/// <param name="siteId">The site ID.</param>
/// <param name="areaId">The area ID to filter by, or null for every area.</param>
@@ -0,0 +1,28 @@
using ZB.MOM.WW.ScadaBridge.Commons.Types;
// Same namespace convention as IOperationTrackingStore (see the note there).
namespace ZB.MOM.WW.ScadaBridge.Commons.Interfaces;
/// <summary>
/// Optional batched read surface of an <see cref="IOperationTrackingStore"/> (AUD-7).
/// </summary>
/// <remarks>
/// Kept as a separate interface rather than a new <see cref="IOperationTrackingStore"/> member so
/// existing implementations and test doubles are untouched: a consumer probes for it and falls
/// back to per-id <see cref="IOperationTrackingStore.GetStatusAsync"/> when it is absent. The
/// read has the same read-your-writes guarantee as <c>GetStatusAsync</c>, but pays the writer
/// queue barrier once for the whole set instead of once per id.
/// </remarks>
public interface IOperationTrackingBatchReader
{
/// <summary>
/// Returns the latest snapshot of each supplied id that has a tracking row. Ids with no row
/// (purged or never recorded) are absent from the result.
/// </summary>
/// <param name="ids">The operation ids to read; duplicates are ignored.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The snapshots found, keyed by id.</returns>
Task<IReadOnlyDictionary<TrackedOperationId, TrackingStatusSnapshot>> GetStatusManyAsync(
IReadOnlyCollection<TrackedOperationId> ids,
CancellationToken ct = default);
}
@@ -438,31 +438,7 @@ public sealed class SitePairChannelProvider : IDisposable
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false))
{
SweepGraveyard();
var now = DateTime.UtcNow;
foreach (var kvp in _sites)
{
var pair = kvp.Value;
bool due;
lock (pair.Gate)
{
due = !pair.CurrentIsA && pair.ChannelA is not null && now >= pair.NextProbeUtc;
}
if (due)
{
try
{
await TryFailbackAsync(kvp.Key, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Failback probe for site {TargetSiteId} faulted", kvp.Key);
}
}
}
await RunDueFailbackProbesAsync(DateTime.UtcNow, ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
@@ -471,6 +447,54 @@ public sealed class SitePairChannelProvider : IDisposable
}
}
/// <summary>COMM-8: how many failback probes one sweep runs concurrently.</summary>
internal const int FailbackProbeParallelism = 8;
/// <summary>
/// COMM-8: probes every site that is due for failback at <paramref name="nowUtc"/>,
/// concurrently up to <see cref="FailbackProbeParallelism"/>. The probes used to run one
/// after another, each up to its 5 s deadline, so 30 black-holed NodeAs made one pass take
/// ~150 s: a site whose NodeA had recovered waited minutes past its backoff, and the
/// graveyard sweep (which runs once per pass) stalled with it. Per-site state is guarded by
/// each pair's own gate, so concurrent probes of different sites do not interact.
/// </summary>
/// <param name="nowUtc">The time the due check is evaluated at.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that completes when every due probe has finished.</returns>
internal async Task RunDueFailbackProbesAsync(DateTime nowUtc, CancellationToken ct)
{
var due = new List<string>();
foreach (var kvp in _sites)
{
var pair = kvp.Value;
lock (pair.Gate)
{
if (!pair.CurrentIsA && pair.ChannelA is not null && nowUtc >= pair.NextProbeUtc)
due.Add(kvp.Key);
}
}
if (due.Count == 0)
return;
await Parallel.ForEachAsync(due,
new ParallelOptions { MaxDegreeOfParallelism = FailbackProbeParallelism, CancellationToken = ct },
async (siteId, token) =>
{
try
{
await TryFailbackAsync(siteId, token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Failback probe for site {TargetSiteId} faulted", siteId);
}
}).ConfigureAwait(false);
}
/// <summary>
/// Parks a channel that is no longer reachable through <see cref="_sites"/> instead of
/// disposing it inline.
@@ -235,6 +235,14 @@ public class AuditLogEntityTypeConfiguration : IEntityTypeConfiguration<AuditLog
.IsDescending(false, false, true)
.HasDatabaseName("IX_AuditLog_Channel_Status_Occurred");
// AUD-5: the per-channel retention purge (DELETE TOP (@batch) ... WHERE Category =
// @channel AND OccurredAtUtc < @threshold) had no index with the two predicates
// adjacent — Status sits between them in IX_AuditLog_Channel_Status_Occurred — so each
// batch scanned most of the table. Created via raw SQL ON ps_AuditLog_Month so it stays
// partition-aligned for the partition-switch purge (AuditLogChannelOccurredIndex).
builder.HasIndex(e => new { e.Channel, e.OccurredAtUtc })
.HasDatabaseName("IX_AuditLog_Channel_Occurred");
builder.HasIndex(e => new { e.Target, e.OccurredAtUtc })
.IsDescending(false, true)
.HasFilter("[Target] IS NOT NULL")
@@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
{
/// <summary>
/// AUD-5 (WP6 task 6.5): <c>IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc)</c> for the
/// per-channel retention purge (<c>DELETE TOP (@batch) ... WHERE Category = @channel AND
/// OccurredAtUtc &lt; @threshold</c>), whose channel and age predicates were not adjacent in
/// any index.
/// </summary>
public partial class AuditLogChannelOccurredIndex : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
// AuditLog is monthly-partitioned (ps_AuditLog_Month) with a partition-switch purge,
// so the index MUST be partition-aligned. EF's CreateIndex cannot express the
// ON ps_AuditLog_Month(OccurredAtUtc) clause -> raw SQL, exactly as
// ReviewRemediationIndexes / AddAuditLogSourceNode. On a large production AuditLog
// consider WITH (ONLINE = ON) (Enterprise edition) in the generated script.
migrationBuilder.Sql(@"
CREATE NONCLUSTERED INDEX IX_AuditLog_Channel_Occurred
ON dbo.AuditLog (Category, OccurredAtUtc)
ON ps_AuditLog_Month(OccurredAtUtc);");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(@"
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IX_AuditLog_Channel_Occurred' AND object_id = OBJECT_ID('dbo.AuditLog'))
DROP INDEX IX_AuditLog_Channel_Occurred ON dbo.AuditLog;");
}
}
}
@@ -2043,6 +2043,9 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
.IsDescending(false, true)
.HasDatabaseName("IX_AuditLog_Actor_Occurred");
b.HasIndex("Channel", "OccurredAtUtc")
.HasDatabaseName("IX_AuditLog_Channel_Occurred");
b.HasIndex("EventId", "OccurredAtUtc")
.IsUnique()
.HasDatabaseName("UX_AuditLog_EventId_Occurred");
@@ -769,10 +769,10 @@ VALUES
pBatch.Value = (int)Math.Min(batchSize, maxRows - totalDeleted);
cmd.Parameters.Add(pBatch);
var pChannel = cmd.CreateParameter();
pChannel.ParameterName = "@channel";
pChannel.Value = channel;
cmd.Parameters.Add(pChannel);
// AUD-5: bind as varchar(32) to match the Category column. An untyped string
// parameter goes out as nvarchar, which under a SQL collation converts the
// column side and rules out a seek on IX_AuditLog_Channel_Occurred.
AddParameter(cmd, "@channel", SqlDbType.VarChar, size: 32, channel);
var pThreshold = cmd.CreateParameter();
pThreshold.ParameterName = "@threshold";
@@ -407,21 +407,20 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
// Supersession: a newer deploy for the same instance replaces any prior pending
// row. Safe because the per-instance operation lock serializes same-instance
// deploys. SaveChanges is deferred to the caller, matching the other Add methods.
// deploys. The new row's SaveChanges is deferred to the caller, matching the other
// Add methods.
//
// Only the prior rows' KEYS are read: each row carries the whole flattened
// ConfigurationJson (tens of KB), and materialising it just to delete it was the
// dominant cost of the supersede. The delete itself stays a tracked Remove (not
// ExecuteDelete) so it still commits atomically with the new row in the caller's
// SaveChanges.
var priorIds = await _dbContext.Set<PendingDeployment>()
.Where(p => p.InstanceId == pending.InstanceId)
.Select(p => p.Id)
.ToListAsync(cancellationToken);
foreach (var id in priorIds)
{
RemovePendingByKey(id);
}
// DEP-5: the prior rows are removed with a set-based ExecuteDelete keyed on the
// instance — never materialised (each carries the whole flattened ConfigurationJson)
// and never tracked. The old tracked key-only stubs made the caller's SaveChanges
// throw DbUpdateConcurrencyException whenever the TTL purge (or reconciliation)
// removed one of those rows first, and the failed stub then stayed tracked and
// poisoned every later staging save on the shared bulk-deploy context. The trade
// is that the supersede commits on its own, just before the insert: a failed
// insert leaves the instance with no pending row, which is what the superseded
// deploy was about to become anyway.
var instanceId = pending.InstanceId;
await DeletePendingWhereAsync(p => p.InstanceId == instanceId, cancellationToken);
await _dbContext.Set<PendingDeployment>().AddAsync(pending, cancellationToken);
}
@@ -505,29 +504,6 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
return rows.Count;
}
/// <summary>
/// Marks the pending row with primary key <paramref name="id"/> for deletion on the next
/// <c>SaveChanges</c> without loading it: an already-tracked instance is removed in place,
/// otherwise a key-only stub is attached and removed (EF deletes by key).
/// </summary>
/// <param name="id">Primary key of the pending row.</param>
private void RemovePendingByKey(int id)
{
var set = _dbContext.Set<PendingDeployment>();
var tracked = set.Local.FirstOrDefault(p => p.Id == id);
if (tracked != null)
{
set.Remove(tracked);
return;
}
var stub = new PendingDeployment(
string.Empty, 0, string.Empty, string.Empty, string.Empty,
default, default) { Id = id };
set.Attach(stub);
set.Remove(stub);
}
/// <inheritdoc />
public async Task<int> PurgeTerminalDeploymentRecordsAsync(
DateTimeOffset cutoffUtc,
@@ -801,6 +777,18 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
return entry.State == EntityState.Detached;
}
/// <inheritdoc />
public async Task<InstanceState?> GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default)
{
// A scalar projection is never tracked and never identity-resolved, so this sees a
// state committed by another request after this context loaded the instance.
return await _dbContext.Set<Instance>()
.Where(i => i.Id == instanceId)
.Select(i => (InstanceState?)i.State)
.FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default)
{
return await _dbContext.Set<Instance>()
@@ -501,6 +501,29 @@ public class TemplateEngineRepository : ITemplateEngineRepository
.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
}
/// <inheritdoc />
public async Task<IReadOnlyList<Instance>> GetInstancesByIdsUntrackedAsync(
IReadOnlyCollection<int> ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(ids);
var result = new List<Instance>(ids.Count);
// Chunked so the IN list stays well under SQL Server's 2,100-parameter limit.
foreach (var chunk in ids.Distinct().Chunk(500))
{
result.AddRange(await _context.Instances
.AsNoTracking()
.Where(i => chunk.Contains(i.Id))
.Include(i => i.AttributeOverrides)
.Include(i => i.AlarmOverrides)
.Include(i => i.ConnectionBindings)
.Include(i => i.NativeAlarmSourceOverrides)
.AsSplitQuery()
.ToListAsync(cancellationToken));
}
return result;
}
/// <inheritdoc />
public async Task<IReadOnlyList<Instance>> GetAllInstancesAsync(CancellationToken cancellationToken = default)
{
@@ -521,6 +544,40 @@ public class TemplateEngineRepository : ITemplateEngineRepository
.ToListAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default)
{
return await _context.Instances
.AsNoTracking()
.Where(i => i.SiteId == siteId)
.ToListAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<IReadOnlyList<(int Id, string UniqueName)>> GetInstanceNamesAsync(CancellationToken cancellationToken = default)
{
var rows = await _context.Instances
.AsNoTracking()
.Select(i => new { i.Id, i.UniqueName })
.ToListAsync(cancellationToken);
return rows.Select(r => (r.Id, r.UniqueName)).ToList();
}
/// <inheritdoc />
public async Task<bool> TemplateNameExistsInFolderAsync(
int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(name);
// Only the destination folder's names are read (one narrow projection), then compared
// case-insensitively in memory — independent of the database collation.
var siblingNames = await _context.Templates
.AsNoTracking()
.Where(t => t.FolderId == folderId && t.Id != excludeTemplateId)
.Select(t => t.Name)
.ToListAsync(cancellationToken);
return siblingNames.Any(n => string.Equals(n, name, StringComparison.OrdinalIgnoreCase));
}
/// <inheritdoc />
public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default)
{
@@ -713,16 +713,36 @@ public sealed class RealMxGatewayClient : IMxGatewayClient
/// Maps MXAccess quality. A failing status proxy is authoritative bad; otherwise
/// the OPC-style quality byte: ≥192 Good, ≥64 Uncertain, else Bad.
/// </summary>
private static QualityCode MapQuality(int quality, IEnumerable<MxStatusProxy> statuses)
/// <remarks>
/// DCL-10: on the per-value event path (~37 500 events/s per site at target). Takes the
/// concrete repeated field and index-loops it — <c>IEnumerable.Any</c> boxed the
/// repeated-field enumerator on every event although the list is normally empty or one
/// entry — and maps the quality byte through a static table (no per-call work beyond a
/// bounds check and an array read).
/// </remarks>
internal static QualityCode MapQuality(int quality, IReadOnlyList<MxStatusProxy> statuses)
{
if (statuses.Any(s => !s.IsSuccess()))
return QualityCode.Bad;
return quality switch
for (var i = 0; i < statuses.Count; i++)
{
>= 192 => QualityCode.Good,
>= 64 => QualityCode.Uncertain,
_ => QualityCode.Bad,
};
if (!statuses[i].IsSuccess())
return QualityCode.Bad;
}
if (quality < 0) return QualityCode.Bad;
return quality < QualityByByte.Length ? QualityByByte[quality] : QualityCode.Good;
}
/// <summary>
/// DCL-10: OPC-style quality byte → quality: ≥192 Good, ≥64 Uncertain, else Bad. Values above
/// 255 map to Good and negatives to Bad, exactly as the former range switch did.
/// </summary>
private static readonly QualityCode[] QualityByByte = BuildQualityMap();
private static QualityCode[] BuildQualityMap()
{
var map = new QualityCode[256];
for (var q = 0; q < map.Length; q++)
map[q] = q >= 192 ? QualityCode.Good : q >= 64 ? QualityCode.Uncertain : QualityCode.Bad;
return map;
}
private static MxValue ToMxValue(object? value) => value switch
@@ -63,6 +63,9 @@ public class DeploymentService
/// Reason reported on every <see cref="SkippedInstanceResult"/> a bulk site
/// deploy produces for a <see cref="InstanceState.Disabled"/> instance.
/// </summary>
/// <summary>DEP-4: instances bulk-loaded (untracked) per chunk by the fleet staleness read.</summary>
private const int StalenessPreloadChunk = 500;
internal const string DisabledSkipReason =
"Disabled — bulk deploy preserves disabled state; deploy individually to re-enable";
@@ -330,6 +333,20 @@ public class DeploymentService
{
var instanceId = instance.Id;
// DEP-6: a bulk deploy loaded its candidates once, up front, and EF identity
// resolution hands Prepare that same tracked entity — so a Disable committed after
// the batch started was invisible here, and the batch would deploy (and finalise
// as enabled) an instance the operator had just stopped. Disable/enable take this
// operation lock too, so a fresh, untracked read of the state taken while holding
// it is authoritative. Single-instance deploy (no reconcileGate) keeps
// deploy-and-enable as its explicit operator action.
if (reconcileGate is not null
&& await _repository.GetInstanceStateAsync(instanceId, cancellationToken) == InstanceState.Disabled)
{
lockHandle.Dispose();
return PreparedDeployment.Skipped(DisabledSkipReason);
}
// Generate unique deployment ID
var deploymentId = Guid.NewGuid().ToString("N");
@@ -503,6 +520,15 @@ public class DeploymentService
{
command = await StagePendingDeploymentAsync(prepared, user, cancellationToken);
}
catch
{
// DEP-5: a failed staging save leaves its Added row tracked on the scoped
// context; in a bulk deploy every later instance's staging save would retry
// it and fail the same way. Drop it while still holding dbGate (the only
// repository writer in phase 2), like MarkDeploymentFailedAsync does (P7-5).
_repository.DetachPendingChanges();
throw;
}
finally
{
dbGate?.Release();
@@ -833,8 +859,19 @@ public class DeploymentService
string ConfigJson,
string SiteIdentifier,
IDisposable? LockHandle,
Result<DeploymentRecord>? EarlyResult)
Result<DeploymentRecord>? EarlyResult,
string? SkipReason = null)
{
/// <summary>
/// DEP-6: a bulk-deploy instance found Disabled once its operation lock was held —
/// reported as a skipped row (never sent, never re-enabled), not as a failure.
/// </summary>
/// <param name="reason">The skip reason shown in the bulk summary.</param>
/// <returns>A prepared deployment holding no lock, with <see cref="SkipReason"/> set.</returns>
public static PreparedDeployment Skipped(string reason) =>
new(null!, string.Empty, null!, string.Empty, string.Empty, string.Empty, null,
Result<DeploymentRecord>.Failure(reason), reason);
/// <summary>Builds a prepare-phase-resolved deployment carrying the given result and holding no lock.</summary>
/// <param name="result">The result to hand back to the caller.</param>
/// <returns>A prepared deployment whose <see cref="EarlyResult"/> is set.</returns>
@@ -1077,6 +1114,13 @@ public class DeploymentService
continue;
}
if (step.SkipReason is { } skipReason)
{
skipped.Add(new SkippedInstanceResult(instance.Id, instance.UniqueName, skipReason));
disabledCount++;
continue;
}
if (step.EarlyResult is { } early)
{
results.Add(ToInstanceResult(instance.Id, instance.UniqueName, early));
@@ -2092,13 +2136,25 @@ public class DeploymentService
// resolved together after the loop with ONE untracked snapshot read.
var mismatched = new Dictionary<int, string>();
foreach (var instanceId in instanceIds.Distinct())
// DEP-4: load the deployed instances in untracked chunks (one split query each)
// instead of a tracked four-Include load per instance — the evaluator's scoped
// context used to end up tracking every deployed instance, override and binding.
var toEvaluate = instanceIds.Distinct().Where(deployedHashes.ContainsKey).ToList();
foreach (var instanceId in toEvaluate)
{
cancellationToken.ThrowIfCancellationRequested();
if (!deployedHashes.TryGetValue(instanceId, out var deployedHash))
continue;
if ((evaluated % StalenessPreloadChunk) == 0)
{
var chunk = toEvaluate.Skip(evaluated).Take(StalenessPreloadChunk).ToList();
session.PreloadInstances(
await _templateRepository.GetInstancesByIdsUntrackedAsync(chunk, cancellationToken)
?? (IReadOnlyList<Instance>)Array.Empty<Instance>());
}
evaluated++;
// Read-only path: hash only — no validation (its result was always discarded
@@ -1,3 +1,4 @@
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
@@ -48,6 +49,7 @@ public sealed class FlattenSession
private readonly Dictionary<int, CachedChain> _chains = new();
private readonly Dictionary<int, (long Version, IReadOnlyList<TemplateComposition> Compositions)> _compositions = new();
private readonly Dictionary<int, IReadOnlyDictionary<int, DataConnection>> _dataConnections = new();
private readonly Dictionary<int, Instance> _preloadedInstances = new();
private IReadOnlyList<ResolvedScript>? _sharedScripts;
private IReadOnlyDictionary<string, string>? _schemaLibrary;
@@ -78,6 +80,27 @@ public sealed class FlattenSession
/// <summary>Number of per-site data-connection queries that missed the memo.</summary>
public int DataConnectionLoads { get; private set; }
/// <summary>
/// DEP-4: hands the session instances already loaded in bulk (untracked) so the flatten
/// does not load each one again. Only read-only callers (fleet staleness) preload; a
/// deploy's session never does, so prepare keeps its tracked load.
/// </summary>
/// <param name="instances">The preloaded instances.</param>
public void PreloadInstances(IEnumerable<Instance> instances)
{
foreach (var instance in instances)
_preloadedInstances[instance.Id] = instance;
}
/// <summary>
/// Takes (and forgets) a preloaded instance, so a chunked caller never holds more than
/// one chunk of the fleet in memory.
/// </summary>
/// <param name="instanceId">The instance id.</param>
/// <returns>The preloaded instance, or <see langword="null"/> when none was preloaded.</returns>
public Instance? TakePreloadedInstance(int instanceId) =>
_preloadedInstances.Remove(instanceId, out var instance) ? instance : null;
/// <summary>
/// Every template id this session resolved — the union of all inheritance and
/// composed chains it walked. The staleness fast path records the watermark
@@ -190,8 +190,9 @@ public class FlatteningPipeline : IFlatteningPipeline
private async Task<Result<(FlattenedConfiguration Config, IReadOnlyDictionary<int, DataConnection> DataConnections)>>
FlattenCoreAsync(int instanceId, FlattenSession session, CancellationToken cancellationToken)
{
// Load instance with full graph
var instance = await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken);
// Load instance with full graph (DEP-4: a read-only caller may have bulk-preloaded it)
var instance = session.TakePreloadedInstance(instanceId)
?? await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken);
if (instance == null)
return Result<(FlattenedConfiguration, IReadOnlyDictionary<int, DataConnection>)>.Failure(
$"Instance with ID {instanceId} not found.");
@@ -260,7 +260,9 @@ public static class EndpointExtensions
var sharedSchemaRepo =
httpContext.RequestServices.GetService<ISharedSchemaRepository>();
var resolveRef = await SchemaRefResolver.BuildAsync(
sharedSchemaRepo, [method.ParameterDefinitions], httpContext.RequestAborted);
sharedSchemaRepo, [method.ParameterDefinitions],
httpContext.RequestServices.GetService<SharedSchemaLibraryCache>(), // INB-2
httpContext.RequestAborted);
var paramResult = ParameterValidator.Validate(body, method.ParameterDefinitions, resolveRef);
if (!paramResult.IsValid)
@@ -651,7 +651,9 @@ public class InboundScriptExecutor
var sharedSchemaRepo =
scope?.ServiceProvider.GetService<ISharedSchemaRepository>();
var resolveRef = await SchemaRefResolver.BuildAsync(
sharedSchemaRepo, [method.ReturnDefinition], cts.Token);
sharedSchemaRepo, [method.ReturnDefinition],
scope?.ServiceProvider.GetService<SharedSchemaLibraryCache>(), // INB-2
cts.Token);
// Validate the script's return value against the
// method's declared ReturnDefinition. A method whose script returns a
@@ -528,6 +528,17 @@ public sealed class AuditWriteMiddleware
/// afterwards so the framework's next reader (the endpoint handler's
/// JSON parser) sees the full body.
/// </remarks>
/// <summary>
/// INB-3: how many body bytes the audit copy expects to read — the declared
/// <c>Content-Length</c> when it is under the cap, else the cap. The scratch buffer is
/// rented at this plus one byte.
/// </summary>
/// <param name="contentLength">The request's declared Content-Length, if any.</param>
/// <param name="capBytes">The audit capture cap.</param>
/// <returns>The expected capture length in bytes.</returns>
internal static int ExpectedCaptureBytes(long? contentLength, int capBytes) =>
contentLength is long declared && declared >= 0 && declared < capBytes ? (int)declared : capBytes;
private static async Task<(string? body, bool truncated)> ReadBufferedRequestBodyAsync(
HttpRequest request,
int capBytes)
@@ -543,7 +554,14 @@ public sealed class AuditWriteMiddleware
// (and immediately discard) `cap + 1` bytes per request — the pool
// may hand back a buffer LARGER than `limit`, so we treat `limit`
// (not `buffer.Length`) as the read ceiling.
var limit = capBytes + 1;
//
// INB-3: size the rent to the declared Content-Length when it is under the cap. A
// 200-byte body used to rent cap + 1 (1 MiB + 1 → the 2 MiB pool bucket, LOH) per
// request; a burst beyond the pool's per-core retention allocated fresh LOH arrays.
// Kestrel enforces that the body matches Content-Length, and anything read past the
// declared length is still reported as truncated below.
var expected = ExpectedCaptureBytes(request.ContentLength, capBytes);
var limit = expected + 1;
var buffer = ArrayPool<byte>.Shared.Rent(limit);
try
{
@@ -567,8 +585,8 @@ public sealed class AuditWriteMiddleware
return (null, false);
}
var truncated = total > capBytes;
var bytesForString = truncated ? capBytes : total;
var truncated = total > expected;
var bytesForString = truncated ? expected : total;
var content = DecodeUtf8Bounded(buffer, bytesForString, cutAtValidBytes: truncated);
return (string.IsNullOrEmpty(content) ? null : content, truncated);
}
@@ -83,13 +83,39 @@ internal static class RelayProvenance
context.Items[AuditWriteMiddleware.InboundExecutionIdItemKey] = proof.ExecutionId;
}
/// <summary>INB-4: the full replay-cache scan runs at most once per this many seconds.</summary>
private const int ReplayPruneIntervalSeconds = 5;
/// <summary>Unix second before which no further prune scan runs (INB-4).</summary>
private static long _nextPruneAt;
/// <summary>Number of prune scans performed — a test hook for INB-4.</summary>
internal static int PruneScans;
private static bool TryRecordProof(Proof proof)
=> TryRecordProof(proof.ExecutionId, proof.Nonce!, proof.Time);
/// <summary>Records a proof as seen; <see langword="false"/> for a replay or a full cache.</summary>
/// <param name="executionId">The proof's execution id.</param>
/// <param name="nonce">The proof's nonce.</param>
/// <param name="proofTime">The proof's own unix-second timestamp.</param>
/// <returns>Whether the proof was new and recorded.</returns>
internal static bool TryRecordProof(Guid executionId, string nonce, long proofTime)
{
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
// INB-4: prune on a time basis. Each entry lives ~301 s past its proof time, so above
// ~14 relayed req/s the count stays over the threshold with nothing expired, and the
// old every-call scan walked up to the whole dictionary per relayed request. One
// thread per interval wins the CAS and scans; everyone else skips straight to the add.
if (SeenProofs.Count >= ReplayPruneThreshold)
{
foreach (var kv in SeenProofs)
if (kv.Value <= now) SeenProofs.TryRemove(kv);
var due = Interlocked.Read(ref _nextPruneAt);
if (now >= due && Interlocked.CompareExchange(ref _nextPruneAt, now + ReplayPruneIntervalSeconds, due) == due)
{
Interlocked.Increment(ref PruneScans);
foreach (var kv in SeenProofs)
if (kv.Value <= now) SeenProofs.TryRemove(kv);
}
}
// Still full after pruning live entries: fail closed rather than grow without bound.
@@ -97,7 +123,7 @@ internal static class RelayProvenance
// The proof is valid for +/- the window around its own timestamp, so keep the record
// until the far edge of that window.
return SeenProofs.TryAdd(proof.ExecutionId.ToString("N") + ":" + proof.Nonce, proof.Time + ProofWindowSeconds + 1);
return SeenProofs.TryAdd(executionId.ToString("N") + ":" + nonce, proofTime + ProofWindowSeconds + 1);
}
/// <summary>Reads a stream fully, failing if it exceeds the given byte limit.</summary>
@@ -44,9 +44,26 @@ public static class SchemaRefResolver
/// A synchronous <c>name → schema JSON?</c> resolver, or <c>null</c> when no definition
/// uses a <c>$ref</c> (so the validators take their unchanged no-resolver path).
/// </returns>
public static Task<Func<string, string?>?> BuildAsync(
ISharedSchemaRepository? repository,
IEnumerable<string?> definitions,
CancellationToken ct = default)
=> BuildAsync(repository, definitions, cache: null, ct);
/// <summary>
/// As <see cref="BuildAsync(ISharedSchemaRepository?, IEnumerable{string?}, CancellationToken)"/>,
/// serving the library from <paramref name="cache"/> when one is supplied (INB-2) instead of
/// reading it from the database on every call.
/// </summary>
/// <param name="repository">The shared-schema repository, or <c>null</c> when none is registered.</param>
/// <param name="definitions">The schema definition JSON strings to be validated (parameter and/or return).</param>
/// <param name="cache">The process-wide library snapshot cache, or <c>null</c> to read the repository directly.</param>
/// <param name="ct">Cancellation token for the library load.</param>
/// <returns>A synchronous resolver, or <c>null</c> when no definition uses a <c>$ref</c>.</returns>
public static async Task<Func<string, string?>?> BuildAsync(
ISharedSchemaRepository? repository,
IEnumerable<string?> definitions,
SharedSchemaLibraryCache? cache,
CancellationToken ct = default)
{
// Skip the library round-trip entirely unless some definition uses a $ref.
@@ -55,8 +72,9 @@ public static class SchemaRefResolver
return null;
}
var library = await repository.ListAsync(ct);
var map = library.ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal);
IReadOnlyDictionary<string, string> map = cache is not null
? await cache.GetAsync(repository, ct)
: (await repository.ListAsync(ct)).ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal);
return name => map.GetValueOrDefault(name);
}
}
@@ -29,6 +29,11 @@ public static class ServiceCollectionExtensions
services.AddSingleton(sp => new ApiMethodCache(
sp.GetRequiredService<IOptions<InboundApiOptions>>().Value.ApiMethodCacheTtl));
// INB-2: the shared-schema library snapshot runtime $ref resolution reads, on the same
// TTL as the ApiMethod row it is resolved for.
services.AddSingleton(sp => new SharedSchemaLibraryCache(
sp.GetRequiredService<IOptions<InboundApiOptions>>().Value.ApiMethodCacheTtl));
// Routed calls go through the IInstanceRouter seam; the
// production implementation delegates to CommunicationService.
services.AddScoped<IInstanceRouter, CommunicationServiceInstanceRouter>();
@@ -0,0 +1,57 @@
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
namespace ZB.MOM.WW.ScadaBridge.InboundAPI;
/// <summary>
/// INB-2: a short-TTL, process-wide snapshot of the shared-schema library (name → schema
/// JSON) for runtime <c>$ref</c> resolution.
/// </summary>
/// <remarks>
/// A method whose parameter or return definition used a <c>$ref</c> read the whole library
/// from the database twice per request (once for parameter validation, once for return
/// validation, on different scopes). The library changes only on a designer edit, so one
/// snapshot is shared for <see cref="InboundApiOptions.ApiMethodCacheTtl"/> — the same bound
/// the resolved <c>ApiMethod</c> row is already cached for, so a schema edit becomes visible
/// to callers on the same cadence as a method edit. Concurrent misses may both load; the
/// last write wins, which is harmless for a read-only snapshot.
/// </remarks>
public sealed class SharedSchemaLibraryCache
{
private sealed record Snapshot(IReadOnlyDictionary<string, string> Library, DateTimeOffset ExpiresAtUtc);
private readonly TimeSpan _ttl;
private readonly TimeProvider _timeProvider;
private Snapshot? _snapshot;
/// <summary>Initializes the cache.</summary>
/// <param name="ttl">How long a loaded library snapshot is served.</param>
/// <param name="timeProvider">Clock; defaults to the system clock.</param>
public SharedSchemaLibraryCache(TimeSpan ttl, TimeProvider? timeProvider = null)
{
if (ttl <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(ttl), ttl, "SharedSchemaLibraryCache TTL must be positive.");
_ttl = ttl;
_timeProvider = timeProvider ?? TimeProvider.System;
}
/// <summary>Returns the cached library snapshot, loading it through <paramref name="repository"/> when stale.</summary>
/// <param name="repository">The shared-schema repository used on a miss.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The library as name → schema JSON.</returns>
public async Task<IReadOnlyDictionary<string, string>> GetAsync(ISharedSchemaRepository repository, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(repository);
var now = _timeProvider.GetUtcNow();
var current = Volatile.Read(ref _snapshot);
if (current is not null && current.ExpiresAtUtc > now)
return current.Library;
var library = (await repository.ListAsync(ct).ConfigureAwait(false))
.ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal);
Volatile.Write(ref _snapshot, new Snapshot(library, now + _ttl));
return library;
}
/// <summary>Drops the snapshot so the next lookup reloads the library.</summary>
public void Invalidate() => Volatile.Write(ref _snapshot, null);
}
@@ -4449,7 +4449,10 @@ public class ManagementActor : ReceiveActor
var inboundRepo = sp.GetRequiredService<IInboundApiRepository>();
var siteRepo = sp.GetRequiredService<ISiteRepository>();
var templates = await templateRepo.GetAllTemplatesAsync();
// MGT-5: names resolve against narrow (Id, Name) projections — the exporter loads the
// selected rows itself, so the full tracked template graph and every instance with its
// child collections were materialised here only to map names to ids.
var templates = await templateRepo.GetTemplateStubsAsync();
var sharedScripts = await templateRepo.GetAllSharedScriptsAsync();
var externalSystems = await externalRepo.GetAllExternalSystemsAsync();
var dbConnections = await externalRepo.GetAllDatabaseConnectionsAsync();
@@ -4462,7 +4465,7 @@ public class ManagementActor : ReceiveActor
// Site/instance-scoped selection. Sites match on SiteIdentifier
// (preferred) or Name; instances match on UniqueName.
var sites = await siteRepo.GetAllSitesAsync();
var instances = await templateRepo.GetAllInstancesAsync();
var instances = await templateRepo.GetInstanceNamesAsync();
int[] ResolveIds<T>(IReadOnlyList<T> all, IReadOnlyList<string>? names,
Func<T, string> getName, Func<T, int> getId, string entityType)
@@ -185,7 +185,7 @@ public static class FlowShapePredictor
_nodes.Add(new PredictedNode(id, kind, lane, title, inputDependent, mergedNote));
if (_previous != null)
{
var fromLane = _nodes.First(n => n.Id == _previous).Lane;
var fromLane = _nodes[IndexOf(_previous)].Lane;
_edges.Add(new PredictedEdge(_previous, id, (fromLane == FlowLane.Central) != (lane == FlowLane.Central), async));
}
@@ -194,12 +194,28 @@ public static class FlowShapePredictor
return id;
}
/// <summary>
/// CMN-11: O(1) node lookup. Ids are minted append-only as <c>"n" + (index + 1)</c>, so the
/// index is read from the id; the linear scan is only a fallback for a foreign id.
/// </summary>
/// <param name="id">The node id.</param>
/// <returns>The node's index, or -1 when absent.</returns>
private int IndexOf(string id)
{
if (id.Length > 1 && id[0] == 'n'
&& int.TryParse(id.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out var ordinal)
&& ordinal >= 1 && ordinal <= _nodes.Count
&& _nodes[ordinal - 1].Id == id)
return ordinal - 1;
return _nodes.FindIndex(n => n.Id == id);
}
/// <summary>Appends a note to an existing node.</summary>
/// <param name="id">The id of the node to annotate.</param>
/// <param name="note">The note to append.</param>
internal void Annotate(string id, string note)
{
var i = _nodes.FindIndex(n => n.Id == id);
var i = IndexOf(id);
if (i < 0) return;
var n = _nodes[i];
_nodes[i] = n with { Note = n.Note == null ? note : $"{n.Note}; {note}" };
@@ -90,9 +90,10 @@ public class EventLogPurgeService : BackgroundService
private const double TablePageFillFactor = 0.78;
/// <summary>
/// Number of secondary indexes on <c>site_events</c>: timestamp, instance_id,
/// Number of secondary indexes on <c>site_events</c>: timestamp, (instance_id, timestamp),
/// (event_type, timestamp) and (severity, timestamp). The sampled <c>indexed_bytes</c>
/// charges every covered column once per index, hence <c>3 * octet_length(timestamp)</c>.
/// charges every covered column once per index, hence <c>4 * octet_length(timestamp)</c>
/// (SEL-1 added timestamp to the instance index).
/// </summary>
private const int IndexedColumnCount = 4;
@@ -734,7 +735,7 @@ public class EventLogPurgeService : BackgroundService
+ octet_length(severity) + COALESCE(octet_length(instance_id), 0)
+ octet_length(source) + octet_length(message)
+ COALESCE(octet_length(details), 0) AS payload_bytes,
(3 * octet_length(timestamp)) + octet_length(event_type)
(4 * octet_length(timestamp)) + octet_length(event_type)
+ octet_length(severity) + COALESCE(octet_length(instance_id), 0)
AS indexed_bytes
FROM site_events LIMIT {SizeSampleRows}
@@ -746,7 +747,7 @@ public class EventLogPurgeService : BackgroundService
+ octet_length(severity) + COALESCE(octet_length(instance_id), 0)
+ octet_length(source) + octet_length(message)
+ COALESCE(octet_length(details), 0) AS payload_bytes,
(3 * octet_length(timestamp)) + octet_length(event_type)
(4 * octet_length(timestamp)) + octet_length(event_type)
+ octet_length(severity) + COALESCE(octet_length(instance_id), 0)
AS indexed_bytes
FROM site_events ORDER BY rowid DESC LIMIT {SizeSampleRows}
@@ -67,7 +67,8 @@ public static class SiteEventLogSchema
details TEXT
);
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON site_events(timestamp);
CREATE INDEX IF NOT EXISTS idx_events_instance ON site_events(instance_id);
DROP INDEX IF EXISTS idx_events_instance;
CREATE INDEX IF NOT EXISTS idx_events_instance_timestamp ON site_events(instance_id, timestamp);
DROP INDEX IF EXISTS idx_events_type;
DROP INDEX IF EXISTS idx_events_severity;
CREATE INDEX IF NOT EXISTS idx_events_type_timestamp ON site_events(event_type, timestamp);
@@ -85,6 +86,11 @@ public static class SiteEventLogSchema
// part of LocalDb's replicated-table digest, so a pair may upgrade one node at a
// time as far as this change is concerned.
//
// SEL-1 (2026-12-03): the instance_id index got the same treatment — the Instances
// page drill-in filters by instance and orders by (timestamp, id), which the old
// single-column idx_events_instance could only answer by fetching and sorting every
// row of that instance. Dropped and rebuilt in place on first boot, like #123.
//
// The query service also supports keyword search via leading-wildcard
// LIKE on message/source. A leading-wildcard LIKE cannot use a B-tree
// index, so that path intentionally full-scans; severity/event_type/
@@ -505,10 +505,13 @@ public class InstanceActor : ReceiveActor
var self = Self;
var instanceName = _instanceUniqueName;
var storage = _storage;
// SRT-5: SQLite's async APIs run synchronously (open included), so the ungated read is
// started on the thread pool rather than inline on this actor's dispatcher thread.
var load = _staticStateResetGate == null
? storage.GetStaticOverridesAsync(instanceName)
? Task.Run(() => storage.GetStaticOverridesAsync(instanceName))
: _staticStateResetGate
.ContinueWith(_ => storage.GetStaticOverridesAsync(instanceName))
.ContinueWith(_ => storage.GetStaticOverridesAsync(instanceName),
TaskScheduler.Default)
.Unwrap();
load.ContinueWith(t =>
{
@@ -2158,7 +2161,20 @@ public class InstanceActor : ReceiveActor
var key = kvp.Key;
var logger = _logger;
var instanceName = _instanceUniqueName;
_storage.SetStaticOverrideAsync(instanceName, key, native!)
var storage = _storage;
var nativeValue = native!;
// SRT-5: off the dispatcher and on the ordered persist chain, so the
// normalising write can never land after (and undo) a newer flush.
var previous = _staticOverridePersistTail;
var normalize = Task.Run(async () =>
{
try { await previous.ConfigureAwait(false); }
catch { /* logged by its own continuation */ }
await storage.SetStaticOverrideAsync(instanceName, key, nativeValue)
.ConfigureAwait(false);
});
_staticOverridePersistTail = normalize;
normalize
.ContinueWith(t => logger.LogWarning(t.Exception?.GetBaseException(),
"Failed to normalize static override {Instance}.{Attr} to native JSON",
instanceName, key),
@@ -2231,6 +2247,19 @@ public class InstanceActor : ReceiveActor
}
list.Add(child);
break;
case TriggerRoutingKind.MonitoredAttributes:
// SRT-7: an Expression trigger whose reads are all literal keys hears only
// changes of those attributes (its snapshot is only ever read at those keys).
foreach (var attribute in decision.MonitoredAttributeSet!)
{
if (!_childrenByMonitoredAttribute.TryGetValue(attribute, out var set))
{
set = new List<IActorRef>();
_childrenByMonitoredAttribute[attribute] = set;
}
set.Add(child);
}
break;
case TriggerRoutingKind.AllChanges:
_allChangeChildren.Add(child);
break;
@@ -131,8 +131,17 @@ public class NativeAlarmActor : ReceiveActor
// Rehydrate last-known state from SQLite (non-blocking), then subscribe.
// A fresh source snapshot will reconcile/replace this once it arrives.
(_rehydrationRead ?? _storage.GetNativeAlarmsAsync(_instanceName, _source.CanonicalName))
.PipeTo(Self, Self, rows => new RehydrationCompleted(rows));
// SRT-5: Microsoft.Data.Sqlite's *Async methods run synchronously (connection open
// included), so the read is started on the thread pool — never on this actor's
// dispatcher thread — and the result is piped back. Persist flushes chain behind it
// (the tail starts as the read), so a flush can never commit before the read runs.
var storage = _storage;
var instanceName = _instanceName;
var canonicalName = _source.CanonicalName;
var read = _rehydrationRead
?? Task.Run(() => storage.GetNativeAlarmsAsync(instanceName, canonicalName));
_persistTail = read;
read.PipeTo(Self, Self, rows => new RehydrationCompleted(rows));
SendSubscribe();
@@ -158,6 +167,13 @@ public class NativeAlarmActor : ReceiveActor
private readonly Task<IReadOnlyList<NativeAlarmRow>>? _rehydrationRead;
/// <summary>
/// SRT-5: the ordered persist chain (InstanceActor's static-override pattern). Each flush
/// runs on the thread pool after the previous one, so batches commit in order without the
/// SQLite open/transaction/commit ever running on the actor's dispatcher thread.
/// </summary>
private Task _persistTail = Task.CompletedTask;
private string? _subscribeCorrelation;
private DateTimeOffset _subscribeDeadline;
private int _subscribeDelayMs;
@@ -427,10 +443,7 @@ public class NativeAlarmActor : ReceiveActor
return;
}
var overflow = _alarms.Values
.OrderBy(a => a.TransitionTime)
.Take(_alarms.Count - cap)
.ToList();
var overflow = SelectOldest(_alarms.Values, _alarms.Count - cap);
foreach (var evicted in overflow)
{
@@ -455,12 +468,68 @@ public class NativeAlarmActor : ReceiveActor
// This condition is gone for good — evict the parent's
// _latestAlarmEvents key so it does not retain a stale entry.
NotifyParentDropped(sourceRef);
_logger.LogWarning(
"Native alarm cap {Cap} exceeded for {Source} on {Instance}; dropped oldest mirrored alarm {Ref}",
cap, _source.CanonicalName, _instanceName, sourceRef);
LogCapEviction(cap, sourceRef);
}
}
/// <summary>
/// SRT-14: the <paramref name="count"/> oldest mirrored conditions (by transition time),
/// oldest first, chosen with a bounded max-heap — O(n log k) with k almost always 1 — instead
/// of sorting the whole mirror on every transition at the cap.
/// </summary>
/// <param name="alarms">The mirrored conditions.</param>
/// <param name="count">How many to select.</param>
/// <returns>The selected conditions, oldest first.</returns>
internal static List<NativeAlarmTransition> SelectOldest(
IEnumerable<NativeAlarmTransition> alarms, int count)
{
var result = new List<NativeAlarmTransition>(Math.Max(0, count));
if (count <= 0) return result;
// Max-heap on transition time holding the k oldest seen so far.
var heap = new PriorityQueue<NativeAlarmTransition, DateTimeOffset>(
count + 1, Comparer<DateTimeOffset>.Create((a, b) => b.CompareTo(a)));
foreach (var alarm in alarms)
{
if (heap.Count < count)
{
heap.Enqueue(alarm, alarm.TransitionTime);
}
else if (heap.TryPeek(out _, out var newestKept) && alarm.TransitionTime < newestKept)
{
heap.EnqueueDequeue(alarm, alarm.TransitionTime);
}
}
while (heap.TryDequeue(out var alarm, out _))
result.Add(alarm);
result.Reverse(); // the max-heap drains newest first
return result;
}
private DateTimeOffset _lastCapWarningAt = DateTimeOffset.MinValue;
private int _capEvictionsSinceWarning;
/// <summary>
/// SRT-14: the cap eviction Warning is rate-limited (once a minute, carrying the count of
/// evictions since the last one) so a sustained flood at the cap does not log a Warning per
/// transition. Evictions are never silent — the first one after a quiet minute logs at once.
/// </summary>
private void LogCapEviction(int cap, string sourceRef)
{
_capEvictionsSinceWarning++;
var now = DateTimeOffset.UtcNow;
if (now - _lastCapWarningAt < CapWarningInterval) return;
_logger.LogWarning(
"Native alarm cap {Cap} exceeded for {Source} on {Instance}; dropped oldest mirrored alarm {Ref} ({Evicted} eviction(s) since the last warning)",
cap, _source.CanonicalName, _instanceName, sourceRef, _capEvictionsSinceWarning);
_lastCapWarningAt = now;
_capEvictionsSinceWarning = 0;
}
private static readonly TimeSpan CapWarningInterval = TimeSpan.FromMinutes(1);
/// <summary>
/// Signals the parent Instance Actor that a native condition has
/// left the mirror for good so it can evict the matching <c>_latestAlarmEvents</c>
@@ -641,11 +710,27 @@ public class NativeAlarmActor : ReceiveActor
var deletes = _dirtyUpserts.Where(kv => kv.Value is null).Select(kv => kv.Key).ToList();
_dirtyUpserts.Clear();
_storage.ApplyNativeAlarmChangesAsync(_instanceName, _source.CanonicalName, batch, deletes)
.ContinueWith(
task => _logger.LogWarning(task.Exception,
// SRT-5: run the batched transaction on the thread pool, chained behind the previous
// flush (and the rehydration read) so batches stay ordered. SQLite's async APIs block
// synchronously; a write waiting on the shared LocalDb write lock must not park a
// default-dispatcher thread.
var storage = _storage;
var instanceName = _instanceName;
var canonicalName = _source.CanonicalName;
var logger = _logger;
var previous = _persistTail;
var persist = Task.Run(async () =>
{
try { await previous.ConfigureAwait(false); }
catch { /* The prior batch/read was logged; a transient failure must not poison future writes. */ }
await storage.ApplyNativeAlarmChangesAsync(instanceName, canonicalName, batch, deletes)
.ConfigureAwait(false);
});
_persistTail = persist;
persist.ContinueWith(
task => logger.LogWarning(task.Exception,
"Failed to persist {Count} native alarm changes on {Instance}",
batch.Count + deletes.Count, _instanceName),
batch.Count + deletes.Count, instanceName),
TaskContinuationOptions.OnlyOnFaulted);
}
@@ -0,0 +1,140 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
/// <summary>
/// SRT-7: extracts the canonical attribute keys a trigger expression reads, so an
/// Expression-triggered script/alarm can be routed only the changes it depends on instead
/// of every attribute change on the instance.
/// </summary>
/// <remarks>
/// <para>
/// The walk is deliberately conservative. It recognises exactly the two literal read forms
/// <see cref="TriggerExpressionGlobals"/> exposes — <c>Attributes["k"]</c> (key <c>k</c>) and
/// <c>Children["c"].Attributes["k"]</c> (key <c>c.k</c>) — and gives up (returns
/// <see langword="false"/>, which routes the child to every change exactly as before) on
/// anything it cannot pin down: a non-literal index, any other use of the
/// <c>Attributes</c>/<c>Children</c>/<c>Parent</c> globals (an alias, a member access, a
/// method-group pass), a parse error, or an expression that reads no attribute at all (it may
/// depend on something other than attribute values, e.g. the clock, and has always been
/// re-evaluated on every change).
/// </para>
/// <para>
/// Routing remains an optimisation: the child's own snapshot/evaluation is unchanged. A child
/// routed by keys simply stops receiving changes for attributes its expression never reads.
/// </para>
/// </remarks>
internal static class TriggerExpressionKeys
{
private static readonly CSharpParseOptions ScriptParse =
CSharpParseOptions.Default.WithKind(SourceCodeKind.Script);
/// <summary>
/// Tries to extract the literal attribute keys an expression reads.
/// </summary>
/// <param name="expression">The trigger expression source.</param>
/// <param name="keys">The distinct canonical keys read, when the method returns <see langword="true"/>.</param>
/// <returns><see langword="true"/> when every attribute read is a recognised literal form and at least one exists.</returns>
public static bool TryExtract(string? expression, out IReadOnlyList<string> keys)
{
keys = Array.Empty<string>();
if (string.IsNullOrWhiteSpace(expression)) return false;
SyntaxTree tree;
try
{
tree = CSharpSyntaxTree.ParseText(expression, ScriptParse);
}
catch
{
return false;
}
var root = tree.GetRoot();
if (root.ContainsDiagnostics) return false;
var found = new List<string>();
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var id in root.DescendantNodes().OfType<IdentifierNameSyntax>())
{
switch (id.Identifier.ValueText)
{
case "Parent":
return false;
case "Attributes":
{
// Children["c"].Attributes["k"]: the identifier is the Name of a member access
// whose receiver is a literal Children index.
if (id.Parent is MemberAccessExpressionSyntax member && member.Name == id)
{
if (!TryChildPrefix(member.Expression, out var childPrefix)) return false;
if (!TryLiteralIndex(member, out var key)) return false;
Add(childPrefix + "." + key);
break;
}
// Attributes["k"]
if (!TryLiteralIndex(id, out var rootKey)) return false;
Add(rootKey);
break;
}
case "Children":
// Valid only as the receiver of Children["c"].Attributes[...]; that whole
// form is validated from the Attributes identifier above.
if (!IsChildrenReceiver(id)) return false;
break;
}
}
if (found.Count == 0) return false;
keys = found;
return true;
void Add(string key)
{
if (seen.Add(key)) found.Add(key);
}
}
/// <summary>True when <paramref name="node"/> is directly indexed by one string literal.</summary>
private static bool TryLiteralIndex(ExpressionSyntax node, out string key)
{
key = "";
if (node.Parent is not ElementAccessExpressionSyntax access || access.Expression != node)
return false;
return TrySingleStringLiteral(access.ArgumentList, out key);
}
/// <summary>Matches <c>Children["c"]</c> and returns <c>c</c>.</summary>
private static bool TryChildPrefix(ExpressionSyntax receiver, out string prefix)
{
prefix = "";
return receiver is ElementAccessExpressionSyntax access
&& access.Expression is IdentifierNameSyntax { Identifier.ValueText: "Children" }
&& TrySingleStringLiteral(access.ArgumentList, out prefix);
}
private static bool IsChildrenReceiver(IdentifierNameSyntax id) =>
id.Parent is ElementAccessExpressionSyntax access
&& access.Expression == id
&& access.Parent is MemberAccessExpressionSyntax member
&& member.Expression == access
&& member.Name.Identifier.ValueText == "Attributes"
&& TrySingleStringLiteral(access.ArgumentList, out _);
private static bool TrySingleStringLiteral(BracketedArgumentListSyntax args, out string value)
{
value = "";
if (args.Arguments.Count != 1) return false;
if (args.Arguments[0].Expression is not LiteralExpressionSyntax literal
|| !literal.IsKind(SyntaxKind.StringLiteralExpression))
return false;
value = literal.Token.ValueText;
return value.Length > 0;
}
}
@@ -14,13 +14,18 @@ internal enum TriggerRoutingKind
AllChanges,
/// <summary>Never reacts to attribute changes (interval / call-only scripts).</summary>
None
None,
/// <summary>SRT-7: reacts to changes of any of a set of named attributes — an Expression
/// trigger whose attribute reads are all literal keys (see <see cref="TriggerExpressionKeys"/>).</summary>
MonitoredAttributes
}
/// <summary>
/// Result of classifying a child's trigger for attribute-change routing.
/// </summary>
internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind, string? MonitoredAttribute)
internal readonly record struct TriggerRoutingDecision(
TriggerRoutingKind Kind, string? MonitoredAttribute, IReadOnlyList<string>? MonitoredAttributeSet = null)
{
public static readonly TriggerRoutingDecision AllChanges = new(TriggerRoutingKind.AllChanges, null);
public static readonly TriggerRoutingDecision None = new(TriggerRoutingKind.None, null);
@@ -29,6 +34,23 @@ internal readonly record struct TriggerRoutingDecision(TriggerRoutingKind Kind,
/// <param name="attribute">The name of the attribute to monitor.</param>
/// <returns>A <see cref="TriggerRoutingDecision"/> of kind <see cref="TriggerRoutingKind.MonitoredAttribute"/>.</returns>
public static TriggerRoutingDecision Monitored(string attribute) => new(TriggerRoutingKind.MonitoredAttribute, attribute);
/// <summary>Creates a decision routing on changes to any of several named attributes (SRT-7).</summary>
/// <param name="attributes">The attribute names to monitor.</param>
/// <returns>A <see cref="TriggerRoutingDecision"/> of kind <see cref="TriggerRoutingKind.MonitoredAttributes"/>.</returns>
public static TriggerRoutingDecision MonitoredSet(IReadOnlyList<string> attributes) =>
new(TriggerRoutingKind.MonitoredAttributes, null, attributes);
/// <summary>
/// SRT-7: routes an Expression trigger by the literal attribute keys it reads, falling back
/// to all-changes whenever the keys cannot be pinned down.
/// </summary>
/// <param name="triggerConfigJson">The Expression trigger config JSON.</param>
/// <returns>The routing decision.</returns>
public static TriggerRoutingDecision ForExpression(string? triggerConfigJson) =>
TriggerExpressionKeys.TryExtract(TriggerExpressionGlobals.ExtractExpression(triggerConfigJson), out var keys)
? MonitoredSet(keys)
: AllChanges;
}
/// <summary>
@@ -79,7 +101,8 @@ internal static class TriggerRouting
/// <summary>
/// Classifies a script trigger. valuechange/conditional → the named attribute (fail open to
/// all-changes if unparseable); expression → all-changes; interval/call → none; anything
/// all-changes if unparseable); expression → its literal attribute keys (SRT-7; all-changes
/// when they cannot be extracted); interval/call → none; anything
/// unknown → all-changes (fail open — a misconfigured script still reacts, its own gate
/// remains the correctness check).
/// </summary>
@@ -96,7 +119,7 @@ internal static class TriggerRouting
? TriggerRoutingDecision.Monitored(attr)
: TriggerRoutingDecision.AllChanges;
case "expression":
return TriggerRoutingDecision.AllChanges;
return TriggerRoutingDecision.ForExpression(triggerConfigJson);
case "interval":
case "call":
return TriggerRoutingDecision.None;
@@ -106,7 +129,8 @@ internal static class TriggerRouting
}
/// <summary>
/// Classifies an alarm trigger. Expression → all-changes; HiLo/ValueMatch/RangeViolation/
/// Classifies an alarm trigger. Expression → its literal attribute keys (SRT-7; all-changes
/// when they cannot be extracted); HiLo/ValueMatch/RangeViolation/
/// RateOfChange → the named attribute (fail open to all-changes if unparseable); an
/// unknown/unparseable trigger type → all-changes (fail open).
/// </summary>
@@ -120,7 +144,7 @@ internal static class TriggerRouting
switch (tt)
{
case AlarmTriggerType.Expression:
return TriggerRoutingDecision.AllChanges;
return TriggerRoutingDecision.ForExpression(triggerConfigJson);
case AlarmTriggerType.HiLo:
case AlarmTriggerType.ValueMatch:
case AlarmTriggerType.RangeViolation:
@@ -51,7 +51,7 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tracking;
/// path.
/// </para>
/// </remarks>
public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, IDisposable
public class OperationTrackingStore : IOperationTrackingStore, IOperationTrackingBatchReader, IAsyncDisposable, IDisposable
{
/// <summary>Queue bound; past it <c>Record*Async</c> waits (never drops).</summary>
internal const int MaxQueuedWrites = 8192;
@@ -595,7 +595,61 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable,
return null;
}
return new TrackingStatusSnapshot(
return ReadSnapshot(reader);
}
/// <summary>Most ids bound into one <c>IN (…)</c> read (well under SQLite's parameter limit).</summary>
private const int MaxIdsPerStatusRead = 500;
/// <inheritdoc/>
/// <remarks>
/// AUD-7: one writer-queue barrier for the whole set, then chunked <c>IN (…)</c> reads on one
/// connection — instead of a barrier + connection + query per id.
/// </remarks>
public async Task<IReadOnlyDictionary<TrackedOperationId, TrackingStatusSnapshot>> GetStatusManyAsync(
IReadOnlyCollection<TrackedOperationId> ids,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(ids);
var result = new Dictionary<TrackedOperationId, TrackingStatusSnapshot>();
if (ids.Count == 0)
{
return result;
}
await WaitForQueuedWritesAsync(ct).ConfigureAwait(false);
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposeState) != 0, this);
await using var readConnection = _localDb.CreateConnection();
foreach (var chunk in ids.Select(i => i.ToString()).Distinct(StringComparer.Ordinal).Chunk(MaxIdsPerStatusRead))
{
await using var cmd = readConnection.CreateCommand();
var names = new string[chunk.Length];
for (var i = 0; i < chunk.Length; i++)
{
names[i] = "$id" + i.ToString(CultureInfo.InvariantCulture);
cmd.Parameters.AddWithValue(names[i], chunk[i]);
}
cmd.CommandText =
"SELECT TrackedOperationId, Kind, TargetSummary, Status, " +
"RetryCount, LastError, HttpStatus, CreatedAtUtc, UpdatedAtUtc, TerminalAtUtc, " +
"SourceInstanceId, SourceScript, SourceNode " +
"FROM OperationTracking WHERE TrackedOperationId IN (" + string.Join(", ", names) + ");";
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await reader.ReadAsync(ct).ConfigureAwait(false))
{
var snapshot = ReadSnapshot(reader);
result[snapshot.Id] = snapshot;
}
}
return result;
}
private static TrackingStatusSnapshot ReadSnapshot(SqliteDataReader reader) =>
new TrackingStatusSnapshot(
Id: TrackedOperationId.Parse(reader.GetString(0)),
Kind: reader.GetString(1),
TargetSummary: reader.IsDBNull(2) ? null : reader.GetString(2),
@@ -609,7 +663,6 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable,
SourceInstanceId: reader.IsDBNull(10) ? null : reader.GetString(10),
SourceScript: reader.IsDBNull(11) ? null : reader.GetString(11),
SourceNode: reader.IsDBNull(12) ? null : reader.GetString(12));
}
/// <inheritdoc/>
public async Task PurgeTerminalAsync(
@@ -111,6 +111,19 @@ public static class StoreAndForwardSchema
"CREATE INDEX IF NOT EXISTS idx_sf_messages_status_created ON sf_messages(status, created_at)";
orderIndex.ExecuteNonQuery();
}
// SF-3: covering index for the sweep's fair lane ranking. Leading (status, category,
// target, created_at) matches ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY
// created_at) so the window reads rows already in lane order with no sort, and the
// trailing due-predicate columns + id make it covering, so the ranking never reads a
// payload. Applied in place on every boot (idempotent); local only — indexes are not
// part of LocalDb's CDC capture.
using (var laneIndex = connection.CreateCommand())
{
laneIndex.CommandText =
"CREATE INDEX IF NOT EXISTS idx_sf_messages_lane ON sf_messages(status, category, target, created_at, last_attempt_at_ms, retry_interval_ms, id)";
laneIndex.ExecuteNonQuery();
}
}
/// <summary>
@@ -199,9 +199,6 @@ public class StoreAndForwardStorage
await using var connection = OpenConnection();
await using var cmd = connection.CreateCommand();
const string cols = @"id, category, target, payload_json, retry_count, max_retries,
retry_interval_ms, created_at, last_attempt_at, status, last_error, origin_instance,
execution_id, source_script, parent_execution_id";
const string dueExpr = @"(last_attempt_at_ms IS NULL
OR retry_interval_ms = 0
OR (@nowMs - last_attempt_at_ms) >= retry_interval_ms)";
@@ -211,30 +208,35 @@ public class StoreAndForwardStorage
// (created_at, rowid as the same-instant tie-break), and `blocked_by` counts the
// not-yet-due rows at or before each row. Only the lane prefix with
// blocked_by = 0 is eligible, so a younger row can never be handed out while an
// older row of the same lane is still pending but backing off — previously the
// head's failure pushed ITS last_attempt_at forward while the rows behind it
// kept their older stamps, so a later sweep delivered B before A. It also means
// a dead target is probed once per head retry interval rather than by whichever
// staggered row happened to come due on each sweep.
// older row of the same lane is still pending but backing off.
//
// The page is then taken FAIRLY across lanes by lane rank (review 2026-10-21
// 02/C2): one dead target holding hundreds of rows contributes one row per
// "round" like every other lane instead of owning the whole page. Within a lane
// rank order == enqueue order, preserved by the service's stable GroupBy.
// "round" like every other lane. Within a lane rank order == enqueue order.
//
// SF-3: the ranking runs over a NARROW projection (id + lane keys + due columns)
// that idx_sf_messages_lane covers, so the window never touches a payload; only
// the chosen page of ids is joined back for the full rows.
cmd.CommandText = $@"
SELECT {cols}
FROM (
SELECT {cols},
ROW_NUMBER() OVER lane AS lane_rank,
SUM(CASE WHEN {dueExpr} THEN 0 ELSE 1 END) OVER lane AS blocked_by
FROM sf_messages
WHERE status = @pending
WINDOW lane AS (PARTITION BY category, target ORDER BY created_at ASC, rowid ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
WITH page AS (
SELECT id, lane_rank, created_at, rid
FROM (
SELECT id, created_at, rowid AS rid,
ROW_NUMBER() OVER lane AS lane_rank,
SUM(CASE WHEN {dueExpr} THEN 0 ELSE 1 END) OVER lane AS blocked_by
FROM sf_messages
WHERE status = @pending
WINDOW lane AS (PARTITION BY category, target ORDER BY created_at ASC, rowid ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
)
WHERE blocked_by = 0
ORDER BY lane_rank ASC, created_at ASC, rid ASC"
+ (limit > 0 ? "\n LIMIT @limit" : string.Empty) + $@"
)
WHERE blocked_by = 0
ORDER BY lane_rank ASC, created_at ASC"
+ (limit > 0 ? "\n LIMIT @limit" : string.Empty);
SELECT {SweepColumnsM}
FROM page p
JOIN sf_messages m ON m.id = p.id
ORDER BY p.lane_rank ASC, p.created_at ASC, p.rid ASC";
if (limit > 0)
cmd.Parameters.AddWithValue("@limit", limit);
@@ -244,6 +246,15 @@ public class StoreAndForwardStorage
return await ReadMessagesAsync(cmd);
}
/// <summary>The sweep's column list qualified with the <c>m</c> alias (SF-3 join-back).</summary>
private static readonly string SweepColumnsM =
string.Join(", ", new[]
{
"id", "category", "target", "payload_json", "retry_count", "max_retries",
"retry_interval_ms", "created_at", "last_attempt_at", "status", "last_error", "origin_instance",
"execution_id", "source_script", "parent_execution_id",
}.Select(c => "m." + c));
/// <summary>
/// Updates a message after a delivery attempt.
/// </summary>
@@ -188,7 +188,8 @@ public class AreaService
return Result<bool>.Failure($"Area with ID {areaId} not found.");
// Check for instances assigned to this area
var allInstances = await _repository.GetInstancesBySiteIdAsync(area.SiteId, cancellationToken);
// TPL-4: shallow + untracked — only AreaId/UniqueName are read.
var allInstances = await _repository.GetInstancesBySiteIdShallowAsync(area.SiteId, cancellationToken);
var allAreas = await _repository.GetAreasBySiteIdAsync(area.SiteId, cancellationToken);
// Collect this area and all descendant area IDs
@@ -183,6 +183,15 @@ public class InstanceService
var overrides = await _repository.GetOverridesByInstanceIdAsync(instanceId, cancellationToken);
var existingOverride = overrides.FirstOrDefault(o => o.AttributeName == attributeName);
// UI-6: an unchanged value is not rewritten — no save and no UpdateOverride audit row
// burying the one real edit of a bulk save.
if (existingOverride != null
&& string.Equals(existingOverride.OverrideValue, overrideValue, StringComparison.Ordinal)
&& existingOverride.ElementDataType == templateAttr.ElementDataType)
{
return Result<InstanceAttributeOverride>.Success(existingOverride);
}
if (existingOverride != null)
{
existingOverride.OverrideValue = overrideValue;
@@ -250,7 +259,9 @@ public class InstanceService
// rule for a composed alarm. Mirrors SetAttributeOverrideAsync.
// The resolver reads member names and lock flags only, so the no-tracking,
// script-body-free analysis projection suffices (review 2026-10-21 04/P6, 08/P1).
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
// TPL-4: the template's analysis closure (chain + compositions) is all the resolver
// walks — not the whole template table.
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(instance.TemplateId, cancellationToken);
var resolvedAlarm = TemplateResolver
.ResolveAllMembers(instance.TemplateId, allTemplates)
.FirstOrDefault(m => m.MemberType == "Alarm" && m.CanonicalName == alarmCanonicalName);
@@ -228,12 +228,9 @@ public class TemplateService
// only invariant the move can break is two templates sharing a
// (FolderId, Name) at the destination, which the design's
// naming-collisions-are-design-time-errors rule forbids.
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
var collision = allTemplates.FirstOrDefault(t =>
t.Id != templateId &&
t.FolderId == newFolderId &&
string.Equals(t.Name, template.Name, StringComparison.OrdinalIgnoreCase));
if (collision != null)
// TPL-4: a (FolderId, Name) existence query, not a load of every template.
if (await _repository.TemplateNameExistsInFolderAsync(
newFolderId, template.Name, templateId, cancellationToken))
{
var location = newFolderId.HasValue ? "the target folder" : "the root";
return Result<Template>.Failure(
@@ -449,7 +446,9 @@ public class TemplateService
var template = await _repository.GetTemplateByIdAsync(attribute.TemplateId, cancellationToken);
if (template?.ParentTemplateId != null)
{
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
// TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
template.ParentTemplateId.Value, cancellationToken);
var parentMember = TemplateResolver.FindMemberByCanonicalName(
attribute.Name, template.ParentTemplateId.Value, allTemplates);
if (parentMember != null)
@@ -676,7 +675,9 @@ public class TemplateService
var template = await _repository.GetTemplateByIdAsync(alarm.TemplateId, cancellationToken);
if (template?.ParentTemplateId != null)
{
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
// TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
template.ParentTemplateId.Value, cancellationToken);
var parentMember = TemplateResolver.FindMemberByCanonicalName(
alarm.Name, template.ParentTemplateId.Value, allTemplates);
if (parentMember != null)
@@ -853,7 +854,9 @@ public class TemplateService
var template = await _repository.GetTemplateByIdAsync(script.TemplateId, cancellationToken);
if (template?.ParentTemplateId != null)
{
var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
// TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
template.ParentTemplateId.Value, cancellationToken);
var parentMember = TemplateResolver.FindMemberByCanonicalName(
script.Name, template.ParentTemplateId.Value, allTemplates);
if (parentMember != null)
@@ -207,8 +207,28 @@ public sealed partial class BundleImporter
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
var service = new TemplateService(_templateRepo, _auditService);
// TRN-11: every owner/base root name was looked up with its own
// `t.Name.ToLower() == lower` query (unindexable) — twice per derived template. The
// (Id, Name, IsDerived) projection of the whole table is loaded ONCE into a
// case-insensitive index instead (narrow: no members, no script bodies). This loop
// only ever creates or deletes DERIVED templates, so a hit on a base row is always
// current; a name with no base row in the index falls back to the live query, so the
// derived-only / not-found diagnostics still see what earlier rows wrote.
Dictionary<string, List<TemplateRow>>? templateRowsByName = null;
async Task<IReadOnlyList<TemplateRow>> Named(string name)
{
if (templateRowsByName is null)
{
var all = await _dbContext.Templates.AsNoTracking()
.Select(t => new TemplateRow(t.Id, t.Name, t.IsDerived))
.ToListAsync(ct).ConfigureAwait(false);
templateRowsByName = all
.GroupBy(r => r.Name, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase);
}
if (templateRowsByName.TryGetValue(name, out var cached) && cached.Any(r => !r.IsDerived))
return cached;
var lower = name.ToLower();
return await _dbContext.Templates.AsNoTracking()
.Where(t => t.Name.ToLower() == lower)
@@ -5653,6 +5653,8 @@ public sealed partial class BundleImporter : IBundleImporter
}
}
// TRN-11: one connection read per target site, not one per referencing row.
var targetConnNamesBySiteId = new Dictionary<int, HashSet<string>>();
foreach (var (site, name) in referencedConnections)
{
if (bundleConnectionRefs.Contains((site, name))) continue; // carried → creatable
@@ -5663,8 +5665,13 @@ public sealed partial class BundleImporter : IBundleImporter
&& mapping.TargetConnectionName is { Length: > 0 } tn
? tn
: name;
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
if (FindByName(conns, c => c.Name, targetName) is null)
if (!targetConnNamesBySiteId.TryGetValue(targetSite.Id, out var connNames))
{
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
connNames = new HashSet<string>(conns.Select(c => c.Name), StringComparer.OrdinalIgnoreCase);
targetConnNamesBySiteId[targetSite.Id] = connNames;
}
if (!connNames.Contains(targetName))
{
errors.Add(
$"Connection '{site}/{name}' is referenced by the bundle but is neither carried in "