fix(sql): row-cap key-value and where-pair plans with a TOP/LIMIT N+1 dialect seam (R06:S-1)

Key-value and where-pair plans had no row limit, so a selector pointed at a history
or events table materialised every matching row on every poll. ISqlDialect gains
RowLimitPrefix/RowLimitSuffix(n) (SQL Server TOP (n), Postgres LIMIT n, Oracle FETCH
FIRST n ROWS ONLY); plans carry a RowCap (distinct keys, or 1) and ask for RowCap+1
rows; the reader also stops client-side at RowCap+1. Getting the extra row proves the
selector ambiguous: the group publishes BadConfigurationError with a rate-limited
warning. The reader reports those answered refusals so the driver counts them as
answer evidence, and any refusal-only poll now restores Healthy after a comms fault.

Refs #744
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
Joseph Doherty
2026-10-22 15:57:13 -04:00
parent 7f5d959fb9
commit 0a5aa9fc43
21 changed files with 420 additions and 54 deletions
@@ -187,7 +187,7 @@ public sealed class SqlPollReaderTests
}
[Fact]
public async Task ReadAsync_wideRow_whenTheSelectorMatchesManyRows_warnsInsteadOfSilentlyPickingOne()
public async Task ReadAsync_wideRow_whenTheSelectorMatchesManyRows_publishesAConfigurationError_andWarns()
{
using var fixture = new SqlitePollFixture();
// A second row for the SAME station. The where-pair form emits no ORDER BY and no row limit, so
@@ -201,8 +201,11 @@ public sealed class SqlPollReaderTests
var snapshots = await reader.ReadAsync(["Oven"], CancellationToken.None);
// Still a value — the reader degrades to "last row wins", exactly as the key-value model does.
snapshots[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
// R06:S-1: the where-pair plan now asks for TWO rows (one more than it can use). Getting the second is
// proof the selector is ambiguous, so the group publishes a configuration error rather than a
// storage-order-dependent "last row" value — and nothing past that second row is ever read.
snapshots[0].StatusCode.ShouldBe(SqlStatusCodes.BadConfigurationError);
snapshots[0].Value.ShouldBeNull();
var warning = logger.Entries.ShouldHaveSingleItem();
warning.Level.ShouldBe(LogLevel.Warning);
@@ -277,13 +280,93 @@ public sealed class SqlPollReaderTests
$"INSERT INTO {SqlitePollFixture.KeyValueTable} " +
$"({SqlitePollFixture.KeyColumn}, {SqlitePollFixture.ValueColumn}, {SqlitePollFixture.TimestampColumn}) " +
$"VALUES ('{SqlitePollFixture.PresentKey}', 99.0, '2026-07-24T10:00:09Z')");
var reader = Reader(fixture, KvTag("Speed", SqlitePollFixture.PresentKey));
// Two keys, one absent: the duplicate fits inside the row cap (2), so it is not provably a history
// table — the last-row-wins rule still applies there (the cap test below covers the other side).
var reader = Reader(fixture,
KvTag("Speed", SqlitePollFixture.PresentKey), KvTag("Gone", SqlitePollFixture.AbsentKey));
var snapshots = await reader.ReadAsync(["Speed"], CancellationToken.None);
var snapshots = await reader.ReadAsync(["Speed", "Gone"], CancellationToken.None);
// Design §3.6: the contract is one row per key; when a source breaks it the reader is at least
// deterministic — last occurrence in reader order — rather than silently arbitrary.
snapshots[0].Value.ShouldBe(99.0);
snapshots[1].StatusCode.ShouldBe(SqlStatusCodes.BadNoData);
}
/// <summary>
/// <b>R06:S-1.</b> A key-value tag pointed at a history table (many rows per key) used to pull every
/// matching row into memory on every poll. The plan now asks for one row more than it has keys; a full
/// result set proves the selector is ambiguous, so every member publishes a configuration error and a
/// (rate-limited) warning names the table. The positive control: the same tag against a clean source
/// reads Good.
/// </summary>
[Fact]
public async Task ReadAsync_keyValueRowCapExceeded_publishesAConfigurationError_forEveryMember()
{
using var fixture = new SqlitePollFixture();
var logger = new RecordingLogger();
var clean = Reader(fixture, logger, KvTag("Speed", SqlitePollFixture.PresentKey));
(await clean.ReadAsync(["Speed"], CancellationToken.None))[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
logger.Entries.ShouldBeEmpty();
for (var i = 0; i < 50; i++)
{
fixture.Execute(string.Create(CultureInfo.InvariantCulture,
$"INSERT INTO {SqlitePollFixture.KeyValueTable} " +
$"({SqlitePollFixture.KeyColumn}, {SqlitePollFixture.ValueColumn}, {SqlitePollFixture.TimestampColumn}) " +
$"VALUES ('{SqlitePollFixture.PresentKey}', {i}, '2026-07-24T11:00:00Z')"));
}
var reader = Reader(fixture, logger, KvTag("Speed", SqlitePollFixture.PresentKey), KvTag("Speed2", SqlitePollFixture.PresentKey));
var snapshots = await reader.ReadAsync(["Speed", "Speed2"], CancellationToken.None);
snapshots.ShouldAllBe(x => x.StatusCode == SqlStatusCodes.BadConfigurationError);
var warning = logger.Entries.ShouldHaveSingleItem();
warning.Level.ShouldBe(LogLevel.Warning);
warning.Message.ShouldContain(SqlitePollFixture.KeyValueTable);
}
/// <summary>
/// The client-side half of the cap: a dialect whose limit fragments are empty (a provider that cannot
/// spell one) must still stop reading at cap + 1 and report the same configuration error.
/// </summary>
[Fact]
public async Task ReadAsync_aDialectThatEmitsNoLimit_isStillCappedClientSide()
{
using var fixture = new SqlitePollFixture();
AddSecondRowForPresentStation(fixture);
var reader = new SqlPollReader(fixture.Factory, fixture.ConnectionString, new NoLimitDialect(),
commandTimeout: CommandTimeout, operationTimeout: OperationTimeout,
maxConcurrentGroups: 4, nullIsBad: false,
resolve: Resolver(WideTag("Oven", "oven_temp", selectorValue: SqlitePollFixture.PresentStation)));
var snapshots = await reader.ReadAsync(["Oven"], CancellationToken.None);
snapshots[0].StatusCode.ShouldBe(SqlStatusCodes.BadConfigurationError);
}
/// <summary>SQLite with the row-limit fragments blanked — the "provider cannot spell a limit" shape.</summary>
private sealed class NoLimitDialect : ISqlDialect
{
private readonly SqliteDialect _inner = new();
public SqlProvider Provider => _inner.Provider;
public System.Data.Common.DbProviderFactory Factory => _inner.Factory;
public int MaxBindParameters => _inner.MaxBindParameters;
public string LivenessSql => _inner.LivenessSql;
public string SingleRowLimitPrefix => _inner.SingleRowLimitPrefix;
public string SingleRowLimitSuffix => _inner.SingleRowLimitSuffix;
public string RowLimitPrefix(int rows) => string.Empty;
public string RowLimitSuffix(int rows) => string.Empty;
public string ListSchemasSql => _inner.ListSchemasSql;
public string DefaultSchemaSql => _inner.DefaultSchemaSql;
public string ListTablesSql => _inner.ListTablesSql;
public string ListColumnsSql => _inner.ListColumnsSql;
public string QuoteIdentifier(string ident) => _inner.QuoteIdentifier(ident);
public string ParameterMarker(string baseName) => _inner.ParameterMarker(baseName);
public string ParameterBindName(string baseName) => _inner.ParameterBindName(baseName);
public void ConfigureCommand(System.Data.Common.DbCommand command) => _inner.ConfigureCommand(command);
public void ConfigureParameter(System.Data.Common.DbParameter parameter, object? value) => ((ISqlDialect)_inner).ConfigureParameter(parameter, value);
public DriverDataType MapColumnType(string sqlDataType) => _inner.MapColumnType(sqlDataType);
}
// ---- the frozen-peer contract ----