spark-test commented on code in PR #60353: URL: https://github.com/apache/spark/pull/60353#discussion_r4571268133
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveGapFill.scala: ########## @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package org.apache.spark.sql.catalyst.analysis + +import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, UnresolvedGapFill} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_GAP_FILL +import org.apache.spark.sql.errors.QueryCompilationErrors +import org.apache.spark.sql.internal.SQLConf + +/** + * Rejects [[UnresolvedGapFill]] until the operator is implemented. + * + * When `spark.sql.gapFillRelationOperator.enabled` is off, it fails without waiting for the + * child, so a missing table also gets this error. When it is on, it waits for the child to + * resolve, so errors that leave the child unresolved (such as a missing table or column) are + * reported first. Errors that the final analysis check raises on a resolved child still come + * after this error. + */ +object ResolveGapFill extends Rule[LogicalPlan] { + + override def apply(plan: LogicalPlan): LogicalPlan = plan.resolveOperatorsWithPruning( + _.containsPattern(UNRESOLVED_GAP_FILL), ruleId) { + case g: UnresolvedGapFill if !conf.getConf(SQLConf.GAP_FILL_ENABLED) || g.childrenResolved => Review Comment: **Nit (P3):** With the gate on, this case fires only once the child is resolved, and the rule runs only in the fixed-point Resolution batch. By the review's reading of the analyzer, some inputs resolve only in a later batch: ResolveUnresolvedHaving runs alone as the last batch and resolves HAVING over a GROUP BY whose select list has a generator and a window function. Take `SELECT * FROM (SELECT explode(array(a)) AS col, count(*) OVER () AS cnt, a FROM VALUES (1), (2), (3), (NULL) AS t(a) GROUP BY a HAVING a IS NOT NULL) GAP FILL (ORDER BY a BIN WIDTH 1)`. Its input is still unresolved when this rule last runs, so the rule never throws. CheckAnalysis has no case for UnresolvedGapFill, so analysis ends in UNRESOLVED_COLUMN for `a`, a column the input has. The PR description promises UNSUPPORTED_FEATURE.GAP_FILL for every GAP FILL query, and the conf doc says GAP FILL queries are rejected whatever the value. With the gate off, the same query does get that error. The later PRs that r eplace this rejection with resolution in the same place would leave such inputs unresolved too. Consider also rejecting a leftover UnresolvedGapFill in CheckAnalysis's bottom-up pass, before its generic operator case, so the rejection no longer depends on which batch resolves the input. That pass checks children first, so a missing table still reports TABLE_OR_VIEW_NOT_FOUND first. This extends an [existing discussion](https://github.com/apache/spark/pull/60353#discussion_r4557248417). **Verification:** - **Regression:** With the gate on, `SELECT * FROM (SELECT explode(array(a)) AS col, count(*) OVER () AS cnt, a FROM VALUES (1), (2), (3), (NULL) AS t(a) GROUP BY a HAVING a IS NOT NULL) GAP FILL (ORDER BY a BIN WIDTH 1)` fails with UNSUPPORTED_FEATURE.GAP_FILL. - **Compatibility:** With the gate on, a GAP FILL query over a missing table still fails with TABLE_OR_VIEW_NOT_FOUND, and one over a temp view fails with UNSUPPORTED_FEATURE.GAP_FILL. With the gate off, both fail with UNSUPPORTED_FEATURE.GAP_FILL. ########## sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4: ########## @@ -1309,6 +1311,40 @@ binByClause RIGHT_PAREN (AS? tblAlias=errorCapturingIdentifier)? ; +gapFillClause + : GAP FILL LEFT_PAREN + (PARTITION BY partitionCol+=multipartIdentifier + (COMMA partitionCol+=multipartIdentifier)*)? + ORDER BY timeCol=multipartIdentifier + BIN WIDTH binWidth=expression + (ALIGN TO origin=expression + | FROM rangeStart=expression TO rangeEnd=expression Review Comment: **Blocking (P1):** This alternative lets TO follow any expression, and Spark's first parsing stage (SLL) predicts with context-free follow sets. So at a unit-to-unit interval literal such as `INTERVAL '0 01:00:00' DAY TO SECOND`, or at the optional TO of an `INTERVAL DAY TO SECOND` type, a second reading stays viable: the literal ends before TO, and `TO SECOND ...` is read as the end of a GAP FILL range. That reading survives while the following tokens can continue the range-end expression. After a `)` it also survives while they can continue a relation, for example `AS c_1, count_if(...) AS c_2, ...` read as a clause alias and a FROM relation list. Prediction therefore scans to the end of the enclosing expression or list for each such literal, in statements that do not use GAP FILL. A repro with parsers generated by ANTLR 4.13.1 from both grammars, run through Spark's SLL-then-LL strategy, shows the cost. A select list of 1000 `count_if(ts > now() - INTERVAL '0 01:00:00' DAY TO SECOND) AS c_i` items takes 14,082,042 lookahead tokens instead of 89,042, about 50 ms more per parse. A WHERE clause that joins 400 `c_i > INTERVAL '1 2' DAY TO HOUR` comparisons with AND takes 1,294,454 instead of 17,254. The work grows quadratically with the number of such literals, while trees and results stay identical and nothing falls back to LL; single-unit literals stay flat. `spark.sql.gapFillRelationOperator.enabled` does not gate the grammar, so SparkSession.sql, Spark Connect, the Thrift server and stored view text all pay this cost. Reordering the interval alternatives changed which reading SLL picks, not how far it scans. This extends an [existing discussion](https://github.com/apache/spark/pull/60353#discussion_r4557248379). **Recommended change:** Require parenthesized range bounds in gapFillClause, `FROM (startExpr) TO (endExpr)`, so that TO no longer follows a bare expression, and keep the rangeStart and rangeEnd labels so AstBuilder stays unchanged. Then restore the base branch's interval rules. Commits 40bbc16056b and c959ae30851 changed them only to compensate for the range's TO; 40bbc16056b says the GAP FILL range FROM ... TO ... made the first parsing stage misread literals. Restoring them means: list errorCapturingMultiUnitsInterval first in `interval`, drop the multiUnitsBeforeUnitToUnit alternative, put error1 before error2 again in errorCapturingUnitToUnitInterval, and remove the comment that explains the reordering. Update the parser tests that write a range (the every-clause and shuffled-order queries, the repeated FROM case and the range-start test) to the new syntax. Add parser tests that an unparenthesized range is a syntax error and that first-stage lookahead stays flat for statement s with many unit-to-unit interval literals, such as long select lists and WHERE conjunctions. Keep the interval-literal tests as guards for the base-branch behavior, and update the syntax shown in the PR description. **Why this works:** With the bounds in parentheses, a range-start expression can only be followed by RIGHT_PAREN, so the GAP FILL clause no longer lets TO follow a bare expression. The only other rule with TO after an expression, changesClause, needs SYSTEM_VERSION, VERSION, SYSTEM_TIME or TIMESTAMP right after TO, as on the base branch. At the interval and INTERVAL-type decisions, the reading that ends the literal before TO then dies at or just after TO, as on the base branch, and SLL resolves within a few tokens. The base interval rules are sufficient again, so the compensating reorder and error-capturing alternative are no longer needed. **Scope:** Change the GAP FILL range to parenthesized bounds, restore the base branch's interval rules, and update the parser tests and the PR description for the new syntax. **Compatibility:** GAP FILL queries that parse are still rejected as before, the other clauses, pipe forms, aliases and keywords are unchanged, and the range still takes general expressions as bounds. **Risks:** The accepted GAP FILL syntax changes: a range written without parentheses becomes a syntax error. No release contains GAP FILL and every GAP FILL query is still rejected, so no query that works today breaks, but the later GAP FILL PRs and any documentation must use the parenthesized form. A scalar subquery used as a bound then needs its own parentheses inside the range's, as in `FROM ((SELECT min(ts) FROM t)) TO (...)`. **Constraints:** Do not let TO follow a bare expression anywhere in the GAP FILL clause again, and check later clause additions for first-stage lookahead on statements with many unit-to-unit interval literals. Keep the rangeStart and rangeEnd labels and one FROM token per range, so that AstBuilder and the duplicate-clause check need no change. **Exclusions:** - Changing Spark's two-stage parse strategy, for example to bound SLL lookahead or to fall back to LL on slow predictions, is a separate repository-wide change that this fix does not need. **Success:** Statements without GAP FILL parse with the same outcome, parse tree, error and first-stage lookahead as on the base branch, including select and IN lists of interval-ending aggregate calls and scalar subqueries, `::INTERVAL x TO y` casts, and long WHERE conjunctions of comparisons with unit-to-unit interval literals. `FROM (startExpr) TO (endExpr)` parses in the first stage in both keyword modes, including bounds that end in an interval literal, and a range without parentheses is a syntax error. A repeated parenthesized range still raises DUPLICATE_CLAUSES naming FROM. **Verification:** - **Regression:** With first-stage prediction profiling on, parse statements that each hold hundreds of unit-to-unit interval literals or INTERVAL x TO y types followed by more of the expression or list: a select list of items like count_if(ts > now() - INTERVAL '0 01:00:00' DAY TO SECOND) AS c_i, an IN list of scalar subqueries that each end in a DAY TO HOUR literal, a select list of (SELECT x::INTERVAL DAY TO SECOND) AS a_i subqueries, and a WHERE clause that joins hundreds of c_i > INTERVAL '1 2' DAY TO HOUR comparisons with AND. Assert that the maximum lookahead of the interval and INTERVAL-type decisions stays a small constant, as on the base branch, instead of growing with the statement. - **Compatibility:** In both keyword modes, interval literals and INTERVAL types outside GAP FILL, including the error-capturing forms and malformed literals that the interval tests exercise, keep the base branch's parse trees, error conditions and error positions, and the valid ones parse in the first stage without the LL retry. - **Behavior:** In both keyword modes, a GAP FILL clause with `FROM (startExpr) TO (endExpr)` parses to the same UnresolvedGapFill fields as before, both in the relation form and as a pipe step, including bounds that end in an interval literal and the range in any position among the optional clauses. A repeated range raises DUPLICATE_CLAUSES naming FROM, and a range without parentheses is a PARSE_SYNTAX_ERROR. ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/parser/PlanParserSuite.scala: ########## @@ -3560,6 +3563,343 @@ class PlanParserSuite extends AnalysisTest { |)""".stripMargin)).size == 1) } + test("GAP FILL: clause parses into the expected UnresolvedGapFill") { + // Minimal clause without PARTITION BY, optional clauses or a table alias. + val minimal = singleGapFill(parsePlan( + """SELECT * FROM metrics GAP FILL ( + | ORDER BY ts + | BIN WIDTH INTERVAL '5' MINUTE + |)""".stripMargin)) + assert(minimal.partitionColumns.isEmpty) + assert(minimal.timeColumn == UnresolvedAttribute(Seq("ts"))) + assert(minimal.binWidthExpr == parseExpression("INTERVAL '5' MINUTE")) + assert(minimal.originExpr.isEmpty) + assert(minimal.rangeStartExpr.isEmpty && minimal.rangeEndExpr.isEmpty) + assert(minimal.fillColumns.isEmpty) + assert(minimal.maxGapExpr.isEmpty) + assert(minimal.binStart.isEmpty && minimal.isGenerated.isEmpty) + + // Qualified columns and several PARTITION BY columns. + val partitioned = singleGapFill(parsePlan( + """SELECT * FROM t1 GAP FILL ( + | PARTITION BY t1.region, t1.device_id + | ORDER BY t1.ts + | BIN WIDTH INTERVAL '5' MINUTE + |)""".stripMargin)) + assert(partitioned.partitionColumns == Seq( + UnresolvedAttribute(Seq("t1", "region")), + UnresolvedAttribute(Seq("t1", "device_id")))) + assert(partitioned.timeColumn == UnresolvedAttribute(Seq("t1", "ts"))) + } + + test("GAP FILL: every clause and fill method parses, in any clause order") { Review Comment: **Nit (P3):** The grammar fixes `PARTITION BY`, `ORDER BY` and `BIN WIDTH` first, and only the optional clauses after them can come in any order. The shuffled query here reorders only those, and the malformed-clauses test below asserts that `GAP FILL (BIN WIDTH ...)` is a syntax error. A name that limits the claim to the optional clauses would match what the test checks: ```suggestion test("GAP FILL: every clause and fill method parses, with optional clauses in any order") { ``` **Verification:** - **Inspection:** The renamed test's name limits the any-order claim to the optional clauses after BIN WIDTH, and no other GAP FILL test name claims that every clause can appear in any order. ########## sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4: ########## @@ -1309,6 +1309,40 @@ binByClause RIGHT_PAREN (AS? tblAlias=errorCapturingIdentifier)? ; +gapFillClause + : GAP FILL LEFT_PAREN + (PARTITION BY partitionCol+=multipartIdentifier + (COMMA partitionCol+=multipartIdentifier)*)? + ORDER BY timeCol=multipartIdentifier + BIN WIDTH binWidth=expression + (ALIGN TO origin=expression + | FROM rangeStart=expression TO rangeEnd=expression Review Comment: Thanks, confirmed: with the unit-to-unit form listed first, these statements parse in the first stage again in both keyword modes, and the new tests pin that. One cost from the same range syntax remains, and this review raises it separately: statements with many unit-to-unit interval literals, such as long select lists or WHERE conjunctions, now need a much longer first-stage lookahead. <!-- SPARK_DEV_REVIEW_REPLY {"feedback_id":"inline:4557248379","thread_id":"inline:4557248379","verdict_sha256":"a940a435fec024843d11d38045319cfb93e2a17431195ba59f88c1a007e93ac2"} --> ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveGapFill.scala: ########## @@ -0,0 +1,40 @@ +/* + * 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. + */ + +package org.apache.spark.sql.catalyst.analysis + +import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, UnresolvedGapFill} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_GAP_FILL +import org.apache.spark.sql.errors.QueryCompilationErrors +import org.apache.spark.sql.internal.SQLConf + +/** + * Rejects [[UnresolvedGapFill]] until the operator is implemented. + * + * When `spark.sql.gapFillRelationOperator.enabled` is off, it fails without waiting for the + * child, so a missing table also gets this error. When it is on, it waits for the child to + * resolve, so an error in the child (such as a missing table) is still reported first. Review Comment: Thanks, the Scaladoc now matches what the rule does. A related gap with the gate on, for inputs that the analyzer resolves only after the Resolution batch, is raised separately in this review. <!-- SPARK_DEV_REVIEW_REPLY {"feedback_id":"inline:4557248417","thread_id":"inline:4557248417","verdict_sha256":"a940a435fec024843d11d38045319cfb93e2a17431195ba59f88c1a007e93ac2"} --> -- 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]
