Skip to content

Add KQL conformance tests from open-source implementations - #102159

Merged
alexey-milovidov merged 104 commits into
masterfrom
kql-conformance-tests
May 11, 2026
Merged

alexey-milovidov merged 104 commits into
masterfrom
kql-conformance-tests

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Apr 9, 2026 •

Copy link
Copy Markdown
Member

Add 302 conformance test cases for the Kusto Query Language dialect, adapted from three open-source KQL implementations:

  • 123 tests from baby-kusto-csharp — a self-contained KQL execution engine (MIT License, Copyright Microsoft Corporation). Source: test/BabyKusto.Core.Tests/EndToEndTests.cs
  • 145 tests from kusto-loco — an extended KQL engine fork of BabyKusto (MIT License, Copyright Neil MacMullen). Source: test/BasicTests/
  • 34 tests from pql — a KQL-inspired language that compiles to SQL (Apache License 2.0, Copyright RunReveal Inc.). Source: 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):

  • Build/Testing/Packaging Improvement

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

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.5.1.503

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]>
@clickhouse-gh

clickhouse-gh Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7fe6057]

Summary: ✅


AI Review

Summary

This PR adds broad KQL conformance coverage and corresponding parser/function adjustments. I found three still-live issues: one correctness issue in let binding lifecycle and two coverage regressions where previously active checks are still disabled instead of being kept as executable negative tests.

Findings

❌ Blockers

  • [src/Parsers/Kusto/Utilities.cpp:98] kqlLetBindings is still thread_local process-lifetime state and is not cleared on query/session boundaries. let values can leak across unrelated queries on reused worker threads, making results depend on execution history.
    Suggested fix: bind let storage to query/session Context lifecycle or add guaranteed query-end cleanup on all paths.

⚠️ Majors

  • [tests/queries/0_stateless/02366_kql_datatype.sql:42-44] time(2) checks are still commented out, removing executable coverage.
    Suggested fix: keep them as explicit expected-error assertions instead of comments.
  • [tests/queries/0_stateless/02366_kql_func_dynamic.sql:135-175] multiple previously active checks (set_* wrappers with array_sort_asc, and zip) remain commented out.
    Suggested fix: convert each to explicit expected-error checks so the cases stay covered.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Cross-query let state leak remains in parser path.
No test removal ⚠️ Several previously active test assertions are still disabled via comments.
Experimental gate ➖
No magic constants ✅
Backward compatibility ⚠️ Query behavior can depend on prior query history due to leaked let bindings.
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ⚠️ Stateful leakage risk makes rollout unsafe for mixed workloads.
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Fix let binding lifecycle so bindings cannot leak across unrelated queries.
  2. Restore disabled stateless coverage by replacing commented-out checks with deterministic expected-error assertions.

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Apr 9, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as draft April 9, 2026 03:39
alexey-milovidov and others added 7 commits April 9, 2026 04:35
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]>
Comment thread src/Parsers/Kusto/ParserKQLJoin.cpp Resolved
alexey-milovidov and others added 3 commits April 9, 2026 05:38
…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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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).

Comment thread src/Parsers/Kusto/ParserKQLJoin.cpp Resolved
alexey-milovidov and others added 4 commits April 9, 2026 06:07
- 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]>
Comment thread src/Parsers/Kusto/ParserKQLTop.cpp Resolved
Comment thread src/Parsers/Kusto/ParserKQLUnion.cpp Resolved
alexey-milovidov and others added 10 commits May 5, 2026 14:04
…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]>

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Submitting existing pending review to allow new inline comments.

Comment thread src/Parsers/Kusto/ParserKQLQuery.cpp Resolved
Comment thread src/Parsers/Kusto/ParserKQLQuery.cpp Resolved
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, provide a fix for Unit tests (msan, function_prop_fuzzer)

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — investigated, this is a chronic trunk MSan bug in MultiVolnitsky, not caused by PR #102159. There is already an open fix PR by @yakov-olkhovskiy.

Failure signature (from Unit tests (msan, function_prop_fuzzer) log on commit 91bf295):

SUMMARY: MemorySanitizer: use-of-uninitialized-value src/Common/Volnitsky.h:724:31 in putNGramBase

Triggered via MultiVolnitskyBase::hasMoreToSearch → putNGramUTF8CaseInsensitive (the uninitialized value originates in Volnitsky.h:186 seq_l.i.i) when multiSearchFirstIndexCaseInsensitiveUTF8 is invoked from the function-property fuzzer.

This PR doesn't touch Volnitsky.h or any multiSearch* code path. The 53 modified files are entirely under src/Parsers/Kusto/ (KQL parser/functions). The asan_ubsan and tsan variants of function_prop_fuzzer pass on the same commit; only the MSan variant fails — consistent with a pre-existing uninitialized-memory finding triggered by random fuzzer inputs.

CIDB chronic-trunk evidence (last 60 days, test_context_raw LIKE '%putNGramBase%'):

  • 10 master hits spread across 14 different days (most recent: 2026-05-08 19:54 UTC)
  • 62 PR hits across 56 distinct unrelated PRs
  • First seen 2026-04-23, still active 2026-05-10

Existing fix: #103864 — Fix MultiVolnitsky fallback for failed UTF-8 ngram inserts (open, modifies src/Common/Volnitsky.h exactly where this fires — rolls back partial putNGram inserts on failure and routes failed needles to fallback searchers). Last reviewed by @vdimir 2026-05-07 (commented). I'd suggest just unblocking that PR — once it merges, this trunk noise disappears for everyone.

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
@clickhouse-gh

clickhouse-gh Bot commented May 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 67.92% (1080/1590) | lost baseline coverage: 33 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this May 11, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 11, 2026
Merged via the queue into master with commit 2f0c100 May 11, 2026
165 checks passed
@alexey-milovidov
alexey-milovidov deleted the kql-conformance-tests branch May 11, 2026 00:46
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 11, 2026
cursor Bot pushed a commit that referenced this pull request May 11, 2026
…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]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request May 15, 2026
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"
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request May 15, 2026
…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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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"
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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
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.

3 participants