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

298 lines
14 KiB
C#

using System.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.Logging;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// What this process did to the schema when it started (OPEN-55).
///
/// A record rather than a log line, because the operator has to be able to ask
/// the running edge whether the tables this build expects are actually in the
/// database it is serving against. Before this, the only symptom of a schema
/// that predates a feature was a pillar that quietly answered nothing.
/// </summary>
public sealed record SchemaUpgradeOutcome(
string Strategy,
int TablesAdded,
int MigrationsBaselined,
int MigrationsApplied,
IReadOnlyList<string> MissingTables);
/// <summary>
/// Brings an existing database up to the schema the current build needs.
///
/// <c>EnsureCreated</c> — the default on sqlite — creates a missing database and
/// changes nothing about an existing one, so an upgrade that keeps its database
/// arrives with every table except the new ones. <c>Migrate</c> — the default on
/// postgres — cannot rescue that database either: it has no history table, so
/// the migration set would begin by creating tables that are already there. Same
/// bug, two faces, and both are fixed here.
///
/// What is never done is a destructive one. A table that exists is left alone
/// with everything in it; only what is absent is created, and it is created from
/// the model through the provider in use, so an upgraded database and a fresh
/// one have the same shape.
/// </summary>
public static class SchemaUpgrader
{
/// <summary>
/// Tables the current model describes that this database does not have.
/// Empty is the invariant; non-empty means a pillar this build can run has
/// no storage behind it.
/// </summary>
public static async Task<IReadOnlyList<string>> MissingTablesAsync(OpenWafDbContext db, CancellationToken ct = default)
{
var existing = await ExistingTablesAsync(db, ct);
return ModelTables(db).Where(table => !existing.Contains(table)).ToList();
}
/// <summary>
/// Create, in place, the tables this database predates. Returns what it
/// added — empty when there was nothing to add, which is every start after
/// the first one.
/// </summary>
public static Task<IReadOnlyList<string>> AddMissingTablesAsync(
OpenWafDbContext db, ILogger log, CancellationToken ct = default)
=> AddMissingTablesAsync(db, log, db.Database.GenerateCreateScript(), ct);
/// <summary>
/// The same step for a caller that supplies the DDL rather than letting EF
/// generate it — which is what a build that cannot reach the design-time
/// model has to do. The script is still EF's own output for this provider;
/// it was produced at build time instead of at start-up.
/// </summary>
public static async Task<IReadOnlyList<string>> AddMissingTablesAsync(
OpenWafDbContext db, ILogger log, string script, CancellationToken ct = default)
{
var missing = await MissingTablesAsync(db, ct);
if (missing.Count == 0) return missing;
var statements = SchemaDdl.StatementsFor(
script,
new HashSet<string>(missing, StringComparer.OrdinalIgnoreCase));
if (statements.Count == 0)
{
// The model says these tables are missing and the generated script
// has nothing recognisable that creates them. Creating nothing and
// saying so is the only honest move left.
log.LogError(
"edge: the database is missing {Tables} but no statement in the generated schema creates them — "
+ "the affected pillars will report themselves unavailable rather than answer with nothing.",
string.Join(", ", missing));
return [];
}
foreach (var statement in statements)
await db.Database.ExecuteSqlRawAsync(statement, ct);
log.LogWarning(
"edge: the database predates the current schema — created {Count} missing table(s) in place: {Tables}. "
+ "Nothing that was already in the database was touched, so the operator's lists are intact.",
missing.Count, string.Join(", ", missing));
return missing;
}
/// <summary>
/// Give a database that predates the migration set a history table, so the
/// migration then applies only what is genuinely missing. Returns how many
/// migrations were claimed; zero means nothing was claimed — either the
/// database is empty and the migrations will describe it from the beginning,
/// or the claim could not be made honestly and the migration is left to
/// report what it finds.
/// </summary>
public static async Task<int> BaselineIfUntrackedAsync(OpenWafDbContext db, ILogger log, CancellationToken ct = default)
{
var history = db.GetService<IHistoryRepository>();
// Asked of the table listing rather than of IHistoryRepository.Exists:
// measured on postgres, Exists() answered true for a database that has
// tables and no history table at all — which is exactly the state this
// method exists to notice. On sqlite the same call answered false. The
// listing is the one answer both providers agree on.
var existing = await ExistingTablesAsync(db, ct);
if (existing.Contains(HistoryRepository.DefaultTableName)) return 0;
if (existing.Count == 0)
{
// Either a first install, which the migrations describe from the
// beginning, or a listing this provider does not answer — and an
// empty listing is the one answer that would make an upgrade
// destructive, so it is said out loud rather than treated as "empty".
log.LogWarning(
"edge: the table listing for this database came back empty while it has no migration history — "
+ "nothing can be baselined, so the migrations will run against it and report what they find.");
return 0;
}
var assembly = db.GetService<IMigrationsAssembly>();
var migrations = new List<SchemaBaseline.Migration>();
var productVersions = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var id in db.Database.GetMigrations())
{
var migration = assembly.CreateMigration(assembly.Migrations[id], db.Database.ProviderName ?? string.Empty);
migrations.Add(new SchemaBaseline.Migration(
id,
migration.TargetModel.GetEntityTypes()
.Select(entity => entity.GetTableName())
.Where(name => name is not null)
.Select(name => name!)
.Distinct()
.ToList()));
productVersions[id] = migration.TargetModel.FindAnnotation("ProductVersion")?.Value?.ToString() ?? "unknown";
}
var claimed = SchemaBaseline.Choose(migrations, existing);
if (claimed.Count == 0)
{
log.LogWarning(
"edge: the database has {Count} table(s) and no migration history, and none of the migrations "
+ "can be shown to have run — not baselining, so the migration will run against it and fail loudly "
+ "rather than be guessed at.", existing.Count);
return 0;
}
await db.Database.ExecuteSqlRawAsync(history.GetCreateScript(), ct);
foreach (var id in claimed)
await db.Database.ExecuteSqlRawAsync(
history.GetInsertScript(new HistoryRow(id, productVersions[id])), ct);
log.LogWarning(
"edge: the database has no migration history — baselined {Claimed} of {Total} migrations "
+ "({Migrations} were already applied to it) and will run the rest.",
claimed.Count, migrations.Count, string.Join(", ", claimed));
return claimed.Count;
}
/// <summary>
/// How many migrations this database still has to run.
/// </summary>
public static async Task<int> PendingMigrationsAsync(OpenWafDbContext db, CancellationToken ct = default)
=> (await db.Database.GetPendingMigrationsAsync(ct)).Count();
/// <summary>
/// The tables this database actually has. Provider-specific because there is
/// no provider-neutral way to ask it, and an empty answer from a query that
/// does not exist on this provider would read as "everything is missing" —
/// which is the one answer that makes an upgrade destructive.
/// </summary>
private static async Task<IReadOnlySet<string>> ExistingTablesAsync(OpenWafDbContext db, CancellationToken ct)
{
var sql = db.Database.ProviderName switch
{
"Microsoft.EntityFrameworkCore.Sqlite" => "SELECT name FROM sqlite_master WHERE type = 'table'",
"Npgsql.EntityFrameworkCore.PostgreSQL" => "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = current_schema()",
_ => throw new NotSupportedException(
$"the in-place schema upgrade has no table listing for {db.Database.ProviderName}")
};
var tables = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var connection = db.Database.GetDbConnection();
var openedHere = connection.State != ConnectionState.Open;
if (openedHere) await db.Database.OpenConnectionAsync(ct);
try
{
await using var command = connection.CreateCommand();
command.CommandText = sql;
await using var reader = await command.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct)) tables.Add(reader.GetString(0));
}
finally
{
if (openedHere) await db.Database.CloseConnectionAsync();
}
return tables;
}
/// <summary>
/// The tables the model this process is running with describes.
///
/// Asked of the runtime model rather than the design-time one. The two answer
/// the same question for table names, and the design-time one is not merely
/// the more ceremonial choice: EF refuses it outright in a NativeAOT build
/// ("Design-time DbContext operations are not supported when publishing with
/// NativeAOT"), which made this one call the reason a compiled edge refused to
/// start at all. The runtime model is the one the process actually queries
/// with, so it is also the more honest thing to ask.
///
/// Asked per entity type rather than of the relational model, and that is not
/// style either: measured on a compiled model, <c>GetRelationalModel()</c> on
/// the runtime model threw <c>The annotation 'Relational:DefaultMappings'
/// cannot be added because an annotation with the same name already exists on
/// the object EntityType: CountryRule</c> — the relational model of a compiled
/// model already exists, and building it a second time collides with itself.
/// <c>GetTableName()</c> reads the mapping directly, and it is the same call
/// <see cref="BaselineIfUntrackedAsync"/> already makes on a migration's
/// target model.
/// </summary>
private static IReadOnlyList<string> ModelTables(OpenWafDbContext db)
=> db.Model.GetEntityTypes()
.Select(entity => entity.GetTableName())
.Where(name => name is not null)
.Select(name => name!)
.Distinct()
.ToList();
/// <summary>
/// The DDL this build carries for the provider in use. Null when it carries
/// none — the caller decides what that means, and it is never "no schema".
/// </summary>
public static string? EmbeddedScriptFor(OpenWafDbContext db)
=> EmbeddedSchema.ScriptFor(db.Database.ProviderName);
/// <summary>
/// Create the tables this database does not have from the DDL this build
/// carries, instead of from a model EF is asked to build at run time.
///
/// This is the <c>ensurecreated</c> step for a binary that cannot run
/// <c>ensurecreated</c>. What it does is the same thing: only what is absent
/// is created, from the provider-shaped statements the model generated at
/// build time, and a table that already holds the operator's lists is left
/// exactly as it is.
/// </summary>
public static async Task<IReadOnlyList<string>> ApplyScriptAsync(
OpenWafDbContext db, ILogger log, CancellationToken ct = default)
{
var script = EmbeddedScriptFor(db)
?? throw new NotSupportedException(
$"the schema script this build carries has no entry for {db.Database.ProviderName}; "
+ "the script strategy is only available for a provider whose DDL was generated at build time.");
var missing = await MissingTablesAsync(db, ct);
if (missing.Count == 0) return missing;
var statements = SchemaDdl.StatementsFor(
script,
new HashSet<string>(missing, StringComparer.OrdinalIgnoreCase));
if (statements.Count == 0)
{
log.LogError(
"edge: the database is missing {Tables} but the schema script this build carries has no "
+ "statement that creates them — the affected pillars will report themselves unavailable rather "
+ "than answer with nothing.",
string.Join(", ", missing));
return [];
}
foreach (var statement in statements)
await db.Database.ExecuteSqlRawAsync(statement, ct);
log.LogWarning(
"edge: the schema came from the DDL this build carries rather than from a model built at start-up — "
+ "created {Count} table(s): {Tables}. Nothing that was already in the database was touched.",
missing.Count, string.Join(", ", missing));
return missing;
}
}