Repository navigation
Fix wrong results reading a Nested sibling beside a re-added subcolumn - #112997
Conversation
A physically present, never-altered Nested sibling returned its default value when read beside a subcolumn that had been dropped and re-added. With `share_nested_offsets` (default on), `ISerialization::getFileNameForStream` rewrites an offsets substream's name prefix to the Nested table name when `isPossibleOffsetsOfNested` holds, so every `arr.*` sibling names the same on-disk stream. After DROP + ADD of `arr.nested`, the subcolumn `arr.nested.b` is missing from the part and its only readable substream is that shared `arr.size0`. `MergeTreeReaderWide` recorded a prefetched stream in `prefetched_streams` by name alone, and `readData`'s getter consumed membership as "this stream is already positioned at from_mark for the column about to read it". Those coincide only while at most one requested column reads a given stream per `readRows` call, which the shared-offsets layout deliberately violates. So the subcolumn's claim suppressed the sibling's `seekToMark`, the sibling read from where the subcolumn had left the stream, `SerializationArray` got no usable offsets and produced 0 rows, `readRows` nulled the slot, and the fill layer then correctly default-filled a genuinely null column. `readRows` already documents the violated invariant: positions for all streams must be kept in sync, so no seeks may be skipped. Key `prefetched_streams` by stream name to the position of the claiming column so a skipped seek is authorized only for that column. Every single-owner path is unchanged, keeping the prefetch optimization intact; only a second, different column reading the same stream now seeks, which the existing invariant already requires. The duplicate-prefetch guards stay name-only, since they exist to avoid issuing two prefetches for one stream rather than to decide position. Measured before the change: 100% of rows wrong on a Wide part, and on object storage with no non-default settings because `remote_filesystem_read_prefetch` defaults to true. Compact parts were never affected. Merges and mutations write correct data, so this is a read-path defect only. No new setting and no format change. Co-Authored-By: Claude Fable 5 <[email protected]>
The test set `local_filesystem_read_prefetch` and then asserted content, but `prefetchForAllColumns` returns early when a nonzero `filesystem_prefetches_limit` is below the number of columns read, and the stateless runner randomizes that setting. In that case no stream is ever claimed, the first read seeks every stream normally, and every content assertion passes with the code path under test never taken. Read the effective limit and require it to permit prefetching. Reading it rather than pinning it with `SET` is what makes the guard falsifiable: an in-query `SET` overrides the runner's injection, so a pinned-then-asserted value can never fail. Verified by making it fire: the test passes at the runner's own draws of 0 and 10 and fails at 2 and 8, with the guard row as the only differing line. A `ProfileEvents` liveness assertion was rejected after measurement. There is no local-disk prefetch counter; the only real discriminator is a synchronous-wait counter emitted solely by the buffer used for `local_filesystem_read_method = 'pread_threadpool'`, which the runner randomizes over four values, so the assertion would be vacuous in three of four draws. Pinning the method to keep it would have narrowed real coverage, since the defect reproduces under all four methods. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (click to expand)Two review rounds by an independent model, adjudicated against the code. Round 1 raised one blocker ❌ Blockers
|
| # | Finding | Verdict |
|---|---|---|
| 2 | The test had no oracle proving the prefetch path ran. With prefetched_streams empty every content assertion passes for the wrong reason, and prefetchForAllColumns early-returns when the number of columns exceeds filesystem_prefetches_limit, which the test runner randomizes to 0 or 10. |
AGREE, fixed. A liveness row now reads the effective filesystem_prefetches_limit and fails the test when a draw would skip prefetching, rather than pinning the setting and silencing it. Verified falsifiable in both directions: it passes at limits 0 and 10 and fails at 2 and 8. |
💡 Noted, not blocking
- The liveness row closes the prefetch-limit route but not a second one:
local_filesystem_read_methodis randomized overread,pread,mmapandpread_threadpool, andReadBuffer::prefetchis a no-op for the three non-async methods, so roughly three runs in four do not take the prefetch path. This is a detection-probability gap, not a green-when-broken hazard, and there is no clean assertion to close it, because the local async buffer'sprefetchincrements no profile event. The mutation check shows the path is genuinely exercised on this change: reverting only the ownership comparison makes the new test fail with output byte-identical to the pre-fix output. - Owner-token validity was re-derived independently at all three claim sites: the column list is built once and never mutated, its size is asserted on every
readRows, and the map is cleared at each of the three lifetime boundaries, so a per-call column position is a sound token. - The two
erasesites and the two duplicate-prefetch guards correctly stay name-only. After a seek to start the stream is positioned for nobody, so revoking the whole claim is conservative; the guards answer whether a prefetch is already in flight on a file, which is not a per-column question. - Symmetric-subsystem sweep: this state exists in one file pair only,
MergeTreeReaderCompacthas no equivalent and serves as a control, so no sibling carrier is left unfixed.
Session id: cron:clickhouse-review-slot-50:20260802-115400
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260802-074100 |
|
cc @CurtizJ @CheSema, could you review this? With |
|
Workflow [PR], commit [bbb3654] Summary: ✅
AI ReviewSummaryThis PR narrows Findings❌ Blockers
Final Verdict❌ Changes requested. The owner check needs to hold across continuation reads too, or the PR metadata/user-visible claim needs to be narrowed until that path is fixed. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 36/36 (100.00%) · Uncovered code |
| /// A prefetch leaves the stream positioned for the column that issued it. Another column | ||
| /// sharing this stream must still seek, or it reads from where the first one stopped. | ||
| auto prefetched_it = stream_name ? prefetched_streams.find(*stream_name) : prefetched_streams.end(); | ||
| bool was_prefetched = prefetched_it != prefetched_streams.end() && prefetched_it->second == pos; |
There was a problem hiding this comment.
The new owner token only feeds the was_prefetched half of this condition. On the second readRows call for the same range, MergeTreeRangeReader::DelayedStream::readRows flips continue_reading to true, prefetchForAllColumns can still let the first column claim the shared arr.size0 stream at the current cursor, and then the sibling reaches this line with was_prefetched == false but seek_to_mark == false anyway. That means the sibling still reads from where the first column stopped, so the same wrong-results pattern remains as soon as the range spills into a continuation block. The new many granules test does not cover that path because its 100-row fixture always stays below the randomized max_block_size floor, so it never enters continue_reading.
Could we carry the owner check into the continuation case as well, or explicitly narrow the user-facing fix until the multi-block path is handled?
There was a problem hiding this comment.
Both facts are right and I concede them: the owner token feeds only the was_prefetched term, and the 100-row fixtures never enter continue_reading because the runner draws max_block_size from [8000, 100000] (tests/clickhouse-test:1432). The conclusion is where I disagree: that corruption is prefetch-independent, so it is a separate pre-existing defect rather than a gap in this change.
Every write to prefetched_streams (:571, :604) is reached only through prefetchForAllColumns, which returns early at :120-125 when the per-storage prefetch setting is off. With prefetch off the map is empty, find() at :646 returns end(), and this diff is inert. Yet the corruption is still there. Re-measured just now on this build and on a pristine-master build (c5efc69a), fixture index_granularity = 8192, 20000 rows, Wide, share_nested_offsets = 1, DROP+ADD, oracle sum(length(nb)), countIf(aid wrong), clean is 39999 0:
max_block_size |
prefetch | this PR | pristine master |
|---|---|---|---|
| 1000 | 0 | 21999 16000 |
21999 16000 |
| 1000 | 1 | 21999 16000 |
19999 17000 |
| 8000 | 0 | abort | abort |
| 100000 | 0 | 39999 0 |
39999 0 |
| 100000 | 1 | 39999 0 |
39999 20000 |
At every prefetch-off cell the two builds agree, so the multi-block defect exists where this diff cannot participate. At every prefetch-on cell this change is equal or better, never worse.
On carrying the owner check into the continuation case: that would be incorrect, not just wider. seek_to_mark seeks to from_mark (getStream -> stream.seekToMark(from_mark)), and on a continuation call from_mark is where the chain started, not where the previous block stopped: DelayedStream::readRows passes current_mark unchanged (MergeTreeRangeReader.cpp:199), and current_mark is reassigned only when continue_reading is reset to false (:229-230), while current_offset accumulates. Forcing a seek there would rewind to the granule start and re-read consumed rows. !continue_reading suppresses the seek unconditionally because resuming where the stream already is is what continuation means; fixing that regime needs a per-stream resume position, which is a different change.
So I took your second option. The changelog entry now names the prefetch precondition in its first sentence and states that the multi-block case is not covered, and the description says why this diff is inert there. The residual is tracked separately, with both of its triggers (partial final granule, and multi-block continuation) and a repro.
CI finish ledger - bbb3654CI is fully finished on this head and there are no failures to own.
174 check-runs: 156 Session id: cron:our-pr-ci-monitor:20260802-180000 |
|
@Avogar can you give a final look? The PR is small |
Avogar
left a comment
There was a problem hiding this comment.
@groeneai this fix is wrong, I will revert it.
We should never read from the same stream twice - we should always use the substreams cache to share the content of the shared substreams.
Without alter the example showed in PR description works, because both arr.id and arr.nested have getNameInStorage() = 'arr' maning these 2 columns share the substreams cache. But when we add new column arr.nested via alter, the getNameInStorage() of arr.nested.b is arr.nested instead of arr for some reason, so we need to fix that, not the seek of the shared stream.
I will create the fix myself
|
#112769 maybe also should be reverted |
|
Agreed on the revert, and thanks for the root cause. Reading the shared substream once is the On #112769 I measured rather than reasoned from the diff. Five debug builds in one tree, each #112769 is not needed. #113225 alone covers it.
The 48 fail on both arms for harness reasons ( Mechanism, so this is not merely a green run: I instrumented the predicate to log both spellings One caveat before it goes: arm E shows #112769 alone does not fix 04770 and crashes on the On the test: 04756 passes on #113461's head, so #113225 does fix that shape. Once the revert is Two residuals from my earlier rounds that bear on your fix, both measured:
|
|
Agreed, I will do it by hand and ping you in that PR. One fact that changes what the revert touches, since #113225 refactored the helper #112769
That is exactly arm B of the matrix above, so it is already measured: 03742, 04770, 04756 and The one wart is that the restored predicate reads Separately, #113461 is merged and 04756 is no longer on master, so the test-only PR re-adding it |
|
Correction: I was wrong about #112769, and it should not be reverted. My "14/14, byte-identical" result was a vacuous pass. The corpus I ran it on never reads a The distinction the corpus missed: after
Mechanism on current master. Measured with a single-variable A/B, only
In the same binary the parent reads That also answers your question about the raw So #112769 stays and I am not opening the revert. I will send the 04756 re-add as planned, and a test for this dotted case, since nothing in the suite pins it today. |
|
The test for the dotted case is #113646. It pins the shape from the correction above: reading Restoring the pre-#112769 inline spelling makes both witness rows read The 04756 re-add is prepared on its own branch and I will link it here when it opens. |
|
The 04756 re-add is open as #113777, as promised above. It answers the question you asked here: #113225 alone does fix the shapes that test covers. Three Two changes from the file this PR carried. The |
…olumn PR ClickHouse#113461 reverted ClickHouse#112997 along with its test. The shapes that test covers are fixed by ClickHouse#113225, so the test is re-added on its own to pin that fix, as requested in ClickHouse#112997. Three of its eleven assertions are live witnesses for ClickHouse#113225: reverting that PR's `getSubcolumnsOfNested` and type-computation repairs makes `missing subcolumn first`, `many granules` and `wrapped element types` report 100, 100 and 66 mismatching rows where 0 is correct. The other eight are controls (part type, reader header, prefetch limit, sibling ordering, prefetch off and the Compact-part pair) and are kept as such. The `no-random-merge-tree-settings` tag the pre-revert file carried is dropped. The test already pins `index_granularity`, `min_bytes_for_wide_part` and `min_rows_for_wide_part` in its `CREATE TABLE ... SETTINGS` clause, which takes precedence over runner injection, and `share_nested_offsets` is not randomized at all. Measured 250 randomized runs green without the tag (200 at --jobs 8, 50 at --jobs 1), plus 50 more with `default_compression_codec` forced to ZSTD, since the tag also pinned that codec to LZ4. Keeping CI randomization on is preferable to a blanket opt-out.
The test file was restored from the commit that ClickHouse#113461 reverted, so three of its comments described ClickHouse#112997's implementation rather than the tree the test now runs against. Two of them named prefetch stream ownership: the invariant that a prefetch positions a stream for the column that issued it, so a sibling sharing that stream must still seek. ClickHouse#113461 reverted the mechanism that held it. On master prefetched_streams is again a std::unordered_set<std::string> consulted by a bare contains, with no owner, so a reader that finds a stream prefetched does not seek regardless of which column prefetched it. Both comments now state what the assertions below them actually pin: under share_nested_offsets a re-added Nested member and its siblings share one offsets stream, so the member's group and element types must be rebuilt from metadata or the siblings read wrong values, and that resolution must hold for every mark rather than only the first. The direction matters and is measured. Comparing the committed reference against a build with ClickHouse#113225's repairs reverted, sum(length(nb)) over the re-added member reads 199 on both arms in all three live assertions; every field that moves is a countIf over a sibling. A comment claiming the re-added member reads wrong would be refutable from the test's own reference file. The third is the filesystem_prefetches_limit block, which ran to four lines. The arithmetic it ended with is re-derivable from the queries below it and from the assertion itself, which spells out the same bound, so that line is dropped and the invariant a reader cannot re-derive is kept: read the effective value rather than pinning it, so a restrictive limit fails this test instead of silencing it. Comment text only. No assertion, expected value, setting or table definition changes, and the reference file is untouched.
Related: #112769
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when filesystem read prefetch is enabled and a
Nestedcolumn is read beside a subcolumn that was dropped and re-added, on tables withshare_nested_offsetsenabled (the default). Such a query could return default values for a physically present column that theALTERs never touched. This needs no non-default settings on object storage, whereremote_filesystem_read_prefetchdefaults to1; on local disks it needslocal_filesystem_read_prefetch = 1. A separate, prefetch-independent defect still corrupts such reads when a range spans several blocks; that one is not covered here.Description
A physically present, never-altered column returned its default value when read beside a missing
Nestedsubcolumn sharing its offsets stream.Root cause: with
share_nested_offsetseveryarr.*sibling names the same offsets stream, so the re-added subcolumn and the surviving sibling read one file.MergeTreeReaderWiderecorded a prefetched stream by name only, and the data getter read that as "this stream is already positioned for the column about to read it". The first column's claim therefore suppressed the second column's mark seek; the second read from where the first stopped, got no usable offsets, came back empty, and was default-filled. ThereadRowscomment already forbids skipping seeks.The fix keys
prefetched_streamsfrom stream name to the position of the claiming column, so a skipped seek is authorized only for that column. Single-owner paths are unchanged, keeping the prefetch optimization; only a second column reading the same stream now seeks, as the invariant requires.Scope: Wide parts, one reader call. The multi-block defect named in the changelog entry is prefetch-independent, so this diff is inert there (
prefetched_streamsis written only under the prefetch gate) and measures identically before and after; tracked separately. Compact parts were never affected and serve as a control. No new setting, no format change.Pre-existing on master, reproduced on a pristine-master build, found while verifying #112769.
Validation matrix
Content oracles, not
length, which the bad read preserves.EXPLAIN header = 1asserted to list both columns, sincequery_plan_remove_unused_columnsotherwise prunes the subcolumn and the query stops triggering the bug. Verified in both directions, including a mutation check where reverting only the ownership comparison reproduces the original output byte for byte.local_filesystem_read_prefetch = 1type = s3disk, no non-default settingstype = local_blob_storagedisk, no non-default settingsshare_nested_offsets = 0Also measured: 13-granule and 1250-granule fixtures;
Array(Nullable(UInt64))andArray(LowCardinality(String))siblings; three siblings; both read orders (the subcolumn must be read first, otherwise the sibling's own prefetch positions the stream and the read is correct);index_granularity1 to 65536 crossed withmax_block_size8000 to 100000; horizontal merge, vertical merge on a remote disk (merge_algorithm = 'Vertical'confirmed inpart_log), mutation, andapply_mutations_on_fly. Merges and mutations write correct data; the defect is on the read path only.New test run 50 times at 8 jobs and 50 times at 1 job with randomized settings. The
nested,share_nested_offsets,prefetchandsubcolumnsuites ran on both arms: the failing sets differ only by tests that fail before the change, none after.Version info
26.8.1.750(included in26.8and later)