Skip to content

Fix quadratic parsing of nested literals, grouped tuples and multi-statement scripts - #133041

Open
Algunenano wants to merge 7 commits into
ClickHouse:masterfrom
Algunenano:parser-literal-scan-memo
Open

Algunenano wants to merge 7 commits into
ClickHouse:masterfrom
Algunenano:parser-literal-scan-memo

Conversation

@Algunenano

@Algunenano Algunenano commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Several parser paths did repeated work that grew quadratically with the nesting depth or with the number of statements:

  • Every operand starting with ( 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 and ParserCollectionOfLiterals now 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.
  • Folding nested brackets into one literal copied the nested value at every level, and a tuple in grouping brackets was split into its elements and rebuilt at every level. The values are now moved and the grouped tuple is folded as a whole.
  • For every statement of a multi-statement input, the unmatched-parentheses check walked the whole rest of the input. It now stops after the current statement once every bracket is closed.
  • The fast path of 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):

  • Performance Improvement

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]

Algunenano and others added 3 commits November 19, 2026 16:43
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [512a1e1]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
ThreadSanitizer: data race (STID: 3960-5634) FAIL cidb
Performance Comparison (arm_release, master_head, 6/8) FAIL Performance dashboard
array_first_last #3 FAIL dashboard

AI Review

Summary

The PR reduces repeated literal scans, collection copies, and bracket walks during parsing. No actionable findings at 512a1e19019543f864a80650fc44bcf984c0061c. The new 05836_literal_bracket_reading_memo regression passes in the current Fast test report; the PR description and discussion provide before/after performance measurements.

Missing context / blind spots
  • ⚠️ Full sanitizer and performance comparison jobs for the current head are still pending in the CI report. Their completed reports will close this validation gap. Local tests were not run inside this CI review job.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 512a1e19019543f864a80650fc44bcf984c0061c was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Nov 20, 2026
@antaljanosbenjamin antaljanosbenjamin self-assigned this Nov 20, 2026
Under TSan only 5% of the stack is allowed, and depth 300 exceeded it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@stresshouse

stresshouse Bot commented Nov 20, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

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

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
  • StressHouse run: 47c6ca4f-f758-462e-a92e-d24686f87c5b
  • MIRAI run: 81d571e3-6d9f-411f-b28f-dab3d3b4c1ae
  • PR check IDs:
    • clickbench_463728_1795175669
    • clickbench_463856_1795175740
    • tpch_adapted_1_official_463933_1795175744
    • tpch_adapted_1_official_464228_1795175832

@Algunenano

Copy link
Copy Markdown
Member Author

Nice speed up for a meme PR:
image

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 21, 2026
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]>
@snelheidai

Copy link
Copy Markdown

The post-parse checkUnmatchedParentheses walk can be skipped in the common case, which cuts the time of this PR's parse_bracketed_literals queries by up to 21% (patch below, in case you want it here). For a non-INSERT statement, tryParseQuery already walks every token before parsing (the lexical-error shortcut). The patch matches brackets during that walk and skips the second walk only when it would return nothing: no mismatch, every bracket closed by the first ; or the end, and the parser stopped before that ;. Otherwise the check runs as before, so error messages don't change.

Server-side query time from system.query_log, this PR (281b3c9 cherry-picked onto master db3a3df) without and with the patch, x86 with 32 vCPUs, interleaved pairs in both arm orders, geometric mean of the paired ratios with 95% CI:

query PR, median ms PR + patch, median ms ratio
parse_bracketed_literals: 300000-element array ::Array(UInt32) 41.3 32.1 0.787 [0.772, 0.802]
parse_bracketed_literals: 300000-element array 133.0 124.6 0.931 [0.916, 0.946]
parse_bracketed_literals: 50000 tuples 90.0 86.3 0.961 [0.955, 0.967]
parse_bracketed_literals: 30000 casts 423.3 419.4 0.990 [0.988, 0.993]
k IN (10000 UInt64 keys) 26.5 25.9 0.988 [0.978, 0.998]
k IN (10000 String keys) 31.0 30.7 0.995 [0.984, 1.006]
k IN (10 keys), control 2.4 2.4 0.998 [0.986, 1.010]

