Skip to content

Build the SQL parser standalone: cut abseil, cctz, re2, boost and the settings schema - #111971

Closed
alexey-milovidov wants to merge 23 commits into
masterfrom
parser-standalone-build
Closed

alexey-milovidov wants to merge 23 commits into
masterfrom
parser-standalone-build

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Supersedes #111952 — that PR's two commits are the
first two here, so it is closed in favour of this one.

How small does src/Parsers get when built on its own? utils/wasm-parser answers it: a build
script, a five-function C entry point and a test, producing a 2.0 MB WebAssembly module (573 KB
gzipped) that parses, pretty-prints and reports syntax errors with positions. The motivating use
case is programs/server/play.html, which today ships only the lexer.

Most of the value is in what had to be cut to get there. Everything below stands on its own.

Dependencies the parser did not need

abseil, cctz and re2 are gone from the parser's transitive closure, and Core/Settings.h
with them.

  • cctz and the embedded timezone database entered through one line: SYSTEM ... SET FAKE TIME
    was parsed and formatted through DateLUT. Which timezone applies belongs to the server, not
    to the query text, so the AST keeps the literal and the interpreter resolves it.
  • re2 was reachable from three places. Two were regular expressions doing what a string scan
    does — maskURIPassword and the Azure connection-string masking. The third compiled
    COLUMNS('regexp') patterns from inside IASTColumnsTransformer::transform; applying a
    transformer needs the expanded column list, so it is name resolution rather than parsing, and
    it moves to Interpreters/applyColumnsTransformer.cpp. Validating a GRANT ... ON S3('...')
    pattern moves to InterpreterGrantQuery.
  • abseil went with re2, plus two direct uses: IParser.h wanted a short append-only list that
    does not allocate, and LiteralTokenMap wanted a flat map.
  • ParserSetQuery consulted the settings schema for one thing — whether a bare SET x names a
    Bool setting. It now records that the value was omitted and BaseSettings::applyChange checks
    the type, which is where the schema is known.
  • boost::algorithm::string is gone; Common/StringUtils.h grows a string overload of
    equalsCaseInsensitive and ASCII case conversion beside the per-character helpers it had.
  • Several includes turned out to be entirely unused, the widest being
    Poco/Util/Application.h in DumpASTNode.h, which reaches Poco::ThreadPool and is pulled in
    by InDepthNodeVisitor.h — over sixty translation units were paying for it.

Exceptions

The parser used throw/catch to decide between alternatives, which is the wrong mechanism — the
failure is an ordinary parse outcome. One of the four sites fired on any malformed string
literal. All four are gone, src/Parsers now contains no catch, and a style check keeps it
that way. That in turn lets the standalone build use -fignore-exceptions, which removed 262 KB
and, as a side effect, the need for an engine implementing the exception-handling proposal.

A latent ODR violation

ASTSQLSecurity::formatImpl was defined identically in two translation units. Static-library
linking never pulls both objects in, so it stayed invisible.

32-bit correctness, all of it latent: a uz literal that does not fit a 32-bit size_t, a
ProfileEvents counter/increment size mismatch, a Boost stored_size constraint in ASTs, and
itoa/iota guarding their long overloads on OS_DARWIN when the real condition is that
long is a distinct type.

Startup and code size for every build, not just the standalone one: the keyword table was
built at startup by 645 inlined resize/string-assign/unordered_set::emplace sequences,
compiling to a 57 KB constructor — the largest function in the parser — and costing 645 string
allocations per process. It is a constexpr std::array now, and the two consistency checks the
constructor performed became static_asserts, so they also run in release builds.

Also: every throw() exception specification in base/poco is now noexcept.

Testing

No behaviour change is intended except where noted below, so the coverage is mostly existing
tests plus two new unit tests where hand-written code replaced a library:

  • gtest_mask_uri_password.cpp checks the string scans against the regular expressions they
    replace, on a hand-written corpus and on 200000 random strings each — this is masking of
    secrets, so "close enough" is not good enough. The Azure connection-string scan is deliberately
    not equivalent: .*? cannot cross a newline, so AccountKey= followed by a value containing one
    did not match and the expression left the secret in place.
  • gtest_literal_token_map.cpp covers overwriting, growth past the inline storage, and agreement
    with std::unordered_map over 500 randomised rounds.
  • 03623 is updated: SET max_threads now reports TYPE_MISMATCH from the server rather than a
    syntax error from the client. Note it does not silently become max_threads = 1, which is
    what deferring the check without a marker would have done. 04660 is the same for a SETTINGS
    clause, which reaches the settings through InterpreterSetQuery::executeForCurrentContext
    rather than through execute, and pins that a rejected shorthand leaves the setting alone.
  • An invalid GRANT ... ON S3('[') pattern now reports CANNOT_COMPILE_REGEXP from the server
    instead of a syntax error. It cannot simply be dropped: the pattern is matched with
    RE2::FullMatch, so one that does not compile would grant nothing, silently.
  • SYSTEM ... SET FAKE TIME echoes the literal instead of renormalising it when formatted.

Verified with a full dbms build and the standalone build's test suite at every step.

Since the first review round: the standalone module aborted on a query the parser rejects by
throwing rather than by returning false — -fignore-exceptions leaves nothing to catch — so
__cxa_throw now jumps back to a setjmp boundary armed by ch_format and the message comes back
as a parse failure, for 570 bytes rather than the 262 KB of -fwasm-exceptions. The value-less
SETTINGS name check reached neither the SET path (Context::applySettingChange drops
everything but the name and the value, and the constraint check casts the value first) nor the
CREATE ... SETTINGS split path; both are fixed, with 04660 and 04662 covering them. The
GRANT ... ON S3('...') pattern is now validated in
AccessRightsElement::throwIfFilterIsNotCompilable, called from CHECK GRANT, from users.xml
grants and from the ATTACH USER replay as well as from InterpreterGrantQuery::execute — 04661.

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Reduced the dependencies and the code size of the SQL parser, which can now be built on its own — see utils/wasm-parser for a standalone WebAssembly build of it. The table of SQL keywords is now built at compile time instead of on every server start.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

alexey-milovidov and others added 8 commits July 26, 2026 18:56
…ncies

Groundwork for building `src/Parsers` on its own (the WebAssembly experiment in
`utils/wasm-parser` that follows). Everything here stands on its own as a fix or a
build-time improvement; nothing is WebAssembly-specific except the platform guards.

Dependencies the parser did not need:

* `DumpASTNode.h` included `Poco/Util/Application.h` and never used it. That header
  reaches `Poco::ThreadPool` and `Poco::SignalHandler`, and `DumpASTNode.h` is pulled in
  by `InDepthNodeVisitor.h`, so over 60 translation units paid for it.
* `ExpressionListParsers.cpp` included `AggregateFunctions/AggregateFunctionFactory.h`
  and never used it either, dragging `IAggregateFunction` and all of `Columns` into one
  of the heaviest translation units in the tree.
* `ParserSystemQuery.cpp` included the whole Keeper client for three path-string
  helpers. Those move to a new `Common/ZooKeeper/ZooKeeperPathUtils.h`; `ZooKeeper.h`
  includes it, so every existing user is unaffected.

`ASTSQLSecurity::formatImpl` was defined identically in both `ASTSQLSecurity.cpp` and
`ASTCreateQuery.cpp`. Static-library linking never pulls both objects in, so the ODR
violation stayed latent; it becomes a duplicate-symbol error as soon as the objects are
linked directly. Removed the copy in `ASTCreateQuery.cpp`.

`CommonParsers.cpp` built the keyword table at startup: 645 inlined
`resize`/`std::string` assign/`unordered_set::emplace` sequences, which compiled to a
57 KB constructor - the single largest function in the parser - plus 645 string
allocations and a hash-set build in every process. It is a `constexpr
std::array<std::string_view, N>` now, indexed directly by `Keyword`; the two consistency
checks the constructor performed became `static_assert`s, so they now also run in release
builds. `getAllKeyWords` and `getKeyWordSet` only feed system tables and query
obfuscation, so they materialize on first use.

32-bit correctness, all of which were latent:

* `ASTs` asked Boost for a `uint32_t` stored size, which Boost rejects unless the type is
  strictly smaller than `size_t`. Pick `size_t` when there is nothing to shrink.
* `DEFAULT_NATIVE_BINARY_MAX_NUM_ROWS` was a `uz` literal that does not fit in a 32-bit
  `size_t`, and is compared against a `UInt64` read off the wire.
* `ProfileEvents::Count` was `size_t` while `Increment` was `Int64`, tripping the
  `static_assert` that the two match.
* `itoa` and `iota` guarded their `long`/`size_t` overloads on `OS_DARWIN`. The real
  condition is that `long` is a type of its own, which is also true on any 32-bit
  platform, so the guard is now `!defined(__LP64__)` as well.
* `CLOCK_MONOTONIC_COARSE` is a Linux extension; `base/time.h` listed the platforms that
  need a substitute one by one and now falls back generically.

`base/defines.h` and Poco's `Platform.h` learn about `__wasm__` so that headers naming
the platform stop erroring out.

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

Three visitors in `src/Databases` were relying on `DumpASTNode.h` to give them
`Poco/Util/AbstractConfiguration.h` transitively; they include it themselves now.
An experiment in how small `src/Parsers` gets on its own. The Web UI currently ships only
the lexer (`Lexer.cpp` builds to a 6 KB `.wasm` with no dependencies); a real parser would
give exact syntax errors with positions and query pretty-printing in the browser.

`utils/wasm-parser/build.sh` compiles 500 translation units with wasi-sdk and links a
2.7 MB module (789 KB gzipped) exporting a five-function C interface. `test.mjs` drives it
through `SELECT`, `CREATE TABLE`, window functions, recursive CTEs, `ALTER`, `INSERT`,
`SYSTEM`, `CREATE USER`, `GRANT`, and two deliberate syntax errors.

`-fwasm-exceptions` is required rather than optional: the parser reports errors by
throwing, and the wasi-sdk headers refuse `setjmp.h` without it.

`wasm_runtime.cpp` substitutes no-ops for the pieces a browser has no use for, each of
which would otherwise dominate the bundle. Stack traces are the sharpest case:
`Common/Exception.cpp` cannot compile against stock libc++ at all, because it
`static_assert`s on `STD_EXCEPTION_HAS_STACK_TRACE` from ClickHouse's patched libc++.
`Core/Settings.cpp` is left out because `ParserSetQuery` calls `Settings::castValueUtil`
once - only to ask whether a bare `SET x` names a `Bool` setting - and that single call
pulls in every `SettingField*Traits` specialization, more code than the parser itself.
The timezone database that `contrib/cctz-cmake` generates into the binary is left out
too, as is query masking.

`shim/` holds the POSIX headers wasi-libc omits (`netdb.h`, `ucontext.h`, `sched.h`,
`pwd.h`, `fenv.h` rounding modes, `sun_path`, `__u6_addr`). Nothing calls into them; they
exist so headers that name those types in signatures still compile.

The README records where the size goes. The largest remaining cut is access-entity DDL:
`CREATE USER`/`ROLE`/`QUOTA`/`ROW POLICY` and `GRANT` account for 334 KB of parser and
`Access` code, roughly a third of the bundle once the re2 and abseil they share with
`COLUMNS('regexp')` matchers is counted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…confine re2

Continues cutting what `src/Parsers` drags in. Measured on the standalone WebAssembly build
(`utils/wasm-parser`), which links only the parser's transitive closure.

abseil is gone. `IParser.h` used `absl::InlinedVector` for the list of expected tokens, which
is a short append-only list that must not allocate - `Parsers/InlineVector.h` does that in
80 lines. `LiteralTokenMap` used `absl::flat_hash_map`; it is only populated when a caller asks
for literal positions, so `std::unordered_map` is enough.

cctz and the timezone database are gone. They entered through one line: `SYSTEM ... SET FAKE
TIME '...'` was parsed into a timestamp with `readDateTimeText` and formatted back with
`LocalDateTime`, both of which resolve against the server timezone via `DateLUT`. Which
timezone applies is a property of the running server, not of the query text, so the AST now
keeps the literal and `InterpreterSystemQuery` resolves it. As a side effect the formatter
echoes the literal instead of renormalizing it.

re2 was reachable from three places, and is now needed only by access-entity DDL:

* `maskURIPassword` and the Azure connection-string masking in `AzureQueue_fwd.h` were regular
  expressions doing what a string scan does. `Common/maskURIPassword.h` scans instead. This is
  masking of secrets, so `gtest_mask_uri_password.cpp` checks the new code against the regular
  expression it replaces - the two also agree on 200000 random strings over `ab:@/.` plus
  newline, which is how the edge cases around leftmost-match were settled.
* `IASTColumnsTransformer::transform` compiled `EXCEPT('regexp')` patterns. Applying a
  transformer needs the expanded column list, so it is name resolution rather than parsing;
  it moves to `Interpreters/applyColumnsTransformer.cpp`, and the AST nodes go back to being
  syntax. Every caller was already in `Interpreters` or `Analyzer`.
* `parseAccessRightsElements.cpp` validates a `GRANT ... ON ...(regexp)` pattern while parsing.
  Left alone: dropping the check would silently accept a grant that can never match. re2 and
  abseil are therefore now exactly the cost of access-entity DDL.

`Core/Settings.h` is gone from the parser. `ParserSetQuery` consulted the settings schema for
one thing: whether a bare `SET x` names a Bool setting, since the shorthand means `= true`. The
parser now records that the value was omitted and `BaseSettings::applyChange` checks the type,
which is where the schema is known. `SET max_threads` reports TYPE_MISMATCH instead of a syntax
error - 03623 is updated - and, importantly, does not silently become `max_threads = 1`, which
is what deferring without the marker would have done. The two `Settings`-taking overloads of
`parseIdentifiersOrStringLiterals` had no caller inside the parser and move to `Interpreters`.

Two more dead includes: `Core/ServerSettings.h` in `ASTAlterQuery.cpp`, and the `<ranges>` and
`Poco/Util/AbstractConfiguration.h` that other files had been getting transitively through the
includes removed here.

