Files
Pavlo Ratushnyi 7c5e1ef230
ci / lint the workflow and the shell (push) Successful in 10s
geo-freshness / the pinned geo database vs the vendor (push) Successful in 5s
ci / the operator page in a real browser (push) Successful in 3m42s
ci / build, test, smoke (push) Failing after 2m6s
ci / build the image and smoke it (push) Successful in 5m7s
the edge gains a schema step a compiled binary can run, and NativeAOT gets a measured verdict
The Dockerfile said "why not NativeAOT" on the authority of another repo's
Dockerfile. That claim is now this repo's own, and it is a measurement.

What was built to find out:

* Persistence/Schema/schema.sqlite.sql — the model's DDL, generated by
  `dotnet ef dbcontext script`, embedded in the binary and read by
  Persistence/EmbeddedSchema.cs. A NativeAOT build cannot ask EF to build a
  model at run time, and EnsureCreated and GenerateCreateScript both go through
  the design-time model, so the schema step has nowhere to get its SQL from.
  OPENWAF_SCHEMA=script is the fourth strategy: same provider-shaped
  statements, produced at build time instead of at start-up. The schema-script
  CI step regenerates the file and fails the run when the committed copy is not
  what the current model produces (5652 bytes today).
* SchemaUpgrader.ModelTables asks the runtime model, per entity type. The
  design-time one is refused outright under NativeAOT, and GetRelationalModel()
  on the runtime model of a compiled model throws
  "The annotation 'Relational:DefaultMappings' cannot be added because an
  annotation with the same name already exists on the object EntityType:
  CountryRule" — building a compiled model's relational model a second time
  collides with itself.
* The persistence layer's queries were rewritten into the shape EF's query
  precompiler accepts: captured parameters copied to locals, conditional
  IQueryable composition written as literal chains, aggregates that take a
  predicate given their own Where. 40 of them were refused before that.
* dotnet-ef and EF Core moved 10.0.0 -> 10.0.12, because 10.0.0's design package
  ships no build host and `--precompile-queries` cannot load a project without it.

What the measurement says, from scripts/aot-probe.sh on osx-arm64: the AOT build
compiles (48,797,072-byte native binary, 10 IL warnings, 0 errors), starts, and
creates all 12 tables from the DDL it carries. Then it never serves. EF refuses
every query at run time ("Query wasn't precompiled and dynamic code isn't
supported with NativeAOT"), and the precompiler that would fix that is not
usable on this model: after all 40 refusals were cleared it emitted 14
declarations with dots in the identifier
(`var openWaf.Domain.Security.BlockEntryPrimaryKeyProperties = …`) — 28 CS1002
and CS1003 errors, one per entity materialisation — with or without --nativeaot.
The refusals themselves trace to dotnet/efcore#35887, #38030 and #35494; the fix
landed in the 12.0-preview1 milestone, not in any 10.0.x.

Two things were not kept, and why:

* The atomic alert-queue claim and the claim release were rewritten as raw SQL
  to dodge the precompiler's ExecuteUpdate failures. Reverted: with the
  statement written as SQL, DateTimeOffset reaches sqlite as a provider
  parameter instead of through the property's own mapping, the reclaim
  comparison stops matching, and
  AlertPushQueueTests.A_delivery_owed_by_a_process_that_stopped_is_owed_by_the_next_one
  fails with the row still owed. A correctness risk here buys nothing when the
  AOT build is blocked further along anyway.
* --nativeaot on the compiled model: its unsafe accessors do not compile
  (CS1503 in BlockEntryEntityType.cs). The plain compiled model is what is
  committed.

The compose gate's two escalation-count scenes also stopped being a coin toss.
They slept a fixed 2 s and then counted; on a loaded host the same tree read 3
rows once and 1 the next, and the assertion is about a settled number either
way. They now wait for three equal reads, bounded. The scene count is unchanged
at 368.

Gates at this commit: build 0 warnings / 0 errors, unit 378/378, integration
405/405, schema-script ok, smoke 256/0, compose-smoke 368/0, README counts
match (256, 368), lint clean (actionlint 1.7.12, shellcheck 0.11.0).

Not verified: the AOT image on linux-x64 — the probe ran on osx-arm64, and the
ILC failure mode that ends the attempt is a codegen bug in EF, not a
platform-specific one, but that is an inference rather than a measurement.
2026-10-06 05:20:28 +02:00

278 lines
13 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// The streak map moved into the database, so N edges mature one streak instead
/// of N streaks (OPEN-52).
///
/// The rules are not reimplemented here: this calls <see cref="StreakRules.Apply"/>
/// against a row, exactly as the in-process <see cref="StreakTracker"/> calls it
/// against a <see cref="StreakState"/>. A second copy of those rules would put
/// the drift back where this class exists to remove it.
///
/// What it costs, stated: one database round trip per observed response, on a
/// request path whose measured p95 is ~3 ms, and one optimistic-concurrency
/// retry when two edges touch the same source at the same moment. That is the
/// price of a threshold that means the same thing behind a load balancer; the
/// default remains the in-process map, and the deployment decides.
/// </summary>
public sealed class SharedStreakTracker : IStreakTracker
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<SharedStreakTracker> _log;
/// <summary>Two edges racing on one row is the normal case here, not a
/// corner. The loser re-reads the winner's row and re-applies the rules, so
/// both refusals are counted; the retry bound is there so a pathological
/// contention loop cannot pin a request thread forever.</summary>
private const int ContentionRetries = 3;
public SharedStreakTracker(IServiceScopeFactory scopeFactory, ILogger<SharedStreakTracker> log)
{
_scopeFactory = scopeFactory;
_log = log;
}
/// <summary>Sync on purpose: <see cref="IStreakTracker.Observe"/> sits on
/// the request path between the upstream's answer and the operator's view of
/// it, and EF Core's synchronous API is real. Making this async would change
/// the interface for every caller to wrap a completed value.</summary>
public StreakOutcome Observe(
string sourceKey, int statusCode, ResponseClass responseClass,
EdgePolicy policy, DateTimeOffset now, RequestEvidence? evidence = null)
{
if (string.IsNullOrEmpty(sourceKey)) return StreakOutcome.None;
// Copied to a local on purpose. EF's query precompiler (the only way a
// NativeAOT build can run a LINQ query at all) fails on a captured method
// parameter — "IdentifierName of type ParameterSymbol: sourceKey" — while
// a local of the same value precompiles. dotnet/efcore#35887, fixed only
// in the 12.0-preview1 line.
var key = sourceKey;
for (var attempt = 0; ; attempt++)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
try
{
var row = db.Streaks.FirstOrDefault(t => t.SourceKey == key);
var isNew = row is null;
row ??= new SourceStreak { SourceKey = sourceKey, LastSeenAt = now };
var state = Read(row);
var outcome = StreakRules.Apply(state, statusCode, responseClass, policy, now, evidence);
Write(row, state);
row.Version++;
if (isNew) db.Streaks.Add(row);
db.SaveChanges();
return outcome;
}
catch (DbUpdateConcurrencyException) when (attempt < ContentionRetries)
{
// Another edge wrote this source between the read and the write.
// Counting on top of its row is the whole point: dropping this
// refusal is how the threshold goes wrong again.
_log.LogDebug("SharedStreaks: contention on {Key}; retrying against the winner's row.", sourceKey);
}
catch (DbUpdateException) when (attempt < ContentionRetries)
{
// Another edge inserted the same key between the read and the
// insert. The retry finds that row and counts on it.
_log.LogDebug("SharedStreaks: insert raced for {Key}; retrying.", sourceKey);
}
}
}
public IReadOnlyList<StreakSnapshot> Snapshot(DateTimeOffset now, EdgePolicy policy)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
EvictIdle(now, policy);
return db.Streaks.AsNoTracking()
.Where(t => t.TotalRefusals > 0 || t.MaxConsecutiveServerErrors > 0)
.ToList()
.Select(t => new StreakSnapshot(
t.SourceKey, t.MaxConsecutiveRefusals, t.TotalRefusals, t.MaxConsecutiveServerErrors,
t.LastStatusCode, t.LastPath, t.LastUserAgent, t.LastCountryCode, t.LastCity, t.LastRegion,
t.LastSeenAt))
.ToList();
}
public StreakSnapshot? Peek(string sourceKey)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var key = sourceKey;
var t = db.Streaks.AsNoTracking().FirstOrDefault(x => x.SourceKey == key);
return t is null ? null : new StreakSnapshot(
t.SourceKey, t.MaxConsecutiveRefusals, t.TotalRefusals, t.MaxConsecutiveServerErrors,
t.LastStatusCode, t.LastPath, t.LastUserAgent, t.LastCountryCode, t.LastCity, t.LastRegion,
t.LastSeenAt);
}
public IReadOnlyList<LiveStreak> LiveStreaks(DateTimeOffset now, EdgePolicy policy, int limit)
=> LiveStreaks(now, policy, limit, 0, out _);
public IReadOnlyList<LiveStreak> LiveStreaks(
DateTimeOffset now, EdgePolicy policy, int limit, int offset, out int standingTotal)
=> LiveStreaks(now, policy, limit, offset, null, out standingTotal);
/// <summary>Same contract as the in-process listing: only sources with
/// something standing, worst first, and <c>standingTotal</c> counted over the
/// filtered set so a filtered page cannot claim a cut that did not happen.</summary>
public IReadOnlyList<LiveStreak> LiveStreaks(
DateTimeOffset now, EdgePolicy policy, int limit, int offset, string? sourceKey,
out int standingTotal)
{
var take = Math.Max(1, limit);
var skip = Math.Max(0, offset);
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
EvictIdle(now, policy);
// Two literal chains rather than one IQueryable assembled by an if. The
// precompiler reads the query from the source text, so a query that is
// composed across statements is "dynamic" to it however it is written at
// run time — and this listing has to work in a NativeAOT build too.
var key = sourceKey;
if (key is null)
{
standingTotal = db.Streaks.AsNoTracking()
.Where(t => t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0)
.Count();
return db.Streaks.AsNoTracking()
.Where(t => t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0)
.OrderByDescending(t => t.ConsecutiveRefusals)
.ThenByDescending(t => t.ConsecutiveServerErrors)
.ThenByDescending(t => t.LastSeenAt)
.Skip(skip).Take(take)
.ToList()
.Select(t => new LiveStreak(
t.SourceKey, t.ConsecutiveRefusals, t.ConsecutiveServerErrors,
t.LastStatusCode, t.LastPath, t.LastCountryCode, t.LastSeenAt))
.ToList();
}
standingTotal = db.Streaks.AsNoTracking()
.Where(t => (t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0) && t.SourceKey == key)
.Count();
return db.Streaks.AsNoTracking()
.Where(t => (t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0) && t.SourceKey == key)
.OrderByDescending(t => t.ConsecutiveRefusals)
.ThenByDescending(t => t.ConsecutiveServerErrors)
.ThenByDescending(t => t.LastSeenAt)
.Skip(skip).Take(take)
.ToList()
.Select(t => new LiveStreak(
t.SourceKey, t.ConsecutiveRefusals, t.ConsecutiveServerErrors,
t.LastStatusCode, t.LastPath, t.LastCountryCode, t.LastSeenAt))
.ToList();
}
public int TrackedCount
{
get
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
return db.Streaks.Count();
}
}
/// <summary>A clean answer ends the run. One statement, no read: this runs
/// for every 2xx/3xx, which is most of the traffic, and a source nobody has
/// ever seen must cost as little here as it does in the in-process map.</summary>
public void ResetIfTracked(string sourceKey)
{
if (string.IsNullOrEmpty(sourceKey)) return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var key = sourceKey;
db.Streaks
.Where(t => t.SourceKey == key && (t.ConsecutiveRefusals > 0 || t.ConsecutiveServerErrors > 0))
// The values are lambda-valued rather than plain constants: the query
// precompiler's funcletizer throws a NullReferenceException on the
// conversion it inserts around a constant in a set-list.
.ExecuteUpdate(u => u
.SetProperty(t => t.ConsecutiveRefusals, r => 0)
.SetProperty(t => t.ConsecutiveServerErrors, r => 0)
.SetProperty(t => t.LastAlertedRefusals, r => 0)
.SetProperty(t => t.LastAlertedServerErrors, r => 0));
}
public void Forget(string sourceKey)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
var key = sourceKey;
db.Streaks.Where(t => t.SourceKey == key).ExecuteDelete();
}
/// <summary>No cap to carry: <see cref="EdgePolicy.MaxTrackedSources"/>
/// bounds a process's memory, and this store is bounded by time instead —
/// idle rows are dropped when read (<see cref="EvictIdle"/>) and pruned by
/// the retention worker.</summary>
public void Configure(EdgePolicy policy) { }
/// <summary>Drop the rows no traffic has touched for longer than the idle
/// window. The context is resolved here rather than passed in: a query whose
/// root is a method parameter cannot be precompiled at all
/// (dotnet/efcore#38030), and precompiled queries are the only queries a
/// NativeAOT build can run.</summary>
private void EvictIdle(DateTimeOffset now, EdgePolicy policy)
{
if (policy.StateIdleTtl <= TimeSpan.Zero) return;
var idleBefore = now - policy.StateIdleTtl;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OpenWafDbContext>();
db.Streaks.Where(t => t.LastSeenAt < idleBefore).ExecuteDelete();
}
private static StreakState Read(SourceStreak row) => new()
{
SourceKey = row.SourceKey,
ConsecutiveRefusals = row.ConsecutiveRefusals,
MaxConsecutiveRefusals = row.MaxConsecutiveRefusals,
TotalRefusals = row.TotalRefusals,
ConsecutiveServerErrors = row.ConsecutiveServerErrors,
MaxConsecutiveServerErrors = row.MaxConsecutiveServerErrors,
LastAlertedRefusals = row.LastAlertedRefusals,
LastAlertedServerErrors = row.LastAlertedServerErrors,
LastRefusalAt = row.LastRefusalAt,
LastSeenAt = row.LastSeenAt,
LastStatusCode = row.LastStatusCode,
LastPath = row.LastPath,
LastUserAgent = row.LastUserAgent,
LastCountryCode = row.LastCountryCode,
LastCity = row.LastCity,
LastRegion = row.LastRegion
};
private static void Write(SourceStreak row, StreakState state)
{
row.ConsecutiveRefusals = state.ConsecutiveRefusals;
row.MaxConsecutiveRefusals = state.MaxConsecutiveRefusals;
row.TotalRefusals = state.TotalRefusals;
row.ConsecutiveServerErrors = state.ConsecutiveServerErrors;
row.MaxConsecutiveServerErrors = state.MaxConsecutiveServerErrors;
row.LastAlertedRefusals = state.LastAlertedRefusals;
row.LastAlertedServerErrors = state.LastAlertedServerErrors;
row.LastRefusalAt = state.LastRefusalAt;
row.LastSeenAt = state.LastSeenAt;
row.LastStatusCode = state.LastStatusCode;
row.LastPath = state.LastPath;
row.LastUserAgent = state.LastUserAgent;
row.LastCountryCode = state.LastCountryCode;
row.LastCity = state.LastCity;
row.LastRegion = state.LastRegion;
}
}