Skip to content

Fix the TextIndexUsedEmbeddedPostings profile event - #112929

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix/text-index-used-embedded-postings-at-use-site
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix/text-index-used-embedded-postings-at-use-site

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

Related: #103526

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

Fixes the TextIndexUsedEmbeddedPostings profile event, which reported wrong values. It is documented as the number of times an embedded posting list has been used, but it was incremented where such a posting list is decoded from the dictionary. A query served from the text index tokens cache uses embedded postings without decoding them, so the event under-counted real uses, and a background merge decodes them without any query, so it also over-counted.

Description

TextIndexUsedEmbeddedPostings is documented as "Number of times a posting list embedded in the dictionary has been used", but it was incremented inside TextIndexSerialization::deserializeTokenInfo, a byte decoder that takes a ReadBuffer and knows nothing about queries. The decoded token info, including its embedded postings, is stored in the server-global tokens cache, so a later query that hits the cache uses those postings through TextIndexAnalyzer::addTokenInfo with no decoding and no increment. Conversely a background merge decodes every token of a dictionary block, incrementing the event without any query involved.

This restores the placement the event had until commit bd477d0 ("slightly better", part of #98226, a pull request about token ordering), which moved it from the use site into the decoder. Note that TextIndexAnalyzer lived in MergeTreeIndexText.cpp at the time.

The event is now incremented in TextIndexAnalyzer::addTokenInfo, guarded by the existing isTokenNeeded predicate so a posting list that no live query can still consume is not counted. The non-embedded posting path cannot reach it by construction, since the increment sits inside the embedded_postings branch.

Users observing this event will see it rise for cache-served reads and no longer rise during merges. The name and description are unchanged, so no documentation changes.

This does not claim to fix the flaky 02346_text_index_parallel_replicas, whose second probe column reads this event. That test is not modified. The fix removes the only mechanism I could measure for its 1 0 result diff, but 2326 local runs of it never reproduced the CI failure, so I cannot demonstrate the flake is gone.

An alternative is to rename the event and add a new "used" one. That keeps existing dashboards numerically stable but breaks the name across 12 documentation pages, so I preferred making the code match the documented meaning.

Validation

Both directions, with the server restarted per arm and the served buildId() asserted equal to each
arm's readelf -n Build ID:

arm UsedEmbeddedPostings TokensCacheHits TokensCacheMisses
before, cold cache 1 0 1
before, warm cache 0 1 0
after, cold cache 1 0 1
after, warm cache 1 1 0

The new test fails on master with a one-line diff (warm 1 1 0 becomes warm 0 1 0) and passes with
the fix. Its warm row also asserts a cache hit and zero cache misses, so it cannot pass by silently
missing the cache and decoding again.

Mutations, each rebuilt and each moving the Build ID: putting the increment back in the decoder
reddens the warm row; removing it entirely reddens both rows; dropping the isTokenNeeded guard, or
hoisting the increment above the readable-rows block, makes an all-tokens-failed query count 2
embedded posting lists instead of 1.

Regression sweep over 170 text-index tests, baseline built from the same worktree with only the two
source files reverted: the same 170 ran in both arms, 0 regressions, 1 improvement (this pull
request's own test), 3 failures shared by both arms from a bare local sandbox.
02346_text_index_parallel_replicas passes in both arms. 50 randomized runs of the new test: 50
passed, 0 failed.

groeneai and others added 3 commits August 1, 2026 12:03
The event is documented as the number of times a posting list embedded in the
text index dictionary has been used, but it was incremented inside
TextIndexSerialization::deserializeTokenInfo, a byte decoder that takes a
ReadBuffer and has no notion of a query.

The decoded TokenPostingsInfo, including its embedded_postings member, is stored
in the server-global TextIndexTokensCache, so a query that hits the cache uses
those postings through TextIndexAnalyzer::addTokenInfo without deserializing
anything and therefore without incrementing the event. Conversely a background
merge decodes every token of a dictionary block through the same function, which
incremented the event with no query using anything. The event therefore
under-counted real uses and over-counted non-uses.

Move the increment to TextIndexAnalyzer::addTokenInfo, where the embedded
postings enter a query, guarded by the pre-existing isTokenNeeded predicate so a
posting list that no live query can still consume is not counted. The
non-embedded readPostingsBlock route cannot reach it by construction, because
the increment sits inside the embedded_postings branch.

This restores the placement the event had until bd477d0
("slightly better", part of ClickHouse#98226, a pull request about token ordering) moved it
into the decoder. The class TextIndexAnalyzer lived in MergeTreeIndexText.cpp at
that time. The name and description of the event are unchanged, so the code is
being made to match its existing documented meaning.

The new test asserts the event is cache-independent: a cold arm and a warm arm
must both report it, and the warm arm must also report a tokens cache hit and
zero cache misses, so it cannot pass by silently missing the cache and decoding
again. It fails without this change and passes with it.
Review round 1 on the shipped test. The C++ change is unaltered except for a
comment reword; no behavior changes here.

The test now has a third arm covering the `isTokenNeeded` guard. Two tokens whose
postings are embedded sit in disjoint id ranges, so an all-tokens search fails
after the first token and the second token's posting list reaches zero query
builders. The guard makes that read exactly 1 use; deleting the guard makes it
read 2, so the arm reddens and the guard is no longer covered by reasoning alone.
The arm also asserts both tokens really are embedded, since a fixture drifting
above the embedding cardinality limit would otherwise let it pass with nothing
embedded at all.

Two environment pins. The tags now include `no-parallel-replicas`: the assertions
read ProfileEvents from the initiator's query_log row, and events raised on a
remote replica are never merged into it, so the parallel-replicas job would read
numbers that no longer measure the counter placement. And
`use_text_index_tokens_cache` is set explicitly, because a `compatibility`
setting below 26.7 restores it to false, which swaps the server-global tokens
cache for a per-query local one and removes the cross-query hit the warm arm
asserts.

Co-Authored-By: Claude Fable 5 <[email protected]>
The dead-query arm asserts an exact TextIndexUsedEmbeddedPostings count of 1,
which holds only while tab_dead has a single active part: the counter is raised
once per part, so a two-part state reads 2 -- the same value an implementation
without the isTokenNeeded guard produces. In that state the cell stops
discriminating and the arm would pass for the wrong reason.

Two pins make the single-part premise explicit instead of implicit:

optimize_throw_if_noop on the OPTIMIZE ... FINAL turns a refused merge into a
loud error. StorageMergeTree::optimize only throws when that setting is set,
and it defaults to false, so a refusal (for example when the background-memory
soft limit rejects the merge) otherwise succeeds silently and leaves two parts.

max_insert_threads = 1 pins the part count across the whole file. The
tokens-cache key embeds the part's full path, so a change to the active part
set between the cold and the warm query would probe a different key and turn
the warm arm's asserted cache hit into a miss. The test runner randomizes
max_insert_threads, and a query-level SET overrides the injected draw.

Measured: both tables single-part; the amended test passes 50/50 under
randomization; deleting the isTokenNeeded conjunct still reddens the arm with
exactly one changed line, dead 1 -> dead 2.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Before opening this pull request I ran an independent code review plus a second-model review of the
diff, over three rounds, and adjudicated every finding. The final round raised none.

Round 1

# Finding Verdict
❌ The new test 04681 asserts per-query ProfileEvents from the initiator's query_log row but was tagged only no-parallel. The ParallelReplicas functional-test job force-enables parallel replicas in the default server profile (tests/config/users.d/enable_parallel_replicas.xml via install.sh --parallel-rep), and the runner's --no-parallel-replicas only skips tests that carry the tag. Events raised on a remote replica are forwarded to the client, not merged into the initiator's counters (RemoteQueryExecutor.cpp), so the assertions would have depended on how the coordinator split mark ranges. AGREE — no-parallel-replicas added, matching the two sibling tests that assert the same counters
❌ The fix adds a new isTokenNeeded gate on the increment, and no shipped test constrained it: deleting the conjunct left the suite green. AGREE — added a third arm (two cardinality-3 tokens in disjoint id ranges under hasAllTokens, one part) that asserts the exact count 1; deleting the guard makes it 2
⚠️ The warm arm needs the server-global tokens cache, but use_text_index_tokens_cache returns to false under a compatibility setting below 26.7, which swaps in a per-query local cache and removes the cross-query hit. AGREE — pinned with an explicit SET, which applyCompatibilitySetting does not override
⚠️ Suggestion to assert raw exact counts on the cold and warm arms too, not just > 0. DISAGREE — those two arms exist to show the event is cache-independent, and > 0 on both is exactly that claim. The count itself is per-analyzer and one analyzer is built per part per query, so an exact count there would additionally pin the part count, which the dead-query arm already asserts exactly. (My round-1 wording gave a different reason, that the two arms do not pin the part count; round 3 established that they do, so the verdict stands on the reason given here.)
⚠️ Suggestion to add a negative test proving background merges no longer increment the event. DISAGREE — structural, so no oracle can observe it: after this change the event has exactly one increment site in the whole tree, inside the analyzer's embedded-postings branch, and none on any decode path
💡 The guard comment described the sufficient condition rather than the predicate. AGREE — reworded

Round 2

# Finding Verdict
❌ The dead-query arm asserts an exact count of 1, which holds only while the table has a single active part, and OPTIMIZE ... FINAL does not guarantee that: StorageMergeTree::optimize throws on a refused merge only under optimize_throw_if_noop, which defaults to false, so a refusal (for example when the background-memory soft limit rejects the merge) succeeds silently and leaves two parts. A two-part state reads 2, which is exactly the value an implementation without the guard produces, so the cell would stop discriminating. AGREE — optimize_throw_if_noop = 1 on the statement turns the refusal into a loud error. Verified with a positive/negative control on a real no-op: Code: 388 CANNOT_ASSIGN_OPTIMIZE with the setting, silent exit 0 without
❌ The warm arm asserts zero tokens-cache misses, but the tokens-cache key embeds the part's full path, so a change to the active part set between the cold and the warm query probes a different key and turns the asserted hit into a miss. max_insert_threads is randomized by the runner and sink_stream_size follows it. AGREE — SET max_insert_threads = 1, which overrides the injected draw

Round 3 — no findings. Two observations, neither requiring a change. First, the round-2
reachability argument for max_insert_threads does not actually apply at this row count:
min_insert_block_size_rows defaults to 1048449 and the test inserts 100000 rows, so squashing
coalesces into a single block and already pins the part set. The pin is kept because it makes that
premise explicit instead of an artifact of a default three settings away, and it becomes
load-bearing above roughly a million rows. Second, no no-fasttest tag is needed for
mergeTreeTextIndex(): its in-tree users carry that tag only for ICU or libstemmer dependencies
that this test does not have.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SYSTEM DROP TEXT INDEX TOKENS CACHE, then run the same hasAnyTokens query twice. On master the second run reports TextIndexUsedEmbeddedPostings = 0 while the first reports 1. Deterministic: 50 of 50 randomized runs.
b Root cause explained? Yes. The event was incremented in TextIndexSerialization::deserializeTokenInfo, a ReadBuffer decoder with no query context. The decoded token info, including its embedded postings, is stored in the server-global tokens cache, so a later query that hits the cache uses those postings through TextIndexAnalyzer::addTokenInfo with no decoding and therefore no increment. A background merge decodes every token of a dictionary block and incremented the event with no query involved.
c Fix matches root cause? Yes. The increment moves from the decode site to the use site. No widened bound, no no-random-* blanket tag, no reduced dataset, no defensive check masking an upstream bug. This restores the placement the event had until commit bd477d0 moved it.
d Test intent preserved / new tests added? Yes. 02346_text_index_parallel_replicas is not modified and passes in both arms of the regression sweep. A new stateless test has three arms. Two assert the event is cache-independent: a cold arm and a warm arm must both report it, and the warm arm must also report a cache hit and zero cache misses so it cannot pass by silently decoding again. The third asserts the event does not fire for a posting list no live query can still consume; it reads exactly 1 and reads 2 when the isTokenNeeded guard is deleted, so the guard is covered by a shipped assertion rather than by reasoning alone. That arm also asserts both its tokens really are embedded, so it cannot pass because nothing was embedded at all.
e Both directions demonstrated? Yes. The new test fails on master with a one-line diff (warm 1 1 0 becomes warm 0 1 0) and passes with the fix. Server restarted per arm and the served buildId() asserted equal to that arm's readelf -n Build ID; the Build ID moved between arms.
f Fix is general across code paths? Yes. Twelve carriers enumerated and dispositioned. The cache-hit route is fixed; the background-merge over-count is fixed by the same move; the introspection route passes postings_serialization = nullptr and never incremented; the pattern-scan route is now consistent and was verified not to consult the tokens cache; the non-embedded posting route cannot reach the increment by construction, since it sits inside the embedded_postings branch.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. This is instrumentation placement inside an existing branch, so it has no type or parameter surface of its own; what varies is the token's state. Covered: embedded versus non-embedded postings, cache hit versus miss, a live token versus one whose queries have all failed versus a bypassed one, postings clipped to empty versus not, a row range clipped to nothing, and the Any and All search modes.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no serialization format, no SettingsChangesHistory.cpp entry. The event's name and description are unchanged, so the documentation stays byte-identical: the code is being made to match the documented meaning. The numeric value users observe does change, rising for cache-served reads and no longer rising during merges, which is disclosed in the description.
i Invariants and contracts preserved? Yes. addPostings is still called on exactly the same condition as before: only the increment is guarded, not the call, because addPostings also populates tokens_with_postings, can erase from queries_by_token, and increments num_read_postings, all of which are read elsewhere. No lock, allocation, or error path changed. The guard uses the pre-existing isTokenNeeded predicate, and the deliberate asymmetry with the row-range early return is documented in the code.

Session id: cron:clickhouse-impl-slot-47:20260801-134502

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @ahmadov @george-larionov, could you review this? The TextIndexUsedEmbeddedPostings event was incremented inside TextIndexSerialization::deserializeTokenInfo, so a query served from the tokens cache used embedded postings without counting them and a background merge counted them without any query; the increment moves to TextIndexAnalyzer::addTokenInfo, guarded by isTokenNeeded.

@groeneai groeneai mentioned this pull request Aug 1, 2026
1 task done
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ca6811a]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: Query context must be created after authentication (STID: 3197-391f) FAIL cidb
Stress test (arm_asan_ubsan) FAIL
Logical error: Query context must be created after authentication (STID: 3197-391f) FAIL cidb

AI Review

Summary

This PR moves TextIndexUsedEmbeddedPostings from TextIndexSerialization::deserializeTokenInfo to TextIndexAnalyzer::addTokenInfo, so cache-served reads count embedded-posting use while background merges stop inflating the counter, and it adds focused stateless coverage for the cache-hit and dead-query paths. I did not find a correctness, compatibility, or test-soundness issue in the current diff.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — ca6811a

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.

174 check-runs, 0 incomplete (paginated check-runs API), Config Workflow and Finish Workflow both green, last completion 23:47:31Z.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan) / Logical error: Query context must be created after authentication (STID 3197-391f) trunk defect, not PR-caused: PostgreSQLHandler::cancelRequest (PostgreSQLHandler.cpp:867) calls Session::makeQueryContext on the unauthenticated second connection a PostgreSQL client opens to send CancelRequest, so Session::makeQueryContextImpl (Session.cpp:690) throws. 61 rows / 36 PRs / 7 master runs in the last 24 h, first seen 15:04Z today #112940 (external, open)
Stress test (amd_debug) / same STID 3197-391f, identical stack same trunk defect, one cause / two jobs #112940 (external, open)

Reports:

Not PR-caused: this PR touches only the TextIndexUsedEmbeddedPostings profile event, and the failure is reachable with no relation to text indexes. This build's base master (workflow started 16:26:42Z) still contained #110760, which is what made CI reach the pre-existing defect; #112935 reverted #110760 at 17:25:28Z, and #112940 reapplies it together with the actual fix (cancelRequest cancels through ProcessList::sendCancelToQueryOfAnyUser, needing no session). No push here: nothing in this PR's diff is implicated.

Session id: cron:our-pr-ci-monitor:20260802-000000

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

Filed the tracking issue for the CI flake this fixes: #113751. It carries the mechanism, a
local reproduction of the counter defect on 25d677a44eb4, and the occurrence list (12
failures across 11 unrelated pull requests and one master run since 2026-07-01).

As stated there, this PR removes the only measured mechanism for that flake's 1 0 result diff
but 2326 local runs never reproduced the CI failure, so #113751 stays open until CI confirms the
signature is gone. No change to this PR.

@rschu1ze

Copy link
Copy Markdown
Member

Fixes the TextIndexUsedEmbeddedPostings profile event, which reported wrong values. It is documented as the number of times an embedded posting list has been used, but it was incremented where such a posting list is decoded from the dictionary. A query served from the text index tokens cache uses embedded postings without decoding them, so the event under-counted real uses, and a background merge decodes them without any query, so it also over-counted.

Pick your poison. Incrementing TextIndexUsedEmbeddedPostings in TextIndexSerialization::deserializeTokenInfo is one valid way to do it and compared to what this PR proposes, it is also the more native/genuine way.

@rschu1ze rschu1ze closed this Aug 10, 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 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