Parser bundle: 2759909 -> 2589773 bytes; cctz 30 KB -> 0, abseil and re2 now attributable
entirely to `GRANT`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`parseAccessRightsElements` compiled the pattern of `GRANT READ ON S3('...')` with re2 while
parsing, purely to reject one that does not compile. That is semantics, and it was the last
thing keeping a regex engine in `src/Parsers`.

The check moves to `InterpreterGrantQuery::execute`, next to the existing validation of TABLE
ENGINE parameter names. It cannot simply be dropped: the pattern is matched with
`RE2::FullMatch` when access is checked, and a pattern that does not compile never matches, so
the grant would be accepted and then silently grant nothing.

An invalid pattern now reports CANNOT_COMPILE_REGEXP from the server instead of a syntax error
from the client.

With this, re2 and abseil leave the parser entirely, and `utils/wasm-parser` stops building
them: 500 translation units down to 320, and 2759909 -> 2292544 bytes (788548 -> 622764
gzipped) since this series started.

Also records in `LiteralTokenInfo.h` why that map is no longer an `absl::flat_hash_map`, and
what to do instead if it ever matters: the flat map really is about twice as fast for the
create/insert/destroy pattern used there, so the note should not be lost.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`LiteralTokenMap` was an `absl::flat_hash_map`, and it was that for a reason: it is built from
scratch for every column expression the `Values` format has to parse and for every query the
client highlights, so construction and destruction dominate, and the flat map was measurably
faster than `std::unordered_map` there. Swapping it for `std::unordered_map` to shed abseil
was a regression.

Rather than take abseil back for one map, this is a table that serves only what the parser asks
of it. Nothing erases, so there are no tombstones and probing stops at the first empty slot;
nothing iterates; keys are `ASTLiteral` addresses and never null, so a null key marks an empty
slot. The first eight entries live inside the object, which is what actually matters here - the
common case stops allocating entirely.

It is faster than what it replaces at every size, on the construct/insert/look-up/destroy
pattern the parser uses (nanoseconds per cycle, aarch64):

    entries   unordered_map   flat_hash_map   LiteralTokenMap
          1          29              12                 5
          3         121              54                10
          8         322             150                57
         64        3673            1124               497
        512       32404            7015              3516

`find` returns a pointer rather than an iterator, which is what the three call sites wanted
anyway. `gtest_literal_token_map.cpp` covers overwriting, growth past the inline storage, and
agreement with `std::unordered_map` over 500 randomised rounds including absent keys.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two related cleanups.

`boost::algorithm::string` is gone from `src/Parsers`. What it was used for was case-insensitive
comparison, ASCII case conversion, splitting, joining and trimming, so `Common/StringUtils.h`
grows a string overload of `equalsCaseInsensitive` and ASCII `toLowerASCII`/`toUpperASCII` beside
the per-character helpers it already had, and the rest became a few lines at the call site. The
comparisons are ASCII now rather than locale-driven, which is what SQL keywords, identifiers and
function names want anyway. Four of the includes turned out to be unused.

The parser also used exceptions to decide between alternatives, which is the wrong mechanism for
it - the "failure" is an ordinary parse outcome, and it forces the whole exception machinery into
a component that otherwise would not need it. All four sites are gone:

* a malformed string literal went through `readQuotedStringWithSQLStyle` and was caught to report
  a syntax error. `tryReadQuotedStringWithSQLStyle` already existed.
* `tryGetLiteralBool` let `FieldVisitorConvertToNumber` throw for anything that is not a number.
  It now asks the field what it holds.
* checking whether a word names an access type constructed `AccessFlags` and caught the failure.
  `AccessFlags::tryFromKeyword` reports it instead; the throwing constructor is unchanged and now
  shares the lookup.
* `ASTSetQuery` ran the value of `format_avro_schema_registry_url` through `Poco::URI` to find
  embedded credentials, catching `Poco::SyntaxException`. Locating credentials in a URI is not
  the parser's job and `Common/maskURIPassword.h` already does exactly this, so it just calls
  that. A URI that `Poco::URI` would have rejected is now masked rather than printed, which is
  the safer direction; a `user@host` with no password is no longer rewritten to
  `user:[HIDDEN]@host`, since there is nothing there to hide.

`src/Parsers` now contains no `catch` at all.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Now that `src/Parsers` has no `catch`, keep it that way: an alternative that does not match is an
ordinary parse outcome and a parser says so by returning false, and routing that through
throw/catch also drags the exception machinery into a component that otherwise does not need it.

The check exempts the harnesses under `tests/`, `examples/` and `fuzzers/`, which are expected to
catch, and `Kusto/`, which is the one part of the parser still using exceptions this way - it
falls back between a number and a timespan, and turns a failed cast into NULL. The exemption is
named in the comment rather than left implicit so it reads as remaining work.

Verified both directions: the check is silent on the tree as it stands, and fires when a `catch`
is put back into `parseQuery.cpp`. The word "catch" in the `obfuscateQueries` word list is not a
false positive, since the pattern requires the opening parenthesis.

Also fixes what running the whole of `check_cpp.sh` turned up in the preceding commits: two error
codes left declared but unused once their throws moved out (`ZooKeeper.cpp`,
`parseIdentifierOrStringLiteral.cpp`), and blank lines left behind by a removed try/catch. The
headers under `utils/wasm-parser/shim/` are exempted from the source heuristics - they deliberately
imitate wasi-libc's own headers, down to the include guards, so `#pragma once` and the indentation
rules do not apply to them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`src/Parsers` has no `catch`, and a syntax error is reported by `tryParseQuery` returning null,
not by throwing. So in a standalone build an exception can only mean a bug or a resource limit,
and there is nothing to unwind to - the exception machinery is pure overhead.

The build now passes `-fignore-exceptions`, which compiles `throw`, `try` and `catch` but emits no
landing pads and no unwind tables. This needs no source changes at all - in particular no macro
over the `throw` keyword, which would have been undefined behaviour and would have mangled the
`throw()` exception specifications in Poco. What is left is a call to `__cxa_throw`, and defining
that in the WebAssembly runtime keeps libc++abi out of the bundle entirely: the exception object
is constructed, its message printed, and the module stops.

`CLICKHOUSE_PARSER_MINIMAL_BUILD` now has a job: `Common/StackTrace.h` is included by
`Common/Exception.h` and so by most of the tree, and it needs `<csetjmp>`, `<csignal>` and
`<ucontext.h>`, none of which exist without exception handling on WebAssembly. The parts that
need them are guarded out rather than making the header unavailable. Poco's `SignalHandler` is
guarded the same way, and `Thread_POSIX` stops referring to it.

Measured, `-Os`, stripped:

    2278794 -> 2016304 bytes,  618187 -> 569362 gzipped

and the module no longer needs an engine implementing the exception-handling proposal - it now
loads on stock Node 20 with no flags, where before it required `--experimental-wasm-exnref`.

Separately, and because they are an obsolete C++ feature in a library we own: every `throw()`
exception specification in `base/poco` is now `noexcept`. There were nineteen, plus two written
`throw ()`. None of them were dynamic specifications, so this is a straight rename.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…uild

# Conflicts:
#	src/Common/QueryFuzzer.cpp
#	src/Interpreters/InterpreterSystemQuery.cpp
#	src/Parsers/ASTAlterQuery.cpp
#	src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
`Generator.cpp` uses `std::views::keys` but only got the `<ranges>` header
transitively, through an include this branch removes.
The README described the state of the first commit that added it: 2.7 MB with
abseil, re2 and cctz in the closure, and an engine implementing the WebAssembly
exception-handling proposal. The later commits removed all four, so re-measure
against the linker map and drop what no longer applies.

Also, wasi-sdk names its AArch64 build `arm64` rather than `aarch64`, so the
download command in the README and in `build.sh` did not work on ARM.
…th `SET` actually takes

The check added to `BaseSettings::applyChange` was never reached from a `SET`
query: `Context::applySettingChangeWithLock` passes the name and the value to
`Settings::set` and drops the rest of the `SettingChange`, and the constraint
check that runs before it casts the value, so `SET max_threads` silently became
`max_threads = 1` and `SET default_database_engine` reported `BAD_GET` rather
than `TYPE_MISMATCH`.

Check it in `InterpreterSetQuery` before the constraints, and in
`Context::applySettingChange`, sharing `BaseSettings::checkShorthandIsBool` with
`applyChange`. This is what 03623 asserts; 04660 adds the `SETTINGS` clause,
which goes through `executeForCurrentContext`, and pins that a rejected
shorthand leaves the setting alone.
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [74093c2]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_tsan, flaky check) FAIL
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
3 more test cases not shown
Stateless tests (amd_msan, flaky check) FAIL
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04661_grant_source_filter_pattern_validation FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
03595_sources_regexp_filter_grants FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
Stateless tests (amd_debug, parallel) FAIL
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
03595_sources_regexp_filter_grants FAIL cidb
Stateless tests (amd_tsan, parallel) FAIL
03595_sources_regexp_filter_grants FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
Scraping system tables FAIL cidb, issue
Stateless tests (arm_binary, parallel) FAIL
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
03595_sources_regexp_filter_grants FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
04662_setting_boolean_shorthand_in_create_settings FAIL cidb
CI Tests DROPPED
Fast test (arm_darwin) DROPPED

AI Review

Summary

This PR makes the SQL parser buildable on its own and moves several semantic checks out of parser-only code so the standalone build can drop heavyweight dependencies. One blocker remains: the new SettingChange::shorthand invariant is enforced on the SQL path, but it is still dropped by the AST JSON representation, which reopens the silent-cast bug for formatQueryFromJSON / clickhouse_json.

Findings

❌ Blockers

  • [src/Parsers/ParserSetQuery.cpp:332] The new shorthand marker is not serialized by ASTSetQuery::writeJSON / readJSON, so parseQueryToJSON('SET max_threads') or parseQueryToJSON('SELECT 1 SETTINGS max_threads') loses the fact that the value was omitted. After the JSON round-trip, formatQueryFromJSON and clickhouse_json replay the pre-fix behavior and accept the setting as 1 instead of throwing TYPE_MISMATCH for non-Bool settings.
Final Verdict

❌ Needs changes before merge. The SQL-path fixes for valueless settings are good, but the same invariant has to survive AST JSON round-trips or the old behavior is still reachable through parseQueryToJSON, formatQueryFromJSON, and the clickhouse_json dialect.

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Jul 27, 2026
Comment thread utils/wasm-parser/wasm_parser.cpp Resolved
…hrows

The standalone module aborted on any query that the parser rejects by throwing
rather than by returning `false` - `SELECT sum(x) OVER (ROWS BETWEEN UNBOUNDED
FOLLOWING AND CURRENT ROW)`, for one - because `-fignore-exceptions` leaves
nothing to catch. Stopping the module on an ordinary user mistake is not
acceptable, so `__cxa_throw` now jumps back to a `setjmp` boundary armed by
`ch_format`, which reports the message as a parse failure; the module stays
usable afterwards, which the test now checks.

This costs 570 bytes and `-lsetjmp`, against the 262 KB and the
exception-handling proposal that `-fwasm-exceptions` would cost. `longjmp` runs
no destructors, so such a query leaks what the parser allocated below the
boundary - documented at `__cxa_throw`.
…T` pattern on every path

Two more consumers were bypassing the checks:

`InterpreterSetQuery::applySettingsFromQuery` splits a `CREATE ... SETTINGS`
clause into engine settings and query settings, and applied the query ones with
`setSetting`, which drops everything but the name and the value. `CREATE TABLE t
(a UInt8) ENGINE = Memory SETTINGS max_threads` was accepted silently and
`SETTINGS default_database_engine` reported `BAD_GET`. It now checks the
shorthand before the constraints and applies through `applySettingChange`.

The `GRANT READ ON S3('...')` pattern was compiled only in
`InterpreterGrantQuery::execute`, so `CHECK GRANT`, grants in `users.xml` and the
`ATTACH USER`/`ATTACH ROLE` replay in `AccessEntityIO` accepted a pattern that
cannot compile - and one that cannot compile grants nothing, because it is
matched with `RE2::FullMatch`. The check moves to
`AccessRightsElement::throwIfFilterIsNotCompilable`, which every one of those
paths now calls.
The randomised agreement check for `maskURIPassword` was described but not
written, and `maskConnectionStringKey` - which masks an Azure account key or
shared-access signature - had no test at all. Both now run 200000 random strings
over the alphabet the expressions are sensitive to.

The connection-string scan is not equivalent: `.*?` cannot cross a newline, so
`AccountKey=<value with a newline>` did not match and the expression left the
secret in place. The scan masks it, and the test pins that difference rather
than the old behaviour.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Noting the state, since #111986 says this one can be closed: this branch is now merged up to master, Style check and Fast test are green, and the three findings of the AI review above are fixed here — the standalone module aborting on a query the parser rejects by throwing, the value-less SETTINGS name check being bypassed by the CREATE ... SETTINGS split, and the GRANT ... ON S3('...') pattern being validated on only one of four paths — plus tests for each and for the secret-masking scans.

I have listed those over on #111986 (#111986 (comment)) so they can be carried over, rather than closing this in a way that loses them. Which of the two branches to keep is your call.

Comment thread utils/wasm-parser/wasm_runtime.cpp Resolved
… thrown type

`__cxa_throw` receives the exception object untyped. Reading it through a `Poco::Exception`
pointer is only defined if it really is a `DB::Exception`; a `std::bad_alloc` from
`operator new`, or a `Poco` exception from elsewhere, is an unrelated object. Establish the
dynamic type from the `type_info` argument first, recover only for `DB::Exception`, and report
just the type name and stop for anything else. `__cxa_allocate_exception` now returns storage
aligned for any type that can be thrown rather than for `char`, since the exception object is
constructed in place there. Filling in the recovery message no longer allocates.

Also drops the `Settings::castValueUtil` shim, dead since `ParserSetQuery` stopped consulting
the settings schema, and silences `cppcoreguidelines-pro-type-member-init` on
`InlineVector`, whose inline storage is deliberately not zeroed - it was failing `Build (arm_tidy)`.
`build.sh` piped the compiler output through `grep error: | head -20 || true`, so the exit status
was the pipeline's and a failed translation unit did not stop the script - it went on to link
whatever objects happened to be in the output directory, including stale ones from an earlier run.
Each object is now removed before its compiler runs, and the compile step exits non-zero.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

State after this round, and a correction to what the earlier note implied about which of these branches is the superset.

Addressed here:

  • The AI review's one blocker - the __cxa_* shim reading an untyped exception object as a Poco::Exception. The dynamic type now comes from the type_info argument first; recovery happens only for typeid(DB::Exception), anything else is reported by type name and stops the module, and __cxa_allocate_exception returns max-aligned storage. Filling in the recovery message no longer allocates, so an allocation failure there cannot re-enter __cxa_throw. See Build the SQL parser standalone: cut abseil, cctz, re2, boost and the settings schema #111971 (comment).
  • Build (arm_tidy) was red on cppcoreguidelines-pro-type-member-init for InlineVector, whose inline storage is deliberately not zeroed - only the first size() elements of it are ever read, and they are written before they are counted. Suppressed with a comment saying so; verified locally that the check does fire without the suppression and does not with it.
  • build.sh piped the compiler output through grep error: | head -20 || true, so a translation unit that failed to compile did not fail the script - it went on to link whatever objects were in the output directory, stale ones included.
  • Dropped the Settings::castValueUtil shim, dead since ParserSetQuery stopped consulting the settings schema.
  • Merged master (the branch was 375 commits behind; clean merge).

On the relationship with #111994 (parser-standalone-v3): I had assumed v3 contained this branch. It does not. Comparing each branch's changed-file set against its own merge base, eleven files here are absent there - Access/Common/AccessRightsElement.{h,cpp}, Access/UsersConfigParser.cpp, Interpreters/Access/InterpreterCheckGrantQuery.cpp, Interpreters/InterpreterSetQuery.cpp and the tests 04660, 04661, 04662. Those are exactly the two review findings that are still open on #111994: the GRANT ... ON S3('...') pattern being validated on only one of four paths, and the value-less SETTINGS name check being bypassed by the CREATE ... SETTINGS split. Conversely v3 has two commits this branch does not - the full-LTO and -Oz builds of the standalone module, worth 1.17 MB against 2.0 MB.

So neither is a superset, and whichever is kept should take the other's part. I have no preference; it is the same change either way.

Not verified here: the WebAssembly build itself, which needs the wasi-sdk this machine cannot fetch. Everything else was built (ninja clickhouse, all objects) and ci/jobs/scripts/check_style/check_cpp.sh is clean.

Comment thread src/Common/SettingsChanges.h Resolved
alexey-milovidov added a commit that referenced this pull request Jul 29, 2026
… `InterpreterGrantQuery::execute`

The description claims #111971 is contained here and can be closed. It was not: the pattern of
`GRANT READ ON S3('...')` was compiled in `InterpreterGrantQuery::execute` only, so `CHECK GRANT`,
grants in `users.xml` and the `ATTACH USER` / `ATTACH ROLE` replay in `AccessEntityIO` all accepted
a pattern that cannot compile. Since access is checked with `RE2::FullMatch`, such a pattern never
matches - the grant looks accepted and grants nothing. `CHECK GRANT READ ON S3('*(')` returned `1`.

This is #111971's `6a0d6942ab3`: the check moves to `AccessRightsElement::throwIfFilterIsNotCompilable`,
called from `execute`, `updateFromQuery`, `InterpreterCheckGrantQuery` and `UsersConfigParser`, with
its test `04661`. The parser still does not compile the pattern - that is the point of this PR - it
is validated where the access rights are built.

#111971's other part, the value-less `SETTINGS name` in a `CREATE ... SETTINGS` clause, is already
handled here: `CREATE TABLE t (a UInt8) ENGINE = Memory SETTINGS max_threads` and
`SETTINGS default_database_engine` both report `TYPE_MISMATCH`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

For the record, #112067 says all four predecessors "are contained here", and for this one that was not true until now: only InterpreterGrantQuery::execute validated the GRANT ... ON S3('...') pattern there, so CHECK GRANT READ ON S3('*(') returned 1 instead of CANNOT_COMPILE_REGEXP, and grants from users.xml and the ATTACH USER / ATTACH ROLE replay were unchecked too.

6a0d6942ab3 from this branch has now been ported to parser-standalone-v4 (ClickHouse/-shabroo@37a51fa000d) together with 04661, so AccessRightsElement::throwIfFilterIsNotCompilable is called from all four paths there. This branch's other part - the value-less SETTINGS name in a CREATE ... SETTINGS clause - was already handled in #112067; verified that CREATE TABLE t (a UInt8) ENGINE = Memory SETTINGS max_threads and SETTINGS default_database_engine both report TYPE_MISMATCH there.

With that, #112067 really is a superset of this PR.

alexey-milovidov and others added 2 commits July 30, 2026 20:26
`Build (arm_tidy)` was red on `cert-msc51-cpp` for the deliberately constant RNG seeds
(deterministic tests, same NOLINT as `gtest_sort.cpp`) and on `cppcoreguidelines-init-variables`
for `key` in `gtest_literal_token_map.cpp`.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111971&sha=918bb1edfb5c0cdd776732725a5d9de4118417a9&name_0=PR&name_1=Build%20%28arm_tidy%29
#111971

Co-Authored-By: Claude Fable 5 <[email protected]>
…ntry

Address review: `SettingChange::shorthand` is recorded at parse time, but the merge-by-name
paths in `AlterCommands::apply` and `DatabaseOnDisk::modifySettingsMetadata` updated an existing
entry with `it->value = change.value`, keeping the stale `shorthand` bit. So a value-less
`ALTER ... MODIFY SETTING index_granularity` on a table whose metadata already stores
`index_granularity = 8192` skipped `checkShorthandIsBool` and silently applied `= 1` instead of
throwing `TYPE_MISMATCH`. The merge now replaces the whole `SettingChange`.

`SettingsChanges::setSetting` had the inverse hazard - overwriting with a concrete value kept a
stale `shorthand = true` - so it clears the marker.

04663 pins both directions: the rejected shorthand leaves the stored value alone, and the Bool
shorthand is accepted when it overwrites a stored entry.

#111971

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jul 31, 2026
The module aborted on any query the parser rejects by throwing rather than by
returning `false` - `SELECT sum(x) OVER (ROWS BETWEEN UNBOUNDED FOLLOWING AND
CURRENT ROW)`, for one - because `-fignore-exceptions` leaves nothing to catch.
`__cxa_throw` now jumps back to a `setjmp` boundary armed by `ch_check` and
`ch_format`, which report the message as a parse failure; the module stays
usable afterwards, which the test now checks. Recovery is gated on the thrown
type being exactly `DB::Exception`; anything else still stops the module.

This costs about 570 bytes and `-lsetjmp`, against the 262 KB and the
exception-handling proposal that `-fwasm-exceptions` would cost. `longjmp` runs
no destructors, so such a query leaks what the parser allocated below the
boundary - documented at `__cxa_throw`.

Ported from `parser-standalone-build` (ebca121, 905c264, 6c4bdae),
which #112067 supersedes; flagged in
#112067 (comment)
…uild

Conflict resolution notes:
- src/Parsers/ASTColumnsTransformers.cpp: kept master's new AST JSON
  serialization (writeJSON/readJSON) and this branch's removal of the
  semantic transform code (which lives in
  src/Interpreters/applyColumnsTransformer.cpp on this branch).
- src/Parsers/ASTCreateQuery.cpp, src/Parsers/ASTSQLSecurity.cpp: master
  added JSON methods in a new ASTSQLSecurity.cpp while this branch had
  moved formatImpl there; combined both.
- src/Parsers/ASTSetQuery.cpp: kept this branch's regex-free
  maskURIPassword masking; dropped the now-unused tryParseURI helper.
- src/Parsers/FunctionSecretArgumentsFinder.{h,cpp}: master moved the
  implementation out of the header into a new .cpp; re-applied this
  branch's dependency cuts there (equalsCaseInsensitive instead of
  boost::iequals, maskConnectionStringKey instead of re2) and added
  regex-free maskURIUserInfo / maskURIPresignedCredentials to
  Common/maskURIPassword.h for master's new S3 URL credential masking,
  checked against the original regular expressions in
  gtest_mask_uri_password.cpp.
- utils/wasm-parser/build.sh: master's new AST JSON deserialization
  makes Poco::JSON reachable from src/Parsers, so the standalone build
  now compiles the Poco JSON sources (and pdjson.c as C).
…parser

- `ASTSystemQuery` stores `fake_time_for_view` as its literal text on this
  branch (converting it to a timestamp needs the server timezone), so the
  AST JSON representation carries the string, not an integer.
- The `MaskURIUserInfo` test expected masking of a password containing a
  slash, which the regular expression it is checked against never matched
  (`[^/?#]+` cannot cross a slash); assert the actual behavior.
- Style check 19 (no `catch` in `src/Parsers`) now exempts the AST JSON
  deserialization (`ASTFromJSON`, `ASTJSONReadHelpers`): it is not a
  grammar parser and reads documents through the throw-based `Poco::JSON`
  API.

change.name = name;
change.value = node->as<ASTLiteral &>().value;
change.shorthand = !have_eq;

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.

change.shorthand is the new bit that distinguishes a valueless setting change from an explicit = true, but the ASTSetQuery JSON serializer still only carries name and value. As a result, parseQueryToJSON('SET max_threads') / parseQueryToJSON('SELECT 1 SETTINGS max_threads') lose the marker on the writeJSON -> readJSON round-trip, and formatQueryFromJSON / the clickhouse_json dialect fall back to the old silent-cast behavior by accepting the change as 1 instead of raising TYPE_MISMATCH for a non-Bool setting. This new invariant needs to be preserved through AST JSON too, with a focused JSON-path regression test.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant