Skip to content

feat(query): sub-selects over an Iceberg graph source - #2313

Merged
aaj3f merged 15 commits into
mainfrom
feat/r2rml-iceberg-subselect
Nov 13, 2026
Merged

aaj3f merged 15 commits into
mainfrom
feat/r2rml-iceberg-subselect

Conversation

@aaj3f

@aaj3f aaj3f commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A sub-select inside a graph-source scope is now evaluated. The R2RML rewrite lowers its body like any other nested scope, so the subquery operator builds R2RML scans of the same source under the enclosing graph context.

Before, every sub-select over an Iceberg source was refused. Without the refusal, its body would have run against the source's empty native index, where an ungrouped COUNT answers 0. Anything the body cannot lower still refuses the whole scope, for example a transitive path, or a variable predicate with a bound object.

Fixes #2241

Behavior

  • Grouped and ungrouped sub-selects joined back to the outer block now answer over an Iceberg source, as do DISTINCT, nested sub-selects, top-k, FROM <source>, and the graph handle with or without a GRAPH block. So do graph blocks mixed with a native ledger. Their rows match a native ledger holding the same data.
  • SPARQL sub-selects are evaluated independently and then joined, as on a native ledger. JSON-LD sub-selects keep JSON-LD's per-row correlation, as on a native ledger. For example, a LIMIT inside one is a top-k per outer row.
  • SQL graph sources: a sub-select the pushdown lane declines now falls back to the per-scan lane and is answered instead of refused. The declined shapes are HAVING over AVG, an OPTIONAL variable the outer block binds, a hidden inner variable the block reuses, OFFSET, and a nested sub-select. The lane still declines them, and the tests pin that.
  • A sub-select written outside every graph scope is evaluated when its body reads the source only through a GRAPH block of its own, or reads no index at all (only VALUES or BIND). An example of where that comes up is a sub-select beside your own GRAPH block on a graph source's handle.
  • Such a sub-select is still refused when its body reads the default view directly, with new advice: "A sub-select reads a graph source only from inside that source's graph block; move it there, or drop the explicit graph block so the whole query is scoped to the graph source."
  • DESCRIBE over a graph source is still refused. The reason is now its rdf:rest* path ("property path"), not "subquery".
  • An EXISTS inside an expression now reads the graph source: BIND(EXISTS {…}), FILTER(EXISTS {…} || …), NOT EXISTS inside a conjunction, and the same inside a sub-select's HAVING, binds and ORDER BY, on SPARQL and JSON-LD, inside the source's scope or the query's own GRAPH block. On main these read the empty native index and answered wrongly with no error (for example BIND(EXISTS…) false on every row where the native twin is true; FILTER(EXISTS… || false) 0 rows instead of 50). They now match the native twin. An EXISTS in the query's own HAVING, ORDER BY, or expressions evaluated after a trailing VALUES runs outside the source's scope and is refused with a 400 that says to move it into WHERE.
  • Edge-annotation patterns over a graph source answer no rows, as the native twin does (a mapping produces no annotations and a native ledger refuses user-written f:reifies* triples); pinned by tests. List patterns lower to ordinary scans.
  • ORDER BY ... LIMIT over a graph-source scan returned wrong rows in two cases: when the scan's input already binds a variable the scan produces, and when a filter was pushed into the scan. Those queries now return the right rows (first commit, below).

Design

  • The body is its own scope. The rewrite already recursed into OPTIONAL, UNION, MINUS and the other nested scopes. A sub-select is now one more of them.
  • Correlated sub-selects keep their written place. The planner correlates a JSON-LD sub-select only with the patterns written before it. The rewrite emitted its fused star scans after its loop, and restored written order only around OPTIONAL and MINUS. So ?c ex:name ?n followed by a sub-select came out with the sub-select first, and it ran once, uncorrelated: a LIMIT inside it kept the top rows overall instead of per ?c. A correlated sub-select now holds its place the same way, and a later star member that binds one of its SELECT variables is not fused above it. SPARQL sub-selects, evaluated independently, still move freely.
  • R2RML scans count as always-binding. The subquery operator seeds a correlation variable per outer row only when the body binds it in every row. It now counts an R2RML scan's variables the way it counts a triple's. The change is for correctness, not speed: a sliced JSON-LD sub-select is seeded with its key per outer row (top-k per group, matching a native ledger) instead of being re-evaluated unseeded. Every scan binds every variable it produces in every row it emits, with one exception: a type variable fused into a wildcard over a classless map, which is left out of the set. A scan row missing a join variable is never paired with a seed.
  • Scan-side top-k sees only rows that reach the output. This is the first commit, fix(r2rml): feed the scan-side top-k only rows that reach the output. It is the same change, with the same patch-id, that perf(r2rml): keyed scans for bound subjects and for the parents of referencing object maps #2316 (keyed scans, Iceberg graph sources: push bound subject sets and child join keys into the scan (VALUES subjects, parent tables of referencing object maps) #2239) carries as its own commit. Git reconciles the two whichever PR lands first.
    • ORDER BY ... LIMIT offers the scan a top-k directive: read files best-first, keep the k best emitted rows, and skip files that cannot beat them. That is sound only if every emitted row reaches the output.
    • Two things dropped rows after the heap had seen them. The first is a join with an input that binds a variable the scan produces (a VALUES block, an earlier pattern, a sub-select's seed). The second is a pushed scan filter the reader may apply only partly.
    • Example: VALUES ?id { 5 2500 } ?s ex:id ?id ORDER BY DESC(?id) LIMIT 2 answered only 2500.
    • set_topk now records no directive when the input binds a produced variable. That also keeps the scan eligible for the scan cache. The scan declines a recorded directive when any filter is pushed. A root scan, and an input sharing no variable with the scan, keep the pushdown.
  • The scan-side top-k observes only rows that emit a solution. This is a later commit, fix(r2rml): the scan-side top-k observes only rows that emit a solution, the same change perf(r2rml): keyed scans for bound subjects and for the parents of referencing object maps #2316 (keyed scans, Iceberg graph sources: push bound subject sets and child join keys into the scan (VALUES subjects, parent tables of referencing object maps) #2239) carries. It belongs to the same class as the first commit: the heap saw rows that never reach the output.
    • 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 lifted the k-th bound above rows that belong in the answer, and the files holding those rows were 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. 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.
    • The directive is declined where no set of columns decides whether a row emits: a star member that is a reference (its key may match no parent row), or one that maps to several object maps.

Caveats

  • A grouped sub-select uses the generic aggregate. The fused R2RML aggregate takes only a top-level grouping.
  • A sliced JSON-LD sub-select that correlates with the outer rows reads its table once per outer row (50 outer rows took 52 table reads on the test fixture). That follows from JSON-LD's semantics, a top-k per outer row; the SPARQL form answers a global top-k with one read. The docs say so (overview, "Sub-selects over a Graph Source"), and Iceberg graph sources: push keys for an object variable the scan's input binds (and a seeded sub-select's key) #2310 would prune each read by key. A sliced sub-select that seeds nothing from the outer row now runs once instead of once per row (102 reads and ~1.06 s fall to 4 reads and ~28 ms for 50 outer rows, same rows).

Tests

  • New it_iceberg_subselect, over a local two-table Iceberg fixture.
    • Every answer is checked against a native ledger holding the same rows, on the same surface. A fixed fact is added so the two cannot agree on "no rows".
    • Shapes:
      • grouped COUNT joined back
      • ungrouped COUNT
      • DISTINCT
      • top-k: SPARQL global, JSON-LD per group
      • nested
      • FROM <source>
      • the graph handle with and without a GRAPH block
      • graph blocks mixed with a native ledger
      • refusals
      • a sub-select beside the user's own GRAPH block, whose body reads through a GRAPH block of its own or only a VALUES; one that reads the default view still refuses
      • seeded joins on scan variables: a dangling FK object, a type variable, a wildcard predicate
      • ORDER BY ... LIMIT over a VALUES-constrained scan
      • table reads per shape
    • SPARQL and JSON-LD twins throughout.
    • Fixture facts the comparisons rely on: all 200 amounts are distinct, so a LIMIT cut has no ties, and both sides count 50 customers by class alone, so the twin copy cannot hide a scan that drops rows.
  • it_iceberg_local_fs: top-k regressions for a scan its input binds and for a joined scan, checked against the native twin. Its new iceberg_local_fs_top_k module, over a new silver.versions fixture, checks that a top-k counts only rows that yield a solution, against a ledger oracle, and that a top-k skipping such rows still prunes files.
  • Unit tests:
    • The rewrite lowers a sub-select body as its own scope.
    • A correlated sub-select keeps its written order; a SPARQL one need not.
    • R2RML scans' always-bound variables.
    • No scan-side top-k when the input binds a produced variable.
    • The outside-graph guard flags a sub-select only when its body reads the default view (six shapes, including a nested body and a path in the body).
  • it_sql_pushdown_lane:
    • Declined sub-selects are answered. Each is stamped MustNotFire, paired with a canary the lane takes, and its rows equal the native twin.
    • The sub-select cases now also run on the per-scan lane, in the golden tests and in the live-bridge differential.
    • CI's sql-bridge job runs that differential against SQLite, Postgres and MySQL.
  • Non-vacuity. With the rewrite arm reverted, every new sub-select test fails with the refusal. Each fix was then reverted on its own and the named tests failed; the restored tree passes again:
    • No top-k directive when the input binds a produced variable: the two operator unit tests; a_constrained_scan_orders_only_its_matching_rows and a_top_k_sub_select_keeps_its_slice (it_iceberg_subselect); both order_by_limit_* tests in it_iceberg_local_fs.
    • Declining the top-k when a filter is pushed: topk_reaches_the_scan_only_when_every_emitted_row_is_output. This case has a unit test only.
    • A correlated sub-select keeps its written place: a_correlated_sub_select_keeps_its_written_order and a_top_k_sub_select_keeps_its_slice.
    • R2RML scans counted as always-binding: r2rml_scans_produce_their_always_bound_vars and a_top_k_sub_select_keeps_its_slice.
    • The required-columns check: with the provider observing every row's sort value again (required → &[]), iceberg_local_fs_top_k::a_top_k_counts_only_rows_that_yield_a_solution fails, answering three rows where the ledger answers four.
    • The outside-graph guard flagging every sub-select again fails the guard unit test and a_sub_select_outside_the_graph_block_reads_through_its_own. Flagging none fails those and what_a_sub_select_cannot_lower_still_refuses.
  • Gates, on a clean Linux box at this branch merged with main, with the top-k commit (88eef8d):
    • fmt (workspace and testsuite-sparql).
    • cargo clippy --all --all-features --all-targets --locked -- -D warnings.
    • wasm32 clippy.
    • Crate tests: fluree-db-query 1,797, fluree-db-iceberg (aws) 506.
    • fluree-db-api lib (iceberg,native) 1,207.
    • Integration targets: it_iceberg_local_fs 33 (with the new top-k module), it_iceberg_subselect 12, grp_graphsource 282, it_graph_source_r2rml 67, it_iceberg_policy 15, it_fused_aggregate_routing 1, it_iceberg_warehouse_root 1, it_sql_graph_source 6, it_sql_pushdown_lane 21, it_r2rml_untyped_columns 2.
    • At c614c04, the commit before the top-k change, the full list also passed: CI's default-features check and server no-features check; fluree-db-api clippy with iceberg,native and sql,native; fluree-db-r2rml (all features) 173; grp_query_sparql 558; it_delta_local_fs 16; fluree-db-server lib 225; and the W3C suite (clippy and 85 tests).
    • 0 failed.
    • The live-bridge differential (live_bridge in it_sql_pushdown_lane and it_sql_graph_source) against SQLite, Postgres 16 and MySQL 8, as CI's sql-bridge job runs it: 5 passed, none skipped. That run was at 4b5eb59, before the review fixes; none of those fixes touches the SQL lane, and CI repeats it.

Breaking changes (for embedders)

  • A query with a sub-select inside a graph-source scope used to fail with "cannot be evaluated over a virtual dataset … subquery". It now returns rows. A caller that matched on that refusal no longer sees it.
  • On a SQL graph source, the sub-select shapes the pushdown lane declines are answered by the per-scan lane instead of refused.
  • The refusal for a sub-select outside every graph scope, and DESCRIBE's refusal reason, have new wording.
  • A query addressed to a graph source with an EXISTS in its own HAVING, ORDER BY, or in expressions evaluated after a trailing VALUES is now refused (400, err:db/InvalidQuery) where it used to answer wrongly. EXISTS inside WHERE expressions now answers correctly where it used to answer wrongly.
  • fluree_db_query::r2rml::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.

Follow-ups

aaj3f added 7 commits November 3, 2026 10:10
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.
…ugh the R2RML rewrite

The rewrite recursed into OPTIONAL, UNION, MINUS and the other nested scopes
but refused a sub-select, because the subquery operator would otherwise run
its body against the graph source's native index, which is empty: an
ungrouped COUNT answered 0. A sub-select's body is now rewritten as its own
scope like the others, so the subquery operator builds R2RML scans of the
same source under the enclosing graph context. Anything the body cannot lower
(a transitive path, an unconvertible triple) still refuses the whole scope.

Two consequences follow from where the body now runs.

A JSON-LD sub-select is correlated with the patterns written before it: the
planner takes its correlation inputs from those siblings only. The rewrite
emits its grouped star scans after its loop and restored written order only
around OPTIONAL and MINUS, so `?c ex:name ?n` followed by a sub-select came
out with the sub-select first, and it ran once, uncorrelated: a LIMIT inside
it kept the top rows overall instead of per ?c. A correlated sub-select now
holds its written place the same way, and a later star member binding one of
its SELECT variables is not fused above it. SPARQL sub-selects, evaluated
independently, move freely as before.

The subquery operator seeds a correlation variable per outer row only when
the body binds it in every row. It now counts an R2RML scan's variables as
it counts a triple's, so a sliced JSON-LD sub-select is seeded with its key
(top-k per group, as on a native ledger) instead of re-evaluated unseeded per
row. A scan binds every variable it produces in every row it emits, except a
type variable fused into a wildcard over a classless map, which is left out;
and a scan row missing a join variable never pairs with a seed.

A sub-select written outside every graph scope (beside the user's own GRAPH
block) is still refused, now with advice to move it inside the source's graph
block. DESCRIBE over a graph source stays refused; its test now asserts the
refusal text, since its rdf:rest* path, not a sub-select, is what refuses it.
On a SQL graph source, a sub-select the pushdown lane declines (HAVING over
AVG, an OPTIONAL variable the outer block binds, a hidden variable the block
reuses, OFFSET, a nested sub-select) falls back to the per-scan lane and is
answered instead of refused; the lane tests pin those shapes to the native
twin and to the lane's absence.

The new it_iceberg_subselect target checks each shape on SPARQL and JSON-LD,
through FROM <source>, the source's graph handle, and graph blocks mixed with
a native ledger, against a native twin of the same rows.
… reads the empty view

The guard on patterns outside every graph scope flagged each top-level
sub-select as unsupported without looking inside it. So a query whose own
graph block kept the source's wrap from applying refused a sub-select that
reads the source only through a graph block of its own, which the graph
operator lowers inside the sub-select, and one that reads no index at all
(only VALUES or BIND). The guard now descends into the body and flags the
sub-select only when the body reads the default view through a triple or
list pattern outside its graph scopes. Paths in the body are still flagged.
…mers on both sides

The top-k cases compare row sets under a LIMIT, which is sound only when no
two amounts tie at the cut; the test now asserts every amount is distinct.
The twin is copied through a star over every customer property, which would
silently leave out a customer missing one, so both sides now count their
customers by class alone against the fixture's 50.
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.
@aaj3f aaj3f added enhancement New feature or request area:iceberg Iceberg catalogs/credentials, R2RML, virtual datasets, materialize area:query Query execution, planning, fast paths, overlay, result formatting labels Nov 11, 2026
The top-k test module declared its own copy of support/span_capture.rs.
It now uses the one it_iceberg_local_fs declares, as the same module does
on the keyed-scans branch, so the two branches carry identical lines for
it and merge without loading the file as a module twice.

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

The lowering, the written-order handling for correlated sub-selects and the top-k soundness changes all look right. Approving, but please address the points below before merging.

Docs (please fix in this PR): the docs still say sub-selects over a graph source are refused, and nothing here updates them — docs/graph-sources/iceberg.md ("No transitive traversal" limitation), docs/graph-sources/r2rml.md (same item), docs/graph-sources/sql.md ("no other lane for a sub-select over a graph source"), the "Native ledgers only" callout in docs/query/graph-crawl.md, and the "Query Patterns a Graph Source Cannot Evaluate" section of docs/graph-sources/overview.md. The remaining refusal (a sub-select outside the graph block that reads the default view) and its advice belong there too.

Also:

  • The description has a breaking-changes section but the PR has no breaking-change label.
  • Trivial conflict with #2309 in fluree-db-api/Cargo.toml and scripts/local/write_local_iceberg_table.py (both add entries in the same spot); whichever lands second resolves it.

// rewrite. It binds its variables in every row it emits, like the
// triples it replaces, with the one exception its own method
// leaves out.
Pattern::R2rml(rp) => produced.extend(rp.always_bound_vars()),

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.

A sliced JSON-LD sub-select still reads the whole table once per outer row (the description's 52 reads for 50 rows). That shape used to be refused and now runs, so a LIMIT sub-select under a large outer block is thousands of Iceberg scans, and #2310 only adds file pruning per read. Please state this in the docs alongside the fix above, so it isn't discovered in production.

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 this needed saying in the docs, and 6af7c34 does that: the overview's new "Sub-selects over a Graph Source" section has a "Cost: a sliced JSON-LD sub-select reads per outer row" note (and iceberg.md item 6), pointing at #2310 for pushing the key into each read.

I did want to understand why it runs per row before just documenting it, though. For the shape in the description it's per-row by JSON-LD's own semantics -- a limit inside a JSON-LD sub-select that shares a variable with the outer rows is a top-k per outer row, exactly as on a native ledger, while the SPARQL form answers a global top-k with one read. So those 52 reads for 50 rows are the price of the semantics rather than waste, and the docs now say that both ways.

But looking at it turned up real waste right next to it: a sliced JSON-LD sub-select that seeds nothing (it shares a variable only through an OPTIONAL, or one its body never binds) was still re-run once per outer row, identically every time. 791f9d6 evaluates that once -- on the fixture, 50 outer rows went from 102 table reads and ~1.06 s to 4 reads and ~28 ms, same rows. it_iceberg_subselect::a_slice_that_seeds_nothing_is_read_once pins both the read counts and the documented per-row cost, and fails with the fix reverted.

}
}
// The leaves that read this view's index.
Pattern::Triple(_) | Pattern::ListView(_) => reads_view = true,

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: only triple and list patterns count as reading this view, so a sub-select whose body is edge-annotation patterns is no longer refused out here and runs against the empty native index. Inside a graph scope the rewrite passes list and annotation patterns through untouched, so the same body is silently empty there too. The top-level forms already behave that way, so this is consistent, but the old blanket sub-select refusal used to catch them. Read from the code, not reproduced.

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.

Good instinct to flag it even from a read -- I reproduced it, and it turned out to be half "fine by contract" and half "the read was slightly off", so here's where it landed:

  • Edge annotations do come back empty over a graph source, inside its scope or beside the user's own GRAPH block. I think that's actually the right answer though: a mapping has no annotation term map, and a native ledger refuses a user-written f:reifies* triple, so neither the source nor its native twin can ever hold an annotation. So rather than refuse it, c9552ff pins it against the twin on both surfaces (SPARQL {| |} / rdf:reifies, JSON-LD @annotation / @reifies), in a sub-select and at top level, with a control count so the 0 is provably the annotation's and not an empty fixture.
  • List patterns don't actually pass through untouched inside a graph scope: the list view is stripped back to plain triples before the rewrite (including in a sub-select's body), so they lower to ordinary scans. There's a new pin for the sub-select case -- without the strip it answers 5 rows from the ledger's own list instead of the source's 12. Outside a graph block a list pattern still counts as reading the view, so that sub-select still refuses.

The rewrite comments and the overview say this now instead of leaving it "undefined".

One more thing while I was in the class: sweeping for other nested scopes the rewrite doesn't reach turned up a pre-existing silent wrong answer -- an EXISTS inside an expression (BIND(EXISTS {..}), FILTER(EXISTS {..} || ..)) was never lowered and read the empty native index. Details in the top-level reply; it's fixed in this PR.

@aaj3f aaj3f added the breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section label Nov 12, 2026
A JSON-LD sub-select runs per outer row when it is sliced, seeded with
the outer row's values for its join keys: the variables it shares with
the outer rows and binds in every row itself. One with no join key (it
shares no variable, or binds the shared one only in an OPTIONAL, which
the merge reconciles instead) was still run per outer row, from the same
empty seed each time, and so answered the same rows every time. Over a
graph source each run reads the tables again: 50 outer rows took 102
table reads where one evaluation takes 3.

Per-row mode seeds only join keys, so with none the sub-select is now
evaluated once and joined, sliced or not, as it already was when
unsliced. The answers are unchanged.
…as a twin would

A sub-select is no longer refused wholesale over a graph source, so the
patterns the R2RML rewrite leaves alone in its body now run. Two kinds
are pinned here against the contract that a graph source answers as a
native ledger holding the mapping's triples would.

