feat(sql): IBatchSubscribable and lifecycle-generation-stamped health (R02:P1, R06:S-9)

R02:P1: SqlDriver runs PollGroupEngine, so it now implements IBatchSubscribable and
raises one OnDataChangeBatch per poll burst (DriverInstanceActor forwards one message
per cycle instead of one per tag).
S-9: InitializeAsync/ShutdownAsync take a lifecycle generation; their health writes
apply only while current, and a poll that started under an older generation (one that
outlived the engine's teardown wait) no longer writes its verdict onto the new
configuration. Poll-driven updates can no longer end Initializing - only the
initialize's own final write does. Lifecycle writes now preserve LastSuccessfulRead.

Refs #744
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
Joseph Doherty
2026-10-22 16:03:23 -04:00
parent ab29b76be0
commit a7d21d5a65
2 changed files with 179 additions and 21 deletions
@@ -385,6 +385,85 @@ public sealed class SqlDriverTests
driver.GetHealth().LastSuccessfulRead.ShouldNotBeNull().ShouldBeGreaterThan(before);
}
/// <summary>
/// <b>R06:S-9 / lifecycle generations.</b> A poll that started before a Shutdown → Initialize cycle
/// (it can outlive the engine's 5 s teardown wait) must not write its verdict onto the NEW
/// configuration's health. Control: the same BadTimeout verdict under the current generation degrades.
/// </summary>
[Fact]
public async Task ObservePollOutcome_fromASupersededGeneration_isIgnored()
{
using var fixture = new SqlitePollFixture();
await using var driver = NewDriver(fixture, KvEntry("Speed", SqlitePollFixture.PresentKey));
await driver.InitializeAsync(ConfigJson, CancellationToken.None);
var stale = driver.LifecycleGenerationForTests;
await driver.ShutdownAsync(CancellationToken.None);
await driver.InitializeAsync(ConfigJson, CancellationToken.None);
driver.GetHealth().State.ShouldBe(DriverState.Healthy);
var timedOut = new DataValueSnapshot(null, SqlStatusCodes.BadTimeout, null, DateTime.UtcNow);
driver.ObservePollOutcome([timedOut], generation: stale);
driver.GetHealth().State.ShouldBe(DriverState.Healthy, "a superseded poll must not degrade the new init");
driver.ObservePollOutcome([timedOut], generation: driver.LifecycleGenerationForTests);
driver.GetHealth().State.ShouldBe(DriverState.Degraded);
}
/// <summary>
/// Only the initialize's own final write ends <c>Initializing</c>: a Good poll landing mid-init used to
/// flip it to Healthy before liveness had even answered. Control: once the init completes it is Healthy.
/// </summary>
[Fact]
public async Task APollLandingMidInitialize_cannotEndInitializing()
{
using var fixture = new SqlitePollFixture();
var factory = new GatedFactory();
await using var driver = NewDriver(fixture, fixture.ConnectionString, CapturingLogger.Null, factory,
KvEntry("Speed", SqlitePollFixture.PresentKey));
factory.Arm();
var init = driver.InitializeAsync(ConfigJson, CancellationToken.None);
(await factory.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)).ShouldBeTrue();
driver.GetHealth().State.ShouldBe(DriverState.Initializing);
driver.ObservePollOutcome([new DataValueSnapshot(42.0, SqlStatusCodes.Good, DateTime.UtcNow, DateTime.UtcNow)]);
driver.GetHealth().State.ShouldBe(DriverState.Initializing);
factory.Release();
await init.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
driver.GetHealth().State.ShouldBe(DriverState.Healthy);
}
/// <summary>A SQLite factory whose next connection creation blocks until released — parks an initialize.</summary>
private sealed class GatedFactory : DbProviderFactory
{
private readonly ManualResetEventSlim _release = new(initialState: true);
private volatile bool _armed;
public TaskCompletionSource<bool> Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public void Arm()
{
_release.Reset();
_armed = true;
}
public void Release() => _release.Set();
public override DbConnection CreateConnection()
{
if (_armed)
{
_armed = false;
Entered.TrySetResult(true);
_release.Wait(TimeSpan.FromSeconds(30));
}
return Microsoft.Data.Sqlite.SqliteFactory.Instance.CreateConnection()!;
}
}
// ---- Driver.Sql-010: the health field is read-modify-written from several poll loops ----
[Fact]
@@ -474,6 +553,31 @@ public sealed class SqlDriverTests
Volatile.Read(ref changes).ShouldBe(afterUnsubscribe);
}
/// <summary>
/// <b>R02:P1.</b> The driver runs <c>PollGroupEngine</c>, so it raises one batch per poll burst:
/// <c>DriverInstanceActor</c> then forwards one message per cycle instead of one per tag. Both tags of
/// the first (force-raised) poll arrive in the SAME batch, on the subscription's handle.
/// </summary>
[Fact]
public async Task Subscribe_raisesOneBatchPerPollBurst()
{
using var fixture = new SqlitePollFixture();
await using var driver = NewDriver(fixture,
KvEntry("Speed", SqlitePollFixture.PresentKey), KvEntry("Pressure", SqlitePollFixture.SecondPresentKey));
await driver.InitializeAsync(ConfigJson, CancellationToken.None);
var batchable = driver.ShouldBeAssignableTo<IBatchSubscribable>();
var first = new TaskCompletionSource<DataChangeBatchEventArgs>(TaskCreationOptions.RunContinuationsAsynchronously);
batchable!.OnDataChangeBatch += (_, args) => first.TrySetResult(args);
var handle = await driver.SubscribeAsync(["Speed", "Pressure"], TimeSpan.FromMilliseconds(100), CancellationToken.None);
var batch = await first.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
batch.SubscriptionHandle.ShouldBe(handle);
batch.Items.Select(i => i.FullReference).OrderBy(r => r, StringComparer.Ordinal).ShouldBe(["Pressure", "Speed"]);
batch.Items.Single(i => i.FullReference == "Speed").Snapshot.Value.ShouldBe(SqlitePollFixture.PresentValue);
}
// ---- disposal ----
[Fact]