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.
This commit is contained in:
Pavlo Ratushnyi
2026-10-02 08:26:45 +02:00
parent 058e68be7e
commit 2b0163aa80
11 changed files with 698 additions and 10 deletions
+17
View File
@@ -238,6 +238,21 @@ async function load() {
? 'newest ' + obs.length + ' of ' + obsRes.total + ' recorded sources — the rest are older and this table is not the whole window'
: obsRes.total + ' ' + plural(Number(obsRes.total), 'source') + ' the edge has recorded';
const allowed = new Map((rules || []).map((r) => [r.code, r.isAllowed]));
// A failed write is not a stale read: the row never existed, and the
// listing kept answering 200 with the count it already had. Measured on the
// shipped image with writes to source_observations and edge_alerts aborted:
// X-Total-Count stayed at 4 while three new sources were refused, the alert
// table stayed at 1 row through a six-request 5xx storm, and /readyz said
// "ready". Each number is escaped on its own, so the join stays raw.
const writeProblems = [];
if (Number(state.observationWriteFailures) > 0)
writeProblems.push('observations not persisted \u00d7' + esc(state.observationWriteFailures)
+ ' (' + esc(state.observationsLost) + ' rows lost)');
if (Number(state.alertWriteFailures) > 0)
writeProblems.push('alerts not persisted \u00d7' + esc(state.alertWriteFailures)
+ ' (' + esc(state.alertsLost) + ' lost)');
if (Number(state.retentionPruneFailures) > 0)
writeProblems.push('retention not running \u00d7' + esc(state.retentionPruneFailures));
el('summary').innerHTML =
'<span class="pill">mode ' + esc(state.mode) + '</span> ' +
// The age against the bound it is measured against was half the story, and
@@ -256,6 +271,8 @@ async function load() {
+ (Number(state.policyReloadFailures) > 0
? ' \u00b7 policy not re-read from storage \u00d7' + esc(state.policyReloadFailures) : '')
+ '</span> ' +
'<span class="pill' + (writeProblems.length ? ' warn' : '') + '">durable writes '
+ (writeProblems.length ? writeProblems.join(' \u00b7 ') : 'ok') + '</span> ' +
'<span class="pill">tracked ' + esc(state.trackedSources) + '</span> ' +
'<span class="pill">engine bans ' + esc(state.engineBans) + '</span> ' +
'<span class="pill">operator blocks ' + esc(state.operatorBlocks) + '</span> ' +
+27 -1
View File
@@ -403,7 +403,7 @@ internal static class AdminEndpoints
supportsCity = geo.Info?.SupportsCity ?? false
}));
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, StreakTracker tracker) =>
group.MapGet("/state", (EdgeStateStore state, EdgePolicyProvider policyProvider, StreakTracker tracker, DurabilityHealth durability) =>
{
var now = DateTimeOffset.UtcNow;
var allowLive = state.Current.AllowEntries.Count(a => a.IsLive(now));
@@ -443,6 +443,32 @@ internal static class AdminEndpoints
snapshotLastRefreshError = state.LastRefreshError,
policyReloadFailures = policyProvider.ReloadFailures,
policyLastReadAt = policyProvider.LastReloadSuccessAt,
// The read side says whether what this edge is enforcing came from
// storage. The write side says whether what this edge saw ever
// reached storage — and it used to say nothing at all. Measured on
// the shipped image with SQLite triggers aborting every write to
// source_observations and edge_alerts while reads kept answering:
// /admin-api/observations held X-Total-Count: 4 across the break
// while three new sources were being refused, /admin-api/alerts
// held 1 row through a six-request 5xx storm, and the log carried
// "flush failed, 4 entries dropped" plus two "could not persist".
// EntriesLost is cumulative on purpose: a dropped row is not
// recovered by a later successful write.
observationWriteFailures = durability.Get(DurabilityHealth.Observations).Failures,
observationsLost = durability.Get(DurabilityHealth.Observations).EntriesLost,
observationLastWriteError = durability.Get(DurabilityHealth.Observations).LastError,
observationLastWriteAt = durability.Get(DurabilityHealth.Observations).LastSuccessAt,
alertWriteFailures = durability.Get(DurabilityHealth.Alerts).Failures,
alertsLost = durability.Get(DurabilityHealth.Alerts).EntriesLost,
alertLastWriteError = durability.Get(DurabilityHealth.Alerts).LastError,
alertLastWriteAt = durability.Get(DurabilityHealth.Alerts).LastSuccessAt,
// Counted, and deliberately not a /readyz failure: a prune that
// cannot run keeps aggregates past the age they promise to age out
// at, which the operator has to be able to see, but it does not
// change what this edge enforces. See Program.cs.
retentionPruneFailures = durability.Get(DurabilityHealth.Retention).Failures,
retentionLastError = durability.Get(DurabilityHealth.Retention).LastError,
retentionLastPruneAt = durability.Get(DurabilityHealth.Retention).LastSuccessAt,
mode = state.Current.Policy.Mode.ToString()
});
});
+38 -1
View File
@@ -50,6 +50,7 @@ builder.Services.AddSingleton(sp => new EdgeStateStore(
RefreshTtl = EdgeStateStore.ParseRefreshTtl(builder.Configuration["OpenWaf:State:RefreshTtlSeconds"])
});
builder.Services.AddSingleton<BlockStore>();
builder.Services.AddSingleton<DurabilityHealth>();
builder.Services.AddSingleton<AlertWriter>();
// An empty string in appsettings.json is not the same as "unset" to the
// configuration system, and it silently defeats the environment fallback —
@@ -93,7 +94,7 @@ app.MapGet("/healthz", (IGeoIpLookup geo, EdgeStateStore state) => Results.Ok(ne
geoStale = geo.Info is not null && geo.Info.IsStale(TimeSpan.FromDays(90))
}));
app.MapGet("/readyz", async (OpenWafDbContext db, EdgeStateStore state, EdgePolicyProvider policy, CancellationToken ct) =>
app.MapGet("/readyz", async (OpenWafDbContext db, EdgeStateStore state, EdgePolicyProvider policy, DurabilityHealth durability, CancellationToken ct) =>
{
try
{
@@ -127,6 +128,42 @@ app.MapGet("/readyz", async (OpenWafDbContext db, EdgeStateStore state, EdgePoli
+ $"{(DateTimeOffset.UtcNow - state.Current.GeneratedAt).TotalSeconds:0.#} s old against "
+ $"a ttl of {state.RefreshTtl.TotalSeconds:0.#} s",
statusCode: StatusCodes.Status503ServiceUnavailable);
// The read side was made honest first; the write side was still silent.
// Measured on the shipped image with SQLite triggers aborting every
// INSERT/UPDATE on source_observations and edge_alerts while reads kept
// working: /admin-api/observations answered 200 with the same
// X-Total-Count as before the break (4 — three new sources never
// arrived), /admin-api/alerts still showed its one row after a six
// request 5xx storm, and /readyz answered {"status":"ready"} the whole
// time. A failed read keeps a stale value; a failed write loses a row
// that no later request can bring back, and the operator's listings
// quietly stop being the set the edge actually saw.
var observations = durability.Get(DurabilityHealth.Observations);
if (observations.Failures > 0)
return Results.Problem(
detail: $"the streak history is not being persisted: {observations.Failures} consecutive failed "
+ $"writes, {observations.EntriesLost} source rows lost (last error: "
+ $"{observations.LastError}); the observation listings are missing sources this edge "
+ $"saw, and the last write that succeeded was "
+ $"{observations.LastSuccessAt?.ToString("O") ?? "never"}",
statusCode: StatusCodes.Status503ServiceUnavailable);
var alerts = durability.Get(DurabilityHealth.Alerts);
if (alerts.Failures > 0)
return Results.Problem(
detail: $"alerts are not being persisted: {alerts.Failures} consecutive failed writes, "
+ $"{alerts.EntriesLost} alerts lost (last error: {alerts.LastError}); the alerting "
+ $"pillar is not reaching the operator, so a failing upstream is invisible",
statusCode: StatusCodes.Status503ServiceUnavailable);
// Retention is counted and reported on /admin-api/state, and is
// deliberately NOT a readiness failure. A prune that cannot run keeps
// aggregates past the age the README promises they age out at — a
// privacy and disk-space problem, and one an operator has to be told
// about — but it does not change what this edge enforces or what it
// tells the operator about what it enforced. Pulling every edge out of
// rotation because a 30-minute cleanup loop is failing would trade a
// data-retention defect for an outage.
return Results.Ok(new { status = "ready" });
}
catch (Exception ex)
@@ -14,11 +14,13 @@ namespace OpenWaf.Infrastructure.Persistence;
public sealed class AlertWriter
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly DurabilityHealth _health;
private readonly ILogger<AlertWriter> _log;
public AlertWriter(IServiceScopeFactory scopeFactory, ILogger<AlertWriter> log)
public AlertWriter(IServiceScopeFactory scopeFactory, DurabilityHealth health, ILogger<AlertWriter> log)
{
_scopeFactory = scopeFactory;
_health = health;
_log = log;
}
@@ -46,9 +48,18 @@ public sealed class AlertWriter
CreatedAt = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync(ct);
_health.RecordSuccess(DurabilityHealth.Alerts, 1);
}
catch (Exception ex)
{
// Counted, not just logged. The alert table is the whole point of
// this pillar — "an alert nobody reads is a log line" — and an
// alert that never reached the table is worse: measured on the
// shipped image with writes to edge_alerts aborted, a six-request
// 5xx storm left the alert listing at the one row it already had,
// /readyz answered "ready", and the storm was invisible to the
// operator while the upstream was failing.
_health.RecordFailure(DurabilityHealth.Alerts, ex, 1);
_log.LogWarning(ex, "AlertWriter: could not persist a {Kind} alert for {Key}.", kind, sourceKey);
}
}
@@ -0,0 +1,146 @@
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Counts what each background pillar's durable writes actually lost.
///
/// The write side had the same failure posture as the read side — catch
/// everything, log one line, keep the process alive — and the same blindness.
/// Measured on the shipped image (openwaf:ci, the head tree) with SQLite
/// triggers that abort every INSERT and UPDATE on <c>source_observations</c>
/// and <c>edge_alerts</c> while leaving reads alone:
/// before the break GET /admin-api/observations → X-Total-Count: 4
/// GET /admin-api/alerts → 1 row
/// triggers installed, three new sources and six more 502s from one address
/// GET /admin-api/observations → 200, X-Total-Count: 4
/// GET /admin-api/alerts → 200, still 1 row
/// /healthz 200, /readyz 200 {"status":"ready"}
/// /admin-api/state → no write-side field at all
/// the log: "ObservationWriter: flush failed, 4 entries
/// dropped." and two "AlertWriter: could not persist…"
/// triggers dropped X-Total-Count: 9 again
///
/// So the edge lost four sources of streak history and every alert a 5xx storm
/// raised, and the operator's surface — the alert table being "the whole point
/// of the alerting pillar" — reported a quiet, healthy edge. A dropped write is
/// not recoverable by a retry from the UI: the row never existed.
///
/// The counters are per pillar and mean "consecutive failed writes since the
/// last successful one", plus a cumulative count of entries lost, because lost
/// observations and lost alerts stay lost. A counter clears only on a write
/// that actually succeeded: a flush that had nothing to write is not evidence
/// that writing works, and a stand that has never written since a blip has not
/// earned a clean answer.
/// </summary>
public sealed class DurabilityHealth
{
public const string Observations = "observations";
public const string Alerts = "alerts";
public const string Retention = "retention";
/// <summary>
/// One pillar's write state. <paramref name="Failures"/> is consecutive
/// failures since the last success; <paramref name="EntriesLost"/> is
/// cumulative, because a dropped row is not brought back by a later write.
/// </summary>
public sealed record Pillar(
string Name,
int Failures,
long EntriesLost,
long EntriesWritten,
string? LastError,
DateTimeOffset? LastSuccessAt)
{
public bool Failing => Failures > 0;
}
private sealed class State
{
public int Failures;
public long EntriesLost;
public long EntriesWritten;
public string? LastError;
public DateTimeOffset? LastSuccessAt;
public Pillar Snapshot(string name) =>
new(name, Failures, EntriesLost, EntriesWritten, LastError, LastSuccessAt);
}
private readonly Dictionary<string, State> _pillars = new(StringComparer.Ordinal);
private readonly object _gate = new();
/// <summary>
/// Records a write that went through. Only call this after SaveChanges
/// actually returned: a flush that decided nothing was due, or a prune that
/// deleted zero rows, says nothing about whether the write path works.
/// </summary>
public void RecordSuccess(string name, int entries = 0)
{
lock (_gate)
{
var s = For(name);
s.Failures = 0;
s.LastError = null;
s.LastSuccessAt = DateTimeOffset.UtcNow;
if (entries > 0) s.EntriesWritten += entries;
}
}
/// <summary>
/// Records a write that did not. <paramref name="entriesLost"/> is how many
/// rows this attempt was carrying, so the surface can say what was lost
/// rather than only that something failed.
/// </summary>
public void RecordFailure(string name, string error, int entriesLost = 0)
{
lock (_gate)
{
var s = For(name);
s.Failures++;
s.LastError = error;
s.EntriesLost += entriesLost;
}
}
/// <summary>
/// The exception form, because the exception an EF save throws is a wrapper
/// and the operator needs the reason underneath it: measured in a test,
/// <c>DbUpdateException.Message</c> is "An error occurred while saving the
/// entity changes…" while the actual reason — "gate: durable write blocked",
/// "no such table: policy_settings" — sits on the innermost exception. A
/// surface that quotes the wrapper tells the reader nothing to act on.
/// </summary>
public void RecordFailure(string name, Exception ex, int entriesLost = 0) =>
RecordFailure(name, RootCause(ex).Message, entriesLost);
private static Exception RootCause(Exception ex)
{
var current = ex;
while (current.InnerException is not null) current = current.InnerException;
return current;
}
public Pillar Get(string name)
{
lock (_gate) return For(name).Snapshot(name);
}
public IReadOnlyList<Pillar> All()
{
lock (_gate)
{
return _pillars.Select(kv => kv.Value.Snapshot(kv.Key))
.OrderBy(p => p.Name, StringComparer.Ordinal)
.ToList();
}
}
private State For(string name)
{
if (!_pillars.TryGetValue(name, out var s))
{
s = new State();
_pillars[name] = s;
}
return s;
}
}
@@ -19,6 +19,7 @@ public sealed class ObservationWriter : BackgroundService
private readonly IServiceScopeFactory _scopeFactory;
private readonly StreakTracker _tracker;
private readonly EdgePolicyProvider _policy;
private readonly DurabilityHealth _health;
private readonly ILogger<ObservationWriter> _log;
private readonly TimeSpan _flushInterval = TimeSpan.FromSeconds(15);
private readonly Dictionary<string, DateTimeOffset> _lastWrittenAt = new(StringComparer.Ordinal);
@@ -27,11 +28,13 @@ public sealed class ObservationWriter : BackgroundService
IServiceScopeFactory scopeFactory,
StreakTracker tracker,
EdgePolicyProvider policy,
DurabilityHealth health,
ILogger<ObservationWriter> log)
{
_scopeFactory = scopeFactory;
_tracker = tracker;
_policy = policy;
_health = health;
_log = log;
}
@@ -113,12 +116,21 @@ public sealed class ObservationWriter : BackgroundService
}
}
await db.SaveChangesAsync(ct);
_health.RecordSuccess(DurabilityHealth.Observations, due.Count);
return due.Count;
}
catch (Exception ex)
{
// The writer must survive: losing observations is better than
// taking the host down over a transient database error.
// taking the host down over a transient database error. What it may
// not do is survive quietly. Measured on the shipped image with the
// write path aborted by SQLite triggers: three new sources never
// reached source_observations, /admin-api/observations kept
// answering 200 with the same X-Total-Count as before the break,
// /readyz said "ready", and the only trace was this log line. The
// rows are not recoverable later — the streak history the operator
// reasons about is simply missing them.
_health.RecordFailure(DurabilityHealth.Observations, ex, due.Count);
_log.LogWarning(ex, "ObservationWriter: flush failed, {Count} entries dropped.", due.Count);
return 0;
}
@@ -16,13 +16,15 @@ public sealed class RetentionWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly EdgePolicyProvider _policy;
private readonly DurabilityHealth _health;
private readonly ILogger<RetentionWorker> _log;
private readonly TimeSpan _interval = TimeSpan.FromMinutes(30);
public RetentionWorker(IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, ILogger<RetentionWorker> log)
public RetentionWorker(IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, DurabilityHealth health, ILogger<RetentionWorker> log)
{
_scopeFactory = scopeFactory;
_policy = policy;
_health = health;
_log = log;
}
@@ -45,10 +47,25 @@ public sealed class RetentionWorker : BackgroundService
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
await db.Observations.Where(o => o.LastSeenAt < now - policy.ObservationRetention).ExecuteDeleteAsync(ct);
await db.Blocks
.Where(b => b.Source == BlockSource.Engine && b.ExpiresAt != null && b.ExpiresAt < now - policy.BanRetention)
.ExecuteDeleteAsync(ct);
await db.Alerts.Where(a => a.CreatedAt < now - policy.BanRetention).ExecuteDeleteAsync(ct);
try
{
await db.Observations.Where(o => o.LastSeenAt < now - policy.ObservationRetention).ExecuteDeleteAsync(ct);
await db.Blocks
.Where(b => b.Source == BlockSource.Engine && b.ExpiresAt != null && b.ExpiresAt < now - policy.BanRetention)
.ExecuteDeleteAsync(ct);
await db.Alerts.Where(a => a.CreatedAt < now - policy.BanRetention).ExecuteDeleteAsync(ct);
_health.RecordSuccess(DurabilityHealth.Retention);
}
catch (Exception ex)
{
// The retention promise is a privacy promise: aggregates age out on
// purpose. A prune that fails and only logs leaves idle sources in
// the database longer than the README says they are kept, with no
// way for an operator to tell "nothing was due" from "this has not
// run in a week". Counted here and reported on /state; deliberately
// NOT a readiness failure — see Program.cs.
_health.RecordFailure(DurabilityHealth.Retention, ex);
throw;
}
}
}
@@ -0,0 +1,258 @@
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);
}
}
+81
View File
@@ -331,6 +331,87 @@ check 'putting the table back clears the counters and readiness returns' '200' "
check 'and the policy answer says so again' 'X-Policy-Reload-Failures: 0' \
"$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/policy" | grep -i '^x-policy-reload-failures:' | tr -d '\r')"
echo '- a pillar that cannot write says so'
# The read side got its counters first; the write side was still silent, and a
# failed write is worse than a failed read — the row never existed, and no later
# request brings it back. Measured on the shipped image with SQLite triggers
# aborting every INSERT and UPDATE on source_observations and edge_alerts while
# reads stayed 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, GET /admin-api/alerts still showed its one row, /healthz
# and /readyz answered 200, /admin-api/state had no write-side field at all, and
# the log carried "ObservationWriter: flush failed, 4 entries dropped." plus two
# "AlertWriter: could not persist…". A trigger, not a dropped table, on purpose:
# a missing table breaks the listing too, and a broken listing is honest about
# being broken. The lie this asserts is the 200 that stays complete-looking.
TOTAL_BEFORE=$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=1" \
| grep -i '^x-total-count:' | tr -d '\r' | awk '{print $2}')
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
for t in ("source_observations", "edge_alerts"):
for op in ("INSERT", "UPDATE"):
c.execute(f'CREATE TRIGGER "gate_{t}_{op}" BEFORE {op} ON "{t}" '
"BEGIN SELECT RAISE(ABORT, 'gate: durable write blocked'); END")
print("triggers:", [r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")])
PYSQL
for src in 203.0.113.201 203.0.113.202 203.0.113.203; do
for i in 1 2 3; do code -H "$(xff "$src")" "$EDGE/no-write-$i" >/dev/null; done
done
for i in $(seq 1 6); do code -H "$(xff 203.0.113.210)" "$EDGE/boom" >/dev/null; done
OBS_FAILS=0
for _ in $(seq 1 12); do
OBS_FAILS=$(admin "$EDGE/admin-api/state" | jval observationWriteFailures)
[ "${OBS_FAILS:-0}" != "0" ] && break
sleep 3
done
printf ' info observation write failures counted after writes were blocked: %s\n' "${OBS_FAILS:-0}"
check 'the state counts observations this edge could not persist' 'yes' \
"$([ "${OBS_FAILS:-0}" != "0" ] && echo yes || echo no)"
check 'and it says how many rows were lost, not only that something failed' 'yes' \
"$(admin "$EDGE/admin-api/state" | jval observationsLost | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
check 'the alerting pillar counts its lost alerts too' 'yes' \
"$(admin "$EDGE/admin-api/state" | jval alertWriteFailures | awk '{exit ($1+0>=1)?0:1}' && echo yes || echo no)"
TOTAL_AFTER=$(hdr -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/observations?limit=1" \
| grep -i '^x-total-count:' | tr -d '\r' | awk '{print $2}')
printf ' info X-Total-Count across the break: %s -> %s (three new sources saw, none stored)\n' "$TOTAL_BEFORE" "$TOTAL_AFTER"
check 'the listing still answers with the count it had before the break' "$TOTAL_BEFORE" "$TOTAL_AFTER"
check 'readiness names the write pillar that is failing' '503' "$(code "$EDGE/readyz")"
check 'the failure it names is the real reason, not an EF wrapper' 'yes' \
"$(admin "$EDGE/admin-api/state" | jval observationLastWriteError | grep -qi 'durable write blocked' && echo yes || echo no)"
sidecar <<'PYSQL'
import sqlite3
c = sqlite3.connect("/app/data/openwaf.db", isolation_level=None)
for r in list(c.execute("SELECT name FROM sqlite_master WHERE type='trigger'")):
c.execute(f'DROP TRIGGER "{r[0]}"')
print("triggers after cleanup:", c.execute("SELECT count(*) FROM sqlite_master WHERE type='trigger'").fetchone()[0])
PYSQL
for src in 203.0.113.221 203.0.113.222; do
for i in 1 2 3; do code -H "$(xff "$src")" "$EDGE/healed-$i" >/dev/null; done
done
for _ in $(seq 1 12); do
[ "$(admin "$EDGE/admin-api/state" | jval observationWriteFailures)" = "0" ] && break
sleep 3
done
check 'the observation pillar heals on its next successful write' '0' \
"$(admin "$EDGE/admin-api/state" | jval observationWriteFailures)"
# Readiness does not come back yet, and that is the semantics being asserted: a
# counter clears only on a successful write of its own pillar, so the alert
# pillar — which has had nothing to write since the break — keeps the edge
# unready. A gauge that reset on any write would have said "ready" here while
# the alerting pillar had still not produced a single row.
check 'readiness still refuses until the alert pillar writes again' '503' "$(code "$EDGE/readyz")"
# Twelve 502s from a fresh source: the alerting threshold this run set is 3,
# and the escalation alerts at 3 and 6, so this is enough to raise one for sure.
for i in $(seq 1 12); do code -H "$(xff 203.0.113.230)" "$EDGE/boom" >/dev/null; done
for _ in $(seq 1 12); do
[ "$(code "$EDGE/readyz")" = "200" ] && break
sleep 3
done
check 'and readiness returns once every failing pillar has written again' '200' "$(code "$EDGE/readyz")"
check 'the rows the edge sees now land again' 'yes' \
"$([ "$(admin "$EDGE/admin-api/state" | jval alertWriteFailures)" = "0" ] && echo yes || echo no)"
echo
printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]
+72
View File
@@ -496,6 +496,78 @@ const rgb = (s) => s.match(/\d+/g).slice(0, 3).map(Number);
await broken.close();
}
// The write half of the same contract. A failed write loses a row for good —
// measured on the shipped image with SQLite triggers aborting every INSERT
// and UPDATE on source_observations and edge_alerts: the observation listing
// kept answering with the X-Total-Count it had before the break while three
// new sources were being refused, the alert table kept its one row through a
// six-request 5xx storm, and /readyz said "ready". scripts/compose-smoke.sh
// proves that end to end against the image; what is proven here is that the
// page renders the fields it now has to render, and that a write failure is
// shown as a write failure rather than folded into the snapshot pill.
{
const lost = await browser.newPage();
const lostProblems = [];
lost.on('pageerror', (e) => lostProblems.push('pageerror: ' + e.message));
await lost.route('**/admin-api/state', (route) => route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
snapshotAgeSeconds: 0.4, snapshotTtlSeconds: 30, snapshotStale: false,
snapshotRefreshFailures: 0, snapshotLastRefreshError: null,
policyReloadFailures: 0, policyLastReadAt: '2026-10-02T05:12:07.0000000+00:00',
observationWriteFailures: 3, observationsLost: 4,
observationLastWriteError: 'gate: durable write blocked',
observationLastWriteAt: '2026-10-02T05:11:52.0000000+00:00',
alertWriteFailures: 2, alertsLost: 2,
alertLastWriteError: 'gate: durable write blocked',
retentionPruneFailures: 1, retentionLastError: 'gate: durable write blocked',
retentionLastPruneAt: '2026-10-02T04:41:19.0000000+00:00',
trackedSources: 4, operatorBlocks: 2, engineBans: 0,
allowEntries: 0, allowEntriesExpired: 0, mode: 'Enforce'
})
}));
await lost.goto(`${EDGE}/admin`, { waitUntil: 'domcontentloaded' });
await lost.fill('#token', TOKEN);
await lost.click('#save');
await lost.waitForFunction(
() => /durable writes/.test([...document.querySelectorAll('#summary .pill')]
.map((p) => p.textContent).join(' | ')),
null, { timeout: 15000 }).catch(() => {});
const writePill = await lost.evaluate(() => {
const pill = [...document.querySelectorAll('#summary .pill')].find((p) => /durable writes/.test(p.textContent));
return pill ? { text: pill.textContent.replace(/\s+/g, ' ').trim(), cls: pill.className } : null;
});
const snapshotPill = await lost.evaluate(() => {
const pill = [...document.querySelectorAll('#summary .pill')].find((p) => /snapshot/.test(p.textContent));
return pill ? { text: pill.textContent.replace(/\s+/g, ' ').trim(), cls: pill.className } : null;
});
check('a write that never reached storage is marked on the page, with what it cost',
!!writePill && /observations not persisted/.test(writePill.text)
&& /4 rows lost/.test(writePill.text) && /alerts not persisted/.test(writePill.text)
&& /warn/.test(writePill.cls),
JSON.stringify(writePill));
check('and it is shown as a write failure, not folded into the snapshot pill',
!!snapshotPill && !/warn/.test(snapshotPill.cls) && !/not persisted/.test(snapshotPill.text)
&& /retention not running/.test(writePill.text || ''),
JSON.stringify({ write: writePill, snapshot: snapshotPill }));
check('the page threw no javascript on that answer', lostProblems.length === 0, lostProblems.join(' | '));
await lost.close();
}
// The clean case, on the real stand rather than a rendered contract: the pill
// has to say it checked, because a pill that only appears when something is
// wrong is how "no alerts" and "alerts are not being written" look identical.
{
const cleanPill = await page.evaluate(() => {
const pill = [...document.querySelectorAll('#summary .pill')].find((p) => /durable writes/.test(p.textContent));
return pill ? { text: pill.textContent.replace(/\s+/g, ' ').trim(), cls: pill.className } : null;
});
check('with the write path healthy the page says so rather than staying quiet',
!!cleanPill && /durable writes ok/.test(cleanPill.text) && !/warn/.test(cleanPill.cls),
JSON.stringify(cleanPill));
}
// A phone in dark mode is the case an operator actually reaches the console
// from — the address that got them blocked is the one they are typing about.
// Both halves of this used to be broken and measured: the page overflowed a
+11
View File
@@ -142,6 +142,17 @@ check 'the policy answer carries its provenance header' 0 \
"$(curl -s -D- -o /dev/null -H "X-Admin-Token: $TOKEN" \
"http://127.0.0.1:$EDGE_PORT/admin-api/policy" | tr -d '\r' \
| sed -n 's/^[Xx]-[Pp]olicy-[Rr]eload-[Ff]ailures: //p')"
# The write side of the same contract. A failed write is worse than a failed
# read — the row never existed and no later request brings it back — so the
# counters exist even in a clean run, where they read 0 0 0. A surface that
# answers "0" for a field it never publishes is indistinguishable from one that
# publishes it and means it, which is why the keys are asserted too.
check 'the state counts writes it could not persist, and there are none' '0 0 0' \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["observationWriteFailures"], d["alertWriteFailures"], d["retentionPruneFailures"])')"
check 'and it carries what was lost and when a write last landed' True \
"$(printf '%s' "$STATE_JSON" | python3 -c 'import sys,json;d=json.load(sys.stdin);print(all(k in d for k in ("observationsLost","alertsLost","observationLastWriteAt","alertLastWriteAt","retentionLastPruneAt")))')"
check 'readiness is ready while the write path is healthy' 200 \
"$(code "http://127.0.0.1:$EDGE_PORT/readyz")"
check 'switching the engine off is accepted' Off \
"$(curl -s -X PUT -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' --data-binary "$POLICY_OFF_JSON" \
"http://127.0.0.1:$EDGE_PORT/admin-api/policy" | python3 -c 'import sys,json;print(json.load(sys.stdin)["mode"])')"