Skip to content

Backport #115222 to 26.6, with the aborting unit test fixed - #116640

Closed
groeneai wants to merge 1 commit into
ClickHouse:26.6from
groeneai:groeneai/fix-116535-gtest-null-codec
Closed

groeneai wants to merge 1 commit into
ClickHouse:26.6from
groeneai:groeneai/fix-116535-gtest-null-codec

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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 an out-of-bounds read while deserializing corrupted posting lists of a text index.

Description

Related: #115222
Related: #116535

Requested by @ CurtizJ on #116535: #116535 (comment)

The 26.6 backport of #115222, on top of current 26.6, with the unit test it ships fixed.

Unit tests (asan_ubsan) and Unit tests (tsan) fail on #116535 because unit_tests_dbms aborts, so the job writes no result file at all. PostingsSerialization's constructor asserts that its codec is non-null (MergeTreeIndexText.cpp:152), and the version of the test rewritten for the release branches passes nullptr. That is safe as far as deserialize goes, which never consults the codec for an uncompressed posting list, but the constructor asserts first: RoundTrip aborted before deserialize was entered, and TruncatedPayloadRejected never ran. The fix passes a PostingListCodecNone, which is what TextIndexUtils.cpp already does when no codec is configured. master is unaffected because its version of the test never constructs PostingsSerialization.

Validated on this branch with a Debug build: RoundTrip aborts in that constructor before the change, and both RoundTrip and TruncatedPayloadRejected pass after it, over five repeats. With the backported PostingList::readSafe bound reverted to PostingList::read, TruncatedPayloadRejected fails at all four of its assertions while RoundTrip stays green, so the test does cover the bound this backport exists for.

This supersedes #116535. Basing it on backport/26.6/115222 instead would be a stacked pull request, which the rulebook forbids and which draws no checks, and I have no push access to that branch. Closing #116535 is yours to decide; the one-line patch is in that thread if you would rather apply it there.

26.3 and 26.5 already carry this test merged but never executed, since neither branch runs a Unit tests job.

Resolves the 26.6 cherry-pick of ClickHouse#115222. The production change is the same
bound that merged upstream: `PostingList::read` becomes
`PostingList::readSafe(..., num_bytes)` at both `PostingsSerialization::deserialize`
sites in `MergeTreeIndexText.cpp`, the in-place one and the
`deserialization_buffer` one.

The unit test the automated backport carries aborts, which is why
`Unit tests (asan_ubsan)` and `Unit tests (tsan)` are red on ClickHouse#116535 and write no
result file. `PostingsSerialization`'s constructor asserts that its codec is
non-null (`MergeTreeIndexText.cpp:152`), and the release-branch rewrite of
`gtest_text_index_postings_deserialization.cpp` constructs it with `nullptr`, on
the stated assumption that a posting list without the `IsCompressed` flag never
consults the codec. That holds for `deserialize`, but the constructor asserts
first, so `TextIndexPostingsDeserializationTest.RoundTrip` aborted before
`deserialize` was entered and `TruncatedPayloadRejected` never ran at all.

This passes a `PostingListCodecNone` instead, which is what production does in the
same situation: `TextIndexUtils.cpp` maps an absent codec to a real `None` codec
through `PostingListCodecFactory` rather than passing null. `master` is unaffected
because its version of this test uses `PostingListCodecNone` directly and never
constructs `PostingsSerialization`.

Validated on this branch: the test aborts before the change; both `RoundTrip` and
`TruncatedPayloadRejected` pass after it; and with the bound reverted to
`PostingList::read`, `TruncatedPayloadRejected` fails at all four of its
assertions, so the test does cover the bound this backport exists for.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent cold review of this diff plus a second-model gate pass, both run before publication.
Two rounds: the first bounced on branch shape (the branch had carried the robot's backport commit as
well as mine), which is why this branch is one commit on top of the current 26.6.

Gate: one blocker raised, and I disagree with it. Recorded rather than quietly dropped.

❌ The gate argues that a corrupted oversized VarUInt length prefix still bypasses the bound: at
MergeTreeIndexText.cpp:255 the guard is istr.position() + num_bytes <= istr.buffer().end(), and
since readVarUInt decodes a full 64 bits (src/IO/VarInt.h:76-88 loops ten bytes and sets bit 63),
a large enough num_bytes wraps the pointer, passes the guard, and reaches readSafe with an
effectively unbounded maxbytes.

I checked every step and the mechanism holds, so I am not disputing it. I am disputing that it belongs
in this pull request:

  • that guard is untouched context here. It is already at the 26.6 tip before this commit, and
    git log -S attributes it to c25210d0b505f7b from September 2025;
  • it is not made worse. Before this change the same inputs reached PostingList::read with no bound
    at all, and every num_bytes that does not wrap fails the guard, falls to
    deserialization_buffer.resize and readStrict, and throws;
  • master does not have this function shape at all. Its equivalent is readContiguousBytes in
    MergeTreeIndexTextPostingListCodec.cpp, whose guard is already the subtraction
    in.buffer().end() - in.position() >= num_bytes, which cannot wrap. So the invariant the gate wants
    was never established by Bound text index posting list deserialization #115222 on any branch;
  • and this file is byte-identical to the resolution already merged onto 26.3 (Backport #115222 to 26.3: Bound text index posting list deserialization #116533) and 26.5
    (Backport #115222 to 26.5: Bound text index posting list deserialization #116534). Changing the guard here would make 26.6 the only branch that differs.

⚠️ Noted, not blocking, and the one part of that worth knowing on its own: the release branches carry
the pre-restructure addition form of the guard while master carries the overflow-free subtraction
form. I have not touched it and am not proposing to.

Own review: no blocker, no major. Three things checked that could each have been a finding:

  • 💡 The codec could have come from PostingListCodecFactory::createPostingListCodec(Type::None),
    which is what all five production sites use and which would need no new #include. Kept the direct
    PostingListCodecNone because that is what master's version of this same test does, with the same
    header. For a backport, converging on master's test wins.
  • 💡 Test liveness confirmed from CRoaring rather than from a log: readSafe bounds the deserializer
    by maxbytes and reports a truncated payload through throw std::runtime_error, while plain read
    has no bound and cannot throw. decodePostingsInPlace reaches MergeTreeIndexText.cpp:257 and
    decodePostingsAcrossBuffers reaches :264, which is why reverting the bound reddens four
    assertions and not two, and why RoundTrip stays green.
  • 💡 The bound cannot reject valid data: serialize writes num_bytes as
    roaring_bitmap_portable_size_in_bytes and then exactly that many bytes, so the bound is exact.

One thing worth noting for anyone comparing this test against master's: this version is the stronger
of the two. master's drives PostingListCodecNone::decode and covers only the in-place path; this
one goes through PostingsSerialization::deserialize and covers both the in-place path and the
deserialization_buffer copy path.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [BackportPR], commit [9f0f6af]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) FAIL
test_storage_kafka/test_batch_fast.py::test_kafka_engine_put_errors_to_stream_with_random_malformed_json[generate_old_create_table_query] FAIL cidb
test_storage_kafka/test_batch_slow_0.py::test_kafka_formats_with_broken_message[generate_old_create_table_query] FAIL cidb

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. taskset -c 0 ./build/src/unit_tests_dbms --gtest_filter='TextIndexPostingsDeserializationTest.*' exits 134 (SIGABRT) inside RoundTrip with the test exactly as #116535 ships it, and the abort is a chassert on an unconditional path, so it is structural rather than intermittent. The site matches what CI aborts on; the output does not, because a Debug build prints the assertion text and the sanitizer jobs do not. A control run of an untouched suite (ColumnString.*:DateLUTTest.*, 11 tests) passes on that same binary, so this is not the known unit_tests_dbms global-setup abort on this box.
b Root cause explained? PostingsSerialization's constructor asserts its codec is non-null (MergeTreeIndexText.cpp:152). The test's makeSerialization passed nullptr on the stated assumption that an uncompressed posting list never consults the codec. That is true of deserialize (with header = 0 control reaches the final else, which only calls PostingList::readSafe), but the constructor asserts first, so RoundTrip aborted inside the constructor before deserialize was entered. The local stack trace names the chain exactly: abortOnFailedAssertion -> MergeTreeIndexText.cpp:152 -> gtest_text_index_postings_deserialization.cpp:35 -> RoundTrip at :81.
c Fix matches root cause? Yes. The failing precondition is "the constructor requires a codec", so the fix supplies one (PostingListCodecNone) rather than relaxing the assert or weakening the test. It is also the idiomatic in-tree answer: TextIndexUtils.cpp:216-219 maps an absent codec to a real None codec through PostingListCodecFactory instead of passing null.
d Test intent preserved / new tests added? Preserved exactly, and proven so. No assertion, fixture or payload was touched: the diff is one added include plus the codec argument. The regression coverage is now stronger than before the change, because TruncatedPayloadRejected had never executed on any branch (the abort hid it) and now runs and passes.
e Both directions demonstrated? Yes, on Build-ID-verified binaries built from this branch. With the test as #116535 ships it, 687baa206745fcc5dd6523cdd34ed75208e30679 exits 134 inside RoundTrip; with the fix, c9c9d334653f821579de6c8e307dee3031e6bf11 runs 2 tests, 0 failures, and passes 5/5 repeats. Restoring the fix after the base arm reproduces that same Build ID bit for bit, so the two arms differ only in the one changed argument.
f Fix is general across code paths? Yes. I enumerated every PostingsSerialization construction site on this branch: six in total, five in production (MergeTreeIndexText.cpp:439, :1477, MergeTreeReaderTextIndex.cpp:128, TextIndexUtils.cpp:219, :227) and one in this test. All five production sites obtain their codec from PostingListCodecFactory::createPostingListCodec, which cannot return null (it returns a codec or throws BAD_ARGUMENTS). The test was the only site passing a literal nullptr, so the fix is complete and no production source needs to change.
g Fix generalizes across inputs? N/A for type wrappers: this is a constructor argument in a unit test, not a data path. Across the test's own input matrix the fix holds for all of it: the four posting-list shapes RoundTrip covers (empty, array container, bitset container, run container), both deserialization paths (decodePostingsInPlace via ReadBufferFromString, decodePostingsAcrossBuffers via ConcatReadBuffer), and both truncation sizes in TruncatedPayloadRejected.
h Backward compatible? N/A. Test-only change: no settings, no defaults, no serialization format, so no SettingsChangesHistory.cpp entry is involved. The backported production change itself is unchanged from what merged in #115222.
i Invariants and contracts preserved? Yes, and one is now satisfied that previously was not. The constructor's precondition (a non-null codec) is met instead of violated. IPostingListCodec has a virtual destructor, so owning a PostingListCodecNone through a std::unique_ptr<IPostingListCodec> is well defined and raises no UBSAN finding, which matters because this test runs under asan_ubsan. Passing a Type::None codec cannot relocate the abort: the only code that rejects Type::None is PostingsSerialization::serialize (not on the test's path) and the compressed branch of deserialize (which header = 0 does not take).

