Repository navigation
Populate nested columns before creating ColumnArray - #112504
Conversation
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]>
|
Workflow [PR], commit [3931fb8] Summary: ✅
AI ReviewSummaryThis PR removes the external construction pattern that let Final VerdictNo new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 289/300 (96.33%) · Uncovered code |
…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]>
…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`.
|
🕵 @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 |
|
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:
On the server death: I cannot attribute it from this run, and not because there was nothing to find. The job was SIGKILLed before On the silence, which is the half I can fix. 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. |
|
Fixing PR: #113039 Your hypothesis is partly refuted, and the refutation is the finding. The missing crash trace and The silence itself has a concrete cause. That does not fix #108689 and makes no claim about OOM. It makes the class attributable, which is Your change is exonerated separately: 22 job-level errors over 8266 runs in 35 days (0.27%), 0 on |
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<>()); |
There was a problem hiding this comment.
Interesting if it will make the code any slower.
There was a problem hiding this comment.
Plan B in case it will - move this extensive check to debug builds.
alexey-milovidov
left a comment
There was a problem hiding this comment.
Fantastic change, I love it!
|
Hi @alexey-milovidov — while reviewing this PR I found the following:
Happy to discuss — close anything that's wrong or already addressed. |
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]>
Changelog category (leave one):
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
ColumnArrayconstructor 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 theColumnArrayfirst, with an empty nested column and an offsets column that is pre-sized but not yet filled, and populate both afterwards throughgetDataandgetOffsets. 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 thensizeAtreports 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
ColumnArrayfrom them, so aColumnArraynever 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, thesplitBy*/token family (FunctionTokens.h),timeSlots,geohashesInBox,synonyms,h3kRing,h3HexRing,h3Line,h3ToChildren,h3PolygonToCells,h3PolygonToCellsWithContainment,s2GetNeighbors,currentRoles,currentProfiles,getTypeSerializationStreams,addressToLineWithInlines,JSONAllPaths/JSONDynamicPaths/JSONSharedDataPaths(JSONPaths.cpp) andJSONAllValues. 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:
ColumnArrayitself (cloneResized,filter,permute,replicate, ...) grow the nested column and the offsets together through the accessors of the class that owns the invariant;StoragePostgreSQLfills the array withIColumn::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.