Repository navigation
Fix quadratic parsing of nested literals, grouped tuples and multi-statement scripts - #133041
Algunenano wants to merge 7 commits into
Conversation
…t input Check that `::` follows a collection before reading it as cast text, and remember brackets where a literal reading failed, so enclosing levels do not rescan them. Move nested literal values when folding brackets instead of copying them, and stop the unmatched-parentheses walk after the current statement. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…uples Take the text of a collection cast from the query when it is written as the text reader expects, instead of scanning it again. Fold a tuple literal in grouping brackets as a whole instead of splitting it into elements at every level. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The parser reads tokens that are already lexed far more often than it lexes new ones, and each read paid for a call with the frame and stack protector of the lexing loop. Keep the lexing loop out of line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [512a1e1] Summary: ❌
AI ReviewSummaryThe PR reduces repeated literal scans, collection copies, and bracket walks during parsing. No actionable findings at Missing context / blind spots
Final VerdictStatus: ✅ Approve |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Commit See the job log for details. |
Under TSan only 5% of the stack is allowed, and depth 300 exceeded it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=11 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
This reverts bf6b05d, which made `ParserCastOperator` scan a literal collection without building its text and build it only when `::` follows. ClickHouse#133041 rewrites the same scan: it checks for `::` before building the text and also remembers the brackets where a reading failed. Both changes edit `scanCollectionOfLiteralsAsText` and `ParserCastOperator::parseImpl`, so they conflict, and ClickHouse#133041 covers this part. What stays is the independent change to `ParserCollectionOfLiterals`: numbers and strings go straight to `ParserNumber` and `ParserStringLiteral`. It merges with ClickHouse#133041 without conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The post-parse Server-side query time from
The perf-test queries ran with the test's settings, 60 pairs each. The IN rows are Patch (src/Parsers/parseQuery.cpp, on top of this PR)diff --git a/src/Parsers/parseQuery.cpp b/src/Parsers/parseQuery.cpp
index afdc5d99e95..593e7a49142 100644
--- a/src/Parsers/parseQuery.cpp
+++ b/src/Parsers/parseQuery.cpp
@@ -524,11 +524,40 @@ ASTPtr tryParseQuery(
IParser::Pos set_lookahead(token_iterator);
const bool committed_to_set = parser.consumesRawText() && isCommittedToSetQuery(set_lookahead);
const bool consumes_raw_text = parser.consumesRawText() && !committed_to_set;
+ /// The walk below visits every token of the statement anyway, so it also matches the brackets. If they match up
+ /// to the first `;` (or the end), `checkUnmatchedParentheses` after the parse would find nothing: it walks the
+ /// same tokens and stops at that `;` unless the parse looked past it. Then the second walk is skipped.
+ bool brackets_match = false;
+ const char * walked_until = nullptr;
if (consumes_raw_text || !ParserKeyword(Keyword::INSERT_INTO).ignore(lookahead))
{
- while (lookahead->type != TokenType::Semicolon && lookahead->type != TokenType::EndOfStream)
+ std::vector<TokenType> open_brackets;
+ bool brackets_valid = true;
+ while (true)
{
- if (lookahead->isError() && (!consumes_raw_text || lookahead->type == TokenType::ErrorMaxQuerySizeExceeded))
+ /// Look the token up once: every access of the token stream also tracks the furthest position.
+ const Token & token = *lookahead;
+ if (token.type == TokenType::Semicolon || token.type == TokenType::EndOfStream)
+ {
+ walked_until = token.begin;
+ break;
+ }
+
+ if (token.type == TokenType::OpeningRoundBracket || token.type == TokenType::OpeningSquareBracket)
+ {
+ open_brackets.push_back(token.type);
+ }
+ else if (token.type == TokenType::ClosingRoundBracket || token.type == TokenType::ClosingSquareBracket)
+ {
+ const auto opening = token.type == TokenType::ClosingRoundBracket ? TokenType::OpeningRoundBracket
+ : TokenType::OpeningSquareBracket;
+ if (!open_brackets.empty() && open_brackets.back() == opening)
+ open_brackets.pop_back();
+ else
+ brackets_valid = false;
+ }
+
+ if (token.isError() && (!consumes_raw_text || token.type == TokenType::ErrorMaxQuerySizeExceeded))
{
// Advance the position for further processing of possible test hint.
// Capture max() BEFORE current_statement_end, which walks fresh tokens
@@ -560,6 +589,8 @@ ASTPtr tryParseQuery(
++lookahead;
}
+ brackets_match = brackets_valid && open_brackets.empty();
+
/// We should not spoil the info about maximum parsed position in the original iterator.
tokens.reset();
}
@@ -597,8 +628,9 @@ ASTPtr tryParseQuery(
/// the first error token, so a lexer-rejected token before a later `)` reads as unmatched.
/// Only the parens inside the current statement are reported, so the walk stops after it once every
/// bracket is closed: walking the rest of a multi-statement input for each statement is quadratic.
- UnmatchedParentheses unmatched_parens
- = consumes_raw_text ? UnmatchedParentheses{} : checkUnmatchedParentheses(TokenIterator(tokens), last_token.end);
+ UnmatchedParentheses unmatched_parens;
+ if (!consumes_raw_text && !(brackets_match && last_token.end <= walked_until))
+ unmatched_parens = checkUnmatchedParentheses(TokenIterator(tokens), last_token.end);
if (!unmatched_parens.empty())
{
/// `checkUnmatchedParentheses` can walk past the current statement, so it can |
|
Following up on my previous comment: the same pre-parse walk can also tell the parser which brackets a
Same setup as before (server-side time from
The syntax-error rows add a trailing Outputs and error messages are identical with and without the patch for the 65 malformed inputs from before, for 75 more with Patch (src/Parsers, on top of this PR and the previous patch)diff --git a/src/Parsers/ExpressionElementParsers.cpp b/src/Parsers/ExpressionElementParsers.cpp
index 2b117646b39a..0b1b1197069e 100644
--- a/src/Parsers/ExpressionElementParsers.cpp
+++ b/src/Parsers/ExpressionElementParsers.cpp
@@ -1,3 +1,4 @@
+#include <algorithm>
#include <cerrno>
#include <cmath>
#include <cstdlib>
@@ -1191,6 +1192,15 @@ struct FailedLiteralReadings
/// Opening brackets where `ParserCollectionOfLiterals` failed.
std::unordered_set<const char *> collections;
+
+ /// What the walk of `tryParseQuery` over the statement found before the parse: up to `brackets_known_until` the
+ /// brackets match, and of those only the brackets in `followed_by_cast` are closed right before a `::`. Any other
+ /// bracket there is not the operand of a cast, so it is not scanned for a collection of literals followed by `::`.
+ const char * brackets_known_until = nullptr;
+ /// Sorted.
+ std::vector<const char *> followed_by_cast;
+ /// The number of elements of the long collections there, by opening bracket. Sorted.
+ std::vector<std::pair<const char *, size_t>> long_collection_sizes;
};
/// A reading that ended this close to its bracket costs less to repeat than to remember.
@@ -1203,6 +1213,23 @@ static FailedLiteralReadings & getFailedLiteralReadings(Expected & expected)
return *expected.failed_literal_readings;
}
+void rememberBracketsBeforeCast(
+ Expected & expected,
+ const char * known_until,
+ const std::vector<const char *> & brackets_followed_by_cast,
+ const std::vector<std::pair<const char *, size_t>> & long_collection_sizes)
+{
+ auto & readings = getFailedLiteralReadings(expected);
+ readings.brackets_known_until = known_until;
+ /// The walk lists the brackets as they close, which is in order unless they nest.
+ readings.followed_by_cast = brackets_followed_by_cast;
+ if (!std::is_sorted(readings.followed_by_cast.begin(), readings.followed_by_cast.end()))
+ std::sort(readings.followed_by_cast.begin(), readings.followed_by_cast.end());
+ readings.long_collection_sizes = long_collection_sizes;
+ if (!std::is_sorted(readings.long_collection_sizes.begin(), readings.long_collection_sizes.end()))
+ std::sort(readings.long_collection_sizes.begin(), readings.long_collection_sizes.end());
+}
+
/// Scans an array or a tuple of numbers, strings and `NULL`s, and of nested arrays and tuples of them,
/// leaving `pos` right after it, and appends its text to `literal.text` token by token: without
/// whatever the query holds between the tokens - a comment, or a space between a minus and its
@@ -1587,6 +1614,11 @@ static bool readCollectionOfLiteralsBeforeCast(IParser::Pos & pos, LiteralAsText
bool remembered = false;
if (const auto * readings = expected.failed_literal_readings.get())
{
+ /// The walk over the statement knows that no `::` follows this bracket.
+ if (pos->begin < readings->brackets_known_until
+ && !std::binary_search(readings->followed_by_cast.begin(), readings->followed_by_cast.end(), pos->begin))
+ return false;
+
if (auto it = readings->cast_operands.find(pos->begin); it != readings->cast_operands.end())
{
after_literal = it->second;
@@ -2018,6 +2050,18 @@ bool ParserCollectionOfLiterals<Collection>::parseImpl(Pos & pos, ASTPtr & node,
layers.emplace_back(pos);
pos.increaseDepth();
+ /// A long collection gets its size from the walk over the statement, so that it does not grow element by element.
+ if (const auto * readings = expected.failed_literal_readings.get();
+ readings && !readings->long_collection_sizes.empty() && layers.back().literal_begin->begin < readings->brackets_known_until)
+ {
+ const char * begin = layers.back().literal_begin->begin;
+ const auto & sizes = readings->long_collection_sizes;
+ auto it = std::lower_bound(
+ sizes.begin(), sizes.end(), begin, [](const auto & entry, const char * key) { return entry.first < key; });
+ if (it != sizes.end() && it->first == begin)
+ layers.back().arr.reserve(it->second);
+ }
+
auto fail = [&]
{
for (auto & layer : layers)
diff --git a/src/Parsers/ExpressionElementParsers.h b/src/Parsers/ExpressionElementParsers.h
index 1492a259d8df..86d3f65b0f5f 100644
--- a/src/Parsers/ExpressionElementParsers.h
+++ b/src/Parsers/ExpressionElementParsers.h
@@ -6,6 +6,7 @@
#include <optional>
#include <string_view>
+#include <vector>
namespace DB
@@ -275,6 +276,16 @@ protected:
bool parseImpl(Pos & pos, ASTPtr & node, Expected & expected) override;
};
+/// Passes to the parse what `tryParseQuery` found walking over the tokens of the statement: up to `known_until` the
+/// brackets match, and only the brackets in `brackets_followed_by_cast` (by opening bracket) are closed right before
+/// a `::`, so `ParserCastOperator` does not scan the others for a collection of literals followed by `::`.
+/// `long_collection_sizes` maps the opening bracket of each long collection there to its number of elements.
+void rememberBracketsBeforeCast(
+ Expected & expected,
+ const char * known_until,
+ const std::vector<const char *> & brackets_followed_by_cast,
+ const std::vector<std::pair<const char *, size_t>> & long_collection_sizes);
+
/** NULL literal.
*/
class ParserNull : public IParserBase
diff --git a/src/Parsers/parseQuery.cpp b/src/Parsers/parseQuery.cpp
index 593e7a49142e..58cc7c311338 100644
--- a/src/Parsers/parseQuery.cpp
+++ b/src/Parsers/parseQuery.cpp
@@ -5,6 +5,7 @@
#include <Parsers/ASTInsertQuery.h>
#include <Parsers/ASTExplainQuery.h>
#include <Parsers/CommonParsers.h>
+#include <Parsers/ExpressionElementParsers.h>
#include <Parsers/Lexer.h>
#include <Parsers/TokenIterator.h>
#include <Common/StringUtils.h>
@@ -428,6 +429,22 @@ const char * getInsertData(const ASTPtr & ast)
}
+/// Whether the token at `position` follows a closing bracket. Only there can an error message list the `::` that a parse
+/// with the facts of the walk over the statement does not note after a collection of literals that no `::` follows.
+static bool followsClosingBracket(IParser::Pos pos, const char * position)
+{
+ if (!position)
+ return false;
+
+ bool after_closing_bracket = false;
+ while (!pos->isEnd() && pos->begin < position)
+ {
+ after_closing_bracket = pos->type == TokenType::ClosingRoundBracket || pos->type == TokenType::ClosingSquareBracket;
+ ++pos;
+ }
+ return after_closing_bracket && pos->begin == position;
+}
+
ASTPtr tryParseQuery(
IParser & parser,
const char * & _out_query_end, /* also query begin as input parameter */
@@ -529,14 +546,35 @@ ASTPtr tryParseQuery(
/// same tokens and stops at that `;` unless the parse looked past it. Then the second walk is skipped.
bool brackets_match = false;
const char * walked_until = nullptr;
+ /// The opening brackets that are closed right before a `::`, known when the brackets match.
+ std::vector<const char *> brackets_followed_by_cast;
+ /// The number of commas directly inside each long bracket, by its opening bracket.
+ std::vector<std::pair<const char *, size_t>> long_collection_sizes;
if (consumes_raw_text || !ParserKeyword(Keyword::INSERT_INTO).ignore(lookahead))
{
- std::vector<TokenType> open_brackets;
+ struct OpenBracket
+ {
+ TokenType type;
+ const char * begin;
+ /// The commas of the enclosing bracket counted before this one opened.
+ size_t enclosing_commas;
+ };
+ /// Only a collection this long is worth sizing up front.
+ static constexpr size_t min_sized_collection_commas = 64;
+ /// The commas directly inside the innermost open bracket so far.
+ size_t commas = 0;
+ std::vector<OpenBracket> open_brackets;
+ /// The opening bracket of the bracket that the previous token closed.
+ const char * just_closed = nullptr;
bool brackets_valid = true;
while (true)
{
/// Look the token up once: every access of the token stream also tracks the furthest position.
const Token & token = *lookahead;
+ if (just_closed && token.type == TokenType::DoubleColon)
+ brackets_followed_by_cast.push_back(just_closed);
+ just_closed = nullptr;
+
if (token.type == TokenType::Semicolon || token.type == TokenType::EndOfStream)
{
walked_until = token.begin;
@@ -545,14 +583,25 @@ ASTPtr tryParseQuery(
if (token.type == TokenType::OpeningRoundBracket || token.type == TokenType::OpeningSquareBracket)
{
- open_brackets.push_back(token.type);
+ open_brackets.push_back({token.type, token.begin, commas});
+ commas = 0;
+ }
+ else if (token.type == TokenType::Comma)
+ {
+ ++commas;
}
else if (token.type == TokenType::ClosingRoundBracket || token.type == TokenType::ClosingSquareBracket)
{
const auto opening = token.type == TokenType::ClosingRoundBracket ? TokenType::OpeningRoundBracket
: TokenType::OpeningSquareBracket;
- if (!open_brackets.empty() && open_brackets.back() == opening)
+ if (!open_brackets.empty() && open_brackets.back().type == opening)
+ {
+ just_closed = open_brackets.back().begin;
+ if (commas >= min_sized_collection_commas)
+ long_collection_sizes.emplace_back(just_closed, commas + 1);
+ commas = open_brackets.back().enclosing_commas;
open_brackets.pop_back();
+ }
else
brackets_valid = false;
}
@@ -595,9 +644,32 @@ ASTPtr tryParseQuery(
tokens.reset();
}
+ /// With matching brackets the parse need not look for a `::` after a collection of literals that no `::` follows.
+ /// That changes nothing it reads, but it does not note `::` as expected after such a collection, and an error
+ /// lists what was expected. So a statement that fails right after a closing bracket is parsed again without it,
+ /// to report exactly the same. Callers that collect highlights or literal tokens get the parse they always had.
+ const bool remember_brackets = brackets_match && !expected.enable_highlighting && !expected.literal_token_map;
+ if (remember_brackets)
+ rememberBracketsBeforeCast(expected, walked_until, brackets_followed_by_cast, long_collection_sizes);
+
ASTPtr res;
- const bool parse_res = parser.parse(token_iterator, res, expected);
- const auto last_token = token_iterator.max();
+ const IParser::Pos parse_begin = token_iterator;
+ bool parse_res = parser.parse(token_iterator, res, expected);
+ auto last_token = token_iterator.max();
+ if (remember_brackets && (!parse_res || (!token_iterator->isEnd() && token_iterator->type != TokenType::Semicolon))
+ && followsClosingBracket(parse_begin, expected.max_parsed_pos))
+ {
+ expected.variants.clear();
+ expected.max_parsed_pos = nullptr;
+ expected.failed_keyword_readings.reset();
+ expected.failed_subquery_readings.reset();
+ expected.failed_literal_readings.reset();
+ tokens.reset();
+ token_iterator = parse_begin;
+ res = nullptr;
+ parse_res = parser.parse(token_iterator, res, expected);
+ last_token = token_iterator.max();
+ }
_out_query_end = last_token.end;
/// Also check on the AST level, because the generated AST depth can be greater than the recursion depth of the parser. |
…rackets `tryParseQuery` already walks every token of a non-INSERT statement before parsing. Matching the brackets during that walk lets it skip `checkUnmatchedParentheses` when that would find nothing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The parse looks at the `;` after the statement, so compare the beginning of the last token it read. Co-Authored-By: Claude Opus 5.5 <[email protected]>

Several parser paths did repeated work that grew quadratically with the nesting depth or with the number of statements:
(or[was read as cast text (building a string) before checking whether::follows, and every enclosing level read the same brackets again. Both the cast reading andParserCollectionOfLiteralsnow check first and remember the brackets where a reading failed, the same way failed subquery and keyword readings are remembered. A collection cast written the way the text reader expects takes its text straight from the query.Tokens::operator[]is inlined, with the lexing loop out of line.Examples (parse and format):
((1, ((1, ... 1))))with depth 4000 goes from 11.8 s to 0.16 s,(((...(1, 2, ..., 1600)...)))with 1600 grouping brackets from 1.05 s to 0.05 s, a script of 16000 statements from 7.9 s to 0.14 s. Flat inputs get 6-27% fewer cycles. Parsing results and error messages are unchanged.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix quadratic parsing time of deeply nested literals and casts, tuples in many grouping brackets, and scripts with many statements.
Workflow [PR]
Sync PR [sync-upstream/pr/133041]