Edge annotations (`{| … |}`, `rdf:reifies`, `@annotation`, `@reifies`)
match nothing over a source, inside its scope or beside the user's own
graph block. That is the twin's answer: a mapping has no term map for an
annotation, and a native ledger refuses a user-written `f:reifies*`
triple, so neither holds one. An ungrouped COUNT shows the empty match
as a 0, and the same count without the annotation counts every order.

The list view, which wraps a SPARQL pattern a stored list could match on
a ledger holding lists, is removed from a sub-select's body inside a
graph-source scope as from the scope's own patterns. A wildcard in that
body therefore scans the source rather than answering from the ledger's
lists.
…ey cost

The graph-source docs still listed sub-selects among the patterns a
graph source refuses. The Iceberg, R2RML and SQL pages, the graph-crawl
callout and the overview now say what runs instead:

- a sub-select inside the source's scope lowers to table scans;
- SPARQL evaluates one once, while JSON-LD correlates one with the
  patterns before it;
- a SQL source's per-scan lane answers what the pushdown lane declines.

The overview's new section states the cost a reader would otherwise find
in production. A JSON-LD sub-select with a limit or offset, correlated
with the outer rows, runs once per outer row and reads its tables in full
each time, until the outer key is pushed into the scan (#2310). The
section gives the ways around it.

It also covers the refusal that remains: a sub-select outside every
GRAPH block whose body reads the default view, with the error's advice
and an example of both forms. And it says why annotation patterns match
nothing over a source: no mapping produces an annotation. The rewrite's
comments now say the same, in place of calling RDF-star over a source
undefined.
The R2RML rewrite lowered EXISTS patterns and, with this PR, sub-select
bodies, but passed FILTER, BIND and UNWIND through untouched. An EXISTS
embedded in one of their expressions was never lowered, so over a graph
source it read the source's empty native index and answered as a
success: every EXISTS false, every NOT EXISTS true. On main,
`BIND(EXISTS { ?o ex:customer ?c } AS ?b)` answers false for customers
that have orders, `FILTER(EXISTS {…} || …)` drops every row, and
`FILTER(NOT EXISTS {…} && …)` keeps rows it should drop, on both SPARQL
and JSON-LD, with or without a graph block of the user's own. A
sub-select's HAVING or ORDER BY had the same gap. Main refused those
along with every sub-select, and lowering the body alone made them
answer wrongly.

The rewrite now lowers every pattern list embedded in a FILTER, BIND or
UNWIND expression, and in a sub-select's HAVING, per-group binds and
ORDER BY, as its own scope. It carries their unconverted and unsupported
patterns like any nested scope, so a path in one still refuses. An
expression that embeds nothing is passed through as before.

The guard for patterns outside every graph scope looks inside the same
expressions. An embedded EXISTS that reads the default view counts as
reading it, so a sub-select carrying one refuses, and paths in one are
flagged.

A query's own HAVING and ORDER BY run after its WHERE, outside the graph
scope the WHERE is wrapped in. So do the binds a trailing VALUES moves
out of the WHERE: GROUP BY expressions, aggregate inputs and SELECT
expressions. An EXISTS in any of them always read the empty index. On
main a HAVING EXISTS kept no groups, an ORDER BY EXISTS ordered by a
constant, and SUM(IF(EXISTS …)) before a trailing VALUES summed zeros.
Such a query is now refused, wrapped or not, with the remedy: move the
condition into the WHERE as a FILTER, or BIND it there.
…ed after it

The overview gains a section on EXISTS over a graph source. An EXISTS in
the WHERE clause, as a pattern, inside an expression or in a
sub-select's HAVING or ORDER BY, reads the source. One in the query's
own HAVING or ORDER BY, or in an expression evaluated after a trailing
VALUES, runs outside the source's scope and is refused. The section
gives the remedy: move the condition into the WHERE as a FILTER or BIND.
The Iceberg and R2RML pages point to it.
aaj3f added a commit that referenced this pull request Nov 13, 2026
The sub-select branch (#2313) lands before this branch, so this branch
carries it.

Resolutions:
- graph_source/r2rml.rs: the scan-side top-k feeds its heap through
  batch_sort_values_where (sub-select branch: only rows that emit a
  solution) and reads its parallel tail through read_files_in_order (this
  branch); imports unioned.
- it_iceberg_local_fs.rs: both sides' tests kept, and the span-capture and
  top-k modules declared once. Both sides added a WINDOW_IDS_R2RML over
  silver.people_window; the sub-select branch's (id and name, integer ids)
  is WINDOW_PEOPLE_R2RML here, as in the integrated branch.
- Cargo.toml, write_local_iceberg_table.py: both sides' test binaries and
  tables kept.
aaj3f added a commit that referenced this pull request Nov 13, 2026
aaj3f added a commit that referenced this pull request Nov 13, 2026
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.
@aaj3f

aaj3f commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bplatz -- the docs catch was fair, and chasing it properly ended up finding something more important (below).

…-iceberg-subselect

# Conflicts:
#	fluree-db-api/Cargo.toml
#	scripts/local/write_local_iceberg_table.py
@aaj3f
aaj3f merged commit 32c8cad into main Nov 13, 2026
19 checks passed
@aaj3f
aaj3f deleted the feat/r2rml-iceberg-subselect branch November 13, 2026 15:24
aaj3f added a commit that referenced this pull request Nov 13, 2026
…ed-plan branch

# Conflicts:
#	scripts/local/write_local_iceberg_table.py
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.
bplatz added a commit that referenced this pull request Nov 13, 2026
Main's #2313 decided that an annotation pattern over a graph source matches
nothing rather than being refused: a mapping produces no annotation, and a
ledger loaded with the mapping's triples holds none, so the empty answer is
the native twin's. On next an annotation lowers to the rdf:reifies link and a
TermComponents pattern, and the rewriter refused TermComponents, so
it_iceberg_subselect's annotation_patterns_match_nothing_over_a_graph_source
failed after the main merge. TermComponents reads the term dictionary, which
a graph source has none of; it is now left in place like EdgeAnnotation, and
does not count as reading the view. The link is a triple, rewritten like any
other, and no map produces it.
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 enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sub-selects over an Iceberg graph source are refused; the SQL lane evaluates some of them

2 participants