Files
openwaf/dotnet/OpenWaf.Tests.Integration/WriteFailureVisibilityTests.cs
T
Pavlo Ratushnyi 2b0163aa80 A pillar that could not write kept answering with the count it had before the break
The read side got its counters last cycle; the write side was still catching
everything, logging one line and keeping the process alive. A failed write is
worse than a failed read - the row never existed and no later request brings it
back - and the surface hid it better. Measured on the shipped image with SQLite
triggers aborting every INSERT/UPDATE on source_observations and edge_alerts
while reads kept working: three new sources refused and a six-request 5xx storm
later, GET /admin-api/observations answered 200 with the same X-Total-Count it
had before the break (46), GET /admin-api/alerts still showed its one row,
/healthz and /readyz were 200, /admin-api/state had no write-side field at all,
and the log carried "flush failed, 4 entries dropped" plus two "could not
persist".

DurabilityHealth counts each writer separately; /state reports
observationWriteFailures/observationsLost/observationLastWriteError,
alertWriteFailures/alertsLost and retentionPruneFailures; /readyz answers 503
naming the pillar, the rows lost and the innermost error rather than EF's
wrapper. A counter clears only on a successful write of its own pillar, and
retention is reported without being a readiness failure - stated in code, with
the reason.

Teeth: WriteFailureVisibilityTests (5) - 5 failed / 0 passed before the fix.
Gates: compose-smoke 53 -> 63 (blocks writes with triggers, asserts the
unchanged X-Total-Count as the lie, and heals per pillar), smoke.sh 25 -> 28,
console-check 53 -> 57.
2026-10-02 08:26:45 +02:00

259 lines
12 KiB
C#

using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Tests.Integration;
/// <summary>
/// The write side of the edge catches everything it throws, logs one line and
/// keeps the process alive. That posture is right — a database restart must not
/// take the gate down — but the write side paid for it with the same blindness
/// the read side had before the pillar-health work: a failed write loses a row
/// permanently, and no surface said anything.
///
/// Measured on the shipped image (openwaf:ci, the head tree), one stand with a
/// real upstream, breaking only the write path with SQLite triggers so the
/// reads stayed honest:
/// before the break GET /admin-api/observations → X-Total-Count: 4
/// GET /admin-api/alerts → 1 row
/// CREATE TRIGGER … BEFORE INSERT/UPDATE ON source_observations, edge_alerts
/// BEGIN SELECT RAISE(ABORT,'gate'); END
/// three new sources refused, six more 502s from one address
/// GET /admin-api/observations → 200, X-Total-Count: 4
/// GET /admin-api/alerts → 200, 1 row
/// /healthz 200, /readyz 200 {"status":"ready"}
/// /admin-api/state → no write-side field at all
/// log: "ObservationWriter: flush failed, 4 entries
/// dropped." + two "AlertWriter: could not persist…"
/// DROP TRIGGER X-Total-Count: 9
///
/// The listings were not stale. They were complete about a set that had quietly
/// stopped being the set the edge saw, and the alert table — the whole point of
/// the alerting pillar — showed nothing about a 5xx storm that was happening.
/// </summary>
public sealed class WriteFailureVisibilityTests
{
private static async Task RunSql(EdgeFixture f, string sql)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
await db.Database.ExecuteSqlRawAsync(sql);
}
/// <summary>
/// Aborts writes without touching reads, which is the point: a dropped
/// table would break the listing too and the listing would then be honest
/// about being broken. A trigger leaves the listing answering 200.
/// </summary>
private static async Task BlockWrites(EdgeFixture f, string table, string operation = "INSERT|UPDATE")
{
foreach (var op in operation.Split('|'))
await RunSql(f, $"""CREATE TRIGGER "gate_{table}_{op}" BEFORE {op} ON "{table}" BEGIN SELECT RAISE(ABORT, 'gate: durable write blocked'); END""");
}
private static async Task UnblockWrites(EdgeFixture f)
{
using var scope = f.Factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var names = await db.Database
.SqlQueryRaw<string>(""""SELECT name FROM sqlite_master WHERE type='trigger'"""")
.ToListAsync();
foreach (var name in names)
await RunSql(f, $"""DROP TRIGGER IF EXISTS "{name}" """);
}
// The fixture's own flush helper discards the count, and the count is the
// assertion here: 0 means the flush carried nothing into storage.
private static Task<int> Flush(EdgeFixture f) =>
f.Service<ObservationWriter>().FlushAsync(CancellationToken.None);
private static async Task<JsonElement> StateAsync(EdgeFixture f)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/state");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
response.EnsureSuccessStatusCode();
return JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
}
private static async Task<(HttpStatusCode Status, string Text)> ReadyzAsync(EdgeFixture f)
{
using var response = await f.Client.GetAsync("/readyz");
return (response.StatusCode, await response.Content.ReadAsStringAsync());
}
private static async Task<(int Total, bool Truncated)> ObservationsTotalAsync(EdgeFixture f)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/observations?limit=1");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
response.EnsureSuccessStatusCode();
string Header(string name)
=> response.Headers.TryGetValues(name, out var a) ? string.Join(",", a) : "";
return (int.Parse(Header("X-Total-Count")), Header("X-Truncated") == "true");
}
[Fact]
public async Task A_flush_that_cannot_write_is_counted_and_readiness_names_the_pillar()
{
await using var f = new EdgeFixture();
Assert.Equal(HttpStatusCode.OK, (await ReadyzAsync(f)).Status);
for (var i = 0; i < 3; i++) await f.SendAsync(f.Client, $"/nope-{i}", "203.0.113.11");
await BlockWrites(f, "source_observations");
Assert.Equal(0, await Flush(f));
var state = await StateAsync(f);
Assert.True(state.GetProperty("observationWriteFailures").GetInt32() >= 1,
$"/state did not count the failed flush: {state}");
Assert.True(state.GetProperty("observationsLost").GetInt64() >= 1,
$"/state did not say how many rows were lost: {state}");
Assert.Contains("gate: durable write blocked", state.GetProperty("observationLastWriteError").GetString());
var (status, text) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.ServiceUnavailable, status);
Assert.Contains("streak history is not being persisted", text);
Assert.Contains("rows lost", text);
}
[Fact]
public async Task The_listing_keeps_answering_its_old_count_while_the_edge_is_still_seeing_sources()
{
await using var f = new EdgeFixture();
// One honest write first, so the number in the header is a real one.
await f.SendAsync(f.Client, "/one", "203.0.113.12");
await f.FlushObservationsAsync();
var (before, _) = await ObservationsTotalAsync(f);
Assert.Equal(1, before);
await BlockWrites(f, "source_observations");
for (var i = 0; i < 3; i++) await f.SendAsync(f.Client, $"/two-{i}", "203.0.113.13");
for (var i = 0; i < 3; i++) await f.SendAsync(f.Client, $"/three-{i}", "203.0.113.14");
Assert.Equal(0, await Flush(f));
var (after, truncated) = await ObservationsTotalAsync(f);
// This is the lie, asserted directly: the answer is a 200 with a total
// that no longer describes what this edge saw, and it says nothing about
// the difference.
Assert.Equal(before, after);
Assert.False(truncated);
// The counters are what makes the 200 interpretable at all.
var state = await StateAsync(f);
Assert.True(state.GetProperty("observationWriteFailures").GetInt32() >= 1);
Assert.True(state.GetProperty("observationsLost").GetInt64() >= 2,
$"two sources were dropped and /state said {state.GetProperty("observationsLost")}");
}
[Fact]
public async Task An_alert_that_never_reached_the_table_is_counted_and_readiness_names_it()
{
await using var f = new EdgeFixture();
await BlockWrites(f, "edge_alerts");
// Raised through the writer's own API, which is what the guard calls
// when a server-error streak crosses the threshold.
await f.Service<AlertWriter>().RaiseAsync(
"server_error_streak", "203.0.113.21", 3, StatusCodes.Status502BadGateway, "/boom", "gate test");
var state = await StateAsync(f);
Assert.True(state.GetProperty("alertWriteFailures").GetInt32() >= 1,
$"/state did not count the lost alert: {state}");
Assert.True(state.GetProperty("alertsLost").GetInt64() >= 1, $"/state: {state}");
var (status, text) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.ServiceUnavailable, status);
Assert.Contains("alerts are not being persisted", text);
// And the alert listing itself still looks fine — that is the whole
// reason the counter has to exist.
using var request = new HttpRequestMessage(HttpMethod.Get, "/admin-api/alerts?limit=500");
request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken);
using var response = await f.Client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(0, JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.GetArrayLength());
}
[Fact]
public async Task A_write_that_succeeds_clears_the_counters_and_readiness_comes_back()
{
await using var f = new EdgeFixture();
await f.SendAsync(f.Client, "/heal", "203.0.113.31");
await BlockWrites(f, "source_observations");
Assert.Equal(0, await Flush(f));
Assert.Equal(HttpStatusCode.ServiceUnavailable, (await ReadyzAsync(f)).Status);
await UnblockWrites(f);
// A fresh source, not the same one: the writer stamps its
// last-written-at before it attempts the write, so the row it lost is
// not retried until that source is due again a write interval later
// (ObservationWriteInterval, 30 s by default). That is the write
// amplification bound doing its job, and it is why EntriesLost is
// cumulative rather than a gauge.
await f.SendAsync(f.Client, "/healed", "203.0.113.32");
Assert.True(await Flush(f) >= 1, "the recovery flush wrote nothing");
var state = await StateAsync(f);
Assert.Equal(0, state.GetProperty("observationWriteFailures").GetInt32());
Assert.True(state.GetProperty("observationsLost").GetInt64() >= 1,
"entries lost is cumulative: a later success does not bring the row back");
Assert.Equal(JsonValueKind.Null, state.GetProperty("observationLastWriteError").ValueKind);
var (status, text) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.OK, status);
Assert.Contains("ready", text);
var (total, _) = await ObservationsTotalAsync(f);
Assert.Equal(1, total);
}
[Fact]
public async Task A_prune_that_cannot_run_is_counted_and_deliberately_does_not_make_the_edge_unready()
{
await using var f = new EdgeFixture();
// A row the prune genuinely wants to delete. Without one, the prune
// deletes zero rows, the DELETE trigger never fires and the test passes
// for the wrong reason — which is exactly the shape of assertion this
// project keeps having to rewrite.
using (var scope = f.Factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var aged = DateTimeOffset.UtcNow.AddDays(-400);
db.Observations.Add(new SourceObservation
{
SourceKey = "203.0.113.98",
FirstSeenAt = aged,
LastSeenAt = aged,
MaxConsecutiveRefusals = 1,
TotalRefusals = 1,
TotalServerErrorStreak = 0
});
await db.SaveChangesAsync();
}
// Retention deletes; blocking DELETE breaks the prune and nothing else.
await BlockWrites(f, "source_observations", "DELETE");
await Assert.ThrowsAnyAsync<Exception>(
async () => await f.Service<RetentionWorker>().PruneAsync(CancellationToken.None));
var state = await StateAsync(f);
Assert.True(state.GetProperty("retentionPruneFailures").GetInt32() >= 1, $"/state: {state}");
Assert.Contains("gate: durable write blocked", state.GetProperty("retentionLastError").GetString());
// The other pillars are untouched, so the boundary is testable rather
// than asserted in a comment: a retention failure is reported, not
// acted on by pulling the edge out of rotation.
Assert.Equal(0, state.GetProperty("observationWriteFailures").GetInt32());
Assert.Equal(0, state.GetProperty("alertWriteFailures").GetInt32());
var (status, _) = await ReadyzAsync(f);
Assert.Equal(HttpStatusCode.OK, status);
}
}