Repository navigation
fix(iceberg): a scan's file reads stop when the scan is dropped - #2366
Conversation
Every Iceberg scan reads its data files through `buffer_unordered`, each read a `tokio::spawn`ed task the stream awaited. Dropping the stream (its consumer has the rows a LIMIT needs, or the query was cancelled or timed out) dropped the `JoinHandle`s, which detaches the tasks rather than stopping them, so every read in flight ran on to the end of its file. A file over 64 MiB decodes on blocking threads, which not even an aborted task stops, so those went on fetching and decoding too. - `graph_source::file_read::read_in_own_task` spawns one file's read and aborts it when dropped. All four fan-outs use it: the query scan, the top-k scan's parallel tail, `stream_scan_tasks` (the materialize and collecting reads) and the ephemeral provider's scan. - `SendParquetReader::decode_large_file` reads through an `AbandonableStorage`, which refuses every read once the future that started the decode is dropped, so the blocking decode ends at its next fetch. The same guard stops the other slices of a row-group-parallel decode when one of them fails and the decode returns early. A read that finishes is unaffected, and so are query results. Tests: a dropped read aborts its task; a dropped `buffer_unordered` stream of reads aborts the reads in flight and starts no more; a large file's decode, held at its third fetch and then dropped, fetches nothing more (116 fetches without the guard). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
…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]>
bplatz
left a comment
There was a problem hiding this comment.
Approving. The abort sits in the right place, and the read path is safe to cancel mid-flight: the disk cache's FlightGuard clears its slot on drop, and there's no await between a fill's fetch and its temp-file write. A few small comments inline, none blocking.
On the disk-cache corner in the description: agreed it doesn't need code. Waiters retry rather than hang, and the extra cost only shows up in the case you describe.
| /// needs, or a cancelled query unwinds) drops the reads in flight. A bare | ||
| /// `tokio::spawn` left each of those reads running to the end of its file, for | ||
| /// no one. |
There was a problem hiding this comment.
Nit: this sentence describes the old behaviour, which the PR body already covers, so I'd drop it. Same for the AbandonableStorage doc in send_parquet.rs ("They went on…", L336–339) and the two large-file test docs (L2594–2595, L2684–2686).
There was a problem hiding this comment.
Agreed. This sentence went away with the module itself once I took you up on the inlining (b6c61f2, see the thread below), and the read_files_in_order doc that replaces it only says what dropping the stream does now. The AbandonableStorage doc and the two large-file test docs are rewritten the same way in bad71e2, so they describe what the guard does rather than what it replaced. The history stays in the PR description.
| pub(crate) fn spawn_file_read<F>( | ||
| read: F, | ||
| ) -> impl Future<Output = QueryResult<Vec<ColumnBatch>>> + Send + Sync + 'static | ||
| where | ||
| F: Future<Output = QueryResult<Vec<ColumnBatch>>> + Send + 'static, | ||
| { | ||
| let task = AbortOnDropHandle::new(tokio::spawn(read)); | ||
| async move { | ||
| task.await | ||
| .map_err(|e| QueryError::Internal(format!("Parquet read worker failed: {e}")))? | ||
| } | ||
| } |
There was a problem hiding this comment.
Optional: this has one caller and is a few lines, so it could live inline in read_files_in_order. The emit-order test already covers the abort, and the Box<dyn Stream + Send + Sync> there enforces Sync at compile time, so most of this module's tests could go too.
There was a problem hiding this comment.
Agreed, I think it's cleaner, done in b6c61f2. The spawn under AbortOnDropHandle now sits in read_files_in_order and the file_read module is gone. Before dropping its tests I wanted to make sure your read of the coverage held, so I swapped in a bare tokio::spawn there and a_dropped_scan_stream_aborts_the_reads_in_flight fails (count stayed at 0), so the stream-level test does carry the abort. The finished-read case is covered by the emit-order tests, and Sync by the boxed stream type, as you said. endless_read and wait_for moved next to the one test that uses them.
| let held = second_row_group_reads.load(SeqCst); | ||
| gate.add_permits(1 << 20); | ||
| tokio::time::sleep(std::time::Duration::from_millis(500)).await; | ||
| assert_eq!( | ||
| second_row_group_reads.load(SeqCst), | ||
| held, | ||
| "the second slice fetched more after the decode returned" | ||
| ); |
There was a problem hiding this comment.
Possible rare flake: the second slice checks the abandoned flag and bumps this counter in one poll. If its thread is pre-empted in between, the check can pass just before the decode returns while the increment lands after held is read. Allowing one in-flight fetch (<= held + 1) closes that, and still catches a missing guard (~42 more fetches).
There was a problem hiding this comment.
Good catch, I think you're right about the window. refuse_if_abandoned passes, the thread gets pre-empted before fetch_add, the decode returns and held gets read, and then the increment lands. adb75df allows <= held + 1 and adds a comment saying why. Since a slice only has one fetch in flight at a time, one is the most that can slip through that way, and a slice missing the guard still trips it by dozens.
| // Every blocking decode below reads through this storage. Dropping this | ||
| // future (its scan was dropped, or a sibling slice failed and returned | ||
| // early) drops the guard, and those decodes stop at their next fetch | ||
| // instead of reading the rest of the file. | ||
| let (storage, _abandon_on_drop) = AbandonableStorage::wrap(storage); |
There was a problem hiding this comment.
Follow-up idea, not for this PR: the small-file path has no equivalent. read_task_small_file runs decode_batches_arrow synchronously on the read's task for files up to 64 MiB, so those decodes occupy runtime workers and an abort can't interrupt them. Moving that decode to spawn_blocking behind this same guard would fix both.
There was a problem hiding this comment.
Good call, @bplatz, and it turned out cheap enough that I folded it in here as cf5bd1812. Your read is right: read_task_small_file decoded the fetched bytes on the read's own task, so a decode of up to 64 MiB held a runtime worker the whole time, and the guard couldn't reach it, since it sits on storage reads and an in-memory decode makes none.
So "behind the same guard" ended up meaning the same AbandonOnDrop, one layer down. decode_small_file runs the decode on spawn_blocking, as the large path does, and hands it the bytes through AbandonableChunks, a ChunkReader that refuses every read once the future awaiting the decode is dropped. The decode reads each page through its ChunkReader, so an abandoned one now stops at its next page instead of finishing the file. The iceberg.decode span is created on the read's task and entered on the blocking thread, so it keeps its parent and still times the decode.
a_dropped_small_file_read_stops_decoding holds a decode at one of its page reads, aborts the read, and checks both halves: the abort lands while the decode is held (it times out with the decode put back on the task), and no page is read after it (it fails with the check taken out). The cost is one blocking-pool hop per small file, which I haven't benchmarked but would expect to be noise next to a decode that size, and how many decode at once is still bounded by the scan's concurrency in read_files_in_order, as it is for large files.
…order spawn_file_read had one caller and a few lines, so the spawn under an AbortOnDropHandle now sits in read_files_in_order itself and the file_read module goes. Its tests are covered elsewhere: the stream-drop test fails without the abort (checked by swapping in a bare tokio::spawn), the emit-order tests cover a read's batches and errors, and the stream's Box<dyn Stream + Send + Sync> enforces Sync at compile time. The two test helpers move next to the one test that uses them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…not what it replaced AbandonableStorage's doc and the two large-file test docs described how a dropped decode behaved before this change. The PR description carries that; in the code it goes stale once the change lands. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…st its check The second slice checks the abandoned flag and bumps the test's counter in one poll, so a fetch that passed the check just before the decode returned could count after the test read it, and fail the equality. A slice runs one fetch at a time, so allowing one more still catches a slice that kept reading its row group, which fetches dozens more. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s scan is dropped A file of up to 64 MiB is fetched whole (or as its projected chunks) and then decoded in `read_task_small_file` on the read's own task. That decode held a runtime worker for as long as it ran, and dropping the scan couldn't interrupt it: the abandon guard sits on storage reads, and an in-memory decode makes none. `decode_small_file` now runs that decode on a blocking thread, like a large file's, and reads the bytes through `AbandonableChunks`, a `ChunkReader` that refuses every read once the future awaiting the decode is dropped. The decode reads each page through its `ChunkReader`, so an abandoned one ends at its next page. The `iceberg.decode` span is created on the read's task and entered on the blocking thread, so it keeps its parent and its time. Test: `a_dropped_small_file_read_stops_decoding` holds a decode at one of its page reads, aborts the read, and checks that the abort lands while the decode is held (it fails if the decode runs on the task) and that no page is read after it (it fails without the check). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings #2408 and #2366. #2408 and next's #2393 each add the structured-value check to the expander. Next's is kept, as #2408's merge notes say: a value object takes no type from its term there, so the check reads only the object's own `@type`. #2408's two later changes are carried into it: a vector type admits an array only (a map typed `@vector` was dropped by a bulk import), and a value object typed `@id` keeps its own message that its `@value` must be a string IRI. The adapter's refusal of a structured `@value` with no literal form merged as is. Both expander tests are kept; #2408's loses its last assertion, that a value object under a `@vector` term takes the term's type, which next refuses. Both integration tests are kept. #2408's compatibility entry drops "or the term it sits under", which would contradict next's "A JSON-LD value object is taken as written".
Partially addresses #2363: this fixes its third item, a dropped scan's file reads running on to the end of their files. Its second item, a LIMIT bounding how much of each file a scan reads in the first place, stays open there; why it isn't in this PR is below.
Every Iceberg scan reads its data files through
buffer_unordered, each file read atokio::spawnthe stream awaited. Dropping the stream (the operator has the rows its LIMIT needs, or the query was cancelled or timed out) drops thoseJoinHandles, and dropping aJoinHandledetaches the task rather than stopping it. So every read in flight kept going to the end of its file, for no one. A file over 64 MiB decodes onspawn_blockingthreads, which not even an aborted task stops, so those kept fetching and decoding too. Claude found this in the synthetic repro on the issue.What changes
read_files_in_order(fluree-db-api/src/graph_source/r2rml.rs) spawns each file's read under tokio-util'sAbortOnDropHandle, where it did a baretokio::spawn(read).await, so dropping the scan's stream aborts the reads in flight. Since perf(r2rml): Iceberg scans plan from the kept file list, and a paged unordered query returns the same rows every time #2315 every scan reads its files through it (the query scan and the top-k scan's parallel tail inscan_table_inner,stream_scan_tasksfor the materialize and collecting reads, and the ephemeral provider's scan), so that's the one place the change lives. The per-file spans are still created before the spawn, so they keep their parents.Mutexuntil it's spawned (a scan's stream has to beSync, and a pending read isn't), and once spawned the future holds only the task's handle, so the stream staysSync; its boxedSend + Synctype checks that at compile time.AbortOnDropHandlerather than another hand-rolledAbortOnDropnext to the indexer's; tokio-util was already in the lockfile and is now a direct dependency offluree-db-apibehind itsicebergfeature. (Until review this sat in a one-callergraph_source::file_read::spawn_file_readhelper with tests of its own; it's inline now,b6c61f2b1.)AbandonableStorage(fluree-db-iceberg/src/io/send_parquet.rs):decode_large_filereads through it, and it refuses every read once the future that started the decode is dropped. The blocking decode then ends at its next fetch, with an error no one reads. The same guard stops the slices after the one that fails in a row-group-parallel decode, which returns at the first failure it awaits; before, those ran to the end too.Query results don't change, and neither does a read that finishes before its stream is dropped. Small files decode inline on the read's task, so the abort reaches them at their next await.
One corner worth knowing, though: with a disk cache configured, the read being aborted can be the one filling the cache for its file (
coalesced_fetchatsend_parquet.rs:641,:816and:1051). Another query waiting on that same fill then sees the flight go away and restarts the fetch itself (DiskArtifactCache::coalesceinfluree-db-core/src/disk_cache.rsretries rather than hangs), where onmainthe detached leader finished the fill and handed it the bytes. Results and error types don't change, but that other query's latency and bytes can go up. It takes a disk cache, two queries reading one file at once, and the leader's scan dropped mid-fill, so I don't think it's worth code; if we did care, the option would be to let a fill's GET finish detached (a landed fill is reusable, unlike a decode) while still aborting the decode. Happy to talk through that one.Measured
Same box and synthetic tables as on #2363: LocalStack as S3 with 20 ms injected on its egress, the server (
dev-fast, default features) pinned to 16 vCPUs on a c7i.8xlarge, a fresh server per build. What matters here is what a query leaves running after it answers, so each query is followed by 10 s with nothing else running, counting the S3 GETs issued, the MB the S3 container sent and the server's CPU-s in that window. Cold / warm:LIMIT 5overmainmain, run again at the endmainmain, run againmain, two runsThe MB after the response with this PR are response bodies already on the wire when the reads were aborted; no new GET goes out. Inside the query window nothing moves (21.9 / 21.4 s and 1,318 / 1,296 GETs on the first query, against 21.2 / 20.8 s and 1,310 / 1,295 on
main). The 576-file reads mostly finish before the response anyway, so whethermainleaves work behind there depends on timing; with #2365 alone it left 99 MB.What this PR doesn't help with, and I want to be upfront about it: a cancelled query. Cancellation is cooperative and checked between batches, and a scan yields nothing until a whole file is read, so nothing drops the stream until the first file is done. With the client hanging up 3 s into a full-table
SUMover the 8 x 136 MB table, the server kept reading for the next 30 s onmain(1,185 GETs, 9.8 GB) and with this PR alike (1,161 GETs, 9.6 GB). Bounding that wait is the same per-file streaming that #2363's second item needs.Results: a
COUNTcontrol and the full-tableSUMare identical on every build; the unorderedLIMIT 5answers vary run to run onmaintoo, and every row returned, in every run on every build, is a row of its table.Why the LIMIT budget isn't in this PR
The budget is already there (
R2rmlScanOperator::row_budget), butR2rmlTableProvider::scan_tablehas nowhere to carry it, so it means either a new parameter, which breaks any embedder implementing the trait, or a second additive method. #2315 added one (scan_table_ordered, for the scan's emit order) and moved this same fan-out intoread_files_in_order, so I'd rather the hint ride on that request than land beside it; that's a trait-shape decision I didn't want to make unilaterally in this PR. Bounding the read within a file also needs the per-file read to stream its batches (read_taskreturns the whole file as aVec<ColumnBatch>); the Delta reader's bounded channel (fluree-db-delta/src/table.rs) is the model, and it's a bigger change than this one.Sequencing with #2315
#2315 has landed, and this branch now merges
main(f587e2fed) rather than being rebased, so nothing already under review was force-pushed. The two files that conflicted,r2rml.rsandephemeral.rs, take #2315's side whole, and the abort lives where the plan here said it would:read_files_in_orderspawns each read underAbortOnDropHandleinside its existingMutexblock, so the ephemeral provider gets it through the same call.a_dropped_scan_stream_aborts_the_reads_in_flightmoved tor2rml::emit_order_testsand drivesread_files_in_orderitself, under all three emit orders (AsListedandSmallestFirstrunbuffered,Completionrunsbuffer_unordered), with its counting reads next to it. One conflict git didn't flag: #2315 gavedecode_large_fileaniceberg_schemaargument, so the two large-file tests now passNonefor it.The first version of this PR suggested
read_in_own_task(read)for that spot, which wouldn't have compiled: it took a closure that built the read, and wrapping #2315's already-built read in one puts a value that isn'tSyncinto the stream. Claude's review pass caught it, and it's why the spawn takes the built read.Tests
r2rml::emit_order_tests::a_dropped_scan_stream_aborts_the_reads_in_flight:read_files_in_orderover 16 reads with 4 in flight, dropped after its first poll, aborts the 4 in flight and starts no more, in each of the three emit orders.send_parquet::tests::a_dropped_large_file_read_stops_fetching: a 38 MB file's decode, held at its third fetch and then aborted, fetches nothing more. Without the guard it went on to 116 fetches, the rest of the file.send_parquet::tests::a_failing_slice_stops_the_slices_after_it: a row-group-parallel decode in two slices, with every read of the first failing and the second's held. Once the decode returns, the second slice fetches at most the one fetch that had already passed its check; without the guard it made 42 more fetches. (The decode awaits its slices in order, so this covers the slices after the failing one; a slice still running ahead of it is awaited as before.)The stream-drop test fails without the abort (see below), and both large-file tests fail with the decode reading through the bare storage.
Verification
After merging
main, atf587e2fed, on a Mac and only for the touched crates (CI runs the full gate):cargo fmt --all -- --check,cargo clippy -p fluree-db-iceberg --all-targets --all-features -- -D warningsandcargo clippy -p fluree-db-api --all-targets --features iceberg -- -D warnings: clean.cargo test -p fluree-db-iceberg --all-features: 528 passed, 0 failed (9 ignored).cargo test -p fluree-db-api --features iceberg --lib: 1,233 passed, 0 failed (1 ignored);it_iceberg_local_fs,it_iceberg_subselectandit_iceberg_filtered_logical_table: 42, 16 and 8 passed.spawn_file_readspawning through a baretokio::spawnfailsa_dropped_read_aborts_its_taskanda_dropped_scan_stream_aborts_the_reads_in_flight(the other sevenfile_readandemit_order_teststests pass);read_files_in_ordergoing back totokio::spawn(read)and skippingspawn_file_readfailsa_dropped_scan_stream_aborts_the_reads_in_flight; anddecode_large_fileforgetting itsAbandonOnDropguard fails both large-file tests.After review, at
adb75dfeb(mergingmainat9a3052a28, thenb6c61f2b1,bad71e2efandadb75dfebfor Brian's notes), on a Mac and only for the touched crates:cargo fmt -p fluree-db-iceberg -p fluree-db-api -- --check,cargo clippy -p fluree-db-iceberg --features aws --all-targets -- -D warningsandcargo clippy -p fluree-db-api --features iceberg --all-targets -- -D warnings: clean.cargo test -p fluree-db-iceberg --features aws --lib send_parquet: 29 passed;cargo test -p fluree-db-api --features iceberg --lib emit_order_tests: 6 passed.read_files_in_orderspawning through a baretokio::spawnfailsa_dropped_scan_stream_aborts_the_reads_in_flight(count stayed at 0), which is what let thefile_readmodule's own tests go.Before the merge, on a c7i.8xlarge, at
790f7610c(the first round of review fixes):cargo fmt --all -- --check,cargo clippy --all --all-features --all-targets --locked -- -D warningsandcargo check --workspace --all-targets --locked(CI's flags): clean.cargo test -p fluree-db-iceberg --all-features: 507 passed, 0 failed (9 ignored).cargo test -p fluree-db-api --all-features: 99 test binaries, 5,691 passed, 0 failed (137 ignored).spawn_file_readspawning through a baretokio::spawninstead ofAbortOnDropHandle,a_dropped_read_aborts_its_taskanda_dropped_scan_stream_aborts_the_reads_in_flightfail (the reads are never dropped), and the other twofile_readtests pass.The measurements above are from
ed704eabe, againstmainbefore #2315.790f7610cchanges how the abort handle is held, not when it fires, and the merge moves the call intoread_files_in_orderwithout changing what it does, so I didn't re-run them on the merged branch.testsuite-sparql/isn't touched.🤖 Generated with Claude Code