Skip to content

[Bug] Fix SeriesScanUtil/AlignedSeriesScanUtil correctness bugs and remove dead streamingQueryMemChunk config - #19445

Open
JackieTien97 wants to merge 6 commits into
masterfrom
ty/glm-scan-test
Open

JackieTien97 wants to merge 6 commits into
masterfrom
ty/glm-scan-test

Conversation

@JackieTien97

@JackieTien97 JackieTien97 commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #19443

How the Bugs Were Located

  1. Randomized differential fuzzing (SeriesScanUtilFuzzTest): We built an oracle-checked differential test harness driving SeriesScanUtil and AlignedSeriesScanUtil across three data models (non-aligned, aligned tree, aligned table), ascending/descending scans, closed and open files (flushed chunks + memtables + .mods), file/memtable deletions, time/value/IS [NOT] NULL filters, LIMIT/OFFSET, duplicate timestamps within aligned TVLists, and three scan drivers (SeriesScanOperator style, explicit file→chunk→page statistics audit, and SeriesAggregationScanOperator style).
  2. Production-reachability audit & end-to-end IT reproduction (IoTDBSeriesScanDefectIT): From the minimal UT failures surfaced by the fuzzer, we audited each candidate against production code paths:
    • 8 bugs confirmed production-reachable and reproduced end-to-end in both 1C1D (SimpleIT) and 1C3D (ClusterIT) before applying fixes, plus a pre-existing MergeSortMultiAlignedTVListIterator deletion-skipping bug (loop index 4254, replayable via scan_seed=5254), TVList.TVListIterator#reset deleteCursor bug, and altered-column (INT32/BOOLEAN -> STRING) aligned page predicate pushdown bugs caught during review.
    • 3 legacy-path issues confirmed unreachable in production:
      • Multi-memtable priority tie in a single open file (TsFileProcessor.asyncFlush() has 0 callers in src/main since DirectFlushPolicy unconditionally closes the processor).
      • Two non-streaming memchunk issues (IoTDBConfig.streamingQueryMemChunk defaulted to true with no config property or production caller of setStreamingQueryMemChunk).
    • Removed the dead IoTDBConfig.streamingQueryMemChunk flag, ReadOnlyMemChunk#getMemPointIterator, MemPointIterator's dead non-streaming tsBlocks/streamingQueryMemChunk branch, and the unreachable MemChunkReader/MemAlignedChunkReader/MemPageReader/MemAlignedPageReader/PageMetadata/AlignedPageMetadata classes (along with their non-streaming tests).

Root Causes & Solutions (with Examples)

1. Flushing aligned memtable value-column deletions ignored on point-read and multi-TVList paths (plus MergeSortMultiAlignedTVListIterator & TVListIterator#reset)

  • Example: Aligned d1(s0, s1) with closed seq file (2, 200, 99) and flushing unseq memtable (1, 10, 1), (2, 20, 2) (or two sorted TVLists in a flushing memtable). After DELETE FROM root.db.d1.s0 WHERE time >= 1 AND time <= 2 (recorded in modsToMemtable), SELECT s0, s1 FROM root.db.d1 WHERE time <= 2:
    • Before: Returned deleted s0 values (1 -> (10, 1), 2 -> (20, 2)).
    • After: Returns 1 -> (null, 1), 2 -> (null, 2).
  • Merge-sort multi-TVList example (scan_seed=5254): One open file with overlapping TVLists tv0 = (10:1, 20:2, 30:3) and tv1 = (15:4, 25:5) and value deletion [10, 15]:
    • Before: Returned 20 -> 3 instead of 20 -> 2 (and in DESC, 30 -> 171.9 instead of 30 -> 199.4).
    • After: Returns 20 -> 2, 25 -> 5, 30 -> 3 (and exact rows in DESC).
  • Root cause & fix:
    • AlignedTVListIterator.nextTimeValuePair() / currentTimeValuePair() read raw values without checking valueColumnsDeletionList, and AlignedTVListIterator.reset() / TVList.TVListIterator.reset() / batch DESC scans did not reset delete cursors properly.
    • OrderedMultiAlignedTVListIterator.currentIteratorIndex(int) ignored the per-column deletion bitMap.
    • MergeSortMultiAlignedTVListIterator.prepareNext() left skipped iterators in probeIterators after pushing them back to the heap, causing stale time keys to pair with later rows; also added the !tsDataTypeList.isEmpty() guard matching OrderedMultiAlignedTVListIterator.

2. Stale file-unpack horizon after a fully-deleted leading seq file breaks OFFSET/LIMIT pushdown and aggregation statistics

  • Example: Non-aligned d1.s0 with seq File A (1, 1), (2, 2) (fully deleted via mods; kept alive by sibling s1), unseq File U (2, 20), (3, 30), and seq File B (3, 3), (4, 4):
    • SELECT s0 FROM root.db.d1 LIMIT 2 OFFSET 2: Before returned 3 -> 3, 4 -> 4; After returns 4 -> 4.
    • SELECT COUNT(s0), SUM(s0) FROM root.db.d1: Before returned 4, 57.0; After returns 3, 54.0.
  • Root cause & fix: SeriesScanUtil.initFirstChunkMetadata() unpacked overlapped files only up to the first TimeSeriesMetadata's endpoint (2). When File A yielded zero chunks, File U's chunk (ending at 3) became firstChunkMetadata without advancing the unpack horizon to 3, leaving File B unpacked and undetected as overlapping.
  • Fixed in SeriesScanUtil: stabilize the unpack horizon in a loop whenever unpacked metadata/chunks extend past the previous horizon before filtering or returning firstChunkMetadata.

3. Wildcard SELECT * OFFSET/LIMIT over-consumes offset on all-null rows in tree model (while preserving single-sparse-column OFFSET skipping & skipping stats work when OFFSET == 0)

  • Example: Aligned tree d1(s0, s1), page 1 (1, 1, null), (2, null, 2), (3, 3, null), page 2 (4, 4, null), (5, 5, null), after DELETE FROM root.db.d1.s1 WHERE time >= 1 AND time <= 5. SELECT * FROM root.db.d1 LIMIT 5 OFFSET 3:
    • Before: Skipped page 1 consuming 3 rows of offset (including all-null row 2), returning 4 -> (4, null), 5 -> (5, null).
    • After: Returns 5 -> (5, null).
  • Root cause & fix: AlignedSeriesScanUtil.timeAllSelected() returned true whenever queryAllSensors was set, ignoring dropped/deleted columns. Removed the unused queryAllSensors parameter from AlignedSeriesScanUtil, AlignedSeriesScanOperator, and ExternalTsFileSeriesScanUtil and routed file/chunk/page OFFSET skipping through paginationController.hasCurOffset() (checked first to avoid statistics lookups when no offset remains) + canUseTimeStatistics(IMetadata) + current*TimeStatistics().getCount(), preserving metadata-level OFFSET skipping when a single sparse column remains (or when pairwise-disjoint value columns cover all timestamps).

4. Pushed-down value filter bypassed or failing on modified / type-altered aligned pages (while preserving LIMIT fast path for unaffected columns)

  • Deletion example: Aligned d1(s0, s1) with (1, 10, 1), (2, 20, 2), (3, 30, 3) after DELETE FROM root.db.d1.s0 WHERE time = 2. SELECT s0, s1 FROM root.db.d1 WHERE s0 != 173:
    • Before: Returned 1 -> (10, 1), 2 -> (null, 2), 3 -> (30, 3).
    • After: Returns 1 -> (10, 1), 3 -> (30, 3).
  • Altered INT32 -> STRING example: Aligned d(s0 INT32, s1 INT32) with (1, 1, 10), (2, 2, 20), (3, 100, 30) flushed, then ALTER TIMESERIES root.reviewalter.d.s0 SET DATA TYPE STRING. SELECT s0, s1 FROM root.reviewalter.d WHERE s0 != '2':
    • Before: Returned [1, 2, 3] because pre-alteration numeric extrema [1, 100] sort before '2' as strings.
    • After: Returns [1, 3] (and [1, 3, 5] on multi-page chunks in both ASC and DESC), while WHERE s1 > 0 LIMIT 1 retains the early-stop LIMIT fast path.
  • Altered BOOLEAN -> STRING example: Aligned d(s0 BOOLEAN, s1 INT32) with (1, true, 10), (2, false, 20), (3, true, 30) flushed, then ALTER TIMESERIES root.reviewbool.d.s0 SET DATA TYPE STRING. SELECT s0, s1 FROM root.reviewbool.d WHERE s0 != 'false':
    • Before: Failed with 301: BOOLEAN statistics does not support: min (or status 724 on base) because StringFilterOperators.allSatisfy(...) called BooleanStatistics.getMinValue().
    • After: Returns [1, 3] (and [1, 3, 5] on multi-page chunks in both ASC and DESC), while WHERE s1 > 0 LIMIT 1 retains the early-stop LIMIT fast path.
  • Root cause & fix: Upstream AbstractAlignedPageReader evaluates pushDownFilter.allSatisfy(...) against pre-deletion / pre-type-alteration statistics, bypassing row-level filtering when a value deletion turns a referenced column's value into null or throwing / mis-evaluating when a column's stored statistics are invalid for its altered target type (!SchemaUtils.canUseStatisticsAfterAlter(...)).
  • Fixed in SeriesScanUtil.nextPage(): evaluate pushDownFilter.allSatisfy(...) against a stats-aware IMetadata adapter before ever touching raw pageReader statistics. Any filter referencing a type-invalidated column immediately falls back to decode → getTransferedDataTypeTsBlock → applyPushDownFilterAndPagination without calling BooleanStatistics.getMinValue(); deletions only trigger fallback when pre-deletion statistics would falsely return allSatisfy == true (still guarding any type-altered column on compound filters); unaffected columns keep the early-stop LIMIT fast path.

5. COUNT_TIME(*) over-counts dropped/all-null rows on aligned tree devices without regressing compaction or value-only aggregations

  • Examples (SELECT COUNT_TIME(*) FROM root.db.d1):
    • Dropped column: (1, 1, null), (2, null, 2), (3, 3, null) + DELETE TIMESERIES root.db.d1.s1 (and 3-column variant dropping s2): Before 3 → After 2.
    • Full-column deletion: Same data + DELETE FROM root.db.d1.s1 WHERE time >= 1 AND time <= 3: Before 3 → After 2.
    • Whole-row deletion dropping an entire value page: Page 1 (1, null, 1), (2, 2, null), (3, 3, null), Page 2 (4, 4, null) + DELETE FROM root.db.d1.* WHERE time = 1: Before 4 → After 3.
  • Root cause & fix:
    • Value-only aggregations (COUNT(s0), SUM(s1)) and compaction direct-flush remain untouched (no modified propagation in ModificationUtils / DiskAlignedChunkMetadataLoader / DiskAlignedChunkLoader), whereas COUNT_TIME(*) (valueColumnIndex == -1) relies on time-column statistics that include all-null rows.
    • Added canUseCurrent{File,Chunk,Page}TimeStatistics() on SeriesScanUtil / AlignedSeriesScanUtil and routed time-statistics aggregators (TreeAggregator.usesTimeStatistics()) through them in AbstractSeriesAggregationScanOperator.
    • AlignedSeriesScanUtil uses time statistics when metadata.timeAllSelected() holds or pairwise-disjoint non-empty value columns' counts sum to timeStatistics.getCount(), uses the single remaining column's exact statistics when nonNullCount == 1, and falls back to row-level scanning when nonNullCount == 0 (with measurementCount > 0) or multiple sparse columns overlap.

6. Dead IoTDBConfig.streamingQueryMemChunk & non-streaming memchunk reader cleanup

  • Removed IoTDBConfig.streamingQueryMemChunk (isStreamingQueryMemChunk / setStreamingQueryMemChunk), ReadOnlyMemChunk#getMemPointIterator and initChunkMetaFromTvLists(Filter), AlignedReadOnlyMemChunk#initChunkMetaFromTvLists(Filter) and unused valueStatisticsList, MemPointIterator's dead streamingQueryMemChunk/tsBlocks/getBatch/addTsBlock path, the unreachable MemChunkReader/MemAlignedChunkReader/MemPageReader/MemAlignedPageReader/PageMetadata/AlignedPageMetadata classes (and their 4 non-streaming tests), and their exclusive StorageEngineMessages constants. Simplified ResourceByPathUtils, MemChunkLoader, MemAlignedChunkLoader, and SeriesScanUtil to the always-streaming path.

Verification

  • End-to-end IT (IoTDBSeriesScanDefectIT) (using test-only FlushHoldAgent + FlushHoldController to hold the blocker flush on a bounded test-controlled latch at entry of MemTableFlushTask#syncFlushMemTable() on every participating DataNode replica, verifying held == true and waitingTasks >= 1 through DELETE and SELECT, and releasing the latch in finally before joining both flush futures):
    • SimpleIT (1C1D): 12/12 PASS (12.49s).
    • ClusterIT (1C3D): 12/12 PASS (14.83s).
    • Delayed-client stress check (15s pause of the test-client thread immediately after the pre-DELETE assertions): D1a & D1b PASS on both 1C1D and 1C3D.
  • Unit & fuzz tests:
    • BatchedAlignedSeriesReadChunkCompactionTest: 13/13 PASS.
    • SeriesScanUtilDefectTest: 20/20 PASS (covering all 8 defect groups + INT32 -> STRING & BOOLEAN -> STRING altered-type predicate recheck, compound deletion+altered filter, unaffected LIMIT fast path, OFFSET=0 sparse-aligned pagination stats short-circuit, MergeSortMultiAlignedTVListIterator ASC/DESC, TVListIterator#reset, nonNullCount == 0, disjoint-range COUNT_TIME, single-sparse-column OFFSET skipping, unaffected-column LIMIT fast path, and per-column duplicate-timestamp merging).
    • SeriesScanUtilFuzzTest: default (6/6) PASS; individual strict replays (scan_strict=1 scan_flushed=1 scan_subset=1) for seeds 1808, 3895, 5254, 18903, 20612, 21460, 42348, and 46182 all PASS.
    • Related scan/reader/TVList UTs (AlignedTVListIteratorTest, AlignedTVListTest, AlignedSingleColumnSeriesScanLimitOffsetPushDownTest, AlignedSeriesScanLimitOffsetPushDownTest, AlignedSeriesScanPredicatePushDownTest, SeriesScanLimitOffsetPushDownTest, SeriesScanPredicatePushDownTest) — 112/112 PASS in combined datanode run.
  • Checks: mvn spotless:apply, Checkstyle (0 violations), ForbiddenAPIs (0 errors), Apache RAT (0 unapproved), python3 .github/scripts/check-it-selection.py, and both en & -P with-zh-locale builds PASS.

This PR has:

  • been self-reviewed.
  • added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
  • added unit tests or modified existing tests to cover new code paths, ensuring the threshold for code coverage.
  • added integration tests.
  • been tested in a test IoTDB cluster.

Key changed/added classes in this PR
  • AlignedTVList, TVList, MemPointIterator, MultiTVListIterator, MultiAlignedTVListIterator, OrderedMultiAlignedTVListIterator, MergeSortMultiAlignedTVListIterator
  • SeriesScanUtil, AlignedSeriesScanUtil, AlignedSeriesScanOperator, ExternalTsFileSeriesScanUtil
  • TreeAggregator, AbstractSeriesAggregationScanOperator
  • IoTDBConfig, ResourceByPathUtils, MemChunkLoader, MemAlignedChunkLoader, ReadOnlyMemChunk, AlignedReadOnlyMemChunk
  • IoTDBSeriesScanDefectIT, FlushHoldAgent, FlushHoldController, and scanfuzz/* test suite

Cover SeriesScanUtil and AlignedSeriesScanUtil with a differential test
harness in the test sources of datanode:

- SeriesScanUtilFuzzTest generates scenarios (closed and open files,
  flushed chunks, memory tables, deletions, time and value filters, limit
  and offset, ascending and descending) and checks three ways of scanning
  against a brute-force oracle.
- SeriesScanUtilDefectTest pins twelve defects with minimal scenarios and
  asserts the correct result, so its tests fail until each defect is fixed.
- SeriesScanKnownIssues keeps the randomized test green by leaving out the
  scenarios that hit a known defect; scan_strict=1 runs them all the same.

No production code is changed.
…streamingQueryMemChunk

Fixes #19443

- Apply value-column deletions in AlignedTVListIterator point-read paths and OrderedMultiAlignedTVListIterator (and reset delete cursors on reset / DESC scans).
- Advance the file unpack horizon in SeriesScanUtil when leading metadata yields no chunks so overlapping seq/unseq chunks are not skipped by OFFSET/LIMIT or double-counted by aggregation statistics.
- Stop trusting queryAllSensors as timeAllSelected in AlignedSeriesScanUtil for tree-model wildcard OFFSET/LIMIT pushdown.
- Decode modified AbstractAlignedPageReader pages with deletions applied before evaluating pushDownFilter and pagination in SeriesScanUtil.nextPage().
- Gate COUNT_TIME statistics via canUseCurrent*TimeStatistics() and exact single-non-null aligned time statistics without regressing value-only aggregation statistics; propagate modified flags for deleted value columns and dropped value pages in ModificationUtils, DiskAlignedChunkMetadataLoader, and DiskAlignedChunkLoader.
- Remove immutable IoTDBConfig.streamingQueryMemChunk and dead non-streaming branches in ResourceByPathUtils, MemChunkLoader, MemAlignedChunkLoader, and SeriesScanUtil.
- Remove unreachable D2/D6/D8 defect UTs, fix queried-column deletion projection in SeriesScanMaterializer, and add end-to-end IoTDBSeriesScanDefectIT covering all 8 bugs.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 7734fa2. The eight fixes hold up (see "What was verified" at the end). Three things need attention before merge; the first one is blocking.

1. Blocking: unit-test (datanode) fails, compaction loses its direct-flush path

Details are in the inline comments on ModificationUtils and DiskAlignedChunkLoader. In short, the new modified propagation is shared with compaction, so a chunk group with a fully deleted value column no longer takes the direct-flush path:

  • BatchedAlignedSeriesReadChunkCompactionTest.testSimpleCompactionWithAllDeletedColumnByFlushChunk:204 expected:<14> but was:<8>
  • BatchedAlignedSeriesReadChunkCompactionTest.testSimpleCompactionWithPartialDeletedColumnByFlushChunk:339 expected:<15> but was:<12>

Both fail on Ubuntu and Windows and reproduce locally on this head. The compacted data is still correct (13/13 once the two count assertions are replaced by prints); only the speed changes.

The propagation is also not needed for the COUNT_TIME fix: AlignedSeriesScanUtil.canUseCurrent*TimeStatistics() already rejects or exactly resolves every shape it covers. I suggest restoring ModificationUtils, DiskAlignedChunkLoader and DiskAlignedChunkMetadataLoader to their base versions.

2. Query performance after a deletion (same cause)

SeriesScanUtil-level A/B on identical fixtures, median of 30 runs, three columns × 1M rows with s2 deleted over the whole range. All three builds return identical results.

Query base this PR this PR with item 1 applied
wildcard LIMIT 100 OFFSET 400000 0.28 ms 5.54 ms 0.40 ms
WHERE s0 != -1 23.4 ms 45.9 ms 22.6 ms
value aggregation (SUM-style) 0.33 ms 58.8 ms 0.40 ms
COUNT_TIME-style 0.32 ms 58.3 ms 0.33 ms
50-column device, one column deleted, value aggregation 1.15 ms 83.1 ms 1.26 ms

Deleting only the second half of the middle file still takes the aggregations from 0.08 ms to 5.9 ms.

Without deletions, base, this PR and the patched build are level within run-to-run noise (two rounds in opposite order, differences of a few percent in both directions): full scans ASC/DESC, sparse columns, LIMIT/OFFSET, aggregations, overlapping merge, 200 files, a 50-column device, and seven memory-table workloads (batch path, ordered and merge-sort TVLists, merge against a sequence file).

3. Pre-existing: MergeSortMultiAlignedTVListIterator, which the new fuzz test hits outside the default seeds

Not part of this diff, so there is no inline anchor. scan_strict=1 scan_first=5000 fails at seed index 4254 (ALIGNED_TREE, DESC): expected 30:[199.4] but got 30:[171.9]. Base 96a0c6d fails the same way, so this is not a regression.

In MergeSortMultiAlignedTVListIterator.prepareNext() (lines 198–211), a row whose queried columns are all deleted is skipped by advancing its iterators and pushing them back onto the heap, but they stay in probeIterators. When the next row belongs to another TVList, next() (or the next skip) advances that iterator again although its heap entry is still pending, and the stale time key is later paired with the wrong row.

Minimal case, one open file with a value deletion on [32, 35]: tv0 = 29, 30, 34 and tv1 = 32, plus one point at 31 from another open file. Expected 30:[199.4], 29:[171.9], actual 30:[171.9], 29:[171.9]. ASC is affected too: tv0 = 10 (deleted), 20, 30 and tv1 = 15 (deleted), 25 returns 20:[3] instead of 20:[2], and SUM is wrong.

The fix is one line (java.util.Iterator is then unused):

       if (ignoreAllNullRows && bitMap.isAllMarked()) {
-        Iterator<Integer> it = probeIterators.iterator();
-        while (it.hasNext()) {
-          int idx = it.next();
+        for (int idx : probeIterators) {
           AlignedTVList.AlignedTVListIterator iterator = alignedTvListIterators.get(idx);
           iterator.next();
           if (iterator.hasNextTimeValuePair()) {
             heap.add(new Pair<>(iterator.currentTime(), idx));
-          } else {
-            it.remove();
           }
         }
+        probeIterators.clear();
         hasNext = false;
       }

It needs a memory table with at least two time-overlapping TVLists plus a value deletion, so it is narrow, but it is the merge-sort sibling of D1b. The default seeds do not reach it, which is why CI is green here.

4. Minor

  • IoTDBConfig.isStreamingQueryMemChunk / setStreamingQueryMemChunk and the three-argument MemChunkLoader / MemAlignedChunkLoader constructors are public. The description says there is no production setter; the setter exists, so a downstream fork may reference it.
  • Leftovers of the non-streaming path: ReadOnlyMemChunk.initChunkMetaFromTvLists(Filter), AlignedReadOnlyMemChunk.nonStreamingTimeValuePairIterator and getMemPointIterator(), MemPointIterator.streamingQueryMemChunk, and the "Only used when StreamingQueryMemChunk is configured as false" comment.
  • dual-table-manual-enhanced (…, 1) is red in one of the two runs: IoTDBPipeClusterIT.testHistoryDataWithEmptyField. The other run of the same commit passed it, and it failed on unrelated PRs this week, including a docs-only one.

What was verified on this head

  • SeriesScanUtilDefectTest 9/9, default SeriesScanUtilFuzzTest 6/6, strict fuzz over seeds 5000–7999 (18,000 scenarios with flushed chunks and sensor subsets; only the item-3 seed fails).
  • CI: every Cluster / Table Cluster / Edge / Windows IT job is green; IoTDBSeriesScanDefectIT is 11/11 in both SimpleIT and ClusterIT.
  • With items 1 and 3 applied on top of this head: strict fuzz green over seeds 5000–7999 and 20000–22999 (36,000 scenarios), the compaction suite 13/13, 270 tests in 27 related unit-test classes green, and IoTDBSeriesScanDefectIT 11/11 in SimpleIT locally.
  • Not covered: TTL, TopK runtime filters, type changes, and an unclosed file with flushed chunks plus deletions on a real cluster. The fuzz fixture does not generate the last one either, so for that path item 1 rests on reading the code.

valueChunkMetadataList.set(i, null);
currentRemoved = true;
if (ignoreAllNullRows) {
modified = true;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking. This flag also reaches compaction: modifyAlignedChunkMetaData is shared with MultiTsFileDeviceIterator and FastAlignedSeriesCompactionExecutor, and BatchedReadChunkAlignedSeriesCompactionExecutor only direct-flushes a chunk whose time chunk is unmodified. A value column deleted as a whole therefore sends the remaining chunks of the group down the deserialize path. BatchedAlignedSeriesReadChunkCompactionTest.testSimpleCompactionWithAllDeletedColumnByFlushChunk:204 expects 14 directly flushed chunks and gets 8, and ...testSimpleCompactionWithPartialDeletedColumnByFlushChunk:339 expects 15 and gets 12. Both fail in the unit-test (datanode) jobs on Ubuntu and Windows. The compacted data is still correct, only slower.

The flag is not needed for the COUNT_TIME fix. Once the deleted column is null, AlignedSeriesScanUtil.canUseCurrent*TimeStatistics() either finds a remaining dense column (the time statistics are exact), resolves the single remaining column (its statistics are the row statistics), or rejects the statistics. With this hunk, the one at lines 157–166 and the markDeletedPagesModified call in DiskAlignedChunkLoader disabled: SeriesScanUtilDefectTest is 9/9, this compaction suite is 13/13, and the strict fuzz over seeds 5000–7999 fails in exactly the same single place as this head. Keeping it also costs query performance; see item 2 in the review summary.

: new TableChunkReader(
timeChunk, valueChunkList, globalTimeFilter, filterRowsRecorder);
if (ignoreAllNullRows) {
markDeletedPagesModified(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Goes together with the comment on ModificationUtils; I would drop this one too. Besides taking statistics and page skipping away from every page that overlaps a deletion (numbers in item 2 of the review summary), it is broader than the condition it describes:

  • With the three-argument constructor used by MemAlignedChunkMetadataLoader for unclosed files, removedValueColumnDeletions is null, so chunkModified && hasNullValueChunk marks every page of the chunk, including the ones the deleted column never reached.
  • With the four-argument constructor the ranges come from the modification entries rather than from the removed chunk, so a deletion wider than that chunk (for example time >= 1) also marks pages where the column had no values.

DiskAlignedChunkMetadataLoader.collectRemovedValueColumnDeletions becomes unused with it.

.map(IMeasurementSchema::getType)
.collect(Collectors.toList());
this.queryAllSensors = queryAllSensors;
this.ignoreAllNullRows = context.isIgnoreAllNullRows();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

queryAllSensors is no longer read anywhere, but it is still a constructor parameter and AlignedSeriesScanOperator and ExternalTsFileSeriesScanUtil still pass it. Suggest removing it so that nobody assumes the old shortcut can still be switched on.

return null;
});
// Allow the target FLUSH RPC to move d1's working memtable into flushingMemTables
Thread.sleep(300);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two sleeps are what keep d1's memtable in flushingMemTables for the DELETE and the query. If the blocker flush finishes earlier, the memtable is already flushed and the case still passes, but through the closed-file path, so it no longer covers what its name says. integration-test/AGENTS.md prefers an observable condition over a fixed sleep. Not blocking, but an observable precondition would turn such a false pass into a visible failure.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recommend fixing the performance regressions before merging 7734fa2473. I compared this head with 96a0c6d390 on identical inputs. Three results add evidence to existing discussions.

  • Compaction. BatchedAlignedSeriesReadChunkCompactionTest passed 13/13 on the base and 11/13 on this head. With a value column deleted across the whole test range, the number of directly flushed chunks fell from 14 to 8. With the deletion limited to part of the range, it fell from 15 to 12. The same two assertions failed on Linux and Windows. Compaction discussion · Linux CI · Windows CI
  • Value-only aggregation. In a 64-page chunk with 2,048 live s0 values and s1 fully deleted, COUNT(s0), COUNT(s1) returned (2048, 0) on both revisions. The base answered from chunk statistics without opening a chunk reader. This head decoded all 64 pages. Please preserve exact value-column statistics when a deletion invalidates the time-column row count. Page-marking discussion
  • Flushing memtable coverage. I ran D1a and D1b against the unfixed base, changing only Thread.sleep(300) to targetFlushFuture.get(60, TimeUnit.SECONDS) in the PR test. Both passed with the target flush already complete before DELETE. A deterministic test should wait until the target memtable enters flushing and hold it there through SELECT. Flush timing discussion

The nine new defect unit tests and 2,400 strict differential scenarios passed on this head. IoTDBSeriesScanDefectIT passed 11/11 on both 1C1D and 1C3D. Another 28 existing aggregation and deletion integration tests passed on 1C1D.

@Override
protected boolean timeAllSelected(IMetadata metadata) {
if (queryAllSensors || metadata.getMeasurementCount() == 0) {
if (!ignoreAllNullRows || metadata.getMeasurementCount() == 0) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve OFFSET skipping for a single sparse column

After dropping s1, SELECT * expands to s0, but an old file can still contain timestamps where only s1 had a value. The non-null count of s0 is the exact number of visible rows in that file. With s0 present at every second timestamp, LIMIT 1 OFFSET 1024 returned timestamp 2049 on both revisions. The base decoded 1 page and this head decoded 65. Please use the selected column's count for pagination when its statistics are usable.

if (!ignoreAllNullRows || metadata == null) {
return true;
}
return timeAllSelected(metadata) || hasAtMostOneNonNullMeasurement(metadata);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Use file statistics when disjoint value ranges prove full coverage

I tested COUNT_TIME(*) on 16 unmodified files. Each had 128 timestamps, with s0 covering the first 64 and s1 the last 64. Both revisions returned 2,048. The base answered from 16 file statistics and this head decoded all 16 pages. When the value columns' time ranges are pairwise disjoint and their counts sum to the time-column count, the metadata proves that every timestamp has a selected value. Please retain the statistics path for that case.

if (pushDownFilter != null
&& firstPageReader.isModified()
&& firstPageReader.getPageReader() instanceof AbstractAlignedPageReader) {
TsBlock tsBlock = firstPageReader.getAllSatisfiedPageData(orderUtils.getAscending());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve the LIMIT fast path when a deletion does not affect the predicate

On an 8,192-row page, every s0 was positive and a deletion affected a single s1 value. For WHERE s0 > 0 LIMIT 1, the base used the s0 statistics and made zero per-value predicate evaluations. This branch materialized the whole page and evaluated all 8,192 values to return the same first row. Can the reader keep checking row visibility while still using the predicate column's statistics and applying the limit early when that column is unaffected?

if (deletions == null || deletions.isEmpty()) {
return false;
}
for (TimeRange range : deletions) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid restarting the deletion-range scan for every page

With 64 pages and 256 disjoint removed-column deletion intervals all falling in the last page, I measured 63 × 256 + 1 = 16,129 interval visits before the reader returned its first page. The base had no such pass. Sorting and merging the ranges once, then advancing a cursor as the pages are visited in time order, would avoid the O(pages × intervals) setup cost.

pages.add(new ArrayList<>());
}
pages.get(pages.size() - 1).add(row);
byTime.put(row.time, row);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Merge duplicate timestamps per column in the test oracle

In one aligned TVList, write (time=1, s0=10, s1=null) followed by (time=1, s0=null, s1=20). I get (1, 10, 20) from both revisions in both scan directions, but expectedRows() gives (1, null, 20) because byTime.put replaces the entire first row. Please retain the last non-null value per column in the oracle and include repeated timestamps within a single TVList in the generator.

for (Problem problem : found) {
problems
.computeIfAbsent(problem.kind, ignored -> new ArrayList<>())
.add(new Example(problem.detail, scenario.describe(), fullSeed));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Print the scenario number accepted by scan_seed

The failure report prints fullSeed, while scan_seed parses an integer scenario number and applies the seed transformation again. For NON_ALIGNED in ASC order, scenario 2500 produces 2500007500. Passing the printed value to scan_seed throws NumberFormatException. Please include the replayable scan_seed=2500 along with the model and direction in the failure output.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 7734fa2473 independently and deduplicated against the existing review comments (compaction/query regression from ModificationUtils & DiskAlignedChunkLoader modified propagation, MergeSortMultiAlignedTVListIterator probeIterators.clear(), OFFSET/LIMIT/COUNT_TIME fast paths, IoTDBSeriesScanDefectIT flush sleeps, and StreamingQueryMemChunk leftovers).

Adding 5 remaining non-duplicate notes inline: two [P2] edge cases (AlignedSeriesScanUtil nonNullCount == 0 fallback and TVList.TVListIterator#reset deleteCursor) and three [P3] follow-ups (!tsDataTypeList.isEmpty() guard on MergeSortMultiAlignedTVListIterator, plus default fuzz coverage for flushedChunks/subsetSensors, IS [NOT] NULL, and .mods on open files with flushed chunks).

singleNonNullMeasurementStatistics = valueStats;
}
}
return nonNullCount == 1 ? singleNonNullMeasurementStatistics : timeStatistics;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reject nonNullCount == 0 instead of falling back to timeStatistics when measurementCount > 0

hasAtMostOneNonNullMeasurement(IMetadata) (lines 159–168) returns true when nonNullCount == 0 (every queried column has null or empty statistics while ignoreAllNullRows == true and measurementCount > 0), so canUseAlignedTimeStatistics(metadata) reports that time statistics are usable. However, getAlignedTimeStatistics(...) here evaluates return nonNullCount == 1 ? singleNonNullMeasurementStatistics : timeStatistics;, returning the unprojected timeStatistics (non-zero count) instead of 0.

For example, on a MemAlignedPageReader (which now exposes getMeasurementCount()) or aligned metadata whose queried subset of columns is all-null over those timestamps, COUNT_TIME would over-count rows from timeStatistics. Consider tightening hasAtMostOneNonNullMeasurement to require nonNullCount == 1 when measurementCount > 0 (or returning an empty Statistics when nonNullCount == 0).


@Override
public void reset() {
super.reset();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reset deleteCursor in super.reset() (TVList.TVListIterator#reset) as well

AlignedTVListIterator.reset() resets timeDeleteCursor[0] and valueColumnDeleteCursor for both ASC (0) and DESC (size - 1) after calling super.reset(). However, TVList.TVListIterator.reset() (TVList.java:1206–1209) only resets index = 0; probeNext = false; and leaves TVListIterator.deleteCursor[0] (TVList.java:819, 851–853) at its exhausted position (deletionList.size() in ASC, -1 in DESC), so resetting a non-aligned TVListIterator with deletions silently skips all deletions on the second pass.

}
}
if (ignoreAllNullRows && bitMap.isAllMarked()) {
if (ignoreAllNullRows && !tsDataTypeList.isEmpty() && bitMap.isAllMarked()) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Also guard !tsDataTypeList.isEmpty() in MergeSortMultiAlignedTVListIterator.prepareNext()

Supplementing the earlier review note on MergeSortMultiAlignedTVListIterator.prepareNext() (lines 198–211): when applying the probeIterators.clear() fix there, line 198 (if (ignoreAllNullRows && bitMap.isAllMarked())) should also check !tsDataTypeList.isEmpty() to match OrderedMultiAlignedTVListIterator:101 and AlignedTVList:2290, since BitMap.isAllMarked() (BitMapArrayImpl) returns true when size == 0.

config.smallPage = index % 2 == 0;
config.multipleMemChunks = MULTIPLE_MEM_CHUNKS;
config.flushedChunks = FLUSHED_CHUNKS;
config.subsetSensors = SUBSET_SENSORS;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Exercise flushedChunks and subsetSensors in a slice of default scenarios

Unlike multipleMemChunks, both flushedChunks (open file with flushed disk chunks) and subsetSensors (reading a subset of stored aligned columns) are valid production states, yet both default to false unless env/system properties are passed manually. Toggling them on a slice of index values by default (similar to config.smallPage = index % 2 == 0 on line 106) would cover subset-sensor time statistics and open-file flushed chunks in regular CI runs.

return rnd.nextBoolean()
? ValueFilterApi.eq(column, operand, type)
: ValueFilterApi.notEq(column, operand, type);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Cover IS NULL / IS NOT NULL filters and .mods deletions on open files with flushed chunks

Two small generator gaps worth closing:

  1. randomValueFilter only generates value comparison/range filters (which always evaluate null to false); adding ValueFilterApi.isNull(column) and ValueFilterApi.isNotNull(column) exercises CompareNullFilter.canSkip / allSatisfy on aligned pages where deletions turn values into null.
  2. In generate (line 421, if (file.open) { continue; }), file-level .mods deletions are skipped for all open files; allowing .mods deletions when !file.diskChunks.isEmpty() would exercise the ResourceByPathUtils.getVisibleMetadataListFromWriter + MemAlignedChunkMetadataLoader modification path on open files.

@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.19403% with 37 lines in your changes missing coverage. Please review.
✅ Project coverage is 50.71%. Comparing base (96a0c6d) to head (da61336).

Files with missing lines Patch % Lines
...he/iotdb/db/utils/datastructure/AlignedTVList.java 58.53% 17 Missing ⚠️
...gine/execution/operator/source/SeriesScanUtil.java 91.15% 10 Missing ⚠️
.../source/AbstractSeriesAggregationScanOperator.java 68.75% 5 Missing ⚠️
...ecution/operator/source/AlignedSeriesScanUtil.java 97.22% 2 Missing ⚠️
...ryengine/execution/aggregation/TreeAggregator.java 80.00% 1 Missing ⚠️
...ource/relational/ExternalTsFileSeriesScanUtil.java 0.00% 1 Missing ⚠️
...e/dataregion/read/reader/chunk/MemChunkLoader.java 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #19445      +/-   ##
============================================
+ Coverage     50.64%   50.71%   +0.07%     
  Complexity      137      137              
============================================
  Files          5788     5782       -6     
  Lines        427308   427041     -267     
  Branches      56800    56802       +2     
============================================
+ Hits         216401   216585     +184     
+ Misses       210907   210456     -451     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please fix the incorrect query result after ALTER TIMESERIES ... SET DATA TYPE STRING before merging 624424cddf. The six performance cases from the previous review are back at their baseline counts. The compaction suite passed 13/13, and IoTDBSeriesScanDefectIT passed 11/11 on both 1C1D and 1C3D.

}
List<ValuePageReader> valuePageReaders = pageReader.getValuePageReaderList();
if (!hasModifiedValuePage(valuePageReaders)) {
return false;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Recheck the predicate after converting an aligned column to STRING

A type change can invalidate page statistics while leaving every value page's deletion flag clear. This early return then lets the reader accept s0 != '2' for the entire page. The stored numeric extrema are 1 and 100. Both '1' and '100' sort before '2' as strings, even though the page contains a value that converts to '2'.

CREATE DATABASE root.reviewalter;
CREATE ALIGNED TIMESERIES root.reviewalter.d(s0 INT32, s1 INT32);
INSERT INTO root.reviewalter.d(time, s0, s1) ALIGNED
  VALUES (1, 1, 10), (2, 2, 20), (3, 100, 30);
FLUSH root.reviewalter;
ALTER TIMESERIES root.reviewalter.d.s0 SET DATA TYPE STRING;
SELECT s0, s1 FROM root.reviewalter.d WHERE s0 != '2';

On real 1C1D instances, 7734fa2473 returned the expected timestamps [1, 3]. This head and the base 96a0c6d390 both returned [1, 2, 3], including the row that the predicate excludes. EXPLAIN confirmed that the predicate reached AlignedSeriesScan.

Please preserve the decode, convert, then filter path when a predicate column's stored statistics are invalid for its queried type, and add this SQL case to the regression tests.

&& filterAllSatisfy(pushDownFilter, firstTimeSeriesMetadata)
&& timeAllSelected(firstTimeSeriesMetadata)) {
long rowCount = firstTimeSeriesMetadata.getStatistics().getCount();
&& canUseTimeStatistics(firstTimeSeriesMetadata)) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Skip pagination statistics when no OFFSET remains

The file, chunk, and page paths call canUseTimeStatistics(...) before checking the remaining offset. On a sparse aligned device this can collect and sort the value-column ranges even when the query has no OFFSET, or after an earlier file has consumed it.

I scanned 1,024 rows across 64 sparse columns and 16 pages with OFFSET=0. Both revisions returned the same rows and decoded 16 pages. In IoTDB's pagination checks alone, 624424cddf made 1,156 additional value-statistics lookups and 12,278 additional range-start reads compared with 7734fa2473. These counters exclude the work inside TsFile's own timeAllSelected().

Please put paginationController.hasCurOffset() first in the offset-specific condition at all three levels, ahead of the coverage and row-count calculations.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 624424cddf. The comments from the three earlier reviews are addressed in the code and the tests; what I checked is at the end. Three items are still open (inline), plus one note on the correctness finding of the previous review.

Still open

  1. Cluster IT - 1C1D / Windows (2) is red on this head. IoTDBSeriesScanDefectIT.testD1bValueDeletionOfMemoryTableIsAppliedWithTwoTVLists times out waiting for the blocker flush to show up in the flush-queue metric. The same commit is green on the Ubuntu job of that workflow and in Cluster IT - 1C3D, and passed 11/11 three times locally in SimpleIT, so the "11/11 on 1C1D and 1C3D" reported in the previous review is consistent with this; it just does not cover Windows. Details and a likely cause are in the inline comment.
  2. The fuzz generator throws on some seeds in strict mode (SeriesScanScenario.randomDeletionRanges): 7 of 300,000 scenarios, none in the default range, so CI stays green.
  3. Leftovers of the non-streaming path: ReadOnlyMemChunk.getMemPointIterator() now always returns null, and MemPointIterator.streamingQueryMemChunk with its branch is still there.

The ALTER ... SET DATA TYPE STRING case from the previous review

I re-ran it on three builds with a real 1C1D instance, with one extra variant that also deletes a value:

root.x.d(s0 INT32, s1 INT32) with (1, 1, 10), (2, 2, 20), (3, 100, 30), then ALTER TIMESERIES root.x.d.s0 SET DATA TYPE STRING base 96a0c6d390 7734fa2473 this head
WHERE s0 != '2' 1, 2, 3 (wrong) 1, 3 1, 2, 3 (wrong)
WHERE s0 = '2' 2 2 2
same predicate without the ALTER (WHERE s0 != 2) 1, 3 1, 3 1, 3
ALTER plus DELETE ... s0 WHERE time = 3, WHERE s0 != '2' 1, 2, null (wrong) 1 1

So the finding is confirmed: the wrong result exists on the base, 7734fa2473 fixed it as a side effect of decoding every modified aligned page, and needsModifiedAlignedPagePushDownFallback brings it back because a type change marks the page as modified without marking any of its value pages. When a deletion is present as well, the fallback does run and the result is right again.

What I verified on this head

  • SeriesScanUtilDefectTest 17/17, default SeriesScanUtilFuzzTest 6/6.
  • Strict fuzz (scan_strict=1 scan_flushed=1 scan_subset=1): seeds 5000–7999 and 30000–32999 green (18,000 scenarios each). Seeds 20000–22999 show the two generator errors from item 2 and are green once the generator is fixed, so nothing is hidden behind them.
  • BatchedAlignedSeriesReadChunkCompactionTest 13/13, 284 tests in 27 related unit-test classes green, IoTDBSeriesScanDefectIT 11/11 three times locally in SimpleIT.

Performance against base (SeriesScanUtil level, same fixtures, identical results in all three builds)

Query base 7734fa2473 this head
column deleted, wildcard LIMIT 100 OFFSET 400000 0.33 ms 5.6 ms 0.33 ms
column deleted, value aggregation 0.35 ms 59.0 ms 0.33 ms
column deleted, full scan with WHERE s0 != -1 23–26 ms 46.6 ms 23.5 ms
single sparse column, LIMIT 1 OFFSET 499999 10–13 ms not measured 0.4 ms
WHERE s0 != -1 LIMIT 1, one unrelated value deleted 0.52 ms not measured 0.54 ms

Without deletions (full scans, overlapping merge, 200 files, a 50-column device, seven memory-table workloads) the three builds are level within run-to-run noise.

Note on the description

The scenario that failed before the MergeSortMultiAlignedTVListIterator fix is scan_seed=5254 (loop index 4254). scan_seed=4254 is a different scenario. Both pass on this head.

});
// Wait until the blocker FLUSH occupies the sole flush thread on every replica DataNode
awaitCondition(
"blocker flush to occupy the sole flush thread on all " + replicaCount + " replica(s)",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fails on Windows CI. Cluster IT - 1C1D / Windows (2) (job 141254538766) fails here with Timed out waiting for blocker flush to occupy the sole flush thread on all 1 replica(s). The same commit is green on the Ubuntu job of that workflow and passed 11/11 three times locally in SimpleIT. The previous sleep-based version of this test passed both Windows runs of 7734fa2473.

The DataNode log of the failed run shows that the flush was running the whole time: the blocker command was issued at 14:45:49.57 (log time, UTC+8), the 2.4 MB unsequence memtable was flushed from 49.58 to 46:00.31, and the wait gave up at about 46:04.6. So the single flush thread was busy for 10.7 s of the 15 s window while /metrics never reported running >= 1. No scrape exception is logged.

Most likely cause (not reproduced, I have no Windows machine): prometheus_reporter_async_update=false makes every scrape compute all gauges on the request path, and on Windows that starts two PowerShell processes (Get-CimInstance Win32_PerfFormattedData_PerfDisk_PhysicalDisk and Win32_PerfFormattedData_PerfProc_Process) plus netstat -ano for each node, cached for 10 s with the first call always executed. testD1b was the first test in this class to scrape, so the first poll took longer than the remaining flush time. testD1a passed right afterwards (8.4 s) with the caches warm. Linux reads /proc for these gauges (plus a short shell pipeline for the connection count) and the macOS managers are not implemented, which is why nothing shows up on either.

Suggestions: take the first (cold) scrape before anything is timed, scrape only the DataNodes (the flush gauges do not exist on the ConfigNode), and make the blocker last much longer than the worst-case poll. testD1a is exposed to the same race whenever the 10 s cache expires in the middle of the test.

private static List<TimeRange> randomDeletionRanges(Random rnd, List<Row> rows) {
List<TimeRange> ranges = new ArrayList<>();
long start = rows.get(0).time;
long end = rows.get(rows.size() - 1).time;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the rows appended by maybeAddDuplicateTimestamp the rows are in insertion order, not time order, so rows.get(0) and rows.get(last) are no longer the minimum and the maximum. When the last row carries an earlier timestamp than the first, new TimeRange(start, end) throws IllegalArgumentException: min:.. should not be larger than max:... Because this happens inside generate, the parameterized test reports an error before the oracle runs.

In strict configuration (scan_strict=1 scan_flushed=1 scan_subset=1 scan_first=1000 scan_scenarios=50000) this hits 7 of 300,000 scenarios: scan_seed 1808, 3895, 18903, 21460, 20612, 42348 and 46182 (six ALIGNED_TABLE, one ALIGNED_TREE). The default range 1000–1059 is not affected, so CI stays green, and the "strict wide run" in the description stops at 5999, before the first one.

Taking the minimum and maximum over the row times fixes it without changing any other scenario (no random numbers are consumed). With that change all seven seeds and the whole 20000–22999 range (18,000 scenarios) pass, so nothing is hidden behind the crash:

-    long start = rows.get(0).time;
-    long end = rows.get(rows.size() - 1).time;
+    long start = Long.MAX_VALUE;
+    long end = Long.MIN_VALUE;
+    for (Row row : rows) {
+      start = Math.min(start, row.time);
+      end = Math.max(end, row.time);
+    }


public MemPointIterator getMemPointIterator() {
return timeValuePairIterator;
return null;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This getter returned null in production before this PR as well, because the field was only assigned on the non-streaming path, so it is not a regression. But a public getter that always returns null is a trap: its only callers are the constructors of MemChunkReader and MemAlignedChunkReader, which then hold a null iterator. Since SeriesScanUtil routes every MemChunkLoader to the fake-page path, those two readers (and MemPageReader / MemAlignedPageReader behind them) have no working path left. Suggest deleting the getter together with them.

Same topic, not in this diff: MemPointIterator.streamingQueryMemChunk is still true by default, setStreamingQueryMemChunk has no caller left, and the non-streaming branch of addTsBlock is dead.

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recommend holding the merge until the BOOLEAN to STRING predicate case is fixed. I rechecked afe1c494b1 against 624424cddf, 7734fa2473, and the base 96a0c6d390.

Open findings

  1. [P1] A legal query fails after altering an aligned BOOLEAN column to STRING. An unfiltered read returns the converted values true, false, true. Adding WHERE s0 != 'false' should return timestamps [1, 3], but this head raises 301: BOOLEAN statistics does not support: min. The inline comment includes the SQL and the failing call.
  2. [P2] Seven strict fuzz seeds still fail in the generator. I replayed 1808, 3895, 18903, 21460, 20612, 42348, and 46182 individually with scan_strict=1 scan_flushed=1 scan_subset=1. All seven throw before the scan starts. For example, scan_seed=1808 fails in aligned-table DESC with min:27 should not be larger than max: 26. randomDeletionRanges() uses the first and last rows as bounds, but appending a duplicate timestamp can leave the rows out of time order. Please compute the actual minimum and maximum timestamps. Generator discussion
  3. Flush IT scheduling and Windows verification. The new warmup samples the flush queues before starting the blocker, and the assertions detect a target flush that finishes too early. The test still needs the blocker to last through DELETE and SELECT. At 2026-11-29 09:50 UTC, the Windows shard that failed on the previous head was still in progress. A test-controlled release of the blocker would remove the remaining dependency on machine speed. Flush timing discussion · Windows job on this head
  4. Non-streaming reader cleanup remains. ReadOnlyMemChunk.getMemPointIterator() always returns null, and the MemChunkReader and MemAlignedChunkReader constructors still store that result. MemPointIterator also retains its non-streaming flag and branch. This is a cleanup item. Please remove the obsolete path together with its callers, or document who still requires it. The removed config accessors and three-argument loader constructors were public on the base revision, so downstream callers of those internals need to adapt. Reader cleanup discussion
  5. The PR description gives the wrong replay seed for the merge-sort defect. On 7734fa2473, scan_seed=5254 reproduced the aligned-tree DESC error at timestamp 30 (expected 199.4, actual 171.9). scan_seed=4254 passed all six parameter combinations there. The loop index was 4254, and the replayable scenario number was 5254. Please update the description. The corrected seed passes on this head. Earlier review

Verified fixes on this head

Case Observed result
INT32 to STRING, WHERE s0 != '2' Correct timestamps [1, 3], both before and after deleting an unrelated s1 value.
Wide sparse scan with OFFSET=0 On 64 columns, 16 pages, and 1,024 rows, pagination checks fell from 18 to 0, extra value-statistics lookups from 1,156 to 0, and extra range-start reads from 12,278 to 0. With OFFSET 64, the first returned timestamp was 65.
Aligned compaction and value aggregation after a column deletion All 13 compaction tests passed. COUNT(s0), COUNT(s1) returned (2048, 0) from one chunk statistic with zero decoded pages.
Single sparse column with OFFSET, and COUNT_TIME(*) over disjoint measurement ranges The offset query decoded one page. COUNT_TIME(*) returned 2,048 from 16 file statistics with zero decoded pages.
Deletion outside the predicate column, and many removed-column intervals WHERE s0 > 0 LIMIT 1 needed zero per-value predicate evaluations on an 8,192-row page. The 64-page, 256-interval fixture made zero extra interval visits before delivering the first page.
Duplicate timestamps in one aligned TVList The oracle and scan both returned (10, 20) in ASC and DESC. Fuzz failures now print the scenario number accepted by scan_seed.

The obsolete queryAllSensors parameter is gone from the scan constructors. The defect suite covers all-null projected statistics, deletion-cursor reset, and merge-sort deletion skipping in both directions. The generator exercises flushed chunks, sensor subsets, null predicates, and modifications on open files with flushed chunks.

The targeted Maven run passed 43 unit tests, including all 19 SeriesScanUtilDefectTest cases. IoTDBSeriesScanDefectIT passed 12/12 on both 1C1D and 1C3D. I ran the additional Boolean SQL assertion and the seven seed replays separately.

// Only when pushDownFilter.allSatisfy(pageReader) returns true does AbstractAlignedPageReader
// skip row-level filtering; when it returns false, deletions and target-type conversion are
// already applied before filtering.
if (!pushDownFilter.allSatisfy(pageReader)) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Check the stored statistics type before the first allSatisfy call

pushDownFilter.allSatisfy(pageReader) executes before hasValuePageWithInvalidStatistics(...). A pushed-down STRING inequality calls BooleanStatistics.getMinValue() on a page written as BOOLEAN. That method throws, so execution never reaches the new type-validity check.

CREATE DATABASE root.reviewbool;
CREATE ALIGNED TIMESERIES root.reviewbool.d(s0 BOOLEAN, s1 INT32);
INSERT INTO root.reviewbool.d(time, s0, s1) ALIGNED
  VALUES (1, true, 10), (2, false, 20), (3, true, 30);
FLUSH root.reviewbool;
ALTER TIMESERIES root.reviewbool.d.s0 SET DATA TYPE STRING;
SELECT s0, s1 FROM root.reviewbool.d WHERE s0 != 'false';

On real 1C1D instances, 7734fa2473 returned the expected timestamps [1, 3]. Both 624424cddf and this head returned 301: BOOLEAN statistics does not support: min. The base 96a0c6d390 also failed this query, wrapping the page-decode error as status 724. On this head, EXPLAIN placed the predicate in AlignedSeriesScan, and the DataNode stack pointed to this line via StringFilterOperators.ValueNotEq.allSatisfy.

Please check whether the predicate's referenced columns have usable statistics before handing the page to allSatisfy. When conversion invalidates those statistics, decode the values, convert them to the target type, and evaluate the predicate. Please add this Boolean case alongside the integer conversion IT and retain the fast path for predicates on unaffected columns.

… dead non-streaming mem readers, and isolate flush IT metrics

@JackieTien97 JackieTien97 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One test-stability issue remains on 5ce8ed4bcb because D1a and D1b depend on the blocker flush lasting through DELETE and SELECT. The unmodified IoTDBSeriesScanDefectIT suite passed 12/12 locally on 1C1D and 1C3D, and 12/12 on the Windows shard that previously failed. Windows CI

The other four findings from the previous review are addressed. The BOOLEAN to STRING query returned timestamps [1, 3], all seven failing fuzz seeds passed on replay, the obsolete non-streaming reader path was removed, and the PR description now gives the correct scan_seed=5254. Previous review


// Verify d1's memtable stayed queued in flushingMemTables through both DELETE and SELECT so
// the test cannot silently pass via the closed-file path.
assertFalse("Blocker flush finished before SELECT completed", blockerFlushFuture.isDone());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep the target memtable queued through the SQL assertions

The queue checks establish that the target memtable is waiting before DELETE. The blocker can finish as soon as those checks return, allowing the target to flush while the test client is descheduled.

I reproduced this on this head with an isolated copy of D1b. I paused only the test-client thread for 15 seconds immediately after the two pre-DELETE assertions. On resumption, both flush futures were complete. DELETE succeeded and SELECT returned the expected rows, then this line failed with Blocker flush finished before SELECT completed.

Could the test control when the blocker releases the sole flush worker on each participating DataNode? For example, hold the blocker on a test-controlled latch, wait for the target to queue, and run DELETE and SELECT while it is held. Release the latch in finally before joining either future, with bounded waits for the synchronization points. This would preserve the flushing-memtable coverage even when the test client is delayed. Earlier flush-timing discussion

@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Multiple correctness issues in SeriesScanUtil and AlignedSeriesScanUtil with deletions, overlaps, pushdown filters, and COUNT_TIME

1 participant