Skip to content

Batched join lanes run under reasoning and decode what they emit - #2271

Merged
bplatz merged 9 commits into
mainfrom
perf/reasoning-batched-probes
Nov 11, 2026
Merged

bplatz merged 9 commits into
mainfrom
perf/reasoning-batched-probes

Conversation

@bplatz

@bplatz bplatz commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Reasoning queries and datalog rule bodies run with eager materialization. Eager materialization kept every nested-loop join and property join off its batched lanes, so each join ran row by row. This PR lets those lanes run under reasoning:

  • Admission is opt-in per lane. The lane planners and probe_lane_admission take a LaneOutput. DecodesForEager lanes are admitted under eager: the overlay ops they merge already include the derived facts, because translation walks the combined reasoning overlay. Encoded lanes decline eager callers with an overlay, as every lane did before. In the nested-loop join, batched_lane_output() lists the subject, object and exists lanes, and any other join lane is Encoded. A new lane runs under reasoning only once its own diff says it decodes.

  • Decoded output. Under eager, these lanes emit decoded Sid/Lit bindings, as the per-row scan does:

    • the nested-loop join's subject, exists and object lanes;
    • the shared probe helpers the property join uses.

    Subjects decode through the overlay's novelty-aware graph view (resolve_subject_sid), the same path the scan uses. Without this, a rule head built from an encoded binding derives nothing.

  • Property join. Under eager within one ledger, the lanes are planned before the first subject is keyed. When some lane will probe or walk, subject keys normalize to ids so the batched probe and SPOT star walks engage. When every lane declines, keys stay Sid, so a declined plan does no reverse lookups, as on main. Multi-ledger keys already take subject_key_multi.

  • Unchanged. These keep the per-row path under eager, exactly where admission declined them before:

    • multi-ledger eager contexts, which need IriMatch provenance;
    • cyclic BGP probes, the OPTIONAL builders and the range semijoin, which are Encoded.

A cold lane must translate its predicate's entire overlay extent before its first probe. A derived extent can be far larger than the query's input, while the per-row scan translates only the overlay facts in each row's own range. So for eager callers:

  • Selective inputs stay per-row. When the predicate's ops aren't translated yet, the nested-loop join defers its overlay plan to the first flush. If that flush ends the input and holds fewer rows than one per eight overlay facts of the predicate, the rows take the per-row path. The overlay facts are counted with a new OverlayProvider::overlay_range_flake_count; the reasoning overlay answers it with binary searches. Once a wide input has translated the ops, selective inputs take the lane too.

    The property join is not deferred: its fallback scans each predicate in full, so a cold lane costs it no more than before.

  • Predicates the index lacks decline before translation. Their ops could only decide between declining and an empty lane, and the fallback is correct either way.

Supporting changes:

  • Translated ops live on the reasoning materialization (DerivedFactsOverlay::attachment, reasoning_ops.rs). A lane translates a derived predicate's facts into index ids the first time a query needs them. Every later query reading that materialization reuses the translation, and it is dropped with the materialization. Derived extents are translated once per materialization rather than once per query. Other eager callers (datalog fixpoint passes, whose rule bodies run with reasoning off) and ordinary novelty stay per-execution, as on main. There is no separate cache or budget.
    • Binding: translations are kept for one overlay content version, store, snapshot and to_t, and replaced when that changes. A context reading another overlay (a dataset member over plain novelty) never touches them.
    • Memory: translations count toward the materialization's reasoning memory budget (f:reasoningMaxMemoryMb and its overrides), beside its derived facts, once per materialization. Each translation reserves its estimated size before it is made. One that won't fit isn't made: the lane declines and the join runs per row. The first refusal per materialization logs a WARN with the phase, estimated sizes, limit, derived-fact count and what to change. docs/query/reasoning.md ("Memory a cached result holds") states the provisioning contract.
    • Empty results aren't kept. Failed translations are, so a materialization walks the extent, fails and warns once.
  • The object lane's view of the ops (its IRI_REF subset in object order) is built once and kept beside them. It used to be filtered and re-sorted on every flush.
  • Decoded left keys of an eager stream resolve to subject ids through a per-operator memo, capped at 2^18 entries. Eager streams repeat subjects across many rows, and every row's key is decoded. While the overlay plan is deferred, keys are not resolved. The flush resolves them only once the lane proceeds, so rows the flush hands to the per-row path pay no lookups.

Tests

it_reasoning_batched_probe (in grp_reasoning):

  • OWL 2 RL cases, run over an index and then with a later commit in novelty. Each case runs as JSON-LD and as SPARQL and checks three things:

    • the rows;
    • the lane that produced them: use_batched plus the lane's flush span, or the property join's used_batched_probe / used_spot_star_walk;
    • the rows of a never-indexed copy of the ledger.

    Lanes covered: subject, subject with FILTER, an entailed ref emitted by the subject lane, exists, object, object-lane subjects meeting an entailed edge and an entailed type, and a property-join star on an entailed anchor. OPTIONAL is checked by rows only.

  • Named graph. Facts a rule derives into a named graph, read by a subject-lane and an object-lane join inside that graph.

  • Datalog rule bodies on the subject and object lanes. The rule heads are built from an object-lane subject, a subject-lane ref and a subject-lane literal.

  • OWL 2 RL and datalog over one state, deriving different facts for the probed predicate. Neither is served the other's cached ops.

it_reasoning_lane_cache, a binary of its own. These tests read the translations an earlier query left on a materialization, and in grp_reasoning a sibling test could evict that materialization from the reasoning cache:

  • Selective inputs over 400 derived edges, through the subject and the object lane:
    • one row with a cold cache runs per-row;
    • sixty rows take the lane;
    • one row then takes the lane once the ops are cached.
  • A deferred plan that declines on a non-final flush. A datalog rule derives strings no dictionary holds, and a LIMIT makes the first flush non-final. Every row survives the reroute, and a rerun declines before accumulating, because the failed translation is cached.

Unit tests, in fast_path_common, for:

  • the cache bound;
  • the cached failed translation;
  • eager admission per LaneOutput;
  • translations kept on a materialization, for contexts reading its overlay, within its reasoning memory budget;
  • reasoning_ops: the budget beside the derived facts, binding replacement, a translation finished under a replaced binding, and empty and failed translations;
  • the reasoning overlay's range count.

Each part was confirmed to fail with the code it pins broken:

Code broken What failed
Eager decline restored in admission and the join Routing (use_batched: false)
Object-lane subject not decoded Rule head's grandparent fact missing
Shared builder not decoded childName and descendantOf facts missing
Subject-lane ref not decoded descendantOf fact missing
Property-join key normalization gated on eager Batched walk routing
Selective-input deferral off Cold one-row query took the lane
Reasoning overlay can't count its extent Cold one-row query took the lane
Cost ratio 0 (always per-row) Sixty-row query ran per-row
Cost ratio 10^6 (never per-row) Cold one-row query took the lane
Translated ops never seen as cached Warm one-row query stayed per-row
Runner never attaches the translations to the query Selective-input and mid-stream-decline tests
Reservation ignores the reasoning memory budget reasoning_ops budget unit test
A new store binding keeps the old translations reasoning_ops binding unit tests
Rows dropped instead of rerouted on a mid-stream decline Non-final decline test, rows
Stored left batches cleared after a reroute Non-final decline test (panic)
Failed translation not cached Non-final decline test, rerun
Deferred keys never resolved Five lane tests
Encoded lanes admitted under eager Eager admission unit test

Follow-up: #2324 (Novelty / CompositeOverlay count a predicate's range)
Follow-up: #2325 (cyclic rule body derives nothing on an indexed ledger; on main, found here)
Follow-up: #2326 (it_reasoning_request_limits fuel tests flake under load; on main)
Follow-up: #2332 (move the scan's whole-graph reasoning translations onto the materialization)
Follow-up: #2292 (add persisted reasoning and reasoningFreshness: "strict" to the reasoning memory WARN and docs once it reaches main)

…hey emit

Reasoning queries and datalog rule bodies run with eager materialization,
which kept every nested-loop join and property join on the per-row path.
Those lanes now stay engaged: the probe-lane admission no longer declines
eager callers, and under eager the subject, exists and object lanes and the
shared probe helpers emit decoded `Sid`/`Lit` bindings, as the per-row scan
does. A rule head built from an encoded binding derived nothing. The
property join keys eager subjects by id in one ledger. Multi-ledger eager
contexts, cyclic BGP probes and the grouped OPTIONAL builder keep their
per-row behavior.

Resolved per-predicate overlay ops are also cached across queries, keyed
like the scan's cross-query translation cache and bounded by the ops they
retain, so a large derived extent is translated once per state. Decoded
left keys resolve to subject ids through a per-operator memo.
@bplatz bplatz added the performance Performance improvement (release notes: Performance) label Nov 6, 2026
@bplatz
bplatz requested a review from a team November 6, 2026 05:04
…and the ops cache is bounded per entry

A cold lane translates its predicate's whole overlay extent before the first
probe; a derived extent can be far larger than the input, where the per-row
scan translates only each row's own matches. Under eager materialization the
nested-loop join now defers its overlay plan to the first flush, and a final
flush with fewer rows than one per eight overlay facts of the predicate runs
per-row. The count comes from a new OverlayProvider::overlay_range_flake_count,
which the reasoning overlay answers by binary search. Predicates the index
lacks decline before translation.

The cross-query ops cache now serves eager callers only, keeps no empty
results, and charges each entry a fixed cost for its key and node, so many
small entries are bounded as well as a few large ones. The object lane's
IRI_REF subset in object order is cached beside the PSOT ops instead of being
filtered and re-sorted on every flush. The decoded-key memo runs for eager
callers only.

@jdorety jdorety left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review

The core change looks correct. I traced every lane that relied on probe_lane_admission declining eager callers: each one now either declines eager itself or decodes its output. I also checked the cross-query cache key and the deferral state machine. Every check I ran was against the branch head (5da2d34) and compared indexed results with a never-indexed copy of the same ledger, and none produced a wrong result. Two things should be resolved before merge.

Blocking

1. The mid-stream reroute has no test (fluree-db-query/src/join.rs:~1991-2006).

When a deferred plan resolves to Decline on a flush that isn't the last one, the accumulated rows are moved to per_row_backlog. stored_left_batches is kept across the flush boundary. Production queries reach this:

  • an indexed ledger;
  • a datalog rule that derives a string not in the dictionary (BIND(CONCAT(...))), so translation fails and the plan declines;
  • more than 1024 left rows;
  • a LIMIT, so the first flush is not the last one.

No existing test reaches it. Two planted bugs passed all of grp_reasoning and fluree-db-query --lib join:

  • draining the accumulator without rerouting, which silently drops rows;
  • rerouting and then clearing stored_left_batches, which panics with an index out of bounds at join.rs:1908.

The test below reaches this path. It passes at 5da2d34 and fails under both planted bugs. Before adding it, it should also assert the routing (the reroute event or the flush span), so it can't pass by taking the generic lane.

Test: non-final flush whose deferred plan resolves to Decline
use crate::support::{genesis_ledger_for_fluree, normalize_rows};
use fluree_db_api::{Fluree, FlureeBuilder, GraphDb, QueryInput, ReindexOptions};
use serde_json::{json, Value};

// A non-final flush whose deferred overlay plan resolves to Decline. A datalog
// rule derives `ex:caseId` literals that are in no dictionary, so translating
// the predicate's overlay fails and the subject lane declines. LIMIT 1024 makes
// the first flush 1024 rows; 3000 marker rows keep the left input going past it.

const MARKERS: usize = 3000;
const FILLER: usize = 4000;
const RULE_INPUTS: [usize; 4] = [3, 7, 1500, 2999];

fn path2_data() -> Value {
    let mut graph = Vec::new();
    for i in 0..MARKERS {
        graph.push(json!({"@id": "ex:board", "ex:levels": {"@id": format!("ex:s{i}")}}));
    }
    // Stored caseIds index the predicate and outnumber the markers in stats.
    for i in 0..FILLER {
        graph.push(json!({"@id": format!("ex:k{i}"), "ex:caseId": format!("stored-k{i}")}));
    }
    for i in 0..10 {
        graph.push(json!({"@id": format!("ex:s{i}"), "ex:caseId": format!("stored-s{i}")}));
    }
    // Rule inputs: early markers (in the first flush) and late ones (after it).
    for i in RULE_INPUTS {
        graph.push(json!({"@id": format!("ex:s{i}"), "ex:parent": {"@id": format!("ex:p{i}")}}));
    }
    json!({"@context": {"ex": "http://example.org/ns/"}, "@graph": graph})
}

fn path2_rule() -> Value {
    json!({
        "@context": {"f": "https://ns.flur.ee/db#"},
        "@id": "http://example.org/ns/rule/caseId",
        "f:rule": {"@type": "f:sparql", "@value":
            "PREFIX ex: <http://example.org/ns/>\n\
             CONSTRUCT { ?x ex:caseId ?id } WHERE { ?x ex:parent ?y BIND(CONCAT(\"derived-\", STR(?y)) AS ?id) }"}
    })
}

async fn sorted_rows(fluree: &Fluree, view: &GraphDb, input: QueryInput<'_>) -> Vec<Value> {
    let r = fluree.query(view, input).await.expect("query");
    let mut rows = normalize_rows(&r.to_jsonld(&view.snapshot).expect("jsonld"));
    rows.sort_by_key(ToString::to_string);
    rows
}

#[tokio::test(flavor = "current_thread")]
async fn path2_non_final_decline_after_deferral() {
    let fluree = FlureeBuilder::memory().build_memory();
    let id = "it/path2:main";
    let oracle_id = "it/path2-oracle:main";
    for lid in [id, oracle_id] {
        let ledger = genesis_ledger_for_fluree(&fluree, lid);
        let ledger = fluree.insert(ledger, &path2_data()).await.expect("seed").ledger;
        fluree.insert(ledger, &path2_rule()).await.expect("rule");
    }
    fluree
        .reindex(id, ReindexOptions::default())
        .await
        .expect("reindex");
    let view = fluree.db(id).await.expect("view");
    let oracle = fluree.db(oracle_id).await.expect("oracle");
    assert!(view.snapshot.range_provider.is_some(), "indexed");

    let jsonld = json!({
        "@context": {"ex": "http://example.org/ns/"},
        "select": ["?x", "?id"],
        "where": [{"@id": "ex:board", "ex:levels": "?x"}, {"@id": "?x", "ex:caseId": "?id"}],
        "reasoning": "datalog",
        "limit": 1024
    });
    let sparql = "# PRAGMA reasoning: datalog\nPREFIX ex: <http://example.org/ns/>\n\
                  SELECT ?x ?id WHERE { ex:board ex:levels ?x . ?x ex:caseId ?id } LIMIT 1024";
    let mut expected: Vec<Value> = (0..10)
        .map(|i| json!([format!("ex:s{i}"), format!("stored-s{i}")]))
        .chain(RULE_INPUTS.iter().map(|i| {
            json!([format!("ex:s{i}"), format!("derived-http://example.org/ns/p{i}")])
        }))
        .collect();
    expected.sort_by_key(ToString::to_string);

    for (surface, input) in [
        ("SPARQL", QueryInput::Sparql(sparql)),
        ("JSON-LD", QueryInput::JsonLd(&jsonld)),
    ] {
        let got = sorted_rows(&fluree, &view, input).await;
        let want = sorted_rows(&fluree, &oracle, input).await;
        assert_eq!(want, expected, "{surface}: oracle");
        assert_eq!(got, expected, "{surface}: indexed");
    }
}

2. The cross-query ops cache admits non-reasoning callers (fluree-db-query/src/fast_path_common.rs:2440).

The doc comment on ops_cross_query says novelty extents stay per-execution. pred_ops_key, however, admits any caller with ctx.eager_materialization set. Instrumented runs showed two non-reasoning sources of entries:

  • Datalog fixpoint passes (datalog_rules/execute.rs:339). Each pass caches under a new content_version. Four passes stored 8 entries. The only reuse was inside the same pass; nothing was read after the fixpoint.
  • Single-ledger multi-graph dataset members (decode_members). The scan's predicate_otype_uniform check (binary_scan.rs:~346) caches plain novelty ops under a new key on every commit.

Results stay correct. The cost is that these entries push the reasoning extents the cache is meant for out of it. Please either gate admission on a reasoning materialization (e.g. reasoning_active, or a flag set at runner.rs:939 when derived_overlay.is_some()), or correct the comment if the broader admission is intended. If you'd rather defer this, file an issue and link it with Follow-up: #N.

Non-blocking

3. The warm phase of a_cold_lane_leaves_a_selective_input_per_row depends on the 16-entry reasoning cache (fluree-db-api/tests/it_reasoning_batched_probe.rs:827).

If the reasoning cache entry is evicted between wide and warm, the overlay is rebuilt with a new content_version. The ops lookup then misses, the query goes per-row, and the test fails. Forcing that eviction reproduces the failure every time. In normal conditions it didn't fail in 80 full grp_reasoning runs (40 at default threads, 40 at 64). Other tests caused up to 16 reasoning-cache misses inside this test's window, and 16 is what eviction needs. A bounded retry would remove the risk: if the selective query goes per-row, rerun wide and then the selective query, up to 3 times. A real regression still fails every attempt.

4. Possibly unrelated: at 64 threads, two tests in it_reasoning_request_limits failed in 17 of 40 runs at line 162. They assume a back-to-back query is served from the reasoning cache. I haven't checked whether this also happens on main.

@aaj3f aaj3f 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.

@bplatz this is really nice, and at a design level no pushback from me: decoding what the lanes emit and reusing the scan's translation key is what I'd have reached for. The wins are big (a 101k-row reasoning join went from ~1 s to ~0.2 s on Claude's box run, and an object-lane probe ~4×), and the batched lanes matched the per-row path on every reasoning shape Claude threw at them. Two headline notes. (1) The one thing I don't think should merge as-is: under reasoning, the subject keys get resolved to ids up front, for every row, before anything knows whether a batched walk will run. When the lanes then decline (a super-property only the reasoner populates being the canonical case), that's pure added work, and that star query runs ~1.85× slower than on main. Details and a cheap fix below. (2) Admission's eager default flipped from decline to admit, so lanes that can't decode now opt out by hand. Next's typed object lane, #2292's pair join and my #2214's union probes were all written under the old default, and each gets admitted under reasoning as soon as it meets this change in a merge. #2214 and this PR also rewrite the same use_batched expression and subject-lane binding in join.rs (six conflict hunks), so whichever of us lands second carries the decode into the other's lanes. An opt-in capability on the lane planners would make that a compile-time question rather than a merge-resolution one, and I'd fold it in here since this PR already holds the chokepoint.

Approving to unblock you, and because I'm confident you'll want to address the perf-related items pre-merge anyway

Full review below:


🔄 Request changes.

This is a really nice piece of work, @bplatz. The lanes decode exactly what the per-row scan decodes, the cost guard is well reasoned, and the mutation table in the body is the strongest evidence I've seen on a lane PR. On correctness I have nothing: the batched lanes match the per-row path across everything Claude threw at them (sameAs, class and property closures, lists, typed and lang literals, policy, novelty with retractions, time travel). I'm requesting changes for one performance regression only. Under reasoning, subject keys are resolved to ids for every row before the lane decides, so when the lanes decline, a reasoning star over a derived-only predicate runs ~1.85× slower than on main (and a 1,000-row exists probe the cost check keeps per-row runs 5–9% slower). Gating the resolution on a lane actually engaging keeps every win below. The rest are fold-it-in-now items.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Reuses the scan's decode (resolve_subject_sid, decode_overlay_object) and its GlobalTranslationKey. ⚠️ Eager admission is now opt-out per lane rather than opt-in (headline note 2), and the new cross-query cache sits beside the scan's own without a word about how they relate.
  • Performance (speed first, memory second): ✖ CRITICAL: the reasoning property-join star over a derived-only predicate regressed 108.9–110.5 ms → 200.9–205.6 ms on a clean box, and a 1,000-row NLJ exists probe that the cost check keeps per-row regressed 5–9%. Everything else measured either flat (non-reasoning joins) or much faster (reasoning: wide subject lane 3.3–5.8×, object lane 2.9–4.2×, LIMIT 10 over an indexed predicate with a derived extent 22–25× warm and 1.7–2.2× cold; datalog_fixpoint up to 87% faster). Criterion A/B, two rounds each, on query_hot_bsbm, query_overlay_matrix, query_hot_optional and query_hot_fanout_star: no bench slowed by more than 2.9%. Memory: up to ~160 MiB of process-lifetime cache, fixed at compile time.
  • Deployment targets: ⚠️ The cache is a process-lifetime static in fluree-db-query, reached by every embedder. It is a pure cache, so it stays correct with many processes, and nothing outlives a response that matters. Its ~160 MiB ceiling is not configurable, which is worth saying for memory-capped hosts. wasm32 check/clippy and wasm-smoke are green on this head.
  • Testing: ✔ it_reasoning_batched_probe is wired into grp_reasoning, pins rows, lane and a per-row oracle, and the body's mutation table reports each pinned piece going red when broken. It passed in CI's test job on 5da2d346a and in release on Claude's box. Claude's 182-result-set differential (base vs head, indexed vs oracle) found no difference.
  • Conventions: ✔ Multi-line commit bodies, performance label, clippy/fmt green. One stale doc comment (join.rs:2055).

Verified at branch HEAD: Claude ran a base-vs-head differential (182 result sets identical, 0 indexed/oracle mismatches, 148 with a batched lane at head), timing A/B in release on a c7i.8xlarge (two rounds, two ledgers, three states each), a single-thread routing diagnostic for the regressed star, a mutation check of the property-join finding (115.9–119.8 ms with the eager gate restored, file restored after), and criterion A/B on five benches (no non-reasoning bench slower by more than 2.9%; datalog_fixpoint up to 87% faster); CI is green on 5da2d346a.

Just be sure to gate the eager key resolution on a lane engaging before this merges. With that, I'd approve, and the opt-in admission is the one fold-in I'd most like to see alongside it.

// `subject_key_multi` above. A policy does not gate this: the batched
// walks an all-`Id` key set enables (`subject_probe_lane_plan` /
// `star_probe_lane_plan`) decide per predicate whether the view
// policy can touch them, and decline to the filtered scans when it

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.

CRITICAL: under reasoning, the property join now does a reverse dictionary lookup for every subject key, including when no batched walk engages, and that makes reasoning stars over a derived-only predicate slower than main.

subject_key now normalizes every eager Sid to an id through TermDicts::subject_id. It does that for every row of the driver scan (:591) and every row of each fallback predicate scan (:854), before anything knows whether a batched walk will run. When every lane then declines, the lookups buy nothing. That happens for a predicate the index lacks (eager_declines_unindexed), a predicate the policy touches, or a translation failure. On main, eager keys stayed Sid and paid nothing.

The case is the canonical sub-property one: the data asserts only ex:mentors, and the query asks for ex:knows. Claude reproduced it on a c7i.8xlarge box (release, 100k people, OWL 2 RL, SELECT ?x ?y WHERE { ?x a ex:Student . ?x ex:knows ?y } LIMIT 10, which plans as a property join). Base eccd062a1 took 108.9–110.5 ms and head 5da2d346a took 200.9–205.6 ms, three warm runs each on one thread. With a 4-worker runtime the same query was 116.7–173.5 ms at base and 172.1–202.9 ms at head, across two rounds and three ledger states. Claude confirmed the cause by mutation: with only this match arm gated back to if !ctx.eager_materialization at head, the same single-thread run took 115.9–119.8 ms.

The fix is to normalize eager keys only when the chunk will actually run a batched walk. For example, decide it once per chunk from chunk_lanes (any Probe/SpotStar lane), and keep Sid keys for the fallback scans otherwise. main's cost and the PR's wins both survive that.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 837eeb1

Measured on an m7a.4xlarge: 100k entities, ex:mentors ⊑ ex:knows, OWL 2 RL, SELECT ?x ?y WHERE { ?x a ex:Student . ?x ex:knows ?y } LIMIT 10, warm p50 over 3 rounds with the build order rotated. Single-thread: main 141–146 ms, before the fix 168–203 ms, after 138–142 ms. 4 workers and an indexed-plus-novelty state show the same pattern.

Comment thread fluree-db-query/src/join.rs Outdated
@@ -1544,11 +1575,28 @@ impl Operator for NestedLoopJoinOperator {
// the batched lane (the merge injects their facts) instead

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.

Blocking (same class as the property-join comment): the nested-loop join pays the same lookup before its cost check runs. Under eager every left row's Sid is resolved to an s_id (memoized, but one reverse lookup per distinct subject) as it is accumulated. Then, for a cold lane, the final flush can hand all of those rows back to the per-row path (join.rs:1992-2000), which never needed the ids. Claude measured SELECT ?y WHERE { ex:hub ex:knows ?y . ?y a ex:Agent } (1,000 rows, an rdf:type exists probe whose derived extent is far over 1000 × 8) at 10.1–11.5 ms warm at base and 10.9–12.3 ms at head, +5–9% run for run across two rounds and two ledgers. By the cost check's own rule (1,000 × 8 is far under the derived rdf:type extent), that probe goes per-row, so its ops never warm and every run pays the lookups again. Claude didn't capture this query's routing or isolate it by mutation; the number is measured, and the mechanism comes from reading the code path above.

A cheap fix: while batched_overlay_deferred is set, accumulate (batch, row) only, and resolve the keys at the flush once the plan is known to proceed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 837eeb1

Same box, SELECT ?y WHERE { ex:hub ex:knows ?y . ?y a ex:Agent } (1,000 rows, cold lane, per-row): main 7.9–8.2 ms, before the fix 8.6–8.7 ms, after 8.1–8.4 ms. The remaining 1–4% is unexplained.

Comment thread fluree-db-query/src/fast_path_common.rs Outdated
if ctx.eager_materialization {
return Some(ProbeLanePlan::Decline);
}
// Eager callers (reasoning) are admitted: the resolved ops carry the

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.

Optional (design). This is more of a design note than a defect. Admission used to decline eager for every lane, and now it admits eager for every lane; a lane that can't decode has to remember to opt out (cyclic at cyclic_bgp.rs:1147, the grouped OPTIONAL builder at optional.rs:1173,1230). That's correct today. But next's typed object lane, #2292's batched pair join and #2214's union probes were all written under the old default, and each will be admitted under reasoning as soon as it meets this change in a merge. I wonder if the lane planners should take the capability as an argument instead, e.g. LaneOutput::{Encoded, DecodesForEager}, with probe_lane_admission declining eager unless it's DecodesForEager. That makes the next lane decline by default and puts admitting it in a reviewable diff. It's about eight call sites, and this PR already holds the chokepoint. I recognize this is non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 837eeb1 and 2da29fe

In the nested-loop join the output is declared per lane (batched_lane_output()), so a new join lane that isn't listed, such as #2292's pair lane, declines eager by default. I posted heads-ups on #2214 and #2292.

rhs: Option<&Flake>,
leftmost: bool,
) -> Option<usize> {
// The base's whole-graph count bounds its range count.

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.

Optional (performance). Novelty doesn't implement overlay_range_flake_count, so this falls back to the base's whole-graph count (as does CompositeOverlay in fluree-db-api/src/overlay.rs:84). With a lot of unindexed novelty, a cold final flush with fewer than novelty / 8 rows goes per-row whatever the probed predicate's own extent. That gives up the PR's win, though it doesn't fall below main. Novelty's segments already return the range as a slice (seg.range(index, first, rhs, leftmost), fluree-db-novelty/src/lib.rs:1775), so the count is a sum of len()s over the graph's segments. StagedLedger could do the same. Minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deferred to #2324.

Comment thread fluree-db-query/src/fast_path_common.rs Outdated
return Ok(Some(hit));
}
let computed = compute()?;
if let Some(ops) = &computed {

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.

Optional (performance). Only Some is kept across queries. When translation fails (collect_resolved_overlay_ops walks the whole extent, logs a warn!, and returns None), every later query against the same state walks, fails and warns again. A rule that derives a string the dictionaries have never seen is enough (resolve_string_v3) when it derives into an indexed predicate. main declined eager before translating, so this is new per-query work. A negative entry (say, a sentinel per key) would make it once per state. Claude didn't reproduce this one: the harness's CONCAT rule derived into a predicate the index lacks, which eager_declines_unindexed catches first. Not a big deal, but cheap insurance; I'd fold it in here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 837eeb1

Since b8aba38 the negative entry lives on the materialization with the other translations.

Comment thread fluree-db-query/src/fast_path_common.rs Outdated
type PredOpsKey = (crate::binary_scan::GlobalTranslationKey, Sid);

/// Budget of the cross-query per-predicate cache, in ops (~40 B each).
const PRED_OPS_CACHE_MAX_OPS: usize = 1 << 22;

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.

Optional (memory). Two small things on the new cache. (1) Each datalog fixpoint pass builds a fresh DerivedFactsOverlay (datalog_rules/execute.rs:379-385), so its cross-query entries are never read after the pass, yet they hold LRU budget until evicted; skipping the cross-query insert for an intermediate pass would keep the budget for the closure queries actually reuse. (2) The 4M-op budget is a compile-time constant in a process-lifetime static, beside the scan's own global_translation_cache, which is keyed by the same GlobalTranslationKey and can hold the same derived extent whole. An embedder sees up to ~160 MiB here that it can't size, so we may want at least a sentence in the doc comment naming both caches and the budget, or a knob. Minor; I'd rather see it in this PR than tracked-and-forgotten.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in b8aba38, differently from what you suggested.

(1) Fixpoint passes no longer keep anything across queries: translations now live on the reasoning materialization, and rule bodies run with reasoning off, so they never get one.

(2) There's no knob, and the separate cache is gone. Translations are made lazily on the materialization, shared by the queries reading it, and dropped with it. They count toward its reasoning memory budget beside the derived facts. One that won't fit isn't made: the join runs per row, with one WARN per materialization. docs/query/reasoning.md has the provisioning contract. Moving the scan's global_translation_cache the same way is #2332.

));
}
if std::mem::take(&mut self.batched_overlay_deferred) {
// Only a final flush knows its input is all there is.

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.

Nit. compute_batched_overlay_mode's doc comment (join.rs:2055) still says "Decline cases route ... BEFORE any accumulation, so a flush never reroutes mid-stream", and a deferred plan now reroutes at exactly this flush. This is so minor, but the comment is the invariant the next reader will trust. Commenting here because join.rs:2055 is not in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 837eeb1

@@ -0,0 +1,995 @@
//! Batched join lanes under a reasoning overlay.

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.

Praise. The mutation table in the body (each row a broken piece of code and the test that went red) is the best evidence a perf PR in this area has carried. Claude also ran a broader differential on the box: 27 SPARQL and 5 policy-restricted JSON-LD queries under OWL 2 RL, RDFS, datalog and none, covering owl:sameAs, sub-class/sub-property, domain/range, inverse/symmetric/transitive, OPTIONAL, UNION, @list, lang and typed literals, and policy denies on base, derived and rdf:type. They ran at the index, after a commit that both adds and retracts facts that fed derived ones, and in time travel back. All 182 result sets were identical at base and head and matched a never-indexed oracle, and 148 of them flushed a batched lane at head.

…hem; admission is opt-in per lane

Under reasoning, the property join resolved every Sid key to an id before
knowing whether a batched walk would run. It now plans its lanes first and
keeps Sid keys when every lane declines. The nested-loop join no longer
resolves decoded keys while its overlay plan is deferred; the flush resolves
them once the lane proceeds, and rows without an id go per-row. Stored left
batches survive a flush that leaves a per-row backlog.

The lane planners take a LaneOutput. Admission declines eager callers for
Encoded lanes, so a lane is admitted under reasoning only by declaring that
it decodes. The cyclic cascade, OPTIONAL builders and range semijoin are
Encoded.

The cross-query ops cache admits reasoning queries only (not datalog
fixpoint passes or dataset members), keeps failed translations so a state
walks and warns once, and documents its budget beside the scan's
translation cache.

Adds a test for a deferred plan that declines on a non-final flush, and a
unit test for eager admission.
…lane

A batched lane added to the join without being listed declines eager callers
by default, like a lane planner called with LaneOutput::Encoded.
…aterialization

Both depend on a cross-query entry keyed by the materialization's content
version; an eviction from the reasoning cache rebuilds it under a new one.
A regression still fails every attempt.
…soning-only cross-query ops

The selective-input and mid-stream-decline tests read what an earlier query
left in the cross-query ops cache, keyed by a materialization that sibling
tests in grp_reasoning could evict from the process-wide reasoning cache. In
a binary of their own they no longer need retries. Their shared helpers move
to tests/support/reasoning_lanes.rs.

A unit test pins that only reasoning queries keep translated ops across
queries.
…ops, within its memory budget

The batched lanes' translations of derived facts now live on the
materialization (DerivedFactsOverlay::attachment) instead of a process-wide
LRU with a fixed 160 MiB ceiling. They are made lazily, shared by every query
reading that materialization, and dropped with it. A materialization keeps
translations for one store binding and replaces them when it changes.

They count toward the materialization's reasoning memory budget beside its
derived facts, once per materialization: a translation is reserved before it
is made, and one that would pass the budget is not made, so the lane declines
and its join runs per row. The first refusal per materialization logs a WARN
with the phase, estimated sizes, limit and derived-fact count, and what to
change. The reasoning docs describe the provisioning contract.
@bplatz

bplatz commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@jdorety, on your review:

  1. Mid-stream reroute test: addressed in 837eeb1. Your test is in as a_deferred_plan_declining_mid_stream_keeps_every_row. It asserts that a flush before the last one declined, through a new join batched probe: overlay plan declined; per-row debug event. It fails under both of your planted bugs. A failed translation is now cached, so a rerun declines before accumulating, and the test checks that too.
  2. Cache admitting non-reasoning callers: addressed in 837eeb1 and b8aba38. Translations now live on the reasoning materialization itself, so fixpoint passes (rule bodies run with reasoning off) and dataset members reading plain novelty can't reach them. only_a_materialization_keeps_ops_across_queries pins this.
  3. warm phase flake: addressed in e3409f9. The two cache-dependent tests moved to a binary of their own, it_reasoning_lane_cache, with no retries. It failed 0 of 40 runs at 64 threads.
  4. it_reasoning_request_limits at 64 threads: this reproduces on main (4 of 40 runs). The warm query materializes again after a sibling evicts its result from the 16-entry reasoning cache. Filed as it_reasoning_request_limits fuel tests flake under load: the warm query re-materializes #2326.

@bplatz
bplatz merged commit c7fd79d into main Nov 11, 2026
28 of 30 checks passed
@bplatz
bplatz deleted the perf/reasoning-batched-probes branch November 11, 2026 16:15
bplatz added a commit that referenced this pull request Nov 11, 2026
Brings #2271 (reasoning batched lanes) and #2274 (spatial index rebuild).

- The object lane's overlay ops: main caches the IRI_REF subset as the
  merge plan; next's object lane also batches triple-term keys, so a
  term-handle flush reconciles against its own o_type subset
  (object_probe_ops) instead of the plan's ref ops.
- The left-key loop keeps next's per-key o_type and main's deferred,
  memoized key resolution; the per-row path keeps next's independent scan
  replay ahead of main's open_per_row_scan.
- Overlay providers carry both new methods (next's overlay_graph_ids,
  main's overlay_range_flake_count).
- Lane admission takes main's LaneOutput and keeps next's pooled-graph gate.
- Main's tests: async genesis ledgers, content_store by namespace,
  ContentBytes, 64-bit list place. The named-graph reasoning lane test pins
  its graph dedicated, since the batched lanes don't read a pooled graph
  under reasoning.
aaj3f added a commit that referenced this pull request Nov 13, 2026
Brings in main at 467f0da, with #2271's LaneOutput admission, #2251's
graph drop and #2226's language-tag pushdown.

- cyclic_bgp.rs: the per-member subject probe plan takes
  LaneOutput::Encoded, since the cascade emits encoded bindings.
- join.rs: the batched gate takes main's deferred overlay plan and eager
  rule, and keeps this branch's one-graph scope test. The union probes'
  per-member plans take LaneOutput::Encoded: the union variant emits
  encoded rows and declines eager materialization. The one-graph object
  probe takes main's branch_or_none, Arc'd ops and eager subject decoding;
  the subject probe takes main's subject_lane_object_binding.
- join.rs: main's flush now hands a declined plan's rows to the per-row
  path. The one-graph plan declines every union scope, so that check skips
  the union variant, which carries its members' own plans.
- join.rs: open_per_row_scan takes the scope's TermView, which this
  branch threads through the per-row path.
- registers: main greened the optional-complex cluster, this branch
  open-eq-05/06; both leave the register.
- tests: graph_id_for_iri is assigned_graph_id on main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants