Skip to content

perf(r2rml): keyed scans for bound subjects and for the parents of referencing object maps - #2316

Merged
aaj3f merged 22 commits into
mainfrom
perf/r2rml-keyed-scans
Nov 13, 2026
Merged

aaj3f merged 22 commits into
mainfrom
perf/r2rml-keyed-scans

Conversation

@aaj3f

@aaj3f aaj3f commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two query shapes over an Iceberg-backed R2RML graph source used to read whole tables even though the query already held the keys it needed. With this PR the keys narrow the scan:

  1. Subjects bound by the scan's input. When a VALUES block or an earlier pattern binds the subject variable, each map's scan gets the reversed template keys of the bound subjects, as an IN (or =) on the key column(s). Until now this only happened for a single constant subject.
  2. Parents of referencing object maps. The parent of a rr:parentTriplesMap join is read for the join keys each window of referencing rows needs: a semi-join probe with the keys pushed. It used to be read whole before the first referencing row. One probe-built index per parent serves every map and every RefObjectMap that reads it. A map probes only while the planned file counts show its probes skip files, and its probes together stay under one whole read. Every whole read now streams, folding batches into the lookup as they arrive, so the parent's raw batches are never resident next to the lookup built from them.

Both rest on the Parquet reader applying a pushed IN row by row; it used to only prune with it. Pruning with an IN is now a binary search per file: members sorted once, bounds decoded once.

Two commits fix wrong answers from the scan-side top-k under ORDER BY … LIMIT k, which fed its heap rows that never reach the output:

  • rows a later step drops (the first commit): the join with the scan's input, when the input binds a variable the scan produces, or a pushed filter the reader applies only in part. VALUES ?id { 5 2500 } ?s ex:id ?id ORDER BY DESC(?id) LIMIT 2 answered only 2500.
  • rows that yield no solution (88ecddc1c): a NULL subject column, a NULL star member, a dangling reference.

No query answer changes otherwise. Keep-min on a duplicate parent join key is unchanged here: a probe returns every parent row of each key it probes.

Fixes #2239
Partially addresses #1841: this removes the raw-batch double residency at the R2RML parent-scan site the issue's comment names, and a LIMIT or bound key set no longer reads the parent whole. The issue's main point remains open: query memory accounting charges a flat size per binding and ignores the heap behind bindings, at every charging site.
Context: #1583 (what a duplicate parent key should mean; not changed here).

Changes

Top-k soundness (r2rml/operator.rs, fluree-db-iceberg scan/topk.rs)

  • set_topk records no directive when the scan's input binds a variable the scan produces, so the scan also stays eligible for the scan cache. At scan time the directive is declined on a residual filter (as before) or on any pushed filter.
  • The heap counts only rows that yield a solution. The directive names the columns a row needs non-null (the subject's, each star member's), and the Iceberg reader skips rows with a NULL in one. It is declined when a star member is a reference (it may dangle) or maps to several object maps.

Row-level IN (fluree-db-iceberg io/arrow_reader.rs)

  • Each member is prepared exactly as column = member, held in a hashed set of the column's comparison type (integers, text, decimal128), or applied as one equality per member up to 64 for other types.
  • A member that can't be compared exactly keeps every row; a member no cell can hold drops out; a null cell is dropped.

IN pruning (scan/pruning.rs, scan/predicate.rs)

  • InSet builds, once, one sorted run per kind whose comparisons are total. Decimals, NaN floats and UUIDs are checked one by one as before.
  • A file or row group is decided by a binary search per run against bounds decoded once, with exactly the per-member semantics. Planning a 1024-member set over 2000 files dropped from about 1 s to 1.5 ms (debug build).
  • Members are shared, so a plan's per-file copy of its filter copies a pointer.
  • The fluree materialize path's uncapped key sets get the same speedup.

Subject keys (fluree-db-r2rml TemplateReverser, r2rml/operator.rs)

  • Per input window, bound subject IRIs are reversed through each map's IRI template: one filter per key column (exact for one column, a superset for several; the join stays exact).
  • An IRI the template cannot produce adds no key, and a map that can produce none of them isn't scanned.
  • A table the scan cache would hold takes the keys by its known row count (cached plan, snapshot summary, or disk catalog; never a manifest read). With no known count, the first window pushes and a later one learns.

Keyed parent index (r2rml/operator.rs)

  • CompleteParentLookup is the only type the per-operator cache and the query-scoped parent memo hold, and only a whole read builds one.
  • One probe-built index per parent and join columns serves the whole scan. Every map and RefObjectMap that reads the parent shares its resolved keys and its single whole read. Each window resolves, in one probe, the keys all of its RefObjectMaps' columns hold: a ship-to and a bill-to address into one parent, or two maps into one parent.
  • Probe-built indexes record resolved keys, including absent ones. A probe folds only the rows of the keys it probed: a provider never drops a row the pushed filters keep, but may return more (every row of a file whose bounds admit a key), and a key read that way can be missing rows in files the probe skipped.
  • Probes are bounded per referencing map: one map's probes together read fewer files than one whole read (one probe when there are no file counts), and another map's probes don't count against it. The worst case is one whole read's worth of probes per referencing map, plus one whole read, which then serves every map.
  • A probe's file counts are planned from the snapshot's kept file list (memory, then the disk catalog), the same path a scan takes; manifests are read only on a cold miss.
  • When probes give way to a whole read, what they built is dropped and its memory charge released first, so the parent is never held or charged twice.
  • While a probe-built parent is in play, a window is cut to its LIMIT budget.
  • Whole reads stream and are charged per batch.
  • Every read whose result folds into an order-independent structure (the probe, the whole read behind build_parent_lookup, and the fused aggregate's reference-key parent map, dimension maps and semi-join levels) goes through one helper, scan_for_lookup, which asks for ScanOrder::Any, so it streams as files finish rather than in the fixed order a sliced scan needs. Output order still comes from the main scan. Measured: parity on every parent shape on local disk with equal-size files; the gain should show where reads differ in latency.
  • A fused semi-join level's SCD-2 decline is decided once the whole level is read, so it no longer depends on whether a larger subject's colliding rows arrive before the keep-min row (it changed which lane a query takes, not its answer). feat(r2rml): an R2RML graph source answers over the set of triples its mapping defines #2317 replaces this with its every-parent rule.
  • A keyed read's file and row counts (the probe budget and cache sizing) resolve an rr:sqlQuery parent to its FROM table first, so a reference into a filtered parent from feat(r2rml): narrow a triples map over Iceberg with a restricted rr:sqlQuery #2309 is probed instead of failing.

Switches

  • FLUREE_R2RML_KEY_PUSHDOWN (default on) turns off both key pushes; whole reads still stream.

Breaking changes (for embedders)

  • fluree_db_iceberg::Expression::In's values is now an InSet instead of a Vec<LiteralValue>. It derefs to the members and is built by Expression::in_list or InSet::new; code that constructs Expression::In { values: vec![..], .. } literally must switch to one of those.
  • ScanTopK gains required_columns: Vec<String>. A struct literal must set it (empty when nothing is required), and a provider that cannot check every named column must not prune with the directive.
  • R2rmlTableProvider gains scan_file_counts and known_row_count, both defaulting to Ok(None) (no change needed for implementors).
  • FLUREE_R2RML_IN_PUSHDOWN_MAX now defaults to 1024 (was 64) and bounds every set a scan push carries. A FILTER … IN or single-variable VALUES set of 65 to 1024 values used to be applied only in the engine after a full scan; it is now pushed, so files whose bounds exclude every value are skipped and the reader drops rows outside the set. Answers are unchanged. Measured on a 16-file, 2M-row table, such a set is 2.6 to ~2,800 times faster (12.1 s → 5.9 ms for 256 ids in one file; 11.5 s → 2.0 s for a 256-value set matching a quarter of the rows); a 1024-value set that matches every row takes the same time (24.8 s both; 2.5 vs 2.6 s for VALUES, with ~0.8% more instructions from the reader's row check). Set the variable to 64 for the old behaviour.

Tests

  • Unit tests:
    • set_topk and what scan_table receives.
    • Subject keys: pushed, composite, unbound, irreversible, unproducible map.
    • Perf guard, with and without a known count.
    • Probe path checked against a whole read under LIMIT 1/2/5/100/none, with a duplicate parent key and dangling FKs.
    • Probe rules: no counts, clustered, unclustered, cumulative bound, and a map refused a probe by its own budget only (it keeps probing while two maps' reads together reach a whole read).
    • Two RefObjectMaps into one parent through different columns (star, variable predicate); two maps into one parent across input windows; a bounds-only provider that returns extra rows; the memory charge after probes give way to a whole read. Each against a whole read.
  • Reader IN tests: integer widths incl. u64 overflow, text, decimal grid, dates, undecidable members.
  • Pruning tests: a 160,000-case differential against the per-member check (truncated-string shapes, NaN and both zeros, decimal scales), plus clone sharing.
  • TemplateReverser round-trip.
  • Integration (it_iceberg_local_fs, iceberg_local_fs_top_k; SPARQL and JSON-LD twins, against a ledger holding the same triples):
    • top-k over a joined scan and over a reference bound by VALUES;
    • top-k over a two-file fixture whose top rows yield no solution (a NULL subject, a NULL star member, a dangling reference), plus a pruning control;
    • a VALUES subject set;
    • a referencing map with a duplicate parent key, dangling FKs, LIMIT and VALUES;
    • two RefObjectMaps and two maps into one parent.
  • Each new test fails with its fix reverted.
  • Gates at 10e2037 (the merges after it bring only the base branch's docs commit and test-capture fix), on a quiet dedicated 32-vCPU cloud machine with CI's environment: fmt (workspace and testsuite-sparql), cargo clippy --all --all-features --all-targets --locked -- -D warnings, the wasm32 fluree-db-api and parse lanes, cargo check --workspace --all-targets, and fluree-db-server with no default features. Tests: fluree-db-r2rml 175, fluree-db-iceberg 528, fluree-db-query 1850 and fluree-db-delta 86 (each --all-features); fluree-db-api with iceberg,native: lib 1216, grp_graphsource 282, grp_query_sparql 558, it_graph_source_r2rml 70, it_iceberg_local_fs 46, it_iceberg_policy 15, it_fused_aggregate_routing 1; with sql,native: it_sql_graph_source 6, it_sql_pushdown_lane 21, it_r2rml_untyped_columns 2; with delta,native: it_delta_local_fs 16, it_delta_differential 3; the W3C suite 85. No failures. Not run there: CI's SQL live-bridge differential job, the Python wheel, the wasm browser and Node smoke tests, and macOS. A later commit moves one test's log capture onto fluree_test_support::scoped_default, which the workspace harness check (harness_coverage, run by CI and not in the list above) requires.

Measurements

Against the base

Local filesystem, release build, the same shared machine (load 9 to 14), before = the base commit. Tables:

  • customers: 2M rows, 16 files.
  • customers_history: about 9.0M rows, 36 files, a non-unique customer_id.
  • orders: 6M rows, 24 files, 0.1% dangling FKs; scaled from about 30M, since a LIMIT reads one window.
  • members: 2M of 20M ids, shuffled or sorted, 16 files; events: 2M rows.

Medians of 3 interleaved processes; warm = queries 1 to 3. Answers identical on every shape, SPARQL and JSON-LD; every LIMIT answer self-checked.

shape before warm after warm peak RSS
VALUES ?s {3 subjects} ?s ex:name ?n 1091 ms 7 ms 589 → 68 MB
same subjects as a UNION of constants 16 ms 18 ms unchanged
VALUES ?s {64 subjects} 1077 ms 71 ms 594 → 169 MB
VALUES ?s {500 subjects} 1050 ms 14 ms 556 → 189 MB
?a ex:currentVersion ?v . ?v ex:versionScore ?x (3 bound ?a) 5904 ms 17 ms 777 → 88 MB
?o ex:forCustomer ?c LIMIT 5 (9M-row parent) 3595 ms 118 ms 1760 → 306 MB
VALUES ?o {3 orders} ?o ex:forCustomer ?c 6857 ms 23 ms 1483 → 84 MB
?o ex:forCustomer ?c, no LIMIT (6M rows) 28.1 s CPU 28.0 s CPU result-dominated
the same joined to the whole parent, 2,981 rows out 31.4 s CPU 31.1 s CPU 1576 → 1417 MB (cold, 5 runs)
low-yield LIMIT 5, unclustered parent 1296 ms, 9.8 s CPU 1268 ms, 2.7 s CPU
low-yield LIMIT 5, clustered parent 1268 to 1447 ms, 8.9 to 9.8 s CPU 1368 to 1370 ms, 1.5 s CPU
large input over a small cached table 37.2 s CPU 37.2 s CPU
  • Multi-second shapes are compared by CPU (user+sys): wall time on this machine varies about 2x for the same work.
  • On the clustered low-yield shape, one probe reads about a third of the parent before the parent is read whole.

The shared parent index, probe completeness and the top-k null mask

The final branch against f5a502758 (the commit before them): release build with fat LTO, a quiet dedicated 32-vCPU cloud machine, 5 interleaved rounds, instructions retired per process (billions). Answers identical.

shape before after
?o ex:forCustomer ?c LIMIT 5 49.75 49.75
VALUES ?o {3 orders} ?o ex:forCustomer ?c 7.73 7.73
low-yield LIMIT 5 73.77 73.62
the whole-parent join 393.1 (14.96 s wall) 383.1 (14.85 s wall)
two maps into one small parent 2.881 2.880
two maps into one 116-file parent 19.32 (39.2 ms) 19.32 (39.8 ms)
keyed top-k by score 227 (base spread 221 to 250) 241
keyed top-k over a star 310.2 311.1

The null mask's cost on a fully populated keyed top-k is within run-to-run noise: instructions −1.3% median over 8 more interleaved rounds (241.8 before, 238.7 after).

Not covered

  • The fused aggregate builds its own parent and dimension maps (fused_aggregate.rs) and still reads them whole.
  • An object variable bound by the scan's input pushes no keys yet (only subjects are reversed).

Follow-up: #2310

Stacking

Stacked on #2315 (perf/iceberg-filtered-plan-from-cache, filtered scans planned from the cached kept file list); review that first. Its reviewed head is merged in, which also brings #2309 and #2313 (merged into #2315 so they land first).

The first commit (9d7c7ba32, top-k fed rows a later step drops) is identical by patch-id to the one in #2313, which carries the top-k fixes to main on their own. #2313's required-columns commit matches this branch's 88ecddc1c in code; the two differ only in how the top-k test module imports the shared span capture. Whichever lands first, the other's copy reduces to that import.

  • CI (.github/workflows/ci.yml) runs only on pull requests into main, so while this PR is stacked it shows no CI run, only the Release workflow. The gates listed under Tests ran on a cloud machine with CI's commands. CI runs once the base is retargeted to main.

aaj3f added 14 commits November 3, 2026 00:24
ORDER BY ... LIMIT offers the R2RML scan a top-k directive: the provider
reads files best-first, keeps the k best rows it emits, and skips every file
that cannot beat them. That is sound only when every row the scan emits
reaches the operator's output, and two things dropped rows after the heap had
seen them:

- the join with the scan's input, when the input binds a variable the scan
  produces (a VALUES block, an earlier pattern, the seed of a sub-select or
  GRAPH scope): a produced row that matches no input row is dropped;
- a pushed scan filter, which the Parquet reader may apply only partly (it
  skipped IN sets, comparisons on unprojected columns, and literals that do
  not compare exactly with the column, and row filtering can be switched
  off), as may other providers.

Fed those rows, the heap's bound rode above the true top-k and pruned the
files holding it: VALUES ?id { 5 2500 } ?s ex:id ?id ORDER BY DESC(?id)
LIMIT 2 answered only 2500, and a VALUES naming two cells ahead of
?p ex:cell ?c ; ex:id ?id under ORDER BY DESC(?id) LIMIT 3 answered nothing.

set_topk now records no directive when the input binds a variable the scan
produces, which also leaves the scan eligible for the scan cache (a recorded
directive kept it off the cache even when declined later), and the scan
declines a recorded directive when any filter is pushed, as it already did
for residual filters and the view-policy gate. A root scan and an input that
shares no variable with the scan (a cross product, which every produced row
survives) keep the pushdown.
…y search

The Parquet reader treated a pushed IN as transparent: a set only pruned
files and row groups, and every row of a surviving row group came back. It
is now a row test. Each member is prepared exactly as an equality against
the column would be (the same exactness and coercion rules the comparisons
use), and the members are held in a hashed set of the column's comparison
type (integers, text, decimal128), or applied as one equality per member up
to 64 members for other types. A member the filter cannot compare exactly
keeps every row, a member no cell can hold drops out, and a null cell is
dropped.

Pruning checked every member against every file's bounds, decoding the
bounds again for each member: 1024 members over 2000 files took about a
second to plan (debug build). Expression::In now carries an InSet: the
members plus an ordered view built once from them, one sorted, deduplicated
run per kind whose comparisons are total, with decimals, NaN floats and
UUIDs checked one by one as before. A file or row group is decided by one
binary search per run against bounds decoded once (some member lies in
[lower, upper] iff the first member at or above lower is at or below upper;
a bound a run cannot be compared with constrains nothing, as the per-member
rule keeps on unknown), now about 1.5 ms for the same plan. The decision
equals the per-member check on 160,000 random sets and bounds of every kind,
including truncated-string shapes, NaN and both zeros, and decimal scales.
Members and ordered view sit behind Arcs, so the plan's per-file clone of
its filter copies two pointers, not the set. There is no separate prune
cap: every pushed set prunes, including the materialize path's uncapped key
sets.
A scan whose subject variable is bound by its input (a VALUES block, an
earlier pattern) read the whole table and joined the bound subjects in
memory; only a single constant subject was reversed through the subject
template into a key-column filter. Per input window, the distinct subject
IRIs the window binds are now reversed through each map's IRI template and
pushed as an IN (or =) on the key column(s): one filter per column, exact
for a one-column key and a superset for several, with the join still the
exact check. A row leaving the subject unbound, or a binding that cannot be
read as an IRI, pushes nothing; a literal binding joins no IRI subject and
adds no key.

Template reversal is split in two (TemplateReverser): deciding once whether
a template can be reversed, then each IRI. Through a reverser every IRI the
template produces reverses, so an IRI that does not is one the map cannot
produce, and a map that can produce none of the bound subjects is not
scanned at all.

A filtered scan bypasses the operator's scan cache, so a table the cache
would hold takes the keys by its size when the provider already knows it
(R2rmlTableProvider::known_row_count; the Iceberg provider answers from
its scan-files cache, the snapshot summary's total-records, or the disk
catalog cache, never by reading manifests): too large to cache, every
window pushes; small, it is read once unfiltered and replayed. With no
known count the first window pushes and a later one reads the table
unfiltered, which caches a small table or shows it is too large.

FLUREE_R2RML_IN_PUSHDOWN_MAX, the largest set any scan push carries, now
defaults to 1024 (was 64): the reader applies a set row by row and prunes
with it by binary search. FLUREE_R2RML_KEY_PUSHDOWN (default on) turns the
key push off.
…need

The parent of a rr:parentTriplesMap join was scanned unfiltered and
collected in full into a hash lookup before the first referencing row was
read, however few rows reached it: a LIMIT 5 over a fact table joined to a
9M-row dimension read the whole dimension. The raw parent batches and the
lookup built from them were resident at once, and only the lookup was
charged to the query's memory budget.

Now, per window of referencing rows, the join keys the window holds that
are not yet resolved are read from the parent with the keys pushed (a
semi-join probe), and every key read is folded in: the pushed filter keeps
every parent row of each key it keeps, so keep-min on a duplicate key is
unchanged, and a probed key nothing came back for is a dangling reference,
never probed again. While a parent is resolved this way a window is cut to
its row budget, so a LIMIT 5 probes about five keys rather than a whole
Parquet batch's. A probe is made only when the keyed read's planned file
counts (R2rmlTableProvider::scan_file_counts; the Iceberg provider plans the
filtered scan, manifests only) show it skips files and all probes together
read fewer files than one whole read; without counts, at most one probe.
Otherwise, and when a window holds more keys than the push cap, the parent
is read whole once.

A whole read now streams: batches fold into the lookup as they arrive and
are charged per batch, so the raw parent is never resident beside the
lookup, on every path. The lookup a whole read builds is a
CompleteParentLookup, the only type the per-operator cache and the
query-scoped parent memo hold, so a lookup built by probes can never be
served as whole to another batch or operator. The trusted-crawl ref
shortcut is unchanged.
…keyed-scans

# Conflicts:
#	fluree-db-api/tests/it_iceberg_local_fs.rs
…pt list

With filtered scans planning from a snapshot's kept file list, the keyed
reads' file counts (scan_file_counts, which decide whether a parent probe is
worth making) still planned by reading the manifests on every call. They now
go through the same path as a scan: plan_from_kept_files, factored out of
scan_table, plans from the in-memory list, then the disk catalog's
(promoted into memory), and only on a cold miss reads the manifests,
keeping the list for the scan that follows. known_row_count reads the kept
list's record count (memory, then disk) before the snapshot summary, and
still never reads manifests.

Also fixes the seams the merge left: the cached list's record count is now
CachedScanFiles::record_count(), the snapshot schema
TableMetadata::read_schema_for_snapshot, and the window mapping the top-k
and subject-set tests use is renamed WINDOW_PEOPLE_R2RML, as the filtered
plan tests define their own WINDOW_IDS_R2RML.
…reads it

A probe-built parent index is keyed like a complete lookup, by the parent
TriplesMap and its join columns, but it carried the join columns of the
referencing map that created it and resolved only the keys those columns
held. Two RefObjectMaps reading one parent by the same parent column through
different columns of their own (a ship-to and a bill-to address) shared the
first one's index, so the second one's references resolved only when the
first happened to hold the same key; a star or variable predicate holding
both lost the rest. Across TriplesMaps, the index kept from one input
window's scan for the next was the last map's, so from the second window
another map read its keys through the wrong columns: an absent column
probed nothing and dropped every reference, a column of the same name
probed the wrong keys.

The index now holds only what the parent holds for the keys resolved, one
per key for the whole scan, shared by every map. Each map records the
columns of its own table its RefObjectMaps read each parent by, and a
window resolves the keys every one of them holds, in one probe. The bound
on probes (together fewer files than one whole read; one probe without file
counts) now holds per parent rather than per map.
A probe folded every row the keyed read returned and marked each key those
rows carried as resolved. That is complete only for the probed keys: a
provider never drops a row the pushed filters keep, but it may return more
than they keep, such as every row of each file whose bounds admit a key
when row filtering is off or the provider prunes by file only. A key that
came back that way may be missing its rows in the files that were skipped,
so a duplicate parent key kept the minimum over part of its rows, a subject
other than a whole read's, and the key was never probed again. Now only the
rows of probed keys are folded, and only probed keys are resolved.
The batches a parent probe folded were charged to the query's memory budget
and never released. When later windows needed more keys than probing was
worth and the parent was read whole, the probe-built index was dropped but
its charge stayed, and the whole read was charged on top: up to about twice
the parent, enough to fail a query with MemoryBudgetExceeded that fit
before. The index now tracks what it was charged (folded batches and the
keys it resolved), and before the whole read it is emptied and that charge
released, so the parent is neither held nor charged twice. The per-window
set of missing keys is transient and bounded by the push cap, so it is not
charged.
The scan-side top-k reads a map's files best-first and stops once no unread
file can beat the k-th sort value it has seen. It counted every row it
read, but a row whose subject column is NULL mints no subject, and a row
with a NULL in a same-subject star member's column yields no star row:
both are dropped after the scan. Counted, they lift the k-th bound above
rows that belong in the answer, and the files holding those rows are
skipped. With a NULL id on the top name, ORDER BY DESC(?name) LIMIT 4
answered three rows where a ledger answers four.

ScanTopK now names the columns a row must hold non-null to yield a
solution (required_columns: the subject's template placeholders or column,
and each star member's object column or template placeholders; a constant
needs none), and the Iceberg provider observes a sort value only from rows
non-null in all of them. A required column the table lacks declines the
directive. Where no set of columns decides whether a row emits, the
directive is declined: a star member that is a reference (its key may
match no parent row) or that maps to several object maps.

The pushed-filter arm of topk_feed_may_drop_rows is now documented as
defence in depth: every source of a scan filter already declines the
directive or keeps it from being recorded.
One probe-built index now serves every map that references a parent, and
its probe budget (keyed reads together fewer files than one whole read; one
probe without file counts) had become shared too. That counts one map's
probes against another's: two maps over one parent whose keyed reads each
skipped most files, but together reached the whole table, had the second
map's cheap probe refused for a whole read of the parent. On a 36-file,
9M-row parent that turned a 41 ms query into a 4.9 s one. The index,
its resolved keys and the single whole read stay shared; the budget is
counted per referencing map again, as it was before the index was shared.

A test pins the per-map probe budget at the index itself: one map keeps probing
while its own reads stay under a whole read even though two maps' reads
together reach it, and is refused only by what it alone has read. The doc
of worth_probing now says why: another map's reads are sunk cost, the
choice for a window is this probe or a whole read now, and the worst case
is one whole read's worth of probes per referencing map plus one whole
read that then serves every map.
Brings the planner branch's final state, which also carries origin/main.

Resolutions:
- graph_source/r2rml.rs, r2rml/mod.rs: the imports take both ScanFileCounts
  (keyed scans) and ScanOrder (the planner branch); the kept-list planner
  helper and main's catalog-client warm-up both stay.
- r2rml/operator.rs: the main scan takes the planner branch's scan order;
  its cache key was already hoisted by keyed scans. Parent probes and whole
  parent reads use scan_table, which owes a deterministic order.
- it_iceberg_local_fs.rs: both sides' tests kept.
@aaj3f aaj3f added breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section area:iceberg Iceberg catalogs/credentials, R2RML, virtual datasets, materialize area:query Query execution, planning, fast paths, overlay, result formatting performance Performance improvement (release notes: Performance) labels Nov 11, 2026

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

Key pushdown is sound as far as I can find: a reversed template key either gives an exact or superset filter or skips the push, probes fold only the rows of the keys they asked for, and the caches hold only whole-read lookups. I also ran the fluree-db-query r2rml tests, the fluree-db-iceberg suite and it_iceberg_local_fs on this head; all pass. Approving, but please look at the inline comment and the points below before merging.

  • FLUREE_R2RML_IN_PUSHDOWN_MAX now defaults to 1024, which also changes FILTER … IN and VALUES sets that were already pushed. docs/audit-impl/cov-scan-gates.md still says =64.
  • Landing order, as on #2315: #2309 and #2313 first, then #2315 and this stack rebased onto them. The two top-k commits here are the ones reviewed in #2313, so they drop out once it is on main.

Comment thread fluree-db-query/src/r2rml/operator.rs Outdated
"R2RML parent: reading the rows of a window's join keys"
);
let mut stream = provider
.scan_table(

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.

Parent reads pay for a fixed row order they don't use. Probes and whole parent reads go through scan_table, which since #2315 means smallest-file-first with head-of-line blocking. The lookup they build is a hash map with keep-min on a duplicate key, so its contents don't depend on read order. Asking for ScanOrder::Any here (and in build_parent_lookup) would let the reads stream as they finish. Your whole-parent numbers show parity, so this is a missed gain rather than a regression — fine as a follow-up if you'd rather not touch it 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.

Agreed, and done here rather than as a follow-up -- a8b7ed1 routes every read that folds into an order-independent structure through one helper, scan_for_lookup, which asks for ScanOrder::Any: this probe, the whole read in build_complete_parent that feeds build_parent_lookup, and the fused aggregate's reference-key parent map, its terminal and interior dimension maps, and its semi-join levels.

Sweeping those turned up one read whose result did depend on order, which I'm glad we caught before flipping them: a semi-join level's SCD-2 decline compared each row only with the row kept so far, so whether it declined depended on whether a larger subject's colliding rows happened to arrive before the keep-min row. f6709e1 decides that once the whole level is read, so it declines exactly when the keep-min subject's own rows disagree. (It only changes which lane a query takes, not its answer -- the generic path binds the keep-min subject either way.) Output order still comes from the main scan, which stays deterministic for a sliced query.

Tests: unit tests record the order each parent and dimension read asks for, and a new paging test pages an unordered LIMIT/OFFSET query over a referencing map (parent read whole and probed) on both surfaces in two fresh instances; with the parent fold made first-wins, that test is the only integration test that fails.

Measured before/after on a quiet box: parity on every parent shape (e.g. the whole 9M-row parent 11.21 → 11.28 s warm, 12.78 → 12.52 s cold). The head-of-line gain you'd expect didn't show here, but that was local disk with equal-size parent files -- it should show where file reads differ in latency, which I couldn't measure without standing up cloud storage.

… subject only

A semi-join level keeps, per join key, the row with the smallest parent
subject, and declines the fuse when two rows of one key and one subject
disagree on the constraint result or the next hop (an SCD-2 collision),
since keep-min alone cannot choose between them. The check compared each
arriving row with whatever row was kept so far, so it declined or not by
the order the rows arrived in: two colliding rows of a larger subject read
before the smaller subject's row declined, and read after it did not.

The collision now marks the kept row, a smaller subject replaces the row
and its mark, and the level declines after it is read if a kept row is
marked. The decision is the same in any arrival order: it declines exactly
when the keep-min subject's own rows disagree. A collision on a subject
keep-min discards no longer declines; the generic path binds the keep-min
subject too, so the answer is the same.
A sliced query's scans emit their files smallest first, so its rows come
in the same order on every execution. Parent reads went through the same
`scan_table`, so a parent probe or whole parent read waited on its smallest
file first even though nothing it builds depends on order: the parent
lookup keeps the smallest subject on a duplicate key, whatever order the
rows arrive in.

Reads that fold into a structure whose contents do not depend on read
order now go through one helper, `scan_for_lookup`, which asks for
`ScanOrder::Any` and folds each file as its read finishes: a parent probe
and a whole parent read in the R2RML scan operator, and the fused
aggregate's reference-key parent map, terminal and interior dimension maps,
and semi-join levels (the last made order-independent by the previous
commit). The query's own row order comes from its main scan, which keeps
the order the query owes.

Tests: unit tests record the order each read asks for (every parent and
dimension read asks for `Any`; the main scan of a sliced query stays
deterministic), and a paging test over a referencing map checks that the
pages of an unordered `LIMIT`/`OFFSET` query, over a parent read whole and
one read by key, are the child's scan order with each row's keep-min
parent, on SPARQL and JSON-LD, in two fresh instances.
`FLUREE_R2RML_IN_PUSHDOWN_MAX` defaults to 1024 since the keyed scans, and
SWITCHES.md and the code say so; the scan-gate record still read `=64`.
It now says the cap was 64 when those switches landed and is 1024 now.

Raising the cap was measured: FILTER IN and VALUES sets of 64, 256 and 1024
values over a 16-file, 2M-row table, selective and not, with the cap at 64
and at 1024. A set the larger cap now pushes is 2.6 to 2,800 times faster,
and one that matches every row (where the push can skip nothing) takes the
same time.
Brings the planner branch's review fixes and what it now carries: the
reviewed row-filter (#2309) and scan top-k (#2313) branches, and
origin/main.

Resolutions:
- iceberg io/arrow_reader.rs: one prepared check serves both lanes. The
  row filter's comparisons and its IN sets (keyed scans: a member set
  applied row by row) and the exact row filter of an rr:sqlQuery map
  (#2309) both prepare through prepare_check, whose Check carries the
  literal as a one-element array; check_mask applies Compare (wrapping the
  literal as a scalar), Member (the set's row mask), NotNull and DropAll
  for either lane. An IN member that prepares to NotNull keeps every row,
  like any member the filter cannot compare exactly.
- query r2rml/operator.rs: the top-k tests #2313 adds are the ones keyed
  scans already carries (9d7c7ba and 88ecddc, same code); one copy is
  kept.
- api it_iceberg_local_fs.rs: the #2313 top-k cases over people_window
  likewise appear once. The paging test keeps keyed scans' shared
  paged_scan_order helper and takes the planner branch's selectOne and
  AgentJson checks and doc. The fixture list gains the tombstones table.
- scripts/local/write_local_iceberg_table.py: the planner side's blocks
  (the filtered customers_history/orders tables, versions, tombstones)
  hold keyed scans' versions block verbatim; taken once.

Parent and dimension reads stay on scan_for_lookup (no row order); every
plain scan_table left in the query crate's r2rml lane is in a test.

No test expectation changes.
… parent first

The row-filter branch made the table loader refuse an rr:sqlQuery alias: a
reader must resolve the logical table first, so a filtered map is never
read without its filter. Two reads keyed scans added still handed the
loader the map's table name: scan_file_counts, which decides whether a
parent probe is worth making, and known_row_count, which sizes the scan
cache. A reference into a filtered parent therefore failed every query
("reached the table loader unresolved").

Both now resolve the logical table and count its FROM table: the table's
count bounds what the filter keeps, and the file counts only decide whether
a keyed read is worth making. The filtered-logical-table suite's reference,
crawl and kept-list cases pin it; they failed without this.
@aaj3f

aaj3f commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bplatz -- and for running the suites on the head.

Base automatically changed from perf/iceberg-filtered-plan-from-cache to main November 13, 2026 16:25
@aaj3f
aaj3f merged commit fe5febc into main Nov 13, 2026
19 checks passed
@aaj3f
aaj3f deleted the perf/r2rml-keyed-scans branch November 13, 2026 17:32
aaj3f added a commit that referenced this pull request Nov 13, 2026
Brings in main through fe5febc (#2316 and the deterministic-order fixes).
One conflict, in grp_query.rs's module list: this branch's
it_union_fact_identity and main's it_unordered_output_order are both kept.
bplatz added a commit that referenced this pull request Nov 13, 2026
Brings #2296, #2309, #2313, #2315, #2316, #2317, #2367, #2368, #2369,
#2373, #2374, #2378 and #2379.

Ports onto next:

- #2374 (bound-object probe reads POST): main's POST walk and per-type
  flush replace next's OPST walk. The lane keys (o_type, o_key), so next's
  triple-term handles are one more covered type (object_probe_covers takes
  TripleTermDict) rather than a flush per type; a term's matches are read
  whole, as a ref's are. The wildcard cursor still keys refs only. Pooled
  graphs decline through dedicated_branch(Post); o_i is 64-bit. Next's
  pair join keys its subject through the shared LaneKey.
- #2373 (leaflet type constant under replay): replays_history and
  o_type_const_for beside next's may_hold_keys; the row-labelling lanes
  take main's const-unless-replaying form over next's always-read-column.
- #2368: the cyclic join decodes for eager callers with next's list index
  sentinel; both reasoning tests kept (cyclic operator and pair lane).
- #2317 (GRAPH streams): main's work queue and InnerStream with next's
  pooled-graph pruning before each enumerated graph.
- #2315: list predicates are an ordered set in next's multi-ledger view;
  the annotation edge probe stays deleted (no bundle lane on next).
- #2296 (rebase reads its new line): ported onto next's fenced resets,
  erasure checks and peer sync (follow_record keeps next's unchanged-head
  arm); a non-fast-forward rebase moves head and index in one fenced
  reset.
- Main's new tests: async genesis_ledger, graph_source_store for mapping
  writes, leaf_rows for leaflets-per-leaf, storage lock off for two file
  instances. New pattern/function matches cover TermComponents and the
  triple-term functions; AnnotationTarget arms dropped.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:iceberg Iceberg catalogs/credentials, R2RML, virtual datasets, materialize area:query Query execution, planning, fast paths, overlay, result formatting breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg graph sources: push bound subject sets and child join keys into the scan (VALUES subjects, parent tables of referencing object maps)

2 participants