Skip to content

Populate nested columns before creating ColumnArray - #112504

Merged
alexey-milovidov merged 10 commits into
masterfrom
columnarray-populate-nested-first
Aug 9, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
columnarray-populate-nested-first

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

Implements https://github.com/ClickHouse/ClickHouse/pull/109212/changes#r3677410450 - "Why doesn't this code populate nested columns first, and only then create the resulting array?"

The ColumnArray constructor checks that the last offset is equal to the size of the nested column, but it skipped the check when the nested column was empty. That exception existed because of a construction idiom used by a number of array-producing functions: create the ColumnArray first, with an empty nested column and an offsets column that is pre-sized but not yet filled, and populate both afterwards through getData and getOffsets. Such a column carries uninitialized offsets at construction time, so nothing can be validated there, and the exception left a hole: a column with, say, offsets = [1] and no elements at all passed construction unnoticed, and then sizeAt reports a size that is not there and the consumers of the column read the nested column out of bounds.

This removes the idiom instead of the check. Every producer now fills the nested column and the offsets first and creates the ColumnArray from them, so a ColumnArray never exists in an inconsistent state, and the check in the constructor applies to every construction with non-empty offsets.

The functions that were built this way: arrayRandomSample, array, the splitBy*/token family (FunctionTokens.h), timeSlots, geohashesInBox, synonyms, h3kRing, h3HexRing, h3Line, h3ToChildren, h3PolygonToCells, h3PolygonToCellsWithContainment, s2GetNeighbors, currentRoles, currentProfiles, getTypeSerializationStreams, addressToLineWithInlines, JSONAllPaths/JSONDynamicPaths/JSONSharedDataPaths (JSONPaths.cpp) and JSONAllValues. The rewrite is mechanical - the same values are written into the same containers, only through local column objects - so no behaviour change is expected for any of them.

Two places keep building the array before it is filled, on purpose:

  • the methods of ColumnArray itself (cloneResized, filter, permute, replicate, ...) grow the nested column and the offsets together through the accessors of the class that owns the invariant;
  • StoragePostgreSQL fills the array with IColumn::insert, which appends to the nested column and to the offsets in one step, so the column is consistent after every insert.

Also adds a unit test for the offsets validation in the constructor.

This is also what was blocking the monotonicity check in #109212: with the empty-nested-column exception gone, the constructor is a place where the offsets can be validated for real.

The `ColumnArray` constructor checks that the last offset is equal to the
size of the nested column, but skipped the check when the nested column was
empty. That exception was needed because a number of array-producing
functions create the `ColumnArray` first - with an empty nested column and
an offsets column that is pre-sized but not yet filled - and populate both
afterwards through `getData` and `getOffsets`, so at construction time the
offsets are still uninitialized.

Remove the idiom instead of the check: fill the nested column and the
offsets first and create the `ColumnArray` from them, so it never exists in
an inconsistent state, and check the offsets on every construction with
non-empty offsets. Previously a column with, say, `offsets = [1]` and no
elements at all passed construction unnoticed, and then `sizeAt` reports a
size that is not there and the consumers read the nested column out of
bounds.

The methods of `ColumnArray` itself keep growing the nested column and the
offsets together through the accessors of the class that owns the invariant,
and `StoragePostgreSQL` fills the array with `IColumn::insert`, which
appends to both in one step.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3931fb8]

Summary: ✅


AI Review

Summary

This PR removes the external construction pattern that let ColumnArray exist with unvalidated offsets, strengthens the constructor to reject empty-offset and non-monotonic cases, and updates the runtime dataflow statistics path to stop sampling partially read array columns on compact parts. I did not find a remaining correctness, safety, or compatibility issue in the current head; the prior concern about poisoning automatic_parallel_replicas input-byte estimates is fixed, and the current CI for PR #112504 is all green.

Final Verdict

No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.70% -0.10%

Changed lines: Changed C/C++ lines covered: 289/300 (96.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 30, 2026
Comment thread src/Columns/ColumnArray.cpp Resolved
alexey-milovidov and others added 2 commits July 31, 2026 07:53
…est under sanitizers

Address review: the constructor guard skipped the case of empty offsets with
a non-empty nested column, so such an inconsistent ColumnArray (zero rows
reported, hidden elements carried) still passed construction. Treat empty
offsets as an implicit last offset of 0 and validate the nested column size
against it too.

Also guard the ColumnArray.InconsistentOffsetsAreRejected unit test with
DEBUG_OR_SANITIZER_BUILD: LOGICAL_ERROR aborts in debug and sanitizer builds
instead of throwing, so EXPECT_THROW cannot catch it there. This is what
failed the Unit tests (asan_ubsan, tsan, msan) jobs:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112504&sha=d55c8a4ff50952a05e8dfefbcb897dd7a4bbf450&name_0=PR

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Columns/ColumnArray.cpp Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 31, 2026
…format

The monotonicity check in SerializationArray::deserializeOffsetsBinaryBulk was gated on
settings.native_format, which is assigned in exactly two places (NativeReader.cpp:99 and
NativeWriter.cpp:80). The check belongs to the encoding, not to the format: the branch
right above it reads offsets either as sizes, accumulating them with a non-negative step
so the result is monotonic by construction, or as absolute values straight off the wire,
where a decreasing sequence is possible. Only the second branch needs verifying, and
Native is not its only user.

MergeTreeIndexGranuleSet::deserializeBinary and MergeTreeIndexBulkGranulesSet::deserializeBinary
set position_independent_encoding = false, so a skip index granule is read as absolute
offsets with no check, and then MergeTreeIndexGranuleSet::deserializeBinary calls getExtremes
on the result. With decreasing offsets, offsetAt(i) exceeds offsets[i] and that read walks
past the end of the nested column.

Keying the check on the encoding instead of the format covers those two readers and adds
nothing to MergeTree part reads, which do not set position_independent_encoding and so take
the sizes branch. The offsets column accumulates across range reads rather than being
rebuilt per call, so the scan is limited to the values this call appended, starting one
element early to keep the comparison across the range boundary. Native keeps its current
error code and message.

The earlier ColumnArray constructor check is dropped: it cannot see these offsets, since
the read path builds the column through DataTypeArray::createColumn and fills it in place,
and ClickHouse#112504 removes the constructor's !data->empty() exception separately.
…structor

Matching only the last offset with the size of the nested column is not
enough: a decreasing offset in the middle makes `sizeAt` underflow to a
huge value, so consumers read the nested column out of bounds even
though the last offset is correct. Check the whole offsets sequence for
monotonicity, following the precedent in `SerializationArray`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112504&sha=1f924407d1fc866769493d5ba8df685640afa21a&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The server disappeared after ~4290/12235 tests with ConnectionRefusedError and no crash trace or sanitizer report, then the job produced no output at all for almost two hours until the 9000 s timeout killed it. No test failed. This matches #108689 (runner-wide OOM / "Server died" on stateless runners) and is unrelated to this change, which only affects ColumnArray construction. Merged master and re-triggered CI.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator

I confirmed the shape, and the two-hour silence turns out to have its own root cause, separate from whatever killed the server.

Timeline from the job log, which is the only artifact this run produced:

  • 08:39:02, test 4291/12235 passes.
  • 08:40:56, Hung check failed: server is not responding, alongside Cannot collect C stacktraces under ASan: debugger attach is disabled.
  • 08:41:21, clickhouse-test prints StopTesting and exits.
  • 08:41:21 to 10:36:22, zero output, then praktika's 9000 s timeout SIGKILLs the container.

On the server death: I cannot attribute it from this run, and not because there was nothing to find. The job was SIGKILLed before CHECK_ERRORS and COLLECT_LOGS, so no server log was ever uploaded (this job's links array holds job.log alone, against five for the sibling db disk, distributed plan, sequential, 1/3 job at the same sha) and check_ch_is_oom_killed never ran. The missing crash trace and sanitizer report are therefore a consequence of the harness dying, not evidence about the server. The one direct clue is in the ps dump: pid 611 is [clickhouse-serv] <defunct>, a zombie under clickhouse-watchd, so the process did terminate rather than merely stop answering.

On the silence, which is the half I can fix. run_tests in ci/jobs/functional_tests.py sets outer_timeout = global_time_limit + 900 if global_time_limit > 0 else None. The regular parallel suite is neither the flaky nor the targeted check, so global_time_limit stays 0 and the inner timeout is None; --global_time_limit appears nowhere in the log, which confirms that branch. Shell.run then does an unbounded stdout_thread.join(), and those reader threads end only at pipe EOF, which needs every write end closed. clickhouse-test starts test processes with start_new_session=True, while cleanup_child_processes signals only its own process group and its direct children's groups, so a grandchild in its own session survives holding the inherited stdout pipe. I reproduced this in isolation: the child exits at t=0.0 s while the reader thread stays blocked and reaches EOF only at t=25 s, when the orphan exits.

So a dead server costs about 1 h 55 m of runner time producing nothing, and discards precisely the diagnostics that would have identified the cause. That is why this class keeps landing as unattributable.

Scope: 22 job-level errors across 8266 runs of this check in 35 days (0.27 percent), 0 on master. #111789 moved the job to a 128 GiB runner and is present at this sha, but the class continued after it merged, so it is not resolved by it.

A fix task is created for the harness half and is being worked at full effort; I will post the fixing-PR link here. I found no existing PR for it.

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator

Fixing PR: #113039

Your hypothesis is partly refuted, and the refutation is the finding. The missing crash trace and
sanitizer report are not evidence about the server: the job was SIGKILLed by the 9000 s watchdog
before CHECK_ERRORS and COLLECT_LOGS, so those diagnostics were never produced, and
check_ch_is_oom_killed runs only inside COLLECT_LOGS, so the #108689 OOM signature could not
have appeared either way. The failing job's report has 1 link; the sibling job at the same sha
has 5.

The silence itself has a concrete cause. ci/jobs/functional_tests.py runs the suite as
clickhouse-test ... | ts | tee -a, and clickhouse-test spawned each test with
start_new_session=True and no stdout/stderr, so the bash -c "<test> > out 2> err" wrapper
inherited the write end of that pipe (the redirect binds only the command it execs). A test that
escaped into its own session outlived the worker, ts never saw EOF, tee never exited, and
Shell.run blocked in proc.wait() plus both reader joins. Measured on that shape: 12.03 s
inherited versus 0.03 s detached, with no timeout configured.

That does not fix #108689 and makes no claim about OOM. It makes the class attributable, which is
why it kept landing without evidence.

Your change is exonerated separately: 22 job-level errors over 8266 runs in 35 days (0.27%), 0 on
master, and the 11 hits in 14 days are 11 distinct PRs. #111789 is not the owner either; I
verified it present at the failing sha and the class continued after it merged.

alexey-milovidov and others added 3 commits August 3, 2026 21:00
The runtime dataflow statistics sampler (automatic parallel replicas)
serializes the columns straight out of the MergeTree reader, before
`fillMissingColumns` runs. A column under an unfinished on-the-fly
mutation (e.g. `CLEAR COLUMN`) is read partially at that point: only the
array offsets are read from the part and the nested column stays empty.
Serializing such a column goes through `ColumnArray::convertToFullColumnIfConst`,
which rebuilds the `ColumnArray` and now trips the constructor
consistency check with the exception `offsets_column has data
inconsistent with nested_column. Data size: 0, last offset: 1`.

Expose `IMergeTreeReader::partially_read_columns` and skip those columns
when building the sample, next to the existing skip of null (not yet
filled) columns.

Verified: the new test fails with LOGICAL_ERROR 3/3 before the fix and
passes 3/3 after it; `04329_array_tuple_fill_missing_column_bad_cast`
and `03634_autopr_input_bytes_estimation_compact` still pass.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112504&sha=184f05a3362a2678c17666d20a12023ef2e3f344&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
PR: #112504

Co-Authored-By: Claude Fable 5 <[email protected]>
…ly read columns

Skipping partially read columns in `toColumnsWithTypeAndName` broke the
accounting contract of `RuntimeDataflowStatisticsCacheUpdater::recordInputColumns`:
the compression ratio was derived from the surviving columns only, but applied to
the `read_bytes` of the whole block, so a block dominated by a partially read
array could cache a badly wrong `input_bytes` estimate for automatic parallel
replicas. It also needlessly dropped such columns on the `column_sizes` path,
which never serializes them.

Instead, pass the set of partially read columns down to `recordInputColumns`:
the `column_sizes` path (wide parts) keeps them - it only calls `byteSize` -
and the serialization path (compact parts) marks the statistics unsupported for
the query, because a compact part has no per-column byte split to subtract.

Co-Authored-By: Claude Fable 5 <[email protected]>
/// in the middle makes `sizeAt` underflow to a huge value, and the consumers read the nested column
/// out of bounds even though the last offset is correct. The offsets have to be non-decreasing.
/// The scan is linear, but it is cheap compared to filling the offsets in the first place.
const auto * non_monotonic = std::adjacent_find(offsets_data.begin(), offsets_data.end(), std::greater<>());

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Interesting if it will make the code any slower.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Plan B in case it will - move this extensive check to debug builds.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fantastic change, I love it!

@alexey-milovidov alexey-milovidov self-assigned this Aug 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 9, 2026
Merged via the queue into master with commit 9e423d6 Aug 9, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the columnarray-populate-nested-first branch August 9, 2026 23:20
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @alexey-milovidov — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

pull Bot pushed a commit to Mattlk13/ClickHouse that referenced this pull request Aug 17, 2026
arrayAutocorrelation accepts Array(Nothing) deliberately, because [] has that
type and arrayAutocorrelation([]) returns []. Both of its ColumnNothing
branches guarded on the column type alone, when the correct condition is type
and emptiness: ColumnNothing keeps only a row count and holds no readable
elements, so a length-N Array(Nothing) like [arrayMax([])] is a structurally
valid ColumnArray with zero accessible elements, and this function has no way
to represent it.

The non-const branch reused the input offsets next to a fresh empty
ColumnFloat64, producing offsets=[1] with 0 elements. Since ClickHouse#112504 the
ColumnArray constructor rejects that:

  Logical error: 'offsets_column has data inconsistent with nested_column.
  Data size: 0, last offset: 1'

which is an exception in release builds and an abort in debug and sanitizer
builds. The const branch instead zeroed the offsets, so it silently returned []
for any input length.

Both branches now reject a non-empty Nothing column with ILLEGAL_COLUMN, using
the message already used for this condition in assumeNotNull and in
IFunction::defaultImplementationForNothing. The empty case is unchanged. No
value is synthesized, because Nothing holds no values and any number produced
would be invented.

Found by the AST fuzzer (STID 2632-416b). Before ClickHouse#112504 this was a silent
wrong result: 26.7.4.15 returns [0]. ClickHouse#112504 is the detector and is correct.

arrayPartialAutocorrelation in the open ClickHouse#102160 carries the same defect in both
places.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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