Skip to content

[pull] master from ClickHouse:master - #1

Merged
pull[bot] merged 3815 commits into
erickirt:masterfrom
ClickHouse:master
Dec 9, 2024
Merged

pull[bot] merged 3815 commits into
erickirt:masterfrom
ClickHouse:master

Conversation

@pull

@pull pull Bot commented Dec 9, 2024 •

Copy link
Copy Markdown

See Commits and Changes for more details.


Created by pull[bot] (v2.0.0-alpha.1)

Can you help keep this open source service alive? 💖 Please sponsor : )

yariks5s and others added 30 commits December 2, 2024 17:39
Better prewarm of mark and primary index caches
Force_connected for retry resume connection establisher
…bles adds a new column,it will cause an identifier error
pull Bot pushed a commit that referenced this pull request Jan 30, 2026
…uster

Fix SYSTEM DROP QUERY CACHE TAG not working with ON CLUSTER
pull Bot pushed a commit that referenced this pull request Feb 10, 2026
Two issues were causing CancellationChecker::workerFunction() to spin
instead of waiting:

1. Overflow in wait_for: When a query was registered with an extremely
   large timeout (e.g., ~9.2e12 ms, close to INT64_MAX), the
   std::condition_variable::wait_for() would overflow when converting
   milliseconds to nanoseconds internally (multiplying by 1,000,000).
   This caused wait_for to return immediately instead of waiting.

2. Stale now_ms in predicate: The predicate lambda captured now_ms by
   value, but this timestamp was computed before the wait. On spurious
   wakeups, the predicate would compare the task's endtime against the
   stale timestamp, incorrectly returning false even when the task had
   actually expired. Combined with issue #1, this caused infinite spinning.

Fix:
- Cap timeout to 1 year maximum to prevent chrono overflow
- Use fresh timestamp inside the predicate to correctly detect expiration
pull Bot pushed a commit that referenced this pull request Feb 18, 2026
Add CHouse UI to Community Tools
pull Bot pushed a commit that referenced this pull request Mar 31, 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]>
pull Bot pushed a commit that referenced this pull request Mar 31, 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]>
pull Bot pushed a commit that referenced this pull request Apr 26, 2026
…079-3df0)

`LimitSeekableReadBuffer::seek` used the expression
`pos + position_change` inside its in-buffer fast-path check. When the
inner buffer has not materialized its memory yet — as is the case for
`EmptyReadBuffer`, `ParallelReadBuffer`, and `ReadWriteBufferFromHTTP`,
all of which start with `pos == nullptr` — and a non-zero seek is
requested before the first `next()`, this triggers undefined behavior
per [expr.add]: "applying non-zero offset N to null pointer". On master
BuzzHouse (arm_asan_ubsan) this surfaced from the BACKUP write path as
STID 3079-3df0:

```
src/IO/LimitSeekableReadBuffer.cpp:97:34: runtime error: applying non-zero offset 1178 to null pointer
  #0 DB::LimitSeekableReadBuffer::seek(long, int)
  #1 DB::BackupWriterDefault::copyDataToFile(...)
  #2 DB::BackupImpl::writeFile(...)
  #3 DB::BackupsWorker::writeBackupEntries(...)
```

Replace the pointer-arithmetic comparison with an equivalent check
expressed via pointer *differences* and integer arithmetic, which is
well-defined regardless of whether `pos` is null. The condition is
mathematically identical to the original for all legal inputs.

Add `gtest_limit_seekable_read_buffer.cpp` covering the null-`pos`
regression plus two sanity tests for the in-buffer and out-of-buffer
seek paths. Without the fix the first test reproduces the exact UBSan
error from CI; with the fix all three pass cleanly under
`-fsanitize=address,undefined`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=4b8132993ce0625e9c0ed0bf15ed16eb6df8262b&name_0=MasterCI&name_1=BuzzHouse+%28arm_asan_ubsan%29
pull Bot 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]>
pull Bot pushed a commit that referenced this pull request May 13, 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]>
pull Bot pushed a commit that referenced this pull request May 13, 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]>
pull Bot pushed a commit that referenced this pull request Jun 6, 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.
pull Bot 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]>
pull Bot pushed a commit that referenced this pull request Jul 31, 2026
Binary operators between instant vectors without any tags, e.g.
'vector(1) + vector(2)', as well as 'topk(1, vector(1))',
'label_replace(vector(1), ...)' and binary operators with 'on()'
failed with an error like 'Argument #1 of function
timeSeriesGroupToTags has wrong type UInt8, it must be UInt64'.

