| From: | Henson Choi <assam258(at)gmail(dot)com> |
|---|---|
| To: | jian he <jian(dot)universality(at)gmail(dot)com>, Tatsuo Ishii <ishii(at)postgresql(dot)org> |
| Cc: | zsolt(dot)parragi(at)percona(dot)com, sjjang112233(at)gmail(dot)com, vik(at)postgresfriends(dot)org, er(at)xs4all(dot)nl, jacob(dot)champion(at)enterprisedb(dot)com, david(dot)g(dot)johnston(at)gmail(dot)com, peter(at)eisentraut(dot)org, li(dot)evan(dot)chao(at)gmail(dot)com, pgsql-hackers(at)postgresql(dot)org |
| Subject: | Re: Row pattern recognition |
| Date: | 2026-12-01 07:45:46 |
| Message-ID: | CAAAe_zBR8UWL93aEGX1wyjSMXAFqoQuEwa7YSCrAX1KrN_eErQ@mail.gmail.com |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
Hi Tatsuo,
> OK, attached are the v55 patches based on the v54 plus your 6 patches.
Thank you. Attached are nine incremental patches on top of v55, again
as nocfbot. As I said, I am sending the results of my v54 audit in
several mails, grouped by severity. This first mail has the defect
fixes, the documentation of the plan-time limitation we agreed on, and
two changes to the pattern limits. make check passes after each patch.
0001 Apply review comments on RPR deparse, node output and docs
0002 Fix crash and runaway planning time with long or deep row patterns
0003 Fix wrong row pattern matches when a group follows a copy of itself
0004 Print routine parameters by number inside DEFINE when deparsing
0005 Accept row pattern variables that the lexer turns into lookahead
tokens
0006 Carry DEFINE inputs through grouping and eager aggregation
0007 Remove PlaceHolderVar wrapping of row pattern navigation
arguments
0008 Document plan-time folding of row pattern navigation arguments
0009 Stop counting a row pattern alternation as a nesting level
0006, 0004 and 0007 fix items 1, 2 and 3 of my Oct 9 mail [1]. 0001
addresses your Oct 19 review of my ten patches of Oct 8. 0002, 0003 and
0005 fix new defects found in the audit, 0008 documents the limitation
we agreed on, and 0009, with the depth check of 0002, changes the
pattern limits. Each fix has regression tests.
v55 no longer applies to master since Tom's fix for BUG #19911, which
made tuplestores support absolute row numbers. With it,
window_gettupleslot() seeks by absolute row number,
WindowObjectData.seekpos is gone and markpos starts at 0. The only
conflict is in begin_partition(), in the executor patch of v55. I
resolved it by replacing the reset of the navigation WindowObject with
/* Reset mark position for RPR navigation */
if (winstate->nav_winobj)
winstate->nav_winobj->markpos = 0;
/* Reset mark position for each real window function */
and the nine patches here apply on top of v55 rebased that way. The
XXX comment on the navigation read pointer in prepare_tuplestore()
also mentions seekpos and tuplestore_skiptuples(); I reworded it for
tuplestore_seek(), which still walks a spilled tuplestore a tuple at a
time.
Below, the fixes are grouped by severity, most severe first. 0002 and
0007 each appear in two groups. The commit messages have the details.
1. Wrong results (0003)
When an element X is directly followed by a group whose body is also X,
pattern optimization merges X into the group: X X{0,M} becomes
X{1,M+1}. When the group can be skipped, has a finite upper bound and
X can match empty, this changes the matches. Take three rows, where
row 1 satisfies only B, row 2 satisfies A and C, and row 3 satisfies
only C:
PATTERN ((A | B??) ((A | B??))? C)
matched rows 1-3 instead of rows 1-2 and 3-3. In X{1,M+1}, an empty
match in the first iteration ends the loop (ISO/IEC 19075-5 7.2.8). In
the pattern as written, the group can still start its own first
iteration after an empty X. Trino and Perl also return rows 1-2 and
3-3. 0003 no longer merges X into such a group; every other pattern is
optimized as before.
2. Backend crashes (0002, 0007)
A long alternation written without spaces around "|", such as
"A*|B*|C*|...", was parsed recursively, one recursion level per branch.
Parsing took quadratic time, and at around 100000 branches the backend
died with SIGSEGV. 0002 parses such a chain in a single pass into the
same flat alternation that spaces around "|" produce.
0002 also fixes the planning time of such patterns. An unspaced chain
was parsed into alternations nested one per branch, and alternations
nested like this, or in parentheses, had their duplicate branches
removed again at every nesting level, which took time cubic in the
number of branches. Duplicates are now removed once, after flattening.
On an assert-enabled build, an unspaced chain of 1200 distinct branches
now plans in 7.9 ms instead of 2907 ms, and 1200 distinct branches
nested over 120 levels in 7.7 ms instead of 296 ms. Pattern
optimization also had no interrupt checks, so it could not be canceled.
The second crash is fixed by 0007. After the Oct 9 mail I found an
assertion failure that has the same cause as the internal error in item
3 of that mail. On an assert-enabled build, this query takes the
backend down in alias_relid_set():
CREATE TABLE s1 (id int, v int);
INSERT INTO s1 SELECT g, g FROM generate_series(1, 3) g;
CREATE TABLE s2 (id int);
INSERT INTO s2 SELECT generate_series(1, 3);
CREATE TABLE rb (k bigint);
INSERT INTO rb VALUES (10);
CREATE FUNCTION fj(p bigint) RETURNS TABLE(cnt bigint)
LANGUAGE sql STABLE AS $$
SELECT count(*) OVER w FROM s1 JOIN s2 USING (id)
WINDOW w AS (ORDER BY id
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
PATTERN (A B+) DEFINE B AS PREV(v + p) > 0)
$$;
SELECT k, max(cnt)
FROM (SELECT 10 AS k) a LEFT JOIN rb USING (k), LATERAL fj(k) g
GROUP BY k;
TRAP: failed Assert("n >= 0 && n < list->length")
0007 removes the wrapping that causes it, and the query returns
10 | 3. Section 4 has the rest of the change.
3. Internal errors while planning (0006)
This is item 1 of the Oct 9 mail. Planning failed with an internal
error when DEFINE was the only reader of a column that is functionally
dependent on a GROUP BY key. With 0006, DEFINE can read the other
columns of a table whose primary key is in GROUP BY, as in a query
without RPR. Without the primary key it still cannot.
In 0006, make_group_input_target() adds the columns that DEFINE reads to
the input target of the grouping step. It uses
add_define_inputs_walker(), which already does the same for the window
input target. The walker stops at any expression that the input target
already computes, so a grouped expression such as GROUP BY a + b keeps
its plan.
Jian was the first to report this defect, with a patch, on Sep 22. I
did not take the patch because it also pulls out the columns under a
grouped expression. With GROUP BY a + b, a and b cannot be used after
grouping, yet the patch carries them on their own into the input of the
grouping step, as if they could be. 0006 stops at a + b, as described
above, so a and b are not carried on their own.
0006 also fixes the same kind of omission in eager aggregation. Take
a column that DEFINE reads and that appears elsewhere in the query only
inside aggregates. create_agg_clause_infos() treated it as used only
within aggregates, so the column was not available above the partial
aggregation. Here p has id, its primary key, and v; c has pid and x;
d has pid:
SET min_eager_agg_group_size = 1;
SELECT p.id, sum(p.v + c.x), count(*) OVER w
FROM p JOIN c ON c.pid = p.id JOIN d ON d.pid = p.id
GROUP BY p.id
WINDOW w AS (ORDER BY p.id
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
PATTERN (X Y+) DEFINE Y AS v > PREV(v));
ERROR: variable not found in subplan target lists
0006 makes create_agg_clause_infos() collect the Vars of DEFINE clauses
as well as those of the target list and HAVING, so these columns are
registered as used outside aggregates.
4. Navigation arguments and plan-time folding (0007, 0008)
As we agreed, 0007 removes the PlaceHolderVar wrapping that v55 added
in subquery pull-up and join alias expansion. When a join alias was
expanded below its join level, the wrapping led to crashes or internal
errors: the LATERAL f3(k) query in item 3 of the Oct 9 mail is that
case, and the fj(k) query in section 2 is a variant of it. The
tests of 0007 read a merged JOIN USING column in a navigation argument
in those shapes.
Without the wrapping, a navigation argument is folded like any other
expression. A constant that pull-up, join alias expansion, virtual
generated column expansion, a simplification such as COALESCE(0, v) or a
not-null proof, or SQL function inlining leaves there may be evaluated
at plan time, and an error it raises, such as division by zero, is
raised even when the navigation has no row to land on. The opening
example of my Nov 21 mail, over a one-row VALUES, returned a count of 0
in v55 and now raises. The tests keep one such query for pull-up and
one for join aliases, drop the other tests of the wrapping, and keep the
results of the rest.
0008 documents this as a limitation. "Expression Evaluation Rules"
shows plan-time evaluation only for a constant CASE arm, so 0008 adds
paragraphs there on how a column can become a constant while the query
is planned, with examples outside row pattern recognition: the output
of a pulled-up subquery, WITH query or VALUES list, a virtual generated
column, COALESCE and IS NULL on a NOT NULL column, and an inlined SQL
function that does not use its argument. A last paragraph applies
this to navigation arguments. 0008 points to it from the navigation
functions and describes it in README.rpr.
In the Oct 9 mail I asked whether a parameter of an inlined SQL
function, read inside DEFINE, should count as an outer reference. I
now think it should not: it is a value passed into the function body.
If the caller passes a column, DEFINE reads that column, and
LATERAL f3(k) now runs. If the caller passes a constant, it is folded
like a constant written in the body, as $1 of a prepared statement is
under a custom plan.
There is one more path by which pull-up reaches DEFINE. When a FROM
subquery whose output column is a scalar subquery is pulled up, that
subquery runs inside DEFINE. I would like to ask your view on how this
fits the nesting restrictions of the standard, so I will send that in a
separate mail.
5. Dump and restore (0004, 0005)
0004 is item 2 of the Oct 9 mail. get_parameter() prints a named
parameter qualified with the function name, as in f.threshold. DEFINE
rejects all qualified names, because there the qualifier position is
reserved for pattern variables. So a function with a SQL-standard
body (BEGIN ATOMIC) that read a named parameter in DEFINE could not be
restored from a dump. Printing the bare name would not work either,
because a column of the same name would take its place. So 0004 prints
every routine parameter as $n inside DEFINE.
0005 fixes a defect found in the audit. base_yylex() turns NULLS into
NULLS_LA when FIRST or LAST follows, FORMAT into FORMAT_LA before JSON,
and WITHOUT into WITHOUT_LA before TIME. In PATTERN, two variable names
can stand next to each other, so PATTERN (nulls first) was a syntax
error. PATTERN ("nulls" first) was accepted, but pg_get_viewdef()
printed it back as nulls first, so a view holding it could not be
restored from a dump. 0005 accepts the three lookahead tokens as
variable names in the PATTERN grammar.
6. Pattern limits (0002, 0009)
v55 checked the nesting depth limit at plan time, 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. 0002
checks the depth of the pattern as written, at parse time, so
CREATE VIEW and PREPARE reject it with the error position. As a
result, depth that optimization used to remove now counts toward the
limit, and these shapes, which v55 accepted, are rejected from 255
levels on:
- redundant parentheses such as ((((A))))
- (((A+)+)+)
- (A (B (C ...)))
Each nesting level has a slot in the counts[] array, which holds the
iteration count of the group at that level. An alternation needs no
slot, but it still took a level, because its branches were compiled one
level below it. So nested quantified alternations reached the limit at
127 levels instead of 254. Since 0002 counts depth as written, so did
(A | (B | ...)), which v55 flattened into one alternation. 0009 makes
an alternation take no level: its branches are compiled at its own
level, and the parse-time check counts only groups. Both shapes are now
accepted up to 254 levels.
7. Your Oct 19 review (0001)
- reserve_colname() now copies the name it stores.
- The varNames comment of _outRPRPattern() says what makeRPRPattern()
guarantees.
- The loops in get_query_def() and similar functions use
foreach_node().
- README.rpr now also lists scan.l and the other missing files.
- The two "Under ANALYZE" places in perform.sgml are marked up as
<command>EXPLAIN ANALYZE</command>.
Remaining correctness problem
With this increment, one known correctness problem is left. A window
named after, initial, seek or pattern cannot be referenced by another
window definition, as in WINDOW w2 AS (pattern ORDER BY x), unless its
name is quoted. For a view that does quote it, pg_get_viewdef() prints
the name without quotes, so the view cannot be restored from a dump.
Core has the same problem with windows named rows, range, groups or
partition. CF 7056 [2][3] fixes it and is Ready for Committer. That
patch adds appendWindowRefName() with a list of names to quote. I plan
to make such views restorable by adding after, initial, seek and pattern
to that list, so I am waiting for CF 7056 to go in first. Writing
these names unquoted in a window reference stays a restriction.
You tested v3 of the CF 7056 patch yourself on Aug 27; could you
consider committing it?
Later I will send the performance patches, the remaining review items I
accepted, and the larger improvements.
[1]
https://postgr.es/m/CAAAe_zBno3aWzkJ6iu-Qsj-wniF+j+i3crZRs9DX9UCZZjG_Xg@mail.gmail.com
[2] https://commitfest.postgresql.org/patch/7056/
[3]
https://postgr.es/m/CAHJxwBWx_v=aWp7ZrGRFw2r_7MJdxYX2um3ZOmxTg4c_tL1qLA@mail.gmail.com
Best regards,
Henson
| Attachment | Content-Type | Size |
|---|---|---|
| nocfbot-0001-Apply-review-comments-on-RPR-deparse-node-output-and-d.txt | text/plain | 10.4 KB |
| nocfbot-0002-Fix-crash-and-runaway-planning-time-with-long-or-deep-.txt | text/plain | 41.9 KB |
| nocfbot-0003-Fix-wrong-row-pattern-matches-when-a-group-follows-a-c.txt | text/plain | 26.1 KB |
| nocfbot-0004-Print-routine-parameters-by-number-inside-DEFINE-when-.txt | text/plain | 10.0 KB |
| nocfbot-0005-Accept-row-pattern-variables-that-the-lexer-turns-into.txt | text/plain | 10.5 KB |
| nocfbot-0006-Carry-DEFINE-inputs-through-grouping-and-eager-aggrega.txt | text/plain | 22.5 KB |
| nocfbot-0007-Remove-PlaceHolderVar-wrapping-of-row-pattern-navigati.txt | text/plain | 37.1 KB |
| nocfbot-0008-Document-plan-time-folding-of-row-pattern-navigation-a.txt | text/plain | 8.0 KB |
| nocfbot-0009-Stop-counting-a-row-pattern-alternation-as-a-nesting-l.txt | text/plain | 26.8 KB |
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Henson Choi | 2026-12-01 08:06:08 | Re: Row pattern recognition |
| Previous Message | Michael Paquier | 2026-12-01 07:26:46 | Re: Reapply graceful socket shutdown on Windows (revert 29992a6a509) |