docs(code): honest rationales — Akka restart semantics, per-key shards, EF literal inlining; retire or annotate orphaned members

This commit is contained in:
Joseph Doherty
2026-08-16 05:33:33 -04:00
parent dbc9223206
commit b9e9df4081
11 changed files with 133 additions and 58 deletions
@@ -1491,8 +1491,15 @@ public sealed class RawTreeService(IDbContextFactory<OtOpcUaConfigDbContext> dbF
var sourceCode = Expression.Property(parameter, nameof(Script.SourceCode));
var contains = typeof(string).GetMethod(nameof(string.Contains), [typeof(string)])!;
// Indexing a captured array (rather than Expression.Constant(path)) keeps EF parameterising each
// path instead of inlining it as a SQL literal, so the paths never reach the generated SQL text.
// Indexing an array (rather than Expression.Constant(path) directly) keeps the expression tree
// cache-friendly: every rename of the same path-count produces the same tree shape.
// ⚠️ It does NOT guarantee parameterisation. The array here is a constant with no closure over it,
// so EF may well inline each path into the SQL as an escaped literal — which is safe (EF escapes
// the Contains argument either way, so there is no injection surface) but means a rename can emit up
// to ScriptScanBatchSize (200) literals per batch and churn the plan cache. Whether the provider
// actually parameterises this shape is unverified: proving it needs a SQL-Server-backed test, not
// EF InMemory. Recorded in the follow-up register of
// docs/plans/2026-08-15-perf-roadmap-remainder.md.
var values = paths.ToArray();
Expression? body = null;
for (var i = 0; i < values.Length; i++)
@@ -316,6 +316,14 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
/// <summary>
/// Re-authorizes live subscriptions when a deployment installs a new authorization generation.
/// </summary>
/// <remarks>
/// ⚠️ <b>This is the only trigger, and the pass's memo depends on that.</b>
/// <see cref="IsSubscriptionStillPermitted"/> memoizes key revocation and expiry for the span of one
/// pass — safe only while revalidation is deploy-triggered, because a pass is then a momentary
/// event whose verdicts cannot go stale within it. A future periodic trigger must give each tick a
/// fresh memo (it already does — the dictionary is pass-local) and must not be tempted to reuse one
/// across ticks, or an expiry landing between ticks would be served the previous tick's allow.
/// </remarks>
/// <param name="snapshot">The newly published snapshot; unused — the current state is re-read per item.</param>
private void OnAuthorityChanged(DataPlaneAuthoritySnapshot snapshot) => RevalidateMonitoredItems();
@@ -32,13 +32,16 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
/// deploy costs one repopulation and cannot be wrong. Deployments are rare relative to reads.
/// </para>
/// <para>
/// <b>Storage is sharded per session, under a two-level bound.</b> Each session key owns its own
/// dictionary, capped at <see cref="MaxEntriesPerSession"/>; overflowing it clears <i>that shard
/// only</i>. A second, global <see cref="MaxEntries"/> bound clears every shard, and exists purely
/// so many sessions each staying under their own cap cannot add up to unbounded growth. The flat
/// cache this replaced had only the global bound, which made one machine consumer crawling a large
/// tree an eviction event for every other session on the server — the sessions doing ordinary work
/// paid for the crawl. Both caps are enforced against <see cref="Interlocked"/> counters, never
/// <b>Storage is sharded per calling KEY, under a two-level bound.</b> The shard key is
/// <c>ApiKeyId ?? Principal</c>, so <i>sessions sharing one API key share one shard and one
/// <see cref="MaxEntriesPerSession"/> cap</i> — the isolation is across distinct keys, not across
/// sessions. Overflowing a shard clears <i>that shard only</i>, so a crawl by one key cannot evict
/// another key's entries. A second, global <see cref="MaxEntries"/> bound clears every shard, and
/// exists purely so many keys each staying under their own cap cannot add up to unbounded growth.
/// The flat cache this replaced had only the global bound, which made one machine consumer
/// crawling a large tree an eviction event for every other caller on the server — the callers
/// doing ordinary work paid for the crawl. Both caps are enforced against
/// <see cref="Interlocked"/> counters, never
/// <see cref="ConcurrentDictionary{TKey,TValue}.Count"/>, which locks the whole table.
/// </para>
/// </remarks>
@@ -46,7 +49,7 @@ public sealed class SessionAclDecisionCache
{
/// <summary>
/// Process-wide entry ceiling, past which <b>every</b> shard clears. The outer of the two bounds,
/// and a rare fallback: it exists so a large fleet of sessions each staying well under
/// and a rare fallback: it exists so a large fleet of distinct keys each staying well under
/// <see cref="MaxEntriesPerSession"/> still cannot grow the cache without limit.
/// </summary>
/// <remarks>
@@ -59,16 +62,18 @@ public sealed class SessionAclDecisionCache
public const int MaxEntries = 100_000;
/// <summary>
/// Per-session entry ceiling, past which that session's shard alone clears. The inner and normally
/// the only bound reached: it is what keeps one machine consumer crawling a 50k-node tree from
/// evicting the decisions of every other session on the server.
/// Per-<b>key</b> entry ceiling (the shard key is <c>ApiKeyId ?? Principal</c>, so every session
/// using the same API key shares this one budget), past which that shard alone clears. The inner
/// and normally the only bound reached: it is what keeps one machine consumer crawling a 50k-node
/// tree from evicting the decisions taken for every OTHER key on the server. The name predates the
/// shard key and is kept for source compatibility.
/// </summary>
/// <remarks>
/// Clearing beats evicting <i>within a shard</i>: an LRU needs per-entry bookkeeping on the hot path
/// to save a trie walk that is itself cheap, so the eviction policy would cost more than the miss it
/// prevents. The failure mode of clearing is a burst of recomputation, which is exactly the steady
/// state of not having a cache at all — and sharding confines that burst to the session that caused
/// it, which is the part the old flat cache got wrong.
/// state of not having a cache at all — and sharding confines that burst to the key that caused it,
/// which is the part the old flat cache got wrong.
/// </remarks>
public const int MaxEntriesPerSession = 20_000;
@@ -105,7 +110,7 @@ public sealed class SessionAclDecisionCache
/// answer is already memoized, so the allocation the cache exists to avoid is paid on the hit
/// path too. Read and Browse ask this question once per node, which is precisely where paying
/// for a walk that never runs is worth removing. <see cref="GetOrAdd"/> remains, delegating
/// here, for callers that genuinely have nothing cheaper to offer.
/// here, but has no production caller — it is exercised by the cache's own tests.
/// </para>
/// <para>
/// The generation is checked (and a stale cache dropped) here rather than in
@@ -187,8 +192,14 @@ public sealed class SessionAclDecisionCache
/// <summary>
/// Returns the memoized decision for this key, computing and storing it when absent or when the
/// generation has moved on. A convenience over <see cref="TryGet"/> + <see cref="Set"/> for callers
/// that have no cheaper way to express the walk than a closure.
/// generation has moved on. A convenience over <see cref="TryGet"/> + <see cref="Set"/>.
/// <para>
/// <b>Retained for tests; production has no caller.</b> <see cref="DataPlaneAuthorizer"/> uses
/// the split <see cref="TryGet"/>/<see cref="Set"/> pair precisely so a hit pays for no closure,
/// and no other caller has appeared since. Kept because it is the readable single-expression
/// form of the same protocol and is how the cache's tests drive it — not because a production
/// caller is expected back.
/// </para>
/// </summary>
/// <param name="generation">The authorization generation the decision is being taken under.</param>
/// <param name="sessionKey">Stable identity of the calling session — its key id, else its principal.</param>
@@ -8,16 +8,20 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Historian;
/// <summary>
/// Continuous-historization engine for non-Galaxy (driver) tags. Registers interest with the
/// per-node <see cref="DependencyMuxActor"/> for the configured historized tag refs, then taps the
/// <see cref="VirtualTagActor.DependencyValueChanged"/> values the mux fans for those refs:
/// values the mux fans for those refs — in production a
/// <see cref="VirtualTagActor.DependencyValueBatch"/> per driver burst, with the per-value
/// <see cref="VirtualTagActor.DependencyValueChanged"/> receive retained for direct senders and tests:
/// value → coerce to numeric → append to the durable <see cref="IHistorizationOutbox"/> (the crash
/// boundary) → a self-paced drain writes the outbox through <see cref="IHistorianValueWriter"/>'s
/// live-value path and acks (truncates) on success.
/// </summary>
/// <remarks>
/// <para>
/// <b>Message path (grounded against the real actors).</b> The mux fans
/// <see cref="VirtualTagActor.DependencyValueChanged"/> — which carries only
/// <c>(TagId, Value, TimestampUtc)</c> and <em>no quality</em> — to every registered subscriber.
/// <b>Message path (grounded against the real actors).</b> The mux fans each value — carrying
/// only <c>(TagId, Value, TimestampUtc)</c> and <em>no quality</em> — to every registered
/// subscriber, batched as a <see cref="VirtualTagActor.DependencyValueBatch"/> on the production
/// path and as a bare <see cref="VirtualTagActor.DependencyValueChanged"/> from a direct sender
/// or a test.
/// The recorder reuses that existing fan-out (no change to <c>DriverHostActor</c>), so values
/// arrive Good-quality by the same convention the scripted-alarm host uses (the mux only
/// forwards driver-published values); historized samples are recorded with
@@ -29,9 +29,11 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
/// </para>
///
/// <para>
/// <b>Data flow.</b> <see cref="DependencyMuxActor"/> delivers a
/// <see cref="VirtualTagActor.DependencyValueChanged"/> for every tag the loaded alarms
/// depend on; the host pushes each into the upstream. The engine self-evaluates: its own
/// <b>Data flow.</b> <see cref="DependencyMuxActor"/> delivers the values of every tag the
/// loaded alarms depend on — in production as a batched
/// <see cref="VirtualTagActor.DependencyValueBatch"/> per driver burst, with the per-value
/// <see cref="VirtualTagActor.DependencyValueChanged"/> receive retained for direct senders and
/// tests; the host pushes each into the upstream. The engine self-evaluates: its own
/// <see cref="ITagUpstreamSource.SubscribeTag"/> observer re-runs the predicates and raises
/// <see cref="ScriptedAlarmEngine.OnEvent"/>. The host does NOT call evaluate — it only
/// feeds values in and fans emissions out.
@@ -134,9 +136,10 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// <summary>Factory method to create Props for a <see cref="ScriptedAlarmHostActor"/>.</summary>
/// <param name="publishActor">The OPC UA publish actor that consumes
/// <see cref="OpcUaPublishActor.AlarmStateUpdate"/> bridged from engine emissions.</param>
/// <param name="mux">Optional dependency multiplexer the host registers interest with so it
/// receives a <see cref="VirtualTagActor.DependencyValueChanged"/> per dependency tag. Null on the
/// dev/Mac path (no live values).</param>
/// <param name="mux">Optional dependency multiplexer the host registers interest with so it receives
/// its dependency tags' values — a <see cref="VirtualTagActor.DependencyValueBatch"/> per burst in
/// production, or a per-value <see cref="VirtualTagActor.DependencyValueChanged"/> from a direct
/// sender or a test. Null on the dev/Mac path (no live values).</param>
/// <param name="upstream">The mux-fed upstream the engine reads + subscribes from. MUST be the
/// same instance the <paramref name="engine"/> was constructed around.</param>
/// <param name="engine">The scripted-alarm engine this host owns + disposes.</param>
@@ -403,10 +406,12 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
/// Loops the per-value handler, preserving in-burst order.</summary>
/// <remarks>
/// <b>Mid-batch exception policy: unguarded, deliberately.</b> An exception escaping
/// <see cref="OnDependencyChanged"/> drops the remaining items of this burst and restarts the actor
/// — exactly what it already did when the same values arrived as N separate messages (the tail is
/// then lost to the mailbox flush instead of to the loop), so batching changes the blast radius by
/// nothing. Catching per item is deliberately NOT done: the handler is a single
/// <see cref="OnDependencyChanged"/> drops the remaining items of this burst and restarts the actor.
/// That IS wider than the per-message path — Akka restarts do not flush the mailbox, only the
/// failing message is dropped, so as N separate messages the same fault would cost one value rather
/// than the burst's tail. Accepted: the engine tolerates a missed intermediate value (the next
/// delivery for that tag re-converges its state). Catching per item is deliberately NOT done: the
/// handler is a single
/// <c>IUpstreamValueSource.Push</c> into an in-memory cache, so a throw means the upstream itself is
/// broken and swallowing it would feed the engine a silently truncated burst. Contrast
/// <c>ContinuousHistorizationRecorder.IngestAsync</c>, which DOES catch per item because its
@@ -8,9 +8,11 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
/// Bridges a driver that implements <see cref="IDependencyConsumer"/> onto the per-node
/// <see cref="DependencyMuxActor"/>. Spawned as a child of <c>DriverHostActor</c> for each such
/// driver: on start (and on every apply via <see cref="ReRegister"/>) it registers the driver's
/// declared <see cref="IDependencyConsumer.DependencyRefs"/> with the mux, and forwards each
/// <see cref="VirtualTagActor.DependencyValueChanged"/> the mux fans out into
/// <see cref="IDependencyConsumer.OnDependencyValue"/>.
/// declared <see cref="IDependencyConsumer.DependencyRefs"/> with the mux, and forwards each value
/// the mux fans out into <see cref="IDependencyConsumer.OnDependencyValue"/>. The production
/// delivery is the batched <see cref="VirtualTagActor.DependencyValueBatch"/> — one message per
/// driver burst; the per-value <see cref="VirtualTagActor.DependencyValueChanged"/> receive remains
/// for direct senders and tests, and the batch handler simply loops it.
///
/// <para>
/// This is the exact seam a <c>VirtualTagActor</c> uses to receive its inputs, generalised so a
@@ -76,11 +78,13 @@ public sealed class DependencyConsumerMuxAdapter : ReceiveActor
/// <remarks>
/// <b>Mid-batch exception policy: unguarded, matching the single-value path.</b> An exception
/// escaping <see cref="IDependencyConsumer.OnDependencyValue"/> drops the remaining items of this
/// burst and restarts the adapter — the same outcome the single-value handler already has (there the
/// tail is lost to the mailbox flush rather than to the loop), so batching does not widen it.
/// Catching per item HERE only would make the batch path quietly more forgiving than the single-value
/// one for the same consumer fault, so the two are deliberately kept identical: a consumer that needs
/// per-value fault tolerance owns it inside its own <c>OnDependencyValue</c>.
/// burst and restarts the adapter. This DOES widen the per-fault loss: Akka restarts do not flush
/// the mailbox (only the failing message is dropped), so as N separate messages the same fault
/// would have cost one value, while batched it costs the rest of the burst's tail. Accepted,
/// because an <see cref="IDependencyConsumer"/> tolerates missed intermediate values — the next
/// delivery re-converges its state — and catching per item HERE only would make the batch path
/// quietly more forgiving than the single-value one for the same consumer fault. A consumer that
/// needs per-value fault tolerance owns it inside its own <c>OnDependencyValue</c>.
/// </remarks>
/// <param name="msg">The batch of matched dependency values.</param>
private void OnDependencyValueBatch(VirtualTagActor.DependencyValueBatch msg)