Repository navigation
Description
When a UNION's branches share one UNION ALL statement, union_plan (fluree-db-query/src/r2rml/sql_lane/mod.rs) renders seeded_root(b, keyset) once per branch, so the outer key set is sent and materialised once per branch: the pinned statement carries (VALUES (10), (12)) twice for two branches. #1788 sized the chunk for this by dividing the key-set row cap and byte budget by the branch count (keysets_for(branch, copies, …)), so an N-branch union at a full chunk now stays inside the budget, at the cost of N times more statements for a large seed.
The better shape, from the #1788 review: hoist the key set to one JOIN outside the union on the shared slot. The grouping precondition already guarantees every grouped branch seeds on the same key shape (UnionLayout assigns the seed's slot by variable, column position and column type, and a branch that disagrees is not grouped), so the key set can join the union's derived table once:
SELECT … FROM (
SELECT … , 0 AS tag FROM t0 WHERE …
UNION ALL
SELECT … , 1 AS tag FROM t1 WHERE …
) AS u
JOIN (VALUES (10), (12)) AS k (k0) ON k.k0 = u.<seed slot>That sends the key set once, lets the chunk go back to the provider's cap, and keeps the branch tag decode unchanged. Things to check on the way:
- the branches lose their seed predicate, so a branch's own
WHEREno longer narrows on the key; the database must be able to push the join predicate through the union (Postgres and MySQL 8 do; SQLite's planner may scan each branch whole, so measure there before making it the only shape) - a branch whose seed slot is NULL-padded (a branch not binding the seeded variable) must not join at all, which today's per-branch seeding handles by construction
plan_for_cacheand the bounded COUNT probe build from the branch root; they must keep working from the hoisted shape- pin the statement on the fake and replay through
key_sets_above_the_cap_chunk_or_stay_in_the_engine's union case (2001 keys over two branches is 1000 + 1000 + 1 today and should return to 2000 + 1)
Deferred from #1788 to keep its scope; the divided budget is correct, only wasteful.
Activity
perf(sql): join the outer key set to a shared UNION ALL statement once
bplatz commentedon Sep 5, 2026
Implemented on #1788 (ce42222): the outer key set joins the
UNION ALLderived table once, outside the union, on the slots the branches' seed columns share (UnionLayout.seed_slots). The renderer now types derived tables before inferring key-set types so a key equated with a union slot resolves. 2001 keys over two branches go out as 2000 + 1 again; pinned as the exact statement on the fake and replayed live on SQLite, Postgres and MySQL. In-blockVALUESstill lowers inside each branch, bounded by the key-set cap. The PR body carriesFixes #1794, so this closes on merge.