Repository navigation
Build the SQL parser standalone: cut abseil, cctz, re2, boost, locale and the settings schema - #111994
Build the SQL parser standalone: cut abseil, cctz, re2, boost, locale and the settings schema#111994alexey-milovidov wants to merge 25 commits into
Conversation
…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]>
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]>
Six conflicts, all mechanical except one: * `Common/ErrorCodes.cpp` - master's `END = 1010` alongside this branch's `CLICKHOUSE_PARSER_MINIMAL_BUILD` guard around `values`. * `Common/QueryFuzzer.cpp`, `Parsers/ASTAlterQuery.cpp`, `MergeTree/MergeTreeDataSelectExecutor.cpp` - include-list conflicts; master's new `Databases/DataLake/DataLakeConstants.h`, `Core/UUID.h` and `Parsers/IAST(Hash).h` kept next to this branch's removals and its move of `parseIdentifiersOrStringLiteralsWithSettings`. * `Interpreters/InterpreterSystemQuery.cpp` - master's new `*_ALL_BACKGROUND` cases next to the scope this branch put around the `SET FAKE TIME` case. * `Parsers/ASTTablesInSelectQuery.cpp` - master's rewrite of the aliased `ON` formatting is taken as is. It reaches the same end this branch was after, and more directly: the wrap is now decided by `frame.need_parens` alone, so `getTreeHash` is not called at all and `Parsers/IASTHash.h` is out of the file.
`programs/keeper-bench/Generator.cpp` uses `std::views::keys` while relying on `<ranges>` arriving transitively. The build defines `_LIBCPP_REMOVE_TRANSITIVE_INCLUDES`, so trimming includes elsewhere is enough to break it, which merging master into this branch did.
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 on three of its four cases.
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.
The README described the module as it was in the first commit of this series: 2.7 MB with abseil, re2 and cctz in it, requiring an engine that implements the WebAssembly exception-handling proposal, and shimming `Settings::castValueUtil` to keep the settings schema out. None of that is true any more - it is 1.6 MB, needs no flags, and the settings schema left the parser's closure for good rather than being shimmed away. Also: * `build.sh` no longer swallows compilation failures. It piped the compilers' output through `grep error: | head -20 || true`, so a translation unit that failed to compile was printed and then ignored, and the link picked up whichever objects a previous run had left in place. Each object is now removed before its compiler runs, and a failure stops the build. * `wasm_runtime.cpp` no longer defines `Settings::castValueUtil`. Nothing references it since `ParserSetQuery` stopped consulting the settings schema.
The cherry-picked README described the module as it was before the last two commits of the series: `-Os`, 1.6 MB, 463 KB gzipped. With `-Oz`, full LTO and `-fvirtual-function-elimination` it is 1.17 MB, 362 KB gzipped, 273 KB brotli, over 320 translation units. Also names all three layers that now check the valueless `SET` shorthand, not just `BaseSettings::applyChange`.
|
Workflow [PR], commit [d535907] Summary: ❌
AI ReviewSummaryThis PR strips heavy transitive dependencies out of Tests
Final Verdict
|
| -D_WASI_EMULATED_PROCESS_CLOCKS -D_WASI_EMULATED_GETPID | ||
| -DCLICKHOUSE_PARSER_MINIMAL_BUILD | ||
| -DFMT_USE_LOCALE=0 | ||
| -fignore-exceptions |
There was a problem hiding this comment.
-fignore-exceptions is not sound with the current parser surface. tryParseQuery never catches, and parsers still throw on ordinary malformed input, not just on bugs or resource exhaustion: for example ParserColumnsTransformers throws SYNTAX_ERROR for an invalid APPLY lambda, and IParser::Pos::operator= throws when backtracking exceeds the limit.
In the standalone runtime __cxa_throw aborts, so those queries kill the wasm module instead of making ch_format return 0 with an error message. For the browser use case that turns user typos into a hard failure. This needs either real exception support in the standalone build, or a no-throw entrypoint that translates all parser exceptions into parse failures.
There was a problem hiding this comment.
Correct that the justification was wrong: IParser::Pos::operator= throws TOO_SLOW past the backtracking limit and increaseDepth throws TOO_DEEP_RECURSION, both of which ordinary input reaches - those limits exist precisely for user input - so it is not true that an exception can only mean a bug or a resource exhaustion internal to the build.
What is fixed in 2137660: __cxa_throw now records the message in a fixed buffer (it must not allocate - the throw may be std::bad_alloc) and exports it as ch_error_data/ch_error_size, and it uses __builtin_trap instead of std::abort, so control returns to the embedder with linear memory intact instead of possibly ending the WASI process. The contract is documented in the README: on a trap, read the message, drop the instance, instantiate again (the module is compiled once; instantiating is cheap, and the allocator was interrupted mid-operation so the instance must not be reused).
What is not fixed: making those queries return 0 from ch_format instead of trapping needs real unwinding, i.e. -fwasm-exceptions plus a catch. That costs bundle size and requires the engine to implement the exception-handling proposal, which this build deliberately avoids. It is a trade-off, not an oversight, so it is now stated in the README rather than misstated - and left for @alexey-milovidov to decide.
There was a problem hiding this comment.
Fixed on the superseding #112067 (parser-standalone-v4): commit be78590 ports the recovery boundary from #111971 — a setjmp boundary armed by ch_check and ch_format, with __cxa_throw recovering only for DB::Exception (anything else still traps), built with -mllvm -wasm-enable-sjlj. A parser throw on malformed input (e.g. ROWS BETWEEN UNBOUNDED FOLLOWING AND CURRENT ROW) now reports the error instead of killing the module instance. This branch is superseded, so the fix is not duplicated here.
… macros Review feedback on the predecessor PR #111952 (`Algunenano`, `clickhouse-gh`), which applies verbatim to this branch: * 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.
…mn level Review feedback from `clickhouse-gh`: 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. The other half of the finding does not reproduce: named collections 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.
Review feedback from `clickhouse-gh`: the claim that an exception in this build can only mean a bug or a resource limit is wrong. `IParser::Pos` throws `TOO_DEEP_RECURSION` and `TOO_SLOW` when a query exceeds the depth or backtracking limit that `ch_format` passes, and a handful of parsers throw on input they have already committed to, so ordinary input reaches `throw` - and with `-fignore-exceptions` that took the module down with no message reaching the caller. Recovering from those without unwinding is not possible, but losing the message is. `__cxa_throw` now records it in a fixed buffer - it must not allocate, the throw may be `std::bad_alloc` - and exports it as `ch_error_data`/`ch_error_size`. It also uses `__builtin_trap` instead of `std::abort`, so control returns to the embedder with linear memory intact rather than possibly ending the WASI process. The README states the contract: on a trap, read the message, drop the instance, instantiate again. Making such queries return an error instead of trapping needs real unwinding - `-fwasm-exceptions` plus a `catch` in `ch_format` - which costs bundle size and an engine that implements the exception-handling proposal. That trade-off is left as it is, and now documented rather than misstated.
…nd make the wasm shim type-safe Two blockers from the AI review. `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 WebAssembly exception shim was not ABI-safe: `__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.
|
A note on the relationship with #111971 ( Comparing each branch's changed-file set against its own merge base, eleven files exist only on #111971 - So neither is a superset. Whichever is kept should take the other's part. |
One conflict, in `src/Parsers/FunctionSecretArgumentsFinder.h`: master moved the whole implementation out of the header into a new `FunctionSecretArgumentsFinder.cpp` while rewriting the S3 secret masking. Master's version of the header is taken as is, and this branch's part - keeping the parser free of `re2` and `boost::algorithm` - is re-applied to the new `.cpp`: * `boost::iequals` becomes `equalsCaseInsensitive`. * The Azure connection-string patterns become `maskConnectionStringKey`, as before. * The two new regular expressions in `maskS3URICredentials` become `maskURIUserinfo` and `maskPresignedURLParameters` in `Common/maskURIPassword.h`. This is masking of secrets, so `gtest_mask_uri_password.cpp` checks both scans against the expressions they replace over a corpus that covers the leftmost-match and greediness edges. Without this the standalone build would not link: `utils/wasm-parser` compiles all of `src/Parsers/*.cpp` and links no `re2`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ze `inplace` `cppcoreguidelines-pro-type-member-init` flagged both constructors, since `inplace` is the one member without a default initializer. It is deliberate - the array is scratch space and only the first `count` elements are ever read - so the two constructors get a `NOLINT` and the reason is written down next to them. https://github.com/ClickHouse/ClickHouse/actions/runs/30326667549/job/90173621556 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…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.
(cherry picked from commit 6a0d694)
…ead the change directly `BaseSettings::applyChange` checks the shorthand against the settings schema, and the previous commit extended that to the `CREATE ... SETTINGS` split, but some engines never apply their settings to a `BaseSettings` at all - they read `ASTStorage::settings->changes` themselves, where there is no schema. `Join` is the case that failed silently: `SettingFieldNumber::operator=(const Field &)` converts the synthetic `Bool(true)` to `1`, so `ENGINE = Join(...) SETTINGS max_rows_in_join` became `max_rows_in_join = 1`. The String-valued readers - `disk` and `storage_policy` of the Log family, `keeper_path` of the queue engines - reported the shorthand as a `BAD_GET` from `safeGet` at the wrong layer. Each of those consumers now rejects the shorthand for the settings it knows are not Bool, through a new `BaseSettingsHelpers::throwValuelessSettingIsNotBool` overload for callers that have no type name to report, and `SettingsChanges::tryGetChange` for the ones that need the change rather than its value. `04663` covers both shapes, including that the Bool ones still accept the shorthand. `04662`'s reference is adjusted for this branch: the formatter keeps the value-less form, so `engine_full` shows `SETTINGS ttl_only_drop_parts` rather than `ttl_only_drop_parts = true`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
|
||
| } | ||
|
|
||
| TEST(MaskURIPassword, MatchesTheRegularExpressionItReplaced) |
There was a problem hiding this comment.
The PR description explicitly relies on gtest_mask_uri_password.cpp proving agreement with the old regex on 200000 randomized strings, but the committed test only iterates a small fixed corpus. For secret-masking code that is supposed to be behavior-preserving, that is materially weaker evidence: a credential-leaking edge case can still ship as long as it is not in this list. Please either add the randomized/property loop the description refers to, or tone the claim down to match the actual coverage.
There was a problem hiding this comment.
Agreed — the randomized comparison lived only in a throwaway harness. It is now part of the committed test on the superseding #112067 (commit 4d55779): maskURIPassword is cross-checked against the regular expression on 200000 random strings over its meaningful characters, and maskURIUserinfo/maskPresignedURLParameters on 50000 token-built strings, all with a deterministic seed so a failure is reproducible. This branch is superseded, so the fix is not duplicated here.
#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)
|
Status: this PR is superseded by #112067 (
Both unresolved review threads here are addressed on #112067 (replies on the threads). Nothing on this branch remains unported; closing it in favor of #112067 is the author's call. Related: #112067 |
Supersedes #111986,
#111971 and
#111952 — all three are contained here and can be
closed.
How small does
src/Parsersget when built on its own?utils/wasm-parseranswers it: a buildscript, a five-function C interface and a test, producing a 1.17 MB WebAssembly module (362 KB
gzipped, 273 KB brotli) 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 todayships only the lexer.
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>andCore/Settings.hare all gone fromthe parser's transitive closure.
SYSTEM ... SET FAKE TIMEwas parsedand formatted through
DateLUT. Which timezone applies belongs to the server, not the querytext, so the AST keeps the literal and the interpreter resolves it.
(
maskURIPassword, Azure connection strings); the third compiledCOLUMNS('regexp')patternsinside
IASTColumnsTransformer::transform, which is name resolution rather than parsing andmoves to
Interpreters/applyColumnsTransformer.cpp. Validating aGRANT ... ON S3('...')pattern moves to
InterpreterGrantQuery.<locale>in.boost::to_loweris locale-based, andAccessType.hreached<ostream>throughboost/algorithm/string/split.hpp. Poco'sBugcheck::whatbuilt one message with anostringstream, and sinceBugcheck.harrives viaPoco/Foundation.h, that single include wasworth 181 KB.
ParserSetQueryconsulted the settings schema for one thing - whether a bareSET xnames aBool setting. It records that the value was omitted and
BaseSettings::applyChangechecks thetype, 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/Parserscontains nocatch, and a style check keeps it thatway. That lets the standalone build use
-fignore-exceptions, worth 262 KB and the need for anengine implementing the exception-handling proposal.
Costs that were not the parser
abi::__cxa_demanglewas 132 KB, reached only to put a type name in an exception message.ErrorCodes::valueswas 150 KB of data - the per-code statistics behindsystem.errors.IAST::setAlias's "this node does not take an alias" error message namedgetColumnName()andgetID(), and that unreachable throw was the only thing in the parser naming either, keeping anoverride of both alive in all ~150 AST classes.
Latent bugs found on the way
ASTSQLSecurity::formatImplwas defined identically in two translation units. Static-librarylinking never pulls both objects in, so the ODR violation stayed invisible.
Poco/Util/Application.hwas included but unused byDumpASTNode.h, which reachesPoco::ThreadPooland arrives viaInDepthNodeVisitor.h- over sixty translation units paid.uzliteral that does not fit a 32-bitsize_t, aProfileEventscounter/increment size mismatch, a Booststored_sizeconstraint inASTs, anditoa/iotaguarding theirlongoverloads onOS_DARWINwhen the real condition is thatlongis a distinct type.Optimizing for size
The standalone build uses
-Oz, full LTO and-fvirtual-function-elimination. The last of thoseneeds 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.
-Ozover-Osis worth 19% of the module. Most of the size is inlining rather than templateinstantiation: attributing every symbol to the template that owns it puts
std::vector's memberfunctions at 42 KB and
std::string's at 5 KB, the latter being that small only because stringoperations are inlined into their callers and never emitted as string symbols at all.
-Ozcostsabout 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 namedgetColumnName()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/emplacesequences, compiling to a 57 KB constructor - the largest function in the parser - and costing 645
string allocations per process. It is a
constexpr std::arraynow, and the two consistency checksthe constructor performed became
static_asserts, so they also run in release builds. The twoAccesstables get the same treatment. Everythrow()exception specification inbase/pocoisnow
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.cppchecks 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.cppcovers overwriting, growth past the inline storage, and agreementwith
std::unordered_mapover 500 randomised rounds.User-visible changes, all deliberate:
SET max_threadsreports TYPE_MISMATCH from the server rather than a syntax error from theclient (03623 updated). It does not silently become
max_threads = 1, which is whatdeferring the check without a marker would have done.
GRANT ... ON S3('[')pattern reports CANNOT_COMPILE_REGEXP instead of a syntaxerror. It cannot simply be dropped: the pattern is matched with
RE2::FullMatch, so one thatdoes not compile would grant nothing, silently.
SYSTEM ... SET FAKE TIMEechoes its literal instead of renormalising it when formatted.user@hostwith nopassword is no longer rewritten to
user:[HIDDEN]@host, since there is nothing to hide.IAST::setAlias's error message shows the offending node instead of its kind.One item is no longer part of this branch:
ASTTableJoin::formatImplhashed every aliasedONexpression and discarded the answer unless the old analyzer's
collapse_identical_nodes_to_aliaseswas set. Master has since replaced that whole block withframe.need_parens(Remove unnecessary parens special cases left after #92340), which does nothash at all, so the merge takes master's version.
Verified with a full
dbmsbuild, the whole ofcheck_cpp.sh, and the standalone build's testsuite at every step.
Changelog category (leave one):
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-parserfor 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