Repository navigation
Add KQL conformance tests from open-source implementations - #102159
Conversation
Add 302 conformance test cases for the Kusto Query Language dialect, adapted from three open-source KQL implementations: - 123 tests from baby-kusto-csharp (MIT License, Copyright Microsoft Corporation) - 145 tests from kusto-loco (MIT License, Copyright Neil MacMullen) - 34 tests from pql (Apache 2.0, Copyright RunReveal Inc.) These tests cover: `print`, `project`, `extend`, `summarize`, `sort`, `take`/`limit`, `top`, `count`, `distinct`, `where`/`filter`, `join` (multiple kinds), `mv-expand`, `lookup`, `union`, `let`, `in`/`!in`, string operators (`contains`, `startswith`, `endswith`, `matches regex`), case-insensitive variants (`=~`, `!~`, `contains_cs`, etc.), aggregation functions (`count`, `sum`, `avg`, `min`, `max`, `dcount`, `percentile`, `make_list`, `make_set`, `arg_min`, `arg_max`), scalar functions (`strlen`, `substring`, `strcat`, `replace_string`, `split`, `trim`, `tolower`, `toupper`, `reverse`, `indexof`, `bin`, `bin_at`, `round`, `abs`, `sqrt`, `pow`, `log`, `exp`, `isnull`, `isempty`, `coalesce`, `iff`, `case`, `todatetime`, `toint`, `tolong`, `todouble`, `tostring`, `array_length`, `array_sort_asc`, `array_reverse`, `array_index_of`, `geo_distance_2points`), datetime functions, IP functions, type casting, null handling, and arithmetic/comparison operators. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [7fe6057] Summary: ✅ AI ReviewSummaryThis PR adds broad KQL conformance coverage and corresponding parser/function adjustments. I found three still-live issues: one correctness issue in Findings❌ Blockers
ClickHouse Rules
Final VerdictStatus: Minimum required actions:
|
Implement missing KQL (Kusto Query Language) features to improve conformance with open-source KQL test suites (baby-kusto, kusto-loco, pql). New functions (34): - Math: `abs`, `sqrt`, `pow`, `log`, `log10`, `log2`, `sign`, `exp`, `isfinite`, `isinf` - General: `iff`, `not`, `min_of`, `max_of`, `coalesce`, `case`, `row_number`, `format`, `format_interp` - String: `replace_string`, `url_encode_component`, `padleft`, `padright`, `trimws`, `strcat_array`, `isascii`, `isutf8`, `endsWith` - Geo: `geo_distance_2points`, `geo_point_to_geohash` - Other: `parsehex`, `tohex`, `todatetimefmt`, `datetime_utc_to_local`, `any` (alias for `take_any`) New operators (6): - `count` (standalone pipe operator with `count as` alias support) - `top N by col` (with sort direction) - `join kind=<type>` (inner, fullouter, leftouter, rightouter, etc.) - `union` (combining table results) - `between` / `!between` (range filtering with `..` syntax) Parser fixes: - Handle `@'...'` verbatim string literals in KQL expressions - Fix operator validation when operator is last token in subquery - Support `count` as last operator in pipe chains (including `count | count`) - Preprocess `union`/`join` operators by rewriting to SQL subqueries Boolean output: - All boolean-returning KQL functions now output `true`/`false` instead of `0`/`1` by wrapping results in `toBool()` - Affected: `isnull`, `isnotnull`, `isempty`, `isnotempty`, `not`, `isnan`, `isfinite`, `isinf`, `isascii`, `isutf8` - Comparison operators (`contains`, `startswith`, `endswith`, `has`, `matches regex`, `between`) also wrapped in `toBool()` Bug fixes: - `take_any`/`take_anyif` now correctly map to ClickHouse `any`/`anyIf` - `tolong`/`toint` now handle float inputs by truncating instead of returning NULL Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Format datetime output in KQL ISO format: `YYYY-MM-DDThh:mm:ss.NNNNNNN` (T separator, 7 fractional digits) for `startofday`, `endofday`, `startofweek`, `endofweek`, `startofmonth`, `endofmonth`, `startofyear`, `endofyear`, and `bin` with datetime - Fix `endof*` functions to use 100-nanosecond precision instead of microsecond for correct 7-digit fractional representation - Fix `endofweek` to use `toStartOfWeek` instead of `toStartOfDay` - Fix `tolong`/`toint` to handle float inputs by truncating to integer instead of returning NULL (e.g., `tolong(100.5)` now returns `100`) - Update old KQL test references for the new datetime format Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Fix `bin`/`floor` to handle column references as bin_size parameter, not just constant literals. Previously, `bin(a, b)` where `b` is a column would fail silently. - Fix `geo_distance_2points` to validate input coordinates and return NULL for out-of-range values (lon outside [-180,180], lat outside [-90,90]) or NULL inputs, matching KQL semantics. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Add `let name = value;` support to KQL dialect. Let bindings are stored in thread-local storage and substituted as BareWords in subsequent KQL expressions. - Fix `extract` function: capture group 0 now correctly returns the entire match by converting groups to non-capturing. Capture groups > 0 use `extractAllGroupsHorizontal` for reliable group extraction. - Fix duplicate include in IParserKQLFunction.cpp Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Detect comparison operators (>, <, >=, <=) and logical operators (and, or) in KQL project expressions and wrap them in `toBool()` so they output `true`/`false` instead of `0`/`1`. Update existing KQL test references for the new boolean output format. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… hex
- Fix `geo_point_to_geohash` default precision from 12 to 5 characters
(KQL default)
- Fix `tohex`/`format` to strip leading zeros from hex output
- Fix `format` to support uppercase 'X' format specifier
- Fix `format_interp` to strip leading zeros from hex interpolation
- Fix `substring` to return empty string when startingIndex >= length
instead of wrapping around with modulo
- Fix `tolong` to support hex string input (e.g., `tolong('0xa0')` = 160)
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Fix `substring` to clamp negative startingIndex to 0 instead of
wrapping around from end. In KQL, `substring('abc', -1, 20)` returns
`'abc'` (starts from position 0), not `'c'`.
Update old KQL test references for the new substring behavior.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ystack - Fix `bin`/`floor` to use `floor()` for correct negative number behavior. `bin(-1, 3)` now correctly returns `-3` instead of `0`. - Fix `tolong` to use `round()` instead of truncation for float inputs. `tolong(1198.9)` now returns `1199` instead of `1198`. - Fix `contains`, `startswith`, `endswith` (and their `_cs`/negated variants) to work with constant haystack and column needle. Previously these threw "ILLEGAL_COLUMN" because `ilike` doesn't support constant haystack with non-constant needle. Now uses `positionCaseInsensitive`/`startsWith`/ `endsWith` as fallback. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Fix the position-based fallback for literal haystack with column needle to handle Nullable columns by wrapping in `ifNull(toString(...), '')`. Also fix operator precedence for negated expressions by adding parentheses: `not (positionCaseInsensitive(...) > 0)`. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Fix `order by col asc` to default to NULLS FIRST as per KQL semantics (ClickHouse defaults to NULLS LAST for ascending). - Revert `tolong` from rounding to truncation — KQL `tolong` truncates float values towards zero, not rounds. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
|
||
| std::unordered_map<String, String> & kqlLetBindings() | ||
| { | ||
| static thread_local std::unordered_map<String, String> bindings; |
There was a problem hiding this comment.
kqlLetBindings stores let variables in a static thread_local map, but the cleanup function kqlLetBindingsClear is never called anywhere in the parser flow.
That leaks let state across independent queries executed on the same thread and allows stale bindings from a previous query to affect parsing of later queries. It can also accumulate memory for long-lived threads.
Please clear bindings at statement/query boundaries (including exception paths), e.g. with an RAII guard in ParserKQLStatement::parseImpl, so let scope stays per-query.
There was a problem hiding this comment.
kqlLetBindings is still process-lifetime thread_local state and kqlLetBindingsClear is only wired to dialect switches, not query/session boundaries (Utilities.cpp lines 83-105). This still leaks let bindings across unrelated queries that reuse the same worker thread, so query results can depend on execution history.
There was a problem hiding this comment.
I re-checked current HEAD, and this is still live.
kqlLetBindings remains static thread_local in Utilities.cpp and is only cleared from the SET dialect path in ParserKQLStatement::parseImpl; there is still no per-query or per-session cleanup hook. That means let bindings can leak across unrelated queries executed on the same worker thread.
The added comment documents the limitation, but it does not prevent cross-query state bleed. This still needs a real lifecycle boundary (query/session-context ownership, or guaranteed cleanup at query end on all paths).
- Fix `dynamic({...})` to produce JSON string instead of throwing error.
Property bags like `dynamic({"a":123})` now output `'{"a":123}'`.
- Fix `dynamic([...])` arrays to use `CAST(... AS Array(Dynamic))` for
mixed-type array support (integers and strings in same array).
- Add `prefer_column_name_to_alias=1` setting to test files to fix
column alias shadowing in KQL `project` expressions.
- Add `allow_experimental_dynamic_type=1` for mixed-type array support.
- Fix reference files: `NaN` → `nan` (ClickHouse output), `True`/`False`
→ `true`/`false` (standard KQL boolean format).
- Update old KQL test references for dynamic type changes.
- Fix sort ascending nulls-first default for KQL.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Remove trailing semicolons from reference files (SQL statement
terminators that leaked into expected output).
- Fix `dynamic({...})` property bag support — now produces JSON string.
- Fix `dynamic([...])` to use `CAST(... AS Array(Dynamic))`.
- Add `prefer_column_name_to_alias=1` and `allow_experimental_dynamic_type=1`.
- Fix reference: NaN→nan, True/False→true/false.
- Fix sort ascending nulls-first default.
- Update old KQL test references.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Wrap `todatetime`, `make_datetime`, and `datetime()` output in KQL ISO format: `YYYY-MM-DDThh:mm:ss.NNNNNNN`. - Fix array format in kusto_loco reference: tab-separated → comma-separated (test framework artifact from Python-based kusto-loco). - Fix trailing semicolons in reference files. - Update old KQL test references for datetime format changes. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ClickHouse geoDistance gives ~1198.9m for Space Needle to Pike Place Market. tolong truncates to 1198, not 1199. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ereference After consuming `step` (or a unary `-` after `step`), the parser fell through to `String(pos->begin, pos->end)` without checking `isValidKQLPos(pos)`. Inputs like `range x from 1 to 3 step` or `range x from 1 to 3 step -` would dereference an end-of-stream token instead of producing a clean syntax exception. Add the missing guards so malformed step clauses fail with a syntax error. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`ParserKQLQuery` stored the position of the `count` keyword in `operation_pos` so that bare `T | count` (no arguments) keeps a valid token even at end of stream. `ParserKQLCount::parseImpl` then read `pos->begin..pos->end` and compared it to `as`, which is always false for the `count` token, so the optional alias was silently dropped and the result column was always `Count`. Teach `ParserKQLCount` to skip a leading `count` keyword before reading the optional `as <alias>`, restoring correct alias handling without regressing the bare-`count` case. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`ToInt::convertImpl` and `ToLong::convertImpl` inlined the input expression six times inside `multiIf`. For non-deterministic arguments such as `toint(rand())` each branch could observe a different value, producing inconsistent row-level results. Bind the input once via the SQL `(<expr>) AS <alias>` pattern (the same mechanism used by `IParserKQLFunction::formatTimespanSQL`), and use unique alias names per call site via `generateUniqueIdentifier`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`DayOfWeek::convertImpl` computed `toDayOfWeek({0}) % 7` twice — once in the
`if` condition and once when building the value. For non-deterministic
arguments this could produce inconsistent results within a single call, and
for expensive arguments it did avoidable extra work.
Bind the modulus once via the SQL `(<expr>) AS <alias>` pattern with a
unique alias name per call site.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This workflow change (switching the vector_search_stress runner from arm-large-storage to arm-large) is unrelated to the KQL conformance tests in this PR and should not be part of it. Restore the file to match master.
…g scope ParserKQLStatement.cpp: drop the silent `catch (const DB::Exception &)` fallback that was substituting raw tokens for the translated `let` value. That fallback hid real syntax/semantic errors (e.g. unknown KQL function in a `let` value would silently store the raw text and surface a confusing error downstream); other `getExprFromToken` call sites all let the exception propagate, so this aligns with project convention and the "no fallback" rule in CLAUDE.md. Utilities.cpp: expand the `kqlLetBindings` doc comment to record the cross-query thread_local leakage limitation and explain why the suggested per-statement RAII clearing is unsafe (it would break multi-statement `let` scripts like `let x = 5; print x;`). PR: #102159 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
KQL keywords are case-insensitive, but the dispatch in `ParserKQLQuery::parseImpl` at the top-level table_name comparison and in the `range` fast-path's pipe-operator loop still compared the raw token text. As a result, `PRINT 1`, `RANGE x from 1 to 3 step 1`, and `range x from 1 to 3 step 1 | COUNT` would bypass the dedicated paths or fail operator dispatch even though the same lowercase forms work. Normalize both with `Poco::toLower` before comparing — consistent with how the rest of this file already handles KQL keywords. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
@groeneai, provide a fix for Unit tests (msan, function_prop_fuzzer) |
|
@alexey-milovidov — investigated, this is a chronic trunk MSan bug in Failure signature (from Triggered via This PR doesn't touch CIDB chronic-trunk evidence (last 60 days,
Existing fix: #103864 — CC @yakov-olkhovskiy / @vdimir. |
…or tests The Fast test job on PR #102159 (commit 2251f6d) showed several KQL checks fail on `clickhouse-server` because of `Dynamic`/`Nullable`/array interactions while passing on `clickhouse-local`. Commit 9ccb23f had disabled them with `FIXME` markers, which weakened existing stateless coverage in-tree. Per review feedback, restore the original assertions as runnable expected-error tests instead, so they still execute and we catch any future regression in the `kql_array_sort_*` / `arraySum` / nested-array-cast paths. For the two `array_sort_asc/desc(split(...))` cases that succeed on `clickhouse-server`, re-enable as plain runnable tests and add the corresponding rows to the reference file. The `extend ex = array_sort_desc(...)` case in `02366_kql_extend.sql` still trips a parser `SYNTAX_ERROR` (the `ex =` alias is not yet supported); it is now annotated as `clientError SYNTAX_ERROR` so we will notice when the parser is improved. PR: #102159
LLVM Coverage Report
Changed lines: 67.92% (1080/1590) | lost baseline coverage: 33 line(s) · Uncovered code |
…heriting constructor Resolve merge conflicts from PR #102159 (KQL conformance tests): - KQLStringFunctions.cpp: take master's getConvertedArgument rewrite for parse_json(dynamic(...)) - ParserKQLMakeSeries.cpp: take master's timespan.toSeconds() fix Update 18 sites in new/modified KQL parsers (ParserKQLCount, ParserKQLTop, ParserKQLUnion, ParserKQLJoin, ParserKQLQuery, ParserKQLStatement) to use the Pos(Tokens&, const Pos&) constructor instead of Pos(Tokens&, max_depth, max_backtracks), preserving recursion depth counters across re-tokenized sub-expressions. Regenerate .github/workflows/pull_request.yml. Co-authored-by: Yakov Olkhovskiy <[email protected]>
Per the unresolved review thread on `Utilities.cpp:98`, the `kqlLetBindings`
thread-local store had no per-query cleanup hook: bindings could leak across
unrelated queries served by the same worker thread when the user did not
toggle `dialect` between them. Per-statement RAII clearing was previously
rejected because it would also wipe state needed by `let x = 5; print x;`
multi-statement scripts.
Install the guard only on the path that consumes bindings (regular KQL
queries falling through to `query_with_output_p.parse`). The `let` and
`SET` branches return earlier without constructing the guard, so:
* `let name = value;` keeps bindings — chains of `let` continue to share
state across separate `parseImpl` calls.
* `SET dialect = ...` already clears (unchanged).
* Any other KQL statement clears `kqlLetBindings` on scope exit, including
exception paths.
This bounds the cross-query leak window: stale bindings cannot persist
past the next non-`let` query on the same worker thread. Update the doc
comment on `kqlLetBindings` to describe the new lifecycle and the residual
gap (a chain of `let`s with no consuming statement on the same thread),
which still requires `Context`-scoped storage to close completely.
Validated against the conformance suite locally:
- `tests/queries/0_stateless/04092_kql_conformance_baby_kusto.sql`
(multiple `let; let; print extract(...)` patterns), passes.
- `tests/queries/0_stateless/04094_kql_conformance_pql.sql`, passes.
- `tests/queries/0_stateless/04093_kql_conformance_kusto_loco.sql`, passes.
- All `02366_kql_*.sql` tests pass.
PR: ClickHouse#102159
Review thread: "kqlLetBindings cleanup"
…ests
Per the unresolved review thread on `02366_kql_datatype.sql`, the
`time(2)` / `time(2) + 1d` checks were disabled with a `FIXME` comment
when the timespan parser was tightened to reject bare numeric literals
(`d4d3a` and follow-ups). Commenting them out removed runnable
regression coverage and conflicts with the "no test removal" rule.
Restore the assertions as executable negative checks with
`-- { clientError BAD_ARGUMENTS }` annotations, matching the pattern
already used elsewhere in the file (e.g. `print int('4')`). If the
parser is later extended to accept bare numerics for `time`, the test
will fail loudly instead of silently passing.
Verified locally: `clickhouse-server` rejects `time(2)` with
`BAD_ARGUMENTS` ("Not a correct timespan expression: time"), the
test's expected-error annotation absorbs both rows, and the test now
passes against `tests/queries/0_stateless/02366_kql_datatype.reference`
unchanged.
PR: ClickHouse#102159
Review thread: `02366_kql_datatype.sql` `time(2)` disabled
Per the unresolved review thread on `Utilities.cpp:98`, the `kqlLetBindings`
thread-local store had no per-query cleanup hook: bindings could leak across
unrelated queries served by the same worker thread when the user did not
toggle `dialect` between them. Per-statement RAII clearing was previously
rejected because it would also wipe state needed by `let x = 5; print x;`
multi-statement scripts.
Install the guard only on the path that consumes bindings (regular KQL
queries falling through to `query_with_output_p.parse`). The `let` and
`SET` branches return earlier without constructing the guard, so:
* `let name = value;` keeps bindings — chains of `let` continue to share
state across separate `parseImpl` calls.
* `SET dialect = ...` already clears (unchanged).
* Any other KQL statement clears `kqlLetBindings` on scope exit, including
exception paths.
This bounds the cross-query leak window: stale bindings cannot persist
past the next non-`let` query on the same worker thread. Update the doc
comment on `kqlLetBindings` to describe the new lifecycle and the residual
gap (a chain of `let`s with no consuming statement on the same thread),
which still requires `Context`-scoped storage to close completely.
Validated against the conformance suite locally:
- `tests/queries/0_stateless/04092_kql_conformance_baby_kusto.sql`
(multiple `let; let; print extract(...)` patterns), passes.
- `tests/queries/0_stateless/04094_kql_conformance_pql.sql`, passes.
- `tests/queries/0_stateless/04093_kql_conformance_kusto_loco.sql`, passes.
- All `02366_kql_*.sql` tests pass.
PR: ClickHouse#102159
Review thread: "kqlLetBindings cleanup"
…ests
Per the unresolved review thread on `02366_kql_datatype.sql`, the
`time(2)` / `time(2) + 1d` checks were disabled with a `FIXME` comment
when the timespan parser was tightened to reject bare numeric literals
(`d4d3a` and follow-ups). Commenting them out removed runnable
regression coverage and conflicts with the "no test removal" rule.
Restore the assertions as executable negative checks with
`-- { clientError BAD_ARGUMENTS }` annotations, matching the pattern
already used elsewhere in the file (e.g. `print int('4')`). If the
parser is later extended to accept bare numerics for `time`, the test
will fail loudly instead of silently passing.
Verified locally: `clickhouse-server` rejects `time(2)` with
`BAD_ARGUMENTS` ("Not a correct timespan expression: time"), the
test's expected-error annotation absorbs both rows, and the test now
passes against `tests/queries/0_stateless/02366_kql_datatype.reference`
unchanged.
PR: ClickHouse#102159
Review thread: `02366_kql_datatype.sql` `time(2)` disabled
Add 302 conformance test cases for the Kusto Query Language dialect, adapted from three open-source KQL implementations:
test/BabyKusto.Core.Tests/EndToEndTests.cstest/BasicTests/testdata/Goldens/Coverage includes:
print,project,extend,summarize,sort,take/limit,top,count,distinct,where/filter,join(multiple kinds),mv-expand,lookup,let,in/!in, string operators, case-insensitive variants, aggregation functions (count,sum,avg,min,max,dcount,percentile,make_list,make_set,arg_min,arg_max), scalar functions (strlen,substring,strcat,split,trim,tolower,toupper,reverse,bin,round,abs,sqrt,pow,log,isnull,coalesce,iff,case, type casts,array_length,array_sort_asc,geo_distance_2points), datetime functions, IP functions, null handling, and arithmetic/comparison operators.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add more tests for Kusto (KQL).
Documentation entry for user-facing changes
🤖 Generated with Claude Code
Version info
26.5.1.503