Skip to content

Fix wrong results reading a Nested sibling beside a re-added subcolumn - #112997

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-wide-reader-prefetch-shared-nested-offsets
Aug 4, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-wide-reader-prefetch-shared-nested-offsets

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112769

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 Nested column is read beside a subcolumn that was dropped and re-added, on tables with share_nested_offsets enabled (the default). Such a query could return default values for a physically present column that the ALTERs never touched. This needs no non-default settings on object storage, where remote_filesystem_read_prefetch defaults to 1; on local disks it needs local_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 Nested subcolumn sharing its offsets stream.

CREATE TABLE t (`id` UInt64, `arr.id` Array(UInt64), `arr.nested` Array(Tuple(a String, b Float64)))
ENGINE = MergeTree ORDER BY id SETTINGS min_bytes_for_wide_part = 0;
INSERT INTO t SELECT number, [number + 10], [(toString(number), number * 1.5)] FROM numbers(100);
ALTER TABLE t DROP COLUMN `arr.nested`;
ALTER TABLE t ADD COLUMN `arr.nested` Array(Tuple(a String, b Float64));

SELECT `arr.nested`.b, `arr.id` FROM t SETTINGS local_filesystem_read_prefetch = 1;
-- every row returned [0] [0]; `arr.id` holds [10], [11], ...

Root cause: with share_nested_offsets every arr.* sibling names the same offsets stream, so the re-added subcolumn and the surviving sibling read one file. MergeTreeReaderWide recorded 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. The readRows comment already forbids skipping seeks.

The fix keys prefetched_streams from 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_streams is 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 = 1 asserted to list both columns, since query_plan_remove_unused_columns otherwise 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.

arm wrong rows before after
Wide, local disk, local_filesystem_read_prefetch = 1 100 / 100 0
Wide, local disk, prefetch off 0 0
Wide, type = s3 disk, no non-default settings 100 / 100 0
Wide, type = local_blob_storage disk, no non-default settings 100 / 100 0
Compact, any setting 0 0
Wide, share_nested_offsets = 0 0 0

Also measured: 13-granule and 1250-granule fixtures; Array(Nullable(UInt64)) and Array(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_granularity 1 to 65536 crossed with max_block_size 8000 to 100000; horizontal merge, vertical merge on a remote disk (merge_algorithm = 'Vertical' confirmed in part_log), mutation, and apply_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, prefetch and subcolumn suites ran on both arms: the failing sets differ only by tests that fail before the change, none after.

Version info

  • Merged into: 26.8.1.750 (included in 26.8 and later)

groeneai and others added 2 commits August 2, 2026 08:45
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]>
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two review rounds by an independent model, adjudicated against the code. Round 1 raised one blocker
and one major; both are resolved below. Round 2 raised no blockers and no majors, and an independent
gate re-review of the round-2 delta returned zero findings.

❌ Blockers

# Finding Verdict
1 The ownership authorization does not cover the continue_reading regime: seek_to_mark is !was_prefetched && !continue_reading && !read_without_marks, and the new ownership test only feeds the first term, so a correctly-identified non-owner still skips its seek on a continuation block. AGREE on the fact, resolved by scope. The continue_reading term needs no claim at all: every write site of prefetched_streams sits under the prefetch gate, so with prefetch off the map is empty and this change is provably inert, yet the corruption still occurs there. Measured: pre-fix and fixed binaries produce byte-identical output at 11 of 11 prefetch = 0 cells, across two fixtures crossed with max_block_size 1000 to 100000. So that is a distinct pre-existing defect, not a hole in this fix, and it is tracked on its own. Two checks before accepting that: this change is never worse in that regime (at every prefetch = 1 cell it is equal or strictly better, 40000 to 32000 wrong rows at max_block_size = 8000, and three aborts become completed reads), and the new test cannot become flaky from the residual, since its 100-row fixtures are a single block at every max_block_size the runner draws. The description now states this limitation rather than implying general correctness.

⚠️ Majors

# 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_method is randomized over read, pread, mmap and pread_threadpool, and ReadBuffer::prefetch is 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's prefetch increments 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 erase sites 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, MergeTreeReaderCompact has no equivalent and serves as a control, so no sibling carrier is left unfixed.

Session id: cron:clickhouse-review-slot-50:20260802-115400

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One clickhouse local invocation, no runner, no concurrency, no randomization; 100% of rows wrong under the trigger, verified at 10, 100 and 5000 rows. The SELECT in the description is the whole reproducer.
b Root cause explained? Yes. With share_nested_offsets, ISerialization::getFileNameForStream rewrites an offsets substream's prefix to the Nested table name, so every arr.* sibling names one on-disk stream. MergeTreeReaderWide recorded a prefetched stream by name only, and the data getter consumed that as "this stream is positioned for the column about to read it". The re-added subcolumn claims the shared stream, so the sibling's mark seek is suppressed, the sibling reads from where the subcolumn stopped, gets no usable offsets, returns 0 rows, is nulled in readRows, and is then correctly default-filled.
c Fix matches root cause? Yes. The claim now records which column made it and authorizes only that column. No widened bound, no no-random-* tag on an existing test, no dataset reduction, and no guard at the symptom site: the fill layer is proven innocent and untouched.
d Test intent preserved / new tests added? Yes. No existing test was modified or weakened. One new stateless test with eleven assertion rows, four of them controls, plus a printed part type so a run that drew the wrong part type is visible instead of vacuously green. Three vacuous oracle forms were identified and avoided, and the test asserts its own non-vacuity twice: EXPLAIN header = 1 proves both columns reach the reader, and a liveness row fails the test if a randomized filesystem_prefetches_limit would skip prefetching altogether. Both guards were verified to be falsifiable, not decorative: each was made to fire.
e Both directions demonstrated? Yes. Fails before (100 of 100 rows wrong) and on a separate pristine-master build, passes after, with build ids recorded per arm. Additionally, reverting only the ownership comparison makes the new test fail with output byte-identical to the pre-fix output, so the test is provably load-bearing on this exact change; two -Werror diagnostics on intermediate mutant spellings are independent evidence that the new owner argument is genuinely consumed. Build ids are not bit-reproducible in this tree, so each arm was verified by behaviour rather than by hash.
f Fix is general across code paths? Yes. All 16 lines carrying this state are in one file pair and were enumerated; both claim sites are fixed, not only the reported one. MergeTreeReaderCompact has no equivalent state and is covered as a control. The horizontal-merge, vertical-merge, mutation, on-the-fly-mutation and read_without_marks paths were each measured rather than reasoned about; merges and mutations write correct data, so this is a read-path defect only. The multi-block continue_reading regime was measured separately, across max_block_size 1000 to 100000 on two fixtures: it carries a prefetch-independent defect that reproduces identically with and without this change (byte-identical output at every prefetch = 0 cell, 11 of 11), so it is pre-existing and is tracked on its own rather than fixed here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Measured with Array(Nullable(UInt64)) and Array(LowCardinality(String)) siblings, two and three siblings, both read orders, single granule and 13 and 1250 granules, Wide and Compact parts, local and s3 and local_blob_storage disks, and index_granularity 1 to 65536 crossed with max_block_size 8000 to 100000. The wrapper, multi-granule, multi-sibling and both-order cases are in the test.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No new setting, no default change, no serialization or on-disk format change, so no SettingsChangesHistory.cpp entry is required. Existing parts are read exactly as before; only an in-memory seek decision changes. The user-visible change is wrong results becoming correct results.
i Invariants and contracts preserved? Yes, and the change enforces one the file already documents in readRows: positions for all streams must be kept in sync, so no seeks may be skipped. prefetched_from_mark's mark-level invalidation is untouched; the clear at the end of readRows is what makes a per-call column position a valid owner token; the seek_to_mark expression is byte-for-byte unchanged, so read_without_marks still never seeks and continue_reading still never re-seeks mid-continuation. The map is reader-local and only touched on the reading thread, so no new concurrency contract. Error and early-return paths are unaffected: the two erase calls remain, and dropping a claim is conservative because it forces a seek.

Session id: cron:clickhouse-impl-slot-7:20260802-074100

@groeneai

groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @CheSema, could you review this? With share_nested_offsets every arr.* sibling names one offsets stream, but MergeTreeReaderWide recorded a prefetched stream by name only, so a re-added subcolumn's prefetch suppressed the surviving sibling's mark seek: the sibling read from the wrong position, came back empty, and was then default-filled. The claim now records which column made it.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bbb3654]

Summary: ✅


AI Review

Summary

This PR narrows MergeTreeReaderWide's prefetch ownership from "stream name only" to "stream name + requesting column" and adds a regression test for shared Nested offsets after DROP COLUMN + ADD COLUMN. That fixes the first-read prefetch case, but the same wrong-results path is still present once the same range is read through a continuation block, so the user-visible bug is not fully fixed yet.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeReaderWide.cpp:647] The new owner token is ignored as soon as continue_reading becomes true. MergeTreeRangeReader::DelayedStream::readRows sets continue_reading = true after the first chunk, prefetchForAllColumns can still let the first column claim the shared offsets stream at the current cursor, and the sibling then reaches this line with was_prefetched == false but still skips seekToMark because of !continue_reading. For a query that spans more than one readRows call, the sibling still reads from where the first column stopped and can return wrong results again. The new many granules test does not cover this because numbers(100) stays below the randomized max_block_size floor and never exercises the continuation path.
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

Metric Baseline Current Δ
Lines 80.90% 86.50% +5.60%
Functions 91.40% 91.90% +0.50%
Branches 73.00% 78.70% +5.70%

Changed lines: Changed C/C++ lines covered: 36/36 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 2, 2026
@PedroTadim PedroTadim self-assigned this Aug 2, 2026
/// 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bbb3654

CI is fully finished on this head and there are no failures to own.

Check / test Reason Owner / fixing PR
(none) - -

174 check-runs: 156 success, 18 skipped (not scheduled for this change), 0 failure / timed_out / cancelled. Config Workflow and Finish Workflow both success. CIDB reports 0 FAIL/ERROR rows for this PR.

Session id: cron:our-pr-ci-monitor:20260802-180000

@PedroTadim

Copy link
Copy Markdown
Member

@Avogar can you give a final look? The PR is small

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 4, 2026
Merged via the queue into ClickHouse:master with commit 5090eb7 Aug 4, 2026
179 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 4, 2026

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@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

@PedroTadim

Copy link
Copy Markdown
Member

#112769 maybe also should be reverted

@Avogar

Avogar commented Aug 5, 2026

Copy link
Copy Markdown
Member

My fix seems like a duplicate of #113225. This one looks good. @groeneai when revert is merged, we can add a test from this PR to make sure #113225 alone fixes it.

#112769 also look suspicious. @groeneai check if this PR is needed or #113225 alone fixes everything.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed on the revert, and thanks for the root cause. Reading the shared substream once is the
right layer; my change authorized a second physical read instead of removing it, and the
getNameInStorage() remapping you point at is the actual defect.

On #112769 I measured rather than reasoned from the diff. Five debug builds in one tree, each
arm's SELECT lower(buildId()) asserted against its own readelf -n before every verdict.
Arm A is exactly #113461's head (5e99f4a2c961: #112769 + #113225, #112997 reverted); arm B is
arm A with #112769's call-site decision reverted; arm C has neither fix; arm E has #112769
without #113225.

#112769 is not needed. #113225 alone covers it.