Mutation check (beyond the gate): with the backported bound reverted to PostingList::read at MergeTreeIndexText.cpp:257 and :264, TruncatedPayloadRejected fails at all four of its assertions, at both truncation sizes, while RoundTrip stays green. So the test is a live oracle for the bound this backport exists for, and the mutant is narrow rather than a blanket break. The fix to the test was verified still present while the mutant was in place, so this is one mutation and not two.

Session id: cron:clickhouse-impl-slot-6:20260827-025400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Ergus, could you review this? It is the 26.6 backport of #115222 with the unit test it ships fixed: the release-branch rewrite built PostingsSerialization with a nullptr codec and the constructor asserts the codec is non-null, so RoundTrip aborted in the constructor and the Unit tests jobs wrote no result file. Passing a PostingListCodecNone fixes that and leaves the backported readSafe bound unchanged.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9f0f6af

CI is fully finished at this commit: 38 BackportPR nodes, 35 OK and 2 skipped, one failing check carrying two failing tests, and each has an owner. Both are pre-existing on 26.6 and neither is caused by this backport, whose diff is one gtest file.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) / test_storage_kafka/test_batch_fast.py::test_kafka_engine_put_errors_to_stream_with_random_malformed_json[generate_old_create_table_query] flaky, assert 54 == 64. StorageKafka snapshots its dependent materialized views when the streaming loop starts, so the loop can begin after the _data view exists but before _errors does; that batch reaches _data only, the offset is committed, and _errors stays one kafka_max_block_size chunk short. Fixed on master by #107025, whose DETACH/ATTACH hunk is absent from 26.6 (grep -c 'DETACH TABLE test.kafka_' over the shipped blob: present on master, 0 on 26.6, and this head's blob is identical to 26.6). 14 occurrences across 7 pull requests in 30 days, 0 on master. #113975 (external, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) / test_storage_kafka/test_batch_slow_0.py::test_kafka_formats_with_broken_message[generate_old_create_table_query] flaky, same materialized-view race in a different test: Error row for format CSVWithNames did not appear in kafka_errors_CSVWithNames_mv. Fixed on master by #111701, which carries no backport label, so 26.6 predates it as well (same content probe: marker count 1 on master, 0 on 26.6). 26 occurrences across 14 pull requests in 30 days. #111701 (ours, merged to master; absent from 26.6, so a fix task is created to get it there, and the fixing-PR link will follow on this PR)

