Skip to content

Build the SQL parser standalone: cut abseil, cctz, re2, boost, locale, the settings schema, and optionally formatting and DCL - #112067

Merged
alexey-milovidov merged 42 commits into
masterfrom
parser-standalone-v4
Jul 31, 2026
Merged

alexey-milovidov merged 42 commits into
masterfrom
parser-standalone-v4

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Supersedes #111994,
#111986,
#111971 and
#111952 — all four are contained here and can be
closed.

How small does src/Parsers get when built on its own? utils/wasm-parser answers it: a build
script, a small C interface and a test, producing a WebAssembly module that parses, pretty-prints
and reports syntax errors with positions, on any engine with no flags. The motivating use case is
programs/server/play.html, which today ships only the lexer.

build bytes gzip -9 brotli -q 11 zstd --ultra -22
everything 1168636 362827 273666 293095
--no-dcl 966857 296331 225230 241372
--no-formatting 926511 298006 229139 246040
--no-formatting --no-dcl 754152 242329 188219 201737

The first version was 2.7 MB.

How it compares

Sorted by brotli, which is what a browser negotiates:

bytes gzip -9 brotli -q 11 zstd --ultra -22
node-sql-parser 5.4.0, one dialect, JS 323347 71122 58777 62024
@clickhouse/parser 0.3.0 + zod, JS 1128583 196944 153347 161974
libpg-query 17.7.4, wasm 1150984 229158 168575 176785
— its emscripten glue, on top of that 58903 16679 14888 15718
this, --no-formatting --no-dcl 754152 242329 188219 201737
this, everything 1168636 362827 273666 293095
sql.js 1.14.1, wasm 659730 322193 278641 289690
node-sql-parser 5.4.0, all 20+ dialects, JS 2609025 504010 333174 360819
@polyglot-sql/sdk 0.6.2, wasm 21656938 4805067 2020675 2150089

The row to measure against is libpg-query: the same idea, a production database's own parser
compiled to WebAssembly rather than reimplemented. With its glue it is 183463 brotli against this
build's 188219 — the same ballpark, for a grammar of comparable size.

The two JS parsers are smaller, and both are reimplementations. @clickhouse/parser is a Peggy
grammar with Zod schemas for the same dialect, so it can drift from the server, where this cannot;
its published index.mjs is 3.6 MB unminified and imports zod externally, so the row above is
both, bundled and minified with esbuild, as a consumer would ship them. node-sql-parser is the
smallest thing here per dialect, and covers much less of any of them; loading all its dialects
costs more than this whole module.

sql.js is a whole SQLite — engine, storage and all, not a parser — and is here only for scale.
It is the one entry smaller than this uncompressed and larger after compression. polyglot is a
transpiler carrying thirty grammars and thirty generators; stripped, but built at Rust's default
release settings rather than for size.

superjobru/clickhouse-sql-parser is not in the table: an abandoned prototype, last commit
February 2022, about 55 KB of Rust handling basic CREATE TABLE, with nothing published to
measure.

Most of the value is in what had to be cut to get there, and very little of it is parser code.
Everything below stands on its own.

Dependencies the parser did not need

abseil, cctz, re2, boost::algorithm::string, <locale> and Core/Settings.h are all gone from
the parser's transitive closure.

  • cctz and the timezone database entered through one line: SYSTEM ... SET FAKE TIME was parsed
    and formatted through DateLUT. Which timezone applies belongs to the server, not 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, Azure connection strings); the third compiled COLUMNS('regexp') patterns
    inside IASTColumnsTransformer::transform, which is name resolution rather than parsing and
    moves to Interpreters/applyColumnsTransformer.cpp. Validating a GRANT ... ON S3('...')
    pattern moves to InterpreterGrantQuery.
  • Nothing wants a locale - keywords and identifiers are ASCII - but twelve objects pulled
    <locale> in. boost::to_lower is locale-based, and AccessType.h reached <ostream> through
    boost/algorithm/string/split.hpp. Poco's Bugcheck::what built one message with an
    ostringstream, and since Bugcheck.h arrives via Poco/Foundation.h, that single include was
    worth 181 KB.
  • ParserSetQuery consulted the settings schema for one thing - whether a bare SET x names a
    Bool setting. It records that the value was omitted and BaseSettings::applyChange checks the
    type, where the schema is known.

Exceptions

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

Costs that were not the parser

abi::__cxa_demangle was 132 KB, reached only to put a type name in an exception message.
ErrorCodes::values was 150 KB of data - the per-code statistics behind system.errors.
IAST::setAlias's "this node does not take an alias" error message named getColumnName() and
getID(), and that unreachable throw was the only thing in the parser naming either, keeping an
override of both alive in all ~150 AST classes.

Latent bugs found on the way

  • ASTSQLSecurity::formatImpl was defined identically in two translation units. Static-library
    linking never pulls both objects in, so the ODR violation stayed invisible.
  • Poco/Util/Application.h was included but unused by DumpASTNode.h, which reaches
    Poco::ThreadPool and arrives via InDepthNodeVisitor.h - over sixty translation units paid.
  • 32-bit correctness, all 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.
  • ASTTableJoin::formatImpl hashed every aliased ON expression and then discarded the answer
    unless the old analyzer's collapse_identical_nodes_to_aliases was set.

Optimizing for size

The standalone build uses -Oz, full LTO and -fvirtual-function-elimination. The last of those
needs full LTO, which is why the server, on ThinLTO, cannot have it - clang rejects the
combination outright; here the whole program is 320 translation units, so it is available.

-Oz over -Os is worth 19% of the module. Most of the size is inlining rather than template
instantiation: attributing every symbol to the template that owns it puts std::vector's member
functions at 42 KB and std::string's at 5 KB, the latter being that small only because string
operations are inlined into their callers and never emitted as string symbols at all. -Oz costs
about 22% of parse throughput, which is the right way round for something downloaded once and
then asked to parse one query at a time.

Virtual function elimination works per vtable slot, so one surviving call keeps the override in
every class. Three call sites were holding slots open for nothing, the striking one being
IAST::setAlias: its "this node does not take an alias" error message named getColumnName()
and getID(), and that unreachable throw was the only thing in the parser naming either.

For every build, not just the standalone one

The SQL keyword table was built at startup by 645 inlined resize/string-assign/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. The two
Access tables get the same treatment. Every throw() exception specification in base/poco is
now noexcept.

Testing

No behaviour change is intended except where listed, so coverage is existing tests plus two unit
tests where hand-written code replaced a library:

  • gtest_mask_uri_password.cpp checks the string scan against the regular expression it replaces;
    they agree on 200000 random strings over ab:@/. and newline. This is masking of secrets, so
    "close enough" is not good enough.
  • gtest_literal_token_map.cpp covers overwriting, growth past the inline storage, and agreement
    with std::unordered_map over 500 randomised rounds.

User-visible changes, all deliberate:

  • SET max_threads reports TYPE_MISMATCH from the server rather than a syntax error from the
    client (03623 updated). It does not silently become max_threads = 1, which is what
    deferring the check without a marker would have done.
  • An invalid GRANT ... ON S3('[') pattern reports CANNOT_COMPILE_REGEXP 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 its literal instead of renormalising it when formatted.
  • A malformed URI in a setting value is now masked rather than printed; user@host with no
    password is no longer rewritten to user:[HIDDEN]@host, since there is nothing to hide.
  • Case-insensitive comparison of keywords and access-type names is ASCII rather than locale-driven.
  • IAST::setAlias's error message shows the offending node instead of its kind.
  • The EPHEMERAL column type is no longer rewritten by the server's query_masking_rules.

Two things the module can be built without

Both are build options rather than defaults, and ch_features reports which one a given module
was built with.

  • --no-formatting (242 KB). Turning an AST back into SQL cannot be dropped piecemeal:
    formatImpl is virtual, every AST class overrides it, and the linker keeps all 116
    implementations as long as one call goes through that slot — removing the call from the entry
    point saved 48 bytes. Removing the last one removes all of it.

    Parsing itself formats, in four places that keep a fragment of the query as a string rather
    than as a subtree: the type in CAST(x, 'T') and x::T, the column type inside
    defaultValueOfTypeName for EPHEMERAL, and the settings in the viewExplain that a
    (EXPLAIN ... SELECT ...) subquery becomes. All four now go through astText, which formats
    as before and falls back to the query text — the new textBetween — only where there is no
    formatter. The two are not interchangeable: the formatted spelling is canonical and is what
    ends up in table metadata, while the source text carries the user's line breaks into it.

  • --no-dcl (202 KB). Access management — CREATE USER, CREATE ROLE, quotas, row policies,
    settings profiles, masking policies, GRANT, REVOKE, CHECK GRANT, SET ROLE, EXECUTE AS
    and the SHOW statements that go with them. DEFINER on a view still parses, being part of
    CREATE. It is the only family of statements worth an option: CREATE TABLE is 57 KB, ALTER
    36 KB, SYSTEM 32 KB, and they overlap too much to be worth one each. DCL is different because
    it is not only grammar — GRANT needs the privilege lattice in src/Access/Common and
    CREATE USER the authentication types and host patterns. The README has the full table.

Verified with a full dbms build, all 26409 unit tests, the whole of check_cpp.sh, and the
standalone build's test suite at every step.

The EPHEMERAL part of astText is also #112048 on
its own, since it fixes a bug that has nothing to do with this: the type was formatted with
formatForLogging, which runs the server's query_masking_rules over it. Whichever merges first,
the other needs a merge from master.

Related: #112048

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 tables of SQL keywords and access types are now built at compile time instead of on every server start.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.551 (included in 26.8 and later)

alexey-milovidov and others added 17 commits July 27, 2026 10:18
…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]>
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]>
It was staged in the working tree before this branch was created, unrelated to the parser
work, and got swept into the first commit of the branch. This puts it back to its state on
`master`, so the branch touches only the parser and its dependencies.

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]>
Three findings from breaking down where the 2.0 MB bundle actually goes. None of them is parser
code; together they are 203 KB, about 10%.

`abi::__cxa_demangle` was 132 KB - a complete C++ name parser, more than `src/IO` and `src/Core`
put together. The only thing reaching it is a type name inside an exception message, from
`FieldVisitorConvertToNumber`, `typeid_cast` and `makeASTForLogicalFunction`. In a build with no
exception handling that message is never displayed, so `demangle` returns the mangled name, which
is what it already does when demangling fails.

`ErrorCodes::values` was 150 KB of data - 86% of the whole DATA section. It is one
`ErrorPairHolder` per error code, each holding the last message, format string, query id and
captured stack trace, twice over for local and remote, plus a mutex. That is what backs
`system.errors`; a parser needs the code-to-name table above it and nothing else.

Two tables in `Access` were built at startup by expanding a macro list at every call site, the
same pattern already fixed for the SQL keywords: `makeNodes` compiled to 35 KB and the access-type
name converter to 11 KB, because each of the 258 entries materialized its own string views and
call. Both are driven from a `constexpr` table now. `makeNodes` still builds its tree at runtime -
it resolves parent groups by name - but from a loop rather than 258 inlined calls.

    2016304 -> 1813657 bytes,  569362 -> 512278 gzipped

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

libc++'s locale.cpp is over 150 KB and nothing in the parser wants a locale: keywords,
identifiers, access-type names and connection strings are all ASCII, and converting them
according to the C++ locale is wrong as well as expensive. Twelve objects were dragging it in,
none of them deliberately.

`boost::to_lower` and friends are locale-based, so `Access/Common` reached `std::locale` through
them - and `AccessType.h` reached it through `boost::algorithm::string/split.hpp`, which includes
`<ostream>`, so every translation unit that touched an access type paid for it. Those use the
ASCII helpers now, and `Common/StringUtils.h` gains `replaceAll` for the multi-character
replacements that `std::replace` cannot do.

The rest:

* fmt is built with `FMT_USE_LOCALE=0`; it only wanted a locale for thousands separators.
* Poco's `Bugcheck::what` built its message with an `ostringstream`. `Bugcheck.h` is reached from
  `Poco/Foundation.h`, so that single `<sstream>` put the locale tables in front of nearly every
  Poco translation unit - by itself it accounted for 181 KB of the bundle.
* `Poco/Net/IPAddress.h` included `<ostream>` for one `operator<<` declaration; `<iosfwd>` is
  enough for a declaration.

    1813657 -> 1603384 bytes,  512278 -> 462982 gzipped

Three referrers are left and locale.cpp stays linked until all of them go: Poco's `Format` and
`DigestStream`, which are stream-based by nature, and `double-conversion`, whose `ToLower` uses
`std::use_facet<std::ctype<char>>` to parse "infinity" and "nan" - that one is in the submodule
and needs a bump of the ClickHouse fork.

Check 20 forbids `boost::to_lower`/`to_upper` where the locale must not be linked. It covers
`src/Parsers`, `src/Access` and `base/poco`, which are now free of it; the rest of the tree still
has around ninety call sites, and the paths widen as those are converted.

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

`-flto -fwhole-program-vtables -fvirtual-function-elimination` on the standalone build. The last
of those drops virtual functions that nothing calls through a vtable, and it needs full LTO -
which is why the server, on ThinLTO, cannot have it: clang rejects the combination outright. Here
the whole program is these 320 translation units, so it is both available and cheap.

Virtual function elimination works per vtable slot: one surviving call anywhere keeps the
override in every class. Three call sites were holding slots open that the parser has no other
use for.

`IAST::setAlias` is the striking one. Its "this node does not take an alias" error message named
`getColumnName()` and `getID()`, and that single throw - which nothing reaches in normal operation
- was the only thing in the parser naming either. It kept an override of both alive in all ~150
AST classes. It reports the offending node with `formatForErrorMessage` now, which is on the
formatting path anyway and says more than the node's kind did.

Two parsers asked an identifier for its name through `getColumnName()`, which is the virtual
column-naming machinery - `ASTSubquery`, for one, answers it by hashing its whole subtree. Both
already had an `ASTIdentifier` in hand, so they use `getIdentifierName`.

Also, `ASTTableJoin::formatImpl` hashed every aliased ON expression to look it up in
`printed_asts_with_alias`, then discarded the answer unless `collapse_identical_nodes_to_aliases`
was set - which is the old analyzer's path, off by default. The lookup moves inside the branch
that uses it, so the common path stops computing a SipHash of the subtree it is about to print.

    1603384 -> 1444957 bytes,  462982 -> 429053 gzipped

Most of that is LTO. The call-site fixes are worth less than the size of the methods they free,
because `wasm-ld` has no `--lto-whole-program-visibility`, so elimination stays conservative.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Where the size goes is inlining, not template instantiation. Attributing every symbol to the
template that owns it puts `std::vector`'s own member functions at 42 KB and `std::string`'s at
5 KB - the string figure is that small because string operations are inlined into their callers
rather than emitted, so they are invisible to any per-symbol accounting and show up inside
`parseImpl` and `formatImpl` bodies instead.

-Oz attacks exactly that, and is worth far more than replacing either container would be:

    -Os   1444957 bytes,  429053 gzipped,  307662 brotli
    -Oz   1167632 bytes,  362388 gzipped,  273443 brotli

It costs about 22% of parse throughput - 155 to 190 microseconds for a mid-sized query with
formatting - which is the right way round for something downloaded once and then asked to parse
one query at a time.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Turning an AST back into SQL is 242 KB of the 1.17 MB WebAssembly parser - a
fifth of it - and none of it can be dropped piecemeal. `formatImpl` is virtual,
every AST class overrides it, and the linker keeps all 116 implementations as
long as one call goes through that slot, so removing the call from the entry
point saves 48 bytes. `build.sh --no-formatting` removes the last call instead
and produces a 926 KB module that answers whether a query parses.

The switch is `CLICKHOUSE_PARSER_NO_FORMATTING`, and it is confined to the four
functions in `IAST.cpp` that call `formatImpl`, plus
`formatWithPossiblyHidingSensitiveData`, which becomes a placeholder. Nothing in
the 116 AST classes needs an `#ifdef`; they simply become unreachable.

That still leaves parsing itself, which reaches the formatter in a few places
that have to keep a fragment of the query as a string: the type in
`CAST(x, 'T')` and `x::T`, the column type inside `defaultValueOfTypeName` for
`EPHEMERAL`, and the settings in the `viewExplain` a `(EXPLAIN ... SELECT ...)`
subquery turns into. These now go through `astText`, which formats as before,
and in a build with no formatter uses the text the user wrote - captured with
the new `textBetween`.

The two are not interchangeable, which is why `astText` exists rather than the
source text being used everywhere: the formatted spelling is canonical and is
what ends up in table metadata, while the source text carries the user's line
breaks into it. `CREATE TABLE t (x UInt8, e Enum8\n  (\n 'hello' = 1 ...`
would store the newlines and indentation inside the string literal, and
`SHOW CREATE TABLE` would print them back.

One behaviour change: the `EPHEMERAL` type text was produced by
`formatForLogging`, which hides secrets and applies the server's query masking
rules to it - a data type has no secrets, and the comment there said as much.
It now uses the same call as the other three sites.
…matter

The section described an earlier version of the change, in which parsing took
the type text straight from the query in every build. It does not - see
`astText` - because the formatted spelling is the one that ends up in table
metadata.
Access management - `CREATE USER`, `CREATE ROLE`, quotas, row policies, settings
profiles, masking policies, `GRANT`, `REVOKE`, `CHECK GRANT`, `SET ROLE`,
`EXECUTE AS`, `SHOW GRANTS`, `SHOW ACCESS`, `SHOW CREATE USER`,
`SHOW PRIVILEGES` - is 201779 bytes of the 1168636-byte WebAssembly parser, and a
SQL editor in a browser has little use for it. `build.sh --no-dcl` leaves it out,
which also brings the module below what it costs with formatting removed:

    everything                    1168636    362827 gzipped
    --no-dcl                       966857    296331
    --no-formatting                926511    298006
    --no-formatting --no-dcl       754152    242329

`CLICKHOUSE_PARSER_NO_DCL` takes these out of the dispatch in `ParserQuery.cpp`
and `ParserQueryWithOutput.cpp`, and the linker drops `src/Parsers/Access` and
`src/Access/Common` with them - verified with `llvm-nm`: no `ParserGrantQuery`,
no `AccessFlags`. `DEFINER` on a view still parses, being part of `CREATE`.

The alternatives are grouped into five functions rather than guarded one by one,
because each has to keep its place in the chain: `SET ROLE` is tried before
`SET`, which would otherwise read it as the shorthand for a `Bool` setting named
`ROLE`, and `SHOW CREATE USER` before `SHOW TABLES`.

The module gains a `ch_features` export saying which of these switches it was
built with, so one piece of JavaScript can drive more than one build; `test.mjs`
uses it to decide whether the DCL cases are expected to parse.

The README gains what each other family of statements costs, measured the same
way. Nothing else comes close - `CREATE TABLE` is 56533, `ALTER` 35978, `SYSTEM`
32086 - and they overlap too much to be worth an option each.
Two weeks of master, and six files needed a decision:

* `ASTTablesInSelectQuery.cpp` - master rewrote the ON-clause paren logic and no
  longer calls `getTreeHash` while formatting, which is exactly what my change
  was avoiding. Took master's version and dropped mine.
* `ErrorCodes.cpp` - master added an error code (`END` 1009 -> 1010) right where
  the minimal-build guard begins.
* `InterpreterSystemQuery.cpp` - master added `STOP/START/... ALL BACKGROUND`
  cases immediately after `TEST_VIEW`, which my change had wrapped in a block.
* `MergeTreeDataSelectExecutor.cpp` - master added two includes next to the one
  swapped for `parseIdentifiersOrStringLiteralsWithSettings.h`; it still uses the
  `Settings`-taking overload, so the swap stands.
