Repository navigation
perf(r2rml): Iceberg scans plan from the kept file list, and a paged unordered query returns the same rows every time - #2315
Conversation
…name A scan task's schema names the columns of the batches it decodes, and the R2RML operator finds columns by name, as the mapping names them now. The scan planners attached the schema the snapshot was written under, so a read of a snapshot older than a rename (a time-pinned query, or a current snapshot followed by a rename with no commit since) named the column by its old name, and the mapping's column matched nothing: the query returned no rows, without an error. Only a warm unfiltered scan answered, because the scan-files cache path rebuilt its tasks with the snapshot's schema under current names. The materialize reads resolved the mapping's columns through the old names too, so a window ending before a rename (a pinned or capped window) projected without the renamed column, and a twin built from it lacked those values. Before this change, with the new fixture silver.renamed (three rows, then `name` renamed `full_name`, then two rows) and a mapping that reads `full_name`, a read pinned to the first snapshot returned, on SPARQL and JSON-LD alike: unfiltered, first scan (cache miss) no rows unfiltered, repeated (cache hit) alice, bob, carol filtered, first scan or repeated no rows and both materialize reads to that snapshot returned batches with no `full_name` column. All of them now answer. TableMetadata::read_schema_for_snapshot (moved from fluree-db-api's read_schema, rule unchanged) is the snapshot's field ids and types under current names; a field dropped since keeps its old name unless a current field has taken it. All three planner entries (both scan planners and plan_incremental) and both materialize reads use it. Pruning is by field id and type, so it is unaffected. scripts/local/write_local_iceberg_table.py writes silver.renamed in a block of its own.
…ts are read concurrently Every walk of a snapshot's manifests (both scan planners, the incremental planner, and the two manifest-only stats reads) now goes through manifest::reader::read_manifests. It reads up to ScanConfig::manifest_read_concurrency manifests at once (default 16) and yields them in manifest-list order, so plans, counters and the first error reported are those of a sequential walk. One await per manifest made planning cost one object-store round trip per commit of the table. A plan is now built in three shared steps: read the snapshot's live files, sort them into plan order (commit, then path), select the files the filter may match. Selection needs only the list, so SendScanPlanner gains plan_from_files, which plans any filter from a kept list (KeptFiles: the files, their record total and the delete flag) without reading a manifest, with the same file test, residual filter, iceberg.scan_plan span and merge-on-read refusal as a plan read from the manifests; and plan_scan_for_snapshot_retaining_files, which also returns the whole sorted list from its one manifest read. Selection borrows from a kept list and clones only what it selects, building each task in place, and an unfiltered plan takes the kept record total instead of re-summing it: planning 2,400 kept files unfiltered costs what copying the list does. DataFile::approx_size_bytes estimates an entry's memory for weighing caches of file lists. The planner's module doc no longer claims partition-summary pruning, which nothing implements.
FileScanTask::residual_filter is now an Option<Arc<Expression>>. A plan wraps its filter once and every selected task holds the same Arc, where each task held a deep copy of the expression (its column names, literals and IN lists), so a plan's cost grew with files times filter size. The Parquet reader's per-row-group workers share it the same way instead of cloning it per worker. Planning 2,400 kept files under a 1,024-member IN that selects all of them drops from 31-33 ms to 25-27 ms; what remains is the per-file bounds test. A test asserts that every task of a plan holds the same residual. FileScanTask::for_whole_file and for_whole_file_with_schema take the residual as an Option<Arc<Expression>>; a caller passing None is unchanged.
…e list A scan with a pushed filter bypassed the scan-files cache and re-read the manifest list and every manifest, one at a time, on every query; only unfiltered scans reused the cached list. A snapshot's live file list never changes, so the cache now keeps the whole unfiltered list (in memory and in the disk catalog cache) whatever the first scan's filter, and every scan of the snapshot, filtered or not, plans from it through SendScanPlanner::plan_from_files. On a 2,400-file table a repeated filtered query spends about 0.3 ms planning instead of about 100 ms. The cache entry keeps the list's record total, so a warm unfiltered scan plans at the cost of the task rebuild it replaces. The miss writes the list to the disk catalog cache on a blocking thread, off the query's path, serialized from the kept list rather than a copy. A filtered first scan used to write nothing there, and 2,400 files are 2 MB of JSON (5 to 15 ms); written inline, it made a cold filtered query slower than before even though its planning was faster. iceberg.scan_plan now fires on every Iceberg scan, cache hits included, so a warm unfiltered scan reports its file count where it reported nothing; fluree-bench-virtual's note on the span says so. The merge-on-read refusal of a kept list moves into the planner, replacing guard_cached_scan_files. The in-memory scan-files cache is weighed by the lists' approximate size in KiB instead of by entry count, against FLUREE_ICEBERG_SCAN_FILES_CACHE_MB (default 512). 128 entries could be gigabytes for large tables and a few megabytes for small ones. moka accepts an entry heavier than the whole budget and silently drops it at its next maintenance pass, so such a list is refused before insert and kept only in the disk catalog cache. The disk format is unchanged: its counters are written as the unfiltered list's. The Iceberg docs describe the kept list and no longer claim partition pruning.
… file DiskCatalogCache::write wrote every entry through `<entry>.tmp` and renamed it into place. Two writers of one key (two queries missing the same snapshot at once, in one process or two) shared that temp file, so one could truncate or overwrite the file the other had just renamed into place: a reader could see it partly written, and a writer whose bytes landed over a longer one's left a tail that does not parse. Such a read fails closed (the entry is deleted and the scan reads the manifests), but the entry is lost, and the scan-files write now runs on a blocking thread while the query goes on, which widens the window. The temp name is now unique per write (process id plus a process-wide counter) and stays in the entry's directory, so each rename atomically installs one writer's complete bytes. prune_dir counts and removes the new temp names like any other file. A test races four writers of differently sized lists on one key, with a reader that must only ever see a miss before the first write and one writer's complete list after it.
An Iceberg graph-source scan read its data files with up to N reads in flight and emitted each file's rows as its read finished. Completion order varies with I/O timing, so a query with no ORDER BY answered its rows in a different order from one execution to the next, and a client paging it with LIMIT/OFFSET could skip or repeat rows across pages. A scan now owes the query a ScanOrder. Deterministic is the default; the query root (build_operator_tree) grants Any only when no LIMIT or OFFSET appears anywhere in the query, sub-SELECTs and EXISTS expressions included, since only a slice can observe an unordered answer's order. The decision travels in PlanningContext to the R2RML scan and fused-aggregate operators, and to the provider through R2rmlTableProvider:: scan_table_ordered, an additive method whose default is scan_table. Any path that plans without the root, and any provider that does not override the new method, stays deterministic. Parent lookups always are. The Iceberg provider reads every row-emitting scan through read_files_in_order with an explicit EmitOrder: - SmallestFirst for a deterministic query scan: the manifest's file_size_in_bytes, ties in plan order (commit, then path), a total order for one snapshot. The head of the read window is the cheapest file, so a LIMIT is answered from small files and a large file does not hold back the files behind it. Commit order did: on a table whose files differ 25x in size, LIMIT 25 took 5x longer. - Completion for a query with no slice, as before. - AsListed for the materialize/incremental stream (commit order, which a resumable consumer relies on) and the top-k tail (best-first). The provisional-mapping scan does the same. The graph-source crawl applies its subject OFFSET after the query, so a crawl with an OFFSET and no LIMIT reaches the engine with no slice. It sets QueryExecutionOptions::deterministic_scans, carried to ExecutionContext as trust_fk_refs is, and its scans stay deterministic. A class mapped by several TriplesMaps is now scanned in mapping-document order: CompiledR2rmlMapping::triples_maps is an IndexMap in document order instead of a HashMap, whose iteration order differed per instance, so the maps' rows came in a different order per process. The dedupe of alike maps keeps the first in document order. Tests: a debug-build hook (FLUREE_DEBUG_ICEBERG_SLOW_READ) delays one data file's read so completion order differs from the fixed order on purpose. On a five-file table the pages of LIMIT/OFFSET partition the answer twice over on SPARQL and JSON-LD, an unsliced answer streams in completion order, a crawl's OFFSET lands in the fixed order, and the materialize read keeps commit order. Eight IR shapes check the order each scan is asked for, and the fused aggregate's own scan follows the same rule. Unit tests cover the listed and smallest-first orders, a read error in its file's place, and the document order of mapped TriplesMaps. The graph-source docs describe the row order a query gets, and that a Delta source is paged by an ORDER BY. Out of scope: a table append or compaction between two page requests changes the snapshot, and with it the order; holding pages across that needs a snapshot pinned across requests. Delta graph sources keep their unordered scan: an ordered Delta dispatcher was measured and was not speed-neutral.
read_files_in_order spawned a file's read as the stream of files was pulled; the scan it replaced spawned it on the read future's first poll. On a decode-bound unsliced COUNT over 24 equal files (16 reads in flight), the completion lane, meant to be today's scan unchanged, peaked at 498 MiB against 315 MiB under glibc malloc, with equal wall time and instructions. Every lane now builds the read when its file is admitted (keeping the read's span under the consumer's) and spawns it on first poll, the shape the scan had before: the same COUNT peaks at 308 MiB against 307 MiB. The fixed-order lanes still start every read their window admits, since both combinators poll all admitted futures. A mutex makes the pending read Sync, as the stream must be. The debug-build slow-read hook is gone, with its process-environment mutation: the paging test no longer asserts anything about the unsliced answer's order (it checks that every row comes once), and the ordered lane's order is checked against the order derived from the table's own files. That the unsliced lane streams in completion order is pinned by the routing test and by a reader unit test with controlled futures. Both providers map a ScanOrder to an EmitOrder through EmitOrder::for_query.
…d sites The fused aggregate is built at two sites: as the SQL-lane detector's fallback (a plain COUNT reaches it there) and directly, when that detector declines; a SUM over a top-level BIND is declined (the block must be the whole WHERE) and reaches the second site. The fused-order test now runs both shapes, unsliced and under a LIMIT, so dropping the scan order at either site fails it. A provisional-mapping query asks its provider for the same orders a persisted one does.
The fused aggregate emits its groups in its fold map's iteration order, and a GROUP BY with no ORDER BY paged by LIMIT/OFFSET reads that order. The default (vector-fold) path keys a hashbrown table with an Fx hash, whose order is fixed for a given input; the path behind FLUREE_FUSED_VECTOR_FOLD=0 used std's HashMap, whose hasher is seeded per instance, so the same rows came out in a different group order on every execution. It now uses an FxHashMap. No other hashed map on the graph-source scan path is iterated into output (the rest are lookups). Tests: fresh fused operators fold the same rows into 50 groups and emit them in one order on both paths (the std map fails it); over a local table, ten GROUP BY pages of ten partition one page of 1,000, on SPARQL and JSON-LD, and two fresh instances agree.
A snapshot's file list heavier than the whole in-memory budget (FLUREE_ICEBERG_SCAN_FILES_CACHE_MB, default 512) was not kept in memory, so every scan of such a table (one over roughly 150,000 data files) read its list again from the disk catalog cache, or from every manifest with that cache off. It now goes to one oversize slot beside the budgeted entries, keyed and scoped as they are: the latest such list is served warm, and a second replaces the first, so memory beyond the budget stays bounded to one list. The first list to land there is logged at info. A budget of 0 still keeps no list.
plan_from_files recorded its counters on the iceberg.scan_plan span but did not emit the "Scan planning complete" line, so the line appeared on a cache miss and not on a hit. Every planning arm now ends in one finish_plan that does both. A test captures the log of a fresh plan, a miss and a hit, and finds the same line once for each.
…map dependency fluree-db-r2rml depends on indexmap since its TriplesMaps keep document order; testsuite-sparql is its own workspace, so its lockfile records the new edge separately.
…le with uneven files A query with a LIMIT or OFFSET reads a graph source's data files in a fixed order so its pages hold together. Over files of very different sizes, rows are then taken in file order rather than as each read finishes; a grouped query, which reads the whole table before its LIMIT applies, measured about 13% slower than completion order. Say so beside the row-order rules.
…gh the test-support floor The test that checks every planning arm logs its plan installed a thread-local subscriber with tracing's set_default. A callsite first registered on another test's thread can then be cached as never interesting, and the capture intermittently sees nothing; the workspace harness check refuses the direct call. Use fluree_test_support's scoped_default, as the other log-capture tests do.
bplatz
left a comment
There was a problem hiding this comment.
Planning from the kept list, the size-weighed cache, the rename fix and the root-level scan-order decision all look right, and the measurements are the kind I want to see. Approving, but please look at the inline comments and the two points below before merging.
The generic GROUP BY still emits groups in a random order. GroupByOperator (fluree-db-query/src/groupby.rs) keeps its groups in a std HashMap and transform_groups iterates it straight into output. This PR fixed exactly that in the fused aggregate and says no other hashed map on the graph-source path is iterated into output, but the planner picks this operator on its traditional path (grouped-list output and aggregates the streaming operator declines), so a paged GROUP BY of those shapes still varies per execution. Same fix: an Fx or insertion-ordered map. Not in the diff, so no inline anchor.
Landing order. This conflicts with two PRs that are already approved: #2309 (ephemeral.rs, send_parquet.rs, scan/mod.rs, scan/planner.rs) and #2313 (graph_source/r2rml.rs, it_iceberg_local_fs.rs). Please land #2309 and #2313 first and rebase this one (and the #2316 → #2317 stack on top of it) onto them. The order matters because the #2309 conflict is semantic, not just textual: #2309 attaches its exact row filter after planning, and this PR rewrites those planning arms to go through plan_from_files. A filtered map that plans from the kept list without the exact filter reads rows its mapping excludes, silently. With #2309 on main first, its tests run against this rebase and catch a dropped filter; in the other order the resolution lands in #2309 with nothing here to check it.
| /// or on a sub-SELECT at any depth, including inside an `EXISTS` in a filter, | ||
| /// bind or modifier expression. | ||
| pub(crate) fn query_has_slice(query: &Query) -> bool { | ||
| query.limit.is_some() |
There was a problem hiding this comment.
selectOne observes scan order too and isn't counted here. It takes the first row at format time rather than setting limit, so a selectOne with no ordering gets ScanOrder::Any and can return a different row from run to run. Same class as the crawl's after-the-query slice; query.output.is_select_one() belongs in this check.
There was a problem hiding this comment.
Good catch -- fixed in 8c4885b: the root check is now query_takes_prefix (a slice anywhere, or selectOne).
Sweeping for other "take a prefix after the query runs" spots turned up a real one I hadn't considered: an AgentJson response under a byte budget returns the rows that fit plus a resume query with OFFSET, so the first page ran in any order while the resume page ran in the fixed one. On the five-file paging fixture the budgeted first page started at person 1 while the fixed order starts at 2401 -- so pages genuinely didn't partition. The query builders now turn on deterministic scans whenever the format pages its rows (regardless of whether .format() or .execution_options() is called first). There's a selectOne case in the routing test, selectOne + a budgeted AgentJson page in the paging test, and a builder unit test; each fails with its fix reverted. I left the CLI's "first N of M rows" preview alone since it doesn't page.
| .oversize_scan_files | ||
| .lock() | ||
| .unwrap_or_else(std::sync::PoisonError::into_inner) = | ||
| Some((scope.qualify(metadata_location).into_owned(), scan_files)); |
There was a problem hiding this comment.
This slot has no cap. The list carries per-column stats for every column of every file, so a wide table with many files is gigabytes held here, and a filtered scan now keeps the whole list where it used to keep only the files it selected and cache nothing. Please cap it (above some multiple of the budget, plan without retaining). Dropping stats for columns no mapping reads would shrink every list and is fine as a follow-up.
There was a problem hiding this comment.
Agreed it needed a cap -- 1d10770: the oversize slot takes a list of at most two budgets; a heavier one isn't kept and leaves the slot's current list in place, so the cache holds at most three budgets (1.5 GiB at the default). the_oversize_slot_keeps_no_list_heavier_than_its_cap pins it.
On dropping stats for columns no mapping reads -- I looked at doing it here, but I don't think it's safe with the cache keyed the way it is. The key is the table snapshot (under a storage identity), not the mapping, so every graph source over that table shares the one list, and the disk cache shares it across processes. Another mapping's columns, a row filter's WHERE columns, or a top-k sort column can all need stats the first mapping doesn't map. It wouldn't give wrong answers (missing stats just keep files), but it would silently take pruning away from the others. Doing it properly needs a per-column-set key or a registry of the columns in use, which felt like a separate design rather than something to slip in here -- happy to talk it through if you see a simpler cut.
| Err(e) => futures::stream::iter(vec![Err(e)]), | ||
| }); | ||
| Box::pin(stream) | ||
| read_files_in_order(tasks, EmitOrder::AsListed, concurrency, move |task| { |
There was a problem hiding this comment.
This read was buffer_unordered on main, so the materialize stream changes from completion order to listed order here (head-of-line blocking), as does the top-k tail further down. The description says materialize "keeps" commit order, and the measurements cover query shapes only. Please correct the description and add a materialize throughput number, or say why it can't move.
There was a problem hiding this comment.
You're right on both counts -- main read both of these with buffer_unordered, and the description saying materialize "keeps" commit order was wrong (it introduces it). The description is corrected.
I did keep both in listed order though, because it turns out both actually depend on it:
- Materialize: without an
order_bycolumn the last row read for a subject wins (MaterializeAccum::record), so a tombstone committed after a live row has to be read after it -- with completion order it can be applied first and the deleted subject survives.order_byties and nulls fall back to read position too. So main's unordered read was a latent bug here rather than something to restore. 89d13a6 pins it with a multi-file table where the live row sits in a large early file and the tombstone in a small later one -- it fails on main in 3 of 3 runs (the deleted subject comes back on the first materialize) and passes here. - Top-k tail: it only runs under
ORDER BY … LIMIT, where tied rows keep read order, so completion order could put different tied rows on a page from run to run.
The throughput side, measured on a quiet box (24 files, 25x size spread, 3.36M rows): draining the materialize read is 188 ms vs 171 ms on main with the same instruction count, and the first batch arrives at 94 ms instead of 16 ms. A full materialize of a 672k-row table of that shape is 44.9 s vs 45.4 s -- the read is under 1% of the pass, so it doesn't register.
The row filter (#2309) lands before this branch, so this branch carries it and its tests check the planning arms rewritten here. Resolutions: - scan/planner.rs, scan/mod.rs: a task holds the shared residual filter (this branch) and the exact row filter (row-filter branch); KeptFiles and the exact-filter types are both exported. - io/send_parquet.rs: every decode passes the shared residual by reference and the exact filter beside it. - graph_source/ephemeral.rs: the provisional scan loads a filtered map's FROM table and narrows its plan to the row filter (row-filter branch), then reads its files in the order the query owes (this branch); the same resolution as the integrated branch. - graph_source/r2rml.rs (merged clean): the row filter is applied after the planning arms, to the tasks of whichever arm planned, so a scan-files cache hit (memory or disk) is narrowed as a manifest walk is. - write_local_iceberg_table.py: both sides' tables kept.
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.
… filter The row filter is applied to the tasks of whichever planning arm ran, so a scan-files cache hit is narrowed as a manifest walk is. Pin it: keep both tables' file lists through the unfiltered maps over them, delete the data manifests so only the kept list can plan, and check every case of the filtered mapping against the native oracle on SPARQL and JSON-LD, from the in-memory list and, in a second instance, from the disk catalog cache.
…tion A query with no ORDER BY may answer in any order, but a client pages it with LIMIT/OFFSET, so it must answer in the same order every time it runs over the same data. Four operators and one formatter iterated a std HashMap/HashSet into their output, and a std map is seeded at random per instance, so each execution answered in a different order: - GroupByOperator (the generic GROUP BY: grouped-list output, GROUP_CONCAT and the other aggregates the streaming operator declines) held its groups in a std map. It is now Fx-hashed, and moves its groups out to emit them instead of cloning every group and row. - A property path with both ends unbound emitted its closure in the order of a std node set (and its composite domain's). Both are Fx-hashed. - The RDF list view read the list-holding predicates of a variable predicate in std set order, which ordered the lists it answered and the labels of their cells. The set is a BTreeSet. - The annotation probe's hash lane answered a driving row with an unbound subject from a std map of swept edges. It is Fx-hashed. - The JSON-LD graph crawl formatted a subject's predicates (and reverse predicates) in std map order. Order alone was hidden by the sorted output object, but which path reaches a shared node first decides what its cached rendering holds (the cycle cut depends on the path), so the same subject rendered differently from run to run. Both are iterated in predicate order. An Fx-hashed map has no per-instance seed: its order is fixed by the keys inserted and the order they arrive in, which the input fixes. It also hashes faster than the std map.
…ans in one order A graph-source scan may emit rows as its file reads finish only when nothing takes a prefix of the answer. The query root counted LIMIT and OFFSET at any depth, and the browse crawl asks for fixed order through QueryExecutionOptions::deterministic_scans because it pages subjects after the query. Two other prefixes were missed: - A JSON-LD selectOne keeps the first row when the result is formatted, without setting a limit, so it got ScanOrder::Any and could answer a different row from run to run. The root check is now query_takes_prefix: a slice anywhere, or selectOne. - An AgentJson response under a byte budget returns the rows that fit and hasMore, with a resume query that carries OFFSET. The first page came from a query with no slice (any order) and the next from one with an OFFSET (fixed order), so the pages did not partition the answer. The query builders now read their execution options through QueryCore::execution, which turns on deterministic scans when the format pages its rows (FormatterConfig::pages_rows). The field is private, so every execute path goes through it, and the order of .format() and .execution_options() on the builder no longer matters. Format-time slices that are not pages (the CLI's table preview of the first N rows, which re-runs nothing) are left alone.
…two budgets A kept file list carries statistics for every column of every data file, so a wide table with many files weighs gigabytes, and the oversize slot, which keeps the latest list heavier than the whole budget, had no upper bound. A filtered scan now keeps the whole list too, so it could pin one. The slot now takes a list of at most OVERSIZE_SLOT_BUDGETS (2) budgets. A heavier list is not kept in memory (the scan that read it plans from it and drops it; later scans plan from the disk catalog cache or the manifests), and it leaves the slot's list in place. The cache's memory is bounded by three budgets. put_scan_files says where a list went (ScanFilesKept).
…slice is tested `read_in_own_task` took a closure that built the read, to keep the future it returned `Sync`. That shape doesn't carry over to #2315's `read_files_in_order`, which builds each read ahead and holds it in a `Mutex` until it spawns it: wrapping a built read in a closure puts a value that isn't `Sync` into the future, and the stream's `Sync` bound fails. `spawn_file_read` takes the built read instead, spawns it at once, and returns a future that holds only the task's handle, so it is `Sync` whatever the read is and fits both shapes. The handle is tokio-util's `AbortOnDropHandle` rather than a second hand-rolled `AbortOnDrop`; tokio-util is already in the lockfile and becomes a direct dependency of `fluree-db-api` behind its `iceberg` feature. Tests: `the_read_future_is_sync_for_a_read_that_is_not` asserts `Send + Sync` for a read that isn't `Sync`, both called directly and from a future that holds the read in a `Mutex` until it spawns it. `a_failing_slice_stops_the_slices_after_it` runs a row-group-parallel decode in two slices, fails every read of the first and holds the second's: once the decode returns, the second slice fetches nothing more (42 more fetches without the storage guard). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…bject With a delete convention and no ordering column, a materialize pass keeps the last row it reads for each subject, so its read must follow commit order. The materialize read on main emitted files as their reads finished. The new fixture silver.tombstones commits 200,000 live revisions of subjects 1..=10 in one large file, then subject 7's tombstone in a one-row file. Five fresh materializations must each retract subject 7 and keep the other nine. On origin/main the test fails in every run tried (3 of 3 processes on a c7i.8xlarge, each at its first materialization): the small file is read first and the large file's live rows resurrect subject 7. On this branch it passes, and it fails 3 of 3 here with the materialize read switched back to completion order.
…ow provides The row-filter branch checks a filter against the schema an unpinned read reads, through a read_schema helper in r2rml.rs. This branch moved that helper into fluree-db-iceberg as TableMetadata::read_schema_for_snapshot, with the same rule, so the merge left a call to a function that no longer exists. Call the moved method.
…as the rest of its binary The local-roots guard reads FLUREE_ICEBERG_LOCAL_ROOTS once per process, so the first test to build storage fixes the roots for every test in the binary. This test set them to the fixtures directory alone, so when it ran first, the empty-table test, which stages under the scratch directory, was refused. Set them through set_local_roots, as every other test here does.
|
Thanks @bplatz -- really useful pass, and the GROUP BY catch in particular, since the PR made a claim that turned out not to hold. GROUP BY / the "no other hashed map" claim. You're right, and the claim was wrong in more places than Landing order. Agreed -- and the semantic part is exactly why I didn't want it resolved in a later conflict. Both #2309 and #2313 are merged into this branch (dd6217c, b835712, at their reviewed-and-fixed heads), so #2309's own tests run here. The exact row filter is applied after all three planning arms (memory hit, disk hit, manifest walk), to whatever plan they produce, so a kept-list hit can't skip it. 7b89d70 pins that: it warms the file lists through unfiltered maps, deletes the manifests so only the kept list can plan, then checks every filtered case against a native oracle on both surfaces, from the memory cache and from the disk catalog cache. With narrowing skipped on the kept-list arms, that test fails and so do four existing ones. #2316 → #2317 have the same merges carried up. |
…ed-plan branch # Conflicts: # scripts/local/write_local_iceberg_table.py
…s branch #2315 moved every scan's file reads into `read_files_in_order`, the ephemeral provider's included, so the two conflicted files (`r2rml.rs`, `ephemeral.rs`) take main's side, and `read_files_in_order` now spawns each read through `spawn_file_read(read).await` inside its `Mutex` block instead of `tokio::spawn(read).await`. One spot aborts every scan's reads. `a_dropped_scan_stream_aborts_the_reads_in_flight` moves to `emit_order_tests` and drives `read_files_in_order` itself, under all three emit orders (`buffered` and `buffer_unordered`); its read helpers move to `file_read::test_reads` so both modules share them. The doc notes that pointed ahead to #2315 now describe the code as it is. #2315 also gave `decode_large_file` an `iceberg_schema` argument; the two large-file tests pass `None` for it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ndow branch No textual conflicts. #2315 gave `decode_batches_arrow` a `row_group_subset` argument, so the ranged-vs-in-memory decode test in `chunk_reader.rs` passes `None` (the whole file) for it in both calls. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.
…ists list_view.rs takes main's version: its read-order change (predicates in a BTreeSet) landed in #2315. This branch keeps only the test-only of_predicates constructor there.
Partially addresses #2240: a filtered query plans from the cached file list, pruned in memory. Still open: skipping manifests by partition summary when the file list is not cached (follow-up below).
Follow-up: #2318 (manifest skipping by partition summary, partition values by field id)
Follow-up: #2319 (Delta graph sources: a paged unordered query is nondeterministic)
What changes
A filtered scan plans from the snapshot's kept file list. A snapshot's live data files never change. They are now read from the manifests once and kept in the scan-files cache, in memory and in the disk catalog cache, whatever the first scan's filter was. Every scan of that snapshot, filtered or not, then selects its files from that list in memory, with the same
can_contain_filetest the manifest walk uses. Until now, a scan with a pushed filter skipped the cache and re-read the manifest list and every manifest, one after another, on every query.Planning is now three shared steps in
fluree-db-iceberg/src/scan/planner.rs: read the snapshot's live files, sort them into plan order (commit, then path), and select.SendScanPlanner::plan_from_filesruns the select step on a kept list (KeptFiles: the files, their record total and the delete flag). It produces exactly what a plan read from the manifests produces:iceberg.scan_planspan, counters and "Scan planning complete" log line;guard_cached_scan_filesis gone.On a cache miss,
plan_scan_for_snapshot_retaining_filesreads the manifests once, keeps the whole sorted list and selects from it. The list is written to the disk catalog cache on a blocking thread, off the query's path. Each disk-cache write now uses its own temp file, so two queries writing one entry at once can no longer leave it torn. A warm unfiltered scan now also plans throughplan_from_files, at the cost of the task rebuild it replaces.Manifests are read concurrently. Every walk of a snapshot's manifests goes through one helper,
manifest::reader::read_manifests: both planners, the incremental planner, and the two manifest-only stats reads. It reads up to 16 manifests at a time (ScanConfig::with_manifest_read_concurrency) and yields them in manifest-list order, so plans, counters and the first error reported are unchanged.A scan's file tasks share one residual filter.
FileScanTask::residual_filteris anArc<Expression>, wrapped once per plan; before, each task held a deep copy of the filter.The in-memory scan-files cache is bounded by bytes. It was bounded by entry count (128). It is now weighed by the lists' approximate size (
DataFile::approx_size_bytes, a few KiB per file) againstFLUREE_ICEBERG_SCAN_FILES_CACHE_MB(default 512).A list heavier than the whole budget (a table of more than about 150,000 data files) goes to one oversize slot beside the budgeted entries, keyed and scoped as they are. The latest such list stays warm, and a second one replaces the first, so memory beyond the budget is bounded to one list, and that list may weigh at most two budgets: a heavier list is not kept in memory and leaves the slot as it was, so the cache holds at most three budgets (1.5 GiB at the default). The first list to land there is logged at info.
0keeps no list in memory. moka accepts an entry heavier than its whole capacity and then drops it without a trace, so an oversize list never goes to moka. Every list is also written to the disk catalog cache. The disk format is unchanged.A paged unordered query returns the same rows on every execution. Paging an unordered answer with LIMIT/OFFSET was nondeterministic. An Iceberg graph-source scan read its data files in parallel and emitted each file's rows as its read finished. So a query with no ORDER BY returned its rows in a different order from run to run, and a client paging it could skip or repeat rows.
A scan now owes the query a
ScanOrder:Anyonly when no LIMIT or OFFSET appears anywhere in the query, sub-SELECTs and EXISTS included; only a slice can observe the order of an unordered answer. Such a scan streams files as their reads finish, as before.file_size_in_bytes), ties in plan order. That is a total order for one snapshot. The head of the read window is the cheapest file, so a LIMIT is answered from small files. Commit order would have made LIMIT 25 5x slower on a table whose files differ 25x in size.(data_sequence_number, path)order); main read them as their reads finished (buffer_unordered). Materialize depends on that order: without anorder_bycolumn the last row read for a subject wins, so a tombstone committed after a live row must be read after it, andorder_byties and nulls are also broken by read position. This fixes a data-integrity bug on main: a fresh materialize of a mapping with a delete convention and noorder_bycould resurrect a deleted subject when the tombstone sat in a later, smaller file.a_tombstone_committed_after_a_large_file_retracts_its_subjectfails on main in 3 of 3 runs and passes here. On a 24-file table whose files differ 25x in size (3.36M rows), draining the materialize read takes 188 ms against 171 ms on main (same instruction count), and its first batch arrives after 94 ms instead of 16 ms; a full materialize of a 672k-row table of the same shape takes 44.9 s against 45.4 s, since the read is under 1% of the pass.selectOne, and an AgentJson response cut by a byte budget (which returns a resume query with OFFSET), take a prefix of the answer, so their scans read deterministically too. Before this, a budgeted first page was read in any order while its resume page was read in the fixed one, so pages did not partition the answer.EmitOrder::{AsListed, SmallestFirst, Completion}).The decision travels in
PlanningContextto the R2RML scan operator and both fused-aggregate construction sites, and to the provider through an additiveR2rmlTableProvider::scan_table_ordered. Any path that plans without the query root, and any provider that doesn't override the new method, scans deterministically. Parent lookups always do. The graph-source crawl applies its subject OFFSET after the query, so it asks for deterministic scans throughQueryExecutionOptions::deterministic_scans, carried toExecutionContextastrust_fk_refsis.A class mapped by several TriplesMaps is scanned in mapping-document order:
triples_mapswas aHashMap, so its maps' rows came in a different order per process.The fused GROUP BY emits its groups in its fold map's iteration order, which a paged GROUP BY reads. Only the path behind
FLUREE_FUSED_VECTOR_FOLD=0was affected: it used std'sHashMap, whose hasher is seeded per instance, so the same rows came out in a different group order on every execution. That path now uses anFxHashMap. The default (vector-fold) path already keyed a hashbrown table with an Fx hash, which is fixed for a given input. The genericGroupByOperator, the both-ends-unbound property-path closure, the RDF list view's predicate set, the annotation probe's hash lane and the JSON-LD crawl iterated std hashed maps into output too (on the crawl, the content of a node shared by two paths varied, since its cut rendering was path-dependent and cached); each is now Fx-hashed or ordered, with a test that runs each shape six times and requires identical answers. The generic GROUP BY also got ~4-6% faster (instructions -4.5%) by moving groups out instead of cloning them.Each file read is built when the read window admits the file and spawned on its first poll, the shape the scan had before. An earlier version of this branch spawned reads eagerly, as the list of files was pulled. That left wall time unchanged, but peak RSS under glibc malloc rose from 308 to about 500 MiB on an unsliced COUNT over 24 equal files.
Fixes a pinned read across a column rename (the first commit, standalone). A scan task's schema names its batches' columns, and the R2RML operator finds columns by the names the mapping uses now. The planners attached the schema the snapshot was written under. So a read of a snapshot older than a rename returned no rows, without an error, except when a warm unfiltered scan was served from the cache. The materialize reads also resolved the mapping's columns through the old names, so a window ending before a rename lacked the renamed column. Every planner entry and both materialize reads now use
TableMetadata::read_schema_for_snapshot: the snapshot's field ids and types, under current names. On the base, with the new fixturesilver.renamed, a read pinned to the pre-rename snapshot returned the following (SPARQL and JSON-LD alike):Behavior notes
iceberg.scan_planand "Scan planning complete" now fire on every Iceberg scan, cache hits included. A warm unfiltered scan reportsfiles_selected = Ninfluree-bench-virtualwhere it reported nothing. For a top-k scan,files_selectedsums the planning and top-k read stages, as a cold top-k scan already did.data_sequence_number, as cache hits did before. The incremental and materialize paths plan from the manifests and keep it.plan_incrementaland both materialize reads for atosnapshot older than a rename: the renamed column is now read.ORDER BYdoes not avoid it: any LIMIT or OFFSET takes the fixed order. The Iceberg docs' row-order section says so (e203204).Breaking changes (for embedders)
FileScanTask::residual_filterisOption<Arc<Expression>>.FileScanTask::for_whole_fileandfor_whole_file_with_schematake the residual asOption<Arc<Expression>>; a caller passingNoneis unchanged.ScanConfighas a new public field,manifest_read_concurrency. Struct-literal construction must add it.R2rmlCache::new'smetadata_capacityno longer bounds the scan-files cache;FLUREE_ICEBERG_SCAN_FILES_CACHE_MBdoes, plus the one oversize slot.CompiledR2rmlMapping::triples_mapsis anIndexMapin mapping-document order (was aHashMap). Iteration and the serde shape are compatible. Remove withshift_removeto keep the order.R2rmlTableProvidergainsscan_table_ordered(.., order: ScanOrder), with a default that callsscan_table. An implementor that doesn't override it scans deterministically, asscan_tablemust. New public type:fluree_db_query::r2rml::ScanOrder.PlanningContext(scan_order),ExecutionContext(deterministic_scans) andContextConfig(deterministic_scans) each gain a public field. Struct literals must add it or use..Default::default().QueryExecutionOptionsgainsdeterministic_scansandwith_deterministic_scans.Measurements
Planning. Local filesystem table: 300 manifests, 2,400 Parquet files (identity
regionandday(ts)partitions), 120,000 rows. Base and branch builds of one harness ran strictly interleaved, 7 pairs per shape, each process with an empty cache dir, on a shared machine (load average 10 to 21). Medians, with mins in brackets:INof 3 ids (wall)region = "EU", 30,000 rows (wall)LIMIT 10(wall)The added-latency rows are the planner alone, over a storage that sleeps before every read (an object-store stand-in); that is where concurrent manifest reads pay. Cold wall times are dominated by data-file reads and are noisy. Every cold shape's minimum improved: 400-row window 65 to 58 ms,
IN64 to 62, region + window 68 to 59, unfiltered 76 to 59.Planning in isolation, in one process, on the 2,400-file kept list:
INselecting all filesCorrectness against the base: 417 harness queries return identical answers, and identical
files_selected/files_prunedwherever the base planned.plan_scan_for_snapshotunder eleven filters gives identical counters and an identical hash of every task's path, sequence number, residual and projection, in order.Row order. A quiet dedicated 16-vCPU cloud machine. Base and branch release builds of one harness ran interleaved, 6 rounds of one process per shape, 6 queries per process; the cell is the median of q1..q5. The tables are 24 files: even = 24 x 125,000 rows; skewed = (500,000, 20,000, 20,000, 20,000) x 6. Branch ÷ base, warm wall time:
OFFSETpast the end)COUNTLIMIT 25LIMIT 25 OFFSET 100000FILTER, no sliceFILTER … LIMIT 25 OFFSET 1000GROUP BY, no sliceGROUP BY … LIMIT 10 OFFSET 20LIMIT 255.5G to 2.3G,LIMIT 25 OFFSET 10000025.1G to 13.1G, filtered page 4.0G to 1.3G.COUNT, even files: 307 to 314 MiB) and falls on the sliced skewed ones (LIMIT 25356 to 82 MiB,LIMIT 25 OFFSET 100000861 to 447 MiB).Tests
fluree-db-iceberg:read_manifestskeeps list order, never exceeds its bound, and reports the first failure in list order.plan_from_filesplans all equal a hand-worked file list and order, with a shared residual and the same counters, and a hit reads no storage. All three log one identical "Scan planning complete" line.read_schema_for_snapshotandDataFile::approx_size_bytes.fluree-db-api:iceberg.scan_plancounts on warm scans.fluree-db-r2rml: TriplesMaps iterate in document order, through a serde round trip.fluree-db-query: fused operators fold the same rows into the same group order on every execution, on both fold paths.testsuite-sparql),cargo clippy --all --all-features --all-targets --locked -- -D warnings, the wasm32fluree-db-apiand parse lanes,cargo check --workspace --all-targets, andfluree-db-serverwith no default features. Tests:fluree-db-r2rml174,fluree-db-iceberg517,fluree-db-query1828 andfluree-db-delta86 (each--all-features);fluree-db-apiwithiceberg,native: lib 1216,grp_graphsource282,grp_query_sparql558,it_graph_source_r2rml70,it_iceberg_local_fs37,it_iceberg_policy15,it_fused_aggregate_routing1,it_iceberg_warehouse_root1; withsql,native:it_sql_graph_source6,it_sql_pushdown_lane21,it_r2rml_untyped_columns2; withdelta,native:it_delta_local_fs16,it_delta_differential3; the W3C suite 85, with its clippy. 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 ontofluree_test_support::scoped_default, which the workspace harness check (harness_coverage, run by CI and not in the list above) requires.Stacking and landing order
#2309 and #2313 land first: both are merged into this branch at their reviewed heads, so this branch's planning changes are tested against #2309's row filter (the exact filter is applied after every planning arm, kept-list hits included, pinned by
a_filtered_map_planned_from_the_kept_file_list_applies_its_filter). Their commits show in this diff until they are on main.Not in this PR
Manifest skipping by partition summary, and partition values keyed by field id, are a follow-up issue (#2318). So is a deterministic order for a sliced Delta scan (Follow-up: #2319): an ordered Delta dispatcher was measured and was not speed-neutral.