Skip to content

validate discriminators in Variant binary bulk deserialization - #107991

Merged
Avogar merged 2 commits into
ClickHouse:masterfrom
uwezkhan:variant-discriminator-bounds
Jul 1, 2026
Merged

Avogar merged 2 commits into
ClickHouse:masterfrom
uwezkhan:variant-discriminator-bounds

Conversation

@uwezkhan

@uwezkhan uwezkhan commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

A Variant local discriminator is a UInt8 where 255 means NULL and any other value must be a valid variant index. When deserializing a Variant column from a Native block, SerializationVariant::deserializeBinaryBulkWithMultipleStreams / deserializeCompactDiscriminators read these bytes straight from the input and use them to index variant_limits and variant_rows_offsets, both sized to the number of variants:

AddressSanitizer: heap-buffer-overflow ... WRITE of size 8
    #0 ... ++variant_limits[discr]   (discr = 200, vector size = 2)

For a column with N variants, a crafted block carrying a discriminator in [N, 254] writes out of bounds. All three discriminator encodings reach the unguarded index: BASIC (full column), and the COMPACT and PLAIN granules of the compact mode.

The single-value deserializeBinary path already rejects an out-of-range discriminator; the bulk path did not. Fix validates each discriminator where it enters from the stream and throws INCORRECT_DATA for anything that is neither NULL nor a real variant index, so the rejection lives in the serializer rather than relying on the caller.

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):

Fix an out-of-bounds write when reading a Variant column from a malformed Native block whose discriminators reference a variant index that does not exist.

Version info

  • Backported to: 26.6.4.28, 26.3.33.15

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [181a925]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) FAIL
Server died FAIL cidb, issue ISSUE EXISTS
ThreadSanitizer: data race (STID: 4071-3348) FAIL cidb IGNORED

AI Review

Summary

This PR hardens Variant bulk deserialization from malformed Native blocks by rejecting out-of-range discriminators in the full-column reader, and the original cached-full-reader out-of-bounds path is fixed. One subcolumn-only path still accepts malformed discriminator bytes, so the validation contract is not complete yet.

Findings

⚠️ Majors

  • [src/DataTypes/Serializations/SerializationVariantElement.cpp:180] Native discriminator validation is still incomplete for Variant subcolumn reads. SerializationVariantElement reads and caches BASIC discriminator bytes, but then only compares them with the requested variant_discriminator; for Variant(String, UInt64), a byte 2 is treated as "not String" instead of throwing INCORRECT_DATA. The PLAIN compact-granule branch uses the same equality-only logic, and SerializationVariantElementNullMap reuses the same pattern for .null subcolumns.
    Suggested fix: validate every discriminator read from the stream before caching/counting it in the subcolumn readers, including the shared compact PLAIN branch.
Tests
  • ⚠️ Add focused regression coverage for subcolumn reads, for example selecting v.String and v.String.null from a corrupted Native block. A compact PLAIN granule with an invalid discriminator should also be covered, because the current compact test only exercises a COMPACT granule discriminator.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: reject out-of-range discriminators in the subcolumn deserialization paths and cover those paths with focused Native regression tests.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 19, 2026
@Avogar Avogar self-assigned this Jun 22, 2026
…ation paths

Extend the discriminator bounds check from `SerializationVariant` to also cover
`ColumnVariant::validateState`, `SerializationVariantElement`, and
`SerializationVariantElementNullMap`. Use `INCORRECT_DATA` for native format
(untrusted input) and `LOGICAL_ERROR` otherwise.

Extract a `checkDiscriminatorValue` helper function to avoid repeating the
check-and-throw pattern at every call site.

Add tests with pregenerated `.native` files containing corrupted discriminators
(both plain and compact granule formats).

Related: ClickHouse#107991
Related: ClickHouse/clickhouse-private#59665

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@Avogar

Avogar commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

Thanks for the contribution! It's a good idea to add this check. I made a few additional changes to add similar check in other places where it's needed and added a few tests.

settings.continuous_reading,
variant_element_state->discriminators_state,
settings,
num_variants,

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.

Malformed Native input is still accepted when the query reads only Variant subcolumns. In the BASIC path above, the newly-read discriminator bytes are cached at line 189 and the later loops only compare them with variant_discriminator; for Variant(String, UInt64) a byte 2 is treated as "not String" instead of INCORRECT_DATA. The PLAIN compact-granule branch in deserializeCompactDiscriminators has the same equality-only counting at lines 379-383, and SerializationVariantElementNullMap reuses the same pattern for .null subcolumns.

Please validate every discriminator read from the stream before caching/counting it in the subcolumn readers as well, and add a focused regression such as selecting v.String / v.String.null from a corrupted Native block.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right, but this is the subcolumn reader, not the full one. The OOB this PR is about lives in the full reader's ++variant_limits[discr] / ++variant_rows_offsets[discr], where a raw discr in [N, 254] indexes a vector sized to num_variants. The subcolumn path here never does that: it only compares discriminators_data[i] == variant_discriminator (the limit/rows_offset counting, the null-map fill, and the final insert loop), so an out-of-range byte is counted as "not this variant" and is never used as an index. No out-of-bounds write. The compact granule it shares is covered now that num_variants flows into readDiscriminatorsGranuleStart. Rejecting the stray byte in the BASIC subcolumn path would be a stricter-input policy rather than a safety fix, with the trade-off that it'd reject blocks the full reader still reads fine.

@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.40% -0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.60% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 151/164 (92.07%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 4 line(s) · Uncovered code

Full report · Diff report

@uwezkhan

Copy link
Copy Markdown
Contributor Author

Looks good, thanks for finishing it off. Threading num_variants into readDiscriminatorsGranuleStart covers the compact subcolumn path I'd missed, and gating validateState on native_format reads cleaner than scattering a check at every index site.

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — 2 query(s) regressed out of 38 analysed

This PR only hardens bounds-checking of Variant/Dynamic discriminators during deserialization from the Native format and MergeTree reads. ClickBench and TPC-H use fixed, standard-typed schemas that never exercise the Variant code path, so the five sub-25% deltas cannot plausibly be caused by this change and were downgraded to run-to-run variance. Two TPC-H queries (Q4 +210%, Q7 +785%) exceed the automatic hard-trust threshold and so their verdicts stand, but both had very noisy baseline measurements and hit no Variant path — a re-run is recommended before treating them as real regressions.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 259 218 -15.8% <0.0001 PR only adds bounds checks to Variant/Dynamic deserialization; ClickBench uses fixed types, so this -15.8% is variance
⚠️ 30 not_sure 240 280 +16.7% <0.0001 Variant/Dynamic-only change; Q30 touches no Variant columns, so +16.7% is run-to-run variance
⚠️ 31 not_sure 308 360 +16.5% <0.0001 Variant/Dynamic-only change; Q31 exercises no Variant path, +16.5% is variance

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🔴 2 regressed · ⚠️ 2 inconclusive

Flagged queries (4 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 4 regression 326 1011 +210.1% <0.0001 Delta exceeds hard-trust threshold so verdict stands, but base was very noisy (CV~46%); re-run to confirm
🔴 7 regression 71 628 +784.5% <0.0001 Held by hard-trust threshold; base extremely noisy (CV~103%, 71ms) vs stable 628ms source, re-run advised
⚠️ 8 not_sure 168 209 +24.4% <0.0001 Variant/Dynamic-only change; TPC-H uses standard types, so +24.4% is variance not a PR effect
⚠️ 16 not_sure 100 50 -50.0% <0.0001 Variant/Dynamic-only change; noisy base (CV~23%), so -50% improvement is variance not real

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: ac16b8bf-687e-4257-b7a1-9ba2d7f51e01
  • MIRAI run: 55d152b2-c7a3-4ef4-bfa7-fa8781621f22
  • PR check IDs:
    • clickbench_633483_1782921149
    • clickbench_633490_1782921149
    • clickbench_633500_1782921149
    • tpch_adapted_1_official_633520_1782921149
    • tpch_adapted_1_official_633534_1782921149

@Avogar
Avogar added this pull request to the merge queue Jul 1, 2026
Merged via the queue into ClickHouse:master with commit 2038a36 Jul 1, 2026
165 of 167 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

validate discriminators in Variant binary bulk deserialization

ClickGap verified: reproduced it with the script below on 26.5; tested 6 version(s) — 5 affected, 1 clean (see Affects); long-standing (not a recent regression); introducing PR not yet pinned.

Reproduction

# Variant(String, UInt64) has 2 variants, so valid local discriminators are 0, 1, or 255 (NULL).
# Build a malformed Native block whose 2nd row discriminator byte is 2 (out of bounds):
base64 -d > corrupt.native <<'B64'
AQMBdhdWYXJpYW50KFN0cmluZywgVUludDY0KQAAAAAAAAAAAAL/BWhlbGxv
B64
clickhouse local --table test --input-format Native -q "SELECT * FROM test" < corrupt.native
# Pre-fix: heap out-of-bounds write -> "libc++ Hardening assertion __n < size() ... vector[] index out of bounds" / SIGABRT crash.
# Fixed:   throws INCORRECT_DATA -> "Invalid discriminator value 2 (num_variants = 2)".

Bisect

  • Reproduces on every release line tested down to v24.1.8.22 (the oldest with a downloadable binary for this repro). The introducing change predates v24.1.8.22, so it can't be pinned from release binaries — this is a long-standing issue, not a recent regression. A maintainer with full git history can git blame the relevant file/line to find the exact change.

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3, 26.2, 26.1
  • Does NOT reproduce on: master
  • Backport needed: 26.5, 26.4, 26.3, 26.2, 26.1

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-json-datatype
Severity: P2

cc fix PR reviewer: @Avogar


ClickGap · Finding: phase_d_pr107991

Triage metadata

  • Primary component: comp-json-datatype
  • Secondary components: comp-testing
  • Component owners (comp-json-datatype): @Avogar @nikitamikhaylov

@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Aug 27, 2026
PedroTadim added a commit that referenced this pull request Aug 27, 2026
Backport #107991 to 26.5: validate discriminators in Variant binary bulk deserialization
PedroTadim added a commit that referenced this pull request Aug 27, 2026
Backport #107991 to 26.6: validate discriminators in Variant binary bulk deserialization
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
@azat azat added v26.3-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore labels Aug 29, 2026
Avogar added a commit that referenced this pull request Sep 3, 2026
Resolve conflicts for the 26.3 backport of the Variant discriminator
bounds validation.

All conflicts come from the serialization pooling infrastructure
(`getHash`, static `create`, `ISerialization::pooled`, `supportsPooling`,
`allocatedBytes`), which exists on `master` but not on 26.3, where these
serializations are still constructed directly via `std::make_shared` with
public constructors. The resolution keeps 26.3's construction style and
threads `num_variants` through it, dropping the pooling-only declarations
and definitions.

`SerializationVariantElement` and `SerializationVariantElementNullMap`
take `num_variants` as a required constructor argument, since every
construction site in the 26.3 tree passes a real count. A defaulted `0`
would make `checkDiscriminatorValue` reject every non-NULL discriminator.
The subcolumn creators keep their `num_variants_ = 0` defaults as on
`master`.

Related: #117736
Related: #107991

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
robot-ch-test-poll4 added a commit that referenced this pull request Sep 3, 2026
Cherry pick #107991 to 26.3: validate discriminators in Variant binary bulk deserialization
robot-clickhouse added a commit that referenced this pull request Sep 3, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 3, 2026
Avogar added a commit that referenced this pull request Sep 8, 2026
Backport #107991 to 26.3: validate discriminators in Variant binary bulk deserialization
@rienath rienath added v26.2-must-backport v26.5-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore labels Sep 9, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 9, 2026
@azat azat added pr-synced-to-cloud The PR is synced to the cloud repo and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo labels Sep 11, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 11, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ation paths

Extend the discriminator bounds check from `SerializationVariant` to also cover
`ColumnVariant::validateState`, `SerializationVariantElement`, and
`SerializationVariantElementNullMap`. Use `INCORRECT_DATA` for native format
(untrusted input) and `LOGICAL_ERROR` otherwise.

Extract a `checkDiscriminatorValue` helper function to avoid repeating the
check-and-throw pattern at every call site.

Add tests with pregenerated `.native` files containing corrupted discriminators
(both plain and compact granule formats).

Related: ClickHouse#107991
Related: ClickHouse/clickhouse-private#59665

Co-Authored-By: Claude Opus 4.6 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…tor-bounds

validate discriminators in Variant binary bulk deserialization
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
PROTO: malformed Native Variant discriminators -> crash (OOB write).
Effect in the production build a394e92: its upstream test(s) 04305_variant_corrupted_discriminators_native, 04306_variant_corrupted_compact_discriminator_native fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04305_variant_corrupted_discriminators_native,04306_variant_corrupted_compact_discriminator_native.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport v26.3-must-backport v26.4-must-backport v26.5-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.