The group #0 constant (meaning a group with no tags) was generated
as a plain literal 0 in several places, and ClickHouse infers type
UInt8 for such a literal while all timeSeries* functions working
with groups require UInt64. Generate CAST(0, 'UInt64') instead,
the same way transformGroupASTForAggregationOperator already does,
and teach the group #0 short-circuit in
transformGroupASTForBinaryOperator to recognize the CAST form.
pull Bot pushed a commit that referenced this pull request Aug 1, 2026
The comment on the outer-join control claimed that no `__join_result_dummy`
marker is minted for those shapes. That is not what the code does: both mint
sites are join-kind-unconditional (`JoinStepLogical.cpp:142-148` gates only on
`outputs.empty()`, `:437-445` only on `required_nodes.empty()`); the sole
join-kind-dependent code nearby is the nullability conversion, which does not
gate minting.

Measured with `EXPLAIN input_headers = 1, keep_logical_steps = 1` on the fix
binary, the enclosing join's per-side input headers are:

  primary (aborts without the fix)  #0 __join_result_dummy  #1 __join_result_dummy
  outer joins                       #0 __join_result_dummy, __table3.a  #1 __table4.a
  explicit CROSS JOIN               #0 __join_result_dummy, __table3.a  #1 __table4.a
  derived tables                    #0 __table1.c                      #1 __table4.c

So the outer-join and explicit-cross shapes DO mint the marker, into the left
child header only. What makes them negative controls is the property the defect
actually needs: the two child headers of the enclosing join share no column
name, so each name's queue holds exactly one input node and the mapping
resolves to the same node whether it is rebuilt per child or hoisted. Only the
primary shape has both children reduced to the identical marker name.

The derived-table comment named `x.c` / `y.c` as the resulting column names;
the measurement shows the table-expression-qualified `__table1.c` /
`__table4.c`. Reworded to the measured names.

Comment-only: the non-comment content of the test is unchanged (sha256
8d02af43049db436 before and after), `clickhouse format --multiquery --oneline`
is identical across both revisions, and the `.reference` file has zero diff
lines.
pull Bot pushed a commit that referenced this pull request Aug 3, 2026
Fix column index in temporary-table path of system.tables
pull Bot 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].
pull Bot pushed a commit that referenced this pull request Aug 17, 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.
pull Bot pushed a commit that referenced this pull request Aug 17, 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.
pull Bot 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
pull Bot pushed a commit that referenced this pull request Sep 9, 2026
…ex comment

Three of Copilot's four comments on
ClickHouse#112309.

`deserialize` took the row count straight from the serialized state and resized
`samples` to it. States are user-transportable via `hierarchicalKMeansState`, so
that count is untrusted input about to become an allocation. Bounded against
`sample_cap`, which is the most the reservoir could ever have held. The
comparison divides rather than multiplies, since `sample_cap * dim` overflows
for large caps. `ReservoirSampler::read` guards the same way with a fixed 1 GiB
cap, which would be wrong here - a legitimate 5M-vector reservoir at dim 768 is
15 GB, so the bound has to come from the configured cap instead.

Verified with a crafted blob claiming 1M vectors of dimension 3 against a
`sample_cap` of 5: rejected with `INCORRECT_DATA` before allocating, while the
same blob under a large enough cap gets past the bound and fails later on the
truncated payload. Note a plain SQL `CAST` between differently-parameterised
states cannot reach this path at all - the type system rejects the conversion
first - so the test goes through `unhex` to exercise it.

`memcpy` was used with no `#include <cstring>`, relying on a transitive include.

The `useDefaultImplementationForConstants` comment in `assignCentroid` said
"arg #1" while the constant it means is argument index 1, the second one.

Copilot's fourth comment, on the dictionary path allocating a vector per
centroid before sorting, is not addressed: see the PR discussion. It is real but
runs once per dictionary version, not per block or per row.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pull Bot pushed a commit that referenced this pull request Sep 19, 2026
…t covers a slow reject

test_native_default_session_user_with_password fails only on the
amd_llvm_coverage integration shards, with "TimeoutError: timed out" at
native_hello's sock.recv(1): 3 failures over 7,621 coverage rows in 30 days,
across three unrelated PRs (one of them documentation-only), and 0 master
failures in 90 days.

A rejected native login is answered only after two symbolized stack traces are
rendered. The first comes from the catch in AccessControl::authenticate
(src/Access/AccessControl.cpp:629); the second from writeException
(src/IO/WriteHelpers.cpp:77-85), reached through TCPHandler::runImpl's
sendException (src/Server/TCPHandler.cpp:507, :531) with the server context's
calculate_text_stack_trace, and the packet reaches the wire only after it. Since
StackTrace::toStringCached keys on the exact frame-pointer triple, the two
distinct exceptions each pay a full DWARF symbolization. In the failing job's
log (PR ClickHouse#115680 / 4ee5eff, coverage 2/8) those renders took 8.59s and
10.35s, so the client's first byte arrived 18.9s after connect; a second case in
the same run took 16.6s. The helper allowed 10s.

Nothing here is a server defect: coverage binaries are never shipped, the same
renders cost 0.04s once the DWARF is parsed, and the logging is deliberate
(AccessControl.cpp:661-663). The server's handshake_timeout_milliseconds is
checked only before a read (src/IO/ReadBufferFromPocoSocket.cpp:106), which is
why the answer does arrive at 18.9s instead of the connection being dropped.

60s is not an arbitrary pick: 60000ms is the value this repository already uses
for a handshake read deadline on a slow lane, in six places. One is
00563_shard_insert_into_remote.sql (SET handshake_timeout_ms = 60000, by Alexey
Milovidov, d4fed63); four are my own merged CI fixes (01600, 02040, 03630,
03443), each commented that the default 10s handshake_timeout_ms is not enough on
slow lanes; stress_tests.lib:362 uses 30s. Two samples fix the order of magnitude
of a first-time symbolization on a loaded runner, not its tail, so a deadline
just above the observed maximum would re-flake. The cost is bounded: this is a
deadline rather than a sleep, so a passing call pays nothing, native_hello has no
retry loop, and pytest.ini's timeout = 900 still catches a genuine hang.

The client's own handshake_timeout_ms default is also 10s, but that setting is an
SLA for a real connection deciding when to fail over. This read only observes
whether a login was rejected and asserts nothing about latency, so a
client-realistic deadline adds no assertion value and only decides how often the
observation is lost.

Alternatives rejected: suppressing either render removes deliberate diagnostics
on a security-relevant path; calculate_text_stack_trace=0 in the test profile
would leave render #1 at 8.59s, i.e. 86% of a 10s budget, and weaken diagnostics
for the module's other tests; skipping the case under coverage deletes reject-path
coverage on the flavour whose purpose is measuring it.

Two other hand-rolled native Hello sites are deliberately left alone.
test_interserver_marker_requires_cluster_secret rethrows in interserver mode at
TCPHandler.cpp:521-526 before sendException, so the packet-gating render is
structurally absent and its oracle is a closed connection; it has never failed
with this signature. In test_tcp_hello_string_limits a client timeout is part of
the oracle (a rejection arm returns False on socket.timeout), and that module
shortens the server's handshake timeout to 3000ms on purpose.

Validation: with the coverage binary from the failing job the module passes 30/30
and the three native_hello callers pass 10 times each. The failure is reproduced
deterministically against a stub listener answering after 15s: before this change
the helper raises TimeoutError at sock.recv(1) in 10.01s, the exact CI frame;
after it, the helper returns the Exception packet at 15.00s. A never-answering
stub fails at 10s before and 60.00s after, so the constant is the operative
variable, and an arm answering ServerHello instead still reddens the assertion in
0.05s. The 18.9s magnitude is measured in CI and is not reproducible on an idle
box, where the same binary answers a reject in 0.105s.

Co-Authored-By: Claude Opus 5 <[email protected]>
pull Bot pushed a commit that referenced this pull request Sep 24, 2026
The fixture fills its tables with min_insert_block_size_rows = 1, which
disables squashing, so every block numbers(1000000) emits becomes its own
part: 16 parts, 15 x 65409 + 18865 rows. Nothing stops merges, so the
background scheduler collapses those 16 tiny single-partition parts while
the harness is timing.

The data is inserted in ascending order and the table is ORDER BY (), so
each part covers a contiguous value range, and filterPartsByStatistics
keeps only the parts whose range holds one of the three sought values:
3 of the 16 parts the fill writes, but both of 2 merged parts. Since
total_marks_pk is summed over the survivors only, the granules the skip
index has to evaluate are a step function of how far merging got before
timing started, 39246 marks at 16 parts and up to 200003 at 2. The two
sides of a comparison run set up concurrently on two servers, reach
different points of that collapse, and the harness reports the difference
as a slowdown of the binary under test.

Over 10 days on Performance Comparison (arm_release, master_head, N/6),
query #0 measures at two separated modes with an empty 16..24 ms bucket in
2493 samples per side, and the two sides' distributions match to within 2
samples. A mode flip reads as up to +291%, the job's own report calls the
query slower, and the dashboard rates it confirmed_regression, which reds
the shard on PRs whose diff cannot reach the query, and on master.

SelectedMarks, SelectedRanges and SelectedRows are identical in both modes
on both architectures, so no engine path misbehaves: the read is 3 granules
either way and only the amount of index analysis moves. The fix therefore
belongs in the fixture, which manufactures the non-determinism in its own
fill. Stopping merges per table mirrors set_index_analysis.xml, the sibling
fixture for this same feature; the per-table form, as in
adaptive_codec_merge.xml, cannot reach another test's tables, and teardown
restores merges and drops both tables, where the old file left
test_minmax_index behind.

Validated with an exact count oracle instead of timings, which makes it
arch- and build-independent: with the pin, query #0 reports
SelectedPartsTotal = 16 and SelectedMarksTotal = 39246, and query #1
reports 200003, on all 315 probes including after repeated sleeps.
Unpinned, the same probe sees 11 parts / 91574 marks and then 6 / 156984
within half a second, and 6 / 156984 in the settled state. Removing only
the two SYSTEM STOP MERGES lines brings the drift back. A co-tenant table
filled while the pin is active still merges 16 parts down to 6, and after
the drop_query block a fresh table of the same name merges again.

Determinizing necessarily picks one mode, so the series steps once: amd
from ~31 ms to ~14 ms, while the arm median stays at 8 ms.

Related: ClickHouse#100759

Co-Authored-By: Claude Opus 5 <[email protected]>
pull Bot pushed a commit that referenced this pull request Sep 24, 2026
Holding merges keeps the parts the fill writes, but it does not determine
how they are cut. min_insert_block_size_rows = 1 disables squashing, so one
part is written per source block, and the source block size for
numbers(1000000) is max_block_size, which this fixture never set. The
existing max_insert_block_size = 65536 does not supply it:
use_strict_insert_block_limits defaults to false, and in that state the
max_insert_block_size settings are not enforced for an INSERT. So the
16-part layout every figure here depends on was a property of the compiled
DEFAULT_BLOCK_SIZE rather than of the fixture, and the arithmetic closes
only on that value: 15 x 65409 + 18865 = 16 parts, 3 x 13082 = 39246
selected marks, 15 x 13082 + 3773 = 200003 total. Setting max_block_size to
65409 in both fills makes the cut a property of the settings and keeps
those measured values unchanged, which is what
join_convert_full_to_left_or_right.xml already does for the same reason.

The pin could also fail silently. SYSTEM STOP MERGES <table> does not error
when the table is not found: the statement resolves the StorageID without
an existence check, and the action lock is added only if the catalog
returns a table. A rename or a typo would therefore turn the pin back into
a no-op, and because the fixture asserted nothing about its own layout the
only symptom would have been confirmed_regression reds reappearing weeks
later on unrelated pull requests, which is the failure this fixture change
exists to end. One throwIf over system.parts per table, in the shape
group_by_low_cardinality_array_join.xml uses, turns that into an immediate
job failure: a setup query that raises is fatal, since perf.py re-raises it
out of the worker thread.

Validated with the same exact count oracle: query #0 reports
SelectedPartsTotal = 16 and SelectedMarksTotal = 39246, and query #1
reports 200003, on all 574 tight probes and every settled iteration.
The assertion was proven live in both directions it has to catch. With only
the two SYSTEM STOP MERGES lines removed, test_set_index is down to 11
active parts by the time the fills finish and the assertion fires on every
run; with merges still held but max_block_size set to 70000, both tables
land at 15 parts and it fires again. SelectedMarks, SelectedRanges and
SelectedRows are unchanged throughout, so the fixture still analyses the
same 3 granules it always read.

Corrects the previous commit message's disclosure of the one-time step in
the amd series: measured at the pinned layout it is ~20 ms, the median over
174 job-sides in 30 days, not ~14 ms, which rested on 4 samples. The arm
median is unchanged at ~8 ms.

Related: ClickHouse#100759

Co-Authored-By: Claude Opus 5 <[email protected]>
pull Bot pushed a commit that referenced this pull request Sep 24, 2026
Review asked to keep the block sizes always a power of two, so the fill's
`max_block_size` moves from 65409 to 65536. It now matches the
`max_insert_block_size` beside it and
tests/performance/join_convert_full_to_left_or_right.xml, which pins the same
pair at 65536.

65409 was the current default of the setting (`DEFAULT_BLOCK_SIZE` in
src/Core/Defines.h, 65536 minus the SIMD padding), so the pinned value is now a
deliberate round number instead of a restatement of that default. The comment
dropped the sentence naming 65409 as the default, which the swap makes false,
and states the invariant the pin buys instead.

Nothing the test asserts or measures changes. Both tables still write 16 active
parts, so the `throwIf` oracles stand; the cut moves from 15 x 65409 rows +
18865 to 15 x 65536 + 16960. Measured with `EXPLAIN indexes = 1` on all three
queries, 65409 -> 65536:

  #0  parts 3/16 unchanged, index range 39246 -> 39321 granules, read 3 -> 3
  #1  parts 1/16 unchanged, read 1 -> 1
  #2  parts 12/16 unchanged, 156984 -> 157284 granules, read 133114 -> 133110

The +0.19% is the range the skip index walks, not the data read. With both
sides at one layout the worst arm spread measured on #0 is +9.6% over 5537
jobs, against the check's 15% floor, so the shift is far below either.
pull Bot pushed a commit that referenced this pull request Sep 27, 2026
These queries were flagged as slower/faster/unstable on master runs, or scored as confirmed regressions by the performance dashboard on unrelated PRs, because the two compared servers did not measure the same work:

- `and_compare_chain_derived`: both tables are created with `numbers_mt`, which writes a varying number of parts, and the measured runs stop merges, so the servers read different layouts (the join query took 34 ms over 17 parts and 82 ms over one part on the same binary). Merge each table to one part and check it. Query 2 now keeps 2M rows per side (`8000000 < l.v`) and runs at about 150 ms instead of 20 ms.
- `set_index`: the IN set was built from `rand`, so every run looked up a different set, selected different ranges and read a different number of rows before `read_overflow_mode = 'break'`. Use a fixed pseudo-random sample (`toUInt32(cityHash64(number))`) and merge the 500M-row table to one part.
- `formats_columns_nullable`: `SELECT * ... LIMIT 1000` read 6-10 ms, and parallel parsing parsed a varying amount ahead before the LIMIT cancelled it (`LIMIT 30000` of CSV took 197 ms with it and 38 ms without). Disable parallel parsing for that query and read 100000 rows, about 200 ms for text formats.
- `serialization_pool_lookup`: the fixed `max_threads = 16` oversubscribed the 8 pinned cores of the amd runners; query 0 was flagged in 9.3% of amd master runs against 0.4% on arm. Use the harness default of one thread per pinned CPU.

Master flag rates over 14 days (slower/faster/unstable share of master runs): `and_compare_chain_derived #2` 5-8%, `set_index #0` 14% (arm), `formats_columns_nullable #1` 19% (arm), `serialization_pool_lookup #0` 9% (amd).
pull Bot pushed a commit that referenced this pull request Sep 27, 2026
test_complex_table_schema and test_varchar_char_types_via_unity_catalog fail with
"subprocess.TimeoutExpired: ... bin/spark-sql ... timed out after 600 seconds".
CIDB over 30 days: 5 rows across 5 distinct PRs for this signature, 0 on master.

The Unity Catalog server accepts GET /schemas/{name} and never answers it, and the
UC Java client issues that request through java.net.http.HttpClient with no
per-request timeout, so the Spark driver parks for the whole subprocess budget.
The jstack that the test's own hang diagnostics capture 600s into the stall puts
it in the batch's first statement:

  "main" #1 cpu=11625.96ms elapsed=600.24s WAITING (parking)
    jdk.internal.net.http.HttpClientImpl.send
    io.unitycatalog.client.api.SchemasApi.getSchemaWithHttpInfo(SchemasApi.java:273)
    io.unitycatalog.spark.UCProxy.loadNamespaceMetadata(UCSingleCatalog.scala:399)
    SupportsNamespaces.namespaceExists(SupportsNamespaces.java:98)
    CreateNamespaceExec.run(CreateNamespaceExec.scala:43)

CreateNamespaceExec.run probes namespaceExists before creating anything. In the
same diagnostics both socket ends are ESTAB with Recv-Q = Send-Q = 0 for 600s
(the request was fully delivered and UC produced no response byte) while a
concurrent UC liveness probe answered in 10.7ms, so the server was serving other
requests and a fresh client converges.

Two alternatives are excluded by measurement. Ivy package resolution is not
involved: the failing run reports "0 artifacts copied, 33 already retrieved
(0kB/16ms)", because the image pre-resolves the same --packages list at build
time. Derby metastore init is not involved either: the JVM got well past
ObjectStore init.

UC is a third-party server pinned in the test image and its client constructs its
own HttpClient, so neither the handler nor a request timeout is reachable from the
spark-sql command line. The only lever the test owns is to survive the stall,
which is what ClickHouse#107133 established and ClickHouse#109641 extended to the read path.

Hence the same two-part remedy at the two measured write sites: rewrite the batch
into the idempotent form already used at the precedent site (CREATE SCHEMA IF NOT
EXISTS, CREATE TABLE IF NOT EXISTS, INSERT OVERWRITE), then pass
retry_on_timeout=True so one fresh-JVM replay is allowed. 2 x 300s fits the 900s
per-test cap from tests/integration/pytest.ini with roughly 300s of headroom; no
timeout constant changes. Both tables are named with a fresh uuid4() and hold
exactly one row, so a replay converges to identical content.

test_snapshot_version is deliberately left alone. It asserts the Delta commit
history (get_table_versions() == ["0","1","2"] and _commit_version), so INSERT
OVERWRITE would add a commit and break the assertions; making it replay-safe
needs a real restructure. That is the same boundary ClickHouse#109641 drew when it retried
only that test's read-only DESCRIBE HISTORY.

Validation. Since the UC stall cannot be forced, a temporary local injection
reported a timeout after the batch had really executed and committed, which is
the worst case for a replay: 4/4 test executions passed and each logged the
retry. Reverting exactly one edit at a time then reddens the run for the
predicted reason (SCHEMA_ALREADY_EXISTS, TABLE_OR_VIEW_ALREADY_EXISTS, and a
duplicate row breaking the column assertions), so no edit is decoration. Without
injection: 4/4 on the pristine tree and 4/4 with the fix in the same wall-clock
band, 21 passed / 3 skipped for the whole module, and 40/40 over --count 10 on
all four parameter ids.

Failing job:
https://github.com/ClickHouse/ClickHouse/actions/runs/35763632624/job/107009114425

Co-Authored-By: Claude Opus 5 <[email protected]>
pull Bot pushed a commit that referenced this pull request Sep 27, 2026
…ce test

Each fill INSERT squashes the numbers_mt stream into parts of 256 MiB
(min_insert_block_size_bytes), so a part holds the next ~3 blocks in the
order the SELECT threads deliver them. perf.py fills both servers at the
same time and merges stay stopped, so the two servers of a comparison
measure different layouts for the whole test. On ClickHouse#104431 the right server
read 16% more compressed bytes for query #1 with the same CPU time, and
the dashboard gate reported +19.8% as a confirmed regression.

Setting min_insert_block_size_rows = 1000000 (above the 500000 rows of an
INSERT) and min_insert_block_size_bytes = 0 on both INSERTs makes each of
them one block, sorted by the key when written, so both servers get the
same two intersecting parts. The SELECT's SETTINGS reach the INSERT's
squashing through InsertQuerySettingsPushDownVisitor. A throwIf fill
query fails the test if the table does not have exactly 2 active parts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
pull Bot pushed a commit that referenced this pull request Sep 27, 2026
Query #0 groups 5M rows by a single-type Dynamic key. For every row the
aggregation looks up the variant's default serialization in
SerializationObjectPool: a shared lock on the key's shard mutex,
weak_ptr::lock, and the release of the returned SerializationPtr. These
are atomic read-modify-writes on two cache lines that every aggregation
thread writes for every row. One key means one shard, so the pool's
sharding cannot spread the load, and the query is bound by how fast those
lines move between cores. That speed is fixed per server process.

CI data (query_metric_runs_v1, arm, 1177 runs since 2026-09-17): the 5-7
samples of one server agree within 0.7% (p50), but the per-process medians
span 0.643-0.840 s (p05-p95). Fast and slow processes do the same work
(same arena bytes, memory, two-level hash tables and page faults) and
differ only in user CPU time (9.5 vs 12.1 s). The wall time does not
depend on the thread count: arm 0.754 s with 16 threads vs 0.775 s with
12, amd 0.669 s with 16 threads on 8 pinned cores vs 0.686 s with 8. So
each A/B run compares two random draws of that per-process speed. Runs
whose new/old median moved by more than 15% (raw samples):

                                 arm PR   arm master   amd PR   amd master
    serialization_pool_lookup #0  123/789     54/558    68/176     220/560
    serialization_pool_lookup #1   41/789     11/558     5/176      20/560
    serialization_pool_lookup #2    0/789      0/558     0/176       0/560
    group_by_dynamic_keys #0        0/782      0/559     0/173       0/559

group_by_dynamic_keys #0 runs the same per-row lookup path with
max_threads = 1. On PR ClickHouse#117533 the performance dashboard scored #0 as a
confirmed regression (arm 5/6, 0.670 -> 0.799 s) that the shard's own
report did not flag.

Run #0 in one thread, from numbers instead of numbers_mt, so it times the
pool's hit path itself, which does not depend on the process. Queries #1
(two keys, where sharding spreads the load) and #2 (the multi-threaded
MergeTree read) keep the contention coverage.

Local check on x86 with the official 26.10.1.820 master build, perf.py,
7 runs: old #0 1.76 s with 12 threads (15.4 s user CPU per run), new #0
0.57 s (0.56 s user CPU), same result. Ten fresh servers pinned to 8
cores with max_threads = 8: old #0 per-process medians 0.68-1.08 s; new
#0 0.56-0.58 s in 8 of them and 0.72-0.73 s in the two whose table
fills were also about 25% slower (9.2-10.0 s vs 7.4-8.6 s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
pull Bot pushed a commit that referenced this pull request Sep 28, 2026
Pointing `contrib/nlohmann-json` at the ClickHouse fork makes the copy of
`nlohmann::json` that `ai-sdk-cpp` vendors in
`third_party/nlohmann_json_patched` an ODR violation rather than a duplicate.
Both are version 3.12.0, so both define the same `nlohmann::json_abi_v3_12_0`
symbols, and the two definitions no longer match: the fork holds a
`number_buffer` member in `lexer` that the vendored copy has no field for, and
drops the `decimal_point_char` the vendored copy keeps, so the fork's `parser`
is the larger of the two. The linker resolves this by keeping one definition of
each symbol, so a `parser` laid out by the vendored header is handed to a
`parse` compiled from the fork header, which reads and destroys members past
the end of it.

In a sanitizer build this aborts on the first response of a model, which is how
it was found - every AI client test of
ClickHouse#114043 failed this way:

    ERROR: AddressSanitizer: stack-buffer-overflow
        #0 nlohmann::json_abi_v3_12_0::detail::parser<...>::parse(...)
             contrib/nlohmann-json/single_include/nlohmann/json.hpp:13073
        #1 nlohmann::json_abi_v3_12_0::basic_json<...>::parse<...>(...)
             contrib/ai-sdk-cpp/third_party/nlohmann_json_patched/include/nlohmann/json.hpp:4053
        #2 ai::providers::BaseProviderClient::generate_text_single_step(...)
      [32, 232) 'ref.tmp' (line 4053) <== Memory access at offset 240 overflows this variable

and the `MemorySanitizer` build reports the same defect from the other side,
the `lexer` destructor of that call destroying a `std::string` that was never
constructed. In a release build the same code reads and writes past the end of
a stack object without anything catching it, on the path of the `??` command of
the client and of the server-side `aiGenerate` function.

Nothing on this branch drives a model, which is why its own CI does not show
this, so the fix goes here rather than only in the pull request that found it:
this branch is the one that introduces the second definition.

Build `ai-sdk-cpp` against `contrib/nlohmann-json` instead, so there is one.
The vendored copy exists to keep the number parsing away from the locale, which
the fork does properly, so there is nothing left to keep it for.
`nlohmann-json` is now added unconditionally rather than only for
`google-cloud-cpp` - the two are enabled independently of each other - and its
include directory is marked as a system one, because it now reaches
ClickHouse's own translation units through `ai-sdk-cpp`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pull Bot pushed a commit that referenced this pull request Sep 28, 2026
Each fill INSERT squashes the numbers_mt stream in the order the SELECT
threads deliver its 65409-row blocks and cuts a part once
min_insert_block_size_rows (1048449) rows have accumulated, i.e. every 17
blocks, so each INSERT writes 8 parts whose key ranges depend on thread
timing. perf.py fills both servers at the same time and merges stay
stopped, so the two servers of a comparison measure different 16-part
tables for the whole test. Queries #0 and #1 stop at their LIMIT and read
a layout-dependent number of rows: on ClickHouse#120186 the new server read 31%
more rows for both, and the dashboard gate reported +17.9% and +19.3% as
confirmed regressions.

Both INSERTs now set min_insert_block_size_rows = 10000000 (above the
8000000 rows of an INSERT) and min_insert_block_size_bytes = 0 (an INSERT
is ~350 MB, so the 256 MiB default would still cut it in two). Each INSERT
becomes one block, sorted by the key when written, so both servers get the
same two intersecting parts, the fixture the test was measured with. A
throwIf fill query fails the test if the table does not have exactly 2
active parts. max_insert_threads cannot do this: it only fans the squashed
blocks out to the insert sinks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
pull Bot pushed a commit that referenced this pull request Sep 29, 2026
…ion over a `Nullable` argument

The `-If` null adapters merged the null map with the condition into a buffer
sized by the absolute end row of the call and filled only `[row_begin, row_end)`.
Aggregation in order calls `addBatchSinglePlace` once per key interval, and
window frames once per frame update, so with 8-row groups every call asked for
up to 64 KiB to use 8 bytes. The merges the nested functions do for themselves
(`SingleValueData`, `groupBit*`, the simple moments, `regr_*`,
`timeSeriesLastTwoSamples`) were sized the same way.

On x86_64 every such request above 32 KiB exceeds jemalloc's thread cache
limit (`opt_tcache_max`) and takes the arena large-extent path, whose cost
depends on the state of the process. On aarch64 (64 KiB pages) these sizes are
small size classes served from the thread cache. That is why queries #2 to #5
of `tests/performance/aggregation_in_order_if_null_map.xml` are unstable on
the amd runners only: in the last 14 days CIDB has 2008 of the test's 2174 amd
`unstable` verdicts on #2 to #5, and 8 on arm in total.

With a single `Nullable` argument no merged map is needed:
`addBatchSinglePlaceNotNull` takes the null map and the condition column
separately, and every implementation handles `if_argument_pos`
(`AggregateFunctionIf` already calls them all that way). So
`AggregateFunctionIfNullUnary` with a non-`Nullable` condition passes the
value's null map and the condition at position 1, and
`AggregateFunctionIfNullVariadic` with exactly one `Nullable` argument passes
that argument's null map to the nested `-If` function, which applies the
condition. The merges those calls reach allocate `row_end - row_begin` bytes
and call their kernels with pointers rebased by `row_begin`, as `sum` and
`avg` already do. The same rows are added in the same order, so the results
do not change. Two or more `Nullable` arguments (query #5, `corr(x, w)`), a
`Nullable` condition of a one-argument `-If` function and the TimeSeries
array merges keep their merged buffer.

Measured on a release build (x86_64, `max_threads` 8), base / this change,
per run of each query of the test:
- jemalloc large allocations above 32 KiB: #0 703 / 703, #1 714 / 714,
  #2 302182 / 703, #3 302142 / 663, #4 229046 / 1718, #5 115413 / 115413;
- CPU profiler samples in the jemalloc large-extent path: #2 33% / 0.9%,
  #3 31% / 0.5%;
- perf.py median of 13 runs, two alternating rounds (ms): #2 38.2, 39.8 /
  24.6, 21.7; #3 39.0, 40.2 / 21.3, 19.8; #4 44.3, 45.4 / 28.3, 25.9;
  #0, #1 and #5 unchanged;
- `minIf(x, cond) OVER (ORDER BY k ROWS BETWEEN 100 PRECEDING AND CURRENT
  ROW)` over 1M rows: 340 / 166 ms, and `sumIf(y, cn)` over a `Nullable`
  condition: 301 / 89 ms;
- aggregation without keys over the same table: 12.2 / 12.3 ms.

Query #0, flagged on ClickHouse#118490,
never had such a buffer and is not changed here.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118490&sha=8ded98e22889e53dd536b141b564e136c76482a9&name_0=PR&name_1=Performance%20Comparison%20(amd_release%2C%20master_head%2C%203%2F6)

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.