Compare commits

...

5 Commits

Author SHA1 Message Date
Joseph Doherty 56f73e49ec docs(drivers): mark reconfigure-while-faulted Task 1 complete
v2-ci / build (push) Failing after 36s
v2-ci / unit-tests (tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests) (push) Has been skipped
2026-06-14 17:23:10 -04:00
Joseph Doherty 7ffe8939e7 style(drivers): clarify Reconnecting InitializeFailed no-op is generation-agnostic (code-review nit) 2026-06-14 17:19:34 -04:00
Joseph Doherty 751786ec8c fix(drivers): adopt corrected config via ApplyDelta while (re)connecting (#7)
A DriverInstanceActor stuck Reconnecting/Connecting now adopts a config delivered via ApplyDelta and
re-initialises with it, instead of dead-lettering and retrying the stale config forever. A monotonic
init generation supersedes the in-flight init so the corrected config always wins.
2026-06-14 17:15:28 -04:00
Joseph Doherty 806a252f25 docs(drivers): implementation plan for reconfigure-while-faulted (#7) 2026-06-14 17:11:07 -04:00
Joseph Doherty 076ca025ba docs(drivers): design for adopting config mid-(re)connect (reconfigure-while-faulted #7) 2026-06-14 17:08:24 -04:00
5 changed files with 630 additions and 8 deletions
@@ -0,0 +1,166 @@
# Driver-reconfigure-while-faulted — Design
**Date:** 2026-06-14
**Status:** Approved (brainstorming) — ready for implementation plan
**Branch:** `feat/driver-reconfigure-while-faulted` off master `f9be3843`
**Follow-up:** `pending.md` open item #7 (also "Incidental findings from the OpcUaClient live-verify (2026-06-13)").
## Problem
A `DriverInstanceActor` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs`)
that is stuck `Reconnecting` (its `InitializeAsync` keeps failing on a bad config) **ignores a
corrected config**. When the operator deploys a fix, `DriverHostActor.ApplyChildDelta` `Tell`s the
child a `DriverInstanceActor.ApplyDelta` — but only the `Connected()` and `Stubbed()` behaviours have
a `Receive<ApplyDelta>` handler. In `Connecting()` and `Reconnecting()` the message **dead-letters**,
so the actor keeps retrying the stale `_currentConfigJson` forever. The only workaround today is to
restart the whole node (which respawns the driver actor fresh from the current deployment artifact).
Surfaced live on 2026-06-13: a `MAIN-opcua-eq` driver was faulted from a prior bad config and never
adopted the corrected one until the node was restarted.
## Goal
An `ApplyDelta` delivered while the actor is `Connecting` or `Reconnecting` **adopts the new config and
re-initialises with it**, so a corrected deployment recovers a faulted driver without a node restart —
and the adopted config is guaranteed to win, even against an old initialise still in flight.
Non-goals: changing the `Connected` apply path (`ReinitializeAsync`), the host/spawn logic, any
message contract visible outside the actor, or anything in EF/Configuration. The live `/run`
verification is deferred (user-driven).
## Approach (chosen: B — generation guard + immediate re-init)
Alternatives considered:
- **A — config-swap only.** `ApplyDelta` just sets `_currentConfigJson` + replies success; the
`Reconnecting` retry timer picks the new config up on its next tick. Smallest diff, but in
`Connecting` (no timer) an old in-flight init that *succeeds* connects on the stale config — the
adopt can lose the race — plus up to `reconnectInterval` latency. **Rejected:** the adopt isn't
guaranteed to stick, which is the whole point.
- **C — host respawns the faulted child.** `DriverHostActor` `Context.Stop`s + respawns the child
with the new config (automating "restart node"). No state-machine change, but drops health history
and live subscriptions, adds restart churn, and papers over the actor contract instead of fixing
it. **Rejected.**
- **B — generation guard + immediate re-init (chosen).** The corrected config always wins; immediate
retry (no timer-tick wait); also closes a latent concurrent-init window in `Reconnecting`.
Contained to this one actor; fully unit-testable offline.
### Generation guard (the correctness mechanism)
Each `InitializeAsync` attempt is tagged with a monotonic generation. A result is honoured only when
it matches the latest generation; an older result is from a **superseded** attempt (e.g. an
`ApplyDelta` adopted a new config mid-(re)connect) and is dropped.
```csharp
private int _initGeneration;
private void InitializeAsync(string driverConfigJson)
{
_currentConfigJson = driverConfigJson;
var generation = ++_initGeneration; // bump on the actor thread; the closure captures the local
var self = Self;
_ = Task.Run(async () =>
{
try
{
await _driver.InitializeAsync(driverConfigJson, CancellationToken.None);
self.Tell(new InitializeSucceeded(generation));
}
catch (Exception ex)
{
self.Tell(new InitializeFailed(ex.Message, generation));
}
});
}
```
The two internal result records gain the token (nothing outside the actor constructs them):
```csharp
public sealed record InitializeSucceeded(int Generation);
public sealed record InitializeFailed(string Reason, int Generation);
```
Every `InitializeSucceeded`/`InitializeFailed` handler in `Connecting()` and `Reconnecting()` drops a
superseded result first:
```csharp
if (msg.Generation != _initGeneration) return; // superseded — a newer InitializeAsync replaced this one
```
`_initGeneration` is read/written **only on the actor thread** — `InitializeAsync` runs inside a
message handler, the `Task.Run` closure captures `generation` as a local, and the result handler runs
on the actor thread. No lock needed.
### The adopt handler (new — `Connecting` + `Reconnecting`)
```csharp
Receive<ApplyDelta>(msg =>
{
_log.Info("DriverInstance {Id}: ApplyDelta during (re)connect — adopting new config, re-initialising now",
_driverInstanceId);
InitializeAsync(msg.DriverConfigJson); // swaps _currentConfigJson, bumps generation (supersedes the
// in-flight init), starts a fresh attempt immediately
Sender.Tell(new ApplyResult(true, "config adopted; reinitializing", msg.Correlation));
});
```
The actor **stays in its current state**; the new init's result drives the next transition through
the existing (now generation-guarded) handlers:
- `Connecting`: new init succeeds → `Become(Connected)`; fails → `Become(Reconnecting)`.
- `Reconnecting`: new init succeeds → `Become(Connected)` (and the existing handler cancels the retry
timer); fails → no-op, the retry timer keeps retrying the **new** config (now in `_currentConfigJson`).
The `Reconnecting` retry timer is **left running** — if the immediate attempt fails it continues
retrying the new config. A redundant concurrent attempt (immediate + a timer tick) is harmlessly
deduped by the generation guard.
### Why it's correct
- **No stale hijack.** In `Connecting`, if the old in-flight init's `InitializeSucceeded(oldGen)` lands
while still connecting, the guard drops it, so the actor cannot connect on the stale config. Only the
new-generation result transitions it. (If the stale result lands *after* the new init already reached
`Connected`, it dead-letters harmlessly — `Connected` has no `InitializeSucceeded` handler.)
- **No subscription churn / leak.** `Connecting` has no live subscription yet; `Reconnecting` already
detached on its entry (`DisconnectObserved`/`ForceReconnect` call `DetachSubscription`). `_desiredRefs`
is retained and re-applied by `ResubscribeDesired` on the next `Connected` entry. The adopt handler
touches no subscription state.
- **Reuses an established pattern.** The `Reconnecting` retry loop already calls `InitializeAsync`
(not `ReinitializeAsync`) repeatedly on a not-connected driver, so adopting via `InitializeAsync`
introduces no new driver-contract assumption.
- **`Stubbed` untouched.** It never calls `InitializeAsync`, so `_initGeneration` stays 0 and its
existing `ApplyDelta` stubbed-success reply is unchanged.
## Testing (offline — Akka TestKit, no live gate)
Observability uses the existing pattern: with a `SetDesiredSubscriptions` set, a `Connected` entry
auto-subscribes, so `driver.SubscribeCount` is the deterministic "did we connect, and on which config"
probe. The shared stub gains **opt-in** per-config gating + config capture (additive — existing
`InitializeShouldThrow`/`InitializeCount` fields and their tests are untouched).
1. **Reconnecting adopts a corrected config and connects** (headline bug). Init throws for `v1` →
stuck `Reconnecting`; `Ask<ApplyResult>(ApplyDelta(v2))` where `v2` succeeds → reply `Success` with
the correlation; the actor reaches `Connected` on `v2` (`SubscribeCount` goes to 1; the config that
drove `Connected` is `v2`).
2. **Generation guard ignores a superseded in-flight result** (the race). A gated `v1` init is pending
in `Connecting`; `ApplyDelta(v2)` is sent (also gated). Release `v1` → the actor **stays
`Connecting`** (no auto-subscribe fires, `SubscribeCount == 0`). Release `v2` → `Connected`
(`SubscribeCount == 1`). Proves a stale init cannot hijack state.
3. **Regression** — existing tests stay green: `Initialize_failure_keeps_actor_in_Reconnecting_state`,
`ApplyDelta_when_Connected_calls_ReinitializeAsync_and_replies_success`.
## Files touched
- `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs` — generation field + tagged
result records + guarded handlers + the two new `Receive<ApplyDelta>` handlers.
- `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverInstanceActorTests.cs` — new adopt +
generation-guard tests; extend the private stub with opt-in gating/config-capture.
No host change, no contract change visible outside the actor, no EF/Configuration change, no bUnit.
## Risk / classification
**High-risk** — actor state machine + concurrency. Full review chain (spec + code reviews) and a final
integration review. The live `/run` gate (deploy a corrected config to a faulted `MAIN-opcua-eq` and
confirm it adopts without a node restart) is **deferred** per the user's instruction.
@@ -0,0 +1,347 @@
# Driver-reconfigure-while-faulted — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:subagent-driven-development to implement this plan task-by-task.
**Goal:** A `DriverInstanceActor` that is `Connecting`/`Reconnecting` adopts a corrected config delivered via `ApplyDelta` and re-initialises with it (instead of dead-lettering and retrying the stale config forever), with the adopted config guaranteed to win against an old initialise still in flight.
**Architecture:** Add a monotonic **generation** to each `InitializeAsync` attempt; tag the `InitializeSucceeded`/`InitializeFailed` result records with it and drop superseded results in the `Connecting`/`Reconnecting` handlers. Add a `Receive<ApplyDelta>` to both not-connected behaviours that calls `InitializeAsync(newConfig)` (swaps `_currentConfigJson`, bumps the generation, retries immediately) and replies `ApplyResult(true,…)`. Contained to one actor; no host/contract/EF change.
**Tech Stack:** C# / .NET 10, Akka.NET `ReceiveActor`, xUnit + Shouldly, Akka.TestKit.
**Design doc:** `docs/plans/2026-06-14-driver-reconfigure-while-faulted-design.md` (committed `076ca025`).
---
### Task 0: Feature branch (already created)
**Classification:** trivial
**Estimated implement time:** ~0 min (precondition already met)
**Parallelizable with:** none
The branch `feat/driver-reconfigure-while-faulted` already exists off master `f9be3843`, and the
design doc is committed on it (`076ca025`). No action — included only so the task graph records the
precondition. Implementers for later tasks commit **on this branch** (never on master), stage **by
path** (never `git add .`), and never stage `sql_login.txt`, `src/Server/ZB.MOM.WW.OtOpcUa.Host/pki/`,
`pending.md`, `current.md`, or `docker-dev/docker-compose.yml`.
---
### Task 1: Adopt corrected config mid-(re)connect (`DriverInstanceActor`)
**Classification:** high-risk (actor state machine + concurrency)
**Estimated implement time:** ~6 min
**Parallelizable with:** none
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs`
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverInstanceActorTests.cs`
This is one atomic actor change (generation guard + adopt handlers are interdependent — neither is
meaningfully landable alone) plus its tests, in a single production file + single test file. Follow
TDD: extend the stub, write the two failing tests, implement, then prove the whole `DriverInstanceActorTests`
class + the Runtime suite stay green.
**Background the implementer needs (don't re-derive):**
- State machine: `Connecting()` (~line 217), `Connected()` (~258), `Reconnecting()` (~302),
`Stubbed()` (~204). Only `Connected`/`Stubbed` currently handle `ApplyDelta`. The bug: `ApplyDelta`
dead-letters in `Connecting`/`Reconnecting`.
- `InitializeAsync` (~line 338) runs the driver init on a `Task.Run` and `self.Tell`s
`InitializeSucceeded`/`InitializeFailed`. The `Reconnecting` `RetryConnect` timer re-calls
`InitializeAsync(_currentConfigJson)` every `_reconnectInterval`.
- `InitializeSucceeded`/`InitializeFailed` are **never** constructed outside this file (verified), so
adding a `Generation` param is safe. Existing tests drive state only via `InitializeRequested` +
polling `driver.InitializeCount` — they don't construct the result records.
- `ApplyDelta` is `Tell`'d fire-and-forget by `DriverHostActor`; its `ApplyResult` reply already
dead-letters harmlessly (no host handler). Reply anyway, for consistency + testability.
- Observability for "did we connect, and on which config": with a `SetDesiredSubscriptions` set, a
`Connected` entry auto-subscribes (`ResubscribeDesired` → `driver.SubscribeAsync`), so
`driver.SubscribeCount` is the deterministic probe.
**Step 1: Extend the private `StubDriver` (additive — do not break existing fields/tests)**
In `DriverInstanceActorTests.cs`, extend the existing private `StubDriver` so a test can (a) capture
each config passed to `InitializeAsync`, and (b) optionally gate/branch init behaviour per config.
Keep `InitializeShouldThrow` + `InitializeCount` working exactly as before (used by other tests).
```csharp
// Add to StubDriver:
private readonly object _initConfigsLock = new();
/// <summary>Every config string passed to <see cref="InitializeAsync"/>, in call order.</summary>
public List<string> InitConfigs { get; } = new();
/// <summary>Optional per-config init behaviour. When set, it fully owns the init outcome for that
/// config (await/throw); <see cref="InitializeShouldThrow"/> is ignored. Null ⇒ legacy behaviour.</summary>
public Func<string, Task>? InitBehavior { get; set; }
public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
Interlocked.Increment(ref InitializeCount);
lock (_initConfigsLock) InitConfigs.Add(driverConfigJson);
if (InitBehavior is not null) { await InitBehavior(driverConfigJson); return; }
if (InitializeShouldThrow) throw new InvalidOperationException("stub-init-fail");
}
```
(Change `InitializeAsync` from the current synchronous `Task`-returning body to `async Task`; the
`return Task.CompletedTask;` line goes away. `SubscribableStubDriver`/`WritableStubDriver` inherit
unchanged.)
**Step 2: Write the failing headline test — Reconnecting adopts a corrected config and connects**
```csharp
/// <summary>A driver stuck Reconnecting (init failing on a bad config) adopts a corrected config
/// delivered via ApplyDelta and connects on it — no node restart. Closes pending.md #7.</summary>
[Fact]
public async Task ApplyDelta_while_Reconnecting_adopts_new_config_and_connects()
{
const string bad = "{\"v\":\"bad\"}";
const string good = "{\"v\":\"good\"}";
var driver = new SubscribableStubDriver
{
// Fail every init except the corrected config.
InitBehavior = cfg => cfg == good ? Task.CompletedTask : throw new InvalidOperationException("bad-cfg"),
};
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, reconnectInterval: TimeSpan.FromMilliseconds(50)));
// A desired subscription so a Connected entry is observable via SubscribeCount.
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(new[] { "tag-a" }, TimeSpan.FromMilliseconds(100)));
// Boot on the bad config → stuck Reconnecting (retries fail).
actor.Tell(new DriverInstanceActor.InitializeRequested(bad));
AwaitCondition(() => driver.InitializeCount >= 2, TimeSpan.FromSeconds(2)); // proven retrying
driver.SubscribeCount.ShouldBe(0); // never connected
// Operator deploys the fix.
var correlation = CorrelationId.NewId();
var reply = await actor.Ask<DriverInstanceActor.ApplyResult>(
new DriverInstanceActor.ApplyDelta(good, correlation), TimeSpan.FromSeconds(3));
reply.Success.ShouldBeTrue();
reply.Correlation.ShouldBe(correlation);
// It now connects on the corrected config and auto-subscribes.
AwaitCondition(() => driver.SubscribeCount >= 1, TimeSpan.FromSeconds(3));
driver.InitConfigs.ShouldContain(good);
}
```
**Step 3: Write the failing race test — generation guard drops a superseded in-flight result**
```csharp
/// <summary>A stale InitializeSucceeded from an old (superseded) config cannot hijack the state:
/// while a gated old-config init is pending in Connecting, an ApplyDelta adopts a new config; the
/// old init completing afterwards is ignored, and only the new config drives Connected.</summary>
[Fact]
public async Task ApplyDelta_supersedes_in_flight_init_so_stale_result_is_ignored()
{
const string v1 = "{\"v\":1}";
const string v2 = "{\"v\":2}";
var gate1 = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var gate2 = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var driver = new SubscribableStubDriver
{
InitBehavior = cfg => cfg == v1 ? gate1.Task : gate2.Task, // both succeed only when released
};
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, reconnectInterval: TimeSpan.FromSeconds(30)));
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(new[] { "tag-a" }, TimeSpan.FromMilliseconds(100)));
// v1 init starts and blocks on gate1 → actor sits in Connecting.
actor.Tell(new DriverInstanceActor.InitializeRequested(v1));
AwaitCondition(() => driver.InitConfigs.Contains(v1), TimeSpan.FromSeconds(2));
// Adopt v2 while v1's init is still pending; v2 init starts and blocks on gate2.
await actor.Ask<DriverInstanceActor.ApplyResult>(
new DriverInstanceActor.ApplyDelta(v2, CorrelationId.NewId()), TimeSpan.FromSeconds(3));
AwaitCondition(() => driver.InitConfigs.Contains(v2), TimeSpan.FromSeconds(2));
// Release the OLD (superseded) init. Its success must be ignored — actor stays Connecting.
gate1.SetResult();
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(400)); // no AttributeValuePublished / churn
driver.SubscribeCount.ShouldBe(0); // did NOT connect on the stale v1
// Release the NEW init → connects on v2.
gate2.SetResult();
AwaitCondition(() => driver.SubscribeCount >= 1, TimeSpan.FromSeconds(3));
}
```
**Step 4: Run both new tests — verify they FAIL**
```bash
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests \
--filter "FullyQualifiedName~DriverInstanceActorTests.ApplyDelta_while_Reconnecting_adopts_new_config_and_connects|FullyQualifiedName~DriverInstanceActorTests.ApplyDelta_supersedes_in_flight_init_so_stale_result_is_ignored"
```
Expected: both FAIL today — `ApplyDelta` dead-letters in `Connecting`/`Reconnecting`, so the actor
never connects and `SubscribeCount` stays 0 (Ask for `ApplyResult` also times out).
**Step 5: Implement the production change in `DriverInstanceActor.cs`**
(a) Field, near the other private fields (after `_currentConfigJson`):
```csharp
/// <summary>Monotonic token tagging each <see cref="InitializeAsync"/> attempt. An init result is
/// honoured only when its generation matches the latest; an older result is from a superseded attempt
/// (e.g. an <see cref="ApplyDelta"/> adopted a new config mid-(re)connect) and is dropped. Touched only
/// on the actor thread, so no lock is needed.</summary>
private int _initGeneration;
```
(b) Tag the result records (top of the class, with the other record decls):
```csharp
public sealed record InitializeSucceeded(int Generation);
public sealed record InitializeFailed(string Reason, int Generation);
```
(c) `InitializeAsync` — bump + tag:
```csharp
private void InitializeAsync(string driverConfigJson)
{
_currentConfigJson = driverConfigJson;
var generation = ++_initGeneration;
var self = Self;
_ = Task.Run(async () =>
{
try
{
await _driver.InitializeAsync(driverConfigJson, CancellationToken.None);
self.Tell(new InitializeSucceeded(generation));
}
catch (Exception ex)
{
self.Tell(new InitializeFailed(ex.Message, generation));
}
});
}
```
(d) Guard the result handlers. In **`Connecting()`**, prepend the stale check to both:
```csharp
Receive<InitializeSucceeded>(msg =>
{
if (msg.Generation != _initGeneration) return; // superseded by a newer InitializeAsync
_log.Info("DriverInstance {Id}: connected", _driverInstanceId);
Become(Connected);
PublishHealthSnapshot();
ResubscribeDesired();
AttachAlarmSource();
});
Receive<InitializeFailed>(msg =>
{
if (msg.Generation != _initGeneration) return; // superseded
_log.Warning("DriverInstance {Id}: initialize failed: {Reason}", _driverInstanceId, msg.Reason);
RecordFault();
Become(Reconnecting);
PublishHealthSnapshot();
});
```
In **`Reconnecting()`**, guard the success handler (the failed handler is already a no-op — leave it,
optionally drop the now-unused `_` param name to `msg` for symmetry but keep it a no-op):
```csharp
Receive<InitializeSucceeded>(msg =>
{
if (msg.Generation != _initGeneration) return; // superseded
Timers.Cancel("retry-connect");
_log.Info("DriverInstance {Id}: reconnected", _driverInstanceId);
Become(Connected);
PublishHealthSnapshot();
ResubscribeDesired();
AttachAlarmSource();
});
```
(e) Add the adopt handler to **both** `Connecting()` and `Reconnecting()`. Put a private helper near
`InitializeAsync` and wire `Receive<ApplyDelta>(AdoptConfigDuringInit);` into each behaviour:
```csharp
/// <summary>Adopt a new config while not connected: ApplyDelta in Connecting/Reconnecting re-inits
/// immediately with the new config. <see cref="InitializeAsync"/> swaps <c>_currentConfigJson</c> and
/// bumps the generation, so the in-flight (old-config) init is superseded and its result is dropped.
/// The actor stays in its current state; the new init's result drives the next transition. In
/// Reconnecting the retry timer is left running — if this immediate attempt fails it keeps retrying
/// the new config (a redundant concurrent attempt is deduped by the generation guard).</summary>
private void AdoptConfigDuringInit(ApplyDelta msg)
{
_log.Info("DriverInstance {Id}: ApplyDelta during (re)connect — adopting new config, re-initialising now",
_driverInstanceId);
InitializeAsync(msg.DriverConfigJson);
Sender.Tell(new ApplyResult(true, "config adopted; reinitializing", msg.Correlation));
}
```
Do **not** change `Connected()`'s `ApplyDelta` (still `ReinitializeAsync` via
`HandleApplyDeltaAsync`) or `Stubbed()`'s.
**Step 6: Run the new tests — verify they PASS**
```bash
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests \
--filter "FullyQualifiedName~DriverInstanceActorTests.ApplyDelta_while_Reconnecting_adopts_new_config_and_connects|FullyQualifiedName~DriverInstanceActorTests.ApplyDelta_supersedes_in_flight_init_so_stale_result_is_ignored"
```
Expected: both PASS.
**Step 7: Run the full `DriverInstanceActorTests` class + the Runtime suite — verify no regression**
```bash
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter "FullyQualifiedName~DriverInstanceActorTests"
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests
```
Expected: all green. In particular `Initialize_failure_keeps_actor_in_Reconnecting_state` (the
generation guard makes the latest-generation `InitializeFailed` honoured and stale ones ignored — both
are no-ops, so `InitializeCount` still climbs ≥3) and
`ApplyDelta_when_Connected_calls_ReinitializeAsync_and_replies_success` (Connected path untouched).
**Step 8: Commit (by path)**
```bash
git add src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverInstanceActorTests.cs
git commit -m "fix(drivers): adopt corrected config via ApplyDelta while (re)connecting (#7)
A DriverInstanceActor stuck Reconnecting/Connecting now adopts a config delivered via ApplyDelta and
re-initialises with it, instead of dead-lettering and retrying the stale config forever. A monotonic
init generation supersedes the in-flight init so the corrected config always wins."
```
**Acceptance criteria:**
- [ ] `ApplyDelta` in `Connecting` and `Reconnecting` adopts the new config + replies `ApplyResult(true)`.
- [ ] A superseded in-flight init result cannot transition the actor (generation guard).
- [ ] `Connected`/`Stubbed` `ApplyDelta` paths unchanged; no host/contract/EF change.
- [ ] New tests pass; full `Runtime.Tests` suite green.
---
### Task 2: Docs + bookkeeping
**Classification:** trivial
**Estimated implement time:** ~2 min
**Parallelizable with:** none (run after Task 1)
**Files:**
- Modify: `pending.md` (**disk-only — never stage/commit**)
- (No code/doc commits beyond the design+plan already committed.)
Done by the orchestrator, not a subagent. After Task 1 is merged-ready:
- Update `pending.md`: mark open follow-up #7 done with the merge SHA; note the live `/run` gate is
deferred (per user instruction this session). Do **not** `git add` it.
- Confirm the full solution builds clean and the Runtime suite is green for the final integration
review.
---
### Task 3: Live `/run` verification — DEFERRED (skipped this session)
**Classification:** n/a (user-driven)
**Estimated implement time:** n/a
**Deferred per the user's instruction ("skip the live test part").** When run: with docker-dev up, put
`MAIN-opcua-eq` into a faulted/`Reconnecting` state via a bad `DriverConfig`, deploy a corrected config
(`POST http://localhost:9200/api/deployments`, header `X-Api-Key: docker-dev-deploy-key`), and confirm
from central-1 logs that the driver **adopts the new config and connects without a node restart**
(today it would retry the stale config forever). Do not perform this step now.
---
## Execution notes (hard rules for every implementer)
- Commit **on `feat/driver-reconfigure-while-faulted`**, never master. Stage **by path**, never `git add .`.
- Never stage `sql_login.txt`, `src/Server/ZB.MOM.WW.OtOpcUa.Host/pki/`, `pending.md`, `current.md`,
`docker-dev/docker-compose.yml`. Never echo/commit secrets. No force-push, no `--no-verify`.
- No EF/Configuration/migration change. No bUnit.
@@ -0,0 +1,10 @@
{
"planPath": "docs/plans/2026-06-14-driver-reconfigure-while-faulted-plan.md",
"tasks": [
{"id": 0, "subject": "Task 0: Feature branch (already created)", "status": "completed"},
{"id": 1, "subject": "Task 1: Adopt corrected config mid-(re)connect (DriverInstanceActor)", "status": "completed", "blockedBy": [0]},
{"id": 2, "subject": "Task 2: Docs + bookkeeping", "status": "pending", "blockedBy": [1]},
{"id": 3, "subject": "Task 3: Live /run verification — DEFERRED (skipped)", "status": "pending", "blockedBy": [1]}
],
"lastUpdated": "2026-06-14"
}
@@ -33,8 +33,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
public static readonly TimeSpan DefaultReconnectInterval = TimeSpan.FromSeconds(10);
public sealed record InitializeRequested(string DriverConfigJson);
public sealed record InitializeSucceeded;
public sealed record InitializeFailed(string Reason);
public sealed record InitializeSucceeded(int Generation);
public sealed record InitializeFailed(string Reason, int Generation);
public sealed record DisconnectObserved(string Reason);
public sealed record ApplyDelta(string DriverConfigJson, CorrelationId Correlation);
public sealed record ApplyResult(bool Success, string? Reason, CorrelationId Correlation);
@@ -86,6 +86,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private readonly ILoggingAdapter _log = Context.GetLogger();
private string? _currentConfigJson;
/// <summary>Monotonic token tagging each <see cref="InitializeAsync"/> attempt. An init result is
/// honoured only when its generation matches the latest; an older result is from a superseded attempt
/// (e.g. an <see cref="ApplyDelta"/> adopted a new config mid-(re)connect) and is dropped. Touched only
/// on the actor thread, so no lock is needed.</summary>
private int _initGeneration;
/// <summary>
/// Timestamps of recent Faulted-state transitions; used to compute the 5-minute error count.
/// No lock needed — every read/write site runs inside an Akka message handler, which is
@@ -222,8 +228,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// "write timeout". Synchronous Receive: Sender.Tell on the actor thread is safe (#4a-instance).
Receive<WriteAttribute>(_ =>
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
Receive<InitializeSucceeded>(_ =>
Receive<ApplyDelta>(AdoptConfigDuringInit);
Receive<InitializeSucceeded>(msg =>
{
if (msg.Generation != _initGeneration) return;
_log.Info("DriverInstance {Id}: connected", _driverInstanceId);
Become(Connected);
PublishHealthSnapshot();
@@ -232,6 +240,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
});
Receive<InitializeFailed>(msg =>
{
if (msg.Generation != _initGeneration) return;
_log.Warning("DriverInstance {Id}: initialize failed: {Reason}", _driverInstanceId, msg.Reason);
RecordFault();
Become(Reconnecting);
@@ -306,8 +315,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// timeout on an inbound write to a transiently-down driver). Synchronous Receive (#4a-instance).
Receive<WriteAttribute>(_ =>
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
Receive<InitializeSucceeded>(_ =>
Receive<ApplyDelta>(AdoptConfigDuringInit);
Receive<InitializeSucceeded>(msg =>
{
if (msg.Generation != _initGeneration) return;
Timers.Cancel("retry-connect");
_log.Info("DriverInstance {Id}: reconnected", _driverInstanceId);
Become(Connected);
@@ -315,6 +326,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
ResubscribeDesired();
AttachAlarmSource();
});
// A failure here is a no-op regardless of generation — the retry timer keeps trying the
// current config; only a (generation-matched) InitializeSucceeded transitions state.
Receive<InitializeFailed>(_ => { /* keep retrying via timer */ });
Receive<SetDesiredSubscriptions>(StoreDesiredSubscriptions);
Receive<ForceReconnect>(_ => { /* already reconnecting — no-op */ });
@@ -338,21 +351,36 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private void InitializeAsync(string driverConfigJson)
{
_currentConfigJson = driverConfigJson;
var generation = ++_initGeneration;
var self = Self;
_ = Task.Run(async () =>
{
try
{
await _driver.InitializeAsync(driverConfigJson, CancellationToken.None);
self.Tell(new InitializeSucceeded());
self.Tell(new InitializeSucceeded(generation));
}
catch (Exception ex)
{
self.Tell(new InitializeFailed(ex.Message));
self.Tell(new InitializeFailed(ex.Message, generation));
}
});
}
/// <summary>Adopt a new config while not connected: ApplyDelta in Connecting/Reconnecting re-inits
/// immediately with the new config. <see cref="InitializeAsync"/> swaps <c>_currentConfigJson</c> and
/// bumps the generation, so the in-flight (old-config) init is superseded and its result is dropped.
/// The actor stays in its current state; the new init's result drives the next transition. In
/// Reconnecting the retry timer is left running — if this immediate attempt fails it keeps retrying
/// the new config (a redundant concurrent attempt is deduped by the generation guard).</summary>
private void AdoptConfigDuringInit(ApplyDelta msg)
{
_log.Info("DriverInstance {Id}: ApplyDelta during (re)connect — adopting new config, re-initialising now",
_driverInstanceId);
InitializeAsync(msg.DriverConfigJson);
Sender.Tell(new ApplyResult(true, "config adopted; reinitializing", msg.Correlation));
}
private async Task HandleApplyDeltaAsync(ApplyDelta msg)
{
var replyTo = Sender;
@@ -259,6 +259,69 @@ public sealed class DriverInstanceActorTests : RuntimeActorTestBase
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
}
/// <summary>A driver stuck Reconnecting (init failing on a bad config) adopts a corrected config
/// delivered via ApplyDelta and connects on it — no node restart. Closes pending.md #7.</summary>
[Fact]
public async Task ApplyDelta_while_Reconnecting_adopts_new_config_and_connects()
{
const string bad = "{\"v\":\"bad\"}";
const string good = "{\"v\":\"good\"}";
var driver = new SubscribableStubDriver
{
InitBehavior = cfg => cfg == good ? Task.CompletedTask : throw new InvalidOperationException("bad-cfg"),
};
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, reconnectInterval: TimeSpan.FromMilliseconds(50)));
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(new[] { "tag-a" }, TimeSpan.FromMilliseconds(100)));
actor.Tell(new DriverInstanceActor.InitializeRequested(bad));
AwaitCondition(() => driver.InitializeCount >= 2, TimeSpan.FromSeconds(2));
driver.SubscribeCount.ShouldBe(0);
var correlation = CorrelationId.NewId();
var reply = await actor.Ask<DriverInstanceActor.ApplyResult>(
new DriverInstanceActor.ApplyDelta(good, correlation), TimeSpan.FromSeconds(3));
reply.Success.ShouldBeTrue();
reply.Correlation.ShouldBe(correlation);
AwaitCondition(() => driver.SubscribeCount >= 1, TimeSpan.FromSeconds(3));
driver.InitConfigs.ShouldContain(good);
}
/// <summary>A stale InitializeSucceeded from an old (superseded) config cannot hijack the state:
/// while a gated old-config init is pending in Connecting, an ApplyDelta adopts a new config; the
/// old init completing afterwards is ignored, and only the new config drives Connected.</summary>
[Fact]
public async Task ApplyDelta_supersedes_in_flight_init_so_stale_result_is_ignored()
{
const string v1 = "{\"v\":1}";
const string v2 = "{\"v\":2}";
var gate1 = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var gate2 = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var driver = new SubscribableStubDriver
{
InitBehavior = cfg => cfg == v1 ? gate1.Task : gate2.Task,
};
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, reconnectInterval: TimeSpan.FromSeconds(30)));
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(new[] { "tag-a" }, TimeSpan.FromMilliseconds(100)));
actor.Tell(new DriverInstanceActor.InitializeRequested(v1));
AwaitCondition(() => driver.InitConfigs.Contains(v1), TimeSpan.FromSeconds(2));
await actor.Ask<DriverInstanceActor.ApplyResult>(
new DriverInstanceActor.ApplyDelta(v2, CorrelationId.NewId()), TimeSpan.FromSeconds(3));
AwaitCondition(() => driver.InitConfigs.Contains(v2), TimeSpan.FromSeconds(2));
gate1.SetResult();
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(400));
driver.SubscribeCount.ShouldBe(0);
gate2.SetResult();
AwaitCondition(() => driver.SubscribeCount >= 1, TimeSpan.FromSeconds(3));
}
private class StubDriver : IDriver
{
/// <summary>Gets or sets a value indicating whether initialization should throw.</summary>
@@ -268,6 +331,13 @@ public sealed class DriverInstanceActorTests : RuntimeActorTestBase
/// <summary>Gets the number of times reinitialization was called.</summary>
public int ReinitializeCount;
private readonly object _initConfigsLock = new();
/// <summary>Every config string passed to <see cref="InitializeAsync"/>, in call order.</summary>
public List<string> InitConfigs { get; } = new();
/// <summary>Optional per-config init behaviour. When set, it fully owns the init outcome for that
/// config (await/throw); <see cref="InitializeShouldThrow"/> is ignored. Null ⇒ legacy behaviour.</summary>
public Func<string, Task>? InitBehavior { get; set; }
/// <summary>Gets the driver instance ID.</summary>
public string DriverInstanceId => "stub-driver-1";
/// <summary>Gets the driver type.</summary>
@@ -276,11 +346,12 @@ public sealed class DriverInstanceActorTests : RuntimeActorTestBase
/// <summary>Initializes the driver with the specified configuration JSON.</summary>
/// <param name="driverConfigJson">The driver configuration JSON.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
Interlocked.Increment(ref InitializeCount);
lock (_initConfigsLock) InitConfigs.Add(driverConfigJson);
if (InitBehavior is not null) { await InitBehavior(driverConfigJson); return; }
if (InitializeShouldThrow) throw new InvalidOperationException("stub-init-fail");
return Task.CompletedTask;
}
/// <summary>Reinitializes the driver with the specified configuration JSON.</summary>