Files
Pavlo Ratushnyi 1e0d11df1c
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
the first query moves off ef, and the aot edge reads its own policy from the database
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

340 lines
15 KiB
C#

#nullable enable
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OpenWaf.Data;
/// <summary>
/// A typed query whose SQL is rendered from an expression tree that is walked,
/// never compiled.
///
/// That last clause is the whole reason this type exists. EF answers the same
/// shape under NativeAOT with <c>Query wasn't precompiled and dynamic code isn't
/// supported with NativeAOT</c> — 32 of them in the 2026-10-07 probe window
/// before the first query moved off EF, 18 after —
/// because its query pipeline compiles expression trees into IL at run time.
/// Walking the tree with a switch over <see cref="ExpressionType"/> needs no
/// dynamic code, and the row materializer is a <c>Func&lt;DbDataReader,T&gt;</c>
/// the compiler emitted, so there is nothing left for the runtime to generate.
/// The mechanism is the neighbouring deployment's
/// (<c>~/work/tskr/app/lib/MicroOrmRuntime/Query.cs</c>, 1,219 lines); this is the
/// first slice of it, sized to the one query this tree has moved so far.
///
/// <b>The supported grammar is a closed set, and it says so.</b> Anything outside
/// it throws <see cref="UnsupportedQueryNodeException"/> naming the node, rather
/// than rendering SQL that is quietly wrong. What is supported today: comparisons
/// (<c>== != &lt; &lt;= &gt; &gt;=</c>) between a column and a value, null tests,
/// <c>&amp;&amp;</c>, <c>||</c>, <c>!</c>, captured locals and closure fields on the
/// value side, ordering, <c>Take</c>/<c>Skip</c>. What is not: joins, subqueries,
/// aggregates other than <c>Count</c>, updates and deletes, JSON columns, enum
/// comparisons. Each of those is a decision with a cost, not an oversight — and
/// <c>RenderSelect</c> is public so the rendered text can be asserted without a
/// database, which is how the neighbouring project tests its own renderers.
/// </summary>
public sealed class Query<T>
{
private readonly OrmContext _db;
private readonly Func<DbDataReader, ISqlDialect, T> _map;
private readonly TableMeta _meta;
private readonly List<string> _where = [];
private readonly List<(string Column, bool Descending)> _order = [];
private readonly List<object?> _args = [];
private int? _limit;
private int? _offset;
public Query(OrmContext db, TableMeta meta, Func<DbDataReader, ISqlDialect, T> map)
{
_db = db;
_meta = meta;
_map = map;
}
public Query<T> Where(Expression<Func<T, bool>> predicate)
{
// No extra parentheses here: Translate parenthesizes every binary term it
// emits, so a WHERE over one term reads as WHERE (x = @p0) and a WHERE over
// several reads as WHERE ((…) AND (…)) rather than a stack of brackets.
_where.Add(Translate(predicate.Body, predicate.Parameters[0]));
return this;
}
public Query<T> OrderBy(Expression<Func<T, object?>> selector) => Order(selector, false);
public Query<T> OrderByDescending(Expression<Func<T, object?>> selector) => Order(selector, true);
private Query<T> Order(Expression<Func<T, object?>> selector, bool descending)
{
_order.Add((ColumnOf(selector.Body, selector.Parameters[0]), descending));
return this;
}
public Query<T> Take(int n) { _limit = n; return this; }
public Query<T> Skip(int n) { _offset = n; return this; }
/// <summary>The SELECT this query would run, with the parameters it binds in
/// the same order. Public on purpose: the renderer is the test seam, and a
/// wrong query should be red against a string, not only against a database.</summary>
public string RenderSelect()
{
var sb = new StringBuilder("SELECT ");
var quoted = new List<string>(_meta.Columns.Length);
foreach (var column in _meta.Columns) quoted.Add(_db.Dialect.Quote(column));
sb.Append(string.Join(", ", quoted));
return AppendFrom(sb);
}
/// <summary>The COUNT this query would run for <see cref="CountAsync"/>.</summary>
public string RenderCount() => AppendFrom(new StringBuilder("SELECT " + _db.Dialect.CountAllExpression));
private string AppendFrom(StringBuilder sb)
{
sb.Append(" FROM ").Append(_db.Dialect.Quote(_meta.Table));
if (_where.Count > 0) sb.Append(" WHERE ").Append(string.Join(" AND ", _where));
if (_order.Count > 0)
{
sb.Append(" ORDER BY ");
var terms = new List<string>(_order.Count);
foreach (var o in _order)
terms.Add(_db.Dialect.Quote(o.Column) + (o.Descending ? " DESC" : " ASC"));
sb.Append(string.Join(", ", terms));
}
sb.Append(_db.Dialect.Page(_limit, _offset));
return sb.ToString();
}
public IReadOnlyList<object?> Arguments => _args;
public async Task<List<T>> ToListAsync(CancellationToken ct = default)
{
var sql = RenderSelect();
await using var connection = await _db.DataSource.OpenConnectionAsync(ct);
await using var command = connection.CreateCommand();
command.CommandText = sql;
Bind(command);
await using var reader = await command.ExecuteReaderAsync(ct);
var rows = new List<T>();
while (await reader.ReadAsync(ct)) rows.Add(_map(reader, _db.Dialect));
return rows;
}
public async Task<long> CountAsync(CancellationToken ct = default)
{
var sql = RenderCount();
await using var connection = await _db.DataSource.OpenConnectionAsync(ct);
await using var command = connection.CreateCommand();
command.CommandText = sql;
Bind(command);
var value = await command.ExecuteScalarAsync(ct);
return Convert.ToInt64(value, CultureInfo.InvariantCulture);
}
public async Task<T?> FirstOrDefaultAsync(CancellationToken ct = default)
{
_limit = 1;
var rows = await ToListAsync(ct);
return rows.Count > 0 ? rows[0] : default;
}
private void Bind(DbCommand command)
{
for (var i = 0; i < _args.Count; i++)
{
var parameter = command.CreateParameter();
parameter.ParameterName = "@p" + i.ToString(CultureInfo.InvariantCulture);
parameter.Value = _args[i] ?? DBNull.Value;
command.Parameters.Add(parameter);
}
}
// ---- the translator ----------------------------------------------------
private string Translate(Expression expression, ParameterExpression entity)
{
switch (expression)
{
case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert:
return Translate(convert.Operand, entity);
case UnaryExpression { NodeType: ExpressionType.Not } not:
return "NOT (" + Translate(not.Operand, entity) + ")";
case BinaryExpression binary:
return TranslateBinary(binary, entity);
case MemberExpression flag when IsColumn(flag, entity):
// A bare boolean column, rendered as a truth test: both providers
// this tree runs store a bool as 1/0.
return _db.Dialect.Quote(ColumnOf(flag, entity)) + " = 1";
case MethodCallExpression call:
throw new UnsupportedQueryNodeException(
$"method call '{call.Method.DeclaringType?.Name}.{call.Method.Name}'");
default:
throw new UnsupportedQueryNodeException(expression.NodeType.ToString());
}
}
private string TranslateBinary(BinaryExpression binary, ParameterExpression entity)
{
switch (binary.NodeType)
{
case ExpressionType.AndAlso:
return "(" + Translate(binary.Left, entity) + " AND " + Translate(binary.Right, entity) + ")";
case ExpressionType.OrElse:
return "(" + Translate(binary.Left, entity) + " OR " + Translate(binary.Right, entity) + ")";
}
var left = Operand(binary.Left, entity);
var right = Operand(binary.Right, entity);
// A null on either side is an IS [NOT] NULL test, never an equality with a
// parameter: "col = NULL" is unknown, not false, and a ban filter built that
// way silently stops matching the rows it was written for.
if (left.IsNull && right.IsNull)
throw new UnsupportedQueryNodeException("null compared with null");
if (left.IsNull) return NullTest(right.Column, binary.NodeType);
if (right.IsNull) return NullTest(left.Column, binary.NodeType);
var op = binary.NodeType switch
{
ExpressionType.Equal => "=",
ExpressionType.NotEqual => "<>",
ExpressionType.GreaterThan => ">",
ExpressionType.GreaterThanOrEqual => ">=",
ExpressionType.LessThan => "<",
ExpressionType.LessThanOrEqual => "<=",
_ => throw new UnsupportedQueryNodeException(binary.NodeType.ToString()),
};
// One side is the column, the other is a value already mapped for this
// provider. The parameter is appended before the placeholder is written, so
// the numbering and the bind order cannot disagree.
var column = left.Column ?? right.Column
?? throw new UnsupportedQueryNodeException("a comparison with no column on either side");
_args.Add(left.Column is null ? left.Value : right.Value);
// Parenthesized even though SQL's own precedence would usually allow it
// without: a rendered predicate is read by a human in a log, and a test
// that mixes AND and OR should not depend on who remembers the table.
return "(" + _db.Dialect.Quote(column) + " " + op + " " + _db.Dialect.Param(_args.Count - 1) + ")";
}
private string NullTest(string? column, ExpressionType nodeType)
{
if (column is null)
throw new UnsupportedQueryNodeException("a null test with no column to test");
return nodeType switch
{
ExpressionType.Equal => "(" + _db.Dialect.Quote(column) + " IS NULL)",
ExpressionType.NotEqual => "(" + _db.Dialect.Quote(column) + " IS NOT NULL)",
_ => throw new UnsupportedQueryNodeException(nodeType.ToString() + " against null"),
};
}
private readonly record struct OperandResult(string? Column, object? Value, bool IsNull);
private OperandResult Operand(Expression expression, ParameterExpression entity)
{
var unwrapped = Unwrap(expression);
if (unwrapped is ConstantExpression { Value: null }) return new OperandResult(null, null, true);
if (IsColumn(unwrapped, entity)) return new OperandResult(ColumnOf(unwrapped, entity), null, false);
var mapped = Value(unwrapped, entity);
// A captured null is a null test too. Rendering it as "col = @p0" bound to
// DBNull parses, runs, and matches nothing — the quietest wrong answer
// there is, and the one a nullable ban expiry produces.
return new OperandResult(null, mapped, mapped is null);
}
private static Expression Unwrap(Expression expression) =>
expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert
? Unwrap(convert.Operand)
: expression;
private static bool IsColumn(Expression expression, ParameterExpression entity) =>
Unwrap(expression) is MemberExpression member && RootOf(member) == entity;
private static Expression? RootOf(Expression expression) =>
expression switch
{
MemberExpression member => RootOf(member.Expression!),
UnaryExpression unary => RootOf(unary.Operand),
ParameterExpression parameter => parameter,
_ => null,
};
private string ColumnOf(Expression expression, ParameterExpression entity)
{
if (Unwrap(expression) is not MemberExpression member)
throw new UnsupportedQueryNodeException("an ordering or test that is not a column");
var name = member.Member.Name;
var column = _meta.ColumnOf(name);
if (column.Length == 0)
throw new UnsupportedQueryNodeException($"member '{name}' is not a column of {_meta.Table}");
return column;
}
/// <summary>The value side of a comparison: a literal, a captured local, or a
/// closure field. Reading a closure field is reflection over a field the
/// compiler generated for a lambda — the same move the neighbouring
/// deployment's renderer makes, and the one its AOT deployment proves works.</summary>
private object? Value(Expression expression, ParameterExpression entity)
{
expression = Unwrap(expression);
switch (expression)
{
case ConstantExpression constant:
return MapValue(constant.Value);
case MemberExpression member:
{
// The root of a captured variable is a ConstantExpression holding
// the closure object itself. It is the OWNER of the field read, not
// a value to bind — mapping it as a parameter is how a captured
// local turns into "a parameter of type <>c__DisplayClass10_0".
object? owner = null;
if (member.Expression is not null)
{
var ownerExpression = Unwrap(member.Expression);
owner = ownerExpression is ConstantExpression root ? root.Value : Value(ownerExpression, entity);
}
var raw = member.Member switch
{
FieldInfo field => field.GetValue(owner),
PropertyInfo property => property.GetValue(owner),
_ => throw new UnsupportedQueryNodeException($"member '{member.Member.Name}' on the value side"),
};
return MapValue(raw);
}
default:
throw new UnsupportedQueryNodeException(expression.NodeType.ToString() + " on the value side");
}
}
private object? MapValue(object? value) => value switch
{
null => null,
DateTimeOffset instant => _db.Dialect.WriteDateTimeOffset(instant),
bool flag => flag ? 1 : 0,
string or byte or sbyte or short or ushort or int or uint or long or ulong or float or double or decimal or Guid => value,
_ => throw new UnsupportedQueryNodeException(
$"a parameter of type {value.GetType().Name}; the generated query layer names the CLR types it binds"),
};
}
/// <summary>A query shape this layer refuses, said by name at the call site
/// rather than answered with SQL that looks right.</summary>
public sealed class UnsupportedQueryNodeException(string what)
: NotSupportedException($"OpenWaf.Data cannot render {what}. Either extend the renderer or leave the query to EF.")
{
public string What { get; } = what;
}