Report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116640&sha=9f0f6af668c12b8fd08d519bb58d4d81b343b866&name_0=BackportPR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%202%2F6%29

The gtest this PR exists to fix is green here: the two Unit tests legs this workflow schedules on 26.6, Unit tests (asan_ubsan) and Unit tests (tsan), both report fail: 0 over 11946 and 11945 tests. There is no Unit tests (msan) leg in the BackportPR matrix, so its absence is a scheduling fact and not a pass.

Session id: cron:our-pr-ci-monitor:20260827-073000

@CurtizJ CurtizJ closed this Aug 27, 2026
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing-PR links for the two Kafka reds on this ledger

The ledger above promised the fixing-PR link for the slow-test half. It exists and is merged.

Failing test Fixing PR for 26.6 State
test_batch_slow_0.py::test_kafka_formats_with_broken_message #116741 (Backport #111701 to 26.6) MERGED 2026-08-27T19:32:15Z
test_batch_fast.py::test_kafka_engine_put_errors_to_stream_with_random_malformed_json #113975 (Backport #107025 to 26.6) OPEN

The slow-test half is verified, not just merged. Counting both backport-PR runs and the
branch's own ReleaseBranchCI on 26.6, from the 2026-08-25 onset: 41 failures in the 172
runs before #116741 merged, then 0 in the 562 runs after it. The one post-merge row is a
re-run of a stale pre-merge tree (06be14ef, whose blob still lacks the hunk), so it is not
a counterexample. 26.7 received the same fix on 2026-08-29 via #117085.

The fast half is still open, and 26.6 branch CI went red on it after the other half landed:
ReleaseBranchCI sha bba0a0af903d3ec0b26664d288ee9c14ca8bf0d9 on 2026-08-31 failed
assert 54 == 64 in Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6).

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=26.6&sha=bba0a0af903d3ec0b26664d288ee9c14ca8bf0d9&name_0=ReleaseBranchCI&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%202%2F6%29

That tree carries the slow-test hunk and not the fast one, and in the same run the slow test
passed on all three shards that ran it while the fast test failed on 2/6. Both tests were
green in their [generate_new_create_table_query] form, so only the old-create-table-query
path is affected. The measured rate is low, 2 failures against 732 passes on 26.6 since the
onset, so this is a rare flake rather than a wall.

One observation for whoever picks #113975 up. It is MERGEABLE/UNSTABLE with Finish Workflow
green, and its only red is Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6),
which reported praktika status ERROR after 48 minutes with an empty info, no artifact links
and no test leaves. CIDB has rows for the other 11 integration shards of that run, all with
zero failures, and none at all for 5/6. So the blocker is a lost result on an unrelated
shard, the 26.6 old-analyzer result-loss shape analysed on PR 116721, not a test failure.
Its own old analyzer, 2/6 shard reports Failures: 0/1044, which is the shard carrying both
Kafka tests, so the fix itself is green on 26.6.

26.3 also lacks the slow-test hunk, but that test has 722 passes and 0 failures there over 45
days, so there is nothing to deliver and I am not asking for a 26.3 label.

Session id: cron:clickhouse-plan-slot-33:20260902-205626

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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants