Skip to content

Remap text index posting lists in bulk when merging parts - #122252

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:text-index-merge-bulk-mapoffsets
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:text-index-merge-bulk-mapoffsets

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120802

Changelog category (leave one):

  • Performance Improvement

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

Merging parts of a table with a text index now remaps a whole posting list at once instead of looking up one row id at a time, which makes such merges up to 10% faster. The produced index is unchanged.

Description

Merging a text index remaps every posting row id into the merged part's numbering. After #120982 that is still one PackedPartOffsets::operator[] per (row, token) pair plus one UInt32 check each, although a posting list is a sorted, usually dense run of row ids and a part whose rows the merge did not interleave maps affinely.

PackedPartOffsets now records whether its pages hold a single consecutive run, and gains mapOffsets, which remaps a whole list: one addition per row id for an affine map, one page resolution per run of row ids sharing a page for a dense list, and the per-row-id lookup otherwise, since a sparse list ends a run after a few row ids while that path is already cheap. adjustPartOffsets checks the UInt32 bound once, on the last row id, which adds no assumption: checkRowIdsInPart already reduces the part-rows check on the same arrays to that row id, and the map is increasing, so the last row id maps to the largest value.

Measured with OPTIMIZE ... DRY RUN PARTS over the vocabulary and multiblock layouts of tests/performance/text_index_merge.xml plus an ngrams(3) pair, 20 paired repetitions, arm order rotated, base run twice as an A/A null: disjoint parts -3.5% to -10.6% (ngrams(3) -8.7%), interleaved -2.8% to -4.6%, 95% CIs excluding zero; two layouts inside the null; nothing slower; CPU tracks wall clock. The fixtures are rebuilt here because the vocabulary fill uses rand(id * 15 + x), whose argument is ignored, so running it per arm would merge different data.

The index is byte-identical: over 18 merge layouts every merged part file equals master's, 112 of them skp_idx_*, and query results match. The same rig with that offset off by one reports differing index files. New unit tests pin mapOffsets against operator[] for every page layout the structure builds.


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

MergeTextIndexesTask::adjustPartOffsets rewrote every posting row id from a source
part's numbering into the merged part's numbering one row id at a time, through a
random-access lookup in PackedPartOffsets. A posting list is a sorted, usually dense
run of row ids, and a part whose rows a merge did not interleave maps affinely, so
the page lookup and the per-row-id bound check are paid for and never used.
The report on ClickHouse#120802 measures 12.9% of self time in a profile of an ngrams(3)
merge of 9 parts on an arm64 host. That profile is not reproduced here; what is
measured here is the effect: removing the per-row-id work moves a whole ngrams(3)
merge of disjoint parts by -8.74% [-10.92, -6.56].

PackedPartOffsets now tracks whether its pages hold a single consecutive run and
offers mapOffsets, which remaps a whole array of offsets: by adding one constant
when the map is affine, by resolving each page once per run of offsets on it when
the posting list is dense, and one offset at a time otherwise. A sparse posting list
would end a run after a few offsets while the per-offset path is already cheap,
which is why it keeps that path.

adjustPartOffsets checks the UInt32 bound once, on the last row id, which adds no
assumption: checkRowIdsInPart already reduces the part-rows bound check on the same
arrays to the last row id, because the row ids are sorted by the format, and the map
is monotonically increasing by construction, so the last row id is remapped to the
largest value. A merged part with more than UInt32::max rows still throws, also on
the affine path, because every mapped value is at least the first one, so if the
largest does not fit then neither does the value the check looks at.

mapOffsets returns for every offset exactly what operator[] returns, so the merged
index is byte-identical. The new unit tests pin that against every page layout the
structure can build, for dense and for sparse posting lists.

Related: ClickHouse#120802
Keep the invariants a reader cannot derive (contiguity, page completeness, mapOffsets preconditions, the unsigned page-window wrap, the merge order), drop the narration of the fix itself.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Sep 25, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex, full pass over the three changed files) plus my own cold review of the resulting code, written before reading any implementation evidence. Neither pass found a defect in the mechanism: I re-derived the four mapping strategies against operator[] by hand and they agree by construction, and the run loop always advances, because an offset below the page wraps in defined UInt32 arithmetic and ends the run exactly like an offset above it. The one-check UInt32 bound adds no assumption: the map is strictly increasing by construction and the row ids are sorted by the format, the same premise checkRowIdsInPart already relies on, on the same arrays, for its part-rows bound. It now throws before mutating the array, where the old loop threw halfway through it.

Two fix rounds were bounced; neither changed a tracked file. The published tree differs from the reviewed one by a comment trim only, proven comment-only by a preprocessor-stripped comparison of every changed file.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new unit tests pin output equivalence, so they would stay green if the bulk path degraded back to per-row lookups; the gate asked for test-visible branch counters or a benchmark tied to the production caller. Raised in two consecutive review rounds, so it is surfaced here rather than settled quietly: please overrule me if you want the in-tree assertion. DISAGREE The performance half of the contract is already pinned in-tree: tests/performance/text_index_merge.xml fills multiblock_{codec} and multiblock_intersecting_{codec} deterministically (no rand), covering the affine and the dense-run path, and this change moves those arms by -10.59% [-13.05, -8.14], -6.80% [-8.23, -5.38] and -2.79% [-4.29, -1.28] over 20 paired repetitions against an A/A null of 2.18%, so a revert resurfaces there at the same magnitude. Path selection was confirmed out of tree (5.6M affine, 0.9M run-path, 2.5M sparse row ids, in a run whose merged parts are byte-identical to the base arm's). In-tree counters would put instrumentation inside a header-only structure on the merge hot path, to observe an optimization whose output is provably identical, and would pin min_offsets_per_page_for_runs = 32, a tuning constant I expect to be revisited.
2 ⚠️ My own draft of this PR description inverted which performance fixtures were measured AGREE Rewritten before publication to name the layouts actually measured and to give the real reason they are rebuilt locally (the vocabulary fill's rand(...) argument is ignored, so running it per arm would merge different data). No code changed.
3 ⚠️ The commit message stated a perf self-time figure measured by the reporter on other hardware, without saying so AGREE Attributed, and the figure measured here added instead: a disjoint ngrams(3) merge moves -8.74% [-10.92, -6.56].
4 💡 The consecutive-page run branch and the affine path bypass Page::operator[]'s debug bound assertions Noted, not blocking Release behaviour is identical or safer, and reaching it needs row ids that are both corrupt and unsorted; left unguarded deliberately rather than adding a branch to the hot loop for an unreachable case.
5 💡 is_contiguous's page-continuation test assumes every already-flushed page is exactly full Noted, not blocking It holds by construction: insert flushes only at exactly the page size and the only other flush() runs once at finalization, the same invariant operator[]'s i >> 10 indexing already required.
6 💡 Invariant carriers not named in my own plan: the per-entry remap of position doc ids, the projection consumer of the same map, and the requirement that the map be flushed before it is read Noted, not blocking All relied upon and unchanged; positions are remapped through adjustPartOffset, which is operator[] plus the bound check, so it cannot drift from mapOffsets.

Also noticed and not raised: the in-tree performance test has no ngrams merge fixture, which is where this gain is largest. That predates this change and is nobody's regression.

Severity: ❌ blocker / ⚠️ major / 💡 nit. Row 1 is a disagreement, not a fix, and is called out above so you can require the in-tree assertion if you disagree with my reasoning; every other finding was fixed or is noted as not blocking. The reviewed tree was not edited during review.

Session id: cron:clickhouse-review-slot-10:20260925-133700

@groeneai
groeneai requested review from CurtizJ and ahmadov September 25, 2026 14:26
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af9aa78]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 2/6) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (amd_release, master_head, 3/6) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (amd_release, master_head, 4/6) FAIL Performance dashboard
tokenizers #6 FAIL dashboard
tokenizers #1 FAIL dashboard
Performance Comparison (amd_release, master_head, 5/6) FAIL Performance dashboard
push_down_limit #1 slower query history
Performance Comparison (arm_release, master_head, 3/6) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
Check Results FAIL
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

This PR adds a bulk remap path for text-index posting row ids during merges by teaching PackedPartOffsets to remap a whole posting list at once, then wiring MergeTextIndexesTask to use it. I reviewed the changed code, the added unit coverage, the existing text-index merge/corruption checks, and the prior PR discussion, and I did not find a correctness, safety, or contract issue that warrants an inline review comment.

Final Verdict

✅ No blocking or major issues found in the current PR head (af9aa78062146523c008129fe2a9b37742aab35d).

LLVM Coverage Report

Measured on commit af9aa78.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 25, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 25, 2026
Build (arm_tidy) failed the compile of gtest_merged_part_offsets.cpp:
bugprone-random-generator-seed is promoted to an error by WarningsAsErrors: '*',
and MapOffsetsUnsortedOffsets seeds mt19937 with a constant on purpose, so that a
shuffle failure is reproducible. Suppress the check on that line, which is the
in-tree pattern for a deterministic test seed
(src/Common/tests/gtest_bit_packed_uint64_array.cpp:70,
src/Compression/tests/gtest_pfor.cpp:101).
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 688f8c01-affe-4c04-b165-95124879b1e7
  • MIRAI run: 6ec38df4-796d-412c-ba29-53172768077c
  • PR check IDs:
    • clickbench_1833393_1790362008
    • clickbench_1833399_1790362008
    • clickbench_1833410_1790362008
    • tpch_adapted_1_official_1833416_1790362008
    • tpch_adapted_1_official_1833427_1790362008
    • tpch_adapted_1_official_1833465_1790362008

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - af9aa78

Every failure below has an owner: a fixing PR (mine 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
Performance Comparison (amd_release, master_head, 4/6) / tokenizers #1, #6 dashboard confirmed_regression, client_time +15.8% and +19.2%, while the shard's own report calls nothing slower. The fixture runs tokens() over Memory tables, so it never merges a text index, which is the only thing this PR changes, and CIDB has these two queries unstable on other PRs and on master in the last 7 days ClickHouse/performance-comparison#5 (external), the dashboard's fix for noisy queries scored confirmed_regression on unrelated PRs
Performance Comparison (arm_release, master_head, 3/6) no query was judged: the shard reports performance dashboard verdict unavailable: dashboard did not serve this shard within 600s: run [...] has no arm data for test [add_days_fixed_offset] yet, and the gate fails a shard it could not judge. CIDB has the same message on 21 PRs and one master commit for jobs started 19:05-19:49Z today a fix task is created (investigating at full effort, fixing-PR link to follow here)
Performance Comparison (arm_release, master_head, 4/6) same class, HTTP 404 ... test comparison details not found a fix task is created (the same owner as the row above)
Performance Comparison (arm_release, master_head, 5/6) same class, has no arm data ... yet a fix task is created (the same owner as the row above)
Performance Comparison (arm_release, master_head, 6/6) same class, HTTP 500 ... connection refused from the dashboard's backend a fix task is created (the same owner as the row above)
Performance Comparison (amd_release, master_head, 2/6) same class, HTTP 404 a fix task is created (the same owner as the row above)
Performance Comparison (amd_release, master_head, 3/6) same class, HTTP 500 ... connection refused a fix task is created (the same owner as the row above)
Performance Comparison (amd_release, master_head, 5/6) same class, HTTP 404. The shard's own report also lists push_down_limit #1 as slower; that fixture reads numbers() and no table a fix task is created (the same owner as the row above)
Mergeable Check, PR rollup rows, red only because of the shards above ClickHouse/performance-comparison#5 (external) and a fix task is created, the same owners as the rows above

All 173 check runs completed (146 pass, 19 not selected, 8 red), Finish Workflow is green and
CH Inc sync passed on this head.

Session id: cron:our-pr-ci-monitor:20260925-230059

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison shards that failed with 'performance dashboard verdict unavailable' created: #122369

pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 26, 2026
The REPORT-stage uploads of a performance shard probed CIDB once and
skipped the whole step when that probe failed ("CIDB not ready -
skipping"), and a failed INSERT was not retried either. That was fine
while the tables were informational (ClickHouse#108712), but since ClickHouse#120927 the
performance dashboard computes the master_head verdict from exactly
these tables. A CIDB refusal of seconds or an overload of minutes
therefore dropped the shard's rows, and perf_dashboard_gate then waited
600 s for data that was never sent and failed the shard with "dashboard
did not serve this shard within 600s", blaming the dashboard.

Measured: ClickHouse#113589 arm 6/6 skipped all three uploads on "Connection
refused" and failed after 614 s. On 2026-09-25 a CIDB overload
(TOO_MANY_SIMULTANEOUS_QUERIES, read timeouts) failed 70 shards on 21
PRs and master. In 74 of the 76 occurrences since 2026-09-22 that are
not the time zone shape fixed by ClickHouse#121847, an upload was skipped or
failed. The same run of ClickHouse#122252 is the control: amd 1/6 uploaded and
got its verdict in 2 s, while arm 6/6 skipped the uploads and failed.

Now one helper runs all four INSERT sites. In master_head mode the
three tables the verdict is computed from (query_metric_runs_v1,
query_metrics_v2, perf_test_times_v1) are retried every 60 s until one
600 s deadline, which is taken when the uploads start and shared with
the gate's wait. The other tables keep a single attempt, and nothing is
sent after the deadline. Every attempt carries the same
insert_deduplication_token, because some INSERTs that timed out on the
client had committed on the server. If one of the three inputs was not
uploaded, the gate fails at once and names it instead of polling the
dashboard. A shard without a verdict still fails, as ClickHouse#120927 designed,
and release_base keeps its single call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@CurtizJ CurtizJ self-assigned this Oct 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Dear @CurtizJ, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

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-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants