From 0b66d93c7d072e8ff815f3a2c7c49a185e5d0ae1 Mon Sep 17 00:00:00 2001 From: Henson Choi Date: Fri, 13 Nov 2026 15:13:06 +0900 Subject: [PATCH 2/9] Fix crash and runaway planning time with long or deep row patterns A long alternation written without spaces around "|", such as "A*|B*|C*|...", was parsed recursively, one level per branch. It took quadratic time and a long enough chain crashed the backend. Parse it in a single pass into the same flat alternation that the spaced spelling produces. Alternations nested in parentheses, or by such a chain, had their duplicate branches removed again at every nesting level, so planning time grew with the cube of the number of branches. Remove duplicates once after flattening. Flattening a nested sequence now splices its child list into the parent instead of copying it. The optimized pattern is unchanged in all cases. Pattern optimization never checked for interrupts, so planning a large pattern could not be canceled. Check for interrupts in the optimizer passes and while scanning the optimized pattern, and check the stack depth where flattening and deparsing recurse. The nesting depth limit was checked only when a query was planned, against the depth left after pattern optimization, so a view could be created with a pattern that failed whenever a query read the window result. Check the depth of the pattern as written, when it is parsed, instead. As a result, depth that optimization used to remove, such as that of redundant parentheses, now counts toward the limit. --- doc/src/sgml/advanced.sgml | 3 +- doc/src/sgml/ref/select.sgml | 10 +- src/backend/executor/README.rpr | 49 +++++--- src/backend/optimizer/plan/rpr.c | 67 +++++++--- src/backend/parser/gram.y | 99 +++++++++------ src/backend/parser/parse_rpr.c | 51 +++++--- src/backend/utils/adt/ruleutils.c | 2 + src/test/regress/expected/rpr_base.out | 161 ++++++++++++++++++++++++- src/test/regress/sql/rpr_base.sql | 106 +++++++++++++++- 9 files changed, 450 insertions(+), 98 deletions(-) diff --git a/doc/src/sgml/advanced.sgml b/doc/src/sgml/advanced.sgml index ef7de636b04..c0daa208966 100644 --- a/doc/src/sgml/advanced.sgml +++ b/doc/src/sgml/advanced.sgml @@ -672,8 +672,7 @@ FROM stock (e.g., (A | B | A) becomes (A | B)), and simplifying nested quantifiers (e.g., (A*)* becomes A*). - These optimizations reduce pattern complexity and also decrease - nesting depth, making the 254-level depth limit rarely encountered. + These optimizations reduce pattern complexity. They are applied transparently and can be observed in EXPLAIN output. diff --git a/doc/src/sgml/ref/select.sgml b/doc/src/sgml/ref/select.sgml index e970f18349d..31fdae7d94c 100644 --- a/doc/src/sgml/ref/select.sgml +++ b/doc/src/sgml/ref/select.sgml @@ -1181,11 +1181,11 @@ DEFINE definition_variable_name AS (parentheses) is 254 levels. An alternation costs a level of its own, so a pattern that nests alternations reaches the limit at about half as many parentheses. - However, pattern optimizations such as flattening nested sequences - and simplifying nested quantifiers may reduce the effective depth, - so this limit is rarely reached in practice. - The pattern is also limited to 32767 elements, counted after these - optimizations: one for each occurrence of a pattern variable, two for + The depth is that of the pattern as written, so parentheses count + even where they are redundant. + The pattern is also limited to 32767 elements, counted after pattern + optimizations such as flattening nested sequences and simplifying + nested quantifiers: one for each occurrence of a pattern variable, two for each group with a quantifier other than {1}, one for each alternation plus one for each of its alternatives, and one more for the pattern as a whole. A larger pattern is rejected with diff --git a/src/backend/executor/README.rpr b/src/backend/executor/README.rpr index 26d10a6816b..646bdfa0b56 100644 --- a/src/backend/executor/README.rpr +++ b/src/backend/executor/README.rpr @@ -276,12 +276,14 @@ self, so they no longer match scan.l. row_pattern_quantifier_opt therefore accepts each glued spelling, takes the quantifier it half spells, and sets RPRPatternNode.trailing_alt on the term to record that an alternation operator came with it. The flag stays on the -term while the sequence keeps growing; splitRPRTrailingAlt() then splits the -finished sequence at the flagged term into ALT(left, right), where the right -branch is the whole remaining sequence. That is what keeps '|' the -lowest-precedence operator of the pattern language: "A*|B C" parses as -"A* | (B C)", identical to the spaced form. A flagged term with nothing to -its right is a dangling '|' and is rejected. +term while the sequence keeps growing; splitRPRTrailingAlt() then cuts the +finished sequence after every flagged term and returns one ALT whose +branches are the pieces. That is what keeps '|' the lowest-precedence +operator of the pattern language: "A*|B C" parses as "A* | (B C)" and +"A*|B*|C" as "A* | B* | C". The '|' rule splices such an ALT into the +alternation it is building, so a glued spelling gives the same tree as the +spaced one. The sequence is walked once, with no recursion. A flagged +term with nothing to its right is a dangling '|' and is rejected. trailing_alt is transient. splitRPRTrailingAlt() clears it on every path, the error paths included, so a finalized tree never carries it and it @@ -289,9 +291,11 @@ reaches neither the plan nor the query id. III-3. DEFINE Clause Transformation -transformDefineClause() first validates the PATTERN variable count and -collects the names, then rejects any DEFINE variable that PATTERN does not -use. After that it processes each DEFINE variable as follows: +transformDefineClause() first walks the PATTERN tree with +validateRPRPattern(), which enforces the variable-count and nesting-depth +limits and collects the names, then rejects any DEFINE variable that +PATTERN does not use. After that it processes each DEFINE variable as +follows: (1) Checks for duplicate variable names -- this one in a pass of its own over the whole list, before any expression is transformed @@ -300,6 +304,12 @@ use. After that it processes each DEFINE variable as follows: steps below see the final expression form (3) Wraps in a TargetEntry with the variable name set in resname +The depth limit is the planner's (V-2), counted the same way (a GROUP and +an ALT one level each, a SEQ none) but on the tree as written. Phase 1 +never deepens a pattern, so nothing stored can fail the depth test later; +parentheses that Phase 1 would remove count too. The element limit stays +in the planner, because it is defined on the optimized pattern. + Parse analysis puts nothing in the query targetlist for a DEFINE clause. Getting what it reads to the WindowAgg is the planner's job, and it is done the way havingQual's is: build_base_rel_tlists() marks the columns needed so @@ -731,10 +741,15 @@ V-2. The 6 Phases of buildRPRPattern() Phase 5: Finalization (finalizeRPRPattern) Phase 6: Absorbability analysis (computeAbsorbability) -Phase 2 also rejects a pattern too large for the element array or nested too -deep. The depth test is made on entry to each node, before the children -raise the counter, so the one-byte RPRDepth can never wrap. Neither limit -depends on the input rows: a pattern that compiles once compiles every time. +Phase 2 also rejects a pattern too large for the element array and keeps +a depth test as a guard. The depth test is made on entry to each node, +before the children raise the counter, so the one-byte RPRDepth can never +wrap. Neither limit depends on the input rows: a pattern that compiles +once compiles every time. +Parse analysis has already applied the depth test (III-3), so only the +element limit can still fail here. V-3 (d) wraps a run of alternations in a +group, but each of them arrived inside parentheses that V-3 (h) removed, so +the result is never deeper than the pattern as written. V-3. Phase 1: Parse Tree Optimization @@ -762,6 +777,9 @@ error. (a) SEQ flattening: Unwrap nested SEQ nodes SEQ(A, SEQ(B, C)) -> SEQ(A, B, C) + A parenthesized subsequence is optimized on its own before it is + spliced in, so its merges come first: B (B A (B A)+) becomes + B (B A){2,}, not B{2} A (B A)+. (b) Consecutive variable merging: Merge consecutive occurrences of the same variable into a single quantifier @@ -786,6 +804,8 @@ error. (f) ALT flattening and deduplication (A | (B | C)) -> (A | B | C) (A | B | A) -> (A | B) + Nested alternations are flattened all the way down first, and + duplicates are then removed once over the whole list. (g) Quantifier multiplication: Collapse nested quantifiers when the achievable counts are contiguous and the preferred match does not @@ -826,7 +846,8 @@ BEGIN and an END for each GROUP whose quantifier is not {1,1}, an ALT plus one SEP per branch for each alternation, and one FIN for the whole pattern; a SEQ contributes nothing. A new element kind therefore has to be added to scanRPRPattern() and fillRPRPattern() together, and so -does any change to the depth an element is given. +does any change to the depth an element is given, which the parse-time +depth test in validateRPRPattern() (III-3) must follow as well. The rule is that a node's own markers sit at the depth the node was given and its contents one level deeper: BEGIN and END at the group's diff --git a/src/backend/optimizer/plan/rpr.c b/src/backend/optimizer/plan/rpr.c index df3a0b51850..c5d18b615af 100644 --- a/src/backend/optimizer/plan/rpr.c +++ b/src/backend/optimizer/plan/rpr.c @@ -58,7 +58,7 @@ pg_nodiscard static List *mergeConsecutiveAlts(List *children); pg_nodiscard static List *mergeGroupPrefixSuffix(List *children); static RPRPatternNode *optimizeSeqPattern(RPRPatternNode *pattern); -pg_nodiscard static List *flattenAltChildren(List *children); +pg_nodiscard static List *flattenAltChildren(List *flattened, List *children); pg_nodiscard static List *removeDuplicateAlternatives(List *children); static RPRPatternNode *optimizeAltPattern(RPRPatternNode *pattern); @@ -290,8 +290,10 @@ flattenSeqChildren(List *children) if (opt->nodeType == RPR_PATTERN_SEQ) { - newChildren = list_concat(newChildren, - list_copy(opt->children)); + /* Splice its children in; the nested list is not needed again */ + newChildren = list_concat(newChildren, opt->children); + list_free(opt->children); + opt->children = NIL; } else { @@ -689,24 +691,40 @@ optimizeSeqPattern(RPRPatternNode *pattern) * (A | (B | C)) -> (A | B | C) * * Splices each nested ALT's children into the parent list at the position the - * ALT occupied, so the flattened alternatives keep their place. Like + * ALT occupied, so the flattened alternatives keep their place. A nested + * alternation (which can only sit inside parentheses) is descended into + * rather than optimized on its own, so the caller removes duplicates once + * over the whole flattened list instead of once per nesting level. Like * flattenSeqChildren(), this pass can end up longer than what it started - * with, so it builds a new list rather than compacting the cells it has; the - * caller must assign the result. + * with, so it builds a new list; the caller passes NIL as flattened and must + * assign the result. */ static List * -flattenAltChildren(List *children) +flattenAltChildren(List *flattened, List *children) { - List *flattened = NIL; + check_stack_depth(); foreach_node(RPRPatternNode, child, children) { - RPRPatternNode *optimized = optimizeRPRPattern(child); + RPRPatternNode *inner = child; + RPRPatternNode *opt; - if (optimized->nodeType == RPR_PATTERN_ALT) - flattened = list_concat(flattened, optimized->children); - else - flattened = lappend(flattened, optimized); + /* GROUP{1,1} is always unwrapped, so look through it */ + while (inner->nodeType == RPR_PATTERN_GROUP && + inner->min == 1 && inner->max == 1) + inner = linitial_node(RPRPatternNode, inner->children); + + if (inner->nodeType == RPR_PATTERN_ALT) + { + flattened = flattenAltChildren(flattened, inner->children); + continue; + } + + opt = optimizeRPRPattern(child); + + /* Only a nested ALT optimizes to an ALT; those are handled above */ + Assert(opt->nodeType != RPR_PATTERN_ALT); + flattened = lappend(flattened, opt); } return flattened; @@ -733,6 +751,9 @@ removeDuplicateAlternatives(List *children) RPRPatternNode *node = list_nth_node(RPRPatternNode, children, readpos); bool isDuplicate = false; + /* Each branch is compared with every survivor before it */ + CHECK_FOR_INTERRUPTS(); + /* * Survivors are compacted towards the front, so those already kept * are the cells below writepos. writepos never passes readpos, so @@ -768,7 +789,7 @@ static RPRPatternNode * optimizeAltPattern(RPRPatternNode *pattern) { /* Recursively optimize children and flatten nested ALT */ - pattern->children = flattenAltChildren(pattern->children); + pattern->children = flattenAltChildren(NIL, pattern->children); /* Remove duplicate alternatives */ pattern->children = removeDuplicateAlternatives(pattern->children); @@ -1005,6 +1026,7 @@ optimizeRPRPattern(RPRPatternNode *pattern) Assert(pattern != NULL); check_stack_depth(); + CHECK_FOR_INTERRUPTS(); /* * A fixed count leaves reluctance nothing to decide. Drop it here: the @@ -1029,6 +1051,9 @@ optimizeRPRPattern(RPRPatternNode *pattern) break; } + /* The post-passes above rescan the whole subtree on the way back up */ + CHECK_FOR_INTERRUPTS(); + /* Again: a rewrite may have produced a fixed count of its own */ if (result->min == result->max) result->reluctant = false; @@ -1054,14 +1079,16 @@ scanRPRPatternRecursive(RPRPatternNode *node, char **varNames, int *numVars, Assert(node != NULL); check_stack_depth(); + CHECK_FOR_INTERRUPTS(); - /* Check recursion depth limit before overflow occurs */ + /* + * Parse analysis made this test on the pattern as written and + * optimization never deepens one, so this only keeps RPRDepth from + * wrapping. + */ if (depth >= RPR_DEPTH_MAX) - ereport(ERROR, - errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), - errmsg("pattern nesting too deep"), - errdetail("Pattern nesting depth %d exceeds maximum %d.", - depth, RPR_DEPTH_MAX - 1)); + elog(ERROR, "pattern nesting depth %d exceeds maximum %d", + depth, RPR_DEPTH_MAX - 1); /* Track maximum depth */ *maxDepth = Max(*maxDepth, depth); diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y index cf30f443aad..43a279c7fd3 100644 --- a/src/backend/parser/gram.y +++ b/src/backend/parser/gram.y @@ -17107,11 +17107,23 @@ row_pattern_alt: RPRPatternNode *lhs = castNode(RPRPatternNode, $1); RPRPatternNode *rhs = splitRPRTrailingAlt(castNode(RPRPatternNode, $3), yyscanner); + List *rhsitems; + + /* + * A glued "B*|C" on the right comes back as an ALT of its + * own; splice its branches in so that the tree is the same + * as for the spaced spelling. A parenthesized alternation + * is a GROUP, so it is never flattened here. + */ + if (rhs->nodeType == RPR_PATTERN_ALT) + rhsitems = rhs->children; + else + rhsitems = list_make1(rhs); /* If left side is already ALT, append to it */ if (lhs->nodeType == RPR_PATTERN_ALT) { - lhs->children = lappend(lhs->children, rhs); + lhs->children = list_concat(lhs->children, rhsitems); $$ = (Node *) lhs; } else @@ -17119,7 +17131,7 @@ row_pattern_alt: RPRPatternNode *n = makeNode(RPRPatternNode); n->nodeType = RPR_PATTERN_ALT; - n->children = list_make2(lhs, rhs); + n->children = lcons(lhs, rhsitems); n->min = 1; n->max = 1; n->reluctant = false; @@ -20714,15 +20726,22 @@ makeRPRSeqOrSingle(List *children, int location) /* * A glued quantifier such as "A*|" leaves trailing_alt set on its term while - * the enclosing sequence is built. Once the sequence is complete, split it at - * the flagged term into alt(left, right), where the right operand is the whole - * remaining sequence -- this keeps "|" as the lowest-precedence operator, so - * "A*|B C" parses as "A* | (B C)", identical to the spaced form. A flag with - * nothing to its right is a dangling "|" and is rejected. + * the enclosing sequence is built. Once the sequence is complete, cut it + * after every flagged term and return one alternation whose branches are the + * segments -- this keeps "|" as the lowest-precedence operator, so "A*|B C" + * parses as "A* | (B C)" and "A*|B*|C" as "A* | B* | C", identical to the + * spaced forms. A flag with nothing to its right is a dangling "|" and is + * rejected. The sequence is walked once, without recursion, so the cost + * stays linear in the number of terms. */ static RPRPatternNode * splitRPRTrailingAlt(RPRPatternNode *node, core_yyscan_t yyscanner) { + List *branches = NIL; + List *segment = NIL; + RPRPatternNode *first; + RPRPatternNode *altn; + if (node->nodeType != RPR_PATTERN_SEQ) { if (node->trailing_alt) @@ -20738,37 +20757,43 @@ splitRPRTrailingAlt(RPRPatternNode *node, core_yyscan_t yyscanner) foreach_node(RPRPatternNode, child, node->children) { - if (child->trailing_alt) - { - int splitIdx = foreach_current_index(child); - List *lefthalf = list_copy_head(node->children, splitIdx + 1); - List *righthalf = list_copy_tail(node->children, splitIdx + 1); - RPRPatternNode *altn; - RPRPatternNode *rightnode; - - child->trailing_alt = false; - if (righthalf == NIL) - ereport(ERROR, - errcode(ERRCODE_SYNTAX_ERROR), - errmsg("alternation operator \"|\" requires a pattern on both sides"), - parser_errposition(child->location)); - - /* the right branch starts at its own first element, not the seq start */ - rightnode = splitRPRTrailingAlt(makeRPRSeqOrSingle(righthalf, - ((RPRPatternNode *) linitial(righthalf))->location), - yyscanner); - altn = makeNode(RPRPatternNode); - altn->nodeType = RPR_PATTERN_ALT; - altn->children = list_make2(makeRPRSeqOrSingle(lefthalf, node->location), - rightnode); - altn->min = 1; - altn->max = 1; - altn->reluctant = false; - altn->location = node->location; - return altn; - } + segment = lappend(segment, child); + if (!child->trailing_alt) + continue; + + child->trailing_alt = false; + if (foreach_current_index(child) == list_length(node->children) - 1) + ereport(ERROR, + errcode(ERRCODE_SYNTAX_ERROR), + errmsg("alternation operator \"|\" requires a pattern on both sides"), + parser_errposition(child->location)); + + /* each branch starts at its own first element */ + first = linitial_node(RPRPatternNode, segment); + branches = lappend(branches, + makeRPRSeqOrSingle(segment, first->location)); + segment = NIL; } - return node; + + /* no glued "|" in this sequence */ + if (branches == NIL) + { + list_free(segment); + return node; + } + + first = linitial_node(RPRPatternNode, segment); + branches = lappend(branches, + makeRPRSeqOrSingle(segment, first->location)); + + altn = makeNode(RPRPatternNode); + altn->nodeType = RPR_PATTERN_ALT; + altn->children = branches; + altn->min = 1; + altn->max = 1; + altn->reluctant = false; + altn->location = node->location; + return altn; } /* diff --git a/src/backend/parser/parse_rpr.c b/src/backend/parser/parse_rpr.c index 63a4acbeb19..3632ebdbc6f 100644 --- a/src/backend/parser/parse_rpr.c +++ b/src/backend/parser/parse_rpr.c @@ -7,7 +7,8 @@ * structures during query analysis: * - Validates frame options (ROWS only, must start at CURRENT ROW, no * EXCLUDE, and CURRENT ROW is not accepted as the frame end) - * - Validates PATTERN variable count (max RPR_VARID_MAX + 1) + * - Validates PATTERN variable count (max RPR_VARID_MAX + 1) and nesting + * depth (max RPR_DEPTH_MAX - 1) * - Transforms DEFINE clause * - Stores the PATTERN parse tree and the AFTER MATCH SKIP TO flag * @@ -49,8 +50,8 @@ typedef struct } DefineWalkCtx; /* Forward declarations */ -static void validateRPRPatternVarCount(ParseState *pstate, RPRPatternNode *node, - List **varNames); +static void validateRPRPattern(ParseState *pstate, RPRPatternNode *node, + int depth, List **varNames); static List *transformDefineClause(ParseState *pstate, WindowDef *windef); static bool define_walker(Node *node, void *context); static bool rpr_frame_is_supported(int frameOptions); @@ -147,21 +148,27 @@ rpr_frame_is_supported(int frameOptions) } /* - * validateRPRPatternVarCount - * Validate that PATTERN variable count fits the varId range. + * validateRPRPattern + * Check PATTERN variable count and nesting depth against their limits. * * Recursively traverses the pattern tree, collecting unique variable names. * Throws an error if the number of unique variables would require a varId * greater than RPR_VARID_MAX. * + * depth is counted as the planner counts it, but on the pattern as written. + * Optimization never deepens a pattern, so a pattern accepted here cannot + * fail the planner's depth test, and a view or rule is never stored with a + * pattern too deep to run. The counting rule must stay in step with + * scanRPRPatternRecursive() and fillRPRPattern() in rpr.c. + * * varNames collects the unique PATTERN variable names, which is what * transformColumnRef checks via p_rpr_pattern_vars to identify pattern * variable qualifiers. Cross-checking DEFINE variable names against this * list is the caller's responsibility, since it only needs to run once. */ static void -validateRPRPatternVarCount(ParseState *pstate, RPRPatternNode *node, - List **varNames) +validateRPRPattern(ParseState *pstate, RPRPatternNode *node, int depth, + List **varNames) { /* Pattern node must exist - parser always provides non-NULL root */ Assert(node != NULL); @@ -174,6 +181,15 @@ validateRPRPatternVarCount(ParseState *pstate, RPRPatternNode *node, check_stack_depth(); + /* Same test as the planner's scanRPRPatternRecursive(), on the raw tree */ + if (depth >= RPR_DEPTH_MAX) + ereport(ERROR, + errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), + errmsg("pattern nesting too deep"), + errdetail("Pattern nesting depth %d exceeds maximum %d.", + depth, RPR_DEPTH_MAX - 1), + parser_errposition(pstate, exprLocation((Node *) node))); + switch (node->nodeType) { case RPR_PATTERN_VAR: @@ -211,13 +227,16 @@ validateRPRPatternVarCount(ParseState *pstate, RPRPatternNode *node, break; case RPR_PATTERN_SEQ: + /* A sequence adds no level */ + foreach_node(RPRPatternNode, child, node->children) + validateRPRPattern(pstate, child, depth, varNames); + break; + case RPR_PATTERN_ALT: case RPR_PATTERN_GROUP: - /* Recurse into children */ + /* An alternation and a group each add one */ foreach_node(RPRPatternNode, child, node->children) - { - validateRPRPatternVarCount(pstate, child, varNames); - } + validateRPRPattern(pstate, child, depth + 1, varNames); break; } } @@ -246,11 +265,11 @@ transformDefineClause(ParseState *pstate, WindowDef *windef) Assert(windef->rpCommonSyntax->rpDefs != NULL); /* - * Validate PATTERN variable count and collect the PATTERN variable names - * for transformColumnRef. + * Validate PATTERN variable count and nesting depth, and collect the + * PATTERN variable names for transformColumnRef. */ - validateRPRPatternVarCount(pstate, windef->rpCommonSyntax->rpPattern, - &patternVarNames); + validateRPRPattern(pstate, windef->rpCommonSyntax->rpPattern, 0, + &patternVarNames); pstate->p_rpr_pattern_vars = patternVarNames; /* @@ -265,7 +284,7 @@ transformDefineClause(ParseState *pstate, WindowDef *windef) /* * Reject any DEFINE variable whose name does not appear in PATTERN. This * cross-check only needs to run once, so it lives here in the caller - * rather than in the recursive validateRPRPatternVarCount(). + * rather than in the recursive validateRPRPattern(). */ foreach_node(ResTarget, rt, windef->rpCommonSyntax->rpDefs) { diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index 72d0e414275..d3e3b69ec9e 100644 --- a/src/backend/utils/adt/ruleutils.c +++ b/src/backend/utils/adt/ruleutils.c @@ -7214,6 +7214,8 @@ get_rule_pattern_node(RPRPatternNode *node, deparse_context *context) Assert(node != NULL); + check_stack_depth(); + switch (node->nodeType) { case RPR_PATTERN_VAR: diff --git a/src/test/regress/expected/rpr_base.out b/src/test/regress/expected/rpr_base.out index 6d03efbf90d..c0cb4db155d 100644 --- a/src/test/regress/expected/rpr_base.out +++ b/src/test/regress/expected/rpr_base.out @@ -6624,6 +6624,52 @@ SELECT line FROM unnest(string_to_array(pg_get_viewdef('rpr_dp_struct'), E'\n')) (6 rows) DROP VIEW rpr_dp_struct; +-- Glued and spaced spellings build one tree, so each pair shares a WindowAgg. +EXPLAIN (COSTS OFF) +SELECT + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A*|B*|C) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A* | B* | C) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | B*|C) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | B* | C) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN ((A*|B*|C)+) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN ((A* | B* | C)+) DEFINE A AS id > 1, B AS id > 2, C AS id > 3) +FROM (VALUES + (1), + (2)) AS t(id); + QUERY PLAN +------------------------------------------------------------------------------------------------------------ + WindowAgg + Window: w3 AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: (a*# | b*# | c)+ + -> WindowAgg + Window: w2 AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: (a | b*# | c) + -> WindowAgg + Window: w1 AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: (a*# | b*# | c) + -> Sort + Sort Key: "*VALUES*".column1 + -> Values Scan on "*VALUES*" +(12 rows) + +-- A long glued chain is parsed without recursion and deduplicated once. +\set ECHO none + QUERY PLAN +----------------------------------------------------------------------------------------------- + WindowAgg + Window: w AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: (a*# | a) + -> Sort + Sort Key: "*VALUES*".column1 + -> Values Scan on "*VALUES*" +(6 rows) + -- Execution semantics (deparse cannot show reluctant shortest-match). The -- rpr_glue rows -- A rows 1-3 and 5, B rows 4 and 6 -- show when the '|B' -- alternative is reachable. With "*" the first branch always succeeds, so B @@ -6686,6 +6732,11 @@ SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRE ERROR: syntax error at or near ")" LINE 1: ...CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (A*|B|) DEFINE A... ^ +-- a dangling '|' after glued branches is blamed on the last one +SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (A*|B*|) DEFINE A AS val > 0, B AS val <= 0); +ERROR: alternation operator "|" requires a pattern on both sides +LINE 1: ...N CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (A*|B*|) DEFIN... + ^ SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (|A) DEFINE A AS val > 0); ERROR: syntax error at or near "|" LINE 1: ...WEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (|A) DEFINE... @@ -7642,6 +7693,24 @@ WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING 10 | 100 | 0 (10 rows) +-- A parenthesized subsequence is merged before its surroundings +EXPLAIN (COSTS OFF) +SELECT COUNT(*) OVER w +FROM (VALUES + (1), + (2)) AS t(id) +WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (B (B A (B A)+)) DEFINE A AS id > 0, B AS id > 0); + QUERY PLAN +----------------------------------------------------------------------------------------------- + WindowAgg + Window: w AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: b (b a){2,} + -> Sort + Sort Key: "*VALUES*".column1 + -> Values Scan on "*VALUES*" +(6 rows) + -- ALT flatten: (A | (B | C))+ -> (a | b | c)+ EXPLAIN (COSTS OFF) SELECT COUNT(*) OVER w FROM rpr_plan @@ -7692,6 +7761,60 @@ WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING 10 | 100 | 0 (10 rows) +-- Nested alternations flatten and deduplicate across levels +EXPLAIN (COSTS OFF) +SELECT COUNT(*) OVER w +FROM (VALUES + (1), + (2)) AS t(id) +WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | (B | (A | (C | B)))) DEFINE A AS id > 0); + QUERY PLAN +----------------------------------------------------------------------------------------------- + WindowAgg + Window: w AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: (a | b | c) + -> Sort + Sort Key: "*VALUES*".column1 + -> Values Scan on "*VALUES*" +(6 rows) + +-- A quantified group stops the flattening +EXPLAIN (COSTS OFF) +SELECT COUNT(*) OVER w +FROM (VALUES + (1), + (2)) AS t(id) +WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | (B | A)+ | ((B | A))) DEFINE A AS id > 0); + QUERY PLAN +----------------------------------------------------------------------------------------------- + WindowAgg + Window: w AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: (a | (b | a)+ | b) + -> Sort + Sort Key: "*VALUES*".column1 + -> Values Scan on "*VALUES*" +(6 rows) + +-- Nested duplicates collapse to a single variable +EXPLAIN (COSTS OFF) +SELECT COUNT(*) OVER w +FROM (VALUES + (1), + (2)) AS t(id) +WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | ((A | (A)))) DEFINE A AS id > 0); + QUERY PLAN +----------------------------------------------------------------------------------------------- + WindowAgg + Window: w AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: a + -> Sort + Sort Key: "*VALUES*".column1 + -> Values Scan on "*VALUES*" +(6 rows) + -- Quantifier multiply: (A{2}){3} -> a{6} EXPLAIN (COSTS OFF) SELECT COUNT(*) OVER w FROM rpr_plan @@ -11940,8 +12063,8 @@ LINE 3: ...V231 V232 V233 V234 V235 V236 V237 V238 V239 V240 V241) DEFI... ^ DETAIL: The maximum number of row pattern variables is 240. -- Pattern nesting-depth boundary: 254 levels are accepted, 255 rejected. --- Reluctant quantifiers are not subject to quantifier multiplication, so the --- nesting survives optimization and still reaches the depth check. +-- The depth is checked at parse time on the pattern as written, before any +-- optimization. -- ECHO is silenced so the generated deeply nested patterns do not flood the -- expected output. -- 254 nested GROUP{3,7}? -> depth 254 = maximum, accepted. @@ -11954,6 +12077,40 @@ DETAIL: The maximum number of row pattern variables is 240. (2 rows) ERROR: pattern nesting too deep +LINE 3: ...((((((((((((((((((((((((((((((((((((((((((((((((((A{3,7}?){3... + ^ +DETAIL: Pattern nesting depth 255 exceeds maximum 254. +-- Redundant parentheses count: 254 are accepted, a view with 255 is rejected. +\set ECHO none + QUERY PLAN +----------------------------------------------------------------------------------------------- + WindowAgg + Window: w AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: a + -> Sort + Sort Key: "*VALUES*".column1 + -> Values Scan on "*VALUES*" +(6 rows) + +ERROR: pattern nesting too deep +LINE 6: ...((((((((((((((((((((((((((((((((((((((((((((((((((A)))))))))... + ^ +DETAIL: Pattern nesting depth 255 exceeds maximum 254. +-- A parenthesized alternation costs two levels: 127 nested pass, 128 fail. +\set ECHO none + QUERY PLAN +----------------------------------------------------------------------------------------------- + WindowAgg + Window: w AS (ORDER BY "*VALUES*".column1 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) + Pattern: a + -> Sort + Sort Key: "*VALUES*".column1 + -> Values Scan on "*VALUES*" +(6 rows) + +ERROR: pattern nesting too deep +LINE 6: ...A | (A | (A | (A | (A | (A | (A | (A | (A | (A | (A | (A))))... + ^ DETAIL: Pattern nesting depth 255 exceeds maximum 254. DROP TABLE rpr_errors; -- ============================================================ diff --git a/src/test/regress/sql/rpr_base.sql b/src/test/regress/sql/rpr_base.sql index 0ff8b378e3c..ebf9c183cdc 100644 --- a/src/test/regress/sql/rpr_base.sql +++ b/src/test/regress/sql/rpr_base.sql @@ -3862,6 +3862,34 @@ WINDOW w1 AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTE w6 AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN ((A*|B)+) DEFINE A AS val > 0, B AS val <= 0); SELECT line FROM unnest(string_to_array(pg_get_viewdef('rpr_dp_struct'), E'\n')) AS line WHERE line ~ 'PATTERN'; DROP VIEW rpr_dp_struct; +-- Glued and spaced spellings build one tree, so each pair shares a WindowAgg. +EXPLAIN (COSTS OFF) +SELECT + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A*|B*|C) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A* | B* | C) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | B*|C) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | B* | C) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN ((A*|B*|C)+) DEFINE A AS id > 1, B AS id > 2, C AS id > 3), + count(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN ((A* | B* | C)+) DEFINE A AS id > 1, B AS id > 2, C AS id > 3) +FROM (VALUES + (1), + (2)) AS t(id); +-- A long glued chain is parsed without recursion and deduplicated once. +\set ECHO none +SELECT format($$EXPLAIN (COSTS OFF) SELECT count(*) OVER w + FROM (VALUES + (1), + (2)) AS t(id) + WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (%sA) DEFINE A AS id > 0)$$, + repeat('A*|', 20000)) \gexec +\set ECHO all -- Execution semantics (deparse cannot show reluctant shortest-match). The -- rpr_glue rows -- A rows 1-3 and 5, B rows 4 and 6 -- show when the '|B' -- alternative is reachable. With "*" the first branch always succeeds, so B @@ -3890,6 +3918,8 @@ SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRE SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (A*||B) DEFINE A AS val > 0, B AS val <= 0); SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (A||B) DEFINE A AS val > 0, B AS val <= 0); SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (A*|B|) DEFINE A AS val > 0, B AS val <= 0); +-- a dangling '|' after glued branches is blamed on the last one +SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (A*|B*|) DEFINE A AS val > 0, B AS val <= 0); SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (|A) DEFINE A AS val > 0); SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN ((A*|)) DEFINE A AS val > 0); SELECT count(*) OVER w FROM rpr_glue WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (A* *|B) DEFINE A AS val > 0, B AS val <= 0); @@ -4464,6 +4494,15 @@ WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING AFTER MATCH SKIP TO NEXT ROW PATTERN (A ((B) (C))) DEFINE A AS val <= 30, B AS val <= 60, C AS val > 60); +-- A parenthesized subsequence is merged before its surroundings +EXPLAIN (COSTS OFF) +SELECT COUNT(*) OVER w +FROM (VALUES + (1), + (2)) AS t(id) +WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (B (B A (B A)+)) DEFINE A AS id > 0, B AS id > 0); + -- ALT flatten: (A | (B | C))+ -> (a | b | c)+ EXPLAIN (COSTS OFF) SELECT COUNT(*) OVER w FROM rpr_plan @@ -4483,6 +4522,33 @@ WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING AFTER MATCH SKIP PAST LAST ROW PATTERN ((A | B | A)+) DEFINE A AS val <= 50, B AS val > 50); +-- Nested alternations flatten and deduplicate across levels +EXPLAIN (COSTS OFF) +SELECT COUNT(*) OVER w +FROM (VALUES + (1), + (2)) AS t(id) +WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | (B | (A | (C | B)))) DEFINE A AS id > 0); + +-- A quantified group stops the flattening +EXPLAIN (COSTS OFF) +SELECT COUNT(*) OVER w +FROM (VALUES + (1), + (2)) AS t(id) +WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | (B | A)+ | ((B | A))) DEFINE A AS id > 0); + +-- Nested duplicates collapse to a single variable +EXPLAIN (COSTS OFF) +SELECT COUNT(*) OVER w +FROM (VALUES + (1), + (2)) AS t(id) +WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (A | ((A | (A)))) DEFINE A AS id > 0); + -- Quantifier multiply: (A{2}){3} -> a{6} EXPLAIN (COSTS OFF) SELECT COUNT(*) OVER w FROM rpr_plan @@ -6970,8 +7036,8 @@ SELECT format($$SELECT COUNT(*) OVER w FROM rpr_errors \set ECHO all -- Pattern nesting-depth boundary: 254 levels are accepted, 255 rejected. --- Reluctant quantifiers are not subject to quantifier multiplication, so the --- nesting survives optimization and still reaches the depth check. +-- The depth is checked at parse time on the pattern as written, before any +-- optimization. -- ECHO is silenced so the generated deeply nested patterns do not flood the -- expected output. -- 254 nested GROUP{3,7}? -> depth 254 = maximum, accepted. @@ -6987,6 +7053,42 @@ SELECT format($$SELECT id, val, COUNT(*) OVER w FROM rpr_errors repeat('(', 255), repeat('){3,7}?', 255)) \gexec \set ECHO all +-- Redundant parentheses count: 254 are accepted, a view with 255 is rejected. +\set ECHO none +SELECT format($$EXPLAIN (COSTS OFF) SELECT count(*) OVER w + FROM (VALUES + (1), + (2)) AS t(id) + WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (%sA%s) DEFINE A AS id > 0)$$, + repeat('(', 254), repeat(')', 254)) \gexec +SELECT format($$CREATE VIEW rpr_deep_v AS SELECT count(*) OVER w + FROM (VALUES + (1), + (2)) AS t(id) + WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (%sA%s) DEFINE A AS id > 0)$$, + repeat('(', 255), repeat(')', 255)) \gexec +\set ECHO all + +-- A parenthesized alternation costs two levels: 127 nested pass, 128 fail. +\set ECHO none +SELECT format($$EXPLAIN (COSTS OFF) SELECT count(*) OVER w + FROM (VALUES + (1), + (2)) AS t(id) + WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (%sA%s) DEFINE A AS id > 0)$$, + repeat('A | (', 127), repeat(')', 127)) \gexec +SELECT format($$EXPLAIN (COSTS OFF) SELECT count(*) OVER w + FROM (VALUES + (1), + (2)) AS t(id) + WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING + PATTERN (%sA%s) DEFINE A AS id > 0)$$, + repeat('A | (', 128), repeat(')', 128)) \gexec +\set ECHO all + DROP TABLE rpr_errors; -- ============================================================ -- 2.54.0 (Apple Git-157)