oracle A (both) B (no #112769) C (neither) E (no #113225)
03742 (#112769's own test) pass pass abort pass
04770 (#113225's test) pass pass abort crash after row 1
04756 (#112997's test) pass pass 3 wrong rows 3 wrong rows
14-case probe: DDL and sibling DEFAULT, MODIFY, on-fly mutation, share_nested_offsets = 0, true Nested(), Map member 14/14 14/14, byte-identical abort crash at Map
379 nested/subcolumn tests 298 OK / 48 FAIL same, fail set identical, 0 only-in-B

The 48 fail on both arms for harness reasons (CLUSTER_DOESNT_EXIST and similar; my node has no
cluster), so only the set difference is meaningful, and it is empty.

Mechanism, so this is not merely a green run: I instrumented the predicate to log both spellings
per column. They genuinely disagree 17 times (arr.nested.b resolves nameInStorage=arr, so
the pre-#112769 parent lookup fails), yet the output is identical, because #113225 repaired the
fall-through path itself. getSubcolumnsOfNested now groups by the column in storage and
fillMissingColumns resolves the type from the metadata shape, so reaching that path with the
wrong parent name no longer builds the wrong column. #112769 became dead weight the moment
#113225 landed. git revert of it now conflicts, since #113225 edited the helper it added.

One caveat before it goes: arm E shows #112769 alone does not fix 04770 and crashes on the
Map member case. Reverting #112769 is fine; please keep #113225.

On the test: 04756 passes on #113461's head, so #113225 does fix that shape. Once the revert is
merged I will open a test-only PR re-adding it, and link it here.

Two residuals from my earlier rounds that bear on your fix, both measured:

  • Forcing the seek in the continue_reading case is unsound rather than incomplete.
    seek_to_mark seeks to from_mark, which on a continuation call is not the resume row
    (DelayedStream::readRows passes current_mark unchanged), so it rewinds and re-reads
    consumed rows. One shared read via the substreams cache avoids this entirely.
  • The multi-block corruption also occurs at local_filesystem_read_prefetch = 0, where my diff
    was provably inert (prefetched_streams is only written under the prefetch gate). Tracked
    separately; Fix wrong results reading a re-added Nested member subcolumn #113225 may cover it, and I will check once the revert lands.

@Avogar

Avogar commented Aug 5, 2026

Copy link
Copy Markdown
Member

@groeneai if you agree, you can revert #112769 manually (as you said there are conflicts) - remove dead code, keep the test, ping me in the PR

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

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
added rather than sitting beside it:

That is exactly arm B of the matrix above, so it is already measured: 03742, 04770, 04756 and
the 14 probe cases are byte-identical to arm A. 03742_test_flattened_crash stays untouched.

The one wart is that the restored predicate reads requested_column->getNameInStorage() two
lines below :416, where you deliberately stopped trusting that spelling. It is harmless here
because the remapped case now falls through to the path #113225 repaired, which is why arm B is
green, but say the word if you would rather I resolve the parent through
tryGetColumnInStorage at the call site instead and leave no raw read behind.

Separately, #113461 is merged and 04756 is no longer on master, so the test-only PR re-adding it
is unblocked. I will send that one too and link it here.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Correction: I was wrong about #112769, and it should not be reverted. isSubcolumnOfAvailableColumn is load-bearing. Sorry for the wasted round.

My "14/14, byte-identical" result was a vacuous pass. The corpus I ran it on never reads a .null subcolumn at all (grep -c '\.null' is 0 in both probe files, while arr.nested. matches 6 and 5, so subcolumn reads were present and null-map reads were not), and it contains no MODIFY COLUMN that introduces nullability. The single MODIFY COLUMN in it adds a Tuple element.

The distinction the corpus missed: after DROP COLUMN + ADD COLUMN the stored data really is gone, so default-filling the subcolumn is correct. After a metadata-only T -> Nullable(T) MODIFY the data is still on disk, so default-filling is wrong results. Every green signal I cited uses DROP+ADD:

  • 03742 has 14 DROP/ADD and zero MODIFY COLUMN; its arr.nested.null reference row is [NULL], which is correct there.
  • 04770 is DROP+ADD as well, and asserts only sum(length(...)), never a null-map value.
  • 04161 declares zero dotted columns (its only two dotted-backtick hits, :93 and :114, are comment lines), and a non-dotted name is never remapped, so both spellings agree on every cell of it.

Mechanism on current master. MergeTreeBlockReadUtils.cpp:130 injects the parent under its literal name arr.n. IMergeTreeReader.cpp:66-67 runs the requested list through Nested::convertToSubcolumns (share_nested_offsets defaults true, MergeTreeSettings.cpp:280), and NestedUtils.cpp:544 rebuilds arr.n.null as NameAndTypePair{"arr", "n.null", ...}, so getNameInStorage() becomes arr while the injected parent is still keyed arr.n. NamesAndTypesList::contains is an exact compare (NamesAndTypes.cpp:275), so the pre-#112769 inline predicate asks contains("arr") and gets false where the helper asks contains("arr.n") and gets true. Not deferring reaches createColumnWithDefaultValue, which builds an all-NULL null map where all-zero is correct.

Measured with a single-variable A/B, only inplaceBlockConversions.cpp differing between arms, each arm's SELECT lower(buildId()) asserted against its own readelf -n, 3/3 deterministic:

shape, read on the part written before the MODIFY helper inline predicate
dotted arr.n -> Array(Nullable(String)), read arr.n.null [0,0] [1,1]
declared Nested(n String, i UInt64), same MODIFY [0,0] [1,1]
dotted Array(Tuple(a Nullable(UInt8))), read arr.t.a.null [0] [1]
dotted single member, no sibling in the group [0,0] [1,1]

In the same binary the parent reads ['a','b'] and arrayMap(v -> v IS NULL, arr.n) reads [0,0], so the [1,1] null map contradicts both. Unchanged across arms, as controls: a non-dotted column, a non-Array dotted member, share_nested_offsets = 0, and the Memory engine. Default settings, no experimental gate, and Compact parts diverge too.

That also answers your question about the raw getNameInStorage() read two lines below :416: resolving the parent through tryGetColumnInStorage is not a style preference, it is the correct behaviour. The raw read is exactly what returns arr for a remapped pair.

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.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

The test for the dotted case is #113646. It pins the shape from the correction above: reading arr.n.null on a part written before a metadata-only T to Nullable(T) MODIFY, on both a Wide and a Compact part, with the parent read and arrayMap(v -> v IS NULL, ...) alongside as controls.

Restoring the pre-#112769 inline spelling makes both witness rows read [1,1] where [0,0] is correct, and leaves all five control lines unchanged. Running every plausible existing pinner on that same binary, all pass: the four stateless tests that hold both a MODIFY COLUMN ... Nullable and a dotted or declared-Nested column (03210, 04161, 04338, 04697), plus 03742 and 04770. The uniform reason is that a .null read on a dotted column occurs zero times in all six, and that read is exactly what the remap rewrites.

The 04756 re-add is prepared on its own branch and I will link it here when it opens.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

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
of its eleven assertions are live witnesses against a build with #113225's getSubcolumnsOfNested
and type-computation repairs reverted, reporting 100, 100 and 66 mismatching rows where 0 is
correct; the other eight hold on both arms and are kept as controls. Nothing from #112997 is
needed for them.

Two changes from the file this PR carried. The no-random-merge-tree-settings tag is dropped,
since the test already pins index_granularity, min_bytes_for_wide_part and
min_rows_for_wide_part in its CREATE TABLE ... SETTINGS clause and share_nested_offsets is
not randomized; 250 randomized runs are green without it. And three comments that described the
prefetch stream ownership #113461 reverted now state what the assertions below them actually pin.

pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 7, 2026
…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.
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 7, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants