Repository navigation
Fix reading a LowCardinality subcolumn of Nullable(Tuple(...)) together with its parent - #112232
Conversation
…entation An extracted subcolumn of a Nullable(Tuple(...)) column whose element is a non-nullable LowCardinality(T) has its type promoted to LowCardinality(Nullable(T)) so that it can carry the parent's NULLs. On a Compact part MergeTreeReaderCompact therefore creates the result column already promoted, and SerializationNullableWithParentNullMap built its per-range deserialization buffer from it. The nested SerializationLowCardinality deserializes into that nullable-dictionary buffer and publishes it to the shared substreams cache, so the published substream is not the on-disk LowCardinality(T) representation. A sibling reader of the same streams, that is the parent subcolumn or assumeNotNull() over it, adopts the cached column directly and ends up holding a nullable dictionary under a declared type that is not nullable. Depending on the build that surfaces as wrong values, Code: 49, or an abort on a bad cast. Nothing mutated the published column; it was never the right representation. Build the buffer from the pre-promotion type instead, which NullableSubcolumnCreator still knows and now passes to the wrapper, and let the existing promotion in applyParentNullMapToExtractedSubcolumn promote the private per-range column afterwards. That keeps a single promotion owner and leaves the published substreams in the representation a reader of the parent expects. The new constructor parameter enters getHash() so the two flavours of the wrapper cannot share a pooled instance. Promoting on a private copy at the in-place promotion instead was evaluated and measured to be a no-op: while the buffer is pre-promoted, that code is unreachable, because its guard is !nestedIsNullable(). Wide parts were unaffected, since MergeTreeReaderWide reads each column separately, and so was the getSubcolumn branch taken when write_marks_for_substreams_in_compact_parts is disabled, which already copies. Regression from ClickHouse#108679, which introduced this read path. Affects master and 26.7. Related: ClickHouse#100394
…t and the pooling hash
Length-prefix the on-disk type name in getHash(), matching SerializationNamed and
SerializationLowCardinality, the two in-tree serializations that fold a variable-length
string into a pooling key. No behaviour change: the name is the last field hashed and
SipHash mixes the total byte count, so no collision was reachable.
The test's leading comment stated the pre-fix behaviour as the expectation while the
assertion checks the opposite; reworded to the invariant actually asserted, which is that
the parent's dictionary must stay non-nullable and must not gain a NULL placeholder when
the child subcolumn is read in the same query. The reference is regenerated because the
file uses -- { echo }.
The PR description previously asserted three release-build symptoms without measuring
them, two of which contradicted each other. Measured on the official 26.6.2.120 and
26.7.2.26 binaries: 26.6 is correct on every query, while on 26.7 the same shape gives
unstable wrong values for a LowCardinality(UInt32) element, Code: 49 for the
assumeNotNull projection, and a libc++ string_view hardening termination for a
LowCardinality(String) element. The termination is real but is not a bad cast, so that
wording is gone.
Co-Authored-By: Claude Fable 5 <[email protected]>
The test's fails-without-the-fix property holds only on the branch of MergeTreeReaderCompact::readData that reads through the parent-null-map wrapper, which is selected by write_marks_for_substreams_in_compact_parts. Pin it to 1 on the five Compact carrier tables so a server- or job-level override cannot silently move the test onto the getSubcolumn branch, which already copies and was never broken. The wide-part table and the deliberate top-level non-carrier control are left alone. Correct the wide-part comment as well. MergeTreeReaderWide keys its SubstreamsCache by name in storage and does share one cache between a parent subcolumn and its child, so "each column gets its own read" was the wrong reason; wide is simply measured as unaffected. The release-build symptom for a LowCardinality(String) element was re-measured with the exit status taken directly from the binary invocation: the process is killed by SIGABRT, exit status 134, on four of four runs with no rows on stdout. The earlier record of status 0 came from reading $? after a pipeline.
Internal second-model review - adjudication log (click to expand)Pre-publication review by an independent model (engine: codex), plus my own cold review of the
Severity: ❌ blocker / |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-43:20260728-051900 |
|
cc @Avogar @CurtizJ - could you review this? It fixes a regression from #108679: an extracted subcolumn of |
|
Workflow [PR], commit [5c2b049] Summary: ✅
AI ReviewSummaryThis PR fixes the Final Verdict
|
…on test assumeNotNull has an unspecified result when its argument is NULL, so the 04651 regression test must not pin the values it produced on the parent-NULL rows: those values are today's implementation detail and would make the test fail on unrelated changes even with the shared-cache bug still fixed. Every assumeNotNull call is now wrapped in ignore(), which keeps the call evaluated while dropping the value comparison. Keeping it evaluated is required: what the bug breaks is the function's return-type post-condition (Expected Tuple(b UInt32), Got Tuple(Nullable(UInt32))), not the value, so a form that removes the call would remove the coverage. The two other forms suggested in review were measured and rejected: toTypeName(assumeNotNull(...)) is constant-folded at analysis time, so assumeNotNull is never executed and a build with the fix reverted passes; restricting the comparison to non-NULL rows removes the parent-NULL rows, which are exactly the rows that trigger the promotion. With ignore(), a build with the fix reverted still fails with the original message. Reported by the automated review on the pull request.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 20/21 (95.24%) · Uncovered code |
|
cc @nihalzp |
alexey-milovidov
left a comment
There was a problem hiding this comment.
That's quite complex, but looks alright.
|
The backport ask covering this PR is on #111949, together with the per-branch measurements: #111949 (comment) Two points from there that apply to this PR specifically. The floor is |
Related: #100394
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed reading a subcolumn of a
Nullable(Tuple(...))column whose element is a non-nullableLowCardinality(T)when the same query also reads the parent subcolumn. On a Compact part the parent returned wrong values, or the query failed withUnexpected return type from assumeNotNull, or the server was killed by astring_viewhardening assertion, because the extracted subcolumn was deserialized into aLowCardinality(Nullable(T))buffer whose substreams were then shared with the parent's read.Description
Reported as an
AST fuzzer (amd_debug)failure on #100394: CI report.This is not an analyzer or executor type-derivation problem. It is a regression from my own merged #108679, which introduced this read path. Carriers are
masterand26.7: both #108679 commits are ancestors of26.7and ofmaster, and of neither26.6nor anything older.I measured the official release binaries
26.6.2.120and26.7.2.26on the shape below, a Compact part withindex_granularity = 1.26.6is correct on every query. On26.7the same queries give three different outcomes, selected by the element type and the projection list rather than by build flags:26.6.2.12026.7.2.26SELECT x.a FROM t, the parent aloneSELECT x.a.b, x.a FROM t,LowCardinality(UInt32)element(32438),(31553),(31542),(31253)on four runs where(2)is correctSELECT x.a.b, x, x.a, isNull(x.a.b), assumeNotNull(x.a) FROM tUnexpected return type from assumeNotNull. Expected Tuple(b UInt32). Got Tuple(Nullable(UInt32))SELECT x.a.b, x.a FROM s,LowCardinality(String)elementSIGABRTon 4 of 4 runs, exit status 134, no rows on stdout:libcxx/include/string_view:331: libc++ Hardening assertion __len <= ... failedThe last row is a real termination on a release build, and it is not a bad cast: the parent reads a nullable dictionary's index data under a declared type that is not nullable and derives a nonsensical string length, which libc++ hardening catches, and
std::__libcpp_verbose_abortthen callsstd::abort().Code: 49and the termination are not the same condition selected by build type: on the same release binary theUInt32element throws while theStringelement aborts. What the build type does change is the fate of thatCode: 49, sinceLOGICAL_ERRORis turned into an abort in debug and sanitizer builds, which is the form the fuzzer reported.Root cause
An extracted subcolumn of
Nullable(Tuple(...))with a non-nullableLowCardinality(T)element has its type promoted toLowCardinality(Nullable(T)), so that it can carry the parent's NULLs.MergeTreeReaderCompacttherefore creates the result column already asLowCardinality(Nullable(T)), andSerializationNullableWithParentNullMap::deserializeBinaryBulkWithMultipleStreamsbuilt its per-range deserialization buffer from it withcolumn->cloneEmpty().The nested
SerializationLowCardinalitydeserializes into that nullable-dictionary buffer and publishes it to the sharedSubstreamsCache. The published substream is therefore not the on-diskLowCardinality(T)representation. A sibling reader of the same streams in the same query, that is the parent subcolumnx.aorassumeNotNull(x.a), adopts the cached column directly, so the parent holds a nullable-dictionary column while its declared type is stillNullable(Tuple(b LowCardinality(UInt32))), and thecolumnMatchesTypepost-condition inExpressionActionsthrows.Nothing mutates the published column. It simply was never the right representation. That is also why the parent on its own is always correct and only becomes wrong when the child is read in the same query: without the child read there is nothing in the cache to adopt.
Reproducer
The sharpest form of the bug needs no NULL in the data at all. On a table with zero parent-NULL rows,
SELECT dumpColumnStructure(x.a)andSELECT x.a.b, dumpColumnStructure(x.a)must report the same dictionary size, and before this change the second one reported one entry more: the parent's dictionary gained a NULL placeholder purely because the child was also selected. That equality is asserted in the new test, and it is what distinguishes this fix from one that merely stops the exception.The fix
Deserialize into a buffer that has the on-disk representation, and promote the private per-range column afterwards:
SerializationNullableWithParentNullMapnow carries the pre-promotion (on-disk) type, passed in at construction byNullableSubcolumnCreator, which is where that type is still known. When it is set, the per-range buffer is built from it instead of from the promoted result column.getHash(), otherwise the two flavours of the wrapper would collide on a single pooled instance.applyParentNullMapToExtractedSubcolumnbecomes reachable and correct and remains the single promotion owner. It runs on theIColumn::mutated private column, so it can never touch the published one. Deleting it now makes the reproducer fail withCannot apply a null map to LowCardinality(UInt32) with a non-nullable dictionary, so that line is load-bearing.I first evaluated promoting on a private copy at the in-place promotion instead, and measured it to be a no-op: while the buffer is pre-promoted, that code is unreachable, since its guard is
!nestedIsNullable().Wide parts were measured and are not affected. With
write_marks_for_substreams_in_compact_parts = 0the reader takes thegetSubcolumnbranch, which already copies, so that path was correct too, and the new test pins that setting to1on its Compact tables so it keeps exercising the branch that was broken. A top-levelNullable(Tuple(b LowCardinality(UInt32)))without the outerTupleis not a carrier either.The change is in the serialization layer, so it also reaches
StorageLog, which builds this wrapper throughIDataType::getSerializationand likewise shares oneSubstreamsCacheper name in storage across subcolumn reads. I am not claiming a Log symptom: reading this shape from aLogtable fails withCode: 33on26.6, on26.7, and on master alike, so that is a separate pre-existing problem which this change neither causes nor fixes.There is no on-disk format change, no new or changed setting, and the non-LowCardinality flavour of the wrapper is unchanged.
Testing
New stateless test
04651_nullable_tuple_lowcardinality_subcolumn_shared_cache, covering the reported query shape, both projection orders, the zero-parent-NULL structural assertion, the leaf typesLowCardinalityofUInt32,String,FixedStringandDate, a multi-element inner tuple, an already-LowCardinality(Nullable(T))leaf (which must not be de-nullabilised), a wide-part control, a top-levelNullable(Tuple(...))control, and a multi-range read with a smallmax_block_size.Every value in the test was cross-checked against an
ENGINE = Memorytwin of the same shape, which has no read path and therefore no substreams cache. The test fails on master and passes with this change. It ran 50 times with the default randomization, and the wholenullable_tupletest family ran 50 times each, 1150 runs in total, with no failures.Note that the fix does not restore the
26.6output of the child subcolumn: on a parent-NULL rowx.a.bis\Nhere and was1or3on26.6, because the promotion toLowCardinality(Nullable(T))is exactly what #108679 added. What is restored is that reading the child no longer changes what the parent returns.ColumnsOwnershipValidator(#110471) does not catch this, because the published column is legitimately shared. Only its representation was wrong. I did not extend the validator here.26.7is affected, so this wantsv26.7-must-backportafter merge.Version info
26.8.1.474(included in26.8and later)