Skip to content

Fix off-by-one and integer overflow in Wasmtime memory bounds check - #1

Closed
bacek wants to merge 1 commit into
masterfrom
spr/master/e31f0f25
Closed

bacek wants to merge 1 commit into
masterfrom
spr/master/e31f0f25

Conversation

@bacek

@bacek bacek commented Mar 13, 2026 •

Copy link
Copy Markdown
Owner

WasmTimeCompartment::getMemory used ptr + size >= memory_span.size()
which has two bugs:

  • Off-by-one: a slice that exactly reaches the end of memory
    (ptr + size == memory_span.size()) is a valid access but was
    incorrectly rejected.

  • Unsigned integer overflow: WasmPtr and WasmSizeT are both
    uint32_t. With ptr = 0xFFFFFFFF, size = 1 the addition wraps to
    0, the check passes, and memory_span[0xFFFFFFFF] is accessed far
    outside the WASM linear memory, breaking sandbox isolation.

Fix: rewrite the check as size > memory_span.size() || ptr > memory_span.size() - size,
which avoids any addition and correctly accepts the boundary case.

The WasmEdge backend is not affected (it delegates bounds checking to
WasmEdge_MemoryInstanceGetPointer).

Co-Authored-By: Claude Sonnet 4.6 [email protected]


Stack:


⚠️ Part of a stack created by spr. Do not merge manually using the UI - doing so may have unexpected results.

`WasmTimeCompartment::getMemory` used `ptr + size >= memory_span.size()`
which has two bugs:

- Off-by-one: a slice that exactly reaches the end of memory
  (`ptr + size == memory_span.size()`) is a valid access but was
  incorrectly rejected.

- Unsigned integer overflow: `WasmPtr` and `WasmSizeT` are both
  `uint32_t`. With `ptr = 0xFFFFFFFF, size = 1` the addition wraps to
  `0`, the check passes, and `memory_span[0xFFFFFFFF]` is accessed far
  outside the WASM linear memory, breaking sandbox isolation.

Fix: rewrite the check as `size > memory_span.size() || ptr > memory_span.size() - size`,
which avoids any addition and correctly accepts the boundary case.

The WasmEdge backend is not affected (it delegates bounds checking to
`WasmEdge_MemoryInstanceGetPointer`).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

commit-id:e31f0f25
@bacek bacek closed this Mar 13, 2026
bacek pushed a commit that referenced this pull request Apr 1, 2026
## #1: Cross-test ownership ratio (find_tests.py)

Replace plain `1/width` scoring with `1/(width × region_test_count)` where
`region_test_count = uniqExact(test_name)` for each region.  A region covered
by 1 test scores 1000× higher than one covered by 1000 tests, naturally
eliminating the hot-region problem without a hard cap.

## #2: Branch direction (LLVMCoverageMapping + coverage_log)

Parse `BranchRegion` (LLVM kind=4) in `readLLVMCoverageMapping`.  Format:
kind-marker → true_counter → false_counter → line/col, producing two
`CoverageRegion` entries with `is_branch=true` and `is_true_branch` set.
Added `branch_flags Array(UInt8)` to `system.coverage_log` (0=code, 1=true,
2=false).  Tests that covered both sides of a changed condition now carry that
information for smarter ranking.

## #3: Indirect call targets (coverage.h/cpp + CoverageCollection)

Read `LLVMProfileData::Values` (LLVM value profiling, kind IPVK_IndirectCallTarget)
to capture which concrete functions were called via virtual dispatch or function
pointers.  Each observation: `(caller_name_hash, caller_func_hash, callee_offset,
call_count)` where `callee_offset = callee_abs − binary_load_base` (from
`/proc/self/maps`), stable across ASLR restarts.  Flushed alongside coverage
counters into `system.coverage_indirect_calls`.  Fixes the fundamental gap where
a test covering `IStorage::read` cannot be distinguished from a test specifically
dispatching to `StorageMergeTree::read`.

## #4: XRay call-depth tracking (coverage.h/cpp + cmake/sanitize.cmake)

New CMake option `WITH_COVERAGE_XRAY=ON` enables `CLICKHOUSE_XRAY_INSTRUMENT_COVERAGE`.
At test start, activates XRay (`__xray_patch`) with a handler that maintains per-thread
relative call depth.  On first activation, builds a `(xray_function_id → profile_data_index)`
map by resolving each function via `__xray_function_address(id)` + `dladdr()` → symbol name
→ FNV64 hash → match against `LLVMProfileData::NameRef`.  This solves the PIE
`FunctionPointer=0` limitation: XRay provides real runtime text addresses where
`LLVMProfileData::FunctionPointer` is always null.  When enabled, `min_depth` in
`CovCounter` contains actual call depth; otherwise falls back to call-count proxy.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
bacek pushed a commit that referenced this pull request Apr 1, 2026
…call)

Evaluation: 50 recently merged PRs, 1319 test instances from CIDB targeted
job, compared against new find_tests.py output.

Changes:

1. Per-file keyword matching: call _get_keyword_fallback_tests once per
   changed C++ file instead of once for all files.  Previously a PR touching
   ArrowColumnToCHColumn.cpp + MsgPackRowInputFormat.cpp would pick only
   'Pack' (5 hits, more specific) as the single keyword, missing all 54
   arrow tests.  Per-file: Arrow (54) + Pack (9) = 63 tests found.
   Impact: PR 100038 improved 39%→68%.

2. 3-char all-uppercase acronyms allowed: CSV, ORC, URL, JWT, etc. now
   qualify as keywords (previously filtered at length < 4).  Generic 3-char
   acronyms (API, SQL, DDL, etc.) added to COMMON_ACRONYMS blacklist.

3. Merge trailing single-uppercase suffix into preceding word: regex split
   of 'optimizeTopK' produced ['optimize', 'Top'] losing 'K'.  Added [A-Z]
   to the findall pattern and merge single-char uppercase tokens into the
   previous word → 'TopK' emerges correctly.  Also fixes 'MergeN', 'DataN'.

4. Broad-keyword fallback when no specific/dir keyword exists: previously
   returned empty if all file keywords had > SPECIFIC_MAX=100 hits.  Now
   falls back to the best broad-tier keyword (101–200 hits) as last resort.
   Fixes: KeeperStorage.cpp → 'Keeper' (156 hits) now finds 156 keeper tests.

5. Zero-hit directory keyword skip: if a path-component keyword matches zero
   test files (e.g. 'Coordination' for KeeperStorage.cpp) it is silently
   skipped rather than blocking the file-keyword fallback.

