Repository navigation
[SPARK-60381][SQL] Account the late-materialization survivor buffer to the task's execution memory - #59639
[SPARK-60381][SQL] Account the late-materialization survivor buffer to the task's execution memory#59639peter-toth wants to merge 4 commits into
Conversation
…o the task's execution memory
dongjoon-hyun
left a comment
There was a problem hiding this comment.
Thank you for the follow-up, @peter-toth. I reviewed the latest commit, 0c670c9, and left 15 inline comments. I found no path that returns wrong rows in this commit, and every path I traced releases what it reserves, including early close and exceptions. Most items are about what the reservation and the spill cost other consumers, and about what the tests leave unpinned. Here is a summary, ordered by priority.
Correctness
LateMaterializationParquetRecordReaderL1016: A spill can raise the reader's real heap use while it tells the task memory manager that memory was freed, because the re-read's ranges and key pages are not accounted.LateMaterializationParquetRecordReaderL810: An unchecked error from another consumer's spill, triggered by this reservation, now leaves the reader insideFileScanRDD, whereignoreCorruptFilestakes it for a corrupt file.LateMaterializationParquetRecordReaderL577: Without a pushed data filter, the pre-built store also reads the key columns' offset indexes, so an unreadable one gives the filter up only in a task with on-heap vectors.LateMaterializationParquetRecordReaderL1009: Nothing enforces that a spill on the reading thread comes only between two batches.
Memory and performance
LateMaterializationParquetRecordReaderL1069: Asking formax(missing, used)can spill other consumers, evict cached blocks or block the task for memory the buffer does not need, and the test passes only because 10,000 bytes are free.LateMaterializationParquetRecordReaderL814: A denied range reservation, as small as 40 bytes, silently gives the filter up for the whole row group.LateMaterializationParquetRecordReaderL575: Row groups in which every row survives hold the largest buffers but can never be spilled, although a whole-block key re-read needs no offset index.LateMaterializationParquetRecordReaderL1111: Scan tasks that held no execution memory before now count as active tasks, which shrinks the other tasks' shares.LateMaterializationParquetRecordReaderL511: After a spill the next row group splices again, so steady pressure repeats the buffer, spill and re-read cycle for every row group.LateMaterializationParquetRecordReaderL375: Each batch walks the whole queue and takes the executor-wide memory manager lock, and phase 1 reads anAtomicLongper survivor.
Tests
ParquetStorageFilterSuiteL2276: The re-read bookkeeping is not pinned, and four one-line mutations should pass the whole suite.ParquetStorageFilterSuiteL1984: An inline copy of this fixture remains, and two of the new helpers could reuse existing ones.
Docs and comments
LateMaterializationParquetRecordReaderL976: ThespliceCurrentRowGroupjavadoc at L168-169 no longer holds after a spill.
Cleanup
LateMaterializationParquetRecordReaderL1028: The remaining ranges can be built per range instead of per row, and thereaderRangesForcall and theremainingRows <= 0guard are dead.LateMaterializationParquetRecordReaderL228: The new fields split the "Splicing state." field block.
Items 1, 5, 6 and 11 are the most important. Items 2 and 4 describe cases that I could not trigger with in-tree code today. Items 5 and 7 also contradict sentences in the PR description, which becomes the commit message.
| long before = survivorMemory.getUsed(); | ||
| abandonSplicing(); | ||
| rereadRemainingKeys = true; | ||
| return before - survivorMemory.getUsed(); |
There was a problem hiding this comment.
A spill can leave the reader holding more heap than before, while it tells the task memory manager that memory was freed. This returns only the queued key bytes, and TaskMemoryManager hands them straight to the consumer that asked. The next nextBatch() then allocates two things that heldCharge() does not count, since L1050 counts rangeCharge for loadedRanges only:
remainingRanges(L1032-1036), a secondRowRangeswith oneRangeper remaining run, whileloadedRangesstays referenced by the field, by the non-key readers'RangeListState(ParquetReadState.java:107) and bydataPages;rereadKeyPages(L1038), the compressed key pages of every remaining row, which parquet reads into heap buffers that stay until the next row group.
For example, take a 1M-row row group with a long key and 100k scattered survivors (one range each), spilled after its first batch of 4096 rows. The spill frees 95,904 x 9 B, about 0.86 MB. The re-read then allocates about 3.6 MB of new ranges (3.8 MB at ROW_RANGE_BYTES) and reads the key chunk's remaining pages, about 7.7 MB for plain longs. So the reader's real footprint grows by several MB under the memory pressure that caused the spill, and scattered survivors are what a selective bloom filter produces. Two things make it more likely that this consumer is the one spilled: getUsed() includes the unspillable rangeCharge, so ceilingEntry(required - got) (TaskMemoryManager.java:242-249) can pick it when it can free little, and spill() ignores size, so a request for one page drops the whole queue. I traced this by reading the code and did not run it. Could spillQueuedSurvivors return 0 when the re-read would cost at least what it frees, e.g. the remaining ranges at ROW_RANGE_BYTES plus blockAccounting.compressedBytesForRowRanges over the key paths (no I/O, since L579 built the store), or else charge the new ranges?
There was a problem hiding this comment.
Gone with the spill in 778c14954a9, see viirya's comment.
| if (rangeBytes > cap) return null; | ||
| if (rangeCharge > cap) return null; | ||
| } | ||
| if (!reserveSurvivorMemory((accountKeys ? splicedBytes : 0L) + rangeCharge)) { |
There was a problem hiding this comment.
This is the first task-memory acquisition inside FileScanRDD's per-file read, so an unchecked error from a spill it triggers now looks like a corrupt file. The two reservations (L810 and L814) are outside every catch of the reader. When the pool cannot grant them, TaskMemoryManager.spillConsumer spills other consumers of the task and converts only interrupts and IOException (TaskMemoryManager.java:326-341), so any other RuntimeException or InternalError from their spill() propagates unchanged. Consumers that accept a spill triggered by another consumer include UnsafeExternalSorter while it is being read, HybridRowQueue, Spillable collections and another late-materialization reader of the same task. With spark.sql.files.ignoreCorruptFiles=true, such an error now leaves nextBatch() and reaches FileScanRDD.scala:284-289, which skips the rest of the file. The task then succeeds with a truncated scan, and the other consumer may be left half-spilled. Before this PR, the same error could only come from that consumer's own allocation outside FileScanRDD, and it failed the task. This is the concern for which throwIfKilled wraps a kill in a checked SparkException (ParquetStorageFilter.scala:276-280). I found no in-tree spill path that throws such an error today, apart from invariant checks, so this is about robustness. Could the two reservations rethrow a foreign RuntimeException or InternalError in a form that ignoreCorruptFiles does not swallow?
There was a problem hiding this comment.
Agreed. Wrapping the two reservations the way throwIfKilled wraps a kill, in a checked SparkException around the cause, looks like a cheap fix. FileScanRDD then can't take another consumer's spill failure for a corrupt file under ignoreCorruptFiles. A kill that lands during that spill is already safe: TaskMemoryManager rethrows it as a RuntimeException, which the same wrap would cover, and the task is still killed afterwards anyway.
There was a problem hiding this comment.
Done in 778c14954a9. Every reservation now rethrows through ParquetStorageFilter.memoryReservationFailed:
- a
RuntimeExceptiongoes out in a checkedSparkException, as inthrowIfKilled; - an
InternalErrorgoes out in anUnknownError.
A new test has another consumer's spill throw each one, and checks that shouldIgnoreCorruptFileException rejects what comes out.
| // spilled. Phase 2 reads its store anyway, and gives the filter up on an unreadable index. | ||
| spillableRowGroup = | ||
| spliceCurrentRowGroup && accountKeys && finalRowCount < blockRowCount; | ||
| if (spillableRowGroup) { |
There was a problem hiding this comment.
Minor: When no parquet filter is pushed, this is the block's first store build, so it also reads the key columns' offset indexes, and "Phase 2 reads its store anyway" at L574 holds only for the non-key ones. With a pushed filter, usually the inferred isnotnull(key), initialize has already built every block's store over the whole projection through getFilteredRecordCount, so nothing changes. Without one (spark.sql.parquet.filterPushdown=false, an INT96 timestamp key that ParquetFilters cannot convert, a coalesce(...) join key, or the suite's direct readers), the base built the store in phase 2 over nonKeyColumns only. Now every partly read spliced row group in an on-heap task:
- reads one more offset index per key column chunk, whether or not a spill comes, and the metrics do not count it;
- gives the filter up when a key column's offset index is unreadable, because
ColumnIndexStoreImpl.createthen returns its empty store and phase 2 throwsMissingOffsetIndexException. L596 then logsOFFSET_INDEX_UNREADABLEnaming a non-key column whose index is fine. The same file read outside a task, or off heap, keeps the filter. For example, "the checked column is false for a row group read without its offset index" withbreakOffsetIndex(damaged, 1, columnIdx = 0)underreadInTask(memoryTask(...))should return that row group unchecked (I did not run it); - fails the read on an unchecked error decoding that index, such as an encrypted file's
TagVerificationException, where a plain read never reads it.
No test covers the in-task, no-filter, partly read case. Could you note this in the comment at L571-574 and add such a test?
There was a problem hiding this comment.
Gone with the spill in 778c14954a9. Phase 2 builds the store over its own columns again, as before this PR.
| * reading thread, since the reader takes no lock. There it can come only between two batches. | ||
| */ | ||
| private long spillQueuedSurvivors() { | ||
| if (Thread.currentThread() != readerThread || !spillableRowGroup || !spliceCurrentRowGroup |
There was a problem hiding this comment.
Minor: The javadoc says a spill on the reading thread "can come only between two batches", but nothing here checks it. spillableRowGroup is already true from L575 on, including while super.nextBatch() reads each batch. If a consumer ever acquired task memory on the reading thread inside nextBatch(), this would run between the re-read check at L376 and the poll at L381. spliceCurrentRowGroup would turn false, the poll would be skipped, and L394-395 would publish the persistent key vectors, which the base reset but did not fill because installRowGroup cleared their readers. Those rows are marked checked, so the post-scan Filter would skip the storage filter on them. I found nothing in the parquet, vectorized or FileScanRDD read paths that acquires task memory there today, so this is latent. Could a flag set on entry to nextBatch() and cleared in a finally make spillQueuedSurvivors return 0 inside it?
| long used = survivorMemory.getUsed(); | ||
| long missing = held - used; | ||
| if (missing <= 0) return true; | ||
| long granted = survivorMemory.acquireMemory(Math.max(missing, used)); |
There was a problem hiding this comment.
Asking for max(missing, used) makes the memory manager treat the whole amount as required, so a few missing bytes can spill other consumers, evict cached blocks, or block the task. TaskMemoryManager.acquireExecutionMemory spills other consumers until got >= required (TaskMemoryManager.java:240-249), maybeGrowPool(numBytes - memoryFree) can evict storage blocks (ExecutionMemoryPool.scala:120), and a task below 1/2N of the pool waits in lock.wait() while toGrant < numBytes (ExecutionMemoryPool.scala:139-142). All of this can happen when missing alone was free. The ask is not clamped to the cap either, so at the default 64 MiB the last step asks about 49 MiB for a 9-byte shortfall, and the excess stays reserved through the store build and phase 2's I/O until L629. The test "the survivor buffer asks for little more memory than it holds" passes only because 10,000 bytes are free against at most 392 reserved. With memoryManager.limit(held + 300L) at ParquetStorageFilterSuite.scala:2266, which is still more than the 220 bytes the buffer ever holds, I expect the assertion at ParquetStorageFilterSuite.scala:2272 to fail. At survivor 18 of the second row group the buffer holds 202 bytes and has 196 reserved, so it needs 6 more. It asks for 196, gets the 104 that are free, and TaskMemoryManager spills other for the rest. So "a buffer that fits in the free memory spills no other consumer" in the PR description holds only for a buffer under about half the free memory. I traced this by reading the code and did not run it. Could the ask be bounded, e.g. max(missing, min(used, 1 MiB, cap - used)), and the excess released right after phase 1, with the test and the description narrowed to match?
There was a problem hiding this comment.
This reproduces as you predicted. In "the survivor buffer asks for little more memory than it holds", with memoryManager.limit(held + 10000L) the other consumer keeps 1000000. With memoryManager.limit(held + 300L), which is still more than the 220 bytes the buffer ever holds, the rows are still right, but other.getUsed drops to 0: the whole other consumer is spilled. So the test should also cover a free amount close to what the buffer holds, and the PR description's "a buffer that fits in the free memory spills no other consumer" doesn't hold yet. Since the ask is not clamped to the cap either, near the default 64 MiB the reservation can briefly reach about twice maxSplicedRowGroupBytes, until L629 trims it.
There was a problem hiding this comment.
Done in 778c14954a9, with your formula. What phase 1 reserved ahead is released before phase 2 reads.
The test now leaves 440 bytes free, twice the 220 the buffer holds. A new case with a 300-byte cap and 300 bytes free fails without the clamp to the cap. The description now says the reservation stays below twice what is held while small, and below 1 MiB more once larger.
| } | ||
| } | ||
|
|
||
| test("a spill while a spliced row group is emitted frees its survivors, and its keys are read " + |
There was a problem hiding this comment.
The re-read bookkeeping is not pinned: this is the only test that drives it, and it spills once, after the first batch of block 0, over one range, one page and one long key. Each of these one-line mutations should still pass the whole suite:
- dropping
rowsEmittedInRowGroup = 0L;(LateMaterializationParquetRecordReader.java:512), since the field starts at 0 for block 0, and block 1 here survives whole, so it is never spilled; rowsEmittedInRowGroup = columnarBatch.numRows()instead of+=(LateMaterializationParquetRecordReader.java:378), since the two agree after the first batch;- dropping
loadedBlockIndex = blockIdx;(LateMaterializationParquetRecordReader.java:626), since the default 0 is right for block 0; - replacing only
keyColumns[0]'s reader (LateMaterializationParquetRecordReader.java:1042-1045), since there is one key.
In production a spill can come at any batch of any row group, so each of these would put keys on other rows, marked checked, which the post-scan Filter trusts. requireRowCount catches it only when the row counts disagree. I checked these by reading the tests and did not run them. Could you add spills after the second batch and at the first batch of block 1, e.g. over twoRowGroupsOf20 with the even-keys filter so that both row groups are read in part, one over writePagedFile whose remaining rows start on a later page, and one over the two-key fixture of "two key columns are both charged"? Deriving loadedBlockIndex from nextBlockIndex - 1, and the rows left from the base's totalCountLoadedSoFar - rowsReturned through a protected accessor, would also remove two of these mirrors.
There was a problem hiding this comment.
I ran the spill at other points against this commit, using a variant of readWithSpill that spills at the n-th batch instead of the first:
- over
twoRowGroupsOf20withk % 2 == 0and batch size 4, so both row groups are read in part: at each of the six batches, which includes the 2nd and 3rd batches of block 0 and every batch of block 1; - over
writePagedFilewithk % 3 == 0and batch size 16, so the remaining rows start on later pages: at batches 1, 2 and 5.
Every case returned exactly the expected keys, all marked checked. A spill at a row group's last batch freed nothing, as it should, since the queue is empty there. So the current bookkeeping looks right, and these cases would pin the mutations you list. Could they be added? One spill over the two-key fixture would also cover replacing every key's reader, not only keyColumns[0]'s.
There was a problem hiding this comment.
Gone with the spill in 778c14954a9. Thanks for running the cases, viirya.
| // 40 rows of a long key and a string value in two row groups of 20. A filter of `k >= 10` keeps | ||
| // one range of 10 rows in the first and all 20 rows of the second. A buffered long key costs 9 | ||
| // bytes and a range 40, so the first row group holds 130 bytes and the second 220. | ||
| private def twoRowGroupsOf20(dir: File): String = { |
There was a problem hiding this comment.
Nit: The same fixture is still inlined at L1630-1635, in "a key vector that cannot grow, or a codec's InternalError, gives the row group up", which could call this and keep val rows for its expected rows.take(20) ++ rows.drop(30) at L1665. Two of the new helpers could also reuse existing ones. readWithSpill could deny the next acquisition with memoryManager.markExecutionAsOutOfMemoryOnce(), as UnsafeExternalSorterSuite.java:257 does, instead of limit(0L) and the limit(1L << 40) restore, and the 76 and 130 assertions should still hold. The two local bytes helpers (L2233-2240 and L2313-2318) repeat readUnderCap with asTask around the read. Could you reuse them?
There was a problem hiding this comment.
Done in 778c14954a9:
- "a key vector that cannot grow, or a codec's InternalError, gives the row group up" now calls
twoRowGroupsOf20; readWithSpillwent with the spill;- the denial test's
bytesreads throughreadUnderCap, which now takes an optional task context.
| * Gives up splicing for the row group being evaluated and frees its buffered survivors. Phase 2 | ||
| * then reads every projected column, so the rows are unaffected. | ||
| * Gives up splicing for the row group being read and frees its buffered survivors, but not the | ||
| * published ones. Phase 2, or the key re-read after a spill, then reads the key columns, so the |
There was a problem hiding this comment.
Minor: This now says that the re-read after a spill reads the key columns, but the spliceCurrentRowGroup javadoc at L168-169 still says "False means phase 2 read every projected column, so the emit path takes the key columns from the persistent batch". After a spill that flag is false, but phase 2 read only the non-key columns and the keys come from rereadKeyPages. Also, spillableRowGroup stays true after the MissingOffsetIndexException fallback abandons splicing at L601, which is harmless only because spillQueuedSurvivors also checks spliceCurrentRowGroup and the queue. Could the field javadoc say something like "False means the key columns are read from the file, by phase 2 or by the re-read after a spill", and could the fallback clear spillableRowGroup?
There was a problem hiding this comment.
Gone with the spill in 778c14954a9. The spliceCurrentRowGroup javadoc holds again, and spillableRowGroup is gone.
| rereadRemainingKeys = false; | ||
| long remainingRows = loadedRowCount - rowsEmittedInRowGroup; | ||
| if (remainingRows <= 0) return; | ||
| PrimitiveIterator.OfLong rows = loadedRanges.iterator(); |
There was a problem hiding this comment.
Nit: This walks loadedRanges one row at a time: nextLong() per emitted row, then addSelectedRow per remaining row. Parquet 1.18.1's public RowRanges.getRanges() and Builder.addSelectedRange(from, to) build the same ranges per range, and ParquetReadState.java:107 already reads getRanges(): long skip = rowsEmittedInRowGroup; for (RowRanges.Range r : loadedRanges.getRanges()) { long n = r.to - r.from + 1; if (skip >= n) { skip -= n; continue; } remaining.addSelectedRange(r.from + skip, r.to); skip = 0; }. Also, a spill comes only after a batch was emitted, so remainingRows is below the block's row count and readerRangesFor at L1041 always returns remainingRanges, and the queue is non-empty only while rows remain, so the guard at L1027 never fires. loadedBlockIndex and loadedRowCount also equal nextBlockIndex - 1 and loadedRanges.rowCount() here. Could you simplify this?
| /** Set by a spill, so the next batch reads the keys of the rest of the row group again. */ | ||
| private boolean rereadRemainingKeys; | ||
| /** The key pages read again after a spill, closed with the row group. */ | ||
| private PageReadStore rereadKeyPages; |
There was a problem hiding this comment.
Nit: These two new groups are inserted inside the "Splicing state." block, before its last two members, so persistentBatchColumns and spliceBatchColumns (L229-232) now sit under "The block, final ranges and row count of the row group being emitted.", although they are per-file vectors that takeOverBatch sets. AGENTS.md asks a new member to "follow the sectioning the file already uses and put the new member with the code it belongs with". Could you move L209-228 below spliceBatchColumns?
viirya
left a comment
There was a problem hiding this comment.
Thanks for the follow-up, @peter-toth, and thanks @dongjoon-hyun for the thorough pass. I agree with all 15 of his items. I ran two of them against this commit, and replied in their threads:
- Item 5 reproduces as predicted. With 300 bytes free, which is more than the buffer ever holds, the read spills the other consumer whole.
- The re-read after a spill returns the right rows, all checked, at every other spill point I tried. So item 11 is about tests that pin it, not about a bug. The probes I used could serve as those tests.
My main question is about scope. Most of the open items (1, 3, 4, 7, 9, 11, 13, 14) sit in the spill half of the PR, and that half frees only a narrow slice of the buffer. I left the details inline on spill(). Would you consider landing the accounting and the denial handling first, and adding the spill once several readers per task exist?
| } | ||
|
|
||
| @Override | ||
| public long spill(long size, MemoryConsumer trigger) { |
There was a problem hiding this comment.
I suggested a spillable consumer on #58895, but seeing what it takes here, I'm not sure the spill earns its place in this PR. It frees memory only when all of these hold:
- the column vectors are on heap;
- phase 2 reads the row group in part;
- the spill comes from the reading thread (so never under a pipelined Python UDF, whose writer thread drives the scan);
- the rows' keys are still queued, not yet emitted.
It never frees the ranges. In exchange it brings the store pre-build (item 3), replaceColumnReader, the loaded* / rowsEmittedInRowGroup mirrors, the thread confinement and the key re-read, and the re-read can allocate more than the spill freed (item 1). Accounting plus denial already gives the memory manager what it needs: other consumers spill before this one is refused, and a refused reader backs off.
Would you consider having spill() return 0 here, and adding the spill in a follow-up once several readers per task exist (the SPJ case in the description), where its benefit can be measured? That would also resolve items 1, 3, 4, 7, 9, 13 and 14 for this PR.
There was a problem hiding this comment.
Done in 778c14954a9. spill() returns 0, and the key re-read with everything it needed is gone.
I'd rather not plan the spill as a follow-up for the SPJ case either:
- it frees only the queued on-heap keys, never the ranges;
- the re-read it forces allocates outside the memory manager, under the pressure that triggered it;
- in a sorted merge every open reader also holds its current row group's column chunks, which nothing accounts and which are usually larger than this buffer.
With several readers per task, accounting with denial is what bounds them.
| s"read, up to ${PARQUET_STORAGE_FILTER_PUSHDOWN_MAX_SPLICED_ROW_GROUP_BYTES.key}, " + | ||
| "outside Spark's memory manager.") | ||
| s"read, up to ${PARQUET_STORAGE_FILTER_PUSHDOWN_MAX_SPLICED_ROW_GROUP_BYTES.key}, in " + | ||
| "the task's execution memory unless column vectors are off heap.") |
There was a problem hiding this comment.
"in the task's execution memory unless column vectors are off heap" reads as if nothing is accounted off heap. The row ranges are accounted off heap too, and with scattered survivors they are the larger part. Maybe: "The matching key values and row ranges of a row group are buffered while it is read, up to ..., and counted against the task's execution memory, except key values held in off-heap column vectors."
dongjoon's first round and viirya's review. None of it changes a query answer. - The spill is gone, as viirya suggested. The consumer's spill() frees nothing. The key re-read, the column index store built before phase 2, replaceColumnReader, the reading-thread check and the emitted-row bookkeeping go with it. - A reservation asks for at most 1 MiB more than the buffer holds, and never past the cap. What phase 1 reserved ahead is given back before phase 2 reads. - Emitting a row group releases its memory in 1 MiB steps rather than per batch. A running total of the queued charges and a plain copy of the reservation replace the queue walk and the atomic read. - A denied reservation with no key values in it gives the filter up at once, since giving splicing up frees nothing. That is always the case off heap. - An error from another consumer's spill during a reservation goes out in a form ignoreCorruptFiles cannot take for a corrupt file. - Four new metrics count the row groups the budget limited, by what it gave up and why. The first of each kind per split is logged at INFO. - Comments: the conf docs say what is counted off heap, and that a task holding the buffer shares on-heap execution memory. The accounting fields move below the emitted batch's arrays. - Tests: the spill tests go. New tests cover the step release, the cap on an ask and an error from another consumer's spill. The denial test also covers off heap and the metrics. The test access reads a survivor batch's vectors without reflection, and the denial and codec tests reuse the read and fixture helpers.
dongjoon-hyun
left a comment
There was a problem hiding this comment.
Thank you for addressing items 1-15, @peter-toth. I reviewed the latest commit, 778c149, and left 13 inline comments, continuing the numbering from items 1-15. Dropping the spill, as @viirya suggested, closed most of the open items, and every path I traced still releases what the reader reserves. Item 16 is the one path I found that can drop rows: under ignoreCorruptFiles, an IOException from evicting a cached block during a reservation skips the rest of a healthy file. Here is a summary, ordered by priority.
Correctness
LateMaterializationParquetRecordReaderL1052: anIOExceptionfrom evicting a cached block inside the reservation gets past the catch, soignoreCorruptFilesskips the rest of a healthy file.LateMaterializationParquetRecordReaderL817: a splicing give-up is counted before phase 2's offset-index fallback can still give the filter up, so that row group counts as one that kept the filter.ParquetStorageFilterL341:memoryReservationFailedcopies two cases ofrethrowIfMustPropagateinstead of calling it, so a fatal error nested in another consumer's spill error can end up pastkillOnFatalError.depth.
Memory and performance
LateMaterializationParquetRecordReaderL803: a memory denial is forgotten at the next row group, so steady pressure repeats the buffering and the denial in every row group of the split.LateMaterializationParquetRecordReaderL491: each file'sSurvivorMemorystays in the task's consumer set until the task ends.
Tests
LateMaterializationParquetRecordReaderL1058: no test reaches a partial grant or checks what a denied read leaves reserved, and five one-line mutations should pass the suite.ParquetStorageFilterSuiteL1210: two cap tests check one counter rather than all four.ParquetTestAccessL239:queuedSurvivorSetsnames the package-privateSurvivorBatchin a cast, against the file's own rule.ParquetStorageFilterSuiteL2200: the 400,000-row fixture is written by two tests, the suite's slowest and fourth-slowest.ParquetStorageFilterSuiteL2224: the assertion message still describes round 1's per-batch release.ParquetStorageFilterSuiteL2179:readInTaskwrapsreadCheckedin the confs and the task by hand.
Cleanup
LateMaterializationParquetRecordReaderL234:accountKeysand the reservation at L800-805 re-deriveMEMORY_MODEandheldCharge().LateMaterializationParquetRecordReaderL722:rangeCharge = 0L;is a dead store.
Items 16, 17 and 21 are the most important. Items 16 and 17 also contradict sentences in the PR description, which becomes the commit message.
| long granted; | ||
| try { | ||
| granted = survivorMemory.acquireMemory(ask); | ||
| } catch (RuntimeException | InternalError e) { |
There was a problem hiding this comment.
An IOException from evicting a cached block inside this reservation gets past this catch, so under ignoreCorruptFiles the read skips the rest of a healthy file. acquireMemory can grow the execution pool by evicting storage, and eviction writes a block with a disk level to disk on this thread:
maybeGrowPool(numBytes - memoryFree)(ExecutionMemoryPool.scala:120) andfreeSpaceToShrinkPool(UnifiedMemoryManager.scala:171);evictBlocksToFreeSpace(StorageMemoryPool.scala:127), whose loop has afinallyand nocatch(MemoryStore.scala:548-550);dropFromMemory, thendiskStore.putorputBytes(BlockManager.scala:2273 and 2283), thenDiskStore.put(DiskStore.scala:86-89).
TaskMemoryManager converts only an IOException from a consumer's spill() (TaskMemoryManager.java:331), not one from memoryManager.acquireExecutionMemory at TaskMemoryManager.java:206 and 301. So a full or failing local disk sends IOException: No space left on device out of nextBatch(), DataSourceUtils.shouldIgnoreCorruptFileException accepts it (DataSourceUtils.scala:273), and FileScanRDD.scala:284-289 logs "Skipped the rest of the content in the corrupted file" while the task succeeds. If openForWrite fails (DiskStore.scala:159), the FileNotFoundException is skipped as a missing file under ignoreMissingFiles (FileScanRDD.scala:277-280), or otherwise fails the query as FAILED_READ_FILE.FILE_NOT_EXIST naming the Parquet file (FileDataSourceV2.scala:139-140). If the error comes from the retry at TaskMemoryManager.java:301, the bytes granted at TaskMemoryManager.java:206 also belong to no consumer, so the task that now succeeds reports "Managed memory leak detected". This needs only a storage pool that has borrowed execution memory and holds blocks of a disk level, such as Dataset.cache()'s default MEMORY_AND_DISK, and even a row group's first reservation, 49 bytes for a long key, can trigger it. Before this PR the read never acquired execution memory inside FileScanRDD's per-file read, and the PR description says the reader "rethrows in a form FileScanRDD cannot take for a corrupt file under ignoreCorruptFiles". I traced this by reading the code and did not run it. Could this catch Exception | InternalError, which compiles although nothing here declares a checked exception, with memoryReservationFailed wrapping any NonFatal exception in the checked SparkException (which leaves an InterruptedException from the 1/2N wait as it is), and its doc and the description naming the eviction? A test could pass a TaskMemoryManager subclass whose acquireExecutionMemory throws an IOException, since TestMemoryManager's is private[memory].
There was a problem hiding this comment.
Done in 4b28a3f1a8f. The catch is now Exception | InternalError, and memoryReservationFailed wraps whatever rethrowIfMustPropagate does not rethrow in a checked SparkException. A new case in the error test has the task's memory manager throw an IOException, through a TaskMemoryManager subclass, and checks that shouldIgnoreCorruptFileException rejects what comes out. The doc and the description name the eviction.
|
|
||
| // A partly filled set of accumulators goes to the queue as this row group's last batch. | ||
| if (currentKeyAccumulators != null) pushAccumulators(); | ||
| if (splicingGivenUp != null) recordBudgetGiveUp(splicingGivenUp); |
There was a problem hiding this comment.
This counts a splicing give-up before phase 2 can still give the filter up, so a row group whose offset index parquet cannot read is counted as one that kept the filter. When phase 2's readFilteredRowGroup throws MissingOffsetIndexException (L577-595), L588 sets filterGivenUp and the row group comes back whole and unchecked, but SPLICING_ON_CAP or SPLICING_ON_MEMORY has already been counted here, and the INFO line ending "The storage filter is still applied" may have gone out for it. StorageFilterMetrics documents those counters as "row groups that kept the filter but read their key columns a second time" (ParquetStorageFilter.scala:55-56), and the PR description says "Each row group counts once, under the last thing given up and what caused it". The same splicing give-up followed by a decoding or evaluation error in phase 1 counts nothing, since those paths return before L817. For example, take the damaged file of "the checked column is false for a row group read without its offset index" (ParquetStorageFilterSuite.scala:2082-2083) and read it with maxSplicedRowGroupBytes=2100b. Each block's 50 scattered even keys pass the cap at survivor 43 (43 x 49 = 2,107 B), while their 2,000 B of ranges fit. So all three blocks count here, block 1 then gives the filter up in phase 2, and budgetGiveUps reads (3, 0, 0, 0) where (2, 0, 0, 0) is right. The rows are right. I traced this by reading the code and did not run it. Could evaluateStorageFilter hand the give-up back, or keep it in a field, so that loadNextRowGroup records it inside if (!filterGivenUp) at L598, with a test over that fixture?
There was a problem hiding this comment.
Done in 4b28a3f1a8f. Phase 1 leaves the give-up in a field, and loadNextRowGroup records it only once phase 2 keeps the filter. A new test reads your example, the damaged file at a cap of 2,100 bytes, and expects (2, 0, 0, 0). It also checks that the row group read whole holds nothing while it is emitted.
| * [[rethrowIfMustPropagate]]. Typed as returning a `RuntimeException` so Java code can write | ||
| * `throw memoryReservationFailed(e)`. | ||
| */ | ||
| def memoryReservationFailed(e: Throwable): RuntimeException = e match { |
There was a problem hiding this comment.
Minor: This copies two cases of rethrowIfMustPropagate (L271-282) instead of calling it, and leaves out its search of the cause chain. A RuntimeException from another consumer's spill() with a fatal error in its cause chain goes out here as SparkException(RuntimeException(...)), and FileScanRDD wraps that in FAILED_READ_FILE (FileDataSourceV2.scala:141-142). So the fatal error sits two levels deeper than when the same spill error comes out of that consumer's own acquisition. At the default spark.executor.killOnFatalError.depth of 5 (Executor.scala:1144 and 1654-1661), a fatal error at depth 4 or 5 of the spill's exception is then missed, and the task fails and is retried on a JVM that ran out of memory instead of the executor exiting. With that internal conf at 2 or 3, one or two wrappers are enough. I found no in-tree spill that builds such a chain, so this is about robustness. Also, the doc's "and anything else, such as the SparkOutOfMemoryError of a failed spill, as it is, as in [[rethrowIfMustPropagate]]" describes input that the only caller never passes, since its catch (RuntimeException | InternalError e) (LateMaterializationParquetRecordReader.java:1052) does not catch a SparkOutOfMemoryError. Could this be rethrowIfMustPropagate(e, fromRead = false) followed by throw new SparkException("A storage filter failed to reserve memory", e)? That keeps both outcomes of my item 2 and the spill-error test, and it fits the wider catch of item 16.
There was a problem hiding this comment.
Done in 4b28a3f1a8f, as you suggested: rethrowIfMustPropagate(e, fromRead = false), then the SparkException. The doc no longer describes input the caller never passes.
| long keyCharge = accountKeys ? bufferedKeyCharge() : 0L; | ||
| boolean denied = !reserveSurvivorMemory(keyCharge + rangeCharge); | ||
| if (denied && keyCharge > 0L) { | ||
| splicingGivenUp = BudgetGiveUp.SPLICING_ON_MEMORY; |
There was a problem hiding this comment.
Minor: Nothing carries a denial over to the next row group: L536 starts each one with spliceCurrentRowGroup = canNarrowRowGroup, and L510 releases the reservation to 0. When the free memory stays between what the ranges need and what the keys need, as in the denial test's memoryTask(105), every later row group of the split repeats the same work. It allocates its accumulator sets (36,864 B per set for a long key at capacity 4096), copies each survivor's key, makes about log2(F / 49) + F / 1 MiB reservations through the executor-wide memory manager for F bytes free, ends in a denied one that runs the task's spill pass, frees it all, and reads the key column again in phase 2. ParquetStorageFilterSuite.scala:2295 pins that repeat with denied == Seq(0L, 2L, 0L, 0L). This is the denial counterpart of my item 9, which went with the spill. Pressure can be transient, so giving splicing up for the rest of the file could cost re-reads that a later grant would have saved. Could a denial make the reader skip splicing for the next row group only, counted under rowGroupsSplicingGivenUpByMemory, while it keeps the filter and still reserves the ranges?
There was a problem hiding this comment.
I'd rather keep each row group deciding on its own. Memory pressure can pass between two row groups, and skipping splicing then costs a second read of the key column that the memory would have saved. What a denied row group does in vain, copying its survivors and a few reservations, is small next to that read. So I'll leave this one as it is.
| TaskContext context = TaskContext.get(); | ||
| TaskMemoryManager taskMemoryManager = context == null ? null : context.taskMemoryManager(); | ||
| if (taskMemoryManager != null) { | ||
| survivorMemory = new SurvivorMemory(taskMemoryManager); |
There was a problem hiding this comment.
Nit: Each reader creates its own SurvivorMemory here, TaskMemoryManager.acquireExecutionMemory adds it to the task's consumers at its first reservation (TaskMemoryManager.java:256), and only cleanUpAllAllocatedMemory clears that set (TaskMemoryManager.java:916). So a task keeps one per file it reserved for, about 80 B each. Every contended acquisition by any consumer of the task, every page-allocation recovery and every memory-usage snapshot walks them under the task memory manager's lock, although a closed one costs only a getUsed() check. At the default 128 MB / 4 MB packing that is about 33 per scan per task, so it is negligible today. It grows with a lowered openCostInBytes, with a bucketed scan over many files, and with the several readers per task that the description expects once storage filters reach storage-partitioned joins. The round-1 javadoc said "The task's memory manager keeps every consumer until the task ends", and the new one does not. Could the SurvivorMemory javadoc keep that, so that the change for several readers per task can share one consumer per task and scan?
There was a problem hiding this comment.
Done in 4b28a3f1a8f. The SurvivorMemory javadoc says so again.
|
|
||
| // One row group of 400,000 rows of a long key and a string value. Under `k >= 10` its 399,990 | ||
| // survivors fall in one range and buffer 3,599,950 bytes, several steps of the reservation. | ||
| private def oneRowGroupOf400000(dir: File): String = { |
There was a problem hiding this comment.
Nit: "emitting a row group releases its memory in steps" and "the survivor buffer asks for little more memory than it holds" each write this 400,000-row file through repartition(1) and collect about 400,000 (Long, Boolean) rows. In this commit's CI run they are the suite's slowest and fourth-slowest tests, 1.126 s and 0.601 s of its 26.1 s. A wider key would need fewer rows, but it would change the steps the first test pins, and at a few thousand rows the doubling would stop inside the second test's margin, so that test would no longer catch an unclamped ask. Could the second test's 400,000-row case move into the first test, reading the same file twice, so it is written once?
There was a problem hiding this comment.
Done in 4b28a3f1a8f. The step test reads the same file again for the margin check, so it is written once.
| val (rows, held) = readInTask(path, context, offHeap, cap = cap) | ||
| val name = s"off heap $offHeap under a cap of $cap" | ||
| assert(rows == marked(10L until 40L, checked = true), s"$name: got $rows") | ||
| assert(held == expected, s"$name: each batch must hold what is still buffered; got $held") |
There was a problem hiding this comment.
Nit: "each batch must hold what is still buffered" fits round 1's per-batch release, where this assertion expected Seq(130L, 94L, 58L, 220L, 184L, 148L, 112L, 76L) at 0c670c9. Now each batch holds its row group's whole reservation until the next one loads, e.g. 130 at block 0's second batch, which buffers 94. Could the message say something like "each batch must hold its row group's reservation until the next row group loads"?
| // Reads `path` under `k >= 10` in batches of `batchSize` and a cap of `cap`, as a task of | ||
| // `context`. Returns the rows, and what the task holds as each batch is read. The confs are set | ||
| // outside the task, which sees a read-only one. | ||
| private def readInTask( |
There was a problem hiding this comment.
Nit: readInTask sets its three confs with withSQLConf and then calls readChecked inside asTask, which readUnderCap (L203-219) now does through context: Option[TaskContext] = None. Could readChecked take the same parameter, so readInTask passes its confs through readChecked's conf?
There was a problem hiding this comment.
Done in 4b28a3f1a8f. readChecked takes the task, and readInTask passes its confs through conf.
| */ | ||
| private long reservedBytes; | ||
| /** Whether the key values are accounted too, which needs them on heap. */ | ||
| private boolean accountKeys; |
There was a problem hiding this comment.
Nit: accountKeys is MEMORY_MODE == MemoryMode.ON_HEAP wherever it has an effect. Without a task memory manager every use of heldCharge() is already a no-op: reserveSurvivorMemory returns at L1043, and reservedBytes stays 0, so the releases and the trim return at once. L800-802 also rebuild heldCharge() by hand, where keyCharge > 0L is held > rangeCharge, and L805's rangeCharge is heldCharge() once abandonSplicing() has run. Could the field go, with heldCharge() testing MEMORY_MODE and L800-805 reading long held = heldCharge(); boolean denied = !reserveSurvivorMemory(held); if (denied && held > rangeCharge) { ... denied = !reserveSurvivorMemory(heldCharge()); }? A term added to heldCharge() would then also reach the reservation.
| long splicedBytes = 0L; | ||
| long rangeBytes = 0L; | ||
| // The budget weighs both the key values buffered for splicing and the survivors' ranges. | ||
| rangeCharge = 0L; |
There was a problem hiding this comment.
Nit: This store never changes the value. L509 zeroes rangeCharge at the start of every loadNextRowGroup, L527's continue comes before phase 1, the one at L567 is reached only when nothing survived, since a range is charged only for a survivor (L770-771), and a row group whose filter was given up zeroes it at L552 and returns at L615. L545 is the only caller. Could it go, with the comment at L721 moving to cap?
dongjoon's second round. None of it changes a query answer. - A reservation catches any exception, since evicting a cached block to disk inside it can raise an IOException, which ignoreCorruptFiles would take for a corrupt file. memoryReservationFailed now calls rethrowIfMustPropagate and wraps the rest in a checked SparkException. - A splicing give-up is recorded only once phase 2 keeps the filter, so a row group whose offset index parquet cannot read is no longer counted as one that kept it. - accountKeys goes, since heldCharge() can test the memory mode, and phase 1 reserves through heldCharge(). A dead store in phase 1 goes too. - Comments: the SurvivorMemory javadoc says again that the task keeps every consumer until it ends, and the memoryReservationFailed doc names the eviction. - Tests: the denial test checks that every read releases what it reserved, and covers reservations granted in part. The step test and the accounted test pin the exact asks. A new test covers the offset-index give-up after a splicing give-up. The error test covers an IOException from the memory manager. Two cap tests check all four counters. The 400,000-row file is written once, readChecked takes the task, and the test access looks up SurvivorBatch by name again.
|
Thank you for updating, @peter-toth . |
dongjoon-hyun
left a comment
There was a problem hiding this comment.
Thank you for addressing items 16-28, @peter-toth. I reviewed the latest commit, 4b28a3f, and left 15 inline comments, continuing the numbering from items 16-28. I found no path that returns wrong rows or leaves a reservation behind, and CI is green. Here is a summary, ordered by priority.
Before merging: the PR description
LateMaterializationParquetRecordReaderL1054: anErrorother than anInternalError, such as theSparkOutOfMemoryErrorof a failed spill, goes out as it is, while the description says anything else goes out wrapped in a checkedSparkException.LateMaterializationParquetRecordReaderL132: "lets other consumers spill before this one is refused" does not hold for the shuffle writer a storage-filtered scan usually feeds, which refuses a spill triggered by another consumer.
Optional: tests
LateMaterializationParquetRecordReaderL555: droppingrangeCharge = 0L;passes the suite, and keeps up to the cap reserved through a row group read without the filter.LateMaterializationParquetRecordReaderL1104: nothing pins theON_HEAPmode, sinceTestMemoryManagerignores the mode.LateMaterializationParquetRecordReaderL804: two one-line mutations of the denial block pass the suite.ParquetStorageFilterSuiteL2424: the error test passes with a two-casememoryReservationFailed, so item 18 is not pinned.
Optional: docs and comments
LateMaterializationParquetRecordReaderL600: "reports nothing" is stale, and "each once" is at most once.LateMaterializationParquetRecordReaderL392: the next batch's trim usually releases nothing.ParquetStorageFilterSuiteL2461: the comment mixes the ask with the reservation it reaches.LateMaterializationParquetRecordReaderL226: the field is also null in two more cases.LateMaterializationParquetRecordReaderL1093: up to one batch of key vectors per key column is held beyond the reservation.
Optional: cleanup
LateMaterializationParquetRecordReaderL792: the cap's splicing give-up andabandonSplicing()could share one guard.LateMaterializationParquetRecordReaderL287:close()can release in two lock round trips.ParquetStorageFilterSuiteL2102: the new test rebuilds the fixture of the test above it.ParquetStorageFilterSuiteL215: thecontext matchis repeated inreadChecked.
+1, LGTM. CI is green on 4b28a3f. Items 29 and 30 are about the PR description, which becomes the commit message, so could you update it before merging? The matching code comments and items 31-43 are optional; of those, 31 and 32 pin the most for their cost.
| try { | ||
| granted = survivorMemory.acquireMemory(ask); | ||
| } catch (Exception | InternalError e) { | ||
| // Another consumer's spill and the eviction of cached blocks run inside, so this can raise |
There was a problem hiding this comment.
Minor: This catches Exception | InternalError, so any other Error raised inside acquireMemory goes out as it is. The one a reservation can meet is the SparkOutOfMemoryError (SPILL_OUT_OF_MEMORY) that TaskMemoryManager.spillConsumer makes of another consumer's spill IOException, e.g. on a full local disk (TaskMemoryManager.java:331-340). That outcome is right: shouldIgnoreCorruptFileException does not take it, and the task fails as it would from any other consumer's request. But the PR description, which becomes the commit message, says that "a fatal error, or one raised by a pending task kill, goes out as the reader's other error paths send it" and that "anything else goes out wrapped in a checked SparkException". This error is neither: Executor.isFatalError does not count it as fatal (Executor.scala:1659), and nothing wraps it. 778c149's scaladoc said so, and as my item 18 noted, memoryReservationFailed never receives it, so this catch is the place to say it. Could this comment add something like "An Error other than an InternalError, such as the SparkOutOfMemoryError of a failed spill, goes out as it is, since FileScanRDD cannot take it for a corrupt file.", and the description's Errors bullet get a matching sub-bullet before merging?
There was a problem hiding this comment.
Done in 09b8b2186e3. The comment at the catch says so, and the description's Errors bullet has the matching sub-bullet.
|
|
||
| /** | ||
| * The most the survivor buffer reserves beyond what it holds, see | ||
| * {@link #reserveSurvivorMemory}. The task's memory manager spills other consumers to grant a |
There was a problem hiding this comment.
Minor: This javadoc, and the PR description's "No spill" bullet ("Accounting with denial already lets other consumers spill before this one is refused"), hold only for consumers that yield to another consumer's request, and the one a storage-filtered scan usually shares its task with does not. Storage filters are runtime bloom filters, which InjectRuntimeFilter adds only for a join it expects to shuffle (InjectRuntimeFilter.scala:432-446), so the scan's task usually feeds a shuffle write, which past 200 partitions is an UnsafeShuffleWriter. Its ShuffleExternalSorter returns 0 for any other consumer's trigger (ShuffleExternalSorter.java:302), as does an UnsafeExternalSorter that is still being fed (UnsafeExternalSorter.java:227-231) or a BytesToBytesMap that is still being built (BytesToBytesMap.java:1061-1064). TaskMemoryManager then drops it (TaskMemoryManager.java:303), and the reservation gets only the free part of the task's share, the case in my item 6. Only spillable collections under on-heap Tungsten, a sorter being read, or a map with a destructive iterator yield. The behavior itself is settled by items 6 and 19, but since the description becomes the commit message, could it say something like "lets other consumers that yield to another consumer's request, such as a sorter being read, spill before this one is refused", and this javadoc "may spill other consumers, or evict cached blocks, to grant a request in full"?
There was a problem hiding this comment.
Done in 09b8b2186e3, with your wording in this javadoc and in the description's No spill bullet.
| boolean filterGivenUp = survivors == null; | ||
| if (filterGivenUp) abandonSplicing(); | ||
| if (filterGivenUp) { | ||
| rangeCharge = 0L; |
There was a problem hiding this comment.
Nit: Nothing pins this reset, the phase-1 twin of L592, which "a row group whose filter phase 2 gives up does not count as giving splicing up" pins through its held. Every test whose phase 1 gives the filter up after reserving runs without a task memory manager, and the denials in "memory the task's memory manager denies gives splicing up, and then the filter" give it up before anything is reserved. Without this line, abandonSplicing() at L556 and the release at L560 stop at heldCharge(), which still counts the ranges and is above the reservation, so a row group whose ranges pass the cap keeps up to the cap (64 MB by default) reserved through its plain read, until the next row group loads. For example, twoRowGroupsOf20 under an even-key filter at a cap of 300 bytes reaches 300 bytes reserved (asks of 49, 49, 98 and 104), gives splicing up at survivor 7 (back to 280) and the filter at survivor 8, with 280 still reserved; under memoryTask(100L) the filter goes with 98 reserved. Could a test read both in a memory task and expect every row unchecked, a held of 0 at every batch, and give-ups of (0, 0, 2, 0) and (0, 0, 0, 2)? A helper that both give-up sites call (rangeCharge = 0L; abandonSplicing(); here and at L591-593) would also keep a future give-up site from forgetting the reset.
There was a problem hiding this comment.
Done in 09b8b2186e3. Both give-up sites call a new abandonFilter(), which drops the ranges' charge. The new test "a row group whose filter phase 1 gives up holds no memory while it is read whole" reads your two cases. It expects (0, 0, 2, 0) and (0, 0, 0, 2), every row unchecked, and nothing held at any batch. Dropping the reset now fails it, and the phase-2 test of item 17.
| */ | ||
| private static final class SurvivorMemory extends MemoryConsumer { | ||
| SurvivorMemory(TaskMemoryManager taskMemoryManager) { | ||
| super(taskMemoryManager, MemoryMode.ON_HEAP); |
There was a problem hiding this comment.
Nit: Nothing pins this ON_HEAP for an off-heap reader. TestMemoryManager grants and releases from one pool whatever the mode (TestMemoryManager.scala:37-80), and the off-heap cases have no other consumer, so passing the reader's MEMORY_MODE here should pass the whole suite. On an executor, that would charge the ranges, which are on heap, to the off-heap pool, which the description's "Off heap" bullet says this must not do. Where that pool is empty, e.g. with spark.sql.columnVector.offheap.enabled set while spark.memory.offHeap.size stays 0, every reservation would get 0, and every row group with a survivor would give the filter up. ObservedTaskMemoryManager already receives the consumer. Could it pass consumer.getMode to onAcquire, so that the off-heap case of "the survivor buffer is accounted to the task's execution memory" expects ON_HEAP for every ask?
There was a problem hiding this comment.
Done in 09b8b2186e3. ObservedTaskMemoryManager passes consumer.getMode, and each case of the accounted test expects only ON_HEAP asks. For the record, "off-heap column vectors through the planner" already failed under that mutation at 4b28a3f. The real memory manager has no off-heap pool there, so the reader gave the filter up and returned 100 rows instead of 51. The new check names the cause.
| // key values in it, giving splicing up frees nothing, so the ranges are denied too. | ||
| long held = heldCharge(); | ||
| boolean denied = !reserveSurvivorMemory(held); | ||
| if (denied && held > rangeCharge) { |
There was a problem hiding this comment.
Nit: Nothing pins this guard, or the result of the retry at L807: replacing held > rangeCharge with true, or L807 with denied = false, should pass the whole suite. The only denial without key values that the suite reaches is the off-heap rows(0L), which checks the rows only; without the guard it makes a second 40-byte acquire, is denied again, and ends the same way. With L807 mutated, rows(0L) and bytes(0L) keep the filter past survivor 1, and survivor 2, in the same range, is denied without key values and gives it up one survivor later, with the same rows, the same (0, 0, 0, 2) and the same log line. In production the first would repeat the acquire and its spill pass for every denied row group off heap, which my item 6 asked to avoid, and the second would leave a row group whose last survivor is denied keeping the filter with its last range unreserved, counted as a splicing give-up. Could a test record the asks of an off-heap read under memoryTask(0L), expecting one 40-byte ask per row group, and read under keyAtLeast(19L) with nothing free, whose first row group has a single survivor, expecting (0, 0, 0, 2) where the L807 mutation gives (0, 1, 0, 1)?
There was a problem hiding this comment.
Done in 09b8b2186e3. The denial test now expects one 40-byte ask per row group off heap under memoryTask(0L), and (0, 0, 0, 2) under keyAtLeast(19L) with nothing free. Each of the two mutations fails it.
| } | ||
|
|
||
| /** | ||
| * The survivor buffer's account with the task's memory manager, so other consumers see what it |
There was a problem hiding this comment.
Nit: The charge grows per row (L895), but each set of survivor vectors is allocated a whole batch at a time (L863-868), e.g. 4096 x 9 = 36,864 bytes for a long key. So the set being filled, and while emitting the last partly filled one, holds up to one batch per key column beyond the reservation; each row group's first ask is 49 bytes. That is bounded, like the unaccounted keyScratchVectors, and the conf doc already calls the charge an estimate, so no code change is needed. Could this javadoc say so, since "so other consumers see what it holds" reads as exact?
There was a problem hiding this comment.
Done in 09b8b2186e3. The javadoc says that up to a batch per key column is held beyond the charge.
| if (splicedBytes + rangeBytes > cap) { | ||
| if (bufferedKeyCharge() + rangeCharge > cap) { | ||
| // The buffer goes first, which is a no-op once splicing is given up. | ||
| if (spliceCurrentRowGroup) splicingGiveUp = BudgetGiveUp.SPLICING_ON_CAP; |
There was a problem hiding this comment.
Nit: Once splicing is off, bufferedKeyCharge() is 0, so this block is entered only when the ranges alone pass the cap, and it returns right after. The unguarded abandonSplicing() below is then a no-op only because the reservation never passes the cap, now that it also releases memory. Could the two share the guard, if (spliceCurrentRowGroup) { splicingGiveUp = BudgetGiveUp.SPLICING_ON_CAP; abandonSplicing(); }, as in the denial block below, and the "no-op" clause go?
| checkedVector = null; | ||
| } | ||
| } finally { | ||
| releaseSurvivorMemoryTo(0L); |
There was a problem hiding this comment.
Nit: When close() runs while a spliced on-heap row group is still reserved, abandonSplicing() (L1014) first releases down to the ranges and this line then releases them: two trips through the executor-wide memory manager lock, each ending in notifyAll(). That happens for a reader closed early, as in the accounted test's early close (90, then 40 bytes), at the end of a file in which the filter excluded no row (nextBatch() then returns at VectorizedParquetRecordReader.java:404 before loading again), and after a phase-1 error. When the filter excluded any row, L513 has already released everything. Could close() zero rangeCharge before closeSplicingState(), leaving this line as the safety net?
There was a problem hiding this comment.
Done in 09b8b2186e3. close() zeroes rangeCharge first, so abandonSplicing() releases everything in one trip.
| } | ||
| } | ||
|
|
||
| test("a row group whose filter phase 2 gives up does not count as giving splicing up") { |
There was a problem hiding this comment.
Nit: This rebuilds the fixture and the expected rows of the test above it: blocks (L2109 and L2077), the schema (L2110 and L2078), the even-key filter (L2111-2112 and L2079-2080), the damaged file (L2113-2114 and L2089-2090), and the expected rows (L2121-2125 against L2081 and L2095-2098). Its 2,107-byte arithmetic and its 13, 25 and 13 batches hold only for that layout. Could the two share a helper beside twoRowGroupsOf20, as item 12 did for the 40-row fixture?
There was a problem hiding this comment.
Done in 09b8b2186e3. Both tests use damagedMiddleRowGroup, beside twoRowGroupsOf20, over threeRowGroupsOf100 and evenKey.
| readCounting(path, formatReader(schema, Nil, storageFilters, countingHadoopConf(), metrics)) | ||
| def read(): (Int, Long) = readCounting( | ||
| path, formatReader(schema, Nil, storageFilters, countingHadoopConf(), metrics)) | ||
| context match { |
There was a problem hiding this comment.
Nit: readChecked ends in the same context match (L2014-2017). Could both be context.fold(read())(asTask(_)(read())), or call one helper beside asTask that takes an Option[TaskContext]?
There was a problem hiding this comment.
Done in 09b8b2186e3. Both are context.fold(read())(asTask(_)(read())) now.
|
Thank you for the approval, @dongjoon-hyun. Items 29-43 are done in 09b8b2186e3, and the description is updated for 29, 30 and 35. |
|
Merge Summary:
Posted by |
|
Thank you @dongjoon-hyun and @viirya for the review. |
What changes were proposed in this pull request?
The late-materialization Parquet reader (SPARK-59620) buffers a row group's surviving key values and row ranges before it emits that row group, up to
spark.sql.parquet.storageFilterPushdown.maxSplicedRowGroupBytesper reader. Today the buffer is outside Spark's memory manager. This PR accounts it to the task's execution memory through aMemoryConsumer. It was on the follow-up list of #58895, and viirya suggested it there after the merge (comment).Reserving: phase 1 reserves the buffer as it grows.
Releasing: as batches are emitted, the reservation steps down once it is 1 MiB past what is still buffered. The rest goes when the next row group loads, or at close. So emitting a row group takes the memory manager's lock a few times, not once per batch.
No spill: the consumer's
spill()frees nothing.Off heap: the consumer is
ON_HEAPwhatever the reader's memory mode, asWindowSegmentTree's spiller is (SPARK-56546). Off-heap column vectors allocate native memory outside the Tungsten off-heap pool, so anOFF_HEAPconsumer would charge that pool for memory it never held. With off-heap vectors only the row ranges are accounted.Errors: the task's memory manager runs other consumers' spills inside a reservation, and can evict cached blocks to disk there. So a reservation can raise anything, an
IOExceptionincluded. The reader rethrows it in a formFileScanRDDcannot take for a corrupt or missing file:InternalErrorin anUnknownError;Error, such as theSparkOutOfMemoryErrorof a failed spill, goes out as it is;SparkException.Metrics: four new scan metrics count the row groups the budget limited. Each row group counts at most once, under the last thing given up and what caused it:
row groups with key columns read twice by storage filter (buffer cap)and(memory denied): splicing was given up and the filter kept;row groups read without storage filter (buffer cap)and(memory denied): the filter was given up.The first of each kind per split is also logged, at INFO.
Why are the changes needed?
Each reader buffers up to 64 MB by default, which the memory manager cannot see. Today a task holds one per scan at a time, so an executor holds about one per running task. Under a sorted merge over many files, as storage-partitioned joins do once storage filters reach them, one task would hold many at once. Accounted, other consumers spill earlier, and a reader that is denied memory gives the buffer up instead. The new metrics show when a scan loses splicing or the filter, and whether the cap or memory pressure caused it.
Does this PR introduce any user-facing change?
No. The feature is unreleased and off by default. With it on:
How was this patch tested?
New tests in
ParquetStorageFilterSuite, most under a task whose memory manager the test controls:RuntimeExceptionor anInternalErrorfrom another consumer's spill, or anIOExceptionfrom the memory manager, fails the read with a checkedSparkExceptionor anUnknownError.ignoreCorruptFilesswallows none of them. A fatal error nested in one goes out as itself.Each was checked by mutation. These all make at least one of them fail:
ParquetStorageFilterSuitepasses.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code with Claude Opus 5.5