Skip to content

SparseGrams tokenizer perf improvement - #110541

Merged
rschu1ze merged 15 commits into
ClickHouse:masterfrom
UnamedRus:vk/sparse-grams-tokenizer-perf
Aug 10, 2026
Merged

rschu1ze merged 15 commits into
ClickHouse:masterfrom
UnamedRus:vk/sparse-grams-tokenizer-perf

Conversation

@UnamedRus

@UnamedRus UnamedRus commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Speed up sparse grams tokenizer a bit (should be around 10-20%)

Changelog category (leave one):

  • Performance Improvement

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

Optimized building of text and bloom filter based skip indexes with sparseGrams tokenizer

Version info

  • Merged into: 26.8.1.1090 (included in 26.8 and later)

UnamedRus and others added 3 commits July 15, 2026 04:31
The sparse-grams tokenizer feeds text (`text(tokenizer = sparseGrams(...))`)
and bloom-filter (`sparse_grams(...)`) secondary indexes. Building those
indexes tokenizes every value, and the tokenizer was delivered one token at a
time through `ITokenizer::nextInString`: the whole-string entry points
(`forEachToken`, and therefore `forEachTokenToBloomFilter` / `tokenizeToArray`)
looped over that pull primitive, paying a per-token `std::tie` data-change
check plus offset arithmetic ~2N times for a string of N symbols. That
per-token plumbing, not the token selection itself, dominated the build.

Add a batch `SparseGramsTokenizer::forEachTokenImpl` that generates the whole
string once and hands each token straight to the callback, and route the
`SparseGrams` case of `forEachToken` to it. Same tokens in the same order, so
index contents and the `tokens` function output are unchanged. Also make
`SparseGramsImpl::getNextIndices` iterative and return by out-parameter instead
of constructing an `std::optional` per token, and drop a write-only `position`
field from the convex-hull element.

Measured on bloom-filter index build over 120k random 200-byte values:
`sparse_grams(3, 8)` ~1.25x, `sparse_grams(3, 100)` ~1.12x; the tokenizer in
isolation (`tokens`) ~1.15x. Output verified byte-identical to before across
the `sparseGrams`/`sparseGramsUTF8`/`sparseGramsHashes` functions, the `tokens`
function, and text/bloom index query results.

Adds tests/performance/sparse_grams_index_build.xml covering both index builds
and the isolated tokenizer.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous commit copied `src/Interpreters/ITokenizer.h` from a working tree
based on another feature branch, pulling in unrelated changes (`tokenizeToArray`,
the `IColumn_fwd` include, and `ITokenizer` constructor/`type` tweaks) that are
not part of this change. Restore the file to `master` plus only the batch
`SparseGramsTokenizer::forEachTokenImpl` addition and its dispatch routing.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [85d241d]

Summary: ✅


AI Review

Summary

This PR routes SparseGrams token emission through a batch forEachToken path, removes the recursive/std::optional hot-path overhead in SparseGramsImpl, and adds a dedicated performance benchmark for sparse-grams index build/tokenization. I did not find any unresolved correctness, compatibility, or evidence gaps in the current head after checking the diff, the current code, prior review threads, and the current all-green Praktika run.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

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

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only refactors the sparseGrams tokenizer (sparseGramsImpl.h streaming interface and ITokenizer.h) plus adds a tokenizer perf test — a full-text/bloom-index code path that no ClickBench query exercises. Every flagged query, including the deterministically-flagged Q30 (+18.3%), runs entirely off that path, so the uniform small slowdowns are run-to-run/co-location variance, not a regression from this change. Q30 is downgraded to not_sure and the remaining envelope-suppressed rows are left non-directional. No action needed for the ClickBench results; the sparse-grams tokenizer change looks performance-neutral on this suite.

clickbench

⚠️ 6 inconclusive

Flagged queries (6 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1311 1449 +10.5% 0.0002 This PR only touches the sparseGrams tokenizer, which Q18 never exercises, so the +10.5% is off-path variance and the non-directional verdict is correct.
⚠️ 28 not_sure 1048 1104 +5.3% <0.0001 Q28 does not use any sparse-grams/text-index path, so the +5.3% cannot be attributed to this PR; the suppressed verdict is correct.
⚠️ 30 not_sure 279 330 +18.3% <0.0001 The +18.3% is deterministically flagged, but this PR only changes the sparseGrams tokenizer, a full-text-index path Q30 never runs, so this is off-path variance not a PR effect.
⚠️ 32 not_sure 1320 1451 +9.9% <0.0001 The changed code is the sparseGrams tokenizer; Q32 does not touch it, so the +9.9% is unrelated run-to-run variance.
⚠️ 33 not_sure 1236 1337 +8.2% <0.0001 Q33 exercises no tokenizer/text-index path, so the +8.2% is off-path variance; the non-directional verdict is correct.
⚠️ 34 not_sure 1256 1360 +8.3% <0.0001 Q34 does not run the sparseGrams path this PR modifies, so the +8.3% cannot be a PR effect and is correctly left non-directional.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 126613c1-65ec-464a-a4f5-e07e0c039fdb
  • MIRAI run: 4ddb4830-e557-4576-a4bf-37f5cb860eab
  • PR check IDs:
    • clickbench_1801738_1785940285
    • clickbench_1801747_1785940286
    • clickbench_1801756_1785940285
    • tpch_adapted_1_official_1801772_1785940285
    • tpch_adapted_1_official_1801794_1785940287
    • tpch_adapted_1_official_1801808_1785940288

Comment thread src/Interpreters/ITokenizer.h Resolved
@Ergus Ergus self-assigned this Jul 20, 2026

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree here with the Bot about the perf test.
The code looks correct so far and the de-recursion is always better to read :). However, I won't really expect any measurable performance difference from it.

Let's see the performance results before approving

/// bypassing the per-token `nextInString` pull (its `std::tie` data-change check and offset
/// arithmetic on every token). Emits the same tokens in the same order as `nextInString`.
template <Fn<bool(const char *, size_t)> Callback>
void forEachTokenImpl(const char * __restrict data, size_t length, Callback && callback) const

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the only change that I think could produce some real improvement.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's seems consistently show around 10% time improvement, but i cannot guarantee that's all of changes are required for that, indeed.

https://performance.ci.clickhouse.com/runs/pr-110541-dd94677a76800093e88be94de43a1931f7ed63a5/tests/sparse_grams_index_build?query_index=0

Reduced the number of rows inserted into sg_src from 5 million to 1 million for performance testing.
Comment thread src/Functions/sparseGramsImpl.h Outdated
}

std::optional<SubString> getNextIndices()
/// Drain the current batch of answers, refilling it via `consume` until there is a result or the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@UnamedRus The irrelevant slop in the comment will need to go first:

Iterative (not recursive) and returns by out-parameter rather than an `std::optional`; both are on the hot path, called ~2N times for a string of N symbols.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, slightly changed, but can't think of something significantly better worder.

Comment thread src/Interpreters/ITokenizer.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.40% 78.40% +0.00%

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

Full report · Diff report

@UnamedRus
UnamedRus requested a review from rschu1ze August 3, 2026 19:05

@rschu1ze rschu1ze left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Defer to @Ergus for review.

I see that the new performance tests (results) shows improvements but it also runs too long in absolute terms. Runtimes are ideally at most 1 sec.

Image

@UnamedRus

Copy link
Copy Markdown
Contributor Author

Sure, i increased perf test size because original scale didn't show perf improvement confidentially.

<create_query>CREATE TABLE sg_text_3_8 (s String, INDEX idx s TYPE text(tokenizer = sparseGrams(3, 8)) GRANULARITY 1) ENGINE = MergeTree ORDER BY tuple()</create_query>
<create_query>SYSTEM STOP MERGES</create_query>

<fill_query>INSERT INTO sg_src SELECT randomPrintableASCII(200) FROM numbers(1_500_000)</fill_query>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@UnamedRus This commit made the perf test bigger, not smaller. Like to reduce from 1.5 mio to let's say 150k?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's got somewhat messy,
Initially it was 1 Mil row test, which show different barely visible, (may be few dozen less stack traces frames in tokenizer code)
Then i bumped it to 5Mil, which showed that reliable enough.
But, as you noticed it made test run longer, multiple seconds per each query.
So, i decreased it, but to slightly bigger than it was initially (1M -> 1.5M)

Last (fast) run, where difference is barely noticeable at 1.5M rows
https://performance.ci.clickhouse.com/runs/pr-110541-85d241dbd9915a2a30a739c595bf79ce1e5638f7/tests/sparse_grams_index_build?query_index=1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay then, tnx.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, may be it's me, who is wrong. (new perf dashboard is bit silly in showing which metric change is actually useful/important)
image

https://s3.amazonaws.com/clickhouse-test-reports/PRs/110541/85d241dbd9915a2a30a739c595bf79ce1e5638f7/performance_comparison_amd_release_master_head_2_6/report.html
This is last run, we have 4 queries in test, and it's 1.3-1.8s total time per query (so user time probably 16x of that) , is that acceptable or, should i tune it down?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's fine - I think we (ClickHouse) will need to do a sweep of the performance test results and trim runtimes of all overlong tests.

@rschu1ze
rschu1ze added this pull request to the merge queue Aug 10, 2026
Merged via the queue into ClickHouse:master with commit ddf3e53 Aug 10, 2026
179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Aug 11, 2026
…x_build_test_fix

Follow-up for ClickHouse#110541 (reduce size of sparse grams build test)
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-performance Pull request with some performance improvements 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.

5 participants