Skip to content

fix(query): COUNT(*) counts joined rows, not distinct subjects, on an anchored star - #1706

Merged
aaj3f merged 10 commits into
mainfrom
fix/generic-count-star-row-multiplicity
Aug 28, 2026
Merged

aaj3f merged 10 commits into
mainfrom
fix/generic-count-star-row-multiplicity

Conversation

@aaj3f

@aaj3f aaj3f commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1700

The trap first, because it's the opposite of what we usually assume

On the reported shape the fast path was the correct one and the generic pipeline was wrong — COUNT(*) over { ?s a ex:Gadget . ?s ex:tag ?o } gave 5 normally and 2 under FLUREE_DISABLE_QUERY_FAST_PATHS. That inverts our usual polarity, and since the kill switch is the oracle every fast-path suite establishes ground truth against, the instinct to "fix toward the kill-switch answer" would have taken the correct lane and broken it. Flagging it up front because it's the easiest thing to get backwards while reading this diff.

It turned out not to be an aggregate defect at all. The rows were already gone before the aggregate ran — SELECT ?s WHERE { ?s a ex:Gadget . ?s ex:tag ?o } returns 2 rows at HEAD where SPARQL bag semantics want 5, and it does that on both lanes.

Mechanism

PropertyJoinOperator demotes a predicate to an existence-only (semijoin) constraint when its object variable is absent from the block's needed-vars set — property_join.rs:424, emit_object. It records that the subject has some object under that predicate (entry.1 |= 1u64 << pred_idx, property_join.rs:1060) and drops the per-subject object list. That's a set operation, so a subject's N objects collapse to one row.

It was applied unconditionally, at both call sites (where_plan.rs:1260 and where_plan.rs:3138). COUNT(*) names no variables, so ?o is in nothing's needed set, the demotion fires, and the count comes back as the number of qualifying subjects.

The sequential chain already has exactly the right gate for this and the property-join path just never consulted it: where_dedup_safe (operator_tree.rs:3172) asserts that nothing downstream can observe WHERE-output row multiplicity, and it's what licenses the chain's early DistinctOperator at where_plan.rs:3080. AggregateFn::CountAll.duplicate_insensitive() is already false, so the license was sitting right there, correctly computed, unread. The fix threads it into property_join_needed_vars and, when the license is absent, pins every variable object in the block as needed.

Reusing where_dedup_safe rather than minting a second license is the load-bearing design decision here, because it makes the fix sound by reduction: on a block whose schema has already had the object var pruned, the demotion collapses exactly the rows an explicit DistinctOperator over that schema would collapse, so "demotion is sound" follows from "early dedup is sound" with no new argument needed. The doc comment at where_plan.rs:1243 is the fullest statement of that invariant.

Bound objects are untouched — ?s a ex:Gadget matches at most one flake per subject, so existence-only already carries its multiplicity exactly. And SELECT DISTINCT ?s / COUNT(DISTINCT ?s) still get the pruned plan; this narrows the pruning rather than disabling it, and there's a unit test pinning each direction so it can't quietly degrade into a blanket disable.

It's meaningfully worse than the issue reported, and mostly in the oracle's blind spot

Reverting the one-line license check and re-running the new test gives the damage report. The shapes where the two lanes disagreed — the only ones a differential oracle could ever have seen — are just the two where a COUNT(*) fast path existed and got it right:

shape fast generic truth
COUNT(*) { ?s a Gadget . ?s tag ?o } 5 2 5
COUNT(*) { ?s a Widget . ?s name ?n } 4 3 4

Everything else was wrong identically on both lanes, so fast-vs-generic was green on all of it:

shape both lanes truth
SELECT ?s { ?s a Gadget . ?s tag ?o } 2 rows 5
SELECT ?s (COUNT(*)) … GROUP BY ?s 1, 1 3, 2
COUNT(*) { ?s a Gadget . ?s tag ?o . ?s code ?c } 2 8

That last one is the one I'd point at hardest — a 4x undercount on a two-variable-object star, invisible to the oracle, and 8 isn't the row count of either predicate alone so nothing else would have caught it by coincidence either. COUNT(?o) was right all along, but only by accident: naming ?o in the aggregate puts it in the needed set, so the demotion never fired.

The oracle-test grep

Went looking for existing assertions that pinned COUNT(*) through the kill switch, on the theory that any of them would have been measuring against a broken reference. Nothing was — the full fluree-db-api suite (43 test binaries) and the W3C SPARQL conformance suite are green with zero expectation edits. Worth saying why, since "no test changed" is also what a vacuous check looks like:

  • it_differential_fastpath.rs is the fast-vs-generic harness, and its only COUNT(*) case is the single-triple { ?s ?p ?o } — no star, no unread object var. Its one star with an unread object var (?s bsbm:productType ?o . ?s bsbm:label ?l, :428) has no bound object and no object bounds, so has_property_join_anchor is false and it never reaches the property join at all.
  • it_repeated_var_fast_path_guards.rs does assert COUNT(*) on both lanes, but against hand-computed values rather than against the other lane, and its star cases repeat a variable — which makes analyze_property_join set object_vars_distinct = false and decline. So it was correct, and correct for a reason that survives this change.
  • The W3C suite is memory-backed throughout, so it never indexes and never reaches this path — the same blind spot we hit in fix(query): correct three fast paths that diverged from the generic pipeline #1666's neighbourhood.

So the honest read is that the wrong answers here were entirely unpinned rather than mispinned, which is the more likely explanation for how it survived. I'd rather report that plainly than claim a cleanup I didn't have to do.

What the fix costs on ordinary query shapes

The fan-out fixture numbers further down are deliberately adversarial; this table is the boring case. 2,000 subjects (name/email single-valued, tag ×8), bulk-imported and indexed, min of 7, debug build both sides, the two sides differing only in where_plan.rs (base vs this branch) so it isolates exactly the planner change. Times are end-to-end — query plus SPARQL-JSON serialization — so C's multiple includes serializing the 8x answer rows, which is real user-visible cost, not planner overhead:

shape main branch rows
A SELECT ?s ?name { ?s a Person . ?s name ?name } 33.8 ms 33.4 ms 2000 → 2000
B A + ?s email ?e — unused, single-valued 33.7 ms 34.8 ms 2000 → 2000
C A + ?s tag ?t — unused, multi-valued x8 36.3 ms 215.9 ms 2000 → 16000
D SELECT DISTINCT over C 38.5 ms 38.8 ms 2000 → 2000
CONSTRUCT { ?s flag "y" } over C's star 30.1 ms 30.5 ms graph: 2000 nodes both
ASK over C's star 10.6 ms 10.4 ms true both

A and D flat is the narrowing working — this didn't become a blanket disable, and D still takes the pruned plan. B is the only true regression shape: the unused single-valued ?e is now carried as a real column through the join instead of being reduced to an existence bit — same 2,000 rows, one extra column, ~3% here and possibly noise, but it's the shape to watch since it pays without its answer changing. C is not like-for-like: main returned 2,000 rows where SPARQL requires 16,000, so the branch does 8x the work for 5.9x the time and per-row cost falls, 18.2 → 13.5 µs/row end-to-end. The blast radius on shapes whose answers were already correct is roughly nil, and where the answer changed, the added time buys the rows that were owed.

On the cost, and why CONSTRUCT and ASK get the license back

For SELECT ?s the extra rows are answer rows, and that half of the trade is well made — measured, the per-answer-row cost actually falls from 48 µs to 9.5 µs. But where_dedup_safe is sound without being tight, and the slack lands on the outputs that aren't solution bags at all.

QueryOutput::restriction() returns None for every non-Select output (ir/query.rs:159), so the license reads false for all CONSTRUCT and ASK queries. A CONSTRUCT result is an RDF graph and an ASK is a boolean, so for both, the extra rows are provably discarded.

CONSTRUCT. Measured on 3,000 subjects × 40 tags (120k pairs, indexed), min of 3, CONSTRUCT { ?s ex:flag "y" } WHERE { ?s a ex:Gadget . ?s ex:tag ?o }:

before the #1700 fix fix without the CONSTRUCT license fix as it stands
time 0.1464s 0.9026s 0.1380s
graph 3,000 nodes 3,000 nodes 3,000 nodes, same sha

Read the denominators carefully, because the 6.2x in that table is easy to misquote: against main, licensed CONSTRUCT is flat (0.1464s → 0.1380s). The 0.9026s middle column is what this correctness fix would have cost CONSTRUCT without the license — a state that never shipped. The license is damage control for the fix's own cost on graph outputs, not a speedup over the previous release, and the code comment at the license's unit test says exactly that so the number can't drift into a release note with the wrong denominator. SELECT DISTINCT ?s and COUNT(DISTINCT ?s) were flat across all three columns, which is what says this is the planner and not the box.

The obvious form of the narrowing — license every QueryOutput::Construct at the call site — has a hole in each direction, which is why it lives in a named helper instead: result_is_multiplicity_blind (operator_tree.rs:2367, consumed at :3190), with two exclusions that are load-bearing.

  • A template blank node is minted fresh per solution and shared only within a row, so distinct solutions build distinct triples and collapsing them changes the graph.
  • A LIMIT/OFFSET cuts the solution sequence before the template is instantiated, so collapsing rows first changes which solutions survive.

Both are unit-pinned in both directions. And bnode_vars is empty for every JSON-LD/FQL construct and every DESCRIBE per the field's own doc comment, so this recovers the whole non-SPARQL graph-producing surface rather than carving out one SPARQL shape.

ASK. The same reasoning covers ASK, and more simply: every formatter either reads solution-sequence emptiness and nothing else (format_ask in format/mod.rs, the boolean arm of sparql_xml::format) or rejects ASK outright (TSV/CSV, the streaming endpoint), so there's no blank-node caveat at all. Both surfaces already lower ASK with LIMIT 1 — lower_ask in fluree-db-sparql and the "ask" branch of the JSON-LD parser (parse/mod.rs:257) both set it — so the true case was already cheap-ish at execution time, but the plan still carried the full cartesian join, and PropertyJoinOperator does its per-predicate scans and per-subject object collection in open() where no LIMIT can reach. Granting ASK the license took two pieces:

  • an Ask arm in result_is_multiplicity_blind, which must tolerate LIMIT (a limit of any value preserves emptiness — LIMIT 0 is empty on both sides of the dedup — and both surfaces always plan ASK with one) and must exclude OFFSET (it counts rows off the front, so OFFSET 5 over six duplicates is non-empty while its deduped form is empty; no surface can currently produce that IR, the guard is for programmatic construction);
  • an empty needed-vars set for a licensed, modifier-free ASK in build_operator_tree_inner. ASK's referenced_vars() conservatively reports None, which the WHERE planner was reading as all vars needed — and needed vars are protected vars, which blocks the demotion regardless of the license. A licensed ASK needs no variable downstream (the output is emptiness), so it now gets the same empty set a constant-template CONSTRUCT already gets via compute_variable_deps; join and FILTER vars stay protected through their reference counts, and any modifier that could read a variable (grouping, ordering, post-VALUES) falls back to the conservative default.

The plan shape is pinned end-to-end (ask_over_a_fanout_star_plans_the_existence_only_join builds the full operator tree and asserts the object var is out of the schema; its offset twin asserts it stays in), and the fan-out fixture's integration test now runs ASK on both lanes and both surfaces in both truth directions. A result test alone cannot see this license — the boolean is identical either way — which is exactly why the plan-shape pin exists; the integration cases guard the other direction, that the license didn't break ASK's emptiness semantics where the demotion actually fires.

Measured honestly, the ASK win is real but bounded at these scales, because LIMIT 1 was already capping the materialization for the true case: ASK { ?s a Person . ?s tag ?t } end-to-end, min of 7, debug — 12.2 → 10.4 ms at 2,000 subjects ×8 (~15%), 54.1 → 41.5 ms at 3,000 ×40 (~23%, growing with fan-out; what the license removes is open()-side per-subject object-list collection and the first batch of product materialization, neither of which a LIMIT can reach). The control behaved: ASK { … FILTER(?t = "nope") } is flat across all states, because the FILTER reads ?t, ?t's reference count protects it, and the demotion correctly never fires — licensed or not.

The license's enumeration is a gate now, not a comment

The CONSTRUCT half of the license is the one part of this PR that removes rows, and it rests on an enumeration of output paths ("every serializer canonicalizes or rejects") that would fail silently if a new output path ever joined the set unclassified — the zero-column DistinctOperator bug below is proof the seam is live rather than theoretical. I considered splitting the optimization out so the correctness fix merges on its own risk profile, and decided the honest move is the opposite: keep it here and make the enumeration structural, so the risk is addressed by a gate rather than by distance.

every_output_format_collapses_or_rejects_construct (it_query_construct.rs) holds the classification in a macro whose match over OutputFormat has no wildcard arm — adding a variant stops the file compiling until the new path is classified — and the same identifier list drives the runtime loop, so a variant cannot be classified without also being tested. The test is behavioral, not documentary: it runs a CONSTRUCT whose WHERE provably still carries 12 duplicate solutions (asserted as a precondition, so the gate can't pass vacuously on an already-collapsed stream — a LIMIT keeps the query outside the license), then feeds the result to every format through format_results_string and asserts each one either collapses the duplicates to one triple per subject or errors. The streaming endpoint is the one path that doesn't route through there, so its rejection of CONSTRUCT and ASK is pinned separately (streaming_endpoint_keeps_rejecting_construct_and_ask, view/stream_query.rs) with a comment naming the license as the thing that breaks if it's ever lifted.

If a future format legitimately needs to stream CONSTRUCT without canonicalizing, the license itself has to change — and the gate failing is the reminder, instead of a wrong query result somewhere downstream.

Two output changes worth naming

Both are consequences of the correctness fix, both are what SPARQL requires, and neither was stated or pinned anywhere before. They're pinned now, and documented for users in docs/query/construct.md (new Solution Multiplicity: Blank Nodes and LIMIT section, including the subselect rewrite for preview-with-LIMIT — verified against the fan-out fixture).

  1. A blank-node CONSTRUCT template mints one blank per solution, not per subject. §16.2 instantiates the template once per solution and the sequence is a bag, so on this PR's own fixture the graph goes from 4 nodes / 2 blanks to 7 / 5. Measured both ways.
  2. CONSTRUCT … LIMIT n can return fewer triples. With the solution sequence correctly 40-deep per subject, LIMIT 10 now takes ten solutions off one subject where it used to take ten collapsed rows off ten subjects — 10 triples → 1 on the perf fixture. The old number came from slicing a solution sequence that was wrong; without an ORDER BY neither is more "correct" than the other under SPARQL, but it is a visible change, it's why the LIMIT guard above exists rather than being folded into the blank-node one, and it's the case the docs now spell out (preview-with-LIMIT is a common UI call, and it takes both barrels: excluded from the license and fewer triples than before).

A latent family of zero-column row-count bugs, surfaced by the above

A column-less Batch carries no row count through Batch::new (it reads the count off columns.first()), and the batch layer has a test pinning exactly that trap (test_batch_new_loses_len_for_empty_schema) — so every operator that rebuilds a batch column-by-column is a place a row count can silently vanish once a plan's WHERE schema prunes to zero columns. This PR found three of them, each caught by a different net, which is the strongest evidence in the whole diff that this seam is live rather than theoretical:

  1. DistinctOperator — caught by the existing api suite when the CONSTRUCT license made it reachable (sparql_construct_repeated_triple_collapses_in_both_serializations went to an empty graph). A fully-constant template — CONSTRUCT { <s> <p> "dup" } WHERE { ?s ?p ?o } — both licenses dedup and needs no WHERE variable, so the block prunes to an empty schema; the operator built a zero-row batch and its columns.first() … unwrap_or(true) guard read "all rows were duplicates" forever, swallowing the stream. Every row of a zero-column input is the empty tuple, so DISTINCT over N of them is exactly one row, or none when the child produced nothing. Fixed with Batch::empty_schema_with_len, in its own commit ahead of the one that makes it reachable, both directions pinned.
  2. LimitOperator — caught by the W3C suite the moment the ASK license went in: ask-7 (ASK { :x :p ?x }, three matches) came back false. The truncation branch rebuilds the batch column-by-column, so truncating a zero-column batch of 3 to LIMIT 1 produced a zero-row batch and format_ask read emptiness. This one is reachable from main today, no license required: CONSTRUCT { <s> <p> "dup" } WHERE { ?s ?p ?o } LIMIT 1 prunes the schema empty via compute_variable_deps (a constant template needs no variable — untouched, pre-existing behavior) and returns an empty graph whenever the WHERE matches more rows than the limit. Verified failing at this PR's own head before the fix; the plan for that query is identical on main.
  3. OffsetOperator — same rebuild in its partial-skip branch, same fix, found by reading the sibling operator after Limit fell. CONSTRUCT … OFFSET 2 over the pruned-empty schema dropped every surviving row.

All three now route zero-column batches through Batch::empty_schema_with_len, each with unit tests pinning both directions, plus an integration pin (constant_template_construct_with_limit_keeps_its_triple) covering the main-reachable LIMIT/OFFSET shapes end-to-end. None of the three was introduced here — a zero-column WHERE stage needs a consumer that needs no variable at all, and a wildcard SELECT reports None for its projection, which pins every variable — but the count going from one latent instance to three found is why the output-path enumeration above is a compiled gate and not a comment.

Tests

New it_count_star_row_multiplicity.rs (own binary — the kill switch is process-global). Both lanes, both surfaces, every expectation arithmetic on the fixture and never fast-vs-generic, precisely because the oracle was the broken side here. It now also carries the ASK cases (both truth directions, SPARQL + JSON-LD twins).

The fixture is multiplicity-bearing by construction and each shape is pinned alongside its distinct-subject count so the two numbers always differ — a single-object-per-subject fixture cannot tell a passing run from a failing one, which is presumably how this survived, so flatten this one and the subjects assertions fail rather than the file going quietly vacuous. I checked non-vacuity the direct way: revert where_plan.rs alone with the tests kept and 18 assertions fail across both lanes; restore it and all pass. The ASK license got the same treatment: with the Ask arm of result_is_multiplicity_blind stubbed to false, ask_over_a_fanout_star_plans_the_existence_only_join fails with the object var back in the schema and ask_licenses_where_dedup_including_under_its_own_limit fails on every licensed case; restored, all green. (The ASK result cases pass either way — the boolean can't see the plan — which is why the plan-shape tests exist.)

JSON-LD twins throughout, per the three-surface parity rule — both surfaces lower to the same IR, so a WHERE-planner defect reaches both, and the twins did in fact fail alongside the SPARQL cases before the fix.

Bench

This is a hot-path change that had no bench coverage in either direction, and the advisory per-PR job runs only query_overlay_matrix and query_hot_bsbm — neither a CONSTRUCT nor a star with an unprojected object — so neither the regression nor the recovery would have surfaced in CI.

New query_hot_fanout_star covers the shape: construct_blank_free (licensed — the regression guard), select_unprojected_object (not licensed — so the cost of correctness is tracked rather than rediscovered), and select_distinct as the control. Verified discriminating at tiny scale — 240 µs / 789 µs / 240 µs in case order — and the attribution matters: the two 240s are construct_blank_free and select_distinct, both on the pruned plan, and the 789 µs is select_unprojected_object — the SELECT cost of correctness at 8k pairs, the number this whole trade turns on. It grows with fan-out, which is why the case exists: a future optimization that carries multiplicity without materializing object bindings has a number to beat. Its own fixture because BSBM has no multi-valued same-subject predicate and adding one would move query_hot_bsbm's committed baseline for unrelated cases.

Registered, deliberately not gated — these are two separate things and the distinction is easy to misread, so stating it plainly. The bench is fully registered per the six-step workflow in docs/contributing/benches.md: a [[bench]] entry, a regression-budget.json entry under crates.fluree-db-api.query_hot_fanout_star (tiny 10 / small 5 / medium 3, copied from its query_hot_* siblings), and a row in the Current categories table. workspace_reconcile reconciles clean in both directions — 17 declared benches, zero unbudgeted, zero stale.

What it is not in is the gated per-PR run, which is two hardcoded cargo bench lines in ci.yml (query_overlay_matrix, query_hot_bsbm). Adding a third spends every PR's CI budget, which is a call that affects everyone rather than one I should make unilaterally — so its absence there is a decision, not an oversight. Say the word and I'll add the line in this PR. It isn't dead meanwhile: the nightly workflow compiles and smoke-runs every declared bench target, and bench-baseline compare reports a case with no baseline as a new scenario rather than a breach.

I got this wrong on the first push — I added the [[bench]] entry without the budget entry and reddened the test job. Two small things came out of fixing it, both folded in here. The Current categories table was missing query_hot_property_path (declared and budgeted since it shipped, just unlisted), which I added while editing that cell. And step 5 of the guide tells you to "leave the entries empty" when you have no baseline yet — but the reconciler tests !m.is_empty(), so an empty map fails the gate exactly as a missing one does. Corrected, with a pointer to cargo test -p fluree-bench-support --test workspace_reconcile, which is the cheap local gate that would have caught my mistake before CI did.

Gates

  • cargo test -p fluree-db-query — 1,436 lib + 60 across the integration binaries, green
  • cargo test -p fluree-db-api --features native — 43 binaries, zero failures
  • testsuite-sparql --test w3c_sparql — 36 registers green (and load-bearing this time: the two ASK registers went red against an intermediate state of the ASK license and caught the LimitOperator zero-column trap before it could ship)
  • cargo clippy -p fluree-db-query -p fluree-db-api --all-targets --no-deps --features native — clean (includes the new bench target)
  • cargo bench --bench query_hot_fanout_star -- --test — green
  • cargo test -p fluree-bench-support — green (workspace_reconcile still clean; no bench scenarios changed)
  • cargo fmt --all --check — clean, run last

aaj3f added 2 commits August 26, 2026 15:27
`PropertyJoinOperator` demotes a predicate to an existence-only (semijoin)
constraint when its object variable is absent from the block's needed-vars
set: it records that the subject has *some* object under that predicate and
drops the per-subject object list. That is a set operation, so it collapses a
subject's N objects down to a single row.

It was applied unconditionally. On `{ ?s a ex:Gadget . ?s ex:tag ?o }` — a
bound-object-anchored star whose object var nothing downstream reads — a
subject with three tags contributed one row, so `COUNT(*)` returned the number
of qualifying subjects rather than the number of joined rows.

The sequential chain already has the right gate for exactly this: its early
dedup fires only under `where_dedup_safe`, which asserts that nothing
downstream can observe WHERE-output row multiplicity. The property-join path
never consulted it. Thread it through both call sites and, when the license is
absent, pin every variable object in the block as needed so the block produces
its full cartesian product.

Bound objects are untouched — `?s a ex:Gadget` matches at most one flake per
subject, so existence-only already carries its multiplicity exactly. And a
dedup-safe consumer (`SELECT DISTINCT ?s`, `COUNT(DISTINCT ?s)`) still gets
the pruned plan; the two new unit tests pin both directions so the fix cannot
degrade into a blanket disable.

Refs #1700
…faces

Every expectation is arithmetic on the fixture, checked against both the
fast lane and the generic pipeline — never against each other.

That distinction is the point. `FLUREE_DISABLE_QUERY_FAST_PATHS` is this
repo's differential oracle, and on the reported shape the oracle was the
broken side: the `COUNT(*)` fast path answered 5 from index metadata while the
generic pipeline it gets checked against answered 2. A fast-vs-generic
comparison would have flagged the correct lane as the regression.

The fixture is multiplicity-bearing by construction and each shape is pinned
alongside its distinct-subject count, so the two numbers always differ. A
single-object-per-subject fixture cannot tell a passing run from a failing
one, which is presumably how this survived; flatten this one and the
`subjects` assertions fail rather than the file quietly going vacuous. The
two-variable-object case (3x2 + 2x1 = 8) is likewise not the row count of
either predicate alone.

Covers the grouped `COUNT(*)`, the bag-semantics row projections, an OPTIONAL
tail, a bound object (multiplicity 1, must stay collapsed), and the
dedup-safe consumers that must keep the pruned plan. JSON-LD twins throughout,
per the three-surface parity rule — both surfaces lower to the same IR, so a
WHERE-planner defect reaches both.

Own test binary: the kill switch is process-global.

Refs #1700
aaj3f added 4 commits August 26, 2026 18:08
A column-less `Batch` carries no row count through `Batch::new` — the count is
read off `columns.first()`, which is `None` — so the dedup path built a
zero-row batch and its `columns.first() … unwrap_or(true)` guard then read
"all rows were duplicates" on every batch and swallowed the entire stream.
`Batch::empty_schema_with_len` is the constructor that preserves a row count
without columns, and the batch layer already has tests pinning the trap
(`test_batch_new_loses_len_for_empty_schema`).

Every row of a zero-column input is the empty tuple, so DISTINCT over N of
them is exactly one row — one row total across the whole stream — or none when
the child produced nothing. Both directions are pinned.

Latent until now because a zero-column WHERE stage needs a consumer that both
licenses dedup and needs no variable at all, and no such shape reached it: a
wildcard SELECT reports `None` for its projection, which pins every variable.
The next commit makes it reachable.
`where_dedup_safe` was sound but not tight, and the slack landed on CONSTRUCT.
`QueryOutput::restriction()` returns `None` for every non-`Select` output, so
the license read false for all of them — yet a CONSTRUCT result is an RDF
graph, not a solution bag. Every output path enforces that or refuses the
query: the JSON-LD and RDF/XML serializers both call `Graph::canonicalize()`,
streaming JSON excludes CONSTRUCT from its eligibility check, and TSV, CSV,
SPARQL-Results XML and the streaming endpoint all reject it outright. So the
extra solutions were materialized and then discarded.

Measured on 3,000 subjects x 40 tags, min of 3: `CONSTRUCT { ?s ex:flag "y" }
WHERE { ?s a ex:Gadget . ?s ex:tag ?o }` ran 0.1464s before the #1700 fix and
0.9026s after, for a graph that is byte-identical at 3,000 nodes (same sha).
With the license it is back to 0.1380s. `SELECT DISTINCT ?s` and
`COUNT(DISTINCT ?s)` were flat across all three, which is what says this is
the planner and not the box.

Two exclusions, both load-bearing and both pinned:

* A template blank node is minted fresh per solution and shared only within a
  row, so distinct solutions build distinct triples and collapsing them
  changes the graph. `bnode_vars` is empty for every JSON-LD/FQL construct and
  every DESCRIBE, so this keeps the license for the whole non-SPARQL graph
  surface rather than carving out one SPARQL shape.
* `LIMIT`/`OFFSET` cut the solution sequence before the template is
  instantiated, so collapsing rows first changes which solutions survive.

Also pins the CONSTRUCT output change the #1700 fix introduced and did not
state: a blank-node template now mints one blank per solution rather than per
subject (4 nodes / 2 blanks to 7 / 5 on this fixture). That is what SPARQL 1.1
section 16.2 requires — the template is instantiated once per solution — but
nothing asserted it before.
The shape `PropertyJoinOperator`'s semijoin demotion exists to serve, and the
shape #1700 changed the plan for, had no bench coverage in either direction —
which is how a 6.7x CONSTRUCT regression could land and be caught only by
reading the diff. The per-PR advisory job runs `query_overlay_matrix` and
`query_hot_bsbm`; neither is a CONSTRUCT nor a star with an unprojected object.

Three cases over one fan-out fixture:

* `construct_blank_free` — the demotion is licensed, so this is the regression
  guard. Lose the license and it materializes the full cartesian product to
  produce a byte-identical graph.
* `select_unprojected_object` — the demotion is not licensed; every fan-out row
  is an answer row. Deliberately the expensive one, so the cost of correctness
  is tracked rather than rediscovered.
* `select_distinct` — the control. If all three move together the run is
  measuring the box.

Verified discriminating at tiny scale (200 subjects x 40 tags):
construct_blank_free 240us and select_distinct alongside it, against
select_unprojected_object at 789us.

Its own fixture on purpose: BSBM has no multi-valued same-subject predicate,
and adding one would move `query_hot_bsbm`'s committed baseline for unrelated
cases. Not wired into the gated per-PR list — that is a CI-budget call rather
than mine to make; `compare` reports unknown cases as new scenarios and does
not treat them as a breach, and the nightly workflow already compiles and
smoke-runs every bench target.
Step 5 of the six-step workflow, which I skipped — `workspace_reconcile`
rejects a `[[bench]]` with no `crates.<crate>.<bench>` entry, on the reasoning
that an unbudgeted bench means nobody thought about its budget. Numbers copy
the other `query_hot_*` benches (tiny 10 / small 5 / medium 3); they are
placeholders until a nightly run lands a baseline, same as every other entry
in the file.

Registering a budget does not add the bench to the gated per-PR run — that is
two hardcoded `cargo bench` lines in `ci.yml`, and this one is deliberately
not among them.

Also step 6, the `Current categories` table: adds this bench under `query_hot`
and, since that cell was already being edited, `query_hot_property_path`,
which has been declared and budgeted but unlisted.

And corrects step 5's own advice. It told contributors to "leave the entries
empty" when they have no baseline yet, but the reconciler tests
`!m.is_empty()`, so an empty map fails the gate exactly as a missing one does
rather than falling back to `default_budget_pct`. Points at the local command
that catches this before a CI round-trip.

@bplatz bplatz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving — the correctness argument holds and I verified it independently rather than reading it.

Reverted where_plan.rs alone with the new test kept: 18 assertions fail across both lanes. The lane split is exactly as described — COUNT(*) {gadget/tag} fails only on generic (the fast path was right), while the two-object cartesian is 2 vs 8 identically on both, so the differential oracle was structurally blind to it. I re-derived the fixture arithmetic by hand too (5, 8, 6, 4) rather than trusting the expectations. grp_query 422/422 green on the branch.

Reusing where_dedup_safe instead of minting a second license is the right call and makes the whole thing sound by reduction. Plumbing checked: one producer, both property-join sites, and the only other construction defaults to false. No hole. The zero-column DistinctOperator bug is a good independent find.

I measured the cost on ordinary query shapes, since the PR only reports it per-answer-row

2,000 subjects, indexed, min of 7, same debug build both sides — only where_plan.rs differs:

shape main branch rows
A SELECT ?s ?name { ?s a Person . ?s name ?name } 7.55 ms 7.37 ms 2000 → 2000
B … . ?s email ?e — unused, single-valued 7.76 ms 8.29 ms 2000 → 2000
C … . ?s tag ?t — unused, multi-valued x8 10.73 ms 18.47 ms 2000 → 16000
D SELECT DISTINCT over C 11.89 ms 11.68 ms 2000 → 2000

A and D flat confirms the narrowing worked — this didn't become a blanket disable. B is the only true regression (same answer, one extra column, ~7% and possibly noise). C isn't like-for-like: main returned 2,000 rows where SPARQL requires 16,000, and the branch does 8x the work for 1.7x the time — 5.4 µs/row down to 1.15 µs/row.

So the blast radius on normal queries is nil, and the trade is better than the writeup makes it sound. Which is really my only substantive note: see the inline comments before merging — none of them block, but the 6.7x figure is the kind of number that gets quoted in a release note six months from now with nobody remembering the denominator.

One thing not inline-able because the file isn't in the diff: docs/query/construct.md (189 lines) documents neither of the two output changes named in the description — blank-node-per-solution, and CONSTRUCT … LIMIT n returning fewer triples. The LIMIT case takes both barrels (excluded from the license so it builds the full product, and returns 1 triple where it used to return 10), and preview-with-LIMIT is a common UI call. Worth a short section.

/// may collapse them. Without this the license reads false for every
/// CONSTRUCT (`restriction()` is `None` for non-`Select` outputs) and a
/// fan-out join builds its full cartesian product only to have it
/// canonicalized back down — measured at 6.7x for byte-identical output.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth naming the denominator here. 6.7x is 0.9026 / 0.1380 — this license against its own un-licensed intermediate state. Against main it's 0.1464 → 0.1380, about 6%, i.e. flat.

That's still worth doing: it stops the correctness fix from making CONSTRUCT 6x slower. But as written the comment reads as a win over the previous behaviour, and it isn't one — it's damage control for cost this PR would otherwise introduce. Same for the bench header at query_hot_fanout_star.rs:6.

Related: the 240 µs / 789 µs / 240 µs in the description is narrated as a CONSTRUCT result, but by the case ordering the 789 is select_unprojected_object — and the two identical 240s confirm it, since both run the pruned plan. So that figure is actually the SELECT cost of correctness, which is the number that was otherwise missing from the writeup.

aggregates_ok && no_raw_passthrough
}
None => query.output.is_distinct(),
None => query.output.is_distinct() || construct_result_is_multiplicity_blind(query),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QueryOutput::Ask gets no license here — restriction() is None for it, so is_distinct() is false and an ASK over a fan-out star plans the full cartesian product. lower.rs:169 doesn't set limit = 1 either.

ASK is more obviously multiplicity-blind than CONSTRUCT: it's a boolean, so there's no blank-node caveat and no LIMIT caveat. If the CONSTRUCT carve-out earns its two exclusions, this looks like a one-line freebie. Was it deliberate?

/// * **A slice.** `LIMIT`/`OFFSET` cut the solution sequence *before* the
/// template is instantiated, so collapsing rows first changes which
/// solutions survive and therefore which triples get built.
fn construct_result_is_multiplicity_blind(query: &Query) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the piece I'd think hardest about. Everything else in the PR is conservative — produce more rows. This one removes rows, on a hand-enumerated argument that every output path canonicalizes. I spot-checked the two canonicalize() calls and the streaming exclusion and they hold, so I'm not disputing it.

But it's the only part that fails silently if the enumeration is ever incomplete, and it's what surfaced the zero-column DISTINCT bug — which is evidence the seam is live rather than theoretical. Given it's a perf optimization rather than part of the fix, would you consider splitting it out so the correctness change merges on its own risk profile?

aaj3f added 4 commits August 28, 2026 11:30
A column-less Batch carries no row count through Batch::new (it reads
the count off columns.first()), so every operator that rebuilds a batch
column-by-column is a place the count can vanish once a WHERE schema
prunes to zero columns. DistinctOperator was the first instance (fixed
earlier in this branch); LimitOperator's truncation branch and
OffsetOperator's partial-skip branch are the second and third, both
rebuilding via the column loop and losing the length.

The LIMIT form is reachable from main today, no dedup license involved:
CONSTRUCT { <s> <p> "dup" } WHERE { ?s ?p ?o } LIMIT 1 prunes the
schema empty via compute_variable_deps (a constant template needs no
variable) and returned an EMPTY GRAPH whenever the WHERE matched more
rows than the limit — verified failing before this fix. The W3C suite
caught the same trap through ASK the moment ASK gained the dedup
license (ask-7: three matches, LIMIT 1, truncated count lost, boolean
read false), which is what flushed it out.

Both operators now route zero-column batches through
Batch::empty_schema_with_len, with unit tests pinning truncation,
pass-through, and partial-skip; the end-to-end pin
(constant_template_construct_with_limit_keeps_its_triple) lands with
the api-test commit.
ASK is the most multiplicity-blind output of all: every formatter either
reads solution-sequence emptiness and nothing else (format_ask,
sparql_xml's boolean arm) or rejects ASK outright (TSV/CSV, the
streaming endpoint). But restriction() is None for QueryOutput::Ask, so
is_distinct() read false and an ASK over a fan-out star planned the full
cartesian join — both surfaces already lower ASK with LIMIT 1 (lower_ask
in fluree-db-sparql; the JSON-LD parser's "ask" branch), which bounds
materialization for the true case, but no LIMIT reaches
PropertyJoinOperator's open()-side per-subject object collection.

Two pieces:

* construct_result_is_multiplicity_blind grows an Ask arm and becomes
  result_is_multiplicity_blind. The arm tolerates LIMIT (a limit of any
  value preserves emptiness, and both surfaces always plan ASK with one)
  and excludes OFFSET (it counts rows off the front: OFFSET 5 over six
  duplicates is non-empty, its deduped form empty; no surface can lower
  that IR today — the guard is for programmatic construction).
* A licensed, modifier-free ASK now gets an empty needed-vars set in
  build_operator_tree_inner instead of the all-vars fallback. Needed
  vars are protected vars in compute_where_var_stats, so the fallback
  was blocking the demotion regardless of the license; the empty set is
  what a constant-template CONSTRUCT already gets via
  compute_variable_deps, and join/FILTER vars stay protected through
  their reference counts. Grouping, ordering, order-binds, post-VALUES,
  or an offset all fall back to the conservative default.

Plan shape is pinned end-to-end (the object var leaves the WHERE schema;
its offset twin keeps it), and the fan-out fixture's integration test
now runs ASK on both lanes and both surfaces in both truth directions —
the boolean cannot see the license, which is exactly why the plan-shape
tests exist. Non-vacuity: stub the Ask arm to false and both fail.

Measured (end-to-end, min of 7, debug): ASK over the star 12.2 -> 10.4 ms
at 2,000 subjects x8 tags, 54.1 -> 41.5 ms at 3,000 x40, growing with
fan-out; the FILTER control that reads the object var is flat, because
its reference count protects it and the demotion correctly never fires.

Also reframes the license's 6.7x number against its real denominator, in
the unit-test doc comment and the bench header: against the pre-fix
planner, licensed CONSTRUCT is flat (0.1464s -> 0.1380s); the 6.2x
(0.9026s) is what the correctness fix would cost WITHOUT the license — a
state that never shipped. Damage control, not a speedup.
…olumn slices

The CONSTRUCT half of the WHERE-dedup license rests on "every output
path canonicalizes or rejects" — an enumeration that fails silently if a
new output path ever joins the set unclassified, and the zero-column
DistinctOperator bug is proof the seam is live rather than theoretical.
Make it structural instead of a comment:

* every_output_format_collapses_or_rejects_construct holds the
  classification in a macro whose match over OutputFormat has no
  wildcard arm — adding a variant stops the file compiling until the new
  path is classified — and the same identifier list drives the runtime
  loop, so a variant cannot be classified without also being tested.
  The assertion is behavioral: a CONSTRUCT whose WHERE provably still
  carries 12 duplicate solutions (asserted as a precondition, so the
  gate cannot pass vacuously; a LIMIT keeps it outside the license) is
  fed to every format through format_results_string, and each must
  collapse the duplicates to one triple per subject or error.
* The streaming endpoint is the one path that does not route through
  format_results_string, so its rejection of CONSTRUCT and ASK is
  pinned separately in stream_query.rs, with the license named as the
  thing that breaks if the rejection is ever lifted.
* constant_template_construct_with_limit_keeps_its_triple pins the
  main-reachable zero-column LIMIT/OFFSET shapes end-to-end (empty
  graph before the limit.rs/offset.rs fix; exactly one triple after).

If a future format legitimately needs to stream CONSTRUCT without
canonicalizing, the license itself has to change; the gate failing is
the reminder, instead of a wrong query result downstream.
The #1700 fix has two user-visible CONSTRUCT consequences that were
pinned in tests but stated nowhere a user would look: a template blank
node mints one blank per solution (not per subject), and LIMIT counts
solutions before instantiation, so CONSTRUCT ... LIMIT n can return far
fewer than n triples — the common preview-with-LIMIT call takes both
barrels (excluded from the WHERE-dedup license and fewer triples than
before). New "Solution Multiplicity" section states both plainly, with
the subselect rewrite (SELECT DISTINCT ?s ... LIMIT n inside the WHERE)
for previews that mean "n subjects" — verified against the fan-out
fixture: 10 nodes from LIMIT 10.
@aaj3f

aaj3f commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bplatz — all four landed, your denominator point is now structural in all three places it lived, and your ASK question turned out to be the most productive sentence in the review: chasing it flushed out a bug family with one member reachable from main today.

The framing. The comment, the bench header, and the body now state the real frame: against the pre-fix planner, licensed CONSTRUCT is flat (0.1464 → 0.1380 s); 0.9026 s is the fix-without-license, a state that never shipped, so the license is damage control rather than a win. (One small correction to the arithmetic while fixing it: 0.9026/0.1380 is 6.5×, and the intermediate-state ratio is 0.9026/0.1464 = 6.2× — immaterial to the point, which was right.) The 240/789/240 narration is fixed — the 789 µs is select_unprojected_object, the SELECT cost of correctness, exactly as you read it. And I re-measured your four shapes myself so the body owns the numbers: A and D flat, B +3% (your "~7% possibly noise" reproduced smaller), C 8× the work for 5.9× the time with per-row cost falling 18.2 → 13.5 µs — your direction throughout, at end-to-end scale including serialization.

ASK — license granted, with one pushback on the framing. The limit = 1 half already exists on both surfaces: lower/ask.rs sets limit: Some(1) explicitly, and the JSON-LD parser's "ask" branch sets it before lowering runs — lower.rs:169 just copies it. So the decision was license-only; there was no limit to take. It also wasn't quite a one-line freebie: referenced_vars() returns None for Ask, which the planner read as all vars needed, and needed = protected blocked the demotion regardless of the license — so the second piece is an empty needed-vars set for a licensed modifier-free ASK, with grouping/ordering/OFFSET all falling back conservative (OFFSET counts rows, so it genuinely can't have the license). Pinned both lanes, both surfaces, both truth values, plus the plan shape; stubbing the Ask arm fails both new tests. Measured: flat vs main, and 54.1 → 41.5 ms at 3k×40 against the unlicensed intermediate.

The find. The W3C suite went red the moment the ASK license landed (ask-7 → false): LimitOperator's truncation branch rebuilds batches column-by-column and Batch::new loses the row count at zero columns — the same trap as this PR's DistinctOperator fix, and OffsetOperator's partial-skip branch is identical. The LIMIT form needs no license at all: CONSTRUCT { <s> <p> "dup" } WHERE { ?s ?p ?o } LIMIT 1 returns an empty graph on main today, because a constant template prunes the schema empty through entirely pre-existing code. Fixed here with unit pins in both directions and an e2e guard. That's three instances of one seam found by three different nets, which is the strongest concrete support for your instinct on the license-removal piece.

Which is why it stays in, with the risk answered rather than split away: every_output_format_collapses_or_rejects_construct holds the classification in a macro that expands to a wildcard-free match over OutputFormat — a new variant stops compilation until classified — and to the runtime check: a CONSTRUCT carrying twelve duplicate solutions (verified by ran-marker) goes through all nine formats, each of which must collapse or error. The streaming endpoint gets its own pin naming the license. Splitting the optimization out would have added distance without adding safety; the gate adds safety.

docs/query/construct.md gained the multiplicity section — blank-node-per-solution, LIMIT-counts-solutions-not-triples with the preview case, and the { SELECT DISTINCT … LIMIT n } rewrite, each executed against the fan-out fixture before being documented. And your 18-assertion revert count reproduced exactly.

@aaj3f
aaj3f merged commit 517637f into main Aug 28, 2026
14 checks passed
@aaj3f
aaj3f deleted the fix/generic-count-star-row-multiplicity branch August 28, 2026 15:58
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.

Property-join semijoin demotion drops row multiplicity when the object var is unprojected (COUNT(*) undercounts; SELECT drops rows)

2 participants