13 Commits
Author SHA1 Message Date
Pavlo Ratushnyi 1e0d11df1c the first query moves off ef, and the aot edge reads its own policy from the database
ci / build, test, smoke (push) Failing after 3m33s
ci / the same smoke on an image with no base (push) Successful in 8m10s
ci / lint the workflow and the shell (push) Failing after 19s
ci / the operator page in a real browser (push) Successful in 4m41s
ci / build the image and smoke it (push) Failing after 8m11s
Wall 3 starts. Two projects, one query path, measured.

dotnet/OpenWaf.Data is the runtime: OrmContext (a DbDataSource plus an
ISqlDialect), Query<T>, RowReader, OrmMeta. It is typed over System.Data.Common
and carries no provider package; the driver is supplied at composition, which is
how the neighbouring deployment ships it too. Query<T> renders SQL by walking the
expression tree rather than compiling it — that is the exact difference from EF's
pipeline, and the reason it survives a NativeAOT link where EF does not. The
supported grammar is a closed set that refuses by name: joins, subqueries,
aggregates other than COUNT, updates, deletes, JSON columns and method calls each
raise UnsupportedQueryNodeException naming the node, because a renderer that
guesses is a renderer that ships wrong SQL.

dotnet/OpenWaf.Data.Generator is a Roslyn incremental generator attached to
OpenWaf.Infrastructure as an analyzer. For a [Table] class it emits the column
map, the row materializer and an OrmMeta.Register call inside a
[ModuleInitializer], so the question a NativeAOT binary cannot answer — what are
this type's properties — is never asked. The generated file is ordinary C#,
readable in obj/ and asserted against.

PolicySetting is the entity moved and EdgePolicyProvider.ReloadAsync the call
site, which was the first refusal in the probe log. Program.cs composes the
driver and dialect on the same Database:Provider switch EF uses, so one generated
query serves sqlite (the shipped image) and PostgreSQL (the migrations'
provider). EF still owns every write and every other read; the two layers
coexist on one composition root, which is what makes this incremental rather than
a rewrite.

Measured on the AOT binary, same probe, same window, before and after:
queries refused at run time 32 -> 18; EdgePolicyProvider reload failures 1 -> 0;
native binary 49,609,680 -> 49,676,016 bytes. The 18 that remain are named by
their own frames: 14 EdgeStateStore.RefreshAsync, 2 BlockStore.WriteBanAsync,
1 BlockStore.AddOperatorAsync, 1 admin endpoint.

The sqlite timestamp column turned out to be a contract, not a detail. The model
puts EF's DateTimeOffsetToBinaryConverter on every timestamp column, so every row
already written says (localTicks / 1000) * 2048 + (offsetMinutes & 2047); the
formula was derived by probing EF's converter and is now pinned by
SqliteTimestampEncodingTests against that converter over five instants including
+05:30, -05:00 and DateTimeOffset.MinValue — including the microsecond
truncation the /1000 imposes, which is EF's behaviour and is now a test rather
than a future surprise.

Two build traps, both paid for and both recorded where the next person will hit
them. -p:PublishAot on the command line is a global property, so it reaches every
project in the graph including a netstandard2.0 Roslyn analyzer, and the publish
dies with NETSDK1207; AOT is now switched by OpenWafAot=true, which only
OpenWaf.Edge.csproj turns into PublishAot — the same shape as the existing
OpenWafCompiledModel switch. And a raw Microsoft.Data.Sqlite data source needs
SQLitePCL.Batteries.Init() before its first open, because the order in which
EF's provider and this data source are first used is not guaranteed.

Gates on this tree: build 0 warnings, unit 391/391 (13 new: rendered SQL for both
dialects, null tests, the captured-null case, the refusals, the timestamp
encoding), integration 408/408, smoke 256/256, and the AOT probe above. One
earlier run of the 408 carried a single failure in AdminConsoleTests at a host
load average near 30 and the next run was clean; recorded rather than hidden, in
the same family as the load-sensitive compose gates this README already
documents.
2026-10-07 21:48:01 +02:00
Pavlo Ratushnyi 0a3d28184f the aot edge serves traffic now, and the shape still missing a contract was its own healthcheck
ci / lint the workflow and the shell (push) Failing after 54s
ci / build, test, smoke (push) Successful in 6m4s
ci / the operator page in a real browser (push) Failing after 4m53s
ci / build the image and smoke it (push) Failing after 10m29s
ci / the same smoke on an image with no base (push) Failing after 9m2s
Measured on this tree with scripts/aot-probe.sh (osx-arm64, a 49,609,680-byte
native binary, 10 IL warnings, 0 errors): the AOT edge reaches "Now listening
on:", creates its 12 tables from the DDL it carries, proxies a request to the
upstream for 200, and its own --healthcheck mode exits 0. The API wall that
stood between the first cut and a serving edge came down in two edits, and the
json-refusal count went 55 -> 1 -> 0.

The 55 were one shape. The anonymous 8-property /healthz literal had no
compiled contract, so the edge was serving traffic while the endpoint a scratch
container's HEALTHCHECK asks answered 500 - an edge that serves and is restarted
anyway. Health/HealthDtos.cs names it (HealthDto, ReadinessDto). The 1 after
that was Microsoft.AspNetCore.Mvc.ProblemDetails, the body Results.Problem
writes and nobody's DTO in this project: its visible cost was a /readyz 500
naming nothing where a 503 naming the failure is the truth. It now says
"Query wasn't precompiled and dynamic code isn't supported with NativeAOT."

The probe's scoreboard is split the way the finding is. Three assertions that
need no query are gated (healthz 200, proxy 200, --healthcheck exit 0), and the
host must be listening with no response refused for want of a contract. Five
that do need a query are recorded with the answer a working edge would give -
operator block 503 where 204 is right, the streak ban never forms, /readyz 503
where 200 is right - and any of them that ever matches prints MOVED, which is
the signal that the query wall moved. queries refused at run time: 32 in that
window, 30 in the run before it; it counts a window, not a total, because the
background refresh loop retries on its own clock.

Two probe bugs surfaced doing this. It sent "Authorization: Bearer" to the admin
API, which AdminAuth does not read, so three of its assertions were measuring a
401 rather than the query wall; and it asserted nothing about whether the host
had listened at all.

Gates on this tree: build 0 warnings, unit 378/378, integration 408/408 in 51 s
(the new one demands a contract for ProblemDetails and ValidationProblemDetails),
smoke 256/256.

Two stale figures corrected rather than left standing. The registered-type count
was 24 in README and ARCHITECTURE while the file at that commit holds 25 -
CountrySummaryDto arrived without the count being re-derived - and it is 29 now.
The anonymous-literal count is 29 in 23 shapes: 22 response shapes, and 7 inside
an EF query's Select, which belong to the query wall rather than this one. The
"48.8 MB" native binary in ARCHITECTURE matches no measured binary of this tree.
2026-10-07 19:28:22 +02:00
Pavlo Ratushnyi 5c1a2950d0 two more wire shapes stop being anonymous, and the count of the ones left gets re-measured
ci / lint the workflow and the shell (push) Successful in 22s
ci / build, test, smoke (push) Successful in 4m36s
ci / the operator page in a real browser (push) Successful in 4m48s
ci / build the image and smoke it (push) Successful in 8m34s
ci / the same smoke on an image with no base (push) Failing after 8m44s
`countries/summary` answered with a `List<anonymous>`: the anonymous shape is what
EF translates — the record-constructor form compiles and then fails at query time
with "could not be translated", which is a test's finding, not a guess — so the
projection stays inside the query and the *response* becomes a named record,
`CountrySummaryDto(Code, Sources, Refusals)`, mapped after `ToListAsync` with the
sort left where it was. Registered in `EdgeJson`. `Code` stays nullable in the
model and non-null in these rows: the query filters `LastCountryCode != null`,
which the compiler cannot see and EF does apply. The second literal is one the
first pass missed because it spans three lines — a `Results.BadRequest` whose body
was `new { error = … }`, now `ErrorDto`.

The counts in `README.md` and `docs/ARCHITECTURE.md` are corrected, and the
correction is stated rather than quietly applied: `fb75890` records **130
anonymous-object literals in 51 shapes**, and its message repeats that. Those two
figures came from a first-pass scanner that walked braces without skipping string
literals, so every `{` inside an interpolated string was counted as code. The same
tree re-measured with a scanner that skips strings, char literals and comments:
**144 literals in 27 shapes** before this change, **31 in 25 shapes** after it.
The **111** that became `ErrorDto` is the one figure both scanners agree on, which
is why the first commit still moved the wall it claimed to move.

Measured on this tree: `dotnet build OpenWaf.Edge -c Release` 0 warnings, unit
**378/378**, integration **407/407 in 34 s** (unsandboxed; the sandboxed run of
this suite is not a measurement — see the loopback-bind note in the README).
2026-10-07 09:06:57 +02:00
Pavlo Ratushnyi fb758900b8 the admin API's error body stops being anonymous, and the AOT build prices a reflection resolver
Wall 2 of the generator slice (OPEN-79) is the web host, not the database: the
AOT edge never reaches `Now listening` because the admin API's request DTOs have
no compiled JSON contract, and a NativeAOT binary has no reflection resolver to
fall back on. The wire shapes have to be types before a contract can exist for
them, so this starts with the shapes.

Counted in `dotnet/OpenWaf.Edge` before the change: **130 anonymous object
literals** in the JSON path, in **51 distinct shapes**, of which **111 are the
one shape `new { error = … }`**. Those 111 are now `ErrorDto`, and the two
read-only-token refusals that carried a second property are `ReadOnlyRefusalDto`.
`ErrorDto.Error` is nullable because the literal it replaces was — the
unknown-query-parameter validators hand back a `string?` next to the false they
return, and making it non-null would hide a second change inside a mechanical
one. `Admin/EdgeJson.cs` is the edge's `JsonSerializerContext`: 24 registered
types (5 request bodies, the 14 response records the tree already had, the two new
ones, the config-transfer document and its rejected-item row), with
`[JsonSourceGenerationOptions(PropertyNamingPolicy = CamelCase)]` because the
generated contract carries the property names — without that line the same record
answers `{"Error": …}` and the console, the smoke gate and every integration
assertion read a body with no error in it. The recipe is the neighbouring
deployment's (`app/lib/Kernel/KernelJson.cs`, `api/Domain/AppJson.cs`, one line in
its `Program.cs`), not an invention here. **18 anonymous literals in 50 shapes
remain**; they are the rest of the wall, and this commit does not pretend
otherwise.

Two measurements decided the wiring, and both were paid for:

  * A non-empty `TypeInfoResolverChain` **replaces** the reflection resolver, it
    does not extend it. With only the context in the chain, a type it does not
    know fails on a *JIT* build with the sentence the AOT probe reports —
    `JsonTypeInfo metadata for type '<>f__AnonymousType0`1[System.String]' was not
    provided by TypeInfoResolver of type '[EdgeJson]'` — reproduced with a
    standalone probe. So on a build that can reflect, reflection stays at the end
    of the chain: the 18 remaining literals kept served and visible rather than a
    break smuggled into a slice.
  * That fallback is not free on the other side. Naming `DefaultJsonTypeInfoResolver`
    in an AOT publish pulls the reflection-based JSON stack into the native image:
    the publish step ran **66 minutes and never finished**, against **232 s** for
    the same Dockerfile an hour earlier. The branch is now gated on
    `RuntimeFeature.IsDynamicCodeCompiled`, which the AOT compiler substitutes as
    a constant, so the shipped binary contains neither the branch nor the resolver.
    The 66-minute figure was taken at load average 26–34 against the earlier run's
    ~12, so that ratio is an upper bound, not a clean A/B; the weekly runner is
    where the clean number will come from.

`AotJsonContractTests` (2 new) asks the running edge which body types its
endpoints accept — `IAcceptsMetadata`, read from the live `EndpointDataSource`,
with the measured count of 5 asserted so the guard cannot pass on an empty set —
and demands a compiled contract for each; the second test asserts the generated
contract really says `error` and `tokenLevel`. An endpoint added without a
contract is therefore red in the suite, not in next Monday's probe.

Measured on this tree: `dotnet build OpenWaf.Edge -c Release` 0 warnings, unit
**378/378**, integration **407/407 in 2 m 16 s** (unsandboxed). The same suite run
inside the sandbox answered **8 failures of 407**, every one of them `Timed out
waiting for the entry point to build the IHost after 00:05:00` — the loopback-bind
symptom the README already recorded on 2026-10-04 and 2026-10-05, reproduced here
rather than re-diagnosed; the 407 figure is the unsandboxed one.

NOT measured on this tree: whether the AOT edge now reaches `Now listening`. The
rebuild that would answer it was interrupted, so the README and
`docs/ARCHITECTURE.md` say so in those words, and `.github/workflows/aot-probe.yml`
now prints `lines where the edge started listening` — 0 means the host still dies
before serving, 1 means it serves. The 18 remaining anonymous shapes are what
stands between the two.
2026-10-07 08:35:51 +02:00
Pavlo Ratushnyi 0a2cbee558 sqlite is baked into the static link, and the AOT probe now names two walls instead of one
The probe used to report one wall: the binary died in
`Microsoft.Data.Sqlite.SqliteConnection..cctor` with `DllNotFoundException:
e_sqlite3` / `Dynamic loading not supported`. That sentence described a build that
did not link sqlite at all. Two musl-only items in `OpenWaf.Edge.csproj` close it
— `NativeLibrary` puts Alpine's `sqlite-static` `/usr/lib/libsqlite3.a` on the
link line, `DirectPInvoke` makes ILC emit a direct call to the symbol instead of a
run-time module load — and `Dockerfile.aot-probe` installs the package.

Both items are needed, and the order was measured, not guessed. With
`NativeLibrary` alone the link is still fully static (0 interpreters, 0 NEEDED) and
the binary still calls `NativeLibrary.Load("e_sqlite3")` at the first query and
NativeAOT refuses it. The pair is what the runtime pack itself uses for
`System.Native` and the OpenSSL shim (`Microsoft.NETCore.Native.Unix.targets`
140-155), so this is the SDK's mechanism rather than a fork of it.

Measured on the arm64/musl half, this host, 2026-10-06: 58,343,456-byte
`static-pie linked` binary, `readelf -l` 0 interpreters, `readelf -d` 0 NEEDED,
96.4 MB scratch image, and a log with 0 `e_sqlite3` lines that says the edge
created 12 tables from the DDL it carries. Two standalone probes with the same
link say the same thing one level down: direct P/Invoke to sqlite3 opens
`:memory:`, writes two rows and reads `2` back (sqlite 3.53.4); and
`Microsoft.Data.Sqlite` — the ADO layer this tree already uses — opens a
connection and reads `sqlite_version()` back. So the ADO layer survives and only
EF's query compilation is left standing.

The check that sqlite is inside the binary is behavioural, and had to be: the
binary is stripped and `nm` reports 0 `sqlite3_` symbols on a binary that
demonstrably runs sqlite. No tool that only reads the file can answer this.
`.github/workflows/aot-probe.yml` therefore gates four things after the link — no
interpreter, no NEEDED, no `e_sqlite3` line, and the schema line as the positive
half, because a gate that only forbids an error string also passes when the
feature is simply absent. The step was run verbatim against the real artifact
before committing (exit 0), and both failure branches were tested against a
doctored log. It also had a bug caught by that run: it read the log after a fixed
20 s sleep and reported "no schema" on a loaded host, so it now waits up to 180 s
and prints how long it waited — measured 6 s on a quiet host, past 22 s under
load, 3 s in the verification run.

What the probe reports now, which is what closing the first wall buys:

  * hosting refuses to start — `JsonTypeInfo metadata for type
    'OpenWaf.Edge.Admin.NewBlockRequest' was not provided by TypeInfoResolver`,
    3 refusals. The route handlers in the stack are already the generated ones
    (`GeneratedRouteBuilderExtensionsCore`), so the API half is not missing code
    generation; it is missing a registered JSON contract for the admin DTOs.
  * every query is refused — `Query wasn't precompiled and dynamic code isn't
    supported with NativeAOT`, 2 refusals. That is EF's precompiler, whose four
    untranslatable shapes and codegen bug `docs/ARCHITECTURE.md` already carries.

Also measured: `dotnet build OpenWaf.Edge -c Release` (non-musl) 0 warnings, unit
378/378 — the two items are conditioned on the musl RID and the shipped images do
not take this path. Not measured here: the x86-64 musl half, because the musl ILC
crashes under emulation on Apple Silicon; the weekly workflow is the only place
that number exists, and it now carries this gate.
2026-10-06 22:45:59 +02:00
Pavlo Ratushnyi d08ec30e0a the AOT edge links fully static and dies on sqlite, which names the wall exactly
ci / lint the workflow and the shell (push) Successful in 10s
ci / build, test, smoke (push) Failing after 2m11s
ci / the operator page in a real browser (push) Successful in 2m29s
ci / build the image and smoke it (push) Successful in 4m15s
ci / the same smoke on an image with no base (push) Successful in 4m15s
Dockerfile.aot-probe applies the packaging recipe a neighbouring .NET 10 service
already ships — musl RID, StaticExecutable, StaticOpenSslLinking, IlcSingleThreaded,
scratch plus a CA bundle — and the link claim is checked inside the build rather
than asserted in a comment. Measured here (arm64, native): `file` says
`static-pie linked`, `readelf -l` reports 0 program interpreters, `readelf -d`
reports 0 NEEDED shared objects, the binary is 56,820,992 bytes and the image is
94 MB — against 222 MB for the self-contained scratch image and 262 MB chiseled.

It does not serve, and the reason is one step earlier than the query wall:
`Microsoft.Data.Sqlite.SqliteConnection..cctor` throws `DllNotFoundException:
e_sqlite3` with `Dynamic loading not supported`, because SQLitePCLRaw resolves
sqlite by loading a shared library and a NativeAOT binary has no way to load one.
`scripts/compose-smoke.sh` against that image therefore never gets past
readiness: the container reports exited/unhealthy and every curl answers 000.
Behind that sits the EF precompiler wall measured at 7c5e1ef and today.

So the static scratch shape is reachable for this program and the data layer is
the thing in the way. The deployment that ships it has no EF Core and no SQLite:
Npgsql plus a Roslyn source generator that emits queries at build time
(app/lib/MicroOrm there), which is why its AOT binary can be one static file.

.github/workflows/aot-probe.yml re-runs this on the x86-64 runner weekly and
gates only the static-link claim (0 interpreters, 0 NEEDED, static-pie), because
the musl AOT ILC crashes under emulation on Apple Silicon. docker-compose.aot.yml
runs the production smoke against the probe image for whoever wants the failure
in full rather than summarised.
2026-10-06 09:15:29 +02:00
Pavlo Ratushnyi be6c608ada the edge ships on an image with no base, and the 368 assertions agree it behaves
ci / the operator page in a real browser (push) Successful in 2m38s
ci / lint the workflow and the shell (push) Successful in 13s
geo-freshness / the pinned geo database vs the vendor (push) Successful in 4s
ci / build, test, smoke (push) Successful in 2m48s
ci / build the image and smoke it (push) Successful in 4m23s
ci / the same smoke on an image with no base (push) Successful in 5m3s
Dockerfile.scratch builds the same program self-contained and puts it on
scratch: 12 shared objects and the CA bundle — 18.7 MB — carried at their
absolute paths, because a scratch layer has nothing to borrow them from, and the
dynamic loader has to land at the path recorded inside the binary or the kernel
refuses to start the process. Measured on one arm64 host: chiseled 262 MB,
scratch 222 MB. scripts/compose-smoke.sh runs against it unchanged through
docker-compose.scratch.yml: 368 passed, 0 failed, and 368/0 again when the same
gate is called as scripts/ci-gates.sh scratch-smoke.

The first scratch image built here is why that second run matters. It started,
its own HEALTHCHECK reported healthy, and it still failed 7 of the 368. A
self-contained apphost takes its content root from the process's working
directory, a scratch image has no WORKDIR, so the process began in /, never found
the appsettings.json next to it, the reverse proxy had no routes, and every
request that should have reached the upstream answered the edge's own 404 —
including /boom's 502, which turned the "server errors alert, they never ban"
scene into a streak ban. The edge said it in its own log: "Request reached the
end of the middleware pipeline without being handled by application code."

The schema-script gate was red on the runner at 7c5e1ef (run 2462, exit 2):
`dotnet tool restore` from the repo root finds no manifest, prints "No tools were
restored." and exits 0, so the gate's own restore check passed vacuously and
`dotnet ef` then died. It now restores dotnet/dotnet-tools.json by path and asks
the tool for its version before trusting it.

NativeAOT, measured further: with the two alert-queue queries taken out,
`dotnet ef dbcontext optimize --precompile-queries` on EF 10.0.12 reports 0
precompilation errors and writes 8 interceptor files — 14 of whose declarations
have dots in the identifier, because the local is named from the entity type's
full name. The 4 refusals that remain are four shapes the generator cannot
translate at all: Contains over a captured collection, any method parameter
referenced inside a query (down to the CancellationToken), an ExecuteUpdate
set-list, and a literal whose type is not the column's. docs/ARCHITECTURE.md
carries the exception for each. No C# changed in this commit: the experiments
that produced those numbers were reverted, and the query rewrites kept at
7c5e1ef are the ones that made 40 refusals into 4.

Gates: scratch-image and scratch-smoke in scripts/ci-gates.sh and in `all`, and a
fifth CI job that runs the 368 against the scratch image on the runner.
2026-10-06 06:38:07 +02:00
Pavlo Ratushnyi 7c5e1ef230 the edge gains a schema step a compiled binary can run, and NativeAOT gets a measured verdict
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 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
Pavlo Ratushnyi 8ee6570458 the streak map can live in the database, so N edges mature one streak
The multi-instance research measured the gap rather than guessing it: four
refusals from one address, two per edge, at a threshold of 3, produced no ban
anywhere, because the block list was shared through the database and the streak
map was not (research/2026-10-01-multi-instance/, D1). OpenWaf:Policy:
SharedStreaks=true moves the counters onto a row in source_streaks; the default
stays the in-process map, because that is the deployment that loses nothing.

The rules were extracted into StreakRules.Apply and both stores call it — the
in-process map against a StreakState, the shared one against a row. A second
copy of the streak semantics would put the drift back where this removes it.
Version is a concurrency token, so two edges writing one source produce a retry
against the winner's row rather than a silently dropped refusal; a clean answer
on any edge ends the run on every edge, in one statement. The rows age out on
the same ObservationRetentionDays window as observations. Both surfaces say
which store answered: /admin-api/streaks scope is this-process or
shared-database, /admin-api/state answers streakScope, and the console's streak
note stops claiming "this edge process only" when it is not true.

Found by running it for real rather than in-process: two edge processes on one
SQLite file both create the schema on startup, and the loser of that race died
in StartAsync with 'table "allow_entries" already exists' — hosting failed to
start and the process never listened. The schema step now re-checks existence
and continues, because what has to be true is that the schema exists, not that
this process made it.

Measured on this tree: build 0 warnings / 0 errors, unit 132/132, integration
191/191 in 32 s (6 new, two real edge instances on one SQLite file each), smoke
28/0, console 78 assertions 0 failed. Out of process, two edge binaries on one
file at a 5 s TTL: A answered 404, 404; B answered 404 on the third refusal and
403 after it; both edges then reported consecutiveRefusals: 3 with
scope: shared-database, and A started enforcing 4 s later. Before the schema fix
the second process aborted on startup, which is how that fix was found.
2026-10-04 17:13:21 +02:00
Pavlo Ratushnyi 34a13ce796 D5: the alert dedup is per process, and two edges is where that shows 2026-10-01 18:03:54 +02:00
Pavlo Ratushnyi f7ced94f75 The TTL knob got measured, and a sentence in the research turned out to be stale
`research/2026-10-01-multi-instance/RESULTS.md` said, correctly at the time, that
the snapshot TTL "is not operator-tunable... so 'shorten the TTL' is currently a
rebuild, not a deployment change". OPEN-13 made it
`OpenWaf:State:RefreshTtlSeconds` (validated 1-300 s, startup aborts naming the
key outside that range). A claim that was true and is now false is still a claim
sitting in a document, so it is corrected in place, with what changed and when,
rather than quietly rewritten.

`run4.sh` measures the option that claim was blocking. Same stack and same method
as D3 — edge-b serves a steady 200-only stream from one source (a refusal stream
bans its own probe, which is the mistake `run2.sh` made), edge-a writes an
operator block at t0, the first sample edge-b answers as a refusal is the
propagation number. Two phases, and the TTL is read back from `/healthz` rather
than assumed from the environment, because a typo in the key name would otherwise
measure 30 s twice and report it as two different settings.

    ttl=30 (default)  samples=1223 over 44.1 s (~27.7 req/s)  enforced 23 100 ms after the write
    ttl=5             samples=1247 over 44.3 s (~28.1 req/s)  enforced  3 367 ms after the write

**23.1 s → 3.4 s: a 6.9x cut**, and the 30 s phase independently reproduces D3's
23.7 s, which is the second time that number has come out the same.

What it does not say. The request path through edge-b during the same runs: p50
1.75 ms / p95 3.15 ms at TTL 30, p50 1.93 ms / p95 2.78 ms at TTL 5, n=200 each.
The two percentiles move in opposite directions, so the honest reading is "inside
noise", not "cheaper" — and a shorter TTL is more refresh round trips per process
per minute (12 against 2), cheap at the snapshot size that was measured (~3 ms of
queries at 2000 blocks) and unmeasured at any larger size.

For OPEN-12 this turns option (b) from an assumption into a measurement, and
leaves its limit exactly where it was: shortening the TTL fixes propagation, and
does nothing about D1 — four refusals split 2+2 across two edges at threshold 3
still produce no ban anywhere. The streak map is still the thing that would have
to move.

`docs/ARCHITECTURE.md` evolution triggers 2 and 3 updated with what is now true:
the geo-staleness trigger partly fired and was handled (including the case the
90-day runtime alarm does not catch), and the multi-instance trigger now carries
both reproduced findings and the measured TTL effect.
2026-10-01 17:18:12 +02:00
Pavlo Ratushnyi 768dd17a88 Measure the two-edge deployment instead of arguing about it
OPEN-12 asks whether the per-process snapshot is worth replacing. Until now
the answer rested on an SQLite measurement. This runs the deployable image
against PostgreSQL with two edges and one shared database and writes down
what actually happens: round-robin over two edges multiplies the effective
streak threshold (four refusals split 2+2 at threshold 3 produced no ban at
all), a block issued by one edge is enforced by the other after up to the
30 s snapshot TTL (23.7 s measured under 36 req/s, 1.7 s on an idle edge),
and the refresh itself is not the cost (3 ms of queries at 2000 blocks,
request p95 unchanged at 3.3 ms). Concurrent migrations on one database are
safe.

docs/ARCHITECTURE.md's multi-instance evolution trigger now points at the
measurement instead of restating the worry.
2026-10-01 12:33:17 +02:00
Pavlo Ratushnyi a3d0777492 openwaf: edge WAF with one decision point and a streak ban
Initial implementation of the OPEN-2 epic: a .NET 10 YARP edge that
decides from what the upstream answered.

Design (docs/ARCHITECTURE.md, tracker authority 4c9de3f6):
- one short-circuit point, ordered: always-pass prefixes -> allowlist ->
  operator block (301) -> engine ban (403 + Retry-After) -> geo (451)
- a post-response observer feeds a consecutive-refusal streak; N refusals
  in M minutes ban for BanDuration; 5xx alerts and never bans
- provenance on the block row, so clearing engine bans cannot touch an
  operator's entries; the toggle is Off/Observe/Enforce and changes no rows
- inherited protections from the reference deployment: one durable write
  per source per 30s, LRU-bounded streak map, no DB on the request path

Verification: 36 unit + 14 integration tests, plus scripts/smoke.sh (19
assertions against a running edge and a real upstream, including the
distroless --healthcheck mode).

Findings worth keeping (documented in docs/ARCHITECTURE.md):
- ctx.RequestAborted silently cancelled the ban write, because the
  observer runs after the response is written
- SQLite cannot translate DateTimeOffset comparisons; timestamps are
  stored as integers there and stay timestamptz on PostgreSQL
- CIDR masking order silently widened prefixes (198.51.100.24/19 -> /16)
- an empty string in appsettings.json defeats the env fallback (?? on "")
- concurrent ban writes raced into the unique index and lost evidence

Also moves the unrelated 2026-09-30 inference benchmarks out of the
project root into research/.
2026-10-01 02:13:01 +02:00