Skip to content

Guard ColumnString::filter against offsets inconsistent with chars array - #109184

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-columnstring-filter-oob-inconsistent-offsets
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:fix-columnstring-filter-oob-inconsistent-offsets

Conversation

@groeneai

@groeneai groeneai commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107355

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

Fixed a possible out-of-bounds read in ColumnString::filter when a String column arrives with a last offset that does not match the size of its chars array. Filtering such a column now raises INCORRECT_DATA instead of copying past the end of the buffer.

Description

ColumnString::filter (both the const and in-place overloads) passed offsets and chars straight to filterArraysImpl / filterArraysImplInPlace without checking that the two are consistent. The SIMD fast path in filterArraysImplGeneric (ColumnsCommon.cpp) sizes its copies from offsets alone: for a full-passing 64-row chunk it computes chunk_size = offsets_pos[63] - offsets_pos[-1], then does resize + memcpy of that many bytes. A last offset past the end of chars therefore copies from beyond the source buffer.

This surfaced in CI as a SEGV (address not mapped to object) in ResultOffsetsBuilder::insertChunk<64>, reached from FilterTransform::doTransform through ColumnNullable::filter, while filtering a nullable String column produced by the Parquet reader on a metadata-cache hit. That producer is not deterministically reproducible and the offsets of the corrupt column are not recorded, so this PR does not touch it. It validates, where the corruption turns into memory unsafety, the invariant the ColumnString copy constructor already enforces (offsets.back() == chars.size()), the same guard #107355 added to the sibling ColumnString::insertRangeFrom path.

Scope: the check is the O(1) endpoint invariant, so well-formed columns pay one comparison per filter call. It deliberately does not verify that the intermediate offsets are monotonic, which would need a per-row scan on one of the hottest paths in the engine, so a column whose offsets dip in the middle while offsets.back() == chars.size() still reaches the helper. ColumnString::sizeAt already chasserts that property, but the filtering helpers do their own offset arithmetic and never reach it, so if you would rather have sanitizer builds reject the whole class here, I will move the scan under DEBUG_OR_SANITIZER_BUILD.

Validation: the new gtests reproduce the unguarded defect (ASan heap-buffer-overflow, read of 262400 bytes past a 1024-byte region) and pass with the guard; a consistent column exercising the all-pass chunk, the per-row branch and the scalar tail still filters correctly.


Workflow [PR]
Sync PR [sync-upstream/pr/109184]

ColumnString::filter (both the const and in-place overloads) handed
`offsets` and `chars` straight to filterArraysImpl / filterArraysImplInPlace
without checking that they are consistent. The SIMD fast path in
filterArraysImplGeneric (ColumnsCommon.cpp) trusts `offsets` to compute chunk
sizes: for a full-passing 64-row chunk it does
chunk_size = offsets_pos[63] - offsets_pos[-1], then resize + memcpy that many
bytes. If a corrupt column arrives with offsets.back() != chars.size() (offsets
overshoot chars, or non-monotonic), chunk_size is bogus and the memcpy runs off
the end of the destination/source buffer, an out-of-bounds write.

Observed in CI as a SEGV ("address not mapped") with the stack
  __asan_memcpy
  ColumnsCommon.cpp ResultOffsetsBuilder::insertChunk<64> / filterArraysImpl<char8_t>
  ColumnString::filter -> ColumnNullable::filter -> FilterDescription::filter
  -> FilterTransform::doTransform
when filtering a nullable String column produced by the parquet reader on a
metadata-cache-hit path. The corrupt column is produced upstream; this change
does not fix the upstream producer, it converts the silent out-of-bounds write
into a clean INCORRECT_DATA exception so the corruption fails safely and is
diagnosable instead of crashing (or silently corrupting memory) in release
builds.

This mirrors the invariant the ColumnString copy constructor already enforces
(offsets.back() == chars.size()) and the guard recently added to the sibling
ColumnString::insertRangeFrom path.

Adds unit tests that build a ColumnString whose offsets overshoot chars and
assert filter() throws INCORRECT_DATA instead of reading/writing out of bounds
(the large-overshoot case is an ASan heap-buffer-overflow without the guard),
plus a positive test that a consistent column still filters correctly.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes for the crash mechanism: a unit test builds a ColumnString whose offsets overshoot chars and calls filter(); the large-overshoot case is a deterministic ASan heap-buffer-overflow without the guard. The upstream Parquet metadata-cache producer that yields the inconsistent column is NOT deterministically reproducible (ran the exact deltaLake reproducer 60x over the network, 0 crashes), so per the "no speculative changes to code you cannot reproduce" rule this PR does not touch the producer; it guards + tests the manifestation point.
b Root cause explained? filterArraysImplGeneric SIMD fast path computes chunk_size = offsets_pos[63] - offsets_pos[-1] and memcpys that many bytes. If offsets.back() != chars.size() (offsets overshoot chars, or non-monotonic), chunk_size is bogus and the resize+memcpy writes past the buffer end. ColumnString::filter passed offsets/chars in with no consistency check.
c Fix matches root cause? Yes. The guard validates the exact invariant the fast path relies on (offsets.back() == chars.size(), the same invariant the ColumnString copy constructor enforces) before calling filterArraysImpl, converting the OOB write into a clean INCORRECT_DATA exception.
d Test intent preserved / new tests added? New tests added: FilterInconsistentOffsetsThrows, FilterInconsistentOffsetsLargeOvershoot, FilterInPlaceInconsistentOffsetsThrows (assert INCORRECT_DATA), plus FilterConsistentColumnStillWorks (positive path, SIMD + tail). Modeled on the existing insertRangeFrom guard tests. No existing test weakened.
e Both directions demonstrated? Yes. Without the guard: FilterInconsistentOffsetsLargeOvershoot aborts with AddressSanitizer heap-buffer-overflow; the other two "Throws" tests FAIL ("filter did not detect..."). With the guard: all 11 ColumnString tests pass. Full deltaLake reproducer still returns correct results (99997497 rows) with no false-positive on the guarded binary.
f Fix is general across code paths? Both ColumnString::filter overloads (const via filterArraysImpl, in-place via filterArraysImplInPlace) are guarded. The sibling insertRangeFrom path already got the equivalent guard in #107196; filter was the remaining unguarded consumer of the same SIMD offsets math. ColumnArray::filter uses the same helper but with element-offset (not byte/chars) semantics, so the chars-specific invariant does not apply there.
g Fix generalizes across inputs? The guard is on the structural invariant itself (last offset vs chars size), independent of the string values, Nullable/LowCardinality wrapping (those wrap ColumnString, whose filter is called on the inner column), filter selectivity, or result_size_hint. Covered by tests with >= 64 rows (SIMD path), small and large (256 KB) overshoot, and a selective positive filter.
h Backward compatible? Yes. No setting, on-disk, wire, or metadata format change. The only behavior change is on an already-corrupt (invariant-violating) column, which previously invoked undefined behavior (OOB write) and now raises a catchable INCORRECT_DATA exception. Well-formed columns are unaffected (O(1) check on the error path only).
i Invariants and contracts preserved? Yes. The guard enforces the documented ColumnString invariant offsets.back() == chars.size() (the copy constructor already throws on its violation) before filterArraysImpl consumes offsets. It adds no new state and holds on all paths (early-return on empty offsets is unchanged; the check runs before any allocation/copy).

Session id: cron:clickhouse-worker-slot-5:20260702-124200

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CurtizJ @davenger could you review this? It adds an O(1) consistency guard to ColumnString::filter (both overloads) that rejects a column whose offsets.back() != chars.size() with INCORRECT_DATA, instead of letting the filterArraysImpl SIMD fast path do an out-of-bounds memcpy (seen in CI as an ASan SEGV under FilterTransform on a nullable String from the Parquet reader). It mirrors the invariant the copy constructor enforces and the sibling guard added to insertRangeFrom in #107196.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a9d41cf]

Summary: ✅


AI Review

Summary

This PR adds an offsets.back() == chars.size() guard to both ColumnString::filter overloads and extends the ColumnString gtests around last-offset mismatches. The high-level problem is still open: filterArraysImpl and filterArraysImplInPlace subtract every adjacent offset, so a corrupt column with non-monotonic offsets can still drive the same unchecked huge resize/memcpy the PR is trying to turn into INCORRECT_DATA.

Findings

❌ Blockers

  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109184#discussion_r3513607066] [src/Columns/ColumnString.cpp:211, src/Columns/ColumnsCommon.cpp:273-280] The new guard does not enforce the full safety invariant that the filtering helpers rely on. copy_array computes each string length as *offset_ptr - offset_ptr[-1], so offsets = [4, 2, 12] still passes offsets.back() == chars.size() but then underflows arr_size = 2 - 4 to a huge size_t, after which both filter paths still run the unchecked resize + memcpy on corrupt input. I still consider this real because the current change converts only last-offset mismatches into INCORRECT_DATA; non-monotonic offsets remain memory-unsafe.
    Suggested fix: reject decreasing or dipping offsets before calling filterArraysImpl / filterArraysImplInPlace, or harden those helpers to validate monotonicity themselves, and add filter regressions mirroring the existing insertRangeFrom decreasing/dipping-offset tests.
Tests
  • ⚠️ [src/Columns/tests/gtest_column_string.cpp:244-299] The new tests prove only the two endpoint-mismatch shapes (offsets.back() too large or too small). Please add at least one filter test with an intermediate dip, for example offsets = [4, 2, 12], plus the in-place overload, so the suite demonstrates that the underflow path in copy_array is actually closed.
Final Verdict

❌ Not ready to merge: ColumnString::filter is still vulnerable to non-monotonic offsets that satisfy the new endpoint check.

LLVM Coverage Report

Measured on commit a9d41cf.

Metric Baseline Current Δ
Lines 88.70% 88.80% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 58/59 (98.31%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 2, 2026
/// Enforce the ColumnString invariant (offsets.back() == chars.size(), same as the copy
/// constructor) before filterArraysImpl trusts `offsets` to size its memcpys; a violated
/// invariant would otherwise read/write out of bounds instead of failing cleanly.
if (offsets.back() != chars.size())

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.

filterArraysImpl and filterArraysImplInPlace rely on more than offsets.back() == chars.size(): copy_array subtracts every offset from the previous one. A corrupt column like offsets = [4, 2, 12] still passes this new check, but filtering the second row makes arr_size = 2 - 4, which underflows and drives a huge resize/memcpy in both paths. Since the upstream producer is still unknown, the guard here needs to reject non-monotonic offsets too, and the new tests should cover the decreasing/dipping cases the same way insertRangeFrom already does.

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7ce9c3a

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 8/8) / test_keeper_session_refuse_stale_server::test_session_refused_on_stale_keeper flaky (wait_zookeeper_to_start ZK-restart race; 30d: 6 hits / 6 unrelated PRs / 0 master; unrelated to this PR's ColumnString::filter guard) #109037 (ours, open)

Note: Mergeable Check / PR are rollups of the single flaky Integration line above, owned by #109037.

Session id: cron:our-pr-ci-monitor:20260702-173000

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7ce9c3a

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 8/8) / test_keeper_session_refuse_stale_server::test_session_refused_on_stale_keeper chronic flaky (14d: 5 unrelated PRs, 1 hit each; Keeper session test unrelated to this PR's ColumnArray::getExtremes fix) #109037 (ours, open)

Session id: cron:our-pr-ci-monitor:20260703-043000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 53/54 (98.15%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8ae89d3

Every failure below has an owner: a fixing PR, or a full-effort fix task whose
fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky on this lane: secondary replicas are built without setQueryId, so the per-table max_concurrent_queries throttle sees several random query ids for one statement and the query competes against itself #112385 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-083000

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-data-types Type system & core datatypes used across query planning/execution. label Sep 4, 2026
groeneai and others added 2 commits September 5, 2026 08:31
The positive control filtered every third row, so no 64-row block ever passed in
full and the all-pass chunk branch of `filterArraysImplGeneric`, whose unchecked
`chunk_size` arithmetic the guard protects, never ran, even though the comment
claimed it did. The mask now passes rows 0-63 as a block, then every third row,
then leaves a partial trailing chunk, so the all-pass chunk, the per-row branch
inside a chunk and the scalar tail are all covered, and the test asserts the
resulting `chars` size as well as the row contents.

The two overshoot tests differed only in magnitude and killed the same mutant.
They are now one test, using the magnitude that actually leaves the allocation
(ASan: `heap-buffer-overflow`, read of 262400 bytes past a 1024-byte region). The
new mirror case covers a last offset below `chars.size()`, which a guard written
with `>` instead of `!=` would let through.

The comments state the constructed layout and the invariant instead of repeating
the CI stack and the ASan narrative from the PR description, and wrap literal
class and function names in inline code.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a9d41cfe4 with master d1adb9f9f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

39 object files changed (+296.75 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Rules/AggregationPushdown.cpp.o new 278.38 KiB +278.38 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

48 translation units recompiled, 529 s compile time in total, 48 of them have a recent master baseline.

Job report

This branch has not been deployed

No deployments
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 comp-data-types Type system & core datatypes used across query planning/execution. groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants