Both defects were found by #491's live gate against a real HistorianGateway and filed rather than fixed at the time, because each one's fix is a design decision rather than a patch. #537 — both nodes of a redundant pair captured every value, so the historian received duplicate live samples for every historized tag (measured: the gateway's write counter advanced twice per value and halved when one central was stopped). The recorder now reads a capture gate per value, fed from the new PrimaryGatePolicy.ShouldRecordHistorizedValues through IHistorizationRoleView — a third verdict on the same RedundancyRoleView object, registered unconditionally on driver nodes rather than alongside the alarm section's IRedundancyRoleView (which only exists when that section is enabled; piggybacking is the #511 registration accident). Two things are deliberate and easy to get backwards: * It gates the CAPTURE, not the drain — the opposite of the alarm sink. That queue is in LocalDb and replicates, so the Secondary already holds the Primary's rows. The historization outbox is a node-local FasterLog replicating to nobody, so a drain-only gate would leave the standby appending forever to a queue no one empties: unbounded disk, then a flood of stale duplicates the moment it is promoted. Entries a node already captured are still drained by that node. * The peer it stands down for must RECORD THE SAME REFS, not merely hold the same rows — a Primary in this node's own per-cluster mesh. A node carrying no cluster-scoped role cannot establish that and never stands down: under a fleet-wide election the elected Primary is usually running a different cluster's configuration, and deferring to it would end this cluster's historization silently, with the drain reporting success on an empty outbox forever. That is the scope mismatch that once suspended the alarm drain on every node of the rig. An unknown role captures, matching the alarm drain — a duplicate sample is recoverable, a hole in the trend is not. #538 — the drain writes every per-tag group and then acks all-or-nothing (deliberate: RemoveAsync truncates THROUGH an id, so partial acking could drop older unwritten entries). One permanently failing tag therefore pinned the FIFO head while every healthy tag in the batch was re-submitted to the historian on every pass, indefinitely — duplicate samples and an outbox that never truncated, observed live at 8.3 MB from a single unprovisionable tag. The drain now tracks consecutive failures per historian tag and abandons that tag's entries once it exceeds MaxWriteAttempts (new, default 5), so the head advances. The counter only advances on a pass where some OTHER tag wrote successfully: that is what separates "this tag is poison" from "the backend is down". A count-only quarantine looks identical on the poison-tag case and silently discards the whole backlog during an ordinary gateway restart, turning a duplicate-samples bug into a lost-history one. Abandonment is also deferred until every failing tag is over budget, so nothing is discarded on a pass that could not have advanced the head anyway. Each abandonment logs a Warning naming the tag; the total rides RecorderStatus.AbandonedEntries. Capacity also gains a non-zero default (500,000 entries) as the disk backstop for the one case the quarantine deliberately cannot resolve — a historian refusing every write, where retaining is correct. Set 0 to restore unbounded retention. Every new test was falsified by reverting the production change it guards, and each one reddens alone: * drop the backend-reachable evidence -> only A_backend_that_fails_every_tag_abandons_nothing * never abandon -> only A_permanently_failing_tag_is_abandoned_so_healthy_tags_stop_being_rewritten * latch the capture gate at construction -> only The_capture_gate_is_re_read_per_value... * treat any Primary as a scope peer -> only the two scope-mismatch cases Full suite green. (Four OpcUaClient.Browser failures during the run were the opc-plc fixture being down on the shared Docker host; brought it back up and they pass.) Claude-Session: https://claude.ai/code/session_015p7wGqy3YpZNCpDzTpGMKo
This commit is contained in:
@@ -286,6 +286,22 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
|
||||
/// </remarks>
|
||||
private readonly IDriverPrimaryRoleSource? _primaryRoleSource;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #537: where the continuous-historization <b>capture</b> verdict is published for the
|
||||
/// recorder, which taps the mux fan-out and so needs the decision off its own mailbox. Null on
|
||||
/// nodes that wire no redundancy manager.
|
||||
/// </summary>
|
||||
private readonly IHistorizationRoleView? _historizationRoleView;
|
||||
|
||||
/// <summary>
|
||||
/// Tests whether a node named in a redundancy snapshot serves this node's address space — i.e.
|
||||
/// is a per-cluster mesh partner recording the very same historized refs. Null (the default)
|
||||
/// means the caller could not establish it, which never stands this node down. See
|
||||
/// <see cref="PrimaryGatePolicy.ShouldRecordHistorizedValues"/> for why proving the sharing
|
||||
/// matters rather than trusting "somebody is Primary".
|
||||
/// </summary>
|
||||
private readonly Func<CommonsNodeId, bool>? _sharesHistorizationScopeWithLocal;
|
||||
|
||||
/// <summary>
|
||||
/// Host of this node's LocalDb replication partner — the only node that holds a copy of this
|
||||
/// node's alarm queue, and therefore the only node it may ever stand down in favour of.
|
||||
@@ -422,7 +438,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
|
||||
IDeploymentArtifactFetcher? artifactFetcher = null,
|
||||
IAlarmStateStore? alarmStateStore = null,
|
||||
ITelemetryLocalHub? telemetryHub = null,
|
||||
IDriverPrimaryRoleSource? primaryRoleSource = null) =>
|
||||
IDriverPrimaryRoleSource? primaryRoleSource = null,
|
||||
IHistorizationRoleView? historizationRoleView = null,
|
||||
Func<CommonsNodeId, bool>? sharesHistorizationScopeWithLocal = null) =>
|
||||
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
|
||||
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
|
||||
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
|
||||
@@ -433,7 +451,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
|
||||
healthPublisher, virtualTagEvaluator, historyWriter, virtualTagHostOverride,
|
||||
loggerFactory, scriptRootLogger, scriptedAlarmHostOverride, invokerFactory, driverMemberCountProvider,
|
||||
deploymentArtifactCache, redundancyRoleView, replicationPeerHost, fetchAndCacheMode, artifactFetcher,
|
||||
alarmStateStore, telemetryHub, primaryRoleSource));
|
||||
alarmStateStore, telemetryHub, primaryRoleSource, historizationRoleView,
|
||||
sharesHistorizationScopeWithLocal));
|
||||
|
||||
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
|
||||
/// <param name="dbFactory">Database context factory for configuration database access.</param>
|
||||
@@ -480,6 +499,15 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
|
||||
/// <paramref name="redundancyRoleView"/> even though the production object implements both: a test that
|
||||
/// supplies only a role-view double must not silently also satisfy this, or its primary-role assertions
|
||||
/// pass without the publish ever happening. Null on nodes that wire no redundancy manager.</param>
|
||||
/// <param name="historizationRoleView">Gitea #537: where the continuous-historization <i>capture</i>
|
||||
/// verdict is published, for the recorder that taps the mux fan-out. A third distinct parameter for
|
||||
/// the same reason <paramref name="primaryRoleSource"/> is a second — the production object
|
||||
/// implements all three, and a test double supplied for one must not silently satisfy the others.
|
||||
/// Null on nodes that wire no redundancy manager.</param>
|
||||
/// <param name="sharesHistorizationScopeWithLocal">Tests whether a node named in a redundancy
|
||||
/// snapshot serves this node's address space and therefore records the same historized refs. Null
|
||||
/// (the default) means the caller could not establish it, and this node never stands down — see
|
||||
/// <see cref="PrimaryGatePolicy.ShouldRecordHistorizedValues"/>.</param>
|
||||
public DriverHostActor(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext>? dbFactory,
|
||||
CommonsNodeId localNode,
|
||||
@@ -504,8 +532,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
|
||||
IDeploymentArtifactFetcher? artifactFetcher = null,
|
||||
IAlarmStateStore? alarmStateStore = null,
|
||||
ITelemetryLocalHub? telemetryHub = null,
|
||||
IDriverPrimaryRoleSource? primaryRoleSource = null)
|
||||
IDriverPrimaryRoleSource? primaryRoleSource = null,
|
||||
IHistorizationRoleView? historizationRoleView = null,
|
||||
Func<CommonsNodeId, bool>? sharesHistorizationScopeWithLocal = null)
|
||||
{
|
||||
_historizationRoleView = historizationRoleView;
|
||||
_sharesHistorizationScopeWithLocal = sharesHistorizationScopeWithLocal;
|
||||
_telemetryHub = telemetryHub;
|
||||
_deploymentArtifactCache = deploymentArtifactCache;
|
||||
_redundancyRoleView = redundancyRoleView;
|
||||
@@ -1431,6 +1463,22 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
|
||||
_redundancyRoleView?.Publish(
|
||||
PrimaryGatePolicy.ShouldDrainAlarmHistory(_localRole, queueSharingPeerIsPrimary: peerIsPrimary));
|
||||
|
||||
// Gitea #537: the continuous-historization CAPTURE verdict. Same role rule as the drain gate
|
||||
// above, but a different peer question — historization is not pair-local, it is fleet-wide by
|
||||
// historian tag name, so the only node worth standing down for is one recording the SAME refs:
|
||||
// a mesh partner serving this node's address space. With no way to establish that (a legacy
|
||||
// node carrying no cluster-scoped role, or a test harness), the predicate is null and this
|
||||
// node keeps capturing. Duplicate samples are recoverable; a hole in the trend is not.
|
||||
var historizationPeerIsPrimary =
|
||||
_sharesHistorizationScopeWithLocal is { } sharesScope
|
||||
&& msg.Nodes.Any(n => n.Role == RedundancyRole.Primary
|
||||
&& n.NodeId != _localNode
|
||||
&& sharesScope(n.NodeId));
|
||||
|
||||
_historizationRoleView?.PublishHistorizationRole(
|
||||
PrimaryGatePolicy.ShouldRecordHistorizedValues(
|
||||
_localRole, addressSpaceSharingPeerIsPrimary: historizationPeerIsPrimary));
|
||||
|
||||
// The DATA-PLANE verdict, deliberately — the same one HandleRouteNodeWrite gates on, not the
|
||||
// drain verdict published immediately above. A driver reading this claims an exclusive identity
|
||||
// on a shared external system (Gitea #511: the Sparkplug host id), where two claimants is the
|
||||
|
||||
@@ -71,4 +71,56 @@ public static class PrimaryGatePolicy
|
||||
RedundancyRole.Secondary or RedundancyRole.Detached => !queueSharingPeerIsPrimary,
|
||||
_ => true, // unknown role ⇒ drain; a duplicate row beats a silent gap
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Decide whether this node should <b>capture</b> continuous-historization values into its
|
||||
/// durable outbox (Gitea #537).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Same rule as <see cref="ShouldDrainAlarmHistory"/>, deliberately — and for the same
|
||||
/// reason.</b> The historian is append-only and the error costs are asymmetric: a false
|
||||
/// allow costs a duplicate sample, a false deny costs a permanent hole in the trend. So an
|
||||
/// unknown role captures, and only an explicit Secondary/Detached stands down.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>But it gates the CAPTURE, not the drain — the opposite of the alarm sink.</b> That
|
||||
/// choice follows from where the queue lives. The alarm queue is in LocalDb and
|
||||
/// <i>replicates</i>, so the Secondary already holds the Primary's rows and gating the
|
||||
/// drain loses nothing. The historization outbox is a node-local FasterLog that replicates
|
||||
/// to nobody: gating only its drain would leave the standby appending forever to a queue no
|
||||
/// one empties (unbounded disk, and a flood of stale duplicates the moment it is promoted),
|
||||
/// while gating the capture leaves it holding nothing. Values already captured are still
|
||||
/// drained by the node that captured them, so a demotion loses nothing that was recorded.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The residual cost is a capture gap across a failover, bounded by how long the newly
|
||||
/// promoted node takes to see its first snapshot. That is inherent to any non-duplicating
|
||||
/// design; the alternative — both nodes capturing — is what #537 was filed about.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="localRole">This node's last-known redundancy role, or <c>null</c> when unknown.</param>
|
||||
/// <param name="addressSpaceSharingPeerIsPrimary">
|
||||
/// Whether the node holding <see cref="RedundancyRole.Primary"/> in the same snapshot is one
|
||||
/// that serves <b>this node's address space</b>, and therefore captures the very same historized
|
||||
/// refs — its per-cluster mesh partner.
|
||||
/// <para>
|
||||
/// The scoping matters for the same reason it does on the alarm queue, and the mistake is
|
||||
/// easier to make here because it looks safe: the redundancy election reaches only as far as
|
||||
/// the caller can prove, whereas historization is fleet-wide by tag name. A node that stands
|
||||
/// down in favour of a Primary running some <i>other</i> cluster's configuration hands its
|
||||
/// tags to a node that never records them, and nothing says so — the drain simply reports
|
||||
/// success on an empty outbox forever. Callers that cannot establish the sharing pass
|
||||
/// <c>false</c>, which never stands down; duplicates are recoverable, a silent gap is not.
|
||||
/// </para>
|
||||
/// </param>
|
||||
/// <returns><c>true</c> to capture; <c>false</c> only when a node recording these same tags is doing it.</returns>
|
||||
public static bool ShouldRecordHistorizedValues(
|
||||
RedundancyRole? localRole, bool addressSpaceSharingPeerIsPrimary) =>
|
||||
localRole switch
|
||||
{
|
||||
RedundancyRole.Primary => true,
|
||||
RedundancyRole.Secondary or RedundancyRole.Detached => !addressSpaceSharingPeerIsPrimary,
|
||||
_ => true, // unknown role ⇒ capture; a duplicate sample beats a hole in the trend
|
||||
};
|
||||
}
|
||||
|
||||
@@ -57,9 +57,33 @@ public sealed class ContinuousHistorizationOptions
|
||||
/// <summary>Steady drain cadence in seconds (also the post-success reschedule). Defaults to 2.</summary>
|
||||
public double DrainIntervalSeconds { get; init; } = 2;
|
||||
|
||||
/// <summary>Maximum un-acked outbox entries before the drop-oldest capacity policy kicks in;
|
||||
/// <c>0</c> (the default) means unbounded.</summary>
|
||||
public int Capacity { get; init; }
|
||||
/// <summary>
|
||||
/// Maximum un-acked outbox entries before the drop-oldest capacity policy kicks in; <c>0</c>
|
||||
/// means unbounded.
|
||||
/// <para>
|
||||
/// Defaults to 500,000 (Gitea #538) — roughly 50 MB of FasterLog, and hours-to-days of
|
||||
/// backlog depending on tag count and update rate. It is a disk backstop for the one case
|
||||
/// the per-tag quarantine cannot resolve: a historian that is unreachable or refusing
|
||||
/// <em>every</em> write, where nothing proves any particular tag is at fault, so the
|
||||
/// recorder correctly retains rather than discards. Set <c>0</c> to restore unbounded
|
||||
/// retention where the outbox sits on storage that can absorb an arbitrarily long outage.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public int Capacity { get; init; } = 500_000;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #538: consecutive failed drain passes a single historian tag may accumulate — counted
|
||||
/// only across passes where <em>other</em> tags wrote successfully, so a backend outage never
|
||||
/// advances it — before that tag's queued entries are discarded and the FIFO head is allowed to
|
||||
/// advance. Defaults to 5; clamped to at least 1 by the recorder.
|
||||
/// <para>
|
||||
/// Without this, one permanently-failing tag (typically one whose historian tag was never
|
||||
/// provisioned) pins the head forever and every <em>healthy</em> tag in the batch is
|
||||
/// re-written to the historian on every pass, at <see cref="DrainIntervalSeconds"/> cadence,
|
||||
/// indefinitely. Each abandonment logs a Warning naming the tag.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public int MaxWriteAttempts { get; init; } = 5;
|
||||
|
||||
/// <summary>Initial retry backoff (seconds) after a failed drain pass. Defaults to 1.</summary>
|
||||
public double MinBackoffSeconds { get; init; } = 1;
|
||||
|
||||
+161
-15
@@ -60,7 +60,12 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
}
|
||||
|
||||
/// <summary>Outcome of one off-thread drain pass, piped back to the actor thread.</summary>
|
||||
private sealed record DrainResult(bool Success, int Acked, int Attempted);
|
||||
/// <param name="Success">Whether the pass advanced the FIFO head (nothing left blocking it).</param>
|
||||
/// <param name="Acked">Entries durably written and truncated away.</param>
|
||||
/// <param name="Attempted">Entries in the peeked batch.</param>
|
||||
/// <param name="Abandoned">Entries discarded because their tag is poison — see
|
||||
/// <see cref="DrainOnceAsync"/> (Gitea #538). Counted within <paramref name="Attempted"/>.</param>
|
||||
private sealed record DrainResult(bool Success, int Acked, int Attempted, int Abandoned = 0);
|
||||
|
||||
/// <summary>Ask the recorder for its current counters (used by the meter/health wiring).</summary>
|
||||
public sealed class GetStatus
|
||||
@@ -91,13 +96,19 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
/// <param name="OutboxAppendFailures">Lifetime count of durable-boundary append failures (the value
|
||||
/// was dropped, not recorded, and the actor stayed alive rather than restart-looping).</param>
|
||||
/// <param name="LastDrainSucceeded">Whether the most recent drain pass acked cleanly.</param>
|
||||
/// <param name="SuppressedNotPrimary">Lifetime count of values not captured because this node is
|
||||
/// the Secondary of a pair whose Primary records the same refs (Gitea #537).</param>
|
||||
/// <param name="AbandonedEntries">Lifetime count of entries discarded because their historian tag
|
||||
/// kept failing while other tags were writing successfully (Gitea #538).</param>
|
||||
public sealed record RecorderStatus(
|
||||
int QueuedDepth,
|
||||
long TotalRecorded,
|
||||
long DroppedNonNumeric,
|
||||
long OutboxDropped,
|
||||
long OutboxAppendFailures,
|
||||
bool LastDrainSucceeded);
|
||||
bool LastDrainSucceeded,
|
||||
long SuppressedNotPrimary = 0,
|
||||
long AbandonedEntries = 0);
|
||||
|
||||
private readonly IActorRef _dependencyMux;
|
||||
private readonly IHistorianValueWriter _writer;
|
||||
@@ -115,6 +126,20 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
private readonly TimeSpan _drainInterval;
|
||||
private readonly TimeSpan _minBackoff;
|
||||
private readonly TimeSpan _maxBackoff;
|
||||
|
||||
/// <summary>Gitea #537: "should this node be capturing right now?". Supplied by the Runtime wiring
|
||||
/// from the redundancy role view; a null gate (tests, single-node graphs) always captures.</summary>
|
||||
private readonly Func<bool> _captureGate;
|
||||
|
||||
/// <summary>Gitea #538: consecutive failed write passes a tag may accumulate — while OTHER tags are
|
||||
/// writing successfully — before its queued entries are abandoned so the FIFO head can advance.</summary>
|
||||
private readonly int _maxWriteAttempts;
|
||||
|
||||
/// <summary>Consecutive failed write passes per historian tag, counted only across passes that
|
||||
/// proved the backend reachable. Reset on the tag's first success. Mutated exclusively inside
|
||||
/// <see cref="DrainOnceAsync"/>, which <see cref="_draining"/> keeps single-flight.</summary>
|
||||
private readonly Dictionary<string, int> _tagWriteFailures = new(StringComparer.Ordinal);
|
||||
|
||||
private readonly ILoggingAdapter _log = Context.GetLogger();
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
|
||||
@@ -124,8 +149,14 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
private long _totalRecorded;
|
||||
private long _droppedNonNumeric;
|
||||
private long _outboxAppendFailures;
|
||||
private long _suppressedNotPrimary;
|
||||
private long _abandonedEntries;
|
||||
private bool _lastDrainSucceeded = true;
|
||||
|
||||
/// <summary>Last observed state of <see cref="_captureGate"/>, so a change is logged once rather
|
||||
/// than on every value. Seeded open: a gate that starts closed logs its first suppression.</summary>
|
||||
private bool _captureGateOpen = true;
|
||||
|
||||
/// <summary>Gets or sets the timer scheduler (set by Akka via <see cref="IWithTimers"/>).</summary>
|
||||
public ITimerScheduler Timers { get; set; } = null!;
|
||||
|
||||
@@ -138,6 +169,11 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
/// <param name="drainInterval">Steady drain cadence; also the post-success reschedule.</param>
|
||||
/// <param name="minBackoff">Initial retry backoff after a failed drain.</param>
|
||||
/// <param name="maxBackoff">Cap on the exponential retry backoff.</param>
|
||||
/// <param name="captureGate">Gitea #537: "should this node be capturing right now?", read per
|
||||
/// value. Null (the default) always captures — the correct posture for a single-node deployment
|
||||
/// and for tests.</param>
|
||||
/// <param name="maxWriteAttempts">Gitea #538: consecutive failed write passes one tag may
|
||||
/// accumulate, while other tags are succeeding, before its entries are abandoned.</param>
|
||||
/// <returns>Props for the actor.</returns>
|
||||
public static Props Props(
|
||||
IActorRef dependencyMux,
|
||||
@@ -147,9 +183,12 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
int drainBatchSize = 64,
|
||||
TimeSpan? drainInterval = null,
|
||||
TimeSpan? minBackoff = null,
|
||||
TimeSpan? maxBackoff = null) =>
|
||||
TimeSpan? maxBackoff = null,
|
||||
Func<bool>? captureGate = null,
|
||||
int maxWriteAttempts = 5) =>
|
||||
Akka.Actor.Props.Create(() => new ContinuousHistorizationRecorder(
|
||||
dependencyMux, writer, outbox, historizedRefs, drainBatchSize, drainInterval, minBackoff, maxBackoff));
|
||||
dependencyMux, writer, outbox, historizedRefs, drainBatchSize, drainInterval, minBackoff, maxBackoff,
|
||||
captureGate, maxWriteAttempts));
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="ContinuousHistorizationRecorder"/> class.</summary>
|
||||
/// <param name="dependencyMux">The per-node dependency mux to register historized-ref interest with.</param>
|
||||
@@ -160,6 +199,11 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
/// <param name="drainInterval">Steady drain cadence; also the post-success reschedule.</param>
|
||||
/// <param name="minBackoff">Initial retry backoff after a failed drain.</param>
|
||||
/// <param name="maxBackoff">Cap on the exponential retry backoff.</param>
|
||||
/// <param name="captureGate">Gitea #537: "should this node be capturing right now?", read per
|
||||
/// value. Null (the default) always captures.</param>
|
||||
/// <param name="maxWriteAttempts">Gitea #538: consecutive failed write passes one tag may
|
||||
/// accumulate, while other tags are succeeding, before its entries are abandoned. Clamped to at
|
||||
/// least 1.</param>
|
||||
public ContinuousHistorizationRecorder(
|
||||
IActorRef dependencyMux,
|
||||
IHistorianValueWriter writer,
|
||||
@@ -168,7 +212,9 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
int drainBatchSize = 64,
|
||||
TimeSpan? drainInterval = null,
|
||||
TimeSpan? minBackoff = null,
|
||||
TimeSpan? maxBackoff = null)
|
||||
TimeSpan? maxBackoff = null,
|
||||
Func<bool>? captureGate = null,
|
||||
int maxWriteAttempts = 5)
|
||||
{
|
||||
_dependencyMux = dependencyMux ?? throw new ArgumentNullException(nameof(dependencyMux));
|
||||
_writer = writer ?? throw new ArgumentNullException(nameof(writer));
|
||||
@@ -187,6 +233,11 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
_minBackoff = minBackoff is { } mb && mb > TimeSpan.Zero ? mb : TimeSpan.FromSeconds(1);
|
||||
_maxBackoff = maxBackoff is { } xb && xb > TimeSpan.Zero ? xb : TimeSpan.FromSeconds(30);
|
||||
_currentBackoff = _minBackoff;
|
||||
// A null gate captures unconditionally. That is the safe default in both directions it is
|
||||
// reached from: a deployment with no redundancy manager (nothing would ever open a closed
|
||||
// gate), and a test that does not care about the role.
|
||||
_captureGate = captureGate ?? (static () => true);
|
||||
_maxWriteAttempts = maxWriteAttempts > 0 ? maxWriteAttempts : 1;
|
||||
|
||||
ReceiveAsync<VirtualTagActor.DependencyValueChanged>(OnValueChangedAsync);
|
||||
Receive<UpdateHistorizedRefs>(OnUpdateHistorizedRefs);
|
||||
@@ -236,6 +287,33 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
return;
|
||||
}
|
||||
|
||||
// Gitea #537: both nodes of a redundant pair serve the same address space and see the same mux
|
||||
// fan-out, so an ungated recorder writes every sample TWICE (measured on the docker-dev central
|
||||
// pair: the gateway's write counter advanced twice per value, and halved when one node stopped).
|
||||
// The gate closes only on a node whose pair partner is the Primary and is recording the same
|
||||
// refs; it is read PER VALUE rather than latched, so promotion resumes capture on the very next
|
||||
// sample with no restart. Note what is NOT gated: the drain. Entries already captured are this
|
||||
// node's to deliver, and a demoted node must still empty its own outbox.
|
||||
if (!_captureGate())
|
||||
{
|
||||
_suppressedNotPrimary++;
|
||||
if (_captureGateOpen)
|
||||
{
|
||||
_captureGateOpen = false;
|
||||
_log.Info("ContinuousHistorization: this node is not the recording Primary for its address space; "
|
||||
+ "suppressing value capture until it is promoted (the pair Primary is recording these tags).");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_captureGateOpen)
|
||||
{
|
||||
_captureGateOpen = true;
|
||||
_log.Info("ContinuousHistorization: this node is now the recording Primary for its address space; "
|
||||
+ "resuming value capture.");
|
||||
}
|
||||
|
||||
if (!TryCoerceToDouble(msg.Value, out double numeric))
|
||||
{
|
||||
// The SQL analog live-value path is numeric-only — drop non-coercible values (string/null/
|
||||
@@ -431,9 +509,11 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
}
|
||||
|
||||
// Write per-tag batches. The outbox's RemoveAsync truncates the FIFO head THROUGH the acked
|
||||
// id, so partial per-tag acking could drop un-written older entries; ack all-or-nothing —
|
||||
// only when every tag's batch wrote do we truncate the whole peeked prefix (one commit).
|
||||
var allOk = true;
|
||||
// id, so partial per-tag acking could drop un-written older entries; the ack stays
|
||||
// all-or-nothing — only when nothing is left blocking do we truncate the whole peeked
|
||||
// prefix (one commit).
|
||||
var succeeded = 0;
|
||||
var failedGroups = new List<(string Tag, int Count)>();
|
||||
foreach (IGrouping<string, HistorizationOutboxEntry> group in
|
||||
batch.GroupBy(e => e.Tag, StringComparer.Ordinal))
|
||||
{
|
||||
@@ -453,21 +533,82 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
ok = false;
|
||||
}
|
||||
|
||||
if (!ok)
|
||||
if (ok)
|
||||
{
|
||||
allOk = false;
|
||||
succeeded++;
|
||||
_tagWriteFailures.Remove(group.Key);
|
||||
}
|
||||
else
|
||||
{
|
||||
failedGroups.Add((group.Key, values.Count));
|
||||
}
|
||||
}
|
||||
|
||||
if (!allOk)
|
||||
if (failedGroups.Count == 0)
|
||||
{
|
||||
// Leave the entire peeked prefix queued for the next (backed-off) attempt.
|
||||
// Ack the whole prefix by truncating through the last entry (FIFO head advance + commit).
|
||||
await _outbox.RemoveAsync(batch[^1].Id, ct).ConfigureAwait(false);
|
||||
return new DrainResult(true, batch.Count, batch.Count);
|
||||
}
|
||||
|
||||
if (succeeded == 0)
|
||||
{
|
||||
// NOTHING wrote this pass, so there is no evidence any particular tag is at fault — the
|
||||
// backend itself is unreachable or refusing everything. Retain the whole prefix and back
|
||||
// off; this is the outage path, and it must never discard data. Deliberately does not
|
||||
// touch the per-tag counters either: they count consecutive failures observed while the
|
||||
// backend was demonstrably up, so an outage neither advances nor resets them.
|
||||
return new DrainResult(false, 0, batch.Count);
|
||||
}
|
||||
|
||||
// Ack the whole prefix by truncating through the last entry (FIFO head advance + commit).
|
||||
// Gitea #538: at least one tag wrote, so the backend IS reachable and a tag that keeps
|
||||
// failing is poison — most often one whose historian tag was never provisioned (EnsureTags
|
||||
// fires only for newly-ADDED historized tags, so a renamed historianTagname is easy to hit).
|
||||
// Left blocking, it pins the FIFO head forever while every HEALTHY tag in the batch is
|
||||
// re-written to the historian on every pass — duplicate samples, and an outbox that never
|
||||
// truncates. Abandon the poison tag's entries once it has burned through its attempts, so
|
||||
// the head can advance; the loss is bounded to one tag and it is loudly reported, whereas
|
||||
// the alternative silently corrupts every other tag's history.
|
||||
// Count first, decide second. A tag that is over its budget while ANOTHER is still within
|
||||
// its own does not get abandoned yet — the head cannot advance either way, so abandoning it
|
||||
// now would only discard entries early and log the same warning on every pass until the
|
||||
// other tag resolves.
|
||||
var stillBlocking = false;
|
||||
foreach ((string tag, int _) in failedGroups)
|
||||
{
|
||||
int failures = _tagWriteFailures.GetValueOrDefault(tag) + 1;
|
||||
_tagWriteFailures[tag] = failures;
|
||||
if (failures <= _maxWriteAttempts)
|
||||
{
|
||||
stillBlocking = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (stillBlocking)
|
||||
{
|
||||
// Leave the entire peeked prefix queued for the next (backed-off) attempt. Bounded:
|
||||
// every failing tag's counter advanced, so this can repeat at most _maxWriteAttempts
|
||||
// times before the branch below takes over.
|
||||
return new DrainResult(false, 0, batch.Count);
|
||||
}
|
||||
|
||||
var abandoned = 0;
|
||||
foreach ((string tag, int count) in failedGroups)
|
||||
{
|
||||
abandoned += count;
|
||||
_log.Warning(
|
||||
"ContinuousHistorization: historian tag {Tag} has failed {Failures} consecutive write "
|
||||
+ "attempts while other tags wrote successfully; discarding {Count} queued sample(s) so "
|
||||
+ "the outbox can drain. Check the tag exists in the historian — EnsureTags provisioning "
|
||||
+ "runs only for newly-ADDED historized tags, so a changed historianTagname is never "
|
||||
+ "provisioned.",
|
||||
tag, _tagWriteFailures.GetValueOrDefault(tag), count);
|
||||
}
|
||||
|
||||
// Every failure is now over budget; the head may advance. The abandoned entries are
|
||||
// truncated away with the acked ones — that is what "abandoned" means here.
|
||||
await _outbox.RemoveAsync(batch[^1].Id, ct).ConfigureAwait(false);
|
||||
return new DrainResult(true, batch.Count, batch.Count);
|
||||
return new DrainResult(true, batch.Count - abandoned, batch.Count, abandoned);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
@@ -488,6 +629,9 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
{
|
||||
_draining = false;
|
||||
_lastDrainSucceeded = result.Success;
|
||||
// Accumulated on the actor thread from the piped result rather than inside the off-thread drain,
|
||||
// so the counter has a single writer and GetStatus never reads a torn value.
|
||||
_abandonedEntries += result.Abandoned;
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
@@ -515,7 +659,9 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
|
||||
_droppedNonNumeric,
|
||||
_outbox.DroppedCount,
|
||||
_outboxAppendFailures,
|
||||
_lastDrainSucceeded);
|
||||
_lastDrainSucceeded,
|
||||
_suppressedNotPrimary,
|
||||
_abandonedEntries);
|
||||
}
|
||||
|
||||
private static TimeSpan Min(TimeSpan a, TimeSpan b) => a < b ? a : b;
|
||||
|
||||
@@ -41,8 +41,43 @@ public interface IRedundancyRoleView
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Thread-safe <see cref="IRedundancyRoleView"/> + <see cref="IDriverPrimaryRoleSource"/>, each
|
||||
/// backed by its own volatile field.
|
||||
/// A singleton snapshot of the continuous-historization <b>capture</b> decision (Gitea #537), so
|
||||
/// the recorder can ask "should this node be recording historized values right now?".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A separate interface from <see cref="IRedundancyRoleView"/> even though one object
|
||||
/// implements both, because the two are registered on different terms:
|
||||
/// <c>IRedundancyRoleView</c> is registered by <c>AddAlarmHistorian</c> and so exists only
|
||||
/// where the alarm section is enabled, while this one is registered unconditionally on every
|
||||
/// driver-role node. Piggybacking on the alarm registration would silently drop the
|
||||
/// historization gate on any pair that runs historization without alarm history — the same
|
||||
/// registration accident Gitea #511 documents on the neighbouring verdict.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Publishes the <i>decision</i> rather than the role, so
|
||||
/// <see cref="PrimaryGatePolicy.ShouldRecordHistorizedValues"/> stays the single place that
|
||||
/// decides. Note it is <b>not</b> the alarm drain verdict: the two policies agree on the role
|
||||
/// rule but disagree on what makes a peer relevant (a queue-sharing replication partner vs. a
|
||||
/// node serving the same address space), and the wrong peer notion in either direction is a
|
||||
/// silent gap.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public interface IHistorizationRoleView
|
||||
{
|
||||
/// <summary>Whether this node should be capturing continuous-historization values right now.</summary>
|
||||
bool ShouldRecordHistorizedValues { get; }
|
||||
|
||||
/// <summary>Records a fresh decision. Called by <c>DriverHostActor</c> on every redundancy snapshot.</summary>
|
||||
/// <param name="shouldRecordHistorizedValues">
|
||||
/// The decision <see cref="PrimaryGatePolicy.ShouldRecordHistorizedValues"/> produced.
|
||||
/// </param>
|
||||
void PublishHistorizationRole(bool shouldRecordHistorizedValues);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Thread-safe <see cref="IRedundancyRoleView"/> + <see cref="IDriverPrimaryRoleSource"/> +
|
||||
/// <see cref="IHistorizationRoleView"/>, each backed by its own volatile field.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
@@ -55,7 +90,7 @@ public interface IRedundancyRoleView
|
||||
/// them is the bug that live gate already found once.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRoleSource
|
||||
public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRoleSource, IHistorizationRoleView
|
||||
{
|
||||
// Seeded with the decision for "role unknown" rather than a bare false. An unpublished view and a
|
||||
// node whose role nothing ever reports are genuinely the same situation, and they must behave the
|
||||
@@ -71,9 +106,18 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
|
||||
private volatile bool _shouldActAsPrimary =
|
||||
PrimaryGatePolicy.ShouldServiceAsPrimary(localRole: null, driverMemberCount: 1);
|
||||
|
||||
// Seeded for the unknown-role case from the same policy that will later publish here: a node
|
||||
// nothing has reported a role for captures, exactly as an unpaired or single-node deployment must.
|
||||
// Defaulting closed would leave a deployment that never publishes a role with no trend data at all.
|
||||
private volatile bool _shouldRecordHistorizedValues =
|
||||
PrimaryGatePolicy.ShouldRecordHistorizedValues(localRole: null, addressSpaceSharingPeerIsPrimary: false);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool ShouldDrainAlarmHistory => _shouldDrainAlarmHistory;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool ShouldRecordHistorizedValues => _shouldRecordHistorizedValues;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool ShouldActAsPrimary => _shouldActAsPrimary;
|
||||
|
||||
@@ -82,4 +126,8 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void PublishPrimaryRole(bool shouldActAsPrimary) => _shouldActAsPrimary = shouldActAsPrimary;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void PublishHistorizationRole(bool shouldRecordHistorizedValues)
|
||||
=> _shouldRecordHistorizedValues = shouldRecordHistorizedValues;
|
||||
}
|
||||
|
||||
@@ -92,6 +92,13 @@ public static class ServiceCollectionExtensions
|
||||
// publishes two verdicts into the same object rather than into two that disagree.
|
||||
services.TryAddSingleton<RedundancyRoleView>();
|
||||
services.TryAddSingleton<IDriverPrimaryRoleSource>(sp => sp.GetRequiredService<RedundancyRoleView>());
|
||||
|
||||
// Gitea #537: the continuous-historization capture verdict, registered here — unconditionally on
|
||||
// every driver-role node — for the same reason as the line above, and NOT alongside the alarm
|
||||
// drain's IRedundancyRoleView. AddAlarmHistorian registers that one only when its own section is
|
||||
// enabled, so piggybacking would leave a redundant pair that historizes values but not alarms
|
||||
// with no gate at all, and both nodes would write every sample twice with nothing to say so.
|
||||
services.TryAddSingleton<IHistorizationRoleView>(sp => sp.GetRequiredService<RedundancyRoleView>());
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -436,7 +443,15 @@ public static class ServiceCollectionExtensions
|
||||
drainBatchSize: continuousOptions.DrainBatchSize,
|
||||
drainInterval: TimeSpan.FromSeconds(continuousOptions.DrainIntervalSeconds),
|
||||
minBackoff: TimeSpan.FromSeconds(continuousOptions.MinBackoffSeconds),
|
||||
maxBackoff: TimeSpan.FromSeconds(continuousOptions.MaxBackoffSeconds)),
|
||||
maxBackoff: TimeSpan.FromSeconds(continuousOptions.MaxBackoffSeconds),
|
||||
// Gitea #537: read the verdict PER VALUE off the shared role view rather
|
||||
// than capturing a bool, so a promotion resumes capture on the next sample.
|
||||
// The view is registered unconditionally on driver nodes; a null one (test
|
||||
// graphs) captures unconditionally, which is the right posture there.
|
||||
captureGate: resolver.GetService<IHistorizationRoleView>() is { } histRoleView
|
||||
? () => histRoleView.ShouldRecordHistorizedValues
|
||||
: null,
|
||||
maxWriteAttempts: continuousOptions.MaxWriteAttempts),
|
||||
ContinuousHistorizationRecorderActorName);
|
||||
registry.Register<ContinuousHistorizationRecorderKey>(continuousRecorder);
|
||||
}
|
||||
@@ -494,6 +509,19 @@ public static class ServiceCollectionExtensions
|
||||
PeerProbeSupervisorName);
|
||||
registry.Register<PeerProbeSupervisorKey>(peerProbes);
|
||||
|
||||
// Gitea #537: "does this snapshot node record the same historized refs as me?" — true only
|
||||
// for a partner in this node's own per-cluster mesh, which is exactly the set that serves
|
||||
// this node's address space. A node carrying NO cluster-scoped role (the legacy,
|
||||
// pre-Phase-6 shape) cannot establish that, so the predicate stays null and this node never
|
||||
// stands down: on a fleet-wide election the elected Primary is usually running a DIFFERENT
|
||||
// cluster's configuration, and deferring to it would silently end this cluster's
|
||||
// historization altogether — the same scope mismatch that once suspended the alarm drain on
|
||||
// every node at once.
|
||||
Func<Commons.Types.NodeId, bool>? historizationScopePeer =
|
||||
roleInfo.ClusterRole is { } meshRole
|
||||
? nodeId => roleInfo.MembersWithRole(meshRole).Contains(nodeId)
|
||||
: null;
|
||||
|
||||
var driverHost = system.ActorOf(
|
||||
// ackRouter: under ClusterClient mode the node comm actor relays ApplyAcks across
|
||||
// the boundary; under Dps it stays null and the host publishes on the
|
||||
@@ -528,7 +556,11 @@ public static class ServiceCollectionExtensions
|
||||
// Gitea #511: where this actor publishes its Primary DATA-PLANE verdict for drivers
|
||||
// that claim an exclusive external identity. Registered unconditionally by
|
||||
// AddOtOpcUaRuntime, unlike redundancyRoleView above — see the comment there.
|
||||
primaryRoleSource: resolver.GetService<IDriverPrimaryRoleSource>()),
|
||||
primaryRoleSource: resolver.GetService<IDriverPrimaryRoleSource>(),
|
||||
// Gitea #537: where this actor publishes the continuous-historization CAPTURE
|
||||
// verdict, and how it decides which peer is worth standing down for.
|
||||
historizationRoleView: resolver.GetService<IHistorizationRoleView>(),
|
||||
sharesHistorizationScopeWithLocal: historizationScopePeer),
|
||||
DriverHostActorName);
|
||||
registry.Register<DriverHostActorKey>(driverHost);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user