codeant-ai-for-open-source[bot] commented on code in PR #41803: URL: https://github.com/apache/superset/pull/41803#discussion_r3624026956
########## superset/sql/dialects/trino.py: ########## @@ -0,0 +1,338 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +import typing as t + +from sqlglot import exp +from sqlglot.dialects.trino import Trino as SqlglotTrino +from sqlglot.tokens import Token, TokenType + +# Keywords that open a block terminated by ``END`` in Trino SQL routines +# (https://trino.io/docs/current/udf/sql.html). ``CASE`` is included because +# both the ``CASE`` statement and the ``CASE`` expression are terminated by +# ``END``, so counting them keeps the depth balanced either way. +BLOCK_OPENERS: set[str] = {"BEGIN", "CASE", "IF", "LOOP", "REPEAT", "WHILE"} + +# Keywords that are also scalar functions in Trino (e.g. ``IF(a, b, c)`` and +# ``REPEAT('a', 3)``). When immediately followed by ``(`` they are function +# calls, not block openers, unless the token stream shows otherwise (see +# ``_is_paren_condition_block``). +AMBIGUOUS_OPENERS: set[str] = {"IF", "REPEAT"} + +BODY_KEYWORDS: tuple[str, str] = ("RETURN", "BEGIN") + + +def _is_paren_condition_block(tokens: t.Sequence[Token], paren_index: int) -> bool: + """ + Determine whether the parenthesized group starting at ``tokens[paren_index]`` + (an ``L_PAREN``) is a procedural block condition, e.g. ``IF (a > b) THEN``, + as opposed to a scalar function call argument list, e.g. ``IF(a, b, c)``. + + Only ``IF`` has this ambiguity: a parenthesized condition is followed by + ``THEN``, while a scalar function call's closing paren never is. + """ + depth = 0 + for i in range(paren_index, len(tokens)): + token_type = tokens[i].token_type + if token_type == TokenType.L_PAREN: + depth += 1 + elif token_type == TokenType.R_PAREN: + depth -= 1 + if depth == 0: + next_token = tokens[i + 1] if i + 1 < len(tokens) else None + return ( + next_token is not None and next_token.token_type == TokenType.THEN + ) + return False Review Comment: **Suggestion:** The parenthesized-condition check scans from the opening parenthesis to the end of the token stream each time it is called, and this helper is invoked inside token-by-token loops during parsing. For large routines with many `IF(` occurrences this creates quadratic-time behavior and can cause severe parser slowdowns (CPU exhaustion) on user-submitted SQL. Precompute matching parenthesis boundaries once, or limit scans to the local expression span so each token is visited a bounded number of times. [possible bug] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ Trino SQL Lab parsing slows on large inline UDFs. - ⚠️ Elevated CPU use on complex IF-heavy routine bodies. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. In Superset SQL Lab, execute a Trino query that declares a large inline SQL UDF using `WITH FUNCTION ... BEGIN ... END` with many occurrences of `IF(` in the routine body (see InlineUDF handling at `superset/sql/dialects/trino.py:65-88` and Parser integration at `superset/sql/dialects/trino.py:118-233`). 2. Superset calls sqlglot to parse the query with `dialect="trino"`, which uses the custom `Trino.Parser._parse` implementation defined at `superset/sql/dialects/trino.py:172-233` to iterate over `raw_tokens` and, in routine mode, compute block depth via `_block_depth_delta` at `superset/sql/dialects/trino.py:118-145`. 3. For each ambiguous `IF` token followed by `(` inside the routine body, `_block_depth_delta` calls `_is_paren_condition_block(tokens, index + 1)` at `superset/sql/dialects/trino.py:41-62`, which scans the token list from the opening parenthesis index to the end (or until the matching closing parenthesis) to check whether the closing paren is followed by `THEN`. 4. On a routine body with many such `IF(` constructs, this repeated full-stream scan makes the parsing work proportional to the number of tokens times the number of ambiguous `IF(` occurrences (quadratic-time behavior), causing noticeable slowdown or high CPU usage when SQL Lab parses these Trino queries. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=de905d2babe64258abb9c4f08f576a68&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=de905d2babe64258abb9c4f08f576a68&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/sql/dialects/trino.py **Line:** 41:62 **Comment:** *Possible Bug: The parenthesized-condition check scans from the opening parenthesis to the end of the token stream each time it is called, and this helper is invoked inside token-by-token loops during parsing. For large routines with many `IF(` occurrences this creates quadratic-time behavior and can cause severe parser slowdowns (CPU exhaustion) on user-submitted SQL. Precompute matching parenthesis boundaries once, or limit scans to the local expression span so each token is visited a bounded number of times. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41803&comment_hash=c4220f38b33ded418800619e9e7068cfe3bc19a300b4e5a7e42477adb2f142ee&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41803&comment_hash=c4220f38b33ded418800619e9e7068cfe3bc19a300b4e5a7e42477adb2f142ee&reaction=dislike'>👎</a> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