* `ASTAlterQuery.cpp` - master added an include next to the unused
  `Core/ServerSettings.h` this branch removes. Master does not use it either.
* `QueryFuzzer.cpp` - two unrelated includes.

The other 27 files master had also touched merged cleanly.
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4d55779]

Summary: ✅


AI Review

Summary

This PR makes the SQL parser buildable on its own, moves some validation out of src/Parsers, and adds the standalone WebAssembly build. The overall direction looks sound, but two SETTINGS carriers still break the promised invariant that a valueless setting on a non-Bool name is rejected consistently across all supported paths.

Findings

❌ Blockers

  • [src/Parsers/ASTSetQuery.cpp:217,277] ASTSetQuery preserves shorthand in memory and in the tree hash, but writeJSON / readJSON still serialize only {name, value}. A query like SELECT 1 SETTINGS max_threads therefore round-trips through parseQueryToJSON / formatQueryFromJSON or the clickhouse_json dialect as an explicit max_threads = true, which reopens the silent-acceptance bug this PR is supposed to close on that supported carrier. Serialize shorthand and restore it in readJSON, or reject valueless settings on the AST-JSON path instead.

⚠️ Majors

  • [src/Parsers/ASTSetQuery.cpp:353] ASTSetQuery::formatImpl now knows that a valueless setting carries Field(true) plus shorthand = true, but hasSecretParts still unconditionally safeGet<String>() for format_avro_schema_registry_url. executeQueryImpl calls out_ast->hasSecretParts() before settings validation, so SELECT 1 SETTINGS format_avro_schema_registry_url can now fail in the query-logging/secret-detection path instead of reaching the intended TYPE_MISMATCH rejection. hasSecretParts needs the same shorthand guard as the formatter.
Tests
  • ⚠️ Add a focused regression for formatQueryFromJSON(parseQueryToJSON('SELECT 1 SETTINGS max_threads')) and for executing the same JSON under dialect = 'clickhouse_json', so the shorthand marker cannot be dropped silently again.
  • ⚠️ Add a regression for SELECT 1 SETTINGS format_avro_schema_registry_url to prove the query reaches the valueless-setting check rather than failing while probing hasSecretParts().
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: preserve or explicitly reject SettingChange::shorthand on the AST-JSON path, and make ASTSetQuery::hasSecretParts ignore shorthand settings instead of dereferencing them as concrete typed values.

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Jul 27, 2026
…rsers

Brotli is what a browser actually negotiates, and it is 24% better than gzip on
this module - 273666 bytes for the full build, 188219 with formatting and DCL
left out.

The comparison is worth having in writing because it does not flatter us:
`@clickhouse/parser`, the TypeScript one, is smaller than this at every setting
(153347 brotli, bundled with `zod` and minified). What this build offers instead
is the server's own grammar rather than a second implementation of it.
`libpg-query` is the row that matters: PostgreSQL's own parser compiled to
WebAssembly rather than reimplemented, which is the same idea as this. With its
emscripten glue it comes to 183463 brotli against this build's 188219 - close
enough to say the approach costs what it costs, and that there is no large win
left in the grammar itself.

The two JavaScript parsers are smaller and are both reimplementations;
`node-sql-parser` is the smallest per dialect and covers the least. `sql.js` is a
whole SQLite rather than a parser and is here for scale - it is the one entry
smaller than this uncompressed and larger after compression.
…nitialized

`Build (arm_tidy)` failed on every translation unit that reaches `Parsers/InlineVector.h`:
`cppcoreguidelines-pro-type-member-init` wants the defaulted constructor to initialize `inplace`,
which is exactly what it must not do - only the first `count` elements are ever read, and not
zeroing the rest is the whole point of keeping them inline. Marked `NOLINT` with the reason.

Also `<memory>` was included where `<new>` is what `::operator new` comes from.
`Generator.cpp` uses `std::views::keys` and relied on `<ranges>` arriving transitively, which
`_LIBCPP_REMOVE_TRANSITIVE_INCLUDES` does not allow once the includes it came through are trimmed.
It is compiled as part of `ninja clickhouse`.
Deferring the "is this a Bool setting?" question from the parser to `BaseSettings::applyChange`
left the check unreachable for a query's own settings: `Context` applies them through
`Context::setSetting`, which takes a name and a value and never sees `SettingChange::shorthand`.
So `SET max_threads` silently became `max_threads = 1` - exactly the outcome the marker exists to
prevent - and `03623_setting_boolean_shorthand_err_test` failed in `Fast test`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112067&sha=f17a8044a81eafb7cdf33689820d5d31b0876465&name_0=PR&name_1=Fast%20test

The check now runs wherever a whole `SettingChange` is available: `BaseSettings::applyChange` as
before, plus `Context::applySettingChange` and `Context::checkSettingsConstraints`. The constraint
check has to be covered too, because it converts the value to the setting's type first and would
otherwise report the type error as `BAD_GET` from a layer that cannot explain it - which is what
`SET default_database_engine` did.

The test gains the two cases that only the wrong-layer report would have hidden: that a rejected
shorthand leaves the setting at its previous value rather than at 1, and that `SETTINGS` in a
query is checked the same way. The latter uses `{ error ... }` rather than `{ serverError ... }`
because the client applies a query's `SETTINGS` to its own context and rejects it before sending.
Moving the "a valueless setting must be a `Bool`" check out of the parser and into `BaseSettings`
leaves the consumers that keep a raw `SettingsChanges` unguarded. Of those, per-column MergeTree
settings are genuinely reachable: `MergeTreeColumnSettings::validate` only calls `checkCanSet`, so
with the check gone `CREATE TABLE t (x UInt64 SETTINGS (min_compress_block_size))` would have been
accepted and stored `min_compress_block_size = 1`, where before it was a syntax error. Column level
allows only numeric settings, so the shorthand can never be valid there - `ParserColumnDeclaration`
now parses the settings with `shorthand_syntax` off, which restores the old behavior exactly.

Named collections are not affected: they parse their pairs with `ParserSetQuery::parseNameValuePair`,
which requires the `=` token and never sets `shorthand`, so `CREATE NAMED COLLECTION nc AS a` is a
syntax error both before and after this pull request.
`SettingChange::shorthand` was load-bearing but invisible to everything downstream of the parser:
`ASTSetQuery::formatImpl` wrote a valueless change back as `name = true`, so any path that formats
and re-parses a query - parameter substitution, sending a query on to another server - turned it
into an explicit assignment and the type check was skipped again. Formatting now keeps the
valueless form, and `shorthand` takes part in `SettingChange` equality and in the `ASTSetQuery`,
`QueryNode` and `TableFunctionNode` tree hashes, so a shorthand change is no longer interchangeable
with an explicit `= true`. Test: `04653_valueless_setting_format_roundtrip`.
* The `size_t` explicit instantiations in `iota` were guarded by
  `defined(OS_DARWIN) || !defined(__LP64__)`, which is too broad. On an ordinary ILP32 target
  `size_t` is `unsigned int`, i.e. exactly `UInt32`, so the `size_t` instantiation collapses onto
  the `UInt32` one and the translation unit fails with a duplicate explicit instantiation. `size_t`
  is a distinct type only where it is `unsigned long` - Darwin and WebAssembly - so it needs a
  narrower condition than `long` does. A pair of `static_assert`s now pins the assumption in both
  directions, so a platform where it stops holding fails to compile with a clear message instead of
  silently losing or duplicating the instantiation.

* Instead of repeating the platform condition at every use site, define `LONG_IS_A_DISTINCT_TYPE`
  and `SIZE_T_IS_A_DISTINCT_TYPE` in `base/defines.h` and use them in `itoa` and `iota`.

* Combine the `CLOCK_MONOTONIC_COARSE` fallbacks in `base/time.h` into a single block: the Darwin
  and SunOS cases are subsumed by the generic fallback to the precise clock, so only FreeBSD's
  `CLOCK_MONOTONIC_FAST` needs a case of its own.
`__cxa_allocate_exception` returned `char` storage, which need not be aligned for the object
constructed in it, and `__cxa_throw` reinterpreted every thrown object as a `Poco::Exception` -
including `std::bad_alloc`, the one case the comment above it named. The storage is now
`alignas(std::max_align_t)`, and the `std::type_info *` argument decides: exactly `DB::Exception` is
read as such, anything else reports its type name and nothing more.
`03365_time_timezone_issue` failed in `Fast test`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112067&sha=f17a8044a81eafb7cdf33689820d5d31b0876465&name_0=PR&name_1=Fast%20test

`INSERT INTO t VALUES (36610.111::Decimal32(3))` into a `Time64(3)` column reported
`Type mismatch in IN or VALUES section. Expected: Time64(3). Got: Decimal32`.

The parser records the query position of every literal it builds, keyed by the literal's address, so
that `ValuesBlockInputFormat` can turn one row's expression into a template for the rest.
`parseDataTypeAsText` parses a type and keeps only its text, which frees the literals inside the
type - the `3` of `Decimal32(3)` - while their entries stay in the map. `CAST` carries its type as a
string, so the two literals the cast operator builds next land on those freed addresses and inherit
their token positions. The deduced template then replaced the `3` rather than the value:

    '36610.111', '::', 'Decimal32', '(', Nullable(String), ')'

which cannot parse, so every row fell back to single-expression evaluation - and that path converts
through `convertFieldToType`, which has no `Decimal32` to `Time64` conversion, while the template
path casts as a function and does.

`LiteralTokenMap::forget` makes a recorded literal unfindable again - by recording an empty range,
so probing still stops at the first empty slot and there are still no tombstones - and
`parseDataTypeAsText` forgets the literals of the type AST before letting it go. Recording positions
and discarding subtrees are both ordinary things for a parser to do, so whoever does the second has
to undo the first.

Tests: `04654_cast_operator_values_template`, and `LiteralTokenMap.ForgetHidesAnEntry`.
# Conflicts:
#	src/Parsers/ASTColumnsTransformers.cpp
#	src/Parsers/ASTCreateQuery.cpp
#	src/Parsers/ASTSetQuery.cpp
Three semantic conflicts the textual merge could not see:

* `ASTSQLSecurity::formatImpl` lives in `ASTSQLSecurity.cpp` on this branch (the ODR
  cleanup), while master added the same file with only the JSON methods - restore the
  formatter next to them.
* `SYSTEM ... SET FAKE TIME` keeps its literal as a string on this branch instead of a
  `DateLUT`-parsed number, so `fake_time_for_view` is written and read as a JSON string.
* Style check 19 (no `catch` in `src/Parsers`) exempts the AST JSON deserialization:
  it maps Poco JSON exceptions to `BAD_ARGUMENTS` at the boundary and is not a parser
  of SQL text, and nothing in it is on the standalone parser's call graph.
…N` does

`TableFunctionExplain` reparsed the serialized settings string with the shorthand
syntax enabled, so `SELECT * FROM viewExplain('EXPLAIN SYNTAX', 'query_tree_passes',
(SELECT 1))` silently ran with `query_tree_passes = 1`:
`InterpreterExplainQuery::checkAndGetSettings` reads the `Field(true)` a shorthand
stands for as `UInt64(1)`. Parse with `ParserSetQuery(parse_only_internals_ = true,
shorthand_syntax_ = false)`, exactly as `ParserExplainQuery` does for `EXPLAIN` itself.

#112067
…or change

An invalid pattern in `GRANT ... ON URL('...')` is no longer compiled by the parser:
it is rejected by the interpreter with `CANNOT_COMPILE_REGEXP` instead of a syntax
error, as described in the pull request.

Failed in CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112067&sha=37a51fa000d84c9b4cc0b2ef616e0f211d0b8b4d&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
#112067
…rallel

The flaky check runs the test concurrently with itself, and the fixed `user_04661`
name made the runs drop each other's user (`UNKNOWN_ROLE` on `GRANT`, `UNKNOWN_USER`
on `DROP`). Suffix the user with the test database name, which is unique per run.

#112067
The test covers the analyzer's peel of `limit`/`offset` from a subquery's `SETTINGS`
clause; the old analyzer applies them differently, so the with-a-value section
diverged on the old-analyzer CI configuration.

#112067
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)
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The gap noted above is closed: be78590 ports the exception recovery boundary from parser-standalone-build (ebca121 + 905c264 + 6c4bdae, with the test) — __cxa_throw now returns to a setjmp boundary armed by ch_check and ch_format instead of aborting, gated on the thrown type being exactly DB::Exception.

Also in this push: the branch is merged with current master (the AST JSON serialization needed three semantic reconciliations — ASTSQLSecurity::formatImpl restored next to the JSON methods, fake_time_for_view as a JSON string, and a check-19 exemption for the JSON deserialization's Poco::Exception mapping), the viewExplain shorthand bypass from the review is fixed with test 04662, and the three CI reds are addressed: 03595 updated for the deliberate CANNOT_COMPILE_REGEXP change, 04661 made parallel-safe, 04655 pinned to the analyzer whose peel path it covers.

Note the WebAssembly build itself cannot be verified in this environment (no network for wasi-sdk); the ported runtime code is verbatim from the sibling branch where it was built and reviewed.

Comment thread src/Parsers/ASTSetQuery.cpp Resolved
alexey-milovidov and others added 2 commits July 31, 2026 06:26
#111994

Some engines read the `SETTINGS` clause of their definition directly from
`ASTStorage::settings->changes` instead of applying it to a `BaseSettings`
schema, so nothing rejected the value-less form `SETTINGS name` for them:
`Join` silently turned `SETTINGS max_rows_in_join` into `max_rows_in_join = 1`,
and the String readers (`disk`/`storage_policy` of the Log family,
`keeper_path` of the queue engines) reported `BAD_GET` from `safeGet` at the
wrong layer. Ported from `parser-standalone-v3` (#111994):

* a `BaseSettingsHelpers::throwValuelessSettingIsNotBool` overload for callers
  that have no type name to report, and `SettingsChanges::tryGetChange` for
  consumers that also have to look at `shorthand`;
* guards in `registerStorageJoin`, `getDiskName` of the Log family, and
  `createQueueStorage`;
* `InterpreterSetQuery::applySettingsFromQuery` checks the shorthand before
  the constraint check converts the value, and moves the change to the context
  through `applySettingChange` so the `shorthand` flag is not dropped;
* tests `04663_setting_boolean_shorthand_in_create_settings` and
  `04664_setting_boolean_shorthand_raw_engine_settings`.

This makes #112067's containment of #111994 complete.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ressions they replaced

The PR description relied on the hand-written scans agreeing with the old
regular expressions on 200000 randomized strings, but that comparison lived in
a throwaway harness - the committed `gtest_mask_uri_password.cpp` only
iterated a fixed corpus, so the fuzz coverage would not survive future edits
to the scans. The randomized cross-checks are now part of the test:
`maskURIPassword` over 200000 strings of the characters its regular
expression assigns meaning to, and `maskURIUserinfo` /
`maskPresignedURLParameters` over 50000 strings built from the tokens theirs
care about, all with a deterministic seed so a failure is reproducible.

#111994 (comment)
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Ported the last pieces of #111994 that were missing here, so its containment is now complete:

  • efb8f9ef686 — value-less SETTINGS name guards for engines that read ASTStorage::settings->changes directly, with no settings schema to reject the shorthand: Join silently turned SETTINGS max_rows_in_join into max_rows_in_join = 1, and the String readers (disk/storage_policy of the Log family, keeper_path of the queue engines) reported BAD_GET from safeGet at the wrong layer. Also moves query settings from a CREATE's SETTINGS clause to the context through applySettingChange, so the shorthand flag is not dropped on that path. Tests 04663, 04664.
  • 4d557798a80 — the randomized cross-check of maskURIPassword / maskURIUserinfo / maskPresignedURLParameters against the regular expressions they replaced is now part of the committed gtest_mask_uri_password.cpp (200000 / 50000 strings, deterministic seed), addressing the review point on Build the SQL parser standalone: cut abseil, cctz, re2, boost, locale and the settings schema #111994 that it lived only in a throwaway harness.

Verified locally: ninja clickhouse and unit_tests_dbms green, all masking gtests pass, and every statement of 04663/04664 gives the expected result under clickhouse local.

Comment thread src/Parsers/ASTSetQuery.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.60% 78.70% +0.10%

Changed lines: Changed C/C++ lines covered: 1230/1394 (88.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f8a3689d-7e8a-46c8-867d-806189938b95
  • MIRAI run: e5ec058d-2eac-4850-b0dd-b614b1cbde4b
  • PR check IDs:
    • clickbench_1132859_1785516120
    • clickbench_1132961_1785516131
    • clickbench_1133062_1785516141
    • tpch_adapted_1_official_1133191_1785516171
    • tpch_adapted_1_official_1133324_1785516208
    • tpch_adapted_1_official_1133581_1785516379

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Read all the code - all good, plus it improves the code in general and fixes many bugs 👍

In follow-up PRs, I'd like to move the WASM parser build into either CMake or an integration test, move the JavaScript tests to integration test as well, find out if we can get rid of system header "shims", and add a test asserting some threshold on the compiled parser size.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 This PR is merged (a208bbb94ab), but the AI Review verdict left two items unaddressed. Both are real — I reproduced them on master — and both are now fixed in a follow-up: #112902

  • Blocker, ASTSetQuery.cpp:217,277 — writeJSON / readJSON dropped SettingChange::shorthand, so SELECT 1 SETTINGS max_threads round-tripped into an explicit max_threads = true and executing that payload under dialect = 'clickhouse_json' ran with max_threads = 1instead of failing withTYPE_MISMATCH. The flag is now serialized and restored, and a payload pairing it with anything other than trueis rejected withBAD_ARGUMENTS(otherwise the flag could hide a real value — a secret one in particular — fromformatImplandhasSecretParts`, both of which skip a valueless setting's value).
  • Major, ASTSetQuery.cpp:353 — hasSecretParts unconditionally did safeGet<String> for format_avro_schema_registry_url. The top-level form is validated before the masking path is reached, but a subquery is not: SELECT * FROM (SELECT 1 SETTINGS format_avro_schema_registry_url) gave BAD_GET: has Bool, requested String. It now reports the intended TYPE_MISMATCH.

Both requested regressions are in the new test 04665_valueless_setting_ast_json_and_secret_parts, including the formatQueryFromJSON(parseQueryToJSON(...)) round trip, executing the same JSON under the clickhouse_json dialect, and the format_avro_schema_registry_url cases. Both review threads replied to and resolved.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 2, 2026
`SETTINGS name` with no value is a shorthand for `= true` and is rejected for
a setting whose type is not `Bool`. Two paths sidestepped that rule.

`ASTSetQuery::writeJSON` did not serialize `SettingChange::shorthand` and
`readJSON` did not restore it, so the `clickhouse_json` dialect reconstructed
the valueless form as an explicit `name = true`, which is accepted for a
setting of any type: `parseQueryToJSON('SELECT 1 SETTINGS max_threads')`
round-tripped into a query that ran with `max_threads = 1` instead of failing
with `TYPE_MISMATCH`. The flag is now written and read back, and a payload
pairing it with anything other than `true` is rejected, so it cannot be used
to hide a real value - a secret one in particular - from `formatImpl` and from
`hasSecretParts`, both of which skip the value of a valueless setting.

`ASTSetQuery::hasSecretParts` read the value of
`format_avro_schema_registry_url` with `safeGet<String>`. `executeQueryImpl`
masks the query for logging before any settings validation runs, so a valueless
setting reached it as Bool `true` and
`SELECT * FROM (SELECT 1 SETTINGS format_avro_schema_registry_url)` reported
`BAD_GET` instead of the intended `TYPE_MISMATCH`. A valueless setting is now
skipped there as well.

Follow-up to the review comments left on
ClickHouse#112067
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.

2 participants