6. Zero-coverage fallback also uses per-file calling (same fix as #1).

Recall on 50-PR / 1319-instance benchmark:
  Baseline (before this session's work): 67%
  After previous commit (pass weights, supplement pass): ~68%
  After this commit: 70%

Ceiling analysis: 58% of misses (228/393) are previously-failed tests
recorded by CIDB during PR development — these can't be recovered when
running locally on merged PRs.  Another 12% are new test files added by
the PR (not in local checkout).  The remaining 30% are genuine coverage
gaps, with format-domain tests (Parquet/Arrow/ORC cross-keywords) being
the largest fixable category.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
bacek pushed a commit that referenced this pull request May 13, 2026
`AtomicStopwatch::compareAndRestart` and `compareAndRestartDeferred`
computed `UInt64(seconds * 1000000000.0)`, which is undefined behavior
once `seconds * 1e9` exceeds `UInt64::max`. AST fuzzer reaches this path
on `MergeTreeCleanupThread` when the cleanup-interval setting is tuned
to an extreme value and the `UInt64` setting is cast to `double` at the
call site, producing:

```
src/Common/Stopwatch.h:158:35: runtime error: 9.22337e+27 is outside the range of representable values of type 'unsigned long'
    #0 AtomicStopwatch::compareAndRestartDeferred(double) src/Common/Stopwatch.h:158:35
    #1 DB::MergeTreeCleanupThread::iterate() src/Storages/MergeTree/MergeTreeCleanupThread.cpp:50:55
```

Centralise the conversion in `secondsToNanoseconds`, saturating non-finite-sized
inputs at `UInt64::max / 2`. The saturation point is chosen so that
`current_start_ns + threshold` cannot wrap inside the compare-and-restart
loop, preserving "huge threshold → never restart" semantics rather than
silently flipping the comparison.

Adds a gtest covering both methods at `UInt64::max`, `Int64::max`,
`1e30`, and non-positive inputs.

Reported in PR ClickHouse#101033 CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101033&sha=eef19f6d6cde3553b66443d7ec26b2e035d45225&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
STID: 3324-4bde

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bacek pushed a commit that referenced this pull request May 14, 2026
…tion` regressions

`generate_table_function #1` (8 integer column types, 1B rows) regresses ~18% and `#5`
(Date/DateTime, 1B rows) regresses ~16% on AMD release.

`fillColumnWithRandomData` is a big switch over `TypeIndex` that constructs a fresh
column for every block.  At `-march=x86-64-v3` the SLP vectorizer lowers the implicit
~32-byte zero-init of each newly-allocated `ColumnVector`/`ColumnString` to a
`vpxor xmm0; vmovdqu ymm0` pair (29 occurrences in PR vs 0 in master).  Each YMM
store dirties the upper YMM state, so clang inserts a `vzeroupper` (30 inserted)
before every external call from the dispatcher (`operator new`,
`PODArrayBase::reallocPowerOfTwoElements`, etc.) - the per-block dispatch ends up
bracketed by ~30 SSE/AVX transitions for no benefit (the inner PCG generation loop
is byte-equivalent to master's).

The inlined PCG inner loop is the dominant per-row cost, but at v3 the broader
function bloats from 16654 to 18241 bytes (+10%) and the cumulative `vzeroupper`
overhead in the per-block dispatch is what surfaces as the +15-18% regression.
The integer/Date paths are uniformly affected; Decimal/Float paths (#7/#8/#9)
do not regress because they go through a different per-element loop with no YMM
zero-init.

Compiling at v2 keeps the XMM-only zero-init that does not require `vzeroupper`.
The hot PCG inner loop's quality is not affected (master is already at v2 and
generates the same scalar code).

Local Sapphire Rapids LTO (max_threads=12, 10 iter):
  - `#1`:                      master 0.521s, PR 0.521s  (was 0.614s, +18%)
  - `#5`:                      master 0.177s, PR 0.178s  (was 0.208s, +16%)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bacek pushed a commit that referenced this pull request May 14, 2026
…ssion

At v3 the `UniquesHashSet::merge` probe loop lowers `good(hash) = (hash >> s) << s == hash`
to BMI2 `bzhi`/`shlxq`/`shrxq`, which is slightly slower than the legacy `shl %cl + not + test`
sequence on Sapphire Rapids and regresses `uniq_stored #1` by ~9%. Building this single TU with
`-mno-bmi -mno-bmi2` restores the legacy shift codegen while keeping the rest of v3
(AVX2/FMA/etc.) untouched. Bench: v2 0.214s, v3-LTO before 0.233s (+9%), v3-LTO after 0.218s.

The override must live in `src/AggregateFunctions/CMakeLists.txt` because that is where the
`clickhouse_aggregate_functions` target is created. `set_source_files_properties` set in the
parent `src/CMakeLists.txt` scope does not propagate to a target defined in a subdirectory
(unlike the `StorageGenerateRandom` precedent, where the file is absorbed into the `dbms`
target in the same scope via `add_object_library`).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bacek pushed a commit that referenced this pull request Jun 10, 2026
ClickHouse#106278 tried to remove the LIMIT-without-ORDER-BY non-determinism by
sampling with WHERE cityHash64(WatchID) % N = 0. Post-merge master data
showed it did not work: it made the measured queries scan the whole table on
every run, so instead of reducing the noise it regressed it badly:

  classification #0: 6.5% -> 76% noisy
  classification #1:  10% -> 90% noisy

(#2/#3/#4 were already clean.)

Materialize the deterministic subset once into its own single-part table
(single-threaded insert + OPTIMIZE FINAL) and measure over that, so the
determinism lives in the setup (like ClickHouse#106249 for reading_from_file) and the
measured queries read only the subset instead of rescanning the source.
bacek pushed a commit that referenced this pull request Jul 11, 2026
- Resolve setting query parameters on a copy of the changes instead of
  mutating the AST, so the placeholders are preserved for the old-server
  compatibility rewrite in ClientBase::processOrdinaryQuery (review major #1).
- Pass the changes to checkSettingsConstraints as const: the non-const
  overload rewrites the list and drops no-op changes, which lost the
  "changed" flag for a setting explicitly set to its current value
  (e.g. SET log_queries = 1) and broke 03595_set_query_no_eq_set_to_one.
- Teach QueryParameterVisitor / analyzeReceiveQueryParams to discover query
  parameters used as setting values (stored inside FieldFromAST), so
  predefined HTTP handlers accept param_<name> for them (review major #2).
- Renumber the stateless test to 04416 to satisfy the test-numbers style check.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Aug 3, 2026
Fix column index in temporary-table path of system.tables
bacek pushed a commit that referenced this pull request Aug 17, 2026
The assertion added in the previous commit checked the join output header for
__join_result_dummy. That column is synthesized by JoinStepLogical whenever the
join has no required output columns (JoinStepLogical.cpp addToNullableIfNeeded,
the `if (outputs.empty())` branch), which is a property of the SELECT list, not
of the right side. It happened to discriminate the constant-folded `a >= 0`
shape only because that shape leaves `b.size` as the single surviving output
column, so the join output header names it instead of the dummy. That is an
incidental property of this query, not a robust one: any shape where the
surviving column comes from the left side would keep the dummy in the output
header while the right side still fed a non-empty block into the join.

Assert on the right pre-join input header instead, via EXPLAIN
input_headers = 1. `#1 Empty header` is printed exactly when the right input
header has no columns (QueryPlan.cpp explainStep, the `input_header->empty()`
branch), which is the representation under test.

The new form discriminates four mutations where the old one discriminated two:
the constant-folded `a >= 0` shape, a swapped join order, selecting a right
column so PREWHERE no longer consumes all of them, and dropping PREWHERE
entirely.

Reported by clickhouse-gh[bot].
bacek pushed a commit that referenced this pull request Aug 18, 2026
Casting a tag-less vector to a vector grid generated the group #0
constant as a plain literal 0 which ClickHouse types as UInt8, while
timeSeries* functions require UInt64. The clamp() empty-result path for
non-constant bounds converts scalar-backed vectors through toVectorGrid,
so clamp(vector(5), time() * 0 + 1, -1) failed with
'Argument #1 of function timeSeriesGroupToTags has wrong type UInt8'.

Same fix as in ClickHouse#111872 (which covers the remaining converter sites);
the identical hunks will merge cleanly whichever PR lands first.
bacek pushed a commit that referenced this pull request Aug 18, 2026
The UInt64 casts for the no-tags group #0 constant (toVectorGrid,
label manipulation functions, empty on() in binary operators) had no
PromQL test exercising them, so the original "Argument #1 of function
timeSeriesGroupToTags has wrong type UInt8, it must be UInt64" failure
could regress without being noticed. Cover binary operators (including
an empty on() over tag-less vectors), label_replace(), label_join(),
topk() and the SCALAR_GRID range paths.
bacek pushed a commit that referenced this pull request Aug 26, 2026
`AggregatingTransform::initGenerate` used `many_data->variants.size()` as the
number of producers to wait for on the finish barrier. That vector is sized at
construction and used to be immutable afterwards, but the adaptive aggregation
made the last finisher append the early-drain routing table to it, so the
vector grows while the producers that are still arriving read its size:

    Write of size 8 ... by thread T1033:
      #7 DB::AggregatingTransform::initGenerate() src/Processors/Transforms/AggregatingTransform.cpp:1375
    Previous read of size 8 ... by thread T1187:
      #1 DB::AggregatingTransform::initGenerate() src/Processors/Transforms/AggregatingTransform.cpp:1319

Count the producers with `ManyAggregatedData::num_producers`, fixed at
construction time, so the barrier never reads the vector that the last
finisher grows. The barrier's outcome is unchanged: only the finisher whose
`fetch_add` returns `num_producers - 1` proceeds, and it is the only thread
that touches `variants` afterwards.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=ed4df189fc08473dd6cee5c84b4fce89d49ca640&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29

Caused by: ClickHouse#111459
bacek pushed a commit that referenced this pull request Oct 3, 2026
…der unsigned type

ClickHouse#119616 made the code-size pruning of mixed wide `modulo` / `moduloOrNull`
pairs convert every unsigned operand to the next signed size (up to
`Int256`), and stopped pruning pairs with a `UInt256` operand. Both are
needed only when one of the operands is signed. For two unsigned operands
`ModuloImpl` takes the plain remainder in the wider unsigned type, so the
widening only adds cost: `UInt128 % UInt16` ran as `Int256 % Int256`
(a 256-bit division per row), and `UInt256 % UInt64` lost the pruning.

Use the wider of the two unsigned types again (the rule before ClickHouse#119616)
when both operands are unsigned; pairs with a signed operand keep the
ClickHouse#119616 rule. Results, result types and errors do not change.

Release build without LTO, clickhouse-local, max_threads = 1, median of 14:
- min_max_wide_integers ClickHouse#14, GROUP BY u128 % 1000: 0.365 s -> 0.114 s
- wide_integer_division ClickHouse#19, modulo(UInt128, UInt16): 0.053 s -> 0.012 s
- wide_integer_division #1, modulo(UInt256, UInt64): 0.067 s -> 0.035 s
- controls modulo(Int128, UInt16), intDiv(UInt128, UInt16): unchanged

These are the queries that became slower on master right after ClickHouse#119616;
ClickHouse#14 was reported slower on ClickHouse#112950.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Oct 3, 2026
…nce per block

`mortonEncode` with two arguments ran one row loop for every argument type
and mask: per row and argument it tested the mask and `is_const`, reloaded
the ratio, switched on the column width and, with a mask, called the
out-of-line `expand` (36 call sites in the arm `executeImpl`). On arm the
speed of the branch-dense paths depends on the binary's layout, so
`space_filling_curve` #1 (constant mask) and #4 (`UInt32` arguments) have
per-build speed modes and flag unrelated PRs in Performance Comparison
(ClickHouse#122482), while #2 (two `UInt64` columns) is stable.

Now each argument is resolved once per call into a contiguous `UInt64` array
with the range expansion applied: a `UInt64` column that needs no expansion
is read in place, other widths are widened with one type dispatch, and a
constant ratio is applied in one loop per ratio value (`expand` is
`ALWAYS_INLINE` and called with a template-constant ratio, so its switch
folds). A per-row mask keeps the per-row `expand`. `nd == 1` writes the
result column directly. The encode loops only encode.

x86, one core, median fix/base of 5 interleaved rounds over the queries of
`space_filling_curve.xml`: #1 0.57 (BMI2) / 0.55 (lookup-table path, built
with `-mno-bmi2`), #2/#3/#6 0.45-0.64, #4 0.86-0.88, untouched functions
0.99-1.03. Results are unchanged: 545 checksums over every width, mask and
ratio are byte-identical before and after on both code paths, and the new
test fails on both paths under two mutations of the change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Oct 3, 2026
…test

The two compared servers each built a different copy of the fixture:

- `rand64() % 5000000` makes the number of rows with key 5, which queries
  #1 and #3 look up, a fresh draw per server (0 to 3 over 10 local fills);
- each INSERT is squashed into ~5 parts (cut at min_insert_block_size_rows),
  which merge until perf.py's --stop-merges freezes them at a per-server
  point.

#1 and #3 read about one granule per part, so each server read its own
number of granules: in CI the servers read different parts in 80% of runs,
and time follows the rows read (correlation 0.85-0.88). This redded
unrelated PRs (e.g. ClickHouse#118662, arm 4/6, #1 +37.5% confirmed_regression) and
inflated the learned threshold of #1/#3 to 0.41-0.53 (0.04-0.09 for
#0/#2/#4 on the same tables); the dashboard now caps both at
likely_regression as "Flaky lately", so a real regression there cannot red.

Use deterministic data, cityHash64(number, 7) and cityHash64(number, 11)
modulo 5000000 (same key range and duplicate profile; the seeds put key 5
once in each table, the modal case of the random draw, so #1/#3 keep
measuring a non-empty point join), and write each table as one part with
min_insert_block_size_rows = 10000000, min_insert_block_size_bytes = 0
(5M rows give one squashed block). A throwIf on system.parts fails the
fill if the layout ever drifts. Same shape as ClickHouse#122479 and ClickHouse#122660.

Validated through perf.py --stop-merges on two servers, 5 fresh fills per
arm: new fixture identical on all 10 server fills (one part per table, same
data, #1/#3 read 2 granules on both, #0/#2/#4 read 10M rows); old fixture
different on all 5 iterations. Without the insert settings the throwIf
fails the fill.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 19, 2026
…ight-table column

The hash join probe loops called the out-of-line AddedColumns::appendFromBlock
for every matched row. When the join outputs no column of the right table,
record_row_refs is false and the callee returned immediately, but the call
stayed in the loop, and its cost depended on where the linker placed the loop
and the callee: join_squashing_blocks #0/#1 ran 17-20% slower in about one
build in 64 (the amd_release reds on ClickHouse#122184 and ClickHouse#120758), and 1.4x slower in
some process starts.

Make appendFromBlock ALWAYS_INLINE so the record_row_refs test happens in the
loop, and keep the recording part, LazyOutput::addRef, out of line with
NO_INLINE: inlining its body into every probe loop made
hashjoin_low_cardinality_key #0 5-10% slower and pushed processMatch out of
line, even in loops where addRef never runs. Joins that record row refs keep
one call per match, to the same body as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Nov 14, 2026
…up window

`NegativeLimitBySortedStreamTransform::consume` sent every group, even one
that starts and ends inside the current chunk, through the sliding window:
`append_run` pushed a `ChunkSlice` into the empty window deque (allocating the
deque map and a block, and copying the chunk `shared_ptr`), `finalizeWindow`
copied it into `pending` (a second `shared_ptr` copy) and then `window = {}`
(libc++: `clear(); shrink_to_fit();`) freed the block and the map. So each
one-row group cost two memory-tracked allocations, two frees and two atomic
increment/decrement pairs, plus one `pending` entry.

The window is only needed for a group that touches a chunk boundary. A group
that ends inside the chunk while the window is empty also started inside this
chunk, so its output is known when its end is found: the last
`min(L, length + offset)` rows of the run without the trailing `offset` rows,
the same rows `append_run` + `dropExcessRows` + `dropOffsetRows` keep for a
one-slice window. Such groups are now staged into `pending` directly, and
`appendToPending` extends the last pending slice when the new rows continue
it in the same chunk, so the one-row groups of a chunk become one slice.
`generate()` produces the same chunk for a merged slice (same rows, first
start and last end). Groups touching a chunk boundary still use the window.

Evidence that this path is what moves the `negative_limit_by_in_order`
queries #0, #1 and #8 (millions of groups): ClickHouse#125000, which changed only the
allocator of these deques, moved them by -19/-16/-17% on master d3ee313 while
#2-#7 stayed flat; and the ClickHouse#125013 perf job's prewarm counters for #0 show
equal instructions on both sides (10301M vs 10333M, ~1030 per group) and +15%
cycles on one build.

Local A/B (release build, `CMAKE_BUILD_TYPE=None`, no ThinLTO, the perf
test's tables and queries, 12 rotating rounds, geomean of per-round ratios
new/base with bootstrap 95% CI):

  #0 10M one-row groups      0.764 s -> 0.096 s  0.123 [0.113, 0.135]
  #1 1M groups of 10         0.098 s -> 0.049 s  0.457 [0.413, 0.510]
  #2 100k groups of 100      0.025 s -> 0.019 s  0.707 [0.642, 0.785]
  #3-#7 100 groups           0.86-1.03, no CI lower bound above 1.0 (4-15 ms)
  #8 5M two-key groups       0.447 s -> 0.116 s  0.250 [0.236, 0.265]

User-space instructions of 5 runs of #0: 60.3G -> 10.2G (~1190 -> ~190 per
group after subtracting 5 runs of #3), cycles 16.2G -> 3.1G; #8: 31.4G ->
6.4G instructions. In the base profile of #0 about half of the samples are
in the deque allocation, `shrink_to_fit`, `CurrentMemoryTracker` and
jemalloc; none of them is in the top 15 after the change.

Replacing only `window = {}` by `clear()` (keeps the deque blocks) gives
0.526 / 0.594 / 0.583 on #0 / #1 / #8, so the direct staging is 4.3x and
2.3x faster than that on #0 and #8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Nov 16, 2026
…oop over batches of rows

The previous commit replaced the per-row `isCancelled` load with a mask
test on the row index. On AArch64 clang-23 keeps that test and its branch
in the row loop (`tst x23, #0x3ff; b.ne` per row, the only difference
from the previous build of this branch), and `limit_by` #0/#3/#5/#6 and
`optimize_limit_by_keys` #0/#1 are 1.18-1.22x slower than master there,
while the two previous runs had them at 1.00x.

Make the batching explicit instead: an outer loop over batches of 1024
rows checks for cancellation, and the inner row loop contains the hash
lookup only. Measured with the CI binaries on a Graviton 4 host against
the clang-22 master build: 0.99-1.05x (PR build: 1.18-1.22x).

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117346&sha=d847a368b13c19355fbfac4bbcec67663d20ec9f&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29
PR: ClickHouse#117346

Co-Authored-By: Claude Fable 5.1 <[email protected]>
bacek pushed a commit that referenced this pull request Nov 16, 2026
…registers

After the outer batch loop of c23127a, clang 23 on AArch64 keeps two values
in `consumeImpl` that depend on the current row's hash table load in callee-saved
registers. The out-of-line `processRunInsideWindow` saves and restores them in
`stp`/`ldp` pairs together with registers on the next row's key load path, so the
next lookup waits for the previous row's cache miss: `limit_by_in_pk_order` #3
+80%, `limit_by_with_order` #1 +77%, `limit_by` #1 +42% on ARM, with user time
x1.91 and the same page faults. This is the mechanism of e16e062, one call
level down.

Move the growth of `output_slices` into a separate function reached by a tail
call, so `processRunInsideWindow` makes no calls and saves only `x29`/`x30`
(checked in an AArch64 ThinLTO build of the translation unit with clang 23.1.4;
on x86 it saves nothing either).

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117346&sha=8675465598566b9a2f459432b9831f33b2876b86&name_0=PR
PR: ClickHouse#117346

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Nov 16, 2026
The collation sort (#2, 5M rows) and the single-column string sort (#3,
20M rows) take 1.2-1.9 s on MasterCI on both arches. They get
disabled="1" (text and number unchanged) and are appended as #9 and #10
on a quarter of the rows with max_block_size = 16384, a quarter of the
default 65409. `numbers_mt` hands out blocks of exactly max_block_size
rows, so each copy has as many blocks as its original (77 and 306): the
same number of cursors in every per-stream merge and the same 16-stream
final merge, with a quarter of the rows per block. EXPLAIN PIPELINE of
each original and its copy is identical (16 streams).

Measured on official MasterCI release builds, two servers pinned to 24
cores of one NUMA node, perf.py, 25 runs: copy / original time 0.248
(#2) and 0.252 (#3), projected CI medians 380 / 487 ms amd, 298 / 483 ms
arm. On the builds before/after ClickHouse#115869 (sorted array of cursors) #2 is
1.161x faster and its copy 1.159x; on those before/after ClickHouse#126829
(cheaper collation) 2.179x and 2.111x; #3 and its copy show no change
on either pair (1.005 / 1.008, 1.004 / 1.001), as the heap guard should.

#0 and #1 stay as they are: on this rig the ClickHouse#115869 change did not show
on them beyond the A/A resolution, so there was no measured guarantee
that copies would keep their sensitivity.

About 32 s (amd) and 29 s (arm) of query time less per master
performance job; 9 queries stay enabled, so all of them still run.

Related: ClickHouse#129258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Nov 16, 2026
…shorter than a bucket

The selector of a table with buckets of samples wrapped every read in
`WHERE notEmpty(samples)` over `timeSeriesSliceSortedArray(samples, a, b)`.
Filter push-down moves that condition into PREWHERE, which reads the raw
`samples`, computes the slice and drops the raw column, so the raw column
is PREWHERE-only. Since ClickHouse#122919 `MergeTreeBlockSizePredictor` counts such a
column at its part estimate on top of the measured slice copy: for a long
window (the slice is the whole array) bytes per row double, and with
granules under 512 KiB a block holds about one granule instead of two or
three. Whole-metric selectors then process about twice as many blocks
(`promql_selector_id_range_row_cost` #0/#1 1.3x slower with 262144-byte
granules, ClickHouse#131678).

The filter is a no-op unless the range is shorter than a bucket: every
sample of a row lies in [bucket, bucket + step), `min_time`/`max_time` are
the smallest/largest of them, and the inner query keeps a row only if
`max_time >= a AND min_time <= b`. If `min_time >= a` the sample at
`min_time` is in the range, if `max_time <= b` the sample at `max_time` is,
so an empty slice needs `min_time < a AND b < max_time`, i.e.
`b - a < max_time - min_time < step`. With a bound absent the same holds for
the other bound. So the filter is now emitted only when both bounds are set
and `b - a < step` in the units of the table being read (the samples table
or the recent samples table, each with its own step). The difference is
computed in Int128: the bounds of a DateTime64 table can be anywhere in
[INT64_MIN, INT64_MAX]. For long windows nothing on `samples` goes to
PREWHERE, the raw column is read by the main step and measured once, and
the slice is computed after it.

The bucket step at the table scale is moved into `getBucketStep`, shared
with `makeBucketedSamplesTimeRangeConditions`.

Measured (release build, master vs this change concurrently on identical
parts, 2 x 25 interleaved runs, max_threads = 4): row_cost #0 0.81/0.76 at
262144, 0.86/0.81 at 131072, 0.93/0.84 at 524288; #1 0.79/0.73,
0.88/0.83, 0.99/0.91; promql_selector_old_short_window 0.94-0.97. Results
identical.

Edge: a row written directly with `min_time`/`max_time` looser than its
samples (against the documented contract) can now be returned as an empty
array by `timeSeriesSelector(..., 'samples')` for a long range. PromQL drops
series whose merged array is empty, as it does for rows emptied by the
stale-marker filter.

Tests: 05770_time_series_selector_empty_slice_filter checks both sides of the
bucket boundary and the plan shape (no-parallel-replicas: without a local
plan the initiator's EXPLAIN does not show the replicas' filters). New perf
test promql_selector_small_granules: the row_cost shape at 131072-byte
granules, the default of the recent samples table.

Related: ClickHouse#131678
Related: ClickHouse#122919

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant