Skip to content

Restrict host function linking to "env" module imports only - #4

Closed
bacek wants to merge 1 commit into
spr/master/fff0b868from
spr/master/9883fc0f
Closed

bacek wants to merge 1 commit into
spr/master/fff0b868from
spr/master/9883fc0f

Conversation

@bacek

@bacek bacek commented Mar 13, 2026 •

Copy link
Copy Markdown
Owner

`linkHostFunctions` now skips any import whose module name is not
`"env"`, so WASI and other non-host imports are no longer fed to
`getHostFunction`.

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

commit-id:9883fc0f
@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 May 14, 2026
Under x86-64-v3 the `ColumnString` prologue in
`FunctionRandomString::executeImpl` is emitted with YMM stores
(`vmovups ymmword`, `vpbroadcastq`) for the `Chars`/`Offsets` init.
The compiler then has to emit a `vzeroupper` before every virtual call to
`length_column.getUInt(row_num)` inside the per-row loop in case the callee
expects clean AVX/SSE state.  The extra ~6-cycle transition × 100M rows
regresses `random_string` perf test #4 (`randomString(rand() % 10)`) ~15%.

Compiling this file at v2 keeps the SSE-only wrapper codegen used by master,
which avoids any AVX state and therefore no `vzeroupper`.  The hot AVX2 byte
generator `RandImpl::execute` lives in `FunctionsRandom.cpp` and remains
compiled at v3.

Combine the new entry with the existing `FunctionsStringDistance.cpp` rule
under a shared comment block.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bacek pushed a commit that referenced this pull request May 14, 2026
`getReturnTypeImpl` already constrains the second argument of
`kostikConsistentHash` / `jumpConsistentHash` to an integer type, so the
constant bucket count can be read directly via `IColumn::getInt` /
`getUInt` instead of materialising an intermediate `Field`.

Apart from being a small simplification this fixes a `-march=x86-64-v3`
regression: `Field` is a 32-byte object, and `clang` lowered the
`Field buckets_field = (*arguments[1].column)[0]` copy to YMM
`vmovups`-pairs.  The dirtied AVX upper state then forced `vzeroupper`
before every per-row call to the (separately compiled, scalar-only)
`ConsistentHashing` helper, regressing
`consistent_hashes #0/#2/#4` ~10–13% on AMD release.

After the refactor the per-row hot path no longer touches YMM at all;
the remaining `vzeroupper` instructions left in the function body are in
cold exception-construction paths and execute as no-ops because the
upper YMM state is already clean.

On Sapphire Rapids LTO (100M rows):
  - master:                 0.211–0.215 s
  - PR (no fix):            0.227–0.242 s  (+11 %)
  - PR + this refactor:     0.211–0.214 s  (matches master)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bacek pushed a commit that referenced this pull request May 26, 2026
The point-lookup queries (#4-#7) in apply_patch_parts_join produced
18-30% test noise because the four UPDATE statements that build the
patch parts ran with default parallelism. Parallel threads racing into
the patch builder produce different patch-part split boundaries on
every run, which changes how many patch granules a point lookup at
id=5000000 ends up reading. Per-server timing then depends on the
random split, not on the code being measured.

Force INSERT and UPDATE to use a single thread plus a block size large
enough to fit each whole patch, so the patch-part layout is the same
on every run. Locally verified deterministic over 20 cycles. Setup
time goes from ~4.2s to ~6.3s. Scan queries (#0-#3) still detect
patch-apply-path regressions as before.

Refs ClickHouse#100759.
bacek added a commit that referenced this pull request Jun 1, 2026
The style checker's regex-based check #4 can't understand #if
preprocessor directives. Move the extern declarations and the include
outside the guard so the checker can match declaration to usage.

Co-Authored-By: Claude Sonnet 4.6 <[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.
alexey-milovidov pushed a commit that referenced this pull request Aug 3, 2026
Exclude implicitly created skip indices from system.tables.skipping_indices_types
bacek pushed a commit that referenced this pull request Aug 29, 2026
…is not an entry

**Same-cycle detection now has a durable source.** `cycle_entries` was built
from what the changelog still shows - the section, this run's raw entries, the
recorded deletions, the revert graph - and an entry pruned as insignificant on
an earlier run leaves none of those. A revert of it arriving weeks later
therefore looked like a revert of an earlier release: deleting it was rejected,
or keeping a visible bullet for a change with no net effect was accepted.

`release_range_prs` answers the question from git instead: the pull requests
merged into master since the cycle's `vX.Y.1.1-new` tag, from both subject
shapes the repository uses. Git remembers the range whatever the changelog did
with it. `--first-parent`, so the walk stays on master's own commits - a
contributor branch can carry merges of pull requests of the contributor's
*fork*, and there are five such numbers in the 26.8 range (`Merge pull request
#4 from someone/...`), which mean nothing here. 2277 pull requests for that
range, in 0.3s.

**And the limitation from the previous round is closed rather than documented.**
A re-applier that also reverted something of an earlier release has a change of
its own; the link it contributes to the entry it brought back is an annotation
on someone else's bullet and cannot stand in for that. It is checkable without
forbidding a legitimate merge, by asking for *some other* bullet rather than
for a bullet of its own: a section 7 merge into a third entry still passes,
while collapsing the entry into the annotation does not.

Two tests added. The pruned-entry one runs the same input with and without the
range, so it shows both the old verdict and the new one; the annotation one
also asserts that the legitimate merge is still accepted.
bacek pushed a commit that referenced this pull request Aug 29, 2026
…ategory

**`release_range_prs` read every `(#N)` in a subject.** A squashed revert
quotes the original title, `Revert "Something (ClickHouse#90000)" (ClickHouse#115800)`, and the
quoted number would put a pull request of an earlier release into this range -
the very distinction the caller uses the range for, so a revert of it would
look like something this release cancels out rather than a user-visible
reversal. Both shapes are now anchored: the squash number ends the subject, the
`Merge pull request #N` one starts it.

That shape does not occur in the last 60000 commits of this repository, where
reverts land as merge commits, so this is hardening rather than a live bug. The
anchored form is the right parse either way, and the regression pins it along
with a fork's own `Merge pull request #4` appearing mid-line.

**A sibling moved between categories made the merge impossible.** The category
check demanded the recorded header while the shared-bullet rule demanded a
merge into the surviving bullet, so once an edit had moved that bullet the two
contradicted each other and no edit could pass. The expected category is now
the surviving bullet's current one when there is a sibling to merge into, and
the recorded one otherwise: the check follows the bullet rather than a
remembered header.

The two rules then compose instead of fighting - moving the whole merged bullet
elsewhere stays legal, while leaving the survivor and restoring the entry beside
it under the old header is rejected, which the test asserts.
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
…efore measuring

Since 2f07f3f (ClickHouse#122231) `t_materialize_uniq_v2_{i64,f64}` no longer stop
merges, so background merges run while the fill commits its 20 1M-row parts
and keep running during queries #0-#3. Each compared server ends up with its
own layout (CI server logs: 8 servers, 8 layouts, from [6,6,6,1,1] to [20]
million rows). The measured `ALTER ... CLEAR STATISTICS ALL, MATERIALIZE
STATISTICS ALL` runs one single-threaded mutation task per part, so its time
follows the largest part, and the layout lasts the whole job, so the dashboard
confirmation restart reproduces the gap (`confirmed_regression` on unrelated
PRs, e.g. ClickHouse#126296: #4 0.1445 -> 0.1933 s).

Merge both tables into one part in the fill with `OPTIMIZE TABLE ... FINAL
SETTINGS optimize_throw_if_noop = 1` and assert one active part per table with
`throwIf`, as `and_compare_chain_derived.xml` does. Without
`optimize_throw_if_noop` a failed merge assignment only logs and returns
success, leaving a random layout. A table that background merges already
collapsed to one part is still rewritten under FINAL, so the pin never throws
on it. `projection_materialize.xml` measures a mutation over one merged part
the same way and is stable on the same harness.

Validated on the official master release build (26.11.1.120): before, 10
fills gave 5 i64 layouts and a 1.92x spread of #4, and perf.py on two servers
gave right/left 1.249, 0.892, 0.841 in 3 of 5 fills; after, one 20M-row part
per table in 10 of 10 fills, #4/#5 spread 1.029/1.041, and perf.py right/left
within 5% in 5 of 5. Replacing one OPTIMIZE with `SELECT 1` fails the fill.

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

When `hasAny(Array(String), <constant Array(String)>)` does not build the
needle hash set for a block (fewer than 4 needles, a needle longer than 256
bytes, or a block too small for the set to pay off), it used to fall back to
the generic GatherUtils path. That path makes two virtual calls per row from
the per-row loop of `arrayAllAny` (`ColumnString::structureEquals` from
`sliceHas`, and `ColumnString::compareAt` per element/needle pair).

The speed of that loop turned out to depend on code placement. Three PR builds
of 2026-10-18 (ClickHouse#123788, ClickHouse#100394, ClickHouse#63383; their diffs share no file and none
touches Functions/ or Columns/) ran `has_any_constant_string_needles` queries
#5 and #6 1.2-2.1x slower than the master reference in all three process
lifetimes of their perf job, on three different runners, with md5-identical
machine code for the four functions involved. Across 24 inspected CI builds, a
build is slow exactly when a 64-byte line of `compareAt` or `structureEquals`
coincides with a line of the `arrayAllAny` loop modulo 8 KiB (3/3 slow, 0/21
fast). Reproduced locally with the CI binaries: query #6 takes 1.04-1.35 s on
the three slow builds vs 0.62 s on three fast ones, at equal instruction counts.

Now the declined block compares each element with each needle directly
(`getDataAt` + `memequalSmallAllowOverflow15`, the comparison
`ColumnString::compareAt` makes), in the generic path's order (needles outer,
elements inner, first match wins). The loop has no call left, and it is faster
for every declined shape: on a release build, perf test queries #4-#7 take
0.73-0.91x of the base time and #0-#3 (set path) are unchanged.

Adds perf query #7 for the fewer-than-4-needles branch, the only declined
branch the test did not cover. Non-String columns still use the generic path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Oct 23, 2026
`h3_functions` #4 (`h3CellAreaM2`) was 20% slower on aarch64: in the glibc build LLVM merges `sin(x)`
and `cos(x)` into one `sincos` call, which shares the argument reduction, but it assumes `sincos` only
in glibc, Fuchsia and Android, so the musl build made both calls. An explicit `sincos` call does not
help on its own: Clang turns it into the `llvm.sincos` intrinsic, and for a musl target LLVM lowers that
to `sin` and `cos` again.

- Compile with `-fno-builtin-sincos` under musl, so that `sincos` stays a call.
- Link llvm-libc's correctly rounded `sincos`, which gives the same bits as its `sin` and `cos`.
- Bump `contrib/h3` to call `sincos` in `cagnoli` (the cell area functions).
- Add `sinCos` and use it in `geoToUTM`, `UTMToGeo` and `colorOKLCHToSRGB`.

The results of these functions over 200000 inputs are identical before and after.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 1ffa828)
bacek pushed a commit that referenced this pull request Nov 16, 2026
filterWithBlanks copied the left key into the right key column of a LEFT JOIN
one row at a time, with a virtual insertFrom or insertDefault per row. It now
reads the filter 64 rows at a time (bytes64MaskToBits64Mask, as in
filterArraysImpl): a chunk whose rows are all kept is one insertRangeFrom, a
chunk whose rows are all blank is one insertManyDefaults, and any other chunk
keeps the per-row loop. ColumnNullable gets an insertManyDefaults override, so
a blank Nullable chunk fills the nested column and the null map in bulk instead
of 64 virtual insertDefault calls.

Measured on x86 release (8 pinned cores; wall = median of 21 runs, user-space
instructions = median of 3 perf stat runs minus startup), base -> this commit:
- join_nullable_keys_small_table #4: 0.61x wall, 0.47x instructions;
  #8: 0.71x / 0.55x; #3: 0.66x / 0.55x; #7: 0.80x / 0.66x.
- Alternating rows and runs of 2, 3 and 100 rows: 0.86x-0.99x instructions.
- Queries of the same test that do not reach filterWithBlanks: within 0.4%
  instructions (wall moves up to +23% between the two builds from code
  placement alone, with the same instruction count).

The added perf query covers the per-row path (alternating matched and
unmatched rows), which the existing queries of the test do not reach.
The test runs all its queries (`run_all_queries`), as it now has more than
the 10 that CI samples.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bacek pushed a commit that referenced this pull request Nov 16, 2026
The loop moves into a new IColumn::insertFromOrDefaults, which IColumnHelper
implements on the concrete column type, so insertFrom, insertDefault,
insertRangeFrom and insertManyDefaults are no longer virtual calls. Consecutive
64-row chunks that are entirely kept or entirely blank are inserted with one call.

User-space instructions relative to master (x86 release, join_nullable_keys_small_table
and probes with runs of matched rows): #4 0.43x (0.46x with plain 64-row chunks),
UInt64 runs of 1 to 3 rows 0.80x to 0.82x (0.94x to 0.95x), Nullable(UInt64) runs of
1 to 3 rows 0.90x (0.96x); queries that do not reach the function are unchanged.

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

clang 23 turns `direction * CompareHelper<T>::compare(...) > 0` into a `ucmp`/`scmp` intrinsic that the x86
backend expands to a scalar `cmp`/`seta`/`sbb`/`imul` per row, where clang 22 emitted an 8-wide AVX2 compare.
`optimize_trivial_group_by_limit` #4 and #5 were 1.13-1.18x slower on x86 in the last four performance runs of
ClickHouse#117346 because of it.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117346&sha=3dd3995a5ef4e0b7c19340ffe509331cf3e91827&name_0=PR

Co-Authored-By: Claude Fable 5.2 <[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