Internals notes (unpolished)

Broadcast join-key ordering: hash_keys.first() is not "smallest domain"

Not reliable. hash_keys.first() is left always_bound order, not "smallest domain." Selective-leaf-on-the-left does not make that first key the best allow-list.

How hash_keys is built — waratah_compute/src/plan.rs, lines 228-234:

fn hash_keys_for(left: &OutputVars, right: &OutputVars) -> Vec<Variable> {
    left.always_bound
        .iter()
        .filter(|v| right.is_always_bound(v))
        .cloned()
        .collect()
}

Left always_bound order is:

  • Scan: subject, predicate, object (pattern slot order)

  • VALUES: VALUES column order

  • Join: left’s list, then new vars from the right

So for ?k :p ?x ⋈ ?x ?k ?y, keys are [?k, ?x] because ?k is the left scan’s subject, even if ?x has 2 distinct values and ?k has 20 000. The executor then broadcasts ?k.

The pipeline sort only orders leaves by produced_row_count_estimate. It never reorders join keys. join_nodes costing also uses hash_keys.first() for HLL domain, so Broadcast vs Hash can follow the same accident.

Is "selective left" enough?

It helps row count of the build/probe (VALUES of 2 rows tends to sit left, so ?k often appears early). It does not pick the join key with the smallest distinct count. Two keys on one left scan are ordered S→P→O, not by |distinct|.

Path extra footgun: path_right_mode also uses first(). join_nodes forces Broadcast if any key is a path end, but the push may be a key end_of does not recognize → pushed keys ignored → eval_open.


Yes — you can choose at execute time. EncodedSolutions::distinct_values already walks the left batch. After the left side is in hand:

  1. For each hash_keys entry, distinct_values (or a count-only variant).

  2. Keep keys that actually bind a right slot: scan.slot_of(k) or path.end_of(k).

  3. Pick the smallest set that is still useful (and, for scans, ≤ PUSHDOWN_TERMS_LIMIT if you keep that limit).

  4. Optionally prefer a slot that, given already-ground pattern slots, yields a longer RocksDB prefix (P‖S vs P only).

That is exact, not estimated, and cheap next to a wrong full-predicate scan. You would do it in PushedKeyVals::from_solutions / broadcast_filter_for (and the Path cousin), not in the planner.

A lighter planner-only fix: sort hash_keys by join_key_domain_for_node (or VALUES distinct_key_count) so first() is the estimated-smallest domain. Runtime min-of-distinct is still more honest when sketches are missing or two keys share a scan.

What to borrow from Oxigraph’s expression evaluator

Yes — a few of them are worth stealing. Several of the flashiest spareval tricks are row-at-a-time closures, which fight Waratah’s vectorized model. The useful ones are: stay on encoded IDs, fold dead expressions, compile constants once, and treat EXISTS / property paths as encoded graph walks.

Waratah already runs sparopt::Optimizer and already does encoded sameTerm / = / EBV / COALESCE. Oxigraph’s extra juice is mostly in spareval, not in join reordering (their greedy estimates are cruder than your sketches).

Already in the same neighborhood

Oxigraph Waratah

Joins/scans on EncodedTerm

Same

sameTerm as encoded ==

same_term in waratah_compute/src/expr/ops.rs

EBV on native numerics/strings without dict lookup

ebv_of_encoded_term in waratah_compute/src/expr/ops.rs

Filter push + join reorder

sparopt + your sketch planner

Hash join

waratah_exec

Do not copy their per-row Rc<dyn Fn> expression compiler as the main FILTER path. That is Volcano-style. Your analogue is a plan-time kernel (encoded vs residual) applied to a batch.

Worth borrowing

1. "Internal" expression path (no round-trip through strings)

try_build_internal_expression_evaluator only accepts nodes that stay on InternalTerm (EncodedTerm): variables, interned literals/IRIs, nested COALESCE/IF branches. sameTerm then compares encoded values. If either side needs ExpressionTerm, they internalize just that side.

Waratah already does this for FILTER. The gap is BIND/Extend and mixed sameTerm(STR(?x), …): compile "this tree never needs the registry" vs "only these rows do," the way they return None from the internal builder instead of always decoding.

2. Static type inference that deletes work

sparopt tracks VariableType (IRI / literal / undef / …). If a FILTER’s type is always UNDEF (cannot be true), the whole pattern becomes empty. If a BIND expression is always undef, they drop the Extend.

Cheap wins: FILTER(?s = 1) when ?s is a subject (always IRI) → empty; BIND(1/0 AS ?x) → unbound column without running divide. You have sketch statistics; they have algebraic types. Both compose.

3. Compile constant REGEX at plan time

If the pattern and flags are string literals, they build one regex::Regex (with a size limit) and reuse it. Residual REGEX(STR(?v), "a") in Waratah should do the same the day that function lands — not Regex::new per row.

4. Property paths on encoded IDs

Paths (/, |, *, +, !) are compiled to a small PropertyPath<EncodedTerm> and walked with interned predicates. The transitive operators are BFS on hashes, not strings. That is the biggest SPARQL 1.1 hole (~20 W3C failures) and it fits late materialization: only the final ?s/?o columns need registry lookup.

5. EXISTS as a compiled sub-plan

build_exists lowers the inner graph pattern once, then for each outer tuple runs it with that tuple as the input and checks next().is_some(). For Waratah: compile the EXISTS body as a plan, probe (broadcast / allow-list) from the outer batch, stop at first hit. Do not decode. That unblocks a whole FILTER family.

6. Integer column slots in the hot loop

Oxigraph maps Variable → usize once (encode_variable), then tuples are InternalTuple indexed by slot. Waratah still looks up by Variable name on each cell. For FILTER/BIND over a batch, a Vec<Option<EncodedTerm>> (or Arrow column index) per variable is a real win.

7. COUNT(DISTINCT …) on internal terms

They have separate accumulators for "distinct encoded terms" vs "distinct decoded expressions." You already distinct-hash in aggregates; keep that rule: if the arg is a variable, distinct on fingerprints, never strings.

Impressive but do not copy as-is

  • Greedy join order with fake cardinalities (triple size 1/10/100 by how many slots are bound). You already beat this with CMS/HLL.

  • Lateral / for-loop join (SPARQL-dev sep-0006): evaluate the right side per left row when it can use left bindings as index keys. Your broadcast join is the distributed version. A local "index nested loop" for tiny left batches is the same idea.

  • CancellationToken + explain statistics on every node: useful for HTTP timeouts and EXPLAIN ANALYZE, not a query-semantics optimization.

  • NOW() captured once per query: SPARQL requires one timestamp; stash it on ComputeNode::query, don’t call now() per row.

What to actually take next

Highest leverage for Waratah, in order:

  1. Property paths on EncodedTerm (feature + encoding-friendly).

  2. EXISTS/NOT EXISTS as a batched probe of a compiled inner plan.

  3. Type-inference / constant-fold FILTERs to empty (sparopt already does some of this — check you preserve it through lowering).

  4. Plan-time REGEX compilation on the residual path.

  5. Integer slots for expression eval over a batch.

The spareval trick to keep in mind: decode only at the leaves that need strings; everything else is interned-ID dataflow. You are already more aggressive than they are on FILTER. They are more complete on paths, EXISTS, and "this expression never leaves encoded space."