Repository navigation
Fix out-of-bounds write reading a Parquet DECIMAL wider than declared - #113046
PedroTadim merged 6 commits into
Conversation
Reading a Parquet DECIMAL column whose physical element is wider than the ClickHouse type its declared precision maps to wrote past the end of the destination column. Reported as a SIGSEGV in DB::Parquet::Dictionary::index at roughly 60% of runs; in debug and sanitizer builds a chassert aborts instead. SchemaConverter::processPrimitiveColumn chose the decoder from the physical type but derived the destination type from the declared precision alone, and never assigned out_decoded_type. The caller therefore fell back to the declared-precision type and allocated the decode target from it: DECIMAL(9, 2) gives Decimal32, 4 bytes per element, while a physical INT64 decoder writes 8. IntConverter::isTrivial returns true whenever output_size is unset, so every consumer treated the column as a raw byte sink of input_size bytes per value. Such a file is legal Parquet. The specification permits INT64 for precision 1 to 18 and FIXED_LEN_BYTE_ARRAY of any length up to 32, so a DECIMAL(9, 2) stored as INT64 is valid and other writers emit it; rejecting the file would turn a crash into a regression. ClickHouse's own writer always pairs a Decimal<T> with FIXED_LEN_BYTE_ARRAY of sizeof(T), so no round-trip test caught this. Reconcile the two widths at the single function that decides both: when the width the chosen converter writes differs from the declared-precision width, set out_decoded_type to the Decimal type of the converter's width and let the existing castColumn path narrow it. max_precision is already the bucket precision of every sub-branch (9, 18, 38, 76), which map to exactly 4, 8, 16 and 32 bytes. out_inferred_type is untouched, so schema inference still reports the declared precision, and every downstream copy site becomes correct without a per-site bounds check. allow_stats now keys off the decoded width, which is the width convertField actually produces; on the affected shape it was previously true while convertField emitted a DecimalField<Decimal64> into a Decimal32 key range, and on the explicit-wide-hint path it stays true so pruning is preserved. Both defective physical types are covered. The FIXED_LEN_BYTE_ARRAY branch carries the same defect as INT32/INT64: its precision and length bounds are upper bounds within a bucket and the chain is ordered, so an oversized type_length falls through to a wider bucket while the inferred type still follows the declared precision. BYTE_ARRAY decimals bucket on precision only and are unaffected. A file whose values exceed its own declared precision now raises DECIMAL_OVERFLOW instead of corrupting memory. Reading it losslessly remains possible with an explicit wider type hint, so no workflow loses capability. Closes ClickHouse#112659
The test asserted only scalar results, so the change that stops row group statistics of the physical width from being compared against a key range of the narrower declared type had no coverage: reverting it left every arm green. That comparison can prune row groups holding matching rows, so it is a wrong results guard, not a perf tuning. Add two 10-row-group fixtures that differ only in declared precision and assert the pruning verdict from ParquetReadRowGroups / ParquetPrunedRowGroups. The mismatched file must decline pruning; the well-formed one must still prune, which proves the layout and predicate admit pruning at all. Reverting only the allow_stats argument flips the first verdict, so the arm is live. The generator now reads the declared precision back out of each written file, because the footer patch it uses is a blind byte replace and a mis-patched fixture would produce a green but meaningless arm.
The previous two commit messages describe the change that stops row group statistics of the physical width from being used as preventing wrong results. That is not supported. The pruning comparison does not go through Field::operator<, which bails on a tag difference; it goes through Range::less to accurateLess, whose same-tag fast path is skipped on a tag mismatch, so it falls to FieldVisitorAccurateLess, whose decimal arm reaches DecimalField::operator< and compares through the wider of the two widths. That is accurate across Decimal32 and Decimal64, so the pre-fix statistics path produced the correct pruning verdict on this shape. The change stays, on the contract instead: allow_stats is documented to require that no conversion is needed, and on this shape convertField produces a DecimalField<Decimal64> for a column whose type is Decimal(9, 2). Feeding the decoded width to the predicate is simply the correct argument, and it is worth pinning in a test rather than leaving to a refactor. Adjusts one test comment accordingly. No executable change: the queries, the reference and the fixtures are untouched.
Internal second-model reviewAn independent model reviewed this diff cold, without the implementation notes, and a second
❌ A mechanism claim in the review's own first round was wrong, and had been written into the 💡 The new comment uses "the column we decode into". Kept: the surrounding file already reads that 💡 Test number No blockers were found in the source change itself. Every invariant carrier that sizes a write from |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260802-153300 |
|
cc @grantholly-clickhouse @vitlibar, could you review this? SchemaConverter picked the decoder from the physical type but sized the destination column from the declared precision alone and never set out_decoded_type, so a DECIMAL(9, 2) stored as physical INT64 decoded 8 bytes per value into a 4-byte Decimal32 and wrote past the end of the column. |
|
Workflow [PR], commit [8c797af] Summary: ❌
AI ReviewSummaryThis PR fixes the Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 11/12 (91.67%) · Uncovered code |
| # encoded value occupies (INT64 or FIXED_LEN_BYTE_ARRAY with precision 9 -> Decimal32). Reading | ||
| # any of them used to write past the end of the destination column. | ||
|
|
||
| echo '-- dictionary-encoded INT64, declared precision 9' |
There was a problem hiding this comment.
@groeneai can you write the parquet files in the test to avoid creating more binary files in the repo?
There was a problem hiding this comment.
Done in 8c797af: all seven fixtures are gone, and the test writes them into $CLICKHOUSE_TMP/$CLICKHOUSE_TEST_UNIQUE_NAME with pyarrow, which the stateless image already pins (ci/docker/stateless-test/requirements.txt:6).
pyarrow always declares a precision that matches the physical width, so it cannot emit this shape directly. The test writes the wide precision and then rewrites the footer's compact-thrift DecimalType precision varint in place; the replacement is the same byte width, so every offset stays valid. That is the same in-test crafting idiom as 04561_parquet_v3_dictionary_filter_negative_page_count.sh.
I verified the generated files are byte-identical to the ones deleted here, so coverage is unchanged. The generator also reads back the physical type, type_length, row group count, per-row-group encodings and statistics of each file, because the write options only request them: a writer-option regression could otherwise have silently produced a different shape while every result assertion still passed through another decoder path. Mutating any of those four properties in the writer now aborts the test.
|
|
||
| /// Decode into a column as wide as the converter writes; castColumn then narrows it to the | ||
| /// declared precision, throwing DECIMAL_OVERFLOW for values that don't fit. | ||
| auto decoded_type = createDecimal<DataTypeDecimal>(max_precision, scale); |
There was a problem hiding this comment.
@groeneai are you sure this issue doesn't happen with other data types such as FixedString?
There was a problem hiding this comment.
Fair question, and I did not want to answer it from the existing narrative, since that narrative was already wrong once about FIXED_LEN_BYTE_ARRAY. I enumerated every branch of processPrimitiveColumn that pairs a converter with a destination type, and swept them empirically.
The invariant is that the converter's input_size must equal the destination element width. DECIMAL was the only branch where the two are computed from independent inputs: the converter from the physical type, the destination from the declared precision. Everywhere else the destination is derived from the physical type itself, so the two cannot disagree:
FixedString: the escape hatch atSchemaConverter.cpp:983-1006only takes effect whensize == fixed_string_type->getN(), so a narrower hint cannot reach it. The generalFIXED_LEN_BYTE_ARRAYcase buildsDataTypeFixedString(element.type_length)from the physical length. A narrower hint therefore becomes acastColumnfrom the widerFixedString, which raisesTOO_LARGE_STRING_SIZErather than writing out of bounds. Verified withbinary(4),binary(8)andbinary(16)files read as everyFixedStringwidth from 1 to 26.INTEGER: setsout_decoded_typeto the physical width for 64-bit and usesoutput_sizefor 8 and 16 bits, which is the same reconciliation this PR adds forDECIMAL.TIMESTAMP/TIME,DATE,UUID,FLOAT16,INT96,BOOLEAN,FLOAT,DOUBLE,BYTE_ARRAY: each pins both sides to one physical width, andUUID/FLOAT16reject a mismatchedtype_lengthoutright.BYTE_ARRAYdecimals bucket on precision only, so the converter width always equals the destination width.
Sweep: 19 fixtures covering every physical type (INT32, INT64, INT96, FLOAT, DOUBLE, BOOLEAN, BYTE_ARRAY, and FIXED_LEN_BYTE_ARRAY at lengths 2, 4, 8, 16, 26) against 21 hints each, including narrower and wider FixedString, integer, decimal and temporal types. On a debug build, zero aborted; every mismatch surfaced as an exception. The same sweep on pre-fix master also produced zero aborts, while the five DECIMAL fixtures in this test aborted there, so the sweep does have the sensitivity to catch this class.
The seven fixtures were checked in as binaries. pyarrow can produce all of them, so the test now writes them into its own temporary directory: pyarrow picks the physical type, and a footer patch of the compact-thrift DecimalType precision varint gives the declared precision that does not match it. The replacement varint is the same byte width, so every offset stays valid. The generated files are byte-identical to the ones removed here. Also added an arm showing a hint of exactly the decoded width restores row group pruning, which the previous arms did not cover.
The generator only requested a physical type and a dictionary encoding, so a writer-option regression could have silently produced a different shape while every result assertion still passed through another decoder path. It now reads the physical type, type_length, row group count and per-row-group encodings back out of each file. The push-down arms printed a pruned or not-pruned verdict, which any positive prune count satisfied. They now print the read and pruned counts, so pruning a row group that holds matching rows would change the output.
|
Note on the
I also ruled out the alternative, that the converter change altered how an existing corpus file reads: |
|
@groeneai it might be worth add that we will now raise |
CI finish ledger - 8c797afEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
175/175 check-runs completed; The failing query is Session id: cron:our-pr-ci-monitor:20260803-163000 |
7904fee
|
Done, the changelog entry now mentions it. I checked which shapes actually raise it before writing the sentence, since the error is narrower than "reading a decimal": So the entry says reading such a file raises |
…ECIMAL wider than declared
Backport #113046 to 26.7: Fix out-of-bounds write reading a Parquet DECIMAL wider than declared
Backport #113046 to 26.3: Fix out-of-bounds write reading a Parquet DECIMAL wider than declared
Backport #113046 to 26.5: Fix out-of-bounds write reading a Parquet DECIMAL wider than declared
Backport #113046 to 26.6: Fix out-of-bounds write reading a Parquet DECIMAL wider than declared
|
Hi @groeneai @PedroTadim @grantholly-clickhouse — while reviewing this PR I found the following:
Could you review the test PR and add the |
… Parquet DECIMAL wider than declared
… Parquet DECIMAL wider than declared
… Parquet DECIMAL wider than declared
DEC: Parquet DECIMAL stored wider than its precision implies (e.g. DECIMAL(9,2) as INT64) -> crash / memory corruption. Effect in the production build a394e92: the upstream test returns wrong sums on the production build (e.g. 6978099.75 instead of 14083299.5); the Decimal512 shape (FIXED_LEN_BYTE_ARRAY wider than 32 bytes with a narrower declared precision) makes the Int512 converter write 64 bytes per value into a narrower column. Upstream patch unchanged, with its test(s): 04670_parquet_v3_decimal_physical_wider_than_destination. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o reader bugs tests/decimal512/tools/parquet/parquet_decimal_writer.py writes Parquet DECIMAL columns with exactly the physical layout a test asks for (standard library only, no pyarrow): any FIXED_LEN_BYTE_ARRAY width 1..64 with any declared precision, BYTE_ARRAY values of 0..64 bytes, PLAIN / BYTE_STREAM_SPLIT / DELTA_BYTE_ARRAY / RLE_DICTIONARY, UNCOMPRESSED or GZIP, data page V1 or V2, REQUIRED or OPTIONAL, with an independent oracle for the expected text. - 10317_parquet_decimal512_read_matrix: Decimal512 read through every value offset of the big-endian decoder (widths 1..64, lengths 0..64) in 16 layouts; passes on the production build and on the candidates (a coverage test for the padded read, no bug). - 10318_parquet_decimal512_width_mismatch: a FIXED_LEN_BYTE_ARRAY wider than 32 bytes with a narrower declared precision (the Int512 decoder wrote 64 bytes per value into a 32/8/4-byte column: wrong sums and heap corruption on the production build) and a BYTE_ARRAY DECIMAL(100, 2) with DELTA_BYTE_ARRAY under PREWHERE (SIGSEGV on the production build); fixed by the backports of ClickHouse#113046 and ClickHouse#115703. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #112659
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed an out-of-bounds write when reading a
ParquetDECIMALcolumn whose physical type is wider than the type its declared precision maps to, for exampleDECIMAL(9, 2)stored as physicalINT64. Such files are validParquetand other writers produce them, but the reader sized the destination column from the declared precision while the decoder wrote the physical width, corrupting memory. Reading such a file now also raisesDECIMAL_OVERFLOWwhen a value does not fit the declared precision, instead of returning corrupted data, and reads losslessly with a type hint at least as wide as the physical type.Description
Reading a
ParquetDECIMALcolumn whose physical element is wider than its declared precision maps to wrote past the end of the destination column, aSIGSEGVinDB::Parquet::Dictionary::indexon ~60% of runs.SchemaConverter::processPrimitiveColumnpicked the decoder from the physical type but sized the destination from the declared precision alone, never settingout_decoded_type. SoDECIMAL(9, 2)allocatedDecimal32, 4 bytes per element, while the physicalINT64decoder wrote 8. Rejecting such files would be wrong, as the specification permitsINT64for precision 1 to 18. ClickHouse's writer always pairs aDecimal<T>withFIXED_LEN_BYTE_ARRAYofsizeof(T), so no round-trip test caught it.The fix reconciles both widths where they are decided: on a mismatch
out_decoded_typebecomes the converter's width and the existing cast narrows the column.out_inferred_typeis untouched, soDESCRIBEstill reports the declared precision and every copy site becomes correct without a bounds check.Row group statistics are no longer used for push-down on this shape: they decode to a value of the physical width, not the type the key range is built from, and
allow_statsrequires no conversion. Only a hint of exactly that width keeps them usable, matching howallow_statstreats every other type. Well-formed files are unaffected.FIXED_LEN_BYTE_ARRAYcarries the same defect and is covered too. My earlier comment on the issue called that branch correct because each precision bucket carries a length bound; those are upper bounds in an ordered chain, so an oversized length falls through to a wider bucket.The test writes its fixtures with pyarrow instead of committing binaries. It covers both physical types, dictionary and plain pages,
type_length8 and 16, schema inference, the hint, the overflow boundary, and three 10-row-group push-down arms asserting exact prune counts.Version info
26.8.1.730(included in26.8and later)26.7.3.8,26.6.2.158,26.5.7.3,26.3.17.108