The perf-test queries ran with the test's settings, 60 pairs each. The IN rows are SELECT count() FROM t WHERE k IN (...) AND v > 10 AND s != '' on a 4M-row MergeTree ordered by k, 120 pairs each. The saving is one pass over the statement's tokens, about 9 ms for the ~600k tokens of the 300000-element arrays, so its share depends on the rest of the query: the nested-bracket perf-test queries (4-6 ms) changed by 1-3%. Results and peak memory were identical. 65 malformed inputs (unmatched and mismatched brackets, multi-statement scripts, INSERT, unterminated strings) give identical output with clickhouse local --multiquery, clickhouse format and clickhouse format --multiquery.

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

@snelheidai

Copy link
Copy Markdown

Following up on my previous comment: the same pre-parse walk can also tell the parser which brackets a :: follows. Then readCollectionOfLiteralsBeforeCast skips its scan of any literal list that no cast follows, and long lists can be sized up front. On top of the previous patch, this makes the 300000-element array query of parse_bracketed_literals 19% faster with a third less peak memory, and the 50000-tuple query 12% faster. It costs 1% on many casts and a second parse for some syntax errors (patch and details below).

  • While matching brackets, the walk records the opening brackets closed right before :: (usually none), and the cast operator returns at once for any other bracket of the statement. The walk also counts the commas directly inside each bracket, and ParserCollectionOfLiterals reserves the outermost array or tuple of a list with at least 64 of them.
  • Only that scan lists :: as expected after a literal list, at the token right after its closing bracket. So a statement that fails at such a token is parsed again without these facts, and error messages don't change. Parses with highlighting or a literal token map don't use them.

Same setup as before (server-side time from system.query_log, x86 with 32 vCPUs, interleaved pairs in both arm orders, geometric mean of the paired ratios with 95% CI), 80 pairs per query. Baseline: this PR + the previous patch.

query baseline, median ms + this patch, median ms ratio
parse_bracketed_literals: 300000-element array 121.6 98.4 0.808 [0.795, 0.822]
parse_bracketed_literals: 50000 tuples 83.2 73.0 0.880 [0.868, 0.893]
parse_bracketed_literals: the five nested-bracket queries 4.4-5.9 4.2-5.6 0.963-0.985
parse_bracketed_literals: 300000-element array ::Array(UInt32) 32.2 36.4 1.104 [1.088, 1.120]
same query, run on its own 35.8 36.3 1.003 [0.983, 1.023]
parse_bracketed_literals: 30000 casts 419.6 424.1 1.012 [1.007, 1.016]
k IN (10000 UInt64 keys) 18.0 17.3 0.948 [0.932, 0.964]
k IN (10000 String keys) 21.9 21.5 0.980 [0.973, 0.988]
k IN (10 keys), control 2.4 2.4 1.002 [0.987, 1.018]
syntax error: 300000-element array followed by + 107.2 166.9 1.543 [1.528, 1.557]
syntax error: 30000 casts followed by + 402.9 409.3 1.016 [1.012, 1.021]

The syntax-error rows add a trailing + to the perf-test statements and use formatQueryOrNull. The cast query is 10% slower when it runs right after the 300000-element array query, as in this interleaved run, but not on its own: the baseline runs it faster after that query (32.2 ms) than alone (35.8 ms), while the patched build takes about 36.3 ms either way. The real costs are the 1% on 30000 casts and the second parse when a statement fails right after a closing bracket, as in the 1.54x row. Peak memory falls from 79.3 to 53.3 MiB on the 300000-element array and by 0.5 MiB on the 10000-key IN lists; elsewhere it is unchanged.

Outputs and error messages are identical with and without the patch for the 65 malformed inputs from before, for 75 more with :: and long lists (including SELECT (1, 2) 3), and for clickhouse format --multiquery of all 13896 stateless .sql files.

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.

Algunenano and others added 2 commits November 24, 2026 15:21
…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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants