Skip to content

planeval: SQL input with both arms on DataFusion (Phase 2 ver 2, M0-M7) - #128

Open
GordonYuanyc wants to merge 47 commits into
mainfrom
phase2-ver2
Open

GordonYuanyc wants to merge 47 commits into
mainfrom
phase2-ver2

Conversation

@GordonYuanyc

Copy link
Copy Markdown
Collaborator

Summary

Implements Phase 2 ver 2 from PLAN.md §8: SQL comes in, and both arms (pre-ASAP and post-ASAP) execute on DataFusion 43 instead of the hand-written interpreter. Each IR is lowered to a LogicalPlan by a per-variant translator; execution, timing and memory accounting are DataFusion's own. DataFusion itself is not forked — sketches enter through its UDAF/UDF seams.

The ver 1 interpreter is kept as --runtime interp and serves as the bit-for-bit oracle.

Milestone What landed
M0 Sync to ASAPPlanner 2ec3fc8; ver 1 output unchanged apart from the plan id (upstream bumped the DAG wire version to 2)
M1 --sql input through upstream asap-frontend-sql, with a spec-derived catalog
M2 DataFusion session (target_partitions = 1, tracked memory pool), IR↔Arrow type table, datagen → MemTable
M3 Pre-ASAP translators (13/13 scalar variants, 10/36 operators, 10/45 AggIntents) and arm A
M4 9 sketch UDAFs + 14 readout UDFs; post-ASAP translator over all 11 payloads; the maintenance/read splitter; arm B
M5 --runtime interp|datafusion, --no-split, per-phase timing, memory, per-node metrics attribution, refusal counts by reason class
M6 --compare-runtimes: same plan, same rows, both runtimes, accuracy asserted bit-identical
M7 Datagen specs and a sweep over the upstream SQL corpus (scripts/run_sql_corpus.py)

Each milestone was followed by a code review and a fix pass; those fixes are the non-milestone commits.

Results

  • Sketch bindings: 8 of 9 families give bit-identical readouts against ver 1 under the same seed. UnivMon FrequencyEntropy differs by exactly one ULP after the Binary state round trip on one of three test inputs; it is pinned, not hidden.
  • Cross-runtime accuracy: identical bit for bit wherever both runtimes produce a readout (ungrouped KLL across 5 seeds; all 8 groups of a Utf8-keyed KLL).
  • Interpreter cost: on pre-ASAP query time, the interpreter is 2.0x to 7.2x slower than DataFusion on the three reference queries.
  • Split vs no-split: bit-identical, compared at the Arrow buffer level including nested columns.
  • Upstream corpus (132 statements): 117 lower and plan; 73 of those contain no summary at all (whole-plan Fallback, upstream G1). 11 of the 44 summary-binding queries execute on DataFusion — 9 exact accumulators matching arm A bit for bit, and 2 KLL quantiles (worst relative value error 0.085 and 0.046). The other 33 refuse: 20 on Theta (not in asap_sketchlib), 13 on ColumnRef::SampleValue.
  • Zero corpus queries produce a cross-runtime comparison. The interpreter emits readouts only for SummaryEstimate nodes, and refuses most SQL plans outright (76 of its 114 refusals are a Fallback that is not a bare Scan).

Departures from PLAN.md §8

These were decided during implementation; each is worth a look.

  • Memory column. Defined as bytes each arm keeps between queries (memory_column: "bytes_kept_between_queries" in the record), not §8.7's formula. The pool peak is a transient working set, reads 0 for ungrouped sketch aggregates (DataFusion 43 reserves only the delta in Accumulator::size()), and is the identical number on both arms for grouped ones. All terms remain serialized separately.
  • SummaryFamilyType::Plain. Refused for constructed state, as §8.5.2 says, but admitted for declared schema fields: upstream builds state-table group-key fields as Plain(dtype), so a blanket refusal makes GROUP BY untranslatable.
  • asap_sketchlib stays unpinned. A rev pin produced a second copy of the crate, because asap-aware-mapping depends on the same repository without a rev. Cargo.lock and --locked already make the build reproducible.
  • Ingestion horizon. Upstream now wraps every instant selector in a TimeRange identical in shape to a user-written range selector. The injected one is identified by lowering twice against two declared intervals, never by its range value.
  • Plan corrections: exact quantile uses floor, not ceiling (matching score.rs); AggIntent has 45 variants, not 44; the state column sits at index by.len(), not 0.

Open questions

  • Only KLL consumes the seed. For the other 8 families, --seeds N builds N identical sketches, so a seed sweep has no variance to check a guarantee against. DataFusion readouts are therefore kept out of guarantee checking.
  • ver 1 as oracle. M6 argues for keeping it (it is the only PromQL executor, and it has the three-phase split). M7 shows it cannot serve as an oracle on the SQL corpus at present.
  • u64 columns are refused under --sql because §8.6 has no u64 row. hydra_columns_u64.yaml only worked before by being narrowed to Int64.
  • AggIntent::TopK is reachable from SQL (netflow q3/q4, COUNT ... ORDER BY ... LIMIT) and is currently classified PromqlOnly, which is wrong for a SQL query.

Upstream notes

Not filed anywhere; listed here for whoever owns ASAPPlanner.

  • asap-aware-mapping depends on asap_sketchlib without a rev (#451), so no downstream crate can pin the sketch implementation without duplicating it.
  • lower_promql_workload gives the injected ingestion horizon and a user-written range selector the same shape.
  • At ε = 0.01 the default cost model assigns Hll and Theta identical cost, so COUNT(DISTINCT) lands on Theta by enumeration order rather than by any cost decision.

Dependencies

DataFusion 43 / Arrow 53 enter the workspace through asap-frontend-sql. One consequence: arrow-arith 53.4.1 caps chrono below 0.4.40 for the whole workspace. zstd-sys/zstd-safe are held to versions compatible with parquet 53.

Verification

From a clean target/: cargo build --release, cargo test --workspace (660 passed, 0 failed), cargo fmt --all -- --check, cargo clippy --workspace --all-targets --all-features --locked -- -D warnings, and the corpus sweep.

🤖 Generated with Claude Code

GordonYuanyc and others added 30 commits September 23, 2026 00:32
Repin asap-types, asap-aware-mapping and asap-frontend-promql from 3c31338
to 2ec3fc8 and add asap-frontend-sql at the same rev, so one asap-types is
resolved and QueryExpr stays one type. asap_sketchlib moves from the 0.3.0
registry release to the bare git URL upstream itself depends on; the lock
now carries two copies (the workspace 0.2.2 registry pin and the git one)
instead of three. Two transitive pins moved to keep DataFusion 43 resolvable
alongside polars: zstd-safe 7.2.4 -> 7.2.1 (parquet 53.2 caps zstd-sys below
2.0.14) and arrow-arith 53.4.0 -> 53.4.1, which drags chrono back to 0.4.39.

Absorbed from the upstream diff:

- #447 deleted ExecutableOperator and the ExecutableDagNode.operator field.
  run::operator_name derives the name from the payload variant, spelled as
  the deleted enum was, so records and printed plans read the same.
  run::operators, record's NodeCost.operator and family, and the test
  helpers now go through it.
- #447 renamed WindowEdgeCompatibility's residual variant to
  RequiresAlignedPanePhaseOrExactWindowEdgeResidual. Its serde rename keeps
  the wire string, so the JSON is unchanged.
- #445 renamed GlobalSelection::materialize to assemble_selected_dag.
- #448 added compile_executable_dag_with_node_ids; plan.rs calls it and
  keeps the returned ExecutableNodeIdentityMap on Plan, which is the
  pre<->post pairing table G14 was going to reconstruct by hand.
- #417 replaced lower_promql with lower_promql_workload over a
  PlanningWorkload, and wraps every bare instant selector in a TimeRange
  carrying the declared ingestion interval. plan::lower_promql builds the
  workload of one; plan::ingestion_horizon_child names that wrapper, and
  the row source and the pre-ASAP interpreter see through exactly it. A
  TimeRange of any other range is still refused, and the wrapper is not
  charged as its own tree node.

The post-ASAP wire version went 1 -> 2, so the plan id of the section 0
quantile example changes (f3e0cc5615615490 -> b738dc8db0517315). Every other
number in that run -- node list, state bytes, per-seed readouts, rank
errors, claimed bound, memory ratio -- is unchanged.

ValueOperation and ExactOperation were already 9 variants and already
non_exhaustive at 3c31338, contrary to the plan's table; value.rs already
refuses their wildcard arms by name, so nothing changed there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`--sql` and `--query` are exclusive and one is required. A `--sql` query
is lowered by `asap_frontend_sql::lower_sql` over a catalog derived from
the same `--spec` file the rows come from, then planned through the path
the PromQL arm already uses. One current-thread tokio runtime, built once
per process, drives the front end's async DataFusion planning; nothing
else in the crate is async and no synchronous path moved.

`sql_type: timestamp_ms` is new on a datagen `ColumnSpec`. It is the only
way an `i64` column becomes `DataType::Timestamp` in the derived catalog:
`shift` and the monotonic rule do not make a number an instant.

DataFusion's planner wraps even a single unaliased aggregate in an
identity `Project`, so a SQL plan's root is a `Value` node over summary
state rather than over rows. A projection that changes nothing is a
pass-through there; anything else over a producer that holds state is
refused by name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
L0 of the ver 2 runtime, three seams and nothing else:

`df/session.rs` builds a `SessionContext` per seed — `target_partitions =
1`, a `TrackConsumersPool` over a `GreedyMemoryPool`, and an
`ExtensionPlanner` that refuses every user-defined node by name. A seed is
bound where the UDAFs are registered, so `--seeds N` is N sessions;
`SeedBoundFunctions` is the hook and hands back nothing today.
`refuse_unless_aggregates_are_single` walks a physical plan and refuses any
`AggregateExec` that did not collapse to `AggregateMode::Single`.

`df/schema.rs` is the one place the IR ↔ Arrow mapping lives, both
directions, plus `SummaryFamilyType`. A datagen `i64 + shift` column is an
`Int64` until a spec declares `timestamp_ms`.

`df/memtable.rs` turns a `GeneratedTable` into one `RecordBatch` and
registers it as a `MemTable`, so the executed table and the SQL catalog
come from the same spec.

`df/refusal.rs` carries the four reasons — `PromqlOnly`, `TimeAxis`,
`NoConstructor`, `Deferred{issue}` — that M3 and M4 will count.

`datafusion` resolves to the 43.0.0 / arrow 53.4.0 the SQL frontend already
pulled in; the lock gains no second copy.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Resolves the tokio dependency both milestones added: M2's feature set
(rt, rt-multi-thread, macros) is a superset of M1's (rt).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…range value

`lower_promql_workload` (upstream #417) wraps every bare instant selector in a
`TimeRange` carrying the declared ingestion interval, and a range selector the
query wrote lowers to exactly that shape — the two differ only in the range
value, so a value is not evidence of origin. `ingestion_horizon_child` peeled
on the value, so `max_over_time(cpu_cores[1s])` had its one-second window
discarded and would have answered over every row. Only the unrelated
`PerEntity` gate kept that from showing, so the bug was latent, not visible.

Lowering now answers the question once, where the provenance is: each PromQL
query is lowered a second time against a different declared interval. An
injected horizon tracks whichever interval was declared; a range the query
wrote is the same number both times; and one number cannot equal both. The
answer travels with the tree as `TimeRangeOrigin` and reaches every peel site,
which no longer looks at a range at all. A tree with no recorded origin — one
a test builds, one decoded from a document, one the SQL front end lowered —
peels nothing, so its `TimeRange` is refused by name as before. A workload
whose roots disagree is planned as `Unknown`, because CSE can move one root's
subtree into another root's DAG.

`selected_ranges` is exhaustive over `QueryExpr`, so an upstream variant that
can hold a `TimeRange` fails to compile here rather than hiding one from the
scan (PLAN.md 8.11's no-rewrite rule keeps this to reading, never editing).

The two peel sites now ask the same function: `exact.rs` at every node it
visits, `run.rs` at the one node it visits, since `resolve_fallback` accepts
nothing below a bare `Scan`. `rows::tests::fallback_scan_mut` asks it too,
instead of matching `TimeRange` itself, so a test can no longer pass on a peel
production would not do.

Lowering still declares 1s for the tree that is planned, so
`quantile(0.5, cpu_cores)` keeps plan id b738dc8db0517315 byte for byte.

Also renames `sql_count_distinct_offers_hll_first_and_the_cost_model_takes_theta`
to say what upstream actually does: `DefaultCostModel::rank_candidates` is the
identity and every `Sketch` family costs the same, so nothing prefers Theta —
the test pins where an indifferent selection lands today.

Brings these files up to `cargo fmt`, which M2 deferred to avoid a conflict.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This is the one git dependency planeval left unpinned while the four
ASAPPlanner crates are rev-pinned, and it is the crate whose code decides the
numbers ver 1 now serves as the oracle for, so it should not track a moving
default branch.

The lock does not merely gain a rev: `asap-aware-mapping` at 2ec3fc8 depends
on the same repository with no rev (upstream #451 removed its pin), and cargo
treats `git+URL` and `git+URL?rev=` as two sources, so the graph now carries
asap_sketchlib 0.3.0 twice and links two copies of every sketch. Both resolve
to a66fad6 today, so no number moves. A `[patch]` cannot unify them — cargo
refuses a patch that points at the same URL — so the durable fix is upstream
pinning its own dependency.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…laration

M1 added `ColumnSpec::sql_type` and M2 added `DeclaredSqlType`, and each read
the datagen `data_type` strings with its own match, so the two directions
disagreed in two ways that running the binary showed:
`planeval_sql_metrics.yaml`'s `ts` was `Timestamp` in the IR catalog and
`Int64` in the Arrow table, because `rendering_sql_types` handed back
all-defaults regardless of what the spec declared; and `sql.rs` mapped
`u64 -> Int64`, the lossy guess PLAN.md 8.6 leaves out on purpose, while the
Arrow side rendered `UInt64`.

`df::schema::declared_columns(&TableDescription)` is now the single place a
spec's `sql_type` becomes a `DeclaredSqlType`, in `column_spec` order, and it
carries nullability too, which both sides used to hardcode and so agreed on by
luck. `sql.rs::column_type` is gone: the catalog type is
`ir_type(generated_column_arrow_type(..))` over that same declaration, so the
two directions cannot disagree by construction. `column_rendering` names the
rendering a `data_type` spelling selects and is pinned against
`ColumnData::kind` in both directions, so the type decision itself stays in
one exhaustive match.

Consequence, deliberately not papered over: `u64` has no row in 8.6's type
table, so `ir_type(UInt64)` refuses and a spec with a `u64` column is refused
by name under `--sql` (`hydra_columns_u64.yaml` works today, wrongly, by being
narrowed to `Int64`). The Arrow side still renders it unsigned.

Also fixes `summary_arrow_type`: `ExactAggregate(Sum)` returned the raw input
type while `ir_type` widens `Int8/16/32 -> Int64` and DataFusion's `sum` fills
the column at the widened width, so a state column could be declared narrower
than what is written into it. `Min`/`Max` keep their input's type but must now
have one the table covers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`ExecutableOperatorPayload` is not `#[non_exhaustive]`, and PLAN.md 8.3
discipline 1 names it as one of the enums this crate must not wildcard: an
upstream twelfth variant has to break the build here rather than fall into a
catch-all that silently reports no summary family for it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`identity_over` refused any `ProjectItem` carrying an alias, so
`SELECT approx_percentile_cont(latency, 0.99) FROM metrics` ran while the same
query with `AS p99` was refused. The plan for it is a pure rename —
`ProjectItem { alias: "p99", expr: Column(0) }` — no data moves, nothing is
dropped, and the answer is read off the `SummaryEstimate` regardless. Most of
8.8's M7 corpus aliases its projected aggregates, so this would have taken the
corpus out.

The length check and the `Column(i) == i` check stay: those are what stop a
reorder or a drop, and the test pins all four cases.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`.github/workflows/rust.yml` gates on clippy with `-D warnings`, and
`len() > 0` trips `clippy::len_zero`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Pinning by rev while asap-aware-mapping at 2ec3fc8 names the same repository
with no rev made cargo treat the two as different sources, so the graph carried
asap_sketchlib 0.3.0 twice and linked two copies of every sketch — the opposite
of what M0 set out to do when it brought the count from three down to two.

Reproducibility was the reason for the pin, and Cargo.lock already provides it:
the lock is committed, it names the exact commit (a66fad6), and CI resolves with
--locked. The pin only adds protection against a deliberate cargo update, which
is not worth a duplicated sketch implementation. Upstream re-pinning its own
dependency (undoing #451) is what would let us pin without the duplicate.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
SBT-1 rebound as nine `AggregateUDFImpl`s sharing one generic
`SketchAccumulator<S: SketchBinding>`, plus one `ScalarUDFImpl` for each of
the fourteen legal `(SketchAlgorithm, SketchQuery)` pairs. State crosses as
`ScalarValue::Binary`; `Accumulator::size()` reports the sketch footprint, so
DataFusion's memory pool charges the query for it.

`Theta` refuses `NoConstructor` and is not answered with HLL. The parameter
checks are the ver 1 ones, reached through `handle::check_bindable` rather
than restated, and the footprint helpers in `handle.rs` are now shared so both
runtimes compute the same bytes from the same code. New at translation time:
the four count-matrix families refuse a `weight_domain` that carries no
non-negativity proof, instead of discovering a signed weight at the row that
holds it.

Eight of the nine families read out bit-identically against the ver 1 oracle
under the same seed. UnivMon's `Cardinality` and `FrequencyL2` match too;
its `FrequencyEntropy` matches before serialization and shifts by one unit in
the last place after the state round trip, which is pinned by its own test.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Three translators, each an exhaustive match over the upstream enum, each
refusal carrying one of the four reasons M2 defined.

`df/scalar.rs` takes the 13 scalar variants to a DataFusion `Expr` and refuses
the 23 operator variants as `NoConstructor`: upstream #205 merged the two
sub-languages into one enum and dropped the type-level split, so the split is
enforced here instead. `ColumnScope` resolves a `ColumnId` by position in the
input plan's schema rather than by name, which is what a positional column
reference means and what keeps it correct under the renames a projection does.

`df/agg_intent.rs` takes 10 of the 45 measures to an aggregate `Expr`. The
pre-ASAP arm means the query does not approximate, so `Quantile` ignores its
`accuracy` and becomes an exact quantile: `array_agg` filtered to the non-null
rows, then `array_element(array_sort(..), rank)` in a projection above the
reduction, since a scalar over an aggregate cannot sit in the aggregate itself.
`LoweredMeasure` carries that pair. The rank is `floor(q * n) + 1`, clamped to
`n`, which is `score.rs::exact_quantile_sorted`'s `min(floor(q * n), n - 1)`
written one-based; ties fall out of the position, as there. Arrow's float
comparison is `total_cmp`, so `array_sort` orders a `Float64` column exactly as
ver 1's `sort_by(f64::total_cmp)` does. An empty group answers NULL rather than
sorting a null list, which `array_sort` reports as an error.

`df/pre_asap.rs` takes 10 of the 36 variants to a `LogicalPlan`. `Aggregate`
accepts `having`, which becomes a `Filter` over the reduced rows; SQL's HAVING
in fact reaches us as its own `Filter` node, so the field is exercised by a
hand-built tree. `Sort` with a non-empty `partition_by` is refused: a
partitioned order only means anything together with the `Limit` above it, the
tree carries no coupling between the two, and translating the order alone
reports a plausible wrong answer. `Scan` checks the bound schema against the
registered table column by column, on name, type and nullability.

`df/pre_asap_arm.rs` runs a lowered plan on an M2 `SeedSession` through
`single_mode_physical_plan`, so every aggregation an answer comes from is
asserted to be one `AggregateMode::Single` stage rather than a Partial/Final
pair whose merge order the answer would depend on.

Sixteen corpus queries read the same on both arms, bit for bit. Three
differences, recorded rather than reconciled:

- An `Int64` sum past `i64::MAX` wraps to `i64::MIN` in DataFusion 43 where
  ver 1 folds through an `i128` and reports the overflow.
- An exact quantile keeps its input's type where ver 1 widens to `Float64`,
  because ver 1 retains the column as `f64` weights. The values agree.
- A NULL in a reduced column cannot be reached from ver 1 at all: its row
  source is a `GeneratedTable`, whose columns have no null representation.

`sql.rs` grows `lower_sql_root_async`, with the blocking entry point as a thin
wrapper over it, because the process-wide runtime's `block_on` panics when the
caller is already inside a runtime, which every async test here is.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

# Conflicts:
#	aqpbm-planeval/src/df/memtable.rs
#	aqpbm-planeval/src/df/mod.rs
df/post_asap.rs folds the ExecutableDag into a HashMap<PostAsapNodeId,
LogicalPlan> in Kahn order taken from plan.rs, with every node's inputs
bucketed by EdgeRole. The eleven payloads each get an arm: Fallback hands its
subtree to df::pre_asap::lower, Value::Exact(Aggregate) goes through the same
reduce_measures that df::pre_asap::lower_aggregate calls, SummaryAgg and
SummaryEstimate go through M4a's sketch_aggregate_call and readout_call, and
the rest refuse with a reason. SummarySubtract, SummaryDelete and SummaryJoin
refuse permanently; Binary, CandidateTopK and RelationalJoin are deferred.
Each edge's grouping and window stamps are discharged before its plan is read.

df/split.rs finds the cuts: a MaintenanceTime edge feeding a ReadTime consumer.
The producer becomes a MemTable named __asap_state_<plan id>_<node id> whose
schema comes from the edge's intermediate_schema through df::schema. Multiple
cuts give multiple state tables, a plan with no ReadTime node is all read query
and is marked no_summary_in_plan, and a SummaryMerge above a cut refuses.

df/post_asap_arm.rs runs the maintenance queries, registers their state tables
and runs the read query, all through single_mode_physical_plan.
answer_without_split runs the same fold as one query; a test compares the two
answers buffer by buffer.

df/schema.rs splits the two questions the family answers: a constructed state
column's type, where Plain now refuses NoConstructor as §8.5.2 says, and a
declared schema field's type, where Plain is the ordinary group-key column the
splitter has to carry.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
… parameters

DdSketchBinding::from_bytes took `_params` where the other eight
bindings destructure and answer `mismatched_parameters`, so
asap_ddsketch_quantile(state, '{"Kll":{"k":269}}', query) deserialized
and answered instead of refusing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…d the accumulator size relationship

The entropy tolerance asserted `<= f64::EPSILON * expected.abs()`, a
magnitude-dependent relative bound, while its message claimed one unit
in the last place; it now counts representable values between the two
answers and a foreign-parameter case pins the refusal every binding now
gives. The divergence rested on one input, so two differently shaped
inputs join it. Accumulator::size() was only asserted to exceed the
footprint; the gap is now pinned as the accumulator struct itself, once
per group, alongside ver 1's footprint_bytes().

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…n the nullable Scan path

declared_columns hardcoded `nullable: false`, so the one source both
the catalog and the registered table read their nullability from
carried a literal rather than the spec. It now reads the datagen
rendering the spec's data_type names, through the same
column_rendering call the Arrow type goes through, with an exhaustive
match that breaks the build if datagen ever grows a rendering that can
be absent. check_leaf_schema is unchanged and now has both directions
of its nullability branch under test.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…at DataFusion has any

The per-seed session test asserted `!aggregate_functions().is_empty()`
under NoSeedBoundFunctions, which DataFusion's built-ins satisfy on
their own, so it would have passed with register_udaf a no-op. It now
names the built-in set, asserts our nine are absent without binding and
exactly those nine are added with it, and reads the seed off the
registered instance.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…4 boundary, and give the spread measures an oracle

same_number and same cast the Int64 side through f64, so above 2^53 the
comparison could not disagree: the exact quantile over [2^53+1, 1, 2, 3]
at q = 1 answers 9007199254740993 on arm A and 9007199254740992 on
ver 1, and the test asserted agreement. Both helpers now compare the
integer against the float's exact value, with a case either side of
2^53. StdDev, Variance and PearsonCorr are admitted but ver 1 refuses
them and no corpus query reaches them, so each is now pinned against
the same rows computed by hand. The NaN case gains Cardinality and five
more quantile positions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…emas and nulls

`column_bytes` walked only `ArrayData::buffers()`, so a `List<Struct<key,
count>>` — which is exactly how TopK reads out for CmsWithHeap,
CountSketchWithHeap and UnivMon (PLAN §8.5.5) — was compared on its
fingerprint, validity bitmap and i32 offsets alone. Two rankings over
same-length keys compared equal. It now recurses into `child_data()`,
which covers dictionary-encoded Utf8 by the same walk.

Zero batches short-circuited to `vec![] == vec![]`, so two empty answers
agreed without anyone looking at column count, names or types. The
comparison now starts from the physical schema, which exists whether or
not a batch does. Nullability stays out of it: a split run reads a state
table that carries the IR edge's own declaration and the whole-graph run
carries DataFusion's inference of it, and the rows' validity is compared
in the bytes either way.

`refuse_unless_answers_are_identical` was dead — the tests called
`column_bytes` and `assert_eq!`. It is now the entry point and the tests
go through it.

In the arm-B tests, `integers.value(row) as f64` made disagreement above
2^53 impossible, the same cast 84b96f3 removed from arm A; both sides now
compare as `Value` through `whole_equals_float`. Neither `scalars` nor
`keys` checked `is_null`, so a NULL read as `0` or `""` from the raw
buffer and matched on every side; nulls now compare as nulls.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`summary_schema_fields` built the state column as `declared.nullable ||
produced.is_nullable()`. `materialize` feeds the batch through
`RecordBatch::try_new`, which refuses a null in a non-nullable field, so
the `||` guaranteed that check never fired: a declared-NOT-NULL column
fed by a producer that emits nulls was admitted. For a sketch state
`estimate_udf` catches the null later; for an `ExactAggregate` state
nothing does — it flows through the read-time `Value::Project` into the
answer.

The declaration now wins, and the rows are what gets examined. Refusing
on a static disagreement instead was the other option and is wrong here:
DataFusion types every aggregate output nullable, so it would refuse the
grouped-sum plan that does emit no nulls. This keeps
`summary_schema_fields` consistent with `check_leaf_schema` in treating
the declaration as the contract, and differs from it only in checking
the contract against the data rather than against another declaration.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…schema

`Value::Exact(Aggregate)` passed `output_names` straight from the
payload. `reduce_measures` checks it against `by.keys().len() +
measures.len()`, and every other arm derives names via
`output_names(node)`, but nothing compared it to
`node.output_schema.fields.len()`. A disagreement would give the node a
plan of a different width than its declared schema, and the next
consumer's positional `scope.expr(position)` would read the wrong column
or run off the end.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`--runtime interp | datafusion` picks the engine; for one SQL query both now
emit the four numbers §8.7 defines. The DataFusion driver plans each arm once
for the answer it is scored on, then times one `collect` per `Pass` through
`aqpbm_core::measure` — one `Measurement` for the maintenance query, one for
the read query, `--runs` and `--warmup-runs` unchanged.

The memory number was a placeholder. `session.reserved_bytes()` read after
`collect` is always zero, because every operator drops its pool reservation as
the stream drains. `PeakReservationPool` wraps the `TrackConsumersPool` and
samples the total on every `grow` and `try_grow`, so the peak is taken while
the query runs. Both arms report it.

Each DAG node's projection and aggregate is aliased `__asap_n<id>_<field>`;
`df::metrics` walks the physical plan, charges each operator's
`elapsed_compute` to the node whose alias it carries, and sums the rest into
`engine_overhead_ns`. The per-node times are not promised to reconcile with
either wall clock and nothing asserts that they do.
`summary_schema_fields` now compares the edge's declared column name against
the produced name with the alias stripped, which keeps the check rather than
loosening it to position-only.

`refusals` carries the four reason classes plus `unclassified`. Ver 1's
refusals declare no reason class, so they are counted rather than sorted into
classes they never claimed; `total()` covers both and every record says which
runtime it came from.

`no_summary_in_plan` keyed on the absence of a read-time node, which is true
of a plan the planner left entirely in `Fallback` — it reported every such
plan as a summary advantage holding zero state. It keys on the cuts now.
The state `MemTable` is no longer registered by name: `scan_of` embeds the
provider, so the registration was dead and pinned every state table in the
session for the process.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
One plan, one set of rows, one seed, both runtimes. `runtimes.rs` runs
the interpreter and DataFusion over the same `Plan` and `RunConfig`,
pairs their readouts by `node/group/query`, and reports a difference
whenever an approximate or an exact answer disagrees by a single bit.
`--compare-runtimes` prints that comparison and exits non-zero when a
seed disagrees.

Readouts are paired as lists, not as one record per name. A runtime that
emits several readouts under one name has them reported as repeated
rather than overwritten: keeping the last would score one group's answer
against another group's truth.

The four numbers are reported per arm per runtime as separate rows, each
carrying whether the two runtimes' copies measure the same quantity.
Only the post-ASAP aggregate time and the pre-ASAP query time do. The
state bytes are an in-process footprint against a serialized Arrow
column, the pool peak exists on one runtime only, and the pre-ASAP input
bytes are one retained column against a four-column MemTable. The memory
rows are never summed into one number.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`Value::Exact(Aggregate)` was the one alias site of four that passed the
payload's own output names straight to `reduce_measures`, so the
`AggregateExec` it produced carried no `__asap_n<id>_` column and
`metrics.rs` charged its whole `elapsed_compute` to `engine_overhead_ns`.
It now names its node like every other aggregate and projection.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Seven findings in the path that produces the headline numbers, all of
them in how a run is scored and accounted rather than in how it runs.

Grouped accuracy, when the group key was not `Utf8`. `keyed_values` told
a key from a value by downcasting the Arrow column: every Int64/Float64/
UInt64 column was a value, so an integer group key became an "estimate"
whose row carried an empty `GroupKey`; every column that was neither
`Utf8` nor numeric rendered as `format!("{:?}", data_type())`, the same
string for every row; and the truth map was collected into a `HashMap`,
so colliding keys were last-wins. `SELECT bytes, approx_percentile_cont(
latency, 0.5) FROM metrics GROUP BY bytes` emitted 2000 readouts for
1000 rows and reported a worst error of 12.625 for a KLL at k=269.

The split is now structural. `answer_shape` reads the group keys off
each `SummaryAgg`'s `Reduce(by)` prefix and the value columns off the
node that produces them — a `SummaryEstimate`'s state column, or an
`ExactAggregate` `SummaryAgg`'s — and `answer_layout` matches those
names against the answer's schema, refusing a column that belongs to
neither. Keys render through arrow's own `ArrayFormatter`, so a
timestamp, a date, a boolean and a dictionary each spell themselves out.
Two rows that render to one key are refused rather than merged, a value
column that will not cast to `Float64` is refused rather than taken for
a key, and the two arms' group sets are compared before any row is
scored. The same query now reports a worst error of 0.971 over 1000
distinct groups.

Zero and multi-estimate plans. `compare_answers` destructured the
estimate list into exactly one node and returned no readouts otherwise,
so the grouped SUM's `ExactAggregate(Sum)` answer was never compared to
the pre-ASAP arm's and a wrong grouped sum would have gone unnoticed.
Every value column is now scored against its own arm-A column, whatever
produced it; `Readout::query` is `None` for a value no sketch estimated,
which the record spells `ExactAggregateValue`.

The memory column. `Arm::memory_bytes` summed the persistent state with
the engine's transient pool peak. On the grouped SUM the peak is
3,705,856 B on both arms — the same number — and a term equal on both
sides does not cancel in a ratio, it dominates the denominator: 895x
read as 3.1x. The column is now the bytes each arm has to keep between
queries, the summary state against the source table, and says so in the
record as `memory_column`. Each phase's pool peak is still serialized,
under the phase that took it: `maintenance_peak_reserved_bytes`,
`read_peak_reserved_bytes` (computed since M5 and until now dropped) and
`evaluate_peak_reserved_bytes`, so anyone can recompute the other
definition and see that arm A's peak covers a whole query while arm B's
covers maintenance alone.

`no_summary_in_plan`. The splitter has set it since M4 and nothing
carried it out; a plan the planner left whole emitted a `query_time`
ratio near 1.0 and an `accuracy` near 0 with nothing marking that arm B
was arm A. It is on `RunOutcome` and `PlanEvalRecord` now, and the
interpreter answers the same question through `split::no_summary_in_plan`.

`NodeCost.family` read `output_schema.fields.first()`, which is the
first group key on any grouped plan: `GROUP BY service` reported
`Plain(Utf8)`. It reads the family out of the payload that binds it.

`--no-verify` was inert on `--runtime datafusion`: the exact arm was
gated on `pre_asap` alone. The arm still runs and is still timed, since
it is also the baseline the ratios divide by, but its answer is no
longer taken as ground truth.

`rows_emitted` was a copy of `rows_scanned` on this path while the
interpreter reports rows that passed the leaf predicates. It is
`Option<u64>` and `None` here rather than two quantities under one name.

A `collect` that failed mid-timing was swallowed, and a near-zero
elapsed with full `work` was recorded as a real measurement. Both timing
helpers now fail the run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
GordonYuanyc and others added 17 commits September 23, 2026 07:12
…the sweep

Under `--jsonl` a refusal printed `REFUSED ...` to stdout, then a bare
`RefusalCounts` with no `schema_version`, `runtime` or `plan_id`, then
bailed with exit 1. A sweep piping the stream got an unparseable line,
an anonymous object and a dead process on the first refused query.

The prose goes to stderr, stdout gets one `RefusedPlanRecord` — schema
version, runtime, plan id, query, seed, counts and the refusal strings —
and the seed loop runs on. The `bail!` that reported "{} of the plan's
nodes were refused" while counting refusals rather than nodes is gone
with it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

# Conflicts:
#	aqpbm-planeval/src/main.rs
Four datagen specs, one per upstream corpus table, each declaring only the
columns its SQL references: netflow_table, packets, lineitem, raw_samples.
`scripts/run_sql_corpus.py` drives them through the M5 `--runtime` driver once
per runtime per query and writes one JSONL row per query; `scripts/report_sql_corpus.py`
turns that into the per-query table and the counts by reason class.

132 statements: 117 lower and plan, 15 stop at lowering (10 composite
COUNT(DISTINCT), 5 o11y ClickHouse map queries). 73 of the 117 hold no summary
at all and run as arm A. 44 bind a summary; 11 of those execute -- 9 exact
accumulators and 2 KLL. DataFusion refuses 48 by class: 20 no_constructor
(Theta), 15 promql_only, 13 deferred. The interpreter refuses 129 of 132, so
the corpus produced no cross-runtime accuracy comparison.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…ract

The sweep was written when a refused plan printed `REFUSED ...` prose on stdout
and exited non-zero. The fix pass that followed moved the prose to stderr, put a
RefusedPlanRecord on stdout and made the process exit 0 so a sweep survives a
refused query. `refusals_in`/`counts_in` scraped stdout for prose that is no
longer there, `record_in` accepted the refusal record as a run record, and every
refused query was scored as having run: 117 both_runtimes_ran against 15
plan_refused, with the whole DataFusion reason-class table reduced to nothing.

Both scripts now parse stdout as JSON and classify each object by its key set --
plan-eval record, refused-plan record, readout guarantee -- and take the reason
classes from the record's own `refusals` counts, including `unclassified` for
the interpreter arm, which declares no reason class. `arm_a_runs`/`arm_b_runs`
come from the phases the record's `pre_asap` and `approximate` arms carry
instead of a text heuristic, and read `-` where no run record exists at all.
A planning diagnostic is read as the whole block from its `planeval:` line on,
because a multi-line statement puts the lowering marker past the first line.

Nothing defaults to "ran" any more. A stdout line that is not JSON, a JSON
object whose keys match no known record, an exit 0 that produces no record, and
refusal strings that do not tally with the record's counts are each an error
naming the query; the sweep records the query as unreadable, keeps going and
exits non-zero.

Corrected on the current tip: 132 statements, 117 lower and plan, 15 stop at
lowering. DataFusion runs 58 and refuses 59 -- no_constructor 31, promql_only
15, deferred 13, time_axis 0. The interpreter runs 3 and refuses 114, 182
refusals, all unclassified. Still no cross-runtime accuracy comparison: all 117
plans root a Fallback, and the two queries both runtimes run are bare
projections with no readout.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`answer_shape` registered a value owner only from a `SummaryEstimate` or
`SummaryAgg(ExactAggregate)` node's own `output_schema`, so
`SELECT srcip, MAX(pkt_len) AS max_pkt_len ... GROUP BY srcip` refused
`no_constructor`: the answer column `max_pkt_len` is declared by the
downstream `Value{Project}` that carries the SQL alias, and the walk
never looked there. Every aggregate in the upstream SQL corpus is
aliased, so all 44 summary-binding queries refused on the DataFusion arm.

The walk now runs the plan's topological order and gives every node's
output columns a role — a group key, a value owned by the summary node
that computed it, or unattributed. A `Value{Project}` item that is a
bare column reference carries its input column's role up under the new
name; `Filter`, `Sort`, `Limit` and `FinalizeExactAccumulator` carry
theirs through positionally. A projected column that computes something
owns nothing and is still refused, so an unattributed value column
cannot be scored against the wrong arm-A column.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`packets/13` (`SELECT SUM(pkt_len) AS total_bytes FROM packets`) runs on
the interpreter, puts its `ExactAggregate(Sum)` node in arm B, and used
to emit `verified: true` with `readouts: []` — timing and memory for an
answer nothing compared. The interpreter probes only `SummaryEstimate`
nodes, so a plan whose answer is an exact accumulator has no readout to
score, and the boolean could not tell that apart from a scored run.

`verified: bool` is replaced by `answer_check`, which is one of
`scored_against_exact`, `no_readout_compared` and `exact_arm_did_not_run`.
The pair that misled is now unrepresentable, and the field is renamed so
a reader still testing the old boolean fails rather than reading a
string as truthy. Record schema version 8 -> 9. The corpus sweep carries
the value through per runtime and refuses a record that names none of
the three.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A statement that failed `plan_sql` left an anyhow line on stderr and
exit 1, so the only way to tell "does not lower" from "lowers but does
not plan" was to substring-match `planning failed: lower ` in that
prose — the last place the corpus sweep depended on wording, and the
cause of one 10/5-instead-of-15/0 mis-split.

`EvalError::Planning` now carries a `PlanningStage` beside its detail:
catalog, lower, search, compile or validate. A failure prints an
`UnplannedQueryRecord` on stdout — the query, the stage, the detail —
the way a node refusal already prints a `RefusedPlanRecord`, and still
exits 1 with the prose on stderr. The sweep reads the record: `lowers`
is now "the stage it reached is past lowering", not a substring test.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Drop the PromQL front end: `--query`, `--csv`, `plan_promql*`,
`lower_promql*`, `run_promql`, and the `TimeRangeOrigin` machinery that
lowered each query twice to tell the injected ingestion horizon from a
user-written range. `--sql` and `--spec` are now required, and the
interpreter's tests plan their fixtures from SQL instead of PromQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A Refusal raised during physical planning or execution (an accumulator
refusing a row, a readout refusing a state, the extension planner)
reaches the caller as DataFusionError::External, and SessionError
wrapped it as an opaque DataFusion error, so the run ended as a
RowSource failure with no RefusedPlanRecord and no reason class.
SessionError now walks the error's source chain and keeps the Refusal;
an ingest refusal is routed the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DataFusion scores each value column of an exact accumulator against its
own pre-ASAP arm, and the interpreter emits a readout only for a
SummaryEstimate. The one-sided pair counted as a ReadoutCount
difference, so every such plan exited with "the two runtimes read
different answers". A pair only DataFusion can produce is now reported
as having nothing to compare rather than as a disagreement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ORDER BY ... LIMIT or HAVING over a sketch estimate can legitimately
select different groups than the exact arm does. compare_answers turned
any difference in the two group sets into a no_constructor refusal of
the whole run, after every timed pass had already run, so a genuine
approximation error was reported as a missing constructor. Each group
only one arm answers is now a readout whose observed error says which
arm left it out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The top-k readouts (CMS with heap, CountSketch with heap, UnivMon)
return List<Struct<key, count>>, and keyed_rows cast every value column
to Float64, so any plan ending in a TopK readout was refused after it
had executed, even with --no-verify. A list column is now read into
Answer::Ranked and scored against the pre-ASAP arm's ranking by top-k
membership.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SketchQuery::PointCount carries its item as a string, so both runtimes
look it up as DataInput::Str, while an Int64 or Float64 item column is
inserted as DataInput::I64 or F64. The lookup hashed into another
item's counters and returned collision noise with no error. Both the
interpreter's readout resolution and the DataFusion translator now
refuse the readout when the producer's item column is not Utf8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Only Count-Min refused the insert that would push its ingested total
past i32::MAX. CountSketch, Count-Min with heap and CountSketch with
heap checked each row's weight alone, so a hot key could wrap its
counters and publish a negative or tiny estimate with no refusal. The
same cumulative check now covers all four on both runtimes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The state table took each column's nullability from the edge's
SummarySchema, and upstream declares an exact SUM/MIN/MAX NOT NULL. An
ungrouped exact aggregate over no rows is NULL in SQL, so
RecordBatch::try_new rejected the maintenance output and the run ended
as a RowSource error. An exact-accumulator column the query can leave
NULL is now nullable; sketch state keeps the declared NOT NULL check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
df::post_asap::payload_name repeated run::operator_name arm for arm, and
split() recomputed no_summary_in_plan as `cuts.is_empty()`, so the two
runtimes' records could drift apart on the same plan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant