Skip to content

Keep a live posting list builder in the text index token map when its construction throws - #122699

Merged
ahmadov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-builder-exception-safety
Sep 28, 2026
Merged

ahmadov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-text-index-builder-exception-safety

Conversation

@groeneai

@groeneai groeneai commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A failed allocation while building a text index with support_phrase_search = 1 no longer leaves a destroyed posting list builder in the token map.

Description

Related: #113856

Stress test (amd_msan) aborted with MemorySanitizer: use-of-uninitialized-value (STID 1003-358c) in ~PostingListBuilder, called from HashTable::destroyElements while an INSERT that failed with MEMORY_LIMIT_EXCEEDED was unwinding (report, on an unrelated PR).

MergeTreeIndexTextGranuleBuilder::addToken inserts the token into the map first and then placement-news the builder into the cell. With support_phrase_search = 1 the builder starts in the Large state, whose constructor allocates. When that allocation throws, the builder's lifetime ends inside a cell the map still owns, and the map destroys it a second time when the index aggregator is destroyed. MemorySanitizer reports that second destruction; other builds silently destroy a valueless variant.

constructBuilder now constructs a Filtered builder in the cell when the construction throws, then rethrows. Filtered holds no postings, is constructed without allocating, is trivially destroyed and is skipped by build. The success path is unchanged: the handler only runs when the construction throws.

The new test injects allocation faults into five single-threaded INSERTs of 20000 new tokens into a phrase search text index. On an MSan build it aborts in 20/20 runs without the fix (5/5 with the CI binary) and passes 20/20 with it, with 37 of 50 injected faults landing in the repaired constructor. Other builds only exercise the failure path, since the second destruction has no visible effect there.

Not for changelog: the code is from #113856, which is not in any release, and needs the experimental allow_experimental_text_index_phrase_search.


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

Version info

  • Merged into: 26.10.1.948-master (included in 26.10 and later)

groeneai and others added 2 commits September 28, 2026 12:55
… construction throws

`MergeTreeIndexTextGranuleBuilder::addToken` inserts the token into the
`HashMap` first and only then placement-news the `PostingListBuilder`
into the mapped slot, which `HashMapCell` leaves unconstructed. With
`support_phrase_search = 1` the builder starts in the `Large` state,
whose constructor allocates. When that allocation throws
(`MEMORY_LIMIT_EXCEEDED` from a memory limit or from
`memory_tracker_fault_probability`), the builder's lifetime ends inside a
cell the map still owns, and `HashTable::destroyElements` destroys it a
second time when the exception destroys the index aggregator.
MemorySanitizer (use-after-dtor) reports that as
`use-of-uninitialized-value` in `~variant`, which aborted a
`Stress test (amd_msan)` run; other builds destroy a valueless variant.

If the construction throws, construct a `Filtered` builder in the same
cell before rethrowing. It holds no postings, is constructed without
allocating, is trivially destroyed and is skipped by `build`, and no
caller reuses the builder after `update` throws.

The test injects allocation faults into INSERTs that build such an
index. Without the fix it aborts an MSan build in every run.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120319&sha=256c2d13b6eb62d207bdf619104186595f5b3366&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With more than one thread the pipeline executor schedules its threads on a
local pool when the INSERT starts, and an injected fault inside
`ThreadPoolImpl::scheduleImpl` is reported as `CANNOT_SCHEDULE_TASK`, not
`MEMORY_LIMIT_EXCEEDED`, which fails the statement's error hint under a
randomized `max_threads`. The index build runs in the sink's thread either
way, so the reproduction is unchanged.

Measured on a debug build with 500 such INSERTs per arm, every one failed
with `MEMORY_LIMIT_EXCEEDED` at `max_threads = 3` as at `max_threads = 1`,
with and without `async_insert`, so the scheduling fault is rare (0 of 1000
multi-threaded INSERTs) and the pin removes its code path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 28, 2026
@groeneai

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

Pre-publication review in two rounds by an independent model (engine: codex; 2 findings, then 0 on the fix round) plus my own review (4 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ A fault injected while the INSERT schedules pipeline threads would surface as CANNOT_SCHEDULE_TASK, not MEMORY_LIMIT_EXCEEDED, under a randomized max_threads (own review) AGREE, fixed @ b76e3f9 the five fault-injected INSERTs run with max_threads = 1; precautionary: 0 of 1000 INSERTs at max_threads = 3 hit it, because by default the memory tracker does not refuse operator new
2 ⚠️ The randomized test does not itself prove a fault reaches the repaired constructor DISAGREE exact-test MSan A/B: 20/20 aborts without the fix (5/5 with the CI binary), 0/20 with it; 37 of 50 injected faults landed in PostingListBuilder::Large::Large via constructBuilder
3 💡 Related: line in the description should use the full URL AGREE, fixed description updated
4 💡 First commit message says HashMapCell leaves the mapped value unconstructed, but PairNoInit default-constructs it (own review) noted description corrected; the mechanism (a throwing placement-new leaves a destroyed builder in the cell) is unchanged
5 💡 First commit message says the test aborts an MSan build "in every run" (own review) noted true for the local loop; a fresh-server run can miss when no fault reaches the builder

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-11:20260928-143900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test through clickhouse local --queries-file on an MSan build: 20/20 runs abort with the CI stack and origin without the fix, 5/5 with the binary that aborted in CI.
b Root cause explained? addToken inserts the token first, then placement-news the builder into the cell. With positions the Large constructor allocates; when it throws, the dead builder stays in the map and HashTable::destroyElements destroys it again.
c Fix matches root cause? Yes. constructBuilder, the only construct-into-cell site, puts a Filtered builder into the cell before rethrowing, so every occupied cell holds a live builder.
d Test intent preserved / new tests added? New test 05291_text_index_phrase_search_build_memory_fault: 5 single-threaded fault-injected INSERTs, then a clean INSERT and a hasPhrase check.
e Both directions demonstrated? Yes, on Build-ID-verified MSan binaries of one tree: 20/20 abort without the fix, 20/20 clean with it; 37 of 50 injected faults landed in the repaired constructor.
f Fix is general across code paths? Yes. All three constructBuilder callers and every addToken caller go through the helper; the keep-set assignment builds its temporary first; the add spill leaves a live valueless variant.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Checked String, Array(String), LowCardinality(String) and Map keys (abort without, clean with); without positions the constructor cannot throw.
h Backward compatible? (maintainer-approved exception only) Yes. No format, setting or default change.
i Invariants and contracts preserved? Yes. The placeholder construction cannot throw, throw; rethrows the original exception, build skips Filtered, and no caller reuses the builder after update throws.

Session id: cron:clickhouse-impl-slot-6:20260928-113059

@groeneai
groeneai requested review from CurtizJ and ahmadov September 28, 2026 15:43
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b76e3f9]

Summary: ✅


AI Review

Summary

This PR fixes the failure path when a phrase-search text index allocates its first PostingListBuilder: on construction failure, the map slot is repopulated with a live Filtered builder before rethrowing, so teardown no longer destroys a dead std::variant during insert unwinding. I reviewed the changed MergeTreeIndexText path, the skip-index writer that owns the aggregator, the current PR discussion, and the new fault-injection test, and I did not find any unresolved correctness, safety, or evidence gaps in the current code.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit b76e3f9.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... labels Sep 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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.

Compile time of recompiled translation units

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

Job report

@ahmadov ahmadov self-assigned this Sep 28, 2026
@ahmadov
ahmadov added this pull request to the merge queue Sep 28, 2026
Merged via the queue into ClickHouse:master with commit 39646ee Sep 28, 2026
149 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 28, 2026
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-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants