Repository navigation
perf(datanode): decode tree-model TsFiles straight into tablets in the Scan parser - #19536
luoluoyuyu wants to merge 5 commits into
Conversation
…e Scan parser The tree-model Scan parser (TsFileInsertionEventScanParser) used to turn every decoded page into a BatchData and then copy it into the Tablet cell by cell: for an aligned device each row allocated a TsPrimitiveType[6] plus one boxed value per cell, and every cell went through a TypeService dispatch and two array writes (BatchData first, Tablet second). Scanning a 10 GiB aligned tree-model TsFile took 84-106 s. This commit makes the direct-tablet reader shared by both models and uses it from the tree Scan parser: - ChunkDirectTabletReader (moved out of the table parser) is now model agnostic: deviceIdSize 0 and no tag columns for the tree model, and a RowRetention policy that keeps all-null rows for a table but drops the rows without a single surviving cell for the tree model, which is the semantics of the BatchData path. It also reports the parsed/expected point counts of each page for the pipe metrics. - SeriesChunkDirectTabletReader decodes a non-aligned series chunk, whose page is [varint time length][times][values] with neither a null bitmap nor a value count, straight into the single value column of the tablet. The time decoder comes from the TSFile configuration, not from the value chunk header, which is what a non-aligned page uses. - The Scan parser now drives pages and tablets: prepareNextChunkReader() skips chunks without a row in range, loadNextPageWithMemory() reserves the page bytes from a header peek before decompressing so that an out-of-memory retry can reserve the same page again, and recordPagePointCounts() reports each page once. The split, the delete intervals and the modifications are applied while the page is decoded, and the reader of the current chunk owns its buffers. - Delete SinglePageWholeChunkReader, AlignedSinglePageWholeChunkReader, MemoryControlledChunkReader and EstimatedMemoryChunkReader. The page budget is now the sum of the largest uncompressed page of every column, estimated without decompressing anything. The table parser is behaviourally unchanged: it uses the shared reader with KEEP_ALL_NULL_ROWS and the tag columns. Result (local benchmark: 1 device x 6 series, 8192-row chunk groups, PLAIN+LZ4, 2 runs after a warm read, -Xmx4g, best of 2): | 10 GiB file | before | after | speedup | | aligned dense | 84.3 s, 128 MB/s | 22.2 s, 484 MB/s | 3.8x | | aligned sparse (30% null) | 106.0 s, 102 MB/s | 21.7 s, 495 MB/s | 4.9x | | non-aligned dense | 70.7 s, 152 MB/s | 23.8 s, 453 MB/s | 3.0x | | non-aligned sparse (30% gaps) | 74.9 s, 144 MB/s | 27.7 s, 389 MB/s | 2.7x | The 4 GiB files show the same ratios (aligned 4.5-4.8x, non-aligned 2.8-3.0x). The parsed points are identical before and after for every file (for example 2,812,035,072 for the 10 GiB aligned dense file), and only the packing of rows into tablets differs. The per-tablet cost drops from 0.37-0.38 ms to 0.06-0.08 ms for aligned files and from 0.052 ms to 0.017 ms for non-aligned ones; the old path allocated on the order of 10^9 boxed values and row arrays for the 4 GiB aligned file (338 young GCs against 117). The tree-model Query parser (TsFileInsertionEventQueryParser) is not touched; it still reads through TsFileReader/QueryDataSet. Tests: mvn -o -pl iotdb-core/datanode -am test with TsFileInsertionEventParserTest, TsFileInsertionEventScanParserContextTest, PipeTsFileInsertionEventTest, PipeTabletInsertionEventTest, ChunkDirectTabletReaderDeleteIntervalTest and ChunkDirectTabletReaderTypeTest: 76 tests, 0 failures, 0 errors, 3 skipped. test-compile runs spotless and checkstyle and passes.
| // modifications of the page from its first row, so the cursors they leave must not be seen by | ||
| // the decoding pass that follows. | ||
| resetScanCursors(); | ||
| rowDropped = |
There was a problem hiding this comment.
critical iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReader.java:396 — Retention pass empties ModsInfo, so cells deleted by .mods are emitted as present values
computeRowDropped() walks the page via ModsOperationUtil.isDelete, which calls clearModsAndReset and permanently empties that column's mods list once a row time passes the last mod. resetScanCursors() only rewinds the index, so the later decode pass (line 666) sees no mods and leaves cells deleted by .mods marked present. Trigger: aligned tree device whose mod range ends inside a page that also holds later rows.
Fix: Compute a per-column deleted mask (or keep an immutable copy of the mods) during the retention pass, so fillTablet's null marking does not re-walk a ModsInfo already emptied by that pass.
| } | ||
|
|
||
| if (tablet != null && tablet.getRowSize() == tablet.getMaxRowNumber()) { | ||
| if (!loadNextPageWithMemory(reader)) { |
There was a problem hiding this comment.
major iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java:507 — OOM while reserving the next page of a chunk makes the retry skip the rest of the chunk
The reservation at line 507 runs after the current page is fully consumed and can throw PipeRuntimeOutOfMemoryCriticalException, leaving reader.hasCurrentRow() false with a partial tablet pending. The retried getNextTablet() restores the tablet but skips the while (reader.hasCurrentRow()) loop, so line 519 calls prepareNextChunkReader(), releasing the reader and advancing to the next chunk: all remaining pages of the chunk are dropped.
Fix: On retry with a pending tablet, load the reserved page first (or gate the line 519 prepareNextChunkReader() call on the chunk's pages being exhausted) so the rest of the chunk is parsed before the reader is released.
| : pendingAlignedChunkGroup.pageMemoryUsageEstimator; | ||
| return estimator.calculateMaxPageEstimatedMemoryUsageInBytesWithValueChunk(valueChunk.chunk); | ||
| final CachedAlignedValueChunk valueChunk) { | ||
| long bytes = ChunkDirectTabletReader.estimatePageBytes(timeChunkList.get(timeChunkIndex)); |
There was a problem hiding this comment.
minor iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java:1210 — Quadratic aligned page memory estimation reintroduced for wide devices
estimateAlignedPageBytes re-walks the page headers of the time chunk and of every already-cached value chunk on each call, and it is called once per cached value chunk (line 1064), so an aligned group of C columns costs O(C^2) estimatePageBytes calls. The incremental PageMemoryUsageEstimator deleted here was added by 8a8a6da to remove exactly this quadratic cost.
Fix: Keep the running sum of per-chunk max page bytes in PendingAlignedChunkGroup (updated when a value chunk is cached) and add only the candidate chunk's estimate, as the removed estimator did.
| if (state.empty) { | ||
| return false; | ||
| } | ||
| if (state.hasNulls && !AlignedValuePage.isValuePresent(state.nullBitmap, row)) { |
There was a problem hiding this comment.
minor iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReader.java:519 — Retention pass ignores that a value page may hold fewer values than the time page
cellSurvives (line 519) and countPagePoints index the null bitmap with the time-page row index, but AlignedValuePage.valueCount may be smaller than pageRowCount (see its doc and the decodable < count handling in fillTabletInBulk). For rows >= valueCount this reads past the bitmap (ArrayIndexOutOfBoundsException on a page sized exactly) or a stale bit, so rows without cells are kept.
Fix: Treat row >= state.valueCount as absent before calling isValuePresent, and bound the countPagePoints loop by state.valueCount, as fillTabletInBulk already does.
|
Independent review summary — reviewed head I confirmed the four actionable findings already present in the inline threads and found no additional distinct issue:
Both Ubuntu and Windows DataNode unit-test jobs fail in |
ChunkDirectTabletReader (aligned chunk group) and SeriesChunkDirectTabletReader (non-aligned series chunk) duplicated the same page loop: decode the time page, clip it to [startTime, endTime], drop the rows that do not survive, and copy the kept rows into the tablet one segment at a time. The two also duplicated the page header read, decompression, page size estimation and point counting. Extract that skeleton into AbstractDirectTabletReader and PageIo, and leave the subclasses only with what really differs: - AbstractDirectTabletReader: times[], page cursor, binary-search clip, finishPageLoad(), the segment fill loop, the row-drop mask computation and the per-column point counts. The model-specific behaviour is reduced to four hooks: rowSurvives/mayDropRows (retention), fillSegment/skipSegment (decode), resetScanCursors (delete intervals and modifications) and isCellPresent/isCellDeleted (counts). - PageIo: read a page header (single-page chunks keep their statistics in the chunk statistics), decide whether a page overlaps the parsed range, decompress a page, skip a page body, and estimate the memory of the pages of a chunk. - ChunkDirectTabletReader keeps the aligned layout: time page and value pages read in lockstep, [int size][bitmap][values] value pages, tag columns and the table/tree row retention policy. - SeriesChunkDirectTabletReader keeps the non-aligned layout: one page body with [varint time length][times][values], the configured time encoder and points deleted by modifications or delete intervals. No behaviour change: the same rows, timestamps, values, null marks and point counts are emitted, and the same tests pass. The 4 GiB benchmark is unchanged within noise (aligned dense 547.7 MB/s against 554.7 MB/s, non-aligned dense 440.5 MB/s against 419.9 MB/s). The duplicated lines move from the two readers (984 + 413 lines before) into 324 lines of base class and 145 lines of PageIo, and the readers shrink to 700 and 230 lines.
|
Added a second, pure-refactor commit ( What was extracted
What stays in the subclasses
Size The duplicated lines moved out of the readers: 984 + 413 lines before, now 324 (base) + 145 ( No behaviour change Same 76 tests pass (0 failures, 3 skipped). The 4 GiB benchmark is unchanged within noise: aligned dense 547.7 MB/s vs 554.7 MB/s before the refactor, non-aligned dense 440.5 MB/s vs 419.9 MB/s. |
| columnKinds[i].skip(state, Math.min(count, state.valuesLeft())); | ||
| private boolean anyValuePageHasNulls() { | ||
| for (final AlignedValuePage state : pageStates) { | ||
| if (!state.empty && state.hasNulls) { |
There was a problem hiding this comment.
minor iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/ChunkDirectTabletReader.java:408 — mayDropRows ignores all-empty value pages, so all-null rows are kept
Under DROP_ROWS_WITHOUT_KEPT_CELL, mayDropRows() returns false when every value page of the current page is empty (uncompressedSize 0, which loadNextPage treats as "every cell null") and there are no mods/time deletions, because anyValuePageHasNulls() skips state.empty states. computeRowDropped() never runs, so the page's rows are emitted with all cells null instead of being dropped, unlike the removed BatchData path (e.g. compaction-written empty value pages).
Fix: Return true from mayDropRows() when the page has no non-empty value page (every pageState is empty), so the retention pass drops those rows.
There was a problem hiding this comment.
Fixed in 69bce4a: mayDropRows() now also returns true when every value page of the page is empty, so a tree-model page whose cells are all null is dropped like the BatchData path did (a table still keeps those rows).
| resetScanCursors(); | ||
| rowDropped = mayDropRows() ? computeRowDropped() : null; | ||
| if (trackPointCounts) { | ||
| countPagePoints(); |
There was a problem hiding this comment.
minor iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/util/tablet/AbstractDirectTabletReader.java:150 — Point-count pass reuses mods cursors advanced by the retention pass
finishPageLoad() runs computeRowDropped() then countPagePoints() without resetting the forward-only mods/delete-interval cursors. Evaluating the page's later rows moves a column's mods cursor past its earlier ranges; countPagePoints then reads the page's earlier rows from that advanced cursor, so isCellDeleted() misses those deletions and expectedCounts (exposed by getExpectedPointCounts) is over-counted. Trigger: a page with more than one mod range whose last row is still inside the last range.
Fix: Call resetScanCursors() before countPagePoints(), or compute the per-column deleted mask once in the retention pass and reuse it for the point counts.
There was a problem hiding this comment.
Already fixed in 989c5bf: finishPageLoad() calls resetScanCursors() before countPagePoints(), so the counts do not read through cursors advanced by the retention pass.
…state of the direct readers Address the review of the direct tablet readers: - ModsOperationUtil.isDelete used to clear a column's modification list when the cursor ran past the last mod. The reader walks the same page several times (row retention, point counts, decode), so a later pass saw no modifications and emitted cells deleted by .mods as present values. Keep the list instead and move the cursor past the end: the later lookups stay O(1), and a reset makes the same modifications visible again. finishPageLoad() now rewinds the cursors before the point counts as well, because the retention pass leaves them at the end of the page. - getNextTablet() treated "the reader has no current row" as "the chunk is exhausted". After an out-of-memory error while reserving the next page, the retried call restored the pending tablet but skipped the fill loop and released the reader, dropping the rest of the chunk. The loop now loads the reserved page first and only then decides that the chunk is over. - A value page may hold fewer values than the time page: cellSurvives and the point counts indexed its null bitmap with a row index beyond its value count. Treat the rows behind valueCount as absent, as the fill already does. - The aligned page budget was recomputed by walking the headers of every cached chunk for each candidate value chunk, which is quadratic for a wide device. PendingAlignedChunkGroup now keeps the running sum of the largest page of its columns, and a candidate adds only its own estimate. The ModsOperationUtilTest expectations for the list being cleared are updated to the retained-list semantics. The load converter regression (testModifiedAlignedScanVerifiesPointCountsAboveLongCacheBoundary) now passes: 199 points for the modified series and 200 for the other one, with a SUCCESS status. Tests: 127 tests, 0 failures, 0 errors, 3 skipped (the converter visitor, the modifications util, the parser, the scan parser, the pipe events and the reader tests). The 4 GiB aligned dense benchmark stays at 510 MB/s.
|
Fixed the four review findings in 1. .mods deletions were lost (critical). 2. OOM retry skipped the rest of the chunk (major). 3. Shorter value pages indexed past their bitmap (minor). 4. Quadratic aligned page estimate (minor). Validation: 127 tests, 0 failures, 0 errors, 3 skipped (converter visitor, modifications util, parser, scan parser, pipe events, reader tests); the 4 GiB aligned dense benchmark stays at 510 MB/s. The three earlier perf/refactor commits are unchanged. |
| if (!data.hasCurrent()) { | ||
| // Switch chunk reader iff the current chunk is all consumed. The next chunk may have another | ||
| // measurement set, so it can never continue the tablet that is returned here. | ||
| if (!reader.hasCurrentRow()) { |
There was a problem hiding this comment.
critical iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java:522 — Tablet filled exactly at a page boundary of a multi-page chunk drops the rest of the chunk
The loop breaks at line 511 when the tablet is full. fillTablet consumes the whole page when maxRows >= remainingRows, so at a page boundary hasCurrentRow() is false while reader.hasNextPage() is still true. Line 522 then calls prepareNextChunkReader(), whose moveToNextChunkReader() releases the reader and advances the file position, silently discarding the remaining pages of the chunk (data loss). Trigger: a multi-page chunk whose page has exactly the tablet's maxRowNumber rows, e.g. a 2048-row page with the default pipeDataStructureTabletRowSize=2048, where calculateTabletRowCountAndMemory caps maxRowNumber at 2048.
Fix: Gate line 522 on the chunk being exhausted: if (!reader.hasCurrentRow() && !reader.hasNextPage()), so remaining pages are loaded/parsed before the reader is released (as the table parser does via loadNextPage before switching chunks).
There was a problem hiding this comment.
Fixed in 69bce4a: getNextTablet() now switches chunks only when the reader has no current row AND no page left, so the next page of the same chunk is loaded before the reader is released. Added TreeScanPageBoundaryTest (a 3-page chunk with 2048-row pages and 2048-row tablets): it yielded 2048 of 6144 points without the gate and all 6144 with it.
…s at a page boundary getNextTablet() switched chunks whenever the reader had no current row. A tablet that becomes full exactly at the end of a page of a multi-page chunk leaves the next page of that same chunk unread, so the chunk was released and the remaining pages were silently dropped. The chunk is now considered over only when it has no page left either, so the next call loads the next page before the reader is released. Also drop the all-null rows of a page whose value pages are all empty: the retention pass used to skip such pages (anyValuePageHasNulls ignores empty states), so the tree model kept rows that the BatchData path dropped. The new TreeScanPageBoundaryTest writes a 3-page chunk with 2048-row pages and the default 2048-row tablets; it returns 2048 of 6144 points without the gate and all 6144 with it. The modifications util, the converter visitor, the parser, the scan parser, the pipe events and the reader tests pass: 128 tests, 0 failures, 0 errors, 3 skipped.
…t does markModsProcessed() replaces clearModsAndReset(), which no longer clears anything: it moves the forward cursor past the last modification and keeps the list. The stale "clear the mods list and reset the index" documentation that was left in front of sortAndMergeByTime() is removed, and the two call sites and their comments describe the cursor advance instead.
| */ | ||
| private boolean loadNextPageWithMemory(final TabletPageReader pageReader) throws IOException { | ||
| while (pageReader.hasNextPage()) { | ||
| resizePageDataMemoryIfNeeded(pageReader.peekNextPageBytes()); |
There was a problem hiding this comment.
minor iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/event/common/tsfile/parser/scan/TsFileInsertionEventScanParser.java:620 — Page memory reservation uses the size of a page that loadNextPage may skip
loadNextPageWithMemory reserves peekNextPageBytes() (the immediate next page group) then calls loadNextPage(), which internally skips out-of-range / fully-deleted pages (isTimePageNeeded false, clipPageToRange false) and can decompress a later, larger page in the same call. The reserved bytes therefore do not match the page actually decompressed (e.g. a small pruned page followed by a dense in-range page), so allocatedMemoryBlockForBatchData under-accounts the pipe's page memory. The removed MemoryControlledChunkReader reserved a suffix-max estimate that covered skipped pages, and useNextPendingAlignedChunk no longer pre-reserves.
Fix: Make peekNextPageBytes return the max uncompressed page size over the remaining pages, or reserve the exact size of the page inside loadNextPage at the point it decompresses.
What this PR does
The tree-model Pipe Scan parser (
TsFileInsertionEventScanParser) used to turn every decoded page into aBatchDataand then copy it into theTabletcell by cell. For an aligned device every row allocated aTsPrimitiveType[6]plus one boxed value per cell, and every cell went through aTypeServicedispatch and two array writes (BatchDatafirst,Tabletsecond). Scanning a 10 GiB aligned tree-model TsFile took 84–106 s.This PR makes the direct-tablet reader that the table parser already uses (
TableChunkDirectTabletReader, merged in #19459) shared by both models, and switches the tree Scan parser to it:ChunkDirectTabletReader(moved toparser/util/tablet/) is now model-agnostic:deviceIdSize = 0and no tag columns for the tree model;RowRetentionpolicy:KEEP_ALL_NULL_ROWSfor a table,DROP_ROWS_WITHOUT_KEPT_CELLfor the tree model — a row without a single surviving cell (not null, not deleted by.mods, not in a chunk delete interval) is dropped, which is exactly what the oldBatchDatapath did;SeriesChunkDirectTabletReader(new) decodes a non-aligned series chunk, whose page is[varint time length][times][values]with neither a null bitmap nor a value count, straight into the single value column of the tablet. The time decoder comes fromTSFileConfig(time_encoder), not from the value chunk header, which is what a non-aligned page uses.prepareNextChunkReader()advances over chunks that have no row in[startTime, endTime];loadNextPageWithMemory()reserves the page bytes from a header peek before decompressing, so an out-of-memory retry reserves the same page again instead of skipping or duplicating it;recordPagePointCounts()reports each page exactly once, even when one page is split across several tablets;SinglePageWholeChunkReader,AlignedSinglePageWholeChunkReader,MemoryControlledChunkReaderandEstimatedMemoryChunkReader. The page budget is now the sum of the largest uncompressed page of every column, estimated from headers without decompressing anything.The table parser is behaviourally unchanged: it uses the shared reader with
KEEP_ALL_NULL_ROWSand the tag columns. The tree Query parser (TsFileInsertionEventQueryParser,TsFileReader/QueryDataSet) is not touched by this PR.Example
A tree-model file with one device and 6 series (
s0 INT64,s1 DOUBLE,s2 FLOAT,s3 TEXT,s4 BOOLEAN,s5 INT32), 8192-row chunk groups,PLAIN+LZ4:BatchData; every cell is boxed and dispatched individually.TsNullplaceholders and pays a per-cell dispatch for them, the new one stores a null as one bitmap bit.Result: 10 GiB and 4 GiB tree-model TsFiles
One device × 6 series, 8192-row chunk groups,
PLAIN+LZ4, random values, 2 runs after a warm read,-Xmx4g, single thread, best of 2 runs. "Old" is the Scan parser onmasterbefore this PR; "New" is this PR. Sparse aligned = 30% null cells; sparse non-aligned = 30% missing points per series.Per-tablet cost drops from 0.37–0.38 ms to 0.06–0.08 ms for aligned files (≈5–6x) and from 0.052 ms to 0.017 ms for non-aligned ones (≈3x). The old path allocated on the order of 10^9 boxed values and row arrays for the 4 GiB aligned file (338 young GCs against 117); the new parser is decode-bound (~0.45–0.55 GB/s aligned, ~0.39–0.45 GB/s non-aligned).
The gap is larger for aligned files because the old aligned path boxed a whole row into
TsPrimitiveType[6]; non-aligned files pay for six independent time columns (one per series) in both versions, which is why their absolute throughput is lower.Scope and compatibility
ChunkDirectTabletReaderDeleteIntervalTest,ChunkDirectTabletReaderTypeTest) pass unchanged in intent.BatchDataestimate).db.pipe.event.common.tsfile.parser.util.tablet.Tests
mvn -o -pl iotdb-core/datanode -am test-compile -DskipTestspasses withspotless:checkand checkstyle..modsdeleting cells vs rows, chunk delete intervals, the OOM retry of the chunk header, and the page-memory split.This PR has: