Skip to content

Functions stress test - #93543

Merged
alexey-milovidov merged 68 commits into
masterfrom
ft
Mar 21, 2026
Merged

alexey-milovidov merged 68 commits into
masterfrom
ft

Conversation

@al13n321

@al13n321 al13n321 commented Jan 7, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

Changelog entry:

Implement a stress test for functions, checking the soundness of their various properties.

A test that runs random SQL functions on random arguments and checks many things like:

  • If a function is deterministic, and we ran it twice on the same input, it should output the same value
  • ... even if we made some of the arguments const
  • ... even if we ran it first on multiple rows, then on one of those rows.
  • Iff function succeeded when run on multiple rows at once, it should succeed when run on each row indivudually.
  • Constness of return type doesn't change if you change number of rows in the input (without changing their constness).
  • Function's total MemoryTracker alloc/free amount adds up to zero (i.e. nothing leaked).
  • Function throws typechecking-related exceptions only during overload resolution, not during execution. (This seems hopeless, way too many functions fail this, and the IFunction et al interfaces make it really difficult to implement functions properly.)
  • Monotonicity and injectivity.

Currently many of these checks fail on many functions for many different reasons. I'm working on triaging suppressing these errors before the test can run in CI.

Here are some classes of problems found:

  • Interfaces in IFunction.h are terrible, imo. Implementing a function correctly is difficult and requires lots of boilerplate (both the IFunction way and the IFunctionOverloadResolver+IFunctionBase+IExecutableFunction way). Many implementations take shortcuts:
    • Often types are checked only during execution. Because you have to check IColumn types there anyway to get data out of them, so it's a convenient place for that. Maybe there should be an option for the function implementation to provide one function that does both checking and execution? During query analysis it would just be called on columns with 0 rows.
    • Sometimes functions want to carry some information from the typechecking stage (e.g. getReturnTypeImpl) to the execution stage (executeImpl). This is super inconvenient to do, so some IFunctions have mutable fields for that (e.g. Clean up thread safety in FunctionConvert #90644 ), which may break things in subtle ways if the same IFunctionOverloadResolver instance (which is just an IFunction pointer on the inside) is used to create multiple IExecutableFunction instances (which are also just an IFunction pointer on the inside, the exact same one, shared). Maybe IFunction should have a virtual clone() method, and FunctionToOverloadResolverAdaptor::build should use it, so that each IFunction instance gets only one getReturnTypeImpl call for only one overload, and getReturnTypeImpl can be non-const and just assign fields?
    • There's no good mechanism for handling NULL inputs for functions that throw exception on some inputs. E.g. intDiv(NULL, 0) shouldn't throw. Every function that's in this situation has a different awkward ad-hoc solution for this, and most of those solutions have some cases where they fail. E.g. select modulo(if(number=0,null,0), CAST(number AS IPv4)) from numbers(2) fails, but succeeds if you run it separately on each row (from numbers(1) and from numbers(1, 1)). There should be a better default implementation for nulls; maybe IExecutableFunction::defaultImplementationForNulls could just check if the function is fallible, and always filter input rows in that case?
    • (Note that there 1300 functions, so any plan that involves nontrivially updating them all would require lots of resources for dubious payoff.)
  • There's no clear contract on whether ColumnNullable is allowed to have non-default values in the nested column in NULL rows. Some functions output such columns, some other functions break on such inputs.
  • Some functions just have separate code paths for e.g. const and non-const columns, which behave slightly differently. Examples: select -1::Int32 as x, 2::Int32 as y, x%y, materialize(x)%y, select '' as x, 0::Enum8('a' = 0) as y, x < y, materialize(x) < y.
  • (And of course there are actual bugs, e.g. crashes. There were a few, some fixes are in this PR.)

Version info

  • Merged into: 26.4.1.80
  • Backported to: 26.3.11.13, 26.2.19.17, 26.1.13.2, 25.8.24.9

@clickhouse-gh

clickhouse-gh Bot commented Jan 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bcbfb8a]

Summary: ✅


AI Review

Summary

This PR adds a large gtest-based functions stress framework and a broad set of fixes/suppressions uncovered by it, plus related runtime/test adjustments. High-level verdict: useful direction, but there is one remaining concurrency robustness issue in signal handling that should be fixed before merge.

Missing context

  • ⚠️ CI logs/results were not provided in this review context, so runtime validation coverage could not be cross-checked against CI failures.

Findings

  • ⚠️ Majors
    • [src/Common/SignalHandlers.cpp:359] terminate_request_callback is invoked while terminate_request_mutex is held. This is fragile and can deadlock if any callback implementation takes locks, blocks, or waits. The current BaseDaemon callback is simple, but the callback interface is generic and reused behavior can regress later.
    • Suggested fix: capture the callback target and crashing state under the mutex, then invoke the callback after releasing the lock.

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅

Performance & Safety

  • ⚠️ Callback-under-lock in signal termination path can create lock-ordering/deadlock hazards if callback behavior evolves.

Final Verdict

  • Status: ⚠️ Request changes
  • Minimum required action: move terminate_request_callback invocation out of the terminate_request_mutex critical section in SignalListener::run.

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Jan 7, 2026
@nikitamikhaylov nikitamikhaylov self-assigned this Jan 14, 2026
al13n321 and others added 8 commits January 14, 2026 20:30
1. Update expected error codes in tests to match new error codes:
   - `transform`: BAD_ARGUMENTS → NOT_IMPLEMENTED
   - `tupleElement`: NOT_FOUND_COLUMN_IN_BLOCK → ARGUMENT_OUT_OF_BOUND (for index errors) and BAD_ARGUMENTS (for name errors)
   - `parseDateTime`: NOT_ENOUGH_SPACE → CANNOT_PARSE_DATETIME

2. Fix implicit conversion warnings in `StorageGenerateRandom.cpp` that cause arm_tidy build failures:
   - Add explicit casts in `fillBufferWithRandomPrintableASCIIBytes`
   - Fix Enum size type from UInt8/UInt16 to size_t
   - Fix fmt::format scale parameter type

3. Fix DateTime64 random generation to maintain backward compatibility for non-fuzzy mode by using UInt64 arithmetic instead of Int64

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- `StorageGenerateRandom.cpp`: Add explicit casts in `fuzzyRandomInteger`
  template and `intExp10` call to avoid precision loss warnings
- `modulo.cpp`: Add explicit cast for negation result to avoid
  `-Wimplicit-int-conversion-on-negation` warning

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Fix clang-tidy errors in `gtest_functions_stress.cpp`:
- Remove redundant `static` in anonymous namespace
- Fix implicit int-to-float conversions with explicit casts
- Remove unused variable, use `std::min`, `empty()`, `const` methods
- Fix misleading indentation, qualified auto, move-const-arg
- Add NOLINT for `__tsan_on_report` reserved identifier

Update test reference files to match changed error codes:
- `ARGUMENT_OUT_OF_BOUND` instead of `NOT_FOUND_COLUMN_IN_BLOCK` for `tupleElement`
- `CANNOT_PARSE_DATETIME` instead of `NOT_ENOUGH_SPACE` for `parseDateTime`
- Regenerate Enum values in `generateRandom` test after `StorageGenerateRandom` changes

Co-Authored-By: Claude Opus 4.6 <[email protected]>
… wrapper

The `TupleOrArrayFunction` wrapper delegates `executeImpl` directly to the
inner array/tuple function, bypassing the inner function's constant argument
handling. Because the wrapper had `useDefaultImplementationForConstants() = true`
but returned empty `getArgumentsThatAreAlwaysConstant()`, the framework would
unwrap ALL constant arguments before calling `executeImpl`. This caused the
inner `arrayLpNorm` to receive its `p` parameter as a non-const column,
triggering an `ILLEGAL_COLUMN` exception.

Fix by forwarding `getArgumentsThatAreAlwaysConstant` from the inner
`array_function`, so the framework preserves constness of the right arguments.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Feb 5, 2026
alexey-milovidov and others added 4 commits February 6, 2026 05:12
Avoid nesting `chassert` inside `SCOPE_EXIT` macro, which causes
"expected expression" compilation error in sanitizer builds due to
macro expansion issues. Use `make_scope_guard` directly instead.

Update `01905_to_json_string` reference to match new enum values
produced by the refactored random data generation in `StorageGenerateRandom`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ange

After merging master, `WriteBufferValidUTF8` no longer emits U+FFFD
replacement characters for invalid UTF-8 sequences in JSON output -
it strips them instead. Update the reference file to match.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
alexey-milovidov and others added 2 commits March 21, 2026 00:09
Add `ORDER BY length(a)` to the multi-row query to make row order
deterministic. Update reference to match the sorted output.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Skip the stress test under MSan: it finds uninitialized-memory reads
in functions that are hard to debug without a local MSan build. The
test still runs under ASan/UBSan and TSan where it provides value.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Common/SignalHandlers.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Mar 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.70% 83.80% +0.10%
Functions 24.00% 24.60% +0.60%
Branches 76.30% 76.40% +0.10%

PR changed lines: PR changed-lines coverage: 86.63% (2236/2581, 12 noise lines excluded)
Diff coverage report
Uncovered code

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Mar 21, 2026
Merged via the queue into master with commit 29445fc Mar 21, 2026
148 checks passed
@alexey-milovidov
alexey-milovidov deleted the ft branch March 21, 2026 09:44
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 21, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Enable functions stress test as a regular unit test
bcbfb8a
Skip the stress test under MSan: it finds uninitialized-memory reads
in functions that are hard to debug without a local MSan build. The
test still runs under ASan/UBSan and TSan where it provides value.

This is a grave mistake. MSan is the most important of all. Will continue in subsequent PRs.

alexey-milovidov added a commit that referenced this pull request Mar 21, 2026
Address review TODOs and follow-up items from PR #93543:

- Remove template parameters from `FunctionKqlArraySort`: replace
  `<Name, is_desc>` template with runtime constructor parameters.
- Add `H3Validator` to H3 functions that were missing input validation
  (`h3GetBaseCell`, `h3GetResolution`, and all directed edge functions),
  preventing out-of-bounds reads in the H3 contrib library.
  Add `validateEdge` method to `H3Validator` for directed edge indices.
- Add bounds checking to WKB parsing (`readWKB` and variants) to prevent
  huge memory allocations on malformed input.
- Add parameter validation to random distribution functions to prevent
  hangs with extreme parameters (e.g. `randBinomial` with huge trials,
  `randChiSquared` with extreme degrees of freedom).
- Re-enable the functions stress test under MSan (was skipped).
- Add function selection bias (power-of-two-choices) so less-tested
  functions get more coverage.
- Add settings randomization to the stress test, toggling various
  boolean and enum settings that affect function behavior.
- Remove all fixed functions from the stress test excluded list.

#93543

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@Avogar

Avogar commented May 11, 2026

Copy link
Copy Markdown
Member

@al13n321 @alexey-milovidov this PR contains some fixes in functions that might be useful to backport, but this PR contains both fuzzer implementation and bug fixes that makes it very hard to backport the fixes. For example, one of the fixes fixed incorrect result of function IPv6StringToNumOrDefault that was hit by the user. And I believe there is no other way for me to backporte it except creating manual backports.

Avogar added a commit to Avogar/ClickHouse that referenced this pull request May 11, 2026
Fix `IPv6StringToNumOrDefault` not properly zeroing output bytes on parse
failure. Only one byte was zeroed (`vec_res[i] = 0`) instead of all 16
bytes (`std::fill_n(&vec_res[out_offset], offset_inc, 0)`), causing
stale data from previous successful parses to leak into default results.

Backport of ClickHouse#93543
Avogar added a commit that referenced this pull request May 12, 2026
Fix `IPv6StringToNumOrDefault` not properly zeroing output bytes on parse
failure. Only one byte was zeroed (`vec_res[i] = 0`) instead of all 16
bytes (`std::fill_n(&vec_res[out_offset], offset_inc, 0)`), causing
stale data from previous successful parses to leak into default results.

Backport of #93543

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Avogar added a commit that referenced this pull request May 12, 2026
Fix `IPv6StringToNumOrDefault` not properly zeroing output bytes on parse
failure. Only one byte was zeroed (`vec_res[i] = 0`) instead of all 16
bytes (`std::fill_n(&vec_res[out_offset], offset_inc, 0)`), causing
stale data from previous successful parses to leak into default results.

Backport of #93543

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Avogar added a commit that referenced this pull request May 12, 2026
Fix `IPv6StringToNumOrDefault` not properly zeroing output bytes on parse
failure. Only one byte was zeroed (`vec_res[i] = 0`) instead of all 16
bytes (`std::fill_n(&vec_res[out_offset], offset_inc, 0)`), causing
stale data from previous successful parses to leak into default results.

Backport of #93543

Co-Authored-By: Claude Opus 4.6 <[email protected]>
fm4v added a commit that referenced this pull request Jun 10, 2026
`04051_functions_various_bugs` and `03784_functions_various_bugs` (both
added by #93543) asserted
that `trimRight` with a trim character set longer than 16 bytes throws
`TOO_LARGE_STRING_SIZE`. That limit is removed, so the queries now
succeed; convert them to positive assertions and update the references.
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jun 11, 2026
`trimLeft`, `trimRight`, `trimBoth` (and aliases `ltrim`, `rtrim`,
`trim`) rejected a custom trim character set longer than 16 bytes with:

    Code: 131. DB::Exception: Function trimLeft supports at most 16 trim
    characters, but 17 were provided. (TOO_LARGE_STRING_SIZE)

The second argument was fed into `SearchSymbols`, a SIMD search primitive
that is intentionally capped at 16 symbols (`__m128i`) for hot parsers
(CSV/TSV/JSON/URL). A user-provided trim set can be arbitrarily long, so
this was the wrong tool. A real-world query such as

    TRIM(LEADING 'SRID=4326;POINT (' FROM col)

(17 bytes) worked in 25.2 but started failing in 26.4.

Fix: for the custom-characters case, use a 256-entry byte membership
table instead of `SearchSymbols`. It supports a set of any length, looks
up each byte in O(1), and is built once per block. The default
whitespace path keeps its compile-time SIMD search, and the shared
`SearchSymbols` infrastructure is untouched.

Caused by: ClickHouse#93543
fm4v added a commit that referenced this pull request Jun 12, 2026
`trimLeft`, `trimRight`, `trimBoth` (and aliases `ltrim`, `rtrim`,
`trim`) rejected a custom trim character set longer than 16 bytes with:

    Code: 131. DB::Exception: Function trimLeft supports at most 16 trim
    characters, but 17 were provided. (TOO_LARGE_STRING_SIZE)

The second argument was fed into `SearchSymbols`, a SIMD search primitive
that is intentionally capped at 16 symbols (`__m128i`) for hot parsers
(CSV/TSV/JSON/URL). A user-provided trim set can be arbitrarily long, so
this was the wrong tool. A real-world query such as

    TRIM(LEADING 'SRID=4326;POINT (' FROM col)

(17 bytes) worked in 25.2 but started failing in 26.4.

Fix: for the custom-characters case, use a 256-entry byte membership
table instead of `SearchSymbols`. It supports a set of any length, looks
up each byte in O(1), and is built once per block. The default
whitespace path keeps its compile-time SIMD search, and the shared
`SearchSymbols` infrastructure is untouched.

Caused by: #93543
fm4v added a commit that referenced this pull request Jun 12, 2026
`04051_functions_various_bugs` and `03784_functions_various_bugs` (both
added by #93543) asserted
that `trimRight` with a trim character set longer than 16 bytes throws
`TOO_LARGE_STRING_SIZE`. That limit is removed, so the queries now
succeed; convert them to positive assertions and update the references.
fm4v added a commit that referenced this pull request Jun 12, 2026
`trimLeft`, `trimRight`, `trimBoth` (and aliases `ltrim`, `rtrim`,
`trim`) rejected a custom trim character set longer than 16 bytes with:

    Code: 131. DB::Exception: Function trimLeft supports at most 16 trim
    characters, but 17 were provided. (TOO_LARGE_STRING_SIZE)

The second argument was fed into `SearchSymbols`, a SIMD search primitive
that is intentionally capped at 16 symbols (`__m128i`) for hot parsers
(CSV/TSV/JSON/URL). A user-provided trim set can be arbitrarily long, so
this was the wrong tool. A real-world query such as

    TRIM(LEADING 'SRID=4326;POINT (' FROM col)

(17 bytes) worked in 25.2 but started failing in 26.4.

Fix: for the custom-characters case, use a 256-entry byte membership
table instead of `SearchSymbols`. It supports a set of any length, looks
up each byte in O(1), and is built once per block. The default
whitespace path keeps its compile-time SIMD search, and the shared
`SearchSymbols` infrastructure is untouched.

Caused by: #93543
fm4v added a commit that referenced this pull request Jun 12, 2026
`04051_functions_various_bugs` and `03784_functions_various_bugs` (both
added by #93543) asserted
that `trimRight` with a trim character set longer than 16 bytes throws
`TOO_LARGE_STRING_SIZE`. That limit is removed, so the queries now
succeed; convert them to positive assertions and update the references.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-build Pull request with build/testing/packaging improvement pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants