Skip to content

Add sqr arithmetic function - #109061

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
lalitium:add-sqr-function
Jul 11, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
lalitium:add-sqr-function

Conversation

@lalitium

@lalitium lalitium commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #108759

Adds the sqr arithmetic function as a convenience wrapper for calculating x * x. The function delegates to existing multiply semantics, so it preserves the same result type behavior for integers, floats, Decimals, constants, and Nullable values.

Changelog category (leave one):

  • New Feature

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

Add the sqr arithmetic function for calculating the square of a number.

Version info

  • Merged into: 26.7.1.809 (included in 26.7 and later)

@lalitium

lalitium commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov Please approve the check workflow. Thank you.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 1, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [217312e]

Summary: ✅


AI Review

Summary

This PR adds the sqr SQL function by wrapping multiply with a duplicated argument. The earlier LowCardinality exception is fixed, but the current implementation still does not honor the feature request's sqr(x) = x * x contract on LowCardinality inputs: sqr now preserves LowCardinality(...), while x * x / multiply(x, x) flatten to the plain numeric type.

Findings

⚠️ Majors

  • [src/Functions/multiply.cpp:121, src/Functions/IFunction.cpp:701-736, tests/queries/0_stateless/04493_sqr.sql:18-25] [dismissed by author -- https://github.com/Add sqr arithmetic function #109061#discussion_r3509370547] I still consider this real because issue #108759 explicitly promises sqr(x) = x * x with the same return type as multiplication. FunctionSqr lets the unary LowCardinality default path run before it duplicates the argument, so sqr(CAST(... AS LowCardinality(UInt64))) returns LowCardinality(UInt64), while multiply(x, x) on the same input goes through the binary path in IFunctionOverloadResolver::getReturnType and flattens to plain UInt64. The new regression test now locks in that public type mismatch instead of the promised multiply semantics. Suggested fix: either lower sqr to the normal binary multiply(x, x) path before the framework adaptors run, or otherwise make sqr report and execute the same LowCardinality result shape that multiply(x, x) would produce.
Final Verdict

Changes requested. The LowCardinality exception is fixed, but sqr still diverges from the promised x * x / multiply(x, x) return-type behavior on LowCardinality inputs.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 1, 2026
Comment thread src/Functions/multiply.cpp Resolved
Comment thread tests/queries/0_stateless/04493_sqr.sql Resolved
Comment thread src/Functions/multiply.cpp Resolved
lalitium and others added 2 commits July 1, 2026 17:55
The previous revision disabled the default `LowCardinality`, sparse and
replicated column implementations for `FunctionSqr` and forwarded a
duplicated argument pair `{arg, arg}` to the inner `multiply`. For a
constant `LowCardinality` argument the overload resolver reports the result
type as `LowCardinality` (a constant argument is not counted as a full
low-cardinality column in `IFunctionOverloadResolver::getReturnType`), so
`multiply` was then executed on two `LowCardinality` columns with a
`LowCardinality` result type. The default implementation supports only a
single `LowCardinality` argument, which raised `Logical error: Default
functions implementation for LowCardinality is supported only with a single
LowCardinality argument.`

This was found by the AST fuzzer and `FunctionsStress`, e.g.
`SELECT sqr(CAST(1964064 AS LowCardinality(UInt64)))`.
CI: ClickHouse#109061

`sqr` is a unary function, so let it use the default `LowCardinality`,
sparse and replicated implementations like every other unary function. Only
a single argument is ever low-cardinality, so the throwing path is never
reached, and `sqr(x)` now preserves `LowCardinality` by running the wrapped
`multiply` on the dictionary. This differs from `multiply(lc, lc)`, which
flattens two low-cardinality columns to a plain result, but that is the
expected behavior for a unary function; the test now checks the actual
behavior and adds a regression case for the constant `LowCardinality` input.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed 7193f2c6c4a to fix a logical error that the AST fuzzer and FunctionsStress unit test found (failing on all three sanitizers), e.g.:

SELECT sqr(CAST(1964064 AS LowCardinality(UInt64)));
-- Logical error: Default functions implementation for LowCardinality is supported only with a single LowCardinality argument.

Root cause: the previous revision disabled the default LowCardinality/sparse/replicated implementations on FunctionSqr and forwarded a duplicated pair {arg, arg} to the inner multiply. For a constant LowCardinality argument, IFunctionOverloadResolver::getReturnType reports the result type as LowCardinality (a constant argument is not counted as a full low-cardinality column), so multiply was executed on two LowCardinality columns with a LowCardinality result type — a path that only supports a single low-cardinality argument, hence the exception.

Fix: sqr is unary, so it now uses the default LowCardinality/sparse/replicated implementations like every other unary function. Only one argument is ever low-cardinality, so the throwing path is never reached, and sqr(x) preserves LowCardinality by running the wrapped multiply on the dictionary. This means sqr(lc) returns LowCardinality(...) (natural unary behavior) rather than matching multiply(lc, lc)s plain result — so the earlier toTypeName equality assertion was replaced with a regression test for the actual behavior, including the constant LowCardinality case.

Verified locally: the fuzzer query and the full 04493_sqr test now pass; the JIT compileImpl path (sum(sqr(number)) with compile_expressions=1) is unaffected.

@alexey-milovidov note this is past your earlier LGTM (which was on the first commit) — worth a re-check of the last two commits.

Comment thread tests/queries/0_stateless/04493_sqr.sql Resolved
… the `sqr` test

The AST fuzzer found the original logical error via
`SELECT sqr(CAST(1964064 AS LowCardinality(UInt64)))`, which goes through
`CastOverloadResolver` rather than the `toLowCardinality` function. Lock down
that exact constant-`LowCardinality` surface as requested in review. The query
needs `allow_suspicious_low_cardinality_types` (as the fuzzer runs it).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

@lalitx17 Pushed 72627fc9065 addressing the two remaining review threads (both now resolved):

  • Added the exact AST fuzzer reproducer SELECT sqr(CAST(1964064 AS LowCardinality(UInt64))) (the AI review's Major), which exercises the CastOverloadResolver constant-LowCardinality surface. It needs allow_suspicious_low_cardinality_types = 1 (the fuzzer runs with it), and now returns 1 / LowCardinality(UInt64).
  • Confirmed @rschu1ze's negative/unexpected-input coverage is present (strings → ILLEGAL_TYPE_OF_ARGUMENT, negative integers/floats/decimals, +inf/-inf/nan, NULL).

The function_prop_fuzzer unit tests (asan_ubsan/tsan/msan) that caught the original logical error are now green on the fixed head, and there are no CI failures. This is still a Draft — feel free to mark it ready for review once CI on the new commit is green.

@alexey-milovidov

Copy link
Copy Markdown
Member

The sole red — Stress test (arm_ubsan) → Logical error: Block structure mismatch in A stream: different number of columns (STID 0993-386d) — is an unrelated AST-fuzzer flake, not caused by this change.

The jobs that caught the earlier LowCardinality logical error are all green on 72627fc9 (Unit tests (asan_ubsan/tsan/msan, function_prop_fuzzer), AST fuzzer (targeted), Fast test, all Builds), so the sqr LowCardinality fix is CI-confirmed. This PR is still marked as Draft.

@lalitium
lalitium marked this pull request as ready for review July 2, 2026 12:45
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.70% 92.60% -0.10%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 26/41 (63.41%) · Uncovered code

Full report · Diff report

pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Jul 9, 2026
…cess

The client-side AST fuzzer loop swallowed every exception thrown during a
fuzzing step: the `catch (...)` handler recorded the error, the loop bottom
reset it, and fuzzing continued. When the failure mode is persistent - most
importantly a dead server, where the reconnection attempt inside
`processParsedSingleQuery` throws instantly - the client sprints through the
remaining corpus at hundreds of steps per second without contacting the
server and exits with code 0, which the job reports as "Fuzzer exited with
success".

Evidence from `AST fuzzer (amd_debug, targeted)` on PR ClickHouse#109061
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109061&sha=1419f6b7e95c81c812f945c06333998b92d56ad3&name_0=PR&name_1=AST+fuzzer+%28amd_debug%2C+targeted%29):
`fuzzer.log` records 68972 fuzzing steps, of which 52837 produced no outcome
(silent exception), while `server.log` shows the server received only 209
queries within a 47-second window before dying. On PR ClickHouse#106250
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106250&sha=latest&name_0=PR&name_1=AST+fuzzer+%28amd_debug%2C+targeted%29)
a 5-file corpus with ~20 SELECT statements (about 20000 fuzzing steps, over
an hour of work at the measured debug-build rate of 2-6 steps/s) "completed"
in 74 seconds and the job passed. Overall, 13-33% of targeted AST fuzzer
runs per month finish in under 8 minutes of their 30-minute budget.

Client fixes (`programs/client/FuzzLoop.cpp`):
- Print thrown exceptions in the fuzzing-step catch handlers instead of
  swallowing them silently, so `fuzzer.log` shows what actually happened.
- After a thrown exception, check the connection via `tryToReconnect` (the
  same check `processASTFuzzerStep` does for errors received without
  throwing) and stop fuzzing when the server is gone instead of uselessly
  sprinting through the rest of the corpus.
- Register query parameters generated by `QueryFuzzer` (from
  `getLastQueryParameters`) for client-side substitution, mirroring the
  server-side fuzzer in `executeASTFuzzerQueries`; previously any fuzzed
  query containing a substituted `{name:type}` parameter failed with
  "Substitution ... is not set" before reaching the server.

Job fix (`ci/jobs/scripts/fuzzer/run-fuzzer.sh`):
- When the AST fuzzer walks the whole corpus and exits 0 with a meaningful
  part of the FUZZ_TIME_LIMIT budget remaining, restart it (each pass uses a
  fresh random seed) instead of ending the job after a couple of minutes.
  This matters for the targeted variant, whose corpus is a handful of test
  files. The restart is gated on a server liveness probe so a dead server
  still terminates the job for classification.
@alexey-milovidov

Copy link
Copy Markdown
Member

but sqr still diverges from the promised x * x / multiply(x, x) return-type behavior on LowCardinality inputs

This is okay. As it is a unary function, it has a chance to keep LowCardinality in more cases.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 11, 2026
Merged via the queue into ClickHouse:master with commit 7e886e2 Jul 11, 2026
175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…cess

The client-side AST fuzzer loop swallowed every exception thrown during a
fuzzing step: the `catch (...)` handler recorded the error, the loop bottom
reset it, and fuzzing continued. When the failure mode is persistent - most
importantly a dead server, where the reconnection attempt inside
`processParsedSingleQuery` throws instantly - the client sprints through the
remaining corpus at hundreds of steps per second without contacting the
server and exits with code 0, which the job reports as "Fuzzer exited with
success".

Evidence from `AST fuzzer (amd_debug, targeted)` on PR ClickHouse#109061
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109061&sha=1419f6b7e95c81c812f945c06333998b92d56ad3&name_0=PR&name_1=AST+fuzzer+%28amd_debug%2C+targeted%29):
`fuzzer.log` records 68972 fuzzing steps, of which 52837 produced no outcome
(silent exception), while `server.log` shows the server received only 209
queries within a 47-second window before dying. On PR ClickHouse#106250
(https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106250&sha=latest&name_0=PR&name_1=AST+fuzzer+%28amd_debug%2C+targeted%29)
a 5-file corpus with ~20 SELECT statements (about 20000 fuzzing steps, over
an hour of work at the measured debug-build rate of 2-6 steps/s) "completed"
in 74 seconds and the job passed. Overall, 13-33% of targeted AST fuzzer
runs per month finish in under 8 minutes of their 30-minute budget.

Client fixes (`programs/client/FuzzLoop.cpp`):
- Print thrown exceptions in the fuzzing-step catch handlers instead of
  swallowing them silently, so `fuzzer.log` shows what actually happened.
- After a thrown exception, check the connection via `tryToReconnect` (the
  same check `processASTFuzzerStep` does for errors received without
  throwing) and stop fuzzing when the server is gone instead of uselessly
  sprinting through the rest of the corpus.
- Register query parameters generated by `QueryFuzzer` (from
  `getLastQueryParameters`) for client-side substitution, mirroring the
  server-side fuzzer in `executeASTFuzzerQueries`; previously any fuzzed
  query containing a substituted `{name:type}` parameter failed with
  "Substitution ... is not set" before reaching the server.

Job fix (`ci/jobs/scripts/fuzzer/run-fuzzer.sh`):
- When the AST fuzzer walks the whole corpus and exits 0 with a meaningful
  part of the FUZZ_TIME_LIMIT budget remaining, restart it (each pass uses a
  fresh random seed) instead of ending the job after a couple of minutes.
  This matters for the targeted variant, whose corpus is a handful of test
  files. The restart is gated on a server liveness probe so a dead server
  still terminates the job for classification.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The previous revision disabled the default `LowCardinality`, sparse and
replicated column implementations for `FunctionSqr` and forwarded a
duplicated argument pair `{arg, arg}` to the inner `multiply`. For a
constant `LowCardinality` argument the overload resolver reports the result
type as `LowCardinality` (a constant argument is not counted as a full
low-cardinality column in `IFunctionOverloadResolver::getReturnType`), so
`multiply` was then executed on two `LowCardinality` columns with a
`LowCardinality` result type. The default implementation supports only a
single `LowCardinality` argument, which raised `Logical error: Default
functions implementation for LowCardinality is supported only with a single
LowCardinality argument.`

This was found by the AST fuzzer and `FunctionsStress`, e.g.
`SELECT sqr(CAST(1964064 AS LowCardinality(UInt64)))`.
CI: ClickHouse#109061

`sqr` is a unary function, so let it use the default `LowCardinality`,
sparse and replicated implementations like every other unary function. Only
a single argument is ever low-cardinality, so the throwing path is never
reached, and `sqr(x)` now preserves `LowCardinality` by running the wrapped
`multiply` on the dictionary. This differs from `multiply(lc, lc)`, which
flattens two low-cardinality columns to a plain result, but that is the
expected behavior for a unary function; the test now checks the actual
behavior and adds a regression case for the constant `LowCardinality` input.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-feature Pull request with new product feature 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.

Function sqr

4 participants