Re: Row pattern recognition

Поиск
Список
Период
Сортировка
Искать

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached are the v29 patch sets to implement the subset of row pattern
recognition feature defined in the SQL standard.

In this patch set:

- Adjust 0003 and 0004 to deal with the recent changes made by 8b1b342.
 
- Add tests to 0007 for CREATE VIEW/pg_get_viewdef.

Best reagards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached are the v30 patches, just adding a patch to change the
default io_method parameter to sync, expecting this affects something
to the recent CFbot failure.
https://commitfest.postgresql.org/patch/4460/
https://cirrus-ci.com/task/6078653164945408
which is similar to:
https://www.postgresql.org/message-id/20250422.111139.1502127917165838403.ishii%40postgresql.org

(Once the issue resolved, the patch should be removed, of course)

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Attached are the v30 patches, just adding a patch to change the
> default io_method parameter to sync, expecting this affects something
> to the recent CFbot failure.
> https://commitfest.postgresql.org/patch/4460/
> https://cirrus-ci.com/task/6078653164945408
> which is similar to:
> https://www.postgresql.org/message-id/20250422.111139.1502127917165838403.ishii%40postgresql.org

CFBot has just run tests against v30 patches and now it turns to green
again!  I guess io_method = sync definitely did the trick.  Note that
previously only the Windows Server 2019, VS 2019 - Neason & ninja test
had failed.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
> Attached are the v30 patches, just adding a patch to change the
> default io_method parameter to sync, expecting this affects something
> to the recent CFbot failure.
> https://commitfest.postgresql.org/patch/4460/
> https://cirrus-ci.com/task/6078653164945408
> which is similar to:
> https://www.postgresql.org/message-id/20250422.111139.1502127917165838403.ishii%40postgresql.org
> 
> (Once the issue resolved, the patch should be removed, of course)

It seems this has turned to green since May 2, 2025.
https://commitfest.postgresql.org/patch/5679/.

The last time it turned to red was April 16, 2025. Maybe something
committed between the period solved the cause of red, but I don't know
exactly which commit.

Anyway v31 patches now remove the change to default io_method
parameter to see if it passes Windows Server 2019, VS 2019 - Meson &
ninja test.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
>> Attached are the v30 patches, just adding a patch to change the
>> default io_method parameter to sync, expecting this affects something
>> to the recent CFbot failure.
>> https://commitfest.postgresql.org/patch/4460/
>> https://cirrus-ci.com/task/6078653164945408
>> which is similar to:
>> https://www.postgresql.org/message-id/20250422.111139.1502127917165838403.ishii%40postgresql.org
>> 
>> (Once the issue resolved, the patch should be removed, of course)
> 
> It seems this has turned to green since May 2, 2025.
> https://commitfest.postgresql.org/patch/5679/.
> 
> The last time it turned to red was April 16, 2025. Maybe something
> committed between the period solved the cause of red, but I don't know
> exactly which commit.
> 
> Anyway v31 patches now remove the change to default io_method
> parameter to see if it passes Windows Server 2019, VS 2019 - Meson &
> ninja test.

Now I see it passes the test.
https://cirrus-ci.com/build/5671612202090496

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached are the v32 patches for Row pattern recognition.  Recent
changes to doc/src/sgml/func.sgml required v31 to be rebased. Other
than that, nothing has been changed.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached are the v33 patches for Row pattern recognition.  The
difference from v32 is that the raw parse tree printing patch is not
included in v33. This is because now that we have
debug_print_raw_parse.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached are the v34 patches for Row pattern recognition.
Notihing has been changed. Just rebased.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached are the v35 patches for Row pattern recognition.  In v34-0001
gram.y patch, %type for RPR were misplaced. v35-0001 fixes this. Other
patches are not changed.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:
Hi Tatsuo-san,

I just reviewed 0006 docs changes and 0001. I plan to slowly review the patch, maybe one commit a day. 

> On Nov 18, 2025, at 10:33, Tatsuo Ishii  wrote:
> 
> Attached are the v35 patches for Row pattern recognition.  In v34-0001
> gram.y patch, %type for RPR were misplaced. v35-0001 fixes this. Other
> patches are not changed.
> 
> Best regards,
> --
> Tatsuo Ishii
> SRA OSS K.K.
> English: http://www.sraoss.co.jp/index_en/
> Japanese:http://www.sraoss.co.jp
> 

I got a few comments, maybe just questions:

1 - 0001 - kwlist.h
```
+PG_KEYWORD("define", DEFINE, RESERVED_KEYWORD, BARE_LABEL)
```

Why do we add “define” as a reserved keyword? From the SQL example you put in 0006:
```

SELECT company, tdate, price,
 first_value(price) OVER w,
 max(price) OVER w,
 count(price) OVER w
FROM stock
 WINDOW w AS (
 PARTITION BY company
 ORDER BY tdate
 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
 AFTER MATCH SKIP PAST LAST ROW
 INITIAL
 PATTERN (LOWPRICE UP+ DOWN+)
 DEFINE
  LOWPRICE AS price <= 100,
  UP AS price > PREV(price),
  DOWN AS price < PREV(price)
);

```

PARTITION is at the same level as DEFINE, but it’s not defined as a reserved keyword:
```
PG_KEYWORD("partition", PARTITION, UNRESERVED_KEYWORD, BARE_LABEL)
```

Even in this patch,”initial”,”past”, “pattern” and “seek” are defined as unreserved, why?  

So I just want to clarify.

2 - 0001 - gram.y
```
opt_row_pattern_initial_or_seek:
			INITIAL		{ $$ = true; }
			| SEEK
				{
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
							 errmsg("SEEK is not supported"),
							 errhint("Use INITIAL instead."),
							 parser_errposition(@1)));
				}
			| /*EMPTY*/		{ $$ = true; }
		;
```

As SEEK is specially listed here, I guess it might be supported in future. If that is true, would it be better to defer the semantic check to later parse phase, which would future work easier.

3 - 0001 - parsenodes.h
```
+/*
+ * RowPatternCommonSyntax - raw representation of row pattern common syntax
+ *
+ */
+typedef struct RPCommonSyntax
+{
+	NodeTag		type;
+	RPSkipTo	rpSkipTo;		/* Row Pattern AFTER MATCH SKIP type */
+	bool		initial;		/* true if  is
+								 * initial */
+	List	   *rpPatterns;		/* PATTERN variables (list of A_Expr) */
+	List	   *rpDefs;			/* row pattern definitions clause (list of
+								 * ResTarget) */
+} RPCommonSyntax;
+
 /*
  * WindowDef - raw representation of WINDOW and OVER clauses
  *
@@ -593,6 +618,7 @@ typedef struct WindowDef
 	char	   *refname;		/* referenced window name, if any */
 	List	   *partitionClause;	/* PARTITION BY expression list */
 	List	   *orderClause;	/* ORDER BY (list of SortBy) */
+	RPCommonSyntax *rpCommonSyntax; /* row pattern common syntax */
```

RP fields are directly defined in WindowClause, then why do we need a wrapper of RPCommonSyntax? Can we directly define RP fields in WindowRef as well?

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: Row pattern recognition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Nov 18, 2025, at 13:03, Chao Li  wrote:
> 
> Hi Tatsuo-san,
> 
> I just reviewed 0006 docs changes and 0001. I plan to slowly review the patch, maybe one commit a day. 
> 
>> On Nov 18, 2025, at 10:33, Tatsuo Ishii  wrote:
>> 
>> Attached are the v35 patches for Row pattern recognition.  In v34-0001
>> gram.y patch, %type for RPR were misplaced. v35-0001 fixes this. Other
>> patches are not changed.
>> 
>> Best regards,
>> --
>> Tatsuo Ishii
>> SRA OSS K.K.
>> English: http://www.sraoss.co.jp/index_en/
>> Japanese:http://www.sraoss.co.jp
>> 
> 
> I got a few comments, maybe just questions:
> 
> 1 - 0001 - kwlist.h
> ```
> +PG_KEYWORD("define", DEFINE, RESERVED_KEYWORD, BARE_LABEL)
> ```
> 
> Why do we add “define” as a reserved keyword? From the SQL example you put in 0006:
> ```
> 
> SELECT company, tdate, price,
> first_value(price) OVER w,
> max(price) OVER w,
> count(price) OVER w
> FROM stock
> WINDOW w AS (
> PARTITION BY company
> ORDER BY tdate
> ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
> AFTER MATCH SKIP PAST LAST ROW
> INITIAL
> PATTERN (LOWPRICE UP+ DOWN+)
> DEFINE
>  LOWPRICE AS price <= 100,
>  UP AS price > PREV(price),
>  DOWN AS price < PREV(price)
> );
> 
> ```
> 
> PARTITION is at the same level as DEFINE, but it’s not defined as a reserved keyword:
> ```
> PG_KEYWORD("partition", PARTITION, UNRESERVED_KEYWORD, BARE_LABEL)
> ```
> 
> Even in this patch,”initial”,”past”, “pattern” and “seek” are defined as unreserved, why?  
> 
> So I just want to clarify.
> 
> 2 - 0001 - gram.y
> ```
> opt_row_pattern_initial_or_seek:
> INITIAL { $$ = true; }
> | SEEK
> {
> ereport(ERROR,
> (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> errmsg("SEEK is not supported"),
> errhint("Use INITIAL instead."),
> parser_errposition(@1)));
> }
> | /*EMPTY*/ { $$ = true; }
> ;
> ```
> 
> As SEEK is specially listed here, I guess it might be supported in future. If that is true, would it be better to defer the semantic check to later parse phase, which would future work easier.
> 
> 3 - 0001 - parsenodes.h
> ```
> +/*
> + * RowPatternCommonSyntax - raw representation of row pattern common syntax
> + *
> + */
> +typedef struct RPCommonSyntax
> +{
> + NodeTag type;
> + RPSkipTo rpSkipTo; /* Row Pattern AFTER MATCH SKIP type */
> + bool initial; /* true if  is
> + * initial */
> + List   *rpPatterns; /* PATTERN variables (list of A_Expr) */
> + List   *rpDefs; /* row pattern definitions clause (list of
> + * ResTarget) */
> +} RPCommonSyntax;
> +
> /*
>  * WindowDef - raw representation of WINDOW and OVER clauses
>  *
> @@ -593,6 +618,7 @@ typedef struct WindowDef
> char   *refname; /* referenced window name, if any */
> List   *partitionClause; /* PARTITION BY expression list */
> List   *orderClause; /* ORDER BY (list of SortBy) */
> + RPCommonSyntax *rpCommonSyntax; /* row pattern common syntax */
> ```
> 
> RP fields are directly defined in WindowClause, then why do we need a wrapper of RPCommonSyntax? Can we directly define RP fields in WindowRef as well?
> 

4 - 0001 - parsenodes.h
```
+	/* Row Pattern AFTER MACH SKIP clause */
```

Typo: MACH -> MATCH

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: Row pattern recognition

От:
Vik Fearing <vik@postgresfriends.org>
Дата:

On 18/11/2025 06:03, Chao Li wrote:
> 1 - 0001 - kwlist.h
> ```
> +PG_KEYWORD("define", DEFINE, RESERVED_KEYWORD, BARE_LABEL)
> ```
>
> Why do we add “define” as a reserved keyword? From the SQL example you put in 0006:
> ```
> 
> SELECT company, tdate, price,
>   first_value(price) OVER w,
>   max(price) OVER w,
>   count(price) OVER w
> FROM stock
>   WINDOW w AS (
>   PARTITION BY company
>   ORDER BY tdate
>   ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>   AFTER MATCH SKIP PAST LAST ROW
>   INITIAL
>   PATTERN (LOWPRICE UP+ DOWN+)
>   DEFINE
>    LOWPRICE AS price <= 100,
>    UP AS price > PREV(price),
>    DOWN AS price < PREV(price)
> );
> 
> ```
>
> PARTITION is at the same level as DEFINE, but it’s not defined as a reserved keyword:
> ```
> PG_KEYWORD("partition", PARTITION, UNRESERVED_KEYWORD, BARE_LABEL)
> ```
>
> Even in this patch,”initial”,”past”, “pattern” and “seek” are defined as unreserved, why?
>
> So I just want to clarify.


Because of position. Without making DEFINE a reserved keyword, how do 
you know that it isn't another variable in the PATTERN clause?

-- 

Vik Fearing



Re: Row pattern recognition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Nov 18, 2025, at 19:19, Vik Fearing  wrote:
> 
> 
> Because of position. Without making DEFINE a reserved keyword, how do you know that it isn't another variable in the PATTERN clause?
> 

Ah, thanks for the clarification. Now I got it.

I’m continue to review 0002.

5 - 0002 - parse_clause.c
```
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("FRAME must start at current row when row patttern recognition is used")));
```

Nit typo: patttern -> pattern

6 - 0002 - parse_clause.c
```
+	/* DEFINE variable name initials */
+	static char *defineVariableInitials = "abcdefghijklmnopqrstuvwxyz”;
```

This string can also be const, so “static const char *”

7 - 0002 - parse_clause.c
```
+	/*
+	 * Create list of row pattern DEFINE variable name's initial. We assign
+	 * [a-z] to them (up to 26 variable names are allowed).
+	 */
+	restargets = NIL;
+	i = 0;
+	initialLen = strlen(defineVariableInitials);
+
+	foreach(lc, windef->rpCommonSyntax->rpDefs)
+	{
+		char		initial[2];
+
+		restarget = (ResTarget *) lfirst(lc);
+		name = restarget->name;
```

Looks like “name” is not used inside “foreach”.

8 - 0002 - parse_clause.c
```
+	/*
+	 * Create list of row pattern DEFINE variable name's initial. We assign
+	 * [a-z] to them (up to 26 variable names are allowed).
+	 */
+	restargets = NIL;
+	i = 0;
+	initialLen = strlen(defineVariableInitials);
+
+	foreach(lc, windef->rpCommonSyntax->rpDefs)
+	{
+		char		initial[2];
```

I guess this “foreach” for build initial list can be combined into the previous foreach loop of checking duplication. If an def has no dup, then assign an initial to it.

9 - 0002 - parse_clause.c
```
+static void
+transformPatternClause(ParseState *pstate, WindowClause *wc,
+					   WindowDef *windef)
+{
+	ListCell   *lc;
+
+	/*
+	 * Row Pattern Common Syntax clause exists?
+	 */
+	if (windef->rpCommonSyntax == NULL)
+		return;
```

Checking  (windef->rpCommonSyntax == NULL) seems a duplicate, because transformPatternClause() is only called by transformRPR(), and transformRPR() has done the check.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> On 18/11/2025 06:03, Chao Li wrote:
>> 1 - 0001 - kwlist.h
>> ```
>> +PG_KEYWORD("define", DEFINE, RESERVED_KEYWORD, BARE_LABEL)
>> ```
>>
>> Why do we add “define” as a reserved keyword? From the SQL example
>> you put in 0006:
>> ```
>> 
>> SELECT company, tdate, price,
>>   first_value(price) OVER w,
>>   max(price) OVER w,
>>   count(price) OVER w
>> FROM stock
>>   WINDOW w AS (
>>   PARTITION BY company
>>   ORDER BY tdate
>>   ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>>   AFTER MATCH SKIP PAST LAST ROW
>>   INITIAL
>>   PATTERN (LOWPRICE UP+ DOWN+)
>>   DEFINE
>>    LOWPRICE AS price <= 100,
>>    UP AS price > PREV(price),
>>    DOWN AS price < PREV(price)
>> );
>> 
>> ```
>>
>> PARTITION is at the same level as DEFINE, but it’s not defined as a
>> reserved keyword:
>> ```
>> PG_KEYWORD("partition", PARTITION, UNRESERVED_KEYWORD, BARE_LABEL)
>> ```
>>
>> Even in this patch,”initial”,”past”, “pattern” and “seek” are
>> defined as unreserved, why?
>>
>> So I just want to clarify.
> 
> 
> Because of position. Without making DEFINE a reserved keyword, how do
> you know that it isn't another variable in the PATTERN clause?

I think we don't need to worry about this because PATTERN_P is in the
$nonassoc list in the patch, which gives PATTERN different precedence
from DEFINE.

@@ -888,6 +896,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
 %nonassoc	UNBOUNDED NESTED /* ideally would have same precedence as IDENT */
 %nonassoc	IDENT PARTITION RANGE ROWS GROUPS PRECEDING FOLLOWING CUBE ROLLUP
 			SET KEYS OBJECT_P SCALAR VALUE_P WITH WITHOUT PATH
+			AFTER INITIAL SEEK PATTERN_P

And I think we could change DEFINE to an unreserved keyword.  Attached
is a patch to do that, on top of v35-0001.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index fccc26964a0..8ec9f1f265c 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -17982,6 +17982,7 @@ unreserved_keyword:
 			| DECLARE
 			| DEFAULTS
 			| DEFERRED
+			| DEFINE
 			| DEFINER
 			| DELETE_P
 			| DELIMITER
@@ -18402,7 +18403,6 @@ reserved_keyword:
 			| CURRENT_USER
 			| DEFAULT
 			| DEFERRABLE
-			| DEFINE
 			| DESC
 			| DISTINCT
 			| DO
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index 7c60b9b44a8..89dc2a4b95a 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -129,7 +129,7 @@ PG_KEYWORD("default", DEFAULT, RESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("defaults", DEFAULTS, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("deferrable", DEFERRABLE, RESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("deferred", DEFERRED, UNRESERVED_KEYWORD, BARE_LABEL)
-PG_KEYWORD("define", DEFINE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("define", DEFINE, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("definer", DEFINER, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("delete", DELETE_P, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("delimiter", DELIMITER, UNRESERVED_KEYWORD, BARE_LABEL)

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> 2 - 0001 - gram.y
> ```
> opt_row_pattern_initial_or_seek:
> 			INITIAL		{ $$ = true; }
> 			| SEEK
> 				{
> 					ereport(ERROR,
> 							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> 							 errmsg("SEEK is not supported"),
> 							 errhint("Use INITIAL instead."),
> 							 parser_errposition(@1)));
> 				}
> 			| /*EMPTY*/		{ $$ = true; }
> 		;
> ```
> 
> As SEEK is specially listed here, I guess it might be supported in future. If that is true, would it be better to defer the semantic check to later parse phase, which would future work easier.

From a comment in gram.y:

/*
 * If we see PARTITION, RANGE, ROWS, GROUPS, AFTER, INITIAL, SEEK or PATTERN_P
 * as the first token after the '(' of a window_specification, we want the
 * assumption to be that there is no existing_window_name; but those keywords
 * are unreserved and so could be ColIds.  We fix this by making them have the

For this purpose, we want INITIAL and SEEK to be unreserved keywords.

> 3 - 0001 - parsenodes.h
> ```
> +/*
> + * RowPatternCommonSyntax - raw representation of row pattern common syntax
> + *
> + */
> +typedef struct RPCommonSyntax
> +{
> +	NodeTag		type;
> +	RPSkipTo	rpSkipTo;		/* Row Pattern AFTER MATCH SKIP type */
> +	bool		initial;		/* true if  is
> +								 * initial */
> +	List	   *rpPatterns;		/* PATTERN variables (list of A_Expr) */
> +	List	   *rpDefs;			/* row pattern definitions clause (list of
> +								 * ResTarget) */
> +} RPCommonSyntax;
> +
>  /*
>   * WindowDef - raw representation of WINDOW and OVER clauses
>   *
> @@ -593,6 +618,7 @@ typedef struct WindowDef
>  	char	   *refname;		/* referenced window name, if any */
>  	List	   *partitionClause;	/* PARTITION BY expression list */
>  	List	   *orderClause;	/* ORDER BY (list of SortBy) */
> +	RPCommonSyntax *rpCommonSyntax; /* row pattern common syntax */
> ```
> 
> RP fields are directly defined in WindowClause, then why do we need a wrapper of RPCommonSyntax? Can we directly define RP fields in WindowRef as well?

The row pattern common syntax defined in the standard is not only used
in the WINDOW clause, but in the FROM clause. If we would support RPR
in FROM clause in the future, it would be better to use the same code
of row pattern common syntax in WINDOW clause as much as
possible. That's the reason I created RPCommonSyntax. In the
parse/analysis phase, I am not sure how the parse/analysis code would
be in FROM clause at this point. So I did not define yet another
struct for it.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> 4 - 0001 - parsenodes.h
> ```
> +	/* Row Pattern AFTER MACH SKIP clause */
> ```
> 
> Typo: MACH -> MATCH

Thanks for pointing it out. Will fix.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Nov 19, 2025, at 12:14, Chao Li  wrote:
> 
> 
> 9 - 0002 - parse_clause.c

I am continuing to review 0003

10 - 0003
```
+	Assert(list_length(patternVariables) == list_length(defineClause));
```

Is this assert true? From what I learned, pattern length doesn’t have to equal to define length. For example, I got an example from [1]:

```
Example 4
-- This example has three different patterns.
-- Comment two of them, to get error-free query.
SELECT company, price_date, price
  FROM stock_price
    MATCH_RECOGNIZE (
       partition by company
       order by price_date
       all rows per match
       pattern ( limit_50  up   up* down  down*  )
       define
           limit_50 as price <= 50.00,
           up   as price > prev(price),
           down as price < prev(price)
    )
   WHERE company = 'B'
   ORDER BY price_date;
```

In this example, pattern has 5 elements and define has only 3 elements.

11 - 0004 - plannodes.h
```
+	/* Row Pattern Recognition AFTER MACH SKIP clause */
+	RPSkipTo	rpSkipTo;		/* Row Pattern Skip To type */
```

Typo: MACH -> MATCH

I’d stop here, and continue 0005 tomorrow.


[1] https://link.springer.com/article/10.1007/s13222-022-00404-3

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: Row pattern recognition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Nov 20, 2025, at 15:33, Chao Li  wrote:
> 
> 
> I’d stop here, and continue 0005 tomorrow.
> 

I reviewed 0005 today. I'm still not very familiar with the executor code, so going through 0005 has also been a valuable learning process for me.

12 - 0005 - nodeWindowAgg.c
```
+	if (string_set_get_size(str_set) == 0)
+	{
+		/* no match found in the first row */
+		register_reduced_frame_map(winstate, original_pos, RF_UNMATCHED);
+		destroyStringInfo(encoded_str);
+		return;
+	}
```

encoded_str should also be destroyed if not entering the “if” clause.

13 - 0005 - nodeWindowAgg.c
```
static
int
do_pattern_match(char *pattern, char *encoded_str, int len)
{
static regex_t *regcache = NULL;
static regex_t preg;
static char patbuf[1024]; /* most recent 'pattern' is cached here */
```

Using static variable in executor seems something I have never seen, which may persistent data across queries. I think usually per query data are stored in state structures.

14 - 0005 - nodeWindowAgg.c
```
+		MemoryContext oldContext = MemoryContextSwitchTo(TopMemoryContext);
+
+		if (regcache != NULL)
+			pg_regfree(regcache);	/* free previous re */
+
+		/* we need to convert to char to pg_wchar */
+		plen = strlen(pattern);
+		data = (pg_wchar *) palloc((plen + 1) * sizeof(pg_wchar));
+		data_len = pg_mb2wchar_with_len(pattern, data, plen);
+		/* compile re */
+		sts = pg_regcomp(&preg, /* compiled re */
+						 data,	/* target pattern */
+						 data_len,	/* length of pattern */
+						 cflags,	/* compile option */
+						 C_COLLATION_OID	/* collation */
+			);
+		pfree(data);
+
+		MemoryContextSwitchTo(oldContext);
```

Here in do_pattern_match, it switches to top memory context and compiles the re and stores to “preg". Based on the comment of pg_regcomp:
```
/*
* pg_regcomp - compile regular expression
*
* Note: on failure, no resources remain allocated, so pg_regfree()
* need not be applied to re.
*/
int
pg_regcomp(regex_t *re,
const chr *string,
size_t len,
int flags,
Oid collation)
```

“preg” should be freed by pg_regfree(), given the memory is allocated in TopMemoryContext, this looks like a memory leak.

Okay, I’d stop here and continue to review 0006 next week.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Chao,

>> On Nov 18, 2025, at 19:19, Vik Fearing  wrote:
>> 
>> 
>> Because of position. Without making DEFINE a reserved keyword, how do you know that it isn't another variable in the PATTERN clause?
>> 
> 
> Ah, thanks for the clarification. Now I got it.
> 
> I’m continue to review 0002.

Thanks for the review!

> 5 - 0002 - parse_clause.c
> ```
> +		ereport(ERROR,
> +				(errcode(ERRCODE_SYNTAX_ERROR),
> +				 errmsg("FRAME must start at current row when row patttern recognition is used")));
> ```
> 
> Nit typo: patttern -> pattern

Will fix (this involves regression test change because this changes
the ERROR messages in the expected file).

> 6 - 0002 - parse_clause.c
> ```
> +	/* DEFINE variable name initials */
> +	static char *defineVariableInitials = "abcdefghijklmnopqrstuvwxyz”;
> ```
> 
> This string can also be const, so “static const char *”

Agreed. Will fix.

> 7 - 0002 - parse_clause.c
> ```
> +	/*
> +	 * Create list of row pattern DEFINE variable name's initial. We assign
> +	 * [a-z] to them (up to 26 variable names are allowed).
> +	 */
> +	restargets = NIL;
> +	i = 0;
> +	initialLen = strlen(defineVariableInitials);
> +
> +	foreach(lc, windef->rpCommonSyntax->rpDefs)
> +	{
> +		char		initial[2];
> +
> +		restarget = (ResTarget *) lfirst(lc);
> +		name = restarget->name;
> ```
> 
> Looks like “name” is not used inside “foreach”.

Oops. Will fix.

> 8 - 0002 - parse_clause.c
> ```
> +	/*
> +	 * Create list of row pattern DEFINE variable name's initial. We assign
> +	 * [a-z] to them (up to 26 variable names are allowed).
> +	 */
> +	restargets = NIL;
> +	i = 0;
> +	initialLen = strlen(defineVariableInitials);
> +
> +	foreach(lc, windef->rpCommonSyntax->rpDefs)
> +	{
> +		char		initial[2];
> ```
> 
> I guess this “foreach” for build initial list can be combined into the previous foreach loop of checking duplication. If an def has no dup, then assign an initial to it.

You are right. Will change.

> 9 - 0002 - parse_clause.c
> ```
> +static void
> +transformPatternClause(ParseState *pstate, WindowClause *wc,
> +					   WindowDef *windef)
> +{
> +	ListCell   *lc;
> +
> +	/*
> +	 * Row Pattern Common Syntax clause exists?
> +	 */
> +	if (windef->rpCommonSyntax == NULL)
> +		return;
> ```
> 
> Checking  (windef->rpCommonSyntax == NULL) seems a duplicate, because transformPatternClause() is only called by transformRPR(), and transformRPR() has done the check.

Yeah. transformDefineClause() already does the similar check using
Assert. What about using Assert in transPatternClause() as well?

	Assert(windef->rpCommonSyntax != NULL);

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Nov 21, 2025, at 13:25, Chao Li  wrote:
> 
> 
> Okay, I’d stop here and continue to review 0006 next week.
> 

I just finished reviewing 0006, and see some problems:

15 - 0006 - select.sgml
```
+[ row_pattern_common_syntax ]
```

row_pattern_common_syntax doesn’t look like a good name. I searched over the docs, and couldn't find a name suffixed by “_syntax”. I think we can just name it as “row_pattern_recognition_clause” or a shorter name just “row_pattern”.

16 - 0006 - select.sgml
```
+ 
+ [ AFTER MATCH SKIP PAST LAST ROW | AFTER MATCH SKIP TO NEXT ROW ]
``

I think the two values are mutually exclusive, so curly braces should added surround them:

[ { AFTER MATCH SKIP PAST LAST ROW | AFTER MATCH SKIP TO NEXT ROW } ]

[] means optional, and {} means choose one from all alternatives.

17 - 0006 - select.sgml
```
PATTERN pattern_variable_name[+] [, ...]
```

PATTERN definition should be placed inside (), here you missed ()

18 - 0006 - select.sgml
The same code as 17, pattern_variable_name[+], do you only put “+” here, I think SQL allows a lot of pattern quantifiers. From 0001, gram.y, looks like +, * and ? Are supported in this patch. So, maybe we can do:

```
PATTERN ( pattern_element, [pattern_element …] )

and pattern_element = variable name optionally followed by quantifier (reference to somewhere introducing pattern quantifier).
```

19 - 0006 - select.sgml

I don’t see INITIAL and SEEK are described. Even if SEEK is not supported currently, it’s worthy mentioning that.

20 - 0006 - select.sgml
```
+    after a match found. With AFTER MATCH SKIP PAST LAST
+    ROW (the default) next row position is next to the last row of
```

21 - 0006 - select.sgml
```
 [ frame_clause ]
+[ row_pattern_common_syntax ]
```

Looks like row_pattern_common_syntax belongs to frame_clause, and you have lately added row_pattern_common_syntax to frame_clause:
```
 
-{ RANGE | ROWS | GROUPS } frame_start [ frame_exclusion ]
-{ RANGE | ROWS | GROUPS } BETWEEN frame_start AND frame_end [ frame_exclusion ]
+{ RANGE | ROWS | GROUPS } frame_start [ frame_exclusion ] [row_pattern_common_syntax]
+{ RANGE | ROWS | GROUPS } BETWEEN frame_start AND frame_end [ frame_exclusion ] [row_pattern_common_syntax]
 
```

So I guess row_pattern_common_syntax after frame_clause should not be added.

22 - 0006 - advance.sgml
```

DEFINE
 LOWPRICE AS price <= 100,
 UP AS price > PREV(price),
 DOWN AS price < PREV(price)


    Note that PREV returns the price column in the
```

In the “Note” line, “price” refers to a column from above example, so I think it should be tagged by . This comment applies to multiple places.

I will proceed 0007 tomorrow.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Chao,

Thank you for the review!

>> On Nov 20, 2025, at 15:33, Chao Li  wrote:
>> 
>> 
>> I’d stop here, and continue 0005 tomorrow.
>> 
> 
> I reviewed 0005 today. I'm still not very familiar with the executor code, so going through 0005 has also been a valuable learning process for me.
> 
> 12 - 0005 - nodeWindowAgg.c
> ```
> +	if (string_set_get_size(str_set) == 0)
> +	{
> +		/* no match found in the first row */
> +		register_reduced_frame_map(winstate, original_pos, RF_UNMATCHED);
> +		destroyStringInfo(encoded_str);
> +		return;
> +	}
> ```
> 
> encoded_str should also be destroyed if not entering the “if” clause.

Subsequent string_set_discard() will free encode_str since encoded_str
is part of str_set. So no need to call destroyStringInfo(encoded_str)
in not entering "if" clause.

	string_set_discard(str_set);

So I think this is Ok.

> 13 - 0005 - nodeWindowAgg.c
> ```
> static
> int
> do_pattern_match(char *pattern, char *encoded_str, int len)
> {
> static regex_t *regcache = NULL;
> static regex_t preg;
> static char patbuf[1024]; /* most recent 'pattern' is cached here */
> ```
> 
> Using static variable in executor seems something I have never seen, which may persistent data across queries. I think usually per query data are stored in state structures.

Yeah, such a usage maybe rare. But I hesitate to store the data
(regex_t) in WindowAggState because:

(1) it bloats WindowAggState which we want to avoid if possible
(2) it requires execnodes.h to include regex.h. (maybe this itself is harmless, I am not sure)

> 14 - 0005 - nodeWindowAgg.c
> ```
> +		MemoryContext oldContext = MemoryContextSwitchTo(TopMemoryContext);
> +
> +		if (regcache != NULL)
> +			pg_regfree(regcache);	/* free previous re */
> +
> +		/* we need to convert to char to pg_wchar */
> +		plen = strlen(pattern);
> +		data = (pg_wchar *) palloc((plen + 1) * sizeof(pg_wchar));
> +		data_len = pg_mb2wchar_with_len(pattern, data, plen);
> +		/* compile re */
> +		sts = pg_regcomp(&preg, /* compiled re */
> +						 data,	/* target pattern */
> +						 data_len,	/* length of pattern */
> +						 cflags,	/* compile option */
> +						 C_COLLATION_OID	/* collation */
> +			);
> +		pfree(data);
> +
> +		MemoryContextSwitchTo(oldContext);
> ```
> 
> Here in do_pattern_match, it switches to top memory context and compiles the re and stores to “preg". Based on the comment of pg_regcomp:
> ```
> /*
> * pg_regcomp - compile regular expression
> *
> * Note: on failure, no resources remain allocated, so pg_regfree()
> * need not be applied to re.
> */
> int
> pg_regcomp(regex_t *re,
> const chr *string,
> size_t len,
> int flags,
> Oid collation)
> ```
> 
> “preg” should be freed by pg_regfree(), given the memory is allocated in TopMemoryContext, this looks like a memory leak.

I admit current patch leaves the memory unfreed even after a query
finishes. What about adding something like:

static void do_pattern_match_end(void)
{
	if (regcache != NULL)
		pg_regfree(regcache);
}

and let ExecEndWindowAgg() call it?

> Okay, I’d stop here and continue to review 0006 next week.
> 
> Best regards,
> --
> Chao Li (Evan)
> HighGo Software Co., Ltd.
> https://www.highgo.com/
> 
> 
> 
> 


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Chao,

>> On Nov 21, 2025, at 13:25, Chao Li  wrote:
>> 
>> 
>> Okay, I’d stop here and continue to review 0006 next week.
>> 
> 
> I just finished reviewing 0006, and see some problems:
> 
> 15 - 0006 - select.sgml
> ```
> +[ row_pattern_common_syntax ]
> ```
> 
> row_pattern_common_syntax doesn’t look like a good name. I searched over the docs, and couldn't find a name suffixed by “_syntax”. I think we can just name it as “row_pattern_recognition_clause” or a shorter name just “row_pattern”.

I believe these names are based on the SQL standard. All syntax
components do not necessary be suffixed by "clause". For example
in select.sgml,

[ WITH [ RECURSIVE ] with_query [, ...] ]
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
    [ { * | expression [ [ AS ] output_name ] } [, ...] ]
    [ FROM from_item [, ...] ]
    [ WHERE condition ]
    [ GROUP BY { ALL | [ ALL | DISTINCT ] grouping_element [, ...] } ]
    [ HAVING condition ]
    [ WINDOW window_name AS ( window_definition ) [, ...] ]

"window_definition" comes from the standard and does not suffixed by
"clause". If you look into the window clause definition in the
standard, you will see:

 ::=
WINDOW 
 ::=
 [ {   }... ]

So the usage of terms in our document matches the standard. Likewise,
we see the definition of row pattern common syntax in the stabdard:

 ::=
WINDOW 
 ::=
 [ {   }... ]
 ::=
 AS 
 ::=

 ::=
  
 ::=
[  ]
[  ]
[  ]
[  ]
:
:
 ::=
[  ]
 
[  ]
[  ]

So I think "row pattern common syntax" is perfectly appropriate
name. If we change it to “row_pattern_recognition_clause”, it will
just bring confusion.  In the standard “row pattern recognition
clause” is defined RPR in FROM clause.

SELECT ... FROM table MATCH RECOGNIZE (....);

Here MATCH RECOGNIZE (....) is the “row pattern recognition clause”.

> 16 - 0006 - select.sgml
> ```
> + 
> + [ AFTER MATCH SKIP PAST LAST ROW | AFTER MATCH SKIP TO NEXT ROW ]
> ``
> 
> I think the two values are mutually exclusive, so curly braces should added surround them:
> 
> [ { AFTER MATCH SKIP PAST LAST ROW | AFTER MATCH SKIP TO NEXT ROW } ]
> 
> [] means optional, and {} means choose one from all alternatives.

Agreed. Will fix.

> 17 - 0006 - select.sgml
> ```
> PATTERN pattern_variable_name[+] [, ...]
> ```
> 
> PATTERN definition should be placed inside (), here you missed ()

Good catch. Will fix.

> 18 - 0006 - select.sgml
> The same code as 17, pattern_variable_name[+], do you only put “+” here, I think SQL allows a lot of pattern quantifiers. From 0001, gram.y, looks like +, * and ? Are supported in this patch. So, maybe we can do:
> 
> ```
> PATTERN ( pattern_element, [pattern_element …] )
> 
> and pattern_element = variable name optionally followed by quantifier (reference to somewhere introducing pattern quantifier).
> ```

Currently only *, + and ? are supported and I don't think it's worth
to invent "pattern_element".  (Actually the standard defines much more
complex syntax for PATTERN. I think we can revisit this once the basic
support for quantifier *,+ and ? are brought in the core PostgreSQL
code.

> 19 - 0006 - select.sgml
> 
> I don’t see INITIAL and SEEK are described. Even if SEEK is not supported currently, it’s worthy mentioning that.

Agreed. Will fix.

> 20 - 0006 - select.sgml
> ```
> +    after a match found. With AFTER MATCH SKIP PAST LAST
> +    ROW (the default) next row position is next to the last row of
> ```
> 
> 21 - 0006 - select.sgml
> ```
>  [ frame_clause ]
> +[ row_pattern_common_syntax ]
> ```
> 
> Looks like row_pattern_common_syntax belongs to frame_clause, and you have lately added row_pattern_common_syntax to frame_clause:
> ```
>  
> -{ RANGE | ROWS | GROUPS } frame_start [ frame_exclusion ]
> -{ RANGE | ROWS | GROUPS } BETWEEN frame_start AND frame_end [ frame_exclusion ]
> +{ RANGE | ROWS | GROUPS } frame_start [ frame_exclusion ] [row_pattern_common_syntax]
> +{ RANGE | ROWS | GROUPS } BETWEEN frame_start AND frame_end [ frame_exclusion ] [row_pattern_common_syntax]
>  
> ```
> 
> So I guess row_pattern_common_syntax after frame_clause should not be added.

Yes, row_pattern_common_syntax belongs to frame_clause. Will fix.

> 22 - 0006 - advance.sgml
> ```
> 
> DEFINE
>  LOWPRICE AS price <= 100,
>  UP AS price > PREV(price),
>  DOWN AS price < PREV(price)
> 
> 
>     Note that PREV returns the price column in the
> ```
> 
> In the “Note” line, “price” refers to a column from above example, so I think it should be tagged by . This comment applies to multiple places.

You are right. Will fix.

> I will proceed 0007 tomorrow.

Thanks!

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Nov 24, 2025, at 08:59, Chao Li  wrote:
> 
> I will proceed 0007 tomorrow.

I just finished reviewing 0007 and 0008. This patch set really demonstrates the full lifecycle of adding a SQL feature, from changing the syntax in gram.y all the way down to the executor, including tests and docs. I learned a lot from it. Thanks!

23 - 0007

As you mentioned earlier, pattern regular expression support *, + and ?, but I don’t see ? is tested.

24 - 0007

I don’t see negative tests for unsupported quantifiers, like PATTERN (A+?).

25 - 0007
```
+-- basic test with none greedy pattern
```

Typo: “none greedy” -> non-greedy

No comment for 0008.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> I just finished reviewing 0007 and 0008. This patch set really demonstrates the full lifecycle of adding a SQL feature, from changing the syntax in gram.y all the way down to the executor, including tests and docs. I learned a lot from it. Thanks!

You are welcome!

> 23 - 0007
> 
> As you mentioned earlier, pattern regular expression support *, + and ?, but I don’t see ? is tested.

Good catch. I will add the test case. In the mean time I found a bug
with gram.y part which handles '?' quantifier.  gram.y can be
successfully compiled but there's no way to put '?' quantifier in a
SQL statement.  We cannot write directly "ColId '?'" like other
quantifier '*' and '+' in the grammer because '?' is not a "self"
token.  So we let '?' matches Op first then check if it's '?'  or
not. 

			| ColId Op
				{
					if (strcmp("?", $2))
						ereport(ERROR,
								errcode(ERRCODE_SYNTAX_ERROR),
								errmsg("unsupported quantifier"),
								parser_errposition(@2));

					$$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "?", (Node *)makeString($1), NULL, @1);
				}

Another bug was with executor (nodeWindowAgg.c). The code to check
greedy quantifiers missed the case '?'.

> 24 - 0007
> 
> I don’t see negative tests for unsupported quantifiers, like PATTERN (A+?).

I will add such test cases.

> 25 - 0007
> ```
> +-- basic test with none greedy pattern
> ```
> 
> Typo: “none greedy” -> non-greedy

Will fix.

> No comment for 0008.

Thanks again for the review. I will post v35 patch set soon.  Attached
is the diff from v34.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/doc/src/sgml/advanced.sgml b/doc/src/sgml/advanced.sgml
index 7514f2a3848..eec2a0a9346 100644
--- a/doc/src/sgml/advanced.sgml
+++ b/doc/src/sgml/advanced.sgml
@@ -559,13 +559,14 @@ DEFINE
  DOWN AS price < PREV(price)
 
 
-    Note that PREV returns the price column in the
-    previous row if it's called in a context of row pattern recognition. Thus
-    in the second line the definition variable "UP" is TRUE
-    when the price column in the current row is greater than the price column
-    in the previous row. Likewise, "DOWN" is TRUE when the
-    price column in the current row is lower than the price column in the
-    previous row.
+    Note that PREV returns the price
+    column in the previous row if it's called in a context of row pattern
+    recognition. Thus in the second line the definition variable "UP"
+    is TRUE when the price column in the current row is
+    greater than the price column in the previous row. Likewise, "DOWN"
+    is TRUE when the
+    price column in the current row is lower than
+    the price column in the previous row.
    
    
     Once DEFINE exists, PATTERN can be
@@ -624,10 +625,10 @@ FROM stock
    
     When a query involves multiple window functions, it is possible to write
     out each one with a separate OVER clause, but this is
-    duplicative and error-prone if the same windowing behavior is wanted
-    for several functions.  Instead, each windowing behavior can be named
-    in a WINDOW clause and then referenced in OVER.
-    For example:
+    duplicative and error-prone if the same windowing behavior is wanted for
+    several functions.  Instead, each windowing behavior can be named in
+    a WINDOW clause and then referenced
+    in OVER.  For example:
 
 
 SELECT sum(salary) OVER w, avg(salary) OVER w
diff --git a/doc/src/sgml/ref/select.sgml b/doc/src/sgml/ref/select.sgml
index 428bd4f7372..aebc797545e 100644
--- a/doc/src/sgml/ref/select.sgml
+++ b/doc/src/sgml/ref/select.sgml
@@ -937,7 +937,6 @@ WINDOW window_name AS ( expression [, ...] ]
 [ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ]
 [ frame_clause ]
-[ row_pattern_common_syntax ]
 
    
 
@@ -1097,8 +1096,9 @@ EXCLUDE NO OTHERS
     includes following subclauses.
 
 
-[ AFTER MATCH SKIP PAST LAST ROW | AFTER MATCH SKIP TO NEXT ROW ]
-PATTERN pattern_variable_name[+] [, ...]
+[ { AFTER MATCH SKIP PAST LAST ROW | AFTER MATCH SKIP TO NEXT ROW } ]
+[ INITIAL | SEEK ]
+PATTERN ( pattern_variable_name[*|+|?] [, ...] )
 DEFINE definition_varible_name AS expression [, ...]
 
     AFTER MATCH SKIP PAST LAST ROW or AFTER MATCH
@@ -1107,9 +1107,16 @@ DEFINE definition_varible_name AS <
     ROW (the default) next row position is next to the last row of
     previous match. On the other hand, with AFTER MATCH SKIP TO NEXT
     ROW next row position is always next to the last row of previous
-    match. DEFINE defines definition variables along with a
-    boolean expression. PATTERN defines a sequence of rows
-    that satisfies certain conditions using variables defined
+    match. INITIAL or SEEK defines how a
+    successful pattern matching starts from which row in a
+    frame. If INITIAL is specified, the match must start
+    from the first row in the frame. If SEEK is specified,
+    the set of matching rows do not necessarily start from the first row. The
+    default is INITIAL. Currently
+    only INITIAL is supported. DEFINE
+    defines definition variables along with a boolean
+    expression. PATTERN defines a sequence of rows that
+    satisfies certain conditions using variables defined
     in DEFINE clause. If the variable is not defined in
     the DEFINE clause, it is implicitly assumed following
     is defined in the DEFINE clause.
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index 9ce072434b4..d230f43e607 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -4754,7 +4754,7 @@ update_reduced_frame(WindowObject winobj, int64 pos)
 	{
 		char	   *quantifier = strVal(lfirst(lc1));
 
-		if (*quantifier == '+' || *quantifier == '*')
+		if (*quantifier == '+' || *quantifier == '*' || *quantifier == '?')
 		{
 			greedy = true;
 			break;
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index fccc26964a0..fdfe14d54e5 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -16825,7 +16825,21 @@ row_pattern_term:
 			ColId	{ $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "", (Node *)makeString($1), NULL, @1); }
 			| ColId '*'	{ $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "*", (Node *)makeString($1), NULL, @1); }
 			| ColId '+'	{ $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", (Node *)makeString($1), NULL, @1); }
-			| ColId '?'	{ $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "?", (Node *)makeString($1), NULL, @1); }
+/*
+ * '?' quantifier. We cannot write this directly "ColId '?'" because '?' is
+ * not a "self" token.  So we let '?' matches Op first then check if it's '?'
+ * or not.
+ */
+			| ColId Op
+				{
+					if (strcmp("?", $2))
+						ereport(ERROR,
+								errcode(ERRCODE_SYNTAX_ERROR),
+								errmsg("unsupported quantifier"),
+								parser_errposition(@2));
+
+					$$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "?", (Node *)makeString($1), NULL, @1);
+				}
 		;
 
 row_pattern_definition_list:
@@ -17982,6 +17996,7 @@ unreserved_keyword:
 			| DECLARE
 			| DEFAULTS
 			| DEFERRED
+			| DEFINE
 			| DEFINER
 			| DELETE_P
 			| DELIMITER
@@ -18402,7 +18417,6 @@ reserved_keyword:
 			| CURRENT_USER
 			| DEFAULT
 			| DEFERRABLE
-			| DEFINE
 			| DESC
 			| DISTINCT
 			| DO
diff --git a/src/backend/parser/parse_clause.c b/src/backend/parser/parse_clause.c
index 3521d2780e2..8e4dc732861 100644
--- a/src/backend/parser/parse_clause.c
+++ b/src/backend/parser/parse_clause.c
@@ -3920,7 +3920,7 @@ transformRPR(ParseState *pstate, WindowClause *wc, WindowDef *windef,
 	if ((wc->frameOptions & FRAMEOPTION_START_CURRENT_ROW) == 0)
 		ereport(ERROR,
 				(errcode(ERRCODE_SYNTAX_ERROR),
-				 errmsg("FRAME must start at current row when row patttern recognition is used")));
+				 errmsg("FRAME must start at current row when row pattern recognition is used")));
 
 	/* Transform AFTER MACH SKIP TO clause */
 	wc->rpSkipTo = windef->rpCommonSyntax->rpSkipTo;
@@ -3949,7 +3949,7 @@ transformDefineClause(ParseState *pstate, WindowClause *wc, WindowDef *windef,
 					  List **targetlist)
 {
 	/* DEFINE variable name initials */
-	static char *defineVariableInitials = "abcdefghijklmnopqrstuvwxyz";
+	static const char *defineVariableInitials = "abcdefghijklmnopqrstuvwxyz";
 
 	ListCell   *lc,
 			   *l;
@@ -3959,7 +3959,7 @@ transformDefineClause(ParseState *pstate, WindowClause *wc, WindowDef *windef,
 	List	   *defineClause;
 	char	   *name;
 	int			initialLen;
-	int			i;
+	int			numinitials;
 
 	/*
 	 * If Row Definition Common Syntax exists, DEFINE clause must exist. (the
@@ -4030,8 +4030,12 @@ transformDefineClause(ParseState *pstate, WindowClause *wc, WindowDef *windef,
 	 * equivalent.
 	 */
 	restargets = NIL;
+	numinitials = 0;
+	initialLen = strlen(defineVariableInitials);
 	foreach(lc, windef->rpCommonSyntax->rpDefs)
 	{
+		char		initial[2];
+
 		restarget = (ResTarget *) lfirst(lc);
 		name = restarget->name;
 
@@ -4071,26 +4075,12 @@ transformDefineClause(ParseState *pstate, WindowClause *wc, WindowDef *windef,
 								name),
 						 parser_errposition(pstate, exprLocation((Node *) r))));
 		}
-		restargets = lappend(restargets, restarget);
-	}
-	list_free(restargets);
-
-	/*
-	 * Create list of row pattern DEFINE variable name's initial. We assign
-	 * [a-z] to them (up to 26 variable names are allowed).
-	 */
-	restargets = NIL;
-	i = 0;
-	initialLen = strlen(defineVariableInitials);
-
-	foreach(lc, windef->rpCommonSyntax->rpDefs)
-	{
-		char		initial[2];
 
-		restarget = (ResTarget *) lfirst(lc);
-		name = restarget->name;
-
-		if (i >= initialLen)
+		/*
+		 * Create list of row pattern DEFINE variable name's initial. We
+		 * assign [a-z] to them (up to 26 variable names are allowed).
+		 */
+		if (numinitials >= initialLen)
 		{
 			ereport(ERROR,
 					(errcode(ERRCODE_SYNTAX_ERROR),
@@ -4099,12 +4089,16 @@ transformDefineClause(ParseState *pstate, WindowClause *wc, WindowDef *windef,
 					 parser_errposition(pstate,
 										exprLocation((Node *) restarget))));
 		}
-		initial[0] = defineVariableInitials[i++];
+		initial[0] = defineVariableInitials[numinitials++];
 		initial[1] = '\0';
 		wc->defineInitial = lappend(wc->defineInitial,
 									makeString(pstrdup(initial)));
+
+		restargets = lappend(restargets, restarget);
 	}
+	list_free(restargets);
 
+	/* turns a list of ResTarget's into a list of TargetEntry's */
 	defineClause = transformTargetList(pstate, windef->rpCommonSyntax->rpDefs,
 									   EXPR_KIND_RPR_DEFINE);
 
@@ -4120,6 +4114,8 @@ transformDefineClause(ParseState *pstate, WindowClause *wc, WindowDef *windef,
 /*
  * transformPatternClause
  *		Process PATTERN clause and return PATTERN clause in the raw parse tree
+ *
+ * windef->rpCommonSyntax must exist.
  */
 static void
 transformPatternClause(ParseState *pstate, WindowClause *wc,
@@ -4127,11 +4123,7 @@ transformPatternClause(ParseState *pstate, WindowClause *wc,
 {
 	ListCell   *lc;
 
-	/*
-	 * Row Pattern Common Syntax clause exists?
-	 */
-	if (windef->rpCommonSyntax == NULL)
-		return;
+	Assert(windef->rpCommonSyntax != NULL);
 
 	wc->patternVariable = NIL;
 	wc->patternRegexp = NIL;
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 9e17abbaec5..3cc0ce720b2 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -1621,7 +1621,7 @@ typedef struct WindowClause
 	Index		winref;			/* ID referenced by window functions */
 	/* did we copy orderClause from refname? */
 	bool		copiedOrder pg_node_attr(query_jumble_ignore);
-	/* Row Pattern AFTER MACH SKIP clause */
+	/* Row Pattern AFTER MATCH SKIP clause */
 	RPSkipTo	rpSkipTo;		/* Row Pattern Skip To type */
 	bool		initial;		/* true if  is
 								 * initial */
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index 7c60b9b44a8..89dc2a4b95a 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -129,7 +129,7 @@ PG_KEYWORD("default", DEFAULT, RESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("defaults", DEFAULTS, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("deferrable", DEFERRABLE, RESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("deferred", DEFERRED, UNRESERVED_KEYWORD, BARE_LABEL)
-PG_KEYWORD("define", DEFINE, RESERVED_KEYWORD, BARE_LABEL)
+PG_KEYWORD("define", DEFINE, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("definer", DEFINER, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("delete", DELETE_P, UNRESERVED_KEYWORD, BARE_LABEL)
 PG_KEYWORD("delimiter", DELIMITER, UNRESERVED_KEYWORD, BARE_LABEL)
diff --git a/src/test/regress/expected/rpr.out b/src/test/regress/expected/rpr.out
index 59cfed180e7..312b62fb489 100644
--- a/src/test/regress/expected/rpr.out
+++ b/src/test/regress/expected/rpr.out
@@ -165,7 +165,45 @@ SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER
  company2 | 07-10-2023 |  1300 |             |            | 
 (20 rows)
 
--- basic test with none greedy pattern
+-- basic test using PREV. Use '?'
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP? DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+ company  |   tdate    | price | first_value | last_value | nth_second 
+----------+------------+-------+-------------+------------+------------
+ company1 | 07-01-2023 |   100 |         100 |        140 | 07-02-2023
+ company1 | 07-02-2023 |   200 |             |            | 
+ company1 | 07-03-2023 |   150 |             |            | 
+ company1 | 07-04-2023 |   140 |             |            | 
+ company1 | 07-05-2023 |   150 |         150 |         90 | 07-06-2023
+ company1 | 07-06-2023 |    90 |             |            | 
+ company1 | 07-07-2023 |   110 |         110 |        120 | 07-08-2023
+ company1 | 07-08-2023 |   130 |             |            | 
+ company1 | 07-09-2023 |   120 |             |            | 
+ company1 | 07-10-2023 |   130 |             |            | 
+ company2 | 07-01-2023 |    50 |          50 |       1400 | 07-02-2023
+ company2 | 07-02-2023 |  2000 |             |            | 
+ company2 | 07-03-2023 |  1500 |             |            | 
+ company2 | 07-04-2023 |  1400 |             |            | 
+ company2 | 07-05-2023 |  1500 |        1500 |         60 | 07-06-2023
+ company2 | 07-06-2023 |    60 |             |            | 
+ company2 | 07-07-2023 |  1100 |        1100 |       1200 | 07-08-2023
+ company2 | 07-08-2023 |  1300 |             |            | 
+ company2 | 07-09-2023 |  1200 |             |            | 
+ company2 | 07-10-2023 |  1300 |             |            | 
+(20 rows)
+
+-- basic test with none-greedy pattern
 SELECT company, tdate, price, count(*) OVER w
  FROM stock
  WINDOW w AS (
@@ -927,7 +965,7 @@ SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER
 ERROR:  aggregate functions are not allowed in DEFINE
 LINE 11:   LOWPRICE AS price < count(*)
                                ^
--- FRAME must start at current row when row patttern recognition is used
+-- FRAME must start at current row when row pattern recognition is used
 SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
  FROM stock
  WINDOW w AS (
@@ -941,7 +979,7 @@ SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER
   UP AS price > PREV(price),
   DOWN AS price < PREV(price)
 );
-ERROR:  FRAME must start at current row when row patttern recognition is used
+ERROR:  FRAME must start at current row when row pattern recognition is used
 -- SEEK is not supported
 SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
  FROM stock
@@ -977,3 +1015,38 @@ SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER
   DOWN AS price < PREV(1)
 );
 ERROR:  row pattern navigation operation's argument must include at least one column reference
+-- Unsupported quantifier
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (START UP~ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(1),
+  DOWN AS price < PREV(1)
+);
+ERROR:  unsupported quantifier
+LINE 9:  PATTERN (START UP~ DOWN+)
+                          ^
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (START UP+? DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(1),
+  DOWN AS price < PREV(1)
+);
+ERROR:  unsupported quantifier
+LINE 9:  PATTERN (START UP+? DOWN+)
+                          ^
diff --git a/src/test/regress/sql/rpr.sql b/src/test/regress/sql/rpr.sql
index 47e67334994..ffcf5476198 100644
--- a/src/test/regress/sql/rpr.sql
+++ b/src/test/regress/sql/rpr.sql
@@ -75,7 +75,22 @@ SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER
   DOWN AS price < PREV(price)
 );
 
--- basic test with none greedy pattern
+-- basic test using PREV. Use '?'
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
+ nth_value(tdate, 2) OVER w AS nth_second
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ INITIAL
+ PATTERN (START UP? DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(price),
+  DOWN AS price < PREV(price)
+);
+
+-- basic test with none-greedy pattern
 SELECT company, tdate, price, count(*) OVER w
  FROM stock
  WINDOW w AS (
@@ -438,7 +453,7 @@ SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER
   LOWPRICE AS price < count(*)
 );
 
--- FRAME must start at current row when row patttern recognition is used
+-- FRAME must start at current row when row pattern recognition is used
 SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
  FROM stock
  WINDOW w AS (
@@ -484,3 +499,34 @@ SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER
   UP AS price > PREV(1),
   DOWN AS price < PREV(1)
 );
+
+-- Unsupported quantifier
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (START UP~ DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(1),
+  DOWN AS price < PREV(1)
+);
+
+SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w
+ FROM stock
+ WINDOW w AS (
+ PARTITION BY company
+ ORDER BY tdate
+ ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+ AFTER MATCH SKIP TO NEXT ROW
+ INITIAL
+ PATTERN (START UP+? DOWN+)
+ DEFINE
+  START AS TRUE,
+  UP AS price > PREV(1),
+  DOWN AS price < PREV(1)
+);

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Chao,

Any comment on this?

>> 13 - 0005 - nodeWindowAgg.c
>> ```
>> static
>> int
>> do_pattern_match(char *pattern, char *encoded_str, int len)
>> {
>> static regex_t *regcache = NULL;
>> static regex_t preg;
>> static char patbuf[1024]; /* most recent 'pattern' is cached here */
>> ```
>> 
>> Using static variable in executor seems something I have never seen, which may persistent data across queries. I think usually per query data are stored in state structures.
>
>Yeah, such a usage maybe rare. But I hesitate to store the data
>(regex_t) in WindowAggState because:
>
>(1) it bloats WindowAggState which we want to avoid if possible
>(2) it requires execnodes.h to include regex.h. (maybe this itself is harmless, I am not sure)
>
>> 14 - 0005 - nodeWindowAgg.c
>> ```
>> +		MemoryContext oldContext = MemoryContextSwitchTo(TopMemoryContext);
>> +
>> +		if (regcache != NULL)
>> +			pg_regfree(regcache);	/* free previous re */
>> +
>> +		/* we need to convert to char to pg_wchar */
>> +		plen = strlen(pattern);
>> +		data = (pg_wchar *) palloc((plen + 1) * sizeof(pg_wchar));
>> +		data_len = pg_mb2wchar_with_len(pattern, data, plen);
>> +		/* compile re */
>> +		sts = pg_regcomp(&preg, /* compiled re */
>> +						 data,	/* target pattern */
>> +						 data_len,	/* length of pattern */
>> +						 cflags,	/* compile option */
>> +						 C_COLLATION_OID	/* collation */
>> +			);
>> +		pfree(data);
>> +
>> +		MemoryContextSwitchTo(oldContext);
>> ```
>> 
>> Here in do_pattern_match, it switches to top memory context and compiles the re and stores to “preg". Based on the comment of pg_regcomp:
>> ```
>> /*
>> * pg_regcomp - compile regular expression
>> *
>> * Note: on failure, no resources remain allocated, so pg_regfree()
>> * need not be applied to re.
>> */
>> int
>> pg_regcomp(regex_t *re,
>> const chr *string,
>> size_t len,
>> int flags,
>> Oid collation)
>> ```
>> 
>> “preg” should be freed by pg_regfree(), given the memory is allocated in TopMemoryContext, this looks like a memory leak.
>
>I admit current patch leaves the memory unfreed even after a query
>finishes. What about adding something like:
>
>static void do_pattern_match_end(void)
>{
>	if (regcache != NULL)
>		pg_regfree(regcache);
>}
>
>and let ExecEndWindowAgg() call it?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Chao Li <li.evan.chao@gmail.com>
Дата:


> On Nov 27, 2025, at 11:10, Tatsuo Ishii  wrote:
> 
> Hi Chao,
> 
> Any comment on this?
> 
>>> 13 - 0005 - nodeWindowAgg.c
>>> ```
>>> static
>>> int
>>> do_pattern_match(char *pattern, char *encoded_str, int len)
>>> {
>>> static regex_t *regcache = NULL;
>>> static regex_t preg;
>>> static char patbuf[1024]; /* most recent 'pattern' is cached here */
>>> ```
>>> 
>>> Using static variable in executor seems something I have never seen, which may persistent data across queries. I think usually per query data are stored in state structures.
>> 
>> Yeah, such a usage maybe rare. But I hesitate to store the data
>> (regex_t) in WindowAggState because:
>> 
>> (1) it bloats WindowAggState which we want to avoid if possible
>> (2) it requires execnodes.h to include regex.h. (maybe this itself is harmless, I am not sure)

With the static function-scope variables, those data persist across queries, which is error prone. I am afraid that even if I let this pass, other reviewers might have the same concern.

Maybe define a sub structure, say WindowAggCache, and put a pointer of WindowAggCache in WindowAggState, and only allocate memory when a query needs to.

>> 
>>> 14 - 0005 - nodeWindowAgg.c
>>> ```
>>> + MemoryContext oldContext = MemoryContextSwitchTo(TopMemoryContext);
>>> +
>>> + if (regcache != NULL)
>>> + pg_regfree(regcache); /* free previous re */
>>> +
>>> + /* we need to convert to char to pg_wchar */
>>> + plen = strlen(pattern);
>>> + data = (pg_wchar *) palloc((plen + 1) * sizeof(pg_wchar));
>>> + data_len = pg_mb2wchar_with_len(pattern, data, plen);
>>> + /* compile re */
>>> + sts = pg_regcomp(&preg, /* compiled re */
>>> + data, /* target pattern */
>>> + data_len, /* length of pattern */
>>> + cflags, /* compile option */
>>> + C_COLLATION_OID /* collation */
>>> + );
>>> + pfree(data);
>>> +
>>> + MemoryContextSwitchTo(oldContext);
>>> ```
>>> 
>>> Here in do_pattern_match, it switches to top memory context and compiles the re and stores to “preg". Based on the comment of pg_regcomp:
>>> ```
>>> /*
>>> * pg_regcomp - compile regular expression
>>> *
>>> * Note: on failure, no resources remain allocated, so pg_regfree()
>>> * need not be applied to re.
>>> */
>>> int
>>> pg_regcomp(regex_t *re,
>>> const chr *string,
>>> size_t len,
>>> int flags,
>>> Oid collation)
>>> ```
>>> 
>>> “preg” should be freed by pg_regfree(), given the memory is allocated in TopMemoryContext, this looks like a memory leak.
>> 
>> I admit current patch leaves the memory unfreed even after a query
>> finishes. What about adding something like:
>> 
>> static void do_pattern_match_end(void)
>> {
>> if (regcache != NULL)
>> pg_regfree(regcache);
>> }
>> 
>> and let ExecEndWindowAgg() call it?
> 

I’m not sure. But I think if we move the data into WindowAggState, then I guess we don’t have to use TopmemoryContext here.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/






Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Chao,

Sorry, I missed this email.

>> 9 - 0002 - parse_clause.c
> 
> I am continuing to review 0003
> 
> 10 - 0003
> ```
> +	Assert(list_length(patternVariables) == list_length(defineClause));
> ```
> 
> Is this assert true? From what I learned, pattern length doesn’t have to equal to define length. For example, I got an example from [1]:

You are right. If PATTERN clause uses the same pattern variable more
than once (which is perfectly valid), the assertion fails. I will
remove the assersion and fix the subsequent forboth loop.

> ```
> Example 4
> -- This example has three different patterns.
> -- Comment two of them, to get error-free query.
> SELECT company, price_date, price
>   FROM stock_price
>     MATCH_RECOGNIZE (
>        partition by company
>        order by price_date
>        all rows per match
>        pattern ( limit_50  up   up* down  down*  )
>        define
>            limit_50 as price <= 50.00,
>            up   as price > prev(price),
>            down as price < prev(price)
>     )
>    WHERE company = 'B'
>    ORDER BY price_date;
> ```
> 
> In this example, pattern has 5 elements and define has only 3 elements.

Yes.

> 11 - 0004 - plannodes.h
> ```
> +	/* Row Pattern Recognition AFTER MACH SKIP clause */
> +	RPSkipTo	rpSkipTo;		/* Row Pattern Skip To type */
> ```
> 
> Typo: MACH -> MATCH

Will fix/

> I’d stop here, and continue 0005 tomorrow.

Thanks!

> [1] https://link.springer.com/article/10.1007/s13222-022-00404-3
> 
> Best regards,
> --
> Chao Li (Evan)
> HighGo Software Co., Ltd.
> https://www.highgo.com/
> 
> 
> 
> 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
>> On Nov 27, 2025, at 11:10, Tatsuo Ishii  wrote:
>> 
>> Hi Chao,
>> 
>> Any comment on this?
>> 
>>>> 13 - 0005 - nodeWindowAgg.c
>>>> ```
>>>> static
>>>> int
>>>> do_pattern_match(char *pattern, char *encoded_str, int len)
>>>> {
>>>> static regex_t *regcache = NULL;
>>>> static regex_t preg;
>>>> static char patbuf[1024]; /* most recent 'pattern' is cached here */
>>>> ```
>>>> 
>>>> Using static variable in executor seems something I have never seen, which may persistent data across queries. I think usually per query data are stored in state structures.
>>> 
>>> Yeah, such a usage maybe rare. But I hesitate to store the data
>>> (regex_t) in WindowAggState because:
>>> 
>>> (1) it bloats WindowAggState which we want to avoid if possible
>>> (2) it requires execnodes.h to include regex.h. (maybe this itself is harmless, I am not sure)
> 
> With the static function-scope variables, those data persist across queries, which is error prone. I am afraid that even if I let this pass, other reviewers might have the same concern.
> 
> Maybe define a sub structure, say WindowAggCache, and put a pointer of WindowAggCache in WindowAggState, and only allocate memory when a query needs to.
> 
>>> 
>>>> 14 - 0005 - nodeWindowAgg.c
>>>> ```
>>>> + MemoryContext oldContext = MemoryContextSwitchTo(TopMemoryContext);
>>>> +
>>>> + if (regcache != NULL)
>>>> + pg_regfree(regcache); /* free previous re */
>>>> +
>>>> + /* we need to convert to char to pg_wchar */
>>>> + plen = strlen(pattern);
>>>> + data = (pg_wchar *) palloc((plen + 1) * sizeof(pg_wchar));
>>>> + data_len = pg_mb2wchar_with_len(pattern, data, plen);
>>>> + /* compile re */
>>>> + sts = pg_regcomp(&preg, /* compiled re */
>>>> + data, /* target pattern */
>>>> + data_len, /* length of pattern */
>>>> + cflags, /* compile option */
>>>> + C_COLLATION_OID /* collation */
>>>> + );
>>>> + pfree(data);
>>>> +
>>>> + MemoryContextSwitchTo(oldContext);
>>>> ```
>>>> 
>>>> Here in do_pattern_match, it switches to top memory context and compiles the re and stores to “preg". Based on the comment of pg_regcomp:
>>>> ```
>>>> /*
>>>> * pg_regcomp - compile regular expression
>>>> *
>>>> * Note: on failure, no resources remain allocated, so pg_regfree()
>>>> * need not be applied to re.
>>>> */
>>>> int
>>>> pg_regcomp(regex_t *re,
>>>> const chr *string,
>>>> size_t len,
>>>> int flags,
>>>> Oid collation)
>>>> ```
>>>> 
>>>> “preg” should be freed by pg_regfree(), given the memory is allocated in TopMemoryContext, this looks like a memory leak.
>>> 
>>> I admit current patch leaves the memory unfreed even after a query
>>> finishes. What about adding something like:
>>> 
>>> static void do_pattern_match_end(void)
>>> {
>>> if (regcache != NULL)
>>> pg_regfree(regcache);
>>> }
>>> 
>>> and let ExecEndWindowAgg() call it?
>> 
> 
> I’m not sure. But I think if we move the data into WindowAggState, then I guess we don’t have to use TopmemoryContext here.

I decided to add new fields to WindowAggState:

	/* regular expression compiled result cache. Used for RPR. */
	char	   *patbuf;			/* pattern to be compiled */
	regex_t		preg;			/* compiled re pattern */

Then allocate the memory for them using
winstate->ss.ps.ps_ExprContext->ecxt_per_query_memory;

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
>> I just finished reviewing 0007 and 0008. This patch set really demonstrates the full lifecycle of adding a SQL feature, from changing the syntax in gram.y all the way down to the executor, including tests and docs. I learned a lot from it. Thanks!
> 
> You are welcome!
> 
>> 23 - 0007
>> 
>> As you mentioned earlier, pattern regular expression support *, + and ?, but I don’t see ? is tested.
> 
> Good catch. I will add the test case. In the mean time I found a bug
> with gram.y part which handles '?' quantifier.  gram.y can be
> successfully compiled but there's no way to put '?' quantifier in a
> SQL statement.  We cannot write directly "ColId '?'" like other
> quantifier '*' and '+' in the grammer because '?' is not a "self"
> token.  So we let '?' matches Op first then check if it's '?'  or
> not. 
> 
> 			| ColId Op
> 				{
> 					if (strcmp("?", $2))
> 						ereport(ERROR,
> 								errcode(ERRCODE_SYNTAX_ERROR),
> 								errmsg("unsupported quantifier"),
> 								parser_errposition(@2));
> 
> 					$$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "?", (Node *)makeString($1), NULL, @1);
> 				}
> 
> Another bug was with executor (nodeWindowAgg.c). The code to check
> greedy quantifiers missed the case '?'.
> 
>> 24 - 0007
>> 
>> I don’t see negative tests for unsupported quantifiers, like PATTERN (A+?).
> 
> I will add such test cases.
> 
>> 25 - 0007
>> ```
>> +-- basic test with none greedy pattern
>> ```
>> 
>> Typo: “none greedy” -> non-greedy
> 
> Will fix.
> 
>> No comment for 0008.
> 
> Thanks again for the review. I will post v35 patch set soon.  Attached
> is the diff from v34.

Attached are the v35 patches for Row pattern recognition.  Chao Li
reviewed v34 thoroughly. Thank you! v35 reflects the review
comments. Major differences from v34 include:

- Make "DEFINE" an unreserved keyword. Previously it was a reserved keyword.
- Refactor transformDefineClause() to make two foreach loops into single foreach loop.
- Make '?' quantifier in PATTERN work as advertised. Test for '?' quantifier is added too.
- Unsupported quantifier test added.
- Fix get_rule_define().
- Fix memory leak related to regcomp.
- Move regcomp compiled result cache from static data to WindowAggState.
- Fix several typos.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached are the v36 patches, just for rebasing.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
SQL/RPR Patch Review Report
============================

Patch: Row Pattern Recognition (SQL:2016)
Commitfest: https://commitfest.postgresql.org/patch/4460

Review Methodology:
  This review focused on quality assessment, not line-by-line code audit.
  Key code paths and quality issues were examined with surrounding context
  when concerns arose. Documentation files were reviewed with AI-assisted
  grammar and typo checking. Code coverage was measured using gcov and
  custom analysis tools.

Limitations:
  - Not a security audit or formal verification
  - Parser and executor internals reviewed at module level, not exhaustively
  - Performance characteristics not benchmarked


TABLE OF CONTENTS
-----------------

1. Executive Summary
2. Issues Found
   2.1 Critical / Major
   2.2 Minor Issues (Review Needed)
   2.3 Minor Issues (Style)
   2.4 Suggestions for Discussion
3. Test Coverage
   3.1 Covered Areas
   3.2 Untested Items
   3.3 Unimplemented Features (No Test Needed)
4. Code Coverage Analysis
   4.1 Overall Coverage
   4.2 Coverage by File
   4.3 Uncovered Code Risk Assessment
5. Commit Analysis
6. Recommendations
7. Conclusion


1. EXECUTIVE SUMMARY
--------------------

Overall assessment: GOOD

The SQL/RPR patch demonstrates solid implementation quality within its
defined scope. Code follows PostgreSQL coding standards (with minor style
issues), test coverage is comprehensive at 96.4%, and documentation is
thorough with only minor typos.

Rating by Area:
- Code Quality:     Good (PostgreSQL style compliant, 26 static style fixes recommended)
- Test Coverage:    Good (96.4% line coverage, 28 test cases)
- Documentation:    Good (Complete, 1 minor typo)
- Build/Regress:    Pass (make check-world, 753 tests passed)


2. ISSUES FOUND
---------------

2.1 Critical / Major

#1 [Code] Greedy pattern combinatorial explosion
   Pattern: PATTERN (A+ B+ C+) with DEFINE A AS TRUE, B AS TRUE, C AS TRUE
   Impact: Memory exhaustion or infinite wait
   Recommendation: Add work_mem-based memory limit (error on exceed)

   Evidence - No memory limit in current code:
   - nodeWindowAgg.c:5718-5722 string_set_init(): palloc() unconditional
   - nodeWindowAgg.c:5741-5750 string_set_add(): set_size *= 2; repalloc() unlimited
   - nodeWindowAgg.c:5095-5174 generate_patterns(): Triple loop, no limit

   Only work_mem usage in RPR (nodeWindowAgg.c:1297):
     winstate->buffer = tuplestore_begin_heap(false, false, work_mem);
   -> For tuple buffer, unrelated to pattern combination memory (StringSet)

2.2 Minor Issues (Review Needed)

#1 [Code] nodeWindowAgg.c:5849,5909,5912
   pos > NUM_ALPHABETS check - intent unclear, causes error at 28 PATTERN elements

   Reproduction:
   - PATTERN (A B C ... Z A) (27 elements) -> OK
   - PATTERN (A B C ... Z A B) (28 elements) -> ERROR "initial is not valid char: b"

2.3 Minor Issues (Style)

#1 [Code] nodeWindowAgg.c (25 blocks)
   #ifdef RPR_DEBUG -> recommend elog(DEBUG2, ...) or remove

#2 [Code] src/backend/executor/nodeWindowAgg.c
   static keyword on separate line (26 functions)

#3 [Code] src/backend/utils/adt/ruleutils.c
   Whitespace typo: "regexp !=NULL" -> "regexp != NULL"

#4 [Code] nodeWindowAgg.c:4619
   Error message case: "Unrecognized" -> "unrecognized" (PostgreSQL style)

#5 [Doc] doc/src/sgml/ref/select.sgml:1128
   Typo: "maximu" -> "maximum"

2.4 Suggestions for Discussion

#1 Incremental matching with streaming NFA redesign
   Benefits:
   - O(n) time complexity per row (current: exponential in worst case)
   - Bounded memory via state merging and context absorption
   - Natural extension for OR patterns, {n,m} quantifiers, nested groups
   - Enables MEASURES clause with incremental aggregates
   - Proven approach in CEP engines (Flink, Esper)


3. TEST COVERAGE
----------------

3.1 Covered Areas

- PATTERN clause: +, *, ? quantifiers (line 41, 71, 86)
- DEFINE clause: Variable conditions, auto-TRUE for missing (line 120-133)
- PREV/NEXT functions: Single argument (line 44, 173)
- AFTER MATCH SKIP: TO NEXT ROW (line 182), PAST LAST ROW (line 198)
- Aggregate integration: sum, avg, count, max, min (line 258-277)
- Window function integration: first_value, last_value, nth_value (line 34-35)
- JOIN/CTE: JOIN (line 313), WITH (line 324)
- View: VIEW creation, pg_get_viewdef (line 390-406)
- Error cases: 7 error scenarios (line 409-532)
- Large partition: 5000 row smoke test (line 360-387)
- ROWS BETWEEN offset: CURRENT ROW AND 2 FOLLOWING (line 244)

3.2 Untested Items

Feature                  Priority   Recommendation
-------------------------------------------------------------------------------
26 variable limit        Medium     Test 26 variables success, 27th variable error
NULL value handling      Low        Test PREV(col) where col or previous row is NULL

Sample test for 26 variable limit:

    -- Should fail with 27th variable (parser error, no table needed)
    SELECT * FROM (SELECT 1 AS x) t
    WINDOW w AS (
      ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      PATTERN (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
      DEFINE a AS TRUE, b AS TRUE, c AS TRUE, d AS TRUE, e AS TRUE, f AS TRUE,
             g AS TRUE, h AS TRUE, i AS TRUE, j AS TRUE, k AS TRUE, l AS TRUE,
             m AS TRUE, n AS TRUE, o AS TRUE, p AS TRUE, q AS TRUE, r AS TRUE,
             s AS TRUE, t AS TRUE, u AS TRUE, v AS TRUE, w AS TRUE, x AS TRUE,
             y AS TRUE, z AS TRUE, aa AS TRUE
    );
    -- ERROR: number of row pattern definition variable names exceeds 26

Sample test for NULL handling:

    CREATE TEMP TABLE stock_null (company TEXT, tdate DATE, price INTEGER);
    INSERT INTO stock_null VALUES ('c1', '2023-07-01', 100);
    INSERT INTO stock_null VALUES ('c1', '2023-07-02', NULL);  -- NULL in middle
    INSERT INTO stock_null VALUES ('c1', '2023-07-03', 200);
    INSERT INTO stock_null VALUES ('c1', '2023-07-04', 150);

    SELECT company, tdate, price, count(*) OVER w AS match_count
    FROM stock_null
    WINDOW w AS (
      PARTITION BY company
      ORDER BY tdate
      ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      PATTERN (START UP DOWN)
      DEFINE START AS TRUE, UP AS price > PREV(price), DOWN AS price < PREV(price)
    );
    -- Result: all rows show match_count = 0 (NULL breaks pattern matching)

3.3 Unimplemented Features (No Test Needed)

Per documentation (select.sgml:1133-1136):
- MEASURES clause: Not implemented
- SUBSET clause: Not implemented
- AFTER MATCH variants: Only SKIP TO NEXT ROW, PAST LAST ROW supported

Not in documentation, verified by testing:
- {n,m} quantifier: Parser error ("syntax error at or near {")
- (A|B) OR pattern: Not supported (parsed as single variable name "a|b")
- (A B)+ compound repetition: Parser accepts, but execution returns 0 matches


4. CODE COVERAGE ANALYSIS
-------------------------

4.1 Overall Coverage

96.4% (732 / 759 lines)

4.2 Coverage by File (major RPR-modified files)

nodeWindowAgg.c:    96.6% (560/580) - Pattern matching execution engine
parse_clause.c:     96.7% (88/91) - PATTERN/DEFINE analysis
ruleutils.c:        93.1% (54/58) - pg_get_viewdef output

4.3 Uncovered Code Risk Assessment

Total: 27 lines uncovered

Medium Risk (2 items) - Test addition recommended (see section 3.2):
- parse_clause.c:4093: transformDefineClause - 27th variable error
- nodeWindowAgg.c:5623: get_slots - null_slot for PREV at partition first row

Low Risk (25 items) - Defensive code / Unreachable:
- nodeWindowAgg.c:3074: attno_map_walker - Parser validates arg count
- nodeWindowAgg.c:3137-3138: rpr_navigation_walker - switch default
- nodeWindowAgg.c:3566: window_gettupleslot - Before mark position
- nodeWindowAgg.c:4289: WinGetFuncArgInFrame - isout flag
- nodeWindowAgg.c:4393: WinGetSlotInFrame - Boundary check
- nodeWindowAgg.c:4618-4619: row_is_in_reduced_frame - switch default
- nodeWindowAgg.c:4697: register_reduced_frame_map - pos < 0 check
- nodeWindowAgg.c:5007: search_str_set - NULL return continue
- nodeWindowAgg.c:5405: do_pattern_match - Regex compile error
- nodeWindowAgg.c:5435,5437-5438: do_pattern_match - Regex exec error
- nodeWindowAgg.c:5700: pattern_initial - Variable not found
- nodeWindowAgg.c:5776: string_set_get - Index range check
- nodeWindowAgg.c:5850: variable_pos_register - a-z range check
- nodeWindowAgg.c:5910: variable_pos_fetch - a-z range check
- nodeWindowAgg.c:5913: variable_pos_fetch - Index range check
- parse_clause.c:3989: transformDefineClause - A_Expr type check
- parse_clause.c:4145: transformPatternClause - A_Expr type check
- ruleutils.c:6904-6908: get_rule_windowspec - SKIP TO NEXT ROW output

Conclusion: Most uncovered code consists of defensive error handling or
code unreachable due to parser pre-validation. No security or functional risk.


5. COMMIT ANALYSIS
------------------

8 sequential commits:

Commit  Area            Files   +/-         Key Content
-------------------------------------------------------------------------------
1       Raw Parser      4       +174/-16    gram.y grammar (PATTERN/DEFINE)
2       Parse/Analysis  4       +277/-1     parse_clause.c analysis logic
3       Rewriter        1       +109/-0     pg_get_viewdef extension
4       Planner         5       +73/-3      WindowAgg plan node extension
5       Executor        4       +1,942/-11  CORE: Pattern matching engine (+1,850)
6       Docs            3       +192/-7     advanced.sgml, func-window.sgml
7       Tests           3       +1,585/-1   rpr.sql (532), rpr.out (1,052)
8       typedefs        1       +6/-0       pgindent support

Code Change Statistics:
- Total files: 25
- Lines added: 4,358
- Lines deleted: 39
- Net increase: +4,319 lines


6. RECOMMENDATIONS
------------------

6.1 Combinatorial Explosion Prevention (Major, Required)

Add work_mem-based memory limit for StringSet allocation.
Location: string_set_add() in nodeWindowAgg.c:5741-5750
Consistent with existing PostgreSQL approach (Hash Join, Sort, etc.)

6.2 Code Review Required (Minor, Decision Needed)

Location: nodeWindowAgg.c:5849,5909,5912
Issue: pos > NUM_ALPHABETS check intent unclear
Current: PATTERN with 28 elements causes error
Question: Is 27 element limit intentional?

6.3 Code Style Fixes (Minor)

- #ifdef RPR_DEBUG: Use elog(DEBUG2, ...) or remove (25 blocks)
- static keyword on separate line: 26 functions to fix
- Whitespace: "regexp !=NULL" -> "regexp != NULL"
- Error message case: "Unrecognized" -> "unrecognized"

6.4 Documentation Fixes (Minor)

- select.sgml: "maximu" -> "maximum"

6.5 Test Additions (Optional)

Black-box Tests (Functional):

Feature              Test Case                                    Priority
-------------------------------------------------------------------------------
Variable limit       26 variables success, 27 error               Medium
NULL boundary        PREV at partition first row                  Medium

White-box Tests (Coverage) - covered by above black-box tests:

File:Line                          Target Branch
-------------------------------------------------------------------------------
parse_clause.c:4093                Limit error branch (Variable limit test)
nodeWindowAgg.c:5623               null_slot usage (NULL boundary test)


7. CONCLUSION
-------------

Test Quality: GOOD

Core functionality is thoroughly tested with comprehensive error case coverage.

The patch is well-implemented within its defined scope. Identified issues include
one major concern (combinatorial explosion) and minor style/documentation items.

Recommended actions before commit:
1. Add work_mem-based memory limit for pattern combinations (required)
2. Clarify pos > NUM_ALPHABETS check intent (review needed)
3. Fix code style issues (optional but recommended)
4. Fix documentation typo (trivial)
5. Add tests for variable limit and NULL handling (optional)

Points for discussion (optional):
6. Incremental matching with streaming NFA redesign


Attachment:
- coverage.tgz (gcov HTML report, RPR-modified code only)


---
End of Report

2025년 9월 24일 (수) PM 7:36, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Attached are the v33 patches for Row pattern recognition.  The
difference from v32 is that the raw parse tree printing patch is not
included in v33. This is because now that we have
debug_print_raw_parse.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi hackers,

I ran Valgrind memcheck against the RPR (Row Pattern Recognition) implementation
to verify there are no memory issues introduced by the new Row Pattern Recognition feature.

== Test Environment ==

- PostgreSQL: 19devel (master branch)
- Valgrind: 3.22.0
- Platform: Linux x86_64 (RHEL 9)
- Tests executed: rpr.sql

== Executive Summary ==

  +----------------------------------------------------------+
  | RPR Implementation: NO MEMORY ISSUES DETECTED            |
  +----------------------------------------------------------+

All detected leaks originate from existing PostgreSQL core components.
No RPR-related functions appear in any leak stack traces.

== Backend Process 541453: Itemized Leak Analysis ==

Total: 37 bytes definitely lost in 1 block, 1 unique leak context

+================================================================================+
| #  | Bytes | Blocks | Allocator | Root Cause       | RPR? | Verdict           |
+================================================================================+
| 1  | 37    | 1      | strdup    | Postmaster init  | NO   | HARMLESS          |
+================================================================================+
     TOTAL: 37 bytes in 1 block
     RPR-RELATED LEAKS: 0

== RPR Verification ==

All leak stack traces were examined. Key functions NOT present:

  - ExecInitWindowAgg (RPR path)
  - row_pattern_initial, row_pattern_final
  - Any function from src/backend/executor/nodeWindowAgg.c (RPR code paths)
  - Any RPR-related parser functions (PATTERN, DEFINE)

The RPR tests exercised window functions with PATTERN, DEFINE clauses
(e.g., PATTERN (START UP+ DOWN+)), yet none of these code paths appear in leaks.

== Process Summary ==

+--------+----------------+-----------------+----------+--------------------+
| PID    | Type           | Definitely Lost | Errors   | Notes              |
+--------+----------------+-----------------+----------+--------------------+
| 541303 | postmaster     | 37 bytes        | 1        | strdup at startup  |
| 541453 | backend        | 37 bytes        | 12       | See above analysis |
| 541314 | checkpointer   | 37 bytes        | 1        | strdup at startup  |
| 541315 | bgwriter       | 37 bytes        | 1        | strdup at startup  |
| 541316 | walwriter      | 37 bytes        | 1        | strdup at startup  |
| 541317 | autovacuum     | 37 bytes        | 1        | strdup at startup  |
| 541318 | logical rep    | 37 bytes        | 1        | strdup at startup  |
| 541319 | syslogger      | 37 bytes        | 1        | strdup at startup  |
| Others | aux workers    | 37 bytes each   | 1 each   | strdup at startup  |
+--------+----------------+-----------------+----------+--------------------+

== Possibly Lost (LLVM JIT) ==

Additionally, ~16KB in ~165 blocks reported as "possibly lost" from LLVM JIT:
  - llvm::MDTuple, llvm::User allocations
  - Origin: llvm_compile_expr -> jit_compile_expr -> ExecReadyExpr
  - These are LLVM's internal caches, not PostgreSQL leaks

== Other Memory Errors ==

+--------------------------------------------------------------------------+
| NO memory access errors detected:                                        |
|   - Invalid read/write: 0                                                |
|   - Use of uninitialized value: 0                                        |
|   - Conditional jump on uninitialized value: 0                           |
|   - Syscall param errors: 0                                              |
|   - Overlap in memcpy/strcpy: 0                                          |
+--------------------------------------------------------------------------+

Suppressed errors (via valgrind.supp):
  - 541453 (backend): 46 errors from 3 contexts suppressed
  - Other processes: ~0 errors each suppressed

Suppression rules in valgrind.supp (12 categories):
  1. Padding        - write() syscalls with uninitialized struct padding
  2. CRC            - CRC32 calculation on padded buffers
  3. Overlap        - memcpy overlap in bootstrap/relmap
  4. glibc          - Dynamic loader internals
  5. Regex/Pattern  - RE_compile_and_cache, patternsel
  6. Planner        - query_planner memcpy overlap
  7. Cache          - RelCache, CatCache, TypeCache possible leaks
  8. XLogReader     - WAL reader allocations
  9. Parallel       - ParallelWorkerMain allocations
  10. AutoVacuum    - AutoVacWorkerMain allocations
  11. GUC/Backend   - set_config_option, InitPostgres
  12. PL/pgSQL      - plpgsql_compile, SPI_prepare, CachedPlan

All suppressed errors are known, harmless PostgreSQL behaviors.
See attached valgrind.supp for details.

== Conclusion ==

The RPR implementation introduces NO memory leaks. All detected issues
are pre-existing PostgreSQL behaviors related to:

  1. Postmaster startup allocations
  2. LLVM JIT internal caching

These are by-design patterns that trade minimal memory for performance.

== Files Attached ==

- valgrind.supp: Suppression file used for this test
- 541303.log: Postmaster log
- 541453.log: Backend log with full leak details (56KB)
- 5413xx.log: Auxiliary process logs

--
Regards

2025년 12월 23일 (화) PM 10:28, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Attached are the v36 patches, just for rebasing.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson Choi,

> Hi hackers,
> 
> I ran Valgrind memcheck against the RPR (Row Pattern Recognition)
> implementation
> to verify there are no memory issues introduced by the new Row Pattern
> Recognition feature.

Thanks for the test!

> == Conclusion ==
> 
> The RPR implementation introduces NO memory leaks.

Glad to hear that.
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

Thank you for the review! I will take care the issues (it will take
sometime).

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

> SQL/RPR Patch Review Report
> ============================
> 
> Patch: Row Pattern Recognition (SQL:2016)
> Commitfest: https://commitfest.postgresql.org/patch/4460
> 
> Review Methodology:
>   This review focused on quality assessment, not line-by-line code audit.
>   Key code paths and quality issues were examined with surrounding context
>   when concerns arose. Documentation files were reviewed with AI-assisted
>   grammar and typo checking. Code coverage was measured using gcov and
>   custom analysis tools.
> 
> Limitations:
>   - Not a security audit or formal verification
>   - Parser and executor internals reviewed at module level, not exhaustively
>   - Performance characteristics not benchmarked
> 
> 
> TABLE OF CONTENTS
> -----------------
> 
> 1. Executive Summary
> 2. Issues Found
>    2.1 Critical / Major
>    2.2 Minor Issues (Review Needed)
>    2.3 Minor Issues (Style)
>    2.4 Suggestions for Discussion
> 3. Test Coverage
>    3.1 Covered Areas
>    3.2 Untested Items
>    3.3 Unimplemented Features (No Test Needed)
> 4. Code Coverage Analysis
>    4.1 Overall Coverage
>    4.2 Coverage by File
>    4.3 Uncovered Code Risk Assessment
> 5. Commit Analysis
> 6. Recommendations
> 7. Conclusion
> 
> 
> 1. EXECUTIVE SUMMARY
> --------------------
> 
> Overall assessment: GOOD
> 
> The SQL/RPR patch demonstrates solid implementation quality within its
> defined scope. Code follows PostgreSQL coding standards (with minor style
> issues), test coverage is comprehensive at 96.4%, and documentation is
> thorough with only minor typos.
> 
> Rating by Area:
> - Code Quality:     Good (PostgreSQL style compliant, 26 static style fixes
> recommended)
> - Test Coverage:    Good (96.4% line coverage, 28 test cases)
> - Documentation:    Good (Complete, 1 minor typo)
> - Build/Regress:    Pass (make check-world, 753 tests passed)
> 
> 
> 2. ISSUES FOUND
> ---------------
> 
> 2.1 Critical / Major
> 
> #1 [Code] Greedy pattern combinatorial explosion
>    Pattern: PATTERN (A+ B+ C+) with DEFINE A AS TRUE, B AS TRUE, C AS TRUE
>    Impact: Memory exhaustion or infinite wait
>    Recommendation: Add work_mem-based memory limit (error on exceed)
> 
>    Evidence - No memory limit in current code:
>    - nodeWindowAgg.c:5718-5722 string_set_init(): palloc() unconditional
>    - nodeWindowAgg.c:5741-5750 string_set_add(): set_size *= 2; repalloc()
> unlimited
>    - nodeWindowAgg.c:5095-5174 generate_patterns(): Triple loop, no limit
> 
>    Only work_mem usage in RPR (nodeWindowAgg.c:1297):
>      winstate->buffer = tuplestore_begin_heap(false, false, work_mem);
>    -> For tuple buffer, unrelated to pattern combination memory (StringSet)
> 
> 2.2 Minor Issues (Review Needed)
> 
> #1 [Code] nodeWindowAgg.c:5849,5909,5912
>    pos > NUM_ALPHABETS check - intent unclear, causes error at 28 PATTERN
> elements
> 
>    Reproduction:
>    - PATTERN (A B C ... Z A) (27 elements) -> OK
>    - PATTERN (A B C ... Z A B) (28 elements) -> ERROR "initial is not valid
> char: b"
> 
> 2.3 Minor Issues (Style)
> 
> #1 [Code] nodeWindowAgg.c (25 blocks)
>    #ifdef RPR_DEBUG -> recommend elog(DEBUG2, ...) or remove
> 
> #2 [Code] src/backend/executor/nodeWindowAgg.c
>    static keyword on separate line (26 functions)
> 
> #3 [Code] src/backend/utils/adt/ruleutils.c
>    Whitespace typo: "regexp !=NULL" -> "regexp != NULL"
> 
> #4 [Code] nodeWindowAgg.c:4619
>    Error message case: "Unrecognized" -> "unrecognized" (PostgreSQL style)
> 
> #5 [Doc] doc/src/sgml/ref/select.sgml:1128
>    Typo: "maximu" -> "maximum"
> 
> 2.4 Suggestions for Discussion
> 
> #1 Incremental matching with streaming NFA redesign
>    Benefits:
>    - O(n) time complexity per row (current: exponential in worst case)
>    - Bounded memory via state merging and context absorption
>    - Natural extension for OR patterns, {n,m} quantifiers, nested groups
>    - Enables MEASURES clause with incremental aggregates
>    - Proven approach in CEP engines (Flink, Esper)
> 
> 
> 3. TEST COVERAGE
> ----------------
> 
> 3.1 Covered Areas
> 
> - PATTERN clause: +, *, ? quantifiers (line 41, 71, 86)
> - DEFINE clause: Variable conditions, auto-TRUE for missing (line 120-133)
> - PREV/NEXT functions: Single argument (line 44, 173)
> - AFTER MATCH SKIP: TO NEXT ROW (line 182), PAST LAST ROW (line 198)
> - Aggregate integration: sum, avg, count, max, min (line 258-277)
> - Window function integration: first_value, last_value, nth_value (line
> 34-35)
> - JOIN/CTE: JOIN (line 313), WITH (line 324)
> - View: VIEW creation, pg_get_viewdef (line 390-406)
> - Error cases: 7 error scenarios (line 409-532)
> - Large partition: 5000 row smoke test (line 360-387)
> - ROWS BETWEEN offset: CURRENT ROW AND 2 FOLLOWING (line 244)
> 
> 3.2 Untested Items
> 
> Feature                  Priority   Recommendation
> -------------------------------------------------------------------------------
> 26 variable limit        Medium     Test 26 variables success, 27th
> variable error
> NULL value handling      Low        Test PREV(col) where col or previous
> row is NULL
> 
> Sample test for 26 variable limit:
> 
>     -- Should fail with 27th variable (parser error, no table needed)
>     SELECT * FROM (SELECT 1 AS x) t
>     WINDOW w AS (
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       PATTERN (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
>       DEFINE a AS TRUE, b AS TRUE, c AS TRUE, d AS TRUE, e AS TRUE, f AS
> TRUE,
>              g AS TRUE, h AS TRUE, i AS TRUE, j AS TRUE, k AS TRUE, l AS
> TRUE,
>              m AS TRUE, n AS TRUE, o AS TRUE, p AS TRUE, q AS TRUE, r AS
> TRUE,
>              s AS TRUE, t AS TRUE, u AS TRUE, v AS TRUE, w AS TRUE, x AS
> TRUE,
>              y AS TRUE, z AS TRUE, aa AS TRUE
>     );
>     -- ERROR: number of row pattern definition variable names exceeds 26
> 
> Sample test for NULL handling:
> 
>     CREATE TEMP TABLE stock_null (company TEXT, tdate DATE, price INTEGER);
>     INSERT INTO stock_null VALUES ('c1', '2023-07-01', 100);
>     INSERT INTO stock_null VALUES ('c1', '2023-07-02', NULL);  -- NULL in
> middle
>     INSERT INTO stock_null VALUES ('c1', '2023-07-03', 200);
>     INSERT INTO stock_null VALUES ('c1', '2023-07-04', 150);
> 
>     SELECT company, tdate, price, count(*) OVER w AS match_count
>     FROM stock_null
>     WINDOW w AS (
>       PARTITION BY company
>       ORDER BY tdate
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       PATTERN (START UP DOWN)
>       DEFINE START AS TRUE, UP AS price > PREV(price), DOWN AS price <
> PREV(price)
>     );
>     -- Result: all rows show match_count = 0 (NULL breaks pattern matching)
> 
> 3.3 Unimplemented Features (No Test Needed)
> 
> Per documentation (select.sgml:1133-1136):
> - MEASURES clause: Not implemented
> - SUBSET clause: Not implemented
> - AFTER MATCH variants: Only SKIP TO NEXT ROW, PAST LAST ROW supported
> 
> Not in documentation, verified by testing:
> - {n,m} quantifier: Parser error ("syntax error at or near {")
> - (A|B) OR pattern: Not supported (parsed as single variable name "a|b")
> - (A B)+ compound repetition: Parser accepts, but execution returns 0
> matches
> 
> 
> 4. CODE COVERAGE ANALYSIS
> -------------------------
> 
> 4.1 Overall Coverage
> 
> 96.4% (732 / 759 lines)
> 
> 4.2 Coverage by File (major RPR-modified files)
> 
> nodeWindowAgg.c:    96.6% (560/580) - Pattern matching execution engine
> parse_clause.c:     96.7% (88/91) - PATTERN/DEFINE analysis
> ruleutils.c:        93.1% (54/58) - pg_get_viewdef output
> 
> 4.3 Uncovered Code Risk Assessment
> 
> Total: 27 lines uncovered
> 
> Medium Risk (2 items) - Test addition recommended (see section 3.2):
> - parse_clause.c:4093: transformDefineClause - 27th variable error
> - nodeWindowAgg.c:5623: get_slots - null_slot for PREV at partition first
> row
> 
> Low Risk (25 items) - Defensive code / Unreachable:
> - nodeWindowAgg.c:3074: attno_map_walker - Parser validates arg count
> - nodeWindowAgg.c:3137-3138: rpr_navigation_walker - switch default
> - nodeWindowAgg.c:3566: window_gettupleslot - Before mark position
> - nodeWindowAgg.c:4289: WinGetFuncArgInFrame - isout flag
> - nodeWindowAgg.c:4393: WinGetSlotInFrame - Boundary check
> - nodeWindowAgg.c:4618-4619: row_is_in_reduced_frame - switch default
> - nodeWindowAgg.c:4697: register_reduced_frame_map - pos < 0 check
> - nodeWindowAgg.c:5007: search_str_set - NULL return continue
> - nodeWindowAgg.c:5405: do_pattern_match - Regex compile error
> - nodeWindowAgg.c:5435,5437-5438: do_pattern_match - Regex exec error
> - nodeWindowAgg.c:5700: pattern_initial - Variable not found
> - nodeWindowAgg.c:5776: string_set_get - Index range check
> - nodeWindowAgg.c:5850: variable_pos_register - a-z range check
> - nodeWindowAgg.c:5910: variable_pos_fetch - a-z range check
> - nodeWindowAgg.c:5913: variable_pos_fetch - Index range check
> - parse_clause.c:3989: transformDefineClause - A_Expr type check
> - parse_clause.c:4145: transformPatternClause - A_Expr type check
> - ruleutils.c:6904-6908: get_rule_windowspec - SKIP TO NEXT ROW output
> 
> Conclusion: Most uncovered code consists of defensive error handling or
> code unreachable due to parser pre-validation. No security or functional
> risk.
> 
> 
> 5. COMMIT ANALYSIS
> ------------------
> 
> 8 sequential commits:
> 
> Commit  Area            Files   +/-         Key Content
> -------------------------------------------------------------------------------
> 1       Raw Parser      4       +174/-16    gram.y grammar (PATTERN/DEFINE)
> 2       Parse/Analysis  4       +277/-1     parse_clause.c analysis logic
> 3       Rewriter        1       +109/-0     pg_get_viewdef extension
> 4       Planner         5       +73/-3      WindowAgg plan node extension
> 5       Executor        4       +1,942/-11  CORE: Pattern matching engine
> (+1,850)
> 6       Docs            3       +192/-7     advanced.sgml, func-window.sgml
> 7       Tests           3       +1,585/-1   rpr.sql (532), rpr.out (1,052)
> 8       typedefs        1       +6/-0       pgindent support
> 
> Code Change Statistics:
> - Total files: 25
> - Lines added: 4,358
> - Lines deleted: 39
> - Net increase: +4,319 lines
> 
> 
> 6. RECOMMENDATIONS
> ------------------
> 
> 6.1 Combinatorial Explosion Prevention (Major, Required)
> 
> Add work_mem-based memory limit for StringSet allocation.
> Location: string_set_add() in nodeWindowAgg.c:5741-5750
> Consistent with existing PostgreSQL approach (Hash Join, Sort, etc.)
> 
> 6.2 Code Review Required (Minor, Decision Needed)
> 
> Location: nodeWindowAgg.c:5849,5909,5912
> Issue: pos > NUM_ALPHABETS check intent unclear
> Current: PATTERN with 28 elements causes error
> Question: Is 27 element limit intentional?
> 
> 6.3 Code Style Fixes (Minor)
> 
> - #ifdef RPR_DEBUG: Use elog(DEBUG2, ...) or remove (25 blocks)
> - static keyword on separate line: 26 functions to fix
> - Whitespace: "regexp !=NULL" -> "regexp != NULL"
> - Error message case: "Unrecognized" -> "unrecognized"
> 
> 6.4 Documentation Fixes (Minor)
> 
> - select.sgml: "maximu" -> "maximum"
> 
> 6.5 Test Additions (Optional)
> 
> Black-box Tests (Functional):
> 
> Feature              Test Case                                    Priority
> -------------------------------------------------------------------------------
> Variable limit       26 variables success, 27 error               Medium
> NULL boundary        PREV at partition first row                  Medium
> 
> White-box Tests (Coverage) - covered by above black-box tests:
> 
> File:Line                          Target Branch
> -------------------------------------------------------------------------------
> parse_clause.c:4093                Limit error branch (Variable limit test)
> nodeWindowAgg.c:5623               null_slot usage (NULL boundary test)
> 
> 
> 7. CONCLUSION
> -------------
> 
> Test Quality: GOOD
> 
> Core functionality is thoroughly tested with comprehensive error case
> coverage.
> 
> The patch is well-implemented within its defined scope. Identified issues
> include
> one major concern (combinatorial explosion) and minor style/documentation
> items.
> 
> Recommended actions before commit:
> 1. Add work_mem-based memory limit for pattern combinations (required)
> 2. Clarify pos > NUM_ALPHABETS check intent (review needed)
> 3. Fix code style issues (optional but recommended)
> 4. Fix documentation typo (trivial)
> 5. Add tests for variable limit and NULL handling (optional)
> 
> Points for discussion (optional):
> 6. Incremental matching with streaming NFA redesign
> 
> 
> Attachment:
> - coverage.tgz (gcov HTML report, RPR-modified code only)
> 
> 
> ---
> End of Report
> 
> 2025년 9월 24일 (수) PM 7:36, Tatsuo Ishii 님이 작성:
> 
>> Attached are the v33 patches for Row pattern recognition.  The
>> difference from v32 is that the raw parse tree printing patch is not
>> included in v33. This is because now that we have
>> debug_print_raw_parse.
>>
>> Best regards,
>> --
>> Tatsuo Ishii
>> SRA OSS K.K.
>> English: http://www.sraoss.co.jp/index_en/
>> Japanese:http://www.sraoss.co.jp
>>


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:

Hi Ishii-san,

Glad the review was useful!

2026년 1월 2일 (금) AM 11:16, Tatsuo Ishii <ishii@postgresql.org>님이 작성:

Hi Henson,

Thank you for the review! I will take care the issues (it will take
sometime).


If you have other patches that need pre-analysis (coverage, style, valgrind, etc.), feel free to ask anytime. I enjoy this kind of work.

 
Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

> SQL/RPR Patch Review Report
> ============================
>
> Patch: Row Pattern Recognition (SQL:2016)
> Commitfest: https://commitfest.postgresql.org/patch/4460
>
> Review Methodology:
>   This review focused on quality assessment, not line-by-line code audit.
>   Key code paths and quality issues were examined with surrounding context
>   when concerns arose. Documentation files were reviewed with AI-assisted
>   grammar and typo checking. Code coverage was measured using gcov and
>   custom analysis tools.
>
> Limitations:
>   - Not a security audit or formal verification
>   - Parser and executor internals reviewed at module level, not exhaustively
>   - Performance characteristics not benchmarked
>
>
> TABLE OF CONTENTS
> -----------------
>
> 1. Executive Summary
> 2. Issues Found
>    2.1 Critical / Major
>    2.2 Minor Issues (Review Needed)
>    2.3 Minor Issues (Style)
>    2.4 Suggestions for Discussion
> 3. Test Coverage
>    3.1 Covered Areas
>    3.2 Untested Items
>    3.3 Unimplemented Features (No Test Needed)
> 4. Code Coverage Analysis
>    4.1 Overall Coverage
>    4.2 Coverage by File
>    4.3 Uncovered Code Risk Assessment
> 5. Commit Analysis
> 6. Recommendations
> 7. Conclusion
>
>
> 1. EXECUTIVE SUMMARY
> --------------------
>
> Overall assessment: GOOD
>
> The SQL/RPR patch demonstrates solid implementation quality within its
> defined scope. Code follows PostgreSQL coding standards (with minor style
> issues), test coverage is comprehensive at 96.4%, and documentation is
> thorough with only minor typos.
>
> Rating by Area:
> - Code Quality:     Good (PostgreSQL style compliant, 26 static style fixes
> recommended)
> - Test Coverage:    Good (96.4% line coverage, 28 test cases)
> - Documentation:    Good (Complete, 1 minor typo)
> - Build/Regress:    Pass (make check-world, 753 tests passed)
>
>
> 2. ISSUES FOUND
> ---------------
>
> 2.1 Critical / Major
>
> #1 [Code] Greedy pattern combinatorial explosion
>    Pattern: PATTERN (A+ B+ C+) with DEFINE A AS TRUE, B AS TRUE, C AS TRUE
>    Impact: Memory exhaustion or infinite wait
>    Recommendation: Add work_mem-based memory limit (error on exceed)
>
>    Evidence - No memory limit in current code:
>    - nodeWindowAgg.c:5718-5722 string_set_init(): palloc() unconditional
>    - nodeWindowAgg.c:5741-5750 string_set_add(): set_size *= 2; repalloc()
> unlimited
>    - nodeWindowAgg.c:5095-5174 generate_patterns(): Triple loop, no limit
>
>    Only work_mem usage in RPR (nodeWindowAgg.c:1297):
>      winstate->buffer = tuplestore_begin_heap(false, false, work_mem);
>    -> For tuple buffer, unrelated to pattern combination memory (StringSet)
>
> 2.2 Minor Issues (Review Needed)
>
> #1 [Code] nodeWindowAgg.c:5849,5909,5912
>    pos > NUM_ALPHABETS check - intent unclear, causes error at 28 PATTERN
> elements
>
>    Reproduction:
>    - PATTERN (A B C ... Z A) (27 elements) -> OK
>    - PATTERN (A B C ... Z A B) (28 elements) -> ERROR "initial is not valid
> char: b"
>
> 2.3 Minor Issues (Style)
>
> #1 [Code] nodeWindowAgg.c (25 blocks)
>    #ifdef RPR_DEBUG -> recommend elog(DEBUG2, ...) or remove
>
> #2 [Code] src/backend/executor/nodeWindowAgg.c
>    static keyword on separate line (26 functions)
>
> #3 [Code] src/backend/utils/adt/ruleutils.c
>    Whitespace typo: "regexp !=NULL" -> "regexp != NULL"
>
> #4 [Code] nodeWindowAgg.c:4619
>    Error message case: "Unrecognized" -> "unrecognized" (PostgreSQL style)
>
> #5 [Doc] doc/src/sgml/ref/select.sgml:1128
>    Typo: "maximu" -> "maximum"
>
> 2.4 Suggestions for Discussion
>
> #1 Incremental matching with streaming NFA redesign
>    Benefits:
>    - O(n) time complexity per row (current: exponential in worst case)
>    - Bounded memory via state merging and context absorption
>    - Natural extension for OR patterns, {n,m} quantifiers, nested groups
>    - Enables MEASURES clause with incremental aggregates
>    - Proven approach in CEP engines (Flink, Esper)
>
>
> 3. TEST COVERAGE
> ----------------
>
> 3.1 Covered Areas
>
> - PATTERN clause: +, *, ? quantifiers (line 41, 71, 86)
> - DEFINE clause: Variable conditions, auto-TRUE for missing (line 120-133)
> - PREV/NEXT functions: Single argument (line 44, 173)
> - AFTER MATCH SKIP: TO NEXT ROW (line 182), PAST LAST ROW (line 198)
> - Aggregate integration: sum, avg, count, max, min (line 258-277)
> - Window function integration: first_value, last_value, nth_value (line
> 34-35)
> - JOIN/CTE: JOIN (line 313), WITH (line 324)
> - View: VIEW creation, pg_get_viewdef (line 390-406)
> - Error cases: 7 error scenarios (line 409-532)
> - Large partition: 5000 row smoke test (line 360-387)
> - ROWS BETWEEN offset: CURRENT ROW AND 2 FOLLOWING (line 244)
>
> 3.2 Untested Items
>
> Feature                  Priority   Recommendation
> -------------------------------------------------------------------------------
> 26 variable limit        Medium     Test 26 variables success, 27th
> variable error
> NULL value handling      Low        Test PREV(col) where col or previous
> row is NULL
>
> Sample test for 26 variable limit:
>
>     -- Should fail with 27th variable (parser error, no table needed)
>     SELECT * FROM (SELECT 1 AS x) t
>     WINDOW w AS (
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       PATTERN (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
>       DEFINE a AS TRUE, b AS TRUE, c AS TRUE, d AS TRUE, e AS TRUE, f AS
> TRUE,
>              g AS TRUE, h AS TRUE, i AS TRUE, j AS TRUE, k AS TRUE, l AS
> TRUE,
>              m AS TRUE, n AS TRUE, o AS TRUE, p AS TRUE, q AS TRUE, r AS
> TRUE,
>              s AS TRUE, t AS TRUE, u AS TRUE, v AS TRUE, w AS TRUE, x AS
> TRUE,
>              y AS TRUE, z AS TRUE, aa AS TRUE
>     );
>     -- ERROR: number of row pattern definition variable names exceeds 26
>
> Sample test for NULL handling:
>
>     CREATE TEMP TABLE stock_null (company TEXT, tdate DATE, price INTEGER);
>     INSERT INTO stock_null VALUES ('c1', '2023-07-01', 100);
>     INSERT INTO stock_null VALUES ('c1', '2023-07-02', NULL);  -- NULL in
> middle
>     INSERT INTO stock_null VALUES ('c1', '2023-07-03', 200);
>     INSERT INTO stock_null VALUES ('c1', '2023-07-04', 150);
>
>     SELECT company, tdate, price, count(*) OVER w AS match_count
>     FROM stock_null
>     WINDOW w AS (
>       PARTITION BY company
>       ORDER BY tdate
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       PATTERN (START UP DOWN)
>       DEFINE START AS TRUE, UP AS price > PREV(price), DOWN AS price <
> PREV(price)
>     );
>     -- Result: all rows show match_count = 0 (NULL breaks pattern matching)
>
> 3.3 Unimplemented Features (No Test Needed)
>
> Per documentation (select.sgml:1133-1136):
> - MEASURES clause: Not implemented
> - SUBSET clause: Not implemented
> - AFTER MATCH variants: Only SKIP TO NEXT ROW, PAST LAST ROW supported
>
> Not in documentation, verified by testing:
> - {n,m} quantifier: Parser error ("syntax error at or near {")
> - (A|B) OR pattern: Not supported (parsed as single variable name "a|b")
> - (A B)+ compound repetition: Parser accepts, but execution returns 0
> matches
>
>
> 4. CODE COVERAGE ANALYSIS
> -------------------------
>
> 4.1 Overall Coverage
>
> 96.4% (732 / 759 lines)
>
> 4.2 Coverage by File (major RPR-modified files)
>
> nodeWindowAgg.c:    96.6% (560/580) - Pattern matching execution engine
> parse_clause.c:     96.7% (88/91) - PATTERN/DEFINE analysis
> ruleutils.c:        93.1% (54/58) - pg_get_viewdef output
>
> 4.3 Uncovered Code Risk Assessment
>
> Total: 27 lines uncovered
>
> Medium Risk (2 items) - Test addition recommended (see section 3.2):
> - parse_clause.c:4093: transformDefineClause - 27th variable error
> - nodeWindowAgg.c:5623: get_slots - null_slot for PREV at partition first
> row
>
> Low Risk (25 items) - Defensive code / Unreachable:
> - nodeWindowAgg.c:3074: attno_map_walker - Parser validates arg count
> - nodeWindowAgg.c:3137-3138: rpr_navigation_walker - switch default
> - nodeWindowAgg.c:3566: window_gettupleslot - Before mark position
> - nodeWindowAgg.c:4289: WinGetFuncArgInFrame - isout flag
> - nodeWindowAgg.c:4393: WinGetSlotInFrame - Boundary check
> - nodeWindowAgg.c:4618-4619: row_is_in_reduced_frame - switch default
> - nodeWindowAgg.c:4697: register_reduced_frame_map - pos < 0 check
> - nodeWindowAgg.c:5007: search_str_set - NULL return continue
> - nodeWindowAgg.c:5405: do_pattern_match - Regex compile error
> - nodeWindowAgg.c:5435,5437-5438: do_pattern_match - Regex exec error
> - nodeWindowAgg.c:5700: pattern_initial - Variable not found
> - nodeWindowAgg.c:5776: string_set_get - Index range check
> - nodeWindowAgg.c:5850: variable_pos_register - a-z range check
> - nodeWindowAgg.c:5910: variable_pos_fetch - a-z range check
> - nodeWindowAgg.c:5913: variable_pos_fetch - Index range check
> - parse_clause.c:3989: transformDefineClause - A_Expr type check
> - parse_clause.c:4145: transformPatternClause - A_Expr type check
> - ruleutils.c:6904-6908: get_rule_windowspec - SKIP TO NEXT ROW output
>
> Conclusion: Most uncovered code consists of defensive error handling or
> code unreachable due to parser pre-validation. No security or functional
> risk.
>
>
> 5. COMMIT ANALYSIS
> ------------------
>
> 8 sequential commits:
>
> Commit  Area            Files   +/-         Key Content
> -------------------------------------------------------------------------------
> 1       Raw Parser      4       +174/-16    gram.y grammar (PATTERN/DEFINE)
> 2       Parse/Analysis  4       +277/-1     parse_clause.c analysis logic
> 3       Rewriter        1       +109/-0     pg_get_viewdef extension
> 4       Planner         5       +73/-3      WindowAgg plan node extension
> 5       Executor        4       +1,942/-11  CORE: Pattern matching engine
> (+1,850)
> 6       Docs            3       +192/-7     advanced.sgml, func-window.sgml
> 7       Tests           3       +1,585/-1   rpr.sql (532), rpr.out (1,052)
> 8       typedefs        1       +6/-0       pgindent support
>
> Code Change Statistics:
> - Total files: 25
> - Lines added: 4,358
> - Lines deleted: 39
> - Net increase: +4,319 lines
>
>
> 6. RECOMMENDATIONS
> ------------------
>
> 6.1 Combinatorial Explosion Prevention (Major, Required)
>
> Add work_mem-based memory limit for StringSet allocation.
> Location: string_set_add() in nodeWindowAgg.c:5741-5750
> Consistent with existing PostgreSQL approach (Hash Join, Sort, etc.)
>
> 6.2 Code Review Required (Minor, Decision Needed)
>
> Location: nodeWindowAgg.c:5849,5909,5912
> Issue: pos > NUM_ALPHABETS check intent unclear
> Current: PATTERN with 28 elements causes error
> Question: Is 27 element limit intentional?
>
> 6.3 Code Style Fixes (Minor)
>
> - #ifdef RPR_DEBUG: Use elog(DEBUG2, ...) or remove (25 blocks)
> - static keyword on separate line: 26 functions to fix
> - Whitespace: "regexp !=NULL" -> "regexp != NULL"
> - Error message case: "Unrecognized" -> "unrecognized"
>
> 6.4 Documentation Fixes (Minor)
>
> - select.sgml: "maximu" -> "maximum"
>
> 6.5 Test Additions (Optional)
>
> Black-box Tests (Functional):
>
> Feature              Test Case                                    Priority
> -------------------------------------------------------------------------------
> Variable limit       26 variables success, 27 error               Medium
> NULL boundary        PREV at partition first row                  Medium
>
> White-box Tests (Coverage) - covered by above black-box tests:
>
> File:Line                          Target Branch
> -------------------------------------------------------------------------------
> parse_clause.c:4093                Limit error branch (Variable limit test)
> nodeWindowAgg.c:5623               null_slot usage (NULL boundary test)
>
>
> 7. CONCLUSION
> -------------
>
> Test Quality: GOOD
>
> Core functionality is thoroughly tested with comprehensive error case
> coverage.
>
> The patch is well-implemented within its defined scope. Identified issues
> include
> one major concern (combinatorial explosion) and minor style/documentation
> items.
>
> Recommended actions before commit:
> 1. Add work_mem-based memory limit for pattern combinations (required)
> 2. Clarify pos > NUM_ALPHABETS check intent (review needed)
> 3. Fix code style issues (optional but recommended)
> 4. Fix documentation typo (trivial)
> 5. Add tests for variable limit and NULL handling (optional)
>
> Points for discussion (optional):
> 6. Incremental matching with streaming NFA redesign
>
>
> Attachment:
> - coverage.tgz (gcov HTML report, RPR-modified code only)
>
>
> ---
> End of Report
>
> 2025년 9월 24일 (수) PM 7:36, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
>
>> Attached are the v33 patches for Row pattern recognition.  The
>> difference from v32 is that the raw parse tree printing patch is not
>> included in v33. This is because now that we have
>> debug_print_raw_parse.
>>
>> Best regards,
>> --
>> Tatsuo Ishii
>> SRA OSS K.K.
>> English: http://www.sraoss.co.jp/index_en/
>> Japanese:http://www.sraoss.co.jp
>>

Best regards,

Henson 

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

I've been working on an alternative implementation approach for Row
Pattern Recognition (RPR) that addresses some limitations in the
current regex-based patch.

Key differences from the existing approach:

1. Streaming NFA instead of regex engine
   - Process rows incrementally without accumulating encoded strings
   - Avoids O(V^N) combinatorial explosion in multi-variable scenarios

2. No 26-variable limit
   - Variables identified by index, not alphabet encoding

3. Proper Lexical Order support
   - Respects PATTERN alternative order for ONE ROW PER MATCH

4. GREEDY/RELUCTANT quantifier support
   - Longest vs shortest match semantics

5. Incremental MEASURES computation
   - Aggregate values computed during matching, no rescan needed

The attached document describes the design in detail, including:
- Data structures (Pattern, MatchState, MatchContext)
- Execution flow and state transitions
- Context absorption optimization for greedy patterns
- AST optimization passes

This is still a work in progress. I'd appreciate any feedback on
the approach before proceeding with PostgreSQL integration.

Best regards,
Henson

------------------------------------------------------------------------
                         Attachment
------------------------------------------------------------------------


========================================================================
      RPR Streaming NFA Pattern Matching System Overview (DRAFT)
========================================================================

0. Motivation and Approach
------------------------------------------------------------------------

0.1 Background: Limitations of PostgreSQL RPR Patch

    The existing PostgreSQL RPR implementation (RPR-base branch) uses
    a regex-based approach:

    ┌─────────────────────────────────────────────────────────────────┐
    │  Existing Implementation (Regex-based)                          │
    ├─────────────────────────────────────────────────────────────────┤
    │                                                                 │
    │  1. Evaluate all DEFINE conditions for each row                 │
    │     → Encode matching variables as alphabets (a, b, c, ...)     │
    │                                                                 │
    │  2. Accumulate encoded string                                   │
    │     "aabbc" (A match, A match, B match, B match, C match)       │
    │                                                                 │
    │  3. Convert PATTERN to regex                                    │
    │     PATTERN (A+ B+ C) → "^a+b+c"                                │
    │                                                                 │
    │  4. Match using PostgreSQL regex engine                         │
    │     pg_regexec(&preg, encoded_str, ...)                         │
    │                                                                 │
    └─────────────────────────────────────────────────────────────────┘

    Limitations (based on nodeWindowAgg.c analysis):

    ┌──────────────────┬──────────────────────────────────────────────┐
    │ Limitation       │ Cause                                        │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ Combinatorial    │ Cartesian product per row in                 │
    │ Explosion O(V^N) │ generate_patterns(). 3 vars, 20 rows → 3.4B  │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ 26 Variable      │ a-z alphabet encoding (NUM_ALPHABETS=26)     │
    │ Limit            │                                              │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ Lexical Order    │ Encoded by DEFINE declaration order,         │
    │ Not Guaranteed   │ PATTERN alternative order ignored.           │
    │                  │ In (B|A) pattern, A encoded first            │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ No RELUCTANT     │ Only greedy flag exists, no shortest match   │
    │ Support          │ logic                                        │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ MEASURES Not     │ Rescan-based workaround, no incremental      │
    │ Implemented      │ aggregation                                  │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ O(N^2) Retry on  │ No intermediate state maintained. On failure │
    │ Match Failure    │ at row N, retry from row K+1 from scratch    │
    └──────────────────┴──────────────────────────────────────────────┘


0.2 Approach: Streaming NFA-based Pattern Matching

    We adopt an NFA-based approach similar to Apache Flink CEP:

    ┌─────────────────────────────────────────────────────────────────┐
    │  NFA-based Approach                                             │
    ├─────────────────────────────────────────────────────────────────┤
    │                                                                 │
    │  Core Ideas:                                                    │
    │    - Compile pattern to flat array (PatternElement[])           │
    │    - Perform state transitions per row (no regex matching)      │
    │    - Merge identical states to prevent redundant computation    │
    │                                                                 │
    │  Time Complexity: O(N x S x E)                                  │
    │    N: Number of input rows                                      │
    │    S: Number of concurrent active states (bounded by merge)     │
    │    E: Number of pattern elements                                │
    │                                                                 │
    └─────────────────────────────────────────────────────────────────┘

    Resolving Limitations:

    ┌──────────────────┬──────────────────────────────────────────────┐
    │ Original Limit   │ Resolution with Streaming NFA                │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ Combinatorial    │ State transition based, identical state merge│
    │ Explosion O(V^N) │ → O(N×S×E), S proportional to pattern size   │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ 26 Variable      │ Integer varId, size adjustable as needed     │
    │ Limit            │                                              │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ Lexical Order    │ #ALT branches generated in PATTERN order     │
    │ Not Guaranteed   │ → Alternative order preserved in paths[][]   │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ No RELUCTANT     │ Custom NFA enables shortest/longest match    │
    │ Support          │ control                                      │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ MEASURES Not     │ Incremental aggregation computes SUM, COUNT  │
    │ Implemented      │ etc. in real-time                            │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ O(N^2) Retry on  │ Multiple Contexts maintained concurrently    │
    │ Match Failure    │ → Parallel tracking per start point, O(N)    │
    └──────────────────┴──────────────────────────────────────────────┘

    New Advantages:

    ┌──────────────────┬──────────────────────────────────────────────┐
    │ Advantage        │ Description                                  │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ ALL ROWS Mode    │ Track all possible match paths concurrently  │
    │                  │ → Each Context branches/completes separately │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ Context          │ Merge Contexts upon reaching identical state │
    │ Absorption       │ → Eliminate redundant computation, memory    │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ Incremental      │ Compute SUM, COUNT etc. during matching      │
    │ Aggregation      │ → No rescan needed after completion          │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ Flat Array       │ Contiguous memory layout for states[],       │
    │ Structure        │ contexts[] → Good cache locality, no pointer │
    ├──────────────────┼──────────────────────────────────────────────┤
    │ Path Sharing     │ Chunk tree + hash table for path sharing     │
    │                  │ → O(1) reference on fork, memory dedup       │
    └──────────────────┴──────────────────────────────────────────────┘


0.3 Difference from Flink: History Elimination

    ┌─────────────────────────────────────────────────────────────────┐
    │  Flink CEP (Streaming)              PostgreSQL (Batch)          │
    ├─────────────────────────────────────────────────────────────────┤
    │                                                                 │
    │  Original data flows away           Materialized data           │
    │  → Cannot re-access                 → Rescan anytime            │
    │  → Store row data in History        → No History needed         │
    │  → Pointer tree + ref counting      → Store match_start/end only│
    │                                                                 │
    │  Fork: pointer copy O(1)            Fork: copy counts[]         │
    │  MEASURES: backtrack History        MEASURES: rescan range      │
    │                                                                 │
    └─────────────────────────────────────────────────────────────────┘

    Our Implementation Choices:
      - Adopt Incremental Aggregation
      - Compute SUM, COUNT etc. in real-time during matching
      - Maintain only aggregate values without History pointers
      - Store path info as varId arrays in paths[][]


0.4 Design Goals

    ┌──────────────┬──────────────────────────────────────────────────┐
    │ Goal         │ Description                                      │
    ├──────────────┼──────────────────────────────────────────────────┤
    │ Linear       │ O(N×S×E), no combinatorial explosion             │
    │ Complexity   │                                                  │
    ├──────────────┼──────────────────────────────────────────────────┤
    │ Standard     │ SQL:2016 RPR semantics (GREEDY, RELUCTANT, SKIP) │
    │ Compliance   │                                                  │
    ├──────────────┼──────────────────────────────────────────────────┤
    │ Extensibility│ Future extensions: MEASURES, SUBSET, etc.        │
    ├──────────────┼──────────────────────────────────────────────────┤
    │ Simplicity   │ Flat array pattern, clear state transition rules │
    └──────────────┴──────────────────────────────────────────────────┘


0.5 Path Storage Optimization

    Risk of memory explosion when paths[][] are copied on Context fork.
    Share identical paths via chunk tree + hash table:

    ┌─────────────────────────────────────────────────────────────────┐
    │  Chunk Tree Structure                                           │
    ├─────────────────────────────────────────────────────────────────┤
    │                                                                 │
    │  Chunk: fixed-size(2) array + parent pointer + ref count        │
    │                                                                 │
    │  Example: Two paths [A,A,C,D] and [A,A,C,E]                     │
    │                                                                 │
    │      Chunk1[A,A] ← Chunk2[C,D]  (Path1)                         │
    │         RC:2    ↖                                               │
    │                   Chunk3[C,E]  (Path2)                          │
    │                                                                 │
    │      → Share parent chunk (Chunk1), create new chunk from fork  │
    │                                                                 │
    │  Hash table: (parent, values) → reuse identical chunks          │
    │                                                                 │
    └─────────────────────────────────────────────────────────────────┘


1. System Architecture
------------------------------------------------------------------------

┌────────────────────────────────────────────────────────────────────────┐
│                        Processing Pipeline                             │
├────────────────────────────────────────────────────────────────────────┤
│                                                                        │
│  Pattern String   Parser      Pattern          Executor         Result │
│  "A+ B | C" ───▶ (AST) ───▶ (elements) ───▶ (Contexts) ───▶ Match  │
│                                                                        │
│  ┌──────────────────┐  ┌───────────────────┐  ┌───────────────────┐    │
│  │      Parser      │  │      Context      │  │     Executor      │    │
│  │                  │  │                   │  │                   │    │
│  │  Tokenize        │  │  MatchState       │  │  NFAExecutor      │    │
│  │  Build AST       │  │  MatchContext     │  │  Multi-Context    │    │
│  │  Optimize        │  │  State Transition │  │  Absorb/SKIP      │    │
│  │  Compile         │  │  Greedy/Reluctant │  │  Output Mgmt      │    │
│  └──────────────────┘  └───────────────────┘  └───────────────────┘    │
│                                                                        │
└────────────────────────────────────────────────────────────────────────┘


2. Document Structure
------------------------------------------------------------------------

┌──────────────┬────────────────────────────────────────────────────┐
│ Parser       │ Pattern string → PatternElement[] transformation   │
│              │  - Tokenizer: string → tokens                      │
│              │  - Parser: tokens → AST                            │
│              │  - Optimizer: AST simplification                   │
│              │  - Compiler: AST → PatternElement[]                │
├──────────────┼────────────────────────────────────────────────────┤
│ Context      │ Single Context internal behavior                   │
│              │  - MatchState: current position + counters + path  │
│              │  - MatchContext: collection of States              │
│              │  - State transition: variable match, #ALT, #END,   │
│              │    #FIN handling                                   │
│              │  - Greedy/Reluctant quantifier behavior            │
├──────────────┼────────────────────────────────────────────────────┤
│ Executor     │ Multi-Context management                           │
│              │  - NFAExecutor: main execution engine              │
│              │  - Context creation/absorption/removal             │
│              │  - SKIP modes (PAST LAST / TO NEXT)                │
│              │  - Output rows (ONE ROW / ALL ROWS)                │
├──────────────┼────────────────────────────────────────────────────┤
│ Improvements │ Future enhancements                                │
│              │  - Path storage optimization (chunk tree + hash)   │
└──────────────┴────────────────────────────────────────────────────┘


3. Key Data Structures
------------------------------------------------------------------------

3.1 Pattern
    The entire compiled pattern.

    Fields:
      - maxDepth: maximum nesting depth
      - elements[]: PatternElement array
      - variables[]: variable name array (variables[varId] → name)
      - firstMatchIsGreedy: whether first match is Greedy
                            (Context absorption condition)

3.2 PatternElement
    A single element of the compiled pattern.

    Fields:
      - varId: variable identifier or special marker (0+ variable,
               negative special)
      - reluctant: flag (true = shortest, false = longest)
      - min, max: quantifier range
      - depth: nesting depth
      - next: next element index
      - jump: alternative/repeat jump target

3.3 MatchState
    A single state during NFA execution.

    Fields:
      - elementIndex: current PatternElement position
      - counts[]: per-depth repeat counters
      - summaries[]: Summary array (creation order preserved)

    State equivalence: identical if elementIndex + counts[] match
    On merge, summaries are combined

3.4 Summary
    Aggregate values and path information.

    Fields:
      - aggregates{}: incremental aggregates (SUM, COUNT, FIRST,
                      LAST, MIN, MAX)
      - paths[][]: matched variable paths (creation order preserved)

    Merge rules:
      - If aggregate values identical → merge Summaries, combine paths
      - summaries[0].paths[0] = Lexical Order priority path

3.5 MatchContext
    Collection of States with the same start point.

    Fields:
      - matchStart: match start row (unique identifier)
      - matchEnd: match end row (stores currentRow when matchedState
                  updated)
      - states[]: active States (creation order preserved, all branch
                  paths)
      - matchedState: MatchState | null (for Greedy fallback)

3.6 NFAExecutor
    Main execution engine.

    Fields:
      - pattern: compiled pattern
      - contexts[]: active Contexts (creation order preserved)
      - completedContexts[]: completed Contexts (sorted by start,
                             pending emit)
      - skipMode: PAST_LAST / TO_NEXT
      - currentRow: currently processing row number
      - history[]: per-row execution snapshots (for debugging)


4. Execution Flow
------------------------------------------------------------------------

┌─────────────────────────────────────────────────────────────────────┐
│                         Per-Row Processing                          │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  FOR EACH row IN data:                                              │
│      │                                                              │
│      ├─▶ 1. tryStartNewContext(row)                                │
│      │       └─ Create Context if new match can start               │
│      │                                                              │
│      ├─▶ 2. FOR EACH context:                                      │
│      │       └─ processContext(context, row)                        │
│      │           └─ State transitions + incremental aggregation     │
│      │                                                              │
│      ├─▶ 3. mergeStates() + absorbContexts()                       │
│      │       ├─ State Merge (same elementIndex+counts)              │
│      │       ├─ Summary Merge (same aggregates → combine paths)     │
│      │       └─ Absorb later Context into earlier one               │
│      │                                                              │
│      ├─▶ 4. Remove dead/completed Contexts                         │
│      │                                                              │
│      └─▶ 5. emitRows()                                             │
│              ├─ contexts[1+] complete → queue in completedContexts  │
│              └─ contexts[0] complete → emit immediately, process    │
│                  queue                                              │
│                  └─ Iterate items where start < contexts[0].start   │
│                      ├─ PAST LAST: discard if start <= prev end     │
│                      └─ TO NEXT: end >= ctx[0].start → stop (wait)  │
│                                  end < ctx[0].start → emit          │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘


5. Core Concepts
------------------------------------------------------------------------

5.1 State Transitions

    Variable element:  If condition true, move to next, add to paths
    #ALT:              Branch to all alternatives (next, jump chain)
    #END:              Check counter, repeat (jump) or escape (next)
    #FIN:              Match complete

5.2 Matching Modes (3 Axes)

    ┌──────────────────────────────────────────────────────────────────┐
    │  [Axis 1] Output Rows:    ONE ROW / ALL ROWS                     │
    │  [Axis 2] Quantifier:     GREEDY / RELUCTANT                     │
    │  [Axis 3] SKIP Option:    PAST LAST / TO NEXT                    │
    └──────────────────────────────────────────────────────────────────┘

    Output Rows:
      - ONE ROW:   Output paths[0] (Lexical Order priority path)
      - ALL ROWS:  Output all paths

    Quantifier Greediness:
      - GREEDY:    Longest match first, preserve completion and continue
      - RELUCTANT: Shortest match first, return immediately on completion

    SKIP Option:
      - PAST LAST: Multiple Contexts active, discard overlaps on emit
      - TO NEXT:   Start possible every row, allow overlapping matches

5.3 Merge Rules

    State Merge (within Context):
      - Condition: same elementIndex + counts[]
      - Action: combine summaries (preserve creation order)
      - Result: reduce State count at same position, prevent redundant
                computation

    Summary Merge (within State):
      - Condition: same aggregates{} values
      - Action: combine paths (preserve creation order)
      - Result: summaries[0].paths[0] = Lexical Order priority path

5.4 Context Absorption

    Condition: First match in pattern is Greedy (max=Infinity AND
               reluctant=false)
               (same elementIndex AND earlier.counts >= later.counts)
    Action: Remove later Context
    Result: Earlier continues with longer match, prevent redundant
            computation

5.5 Emit Flow

    - contexts[0] complete → emit immediately
    - contexts[1+] complete → queue in completedContexts
    - After contexts[0] emits, process queue (by start order):
        1. start >= contexts[0].start → stop (not yet eligible)
        2. PAST LAST: start <= previous emit's end → discard, continue
        3. TO NEXT: end >= contexts[0].start (overlaps with ctx[0])
                    → stop (this item waits until ctx[0] clears)
        4. TO NEXT: end < contexts[0].start (no overlap)
                    → emit, continue to next item


6. Module Dependencies
------------------------------------------------------------------------

  Parser ────────────────────────────────────────────────────────────
    Output: PatternElement[]
    → Context: State references PatternElement
    → Executor: passed as pattern field

  Context ───────────────────────────────────────────────────────────
    Input: PatternElement[] (read-only)
    Output: MatchContext (completed/in-progress status)
    → Executor: State transitions in processContext()

  Executor ──────────────────────────────────────────────────────────
    Input: Pattern, data rows
    Internal: Context creation/management
    Output: Match results (completedContexts)


7. Context Absorption
------------------------------------------------------------------------

    When the pattern starts with a Greedy quantifier (e.g., A+), later
    Contexts can be absorbed into earlier ones if they reach the same
    state with fewer repetitions. This eliminates redundant computation.

┌─────────────────────────────────────────────────────────────────────┐
│                     Context Absorption                              │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Pattern: A+ B     (A is Greedy: max=Infinity, reluctant=false)     │
│                                                                     │
│  Row 1: A matched                                                   │
│    contexts[0]: start=1, elementIndex=A, counts=[1]                 │
│                                                                     │
│  Row 2: A matched                                                   │
│    contexts[0]: start=1, elementIndex=A, counts=[2]  ← continue     │
│    contexts[1]: start=2, elementIndex=A, counts=[1]  ← new Context  │
│                                                                     │
│  Absorption check:                                                  │
│    - First element is Greedy? YES (A+)                              │
│    - Same elementIndex? YES (both at A)                             │
│    - earlier.counts[0] >= later.counts[0]? YES (2 >= 1)             │
│    → Absorb: Remove contexts[1]                                     │
│                                                                     │
│  Result:                                                            │
│    contexts[0]: start=1, counts=[2]  (only survivor)                │
│                                                                     │
│  Why: Later Context's path is subset of earlier's longer match      │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

    Condition:
      1. Pattern's first match is Greedy (max=Infinity AND reluctant=false)
         - Simple: A+ B
         - Group:  (A B)+ C  (group repeat is also Greedy)
      2. Both Contexts at same elementIndex
      3. earlier.counts[depth] >= later.counts[depth]

    Action: Remove later Context

    Result: Earlier Context continues with longer match,
            prevents redundant computation


8. State Fork and Merge
------------------------------------------------------------------------

    States fork when multiple paths are possible (e.g., at #ALT or when
    min <= count < max at #END). States merge when they reach identical
    positions, combining their paths while preventing redundant work.

┌─────────────────────────────────────────────────────────────────────┐
│                        State Fork                                   │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Pattern: A{1,2} B    (A can match 1 or 2 times)                    │
│                                                                     │
│  At #END element (after A matched once, count=1):                   │
│    - count(1) >= min(1)? YES → can escape to B (next)               │
│    - count(1) < max(2)?  YES → can repeat A (jump)                  │
│                                                                     │
│  Fork into two States:                                              │
│    State1: elementIndex=B, counts=[1]     ← escaped (try B)         │
│    State2: elementIndex=A, counts=[1]     ← repeat (try more A)     │
│                                                                     │
│  Both States continue in parallel within same Context               │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

    Fork Trigger:
      - #END element where min <= count < max
      - #ALT element (branch to all alternatives)

    Fork Action: Create new State for each branch path

    Copy-on-Write Optimization:
      - Forked States share summaries[] via refcount
      - Only copied when one branch modifies (adds path/updates aggregate)
      - Reduces memory allocation during fork-heavy patterns


┌─────────────────────────────────────────────────────────────────────┐
│                        State Merge                                  │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Pattern: (A | B) C                                                 │
│                                                                     │
│  After row matches both A and B conditions:                         │
│    State1: path=[A], elementIndex=C, counts=[1]                     │
│    State2: path=[B], elementIndex=C, counts=[1]                     │
│                                                                     │
│  Merge check:                                                       │
│    - Same elementIndex? YES (both at C)                             │
│    - Same counts[]? YES ([1] == [1])                                │
│    → Merge States                                                   │
│                                                                     │
│  Merged State:                                                      │
│    elementIndex=C, counts=[1]                                       │
│    summaries: [                                                     │
│      { paths: [[A]] },    ← from State1 (creation order)            │
│      { paths: [[B]] }     ← from State2                             │
│    ]                                                                │
│                                                                     │
│  Result: Single State, multiple paths preserved                     │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

    Merge Condition:
      - Same elementIndex
      - Same counts[] array

    Merge Action: Combine summaries (preserve creation order)

    Result: Reduces State count, prevents redundant computation
            summaries[0].paths[0] = Lexical Order priority path


┌─────────────────────────────────────────────────────────────────────┐
│              Summary Array Merge (during State Merge)               │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Same State = Same Future                                           │
│    States with identical (elementIndex + counts[]) will produce     │
│    identical future paths. Only past paths differ.                  │
│                                                                     │
│  Before State merge:                                                │
│    State1: elementIndex=C, counts=[1]                               │
│            summaries: [{ agg:{sum:10}, paths:[[A,C]] }]             │
│    State2: elementIndex=C, counts=[1]                               │
│            summaries: [{ agg:{sum:20}, paths:[[B,C]] }]             │
│            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~                             │
│            same state = same future                                 │
│                                                                     │
│  After State merge:                                                 │
│    Merged: elementIndex=C, counts=[1]                               │
│            summaries: [                                             │
│              { agg:{sum:10}, paths:[[A,C]] },                       │
│              { agg:{sum:20}, paths:[[B,C]] }                        │
│            ]                                                        │
│                                                                     │
│  Why: Merge States now, they will have identical continuations      │
│       summaries[] combined as array (preserve creation order)       │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│              Summary Merge (= Path Merge)                           │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  When: Two Summaries have identical aggregates{}                    │
│        → Merge Summaries, which merges their paths                  │
│                                                                     │
│  Before merge:                                                      │
│    Summary1: { aggregates: {sum:10}, paths: [[A,A]] }               │
│    Summary2: { aggregates: {sum:10}, paths: [[A,B]] }               │
│                                                                     │
│  After merge:                                                       │
│    Summary: { aggregates: {sum:10}, paths: [[A,A], [A,B]] }         │
│                                                                     │
│  Why: Same aggregate = same "value", only paths differ              │
│       Merging Summaries automatically combines their paths          │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

    Summary Merge Condition:
      - Same aggregates{} values (SUM, COUNT, etc. all equal)

    Summary Merge Action:
      - Merge two Summaries into one
      - paths[][] arrays combined (preserve creation order)
      - paths[0] = Lexical Order priority path


┌─────────────────────────────────────────────────────────────────────┐
│                     Path Deduplication                              │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  When: Duplicate paths exist after merging                          │
│                                                                     │
│  Before dedup:                                                      │
│    paths: [[A,B,C], [A,B,C], [A,B,D]]                               │
│            ~~~~~~   ~~~~~~                                          │
│            duplicate                                                │
│                                                                     │
│  After dedup:                                                       │
│    paths: [[A,B,C], [A,B,D]]                                        │
│                                                                     │
│  Why: Duplicate paths provide no additional information             │
│       Remove to reduce memory and output redundancy                 │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

    Deduplication Condition:
      - Identical variable sequence

    Deduplication Action:
      - Keep first occurrence (preserve creation order)
      - Discard duplicates


9. Completion Handling Algorithm
------------------------------------------------------------------------

    When a State reaches #FIN (elementIndex = -1), the pattern has matched.
    Whether to finalize or continue depends on quantifier mode. GREEDY
    preserves completion and continues seeking longer matches, while
    RELUCTANT completes immediately with the shortest match.

┌──────────────────────────────────────────────────────────────────────┐
│                    Completion Handling Algorithm                     │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│              Completion State Occurs (elementIndex = -1)             │
│                               │                                      │
│                               ▼                                      │
│                ┌──────────────────────────────┐                      │
│                │   Active states remain AND   │                      │
│                │   can match pattern input?   │                      │
│                └──────────────┬───────────────┘                      │
│                               │                                      │
│            YES ┌──────────────┴─────────────────┐ NO                 │
│                │                                │                    │
│                ▼                                ▼                    │
│   ┌─────────────────────────┐    ┌─────────────────────────────┐     │
│   │    Can continue more    │    │    Cannot continue more     │     │
│   └────────────┬────────────┘    └──────────────┬──────────────┘     │
│                │                                │                    │
│                ▼                                ▼                    │
│   ┌─────────────────────────┐    ┌─────────────────────────────┐     │
│   │  Is GREEDY quantifier?  │    │     Finalize result         │     │
│   └───────────┬─────────────┘    │                             │     │
│               │                  │   If preserved → fallback   │     │
│               │             NO   │   If none → match failed    │     │
│         YES ┌─┴──────────────┐   │   → Output Lexical Order 1  │     │
│             │                │   └─────────────────────────────┘     │
│             ▼                ▼                                       │
│   ┌────────────────────┐  ┌───────────────────────┐                  │
│   │ Preserve, continue │  │  Complete immediately │                  │
│   │   (for fallback)   │  │    (RELUCTANT)        │                  │
│   └────────────────────┘  └───────────────────────┘                  │
│                                                                      │
├──────────────────────────────────────────────────────────────────────┤
│  Preservation Rule (GREEDY):                                         │
│    1. Preserve 1 State with longest completion path                  │
│    2. If same length, choose Lexical Order priority State            │
│    3. Replace when new longer completion occurs                      │
│                                                                      │
│  Preserved Content:                                                  │
│    - state: completed MatchState (elementIndex=-1, ...)              │
│    - matchEnd: currentRow at matchedState update time                │
│                                                                      │
│  Fallback Condition (GREEDY):                                        │
│    - All active states dead (input unmatched)                        │
│    - matchedState exists → finalize with preserved State             │
│    - Use preserved matchEnd (saved at update time)                   │
└──────────────────────────────────────────────────────────────────────┘


10. AST Optimization
------------------------------------------------------------------------

    After parsing, the AST undergoes three optimization passes to simplify
    structure before compilation. These reduce PatternElement count,
    improving execution performance.

┌─────────────────────────────────────────────────────────────────────┐
│              1. unwrapGroups (Unnecessary Group Removal)            │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Case 1: Remove {1,1} Group wrapper                                 │
│                                                                     │
│    Before:  ((A))                   After:  A                       │
│                                                                     │
│      GROUP {1,1}                      VAR:A {1,1}                   │
│       └── GROUP {1,1}                                               │
│            └── VAR:A {1,1}                                          │
│                                                                     │
│  Case 2: Flatten nested SEQ                                         │
│                                                                     │
│    Before:  (A B) C                 After:  A B C                   │
│                                                                     │
│      SEQ                              SEQ                           │
│       ├── GROUP {1,1}                  ├── VAR:A {1,1}              │
│       │    └── SEQ                     ├── VAR:B {1,1}              │
│       │         ├── VAR:A              └── VAR:C {1,1}              │
│       │         └── VAR:B                                           │
│       └── VAR:C                                                     │
│                                                                     │
│  Case 3: Unwrap single-item SEQ/ALT                                 │
│                                                                     │
│    Before:  SEQ[A]                  After:  A                       │
│    Before:  ALT[A]                  After:  A                       │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│              2. removeDuplicates (Duplicate Alternative Removal)    │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Before:  A | B | A                 After:  A | B                   │
│                                                                     │
│    ALT                                ALT                           │
│     ├── VAR:A {1,1}                    ├── VAR:A {1,1}              │
│     ├── VAR:B {1,1}                    └── VAR:B {1,1}              │
│     └── VAR:A {1,1}  ← duplicate                                    │
│                                                                     │
│  Comparison: astEqual() for structural equality                     │
│                                                                     │
│  Before:  (A B) | (A B) | C         After:  (A B) | C               │
│                                                                     │
│    ALT                                ALT                           │
│     ├── SEQ[A,B]                       ├── SEQ[A,B]                 │
│     ├── SEQ[A,B]  ← duplicate          └── VAR:C                    │
│     └── VAR:C                                                       │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────┐
│              3. optimizeQuantifiers (Quantifier Optimization)       │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Case 1: Merge consecutive identical variables                      │
│                                                                     │
│    Before:  A A A B                 After:  A{3} B                  │
│                                                                     │
│      SEQ                              SEQ                           │
│       ├── VAR:A {1,1}                  ├── VAR:A {3,3}              │
│       ├── VAR:A {1,1}                  └── VAR:B {1,1}              │
│       ├── VAR:A {1,1}                                               │
│       └── VAR:B {1,1}                                               │
│                                                                     │
│  Case 2: Merge nested quantifiers (when one is fixed)               │
│                                                                     │
│    Before:  (A{2}){3}               After:  A{6}                    │
│                                                                     │
│      GROUP {3,3}                      VAR:A {6,6}                   │
│       └── VAR:A {2,2}                                               │
│                                                                     │
│    Calculation: min = 2*3 = 6, max = 2*3 = 6                        │
│                                                                     │
│  Note: Only safe when inner or outer quantifier has min == max      │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

    Optimization Order:
      1. unwrapGroups    - Remove unnecessary structure
      2. removeDuplicates - Eliminate redundant alternatives
      3. optimizeQuantifiers - Merge quantifiers

    Combined Example:

      Input: "((A | A) B B)"

      Step 1 (unwrapGroups):
        GROUP{1,1} -> SEQ, inner GROUP{1,1} -> ALT
        Result: SEQ[ALT[A,A], B, B]

      Step 2 (removeDuplicates):
        ALT[A,A] -> A
        Result: SEQ[A, B, B]

      Step 3 (optimizeQuantifiers):
        B B -> B{2}
        Result: SEQ[A, B{2}]


11. AST to PatternElement[] Compilation
------------------------------------------------------------------------

    The optimized AST is flattened into a linear PatternElement array.
    Each element contains pointers (next, jump) for navigation and depth
    for counter indexing. This flat structure enables efficient state
    transitions during NFA execution.

┌─────────────────────────────────────────────────────────────────────┐
│                    AST Flattening Example                           │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Pattern: "(A | B)+ C"                                              │
│                                                                     │
│  AST:                          PatternElement[]:                    │
│                                                                     │
│    SEQ                         [0] #ALT  next:1              d:1    │
│     ├── GROUP {1,∞}            [1] A     next:3, jump:2      d:2    │
│     │    └── ALT               [2] B     next:3, jump:-1     d:2    │
│     │         ├── VAR:A        [3] #END  next:4, jump:0      d:0    │
│     │         └── VAR:B                  min:1, max:∞               │
│     └── VAR:C {0,1}            [4] C     next:5, min:0, max:1 d:0   │
│                                [5] #FIN  next:-1                    │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

    Pointer Rules:

      next pointer:
        - Sequential elements: index of next element
        - Last element before #FIN: points to #FIN
        - #FIN: -1 (terminal)

      jump pointer:
        - #END: group start index (loop back)
        - ALT branch first element: next alternative start
        - Last alternative: -1

      depth:
        - Top level: 0
        - Inside GROUP/ALT: parent depth + 1
        - #END: parent depth (for repeat counter indexing)

    Flattening Process:

      1. Traverse AST recursively
      2. For each node type:
         - VAR: emit PatternElement with varId, min, max, depth
         - GROUP: flatten content, emit #END with min/max/jump
         - ALT: emit #ALT, flatten each alternative with jump chain
         - SEQ: flatten each item sequentially
      3. Emit #FIN at end
      4. Resolve next pointers (forward references)


┌─────────────────────────────────────────────────────────────────────┐
│                    Pointer Resolution Example                       │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Pattern: "A | B | C"                                               │
│                                                                     │
│  [0] #ALT  next:1, jump:-1                                          │
│       │                                                             │
│       ├──▶ [1] A  next:4, jump:2  ──┐                              │
│       │                              │                              │
│       ├──▶ [2] B  next:4, jump:3  ──┤ (all point to #FIN)          │
│       │                              │                              │
│       └──▶ [3] C  next:4, jump:-1 ──┘                              │
│                                                                     │
│  [4] #FIN  next:-1                                                  │
│                                                                     │
│  #ALT.next = first branch (A)                                       │
│  Each branch.jump = next branch (or -1 for last)                    │
│  Each branch.next = element after ALT (#FIN)                        │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

Thank you for the detailed design documentation. While learning the
document, just a quick comment and question.

> Hi hackers,
> 
> I've been working on an alternative implementation approach for Row
> Pattern Recognition (RPR) that addresses some limitations in the
> current regex-based patch.
> 
> Key differences from the existing approach:
> 
> 1. Streaming NFA instead of regex engine
>    - Process rows incrementally without accumulating encoded strings
>    - Avoids O(V^N) combinatorial explosion in multi-variable scenarios

Sounds good. As you already pointed out, current approach has a memory
space problem. If Streaming NFA could solve the issue, it would be
really good.

> 2. No 26-variable limit
>    - Variables identified by index, not alphabet encoding

Sounds good.

> 3. Proper Lexical Order support
>    - Respects PATTERN alternative order for ONE ROW PER MATCH

Here do you have "ONE ROW PER MATCH" option of RPR in your mind? In my
understanding it's in MATCH_RECOGNIZE clause, but not in RPR in Window
clause. (ALL ROWS PER MATCH is not applicable either in RPR in
Window clause).

> 4. GREEDY/RELUCTANT quantifier support
>    - Longest vs shortest match semantics

Sounds good.

> 5. Incremental MEASURES computation
>    - Aggregate values computed during matching, no rescan needed
> 
> The attached document describes the design in detail, including:
> - Data structures (Pattern, MatchState, MatchContext)
> - Execution flow and state transitions
> - Context absorption optimization for greedy patterns
> - AST optimization passes
> 
> This is still a work in progress. I'd appreciate any feedback on
> the approach before proceeding with PostgreSQL integration.

I understand you are still in the design phase and sorry for jumping
into an implementation question. but If you have an idea, please
advice:

How do you handle '{' and '}' in the PATTERN clause in the raw parser?
I am not a parser expert but it seems it's not easy to handle '{' and
'}' in gram.y.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Ishii-san,

Thank you for the quick feedback and helpful spec clarifications!

2026년 1월 3일 (토) AM 10:05, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Hi Henson,

Thank you for the detailed design documentation. While learning the
document, just a quick comment and question.

> Hi hackers,
>
> I've been working on an alternative implementation approach for Row
> Pattern Recognition (RPR) that addresses some limitations in the
> current regex-based patch.
>
> Key differences from the existing approach:
>
> 1. Streaming NFA instead of regex engine
>    - Process rows incrementally without accumulating encoded strings
>    - Avoids O(V^N) combinatorial explosion in multi-variable scenarios

Sounds good. As you already pointed out, current approach has a memory
space problem. If Streaming NFA could solve the issue, it would be
really good.

> 2. No 26-variable limit
>    - Variables identified by index, not alphabet encoding

Sounds good.

> 3. Proper Lexical Order support
>    - Respects PATTERN alternative order for ONE ROW PER MATCH

Here do you have "ONE ROW PER MATCH" option of RPR in your mind? In my
understanding it's in MATCH_RECOGNIZE clause, but not in RPR in Window
clause. (ALL ROWS PER MATCH is not applicable either in RPR in
Window clause).


You're absolutely right - thank you for the correction!

I'm currently exploring what this NFA structure could theoretically
support, rather than strictly binding to the spec yet. Since I'm
still learning from Oracle manuals and your code without access to
the full SQL:2016 standard, I mixed up MATCH_RECOGNIZE syntax with
Window clause RPR - sorry for the confusion!

Once I have a clearer understanding of the spec, I'll properly
define how it integrates with PostgreSQL's grammar.

Your spec knowledge is invaluable as I continue learning. Thank you!
 
> 4. GREEDY/RELUCTANT quantifier support
>    - Longest vs shortest match semantics

Sounds good.

> 5. Incremental MEASURES computation
>    - Aggregate values computed during matching, no rescan needed
>
> The attached document describes the design in detail, including:
> - Data structures (Pattern, MatchState, MatchContext)
> - Execution flow and state transitions
> - Context absorption optimization for greedy patterns
> - AST optimization passes
>
> This is still a work in progress. I'd appreciate any feedback on
> the approach before proceeding with PostgreSQL integration.

I understand you are still in the design phase and sorry for jumping
into an implementation question. but If you have an idea, please
advice:


Not at all - implementation questions are valuable advice that
help catch what I might miss in the design phase!
 
How do you handle '{' and '}' in the PATTERN clause in the raw parser?
I am not a parser expert but it seems it's not easy to handle '{' and
'}' in gram.y.


You're right - it's not straightforward. Both gram.y and scan.l
need to be modified together.

I've attached a rough patch showing one possible approach. However,
since the OR handling has also been modified in SQL/PGQ, there will
likely be conflicts that need to be resolved when integrating.
 
Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> Here do you have "ONE ROW PER MATCH" option of RPR in your mind? In my
>> understanding it's in MATCH_RECOGNIZE clause, but not in RPR in Window
>> clause. (ALL ROWS PER MATCH is not applicable either in RPR in
>> Window clause).
>>
>>
> You're absolutely right - thank you for the correction!
> 
> I'm currently exploring what this NFA structure could theoretically
> support, rather than strictly binding to the spec yet. Since I'm
> still learning from Oracle manuals and your code without access to
> the full SQL:2016 standard, I mixed up MATCH_RECOGNIZE syntax with
> Window clause RPR - sorry for the confusion!

No problem at all. MATCH_RECOGNIZE and Window clause RPR are quite
similar. In the mean time "Trino" manual maybe useful for you if you
don't have access to the SQL standard.
https://trino.io/docs/current/sql/pattern-recognition-in-window.html

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

Thank you for the comprehensive review!

> SQL/RPR Patch Review Report
> ============================
> 
> Patch: Row Pattern Recognition (SQL:2016)
> Commitfest: https://commitfest.postgresql.org/patch/4460
> 
> Review Methodology:
>   This review focused on quality assessment, not line-by-line code audit.
>   Key code paths and quality issues were examined with surrounding context
>   when concerns arose. Documentation files were reviewed with AI-assisted
>   grammar and typo checking. Code coverage was measured using gcov and
>   custom analysis tools.
> 
> Limitations:
>   - Not a security audit or formal verification
>   - Parser and executor internals reviewed at module level, not exhaustively
>   - Performance characteristics not benchmarked
> 
> 
> TABLE OF CONTENTS
> -----------------
> 
> 1. Executive Summary
> 2. Issues Found
>    2.1 Critical / Major
>    2.2 Minor Issues (Review Needed)
>    2.3 Minor Issues (Style)
>    2.4 Suggestions for Discussion
> 3. Test Coverage
>    3.1 Covered Areas
>    3.2 Untested Items
>    3.3 Unimplemented Features (No Test Needed)
> 4. Code Coverage Analysis
>    4.1 Overall Coverage
>    4.2 Coverage by File
>    4.3 Uncovered Code Risk Assessment
> 5. Commit Analysis
> 6. Recommendations
> 7. Conclusion
> 
> 
> 1. EXECUTIVE SUMMARY
> --------------------
> 
> Overall assessment: GOOD

Glad to hear that.

> The SQL/RPR patch demonstrates solid implementation quality within its
> defined scope. Code follows PostgreSQL coding standards (with minor style
> issues), test coverage is comprehensive at 96.4%, and documentation is
> thorough with only minor typos.
> 
> Rating by Area:
> - Code Quality:     Good (PostgreSQL style compliant, 26 static style fixes
> recommended)
> - Test Coverage:    Good (96.4% line coverage, 28 test cases)
> - Documentation:    Good (Complete, 1 minor typo)
> - Build/Regress:    Pass (make check-world, 753 tests passed)
> 
> 
> 2. ISSUES FOUND
> ---------------
> 
> 2.1 Critical / Major
> 
> #1 [Code] Greedy pattern combinatorial explosion
>    Pattern: PATTERN (A+ B+ C+) with DEFINE A AS TRUE, B AS TRUE, C AS TRUE
>    Impact: Memory exhaustion or infinite wait
>    Recommendation: Add work_mem-based memory limit (error on exceed)

Not sure it's a good solution. I think it's acceptable for users that
the query execution getting slow down when there's not enough
work_mem, but ending up with ERROR would not be acceptable. In order
to run the query without ERROR (and the query getting slow) when
there's not enough memory, RPR needs to use temporary files. Problem
is, if the access pattern is random, accessing files in random manner
would be extremely slow. Unfortunately RPR's pattern match access
pattern is surely random in the current patch.  Thus I think adding
memory usage check is not worth the trouble. What do you think?

Instead we need to look for alternative algorithm to perform the
search.  I hope streaming NFA is a good candidate.

>    Evidence - No memory limit in current code:
>    - nodeWindowAgg.c:5718-5722 string_set_init(): palloc() unconditional
>    - nodeWindowAgg.c:5741-5750 string_set_add(): set_size *= 2; repalloc()
> unlimited
>    - nodeWindowAgg.c:5095-5174 generate_patterns(): Triple loop, no limit
> 
>    Only work_mem usage in RPR (nodeWindowAgg.c:1297):
>      winstate->buffer = tuplestore_begin_heap(false, false, work_mem);
>    -> For tuple buffer, unrelated to pattern combination memory (StringSet)
>
> 2.2 Minor Issues (Review Needed)
> 
> #1 [Code] nodeWindowAgg.c:5849,5909,5912
>    pos > NUM_ALPHABETS check - intent unclear, causes error at 28 PATTERN
> elements

Yeah, in variable_pos_fetch() and variable_pos_register(), following
lines are wrong.
	if (pos < 0 || pos > NUM_ALPHABETS)
	if (index < 0 || index > NUM_ALPHABETS)

They should have been:
	if (pos < 0 || pos >= NUM_ALPHABETS)
	if (index < 0 || index >= NUM_ALPHABETS)

Will fix.

>    Reproduction:
>    - PATTERN (A B C ... Z A) (27 elements) -> OK
>    - PATTERN (A B C ... Z A B) (28 elements) -> ERROR "initial is not valid
> char: b"
> 
> 2.3 Minor Issues (Style)
> 
> #1 [Code] nodeWindowAgg.c (25 blocks)
>    #ifdef RPR_DEBUG -> recommend elog(DEBUG2, ...) or remove

I replaced each of them to "printf...". This way, each debug line is
not accompanied with a query, which is good for developers.

> #2 [Code] src/backend/executor/nodeWindowAgg.c
>    static keyword on separate line (26 functions)

Fixed.

> #3 [Code] src/backend/utils/adt/ruleutils.c
>    Whitespace typo: "regexp !=NULL" -> "regexp != NULL"

Fixed.

> #4 [Code] nodeWindowAgg.c:4619
>    Error message case: "Unrecognized" -> "unrecognized" (PostgreSQL style)

Fixed.

> #5 [Doc] doc/src/sgml/ref/select.sgml:1128
>    Typo: "maximu" -> "maximum"

Fixed.

> 2.4 Suggestions for Discussion
> 
> #1 Incremental matching with streaming NFA redesign
>    Benefits:
>    - O(n) time complexity per row (current: exponential in worst case)
>    - Bounded memory via state merging and context absorption
>    - Natural extension for OR patterns, {n,m} quantifiers, nested groups
>    - Enables MEASURES clause with incremental aggregates
>    - Proven approach in CEP engines (Flink, Esper)

I looking forward to join the discussion.

> 3. TEST COVERAGE
> ----------------
> 
> 3.1 Covered Areas
> 
> - PATTERN clause: +, *, ? quantifiers (line 41, 71, 86)
> - DEFINE clause: Variable conditions, auto-TRUE for missing (line 120-133)
> - PREV/NEXT functions: Single argument (line 44, 173)
> - AFTER MATCH SKIP: TO NEXT ROW (line 182), PAST LAST ROW (line 198)
> - Aggregate integration: sum, avg, count, max, min (line 258-277)
> - Window function integration: first_value, last_value, nth_value (line
> 34-35)
> - JOIN/CTE: JOIN (line 313), WITH (line 324)
> - View: VIEW creation, pg_get_viewdef (line 390-406)
> - Error cases: 7 error scenarios (line 409-532)
> - Large partition: 5000 row smoke test (line 360-387)
> - ROWS BETWEEN offset: CURRENT ROW AND 2 FOLLOWING (line 244)
> 
> 3.2 Untested Items
> 
> Feature                  Priority   Recommendation
> -------------------------------------------------------------------------------
> 26 variable limit        Medium     Test 26 variables success, 27th
> variable error
> NULL value handling      Low        Test PREV(col) where col or previous
> row is NULL
> 
> Sample test for 26 variable limit:
> 
>     -- Should fail with 27th variable (parser error, no table needed)
>     SELECT * FROM (SELECT 1 AS x) t
>     WINDOW w AS (
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       PATTERN (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
>       DEFINE a AS TRUE, b AS TRUE, c AS TRUE, d AS TRUE, e AS TRUE, f AS
> TRUE,
>              g AS TRUE, h AS TRUE, i AS TRUE, j AS TRUE, k AS TRUE, l AS
> TRUE,
>              m AS TRUE, n AS TRUE, o AS TRUE, p AS TRUE, q AS TRUE, r AS
> TRUE,
>              s AS TRUE, t AS TRUE, u AS TRUE, v AS TRUE, w AS TRUE, x AS
> TRUE,
>              y AS TRUE, z AS TRUE, aa AS TRUE
>     );
>     -- ERROR: number of row pattern definition variable names exceeds 26

Good cacth. I will add the test. BTW, the sample test SQL can be
simplied like this:

SELECT * FROM (SELECT 1 AS x) t
 WINDOW w AS (
 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
 PATTERN (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
 DEFINE a AS TRUE
);

Because if a pattern varible (for example "b") is not in the DEFINE
clause, it is treated as if being defined "b AS TRUE" per spec. Same
thing can be said to other pattern variables c ... aa).

> Sample test for NULL handling:
> 
>     CREATE TEMP TABLE stock_null (company TEXT, tdate DATE, price INTEGER);
>     INSERT INTO stock_null VALUES ('c1', '2023-07-01', 100);
>     INSERT INTO stock_null VALUES ('c1', '2023-07-02', NULL);  -- NULL in
> middle
>     INSERT INTO stock_null VALUES ('c1', '2023-07-03', 200);
>     INSERT INTO stock_null VALUES ('c1', '2023-07-04', 150);
> 
>     SELECT company, tdate, price, count(*) OVER w AS match_count
>     FROM stock_null
>     WINDOW w AS (
>       PARTITION BY company
>       ORDER BY tdate
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       PATTERN (START UP DOWN)
>       DEFINE START AS TRUE, UP AS price > PREV(price), DOWN AS price <
> PREV(price)
>     );
>     -- Result: all rows show match_count = 0 (NULL breaks pattern matching)

Thanks. I will add this test.

> 3.3 Unimplemented Features (No Test Needed)
> 
> Per documentation (select.sgml:1133-1136):
> - MEASURES clause: Not implemented
> - SUBSET clause: Not implemented
> - AFTER MATCH variants: Only SKIP TO NEXT ROW, PAST LAST ROW supported
> 
> Not in documentation, verified by testing:
> - {n,m} quantifier: Parser error ("syntax error at or near {")
> - (A|B) OR pattern: Not supported (parsed as single variable name "a|b")
> - (A B)+ compound repetition: Parser accepts, but execution returns 0
> matches
> 
> 
> 4. CODE COVERAGE ANALYSIS
> -------------------------
> 
> 4.1 Overall Coverage
> 
> 96.4% (732 / 759 lines)
> 
> 4.2 Coverage by File (major RPR-modified files)
> 
> nodeWindowAgg.c:    96.6% (560/580) - Pattern matching execution engine
> parse_clause.c:     96.7% (88/91) - PATTERN/DEFINE analysis
> ruleutils.c:        93.1% (54/58) - pg_get_viewdef output
> 
> 4.3 Uncovered Code Risk Assessment
> 
> Total: 27 lines uncovered
> 
> Medium Risk (2 items) - Test addition recommended (see section 3.2):
> - parse_clause.c:4093: transformDefineClause - 27th variable error
> - nodeWindowAgg.c:5623: get_slots - null_slot for PREV at partition first
> row
> 
> Low Risk (25 items) - Defensive code / Unreachable:
> - nodeWindowAgg.c:3074: attno_map_walker - Parser validates arg count
> - nodeWindowAgg.c:3137-3138: rpr_navigation_walker - switch default
> - nodeWindowAgg.c:3566: window_gettupleslot - Before mark position
> - nodeWindowAgg.c:4289: WinGetFuncArgInFrame - isout flag
> - nodeWindowAgg.c:4393: WinGetSlotInFrame - Boundary check
> - nodeWindowAgg.c:4618-4619: row_is_in_reduced_frame - switch default
> - nodeWindowAgg.c:4697: register_reduced_frame_map - pos < 0 check
> - nodeWindowAgg.c:5007: search_str_set - NULL return continue
> - nodeWindowAgg.c:5405: do_pattern_match - Regex compile error
> - nodeWindowAgg.c:5435,5437-5438: do_pattern_match - Regex exec error
> - nodeWindowAgg.c:5700: pattern_initial - Variable not found
> - nodeWindowAgg.c:5776: string_set_get - Index range check
> - nodeWindowAgg.c:5850: variable_pos_register - a-z range check
> - nodeWindowAgg.c:5910: variable_pos_fetch - a-z range check
> - nodeWindowAgg.c:5913: variable_pos_fetch - Index range check
> - parse_clause.c:3989: transformDefineClause - A_Expr type check
> - parse_clause.c:4145: transformPatternClause - A_Expr type check
> - ruleutils.c:6904-6908: get_rule_windowspec - SKIP TO NEXT ROW output
> 
> Conclusion: Most uncovered code consists of defensive error handling or
> code unreachable due to parser pre-validation. No security or functional
> risk.
> 
> 
> 5. COMMIT ANALYSIS
> ------------------
> 
> 8 sequential commits:
> 
> Commit  Area            Files   +/-         Key Content
> -------------------------------------------------------------------------------
> 1       Raw Parser      4       +174/-16    gram.y grammar (PATTERN/DEFINE)
> 2       Parse/Analysis  4       +277/-1     parse_clause.c analysis logic
> 3       Rewriter        1       +109/-0     pg_get_viewdef extension
> 4       Planner         5       +73/-3      WindowAgg plan node extension
> 5       Executor        4       +1,942/-11  CORE: Pattern matching engine
> (+1,850)
> 6       Docs            3       +192/-7     advanced.sgml, func-window.sgml
> 7       Tests           3       +1,585/-1   rpr.sql (532), rpr.out (1,052)
> 8       typedefs        1       +6/-0       pgindent support
> 
> Code Change Statistics:
> - Total files: 25
> - Lines added: 4,358
> - Lines deleted: 39
> - Net increase: +4,319 lines
> 
> 
> 6. RECOMMENDATIONS
> ------------------
> 
> 6.1 Combinatorial Explosion Prevention (Major, Required)
> 
> Add work_mem-based memory limit for StringSet allocation.
> Location: string_set_add() in nodeWindowAgg.c:5741-5750
> Consistent with existing PostgreSQL approach (Hash Join, Sort, etc.)

See the comment above.

> 6.2 Code Review Required (Minor, Decision Needed)
> 
> Location: nodeWindowAgg.c:5849,5909,5912
> Issue: pos > NUM_ALPHABETS check intent unclear
> Current: PATTERN with 28 elements causes error
> Question: Is 27 element limit intentional?

I think these are addressed in the attached v37 patch.

> 6.3 Code Style Fixes (Minor)
> 
> - #ifdef RPR_DEBUG: Use elog(DEBUG2, ...) or remove (25 blocks)
> - static keyword on separate line: 26 functions to fix
> - Whitespace: "regexp !=NULL" -> "regexp != NULL"
> - Error message case: "Unrecognized" -> "unrecognized"

Fixed in v37.

> 6.4 Documentation Fixes (Minor)
> 
> - select.sgml: "maximu" -> "maximum"

Fixed in v37.

> 6.5 Test Additions (Optional)
> 
> Black-box Tests (Functional):
> 
> Feature              Test Case                                    Priority
> -------------------------------------------------------------------------------
> Variable limit       26 variables success, 27 error               Medium
> NULL boundary        PREV at partition first row                  Medium
> 
> White-box Tests (Coverage) - covered by above black-box tests:
> 
> File:Line                          Target Branch
> -------------------------------------------------------------------------------
> parse_clause.c:4093                Limit error branch (Variable limit test)
> nodeWindowAgg.c:5623               null_slot usage (NULL boundary test)

Test added in the v37 patch.

> 7. CONCLUSION
> -------------
> 
> Test Quality: GOOD
> 
> Core functionality is thoroughly tested with comprehensive error case
> coverage.
> 
> The patch is well-implemented within its defined scope. Identified issues
> include
> one major concern (combinatorial explosion) and minor style/documentation
> items.
> 
> Recommended actions before commit:
> 1. Add work_mem-based memory limit for pattern combinations (required)
> 2. Clarify pos > NUM_ALPHABETS check intent (review needed)
> 3. Fix code style issues (optional but recommended)
> 4. Fix documentation typo (trivial)
> 5. Add tests for variable limit and NULL handling (optional)
> 
> Points for discussion (optional):
> 6. Incremental matching with streaming NFA redesign

Definitely we need discussion on this.

> Attachment:
> - coverage.tgz (gcov HTML report, RPR-modified code only)
> 
> 
> ---
> End of Report

Again thank you for the review. Attached are the v37 patches. This
time I added a short description about the patch to the 001 patch. In
the file description about what are implemented and waht not
implemented. Hope this helps to understand the current status of the
patches.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Ishii-san,

I've been working on an NFA implementation prototype.

This is a very early prototype - still buggy and incomplete,
but shows the basic approach. Attached HTML file - open in
browser (runs locally, no server needed).

I used JavaScript for quick prototyping and visualization.
The actual PostgreSQL implementation would be in C, but the
algorithm logic remains the same.

To test:
1. Use default pattern
2. Enter variables sequentially: A, B, C, D, E, F, G, H, I
3. Try different patterns and options in the UI

Implemented:
- Patterns: *, +, ?, (A|B), (A B)+
- Reluctant quantifiers: A+?, A*? (switches to reluctant mode)
  Note: This part probably has issues
- Execution trace with state visualization
- Context management: multiple matches, absorption
- Options: SKIP modes, output modes

Many rough edges, especially reluctant matching.
Just sharing the direction.

My responses may be slow due to company work during weekdays.

Best regards,
Henson

Re: Row pattern recognition

От:
Jacob Champion <jacob.champion@enterprisedb.com>
Дата:
On Sun, Jan 4, 2026 at 7:50 AM Henson Choi  wrote:
> I've been working on an NFA implementation prototype.

Neat! In case it helps, you may also be interested in my (now very out
of date) mails at [1] and [2].

At one point I was also working on an independent implementation of
the preferment rules, to make it easier for developers to intuit how
matches were made, but I can't find that email at the moment. This may
have some overlap with "state visualization" for the engine? I have a
3k-line patch based on top of v22 of the patchset as of September
2024, if there is interest in that, but no promises on quality -- I
would have posted it if I thought it was ready for review :D

Thanks,
--Jacob

[1] https://postgr.es/m/96b4d3c8-1415-04db-5629-d2617ac7a156%40timescale.com
[2] https://postgr.es/m/CAGu%3Du8gcyAQAsDLp-01R21%3DM4bpAiGP9PZz0OyiMo5_bM30PMA%40mail.gmail.com


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> On Sun, Jan 4, 2026 at 7:50 AM Henson Choi  wrote:
>> I've been working on an NFA implementation prototype.
> 
> Neat! In case it helps, you may also be interested in my (now very out
> of date) mails at [1] and [2].
> 
> At one point I was also working on an independent implementation of
> the preferment rules, to make it easier for developers to intuit how
> matches were made, but I can't find that email at the moment.

Maybe this?

https://www.postgresql.org/message-id/CAOYmi%2Bns3kHjC83ap_BCfJCL0wfO5BJ_sEByOEpgNOrsPhqQTg%40mail.gmail.com

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Jacob Champion <jacob.champion@enterprisedb.com>
Дата:
On Mon, Jan 5, 2026 at 3:26 PM Tatsuo Ishii  wrote:
> Maybe this?
>
> https://www.postgresql.org/message-id/CAOYmi%2Bns3kHjC83ap_BCfJCL0wfO5BJ_sEByOEpgNOrsPhqQTg%40mail.gmail.com

That's the one, thanks!

--Jacob


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

Thank you for the design proposal. I'm still learning it, and I have a
few questions for now.

> 3. Proper Lexical Order support
>    - Respects PATTERN alternative order for ONE ROW PER MATCH

RPR in WINDOW clause does not allow to specify "ONE ROW PER MATCH".
(nor ALL ROWS PER MATCH). So I am not sure what you mean here.

> 4. GREEDY/RELUCTANT quantifier support
>    - Longest vs shortest match semantics
> 
> 5. Incremental MEASURES computation
>    - Aggregate values computed during matching, no rescan needed

In my understanding MEASURES does not directly connect to Aggregate
computation with rescan. Can you elaborate why implementing MEASURES
allows to avoid recan for aggregate computation?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Neat! In case it helps, you may also be interested in my (now very out
of date) mails at [1] and [2].

 Thanks for the pointers! I'll definitely dig into those threads.


At one point I was also working on an independent implementation of
the preferment rules, to make it easier for developers to intuit how
matches were made, but I can't find that email at the moment. This may
have some overlap with "state visualization" for the engine? I have a
3k-line patch based on top of v22 of the patchset as of September
2024, if there is interest in that, but no promises on quality -- I
would have posted it if I thought it was ready for review :D

I'd definitely be interested in seeing it, rough edges and all. I haven't
tackled the PostgreSQL integration design yet, so understanding how
preferment rules map to the existing infrastructure would be very helpful.
(Tatsuo found that email, by the way.)
 

Thanks,
--Jacob

[1] https://postgr.es/m/96b4d3c8-1415-04db-5629-d2617ac7a156%40timescale.com
[2] https://postgr.es/m/CAGu%3Du8gcyAQAsDLp-01R21%3DM4bpAiGP9PZz0OyiMo5_bM30PMA%40mail.gmail.com

Best regards,
Henson 

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Ishii-san,
Thank you for the questions and corrections!

> 3. Proper Lexical Order support
>    - Respects PATTERN alternative order for ONE ROW PER MATCH

RPR in WINDOW clause does not allow to specify "ONE ROW PER MATCH".
(nor ALL ROWS PER MATCH). So I am not sure what you mean here.

You're absolutely right to point this out. I've been working without access
to the SQL:2016 standard, relying on Oracle manuals and your implementation,
which led me to incorrectly treat Window clause RPR as a variant of
MATCH_RECOGNIZE.

I now realize there are fundamental differences between R010 (RPR in window
functions) and R020 (MATCH_RECOGNIZE), and I was conflating the two. My
company is supportive of this work, and we're planning to purchase the
standard next week so I can properly understand the spec requirements.

Thank you for catching this - it's exactly the kind of spec guidance I need
as I continue learning.

  > 5. Incremental MEASURES computation
>    - Aggregate values computed during matching, no rescan needed

In my understanding MEASURES does not directly connect to Aggregate
computation with rescan. Can you elaborate why implementing MEASURES
allows to avoid recan for aggregate computation?
 
Let me clarify what I meant by "incremental aggregation" and "rescan":
In the NFA design, I'm building infrastructure for incremental aggregate
computation during pattern matching - maintaining SUM, COUNT, etc. as the
match progresses. When a match completes, if only aggregate functions are
needed, the result can be produced without accessing the original rows again.

I used "rescan" to contrast this with what I assumed was the existing
approach: match first, then aggregate over the matched row range afterward.
However, I haven't studied your implementation carefully enough to know if
this assumption is correct.

Could you clarify how aggregates are currently computed after pattern matching
in your implementation? This would help me understand whether the incremental
approach actually provides a benefit, or if I'm solving a problem that doesn't
exist.

Regarding MEASURES - I incorrectly connected it to this aggregation discussion.
As you noted, MEASURES is a separate R020 feature, not part of R010. The
incremental aggregation infrastructure would support both cases, but they're
distinct features.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
>> 3. Proper Lexical Order support
>> >    - Respects PATTERN alternative order for ONE ROW PER MATCH
>>
>> RPR in WINDOW clause does not allow to specify "ONE ROW PER MATCH".
>> (nor ALL ROWS PER MATCH). So I am not sure what you mean here.
> 
> 
> You're absolutely right to point this out. I've been working without access
> to the SQL:2016 standard, relying on Oracle manuals and your implementation,
> which led me to incorrectly treat Window clause RPR as a variant of
> MATCH_RECOGNIZE.
> 
> I now realize there are fundamental differences between R010 (RPR in window
> functions) and R020 (MATCH_RECOGNIZE), and I was conflating the two. My
> company is supportive of this work, and we're planning to purchase the
> standard next week so I can properly understand the spec requirements.
> 
> Thank you for catching this - it's exactly the kind of spec guidance I need
> as I continue learning.

Glad to hear that you are planning to purchase the standard.  I was
advised by Vik and Jacob the same thing and I really appreciate them
for the suggestion. Without access to 19075-5, I think it's not
possible to implement RPR.

>   > 5. Incremental MEASURES computation
> 
>> >    - Aggregate values computed during matching, no rescan needed
>>
>> In my understanding MEASURES does not directly connect to Aggregate
>> computation with rescan. Can you elaborate why implementing MEASURES
>> allows to avoid recan for aggregate computation?
>>
> 
> Let me clarify what I meant by "incremental aggregation" and "rescan":
> In the NFA design, I'm building infrastructure for incremental aggregate
> computation during pattern matching - maintaining SUM, COUNT, etc. as the
> match progresses. When a match completes, if only aggregate functions are
> needed, the result can be produced without accessing the original rows
> again.

Oh, ok.

> I used "rescan" to contrast this with what I assumed was the existing
> approach: match first, then aggregate over the matched row range afterward.
> However, I haven't studied your implementation carefully enough to know if
> this assumption is correct.

As far as RPR concerns, you are correct. Current implementation does
the "rescan". 

> Could you clarify how aggregates are currently computed after pattern
> matching
> in your implementation? This would help me understand whether the
> incremental
> approach actually provides a benefit, or if I'm solving a problem that
> doesn't
> exist.

Yes, if RPR is enabled, we restart to compute aggregation from the
head of the "reduced frame" (which means the starting row of the
pattern matching), to the end of matching rows. Without RPR,
PostgreSQL reuses the previous aggregate result in some conditions to
avoid the restarting (see the long comment in
eval_windowaggregates()). But currently I think it's not possible for
RPR to avoid it. The reason was explained in the v17 patch (posted on
2024/4/28):

  - In 0005 executor patch, aggregation in RPR always restarts for each
  row. This is necessary to run aggregates on no matching (due to
  skipping) or empty matching (due to no pattern variables matches)
  rows to produce NULL (most aggregates) or 0 (count) properly. In v16
  I had a hack using a flag to force the aggregation results to be
  NULL in case of no match or empty match in
  finalize_windowaggregate(). v17 eliminates the dirty hack.

> Regarding MEASURES - I incorrectly connected it to this aggregation
> discussion.
> As you noted, MEASURES is a separate R020 feature, not part of R010. The
> incremental aggregation infrastructure would support both cases, but they're
> distinct features.

I think R010 has MEASURES too.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Subject: Re: Row pattern recognition

Hi Ishii-san,

I've been working on the pattern grammar and AST for row pattern recognition.
The attached patch extends the PATTERN clause to support more regex-like syntax.

The main additions are:

- Alternation: (A | B)
- Grouping with quantifiers: (A B)+, (A | B)*
- Full quantifier support: +, *, ?, {n}, {n,}, {n,m}
- Reluctant quantifiers: +?, *?, ?? (parsed but not executed yet)

I've introduced RPRPatternNode to represent the pattern as a Thompson-style
AST with four node types: VAR, SEQ, ALT, and GROUP. Each node stores min/max
bounds for quantifiers and a reluctant flag. This should make the eventual
NFA implementation more straightforward.

The parser also does some basic pattern optimizations. For example:
  - (A (B C)) gets flattened to (A B C)
  - ((A)) unwraps to just A
  - (A{2}){3} becomes A{6}
  - (A | B | A) simplifies to (A | B)
  - A A A merges into A{3,3}

I also updated ruleutils.c to deparse patterns properly.


Current state:

The executor still uses regex matching, which works but has some limitations.
Complex patterns with lots of alternations can be slow.

The 26-variable limit is still there since we're mapping to [a-z] for the regex.

Reluctant quantifiers (+?, *?, ??) are parsed but will raise an error if you
try to use them. They'll need proper NFA support to work correctly.

Some optimization code was removed in the process, but it should work better
once NFA matching is in place.


Next steps:

The plan is to replace regex matching with NFA-based execution. The AST
structure is already set up for that.

The first step is converting the Thompson AST into a flat representation -
flattening pattern elements and building actual NFA states with transitions,
then replacing the regex engine with direct NFA matching. This should handle all
the pattern syntax properly, including reluctant quantifiers.

Once that's working, the next step is handling multiple contexts during matching -
tracking which states are active and absorbing context as we go through rows.
This is essential for proper pattern matching behavior.

After that, I'll implement PATH and CLASSIFIER functions, which depend on having
the match context available.

Then there's room for various optimizations - PATH space optimization,
incremental aggregate computation over matched rows, better state merging, etc.

Longer-term, the goal is to get to MATCH_RECOGNIZE in the FROM clause for
full SQL standard compliance.

Let me know if you have any concerns or suggestions about the approach.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Ishii-san,
> 
> I've been working on the pattern grammar and AST for row pattern
> recognition.
> The attached patch extends the PATTERN clause to support more regex-like
> syntax.
> 
> The main additions are:
> 
> - Alternation: (A | B)
> - Grouping with quantifiers: (A B)+, (A | B)*
> - Full quantifier support: +, *, ?, {n}, {n,}, {n,m}
> - Reluctant quantifiers: +?, *?, ?? (parsed but not executed yet)

Excellent!

> I've introduced RPRPatternNode to represent the pattern as a Thompson-style
> AST with four node types: VAR, SEQ, ALT, and GROUP. Each node stores min/max
> bounds for quantifiers and a reluctant flag. This should make the eventual
> NFA implementation more straightforward.
> 
> The parser also does some basic pattern optimizations. For example:
>   - (A (B C)) gets flattened to (A B C)
>   - ((A)) unwraps to just A
>   - (A{2}){3} becomes A{6}
>   - (A | B | A) simplifies to (A | B)
>   - A A A merges into A{3,3}
> 
> I also updated ruleutils.c to deparse patterns properly.
> 
> 
> Current state:
> 
> The executor still uses regex matching, which works but has some
> limitations.
> Complex patterns with lots of alternations can be slow.
>
> The 26-variable limit is still there since we're mapping to [a-z] for the
> regex.
> 
> Reluctant quantifiers (+?, *?, ??) are parsed but will raise an error if you
> try to use them. They'll need proper NFA support to work correctly.
> 
> Some optimization code was removed in the process, but it should work better
> once NFA matching is in place.

Yeah. Now the rpr regression takes more than 7 seconds.  (with current
v37 patch it takes 86ms). I expect NFA matching works better.

> Next steps:
> 
> The plan is to replace regex matching with NFA-based execution. The AST
> structure is already set up for that.

Sounds promising.

> The first step is converting the Thompson AST into a flat representation -
> flattening pattern elements and building actual NFA states with transitions,
> then replacing the regex engine with direct NFA matching. This should
> handle all
> the pattern syntax properly, including reluctant quantifiers.
> 
> Once that's working, the next step is handling multiple contexts during
> matching -
> tracking which states are active and absorbing context as we go through
> rows.
> This is essential for proper pattern matching behavior.

Ok.

> After that, I'll implement PATH and CLASSIFIER functions, which depend on
> having
> the match context available.

What is PATH function? It's not in R010 or R020 as far as I know.

> Then there's room for various optimizations - PATH space optimization,
> incremental aggregate computation over matched rows, better state merging,
> etc.

Sounds good.

> Longer-term, the goal is to get to MATCH_RECOGNIZE in the FROM clause for
> full SQL standard compliance.

What about MEASURES clause? Without it, many things in the standard
cannot be implemented.

> Let me know if you have any concerns or suggestions about the approach.

Here are some comments on your patches.

- It is based on my v36 patches. But the latest one is v37 patch.  It
  would be nice if you create patches based on the my latest patches.

- You are doing some optimization (like (A (B C)) gets flattened to (A
  B C) etc.) in the parse analysis phase. I think doing that kind of
  optimization should be done in the optimizer/planner. Because with
  your patch a deparsed query (as shown by pg_get_viewdef()) looks
  different from what user inputs.

- If you add files to src/backend/parser, it should be noted in
  src/backend/parser/README.
  
- It would be noce to update typedefs patch if you add new typedefs.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
> After that, I'll implement PATH and CLASSIFIER functions, which depend on
> having
> the match context available.

What is PATH function? It's not in R010 or R020 as far as I know.

A Match Path is essentially an array consisting of the CLASSIFIER() values of all rows
within a matched sequence, arranged in chronological order.
 
> Longer-term, the goal is to get to MATCH_RECOGNIZE in the FROM clause for
> full SQL standard compliance.

What about MEASURES clause? Without it, many things in the standard
cannot be implemented.

I admit that my current understanding of the full SQL standard is still evolving. However,
looking at the current codebase, I believed that the syntax I've implemented so far
could be addressed even before mastering every detail of the standard.
That is why I have taken a 'code-first' approach for this stage.

Of course, reaching 'FULL' compliance is undoubtedly the ultimate goal. Given
the complexity, I believe the features should be released in several incremental phases.
I trust that you will help define the strategic roadmap for these releases. As I continue to
deepen my understanding of the standard, I will do my best to contribute to the
technical roadmap as well. 

 
> Let me know if you have any concerns or suggestions about the approach.

Here are some comments on your patches.

- It is based on my v36 patches. But the latest one is v37 patch.  It
  would be nice if you create patches based on the my latest patches.
 
I will rebase my work on your latest v37 patch and move forward with that
for the next version. I’ll submit the updated patch soon.
 
- You are doing some optimization (like (A (B C)) gets flattened to (A
  B C) etc.) in the parse analysis phase. I think doing that kind of
  optimization should be done in the optimizer/planner. Because with
  your patch a deparsed query (as shown by pg_get_viewdef()) looks
  different from what user inputs.

I completely agree that those optimizations belong in the optimizer/planner phase.
I intentionally placed them in the parse analysis phase for now to make debugging
easier during this initial development stage. Once the logic is stabilized, I will move
them to the planner as you suggested to ensure proper deparsing.
 
- If you add files to src/backend/parser, it should be noted in
  src/backend/parser/README.

- It would be noce to update typedefs patch if you add new typedefs.

Thank you for pointing those out. I had overlooked the README in src/backend/parser,
and I will make sure to update it along with the typedefs patch in my next submission.
 
Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
>> What is PATH function? It's not in R010 or R020 as far as I know.
>>
> 
> A Match Path is essentially an array consisting of the CLASSIFIER() values
> of all rows
> within a matched sequence, arranged in chronological order.

So, the PATH function is Oracle specific? Or your own proposal?

>> > Longer-term, the goal is to get to MATCH_RECOGNIZE in the FROM clause for
>> > full SQL standard compliance.
>>
>> What about MEASURES clause? Without it, many things in the standard
>> cannot be implemented.
>>
> 
> I admit that my current understanding of the full SQL standard is still
> evolving. However,
> looking at the current codebase, I believed that the syntax I've
> implemented so far
> could be addressed even before mastering every detail of the standard.
> That is why I have taken a 'code-first' approach for this stage.
> 
> Of course, reaching 'FULL' compliance is undoubtedly the ultimate goal.
> Given
> the complexity, I believe the features should be released in several
> incremental phases.

I totally agree with the incremental approach.

> I trust that you will help define the strategic roadmap for these releases.
> As I continue to
> deepen my understanding of the standard, I will do my best to contribute to
> the
> technical roadmap as well.

Ok, here is my proposal for the strategic roadmap. This should be a
starting point of the discussion.

(1) The first release: this will a subset of R020 (RPR in Window
    clause), but will serve many of pratical uses of RPR.  The
    following features below will not be included.

    - MEASURES
    - SUBSET
    - SEEK
    - AFTER MATCH SKIP TO
    - AFTER MATCH SKIP TO FIRST
    - AFTER MATCH SKIP TO LAST
    - PERMUTE

Note 1: this list needs discussion and may be changed when the release
is made.

Note 2: Because MEASURES cannot be used in this release, all primary
row patter variables in the DEFINE clause must be unqualified ones
(i.e. "price", not "A.price") and they are implicitly qualified by the
universal row pattern variable. In this case the universal row pattern
variable is mapped to the current row, thus "price" in the DEFINE
clause is evaluated in the current row.

After (1) we can choose either (a) extend support for R020, i.e. add
more features to the first release, especially MEASURES or (b) support
a subset of R010 (MATCH_RECOGNIZE).

>> > Let me know if you have any concerns or suggestions about the approach.

> I will rebase my work on your latest v37 patch and move forward with that
> for the next version. I’ll submit the updated patch soon.

Thanks!

> I completely agree that those optimizations belong in the optimizer/planner
> phase.
> I intentionally placed them in the parse analysis phase for now to make
> debugging
> easier during this initial development stage. Once the logic is stabilized,
> I will move
> them to the planner as you suggested to ensure proper deparsing.

Understood. Looks like a good strategy.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
So, the PATH function is Oracle specific? Or your own proposal?


Match PATH is essentially the internal metadata or the trace log of which
Row Pattern Variable (Classifier) was assigned to each row during the
state machine's execution.

Match PATH is simply a set of Classifiers stored in the internal state.

> I trust that you will help define the strategic roadmap for these releases.
> As I continue to
> deepen my understanding of the standard, I will do my best to contribute to
> the
> technical roadmap as well.

Ok, here is my proposal for the strategic roadmap. This should be a
starting point of the discussion.

(1) The first release: this will a subset of R020 (RPR in Window
    clause), but will serve many of pratical uses of RPR.  The
    following features below will not be included.

    - MEASURES
    - SUBSET
    - SEEK
    - AFTER MATCH SKIP TO
    - AFTER MATCH SKIP TO FIRST
    - AFTER MATCH SKIP TO LAST
    - PERMUTE

Note 1: this list needs discussion and may be changed when the release
is made.

Note 2: Because MEASURES cannot be used in this release, all primary
row patter variables in the DEFINE clause must be unqualified ones
(i.e. "price", not "A.price") and they are implicitly qualified by the
universal row pattern variable. In this case the universal row pattern
variable is mapped to the current row, thus "price" in the DEFINE
clause is evaluated in the current row.

After (1) we can choose either (a) extend support for R020, i.e. add
more features to the first release, especially MEASURES or (b) support
a subset of R010 (MATCH_RECOGNIZE).

I am currently fixing the code to satisfy the existing test cases.
Once the modifications are complete, I'll share the details so we can
discuss the differences between the current status and the proposed
roadmap.
 
Best regards,
Henson 

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Ishii-san,


The attached patch implements streaming NFA-based pattern matching.
This is based on your v37 patch and the pattern grammar work I submitted earlier.

This is a testable draft for review, not production-ready yet. It allows
in-depth verification of pattern optimization, pattern matching/merging,
context absorption, and window behavior.


Summary of changes:

1. NFA-based executor replacing regex approach
   - Streaming execution: processes one row at a time
   - Eliminates regex compilation overhead and 26-variable limit
   - Supports up to 252 pattern variables

   Note on 252 limit:
   Each match path stores a sequence of classifiers (one per matched row).
   Using 1-byte encoding keeps memory usage reasonable for long matches.
   Some values are reserved for pattern representation; this limit may
   decrease if more are needed. 200+ should be sufficient for practical use.

2. Pattern optimization moved to planner phase (as you suggested)
   - pg_get_viewdef() now shows original pattern
   - EXPLAIN shows optimized pattern
   - Optimizations: VAR merge (A A A -> A{3}), GROUP merge ((A B) (A B)+ -> (A B){2,}),
     duplicate removal, SEQ/ALT flattening, quantifier multiplication
   - These optimizations also enable absorption for patterns that wouldn't
     otherwise qualify (e.g., (A B) (A B)+ -> (A B){2,} becomes absorbable)

3. Multi-context support with context absorption
   - Multiple concurrent NFA contexts for overlapping matches
   - Absorption optimization: earlier context absorbs later ones
     when they reach the same endpoint

   Note on absorption scope:
   I haven't fully worked out the theoretical bounds for safe absorption yet.
   The current implementation covers most practically useful cases, but a
   complete solution would require more formal analysis.

   Current implementation handles cases where the behavior is clear:
   - Only patterns with unbounded first element (A+, A*, (A B)+, etc.)
   - Only when there's exactly one unbounded element at top level
   - Per-branch analysis for alternation patterns
   This may be extended as we better understand the theoretical limits.

   Examples:
   - A+ B     : absorbable (A+ unbounded first, same endpoint guaranteed)
   - A* B     : absorbable (A* unbounded first)
   - A B+     : NOT absorbable (unbounded not first, different start points)
   - A+ B+    : partial (absorbable while in A+, not after entering B+)
   - A? B     : NOT absorbable (? is bounded: {0,1})
   - A{2,} B  : absorbable (unbounded quantifier at first element)
   - A{2,5} B : NOT absorbable (bounded quantifier)
   - (A B){2,}: absorbable (GROUP with unbounded quantifier at top level)
   - A+ | B+  : absorbable per-branch (each branch analyzed independently)
   - A+ | B C : partial per-branch (A+ absorbable, B C not)
   - (A+ B)+   : NOT YET (absorbable at first A+ entry, nested analysis not implemented)

4. Reluctant quantifiers
   - Will be supported in a follow-up patch
   - I need to study some edge cases in the spec first

Also updated: parser/README, typedefs.list


Testing:

The rpr regression test has been expanded significantly with tests for:
- Alternation and grouping patterns
- Quantifiers ({n}, {n,}, {n,m}, +, *, ?)
- Pattern optimization verification
- Multi-context matching
- Context absorption behavior
- Lexical order compliance

Below is a reference query designed to test NFA functionality in a clean,
unambiguous way. Using explicit ARRAY flags eliminates edge cases and makes
the pattern matching behavior completely predictable, allowing clear verification
of multi-context execution and alternation handling.

Example (multi-context overlapping match test):
Uses ARRAY flags with ANY() to make each row's pattern membership explicit,
making test behavior predictable and easy to verify.

  WITH data AS (
    SELECT * FROM (VALUES
      (1, ARRAY['A']), (2, ARRAY['B']), (3, ARRAY['C']),
      (4, ARRAY['D']), (5, ARRAY['E']), (6, ARRAY['F'])
    ) AS t(id, flags)
  )
  SELECT id, flags, first_value(id) OVER w AS start, last_value(id) OVER w AS end
  FROM data
  WINDOW w AS (
    ORDER BY id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    AFTER MATCH SKIP TO NEXT ROW
    PATTERN (A B C D E | B C D | C D E F)
    DEFINE A AS 'A' = ANY(flags), B AS 'B' = ANY(flags), ...
  );

  -- Result (SKIP TO NEXT ROW enables multi-context):
   id | flags | start | end
  ----+-------+-------+-----
    1 | {A}   |     1 |   5   <- A B C D E
    2 | {B}   |     2 |   4   <- B C D
    3 | {C}   |     3 |   6   <- C D E F
    4 | {D}   |       |
    5 | {E}   |       |
    6 | {F}   |       |


Performance:

Regression test timing (rpr test):

  Parallel group (with other tests):
    Before (v37 regex):  198 ms
    After (NFA):         123 ms  (~38% faster)
    After (NFA + tests): 127 ms  (still ~36% faster)

  Single test (isolated):
    Before (v37 regex):  38 ms
    After (NFA):         26 ms  (~32% faster)
    After (NFA + tests): 41 ms  (+8%, more tests added)

Note: The rpr test was moved out of the parallel group in the schedule
for more accurate timing measurement.

The streaming NFA approach eliminates regex compilation overhead per-row
and reduces redundant DEFINE evaluations, resulting in better performance
especially for complex patterns.


Let me know if you have any questions or concerns.


Best regards,
Henson

Re: Row pattern recognition

От:
Jacob Champion <jacob.champion@enterprisedb.com>
Дата:
On Sat, Jan 10, 2026 at 1:20 AM Henson Choi  wrote:
> I'd definitely be interested in seeing it, rough edges and all. I haven't
> tackled the PostgreSQL integration design yet, so understanding how
> preferment rules map to the existing infrastructure would be very helpful.
> (Tatsuo found that email, by the way.)

Yep -- the dev branch link from that email still works, for you and
anyone interested:

    https://github.com/jchampio/postgres/tree/dev/rpr

--Jacob


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jacob,

Thank you for sharing your dev branch! I extracted test cases from your implementation and found two failing patterns in my executor:

2026년 1월 15일 (목) AM 3:12, Jacob Champion <jacob.champion@enterprisedb.com>님이 작성:
On Sat, Jan 10, 2026 at 1:20 AM Henson Choi <assam258@gmail.com> wrote:
> I'd definitely be interested in seeing it, rough edges and all. I haven't
> tackled the PostgreSQL integration design yet, so understanding how
> preferment rules map to the existing infrastructure would be very helpful.
> (Tatsuo found that email, by the way.)

Yep -- the dev branch link from that email still works, for you and
anyone interested:

    https://github.com/jchampio/postgres/tree/dev/rpr

1. (A | B)+ C with data A, B, A, C

My result: NULL (no match)
Correct: 1-4

2. ((A | B) C)+ with data A, C, B, C, X

My result: 1-2, 3-4 (split matches)
Correct: 1-4
 
--Jacob

Since I implemented the pattern matching and context absorption somewhat naively,
I think these areas will need an overall review. Thanks for the helpful test patterns!

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

> Hi Ishii-san,
> 
> 
> The attached patch implements streaming NFA-based pattern matching.
> This is based on your v37 patch and the pattern grammar work I submitted
> earlier.

Great!

> This is a testable draft for review, not production-ready yet. It allows
> in-depth verification of pattern optimization, pattern matching/merging,
> context absorption, and window behavior.

I squashed your patches into my v37 patches and created v38 patches.
(See attached). Will it be Okay for you to work on the patches from
now on?

Also I have added you to the commit message as an author.

> Summary of changes:

Will check.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

The merged v38 patch passed CI check:
https://cirrus-ci.com/github/postgresql-cfbot/postgresql/cf%2F4460

Congratulations!

>> Summary of changes:
> 
> Will check.

I have one question regaring your patch.

In update_reduced_frame():
+	hasLimitedFrame = (frameOptions & FRAMEOPTION_ROWS) &&
+					  !(frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING);
+	if (hasLimitedFrame && winstate->endOffsetValue != 0)
+		frameOffset = DatumGetInt64(winstate->endOffsetValue);

frameOffset is a offset value n from "ROWS BETWEEN CURRENT ROW AND n FOLLOWING".
Later you use this here:

+	ctxFrameEnd = ctx->matchStartRow + frameOffset + 1;

So my question is, how do you ensure that ctxFrameEnd does not go
beyond the full window frame end?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Ishii-san,

I have one question regaring your patch.

In update_reduced_frame():
+       hasLimitedFrame = (frameOptions & FRAMEOPTION_ROWS) &&
+                                         !(frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING);
+       if (hasLimitedFrame && winstate->endOffsetValue != 0)
+               frameOffset = DatumGetInt64(winstate->endOffsetValue);

frameOffset is a offset value n from "ROWS BETWEEN CURRENT ROW AND n FOLLOWING".
Later you use this here:

+       ctxFrameEnd = ctx->matchStartRow + frameOffset + 1;

So my question is, how do you ensure that ctxFrameEnd does not go
beyond the full window frame end?

In update_reduced_frame():

    frameOffset = endOffsetValue;     // e.g., 2 from "2 FOLLOWING"
   
    for each row (currentPos):
   
        if (!rowExists)               // partition end reached
            finalize all contexts;
            break;
       
        for each context:
            ctxFrameEnd = matchStartRow + frameOffset + 1;
            if (currentPos >= ctxFrameEnd)
                finalize this context;
                continue;

Even if ctxFrameEnd exceeds partition end, the "if (!rowExists)" check
fires first and finalizes all contexts at the actual partition boundary.

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> So my question is, how do you ensure that ctxFrameEnd does not go
>> beyond the full window frame end?
>>
> 
> In update_reduced_frame():
> 
>     frameOffset = endOffsetValue;     // e.g., 2 from "2 FOLLOWING"
> 
>     for each row (currentPos):
> 
>         if (!rowExists)               // partition end reached
>             finalize all contexts;
>             break;
> 
>         for each context:
>             ctxFrameEnd = matchStartRow + frameOffset + 1;
>             if (currentPos >= ctxFrameEnd)
>                 finalize this context;
>                 continue;
> 
> Even if ctxFrameEnd exceeds partition end, the "if (!rowExists)" check
> fires first and finalizes all contexts at the actual partition boundary.

We need to check the *frame" end, not the partition end.

I think your patch relies on !window_gettupleslot() to check whether
the row exists.

	if (!window_gettupleslot(winobj, pos, slot))
		return false;	/* No row exists */

But the function only checks the row existence in the current partition:

 *	Fetch the pos'th tuple of the current partition into the slot,

Thus it is possible that window_gettupleslot() returns true but the
row is not in the current frame in case that the partition is divided
into some frames. You need to check the row existence in a frame. For
this purpose you can use row_is_in_frame().

I ran following query and got the result with v38 (which includes your
NFA patches).

WITH data AS (
 SELECT * FROM (VALUES
  ('A', 1), ('A', 2),
  ('B', 3), ('B', 4)
  ) AS t(gid, id))
  SELECT gid, id, array_agg(id) OVER w
  FROM data
  WINDOW w AS (
   PARTITION BY gid
   ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
   AFTER MATCH SKIP TO NEXT ROW
   PATTERN (A+)
   DEFINE A AS id < 10
  );
 gid | id | array_agg 
-----+----+-----------
 A   |  1 | {1,2}
 A   |  2 | 
 B   |  3 | {3,4}
 B   |  4 | 
(4 rows)

I think the second and 4th rows are expected to return some data in
array_agg colum. In fact v37 patch returns following results for the
same query:

 gid | id | array_agg 
-----+----+-----------
 A   |  1 | {1,2}
 A   |  2 | {2}
 B   |  3 | {3,4}
 B   |  4 | {4}
(4 rows)

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Ishii-san

We need to check the *frame" end, not the partition end.

I think your patch relies on !window_gettupleslot() to check whether
the row exists.

        if (!window_gettupleslot(winobj, pos, slot))
                return false;   /* No row exists */

But the function only checks the row existence in the current partition:

 *      Fetch the pos'th tuple of the current partition into the slot,

Thus it is possible that window_gettupleslot() returns true but the
row is not in the current frame in case that the partition is divided
into some frames. You need to check the row existence in a frame. For
this purpose you can use row_is_in_frame().

I ran following query and got the result with v38 (which includes your
NFA patches).

WITH data AS (
 SELECT * FROM (VALUES
  ('A', 1), ('A', 2),
  ('B', 3), ('B', 4)
  ) AS t(gid, id))
  SELECT gid, id, array_agg(id) OVER w
  FROM data
  WINDOW w AS (
   PARTITION BY gid
   ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
   AFTER MATCH SKIP TO NEXT ROW
   PATTERN (A+)
   DEFINE A AS id < 10
  );
 gid | id | array_agg
-----+----+-----------
 A   |  1 | {1,2}
 A   |  2 |
 B   |  3 | {3,4}
 B   |  4 |
(4 rows)

I think the second and 4th rows are expected to return some data in
array_agg colum. In fact v37 patch returns following results for the
same query:

 gid | id | array_agg
-----+----+-----------
 A   |  1 | {1,2}
 A   |  2 | {2}
 B   |  3 | {3,4}
 B   |  4 | {4}
(4 rows)

While investigating the issue you mentioned, I found that the problem
is caused by the context absorption logic, not the frame boundary check.

The absorption logic removes a newer context when
older->matchEndRow >= newer->matchEndRow:

Example with pattern A+:
- Context at row 1: matchEndRow = 2 (match {1,2})
- Context at row 2: matchEndRow = 2 (match {2})
→ Newer context absorbed, row 2's result lost

With SKIP TO NEXT ROW, each row should produce its own independent match.
The absorption was incorrectly removing these valid overlapping matches.

I modified the absorption logic to only apply to SKIP PAST LAST ROW mode,
where it provides performance benefits without affecting correctness.

For SKIP TO NEXT ROW, absorption is now disabled, allowing each row
to produce independent overlapping matches as expected:

 gid | id | array_agg
-----+----+-----------
 A   |  1 | {1,2}
 A   |  2 | {2}
 B   |  3 | {3,4}
 B   |  4 | {4}
(4 rows)

I'm attaching 3 patches:

1. Test cases from Jacob Champion's branch
   - Added 355 lines of test cases and 51 lines of executor changes

2. Refactored update_reduced_frame for readability and performance
   - Extracted large code blocks into separate functions
   - Early return for already-processed positions
   - Integrated nfa_unlink_context into nfa_context_free
   - Used oldest-first context ordering for early termination

3. Enable context absorption only for SKIP PAST LAST ROW
   - Fixes overlapping match issue for SKIP TO NEXT ROW
   - In my 5000-row test, absorption showed significant performance gain for SKIP PAST LAST ROW
   - Added your test case to regression tests

Since I implemented it in the order of parser/planner/nfa/executor,
the executor flow became somewhat confusing.
I plan to continue improving it by reviewing and refactoring
from the top-level functions downward.

During refactoring, I plan to simplify pattern optimization and context
absorption logic, keeping only the parts that are clearly correct, even
if this means some performance loss in the initial version. We can add
optimizations back later once the core logic is stable and well-tested.

Best regards,
Henson
 

Re: Row pattern recognition

От:
Jacob Champion <jacob.champion@enterprisedb.com>
Дата:
On Wed, Jan 14, 2026 at 7:46 PM Henson Choi  wrote:
> Since I implemented the pattern matching and context absorption somewhat naively,
> I think these areas will need an overall review. Thanks for the helpful test patterns!

You're welcome, glad it was useful!

--Jacob


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Ishii-san,

Thank you for raising the frame boundary concern. You're right that
different contexts have different frame boundaries.

2026년 1월 15일 (목) PM 10:28, Henson Choi <assam258@gmail.com>님이 작성:
Hi Ishii-san

We need to check the *frame" end, not the partition end.

I think your patch relies on !window_gettupleslot() to check whether
the row exists.

        if (!window_gettupleslot(winobj, pos, slot))
                return false;   /* No row exists */

But the function only checks the row existence in the current partition:

 *      Fetch the pos'th tuple of the current partition into the slot,

Thus it is possible that window_gettupleslot() returns true but the
row is not in the current frame in case that the partition is divided
into some frames. You need to check the row existence in a frame. For
this purpose you can use row_is_in_frame().

Your suggestion was to use row_is_in_frame() to check frame boundaries
for each row. However, I took a simpler approach: just disable context
absorption entirely when the frame is limited.

The root cause is that context absorption assumes all contexts see
the same rows. With limited frames, each context starting at a different
row has a different visible range, so we cannot absorb one context into
another.

As I mentioned before, I think we should use absorption conservatively
for now - only in cases where it's clearly safe (e.g., A* at the
beginning of the pattern). We can extend it later through more in-depth
research.

The fix:

    if (winstate->rpSkipTo == ST_PAST_LAST_ROW && !hasLimitedFrame)
        nfa_absorb_contexts(winstate, targetCtx, currentPos);

I added a test case to verify this:

    -- Pattern: A+ B, Data: A(0) A(1) A(2) B(3), Frame: CURRENT ROW AND 2 FOLLOWING
    -- Row 0: frame [0,2], cannot see B at row 3 -> no match
    -- Row 1: frame [1,3], can see A A B -> should match rows 1-3
    WITH frame_absorb_test AS (
     SELECT * FROM (VALUES
      (0, 'A'), (1, 'A'), (2, 'A'), (3, 'B')
     ) AS t(id, flag)
    )
    SELECT id, flag, first_value(id) OVER w AS match_start, last_value(id) OVER w AS match_end
    FROM frame_absorb_test
    WINDOW w AS (
     ORDER BY id
     ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
     AFTER MATCH SKIP PAST LAST ROW
     PATTERN (A+ B)
     DEFINE
      A AS flag = 'A',
      B AS flag = 'B'
    );

Before fix (absorption incorrectly absorbs row 1's context into row 0's):

     id | flag | match_start | match_end
    ----+------+-------------+-----------
      0 | A    |             |
      1 | A    |             |
      2 | A    |             |
      3 | B    |             |

After fix (row 1 correctly matches):

     id | flag | match_start | match_end
    ----+------+-------------+-----------
      0 | A    |             |
      1 | A    |           1 |         3
      2 | A    |             |
      3 | B    |             |

Note that for SKIP TO NEXT ROW, absorption is already disabled,
so your test case with SKIP TO NEXT ROW should
work correctly.

I'm attaching three related commits:

1. Row pattern recognition: Improve NFA state memory management

   This commit refactors NFA state management for better readability
   and maintainability.

2. Row pattern recognition: Disable context absorption for limited frame

   This commit further restricts absorption: even with SKIP PAST LAST ROW,
   absorption is disabled when the frame is limited. With limited frames,
   different contexts have different frame boundaries, making absorption
   unsafe.
 

I ran following query and got the result with v38 (which includes your
NFA patches).

WITH data AS (
 SELECT * FROM (VALUES
  ('A', 1), ('A', 2),
  ('B', 3), ('B', 4)
  ) AS t(gid, id))
  SELECT gid, id, array_agg(id) OVER w
  FROM data
  WINDOW w AS (
   PARTITION BY gid
   ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
   AFTER MATCH SKIP TO NEXT ROW
   PATTERN (A+)
   DEFINE A AS id < 10
  );
 gid | id | array_agg
-----+----+-----------
 A   |  1 | {1,2}
 A   |  2 |
 B   |  3 | {3,4}
 B   |  4 |
(4 rows)

I think the second and 4th rows are expected to return some data in
array_agg colum. In fact v37 patch returns following results for the
same query:

 gid | id | array_agg
-----+----+-----------
 A   |  1 | {1,2}
 A   |  2 | {2}
 B   |  3 | {3,4}
 B   |  4 | {4}
(4 rows)

While investigating the issue you mentioned, I found that the problem
is caused by the context absorption logic, not the frame boundary check.

The absorption logic removes a newer context when
older->matchEndRow >= newer->matchEndRow:

Example with pattern A+:
- Context at row 1: matchEndRow = 2 (match {1,2})
- Context at row 2: matchEndRow = 2 (match {2})
→ Newer context absorbed, row 2's result lost

With SKIP TO NEXT ROW, each row should produce its own independent match.
The absorption was incorrectly removing these valid overlapping matches.

I modified the absorption logic to only apply to SKIP PAST LAST ROW mode,
where it provides performance benefits without affecting correctness.

For SKIP TO NEXT ROW, absorption is now disabled, allowing each row
to produce independent overlapping matches as expected:

 gid | id | array_agg
-----+----+-----------
 A   |  1 | {1,2}
 A   |  2 | {2}
 B   |  3 | {3,4}
 B   |  4 | {4}
(4 rows)

I'm attaching 3 patches:

1. Test cases from Jacob Champion's branch
   - Added 355 lines of test cases and 51 lines of executor changes

2. Refactored update_reduced_frame for readability and performance
   - Extracted large code blocks into separate functions
   - Early return for already-processed positions
   - Integrated nfa_unlink_context into nfa_context_free
   - Used oldest-first context ordering for early termination

3. Enable context absorption only for SKIP PAST LAST ROW
   - Fixes overlapping match issue for SKIP TO NEXT ROW
   - In my 5000-row test, absorption showed significant performance gain for SKIP PAST LAST ROW
   - Added your test case to regression tests

Since I implemented it in the order of parser/planner/nfa/executor,
the executor flow became somewhat confusing.
I plan to continue improving it by reviewing and refactoring
from the top-level functions downward.

During refactoring, I plan to simplify pattern optimization and context
absorption logic, keeping only the parts that are clearly correct, even
if this means some performance loss in the initial version. We can add
optimizations back later once the core logic is stable and well-tested. 

I'm now reviewing the remaining parts: pattern optimization in planner,
absorption function, and step function. Once the review is complete,
I'll send the rest of the patches.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

> Hi Ishii-san,
> 
> Thank you for raising the frame boundary concern. You're right that
> different contexts have different frame boundaries.

Ok.

> Your suggestion was to use row_is_in_frame() to check frame boundaries
> for each row. However, I took a simpler approach: just disable context
> absorption entirely when the frame is limited.
> 
> The root cause is that context absorption assumes all contexts see
> the same rows. With limited frames, each context starting at a different
> row has a different visible range, so we cannot absorb one context into
> another.
> 
> As I mentioned before, I think we should use absorption conservatively
> for now - only in cases where it's clearly safe (e.g., A* at the
> beginning of the pattern). We can extend it later through more in-depth
> research.

Agreed.

> The fix:
> 
>     if (winstate->rpSkipTo == ST_PAST_LAST_ROW && !hasLimitedFrame)
>         nfa_absorb_contexts(winstate, targetCtx, currentPos);
> 
> I added a test case to verify this:
[snip]
> I'm attaching three related commits:
> 
> 1. Row pattern recognition: Improve NFA state memory management
> 
>    This commit refactors NFA state management for better readability
>    and maintainability.
> 
> 2. Row pattern recognition: Disable context absorption for limited frame
> 
>    This commit further restricts absorption: even with SKIP PAST LAST ROW,
>    absorption is disabled when the frame is limited. With limited frames,
>    different contexts have different frame boundaries, making absorption
>    unsafe.

I have applied the patches on top of v38 to create v39 patches.
In addition to these patches, I have made following changes:

- Add check for frame option "EXCLUDE". With RPR, using EXCLUDE is not
  permitted by the SQL standard. A test case added.

- Remove unused typedef from windowfuncs.c (which causes removal of the
  typedef from typedes.list). The typedef was accidentally left by me
  while developing RPR.

- Update the Copyright year to 2026 in some newly added files.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> I'm now reviewing the remaining parts: pattern optimization in planner,
> absorption function, and step function. Once the review is complete,
> I'll send the rest of the patches.

I am reviewing the test cases and found this:

SELECT * FROM (SELECT 1 AS x) t
 WINDOW w AS (
 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
 PATTERN (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
 DEFINE a AS TRUE
);
ERROR:  number of row pattern definition variable names exceeds 26

I thought you have eliminated the 26 variables limit. If so, related
codes using WindowClause->defineInitial should be removed. Shall I do
that? Or you want to do that while refactoring?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:


2026년 1월 17일 (토) 17:19, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Hi Henson,

> I'm now reviewing the remaining parts: pattern optimization in planner,
> absorption function, and step function. Once the review is complete,
> I'll send the rest of the patches.

I am reviewing the test cases and found this:

SELECT * FROM (SELECT 1 AS x) t
 WINDOW w AS (
 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
 PATTERN (a b c d e f g h i j k l m n o p q r s t u v w x y z aa)
 DEFINE a AS TRUE
);
ERROR:  number of row pattern definition variable names exceeds 26

I thought you have eliminated the 26 variables limit. If so, related
codes using WindowClause->defineInitial should be removed. Shall I do
that? Or you want to do that while refactoring?


Already found and cleaned up.
Will include it in the next patch.​​​​​​​​​​​​​​​​


Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Already found and cleaned up.
> Will include it in the next patch.​​​​​​​​​​​​​​​​

Excellent! Thank you so much.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Ishii-san,

2026년 1월 17일 (토) PM 5:38, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Hi Henson,

> Already found and cleaned up.
> Will include it in the next patch.

Excellent! Thank you so much.

 Attached is the patch with the following changes:

1. Removed 26 variables limit and fixed count overflow:
   - Deleted defineInitial field from WindowClause (parsenodes.h),
     WindowAgg (plannodes.h), and related code in createplan.c and parse_rpr.c
   - Now uses RPR_VARID_MAX (252) constant for the limit check
   - Fixed NFA count overflow issue:
     * Changed RPRNFAState.counts from int16 to int32 (execnodes.h)
     * Added RPR_COUNT_MAX (INT32_MAX) constant (rpr.h)
     * Handles pattern matching failures correctly at >32,767 repetitions
     * Added INT32_MAX boundary handling to prevent overflow
   - Updated test cases in rpr.sql:
     * Updated variable limit tests from 26 to 252
     * Added 100K row large partition test to verify int32 overflow handling

2. Simplified context absorption logic (under review):
   - Key insight: Most absorption opportunities provide no practical benefit
     because subsequent contexts are discarded immediately after a match
     succeeds. Only absorption at unbounded pattern start shows measurable impact.
   - Changes:
     * Planner (rpr.c): Added isUnboundedStart() to identify patterns where
       leading unbounded quantifiers enable safe absorption
     * Executor (nodeWindowAgg.c): Simplified to only absorb at pattern start,
       separated cleanup logic into nfa_cleanup_dead_contexts()
     * Added pattern->isAbsorbable flag to enable absorption only when safe
   - Impact: Reduces context growth from quadratic to linear.
     Example from rpr_explain.sql Test 3.1 (PATTERN A+ B, 50 rows):
     * With absorption: 51 total contexts, 3 peak, 30 absorbed
     * Without absorption: Would create O(n²) contexts (each row starts a
       context, creating 1+2+3+4 contexts per 5-row segment)
     * Absorption maintains linear O(n) growth instead of quadratic explosion
   - Note: Changes in EXPLAIN ANALYZE output suggest there may be issues in
     the matching process, particularly in absorption and NFA state transitions.
     I need to review these areas more thoroughly before I can be confident in
     their correctness.

3. Added NFA statistics to EXPLAIN ANALYZE output (under review):
   - Extended explain.c to show NFA construction and matching statistics
   - Added comprehensive statistics tracking (execnodes.h):
     * NFALengthStats structure for min/max/avg length measurements
     * State statistics: peak, total created, merged (deduplicated)
     * Context statistics: peak, total created, absorbed, skipped, pruned
     * Match statistics: succeeded/failed counts with length distributions
   - Implemented statistics collection in nodeWindowAgg.c
   - New test suite: rpr_explain.sql for testing NFA statistics output
   - Note: rpr_explain is not included in parallel_schedule (runs separately)
   - Statistics reveal pattern complexity impact:
     Example from Test 2.7 (PATTERN ((A | B)+)+, 1000 rows):
     * NFA States: 2,664 peak, 892,447 total created
     * Peak grows linearly with rows (~2.6x), likely due to state merging
     * High total shows significant state churn despite controlled peak
     * This demonstrates complex pattern behavior that users should understand
     * Question: Should we add a GUC parameter to limit NFA state peak count
       (e.g., max_rpr_nfa_states) to provide administrators with safety controls?
   - This feature is still under review and may be refined in future patches

4. Major refactoring of pattern compilation and optimization (rpr.c):
   - Split large monolithic functions into smaller, semantically meaningful
     single-purpose functions for better readability
   - Pattern compilation refactored:
     * Added collectDefineVariables() to populate variable names from DEFINE
     * Split scanRPRPattern() into recursive worker and wrapper
     * Extracted allocateRPRPattern() for memory allocation
     * Split fillRPRPattern() by node type: fillRPRPatternVar(),
       fillRPRPatternGroup(), fillRPRPatternAlt()
   - Pattern optimization converted to dispatcher pattern:
     * optimizeSeqPattern() - flattens nested SEQ, merges consecutive vars/groups
     * optimizeAltPattern() - flattens nested ALT, removes duplicates
     * optimizeGroupPattern() - multiplies quantifiers, unwraps single children
   - Each optimization step broken into separate helper functions:
     * flattenSeqChildren(), mergeConsecutiveVars(), mergeConsecutiveGroups()
     * flattenAltChildren(), removeDuplicateAlternatives()
     * tryMultiplyQuantifiers(), tryUnwrapGroup()
   - New optimization: mergeGroupPrefixSuffix()
     * A B (A B)+ -> (A B){2,}
     * (A B)+ A B -> (A B){2,}
     * A B (A B)+ A B -> (A B){3,}
   - Code structure reorganized with categorized forward declarations
   - Added test cases in rpr.sql to verify new optimizations:
     * Consecutive GROUP merge tests
     * Quantifier multiplication tests (including INF blocking)
     * Group prefix/suffix merge tests

5. Fixed quantifier validation:
   - Corrected bounds checking in gram.y (e.g., {,m} now requires m >= 1)
   - Improved error messages for invalid quantifier ranges

Additional notes:
- The NFA statistics output format in EXPLAIN ANALYZE was quickly
  implemented for debugging purposes. I would appreciate feedback from
  experienced PostgreSQL developers on:
  * Whether the output format and structure are appropriate
  * Whether these statistics would be valuable for query tuning in production,
    or if they are only useful for development/debugging
  * If production-worthy, what simplifications might make them more accessible
    to users unfamiliar with NFA internals
- Reluctant quantifier handling needs further clarification. If I cannot
  make confident fixes before the next review cycle, I may temporarily
  raise errors for reluctant cases until the logic is properly sorted out.

Next steps:
- The executor implementation (nodeWindowAgg.c) is the only major component
  remaining for detailed review.
- I will focus on thoroughly reviewing the absorption logic and NFA state
  transition mechanisms to address the concerns noted in section 2.
- After making necessary improvements, I will send the next patch with
  more confidence in the executor correctness.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>  Attached is the patch with the following changes:
[snip]

After applying your patch on top of v39 patch sets, I see compiler
warnings:

nodeWindowAgg.c: In function ‘nfa_absorb_contexts’:
nodeWindowAgg.c:5565:47: warning: the comparison will always evaluate as ‘true’ for the address of ‘counts’ will never be NULL [-Waddress]
 5565 |                                 if (s->counts != NULL && s->counts[0] > newerMaxCount)
      |                                               ^~
In file included from ../../../src/include/executor/execdesc.h:18,
                 from ../../../src/include/executor/executor.h:18,
                 from nodeWindowAgg.c:41:
../../../src/include/nodes/execnodes.h:2532:25: note: ‘counts’ declared here
 2532 |         int32           counts[FLEXIBLE_ARRAY_MEMBER];  /* repetition counts by depth */
      |                         ^~~~~~
nodeWindowAgg.c:5572:47: warning: the comparison will always evaluate as ‘true’ for the address of ‘counts’ will never be NULL [-Waddress]
 5572 |                                 if (s->counts != NULL && s->counts[0] > olderMaxCount)
      |                                               ^~
../../../src/include/nodes/execnodes.h:2532:25: note: ‘counts’ declared here
 2532 |         int32           counts[FLEXIBLE_ARRAY_MEMBER];  /* repetition counts by depth */
      |                         ^~~~~~
nodeWindowAgg.c:5429:33: warning: variable ‘maxDepth’ set but not used [-Wunused-but-set-variable]
 5429 |         int                     maxDepth;
      |                                 ^~~~~~~~

Shall I fix them (and post v40 patches), or would you like to fix and
post another patch?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Shall I fix them (and post v40 patches), or would you like to fix and
post another patch?

Yes, please fix them and post v40. Thanks!

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
>> Shall I fix them (and post v40 patches), or would you like to fix and
>> post another patch?
>>
> 
> Yes, please fix them and post v40. Thanks!

Got it.

BTW, I found IGNORE NULLS module (ignorenulls_getfuncarginframe) needs
to be fixed. The module is used when a window function is called with
IGNORE NULLS option. Currently PostgreSQL ignores the option if RPR is
used because ignorenulls_getfuncarginframe does not call
row_is_in_reduced_frame(). I will bring in the fix into v40.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Hackers,

I’m writing to leave a brief note on State Pruning, a potential optimization for the RPR executor.

To be clear, this is a separate concern from both context absorption and state merging. While state merging handles identical states within a context, and context absorption handles dominance between different contexts, State Pruning focuses on discarding active NFA states that have become irrelevant due to lexical priority rules.

The core idea is to prune individual states by comparing them with the matchedState already secured. If a high-priority branch has already recorded a match, any active states in lower-priority branches may become "dead wood"—even if they are currently matching, they can never supersede the existing winner.

Detailed Example: A+ (prio 0) | B+ (prio 1) Consider an input where both A and B are TRUE for consecutive rows:

Row 1 (A=TRUE, B=TRUE):

A+ matches and records a matchedState (length 1, priority 0).

B+ also matches (length 1, priority 1) and remains in ctx->states.

Pruning Point: Since a priority 0 match is already secured, B+ (priority 1) can never win, regardless of how much longer it matches. We can prune the B+ state here.

Row 2 (A=TRUE, B=TRUE):

Without pruning: The engine evaluates both A+ and B+.

With pruning: Only A+ is evaluated. matchedState is updated to length 2.

Row 3 (A=FALSE, B=FALSE):

A+ fails. The final result is the matchedState from Row 2 (A+ with length 2).

As shown, State Pruning can significantly reduce the NFA workload by stopping redundant branches early. However, implementing this correctly will require substantial research and careful analysis, especially when dealing with the complex interplay between greedy/reluctant quantifiers and branch convergence. We must ensure that pruning a state won't lead to incorrect results in more complex scenarios.

I am documenting this as a future research item. For now, my focus remains on stabilizing the core RPR implementation and context absorption.

Regards,
Henson

2026년 1월 18일 (일) PM 6:26, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
>> Shall I fix them (and post v40 patches), or would you like to fix and
>> post another patch?
>>
>
> Yes, please fix them and post v40. Thanks!

Got it.

BTW, I found IGNORE NULLS module (ignorenulls_getfuncarginframe) needs
to be fixed. The module is used when a window function is called with
IGNORE NULLS option. Currently PostgreSQL ignores the option if RPR is
used because ignorenulls_getfuncarginframe does not call
row_is_in_reduced_frame(). I will bring in the fix into v40.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

>  Attached is the patch with the following changes:
> 
> 1. Removed 26 variables limit and fixed count overflow:
>    - Deleted defineInitial field from WindowClause (parsenodes.h),
>      WindowAgg (plannodes.h), and related code in createplan.c and
> parse_rpr.c
>    - Now uses RPR_VARID_MAX (252) constant for the limit check
>    - Fixed NFA count overflow issue:
>      * Changed RPRNFAState.counts from int16 to int32 (execnodes.h)
>      * Added RPR_COUNT_MAX (INT32_MAX) constant (rpr.h)
>      * Handles pattern matching failures correctly at >32,767 repetitions
>      * Added INT32_MAX boundary handling to prevent overflow
>    - Updated test cases in rpr.sql:
>      * Updated variable limit tests from 26 to 252
>      * Added 100K row large partition test to verify int32 overflow handling
> 
> 2. Simplified context absorption logic (under review):
>    - Key insight: Most absorption opportunities provide no practical benefit
>      because subsequent contexts are discarded immediately after a match
>      succeeds. Only absorption at unbounded pattern start shows measurable
> impact.
>    - Changes:
>      * Planner (rpr.c): Added isUnboundedStart() to identify patterns where
>        leading unbounded quantifiers enable safe absorption
>      * Executor (nodeWindowAgg.c): Simplified to only absorb at pattern
> start,
>        separated cleanup logic into nfa_cleanup_dead_contexts()
>      * Added pattern->isAbsorbable flag to enable absorption only when safe
>    - Impact: Reduces context growth from quadratic to linear.
>      Example from rpr_explain.sql Test 3.1 (PATTERN A+ B, 50 rows):
>      * With absorption: 51 total contexts, 3 peak, 30 absorbed
>      * Without absorption: Would create O(n²) contexts (each row starts a
>        context, creating 1+2+3+4 contexts per 5-row segment)
>      * Absorption maintains linear O(n) growth instead of quadratic
> explosion
>    - Note: Changes in EXPLAIN ANALYZE output suggest there may be issues in
>      the matching process, particularly in absorption and NFA state
> transitions.
>      I need to review these areas more thoroughly before I can be confident
> in
>      their correctness.
> 
> 3. Added NFA statistics to EXPLAIN ANALYZE output (under review):
>    - Extended explain.c to show NFA construction and matching statistics
>    - Added comprehensive statistics tracking (execnodes.h):
>      * NFALengthStats structure for min/max/avg length measurements
>      * State statistics: peak, total created, merged (deduplicated)
>      * Context statistics: peak, total created, absorbed, skipped, pruned
>      * Match statistics: succeeded/failed counts with length distributions
>    - Implemented statistics collection in nodeWindowAgg.c
>    - New test suite: rpr_explain.sql for testing NFA statistics output
>    - Note: rpr_explain is not included in parallel_schedule (runs
> separately)
>    - Statistics reveal pattern complexity impact:
>      Example from Test 2.7 (PATTERN ((A | B)+)+, 1000 rows):
>      * NFA States: 2,664 peak, 892,447 total created
>      * Peak grows linearly with rows (~2.6x), likely due to state merging
>      * High total shows significant state churn despite controlled peak
>      * This demonstrates complex pattern behavior that users should
> understand
>      * Question: Should we add a GUC parameter to limit NFA state peak count
>        (e.g., max_rpr_nfa_states) to provide administrators with safety
> controls?
>    - This feature is still under review and may be refined in future patches
> 
> 4. Major refactoring of pattern compilation and optimization (rpr.c):
>    - Split large monolithic functions into smaller, semantically meaningful
>      single-purpose functions for better readability
>    - Pattern compilation refactored:
>      * Added collectDefineVariables() to populate variable names from DEFINE
>      * Split scanRPRPattern() into recursive worker and wrapper
>      * Extracted allocateRPRPattern() for memory allocation
>      * Split fillRPRPattern() by node type: fillRPRPatternVar(),
>        fillRPRPatternGroup(), fillRPRPatternAlt()
>    - Pattern optimization converted to dispatcher pattern:
>      * optimizeSeqPattern() - flattens nested SEQ, merges consecutive
> vars/groups
>      * optimizeAltPattern() - flattens nested ALT, removes duplicates
>      * optimizeGroupPattern() - multiplies quantifiers, unwraps single
> children
>    - Each optimization step broken into separate helper functions:
>      * flattenSeqChildren(), mergeConsecutiveVars(),
> mergeConsecutiveGroups()
>      * flattenAltChildren(), removeDuplicateAlternatives()
>      * tryMultiplyQuantifiers(), tryUnwrapGroup()
>    - New optimization: mergeGroupPrefixSuffix()
>      * A B (A B)+ -> (A B){2,}
>      * (A B)+ A B -> (A B){2,}
>      * A B (A B)+ A B -> (A B){3,}
>    - Code structure reorganized with categorized forward declarations
>    - Added test cases in rpr.sql to verify new optimizations:
>      * Consecutive GROUP merge tests
>      * Quantifier multiplication tests (including INF blocking)
>      * Group prefix/suffix merge tests
> 
> 5. Fixed quantifier validation:
>    - Corrected bounds checking in gram.y (e.g., {,m} now requires m >= 1)
>    - Improved error messages for invalid quantifier ranges
> 
> Additional notes:
> - The NFA statistics output format in EXPLAIN ANALYZE was quickly
>   implemented for debugging purposes. I would appreciate feedback from
>   experienced PostgreSQL developers on:
>   * Whether the output format and structure are appropriate
>   * Whether these statistics would be valuable for query tuning in
> production,
>     or if they are only useful for development/debugging
>   * If production-worthy, what simplifications might make them more
> accessible
>     to users unfamiliar with NFA internals
> - Reluctant quantifier handling needs further clarification. If I cannot
>   make confident fixes before the next review cycle, I may temporarily
>   raise errors for reluctant cases until the logic is properly sorted out.
> 
> Next steps:
> - The executor implementation (nodeWindowAgg.c) is the only major component
>   remaining for detailed review.
> - I will focus on thoroughly reviewing the absorption logic and NFA state
>   transition mechanisms to address the concerns noted in section 2.
> - After making necessary improvements, I will send the next patch with
>   more confidence in the executor correctness.

Ok, I have merged your patches with my patches to create v40
patches.

My patches are to fix issue with RPR + IGNORE NULLS case. I modified
ignorenulls_getfuncarginframe() which is called from window functions
when IGNORE NULLS option is specified. To cope with RPR, I added
row_is_in_reduced_frame() call to it. Also test cases were added.

Attached are the v40 patches.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Subject: [RPR] Context Absorption Design Documentation - Two-Flag Approach

Hi Hackers,

I'm writing to document the detailed design of context absorption
optimization in Row Pattern Recognition (RPR). This is mainly for
future reference - honestly, I'm afraid I'll forget these details
myself in a few months, and I'd rather have them written down
somewhere public than buried in my notes. I don't want to repeat the mistake of famous mathematical theorems
where brilliant ideas were lost because "the margin was too narrow
to contain the proof" (yes, I'm looking at you, Fermat!). I certainly
don't want future PostgreSQL hackers to spend the next 358 years
trying to re-implement context absorption because the design rationale
was lost. Fortunately, the PostgreSQL community has provided us with
sufficient digital margins. :)

========================================================================
    ROW PATTERN RECOGNITION: CONTEXT ABSORPTION DESIGN (DRAFT)
                Two-Flag Approach for O(n²) → O(n) Optimization
========================================================================

The context absorption feature achieves O(n²) → O(n) performance
improvement by eliminating redundant match searches. The core idea
is simple: a newer context (started at a later row) can never
produce a longer match than an older context when certain conditions
are met. However, the implementation details are subtle enough that
I think they deserve careful documentation.


========================================================================
TWO-FLAG DESIGN
========================================================================

The optimization uses two element flags:

1. RPR_ELEM_ABSORBABLE - "Absorption judgment point"
   Marks WHERE to compare contexts for absorption.
   - For simple unbounded VAR (e.g., A in "A+"): the VAR itself
   - For unbounded GROUP (e.g., "(A B)+"): the END element only

2. RPR_ELEM_ABSORBABLE_BRANCH - "Absorbable region marker"
   Marks ALL elements in the absorbable region.
   - Used for efficient region tracking at runtime
   - All elements at the same depth as the unbounded start


========================================================================
WHY TWO FLAGS?
========================================================================

The key insight: for pattern "(A B)+", we cannot compare contexts
when they're at different positions (one at A, another at B). They
must synchronize at the END element.

Consider "(A B)+" matching data: A B A B A B...
  Row 0 (A): Ctx1 starts, matches A
  Row 1 (B): Ctx1 matches B → END (count=1)
  Row 2 (A): Ctx1 loops to A (count=1), Ctx2 starts, matches A (count=0)
  Row 3 (B): Ctx1 matches B → END (count=2)
             Ctx2 matches B → END (count=1)
             ↑ Both at END with same elemIdx → comparable!
             → Ctx1.count(2) >= Ctx2.count(1) → Absorb Ctx2!

Every group-length rows (2 in this case), the contexts synchronize
at END, making absorption possible. This is why we need:
- ABSORBABLE flag: to mark END as the judgment point
- ABSORBABLE_BRANCH flag: to keep isAbsorbable=true while
  traversing A→B→END


========================================================================
PATTERN-SPECIFIC FLAG SETTINGS
========================================================================

Pattern: A+ B
-------------
Element 0: A (max=INF)
  flags: ABSORBABLE | ABSORBABLE_BRANCH
Element 1: B
  flags: (none)

A+ is absorbable. Judgment point is A itself. Every row at A,
contexts can be compared and absorbed. When contexts move to B,
B has no ABSORBABLE_BRANCH flag, so isAbsorbable turns false.


Pattern: (A B)+ C
-----------------
Element 0: A (depth=1)
  flags: ABSORBABLE_BRANCH
Element 1: B (depth=1)
  flags: ABSORBABLE_BRANCH
Element 2: END (depth=1, max=INF)
  flags: ABSORBABLE | ABSORBABLE_BRANCH
Element 3: C (depth=0)
  flags: (none)

A, B, END are in the absorbable region at depth 1. Only END is the
judgment point where contexts synchronize every 2 rows (group length).
When contexts move to C (depth 0), they leave the absorbable region
and isAbsorbable turns false.


Pattern: (A+ B+)+ C
-------------------
Element 0: A (depth=2, max=INF)
  flags: ABSORBABLE | ABSORBABLE_BRANCH
Element 1: B (depth=2, max=INF)
  flags: (none)
Element 2: END (inner, depth=2)
  flags: (none)
Element 3: END (outer, depth=1, max=INF)
  flags: (none)
Element 4: C (depth=0)
  flags: (none)

Only the FIRST A+ on the FIRST iteration gets flags. Why?
  Ctx1: A+ 10 times → B+ 10 times → outer loop → C
  Ctx2: (1 row later) A+ 9 times → absorbed by Ctx1 at A
  Ctx3: (1 row later) A+ 8 times → absorbed by Ctx1 at A
  ...
  Ctx10: (1 row later) A+ 1 time → absorbed by Ctx1 at A
  Ctx11: (1 row later) B input → pattern starts at A+, no match

Judgment point is A. Absorption works there. When contexts move to B+,
it has no ABSORBABLE_BRANCH flag, so isAbsorbable turns false.


Pattern: A B C
--------------
Element 0: A
  flags: (none)
Element 1: B
  flags: (none)
Element 2: C
  flags: (none)

No unbounded element. Pattern is not absorbable.
Contexts start with isAbsorbable = false from the beginning.


Pattern: A+ C | B+
------------------
Element 0: ALT
  flags: ABSORBABLE_BRANCH
Branch 1:
  Element: A (max=INF)
    flags: ABSORBABLE | ABSORBABLE_BRANCH
  Element: C
    flags: (none)
Branch 2:
  Element: B (max=INF)
    flags: ABSORBABLE | ABSORBABLE_BRANCH

A+ branch: judgment point is A. When contexts move to C, C has no
flags, so isAbsorbable turns false.
B+ branch: judgment point is B, fully absorbable.
ALT gets ABSORBABLE_BRANCH for efficient branch-level flag management.


Pattern: A+ B | (C D)+
----------------------
Element 0: ALT
  flags: ABSORBABLE_BRANCH
Branch 1:
  Element: A (max=INF)
    flags: ABSORBABLE | ABSORBABLE_BRANCH
  Element: B
    flags: (none)
Branch 2:
  Element: C (depth=1)
    flags: ABSORBABLE_BRANCH
  Element: D (depth=1)
    flags: ABSORBABLE_BRANCH
  Element: END (depth=1, max=INF)
    flags: ABSORBABLE | ABSORBABLE_BRANCH

A+ branch: judgment point is A. When contexts move to B, B has no
flags, so isAbsorbable turns false.
(C D)+ branch: judgment point is END, fully absorbable.
Contexts on different branches cannot be compared (different elemIdx).
ALT gets ABSORBABLE_BRANCH for efficient branch-level flag management.


Pattern: A+ | B C
-----------------
Element 0: ALT
  flags: ABSORBABLE_BRANCH
Branch 1:
  Element: A (max=INF)
    flags: ABSORBABLE | ABSORBABLE_BRANCH
Branch 2:
  Element: B
    flags: (none)
  Element: C
    flags: (none)

A+ branch: judgment point is A, fully absorbable.
B C branch: no unbounded element, not absorbable. When contexts enter
B C branch, B has no ABSORBABLE_BRANCH flag, so isAbsorbable turns false.
ALT gets ABSORBABLE_BRANCH because at least one branch (A+) is absorbable.


Pattern: A+ | B C+
------------------
Element 0: ALT
  flags: ABSORBABLE_BRANCH
Branch 1:
  Element: A (max=INF)
    flags: ABSORBABLE | ABSORBABLE_BRANCH
Branch 2:
  Element: B
    flags: (none)
  Element: C (max=INF)
    flags: (none)

A+ branch: judgment point is A, fully absorbable.
B C+ branch: B is not absorbable, C+ has no flags (not first unbounded).


Pattern: A B | C D
------------------
Element 0: ALT
  flags: (none)
Branch 1:
  Element: A
    flags: (none)
  Element: B
    flags: (none)
Branch 2:
  Element: C
    flags: (none)
  Element: D
    flags: (none)

Neither branch has unbounded elements. Pattern is not absorbable.
Contexts start with isAbsorbable = false from the beginning.
ALT has no flags because no branch is absorbable.


========================================================================
ABSORBABLE REGION BOUNDARY: When Contexts Leave Absorbable Region
========================================================================

This section illustrates when contexts transition from absorbable to
non-absorbable state by showing how hasAbsorbableState flag changes
as contexts progress through pattern elements.

Pattern: A+ B+
--------------
Element 0: A (max=INF)
  flags: ABSORBABLE | ABSORBABLE_BRANCH
Element 1: B (max=INF)
  flags: (none)

Context execution:
  Row 0: Ctx starts at A
    → state at A (count=1) → state.isAbsorbable = true
    → Ctx.hasAbsorbableState = true (at least one state is absorbable)
    → Ctx.allStatesAbsorbable = true (all states are absorbable)

  Row 1: Ctx at A
    → state at A (count=2) → state.isAbsorbable = true
    → Ctx.hasAbsorbableState = true
    → Ctx.allStatesAbsorbable = true

  Row 2: First B input, Ctx progresses from A to B
    → state transitions to B (count=1) → state.isAbsorbable = false
    → B has no ABSORBABLE_BRANCH flag
    → Ctx.hasAbsorbableState = false (no absorbable states remain)
    → Ctx.allStatesAbsorbable = false
    → Monotonic property: hasAbsorbableState stays false forever

  Row 3+: Ctx continues at B
    → Ctx.hasAbsorbableState = false (permanent)
    → This context can never absorb others, and cannot be absorbed

Key point: Once contexts leave A+ region and enter B+, absorption
completely stops. The A+ portion achieved O(n) absorption while it
lasted, which is the design goal.


Pattern: ((A B)+ C)+
--------------------
Outer loop iteration 1:
  Inner (A B)+: Elements A, B, inner END (depth=1)
    flags on A, B: ABSORBABLE_BRANCH
    flags on inner END: ABSORBABLE | ABSORBABLE_BRANCH
  Element C (depth=0):
    flags: (none)
  Outer END (depth=0):
    flags: (none)

Context execution (first outer iteration):
  First inner iteration of (A B)+:
    Row 0: Ctx starts at A
      → state at A (count=0, depth=1) → state.isAbsorbable = true
      → Ctx.hasAbsorbableState = true (at least one state is absorbable)
      → Ctx.allStatesAbsorbable = true (all states are absorbable)

    Row 1: Ctx at B, then epsilon transition to inner END
      → state at B (count=0, depth=1) → state.isAbsorbable = true
      → B→END is epsilon transition (same row processing)
      → state at inner END (count=1, depth=1) → state.isAbsorbable = true
      → Ctx.hasAbsorbableState = true
      → Ctx.allStatesAbsorbable = true
      → Inner END loops back to A

  Second inner iteration of (A B)+:
    Row 2: Ctx at A again
      → state at A (count=1, depth=1) → state.isAbsorbable = true
      → Ctx.hasAbsorbableState = true
      → Ctx.allStatesAbsorbable = true

    Row 3: Ctx at B, then epsilon transition to inner END → exit to C
      → state at B (count=1, depth=1) → state.isAbsorbable = true
      → state at inner END (count=2, depth=1) → state.isAbsorbable = true
      → Inner END can loop back or exit (assume (A B)+ min satisfied, exit to C)
      → Ctx.hasAbsorbableState = true (still in absorbable region)
      → Ctx.allStatesAbsorbable = true

  Row 4: Ctx at C, then epsilon transition to outer END
    → state transitions to C (depth=0) → state.isAbsorbable = false
    → C has no ABSORBABLE_BRANCH flag (depth=0, outside inner group)
    → Ctx.hasAbsorbableState = false (no absorbable states remain)
    → Ctx.allStatesAbsorbable = false (C state is not absorbable)
    → Monotonic property: hasAbsorbableState = false is PERMANENT for this context
    → C→outer END is epsilon transition (same row processing)
    → state at outer END (count=1, depth=0) → state.isAbsorbable = false
    → Ctx.hasAbsorbableState = false (still false)
    → Ctx.allStatesAbsorbable = false (still false)
    → Outer END loops back to start

  Row 5+: Ctx continues in second outer iteration (same context)
    → Outer END loops back to A (depth=1)
    → New A state created via transition from outer END state
    → state.isAbsorbable = false (inherited from outer END state, monotonic!)
    → A element has ABSORBABLE_BRANCH flag, but cannot override transition inheritance
    → Ctx.hasAbsorbableState = false (PERMANENT, monotonic property!)
    → Ctx.allStatesAbsorbable = false (PERMANENT, A state is not absorbable)
    → This context can no longer absorb others (hasAbsorbableState = false)
    → This context cannot be absorbed (allStatesAbsorbable = false)
    → Context continues matching but absorption is disabled forever

Note: Element flags only apply at initial state creation (context start).
During state transitions, state.isAbsorbable is inherited from previous state.
Once false, it remains false through all subsequent transitions.

Key points:
- Within first outer iteration's (A B)+ region, absorption works
- When progressing to C (Row 4), hasAbsorbableState becomes false permanently
- Same context continuing to second iteration: absorption stays disabled
- NEW contexts starting at later rows: fresh start with hasAbsorbableState = true
- Example: If a new context (Ctx2) starts at Row 5, Ctx2.hasAbsorbableState = true
- Pattern achieves O(n) absorption within first outer iteration's (A B)+ portion


========================================================================
DETAILED EXECUTION EXAMPLE: A+ | B C+
========================================================================

This section provides a detailed walkthrough of the "A+ | B C+" pattern
execution to illustrate absorption eligibility restoration, state
transition design, and the two-flag absorption mechanism.

Pattern Structure:
------------------
Element 0: ALT
  flags: ABSORBABLE_BRANCH
Branch 1:
  Element: A (max=INF)
    flags: ABSORBABLE | ABSORBABLE_BRANCH
Branch 2:
  Element: B
    flags: (none)
  Element: C (max=INF)
    flags: (none)

Execution with input A=TRUE, B=TRUE, C=FALSE repeated:

Note: A+ keeps A state at the last matched position (not FIN state).
FIN transition is checked and recorded in matchedState, but FIN state
itself is not added to ctx->states. This keeps ctx->states clean with
only in-progress states for absorption comparison.

  Row 1: Ctx1 starts → ALT creates A state and B state simultaneously
    → A state: A=TRUE matches (count=1) [state.isAbsorbable=true]
         * Can transition to FIN → Ctx1.matchedState recorded (Row 1)
         * A state remains in ctx->states (for potential continuation)
    → B state: B=TRUE matches (count=1) [state.isAbsorbable=false]
         * B is bounded (max=1), but remains at B state for next row check
         * B state remains in ctx->states (will check repetition on next row)
    → Row 1 end: Ctx1.states = {A state (isAbsorbable=true), B state (isAbsorbable=false)}
    → Ctx1.hasAbsorbableState = true (A state is absorbable)
    → Ctx1.allStatesAbsorbable = false (B state is not absorbable)
    → Ctx1.matchedState = A branch match ending at Row 1

  Row 2: Ctx2 starts (same as Ctx1 at Row 1)
    → Ctx1: A state matches A=TRUE (count=2) [isAbsorbable=true]
         * Can transition to FIN → Ctx1.matchedState updated (Row 2, longer match)
         * A state remains in ctx->states (count=2)
         B state: count=1 already, max=1, cannot repeat → transitions to C state
         C state checks C=FALSE → mismatch, dies
         * Note: Even if C+ completed, FIN check unnecessary
           (A+ matchedState has better altPriority, would win anyway)
    → Ctx1 Row 2 end: Ctx1.states = {A state (isAbsorbable=true, count=2)}
    → Ctx1.hasAbsorbableState = true (A state is absorbable)
    → Ctx1.allStatesAbsorbable = true (only A state, which is absorbable)
    → Ctx2: A state (count=1) [isAbsorbable=true]
         * Can transition to FIN → Ctx2.matchedState recorded (Row 2)
         * A state remains in ctx->states
         B state: B=TRUE matches (count=1) [isAbsorbable=false]
         * B state remains (will transition to C on next row)
    → Ctx2 Row 2 end: Ctx2.states = {A state (isAbsorbable=true), B state (isAbsorbable=false)}
    → Ctx2.hasAbsorbableState = true (A state is absorbable)
    → Ctx2.allStatesAbsorbable = false (B state is not absorbable)
    → Absorption check: Ctx1.hasAbsorbableState && Ctx2.allStatesAbsorbable?
    → false (Ctx2.allStatesAbsorbable = false) → No absorption

  Row 3: Ctx3 starts
    → Ctx1: A state matches A=TRUE (count=3) [isAbsorbable=true]
         * Can transition to FIN → Ctx1.matchedState updated (Row 3)
         * A state remains (count=3)
    → Ctx1 Row 3 end: Ctx1.states = {A state (isAbsorbable=true, count=3)}
    → Ctx1.hasAbsorbableState = true
    → Ctx1.allStatesAbsorbable = true
    → Ctx2: A state matches A=TRUE (count=2) [isAbsorbable=true]
         * Can transition to FIN → Ctx2.matchedState updated (Row 3)
         * A state remains (count=2)
         B state: count=1 already, max=1, cannot repeat → transitions to C state
         C state checks C=FALSE → mismatch, dies
         * Note: Even if C+ completed, FIN check unnecessary (lexical order)
    → Ctx2 Row 3 end: Ctx2.states = {A state (isAbsorbable=true, count=2)}
    → Ctx2.hasAbsorbableState = true (A state is absorbable)
    → Ctx2.allStatesAbsorbable = true (only A state, which is absorbable)
    → Ctx3: A state (count=1) [isAbsorbable=true]
         B state: B=TRUE matches (count=1) [isAbsorbable=false]
    → Ctx3 Row 3 end: Ctx3.states = {A state (isAbsorbable=true), B state (isAbsorbable=false)}
    → Ctx3.hasAbsorbableState = true (A state is absorbable)
    → Ctx3.allStatesAbsorbable = false (B state is not absorbable)
    → Absorption check: Ctx1 vs Ctx3 (checked first, from back)
         * Pre-check: Ctx1.hasAbsorbableState && Ctx3.allStatesAbsorbable?
         * false (Ctx3.allStatesAbsorbable = false)
         * No absorption attempted (fast filter rejected)
    → Absorption check: Ctx1 vs Ctx2
         * Pre-check: Ctx1.hasAbsorbableState && Ctx2.allStatesAbsorbable?
         * true (both flags are true)
         * Ctx1.states = {A state (count=3)}
         * Ctx2.states = {A state (count=2)}
         * All Ctx2 states covered by Ctx1 (A: 3 >= 2) → Ctx2 absorbed!
         * Note: Even if Ctx1 had additional states (absorbable or not),
           Ctx2 would still be absorbed as long as all Ctx2 states are covered

This example demonstrates three key design aspects:

1. Two-flag absorption design: Ctx2 becomes eligible for absorption
   when its B state disappears due to mismatch. Two distinct flags track:
   - hasAbsorbableState: remains true throughout (A state always absorbable)
   - allStatesAbsorbable: changes from false (Row 2, has B) to true (Row 3, only A)
   This separation enables fast pre-check without state iteration.

2. State transition design: A+ keeps A state in ctx->states at the
   last matched position for absorption comparison. FIN transition is
   only checked and recorded in matchedState, not added to ctx->states.

3. Asymmetric absorption logic: Ctx1 can absorb Ctx2 even if Ctx1
   has additional states, as long as Ctx2.allStatesAbsorbable=true and
   all Ctx2 states are covered by matching Ctx1 states with higher counts.

4. Pruning opportunity (future optimization): With eager pruning,
   the B state could be eliminated at Row 1 (since max=1, count=1, no
   further progression possible), making Ctx1.allStatesAbsorbable=true
   immediately. This would enable absorption at Row 2 instead of Row 3.
   Alternatively, when B state dies during Row 2 processing, we could
   immediately update allStatesAbsorbable and trigger absorption without
   waiting for the next row. However, this optimization is not
   implemented yet - implementation is left for future work.


========================================================================
STATE TRANSITION DESIGN FOR ABSORPTION
========================================================================

NFA State Management Philosophy
--------------------------------

The absorption optimization requires clean separation between:
- In-progress states (ctx->states): active states being evaluated each row
- Completion markers (ctx->matchedState): records best match found so far

This design decision has profound implications for how state transitions
work, especially for unbounded quantifiers like A+.


The FIN State Problem
---------------------

Traditional NFA implementation for A+ would:
  1. Match A=TRUE → increment count
  2. Create TWO states:
     - Loop state: A (count++) → add to ctx->states for next row
     - Escape state: FIN (pattern complete) → add to ctx->states

Problem: If FIN state is added to ctx->states, absorption becomes complex:
  - Ctx1.states = {A state (count=3), FIN state}
  - Ctx2.states = {A state (count=2), FIN state}
  - Both have FIN states, but should we compare them?
  - FIN states don't have meaningful counts to compare
  - FIN is not in ABSORBABLE region (pattern already finished)


The Solution: Deferred FIN Transition
--------------------------------------

Instead of creating FIN state in ctx->states, we:
  1. Keep A state at last matched position in ctx->states
  2. Check if FIN transition is possible
  3. Record completion in ctx->matchedState (separate from ctx->states)
  4. FIN state is NOT added to ctx->states

Example for A+ with continuous A=TRUE input:
  Row 1: Ctx1.states = {A state (count=1)}
         Ctx1.matchedState = {FIN, ending at Row 1}
  Row 2: Ctx1.states = {A state (count=2)}  ← A state updated, not duplicated
         Ctx1.matchedState = {FIN, ending at Row 2}  ← updated to longer match
  Row 3: Ctx1.states = {A state (count=3)}
         Ctx1.matchedState = {FIN, ending at Row 3}

Absorption comparison (Row 3):
  - Ctx1.states = {A state (count=3)}
  - Ctx2.states = {A state (count=2)}
  - Compare: count=3 >= count=2, same elemIdx → absorb Ctx2
  - Clean! No FIN states to complicate the comparison.


Benefits of This Design
------------------------

1. Clean absorption logic:
   - ctx->states contains ONLY in-progress states
   - All states in ctx->states are comparable (same depth, count meaningful)
   - FIN states don't interfere with absorption judgment

2. Efficient state management:
   - No duplicate FIN states created each row
   - matchedState updated in-place (not accumulated)
   - Reduced memory footprint

3. Correct greedy semantics:
   - A+ continues matching as long as A=TRUE
   - matchedState always records the longest match so far
   - When A finally mismatches, we use the last matchedState

4. Simple state tracking:
   - ctx->states reflects "where we are in the pattern"
   - matchedState reflects "best completion found so far"
   - No confusion between "still matching" vs "already finished"


State Absorbability Inheritance
--------------------------------

Element flags (ABSORBABLE, ABSORBABLE_BRANCH) only apply at initial state
creation when a context starts. During state transitions, state.isAbsorbable
is inherited from the previous state, not from element flags.

This inheritance mechanism has critical implications:

1. Initial state creation (context start at Row 0):
   - state.isAbsorbable = (elem->flags & RPR_ELEM_ABSORBABLE_BRANCH) != 0
   - Element flags determine initial absorbability

2. State transitions (A→B, B→END, END→A, etc.):
   - New state inherits state.isAbsorbable from previous state
   - Element flags on the new element do NOT override this inheritance
   - Once state.isAbsorbable = false, it remains false through all transitions

3. Monotonic property:
   - state.isAbsorbable can change from true → false (leaving absorbable region)
   - state.isAbsorbable CANNOT change from false → true (cannot re-enter)
   - This ensures contexts permanently leave absorbable region once they exit

Example: Pattern ((A B)+ C)+

First outer iteration (Row 0-4):
  Row 0: Context starts → A state created
    → state.isAbsorbable = true (from A element's ABSORBABLE_BRANCH flag)

  Row 1: A→B transition
    → B state.isAbsorbable = true (inherited from A state, not from B flag)

  Row 1: B→END transition (epsilon, same row)
    → END state.isAbsorbable = true (inherited from B state)

  Row 4: C created via transition from inner END
    → C state.isAbsorbable = false (C element has no ABSORBABLE_BRANCH flag)

  Row 4: C→outer END transition (epsilon, same row)
    → outer END state.isAbsorbable = false (inherited from C state)

Second outer iteration (Row 5+, same context continuing):
  Row 5+: outer END loops back to A
    → New A state created via transition from outer END state
    → state.isAbsorbable = false (INHERITED from outer END state)
    → A element has ABSORBABLE_BRANCH flag, but this does NOT apply
    → Element flags only apply at context start, not during transitions
    → Monotonic property: once false, stays false forever

This is why hasAbsorbableState becomes permanently false when contexts
leave the first unbounded region - all subsequent states inherit
isAbsorbable=false regardless of element flags they transition to.


========================================================================
PLANNING STAGE: computeAbsorbability()
========================================================================

Located in src/backend/optimizer/plan/rpr.c.

Core Concept: Find First Unbounded Portion
-------------------------------------------
The algorithm identifies the FIRST unbounded portion of the pattern starting
from element 0. Only this first portion gets absorption flags. Elements after
this portion do not get flags, even if they are unbounded.

Examples:
- A+ B+: First unbounded portion is A+. B+ gets no flags.
- ((A B)+ C)+: First unbounded portion is (A B)+. C and outer END get no flags.
- (A B)+ C: First unbounded portion is (A B)+. C gets no flags.

Key constraints for the first unbounded portion:
- Must be unbounded VAR (max=INF) or unbounded GROUP (END has max=INF)
- For unbounded GROUP:
  * All elements inside at the same depth must be simple {1,1} VARs
  * No nested GROUPs inside (depth > startDepth)
  * No unbounded VARs inside (all VARs must be {1,1})

Why these constraints:
- Simple VARs ensure predictable synchronization at END element
- No nested GROUPs keeps depth-based flag assignment simple
- No unbounded VARs inside prevents complex state combinations

Examples of valid first unbounded portions:
- A+ (simple unbounded VAR)
- (A B)+ (unbounded GROUP with simple VARs A and B at depth=1)
- (A B C)+ (unbounded GROUP with simple VARs A, B, C at depth=1)

Examples where outer pattern structure is complex, but absorption still works:
- ((A B)+ C)+
  * Analysis STOPS at first unbounded portion: (A B)+
  * First portion (A B)+ is valid: A and B are simple {1,1} VARs at depth=1
  * C and outer END are beyond first portion (ignored, get no flags)
  * Result: Absorption works for the (A B)+ portion

Examples that fail constraints (cannot set absorption flags):
- (A+ B+)+ (inner A+ and B+ are unbounded VARs, violates constraint for first portion)

Algorithm:

1. Check if pattern is too short (< 2 elements) → not absorbable

2. If pattern starts with ALT:
   - Iterate through each branch
   - For each branch, check isUnboundedStart() on first element of branch
   - If true, call setAbsorbabilityFlagsForBranch() for that branch
   - If any branch is absorbable, set ABSORBABLE_BRANCH on ALT element

3. If pattern does not start with ALT:
   - Check isUnboundedStart() on first element (element 0)
   - If true, call setAbsorbabilityFlagsForBranch(pattern, 0)

Helper function isUnboundedStart(pattern, idx):
  Scans from idx forward to determine if this starts an unbounded portion.

  Case 1: Simple unbounded VAR
    - Element at idx has max=INF
    - Return true immediately

  Case 2: Unbounded GROUP
    - Scan elements from idx forward while depth >= startDepth
    - Find END element with:
      * depth == startDepth
      * max == INF (unbounded loop)
      * jump == idx (loops back to start)
    - Check all elements at startDepth are simple {1,1} VARs
    - Check no nested structures (depth > startDepth)
    - Check for outer nesting: if another END exists at lower depth before FIN
      → nested structure, return false
    - Return true if all checks pass

Helper function setAbsorbabilityFlagsForBranch(pattern, branchIdx):
  Performs two passes:

  1. First pass: detect if this is an unbounded GROUP pattern
     - Scan elements from branchIdx to find END with unbounded max that jumps back
     - Record endIdx if found

  2. Second pass: set flags on all elements at unbounded depth
     - ABSORBABLE_BRANCH: all elements where depth == startDepth
     - ABSORBABLE: judgment point only
       * Unbounded GROUP → only END element gets ABSORBABLE
       * Simple unbounded VAR → only first element gets ABSORBABLE

Runtime conditions (in buildRPRPattern):
  - Check runtime conditions first to avoid unnecessary pattern analysis:
    * rpSkipTo must be ST_PAST_LAST_ROW (not NEXT ROW)
    * Frame must be unlimited (UNBOUNDED FOLLOWING or not ROWS mode)
  - If conditions met: call computeAbsorbability() for structural check
  - If conditions not met: set pattern->isAbsorbable = false directly
  - This eliminates runtime condition checks in executor


========================================================================
RUNTIME OPERATION
========================================================================

Located in src/backend/executor/nodeWindowAgg.c.

State-Level and Context-Level Absorption Flags:

Each NFA state tracks its own absorption status (state->isAbsorbable).
Context tracks TWO distinct absorption flags for different purposes:

State Initialization:
  Two different mechanisms depending on how state is created:

  1. Initial state creation (in nfa_start_context):
     - state->isAbsorbable = (elem->flags & RPR_ELEM_ABSORBABLE_BRANCH) != 0
     - Element flags determine initial absorbability when context starts

  2. State transitions (in nfa_state_clone):
     - state->isAbsorbable = previousState->isAbsorbable
     - Inherited from previous state, NOT from element flags
     - Element flags are NOT checked during transitions
     - Monotonic: once false, stays false through all transitions

Context Initialization (in nfa_start_context):
  - ctx->hasAbsorbableState = pattern->isAbsorbable
  - ctx->allStatesAbsorbable = pattern->isAbsorbable
  - Initial state's isAbsorbable also set based on element 0's flag

Flag Management (after each row in nfa_step()):
  Two flags track absorption status:

  1. hasAbsorbableState (can this context absorb others?):
     - true if at least one state has isAbsorbable=true
     - false if all states have isAbsorbable=false
     - Indicates context is in absorbable region
     - Monotonic: once false, stays false forever

  2. allStatesAbsorbable (can this context be absorbed?):
     - true if ALL states have isAbsorbable=true
     - false if any state has isAbsorbable=false
     - Indicates context is eligible for absorption
     - Can change: false → true (non-absorbable states die)

  Optimization: Once hasAbsorbableState becomes false, no need to recalculate:
    - All absorbable states have died
    - New states only come from transitions (can't create new absorbable states)
    - Both flags remain false permanently
    - Skip all state iteration for flag updates

  Recalculation logic (only if hasAbsorbableState still true):
    - Iterate through all states
    - Check each state's isAbsorbable flag
    - Update both flags based on current states

Absorption Check (in nfa_absorb_contexts()):
  Runtime conditions (SKIP TO PAST LAST ROW, unlimited frame) are
  pre-validated at planning time. Executor simply checks pattern->isAbsorbable.

  Absorption logic: Can Ctx1 (older) absorb Ctx2 (newer)?

  Pre-check (fast filter using context flags):
  1. Ctx1.hasAbsorbableState == true (Ctx1 has ability to absorb)
  2. Ctx2.allStatesAbsorbable == true (Ctx2 is eligible to be absorbed)
     - If either check fails → skip absorption entirely
     - No need to iterate through states for these checks

  Actual absorption check (if pre-check passes):
  3. For each state in Ctx2, find matching state in Ctx1 (same elemIdx)
  4. Each Ctx2 state must be covered: Ctx1 count >= Ctx2 count

  Key insight: asymmetric check with two-flag design
  - Ctx2 (newer): allStatesAbsorbable must be true (checked via flag)
  - Ctx1 (older): hasAbsorbableState must be true (may have extra non-absorbable states)
  - We check if all Ctx2 states are covered by matching Ctx1 states

  Example:
  - Ctx1.states = {A state (absorbable, count=3), X state (non-absorbable)}
  - Ctx1.hasAbsorbableState = true, Ctx1.allStatesAbsorbable = false
  - Ctx2.states = {A state (absorbable, count=2)}
  - Ctx2.hasAbsorbableState = true, Ctx2.allStatesAbsorbable = true
  - Pre-check: Ctx1.hasAbsorbableState && Ctx2.allStatesAbsorbable? Yes
  - Check: A state in Ctx1 covers A state in Ctx2? Yes (3 >= 2)
  - Result: Ctx2 absorbed
  - Ctx1's X state doesn't prevent absorption

This design ensures:
  - No repeated element flag lookups (cached in state)
  - No runtime condition checks (validated once at planning)
  - Fast context-level filtering (two pre-computed flags, no state iteration)
  - Correct synchronization (only at designated judgment points)
  - Simple depth-independent logic (flag-based, not depth comparisons)
  - Asymmetric check: newer context must be fully absorbable, older just needs one


========================================================================
PERFORMANCE IMPACT
========================================================================

Test results for "(A B)+" pattern with 60 rows:
- Absorbed length: 2/2/2 (= group length, correct synchronization)
- Peak states: 5
- Peak contexts: 4
- Absorbed count: 29

The two-flag design ensures contexts synchronize at END elements,
preventing premature absorption attempts at intermediate positions
(A or B). This guarantees correctness while maintaining efficiency.

For absorbable patterns like "A+" or "(A B)+", practically ALL
eligible contexts get absorbed because:
- Contexts separated by group-length rows always synchronize at
  judgment points
- Older contexts always have count >= newer contexts at the same
  judgment point
- This is exactly what achieves O(n²) → O(n) reduction


========================================================================
SUMMARY
========================================================================

The context absorption optimization achieves O(n²) → O(n) performance
by eliminating redundant match searches. The design uses multiple
coordinated mechanisms:

1. Two-Flag Element Design (Planning Time):
   - RPR_ELEM_ABSORBABLE: marks judgment points (WHERE to compare)
   - RPR_ELEM_ABSORBABLE_BRANCH: marks absorbable regions (tracks boundaries)
   - For simple unbounded VAR (A+): judgment point is the VAR itself
   - For unbounded GROUP ((A B)+): judgment point is END element only
   - Ensures contexts synchronize before comparison

2. First Unbounded Portion Strategy (Planning Time):
   - Algorithm identifies FIRST unbounded portion starting from element 0
   - Only this portion gets absorption flags
   - Examples: A+ B+ → only A+ flagged; ((A B)+ C)+ → only (A B)+ flagged
   - Achieves O(n) absorption within first portion (sufficient for most cases)

3. State Inheritance Mechanism (Runtime):
   - Element flags apply ONLY at context start (nfa_start_context)
   - State transitions inherit state.isAbsorbable from previous state
   - Element flags do NOT override inheritance during transitions
   - Monotonic: once state.isAbsorbable = false, stays false forever
   - This ensures contexts permanently leave absorbable region after first portion

4. Two-Flag Context Design (Runtime):
   - hasAbsorbableState: can this context absorb others? (≥1 absorbable state)
     * Monotonic: true→false only, cannot recover once false
   - allStatesAbsorbable: can this context be absorbed? (ALL states absorbable)
     * Dynamic: can change false→true (when non-absorbable states die)
   - Enables fast pre-check without state iteration
   - Optimization: once hasAbsorbableState = false, skip all recalculation forever

5. FIN State Separation (Runtime):
   - ctx->states: in-progress states only (for absorption comparison)
   - ctx->matchedState: pattern completion marker (best match so far)
   - FIN state NOT added to ctx->states (keeps comparison clean)
   - A+ pattern: A state remains at last position, FIN only in matchedState
   - Prevents FIN states from complicating absorption logic

6. Asymmetric Absorption Logic (Runtime):
   - Pre-check: Ctx1.hasAbsorbableState && Ctx2.allStatesAbsorbable
   - Older context (Ctx1): needs ≥1 absorbable state (may have extra states)
   - Newer context (Ctx2): ALL states must be absorbable
   - Check: all Ctx2 states covered by matching Ctx1 states (count ≥)
   - Asymmetry enables absorption even when Ctx1 has non-absorbable states

7. Synchronization at Judgment Points (Runtime):
   - Contexts only compared when at same elemIdx (same pattern position)
   - For (A B)+: contexts synchronize at END every group-length rows
   - For A+: contexts synchronize at A every row
   - Prevents premature comparison at intermediate positions
   - Guarantees correctness while maintaining O(n) efficiency

Key Benefits:
- Correct synchronization: contexts compared only at designated judgment points
- Efficient runtime: no repeated element flag lookups, fast context-level filtering
- Simple state management: clean separation between in-progress vs completed states
- Depth-independent logic: flag-based design works for nested patterns
- Monotonic optimization: permanent false flags skip unnecessary recalculation
- No runtime condition checks: pre-validated at planning time


========================================================================
FUTURE WORK
========================================================================

Element Flags for Next Element Type
------------------------------------
To optimize state transition decisions, planning-time flags indicate
next element type (defined in src/include/optimizer/rpr.h):

  RPR_ELEM_NEXT_IS_END: next element is END (epsilon transition, loop back)
  RPR_ELEM_NEXT_IS_FIN: next element is FIN (epsilon transition, pattern end)

These flags enable faster runtime decisions without accessing the next element:
  - Faster state transition decisions (single flag check vs array lookup)
  - Better cache locality (element data already in cache)
  - Clear distinction between END and FIN transitions
  - Simplified runtime logic (flag-based branching)

Flag definitions added to header file. Setter logic in planning code (rpr.c)
would scan elements and set flags based on next element type during pattern
compilation.


Reluctant Quantifier Support (Mid-term)
---------------------------------------
Reluctant (non-greedy) quantifiers (A+?, B+?) are defined in SQL:2016 standard
but not yet supported by the PostgreSQL parser. Pattern syntax containing '?'
after quantifiers currently results in parser error.

The RPR_ELEM_RELUCTANT flag (0x01) is defined in the header file for future
use, preserving the grammar structure for when parser support is added.

Once parser support is implemented, absorption optimization considerations:
  - Reluctant quantifiers may create different synchronization patterns
  - Count comparison logic remains valid (Ctx1 count >= Ctx2 count)
  - May benefit from specialized absorption rules

This is left as a mid-term consideration pending parser implementation and
subsequent analysis of interaction between reluctant semantics and absorption.


Lexical Order Optimization for ALT Patterns (Long-term)
--------------------------------------------------------
In ALT patterns (e.g., "A+ | B C+"), once a higher-priority branch creates
a matchedState, lower-priority branches cannot win due to lexical order.

Optimization opportunity:
  - Once A+ branch creates matchedState, B C+ branch cannot win
  - B C+ branch can skip FIN transition checks entirely
  - Early pruning: if ctx->matchedState exists with better altPriority,
    skip completion checks for lower-priority branches

Current implementation processes all branches fully, which is correct but
does redundant work for lower-priority branches. This optimization is left
as a long-term consideration due to implementation complexity versus
marginal performance gains.


I hope this documentation helps anyone (including future me) who
needs to understand or modify this code. The design took several
iterations to get right, and I wanted to record the reasoning
while it's still fresh in my mind.

Comments welcome!

Best regards,
Henson

2026년 1월 18일 (일) PM 9:09, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Hi Henson,

>  Attached is the patch with the following changes:
>
> 1. Removed 26 variables limit and fixed count overflow:
>    - Deleted defineInitial field from WindowClause (parsenodes.h),
>      WindowAgg (plannodes.h), and related code in createplan.c and
> parse_rpr.c
>    - Now uses RPR_VARID_MAX (252) constant for the limit check
>    - Fixed NFA count overflow issue:
>      * Changed RPRNFAState.counts from int16 to int32 (execnodes.h)
>      * Added RPR_COUNT_MAX (INT32_MAX) constant (rpr.h)
>      * Handles pattern matching failures correctly at >32,767 repetitions
>      * Added INT32_MAX boundary handling to prevent overflow
>    - Updated test cases in rpr.sql:
>      * Updated variable limit tests from 26 to 252
>      * Added 100K row large partition test to verify int32 overflow handling
>
> 2. Simplified context absorption logic (under review):
>    - Key insight: Most absorption opportunities provide no practical benefit
>      because subsequent contexts are discarded immediately after a match
>      succeeds. Only absorption at unbounded pattern start shows measurable
> impact.
>    - Changes:
>      * Planner (rpr.c): Added isUnboundedStart() to identify patterns where
>        leading unbounded quantifiers enable safe absorption
>      * Executor (nodeWindowAgg.c): Simplified to only absorb at pattern
> start,
>        separated cleanup logic into nfa_cleanup_dead_contexts()
>      * Added pattern->isAbsorbable flag to enable absorption only when safe
>    - Impact: Reduces context growth from quadratic to linear.
>      Example from rpr_explain.sql Test 3.1 (PATTERN A+ B, 50 rows):
>      * With absorption: 51 total contexts, 3 peak, 30 absorbed
>      * Without absorption: Would create O(n²) contexts (each row starts a
>        context, creating 1+2+3+4 contexts per 5-row segment)
>      * Absorption maintains linear O(n) growth instead of quadratic
> explosion
>    - Note: Changes in EXPLAIN ANALYZE output suggest there may be issues in
>      the matching process, particularly in absorption and NFA state
> transitions.
>      I need to review these areas more thoroughly before I can be confident
> in
>      their correctness.
>
> 3. Added NFA statistics to EXPLAIN ANALYZE output (under review):
>    - Extended explain.c to show NFA construction and matching statistics
>    - Added comprehensive statistics tracking (execnodes.h):
>      * NFALengthStats structure for min/max/avg length measurements
>      * State statistics: peak, total created, merged (deduplicated)
>      * Context statistics: peak, total created, absorbed, skipped, pruned
>      * Match statistics: succeeded/failed counts with length distributions
>    - Implemented statistics collection in nodeWindowAgg.c
>    - New test suite: rpr_explain.sql for testing NFA statistics output
>    - Note: rpr_explain is not included in parallel_schedule (runs
> separately)
>    - Statistics reveal pattern complexity impact:
>      Example from Test 2.7 (PATTERN ((A | B)+)+, 1000 rows):
>      * NFA States: 2,664 peak, 892,447 total created
>      * Peak grows linearly with rows (~2.6x), likely due to state merging
>      * High total shows significant state churn despite controlled peak
>      * This demonstrates complex pattern behavior that users should
> understand
>      * Question: Should we add a GUC parameter to limit NFA state peak count
>        (e.g., max_rpr_nfa_states) to provide administrators with safety
> controls?
>    - This feature is still under review and may be refined in future patches
>
> 4. Major refactoring of pattern compilation and optimization (rpr.c):
>    - Split large monolithic functions into smaller, semantically meaningful
>      single-purpose functions for better readability
>    - Pattern compilation refactored:
>      * Added collectDefineVariables() to populate variable names from DEFINE
>      * Split scanRPRPattern() into recursive worker and wrapper
>      * Extracted allocateRPRPattern() for memory allocation
>      * Split fillRPRPattern() by node type: fillRPRPatternVar(),
>        fillRPRPatternGroup(), fillRPRPatternAlt()
>    - Pattern optimization converted to dispatcher pattern:
>      * optimizeSeqPattern() - flattens nested SEQ, merges consecutive
> vars/groups
>      * optimizeAltPattern() - flattens nested ALT, removes duplicates
>      * optimizeGroupPattern() - multiplies quantifiers, unwraps single
> children
>    - Each optimization step broken into separate helper functions:
>      * flattenSeqChildren(), mergeConsecutiveVars(),
> mergeConsecutiveGroups()
>      * flattenAltChildren(), removeDuplicateAlternatives()
>      * tryMultiplyQuantifiers(), tryUnwrapGroup()
>    - New optimization: mergeGroupPrefixSuffix()
>      * A B (A B)+ -> (A B){2,}
>      * (A B)+ A B -> (A B){2,}
>      * A B (A B)+ A B -> (A B){3,}
>    - Code structure reorganized with categorized forward declarations
>    - Added test cases in rpr.sql to verify new optimizations:
>      * Consecutive GROUP merge tests
>      * Quantifier multiplication tests (including INF blocking)
>      * Group prefix/suffix merge tests
>
> 5. Fixed quantifier validation:
>    - Corrected bounds checking in gram.y (e.g., {,m} now requires m >= 1)
>    - Improved error messages for invalid quantifier ranges
>
> Additional notes:
> - The NFA statistics output format in EXPLAIN ANALYZE was quickly
>   implemented for debugging purposes. I would appreciate feedback from
>   experienced PostgreSQL developers on:
>   * Whether the output format and structure are appropriate
>   * Whether these statistics would be valuable for query tuning in
> production,
>     or if they are only useful for development/debugging
>   * If production-worthy, what simplifications might make them more
> accessible
>     to users unfamiliar with NFA internals
> - Reluctant quantifier handling needs further clarification. If I cannot
>   make confident fixes before the next review cycle, I may temporarily
>   raise errors for reluctant cases until the logic is properly sorted out.
>
> Next steps:
> - The executor implementation (nodeWindowAgg.c) is the only major component
>   remaining for detailed review.
> - I will focus on thoroughly reviewing the absorption logic and NFA state
>   transition mechanisms to address the concerns noted in section 2.
> - After making necessary improvements, I will send the next patch with
>   more confidence in the executor correctness.

Ok, I have merged your patches with my patches to create v40
patches.

My patches are to fix issue with RPR + IGNORE NULLS case. I modified
ignorenulls_getfuncarginframe() which is called from window functions
when IGNORE NULLS option is specified. To cope with RPR, I added
row_is_in_reduced_frame() call to it. Also test cases were added.

Attached are the v40 patches.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
While looking into EXPLAIN VERBOSE ANALYZE output of a RPR defined
query, I noticed that the "Output" row of the explain command includes
columns from DEFINE clause (price). This is because columns referenced
in the DEFINE clause must appear on the target list. It is the same
situation as a target list which does not include a column used by
ORDER BY clause like "SELECT price FROM stock ORDER by company".  See
the discussion:
https://www.postgresql.org/message-id/13494.1250901451%40sss.pgh.pa.us

So I think it's ok for now. Opinions?

explain analyze verbose
SELECT company, tdate, price, count(*) OVER w
 FROM stock
 WINDOW w AS (
 PARTITION BY company
 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
 INITIAL
 PATTERN (A{,2} )
 DEFINE
  A AS price = 200 OR price = 140,
  B AS price = 150
);
                                                        QUERY PLAN                                                         
---------------------------------------------------------------------------------------------------------------------------
 WindowAgg  (cost=83.46..113.37 rows=1200 width=50) (actual time=0.017..0.031 rows=10.00 loops=1)
   Output: company, tdate, price, count(*) OVER w, ((price = 200) OR (price = 140)), (price = 150)
   Window: w AS (PARTITION BY stock.company ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
   Pattern: a{0,2}
   Storage: Memory  Maximum Storage: 17kB
   NFA States: 3 peak, 13 total, 0 merged
   NFA Contexts: 3 peak, 11 total, 8 pruned
   NFA: 2 matched (len 1/1/1), 0 mismatched
   Buffers: shared hit=1
   ->  Sort  (cost=83.37..86.37 rows=1200 width=40) (actual time=0.008..0.009 rows=10.00 loops=1)
         Output: company, tdate, price
         Sort Key: stock.company
         Sort Method: quicksort  Memory: 25kB
         Buffers: shared hit=1
         ->  Seq Scan on public.stock  (cost=0.00..22.00 rows=1200 width=40) (actual time=0.003..0.003 rows=10.00 loops=1)
               Output: company, tdate, price
               Buffers: shared hit=1
 Planning Time: 0.023 ms
 Execution Time: 0.050 ms
(19 rows)


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Ishii-san,

I'm sending a patch that refactors the NFA context absorption logic
for Row Pattern Recognition (RPR).

== Overview ==

This patch fixes a flawed NFA execution model where interleaved match/advance
logic prevented correct context absorption. The new design reorganizes
execution into a clear three-phase cycle: "match → absorb → advance",
enabling proper state synchronization for absorption.

== Major Changes ==

1. NFA Execution Flow Redesign (nodeWindowAgg.c)

   Previously, match and advance logic were interleaved in nfa_step_single().
   This interleaved approach prevented proper state synchronization needed
   for absorption - states would scatter to different positions before
   absorption could compare them. Now they are clearly separated:

   - nfa_match(): Convergence phase. Evaluates all waiting states against
     the current row. Checks VAR elements' DEFINE conditions and removes
     failed states.

   - nfa_absorb_contexts(): Absorbs redundant contexts. Performs absorption
     checks at synchronized points after matching completes.

   - nfa_advance(): Divergence phase. Expands epsilon transitions.
     Handles ALT (alternation), END (group termination), and optional
     elements.

   Advantages of three-phase design:
     - Correct absorption: All states evaluate the same row first, ensuring
       synchronized positions for meaningful absorption comparison.
     - Clear semantics: Each phase has single responsibility - convergence,
       optimization, divergence - making the logic easier to understand.
     - Predictable state positions: After match phase, all states are at
       known positions, enabling reliable absorption decisions.

2. Two-flag Absorption Design (rpr.c)

   At planning time, analyzes absorption eligibility and sets two flags:

   - RPR_ELEM_ABSORBABLE: Absorption judgment point (WHERE to compare).
     Set on the VAR element itself for simple unbounded VAR (A+),
     or on END only for groups ((A B)+).

   - RPR_ELEM_ABSORBABLE_BRANCH: Marks the absorbable region.
     Set on ALL elements within the region. Used at runtime to track
     state.isAbsorbable.

   Example - Pattern "(A B)+ C":
     Element 0 (A): ABSORBABLE_BRANCH
     Element 1 (B): ABSORBABLE_BRANCH
     Element 2 (END): ABSORBABLE | ABSORBABLE_BRANCH  <- judgment point
     Element 3 (C): (none)

   Advantages of two-flag design:
     - Correctness: Ensures absorption comparison happens only at synchronized
       points (e.g., END for groups), not at arbitrary positions.
     - Efficiency: All analysis done at planning time; runtime uses simple
       O(1) flag checks instead of pattern structure analysis.
     - Simplicity: Runtime logic is just monotonic flag propagation -
       once state leaves absorbable region, it stays non-absorbable.

3. Context-level Absorption Flags (execnodes.h)

   Added two flags to RPRNFAContext structure:

   - hasAbsorbableState: True if at least one state is absorbable.
     Indicates whether this context can absorb other contexts.

   - allStatesAbsorbable: True if ALL states are absorbable.
     Indicates whether this context can be absorbed.

   Absorption condition: Ctx1.hasAbsorbableState && Ctx2.allStatesAbsorbable

   Advantages of asymmetric two-flag design:
     - Fast pre-filter: O(1) flag check eliminates most context pairs before
       expensive state-by-state comparison.
     - Flexible absorption: Ctx1 can have extra non-absorbable states and
       still absorb Ctx2, as long as Ctx1 covers all of Ctx2's absorbable states.
     - Optimized updates: hasAbsorbableState is monotonic (true→false only),
       skipping recalculation once false. allStatesAbsorbable can recover
       (false→true) when non-absorbable states die.

4. State-level isAbsorbable Flag (execnodes.h)

   Added isAbsorbable field to RPRNFAState structure:

   - Computed at creation: sourceAbsorbable && (elem->flags & ABSORBABLE_BRANCH)
   - Monotonic property: once false, stays false forever
   - Cannot re-enter the absorbable region once left

5. Advance Function Separation

   Split the monolithic processing into per-element-type functions:

   - nfa_advance_alt(): Expands ALT branches. Processes all branches in
     DFS order to preserve lexical priority.

   - nfa_advance_end(): END group repetition logic. Decides loop/exit
     based on count vs min/max constraints.

   - nfa_advance_var(): VAR repetition/exit transitions.

   - nfa_route_to_elem(): Routes to next element. If VAR, adds to waiting
     states; otherwise, recursively expands epsilon transitions.

6. VAR→END Inline Transition

   When a simple VAR (min=max=1) matches and the next element is END,
   we transition to END immediately in the match phase. This is necessary
   for correct absorption: states must be at END to be marked absorbable
   before the absorption check occurs.

7. EXPLAIN Output Improvements (explain.c)

   Changed average length statistics from integer to float with 1 decimal:
   - ExplainPropertyInteger → ExplainPropertyFloat
   - "%.0f" → "%.1f"

== Performance Impact ==

For patterns like "A+ B", context absorption achieves O(n²) → O(n)
complexity improvement.

Example: Input A A A A A B
  - Row 0: Ctx1 at A (count=1)
  - Row 1: Ctx1 at A (count=2), Ctx2 at A (count=1)
    → Ctx1.count >= Ctx2.count, so Ctx2 is absorbed
  - Row 2: Ctx1 at A (count=3), Ctx3 at A (count=1)
    → Ctx3 is absorbed
  - ...

Only one context is maintained throughout, achieving O(n).

== Algorithm Details ==

The absorption algorithm works as follows:

For each pair (older Ctx1, newer Ctx2):
  1. Pre-check: Ctx1.hasAbsorbableState && Ctx2.allStatesAbsorbable
     → If false, skip (fast filter)
  2. Coverage check: For each Ctx2 state with isAbsorbable=true,
     find Ctx1 state with same elemIdx and count >= Ctx2.count
  3. If all Ctx2 absorbable states are covered, absorb Ctx2

The asymmetric design (Ctx1 needs hasAbsorbable, Ctx2 needs allAbsorbable)
allows absorption even when Ctx1 has extra non-absorbable states.

== Key Design Decisions ==

- VAR→END transition in match phase: When a simple VAR (max=1) matches
  and the next element is END, we transition immediately in the match
  phase rather than waiting for advance. This ensures states are at END
  (marked absorbable) before the absorption check.

- Optional VAR skip paths: When advance lands on a VAR with min=0,
  we create both a waiting state AND a skip state (like ALT branches).
  This ensures patterns like "A B? C" work correctly.

- END→END count increment: When transitioning from one END to another
  END within advance, we must increment the outer END's count. This
  handles nested groups like "((A|B)+)+" correctly.

- initialAdvance flag: The first advance after context creation must
  skip FIN recording. Reaching FIN without evaluating any VAR would
  create a zero-length match, which is invalid.

== Future Work ==

- Reluctant quantifiers: Currently rejected at parse time with error
  "reluctant quantifiers are not yet supported". The semantics for mixed
  patterns (e.g., A+? B+) and the optimal implementation approach need
  further clarification.

- State pruning: May be required for reluctant quantifiers (enables early
  match finalization) and context absorption (increases absorption
  eligibility by removing competing states).

- No more large-scale refactoring is planned. Future work will focus on
  quality verification through additional test cases, comprehensive test
  coverage, and memory leak checks.

Please review.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Ishii-san,
> 
> I'm sending a patch that refactors the NFA context absorption logic
> for Row Pattern Recognition (RPR).

Thanks for the new patches. I will create v41 patch.

> - No more large-scale refactoring is planned. Future work will focus on
>   quality verification through additional test cases, comprehensive test
>   coverage, and memory leak checks.

Maybe time to run pgindent? I can run pgindent before creating v41.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Fix references to external documentation not included

2026년 1월 20일 (화) AM 8:34, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Hi Henson,

> Hi Ishii-san,
>
> I'm sending a patch that refactors the NFA context absorption logic
> for Row Pattern Recognition (RPR).

Thanks for the new patches. I will create v41 patch.

> - No more large-scale refactoring is planned. Future work will focus on
>   quality verification through additional test cases, comprehensive test
>   coverage, and memory leak checks.

Maybe time to run pgindent? I can run pgindent before creating v41.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Ishii-san,

> - No more large-scale refactoring is planned. Future work will focus on
>   quality verification through additional test cases, comprehensive test
>   coverage, and memory leak checks.

Maybe time to run pgindent? I can run pgindent before creating v41.

Thanks! I'm tied up with work for a few days. Could you please run
pgindent when you create v41? I'll pick it up from cfbot next week.
I'd appreciate it.
 
Best regards,
Henson

Re: Row pattern recognition

От:
Michael Paquier <michael@paquier.xyz>
Дата:
Вложения:
On Mon, Jan 19, 2026 at 12:32:40AM +0900, Henson Choi wrote:
> I'm writing to document the detailed design of context absorption
> optimization in Row Pattern Recognition (RPR). This is mainly for
> future reference - honestly, I'm afraid I'll forget these details
> myself in a few months, and I'd rather have them written down
> somewhere public than buried in my notes. I don't want to repeat the
> mistake of famous mathematical theorems
> where brilliant ideas were lost because "the margin was too narrow
> to contain the proof" (yes, I'm looking at you, Fermat!). I certainly
> don't want future PostgreSQL hackers to spend the next 358 years
> trying to re-implement context absorption because the design rationale
> was lost. Fortunately, the PostgreSQL community has provided us with
> sufficient digital margins. :)

Note: this message is clearly AI-generated to me, and these are
usually super sloppy.  (I'd suggest to stop posting semi-generated
messages as they tend to be made of mostly unhelpful contents as they
lack judgement and context, but there's no rule against that AFAIK
around here, as well.)
--
Michael

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Michael,

2026년 1월 20일 (화) AM 8:40, Michael Paquier <michael@paquier.xyz>님이 작성:
On Mon, Jan 19, 2026 at 12:32:40AM +0900, Henson Choi wrote:
> I'm writing to document the detailed design of context absorption
> optimization in Row Pattern Recognition (RPR). This is mainly for
> future reference - honestly, I'm afraid I'll forget these details
> myself in a few months, and I'd rather have them written down
> somewhere public than buried in my notes. I don't want to repeat the
> mistake of famous mathematical theorems
> where brilliant ideas were lost because "the margin was too narrow
> to contain the proof" (yes, I'm looking at you, Fermat!). I certainly
> don't want future PostgreSQL hackers to spend the next 358 years
> trying to re-implement context absorption because the design rationale
> was lost. Fortunately, the PostgreSQL community has provided us with
> sufficient digital margins. :)

Note: this message is clearly AI-generated to me, and these are
usually super sloppy.  (I'd suggest to stop posting semi-generated
messages as they tend to be made of mostly unhelpful contents as they
lack judgement and context, but there's no rule against that AFAIK
around here, as well.)

Fair point. I can read technical documentation but lack
English communication skills, so I rely on AI for
translation. Actually, AI is what enabled me to start
contributing to PostgreSQL in the first place. I'll try
to make future posts more readable.
 
--
Michael

Thanks for the feedback.

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
>> Note: this message is clearly AI-generated to me, and these are
>> usually super sloppy.  (I'd suggest to stop posting semi-generated
>> messages as they tend to be made of mostly unhelpful contents as they
>> lack judgement and context, but there's no rule against that AFAIK
>> around here, as well.)
>>
> 
> Fair point. I can read technical documentation but lack
> English communication skills, so I rely on AI for
> translation. Actually, AI is what enabled me to start
> contributing to PostgreSQL in the first place. I'll try
> to make future posts more readable.

Using AI for translation is no problem for me. In fact, since I am not
good at English, sometimes I am googling to look for good translation
of a sentence in my message.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
>> Maybe time to run pgindent? I can run pgindent before creating v41.
>>
> 
> Thanks! I'm tied up with work for a few days. Could you please run
> pgindent when you create v41? I'll pick it up from cfbot next week.
> I'd appreciate it.

Sure no problem.
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Ishii-san,

I agree - this is expected behavior.

DEFINE expressions must be in the target list - this is a
prerequisite for NFA pattern matching. They go through the
standard expression pipeline:

2026년 1월 19일 (월) PM 3:45, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
While looking into EXPLAIN VERBOSE ANALYZE output of a RPR defined
query, I noticed that the "Output" row of the explain command includes
columns from DEFINE clause (price). This is because columns referenced
in the DEFINE clause must appear on the target list. It is the same
situation as a target list which does not include a column used by
ORDER BY clause like "SELECT price FROM stock ORDER by company".  See
the discussion:
https://www.postgresql.org/message-id/13494.1250901451%40sss.pgh.pa.us

So I think it's ok for now. Opinions?

explain analyze verbose
SELECT company, tdate, price, count(*) OVER w
 FROM stock
 WINDOW w AS (
 PARTITION BY company
 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
 INITIAL
 PATTERN (A{,2} )
 DEFINE
  A AS price = 200 OR price = 140,
  B AS price = 150
);
                                                        QUERY PLAN                                                         
---------------------------------------------------------------------------------------------------------------------------
 WindowAgg  (cost=83.46..113.37 rows=1200 width=50) (actual time=0.017..0.031 rows=10.00 loops=1)
   Output: company, tdate, price, count(*) OVER w, ((price = 200) OR (price = 140)), (price = 150)
   Window: w AS (PARTITION BY stock.company ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
   Pattern: a{0,2}
   Storage: Memory  Maximum Storage: 17kB
   NFA States: 3 peak, 13 total, 0 merged
   NFA Contexts: 3 peak, 11 total, 8 pruned
   NFA: 2 matched (len 1/1/1), 0 mismatched
   Buffers: shared hit=1
   ->  Sort  (cost=83.37..86.37 rows=1200 width=40) (actual time=0.008..0.009 rows=10.00 loops=1)
         Output: company, tdate, price
         Sort Key: stock.company
         Sort Method: quicksort  Memory: 25kB
         Buffers: shared hit=1
         ->  Seq Scan on public.stock  (cost=0.00..22.00 rows=1200 width=40) (actual time=0.003..0.003 rows=10.00 loops=1)
               Output: company, tdate, price
               Buffers: shared hit=1
 Planning Time: 0.023 ms
 Execution Time: 0.050 ms
(19 rows)

SQL: DEFINE A AS price = 200

    [PARSE]
    ResTarget { name: "A", val: "price = 200" }
        ↓ findTargetlistEntrySQL99()
    Added to query targetlist
        ↓
    [PLAN]
    WindowAgg.defineClause = List<TargetEntry>
        ↓
    [RUNTIME]
    ExecEvalExpr() called for EACH ROW
        ↓
    varMatched[A] = true/false → used by NFA pattern matching

This is the same as ORDER BY columns not in SELECT - they must
be in the internal target list for execution, as Tom Lane
explained in the thread you referenced.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Ishii-san,

While reviewing the code, I noticed a potential improvement
in 'register_reduced_frame_map()':

diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index 5185ad40237..3a71c279945 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -4770,7 +4770,7 @@ register_reduced_frame_map(WindowAggState *winstate, int64 pos, int val)
        if (pos < 0)
                elog(ERROR, "wrong pos: " INT64_FORMAT, pos);
 
-       if (pos > winstate->alloc_sz - 1)
+       while (pos > winstate->alloc_sz - 1)
        {
                realloc_sz = winstate->alloc_sz * 2;

In practice, 'pos' is always sequential (0, 1, 2, ...),
so the current 'if' works fine - doubling once is always
sufficient for +1 increment.

However, using 'while' would be more defensive, handling
any theoretical case where 'pos' might jump by more than
2x the current size.

It's a trivial change with no functional impact on normal
operation, but makes the code more robust.

What do you think?

Best regards

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Hi Ishii-san,
> 
> While reviewing the code, I noticed a potential improvement
> in 'register_reduced_frame_map()':
> 
> diff --git a/src/backend/executor/nodeWindowAgg.c
> b/src/backend/executor/nodeWindowAgg.c
> index 5185ad40237..3a71c279945 100644
> --- a/src/backend/executor/nodeWindowAgg.c
> +++ b/src/backend/executor/nodeWindowAgg.c
> @@ -4770,7 +4770,7 @@ register_reduced_frame_map(WindowAggState *winstate,
> int64 pos, int val)
>         if (pos < 0)
>                 elog(ERROR, "wrong pos: " INT64_FORMAT, pos);
> 
> -       if (pos > winstate->alloc_sz - 1)
> +       while (pos > winstate->alloc_sz - 1)
>         {
>                 realloc_sz = winstate->alloc_sz * 2;
> 
> In practice, 'pos' is always sequential (0, 1, 2, ...),
> so the current 'if' works fine - doubling once is always
> sufficient for +1 increment.
> 
> However, using 'while' would be more defensive, handling
> any theoretical case where 'pos' might jump by more than
> 2x the current size.
> 
> It's a trivial change with no functional impact on normal
> operation, but makes the code more robust.
> 
> What do you think?

Looks good improvement to me. Will merge into v41.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Fix references to external documentation not included

After applying the patch, I got rpr_explain regression test diffs as
below as attached.

EXTRA_TESTS=rpr_explain make check

Can you please review the regression diffs so that I can confirm to
replace the expected file or not?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff -U3 /usr/local/src/pgsql/current/postgresql/src/test/regress/expected/rpr_explain.out /usr/local/src/pgsql/current/postgresql/src/test/regress/results/rpr_explain.out
--- /usr/local/src/pgsql/current/postgresql/src/test/regress/expected/rpr_explain.out	2026-01-18 16:28:43.075296790 +0900
+++ /usr/local/src/pgsql/current/postgresql/src/test/regress/results/rpr_explain.out	2026-01-20 12:13:25.358105865 +0900
@@ -58,7 +58,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 101 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 80 pruned
-   NFA: 20 matched (len 2/2/2), 0 mismatched
+   NFA: 20 matched (len 2/2/2.0), 0 mismatched
    ->  Seq Scan on nfa_test (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -102,7 +102,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 101 total, 0 merged
    NFA Contexts: 2 peak, 101 total, 0 pruned
-   NFA: 100 matched (len 1/1/1), 0 mismatched
+   NFA: 100 matched (len 1/1/1.0), 0 mismatched
    ->  Seq Scan on nfa_test (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -127,7 +127,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 3 peak, 76 total, 0 merged
    NFA Contexts: 3 peak, 51 total, 25 pruned
-   NFA: 25 matched (len 1/1/1), 0 mismatched
+   NFA: 25 matched (len 1/1/1.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (8 rows)
 
@@ -149,9 +149,9 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a | b | c d | e)
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 4 peak, 361 total, 0 merged
+   NFA States: 5 peak, 363 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 40 pruned
-   NFA: 20 matched (len 2/2/2), 40 mismatched (len 2/2/2)
+   NFA: 20 matched (len 2/2/2.0), 40 mismatched (len 2/2/2.0)
    ->  Seq Scan on nfa_test (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -174,9 +174,9 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b* c+
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 267 total, 99 merged
+   NFA States: 5 peak, 235 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 67 pruned
-   NFA: 33 matched (len 3/3/3), 0 mismatched
+   NFA: 33 matched (len 3/3/3.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -196,10 +196,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a b)+
    Storage: Memory  Maximum Storage: 19kB
-   NFA States: 4 peak, 91 total, 0 merged
+   NFA States: 3 peak, 91 total, 0 merged
    NFA Contexts: 3 peak, 61 total, 30 pruned
-   NFA: 1 matched (len 60/60/60), 0 mismatched
-   NFA: 29 absorbed (len 1/1/1), 0 skipped
+   NFA: 1 matched (len 60/60/60.0), 0 mismatched
+   NFA: 29 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=60.00 loops=1)
 (9 rows)
 
@@ -220,10 +220,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a | b a | b a | b a | b a | b a | b a | b a | b)
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 9 peak, 548 total, 0 merged
+   NFA States: 17 peak, 632 total, 0 merged
    NFA Contexts: 9 peak, 101 total, 1 pruned
-   NFA: 12 matched (len 8/8/8), 3 mismatched (len 2/4/3)
-   NFA: 0 absorbed, 84 skipped (len 1/7/4)
+   NFA: 12 matched (len 8/8/8.0), 3 mismatched (len 2/4/3.0)
+   NFA: 0 absorbed, 84 skipped (len 1/7/4.0)
    ->  Function Scan on generate_series s (actual rows=100.00 loops=1)
 (9 rows)
 
@@ -243,10 +243,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a | b | c)+ d
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 9 peak, 751 total, 0 merged
+   NFA States: 15 peak, 753 total, 0 merged
    NFA Contexts: 5 peak, 101 total, 25 pruned
-   NFA: 25 matched (len 4/4/4), 0 mismatched
-   NFA: 0 absorbed, 50 skipped (len 2/3/2)
+   NFA: 25 matched (len 4/4/4.0), 0 mismatched
+   NFA: 0 absorbed, 50 skipped (len 2/3/2.5)
    ->  Function Scan on generate_series s (actual rows=100.00 loops=1)
 (9 rows)
 
@@ -265,11 +265,11 @@
  WindowAgg (actual rows=1000.00 loops=1)
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: ((a | b)+)+
-   Storage: Memory  Maximum Storage: 56kB
-   NFA States: 2664 peak, 892447 total, 0 merged
-   NFA Contexts: 668 peak, 1001 total, 333 pruned
-   NFA: 1 matched (len 1000/1000/1000), 0 mismatched
-   NFA: 0 absorbed, 666 skipped (len 1/999/500)
+   Storage: Memory  Maximum Storage: 17kB
+   NFA States: 16 peak, 7334 total, 0 merged
+   NFA Contexts: 4 peak, 1001 total, 333 pruned
+   NFA: 334 matched (len 1/2/2.0), 0 mismatched
+   NFA: 0 absorbed, 333 skipped (len 2/2/2.0)
    ->  Function Scan on generate_series s (actual rows=1000.00 loops=1)
 (9 rows)
 
@@ -292,10 +292,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 121 total, 0 merged
+   NFA States: 3 peak, 91 total, 0 merged
    NFA Contexts: 3 peak, 51 total, 10 pruned
-   NFA: 10 matched (len 5/5/5), 0 mismatched
-   NFA: 30 absorbed (len 1/1/1), 0 skipped
+   NFA: 10 matched (len 5/5/5.0), 0 mismatched
+   NFA: 30 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (9 rows)
 
@@ -315,10 +315,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a{2,4} b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 7 peak, 141 total, 0 merged
+   NFA States: 7 peak, 101 total, 0 merged
    NFA Contexts: 6 peak, 51 total, 10 pruned
-   NFA: 10 matched (len 5/5/5), 10 mismatched (len 2/2/2)
-   NFA: 0 absorbed, 20 skipped (len 3/4/4)
+   NFA: 10 matched (len 5/5/5.0), 10 mismatched (len 2/2/2.0)
+   NFA: 0 absorbed, 20 skipped (len 3/4/3.5)
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (9 rows)
 
@@ -340,7 +340,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 101 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 90 pruned
-   NFA: 10 matched (len 3/3/3), 0 mismatched
+   NFA: 10 matched (len 3/3/3.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -362,7 +362,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 3 peak, 134 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 67 pruned
-   NFA: 33 matched (len 3/3/3), 0 mismatched
+   NFA: 33 matched (len 3/3/3.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -389,7 +389,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 101 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 80 pruned
-   NFA: 20 matched (len 5/5/5), 0 mismatched
+   NFA: 20 matched (len 5/5/5.0), 0 mismatched
    ->  Seq Scan on nfa_test (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -409,10 +409,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 271 total, 0 merged
+   NFA States: 3 peak, 191 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 10 pruned
-   NFA: 10 matched (len 10/10/10), 0 mismatched
-   NFA: 80 absorbed (len 1/1/1), 0 skipped
+   NFA: 10 matched (len 10/10/10.0), 0 mismatched
+   NFA: 80 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=100.00 loops=1)
 (9 rows)
 
@@ -432,10 +432,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 24kB
-   NFA States: 5 peak, 590 total, 0 merged
+   NFA States: 3 peak, 396 total, 0 merged
    NFA Contexts: 3 peak, 201 total, 5 pruned
-   NFA: 1 matched (len 196/196/196), 0 mismatched
-   NFA: 194 absorbed (len 1/1/1), 0 skipped
+   NFA: 1 matched (len 196/196/196.0), 0 mismatched
+   NFA: 194 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=200.00 loops=1)
 (9 rows)
 
@@ -457,10 +457,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 231 total, 0 merged
+   NFA States: 3 peak, 171 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 30 pruned
-   NFA: 5 matched (len 5/5/5), 5 mismatched (len 11/11/11)
-   NFA: 60 absorbed (len 1/1/1), 0 skipped
+   NFA: 5 matched (len 5/5/5.0), 5 mismatched (len 11/11/11.0)
+   NFA: 60 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=100.00 loops=1)
 (9 rows)
 
@@ -491,10 +491,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b+ c
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 181 total, 20 merged
+   NFA States: 3 peak, 151 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 70 pruned
-   NFA: 10 matched (len 6/6/6), 0 mismatched
-   NFA: 20 absorbed (len 1/1/1), 0 skipped
+   NFA: 10 matched (len 6/6/6.0), 0 mismatched
+   NFA: 20 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=100.00 loops=1)
 (9 rows)
 
@@ -526,10 +526,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b+ c
    Storage: Memory  Maximum Storage: 18kB
-   NFA States: 5 peak, 159 total, 4 merged
+   NFA States: 3 peak, 115 total, 0 merged
    NFA Contexts: 3 peak, 61 total, 16 pruned
-   NFA: 1 matched (len 30/30/30), 1 mismatched (len 26/26/26)
-   NFA: 42 absorbed (len 1/1/1), 0 skipped
+   NFA: 1 matched (len 30/30/30.0), 1 mismatched (len 26/26/26.0)
+   NFA: 42 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series i (actual rows=60.00 loops=1)
 (9 rows)
 
@@ -561,9 +561,9 @@
        "Pattern": "a+ b+",                                                 +
        "Storage": "Memory",                                                +
        "Maximum Storage": 17,                                              +
-       "NFA States Peak": 5,                                               +
-       "NFA States Total": 102,                                            +
-       "NFA States Merged": 17,                                            +
+       "NFA States Peak": 3,                                               +
+       "NFA States Total": 85,                                             +
+       "NFA States Merged": 0,                                             +
        "NFA Contexts Peak": 3,                                             +
        "NFA Contexts Total": 51,                                           +
        "NFA Contexts Absorbed": 0,                                         +
@@ -573,7 +573,7 @@
        "NFA Mismatched": 0,                                                +
        "NFA Match Length Min": 2,                                          +
        "NFA Match Length Max": 2,                                          +
-       "NFA Match Length Avg": 2,                                          +
+       "NFA Match Length Avg": 2.0,                                        +
        "Plans": [                                                          +
          {                                                                 +
            "Node Type": "Function Scan",                                   +
@@ -619,8 +619,8 @@
        "Pattern": "a+ b",                                                  +
        "Storage": "Memory",                                                +
        "Maximum Storage": 17,                                              +
-       "NFA States Peak": 5,                                               +
-       "NFA States Total": 271,                                            +
+       "NFA States Peak": 3,                                               +
+       "NFA States Total": 191,                                            +
        "NFA States Merged": 0,                                             +
        "NFA Contexts Peak": 3,                                             +
        "NFA Contexts Total": 101,                                          +
@@ -631,10 +631,10 @@
        "NFA Mismatched": 0,                                                +
        "NFA Match Length Min": 10,                                         +
        "NFA Match Length Max": 10,                                         +
-       "NFA Match Length Avg": 10,                                         +
+       "NFA Match Length Avg": 10.0,                                       +
        "NFA Absorbed Length Min": 1,                                       +
        "NFA Absorbed Length Max": 1,                                       +
-       "NFA Absorbed Length Avg": 1,                                       +
+       "NFA Absorbed Length Avg": 1.0,                                     +
        "Plans": [                                                          +
          {                                                                 +
            "Node Type": "Function Scan",                                   +
@@ -695,7 +695,7 @@
        0                                      +
        2                          +
        2                          +
-       2                          +
+       2.0                        +
                                                                         +
                                                                          +
            Function Scan                                +
@@ -740,10 +740,10 @@
    Window: w AS (PARTITION BY p.p ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 219 total, 0 merged
+   NFA States: 3 peak, 165 total, 0 merged
    NFA Contexts: 3 peak, 93 total, 18 pruned
-   NFA: 18 matched (len 5/5/5), 0 mismatched
-   NFA: 54 absorbed (len 1/1/1), 0 skipped
+   NFA: 18 matched (len 5/5/5.0), 0 mismatched
+   NFA: 54 absorbed (len 1/1/1.0), 0 skipped
    ->  Sort (actual rows=90.00 loops=1)
          Sort Key: p.p
          Sort Method: quicksort  Memory: 27kB
@@ -774,10 +774,10 @@
    Window: w AS (PARTITION BY (CASE WHEN (v.v <= 25) THEN 1 ELSE 2 END) ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 96 total, 0 merged
+   NFA States: 3 peak, 77 total, 0 merged
    NFA Contexts: 3 peak, 52 total, 26 pruned
-   NFA: 5 matched (len 5/6/6), 0 mismatched
-   NFA: 19 absorbed (len 1/1/1), 0 skipped
+   NFA: 5 matched (len 5/6/5.8), 0 mismatched
+   NFA: 19 absorbed (len 1/1/1.0), 0 skipped
    ->  Sort (actual rows=50.00 loops=1)
          Sort Key: (CASE WHEN (v.v <= 25) THEN 1 ELSE 2 END)
          Sort Method: quicksort  Memory: 26kB
@@ -823,7 +823,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 2 total, 0 merged
    NFA Contexts: 2 peak, 2 total, 0 pruned
-   NFA: 1 matched (len 1/1/1), 0 mismatched
+   NFA: 1 matched (len 1/1/1.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=1.00 loops=1)
 (8 rows)
 
@@ -847,7 +847,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 6 total, 0 merged
    NFA Contexts: 3 peak, 6 total, 4 pruned
-   NFA: 0 matched, 1 mismatched (len 5/5/5)
+   NFA: 0 matched, 1 mismatched (len 5/5/5.0)
    ->  Function Scan on generate_series s (actual rows=5.00 loops=1)
 (8 rows)
 
@@ -883,10 +883,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a b c)+
    Storage: Memory  Maximum Storage: 19kB
-   NFA States: 4 peak, 81 total, 0 merged
+   NFA States: 3 peak, 81 total, 0 merged
    NFA Contexts: 3 peak, 61 total, 40 pruned
-   NFA: 1 matched (len 60/60/60), 0 mismatched
-   NFA: 19 absorbed (len 1/1/1), 0 skipped
+   NFA: 1 matched (len 60/60/60.0), 0 mismatched
+   NFA: 19 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=60.00 loops=1)
 (9 rows)
 
@@ -908,9 +908,9 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a | b c | d | e)
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 4 peak, 281 total, 0 merged
+   NFA States: 5 peak, 282 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 60 pruned
-   NFA: 20 matched (len 2/2/2), 20 mismatched (len 2/2/2)
+   NFA: 20 matched (len 2/2/2.0), 20 mismatched (len 2/2/2.0)
    ->  Seq Scan on nfa_test (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -930,9 +930,9 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a b? c
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 2 peak, 51 total, 0 merged
+   NFA States: 3 peak, 64 total, 0 merged
    NFA Contexts: 3 peak, 51 total, 37 pruned
-   NFA: 12 matched (len 3/3/3), 1 mismatched (len 2/2/2)
+   NFA: 12 matched (len 3/3/3.0), 1 mismatched (len 2/2/2.0)
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (8 rows)
 
@@ -952,10 +952,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a{2,5} b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 9 peak, 401 total, 0 merged
+   NFA States: 9 peak, 311 total, 0 merged
    NFA Contexts: 7 peak, 101 total, 10 pruned
-   NFA: 10 matched (len 6/6/6), 50 mismatched (len 2/6/5)
-   NFA: 0 absorbed, 30 skipped (len 3/5/4)
+   NFA: 10 matched (len 6/6/6.0), 50 mismatched (len 2/6/5.2)
+   NFA: 0 absorbed, 30 skipped (len 3/5/4.0)
    ->  Function Scan on generate_series s (actual rows=100.00 loops=1)
 (9 rows)
 
@@ -975,9 +975,9 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a b* c
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 4 peak, 86 total, 0 merged
+   NFA States: 3 peak, 91 total, 0 merged
    NFA Contexts: 3 peak, 51 total, 45 pruned
-   NFA: 5 matched (len 9/9/9), 0 mismatched
+   NFA: 5 matched (len 9/9/9.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (8 rows)
 
@@ -1000,10 +1000,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: d+ u+
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 70 total, 3 merged
+   NFA States: 4 peak, 58 total, 0 merged
    NFA Contexts: 3 peak, 31 total, 17 pruned
-   NFA: 3 matched (len 3/14/8), 1 mismatched (len 3/3/3)
-   NFA: 9 absorbed (len 1/1/1), 0 skipped
+   NFA: 3 matched (len 3/14/8.0), 1 mismatched (len 3/3/3.0)
+   NFA: 9 absorbed (len 1/1/1.0), 0 skipped
    ->  Seq Scan on nfa_complex (actual rows=30.00 loops=1)
 (9 rows)
 
@@ -1023,10 +1023,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: u+ s* d+
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 76 total, 4 merged
+   NFA States: 5 peak, 76 total, 0 merged
    NFA Contexts: 3 peak, 31 total, 14 pruned
-   NFA: 4 matched (len 3/11/7), 0 mismatched
-   NFA: 12 absorbed (len 1/1/1), 0 skipped
+   NFA: 4 matched (len 3/11/7.2), 0 mismatched
+   NFA: 12 absorbed (len 1/1/1.0), 0 skipped
    ->  Seq Scan on nfa_complex (actual rows=30.00 loops=1)
 (9 rows)
 
@@ -1052,10 +1052,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a{3,}
    Storage: Memory  Maximum Storage: 18kB
-   NFA States: 4 peak, 150 total, 0 merged
-   NFA Contexts: 3 peak, 51 total, 0 pruned
-   NFA: 1 matched (len 50/50/50), 0 mismatched
-   NFA: 49 absorbed (len 1/1/1), 0 skipped
+   NFA States: 3 peak, 99 total, 0 merged
+   NFA Contexts: 2 peak, 51 total, 0 pruned
+   NFA: 1 matched (len 50/50/50.0), 0 mismatched
+   NFA: 49 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (9 rows)
 
@@ -1080,7 +1080,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 1001 total, 0 merged
    NFA Contexts: 3 peak, 1001 total, 500 pruned
-   NFA: 500 matched (len 2/2/2), 0 mismatched
+   NFA: 500 matched (len 2/2/2.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=1000.00 loops=1)
 (8 rows)
 
@@ -1100,10 +1100,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 21kB
-   NFA States: 5 peak, 2971 total, 0 merged
+   NFA States: 3 peak, 1991 total, 0 merged
    NFA Contexts: 3 peak, 1001 total, 10 pruned
-   NFA: 10 matched (len 100/100/100), 0 mismatched
-   NFA: 980 absorbed (len 1/1/1), 0 skipped
+   NFA: 10 matched (len 100/100/100.0), 0 mismatched
+   NFA: 980 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=1000.00 loops=1)
 (9 rows)
 
@@ -1123,10 +1123,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a | b)+ c
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 6 peak, 2004 total, 0 merged
+   NFA States: 8 peak, 2004 total, 0 merged
    NFA Contexts: 4 peak, 501 total, 167 pruned
-   NFA: 166 matched (len 3/3/3), 1 mismatched (len 2/2/2)
-   NFA: 0 absorbed, 166 skipped (len 2/2/2)
+   NFA: 166 matched (len 3/3/3.0), 1 mismatched (len 2/2/2.0)
+   NFA: 0 absorbed, 166 skipped (len 2/2/2.0)
    ->  Function Scan on generate_series s (actual rows=500.00 loops=1)
 (9 rows)
 
@@ -1150,10 +1150,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 121 total, 0 merged
+   NFA States: 3 peak, 91 total, 0 merged
    NFA Contexts: 3 peak, 51 total, 10 pruned
-   NFA: 10 matched (len 5/5/5), 0 mismatched
-   NFA: 30 absorbed (len 1/1/1), 0 skipped
+   NFA: 10 matched (len 5/5/5.0), 0 mismatched
+   NFA: 30 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (9 rows)
 
@@ -1173,10 +1173,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 121 total, 0 merged
+   NFA States: 3 peak, 91 total, 0 merged
    NFA Contexts: 3 peak, 51 total, 10 pruned
-   NFA: 10 matched (len 5/5/5), 0 mismatched
-   NFA: 30 absorbed (len 1/1/1), 0 skipped
+   NFA: 10 matched (len 5/5/5.0), 0 mismatched
+   NFA: 30 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (9 rows)
 
@@ -1199,10 +1199,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 91 total, 0 merged
+   NFA States: 3 peak, 71 total, 0 merged
    NFA Contexts: 3 peak, 41 total, 10 pruned
-   NFA: 10 matched (len 3/3/3), 0 mismatched
-   NFA: 20 absorbed (len 1/1/1), 0 skipped
+   NFA: 10 matched (len 3/3/3.0), 0 mismatched
+   NFA: 20 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=40.00 loops=1)
 (9 rows)
 
@@ -1222,10 +1222,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a* b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 71 total, 0 merged
-   NFA Contexts: 3 peak, 41 total, 10 pruned
-   NFA: 10 matched (len 3/3/3), 0 mismatched
-   NFA: 20 absorbed (len 1/1/1), 0 skipped
+   NFA States: 4 peak, 102 total, 0 merged
+   NFA Contexts: 2 peak, 41 total, 10 pruned
+   NFA: 10 matched (len 3/3/3.0), 0 mismatched
+   NFA: 20 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=40.00 loops=1)
 (9 rows)
 
@@ -1245,10 +1245,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a? b c
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 3 peak, 41 total, 0 merged
+   NFA States: 4 peak, 82 total, 0 merged
    NFA Contexts: 4 peak, 41 total, 20 pruned
-   NFA: 10 matched (len 3/3/3), 0 mismatched
-   NFA: 0 absorbed, 10 skipped (len 2/2/2)
+   NFA: 10 matched (len 3/3/3.0), 0 mismatched
+   NFA: 0 absorbed, 10 skipped (len 2/2/2.0)
    ->  Function Scan on generate_series s (actual rows=40.00 loops=1)
 (9 rows)
 
@@ -1268,9 +1268,9 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a{3} b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 4 peak, 121 total, 0 merged
+   NFA States: 4 peak, 51 total, 0 merged
    NFA Contexts: 5 peak, 51 total, 10 pruned
-   NFA: 10 matched (len 4/4/4), 30 mismatched (len 2/4/3)
+   NFA: 10 matched (len 4/4/4.0), 30 mismatched (len 2/4/3.0)
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (8 rows)
 
@@ -1290,10 +1290,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a{2,4} b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 7 peak, 141 total, 0 merged
+   NFA States: 7 peak, 101 total, 0 merged
    NFA Contexts: 6 peak, 51 total, 10 pruned
-   NFA: 10 matched (len 5/5/5), 10 mismatched (len 2/2/2)
-   NFA: 0 absorbed, 20 skipped (len 3/4/4)
+   NFA: 10 matched (len 5/5/5.0), 10 mismatched (len 2/2/2.0)
+   NFA: 0 absorbed, 20 skipped (len 3/4/3.5)
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (9 rows)
 
@@ -1313,10 +1313,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a{3,} b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 4 peak, 136 total, 0 merged
+   NFA States: 3 peak, 86 total, 0 merged
    NFA Contexts: 3 peak, 51 total, 5 pruned
-   NFA: 5 matched (len 10/10/10), 0 mismatched
-   NFA: 40 absorbed (len 1/1/1), 0 skipped
+   NFA: 5 matched (len 10/10/10.0), 0 mismatched
+   NFA: 40 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (9 rows)
 
@@ -1340,10 +1340,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 49 total, 0 merged
+   NFA States: 3 peak, 37 total, 0 merged
    NFA Contexts: 3 peak, 21 total, 4 pruned
-   NFA: 4 matched (len 5/5/5), 0 mismatched
-   NFA: 12 absorbed (len 1/1/1), 0 skipped
+   NFA: 4 matched (len 5/5/5.0), 0 mismatched
+   NFA: 12 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=20.00 loops=1)
 (9 rows)
 
@@ -1363,10 +1363,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b c
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 70 total, 3 merged
+   NFA States: 3 peak, 52 total, 0 merged
    NFA Contexts: 3 peak, 31 total, 9 pruned
-   NFA: 3 matched (len 9/9/9), 0 mismatched
-   NFA: 18 absorbed (len 1/1/1), 0 skipped
+   NFA: 3 matched (len 9/9/9.0), 0 mismatched
+   NFA: 18 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=30.00 loops=1)
 (9 rows)
 
@@ -1388,7 +1388,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 31 total, 0 merged
    NFA Contexts: 3 peak, 31 total, 20 pruned
-   NFA: 10 matched (len 3/3/3), 0 mismatched
+   NFA: 10 matched (len 3/3/3.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=30.00 loops=1)
 (8 rows)
 
@@ -1411,9 +1411,9 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a | b) c
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 3 peak, 201 total, 0 merged
+   NFA States: 3 peak, 202 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 60 pruned
-   NFA: 20 matched (len 2/2/2), 20 mismatched (len 2/2/2)
+   NFA: 20 matched (len 2/2/2.0), 20 mismatched (len 2/2/2.0)
    ->  Seq Scan on nfa_test (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -1435,9 +1435,9 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a | b | c | d) e
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 401 total, 0 merged
+   NFA States: 5 peak, 404 total, 0 merged
    NFA Contexts: 3 peak, 101 total, 20 pruned
-   NFA: 20 matched (len 2/2/2), 60 mismatched (len 2/2/2)
+   NFA: 20 matched (len 2/2/2.0), 60 mismatched (len 2/2/2.0)
    ->  Seq Scan on nfa_test (actual rows=100.00 loops=1)
 (8 rows)
 
@@ -1457,10 +1457,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a | b)+ c
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 6 peak, 204 total, 0 merged
+   NFA States: 8 peak, 204 total, 0 merged
    NFA Contexts: 4 peak, 51 total, 17 pruned
-   NFA: 16 matched (len 3/3/3), 1 mismatched (len 2/2/2)
-   NFA: 0 absorbed, 16 skipped (len 2/2/2)
+   NFA: 16 matched (len 3/3/3.0), 1 mismatched (len 2/2/2.0)
+   NFA: 0 absorbed, 16 skipped (len 2/2/2.0)
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (9 rows)
 
@@ -1483,10 +1483,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: (a b)+
    Storage: Memory  Maximum Storage: 18kB
-   NFA States: 4 peak, 61 total, 0 merged
+   NFA States: 3 peak, 61 total, 0 merged
    NFA Contexts: 3 peak, 41 total, 20 pruned
-   NFA: 1 matched (len 40/40/40), 0 mismatched
-   NFA: 19 absorbed (len 1/1/1), 0 skipped
+   NFA: 1 matched (len 40/40/40.0), 0 mismatched
+   NFA: 19 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=40.00 loops=1)
 (9 rows)
 
@@ -1508,8 +1508,8 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 7 peak, 66 total, 0 merged
    NFA Contexts: 6 peak, 41 total, 20 pruned
-   NFA: 5 matched (len 8/8/8), 0 mismatched
-   NFA: 0 absorbed, 15 skipped (len 2/6/4)
+   NFA: 5 matched (len 8/8/8.0), 0 mismatched
+   NFA: 0 absorbed, 15 skipped (len 2/6/4.0)
    ->  Function Scan on generate_series s (actual rows=40.00 loops=1)
 (9 rows)
 
@@ -1531,8 +1531,8 @@
    Storage: Memory  Maximum Storage: 19kB
    NFA States: 60 peak, 286 total, 0 merged
    NFA Contexts: 32 peak, 61 total, 30 pruned
-   NFA: 1 matched (len 60/60/60), 1 mismatched (len 2/2/2)
-   NFA: 0 absorbed, 28 skipped (len 4/58/31)
+   NFA: 1 matched (len 60/60/60.0), 1 mismatched (len 2/2/2.0)
+   NFA: 0 absorbed, 28 skipped (len 4/58/31.0)
    ->  Function Scan on generate_series s (actual rows=60.00 loops=1)
 (9 rows)
 
@@ -1555,10 +1555,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 73 total, 0 merged
+   NFA States: 3 peak, 55 total, 0 merged
    NFA Contexts: 3 peak, 31 total, 6 pruned
-   NFA: 6 matched (len 5/5/5), 0 mismatched
-   NFA: 18 absorbed (len 1/1/1), 0 skipped
+   NFA: 6 matched (len 5/5/5.0), 0 mismatched
+   NFA: 18 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=30.00 loops=1)
 (9 rows)
 
@@ -1578,10 +1578,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 73 total, 0 merged
+   NFA States: 3 peak, 55 total, 0 merged
    NFA Contexts: 3 peak, 31 total, 6 pruned
-   NFA: 6 matched (len 5/5/5), 0 mismatched
-   NFA: 18 absorbed (len 1/1/1), 0 skipped
+   NFA: 6 matched (len 5/5/5.0), 0 mismatched
+   NFA: 18 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=30.00 loops=1)
 (9 rows)
 
@@ -1601,10 +1601,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 18kB
-   NFA States: 5 peak, 73 total, 0 merged
+   NFA States: 3 peak, 55 total, 0 merged
    NFA Contexts: 3 peak, 31 total, 6 pruned
-   NFA: 6 matched (len 5/5/5), 0 mismatched
-   NFA: 18 absorbed (len 1/1/1), 0 skipped
+   NFA: 6 matched (len 5/5/5.0), 0 mismatched
+   NFA: 18 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=30.00 loops=1)
 (9 rows)
 
@@ -1627,10 +1627,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 18kB
-   NFA States: 5 peak, 73 total, 0 merged
+   NFA States: 3 peak, 55 total, 0 merged
    NFA Contexts: 3 peak, 31 total, 6 pruned
-   NFA: 6 matched (len 5/5/5), 0 mismatched
-   NFA: 18 absorbed (len 1/1/1), 0 skipped
+   NFA: 6 matched (len 5/5/5.0), 0 mismatched
+   NFA: 18 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=30.00 loops=1)
 (9 rows)
 
@@ -1655,10 +1655,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 88 total, 0 merged
+   NFA States: 3 peak, 78 total, 0 merged
    NFA Contexts: 3 peak, 51 total, 23 pruned
-   NFA: 17 matched (len 2/3/3), 0 mismatched
-   NFA: 10 absorbed (len 1/1/1), 0 skipped
+   NFA: 17 matched (len 2/3/2.6), 0 mismatched
+   NFA: 10 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
 (9 rows)
 
@@ -1683,7 +1683,7 @@
    Storage: Memory  Maximum Storage: 18kB
    NFA States: 60 peak, 466 total, 0 merged
    NFA Contexts: 31 peak, 31 total, 1 pruned
-   NFA: 0 matched, 29 mismatched (len 2/30/16)
+   NFA: 0 matched, 29 mismatched (len 2/30/16.0)
    ->  Function Scan on generate_series s (actual rows=30.00 loops=1)
 (8 rows)
 
@@ -1706,10 +1706,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 73 total, 0 merged
+   NFA States: 3 peak, 55 total, 0 merged
    NFA Contexts: 3 peak, 31 total, 6 pruned
-   NFA: 6 matched (len 5/5/5), 0 mismatched
-   NFA: 18 absorbed (len 1/1/1), 0 skipped
+   NFA: 6 matched (len 5/5/5.0), 0 mismatched
+   NFA: 18 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series v (actual rows=30.00 loops=1)
 (9 rows)
 
@@ -1732,10 +1732,10 @@
    Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
    Pattern: a+ b c
    Storage: Memory  Maximum Storage: 17kB
-   NFA States: 5 peak, 1150 total, 50 merged
+   NFA States: 3 peak, 851 total, 0 merged
    NFA Contexts: 3 peak, 501 total, 151 pruned
-   NFA: 50 matched (len 8/9/9), 0 mismatched
-   NFA: 299 absorbed (len 1/1/1), 0 skipped
+   NFA: 50 matched (len 8/9/9.0), 0 mismatched
+   NFA: 299 absorbed (len 1/1/1.0), 0 skipped
    ->  Function Scan on generate_series s (actual rows=500.00 loops=1)
 (9 rows)
 
@@ -1757,7 +1757,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 501 total, 0 merged
    NFA Contexts: 3 peak, 501 total, 250 pruned
-   NFA: 250 matched (len 2/2/2), 0 mismatched
+   NFA: 250 matched (len 2/2/2.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=500.00 loops=1)
 (8 rows)
 
@@ -1784,7 +1784,7 @@
    Storage: Memory  Maximum Storage: 17kB
    NFA States: 2 peak, 501 total, 0 merged
    NFA Contexts: 3 peak, 501 total, 495 pruned
-   NFA: 5 matched (len 5/5/5), 0 mismatched
+   NFA: 5 matched (len 5/5/5.0), 0 mismatched
    ->  Function Scan on generate_series s (actual rows=500.00 loops=1)
 (8 rows)
 

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
> Fix references to external documentation not included

After applying the patch, I got rpr_explain regression test diffs as
below as attached.

EXTRA_TESTS=rpr_explain make check

Can you please review the regression diffs so that I can confirm to
replace the expected file or not?

Attached the missing expected file. Please replace. 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

>>> Maybe time to run pgindent? I can run pgindent before creating v41.
>>>
>> 
>> Thanks! I'm tied up with work for a few days. Could you please run
>> pgindent when you create v41? I'll pick it up from cfbot next week.
>> I'd appreciate it.
> 
> Sure no problem.

Pgindent done. Attached are the v41 patches.  Note that I have updated
typedefs.list because some RPR related typedefs were missed.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

I'd like to propose an extension to the Row Pattern Recognition (RPR)
absorption mechanism to handle anchored patterns (those starting with
START or similar prefix elements).

== Background ==

The current RPR implementation includes an absorption optimization that
reduces time complexity from O(n²) to O(n) for unbounded quantifiers
like A+. When multiple match contexts are at the same ABSORBABLE element,
the context that started earlier (having matched more rows) absorbs
later-starting contexts, eliminating redundant processing.

For example, with pattern "A+ B":
  - Ctx1 starts at row 0, matching A
  - Ctx2 starts at row 1, matching A
  - Ctx1 always has more A's → Ctx2 is absorbed (removed)
  - Result: Only 1 context maintained, O(n) complexity

== The Problem ==

This absorption mechanism breaks down for anchored patterns like
"START SECOND A+ B". The PREFIX elements (START, SECOND) block
absorption because contexts at different PREFIX positions cannot
be meaningfully compared.

Without absorption, we regress to O(n²) behavior as contexts
accumulate without being eliminated.

== Proposed Solution: Original/Alternate Simultaneous Progression ==

The key insight is to track two logical "paths" within each context:

1. Original: Starts at Element 0 (PREFIX + BODY)
   - can_absorb = true
   - Can be used as matchedState (actual match result)

2. Alternate: Starts at Element 2 (BODY only, skipping PREFIX)
   - can_be_absorbed = true
   - Used only for absorption eligibility checking
   - Cannot be used as matchedState

Both paths process the same row data simultaneously. The alternate
path serves as a "shadow" that indicates whether the context is
eligible for absorption.

== Absorption Conditions ==

For Ctx1 to absorb Ctx2, all conditions must be met:

1. Ctx1.can_absorb = true (original not outside pattern region)
2. Ctx2.can_be_absorbed = true (alternate still alive in BODY)
3. Ctx2's original has reached ABSORBABLE (PREFIX matching confirmed)
4. Ctx1 started before Ctx2

Note: No count comparison is needed. The alternate being alive
confirms absorption eligibility; the earlier-starting context
always wins.

== Why Wait for Ctx2's Original to Reach ABSORBABLE? ==

We cannot absorb Ctx2 immediately when it starts. We must wait
until Ctx2's original successfully passes through PREFIX elements
(START, SECOND) and reaches the ABSORBABLE point (A+). This
confirms that Ctx2's PREFIX matching succeeded before we remove it.

== Why Absorption is Safe (Common Fate) ==

Once both contexts reach the same ABSORBABLE element (A+), they
share a "common fate":

  - Same element position, same future data stream
  - Same choices ahead (continue A+ or transition to B)
  - If Ctx1 succeeds → Ctx2 would have succeeded too (but shorter match)
  - If Ctx1 fails → Ctx2 would have failed too (nothing lost)
  - The only difference is in the past (rows already matched),
    which doesn't affect future matching decisions

This property guarantees that absorption is safe: we never lose
a potential match by absorbing a later-starting context into an
earlier one.

== Flag Design ==

Compile-time (Element flags):
  - RPR_ELEM_ABSORBABLE: Unchanged (marks WHERE comparison happens)
  - RPR_ELEM_ABSORBABLE_BRANCH_PREFIX: New (PREFIX region, blocks absorption)
  - RPR_ELEM_ABSORBABLE_BRANCH_BODY: New (BODY region, allows absorption)

Runtime (State variables):
  - can_absorb: "Can absorb others" (original=true, alternate=false)
  - can_be_absorbed: "Can be absorbed" (PREFIX→false, BODY→true)

Both flags are monotonic: once false, they cannot become true again.

== Complexity Analysis ==

With this extension:
  - Maximum concurrent contexts: PREFIX_length + 1
  - For "START SECOND A+ B": max 3 contexts at any time
  - Overall complexity: O(n) maintained

Example flow for "START SECOND A+ B" with data r0-r4(A,A,A,A,B):
  Row 0: Ctx1 starts                                           [1]
  Row 1: Ctx2 starts (cannot absorb: PREFIX not confirmed)     [2]
  Row 2: Ctx3 starts                                           [3]
  Row 3: Ctx4 starts, Ctx2 absorbed (PREFIX confirmed)         [3]
  Row 4: Ctx1 matches B, Ctx3-5 discarded                      [1]

Note: This is not an immediate priority. Stabilizing the current
RPR patch comes first. I'm sharing this design early to get feedback
and ensure the approach is sound before implementation.

I have a working design document with detailed state transition
rules and examples. Happy to share more details.

Thoughts?

--
Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
The series of patches are to implement the row pattern recognition
(SQL/RPR) feature. Currently the implementation is a subset of SQL/RPR
(ISO/IEC 19075-2:2016). Namely, implementation of some features of
R020 (WINDOW clause). R010 (MATCH_RECOGNIZE) is out of the scope of
the patches.

Attached are the v42 patches.
The difference from v41 include:

- Add Peter as a reviewer to commit message. He gave a good valuable
  suggestions to the gram.y patch. I accidentally forgot to credit his
  name.

- Tons of enhancements from Henson.

-- Fully rewrite absorption logic (optimizer/plan/rpr.c).
   Example: (a+ b* c?){2,} -> (a+" b* c?){2,}

-- Add safety check to tryMultiplyQuantifiers (optimizer/plan/rpr.c)
   Example: (A{2}){2,3} cannot be rewritten to A{4,6} because it allows
   5 times reputation which is not correct. Perform multiplication
   optimization only in safe case.

-- Fix infinite loop/segfault when unlimited quantifiers (e.g. (A*)*,
   (A+)+) are used.

-- Optimize unlimited quantifiers if possible (e.g. (A*)* -> A*, (A+)+ -> A+)

-- Fix segfault case (SELECT id, flag ...WINDOW w AS (... DEFINE T AS flag)

-- More accurate error position report

-- Some code refactoring in parser/planner patches

-- Split regression test file into rpr.sql and rpr_base.sql

-- Fix outfuncs.c and readfuncs.c

-- Fix some corner cases bug of regular expression optimization

-- Remove unused PATTERN variable to enhance performance

-- Change treatment of undefined DEFINE variables. Previously if
   variable "A" is used in PATTERN but not defined in DEFINE, A is
   automatically defined as "A AS TRUE". Now A is evaluated as TRUE in
   executor and the generated entry for A is removed. This improves
   memory usage.

-- EXPLAIN now shows the absorbable points (a+")

- Bug fix from me.

-- Assertion failure when two or more window clauses are used.
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

> The series of patches are to implement the row pattern recognition
> (SQL/RPR) feature. Currently the implementation is a subset of SQL/RPR
> (ISO/IEC 19075-2:2016). Namely, implementation of some features of
> R020 (WINDOW clause). R010 (MATCH_RECOGNIZE) is out of the scope of
> the patches.
> 
> Attached are the v42 patches.

I found a small typo in a function comment: non-ASCII letter was
used. In my understanding, using non-ASCII letters in the program
files are not recommended. Patch attached.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

I found a small typo in a function comment: non-ASCII letter was
used. In my understanding, using non-ASCII letters in the program
files are not recommended. Patch attached.

Thank you for catching this! You are absolutely right. I apologize for
using non-ASCII characters in the code comments.

I've reviewed all the RPR-related files and found additional instances
of non-ASCII characters:
- Arrows "→" instead of "->"
- Superscript "²" instead of "^2"
- Greater-than-or-equal "≥" instead of ">="

Found in:
- src/backend/optimizer/plan/rpr.c (1 instance)
- src/backend/executor/nodeWindowAgg.c (5 instances)
- src/include/nodes/execnodes.h (4 instances)
- src/test/regress/sql/rpr.sql (7 instances)
- src/test/regress/sql/rpr_base.sql (15 instances)
- src/test/regress/expected/rpr.out (7 instances)
- src/test/regress/expected/rpr_base.out (15 instances)

Total: 54 instances across 7 files.

To ensure comprehensive coverage, I created a Python verification tool
that checks for non-ASCII characters and reports their Unicode code
points. I've verified all 46 files changed in the v42 patch series,
and confirmed no additional non-ASCII characters remain.

I'll be more careful going forward to use only ASCII characters in
source files and comments. Updated patch attached.

Best regards,
Henson
 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Thank you for catching this! You are absolutely right. I apologize for
> using non-ASCII characters in the code comments.
> 
> I've reviewed all the RPR-related files and found additional instances
> of non-ASCII characters:
> - Arrows "→" instead of "->"
> - Superscript "²" instead of "^2"
> - Greater-than-or-equal "≥" instead of ">="
> 
> Found in:
> - src/backend/optimizer/plan/rpr.c (1 instance)
> - src/backend/executor/nodeWindowAgg.c (5 instances)
> - src/include/nodes/execnodes.h (4 instances)
> - src/test/regress/sql/rpr.sql (7 instances)
> - src/test/regress/sql/rpr_base.sql (15 instances)
> - src/test/regress/expected/rpr.out (7 instances)
> - src/test/regress/expected/rpr_base.out (15 instances)
> 
> Total: 54 instances across 7 files.
> 
> To ensure comprehensive coverage, I created a Python verification tool
> that checks for non-ASCII characters and reports their Unicode code
> points. I've verified all 46 files changed in the v42 patch series,
> and confirmed no additional non-ASCII characters remain.
> 
> I'll be more careful going forward to use only ASCII characters in
> source files and comments. Updated patch attached.

Thank you for the prompt response. Your patch applied cleanly here.
BTW, I have a question regarding NFA related objects initialization in
nodeWindowAgg.c.

In release_partition():
	/* Reset NFA state for new partition */
	winstate->nfaContext = NULL;
	winstate->nfaContextTail = NULL;
	winstate->nfaContextFree = NULL;
	winstate->nfaStateFree = NULL;
	winstate->nfaLastProcessedRow = -1;
	winstate->nfaStatesActive = 0;
	winstate->nfaContextsActive = 0;

While in ExecInitWindowAgg():
	/* Initialize NFA free lists for row pattern matching */
	winstate->nfaContext = NULL;
	winstate->nfaContextTail = NULL;
	winstate->nfaContextFree = NULL;
	winstate->nfaStateFree = NULL;
	winstate->nfaLastProcessedRow = -1;

So the latter does not initialize winstate->nfaStatesActive and
winstate->nfaContextsActive. Can you please explain why?
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

BTW, I have a question regarding NFA related objects initialization in
nodeWindowAgg.c.

In release_partition():
        /* Reset NFA state for new partition */
        winstate->nfaContext = NULL;
        winstate->nfaContextTail = NULL;
        winstate->nfaContextFree = NULL;
        winstate->nfaStateFree = NULL;
        winstate->nfaLastProcessedRow = -1;
        winstate->nfaStatesActive = 0;
        winstate->nfaContextsActive = 0;

While in ExecInitWindowAgg():
        /* Initialize NFA free lists for row pattern matching */
        winstate->nfaContext = NULL;
        winstate->nfaContextTail = NULL;
        winstate->nfaContextFree = NULL;
        winstate->nfaStateFree = NULL;
        winstate->nfaLastProcessedRow = -1;

So the latter does not initialize winstate->nfaStatesActive and
winstate->nfaContextsActive. Can you please explain why?

You're absolutely right to notice this inconsistency. Let me explain:

## Why ExecInitWindowAgg() omits these two fields

In ExecInitWindowAgg(), the WindowAggState structure is created via
makeNode(WindowAggState), which internally uses palloc0(). This
zero-initializes all memory, so:

  - All pointers → NULL (0)
  - nfaStatesActive → 0
  - nfaContextsActive → 0
  - All other statistics counters → 0

Technically, only nfaLastProcessedRow = -1 truly needs explicit
initialization since it requires a non-zero value. The nfaContext = NULL
assignments are redundant but follow PostgreSQL's convention of
explicitly setting pointers to NULL for code clarity and documentation.

The pattern in ExecInitWindowAgg() follows PostgreSQL's common practice:
  - Pointers: explicitly initialized to NULL (for readability)
  - Counters: implicitly zero-initialized via palloc0() (intentionally omitted)

This same pattern appears throughout the function for other fields too.
For example, framehead_slot and frametail_slot are explicitly set to NULL,
while framehead_valid and frametail_valid are left zero-initialized.

## What nfaStatesActive and nfaContextsActive do

These two fields serve as internal counters for tracking active NFA
resources:

nfaStatesActive: Tracks the current number of active NFA states in memory.
  - Incremented in nfa_state_alloc() when allocating a new state
  - Decremented in nfa_state_free() when returning a state to the free list
  - Used to calculate nfaStatesMax (peak usage) for EXPLAIN ANALYZE

nfaContextsActive: Tracks the current number of active NFA contexts.
  - Incremented in nfa_context_alloc() when creating a new context
  - Decremented in nfa_context_free() when recycling a context
  - Used to calculate nfaContextsMax (peak usage) for EXPLAIN ANALYZE

Both counters start at 0 and are updated during NFA execution to track
resource usage for performance monitoring.

## Why release_partition() must explicitly reset them

release_partition() is called when moving to a new partition and must
reset per-partition state. Unlike ExecInitWindowAgg() which creates a
fresh structure, release_partition() reuses an existing structure that
contains values from the previous partition.

The root cause of the reset requirement is that release_partition()
calls MemoryContextReset(winstate->partcontext), which frees all
partition-local memory. This includes:
  - All NFA context structures pointed to by nfaContext
  - All NFA state nodes in the free lists (nfaContextFree, nfaStateFree)
  - All other partition-specific data

As a consequence of this memory reset:
  1. The NFA pointers (nfaContext, nfaContextFree, etc.) must be set to
     NULL to avoid dangling pointers
  2. The active resource counters (nfaStatesActive, nfaContextsActive)
     must be reset to 0 since all the resources they were counting have
     been freed

Example scenario:
  Partition 1 processing:
    - nfaStatesActive increments one-by-one as states are allocated,
      decrements as they are freed, fluctuates during execution,
      ends at some non-zero value (e.g., 3)
    - nfaContextsActive similarly fluctuates, ends at some value (e.g., 2)

  Partition 2 starts → release_partition() called:
    - MemoryContextReset(partcontext) frees all NFA structures
    - nfaContext, nfaContextFree, etc. → must set to NULL
    - nfaStatesActive: 3 → must reset to 0
    - nfaContextsActive: 2 → must reset to 0

These counters track instantaneous active resources within a partition,
so they must be reset to 0 when starting a new partition. In contrast,
cumulative statistics like nfaStatesMax and nfaStatesTotalCreated are
NOT reset because they track overall query-wide statistics across all
partitions.

## Why only these two counters?

You might wonder why I don't propose initializing all the other NFA
statistics fields as well. ExecInitWindowAgg() currently omits explicit
initialization for many statistics fields:

  Per-partition internal counters (reset at partition boundaries):
    - nfaStatesActive = 0;        (omitted)
    - nfaContextsActive = 0;      (omitted)

  Query-wide cumulative statistics (never reset):
    - nfaStatesMax = 0;                 (omitted)
    - nfaStatesTotalCreated = 0;        (omitted)
    - nfaStatesMerged = 0;              (omitted)
    - nfaContextsMax = 0;               (omitted)
    - nfaContextsTotalCreated = 0;      (omitted)
    - nfaContextsAbsorbed = 0;          (omitted)
    - nfaContextsSkipped = 0;           (omitted)
    - nfaContextsPruned = 0;            (omitted)
    - nfaMatchesSucceeded = 0;          (omitted)
    - nfaMatchesFailed = 0;             (omitted)
    - nfaMatchLen = {0, 0, 0};          (omitted)
    - nfaFailLen = {0, 0, 0};           (omitted)
    - nfaAbsorbedLen = {0, 0, 0};       (omitted)
    - nfaSkippedLen = {0, 0, 0};        (omitted)

The key distinction is that nfaStatesActive and nfaContextsActive are
the ONLY statistics that get reset in release_partition(). All the other
statistics are cumulative across the entire query and should never be
reset between partitions.

For example, nfaStatesMax tracks the peak number of active states across
ALL partitions, not just within one partition. Similarly,
nfaStatesTotalCreated accumulates the total count across all partitions.
These cumulative statistics start at 0 (via palloc0) and only increase,
never getting reset.

Therefore, I believe it only makes sense to add explicit initialization
for nfaStatesActive and nfaContextsActive, since these are the only two
that release_partition() also explicitly resets. Adding explicit
initialization for all the cumulative statistics would be misleading,
as it might suggest they get reset somewhere (which they don't).

## Proposal for consistency

For consistency with release_partition(), I can add just the two
per-partition counter initializations to ExecInitWindowAgg():

  /* Initialize NFA free lists for row pattern matching */
  winstate->nfaContext = NULL;
  winstate->nfaContextTail = NULL;
  winstate->nfaContextFree = NULL;
  winstate->nfaStateFree = NULL;
  winstate->nfaLastProcessedRow = -1;
  winstate->nfaStatesActive = 0;        // Add this
  winstate->nfaContextsActive = 0;      // Add this

This would make both ExecInitWindowAgg() and release_partition()
initialize the same set of per-partition NFA fields, making the code
more uniform and easier to review. The cumulative statistics fields
remain omitted in both functions, which correctly reflects that they
are never reset.

Functionally, this change makes no difference since palloc0() already
zeros these fields, but it improves code consistency and makes the
per-partition vs. query-wide distinction clearer.

Would you like me to include this change in the next patch?

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Therefore, I believe it only makes sense to add explicit initialization
> for nfaStatesActive and nfaContextsActive, since these are the only two
> that release_partition() also explicitly resets.

That makes sense.

> Adding explicit
> initialization for all the cumulative statistics would be misleading,
> as it might suggest they get reset somewhere (which they don't).
> 
> ## Proposal for consistency
> 
> For consistency with release_partition(), I can add just the two
> per-partition counter initializations to ExecInitWindowAgg():
> 
>   /* Initialize NFA free lists for row pattern matching */
>   winstate->nfaContext = NULL;
>   winstate->nfaContextTail = NULL;
>   winstate->nfaContextFree = NULL;
>   winstate->nfaStateFree = NULL;
>   winstate->nfaLastProcessedRow = -1;
>   winstate->nfaStatesActive = 0;        // Add this
>   winstate->nfaContextsActive = 0;      // Add this
> 
> This would make both ExecInitWindowAgg() and release_partition()
> initialize the same set of per-partition NFA fields, making the code
> more uniform and easier to review. The cumulative statistics fields
> remain omitted in both functions, which correctly reflects that they
> are never reset.
> 
> Functionally, this change makes no difference since palloc0() already
> zeros these fields, but it improves code consistency and makes the
> per-partition vs. query-wide distinction clearer.
> 
> Would you like me to include this change in the next patch?

Yes, please.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

> Therefore, I believe it only makes sense to add explicit initialization
> for nfaStatesActive and nfaContextsActive, since these are the only two
> that release_partition() also explicitly resets.

That makes sense.

Thank you for confirming.

> ## Proposal for consistency
>
>   /* Initialize NFA free lists for row pattern matching */
>   winstate->nfaContext = NULL;
>   winstate->nfaContextTail = NULL;
>   winstate->nfaContextFree = NULL;
>   winstate->nfaStateFree = NULL;
>   winstate->nfaLastProcessedRow = -1;
>   winstate->nfaStatesActive = 0;        // Add this
>   winstate->nfaContextsActive = 0;      // Add this
>
> Would you like me to include this change in the next patch?

Yes, please.


Done. Please see the attached patch.

Best regards,
Henson
 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> ## Proposal for consistency
>> >
>> >   /* Initialize NFA free lists for row pattern matching */
>> >   winstate->nfaContext = NULL;
>> >   winstate->nfaContextTail = NULL;
>> >   winstate->nfaContextFree = NULL;
>> >   winstate->nfaStateFree = NULL;
>> >   winstate->nfaLastProcessedRow = -1;
>> >   winstate->nfaStatesActive = 0;        // Add this
>> >   winstate->nfaContextsActive = 0;      // Add this
>> >
>> > Would you like me to include this change in the next patch?
>>
>> Yes, please.
>>
> 
> 
> Done. Please see the attached patch.

Looks good to me.

BTW, I noticed that following test now succeeds with v42 patch.
In rpr_explain.sql test 11.3:

-- Test 11.3: Consecutive increasing values (using PREV)
-- FIXME: The original pattern was:
--   DEFINE A AS v > PREV(v) OR PREV(v) IS NULL
-- This causes "ERROR: unrecognized node type: 15" (T_FuncExpr) because
-- NullTest(FuncExpr(PREV)) is not properly handled somewhere in the planner.
-- The expression v > PREV(v) works fine, but PREV(v) IS NULL fails.
-- Using COALESCE(PREV(v), 0) as a workaround until the bug is fixed.
EXPLAIN (ANALYZE, BUFFERS OFF, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) OVER w
FROM generate_series(1, 50) AS s(v)
WINDOW w AS (
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    AFTER MATCH SKIP PAST LAST ROW
    PATTERN (A{3,})
    DEFINE A AS v > COALESCE(PREV(v), 0)
);

I changed 
   DEFINE A AS v > COALESCE(PREV(v), 0)
to
   DEFINE A AS v > PREV(v) OR PREV(v) IS NULL
 and get following result.

EXPLAIN (ANALYZE, BUFFERS OFF, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) OVER w
FROM generate_series(1, 50) AS s(v)
WINDOW w AS (
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    AFTER MATCH SKIP PAST LAST ROW
    PATTERN (A{3,})
    DEFINE A AS v > PREV(v) OR PREV(v) IS NULL
);
                              QUERY PLAN                              
----------------------------------------------------------------------
 WindowAgg (actual rows=50.00 loops=1)
   Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
   Pattern: a{3,}"
   Storage: Memory  Maximum Storage: 18kB
   NFA States: 3 peak, 99 total, 0 merged
   NFA Contexts: 2 peak, 51 total, 0 pruned
   NFA: 1 matched (len 50/50/50.0), 0 mismatched
   NFA: 49 absorbed (len 1/1/1.0), 0 skipped
   ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
(9 rows)

Probably we can restore 11.3 test in v43?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

> Done. Please see the attached patch.

Looks good to me.
 
Thank you for reviewing.
 
I changed
   DEFINE A AS v > COALESCE(PREV(v), 0)
to
   DEFINE A AS v > PREV(v) OR PREV(v) IS NULL
 and get following result.

EXPLAIN (ANALYZE, BUFFERS OFF, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) OVER w
FROM generate_series(1, 50) AS s(v)
WINDOW w AS (
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    AFTER MATCH SKIP PAST LAST ROW
    PATTERN (A{3,})
    DEFINE A AS v > PREV(v) OR PREV(v) IS NULL
);
                              QUERY PLAN                             
----------------------------------------------------------------------
 WindowAgg (actual rows=50.00 loops=1)
   Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
   Pattern: a{3,}"
   Storage: Memory  Maximum Storage: 18kB
   NFA States: 3 peak, 99 total, 0 merged
   NFA Contexts: 2 peak, 51 total, 0 pruned
   NFA: 1 matched (len 50/50/50.0), 0 mismatched
   NFA: 49 absorbed (len 1/1/1.0), 0 skipped
   ->  Function Scan on generate_series s (actual rows=50.00 loops=1)
(9 rows)

Probably we can restore 11.3 test in v43?


Yes, I've already restored Test 11.3 with the original pattern:

  DEFINE A AS v > PREV(v) OR PREV(v) IS NULL

Additionally, I've implemented cross-platform normalization for Storage memory values
to address the platform differences (18kB vs 19kB, 23kB vs 24kB, etc.) observed between
macOS and Rocky Linux 10.

The attached patch includes:

1. Test 11.3 restoration with original PREV(v) IS NULL pattern
2. Cross-platform Storage normalization using rpr_explain_filter() PL/pgSQL function
   - Normalizes text format: "Maximum Storage: 18kB" -> "Maximum Storage: NkB"
   - Normalizes JSON format: "Maximum Storage": 17 -> "Maximum Storage": 0
   - Normalizes XML format: <Maximum-Storage>17</Maximum-Storage> -> <Maximum-Storage>0</Maximum-Storage>
   - Preserves NFA statistics unchanged (they are test assertions)
3. All EXPLAIN statements wrapped with rpr_explain_filter()
4. Removed rpr_explain_1.out (no longer needed)
5. Added rpr_explain to parallel_schedule test suite

Patch statistics:
 src/test/regress/expected/rpr_explain.out   |  559 +++---
 src/test/regress/expected/rpr_explain_1.out | 1803 -------------------
 src/test/regress/parallel_schedule          |    2 +-
 src/test/regress/sql/rpr_explain.sql        |  294 ++-
 4 files changed, 521 insertions(+), 2137 deletions(-)
 delete mode 100644 src/test/regress/expected/rpr_explain_1.out

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Yes, I've already restored Test 11.3 with the original pattern:
> 
>   DEFINE A AS v > PREV(v) OR PREV(v) IS NULL

Good.

> Additionally, I've implemented cross-platform normalization for Storage
> memory values
> to address the platform differences (18kB vs 19kB, 23kB vs 24kB, etc.)
> observed between
> macOS and Rocky Linux 10.
> 
> The attached patch includes:
> 
> 1. Test 11.3 restoration with original PREV(v) IS NULL pattern
> 2. Cross-platform Storage normalization using rpr_explain_filter() PL/pgSQL
> function

+-- Filter function to normalize Storage memory values only (not NFA statistics)
+-- Works for text, JSON, and XML formats

What about add reasoning why only storage memory values are normalized
something like:

-- NFA statistics should not change between platforms.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

+-- Filter function to normalize Storage memory values only (not NFA statistics)
+-- Works for text, JSON, and XML formats

What about add reasoning why only storage memory values are normalized
something like:

-- NFA statistics should not change between platforms.

Done. I've updated the comment to:

-- Filter function to normalize Storage memory values only (not NFA statistics).
-- NFA statistics should not change between platforms; if they do, it could
-- indicate issues such as uninitialized memory access.
-- Works for text, JSON, and XML formats.

This round focused primarily on reviewing explain.c.  I believe we're
getting close to the final version now.  Only the nodeWindowAgg.c
code review remains on my side.

For the next submission, would it be helpful if I resend all the
incremental patches I've already sent since v42 together as separate
per-patch files?

I've also made some updates to the documentation (advanced.sgml and
ref/select.sgml).  Could you take a look and let me know if there are
any mistakes or if the changes look good to you?

I've sent several incremental patches on top of v42, and the attached
patch is the next one in that series.  Here are the changes:

Bugs fixed:

- Fix server crash in fillRPRPatternAlt() when an inner ALT is the
  last element of an outer ALT's branch.  Both alternations tried to
  set the 'next' pointer on the same endpoint element, triggering
  Assert(pat->elements[endPos].next == RPR_ELEMIDX_INVALID).  Fix by
  redirecting all elements in the branch that share the old target to
  point to the outer ALT's afterAlt instead.
  (Test: PATTERN (C (A | B) | D) -- inner ALT at end of outer branch)

- Add BEGIN element to fillRPRPatternGroup().  Previously only END was
  emitted for quantified groups, so groups with min=0 had no skip path
  to bypass the group content.  Change to BEGIN/END pairs where
  BEGIN.jump points past END (skip) and END.jump points to the first
  child (loop-back).  Add nfa_advance_begin() to the NFA executor for
  group entry and skip handling.
  (Test: PATTERN (A ((B | C) (D | E))* F?) -- * group matching 0 times)

- Fix deparse output producing wrong parenthesization for nested ALT
  patterns.  The flat-loop approach could not correctly suppress double
  parentheses for single-ALT groups or handle depth transitions around
  alternation separators.  Refactor into mutual recursion:
  deparse_rpr_elements, deparse_rpr_group, deparse_rpr_alt, and
  deparse_rpr_var.

- Fix deparse separator ordering for nested ALT: the ' | ' separator
  was emitted before closing inner parentheses, producing output like
  '(c (a | b | )d)' instead of '(c (a | b) | d)'.  Close parens to
  match separator depth before emitting ' | '.

- Fix missing ALT separator registration in deparse_rpr_alt() when an
  ALT is the first element of an outer ALT's branch.  The code only
  checked elem->next (always -1 for ALT markers) but not elem->jump,
  which carries the outer branch's separator position.

- Fix altEndPositions/altBranchStarts length mismatch caused by the
  'if (*idx > branchStart)' guard that skipped empty branches.  Remove
  the guard so both lists always have matching entries.

- Fix RPRPatternNode.reluctant initialization in gram.y.  ALT, SEQ,
  VAR, and GROUP primary productions used false (0) or left it
  uninitialized (defaulting to 0 from palloc0), but 0 is a valid
  ParseLoc meaning "location at offset 0".  Change all four creation
  sites to use -1 (no location), matching the convention used by
  ParseLoc throughout the parser.

- Fix reluctant quantifier display in both explain.c and ruleutils.c.
  A bare variable with reluctant ? (e.g. A?) was displayed as just 'a'
  since there was no quantifier to attach ? to.  Now emit '{1}?' to
  make the reluctant marker unambiguous.

New optimization:

- Add mergeConsecutiveAlts() to the SEQ optimization pipeline.  After
  GROUP{1,1} unwrap, bare alternations like (A | B) become ALT nodes
  in the SEQ.  This step detects consecutive identical ALT nodes and
  wraps them in a GROUP with the appropriate quantifier, e.g.
  (A | B) (A | B) (A | B) -> (A | B){3}.  Combined with the existing
  mergeGroupPrefixSuffix, patterns like (A | B) (A | B)+ (A | B)
  further reduce to (A | B){3,}.

- Extend tryMultiplyQuantifiers() to fold nested GROUP quantifiers
  (e.g. ((A B)+)* -> (A B)*) in addition to VAR quantifiers.

Other changes:

- Add RPR_VARID_BEGIN (252) to rpr.h for the new control element type.
  Reduce RPR_VARID_MAX from 252 to 251 accordingly and update the
  maximum-variables boundary tests.

- Add RPR_DEPTH_NONE (255) as sentinel for top-level elements that
  have no enclosing group.  Reduce RPR_DEPTH_MAX to 254 accordingly.

- Add BEGIN handling to computeAbsorbabilityRecursive() so that
  absorbability flags propagate correctly through group boundaries.

- Extract show_rpr_nfa_stats() from show_windowagg_info() for NFA
  statistics display.

- Replace defensive NULL check in collectPatternVariables() with
  Assert, since the caller guarantees a non-NULL pattern.

- Pair each EXPLAIN test query in rpr_explain.sql with a
  pg_get_viewdef() check via CREATE TEMP VIEW, verifying that both
  the ruleutils (parse tree) and explain (bytecode) deparse paths
  produce consistent PATTERN output.

- Add comment to rpr_explain_filter() explaining why only Storage
  memory values are normalized: NFA statistics should not change
  between platforms, and variation would indicate issues such as
  uninitialized memory access.

Also add EXPLAIN test cases for nested ALT patterns, consecutive ALT
merging, and ALT prefix/suffix merging.

On a side note, I feel that the automata characteristics of RPR --
state transitions, context management, absorbability, etc. -- tend to
require a much larger volume of test cases than typical RDBMS/SQL
features.  This seems unavoidable given the combinatorial nature of
NFA execution.

Best regards,
Henson 

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi,

Sorry, I forgot to attach the patch file in my previous email.

2026년 2월 7일 (토) PM 2:41, Henson Choi <assam258@gmail.com>님이 작성:
Hi Tatsuo,

+-- Filter function to normalize Storage memory values only (not NFA statistics)
+-- Works for text, JSON, and XML formats

What about add reasoning why only storage memory values are normalized
something like:

-- NFA statistics should not change between platforms.

Done. I've updated the comment to:

-- Filter function to normalize Storage memory values only (not NFA statistics).
-- NFA statistics should not change between platforms; if they do, it could
-- indicate issues such as uninitialized memory access.
-- Works for text, JSON, and XML formats.

This round focused primarily on reviewing explain.c.  I believe we're
getting close to the final version now.  Only the nodeWindowAgg.c
code review remains on my side.

For the next submission, would it be helpful if I resend all the
incremental patches I've already sent since v42 together as separate
per-patch files?

I've also made some updates to the documentation (advanced.sgml and
ref/select.sgml).  Could you take a look and let me know if there are
any mistakes or if the changes look good to you?

I've sent several incremental patches on top of v42, and the attached
patch is the next one in that series.  Here are the changes:

Bugs fixed:

- Fix server crash in fillRPRPatternAlt() when an inner ALT is the
  last element of an outer ALT's branch.  Both alternations tried to
  set the 'next' pointer on the same endpoint element, triggering
  Assert(pat->elements[endPos].next == RPR_ELEMIDX_INVALID).  Fix by
  redirecting all elements in the branch that share the old target to
  point to the outer ALT's afterAlt instead.
  (Test: PATTERN (C (A | B) | D) -- inner ALT at end of outer branch)

- Add BEGIN element to fillRPRPatternGroup().  Previously only END was
  emitted for quantified groups, so groups with min=0 had no skip path
  to bypass the group content.  Change to BEGIN/END pairs where
  BEGIN.jump points past END (skip) and END.jump points to the first
  child (loop-back).  Add nfa_advance_begin() to the NFA executor for
  group entry and skip handling.
  (Test: PATTERN (A ((B | C) (D | E))* F?) -- * group matching 0 times)

- Fix deparse output producing wrong parenthesization for nested ALT
  patterns.  The flat-loop approach could not correctly suppress double
  parentheses for single-ALT groups or handle depth transitions around
  alternation separators.  Refactor into mutual recursion:
  deparse_rpr_elements, deparse_rpr_group, deparse_rpr_alt, and
  deparse_rpr_var.

- Fix deparse separator ordering for nested ALT: the ' | ' separator
  was emitted before closing inner parentheses, producing output like
  '(c (a | b | )d)' instead of '(c (a | b) | d)'.  Close parens to
  match separator depth before emitting ' | '.

- Fix missing ALT separator registration in deparse_rpr_alt() when an
  ALT is the first element of an outer ALT's branch.  The code only
  checked elem->next (always -1 for ALT markers) but not elem->jump,
  which carries the outer branch's separator position.

- Fix altEndPositions/altBranchStarts length mismatch caused by the
  'if (*idx > branchStart)' guard that skipped empty branches.  Remove
  the guard so both lists always have matching entries.

- Fix RPRPatternNode.reluctant initialization in gram.y.  ALT, SEQ,
  VAR, and GROUP primary productions used false (0) or left it
  uninitialized (defaulting to 0 from palloc0), but 0 is a valid
  ParseLoc meaning "location at offset 0".  Change all four creation
  sites to use -1 (no location), matching the convention used by
  ParseLoc throughout the parser.

- Fix reluctant quantifier display in both explain.c and ruleutils.c.
  A bare variable with reluctant ? (e.g. A?) was displayed as just 'a'
  since there was no quantifier to attach ? to.  Now emit '{1}?' to
  make the reluctant marker unambiguous.

New optimization:

- Add mergeConsecutiveAlts() to the SEQ optimization pipeline.  After
  GROUP{1,1} unwrap, bare alternations like (A | B) become ALT nodes
  in the SEQ.  This step detects consecutive identical ALT nodes and
  wraps them in a GROUP with the appropriate quantifier, e.g.
  (A | B) (A | B) (A | B) -> (A | B){3}.  Combined with the existing
  mergeGroupPrefixSuffix, patterns like (A | B) (A | B)+ (A | B)
  further reduce to (A | B){3,}.

- Extend tryMultiplyQuantifiers() to fold nested GROUP quantifiers
  (e.g. ((A B)+)* -> (A B)*) in addition to VAR quantifiers.

Other changes:

- Add RPR_VARID_BEGIN (252) to rpr.h for the new control element type.
  Reduce RPR_VARID_MAX from 252 to 251 accordingly and update the
  maximum-variables boundary tests.

- Add RPR_DEPTH_NONE (255) as sentinel for top-level elements that
  have no enclosing group.  Reduce RPR_DEPTH_MAX to 254 accordingly.

- Add BEGIN handling to computeAbsorbabilityRecursive() so that
  absorbability flags propagate correctly through group boundaries.

- Extract show_rpr_nfa_stats() from show_windowagg_info() for NFA
  statistics display.

- Replace defensive NULL check in collectPatternVariables() with
  Assert, since the caller guarantees a non-NULL pattern.

- Pair each EXPLAIN test query in rpr_explain.sql with a
  pg_get_viewdef() check via CREATE TEMP VIEW, verifying that both
  the ruleutils (parse tree) and explain (bytecode) deparse paths
  produce consistent PATTERN output.

- Add comment to rpr_explain_filter() explaining why only Storage
  memory values are normalized: NFA statistics should not change
  between platforms, and variation would indicate issues such as
  uninitialized memory access.

Also add EXPLAIN test cases for nested ALT patterns, consecutive ALT
merging, and ALT prefix/suffix merging.

On a side note, I feel that the automata characteristics of RPR --
state transitions, context management, absorbability, etc. -- tend to
require a much larger volume of test cases than typical RDBMS/SQL
features.  This seems unavoidable given the combinatorial nature of
NFA execution.

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Sorry, I forgot to attach the patch file in my previous email.

Thanks for the patch!  Patch cleanly applied and regression test
passed here.

>> On a side note, I feel that the automata characteristics of RPR --
>> state transitions, context management, absorbability, etc. -- tend to
>> require a much larger volume of test cases than typical RDBMS/SQL
>> features.  This seems unavoidable given the combinatorial nature of
>> NFA execution.

I agree. A complex feature requires complex tests. We cannot avoid it.

BTW, I have tested RPR with large partition/reduced frame (up to 100k
rows). Following query took over 3 minutes on my laptop.

EXPLAIN (ANALYZE)
SELECT aid, count(*) OVER w
FROM generate_series(1,100000) AS g(aid) WHERE aid <= 100000
WINDOW w AS (
ORDER BY aid
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
AFTER MATCH SKIP PAST LAST ROW
INITIAL
PATTERN (START UP+)
DEFINE START AS TRUE, UP AS aid > PREV(aid)
);
                                                                 QUERY PLAN                                                                 
--------------------------------------------------------------------------------------------------------------------------------------------
 WindowAgg  (cost=4337.40..4504.08 rows=33333 width=14) (actual time=224171.589..224320.055 rows=100000.00 loops=1)
   Window: w AS (ORDER BY aid ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
   Pattern: start up+
   Storage: Disk  Maximum Storage: 4096kB
   NFA States: 200000 peak, 5000050001 total, 0 merged
   NFA Contexts: 100001 peak, 100001 total, 1 pruned
   NFA: 1 matched (len 100000/100000/100000.0), 0 mismatched
   NFA: 0 absorbed, 99998 skipped (len 2/99999/50000.5)
   Buffers: shared hit=3, temp read=400968 written=391
   ->  Sort  (cost=3754.09..3837.42 rows=33333 width=4) (actual time=14.938..38.911 rows=100000.00 loops=1)
         Sort Key: aid
         Sort Method: quicksort  Memory: 3073kB
         Buffers: shared hit=3, temp read=171 written=171
         ->  Function Scan on generate_series g  (cost=0.00..1250.00 rows=33333 width=4) (actual time=5.799..11.672 rows=100000.00 loops=1)
               Filter: (aid <= 100000)
               Buffers: temp read=171 written=171
 Planning:
   Buffers: shared hit=6 read=7
 Planning Time: 0.185 ms
 Execution Time: 224324.532 ms
 
It ran without eating all memory on my box (according to top command,
it was around 200MB). Great! However it took nearly 4 minutes to
complete the query.  I think this is because there are 100k rows
partition/reduced frame, and RPR needs to keep 100k contexts plus 200k
states at the peak. I also ran "perf top" and took following profile.

  19.87%  postgres                               [.] nfa_match
  18.92%  postgres                               [.] nfa_advance_state
  13.60%  postgres                               [.] nfa_cleanup_dead_contexts
  11.25%  postgres                               [.] row_is_in_reduced_frame
  11.06%  postgres                               [.] nfa_state_clone
   5.52%  postgres                               [.] nfa_route_to_elem
   4.39%  postgres                               [.] nfa_add_state_unique.isra.0
   4.32%  postgres                               [.] nfa_state_alloc
   2.36%  libc.so.6                              [.] __memset_avx2_unaligned_erms
   0.63%  postgres                               [.] memset@plt

The reason for nfa_match is called so many times is, it's in a a loop
which iterate over all the contexts:

	for (ctx = winstate->nfaContext; ctx != NULL; ctx = ctx->next)

I don't try to say we should enhance nfa modules in the case when
there is a large reduced frame, because I don't think this is a
realistic use case and I doubt it's worth to fight against unrealistic
scenario.

Note that even if the partition size is large, if we change the PATTERN to:

PATTERN (START UP{,3})

which generates only 4 rows reduced frames, we get very good
performance:

test=# test=# test=# EXPLAIN (ANALYZE)
SELECT aid, count(*) OVER w
FROM generate_series(1,100000) AS g(aid) WHERE aid <= 100000
WINDOW w AS (
ORDER BY aid
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
AFTER MATCH SKIP PAST LAST ROW
INITIAL
PATTERN (START UP{,3})
DEFINE START AS TRUE, UP AS aid > PREV(aid)
);
---------------------------------------------------------------------------------------------------------------------------------------------
 WindowAgg  (cost=4337.40..4504.08 rows=33333 width=14) (actual time=36.586..91.988 rows=100000.00 loops=1)
   Window: w AS (ORDER BY aid ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
   Pattern: start up{0,3}
   Storage: Memory  Maximum Storage: 17kB
   NFA States: 8 peak, 325001 total, 0 merged
   NFA Contexts: 5 peak, 100001 total, 0 pruned
   NFA: 25000 matched (len 4/4/4.0), 0 mismatched
   NFA: 0 absorbed, 75000 skipped (len 1/3/2.0)
   Buffers: temp read=171 written=171
   ->  Sort  (cost=3754.09..3837.42 rows=33333 width=4) (actual time=36.561..40.933 rows=100000.00 loops=1)
         Sort Key: aid
         Sort Method: quicksort  Memory: 3073kB
         Buffers: temp read=171 written=171
         ->  Function Scan on generate_series g  (cost=0.00..1250.00 rows=33333 width=4) (actual time=14.297..28.692 rows=100000.00 loops=1)
               Filter: (aid <= 100000)
               Buffers: temp read=171 written=171
 Planning Time: 0.087 ms
 Execution Time: 94.810 ms
(18 rows)

I think this is more realistic use case than former. If I were
correct, we don't need to work on current nfa code to squeeze better
performance for unrealistic 100k reduced frame case. I maybe wrong
and I would love to hear from others especially, Henson, Vik, Jacob.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thank you for the thorough testing and performance profiling!

BTW, I have tested RPR with large partition/reduced frame (up to 100k
rows). Following query took over 3 minutes on my laptop.

The profiling results are very insightful and help us understand where
the time is spent in extreme cases.
 
I don't try to say we should enhance nfa modules in the case when
there is a large reduced frame, because I don't think this is a
realistic use case and I doubt it's worth to fight against unrealistic
scenario.

I agree with your assessment. Let me clarify:

The pattern itself (START UP+) is realistic - it's a common pattern for
detecting upward trends. However, 100k+ consecutive matches without
interruption is not realistic. Your UP{,3} example (94ms for 100k partition)
demonstrates that the current implementation performs very well for realistic
use cases.
 
I think this is more realistic use case than former. If I were
correct, we don't need to work on current nfa code to squeeze better
performance for unrealistic 100k reduced frame case. I maybe wrong
and I would love to hear from others especially, Henson, Vik, Jacob.

I agree that we should prioritize realistic use cases. That said, there are
potential optimizations that could help:

1. Anchored pattern absorption (see my earlier message:
   https://www.postgresql.org/message-id/CAAAe_zAEg7sVM%3DWDwXMyE-odGmQyXSVi5ZzWgye6SupSjdMKpg%40mail.gmail.com)

2. Alt-pruning: In patterns like "A* | B*", once the higher-priority A branch
   has a confirmed match, the B branch can be pruned immediately. Even if B
   could continue extending to a longer match, it can never be selected due to
   lexical order semantics—A will always win. This proactive pruning respects
   SQL standard semantics while reducing unnecessary state expansion.

However, given the complexity of NFA internals, I believe we should take a
step-by-step approach:

1. First, stabilize the current RPR patch and prepare it for review
2. Then, consider optimizations as separate follow-up patches
3. Each optimization should be well-tested and reviewed independently

This approach reduces risk and makes review more manageable. The fact that
the current implementation handles even unrealistic 100k-row cases without
crashing (just slowly) shows it's already robust.

What do you think about this phased approach?

Best regards,
Henson

P.S. I discovered a crash bug that was introduced in the latest patch
refactoring. The issue occurs with nested alternation patterns like
(A+ | (A | B)+)*, where infinite recursion happens in nfa_advance_alt when
the inner BEGIN(+)'s skip jump is followed as an ALT branch pointer. I will
include the fix in the next patch update. 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Thank you for the thorough testing and performance profiling!
> 
> BTW, I have tested RPR with large partition/reduced frame (up to 100k
>> rows). Following query took over 3 minutes on my laptop.
>>
> 
> The profiling results are very insightful and help us understand where
> the time is spent in extreme cases.

Glad to hear that the data is useful.

> I agree with your assessment. Let me clarify:
> 
> The pattern itself (START UP+) is realistic - it's a common pattern for
> detecting upward trends. However, 100k+ consecutive matches without
> interruption is not realistic. Your UP{,3} example (94ms for 100k partition)
> demonstrates that the current implementation performs very well for
> realistic
> use cases.

Yes, I agree.

> I agree that we should prioritize realistic use cases. That said, there are
> potential optimizations that could help:
> 
> 1. Anchored pattern absorption (see my earlier message:
> 
> https://www.postgresql.org/message-id/CAAAe_zAEg7sVM%3DWDwXMyE-odGmQyXSVi5ZzWgye6SupSjdMKpg%40mail.gmail.com
> )
> 
> 2. Alt-pruning: In patterns like "A* | B*", once the higher-priority A
> branch
>    has a confirmed match, the B branch can be pruned immediately. Even if B
>    could continue extending to a longer match, it can never be selected due
> to
>    lexical order semantics―A will always win. This proactive pruning
> respects
>    SQL standard semantics while reducing unnecessary state expansion.
> 
> However, given the complexity of NFA internals, I believe we should take a
> step-by-step approach:
> 
> 1. First, stabilize the current RPR patch and prepare it for review
> 2. Then, consider optimizations as separate follow-up patches
> 3. Each optimization should be well-tested and reviewed independently
> 
> This approach reduces risk and makes review more manageable. The fact that
> the current implementation handles even unrealistic 100k-row cases without
> crashing (just slowly) shows it's already robust.
> 
> What do you think about this phased approach?

I totally agree.

> Best regards,
> Henson
> 
> P.S. I discovered a crash bug that was introduced in the latest patch
> refactoring. The issue occurs with nested alternation patterns like
> (A+ | (A | B)+)*, where infinite recursion happens in nfa_advance_alt when
> the inner BEGIN(+)'s skip jump is followed as an ALT branch pointer. I will
> include the fix in the next patch update.

Thanks for fixing the issue.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Ishii-san,

During code review of nodeWindowAgg.c, I discovered that update_reduced_frame()
can receive the same pos value repeatedly for RANGE/GROUPS frames.


----------------------------------------------------------------------
PATTERN DISCOVERED
----------------------------------------------------------------------

For RANGE/GROUPS frames with peer rows (rows having the same ORDER BY value):

  Data: id=1,2,3 all have val=10 (peer rows)
        id=4,5 both have val=20 (peer rows)

  RANGE frame processing:
  - id=1 processing: pos=0 (frameheadpos points to first peer)
  - id=2 processing: pos=0 (same frameheadpos)
  - id=3 processing: pos=0 (same frameheadpos)
  - id=4 processing: pos=3
  - id=5 processing: pos=3

ROWS frames always have sequential pos values (0,1,2,3,4...), but RANGE/GROUPS
can have repeated pos values (0,0,0,3,3...).


----------------------------------------------------------------------
CURRENT IMPLEMENTATION ISSUE
----------------------------------------------------------------------

The current implementation appears to assume sequential processing only, which
is valid for ROWS frames. Two specific issues found:

1. In update_reduced_frame():
   - The pos <= nfaLastProcessedRow check assumes "already processed pos doesn't
     need reprocessing", but RANGE/GROUPS require processing the same pos
     multiple times.

2. In nfa_process_row():
   - Frame boundary calculation: ctxFrameEnd = matchStartRow + frameOffset + 1
   - This adds frameOffset directly to row position, which works for ROWS but
     may be incorrect for RANGE (value-based) and GROUPS (group-based) frames.


----------------------------------------------------------------------
TEST COVERAGE LIMITATION
----------------------------------------------------------------------

The existing RANGE/GROUPS test cases in rpr_base.sql only cover simple scenarios
that don't reach the frame end, which is why this issue wasn't detected.

Most tests target ROWS frames, with only a small number testing RANGE/GROUPS
frames.


----------------------------------------------------------------------
PROPOSAL
----------------------------------------------------------------------

Rather than directly modifying these functions, we should consider an
alternative approach for non-UNBOUNDED frames:
- Strictly respect the frame head position
- Minimize lower-level optimizations (absorption/pruning)
- Avoid creating subsequent contexts for limited reuse benefit
- For bounded frames, the benefit of context reuse across rows may be limited
  compared to UNBOUNDED frames where contexts can be reused extensively
- This would simplify RANGE/GROUPS handling at the cost of some optimization

To implement this properly, we need to broaden our understanding of the
execution structure through code review of Window clauses and Aggregate
functions.

Therefore, for this round of nodeWindowAgg.c review:
1. Perform code simplification/refactoring for ROWS frames only
2. Add FIXME comments to RANGE/GROUPS test cases
3. Defer RANGE/GROUPS handling to a future phase

There may be other issues beyond RANGE/GROUPS.
After this code review round is complete, I would like to regroup and discuss
the direction forward.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

In my understanding RANGE/GROUPS are not allowed when RPR is defined.
(See ISO/IEC 19075-5 section 6.10.2 "ROWS BETWEEN CURRENT ROW AND").
So proper fix would be to error out at the parse/analyze phase if
RANGE/GROUPS are used when RPR is defined.

Vik, Jaconb,
Thoughts?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

> Hi Ishii-san,
> 
> During code review of nodeWindowAgg.c, I discovered that
> update_reduced_frame()
> can receive the same pos value repeatedly for RANGE/GROUPS frames.
> 
> 
> ----------------------------------------------------------------------
> PATTERN DISCOVERED
> ----------------------------------------------------------------------
> 
> For RANGE/GROUPS frames with peer rows (rows having the same ORDER BY
> value):
> 
>   Data: id=1,2,3 all have val=10 (peer rows)
>         id=4,5 both have val=20 (peer rows)
> 
>   RANGE frame processing:
>   - id=1 processing: pos=0 (frameheadpos points to first peer)
>   - id=2 processing: pos=0 (same frameheadpos)
>   - id=3 processing: pos=0 (same frameheadpos)
>   - id=4 processing: pos=3
>   - id=5 processing: pos=3
> 
> ROWS frames always have sequential pos values (0,1,2,3,4...), but
> RANGE/GROUPS
> can have repeated pos values (0,0,0,3,3...).
> 
> 
> ----------------------------------------------------------------------
> CURRENT IMPLEMENTATION ISSUE
> ----------------------------------------------------------------------
> 
> The current implementation appears to assume sequential processing only,
> which
> is valid for ROWS frames. Two specific issues found:
> 
> 1. In update_reduced_frame():
>    - The pos <= nfaLastProcessedRow check assumes "already processed pos
> doesn't
>      need reprocessing", but RANGE/GROUPS require processing the same pos
>      multiple times.
> 
> 2. In nfa_process_row():
>    - Frame boundary calculation: ctxFrameEnd = matchStartRow + frameOffset
> + 1
>    - This adds frameOffset directly to row position, which works for ROWS
> but
>      may be incorrect for RANGE (value-based) and GROUPS (group-based)
> frames.
> 
> 
> ----------------------------------------------------------------------
> TEST COVERAGE LIMITATION
> ----------------------------------------------------------------------
> 
> The existing RANGE/GROUPS test cases in rpr_base.sql only cover simple
> scenarios
> that don't reach the frame end, which is why this issue wasn't detected.
> 
> Most tests target ROWS frames, with only a small number testing RANGE/GROUPS
> frames.
> 
> 
> ----------------------------------------------------------------------
> PROPOSAL
> ----------------------------------------------------------------------
> 
> Rather than directly modifying these functions, we should consider an
> alternative approach for non-UNBOUNDED frames:
> - Strictly respect the frame head position
> - Minimize lower-level optimizations (absorption/pruning)
> - Avoid creating subsequent contexts for limited reuse benefit
> - For bounded frames, the benefit of context reuse across rows may be
> limited
>   compared to UNBOUNDED frames where contexts can be reused extensively
> - This would simplify RANGE/GROUPS handling at the cost of some optimization
> 
> To implement this properly, we need to broaden our understanding of the
> execution structure through code review of Window clauses and Aggregate
> functions.
> 
> Therefore, for this round of nodeWindowAgg.c review:
> 1. Perform code simplification/refactoring for ROWS frames only
> 2. Add FIXME comments to RANGE/GROUPS test cases
> 3. Defer RANGE/GROUPS handling to a future phase
> 
> There may be other issues beyond RANGE/GROUPS.
> After this code review round is complete, I would like to regroup and
> discuss
> the direction forward.
> 
> Best regards,
> Henson


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

I found following in rpr_base.sql:

-- {0} is not allowed (min must be >= 1)
SELECT id, val, COUNT(*) OVER w as cnt
FROM rpr_quant
WINDOW w AS (
    ORDER BY id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A{0} B)
    DEFINE A AS val > 1000, B AS val > 0
)
ORDER BY id;

However in my uderstanding the SQL standard allows A{0}.

PATTERN (A{0} B)
is equivalant to:
PATTERN (B)

Another interesting PATTERN is:

A{,}

This is equivalant to A{0,}

BTW, after studied this more, I found that A{0,0} is not allowed. In
this form the right hand side number shall be greater than 0. From
ISO/IEC 9075-2 7.9  "Syntax Rules 20)

"If      is specified, then let VUI1 and VUI2 be the values of the first
and second 's, respectively. VUI1 shall be less than
or equal to VUI2, and VUI2 shall be greater than 0 (zero)."

However according to the Google, Oracle and Snowflake allows A{0,0}:
they break the standard. So, what do you think PostgreSQL should do
here?  My preference is "always follow the standard". But others might
think differently.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thank you for the detailed analysis and references to the standard.

However in my uderstanding the SQL standard allows A{0}.

PATTERN (A{0} B)
is equivalant to:
PATTERN (B)

I agree. We should support A{0} to comply with the standard.
 
BTW, after studied this more, I found that A{0,0} is not allowed. In
this form the right hand side number shall be greater than 0. From
ISO/IEC 9075-2 7.9 <row pattern syntax> "Syntax Rules 20)

"If <left brace> <unsigned integer> <comma> <unsigned integer> <right
brace> is specified, then let VUI1 and VUI2 be the values of the first
and second <unsigned integer>'s, respectively. VUI1 shall be less than
or equal to VUI2, and VUI2 shall be greater than 0 (zero)."


Good catch. I agree we should follow the standard strictly. Since I
don't have direct access to the ISO/IEC 9075-2 document, I trust your
interpretation that A{0,0} should be rejected per SR 20.

However, this raises interesting questions: should we optimize patterns
by removing {0} quantifiers or simplifying them? And if so, how should
we handle patterns that become empty after such optimization?

For example:
- PATTERN (A{0})          → empty pattern
- PATTERN (A{0} B{0})     → empty pattern
- PATTERN (A{0} B)        → PATTERN (B) after optimization

Empty patterns would result in zero-length matches, which our current
implementation explicitly treats as invalid (see initialAdvance flag
logic in nodeWindowAgg.c).

More importantly, I recall that zero-length matches caused serious
issues during development, which is why we added logic to explicitly
avoid them.

The reason I cannot immediately provide a concrete plan for A{0}
support is that I need to deeply understand the semantic meaning of
zero-length matches in the SQL standard first. Without this
understanding, any implementation approach could be fundamentally
flawed.

Specifically, I need to investigate:
- What zero-length matches mean semantically in RPR
- How to handle empty patterns according to the standard
- The correct behavior when a pattern optimizes to nothing

After the current code review phase is complete, I'm also considering
setting up an Oracle test environment to observe how it handles these
edge cases. This could provide valuable insights into the expected
behavior, especially for zero-length matches and empty patterns.

Do you have insights on how the standard handles empty patterns or
zero-length matches?

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

However, this raises interesting questions: should we optimize patterns
by removing {0} quantifiers or simplifying them? And if so, how should
we handle patterns that become empty after such optimization?

For example:
- PATTERN (A{0})          → empty pattern
- PATTERN (A{0} B{0})     → empty pattern
- PATTERN (A{0} B)        → PATTERN (B) after optimization

Empty patterns would result in zero-length matches, which our current
implementation explicitly treats as invalid (see initialAdvance flag
logic in nodeWindowAgg.c).

More importantly, I recall that zero-length matches caused serious
issues during development, which is why we added logic to explicitly
avoid them.

The reason I cannot immediately provide a concrete plan for A{0}
support is that I need to deeply understand the semantic meaning of
zero-length matches in the SQL standard first. Without this
understanding, any implementation approach could be fundamentally
flawed.

Specifically, I need to investigate:
- What zero-length matches mean semantically in RPR
- How to handle empty patterns according to the standard
- The correct behavior when a pattern optimizes to nothing

After the current code review phase is complete, I'm also considering
setting up an Oracle test environment to observe how it handles these
edge cases. This could provide valuable insights into the expected
behavior, especially for zero-length matches and empty patterns.

Our current implementation cannot support A{0} due to a structural limitation.

The reduced_frame_map uses row-based representation (reduced_frame_map[pos] = val),
which can only express matches consuming at least one row. It cannot represent
zero-length matches that occur between rows without consuming any row position.

Patterns like A{0}, A*, or A? can produce zero-length matches with no row to mark
as RF_FRAME_HEAD and no position to register in the frame map.

We currently prevent this using the initialAdvance flag (nodeWindowAgg.c),
which skips FIN recording during initial epsilon transitions.

Supporting A{0} requires either restructuring reduced_frame_map to handle
virtual positions, or separate handling for zero-length matches. Before
choosing an approach, we need clarity on what the SQL standard expects for
zero-length match semantics (output generation, aggregate behavior, etc.).

Given this structural limitation, I'd like to ask: should we keep the current
initialAdvance mechanism (which prevents zero-length matches) and handle A{0}
separately?

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Hi Henson,
> 
> In my understanding RANGE/GROUPS are not allowed when RPR is defined.
> (See ISO/IEC 19075-5 section 6.10.2 "ROWS BETWEEN CURRENT ROW AND").
> So proper fix would be to error out at the parse/analyze phase if
> RANGE/GROUPS are used when RPR is defined.

Attached is a patch to disallow RANGE/GROUPS when RPR is used. On top
of your last patches.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/src/backend/parser/parse_rpr.c b/src/backend/parser/parse_rpr.c
index 048e84bd7bd..cc693b36208 100644
--- a/src/backend/parser/parse_rpr.c
+++ b/src/backend/parser/parse_rpr.c
@@ -68,6 +68,25 @@ transformRPR(ParseState *pstate, WindowClause *wc, WindowDef *windef,
 		return;
 
 	/* Check Frame options */
+
+	/* Frame type must be "ROW" */
+	if (wc->frameOptions & FRAMEOPTION_GROUPS)
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("FRAME option GROUP is not permitted when row pattern recognition is used"),
+				 errhint("Use: ROWS insted"),
+				 parser_errposition(pstate,
+									windef->frameLocation >= 0 ?
+									windef->frameLocation : windef->location)));
+	if (wc->frameOptions & FRAMEOPTION_RANGE)
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("FRAME option RANGE is not permitted when row pattern recognition is used"),
+				 errhint("Use: ROWS insted"),
+				 parser_errposition(pstate,
+									windef->frameLocation >= 0 ?
+									windef->frameLocation : windef->location)));
+
 	/* Frame must start at current row */
 	if ((wc->frameOptions & FRAMEOPTION_START_CURRENT_ROW) == 0)
 	{

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Attached is a patch to disallow RANGE/GROUPS when RPR is used. On top
of your last patches.

 Thanks for the patch. I've applied it with a typo fix ("insted" -> "instead")
and will include it in the next patch series.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Hi Tatsuo,
> 
> However, this raises interesting questions: should we optimize patterns
>> by removing {0} quantifiers or simplifying them? And if so, how should
>> we handle patterns that become empty after such optimization?
>>
>> For example:
>> - PATTERN (A{0})          → empty pattern
>> - PATTERN (A{0} B{0})     → empty pattern
>> - PATTERN (A{0} B)        → PATTERN (B) after optimization

Those optimizations are valid for now because they will produce the
same output tables.  However, if we implement MEASURES, we cannot do
such that optimization. For example,

PATTERN (A{0} B) allows to inquire count(A.*), while PATTERN (B) will
not.

>> Empty patterns would result in zero-length matches, which our current
>> implementation explicitly treats as invalid (see initialAdvance flag
>> logic in nodeWindowAgg.c).
>>
>> More importantly, I recall that zero-length matches caused serious
>> issues during development, which is why we added logic to explicitly
>> avoid them.
>>
>> The reason I cannot immediately provide a concrete plan for A{0}
>> support is that I need to deeply understand the semantic meaning of
>> zero-length matches in the SQL standard first. Without this
>> understanding, any implementation approach could be fundamentally
>> flawed.
>>
>> Specifically, I need to investigate:
>> - What zero-length matches mean semantically in RPR

There are four kinds of pattern matching results in RPR.

1. match:
Pattern successfully matches and maps to a sequence of rows
count aggregate returns > 0
count aggregate as a pattern measure[1] returns > 0
other aggregates return non null
classifier() returns non null result
ordinary column references are null/non null

2. unmatch:
Pattern fails to match a sequence of rows.
count aggregate returns 0
count aggregate as a pattern measure returns 0
other aggregates return null
classifier() returns null
ordinary column references are null/non null

3. no match:
Pattern matching skipped due to AFTER MATCH clause
count aggregate returns 0
count aggregate as a pattern measure returns null
other aggregates return null
classifier() returns null
ordinary column references are null/non null

4. empty match:
Pattern successfully matches but failed to map to a row
count aggregate returns 0
count aggregate as a pattern measure returns 0
other aggregates return null
classifier() returns null
ordinary column references are null/non null

As you can see there's no difference among 2, 3 and 4 in terms of the
output table except "count aggregate as a pattern measure". However we
have not implemented MEASURES, and we can ignore the difference for
now.

[1] e.g. "MEASURES count(*) AS mcount"

>> - How to handle empty patterns according to the standard
>> - The correct behavior when a pattern optimizes to nothing
>>
>> After the current code review phase is complete, I'm also considering
>> setting up an Oracle test environment to observe how it handles these
>> edge cases. This could provide valuable insights into the expected
>> behavior, especially for zero-length matches and empty patterns.
>>
> 
> Our current implementation cannot support A{0} due to a structural
> limitation.
> 
> The reduced_frame_map uses row-based representation (reduced_frame_map[pos]
> = val),
> which can only express matches consuming at least one row. It cannot
> represent
> zero-length matches that occur between rows without consuming any row
> position.

I think we don't need to worry about this ("It cannot represent
zero-length matches that occur between rows without consuming any row
position." problem) In Window RPR (R020) if an empty match is found,
the row position immediately moves to next row. This is because Window
clause requires that number of rows in the input table and the output
table exactly matches. If we insert unmatched rows between the rows,
the number of rows in the output table is different from the number of
rows in the input table, which is not allowed.

> Patterns like A{0}, A*, or A? can produce zero-length matches with no row
> to mark
> as RF_FRAME_HEAD and no position to register in the frame map.

For empty matching rows we just record the starting row position in
reduced_frame_map. We may need to introduce new DEFINE something like
RF_EMPTY though. And row_is_in_reduced_frame returns -1 if RF_EMPTY is
detected. This makes an empty match case behaves like an unmatch case
but it should be ok (see above).

> We currently prevent this using the initialAdvance flag (nodeWindowAgg.c),
> which skips FIN recording during initial epsilon transitions.
> 
> Supporting A{0} requires either restructuring reduced_frame_map to handle
> virtual positions, or separate handling for zero-length matches. Before
> choosing an approach, we need clarity on what the SQL standard expects for
> zero-length match semantics (output generation, aggregate behavior, etc.).

See above. In summary I think we don't need to modify the structure of
reduced_frame_map.

> Given this structural limitation, I'd like to ask: should we keep the
> current
> initialAdvance mechanism (which prevents zero-length matches) and handle
> A{0}
> separately?
> 
> Best regards,
> Henson

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

This round focused on reviewing nodeWindowAgg.c -- the NFA executor
-- which was the last piece remaining on my review list.  I've also
added a comprehensive NFA runtime test suite.

The attached patch continues the incremental series on top of v42.
Here are the changes:


FIXME issues documented:

These require non-trivial structural changes, so I've documented
them as FIXME comments for now rather than attempting a fix.

- altPriority tracks only the last ALT choice, so repeated or nested
  ALTs like (A|B)+ cannot correctly implement SQL standard lexical
  ordering.  A full-path classifier structure is needed.

- Cycle prevention condition (count == 0 && min == 0) is insufficient
  for patterns like (A*)* where cycles occur at count > 0.  Currently
  relies on implicit duplicate detection in nfa_add_state_unique.


Bugs fixed:

- Fix nfa_advance_begin() routing order: enter group first (lexically
  first), then skip path (lexically second).

- Add ALT scope boundary check in nfa_advance_alt() and
  computeAbsorbabilityRecursive() to stop branch traversal when
  element depth exits ALT scope.

- Disallow RANGE and GROUPS frame types with row pattern
  recognition, as the SQL standard only requires ROWS.
  Also remove the now-dead frame-type determination code.


NFA executor refactoring (nodeWindowAgg.c):

- Simplify nfa_process_row() phase 1: remove nfa_advance() call
  after forced mismatch at frame boundary, since all states are
  already at VAR positions and mismatch removes them.  Replace
  the redundant phase 3 frame boundary check with Assert.

- Simplify update_reduced_frame() result registration: mismatch
  path now returns early, and the post-processing SKIP mode cleanup
  block (nfa_remove_contexts_up_to vs nfa_context_free) is removed
  since eager pruning handles SKIP PAST LAST ROW and both paths
  now simply call nfa_context_free().

- Replace nfa_remove_contexts_up_to() with eager pruning inside
  nfa_add_matched_state().  When matchEndRow is extended during
  greedy matching, pending contexts within the match range are
  pruned incrementally instead of after match completion.  For
  SKIP PAST LAST ROW patterns like START UP+, this reduces the
  number of live contexts at each row from O(n) to O(1), avoiding
  O(n^2) per-row processing of contexts that would be skipped
  anyway.

- Optimize nfa_states_equal() to compare counts only up to the
  current element's depth instead of the full maxDepth.

- Rename nfa_state_clone -> nfa_state_create,
  nfa_find_context_for_pos -> nfa_get_head_context for clarity.

- Add nfa_record_context_success/skipped/absorbed statistics helpers.

- Remove unused RPRPattern parameter from
  nfa_update_absorption_flags().


Absorbability refactoring (rpr.c):

- Remove parentDepth parameter from isUnboundedStart() and
  computeAbsorbabilityRecursive().  Scope boundaries are now
  determined by element depth comparison instead of an explicit
  parent depth parameter.

- Simplify isUnboundedStart(): check simple VAR case first, then
  GROUP case with a depth-bounded loop instead of a FIN-terminated
  traversal with multiple break conditions.


Test changes:

- Add rpr_nfa.sql: comprehensive NFA runtime test suite covering
  quantifier boundaries (min/max/exact), alternation priority, nested
  patterns, frame boundary variations, INITIAL mode (syntax error
  expected), pathological patterns, context absorption, and FIXME
  reproduction cases.

- Add nth_value out-of-frame tests, ReScan/LATERAL test, and
  nth_value IGNORE NULLS test to rpr.sql.

- Change selected EXPLAIN test queries in rpr_explain.sql from
  EXPLAIN (COSTS OFF) to EXPLAIN (ANALYZE, ...) to verify actual
  NFA execution statistics.

- Fix stale comments across rpr.sql, rpr_base.sql, and rpr_nfa.sql:
  remove resolved BUG annotations, update error messages to match
  actual output, correct optimization result descriptions, and
  standardize Expected comment placement to after SQL statements.


Other changes:

- Run pgindent on RPR source files.  Add /*----------*/ comment
  guards to protect structured comments from reformatting.


Coverage:

I ran gcov on the modified lines (diff-only coverage).  The attached
coverage.zip contains an HTML report.  Summary:

- 18 files, 124 functions, 2238 modified lines analyzed
- Overall: 92.1% line coverage (2061/2238)
- Core files (nodeWindowAgg.c, rpr.c, explain.c, parse_rpr.c):
  98.0-98.5% each
- Node serialization (outfuncs.c, readfuncs.c, equalfuncs.c):
  0% -- these implement RPRPattern serialization for plan caching,
  but regression tests don't exercise prepared statements with RPR
- ruleutils.c: 96.3% -- untested lines are the reluctant quantifier
  display path ({1}?), which is currently rejected at parse time

The node serialization functions (141 lines, 0% coverage) are the
largest untested area.  I'm not sure how to trigger these paths
in the regression test framework.  Any suggestions?

I'll send a separate email within a few days listing the FIXME
issues and other unresolved items from the mailing list discussion
for your review.


Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

Thanks for the patches! I applied them on top of v42 and rebased
against current master.  Attached are the v43 patches.

> Hi Tatsuo,
> 
> This round focused on reviewing nodeWindowAgg.c -- the NFA executor
> -- which was the last piece remaining on my review list.  I've also
> added a comprehensive NFA runtime test suite.
> 
> The attached patch continues the incremental series on top of v42.
> Here are the changes:
> 
> 
> FIXME issues documented:
> 
> These require non-trivial structural changes, so I've documented
> them as FIXME comments for now rather than attempting a fix.
> 
> - altPriority tracks only the last ALT choice, so repeated or nested
>   ALTs like (A|B)+ cannot correctly implement SQL standard lexical
>   ordering.  A full-path classifier structure is needed.
> 
> - Cycle prevention condition (count == 0 && min == 0) is insufficient
>   for patterns like (A*)* where cycles occur at count > 0.  Currently
>   relies on implicit duplicate detection in nfa_add_state_unique.
> 
> 
> Bugs fixed:
> 
> - Fix nfa_advance_begin() routing order: enter group first (lexically
>   first), then skip path (lexically second).
> 
> - Add ALT scope boundary check in nfa_advance_alt() and
>   computeAbsorbabilityRecursive() to stop branch traversal when
>   element depth exits ALT scope.
> 
> - Disallow RANGE and GROUPS frame types with row pattern
>   recognition, as the SQL standard only requires ROWS.
>   Also remove the now-dead frame-type determination code.
> 
> 
> NFA executor refactoring (nodeWindowAgg.c):
> 
> - Simplify nfa_process_row() phase 1: remove nfa_advance() call
>   after forced mismatch at frame boundary, since all states are
>   already at VAR positions and mismatch removes them.  Replace
>   the redundant phase 3 frame boundary check with Assert.
> 
> - Simplify update_reduced_frame() result registration: mismatch
>   path now returns early, and the post-processing SKIP mode cleanup
>   block (nfa_remove_contexts_up_to vs nfa_context_free) is removed
>   since eager pruning handles SKIP PAST LAST ROW and both paths
>   now simply call nfa_context_free().
> 
> - Replace nfa_remove_contexts_up_to() with eager pruning inside
>   nfa_add_matched_state().  When matchEndRow is extended during
>   greedy matching, pending contexts within the match range are
>   pruned incrementally instead of after match completion.  For
>   SKIP PAST LAST ROW patterns like START UP+, this reduces the
>   number of live contexts at each row from O(n) to O(1), avoiding
>   O(n^2) per-row processing of contexts that would be skipped
>   anyway.
> 
> - Optimize nfa_states_equal() to compare counts only up to the
>   current element's depth instead of the full maxDepth.
> 
> - Rename nfa_state_clone -> nfa_state_create,
>   nfa_find_context_for_pos -> nfa_get_head_context for clarity.
> 
> - Add nfa_record_context_success/skipped/absorbed statistics helpers.
> 
> - Remove unused RPRPattern parameter from
>   nfa_update_absorption_flags().
> 
> 
> Absorbability refactoring (rpr.c):
> 
> - Remove parentDepth parameter from isUnboundedStart() and
>   computeAbsorbabilityRecursive().  Scope boundaries are now
>   determined by element depth comparison instead of an explicit
>   parent depth parameter.
> 
> - Simplify isUnboundedStart(): check simple VAR case first, then
>   GROUP case with a depth-bounded loop instead of a FIN-terminated
>   traversal with multiple break conditions.
> 
> 
> Test changes:
> 
> - Add rpr_nfa.sql: comprehensive NFA runtime test suite covering
>   quantifier boundaries (min/max/exact), alternation priority, nested
>   patterns, frame boundary variations, INITIAL mode (syntax error
>   expected), pathological patterns, context absorption, and FIXME
>   reproduction cases.
> 
> - Add nth_value out-of-frame tests, ReScan/LATERAL test, and
>   nth_value IGNORE NULLS test to rpr.sql.
> 
> - Change selected EXPLAIN test queries in rpr_explain.sql from
>   EXPLAIN (COSTS OFF) to EXPLAIN (ANALYZE, ...) to verify actual
>   NFA execution statistics.
> 
> - Fix stale comments across rpr.sql, rpr_base.sql, and rpr_nfa.sql:
>   remove resolved BUG annotations, update error messages to match
>   actual output, correct optimization result descriptions, and
>   standardize Expected comment placement to after SQL statements.
> 
> 
> Other changes:
> 
> - Run pgindent on RPR source files.  Add /*----------*/ comment
>   guards to protect structured comments from reformatting.
>
> Coverage:
> 
> I ran gcov on the modified lines (diff-only coverage).  The attached
> coverage.zip contains an HTML report.  Summary:
> 
> - 18 files, 124 functions, 2238 modified lines analyzed
> - Overall: 92.1% line coverage (2061/2238)
> - Core files (nodeWindowAgg.c, rpr.c, explain.c, parse_rpr.c):
>   98.0-98.5% each
> - Node serialization (outfuncs.c, readfuncs.c, equalfuncs.c):
>   0% -- these implement RPRPattern serialization for plan caching,
>   but regression tests don't exercise prepared statements with RPR
> - ruleutils.c: 96.3% -- untested lines are the reluctant quantifier
>   display path ({1}?), which is currently rejected at parse time

Thanks for the report.

> The node serialization functions (141 lines, 0% coverage) are the
> largest untested area.  I'm not sure how to trigger these paths
> in the regression test framework.  Any suggestions?

I think we can leave it as it is, until reluctant quantifier is
implemented.

> I'll send a separate email within a few days listing the FIXME
> issues and other unresolved items from the mailing list discussion
> for your review.

Looking forward to reading your email.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Thanks for rebasing to v43!

I noticed the Cirrus CI 32-bit build (test_world_32) failed on three
tests, all due to the same root cause in rpr_explain.out:

  Sort Method: quicksort  Memory: 27kB  (expected, 64-bit)
  Sort Method: quicksort  Memory: 22kB  (actual, 32-bit)

The rpr_explain_filter() function was already normalizing the RPR
Storage memory values, but missed the Sort node's "Memory: NNkB"
which also varies between 32-bit and 64-bit due to pointer/struct
size differences.

The attached incremental patch adds Sort Method memory normalization
to rpr_explain_filter(), using the same approach as the existing
Storage and Maximum Storage filters.

> The node serialization functions (141 lines, 0% coverage) are the
> largest untested area.  I'm not sure how to trigger these paths
> in the regression test framework.  Any suggestions?

I think we can leave it as it is, until reluctant quantifier is
implemented.

Agreed.
 
> I'll send a separate email within a few days listing the FIXME
> issues and other unresolved items from the mailing list discussion
> for your review.

Looking forward to reading your email.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Thanks for rebasing to v43!
> 
> I noticed the Cirrus CI 32-bit build (test_world_32) failed on three
> tests, all due to the same root cause in rpr_explain.out:
> 
>   Sort Method: quicksort  Memory: 27kB  (expected, 64-bit)
>   Sort Method: quicksort  Memory: 22kB  (actual, 32-bit)

I noticed that too.

> The rpr_explain_filter() function was already normalizing the RPR
> Storage memory values, but missed the Sort node's "Memory: NNkB"
> which also varies between 32-bit and 64-bit due to pointer/struct
> size differences.
> 
> The attached incremental patch adds Sort Method memory normalization
> to rpr_explain_filter(), using the same approach as the existing
> Storage and Maximum Storage filters.

Looks good fix to me. Is that Ok for you to not release v44 patch
immediately?  Our patch set is very large and I hesitate to post a new
patch set too offten.

>> The node serialization functions (141 lines, 0% coverage) are the
>> > largest untested area.  I'm not sure how to trigger these paths
>> > in the regression test framework.  Any suggestions?
>>
>> I think we can leave it as it is, until reluctant quantifier is
>> implemented.
>>
> 
> Agreed.

Thanks for agreeing on this.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

As promised, here is a summary of the open items and my proposed
plan for the remaining work.


1. FIXME bugs (to fix within the patch)

These are correctness issues that should be resolved before commit.

[FIXME] Cycle prevention insufficient

  The cycle prevention condition (count == 0 && min == 0) is
  insufficient for patterns like (A*)* where cycles occur at
  count > 0.  Currently relies on implicit duplicate detection
  in nfa_add_state_unique.  An explicit cycle detection logic
  needs to be added.

[FIXME] altPriority -- incomplete lexical ordering

  altPriority tracks only the last ALT choice, so repeated or
  nested ALTs like (A|B)+ cannot correctly implement SQL standard
  lexical ordering.  We may need to maintain an internal classifier
  that tracks the entire ALT path to correctly determine lexical
  priority across repeated alternations.  I'm considering an
  elemIdx-based classifier that records the sequence of element
  positions through ALT branches -- from elemIdx we can derive
  altPriority, varId, and variable name, so it carries more
  information than a varId-based approach, which cannot distinguish
  branches when the same variable appears in multiple ALT
  alternatives.  Since the classifier sequence grows with each
  ALT choice, state forks will need an efficient sharing structure
  (e.g., chunk tree with refcounting) to avoid memory explosion.
  The details still need refinement and verification, so it may
  take some time.


2. Test and documentation (within the patch)

Node serialization 0% coverage

  outfuncs.c/readfuncs.c/equalfuncs.c.  You suggested leaving
  this until reluctant quantifiers are implemented.  This depends
  on the scope decision in section 4 -- if reluctant quantifiers
  are included, we should address coverage then.

Test reorganization

  - Remove tests from rpr.sql that duplicate coverage in rpr_base.sql
    and rpr_nfa.sql
  - Restructure tests around SQL-centric scenarios rather than
    internal implementation details
  - Add real-world scenario tests (e.g., stock V-shape, sessionization)

Documentation review

  - Review and enhance the existing SGML documentation
  - Ensure all implemented features are accurately documented


3. Performance optimizations (separate follow-up patches)

These require thorough analysis and research, but since they are
pure performance improvements with no compatibility impact, they
can be submitted as independent patches afterward.

State pruning optimization

  Active NFA states with lower lexical priority than an already
  confirmed match candidate could be pruned early.  Correctness
  is hard to guarantee for all pattern combinations.  Documented
  as a future research item.

Anchored pattern absorption optimization

  PREFIX elements (e.g., START in "START A+ B") block absorption,
  causing O(n^2) regression for anchored patterns.  A draft design
  exists: track an alternate "shadow" path that skips PREFIX and
  starts at the BODY region, enabling absorption eligibility checks
  while the original path processes PREFIX normally.  This keeps
  concurrent contexts bounded to PREFIX_length + 1, maintaining
  O(n) complexity.  The design needs further refinement before
  implementation.


4. Unimplemented features

The following R020 features are listed in the commit message as not
yet implemented.  Could you let me know which ones you'd like to
include in this patch versus deferring to follow-up patches?

  Requires per-match state tracking infrastructure:
  - MEASURE -- new clause, pattern variable references in target list,
    and per-match aggregate evaluation within the NFA executor
  - CLASSIFIER -- requires per-row variable binding in match state;
    the altPriority fix in section 1 would provide part of this
    infrastructure

  Quantifier/pattern extensions:
  - Reluctant quantifiers (*? etc.) -- parsing exists, runtime error
  - {- -} (exclusion)
  - Empty pattern -- A{0}, () empty pattern.  Should we implement
    A{0} in this patch and defer empty match semantics (unmatch vs
    empty match distinction) to when MEASURE is implemented?
    A{0,0}: standard forbids, Oracle/Snowflake allow.
    Should we follow the standard and reject A{0,0}?
  - PERMUTE -- can be expanded to alternations at parse time

  Navigation/control:
  - SEEK
  - AFTER MATCH SKIP TO / FIRST / LAST
    (only SKIP PAST LAST ROW and SKIP TO NEXT ROW are supported)

  Row pattern functions:
  - SUBSET -- variable grouping for aggregate evaluation
  - FIRST, LAST

  Out of scope:
  - MATCH_RECOGNIZE (R010)


I'd like your thoughts on the following scope questions:
  - Reluctant quantifiers: in scope for this patch?
  - A{0}: proceed with implementation?
  - () empty pattern: also in scope, or defer?
  - A{0,0}: reject per standard, or allow like Oracle/Snowflake?

There are quite a few items listed above, and I'd like to
make sure I'm working on the right things in the right order.
If you could give me some guidance on which items to prioritize
and how you'd like to see these addressed, that would be very
helpful.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> Looks good fix to me. Is that Ok for you to not release v44 patch
> immediately?  Our patch set is very large and I hesitate to post a new
> patch set too offten.

Sure, no problem.  I think it's better to bundle it with the next
round of changes rather than posting a separate v44 just for this fix.
There's no real urgency since the 32-bit issue only affects the
explain test output and doesn't impact functionality.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Anchored pattern absorption optimization
> 
>   PREFIX elements (e.g., START in "START A+ B") block absorption,
>   causing O(n^2) regression for anchored patterns.  A draft design
>   exists: track an alternate "shadow" path that skips PREFIX and
>   starts at the BODY region, enabling absorption eligibility checks
>   while the original path processes PREFIX normally.  This keeps
>   concurrent contexts bounded to PREFIX_length + 1, maintaining
>   O(n) complexity.  The design needs further refinement before
>   implementation.

What do you mean by "Anchored pattern" here? I am asking because R010
(RPR in Window clause) does not allow to use anchors (^ and $) in
PATTERN clause.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,
 
What do you mean by "Anchored pattern" here? I am asking because R010
(RPR in Window clause) does not allow to use anchors (^ and $) in
PATTERN clause.

Good catch - the term "anchored pattern" is indeed confusing here.
You're absolutely right that SQL:2023 R010 does not allow regex anchors
(^ and $) in the PATTERN clause.
In this context, I was using "anchored" to mean "a pattern that starts
with a PREFIX element" - not referring to regex anchors at all. The
example "START A+ B" has a PREFIX element (START) that "anchors" the
pattern matching to begin at a specific point.
To avoid confusion with SQL regex anchors, I suggest we change the
terminology:

"Anchored pattern" → "Pattern with PREFIX" or "PREFIX-led pattern"
"Anchored pattern absorption" → "PREFIX pattern absorption optimization"

The optimization issue remains the same: PREFIX elements block the
absorption mechanism, requiring the "shadow path" approach to maintain
O(n) complexity while processing patterns like "START A+ B".
Does this clarification make sense?

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> What do you mean by "Anchored pattern" here? I am asking because R010
>> (RPR in Window clause) does not allow to use anchors (^ and $) in
>> PATTERN clause.
>>
> 
> Good catch - the term "anchored pattern" is indeed confusing here.
> You're absolutely right that SQL:2023 R010 does not allow regex anchors
> (^ and $) in the PATTERN clause.
> In this context, I was using "anchored" to mean "a pattern that starts
> with a PREFIX element" - not referring to regex anchors at all. The
> example "START A+ B" has a PREFIX element (START) that "anchors" the
> pattern matching to begin at a specific point.

Ok.

> To avoid confusion with SQL regex anchors, I suggest we change the
> terminology:
> 
> "Anchored pattern" → "Pattern with PREFIX" or "PREFIX-led pattern"

I like "Pattern with PREFIX".

> "Anchored pattern absorption" → "PREFIX pattern absorption optimization"

Looks good.

> The optimization issue remains the same: PREFIX elements block the
> absorption mechanism, requiring the "shadow path" approach to maintain
> O(n) complexity while processing patterns like "START A+ B".
> Does this clarification make sense?

Yes!

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> As promised, here is a summary of the open items and my proposed
> plan for the remaining work.

> 1. FIXME bugs (to fix within the patch)
> 2. Test and documentation (within the patch)
> 3. Performance optimizations (separate follow-up patches)

1-3 look good.

> 4. Unimplemented features
> 
> The following R020 features are listed in the commit message as not
> yet implemented.  Could you let me know which ones you'd like to
> include in this patch versus deferring to follow-up patches?
> 
>   Requires per-match state tracking infrastructure:
>   - MEASURE -- new clause, pattern variable references in target list,
>     and per-match aggregate evaluation within the NFA executor
>   - CLASSIFIER -- requires per-row variable binding in match state;
>     the altPriority fix in section 1 would provide part of this
>     infrastructure

I thought we can defere these after the first committed version.  I
think these are too large to add the current patch sets.

>   Quantifier/pattern extensions:
>   - Reluctant quantifiers (*? etc.) -- parsing exists, runtime error

Reluctant quantifiers seem to have important usecases (i.e. the
shortest path). But if implementation is too difficult, we should
defer to after the first version.

>   - {- -} (exclusion)
>   - Empty pattern -- A{0}, () empty pattern.  Should we implement
>     A{0} in this patch and defer empty match semantics (unmatch vs
>     empty match distinction) to when MEASURE is implemented?

Yes, I think so. We should defer.

>     A{0,0}: standard forbids, Oracle/Snowflake allow.
>     Should we follow the standard and reject A{0,0}?

I think we should follow the standard.

>   - PERMUTE -- can be expanded to alternations at parse time

I though we could defer after the first commit. Do you wish to
implemenet it now?

>   Navigation/control:
>   - SEEK
>   - AFTER MATCH SKIP TO / FIRST / LAST
>     (only SKIP PAST LAST ROW and SKIP TO NEXT ROW are supported)

Let's defer them.

>   Row pattern functions:
>   - SUBSET -- variable grouping for aggregate evaluation
>   - FIRST, LAST

Let's defer them.

>   Out of scope:
>   - MATCH_RECOGNIZE (R010)
> 
> 
> I'd like your thoughts on the following scope questions:
>   - Reluctant quantifiers: in scope for this patch?

I found reluctant quantifiers are useful but also I don't want to make
patch sets far bigger. How do yo estimate the difficulty and the size
of the code for reluctant quantifiers?

>   - A{0}: proceed with implementation?
>   - () empty pattern: also in scope, or defer?

I think we can defer.

>   - A{0,0}: reject per standard, or allow like Oracle/Snowflake?

Let's reject per standard.

> There are quite a few items listed above, and I'd like to
> make sure I'm working on the right things in the right order.
> If you could give me some guidance on which items to prioritize
> and how you'd like to see these addressed, that would be very
> helpful.

Here are my thoughts. What do you think?

BTW, while researching the standard, I am wondering whether empty
DEFINE clause is allowed (DEFINE without any variable definition at
all). According to ISO/IEC 9075-2:

 ::=
  [ {   }...]

 ::=
  AS < row pattern definition search condition>
:
:

So, it seems a bare DEFINE clause is not allowed. However searching
goole, it says that the standard allow a bare DEFINE. Maybe it's a
hallucination?
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
From: Henson Choi <assam258(at)gmail(dot)com>
To: Tatsuo Ishii <ishii(at)postgresql(dot)org>
Cc: 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, pgsql-hackers(at)postgresql(dot)org
Subject: Re: Row pattern recognition

Hi Tatsuo,

Thanks for the feedback!  Here are my responses to your questions.


> Reluctant quantifiers seem to have important usecases (i.e. the
> shortest path). But if implementation is too difficult, we should
> defer to after the first version.
>
> How do you estimate the difficulty and the size of the code for
> reluctant quantifiers?

The core difficulty is not in nfa_advance() itself but in matched
state replacement: once a greedy match is confirmed, replacing it
with a shorter reluctant match requires updating matchedState, which
the current structure does not support cleanly.

This is the same design gap that underlies the altPriority FIXME:
both problems require rethinking how the confirmed match state
interacts with the active NFA state list.  I think it is worth
solving them together.

I would prefer to work on the altPriority redesign first and include
reluctant quantifiers and state pruning as part of that work if the
design allows it cleanly.

If I encounter design issues that are difficult to resolve, I will
come back to discuss before proceeding.


> >   - {- -} (exclusion)
> >   - Empty pattern -- A{0}, () empty pattern.  Should we implement
> >     A{0} in this patch and defer empty match semantics (unmatch vs
> >     empty match distinction) to when MEASURE is implemented?
>
> Yes, I think so. We should defer.
>
> >   - A{0}: proceed with implementation?
> >   - () empty pattern: also in scope, or defer?
>
> I think we can defer.

Just to confirm: my understanding is that A{0} is in scope for this
patch, while () empty pattern and empty match semantics are deferred.
Is that correct?  If so, I plan to implement A{0} together with the
cycle detection fix for patterns like (A*)*, since both involve
zero-length iteration handling.


> I though we could defer after the first commit. Do you wish to
> implement it now?
> [regarding PERMUTE]

I am happy to defer PERMUTE.


> 1-3 look good.

I will address test reorganization and documentation review after the bug
fixes and feature implementations are complete.


> BTW, while researching the standard, I am wondering whether empty
> DEFINE clause is allowed (DEFINE without any variable definition at
> all).  [...] So, it seems a bare DEFINE clause is not allowed.
> However searching google, it says that the standard allow a bare
> DEFINE. Maybe it's a hallucination?

That seems right.  DEFINE with no definitions is not allowed; the
parser rejects it syntactically.

On a related note: since the standard treats variables not listed in
DEFINE as implicitly TRUE, should we allow PATTERN without DEFINE?


Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
>> Reluctant quantifiers seem to have important usecases (i.e. the
>> shortest path). But if implementation is too difficult, we should
>> defer to after the first version.
>>
>> How do you estimate the difficulty and the size of the code for
>> reluctant quantifiers?
> 
> The core difficulty is not in nfa_advance() itself but in matched
> state replacement: once a greedy match is confirmed, replacing it
> with a shorter reluctant match requires updating matchedState, which
> the current structure does not support cleanly.
> 
> This is the same design gap that underlies the altPriority FIXME:
> both problems require rethinking how the confirmed match state
> interacts with the active NFA state list.  I think it is worth
> solving them together.

Agreed.

> I would prefer to work on the altPriority redesign first and include
> reluctant quantifiers and state pruning as part of that work if the
> design allows it cleanly.
> 
> If I encounter design issues that are difficult to resolve, I will
> come back to discuss before proceeding.

Sounds like a perfect plan!

>> >   - {- -} (exclusion)
>> >   - Empty pattern -- A{0}, () empty pattern.  Should we implement
>> >     A{0} in this patch and defer empty match semantics (unmatch vs
>> >     empty match distinction) to when MEASURE is implemented?
>>
>> Yes, I think so. We should defer.
>>
>> >   - A{0}: proceed with implementation?
>> >   - () empty pattern: also in scope, or defer?
>>
>> I think we can defer.
> 
> Just to confirm: my understanding is that A{0} is in scope for this
> patch, while () empty pattern and empty match semantics are deferred.
> Is that correct?  If so, I plan to implement A{0} together with the
> cycle detection fix for patterns like (A*)*, since both involve
> zero-length iteration handling.

Thanks for clarification. That's my understanding too.

>> I though we could defer after the first commit. Do you wish to
>> implement it now?
>> [regarding PERMUTE]
> 
> I am happy to defer PERMUTE.

Ok.

>> 1-3 look good.
> 
> I will address test reorganization and documentation review after the bug
> fixes and feature implementations are complete.

I can work on the documentation review part.

>> BTW, while researching the standard, I am wondering whether empty
>> DEFINE clause is allowed (DEFINE without any variable definition at
>> all).  [...] So, it seems a bare DEFINE clause is not allowed.
>> However searching google, it says that the standard allow a bare
>> DEFINE. Maybe it's a hallucination?
> 
> That seems right.  DEFINE with no definitions is not allowed; the
> parser rejects it syntactically.
> 
> On a related note: since the standard treats variables not listed in
> DEFINE as implicitly TRUE, should we allow PATTERN without DEFINE?

ISO/IEC 19075-5 stats that DEFINE is not optional (Table 18 - Row
pattern recognition in windows - syntax summary) So we should not
allow PATTERN without DEFINE.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

> Thanks for the patches! I applied them on top of v42 and rebased
> against current master.  Attached are the v43 patches.

I noticed that current RPR patches allows to use PREV/NEXT anywhere in
an SQL statement where normal functions are allowed. According to the
standard, PREV/NEXT are only allowed in a DEFINE clause. Attached is a
patch to follow the standard regarding PREV/NEXT.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

I noticed that current RPR patches allows to use PREV/NEXT anywhere in
an SQL statement where normal functions are allowed. According to the
standard, PREV/NEXT are only allowed in a DEFINE clause. Attached is a
patch to follow the standard regarding PREV/NEXT.

Thanks for the patch! I applied it to my local branch and all
regression tests pass.

Best regards,
Henson 

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Here are two incremental patches on top of v43 + our previous two.


nocfbot-0003: Fix ALT lexical ordering via DFS early termination

The altPriority FIXME turned out to have a simple solution.  The key
insight is that the NFA state list is already in lexical order from
DFS traversal, so when a state reaches FIN, all remaining states in
the list have worse lexical priority and can be pruned immediately.

This makes the altPriority field unnecessary -- DFS traversal order
itself guarantees correct lexical ordering.  The patch removes
altPriority from RPRNFAState entirely and adds early termination
in nfa_advance(): when a new FIN is reached, the remaining states
are freed and processing stops.

This also implements the state pruning optimization I mentioned
earlier -- it falls out naturally from the same mechanism.

Changes:
- Remove altPriority field from RPRNFAState and all call sites
- Add early termination in nfa_advance() on new FIN arrival
- Simplify nfa_add_matched_state() to unconditional replacement
- Fix outer END count increment for quantified VARs in
  nfa_advance_var()
- Remove FIXME 1 test cases, add test_alt_lexical_order test
- Add EXPLAIN ANALYZE test verifying early termination statistics


nocfbot-0004: Implement reluctant quantifiers

With the DFS early termination infrastructure from nocfbot-0003,
reluctant quantifiers become straightforward: reverse the DFS
traversal order so that shorter matches are explored first, then
apply the same early termination to stop at the shortest match.

Greedy explores enter/loop before skip/exit; reluctant reverses
this to skip/exit before enter/loop.  When the preferred (shorter)
path reaches FIN, the longer path is pruned immediately.

Changes:
- Remove parser error rejecting reluctant quantifier syntax
- Extend tryUnwrapGroup() to propagate reluctant flag when
  unwrapping single-child groups: (A)+? -> A+?
- Add reluctant branching in nfa_advance_begin(),
  nfa_advance_end(), and nfa_advance_var() with per-branch
  early termination
- Add tests in rpr_base.sql, rpr_nfa.sql, and rpr.sql covering
  basic reluctant semantics, quantifier boundaries, interaction
  with greedy quantifiers, and nested/alternation combinations


> I found reluctant quantifiers are useful but also I don't want to make
> patch sets far bigger. How do you estimate the difficulty and the size
> of the code for reluctant quantifiers?

You asked earlier how I estimated the difficulty of reluctant
quantifiers.  It turned out the answer was subtraction, not
addition -- removing altPriority and simplifying the match logic
first made reluctant quantifiers almost trivial to add on top.

Next I plan to work on the remaining FIXME (cycle prevention for
patterns like (A*)*), A{0} implementation, and test reorganization.


Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Here are two incremental patches on top of v43 + our previous two.

I have tried v43 + those patches and it passed the regression test.

> nocfbot-0003: Fix ALT lexical ordering via DFS early termination
> 
> The altPriority FIXME turned out to have a simple solution.  The key
> insight is that the NFA state list is already in lexical order from
> DFS traversal, so when a state reaches FIN, all remaining states in
> the list have worse lexical priority and can be pruned immediately.
> 
> This makes the altPriority field unnecessary -- DFS traversal order
> itself guarantees correct lexical ordering.  The patch removes
> altPriority from RPRNFAState entirely and adds early termination
> in nfa_advance(): when a new FIN is reached, the remaining states
> are freed and processing stops.
> 
> This also implements the state pruning optimization I mentioned
> earlier -- it falls out naturally from the same mechanism.
> 
> Changes:
> - Remove altPriority field from RPRNFAState and all call sites
> - Add early termination in nfa_advance() on new FIN arrival
> - Simplify nfa_add_matched_state() to unconditional replacement
> - Fix outer END count increment for quantified VARs in
>   nfa_advance_var()
> - Remove FIXME 1 test cases, add test_alt_lexical_order test
> - Add EXPLAIN ANALYZE test verifying early termination statistics

Sounds good.

> nocfbot-0004: Implement reluctant quantifiers
> 
> With the DFS early termination infrastructure from nocfbot-0003,
> reluctant quantifiers become straightforward: reverse the DFS
> traversal order so that shorter matches are explored first, then
> apply the same early termination to stop at the shortest match.
> 
> Greedy explores enter/loop before skip/exit; reluctant reverses
> this to skip/exit before enter/loop.  When the preferred (shorter)
> path reaches FIN, the longer path is pruned immediately.
> 
> Changes:
> - Remove parser error rejecting reluctant quantifier syntax
> - Extend tryUnwrapGroup() to propagate reluctant flag when
>   unwrapping single-child groups: (A)+? -> A+?
> - Add reluctant branching in nfa_advance_begin(),
>   nfa_advance_end(), and nfa_advance_var() with per-branch
>   early termination
> - Add tests in rpr_base.sql, rpr_nfa.sql, and rpr.sql covering
>   basic reluctant semantics, quantifier boundaries, interaction
>   with greedy quantifiers, and nested/alternation combinations

This is really good news!

>> I found reluctant quantifiers are useful but also I don't want to make
>> patch sets far bigger. How do you estimate the difficulty and the size
>> of the code for reluctant quantifiers?
> 
> You asked earlier how I estimated the difficulty of reluctant
> quantifiers.  It turned out the answer was subtraction, not
> addition -- removing altPriority and simplifying the match logic
> first made reluctant quantifiers almost trivial to add on top.

Glad to hear that you found simpler solution to implement reluchtant
quantifiers.

> Next I plan to work on the remaining FIXME (cycle prevention for
> patterns like (A*)*), A{0} implementation, and test reorganization.

Ok. Looking forward to the next patches.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Here are six incremental patches on top of v43.

nocfbot-0001 through nocfbot-0004 are the same patches from the
previous round (32-bit test fix, PREV/NEXT restriction, ALT lexical
ordering, reluctant quantifiers).

nocfbot-0005: Detect zero-consumption NFA cycles

Adds a per-element visited bitmap to detect zero-consumption cycles
during DFS epsilon expansion.  Before each state's DFS, the bitmap
is cleared; as nfa_advance_state() recurses through epsilon
transitions, each elemIdx is marked visited.  If the same elemIdx
is reached again within the same DFS, it means an epsilon-only
loop -- the state is freed immediately.

The ad-hoc (count == 0 && min == 0) exit condition in
nfa_advance_end() is removed.  The FIXME test cases are resolved
and renamed to "Zero-Consumption Cycle Detection".

nocfbot-0006: Allow A{0} quantifier

With cycle detection in place, this becomes straightforward.
Lowers the {n} bound minimum from 1 to 0.  A{0} is treated as an
epsilon transition -- the variable is skipped entirely.

Next I plan to work on test reorganization, cross-database result
comparison, and a review pass over the NFA executor.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Here are six incremental patches on top of v43.
> 
> nocfbot-0001 through nocfbot-0004 are the same patches from the
> previous round (32-bit test fix, PREV/NEXT restriction, ALT lexical
> ordering, reluctant quantifiers).
> 
> nocfbot-0005: Detect zero-consumption NFA cycles
> 
> Adds a per-element visited bitmap to detect zero-consumption cycles
> during DFS epsilon expansion.  Before each state's DFS, the bitmap
> is cleared; as nfa_advance_state() recurses through epsilon
> transitions, each elemIdx is marked visited.  If the same elemIdx
> is reached again within the same DFS, it means an epsilon-only
> loop -- the state is freed immediately.
> 
> The ad-hoc (count == 0 && min == 0) exit condition in
> nfa_advance_end() is removed.  The FIXME test cases are resolved
> and renamed to "Zero-Consumption Cycle Detection".
> 
> nocfbot-0006: Allow A{0} quantifier
> 
> With cycle detection in place, this becomes straightforward.
> Lowers the {n} bound minimum from 1 to 0.  A{0} is treated as an
> epsilon transition -- the variable is skipped entirely.

Great!

> Next I plan to work on test reorganization, cross-database result
> comparison, and a review pass over the NFA executor.

Looking forward to seeing next patches.

BTW, in create_windowagg_plan (createplan.c),
around:
/* Build RPR pattern and filter defineClause */

collectPatternVariables, filterDefineClause and buildRPRPattern are
called in a block without any if or any other conditional
statements. This is an unusual codiing style in PostgreSQL.  I suggest
to fix this.  Attached is a proposed patch for this.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index bbc2c7e71f4..e7aafc89700 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -2484,6 +2484,10 @@ create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
 	Oid		   *ordOperators;
 	Oid		   *ordCollations;
 	ListCell   *lc;
+	List	   *defineVariableList = NIL;
+	List	   *filteredDefineClause = NIL;
+	RPRPattern *compiledPattern = NULL;
+
 
 	/*
 	 * Choice of tlist here is motivated by the fact that WindowAgg will be
@@ -2535,50 +2539,45 @@ create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
 	}
 
 	/* Build RPR pattern and filter defineClause */
+	if (wc->rpPattern)
 	{
-		List	   *defineVariableList = NIL;
-		List	   *filteredDefineClause = NIL;
-		RPRPattern *compiledPattern = NULL;
-
-		if (wc->rpPattern)
-		{
-			List	   *patternVars;
+		List	   *patternVars;
 
-			/*
-			 * Filter defineClause to include only variables used in PATTERN.
-			 * This eliminates unnecessary DEFINE evaluations at runtime.
-			 */
-			patternVars = collectPatternVariables(wc->rpPattern);
-			filteredDefineClause = filterDefineClause(wc->defineClause,
-													  patternVars,
-													  &defineVariableList);
-
-			compiledPattern = buildRPRPattern(wc->rpPattern,
-											  defineVariableList,
-											  wc->rpSkipTo,
-											  wc->frameOptions);
-		}
-
-		/* And finally we can make the WindowAgg node */
-		plan = make_windowagg(tlist,
-							  wc,
-							  partNumCols,
-							  partColIdx,
-							  partOperators,
-							  partCollations,
-							  ordNumCols,
-							  ordColIdx,
-							  ordOperators,
-							  ordCollations,
-							  best_path->runCondition,
-							  wc->rpSkipTo,
-							  compiledPattern,
-							  filteredDefineClause,
-							  best_path->qual,
-							  best_path->topwindow,
-							  subplan);
+		/*
+		 * Filter defineClause to include only variables used in PATTERN. This
+		 * eliminates unnecessary DEFINE evaluations at runtime.
+		 */
+		patternVars = collectPatternVariables(wc->rpPattern);
+		filteredDefineClause = filterDefineClause(wc->defineClause,
+												  patternVars,
+												  &defineVariableList);
+
+		/* Compile and optimize RPR patterns */
+		compiledPattern = buildRPRPattern(wc->rpPattern,
+										  defineVariableList,
+										  wc->rpSkipTo,
+										  wc->frameOptions);
 	}
 
+	/* And finally we can make the WindowAgg node */
+	plan = make_windowagg(tlist,
+						  wc,
+						  partNumCols,
+						  partColIdx,
+						  partOperators,
+						  partCollations,
+						  ordNumCols,
+						  ordColIdx,
+						  ordOperators,
+						  ordCollations,
+						  best_path->runCondition,
+						  wc->rpSkipTo,
+						  compiledPattern,
+						  filteredDefineClause,
+						  best_path->qual,
+						  best_path->topwindow,
+						  subplan);
+
 	copy_generic_path_info(&plan->plan, (Path *) best_path);
 
 	return plan;

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

> BTW, in create_windowagg_plan (createplan.c),
> around:
> /* Build RPR pattern and filter defineClause */
>
> collectPatternVariables, filterDefineClause and buildRPRPattern are
> called in a block without any if or any other conditional
> statements. This is an unusual codiing style in PostgreSQL.  I suggest
> to fix this.  Attached is a proposed patch for this.

Good catch, thank you!  I've renumbered your patch as nocfbot-0007
and extended the same cleanup to rpr.c and parse_rpr.c as
nocfbot-0008.

nocfbot-0007: Refactor create_windowagg_plan to remove bare
              variable-scoping block (your patch, renumbered)

nocfbot-0008: Remove bare variable-scoping blocks in RPR code

  Applies the same cleanup to rpr.c and parse_rpr.c, with minor
  pgindent formatting fixes.

I'll keep this coding style point in mind for future code as well.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> BTW, in create_windowagg_plan (createplan.c),
>> around:
>> /* Build RPR pattern and filter defineClause */
>>
>> collectPatternVariables, filterDefineClause and buildRPRPattern are
>> called in a block without any if or any other conditional
>> statements. This is an unusual codiing style in PostgreSQL.  I suggest
>> to fix this.  Attached is a proposed patch for this.
> 
> Good catch, thank you!  I've renumbered your patch as nocfbot-0007
> and extended the same cleanup to rpr.c and parse_rpr.c as
> nocfbot-0008.
> 
> nocfbot-0007: Refactor create_windowagg_plan to remove bare
>               variable-scoping block (your patch, renumbered)
> 
> nocfbot-0008: Remove bare variable-scoping blocks in RPR code
> 
>   Applies the same cleanup to rpr.c and parse_rpr.c, with minor
>   pgindent formatting fixes.
> 
> I'll keep this coding style point in mind for future code as well.

Thank you for quick response!

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

Currently we do not account the cost of RPR while planning.  Attached
is the first attempt to try to estimate the RPR costs. The cost model
is very simple:

expression cost per PATTERN variable * number of input tuples

Any idea to make this estimation better?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c
index 89ca4e08bf1..5a221214b21 100644
--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -103,6 +103,7 @@
 #include "optimizer/placeholder.h"
 #include "optimizer/plancat.h"
 #include "optimizer/restrictinfo.h"
+#include "optimizer/rpr.h"
 #include "parser/parsetree.h"
 #include "utils/lsyscache.h"
 #include "utils/selfuncs.h"
@@ -3227,12 +3228,16 @@ cost_windowagg(Path *path, PlannerInfo *root,
 	 * many rows the window function will fetch, it's hard to do better.  In
 	 * any case, it's a good estimate for all the built-in window functions,
 	 * so we'll just do this for now.
+	 *
+	 * Moreover, if DEFINE/PATTERN clause exists, we charge their expressions
+	 * per tuple.
 	 */
 	foreach(lc, windowFuncs)
 	{
 		WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
 		Cost		wfunccost;
 		QualCost	argcosts;
+		QualCost	defcosts;
 
 		argcosts.startup = argcosts.per_tuple = 0;
 		add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
@@ -3245,6 +3250,37 @@ cost_windowagg(Path *path, PlannerInfo *root,
 		startup_cost += argcosts.startup;
 		wfunccost += argcosts.per_tuple;
 
+		/* also add DEFINE clause expressions' cost to per-input-row costs */
+		if (winclause->rpPattern)
+		{
+			List	   *pattern_vars;	/* list of pattern variable names */
+			ListCell   *lc2;
+
+			pattern_vars = collectPatternVariables(winclause->rpPattern);
+
+			/* iterate according to the pattern variable */
+			foreach(lc2, pattern_vars)
+			{
+				char	   *ptname = strVal((char *) lfirst(lc2));
+
+				/* iterate according to the DEFINE clause */
+				foreach_node(TargetEntry, def, winclause->defineClause)
+				{
+					if (!strcmp(ptname, def->resname))
+					{
+						/*
+						 * varname found. Add DEFINE clause expressions' cost
+						 * to per-input-row costs.
+						 */
+						cost_qual_eval_node(&defcosts, (Node *) def->expr, root);
+						startup_cost += defcosts.startup;
+						wfunccost += defcosts.per_tuple;
+					}
+				}
+			}
+			list_free_deep(pattern_vars);
+		}
+
 		/*
 		 * Add the filter's cost to per-input-row costs.  XXX We should reduce
 		 * input expression costs according to filter selectivity.

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

I recently purchased the ISO/IEC 19075-5:2021 standard document
through my company, and have started cross-referencing it against
the implementation.

> nocfbot-0005: Detect zero-consumption NFA cycles
 
The cycle detection itself is necessary, but I found a behavioral
difference from the standard (Section 7.2.8).

When a group body is nullable (e.g. A? in (A?){2,3}), the visited
bitmap blocks re-entry to the skipped variable, so the END element
never gets a chance to produce an exit state for count < min.
The standard/Perl allows empty iterations to count toward min.

I plan to fix this by adding a compile-time flag on END elements
that indicates the group body can iterate with empty matches.
When the flag is set, nfa_advance_end() will generate the exit
state even when count < min.

> nocfbot-0006: Allow A{0} quantifier
 
After reviewing the standard, I'd like to withdraw this patch.

Section 4.14.1 explicitly requires n > 0 for the {n} quantifier.
While A{0} works correctly as an epsilon transition with the cycle
detection in place, it violates the standard.

Since we aim for standard conformance, I think we should keep the
n >= 1 restriction for {n}.

I'll include this revert in the next patch set.

Best regards,
Choi

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> I recently purchased the ISO/IEC 19075-5:2021 standard document
> through my company, and have started cross-referencing it against
> the implementation.
> 
>> nocfbot-0005: Detect zero-consumption NFA cycles
> 
> 
> The cycle detection itself is necessary, but I found a behavioral
> difference from the standard (Section 7.2.8).
> 
> When a group body is nullable (e.g. A? in (A?){2,3}), the visited
> bitmap blocks re-entry to the skipped variable, so the END element
> never gets a chance to produce an exit state for count < min.
> The standard/Perl allows empty iterations to count toward min.
> 
> I plan to fix this by adding a compile-time flag on END elements
> that indicates the group body can iterate with empty matches.
> When the flag is set, nfa_advance_end() will generate the exit
> state even when count < min.

Ok.

>> nocfbot-0006: Allow A{0} quantifier
>>
> 
> After reviewing the standard, I'd like to withdraw this patch.
> 
> Section 4.14.1 explicitly requires n > 0 for the {n} quantifier.
> While A{0} works correctly as an epsilon transition with the cycle
> detection in place, it violates the standard.
> 
> Since we aim for standard conformance, I think we should keep the
> n >= 1 restriction for {n}.

This is my bad. I didn't realize the standard prohibits A{0} even I
have the standard document.

> I'll include this revert in the next patch set.

Thanks!
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Here are ten incremental patches on top of v43.

nocfbot-0001 through nocfbot-0005 are the same as the previous round
(32-bit test fix, PREV/NEXT restriction, ALT lexical ordering,
reluctant quantifiers, cycle detection).

As discussed, the A{0} patch (old nocfbot-0006) is withdrawn since
Section 4.14.1 requires n > 0.  Your bare-block refactoring patches
are renumbered accordingly:

nocfbot-0006: Refactor create_windowagg_plan to remove bare
              variable-scoping block (your patch, renumbered)

nocfbot-0007: Remove bare variable-scoping blocks in RPR code

Three new patches:

nocfbot-0008: Fix empty-match iteration for nullable group bodies

This is the fix I mentioned for the Section 7.2.8 behavioral
difference.  When a group body is nullable (e.g. A? in (A?){2,3}),
the visited bitmap blocks re-entry to the skipped variable, so the
END element never gets a chance to produce an exit state for
count < min.

The fix adds a compile-time canEmptyLoop flag on END elements.
The fillRPRPattern functions now return whether each sub-pattern
is nullable, and this information propagates up to set the flag
on the enclosing END element.

At runtime, when the flag is set and count < min,
nfa_advance_end() creates a fast-forward exit state that jumps
directly past the group, treating all remaining required
iterations as empty.  This avoids the cycle detection while
still counting empty iterations toward min, matching the
standard and Perl behavior.

nocfbot-0009: Fix use-after-free in NFA alternation and
              optional-VAR routing

Two use-after-free bugs in the NFA advance phase:

1) nfa_advance_alt() reused the original state for the first ALT
   branch, then created copies for subsequent branches.  If
   nfa_advance_state() freed the original (e.g. via
   nfa_add_state_unique() deduplication), subsequent branches
   would copy from freed memory.  Fix: create independent states
   for all branches and free the original.

2) nfa_route_to_elem() created the skip state for optional VARs
   after calling nfa_add_state_unique(), which may free the
   source state.  Fix: create the skip state before add_unique.

nocfbot-0010: Remove redundant conditions and fix comments in
              NFA executor

Cleanup pass over NFA executor functions:

- nfa_states_equal(): removed always-true compareDepth > 0
  guard (RPRDepth is uint8, so depth + 1 is always >= 1)
- nfa_start_context(): removed always-true NULL/count guards
  and bare variable-scoping block
- nfa_advance_var(): removed always-true count > 0 checks in
  three places (nfa_advance_var is only reached after match
  phase where count++ already executed, and max=0 is forbidden)
- nfa_process_row(): fixed missing periods in phase comments

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi hackers,

I'd like to share an internal design document for the NFA executor
in the row pattern recognition (RPR) patch.

The attached guide covers:

- Pattern element structure (RPRPatternElement fields and flags)
- Compilation phases (AST to flat element array)
- Runtime execution model (Match / Absorb / Advance phases)
- Cycle detection for zero-consumption loops
- Empty-loop handling for nullable group bodies
- Reluctant quantifier support
- Absorption optimization for redundant context pruning

The full English text follows below.  All three language
versions are also attached:

  RPR_NFA_Algorithm_Guide.txt     (English)
  RPR_NFA_Algorithm_Guide_KO.txt  (Korean)
  RPR_NFA_Algorithm_Guide_JA.txt  (Japanese)

These are reference documents intended to help reviewers understand
the NFA executor internals.  They are not part of the patch itself.

================================================================================
  PostgreSQL Row Pattern Recognition: Flat-Array Stream NFA Guide
================================================================================

  Target audience: Developers with a basic understanding of the PostgreSQL
                   executor and planner architecture

  Scope: The entire process from PATTERN/DEFINE clause parsing to NFA
         runtime execution

  Related code:
    - src/backend/parser/parse_rpr.c          (parser phase)
    - src/backend/optimizer/plan/rpr.c        (optimizer phase)
    - src/backend/executor/nodeWindowAgg.c    (executor phase)
    - src/include/nodes/plannodes.h           (plan node definitions)
    - src/include/nodes/execnodes.h           (execution state definitions)
    - src/include/optimizer/rpr.h             (types and constants)

================================================================================


What is a Flat-Array Stream NFA?

  The NFA in this implementation is not a traditional state-transition graph
  but a flat array of fixed-size 16-byte elements. At runtime, it processes
  the row stream in a forward-only manner, expanding epsilon transitions
  eagerly without backtracking.

  - Flat-Array: Pattern compiled into a flat array,
                not a graph (Chapter IV)
  - Stream:     Rows consumed sequentially in one direction,
                never revisited (Chapter XII)
  - NFA:        Nondeterministic execution where multiple states
                coexist within a single context (Chapter VI)


Chapter I  Row Pattern Recognition Overview
================================================================================

Row Pattern Recognition (hereafter RPR) is a feature introduced in SQL:2016
that matches regex-based patterns against ordered row sets.

The SQL standard defines two forms:

  Feature R010: MATCH_RECOGNIZE (FROM clause)
    - Dedicated table operator
    - Provides dedicated functions such as MATCH_NUMBER(), CLASSIFIER()
    - Supports ONE ROW PER MATCH / ALL ROWS PER MATCH

  Feature R020: RPR in a window (WINDOW clause)
    - Integrated into the existing window function framework
    - Supports ALL ROWS PER MATCH only
    - No MATCH_NUMBER()

This implementation targets Feature R020.

The basic syntax is as follows:

  SELECT ...
  OVER (
    PARTITION BY ...
    ORDER BY ...
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    [INITIAL | SEEK]   -- SEEK is defined in the standard but not implemented
    AFTER MATCH SKIP TO NEXT ROW | SKIP PAST LAST ROW
    PATTERN ( <regex> )
    DEFINE <variable> AS <condition>, ...
  )

The PATTERN clause is a regular expression over row pattern variables.
The DEFINE clause specifies boolean conditions that determine whether each
variable evaluates to true for the current row.

Example:

  PATTERN (A+ B)
  DEFINE A AS price > PREV(price),
         B AS price < PREV(price)

This pattern matches "a span where prices rise consecutively then drop."


Chapter II  Overall Processing Pipeline
================================================================================

RPR processing is divided into three phases:

  +------------------------------------------------------------+
  |  1. Parsing (Parser)                                       |
  |     SQL text -> PATTERN AST + DEFINE expression tree       |
  |                                                            |
  |  2. Compilation (Optimizer/Planner)                        |
  |     PATTERN AST -> optimization -> flat NFA element array  |
  |                                                            |
  |  3. Execution (Executor)                                   |
  |     Row-by-row matching via NFA simulation                 |
  +------------------------------------------------------------+

Each phase uses independent data structures, and the interfaces between
phases are well-defined:

  Parser -> Planner:    WindowClause.rpPattern (RPRPatternNode tree)
                        WindowClause.defineClause (TargetEntry list)

  Planner -> Executor:  WindowAgg.rpPattern (RPRPattern struct)
                        WindowAgg.defineClause (TargetEntry list)


Chapter III  Parsing Phase
================================================================================

III-1. Entry Point

  transformWindowDefinitions() (parse_clause.c)
    +-- transformRPR() (parse_rpr.c)

transformRPR() is invoked when RPCommonSyntax is present and performs the
following:

  (1) Frame option validation
      - Only ROWS is allowed (RANGE, GROUPS are not)
      - The start boundary must be CURRENT ROW
      - EXCLUDE option is not allowed

  (2) Transcription to WindowClause
      - Copies rpPattern, rpSkipTo, initial fields

  (3) DEFINE clause transformation (transformDefineClause)

III-2. PATTERN AST

The parser transforms the PATTERN clause into an RPRPatternNode tree.
Each node has one of the following four types:

  RPR_PATTERN_VAR    Variable reference. Name stored in varName field.
  RPR_PATTERN_SEQ    Concatenation. Children node list in children.
  RPR_PATTERN_ALT    Alternation. Branch node list in children.
  RPR_PATTERN_GROUP  Group (parentheses). Body node list in children.

All nodes have min/max fields to express quantifiers:

  A       -> VAR(A, min=1, max=1)
  A+      -> VAR(A, min=1, max=INF)
  A*      -> VAR(A, min=0, max=INF)
  A?      -> VAR(A, min=0, max=1)
  A{3,5}  -> VAR(A, min=3, max=5)

If the reluctant field is not -1, the quantifier is reluctant (non-greedy).

Example: PATTERN ((A+ B) | C*)

  ALT
  +-- SEQ
  |   +-- VAR(A, 1, INF)
  |   +-- VAR(B, 1, 1)
  +-- VAR(C, 0, INF)

III-3. DEFINE Clause Transformation

transformDefineClause() processes each DEFINE variable as follows:

  (1) Checks for duplicate variable names
  (2) Transforms the expression into a standard SQL expression
  (3) Coerces to Boolean type (coerce_to_boolean)
  (4) Wraps in a TargetEntry with the variable name set in resname

Variables that are used in PATTERN but not defined in DEFINE are implicitly
evaluated as TRUE (matching all rows).


Chapter IV  Compilation Phase
================================================================================

IV-1. Entry Point

  create_windowagg_plan() (createplan.c)
    +-- collectPatternVariables()   Collect variable names
    +-- filterDefineClause()        Remove unused DEFINE entries
    +-- buildRPRPattern()           NFA compilation (6 phases)

IV-2. The 6 Phases of buildRPRPattern()

  Phase 1: AST optimization (optimizeRPRPattern)
  Phase 2: Statistics collection (scanRPRPattern)
  Phase 3: Memory allocation (allocateRPRPattern)
  Phase 4: NFA element fill (fillRPRPattern)
  Phase 5: Finalization (finalizeRPRPattern)
  Phase 6: Absorbability analysis (computeAbsorbability)

IV-3. Phase 1: AST Optimization

After copying the parser-generated AST, the following optimizations are
applied:

  (a) SEQ flattening: Unwrap nested SEQ nodes
      SEQ(A, SEQ(B, C)) -> SEQ(A, B, C)

  (b) Consecutive variable merging: Merge consecutive occurrences of the
      same variable into a single quantifier
      A A -> A{2}
      A{2,3} A{1,2} -> A{3,5}

  (c) Consecutive group merging: Merge repeated identical groups
      (A B)+ (A B)+ -> (A B){2,INF}

  (d) Consecutive ALT merging: Merge repeated identical ALT nodes
      (A | B) (A | B) (A | B) -> (A | B){3}

  (e) Prefix/suffix absorption: Absorb identical sequences before/after
      a group
      A B (A B)+ -> (A B){2,INF}

  (f) ALT flattening and deduplication
      (A | (B | C)) -> (A | B | C)
      (A | B | A) -> (A | B)

  (g) Quantifier multiplication: Collapse nested quantifiers when safe
      (A+)+ -> A+
      (A{2,3}){5} -> A{10,15}

  (h) Single-child unwrap
      SEQ(A) -> A,  (A){1,1} -> A

IV-4. Phase 4: NFA Element Array Generation

Transforms the optimized AST into a flat array of RPRPatternElement.
This is the core data structure used for NFA simulation at runtime.

RPRPatternElement struct (16 bytes):

  Field      Size     Description
  ---------------------------------------------------------
  varId      1B      Variable ID (0-251) or control code (252-255)
  depth      1B      Group nesting depth
  flags      1B      Bit flags (see below)
  reserved   1B      Padding
  min        4B      Quantifier lower bound
  max        4B      Quantifier upper bound
  next       2B      Next element index (sequential flow)
  jump       2B      Branch target index (for ALT/GROUP)

Control codes:

  RPR_VARID_BEGIN (252)  Group start marker
  RPR_VARID_END   (253)  Group end marker
  RPR_VARID_ALT   (254)  Alternation start marker
  RPR_VARID_FIN   (255)  Pattern completion marker

Element flags (1 byte, bitmask):

  Bit  Constant                    Set on        Description
  --------------------------------------------------------------------------
  0x01 RPR_ELEM_RELUCTANT          VAR, BEGIN,   Non-greedy quantifier.
                                   END           Prefers shorter match: try
                                                 exit-loop first, then repeat.
                                                 Set on VAR for simple (A+?),
                                                 on BEGIN+END for group ((...)+?)

  0x02 RPR_ELEM_EMPTY_LOOP         END           Group body can produce empty
                                                 match (all children nullable).
                                                 Creates a fast-forward exit clone
                                                 alongside the normal loop-back so
                                                 cycle detection doesn't kill
                                                 legitimate matches. (IV-4b)

  0x04 RPR_ELEM_ABSORBABLE_BRANCH  VAR, BEGIN,   Element lies within an
                                   END, ALT      absorbable region. Used at
                                                 runtime to track whether the
                                                 current NFA state is in an
                                                 absorbable context.

  0x08 RPR_ELEM_ABSORBABLE         VAR, END      Absorption judgment point.
                                                 WHERE to compare consecutive
                                                 iterations for absorption.
                                                 - Simple unbounded VAR (A+):
                                                   set on the VAR itself
                                                 - Unbounded GROUP ((A B)+):
                                                   set on the END element only

  Accessor macros:
    RPRElemIsReluctant(e)        (e)->flags & 0x01
    RPRElemCanEmptyLoop(e)       (e)->flags & 0x02
    RPRElemIsAbsorbableBranch(e) (e)->flags & 0x04
    RPRElemIsAbsorbable(e)       (e)->flags & 0x08

Example: PATTERN (A+ B | C)

  AST: ALT(SEQ(VAR(A,1,INF), VAR(B,1,1)), VAR(C,1,1))

  Compilation result:

  idx  varId  depth  min  max  next  jump  Description
  ---------------------------------------------------
   0   ALT    0      1    1    1     -1    Alternation start
   1   A(0)   1      1    INF  2     3     Branch 1: A+
   2   B(1)   1      1    1    4     -1    Branch 1: B -> FIN
   3   C(2)   1      1    1    4     -1    Branch 2: C -> FIN
   4   FIN    0      1    1    -1    -1    Pattern completion

  - idx 0: ALT marker. next(=1) is the start of the first branch
  - idx 1: Variable A. next(=2) is B, jump(=3) is the start of the second branch
  - idx 2: Variable B. next(=4) is FIN
  - idx 3: Variable C. next(=4) is FIN
  - idx 4: FIN marker. Match completion signal

Roles of next and jump:

  - next: The next element to move to "after consuming" the current element.
          For VAR, the next position after a successful match.
          For BEGIN/END, the next position inside/outside the group.

  - jump: The element to "skip to."
          In ALT, a jump from one branch to the next branch.
          In BEGIN, a skip path to END+1 (for groups with min=0).
          In END, a loop-back to the start of the group body.

Example: PATTERN ((A B)+)

  idx  varId    depth  min  max  next  jump  Description
  ---------------------------------------------------
   0   BEGIN    0      1    INF  1     4     Group start
   1   A(0)     1      1    1    2     -1    A
   2   B(1)     1      1    1    3     -1    B
   3   END      0      1    INF  4     1     Group end
   4   FIN      0      1    1    -1    -1    Pattern completion

  - idx 0: BEGIN. next(=1) enters the group body.
           jump(=4) skips to after END = FIN (used when min=0).
  - idx 3: END. next(=4) exits the group.
           jump(=1) loops back to the start of the group body.

IV-4a. Reluctant Flag (RPR_ELEM_RELUCTANT)

The reluctant flag is set during Phase 4 (fillRPRPattern) when the AST node
has a non-negative reluctant field (reluctant >= 0). It reverses the priority
of quantifier expansion at runtime:

  Greedy (default):  try loop-back first, then exit  (prefer longer match)
  Reluctant:         try exit first, then loop-back   (prefer shorter match)

The flag is set on all elements that carry the quantifier:

  Simple VAR (A+?):     RPR_ELEM_RELUCTANT on the VAR element
  Group ((...)+?):      RPR_ELEM_RELUCTANT on BEGIN and END elements

At runtime (nfa_advance), the flag controls DFS exploration order:

  VAR with quantifier:
    Greedy:    primary path = next (continue), clone = jump (skip)
    Reluctant: primary path = jump (skip), clone = next (continue)

  END element:
    Greedy:    primary path = jump (loop-back), clone = next (exit)
    Reluctant: primary path = next (exit), clone = jump (loop-back)

  BEGIN with min=0:
    Greedy:    primary path = next (enter group), clone = jump (skip)
    Reluctant: primary path = jump (skip), clone = next (enter group)

The absorption optimization requires greedy quantifiers. Reluctant
quantifiers are excluded from absorbability analysis (see IV-5).

IV-4b. Empty Loop Flag (RPR_ELEM_EMPTY_LOOP)

The empty-loop flag is set during Phase 4 (fillRPRPatternGroup) on the END
element when the group body is nullable -- i.e., every path through the
body can match zero rows (all children are nullable).

Example patterns that trigger this flag:

  (A?)*    A is nullable (min=0), so group body is nullable -> END gets flag
  (A? B?)+ Both children nullable -> body nullable -> END gets flag
  (A | B*) B* is nullable, making the ALT nullable -> END gets flag

The flag works in conjunction with the zero-consumption cycle detection
(elemIdx visited bitmap). Without this flag, cycle detection alone would
cause legitimate matches to fail.

Problem example: (A*){2,3}
  - Iteration 1: A* consumes all available rows -> count=1, END reached
  - Loop-back for iteration 2: A* matches zero rows -> END reached again
  - Cycle detection sees the same elemIdx on the same row -> state killed
  - count never reaches min(2) -> match fails (incorrect)

With the RPR_ELEM_EMPTY_LOOP flag, nfa_advance_end creates two paths:
the normal loop-back (which cycle detection will eventually kill) and
a fast-forward exit clone that bypasses the loop entirely.
(See IX-4(c) for detailed runtime behavior.)
    - Zero-consumption is impossible since body is not nullable

IV-5. Absorbability Analysis (RPR_ELEM_ABSORBABLE)

Context absorption is an optimization technique that reduces O(n^2) to O(n).
(Runtime behavior is described in Chapter VIII.)

This phase determines whether the pattern has a structure suitable for the
absorption optimization and sets flags on the relevant elements:

  RPR_ELEM_ABSORBABLE         Absorption comparison point
  RPR_ELEM_ABSORBABLE_BRANCH  Element within an absorbable region

Eligibility conditions:

  (1) SKIP PAST LAST ROW (not NEXT ROW)
  (2) Frame end is UNBOUNDED FOLLOWING

Structural conditions (isUnboundedStart + computeAbsorbabilityRecursive):

  Case 1: Simple VAR+ (e.g., A+)
          -> ABSORBABLE | ABSORBABLE_BRANCH set on the VAR
  Case 2: GROUP+ whose body consists only of {1,1} VARs (e.g., (A B)+)
          -> ABSORBABLE_BRANCH on children,
            ABSORBABLE | ABSORBABLE_BRANCH on END
  Case 3: GROUP+ whose body starts with VAR+ (e.g., (A+ B)+)
          -> Recurses from BEGIN into the body, applying Case 1.
            ABSORBABLE | ABSORBABLE_BRANCH set on A.
            B and END get no flags -> absorption stops once past A.

Absorbability is determined per-element, not per-pattern.
Absorption comparison is performed only when a state resides at an
element with the RPR_ELEM_ABSORBABLE flag. Once a state leaves the
flagged region, absorption is permanently disabled for that state.

Through this mechanism, the runtime guarantees monotonicity:
"a context that started earlier always subsumes a context that
started later."


Chapter V  NFA Runtime Data Structures
================================================================================

V-1. RPRNFAState -- NFA State

A single NFA state represents "how far the pattern has progressed."

  Field         Description
  ---------------------------------------------------------
  elemIdx       Index of the current pattern element
  counts[]      Repetition count per group depth
  isAbsorbable  Whether the state is in an absorbable region
  next          Next state in the linked list

The size of the counts array is (maxDepth + 1), allocated as a flexible
array member at the end of the struct.

Example: In PATTERN ((A B)+ C), a state waiting for B in the 3rd iteration

  Element array: [0:BEGIN(d0) 1:A(d1) 2:B(d1) 3:END(d0) 4:C(d0) 5:FIN]

  elemIdx = 2 (B, depth 1)
  counts[0] = 2 (depth 0: depth of END. Group completed 2 iterations)
  counts[1] = 1 (depth 1: depth of B. A matched in current iteration)

  Counts are indexed by depth, not by elemIdx.
  counts[0] is incremented when passing through END(depth 0),
  and the group repetition count is preserved even when
  the state is at B(depth 1).

Definition of two states being "equal":

  Two states are equal if they have the same elemIdx and the same counts
  up to the depth of that element.
  nfa_states_equal() compares counts[0..elem->depth] using memcmp.
  Only counts at or below the depth of the current element are meaningful.

V-2. RPRNFAContext -- Matching Context

A single context represents "a matching attempt started from a specific
start row."

  Field                 Description
  ---------------------------------------------------------
  states                Linked list of active NFA states
  matchStartRow         Row number where matching started
  matchEndRow           Row number where matching completed (-1 if incomplete)
  lastProcessedRow      Last row processed
  matchedState          State that reached FIN (for greedy fallback)
  hasAbsorbableState    Whether this context can absorb other contexts
  allStatesAbsorbable   Whether this context can be absorbed
  next, prev            Doubly-linked list

Since the NFA is nondeterministic, multiple states can coexist
simultaneously within a single context.

Example: In PATTERN (A | B) C, if the first row matches both A and B,
two states coexist within the context:

  State 1: elemIdx=3 (waiting for C, via branch A)
  State 2: elemIdx=3 (waiting for C, via branch B)

In this case, since the (elemIdx, counts) of the two states are equal,
nfa_add_state_unique() retains only State 1 (branch A), which was
added first.
Because DFS processes the first branch of ALT first, the state via A
is registered first, and the state via B is discarded as a duplicate.
This is the preferment guarantee.

V-3. RPR Fields of WindowAggState

  nfaContext / nfaContextTail   Doubly-linked list of active contexts
  nfaContextFree                Reuse pool for contexts
  nfaStateFree                  Reuse pool for states
  nfaVarMatched                 Per-row cache: varMatched[varId]
  nfaVisitedElems               Bitmap for cycle detection
  nfaStateSize                  Precomputed size of RPRNFAState

Memory management:

  States and contexts are managed through their own free lists.
  Instead of palloc, they are obtained from the reuse pool, and
  returned to the pool upon deallocation.
  This reduces the overhead of frequent allocation/deallocation.


Chapter VI  NFA Execution: 3-Phase Model
================================================================================

VI-1. Entry Point and Overall Flow

When the window function processes each row, row_is_in_reduced_frame()
is called. This function determines whether the current row belongs to
a matched frame, and if necessary, calls update_reduced_frame() to
drive the NFA.

Flow of update_reduced_frame():

  (1) Find or create a context for the target row
  (2) Enter the row processing loop
  (3) After the loop ends, record the result in reduced_frame_map

Pseudocode of the row processing loop:

  targetCtx = nfa_get_head_context(pos)
  if targetCtx == NULL:
      targetCtx = nfa_start_context(pos)

  for currentPos = startPos ...
      if not nfa_evaluate_row(currentPos):  -- row does not exist
          nfa_finalize_all_contexts()       -- finalize all contexts
          break

      nfa_process_row(currentPos)           -- 3-phase processing
      nfa_start_context(currentPos + 1)     -- pre-create next start point
      nfa_cleanup_dead_contexts()           -- remove dead contexts

      if targetCtx->states == NULL:         -- target context exhausted
          break

Key point: Processing a single row may require processing multiple rows
ahead. Due to the nature of window functions, determining the frame for
row N requires looking at rows beyond N.

VI-2. Context Creation: nfa_start_context()

Creates a new context and performs the initial advance.

  (1) Allocate context via nfa_context_alloc()
  (2) Set matchStartRow = pos
  (3) Create initial state: elemIdx=0 (first pattern element), counts=all zero
  (4) Call nfa_advance(initialAdvance=true)

The initial advance expands epsilon transitions at the beginning of
the pattern. For example, the initial advance for PATTERN ((A | B) C):

  Start: elemIdx=0 (ALT)
    -> Expand ALT branches
      -> elemIdx=1 (A) -- VAR, so add state; stop here
      -> elemIdx=2 (B) -- VAR, so add state; stop here

  Result: Two states in the context {waiting for A, waiting for B}

During the initial advance, reaching FIN is not recorded as a match.
This is to prevent empty matches (zero-length matches).

VI-3. Row Evaluation: nfa_evaluate_row()

Evaluates all variable conditions in the DEFINE clause at once for
the current row.

  for each defineClause[i]:
      result = ExecEvalExpr(defineClause[i])
      varMatched[i] = (not null and true)

To support row navigation operators such as PREV() and NEXT(),
the previous row, current row, and next row are set in separate slots:

  ecxt_scantuple  = previous row (for PREV reference)
  ecxt_outertuple = current row  (default reference)
  ecxt_innertuple = next row     (for NEXT reference)

The varMatched array is referenced later in Phase 1 (Match).

VI-4. nfa_process_row(): 3-Phase Processing

NFA processing for a single row is divided into three phases:

  +--------------------------------------------+
  |  Phase 1: MATCH (convergence)              |
  |  Compare the current row against each VAR  |
  |  state. Remove states that fail to match.  |
  |                                            |
  |  Phase 2: ABSORB (absorption)              |
  |  Merge duplicate contexts to prevent       |
  |  state explosion.                          |
  |                                            |
  |  Phase 3: ADVANCE (expansion)              |
  |  Expand epsilon transitions to prepare     |
  |  for the next row.                         |
  +--------------------------------------------+

This ordering is important:

  - Match executes first to "consume the current row."
  - Absorb executes immediately after Match, when states have been updated.
  - Advance executes last to prepare "states waiting for the next row."


Chapter VII  Phase 1: Match
================================================================================

nfa_match() iterates through each state in the context:

  (1) Check whether the state's elemIdx is a VAR element
  (2) Compare against the current row using nfa_eval_var_match()
  (3) Match success: increment repetition count, retain state
  (4) Match failure: remove state

Match determination (nfa_eval_var_match):

  If varId is within the range of defineVariableList:
      Use the value of varMatched[varId]

  If varId exceeds the range (variable not defined in DEFINE):
      Unconditionally true (matches all rows)

Immediate advance for simple VARs:

  For a VAR with min=1, max=1 where the next element is END,
  the Match phase processes through END immediately.
  This is necessary for accurate state comparison in Phase 2 (Absorb).

  Example: In PATTERN ((A B)+), when A matches, it immediately advances
  to B, and when B matches, it immediately advances through END to
  complete the group count. This enables absorption comparison with
  other contexts.


Chapter VIII  Phase 2: Absorb (Context Absorption)
================================================================================

VIII-1. Problem

In the current implementation, a new context is started for each row processed.
Applying PATTERN (A+) to 10 rows produces 10 contexts,
each of which tracks state independently.

If there are N rows, the total number of states becomes O(N^2):

  Context 1 (started at row 1): can match A up to N times
  Context 2 (started at row 2): can match A up to N-1 times
  ...
  Context N (started at row N): can match A 1 time

VIII-2. Solution: Context Absorption

Key observation: a context started earlier contains
all matches of a later-started context (monotonicity principle).

If Context 1 started at row 1 and matched A 5 times,
the state where Context 2 (started at row 2) matched A 4 times
is already contained within Context 1.

Therefore Context 2 can be "absorbed" into Context 1.

VIII-3. Absorption Conditions

  (1) The pattern is marked as isAbsorbable (see IV-5)
  (2) allStatesAbsorbable of the target context is true
  (3) An earlier context "covers" all states of the target

Cover condition (nfa_states_covered):

  A state with the same elemIdx exists in the earlier context,
  and the count at that depth is greater than or equal -- then it is covered.

VIII-4. Dual-Flag Design

Two boolean flags make the absorption decision efficient:

  hasAbsorbableState (monotonic: only true->false transition possible)
    "Does this context have the ability to absorb other contexts?"
    true if at least one absorbable state exists.
    Transitions to false when states are removed leaving no absorbable states.
    Once false, it never becomes true again.

  allStatesAbsorbable (dynamic: can fluctuate)
    "Can this context be absorbed?"
    true if all states are in an absorbable region.
    Becomes false when a non-absorbable state is added; reverts to true when it is removed.

VIII-5. Absorption Order

nfa_absorb_contexts() traverses from tail (newest) to head (oldest).

  for ctx = tail to head:
      if ctx.allStatesAbsorbable:
          for older = ctx.prev to head:
              if older.hasAbsorbableState:
                  if nfa_states_covered(older, ctx):
                      free(ctx)  -- absorbed
                      break

Since inspection starts from the newest context, the most recently started
(= having the shortest match) context is absorbed first.


Chapter IX  Phase 3: Advance (Epsilon Transition Expansion)
================================================================================

IX-1. Overview

nfa_advance() expands epsilon transitions from each state after Match,
generating "new states waiting for the next row."

An epsilon transition is a transition that moves without consuming a row:

  - ALT: branch to each alternative
  - BEGIN: enter group (or skip if min=0)
  - END: loop-back within group (or exit when condition is met)
  - FIN: record match completion
  - VAR loop/exit: repeat/exit according to the quantifier

Expansion stops upon reaching a VAR element, and the state is added.
This is because VAR is the element that "will consume the next row."

IX-2. Processing Order: DFS and Preferment

advance processes states in lexicographic order,
performing Depth-First Search (DFS) on each state.

This DFS order is what guarantees the SQL standard's "preferment":

  The branch that appears first in the PATTERN text takes precedence.

Example: PATTERN (A | B) C

  The first branch A of the ALT takes precedence over the second branch B.
  When both A and B can match, the match via A is selected.

nfa_add_state_unique() prevents duplicate addition of the same state,
so the state added first (= from the preferred branch) is retained.

IX-3. Routing Function: nfa_route_to_elem()

All inter-element transitions in the advance phase go through nfa_route_to_elem().
This function branches its behavior based on the type of the next element:

  If the next element is VAR:
    (1) Add the state to the context (nfa_add_state_unique)
    (2) If the VAR has min=0, also add a skip path (recurse via next)
    -> Expansion stops here (VAR is the element that "will consume the next row")

  If the next element is non-VAR (ALT, BEGIN, END, FIN):
    -> Recursively call nfa_advance_state() to continue expansion

With this structure, advance recursively follows epsilon transitions
until reaching a VAR, consistently stopping only at VAR elements.

IX-4. Per-Element advance Behavior

(a) ALT (nfa_advance_alt)

  Upon encountering an ALT element, all branches are expanded in order.
  The first element of each branch is connected via a jump pointer.

  idx=0 (ALT) -> branch 1 start (next) -> branch 2 start (jump) -> ...

  nfa_advance_state() is recursively called for each branch.

(b) BEGIN (nfa_advance_begin)

  Handles group entry.
  jump points to the element after END (= first element outside the group).

  Greedy (default):
    (1) Enter the group body (move via next, reset the count at that depth)
    (2) If min=0, also add a group skip path (move via jump)

  Reluctant:
    Order reversed -- skip path first, group entry second.
    If the skip path reaches FIN, the group entry path is not generated
    (shortest match preferred).

(c) END (nfa_advance_end)

  Handles group termination. This is the core of the repetition logic.

  Let count be the count at the current depth:

  count < min:
    Loop-back (move via jump, repeat the group body)

    If the RPR_ELEM_EMPTY_LOOP flag is set:
      In addition to loop-back, also add a fast-forward exit path.
      This is because the body may produce an empty match, causing count
      to never reach min. fast-forward resets counts[depth] to 0
      and exits via next (treating the remaining required iterations
      as empty matches).

  min <= count < max:
    Greedy: loop-back first, exit second
    Reluctant: exit first, loop-back second
              If the exit path reaches FIN, loop-back is omitted.

  count >= max:
    Unconditional exit (move via next)

  On exit: reset counts[depth] = 0, and if the next element is an outer END,
  increment the count at the outer depth.

(d) VAR (nfa_advance_var)

  Handles repeat/exit for a VAR element with a quantifier.

  Let count be the count at the current depth:

  count < min:
    Unconditional loop (stay at the same elemIdx, wait for the next row)

  min <= count < max:
    Greedy: loop first, exit (next) second
    Reluctant: exit first, loop second
              If the exit path reaches FIN, loop is omitted.

  count >= max:
    Unconditional exit (move via next)

  On exit: reset counts[depth] = 0.

(e) FIN

  Match success. The current state is moved to matchedState for recording,
  and matchEndRow is set to the current row.

  Upon reaching FIN, all remaining unprocessed states are removed
  (early termination). By DFS order, the path that reached FIN first
  has the highest preferment, so the rest are inferior paths.
  This is the core mechanism that guarantees preferment.

  In SKIP PAST LAST ROW mode, upon reaching FIN, subsequent contexts
  that started within the match range are immediately pruned.

IX-5. State Deduplication: nfa_add_state_unique()

When adding a new state to a context, it is compared against existing states;
if an identical state already exists, it is not added.

Comparison criteria: elemIdx + counts[0..elem->depth] (see V-1)

This deduplication is the core mechanism that suppresses NFA state explosion.
Because DFS order causes preferred-branch states to be added first,
identical states from lower-priority branches are automatically discarded.

IX-6. Cycle Detection: nfaVisitedElems

When a group body can produce an empty match (zero consumption),
looping back from END may cause an infinite loop.

Example: PATTERN ((A?)*)

  A? has min=0, so it can pass through without matching.
  If the outer group repeats: BEGIN -> A? skip -> END -> BEGIN -> ...

To prevent this:

  (1) At compile time: set the RPR_ELEM_EMPTY_LOOP flag on the END
      of groups whose body is nullable.
      The runtime effect of this flag is described in IX-4(c):
      when count < min, a fast-forward exit path is added,
      resolving the deadlock where count cannot increase due to empty matches.

  (2) At runtime: initialize the nfaVisitedElems bitmap immediately before
      DFS expansion of each state within advance (once per state).
      During DFS, set the corresponding elemIdx bit when visiting each element.
      If a previously visited elemIdx is revisited, that path is terminated.

  Note: the bitmap tracks only elemIdx and does not consider counts.
  Therefore, legitimate revisits to the same elemIdx but with different counts
  may also be blocked. This only occurs when the group body is nullable
  (all paths can match empty), causing END -> loop-back -> skip -> END
  within a single DFS. In such cases the END element has the
  RPR_ELEM_EMPTY_LOOP flag, so the fast-forward exit (IX-4(c)) provides
  an alternative path that bypasses the cycle.


Chapter X  Match Result Processing
================================================================================

X-1. Reduced Frame Map

RPR match results are recorded in a byte array called reduced_frame_map.
One byte is allocated per row, and the value is one of the following:

  RF_NOT_DETERMINED (0)  Not yet processed
  RF_FRAME_HEAD     (1)  Start row of the match
  RF_SKIPPED        (2)  Interior row of the match (skipped in frame)
  RF_UNMATCHED      (3)  Match failure

The window function references this map to determine frame inclusion for each row.

X-2. AFTER MATCH SKIP

Determines the starting point for the next match attempt after a successful match:

  SKIP TO NEXT ROW:
    New match attempt begins from the row after the match start row.
    Overlapping matches are possible.

  SKIP PAST LAST ROW:
    New match attempt begins from the row after the match end row.
    Only non-overlapping matches are possible.

X-3. INITIAL vs SEEK

  Standard definition (section 6.12):
  INITIAL: "is used to look for a match whose first row is R."
  SEEK:    "is used to permit a search for the first match anywhere
           from R through the end of the full window frame."
  In either case, if there is no match, the reduced window frame is empty.
  The default is INITIAL.

  Current implementation:
  SEEK is not supported (the parser raises an error).
  Only INITIAL is supported, searching only for matches starting at each
  row position pos.


Chapter XI  Worked Example: Full Execution Trace
================================================================================

XI-1. Query

  SELECT company, tdate, price,
         first_value(price) OVER w AS start_price,
         last_value(price) OVER w AS end_price
  FROM stock
  WINDOW w AS (
    PARTITION BY company
    ORDER BY tdate
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    AFTER MATCH SKIP PAST LAST ROW
    PATTERN (A+ B)
    DEFINE A AS price > PREV(price),
           B AS price < PREV(price)
  );

XI-2. Data

  Row#    tdate       price
  --------------------------
  0       2024-01-01  100
  1       2024-01-02  110
  2       2024-01-03  120
  3       2024-01-04  115
  4       2024-01-05  130

XI-3. Compilation Result

  PATTERN (A+ B) -> unchanged after optimization

  idx  varId  depth  min  max  next  jump
  ------------------------------------------
   0   A(0)   0      1    INF  1     -1     A+
   1   B(1)   0      1    1    2     -1     B
   2   FIN    0      1    1    -1    -1

  DEFINE: A -> "price > PREV(price)", B -> "price < PREV(price)"
  isAbsorbable = true (A+ is a simple unbounded VAR)

XI-4. Execution Trace

--- Row 0 (price=100) ---

  update_reduced_frame(0) called.

  Context C0 created (matchStartRow=0).
  Initial advance: elemIdx=0(A) -> VAR, so state is added.
  C0.states = [{elemIdx=0, counts=[0]}]

  nfa_evaluate_row(0):
    A: price(100) > PREV(price) -> no PREV -> false
    B: price(100) < PREV(price) -> no PREV -> false
    varMatched = [false, false]

  nfa_process_row(0):
    Phase 1 (Match): A(0) state vs varMatched[0]=false -> state removed
    C0.states = [] (empty)

    Phase 2 (Absorb): skipped (no states)
    Phase 3 (Advance): skipped (no states)

  C0.states is empty, so the loop terminates.
  matchEndRow < matchStartRow -> RF_UNMATCHED.
  register_reduced_frame_map(0, RF_UNMATCHED).

--- Row 1 (price=110) ---

  update_reduced_frame(1) called.

  Context C1 created (matchStartRow=1).
  Initial advance: C1.states = [{elemIdx=0, counts=[0]}]

  nfa_evaluate_row(1):
    A: 110 > PREV(100) -> true
    B: 110 < PREV(100) -> false
    varMatched = [true, false]

  nfa_process_row(1):
    Phase 1 (Match): A(0) match succeeds -> counts[0]++ -> counts=[1]
    C1.states = [{elemIdx=0, counts=[1]}]

    Phase 3 (Advance):
      State {elemIdx=0, counts=[1]}: A+ (min=1, count=1, max=INF)
        count >= min, so:
        Greedy -> loop first: keep {elemIdx=0, counts=[1]}
                  exit: reset counts[0]=0, next(=1) -> {elemIdx=1, counts=[0]}
    C1.states = [{elemIdx=0, counts=[1]}, {elemIdx=1, counts=[0]}]

--- Row 2 (price=120) ---

  Context C2 created (matchStartRow=2).
  Initial advance: C2.states = [{elemIdx=0, counts=[0]}]

  nfa_evaluate_row(2):
    A: 120 > PREV(110) -> true
    B: 120 < PREV(110) -> false
    varMatched = [true, false]

  C1 nfa_process_row(2):
    Phase 1 (Match):
      {elemIdx=0, counts=[1]}: A matches -> counts=[2]
      {elemIdx=1, counts=[0]}: B does not match -> removed
    C1.states = [{elemIdx=0, counts=[2]}]

  C2 nfa_process_row(2):
    Phase 1 (Match):
      {elemIdx=0, counts=[0]}: A matches -> counts=[1]
    C2.states = [{elemIdx=0, counts=[1]}]

    Phase 2 (Absorb):
      Does C1 (started earlier) cover C2?
        C1: {elemIdx=0, counts=[2]}, C2: {elemIdx=0, counts=[1]}
        Same elemIdx, C1.counts >= C2.counts -> covered
      C2 absorbed. -> removed.

    Phase 3 (Advance):
      {elemIdx=0, counts=[2]}: Greedy -> loop + exit
        Loop: {elemIdx=0, counts=[2]}
        Exit: reset counts[0]=0, next(=1) -> {elemIdx=1, counts=[0]}
    C1.states = [{elemIdx=0, counts=[2]}, {elemIdx=1, counts=[0]}]

  Context C3 created (matchStartRow=3).

--- Row 3 (price=115) ---

  nfa_evaluate_row(3):
    A: 115 > PREV(120) -> false
    B: 115 < PREV(120) -> true
    varMatched = [false, true]

  nfa_process_row(3):
    Phase 1 (Match):
      {elemIdx=0, counts=[2]}: A does not match -> removed
      {elemIdx=1, counts=[0]}: B matches -> counts=[1]
    C1.states = [{elemIdx=1, counts=[1]}]

    Phase 3 (Advance):
      {elemIdx=1, counts=[1]}: B (min=1, max=1)
        count(1) >= max(1) -> unconditional exit
        Reset counts[0]=0, next = 2 (FIN)
      FIN reached -> matchEndRow = 3, matchedState recorded.
      Early termination: no remaining states, so completed immediately.
    C1.states = [] (empty after reaching FIN)

  C1.states is empty and matchEndRow=3 >= matchStartRow=1 -> match succeeds.

  register_reduced_frame_map(1, RF_FRAME_HEAD)
  register_reduced_frame_map(2, RF_SKIPPED)
  register_reduced_frame_map(3, RF_SKIPPED)

--- Row 4 (price=130) ---

  update_reduced_frame(4) called.
  C3 was already created but matchStartRow=3, so it is not applicable.
  New context C4 created (matchStartRow=4).

  nfa_evaluate_row(4):
    A: 130 > PREV(115) -> true
    B: 130 < PREV(115) -> false

  ... No subsequent rows, so nfa_finalize_all_contexts() is called.
  Match incomplete -> RF_UNMATCHED.

XI-5. Final Result

  Row 0: RF_UNMATCHED  -> frame = the row itself
  Row 1: RF_FRAME_HEAD -> frame = rows 1 through 3
  Row 2: RF_SKIPPED    -> inside row 1's match
  Row 3: RF_SKIPPED    -> inside row 1's match
  Row 4: RF_UNMATCHED  -> frame = the row itself


Chapter XII  Summary of Key Design Decisions
================================================================================

XII-1. Flat Array vs Tree-Based NFA

  Choice: Flat array (RPRPatternElement[])

  Rationale:
  - Cache-friendly: 16-byte fixed size, contiguous memory
  - Index-based references: 2-byte indices instead of pointers
  - Easy to serialize: can use memcpy when passing to plan nodes

XII-2. Forward-only Execution vs Backtracking

  Choice: Forward-only (state set tracking)

  Rationale:
  - Backtracking takes exponential time in the worst case
  - NFA simulation guarantees polynomial time
  - DFS order naturally guarantees preferment.
    Greedy/reluctant per quantifier requires only reversing the DFS order
  - Window functions receive sorted rows sequentially.
    Forward-only fits directly into this pipeline,
    whereas backtracking requires re-fetching previous rows
  - DEFINE conditions are SQL expressions (PREV, RUNNING aggregates, etc.)
    with high re-evaluation cost. Forward-only requires only one evaluation
    per row

XII-3. Per-Context Management

  Choice: Independent context per start row

  Rationale:
  - Supports overlapping matches under SKIP TO NEXT ROW
  - Determines the frame for each row independently
  - Absorption optimization can eliminate redundant contexts in O(n)

XII-4. Memory Pool Management

  Choice: Custom free list

  Rationale:
  - NFA states are created and destroyed in large numbers per row
  - Avoids palloc/pfree overhead
  - State size is variable (counts[] array), but within a single query
    maxDepth is fixed, so all states have the same size

XII-5. Execution Optimization Summary

  The following optimizations make the NFA simulation practical.

  -- Compile-time --

  (1) AST Optimization (IV-3)

    Simplifies the AST before converting the pattern to an NFA.
    Reduces the number of NFA elements through consecutive variable
    merging (A A -> A{2}), SEQ flattening, quantifier multiplication,
    and other transformations.

    Significance: Reducing the element count directly shrinks the state
    space, decreasing the cost of all subsequent runtime phases (match,
    absorb, advance).

  -- Runtime: advance phase --

  (2) Group Skip (IX-4(b))

    At the BEGIN of a group with min=0, uses jump to skip the entire
    group. Moves directly to the first element outside the group without
    exploring the group body. Greedy enters then skips; Reluctant skips
    then enters.

    Significance: For optional groups (min=0), immediately generates
    a skip path without exploring the body, avoiding unnecessary DFS
    expansion.

  (3) State Deduplication (IX-5)

    During advance, DFS may generate states with the same (elemIdx,
    counts) combination through multiple paths. Additionally, unlike
    VAR repetition, group repetition cannot perform absorption
    comparison using VAR states, so inline advance is performed from
    after Phase 1 match through to END; this process can also produce
    duplicate states reaching the same END.
    nfa_add_state_unique() blocks duplicate addition of identical states
    in both cases.

    Significance: Prevents exponential growth of the state count in
    ALT branches and quantifier expansion. Since DFS order causes the
    preferred branch's state to be registered first, identical states
    from lower-priority branches are automatically discarded, thereby
    also guaranteeing preferment.

  (4) Cycle Detection and Fast-Forward (IX-6, IX-4(c))

    When a nullable group body (e.g., A?) repeats empty matches,
    the END -> BEGIN loop-back can continue indefinitely.

    Two mechanisms resolve this:
    - A visited bitmap (nfaVisitedElems) blocks revisitation of the
      same element, preventing infinite loops (safety)
    - At an END with the RPR_ELEM_EMPTY_LOOP flag set, when
      count < min, the remaining required iterations are treated as
      empty matches and a fast-forward exit path out of the group is
      added (correctness)

    Significance: Cycle detection guarantees termination, and
    fast-forward guarantees that the min condition is satisfied.
    Without these, patterns containing nullable groups would fall
    into infinite loops or fail to match.

  (5) Match Pruning (IX-4(e))

    When a state reaches FIN during advance, all remaining unprocessed
    states of that context are removed. Because of DFS order, the path
    that reaches FIN first has the highest preferment, so the remaining
    paths are inferior.

    Significance: Once the best match is determined, exploration of
    inferior paths is immediately terminated. This mechanism achieves
    both preferment guarantees and performance optimization.

  -- Runtime: inter-context --

  (6) Early Termination (SKIP PAST LAST ROW)

    In SKIP PAST LAST ROW mode, when a match is found, subsequent
    contexts whose start rows fall within the match range are pruned
    immediately without further processing.
    In SKIP TO NEXT ROW mode, overlapping contexts are preserved
    because each row requires its own independent match.

    Significance: Prunes subsequent contexts whose start rows overlap
    with a prior match range, avoiding unnecessary processing.

  (7) Context Absorption (Chapter VIII)

    If an independent context is created for each row, O(n^2) states
    accumulate. By exploiting the monotonicity that an earlier-started
    context subsumes the states of a later-started context, redundant
    contexts are eliminated early.

    Absorbability is determined per-element; comparison is performed
    only at elements with the RPR_ELEM_ABSORBABLE flag (see IV-5).

    Significance: Keeps the number of active contexts at a constant
    level, achieving O(n^2) -> O(n) time complexity. Without this,
    performance degrades sharply on long partitions.


Appendix A. Key Function Index
================================================================================

  Function                       File                  Role
  ----------------------------------------------------------------------
  transformRPR                   parse_rpr.c           Parser entry point
  transformDefineClause          parse_rpr.c           DEFINE transformation
  collectPatternVariables        rpr.c                 Variable collection
  filterDefineClause             rpr.c                 DEFINE filtering
  buildRPRPattern                rpr.c                 NFA compilation main
  optimizeRPRPattern             rpr.c                 AST optimization
  fillRPRPattern                 rpr.c                 NFA element generation
  finalizeRPRPattern             rpr.c                 Finalization
  computeAbsorbability           rpr.c                 Absorption analysis
  update_reduced_frame           nodeWindowAgg.c       Execution main loop
  nfa_start_context              nodeWindowAgg.c       Context creation
  nfa_process_row                nodeWindowAgg.c       3-phase processing
  nfa_evaluate_row               nodeWindowAgg.c       DEFINE evaluation
  nfa_match                      nodeWindowAgg.c       Phase 1
  nfa_absorb_contexts            nodeWindowAgg.c       Phase 2
  nfa_advance                    nodeWindowAgg.c       Phase 3
  nfa_advance_state              nodeWindowAgg.c       Per-state branching
  nfa_route_to_elem              nodeWindowAgg.c       Element routing
  nfa_advance_alt                nodeWindowAgg.c       ALT handling
  nfa_advance_begin              nodeWindowAgg.c       BEGIN handling
  nfa_advance_end                nodeWindowAgg.c       END handling
  nfa_advance_var                nodeWindowAgg.c       VAR handling
  nfa_add_state_unique           nodeWindowAgg.c       Deduplication
  nfa_states_covered             nodeWindowAgg.c       Absorption coverage check


Appendix B. Data Structure Relationship Diagram
================================================================================

  Parser Layer
  --------
  RPCommonSyntax
    |--- rpSkipTo: RPSkipTo
    |--- initial: bool
    +--- rpPattern: RPRPatternNode* (tree)
         |--- nodeType: VAR | SEQ | ALT | GROUP
         |--- min, max: quantifier
         |--- varName: variable name (VAR only)
         +--- children: List* (SEQ/ALT/GROUP only)

  Planner Layer
  ----------
  WindowAgg (plan node)
    |--- rpSkipTo: RPSkipTo
    |--- defineClause: List<TargetEntry>
    +--- rpPattern: RPRPattern*
         |--- numVars: int
         |--- varNames: char**
         |--- maxDepth: RPRDepth
         |--- isAbsorbable: bool
         |--- numElements: int
         +--- elements: RPRPatternElement[]  (flat array)
              |--- varId      (1B)
              |--- depth      (1B)
              |--- flags      (1B)
              |--- reserved   (1B)
              |--- min, max   (4B + 4B)
              +--- next, jump (2B + 2B)

  Executor Layer
  ----------
  WindowAggState
    |--- rpPattern: RPRPattern* (copied from plan)
    |--- defineClauseList: List<ExprState>
    |--- nfaVarMatched: bool[] (per-row cache)
    |--- nfaVisitedElems: bitmapword* (cycle detection)
    |--- nfaContext <-> nfaContextTail (doubly-linked list)
    |   +--- RPRNFAContext
    |       |--- states: RPRNFAState* (linked list)
    |       |   |--- elemIdx
    |       |   |--- counts[]
    |       |   +--- isAbsorbable
    |       |--- matchStartRow, matchEndRow
    |       |--- matchedState (cloned on FIN arrival)
    |       |--- hasAbsorbableState
    |       +--- allStatesAbsorbable
    |--- nfaContextFree (recycling pool)
    +--- nfaStateFree (recycling pool)


Appendix C. NFA Element Array Examples
================================================================================

C-1. PATTERN (A B C)

  idx  varId  depth  min  max  next  jump
  ------------------------------------------
   0   A      0      1    1    1     -1
   1   B      0      1    1    2     -1
   2   C      0      1    1    3     -1
   3   FIN    0      1    1    -1    -1

C-2. PATTERN (A+ B*)

  idx  varId  depth  min  max  next  jump  flags
  -------------------------------------------------
   0   A      0      1    INF  1     -1    ABSORBABLE | ABSORBABLE_BRANCH
   1   B      0      0    INF  2     -1
   2   FIN    0      1    1    -1    -1

  Only A+ is the absorption point (Case 1). Once past A,
  absorption is permanently disabled for that state.

C-3. PATTERN (A | B | C)

  idx  varId  depth  min  max  next  jump
  ------------------------------------------
   0   ALT    0      1    1    1     -1     alternation start
   1   A      1      1    1    4     2      branch 1 -> FIN, jump -> branch 2
   2   B      1      1    1    4     3      branch 2 -> FIN, jump -> branch 3
   3   C      1      1    1    4     -1     branch 3 -> FIN
   4   FIN    0      1    1    -1    -1

C-4. PATTERN ((A B)+ C)

  idx  varId    depth  min  max  next  jump  flags
  -----------------------------------------------------------
   0   BEGIN    0      1    INF  1     4     ABSORBABLE_BRANCH
   1   A        1      1    1    2     -1    ABSORBABLE_BRANCH
   2   B        1      1    1    3     -1    ABSORBABLE_BRANCH
   3   END      0      1    INF  4     1     ABSORBABLE | ABSORBABLE_BRANCH
   4   C        0      1    1    5     -1
   5   FIN      0      1    1    -1    -1

  Case 2: GROUP+ with {1,1} body VARs. A, B are branches;
  END is the absorption point. Compare with C-6 (Case 3).

C-5. PATTERN ((A | B)+? C)

  idx  varId    depth  min  max   next  jump  flags
  ---------------------------------------------------
   0   BEGIN    0      1    INF   1     5     RELUCTANT, group start
   1   ALT      1      1    1     2     -1    alternation start
   2   A        2      1    1     4     3     branch 1
   3   B        2      1    1     4     -1    branch 2
   4   END      0      1    INF   5     1     RELUCTANT, group end
   5   C        0      1    1     6     -1
   6   FIN      0      1    1     -1    -1

C-6. PATTERN ((A+ B)+ C)  -- Absorbability flag example

  idx  varId    depth  min  max   next  jump  flags
  ----------------------------------------------------------
   0   BEGIN    0      1    INF   1     4     ABSORBABLE_BRANCH, group start
   1   A        1      1    INF   2     -1    ABSORBABLE | ABSORBABLE_BRANCH
   2   B        1      1    1     3     -1
   3   END      0      1    INF   4     1     group end
   4   C        0      1    1     5     -1
   5   FIN      0      1    1     -1    -1

  Recurses from BEGIN into the body -> A matches Case 1 (simple VAR+).
  A gets ABSORBABLE | ABSORBABLE_BRANCH, BEGIN gets ABSORBABLE_BRANCH.
  B and END get no flags -> absorption stops once the state advances to B.
  (See IV-5 Case 3)

C-7. PATTERN ((A+ B | C*)+ D)  -- Per-branch absorption in ALT

  idx  varId    depth  min  max   next  jump  flags
  ----------------------------------------------------------
   0   BEGIN    0      1    INF   1     6     ABSORBABLE_BRANCH
   1   ALT      1      1    1     2     -1    ABSORBABLE_BRANCH
   2   A        2      1    INF   3     4     ABSORBABLE | ABSORBABLE_BRANCH
   3   B        2      1    1     5     -1
   4   C        2      0    INF   5     -1    ABSORBABLE | ABSORBABLE_BRANCH
   5   END      0      1    INF   6     1     EMPTY_LOOP
   6   D        0      1    1     7     -1
   7   FIN      0      1    1     -1    -1

  ALT branches are checked independently for absorbability.
  Branch 1: A+ matches Case 1 -> A gets ABSORBABLE. B has no flag.
  Branch 2: C* matches Case 1 -> C gets ABSORBABLE.
  Both A and C get ABSORBABLE_BRANCH as part of their respective branch paths.
  END has EMPTY_LOOP: branch 2 (C*) is nullable, making the group body nullable.
  BEGIN and ALT get ABSORBABLE_BRANCH (on the path to absorbable elements).


================================================================================
  End of document
================================================================================

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Here are ten incremental patches on top of v43.

Thanks.

BTW, I noticed that RPR accepts table name qualified variables in
DEFINE clause.

SELECT company, tdate, price, first_value(price) OVER w, last_value(price) OVER w,
 nth_value(tdate, 2) OVER w AS nth_second
 FROM stock
 WINDOW w AS (
 PARTITION BY company
 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
 INITIAL
 PATTERN (START UP+ DOWN+)
 DEFINE
  START AS TRUE,
  UP AS stock.price > PREV(price),	<-- table name "stock" is uded
  DOWN AS price < PREV(price)
);

The standard does not allow to use range variables, declared in the
FROM clause, in the DEFINE clause (19075-5 6.5). Attached patch raises
an error in this case.

psql:a.sql:13: ERROR:  range var qualified name "stock.price" is not allowed in DEFINE clause
LINE 11:   UP AS stock.price > PREV(price),
                 ^

Also, currently we do not support pattern variable range vars in the
DEFINE caluse (e.g. UP.price). If used, we see a confusing error
message:

ERROR: missing FROM-clause entry for table "UP"
LINE 13: UP AS UP.price > PREV(price),
               ^

The attached patch errors out differently. I believe this is an
enhancement.

psql:a.sql:13: ERROR:  range var qualified name "up.price" is not allowed in DEFINE clause
LINE 11:   UP AS UP.price > PREV(price),
                 ^

Thoughts?
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 219681d6e88..f92fa793c10 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -613,6 +613,17 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
 			return node;
 	}
 
+	/*
+	 * DEFINE clause in RPR does not allow to use table names.
+	 */
+	if (pstate->p_expr_kind == EXPR_KIND_RPR_DEFINE &&
+		list_length(cref->fields) != 1)
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("range var qualified name \"%s\" is not allowed in DEFINE clause",
+						NameListToString(cref->fields)),
+				 parser_errposition(pstate, cref->location)));
+
 	/*----------
 	 * The allowed syntaxes are:
 	 *

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

The standard does not allow to use range variables, declared in the
FROM clause, in the DEFINE clause (19075-5 6.5). Attached patch raises
an error in this case.
 
Agreed. §6.5 is explicit about mutual exclusivity of the two sets of
range variables. Your patch is correct for this case.

Also, currently we do not support pattern variable range vars in the
DEFINE caluse (e.g. UP.price). If used, we see a confusing error
message:

ERROR: missing FROM-clause entry for table "UP"
LINE 13: UP AS UP.price > PREV(price),
               ^

Pattern variable qualified names like `UP.price` are actually valid
standard syntax (§4.16 uses them in examples), so "is not allowed"
is misleading — "is not supported" would be more accurate.

To distinguish the two cases, we could expose `patternVarNames` via
ParseState (it is already collected by `validateRPRPatternVarCount`
before DEFINE expressions are transformed) and check in
`transformColumnRef` whether the qualifier is a pattern variable:

  - pattern variable qualifier → "not supported"
  - anything else              → "not allowed"

Would it be okay if I revise the patch along those lines?

Best regards,
Henson
 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> The standard does not allow to use range variables, declared in the
>> FROM clause, in the DEFINE clause (19075-5 6.5). Attached patch raises
>> an error in this case.
>>
> 
> Agreed. §6.5 is explicit about mutual exclusivity of the two sets of
> range variables. Your patch is correct for this case.
> 
> Also, currently we do not support pattern variable range vars in the
>> DEFINE caluse (e.g. UP.price). If used, we see a confusing error
>> message:
>>
>> ERROR: missing FROM-clause entry for table "UP"
>> LINE 13: UP AS UP.price > PREV(price),
>>                ^
>>
> 
> Pattern variable qualified names like `UP.price` are actually valid
> standard syntax (§4.16 uses them in examples), so "is not allowed"
> is misleading ― "is not supported" would be more accurate.

Fair enough.

> To distinguish the two cases, we could expose `patternVarNames` via
> ParseState (it is already collected by `validateRPRPatternVarCount`
> before DEFINE expressions are transformed) and check in
> `transformColumnRef` whether the qualifier is a pattern variable:

Oh, I didn't realize it.

>   - pattern variable qualifier → "not supported"
>   - anything else              → "not allowed"
> 
> Would it be okay if I revise the patch along those lines?

Sure. Thanks.
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Currently we do not account the cost of RPR while planning.  Attached
is the first attempt to try to estimate the RPR costs. The cost model
is very simple:

expression cost per PATTERN variable * number of input tuples

Any idea to make this estimation better?

 >   foreach(lc, windowFuncs)
>   {
>   ...
> + /* also add DEFINE clause expressions' cost to per-input-row costs */
> + if (winclause->rpPattern)
> + {
> + List   *pattern_vars; /* list of pattern variable names */
> + ListCell   *lc2;
> +
> + pattern_vars = collectPatternVariables(winclause->rpPattern);
> +
> + /* iterate according to the pattern variable */
> + foreach(lc2, pattern_vars)
> + {
> + char   *ptname = strVal((char *) lfirst(lc2));

`collectPatternVariables` returns a list of String nodes (via
`makeString()`), so `strVal(lfirst(lc2))` is the idiomatic form.
The `(char *)` cast is misleading.

There is also a correctness issue: DEFINE expressions belong to the
window clause, not to individual window functions, so their cost
should not be multiplied by the number of window functions sharing
the clause.

The fix is to compute the DEFINE cost once outside the loop and add
it to `startup_cost` and `total_cost` directly, after the
`foreach(lc, windowFuncs)` block.

Regarding the cost model: the NFA executor evaluates all DEFINE
expressions once per row into a shared `nfaVarMatched[]` array that
all active contexts read from, and contexts advance strictly forward
so no prior row is ever re-evaluated.  The one-evaluation-per-row
cost model is therefore accurate.  NFA-aware cost
modeling could be built on top of this foundation in a separate patch
down the road, once the NFA implementation has matured.

For now, the DEFINE expression costs themselves already serve as a
natural penalty — a window clause with RPR will consistently appear
more expensive than a comparable plain window function.  This gives
the surrounding plan a reasonable cost signal for decisions such as
join ordering and materialization of RPR subqueries.  So the current
approach is reasonable as a first step.

Other than that, the approach looks good to me.  Would it be okay if
I revise the patch along those lines?

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Currently we do not account the cost of RPR while planning.  Attached
>> is the first attempt to try to estimate the RPR costs. The cost model
>> is very simple:
>>
>> expression cost per PATTERN variable * number of input tuples
>>
>> Any idea to make this estimation better?
>>
> 
>  >   foreach(lc, windowFuncs)
>>   {
>>   ...
>> + /* also add DEFINE clause expressions' cost to per-input-row costs */
>> + if (winclause->rpPattern)
>> + {
>> + List   *pattern_vars; /* list of pattern variable names */
>> + ListCell   *lc2;
>> +
>> + pattern_vars = collectPatternVariables(winclause->rpPattern);
>> +
>> + /* iterate according to the pattern variable */
>> + foreach(lc2, pattern_vars)
>> + {
>> + char   *ptname = strVal((char *) lfirst(lc2));
> 
> `collectPatternVariables` returns a list of String nodes (via
> `makeString()`), so `strVal(lfirst(lc2))` is the idiomatic form.
> The `(char *)` cast is misleading.

Ok.

> There is also a correctness issue: DEFINE expressions belong to the
> window clause, not to individual window functions, so their cost
> should not be multiplied by the number of window functions sharing
> the clause.

You are right.

> The fix is to compute the DEFINE cost once outside the loop and add
> it to `startup_cost` and `total_cost` directly, after the
> `foreach(lc, windowFuncs)` block.

Looks good.

> Regarding the cost model: the NFA executor evaluates all DEFINE
> expressions once per row into a shared `nfaVarMatched[]` array that
> all active contexts read from, and contexts advance strictly forward
> so no prior row is ever re-evaluated.  The one-evaluation-per-row
> cost model is therefore accurate.  NFA-aware cost
> modeling could be built on top of this foundation in a separate patch
> down the road, once the NFA implementation has matured.
> 
> For now, the DEFINE expression costs themselves already serve as a
> natural penalty ― a window clause with RPR will consistently appear
> more expensive than a comparable plain window function.  This gives
> the surrounding plan a reasonable cost signal for decisions such as
> join ordering and materialization of RPR subqueries.  So the current
> approach is reasonable as a first step.
> 
> Other than that, the approach looks good to me.  Would it be okay if
> I revise the patch along those lines?

Yes, no problem. Thanks!
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

I'd like to propose an extension to the context absorption optimization
for Row Pattern Recognition in the window clause: PREFIX pattern
absorption. This refines the "anchored pattern absorption" concept I
posted earlier [1], renaming it to "PREFIX pattern absorption" per
Ishii-san's feedback [2], and formalizing the absorption conditions
with count-dominance analysis.

It builds on the existing absorption framework to handle patterns where
a fixed-length prefix precedes the unbounded greedy repetition, using a
"shadow path" design.

[1] https://www.postgresql.org/message-id/CAAAe_zAEg7sVM=WDwXMyE-odGmQyXSVi5ZzWgye6SupSjdMKpg@mail.gmail.com
[2] https://www.postgresql.org/message-id/20260217.180053.64368434967157940.ishii@postgresql.org


1. Problem Definition
=====================

1.1 Current Absorption Scope

Context absorption currently applies to patterns with an unbounded-start
structure -- where an unbounded greedy repetition appears at the very
beginning of the pattern.

Example: A+ B -- the first element A+ is an unbounded repetition, so an
older context always has a repeat count greater than or equal to any
newer context, making immediate absorption possible.

1.2 The PREFIX Pattern Problem

For patterns like START SECOND A+ B+, where a finite-length prefix
(PREFIX) precedes the unbounded repetition (A+), absorption does not
currently work.

Why:
- A new context starts at the START element, so it is not at the same
  pattern position as an older context in the A+ region.
- The allStatesAbsorbable condition is not satisfied, so absorption
  never fires.
- Contexts accumulate while traversing the PREFIX, causing O(n^2)
  regression.


2. Relationship to the Existing Framework
==========================================

2.1 Position in the Three-Phase Execution Model

The Match -> Absorb -> Advance model is preserved as-is. PREFIX
absorption is an extension of the Absorb phase's eligibility criteria,
not a new phase.

2.2 Prerequisites

The same four prerequisites as existing absorption apply:

1. Greedy quantifier -- A+ must be greedy.
2. SKIP TO PAST LAST ROW -- prior matches suppress subsequent start
   points.
3. UNBOUNDED FOLLOWING -- all contexts see the same future rows.
4. Match-start-independent DEFINE predicates -- including predicates of
   PREFIX elements.

2.3 Extension of the Dominance Order

In existing absorption, the dominance condition is:

    C_old and C_new are in the absorbable region of the same element,
    and C_old.counts >= C_new.counts.

In PREFIX patterns this condition cannot be directly satisfied: C_new is
in the PREFIX region while C_old is in the BODY region. We therefore
need a mechanism to track what C_new's state *would be* if it had
already reached the BODY region.


3. Design: Shadow Path
=======================

3.1 Core Idea

Each context logically executes two parallel paths:

- Original path: executes the full pattern in order (PREFIX -> BODY).
  This is the path that produces the actual match result and evaluates
  PREFIX predicates.

- Shadow path: skips the PREFIX and starts directly in the BODY region
  (A+).
  - Used solely for absorption eligibility decisions.
  - Does not produce match results.
  - Actually evaluates the BODY element's DEFINE predicates to track
    counts accurately.
  - The shadow is placed at the BODY start state upon creation and
    immediately advances, so its initial count is 1.
  - Not created if there is no preceding context (nothing to be
    absorbed into).
  - Discarded when the preceding context dies.
  - Discarded when the shadow leaves the absorbable region (BODY->TAIL
    transition or match failure).

3.2 Absorption Conditions

For C_old to absorb C_new, all of the following must hold:

1. C_old is past the PREFIX and in the absorbable region (BODY).
   - hasAbsorbableState = true (existing flag)

2. C_new was created at or after the row where C_old entered the
   absorbable region.
   - "Same row" means: in the Match phase C_old enters BODY and C_new
     is created; the subsequent Absorb phase of that same row can then
     perform the absorption check.

3. C_new's shadow path is alive in the absorbable region.
   - allStatesAbsorbable = true (evaluated on the shadow)

4. C_old.counts[depth] >= C_new.shadow.counts[depth]
   - Same count-dominance condition as existing absorption (equality
     counts as dominance).
   - The shadow's count increases as it processes rows, so the
     comparison uses actual counts at absorption time.

Condition 2 is the key insight. Only contexts created after C_old has
passed through the PREFIX into the absorbable region are eligible for
absorption. Contexts created while C_old is still in the PREFIX cannot
be absorbed.

3.3 Common Fate

Soundness argument for absorption:

    C_old's original path and C_new's shadow path are at the same BODY
    element (A+). By match-start independence, the DEFINE predicates of
    both paths produce identical results on the same row. If C_new's
    shadow can match at some future row r, then C_old can also complete
    a match at row r (it has matched at least as many times, sees the
    same future rows, and DEFINE evaluations are identical). Under SKIP
    TO PAST LAST ROW, C_old's match includes C_new's start point, so
    removing C_new does not lose any reported match.

3.4 Complexity

With PREFIX absorption, the maximum number of simultaneously active
contexts is bounded by PREFIX_length + 1. Every C_new created after
C_old enters BODY is absorbed immediately, so the only contexts that can
coexist are those still traversing the PREFIX plus the single C_old in
BODY. Since PREFIX length is a per-pattern constant, overall execution
complexity is O(n).

3.5 Removal of Non-Absorbable Contexts

Contexts that do not satisfy condition 2 -- i.e., those created before
C_old entered BODY -- cannot be removed by PREFIX absorption.

These contexts are removed by the existing SKIP TO PAST LAST ROW
mechanism, which is separate from PREFIX absorption. When C_old
successfully matches, all subsequent contexts whose start points fall
within C_old's match range are removed as overlaps. Since contexts
created during the PREFIX region have start points within C_old's match
range, they are automatically removed upon C_old's match completion.

The number of such contexts is at most PREFIX_length, which does not
affect the O(n) complexity (see Section 3.4).


4. Compile-Time Analysis
=========================

4.1 Pattern Structure Recognition

At compile time, traverse the pattern elements from the start until the
first unbounded greedy repetition is found. All preceding fixed-length
elements form the PREFIX; the unbounded element is the BODY; everything
after it is the TAIL. If the first element is already unbounded, the
pattern has no PREFIX and existing absorption applies directly.

    Pattern: E1 E2 ... Ek  A+          B+ ...
             \__________/  \__/         \___/
              PREFIX        BODY         TAIL
                           (absorbable)  (non-absorbable)


5. Worked Example
==================

Pattern: START SECOND A+ B+
PREFIX: START, SECOND (length 2)
BODY: A+ (absorbable)
TAIL: B+ (non-absorbable)

Data: r0-r3 satisfy A only, r4-r5 satisfy B only, r6 satisfies neither
A nor B.

Row  C1(orig)   C2(orig)   C2(shadow)  C3(orig)   C3(shadow)  Active
r0   START       -           -           -           -          1
r1   SECOND      START       A(cnt=1)    -           -          2
r2   A(cnt=1)    SECOND      A(cnt=2)    START       A(cnt=1)   3
     ^ C1 reaches BODY
     -> C3: shadow A(cnt=1), created at C1's BODY entry
        -> absorbed (1 >= 1)
     -> C2: created before C1's BODY entry
        -> not absorbable                                       2
r3   A(cnt=2)    A(cnt=1)    A(cnt=3)    -           -          2
r4   B(cnt=1)    B(cnt=1)    (discard)   -           -          2
     ^ TAIL      ^ TAIL      ^ shadow A+->B+ -> TAIL -> discard
r5   B(cnt=2)    B(cnt=2)    -           -           -          2
r6   neither A nor B -> B+ ends -> C1 match (r0-r5)             0
     C2 removed by SKIP TO PAST LAST ROW overlap
     (C2 start r1 falls within C1 match range r0-r5)

Max concurrent contexts: 3 = PREFIX_length(2) + 1

Key observations:
- C3 is immediately removed at r2 by PREFIX absorption (shadow-path-
  based).
- C2's shadow is discarded at r4 when A+->B+ transition moves it into
  TAIL.
- C2 is not absorbable (condition 2 not met), survives until r6, then
  removed by SKIP TO PAST LAST ROW overlap when C1 matches
  (Section 3.5).

This is a design proposal at this stage. Thoughts and feedback welcome.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Attached are two more incremental patches (nocfbot-0011, nocfbot-0012)
on top of v43, continuing the nocfbot-0001..0010 series.

nocfbot-0011: Add RPR DEFINE expression cost to WindowAgg cost estimation

  Revised version of your cost estimation patch [1].  Fixes the
  `(char *)` cast and moves DEFINE cost outside the windowFuncs loop.

nocfbot-0012: Reject qualified column references in RPR DEFINE clause

  Revised version of your qualified column reference patch [2].
  Exposes `patternVarNames` via `ParseState.p_rpr_pattern_vars` to
  distinguish pattern variable qualifiers ("not supported") from
  FROM-clause range variable qualifiers ("not allowed").

  Variables appearing only in DEFINE (not in PATTERN) are also
  collected into `p_rpr_pattern_vars` so they get the "not supported"
  message, but the RPR_VARID_MAX count check still applies only to
  PATTERN variables.

[1] https://www.postgresql.org/message-id/20260227.225456.33226875991025537.ishii@postgresql.org
[2] https://www.postgresql.org/message-id/20260227.145539.1921177948671828231.ishii@postgresql.org

Attachment:
  nocfbot-0011-define-cost.txt
  nocfbot-0012-qualified-refs.txt

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Attached are two more incremental patches (nocfbot-0011, nocfbot-0012)
> on top of v43, continuing the nocfbot-0001..0010 series.
> 
> nocfbot-0011: Add RPR DEFINE expression cost to WindowAgg cost estimation
> 
>   Revised version of your cost estimation patch [1].  Fixes the
>   `(char *)` cast and moves DEFINE cost outside the windowFuncs loop.
> 
> nocfbot-0012: Reject qualified column references in RPR DEFINE clause
> 
>   Revised version of your qualified column reference patch [2].
>   Exposes `patternVarNames` via `ParseState.p_rpr_pattern_vars` to
>   distinguish pattern variable qualifiers ("not supported") from
>   FROM-clause range variable qualifiers ("not allowed").
> 
>   Variables appearing only in DEFINE (not in PATTERN) are also
>   collected into `p_rpr_pattern_vars` so they get the "not supported"
>   message, but the RPR_VARID_MAX count check still applies only to
>   PATTERN variables.
> 
> [1]
> https://www.postgresql.org/message-id/20260227.225456.33226875991025537.ishii@postgresql.org
> [2]
> https://www.postgresql.org/message-id/20260227.145539.1921177948671828231.ishii@postgresql.org
> 
> Attachment:
>   nocfbot-0011-define-cost.txt
>   nocfbot-0012-qualified-refs.txt

Thanks. I will try them out. Once they look good, shall I release v44
patch sets? Or do you have a plan to add more patches?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> Thanks. I will try them out. Once they look good, shall I release v44
> patch sets? Or do you have a plan to add more patches?

The NFA executor code looks stable to me at this point. I do have some
additional optimization ideas around absorption, but I think it's better
new features should be added more carefully, or deferred until after the commit.

Please go ahead and release v44. Having a fresh patch set will also
make it easier to proceed with the next round of test modifications
and improvements.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
>> Thanks. I will try them out. Once they look good, shall I release v44
>> patch sets? Or do you have a plan to add more patches?
> 
> The NFA executor code looks stable to me at this point. I do have some
> additional optimization ideas around absorption, but I think it's better
> new features should be added more carefully, or deferred until after the
> commit.
> 
> Please go ahead and release v44. Having a fresh patch set will also
> make it easier to proceed with the next round of test modifications
> and improvements.

Your patches look good. Attached are the v44 pathes, with minor fixes
to docs (mention that reluctant quantifiers are supported, exclusion
and empty PATTERN are not supported). Also makes clear the range of n
and m in {n, m} and other regular expression.

---- Major differences from v43 patches ----

- Implement reluctant quantifiers

- Disallow using PREV()/NEXT() in other than the DEFINE caluse

- Reject qualied column references in the DEFINE clause

- Fix explain test failures on 32bit platforms

- Fix and cleanup the NFA engine

- Fix docs that reluctant quantifiers are supported, exclusion and
  empty PATTERN are not supported.

- Some code refactorings

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi,Tatsuo

While reviewing the RPR test cases, I noticed that a subquery filter
on RPR window function results silently returns wrong results.

For example, given this query:

  SELECT * FROM (
      SELECT id, val, COUNT(*) OVER w as cnt
      FROM rpr_copy
      WINDOW w AS (
          ORDER BY id
          ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
          PATTERN (A B?)
          DEFINE A AS val > 10, B AS val > 20
      )
  ) sub
  WHERE cnt > 0
  ORDER BY id;

This should return 2 rows, but returns 0 rows instead.

The EXPLAIN plan shows that "cnt > 0" is pushed down into the
WindowAgg node as a Run Condition:

  WindowAgg
    Run Condition: (count(*) OVER w > 0)    <-- pushed down
    ->  Sort
          ->  Seq Scan on rpr_copy

I will investigate the cause and work on a fix.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi,Tatsuo
> 
> While reviewing the RPR test cases, I noticed that a subquery filter
> on RPR window function results silently returns wrong results.
> 
> For example, given this query:
> 
>   SELECT * FROM (
>       SELECT id, val, COUNT(*) OVER w as cnt
>       FROM rpr_copy
>       WINDOW w AS (
>           ORDER BY id
>           ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>           PATTERN (A B?)
>           DEFINE A AS val > 10, B AS val > 20
>       )
>   ) sub
>   WHERE cnt > 0
>   ORDER BY id;
> 
> This should return 2 rows, but returns 0 rows instead.

Thanks for the report!

> The EXPLAIN plan shows that "cnt > 0" is pushed down into the
> WindowAgg node as a Run Condition:
> 
>   WindowAgg
>     Run Condition: (count(*) OVER w > 0)    <-- pushed down
>     ->  Sort
>           ->  Seq Scan on rpr_copy
> 
> I will investigate the cause and work on a fix.

I think there are two ways to solve the issue:

1) Fix the executor
2) Fix the planner

I tried #1 but I don't know how to fix it. The run condition is
already pushed in the window function. Existing code forces to stop
the aggregate evaluation if the run condition is not
satisfied. Without RPR, the optimization is correct because once the
run condition is not satisfied, there's no chance that the subsequence
rows satisfy the condition. But RPR is used, a partition/frame is
divided into multiple reduced frames and each should be evaluated to
the end of the partition/frame.

So, I tried #2 so that the planner does not push down the run
condition.

Attached is the patch.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c
index 90275e25872..b67c35af39a 100644
--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -2453,6 +2453,17 @@ find_window_run_conditions(Query *subquery, AttrNumber attno,
 	wclause = (WindowClause *) list_nth(subquery->windowClause,
 										wfunc->winref - 1);
 
+	/*
+	 * If a DEFINE clause exists, we cannot push down a run condition. In the
+	 * case, a window partition (or frame) is divided into multiple reduced
+	 * frames and each frame should be evaluated to the end of the partition
+	 * (or full frame end). This means we cannot apply the run condition
+	 * optimization because it stops evaluation window functions in certain
+	 * cases.
+	 */
+	if (wclause->defineClause != NIL)
+		return false;
+
 	req.type = T_SupportRequestWFuncMonotonic;
 	req.window_func = wfunc;
 	req.window_clause = wclause;

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> The NFA executor code looks stable to me at this point. I do have some
>> additional optimization ideas around absorption, but I think it's better
>> new features should be added more carefully, or deferred until after the
>> commit.
>> 
>> Please go ahead and release v44. Having a fresh patch set will also
>> make it easier to proceed with the next round of test modifications
>> and improvements.

CFBot complains v44-0007 patch corrupted.
https://cfbot.cputube.org/patch_4460.log

In my local environment, the patch size was:
-rw-rw-r-- 1 t-ishii t-ishii 966311  3月  4 16:10 /home/t-ishii/v44-0007-Row-pattern-recognition-patch-tests.patch
While the file downloaded from PostgreSQL mailing list archive was:
-rw-rw-r-- 1 t-ishii t-ishii 250064  3月  4 16:15 v44-0007-Row-pattern-recognition-patch-tests.patch

So it seems the file was truncated somwhere between me and PostgreSQL
ML archiving.

Can you check the size of the file attached to your mail?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

CFBot complains v44-0007 patch corrupted.
https://cfbot.cputube.org/patch_4460.log

I downloaded v44-0007 from the mailing list archive and applied it
successfully in my local environment. Everything works fine here.
 
So it seems the file was truncated somwhere between me and PostgreSQL
ML archiving.

It seems CFBot does not retry once it fails, so the initial truncation
error has become permanent.
 
Can you check the size of the file attached to your mail?

I didn't check the raw attachment size, but the patch applied cleanly
without any issues.

To work around this, how about splitting the test patch (0007) into
separate patches for .sql and .out files? This would reduce the
individual file sizes and help avoid truncation during archiving.

Best regards,
Henson
 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> I downloaded v44-0007 from the mailing list archive and applied it
> successfully in my local environment. Everything works fine here.

Oh, ok.
I tried to download the file again, and now the file size increased!
It seems the ML downloading feature is a little bit instable?

> I didn't check the raw attachment size, but the patch applied cleanly
> without any issues.
> 
> To work around this, how about splitting the test patch (0007) into
> separate patches for .sql and .out files? This would reduce the
> individual file sizes and help avoid truncation during archiving.

Yeah, let's give it a try.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
장성준 <sjjang112233@gmail.com>
Дата:
Hi hackers

I converted PostgreSQL RPR regression test queries to Oracle
MATCH_RECOGNIZE syntax and executed them on both systems to perform
cross-validation.

The tests were based on the following PostgreSQL regression test files:

  rpr_base.sql
  rpr_nfa.sql


PostgreSQL bug: zero-min reluctant quantifier

During cross-validation a PostgreSQL bug was discovered involving
reluctant quantifiers whose minimum repetition is 0.

Example pattern:

  PATTERN (A*?)
  DEFINE A AS val > 0

Result comparison:

pattern   PostgreSQL (cnt)   Oracle (cnt)
A*?       1,1,1              0,0,0
A??       1,1,1              0,0,0
A+?       1,1,1              1,1,1

For reluctant quantifiers with min=0 (such as *? and ??), PostgreSQL
always consumes at least one row, while Oracle allows a zero-length
match. When min>=1 (e.g., A+?), both systems behave the same.

This behavior was consistently observed across the converted tests.


Design difference: unused DEFINE variables

Example:

  PATTERN (A+)
  DEFINE A AS id > 0, B AS id > 5

PostgreSQL executes the query successfully and ignores the unused
variable B.

Oracle raises:

  ORA-62503: illegal variable definition


Oracle limitations observed


Bounded quantifier limit

A{200}  -> works
A{201}  -> ORA-62518

Oracle appears to limit the upper bound of bounded quantifiers to 200,
while PostgreSQL does not impose this restriction.


Nested nullable quantifiers

Examples:

  (A*)*
  (A*)+
  (((A)*)*)*

  (A?|B){1,2}
  ((A?){2,3}){2,3}
  (A?){n,m}
  (A? B?){2,3}

Oracle raises:

  ORA-62513

when a nullable subpattern is wrapped by an outer quantifier, while
PostgreSQL executes these patterns successfully.


These results come from running the converted PostgreSQL RPR regression
tests on Oracle for comparison.

Best regards,
SugJun

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

PostgreSQL bug: zero-min reluctant quantifier

During cross-validation a PostgreSQL bug was discovered involving
reluctant quantifiers whose minimum repetition is 0.

Example pattern:

  PATTERN (A*?)
  DEFINE A AS val > 0

Result comparison:

pattern   PostgreSQL (cnt)   Oracle (cnt)
A*?       1,1,1              0,0,0
A??       1,1,1              0,0,0
A+?       1,1,1              1,1,1

For reluctant quantifiers with min=0 (such as *? and ??), PostgreSQL
always consumes at least one row, while Oracle allows a zero-length
match. When min>=1 (e.g., A+?), both systems behave the same.

This is indeed a bug. Thanks SugJun for finding it. I'll fix this in
the next patch.

Design difference: unused DEFINE variables

Example:

  PATTERN (A+)
  DEFINE A AS id > 0, B AS id > 5

PostgreSQL executes the query successfully and ignores the unused
variable B.

Oracle raises:

  ORA-62503: illegal variable definition

Currently PostgreSQL silently removes unused DEFINE variables during
optimization. Do you think we should raise an error instead, as Oracle
does?
 
Oracle limitations observed


Bounded quantifier limit

A{200}  -> works
A{201}  -> ORA-62518

Oracle appears to limit the upper bound of bounded quantifiers to 200,
while PostgreSQL does not impose this restriction.

I don't think we need to impose an artificial limit like Oracle's 200.
What do you think?
 
Nested nullable quantifiers

Examples:

  (A*)*
  (A*)+
  (((A)*)*)*

  (A?|B){1,2}
  ((A?){2,3}){2,3}
  (A?){n,m}
  (A? B?){2,3}

Oracle raises:

  ORA-62513

when a nullable subpattern is wrapped by an outer quantifier, while
PostgreSQL executes these patterns successfully.

This seems like an Oracle limitation rather than a standard requirement.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> PostgreSQL bug: zero-min reluctant quantifier
>>
>> During cross-validation a PostgreSQL bug was discovered involving
>> reluctant quantifiers whose minimum repetition is 0.
>>
>> Example pattern:
>>
>>   PATTERN (A*?)
>>   DEFINE A AS val > 0
>>
>> Result comparison:
>>
>> pattern   PostgreSQL (cnt)   Oracle (cnt)
>> A*?       1,1,1              0,0,0
>> A??       1,1,1              0,0,0
>> A+?       1,1,1              1,1,1
>>
>> For reluctant quantifiers with min=0 (such as *? and ??), PostgreSQL
>> always consumes at least one row, while Oracle allows a zero-length
>> match. When min>=1 (e.g., A+?), both systems behave the same.
>>
> 
> This is indeed a bug. Thanks SugJun for finding it. I'll fix this in
> the next patch.

Thanks in advance.

> Design difference: unused DEFINE variables
>>
>> Example:
>>
>>   PATTERN (A+)
>>   DEFINE A AS id > 0, B AS id > 5
>>
>> PostgreSQL executes the query successfully and ignores the unused
>> variable B.
>>
>> Oracle raises:
>>
>>   ORA-62503: illegal variable definition
>>
> 
> Currently PostgreSQL silently removes unused DEFINE variables during
> optimization. Do you think we should raise an error instead, as Oracle
> does?

No, I don't think so. I think the standard does not say anything if a
pattern variable defined in DEFINE clause is not used in PATTERN
clause. So the expected behavior would be implementation dependent. I
think just ignoring the variable is fine.

>> Oracle limitations observed
>>
>>
>> Bounded quantifier limit
>>
>> A{200}  -> works
>> A{201}  -> ORA-62518
>>
>> Oracle appears to limit the upper bound of bounded quantifiers to 200,
>> while PostgreSQL does not impose this restriction.
>>
> 
> I don't think we need to impose an artificial limit like Oracle's 200.
> What do you think?

Agreed. We do not need to follow Oracle here.

>> Nested nullable quantifiers
>>
>> Examples:
>>
>>   (A*)*
>>   (A*)+
>>   (((A)*)*)*
>>
>>   (A?|B){1,2}
>>   ((A?){2,3}){2,3}
>>   (A?){n,m}
>>   (A? B?){2,3}
>>
>> Oracle raises:
>>
>>   ORA-62513
>>
>> when a nullable subpattern is wrapped by an outer quantifier, while
>> PostgreSQL executes these patterns successfully.
>>
> 
> This seems like an Oracle limitation rather than a standard requirement.

Agreed. For example, the standard explicitly stats A(*)* is permitted
(ISO/IEC 19075-5, 4.1.4.1 Introduction to the PATTEREN syntax).

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

I reviewed the planner's Window clause optimizations and found
additional issues with RPR windows.  Thanks to SungJun's Oracle
cross-validation work, all converted regression tests now pass
on both systems.  With these fixes, I'd like to move on to
non-functional quality testing next.

Here are eight incremental patches on top of v44.


nocfbot-0001: Fix elog message to use lowercase per PostgreSQL convention

  Minor style fix: lowercase the elog error message in
  nodeWindowAgg.c to follow PostgreSQL coding convention.


nocfbot-0002: Fix RPR reluctant quantifier flag lost during VIEW serialization

  The reluctant flag on quantifiers was lost when a VIEW containing
  RPR was serialized and restored via ruleutils.c.  This patch fixes
  gram.y, rpr.c, ruleutils.c, and parsenodes.h so the flag survives
  the round-trip.


nocfbot-0003: Expand RPR test coverage and improve test comments

  Reorganizes test cases across rpr.sql, rpr_base.sql, rpr_explain.sql,
  and rpr_nfa.sql.  Moves base functionality tests from rpr.sql to
  rpr_base.sql and NFA-specific tests to rpr_nfa.sql.  Adds better
  section comments throughout.  Duplicate tests in rpr.sql were
  removed.  No reduction in test coverage.


nocfbot-0004: Keep RPR test objects for pg_upgrade/pg_dump testing

  Adjusts rpr_base.sql and rpr_explain.sql so that test tables and
  views are not dropped at the end of the test.  This allows
  pg_upgrade and pg_dump regression testing to cover RPR objects.


nocfbot-0005: Disable run condition pushdown for RPR windows

  Revised version of your run condition fix [1].  Existing test
  expected output updated accordingly.


nocfbot-0006: Disable frame optimization for RPR windows

  Prevents the planner from optimizing the window frame for RPR
  windows.  The frame clause in RPR has different semantics (it
  bounds the pattern search space), so standard frame optimizations
  must be disabled.  Adds EXPLAIN tests to verify.  Please review
  this one -- it's a newly discovered issue.


nocfbot-0007: Add stock scenario tests for RPR pattern matching

  Adds stock trading scenario tests using realistic synthetic data
  (stock.data with 1632 rows).  Tests V-shape recovery, W-shape,
  consecutive rises, and other common pattern matching use cases.


nocfbot-0008: Fix zero-min reluctant quantifier to produce zero-length match

  Fixes the bug reported by SungJun [2]: reluctant quantifiers with
  min=0 (A*?, A??) were incorrectly consuming at least one row instead
  of producing a zero-length match.  The NFA can now internally
  distinguish between a zero-length match and no match, so it will
  be ready when additional infrastructure (e.g. MATCH_NUMBER) is
  added.  Now matches Oracle behavior.


[1]
https://www.postgresql.org/message-id/20260304.153822.445473532741409674.ishii@postgresql.org
[2]
https://www.postgresql.org/message-id/CAE+cgNiUbKeH1A0PoxV2QjpsoxJLe+pJcGz_gdxwOwu_9zqchw@mail.gmail.com


Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> I reviewed the planner's Window clause optimizations and found
> additional issues with RPR windows.  Thanks to SungJun's Oracle
> cross-validation work, all converted regression tests now pass
> on both systems.  With these fixes, I'd like to move on to
> non-functional quality testing next.

Sounds good.

> Here are eight incremental patches on top of v44.
> 
> 
> nocfbot-0001: Fix elog message to use lowercase per PostgreSQL convention
> 
>   Minor style fix: lowercase the elog error message in
>   nodeWindowAgg.c to follow PostgreSQL coding convention.

Thanks.

> nocfbot-0002: Fix RPR reluctant quantifier flag lost during VIEW
> serialization
> 
>   The reluctant flag on quantifiers was lost when a VIEW containing
>   RPR was serialized and restored via ruleutils.c.  This patch fixes
>   gram.y, rpr.c, ruleutils.c, and parsenodes.h so the flag survives
>   the round-trip.

Great.

> nocfbot-0003: Expand RPR test coverage and improve test comments
> 
>   Reorganizes test cases across rpr.sql, rpr_base.sql, rpr_explain.sql,
>   and rpr_nfa.sql.  Moves base functionality tests from rpr.sql to
>   rpr_base.sql and NFA-specific tests to rpr_nfa.sql.  Adds better
>   section comments throughout.  Duplicate tests in rpr.sql were
>   removed.  No reduction in test coverage.

Sounds good.

> nocfbot-0004: Keep RPR test objects for pg_upgrade/pg_dump testing
> 
>   Adjusts rpr_base.sql and rpr_explain.sql so that test tables and
>   views are not dropped at the end of the test.  This allows
>   pg_upgrade and pg_dump regression testing to cover RPR objects.

Great.

> nocfbot-0005: Disable run condition pushdown for RPR windows
> 
>   Revised version of your run condition fix [1].  Existing test
>   expected output updated accordingly.

Thanks for including the patch.

> nocfbot-0006: Disable frame optimization for RPR windows
> 
>   Prevents the planner from optimizing the window frame for RPR
>   windows.  The frame clause in RPR has different semantics (it
>   bounds the pattern search space), so standard frame optimizations
>   must be disabled.  Adds EXPLAIN tests to verify.  Please review
>   this one -- it's a newly discovered issue.

Oh, this is a very important finding! I will definitely look into the
patch.

> nocfbot-0007: Add stock scenario tests for RPR pattern matching
> 
>   Adds stock trading scenario tests using realistic synthetic data
>   (stock.data with 1632 rows).  Tests V-shape recovery, W-shape,
>   consecutive rises, and other common pattern matching use cases.

Excellent.

> nocfbot-0008: Fix zero-min reluctant quantifier to produce zero-length match
> 
>   Fixes the bug reported by SungJun [2]: reluctant quantifiers with
>   min=0 (A*?, A??) were incorrectly consuming at least one row instead
>   of producing a zero-length match.  The NFA can now internally
>   distinguish between a zero-length match and no match, so it will
>   be ready when additional infrastructure (e.g. MATCH_NUMBER) is
>   added.  Now matches Oracle behavior.

Does "a zero-length match" mean "an empty match"?

BTW, currently we place all nfa_* functions at the bottom of
nodeWindowAgg.c.  However nodeWindowAgg.c in master branch places "API
exposed to window functions" at the bottom of the file. Do you think
we should follow the way?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi, Tatsuo

Does "a zero-length match" mean "an empty match"?

Yes, they refer to the same thing.  "Zero-length match" is the more
common term in general regex implementations (PCRE2, Perl, Python,
Java, etc.[1]), but the RPR standard (ISO/IEC 19075-5, Section 4.12.2)
uses "empty match" exclusively.

[1] https://www.regular-expressions.info/zerolength.html
 

BTW, currently we place all nfa_* functions at the bottom of
nodeWindowAgg.c.  However nodeWindowAgg.c in master branch places "API
exposed to window functions" at the bottom of the file. Do you think
we should follow the way?

Yes, we should follow master's convention.  I see three options:

  (a) Reorder within nodeWindowAgg.c: move the nfa_* functions up and
      keep the "API exposed to window functions" section at the bottom,
      matching master's layout.

  (b) Separate file under src/backend/executor/, keeping it close to
      nodeWindowAgg.c while making the boundary explicit.

  (c) A dedicated src/backend/rpr/ directory modeled on
      src/backend/regex/, giving the NFA engine its own namespace.
      This could also be an opportunity to consolidate the existing
      src/backend/optimizer/plan/rpr.c into the same directory.

For now (a) is the safest change.  Longer term, (b) or (c) would make
more sense -- especially when we extend to MATCH_RECOGNIZE (R010),
where the NFA engine will need to be shared across both code paths.
Either way, the NFA engine can be exposed via a header so that R010
can share it without further restructuring.

Since the NFA algorithm is not familiar territory for most DBMS
developers, it would also be worth preserving the detailed algorithm
description posted earlier in this thread -- either as structured
comments or as a dedicated README alongside the code.

What do you think?  Should we start with (a) now and revisit the
broader restructuring approaches -- (b) or (c) -- later, or would you
prefer to discuss them first?  Either of those would also resolve the
file layout convention issue naturally, since new files would follow
proper conventions from the start.


One more thing: there are no ECPG example programs or regression tests
for RPR yet.  I'd like to propose adding them.  Shall I draft an
initial set, or would you prefer to coordinate with the ECPG
maintainers first?


Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi, Tatsuo
> 
> Does "a zero-length match" mean "an empty match"?
>>
> 
> Yes, they refer to the same thing.  "Zero-length match" is the more
> common term in general regex implementations (PCRE2, Perl, Python,
> Java, etc.[1]), but the RPR standard (ISO/IEC 19075-5, Section 4.12.2)
> uses "empty match" exclusively.
> 
> [1] https://www.regular-expressions.info/zerolength.html

I found Trino uses "empty match" too [2]. So for SQL users, I guess
"empty match" is more familiar wording.

> Yes, we should follow master's convention.  I see three options:
> 
>   (a) Reorder within nodeWindowAgg.c: move the nfa_* functions up and
>       keep the "API exposed to window functions" section at the bottom,
>       matching master's layout.
> 
>   (b) Separate file under src/backend/executor/, keeping it close to
>       nodeWindowAgg.c while making the boundary explicit.
> 
>   (c) A dedicated src/backend/rpr/ directory modeled on
>       src/backend/regex/, giving the NFA engine its own namespace.
>       This could also be an opportunity to consolidate the existing
>       src/backend/optimizer/plan/rpr.c into the same directory.
> 
> For now (a) is the safest change.  Longer term, (b) or (c) would make
> more sense -- especially when we extend to MATCH_RECOGNIZE (R010),
> where the NFA engine will need to be shared across both code paths.
> Either way, the NFA engine can be exposed via a header so that R010
> can share it without further restructuring.
> 
> Since the NFA algorithm is not familiar territory for most DBMS
> developers, it would also be worth preserving the detailed algorithm
> description posted earlier in this thread -- either as structured
> comments or as a dedicated README alongside the code.
> 
> What do you think?  Should we start with (a) now and revisit the
> broader restructuring approaches -- (b) or (c) -- later, or would you
> prefer to discuss them first?  Either of those would also resolve the
> file layout convention issue naturally, since new files would follow
> proper conventions from the start.

I prefer (a) or (b) for now, at least for the first commit. The reason
is, current nfa functions take a WindowAggState argument. If we prefer
(c), I think we need to change some of (or most of) nfa functions so
that they do not take the WindowAggState argument. What do you think?

> One more thing: there are no ECPG example programs or regression tests
> for RPR yet.  I'd like to propose adding them.  Shall I draft an
> initial set, or would you prefer to coordinate with the ECPG
> maintainers first?

I am not familiar with ECPG. Do you know if ECPG has Window clause
tests? If ECPG does not have any Window clause tests, is it worth to
add RPR tests to ECPG?

[2] https://trino.io/docs/current/sql/match-recognize.html#evaluating-expressions-in-empty-matches-and-unmatched-rows

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

I found Trino uses "empty match" too [2]. So for SQL users, I guess
"empty match" is more familiar wording.

Agreed.  Since RPR is a feature defined by the SQL standard, using the
standard's own terminology is the right choice: it lets users
cross-reference the specification directly.  That said, "zero-length
match" is widely used in the regex literature (PCRE2, Perl, Python,
Java, etc.), so developers researching the topic should treat the two
terms as synonymous.  In the SQL context, "empty match" is the preferred term.

 
>   (a) Reorder within nodeWindowAgg.c: move the nfa_* functions up and
>       keep the "API exposed to window functions" section at the bottom,
>       matching master's layout.
>
>   (b) Separate file under src/backend/executor/, keeping it close to
>       nodeWindowAgg.c while making the boundary explicit.
>
>   (c) A dedicated src/backend/rpr/ directory modeled on
>       src/backend/regex/, giving the NFA engine its own namespace.
>       This could also be an opportunity to consolidate the existing
>       src/backend/optimizer/plan/rpr.c into the same directory.

I prefer (a) or (b) for now, at least for the first commit. The reason
is, current nfa functions take a WindowAggState argument. If we prefer
(c), I think we need to change some of (or most of) nfa functions so
that they do not take the WindowAggState argument. What do you think?
 
That is a valid concern.  (c) will be necessary in the long run, but
MATCH_RECOGNIZE (R010) is not yet on the horizon, and restructuring the
NFA layer now -- before that requirement is concrete -- carries a real
risk of introducing defects during the refactoring.  The risks outweigh the
benefits at this stage.

Instead, I'll try (b): a separate file under src/backend/executor/
can retain the WindowAggState argument while making the NFA boundary
explicit, and the change is still reviewable.  If (b) turns out to be
harder than expected or surfaces unexpected issues, I'll fall back to
(a).

If (b) works out, I'll add a structured header comment to the new file
to preserve the algorithm description for future reviewers.


I am not familiar with ECPG. Do you know if ECPG has Window clause
tests? If ECPG does not have any Window clause tests, is it worth to
add RPR tests to ECPG?
 
I checked src/interfaces/ecpg/test/ and confirmed there are no Window
clause tests there at all.  If ECPG has no Window clause coverage, I
see no reason to add RPR tests there at this stage.  I think it would be better to leave ECPG tests out of this patch set for now.


Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> nocfbot-0006: Disable frame optimization for RPR windows
>> 
>>   Prevents the planner from optimizing the window frame for RPR
>>   windows.  The frame clause in RPR has different semantics (it
>>   bounds the pattern search space), so standard frame optimizations
>>   must be disabled.  Adds EXPLAIN tests to verify.  Please review
>>   this one -- it's a newly discovered issue.
> 
> Oh, this is a very important finding! I will definitely look into the
> patch.

As I promised, I looked into nocfbot-0006 and it is good to me.

While at it, I looked around optimize_window_clauses and encountered
this:
				/*
				 * Perform the same duplicate check that is done in
				 * transformWindowFuncCall.
				 */
				if (equal(wc->partitionClause, existing_wc->partitionClause) &&
					equal(wc->orderClause, existing_wc->orderClause) &&
					wc->frameOptions == existing_wc->frameOptions &&
					equal(wc->startOffset, existing_wc->startOffset) &&
					equal(wc->endOffset, existing_wc->endOffset))

It looks like it missed the check for DEINFE and PATTERN clause but
with your patch, if RPR is defined we do not come here anyway. So, I
looked in transformWindowFuncCall (parse_agg.c) as it mentioned in the
comment above and I found this:

			/*
			 * Also see similar de-duplication code in optimize_window_clauses
			 */
			if (equal(refwin->partitionClause, windef->partitionClause) &&
				equal(refwin->orderClause, windef->orderClause) &&
				refwin->frameOptions == windef->frameOptions &&
				equal(refwin->startOffset, windef->startOffset) &&
				equal(refwin->endOffset, windef->endOffset))

This basically combines a window definition without window name into
an existing window definition if they shar the identical window
definition. For example:

CREATE TEMP TABLE rpr_copy (id INT, val INT);
INSERT INTO rpr_copy VALUES (1, 10), (2, 20), (3, 30), (4, 40);
SELECT id, val, first_value(id) OVER (
       ORDER BY id
       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
), first_value(id) OVER w1
FROM rpr_copy
WINDOW w1 AS (
       ORDER BY id
       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
       PATTERN (A+)
       DEFINE A AS val > 10
);

The two window definitions are regarded as identical and produces
wrong result.

 id | val | first_value | first_value 
----+-----+-------------+-------------
  1 |  10 |             |            
  2 |  20 |           2 |           2
  3 |  30 |             |            
  4 |  40 |             |            
(4 rows)

Of course proper result is:

 id | val | first_value | first_value 
----+-----+-------------+-------------
  1 |  10 |           1 |            
  2 |  20 |           2 |           2
  3 |  30 |           3 |            
  4 |  40 |           4 |            
(4 rows)

Explain result:

                                   QUERY PLAN                                   
--------------------------------------------------------------------------------
 WindowAgg  (cost=209.33..215.01 rows=2260 width=17)
   Window: w1 AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
   Pattern: a+"
   ->  Sort  (cost=158.51..164.16 rows=2260 width=8)
         Sort Key: id
         ->  Seq Scan on rpr_copy  (cost=0.00..32.60 rows=2260 width=8)
(6 rows)

The two window definitions are unified into w1, which has the RPR
part, which is wrong.  To fix this, we need to check the RPR part
while unifying the window definitions. Attached patch does it (on top
of v44).

Question is, should we fix optimize_window_clause as well? As I
mentioned earlier, with Henson's fix it does not produce any bug at
this moment. However, we may want to fix for code consistency.  Not
fixing it will break the comment.

Thoughts?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index 81e1d70ffc1..5e942075444 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -1110,7 +1110,8 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
 				equal(refwin->orderClause, windef->orderClause) &&
 				refwin->frameOptions == windef->frameOptions &&
 				equal(refwin->startOffset, windef->startOffset) &&
-				equal(refwin->endOffset, windef->endOffset))
+				equal(refwin->endOffset, windef->endOffset) &&
+				equal(refwin->rpCommonSyntax, windef->rpCommonSyntax))
 			{
 				/* found a duplicate window specification */
 				wfunc->winref = winref;

Re: Row pattern recognition

Hi Tatsuo,

> Question is, should we fix optimize_window_clause as well?

Yes, we should. The comment in optimize_window_clauses explicitly
states "Perform the same duplicate check that is done in
transformWindowFuncCall", so the two checks must remain in sync.
Even if omitting the RPR fields produces no visible bug today (because
the early return guard in nocfbot-0006 already skips RPR windows), the
code would be misleading and fragile: a future change could remove
that guard and silently reintroduce the bug.

Adding the RPR fields explicitly also serves as defensive coding and
makes the intent clear to anyone reading or modifying the code later.

When incorporating nocfbot-0006 as patch 06/12, this fix was included:

    wc->rpSkipTo == existing_wc->rpSkipTo &&
    wc->initial == existing_wc->initial &&
    equal(wc->defineClause, existing_wc->defineClause) &&
    equal(wc->rpPattern, existing_wc->rpPattern)

Patch 06/12 now covers both the frame optimization guard and the
optimize_window_clauses deduplication fix, with EXPLAIN-based regression
tests added to verify the behavior.

> The two window definitions are regarded as identical and produces
> wrong result.

Thank you for finding this. Your patch has been incorporated as patch
09/12 ("Fix window deduplication for RPR windows at parse time"),
modified to add regression test cases covering the scenario. The fix
adds the missing RPR check in transformWindowFuncCall:

    equal(refwin->rpCommonSyntax, windef->rpCommonSyntax)

This prevents incorrect merging of an RPR window with a non-RPR window
that has identical frame options.

The previous submission (nocfbot-0001..0008) has been extended to
12 patches. Changes since the last submission:

  06/12  Disable frame optimization for RPR windows  [updated]
         optimize_window_clauses deduplication fix added, as discussed.

  09/12  Fix window deduplication for RPR windows at parse time  [new]
         Incorporates your fix with test cases added.

  10/12  Walk DEFINE clause in window tree traversal  [new]
         A newly discovered issue: nodeFuncs.c was not visiting the
         DEFINE clause in expression_tree_walker, query_tree_walker,
         and their mutator counterparts. The demonstrated case is SQL
         function inlining: a SQL function with a parameter used in
         DEFINE (e.g., DEFINE A AS v > $1) would fail to substitute
         the actual argument, producing wrong results.

  11/12  Use SQL standard term "empty match" in RPR comments  [new]
         Align NFA comment terminology with the SQL standard: replace
         implementation-specific terms "zero-length match" and
         "zero-consumption" with the standard term "empty match".

  12/12  Extract RPR NFA engine into execRPR.c  [new]
         Following the earlier discussion about file layout, this
         implements option (b): move the NFA engine to a dedicated
         src/backend/executor/execRPR.c, keeping it close to
         nodeWindowAgg.c while making the boundary explicit. Functions
         still take WindowAggState as an argument (no signature change).
         The public interface is declared in execRPR.h using the ExecRPR*
         naming convention, consistent with other executor headers.
         The NFA algorithm guide shared earlier in this thread has also
         been incorporated as structured comments at the top of the file,
         as suggested.

The full updated series (12 patches on top of v44) is attached.

Regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> Question is, should we fix optimize_window_clause as well?
> 
> Yes, we should. The comment in optimize_window_clauses explicitly
> states "Perform the same duplicate check that is done in
> transformWindowFuncCall", so the two checks must remain in sync.
> Even if omitting the RPR fields produces no visible bug today (because
> the early return guard in nocfbot-0006 already skips RPR windows), the
> code would be misleading and fragile: a future change could remove
> that guard and silently reintroduce the bug.
> 
> Adding the RPR fields explicitly also serves as defensive coding and
> makes the intent clear to anyone reading or modifying the code later.

Agreed.

> When incorporating nocfbot-0006 as patch 06/12, this fix was included:
> 
>     wc->rpSkipTo == existing_wc->rpSkipTo &&
>     wc->initial == existing_wc->initial &&
>     equal(wc->defineClause, existing_wc->defineClause) &&
>     equal(wc->rpPattern, existing_wc->rpPattern)
> 
> Patch 06/12 now covers both the frame optimization guard and the
> optimize_window_clauses deduplication fix, with EXPLAIN-based regression
> tests added to verify the behavior.

Good.

> Thank you for finding this. Your patch has been incorporated as patch
> 09/12 ("Fix window deduplication for RPR windows at parse time"),
> modified to add regression test cases covering the scenario. The fix
> adds the missing RPR check in transformWindowFuncCall:
> 
>     equal(refwin->rpCommonSyntax, windef->rpCommonSyntax)
> 
> This prevents incorrect merging of an RPR window with a non-RPR window
> that has identical frame options.

Good.

> The previous submission (nocfbot-0001..0008) has been extended to
> 12 patches. Changes since the last submission:
> 
>   06/12  Disable frame optimization for RPR windows  [updated]
>          optimize_window_clauses deduplication fix added, as discussed.
>
>   09/12  Fix window deduplication for RPR windows at parse time  [new]
>          Incorporates your fix with test cases added.

Thanks for adding test cases.

>   10/12  Walk DEFINE clause in window tree traversal  [new]
>          A newly discovered issue: nodeFuncs.c was not visiting the
>          DEFINE clause in expression_tree_walker, query_tree_walker,
>          and their mutator counterparts. The demonstrated case is SQL
>          function inlining: a SQL function with a parameter used in
>          DEFINE (e.g., DEFINE A AS v > $1) would fail to substitute
>          the actual argument, producing wrong results.

Excellnt findings!  BTW, I realized that we cannot use $1 of function
in PATTERN clause like: A{$1}.

ERROR:  42601: syntax error at or near "$1"
LINE 10:         PATTERN (A{$1})
                            ^
LOCATION:  scanner_yyerror, scan.l:1211

Should we document somewhere?

>   11/12  Use SQL standard term "empty match" in RPR comments  [new]
>          Align NFA comment terminology with the SQL standard: replace
>          implementation-specific terms "zero-length match" and
>          "zero-consumption" with the standard term "empty match".

Ok.

>   12/12  Extract RPR NFA engine into execRPR.c  [new]
>          Following the earlier discussion about file layout, this
>          implements option (b): move the NFA engine to a dedicated
>          src/backend/executor/execRPR.c, keeping it close to
>          nodeWindowAgg.c while making the boundary explicit. Functions
>          still take WindowAggState as an argument (no signature change).
>          The public interface is declared in execRPR.h using the ExecRPR*
>          naming convention, consistent with other executor headers.
>          The NFA algorithm guide shared earlier in this thread has also
>          been incorporated as structured comments at the top of the file,
>          as suggested.

Excellent work! Now the exported NFA engine API is cleary separated
from NFA internal static fnctions, which greatly enhances the
readability.

> The full updated series (12 patches on top of v44) is attached.

Thank you! Patch applied cleanly and passed all the regression tests.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,
 
>   10/12  Walk DEFINE clause in window tree traversal  [new]
>          A newly discovered issue: nodeFuncs.c was not visiting the
>          DEFINE clause in expression_tree_walker, query_tree_walker,
>          and their mutator counterparts. The demonstrated case is SQL
>          function inlining: a SQL function with a parameter used in
>          DEFINE (e.g., DEFINE A AS v > $1) would fail to substitute
>          the actual argument, producing wrong results.

Excellnt findings!  BTW, I realized that we cannot use $1 of function
in PATTERN clause like: A{$1}.

ERROR:  42601: syntax error at or near "$1"
LINE 10:         PATTERN (A{$1})
                            ^
LOCATION:  scanner_yyerror, scan.l:1211

Should we document somewhere?

The PATTERN quantifier {n} only accepts Iconst (integer literal) in the
grammar.  When a host variable or function parameter is used (e.g.,
A{$1}), the user gets a generic syntax error.

Oracle accepts broader syntax and validates later, producing an error
at a later stage rather than a syntax error at parse time.

PostgreSQL itself already has precedent for this pattern -- in fact,
within the same window clause, frame offset (ROWS/RANGE/GROUPS) accepts
a_expr in the grammar and then rejects variables in parse analysis via
transformFrameOffset() -> checkExprIsVarFree().

I'd lean against documenting this.  The SQL standard already defines
the quantifier bound as <unsigned integer literal>, so there is nothing
beyond the standard to call out, and documenting what is *not* allowed
tends to raise questions that wouldn't otherwise occur to users.

Rather, I think accepting a broader grammar and validating later would
be the more appropriate response, producing a descriptive error like:

  "argument of bounded quantifier must be an integer literal"

I can either include this in the current patch set or handle it as a
separate follow-up after the main series is committed.  What do you
think?

Regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> Excellnt findings!  BTW, I realized that we cannot use $1 of function
>> in PATTERN clause like: A{$1}.
>>
>> ERROR:  42601: syntax error at or near "$1"
>> LINE 10:         PATTERN (A{$1})
>>                             ^
>> LOCATION:  scanner_yyerror, scan.l:1211
>>
>> Should we document somewhere?
>>
> 
> The PATTERN quantifier {n} only accepts Iconst (integer literal) in the
> grammar.  When a host variable or function parameter is used (e.g.,
> A{$1}), the user gets a generic syntax error.

Ok.

> Oracle accepts broader syntax and validates later, producing an error
> at a later stage rather than a syntax error at parse time.
> 
> PostgreSQL itself already has precedent for this pattern -- in fact,
> within the same window clause, frame offset (ROWS/RANGE/GROUPS) accepts
> a_expr in the grammar and then rejects variables in parse analysis via
> transformFrameOffset() -> checkExprIsVarFree().
> 
> I'd lean against documenting this.  The SQL standard already defines
> the quantifier bound as , so there is nothing
> beyond the standard to call out, and documenting what is *not* allowed
> tends to raise questions that wouldn't otherwise occur to users.
> 
> Rather, I think accepting a broader grammar and validating later would
> be the more appropriate response, producing a descriptive error like:
> 
>   "argument of bounded quantifier must be an integer literal"
> 
> I can either include this in the current patch set or handle it as a
> separate follow-up after the main series is committed.  What do you
> think?

I think handing it as a separate follow-up after the commit is enough
unless other developers complain.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
SungJun Jang <sjjang112233@gmail.com>
Дата:
Hi hackers,

I ran a cross-validation test comparing PostgreSQL RPR (current patch) and Trino MATCH_RECOGNIZE to verify both result correctness and performance characteristics across different scales.

The dataset consists of two segments where rows are arranged sequentially as:

A → B → C → D

Each segment contains a fixed distribution of categories A/B/C/D. Category E does not exist in the dataset and is used to test match failure behavior.

Test scales ranged from 20,000 to 100,000 rows.

All tests were executed using:

AFTER MATCH SKIP PAST LAST ROW

Test Environment

Item        | PostgreSQL              | Trino
------------+-------------------------+-----------------------
Version     | 19devel (RPR patch)    | 471
Runtime     | Local                  | Local Docker container
Platform    | Linux x86_64           | Linux x86_64
RPR syntax  | WINDOW clause          | MATCH_RECOGNIZE

Dataset Structure

Each segment contains sequential categories:

A : ~1/3 of rows
B : ~1/3 of rows
C : ~1/3 of rows
D : 1 row

Example at 1x scale:

Segment size : 10,000 rows
Total rows : 20,000

Test Cases

Test 1
Pattern:
PATTERN (A+ B+ C+ D)

Expected result:
1 match per segment (2 total)

Reason:
Data is arranged exactly as A → B → C → D.

Test 2
Pattern:
PATTERN (A+ B+ C+ E)

Expected result:
0 rows (no match)

Reason:
Category E does not exist in the dataset.

Correctness Results

Across all scales both systems returned identical results.

Test 1 → 1 match per segment (2 total)
Test 2 → 0 rows

Performance Results

Scale | Total Rows | PG Test1 | PG Test2 | Trino Test1 | Trino Test2
------+------------+----------+----------+-------------+-------------
1x    |  20,000    | 19 ms    | 17 ms    | ~0.3 s      | ~358 s
2x    |  40,000    | 37 ms    | 37 ms    | ~0.8 s      | ~1,364 s
3x    |  60,000    | 57 ms    | 51 ms    | ~1.5 s      | ~4,424 s
4x    |  80,000    | 73 ms    | 68 ms    | ~2.3 s      | ~9,989 s
5x    | 100,000    | 99 ms    | 92 ms    | ~3.3 s      | ~20,014 s

Note:
Trino measurements are adjusted to remove JVM startup overhead (~2.4s measured via SELECT 1).

Observations

Match success (Test 1)

Both systems scale approximately linearly because the entire segment is consumed in a single pass after a successful match.

PostgreSQL shows lower absolute latency.

Match failure (Test 2)

PostgreSQL maintains near-linear scaling.

This appears to be due to its NFA implementation combined with Context Absorption, which discards redundant matching contexts when they reach the same NFA state but start later in the input.

Example:

Ctx1 start=0 length=2
Ctx2 start=1 length=1

Ctx1 subsumes Ctx2, so Ctx2 is discarded.

This keeps the number of active contexts small and prevents quadratic growth.

Measured scaling:

17 ms → 92 ms (1x → 5x)

which is consistent with O(n).

Trino also uses an NFA approach but appears to lack Context Absorption or a similar optimization.

As a result, it explores matching contexts from all possible start positions, leading to rapidly increasing backtracking cost.

Measured scaling:

358 s → 20,014 s (1x → 5x)

This exceeds theoretical O(n²) growth and appears closer to O(n²)–O(n³) in practice, likely compounded by JVM memory and GC overhead.

Summary

Correctness

PostgreSQL RPR and Trino MATCH_RECOGNIZE produce identical matching results across all tested scales.

Performance

Match success:
Both systems scale roughly linearly.

Match failure:
PostgreSQL maintains O(n) scaling while Trino shows O(n²) or worse behavior.

At the largest tested scale:

PostgreSQL : ~92 ms
Trino : ~20,014 s (≈ 5.6 hours)

PostgreSQL is therefore approximately 217,000× faster in this scenario.

Conclusion

Both systems use NFA-based pattern matching.

The key difference appears to be Context Absorption in PostgreSQL, which removes redundant matching contexts and guarantees linear scaling even when patterns fail to match.

This optimization prevents the non-linear performance degradation typically associated with row pattern recognition.

Best regards

SungJun

2026년 3월 9일 (월) PM 2:22, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Hi Henson,

>> Excellnt findings!  BTW, I realized that we cannot use $1 of function
>> in PATTERN clause like: A{$1}.
>>
>> ERROR:  42601: syntax error at or near "$1"
>> LINE 10:         PATTERN (A{$1})
>>                             ^
>> LOCATION:  scanner_yyerror, scan.l:1211
>>
>> Should we document somewhere?
>>
>
> The PATTERN quantifier {n} only accepts Iconst (integer literal) in the
> grammar.  When a host variable or function parameter is used (e.g.,
> A{$1}), the user gets a generic syntax error.

Ok.

> Oracle accepts broader syntax and validates later, producing an error
> at a later stage rather than a syntax error at parse time.
>
> PostgreSQL itself already has precedent for this pattern -- in fact,
> within the same window clause, frame offset (ROWS/RANGE/GROUPS) accepts
> a_expr in the grammar and then rejects variables in parse analysis via
> transformFrameOffset() -> checkExprIsVarFree().
>
> I'd lean against documenting this.  The SQL standard already defines
> the quantifier bound as <unsigned integer literal>, so there is nothing
> beyond the standard to call out, and documenting what is *not* allowed
> tends to raise questions that wouldn't otherwise occur to users.
>
> Rather, I think accepting a broader grammar and validating later would
> be the more appropriate response, producing a descriptive error like:
>
>   "argument of bounded quantifier must be an integer literal"
>
> I can either include this in the current patch set or handle it as a
> separate follow-up after the main series is committed.  What do you
> think?

I think handing it as a separate follow-up after the commit is enough
unless other developers complain.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi SungJun,

> Hi hackers,
> 
> I ran a cross-validation test comparing PostgreSQL RPR (current patch) and
> Trino MATCH_RECOGNIZE to verify both result correctness and performance
> characteristics across different scales.

Thank you for the excellent report! I am glad to see that PostgreSQL
RPR is much faster than Trino, especially in the match failure cases.

Is it possible to share the data generation script and the query for
PostgreSQL so that I could locally perform the tests?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi SungJun,

Thanks for the cross-validation report.

This appears to be due to its NFA implementation combined with Context Absorption, 
which discards redundant matching contexts when they reach the same NFA state 
but start later in the input.

Example:

Ctx1 start=0 length=2
Ctx2 start=1 length=1

Ctx1 subsumes Ctx2, so Ctx2 is discarded.

This keeps the number of active contexts small and prevents quadratic growth.

Your description is accurate. An earlier-started context subsumes
all matches of a later-started context (monotonicity principle),
so the newer one can be safely removed.

However, Context Absorption is not universally applicable. It
requires careful analysis of several factors, and we continue to
refine the conditions under which absorption can be safely applied.

The current scope of absorption is determined by three factors:

1. Pattern structure:
   Currently supported:
   - Simple unbounded quantifiers: A+, (A B)+
   - Leading unbounded quantifier in group: (A+ B)+
   - First iteration of nested unbounded alternation (e.g., ((A+)|(B+))+)
   Planned improvements:
   - Patterns with a prefix before the repeating group (e.g., A (B+) C)
   - Fixed-length iteration groups (e.g., (A B{2})+ where each
     iteration consumes exactly 3 rows)

2. Frame specification:
   - AFTER MATCH SKIP TO NEXT ROW is not eligible (only
     SKIP PAST LAST ROW)
   - Frame end must be UNBOUNDED FOLLOWING

3. DEFINE clause evaluation:
   - Absorption relies on the monotonicity assumption that DEFINE
     conditions produce the same result regardless of starting
     position. Currently DEFINE uses simple boolean conditions
     where this holds. However, future additions such as
     CLASSIFIER() or running aggregates (e.g., RUNNING SUM())
     may introduce context-dependent evaluation that breaks
     this invariance, requiring absorption to be disabled for
     those cases.

That said, many practically useful patterns fall within these
conditions. Here are examples from our regression tests using
synthetic stock data:

  V-shape recovery (decline then rise):
    PATTERN (DECLINE{4,} RISE{4,})
    DEFINE
      DECLINE AS price < PREV(price),
      RISE AS price > PREV(price)

  W-bottom (decline, bounce, re-decline, recovery):
    PATTERN (DECLINE{3,} BOUNCE{3,} DIP{3,} RECOVER{3,})
    DEFINE
      DECLINE AS price < PREV(price),
      BOUNCE AS price > PREV(price),
      DIP AS price < PREV(price),
      RECOVER AS price > PREV(price)

  Consolidation then breakout:
    PATTERN (FLAT{5,} BREAKOUT)
    DEFINE
      FLAT AS price BETWEEN PREV(price) * 0.98 AND PREV(price) * 1.02,
      BREAKOUT AS price > PREV(price) * 1.05

  Price-volume divergence (bearish signal):
    PATTERN (INIT DIVERGE{3,})
    DEFINE
      DIVERGE AS price > PREV(price) AND volume < PREV(volume)

  Volume climax reversal:
    PATTERN (RALLY{3,} CLIMAX SELLOFF{2,})
    DEFINE
      RALLY AS price > PREV(price),
      CLIMAX AS volume > PREV(volume) * 1.5,
      SELLOFF AS price < PREV(price)

All of these use unbounded quantifiers with position-invariant
DEFINE conditions -- exactly the cases where Context Absorption
guarantees O(n) scaling. So despite the constraints, it remains
a powerful optimization for the workloads where RPR is most
commonly applied.

Best regards,
Henson 

Re: Row pattern recognition

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello

+ /*
+ * Make sure that the row pattern definition search condition is a boolean
+ * expression.
+ */
+ foreach_ptr(TargetEntry, te, defineClause)
+ (void) coerce_to_boolean(pstate, (Node *) te->expr, "DEFINE");

Isn't this incorrect? I think it should update te->expr, as currently
it is possible to construct queries where this produces unexpected
results.

CREATE TYPE truthyint AS (v int);

CREATE FUNCTION truthyint_to_bool(truthyint) RETURNS boolean AS $$
  SELECT ($1).v <> 0;
$$ LANGUAGE SQL IMMUTABLE STRICT;

CREATE CAST (truthyint AS boolean)
  WITH FUNCTION truthyint_to_bool(truthyint)
  AS ASSIGNMENT;

CREATE TABLE test_coerce (id serial, val truthyint);
INSERT INTO test_coerce VALUES
  (1, ROW(1)),
  (2, ROW(0)),
  (3, ROW(5)),
  (4, ROW(0));

SELECT id, val, COUNT(*) OVER w AS cnt
FROM test_coerce
WINDOW w AS (
    ORDER BY id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+)
    DEFINE A AS val
)
ORDER BY id;

Same query provides the correct result with a table that has an actual
boolean column.


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Zsolt, Tatsuo,

+ foreach_ptr(TargetEntry, te, defineClause)
+ (void) coerce_to_boolean(pstate, (Node *) te->expr, "DEFINE");

Isn't this incorrect? I think it should update te->expr, as currently
it is possible to construct queries where this produces unexpected
results.

Good catch, Zsolt. You're right — the return value of
coerce_to_boolean() must be assigned back to te->expr, otherwise
any implicit cast (e.g., a user-defined type with an assignment
cast to boolean) is silently discarded.

The fix is straightforward:

    foreach_ptr(TargetEntry, te, defineClause)
        te->expr = (Expr *) coerce_to_boolean(pstate, (Node *) te->expr, "DEFINE");

I've confirmed that your example query produces incorrect results
without the fix (the truthyint value is evaluated as-is without
the cast) and correct results with it.

Patch 13 is attached with the fix and a regression test case based
on your example.

By the way, thank you for joining the TDE hooks discussion when
I was just getting started as a contributor — that meant a lot.
Great work on pg_tde at Percona, and rooting for the extensible
SMGR effort as well. Hope it's all going well!

Tatsuo, please review when you get a chance.

Regards,
Henson
 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Zsolt,

Thanks for the report and the test case!

> Good catch, Zsolt. You're right ― the return value of
> coerce_to_boolean() must be assigned back to te->expr, otherwise
> any implicit cast (e.g., a user-defined type with an assignment
> cast to boolean) is silently discarded.
> 
> The fix is straightforward:
> 
>     foreach_ptr(TargetEntry, te, defineClause)
>         te->expr = (Expr *) coerce_to_boolean(pstate, (Node *) te->expr,
> "DEFINE");
> 
> I've confirmed that your example query produces incorrect results
> without the fix (the truthyint value is evaluated as-is without
> the cast) and correct results with it.
> 
> Patch 13 is attached with the fix and a regression test case based
> on your example.

Yeah, current patch needs to be fixed. Question is, the output of the
expression of DEFINE clause must be a strict boolean or, it is allowed
to accept an expression coercive to boolean?

If we prefer the former, we should use exprType() instead.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:


2026년 3월 12일 (목) AM 9:21, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Hi Zsolt,

Thanks for the report and the test case!

> Good catch, Zsolt. You're right ― the return value of
> coerce_to_boolean() must be assigned back to te->expr, otherwise
> any implicit cast (e.g., a user-defined type with an assignment
> cast to boolean) is silently discarded.
>
> The fix is straightforward:
>
>     foreach_ptr(TargetEntry, te, defineClause)
>         te->expr = (Expr *) coerce_to_boolean(pstate, (Node *) te->expr,
> "DEFINE");
>
> I've confirmed that your example query produces incorrect results
> without the fix (the truthyint value is evaluated as-is without
> the cast) and correct results with it.
>
> Patch 13 is attached with the fix and a regression test case based
> on your example.

Yeah, current patch needs to be fixed. Question is, the output of the
expression of DEFINE clause must be a strict boolean or, it is allowed
to accept an expression coercive to boolean?

If we prefer the former, we should use exprType() instead.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Sorry about the empty reply — sent it by accident.

Yeah, current patch needs to be fixed. Question is, the output of the
expression of DEFINE clause must be a strict boolean or, it is allowed
to accept an expression coercive to boolean?

If we prefer the former, we should use exprType() instead.

Good question. Both the SQL standard and PostgreSQL's existing
behavior point toward allowing coercion.

In the SQL standard (ISO/IEC 19075-5), DEFINE specifies a "Boolean
condition" for each pattern variable. The standard does not suggest
a stricter type requirement on DEFINE than on other boolean contexts
like WHERE or HAVING.

PostgreSQL's WHERE clause already accepts implicit casts to boolean
via coerce_to_boolean(). You can verify this with Zsolt's setup:

    CREATE TYPE truthyint AS (v int);
    CREATE FUNCTION truthyint_to_bool(truthyint) RETURNS boolean AS $$
      SELECT ($1).v <> 0;
    $$ LANGUAGE SQL IMMUTABLE STRICT;
    CREATE CAST (truthyint AS boolean)
      WITH FUNCTION truthyint_to_bool(truthyint)
      AS ASSIGNMENT;

    CREATE TABLE test_coerce (id serial, val truthyint);
    INSERT INTO test_coerce VALUES
      (1, ROW(1)), (2, ROW(0)), (3, ROW(5)), (4, ROW(0));

    SELECT id, val FROM test_coerce WHERE val ORDER BY id;
    -- returns rows 1 and 3 (where val casts to true)

As Zsolt noted, the same query works correctly with an actual
boolean column. The issue is specifically that the implicit cast
is not being applied.

All other boolean contexts in the parser (WHERE, HAVING, JOIN/ON,
WHEN, etc.) use coerce_to_boolean() and assign the result back.
I think DEFINE should be consistent with these — it would be
surprising if `DEFINE A AS val` rejected a type that `WHERE val`
accepts.

Regards,
Henson
 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Yeah, current patch needs to be fixed. Question is, the output of the
>> expression of DEFINE clause must be a strict boolean or, it is allowed
>> to accept an expression coercive to boolean?
>>
>> If we prefer the former, we should use exprType() instead.
>>
> 
> Good question. Both the SQL standard and PostgreSQL's existing
> behavior point toward allowing coercion.
> 
> In the SQL standard (ISO/IEC 19075-5), DEFINE specifies a "Boolean
> condition" for each pattern variable. The standard does not suggest
> a stricter type requirement on DEFINE than on other boolean contexts
> like WHERE or HAVING.
> 
> PostgreSQL's WHERE clause already accepts implicit casts to boolean
> via coerce_to_boolean(). You can verify this with Zsolt's setup:
> 
>     CREATE TYPE truthyint AS (v int);
>     CREATE FUNCTION truthyint_to_bool(truthyint) RETURNS boolean AS $$
>       SELECT ($1).v <> 0;
>     $$ LANGUAGE SQL IMMUTABLE STRICT;
>     CREATE CAST (truthyint AS boolean)
>       WITH FUNCTION truthyint_to_bool(truthyint)
>       AS ASSIGNMENT;
> 
>     CREATE TABLE test_coerce (id serial, val truthyint);
>     INSERT INTO test_coerce VALUES
>       (1, ROW(1)), (2, ROW(0)), (3, ROW(5)), (4, ROW(0));
> 
>     SELECT id, val FROM test_coerce WHERE val ORDER BY id;
>     -- returns rows 1 and 3 (where val casts to true)
> 
> As Zsolt noted, the same query works correctly with an actual
> boolean column. The issue is specifically that the implicit cast
> is not being applied.
> 
> All other boolean contexts in the parser (WHERE, HAVING, JOIN/ON,
> WHEN, etc.) use coerce_to_boolean() and assign the result back.
> I think DEFINE should be consistent with these ― it would be
> surprising if `DEFINE A AS val` rejected a type that `WHERE val`
> accepts.

Ok. we should be consistent with WHERE etc. unless the standard
requres DEFINE stricter. But if the tle is in the target list
(possibly with resjunk attribute), it could be different from the one
in the DEFINE because of the casting by coerce_to_boolean(). i.e.:

- tle in the target list has no cast node
- tle in the DEFINE may have cast node

I don't know how this could affect subsequent RPR process but I would
like to keep the prerequisites that tle in DEINE and the traget list
is identical.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Thank you for your thoughtful feedback on the tle identity concern.

Ok. we should be consistent with WHERE etc. unless the standard
requres DEFINE stricter. But if the tle is in the target list
(possibly with resjunk attribute), it could be different from the one
in the DEFINE because of the casting by coerce_to_boolean(). i.e.:

- tle in the target list has no cast node
- tle in the DEFINE may have cast node

I don't know how this could affect subsequent RPR process but I would
like to keep the prerequisites that tle in DEINE and the traget list
is identical.

> is identical.

That is a very good point regarding tle identity.

On the implementation side, the DEFINE clause TargetEntries are
already deep-copied via copyObject in the parser (parse_rpr.c),
so adding a cast node to the DEFINE tle does not affect the
target list tle -- they are independent copies at that point.

On the semantic side, the two serve different purposes: the target
list produces output columns (where the user expects the original
type), while the DEFINE expression is evaluated as a boolean for
pattern matching. This is the same pattern as WHERE, where the
WHERE expression may carry a cast node but the target list for the
same column does not.

That said, if you would prefer to keep them structurally identical,
an alternative would be to reject non-boolean types in DEFINE with
a clear error (using exprType() check). However, this would be
stricter than WHERE/HAVING behavior, which might surprise users.

I would suggest that allowing coercion is the right choice for
consistency, but I am happy to go with whichever approach you
prefer.


On a separate topic, I have found a server crash bug in the current
PREV/NEXT implementation. Nesting navigation functions causes the
backend to crash:

    CREATE TABLE t (id int, price int);
    INSERT INTO t VALUES (1,10),(2,20),(3,15),(4,25),(5,30);

    SELECT * FROM t WINDOW w AS (
        ORDER BY id
        ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
        PATTERN (A B+)
        DEFINE B AS prev(prev(b.price)) > 0
    );
    -- server process crashes

The SQL standard (ISO/IEC 19075-5, Section 5.6.2) prohibits nesting
PREV/NEXT within PREV/NEXT. The first argument of PREV/NEXT must
contain a column reference, not another navigation function call.
Currently there is no parser-level check for this, so the nested
call passes through to the executor and crashes.

I have attached a test file (rpr_nav_nesting_test.txt) containing
6 test cases that cover the prohibited nesting patterns:

  - PREV(PREV(price))        direct same-kind nesting
  - NEXT(NEXT(price))        direct same-kind nesting
  - PREV(NEXT(price))        cross nesting
  - NEXT(PREV(price))        cross nesting
  - PREV(ABS(PREV(price)))   nesting hidden inside another function
  - NEXT(ABS(NEXT(price)))   nesting hidden inside another function

All of these currently crash the server. After a fix, they should
all produce a syntax error.


Finally, while reviewing the standard and the current
PREV/NEXT implementation, I have some thoughts on the
design.

The current approach uses all three ExprContext slots
(scan/outer/inner) with varno rewriting, which fixes offsets at
+/-1. The standard requires variable offsets like PREV(price, 3),
and the three-slot model cannot support this.

I think a simpler approach would be to use just one slot
(ecxt_outertuple) and swap it during expression evaluation:

  For `price > PREV(price, 2)`:
        ^^^^    ^^^^  ^^^^^
         |       |      |
         v       v      v
    1. [price]       read from current slot   --> datum_a
    2. [PREV( ,2)]   swap slot to (currentpos - 2)
    3.   [price]     read from swapped slot   --> datum_b
    4. [)]           restore slot
    5. [>]           evaluate datum_a > datum_b

Since step 1 already extracts the value as a Datum before the
swap in step 2, the result is safe. No varno rewriting is needed
-- all column reads just use the one slot, and the swap/restore
controls which row they see.

One thing I noticed is that the SQL standard explicitly requires
all column references inside a navigation function to be qualified
by the same row pattern variable (Section 5.2):

  "All row pattern column references in an aggregate or row
   pattern navigation operation are qualified by the same row
   pattern variable."

This means the navigation argument is always evaluated in a single
row context -- which is exactly what makes the one-slot swap model
work. It seems like the standard may have been designed with this
kind of implementation in mind.

With this approach, the existing varno rewriting infrastructure and
the extra slots for PREV/NEXT would no longer be needed, which
should simplify the code considerably.

I also believe this design would scale well to future extensions.
Variable offsets (PREV(price, N)) would work naturally, and when
we add FIRST/LAST navigation or row pattern variable qualifiers,
only the target row calculation would change -- the swap/restore
mechanism itself would remain the same.

What do you think about this approach?

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Thank you for your thoughtful feedback on the tle identity concern.
> 
> Ok. we should be consistent with WHERE etc. unless the standard
>> requres DEFINE stricter. But if the tle is in the target list
>> (possibly with resjunk attribute), it could be different from the one
>> in the DEFINE because of the casting by coerce_to_boolean(). i.e.:
>>
>> - tle in the target list has no cast node
>> - tle in the DEFINE may have cast node
>>
>> I don't know how this could affect subsequent RPR process but I would
>> like to keep the prerequisites that tle in DEINE and the traget list
>> is identical.
>>
> 
>> is identical.
> 
> That is a very good point regarding tle identity.
> 
> On the implementation side, the DEFINE clause TargetEntries are
> already deep-copied via copyObject in the parser (parse_rpr.c),
> so adding a cast node to the DEFINE tle does not affect the
> target list tle -- they are independent copies at that point.
> 
> On the semantic side, the two serve different purposes: the target
> list produces output columns (where the user expects the original
> type), while the DEFINE expression is evaluated as a boolean for
> pattern matching. This is the same pattern as WHERE, where the
> WHERE expression may carry a cast node but the target list for the
> same column does not.
> 
> That said, if you would prefer to keep them structurally identical,
> an alternative would be to reject non-boolean types in DEFINE with
> a clear error (using exprType() check). However, this would be
> stricter than WHERE/HAVING behavior, which might surprise users.
> 
> I would suggest that allowing coercion is the right choice for
> consistency, but I am happy to go with whichever approach you
> prefer.

I have run a SELECT below after applying your patch:

SELECT id, COUNT(*) OVER w AS cnt
FROM test_coerce WHERE val
WINDOW w AS (
    ORDER BY id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+)
    DEFINE A AS val
)
ORDER BY id;

The point with the SELECT is, the target list lacks val column but it
has WHERE clause with a qual "val".  Thus the SELECT's query tree has
TargetEntry with VAR varattno = 2 (val) and resjunk attribute is true,
and "quals" has cast expression on top of VAR varattno = 2. So the
target entry and qual has different expressions. Probably I should not
expect that the expression in target list is identical to the
expression in other places (WHERE, DEFINE).

> I would suggest that allowing coercion is the right choice for

So I Agree with you.

> On a separate topic, I have found a server crash bug in the current
> PREV/NEXT implementation. Nesting navigation functions causes the
> backend to crash:
> 
>     CREATE TABLE t (id int, price int);
>     INSERT INTO t VALUES (1,10),(2,20),(3,15),(4,25),(5,30);
> 
>     SELECT * FROM t WINDOW w AS (
>         ORDER BY id
>         ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>         PATTERN (A B+)
>         DEFINE B AS prev(prev(b.price)) > 0
>     );
>     -- server process crashes
> 
> The SQL standard (ISO/IEC 19075-5, Section 5.6.2) prohibits nesting
> PREV/NEXT within PREV/NEXT. The first argument of PREV/NEXT must
> contain a column reference, not another navigation function call.
> Currently there is no parser-level check for this, so the nested
> call passes through to the executor and crashes.
> 
> I have attached a test file (rpr_nav_nesting_test.txt) containing
> 6 test cases that cover the prohibited nesting patterns:
> 
>   - PREV(PREV(price))        direct same-kind nesting
>   - NEXT(NEXT(price))        direct same-kind nesting
>   - PREV(NEXT(price))        cross nesting
>   - NEXT(PREV(price))        cross nesting
>   - PREV(ABS(PREV(price)))   nesting hidden inside another function
>   - NEXT(ABS(NEXT(price)))   nesting hidden inside another function
> 
> All of these currently crash the server. After a fix, they should
> all produce a syntax error.

I thought PREV, NEXT nesting check was there but apparently I was
wrong.

> Finally, while reviewing the standard and the current
> PREV/NEXT implementation, I have some thoughts on the
> design.
> 
> The current approach uses all three ExprContext slots
> (scan/outer/inner) with varno rewriting, which fixes offsets at
> +/-1. The standard requires variable offsets like PREV(price, 3),
> and the three-slot model cannot support this.
> 
> I think a simpler approach would be to use just one slot
> (ecxt_outertuple) and swap it during expression evaluation:
> 
>   For `price > PREV(price, 2)`:
>         ^^^^    ^^^^  ^^^^^
>          |       |      |
>          v       v      v
>     1. [price]       read from current slot   --> datum_a
>     2. [PREV( ,2)]   swap slot to (currentpos - 2)
>     3.   [price]     read from swapped slot   --> datum_b
>     4. [)]           restore slot
>     5. [>]           evaluate datum_a > datum_b
> 
> Since step 1 already extracts the value as a Datum before the
> swap in step 2, the result is safe. No varno rewriting is needed
> -- all column reads just use the one slot, and the swap/restore
> controls which row they see.
> 
> One thing I noticed is that the SQL standard explicitly requires
> all column references inside a navigation function to be qualified
> by the same row pattern variable (Section 5.2):
> 
>   "All row pattern column references in an aggregate or row
>    pattern navigation operation are qualified by the same row
>    pattern variable."
> 
> This means the navigation argument is always evaluated in a single
> row context -- which is exactly what makes the one-slot swap model
> work. It seems like the standard may have been designed with this
> kind of implementation in mind.
> 
> With this approach, the existing varno rewriting infrastructure and
> the extra slots for PREV/NEXT would no longer be needed, which
> should simplify the code considerably.
> 
> I also believe this design would scale well to future extensions.
> Variable offsets (PREV(price, N)) would work naturally, and when
> we add FIRST/LAST navigation or row pattern variable qualifiers,
> only the target row calculation would change -- the swap/restore
> mechanism itself would remain the same.
> 
> What do you think about this approach?

Looks great. Do you have any idea how to let the existing ExecEvalExpr
handle the swap/restore mechanism?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Looks great. Do you have any idea how to let the existing ExecEvalExpr
handle the swap/restore mechanism?


Yes. I think the key insight is that ExecEvalExpr compiles expressions into
a flat array of ExprEvalStep operations, which makes the swap/restore natural
to implement without any changes to the ExecEvalExpr caller interface.

I should also say that this approach was shaped by the constraints you
identified early on -- the three-slot model's limitations and the need
for variable offsets. Without that clear problem framing, I would not
have thought in this direction.

The idea is to introduce two new ExprEvalOp steps:

  EEOP_RPR_NAV_SET     -- save current slot, swap to target row
  EEOP_RPR_NAV_RESTORE -- restore original slot

These two steps bracket the inner expression steps in the flat array.

For `price > PREV(price)`:
  1. EEOP_OUTER_VAR      -- fetch price from current slot --> datum_a
  2. EEOP_RPR_NAV_SET    -- save current slot, swap to (currentpos - 1)
  3. EEOP_OUTER_VAR      -- fetch price from swapped slot --> datum_b
  4. EEOP_RPR_NAV_RESTORE -- restore original slot
  5. EEOP_GT             -- evaluate datum_a > datum_b
  6. EEOP_DONE

For `price > PREV(price, 3)` (with offset):
  1. EEOP_OUTER_VAR      -- fetch price from current slot --> datum_a
  2. EEOP_CONST          -- evaluate offset constant 3 --> datum_off
  3. EEOP_RPR_NAV_SET    -- save current slot, swap to (currentpos - 3)
  4. EEOP_OUTER_VAR      -- fetch price from swapped slot --> datum_b
  5. EEOP_RPR_NAV_RESTORE -- restore original slot
  6. EEOP_GT             -- evaluate datum_a > datum_b
  7. EEOP_DONE

For `price < NEXT(price)`:
  1. EEOP_OUTER_VAR      -- fetch price from current slot --> datum_a
  2. EEOP_RPR_NAV_SET    -- save current slot, swap to (currentpos + 1)
  3. EEOP_OUTER_VAR      -- fetch price from swapped slot --> datum_b
  4. EEOP_RPR_NAV_RESTORE -- restore original slot
  5. EEOP_LT             -- evaluate datum_a < datum_b
  6. EEOP_DONE

ExprState holds the flat array of ExprEvalSteps, and each step carries
its own payload. The RPR navigation steps would store a pointer to the
window execution state in their payload, so that they can access the
current row position and the tuplestore at evaluation time. Since
PREV/NEXT are only permitted in the DEFINE clause, the window execution
state is always valid when these steps are evaluated, which eliminates
the risk of accessing stale or invalid state.

The EEOP_RPR_NAV_SET step would:
  1. Save the current slot for later restore
  2. Compute the target position from currentpos and the direction offset
  3. Fetch the corresponding TupleTableSlot from the tuplestore
  4. Replace econtext->ecxt_outertuple with the target slot

The EEOP_RPR_NAV_RESTORE step would:
  1. Retrieve the previously saved slot
  2. Restore econtext->ecxt_outertuple to the original slot

This design also fits well with the future roadmap for FIRST/LAST navigation.
Once the match history infrastructure is in place, FIRST/LAST can look
up the first or last row matched by a given pattern variable from the
history, compute the target position from that, and pass it to
EEOP_RPR_NAV_SET -- the save/restore mechanism itself stays the same.

I would like to work on an experimental implementation of this approach,
including the parser-level check to reject nested PREV/NEXT calls as
required by the standard. The nesting check will be part of the same
implementation rather than a separate fix, as the parser structure may
need to be adjusted as part of the redesign anyway.

Since the expression compilation infrastructure is not an area I am
deeply familiar with, it may take some time to get right. I would
appreciate your patience in reviewing it when it is ready.

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Yes. I think the key insight is that ExecEvalExpr compiles expressions into
> a flat array of ExprEvalStep operations, which makes the swap/restore
> natural
> to implement without any changes to the ExecEvalExpr caller interface.
> 
> I should also say that this approach was shaped by the constraints you
> identified early on -- the three-slot model's limitations and the need
> for variable offsets. Without that clear problem framing, I would not
> have thought in this direction.

I am not an expert of this area but I have some questions.

> The idea is to introduce two new ExprEvalOp steps:
> 
>   EEOP_RPR_NAV_SET     -- save current slot, swap to target row
>   EEOP_RPR_NAV_RESTORE -- restore original slot
> 
> These two steps bracket the inner expression steps in the flat array.
> 
> For `price > PREV(price)`:
>   1. EEOP_OUTER_VAR      -- fetch price from current slot --> datum_a
>   2. EEOP_RPR_NAV_SET    -- save current slot, swap to (currentpos - 1)
>   3. EEOP_OUTER_VAR      -- fetch price from swapped slot --> datum_b
>   4. EEOP_RPR_NAV_RESTORE -- restore original slot
>   5. EEOP_GT             -- evaluate datum_a > datum_b

I was not able to find the definition for EEOP_GT. Is this a new one?

> The EEOP_RPR_NAV_SET step would:
>   1. Save the current slot for later restore
>   2. Compute the target position from currentpos and the direction offset
>   3. Fetch the corresponding TupleTableSlot from the tuplestore

I am afraid ExecEvalExpr does not allow this because ExecEvalExpr does
not accept arguments like WindowObject or WindowAggState that are
necessary for accessing the tuplestore created for the Window
aggregate node.

That is (ExecEvalExpr doe not accept arguments like WindowObject or
WindowAggState) the reason why EEOP_WINDOW_FUNC is implemented like this:

			/*
			 * Like Aggref, just return a precomputed value from the econtext.
			 */
			WindowFuncExprState *wfunc = op->d.window_func.wfstate;

			Assert(econtext->ecxt_aggvalues != NULL);

			*op->resvalue = econtext->ecxt_aggvalues[wfunc->wfuncno];
			*op->resnull = econtext->ecxt_aggnulls[wfunc->wfuncno];

so that ExecEvalExpr can access the window function's result from
op->resvalue and op->resnull.  See eval_windowfunction for more
details.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thank you for the careful review and excellent questions.

I was not able to find the definition for EEOP_GT. Is this a new one?

You're right -- EEOP_GT does not exist. I oversimplified the example.

In PostgreSQL, comparison operators like `>` are not dedicated opcodes.
They are dispatched through EEOP_FUNCEXPR variants as regular function
calls. For example, `price > PREV(price)`:

  - The parser resolves `>` to the appropriate pg_operator entry
  - The expression compiler emits an EEOP_FUNCEXPR variant
  - At runtime, op->d.func.fn_addr points to the operator function,

I am afraid ExecEvalExpr does not allow this because ExecEvalExpr does
not accept arguments like WindowObject or WindowAggState that are
necessary for accessing the tuplestore created for the Window
aggregate node.

This is the key question. You are right that ExecEvalExpr's signature
does not accept WindowAggState, and I do not intend to change it.

The approach is to pass WindowAggState through the step's own payload,
the same way EEOP_WINDOW_FUNC carries WindowFuncExprState in
op->d.window_func.wfstate. Each ExprEvalStep has a union of per-opcode
payload structs. A new payload for RPR navigation would look like:

    struct
    {
        WindowAggState *winstate;   /* access to tuplestore */
        int64       offset;         /* signed offset: PREV=-1, NEXT=+1 */
    }           rpr_nav;

The expression compiler (ExecInitExprRec) populates this when it
encounters a PREV/NEXT node, storing the pointer to the enclosing
WindowAggState. At runtime, EEOP_RPR_NAV_SET retrieves it from the
payload and uses it to fetch the target row:

    /* pseudo-code for EEOP_RPR_NAV_SET */
    winstate = op->d.rpr_nav.winstate;
    /* 1. save current slot into winstate for later restore */
    winstate->saved_outertuple = econtext->ecxt_outertuple;
    /* 2. compute target position */
    target_pos = winstate->currentpos + op->d.rpr_nav.offset;
    /* 3. fetch target row from tuplestore via winstate */
    target_slot = fetch_row_from_tuplestore(winstate, target_pos);
    /* 4. swap */
    econtext->ecxt_outertuple = target_slot;

    /* pseudo-code for EEOP_RPR_NAV_RESTORE */
    winstate = op->d.rpr_nav.winstate;
    econtext->ecxt_outertuple = winstate->saved_outertuple;

The key difference from EEOP_WINDOW_FUNC: existing steps read
precomputed values, but PREV/NEXT requires fetching a *different*
row at runtime -- because the target depends on the current row
position during pattern matching, which is not known in advance.
The mechanism for passing state is the same (step payload), but
the runtime behavior is a departure from the existing pattern.

I have examined the alternatives carefully:

  - The precomputation approach (EEOP_WINDOW_FUNC style) does not apply
    here: there is no fixed set of values to precompute, because the
    target row depends on the current position during pattern matching.

  - The three-slot model (current implementation) cannot support variable
    offsets like PREV(price, 3), and requires varno rewriting that adds
    complexity elsewhere.

  - A callback-based approach (registering a fetch function in econtext)
    would still require passing WindowAggState somehow, just through a
    different indirection.

The step payload approach is the only path I have found that:

  - Leaves ExecEvalExpr's signature unchanged
  - Eliminates varno rewriting entirely
  - Supports variable offsets naturally
  - Extends to FIRST/LAST navigation later

If anyone sees a cleaner path, I would genuinely welcome the
discussion.

I plan to have an experimental implementation ready before next week.
The initial version will pass WindowAggState broadly; we can
narrow the interface to the minimum required during review.
Let's continue the discussion with actual code.

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> I was not able to find the definition for EEOP_GT. Is this a new one?
>>
> 
> You're right -- EEOP_GT does not exist. I oversimplified the example.
> 
> In PostgreSQL, comparison operators like `>` are not dedicated opcodes.
> They are dispatched through EEOP_FUNCEXPR variants as regular function
> calls. For example, `price > PREV(price)`:
> 
>   - The parser resolves `>` to the appropriate pg_operator entry
>   - The expression compiler emits an EEOP_FUNCEXPR variant
>   - At runtime, op->d.func.fn_addr points to the operator function,

Ok.

> I am afraid ExecEvalExpr does not allow this because ExecEvalExpr does
>> not accept arguments like WindowObject or WindowAggState that are
>> necessary for accessing the tuplestore created for the Window
>> aggregate node.
> 
> 
> This is the key question. You are right that ExecEvalExpr's signature
> does not accept WindowAggState, and I do not intend to change it.
> 
> The approach is to pass WindowAggState through the step's own payload,
> the same way EEOP_WINDOW_FUNC carries WindowFuncExprState in
> op->d.window_func.wfstate. Each ExprEvalStep has a union of per-opcode
> payload structs. A new payload for RPR navigation would look like:
> 
>     struct
>     {
>         WindowAggState *winstate;   /* access to tuplestore */
>         int64       offset;         /* signed offset: PREV=-1, NEXT=+1 */
>     }           rpr_nav;
> 
> The expression compiler (ExecInitExprRec) populates this when it
> encounters a PREV/NEXT node, storing the pointer to the enclosing
> WindowAggState. At runtime, EEOP_RPR_NAV_SET retrieves it from the
> payload and uses it to fetch the target row:
> 
>     /* pseudo-code for EEOP_RPR_NAV_SET */
>     winstate = op->d.rpr_nav.winstate;
>     /* 1. save current slot into winstate for later restore */
>     winstate->saved_outertuple = econtext->ecxt_outertuple;
>     /* 2. compute target position */
>     target_pos = winstate->currentpos + op->d.rpr_nav.offset;
>     /* 3. fetch target row from tuplestore via winstate */
>     target_slot = fetch_row_from_tuplestore(winstate, target_pos);
>     /* 4. swap */
>     econtext->ecxt_outertuple = target_slot;
> 
>     /* pseudo-code for EEOP_RPR_NAV_RESTORE */
>     winstate = op->d.rpr_nav.winstate;
>     econtext->ecxt_outertuple = winstate->saved_outertuple;
> 
> The key difference from EEOP_WINDOW_FUNC: existing steps read
> precomputed values, but PREV/NEXT requires fetching a *different*
> row at runtime -- because the target depends on the current row
> position during pattern matching, which is not known in advance.
> The mechanism for passing state is the same (step payload), but
> the runtime behavior is a departure from the existing pattern.
> 
> I have examined the alternatives carefully:
> 
>   - The precomputation approach (EEOP_WINDOW_FUNC style) does not apply
>     here: there is no fixed set of values to precompute, because the
>     target row depends on the current position during pattern matching.
>
>   - The three-slot model (current implementation) cannot support variable
>     offsets like PREV(price, 3), and requires varno rewriting that adds
>     complexity elsewhere.
> 
>   - A callback-based approach (registering a fetch function in econtext)
>     would still require passing WindowAggState somehow, just through a
>     different indirection.
> 
> The step payload approach is the only path I have found that:
> 
>   - Leaves ExecEvalExpr's signature unchanged
>   - Eliminates varno rewriting entirely
>   - Supports variable offsets naturally
>   - Extends to FIRST/LAST navigation later

Thank you for the detailed explanation. I agreed the approach.

> If anyone sees a cleaner path, I would genuinely welcome the
> discussion.
> 
> I plan to have an experimental implementation ready before next week.
> The initial version will pass WindowAggState broadly; we can
> narrow the interface to the minimum required during review.
> Let's continue the discussion with actual code.

Looking forward to reviewing the implementation.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
SungJun Jang <sjjang112233@gmail.com>
Дата:
Hi hackers,

Thank you for the excellent report! I am glad to see that PostgreSQL
RPR is much faster than Trino, especially in the match failure cases.

Is it possible to share the data generation script and the query for
PostgreSQL so that I could locally perform the tests?

Here is a self-contained guide to reproduce the RPR ABCD pattern test locally
using PostgreSQL, Trino, and Oracle.


Requirements:

PostgreSQL 19devel build with the RPR patch applied (local)

Trino and Oracle can be set up via Docker (see README for details):

  https://github.com/assam258-5892/docker-databases

Start all services:

  cd ~/docker-databases && docker compose up -d trino-service oracle-service

Note: docker compose up does not pull images automatically if they are already
cached locally. To fetch the latest images, run docker compose pull first.

Note: The Oracle image requires an Oracle account. Register at
https://container-registry.oracle.com, accept the license for the database
image, then log in before pulling:

  docker login container-registry.oracle.com

Connect to each database shell:

  Trino:  docker compose exec -it trino-service trino
  Oracle: docker compose exec -it oracle-service sqlplus / as sysdba


Step 1: Create the test table and data

PostgreSQL (1x scale, 20,000 rows):

DROP TABLE IF EXISTS abcd_test;
CREATE TABLE abcd_test AS
SELECT v,
       CASE
           WHEN v % 10000 < 3333 THEN 'A'
           WHEN v % 10000 >= 3333 AND v % 10000 < 6666 THEN 'B'
           WHEN v % 10000 >= 6666 AND v % 10000 < 9999 THEN 'C'
           WHEN v % 10000 = 9999 THEN 'D'
       END AS cat
FROM generate_series(0, 19999) AS v;

ANALYZE abcd_test;


Trino (1x scale, 20,000 rows):

CREATE SCHEMA IF NOT EXISTS memory.test;

DROP TABLE IF EXISTS memory.test.abcd_test;
CREATE TABLE memory.test.abcd_test AS
WITH nums AS (
    SELECT a.v * 10000 + b.v AS v
    FROM UNNEST(sequence(0, 1)) AS a(v)
    CROSS JOIN UNNEST(sequence(0, 9999)) AS b(v)
)
SELECT CAST(v AS INTEGER) AS v,
       CASE
           WHEN v % 10000 < 3333 THEN 'A'
           WHEN v % 10000 >= 3333 AND v % 10000 < 6666 THEN 'B'
           WHEN v % 10000 >= 6666 AND v % 10000 < 9999 THEN 'C'
           WHEN v % 10000 = 9999 THEN 'D'
       END AS cat
FROM nums;

Note: Trino sequence() is limited to 10,000 elements per call, so a CROSS JOIN
is used. For scale Sx, change sequence(0, 1) to sequence(0, S*2-1).


Oracle (1x scale, 20,000 rows):

DROP TABLE abcd_test PURGE;
CREATE TABLE abcd_test AS
SELECT v,
       CASE
           WHEN MOD(v, 10000) < 3333 THEN 'A'
           WHEN MOD(v, 10000) >= 3333 AND MOD(v, 10000) < 6666 THEN 'B'
           WHEN MOD(v, 10000) >= 6666 AND MOD(v, 10000) < 9999 THEN 'C'
           WHEN MOD(v, 10000) = 9999 THEN 'D'
       END AS cat
FROM (SELECT LEVEL - 1 AS v FROM dual CONNECT BY LEVEL <= 20000);

EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ABCD_TEST');


Verify data distribution (all engines):

SELECT cat, COUNT(*) AS cnt FROM abcd_test GROUP BY cat ORDER BY cat;

Expected (1x): A=6666, B=6666, C=6666, D=2


Step 2: Run Test 1 — A+ B+ C+ D (match expected)

Expected: 2 rows returned (one match per segment)

PostgreSQL:

SELECT match_first, match_last, match_len
FROM (
    SELECT v,
           first_value(v) OVER w AS match_first,
           last_value(v) OVER w AS match_last,
           count(*) OVER w AS match_len
    FROM abcd_test
    WINDOW w AS (
        ORDER BY v
        ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
        AFTER MATCH SKIP PAST LAST ROW
        PATTERN (A+ B+ C+ D)
        DEFINE
            A AS cat = 'A',
            B AS cat = 'B',
            C AS cat = 'C',
            D AS cat = 'D'
    )
) result
WHERE match_len > 0;


Trino / Oracle:

SELECT match_first, match_last, match_len
FROM abcd_test
MATCH_RECOGNIZE (
    ORDER BY v
    MEASURES
        FIRST(v) AS match_first,
        LAST(v) AS match_last,
        COUNT(*) AS match_len
    ONE ROW PER MATCH
    AFTER MATCH SKIP PAST LAST ROW
    PATTERN (A+ B+ C+ D)
    DEFINE
        A AS cat = 'A',
        B AS cat = 'B',
        C AS cat = 'C',
        D AS cat = 'D'
) mr;

Note: Trino uses memory.test.abcd_test as the table name.

Expected result (1x):

match_first | match_last | match_len
------------|------------|----------
          0 |       9999 |     10000
      10000 |      19999 |     10000


Step 3: Run Test 2 — A+ B+ C+ E (match failure)

Expected: 0 rows (E does not exist)

Use the same queries as Test 1 with two changes:

PATTERN: (A+ B+ C+ D) → (A+ B+ C+ E)

DEFINE: cat = 'D' → cat = 'E'

Warning: Trino Test 2 at 1x scale takes approximately 5-6 minutes.


Step 4: Scale up (optional)

Re-create the test table at 2x scale (40,000 rows) and then repeat Step 2 and
Step 3.

PostgreSQL (2x scale, 40,000 rows):

DROP TABLE IF EXISTS abcd_test;
CREATE TABLE abcd_test AS
SELECT v,
       CASE
           WHEN v % 20000 < 6666 THEN 'A'
           WHEN v % 20000 >= 6666 AND v % 20000 < 13332 THEN 'B'
           WHEN v % 20000 >= 13332 AND v % 20000 < 19999 THEN 'C'
           WHEN v % 20000 = 19999 THEN 'D'
       END AS cat
FROM generate_series(0, 39999) AS v;

ANALYZE abcd_test;


Trino (2x scale, 40,000 rows):

CREATE SCHEMA IF NOT EXISTS memory.test;

DROP TABLE IF EXISTS memory.test.abcd_test;
CREATE TABLE memory.test.abcd_test AS
WITH nums AS (
    SELECT a.v * 10000 + b.v AS v
    FROM UNNEST(sequence(0, 3)) AS a(v)
    CROSS JOIN UNNEST(sequence(0, 9999)) AS b(v)
)
SELECT CAST(v AS INTEGER) AS v,
       CASE
           WHEN v % 20000 < 6666 THEN 'A'
           WHEN v % 20000 >= 6666 AND v % 20000 < 13332 THEN 'B'
           WHEN v % 20000 >= 13332 AND v % 20000 < 19999 THEN 'C'
           WHEN v % 20000 = 19999 THEN 'D'
       END AS cat
FROM nums;


Oracle (2x scale, 40,000 rows):

DROP TABLE abcd_test PURGE;
CREATE TABLE abcd_test AS
SELECT v,
       CASE
           WHEN MOD(v, 20000) < 6666 THEN 'A'
           WHEN MOD(v, 20000) >= 6666 AND MOD(v, 20000) < 13332 THEN 'B'
           WHEN MOD(v, 20000) >= 13332 AND MOD(v, 20000) < 19999 THEN 'C'
           WHEN MOD(v, 20000) = 19999 THEN 'D'
       END AS cat
FROM (SELECT LEVEL - 1 AS v FROM dual CONNECT BY LEVEL <= 40000);

EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ABCD_TEST');

Expected (2x): A=13332, B=13332, C=13332, D=4

Then run Step 2 and Step 3 as-is.

Warning: Trino Test 2 at 2x scale takes approximately 20-25 minutes.


Please let me know if you encounter any issues reproducing this.

Best regards
SungJun
 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

Attached is the v45 patches. These are basically your patches
(0001-0013) on top of v44, plus rebase. Major changes/fixes since v44
include:

- Rebase. Due to commits (SQL/PG) rebase was required.

  I had to resolve shift/reduce conflicts while rebasing gram.y. In
  the end, I removed follwing in the v44 patch.
---------------------------------------------------------------------------
 qual_Op:	Op
 					{ $$ = list_make1(makeString($1)); }
 			| OPERATOR '(' any_operator ')'
 					{ $$ = $3; }
+			| '|'
+					{ $$ = list_make1(makeString("|")); }
 		;
--------------------------------------------------------------------------- 

  Also, we don't need the patch to scan.l anymore since the necessary
  changes are already there, thanks to SQL/PGQ commit.
  
- Fix elog message to use lowercase per PostgreSQL convention

  Minor style fix: lowercase the elog error message in
  nodeWindowAgg.c to follow PostgreSQL coding convention.

- Fix RPR reluctant quantifier flag lost during VIEW serialization

  The reluctant flag on quantifiers was lost when a VIEW containing
  RPR was serialized and restored via ruleutils.c.  This patch fixes
  gram.y, rpr.c, ruleutils.c, and parsenodes.h so the flag survives
  the round-trip.

- Expand RPR test coverage and improve test comments

  Reorganizes test cases across rpr.sql, rpr_base.sql, rpr_explain.sql,
  and rpr_nfa.sql.  Moves base functionality tests from rpr.sql to
  rpr_base.sql and NFA-specific tests to rpr_nfa.sql.  Adds better
  section comments throughout.  Duplicate tests in rpr.sql were
  removed.  No reduction in test coverage.

- Keep RPR test objects for pg_upgrade/pg_dump testing

  Adjusts rpr_base.sql and rpr_explain.sql so that test tables and
  views are not dropped at the end of the test.  This allows
  pg_upgrade and pg_dump regression testing to cover RPR objects.

- Disable run condition pushdown for RPR windows
  Revised version of Tatsuo's run condition fix [1].  Existing test
  expected output updated accordingly.

- Disable frame optimization for RPR windows

  Prevents the planner from optimizing the window frame for RPR
  windows.  The frame clause in RPR has different semantics (it
  bounds the pattern search space), so standard frame optimizations
  must be disabled.  Adds EXPLAIN tests to verify.  Please review
  this one -- it's a newly discovered issue.

- Add stock scenario tests for RPR pattern matching

  Adds stock trading scenario tests using realistic synthetic data
  (stock.data with 1632 rows).  Tests V-shape recovery, W-shape,
  consecutive rises, and other common pattern matching use cases.

- Fix zero-min reluctant quantifier to produce zero-length match

  Fixes the bug reported by SungJun [2]: reluctant quantifiers with
  min=0 (A*?, A??) were incorrectly consuming at least one row instead
  of producing a zero-length match.  The NFA can now internally
  distinguish between a zero-length match and no match, so it will
  be ready when additional infrastructure (e.g. MATCH_NUMBER) is
  added.  Now matches Oracle behavior.

- Fix coerce_to_boolean result not applied in DEFINE clause

[1]
https://www.postgresql.org/message-id/20260304.153822.445473532741409674.ishii@postgresql.org
[2]
https://www.postgresql.org/message-id/CAE+cgNiUbKeH1A0PoxV2QjpsoxJLe+pJcGz_gdxwOwu_9zqchw@mail.gmail.com

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello

I found one more bug, the following testcase crashes the server:

CREATE TEMP TABLE t (id int, val text);
INSERT INTO t VALUES
  (1,'A'),(2,'B'),
  (3,'A'),(4,'B'),
  (5,'A'),(6,'B'),
  (7,'A'),(8,'B'),
  (9,'X');

SELECT id, val, count(*) OVER w AS match_count
FROM t
WINDOW w AS (
  ORDER BY id
  ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
  INITIAL
  PATTERN (A B (A B){1,2} A B)
  DEFINE
    A AS val = 'A',
    B AS val = 'B'
);

Where the code does

+ child->min += 1;

It should also increment max if it's not infinity.

if (child->max != RPR_QUANTITY_INF)
    child->max += 1;


+ expr = te->expr;
...
+ attno_map((Node *) expr);

It it okay to mutate an object in the plan cache in the executor?
Wouldn't it be better to first copy it?

> Adds stock trading scenario tests using realistic synthetic data
> (stock.data with 1632 rows). Tests V-shape recovery, W-shape,
> consecutive rises, and other common pattern matching use cases.

The data file is not included in the patchset

+ if (wc->frameOptions & FRAMEOPTION_GROUPS)
+ ereport(ERROR,
+ (errcode(ERRCODE_SYNTAX_ERROR),
+ errmsg("FRAME option GROUP is not permitted when row pattern
recognition is used"),
+ errhint("Use: ROWS instead"),
+ parser_errposition(pstate,
+ windef->frameLocation >= 0 ?
+ windef->frameLocation : windef->location)));

Here and at a few other places, shouldn't this use a different error
code, like ERRCODE_WINDOWING_ERROR?

Also a typo, the error message should say GROUPS.

+ elog(ERROR, "PREV/NEXT must have 1 argument but function %d has %d args",
+ func->funcid, nargs);

Isn't this a user triggerable error, which should have a proper error code?


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Thanks for the review!

> I found one more bug, the following testcase crashes the server:
> 
> CREATE TEMP TABLE t (id int, val text);
> INSERT INTO t VALUES
>   (1,'A'),(2,'B'),
>   (3,'A'),(4,'B'),
>   (5,'A'),(6,'B'),
>   (7,'A'),(8,'B'),
>   (9,'X');
> 
> SELECT id, val, count(*) OVER w AS match_count
> FROM t
> WINDOW w AS (
>   ORDER BY id
>   ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>   INITIAL
>   PATTERN (A B (A B){1,2} A B)
>   DEFINE
>     A AS val = 'A',
>     B AS val = 'B'
> );

I just confirmed the crash.

> Where the code does
> 
> + child->min += 1;
> 
> It should also increment max if it's not infinity.
> 
> if (child->max != RPR_QUANTITY_INF)
>     child->max += 1;

Henson, What do you think? 

> + expr = te->expr;
> ...
> + attno_map((Node *) expr);
> 
> It it okay to mutate an object in the plan cache in the executor?
> Wouldn't it be better to first copy it?

Good point. You are right, the plan cache should be read only.
However, Henson is working on a different approach and the code will
not be used any more...

>> Adds stock trading scenario tests using realistic synthetic data
>> (stock.data with 1632 rows). Tests V-shape recovery, W-shape,
>> consecutive rises, and other common pattern matching use cases.
> 
> The data file is not included in the patchset

I forggot to include the data file. Please apply attached patch on top
of v45.

> + if (wc->frameOptions & FRAMEOPTION_GROUPS)
> + ereport(ERROR,
> + (errcode(ERRCODE_SYNTAX_ERROR),
> + errmsg("FRAME option GROUP is not permitted when row pattern
> recognition is used"),
> + errhint("Use: ROWS instead"),
> + parser_errposition(pstate,
> + windef->frameLocation >= 0 ?
> + windef->frameLocation : windef->location)));
> 
> Here and at a few other places, shouldn't this use a different error
> code, like ERRCODE_WINDOWING_ERROR?

Agreed.

> Also a typo, the error message should say GROUPS.
> 
> + elog(ERROR, "PREV/NEXT must have 1 argument but function %d has %d args",
> + func->funcid, nargs);
> 
> Isn't this a user triggerable error, which should have a proper error code?

Right. Maybe ERRCODE_TOO_MANY_ARGUMENTS?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

From c76758ce160b2b0ad3c3ced5ae33c6ebd2dadd8b Mon Sep 17 00:00:00 2001
From: Tatsuo Ishii 
Date: Thu, 19 Mar 2026 09:46:27 +0900
Subject: [PATCH v1] Add missing regression test data.

---
 src/test/regress/data/stock.data | 1632 ++++++++++++++++++++++++++++++
 1 file changed, 1632 insertions(+)
 create mode 100644 src/test/regress/data/stock.data

diff --git a/src/test/regress/data/stock.data b/src/test/regress/data/stock.data
new file mode 100644
index 00000000000..645bb643df7
--- /dev/null
+++ b/src/test/regress/data/stock.data
@@ -0,0 +1,1632 @@
+1	1	364.750	15800	0.000	0.000	0.000
+1	2	368.250	21200	0.000	0.000	0.000
+1	3	368.500	24400	0.000	0.000	0.000
+1	4	368.750	22900	0.000	0.000	0.000
+1	5	369.500	35400	0.000	0.000	0.000
+1	6	369.000	29300	0.000	0.000	0.000
+1	7	367.750	19000	0.000	0.000	0.000
+1	8	374.125	37200	0.000	0.000	0.000
+2	9	343.250	56800	0.000	0.000	0.000
+2	10	338.500	45200	0.000	0.000	0.000
+2	11	338.750	40900	0.000	0.000	0.000
+2	12	344.750	35200	0.000	0.000	0.000
+2	13	349.750	28500	0.000	0.000	0.000
+2	14	346.000	25600	0.000	0.000	0.000
+3	15	349.000	24900	0.000	0.000	0.000
+3	16	349.250	20700	0.000	0.000	0.000
+3	17	349.750	22200	0.000	0.000	0.000
+3	18	351.250	19600	0.000	0.000	0.000
+3	19	352.000	32500	0.000	0.000	0.000
+3	20	349.500	32200	0.000	0.000	0.000
+3	21	344.500	18600	0.000	0.000	0.000
+3	22	345.000	61200	0.000	0.000	0.000
+4	23	238.250	37100	0.000	0.000	0.000
+4	24	230.625	61500	0.000	0.000	0.000
+4	25	223.000	161700	0.000	0.000	0.000
+4	26	229.875	55300	0.000	0.000	0.000
+4	27	235.250	38500	0.000	0.000	0.000
+5	28	310.000	36000	0.000	0.000	0.000
+5	29	311.750	26800	0.000	0.000	0.000
+5	30	312.750	31900	0.000	0.000	0.000
+5	31	314.750	21100	0.000	0.000	0.000
+5	32	315.500	27400	0.000	0.000	0.000
+5	33	316.500	40700	0.000	0.000	0.000
+5	34	321.750	53500	0.000	0.000	0.000
+5	35	326.000	48700	0.000	0.000	0.000
+5	36	322.500	46000	0.000	0.000	0.000
+5	37	317.500	35600	0.000	0.000	0.000
+5	38	325.500	34000	0.000	0.000	0.000
+5	39	327.250	30700	0.000	0.000	0.000
+5	40	327.750	36700	0.000	0.000	0.000
+5	41	328.625	23200	0.000	0.000	0.000
+5	42	330.500	29700	0.000	0.000	0.000
+5	43	336.500	39200	0.000	0.000	0.000
+5	44	340.750	34400	0.000	0.000	0.000
+5	45	338.500	32200	0.000	0.000	0.000
+6	46	353.000	27800	0.000	0.000	0.000
+6	47	352.000	55600	0.000	0.000	0.000
+6	48	355.000	31300	0.000	0.000	0.000
+6	49	356.000	26900	0.000	0.000	0.000
+6	50	358.000	18900	0.000	0.000	0.000
+6	51	361.250	26400	0.000	0.000	0.000
+7	52	311.750	25100	0.000	0.000	0.000
+7	53	314.000	37900	0.000	0.000	0.000
+7	54	317.000	34000	0.000	0.000	0.000
+7	55	317.750	23700	0.000	0.000	0.000
+7	56	319.000	23400	0.000	0.000	0.000
+7	57	316.500	24200	0.000	0.000	0.000
+8	58	316.000	37200	0.000	0.000	0.000
+8	59	315.000	31500	0.000	0.000	0.000
+8	60	302.000	124700	0.000	0.000	0.000
+8	61	300.000	196100	0.000	0.000	0.000
+8	62	298.000	70000	0.000	0.000	0.000
+8	63	294.500	88200	0.000	0.000	0.000
+8	64	296.500	53800	0.000	0.000	0.000
+8	65	299.000	47900	0.000	0.000	0.000
+8	66	301.750	33300	0.000	0.000	0.000
+8	67	299.500	31800	0.000	0.000	0.000
+9	68	299.500	76700	0.000	0.000	0.000
+9	69	296.750	41900	0.000	0.000	0.000
+9	70	291.250	46700	0.000	0.000	0.000
+9	71	293.750	31100	0.000	0.000	0.000
+9	72	290.000	48900	0.000	0.000	0.000
+9	73	287.000	56300	0.000	0.000	0.000
+9	74	287.000	40700	0.000	0.000	0.000
+9	75	285.500	27900	0.000	0.000	0.000
+9	76	284.000	27400	0.000	0.000	0.000
+9	77	286.000	23500	0.000	0.000	0.000
+9	78	291.250	38000	0.000	0.000	0.000
+9	79	296.750	42900	0.000	0.000	0.000
+9	80	295.000	19500	0.000	0.000	0.000
+9	81	314.000	102900	0.000	0.000	0.000
+9	82	315.750	84100	0.000	0.000	0.000
+10	83	302.000	44600	0.000	0.000	0.000
+10	84	301.000	45000	0.000	0.000	0.000
+10	85	294.750	27900	0.000	0.000	0.000
+10	86	293.500	17600	0.000	0.000	0.000
+10	87	291.750	21600	0.000	0.000	0.000
+10	88	290.500	30300	0.000	0.000	0.000
+10	89	291.750	22700	0.000	0.000	0.000
+10	90	298.750	16200	0.000	0.000	0.000
+10	91	302.250	49100	0.000	0.000	0.000
+10	92	305.500	35500	0.000	0.000	0.000
+10	93	309.750	63200	0.000	0.000	0.000
+10	94	309.500	43200	0.000	0.000	0.000
+11	95	383.750	19300	0.000	0.000	0.000
+11	96	389.500	28900	0.000	0.000	0.000
+11	97	394.500	41700	0.000	0.000	0.000
+11	98	396.250	28200	0.000	0.000	0.000
+11	99	401.000	55000	0.000	0.000	0.000
+11	100	402.000	41100	0.000	0.000	0.000
+11	101	403.000	38500	0.000	0.000	0.000
+11	102	404.000	33100	0.000	0.000	0.000
+11	103	404.000	33800	0.000	0.000	0.000
+12	104	388.000	25800	0.000	0.000	0.000
+12	105	388.500	44900	0.000	0.000	0.000
+12	106	390.000	38400	0.000	0.000	0.000
+12	107	390.750	23200	0.000	0.000	0.000
+12	108	396.500	25100	0.000	0.000	0.000
+12	109	398.750	38000	0.000	0.000	0.000
+12	110	398.000	33600	0.000	0.000	0.000
+12	111	394.500	54000	0.000	0.000	0.000
+12	112	397.000	20900	0.000	0.000	0.000
+13	113	398.125	28500	0.000	396.000	401.000
+13	114	394.500	39900	0.000	392.500	397.500
+13	115	390.000	37600	0.000	390.000	393.750
+13	116	389.500	31000	0.000	386.000	392.750
+13	117	385.500	25800	0.000	385.500	389.750
+13	118	390.500	18000	0.000	385.000	390.500
+13	119	391.750	14600	0.000	391.500	395.500
+13	120	399.000	27800	0.000	392.250	399.000
+13	121	402.000	46500	0.000	399.000	403.000
+13	122	409.000	36300	0.000	404.500	409.500
+13	123	409.250	54500	0.000	409.250	413.750
+13	124	411.750	46200	0.000	406.000	412.500
+13	125	418.750	60200	0.000	412.750	419.500
+13	126	418.750	32700	0.000	416.000	420.000
+14	127	411.500	24800	0.000	411.250	415.500
+14	128	415.250	53000	0.000	412.000	423.000
+14	129	420.000	49700	0.000	417.250	425.000
+14	130	423.250	68700	0.000	422.750	429.000
+14	131	422.500	45400	0.000	420.750	424.750
+14	132	424.000	20900	0.000	420.750	424.250
+14	133	428.875	37600	0.000	427.000	430.000
+14	134	439.000	59800	0.000	427.250	439.000
+15	135	448.750	29300	0.000	444.750	449.500
+15	136	444.000	27400	0.000	444.000	449.750
+15	137	443.500	30900	0.000	440.500	448.500
+15	138	437.875	26500	0.000	437.500	442.875
+15	139	437.750	29000	0.000	433.500	440.000
+15	140	430.500	27500	0.000	430.250	441.250
+15	141	425.500	52300	0.000	424.250	428.880
+15	142	428.000	59900	0.000	419.500	429.000
+15	143	432.500	34600	0.000	427.250	435.000
+15	144	437.500	33100	0.000	432.000	438.500
+15	145	434.500	24300	0.000	434.000	437.750
+15	146	431.500	28500	0.000	430.500	437.500
+15	147	428.000	15500	0.000	427.000	432.750
+15	148	424.250	44900	0.000	424.000	428.750
+15	149	423.000	34000	0.000	420.000	426.500
+15	150	422.875	37800	0.000	420.000	424.000
+15	151	423.500	24000	0.000	423.250	428.000
+15	152	429.500	23200	0.000	420.500	429.500
+15	153	434.250	31800	0.000	429.750	435.000
+15	154	430.250	36500	0.000	426.500	436.250
+16	155	309.750	41400	0.000	307.125	310.750
+16	156	317.000	44500	0.000	309.750	317.000
+16	157	315.000	39900	0.000	313.125	319.750
+16	158	322.000	40600	0.000	318.500	322.500
+16	159	324.250	35300	0.000	321.000	325.250
+16	160	323.000	32300	0.000	322.500	327.000
+16	161	329.250	47700	0.000	323.250	330.000
+16	162	329.500	56700	0.000	328.500	333.500
+16	163	321.000	45400	0.000	320.000	328.500
+17	164	298.000	31900	0.000	290.500	298.000
+17	165	272.000	165000	0.000	270.750	285.125
+17	166	259.500	290400	0.000	252.750	261.000
+17	167	270.750	136000	0.000	266.000	270.750
+17	168	268.750	96600	0.000	266.000	271.750
+17	169	260.000	99100	0.000	258.000	264.500
+17	170	251.500	100900	0.000	250.500	260.750
+17	171	259.500	78100	0.000	253.000	261.000
+17	172	260.500	64600	0.000	260.500	267.500
+17	173	260.000	51400	0.000	259.000	264.500
+17	174	258.000	40800	0.000	257.000	261.000
+17	175	257.750	39400	0.000	255.000	257.750
+17	176	255.500	47500	0.000	253.500	257.500
+17	177	248.500	147400	0.000	247.250	254.000
+17	178	251.500	107100	0.000	245.000	251.500
+17	179	259.500	70100	0.000	252.500	262.000
+17	180	261.750	49800	0.000	255.000	263.500
+17	181	274.000	146700	0.000	270.500	284.500
+17	182	281.000	82800	0.000	277.500	283.750
+17	183	282.000	52000	0.000	281.000	284.500
+17	184	279.250	39600	0.000	278.000	280.250
+18	185	248.000	38000	0.000	247.750	250.000
+18	186	246.500	25100	0.000	244.000	248.250
+18	187	247.000	27100	0.000	245.000	248.750
+18	188	244.375	30500	0.000	244.000	248.000
+18	189	243.250	31600	0.000	240.500	244.250
+18	190	246.250	34900	0.000	245.250	248.500
+18	191	245.250	35300	0.000	245.130	249.750
+18	192	241.250	30700	0.000	240.250	244.500
+19	193	240.500	34800	0.000	237.500	243.250
+19	194	246.500	43600	0.000	236.500	246.500
+19	195	249.500	68300	0.000	246.500	251.500
+19	196	250.000	35100	0.000	249.125	254.000
+19	197	248.750	56400	0.000	247.000	251.500
+19	198	249.250	32100	0.000	246.750	250.500
+19	199	247.500	29300	0.000	247.375	250.750
+19	200	245.750	20000	0.000	245.250	247.500
+19	201	246.250	22500	0.000	245.125	246.750
+19	202	243.000	38800	0.000	242.500	247.750
+20	203	182.250	84300	0.000	176.500	183.500
+20	204	179.000	63300	0.000	179.000	185.500
+20	205	173.000	59200	0.000	171.750	178.500
+20	206	171.500	69600	0.000	170.250	175.250
+20	207	165.125	70500	0.000	165.125	172.250
+20	208	156.500	113200	0.000	155.250	165.000
+20	209	152.000	131000	0.000	150.500	157.250
+20	210	159.625	109100	0.000	150.500	159.750
+20	211	161.880	87800	0.000	161.750	168.500
+20	212	166.500	75800	0.000	158.000	166.500
+20	213	170.500	95900	0.000	169.250	173.750
+20	214	171.500	80600	0.000	166.500	173.500
+20	215	169.250	59500	0.000	168.250	175.000
+20	216	166.750	47000	0.000	164.750	168.000
+20	217	165.000	59700	0.000	165.000	171.000
+20	218	164.000	25800	0.000	160.250	164.000
+20	219	160.875	51900	0.000	160.000	166.750
+20	220	159.000	84100	0.000	153.500	159.500
+20	221	160.250	125800	0.000	154.250	161.750
+20	222	159.500	63900	0.000	158.500	163.500
+20	223	157.750	56100	0.000	155.625	160.500
+20	224	156.250	74200	0.000	154.250	159.500
+20	225	164.125	60900	0.000	159.250	164.750
+20	226	162.000	87000	0.000	160.750	164.500
+21	227	162.250	51800	0.000	161.750	166.000
+21	228	164.250	65300	0.000	160.130	164.250
+21	229	168.000	48900	0.000	166.000	168.875
+21	230	168.875	45100	0.000	168.250	171.375
+21	231	167.500	78000	0.000	166.750	171.250
+21	232	166.625	53000	0.000	165.500	170.250
+21	233	165.750	49000	0.000	163.500	166.500
+21	234	163.250	58700	0.000	163.250	167.125
+21	235	168.500	56700	0.000	162.630	168.500
+22	236	212.000	89200	0.000	212.000	217.750
+22	237	207.500	117700	0.000	206.000	209.750
+22	238	212.000	95100	0.000	207.500	212.500
+22	239	212.250	74000	0.000	211.500	214.000
+22	240	215.500	68400	0.000	211.880	215.750
+22	241	220.000	79200	0.000	216.000	220.000
+23	242	222.500	45700	0.000	222.250	224.630
+23	243	223.250	43000	0.000	221.500	223.500
+23	244	224.250	47700	0.000	223.500	225.250
+23	245	226.500	43800	0.000	223.380	226.500
+23	246	230.000	88800	0.000	226.250	230.000
+23	247	229.380	118000	0.000	229.000	230.880
+23	248	228.500	127100	0.000	228.375	231.000
+23	249	230.380	136400	0.000	228.500	230.750
+24	250	249.880	97500	0.000	249.630	255.000
+24	251	251.000	90400	0.000	248.130	252.250
+24	252	256.500	90400	0.000	251.000	257.000
+24	253	257.750	111000	0.000	257.625	259.750
+24	254	259.250	87200	0.000	256.000	259.250
+24	255	261.000	111100	0.000	258.250	261.250
+24	256	263.750	75900	0.000	261.250	264.500
+24	257	258.000	121100	0.000	257.750	263.250
+24	258	254.000	125500	0.000	254.000	257.250
+24	259	253.500	78400	0.000	252.750	257.750
+24	260	258.000	74700	0.000	253.000	258.000
+25	261	279.750	62700	0.000	277.130	280.000
+25	262	277.625	85500	0.000	276.750	280.375
+25	263	276.630	99800	0.000	276.630	280.380
+25	264	276.250	113600	0.000	276.000	279.500
+25	265	274.250	187100	0.000	272.750	276.380
+25	266	272.000	105300	0.000	272.000	275.500
+25	267	270.500	111000	0.000	268.000	272.750
+25	268	271.000	66000	0.000	270.500	272.500
+25	269	272.500	43000	0.000	270.250	272.500
+25	270	273.000	56200	0.000	272.000	273.880
+25	271	275.500	55200	0.000	273.750	275.500
+25	272	272.250	73400	0.000	272.000	275.500
+26	273	262.250	89000	0.000	262.000	267.750
+26	274	259.500	146100	0.000	257.500	261.750
+26	275	260.250	90300	0.000	257.500	260.625
+26	276	261.000	74100	0.000	258.880	261.880
+26	277	264.500	44400	0.000	260.250	264.880
+26	278	262.000	78900	0.000	261.250	264.500
+27	279	272.500	132000	0.000	270.130	272.500
+27	280	272.000	79800	0.000	271.375	272.625
+27	281	271.130	75600	0.000	270.750	272.880
+27	282	270.000	113800	0.000	269.880	271.500
+27	283	264.000	179500	0.000	263.500	270.500
+27	284	258.000	215300	0.000	257.500	263.250
+27	285	258.250	154200	0.000	256.500	259.625
+27	286	259.500	95600	0.000	257.500	260.500
+27	287	261.250	96500	0.000	259.250	262.000
+27	288	259.750	119000	0.000	259.250	261.625
+27	289	258.750	81500	0.000	257.130	259.750
+28	290	257.380	53700	0.000	257.250	259.250
+28	291	256.000	52200	0.000	255.375	257.500
+28	292	257.750	76200	0.000	255.630	258.630
+28	293	258.750	93400	0.000	257.380	259.500
+28	294	258.750	99000	0.000	258.500	259.630
+28	295	257.250	123100	0.000	255.750	257.500
+28	296	260.500	188300	0.000	257.000	261.000
+28	297	260.250	103300	0.000	259.000	261.250
+29	298	264.250	110100	0.000	261.630	264.380
+29	299	266.000	98100	0.000	264.250	266.750
+29	300	267.500	146100	0.000	266.625	268.000
+29	301	270.250	199400	0.000	267.500	270.250
+29	302	270.250	89800	0.000	269.000	270.625
+29	303	271.000	78600	0.000	269.250	271.250
+29	304	272.750	107600	0.000	269.880	273.500
+29	305	273.500	119200	0.000	272.750	275.250
+29	306	273.500	0	0.000	0.000	0.000
+30	307	236.250	146100	0.000	236.250	242.000
+30	308	239.500	358100	0.000	235.500	239.500
+30	309	243.500	241500	0.000	240.500	244.000
+30	310	251.125	304800	0.000	248.375	253.625
+30	311	251.250	231000	0.000	248.875	253.000
+30	312	253.000	152800	0.000	249.625	254.000
+30	313	253.500	175100	0.000	252.500	257.880
+30	314	254.000	141800	0.000	252.125	255.500
+30	315	258.000	110000	0.000	253.000	258.250
+30	316	261.750	374200	0.000	261.250	264.000
+30	317	262.380	275100	0.000	261.380	265.000
+30	318	261.500	169700	0.000	259.875	261.750
+31	319	262.500	87100	0.000	262.250	266.500
+31	320	258.250	91100	0.000	257.750	262.500
+31	321	260.880	105600	0.000	258.250	262.000
+31	322	261.750	85000	0.000	258.500	261.880
+31	323	259.630	68400	0.000	259.000	262.250
+31	324	257.250	45500	0.000	257.250	260.250
+31	325	256.750	39900	0.000	255.000	257.500
+31	326	258.000	102400	0.000	255.250	259.500
+32	327	268.125	180700	0.000	267.750	272.000
+32	328	270.250	80900	0.000	267.000	270.250
+32	329	271.000	107200	0.000	267.750	271.000
+32	330	273.000	149400	0.000	269.250	273.000
+32	331	273.500	262900	0.000	273.000	276.750
+32	332	276.250	150300	0.000	273.000	276.250
+32	333	278.630	172800	0.000	275.500	279.500
+32	334	281.000	132700	0.000	278.750	281.500
+32	335	279.125	178400	0.000	279.000	281.750
+33	336	311.000	96900	0.000	308.130	311.000
+33	337	308.250	85000	0.000	307.625	311.000
+33	338	305.750	119200	0.000	304.500	306.625
+33	339	303.500	133200	0.000	303.000	306.500
+33	340	298.500	168400	0.000	297.130	299.750
+33	341	299.630	77900	0.000	299.130	300.630
+33	342	301.750	91100	0.000	300.130	301.880
+33	343	306.630	78700	0.000	299.750	307.000
+33	344	308.125	132600	0.000	306.750	310.000
+33	345	305.500	82400	0.000	304.000	308.250
+34	346	308.875	80600	0.000	308.250	312.875
+34	347	306.750	124000	0.000	306.250	309.250
+34	348	310.000	123300	0.000	307.000	310.250
+34	349	310.250	102600	0.000	309.750	312.875
+34	350	312.000	80400	0.000	309.880	312.250
+34	351	308.880	115900	0.000	308.500	312.000
+34	352	310.500	98300	0.000	307.500	310.500
+34	353	314.250	116900	0.000	309.750	314.250
+34	354	315.625	118600	0.000	314.250	317.500
+34	355	318.000	98700	0.000	315.000	318.500
+34	356	319.750	149000	0.000	318.000	321.500
+34	357	311.250	121900	0.000	311.000	317.500
+34	358	309.000	84400	0.000	308.130	309.880
+34	359	312.000	126500	0.000	308.625	312.250
+35	360	78.000	512100	0.000	77.500	78.500
+35	361	75.375	607700	0.000	75.250	78.000
+35	362	74.625	628300	0.000	73.750	75.250
+35	363	74.250	517300	0.000	73.875	75.000
+35	364	72.750	358300	0.000	72.625	74.000
+35	365	72.630	394600	0.000	72.250	73.500
+35	366	73.000	599200	0.000	72.130	73.750
+35	367	73.500	450200	0.000	72.875	74.500
+35	368	74.130	304400	0.000	73.880	74.250
+35	369	73.875	289200	0.000	73.375	74.500
+36	370	72.250	498300	0.000	69.875	72.375
+36	371	71.630	476800	0.000	71.000	72.500
+36	372	71.250	282600	0.000	71.000	71.880
+36	373	71.630	350300	0.000	70.880	71.880
+36	374	70.880	261500	0.000	70.500	71.630
+36	375	70.500	531700	0.000	70.380	71.130
+36	376	69.625	391900	0.000	69.500	70.750
+36	377	69.625	337000	0.000	69.125	70.500
+36	378	70.000	338900	0.000	69.500	70.625
+36	379	70.000	393400	0.000	69.625	70.125
+36	380	69.630	293200	0.000	69.630	70.250
+36	381	69.500	205300	0.000	69.500	70.000
+36	382	70.000	268300	0.000	69.750	70.000
+36	383	68.630	381500	0.000	68.500	69.880
+36	384	68.250	693200	0.000	67.250	68.500
+36	385	67.630	316100	0.000	67.500	68.250
+36	386	67.750	406600	0.000	67.380	68.000
+36	387	67.500	305800	0.000	67.375	67.875
+36	388	66.500	466500	0.000	66.125	67.750
+36	389	66.250	652800	0.000	65.750	66.625
+36	390	66.750	399300	0.000	66.125	66.875
+36	391	67.880	502100	0.000	66.500	68.380
+36	392	68.500	538900	0.000	68.380	69.250
+36	393	67.880	407700	0.000	67.750	68.500
+36	394	67.750	396500	0.000	67.750	68.630
+36	395	71.250	439900	0.000	67.625	71.375
+36	396	70.000	626100	0.000	69.380	71.000
+37	397	65.000	208900	0.000	64.500	65.125
+37	398	65.380	291800	0.000	64.880	65.380
+37	399	65.750	377600	0.000	65.500	66.380
+37	400	67.250	283500	0.000	65.380	67.250
+37	401	66.630	582400	0.000	66.380	67.630
+37	402	66.375	257200	0.000	66.125	66.625
+37	403	65.625	393900	0.000	65.625	66.750
+37	404	65.250	295500	0.000	65.130	65.750
+37	405	65.000	329700	0.000	64.630	65.250
+37	406	66.000	412400	0.000	64.880	66.130
+38	407	64.875	176300	0.000	64.000	64.875
+38	408	64.875	163300	0.000	64.375	65.125
+38	409	64.750	253800	0.000	64.250	65.000
+38	410	64.250	279200	0.000	64.000	64.630
+38	411	64.380	308600	0.000	64.000	64.630
+38	412	62.500	412000	0.000	62.500	64.500
+38	413	63.500	610300	0.000	61.250	63.500
+38	414	63.380	472800	0.000	63.000	63.750
+39	415	54.625	512900	0.000	53.375	54.750
+39	416	54.250	504900	0.000	54.000	55.250
+39	417	53.500	651700	0.000	53.500	55.000
+39	418	53.000	334100	0.000	52.750	53.750
+39	419	52.000	579900	0.000	51.875	53.500
+39	420	51.125	672300	0.000	51.000	52.875
+39	421	51.250	451000	0.000	50.380	51.630
+39	422	51.250	411900	0.000	50.875	51.750
+39	423	51.250	663800	0.000	50.500	51.625
+39	424	53.875	821800	0.000	52.000	54.500
+39	425	53.500	761400	0.000	53.250	54.375
+40	426	66.000	437200	0.000	64.250	66.000
+40	427	65.130	553000	0.000	64.750	66.130
+40	428	64.880	449000	0.000	64.380	65.380
+40	429	64.750	397400	0.000	64.250	65.000
+40	430	64.380	375800	0.000	63.880	64.630
+40	431	65.000	270800	0.000	64.000	65.250
+40	432	65.125	410600	0.000	64.375	65.500
+40	433	65.500	555700	0.000	65.130	66.000
+40	434	65.250	644100	0.000	64.380	65.380
+41	435	56.750	492500	0.000	56.250	56.880
+41	436	56.630	616200	0.000	55.750	56.630
+41	437	56.380	348000	0.000	56.130	56.630
+41	438	55.625	461800	0.000	55.500	56.375
+41	439	55.500	438400	0.000	55.250	55.875
+41	440	56.130	514900	0.000	55.130	56.380
+41	441	57.880	673900	0.000	55.880	58.130
+41	442	58.000	700200	0.000	57.250	58.500
+41	443	58.750	796900	0.000	57.880	59.130
+41	444	60.250	1089200	0.000	59.750	60.750
+41	445	59.880	747600	0.000	59.880	60.500
+42	446	55.875	387300	0.000	55.000	56.750
+42	447	55.500	396600	0.000	55.500	56.500
+42	448	54.880	372500	0.000	54.500	55.380
+42	449	54.130	551600	0.000	53.500	55.130
+42	450	54.000	346100	0.000	53.875	54.500
+42	451	54.375	427300	0.000	54.125	55.000
+42	452	54.500	389800	0.000	53.380	54.630
+42	453	54.625	497600	0.000	54.250	55.250
+42	454	53.625	524200	0.000	53.250	54.250
+43	455	64.625	1058800	0.000	63.375	64.625
+43	456	64.500	689400	0.000	64.250	64.880
+43	457	63.750	1140600	0.000	63.625	65.125
+43	458	63.250	892800	0.000	63.000	63.880
+43	459	63.875	512200	0.000	63.250	63.875
+43	460	64.375	645800	0.000	64.000	64.750
+43	461	65.750	1214100	0.000	64.500	65.750
+43	462	66.000	911700	0.000	65.000	66.130
+43	463	65.125	685600	0.000	64.625	65.750
+43	464	64.880	717200	0.000	64.500	65.250
+43	465	64.125	491600	0.000	64.125	64.625
+43	466	64.250	759200	0.000	64.000	64.750
+43	467	64.500	384600	0.000	64.000	64.750
+43	468	64.750	497500	0.000	64.500	65.250
+43	469	65.125	855600	0.000	64.750	65.250
+43	470	64.875	777200	0.000	64.750	65.125
+43	471	64.750	487900	0.000	64.750	65.130
+43	472	63.875	569800	0.000	63.875	64.875
+43	473	64.380	372400	0.000	64.000	64.750
+44	474	60.000	290100	0.000	60.000	60.630
+44	475	60.380	358800	0.000	59.380	60.750
+44	476	61.000	638300	0.000	60.380	61.250
+44	477	61.500	963900	0.000	59.750	61.630
+44	478	62.500	1247100	0.000	61.380	62.500
+44	479	63.500	985100	0.000	62.880	63.630
+44	480	64.500	1556300	0.000	63.125	65.000
+44	481	66.875	1688100	0.000	64.750	66.875
+44	482	66.750	1578700	0.000	66.375	67.500
+45	483	76.750	1321700	0.000	74.750	76.750
+45	484	75.500	1604100	0.000	75.500	77.630
+45	485	76.380	1254000	0.000	75.250	76.630
+45	486	76.000	887100	0.000	75.630	76.500
+45	487	76.630	490500	0.000	75.750	77.000
+45	488	76.250	868300	0.000	76.250	77.250
+45	489	74.750	831000	0.000	74.500	76.375
+45	490	73.375	997900	0.000	73.250	74.875
+45	491	74.130	747500	0.000	73.380	74.630
+45	492	74.500	614900	0.000	73.250	74.630
+45	493	75.130	752300	0.000	74.630	76.130
+45	494	79.000	1346100	0.000	75.375	79.000
+45	495	80.380	2207600	0.000	78.380	80.380
+45	496	81.130	1342500	0.000	79.250	81.130
+45	497	83.500	1439300	0.000	81.380	84.500
+45	498	82.750	1500400	0.000	82.375	84.375
+46	499	96.130	725400	0.000	95.750	98.000
+46	500	96.250	373700	0.000	96.125	97.125
+46	501	93.000	760600	0.000	92.500	97.000
+46	502	95.625	915100	0.000	92.375	95.625
+46	503	96.000	950900	0.000	95.000	96.750
+46	504	97.625	1024200	0.000	95.500	98.500
+46	505	96.630	1060600	0.000	96.500	98.380
+46	506	98.000	1114200	0.000	96.000	99.250
+46	507	98.000	850900	0.000	97.000	98.380
+47	508	102.000	711800	0.000	101.880	103.250
+47	509	102.625	858000	0.000	101.250	102.875
+47	510	103.250	607100	0.000	102.000	103.375
+47	511	103.875	894200	0.000	102.625	104.000
+47	512	106.625	1651200	0.000	104.625	106.750
+47	513	107.000	1049000	0.000	106.000	107.380
+47	514	108.750	978800	0.000	107.375	109.000
+47	515	109.500	1007500	0.000	107.250	110.000
+47	516	110.125	794100	0.000	109.625	110.500
+47	517	112.630	1020400	0.000	110.000	112.630
+47	518	111.500	929400	0.000	111.000	112.130
+48	519	116.500	424700	0.000	115.625	116.625
+48	520	115.250	668900	0.000	114.000	115.250
+48	521	114.000	722000	0.000	113.125	115.000
+48	522	111.750	802300	0.000	110.750	114.750
+48	523	111.250	673500	0.000	110.500	112.500
+48	524	110.750	538900	0.000	110.250	111.750
+48	525	112.500	813000	0.000	109.750	112.875
+48	526	114.630	665400	0.000	113.000	115.000
+48	527	115.630	843600	0.000	113.380	115.630
+48	528	114.380	647800	0.000	114.250	115.880
+48	529	113.000	404400	0.000	112.875	115.000
+48	530	111.250	734800	0.000	110.250	112.880
+48	531	111.875	890300	0.000	110.250	111.875
+48	532	113.500	803000	0.000	111.250	113.875
+48	533	114.000	662100	0.000	113.000	114.880
+48	534	115.750	573900	0.000	113.630	116.130
+48	535	113.130	791400	0.000	113.000	116.250
+48	536	113.375	831700	0.000	112.625	114.750
+48	537	113.750	672300	0.000	113.130	114.500
+48	538	114.250	419600	0.000	113.630	114.630
+48	539	117.250	737800	0.000	114.125	117.250
+48	540	118.000	971500	0.000	117.000	119.750
+48	541	121.000	1170300	0.000	118.130	121.000
+48	542	121.750	1233400	0.000	121.500	122.875
+48	543	121.130	625500	0.000	120.250	122.250
+49	544	120.875	542900	0.000	120.250	122.750
+49	545	118.000	865300	0.000	117.750	121.380
+49	546	120.000	669800	0.000	117.880	120.880
+49	547	120.250	556200	0.000	119.750	121.000
+49	548	121.000	373100	0.000	120.375	121.250
+49	549	119.250	943300	0.000	118.625	119.625
+50	550	122.880	814300	0.000	121.630	123.500
+50	551	121.750	691100	0.000	121.500	123.250
+50	552	123.125	819700	0.000	121.500	124.250
+50	553	123.750	911500	0.000	122.625	124.875
+50	554	123.875	942300	0.000	123.125	124.500
+50	555	123.000	1070900	0.000	122.875	124.125
+50	556	124.625	1099300	0.000	122.750	124.750
+50	557	126.625	1111900	0.000	124.250	126.625
+50	558	128.625	2097500	0.000	126.000	129.500
+50	559	127.875	1271500	0.000	126.500	128.375
+51	560	129.875	1190200	0.000	128.875	130.125
+51	561	131.130	1391200	0.000	129.130	131.250
+51	562	132.130	1104600	0.000	131.000	132.250
+51	563	132.250	803300	0.000	131.750	132.500
+51	564	134.250	658400	0.000	131.500	134.250
+51	565	133.000	687100	0.000	132.750	134.000
+52	566	126.750	1413200	0.000	125.000	127.250
+52	567	126.500	946400	0.000	125.500	127.000
+52	568	123.880	922600	0.000	123.500	126.500
+52	569	122.250	1474500	0.000	121.750	123.250
+52	570	122.125	803600	0.000	122.000	123.375
+52	571	122.250	650900	0.000	121.880	122.880
+52	572	123.625	858900	0.000	122.375	123.625
+52	573	125.250	1165800	0.000	124.000	125.750
+52	574	126.875	784800	0.000	125.125	127.250
+52	575	127.500	1030600	0.000	127.000	128.250
+52	576	124.500	1354300	0.000	124.000	127.630
+53	577	111.250	1043200	0.000	109.250	111.500
+53	578	112.880	1458900	0.000	110.750	113.500
+53	579	110.000	1241300	0.000	109.875	112.500
+53	580	110.250	1117000	0.000	109.375	111.750
+53	581	111.500	812900	0.000	109.750	111.625
+53	582	112.000	1005000	0.000	111.625	112.875
+53	583	111.000	779400	0.000	110.375	111.500
+53	584	109.250	868500	0.000	109.125	111.625
+54	585	108.000	729600	0.000	107.375	108.625
+54	586	110.250	1455900	0.000	108.500	110.500
+54	587	110.625	1432300	0.000	110.375	112.000
+54	588	111.000	990700	0.000	110.375	111.500
+54	589	112.000	954700	0.000	111.125	112.500
+54	590	113.750	2110500	0.000	112.750	114.250
+54	591	114.000	817600	0.000	112.500	114.000
+54	592	114.750	1241000	0.000	113.500	115.380
+54	593	114.000	914900	0.000	114.000	115.500
+54	594	112.750	881400	0.000	112.375	114.000
+54	595	112.250	836700	0.000	111.500	113.000
+54	596	112.250	694200	0.000	111.750	113.250
+55	597	112.750	770500	0.000	110.630	112.880
+55	598	112.250	931500	0.000	112.000	113.500
+55	599	111.125	720700	0.000	110.500	112.250
+55	600	110.750	1028700	0.000	110.125	111.125
+55	601	109.880	836400	0.000	109.630	111.380
+55	602	110.750	1104400	0.000	109.500	111.625
+55	603	111.875	899400	0.000	110.625	112.250
+55	604	113.250	1090000	0.000	111.875	113.500
+55	605	113.380	1022900	0.000	112.630	114.250
+55	606	113.750	1122500	0.000	112.750	114.630
+55	607	116.500	1463500	0.000	114.000	116.500
+55	608	116.250	1337900	0.000	116.000	117.250
+56	609	107.250	704700	0.000	105.375	107.500
+56	610	107.125	802400	0.000	106.250	107.375
+56	611	105.250	897500	0.000	105.250	107.130
+56	612	104.375	1076900	0.000	104.125	105.625
+56	613	105.250	856100	0.000	104.000	105.750
+56	614	107.250	925700	0.000	104.500	107.250
+56	615	108.130	1047100	0.000	106.750	108.380
+56	616	107.500	625100	0.000	107.125	108.125
+56	617	107.000	895900	0.000	106.250	107.375
+56	618	106.500	810000	0.000	105.500	107.250
+56	619	106.125	931100	0.000	105.125	106.375
+56	620	105.380	710200	0.000	105.130	107.000
+56	621	107.125	1591800	0.000	104.500	107.750
+56	622	108.250	1002700	0.000	106.750	108.750
+56	623	109.000	1059300	0.000	107.875	109.625
+56	624	108.380	610400	0.000	108.250	109.380
+57	625	124.625	929500	0.000	124.625	126.125
+57	626	125.750	1200100	0.000	125.250	126.875
+57	627	125.880	763200	0.000	125.750	126.500
+57	628	126.750	589700	0.000	123.750	126.875
+57	629	127.500	1270600	0.000	126.500	127.750
+57	630	125.750	1668400	0.000	125.375	127.125
+57	631	124.880	1056700	0.000	124.250	125.750
+57	632	123.250	944300	0.000	123.250	125.500
+57	633	124.000	782700	0.000	122.750	124.000
+58	634	124.250	754200	0.000	123.250	124.500
+58	635	123.750	418300	0.000	123.625	124.250
+58	636	123.125	505200	0.000	122.750	124.250
+58	637	123.500	573600	0.000	122.750	124.000
+58	638	123.125	685000	0.000	122.875	123.875
+58	639	121.000	872500	0.000	120.750	122.630
+58	640	120.000	1388100	0.000	119.875	122.250
+58	641	119.750	1007000	0.000	119.000	120.375
+59	642	123.625	1069600	0.000	123.250	124.625
+59	643	124.130	1163300	0.000	123.630	125.000
+59	644	128.250	2138800	0.000	124.630	128.500
+59	645	129.630	2539000	0.000	129.130	130.630
+59	646	132.500	2270200	0.000	129.375	132.625
+59	647	133.130	1825200	0.000	132.380	134.500
+59	648	133.250	1212300	0.000	132.625	134.125
+59	649	134.625	1936500	0.000	133.250	135.250
+59	650	137.000	1128700	0.000	133.750	137.000
+59	651	136.630	1563600	0.000	136.130	137.630
+60	652	130.500	1037200	0.000	128.250	131.125
+60	653	129.375	1118800	0.000	129.000	130.625
+60	654	128.750	1552200	0.000	128.125	130.000
+60	655	127.750	1197800	0.000	127.750	128.750
+60	656	124.500	2057900	0.000	124.500	128.000
+60	657	125.375	1404400	0.000	124.125	125.625
+60	658	126.380	1098400	0.000	125.500	126.630
+60	659	126.625	993400	0.000	126.375	127.625
+60	660	128.125	840800	0.000	126.875	128.250
+60	661	127.750	949000	0.000	127.500	129.500
+61	662	126.500	1280300	0.000	125.500	126.750
+61	663	125.630	1135000	0.000	125.130	126.880
+61	664	125.375	1258800	0.000	124.750	126.375
+61	665	125.000	770500	0.000	124.630	125.630
+61	666	124.750	579400	0.000	124.750	125.625
+61	667	125.750	772900	0.000	125.000	126.250
+61	668	127.125	925700	0.000	125.375	127.250
+61	669	127.880	978300	0.000	127.000	128.250
+61	670	130.130	2239000	0.000	128.500	130.880
+61	671	130.250	1157600	0.000	129.750	130.625
+61	672	128.000	1551200	0.000	127.750	130.875
+62	673	133.000	1215000	0.000	132.380	133.250
+62	674	132.375	857100	0.000	131.875	132.750
+62	675	131.375	829300	0.000	131.250	132.375
+62	676	130.880	675200	0.000	130.750	131.630
+62	677	130.375	921900	0.000	129.750	131.750
+62	678	129.750	939700	0.000	129.250	130.250
+62	679	128.000	1666600	0.000	127.250	129.500
+62	680	128.625	1371900	0.000	127.250	130.000
+62	681	129.125	1265600	0.000	128.250	129.500
+62	682	129.750	1176100	0.000	128.750	130.130
+62	683	128.500	1644500	0.000	128.500	130.630
+63	684	121.130	1753000	0.000	119.380	121.130
+63	685	120.130	1316600	0.000	119.250	120.500
+63	686	119.875	1819000	0.000	119.125	121.625
+63	687	119.375	1268900	0.000	119.250	120.875
+63	688	118.750	1400300	0.000	117.375	119.750
+63	689	119.380	1365100	0.000	118.380	119.750
+63	690	120.875	1125300	0.000	118.750	121.125
+63	691	122.000	1753000	0.000	121.380	123.380
+63	692	123.130	914300	0.000	122.000	123.250
+63	693	124.000	1151500	0.000	123.125	124.250
+63	694	123.750	820500	0.000	123.500	124.500
+64	695	141.750	1638400	0.000	140.250	141.750
+64	696	144.630	1662500	0.000	142.130	144.880
+64	697	146.625	1940200	0.000	144.250	148.000
+64	698	149.000	1985600	0.000	146.625	149.375
+64	699	148.630	1407600	0.000	147.000	149.380
+64	700	150.250	1890100	0.000	149.130	151.500
+64	701	152.250	1586100	0.000	150.000	153.500
+64	702	152.500	1786100	0.000	151.500	154.500
+64	703	152.875	1524100	0.000	151.625	153.875
+64	704	153.750	1105900	0.000	152.375	154.000
+64	705	154.250	2127800	0.000	153.750	156.625
+64	706	154.000	1220900	0.000	153.380	155.130
+64	707	152.750	1011600	0.000	151.250	154.630
+64	708	153.250	562700	0.000	152.125	153.750
+65	709	141.130	1858600	0.000	138.880	141.250
+65	710	141.125	1561600	0.000	140.500	142.000
+65	711	140.000	1229000	0.000	139.500	140.380
+65	712	138.750	887600	0.000	138.000	140.000
+65	713	136.000	1938300	0.000	135.500	138.875
+65	714	136.125	1628600	0.000	135.125	136.375
+65	715	139.380	1630000	0.000	136.000	139.500
+65	716	140.375	2618100	0.000	138.500	141.000
+65	717	143.750	2629100	0.000	140.875	143.875
+65	718	143.880	2251100	0.000	143.500	145.500
+65	719	144.130	1766900	0.000	142.880	144.500
+65	720	139.250	2866100	0.000	138.750	142.880
+65	721	137.380	4379500	0.000	136.250	139.880
+65	722	137.000	2194500	0.000	136.000	138.500
+65	723	138.250	1413100	0.000	135.625	138.500
+66	724	123.625	2431100	0.000	122.375	124.500
+66	725	122.000	1609300	0.000	121.880	125.250
+66	726	120.880	3142200	0.000	119.750	123.000
+66	727	123.000	2239500	0.000	120.375	123.000
+66	728	121.130	2220400	0.000	120.880	123.380
+66	729	121.875	1947600	0.000	120.500	122.375
+66	730	120.250	1484700	0.000	119.875	121.250
+66	731	121.375	1697000	0.000	120.250	121.375
+66	732	120.375	1283900	0.000	120.125	121.500
+67	733	123.130	2107700	0.000	122.500	124.750
+67	734	121.380	2581200	0.000	119.250	122.000
+67	735	121.500	1103400	0.000	120.000	121.880
+67	736	123.125	998200	0.000	121.250	123.250
+67	737	123.750	751400	0.000	122.875	124.250
+67	738	122.750	1130400	0.000	121.875	124.375
+68	739	151.750	1804700	0.000	151.500	154.130
+68	740	154.250	3308900	0.000	149.500	156.000
+68	741	155.250	2945900	0.000	154.625	156.625
+68	742	158.630	3248800	0.000	155.880	159.630
+68	743	160.125	3272200	0.000	157.750	161.500
+68	744	160.630	2385000	0.000	159.130	162.380
+68	745	163.000	1561700	0.000	159.750	163.000
+68	746	166.875	2792500	0.000	164.250	167.625
+68	747	166.750	2187900	0.000	166.000	167.630
+68	748	164.880	1652200	0.000	163.880	166.750
+68	749	163.750	1430500	0.000	163.250	165.875
+68	750	163.000	2269600	0.000	163.000	167.380
+68	751	165.380	1998200	0.000	162.250	166.130
+69	752	159.250	2057900	0.000	158.750	160.880
+69	753	159.380	1668400	0.000	158.500	160.000
+69	754	160.250	2435800	0.000	159.750	161.000
+69	755	163.000	2284000	0.000	159.125	163.250
+69	756	164.375	2386900	0.000	163.000	165.625
+69	757	166.750	1632200	0.000	164.500	166.750
+69	758	169.000	3203300	0.000	167.130	169.630
+69	759	170.380	3299900	0.000	168.000	172.130
+69	760	173.380	2586600	0.000	170.380	174.000
+69	761	173.250	2109200	0.000	172.000	175.000
+70	762	150.500	2630500	0.000	149.500	153.750
+70	763	150.750	3073300	0.000	148.500	151.880
+70	764	154.630	1908400	0.000	151.000	154.750
+70	765	155.250	1868500	0.000	154.750	156.880
+70	766	156.500	1544300	0.000	154.500	157.250
+70	767	151.000	2044200	0.000	151.000	156.375
+71	768	145.250	2922100	0.000	144.130	147.380
+71	769	140.125	3923900	0.000	140.000	145.750
+71	770	135.000	4665000	0.000	132.000	141.250
+71	771	104.000	6384400	0.000	102.000	130.750
+71	772	115.000	0	0.000	110.130	122.000
+71	773	122.750	5386600	0.000	120.000	125.500
+72	774	118.880	2233600	0.000	115.000	119.250
+72	775	115.500	1824700	0.000	115.000	119.500
+72	776	117.250	2798900	0.000	115.250	118.250
+72	777	118.250	1550200	0.000	116.880	119.500
+72	778	118.250	1217000	0.000	116.500	118.375
+72	779	119.500	1646400	0.000	118.750	120.380
+72	780	119.875	630300	0.000	119.000	119.875
+72	781	115.750	1086800	0.000	115.130	117.630
+73	782	111.630	1230300	0.000	110.750	112.130
+73	783	112.250	769000	0.000	111.500	112.750
+73	784	113.380	867400	0.000	112.750	114.000
+73	785	112.875	896800	0.000	112.625	113.750
+73	786	111.500	932200	0.000	110.750	113.500
+73	787	110.250	1489000	0.000	109.500	111.130
+73	788	114.000	1564900	0.000	111.630	114.750
+73	789	112.875	958200	0.000	112.375	113.875
+74	790	114.125	1652700	0.000	112.500	114.375
+74	791	113.500	947400	0.000	113.375	114.125
+74	792	112.750	1100200	0.000	112.500	114.380
+74	793	112.500	2195900	0.000	110.630	112.630
+74	794	113.000	1558100	0.000	111.880	113.000
+74	795	113.380	1187700	0.000	113.130	114.250
+74	796	115.000	1365300	0.000	113.630	115.250
+74	797	114.625	1992000	0.000	114.500	116.500
+74	798	114.000	1582100	0.000	113.625	115.000
+74	799	113.750	2225000	0.000	112.625	114.000
+74	800	115.500	2406400	0.000	113.250	115.750
+74	801	117.375	2209500	0.000	115.750	117.625
+74	802	118.250	2648200	0.000	117.750	119.375
+74	803	117.125	1619800	0.000	117.125	119.125
+75	804	116.380	1333800	0.000	116.000	118.380
+75	805	116.875	1509800	0.000	116.125	117.500
+75	806	117.130	939000	0.000	116.880	117.630
+75	807	117.380	1049800	0.000	116.880	118.250
+75	808	117.750	1708300	0.000	117.375	118.750
+75	809	116.750	1105600	0.000	116.000	117.630
+75	810	116.250	1141200	0.000	115.875	117.000
+75	811	116.000	1173400	0.000	115.000	116.380
+75	812	116.250	946600	0.000	115.375	116.375
+76	813	98.750	1249700	0.000	98.000	99.380
+76	814	99.500	1127900	0.000	98.500	99.750
+76	815	100.125	1129400	0.000	99.375	100.500
+76	816	100.375	638800	0.000	100.250	100.750
+76	817	99.380	1245400	0.000	98.250	100.750
+76	818	98.880	1157700	0.000	98.500	99.380
+76	819	97.750	956500	0.000	97.500	98.625
+76	820	97.630	1001300	0.000	96.880	98.130
+76	821	97.130	1434200	0.000	96.880	98.130
+76	822	99.250	2026900	0.000	97.380	99.500
+77	823	95.375	1005100	0.000	95.125	95.750
+77	824	94.500	682200	0.000	94.250	95.500
+77	825	94.750	1165700	0.000	94.500	95.375
+77	826	94.130	1192300	0.000	94.000	95.130
+77	827	94.130	1637100	0.000	94.000	94.630
+77	828	98.000	1760400	0.000	94.500	98.130
+77	829	98.875	2366000	0.000	98.375	99.500
+77	830	100.000	2418700	0.000	98.880	100.380
+77	831	99.750	1890500	0.000	99.500	101.630
+78	832	106.625	1050400	0.000	106.000	106.750
+78	833	106.500	1716200	0.000	105.880	107.750
+78	834	106.130	868400	0.000	105.880	106.880
+78	835	105.875	752300	0.000	105.250	106.375
+78	836	105.500	782800	0.000	105.250	105.880
+78	837	105.875	934800	0.000	105.125	106.375
+78	838	106.375	645200	0.000	105.875	106.500
+78	839	107.125	921600	0.000	107.000	108.000
+78	840	110.880	4120700	0.000	110.130	111.250
+78	841	111.125	1916900	0.000	109.875	111.250
+78	842	109.875	1531000	0.000	109.500	110.875
+79	843	102.380	1347000	0.000	101.500	103.500
+79	844	105.500	1634700	0.000	101.880	105.500
+79	845	105.880	1609400	0.000	105.500	107.630
+79	846	107.500	1438200	0.000	105.880	107.750
+79	847	107.880	1192900	0.000	107.130	108.380
+79	848	105.000	1077000	0.000	104.750	107.750
+80	849	107.375	1101700	0.000	107.125	109.000
+80	850	107.880	1162000	0.000	106.380	108.250
+80	851	108.250	1570000	0.000	106.000	109.000
+80	852	109.500	901300	0.000	108.625	109.500
+80	853	105.375	1418600	0.000	105.375	108.625
+80	854	103.500	2258600	0.000	102.875	106.625
+80	855	101.000	3113800	0.000	99.750	103.880
+80	856	100.250	2308100	0.000	99.500	102.000
+80	857	99.250	3121400	0.000	96.250	100.875
+80	858	99.380	1690200	0.000	98.250	100.380
+80	859	100.750	1330300	0.000	99.380	101.630
+80	860	105.375	1866500	0.000	101.750	105.375
+80	861	107.625	2658600	0.000	104.625	109.000
+80	862	107.750	1918300	0.000	106.500	108.750
+80	863	106.750	1270700	0.000	106.625	108.250
+81	864	111.500	3389800	0.000	111.250	116.000
+81	865	112.500	1909400	0.000	110.750	112.875
+81	866	113.380	1173800	0.000	112.130	113.750
+81	867	112.875	997900	0.000	112.375	113.125
+81	868	114.375	1471900	0.000	112.625	114.500
+81	869	112.880	1093100	0.000	112.880	114.630
+81	870	111.250	1435200	0.000	111.000	112.500
+81	871	111.500	954900	0.000	110.625	111.750
+81	872	113.500	1617100	0.000	111.500	113.500
+81	873	112.750	2463900	0.000	112.130	114.000
+81	874	113.750	1896000	0.000	112.250	114.630
+81	875	113.875	2084600	0.000	113.375	114.375
+81	876	113.880	341300	0.000	113.750	114.250
+81	877	113.500	396800	0.000	113.500	114.250
+81	878	113.630	714100	0.000	113.000	113.880
+81	879	113.375	728200	0.000	113.250	113.875
+81	880	113.000	461300	0.000	112.880	113.500
+81	881	112.125	1037700	0.000	112.125	113.750
+81	882	112.500	1307400	0.000	112.250	113.880
+81	883	112.130	1085100	0.000	111.880	113.000
+81	884	110.250	1189400	0.000	110.000	111.875
+81	885	109.000	1715500	0.000	108.750	110.375
+81	886	106.880	2078000	0.000	106.750	110.750
+81	887	108.380	962000	0.000	107.250	108.380
+81	888	108.130	608700	0.000	107.750	108.250
+81	889	106.750	1746500	0.000	105.500	107.130
+81	890	107.500	1168100	0.000	106.750	107.750
+81	891	109.130	1582000	0.000	106.630	109.250
+81	892	115.750	4330400	0.000	114.250	116.130
+81	893	117.625	4592500	0.000	114.875	118.250
+82	894	118.000	1963700	0.000	117.750	119.625
+82	895	119.250	2211000	0.000	117.875	120.125
+82	896	121.000	2841200	0.000	119.880	121.630
+82	897	122.625	2441100	0.000	120.500	122.625
+82	898	124.250	2478400	0.000	122.380	125.000
+82	899	124.500	1949200	0.000	123.000	125.380
+82	900	127.000	2524300	0.000	124.630	127.000
+82	901	126.750	1718300	0.000	126.250	127.130
+82	902	126.880	1919100	0.000	125.630	127.630
+83	903	128.500	2532000	0.000	128.380	131.000
+83	904	129.500	1751700	0.000	128.250	129.875
+83	905	132.375	1865300	0.000	129.625	132.500
+83	906	132.750	2372400	0.000	131.500	133.875
+83	907	134.630	1923800	0.000	132.250	135.000
+83	908	135.000	2485400	0.000	133.880	136.250
+83	909	137.375	2738900	0.000	135.375	137.750
+83	910	139.500	2278100	0.000	137.000	139.750
+83	911	137.880	1854200	0.000	137.880	138.750
+84	912	110.630	2214700	0.000	110.130	111.880
+84	913	108.500	3555500	0.000	108.130	111.000
+84	914	106.875	3026800	0.000	105.625	108.375
+84	915	109.250	2086700	0.000	106.750	109.250
+84	916	109.880	2089000	0.000	109.250	110.750
+84	917	109.750	1463800	0.000	109.375	110.750
+84	918	109.500	2109300	0.000	109.000	110.250
+84	919	108.500	1570400	0.000	108.125	109.375
+85	920	98.000	1438800	0.000	97.630	99.380
+85	921	97.250	1909500	0.000	96.750	98.250
+85	922	99.750	1417200	0.000	97.000	99.875
+85	923	99.880	893600	0.000	99.500	100.500
+85	924	101.250	791000	0.000	99.125	101.625
+85	925	104.250	3033600	0.000	99.750	104.750
+85	926	101.625	2025900	0.000	101.375	103.750
+85	927	99.875	1631900	0.000	99.375	101.250
+85	928	100.380	1315700	0.000	99.630	100.380
+86	929	94.625	1973000	92.000	91.875	94.750
+86	930	92.380	2515900	94.000	92.250	95.000
+86	931	91.250	2040100	92.625	91.250	94.250
+86	932	90.875	1611500	91.375	90.625	92.500
+86	933	90.250	1333300	90.750	89.750	90.875
+86	934	92.375	1338400	90.375	90.250	92.500
+86	935	95.380	3103900	94.000	93.500	95.750
+86	936	95.500	2253200	95.125	95.000	97.125
+86	937	96.375	3582000	95.000	92.625	98.125
+86	938	95.250	1209500	96.250	95.250	96.375
+86	939	92.880	1426400	95.250	92.880	95.500
+86	940	95.630	1273400	92.880	92.880	95.630
+87	941	92.250	1502600	91.125	90.000	92.250
+87	942	91.250	1632500	91.750	91.000	92.130
+87	943	89.880	1401700	90.380	89.630	90.880
+87	944	89.250	1724200	90.000	88.625	90.375
+87	945	89.750	945800	89.625	89.125	89.875
+87	946	90.250	1130700	89.750	89.750	90.875
+87	947	92.125	1581500	90.500	89.875	92.375
+87	948	90.750	1954000	92.750	90.130	93.250
+87	949	89.750	1295100	90.500	89.500	91.130
+87	950	89.625	1314500	90.000	89.125	91.125
+87	951	89.630	1148400	90.000	89.380	90.750
+87	952	89.750	1363200	89.750	89.125	90.625
+87	953	89.875	1446100	89.750	89.250	90.375
+87	954	89.380	1056500	89.880	88.750	90.250
+88	955	82.380	1926400	83.380	82.250	84.880
+88	956	84.875	3020100	82.625	82.625	85.000
+88	957	85.125	2275600	85.375	84.625	85.875
+88	958	86.000	2052900	85.630	84.500	86.130
+88	959	87.500	1712300	86.130	85.880	87.500
+88	960	88.250	3316600	89.500	88.125	89.750
+88	961	88.500	2215600	88.750	87.625	88.875
+88	962	88.625	2063100	88.500	87.500	88.625
+88	963	89.500	1792800	88.500	88.250	89.750
+88	964	90.000	2117200	89.630	89.500	90.250
+88	965	90.125	1324900	89.875	89.625	90.125
+88	966	89.250	1475400	90.000	89.000	90.630
+89	967	89.250	1475400	90.000	89.000	90.630
+89	968	88.130	993100	89.130	88.130	89.250
+89	969	88.125	1000900	87.875	87.750	88.750
+89	970	88.500	1108900	88.130	87.380	88.500
+89	971	88.130	1268600	88.880	87.750	88.880
+89	972	90.750	1681900	88.500	88.250	90.750
+89	973	90.625	2074400	91.250	90.375	92.125
+89	974	92.500	2341200	92.500	92.125	93.000
+89	975	93.875	2044900	92.500	92.375	94.000
+90	976	62.880	2541800	62.380	62.380	63.380
+90	977	56.130	12193500	0.000	56.000	59.880
+90	978	51.875	13421200	53.625	50.750	54.875
+90	979	53.000	8025400	0.000	51.250	53.380
+90	980	51.375	7658000	53.125	50.250	53.250
+90	981	48.875	7384600	51.250	48.750	51.625
+90	982	51.750	6115700	50.000	49.000	52.000
+90	983	51.250	4186200	51.625	51.000	52.625
+91	984	46.380	3638900	47.000	45.880	47.000
+91	985	48.625	3420500	46.500	46.500	48.750
+91	986	48.875	3054500	48.750	47.500	49.250
+91	987	49.000	7802400	52.875	48.750	53.250
+91	988	49.625	3307500	49.125	48.250	50.000
+91	989	50.250	3095700	50.000	49.750	50.875
+91	990	51.500	2981500	51.000	50.875	51.625
+91	991	52.625	3039500	52.000	52.000	52.625
+91	992	52.125	2635400	52.250	52.000	53.000
+92	993	42.250	2494200	43.625	42.000	43.625
+92	994	42.375	3922300	41.875	41.125	42.375
+92	995	45.630	6260300	44.880	44.500	45.880
+92	996	44.000	4216700	46.000	43.875	46.375
+93	997	51.875	2331700	52.250	51.500	52.625
+93	998	52.000	2595300	51.875	51.625	52.500
+93	999	53.125	2067200	52.375	51.875	53.250
+93	1000	55.125	4184000	54.000	53.750	55.250
+93	1001	55.750	1211000	55.500	55.125	56.000
+93	1002	54.380	2487900	56.000	54.380	56.130
+93	1003	53.875	1976800	54.500	53.750	55.125
+93	1004	53.130	2385300	54.750	53.130	54.750
+93	1005	53.750	1865800	53.250	53.250	54.125
+94	1006	59.000	1846800	58.130	58.000	59.130
+94	1007	59.500	2570000	59.000	58.500	59.875
+94	1008	58.500	2379800	60.000	58.500	60.000
+94	1009	58.875	1458600	58.500	58.000	59.375
+94	1010	59.250	1734900	58.875	58.500	59.500
+94	1011	58.630	1690600	59.130	58.500	59.380
+94	1012	58.130	1503100	58.750	58.130	58.880
+94	1013	58.750	1804200	58.250	58.250	59.000
+94	1014	58.630	1586000	58.750	58.380	59.500
+94	1015	57.500	1528100	58.500	57.130	58.500
+94	1016	57.125	2255900	57.375	56.375	57.375
+94	1017	56.000	1959500	56.750	55.750	57.000
+94	1018	55.250	2278500	55.875	55.125	55.875
+94	1019	55.250	3176600	55.125	54.750	55.625
+94	1020	58.630	4219300	55.750	55.750	58.750
+94	1021	58.250	10154900	58.880	55.380	59.380
+95	1022	52.880	1565600	53.380	52.750	53.630
+95	1023	53.250	1985500	52.500	52.000	53.380
+95	1024	54.000	1873700	53.375	53.375	54.625
+95	1025	54.500	1727400	54.380	54.000	54.630
+95	1026	54.625	1495700	55.250	54.500	55.250
+95	1027	52.750	2290200	54.880	52.500	55.000
+96	1028	53.380	2097500	53.500	51.380	53.750
+96	1029	52.250	2207700	53.250	51.750	53.500
+96	1030	58.380	8758100	55.000	54.000	58.630
+96	1031	58.750	5660500	58.375	58.000	59.500
+97	1032	58.500	2217200	58.880	58.500	59.250
+97	1033	57.125	2297500	57.875	56.750	58.250
+97	1034	57.500	1908600	57.375	56.875	57.875
+97	1035	58.000	1608500	57.500	56.875	58.375
+97	1036	58.380	1376600	58.130	57.880	58.630
+97	1037	57.750	1500300	58.250	57.500	58.250
+98	1038	55.625	1817200	56.750	55.625	56.875
+98	1039	55.880	3189300	55.750	54.500	56.250
+98	1040	62.380	8807500	59.000	58.000	62.630
+98	1041	61.380	3714100	62.250	61.130	62.380
+99	1042	72.250	2341600	73.625	72.250	74.125
+99	1043	73.125	2040800	72.500	71.875	73.125
+99	1044	73.250	1536400	72.880	72.750	73.750
+99	1045	74.375	2463400	73.500	73.375	74.500
+99	1046	75.380	3933900	74.000	73.750	75.750
+99	1047	75.000	5216900	75.500	73.875	76.125
+99	1048	74.625	3372500	74.625	74.125	75.375
+99	1049	73.000	2615200	74.625	72.875	74.625
+99	1050	73.880	2829600	72.630	72.630	74.380
+100	1051	71.750	1418500	72.750	71.500	73.000
+100	1052	72.130	2742400	72.000	70.250	72.880
+100	1053	73.625	3292000	72.375	72.250	73.875
+100	1054	74.380	1458600	73.630	73.500	74.380
+100	1055	74.625	2562800	74.875	74.500	75.250
+100	1056	74.380	1352100	74.380	74.130	74.880
+100	1057	74.250	1450700	74.250	73.875	74.375
+100	1058	74.250	1496400	74.125	74.125	74.875
+101	1059	87.130	2576400	87.880	86.000	88.250
+101	1060	89.000	5977700	90.500	88.630	90.500
+101	1061	91.625	5886400	89.375	89.125	92.000
+101	1062	93.500	4318900	91.500	91.000	93.880
+101	1063	93.625	3346300	93.125	92.875	93.875
+101	1064	95.250	3694500	93.125	92.875	95.625
+102	1065	89.375	3394000	90.125	88.375	90.750
+102	1066	89.130	3308400	89.630	88.630	90.250
+102	1067	90.250	2995700	90.500	89.750	90.750
+102	1068	91.750	2905200	91.380	90.880	92.250
+102	1069	93.000	2562500	91.875	91.875	93.375
+102	1070	93.000	2192900	93.630	93.000	94.000
+103	1071	109.000	3285600	106.500	105.625	109.500
+103	1072	108.625	1257200	109.125	108.500	109.750
+103	1073	108.875	1430800	109.125	108.625	109.375
+103	1074	109.630	1795300	108.880	108.880	110.000
+103	1075	109.875	1966800	110.000	109.625	110.375
+103	1076	109.125	1971400	109.875	108.875	110.375
+103	1077	109.250	2327700	109.500	108.380	109.630
+103	1078	110.750	1748300	109.250	109.250	110.875
+103	1079	112.000	2701000	111.000	110.250	112.125
+103	1080	112.375	2946800	112.125	110.750	112.750
+103	1081	113.625	3029700	112.375	112.250	114.625
+103	1082	111.375	3698100	113.875	111.125	114.000
+103	1083	106.750	4700700	111.380	106.500	111.380
+103	1084	107.630	5514300	107.000	105.630	108.250
+103	1085	106.625	3239000	108.125	106.500	108.500
+104	1086	91.880	3744400	89.130	89.130	91.880
+104	1087	89.375	3605800	92.000	89.125	92.000
+104	1088	90.875	2674000	89.875	89.750	91.125
+104	1089	91.250	1877400	90.880	90.880	91.880
+104	1090	91.750	945400	92.000	91.625	92.125
+104	1091	92.000	1572000	91.750	90.750	92.000
+105	1092	87.250	4624600	88.130	86.000	88.500
+105	1093	86.375	2664400	87.250	86.125	87.250
+105	1094	83.125	3742800	86.500	83.125	86.500
+105	1095	87.000	4613000	84.125	83.500	87.750
+105	1096	87.625	4821100	86.750	85.750	89.250
+105	1097	96.250	9856900	90.000	89.625	96.250
+105	1098	102.000	13145900	96.625	96.500	104.125
+105	1099	102.250	5293000	101.500	101.375	103.875
+105	1100	103.000	4959100	100.750	100.750	104.500
+105	1101	107.000	7989000	103.130	103.130	109.000
+105	1102	104.125	4721800	107.625	104.125	108.000
+106	1103	113.625	3467900	114.000	113.500	114.875
+106	1104	114.250	3237400	113.880	113.750	115.000
+106	1105	117.625	5835300	114.375	114.250	118.500
+106	1106	118.000	4985900	118.000	117.500	118.880
+106	1107	119.125	5322200	116.750	116.750	120.875
+106	1108	120.250	4097300	119.000	118.630	120.630
+106	1109	124.125	5355800	121.750	121.250	125.625
+106	1110	125.630	4126200	125.000	124.000	126.130
+106	1111	124.880	2882500	123.880	123.880	125.500
+107	1112	108.750	4722900	114.875	108.375	115.125
+107	1113	110.750	4558900	108.375	107.625	112.000
+107	1114	111.250	3619800	111.130	110.250	113.750
+107	1115	109.750	3046600	111.875	109.500	112.375
+107	1116	111.250	2931600	110.380	110.380	113.750
+107	1117	110.380	2379500	112.130	110.000	112.750
+107	1118	117.625	5407700	111.000	110.500	118.125
+107	1119	119.750	4149900	117.500	116.130	120.500
+108	1120	91.750	3683600	89.630	89.130	92.630
+108	1121	103.630	9014900	96.000	95.630	103.750
+108	1122	103.875	3990400	103.125	101.625	104.125
+108	1123	104.750	3338200	103.500	103.380	105.500
+108	1124	107.380	3992800	105.250	103.750	108.000
+108	1125	107.500	3505300	107.125	107.000	108.875
+108	1126	107.250	3120600	108.000	107.250	109.000
+108	1127	108.875	2265800	108.375	107.750	109.375
+108	1128	109.250	2151100	108.000	108.000	109.375
+109	1129	124.750	1312200	124.750	124.000	125.500
+109	1130	124.500	1864400	124.875	124.125	127.125
+109	1131	123.750	2446500	124.000	123.130	125.250
+109	1132	125.880	2013200	124.250	124.000	125.880
+109	1133	125.000	1845100	125.750	124.625	126.250
+109	1134	126.625	2302300	125.875	125.625	127.125
+109	1135	127.875	1835400	126.875	126.875	128.000
+109	1136	128.380	3148000	128.000	127.630	129.500
+109	1137	126.250	2402400	129.000	126.130	129.380
+109	1138	127.750	2248500	125.500	125.500	128.000
+109	1139	129.875	2858300	128.500	128.250	130.125
+109	1140	130.000	1400900	129.880	129.130	130.000
+109	1141	129.500	2863900	130.750	128.630	131.250
+109	1142	127.625	1875700	129.500	127.375	129.500
+109	1143	125.625	2135400	128.750	125.250	129.125
+109	1144	129.375	3473700	125.500	124.000	129.500
+110	1145	133.375	2886400	130.625	130.250	133.875
+110	1146	133.750	3481600	133.125	132.750	135.125
+110	1147	134.375	1569400	133.375	132.875	134.500
+110	1148	134.500	1429200	134.375	134.000	134.875
+110	1149	133.250	2724100	135.000	133.000	135.750
+110	1150	134.750	2392300	133.500	133.250	135.875
+110	1151	136.880	2774500	134.630	134.630	137.630
+110	1152	145.000	7803800	137.630	137.380	145.500
+110	1153	146.750	5777100	144.750	143.000	150.000
+111	1154	157.625	2833000	158.125	156.125	158.500
+111	1155	158.000	5515400	157.500	157.000	160.750
+111	1156	158.125	2799700	158.250	157.750	160.250
+111	1157	159.375	931300	158.125	158.125	159.625
+111	1158	163.000	3316000	159.630	159.630	163.500
+111	1159	162.625	4677800	163.625	162.625	166.000
+111	1160	162.000	4437400	162.875	159.125	164.000
+111	1161	158.500	3036300	161.375	158.375	162.625
+111	1162	155.625	6051900	151.000	151.000	158.000
+111	1163	160.000	2769900	156.630	156.250	160.130
+112	1164	141.250	3583000	143.130	140.250	143.500
+112	1165	137.625	6308500	140.750	137.125	140.875
+112	1166	143.875	4282700	137.625	0.000	144.000
+112	1167	146.500	4198400	144.380	144.130	148.000
+112	1168	146.875	3670400	147.000	144.000	147.500
+112	1169	143.000	1772200	146.880	143.000	146.880
+113	1170	136.500	2634400	134.500	133.250	136.880
+113	1171	137.880	3931900	138.630	134.380	139.000
+113	1172	137.500	1845300	137.380	135.750	138.380
+113	1173	137.750	2655100	137.375	136.750	139.750
+113	1174	139.750	2343200	138.000	137.750	140.130
+113	1175	137.380	2356700	139.630	136.630	141.250
+113	1176	140.000	3022200	137.250	134.750	140.130
+113	1177	142.380	3917100	140.000	139.000	143.750
+113	1178	153.625	10659100	150.500	149.500	157.000
+113	1179	150.750	3005000	152.250	150.625	152.875
+114	1180	98.625	2949600	102.437	98.625	104.125
+114	1181	99.130	2060000	100.130	99.000	100.810
+114	1182	101.690	1069100	99.380	99.250	101.750
+114	1183	102.750	2307300	102.875	102.750	103.687
+114	1184	103.130	3558000	103.690	102.940	105.500
+114	1185	104.625	2736500	104.000	103.187	105.187
+114	1186	105.625	2635000	104.500	104.062	105.750
+114	1187	106.437	5017000	105.562	105.000	106.812
+114	1188	105.250	3555600	105.375	105.062	107.187
+114	1189	104.250	4308200	105.000	102.625	105.000
+114	1190	104.190	4059400	103.500	102.940	105.500
+114	1191	100.062	7182800	104.312	99.375	104.875
+114	1192	100.130	6410700	98.250	97.500	101.130
+114	1193	102.130	3414500	100.560	100.310	102.440
+114	1194	102.625	4275400	103.500	101.250	104.000
+114	1195	103.437	6321700	103.187	102.375	104.937
+114	1196	105.000	4189100	104.875	104.500	105.187
+114	1197	108.380	4970600	105.190	104.690	108.380
+114	1198	100.125	13907800	100.250	99.625	102.000
+114	1199	99.380	6583500	99.810	98.500	100.630
+114	1200	99.187	3911500	99.812	98.937	100.000
+114	1201	98.125	2807900	99.250	98.000	99.937
+114	1202	96.500	7019700	96.750	95.630	97.880
+114	1203	97.000	5192400	97.130	96.500	98.000
+114	1204	98.187	4413600	97.000	97.000	99.312
+114	1205	98.750	2900100	98.312	98.000	99.562
+114	1206	100.562	3437700	100.000	100.000	101.250
+114	1207	99.380	3585600	100.130	98.690	100.250
+115	1208	98.125	5205100	99.125	98.125	99.812
+115	1209	96.125	6464200	97.125	95.875	98.250
+115	1210	97.500	4167100	97.380	96.690	98.190
+115	1211	99.130	3403400	97.880	97.440	99.880
+115	1212	100.250	2951700	99.187	98.187	100.625
+115	1213	99.630	2925300	100.880	99.000	101.130
+115	1214	101.250	3420700	99.690	99.250	101.380
+115	1215	100.880	3585100	101.310	99.560	101.810
+115	1216	101.560	3594700	100.630	100.560	102.310
+115	1217	102.875	2585000	101.687	101.437	103.000
+115	1218	102.062	4107800	103.000	101.437	103.250
+116	1219	108.812	4240700	109.000	107.625	109.125
+116	1220	106.130	4884000	108.750	106.000	109.250
+116	1221	108.130	4276900	106.250	106.190	109.500
+116	1222	111.750	4039200	110.000	109.940	112.310
+116	1223	112.000	3030000	111.880	110.060	112.130
+116	1224	112.440	3187800	112.500	112.000	114.690
+116	1225	113.000	1636400	112.380	112.310	113.440
+116	1226	114.125	2184600	114.125	113.562	114.812
+116	1227	114.810	4356000	114.130	113.500	116.310
+116	1228	116.750	3166400	116.000	115.500	116.937
+116	1229	115.190	3219800	116.560	114.500	116.630
+117	1230	115.000	2258200	113.750	113.630	115.560
+117	1231	117.062	3189500	114.750	114.625	118.500
+117	1232	118.500	3070100	118.250	117.375	119.250
+117	1233	119.380	2339800	118.500	118.250	120.000
+117	1234	119.625	2268600	119.750	119.000	120.625
+117	1235	117.000	2557800	119.250	117.000	120.000
+117	1236	118.380	2180100	117.130	116.000	118.940
+117	1237	120.187	3168400	118.562	118.500	120.375
+117	1238	122.000	4489200	121.000	120.312	123.000
+117	1239	128.130	12308600	128.250	127.750	131.000
+117	1240	127.440	6049900	126.000	124.500	128.440
+117	1241	123.880	4153100	127.190	123.690	129.000
+117	1242	124.250	2874600	125.875	122.500	125.937
+118	1243	123.500	4994700	125.750	123.375	127.437
+118	1244	122.500	5579800	122.130	118.190	122.500
+118	1245	126.562	4965100	121.375	120.625	126.562
+118	1246	129.130	4557100	128.000	127.630	129.940
+118	1247	130.000	3246800	129.000	128.500	130.687
+118	1248	130.500	3319400	130.000	128.190	130.940
+119	1249	133.625	3820400	134.500	132.187	136.187
+119	1250	131.437	3544900	133.750	130.000	134.125
+119	1251	128.500	4149700	130.750	127.630	131.500
+119	1252	125.375	6268700	125.062	123.375	126.437
+119	1253	124.810	7302600	124.130	118.940	125.250
+119	1254	120.250	6721000	123.750	117.310	123.750
+119	1255	119.250	7183700	124.000	118.750	124.000
+119	1256	120.750	6582400	119.500	118.125	122.875
+119	1257	123.500	9156300	120.750	116.812	123.500
+119	1258	127.312	5841600	124.437	122.500	127.937
+119	1259	130.875	5402500	130.125	129.562	132.875
+119	1260	128.190	4696800	130.500	126.560	130.500
+120	1261	147.380	3456500	148.500	147.190	149.940
+120	1262	147.880	4096300	148.880	145.750	149.750
+120	1263	149.000	3293000	147.690	146.810	149.560
+120	1264	149.940	3569000	148.880	147.500	150.940
+120	1265	151.380	3788700	150.750	149.940	152.190
+120	1266	156.000	4371500	150.880	150.690	156.750
+120	1267	157.125	5109100	157.000	156.500	158.875
+120	1268	157.880	4333900	156.690	156.630	159.880
+120	1269	157.437	2997600	157.000	155.750	157.500
+121	1270	165.000	3885800	163.500	162.500	165.810
+121	1271	164.375	2826400	166.875	164.312	166.875
+121	1272	166.062	4381600	165.437	165.062	169.625
+121	1273	171.560	4908400	166.630	166.630	172.190
+121	1274	176.375	3739300	171.562	171.562	178.937
+121	1275	182.250	4352300	177.500	175.250	183.000
+121	1276	185.000	3535000	182.690	181.130	185.380
+121	1277	187.937	1524900	184.750	184.062	187.937
+121	1278	189.250	2634600	186.500	186.000	189.937
+121	1279	187.125	1881100	188.625	187.000	188.937
+121	1280	186.750	2406600	186.875	186.312	188.625
+121	1281	184.375	1932400	186.750	183.500	187.187
+121	1282	183.000	4074800	185.000	181.500	186.500
+121	1283	189.630	4953800	183.000	182.810	189.880
+122	1284	177.937	4600100	172.250	171.062	177.937
+122	1285	176.940	4554600	178.000	175.750	180.000
+122	1286	173.750	4318700	177.250	173.130	179.690
+122	1287	173.625	5234800	172.000	169.312	173.937
+122	1288	169.750	7399000	171.000	166.500	171.880
+122	1289	168.375	4795400	169.500	165.125	169.500
+122	1290	167.750	4371200	170.500	166.880	170.940
+122	1291	166.750	3871500	168.500	165.062	168.937
+122	1292	171.000	10750500	173.500	170.125	177.000
+122	1293	178.380	5803200	173.880	173.750	178.940
+122	1294	178.875	3779900	178.625	177.062	180.000
+122	1295	182.190	5009500	179.880	178.560	184.880
+122	1296	181.500	3504900	181.630	180.250	182.880
+123	1297	182.000	3951400	179.187	177.125	182.312
+123	1298	181.000	3303000	182.000	180.190	183.500
+123	1299	178.060	3452700	179.500	178.000	180.000
+123	1300	177.630	7252500	177.500	172.940	177.750
+123	1301	168.562	9748400	176.625	168.000	178.000
+123	1302	167.000	5948300	168.687	166.625	170.500
+123	1303	165.380	5007500	167.000	164.000	167.630
+123	1304	169.500	5910500	168.000	166.500	170.500
+123	1305	171.312	4914400	172.000	169.500	173.250
+123	1306	172.380	4133200	171.060	170.560	175.880
+123	1307	178.562	3733400	177.000	176.875	181.250
+123	1308	177.250	2917600	180.000	176.500	181.500
+124	1309	187.000	4265500	186.000	182.312	188.062
+124	1310	186.310	3055900	185.630	184.000	188.060
+124	1311	183.440	4489900	183.500	181.060	183.630
+124	1312	180.000	3423200	184.000	179.940	184.000
+124	1313	179.380	3630500	182.750	177.630	183.880
+124	1314	177.750	4165200	179.500	173.500	179.500
+124	1315	170.375	5964400	177.500	170.125	177.500
+124	1316	166.750	7691800	170.880	164.060	172.310
+124	1317	169.750	7358000	167.000	163.000	169.750
+124	1318	171.875	6580800	169.750	165.125	171.875
+124	1319	194.500	19584900	197.250	192.687	198.750
+124	1320	199.750	10375500	193.380	192.940	206.560
+124	1321	209.880	9333000	204.750	202.310	210.750
+124	1322	212.000	10464600	212.000	208.500	215.250
+124	1323	205.000	5670900	209.250	203.500	210.500
+125	1324	209.250	4169800	211.880	208.000	214.000
+125	1325	217.250	4993400	211.250	211.062	217.500
+125	1326	218.630	4774200	217.250	217.060	221.880
+125	1327	221.000	4186400	220.500	217.500	221.875
+125	1328	225.500	6033400	221.125	215.500	228.437
+125	1329	246.000	12165700	234.000	234.000	246.000
+125	1330	239.250	9036900	241.500	236.000	243.500
+125	1331	237.500	5780200	236.000	232.000	239.625
+125	1332	238.500	4316900	238.250	237.000	240.625
+125	1333	235.875	3895800	238.250	233.062	238.750
+125	1334	232.875	3220900	235.625	232.500	236.375
+125	1335	230.380	3452300	232.750	229.190	233.380
+125	1336	223.750	4299100	230.310	221.750	230.690
+125	1337	221.187	4702500	222.500	221.000	226.000
+125	1338	236.250	8314000	223.000	221.440	236.630
+125	1339	116.000	10552600	116.687	112.625	116.875
+125	1340	116.000	6379500	116.000	114.187	116.750
+126	1341	124.440	6043500	122.750	122.310	124.880
+126	1342	122.000	8442100	123.375	121.000	123.625
+126	1343	122.380	6463000	122.000	120.880	124.060
+126	1344	122.940	6245300	122.630	122.060	125.880
+126	1345	124.000	4354600	125.000	122.750	125.190
+126	1346	123.187	4773000	124.250	122.687	125.625
+127	1347	98.000	18720400	94.000	93.562	98.250
+127	1348	104.750	19673300	99.000	98.380	105.000
+127	1349	107.880	13681500	105.500	104.440	108.440
+127	1350	106.125	10665000	108.812	106.000	109.875
+127	1351	104.060	9710300	105.000	101.810	105.000
+127	1352	105.000	3108400	105.937	104.125	106.000
+127	1353	104.187	5677700	104.937	103.375	104.937
+127	1354	103.060	5719900	103.690	102.130	104.500
+127	1355	103.750	5336000	102.562	102.250	104.437
+127	1356	105.560	6208600	103.440	103.380	106.310
+127	1357	112.000	14679900	109.812	107.937	112.875
+127	1358	116.000	9924400	113.000	112.500	116.500
+128	1359	109.190	7117300	108.000	105.750	109.690
+128	1360	109.125	7680700	110.687	108.625	111.062
+128	1361	108.060	4834900	109.060	107.750	110.440
+128	1362	110.125	4773500	108.500	108.062	110.125
+128	1363	108.375	4005500	109.875	108.250	110.312
+128	1364	108.625	4528700	109.125	108.187	110.437
+128	1365	109.750	3740700	109.687	108.125	110.000
+128	1366	109.250	4081300	109.560	109.060	110.750
+128	1367	109.060	2683100	110.440	108.750	110.500
+128	1368	108.750	3435100	109.690	108.560	110.500
+128	1369	107.875	2870300	109.187	106.625	109.500
+128	1370	115.625	10346800	112.437	111.875	115.812
+128	1371	112.060	8227800	114.000	110.880	114.500
+129	1372	107.000	5665900	107.500	106.130	108.250
+129	1373	109.000	6622500	109.000	107.880	109.810
+129	1374	110.000	8856400	108.250	107.687	111.687
+129	1375	112.750	6563500	110.000	109.940	113.380
+129	1376	113.500	6771400	112.810	111.940	114.690
+129	1377	114.250	6137800	114.500	113.875	115.375
+129	1378	115.250	6492400	115.875	111.625	115.875
+129	1379	121.500	12124300	115.375	115.062	122.250
+129	1380	126.880	11862900	125.000	124.630	128.250
+129	1381	122.500	8163000	125.750	122.060	127.000
+130	1382	102.940	6402800	104.130	102.630	104.810
+130	1383	103.500	7428100	102.380	101.000	104.380
+130	1384	117.000	22927900	112.000	111.750	117.812
+130	1385	114.440	8764700	117.000	113.750	117.000
+131	1386	90.130	7705300	90.190	89.810	94.440
+131	1387	86.000	12579500	85.880	84.810	88.000
+131	1388	81.560	12724900	85.500	80.060	87.940
+131	1389	89.000	9514000	84.500	84.500	89.375
+131	1390	84.810	6052300	89.000	84.250	89.560
+132	1391	92.750	5671800	93.750	91.810	94.000
+132	1392	96.687	9712900	95.375	94.312	97.750
+132	1393	108.312	25243300	104.375	103.500	110.000
+132	1394	111.250	14760400	107.500	107.250	113.937
+133	1395	106.470	6793100	107.170	105.370	107.340
+133	1396	99.290	16688100	105.000	97.905	105.010
+133	1397	95.490	14494800	97.900	95.020	98.400
+133	1398	98.390	12127900	95.100	94.200	98.440
+133	1399	94.960	14246600	95.400	93.340	98.900
+134	1400	99.700	9957300	97.000	97.000	99.880
+134	1401	106.500	19849500	103.000	102.300	110.000
+134	1402	114.470	25822400	112.000	110.450	115.900
+134	1403	114.830	12759100	114.350	113.750	116.400
+135	1404	119.600	7726900	117.500	117.500	119.600
+135	1405	117.800	5629100	119.520	117.760	119.900
+135	1406	115.270	5818000	117.350	115.080	117.590
+135	1407	112.650	9598700	114.000	112.000	114.100
+135	1408	111.800	6757600	112.650	111.640	113.860
+135	1409	112.890	5138900	112.500	111.900	113.600
+135	1410	113.640	3812200	113.250	112.850	114.750
+135	1411	116.970	6154400	113.640	113.560	117.600
+135	1412	117.500	9625700	117.600	116.500	119.000
+135	1413	117.250	6423700	117.000	117.000	118.250
+135	1414	116.100	3099100	117.500	115.600	117.500
+135	1415	117.360	6542700	116.300	116.100	118.140
+136	1416	104.720	9312600	106.500	103.650	106.950
+136	1417	101.960	10266800	104.730	101.600	105.400
+136	1418	103.850	8894800	101.600	101.560	104.130
+136	1419	107.250	8767200	105.900	105.620	107.800
+136	1420	108.530	7841800	106.150	106.110	109.300
+136	1421	107.820	5330100	108.530	107.280	109.380
+137	1422	108.800	5675100	108.500	107.210	109.470
+137	1423	108.180	3704100	107.800	107.100	110.090
+137	1424	106.510	4176800	107.250	105.790	107.370
+137	1425	106.250	4028300	105.800	105.260	107.370
+137	1426	104.190	6398000	105.000	104.100	106.100
+137	1427	104.080	6763200	103.700	102.700	104.540
+137	1428	104.950	5254800	103.850	102.810	104.950
+137	1429	105.860	6024400	105.000	104.650	106.640
+137	1430	106.200	5730200	106.500	105.400	106.850
+137	1431	105.010	4713100	106.350	105.010	106.590
+138	1432	91.300	13783100	94.450	90.300	94.450
+138	1433	90.000	13172200	91.300	87.490	91.500
+138	1434	91.720	11077200	90.200	89.900	92.710
+138	1435	92.710	8676200	91.720	91.340	93.480
+138	1436	93.770	7221200	92.300	92.100	93.900
+138	1437	96.950	11118800	92.900	92.400	97.620
+138	1438	97.310	9785100	97.150	96.800	98.880
+138	1439	98.020	9733000	96.650	95.370	98.450
+138	1440	98.500	7093400	98.030	96.750	99.000
+138	1441	97.140	7525300	98.500	96.760	98.500
+139	1442	123.200	7950400	121.120	120.060	123.210
+139	1443	120.250	8061000	121.550	120.120	122.300
+139	1444	121.100	7036000	120.800	119.410	121.480
+139	1445	121.340	6225500	120.150	120.150	122.140
+139	1446	122.200	5596200	121.510	121.350	122.970
+139	1447	123.890	8054200	121.900	121.010	124.700
+140	1448	75.490	7953000	77.850	75.200	78.250
+140	1449	74.650	13296100	75.400	73.250	75.950
+140	1450	75.600	8909700	75.450	75.300	77.400
+140	1451	76.170	8592000	74.200	73.250	76.770
+140	1452	77.140	7775800	76.180	75.160	77.750
+140	1453	75.940	7240900	75.600	75.470	76.900
+141	1454	72.000	10945600	71.350	71.250	73.620
+141	1455	67.600	12056000	72.010	67.160	72.410
+141	1456	68.580	12012900	67.850	67.700	69.400
+141	1457	70.510	8469900	67.950	67.870	70.710
+141	1458	73.500	5243000	72.450	72.000	73.900
+141	1459	71.300	9488100	73.000	71.030	73.480
+141	1460	69.670	11165100	71.400	69.450	72.250
+141	1461	68.760	10073400	70.600	68.530	71.250
+141	1462	69.410	11034600	68.000	67.550	69.750
+142	1463	69.350	10989800	68.900	67.300	70.000
+142	1464	66.400	11576400	68.750	65.760	69.470
+142	1465	71.180	11918600	70.370	68.000	71.400
+142	1466	71.790	10136400	70.500	70.020	72.700
+142	1467	70.400	12708100	70.750	69.110	71.600
+142	1468	68.250	8832000	70.400	67.220	70.700
+142	1469	67.880	6915000	68.210	67.123	68.230
+142	1470	65.990	7126900	67.940	65.850	68.350
+142	1471	67.900	8370800	67.000	66.610	69.420
+142	1472	69.170	8036800	69.000	66.800	69.900
+142	1473	71.610	8432500	69.200	68.350	72.050
+142	1474	71.830	6940900	70.610	70.400	74.300
+142	1475	71.770	5263300	71.050	70.610	72.640
+143	1476	55.070	12155800	56.050	54.810	56.700
+143	1477	57.580	12672600	54.650	54.010	58.480
+143	1478	63.920	17852500	62.000	61.500	63.920
+143	1479	63.420	7925300	61.540	61.540	63.800
+143	1480	68.480	14600200	67.750	66.580	68.480
+143	1481	64.900	15828900	66.600	64.240	67.005
+143	1482	72.200	21344500	72.800	71.230	73.000
+143	1483	74.250	12532700	71.730	70.260	74.250
+144	1484	72.100	10570000	75.500	71.750	75.550
+144	1485	74.560	7538800	72.500	72.160	74.620
+144	1486	76.560	12544800	75.150	74.560	77.500
+144	1487	76.740	11648500	76.560	74.200	77.050
+144	1488	78.670	12865800	77.000	76.020	79.400
+144	1489	78.940	9844300	78.670	78.500	79.790
+144	1490	80.400	9395200	78.900	78.320	80.500
+144	1491	82.500	12005100	82.000	81.700	83.810
+144	1492	81.680	10466700	81.750	80.470	82.010
+145	1493	80.260	5922700	79.750	79.440	81.507
+145	1494	79.760	2420200	80.200	79.760	81.000
+145	1495	78.500	5784300	79.810	78.260	80.700
+145	1496	77.360	6334400	78.500	76.610	79.180
+145	1497	76.250	8066600	77.000	75.600	77.430
+145	1498	77.500	7871400	77.100	77.100	78.460
+145	1499	80.570	7864500	78.800	78.190	80.570
+145	1500	81.650	5963400	80.700	80.210	81.650
+145	1501	83.590	7923300	81.900	81.810	84.590
+145	1502	86.000	11907000	83.950	83.750	86.180
+145	1503	84.190	9509700	85.550	84.070	85.690
+146	1504	76.500	5617700	77.500	76.500	78.090
+146	1505	75.860	11218600	76.100	74.310	76.350
+146	1506	77.450	8300100	76.400	75.350	77.450
+146	1507	79.330	7793000	78.020	77.910	79.510
+146	1508	79.510	5441300	79.080	78.826	79.700
+146	1509	79.040	6295600	79.570	78.710	80.050
+147	1510	79.850	7024700	81.130	79.800	81.330
+147	1511	79.750	7472200	79.700	78.730	80.680
+147	1512	80.690	5298500	79.690	79.380	80.820
+147	1513	80.880	4615600	81.050	80.350	81.270
+147	1514	81.020	4262200	80.870	80.280	81.500
+147	1515	81.510	4634200	81.450	80.650	81.540
+148	1516	89.700	8842500	91.450	89.010	91.510
+148	1517	90.310	5529700	89.900	89.750	90.460
+148	1518	94.020	19813600	95.070	93.550	95.650
+148	1519	95.320	9302100	95.000	94.710	95.350
+148	1520	97.100	9285300	96.000	95.730	97.440
+148	1521	97.700	6952700	97.230	96.640	98.040
+148	1522	97.510	4371600	97.840	97.320	98.160
+149	1523	99.300	3611700	100.060	99.300	100.300
+149	1524	99.710	3562400	99.100	99.080	100.090
+149	1525	99.370	3930500	99.990	99.320	100.000
+149	1526	98.420	4830500	99.310	98.150	99.770
+149	1527	97.800	5447700	98.420	97.520	99.230
+149	1528	97.310	5690200	98.600	97.190	98.600
+149	1529	95.960	6629600	97.400	95.460	97.510
+149	1530	96.790	7012100	95.200	95.200	97.460
+149	1531	96.540	3362500	96.500	96.230	97.090
+150	1532	96.840	4807000	96.570	95.600	96.890
+150	1533	96.390	3548500	96.580	96.130	96.920
+150	1534	96.450	3971800	95.950	95.560	96.980
+150	1535	94.590	5084200	96.490	94.590	96.880
+150	1536	94.530	6391400	94.300	93.770	95.280
+150	1537	93.060	6536400	94.380	92.680	94.740
+150	1538	91.210	8560800	92.000	91.150	92.980
+150	1539	93.300	6290600	92.000	91.680	93.380
+151	1540	85.350	5677300	85.300	85.050	85.940
+151	1541	83.650	7530100	85.000	83.580	85.010
+151	1542	83.890	6595200	84.400	83.510	84.500
+151	1543	84.950	6009200	84.000	83.420	85.250
+151	1544	85.250	6001500	85.900	85.200	86.090
+151	1545	84.130	6298700	84.840	83.780	85.240
+152	1546	83.690	5268500	83.700	83.100	83.980
+152	1547	82.210	7134900	83.050	81.900	83.050
+152	1548	83.910	5916900	82.540	82.510	83.940
+152	1549	84.020	4361500	83.700	83.510	84.560
+152	1550	84.040	3559500	84.100	83.660	84.540
+152	1551	85.130	4833700	83.600	83.570	85.130
+153	1552	84.160	4650300	84.100	83.980	84.440
+153	1553	84.480	3874200	84.350	83.880	84.650
+153	1554	84.980	4204600	84.480	84.150	84.980
+153	1555	85.740	5198000	85.140	85.010	85.980
+153	1556	86.720	4542700	85.950	85.880	86.980
+153	1557	87.160	5001400	87.000	86.720	88.100
+153	1558	87.320	5150800	87.950	87.130	88.030
+153	1559	88.040	3984400	87.140	87.100	88.100
+153	1560	87.420	3076900	88.040	87.400	88.100
+153	1561	86.710	4090000	87.430	86.510	87.910
+153	1562	86.630	3016300	86.770	86.270	87.200
+153	1563	86.000	4626600	86.020	85.580	86.200
+153	1564	84.980	6665200	86.260	84.430	86.480
+153	1565	84.780	4233700	84.750	84.300	84.980
+153	1566	84.850	5928500	84.780	84.600	85.250
+153	1567	85.920	7275600	84.300	84.290	86.150
+153	1568	89.370	13824500	88.200	88.000	89.730
+153	1569	88.820	7079800	88.450	88.290	89.190
+153	1570	88.100	6272100	88.400	87.660	88.760
+153	1571	87.390	5998900	88.220	87.290	88.450
+153	1572	88.430	5775000	87.360	87.310	88.900
+153	1573	89.000	7337300	88.330	88.250	89.570
+153	1574	90.000	6035100	88.580	88.500	90.270
+153	1575	89.500	4226500	89.800	89.430	90.240
+153	1576	89.750	4518500	89.400	88.950	89.900
+153	1577	90.110	5160900	89.330	89.230	90.600
+153	1578	90.470	5391100	89.550	89.500	91.220
+153	1579	91.200	6553300	91.250	90.970	91.900
+153	1580	92.380	6952100	91.050	90.820	92.700
+153	1581	93.280	6708500	92.400	92.400	93.520
+153	1582	93.370	4907300	92.500	92.500	93.700
+153	1583	93.370	4513100	93.000	93.000	93.950
+154	1584	94.130	3541200	94.280	94.130	94.640
+154	1585	92.700	5664200	94.140	92.540	94.830
+154	1586	92.760	4838700	92.950	92.300	93.100
+154	1587	93.300	4233000	92.700	92.500	93.970
+154	1588	93.570	2868800	93.160	93.160	94.020
+154	1589	94.330	4299200	93.500	93.480	94.670
+155	1590	93.300	3821900	92.640	92.590	93.430
+155	1591	92.920	4541200	92.750	92.750	93.730
+155	1592	92.410	4037900	93.150	92.200	93.210
+155	1593	92.370	4754000	92.940	92.360	93.180
+155	1594	91.600	8051000	92.350	91.590	92.510
+155	1595	92.130	5087800	91.700	91.700	92.560
+155	1596	92.350	4513900	92.020	92.010	93.000
+155	1597	92.410	3424800	92.350	92.090	92.800
+155	1598	91.510	4494300	92.250	91.200	92.410
+156	1599	91.380	4419100	90.460	90.220	91.410
+156	1600	90.440	5740800	91.490	90.040	91.760
+156	1601	90.320	3737900	90.080	89.773	90.620
+156	1602	89.570	4579300	90.230	89.260	90.330
+156	1603	89.000	7836800	89.050	88.706	89.380
+156	1604	88.440	6376500	89.000	88.100	89.200
+156	1605	87.600	5273400	88.280	87.500	88.460
+156	1606	86.200	8296500	87.350	86.090	87.560
+156	1607	85.750	8450000	85.900	85.170	86.240
+156	1608	84.570	7090800	85.760	84.240	85.972
+156	1609	83.640	10708300	84.630	83.470	85.410
+156	1610	76.700	27932400	79.490	76.330	79.660
+156	1611	76.650	13256100	77.150	76.140	77.750
+156	1612	75.480	9292700	76.980	75.250	77.200
+156	1613	72.010	20389800	75.480	71.850	75.870
+156	1614	74.030	16273600	72.990	72.800	74.100
+156	1615	74.210	10985200	74.050	73.260	74.700
+156	1616	74.610	10223400	75.240	74.050	75.720
+156	1617	75.430	12500200	74.680	74.650	76.980
+156	1618	77.050	11706800	75.690	75.500	77.180
+156	1619	75.910	8638300	77.050	75.650	77.110
+157	1620	83.140	5340900	82.930	82.500	83.780
+157	1621	84.000	4490200	83.140	83.000	84.080
+157	1622	84.190	4712900	83.710	83.560	84.630
+157	1623	84.190	5210600	84.150	83.790	84.690
+157	1624	84.700	4661700	84.200	84.100	84.900
+157	1625	86.080	7788600	84.450	84.440	86.210
+157	1626	86.710	8633600	86.080	85.750	87.600
+157	1627	86.950	13328300	86.330	86.220	87.940
+157	1628	89.820	27876200	90.510	89.730	92.040
+157	1629	89.860	10676400	89.800	89.310	90.980
+157	1630	90.480	7391600	90.040	89.550	90.700
+157	1631	91.560	8862300	90.050	90.010	92.000
+157	1632	91.490	9222500	90.910	90.800	91.950
-- 
2.43.0

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Zsolt,

I just confirmed the crash.

Henson, What do you think? 

Good catch by Zsolt. Your careful review is really helping a lot.

I've fixed both the prefix merge and suffix merge paths in
mergeGroupPrefixSuffix() to also increment child->max. I'll
include the fix with a regression test in the next patch series.

Regarding the suggested fix:

    if (child->max != RPR_QUANTITY_INF)
        child->max += 1;

While the quantifier value is int (INT32_MAX = RPR_QUANTITY_INF),
making such repetition counts practically impossible, the +1
approach is not semantically equivalent -- it could silently turn
a finite max into infinity. Instead, I took a fallback approach:
skip the merge entirely when min or max would reach
RPR_QUANTITY_INF after increment, consistent with the overflow
checks in mergeConsecutiveVars/Groups. 
 
Good point. You are right, the plan cache should be read only.
However, Henson is working on a different approach and the code will
not be used any more...

Yes, I'm currently working on a slot-based approach (1-slot
PREV/NEXT) that won't need attno_map, so the plan cache mutation
issue will be gone.
 
I forggot to include the data file. Please apply attached patch on top
of v45.
 
Got it, thanks. By the way, how about splitting the test patch
into two -- one for sql + data files and another for expected
output files? The single test patch is getting quite large and
cfbot often fails to apply it.

Right. Maybe ERRCODE_TOO_MANY_ARGUMENTS?

 I'm currently reworking PREV/NEXT to accept 2 arguments, so this
error handling will change. I'll take care of the proper error
codes along with the GROUPS typo and ERRCODE_WINDOWING_ERROR change.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> I forggot to include the data file. Please apply attached patch on top
>> of v45.
>>
> 
> Got it, thanks. By the way, how about splitting the test patch
> into two -- one for sql + data files and another for expected
> output files? The single test patch is getting quite large and
> cfbot often fails to apply it.

Sounds like a good idea.

> Right. Maybe ERRCODE_TOO_MANY_ARGUMENTS?
>>
> 
>  I'm currently reworking PREV/NEXT to accept 2 arguments, so this
> error handling will change. I'll take care of the proper error
> codes along with the GROUPS typo and ERRCODE_WINDOWING_ERROR change.

Ok, thanks.
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> Got it, thanks. By the way, how about splitting the test patch
>> into two -- one for sql + data files and another for expected
>> output files? The single test patch is getting quite large and
>> cfbot often fails to apply it.
> 
> Sounds like a good idea.

I have made an estimate how large each patch part is.

SQL + data patches:
 src/test/regress/sql/rpr.sql              | 1164 ++++
 src/test/regress/sql/rpr_base.sql         | 3986 +++++++++++++
 src/test/regress/sql/rpr_explain.sql      | 2296 ++++++++
 src/test/regress/sql/rpr_nfa.sql          | 3278 +++++++++++
 src/test/regress/parallel_schedule        |    5 +
 src/test/regress/data/stock.data          | 1632
-----------------------------------------------------
 total					   12361

Expected patches:
 src/test/regress/expected/rpr.out         | 2356 ++++++++
 src/test/regress/expected/rpr_base.out    | 6202 +++++++++++++++++++++
 src/test/regress/expected/rpr_explain.out | 3968 +++++++++++++
 src/test/regress/expected/rpr_nfa.out     | 4340 ++++++++++++++
-----------------------------------------------------
 total					   16866

It seems we will have about 12k (sql and data) and 16k (expected)
patches. Looks nice balance.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

Hi Tatsuo,

Sorry for sending these before your next revision of v45 --
I'll be busy with a project proposal for the next couple of
weeks, so I wanted to share them before that.

Here are the patches on top of v45, incorporating the fixes and
improvements I mentioned earlier, plus additional changes from a
thorough code review. There are quite a few patches since I went
ahead without prior discussion -- please review each one individually
and feel free to drop any that you disagree with.

Here's a summary of each patch (to be applied on top of v45):

  0001: Fix mergeGroupPrefixSuffix() max increment
        When absorbing prefix/suffix, child->max was not incremented,
        causing incorrect quantifier bounds. (reported by Zsolt)

  0002: Fix RPR error codes and GROUPS typo
        Use ERRCODE_WINDOWING_ERROR instead of ERRCODE_SYNTAX_ERROR
        for semantic window-frame violations. Fix "GROUP" typo to
        "GROUPS" in frame validation error message. (reported by Zsolt)

  0003: Add check_stack_depth() and CHECK_FOR_INTERRUPTS()
        Add stack depth protection to recursive pattern optimization
        and interrupt checks to NFA engine loops.

  0004: Fix window_last_value set_mark during RPR
        Restore set_mark=true in window_last_value (normal behavior)
        and add an RPR-specific override inside WinGetFuncArgInFrame.
        This keeps the RPR workaround localized rather than changing
        the caller's semantics unconditionally.

  0005: Fix row_is_in_reduced_frame in WINDOW_SEEK_TAIL
        Pass frameheadpos directly to row_is_in_reduced_frame
        instead of frameheadpos+relpos. Currently only last_value()
        calls this path with relpos=0 so no actual bug, but the
        old expression would be incorrect for negative relpos.
        Also add a bounds check for future callers.

  0006: Clarify ST_NONE intent
        Add comment explaining ST_NONE = 0 is the default for
        non-RPR windows.

  0007: Clarify inverse transition optimization comment
        Document why RPR disables inverse transition: the reduced
        frame changes row by row.

  0008: Reject unused DEFINE variables
        I know you preferred silently ignoring unused DEFINE
        variables [1], and I agree the standard doesn't mandate
        an error. However, if we later add qualified column
        references (e.g. B AS A.price > 100), B's expression
        depends on A being present. If A is not used in PATTERN
        and the planner silently removes it, B's reference to A
        becomes dangling. I worry that silently allowing this now
        could create forward-compatibility problems once qualified
        references are introduced. For that reason, I'm inclined
        to think rejecting them now may be safer than changing
        behavior later, which would be a user-visible compatibility
        break. This is also consistent with Oracle's behavior
        (ORA-62503), as SungJun reported, and it helps catch user
        typos in DEFINE variable names at parse time.

  0009: Clarify RPR documentation in advanced.sgml
        Improve absorption explanation and clarify non-match row
        aggregation behavior with concrete examples.

  0010: Fix typos in RPR comments and parser README

  0011: Clarify excludeLocation and empty quantifier in gram.y
        Add comments explaining the conditional location assignment
        pattern and the empty quantifier rule.

  0012: Clarify RPR_VARID_MAX definition
        Document varId range 0-250 and reserved control element
        values 252+.

  0013: Move local variables to function scope
        In row_is_in_reduced_frame, move declarations out of
        switch case blocks.

  0014: Reset reduced_frame_map pointer in release_partition
        Set reduced_frame_map = NULL and alloc_sz = 0 to prevent
        dangling pointer after partition context reset.

  0015: Remove redundant list manipulation in nfa_add_matched_state
        Simplify doubly-linked list operation that was duplicated
        by the subsequent ExecRPRFreeContext() call.

  experimental: Implement 1-slot PREV/NEXT navigation
        The slot-based PREV/NEXT approach I mentioned earlier.
        This no longer needs attno_map, so the plan cache mutation
        issue is gone. PREV/NEXT now also accepts an optional
        second argument for offset, e.g. PREV(price, 2).

        Note: all existing regression tests pass with this patch,
        but my understanding of TupleSlot internals and JIT is still
        shallow -- the implementation largely copies surrounding
        patterns, so there may be issues I haven't caught yet. I'd
        like to keep this as a separate patch on top of v46 until it
        is trustworthy enough, rather than folding it into the main
        series. I'll continue reviewing and hardening it.

One design decision regarding PREV/NEXT: the SQL standard
requires that the first argument of PREV/NEXT contain at least
one column reference [2] -- e.g. PREV(1) is a syntax error.
Beyond the standard's rationale (no starting row for offsetting),
there is a practical reason: when the target row falls outside
the frame, PREV should return NULL, but a constant expression
like PREV(42) would still evaluate to 42 since it never reads
from the slot. I think it's correct to follow the standard and
reject PREV/NEXT without a column reference. What do you think?

[1] https://www.postgresql.org/message-id/20260305.142049.1864331791480656300.ishii%40postgresql.org
[2] ISO/IEC 19075-5, Subclause 5.6.2

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Sorry for sending these before your next revision of v45 --
> I'll be busy with a project proposal for the next couple of
> weeks, so I wanted to share them before that.

No problem at all. Thank you for your work.

> Here are the patches on top of v45, incorporating the fixes and
> improvements I mentioned earlier, plus additional changes from a
> thorough code review. There are quite a few patches since I went
> ahead without prior discussion -- please review each one individually
> and feel free to drop any that you disagree with.
> 
> Here's a summary of each patch (to be applied on top of v45):
> 
>   0001: Fix mergeGroupPrefixSuffix() max increment
>         When absorbing prefix/suffix, child->max was not incremented,
>         causing incorrect quantifier bounds. (reported by Zsolt)

Looks good to me.

>   0002: Fix RPR error codes and GROUPS typo
>         Use ERRCODE_WINDOWING_ERROR instead of ERRCODE_SYNTAX_ERROR
>         for semantic window-frame violations. Fix "GROUP" typo to
>         "GROUPS" in frame validation error message. (reported by Zsolt)

Looks good to me.

>   0003: Add check_stack_depth() and CHECK_FOR_INTERRUPTS()
>         Add stack depth protection to recursive pattern optimization
>         and interrupt checks to NFA engine loops.

Looks good to me.

>   0004: Fix window_last_value set_mark during RPR
>         Restore set_mark=true in window_last_value (normal behavior)
>         and add an RPR-specific override inside WinGetFuncArgInFrame.
>         This keeps the RPR workaround localized rather than changing
>         the caller's semantics unconditionally.

So, if RPR is active, WinSetMarkPosition() is not called at all?  That
seems too strong limitation.  Can't we set mark at frameheadpos even
if RPR is active? It seems safe since the only allowed franme start
option is ROWS BETWEEN CURRENT ROW and we never step back to the rows
before frameheadpos.

>   0005: Fix row_is_in_reduced_frame in WINDOW_SEEK_TAIL
>         Pass frameheadpos directly to row_is_in_reduced_frame
>         instead of frameheadpos+relpos. Currently only last_value()
>         calls this path with relpos=0 so no actual bug, but the
>         old expression would be incorrect for negative relpos.
>         Also add a bounds check for future callers.

Looks good to me.

>   0006: Clarify ST_NONE intent
>         Add comment explaining ST_NONE = 0 is the default for
>         non-RPR windows.

Looks good to me.

>   0007: Clarify inverse transition optimization comment
>         Document why RPR disables inverse transition: the reduced
>         frame changes row by row.

Looks good to me.

>   0008: Reject unused DEFINE variables
>         I know you preferred silently ignoring unused DEFINE
>         variables [1], and I agree the standard doesn't mandate
>         an error. However, if we later add qualified column
>         references (e.g. B AS A.price > 100), B's expression
>         depends on A being present. If A is not used in PATTERN
>         and the planner silently removes it, B's reference to A
>         becomes dangling. I worry that silently allowing this now
>         could create forward-compatibility problems once qualified
>         references are introduced. For that reason, I'm inclined
>         to think rejecting them now may be safer than changing
>         behavior later, which would be a user-visible compatibility
>         break. This is also consistent with Oracle's behavior
>         (ORA-62503), as SungJun reported, and it helps catch user
>         typos in DEFINE variable names at parse time.

Ok, let's throw an error in the case then.

>   0009: Clarify RPR documentation in advanced.sgml
>         Improve absorption explanation and clarify non-match row
>         aggregation behavior with concrete examples.

Looks good to me.

>   0010: Fix typos in RPR comments and parser README

Looks good to me.

>   0011: Clarify excludeLocation and empty quantifier in gram.y
>         Add comments explaining the conditional location assignment
>         pattern and the empty quantifier rule.

Looks good to me.

>   0012: Clarify RPR_VARID_MAX definition
>         Document varId range 0-250 and reserved control element
>         values 252+.

Looks good to me.

>   0013: Move local variables to function scope
>         In row_is_in_reduced_frame, move declarations out of
>         switch case blocks.

Looks good to me.

>   0014: Reset reduced_frame_map pointer in release_partition
>         Set reduced_frame_map = NULL and alloc_sz = 0 to prevent
>         dangling pointer after partition context reset.

Looks good to me.

>   0015: Remove redundant list manipulation in nfa_add_matched_state
>         Simplify doubly-linked list operation that was duplicated
>         by the subsequent ExecRPRFreeContext() call.

Looks good to me.

>   experimental: Implement 1-slot PREV/NEXT navigation

Great work!

>         The slot-based PREV/NEXT approach I mentioned earlier.
>         This no longer needs attno_map, so the plan cache mutation
>         issue is gone. PREV/NEXT now also accepts an optional
>         second argument for offset, e.g. PREV(price, 2).
> 
>         Note: all existing regression tests pass with this patch,
>         but my understanding of TupleSlot internals and JIT is still
>         shallow -- the implementation largely copies surrounding
>         patterns, so there may be issues I haven't caught yet. I'd
>         like to keep this as a separate patch on top of v46 until it
>         is trustworthy enough, rather than folding it into the main
>         series. I'll continue reviewing and hardening it.

Agreed. Let's keep this as a separate patch.

> One design decision regarding PREV/NEXT: the SQL standard
> requires that the first argument of PREV/NEXT contain at least
> one column reference [2] -- e.g. PREV(1) is a syntax error.
> Beyond the standard's rationale (no starting row for offsetting),
> there is a practical reason: when the target row falls outside
> the frame, PREV should return NULL, but a constant expression
> like PREV(42) would still evaluate to 42 since it never reads
> from the slot. I think it's correct to follow the standard and
> reject PREV/NEXT without a column reference. What do you think?

I agree with you. Let's follow the standard/

I am going to work on v46 patch sets.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

>   0004: Fix window_last_value set_mark during RPR
>         Restore set_mark=true in window_last_value (normal behavior)
>         and add an RPR-specific override inside WinGetFuncArgInFrame.
>         This keeps the RPR workaround localized rather than changing
>         the caller's semantics unconditionally.

So, if RPR is active, WinSetMarkPosition() is not called at all?  That
seems too strong limitation.  Can't we set mark at frameheadpos even
if RPR is active? It seems safe since the only allowed franme start
option is ROWS BETWEEN CURRENT ROW and we never step back to the rows
before frameheadpos.

You raise a valid point. Setting mark at frameheadpos would be safe
for the window function's own read pointer, since we only allow
ROWS BETWEEN CURRENT ROW.

However, the difficulty is with the PREV/NEXT navigation. In the
experimental patch, PREV accepts an optional offset argument --
e.g. PREV(price, N) -- and this offset can be a runtime expression
whose value is not known until evaluation time. If the mark is
advanced to frameheadpos, PREV(price, N) with a large N could try
to access rows that the tuplestore has already truncated.

This is why the experimental patch takes a different approach: it
creates a separate nav_winobj with its own mark pointer pinned at
position 0, so that the tuplestore never truncates rows that PREV
might need. The window function's own mark management is left
unchanged.

The mark=0 approach is safe but conservative -- it prevents the
tuplestore from releasing any rows within the partition. The SQL
standard (ISO/IEC 19075-5, Subclause 5.6.2) requires the offset
argument to be a "runtime constant" -- meaning it cannot reference
columns or row pattern variables. So in practice, the maximum
offset is always known at plan time, which opens the door for a
future optimization: advance the mark to (currentpos - max_offset)
when all PREV offsets in the DEFINE clause are constant.

Since the experimental patch redesigns how mark works for PREV/NEXT
navigation, I think we should drop 0004 from the current series
and revisit the set_mark question together with the experimental
patch. What do you think?

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> So, if RPR is active, WinSetMarkPosition() is not called at all?  That
>> seems too strong limitation.  Can't we set mark at frameheadpos even
>> if RPR is active? It seems safe since the only allowed franme start
>> option is ROWS BETWEEN CURRENT ROW and we never step back to the rows
>> before frameheadpos.
> 
> 
> You raise a valid point. Setting mark at frameheadpos would be safe
> for the window function's own read pointer, since we only allow
> ROWS BETWEEN CURRENT ROW.
> 
> However, the difficulty is with the PREV/NEXT navigation. In the
> experimental patch, PREV accepts an optional offset argument --
> e.g. PREV(price, N) -- and this offset can be a runtime expression
> whose value is not known until evaluation time. If the mark is
> advanced to frameheadpos, PREV(price, N) with a large N could try
> to access rows that the tuplestore has already truncated.
>
> This is why the experimental patch takes a different approach: it
> creates a separate nav_winobj with its own mark pointer pinned at
> position 0, so that the tuplestore never truncates rows that PREV
> might need. The window function's own mark management is left
> unchanged.
>
> The mark=0 approach is safe but conservative -- it prevents the
> tuplestore from releasing any rows within the partition. The SQL
> standard (ISO/IEC 19075-5, Subclause 5.6.2) requires the offset
> argument to be a "runtime constant" -- meaning it cannot reference
> columns or row pattern variables. So in practice, the maximum
> offset is always known at plan time, which opens the door for a
> future optimization: advance the mark to (currentpos - max_offset)
> when all PREV offsets in the DEFINE clause are constant.
>
> Since the experimental patch redesigns how mark works for PREV/NEXT
> navigation, I think we should drop 0004 from the current series
> and revisit the set_mark question together with the experimental
> patch. What do you think?

Agreed. So I just want to make sure I create v46 using 0001-0003 and
0005-0015. Am I correct?

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:


2026년 3월 21일 (토) 23:16, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Hi Henson,

>> So, if RPR is active, WinSetMarkPosition() is not called at all?  That
>> seems too strong limitation.  Can't we set mark at frameheadpos even
>> if RPR is active? It seems safe since the only allowed franme start
>> option is ROWS BETWEEN CURRENT ROW and we never step back to the rows
>> before frameheadpos.
>
>
> You raise a valid point. Setting mark at frameheadpos would be safe
> for the window function's own read pointer, since we only allow
> ROWS BETWEEN CURRENT ROW.
>
> However, the difficulty is with the PREV/NEXT navigation. In the
> experimental patch, PREV accepts an optional offset argument --
> e.g. PREV(price, N) -- and this offset can be a runtime expression
> whose value is not known until evaluation time. If the mark is
> advanced to frameheadpos, PREV(price, N) with a large N could try
> to access rows that the tuplestore has already truncated.
>
> This is why the experimental patch takes a different approach: it
> creates a separate nav_winobj with its own mark pointer pinned at
> position 0, so that the tuplestore never truncates rows that PREV
> might need. The window function's own mark management is left
> unchanged.
>
> The mark=0 approach is safe but conservative -- it prevents the
> tuplestore from releasing any rows within the partition. The SQL
> standard (ISO/IEC 19075-5, Subclause 5.6.2) requires the offset
> argument to be a "runtime constant" -- meaning it cannot reference
> columns or row pattern variables. So in practice, the maximum
> offset is always known at plan time, which opens the door for a
> future optimization: advance the mark to (currentpos - max_offset)
> when all PREV offsets in the DEFINE clause are constant.
>
> Since the experimental patch redesigns how mark works for PREV/NEXT
> navigation, I think we should drop 0004 from the current series
> and revisit the set_mark question together with the experimental
> patch. What do you think?

Agreed. So I just want to make sure I create v46 using 0001-0003 and
0005-0015. Am I correct?

Yes, that’s right!​​​​​​​​​​​​​​​​


Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
>> Agreed. So I just want to make sure I create v46 using 0001-0003 and
>> 0005-0015. Am I correct?
> 
> 
> Yes, that’s right!​​​​​​​​​​​​​​​​

Ok, attached is the v46 patches. Here some comments:

- As git apply did not like 0003, I applied it using patch command.

- 0010 did not apply because 0004 skipped. I modified 0010 a little
  bit and applied it.

- Henson's "experimental" implementation of PREV/NEXT are not included
  in the patch set.

Here are differences from v45.

- Number of patch files are now 9, not 8. As we discussed, I split
  the regression test patches into two separate patch files: SQL +
  data patches and expected files. It seems CFBot does not work
  smoothly if a patch file is too large. We hope the splitting makes
  CFBot work more smoothly.

Below are comments from Henson. See
https://www.postgresql.org/message-id/CAAAe_zBbrnx2fjK2s%2BJgx6TSOdnKAPawXbHeX49WqmX9ji%2BHdg%40mail.gmail.com
for more details.

 0001: Fix mergeGroupPrefixSuffix() max increment
        When absorbing prefix/suffix, child->max was not incremented,
        causing incorrect quantifier bounds. (reported by Zsolt)

  0002: Fix RPR error codes and GROUPS typo
        Use ERRCODE_WINDOWING_ERROR instead of ERRCODE_SYNTAX_ERROR
        for semantic window-frame violations. Fix "GROUP" typo to
        "GROUPS" in frame validation error message. (reported by Zsolt)

  0003: Add check_stack_depth() and CHECK_FOR_INTERRUPTS()
        Add stack depth protection to recursive pattern optimization
        and interrupt checks to NFA engine loops.

  0005: Fix row_is_in_reduced_frame in WINDOW_SEEK_TAIL
        Pass frameheadpos directly to row_is_in_reduced_frame
        instead of frameheadpos+relpos. Currently only last_value()
        calls this path with relpos=0 so no actual bug, but the
        old expression would be incorrect for negative relpos.
        Also add a bounds check for future callers.

  0006: Clarify ST_NONE intent
        Add comment explaining ST_NONE = 0 is the default for
        non-RPR windows.

  0007: Clarify inverse transition optimization comment
        Document why RPR disables inverse transition: the reduced
        frame changes row by row.

  0008: Reject unused DEFINE variables
        I know you preferred silently ignoring unused DEFINE
        variables [1], and I agree the standard doesn't mandate
        an error. However, if we later add qualified column
        references (e.g. B AS A.price > 100), B's expression
        depends on A being present. If A is not used in PATTERN
        and the planner silently removes it, B's reference to A
        becomes dangling. I worry that silently allowing this now
        could create forward-compatibility problems once qualified
        references are introduced. For that reason, I'm inclined
        to think rejecting them now may be safer than changing
        behavior later, which would be a user-visible compatibility
        break. This is also consistent with Oracle's behavior
        (ORA-62503), as SungJun reported, and it helps catch user
        typos in DEFINE variable names at parse time.

  0009: Clarify RPR documentation in advanced.sgml
        Improve absorption explanation and clarify non-match row
        aggregation behavior with concrete examples.

  0010: Fix typos in RPR comments and parser README

  0011: Clarify excludeLocation and empty quantifier in gram.y
        Add comments explaining the conditional location assignment
        pattern and the empty quantifier rule.

  0012: Clarify RPR_VARID_MAX definition
        Document varId range 0-250 and reserved control element
        values 252+.

  0013: Move local variables to function scope
        In row_is_in_reduced_frame, move declarations out of
        switch case blocks.

  0014: Reset reduced_frame_map pointer in release_partition
        Set reduced_frame_map = NULL and alloc_sz = 0 to prevent
        dangling pointer after partition context reset.

  0015: Remove redundant list manipulation in nfa_add_matched_state
        Simplify doubly-linked list operation that was duplicated
        by the subsequent ExecRPRFreeContext() call.

Best regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Attached are 6 incremental patches on top of v46.

0001-0005 are small independent fixes. 0006 is the main
PREV/NEXT navigation redesign that was discussed as the
"experimental" implementation in prior messages.

Here is a summary of each patch:


  0001: Remove unused regex/regex.h include from nodeWindowAgg.c
        The regex header was left over from an earlier implementation
        that used the regex engine for pattern matching. The current
        NFA engine in execRPR.c does not use it.


  0002: Add CHECK_FOR_INTERRUPTS() to nfa_add_state_unique()
        This function iterates through a linked list of NFA states
        to check for duplicates. In state explosion scenarios
        (complex patterns with alternations and quantifiers), this
        list can grow significantly. Without an interrupt check,
        the loop is unresponsive to query cancellation.


  0003: Add CHECK_FOR_INTERRUPTS() to nfa_try_absorb_context()
        Similar to 0002. The absorption loop iterates through the
        context chain, which can grow unbounded with streaming
        window patterns. Each iteration also calls
        nfa_states_covered() which has its own loop.


  0004: Fix in-place modification of defineClause TargetEntry
        In set_upper_references(), the defineClause TargetEntry
        was modified in-place by fix_upper_expr() without making
        a copy first. This follows the same flatCopyTargetEntry()
        pattern already used for the main targetlist in the same
        function.


  0005: Fix mark handling for last_value() under RPR
        This is a revised version of the v45 0004 patch that you
        commented on [1]. You pointed out that suppressing
        WinSetMarkPosition() entirely under RPR was too strong a
        limitation, and we agreed to drop it and revisit together
        with the experimental PREV/NEXT patch.

        The RPR executor patch changed set_mark from true to
        false in window_last_value() to avoid mark advancement
        problems under RPR. But this also penalizes non-RPR
        queries by preventing tuplestore memory reclamation.

        The revised approach: restore set_mark=true (upstream
        default), and add a targeted guard in
        WinGetFuncArgInFrame() that only suppresses mark
        advancement for SEEK_TAIL under RPR -- not for all
        seek types as in v45 0004. Only SEEK_TAIL needs
        suppression because advancing the mark from the tail
        could prevent revisiting earlier rows that still fall
        within a future row's reduced frame.

        [1] https://www.postgresql.org/message-id/20260321.140232.1947157589839395257.ishii%40postgresql.org


  0006: Implement 1-slot PREV/NEXT navigation for RPR
        This is the main patch. It redesigns PREV/NEXT navigation
        from the 3-slot model (outer/scan/inner with varno
        rewriting) to a 1-slot model using expression opcodes.

        Key changes:

        - RPRNavExpr: a new expression node type that replaces
          the previous approach of identifying PREV/NEXT by
          funcid. The parser transforms PREV/NEXT function calls
          into RPRNavExpr nodes in ParseFuncOrColumn().

        - EEOP_RPR_NAV_SET/RESTORE: two new opcodes that
          temporarily swap ecxt_outertuple to the target row
          during expression evaluation. The argument expression
          evaluates against the swapped slot, then the original
          slot is restored. This eliminates varno rewriting and
          naturally supports arbitrary offsets.

        - 2-argument form: PREV(value, offset) and
          NEXT(value, offset) are now supported. The offset
          defaults to 1 if omitted; offset=0 refers to the
          current row. The offset must be a run-time constant
          per the SQL standard.

        - nav_winobj: a dedicated WindowObject with its own
          tuplestore read pointer, separate from aggregate
          processing. A mark pointer pinned at position 0
          prevents tuplestore truncation so that PREV(expr, N)
          can reach any prior row. This is conservative -- it
          retains the entire partition -- but since the standard
          requires offsets to be run-time constants, we could
          advance the mark to (currentpos - max_offset) in a
          future optimization. I'd prefer to defer that until
          the basic navigation is stable.

        - Documentation and tests updated.


Changes from the experimental version of 0006:

- NULL/negative offset error rationale changed from "matching
  Oracle behavior" to the SQL standard (ISO/IEC 9075-2,
  Subclause 5.6.2: "There is an exception if the value of
  the offset is negative or null"). The behavior is the same;
  only the comment was corrected.

- RPRNavKind changed from -1/+1 values to plain enum values.
  The previous version used kind as an arithmetic multiplier
  (offset * kind), but this pattern cannot extend to FIRST/LAST
  which have different position semantics. The new version uses
  a switch statement with pg_sub/add_s64_overflow instead.

- Parser validation walkers consolidated from three separate
  walkers into a single NavCheckResult struct + nav_check_walker,
  reducing tree traversals from up to 4 per RPRNavExpr to 1-2.

- JIT changed from attempting to compile to explicit interpreter
  fallback. See item 2 below for the rationale.

- Additional test cases for subquery offset (caught by
  DEFINE-level restriction), first-arg subquery, and first-arg
  volatile function (allowed per standard).

I've reviewed and revised 0006 since the experimental version.
I think it is now ready to be included in the next version of
the patch set. It passes all existing regression tests (rpr,
rpr_base, rpr_explain, rpr_nfa) and adds comprehensive tests
for the new functionality.

Two items I'd like your opinion on:

1. 0005 (mark handling): The revised approach only suppresses
   mark advancement for SEEK_TAIL under RPR, unlike v45 0004
   which suppressed it for all seek types. Does narrowing to
   SEEK_TAIL seem reasonable to you, or do you see cases where
   other seek types could also be affected?

2. LLVM JIT fallback (in 0006): The mid-expression slot swap
   conflicts with how JIT caches tuple data pointers. The
   experimental version produced wrong results under
   jit_above_cost=0, and I have not found a clean fix within
   the current JIT framework. For now, DEFINE expressions
   containing PREV/NEXT fall back to the interpreter; other
   expressions in the same query are still JIT-compiled.
   I'd like to keep this as-is for now and look for a proper
   JIT solution over time. Does that sound reasonable?


Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Separately from the PREV/NEXT patches, I have been analyzing
how FIRST and LAST navigation would interact with the current
NFA engine -- particularly context absorption and DEFINE
evaluation sharing. This is not a proposal to implement them
now; rather, I wanted to document the design constraints
while the analysis is fresh, so we have a reference when we
are ready to add them.


Design Note: FIRST/LAST Navigation for RPR
===========================================

Scope: This note covers only patterns without quantifiers, where
each pattern variable consumes exactly one row.


1. Navigation Function Classification
--------------------------------------

The SQL standard (ISO/IEC 19075-5:2021) defines four navigation
functions in two categories:

PREV/NEXT -- physical navigation:
  - Scope: entire row pattern partition
  - Offset: physical (row position within partition)
  - Base row: the row denoted by the variable under running
    semantics (in our no-qualifier scope: current eval row)
  - Default offset: 1
  - Can reach rows outside the match (standard 5.6.2)
  - Always RUNNING semantics only

FIRST/LAST -- logical navigation:
  - Standard scope: rows mapped to a specific variable
  - Our scope (no quantifier): match_start to currentpos range
  - Offset: logical (in standard), but equivalent to physical
    when each variable maps to at most one row
  - Base: match_start (FIRST) or currentpos (LAST)
  - Default offset: 0 (unlike PREV/NEXT which default to 1)
  - RUNNING semantics in DEFINE; FINAL available in MEASURES

FIRST/LAST results depend on the match start position
(match_start). Each current row in window RPR triggers an
independent match attempt with its own match_start. FIRST
always depends on match_start. LAST(price) depends only on
currentpos and is match_start-independent, but LAST(price, N)
depends on match_start because the NULL boundary check
(currentpos - N < match_start) varies with match_start.

Example (PATTERN (A B C), match_start = 3):

    FIRST(price)    = R3.price   (match_start row)
    FIRST(price, 1) = R4.price   (match_start + 1)
    LAST(price)     = R5.price   (currentpos row)
    LAST(price, 1)  = R4.price   (currentpos - 1)
    LAST(price, 3)  = NULL       (before match_start)

    PREV(price, 2)  = R3.price   (pos - 2, physical)
    NEXT(price, 2)  = R7.price   (pos + 2, beyond match)

PREV/NEXT can reach any row in the partition regardless of
match boundaries. FIRST/LAST are valid only within the
match_start to currentpos range.


2. match_start and NFA Contexts
-------------------------------

Each match_start defines one match attempt, which corresponds
to one NFA context. Different contexts have different
match_start values. Context absorption merges contexts when
one context's pattern states are covered by another's. If the
merged contexts have different match_start values, FIRST/LAST
would produce incorrect results because the surviving context's
match_start would be used for both.


3. Compound Navigation (PREV/NEXT wrapping FIRST/LAST)
------------------------------------------------------

The standard (5.6.4) permits nesting FIRST/LAST inside
PREV/NEXT. Using the standard's notation with variable
qualifiers (which our no-quantifier scope does not yet
require):

    PREV(LAST(A.Price + A.Tax, 1), 3)

Evaluation proceeds in three steps:
  1. Inner FIRST/LAST: determines target row position only
     (does not evaluate the expression)
  2. Outer PREV/NEXT: applies physical offset from that row
  3. Expression evaluation: at the final destination row only

The reverse nesting (FIRST/LAST wrapping PREV/NEXT) and
same-kind nesting (PREV inside PREV, etc.) are prohibited.

Since the inner function only determines a position, the
compound operation can be flattened into a single RPRNavExpr
node internally, requiring only one slot swap.


4. Context Absorption Rules
----------------------------

Absorption safety depends on whether the navigation function
depends on match_start:

  DEFINE content                  | match_start dep. | absorption
  --------------------------------|------------------|----------
  No navigation                   | none             | safe
  PREV/NEXT only                  | none             | safe
  LAST (no offset)                | none             | safe
  LAST (with offset)              | boundary check   | unsafe
  FIRST (any)                     | direct           | unsafe
  Compound (inner FIRST)          | direct           | unsafe
  Compound (inner LAST, no off.)  | none             | safe
  Compound (inner LAST, with off.)| boundary check   | unsafe

The criterion: if the expression depends on match_start in
any way, absorption is unsafe. Comparing match_start values
at runtime is impractical, so we treat any dependency as
unconditionally unsafe.


5. DEFINE Clause Evaluation Rules
---------------------------------

Currently, nfa_evaluate_row(pos) evaluates all DEFINE
variables once per row and shares the results across all NFA
contexts.

  DEFINE content                  | evaluation
  --------------------------------|--------------------------
  No navigation                   | shared (once per row)
  PREV/NEXT only                  | shared (once per row)
  LAST (no offset)                | shared (once per row)
  LAST (with offset)              | per-context
  FIRST (any)                     | per-context
  Compound (inner FIRST)          | per-context
  Compound (inner LAST, no off.)  | shared (once per row)
  Compound (inner LAST, with off.)| per-context


6. Slot Swap Elision
--------------------

When the final target position resolves to currentpos, the
slot swap can be elided. This applies to:
  - PREV(price, 0), NEXT(price, 0): offset 0
  - LAST(price), LAST(price, 0): always currentpos
  - Compound cases where offsets cancel, e.g.,
    NEXT(LAST(price, 1), 1)


The PREV/NEXT infrastructure (RPRNavExpr, EEOP_RPR_NAV_SET/
RESTORE, nav_winobj) can be reused directly for FIRST/LAST --
it would mainly require adding two RPRNavKind values and
match_start arithmetic in the ExecEvalRPRNavSet switch.
No variable qualifiers, match history tracking, or CLASSIFIER
infrastructure would be needed for this no-quantifier scope.

I do think CLASSIFIER, MEASURES, and match history tracking
should stay out of the initial patch set -- they add
significant complexity to NFA contexts and affect absorption
in ways that are hard to validate incrementally. Variable
qualifiers and quantifier support for navigation functions
are also tied to match history infrastructure, so they should
be deferred as well. Better to get the current feature set
stable first.

With PREV/NEXT now resolved (0006), the next major milestone
would be match history infrastructure (needed for CLASSIFIER,
MEASURES, variable qualifiers, and quantifier-aware
navigation). Before that larger step, there are a few
remaining items that can be done within the current
architecture:

Optimization:
  - PREFIX pattern absorption (e.g., A (B+) C) [1][2]
  - Fixed-length iteration group absorption
    (e.g., (A B{2})+ ) [3]

Feature:
  - FIRST/LAST navigation (this note)
  - LLVM JIT proper support for slot swap (0006 uses
    interpreter fallback) [4][5]

[1] https://www.postgresql.org/message-id/CAAAe_zAEg7sVM%3DWDwXMyE-odGmQyXSVi5ZzWgye6SupSjdMKpg%40mail.gmail.com
[2] https://www.postgresql.org/message-id/CAAAe_zDq7R8CaDfmh8C%2BH3_639Y5LtJD%2B2Z%3D1txDt%3DvaOr90rQ%40mail.gmail.com
[3] https://www.postgresql.org/message-id/CAAAe_zBY%2BEqk_DQpS0cy1Eb67H9v92tyaf%2BU%2BSKKuLGUs_z%2BEA%40mail.gmail.com
[4] https://www.postgresql.org/message-id/CAAAe_zBbrnx2fjK2s%2BJgx6TSOdnKAPawXbHeX49WqmX9ji%2BHdg%40mail.gmail.com
[5] https://www.postgresql.org/message-id/CAAAe_zBCF3dwSjStmG0kJqw_y1z8QD73Rf1G58QTKEvd9tScwA%40mail.gmail.com

The question is how much of this to complete before the
current patches are committed. The patch set is already
substantial, and the next CommitFest is in July. What do
you think -- should we try to include some of these items
in the current round, or focus on getting what we have
committed first? Also, do you see any blockers that might
prevent the current patch set from being committed?


Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Attached are 6 incremental patches on top of v46.

Thank you!

> 0001-0005 are small independent fixes. 0006 is the main
> PREV/NEXT navigation redesign that was discussed as the
> "experimental" implementation in prior messages.
> 
> Here is a summary of each patch:
> 
> 
>   0001: Remove unused regex/regex.h include from nodeWindowAgg.c
>         The regex header was left over from an earlier implementation
>         that used the regex engine for pattern matching. The current
>         NFA engine in execRPR.c does not use it.

Good catch!

>   0002: Add CHECK_FOR_INTERRUPTS() to nfa_add_state_unique()
>         This function iterates through a linked list of NFA states
>         to check for duplicates. In state explosion scenarios
>         (complex patterns with alternations and quantifiers), this
>         list can grow significantly. Without an interrupt check,
>         the loop is unresponsive to query cancellation.

Looks good to me.

>   0003: Add CHECK_FOR_INTERRUPTS() to nfa_try_absorb_context()
>         Similar to 0002. The absorption loop iterates through the
>         context chain, which can grow unbounded with streaming
>         window patterns. Each iteration also calls
>         nfa_states_covered() which has its own loop.

Looks good to me.

>   0004: Fix in-place modification of defineClause TargetEntry
>         In set_upper_references(), the defineClause TargetEntry
>         was modified in-place by fix_upper_expr() without making
>         a copy first. This follows the same flatCopyTargetEntry()
>         pattern already used for the main targetlist in the same
>         function.

Probably we want to modify the comment above since it implies an
in-place modification? What about something like this? (Modifies -> Replace)

	/*
	 * Replace an expression tree in each DEFINE clause so that all Var
	 * nodes's varno refers to OUTER_VAR.
	 */

>   0005: Fix mark handling for last_value() under RPR
>         This is a revised version of the v45 0004 patch that you
>         commented on [1]. You pointed out that suppressing
>         WinSetMarkPosition() entirely under RPR was too strong a
>         limitation, and we agreed to drop it and revisit together
>         with the experimental PREV/NEXT patch.
> 
>         The RPR executor patch changed set_mark from true to
>         false in window_last_value() to avoid mark advancement
>         problems under RPR. But this also penalizes non-RPR
>         queries by preventing tuplestore memory reclamation.
> 
>         The revised approach: restore set_mark=true (upstream
>         default), and add a targeted guard in
>         WinGetFuncArgInFrame() that only suppresses mark
>         advancement for SEEK_TAIL under RPR -- not for all
>         seek types as in v45 0004. Only SEEK_TAIL needs
>         suppression because advancing the mark from the tail
>         could prevent revisiting earlier rows that still fall
>         within a future row's reduced frame.

I think instead we can set a mark at frameheadpos when seek type is
SEEK_TAIL and RPR is enabled. See attached patch.

>   0006: Implement 1-slot PREV/NEXT navigation for RPR
>         This is the main patch. It redesigns PREV/NEXT navigation
>         from the 3-slot model (outer/scan/inner with varno
>         rewriting) to a 1-slot model using expression opcodes.
> 
>         Key changes:
> 
>         - RPRNavExpr: a new expression node type that replaces
>           the previous approach of identifying PREV/NEXT by
>           funcid. The parser transforms PREV/NEXT function calls
>           into RPRNavExpr nodes in ParseFuncOrColumn().
> 
>         - EEOP_RPR_NAV_SET/RESTORE: two new opcodes that
>           temporarily swap ecxt_outertuple to the target row
>           during expression evaluation. The argument expression
>           evaluates against the swapped slot, then the original
>           slot is restored. This eliminates varno rewriting and
>           naturally supports arbitrary offsets.
> 
>         - 2-argument form: PREV(value, offset) and
>           NEXT(value, offset) are now supported. The offset
>           defaults to 1 if omitted; offset=0 refers to the
>           current row. The offset must be a run-time constant
>           per the SQL standard.
> 
>         - nav_winobj: a dedicated WindowObject with its own
>           tuplestore read pointer, separate from aggregate
>           processing. A mark pointer pinned at position 0
>           prevents tuplestore truncation so that PREV(expr, N)
>           can reach any prior row. This is conservative -- it
>           retains the entire partition -- but since the standard
>           requires offsets to be run-time constants, we could
>           advance the mark to (currentpos - max_offset) in a
>           future optimization. I'd prefer to defer that until
>           the basic navigation is stable.
> 
>         - Documentation and tests updated.
>
>
> Changes from the experimental version of 0006:
> 
> - NULL/negative offset error rationale changed from "matching
>   Oracle behavior" to the SQL standard (ISO/IEC 9075-2,
>   Subclause 5.6.2: "There is an exception if the value of
>   the offset is negative or null"). The behavior is the same;
>   only the comment was corrected.
> 
> - RPRNavKind changed from -1/+1 values to plain enum values.
>   The previous version used kind as an arithmetic multiplier
>   (offset * kind), but this pattern cannot extend to FIRST/LAST
>   which have different position semantics. The new version uses
>   a switch statement with pg_sub/add_s64_overflow instead.
> 
> - Parser validation walkers consolidated from three separate
>   walkers into a single NavCheckResult struct + nav_check_walker,
>   reducing tree traversals from up to 4 per RPRNavExpr to 1-2.
> 
> - JIT changed from attempting to compile to explicit interpreter
>   fallback. See item 2 below for the rationale.
> 
> - Additional test cases for subquery offset (caught by
>   DEFINE-level restriction), first-arg subquery, and first-arg
>   volatile function (allowed per standard).
> 
> I've reviewed and revised 0006 since the experimental version.
> I think it is now ready to be included in the next version of
> the patch set. It passes all existing regression tests (rpr,
> rpr_base, rpr_explain, rpr_nfa) and adds comprehensive tests
> for the new functionality.

Excellent! I will take a look at it. (it will take for a while).

> Two items I'd like your opinion on:
> 
> 1. 0005 (mark handling): The revised approach only suppresses
>    mark advancement for SEEK_TAIL under RPR, unlike v45 0004
>    which suppressed it for all seek types. Does narrowing to
>    SEEK_TAIL seem reasonable to you, or do you see cases where
>    other seek types could also be affected?

See the comment above.

> 2. LLVM JIT fallback (in 0006): The mid-expression slot swap
>    conflicts with how JIT caches tuple data pointers. The
>    experimental version produced wrong results under
>    jit_above_cost=0, and I have not found a clean fix within
>    the current JIT framework. For now, DEFINE expressions
>    containing PREV/NEXT fall back to the interpreter; other
>    expressions in the same query are still JIT-compiled.
>    I'd like to keep this as-is for now and look for a proper
>    JIT solution over time. Does that sound reasonable?

I am not an expert of JIT, but for me, it sounds reasonable.  We can
enhance it later on.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index 4f882b877b1..3c9b822708c 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -4933,7 +4933,17 @@ WinGetSlotInFrame(WindowObject winobj, TupleTableSlot *slot,
 	if (isout)
 		*isout = false;
 	if (set_mark)
+	{
+		/*
+		 * If RPR is enabled and seek type is WINDOW_SEEK_TAIL, we set the
+		 * mark position unconditionally to frameheadpos. In this case the
+		 * frame always starts at CURRENT_ROW and never goes back, thus
+		 * setting the mark at the position is safe.
+		 */
+		if (winstate->rpPattern != NULL && seektype == WINDOW_SEEK_TAIL)
+			mark_pos = winstate->frameheadpos;
 		WinSetMarkPosition(winobj, mark_pos);
+	}
 	return 0;
 
 out_of_frame:
diff --git a/src/backend/utils/adt/windowfuncs.c b/src/backend/utils/adt/windowfuncs.c
index efb60c99052..74ef109f72e 100644
--- a/src/backend/utils/adt/windowfuncs.c
+++ b/src/backend/utils/adt/windowfuncs.c
@@ -682,7 +682,7 @@ window_last_value(PG_FUNCTION_ARGS)
 
 	WinCheckAndInitializeNullTreatment(winobj, true, fcinfo);
 	result = WinGetFuncArgInFrame(winobj, 0,
-								  0, WINDOW_SEEK_TAIL, false,
+								  0, WINDOW_SEEK_TAIL, true,
 								  &isnull, NULL);
 	if (isnull)
 		PG_RETURN_NULL();

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Thank you for the review and the attached patch for 0005.
I appreciate you taking the time to look at each patch
carefully.

Attached are 8 incremental patches on top of v46 (replacing
the previous 6-patch set). 0001-0003 are unchanged. 0004 and
0005 incorporate your feedback below. 0006 is a new planner
fix. Previous 0006 becomes 0007. 0008 is new.

>   0004: Fix in-place modification of defineClause TargetEntry

Probably we want to modify the comment above since it implies an
in-place modification? What about something like this? (Modifies -> Replace)

        /*
         * Replace an expression tree in each DEFINE clause so that all Var
         * nodes's varno refers to OUTER_VAR.
         */

Good point, thank you. Applied in the updated 0004.
 
>   0005: Fix mark handling for last_value() under RPR

I think instead we can set a mark at frameheadpos when seek type is
SEEK_TAIL and RPR is enabled. See attached patch.

Thank you for the patch. Your approach is cleaner -- setting
the mark at frameheadpos is more direct than suppressing
advancement. I've adopted it in the updated 0005.
 
>   0006: Implement 1-slot PREV/NEXT navigation for RPR

Excellent! I will take a look at it. (it will take for a while).

No rush at all. In the meantime, while testing the PREV/NEXT
patch in various query patterns, I found a planner issue.
I've also added JIT support. Here is a summary of the new
patches:


  0006: Prevent removal of RPR window functions in unused
        subquery outputs

        Wrapping an RPR window query in a subquery with an
        outer aggregate causes a crash:

          SELECT count(*) FROM (
            SELECT count(*) OVER w FROM ...
            WINDOW w AS (... DEFINE A AS i > PREV(i))
          ) t;

        remove_unused_subquery_outputs() replaces unused subquery
        target entries with NULL constants. When an RPR window
        function's result is not referenced by the outer query,
        this replacement eliminates all active window functions
        for the WindowClause, causing the planner to omit the
        WindowAgg node. DEFINE clause expressions containing
        RPRNavExpr (PREV/NEXT) then lose their execution context,
        leading to a crash.

        The fix skips the NULL replacement for window functions
        whose WindowClause has a defineClause. Even when the
        window function result is unused, RPR pattern matching
        (frame reduction) must still execute -- the WindowAgg
        node must be preserved.

        An alternative would be to let the planner remove the
        window function but teach it to still generate the
        WindowAgg node when defineClause is present, even with
        no active window functions. That would be a more
        targeted optimization but requires deeper planner
        changes. Do you think the current approach is
        sufficient, or would you prefer a different strategy?


  0007: Implement 1-slot PREV/NEXT navigation for RPR
        (unchanged from previous 0006)
 
> 2. LLVM JIT fallback (in 0006): The mid-expression slot swap

I am not an expert of JIT, but for me, it sounds reasonable.  We can
enhance it later on.

  0008: Add JIT compilation support for RPR PREV/NEXT navigation

        EEOP_OUTER_VAR normally uses slot pointers cached in the
        entry block, but the mid-expression slot swap in
        NAV_SET/RESTORE invalidates them. To avoid penalizing
        existing expressions, the reload path is only generated
        when RPR navigation opcodes are present in the
        expression (compile-time decision). Expressions without
        PREV/NEXT produce identical machine code as before.
        NAV_SET/RESTORE use the standard build_EvalXFunc pattern.

        A 100K-row PREV/NEXT test case that runs under
        jit_above_cost=0 is included in rpr.sql.

I would appreciate your thoughts on these when you have time.


Best regards,
Henson
 

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,


I'd like to propose an extension to the context absorption
optimization for Row Pattern Recognition in the window clause:
fixed-length iteration group absorption. This builds on the
two-flag absorption design [1] and three-phase execution
framework [2], and is a sibling optimization to PREFIX pattern
absorption [3].

The existing framework requires group children to have exactly
{1,1} quantifiers. This relaxes the constraint to accept any
fixed-length quantifier (min == max), allowing patterns like
(A B{2})+ and (A (B{2} C){4})+ to benefit from absorption
with no runtime changes.

PREFIX absorption [3] handles fixed-length elements before
the unbounded repetition; this handles fixed-length elements
inside the unbounded group.


[1] Context absorption design - two-flag approach
https://www.postgresql.org/message-id/CAAAe_zCmjDRf9u19xRRbtzq%2B-7ujqadZk0izz0mkef2j%2BWpBBA%40mail.gmail.com
[2] Three-phase absorption framework (Match -> Absorb -> Advance)
https://www.postgresql.org/message-id/CAAAe_zAGLOF_qporKahnL8ajSu_eXZYsJN2M1cEeF5n5GWSNdQ%40mail.gmail.com
[3] PREFIX pattern absorption
https://www.postgresql.org/message-id/CAAAe_zDq7R8CaDfmh8C%2BH3_639Y5LtJD%2B2Z%3D1txDt%3DvaOr90rQ%40mail.gmail.com
[4] FIRST/LAST navigation design note
https://www.postgresql.org/message-id/CAAAe_zCUrKGBgZdaazdO_v9QWHsS_1DXuP%3DrLeNhO3iwsHwwbg%40mail.gmail.com


Design Note: Fixed-Length Iteration Group Absorption
=====================================================


1. Problem Definition
=====================


1.1 Current Absorption Scope

Context absorption currently requires that children of an unbounded
group have exactly {1,1} quantifiers. This means only simple patterns
like (A B)+ qualify for absorption.

Patterns like (A B{2})+ or (A (B{2} C){4})+ are excluded even though
each iteration consumes a fixed number of rows.


1.2 The Fixed-Length Constraint

The existing {1,1} check is overly restrictive. The actual requirement
for absorption is that each iteration of the group consumes a fixed
number of rows, so that the count-dominance property holds: an older
context always has a repeat count >= any newer context at the same
element.

Any group where all children have min == max (recursively) satisfies
this property, regardless of nesting depth or quantifier values.


2. Relationship to the Existing Framework
==========================================


2.1 Position in the Three-Phase Execution Model

The Match -> Absorb -> Advance model [2] is preserved as-is. This
optimization only changes compile-time eligibility analysis in the
two-flag framework [1]; the Absorb phase logic is unchanged.


2.2 Prerequisites

The same four prerequisites as existing absorption apply:

1. Greedy quantifier -- the outer group must be greedy.
2. SKIP TO PAST LAST ROW -- prior matches suppress subsequent
   start points.
3. UNBOUNDED FOLLOWING -- all contexts see the same future rows.
4. Shared DEFINE evaluation -- all contexts produce the same
   DEFINE result for a given row [4].


2.3 Extension of the Dominance Order

The existing dominance condition is unchanged:

    C_old and C_new are in the absorbable region of the same
    element, and C_old.counts >= C_new.counts.

The only change is which patterns are recognized as having an
absorbable region. The runtime count comparison works identically
regardless of the step size per iteration.


3. Correctness Argument
========================


A fixed-length quantifier (min == max) is semantically equivalent
to repeating the element that many times. Therefore any pattern
with fixed-length children can be conceptually unrolled to {1,1}
elements:

  (A B{2})+           -> (A B B)+
  (A (B{2} C){4})+    -> (A B B C B B C B B C B B C)+
  ((A{2} B{3}){2})+   -> (A A B B B A A B B B)+

The unrolled form contains only {1,1} VARs inside the unbounded
group, which is exactly the existing Case 2 that is already proven
correct for absorption.

This optimization recognizes fixed-length groups at compile time
without actually unrolling them. The runtime behavior is identical
to the unrolled form: each iteration consumes a fixed number of
rows, count-dominance holds, and absorption proceeds unchanged.


4. Compile-Time Analysis
=========================


4.1 Change to isUnboundedStart()

Currently, Case 2 in isUnboundedStart() requires all children of
an unbounded group to be simple {1,1} VARs. The relaxation:

- VAR children: accept min == max (any value)
- BEGIN children (nested subgroups): recursively verify that all
  descendants have min == max, including the subgroup's own END
  quantifier
- ALT children: reject (unchanged)

The check follows the existing depth-based traversal of the flat
element array.


4.2 Flat Array Example

Pattern: (A (B{2} C){4})+

  [0] BEGIN depth=0  min=1 max=INF   <- outer group
  [1] A     depth=1  min=1 max=1     <- 1==1 OK
  [2] BEGIN depth=1  min=4 max=4     <- subgroup
  [3] B     depth=2  min=2 max=2     <- 2==2 OK
  [4] C     depth=2  min=1 max=1     <- 1==1 OK
  [5] END   depth=1  min=4 max=4     <- 4==4 OK
  [6] END   depth=0  min=1 max=INF   <- unbounded, greedy

Verification traverses [1]-[5] confirming min==max at every
level. [6] is the outer END: unbounded and greedy, so absorption
applies.


4.3 Runtime: No Changes

The runtime absorption logic (nfa_try_absorb_context,
nfa_states_covered) and flag assignment (RPR_ELEM_ABSORBABLE,
RPR_ELEM_ABSORBABLE_BRANCH) require no changes.


5. Worked Example
==================


Pattern: (A B{2})+
Step size = 1 + 2 = 3.

Data: rows match in repeating A, B, B cycle.
Contexts that fail A at B-rows die immediately (omitted).

Row  Data  C_old             C_new            Active
r0   A     A                 -                1
r1   B     B(cnt=1)          -                1
r2   B     B(cnt=2)->END     -                1
           count=1, loops
r3   A     A                 A                2
r4   B     B(cnt=1)          B(cnt=1)         2
r5   B     B(cnt=2)->END     B(cnt=2)->END    2
           count=2            count=1
           absorb: 2 >= 1 -> C_new absorbed
           C_old loops                        1
r6   A     A                 A                2
r7   B     B(cnt=1)          B(cnt=1)         2
r8   B     B(cnt=2)->END     B(cnt=2)->END    2
           count=3            count=1
           absorb: 3 >= 1 -> C_new absorbed
           C_old loops                        1

Absorption occurs at END (the ABSORBABLE judgment point),
where both contexts synchronize after completing one full
iteration. The older context has a strictly higher group
count and absorbs the newer one.

Between END points, both contexts progress in lockstep
at the same pattern positions. Maximum concurrent contexts
during this phase = 2. Overall complexity remains O(n).


6. Non-Qualifying Patterns
===========================


Patterns where any child has min != max do NOT qualify:

  (A B+ C)+    -- B+ has min=1, max=INF -> NOT fixed
  (A B{2,5})+  -- B has min=2, max=5 -> NOT fixed
  (A B?)+      -- B? has min=0, max=1 -> NOT fixed

These patterns have variable step sizes per iteration, so
count-dominance is not guaranteed. They remain non-absorbable
under this optimization.

Re: Row pattern recognition

Hi Tatsuo,

Attached are 15 incremental patches on top of v46 (replacing
the previous 8-patch set). Here is a summary of the changes
from the previous version:

  0001-0005: Unchanged from the previous set.

  0006: Fix DEFINE expression handling in RPR window
        planning (revised)

        Integration tests in 0007 revealed two crashes:
        (1) subquery wrapping with outer aggregate causes
        WindowAgg removal when RPR window function output
        is unused, (2) RPR and non-RPR windows coexisting
        causes SIGSEGV from RPRNavExpr propagating to the
        wrong WindowAgg. This version extends the fix to
        extract only Var nodes via pull_var_clause()
        instead of adding the whole DEFINE expression to
        the targetlist. The allpaths.c guard is extended
        to also preserve columns referenced by DEFINE
        clauses.

  0007: Add RPR planner integration tests (new)

        Planner optimization interactions with RPR windows
        have been revealing crashes, so this is a dedicated
        test file: window dedup, subquery flattening,
        DEFINE propagation, LATERAL, recursive CTE,
        etc. Will be expanded further.

  0008: Replace reduced frame map with single match result
        (new)

        RPR processes rows sequentially and maintains at
        most one active match per start position. This
        replaces the per-row boolean frame map array with
        four scalar fields (valid, matched, start, length),
        simplifying nodeWindowAgg.c.

  0009: Add fixed-length group absorption for RPR (new)

        Extends context absorption to accept fixed-length
        quantifiers (min == max) inside unbounded groups.
        The NFA compiler optimizes (A B B)+ into
        (A B{2})+, which previously lost absorption
        eligibility because only {1,1} children
        qualified. Now (A B{2})+ and ((A{2} B{3}){2})+
        also qualify with no runtime changes. Also fixes
        two NFA bugs: (1) incorrect absorption at
        non-judgment points -- added ABSORBABLE check
        in nfa_states_covered and fixed isAbsorbable
        propagation in advance exit paths, (2) VAR
        visited bitmap moved to nfa_add_state_unique
        to prevent false cycle detection on new-iteration
        loop-back caused by generalized END chain
        traversal. Design note posted separately [1].

  0010: Rename rpr_explain test views to descriptive
        names (new)

        Replaces sequential view names (rpr_ev83, rpr_ev84)
        with descriptive names (rpr_ev_nav_prev1, etc.) for
        maintainability when adding new tests.

  0011: Implement 1-slot PREV/NEXT navigation for RPR
        (was 0007, rebased)

        Context changes only: optimizer.h include moved to
        0006, test view names updated by 0010.

  0012: Add JIT compilation support for RPR PREV/NEXT
        (was 0008, unchanged)

        Note: master recently disabled JIT by default
        [3]. A quick benchmark with RPR did not show
        measurable improvement from JIT. This patch is
        retained for correctness (the new opcodes must
        be handled when JIT is enabled), but the
        practical benefit may be limited.

  0013: Add tuplestore trim optimization for RPR PREV
        navigation (new)

        The planner extracts max_offset from all PREV
        calls in DEFINE clauses and sets mark = currentpos
        - max_offset at runtime, so only max_offset rows
        are retained. Constant expressions are folded by
        the planner; non-constant offsets (parameters,
        etc.) are evaluated by the executor at init time
        via RPR_NAV_OFFSET_NEEDS_EVAL.

  0014: Update RPR code comments to reflect 1-slot
        navigation model (new)

        Updates stale comments in execRPR.c and
        parse_rpr.c that still referenced the old 3-slot
        design.

  0015: Implement FIRST/LAST navigation for RPR
        (work in progress)

        Adds FIRST(column) and LAST(column) navigation
        functions per SQL standard. Parser, planner,
        executor, and tests are included. See the design
        note [2] for the interaction with context
        absorption.

        Not yet done: compound navigation (e.g.
        PREV(FIRST(col))), tests for FIRST/LAST offset
        variants, tuplestore mark handling for FIRST,
        and additional edge-case tests.

In the FIRST/LAST design note [2], I listed remaining
items that can be done within the current architecture.
With this patch set, all items except PREFIX pattern
absorption are now covered: fixed-length group absorption
(0009), JIT proper support (0012), and FIRST/LAST
navigation (0015). PREFIX absorption is planned
separately, but stabilizing the base patch takes
priority. If it is ready in time, would it make sense
to decide then whether to include it in this round?
Apart from bug fixes, are there any features you
consider essential before the patch can be committed?

[1] Fixed-length group absorption design note
https://www.postgresql.org/message-id/CAAAe_zAKAGKpK9iHx3ZSuG59sP93r5dfootqv5tCfaMt%3Dw6wzA%40mail.gmail.com
[2] FIRST/LAST navigation design note
https://www.postgresql.org/message-id/CAAAe_zCUrKGBgZdaazdO_v9QWHsS_1DXuP%3DrLeNhO3iwsHwwbg%40mail.gmail.com
[3] jit: Change the default to off
https://github.com/postgres/postgres/commit/7f8c88c2b872

Best regards,
Henson

2026년 4월 2일 (목) 오후 12:51, Henson Choi <assam258@gmail.com>님이 작성:
Hi Tatsuo,

Thank you for the review and the attached patch for 0005.
I appreciate you taking the time to look at each patch
carefully.

Attached are 8 incremental patches on top of v46 (replacing
the previous 6-patch set). 0001-0003 are unchanged. 0004 and
0005 incorporate your feedback below. 0006 is a new planner
fix. Previous 0006 becomes 0007. 0008 is new.

>   0004: Fix in-place modification of defineClause TargetEntry

Probably we want to modify the comment above since it implies an
in-place modification? What about something like this? (Modifies -> Replace)

        /*
         * Replace an expression tree in each DEFINE clause so that all Var
         * nodes's varno refers to OUTER_VAR.
         */

Good point, thank you. Applied in the updated 0004.
 
>   0005: Fix mark handling for last_value() under RPR

I think instead we can set a mark at frameheadpos when seek type is
SEEK_TAIL and RPR is enabled. See attached patch.

Thank you for the patch. Your approach is cleaner -- setting
the mark at frameheadpos is more direct than suppressing
advancement. I've adopted it in the updated 0005.
 
>   0006: Implement 1-slot PREV/NEXT navigation for RPR

Excellent! I will take a look at it. (it will take for a while).

No rush at all. In the meantime, while testing the PREV/NEXT
patch in various query patterns, I found a planner issue.
I've also added JIT support. Here is a summary of the new
patches:


  0006: Prevent removal of RPR window functions in unused
        subquery outputs

        Wrapping an RPR window query in a subquery with an
        outer aggregate causes a crash:

          SELECT count(*) FROM (
            SELECT count(*) OVER w FROM ...
            WINDOW w AS (... DEFINE A AS i > PREV(i))
          ) t;

        remove_unused_subquery_outputs() replaces unused subquery
        target entries with NULL constants. When an RPR window
        function's result is not referenced by the outer query,
        this replacement eliminates all active window functions
        for the WindowClause, causing the planner to omit the
        WindowAgg node. DEFINE clause expressions containing
        RPRNavExpr (PREV/NEXT) then lose their execution context,
        leading to a crash.

        The fix skips the NULL replacement for window functions
        whose WindowClause has a defineClause. Even when the
        window function result is unused, RPR pattern matching
        (frame reduction) must still execute -- the WindowAgg
        node must be preserved.

        An alternative would be to let the planner remove the
        window function but teach it to still generate the
        WindowAgg node when defineClause is present, even with
        no active window functions. That would be a more
        targeted optimization but requires deeper planner
        changes. Do you think the current approach is
        sufficient, or would you prefer a different strategy?


  0007: Implement 1-slot PREV/NEXT navigation for RPR
        (unchanged from previous 0006)
 
> 2. LLVM JIT fallback (in 0006): The mid-expression slot swap

I am not an expert of JIT, but for me, it sounds reasonable.  We can
enhance it later on.

  0008: Add JIT compilation support for RPR PREV/NEXT navigation

        EEOP_OUTER_VAR normally uses slot pointers cached in the
        entry block, but the mid-expression slot swap in
        NAV_SET/RESTORE invalidates them. To avoid penalizing
        existing expressions, the reload path is only generated
        when RPR navigation opcodes are present in the
        expression (compile-time decision). Expressions without
        PREV/NEXT produce identical machine code as before.
        NAV_SET/RESTORE use the standard build_EvalXFunc pattern.

        A 100K-row PREV/NEXT test case that runs under
        jit_above_cost=0 is included in rpr.sql.

I would appreciate your thoughts on these when you have time.


Best regards,
Henson
 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>   0006: Fix DEFINE expression handling in RPR window
>         planning (revised)
> 
>         Integration tests in 0007 revealed two crashes:
>         (1) subquery wrapping with outer aggregate causes
>         WindowAgg removal when RPR window function output
>         is unused, (2) RPR and non-RPR windows coexisting
>         causes SIGSEGV from RPRNavExpr propagating to the
>         wrong WindowAgg. This version extends the fix to
>         extract only Var nodes via pull_var_clause()
>         instead of adding the whole DEFINE expression to
>         the targetlist. The allpaths.c guard is extended
>         to also preserve columns referenced by DEFINE
>         clauses.

I took a look at this and have a question.

--- a/src/backend/optimizer/path/allpaths.c
+++ b/src/backend/optimizer/path/allpaths.c
@@ -4750,6 +4750,74 @@ remove_unused_subquery_outputs(Query *subquery, RelOptInfo *rel,
 		if (contain_volatile_functions(texpr))
 			continue;
 
+		/*
+		 * If any RPR window clause references this column in its DEFINE
+		 * clause, don't remove it.  The DEFINE expression needs these columns
+		 * in the tuplestore slot for pattern matching evaluation, even if the
+		 * outer query doesn't reference them.
+		 */

Before this, there's a check in the function:

		if (tle->ressortgroupref || tle->resjunk)
			continue;

Below is the query in the regression test that is suppoed to trigger
the error.  In this case column "i" in the target list should have
resjunk flag to be set to true. So I thought the if statenment above
becomes true and the column i is not removed from subquery's target
list. Am I missing something?

The test case in the patch:

-- Subquery wrapping: RPR window inside outer aggregate.
-- Tests that WindowAgg is not removed by remove_unused_subquery_outputs()
-- when DEFINE clause contains PREV/NEXT.
--
-- PREV in DEFINE + outer aggregate

--EXPLAIN
SELECT count(*) FROM (
  SELECT count(*) OVER w FROM generate_series(1,10) i
  WINDOW w AS (
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+)
    DEFINE A AS i > PREV(i)
  )
) t;

Also I think removal of the WindowAgg node is fine here because it's
not necessary to calculate the result of the sub query at
all. Actually the query above runs fine on v46. I guess some of the
incremental patches caused this to stop working. Can you elaborate?

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thank you for the careful review.

Before this, there's a check in the function:

                if (tle->ressortgroupref || tle->resjunk)
                        continue;

Below is the query in the regression test that is suppoed to trigger
the error.  In this case column "i" in the target list should have
resjunk flag to be set to true. So I thought the if statenment above
becomes true and the column i is not removed from subquery's target
list. Am I missing something? 

That is a very good observation. For the test query you cited, the
resjunk check does indeed protect column "i", as you noted.

The allpaths.c guard is needed for a different scenario: when a Var
already exists in the inner SELECT as a non-resjunk entry, but the
outer query does not reference it. For example:

  SELECT count(*) FROM (
    SELECT i, count(*) OVER w FROM generate_series(1,10) i
    --     ^ in SELECT -> resjunk=false
    WINDOW w AS (
      ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      PATTERN (A+)
      DEFINE A AS i > PREV(i)
    )
  ) t;
  -- outer uses only count(*) -> i is not in attrs_used

In this case, the Var addition logic in parse_rpr.c (pull_var_clause
+ dup check) finds that "i" already exists in the targetlist, so it
does not add a new resjunk entry. Since "i" is resjunk=false and the
outer query does not reference it, remove_unused_subquery_outputs()
would replace it with NULL, breaking DEFINE evaluation.

Changing the existing entry to resjunk=true is not an option either,
since it would alter the subquery's output schema -- the outer query
may reference that column, and at parse time we do not yet know
whether it will. The existing protection mechanisms (resjunk,
ressortgroupref, attrs_used, volatile check) cannot express
"referenced by DEFINE", since DEFINE is a new column reference path
that did not exist in PostgreSQL before. The allpaths.c guard
follows the same pattern as the existing SRF and volatile guards in
that function.

Also I think removal of the WindowAgg node is fine here because it's
not necessary to calculate the result of the sub query at
all. Actually the query above runs fine on v46. I guess some of the
incremental patches caused this to stop working. Can you elaborate?

I agree -- for this specific query, removing the WindowAgg does not
change the count(*) result, since window functions do not change the
number of rows.

Regarding v46: the two bugs were actually latent from the initial
implementation, not caused by incremental patches. The old code
added the entire DEFINE expression (e.g., "i > PREV(i)") to the
query targetlist via findTargetlistEntrySQL99(). In most cases,
DEFINE conditions involve comparison operators, so the resulting
OpExpr did not match existing Var entries in the targetlist, and a
new resjunk entry was created. This accidentally prevented removal.
(In fact, a bare boolean DEFINE such as "DEFINE A AS flag" would
have exhibited the same removal bug even in v46, since
findTargetlistEntrySQL99 would reuse the existing entry instead
of creating a new resjunk one -- confirming that the issue was
latent in the original implementation, not introduced by recent
patches.)

However, that same approach caused the SIGSEGV (Bug 1): when RPR
and non-RPR windows coexist, the non-RPR WindowAgg inherits
targetlist entries containing RPRNavExpr nodes that it cannot
evaluate.

The two bugs are two sides of the same coin -- the old approach
prevented removal but caused SIGSEGV. Switching to Var-only
addition fixed the SIGSEGV but required the allpaths.c guard to
prevent removal.

As for more precise optimization (allowing removal when all
WindowFuncs for an RPR clause are unused), it would require
structural changes to the loop in remove_unused_subquery_outputs(),
which currently evaluates entries individually. Since this function
runs for all subqueries, not just RPR, such a change would need
broader testing.

The patch addresses two distinct issues: the parse_rpr.c change
(Var-only addition) prevents RPRNavExpr from propagating to
non-RPR WindowAgg nodes, while the allpaths.c guard prevents
incorrect column removal. Since both are needed, the guard
cannot simply be reverted. Would it make sense to keep it as-is
for now, and explore the more precise optimization as a separate
follow-up patch?

Best regards,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Thank you for the careful review.
> 
> Before this, there's a check in the function:
>>
>>                 if (tle->ressortgroupref || tle->resjunk)
>>                         continue;
>>
>> Below is the query in the regression test that is suppoed to trigger
>> the error.  In this case column "i" in the target list should have
>> resjunk flag to be set to true. So I thought the if statenment above
>> becomes true and the column i is not removed from subquery's target
>> list. Am I missing something?
> 
> 
> That is a very good observation. For the test query you cited, the
> resjunk check does indeed protect column "i", as you noted.
> 
> The allpaths.c guard is needed for a different scenario: when a Var
> already exists in the inner SELECT as a non-resjunk entry, but the
> outer query does not reference it. For example:
> 
>   SELECT count(*) FROM (
>     SELECT i, count(*) OVER w FROM generate_series(1,10) i
>     --     ^ in SELECT -> resjunk=false
>     WINDOW w AS (
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       PATTERN (A+)
>       DEFINE A AS i > PREV(i)
>     )
>   ) t;
>   -- outer uses only count(*) -> i is not in attrs_used
> 
> In this case, the Var addition logic in parse_rpr.c (pull_var_clause
> + dup check) finds that "i" already exists in the targetlist, so it
> does not add a new resjunk entry. Since "i" is resjunk=false and the
> outer query does not reference it, remove_unused_subquery_outputs()
> would replace it with NULL, breaking DEFINE evaluation.
> 
> Changing the existing entry to resjunk=true is not an option either,
> since it would alter the subquery's output schema -- the outer query
> may reference that column, and at parse time we do not yet know
> whether it will. The existing protection mechanisms (resjunk,
> ressortgroupref, attrs_used, volatile check) cannot express
> "referenced by DEFINE", since DEFINE is a new column reference path
> that did not exist in PostgreSQL before. The allpaths.c guard
> follows the same pattern as the existing SRF and volatile guards in
> that function.
> 
> Also I think removal of the WindowAgg node is fine here because it's
>> not necessary to calculate the result of the sub query at
>> all. Actually the query above runs fine on v46. I guess some of the
>> incremental patches caused this to stop working. Can you elaborate?
>>
> 
> I agree -- for this specific query, removing the WindowAgg does not
> change the count(*) result, since window functions do not change the
> number of rows.
> 
> Regarding v46: the two bugs were actually latent from the initial
> implementation, not caused by incremental patches. The old code
> added the entire DEFINE expression (e.g., "i > PREV(i)") to the
> query targetlist via findTargetlistEntrySQL99(). In most cases,
> DEFINE conditions involve comparison operators, so the resulting
> OpExpr did not match existing Var entries in the targetlist, and a
> new resjunk entry was created. This accidentally prevented removal.
> (In fact, a bare boolean DEFINE such as "DEFINE A AS flag" would
> have exhibited the same removal bug even in v46, since
> findTargetlistEntrySQL99 would reuse the existing entry instead
> of creating a new resjunk one -- confirming that the issue was
> latent in the original implementation, not introduced by recent
> patches.)
> 
> However, that same approach caused the SIGSEGV (Bug 1): when RPR
> and non-RPR windows coexist, the non-RPR WindowAgg inherits
> targetlist entries containing RPRNavExpr nodes that it cannot
> evaluate.
> 
> The two bugs are two sides of the same coin -- the old approach
> prevented removal but caused SIGSEGV. Switching to Var-only
> addition fixed the SIGSEGV but required the allpaths.c guard to
> prevent removal.
> 
> As for more precise optimization (allowing removal when all
> WindowFuncs for an RPR clause are unused), it would require
> structural changes to the loop in remove_unused_subquery_outputs(),
> which currently evaluates entries individually. Since this function
> runs for all subqueries, not just RPR, such a change would need
> broader testing.
> 
> The patch addresses two distinct issues: the parse_rpr.c change
> (Var-only addition) prevents RPRNavExpr from propagating to
> non-RPR WindowAgg nodes, while the allpaths.c guard prevents
> incorrect column removal. Since both are needed, the guard
> cannot simply be reverted.

Thank you for the detailed explanation. That makes sense.

> Would it make sense to keep it as-is
> for now, and explore the more precise optimization as a separate
> follow-up patch?

I agree keep it as is. I think priority of "more precise optimization"
is low for now. We could explore when we have time. What do you think?

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

Hi Tatsuo,

When I started this work a little over three months ago, I had
no idea it would grow into what it is today. There is still
much to refine, but I would not have come this far without
your guidance and support along the way.

This series completes RPR navigation support, including
PREV/NEXT, FIRST/LAST, and compound navigation such as
PREV(FIRST(col)).

Attached are 31 incremental patches on top of v46 (replacing
the previous 15-patch set). Here is a summary of the changes
from the previous version:


  0001-0007: Unchanged from the previous set.

  0008: Replace reduced frame map with single match result
        (revised: int -> int64 type widening for
        row_is_in_reduced_frame() and related variables,
        cascading from 0025)

  0009: Add fixed-length group absorption for RPR
        (unchanged, design note [1])

  0010: Rename rpr_explain test views to descriptive
        names (unchanged)


  0011: Fix quote_identifier() for RPR pattern variable
        name deparse (new)

        Pattern variable names that match SQL keywords were
        not being quoted in pg_get_viewdef() output, causing
        the deparsed view to fail on re-parse.

  0012: Fix execRPR.o ordering in executor Makefile to
        match meson.build (new)

        Ensures consistent build file ordering between Make
        and Meson build systems.

  0013: Remove unused force_colno parameter from RPR
        deparse functions (new)

        Dead parameter cleanup in get_rpr_pattern() and
        get_rpr_define() in ruleutils.c.

  0014: Add CHECK_FOR_INTERRUPTS to RPR context cleanup
        and finalize loops (new)

        Extends interrupt checking to ExecRPRCleanupContexts()
        and ExecRPRFinalizeMatch() loops, complementing the
        earlier additions in 0002 and 0003.

  0015: Narrow variable scope in ExecInitWindowAgg DEFINE
        clause loop (new)

        Moves local variable declarations into their
        respective loop bodies for clarity.

  0016: Normalize RPR element flag macros to return bool
        (new)

        RPR_ELEM_IS_* macros now return bool instead of the
        raw bitmask value, consistent with PostgreSQL style.


  0017: Implement 1-slot PREV/NEXT navigation for RPR
        (was 0011, context changes from 0008 int64)

  0018: Add JIT compilation support for RPR PREV/NEXT
        (was 0012, unchanged)

  0019: Add tuplestore trim optimization for RPR PREV
        navigation (was 0013, context changes from 0008
        int64)

  0020: Update RPR code comments to reflect 1-slot
        navigation model (was 0014, context only)


  0021: Enable JIT compilation for PREV/NEXT navigation
        tests in RPR (new)

        Adds test coverage for JIT-compiled PREV/NEXT
        expressions under jit_above_cost=0, verifying
        that the slot reload path produces correct results.

  0022: Add 2-arg PREV/NEXT test for row pattern
        navigation with host variable (new)

        Tests the PREV(value, offset) form where offset
        is a host variable (prepared statement parameter),
        exercising the RPR_NAV_OFFSET_NEEDS_EVAL path.

  0023: Add Nav Mark Lookback to EXPLAIN and fix
        compute_nav_max_offset() (new)

        EXPLAIN now displays "Nav Mark Lookback: N" for
        RPR windows with PREV navigation, showing how
        many rows the tuplestore retains. Also fixes
        compute_nav_max_offset() to correctly handle
        non-constant offset expressions.


  0024: Implement FIRST/LAST and compound navigation
        for RPR (was 0015, completed)

        The previous WIP patch is now complete with:

        - Compound navigation: PREV(FIRST(col)),
          NEXT(LAST(col, N)), etc. per SQL standard 5.6.4.
          Flattened into a single RPRNavExpr node with
          two offset values (inner position + outer offset).

        - RPRNavOffsetKind enum replaces sentinel macros
          for offset classification (CONSTANT, NEEDS_EVAL,
          FIRST_BASED).

        - Per-context DEFINE re-evaluation for match_start-
          dependent expressions (FIRST, LAST with offset),
          tracked via defineMatchStartDependent bitmapset
          computed by the planner.

        - Tuplestore mark handling extended for FIRST-based
          navigation: mark position accounts for both
          backward reach (PREV) and forward-from-match-start
          reach (FIRST).

        - Documentation added to func-window.sgml.

        See the design note [2] for the absorption safety
        analysis and evaluation sharing rules.


  0025: Guard against int64 overflow in RPR bounded frame
        end computation (new)

        Widens frame position variables from int to int64
        in row_is_in_reduced_frame() and related functions.
        Prevents overflow when frame end position exceeds
        INT_MAX in large partitions.

  0026: Fix RPR error message style: hint format,
        terminology, capitalization (new)

        Aligns RPR error messages with PostgreSQL conventions:
        lowercase first word, consistent use of "row pattern"
        terminology, HINT format corrections.

  0027: Fix comment typos, grammar, and inaccuracies in
        RPR code (new)

        Comment-only changes across execRPR.c, parse_rpr.c,
        nodeWindowAgg.c, and ruleutils.c. No functional
        changes.

  0028: Fix RPR documentation: synopsis, grammar, and
        terminology (new)

        Updates select.sgml, advanced.sgml, and
        func-window.sgml for consistent terminology
        and corrected synopsis examples.

  0029: Fix nav_slot pass-by-ref dangling pointer in RPR
        navigation (new)

        When a DEFINE expression contains multiple navigation
        calls targeting different positions (e.g.,
        PREV(x,1) > PREV(x,2)), the second call re-fetches
        nav_slot, freeing the previous tuple via pfree. Any
        pass-by-ref datum extracted from the first navigation
        becomes a dangling pointer. Fix by copying pass-by-ref
        results into per-tuple memory in the RESTORE step.

  0030: Add inline comments for complex RPR algorithms and
        design notes (new)

        Adds explanatory comments to key algorithms in
        execRPR.c and rpr.c (planner). Covers NFA absorption
        logic, match evaluation flow, navigation mark
        computation, and DEFINE re-evaluation decisions.
        Comment-only changes, no functional changes.

  0031: Remove unused include and fix header ordering in RPR
        files (new)

        Removes an unnecessary include from execExprInterp.c,
        drops a redundant nodeWindowAgg.h include from
        nodeWindowAgg.c, and fixes header ordering in
        parse_rpr.c to match PostgreSQL convention.


Changes from the previous version:

  - 0015 (FIRST/LAST) is now complete as 0024, with compound
    navigation, RPRNavOffsetKind, defineMatchStartDependent,
    and full test coverage.

  - 16 new patches (0011-0016, 0021-0023, 0025-0031) added
    since the previous set. These are all quality improvements:
    bug fixes, safety guards, style normalization, comments,
    and test coverage.

  - New features: compound navigation in 0024 (was "not
    yet done" in previous set), Nav Mark Lookback in
    EXPLAIN output (0023). All other new patches are
    quality improvements.

I am planning to submit PREFIX pattern absorption [3]
as a separate patch after this set is committed. The
changes are confined to the Absorb phase with no
external dependencies, so it can be submitted
independently. The design itself has some complexity
(shadow path tracking), and I would like to refine it
further until I am fully confident in the approach.

With this set I have covered the features I could
foresee. Whether anything else belongs in scope is
your call. From here, I think the emphasis should
shift from adding features to raising overall
quality.
If there are directions you think should be explored,
I am happy to work on them. Otherwise, I plan to focus
on code review, test coverage, and stabilization, and
will continue to submit bug fixes and test additions
as I find them.

I also very much welcome refactoring or restructuring
suggestions from a committer's maintainability
perspective. If anything in the current code will be
painful to maintain long-term, I would much rather
address it now than leave it for after commit.

For stabilization, I am thinking of the same approach
as in early January: gcov analysis, Valgrind runs, and
expanding the test suite.

**WITH THE PLANNER**, the biggest risk is what we do
not know we are missing -- there are too many possible
feature interactions to enumerate up front. To surface
these, I plan to run RPR-only tests under gcov and
review the uncovered planner paths: any line that RPR
could plausibly reach but does not becomes a candidate
risk, and a candidate for a new test. That turns the
unknown into a concrete review list rather than a guess
about which interactions to try. Does that seem like a
good direction?

If anything comes to mind that should be added or
fixed -- at any time -- please let me know.

[1] Fixed-length group absorption design note
https://www.postgresql.org/message-id/CAAAe_zAKAGKpK9iHx3ZSuG59sP93r5dfootqv5tCfaMt%3Dw6wzA%40mail.gmail.com
[2] FIRST/LAST navigation design note
https://www.postgresql.org/message-id/CAAAe_zCUrKGBgZdaazdO_v9QWHsS_1DXuP%3DrLeNhO3iwsHwwbg%40mail.gmail.com
[3] PREFIX pattern absorption design note
https://www.postgresql.org/message-id/CAAAe_zDq7R8CaDfmh8C%2BH3_639Y5LtJD%2B2Z%3D1txDt%3DvaOr90rQ%40mail.gmail.com

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> When I started this work a little over three months ago, I had
> no idea it would grow into what it is today. There is still
> much to refine, but I would not have come this far without
> your guidance and support along the way.

I had no idea too :-) I was struggled with RPR develpment issues,
especially on an NFA engine and navigation operations (PREV/NEXT
etc.). You have solved both of the issues.

> This series completes RPR navigation support, including
> PREV/NEXT, FIRST/LAST, and compound navigation such as
> PREV(FIRST(col)).
> 
> Attached are 31 incremental patches on top of v46 (replacing
> the previous 15-patch set). Here is a summary of the changes
> from the previous version:
> 
> 
>   0001-0007: Unchanged from the previous set.

Here are the review for 0001-0007. I will continue to review rest of
the patches.

0001 was already reviewed (LGTM).
0002-0003 looks good to me.
0004 was already reviewed (LGTM).
0005 thanks for review.
0006

+		 * If it's a window function referencing a window clause with RPR (Row
+		 * Pattern Recognition), don't remove it.  Even when the window

As "RPR" already appears in the prevous comment block above, the "RPR"
appearing in the fist comment block should be "RPR (Row Pattern
Recognition)" and "RPR" here should be without "(Row Pattern
Recognition)".

0007:

diff --git a/src/test/regress/expected/rpr_integration.out b/src/test/regress/expected/rpr_integration.out
new file mode 100644
index 00000000000..a21ac5a8588
--- /dev/null
+++ b/src/test/regress/expected/rpr_integration.out
+-- Non-RPR: frame is optimized (RANGE -> ROWS conversion, etc.)
+-- RPR: frame must stay as specified (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)

For these 2 lines I feel a little bit hard to parse. Probably better
to be written as complete sentences, rather than bullet points. For
example,

+-- Non-RPR case: frame can be optimized (RANGE -> ROWS conversion, etc.)
+-- RPR case: frame must stay as specified (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)

Better to have a blanck line here for readability.

+-- Non-RPR window with default frame -> frame optimization applied

+-- ============================================================
+-- B1. RPR + CTE
+-- ============================================================
+-- CTE with RPR, outer query aggregates

Better to comment what we want to test (or expect).

+-- Multiple CTE references

Better to comment what we want to test (or expect).

+-- ============================================================
+-- B2. RPR + JOIN
+-- ============================================================

Better to comment what we want to test (or expect).

+-- ============================================================
+-- B3. RPR + Set operations
+-- ============================================================

Better to comment what we want to test (or expect).

+-- ============================================================
+-- B8. RPR + Incremental sort
+-- ============================================================
+-- Incremental sort may be used when data is partially sorted.
+CREATE INDEX rpr_integ_id_idx ON rpr_integ (id);
+SET enable_seqscan = off;
+EXPLAIN (COSTS OFF)
+SELECT id, val, count(*) OVER w AS cnt
+FROM rpr_integ
+WINDOW w AS (ORDER BY id
+    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+    PATTERN (A B+)
+    DEFINE B AS val > PREV(val));
+                                  QUERY PLAN                                   
+-------------------------------------------------------------------------------
+ WindowAgg
+   Window: w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
+   Pattern: a b+
+   ->  Index Scan using rpr_integ_id_idx on rpr_integ
+(4 rows)

No incremental sort in this plan?

+-- ============================================================
+-- B9. RPR + Volatile function in DEFINE
+-- ============================================================
+-- Volatile functions must be evaluated per-row, not optimized away.

Can you elaborate how the test below confirm random() is not optimized
away?

+SELECT id, val, count(*) OVER w AS cnt
+FROM rpr_integ
+WINDOW w AS (ORDER BY id
+    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
+    PATTERN (A B+)
+    DEFINE B AS val > PREV(val) AND random() >= 0.0)
+ORDER BY id;
+ id | val | cnt 
+----+-----+-----
+  1 |  10 |   2
+  2 |  20 |   0
+  3 |  15 |   2
+  4 |  25 |   0
+  5 |   5 |   3
+  6 |  30 |   0
+  7 |  35 |   0
+  8 |  20 |   3
+  9 |  40 |   0
+ 10 |  45 |   0
+(10 rows)

0008 and beyond will be reviewd in separate emails.

> I am planning to submit PREFIX pattern absorption [3]
> as a separate patch after this set is committed. The
> changes are confined to the Absorb phase with no
> external dependencies, so it can be submitted
> independently. The design itself has some complexity
> (shadow path tracking), and I would like to refine it
> further until I am fully confident in the approach.

Ok.

> With this set I have covered the features I could
> foresee. Whether anything else belongs in scope is
> your call. From here, I think the emphasis should
> shift from adding features to raising overall
> quality.

Agreed.

> If there are directions you think should be explored, I am happy to
> work on them. Otherwise, I plan to focus on code review, test
> coverage, and stabilization, and will continue to submit bug fixes
> and test additions as I find them.

One thing I want to discuss is, how to deal with the cases when
volatile functions are used in the DEFINE clause. As far as I know,
the SQL standard does not prohibit to use volatile functions there,
but we may need to prohibit to use it for our implementation reasons.

For reference, I studied how non RPR part in WindowAggs.c handles
volatile functions.

1. When searching for identical window functions, if they are volatile
functions, they are considered different window functions.

2. When evaluating the frame offset expression, it is evaluated only once
each time a scan/rescan occurs.

3. When checking whether moving aggregation is available, the
volatility of the window function is checked. If it is volatile,
moving aggregation is disabled.

> I also very much welcome refactoring or restructuring
> suggestions from a committer's maintainability
> perspective. If anything in the current code will be
> painful to maintain long-term, I would much rather
> address it now than leave it for after commit.

Ok, I will let you know when I find anything.

> For stabilization, I am thinking of the same approach
> as in early January: gcov analysis, Valgrind runs, and
> expanding the test suite.
> 
> **WITH THE PLANNER**, the biggest risk is what we do
> not know we are missing -- there are too many possible
> feature interactions to enumerate up front. To surface
> these, I plan to run RPR-only tests under gcov and
> review the uncovered planner paths: any line that RPR
> could plausibly reach but does not becomes a candidate
> risk, and a candidate for a new test. That turns the
> unknown into a concrete review list rather than a guess
> about which interactions to try. Does that seem like a
> good direction?

Sounds like a good direction.

> If anything comes to mind that should be added or
> fixed -- at any time -- please let me know.

Sure, I will.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Here is a review for 0008.

The patch does not apply using git apply.
$ git apply /usr/local/src/pgsql/RPR/make_rpr_patches/v47/input_patches/nocfbot-0008-Replace-reduced-frame-map-with-single-match-result.txt 
error: patch failed: src/backend/executor/nodeWindowAgg.c:247
error: src/backend/executor/nodeWindowAgg.c: patch does not apply
error: patch failed: src/include/nodes/execnodes.h:2694
error: src/include/nodes/execnodes.h: patch does not apply

I applied it using patch command.

$ patch -p1 < /usr/local/src/pgsql/RPR/make_rpr_patches/v47/input_patches/nocfbot-0008-Replace-reduced-frame-map-with-single-match-result.txt 
patching file src/backend/executor/execRPR.c
patching file src/backend/executor/nodeWindowAgg.c
Hunk #1 succeeded at 235 with fuzz 2 (offset -12 lines).
Hunk #2 succeeded at 1017 (offset -15 lines).
Hunk #3 succeeded at 1041 (offset -15 lines).
Hunk #4 succeeded at 1060 (offset -15 lines).
Hunk #5 succeeded at 1340 (offset 4 lines).
Hunk #6 succeeded at 1571 (offset 11 lines).
Hunk #7 succeeded at 2355 (offset 11 lines).
Hunk #8 succeeded at 2464 (offset 11 lines).
Hunk #9 succeeded at 2991 (offset 33 lines).
Hunk #10 succeeded at 3600 (offset -37 lines).
Hunk #11 succeeded at 3900 (offset -37 lines).
Hunk #12 succeeded at 3914 (offset -37 lines).
Hunk #13 succeeded at 3925 (offset -37 lines).
Hunk #14 succeeded at 3938 (offset -37 lines).
Hunk #15 succeeded at 3948 (offset -37 lines).
Hunk #16 succeeded at 4044 (offset -37 lines).
Hunk #17 succeeded at 4065 (offset -37 lines).
Hunk #18 succeeded at 4141 (offset -37 lines).
Hunk #19 succeeded at 4657 (offset -35 lines).
patching file src/include/nodes/execnodes.h
Hunk #2 succeeded at 2698 with fuzz 2 (offset 2 lines).
patching file src/test/regress/expected/rpr_explain.out

From: Henson Choi 
Subject: Re: Row pattern recognition
Date: Sun, 12 Apr 2026 16:27:26 +0900
Message-ID: 

> From 59e99c6b9322f402df560bc693863491487e12db Mon Sep 17 00:00:00 2001
> From: Henson Choi 
> Date: Thu, 2 Apr 2026 14:09:12 +0900
> Subject: [PATCH] Replace reduced frame map with single match result
> 
> The reduced frame map was a per-row byte array tracking match status.
> Since rows are processed sequentially and only one match is active
> at a time, replace it with four scalar fields: valid, matched,
> start, and length.

You are right, we don't need to have the map as an array.

> Also distinguish empty matches (FIN reached with zero rows consumed)
> from unmatched rows via RF_EMPTY_MATCH, counted as matched in NFA
> statistics.

Good enhancement.

> Widen row_is_in_reduced_frame() return type from int to int64,
> since it returns rpr_match_length which is int64.

Good point.

> ---
>  src/backend/executor/execRPR.c            |  56 +++---
>  src/backend/executor/nodeWindowAgg.c      | 233 +++++++++-------------
>  src/include/nodes/execnodes.h             |  21 +-
>  src/test/regress/expected/rpr_explain.out |   8 +-
>  4 files changed, 132 insertions(+), 186 deletions(-)
> 
> diff --git a/src/backend/executor/execRPR.c b/src/backend/executor/execRPR.c
> index 58f9da0b814..1cbe8e14780 100644
> --- a/src/backend/executor/execRPR.c
> +++ b/src/backend/executor/execRPR.c
> @@ -549,7 +549,7 @@
>   *
>   *   (1) Find or create a context for the target row
>   *   (2) Enter the row processing loop
> - *   (3) After the loop ends, record the result in reduced_frame_map
> + *   (3) After the loop ends, record the match result
>   *
>   * Pseudocode of the row processing loop:
>   *
> @@ -923,18 +923,19 @@
>   * Chapter X  Match Result Processing
>   * ============================================================================
>   *
> - * X-1. Reduced Frame Map
> + * X-1. Match Result
>   *
> - * RPR match results are recorded in a byte array called reduced_frame_map.
> - * One byte is allocated per row, and the value is one of the following:
> + * RPR tracks the current match result as a single entry in WindowAggState
> + * with four fields: rpr_match_valid, rpr_match_matched, rpr_match_start,
> + * and rpr_match_length.  When valid is true, the entry describes the

"When valid is true" sounds a little bit confusing for readers. I
think "When rpr_match_valid is true" is cleaner, although it adds more
characters. Same thing can be said to "matchded", "valid" and "length".

> + * match result for the position at rpr_match_start: matched indicates
> + * success or failure, and length gives the number of rows consumed.
> + * A match with length 0 represents an empty match (pattern matched but
> + * consumed no rows).  When valid is false, the position has not been
> + * evaluated yet (RF_NOT_DETERMINED).
>   *
> - *   RF_NOT_DETERMINED (0)  Not yet processed
> - *   RF_FRAME_HEAD     (1)  Start row of the match
> - *   RF_SKIPPED        (2)  Interior row of the match (skipped in frame)
> - *   RF_UNMATCHED      (3)  Match failure
> - *
> - * The window function references this map to determine frame inclusion for
> - * each row.
> + * The window function calls get_reduced_frame_status() to look up a
> + * row's status against the current match result.

This may be misleading since get_reduced_frame_status() is not an
exposed public API to a window function. What about something like
"Row's status against the current match result can be obtained by
calling get_reduced_frame_status()"?

In execRPR.c, documentation occupies 1445 lines out of 3052 lines. I
don't see any other .[ch] files, half of it is taken up by
documentation. I suggest to create something like "README.rpr" and
move the documentation part to it.

> diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
> index aed7cbef99a..dca2de570e8 100644
> --- a/src/backend/executor/nodeWindowAgg.c
> +++ b/src/backend/executor/nodeWindowAgg.c

No comment to nodeWindowAgg.c patch. This part looks good to me.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

Note that applying 0001-0006 produced compiler warning.

execExprInterp.c: In function ‘ExecEvalRPRNavSet’:
execExprInterp.c:6005:23: warning: ‘target_pos’ may be used uninitialized [-Wmaybe-uninitialized]
 6005 |         target_slot = ExecRPRNavGetSlot(winstate, target_pos);
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
execExprInterp.c:5959:25: note: ‘target_pos’ was declared here
 5959 |         int64           target_pos;
      |                         ^~~~~~~~~~

But regression test was ok.
However, after applying 0007, regression test failed.

not ok 196   + rpr_integration                           514 ms
# (test process exited with exit code 2)
# parallel group (9 tests):  jsonpath jsonpath_encoding jsonb_jsonpath sqljson_queryfuncs json_encoding json sqljson_jsontable jsonb sqljson
not ok 197   + json                                       29 ms
# (test process exited with exit code 2)
not ok 198   + jsonb                                      29 ms
# (test process exited with exit code 2)
[snip]

From rpr_integration.out:

-- Verify both produce different results
SELECT
    id, val,
    count(*) OVER w_rpr AS rpr_cnt,
    count(*) OVER w_normal AS normal_cnt
FROM rpr_integ
WINDOW
    w_rpr AS (ORDER BY id
        ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
        PATTERN (A B+)
        DEFINE B AS val > PREV(val)),
    w_normal AS (ORDER BY id
        ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
ORDER BY id;
server closed the connection unexpectedly
	This probably means the server terminated abnormally
	before or while processing the request.
connection to server was lost

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thank you for the feedback.

Note that applying 0001-0006 produced compiler warning.

execExprInterp.c: In function ‘ExecEvalRPRNavSet’:
execExprInterp.c:6005:23: warning: ‘target_pos’ may be used uninitialized [-Wmaybe-uninitialized]
 6005 |         target_slot = ExecRPRNavGetSlot(winstate, target_pos);
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
execExprInterp.c:5959:25: note: ‘target_pos’ was declared here
 5959 |         int64           target_pos;
      |                         ^~~~~~~~~~
 
`ExecRPRNavGetSlot()`, along with the enclosing `ExecEvalRPRNavSet()`
and its `int64 target_pos` declaration, is introduced by nocfbot-0017
(Implement 1-slot PREV/NEXT navigation for RPR), not at the 0001-0006
level.  Could you double-check the actual applied range on your side?
The function simply does not exist at 0001-0006.

Since the function is not present at 0001-0006, I suspect the
applied patch set on your side is in a different state than
expected.  Could you verify the range and contents of the patches
actually applied?

But regression test was ok.
However, after applying 0007, regression test failed.

not ok 196   + rpr_integration                           514 ms
# (test process exited with exit code 2)

nocfbot-0006 was written specifically to prevent the crashes that
0007's tests expose, so with 0001-0007 applied in order the issue
should already be resolved.  On my authoritative base (cfbot/4460) all
rpr_integration tests pass through 0008.  I had been routinely
building only on macOS ARM64 recently, so I just re-verified on
Rocky 9 and Ubuntu 24 AMD64 as well; no build warning and no
rpr_integration failure on either.

For reference, here is my working tree layout.  Titles only for my
post-base commits (hashes on my side won't match yours); base
hashes are public and directly comparable on your side:

  [post-base, newest first]
   31. Remove unused include and fix header ordering in RPR files   (origin/RPR)
   30. Add inline comments for complex RPR algorithms and design notes
   29. Fix nav_slot pass-by-ref dangling pointer in RPR navigation
   28. Fix RPR documentation: synopsis, grammar, and terminology
   27. Fix comment typos, grammar, and inaccuracies in RPR code
   26. Fix RPR error message style: hint format, terminology, capitalization
   25. Guard against int64 overflow in RPR bounded frame end computation
   24. Implement FIRST/LAST and compound navigation for RPR
   23. Add Nav Mark Lookback to EXPLAIN and fix compute_nav_max_offset()
   22. Add 2-arg PREV/NEXT test for row pattern navigation with host variable
   21. Enable JIT compilation for PREV/NEXT navigation tests in RPR
   20. Update RPR code comments to reflect 1-slot navigation model
   19. Add tuplestore trim optimization for RPR PREV navigation
   18. Add JIT compilation support for RPR PREV/NEXT navigation
   17. Implement 1-slot PREV/NEXT navigation for RPR
   16. Normalize RPR element flag macros to return bool
   15. Narrow variable scope in ExecInitWindowAgg DEFINE clause loop
   14. Add CHECK_FOR_INTERRUPTS to RPR context cleanup and finalize loops
   13. Remove unused force_colno parameter from RPR deparse functions
   12. Fix execRPR.o ordering in executor Makefile to match meson.build
   11. Fix quote_identifier() for RPR pattern variable name deparse
   10. Rename rpr_explain test views from sequential numbers to descriptive names
    9. Add fixed-length group absorption for RPR
    8. Replace reduced frame map with single match result
    7. Add RPR planner integration tests
    6. Fix DEFINE expression handling in RPR window planning
    5. Fix mark handling for last_value() under RPR
    4. Fix in-place modification of defineClause TargetEntry in setrefs.c
    3. Add CHECK_FOR_INTERRUPTS() to nfa_try_absorb_context() loop
    2. Add CHECK_FOR_INTERRUPTS() to nfa_add_state_unique() for state explosion patterns
    1. Remove unused regex/regex.h include from nodeWindowAgg.c

  [base, public hashes]
  732acf9b7c6 (cfbot/cf/4460) [CF 4460] v46 - Implement row pattern recognition feature
  6eb8841afaf Row pattern recognition patch (typedefs.list).
  5213dbb3c4f Row pattern recognition patch (tests: expected).
  bdc3a17982b Row pattern recognition patch (tests: SQL, data).
  596bcc434b5 Row pattern recognition patch (docs).
  e02872fd59c Row pattern recognition patch (executor and commands).
  742c6eb673e Row pattern recognition patch (planner).
  8514ca64f2d Row pattern recognition patch (rewriter).
  d26741d4f1d Row pattern recognition patch (parse/analysis).
  f85d2ee8f4a Row pattern recognition patch for raw parser.
  e484b0eea61 (origin/RPR-base, RPR-base) Fix two issues in fast-path FK check introduced by commit 2da86c1ef9

Could you send me the equivalent `git log` for your working tree
covering the full v46 application and the commit immediately
preceding it?  In particular, could you also check whether the
recent master commit titled "Fix integer overflow in
nodeWindowAgg.c" (backpatched to 14) is included in your base?  It
touches the same ROWS/GROUPS frame boundary code path that RPR
interacts with, so its presence or absence will help narrow things
down.  Once I can match the same base locally, I will reproduce and
include the fix in the next revision.

A quick status update:

  - nocfbot-0006: self-review complete, not yet sent (comment tweak per review)
  - nocfbot-0007: under self-review (comment details per review)
  - nocfbot-0008: in progress

I would like to resolve the crash first before sending the next
revision, so that the full set goes out together once our bases are
aligned and A3 passes on your side.

One process question: so far I have been folding review feedback
into the relevant existing patches (i.e. amending nocfbot-0008 to
reflect your comments on it).  Would you prefer that I instead
append the review fixes as new patches at the end of the series
(e.g. nocfbot-0032, 0033, ...), so the history of reviewed changes
stays visible?  Happy to follow whichever workflow you find easier
to review.

Regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo,
> 
> Thank you for the feedback.
> 
> Note that applying 0001-0006 produced compiler warning.
>>
>> execExprInterp.c: In function ‘ExecEvalRPRNavSet’:
>> execExprInterp.c:6005:23: warning: ‘target_pos’ may be used uninitialized
>> [-Wmaybe-uninitialized]
>>  6005 |         target_slot = ExecRPRNavGetSlot(winstate, target_pos);
>>       |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>> execExprInterp.c:5959:25: note: ‘target_pos’ was declared here
>>  5959 |         int64           target_pos;
>>       |                         ^~~~~~~~~~
>>
> 
> `ExecRPRNavGetSlot()`, along with the enclosing `ExecEvalRPRNavSet()`
> and its `int64 target_pos` declaration, is introduced by nocfbot-0017
> (Implement 1-slot PREV/NEXT navigation for RPR), not at the 0001-0006
> level.  Could you double-check the actual applied range on your side?
> The function simply does not exist at 0001-0006.
> 
> Since the function is not present at 0001-0006, I suspect the
> applied patch set on your side is in a different state than
> expected.  Could you verify the range and contents of the patches
> actually applied?

> But regression test was ok.
>> However, after applying 0007, regression test failed.
>>
>> not ok 196   + rpr_integration                           514 ms
>> # (test process exited with exit code 2)
>>
> 
> nocfbot-0006 was written specifically to prevent the crashes that
> 0007's tests expose, so with 0001-0007 applied in order the issue
> should already be resolved.  On my authoritative base (cfbot/4460) all
> rpr_integration tests pass through 0008.  I had been routinely
> building only on macOS ARM64 recently, so I just re-verified on
> Rocky 9 and Ubuntu 24 AMD64 as well; no build warning and no
> rpr_integration failure on either.

You are right. I checked and found the 0006 patch I applied was wrong
one.

nocfbot-0006-Implement-1-slot-PREV-NEXT-navigation-for-RPR.txt:

This should have been:
nocfbot-0006-Fix-DEFINE-expression-handling-RPR-window-planning.txt

Sorry for confusion.

> For reference, here is my working tree layout.  Titles only for my
> post-base commits (hashes on my side won't match yours); base
> hashes are public and directly comparable on your side:
> 
>   [post-base, newest first]
>    31. Remove unused include and fix header ordering in RPR files
> (origin/RPR)
>    30. Add inline comments for complex RPR algorithms and design notes
>    29. Fix nav_slot pass-by-ref dangling pointer in RPR navigation
>    28. Fix RPR documentation: synopsis, grammar, and terminology
>    27. Fix comment typos, grammar, and inaccuracies in RPR code
>    26. Fix RPR error message style: hint format, terminology, capitalization
>    25. Guard against int64 overflow in RPR bounded frame end computation
>    24. Implement FIRST/LAST and compound navigation for RPR
>    23. Add Nav Mark Lookback to EXPLAIN and fix compute_nav_max_offset()
>    22. Add 2-arg PREV/NEXT test for row pattern navigation with host
> variable
>    21. Enable JIT compilation for PREV/NEXT navigation tests in RPR
>    20. Update RPR code comments to reflect 1-slot navigation model
>    19. Add tuplestore trim optimization for RPR PREV navigation
>    18. Add JIT compilation support for RPR PREV/NEXT navigation
>    17. Implement 1-slot PREV/NEXT navigation for RPR
>    16. Normalize RPR element flag macros to return bool
>    15. Narrow variable scope in ExecInitWindowAgg DEFINE clause loop
>    14. Add CHECK_FOR_INTERRUPTS to RPR context cleanup and finalize loops
>    13. Remove unused force_colno parameter from RPR deparse functions
>    12. Fix execRPR.o ordering in executor Makefile to match meson.build
>    11. Fix quote_identifier() for RPR pattern variable name deparse
>    10. Rename rpr_explain test views from sequential numbers to descriptive
> names
>     9. Add fixed-length group absorption for RPR
>     8. Replace reduced frame map with single match result
>     7. Add RPR planner integration tests
>     6. Fix DEFINE expression handling in RPR window planning
>     5. Fix mark handling for last_value() under RPR
>     4. Fix in-place modification of defineClause TargetEntry in setrefs.c
>     3. Add CHECK_FOR_INTERRUPTS() to nfa_try_absorb_context() loop
>     2. Add CHECK_FOR_INTERRUPTS() to nfa_add_state_unique() for state
> explosion patterns
>     1. Remove unused regex/regex.h include from nodeWindowAgg.c
> 
>   [base, public hashes]
>   732acf9b7c6 (cfbot/cf/4460) [CF 4460] v46 - Implement row pattern
> recognition feature
>   6eb8841afaf Row pattern recognition patch (typedefs.list).
>   5213dbb3c4f Row pattern recognition patch (tests: expected).
>   bdc3a17982b Row pattern recognition patch (tests: SQL, data).
>   596bcc434b5 Row pattern recognition patch (docs).
>   e02872fd59c Row pattern recognition patch (executor and commands).
>   742c6eb673e Row pattern recognition patch (planner).
>   8514ca64f2d Row pattern recognition patch (rewriter).
>   d26741d4f1d Row pattern recognition patch (parse/analysis).
>   f85d2ee8f4a Row pattern recognition patch for raw parser.
>   e484b0eea61 (origin/RPR-base, RPR-base) Fix two issues in fast-path FK
> check introduced by commit 2da86c1ef9
> 
> Could you send me the equivalent `git log` for your working tree
> covering the full v46 application and the commit immediately
> preceding it?

Here it is:

t-ishii$ git log --oneline -10|cat
6dd0765463a Row pattern recognition patch (typedefs.list).
009b38f4d2b Row pattern recognition patch (tests: expected).
07864e40e36 Row pattern recognition patch (tests: SQL, data).
55b467849eb Row pattern recognition patch (docs).
28a1ff7e744 Row pattern recognition patch (executor and commands).
728b1fdf106 Row pattern recognition patch (planner).
c388e3e7eb0 Row pattern recognition patch (rewriter).
232725a3e95 Row pattern recognition patch (parse/analysis).
c71940f9e21 Row pattern recognition patch for raw parser.
322bab79744 Move declarations related to locktags from lock.h to new locktag.h

> In particular, could you also check whether the
> recent master commit titled "Fix integer overflow in
> nodeWindowAgg.c" (backpatched to 14) is included in your base?  It
> touches the same ROWS/GROUPS frame boundary code path that RPR
> interacts with, so its presence or absence will help narrow things
> down.  Once I can match the same base locally, I will reproduce and
> include the fix in the next revision.

No, the commit is not in my working tree.

So I guess I should have rebased v46 tree so that the commit is in the
work tree before applying your patches. Am I correct?

> A quick status update:
> 
>   - nocfbot-0006: self-review complete, not yet sent (comment tweak per
> review)
>   - nocfbot-0007: under self-review (comment details per review)
>   - nocfbot-0008: in progress
> 
> I would like to resolve the crash first before sending the next
> revision, so that the full set goes out together once our bases are
> aligned and A3 passes on your side.

Let me check the crash first. Since apparently the crash was caused by
my mis operation.

> One process question: so far I have been folding review feedback
> into the relevant existing patches (i.e. amending nocfbot-0008 to
> reflect your comments on it).

I prefer this way.

> Would you prefer that I instead
> append the review fixes as new patches at the end of the series
> (e.g. nocfbot-0032, 0033, ...), so the history of reviewed changes
> stays visible?  Happy to follow whichever workflow you find easier
> to review.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

You are right. I checked and found the 0006 patch I applied was wrong
one.

Sorry for confusion.

No worries. Having 31 patches in the series is bound to cause
confusion — that is on me for sending such a large set at once.

t-ishii$ git log --oneline -10|cat
6dd0765463a Row pattern recognition patch (typedefs.list).
c71940f9e21 Row pattern recognition patch for raw parser.
322bab79744 Move declarations related to locktags from lock.h to new locktag.h

Thank you for the log. I can see that your base is the original v46
application, while mine is the cfbot rebase from April 1
(732acf9b7c6).

No, the commit is not in my working tree.

So I guess I should have rebased v46 tree so that the commit is in the
work tree before applying your patches. Am I correct?

Since the root cause was the patch file mix-up, a rebase would not
have been necessary in this case. That said, the related fix that
went into master ("Fix integer overflow in nodeWindowAgg.c") touches
the same file as several of my patches, so it may cause conflicts
when applying v47. Please let me know if anything is difficult to
resolve. 

Let me check the crash first. Since apparently the crash was caused by
my mis operation.

Once confirmed, I will send the corrected patches first.

Regarding the README.rpr suggestion from the 0008 review: the
documentation in execRPR.c has dependencies spread across the patch
series, so separating it mid-review would be disruptive. I plan to
split it out as part of the final patch list once all 31 patches have
been reviewed.

I prefer this way.

Good — I will continue folding review feedback into the relevant
existing patches. Patch numbers and subjects will stay stable across
revisions.

Regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
>> So I guess I should have rebased v46 tree so that the commit is in the
>> work tree before applying your patches. Am I correct?
>>
> 
> Since the root cause was the patch file mix-up, a rebase would not
> have been necessary in this case. That said, the related fix that
> went into master ("Fix integer overflow in nodeWindowAgg.c") touches
> the same file as several of my patches, so it may cause conflicts
> when applying v47. Please let me know if anything is difficult to
> resolve.

Ok, I will not rebase current v46 and continue to apply your
incremental patches and review them, until we agree to ship v47.  I
may see conflicts while creating v47 patch sets. I will ask help if if
your assistance needed. Thanks in advance.

> Let me check the crash first. Since apparently the crash was caused by
>> my mis operation.
>>
> 
> Once confirmed, I will send the corrected patches first.

I confirmed 0001-0008 applied cleanly and see no compile
warning. Regression test passed, no crash.

> Regarding the README.rpr suggestion from the 0008 review: the
> documentation in execRPR.c has dependencies spread across the patch
> series, so separating it mid-review would be disruptive. I plan to
> split it out as part of the final patch list once all 31 patches have
> been reviewed.

Ok.

> I prefer this way.
> 
> 
> Good ― I will continue folding review feedback into the relevant
> existing patches. Patch numbers and subjects will stay stable across
> revisions.

Looking forward to seeing revised incremental patch sets.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

 Hi Tatsuo,

Thank you for the careful review and for confirming the build on
your side.

Ok, I will not rebase current v46 and continue to apply your
incremental patches and review them, until we agree to ship v47.  I
may see conflicts while creating v47 patch sets. I will ask help if if
your assistance needed. Thanks in advance.

Understood.  Please let me know whenever a conflict comes up while
assembling v47 and I will help resolve it on my side.
 
I confirmed 0001-0008 applied cleanly and see no compile
warning. Regression test passed, no crash.

Thank you for confirming.
 
> Regarding the README.rpr suggestion from the 0008 review: the
> documentation in execRPR.c has dependencies spread across the patch
> series, so separating it mid-review would be disruptive. I plan to
> split it out as part of the final patch list once all 31 patches have
> been reviewed.

Ok.

Thank you.  I will prepare the README.rpr split as a follow-up patch
after the current 0031 once the series review is complete.

Looking forward to seeing revised incremental patch sets.

Attached is the revised v47 series, with the review comments on
0006, 0007, and 0008 incorporated.  Numbering and subjects are
unchanged from the previous send.

Since the edits in 0006-0008 propagate into the later patches --
mostly as context-line shifts, and in 0017/0023 as updates to the
rpr_integration expected output -- I have attached the full
0001-0031 set rather than only the updated patches.  Applying this
set on top of v46 should give the same final tree as before, just
with the review adjustments folded in.

Summary of changes from the previous v47:

  - 0006 (Fix DEFINE expression handling): per your comment, the
    first occurrence of "RPR" now carries the "(Row Pattern
    Recognition)" expansion and the later occurrence is the bare
    abbreviation.

  - 0007 (Add RPR planner integration tests): overall
    strengthening of the tests and their comments.  Each block
    now carries an intent comment describing what the block is
    trying to cover and what the expected plan or result is,
    the "Non-RPR / RPR" comment pair is reworded as complete
    sentences, and B8 is reworked so that the EXPLAIN plan
    actually exercises Incremental Sort.

    Because some blocks cover features that are only
    introduced later in the series, a few tests in 0007
    temporarily produce error output.  Concretely, B4
    (RPR + prepared statements) uses the 2-argument form
    PREV(val, $1), which is not yet available at the 0007
    point: it is introduced in 0017 (1-slot PREV/NEXT
    navigation), and the accompanying "Nav Mark Lookback"
    EXPLAIN property referenced in the B4 comments is added
    in 0023.  The rpr_integration expected-output file is
    updated by 0017 (to clear the PREV/prepared-statement
    errors) and then again by 0023 (to add the
    "Nav Mark Lookback" lines to the EXPLAIN output), so that
    by the end of the series the output is clean.

    XXX notes have been added in three places where a test
    records behaviour that may be revisited later:

      (1) The subquery-output test documents why the column
          guard in allpaths.c has to be conservative: a column
          referenced only by DEFINE is indistinguishable from
          an exposed column at the targetlist level, so
          remove_unused_subquery_outputs() cannot apply its
          NULL-replacement selectively without risking DEFINE
          evaluation on NULL inputs.  The XXX flags this as a
          candidate for a precise follow-up optimization.

      (2) The B7 Recursive CTE test carries an XXX noting that
          it is unclear whether this case falls under the
          ISO/IEC 9075-2 4.18.5 / 6.17.5 prohibition, and even
          if it does not, whether a query that does trigger
          the prohibition can be constructed at all.  The
          disposition is left to the community.

      (3) The B9 volatile-in-DEFINE test records current
          behaviour using "random() >= 0.0" (structurally
          equivalent to TRUE, so the expected output stays
          deterministic).  The XXX flags that if we decide to
          reject volatile functions in DEFINE, this test must
          be converted into an error-case test.  See the
          dedicated section at the end of this mail.

  - 0008 (Replace reduced frame map with single match result):
      * Comment block X-1 now uses the full field names
        rpr_match_valid / rpr_match_matched / rpr_match_length.
      * get_reduced_frame_status() sentence rephrased in the
        passive voice, as you suggested:
          "Row's status against the current match result can be
           obtained by calling get_reduced_frame_status()."
      * README.rpr split deferred per the above.

  - 0009-0031: no semantic code changes.  Most patches only
    carry context-line shifts from the edits above.  The two
    exceptions are 0017 and 0023, whose rpr_integration.out
    hunks are updated to match the revised B4 test in 0007
    (clearing the temporary errors and adding the
    "Nav Mark Lookback" lines, respectively).

On volatile functions in DEFINE (your 2026-04-13 mail): the SQL
standard itself is relatively narrow here -- the only explicit
restriction it places is that a navigation function's offset must
be a runtime constant.  Volatile expressions in the DEFINE
predicate are not forbidden by the standard.

That said, once we move into the pattern-matching machinery, the
observable semantics of a volatile DEFINE become quite murky.
Depending on the situation, the DEFINE predicate may be evaluated
once per row, or separately per active matching context, or some
combination of both as the NFA explores alternatives.  A user
writing "random() > 0.5" in DEFINE would have a hard time
predicting, let alone relying on, the evaluation count -- and I
have not been able to think of a realistic use case that actually
benefits from this flexibility.

Given the gap between "permitted by the standard" and "meaningful
to the user," my own leaning is toward prohibiting volatile
functions in DEFINE at transformation time, and -- if we go that
way -- also examining whether the new check would make the
existing runtime-constant check on the navigation-function offset
redundant, or whether the two could be folded into a single check
pass.  That said, this is ultimately a policy call, and I would rather defer
the final decision to your judgment as a senior member of the
community: does prohibition seem like the right direction, or
would you prefer to keep the current behaviour in place?

On sequencing, if we do take it up, I would suggest handling it
after the 31-patch set, alongside the README.rpr split as
follow-up work on top of 0031.  Whether it ultimately lands
inside v47 or as a separate piece on top does not need to be
decided right now -- there is still room to discuss it as the
review progresses, and I am happy to adjust either way based on
your direction.

Regards,
Henson
 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
[Chao Li  is added to Cc: I accidentally
forgot to add him. Sorry, Chao.]

Hi Henson,

I looked through 0001-0031 patches.

>  Hi Tatsuo,
> 
> Thank you for the careful review and for confirming the build on
> your side.
> 
> Ok, I will not rebase current v46 and continue to apply your
>> incremental patches and review them, until we agree to ship v47.  I
>> may see conflicts while creating v47 patch sets. I will ask help if if
>> your assistance needed. Thanks in advance.
>>
> 
> Understood.  Please let me know whenever a conflict comes up while
> assembling v47 and I will help resolve it on my side.
> 
> 
>> I confirmed 0001-0008 applied cleanly and see no compile
>> warning. Regression test passed, no crash.
>>
> 
> Thank you for confirming.
> 
> 
>> > Regarding the README.rpr suggestion from the 0008 review: the
>> > documentation in execRPR.c has dependencies spread across the patch
>> > series, so separating it mid-review would be disruptive. I plan to
>> > split it out as part of the final patch list once all 31 patches have
>> > been reviewed.
>>
>> Ok.
> 
> 
> Thank you.  I will prepare the README.rpr split as a follow-up patch
> after the current 0031 once the series review is complete.
> 
> Looking forward to seeing revised incremental patch sets.
> 
> 
> Attached is the revised v47 series, with the review comments on
> 0006, 0007, and 0008 incorporated.  Numbering and subjects are
> unchanged from the previous send.

0001 was already reviewed (LGTM).
0002-0003 looks good to me.
0004 was already reviewed (LGTM).
0005 thanks for review.

> Since the edits in 0006-0008 propagate into the later patches --
> mostly as context-line shifts, and in 0017/0023 as updates to the
> rpr_integration expected output -- I have attached the full
> 0001-0031 set rather than only the updated patches.  Applying this
> set on top of v46 should give the same final tree as before, just
> with the review adjustments folded in.

Thank you for taking care of my request.

> Summary of changes from the previous v47:
> 
>   - 0006 (Fix DEFINE expression handling): per your comment, the
>     first occurrence of "RPR" now carries the "(Row Pattern
>     Recognition)" expansion and the later occurrence is the bare
>     abbreviation.

Confirmed. 0006 Looks good to me.

>   - 0007 (Add RPR planner integration tests): overall
>     strengthening of the tests and their comments.  Each block
>     now carries an intent comment describing what the block is
>     trying to cover and what the expected plan or result is,
>     the "Non-RPR / RPR" comment pair is reworded as complete
>     sentences, and B8 is reworked so that the EXPLAIN plan
>     actually exercises Incremental Sort.
> 
>     Because some blocks cover features that are only
>     introduced later in the series, a few tests in 0007
>     temporarily produce error output.  Concretely, B4
>     (RPR + prepared statements) uses the 2-argument form
>     PREV(val, $1), which is not yet available at the 0007
>     point: it is introduced in 0017 (1-slot PREV/NEXT
>     navigation), and the accompanying "Nav Mark Lookback"
>     EXPLAIN property referenced in the B4 comments is added
>     in 0023.  The rpr_integration expected-output file is
>     updated by 0017 (to clear the PREV/prepared-statement
>     errors) and then again by 0023 (to add the
>     "Nav Mark Lookback" lines to the EXPLAIN output), so that
>     by the end of the series the output is clean.
> 
>     XXX notes have been added in three places where a test
>     records behaviour that may be revisited later:
> 
>       (1) The subquery-output test documents why the column
>           guard in allpaths.c has to be conservative: a column
>           referenced only by DEFINE is indistinguishable from
>           an exposed column at the targetlist level, so
>           remove_unused_subquery_outputs() cannot apply its
>           NULL-replacement selectively without risking DEFINE
>           evaluation on NULL inputs.  The XXX flags this as a
>           candidate for a precise follow-up optimization.
> 
>       (2) The B7 Recursive CTE test carries an XXX noting that
>           it is unclear whether this case falls under the
>           ISO/IEC 9075-2 4.18.5 / 6.17.5 prohibition, and even
>           if it does not, whether a query that does trigger
>           the prohibition can be constructed at all.  The
>           disposition is left to the community.

Ok, let's discuss on this later on.

>       (3) The B9 volatile-in-DEFINE test records current
>           behaviour using "random() >= 0.0" (structurally
>           equivalent to TRUE, so the expected output stays
>           deterministic).  The XXX flags that if we decide to
>           reject volatile functions in DEFINE, this test must
>           be converted into an error-case test.  See the
>           dedicated section at the end of this mail.

Ok.

Comment to A1:

+-- A1. Frame optimization bypass
:
:
+-- Non-RPR window with default frame -> frame optimization applied
+EXPLAIN (COSTS OFF)
+SELECT count(*) OVER w FROM rpr_integ
+WINDOW w AS (ORDER BY id);
+            QUERY PLAN             
+-----------------------------------
+ WindowAgg
+   Window: w AS (ORDER BY id)
+   ->  Sort
+         Sort Key: id
+         ->  Seq Scan on rpr_integ
+(5 rows)

The comment says frame optimization applied. But I don't see any frame
option changes (see how the first query changes the frame options).

I thought a frame optimization is something like this.
EXPLAIN(COSTS OFF)
SELECT row_number() OVER W FROM generate_series(1,5) s(i)
WINDOW w AS (
       ORDER BY i
       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
);
                      QUERY PLAN                      
------------------------------------------------------
 WindowAgg
   Window: w AS (ORDER BY i ROWS UNBOUNDED PRECEDING)
   ->  Sort
         Sort Key: i
         ->  Function Scan on generate_series s
(5 rows)

EXPLAIN(COSTS OFF)
SELECT row_number() OVER W FROM generate_series(1,5) s(i)
WINDOW w AS (
       ORDER BY i
       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
       PATTERN (A+)
       DEFINE A AS i > 2
);
                                  QUERY PLAN                                  
------------------------------------------------------------------------------
 WindowAgg
   Window: w AS (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
   Pattern: a+"
   Nav Mark Lookback: 0
   ->  Sort
         Sort Key: i
         ->  Function Scan on generate_series s
(7 rows)

>   - 0008 (Replace reduced frame map with single match result):
>       * Comment block X-1 now uses the full field names
>         rpr_match_valid / rpr_match_matched / rpr_match_length.
>       * get_reduced_frame_status() sentence rephrased in the
>         passive voice, as you suggested:
>           "Row's status against the current match result can be
>            obtained by calling get_reduced_frame_status()."
>       * README.rpr split deferred per the above.

Thanks for the new patch. 0008 looks good to me.

>   - 0009-0031: no semantic code changes.  Most patches only
>     carry context-line shifts from the edits above.  The two
>     exceptions are 0017 and 0023, whose rpr_integration.out
>     hunks are updated to match the revised B4 test in 0007
>     (clearing the temporary errors and adding the
>     "Nav Mark Lookback" lines, respectively).

Comment to 0009:

+	/* Mark VAR in visited before duplicate check to prevent DFS loops */
+	winstate->nfaVisitedElems[WORDNUM(state->elemIdx)] |=
+		((bitmapword) 1 << BITNUM(state->elemIdx));

Why do not use bms here? Maybe winstate->nfaVisitedElems could become
quite big?

0010-0016 look good to me.

Comment to 0017:
+
+/*
+ * check_rpr_nav_expr
+ *		Validate a single RPRNavExpr node by walking its arg and offset_arg
+ *		subtrees in a single pass each.  Checks for nested PREV/NEXT, missing
+ *		column references, and non-constant offset expressions.
+ */

"Checks for" --> "Check for" (no "s").

+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("PREV and NEXT cannot be nested"),
+				 parser_errposition(pstate, nav->location)));

 errmsg("PREV and NEXT cannot be nested") ->
 errmsg("cannot nest PREV and NEXT") (avoid passive voice in error messages)

+	ereport(ERROR,
+			(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+			 errmsg("next() can only be used in a DEFINE clause")));

errmsg("next() can only be used in a DEFINE clause") ->
errmsg("cannot use next() other than in a DEFINE clause")

The same reason above. There are some places where similar changing
necessary.

+		if (offset > maxOffset)
+			maxOffset = offset;

+			if (offset > *maxOffset)
+				*maxOffset = offset;

You can use Max macro here.

0018-0023 look good to me.

Comment to 0024:

+        first ( value anyelement [, offset bigint ] )
+        anyelement
+       
+       
+        Returns the column value at the row offset
+        rows after the match start row;
+        returns NULL if the target row is beyond the current row.
+        offset defaults to 0 if omitted, referring to the
+        match start row itself.
+        offset must be a non-negative integer.
+        offset must not be NULL.
+        Can only be used in a DEFINE clause.
+       

"Returns the column value at the row" is not appropriate because
first() accepts any expression as the first argument. e.g. first(col1
+ col2).  Instead what about "Returns value evaluated at the row"?
Same thing can be said to other row pattern navigation operations.
I think they inherits my mistakes in my earlier patch. Sorry for this.

--- a/src/test/regress/expected/rpr.out
+++ b/src/test/regress/expected/rpr.out

+-- match_start=3(30): A=id3, B=id4, FIRST(val)=30≠10 → no match

Non ASCII letter(≠) should not be used.

0025-0031 look good to me.

> On volatile functions in DEFINE (your 2026-04-13 mail): the SQL
> standard itself is relatively narrow here -- the only explicit
> restriction it places is that a navigation function's offset must
> be a runtime constant.  Volatile expressions in the DEFINE
> predicate are not forbidden by the standard.
> 
> That said, once we move into the pattern-matching machinery, the
> observable semantics of a volatile DEFINE become quite murky.
> Depending on the situation, the DEFINE predicate may be evaluated
> once per row, or separately per active matching context, or some
> combination of both as the NFA explores alternatives.  A user
> writing "random() > 0.5" in DEFINE would have a hard time
> predicting, let alone relying on, the evaluation count -- and I
> have not been able to think of a realistic use case that actually
> benefits from this flexibility.

Agreed. The flexibility does not bring benefits to users.

> Given the gap between "permitted by the standard" and "meaningful
> to the user," my own leaning is toward prohibiting volatile
> functions in DEFINE at transformation time, and -- if we go that
> way -- also examining whether the new check would make the
> existing runtime-constant check on the navigation-function offset
> redundant, or whether the two could be folded into a single check
> pass.  That said, this is ultimately a policy call, and I would rather defer
> the final decision to your judgment as a senior member of the
> community: does prohibition seem like the right direction, or
> would you prefer to keep the current behaviour in place?

Let's prohibit volatile functions in DEFINE. Although this needs extra
checking, it would make proceeding codes and tests simpler.  If
others, especially Vik and Jacob, think differently, please join the
discussion.

> On sequencing, if we do take it up, I would suggest handling it
> after the 31-patch set, alongside the README.rpr split as
> follow-up work on top of 0031.  Whether it ultimately lands
> inside v47 or as a separate piece on top does not need to be
> decided right now -- there is still room to discuss it as the
> review progresses, and I am happy to adjust either way based on
> your direction.

I too prefer to have it after the 31-patch set.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thank you very much for the careful review covering 0001-0031 in a
single pass.

0001 was already reviewed (LGTM).
0002-0003 looks good to me.
0004 was already reviewed (LGTM).
0005 thanks for review.

Thank you for confirming.
 
Comment to A1:

+-- A1. Frame optimization bypass
:
:
+-- Non-RPR window with default frame -> frame optimization applied
+EXPLAIN (COSTS OFF)
+SELECT count(*) OVER w FROM rpr_integ
+WINDOW w AS (ORDER BY id);
+            QUERY PLAN             
+-----------------------------------
+ WindowAgg
+   Window: w AS (ORDER BY id)
+   ->  Sort
+         Sort Key: id
+         ->  Seq Scan on rpr_integ
+(5 rows)

The comment says frame optimization applied. But I don't see any frame
option changes (see how the first query changes the frame options).

I thought a frame optimization is something like this.
EXPLAIN(COSTS OFF)
SELECT row_number() OVER W FROM generate_series(1,5) s(i)
WINDOW w AS (
       ORDER BY i
       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
);
                      QUERY PLAN                     
------------------------------------------------------
 WindowAgg
   Window: w AS (ORDER BY i ROWS UNBOUNDED PRECEDING)
   ->  Sort
         Sort Key: i
         ->  Function Scan on generate_series s
(5 rows)

EXPLAIN(COSTS OFF)
SELECT row_number() OVER W FROM generate_series(1,5) s(i)
WINDOW w AS (
       ORDER BY i
       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
       PATTERN (A+)
       DEFINE A AS i > 2
);
                                  QUERY PLAN                                 
------------------------------------------------------------------------------
 WindowAgg
   Window: w AS (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
   Pattern: a+"
   Nav Mark Lookback: 0
   ->  Sort
         Sort Key: i
         ->  Function Scan on generate_series s
(7 rows)

Thank you for pointing this out.  I will analyse A1 and reflect
the findings in the next revision.
 
Comment to 0009:

+       /* Mark VAR in visited before duplicate check to prevent DFS loops */
+       winstate->nfaVisitedElems[WORDNUM(state->elemIdx)] |=
+               ((bitmapword) 1 << BITNUM(state->elemIdx));

Why do not use bms here? Maybe winstate->nfaVisitedElems could become
quite big?

Thank you for the suggestion.  I was not aware of Bitmapset when
this was written; I will switch nfaVisitedElems to Bitmapset.

On sizing, nfa->nelems is structurally bounded by RPR_ELEMIDX_MAX
(INT16_MAX), since RPRNFAState.elemIdx is int16 and scanRPRPattern()
rejects anything past that with "pattern too complex".  So the
bitmap is at most 4 KB per WindowAgg even in the worst case.
 
0010-0016 look good to me.

Confirmed.
 
Comment to 0017:
+
+/*
+ * check_rpr_nav_expr
+ *             Validate a single RPRNavExpr node by walking its arg and offset_arg
+ *             subtrees in a single pass each.  Checks for nested PREV/NEXT, missing
+ *             column references, and non-constant offset expressions.
+ */

"Checks for" --> "Check for" (no "s").

Thank you, will fix.
 
+               ereport(ERROR,
+                               (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                                errmsg("PREV and NEXT cannot be nested"),
+                                parser_errposition(pstate, nav->location)));

 errmsg("PREV and NEXT cannot be nested") ->
 errmsg("cannot nest PREV and NEXT") (avoid passive voice in error messages)

+       ereport(ERROR,
+                       (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+                        errmsg("next() can only be used in a DEFINE clause")));

errmsg("next() can only be used in a DEFINE clause") ->
errmsg("cannot use next() other than in a DEFINE clause")

The same reason above. There are some places where similar changing
necessary.

Thank you for the guidance.  I will fix the two messages called out
here and also look over the surrounding RPR errmsg() strings for
similar passive-voice phrasings, and rewrite those in the active
voice consistent with the PostgreSQL message style guide.
 
+               if (offset > maxOffset)
+                       maxOffset = offset;

+                       if (offset > *maxOffset)
+                               *maxOffset = offset;

You can use Max macro here.

Thank you, will switch both sites to Max(). 

0018-0023 look good to me.

Confirmed.
 
Comment to 0024:

+        <function>first</function> ( <parameter>value</parameter> <type>anyelement</type> [, <parameter>offset</parameter> <type>bigint</type> ] )
+        <returnvalue>anyelement</returnvalue>
+       </para>
+       <para>
+        Returns the column value at the row <parameter>offset</parameter>
+        rows after the match start row;
+        returns NULL if the target row is beyond the current row.
+        <parameter>offset</parameter> defaults to 0 if omitted, referring to the
+        match start row itself.
+        <parameter>offset</parameter> must be a non-negative integer.
+        <parameter>offset</parameter> must not be NULL.
+        Can only be used in a <literal>DEFINE</literal> clause.
+       </para></entry>

"Returns the column value at the row" is not appropriate because
first() accepts any expression as the first argument. e.g. first(col1
+ col2).  Instead what about "Returns value evaluated at the row"?
Same thing can be said to other row pattern navigation operations.
I think they inherits my mistakes in my earlier patch. Sorry for this.

Thank you, and please do not apologise -- I should have caught this
when I carried the wording across.  I will reword the synopses for
first(), last(), prev(), next() (and any other entry that inherited
the same phrasing) along the line you suggested.
 
--- a/src/test/regress/expected/rpr.out
+++ b/src/test/regress/expected/rpr.out

+-- match_start=3(30): A=id3, B=id4, FIRST(val)=30≠10 → no match

Non ASCII letter(≠) should not be used.

Thank you, will fix and sweep rpr*.out for any other non-ASCII
characters (the → on the same line is also non-ASCII). 
 
0025-0031 look good to me.

Confirmed.
 
> On volatile functions in DEFINE (your 2026-04-13 mail): the SQL
> standard itself is relatively narrow here -- the only explicit
> restriction it places is that a navigation function's offset must
> be a runtime constant.  Volatile expressions in the DEFINE
> predicate are not forbidden by the standard.
>
> That said, once we move into the pattern-matching machinery, the
> observable semantics of a volatile DEFINE become quite murky.
> Depending on the situation, the DEFINE predicate may be evaluated
> once per row, or separately per active matching context, or some
> combination of both as the NFA explores alternatives.  A user
> writing "random() > 0.5" in DEFINE would have a hard time
> predicting, let alone relying on, the evaluation count -- and I
> have not been able to think of a realistic use case that actually
> benefits from this flexibility.

Agreed. The flexibility does not bring benefits to users.

> Given the gap between "permitted by the standard" and "meaningful
> to the user," my own leaning is toward prohibiting volatile
> functions in DEFINE at transformation time, and -- if we go that
> way -- also examining whether the new check would make the
> existing runtime-constant check on the navigation-function offset
> redundant, or whether the two could be folded into a single check
> pass.  That said, this is ultimately a policy call, and I would rather defer
> the final decision to your judgment as a senior member of the
> community: does prohibition seem like the right direction, or
> would you prefer to keep the current behaviour in place?

Let's prohibit volatile functions in DEFINE. Although this needs extra
checking, it would make proceeding codes and tests simpler.  If
others, especially Vik and Jacob, think differently, please join the
discussion.

Thank you for the decision.  Since this is a policy change that may
still attract further community discussion, I would like to handle
it as a lower-priority, self-contained follow-up on top of 0031, so
it can be picked up, held, or revised independently.  Tentative
plan: reject volatile functions in DEFINE during parse-analysis via
contain_volatile_functions(), fold with the existing offset
runtime-constant check where the two share traversal, and -- if the
prohibition lands -- convert the B9 test into an error-case test
and drop the XXX note.
 
> On sequencing, if we do take it up, I would suggest handling it
> after the 31-patch set, alongside the README.rpr split as
> follow-up work on top of 0031.  Whether it ultimately lands
> inside v47 or as a separate piece on top does not need to be
> decided right now -- there is still room to discuss it as the
> review progresses, and I am happy to adjust either way based on
> your direction.

I too prefer to have it after the 31-patch set.

Thank you, confirmed.  Both items (volatile-DEFINE prohibition and
README.rpr split) will land as follow-up patches on top of 0031,
after the current series is committed.

One quick question: for the 0007 / 0009 / 0017 / 0024 review fixes
summarised below, would additional follow-up patches on top of 0031
be preferable to refreshing the already-reviewed series?


For ease of tracking, here is a one-line summary per patch of the
changes I plan to fold into the next revision:

  0007: analyse A1 and, if the diagnosis holds, revise it so the
        frame optimization bypass is observable in EXPLAIN
        (adjusting the comment and expected output accordingly).
  0009: switch WindowAggState.nfaVisitedElems from a bitmapword[]
        to Bitmapset, replacing the manual WORDNUM/BITNUM sites
        with bms_add_member() / bms_is_member() / bms_free().
  0017: fix the "Checks for" -> "Check for" comment, rewrite the
        called-out passive-voice errmsg() strings (and the similar
        ones nearby) in the active voice, and use Max() at the two
        offset-update sites.
  0024: reword the navigation synopses (first/last/prev/next) to
        "Returns the value of <value> evaluated at the row ...",
        and replace the non-ASCII ≠ / → in rpr.out with != / ->
        (sweeping the rest of rpr*.out for other non-ASCII).

In addition, I plan to follow the current series with two new
patches on top of 0031 (final numbering deferred until they are
posted):

  new: README.rpr split -- extract the design notes currently
       inlined in execRPR.c into src/backend/executor/README.rpr,
       as previously discussed.
  new: Prohibit volatile functions in DEFINE -- separate,
       self-contained patch as described above; intended as a
       lower-priority follow-up that can be picked up, held, or
       revised independently of the main series depending on how
       the community discussion settles.

Separately, one item is deferred for later discussion rather than
folded into a patch:

  deferred: B7 Recursive CTE XXX in 0007 -- whether this case
            falls under ISO/IEC 9075-2 4.18.5 / 6.17.5 prohibition
            ("Ok, let's discuss on this later on.").  Noted, happy
            to pick this up whenever convenient.

Once you let me know your preference on the sequencing question
above, I will send the corresponding patches as soon as they are
ready, and post the two follow-ups separately so that they can be
reviewed and committed on top of the main series.

Thank you again for the thorough review.

Regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Thank you for pointing this out.  I will analyse A1 and reflect
> the findings in the next revision.

Thanks in advance.

>> Comment to 0009:
>>
>> +       /* Mark VAR in visited before duplicate check to prevent DFS loops
>> */
>> +       winstate->nfaVisitedElems[WORDNUM(state->elemIdx)] |=
>> +               ((bitmapword) 1 << BITNUM(state->elemIdx));
>>
>> Why do not use bms here? Maybe winstate->nfaVisitedElems could become
>> quite big?
>>
> 
> Thank you for the suggestion.  I was not aware of Bitmapset when
> this was written; I will switch nfaVisitedElems to Bitmapset.
> 
> On sizing, nfa->nelems is structurally bounded by RPR_ELEMIDX_MAX
> (INT16_MAX), since RPRNFAState.elemIdx is int16 and scanRPRPattern()
> rejects anything past that with "pattern too complex".  So the
> bitmap is at most 4 KB per WindowAgg even in the worst case.

Hmm. From the comment from bitmapset.c:
 * A bitmap set can represent any set of nonnegative integers, although
 * it is mainly intended for sets where the maximum value is not large,
 * say at most a few hundred.

Maybe 4 KB is tool large? If so, there's no need to rush to change the
implementation. You can leave it as it is for now.

>> Comment to 0024:
>>
>> +        first ( value
>> anyelement [, offset
>> bigint ] )
>> +        anyelement
>> +       
>> +       
>> +        Returns the column value at the row offset
>> +        rows after the match start row;
>> +        returns NULL if the target row is beyond the current row.
>> +        offset defaults to 0 if omitted, referring
>> to the
>> +        match start row itself.
>> +        offset must be a non-negative integer.
>> +        offset must not be NULL.
>> +        Can only be used in a DEFINE clause.
>> +       
>>
>> "Returns the column value at the row" is not appropriate because
>> first() accepts any expression as the first argument. e.g. first(col1
>> + col2).  Instead what about "Returns value evaluated at the row"?
>> Same thing can be said to other row pattern navigation operations.
>> I think they inherits my mistakes in my earlier patch. Sorry for this.
>>
> 
> Thank you, and please do not apologise -- I should have caught this
> when I carried the wording across.  I will reword the synopses for
> first(), last(), prev(), next() (and any other entry that inherited
> the same phrasing) along the line you suggested.

Thank you.

>> Let's prohibit volatile functions in DEFINE. Although this needs extra
>> checking, it would make proceeding codes and tests simpler.  If
>> others, especially Vik and Jacob, think differently, please join the
>> discussion.
>>
> 
> Thank you for the decision.  Since this is a policy change that may
> still attract further community discussion, I would like to handle
> it as a lower-priority, self-contained follow-up on top of 0031, so
> it can be picked up, held, or revised independently.  Tentative
> plan: reject volatile functions in DEFINE during parse-analysis via
> contain_volatile_functions(), fold with the existing offset
> runtime-constant check where the two share traversal, and -- if the
> prohibition lands -- convert the B9 test into an error-case test
> and drop the XXX note.

Your tentative plan looks good to me.

>> > On sequencing, if we do take it up, I would suggest handling it
>> > after the 31-patch set, alongside the README.rpr split as
>> > follow-up work on top of 0031.  Whether it ultimately lands
>> > inside v47 or as a separate piece on top does not need to be
>> > decided right now -- there is still room to discuss it as the
>> > review progresses, and I am happy to adjust either way based on
>> > your direction.
>>
>> I too prefer to have it after the 31-patch set.
>>
> 
> Thank you, confirmed.  Both items (volatile-DEFINE prohibition and
> README.rpr split) will land as follow-up patches on top of 0031,
> after the current series is committed.
> 
> One quick question: for the 0007 / 0009 / 0017 / 0024 review fixes
> summarised below, would additional follow-up patches on top of 0031
> be preferable to refreshing the already-reviewed series?

Yes, that's fine. I will apply the delta patch for 0007 / 0009 / 0017
/ 0024 on top of 0031.

> For ease of tracking, here is a one-line summary per patch of the
> changes I plan to fold into the next revision:
> 
>   0007: analyse A1 and, if the diagnosis holds, revise it so the
>         frame optimization bypass is observable in EXPLAIN
>         (adjusting the comment and expected output accordingly).
>   0009: switch WindowAggState.nfaVisitedElems from a bitmapword[]
>         to Bitmapset, replacing the manual WORDNUM/BITNUM sites
>         with bms_add_member() / bms_is_member() / bms_free().
>   0017: fix the "Checks for" -> "Check for" comment, rewrite the
>         called-out passive-voice errmsg() strings (and the similar
>         ones nearby) in the active voice, and use Max() at the two
>         offset-update sites.
>   0024: reword the navigation synopses (first/last/prev/next) to
>         "Returns the value of  evaluated at the row ...",
>         and replace the non-ASCII ≠ / → in rpr.out with != / ->
>         (sweeping the rest of rpr*.out for other non-ASCII).

Confirmed.

> In addition, I plan to follow the current series with two new
> patches on top of 0031 (final numbering deferred until they are
> posted):
> 
>   new: README.rpr split -- extract the design notes currently
>        inlined in execRPR.c into src/backend/executor/README.rpr,
>        as previously discussed.
>   new: Prohibit volatile functions in DEFINE -- separate,
>        self-contained patch as described above; intended as a
>        lower-priority follow-up that can be picked up, held, or
>        revised independently of the main series depending on how
>        the community discussion settles.

Ok.

> Separately, one item is deferred for later discussion rather than
> folded into a patch:
> 
>   deferred: B7 Recursive CTE XXX in 0007 -- whether this case
>             falls under ISO/IEC 9075-2 4.18.5 / 6.17.5 prohibition
>             ("Ok, let's discuss on this later on.").  Noted, happy
>             to pick this up whenever convenient.

Ok.

> Once you let me know your preference on the sequencing question
> above, I will send the corresponding patches as soon as they are
> ready, and post the two follow-ups separately so that they can be
> reviewed and committed on top of the main series.
> 
> Thank you again for the thorough review.

Thank you for your effort!
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

Hi Tatsuo,


Attached are 40 incremental patches on top of v46, with all
review-driven follow-ups folded in.  The 0001-0031 portion is
unchanged from the previous send (filenames preserved).  The new
patches 0032-0040 are the delta + follow-up patches we agreed to
deliver on top of 0031, plus two cosmetic patches that surfaced
during the sweep.

As you suggested, I have not refreshed 0001-0031; the new work
is layered on top so that the existing review state on those
patches stays valid.

Numbering and subjects of 0001-0031 are unchanged.  The new
patches are:


  - 0032 Fix A1 frame optimization bypass test in
    rpr_integration

    Per your A1 review.  Switches the baseline to row_number()
    with an explicit ROWS frame so that the bypass guard is
    actually exercised.  Block comment reworded in A2/A3 style.


  - 0033 Fix imperative voice in check_rpr_nav_expr header
    comment

    Per your typo note: "Checks for" -> "Check for".


  - 0034 Fix passive voice in RPR error messages

    Per your style note.  Sweep of RPR-touched code paths
    (parse_rpr.c, parse_func.c, windowfuncs.c) for the
    "is not permitted when ... is used" / "can only be used in"
    patterns, rewritten to "cannot use ... with" /
    "cannot use ... outside".


  - 0035 Use Max()/Min() macros for RPR extremum accumulation

    Per your Max() macro suggestion.  Sweep of all hand-rolled
    "if (x > y) y = x;" sites in createplan.c, nodeWindowAgg.c,
    and execRPR.c.  No double-evaluation hazards on the call
    sites.


  - 0036 Reword RPR navigation function synopses

    Per your sgml note.  "Returns the column value at the row"
    -> "Returns value evaluated at the row" (the first argument
    can be an arbitrary expression).


  - 0037 Replace non-ASCII characters in RPR code and tests

    Per your non-ASCII note.  Sweep of RPR-touched files;
    mostly comments and rpr*.out.


  - 0038 Move RPR design notes from execRPR.c to README.rpr

    Per the README.rpr split we discussed.  Extracts the
    design block at the head of execRPR.c into
    src/backend/executor/README.rpr (plain text, matching the
    executor/README convention).  No code changes.


  - 0039 Apply pgindent canonicalization to RPR comment blocks

    Cosmetic.  pgindent sweep across RPR-touched files; labeled
    blocks wrapped in /*---------- ... *---------- to preserve
    hanging indents.  No code changes.


  - 0040 Reword RPR navigation function descriptions in
    pg_proc.dat

    Cosmetic.  Aligns the eight RPR navigation descr fields
    with the surrounding "fetch the ... row value" pattern used
    by lag / lead / first_value / last_value / nth_value.


On the items deferred to post-v47:


  - DEFINE volatile prohibition: prepared as a self-contained
    follow-up so it can be reviewed independently of v47.

  - 0009 nfaVisitedElems representation: per your decision,
    kept as-is.  Three points behind that:

      (1) Size concern.  visited is 1 bit per element, a flat
          NFA element is 16 bytes -- a fixed 128:1 ratio
          (~0.78%).  The bitmap is dwarfed by the NFA it
          tracks (worst case ~4 KiB next to ~512 KiB), so it
          is not a memory hot spot.

      (2) Bitmapset misfit.  Its invariants ("no trailing zero
          word", "empty set = NULL") map the per-advance reset
          onto pfree + palloc-on-next-add, which defeats the
          in-place / fixed-capacity reuse pattern this code
          relies on.

      (3) Future variant.  A high-water mark approach (track
          the min/max touched word index, memset only that
          span on reset) preserves the in-place pattern and
          shrinks reset cost from O(numElements/64) to
          O(span_words).  Held as a future optimization
          candidate.

  - 0007 / B7 (Recursive CTE XXX): tracked as a discussion item
    awaiting community input on the standard interpretation.


Regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

Thank you for the patch sets! Quick question:

I know in v47 JIT compilation supports PREV/NEXT. What about
FIRST/LAST and compound forms?

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

I know in v47 JIT compilation supports PREV/NEXT. What about
FIRST/LAST and compound forms?

Yes, those are JIT-compiled too in v47.

The JIT side only deals with two opcodes -- EEOP_RPR_NAV_SET
and EEOP_RPR_NAV_RESTORE.

FIRST/LAST and the compound forms differ only in how
ExecEvalRPRNavSet() computes target_pos for the slot swap;
the opcode interface and the call into ExecEvalRPRNavSet /
ExecEvalRPRNavRestore are unchanged.

So 0018's JIT support carries over to FIRST/LAST and
compounds without any JIT-side change.

Regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> I know in v47 JIT compilation supports PREV/NEXT. What about
>> FIRST/LAST and compound forms?
>>
> 
> Yes, those are JIT-compiled too in v47.
> 
> The JIT side only deals with two opcodes -- EEOP_RPR_NAV_SET
> and EEOP_RPR_NAV_RESTORE.
> 
> FIRST/LAST and the compound forms differ only in how
> ExecEvalRPRNavSet() computes target_pos for the slot swap;
> the opcode interface and the call into ExecEvalRPRNavSet /
> ExecEvalRPRNavRestore are unchanged.
> 
> So 0018's JIT support carries over to FIRST/LAST and
> compounds without any JIT-side change.

Ok, from user's point of view, PREV/NEXT/FIRST/LAST and compound forms
are all JIT-compiled. I will add it to the "major changes" section in
the v47 patches posting.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached is the v47 patches for Row pattern recognition (SQL/RPR).

Major changes from v46 include:

- Change implementation of row pattern navigation operations using
  "1-slot model", which allows to implement more standard compliant
  features such as an offset argument, more row pattern navigation
  operations (FIRST, LAST) and compound forms.

- Row pattern navigation operations now support FIRST, LAST and
  compound forms

- Add JIT compilation support for all row pattern navigation
  operations (including compound forms)

- Add tuplestore trim optimization for RPR PREV navigation

- Window function last_value() now allows to set mark in certain cases

- Change the implementation of reduced frame map. Now consumes less CPU and memory

- Add more optimization (absorption). e.g. (A B B)+

- Add planner integration tests (rpr_integration.sql)

- Add src/backend/executor/README.rpr (previously was in ExecRPR.c)

Current status:

The series of patches are to implement the row pattern recognition
(SQL/RPR) feature. Currently the implementation is a subset of SQL/RPR
(ISO/IEC 19075-2:2016). Namely, implementation of some features of
R020 (WINDOW clause). R010 (MATCH_RECOGNIZE) is out of the scope of
the patches.

Currently following features are implemented in the patches.

- PATTERN
- PATTERN regular expressions (+, *, ?)
  alternation (|), grouping () , {n}, {n,}, {n,m}, {,m}
  reluctant quantifiers (*? etc.),
- DEFINE
- INITIAL
- AFTER MATCH SKIP TO PAST LAST ROW
- AFTER MATCH SKIP TO NEXT ROW
- Row pattern navigation (FIRST, LAST, PREV, NEXT and their compound forms)

Currently following features are not implemented in the patches.

- MEASURES
- Pattern variable name qualified column reference (e.g. A.price)
- SUBSET
- SEEK
- AFTER MATCH SKIP TO
- AFTER MATCH SKIP TO FIRST
- AFTER MATCH SKIP TO LAST
- PATTERN regular expression  {- and -}, () (empty pattern)
  Anchors (^, $) are not permitted with RPR in Window clause by the
  standard.
- PERMUTE
- CLASSIFIER

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, hi hackers,

I'd like to ask for a bit of review help before PGConf.dev 2026
(Vancouver, May 19–22).

For the SQL/RPR R020 poster going on display at the conference, I
have prepared a companion deep-dive page to sit behind the on-site
QR code, building on the patch series Tatsuo has been driving in
this thread:

  https://assam258-5892.github.io/postgresql/rpr/

It walks through the standard scope (R010 vs R020), worked examples,
NFA semantics, navigation functions, parser-to-executor design and
pruning rules, plus an interactive NFA simulator. To widen reach,
the page is also available in 23 AI-pretranslated languages from
the switcher:
العربية, Čeština, Dansk, Deutsch, Español, Suomi, Français,
עברית, Magyar, Italiano, 日本語, 한국어, Nederlands, Norsk,
Polski, Português (BR), Română, Русский, Slovenčina, Svenska,
Türkçe, 中文 (简体), 繁體中文.
Each translated page carries a clear "AI pre-translated, errors
possible" notice.

The ask (light, entirely optional):

  - English original has had one review pass; Korean I reviewed
    myself.
  - Tatsuo — if you ever find a free moment, a quick glance at the
    Japanese version would be very much appreciated, but absolutely
    no rush.
  - Native speakers of any of the other 22 languages — incidental
    corrections welcome (this thread or off-list), but nothing is
    expected.

References (also linked from the deep-dive page):
  - thread: https://www.postgresql.org/message-id/flat/20230625.210509.1276733411677577841.t-ishii%40sranhm.sra.co.jp
  - latest patch (v47): https://postgr.es/m/20260502.140304.670813149418899420.ishii@postgresql.org
  - commitfest #4460: https://commitfest.postgresql.org/patch/4460/

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Attached is the v47 patches for Row pattern recognition (SQL/RPR).

v47 starts to check whether range variable qualified expressions are
used in DEFINE clause. If used, raise an error. This is good because
we don't support the syntax yet (pattern variable range var), or it's
prohibited (from clause range var). However, the error message may not
be appropreate for the case when complex data type is involved.

CREATE TEMP TABLE item (name TEXT, amount INT);
CREATE TABLE
CREATE TEMP TABLE sales(items item);
CREATE TABLE
SELECT (items).name, (items).amount, count(*) OVER w
FROM sales WINDOW w AS (
    ORDER BY (items).name
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    AFTER MATCH SKIP PAST LAST ROW
    PATTERN (A+)
    DEFINE A AS (A.items).amount > 10
);
ERROR:  pattern variable qualified column reference "a.items" is not supported in DEFINE clause
LINE 7:     DEFINE A AS (A.items).amount > 10
                         ^
If I change the DEFINE clause to:

    DEFINE A AS (sales.items).amount > 10

I get:

ERROR:  range variable qualified column reference "sales.items" is not allowed in DEFINE clause
LINE 8:     DEFINE A AS (sales.items).amount > 10
                         ^

In both cases, "a.items" or "sales.items" in the error messages are
not column names, therefore the wording "column reference" in the
error messages are not appropriate.

The checks are in transformColumnRef().  Its argument "ColumnRef
*cref->fields" is a list of column ref fields in DEFINE expression in
the raw parse tree.  Usually it's something like range_var.col_name or
just col_name etc. So it works. However when complex data types are
involved, cref->fields is something like sales.items. No col_name
included. In this case, ColumnRef is under Indirection node, and the
col_name is stored in Indirection->indirection, not in ColumnRef.
Therefore there's no way for transformColumnRef() to know the col_name.

In order to fix the issue, I think we need to add code to understand
range var qualification form "A.item" or "sales.items" in complex data
types case. But is it worth the trouble? The reword is just nicer
error messages. If we support MEASURES, the code is useful. But so far
we have decided to not support it in the first cut of RPR.

Maybe we should just change the error messages something like below
for now?

ERROR:  pattern variable qualified expression "a.items" is not supported in DEFINE clause
ERROR:  range variable qualified expression "sales.items" is not allowed in DEFINE clause

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
On Tue, May 5, 2026 at 8:02 AM Tatsuo Ishii  wrote:
>
> > Attached is the v47 patches for Row pattern recognition (SQL/RPR).
>

Hi
The patchset is too big, I only downloaded v47-0001...
Just a quick skim of the code on my end.
I noticed two code style issues, currently we don't have a code style
reference in the manual.

1. We need to add trailing commas to enum definitions. See
https://git.postgresql.org/cgit/postgresql.git/commit/?id=611806cd726fc92989ac918eac48fd8d684869c7

2.
+ | '{' ',' Iconst '}' Op
+ {
+ if (strcmp($5, "?") != 0)
+ ereport(ERROR,
+ (errcode(ERRCODE_SYNTAX_ERROR),
+ errmsg("invalid token after range quantifier"),
+ errhint("Only \"?\" is allowed after {n,} or {,m} to make it reluctant."),
+ parser_errposition(@5)));
+ if ($3 <= 0 || $3 >= INT_MAX)
+ ereport(ERROR,
+ errcode(ERRCODE_SYNTAX_ERROR),
+ errmsg("quantifier bound must be between 1 and %d", INT_MAX - 1),
+ parser_errposition(@3));
+ $$ = (Node *) makeRPRQuantifier(0, $3, @5, @1, yyscanner);

+ (errcode(ERRCODE_SYNTAX_ERROR),
The leading parenthesis is optional and can be removed, fewer
parentheses are always better.
See related discussion:
https://postgr.es/m/202510100916.s2e6n3xiwvyc@alvherre.pgsql

Since v47-0001 introduces many ereport(ERROR) messages, it makes sense
to move the related regression tests from the other patch into
v47-0001, IMHO.



--
jian
https://www.enterprisedb.com/


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thanks for the close look.  Inline below, then a sketch of what I
plan to put in v48 so you can pick what to pull first.

v47 starts to check whether range variable qualified expressions are
used in DEFINE clause. If used, raise an error. This is good because
we don't support the syntax yet (pattern variable range var), or it's
prohibited (from clause range var). However, the error message may not
be appropreate for the case when complex data type is involved.

CREATE TEMP TABLE item (name TEXT, amount INT);
CREATE TABLE
CREATE TEMP TABLE sales(items item);
CREATE TABLE
SELECT (items).name, (items).amount, count(*) OVER w
FROM sales WINDOW w AS (
    ORDER BY (items).name
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    AFTER MATCH SKIP PAST LAST ROW
    PATTERN (A+)
    DEFINE A AS (A.items).amount > 10
);
ERROR:  pattern variable qualified column reference "a.items" is not supported in DEFINE clause
LINE 7:     DEFINE A AS (A.items).amount > 10
                         ^
If I change the DEFINE clause to:

    DEFINE A AS (sales.items).amount > 10

I get:

ERROR:  range variable qualified column reference "sales.items" is not allowed in DEFINE clause
LINE 8:     DEFINE A AS (sales.items).amount > 10
                         ^

In both cases, "a.items" or "sales.items" in the error messages are
not column names, therefore the wording "column reference" in the
error messages are not appropriate.

Agreed.  Even for the simple non-composite cases the noun is fuzzy
once A_Indirection enters the picture.  "expression" reads naturally
in both cases.
 
In order to fix the issue, I think we need to add code to understand
range var qualification form "A.item" or "sales.items" in complex data
types case. But is it worth the trouble? The reword is just nicer
error messages. If we support MEASURES, the code is useful. But so far
we have decided to not support it in the first cut of RPR.

Not now.  Teaching the pre-check about the surrounding A_Indirection
duplicates work that MEASURES will need anyway, and the only visible
gain before MEASURES is a more accurate echo of the source text.

Instead I'll mark the limitation in three places so future MEASURES
work can't miss it: a block comment above the pre-check that names
the limitation and the revisit point, an XXX cross-reference in
parse_rpr.c pointing back to the pre-check, and composite-type cases
in rpr_base whose expected output quotes only the ColumnRef portion
-- so when indirection-aware quoting lands, those outputs churn as
a tripwire. 
 
Maybe we should just change the error messages something like below
for now?

ERROR:  pattern variable qualified expression "a.items" is not supported in DEFINE clause
ERROR:  range variable qualified expression "sales.items" is not allowed in DEFINE clause

Yes -- planned for v48.  While I'm in that path I'll also clean up
two adjacent issues:

  - the pre-check is binary, so an unknown qualifier (typo,
    undefined name) is misreported as a range-variable reference
    with SYNTAX_ERROR instead of falling through to the standard
    "column does not exist" / "missing FROM-clause entry"
    diagnostic;

  - parse_rpr.c and the SELECT docs claim DEFINE-name "collection"
    and "filtering during planning"; the actual behavior is
    validate-and-reject at parse analysis.


------------------------------------------------------------------
v48 follow-up plan
------------------------------------------------------------------

The items below are independent, so they can ship as separate
patches or as a single batched posting -- whichever you prefer.
Order is just for narrative; nothing depends on anything else.

  [A] Sizable refactor: collapse the four DEFINE walkers across
      parser/planner/executor into a single phase-tagged
      traversal.  On that base, reject volatile / NextValueExpr
      in DEFINE (the NFA may re-evaluate predicates during
      backtracking; STABLE / IMMUTABLE remain accepted), and
      bundle a STABLE/IMMUTABLE baseline test as a guard against
      accidental over-rejection.

  [B] Make the empty-match path observable in tests: replace the
      stale XXX comments in rpr_nfa with the actual behavior, and
      add EXPLAIN ANALYZE coverage in rpr_explain that surfaces
      "NFA: N matched (len 0/0/0.0)" so the NFA-found-but-window-
      empty case is regression-visible.

  [C] Trim the per-advance NFA visited-bitmap reset to a high-water
      mark range instead of the full bitmap.  Tradeoff: two int16
      comparisons added per visit, paying off for larger NFAs but
      added overhead for single-word bitmaps; semantics unchanged.
      I'll leave the decision to apply to your judgment.

  [D] DEFINE qualifier diagnostic: tri-classify (pattern var /
      range var / fall-through), reword to "expression", add
      unknown-qualifier and composite-type tests, and sync the
      adjacent stale comments and SELECT doc.

If any of [A]..[D] looks misjudged or you'd prefer a different
slicing, I'll reshape before posting.

Best,
Henson 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Jian,

> Hi
> The patchset is too big, I only downloaded v47-0001...

Yeah, since the feature is complex...

> 1. We need to add trailing commas to enum definitions. See
> https://git.postgresql.org/cgit/postgresql.git/commit/?id=611806cd726fc92989ac918eac48fd8d684869c7

I forgot that. Thanks for reminding.

> 2.
> + | '{' ',' Iconst '}' Op
> + {
> + if (strcmp($5, "?") != 0)
> + ereport(ERROR,
> + (errcode(ERRCODE_SYNTAX_ERROR),
> + errmsg("invalid token after range quantifier"),
> + errhint("Only \"?\" is allowed after {n,} or {,m} to make it reluctant."),
> + parser_errposition(@5)));
> + if ($3 <= 0 || $3 >= INT_MAX)
> + ereport(ERROR,
> + errcode(ERRCODE_SYNTAX_ERROR),
> + errmsg("quantifier bound must be between 1 and %d", INT_MAX - 1),
> + parser_errposition(@3));
> + $$ = (Node *) makeRPRQuantifier(0, $3, @5, @1, yyscanner);
> 
> + (errcode(ERRCODE_SYNTAX_ERROR),
> The leading parenthesis is optional and can be removed, fewer
> parentheses are always better.
> See related discussion:
> https://postgr.es/m/202510100916.s2e6n3xiwvyc@alvherre.pgsql

Right. I will review all other patches.

> Since v47-0001 introduces many ereport(ERROR) messages, it makes sense
> to move the related regression tests from the other patch into
> v47-0001, IMHO.

Thanks for the suggestion but I do not agree the direction.  It will
make the patch maintenance work harder. Also it will make it difficult
to understand the regression test organization.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

Both coding-style items from Jian's review will be addressed and
included in the next patch series.

> 1. We need to add trailing commas to enum definitions. See
> https://git.postgresql.org/cgit/postgresql.git/commit/?id=611806cd726fc92989ac918eac48fd8d684869c7

I forgot that. Thanks for reminding.

Three enum types introduced by the patch lack a trailing comma on the
last enumerator: RPRNavKind, RPRNavOffsetKind, and RPRPatternNodeType.
All three will be corrected in the next series.
 
> + (errcode(ERRCODE_SYNTAX_ERROR),
> The leading parenthesis is optional and can be removed, fewer
> parentheses are always better.
> See related discussion:
> https://postgr.es/m/202510100916.s2e6n3xiwvyc@alvherre.pgsql

Right. I will review all other patches.

The outer-parentheses pattern appears in 17 ereport() calls in
parse_rpr.c and 2 in optimizer/plan/rpr.c.  All 19 sites will be
cleaned up in the next series.

Jian, I will review your other patches as well.

Best,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> The outer-parentheses pattern appears in 17 ereport() calls in
> parse_rpr.c and 2 in optimizer/plan/rpr.c.  All 19 sites will be
> cleaned up in the next series.

I see them in gram.y as well. See attached patch.

> Jian, I will review your other patches as well.
> 
> Best,
> Henson
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index f3cedfbbb18..aa587e6aced 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -17610,10 +17610,10 @@ opt_row_pattern_initial_or_seek:
 			| SEEK
 				{
 					ereport(ERROR,
-							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-							 errmsg("SEEK is not supported"),
-							 errhint("Use INITIAL instead."),
-							 parser_errposition(@1)));
+							errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+							errmsg("SEEK is not supported"),
+							errhint("Use INITIAL instead."),
+							parser_errposition(@1));
 				}
 			| /*EMPTY*/		{ $$ = true; }
 		;
@@ -17740,40 +17740,40 @@ row_pattern_quantifier_opt:
 						$$ = (Node *) makeRPRQuantifier(0, 1, @1 + 1, @1, yyscanner);
 					else
 						ereport(ERROR,
-								(errcode(ERRCODE_SYNTAX_ERROR),
-								 errmsg("unsupported quantifier \"%s\"", $1),
-								 errhint("Valid quantifiers are: *, +, ?, *?, +?, ??, {n}, {n,}, {,m}, {n,m} and their reluctant versions."),
-								 parser_errposition(@1)));
+								errcode(ERRCODE_SYNTAX_ERROR),
+								errmsg("unsupported quantifier \"%s\"", $1),
+								errhint("Valid quantifiers are: *, +, ?, *?, +?, ??, {n}, {n,}, {,m}, {n,m} and their reluctant versions."),
+								parser_errposition(@1));
 				}
 			/* RELUCTANT quantifiers (when lexer separates tokens) */
 			| '*' Op
 				{
 					if (strcmp($2, "?") != 0)
 						ereport(ERROR,
-								(errcode(ERRCODE_SYNTAX_ERROR),
-								 errmsg("invalid token after \"*\" quantifier"),
-								 errhint("Did you mean \"*?\" for reluctant quantifier?"),
-								 parser_errposition(@2)));
+								errcode(ERRCODE_SYNTAX_ERROR),
+								errmsg("invalid token after \"*\" quantifier"),
+								errhint("Did you mean \"*?\" for reluctant quantifier?"),
+								parser_errposition(@2));
 					$$ = (Node *) makeRPRQuantifier(0, INT_MAX, @2, @1, yyscanner);
 				}
 			| '+' Op
 				{
 					if (strcmp($2, "?") != 0)
 						ereport(ERROR,
-								(errcode(ERRCODE_SYNTAX_ERROR),
-								 errmsg("invalid token after \"+\" quantifier"),
-								 errhint("Did you mean \"+?\" for reluctant quantifier?"),
-								 parser_errposition(@2)));
+								errcode(ERRCODE_SYNTAX_ERROR),
+								errmsg("invalid token after \"+\" quantifier"),
+								errhint("Did you mean \"+?\" for reluctant quantifier?"),
+								parser_errposition(@2));
 					$$ = (Node *) makeRPRQuantifier(1, INT_MAX, @2, @1, yyscanner);
 				}
 			| Op Op
 				{
 					if (strcmp($1, "?") != 0 || strcmp($2, "?") != 0)
 						ereport(ERROR,
-								(errcode(ERRCODE_SYNTAX_ERROR),
-								 errmsg("invalid quantifier combination"),
-								 errhint("Did you mean \"??\" for reluctant quantifier?"),
-								 parser_errposition(@1)));
+								errcode(ERRCODE_SYNTAX_ERROR),
+								errmsg("invalid quantifier combination"),
+								errhint("Did you mean \"??\" for reluctant quantifier?"),
+								parser_errposition(@1));
 					$$ = (Node *) makeRPRQuantifier(0, 1, @2, @1, yyscanner);
 				}
 			/* {n}, {n,}, {,m}, {n,m} quantifiers */
@@ -17823,10 +17823,10 @@ row_pattern_quantifier_opt:
 				{
 					if (strcmp($4, "?") != 0)
 						ereport(ERROR,
-								(errcode(ERRCODE_SYNTAX_ERROR),
-								 errmsg("invalid token after range quantifier"),
-								 errhint("Only \"?\" is allowed after {n} to make it reluctant."),
-								 parser_errposition(@4)));
+								errcode(ERRCODE_SYNTAX_ERROR),
+								errmsg("invalid token after range quantifier"),
+								errhint("Only \"?\" is allowed after {n} to make it reluctant."),
+								parser_errposition(@4));
 					if ($2 <= 0 || $2 >= INT_MAX)
 						ereport(ERROR,
 								errcode(ERRCODE_SYNTAX_ERROR),
@@ -17838,10 +17838,10 @@ row_pattern_quantifier_opt:
 				{
 					if (strcmp($5, "?") != 0)
 						ereport(ERROR,
-								(errcode(ERRCODE_SYNTAX_ERROR),
-								 errmsg("invalid token after range quantifier"),
-								 errhint("Only \"?\" is allowed after {n,} or {,m} to make it reluctant."),
-								 parser_errposition(@5)));
+								errcode(ERRCODE_SYNTAX_ERROR),
+								errmsg("invalid token after range quantifier"),
+								errhint("Only \"?\" is allowed after {n,} or {,m} to make it reluctant."),
+								parser_errposition(@5));
 					if ($2 < 0 || $2 >= INT_MAX)
 						ereport(ERROR,
 								errcode(ERRCODE_SYNTAX_ERROR),
@@ -17853,10 +17853,10 @@ row_pattern_quantifier_opt:
 				{
 					if (strcmp($5, "?") != 0)
 						ereport(ERROR,
-								(errcode(ERRCODE_SYNTAX_ERROR),
-								 errmsg("invalid token after range quantifier"),
-								 errhint("Only \"?\" is allowed after {n,} or {,m} to make it reluctant."),
-								 parser_errposition(@5)));
+								errcode(ERRCODE_SYNTAX_ERROR),
+								errmsg("invalid token after range quantifier"),
+								errhint("Only \"?\" is allowed after {n,} or {,m} to make it reluctant."),
+								parser_errposition(@5));
 					if ($3 <= 0 || $3 >= INT_MAX)
 						ereport(ERROR,
 								errcode(ERRCODE_SYNTAX_ERROR),
@@ -17868,10 +17868,10 @@ row_pattern_quantifier_opt:
 				{
 					if (strcmp($6, "?") != 0)
 						ereport(ERROR,
-								(errcode(ERRCODE_SYNTAX_ERROR),
-								 errmsg("invalid token after range quantifier"),
-								 errhint("Only \"?\" is allowed after {n,m} to make it reluctant."),
-								 parser_errposition(@6)));
+								errcode(ERRCODE_SYNTAX_ERROR),
+								errmsg("invalid token after range quantifier"),
+								errhint("Only \"?\" is allowed after {n,m} to make it reluctant."),
+								parser_errposition(@6));
 					if ($2 < 0 || $4 <= 0 || $2 >= INT_MAX || $4 >= INT_MAX)
 						ereport(ERROR,
 								errcode(ERRCODE_SYNTAX_ERROR),

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

I see them in gram.y as well. See attached patch.

Thank you for the patch. It will be included in the next series.

Best,
Henson 

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo, hi Jian,

Attached are 10 incremental patches on top of v47, covering the
follow-up plan ([A]..[D]) I sketched on 2026-05-05, Jian's two
coding-style items (trailing commas, outer parentheses; gram.y
folded into 0007), one comment-only patch (0009), and one trivial
cleanup (0010).  Packaging into the next version is at your
discretion.

Patch summary:

  - 0001 Add DEFINE non-volatile baseline to rpr_integration B9
      Adds a STABLE/IMMUTABLE baseline ahead of the volatile
      case so the rejection in 0002 is visible against a working
      reference.

  - 0002 Unify RPR DEFINE walkers and reject volatile callees
      [A].  Collapses the four DEFINE walkers (parser / planner
      / executor) into one phase-tagged traversal and, on that
      base, rejects volatile / NextValueExpr at parse-analysis.
      STABLE / IMMUTABLE accepted.  The offset runtime-constant
      check is folded in; B9 flips to error-case and its XXX is
      dropped.

  - 0003 Cover RPR empty-match path with EXPLAIN tests; fix
         stale XXX comments
      [B].  Adds rpr_explain coverage that surfaces "NFA: N
      matched (len 0/0/0.0)" so the NFA-found-but-empty-frame
      path is regression-visible; replaces stale rpr_nfa XXXs.

  - 0004 Reclassify DEFINE qualifier check and reword
         diagnostic to "expression"
      [D].  Tri-classifies (pattern var / range var / fall-
      through) so unknown qualifiers fall through to the
      standard "column does not exist" diagnostic.  Reworded to
      "expression" since the quoted token may include
      indirection on composite types (e.g. (A.items).amount).

  - 0005 Sync stale comments on DEFINE/PATTERN handling
      validateRPRPatternVarCount() rejects DEFINE names not in
      PATTERN, but comments / SELECT doc described it as
      "collection" / "filtered during planning".  Wording
      aligned; XXX note's "column references" bumped to
      "expressions" to match 0004.  Comment + doc only.

  - 0006 Add trailing commas to RPR enum definitions
      Per Jian.  RPRNavKind, RPRNavOffsetKind, RPRPatternNodeType.

  - 0007 Remove optional outer parentheses from ereport() calls
         in RPR files
      Per Jian + Tatsuo's gram.y patch.  19 sites in
      parse_rpr.c / optimizer/plan/rpr.c plus the gram.y sites.

  - 0008 Add high-water mark tracking to NFA visited bitmap
         reset
      [C].  Resets only the touched span (O(span_words) instead
      of O(numElements/64)), at the cost of two int16 comparisons
      per visit.  Semantics unchanged; happy to drop if you
      prefer the simpler bulk reset.

  - 0009 Document DEFINE subquery rejection as intentional
         over-rejection
      Comment-only.  Records that ISO/IEC 9075-2 §4.18.4 /
      6.17.4 (R010 / R020) permits a non-RPR, non-pattern-var-
      correlated subquery in DEFINE, and that our blanket
      rejection is deliberate over-rejection.  The case
      distinction (walk subquery Query for nested RPR; match
      ColumnRef qualifiers against ancestor p_rpr_pattern_vars)
      is doable with existing infrastructure and left as future
      work, not blocked on any other feature.

  - 0010 Remove duplicate #include in nodeWindowAgg.c
      "common/int.h" was included twice and the first occurrence
      was misplaced between catalog/* headers.  Drops the
      misplaced first; the second sits at the correct
      alphabetical position.

Still deferred:
  - B7 Recursive CTE XXX: pending community input on the
    §4.18.5 / 6.17.5 interpretation.

Please let me know if any of 0001-0010 looks misjudged or if you
would prefer a different slicing.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Attached is the v47 patches for Row pattern recognition (SQL/RPR).

While looking into v47, I noticed that
raw_expression_tree_walker_impl() lacks tracking RPCommonSyntax and
its children nodes. Probably this does nothing wrong with RPR
functionalities but just for completeness I created a patch on top of
v47.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 651d049cfa2..c8694726e3c 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -4612,6 +4612,8 @@ raw_expression_tree_walker_impl(Node *node,
 					return true;
 				if (WALK(wd->endOffset))
 					return true;
+				if (WALK(wd->rpCommonSyntax))
+					return true;
 			}
 			break;
 		case T_RangeSubselect:
@@ -4865,6 +4867,24 @@ raw_expression_tree_walker_impl(Node *node,
 					return true;
 			}
 			break;
+		case T_RPCommonSyntax:
+			{
+				RPCommonSyntax *rc = (RPCommonSyntax *) node;
+
+				if (WALK(rc->rpPattern))
+					return true;
+				if (WALK(rc->rpDefs))
+					return true;
+			}
+			break;
+		case T_RPRPatternNode:
+			{
+				RPRPatternNode *rp = (RPRPatternNode *) node;
+
+				if (WALK(rp->children))
+					return true;
+			}
+			break;
 		default:
 			elog(ERROR, "unrecognized node type: %d",
 				 (int) nodeTag(node));

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Hi.

Disclaimer: I had some private off-list discussions with Henson Choi
regarding execRPR.c, and the NFA.
The following are more formal comments regarding execRPR.c and the NFA
algorithm, based on v47-0001 to v47-0009, I haven't applied the
incremental diff yet.
(Since the incremental diffs are scattered across several threads, a
unified v48 would be better).
(I'm still wrapping my head around the NFA in execRPR.c, so take the
comments below with a grain of salt.)


PATTERN (A B C D)
We can short-circuit and exit early if any of the evaluations (A, B,
or C) fail in nfa_match.
This is necessary since the chance of a pattern element evaluation
returning false is not rare, I think.


For src/backend/executor/README.rpr:
We should explicitly explain 'absorbable' and 'absorption' somewhere in
README.rpr, as the text currently just assumes the reader knows what they mean.
Using some example illustrate "absorption" meaning, put it on
README.rpr would be great.
We can also mention that 'DFS' refers to Depth-First Search".

``````
  (4) Call nfa_advance(initialAdvance=true)
``````
In V47, the variable `initialAdvance` does not exist.

In nfa_advance_var, after the first Assert, we can add:
Assert(elem->next <  pattern->numElements);

ExecRPRFinalizeAllContexts seems unnecessary; I commented it out,
rerun the regress tests
(TESTS='test_setup rpr_base rpr_nfa rpr_explain rpr_integration rpr'
meson test -C $BUILD3 --num-processes 20 --suite regress --verbose)
Only two SQL tests in rpr_explain.sql failed.

SELECT first_value(id) OVER w AS match_start FROM stock_ticks
WINDOW w AS ( ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED
FOLLOWING AFTER MATCH SKIP PAST LAST ROW PATTERN ((A B) {2}) DEFINE A
AS price < 100, B AS price < 100);

The query above invokes the following code. Since the PATTERN above is
not greedy, is the comment below incorrect?
``````
    else
    {
        /* Greedy: enter first, skip second */
        state->elemIdx = elem->next;
        nfa_route_to_elem(winstate, ctx, state,
                          &elements[state->elemIdx], currentPos);
        if (skipState != NULL)
        {
            nfa_route_to_elem(winstate, ctx, skipState,
                              &elements[elem->jump], currentPos);
        }
    }
``````

nfa_advance_var
```
    else if (canExit)
    {
        state->counts[depth] = 0;
        state->elemIdx = elem->next;
        nextElem = &elements[state->elemIdx];
        /*
         * Update isAbsorbable for target element (monotonic: AND preserves
         * false)
         */
        state->isAbsorbable = state->isAbsorbable &&
            RPRElemIsAbsorbableBranch(nextElem);
        /* See comment above: increment outer END count for quantified VARs */
        if (RPRElemIsEnd(nextElem))
        {
            if (state->counts[nextElem->depth] < RPR_COUNT_MAX)
                state->counts[nextElem->depth]++;
        }
        nfa_route_to_elem(winstate, ctx, state, nextElem, currentPos);
    }
```
The above ELSE IF overrides all RPRNFAState field values except
RPRNFAState->next.
Should we set RPRNFAState->next to NULL?
(If I add ``state->next = NULL;`` in the above ELSE IF branch, all the
regress tests still pass)
Some comments about the situation of (RPRNFAState) state->next would be great.
This also happens in `` if (canLoop && canExit)``, ``if (reluctant)`` branch.

For function nfa_advance_var, I don't understand the meaning of the
variable "count", after the first Assert I have added below:

    if (count > 2 && !state->isAbsorbable && RPRElemIsReluctant(elem))
        elog(INFO, "count is %d and elem is reluctant and isAbsorbable
is false XXXXX", count);
    if (count > 2 && state->isAbsorbable && RPRElemIsReluctant(elem))
        elog(INFO, "count is %d and elem is reluctant and isAbsorbable
is true XXXXX", count);

Rerunning the regress tests shows that count >= 3 occurs very infrequently.
I'm don't understand isAbsorbable, so I am not sure if the second
``elog(INFO`` is actually reachable or not.
Can we add more complex queries (more count >= 3) to check if the
"count" variable is working correctly?


In function nfa_add_state_unique:
    /* Mark VAR in visited before duplicate check to prevent DFS loops */
    winstate->nfaVisitedElems[WORDNUM(state->elemIdx)] |=
        ((bitmapword) 1 << BITNUM(state->elemIdx));

I honestly don't understand the purpose of the code block above. But it doesn't
seem to influence the subsequent FOR LOOP;
It only modifies its own variables without any other side effects within
nfa_add_state_unique. Could we add some comments explaining which external
functions rely on this code and why it belongs in nfa_add_state_unique?


nfa_states_equal
compareDepth = elem->depth + 1; /* depth 0 needs 1 count, etc. */
The comment above isn't helpful, IMHO, and I don't understand it.
We should focus on why compareDepth should be ```elem->depth + 1```.


function nfa_add_state_unique return value is not being used?
Do we need to do something with the return value, or is this expected?
(I don't have an opinion on it, I guess it would be better to raise this issue)


In nfa_advance_alt, during the main WHILE loop, I think altElem->depth
must be larger than elem->depth.
Therefore we can do
``````
        if (altElem->depth == elem->depth)
            elog(ERROR, "nfa_advance_alt altElem->depth should not be
the same as elem->depth reached");
        if (altElem->depth < elem->depth)
            break;
``````



--
jian
https://www.enterprisedb.com/


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo, jian,

While looking into v47, I noticed that
raw_expression_tree_walker_impl() lacks tracking RPCommonSyntax and
its children nodes. Probably this does nothing wrong with RPR
functionalities but just for completeness I created a patch on top of
v47.

Thanks for catching this. I applied the patch and the RPR regress passes
cleanly. I also re-ran it with debug_raw_expression_coverage_test turned
on (on an assert-enabled build), and the full regress is green as well.

One observation while testing: the GUC catches missing case handlers
once the walker actually reaches a node, but it cannot flag a missing
WALK on its own -- if no caller drives the walker into a subtree, the
omission stays silent. So your inspection was the part that found the
gap; the GUC just confirms the patch closes it. With the patch in, RPR
raw subtrees are on the safety net for any future node-type additions.

I'll include the patch in v48 as nocfbot-0015. My suggestion would
be to defer the fold until the jian-response patches (numbered from
0016 onward, which I'll be sending shortly) have also gone through a
review round, so the whole bundle can land together in one pass.
Patch attached below for convenience.


jian -- thanks for the thorough review. It covers a lot of ground,
and I'm still working through it. Current expectation is that most
items will be accepted; a few smaller ones may end up with a
different conclusion than your suggestion, and those are still under
analysis on my side.

The plan is to turn the responses into a patch series and send them
out for another round of review. More to follow once the batch is in
shape.


Thanks,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Thanks for catching this. I applied the patch and the RPR regress passes
> cleanly. I also re-ran it with debug_raw_expression_coverage_test turned
> on (on an assert-enabled build), and the full regress is green as well.
> 
> One observation while testing: the GUC catches missing case handlers
> once the walker actually reaches a node, but it cannot flag a missing
> WALK on its own -- if no caller drives the walker into a subtree, the
> omission stays silent. So your inspection was the part that found the
> gap; the GUC just confirms the patch closes it. With the patch in, RPR
> raw subtrees are on the safety net for any future node-type additions.

Thanks for checking.

> I'll include the patch in v48 as nocfbot-0015. My suggestion would
> be to defer the fold until the jian-response patches (numbered from
> 0016 onward, which I'll be sending shortly) have also gone through a
> review round, so the whole bundle can land together in one pass.
> Patch attached below for convenience.

Sure. I will wait for your ready-to-go signal before creating the v48
pach set.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

In src/include/nodes/execnodes.h, we're adding quite a few fields to
WindowAggState that are only used for RPR queries.
Should we consolidate these fields behind a single pointer (named
RPRContext) to keep the WindowAggState size smaller for non-RPR
queries?

In function get_reduced_frame_status, I made the following changes:
``````
bool conditionA;
bool conditionB;
bool conditionC;
bool conditionD;
if (!winstate->rpr_match_valid)
    return RF_NOT_DETERMINED;
conditionA = (pos == start && winstate->rpr_match_matched && length == 0);
conditionB = (pos < start || pos >= start + length);
conditionC = !winstate->rpr_match_matched;
conditionD = (pos == start);
if ((conditionA && conditionB) || (conditionA && conditionC) ||
    (conditionA && conditionD))
{
    if (conditionA)
        elog(INFO, "conditionA is true");
    if (conditionB)
        elog(INFO, "conditionB is true");
    if (conditionC)
        elog(INFO, "conditionC is true");
    if (conditionD)
        elog(INFO, "conditionD is true");
}
if ((conditionB && conditionC) || (conditionB && conditionD) ||
(conditionC && conditionD))
{
    elog(INFO, "more than 2 branch is true, should not be reached");
    if (!(conditionC && conditionD))
        elog(INFO, "not (conditionCD is true)");
    if ((conditionB && conditionD))
        elog(INFO, "conditionB and conditionD is true)");
}
``````
I re-ran the regression tests and noticed it's entirely possible for multiple
conditions to be true at once. Because of this, all the IF blocks in
get_reduced_frame_status (after the initial one) are order-dependent. If I move
one IF statement above another, get_reduced_frame_status may return a
different result.
Is this the expected behavior? It seems like a potential logic flaw.

------------------------------------------------------------------------------------
VIII-3. Absorption Conditions

Planner-time prerequisites (all must hold for absorption to be enabled):

  (a) SKIP PAST LAST ROW.  SKIP TO NEXT ROW creates overlapping
      contexts that cannot be safely absorbed.
  (b) Unbounded frame (ROWS BETWEEN CURRENT ROW AND UNBOUNDED
      FOLLOWING).  Limited frames apply differently to each context,
      breaking the monotonicity principle.
  (c) No match_start-dependent navigation in DEFINE.

      Mechanism: each context has a different matchStartRow, so FIRST
      resolves to a different row for each context at the same
      currentpos.  An earlier context's DEFINE result no longer
      subsumes a later one's, making count-dominance comparison
      invalid.  Rather than comparing matchStartRow at runtime
      (which would complicate the absorb path), any match_start
      dependency disables absorption entirely.

      Navigation content              match_start dep.  absorption
      ------------------------------------------------------------
      No navigation                   none              safe
      PREV/NEXT only                  none              safe
      LAST (no offset)                none              safe
      LAST (with offset)              boundary check    unsafe
      FIRST (any)                     direct            unsafe
      Compound (inner FIRST)          direct            unsafe
      Compound (inner LAST, no off.)  none              safe
      Compound (inner LAST, w/off.)   boundary chk      unsafe
------------------------------------------------------------------------------------
"boundary chk" should be "boundary check".
column "match_start dep.", I don't understand the meaning of "direct"
and "boundary check".
"count-dominance" seems like an invented word, but I could not find
the explanation.
"match_start-dependent" occurred many times, it would also deserve an
explanation.
We can also rename it as match_start_dependent.

----------------------------------------------------
Attached is a minor refactoring of ExecRPRProcessRow, no need for
boolean hasLimitedFrame.
``if (hasLimitedFrame && winstate->endOffsetValue != 0)`` seems wrong
to me, endOffsetValue is a Datum,
and you directly compare it with 0.
see also calculate_frame_offsets.
----------------------------------------------------
ExecRPRProcessRow,
nfa_evaluate_row
```
  if (!window_gettupleslot(winobj, pos, slot))
        return false;            /* No row exists */
```
indicates that it's not possible for (currentPos > ctxFrameEnd).
therefore
`````
    if (currentPos >= ctxFrameEnd)
    {
        /* Frame boundary exceeded: force mismatch */
        nfa_match(winstate, ctx, NULL);
        continue;
    }
`````
should change to ```if (currentPos == ctxFrameEnd)```.
With that, the comment wording "exceeded" seems wrong too.

The comment 'Frame boundary exceeded' also needs updating since
it's no longer exceeding the boundary.
----------------------------------------------------
Since I couldn't generate a coverage report, I am using elog(INFO) to test
reachability. Rerun the regress tests, you will find out that the ELSE IF branch
below is not reached by current regress tests.
``````
    else if (targetCtx->states == NULL)
    {
        /* Context already completed - skip to result registration */
        goto register_result;
        elog(INFO, "XXXX reached");
    }
``````



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian, Tatsuo,

Jian, your review keeps paying off beyond the items themselves.  Working
through the ExecRPRProcessRow refactor you proposed -- dropping
hasLimitedFrame and fixing the "endOffsetValue != 0" Datum-vs-0
comparison -- and writing the offset-0 regression test it calls for sent
me back to the standard, where I hit a conformance reading I'd value both
of your judgments on.

The case is the single-row full window frame.  It has two spellings,
semantically identical -- both make the full window frame exactly the
current row:

    ROWS BETWEEN CURRENT ROW AND CURRENT ROW
    ROWS BETWEEN CURRENT ROW AND 0 FOLLOWING

PostgreSQL accepts both today (rpr_base tests the 0 FOLLOWING form with
PATTERN (A)).  But I'm no longer sure either is sanctioned by Subclause
6.10.2, "ROWS BETWEEN CURRENT ROW AND", which reads (paraphrasing
ISO/IEC 19075-5):

  "When performing row pattern recognition in a window, only two options
   are allowed for specifying the window frame extent:
     - ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
     - ROWS BETWEEN CURRENT ROW AND offset FOLLOWING ... [the offset]
       shall be a positive integer ..."

Two things put the single-row frame outside a literal reading, and they
hit both spellings equally:

  - CURRENT ROW as the *end* bound is not one of the two listed options;
    and

  - the offset form requires a *positive integer*, and 0 is not positive
    -- so AND 0 FOLLOWING is no better sanctioned than AND CURRENT ROW.

The two spellings therefore stand or fall together: they denote the same
one-row frame, and neither is literally among 6.10.2's options.
(README.rpr X-4 already follows the strict line -- it lists only
"UNBOUNDED FOLLOWING or n FOLLOWING".)

Either way the behavior is unambiguous: a single-row search space, so the
pattern can only ever map the current row.  That makes it a degenerate,
WHERE-like use rather than real row-pattern matching -- which one might
read as benign (so allow) or as pointless (so reject), so it doesn't
settle the question for me.

This is, in effect, a borderline, harmless standard violation: it sits
just outside 6.10.2 as written, yet is well-defined, runs cleanly, and
leaves every conforming frame unchanged.

So, concretely, the choice:

  (a) Allow it -- accept both spellings and document the degenerate
      frame as a deliberate extension; or

  (b) Forbid it -- follow 6.10.2 to the letter ("only two options" and a
      "positive integer" offset) and reject both spellings in
      transformRPR().

Which reading do you take?  Tatsuo, as co-author your call carries it;
Jian, I'd value yours too, since you were just in this code.

This isn't blocking.  The implementation accepts offset 0 today, so for
now my regression test exercises it (via the 0 FOLLOWING spelling, as
rpr_base already does); if the answer is (b), that test and the existing
one become error tests together.

Thanks,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Jian, Tatsuo,
> 
> Jian, your review keeps paying off beyond the items themselves.  Working
> through the ExecRPRProcessRow refactor you proposed -- dropping
> hasLimitedFrame and fixing the "endOffsetValue != 0" Datum-vs-0
> comparison -- and writing the offset-0 regression test it calls for sent
> me back to the standard, where I hit a conformance reading I'd value both
> of your judgments on.
> 
> The case is the single-row full window frame.  It has two spellings,
> semantically identical -- both make the full window frame exactly the
> current row:
> 
>     ROWS BETWEEN CURRENT ROW AND CURRENT ROW
>     ROWS BETWEEN CURRENT ROW AND 0 FOLLOWING
> 
> PostgreSQL accepts both today (rpr_base tests the 0 FOLLOWING form with
> PATTERN (A)).  But I'm no longer sure either is sanctioned by Subclause
> 6.10.2, "ROWS BETWEEN CURRENT ROW AND", which reads (paraphrasing
> ISO/IEC 19075-5):
> 
>   "When performing row pattern recognition in a window, only two options
>    are allowed for specifying the window frame extent:
>      - ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>      - ROWS BETWEEN CURRENT ROW AND offset FOLLOWING ... [the offset]
>        shall be a positive integer ..."
> 
> Two things put the single-row frame outside a literal reading, and they
> hit both spellings equally:
> 
>   - CURRENT ROW as the *end* bound is not one of the two listed options;
>     and
> 
>   - the offset form requires a *positive integer*, and 0 is not positive
>     -- so AND 0 FOLLOWING is no better sanctioned than AND CURRENT ROW.
> 
> The two spellings therefore stand or fall together: they denote the same
> one-row frame, and neither is literally among 6.10.2's options.
> (README.rpr X-4 already follows the strict line -- it lists only
> "UNBOUNDED FOLLOWING or n FOLLOWING".)
> 
> Either way the behavior is unambiguous: a single-row search space, so the
> pattern can only ever map the current row.  That makes it a degenerate,
> WHERE-like use rather than real row-pattern matching -- which one might
> read as benign (so allow) or as pointless (so reject), so it doesn't
> settle the question for me.
> 
> This is, in effect, a borderline, harmless standard violation: it sits
> just outside 6.10.2 as written, yet is well-defined, runs cleanly, and
> leaves every conforming frame unchanged.
> 
> So, concretely, the choice:
> 
>   (a) Allow it -- accept both spellings and document the degenerate
>       frame as a deliberate extension; or
> 
>   (b) Forbid it -- follow 6.10.2 to the letter ("only two options" and a
>       "positive integer" offset) and reject both spellings in
>       transformRPR().
> 
> Which reading do you take?  Tatsuo, as co-author your call carries it;
> Jian, I'd value yours too, since you were just in this code.
> 
> This isn't blocking.  The implementation accepts offset 0 today, so for
> now my regression test exercises it (via the 0 FOLLOWING spelling, as
> rpr_base already does); if the answer is (b), that test and the existing
> one become error tests together.

I vote for (b).

Reason 1: (a) does not give clear benefit to users.

Reason 2: we haven't implemented some large features yet (MEASURES
etc.)  If we follow (a), we may have to add more code to support it
in the process of implementing MEASURES when they are not necessary if
we had chosen (b).

Reason 3: In the future, we may find an optimization if 0 FOLLOWING is
prohibited.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

-- Consecutive VAR merge: A A+ -> a{2,}
-- Tests line 251: child->max == RPR_QUANTITY_INF branch in mergeConsecutiveVars
-- prev: A{1,1} (finite), child: A+ (infinite) triggers line 251 evaluation
EXPLAIN (COSTS OFF)
SELECT COUNT(*) OVER w FROM rpr_plan
WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
             PATTERN (A A+) DEFINE A AS val > 0);

-- Consecutive VAR merge: A A+ -> a{2,}
-- Tests line 251: child->max == RPR_QUANTITY_INF branch in mergeConsecutiveVars
-- prev: A{1,1} (finite), child: A+ (infinite) triggers line 251 evaluation
EXPLAIN (COSTS OFF)
SELECT COUNT(*) OVER w FROM rpr_plan
WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
             PATTERN (A A+) DEFINE A AS val > 0);

Comments like "Tests line 251" should not appear in SQL, since the
line number would change.
So, we need to rephrase this comment. Please don't delete it, it may
clarify the patch for future readers.


/*
 * nfa_add_state_unique
 *
 * Add a state to ctx->states at the END, only if no duplicate exists.
 * Returns true if state was added, false if duplicate found (state is freed).
 * Earlier states have better lexical order (DFS traversal order), so
existing wins.
 */
static bool
nfa_add_state_unique(WindowAggState *winstate, RPRNFAContext *ctx,
RPRNFAState *state)

The "at the END" confuses me. It may also refers to RPR_VARID_END /
RPRElemIsEnd.
How about something like:
"Add the state to the end of the ctx->states linked list, but only if
a duplicate state is not already present."

I think a bunch of these uppercase ENDs should just be lowercase "end",
capitalizing them may collides visually with RPR_VARID_END and RPRElemIsEnd and
makes the comments harder to read.

In nfa_match:
"Non-VAR elements (ALT, END, FIN) are kept as-is for advance phase."

Here END does mean RPRElemIsEnd, right? That one's probably fine as uppercase
since it's listed alongside other element kinds.

But then:
/*
 * Evaluate VAR elements against current row. For VARs that reach max
 * count with END next, advance through END chain inline so absorb phase
 * can compare states at judgment points.
 */
I'm think END here means the tail of the RPRNFAContext->RPRNFAState linked
list, not the element kind -- which is exactly the ambiguity I'm worried about.

Could we lowercase the list-end ones and keep uppercase only when actually
referring to the END element kind?


The comment under nfa_advance_var is confusing (for me).
/* After a successful match, count >= 1, so at least one must be true */

nfa_advance_var doesn't actually know anything about match status (i
think), it can be reached with count == 0.
I added this elog(INFO) to confirm:
    if (count < 1 && currentPos > -1)
        elog(INFO, "should not reach, count is %d, currentPos=%ld",
count, currentPos);

...and it does fire, so the comment's premise isn't quite right.

------------------------------------------------
please check the attached minor refactoring.
1.  Refactor struct WindowAggState: Remove the nfaStateSize and nfaVisitedNWords
fields because they are constant, and we can easily compute it, seems
not necessary to stay in WindowAggState.

2. Rename nfa_context_alloc() to nfa_context_make(), nfa_state_alloc()
to nfa_state_make(), nfa_state_create() to nfa_state_clone().
Rationale: We have makeNode, changing "alloc" to "make" would be more
intuitive, IMHO.
In tablecmd.c, we have CloneForeignKeyConstraints, which is based on
existing information, creating a new node, here we are doing the same
in
nfa_state_create.

3. Refactor functions: nfa_advance_alt, nfa_advance_begin,
nfa_advance_end, and nfa_advance_var.
Because the (RPRPatternElement *elem) parameter is unnecessary.



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
[mailing-list reply draft -- pgsql-hackers, RPR thread.
 In-reply-to Jian's round-3 review, 2026-05-30 06:45
 (Message-ID CACJufxEsaU8GQ4yeXTWhAO8VjbrZTh5CpvUqz=4a3T0Cwz44pA@mail.gmail.com).
 Covers R3-1..R3-4 (comments) and the three attached refactors R3-5a/b/c.
 All accepted; fold into the v48 refactor series.]

Subject: Re: Row pattern recognition

Hi Jian,

Thanks for the round-3 pass -- all seven are good catches. Going through
them inline below, with a summary of decisions at the end.

> Comments like "Tests line 251" should not appear in SQL, since the
> line number would change.
> So, we need to rephrase this comment. Please don't delete it, it may
> clarify the patch for future readers.

Agreed on both counts -- the intent (this case exercises the
child->max == RPR_QUANTITY_INF branch in mergeConsecutiveVars, where a
finite prev meets an infinite child) is worth keeping; only the "line 251"
anchor is fragile. I'll rephrase it to name the branch and the condition
it covers instead of the line, so it survives any later shuffle.

There's a parallel one a few tests down -- "Tests line 325 ... in
mergeConsecutiveGroups" -- with the same problem, so I'll fix both
together on the same principle.

> The "at the END" confuses me. It may also refers to RPR_VARID_END /
> RPRElemIsEnd.
> How about something like:
> "Add the state to the end of the ctx->states linked list, but only if
> a duplicate state is not already present."

Your wording is clearer than mine -- I'll take it almost verbatim. "at the
END" there meant the list tail, and capitalizing it was exactly the wrong
choice next to the END element kind.

> I think a bunch of these uppercase ENDs should just be lowercase "end",
> [...]
> Could we lowercase the list-end ones and keep uppercase only when actually
> referring to the END element kind?

Yes -- that's the right rule, and I'll go through them on it: lowercase
"end" for the linked-list tail, uppercase END only when it means the
element kind (RPRElemIsEnd / RPR_VARID_END). On the two you singled out:

  - nfa_match, "Non-VAR elements (ALT, END, FIN) ..." -- element kind,
    listed with the others, stays uppercase. Agreed.

  - "advance through END chain inline ..." -- this one is actually the
    element kind too: it walks the chain of group-END *elements* up to the
    absorption judgment point, not the state list. So it stays uppercase,
    but since it tripped you up I'll reword it to "chain of END elements"
    to make that unambiguous rather than leaning on the reader to infer it.

> The comment under nfa_advance_var is confusing (for me).
> /* After a successful match, count >= 1, so at least one must be true */
> nfa_advance_var doesn't actually know anything about match status (i
> think), it can be reached with count == 0.
> [...] and it does fire, so the comment's premise isn't quite right.

You're right, and thanks for confirming it with the elog. nfa_advance_var
is part of the advance phase, which generates every reachable next state
regardless of what matched -- so it's routinely entered with count == 0,
for a VAR just reached through an ALT branch or a group that hasn't been
evaluated yet. The comment carries match-phase reasoning into a phase that
has no notion of matching. The Assert above still holds, but on the
structure of a VAR's bounds, not on any prior match, so I'll reword the
comment to say that instead.

> please check the attached minor refactoring.
> 1.  Refactor struct WindowAggState: Remove the nfaStateSize and
>     nfaVisitedNWords fields because they are constant, and we can easily
>     compute it, [...] not necessary to stay in WindowAggState.
> 2. Rename nfa_context_alloc() to nfa_context_make(), nfa_state_alloc()
>    to nfa_state_make(), nfa_state_create() to nfa_state_clone().
>    Rationale: We have makeNode [...]. In tablecmd.c, we have
>    CloneForeignKeyConstraints, which is based on existing information,
>    creating a new node, here we are doing the same in nfa_state_create.
> 3. Refactor functions: nfa_advance_alt, nfa_advance_begin,
>    nfa_advance_end, and nfa_advance_var. Because the
>    (RPRPatternElement *elem) parameter is unnecessary.

Looked at all three. 0002 and 0003 I'll take; 0001 I'd split.

  1. The two fields differ. nfaVisitedNWords -- yes: in the current tree
     it's read only once, at init, to size the visited bitmap, since the
     per-row reset clears just the high-water [min,max] range. Demoting it
     to a local is clean. (Heads up: the patch is on v47, before that
     high-water-mark change, so its nfa_advance hunk no longer applies and
     drops out on rebase.)

     nfaStateSize I'd keep. The patch recomputes it inside the allocator,
     i.e. on every state allocation -- the hottest path in the engine; a
     pathological (V1|...|Vk)* can allocate hundreds of millions of states.
     It's a loop-invariant fixed at init, so I'd rather keep it precomputed
     than rebuild offsetof + maxDepth*4 each alloc -- the same reasoning I
     gave for keeping the frame offsets out of the per-row loop.

  2. make/clone: agreed, and there's a closer precedent than I'd have
     reached for -- our own regex NFA engine already clones states
     (clonesuccessorstates / cloneouts in regcomp.c), so clone is the right
     word for duplicating an NFA state, not just the CloneForeignKey sense.
     The pair reads well too: make for the blank allocation, clone for
     building a state from an existing one's counts. (create was itself an
     earlier rename of mine from clone "for clarity," so this just lands us
     back on clone, which I now agree is better.) When I apply it I'll also
     tidy two comments the rename left behind -- the nfa_state_make header
     now reads "a new RPRNFAState state," and nfa_state_clone's body comment
     still says "Create."

  3. elem parameter: here I'd keep it, on the same grounds as nfaStateSize.
     The four functions have a single caller, nfa_advance_state, which
     already computes elem = &elements[state->elemIdx] for its own
     mark-visited check and switch, and hands it down. Dropping the
     parameter makes each function rebuild that same address on the
     per-dispatch advance path -- discarding a value the caller already
     holds. And with one trusted caller, the mismatch the change guards
     against can't really arise. The cost either way is tiny; I'd just
     rather keep the value flowing from where it's already computed than
     recompute it, which is the same call I made on nfaStateSize.

Summary of decisions, in the order above:

  "Tests line N" test comments     Rephrase -- name the branch, not the line (both)
  "at the END" wording             Accept -- your wording, near-verbatim
  uppercase END cleanup            Accept -- lowercase the list-end ones, keep the kind
  nfa_advance_var count comment    Reword -- wrong premise; state the structural reason
  0001 nfaVisitedNWords            Accept -- demote to a local
  0001 nfaStateSize                Keep -- hottest path; leave it precomputed
  0002 make / clone rename         Accept -- plus tidy two stray comments
  0003 drop the elem parameter     Keep -- single caller already holds it

So the next revision carries the four comment fixes, 0002, and the
nfaVisitedNWords half of 0001; nfaStateSize and the elem parameter I'd keep
as they are. Happy to be talked round on either if you see a cost I'm
missing.

Thanks again,
Henson

Re: Row pattern recognition

Hi all,

Resolved since the last post:

  D1. Single-row frame conformance, Subclause 6.10.2 -- Tatsuo's call [6]
      was to reject. Both ROWS BETWEEN CURRENT ROW AND CURRENT ROW and
      AND 0 FOLLOWING are now rejected (nocfbot-0025), which in turn
      unblocks the held ExecRPRProcessRow change (nocfbot-0026).

Open decisions (repeated with context at the end):

  D2. The RPRContext consolidation -- Tatsuo's call as co-author;
      non-blocking either way [4].
  D3. The AST "absorption" rename -- Tatsuo's call [2].

  [1] Jian's review, round 1 (2026-05-26):
      https://postgr.es/m/CACJufxH-DZePhbdJM=8nNYceQiSbbXXLTw54iLhxiynQ+4hbBA@mail.gmail.com
  [2] my round-1 reply -- AST "absorption" rename deferred to Tatsuo (D3, 2026-05-27):
      https://postgr.es/m/CAAAe_zDephfiDA_A3FN0hCymJRogEr=Rt3QoCTf4qMYDLk+xNA@mail.gmail.com
  [3] Jian's review, round 2 (2026-05-28):
      https://postgr.es/m/CACJufxGX17thWuEOq1tM5xbRHz2HXm1asooZC3GV25MYGmYqLQ@mail.gmail.com
  [4] my round-2 reply -- RPRContext deferred to Tatsuo (D2, 2026-05-29):
      https://postgr.es/m/CAAAe_zAH0MvP0TBmW3PTLeHjEpiyBz0473zJRM9pwLpseefMNw@mail.gmail.com
  [5] single-row frame conformance question (D1, 2026-05-29):
      https://postgr.es/m/CAAAe_zCbSU=dd-4qTL2QaBQwQ-cf51N_851a9Y5rOoz0wj0aXw@mail.gmail.com
  [6] Tatsuo's reply -- reject single-row frames (D1 resolved, 2026-05-30):
      https://postgr.es/m/20260530.114737.1416684464524168377.ishii@postgresql.org
  [7] Jian's review, round 3 (2026-05-30):
      https://postgr.es/m/CACJufxEsaU8GQ4yeXTWhAO8VjbrZTh5CpvUqz=4a3T0Cwz44pA@mail.gmail.com

Attached: the v47 feature series (v47-0001..0009) rebased onto current
master, plus the incremental patch series carried on top of it.

Base:

  9a41b34a287  2026-05-26  doc:  add comma to UPDATE docs, for consistency

Unchanged -- rebase only (already posted; only rebased, no content change).
Titles for reference:

  nocfbot-0001  Add DEFINE non-volatile baseline to rpr_integration B9
  nocfbot-0002  Unify RPR DEFINE walkers and reject volatile callees
  nocfbot-0003  Cover RPR empty-match path with EXPLAIN tests; fix stale XXX comments
  nocfbot-0004  Reclassify DEFINE qualifier check and reword diagnostic to "expression"
  nocfbot-0005  Sync stale comments on DEFINE/PATTERN handling
  nocfbot-0006  Add trailing commas to RPR enum definitions
  nocfbot-0007  Remove optional outer parentheses from ereport() calls in RPR files
  nocfbot-0008  Add high-water mark tracking to NFA visited bitmap reset
  nocfbot-0009  Document DEFINE subquery rejection as intentional over-rejection
  nocfbot-0010  Remove duplicate #include in nodeWindowAgg.c
  nocfbot-0011  Normalize SQL/RPR standard references
  nocfbot-0012  Add rpr_integration B7 cases for RPR in recursive query
  nocfbot-0013  Reject row pattern recognition in recursive queries
  nocfbot-0014  Enhance README.rpr per Tatsuo Ishii's review
  nocfbot-0015  Round out README.rpr WindowAggState field coverage
  nocfbot-0016  Add raw_expression_tree_walker coverage for RPR raw nodes

  (nocfbot-0016 was sent earlier as 0015; renumbered here so the review
  series runs contiguously from 0017.)

New incremental patches -- nocfbot-0017 onward. These apply Jian He's
review (rounds 1 [1] and 2 [3]) and settle D1. nocfbot-0017..0024 and
0026 are comment / doc / test plus a signature change and a couple of
Assert additions -- no behavior change. nocfbot-0025 is the one
user-visible change: it rejects the single-row frame per D1 [6].

  nocfbot-0017  Enhance README.rpr
      Chapter VIII absorption intro + a worked PATTERN (A+) trace;
      "Depth-First Search" spelled out at first use; the stale
      nfa_advance(initialAdvance=...) reference replaced.

  nocfbot-0018  Clarify execRPR.c comments and tighten an Assert
      Document the NFA invariants (compareDepth slot arithmetic, the
      asymmetric visited-marking scheme, the greedy/non-nullable BEGIN
      label, the ALT depth break, the state->next reset boundary),
      reframe ExecRPRFinalizeAllContexts as the partition-end policy
      holder, and add a defensive Assert in nfa_advance_var.

  nocfbot-0019  nfa_add_state_unique: bool return -> void
      The return value was unused.

  nocfbot-0020  Reluctant bounded mid-band test (rpr_nfa)
      A{3,5}? B, which drives the VAR-level count in nfa_advance_var
      through 3..5.

  nocfbot-0021  Define RPR absorption terminology in README.rpr
      Terminology block for the "match_start dep." column (none /
      direct / boundary check), the "boundary chk" typo fix, the
      count-dominance definition, and the match_start_dependent rename.

  nocfbot-0022  Document the get_reduced_frame_status cascade invariant
      The branches form an order-dependent early-return cascade; the
      running invariant is spelled out so the order reads as intentional.

  nocfbot-0023  Explain the completed-head-context branch in
                update_reduced_frame
      Why a head context can already be complete under SKIP TO NEXT ROW.

  nocfbot-0024  Tighten the frame-boundary check from >= to ==
      The > case is unreachable by the loop invariant; the defense moves
      into an Assert(currentPos <= ctxFrameEnd), and the comment changes
      from "exceeded" to "reached".

  nocfbot-0025  Reject single-row window frame in row pattern recognition
      Per D1 [6], the frame end must be UNBOUNDED FOLLOWING or a positive
      offset FOLLOWING. CURRENT ROW is rejected in transformRPR() at parse
      time; a zero offset -- which need not be a constant -- in
      calculate_frame_offsets() at run time. The two single-row rpr_base
      tests become error cases, with a bind-parameter error test added.

  nocfbot-0026  Remove the redundant zero check on the RPR frame ending
                offset
      With the single-row frame now rejected, a limited frame always
      carries a real offset, so the "endOffsetValue != 0" guard -- which
      compared a Datum directly to zero -- is dropped, leaving a plain
      DatumGetInt64(). This is the offset half of Jian's ExecRPRProcessRow
      cleanup; the structural half (dropping the hasLimitedFrame
      parameter) I've left as-is -- it is loop-invariant and computed once
      outside the per-row loop, so moving it into ExecRPRProcessRow would
      just repeat the work each row.

Coverage -- my decision summaries [2], [4], with the patch each became:

  Round 1 [2]
    Short-circuit optimization       Separate series   -> separate series
    Absorption README narrative      Accept            -> nocfbot-0017
    AST-level "absorption" rename    Pending Tatsuo    -> D3
    DFS expansion                    Accept            -> nocfbot-0017
    initialAdvance README mismatch   Accept            -> nocfbot-0017
    Defensive Assert in advance_var  Accept            -> nocfbot-0018
    Finalize unnecessary?            Keep              -> nocfbot-0018
    Greedy comment label             Accept            -> nocfbot-0018
    state->next reset                Decline           -> nocfbot-0018
    count >= 3 test coverage         Accept            -> nocfbot-0020
    visited marking purpose          Accept            -> nocfbot-0018
    compareDepth comment             Accept            -> nocfbot-0018
    Unused bool return               Accept            -> nocfbot-0019
    ALT depth invariant Assert       Decline           -> nocfbot-0018

  Round 2 [4]
    RPRContext consolidation         Tatsuo's call     -> D2
    get_reduced_frame_status order   Keep              -> nocfbot-0022
    README terminology + typo        Accept            -> nocfbot-0021
    ExecRPRProcessRow refactor       Datum fix only    -> nocfbot-0026
    single-row frame (6.10.2, D1)    Reject (Tatsuo)   -> nocfbot-0025
    currentPos >= -> ==              Accept            -> nocfbot-0024
    states == NULL branch coverage   Already reached   -> nocfbot-0023

Remaining work and decisions

  Decisions (need your input):
    D2  RPRContext consolidation -- Tatsuo.
    D3  AST "absorption" rename -- Tatsuo.

  Held pending a decision:
    - the RPRContext consolidation itself -- done if D2 says go.
    - the AST "absorption" rename itself -- done if D3 says go.

  (D1 settled: the parse-time frame-end check, the offset-0 test as an
   error case, and the Datum-comparison fix are now in nocfbot-0025/0026.)

  From Jian's round-3 review [7] (into the next revision):
    - four comment fixes: the line-number test anchors, the "at the END"
      and uppercase-END wording, and the nfa_advance_var count premise.
    - the make/clone rename of the NFA helpers (one of three attached
      refactors); the other two -- dropping nfaStateSize and the elem
      parameter -- I'd keep, both on hot-path grounds.

  From our in-house review (separate follow-ups):
    - a quantifier-normalization correctness fix (nested unbounded
      quantifiers such as (A{2,})* are currently mis-normalized)
    - a per-tuple memory-context fix in DEFINE evaluation (still verifying)
    - smaller correctness/conformance fixes (an overflow guard, a few
      missing parse-time checks, EXPLAIN output details)
    - documentation gaps (comments, README, SGML)
    - added regression tests (round-trip deparse, edge-case offsets)

  Before the v48 fold (from Jian's off-list comments):
    - INT_MAX -> PG_INT32_MAX (the unbounded-quantifier sentinel; ~24 sites)
    - foreach + lfirst() -> foreach_node (~33 sites)
    - foreach_current_index, dropping the redundant break (3 sites)

  Work, no decision needed:
    - short-circuit (lazy eval) -- stop evaluating a DEFINE predicate
      once its outcome is fixed. A separate series.
      It turns on a standard-interpretation point -- whether skipping is
      sound when a dropped subexpression has side effects.

Thanks again to Jian for the careful reading.

Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson, Jian,

>> In src/include/nodes/execnodes.h, we're adding quite a few fields to
>> WindowAggState that are only used for RPR queries.
>> Should we consolidate these fields behind a single pointer (named
>> RPRContext) to keep the WindowAggState size smaller for non-RPR
>> queries?
> 
> The size win is real -- it's roughly 450-500 bytes per WindowAggState
> that every non-RPR window query carries today. But it takes a wide
> code change to get there: it reshapes every RPR access path, a
> sizable (if mostly mechanical) diff across nodeWindowAgg.c,
> execRPR.c, and the explain side.
> 
> Tatsuo, as co-author -- do you want this in v48? If you do, I'll
> prepare the RPRContext consolidation as an incremental patch for you to
> fold into v48. It isn't blocking either way.

Basically I think Jian's idea is good. In addition to the size reason
above, we would have less code changes when we adapt existing R020
codes to R010.

However it will need a wide code change as Henson said. I would like
to focus on stabilizing our code for now. Therefore I would not want
the refactoring in v48.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> For src/backend/executor/README.rpr:
>> We should explicitly explain 'absorbable' and 'absorption' somewhere in
>> README.rpr, as the text currently just assumes the reader knows what they
> mean.
>> Using some example illustrate "absorption" meaning, put it on
>> README.rpr would be great.
>> We can also mention that 'DFS' refers to Depth-First Search".
> 
> Acknowledged, and the request surfaced an underlying problem in the
> README's terminology. "Absorption" is currently used for two
> distinct things: an AST-level rewrite in Phase 1 that pulls
> identical sequences around a group inside it, and the runtime
> context-equivalence collapse that drives the O(n^2) -> O(n)
> optimization. Sharing the word leaves a reader encountering
> "absorbable" early on without an anchor.
> 
> Rather than disambiguate by qualifier ("prefix/suffix absorption"
> vs "context absorption"), I'd lean toward renaming the AST-level
> case so "absorption" stays reserved for the runtime concept. The
> README then only needs to explain absorption in one place, in
> detail, without the disambig preamble.
> 
> For the rename, "prefix/suffix merging" feels like the natural fit
> -- the other AST-level optimizations in the same Phase 1 are already
> named "consecutive variable / group / ALT merging", so it slots in
> cleanly. "Prefix/suffix factoring" is another candidate if a more
> descriptive verb is preferred.
> 
> Tatsuo, curious what you think of this direction and naming. Happy
> to take any name you prefer for the AST-level operation, or to keep
> the original "absorption" wording with stronger forward-references
> if you'd rather not rename.

Although I don't have any particular strong preferences, keeping
"absorption" for the runtime concept sounds good to me.

For AST level name changing, "prefix/suffix merging" seems to be
already used in other areas according to Google: LLM, Linker, and
string manipulation in DNA. In the normal expression engine area, it
looks like "flattening nested quantifiers" or "quantifiers reduction"
are used for the case. So, for example, "prefix/suffix quantifiers
reduction" seems to be more appropriate?  (If you don't mind it's too
long) In any case, I would like to respect your opinion.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Attached is the v47 patches for Row pattern recognition (SQL/RPR).

I accidentaly noticed that v47-0002 changes findTargetlistEntrySQL99
from static to extern.

-static TargetEntry *findTargetlistEntrySQL99(ParseState *pstate, Node *node,
-											 List **tlist, ParseExprKind exprKind);

I think this is not necessary anymore since findTargetlistEntrySQL99
is not used outside parse_clause.c.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

Thanks, Tatsuo -- your two notes settle both open questions. Answering both
inline below, with a note at the end on the follow-up work.

> Basically I think Jian's idea is good. In addition to the size reason
> above, we would have less code changes when we adapt existing R020
> codes to R010.
>
> However it will need a wide code change as Henson said. I would like
> to focus on stabilizing our code for now. Therefore I would not want
> the refactoring in v48.

Agreed -- out of v48, stabilize first. On R010, I'd treat it as the design
lens, not the schedule: it's far out, so rather than hold RPRContext back
until then, I'd do the consolidation at a sensible point after v48 but shape
it against R010 (what is shared versus per-context, how the fields group), so
one engine core can later back both the R020 window path and R010 without a
second reshape. Not v48 -- on its own schedule once we're stable.

I'll admit the R010 connection had been nagging at me for a while without a
clean answer, and Jian's consolidation suggestion turns out to land right on
it: framed as a size win, it's really the structural move that opens the R010
path -- that reframing is his. Which is why I'd rather shape it deliberately,
as the shared engine core, than fold it in as churn.

> Although I don't have any particular strong preferences, keeping
> "absorption" for the runtime concept sounds good to me.

Good -- "absorption" stays reserved for the runtime context-equivalence
collapse, and the README explains it in one place.

> For AST level name changing, "prefix/suffix merging" seems to be
> already used in other areas according to Google: LLM, Linker, and
> string manipulation in DNA. In the normal expression engine area, it
> looks like "flattening nested quantifiers" or "quantifiers reduction"
> are used for the case. So, for example, "prefix/suffix quantifiers
> reduction" seems to be more appropriate?  (If you don't mind it's too
> long) In any case, I would like to respect your opinion.

Thanks -- you're right that "merging" is well-worn elsewhere, and I'll be
honest that "prefix/suffix merging" isn't a term I'd defend on the merits.
Keeping it for v48 is really a stopgap to contain the ripple: the sibling
Phase-1 rewrites are already named "consecutive variable / group / ALT
merging", so switching to the "flattening / reduction" family would force
renaming those too for consistency. So I'd treat the term itself as genuinely
open -- your "flattening / reduction" neighborhood is the right one -- and
converge on the established academic naming as the paper I'm preparing on the
algorithm, together with a university research group, takes shape. For now I'd
ship "prefix/suffix merging" only to keep the README internally consistent,
and fold the settled term into the glossary pass once the paper lands on it. A
doc-level name is cheap to revise later.

Both of these -- the RPRContext reshape and the naming/terminology -- are
"after v48, by discussion" items, and they aren't the only ones. Rather than
pin down the scope of that follow-up now, I'd suggest we pick it up together
once v48 is stable.

Thanks again,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> I accidentaly noticed that v47-0002 changes findTargetlistEntrySQL99
> from static to extern.
> [...]
> I think this is not necessary anymore since findTargetlistEntrySQL99
> is not used outside parse_clause.c.

Good catch -- you're right, and I'll revert it to static in v48. I
double-checked the current tree: the only callers left are inside
parse_clause.c (the findTargetlistEntry wrapper, plus the GROUP BY and ORDER
BY paths), so the extern prototype in parse_clause.h is now unused. The
revert is just dropping that prototype and restoring the static qualifier
with the in-file forward declaration it used to have.

It's worth saying why it went extern in the first place, since the reason is
no longer visible in the tree:

The DEFINE clause needs its referenced columns present in the plan's
targetlist to be evaluable at run time. The original implementation did
that from the RPR side, in parse_rpr.c, by calling findTargetlistEntrySQL99()
with resjunk = true to add the missing entry -- and since that function was
static in parse_clause.c, reaching it across files is what required exposing
it as extern.

That approach added the whole DEFINE expression to the targetlist, and that
turned out to be the source of a SIGSEGV: when an RPR window and a plain
window coexist, the non-RPR WindowAgg inherited targetlist entries carrying
RPRNavExpr nodes it has no way to evaluate. The fix was to add only the Vars
a DEFINE references (with a guard in allpaths.c to keep those columns from
being pruned), and that is what removed the cross-file call. So the extern
has simply outlived its caller -- exactly as you spotted.

The one loose end there is an optimization, not a correctness issue: the
allpaths.c guard is deliberately coarse, so it also blocks removing a
WindowAgg whose RPR WindowFuncs are all unused. Doing that precisely means
restructuring remove_unused_subquery_outputs(), which runs for every
subquery and not just RPR -- broad enough that I'm treating it as a
longer-term item rather than part of this work. It doesn't bring the
external call back -- the Var-only path stays -- so the revert to static is
safe independently of it.

I'll fold the static revert into v48.

Thanks,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Good catch -- you're right, and I'll revert it to static in v48. I
> double-checked the current tree: the only callers left are inside
> parse_clause.c (the findTargetlistEntry wrapper, plus the GROUP BY and ORDER
> BY paths), so the extern prototype in parse_clause.h is now unused. The
> revert is just dropping that prototype and restoring the static qualifier
> with the in-file forward declaration it used to have.
> 
> It's worth saying why it went extern in the first place, since the reason is
> no longer visible in the tree:
> 
> The DEFINE clause needs its referenced columns present in the plan's
> targetlist to be evaluable at run time. The original implementation did
> that from the RPR side, in parse_rpr.c, by calling
> findTargetlistEntrySQL99()
> with resjunk = true to add the missing entry -- and since that function was
> static in parse_clause.c, reaching it across files is what required exposing
> it as extern.
> 
> That approach added the whole DEFINE expression to the targetlist, and that
> turned out to be the source of a SIGSEGV: when an RPR window and a plain
> window coexist, the non-RPR WindowAgg inherited targetlist entries carrying
> RPRNavExpr nodes it has no way to evaluate. The fix was to add only the Vars
> a DEFINE references (with a guard in allpaths.c to keep those columns from
> being pruned), and that is what removed the cross-file call. So the extern
> has simply outlived its caller -- exactly as you spotted.
> 
> The one loose end there is an optimization, not a correctness issue: the
> allpaths.c guard is deliberately coarse, so it also blocks removing a
> WindowAgg whose RPR WindowFuncs are all unused. Doing that precisely means
> restructuring remove_unused_subquery_outputs(), which runs for every
> subquery and not just RPR -- broad enough that I'm treating it as a
> longer-term item rather than part of this work. It doesn't bring the
> external call back -- the Var-only path stays -- so the revert to static is
> safe independently of it.
> 
> I'll fold the static revert into v48.

Thank for eplaining the history.

BTW, in v47-0002 patch,
there are some non ASCII characters ("§").

+	/*
+	 * Qualified column references in DEFINE are not supported.  This covers
+	 * both FROM-clause range variables (prohibited by §6.5) and pattern
+	 * variable qualified names (e.g. UP.price), which are valid per §4.16
+	 * but not yet implemented.
+	 */

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> BTW, in v47-0002 patch,
> there are some non ASCII characters ("§").

Good catch -- that one's already handled on top of v47. nocfbot-0004
("Reclassify DEFINE qualifier check and reword diagnostic to 'expression'")
reworded that comment, replacing the section signs with a spelled-out
reference: "prohibited by §6.5" became "prohibited by ISO/IEC 19075-5 6.5",
and likewise for §4.16. The signs you're looking at are an artifact of the
base v47-0002 patch, before that incremental.

To be sure it wasn't lurking elsewhere, I re-swept the whole RPR footprint
-- the sources, the headers, README.rpr, and the regression tests -- and
there are no non-ASCII characters left in the current tree. The fix folds
into v48.

Thanks,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

>> BTW, in v47-0002 patch,
>> there are some non ASCII characters ("§").
> 
> Good catch -- that one's already handled on top of v47. nocfbot-0004
> ("Reclassify DEFINE qualifier check and reword diagnostic to 'expression'")
> reworded that comment, replacing the section signs with a spelled-out
> reference: "prohibited by §6.5" became "prohibited by ISO/IEC 19075-5 6.5",
> and likewise for §4.16. The signs you're looking at are an artifact of the
> base v47-0002 patch, before that incremental.
> 
> To be sure it wasn't lurking elsewhere, I re-swept the whole RPR footprint
> -- the sources, the headers, README.rpr, and the regression tests -- and
> there are no non-ASCII characters left in the current tree. The fix folds
> into v48.

Oh, I see. Sorry for noise.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

While tidying RPR comments I found a small inconsistency in the varId bounds.
The comment/README side I'm already fixing in the in-progress series; whether
to also change the bounds is a separate follow-up.  As lead author that one is
ultimately your call, Tatsuo, but I'd welcome Jian's and the list's input on
it first.

The current state, in src/include/optimizer/rpr.h:

  #define RPR_VARID_MAX   251
  #define RPR_VARID_BEGIN 252   /* control codes 252..255 */
  ... END 253, ALT 254, FIN 255

  RPRElemIsVar(e)  ==  ((e)->varId <= RPR_VARID_MAX)   /* 0..251 */

and the limit enforced in parse_rpr.c:

  if (list_length(*varNames) >= RPR_VARID_MAX)   /* reject the 252nd */
      ereport(ERROR, "too many pattern variables", "Maximum is 251");

So 251 variables are accepted as varId 0..250, leaving 251 a hole: never
assigned, yet the macro still classifies it as a variable -- one wider than
the comment's own "0 to RPR_VARID_MAX - 1".

RPRVarId is a uint8, kept small on purpose: varId is the likely per-row
match-history key, and since a match can run arbitrarily long the history
grows with it -- so one byte per row, not two, is what keeps that footprint
in check.

The catch of staying in uint8: the four control codes already fill 252..255,
so 251 is the only free slot for any future sentinel (anchor ^/$, exclusion
{- -}) short of widening to uint16.  So the hole is really the last reserve.

Three ways, by what the gap is spent on:

(1) Leave it -- just the doc alignment already underway: 251 stays a documented
    reserve, macro unchanged.  No follow-up commit.  The one free slot is then
    on hand for a single future control code, should one ever be needed.

(2) Fill it as a 252nd variable (0..251).  Compatible and doable anytime; a few
    lines in parse_rpr.c / rpr.h plus the boundary test.  But it spends the
    last free slot, so a future control code would then force either a
    compatibility-breaking narrow of RPR_VARID_MAX or a widen to two bytes
    (doubling history).  Maximal variables now, the control question deferred.

(3) Reserve 16 control codes now (4 used + 12 spare) at the 0xF0 boundary:
    vars 0..239, control 240..255, existing sentinels unmoved, macro becomes
    (varId & 0xF0) != 0xF0.  Buys 12-code headroom inside the byte, so history
    stays 1 byte and (2)'s fork never arises.  Same edit shape as (2); costs
    only the nominal drop to 240 variables -- but it is a narrowing, so free
    only pre-release.

The asymmetry: (3) is the only one with a deadline -- a narrowing is compatible
only before release, while (1)/(2) stay open forever.  So the question is
whether to spend this one free moment to lock in 1-byte control headroom (3),
or stay minimal now (1)/(2) and take the narrow-or-widen later if it is ever
needed.  My own lean is toward (3): 240 variables is already far more than any
real pattern will use, so the capacity we give up is nominal, while the 12-code
buffer closes the narrow-or-widen fork for good and keeps match history at one
byte -- and it is the one choice that is free only now.  That said, I'd like
the decision to rest on everyone's input -- Jian's and the list's as much as
mine -- with you, Tatsuo, weighing it all and making the final call.

Either way, once the feature matures and the final control-code count is known,
the space can be repacked gap-free -- so none of these is the last word.

Which would you prefer?

Thanks,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson, Jian,

> Hi Tatsuo, Jian,
> 
> While tidying RPR comments I found a small inconsistency in the varId
> bounds.
> The comment/README side I'm already fixing in the in-progress series;
> whether
> to also change the bounds is a separate follow-up.  As lead author that one
> is
> ultimately your call, Tatsuo, but I'd welcome Jian's and the list's input on
> it first.
> 
> The current state, in src/include/optimizer/rpr.h:
> 
>   #define RPR_VARID_MAX   251
>   #define RPR_VARID_BEGIN 252   /* control codes 252..255 */
>   ... END 253, ALT 254, FIN 255
> 
>   RPRElemIsVar(e)  ==  ((e)->varId <= RPR_VARID_MAX)   /* 0..251 */
> 
> and the limit enforced in parse_rpr.c:
> 
>   if (list_length(*varNames) >= RPR_VARID_MAX)   /* reject the 252nd */
>       ereport(ERROR, "too many pattern variables", "Maximum is 251");
> 
> So 251 variables are accepted as varId 0..250, leaving 251 a hole: never
> assigned, yet the macro still classifies it as a variable -- one wider than
> the comment's own "0 to RPR_VARID_MAX - 1".
> 
> RPRVarId is a uint8, kept small on purpose: varId is the likely per-row
> match-history key, and since a match can run arbitrarily long the history
> grows with it -- so one byte per row, not two, is what keeps that footprint
> in check.
> 
> The catch of staying in uint8: the four control codes already fill 252..255,
> so 251 is the only free slot for any future sentinel (anchor ^/$, exclusion
> {- -}) short of widening to uint16.  So the hole is really the last reserve.
> 
> Three ways, by what the gap is spent on:
> 
> (1) Leave it -- just the doc alignment already underway: 251 stays a
> documented
>     reserve, macro unchanged.  No follow-up commit.  The one free slot is
> then
>     on hand for a single future control code, should one ever be needed.
> 
> (2) Fill it as a 252nd variable (0..251).  Compatible and doable anytime; a
> few
>     lines in parse_rpr.c / rpr.h plus the boundary test.  But it spends the
>     last free slot, so a future control code would then force either a
>     compatibility-breaking narrow of RPR_VARID_MAX or a widen to two bytes
>     (doubling history).  Maximal variables now, the control question
> deferred.
> 
> (3) Reserve 16 control codes now (4 used + 12 spare) at the 0xF0 boundary:
>     vars 0..239, control 240..255, existing sentinels unmoved, macro becomes
>     (varId & 0xF0) != 0xF0.  Buys 12-code headroom inside the byte, so
> history
>     stays 1 byte and (2)'s fork never arises.  Same edit shape as (2); costs
>     only the nominal drop to 240 variables -- but it is a narrowing, so free
>     only pre-release.
> 
> The asymmetry: (3) is the only one with a deadline -- a narrowing is
> compatible
> only before release, while (1)/(2) stay open forever.  So the question is
> whether to spend this one free moment to lock in 1-byte control headroom
> (3),
> or stay minimal now (1)/(2) and take the narrow-or-widen later if it is ever
> needed.  My own lean is toward (3): 240 variables is already far more than
> any
> real pattern will use, so the capacity we give up is nominal, while the
> 12-code
> buffer closes the narrow-or-widen fork for good and keeps match history at
> one
> byte -- and it is the one choice that is free only now.  That said, I'd like
> the decision to rest on everyone's input -- Jian's and the list's as much as
> mine -- with you, Tatsuo, weighing it all and making the final call.
> 
> Either way, once the feature matures and the final control-code count is
> known,
> the space can be repacked gap-free -- so none of these is the last word.
> 
> Which would you prefer?

I'd prefer (3). Yes, I agree that 240 pattern variables is enough.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson, Jian,

I'd like to suggest making a slight change to v48 patches
organization. Currently README.rpr is included in 0005 executor
patch. Since README.rpr is a documentation, I think it will be more
natural to move it into 0006 docs patch. This also will make it easier
to judge the size of the patches by category: codes, docs and tests if
README.rpr is correctly categorized.

Thoughts?
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:


2026년 6월 2일 (화) 12:03, Tatsuo Ishii <ishii@postgresql.org>님이 작성:
Hi Henson, Jian,

I'd like to suggest making a slight change to v48 patches
organization. Currently README.rpr is included in 0005 executor
patch. Since README.rpr is a documentation, I think it will be more
natural to move it into 0006 docs patch. This also will make it easier
to judge the size of the patches by category: codes, docs and tests if
README.rpr is correctly categorized.

+1


Thoughts?
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi all,
> 
> Resolved since the last post:
> 
>   D1. Single-row frame conformance, Subclause 6.10.2 -- Tatsuo's call [6]
>       was to reject. Both ROWS BETWEEN CURRENT ROW AND CURRENT ROW and
>       AND 0 FOLLOWING are now rejected (nocfbot-0025), which in turn
>       unblocks the held ExecRPRProcessRow change (nocfbot-0026).
> 
> Open decisions (repeated with context at the end):
> 
>   D2. The RPRContext consolidation -- Tatsuo's call as co-author;
>       non-blocking either way [4].
>   D3. The AST "absorption" rename -- Tatsuo's call [2].
> 
>   [1] Jian's review, round 1 (2026-05-26):
> 
> https://postgr.es/m/CACJufxH-DZePhbdJM=8nNYceQiSbbXXLTw54iLhxiynQ+4hbBA@mail.gmail.com
>   [2] my round-1 reply -- AST "absorption" rename deferred to Tatsuo (D3,
> 2026-05-27):
> 
> https://postgr.es/m/CAAAe_zDephfiDA_A3FN0hCymJRogEr=Rt3QoCTf4qMYDLk+xNA@mail.gmail.com
>   [3] Jian's review, round 2 (2026-05-28):
> 
> https://postgr.es/m/CACJufxGX17thWuEOq1tM5xbRHz2HXm1asooZC3GV25MYGmYqLQ@mail.gmail.com
>   [4] my round-2 reply -- RPRContext deferred to Tatsuo (D2, 2026-05-29):
> 
> https://postgr.es/m/CAAAe_zAH0MvP0TBmW3PTLeHjEpiyBz0473zJRM9pwLpseefMNw@mail.gmail.com
>   [5] single-row frame conformance question (D1, 2026-05-29):
> 
> https://postgr.es/m/CAAAe_zCbSU=dd-4qTL2QaBQwQ-cf51N_851a9Y5rOoz0wj0aXw@mail.gmail.com
>   [6] Tatsuo's reply -- reject single-row frames (D1 resolved, 2026-05-30):
> 
> https://postgr.es/m/20260530.114737.1416684464524168377.ishii@postgresql.org
>   [7] Jian's review, round 3 (2026-05-30):
> 
> https://postgr.es/m/CACJufxEsaU8GQ4yeXTWhAO8VjbrZTh5CpvUqz=4a3T0Cwz44pA@mail.gmail.com
> 
> Attached: the v47 feature series (v47-0001..0009) rebased onto current
> master, plus the incremental patch series carried on top of it.
> 
> Base:
> 
>   9a41b34a287  2026-05-26  doc:  add comma to UPDATE docs, for consistency
> 
> Unchanged -- rebase only (already posted; only rebased, no content change).
> Titles for reference:
> 
>   nocfbot-0001  Add DEFINE non-volatile baseline to rpr_integration B9
>   nocfbot-0002  Unify RPR DEFINE walkers and reject volatile callees

While looking into 0002, I noticed some minor ereport calling style
issues.

Recently we start to use the style:

		ereport(ERROR,
				errcode(ERRCODE_FEATURE_NOT_SUPPORTED),

Rather than (old style):

		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),

Grepping patches shows following results that hire the old style.

$ grep -n '(errcode' *|grep '+'
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1243:+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1248:+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1421:+								(errcode(ERRCODE_SYNTAX_ERROR),
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1428:+								(errcode(ERRCODE_SYNTAX_ERROR),
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1451:+							(errcode(ERRCODE_SYNTAX_ERROR),
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1457:+							(errcode(ERRCODE_SYNTAX_ERROR),
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1463:+							(errcode(ERRCODE_SYNTAX_ERROR),
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1471:+						(errcode(ERRCODE_SYNTAX_ERROR),
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1494:+							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1504:+							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
nocfbot-0025-Reject-single-row-window-frame-in-row-pattern-rec.txt:55:+						(errcode(ERRCODE_WINDOWING_ERROR),

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Oops.

> While looking into 0002, I noticed some minor ereport calling style
> issues.
> 
> Recently we start to use the style:
> 
> 		ereport(ERROR,
> 				errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> 
> Rather than (old style):
> 
> 		ereport(ERROR,
> 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> 
> Grepping patches shows following results that hire the old style.
> 
> $ grep -n '(errcode' *|grep '+'
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1243:+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1248:+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1421:+								(errcode(ERRCODE_SYNTAX_ERROR),
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1428:+								(errcode(ERRCODE_SYNTAX_ERROR),
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1451:+							(errcode(ERRCODE_SYNTAX_ERROR),
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1457:+							(errcode(ERRCODE_SYNTAX_ERROR),
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1463:+							(errcode(ERRCODE_SYNTAX_ERROR),
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1471:+						(errcode(ERRCODE_SYNTAX_ERROR),
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1494:+							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> nocfbot-0002-Unify-RPR-DEFINE-walkers-and-reject-volatile-call.txt:1504:+							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),

These have been fixed in 0007. Sorry for noise.

Maybe this is the only one worth to look into?

> nocfbot-0025-Reject-single-row-window-frame-in-row-pattern-rec.txt:55:+						(errcode(ERRCODE_WINDOWING_ERROR),

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
On Mon, Jun 1, 2026 at 1:35 PM Henson Choi  wrote:
>
> Hi Tatsuo, Jian,
>
> While tidying RPR comments I found a small inconsistency in the varId bounds.
> The comment/README side I'm already fixing in the in-progress series; whether
> to also change the bounds is a separate follow-up.  As lead author that one is
> ultimately your call, Tatsuo, but I'd welcome Jian's and the list's input on
> it first.
>
> The current state, in src/include/optimizer/rpr.h:
>
>   #define RPR_VARID_MAX   251
>   #define RPR_VARID_BEGIN 252   /* control codes 252..255 */
>   ... END 253, ALT 254, FIN 255
>
>   RPRElemIsVar(e)  ==  ((e)->varId <= RPR_VARID_MAX)   /* 0..251 */
>
> and the limit enforced in parse_rpr.c:
>
>   if (list_length(*varNames) >= RPR_VARID_MAX)   /* reject the 252nd */
>       ereport(ERROR, "too many pattern variables", "Maximum is 251");
>
> So 251 variables are accepted as varId 0..250, leaving 251 a hole: never
> assigned, yet the macro still classifies it as a variable -- one wider than
> the comment's own "0 to RPR_VARID_MAX - 1".
>
> RPRVarId is a uint8, kept small on purpose: varId is the likely per-row
> match-history key, and since a match can run arbitrarily long the history
> grows with it -- so one byte per row, not two, is what keeps that footprint
> in check.
>
> The catch of staying in uint8: the four control codes already fill 252..255,
> so 251 is the only free slot for any future sentinel (anchor ^/$, exclusion
> {- -}) short of widening to uint16.  So the hole is really the last reserve.
>
> Three ways, by what the gap is spent on:
>
> (1) Leave it -- just the doc alignment already underway: 251 stays a documented
>     reserve, macro unchanged.  No follow-up commit.  The one free slot is then
>     on hand for a single future control code, should one ever be needed.
>
> (2) Fill it as a 252nd variable (0..251).  Compatible and doable anytime; a few
>     lines in parse_rpr.c / rpr.h plus the boundary test.  But it spends the
>     last free slot, so a future control code would then force either a
>     compatibility-breaking narrow of RPR_VARID_MAX or a widen to two bytes
>     (doubling history).  Maximal variables now, the control question deferred.
>
> (3) Reserve 16 control codes now (4 used + 12 spare) at the 0xF0 boundary:
>     vars 0..239, control 240..255, existing sentinels unmoved, macro becomes
>     (varId & 0xF0) != 0xF0.  Buys 12-code headroom inside the byte, so history
>     stays 1 byte and (2)'s fork never arises.  Same edit shape as (2); costs
>     only the nominal drop to 240 variables -- but it is a narrowing, so free
>     only pre-release.
>
> Which would you prefer?
>

3.

240 variables is enough, as each variable supports multiple complex AND/OR
conditions. Additionally, since PostgreSQL regular expressions use 14 special
characters, reserving the remaining ones in advance is a future-proof approach.

----------------------------------------------------
src/backend/executor/README.rpr

XII-4. Memory Pool Management
  Choice: Custom free list

  Rationale:
  - NFA states are created and destroyed in large numbers per row
  - Avoids palloc/pfree overhead
  - State size is variable (counts[] array), but within a single query
    maxDepth is fixed, so all states have the same size

It would be better simply to mention that:
RPRNFAState and RPRNFAContext are allocated in a partition-lifespan
memory context; they will be destroyed in release_partition.
--------------------------
in ExecRPRFreeContext:
{
    if (ctx->states != NULL)
        nfa_state_free_list(winstate, ctx->states);
    if (ctx->matchedState != NULL)
        nfa_state_free(winstate, ctx->matchedState);
}

If ctx->matchedState points to one of the states already in ctx->states, will
nfa_state_free() be called on the same RPRNFAState twice? Is this double-free
permitted, or do we have a mechanism in place to guard against it?
--------------------------
In ExecRPRProcessRow

            if (currentPos == ctxFrameEnd)
            {
                /* Frame boundary reached: force mismatch */
                nfa_match(winstate, ctx, NULL);
                continue;
            }

If I comment out the CONTINUE, the entire regression still succeeds.



--
jian
https://www.enterprisedb.com/


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

In execRPR.c:

static void
nfa_reevaluate_dependent_vars(WindowAggState *winstate, RPRNFAContext *ctx,
							  int64 currentPos)

This function does not have a forward declaration. Moreover, it is put
in the "API exposed to nodeWindowAgg.c" section. If there's no
particular reason for this, I suggest to add a forward declaration for
it and move it before "API exposed to nodeWindowAgg.c" section.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Catching up on today's notes -- all straightforward, so I'm folding them
into one reply.

> I'd prefer (3). Yes, I agree that 240 pattern variables is enough.

Then (3) it is -- and with Jian on the same choice, that closes it. I'll
go ahead with it. Since it's a narrowing it's only free pre-release, so
it goes in the v48 core rather than a later follow-up.

> static void
> nfa_reevaluate_dependent_vars(WindowAggState *winstate, RPRNFAContext *ctx,
>                               int64 currentPos)
>
> This function does not have a forward declaration. Moreover, it is put
> in the "API exposed to nodeWindowAgg.c" section. [...] I suggest to add
> a forward declaration for it and move it before "API exposed to
> nodeWindowAgg.c" section.

Agreed -- that was just an oversight. I'll add the forward declaration
and move it out of the API-exposed section.

> nocfbot-0025-...:55:+   (errcode(ERRCODE_WINDOWING_ERROR),
> Maybe this is the only one worth to look into?

Right -- I'll update 0025 in the next posting.

Thanks,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Subject: Re: Row pattern recognition

Hi Jian,

> 3.
> 240 variables is enough, as each variable supports multiple complex
> AND/OR conditions. [...] reserving the remaining ones in advance is a
> future-proof approach.

Thanks -- that's (3), and Tatsuo landed on the same choice, so it's
settled. I'll make the change for v48.

> XII-4. Memory Pool Management
>   Choice: Custom free list [...]
> It would be better simply to mention that:
> RPRNFAState and RPRNFAContext are allocated in a partition-lifespan
> memory context; they will be destroyed in release_partition.

Agreed -- that's clearer than the rationale list. I'll replace XII-4 with
that wording.

> If ctx->matchedState points to one of the states already in ctx->states,
> will nfa_state_free() be called on the same RPRNFAState twice? Is this
> double-free permitted, or do we have a mechanism in place to guard
> against it?

No -- they're disjoint by construction, so the two frees never touch the
same state. Step by step:

  - nfa_advance() detaches ctx->states up front (sets it to NULL) and
    rebuilds the list from scratch.
  - Each old state is pulled off and advanced; the one that reaches FIN is
    moved into matchedState and never re-added to ctx->states.
  - So at any moment a state is either on ctx->states or it is
    matchedState, never both.
  - ExecRPRFreeContext frees the list and frees matchedState -- disjoint
    sets, no overlap, so no guard is needed.
  - (When a new FIN replaces matchedState, the previous one is freed right
    there.)

> if (currentPos == ctxFrameEnd) {
>     nfa_match(winstate, ctx, NULL);
>     continue;
> }
> If I comment out the CONTINUE, the entire regression still succeeds.

It isn't dead -- it's the N-FOLLOWING boundary handler. nfa_match(ctx,
NULL) forces a mismatch that finalizes the context on its matchedState,
and the continue skips the rest since it's done for this row.

Without the continue, that finalized context is matched a second time in
the same row -- a context-matched-twice error. It only looks harmless
because the forced mismatch already emptied ctx->states, so the second
nfa_match iterates nothing (and it would also re-run
nfa_reevaluate_dependent_vars(), overwriting the shared nfaVarMatched the
other contexts read). So I'd keep it: a finalized context must not be
matched twice in the same row.

Thanks,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi all,

While going over the row pattern grammar I want to put on record why the
empty pattern -- PATTERN (()) and the like -- is left unsupported, and why
I think that is the right call for this series rather than an oversight.

Today it is simply a syntax error.  row_pattern_primary is either a
variable (ColId) or a parenthesized group '(' row_pattern ')', and
row_pattern has no empty production, so '()' never parses.  The standard's
pattern syntax does allow an empty row pattern -- it matches the empty
sequence, i.e. it produces an empty match -- so the question is whether we
should grow the grammar, plus an NFA "empty" element, to accept it.

My claim is that we do not need to: every way an empty pattern can appear
reduces to something we already handle, so a dedicated empty element in
the executor would be dead weight.  There are two cases.


1. The empty pattern is the whole pattern: PATTERN (())

This pattern has zero pattern variables.  But DEFINE is mandatory (per
ISO/IEC 19075-5, Table 18), an empty DEFINE list is rejected, and every
DEFINE variable must appear in PATTERN -- otherwise we already error with
"DEFINE variable \"%s\" is not used in PATTERN".  A pattern with no
variables cannot satisfy any of that: there is nothing for DEFINE to
define, yet DEFINE can be neither omitted nor left empty.  So an all-empty
pattern is rejected by the existing rules, with no new check needed.

(It is degenerate in any case.  An empty match at every row maps to "no
reduced frame" -- row_is_in_reduced_frame() returns -1 for RF_EMPTY_MATCH
exactly as it does for RF_UNMATCHED -- so every row would simply be
unmatched.)


2. The empty pattern is embedded: A () B

Here '()' consumes no rows; it is the identity element under
concatenation, so A () B is equivalent to A B.  This stays entirely on the
parser/optimizer side: the empty-pattern production would carry an empty
AST node, and an identity fold in the SEQ simplification (next to the
prefix/suffix and consecutive merges it already does) drops the '()'
before the executor ever sees it.  The runtime is untouched -- which is
the whole point.  And if the fold removes everything, the pattern has
collapsed to case 1 and is rejected there.

The AST rewrites it would add:

  Concatenation (identity element):
    A () B          ->  A B
    () A            ->  A
    A ()            ->  A
    A () () B       ->  A B

  Group unwrap (single non-empty child):
    (A ())          ->  (A)  ->  A
    (() A)          ->  (A)  ->  A

  Quantified empty (empty repeated is still empty):
    ()*  ()+  ()?  (){3}    ->  (removed)
    A ()* B         ->  A B

  Collapses to case 1, then rejected:
    (())    (() ())    ((()))    ->  ()  -> rejected as case 1

The one form that is not pure deletion is an empty alternative.  Here the
empty branch is optionality, not nothing, but it is exactly the '?'
quantifier applied to the rest -- X | () is (X)?:

    X | ()          ->  (X)?          (and  () | X  ->  (X)??, reluctant)
      A | ()        ->  A?            (single var: group is redundant)
      A{2} | ()     ->  (A{2})?       (the group is required here -- A{2}?
                                       would parse as a reluctant A{2}, not
                                       an optional one)
      A B | ()      ->  (A B)?         (X may be a sequence)
      A | B | ()    ->  (A | B)?       (... or an alternation)
    (A | ()) B      ->  A? B

The branch order maps to greediness ('X | ()' greedy, '() | X' reluctant).
Either way it rewrites to a group plus '?', both of which we already
support, so it still needs no new machinery.

The rewrites also compose across nesting.  A nested empty alternation
applies the rule at each level, producing a nested nullable quantifier:

    (A | ()) | ()
        ->  A? | ()      (inner   A | ()  ->  A?)
        ->  (A?)?        (outer   X | ()  ->  (X)?,  X = A?)

and (A?)? = A?, (A+)? = A*, (A*)? = A* are all ordinary nullable
constructs, never a new shape:

    A? | ()   ->  (A?)?    (= A?)
    A+ | ()   ->  (A+)?    (= A*)
    A* | ()   ->  (A*)?    (= A*)

Whether the optimizer collapses these to a single quantifier or leaves the
group as-is doesn't matter here -- both are nullable groups the runtime
already handles, so still no executor-level element.  (The optimizer
leaves these unfolded: a non-exact outer over a nullable child falls
outside tryMultiplyQuantifiers' conservative guard, which skips the whole
class that can have gaps (e.g. (A{2}){2,3} = {4,6}).  That is an
over-rejection, not a correctness defect -- folding the nullable cases
would be a safe optional extension; see the aside below.)

(Duplicate empty branches would be merged first by the alternation dedup,
so A | () | () reduces through A | () to A? just the same.)


Putting it together: across the board an empty pattern is either

  (a) rejected by the existing DEFINE rules (case 1),
  (b) the concatenation identity, removable by the AST simplification
      (case 2), or
  (c) an existing nullable construct ('?', the empty alternative),

and none of these would ever need an executor-level empty element.

Given that, and that the feature has little practical use while the
current series is already sizable, I am leaving the empty pattern out of
scope: it stays a syntax error.  Concretely, accepting it would take a
grammar production, an empty AST node, the concatenation-identity deletion
in the SEQ pass, and (optionally) an extension of the quantifier
composition to fold the nullable cases -- all new work, none of it in this
series.  We can revisit it as that small follow-up if anyone actually
wants it.

Thanks,
Henson


------------------------------------------------------------------------
Aside (separable from the post above): quantifier-composition gaps,
unrelated to the empty pattern
------------------------------------------------------------------------

Independent of the empty pattern, the AST-level quantifier-composition
pass (tryMultiplyQuantifiers, rpr.c) over-rejects: it collapses a nested
quantifier (X{p,q}){m,n} into a single X{...} only when the outer is exact
(m == n), the child is {1,1}, or both are unbounded.  Those are the
always-safe sufficient conditions.  But the full foldable class is larger:
(X{p,q}){m,n} is foldable to X{m*p, n*q} whenever the reachable repetition
counts -- the union over k in [m,n] of [k*p, k*q] -- are contiguous (no
gaps).  That holds for every nullable child (p == 0) and, more generally,
whenever the child span q-p is wide enough to bridge the jump between k and
k+1 iterations.  The guard thus rejects a strict superset of the genuinely
unsafe (gap-producing) patterns: a class of provably-safe folds is left
undone, and those patterns reach the executor as nested groups -- handled
correctly, just not normalized.  This is an optimization over-rejection,
not a correctness defect: the output is identical either way.

The two rules side by side (outer {m,n} over child {p,q}, INF = unbounded):

  current guard -- folds iff:
      m = n                                       (outer exact)
    OR (p = 1 AND q = 1)                          (child {1,1})
    OR (q = INF AND n = INF AND NOT(m = 0 AND p >= 2))   (both unbounded)

  true safe set -- foldable iff the reachable counts are contiguous:
      m = n                                       (single interval)
    OR p = 0                                      (nullable child)
    OR ( p <= max(m,1)*(q - p) + 1                (child span bridges the
         AND (m >= 1 OR p <= 1) )                  k -> k+1 jump; child {1,1}
                                                   is the p=q=1 instance)

  over-rejected = safe AND NOT current:
    the non-exact-outer (m != n) folds over a gap-free child -- p = 0
    (nullable) or a span-bridging child.  e.g. (A?)?, (A*)?, (A+)?,
    (A?){2,3}, (A+){0,2}, (A{1,3}){2,4} (all in the table below).
    The boundaries (A{2}){2,3} and (A{2,})* are NOT in the safe set
    (p = 2 fails p <= max(m,1)*(q-p)+1), so both rules reject them --
    correctly; widening the guard must keep doing so.

Verified on the branch -- EXPLAIN's "Pattern:" line shows the optimized
form (a nested group means it was not folded; a flat quantifier means it
was):

  folds today (correct):
    (A){2,3}        -> a{2,3}        (child {1,1})
    (A{2,3}){2}     -> a{4,6}        (outer exact)
    (A*)*           -> a*            (both unbounded)

  gap-free but NOT folded (stays nested; "want" is the safe normal form):
    (A?)?           -> (a?)?         want a?
    (A*)?           -> (a*)?         want a*
    (A+)?           -> (a+)?         want a*
    (A?){2,3}       -> (a?){2,3}     want a{0,3}
    (A+){0,2}       -> (a+){0,2}     want a*
    (A{1,3}){2,4}   -> (a{1,3}){2,4} want a{2,12}

  correctly NOT foldable (real gap -- guard is right here):
    (A{2}){2,3}     -> (a{2}){2,3}   reaches {4,6}, not 4..6

The first three "not folded" rows are the nullable forms the empty pattern
would lean on; the next three show the gap is broader (a range outer over
a non-{1,1} child can still be gap-free).  The win is only normalization /
a smaller NFA, so this is low priority.  And this exact pass has a history
of subtle gap bugs (the (A{2,})* over-flatten and the INF-sum merge, both
recently fixed), so widening the guard toward the safe set above should be
its own patch, with boundary tests covering the foldable cases and the two
gaps -- (A{2}){2,3} and (A{2,})* -- that must stay un-folded.

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

Just a trivial comment to 1.

> While going over the row pattern grammar I want to put on record why the
> empty pattern -- PATTERN (()) and the like -- is left unsupported, and why
> I think that is the right call for this series rather than an oversight.
> 
> Today it is simply a syntax error.  row_pattern_primary is either a
> variable (ColId) or a parenthesized group '(' row_pattern ')', and
> row_pattern has no empty production, so '()' never parses.  The standard's
> pattern syntax does allow an empty row pattern -- it matches the empty
> sequence, i.e. it produces an empty match -- so the question is whether we
> should grow the grammar, plus an NFA "empty" element, to accept it.
> 
> My claim is that we do not need to: every way an empty pattern can appear
> reduces to something we already handle, so a dedicated empty element in
> the executor would be dead weight.  There are two cases.
> 
> 
> 1. The empty pattern is the whole pattern: PATTERN (())
> 
> This pattern has zero pattern variables.  But DEFINE is mandatory (per
> ISO/IEC 19075-5, Table 18), an empty DEFINE list is rejected, and every
> DEFINE variable must appear in PATTERN -- otherwise we already error with
> "DEFINE variable \"%s\" is not used in PATTERN".  A pattern with no
> variables cannot satisfy any of that: there is nothing for DEFINE to
> define, yet DEFINE can be neither omitted nor left empty.  So an all-empty
> pattern is rejected by the existing rules, with no new check needed.

I think current behavior is correct from the standard's point of
view. As you explained, there's no way to accept "PATTERN (())" or
"PATTERN ()" according to the R020 syntax rule.

Note, however, "PATTERN ()" is possible in R010 because it allows to
omit the DEFINE clause itself.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

Please check the attached regression test refactoring and gram.y changes

------------------atatched patch commit
message-----------------------------------------------
v47 rpr reformat gram.y and improve regression tests

Reformat the first three alternatives of row_pattern_quantifier_opt
in gram.y (empty, '*', '+') from inline single-line actions to
multi-line blocks, making them consistent with the surrounding Op
and '{...}' alternatives.

Update regression tests to follow the convention established in
commit ecb2508aaf [1]: do not repeat exact error messages as comments
in regress test files, since such comments silently go stale when
error wording changes.  Replace the removed "Expected: ERROR: ..."
comments with short descriptive comments that state what the test
is checking rather than what output it expects.

Also remove unnecessary newline/comments in src/test/regress/sql/rpr_base.sql.

Add test coverage for:
1. invalid token combinations after a quantifier (A+ !, A+ ?+,
  A* ?+, A? ??), exercising the split-token error paths in
  row_pattern_quantifier_opt
2. set-returning function (generate_series) in a DEFINE clause

[1]: https://git.postgresql.org/cgit/postgresql.git/commit/?id=ecb2508aaf9b978871734ea2fdf701ab7d593d0a
----------------------------end of commit
message-------------------------------------------------

It's based on latest commit in https://github.com/assam258-5892/postgres.git
It will have a small conflict (around 100 lines difference) with v47.

In src/test/regress/sql/rpr_base.sql, wording such as ``Jacob's
Patterns`` should be removed?

```
--   Serialization/Deserialization Tests (objects kept for pg_upgrade/pg_dump)
```
I am not sure what this refers to.

In gram.y:
errmsg("quantifier bound must be between 0 and %d", INT_MAX - 1),
errmsg("quantifier bound must be between 1 and %d", INT_MAX - 1),

Will these cause consistency issues?



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
> Please check the attached regression test refactoring and gram.y changes

Thanks for the patch -- the substance all looks right: the gram.y reformat
is a fair consistency fix, the ecb2508aaf convention (no hardcoded error
text in regress comments) is one we should follow, and the added coverage
(split-token quantifier errors, SRF in DEFINE) fills real gaps.

I'll work these in together with the patches I'm lining up right before the
v48 merge, rather than mid-stream -- the large "Expected: ERROR" comment
cleanup would otherwise churn against the other test edits still in flight.
They'll all land in that v48 round.

Answers to your three questions:

> In src/test/regress/sql/rpr_base.sql, wording such as ``Jacob's
> Patterns`` should be removed?

Those came in from Jacob's branch, but agreed they're better changed:
"Jacob's Patterns" / "from jacob branch" are dev-time provenance notes, not
something to keep in committed tests. I'll give the section a descriptive
header (the tests themselves stay) and do it together with the v48 round
above.

> --   Serialization/Deserialization Tests (objects kept for pg_upgrade/pg_dump)
> I am not sure what this refers to.

Those are views (with RPR in their definition) left undropped on purpose,
so the pg_dump/pg_upgrade tests pick them up: dumping and restoring the
regression DB deparses the RPR window clause and re-parses it, exercising
the serialization round trip. rpr_explain.sql keeps one for the same
reason. I'll reword the comment to say that.

> errmsg("quantifier bound must be between 0 and %d", INT_MAX - 1),
> errmsg("quantifier bound must be between 1 and %d", INT_MAX - 1),
> Will these cause consistency issues?

No, it's intentional. INT_MAX is the unbounded sentinel (RPR_QUANTITY_INF),
so an explicit bound is capped at INT_MAX - 1 to avoid colliding with it;
the "0 vs 1" split just matches each form ({n}/{,m} need >= 1, {n,} allows 0).

Regards,
Henson

Re: Row pattern recognition

От:
Andres Freund <andres@anarazel.de>
Дата:
Hi,

cfbot is currently failing, with crashes inside JIT, on this patch. However,
the patch cfbot is submitting is rather old, because all of the versions
posted since have been marked nocfbot.

Greetings,

Andres Freund


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> cfbot is currently failing, with crashes inside JIT, on this patch.

Thanks for letting know us. If my memory serves, the old cfbot did not
fail. So maybe the failure is due to something changed recently on the
master branch regarding JIT but the patch has not followed it yet?

Henson,
Do yo have any idea?

> However,
> the patch cfbot is submitting is rather old, because all of the versions
> posted since have been marked nocfbot.

Yes, it's intended. They are all incremental diffes against old (v47)
patches to save the patch size.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
> Henson,
> Do you have any idea?

Let me be honest about this one.

I think the root issue is that none of us working on the patch has
enough confidence -- enough real control -- over the tuple slot and JIT
side of it. I wrote the code, it ran fine for me, and I assumed that
meant it was fine; but I have never felt that I fully understand and
control that area. So I cannot point to a specific cause with confidence
yet, and I would rather say that plainly than guess.

One practical note: there have been no tuple slot or JIT changes in the
patch since v47, and none are planned. So that part has been stable, and
reviewing the tuple slot / JIT code against v47 is perfectly viable --
there is no need to wait for a newer revision to look at that area.

What I think would genuinely harden the patch is for someone who knows
tuple slots and JIT well to review -- or rewrite -- that part. I would
very much welcome that, and I am happy to provide the design direction
behind the current code, or any other information a reviewer would need.

To be fair, the same caveat applies to the existing planner code the
patch builds on. I feel I have a reasonable grip on the rest of the
patch, but not on those two areas.

I will keep digging on my side (trying to reproduce the JIT crash with
JIT forced on against the current versions), and report back with
anything concrete I find.

Regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Note, however, "PATTERN ()" is possible in R010 because it allows to
> omit the DEFINE clause itself.

My mistake. the DEFINE clause is mandatory in R010 too. Sorry for
noise.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

The below in advanced.sgml actually seems better suited for
explain.sgml (which currently has no changes).
At the very least, explain.sgml should mention it.

   
    When examining query plans for Row Pattern Recognition with
    EXPLAIN, the pattern output may include special
    markers that indicate optimization opportunities. A double quote
    " marks where pattern absorption can occur,
    and a single quote ' marks absorbable elements
    within a branch. For example, a+" indicates that
    repeated matches of a can be absorbed, while
    (a' b')+" shows that both a
    and b within the group are absorbable.
    These markers are primarily useful for understanding internal
    optimization behavior.
   


......
 PATTERN (LOWPRICE UP+ DOWN+)
 DEFINE
  LOWPRICE AS price <= 100,
  UP AS price > PREV(price),
  DOWN AS price < PREV(price)
);

LOWPRICE, UP, DOWN should be lower case, since they are not keywords?

scanRPRPatternRecursive
It would be better to replace all  ``non-trivial quantifier`` to
``non-trivial quantifier (not {1,1}).``

I want to rename allocateRPRPattern to makeRPRPattern, what do you think?

RPRPatternNode.reluctant_location is not necessary. we never use it
for error reporting,
and since it's restricted to the end of a pattern, it adds very little value.

Is nav_volatile_func_checker really necessary?
We already have contain_volatile_functions and
contain_volatile_functions_not_nextval.
Also per https://www.postgresql.org/message-id/626986.1776785090@sss.pgh.pa.us
The convention is not to check expression volatility during parse
analysis stage.

+bool        trailing_alt pg_node_attr(query_jumble_ignore);
I may check whether trailing_alt is necessary later,  but
query_jumble_ignore is not needed because it's only manipulated in
gram.y and we do JumbleQuery in parse_analyze_fixedparams, which
obviously is later than all gram.y related work.
----------------------------------------------
v47-0001-v47-rpr-reformat-gram.y-again.nocfbot
The HINT message below is somewhat misleading, since the question mark
(?) is actually after the range quantifier.
Change errmsg to errmsg("invalid token \"%s\" after range quantifier",
$5) will make the error message clearer.

+SELECT FROM rpr_err WINDOW w AS ( ROWS BETWEEN CURRENT ROW AND 1
FOLLOWING PATTERN (A {1,2}??) DEFINE A AS TRUE);
+ERROR:  invalid token "??" after range quantifier
+LINE 1: ...TWEEN CURRENT ROW AND 1 FOLLOWING PATTERN (A {1,2}??) DEFINE...
+                                                             ^
+HINT:  Only "?" is allowed after {n,m} to make it reluctant.
----------------------------------------------
v47-0002-v47-rpr-regress-tests-refactoring.nocfbot

-- Consecutive GROUP merge: (A B){2} (A B)+ -> (a b){3,}
-- Exercises the child->max == RPR_QUANTITY_INF branch in
mergeConsecutiveGroups,
--- where a finite prev ((A B){2,2}) meets an infinite child ((A B)+).

We should just drop these comments from the regress tests.
mergeConsecutiveGroups is a static function that might change, and we don't want
to have to update all the tests every time it does.  Also the comments meaning
is still totally clear without them.
----------------------------------------------
v47-0003-refactor-many-functions-in-rpr.c.nocfbot
I did some major refactoring in rpr.c. Instead of allocating new lists to
remove duplicates, we now just mutate them in place using list_delete_nth_cell
(a common pattern in the codebase).
for overflow handling, it would be better use pg_mul_s32_overflow,
pg_add_s32_overflow.
See the commit message for the details.

v47-0004-another-v47-misc-refactoring.nocfbot
Some misc refactoring, that seems to make sense to me, see the commit
message for rationale.

The above v47-0001, v47-0002, and v47-0003, v47-0004 are based on
https://github.com/assam258-5892/postgres
latest commit.



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Re: Row pattern recognition
To: jian he, Tatsuo Ishii (+ pgsql-hackers)

Hi jian, Tatsuo,

Thanks for the careful review -- replies inline. One question up front,
for Tatsuo: I'd like your take on the LOWPRICE/UP/DOWN casing below
(details at that point). The rest are replies to jian's points.

> The below in advanced.sgml actually seems better suited for
> explain.sgml (which currently has no changes).
> At the very least, explain.sgml should mention it.

Agreed; I'll move the EXPLAIN marker description over to explain.sgml.

> LOWPRICE, UP, DOWN should be lower case, since they are not keywords?

They're user identifiers, and the standard and Oracle docs show them in
upper case, so I lean toward leaving the example as written -- though
EXPLAIN and deparse do lower-case them today. Tatsuo, I'd defer the
casing to you.

> scanRPRPatternRecursive
> It would be better to replace all ``non-trivial quantifier`` to
> ``non-trivial quantifier (not {1,1}).``

Agreed, that's clearer; will do.

> I want to rename allocateRPRPattern to makeRPRPattern, what do you think?

Good idea -- makeRPRPattern fits the makeNode/makeXxx convention.

> RPRPatternNode.reluctant_location is not necessary.

Agreed. The field is only written and propagated, never read back, so
I'll drop it and keep the reluctance as a plain bool.

> Is nav_volatile_func_checker really necessary? ... The convention is
> not to check expression volatility during parse analysis stage.

Good point -- I'll move the volatility rejection out of parse analysis
and into the planner, in line with that convention.

> query_jumble_ignore is not needed because it's only manipulated in
> gram.y ...

Right; I'll drop the query_jumble_ignore attribute.

> v47-0001 ... Change errmsg to errmsg("invalid token \"%s\" after range
> quantifier", $5) will make the error message clearer.

Agreed, that reads better; I'll adjust the message accordingly.

> v47-0002 ... We should just drop these comments from the regress tests.

Agreed -- the internal function names don't belong in the tests; I'll
remove them.

> v47-0003 ... mutate them in place using list_delete_nth_cell ...
> for overflow handling ... pg_mul_s32_overflow, pg_add_s32_overflow.

The overflow helpers are a clear win. The in-place list mutation is
behavior-equivalent, but I'd rather not reshape that logic right now
without a concrete need, so I'll hold off on it for the moment. The new
tests are good and I'll fold them in.

More broadly, I see the patch as being in its final verification stage
at this point, so I'd prefer to limit logic changes to those backed by a
clear review or test finding.

> v47-0004 ... Some misc refactoring ...

Mostly agree -- the rpSkipTo/initial comments read more accurately as
flag assignments. I'd keep the "PATTERN AST" wording (it's an AST, not a
flag) and the deparse note, but the rest is fine.

Best,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

While doing a self-review pass over the incremental fixes on top of v47 I
ran into two issues where I'd rather agree on an approach with you before
I pick one.  One of them is a regression I introduced myself in the DEFINE
memory-leak fix; the other is an original design point from v47.  There is
also a third bug which I plan to handle together with the second one, since
it can be affected by that change -- I describe it at the end.

I have verified both of the issues below on an assert-enabled build (and a
non-assert build where relevant).


== 1. DEFINE evaluation reuses the per-output-tuple context (use-after-free) ==

nocfbot-0039 (the DEFINE memory-leak fix) added a ResetExprContext() in
update_reduced_frame, but it resets the wrong context.

ps_ExprContext is the per-output-tuple context that ExecWindowAgg resets
once per output row.  update_reduced_frame now resets it once per NFA row,
while the output row is still being formed -- so a pass-by-ref window
function result already datum-copied into that per-tuple memory (when
numfuncs > 1) is freed before ExecProject reads it.

Minimal trigger -- a pass-by-ref window function plus a second one over an
RPR window:

  SELECT lag(company) OVER w, count(*) OVER w FROM stock
   WINDOW w AS (PARTITION BY company ORDER BY tdate
                ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                AFTER MATCH SKIP PAST LAST ROW INITIAL
                PATTERN (START UP+)
                DEFINE START AS TRUE, UP AS price > PREV(price));

On a CLOBBER_FREED_MEMORY build the lag column comes out as 0x7F garbage;
in production it is garbage or a crash.  (An aggregate is not required --
lag + first_value hits the same reset via the frame-access path.)

Neither v47 nor the patch is the answer on its own: v47 had no reset here,
so no use-after-free, but the DEFINE scratch accumulated over the whole
forward scan (the leak nocfbot-0039 fixed); nocfbot-0039 added the per-row
reset but on the shared per-output-tuple context.  We do want a per-row
reset -- just not on that context.

So I think this needs a dedicated ExprContext for DEFINE evaluation, reset
once per NFA row: it keeps the memory bounded without touching the
per-output-tuple results.

Question: does a dedicated DEFINE ExprContext look right to you?


== 2. PREV/NEXT/FIRST/LAST placeholders collide with user functions ==

The nav operations are polymorphic pg_catalog functions (anyelement, OIDs
8126-8133) recognized by funcid in parse_func.c, which collides with
same-name user functions.

Outside DEFINE, a same-name function masks or clashes with the placeholder:
with public.last(anyelement), SELECT last(123) fails "cannot use last
outside a DEFINE clause"; with public.next(numeric), SELECT next(10) fails
"function next(integer) is not unique"; and even with no user function,
last(123) errors instead of "function last(integer) does not exist".

Inside DEFINE, a same-name function with an exact-type match beats the
anyelement placeholder, so PREV(price) silently becomes a plain FuncExpr
instead of an RPRNavExpr -- a wrong match result with no error (reproduced
for numeric, text and int).  And ruleutils deparses a bare PREV(, so
reparsing a view under a search_path with public.prev rebinds it (pg_dump
is safe via search_path = '').

This is original v47 design, not a regression.  Per the standard,
PREV/NEXT/FIRST/LAST are navigation operations with dedicated syntax, not
general-namespace functions -- the collision comes from mapping them onto
catalog functions plus search-path resolution.

I haven't found a clean approach yet.  Inside DEFINE these names have to be
the navigation operation (per the standard), yet outside DEFINE they
shouldn't shadow or break same-name user functions the way the catalog
placeholders do -- and since the deparse output is unqualified (a bare
PREV(...)), whatever we choose also has to round-trip cleanly.  I'm not
sure how best to reconcile those.

My rough leaning is to not add catalog functions for these at all: leave
resolution outside DEFINE exactly as it is today, and only inside DEFINE
adjust the function-resolution path itself to recognize the navigation
operations.  But that is still quite abstract.

Question: how would you approach this?


== Note: a third bug, to be handled together with item 2 ==

A navigation operation nested inside another nav's offset argument -- e.g.
PREV(price, NEXT(2::bigint, 0)) in a DEFINE clause -- slips past the parser
but trips Assert(!IsA(nav->offset_arg, RPRNavExpr)) in the planner.  So it
aborts at plan time on an assert build; without asserts, the backward form
PREV(price, PREV(2::bigint, 5)) reaches a runtime "cannot fetch row ...
before mark position".

The fix is to reject a nav inside an offset argument in the DEFINE walk.
But since item 2 may reshape that walker substantially from how it works
today, I'll do it together with item 2 and add it as a regression test there.

Thanks,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
On Wed, Jun 10, 2026 at 2:10 PM Henson Choi  wrote:
>
> Hi Tatsuo, Jian,
>
>
> == 2. PREV/NEXT/FIRST/LAST placeholders collide with user functions ==
>
> The nav operations are polymorphic pg_catalog functions (anyelement, OIDs
> 8126-8133) recognized by funcid in parse_func.c, which collides with
> same-name user functions.
>
> Outside DEFINE, a same-name function masks or clashes with the placeholder:
> with public.last(anyelement), SELECT last(123) fails "cannot use last
> outside a DEFINE clause"; with public.next(numeric), SELECT next(10) fails
> "function next(integer) is not unique"; and even with no user function,
> last(123) errors instead of "function last(integer) does not exist".
>
> Inside DEFINE, a same-name function with an exact-type match beats the
> anyelement placeholder, so PREV(price) silently becomes a plain FuncExpr
> instead of an RPRNavExpr -- a wrong match result with no error (reproduced
> for numeric, text and int).  And ruleutils deparses a bare PREV(, so
> reparsing a view under a search_path with public.prev rebinds it (pg_dump
> is safe via search_path = '').
>
> This is original v47 design, not a regression.  Per the standard,
> PREV/NEXT/FIRST/LAST are navigation operations with dedicated syntax, not
> general-namespace functions -- the collision comes from mapping them onto
> catalog functions plus search-path resolution.
>
> I haven't found a clean approach yet.  Inside DEFINE these names have to be
> the navigation operation (per the standard), yet outside DEFINE they
> shouldn't shadow or break same-name user functions the way the catalog
> placeholders do -- and since the deparse output is unqualified (a bare
> PREV(...)), whatever we choose also has to round-trip cleanly.  I'm not
> sure how best to reconcile those.
>
> My rough leaning is to not add catalog functions for these at all: leave
> resolution outside DEFINE exactly as it is today, and only inside DEFINE
> adjust the function-resolution path itself to recognize the navigation
> operations.  But that is still quite abstract.
>
> Question: how would you approach this?
>

SELECT first_value(1);
ERROR:  window function first_value requires an OVER clause
LINE 1: SELECT first_value(1);
               ^

select prosrc, prokind, proname from pg_proc
where proname = 'prev' or proname = 'first' or proname  = 'last' or
proname = 'next';

I am wondering, why the above query result functions not makred as
window function in catalog?


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

== 1. DEFINE evaluation use-after-free (to Tatsuo) ==

>> nocfbot-0039 (the DEFINE memory-leak fix) added a ResetExprContext() in
>> update_reduced_frame, but it resets the wrong context.
>>
>> ps_ExprContext is the per-output-tuple context that ExecWindowAgg resets
>> once per output row.  update_reduced_frame now resets it once per NFA row,
>> while the output row is still being formed -- so a pass-by-ref window
>> function result already datum-copied into that per-tuple memory (when
>> numfuncs > 1) is freed before ExecProject reads it.
>>
>> Neither v47 nor the patch is the answer on its own: v47 had no reset here,
>> so no use-after-free, but the DEFINE scratch accumulated over the whole
>> forward scan (the leak nocfbot-0039 fixed); nocfbot-0039 added the per-row
>> reset but on the shared per-output-tuple context.  We do want a per-row
>> reset -- just not on that context.
>>
>> So I think this needs a dedicated ExprContext for DEFINE evaluation, reset
>> once per NFA row: it keeps the memory bounded without touching the
>> per-output-tuple results.
>>
>> Question: does a dedicated DEFINE ExprContext look right to you?
>
> Can we use winstate->tmpcontext instead?

I don't think we can.  tmpcontext is idle where update_reduced_frame
would reset it, but not *during* DEFINE evaluation: a DEFINE with NEXT()
re-enters the spooler from inside its ExecEvalExpr (ExecEvalRPRNavSet
-> window_gettupleslot -> spool_tuples), and spool_tuples resets
winstate->tmpcontext (via ExecQualAndReset on partEqfunction) for every
input row it pulls under a PARTITION BY.  ExecEvalRPRNavRestore parks a
pass-by-ref nav result in that per-tuple memory to survive until the
next reset.  To give one example,

  -- the cast forces a pass-by-ref result; a by-value bigint is safe
  DEFINE b AS PREV(price::numeric) < NEXT(price::numeric)

frees PREV's result when NEXT spools the next row, before numeric_lt()
reads it -- the same use-after-free as nocfbot-0039, just on a different
context.  It is the normal forward-scan path (the NFA runs ahead of the
spool), and after a tuplestore spill even NEXT-free DEFINEs hit it.

More generally, tmpcontext fits its existing users because each one sets
its slots, evaluates, and resets within a shallow, straight-line region;
it is best kept to that limited, low-depth usage.  DEFINE evaluation
re-enters the spooler mid-expression, so it cannot honor that contract.

So I think the dedicated DEFINE ExprContext is the right call: a
once-per-NFA-row reset is a third cadence, distinct from tmpcontext
(per-input-tuple) and ps_ExprContext (per-output-tuple) -- the same
one-context-per-cadence pattern nodeWindowAgg and nodeAgg already use.

Thanks,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.
Based on https://github.com/assam258-5892/postgres/commits/RPR
Here are more minor review comments:

v47-0001-replace-some-AST-to-clause.nocfbot
Replace some "AST" to "clause".

v47-0002-refactor-gram.y.nocfbot
group Op and trailing ALT into one IF condition, this might improve readability.

v47-0003-refactor-volatile-expression-check.nocfbot

validate_rpr_define_volatility function, along with its helper
functions is removed.
contain_volatile_functions() already covers both volatile FuncExpr callees and
NextValueExpr, so a separate walker is not needed. The trade-off is that we lose
the error cursor position, but that seems better than to maintaining extra code.

The check is also moved to after preprocess_expression(), following the same
pattern as contain_volatile_functions_after_planning.

v47-0004-refactor-validateRPRPatternVarCount.nocfbot

validateRPRPatternVarCount() is recursive. Using the `rpDefs != NULL` sentinel
to gate the "DEFINE variable not used in PATTERN" check at the outermost call
level is awkward. That cross-check only needs to run once; it is better
expressed in the caller, transformDefineClause().

v47-0005-refactor-transformDefineClause.nocfbot

coerce_to_boolean() was deferred to a second pass over the completed
defineClause list, meaning pull_var_clause() ran on an expression that had not
yet been fully coerced/transformed. The more intuitively order should be:
transformExpr → coerce_to_boolean → pull_var_clause, so pull_var_clause always
sees the final expression form.

v47-0006-refactor-transformDefineClause.nocfbot

The allowed nav-expression combination is limited, therefore,
has_column_ref is not necessary.
Column reference checks can use contain_var_clause, and it's cheap.

Also, I made the following error message change:

-ERROR:  row pattern navigation offset must be a run-time constant
+ERROR:  row pattern navigation offset expression must not contain
column references



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

I looked into 0051 and have some suggestions.

If you like, can you please included the changes in v49?
I am going to release v48 soon.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

> index 1a754bcdac5..7ba0b6df849 100644
> --- a/src/backend/commands/explain.c
> +++ b/src/backend/commands/explain.c

> +static int
> +deparse_rpr_node(RPRPattern *pattern, int i, int limit, StringInfo buf)

One letter function argument name "i" looks unusual and better to be
named more meaningful one, like idx?

>  /*
> - * Process an ALT element: adjust depth parens and register separator positions.
> + * Find the END that closes the group opened by the BEGIN at beginIdx: the
> + * first END at the same depth scanning forward.
>   */
> -static void
> -deparse_rpr_alt(RPRPattern *pattern, int *idx, StringInfoData *buf,
> -				RPRDepth *prevDepth, bool *needSpace, List **altSeps)
> +static int
> +rpr_match_end(RPRPattern *pattern, int beginIdx)
>  {
> -	RPRPatternElement *elem = &pattern->elements[*idx];
> -
> -	/* Close parens for depth decrease */
> -	while (*prevDepth > elem->depth)
> -	{
> -		appendStringInfoChar(buf, ')');
> -		(*prevDepth)--;
> -		*needSpace = true;
> -	}
> -
> -	/* Open parens up to ALT's depth */
> -	while (*prevDepth < elem->depth)
> -	{
> -		if (*needSpace)
> -			appendStringInfoChar(buf, ' ');
> -		appendStringInfoChar(buf, '(');
> -		(*prevDepth)++;
> -		*needSpace = false;
> -	}
> +	RPRDepth	d = pattern->elements[beginIdx].depth;
> +	int			j;

If we change function arugument to other than "i", "j" here better to
be named "i".

>  /*
> - * Process a VAR element: adjust depth parens and output variable name.
> + * Scope end of the construct at index i: the first following element whose
> + * depth is no greater than i's own.  For an ALT marker this is the index just
> + * past its last branch, since depth stays constant across branch boundaries.
> + * FIN sits at depth 0, so a top-level ALT stops there.
>   */
> -static void
> -deparse_rpr_var(RPRPattern *pattern, int *idx, StringInfoData *buf,
> -				RPRDepth *prevDepth, bool *needSpace, List **altSeps)
> +static int
> +rpr_alt_scope_end(RPRPattern *pattern, int i)

One letter argument name "i" looks unusual and better to be named more
meaningful one, like idx?

>  {
> -	RPRPatternElement *elem = &pattern->elements[*idx];
> -
> -	/* Open parens for depth increase */
> -	while (*prevDepth < elem->depth)
> -	{
> -		if (*needSpace)
> -			appendStringInfoChar(buf, ' ');
> -		appendStringInfoChar(buf, '(');
> -		(*prevDepth)++;
> -		*needSpace = false;
> -	}
> +	RPRDepth	d = pattern->elements[i].depth;
> +	int			k;

If we change function arugument to other than "i", "j" here better to
be named "i".

> +/*
> + * Boundary of the alternation branch starting at b (i.e. the start of the next
> + * branch, or altEnd if b is the last branch).
> + *
> + * The branch-start element's jump points at the next branch when this is not
> + * the last branch.  jump is overloaded (a group BEGIN also uses it for its
> + * skip path), so confirm a real branch boundary with the relative test
> + * elem[j-1].next != j: at a true boundary the preceding branch's tail has its
> + * next redirected past the alternation, so it does not point at j.
> + */
> +static int
> +rpr_next_branch(RPRPattern *pattern, int b, int altEnd)

One letter function argument name "b" looks unusual and better to be
named more meaningful one, like bno or bid?

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
On Sat, Jun 13, 2026 at 8:26 PM Tatsuo Ishii  wrote:
>
> I have created v48 RPR (Row pattern recognition) patches based on the
> attached incremental patches against v47 patches. I have briefly
> looked through all the incremental patches. If I have missed
> something, I will follow up later.  The patches are based on the
> commit 3e3d7875e95 on the master branch.
>

get_windowclause_startup_tuples
do we need some comments for WindowClause->defineClause

src/backend/executor/README.rpr
  (2) Transcription to WindowClause
      - Copies rpPattern, rpSkipTo, initial fields

In transformRPR, we did this:
``wc->rpPattern = windef->rpCommonSyntax->rpPattern;``
Since this is an assignment, not a copy, is "Copies rpPattern" incorrect?

ISO reference typo: most occurrences use {ISO/IEC 19075},
but rpr_integration.sql and some places reference 9075-2:2016 instead of 19075.
We may need check all occurrences to ensure consistency.

In struct ResultRelInfo, we have fields like {ri_CheckConstraintExprs,
ri_WithCheckOptionExprs}.
Similarly, I want to rename WindowAggState->defineClauseList to
defineClauseExprs

I think the comment on function contain_rpr_walker can be removed,
since transformWithClause already explains it.

Is "judgment" really the right word?

I don't fully understand the purpose of eval_nav_offset_helper now.
Also, the branch where (isnull == true) and (offset < 0) appears
unreachable; it's never hit in the regression tests.
We should add some regression tests for these scenarios.



--
jian
https://www.enterprisedb.com/


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> get_windowclause_startup_tuples
> do we need some comments for WindowClause->defineClause

We already have comments for DEFINE clause. Do you think it's not enough?

	 * Moreover, if row pattern recognition is used, we charge the DEFINE
	 * expressions once per tuple for each variable that appears in PATTERN.

> src/backend/executor/README.rpr
>   (2) Transcription to WindowClause
>       - Copies rpPattern, rpSkipTo, initial fields
> 
> In transformRPR, we did this:
> ``wc->rpPattern = windef->rpCommonSyntax->rpPattern;``
> Since this is an assignment, not a copy, is "Copies rpPattern" incorrect?

I think "Copies" is Ok here. Yes, we do not use copyObject to copy the
rpPattern object but copying just the pointer can be regarded as kind
of "copy".

> ISO reference typo: most occurrences use {ISO/IEC 19075},
> but rpr_integration.sql and some places reference 9075-2:2016 instead of 19075.
> We may need check all occurrences to ensure consistency.

19075 and 9075-2 are the different standard documents.

19075-5: Information technology ― Guidance for the use of database language SQL ― Part 5: Row pattern recognition
9075-2: Information technology ― Database languages ― SQL ― Part 2: Foundation (SQL/Foundation)

IMO they are used differently depending on the context.

> In struct ResultRelInfo, we have fields like {ri_CheckConstraintExprs,
> ri_WithCheckOptionExprs}.
> Similarly, I want to rename WindowAggState->defineClauseList to
> defineClauseExprs

Looks reasonable proposal to me.

> I think the comment on function contain_rpr_walker can be removed,
> since transformWithClause already explains it.

I don't think we want to remove all function comments of
contain_rpr_walker. However I am not against removing "Used by
transformWithClause() to enforce ISO/IEC 9075-2:2016 7.17 SR 3)f) on
WITH RECURSIVE elements." because it's somewhat redundant.

> Is "judgment" really the right word?
> 
> I don't fully understand the purpose of eval_nav_offset_helper now.
> Also, the branch where (isnull == true) and (offset < 0) appears
> unreachable; it's never hit in the regression tests.
> We should add some regression tests for these scenarios.

Yeah. Maybe we can turn them into Assertions?

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi jian,

Thanks for the follow-up review patches. Once v48 is posted I'll base the
work on it and submit the accepted ones in v49. Reasoning per patch below,
with the disposition summarized at the end.

> v47-0001 Replace some "AST" to "clause".

Agreed on dropping "AST" -- it isn't our house term; "parse tree" is the
idiom across the tree, and "AST" barely shows up outside these RPR files
(just a jsonpath comment). One tweak: where the text names the data
structure (the README diagram and III-2 header, the parsenodes.h comments
on rpPattern), I'd use "PATTERN parse tree" rather than "clause", since
"clause" loses the tree-vs-flat-NFA contrast. Plain prose that just means
the SQL clause -> "clause", as you have it.

> v47-0002 group Op and trailing ALT into one IF condition, this might
> improve readability.

Here I'd lean toward keeping the current form. The complexity here comes
from the lexer (regex operators tokenized by the SQL operator lexer), and
grouping the branches doesn't remove it -- it just layers more cleverness
on top. I'd rather not add code complexity onto the lexer complexity; the
flat one-token-one-branch form stays easy to scan. A real simplification
would be lexer-side, out of scope here, so I'd leave 0002 as-is unless you
feel strongly.

> v47-0003 validate_rpr_define_volatility ... is removed.
> contain_volatile_functions() already covers both volatile FuncExpr
> callees and NextValueExpr ... The trade-off is that we lose the error
> cursor position, but that seems better than maintaining extra code.

You're right the detection is equivalent. But this restructures the
parse-side define_walker, which the upcoming PREV/NEXT name-binding fix
also reworks -- it even removes the spot where this check incidentally
backstops a nav mis-binding. I'd rather make the simplify-vs-keep call
against that final walker shape than churn it twice, so I'll keep the
current planner-side check for now and revisit once that fix lands.

> v47-0004 validateRPRPatternVarCount() ... the `rpDefs != NULL`
> sentinel ... is awkward. That cross-check only needs to run once;
> better expressed in the caller, transformDefineClause().

Agreed. The cross-check is a one-shot, list-level test -- a different kind
of thing from the recursive per-node count, and not really what
validateRPRPatternVarCount is for (validating the pattern var count).
Moving it to the caller runs it once by construction and leaves the
function true to its name, a pure count. Rejection behavior is unchanged.

> v47-0005 ... The more intuitive order should be: transformExpr ->
> coerce_to_boolean -> pull_var_clause, so pull_var_clause always sees
> the final expression form.

Agreed, that order is more intuitive. I'll make the change and watch for
any change in error output or behavior -- coerce_to_boolean now runs
per-define before pull_var_clause rather than in a second pass -- with
guard tests for domain-over-bool, nav Var preserved, and non-coercible
error, and submit it in v49 if those and the regression pass clean.

> v47-0006 ... has_column_ref is not necessary. Column reference checks
> can use contain_var_clause, and it's cheap. Also the message change:
> -row pattern navigation offset must be a run-time constant
> +row pattern navigation offset expression must not contain column
>  references

Agreed contain_var_clause is simpler and the new message reads better.
But this restructures define_walker too, which the nav name-binding fix
also reworks -- so as with 0003 I'd rather settle it against the post-fix
walker shape than churn it twice, and revisit once that fix lands.

Summary:

  0001  -> v49   (use "parse tree" where it names the structure, not "clause")
  0002  -> keep the current flat form
  0003  -> revisit after the nav name-binding fix
  0004  -> v49
  0005  -> v49   (after guard tests + regression pass)
  0006  -> revisit after the nav name-binding fix

For 0003 and 0006 -- both swap a hand-rolled walker for a standard helper
(contain_volatile_functions, contain_var_clause) -- I'll think this
through properly when I rework the walker: the convention of reaching for
those helpers against what the current checks buy us (the error cursor,
the specific messages), rather than deciding it by reflex.

More broadly, the substantive correctness defects take priority: the nav
name-binding fix and the rest of that series come ahead of these cleanup
refactors. Once v48 is posted I'll write up the current list of known
issues and send it to the thread.

Thanks again for the careful pass.

Best,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

More review based on https://github.com/assam258-5892/postgres/commits/RPR

remove_unused_subquery_outputs
``````
                        if (dvar->varno == var->varno &&
                            dvar->varattno == var->varattno &&
                            dvar->varlevelsup == var->varlevelsup)
                        {
                            needed_by_define = true;
                            break;
                        }
``````
dvar, var both can be whole-row Vars, but this seems to work for whole-row vars.
We need some simple regress tests for cases where both are whole-row
vars or one of them is a whole-row var.

I've attached a patch with some refactoring. The below is detailed
commit message.
--------------------------------------------------------------------
RPRNavExpr->resulttype should also marked as pg_node_attr(query_jumble_ignore)

collectPatternVariables is not needed.
The parser already ensures every DEFINE variable appears in PATTERN,
so there is nothing to filter.
Also, we don't really do anything special (like make a dummy Const) regarding
PATTERN variables that not appearing in the DEFINE clause.
See nfa_evaluate_row the for loop break.

buildDefineVariableList is trivial. No need to export it as an
external function.

Rename WindowAggState.defineClauseList to defineClauseExprs
Minor refactoring of regress test comments.
Flatten a needlessly nested block in show_window_def().
Replace a post-loop ListCell NULL check in
remove_unused_subquery_outputs() with a boolean flag.
Reduce the number of arguments in make_windowagg.
--------------------------------------------------------------------



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

I think there's a correctness problem in the RPR patch: a window function's
result can change depending on which other, unrelated window functions are
in the same query.

Pattern matching only advances when a window function reads the frame.
nth_value(x, n) returns NULL without reading the frame when n is NULL
(correct per the standard), so if it is the only window function in an RPR
window, the match never advances over those rows and the reduced frame no
longer matches a full scan.

Example -- one partition, 60 rows, price = id * 10:

  CREATE TABLE rpr_dormant (id int, price int);
  INSERT INTO rpr_dormant SELECT g, g*10 FROM generate_series(1,60) g;

  SELECT id, nth_value(price, CASE WHEN id < 50 THEN NULL ELSE 1 END) OVER w
  FROM rpr_dormant
  WINDOW w AS (
    ORDER BY id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    AFTER MATCH SKIP PAST LAST ROW
    PATTERN (A+)
    DEFINE A AS price > PREV(FIRST(price), 50)
  );

Run alone, the nth_value column does not follow the actual match structure;
adding an unrelated first_value(id) OVER w, which reads the frame every row,
changes it.  And while the match is dormant the mark position keeps
advancing, running ahead and trimming rows that the backward navigation
later needs -- so the same query can instead fail with "cannot fetch row N
before WindowObject's mark position".

I think an RPR window should perform the match for each row up front,
building its reduced frame during the row scan before the window functions
are evaluated, regardless of whether any function reads the frame.  The fix
belongs in the executor, not in nth_value -- the early return is standard,
and the same gap is reachable from any user-defined function that skips the
frame.

Does this direction seem right, or is the lazy, frame-driven matching
intentional in a way I'm missing?  Happy to prepare a patch.

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Mon, Jun 15, 2026 at 2:32 PM jian he  wrote:
>
> Hi.
>
> More review based on https://github.com/assam258-5892/postgres/commits/RPR
>

/* arity: a value expression and an optional offset */
Typo: arity

I've attached a patch with some refactoring.
Please note that the inline comments have not yet been updated to
match this refactoring.
The below is detailed commit message.
------------------------------------------------------------------------------------------------
Simplify ParseFuncOrColumn:
It now routes to ParseRPRNavCall exclusively when ParseExprKind is
EXPR_KIND_RPR_DEFINE *and* not column projection *and*
list_length(funcname) == 1.
Original behavior is preserved otherwise.

Centralize error handling:
Treat RPR navigation as FUNCDETAIL_NORMAL to reuse the common error handling in
ParseFuncOrColumn, effectively stripping redundant error checks from
ParseRPRNavCall.

Other miscellaneous code cleanups and minor refactoring.
------------------------------------------------------------------------------------------------



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian and Tatsuo,

Thanks for the patch and the careful review.

Tatsuo, item 1 below (attribute notation inside a DEFINE clause) is a
question for you; the rest is feedback on Jian's patch.

> /* arity: a value expression and an optional offset */
> Typo: arity

"arity" may be an unfamiliar term, so I'll reword the comment in plainer
language ("takes a value expression and an optional offset").

> Simplify ParseFuncOrColumn:
> It now routes to ParseRPRNavCall exclusively when ParseExprKind is
> EXPR_KIND_RPR_DEFINE and not column projection and list_length(funcname)
> == 1. Original behavior is preserved otherwise.
> Centralize error handling:
> Treat RPR navigation as FUNCDETAIL_NORMAL to reuse the common error
> handling in ParseFuncOrColumn, effectively stripping redundant error
> checks from ParseRPRNavCall.

I'd take this structural part -- it's a clear cleanup: ParseRPRNavCall
drops the duplicated decoration checks while the common path gives the
identical messages, with no change in behavior or output.

Two user-visible changes in the patch I'd rather settle on their own
before taking them:

1. Attribute notation inside a DEFINE clause, e.g. (f).prev.

   The guard this change removes is one I deliberately left undecided
   during development (hence the XXX comment), so I'd keep it for now and
   ask here.  Without it, (f).prev with no such field gives a generic
   "column \"prev\" not found ..." instead of the dedicated "cannot use
   row pattern navigation function PREV in attribute notation".  Three
   options:

   (a) Treat (f).prev as an ordinary function (prev(f)), the same as
       outside a DEFINE clause -- which is what the patch does.

   (b) Treat (f).prev as the navigation function -- read the attribute
       notation as navigation.  An ordinary function of that name is still
       reachable as public.prev(...).

   (c) Reject the ambiguous (f).prev with a dedicated error (what is
       currently committed), rather than resolving it one way or the
       other.

   My own leaning is actually (a) -- it keeps attribute notation behaving
   the same inside and outside a DEFINE clause.  (c) is what's in the tree
   now, and either way it changes the user-visible error and SQLSTATE, so
   I'd rather settle this explicitly than let the refactor decide it
   silently.  Tatsuo, what do you think?

2. The offset type-mismatch message.

   The patch rephrases

     offset argument of %s must be type bigint, not type %s
   to
     %s offset argument of type %s cannot be coerced to the expected
     bigint   (+ a hint)

   The behavior is identical, so I'd keep the original wording.  "argument
   ... must be type X, not type Y" is the established phrasing -- it's what
   coerce_to_boolean() produces, and the non-boolean DEFINE error in this
   same feature already uses it.  Rewording only the offset message would
   be inconsistent with that, for no behavioral gain.

One small process note: for patches that aren't really being proposed to
the list yet -- ones still under review, or throwaway implementations
written just to analyze a problem -- could you send them off-list or as a
pull request instead?  That keeps the thread focused on what's actually
being proposed for the patch.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo, Jian,
> 
> I think there's a correctness problem in the RPR patch: a window function's
> result can change depending on which other, unrelated window functions are
> in the same query.
> 
> Pattern matching only advances when a window function reads the frame.
> nth_value(x, n) returns NULL without reading the frame when n is NULL
> (correct per the standard), so if it is the only window function in an RPR
> window, the match never advances over those rows and the reduced frame no
> longer matches a full scan.

Ouch.

> Example -- one partition, 60 rows, price = id * 10:
> 
>   CREATE TABLE rpr_dormant (id int, price int);
>   INSERT INTO rpr_dormant SELECT g, g*10 FROM generate_series(1,60) g;
> 
>   SELECT id, nth_value(price, CASE WHEN id < 50 THEN NULL ELSE 1 END) OVER w
>   FROM rpr_dormant
>   WINDOW w AS (
>     ORDER BY id
>     ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>     AFTER MATCH SKIP PAST LAST ROW
>     PATTERN (A+)
>     DEFINE A AS price > PREV(FIRST(price), 50)
>   );
> 
> Run alone, the nth_value column does not follow the actual match structure;
> adding an unrelated first_value(id) OVER w, which reads the frame every row,
> changes it.  And while the match is dormant the mark position keeps
> advancing, running ahead and trimming rows that the backward navigation
> later needs -- so the same query can instead fail with "cannot fetch row N
> before WindowObject's mark position".
> 
> I think an RPR window should perform the match for each row up front,
> building its reduced frame during the row scan before the window functions
> are evaluated, regardless of whether any function reads the frame.  The fix
> belongs in the executor, not in nth_value -- the early return is standard,
> and the same gap is reachable from any user-defined function that skips the
> frame.
> 
> Does this direction seem right, or is the lazy, frame-driven matching
> intentional in a way I'm missing?  Happy to prepare a patch.

Yes, I think the direction is correct. Probably the patch would someting like this?

diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index cb6a484b7de..b6c12096c85 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -2523,6 +2523,9 @@ ExecWindowAgg(PlanState *pstate)
 			{
 				if (winstate->rpSkipTo == ST_NEXT_ROW)
 					clear_reduced_frame(winstate);
+
+				update_reduced_frame(winstate->nav_winobj,
+									 winstate->frameheadpos);
 			}
 
 			/*


> is the lazy, frame-driven matching
> intentional in a way I'm missing?

Not intentional.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thanks -- I'll go in this direction; your sketch has the shape of it.

> Yes, I think the direction is correct. Probably the patch would someting
> like this?
>
> + update_reduced_frame(winstate->nav_winobj,
> + winstate->frameheadpos);

Right: drive the match once per row, up front, instead of letting frame
access drive it.  That's the plan, with two refinements on top of the sketch.

First, a small refactor: I'll pull the reduced-frame loop and the mark
advance out into their own functions, called once per row before the window
functions run -- so the match tracks the row scan rather than frame reads.

Second, the mark: I'll advance it per NFA row from the match frontier rather
than the output row, so the tuplestore is trimmed as soon as the match is
done with each row.

Thanks,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
On Thu, Jun 18, 2026 at 5:50 PM Tatsuo Ishii  wrote:
>
> Hi Henson,
>
> > Hi Jian and Tatsuo,
> >
> > Thanks for the patch and the careful review.
> >
> > Tatsuo, item 1 below (attribute notation inside a DEFINE clause) is a
> > question for you; the rest is feedback on Jian's patch.
>
> > 1. Attribute notation inside a DEFINE clause, e.g. (f).prev.
> >
> >    The guard this change removes is one I deliberately left undecided
> >    during development (hence the XXX comment), so I'd keep it for now and
> >    ask here.  Without it, (f).prev with no such field gives a generic
> >    "column \"prev\" not found ..." instead of the dedicated "cannot use
> >    row pattern navigation function PREV in attribute notation".  Three
> >    options:
> >
> >    (a) Treat (f).prev as an ordinary function (prev(f)), the same as
> >        outside a DEFINE clause -- which is what the patch does.
> >
> >    (b) Treat (f).prev as the navigation function -- read the attribute
> >        notation as navigation.  An ordinary function of that name is still
> >        reachable as public.prev(...).
> >
> >    (c) Reject the ambiguous (f).prev with a dedicated error (what is
> >        currently committed), rather than resolving it one way or the
> >        other.
> >
> >    My own leaning is actually (a) -- it keeps attribute notation behaving
> >    the same inside and outside a DEFINE clause.  (c) is what's in the tree
> >    now, and either way it changes the user-visible error and SQLSTATE, so
> >    I'd rather settle this explicitly than let the refactor decide it
> >    silently.  Tatsuo, what do you think?
>

ParseFuncOrColumn cleanly handles (f).prev by translating it to prev(f) as a
regular function call. However, if a dedicated window navigation function
exists, this translation creates ambiguity — it becomes unclear whether prev(f)
is window navigation or a normal function call.

Cases with additional dots (e.g., public.prev(arg)) should also be
treated as normal
function calls, IMHO.

As a result, only prev(arg) and prev(arg, offset) are recognized as special
window navigation syntax, despite being visually identical to a function call.

Summary:
Dedicated window navigation functions should be removed entirely.  Window
navigation should be limited to a single syntactic form (no dots) — one that
*looks* like a function call but is parsed as syntax.

This is not unprecedented; there are many existing cases where something appears
to be a function call but is actually a syntax form, for example:

SELECT json_object('{}');
 json_object
-------------
 {}
(1 row)

SELECT public.json_object('{}');
ERROR:  function public.json_object(unknown) does not exist
LINE 1: SELECT public.json_object('{}');
               ^

So I think in the DEFINE context, it makes sense for some form that
looks like a function call to actually be syntax.


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

> ParseFuncOrColumn cleanly handles (f).prev by translating it to prev(f) as a
> regular function call. However, if a dedicated window navigation function
> exists, this translation creates ambiguity -- it becomes unclear whether
> prev(f) is window navigation or a normal function call.

Agreed, and that is the reason I would rather not have a dedicated
navigation function at all.  With navigation handled purely as syntax,
(f).prev never has to compete with it: attribute notation just falls
through to an ordinary function (prev(f)), the same inside and outside a
DEFINE clause.  That is Tatsuo's and my preferred option (a), so I will
settle on it.

> Cases with additional dots (e.g., public.prev(arg)) should also be treated
> as normal function calls, IMHO.

Yes.  A schema-qualified name is the explicit escape hatch to an ordinary
function; navigation is recognized only for an unqualified, single-element
name.

> As a result, only prev(arg) and prev(arg, offset) are recognized as special
> window navigation syntax, despite being visually identical to a function
> call.

Right -- that is exactly the surface I want to land on: the dotless
prev(...)/next(...)/first(...)/last(...) forms are navigation, everything
else is an ordinary function.

> Summary:
> Dedicated window navigation functions should be removed entirely.  Window
> navigation should be limited to a single syntactic form (no dots) -- one
> that *looks* like a function call but is parsed as syntax.

That is the direction I will take the tree.  So the three of us have
converged.

> This is not unprecedented; there are many existing cases where something
> appears to be a function call but is actually a syntax form, for example:
>
> SELECT json_object('{}');
>  json_object
> -------------
>  {}
> (1 row)
>
> SELECT public.json_object('{}');
> ERROR:  function public.json_object(unknown) does not exist
> LINE 1: SELECT public.json_object('{}');
>                ^
>
> So I think in the DEFINE context, it makes sense for some form that looks
> like a function call to actually be syntax.

The json_object parallel is exact at the user-visible level, but I want to
flag that the implementation has to differ underneath -- and that is
actually why navigation is not done the json_object way.

json_object can live in the grammar because two constraints do not apply to
it:

  - No context restriction.  JSON_OBJECT means the same thing wherever a
    value expression is allowed, so a single keyword production in the
    shared a_expr grammar is enough.

  - The name is safe to reserve.  Making json_object a keyword costs almost
    nobody an identifier.

Row pattern navigation has both constraints:

  - It must mean navigation *only* inside DEFINE; everywhere else
    prev/next/first/last are ordinary names.  bison is LALR(1) and
    context-free, so a production cannot be conditioned on "are we inside
    DEFINE"; a_expr is shared by SELECT lists, WHERE, etc.  And a row
    pattern definition is "ColId AS a_expr", so navigation can appear
    anywhere a value expression can.  Special-casing it in the grammar
    would mean duplicating the whole a_expr tree into a second DEFINE-only
    expression grammar (or resorting to lexer feedback), which is not worth
    it.

  - The names are common.  prev/next/first/last (especially next, first,
    last) are everyday column and function names; reserving them globally
    would break existing queries.

So the plan is the opposite of a grammar keyword: parse navigation as an
ordinary FuncCall and reinterpret it in parse analysis, gated on
p_expr_kind == EXPR_KIND_RPR_DEFINE and an unqualified, single-element
name.  That keeps one expression grammar, leaves the names free everywhere
else, and confines the special meaning to exactly the DEFINE context -- the
same "looks like a function call, parsed as syntax" behavior you described,
reached by a lighter path that does not grow the keyword list.

Thanks,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

CREATE TABLE stock (company TEXT, tdate DATE, price INTEGER);
CREATE TEMP TABLE stock (company TEXT, tdate DATE, price INTEGER);
SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS
pg_temp.stock.price > 0 );
SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS public.stock.price
> 0 );
SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS stock.price > 0 );

The error messages for the above 3 SELECT queries are different.
(pg_temp.stock.price, public.stock.price, stock.price) mean the same
thing: column reference,
Should we try to make the error messages consistent?

ERROR:  range variable qualified expression "rpr_composite.items" is
not allowed in DEFINE clause

"Range variable qualified expression" is non-standard that may confuse users.
To improve clarity and consistency, let's align this with the
established error pattern:

ERROR: invalid reference to FROM-clause entry for table "the_table"



What do you all think about renaming validateRPRPatternVarCount to
preprocessRPRPattern?
--------------------------------------------------------------------------------------------------
v48 [1] has a conflict with master, so the attached patches are based
on https://github.com/assam258-5892/postgres/commits/RPR

The attached v48-0001 mainly replaces PG_INT32_MAX with
RPR_QUANTITY_INF, but it also includes other changes.
See the commit message for detail.

The attached v48-0002 patch is more about miscellaneous refactoring.
The commit message is included below, enclosed by "-----":
--------------------------------------------------------------------------------------------------
Refactor buildRPRPattern to accept a WindowClause pointer directly. This
eliminates the need to pass internal fields like rpPattern, rpSkipTo, and
frameOptions as separate arguments.

collectDefineVariables is not needed, it's simple, and can integrated its logic
directly into buildRPRPattern easily.  Also removed tryUnwrapSingleChild since
its was simple enough to inline inside optimizeSeqPattern and
optimizeAltPattern.

Slightly adjust variable limits error message.

Restructure multiple INSERT INTO ... VALUES statements into multi-value insert
blocks (e.g., INSERT INTO ... VALUES (), ()). This is for brevity and is a good
practice even though performance gains is minor.

Long PATTERN strings (more than 2000 width!) in the regression tests were broken
into formatted multiline queries for readability.
--------------------------------------------------------------------------------------------------
[1] https://postgr.es/m/20260613.212530.63949290085162247.ishii%40postgresql.org



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi hackers,
> 
> When a WINDOW clause is not referenced by any window function, the pattern
> is never matched and the DEFINE expressions are never evaluated.
> 
> One consequence is that a DEFINE which would raise a run-time error raises
> nothing when the window is unused.  The same window definition behaves
> differently depending only on whether a window function consumes it:
> 
>   CREATE TABLE t (id int, v int);
>   INSERT INTO t VALUES (1, 10), (2, 20), (3, 15);
> 
> -- (1) the window IS used (count(*) OVER w): the DEFINE is evaluated
> 
>   SELECT count(*) OVER w AS cnt
>   FROM t
>   WINDOW w AS (
>       ORDER BY id
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       INITIAL
>       PATTERN (A+)
>       DEFINE A AS (1 / (v - v)) > 0
>   );
>   -- ERROR:  division by zero
> 
> -- (2) the window is NOT used (no window function): same definition
> 
>   SELECT v
>   FROM t
>   WINDOW w AS (
>       ORDER BY id
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       INITIAL
>       PATTERN (A+)
>       DEFINE A AS (1 / (v - v)) > 0
>   );
>   --  v
>   -- ----
>   --  10
>   --  20
>   --  15
>   -- (no error)
> 
> EXPLAIN (VERBOSE, COSTS OFF) of (2) confirms the window, and with it the
> DEFINE expression, are gone entirely:
> 
>       Seq Scan on public.t
>         Output: v, id
> 
> (A column-dependent division by zero is used so that the expression does not
> constant-fold and can only error at run time.)
> 
> This follows from existing, general planner behavior.  A window definition
> that no window function references is removed from the plan by
> select_active_windows(); the planner does this for every window, because a
> window with no consumer produces no output, so sorting or partitioning it
> would be wasted work.  Before RPR that reasoning was complete: an ordinary
> window has nothing but its output, so dropping an unused one changes nothing
> observable.
> 
> RPR is what turns this into a question.  A DEFINE clause is a per-row
> predicate that can have a run-time effect of its own -- here, raising an
> error -- independent of any output the window produces.  So the assumption
> behind the optimization, that an unused window has no observable behavior,
> no
> longer holds automatically once a window carries a DEFINE.  Whether the
> existing "drop it" optimization should still extend to an RPR window is a
> decision RPR's addition forces, not something the prior behavior settles.
> 
> The question is whether the current behavior is what we want:
> 
>   (a) Keep it.  Skipping the pattern matching for a window that produces
>       nothing is the natural optimization, and an expression that is never
>       evaluated raising no error is normal behavior.
> 
>   (b) Run the matching anyway, even though there is no output to produce, so
>       that DEFINE errors are raised regardless of whether a window function
>       consumes the window.
> 
> Option (a) is cheaper and consistent with how unevaluated expressions
> behave, but I lean towards (b): a faulty DEFINE should fail consistently
> rather than pass silently just because no window function happens to consume
> the window.  I would like to hear what you think.

I think we should follow (a).

From ISO/IEC 9075-2:2016 7.15  General Rules:
------------------------------------
1) Let SL be the  of the  or  that immediately contains TE [1].

Case:

a) If SL does not simply contain a , then the  is disregarded, and the result of TE is the result of the last
, ,  or  of
TE.
------------------------------------
[1] TE: Table expression

So I think the standard requires a window clause to be disregarded if
window function is not included in the select list. As DEFINE is a
part of a window clause, it should be disregarded if there's no window
function in the window clause too.

> behave, but I lean towards (b): a faulty DEFINE should fail consistently
> rather than pass silently just because no window function happens to consume
> the window.  I would like to hear what you think.

But we already pass faulty window clauses. Example:

-- If window function exists, faulty window clause (invalid frame
-- ending offset) is detected.
PREPARE prep AS
SELECT count(*) OVER w
FROM generate_series(1,5) g(i)
WINDOW w AS (
       ROWS BETWEEN CURRENT ROW AND $1 FOLLOWING
);
PREPARE
EXECUTE prep(-1);
psql:prepare.sql:7: ERROR:  frame ending offset must not be negative

DEALLOCATE prep;
DEALLOCATE

-- But if window function does not exist, the faulty window clause
-- (invalid frame ending offset) is not detected.
PREPARE prep AS
SELECT i
FROM generate_series(1,5) g(i)
WINDOW w AS (
       ROWS BETWEEN CURRENT ROW AND $1 FOLLOWING
);
PREPARE
EXECUTE prep(-1);
 i 
---
 1
 2
 3
 4
 5
(5 rows)

I think if we detect faulty DEFINE in the last case , it's not only
against the standard but against our existing behavior.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi,

Attached is the v49 RPR patches. Just rebased. Except that, nothing
has been changed since v48.

> I have created v48 RPR (Row pattern recognition) patches based on the
> attached incremental patches against v47 patches. I have briefly
> looked through all the incremental patches. If I have missed
> something, I will follow up later.  The patches are based on the
> commit 3e3d7875e95 on the master branch.
> 
> The series of patches are to implement the row pattern recognition
> (SQL/RPR) feature. Currently the implementation is a subset of SQL/RPR
> (ISO/IEC 19075-2:2016). Namely, implementation of some features of
> R020 (WINDOW clause). R010 (MATCH_RECOGNIZE) is out of the scope of
> the patches.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> From ISO/IEC 9075-2:2016 7.15 <window clause> General Rules:
> ...
> a) If SL does not simply contain a <window function>, then the <window
> clause> is disregarded, and the result of TE is the result of the last
> <from clause>, <where clause>, <group by clause> or <having clause> of TE.

Thank you -- this is exactly the text I was missing.  I only have ISO/IEC
19075-5 (the guidance / technical report), which describes what a window
definition does but says nothing about a window clause being disregarded
when no window function references it.  The General Rule you quote settles
it: disregarding an unused window clause is required by the standard, and
since DEFINE is part of the window clause, it is disregarded along with the
rest.  So evaluating its DEFINE -- option (b) -- would mean running a clause
the standard tells us to ignore.

> But we already pass faulty window clauses. Example:
> ... ERROR:  frame ending offset must not be negative ...
> I think if we detect faulty DEFINE in the last case, it's not only
> against the standard but against our existing behavior.

Agreed, and the parallel is convincing.  An unused window already escapes
the negative-frame-offset check, so singling out DEFINE as the one clause
that must fire regardless would be inconsistent with how the rest of an
unused window already behaves.

This also matches the planner: select_active_windows() drops any window with
no referencing WindowFunc, and its comment already cites the same <window
clause> General Rules (General Rule 4) as its basis.

Either way, the disregard rule governs only execution.  A failure raised in
the parser, transform, rewrite, or planner is a separate, static layer the
rule does not touch.  And at execution there is nothing to evaluate: an
unused window is never turned into a WindowAgg node, so its DEFINE is never
reached.

So I'm convinced -- let's keep (a), the current behavior, and I'll treat
this open question as closed, with no patch change.  For the record, the two
halves stay cleanly separated: the RPR DEFINE volatility check still visits
every window clause at preprocessing (independent of select_active_windows),
while run-time DEFINE evaluation happens only for windows that survive it.

Thanks for digging up the standard text.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Jian,

Only comments to error messages.

> CREATE TABLE stock (company TEXT, tdate DATE, price INTEGER);
> CREATE TEMP TABLE stock (company TEXT, tdate DATE, price INTEGER);
> SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
> ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS
> pg_temp.stock.price > 0 );
> SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
> ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS public.stock.price
>> 0 );
> SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
> ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS stock.price > 0 );
> 
> The error messages for the above 3 SELECT queries are different.
> (pg_temp.stock.price, public.stock.price, stock.price) mean the same
> thing: column reference,
> Should we try to make the error messages consistent?

I have tested above queries to see how error messages actually look
like. These errors raised by different reasons and becomes different
looks natural. I see no consistency problem here.

SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS
pg_temp.stock.price > 0 );
(1)
psql:rangevar.sql:6: ERROR:  42601: qualified expression "pg_temp.stock.price" is not allowed in DEFINE clause
LINE 3: pg_temp.stock.price > 0 );
        ^
LOCATION:  transformColumnRef, parse_expr.c:966

"stock" table in the FROM clause is actually pg_temp.stock. The
expression "pg_temp.stock.price > 0" is valid in general but in a DEFINE
clause schema qualified column reference is not allowed by the
standard. So the error messages look reasonable to me.

SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS public.stock.price
> 0 );
(2)
psql:rangevar.sql:9: ERROR:  42P01: invalid reference to FROM-clause entry for table "stock"
LINE 2: ...W AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS public.sto...
                                                             ^
DETAIL:  There is an entry for table "stock", but it cannot be referenced from this part of the query.
LOCATION:  errorMissingRTE, parse_relation.c:3864

"stock" table in the FROM clause is actually pg_temp.stock. The
expression "public.stock.price > 0" is not valid because public.stock
is not in the FROM clause. The error messages look reasonable to me.

SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS stock.price > 0 );
(3)
psql:rangevar.sql:11: ERROR:  42601: range variable qualified expression "stock.price" is not allowed in DEFINE clause
LINE 2: ...W AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS stock.pric...
                                                             ^
LOCATION:  transformColumnRef, parse_expr.c:674

The error message precisely points out that the range variable "stock"
qualifies "stock.price", which is not allowed by the standard. I see
no problem here.

> ERROR:  range variable qualified expression "rpr_composite.items" is
> not allowed in DEFINE clause
> 
> "Range variable qualified expression" is non-standard that may confuse users.

Which part of it do you think "non-standard"?  The standard uses both
terms "Range variable" and "qualified".

> To improve clarity and consistency, let's align this with the
> established error pattern:
> 
> ERROR: invalid reference to FROM-clause entry for table "the_table"

-1. As I explained above, these 3 errors raised by the different
 reasons. "invalid reference to FROM-clause entry for table
 "the_table" is only applied to (2). So unified (1) and (3) will make
 more confusion.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> rest.  So evaluating its DEFINE -- option (b) -- would mean running a clause
> the standard tells us to ignore.

Right.

> Agreed, and the parallel is convincing.  An unused window already escapes
> the negative-frame-offset check, so singling out DEFINE as the one clause
> that must fire regardless would be inconsistent with how the rest of an
> unused window already behaves.
> 
> This also matches the planner: select_active_windows() drops any window with
> no referencing WindowFunc, and its comment already cites the same  clause> General Rules (General Rule 4) as its basis.
> 
> Either way, the disregard rule governs only execution.  A failure raised in
> the parser, transform, rewrite, or planner is a separate, static layer the
> rule does not touch.  And at execution there is nothing to evaluate: an
> unused window is never turned into a WindowAgg node, so its DEFINE is never
> reached.

Yes, the rule only applies to execution. I think what we do in other
phases is implementation dependent.

> So I'm convinced -- let's keep (a), the current behavior, and I'll treat
> this open question as closed, with no patch change.  For the record, the two
> halves stay cleanly separated: the RPR DEFINE volatility check still visits
> every window clause at preprocessing (independent of select_active_windows),
> while run-time DEFINE evaluation happens only for windows that survive it.
> 
> Thanks for digging up the standard text.

You are welcome.  Please feel free to ask me if you want to know what
9075-2 says about someting.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

Hi hackers,

This is an increment on top of v49: it lands the two fixes I left as
still-to-come there -- the DEFINE-evaluation use-after-free, now a dedicated
ExprContext, and the PREV/NEXT/FIRST/LAST namespace collision -- adds a
correctness fix found while reviewing the tuplestore spool (dormant
matches), and applies Jian He's and Tatsuo Ishii's review of the v48 series
as a set of mostly behavior-neutral commits.

Before the patch list, a note on CI: cfbot has been red here, but the
failure is not RPR -- it is the libLLVM 19 + ASAN JIT crash (CF 6870), which
reproduces on plain master.  The build-system fix (exclude sanitizer flags
from JIT bitcode generation) is Matheus Alcantara's; the meson half is
v3-0001-Exclude-sanitizer-flags-from-LLVM-JIT-bitcode-gen.patch:

  https://postgr.es/m/CAAAe_zBX5uV9K0ikuROLgdNvDCgGqHRskT-73L+oX9=3aXR2AQ@mail.gmail.com

For v50, what would you think about folding that meson patch in as a
temporary prerequisite at the front of the series, so cfbot's ASAN build
gets past the JIT crash and actually exercises RPR?

First, two cleanups splitting changes unrelated to RPR out of the feature
patch:

  nocfbot-0001  Remove blank-line changes unrelated to row pattern
                recognition
  nocfbot-0002  Remove unnecessary includes from the row pattern
                recognition patch

The fixes -- the two I left as still-to-come in v48, plus the dormant-match
fix found since (nocfbot-0003..0005, all behavior-changing):

  nocfbot-0003  Recognize row pattern navigation operations by name in
                DEFINE
      The placeholder PREV/NEXT/FIRST/LAST pg_proc functions polluted the
      ordinary function namespace and could be silently misbound to
      same-named user functions.  They are dropped; an unqualified
      PREV/NEXT/FIRST/LAST inside a DEFINE clause is recognized as
      navigation by name, while a schema-qualified call still reaches an
      ordinary function.  A navigation operation inside a navigation offset
      -- which must be a run-time constant -- is now rejected instead of
      crashing the planner.  (f).prev follows attribute notation as an
      ordinary function, the same inside and outside DEFINE.

  nocfbot-0004  Use a dedicated ExprContext for RPR DEFINE clause
                evaluation
      nocfbot-0039's interim leak fix had turned into a use-after-free and
      was voided in v48.  DEFINE evaluation now has its own ExprContext,
      reset once per row and separate from both the per-output-tuple context
      and tmpcontext, resolving the leak and the use-after-free together.

  nocfbot-0005  Drive RPR row pattern matching once per row
      Matching only advanced when a window function read the frame, so a row
      whose only window function skips the frame (e.g. nth_value() with a
      NULL offset) left the match behind the current row -- silently wrong
      results and a spurious "cannot fetch row ... before WindowObject's mark
      position" error.
      The match is now driven once per row, before the window functions run;
      the navigation mark advances from the frontier the match reached, so
      the tuplestore is trimmed sooner.

Review of v48 (Jian He, and Tatsuo Ishii), as nocfbot-0006..0013 --
behavior-neutral except where tagged [behavior change]:

  nocfbot-0006  Tidy up row pattern recognition plumbing
      Remove the dead collectPatternVariables()/buildDefineVariableList()
      helpers; drop the redundant rpSkipTo/defineClause arguments of
      make_windowagg(); mark RPRNavExpr.resulttype query_jumble_ignore;
      rename WindowAggState.defineClauseList to defineClauseExprs; assorted
      block flattening.  No change to planner or executor output.

  nocfbot-0007  Further tidy up row pattern recognition plumbing
      Drop the now-unused WindowClause argument of transformDefineClause();
      use foreach_node()/foreach_current_index() in the DEFINE walkers and
      drop their redundant end-of-list break tests; minor include and
      comment fixups.  No output change.

  nocfbot-0008  Refactor transformDefineClause in row pattern recognition
                [behavior change]
      Hoist the "DEFINE variable not used in PATTERN" cross-check out of the
      recursive walker into its caller, and reorder per-variable processing
      to transformExpr -> coerce_to_boolean -> pull_var_clause, dropping the
      separate second coercion pass.  The only observable change is one
      error-cursor position: the duplicate-variable error now points at the
      later definition.  New regression coverage for DEFINE coercion and Var
      propagation is added.

  nocfbot-0009  Replace a bare block with an else in the RPR DEFINE clause
                walker
      Cosmetic flattening of define_walker()'s phase dispatch into an
      if / else if / else chain.

  nocfbot-0010  Rename loop index variables in row pattern deparse helpers
      Tatsuo's suggestion; descriptive names for the deparse index/loop
      variables, no change to deparsed output.

  nocfbot-0011  Rename absorption "judgment point" to "comparison point" in
                comments
      Comment and executor-README wording only; identifiers unchanged.

  nocfbot-0012  Improve comments, documentation, and naming for row pattern
                recognition
      A batch of comment/doc clarity fixes -- the AST-vs-parse-tree wording,
      the Run Condition EXPLAIN test, the contain_rpr_walker comment, the
      ALT-marker and quantifier comments, the RPCommonSyntax.location "or -1"
      convention, and the transformDefineClause header -- plus renaming the
      saturated-count sentinel RPR_COUNT_MAX to RPR_COUNT_INF for
      consistency with RPR_QUANTITY_INF.

  nocfbot-0013  Document eval_nav_offset_helper's NULL/negative offset
                handling
      Comment only.  The NEEDS_EVAL offset branch is reachable (a Param
      offset can be NULL or negative at run time), so it stays a graceful
      return rather than an assertion.


For traceability, where each patch came from:

  patch          proposer        proposal
  -------------  --------------  -------------------------------------------------
  nocfbot-0001   Henson          drop blank-line churn unrelated to RPR
  nocfbot-0002   Henson          drop unnecessary includes
  nocfbot-0003   Henson          nav namespace collision; (f).prev as ordinary function
  nocfbot-0004   Henson          dedicated ExprContext for DEFINE evaluation
  nocfbot-0005   Henson          drive row pattern matching once per row
  nocfbot-0006   Jian He         tidy RPR plumbing
  nocfbot-0007   Henson          further plumbing tidy
  nocfbot-0008   Jian He         refactor transformDefineClause
  nocfbot-0009   Jian He         bare block -> else in the DEFINE walker
  nocfbot-0010   Tatsuo Ishii    rename deparse loop/index variables
  nocfbot-0011   Jian He         "judgment point" -> "comparison point" wording
  nocfbot-0012   Jian He         comment/doc clarity batch + RPR_COUNT_INF rename
  nocfbot-0013   Jian He         document eval_nav_offset NULL/negative offset handling


Still to come -- Jian He's follow-ups on this thread (2026-06-19), to fold
once each approach is agreed (all under review):

  topic                          proposed change
  -----------------------------  -------------------------------------------
  DEFINE qualified column-ref    make the differing pg_temp.t.c /
   error messages                 public.t.c / t.c messages consistent, on
                                  the standard "invalid reference to
                                  FROM-clause entry for table"
  validateRPRPatternVarCount     rename to preprocessRPRPattern
  quantifier INF bound           abstract behind an RPR_QUANTITY_INF macro
  "nullable" variables           rename to match_empty
  splitRPRTrailingAlt            use foreach_node / foreach_current_index
  buildRPRPattern signature      pass the WindowClause directly
  collectDefineVariables /       inline and drop the helpers
   tryUnwrapSingleChild
  variable-limit error msg       fold the maximum into the primary message


Quality work to run alongside, on Linux: Valgrind (leak and use-after-free,
to exercise the DEFINE ExprContext fix, whose reproducer is cassert-only)
and standing gcov coverage to catch untested planner paths.


Longer term, and out of scope for this CF entry:

  - Smaller documentation and error-message follow-ups (glossary, the
    bounded-quantifier message, README wording).
  - Short-circuit / tri-state DEFINE evaluation, as a separate series.
  - SEEK clause support (SQL:2016).
  - Empty pattern PATTERN () -- correctly rejected today; deferred because
    its empty-match semantics (SHOW/OMIT EMPTY MATCHES) are tied to the
    still-out-of-scope MEASURES clause.
  - Relaxing the DEFINE-subquery over-rejection where the standard permits
    it (the subquery does no RPR of its own and makes no outer reference).
  - Prefix-pattern absorption (an optimization; designed and intentionally
    split out as its own series).
  - R010 (MATCH_RECOGNIZE in the FROM clause) and the shared RPRContext it
    would back.


Please let me know if any of the slicing or grouping looks off.

On a personal note, some fatigue has built up, so I'll be easing off the
pace a little for a while and may be slower to follow up on this thread
than I have been.  The work continues -- just at a gentler pace.

Thanks again to Jian and Tatsuo for the careful review.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
> CREATE TABLE stock (company TEXT, tdate DATE, price INTEGER);
> CREATE TEMP TABLE stock (company TEXT, tdate DATE, price INTEGER);
> SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
> ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS
> pg_temp.stock.price > 0 );
> SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
> ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS public.stock.price
>> 0 );
> SELECT count(*) over w FROM stock WINDOW w AS ( ROWS BETWEEN CURRENT
> ROW AND UNBOUNDED FOLLOWING PATTERN (A) DEFINE A AS stock.price > 0 );
>
> The error messages for the above 3 SELECT queries are different.
> (pg_temp.stock.price, public.stock.price, stock.price) mean the same
> thing: column reference,
> Should we try to make the error messages consistent?

Tatsuo has already covered this one, and I'm with him: I'd keep the three
as they are.  They come from three different paths -- a schema-qualified
reference rejected inside DEFINE, a public.stock that simply isn't the
FROM-clause relation, and a range-variable qualification -- so a single
message can't describe all three accurately.

It's worth saying why beyond "different paths".  In the standard a row
pattern variable is itself a range variable -- ISO/IEC 19075-5 4.10 has them
"used to qualify column references" in MEASURES and DEFINE -- so a qualified
name
such as A.price denotes the price column at the rows mapped to pattern
variable A.  That notation collides directly with table/range-variable
qualification: A.price and stock.price are spelled identically, and a
one-component qualifier is ambiguous between a pattern variable and a
relation.  Sorting out that ambiguity is precisely what separates the three
paths above, which is the other reason I'd keep them distinct rather than
fold them into one message now.

We don't implement pattern-variable-qualified references yet -- today an
unqualified column is implicitly the universal row pattern variable, and
that is all DEFINE and MEASURES accept.  I'd like to design and build that
qualifier support once this commit lands; since it sits right on top of the
name resolution you're raising here, I'd genuinely welcome your help with
both the design and the implementation, if you're interested.

> "Range variable qualified expression" is non-standard that may confuse users.
> To improve clarity and consistency, let's align this with the
> established error pattern:
>
> ERROR: invalid reference to FROM-clause entry for table "the_table"

"invalid reference to FROM-clause entry for table" only fits the middle
case (public.stock); routing (1) and (3) through it would misdescribe them.
On the wording, "range variable qualified" is not really non-standard -- it
is the standard's own framing, the same one above: a row pattern variable
is a range variable, and DEFINE qualification is exactly where that
distinction becomes load-bearing once qualifier resolution lands.  A generic
FROM-clause message would erase the very difference we will need to surface
then, so I'd keep the dedicated wording rather than fold it in.

> What do you all think about renaming validateRPRPatternVarCount to
> preprocessRPRPattern?

Agreed the name is too narrow -- besides checking the count against
RPR_VARID_MAX, the function collects the unique PATTERN variable names into
p_rpr_pattern_vars (the list transformColumnRef uses to spot a
pattern-variable qualifier, and for now to reject A.price).  preprocessRPRPattern
feels too broad, though.  Rather than pin a name down now, I'd leave some
room: the function's role will shift as the qualifier work lands, so I'll
work out a fitting name as I write that patch.

> The attached v48-0001 mainly replaces PG_INT32_MAX with
> RPR_QUANTITY_INF, but it also includes other changes.
> See the commit message for detail.

Behavior-neutral and a clear improvement; I'll take it.  I'll go through the
details closely and fold in any fixups as I write the patch.

> The attached v48-0002 patch is more about miscellaneous refactoring.
> [...]
> Refactor buildRPRPattern to accept a WindowClause pointer directly.
> [...]
> collectDefineVariables is not needed [...] Also removed tryUnwrapSingleChild
> [...]
> Slightly adjust variable limits error message.

Also good.  The helper inlining and the WindowClause signature both read as
clear wins; I'll sort out the variable-limit message wording and the rest of
the small details as I fold it.

Thanks again for the careful work.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo, Jian,

Please find attached (coverage.tgz) the code coverage analysis for the RPR branch.

* Measurement setup
- Target: PostgreSQL RPR branch, modified-lines basis (RPR-base..RPR diff)
- Build: gcc --enable-coverage with --with-llvm (LLVM JIT module included; both C and C++ instrumented)
- Tests: make check-world (regression + TAP + contrib; no forced JIT settings)

* Results
- Modified-line coverage: 2,608 / 2,702 (96.5%)
- Functions: 172 / 173 (99.4%)
- Breakdown of the 94 uncovered lines:
  - Reachable (coverable by tests): 28 lines
  - Unreachable (defensive / dead code): 66 lines
    - worth cleaning up (Assert / remove / coverage-exclude): 22 lines
    - best kept as idiomatic guards (enum default, pg_unreachable(),
      public windowapi.h relpos guards): 44 lines

* Projected coverage (modified-lines basis)
- Current:                                              96.5%  (2,608 / 2,702)
- After adding the proposed tests (+28 reachable):      97.6%  (2,636 / 2,702)
- After also cleaning up only the lines worth changing
  (-22; the 44 idiomatic guards are kept on purpose):   98.4%  (2,636 / 2,680)
- If every unreachable line were removed (not advised
  for the idiomatic guards):                            ~100%  (no residual uncovered lines)

* Picking a target -- your input would help
The analysis points to three possible levels:
  (a) tests only             -> 97.6%   (add tests for the 28 reachable lines)
  (b) tests + safe cleanups  -> 98.4%   (also Assert/remove the 22 worth-fixing lines;
                                         keep the 44 idiomatic guards as-is)
  (c) full cleanup           -> ~100%   (also rework the idiomatic guards -- usually undesirable)
My own inclination sits somewhere between (a) and (b): add all the reachable-line tests, and
clean up only the most clear-cut lines (e.g. the arithmetic-underflow Assert conversions and
the dead _equalRPRPattern body), while deciding the remaining defensive lines case by case
rather than touching all 22 at once. I'd value your view on how far to take this.

One caveat: this reachable/unreachable classification was produced with AI assistance, so it
may be wrong in places. When I actually write the test cases I will scrutinize each item
individually and verify it against a coverage build before proposing anything.

* What the report contains
Each uncovered line carries a collapsible box stating:
- Reachable / Unreachable classification + confidence
- Reachable: the concrete SQL test that covers it
- Unreachable: the reason it cannot execute, and the recommended source change
Consecutive lines on the same straight-line flow (no branch in between) are merged into one box.

* How to view
  tar xzf coverage.tgz
  # open coverage/index.html in a browser
  #  -> pick a file -> expand the collapsible box under each red (uncovered) line

* Contents
- coverage/index.html  : per-file coverage overview
- coverage/html/       : per-file detail (source + uncovered-line analysis)
- coverage/untested.md : checklist of uncovered lines

Please review. Feel free to reply with any questions.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Before the patch list, a note on CI: cfbot has been red here, but the
> failure is not RPR -- it is the libLLVM 19 + ASAN JIT crash (CF 6870), which
> reproduces on plain master.  The build-system fix (exclude sanitizer flags
> from JIT bitcode generation) is Matheus Alcantara's; the meson half is
> v3-0001-Exclude-sanitizer-flags-from-LLVM-JIT-bitcode-gen.patch:
> 
> 
> https://postgr.es/m/CAAAe_zBX5uV9K0ikuROLgdNvDCgGqHRskT-73L+oX9=3aXR2AQ@mail.gmail.com
> 
> For v50, what would you think about folding that meson patch in as a
> temporary prerequisite at the front of the series, so cfbot's ASAN build
> gets past the JIT crash and actually exercises RPR?

I have sent an email to those who are working on CI to let them know
the CI is partly broken and the fix has been proposed.
https://www.postgresql.org/message-id/20260622.192319.148395607405547262.ishii%40postgresql.org

Once the fix is installed, the patch does not need to be part of
v50. Let's wait for a while.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

Hi hackers,

This is v50, folding in the outstanding review.  From my side there are no
known issues left, so I think it makes a good starting point for the kind of
thorough public review the feature should get before commit.

On scope: the feature is almost entirely additive.  It adds no SQL-visible
objects -- no DDL, catalog entries, or built-in functions -- and no on-disk
or catalog-format change, so it needs no catversion bump.  Row pattern
recognition is reached only through the new window-specification grammar and
the window-function machinery it extends; code that does not use it follows
the same paths as before.  The footprint is narrow by design, so the risk to
existing behaviour stays low.  It is not meant for back-porting, but it is
contained enough that a back-port would be feasible -- a measure of how
little it disturbs anything else.

That said, the feature is not simple inside, and review would pay off most on
the parts that took the most care: the NFA matcher (alternation, reluctant
quantifiers, nullable / empty-match handling, and the dormant matches in the
tuplestore spool); the executor's tuple-slot navigation (the EEOP_RPR_NAV_SET
/ _RESTORE steps and the slot caching behind PREV / NEXT / FIRST / LAST); and
the planner/executor optimizations -- context absorption and the reduced-frame
navigation that lets the tuplestore be trimmed early.  The surrounding
plumbing is, by comparison, mechanical.

The feature is unchanged since v49 and is re-attached as v49-0001..0009 so
the series applies on master; the work since v49 is the increment
v50-0001..0020 on top.

A note on the posting itself first: the v49 increment went out as
nocfbot-*.txt attachments, which cfbot does not apply, and a later
coverage-report attachment (no patches inside) left the entry with nothing
applicable -- so cfbot has been building plain master, and its current green
is just master's, with no RPR patch applied.  v50 goes out as a normal
format-patch series so cfbot picks it up and actually exercises RPR.

One ASAN task is likely to go red once it does: the libLLVM 19 + ASAN JIT
crash (CF 6870) is still unfixed in master, and RPR exercises the JIT paths,
so the ASAN build will hit it -- a toolchain/master issue, not RPR.  Matheus
Alcantara's meson fix (exclude sanitizer flags from JIT bitcode generation)
addresses it but is not merged yet; it is not folded into this series.

First, two cleanups splitting changes unrelated to RPR out of the feature
patch:

  v50-0001  Remove blank-line changes unrelated to row pattern recognition
  v50-0002  Remove unnecessary includes from the row pattern recognition patch

The fixes (v50-0003..0005, all behavior-changing):

  v50-0003  Recognize row pattern navigation operations by name in DEFINE
  v50-0004  Use a dedicated ExprContext for RPR DEFINE clause evaluation
  v50-0005  Drive RPR row pattern matching once per row

Review of v48 (Jian He, and Tatsuo Ishii), v50-0006..0013 -- behavior-neutral
except where tagged [behavior change]:

  v50-0006  Tidy up row pattern recognition plumbing
  v50-0007  Further tidy up row pattern recognition plumbing
  v50-0008  Refactor transformDefineClause in row pattern recognition
            [behavior change]
  v50-0009  Replace a bare block with an else in the RPR DEFINE clause walker
  v50-0010  Rename loop index variables in row pattern deparse helpers
  v50-0011  Rename absorption "judgment point" to "comparison point" in comments
  v50-0012  Improve comments, documentation, and naming for row pattern recognition
  v50-0013  Document eval_nav_offset_helper's NULL/negative offset handling

New since v49 -- the agreed Jian He follow-ups and the standing quality work
(v50-0014..0020):

  v50-0014  Tidy up the row pattern unbounded-quantifier sentinel
  v50-0015  Simplify row pattern compilation by passing the WindowClause
  v50-0016  Reword the row pattern variable-limit error
  v50-0017  Reformat row pattern regression tests for readability
  v50-0018  Add row pattern recognition coverage tests and tidy unreachable code
  v50-0019  Free RPR NFA states with pfree() under USE_VALGRIND
  v50-0020  Clarify row pattern recognition comments on "step" and no_equal

For traceability, where each patch came from:

  patch     proposer       proposal
  --------  -------------  --------------------------------------------------
  v50-0001  Henson         drop blank-line churn unrelated to RPR
  v50-0002  Henson         drop unnecessary includes
  v50-0003  Henson         nav namespace collision; (f).prev as ordinary function
  v50-0004  Henson         dedicated ExprContext for DEFINE evaluation
  v50-0005  Henson         drive row pattern matching once per row
  v50-0006  Jian He        tidy RPR plumbing
  v50-0007  Henson         further plumbing tidy
  v50-0008  Jian He        refactor transformDefineClause
  v50-0009  Jian He        bare block -> else in the DEFINE walker
  v50-0010  Tatsuo Ishii   rename deparse loop/index variables
  v50-0011  Jian He        "judgment point" -> "comparison point" wording
  v50-0012  Jian He        comment/doc clarity batch + RPR_COUNT_INF rename
  v50-0013  Jian He        document eval_nav_offset NULL/negative offset handling
  v50-0014  Jian He        abstract the quantifier INF bound / sentinel
  v50-0015  Jian He        pass the WindowClause into pattern compilation
  v50-0016  Jian He        fold the maximum into the variable-limit message
  v50-0017  Henson         reformat the regression tests
  v50-0018  Henson         coverage tests + tidy unreachable code
  v50-0019  Henson         free NFA states with pfree() under USE_VALGRIND
  v50-0020  Jian He        clarify the "step" and no_equal comments

Disposition of the latest review (Jian He -- the on-list v48 follow-ups and
the off-list thread that produced v50-0020):

  proposal                              disposition
  ------------------------------------  -------------------------------------
  RPR_QUANTITY_INF sentinel unify       accepted -> v50-0014
  pass WindowClause; inline             accepted -> v50-0015
   collectDefineVariables /
   tryUnwrapSingleChild
  variable-limit error reword           accepted -> v50-0016 (kept errmsg +
                                         errdetail, not a single message)
  define "step"; reword the no_equal    accepted -> v50-0020 (off-list)
   comment
  "nullable" -> match_empty             rejected -- "nullable" is the standard
                                         automata term
  unify DEFINE qualified column-ref     rejected -- keep the dedicated wording
   error messages                        (the range-variable distinction is
                                         needed for the qualifier work)
  validateRPRPatternVarCount ->         deferred -- name to be settled with
   preprocessRPRPattern                  the qualifier patch
  (A B+)+ "variable-length element"     rejected -- the original is accurate;
   -> "quantifier is different"          cf. (A{2} B{3})+, which is absorbable
   (off-list)

Quality work (Linux), each sent as its own follow-up on this thread:

  - Valgrind (leak / use-after-free): no errors across parse, NFA build,
    pattern scan, EXPLAIN and node serialization; exercises the DEFINE
    ExprContext fix, whose reproducer is cassert-only.
  - gcov coverage: modified-line 98.4% (functions 100%); the remaining
    uncovered lines are idiomatic defensive guards (enum-default branches,
    pg_unreachable(), the public windowapi.h relpos guards) kept on purpose.

Both figures were measured at v50-0019; v50-0020 is comment-only, so they
carry over unchanged.  Each report goes out as a separate message so the
details and attachments stay out of this patch mail.

Longer term, and out of scope for this CF entry:

  - Smaller documentation and error-message follow-ups (glossary, the
    bounded-quantifier message, README wording).
  - Short-circuit / tri-state DEFINE evaluation, as a separate series.
  - SEEK clause support (SQL:2016).
  - Empty pattern PATTERN () -- correctly rejected today; deferred because
    its empty-match semantics (SHOW/OMIT EMPTY MATCHES) are tied to the
    still-out-of-scope MEASURES clause.
  - Relaxing the DEFINE-subquery over-rejection where the standard permits it.
  - Prefix-pattern absorption (an optimization; split out as its own series).
  - R010 (MATCH_RECOGNIZE in the FROM clause) and the shared RPRContext it
    would back.

Please let me know if any of the slicing or grouping looks off.

Thanks again to Jian and Tatsuo for the careful review.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi hackers,

Following up on the coverage analysis I posted earlier: I've since pushed the
work it proposed, so please find attached (coverage.tgz) an updated report that
reflects the committed changes. In short, the branch now lands at the target we
discussed.

* What changed since the first report
- New commits add the row pattern recognition coverage tests for the reachable
  lines, and tidy up the unreachable defensive/dead code (Assert conversions,
  removing the dead _equalRPRPattern body, and similar).
- This is essentially the (b) path from the earlier mail: add the reachable-line
  tests plus the safe cleanups, while keeping the idiomatic guards as-is.

* Measurement setup
- Target: PostgreSQL RPR branch, modified-lines basis (RPR-base..RPR diff)
- Build: gcc --enable-coverage with --with-llvm (LLVM JIT module included; both C and C++ instrumented)
- Tests: make check-world (regression + TAP + contrib; no forced JIT settings)

* Results (vs. the first report)
- Modified-line coverage: 96.5% (2,608 / 2,702)  ->  98.4% (2,635 / 2,679)
- Functions:              99.4% (172 / 173)      ->  100%  (170 / 170)
- Remaining 44 uncovered lines are the idiomatic defensive guards we agreed to
  keep on purpose:
  - enum-default branches
  - pg_unreachable()
  - public windowapi.h relpos guards
  I left these untouched rather than reworking them to chase ~100%, which
  matches my earlier inclination and our reading of where the line should sit.

* On the earlier caveat
The first report flagged that the reachable/unreachable classification was
AI-assisted and might be wrong. That is now resolved in practice: each line I
claimed was coverable was verified against a coverage build as I wrote its test,
rather than resting on the classification.

* What the report contains
Each uncovered line carries a collapsible box stating:
- Reachable / Unreachable classification + confidence
- Reachable: the concrete SQL test that covers it
- Unreachable: the reason it cannot execute, and the recommended source change
Consecutive lines on the same straight-line flow (no branch in between) are merged into one box.

* How to view
  tar xzf coverage.tgz
  # open coverage/index.html in a browser
  #  -> pick a file -> expand the collapsible box under each red (uncovered) line

* Contents
- coverage/index.html  : per-file coverage overview
- coverage/html/       : per-file detail (source + uncovered-line analysis)
- coverage/untested.md : checklist of uncovered lines

Please review. Feel free to reply with any questions.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

As a final memory-safety check before wrapping up the RPR patch, I ran the
branch under Valgrind. The short version: no memory errors were found.

Setup, on Linux/AMD64 (Valgrind is not usable on macOS):

  configure: --enable-debug --enable-cassert -DUSE_VALGRIND
  also defined: -DCOPY_PARSE_PLAN_TREES -DWRITE_READ_PARSE_PLAN_TREES
                -DRAW_EXPRESSION_COVERAGE_TEST
  valgrind: --suppressions=src/tools/valgrind.supp --trace-children=yes
            --track-origins=yes --leak-check=no --error-exitcode=128

The round-trip defines keep the parse/plan-tree copy and write/read paths on by
default, so _outRPRPattern, _readRPRPattern and _copyRPRPattern are exercised on
every plan tree, not just at parse time.

I ran installcheck against this instance in three phases.

Phase A, round-trips on: rpr, rpr_nfa, rpr_explain and rpr_integration. These
are normal-size patterns, so the node copy/write-read paths are verified along
the way. All passed.

Phase B, round-trips off: rpr_base, which includes the large 32767-element
pattern. Serializing a tree that big under Valgrind is impractically slow, and
the serialization path is already covered by the normal-size patterns in
Phase A, so I disabled debug_copy_parse_plan_trees and
debug_write_read_parse_plan_trees here to exercise the NFA build and
scanRPRPattern's large arrays without the serialization bottleneck. Passed.

Phase C: window, preceded by test_setup, create_index and sanity_check so the
table, indexes and stats are in place. This one reported a regression diff: a
few EXPLAIN plans came out with Seq Scan / Hash Join where the expected output
has Index Only Scan / Nested Loop or Merge Join. That is a planner artifact of
running window outside the full parallel schedule (a different stats/cost
environment), not anything RPR changed; the same queries match expectations
under a normal check-world run. I included window mainly to exercise the
WindowAgg/RPR interaction under instrumentation, and for that the diff does not
matter, because the memory verdict comes from the Valgrind logs rather than the
regression output.

Results: no VALGRINDERROR markers in any per-pid log, and every log is empty
(with --quiet, a clean run leaves 0-byte logs), window included. The postmaster
exited 0, so --error-exitcode=128 never fired, and the tests ran tens of times
slower than usual, which confirms the code really did run under instrumentation.
So across parse, NFA build, pattern scan, EXPLAIN and node serialization, no
invalid read/write, uninitialised-value use, out-of-bounds access or invalid
free was observed.

The usual caveat applies: this is dynamic analysis, so it only attests to the
paths the tests actually exercised. As I add the coverage tests discussed in
the other thread, I will re-run the same setup over the expanded suite.

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

The attached patch refactors absorbability helper functions, white at
it, also other misc changes.
It's still based on https://github.com/assam258-5892/postgres/commits/RPR

The below is commit message:
----------------------------------------------------------------------------
Rename isUnboundedStart() to start_with_unbounded_quantifier() and
isFixedLengthChildren() to isFixedQuantifier() for clarity.

Rework start_with_unbounded_quantifier() to accept an RPRPatternElement *
directly instead of an index, and restructure its body as an explicit
if/else chain over element kinds (VAR, BEGIN, ALT/FIN, END) rather than
two loosely-coupled early-return checks.

Fix subgroup traversal in isFixedQuantifier() to use elem->jump - 1 to
locate the matching END element directly, replacing the previous loop
that walked next pointers.

Move isAbsorbable initialization from finalizeRPRPattern() into
makeRPRPattern(), and guard the computeAbsorbabilityRecursive() call in
computeAbsorbability() so it is only entered when the first element is
an ALT or has an unbounded quantifier.

Use palloc_array/palloc0_array in makeRPRPattern(). Remove the redundant
"T_RPRPattern" comment on the NodeTag field. Update README.rpr and
in-code comments to reflect the new function names.
----------------------------------------------------------------------------



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Wed, Jun 24, 2026 at 10:33 AM jian he  wrote:
>
> Hi.
>
> It's still based on https://github.com/assam258-5892/postgres/commits/RPR
>

    /*
     * Once the name matches we never fall back to function resolution, so any
     * decoration that does not make sense for a navigation operation is a
     * hard error.  The aggregate/window decorations (agg_star, DISTINCT,
     * WITHIN GROUP, ORDER BY, FILTER, OVER, RESPECT/IGNORE NULLS) are already
     * rejected by the common path in ParseFuncOrColumn, which treated the
     * recognized name as an ordinary function; what remains are the
     * decorations that path accepts for a plain function but a navigation
     * operation must still reject.
     */

The above comments can be deleted, ParseRPRNavCall, ParseFuncOrColumn
already have lots of comments.
Also the error check and its message are quite intuitive in ParseRPRNavCall.

coerce_to_common_type have comments:
```
 * This is used following select_common_type() to coerce the individual
 * expressions to the desired type
 ```

coerce_to_target_type comments says
```
* This is the general-purpose entry point for arbitrary type coercion
* operations.
```
So, I tended to use coerce_to_target_type.

ParseRPRNavCall ending can be simplified because coerce_to_target_type
can handle the same data type.
Therefore, `if (offtype != INT8OID)` is not necessary.

Drop the extra parentheses around ereport() argument lists, fewer
parentheses are always better for new code.



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi jian,

Thanks for the refactor.  I went through it change by change -- the
per-file notes are at the bottom.

A note up front, so the notes don't read as dismissive: at this stage I'd
rather prioritize validated code over better code.  The branch has a lot of
coverage and Valgrind behind it, and every change -- even a clean,
equivalent one -- moves a line out from under that.  So where I say "drop",
it means "not now", not "not good"; most of these would be welcome as a
follow-up.  One piece, though, does need a fix before any of it lands.

That piece is the new guard in computeAbsorbability(): it carries a
behavior change that no test covers.

> Move isAbsorbable initialization from finalizeRPRPattern() into
> makeRPRPattern(), and guard the computeAbsorbabilityRecursive() call in
> computeAbsorbability() so it is only entered when the first element is
> an ALT or has an unbounded quantifier.

First, what "absorbable" means here: the first unbounded repetition of a
fixed-length body reachable from the start of the pattern.  This rule is
worth writing down -- in README.rpr and in the comment on
computeAbsorbability() (or wherever fits best) -- so it is stated once,
explicitly (patch attached: nocfbot-absorb-definition-doc).

By that definition the leading A+ in (A+ B){2,3} is absorbable, but the
patch drops it.

The offending check is in computeAbsorbability():

    if (RPRElemIsAlt(&pattern->elements[0]) ||
        pattern->elements[0].max == RPR_QUANTITY_INF)
        computeAbsorbabilityRecursive(pattern, 0, &hasAbsorbable);

It looks only at elements[0], so a bounded outer group's BEGIN (finite max)
fails the check and the recursion that would descend to A+ never runs.

I'm attaching a small test for this (nocfbot-absorb-bounded-outer-test): it
passes on the branch and fails with v50-0001 applied, pinning both the a+"
marker and the absorbed-context count.

For the rest, change by change -- "ok" = take as-is, "drop" = leave out:

src/backend/optimizer/plan/rpr.c

The branch is already validated under coverage and Valgrind, so I'd rather
not re-open verified logic for equivalent refactors -- glad to take those
as a follow-up.  In file order:

  ok    palloc_array / palloc0_array in makeRPRPattern()
      result->varNames = palloc_array(char *, numVars);
      result->elements = palloc0_array(RPRPatternElement, numElements);

  ok    move the isAbsorbable = false init into makeRPRPattern()

  drop  rename beginElem -> elem in fillRPRPatternGroup()
        only beginElem was renamed; with endElem kept, the begin/end pair is
        no longer symmetric (elem / endElem)

  drop  rename isFixedLengthChildren -> isFixedQuantifier -- keep the old name
        "fixed-length" is the term everywhere else (README.rpr, the nearby
        comments, even this function's own body), and it drops the "children"
        that flags a whole-subtree check

  drop  the jump-1 traversal rewrite in that function -- equivalent refactor,
        defer to a follow-up

  drop  rename to start_with_unbounded_quantifier -- keep isUnboundedStart
    Lone snake_case among camelCase neighbors -- including isFixedQuantifier,
    renamed in this same patch -- and it reads as a predicate though it sets flags.

  drop  start_with_*'s new signature + if/else restructure -- equivalent
        refactor; keep the original isUnboundedStart body

  drop  rename branchFirst -> branchElement -- cosmetic churn, no behavior change

  drop  the new computeAbsorbability() guard -- the regression above
      if (RPRElemIsAlt(&pattern->elements[0]) ||
          pattern->elements[0].max == RPR_QUANTITY_INF)

src/include/nodes/plannodes.h

  ok    drop the redundant /* T_RPRPattern */ on the type field
      NodeTag type;

  drop  reworded "see isUnboundedStart" block comment -- keep the original
        (it still matches now that isUnboundedStart stays)

  ok    drop the inline isAbsorbable comment -- the block comment above covers it
      bool isAbsorbable;

src/backend/executor/README.rpr

  ok    spell out the skip mode -- a clear doc fix on its own
      (1) SKIP PAST LAST ROW (not SKIP TO NEXT ROW)

  drop  isUnboundedStart -> start_with_unbounded_quantifier -- follows the rename

Tatsuo, what's your read on all this -- in particular, hold the equivalent
refactors until after commit, or take them now?

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi jian,

Thanks -- this is a clean improvement, no objections. Honestly this part of the
parser is an area where you read it better than I do, so I'm glad to defer to
you here. Quick notes inline.

> The above comments can be deleted, ParseRPRNavCall, ParseFuncOrColumn
> already have lots of comments.
> Also the error check and its message are quite intuitive in ParseRPRNavCall.

Agreed.

> So, I tended to use coerce_to_target_type.

Agreed.

> ParseRPRNavCall ending can be simplified because coerce_to_target_type
> can handle the same data type.
> Therefore, `if (offtype != INT8OID)` is not necessary.

Agreed.

> Drop the extra parentheses around ereport() argument lists, fewer
> parentheses are always better for new code.

Agreed.

Tatsuo, this one looks good to take whenever you like.

Best,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi all,

A quick heads-up for this thread, cross-referenced from another one.

Haibo Yan has a patch series adding DISTINCT support to plain aggregate
window functions [1]. As it touches window-aggregate frame handling, I
applied it on top of the current RPR patch set and built the two together.
They combine cleanly today: no rebase conflict, and the regression tests
pass with no change to code or tests.

This is structural, not luck. RPR requires the frame to start at CURRENT
ROW, while that feature requires UNBOUNDED PRECEDING, so a single window can
satisfy at most one of them -- no overlap.

That said, the DISTINCT roadmap plans to relax its UNBOUNDED-PRECEDING
restriction (the sliding-frame patches), while RPR's CURRENT-ROW requirement
is fixed by the standard. So as those frame restrictions are lifted the two
could start to overlap, and at that point we'd likely need to review the
related frame-handling changes together. Nothing to act on now -- just
flagging it so we keep an eye on it.

Full review of the DISTINCT series is in the other thread [1].

[1] https://www.postgresql.org/message-id/CAAAe_zCfVbNrOUF5FaE38EcwYbtXacThR9xdVe2UJJPeDSL2KA@mail.gmail.com

Best,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi all,

One small follow-up on top of v50.

Master recently reworded the error raised when RESPECT/IGNORE NULLS is used
on a non-window function, from

  "only window functions accept RESPECT/IGNORE NULLS"

to

  "RESPECT/IGNORE NULLS specified, but %s is not a window function".

rpr_base was written before that change, so one expected-output line now
mismatches and the test fails on current master. The attached patch updates
just that line. No code or behavior change.

I'm sending it as a separate attachment so the v50 series stays as posted;
it applies on top of v50-0020.

Best,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi all,
> 
> A quick heads-up for this thread, cross-referenced from another one.
> 
> Haibo Yan has a patch series adding DISTINCT support to plain aggregate
> window functions [1]. As it touches window-aggregate frame handling, I
> applied it on top of the current RPR patch set and built the two together.
> They combine cleanly today: no rebase conflict, and the regression tests
> pass with no change to code or tests.
> 
> This is structural, not luck. RPR requires the frame to start at CURRENT
> ROW, while that feature requires UNBOUNDED PRECEDING, so a single window can
> satisfy at most one of them -- no overlap.
> 
> That said, the DISTINCT roadmap plans to relax its UNBOUNDED-PRECEDING
> restriction (the sliding-frame patches), while RPR's CURRENT-ROW requirement
> is fixed by the standard. So as those frame restrictions are lifted the two
> could start to overlap, and at that point we'd likely need to review the
> related frame-handling changes together. Nothing to act on now -- just
> flagging it so we keep an eye on it.
> 
> Full review of the DISTINCT series is in the other thread [1].
> 
> [1]
> https://www.postgresql.org/message-id/CAAAe_zCfVbNrOUF5FaE38EcwYbtXacThR9xdVe2UJJPeDSL2KA@mail.gmail.com

Thanks for letting know us!
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi all,
> 
> One small follow-up on top of v50.
> 
> Master recently reworded the error raised when RESPECT/IGNORE NULLS is used
> on a non-window function, from
> 
>   "only window functions accept RESPECT/IGNORE NULLS"
> 
> to
> 
>   "RESPECT/IGNORE NULLS specified, but %s is not a window function".
> 
> rpr_base was written before that change, so one expected-output line now
> mismatches and the test fails on current master. The attached patch updates
> just that line. No code or behavior change.
> 
> I'm sending it as a separate attachment so the v50 series stays as posted;
> it applies on top of v50-0020.

Thanks for the patch. I will include it in the upcoming v50 patches.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Two things before the next review round.  Both aim at the same thing:
keeping the v50 diff to what RPR genuinely changes, so the next round
reviews RPR on its own merits rather than hunks that drifted in or touch
pre-existing window code.

First, the cfbot is currently red on v49 across all platforms.  The cause
is not RPR: master recently reworded the RESPECT/IGNORE NULLS error, which
left rpr_base's expected output stale, so the regression diff fails "make
check" everywhere.  That is exactly the one-line fix you already agreed to
fold in; I have posted it here as v50-0021 so the series builds green on
its own.  This one is required regardless.

Second, while going over the v49 diff against master I found several hunks
that are either unrelated to RPR or that touch pre-existing window code.  I
split them into small patches so each can be decided on its own.

Patch list
----------
Every patch in this reply.  revert-* removes the change from RPR;
optional-* re-applies the same change to master separately.

  v50-0021       cfbot build fix (required regardless)
  revert-0001    drop unrelated include and stray blank line  (required cleanup)
  revert-0004    restore doc paragraph line wrapping          (required cleanup)
  revert-0002    #2 drop the mark-position diagnostic         (your call)
  optional-0001  #2 land the diagnostic on master
  revert-0003    #3 restore the funcname guard                (your call)
  optional-0002  #3 land the guard removal on master
  revert-0005    #5 drop the EXCLUDE TIES tests               (your call)
  optional-0003  #5 land the tests on master

Required cleanups
-----------------
These only remove changes that crept in but have nothing to do with RPR.
I split them out so you can fold them into the feature patch; being
required cleanups, I recommend applying them:

  revert-0001    drop an unrelated "nodes/plannodes.h" include and a stray
                 blank line in eval_windowaggregates()
  revert-0004    restore the line wrapping of two pre-existing doc
                 paragraphs (advanced.sgml, ref/select.sgml)

Your call
---------
The next three touch pre-existing window code, so I would rather you decide
where each belongs.  I prepared the building blocks so you can pick any
option:

  #2  window_gettupleslot() mark-position elog -- add row positions
      v49 extended the can't-happen error with the pos/markpos values.
        (a) keep it in RPR                 -> apply neither patch
        (b) drop it                        -> apply revert-0002
        (c) land it on master separately   -> revert-0002 + optional-0001
      A tiny additive diagnostic; I lean to (c), but (a) is fine too.

  #3  funcname guard in WinCheckAndInitializeNullTreatment()
      v49 removed the "could not get function name" guard as unreachable.
        (a) keep the removal in RPR        -> apply neither patch
        (b) restore the guard, drop it     -> apply revert-0003
        (c) remove it on master separately -> revert-0003 + optional-0002
      The branch is genuinely unreachable, but it drops a deliberate guard
      in pre-existing code, so of the three this one most warrants caution.
      Preserving the guard via (b) or (c) looks safest, but I will leave the
      decision to you.

  #5  EXCLUDE TIES window-frame test coverage
      Two nth_value/last_value cases.  The accounting they exercise already
      exists on master and the tests pass without RPR, so they are not RPR
      coverage.
        (a) keep them in RPR               -> apply neither patch
        (b) land them on master separately -> revert-0005 + optional-0003
      I lean to (b).

For my part, I will carry out the deeper review against v50 with v50-0021
and revert-0001/0004 applied, plus whichever of the above you choose, as
the minimal green baseline.

Best,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
To: Tatsuo Ishii <ishii@postgresql.org>, jian.universality@gmail.com
Cc: pgsql-hackers@postgresql.org, zsolt.parragi@percona.com,
    sjjang112233@gmail.com, vik@postgresfriends.org, er@xs4all.nl,
    jacob.champion@enterprisedb.com, david.g.johnston@gmail.com,
    peter@eisentraut.org, li.evan.chao@gmail.com
Subject: Re: Row pattern recognition
In-Reply-To: <CAAAe_zCd+gzpYSsC04NsKyCJeneChVZCaBP540d0p2=c3abvvw@mail.gmail.com>

Hi Tatsuo,

> v50-0021-adjust-rpr_base-expected-output.patch
> revert-0001-remove-incidental-changes.patch
> revert-0002-revert-mark-position-elog.patch
> revert-0003-restore-funcname-guard.patch
> revert-0004-restore-doc-line-wrapping.patch
> revert-0005-remove-exclude-ties-tests.patch
> optional-0001-include-row-positions-in-mark-position-error.patch
> optional-0002-remove-unreachable-funcname-guard.patch
> optional-0003-add-exclude-ties-test-coverage.patch

Apologies for the noise -- the nine attachments above are not a new full
patch series.  They are the small auxiliary patches described in that mail
(the v50-0021 build fix plus the revert-*/optional-* hunks), meant to be
applied selectively on top of the current v50 series, not to replace it.

Because I attached them as .patch files, cfbot will treat them as the latest
patch set and try to apply them to master.  They are not the series and will
fail there, so the CF entry will go red through no fault of the actual patch
-- please disregard that run.

Re-posting the full series is what restores cfbot, but a plain re-post of
v49 stays red on its own: it needs v50-0021 (the rpr_base expected-output
fix) folded in to build green.  Could you re-post the series with v50-0021
applied, so cfbot tracks the right patch set and goes green again?

Sorry again for the confusion.

Best,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Hi hackers,
> 
> This is v50, folding in the outstanding review.  From my side there are no
> known issues left, so I think it makes a good starting point for the kind of
> thorough public review the feature should get before commit.

Thanks for the incremental patches. I am going to publish v50 patch series.
Here are some commnets to the v50-* patches.

> First, two cleanups splitting changes unrelated to RPR out of the feature
> patch:
>
> v50-0001  Remove blank-line changes unrelated to row pattern recognition
> v50-0002  Remove unnecessary includes from the row pattern recognition
> patch

0001 and 0002 look good to me.

> The fixes (v50-0003..0005, all behavior-changing):
> 
>   v50-0003  Recognize row pattern navigation operations by name in DEFINE

diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index 1f6c8fa4fb2..f3b37aa992c 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c

@@ -2111,6 +2080,151 @@ FuncNameAsType(List *funcname)

+	if (fn->func_variadic)
+		ereport(ERROR,
+				(errcode(ERRCODE_SYNTAX_ERROR),
+				 errmsg("cannot use VARIADIC with row pattern navigation function %s",
+						navname),
+				 parser_errposition(pstate, location)));
+	if (argnames != NIL)
+		ereport(ERROR,
+				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+				 errmsg("row pattern navigation operations cannot use named arguments"),
+				 parser_errposition(pstate, location)));

Shouldn't the error code for the named arguments case be
ERRCODE_SYNTAX_ERROR? As far as I know the SQL standard does not allow
to use named arguments with row pattern navigation operations. So it's
not a required feature.

Also errmsg is different from surroundings. Probably "cannot use named
arguments with row pattern navigation function %s" is better?

diff --git a/src/backend/parser/parse_rpr.c b/src/backend/parser/parse_rpr.c
index 3eaea2be750..8ed01bb8f28 100644
--- a/src/backend/parser/parse_rpr.c
+++ b/src/backend/parser/parse_rpr.c
@@ -472,6 +472,7 @@ transformDefineClause(ParseState *pstate, WindowClause *wc, WindowDef *windef,
  *     * PREV/NEXT wrapping FIRST/LAST flattens to a compound kind
  *     * Other nestings are rejected (FIRST(PREV()), PREV(PREV()), ...)
  *     * offset_arg / compound_offset_arg must not contain column refs
+ *       or nested navigation operations

Needs '*' in front of "or nested....".

>   v50-0004  Use a dedicated ExprContext for RPR DEFINE clause evaluation

Looks good to me.

Will continue reviewes tomorrow.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

Thank you very much for taking the time to start the review.  I will reply
in step, one patch at a time, from 0001 up to wherever your review has
reached -- so far that is 0001..0004 -- and I will keep following along as
you continue.

For convenience I have attached just the four patches you have reviewed,
keeping their original v50 names but renamed to nocfbot-* so that cfbot does
not pick them up:

  nocfbot-0001  Remove blank-line changes unrelated to row pattern recognition
  nocfbot-0002  Remove unnecessary includes from the row pattern recognition patch
  nocfbot-0003  Recognize row pattern navigation operations by name in DEFINE
  nocfbot-0004  Use a dedicated ExprContext for RPR DEFINE clause evaluation

0001, 0002 and 0004 are unchanged from what you reviewed; I include them
only so this reply stands on its own for the reviewed range.  0003 folds in
the three points you raised below.

> 0001 and 0002 look good to me.

Thank you for confirming -- I have left them as they are.

>>   v50-0003  Recognize row pattern navigation operations by name in DEFINE
>
> + if (argnames != NIL)
> + ereport(ERROR,
> + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> + errmsg("row pattern navigation operations cannot use named arguments"),
> + parser_errposition(pstate, location)));
>
> Shouldn't the error code for the named arguments case be
> ERRCODE_SYNTAX_ERROR? As far as I know the SQL standard does not allow
> to use named arguments with row pattern navigation operations. So it's
> not a required feature.

You are right, thank you.  The standard does not provide for named arguments
here at all, so this is a syntax violation rather than an unimplemented
feature.  I have changed the errcode to ERRCODE_SYNTAX_ERROR, which also
makes it consistent with the VARIADIC and argument-count checks alongside
it.

> Also errmsg is different from surroundings. Probably "cannot use named
> arguments with row pattern navigation function %s" is better?

Thank you for the suggested wording; I have adopted it as is:

    errmsg("cannot use named arguments with row pattern navigation function %s",
           navname)

It now reads in the same "cannot use X with row pattern navigation
function %s" shape as the VARIADIC message just above it.  I have also
updated the expected output in rpr.sql to match (ERROR:  cannot use named
arguments with row pattern navigation function PREV).

> + *     * offset_arg / compound_offset_arg must not contain column refs
> + *       or nested navigation operations
>
> Needs '*' in front of "or nested....".

Thank you for catching this.  The last line is a continuation, but the '*'
bullets ran together with the comment's own '*' and hid that.  I switched
the bullets to '-' to match the sibling rule list in this file, so the
continuation now reads clearly:

     * ... enforces, for each outer RPRNavExpr (per ISO/IEC 19075-5 5.6.4
     * nesting rules):
     *   - arg must contain at least one column reference
     *   - PREV/NEXT wrapping FIRST/LAST flattens to a compound kind
     *   - Other nestings are rejected (FIRST(PREV()), PREV(PREV()), ...)
     *   - offset_arg / compound_offset_arg must not contain column refs
     *     or nested navigation operations

I hope this addresses what you had in mind; please let me know if you would
prefer a different form.

>>   v50-0004  Use a dedicated ExprContext for RPR DEFINE clause evaluation
>
> Looks good to me.

Thank you for confirming -- left as is.

> Will continue reviewes tomorrow.

Thank you, I look forward to it.  I will respond to each further patch as
your review reaches it, in the same one-at-a-time fashion.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Will continue reviewes tomorrow.

Sorry for delay. Here is the review for
v50-0005-match-once-per-row.patch.

--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -239,6 +239,10 @@ static int64 row_is_in_reduced_frame(WindowObject winobj, int64 pos);
 
 static void clear_reduced_frame(WindowAggState *winstate);
 static int	get_reduced_frame_status(WindowAggState *winstate, int64 pos);
+static void advance_nav_mark(WindowAggState *winstate, int64 currentPos);
+static void advance_reduced_frame_nfa(WindowObject winobj,
+									  RPRNFAContext *targetCtx, int64 pos,
+									  bool hasLimitedFrame, int64 frameOffset);
 static void update_reduced_frame(WindowObject winobj, int64 pos);
 
 /* Forward declarations - NFA row evaluation */
@@ -2521,6 +2525,16 @@ ExecWindowAgg(PlanState *pstate)
 			{
 				if (winstate->rpSkipTo == ST_NEXT_ROW)
 					clear_reduced_frame(winstate);
+
+				/*
+				 * Drive the row pattern match every row, so it tracks the row
+				 * scan rather than frame access: a window function that skips
+				 * the frame (e.g. nth_value() with a NULL offset) must not
+				 * leave the match state behind currentpos.
+				 */
+				Assert(winstate->nav_winobj != NULL);
+				(void) row_is_in_reduced_frame(winstate->nav_winobj,
+											   winstate->currentpos);

Is there any reason that we call row_is_in_reduced_frame() here,
instead of something like:

   update_frameheadpos(winstate);
   update_reduced_frame(winobj, pos);

row_is_in_reduced_frame() returns row status. Ignoring it using (void)
looks a little bit confusing to me.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

Thanks for the review, and for basing it on the RPR branch. Responses
inline.

> ``(only possible during early development/testing).`` comment is not necessary?

Agreed, and it is actually misleading: varMatched == NULL is a live
signal, not a dev-only artifact. nfa_match() is called with NULL to force
every VAR to not-match at a frame boundary (execRPR.c, "Frame boundary
reached: force mismatch"). I will rewrite the comment to describe that
meaning instead of the "early development/testing" note.

> nfa_match desperately needs an extra i(nt64 currentPos) argument. [...]
> adding currentPos makes it much easier to understand the current
> execution state when debugging with GDB.

Makes sense -- nfa_match() has only the state list in scope, no row
index, which is exactly the thing that is hard to place in GDB. I will
thread currentPos through.

> The comments above in nfa_match are unnecessary because in ``if
> (RPRElemIsAbsorbableBranch(elem)`` we already have many comments, and
> the meaning seems the same.

Agreed -- the loop-top overview's second sentence restates the inline
END-chain block. I will drop it and keep "Evaluate VAR elements against
current row" as a one-line lead.

> Similar to REG_DEBUG, we really need an RPR_DEBUG option. [...] verify
> that ctx->states is not a circular linked list [...] without affecting
> release builds.

Fair point, and there is some history: RPR_DEBUG did exist earlier as
debug logging, and I am the one who proposed removing it. My reason was
narrow, though. I lean on the debugger, and with AI assistance the cost of
inserting, watching, and then removing ad-hoc logs has dropped sharply --
so I treated those logs as ephemeral and optimized for a clean committed
tree rather than for someone reading execRPR.c cold.

For a new contributor that trade-off is the wrong one, and you have
convinced me: a retained set of observation points, plus the Assert-style
sanity checks you describe (non-circular state list, count and
context-ordering invariants), would genuinely lower the barrier to this
code. So I agree with the direction. Rather than settle on a shape now, I
would leave it open: which observation points and checks are actually
worth retaining behind #ifdef RPR_DEBUG can be picked out later as a
separate follow-up, and it is really Tatsuo's call since he suggested the
first version.

> <para> The SQL standard defines more subclauses: MEASURES and SUBSET
> [...] more variations in AFTER MATCH clause. </para>
> This part should stay in the Compatibility section.

Agreed. It is a standard-deviation note, and the SELECT Compatibility
section currently has no row-pattern text, so I will move this paragraph
there.

Unless Tatsuo has a different view by the weekend, I will proceed with the
concrete changes above, leaving the RPR_DEBUG shape open as noted.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thanks for the review. I agree with the direction -- the (void) is
confusing. I did try your exact suggestion and the regression tests pass
unchanged, but I would keep one guard, for the following reason.

> Is there any reason that we call row_is_in_reduced_frame() here,
> instead of something like:
>
>    update_frameheadpos(winstate);
>    update_reduced_frame(winobj, pos);

row_is_in_reduced_frame() guards the update:

    state = get_reduced_frame_status(winstate, pos);
    if (state == RF_NOT_DETERMINED)
    {
        update_frameheadpos(winstate);
        update_reduced_frame(winobj, pos);
    }

Calling update_reduced_frame() unconditionally drops that guard. When
currentpos is already determined -- e.g. an interior row of a previous
match under AFTER MATCH SKIP PAST LAST ROW (RF_SKIPPED) -- it takes an
O(1) early return and overwrites the shared rpr_match_* record, silently
reclassifying a SKIPPED row as UNMATCHED.

This is not observable today -- I confirmed with a guarded-vs-unguarded
differential (patterns, both skip modes, various aggregates: identical
output), because both paths end up with an empty reduced frame. But it
does change the state semantics and leans on that convergence, so I would
rather keep the guard. Two ways, both of which remove the (void):

  A) Keep the guard inline at the call site.

  B) Factor it into a small helper shared by the nav-driving call site
     and row_is_in_reduced_frame():

        static void
        ensure_reduced_frame(WindowObject winobj, int64 pos)
        {
            WindowAggState *winstate = winobj->winstate;

            if (get_reduced_frame_status(winstate, pos) == RF_NOT_DETERMINED)
            {
                update_frameheadpos(winstate);
                update_reduced_frame(winobj, pos);
            }
        }

I lean towards B (no duplicated guard, and the name states the intent),
but A is the smaller diff. Which do you prefer?

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi,

I have 3 patches to present:

v50-0001-refactor-DEFINE-volatile-expression-check.nocfbot
v50-0002-refactor-define_walker.nocfbot
v50-0003-replace-EMPTY_LOOP-to-RPR_ELEM_EMPTY_LOOP.nocfbot

As mentioned before, it's based on
https://github.com/assam258-5892/postgres/commits/RPR.
v50-0001, v50-0002 alrady submitted once patch at [1], now it's more complete.

Except that i want to rename RPSkipTo to RPRSkipTo and rpSkipTo to rprSkipTo,
What do you think?

[1] https://postgr.es/m/CACJufxG57=ddtbN=5RZCzhxWDYXvocKmB7NtZy+DoqZuhxb_DA@mail.gmail.com



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

``The actual mark is set to: min(lookback_mark, lookahead_mark).``
in README.rpr need update?

The attached patch is still based on
https://github.com/assam258-5892/postgres/commits/RPR.

v50-0001-Refactor-visit_nav_plan.partial
v50-0002-Refactor-visit_nav_exec.partial
v50-0003-no-need-compile-and-evaluate-offset-in-expression-evaluation.partial
v50-0004-misc.partial
v50-0001-Evaluate-navigation-offset-once-at-one-place.nocfbot

The ".partial" patch, when combined, contains the same content as the
single patch (v50-0001-Evaluate-navigation-offset-once-at-one-place.nocfbot).
(I first created separated patches, but then I felt the whole change
focuses on one main topic, so merging them made sense to me).

The commit message for the main patch
(v50-0001-Evaluate-navigation-offset-once-at-one-place.nocfbot) is
below:
------------------------------------------------
Subject: [PATCH v51 1/1] Evaluate navigation offset once at one place

Row pattern navigation (PREV/NEXT/FIRST/LAST and their compounds) resolved
offsets (transform a expression to a int64 number) in ExecInitExprRec,
ExecEvalRPRNavSet, extract_const_offset, eval_define_offsets. Serval places
transform the same offset expression to a int64 number, that is too much!

With the attached, a single place (ExecInitWindowAgg->eval_define_offsets) to
handling this.

visit_nav_exec() now evaluates every offset expression at executor init and save
the result on the RPRNavExpr (offset / compound_offset); ExecEvalRPRNavSet()
simply reads those int64 values.  This removes:

  - the RPRNavOffsetKind enum and the offset/kind fields on the
    WindowAgg plan node.  The planner walk (visit_nav_plan /
    compute_define_metadata) now only classifies match_start
    dependency, which is all buildRPRPattern() needs to decide context
    absorption.

  - the per-invocation offset machinery in the executor: the Datum*
    offset arrays in the eval step, rpr_nav_get_compound_offset(), and
    the scattered NULL/negative checks, now centralized in
    eval_nav_offset.

The "retain all" case (backward reach overflows int64) is encoded as the
sentinel navMaxOffset < 0 rather than an enum value; advance_nav_mark() disables
tuplestore trim on it.  EXPLAIN reads the resolved offsets from the planstate
(ExecInitWindowAgg is reached for EXPLAIN without ANALYZE), so it now prints
concrete offsets instead of "runtime".

```
 We must still set nav_saved_outertuple (done above) so that
EEOP_RPR_NAV_RESTORE is a harmless no-op.
```
The above in ExecEvalRPRNavSet is wrong, EEOP_RPR_NAV_RESTORE will never be a
no-op. However we can make EEOP_RPR_NAV_RESTORE no-op, so the above comments
make sense.

Rename eval_nav_offset_helper to eval_nav_offset

Based on https://github.com/assam258-5892/postgres/commits/RPR
------------------------------------------------



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson, Jian,

In v50-0006-tidy-plumbing.patch, the planner cost model seems slightly
changed.  Before the cost was charged according to the number of
pattern variables in PATTERN clause.  But now it is charged according
to the number of pattern variables in DEFINE clause.  Maybe I missed
the discussion on the changing. Can you please explain the reason of
the change?

--- a/src/backend/optimizer/path/costsize.c
+++ b/src/backend/optimizer/path/costsize.c
@@ -3231,30 +3231,18 @@ cost_windowagg(Path *path, PlannerInfo *root,
 	 * so we'll just do this for now.
 	 *
 	 * Moreover, if row pattern recognition is used, we charge the DEFINE
-	 * expressions once per tuple for each variable that appears in PATTERN.
+	 * expressions once per tuple for each DEFINE variable.
 	 */
 	if (winclause->rpPattern)
 	{
-		List	   *pattern_vars;
 		QualCost	defcosts;
 
-		pattern_vars = collectPatternVariables(winclause->rpPattern);
-
-		foreach_node(String, pv, pattern_vars)
+		foreach_node(TargetEntry, def, winclause->defineClause)
 		{
-			char	   *ptname = strVal(pv);
-
-			foreach_node(TargetEntry, def, winclause->defineClause)
-			{
-				if (!strcmp(ptname, def->resname))
-				{
-					cost_qual_eval_node(&defcosts, (Node *) def->expr, root);
-					startup_cost += defcosts.startup;
-					total_cost += defcosts.per_tuple * input_tuples;
-				}
-			}
+			cost_qual_eval_node(&defcosts, (Node *) def->expr, root);
+			startup_cost += defcosts.startup;
+			total_cost += defcosts.per_tuple * input_tuples;
 		}

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> In v50-0006-tidy-plumbing.patch, the planner cost model seems slightly
> changed. Before the cost was charged according to the number of
> pattern variables in PATTERN clause. But now it is charged according
> to the number of pattern variables in DEFINE clause. Maybe I missed
> the discussion on the changing. Can you please explain the reason of
> the change?

The change is a simplification that came out of Jian's v48 review, and it
does not change the cost the model produces.

It follows Jian's suggestion from 2026-06-15 [1]:

> collectPatternVariables is not needed.
> The parser already ensures every DEFINE variable appears in PATTERN,
> so there is nothing to filter.
> Also, we don't really do anything special (like make a dummy Const)
> regarding PATTERN variables that not appearing in the DEFINE clause.

The two loops charge exactly the same set, for the following reason:

- The old loop walked the unique PATTERN variables (collectPatternVariables
  deduplicates, returning each name once) and, for each, looked up the
  matching DEFINE entry by resname and charged that DEFINE's cost.
- Every DEFINE variable is guaranteed to appear in PATTERN -- the parser
  rejects a DEFINE variable that is not used in PATTERN (errmsg "DEFINE
  variable \"%s\" is not used in PATTERN" in parse_rpr.c).  So the DEFINE
  clause is always a subset of the unique PATTERN variables, and each
  DEFINE resname is unique.
- A PATTERN variable that has no DEFINE contributes nothing to the old
  loop, because the inner resname lookup finds no match.

So the old loop already charged each DEFINE expression exactly once, and
nothing else.  Iterating defineClause directly, as v50-0006 does, visits
precisely that same set once each.  The estimate is unchanged; only the
redundant outer walk over PATTERN and the per-variable resname lookup into
the DEFINE clause are removed.

This also matches the premise of the cost model we settled on back in
February: the NFA executor evaluates every DEFINE expression once per row,
so the natural unit for the per-tuple charge is the DEFINE variable.

[1] https://www.postgresql.org/message-id/CACJufxFAQhbOD9EVCTAy-VwDbG4446N10GsxCcgdpFnjHO1Efw%40mail.gmail.com

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
On Sat, Jul 4, 2026 at 6:22 AM Henson Choi  wrote:
>
> Hi Tatsuo,
>
> > In v50-0006-tidy-plumbing.patch, the planner cost model seems slightly
> > changed. Before the cost was charged according to the number of
> > pattern variables in PATTERN clause. But now it is charged according
> > to the number of pattern variables in DEFINE clause. Maybe I missed
> > the discussion on the changing. Can you please explain the reason of
> > the change?
>
> The change is a simplification that came out of Jian's v48 review, and it
> does not change the cost the model produces.
>
> It follows Jian's suggestion from 2026-06-15 [1]:
>
> ....
>
> This also matches the premise of the cost model we settled on back in
> February: the NFA executor evaluates every DEFINE expression once per row,
> so the natural unit for the per-tuple charge is the DEFINE variable.
>
> [1] https://www.postgresql.org/message-id/CACJufxFAQhbOD9EVCTAy-VwDbG4446N10GsxCcgdpFnjHO1Efw%40mail.gmail.com
>
> Best regards,
> Henson

I am wondering if we can have one query to enable (COSTS ON) for testing.

For many rpr tests, the table size is small, EXPLAIN ANALYZE won't
take long, and probably all rows will be sampled.
Of course, once the patch is in committable shape, we need to switch it to OFF.


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> The change is a simplification that came out of Jian's v48 review, and it
> does not change the cost the model produces.
> 
> It follows Jian's suggestion from 2026-06-15 [1]:
> 
>> collectPatternVariables is not needed.
>> The parser already ensures every DEFINE variable appears in PATTERN,
>> so there is nothing to filter.
>> Also, we don't really do anything special (like make a dummy Const)
>> regarding PATTERN variables that not appearing in the DEFINE clause.
> 
> The two loops charge exactly the same set, for the following reason:
> 
> - The old loop walked the unique PATTERN variables (collectPatternVariables
>   deduplicates, returning each name once) and, for each, looked up the
>   matching DEFINE entry by resname and charged that DEFINE's cost.
> - Every DEFINE variable is guaranteed to appear in PATTERN -- the parser
>   rejects a DEFINE variable that is not used in PATTERN (errmsg "DEFINE
>   variable \"%s\" is not used in PATTERN" in parse_rpr.c).  So the DEFINE
>   clause is always a subset of the unique PATTERN variables, and each
>   DEFINE resname is unique.
> - A PATTERN variable that has no DEFINE contributes nothing to the old
>   loop, because the inner resname lookup finds no match.
> 
> So the old loop already charged each DEFINE expression exactly once, and
> nothing else.  Iterating defineClause directly, as v50-0006 does, visits
> precisely that same set once each.  The estimate is unchanged; only the
> redundant outer walk over PATTERN and the per-variable resname lookup into
> the DEFINE clause are removed.

Ok, thanks for the explanation.

> This also matches the premise of the cost model we settled on back in
> February: the NFA executor evaluates every DEFINE expression once per row,
> so the natural unit for the per-tuple charge is the DEFINE variable.

BTW, I was thinking about cases where same DEFINE variable appears
twice or more in PATTERN for a same row. For example PATTERN
(A|A). But in this case it would be optimized out to (A). So we don't
need to worry about A appearing twice. So our cost model is correct in
this case.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> BTW, I was thinking about cases where same DEFINE variable appears
> twice or more in PATTERN for a same row. For example PATTERN (A|A).
> But in this case it would be optimized out to (A). So we don't need
> to worry about A appearing twice. So our cost model is correct in
> this case.

Right, and I think the cost model holds even a bit more broadly than
the (A|A) case.  (A|A) does collapse to (A), but a variable can still
appear more than once in patterns that do not collapse, e.g. PATTERN
(A B | A C), or A A, or A+.

In those cases the model is still correct, for a slightly different
reason than the (A|A) rewrite: the executor evaluates each DEFINE
predicate once per row, not once per PATTERN occurrence.  For each
row it evaluates every DEFINE once and keeps the boolean results in
a varMatched array.

When the same A appears at several positions in the pattern -- for
example the A in each branch of (A B | A C), which are distinct
states -- each looks up varMatched[A], so the same entry is read
more than once; but that read reuses the already-computed value, not
a re-evaluation.  So repetition in PATTERN never multiplies DEFINE
evaluations, and charging once per DEFINE variable in the cost model
matches what the executor actually does.

The related question that does run the other way is that today we
evaluate every DEFINE for a row eagerly, not just the ones that row
actually needs.  For example, in PATTERN (A B C D) a single match
walks the sequence one variable per row -- each row only needs to
test the single variable its state expects -- yet we still evaluate
A, B, C, and D at every row.

That is the short-circuit / lazy DEFINE evaluation Jian raised on
2026-05-26 using that very (A B C D) example (evaluate a predicate
only the first time a state tests it).  If we ever adopt it, the
cost model's premise -- every DEFINE once per row -- would change
with it, so the two are tied together.

There's also a soundness angle that argues for keeping it separate.
DEFINE already forbids volatile functions and sequence operations
(nextval), so the obvious non-deterministic cases are out.  The
wrinkle lazy evaluation adds is that a predicate would then be
evaluated zero or one times per row -- skipped whenever no state
reaches it -- rather than always.  Whether that is safe for a
predicate carrying some state-affecting behavior the volatility ban
does not exclude is something I haven't worked through, so it wasn't a
call I'd want to make lightly under the current review.

As we discussed, that one is best left as a separate series after
the initial commit, and since it was Jian's idea I'd be glad to see
him drive it.  For now I'd keep it out of the in-flight review so the
commit stays small.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

This is a design note on the core data structures for CLASSIFIER and
row pattern variables, aimed at the next round of window-clause row
pattern recognition (RPR, R020) rather than the current patch. I'd
like to share it and open it up for discussion.

It opens with a reflection, because the reflection is the point. For
about six months I took it for granted that we must keep the full
per-row match history during matching. That premise was wrong. Once I
dropped it, the data-structure problem dissolved into a handful of
small, bounded pieces -- which is what the rest of the note works out:
what to store per case, how much, and how to encode it.

I believe the storage/representation side is settled. What I have
deliberately left open is the part that lives in the matching engine
-- the aggregate accumulator lifecycle (clone on branch, discard on
failure) and the winning-match replay. I'd welcome thoughts there,
particularly from Tatsuo and Jian, given their work on the current
patch.

Best regards,
Henson

----------------------------------------------------------------------

RPR CLASSIFIER / row pattern variable storage (window clause)

I. Reflection -- the "full match history" premise was wrong

Since January this year -- six months into starting RPR work in
earnest -- I kept reasoning under one premise:

    To implement CLASSIFIER and row pattern variables, we must keep
    the per-row sequence of variable labels (the match history) that
    the match consumes, throughout matching.

For that half year I set the data-structure problem on top of it --
"where and how do we hold that whole sequence cheaply?" -- and kept
piling up storage / sharing / compression / lookup structures.

Yet no usable lookup structure ever came out. Worse: matchStates
branch and most of them vanish on match failure, so the cost of
building a lookup structure for each of those countless
(soon-discarded) states was exceeding the lookup efficiency it bought
-- paying up front, for the many that die, on behalf of the few that
survive.

The premise was wrong. RPR does not need to keep the full match
history during matching. The one place a full per-row sequence is
genuinely materialized is the universal-scope MEASURE aggregate (case
8, ARRAY_AGG(CLASSIFIER())). So that entire storage / sharing /
compression / lookup apparatus was solving a problem that did not need
solving.

II. The corrected picture -- what to store, per case

Here is how the storage requirement splits, case by case:

1. DEFINE navigation -- the reference range is bounded by the
   navigation offset. The offset is a run-time constant, so the upper
   bound to keep during execution is fixed and can be computed
   directly, without any lookup. A nav with no row pattern variable
   just derives the position from the offset and reads it from the
   tuplestore. (How much to retain, per nav function, is detailed in
   section III.)

2. bare row pattern variable reference (A.col) -- equivalent to
   LAST(A.col, 0). The structure is a pos list for A -- since
   everything in it is A, membership is implicit and no varId is
   needed. As a bare reference this is the special case with length =
   1 (only the last pos); the full list is needed only for an A
   aggregate or a larger FIRST/LAST offset (section III).

3. SUBSET (union) variable -- for SUBSET U=(A,B), CLASSIFIER(U) and
   U.col are merely derived from the primary classification (which row
   is A/B); they are not new information. Because A and B are
   interleaved in the list and we must tell them apart, the structure
   is a list of (pos, varId) pairs.

4. bare CLASSIFIER() (current row) -- unless it is inside an aggregate
   (ARRAY_AGG etc.), only the current row is needed (no list). The
   classifier comes straight from the variable (its name) that the
   pattern element currently being consumed by the matchState
   designates.

5. aggregate in DEFINE -- it drives matching, so it is evaluated live
   during matching under RUNNING semantics (no post-processing
   possible). The aggregate inputs (which row is which variable, its
   column, its classifier) are all already obtained from 1-4, so no
   new structure is needed -- only one running accumulator folding
   them on top. That is as far as the match-history view goes (no full
   history needed). Separately, there are two costs: (a) computing
   live for the many matchStates that mostly fail, and (b) cloning the
   in-progress accumulator into children on a branch. But this is
   aggregate accumulator management cost, not match history.

6-8 (MEASURE aggregates): since the match is already complete, it is
better to avoid paying for a live accumulator per failing candidate
(the cost in 5) and instead process only the winning match by post
replay. What each case must store/replay is below.

6. aggregate in MEASURE -- variable/SUBSET scope -- e.g. sum(A.price),
   sum(U.price), ARRAY_AGG(CLASSIFIER(U)). Only membership is needed
   (values in the tuplestore), compressed as a bitmap / run length
   (alternating m A's and n non-A's; sequential, no lookup). But the
   granularity differs: sum(A.price) / sum(U.price) need only is-A /
   is-U, whereas ARRAY_AGG(CLASSIFIER(U)) must distinguish which
   sub-variable, so it needs per-sub-variable membership (A and B
   each). Those per-sub memberships are precisely the per-row member
   label, and when several aggregates use the same sub-variable, these
   memberships fuse into that single label. (For bare scalar
   CLASSIFIER(U), see 3 -- just the last varId in the U list.)

7. aggregate in MEASURE -- CLASSIFIER(variable) inside an aggregate
   (special case: optimized to the first-occurrence position) -- in
   ARRAY_AGG(CLASSIFIER(A)), CLASSIFIER(A) is a running LAST, so its
   value is null before the first A and the constant 'A' afterwards.
   So instead of the full membership of 6, it optimizes to a single
   first-occurrence position for A (the null->A boundary) -- a
   single-variable special case. (For SUBSET CLASSIFIER(U) the member
   varies, so this optimization does not apply; handle it in 6.) bare
   scalar CLASSIFIER(A) is derived from 2 -- just whether A's list is
   empty.

8. aggregate in MEASURE -- universal scope -- every match row is in
   scope. For a column (e.g. sum(price)) it is all rows, so not even
   membership is needed (values in the tuplestore). For
   ARRAY_AGG(CLASSIFIER()), each row's value is the row pattern
   variable name (the label), and the storage is a run-length encoding
   of varId (a run of the same variable as (varId, run)) -- since all
   rows are in order, no pos is needed; just pile up varId runs (order
   implies pos). (For bare scalar CLASSIFIER(), see 4 -- just the last
   row's varId.)

III. Retained length per nav function -- offset fixes the bound

If 1-2 above say what to hold, this pins down how much of it to hold
during matching, per nav function. The key: the offset is a run-time
constant (a literal, embedded variable, and the like -- not a column
or subquery), so the size of the retained window is fixed at plan
time. So you can pre-allocate a ring buffer of that size per variable,
and there is no lookup during matching.

Physical nav and logical nav split apart:

- physical nav (PREV/NEXT) -- the offset is a physical position in the
  partition, so it does not grow the variable's history at all. The
  anchor is just "that variable's running last row", and offset n
  merely indexes the tuplestore from there. Even when NEXT looks
  ahead, that row is already in the tuplestore (only its
  classification is pending). So: retain = 1 anchor, extra +0.

- logical nav (FIRST/LAST) -- the offset is a position within the rows
  mapped to that variable. Their retention costs are asymmetric.
  FIRST(X.col, n) is the (n+1)-th from the front, and the front never
  changes once passed, so you count X rows and latch only the single
  row where the count reaches n+1 -- a counter + 1 holder, O(1)
  regardless of n (later X rows are ignored). LAST(X.col, n) is the
  (n+1)-th from the back, but since it is running the end keeps
  moving, so you must hold X's last n+1 rows in a sliding window --
  retain = n+1. bare X.col = LAST(X.col, 0) = 1.

- nested PREV/NEXT(FIRST/LAST(X.col, k), m) -- retention follows the
  rule above for the inner (logical) part only: counter+holder for
  FIRST, k+1 sliding for LAST. The physical part m just reads the
  tuplestore from that row, so +0.

Boundary -- this bound applies to navigation references only. An
aggregate reference (sum(A.price) etc.) folds the entire prefix, so it
is absorbed into a running accumulator (5), not a window -- an O(1)
accumulated value, not a length. Do not mix the two into one
structure.

IV. Compressed storage -- one run-length spine

2-3 (during matching) and 6-8 (MEASURE replay) use the same
information under different access patterns, so their encodings
diverge:

- live / sparse (2-3) -- during matching you append only the rows
  mapped to X, as they come. It is a subsequence of all rows, so to
  know which row is which you must carry the pos too (2's pos list,
  3's pos+varId).

- replay / dense (6-8) -- you walk the winning match from the start
  over every match row, so no pos is needed -- order is the pos. This
  is where compression pays off.

The replay-side structures are all one run-length spine, specialized
only by granularity:

- universal classifier (8) -- per-row varId as (varId, run) runs. No
  pos; the cumulative run lengths give the position.

- per-variable membership (6) -- is-X as alternating runs: just a
  repetition of (present length, absent length) pairs (alternative: a
  1-bit-per-row bitmap). The case where is-A alone suffices, as in
  sum(A.price).

- per-sub-member (6) -- (varId, run) within the union, when you must
  tell A/B apart as in ARRAY_AGG(CLASSIFIER(U)). Rows outside U
  (non-A/non-B) must be carried as runs of a "none" sentinel varId so
  that order = pos is preserved.

- single-variable boundary (7) -- ARRAY_AGG(CLASSIFIER(A)) has only
  the null->A boundary, so the run degenerates to essentially a single
  item.

single varId RLE vs several per-variable memberships -- for the
per-sub-member case the two encodings trade off. (i) single varId RLE
(the bullet above): the per-row label comes out directly, but every
aggregate scans the whole span. (ii) several per-variable memberships:
is-A and is-B each as alternating runs (no sentinel needed) -- an
aggregate can pick just the sub-variable streams it uses, but a
CLASSIFIER(U) label must be read by merging several streams.

bitmap vs RLE -- a match is inherently runs (the greedy A^m B^n
shape). So RLE is natural, and since consumption is a sequential scan
no index is needed. A 1-bit-per-row bitmap (as long as the match) wins
only when the runs fragment finely or random access is needed.

Values are not stored -- the spine carries only
membership/label(varId); the actual column values live in the
tuplestore, and the replay scan fetches them by pos as it goes. This
is the principle behind 6-8 repeatedly noting that values stay in the
tuplestore.

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> In those cases the model is still correct, for a slightly different
> reason than the (A|A) rewrite: the executor evaluates each DEFINE
> predicate once per row, not once per PATTERN occurrence.  For each
> row it evaluates every DEFINE once and keeps the boolean results in
> a varMatched array.
> 
> When the same A appears at several positions in the pattern -- for
> example the A in each branch of (A B | A C), which are distinct
> states -- each looks up varMatched[A], so the same entry is read
> more than once; but that read reuses the already-computed value, not
> a re-evaluation.  So repetition in PATTERN never multiplies DEFINE
> evaluations, and charging once per DEFINE variable in the cost model
> matches what the executor actually does.
> 
> The related question that does run the other way is that today we
> evaluate every DEFINE for a row eagerly, not just the ones that row
> actually needs.  For example, in PATTERN (A B C D) a single match
> walks the sequence one variable per row -- each row only needs to
> test the single variable its state expects -- yet we still evaluate
> A, B, C, and D at every row.
> 
> That is the short-circuit / lazy DEFINE evaluation Jian raised on
> 2026-05-26 using that very (A B C D) example (evaluate a predicate
> only the first time a state tests it).  If we ever adopt it, the
> cost model's premise -- every DEFINE once per row -- would change
> with it, so the two are tied together.
> 
> There's also a soundness angle that argues for keeping it separate.
> DEFINE already forbids volatile functions and sequence operations
> (nextval), so the obvious non-deterministic cases are out.  The
> wrinkle lazy evaluation adds is that a predicate would then be
> evaluated zero or one times per row -- skipped whenever no state
> reaches it -- rather than always.  Whether that is safe for a
> predicate carrying some state-affecting behavior the volatility ban
> does not exclude is something I haven't worked through, so it wasn't a
> call I'd want to make lightly under the current review.
> 
> As we discussed, that one is best left as a separate series after
> the initial commit, and since it was Jian's idea I'd be glad to see
> him drive it.  For now I'd keep it out of the in-flight review so the
> commit stays small.

Agreed.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

Thanks for this -- consolidating the offset resolution into one place
is a direction I like, and a couple of things about it are genuinely
nice:

> EXPLAIN reads the resolved offsets from the planstate
> (ExecInitWindowAgg is reached for EXPLAIN without ANALYZE), so it now
> prints concrete offsets instead of "runtime".

That is a real improvement -- the offset becomes visible in the plan
even when it comes from a bind parameter, where today we can only show
"runtime".

It also lines up with a point Tatsuo made back in April: since the
planner already folds a constant offset expression down to a single
Const, doing the resolution in the executor means we no longer have to
care whether the offset was constant or not.  So the direction has his
backing as well.

That said, I don't think we should take it into the patch at this
stage.  The current version has one proven defect: a plain
FIRST(expr, n) with n > 0 loses its forward reach.  I added a test for
it -- "DEFINE A AS v > FIRST(v, 5)" in rpr_explain -- where the
baseline prints "Nav Mark Lookahead: 5" and the patch prints 0.  The
query result is still correct (the mark is under-advanced, so it only
keeps extra rows), but the EXPLAIN is wrong and the tuplestore trim is
lost, so it is a regression against the baseline.

The test will come with the next patch email I send, so you will have
it there to diff against.

More broadly, though, reshaping the offset handling this much right as
we are stabilizing for commit feels like the wrong time -- at this
point I would rather limit changes to minimal fixes for proven
defects.  This is a worthwhile cleanup that deserves proper review
time, and it would be more valuable if it can be refined without that
pressure.

So how about, once the current patch is verified and committed, we
pursue this as a separate follow-up?

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

My first reaction to the define_walker refactor was that something
about it did not sit right, but I could not put my finger on why, so I
kept putting off a clear answer -- sorry about that.  I have taken the
time to think it through now.

To be clear, the patch is good, idiomatic PostgreSQL code:
contain_var_clause() and contain_rprnavexpr() are exactly how we
express these checks elsewhere, and it trims a fair amount of code.

> The allowed nav-expression combination is limited, therefore,
> has_column_ref is not necessary.

This is where I land differently, though.  A DEFINE predicate is
context-sensitive: the same column reference is required inside a
navigation argument but rejected inside its offset.  In
"DEFINE A AS PREV(price, price) > 0", the first price (the argument)
is required and the second (the offset) is rejected.  The
phase-tracking walker models that context directly, in a single pass,
and it generalizes to whatever context-dependent nesting the clause
grows into (MEASURES, further navigation forms).  Dropping it works
today only because the allowed combinations are limited, as you note
-- it leans on that limit rather than on the shape of the clause.

It also gives up the single-pass property the walker was written for
("no subtree is walked twice"): each navigation argument and offset is
now walked about twice, once by the main walk and again by the
contain_* check.  The extra cost is small at parse time, but it is a
step back from a design that deliberately avoided it.

So my preference is to keep the context-aware walker as it stands.
This is more about which foundation we want for an inherently
context-sensitive clause than about anything being wrong in your
version -- if you see it the other way, I would be glad to hear it.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

I found a wrong result that comes from the context-absorption
optimization, and wanted to run it by you both.

  WITH d(id, a, c) AS (
    VALUES (1, true,  false),
           (2, true,  true),
           (3, true,  false),
           (4, false, false))
  SELECT id, count(*) OVER w AS cnt
  FROM d
  WINDOW w AS (
    ORDER BY id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    AFTER MATCH SKIP PAST LAST ROW
    PATTERN (A{5,} | C)
    DEFINE A AS a, C AS c);

   id | cnt
  ----+-----
    1 |   0
    2 |   0
    3 |   0
    4 |   0

id = 2 returns cnt = 0, but C matches [2,2] there, so it should be
1. EXPLAIN ANALYZE on the query reports "0 matched" and "2 absorbed".

The cause: whether a context can be absorbed is decided from its
in-progress states. Once the id=2 context records the C match [2,2],
that match moves to matchedState and its C state leaves the
in-progress set, so only the A run remains and the context is judged
fully absorbable. The id=1 context's longer A run then dominates it
and frees the whole context -- including the recorded [2,2] match.
The dominance argument only covers a context's future matches; it
does not account for a match already recorded on the non-absorbable
branch.

The fix: bring matchedState into the absorption comparison as well --
a context should be absorbed only when the absorbing context also
covers the recorded match, not just the in-progress states, so a
match the absorber cannot reproduce is never dropped.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

I hit a wrong result in row pattern recognition: an alternation
whose last branch is a concatenation of quantified groups matches
one group short.

  WITH d(id, dd, ee) AS (VALUES
    (1, true,  false), (2, false, true),
    (3, true,  false), (4, false, true))
  SELECT id, count(*) OVER w AS cnt
  FROM d
  WINDOW w AS (
    ORDER BY id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A | (B C)+ (D E)+)
    DEFINE A AS false, B AS false, C AS false,
           D AS dd, E AS ee);

   id | cnt
  ----+-----
    1 |   4      <- wrong; should be 0 (no match)
    2 |   0
    3 |   0
    4 |   0

The rows are D E D E, with no B and no C.  By precedence
PATTERN (A | (B C)+ (D E)+) means A | ((B C)+ (D E)+), so a bare
(D E)+ satisfies no branch and no row should match.  Instead row 1
matches [1,4]: the pattern behaves as if it were written
A | (B C)+ | (D E)+.

Cause: the ALT branch walk follows the branch head's jump to reach
the next branch.  That jump was the branch link, but the group
BEGIN's skip-past-END path was later layered onto the same field,
so jump is now overloaded.  When the last branch is (B C)+ (D E)+,
the BEGIN of (B C)+ jumps past its END to the BEGIN of (D E)+, and
the walk mistakes that following group for another alternative.

The same overloaded jump is walked in three places:
nfa_advance_alt (match advance), computeAbsorbabilityRecursive
(absorption marking), and the deparse.  nfa_advance_alt gives the
wrong result above.  computeAbsorbabilityRecursive over-marks the
trailing group as absorbable, though that turns out inert at run
time.  The deparse already sidesteps the overload in
rpr_next_branch() with the relative test elem[j-1].next != j, so
EXPLAIN prints the pattern correctly.

Fix direction: at its core, separate the BEGIN jump (group skip)
from the ALT branch-link jump -- they share one field today, which
is the overload.  I am weighing two ways to do that.

One is to move the group BEGIN's skip-past-END onto next.  Group
entry is already the contiguous BEGIN+1, so next is free, and jump
is left to be the branch link only.  No new elements.

The other is explicit branch-separator markers (a new SEP varid)
that carry the branch link, chained ALT.jump -> SEP -> ... ->
jump = -1 on the last one; branch content still reaches the
post-ALT element through next.

Either way the ALT walk sees jump as a branch link or -1, so
nfa_advance_alt, computeAbsorbabilityRecursive and the deparse can
enumerate branches the same clean way, dropping the relative test
and the depth-based break.  Deparse output stays the same.

I can put together a patch along these lines if the direction
looks right.

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
On Tue, Jul 7, 2026 at 11:40 AM Henson Choi  wrote:
>
> That said, I don't think we should take it into the patch at this
> stage.  The current version has one proven defect: a plain
> FIRST(expr, n) with n > 0 loses its forward reach.  I added a test for
> it -- "DEFINE A AS v > FIRST(v, 5)" in rpr_explain -- where the
> baseline prints "Nav Mark Lookahead: 5" and the patch prints 0.  The
> query result is still correct (the mark is under-advanced, so it only
> keeps extra rows), but the EXPLAIN is wrong and the tuplestore trim is
> lost, so it is a regression against the baseline.
>
> The test will come with the next patch email I send, so you will have
> it there to diff against.
>

The case you mentioned:
PATTERN (A) DEFINE A AS v > FIRST(v, 5)

is fixable easily, it was a mistake I made while refactoring
visit_nav_exec to cut
down the number of eval_nav_offset() calls.

> More broadly, though, reshaping the offset handling this much right as
> we are stabilizing for commit feels like the wrong time -- at this
> point I would rather limit changes to minimal fixes for proven
> defects.  This is a worthwhile cleanup that deserves proper review
> time, and it would be more valuable if it can be refined without that
> pressure.
>
> So how about, once the current patch is verified and committed, we
> pursue this as a separate follow-up?

That refactor is the patch I posted in [1]. An excerpt from its commit message:
```
Row pattern navigation (PREV/NEXT/FIRST/LAST and their compounds) resolves
offsets (transforming an expression into an int64) in ExecInitExprRec,
ExecEvalRPRNavSet, extract_const_offset and eval_define_offsets.  Several
places transform the same offset expression into an int64 -- that is too much.
With the attached, a single place (ExecInitWindowAgg -> eval_define_offsets)
handles this.
```

I think this belongs in the patchset now, rather than as a follow-up after the
main patch is committed. Computing the same offset in several places hurts
readability and, as this bug shows, is error-prone; consolidating it into one
place makes the code easier to read for future reviewers.

Committing the main patch and then posting a separate "make it readable"
refactoring afterward feels weird to me.
Refactoring now benefits everyone by significantly improving readability.

Broadly, I'd defend patch [2] on the same grounds: it improves readability, and
The current patchset doesn't need code that complex. It may not be the most
future-proof approach (I'm not certain) but given how complicated the whole
patchset already is, making each part more readable is a clear win for
reviewers.

Let's improve readability now while we can. Even assuming the patch is
committable today, there are still 9 months to refine it, so there's no rush
that justifies skipping cleanups. Each refactor makes the code more readable and
easier for reviewers to follow, which benefits everyone.

There won't be unlimited rounds of readability refactoring. Each
refactor makes the code clearer.
---------------------------------------------------
I hope the above is convincing.

[1] https://www.postgresql.org/message-id/CACJufxFfMJAMc0R6g4f7Bwr47QDY%2BOBr2vzqqMRbCzjdD9vR2g%40mail.gmail.com
[2] https://postgr.es/m/CAAAe_zC6iN79qEOgD2TzLHxA8i4T9R3pYtn_5dsQV8FXn3cEcA@mail.gmail.com



--
jian
https://www.enterprisedb.com/


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Tatsuo, Jian,
> 
> I hit a wrong result in row pattern recognition: an alternation
> whose last branch is a concatenation of quantified groups matches
> one group short.
> 
>   WITH d(id, dd, ee) AS (VALUES
>     (1, true,  false), (2, false, true),
>     (3, true,  false), (4, false, true))
>   SELECT id, count(*) OVER w AS cnt
>   FROM d
>   WINDOW w AS (
>     ORDER BY id
>     ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>     PATTERN (A | (B C)+ (D E)+)
>     DEFINE A AS false, B AS false, C AS false,
>            D AS dd, E AS ee);
> 
>    id | cnt
>   ----+-----
>     1 |   4      <- wrong; should be 0 (no match)
>     2 |   0
>     3 |   0
>     4 |   0
> 
> The rows are D E D E, with no B and no C.  By precedence
> PATTERN (A | (B C)+ (D E)+) means A | ((B C)+ (D E)+), so a bare
> (D E)+ satisfies no branch and no row should match.  Instead row 1
> matches [1,4]: the pattern behaves as if it were written
> A | (B C)+ | (D E)+.
> 
> Cause: the ALT branch walk follows the branch head's jump to reach
> the next branch.  That jump was the branch link, but the group
> BEGIN's skip-past-END path was later layered onto the same field,
> so jump is now overloaded.  When the last branch is (B C)+ (D E)+,
> the BEGIN of (B C)+ jumps past its END to the BEGIN of (D E)+, and
> the walk mistakes that following group for another alternative.

I think your analysis is correct. I see that AST is correctly
generated. So the issue is in the executor phase.

> The same overloaded jump is walked in three places:
> nfa_advance_alt (match advance), computeAbsorbabilityRecursive
> (absorption marking), and the deparse.  nfa_advance_alt gives the
> wrong result above.  computeAbsorbabilityRecursive over-marks the
> trailing group as absorbable, though that turns out inert at run
> time.  The deparse already sidesteps the overload in
> rpr_next_branch() with the relative test elem[j-1].next != j, so
> EXPLAIN prints the pattern correctly.
> 
> Fix direction: at its core, separate the BEGIN jump (group skip)
> from the ALT branch-link jump -- they share one field today, which
> is the overload.  I am weighing two ways to do that.

Either way works for me.

> One is to move the group BEGIN's skip-past-END onto next.  Group
> entry is already the contiguous BEGIN+1, so next is free, and jump
> is left to be the branch link only.  No new elements.
> 
> The other is explicit branch-separator markers (a new SEP varid)
> that carry the branch link, chained ALT.jump -> SEP -> ... ->
> jump = -1 on the last one; branch content still reaches the
> post-ALT element through next.
> 
> Either way the ALT walk sees jump as a branch link or -1, so
> nfa_advance_alt, computeAbsorbabilityRecursive and the deparse can
> enumerate branches the same clean way, dropping the relative test
> and the depth-based break.  Deparse output stays the same.
> 
> I can put together a patch along these lines if the direction
> looks right.

Ok.
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson, Jian,

v50-0007-tidy-plumbing-more.patch
Looks good to me.

Minor points:

In nfa_advance_alt():

	while (altIdx >= 0)
	{
		RPRPatternElement *altElem;
		RPRNFAState *newState;

		/* Branch jump/next links are always -1 or a valid index */
		Assert(altIdx < pattern->numElements);

Since inside the while loop altIndx == -1 case is already excluded by
the while condition, the comment for the Assert is a little bit
strange. Probably following is better?

		/* Branch jump/next links are always valid index */

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

Thanks for v51. v51-0001 fixes the loss of forward reach for FIRST(expr,
n > 0). That regression was my reason for saying the nav-offset
consolidation should not go in now, so that ground is gone. I will go on
with the review of the series.

Let me put the conclusion first, though. The trouble is not the
consolidation itself but the premise it rests on. There are several
defects in the same place, and the consolidation does not remove them --
it changes what they do, from fail-closed to fail-silent. So rather than
keeping the consolidation apart, I would like to bundle it together with
the related defects and fix them as one. Then it becomes a safe change
and can go into this patchset -- which is where you wanted it.

A word on approach. Neither refactoring for its own sake, nor fixing one
defect at a time as each one turns up, fits where we are. I would rather
we put every defect we have found so far side by side, analyze them
together, and improve towards a single design that resolves all of the
cases at once. Otherwise we keep touching the same place over and over,
paying the review and verification cost again each time. I hope you will
read what follows in that light.

From the verification I have run, the basic idea of the navigation code
looks sound. What it needs now is to be verified against a wider range
of cases and improved from there. I would like you to take ownership of
that area and work it through together with the design, over a broader
scope than a single patch.

For my part: I will verify it from a QA angle first -- building cases,
running them, collecting the failures -- and once it is close to
finished, go over it again in a line-by-line code review.

I have grouped what follows by patch, so it is visible which defect
touches which one.

Background

Today an offset is used in two places, for two different jobs.

  * eval_define_offsets() resolves it once, in ExecInitWindowAgg, to
    fill in the trim metadata (navMaxOffset / navFirstOffset).  That
    decides how far back rows are kept: advance_nav_mark() sets the
    mark position from it, and everything before that is released.

  * The actual navigation target is decided per row, by
    ExecEvalRPRNavSet() evaluating the offset expression.  That decides
    which row we go to.

That split is what keeps the failures below fail-closed. When the two
disagree, we end up asking for a row that has already been released, and
the mark-position check in window_gettupleslot() catches it before any
tuplestore read. The "cannot fetch row: 0 before WindowObject's mark
position: 1" in the defect 1 reproducer is exactly that: init read a 0,
decided it would never look back, and released the row that the per-row
evaluation then went looking for. Nothing comes back silently wrong.

So the redundancy is the safety net. And all of it stands on one
premise: an offset has a value by the time it is resolved. That premise
is already false today.


================================================================
1. The nav-offset consolidation
   v50-0001-Evaluate-navigation-offset-once-at-one-place
   v50-0002-Drop-the-shared-nav_traversal_walker-for-RPR-DEFINE
   v51-0001-Fix-the-regression-failure
================================================================

I applied it on our tree and checked. As your commit message says, every
offset is evaluated at init and stored, and ExecEvalRPRNavSet() only
reads those int64 values. So the per-row evaluation is gone, and the
value frozen at init decides the actual navigation target.

With the two collapsed into one, there is nothing left to disagree with.
The mark check can no longer fire on an offset mismatch -- it only fires
now if the trim metadata itself is wrong (see defect 5) -- and a wrong
init value picks the target row unchallenged. The safety net comes off.

That carries the premise above straight into the results. Running the
reproducer of defect 1 below, as is:

  offset   correct    baseline           with the patch
  ------   --------   ----------------   -------------------
  n = 1    0,9,...    0,9,... (right)    0,0,... (silently wrong)
  n = 2    0,0,8,.    internal elog      0,0,... (silently wrong)
  n = 3    0,0,0,7    internal elog      0,0,... (silently wrong)

All three return the answer for f(0), because the 0 read at init now
decides where PREV points. No error, no warning. Two things get worse at
once: what was fail-closed for n >= 2 becomes fail-silent, and n = 1,
which was *right* on the baseline, becomes wrong.

Five defects sit at this spot; the series already resolves one of them.

Defect 1 -- a nav offset taken from a function or lateral argument

  CREATE TABLE d(v int); INSERT INTO d SELECT generate_series(1,10);
  CREATE TABLE t(x int8); INSERT INTO t VALUES (2);
  CREATE FUNCTION f(n int8) RETURNS TABLE(cnt bigint)
    LANGUAGE sql STABLE AS $$
    SELECT count(*) OVER w FROM d
    WINDOW w AS (ORDER BY v ROWS BETWEEN CURRENT ROW AND UNBOUNDED
                 FOLLOWING PATTERN (A+)
                 DEFINE A AS v > PREV(v, n)) $$;

  SELECT * FROM f(2);        -- fine: the third row is 8
  SELECT * FROM t, f(t.x);   -- ERROR: cannot fetch row: 0 before
                             -- WindowObject's mark position: 1

A query that works when called directly turns into an internal error
once it is inlined and its argument comes from another FROM item.

Whether this happens depends on where the offset value comes from. A
bind parameter (PARAM_EXTERN, $1) is fine: ExecInitWindowAgg runs again
on every execution, and by then the value is there, so even with a
generic plan forced, EXECUTE returns the right answer.

The trouble is with the other kind of parameter. Function-RTE inlining
and lateral references plant a PARAM_EXEC in the nav offset, and that
one has no value yet at init and changes from one outer row to the next.
Executor init freezes the still-unset param as a constant 0, and nothing
re-evaluates it on rescan.

Two neighbours already show the right way. LIMIT/OFFSET calls
recompute_limits() again on rescan, and the frame offsets are evaluated
during execution by calculate_frame_offsets(). The nav offset alone is
frozen once at init and never revisited.

Defect 2 -- EXPLAIN (GENERIC_PLAN) fails on a parameter offset

  EXPLAIN (GENERIC_PLAN, COSTS OFF)
  SELECT count(*) OVER w FROM generate_series(1,5) g(v)
  WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
               PATTERN (A+) DEFINE A AS v > PREV(v, $1));
  -- ERROR: no value found for parameter 1

No user-defined function is involved; this is plain SQL. The same query
returns the right answer when run with EXECUTE. It only fails when you
ask to see the plan: eval_define_offsets() evaluates the offset without
looking at EXEC_FLAG_EXPLAIN_GENERIC.

This one collides with the consolidation head-on. The consolidation
relies on ExecInitWindowAgg being reached for EXPLAIN in order to print
concrete offsets instead of "runtime". But the fix here is to put an
EXEC_FLAG_EXPLAIN_GENERIC guard at that very call, skipping the
evaluation -- the way execPartition.c already skips execution-time
pruning for a generic plan. On today's tree the two fit together: the
kind stays NEEDS_EVAL and EXPLAIN prints "runtime". After the
consolidation they do not. With the plan-node kind gone there is no
"unknown" left to print, so a guarded EXPLAIN would show "Nav Mark
Lookback: 0" -- a made-up number no reader can tell from a real 0.

Defect 3 -- the planner does not account for PARAM_EXEC in DEFINE

  CREATE TABLE outer_t (threshold int);
  INSERT INTO outer_t VALUES (10), (200);
  CREATE TABLE stock (price int);
  INSERT INTO stock SELECT g FROM generate_series(1, 100) g;

  CREATE FUNCTION fn(th int) RETURNS SETOF bigint
  LANGUAGE sql STABLE AS $$
    SELECT DISTINCT count(*) OVER w FROM stock
    WINDOW w AS (ORDER BY price ROWS BETWEEN CURRENT ROW AND UNBOUNDED
                 FOLLOWING AFTER MATCH SKIP PAST LAST ROW
                 INITIAL PATTERN (a+) DEFINE a AS price > th) $$;

  SELECT * FROM fn(10)  ORDER BY 1;   -- 0, 90
  SELECT * FROM fn(200) ORDER BY 1;   -- 0

  -- DISTINCT is planned as a HashAgg here, and HashAgg rescan is gated
  -- on chgParam, so the hash table built for the first outer row is
  -- re-served for the second.
  SELECT o.threshold, f FROM outer_t o, LATERAL fn(o.threshold) f
  ORDER BY 1, 2;
  --  now:      10|0  10|90  200|0  200|90
  --  expected: 10|0  10|90  200|0
  --
  -- Both 200 rows are th=10's cached answer set {0, 90}; 200|0 only
  -- coincides with the right value.  Reversing the outer order makes it
  -- plain: with outer_t as (VALUES (200),(10),(50)), every row gets
  -- 200's answer -- 200|0  10|0  50|0
  -- With SET enable_hashagg = off the plan becomes Sort+Unique and the
  -- result is correct.

The argument is used only inside DEFINE, so once the function is inlined
the PARAM_EXEC appears only in defineClause. But the T_WindowAgg case of
finalize_plan() (the worker under SS_finalize_plan()) finalizes
startOffset and endOffset only, never defineClause, so that param is
missing from extParam and allParam. On rescan the chgParam signal
therefore never reaches the cache node above (here the HashAgg), which
re-serves the hash table built for the first outer row.

This looks like the plumbing root under the two above. If defect 1 is
"the value is not there yet", this one is "nobody notices the value
changed". Even with re-evaluation code in place, the signal that a
parameter changed would not arrive -- so the plumbing has to be laid
first.

The fix looks like one line: add a finalize_primnode() call for
defineClause to the T_WindowAgg case of finalize_plan(). I tried it, and
the stale row disappears with the RPR suites all passing.


Defect 4 -- the outer offset of a compound nav goes unvalidated
            (the series resolves this one)

  CREATE TABLE nav (id int, val int);
  INSERT INTO nav VALUES (1,10), (2,20), (3,30);

  -- inner in range: errors, as it should
  SELECT id, count(*) OVER w FROM nav WINDOW w AS (
      ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      PATTERN (A B+)
      DEFINE A AS TRUE, B AS PREV(FIRST(val, 0), NULL::int8) IS NULL);
  -- ERROR: row pattern navigation offset must not be null

  -- inner out of range (offset 99): same illegal outer offset passes
  SELECT id, count(*) OVER w FROM nav WINDOW w AS (
      ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      PATTERN (A B+)
      DEFINE A AS TRUE, B AS PREV(FIRST(val, 99), NULL::int8) IS NULL);
  -- no error; rows are returned

Today ExecEvalRPRNavSet() validates the inner offset inline at the top,
unconditionally. The outer offset, by contrast, is validated only in the
helper rpr_nav_get_compound_offset() -- and all four compound arms
(PREV/NEXT over FIRST/LAST) break out with target_pos = -1, before that
helper is ever called, as soon as the inner position overflows or falls
outside the match range. The asymmetry is right there in
ExecEvalRPRNavSet(): one check inline and always run, the other
delegated to a callee the early exits skip -- and so the same illegal
query errors out or passes quietly depending on the data.

The series resolves this. The consolidation removes
rpr_nav_get_compound_offset() and lifts both the inner and the outer
offset into eval_nav_offset() at init, where the NULL/negative check
runs once, unconditionally, independent of any row. Both queries above
then error alike. Noting it as a point in the series' favour.

There is something worth pausing on here, though. Nobody knew about this
defect, no test observes it, and the patch was not written to fix it. It
just went away. The same is true of defect 5 below: nobody is watching
what that executor code does today.

If a defect we never knew about can vanish quietly, a defect we never
know about can appear quietly too. Same place, same blind spot. We were
lucky this time; there is no guarantee about the next. That is why I
would rather we sort the defects out and put a test on each of them
first, and lay the consolidation on top of that, than take the series as
it stands.


Defect 5 -- three NEXT_FIRST comments say the opposite of the code
            right below them

This is the very code the patch rewrites. Three comments -- the
visit_nav_exec header, the NEXT_FIRST branch, and its planner twin in
visit_nav_plan -- state that "NEXT_FIRST's reach (inner+outer) is always
>= 0, so it never updates minFirstOffset / firstOffset (which track the
minimum)", while the code immediately below performs an unconditional
Min() update -- and that update is load-bearing. Two of the three -- the
visit_nav_exec header and the NEXT_FIRST branch -- are carried over
verbatim into compute_nav_offsets by v50-0001; the third disappears with
visit_nav_plan. After the consolidation the surviving Min() is the only
one left, so the comment sitting on top of it matters more, not less.

minFirstOffset starts at the sentinel PG_INT64_MAX. In a query where
NEXT_FIRST is the only FIRST-family nav, that Min() is the only path
that pulls the sentinel down to inner + outer. That value becomes
navFirstOffset and forms the lookahead bound in advance_nav_mark. (Today
the update exists twice, in visit_nav_plan for constant offsets and in
visit_nav_exec for runtime ones; after the consolidation only the
executor one is left.)

Remove the Min() trusting the comment, and navFirstOffset stays at the
sentinel: the overflow check in advance_nav_mark then trips, the
matchStart clamp is skipped altogether, the nav mark runs ahead, and
NEXT(FIRST()) fetches collapse with "cannot fetch row: N before
WindowObject's mark position: M".

The planner-side Min() is caught by the tests we have. Drop it and
rpr.sql's existing

    DEFINE A AS TRUE, B AS NEXT(FIRST(val, 1), 1) > 0

case dies with "cannot fetch row: 2 before WindowObject's mark position:
3", and rpr_explain's "Nav Mark Lookahead: 3" turns into "infinite". So
the comments are not merely unhelpful -- two tests that already exist
contradict them.

Nobody is watching the executor-side Min(). Delete that one and all five
rpr tests still pass: constant offsets never reach visit_nav_exec, and
the two existing NEXT(FIRST($1),$2) tests that do reach it use overflow
offsets, where the PG_INT64_MAX clamp hides the difference. To pin it
down, the offset has to be decided at run time and not overflow.

  SET plan_cache_mode = force_generic_plan;

  CREATE TABLE t AS
      SELECT g AS id, g AS v FROM generate_series(1, 200) g;

  PREPARE p(int8, int8) AS
  SELECT sum(cnt) FROM (
      SELECT count(*) OVER w AS cnt
      FROM t WINDOW w AS (
          ORDER BY id
          ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
          AFTER MATCH SKIP TO NEXT ROW
          PATTERN (A+)
          DEFINE A AS NEXT(FIRST(v, $1), $2) >= 0
      )
  ) s;

  EXECUTE p(0, 1);   -- sum = 20099
  EXECUTE p(0, 3);   -- sum = 20094

  -- with the executor-side Min() removed:
  --   ERROR: cannot fetch row: 1 before WindowObject's mark position: 2

force_generic_plan is needed: under a custom plan $1 folds to a Const
and the query goes back through the planner path. Without a case like
this, nobody observes what that executor code and its comment are doing
to each other. The patch rewrites the code and carries the comments over
unchanged, and after the consolidation that copy is the only one left --
so this is the moment to correct them.

One more thing sitting in the same code

make_windowagg assigns node->defineClause = wc->defineClause with no
copy, so the WindowAgg plan node and the parse tree's WindowClause share
the same List header and cells; set_upper_references then writes
OUTER_VAR Vars back into those shared cells. After planning, the DEFINE
TLEs in parse->windowClause therefore carry plan-level structure.
Nothing misbehaves in SQL today -- no code reads it after planning, and
plancache always hands the planner a querytree it is free to scribble on
(a private copy; for a one-shot plan, a tree that is planned exactly
once and then thrown away) -- but it breaks list ownership. And
setrefs.c is inconsistent with itself here: the frame offsets and run
conditions are fixed up by assigning the result back into the plan
node's own field (wplan->startOffset = fix_scan_expr(...)), so the
WindowClause is never dragged along, while defineClause alone is fixed
up by overwriting the cells of a list the plan node does not own
(lfirst(l) = tle) -- which is also unlike the targetlist loop just above
it, which builds a brand-new list.

Where this leaves the series

v51-0001 fixes the loss of forward reach for FIRST(expr, n > 0), which
was my ground for rejecting. Taken. With the regression gone, I have no
reason to block the series either.

But unless it is bundled with the remaining four, it moves the broken
premise from the trim metadata to the actual result.

Also, the fix I had in mind for defect 1 -- classify an offset that
holds an exec param as retain-all at plan time, giving up trim -- cannot
be written on top of this patch: RPRNavOffsetKind, extract_const_offset
and visit_nav_plan are all gone, and disabling trim is now the
navMaxOffset < 0 sentinel. We need to settle the fix together.

================================================================
2. v51-0002-Stop-evaluating-navigation-arguments-in-case-rows-not-exists
================================================================

Defect 6 -- an out-of-range navigation evaluates its argument
            (this patch fixes it)

  CREATE TABLE t (id int, v int);
  INSERT INTO t VALUES (1,10), (2,20), (3,30);

  -- The first row has no PREV row, so by the standard the navigation
  -- is null -> unknown -> the first row must not be mapped.
  SELECT id, count(*) OVER w AS cnt FROM t WINDOW w AS (
      ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      INITIAL PATTERN (A) DEFINE A AS PREV(v IS NULL));
  --  now: first row cnt = 1     expected: 0

  -- COALESCE behaves the same; NEXT does it at the last row.
  SELECT id, count(*) OVER w AS cnt FROM t WINDOW w AS (
      ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      INITIAL PATTERN (A) DEFINE A AS PREV(COALESCE(v, -1)) = -1);

An out-of-range target row is represented not as "there is no row" but
as an all-NULL fake row, and the argument is evaluated on it. So an
argument that looks at NULL directly -- IS NULL, COALESCE -- comes out
true and the row gets mapped. An argument insensitive to NULL (say
PREV(v) > 5) lands on the right answer, but only by accident.

I think both the direction and the implementation are right:
EEOP_RPR_NAV_SET writes a definitive resnull, and the following
EEOP_JUMP_IF_NULL skips the argument steps and lands on RESTORE. That
produces exactly the result the standard asks for. 19075-5 5.6.2 says
"If there is no previous row, the null value is returned", and spells
out the consequence -- "then PREV(A.Price) is null, so the Boolean
condition is not True, and therefore the first row cannot be mapped to
A". The standard mandates the result, not the evaluation strategy; but
skipping the argument is the only reliable way to get that result, since
an argument evaluated against an all-NULL row can turn the null into a
non-null value (IS NULL, COALESCE) -- and it also keeps a side-effecting
or erroring argument from running on a row that does not exist.


Defect 7 -- folding and pull-up erase the column reference in a nav
            argument

This is what the clauses.c hunk of this patch touches.

There are two routes into it.

Folding -- written directly, the parser rejects it:

  ... DEFINE A AS PREV(true)
  -- ERROR: argument of row pattern navigation operation must include
  --        at least one column reference

Yet the same shape passes once folding has been through it. v > 1 OR
true folds to true, and no column reference is left in the navigation
argument.

  ... DEFINE A AS PREV(v > 1 OR true)

Pull-up -- the same logical query gives different answers depending on
the shape of the plan:

  -- (a) a real table, one row
  CREATE TABLE t (id int, v int);
  INSERT INTO t VALUES (1, 10);
  SELECT id, count(*) OVER w AS cnt FROM t WINDOW w AS (
      ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      INITIAL PATTERN (A) DEFINE A AS PREV(v IS NULL));
  --  now: cnt = 1

  -- (b) a single-row VALUES -- the same query, and 0
  WITH t(id, v) AS (VALUES (1, 10))
  SELECT id, count(*) OVER w AS cnt FROM t WINDOW w AS (
      ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      INITIAL PATTERN (A) DEFINE A AS PREV(v IS NULL));
  --  now: cnt = 0

In (b), pull_up_simple_values() pulls the VALUES up and
pullup_replace_vars() substitutes v with the Const 10. No column
reference is left in the navigation argument, so 10 IS NULL is folded
away in advance. The answer depends on the plan shape.

One thing to add: with v51-0002 in, the difference in this query is
covered up -- there is no target row, so neither side evaluates the
argument and both give 0. But the substitution is still there, and the
invariant that arg must hold a column reference is still broken.

Parse analysis imposes opposite requirements on the two children (see
define_walker in parse_rpr.c):

    - arg must contain at least one column reference
    - offset_arg / compound_offset_arg must not contain column refs

The argument has to be evaluated on the target row, so it must keep a
column reference; the offset has to be a run-time constant, so it must
have none. The planner, however, treats them alike and const-folds all
of them recursively -- and so it produces what parse analysis would have
rejected: a navigation argument that does not depend on the target row.
There are more routes that erase the column reference than the
v > 1 OR true above: inline_function(), folding a CASE with a constant
condition, COALESCE(1, v) -> 1.

Pull-up happens earlier still, so clauses.c cannot even reach it. And
the same pull-up route can bypass the volatility check itself -- that is
defect 10 below.


Defect 8 -- a DEFINE predicate is evaluated every row even for a
            variable no state ever tries to map

This is the principle of this patch, one level up.

  CREATE TABLE t (id int, v int);
  INSERT INTO t VALUES (1,1), (2,2), (3,3);

  -- A is false at every row, so B is never tentatively mapped.  By the
  -- standard B's condition is evaluated at no row at all, and all three
  -- rows come back unmatched (cnt = 0).
  SELECT id, v, count(*) OVER w AS cnt FROM t WINDOW w AS (
      ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      PATTERN (A B)
      DEFINE A AS v < 0, B AS 1 / (v - v) > 0);
  --  now: ERROR: division by zero     expected: cnt = 0 on all rows

rpr_evaluate_row() evaluates every DEFINE predicate in defineClauseExprs
on every row, unconditionally. If the predicate of a variable that no
active NFA state tests at that row raises a runtime error, the whole
query dies.

ISO/IEC 19075-5, 4.16 DEFINE: "The Boolean conditions are evaluated on
successive rows of a row pattern partition in a trial match, with the
current row being tentatively mapped to a primary row pattern variable
PRPV as permitted by the pattern." The standard's matching procedure
therefore never evaluates B's condition here -- no row is ever
tentatively mapped to B -- and the result it defines for this query is a
clean "no match", cnt = 0 on every row. We evaluate a condition the
procedure never reaches, and a query with a well-defined result dies
with an error instead.

If v51-0002 says "do not evaluate the argument when there is no target
row", this says "do not evaluate the predicate of a variable you are not
even trying to map". Same grain. You have raised the short-circuit
yourself before, on exactly this shape -- PATTERN (A B) with A false. It
was framed as an optimization then; the case above shows it is also a
correctness question. Would you raise it as a formal item on the list?

Three requests

  * Please split the T_RPRNavExpr case in clauses.c out of this commit.
    As written it does not change behavior: expression_tree_mutator
    already handles T_RPRNavExpr, and eval_const_expressions_mutator's
    default path calls it.  I would rather we analyze defect 7 first,
    and take this up as a patch that actually fixes it.

  * The all-NULL row in nav_null_slot is dead with this fix: its only
    reader, ExecEvalRPRNavSet(), now returns early before installing the
    slot into econtext, so the fake row is never evaluated against.  The
    slot serves only as an out-of-range sentinel now -- please have
    ExecRPRNavGetSlot() return NULL instead and drop nav_null_slot.

  * Two comments.  (1) In ExecEvalRPRNavSet, "If the target row does
    exist..." is followed by the code for the row *not* existing, and
    the same sentence ends with a stray "1".  (2) In ExecInitExprRec
    (execExpr.c), "the EEOP_RPR_NAV_SET step has already stored a
    nav_null_slot" is no longer true with this patch -- that step stores
    nothing into econtext, it only writes a definitive resnull.

================================================================
3. v51-0003-Introduce-execution-struct-RprNavState
================================================================

You are right about the problem. Writing the resolved offsets onto the
RPRNavExpr in the plan tree goes straight against
src/backend/executor/README: "This arrangement allows the plan tree to
be completely read-only so far as the executor is concerned: all data
that is modified during execution is in the state tree.  Read-only plan
trees make life much simpler for plan caching and reuse."  Executor init
would be modifying a tree that is shared through CachedPlan. Moving them
into execution state is the right direction, the FOR PORTION OF
precedent fits, and the code reads clean. I would rather not rush a
verdict on it, though, and take the time to satisfy myself there is no
defect -- it sits right against the premise above, so it is worth the
care.

One thing to note: the rescan side of defect 1 survives this patch.
RprNavState moves the storage from the plan tree into execution state,
but it is still filled once in ExecInitExprRec, and ExecReScanWindowAgg
leaves the nav offsets alone -- so a PARAM_EXEC stays frozen. Seen the
other way, this structure gives us the place to hang that re-evaluation
on.

Two things I would like to settle while reading it.

  * Naming.  Everything in the tree is RPR* (RPRNavExpr, RPRNavKind,
    RPRNFAState); only the new types are RprNavState / RprNavOffsets.

  * The JsonExprState you cite is a plain struct with no NodeTag.
    RprNavState carries a NodeTag and uses makeNode, claiming a new node
    tag; if it is never used as a Node, a palloc would do, as in the
    precedent.


================================================================
4. v50-0001-refactor-DEFINE-volatile-expression-check
   (a patch I have not taken yet)
================================================================

Defect 9 -- the volatility gate only runs before folding

  CREATE FUNCTION off_leak(n bigint DEFAULT (random()*5)::bigint)
    RETURNS bigint LANGUAGE sql STABLE AS 'SELECT n';

  SELECT count(*) OVER w FROM generate_series(1,100) g(v)
  WINDOW w AS (ORDER BY v ROWS BETWEEN CURRENT ROW AND UNBOUNDED
               FOLLOWING PATTERN (A+) DEFINE A AS v > PREV(v,
               off_leak()));
  -- repeat it: ERROR: cannot fetch row: N before WindowObject's
  -- mark position: M

In planner.c, validate_rpr_define_volatility() runs before
preprocess_expression(), so it never sees the volatile default argument
that folding splices in afterwards. The function's STABLE label is
honest: there is no random() in its body, and given its arguments it
returns the same value within a statement.

A default argument is not the only thing that enters DEFINE after the
gate has run. flatten_join_alias_vars can plant a volatile implicit cast
into the merged column of an outer JOIN USING by the same route. (An
inner join will not do: buildMergedJoinVar() prefers the uncoerced input
for JOIN_INNER, so no cast survives into the merged column.) And when it
lands in the DEFINE body rather than in an offset, there is no error at
all: the match simply differs from one execution to the next.

This is a defect you have already aimed at. As your commit message says,
that patch moves the check to after preprocess_expression(), following
contain_volatile_functions_after_planning. That closes the hole. I have
not taken the patch yet, and this defect is the argument for it.

A word on the symptom as well. With the offset evaluated in two places
today, the volatile value differs between them and trips the
mark-position check above. Once the consolidation is in, even that error
is gone and the answer quietly differs from run to run. Six runs of the
same query:

  baseline            86, 88, ERROR, ERROR, ERROR, 90
  with the patch      98, 97, 96, 99, 96, 96

One more thing bothers me here. EXPLAIN of that query prints "Nav Mark
Lookback: runtime" on the baseline and "Nav Mark Lookback: 1" with the
patch, while the offset actually ranges over 0..5 at run time. The error
goes away because the mark is no longer derived from the same evaluation
the navigation uses -- not because the value is right. Baking a constant
lookback out of an offset expression that is not constant may be worth a
look of its own.

So this one has to close before the consolidation, or along with it.

Defect 10 -- the gate is not merely late; some paths never reach it

  CREATE TABLE t (id int);
  INSERT INTO t VALUES (1), (2);

  -- (a) at the top level it is rejected, as it should be
  SELECT id FROM t
  WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED
               FOLLOWING PATTERN (A+) DEFINE A AS random() > 0.5);
  -- ERROR: volatile functions are not allowed in DEFINE clause

  -- (b) wrap it in a FROM subquery and it passes quietly
  SELECT id FROM (
      SELECT id FROM t
      WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED
             FOLLOWING PATTERN (A+) DEFINE A AS random() > 0.5)) s;

  -- (c) control: OFFSET 0 blocks the pull-up, and the error is back
  SELECT id FROM (
      SELECT id FROM t
      WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED
             FOLLOWING PATTERN (A+) DEFINE A AS random() > 0.5)
      OFFSET 0) s;
  -- ERROR: volatile functions are not allowed in DEFINE clause

An EXISTS subquery and a UNION ALL leaf behave like (b).

validate_rpr_define_volatility() is called only from the windowClause
preprocessing loop in subquery_planner. But when the window is not
referenced by any OVER (hasWindowFuncs = false), the windowClause is
dropped before that loop ever sees it:

  - pull_up_simple_subquery(): is_simple_subquery() gates on
    subquery->hasWindowFuncs, not on windowClause != NIL, so the whole
    subquery Query -- windowClause included -- is discarded on pull-up;
  - simplify_EXISTS_query(): the same gate, then an outright
    query->windowClause = NIL;
  - a UNION ALL leaf reaches the first of these through
    pull_up_union_leaf_queries() -> pull_up_subqueries_recurse().

So the same invalid DEFINE is rejected or quietly accepted depending on
the shape of the query: wrap it in a FROM subquery and the error goes
away.

Moving the check after preprocess_expression() does not close this on
its own. All three discards happen earlier in subquery_planner --
pull_up_sublinks(), pull_up_subqueries() and flatten_simple_union_all()
all run before the first preprocess_expression() call -- so the old
position and the new one iterate exactly the same, already-pruned,
parse->windowClause. The check has to be reachable, not just late. Worth
looking at together when we reopen that patch.

One thing to decide

You noted losing the error cursor position as a trade-off in the commit
message. That choice looks unavoidable to me, in fact. When
inline_function() in eval_const_expressions re-parses a SQL function's
prosrc and substitutes it, the substituted FuncExpr keeps a location
relative to the function body. Attach an errposition to that in a
post-fold check and the location is applied to the outer query, where it
points somewhere else entirely. So a post-fold check is better off
attaching no position at all.

But that is exactly why I would keep the pre-fold check. A post-fold
check cannot tell a node the user wrote from a node an inlined function
body brought in -- nothing on the node records which string its location
belongs to -- so it has to drop the cursor for every case, the plain
hand-written volatile included. Only the check before folding can still
point at it. The first for the position (errposition attached), the
second for correctness (errposition omitted) -- how about keeping both?

A policy call rides along with that. Do we accept a volatile in a dead
branch, as in CASE WHEN false THEN random()? A double check catches it
up front; a single post-fold check lets it through. I would like us to
settle which behaviour we want.


================================================================
5. v50-0002-refactor-define_walker
   (another patch I have not taken yet)
================================================================

Defect 11 -- nav_count counts nav nodes, not nesting depth

  DEFINE A AS PREV(FIRST(v) + LAST(v)) > 0
  -- ERROR: cannot nest row pattern navigation more than two levels deep

Rejecting it is right. ISO/IEC 19075-5 5.6.4 describes the compound
operation only for the shape where FIRST / LAST is nested directly
inside PREV / NEXT -- as in PREV(LAST(A.Price + A.Tax, 1), 3) -- and its
evaluation procedure only makes sense for that shape: "The inner
operator, LAST, operates on the set of rows that are mapped to the row
pattern variable A ... The outer operator, PREV, starts from the row
found in step 1 and backs up 3 rows ... Let R be an
implementation-dependent range variable that references the row found by
step 2 [and] the resulting expression R.Price + R.Tax is evaluated". So
a complex expression belongs inside the innermost nav's argument, not
inside the outer one. (The normative Syntax Rules are in ISO/IEC 9075-2;
19075-5 is the explanatory TR.)

PREV(FIRST(v) + LAST(v)) is not that shape: the outer PREV's argument is
an arbitrary expression adding two navs. FIRST(v) and LAST(v) point at
different rows, so there is no row for PREV to back up from. 5.6.2
rejects PREV(1) with the same kind of reasoning -- "Without a column
reference or CLASSIFIER function, there is no way to determine the row
that is the starting point for offsetting." The argument above does have
column references, but two sibling navigations designate two different
rows, so there is still no single row for PREV to offset from.

The trouble is the diagnosis. There is no three-level nesting in that
input; it is two levels deep, with two sibling navs. But ctx->nav_count
counts every RPRNavExpr found anywhere in the outer nav's argument
subtree -- it keeps recursing -- so the count check fires before the
depth check. We reject it for a reason that is not true.

The error should state the actual rule: nav nesting is allowed only when
the inner nav is the direct argument of the outer one. That wording
already sits seven lines below -- "row pattern navigation operation must
be a direct argument of the outer navigation" -- and it does fire
correctly for the single-sibling PREV(v + FIRST(v)). Only this class
never reaches it. The HINT on the errmsg does list the four legal
compound forms, so the user is not left entirely without a clue -- but
the errmsg itself is still false.

This is the very walker your patch reworks. If we reopen it, I would
like the diagnosis fixed along the way.

And the point you make in that commit message -- that "must be a
run-time constant" looks wrong, since the offset can be a plpgsql STABLE
function -- is the same question as defect 1: is an offset that comes
from a function argument or a lateral argument a run-time constant? That
answer sets the fix for defects 1 and 2, so it is best settled together
with this patch.

One more meeting point: the invariant defect 7 leans on -- arg must hold
a column reference, the offset must not -- is exactly the check this
patch rewrites from has_column_ref to contain_var_clause. So the fix for
defect 7 and this patch land in the same place.

================================================================
A proposal
================================================================

I am not against resolving the offset in one place. But that
consolidation rests on the premise that an offset has a value by the
time it is resolved, and that premise is already false today.

The eleven defects above come down to five roots:

  * offsets and arguments are frozen once at executor init
    (defects 1, 2)
  * the planner's tree walks do not look into defineClause yet
    (defect 3, and list ownership with it)
  * the volatility gate runs only before folding, and some paths never
    reach it at all (defects 9, 10)
  * folding and pull-up erase the column reference in a nav argument --
    an invariant parse analysis enforces is broken in the planner
    (defect 7)
  * we evaluate to a different result than the standard defines -- the
    argument of an out-of-range nav, and the predicate of a variable we
    are not even trying to map (defects 6, 8)

So rather than fixing them one at a time, I think they are better done
as one bundle -- with the consolidation in it. What the bundle would
carry:

  1. Make the premise hold: evaluate the offset again once the value is
     known, the way frame offsets and nodeLimit already do, or give up
     trim when the offset comes from such an argument.
  2. Wire defineClause into the planner plumbing (finalize_plan's
     PARAM_EXEC bookkeeping, the reachability of the volatility check).
  3. Settle where the volatility check goes, before and after folding,
     and put it there.
  4. Protect arg from constant folding and from pull-up substitution.
  5. Bring evaluation in line with the standard: no argument when there
     is no target row, no predicate when we are not trying to map.
  6. Add the EXPLAIN guard.
  7. On top of that, resolve the offset in one place -- the
     consolidation.

The comments and the diagnosis get put right along the way (defects 5
and 11).

Going in as one bundle, the consolidation becomes a much safer change
and I would be glad to see it in -- exactly where you want it, in this
patchset, only bundled with the defects.

Would you be able to work on top of these patches? Working from the same
base would make it easier for us to check each other.

I would like us to agree on what goes into this round and what waits,
before we go further.

A note on version numbers

There is still no complete v50. What went out as v50-0001..0020, and
v51-0001..0003 now, are all increments on top of v49. Bumping the
version for every increment means the same number ends up standing for
different patches. This mail is itself an example: v50-0001 and v50-0002
in the section headings above each name two different patches, and
without spelling out the full patch name there is no telling which.

I will post a draft of a numbering convention with the series that
follows. I would welcome your thoughts on it.

Two small things

Noticed while reading the patch:

  * The definition of nav_traversal_walker() is gone, but its
    declaration is still in src/include/optimizer/rpr.h -- and with it
    the whole supporting block: the NavTraversal struct, the NavVisitFn
    callback typedef, and the comment above them, which still says the
    walker is "defined in rpr.c".  NavTraversal and NavVisitFn are also
    still in src/tools/pgindent/typedefs.list.

  * README.rpr still describes navMaxOffsetKind / navFirstOffsetKind,
    RPR_NAV_OFFSET_NEEDS_EVAL and RPR_NAV_OFFSET_RETAIN_ALL.  A comment
    in rpr_explain.sql still refers to visit_nav_exec and one in rpr.sql
    to RPR_NAV_OFFSET_NEEDS_EVAL; the matching rpr.out / rpr_explain.out
    carry the same lines.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Hi Jian, Tatsuo,
> 
> Jian, two questions of yours from earlier in the thread never got an
> answer from me.  Late, but here are both.
> 
>> Except that i want to rename RPSkipTo to RPRSkipTo and rpSkipTo to
>> rprSkipTo, What do you think?

I am not sure what we are talking about because RPSkipTo is a typedef
name but rpSkipTo is a struct member name. Do we want to establish a
policy not only for typedef but for struct members?

> Rather than a yes or no on this one name, I would like to treat it as
> a policy call over the whole list.

To be honest I don't have strong preference about struct or enum
names. However, I suggest to decide a priority for this renaming work
first. I think this kind work is best done after we stabilize our
code. Because we can detect mistakes in the renaming work easier after
establishing code rather than before. What do you think?

BTW, when do we want to refactor WindowAggState so that RPR related
members are grouped into a sub struct? I think this needed to be done
while making our code commitable.

> The split we have is historical.  RP -- RPCommonSyntax, RPSkipTo --
> predates my joining this patch.  RPR came later, from the pattern
> compiler and the NFA I wrote.  Neither author was aware of the other's
> prefix; each of us just used his own.  Now the two meet in one place,
> since RPCommonSyntax holds an RPRPatternNode *rpPattern.
> 
> The full list as it stands:
> 
>   RP*  (parse / plan / exec nodes)
>       RPCommonSyntax, RPSkipTo
>       rpCommonSyntax, rpSkipTo, rpPattern, rpDefs  (parsenodes.h)
>       rpSkipTo, rpPattern       (plannodes.h, execnodes.h)
> 
>   RPR* (pattern compiler, NFA, navigation)
>       RPRPatternNode, RPRPatternNodeType, RPRPattern,
>       RPRPatternElement, RPRElemFlags, RPRElemIdx, RPRVarId,
>       RPRQuantity, RPRDepth, RPRNFAState, RPRNFAContext,
>       RPRNavExpr, RPRNavKind
>       RPR_ELEM_*, RPR_VARID_*, RPR_NAV_*, RPR_QUANTITY_INF,
>       RPR_VARID_MAX
> 
>   typedefs.list carries 15 of these -- 2 RP, 13 RPR.
> 
> So what we would be choosing between is three policies:
> 
>   (a) RPR* throughout -- one prefix for the feature; the RP names
>       (7 identifiers, plus 2 typedefs.list entries) move over.
> 
>   (b) RP* throughout -- the other direction.  It moves far more (13
>       types, plus the whole RPR_ELEM_* / RPR_VARID_* / RPR_NAV_*
>       macro families) and cuts against everything already settled on
>       RPR: the file names (rpr.c, rpr.h, execRPR.c, README.rpr), the
>       tests (rpr.sql, rpr_explain.sql), and the acronym of the
>       feature itself (row pattern recognition).
> 
>   (c) RP for the row pattern syntax as the standard names it (row
>       pattern common syntax, AFTER MATCH SKIP TO), RPR for the
>       machinery that recognizes it -- a deliberate boundary, written
>       down so it reads as intent rather than as an accident.
> 
> I have no strong preference between (a) and (c).  (b) I list for
> completeness -- with everything around it already RPR, it looks like
> the most expensive of the three.  Either way, what I am against is
> settling this one name at a time.

As I said earlier, I have no strong preference. So (a) is fine for me.

> On timing, too: I would rather we decided it after the correctness
> defects are closed.  A rename touches the parse, plan and executor
> nodes at once, so it collides with every patch in flight and with the
> defect work under way -- and it buys a reader nothing today.  Once the
> defects are settled it is a single mechanical patch, and a much easier
> review.

Agreed.

> Tatsuo, since RP is yours and RPR is mine, this is really a call for
> you to make.  Either way suits me.
> 
> Jian, while I am here: v50-0003 (EMPTY_LOOP -> RPR_ELEM_EMPTY_LOOP) is
> taken.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

Over the last few weeks I put the RPR matcher through a systematic
cross-check against Oracle 23ai and Trino 471.  This message reports
what that surfaced: a few correctness defects in the matcher and in
context absorption, and a list of feature gaps that are directions
rather than bugs.


== How the cross-check was done ==

I took the roughly 1,000 PATTERN statements in the regression suite.
At the point each query runs I dumped the source rows and asked each
engine the same three things per row -- the length of the match that
starts at this row, and that match's first and last row.  On PG that
is count(*) / first_value / last_value over the RPR window.  Trino has
the same window form of row pattern recognition, so I ran it there in
the same shape.  Oracle has only MATCH_RECOGNIZE, so there I reduced

  MATCH_RECOGNIZE ... ALL ROWS PER MATCH WITH UNMATCHED ROWS

to the same shape (keeping only the match's first row, empty matches
being the ones with a NULL classifier).

Where Oracle runs a query I judged against Oracle; where Oracle
rejects it (a quantified subpattern that can match empty -- ORA-62513)
I used Trino; where the two engines split I used the ISO/IEC TR
19075-5 text.

On the queries both engines run, zero rows differ.  But the cross-
check surfaced defects in areas the suite did not cover.


== Correctness defects ==

--- 1. Preferment in the matcher ---

There are three roots.

(a) The cycle guard identifies a matcher state by its position in the
    pattern alone.  A state is really (position, repetition count);
    looping back to the same variable with a different count is a new
    state, not a cycle.  The guard kills it and the whole match
    disappears.

      PATTERN (A+ | B){2}  on  A, A, A
        now: no match      expected: 3 rows

(b) An empty iteration does not stop the quantifier (TR 19075-5
    7.2.8: once the lower bound is met and the body matches empty, the
    quantifier stops looping -- the Perl rule).  Discarding the empty-
    iteration state demotes "stop here" below a less-preferred branch,
    which then consumes rows first.

      PATTERN (A? | B)*  on  A, B
        now: 2 rows        expected: 1 row

(c) The fast-forward order is decided by the group's own greed.  When
    min == max the group's greed says nothing, yet the body may still
    prefer to consume.

      PATTERN ((A?){2}?)  on  A, A
        now: 1 row         expected: 2 rows

Engine cross-check:

  case               PG now  exp  Oracle  Trino  std
  (A+|B){2} AAA        0      3     3       3    -
  (A?|B)*  AB          2      1     rej     2    1 (7.2.8)
  ((A?){2}?) AA        1      2     rej     2    -
  ((A??){2}) AA        2    empty   rej   empty  -

One point to note.  On the (A?|B)* row, current PG and Trino give the
same value, 2 rows -- and 2 is wrong.  Had Trino been the sole
reference this defect would have passed; two engines agreeing is not
by itself proof.  I come back to this case, with Perl, in the last
section.

Direction: apply the cycle guard only to states that are not a pattern
variable (a variable consumes a row, so it cannot form an epsilon
cycle, and duplicates are already screened by the existing uniqueness
check, which compares the counts).  When an empty iteration reaches a
repetition's exit with the lower bound already met, do not discard it
-- enumerate the stop at that preference rank.  And decide the fast-
forward order from the body's preference, not the group's.


--- 2. Context absorption ---

The absorption optimization (dropping an inferior context once
dominance holds at a comparison point) produced two wrong answers and
one potential hang.

First, absorption drops a match that a non-absorbable branch has
already recorded.

      PATTERN (A{5,} | C)
      -- at id=2, C matches [2,2] but cnt=0 (expected 1)
      -- EXPLAIN ANALYZE: "0 matched, 2 absorbed"

  The dominance argument covers only a context's future (in-progress)
  matches; a match already recorded on a non-absorbable branch is
  outside it.  (I reported this on the thread on 2026-07-07.)

Second, a wrong result in the alternation branch walk.

      PATTERN (A | (B C)+ (D E)+)   input: D E D E
      -- now: match [1,4]      expected: no match

  The walk follows a link that is overloaded -- it means "next branch"
  at a branch head but "skip this group" at a group head -- so when
  the last branch starts with a group, the trailing group leaks out as
  an extra branch.  The pattern behaves as A | (B C)+ | (D E)+ and
  matches a bare (D E)+.  It is a common-mode wrong answer: the same
  with absorption on and off, so an on/off differential does not catch
  it.  (Reported on 2026-07-08.)

Third, a potential hang in the absorption analysis.  To find a group's
end it walks forward through the pattern; with a {1,1} group in a
non-leading position of a sequence, the walk never leaves the group
and spins.  It is at plan time (EXPLAIN alone triggers it) and the
loop has no interrupt check, so statement_timeout does not fire
either.  A normalization that unwraps a {1,1} group removes this shape
before the matcher is built, so it does not reach users today -- but
one slip there turns it into a plan-time hang.  Bounding that forward
walk would guard it.


== R020 subset vs R010 -- scope, not bugs ==

There are 11 queries PG rejects at parse time that Oracle implements.
None give a wrong answer -- the suite pins each as a negative test.
The root is one thing: PG implements a subset of R020 (the WINDOW
clause) while Oracle implements R010 (MATCH_RECOGNIZE).  Going through
them, each already has a documented rationale -- none is an
unexplained gap.  Six kinds:

  feature                    n   PG error
  aggregate in DEFINE        3   aggregate functions are not allowed
                                 in DEFINE
  variable qualifier in      2   pattern variable qualified
    DEFINE (A.val)               expression ... is not supported in
                                 DEFINE
  pattern anchor ^, $        2   syntax error at or near "^" / "$"
  nav argument with no       2   argument of row pattern navigation
    column, PREV(1)              operation must include at least one
                                 column
  scalar subquery in DEFINE  1   cannot use subquery in DEFINE
                                 expression
  non-integer nav offset     1   offset argument of PREV must be type
    PREV(val, 1.5)               bigint, not type numeric

Grouped by why PG rejects:

Documented as not implemented (the v49 patch message lists both):

- Aggregate in DEFINE.  It needs the per-match RUNNING/FINAL machinery
  that MEASURES relies on (Oracle evaluates it as a running aggregate
  that decides the match length), and this RPR does not implement
  MEASURES.

- Variable qualifier in DEFINE (A.val).  Also listed as not
  implemented; it needs no machinery on the scale of MEASURES, so it
  ranks differently.

Rejected because the standard says so in R020, so PG is right:

- Anchors ^ and $ (and the empty pattern PATTERN ()) are not permitted
  in R020; the v49 message notes this.  Oracle accepts them under
  R010.
- The column-less navigation argument, PREV(1).  ISO/IEC TR 19075-5
  5.6.2 requires the first argument of PREV/NEXT to hold at least one
  column reference or CLASSIFIER function, so PG's rejection follows
  the standard, and was a deliberate call on the thread.

Intentional over-rejection, left as future work:

- A scalar subquery in DEFINE.  19075-5 6.17.4 permits one if it does
  no pattern recognition itself and does not reference an outer
  pattern variable.  PG rejects all subqueries for now by design -- a
  source comment marks it as future work, the blanket rejection
  subsuming both conditions.  This is the one I would call an actual
  direction for later.

Type strictness, correct as is:

- DEFINE must be boolean, and a nav offset must be an integer.
  SQL:2016 requires a boolean DEFINE condition; PG checks at parse
  time while Oracle coerces with type-dependent rules (a text column
  can die at runtime on the first non-boolean value).  A fractional
  row offset like PREV(val, 1.5) has no meaning, so the bigint
  requirement holds too.

I record these so a migrating user knows what to expect and they are
not later read as bugs.  The only forward item is relaxing the DEFINE
subquery rejection, which the source already marks as future work.


== On Trino as a reference ==

Trino implements the empty-match quantifier region Oracle rejects, so
it was a useful tie-breaker there.  But it is only a partial
reference.  The clearest case is the (A? | B)* row above, on rows
A, B:

  PG now, Trino    2 rows   <- both wrong
  standard         1 row    (7.2.8)

Trino keeps looping the * after the body has matched empty, so it lets
the second branch B consume row 2.  7.2.8 says the opposite: once the
lower bound is met and the body matches empty, the quantifier stops.

Perl settles it -- 7.2.8 states its stopping rule is modeled on Perl.
The equivalent pattern matches one character, not two:

  "AB" =~ /^(?:A?|B)*/   ->   "A"

At iteration 2 the preferred branch A? matches empty, the quantifier
stops there, and B is never reached.  Perl and the standard agree on
one row; Trino's two is the outlier -- exactly what PG does now,
which is why PG matching Trino is not by itself proof.  Forms with an
unbounded quantifier over a nullable-body alternation ((A*)*,
(A* B*)*, (A??)* B) cannot be trusted without deriving them from the
standard again.


== Pattern-tree optimizations ==

These rewrites are PG-internal, so the cross-check does not diff them
directly; it sees them only when a rewrite changes the final answer.
Three did.  Each kept the set of matchable lengths but changed which
match is preferred [1].  The rewrite reorders a repetition's exit
decision relative to a choice point in the body, so a plain query
returns a different match with the optimization than without.

- One flattens a nested bounded quantifier, (A{2,3}){1,2} -> A{2,6}.
  The nested form settles the first iteration's count before deciding
  to iterate again: on four A rows it takes three and stops, while
  A{2,6} takes all four.

- Another folds a copy of the body into an adjacent group's
  quantifier, (A | B B)+ (A | B B)+ -> (A | B B){2,}.  The merged form
  defers the group's stop past a choice the separate copy made first:
  it prefers a two-row match where the pattern as written prefers
  four.  A third folds a trailing copy of a group's body the same way,
  with the same effect.

The common cause is reordering the exit decision against a body
choice.  The safe gates: flatten only when the child cannot fall short
of its lower bound (min <= 1 or max unbounded); merge only when the
body consumes a fixed number of rows (equal-length alternatives
count).  A mandatory leading copy of a group's body reorders nothing
and needs no gate.

  [1] "Preferred" is the standard's preference ordering over the
  possible matches (TR 19075-5 7.2): leftmost alternative first, and
  greedy vs. reluctant on each quantifier.  The set of matches does
  not change; only this ordering moves.


That is everything the cross-check surfaced.  The fix directions for
the matcher preferment and absorption defects are above; the R020
rejections each already have a documented rationale, with the DEFINE
subquery relaxation the one forward item.

Best regards,
Henson

Re: Row pattern recognition

От:
신성준 <shinsj4653@gmail.com>
Дата:
Hi Henson, and hackers,

Henson has been mentoring me and suggested I try building and running
this patch, so this is a first-timer's build-and-use note, not a real
review.

I built cf/4460 (v49) on macOS 15 / Apple Silicon (arm64), meson with
cassert and debug. It built without errors. One small thing worth
flagging: it emits two -Wmacro-redefined warnings for INITIAL, in the
generated scanners (backend scan.c and ecpg pgc.c). The new INITIAL
keyword ends up as a token macro (#define INITIAL in gram.h) that
collides with flex's built-in INITIAL start condition (#define INITIAL 0
in the scanner). A plain master build here is warning-clean (no INITIAL
keyword there), so this looks specific to the patch. Seen on clang; not
sure if it's known or turns up on other compilers.

On tests, rpr, rpr_nfa, rpr_explain and rpr_integration pass. rpr_base
has only the RESPECT/IGNORE NULLS wording diff, which looks like the
pending rebase rather than anything real.

I also went beyond the basic example -- the two SKIP modes, quantifier
variants ({2,}, *, a reluctant quantifier, an alternation), and a few
odd inputs (tied values, a NULL mid-run, a single-row partition).
Everything behaved as I'd expect, nothing anomalous.

This was v49, since that's what cfbot has built. Happy to re-run on the
latest after a rebase, on macOS/arm64 if that platform is useful to have
covered.

Best regards,
Seongjun


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi,


> Hi Henson, and hackers,
> 
> Henson has been mentoring me and suggested I try building and running
> this patch, so this is a first-timer's build-and-use note, not a real
> review.

Thanks for the testing.

> I built cf/4460 (v49) on macOS 15 / Apple Silicon (arm64), meson with
> cassert and debug. It built without errors. One small thing worth
> flagging: it emits two -Wmacro-redefined warnings for INITIAL, in the
> generated scanners (backend scan.c and ecpg pgc.c). The new INITIAL
> keyword ends up as a token macro (#define INITIAL in gram.h) that
> collides with flex's built-in INITIAL start condition (#define INITIAL 0
> in the scanner). A plain master build here is warning-clean (no INITIAL
> keyword there), so this looks specific to the patch. Seen on clang; not
> sure if it's known or turns up on other compilers.

Here (Ubuntu 24.0 LTS + bison 3.8.2) I only see enum in gram.h,

# define YYTOKENTYPE
  enum yytokentype
  {
	:
	:
    INITIAL = 472,                 /* INITIAL  */

In addition you see #define INITIAL in gram.h?

If yes, probably we should consider change "INITIAL" to something like
"INITIAL_P" to avoid the collision?

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> Hi hackers,
> 
> This is an increment on top of v49: it carries what has accumulated
> since the last posting, plus one adjustment needed by a recent rebase
> onto master.  The attachments are named nocfbot-XXXX-*.txt so that
> cfbot does not pick them up.
:
:
> 2XXX -- awaiting review from Tatsuo
> 
> Posted earlier but not yet reviewed (2009..2021), and what has
> accumulated since (2022..2026).
> 
>   2009  Refactor transformDefineClause in row pattern recognition
>         [behavior change]                              (= v50-0008)
>   2010  Replace a bare block with an else in the RPR DEFINE clause
>         walker                                         (= v50-0009)
>   2011  Rename loop index variables in row pattern deparse
>         helpers                                        (= v50-0010)
>   2012  Rename absorption "judgment point" to "comparison point" in
>         comments                                       (= v50-0011)
>   2013  Improve comments, documentation, and naming for row pattern
>         recognition                                    (= v50-0012)
>   2014  Document eval_nav_offset_helper's NULL/negative offset
>         handling                                       (= v50-0013)

2009-2014 look good to me.

>   2015  Tidy up the row pattern unbounded-quantifier
>         sentinel                                       (= v50-0014)

From the commit message:

> The grammar and planner spelled the unbounded quantifier bound as a bare
> PG_INT32_MAX, while the executor already used RPR_QUANTITY_INF for the
> same value.  Use RPR_QUANTITY_INF on the parser and planner side as well
> so every stage shares one sentinel; gram.y keeps a local copy of the
> macro to avoid including the planner header.

I am not sure having a local copy of the the macro in gram.y is a good
idea. What about putting it into primnodes.h?

I will continue to review 2016-2021.
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
신성준 <shinsj4653@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

> In addition you see #define INITIAL in gram.h?

Yes -- here gram.h has both the enum and the macro:

    enum yytokentype { ...; INITIAL = 472; ... };
    #define INITIAL 472

The file header says "made by GNU Bison 2.3". That's macOS's system
bison, and it still emits the #define token macros, so INITIAL collides
with flex's #define INITIAL 0 in the scanner. Your 3.8.2 emits only the
enum, which is why you don't see it. 2.3 is the minimum the tree still
accepts (meson.build asks for >= 2.3) and it's what macOS ships, so a
build on that floor hits the warning.

> probably we should consider change "INITIAL" to something like
> "INITIAL_P" to avoid the collision?

That matches the _P convention already used for NULL_P / TRUE_P / IN_P,
so it seemed worth trying. I've attached a small patch that renames the
token to INITIAL_P in kwlist.h and gram.y; the SQL keyword stays
"initial". With it applied, both -Wmacro-redefined warnings are gone and
the build is warning-clean here, still on bison 2.3. The patch is on top
of v49 and named nocfbot-*.txt so cfbot doesn't pick it up. No rush on
this -- it can wait for whenever a cleanup pass fits. Please fold it in
or adjust as you see fit.

Regards,
Seongjun

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Seongjun,

> Yes -- here gram.h has both the enum and the macro:
> 
>     enum yytokentype { ...; INITIAL = 472; ... };
>     #define INITIAL 472
> 
> The file header says "made by GNU Bison 2.3". That's macOS's system
> bison, and it still emits the #define token macros, so INITIAL collides
> with flex's #define INITIAL 0 in the scanner. Your 3.8.2 emits only the
> enum, which is why you don't see it.

That makes sense.

> 2.3 is the minimum the tree still
> accepts (meson.build asks for >= 2.3) and it's what macOS ships, so a
> build on that floor hits the warning.

Yeah, wee should accept a build envrionment with bison 2.3.

>> probably we should consider change "INITIAL" to something like
>> "INITIAL_P" to avoid the collision?
> 
> That matches the _P convention already used for NULL_P / TRUE_P / IN_P,
> so it seemed worth trying. I've attached a small patch that renames the
> token to INITIAL_P in kwlist.h and gram.y; the SQL keyword stays
> "initial". With it applied, both -Wmacro-redefined warnings are gone and
> the build is warning-clean here, still on bison 2.3. The patch is on top
> of v49 and named nocfbot-*.txt so cfbot doesn't pick it up. No rush on
> this -- it can wait for whenever a cleanup pass fits. Please fold it in
> or adjust as you see fit.

Thanks for the patch.  Your patch looks good to me except "INITIALLY"
should be before "INITIAL_P" in ASCII. ('L' == 0x4c, '_' == 0x5f in
ASCII).

> -	INCLUDING INCREMENT INDENT INDEX INDEXES INHERIT INHERITS INITIAL INITIALLY INLINE_P
> +	INCLUDING INCREMENT INDENT INDEX INDEXES INHERIT INHERITS INITIAL_P INITIALLY INLINE_P

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Seongjun, Tatsuo,

I reproduced this here as well, on two platforms:

  - macOS / Apple Silicon, GNU Bison 2.3 (the system bison, and the
    tree's declared minimum): gram.h carries "#define INITIAL 472"
    next to the enum, so it collides with flex's "#define INITIAL 0"
    -- the two -Wmacro-redefined warnings (backend scan.c, ecpg
    pgc.c) both appear.
  - Rocky Linux 10.1, GNU Bison 3.8.2 (a different distro from
    Tatsuo's Ubuntu, but the same bison): gram.h has only the enum,
    no "#define INITIAL", and the build is clean.

So it is purely the bison version, as you and Tatsuo concluded. In
fact I had -Wno-macro-redefined in my build flags because of a compile
issue with some extensions, which masked this warning so I hadn't
noticed it -- thanks for flagging it. Without that flag (a stock
./configure build, or meson), bison 2.3 shows it.

> Your patch looks good to me except "INITIALLY" should be before
> "INITIAL_P" in ASCII. ('L' == 0x4c, '_' == 0x5f in ASCII).

I think the ordering is already right as the patch has it. The
keyword lists sort every _P symbol as if the suffix weren't there,
i.e. by its bare name. In the %token block alone, these adjacent
pairs all place an X_P ahead of a word that raw ASCII would sort
first:

    CHAR_P/CHARACTER, CURRENT_P/CURRENT_CATALOG, DATA_P/DATABASE,
    GROUP_P/GROUPING, IN_P/INCLUDE, INT_P/INTEGER, LOCK_P/LOCKED,
    NAME_P/NAMES, NULL_P/NULLIF, OBJECT_P/OBJECTS_P, OUT_P/OUTER_P,
    REF_P/REFERENCES, TYPE_P/TYPES_P, VALUE_P/VALUES,
    XML_P/XMLATTRIBUTES

INITIAL_P before INITIALLY is the same pattern (INITIAL < INITIALLY).
This is exactly what check_keywords.pl enforces -- it strips the _P
before the comparison -- so the patch passes as-is, while swapping to
INITIALLY first fails with

    'INITIAL' after 'INITIALLY' in bare_label_keyword list is misplaced

and exits non-zero, which would break the build.

So I don't think any reordering is needed. I'll carry the patch as
nocfbot-0002 in the 0XXX (base build adjustment) band of the next
incremental posting, so the series stays coherent until it is folded
into the raw-parser patch.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> 2XXX -- awaiting review from Tatsuo

I have finished reviewing 2015-2026 patches.

>   2015  Tidy up the row pattern unbounded-quantifier sentinel
>                                                        (= v50-0014)
>       Revised per your 07-19 comment.  The macro is no longer a local
>       copy in gram.y: RPR_QUANTITY_INF is now defined once in
>       nodes/parsenodes.h, next to RPRPatternNode whose max field
>       stores it, and gram.y and optimizer/rpr.h use that one
>       definition.  On the placement -- you suggested primnodes.h; I
>       put it in parsenodes.h because that is where RPRPatternNode
>       lives, and parsenodes.h includes primnodes.h, so every stage
>       that saw the macro before still does.  Happy to move it to
>       primnodes.h if you would rather keep it there.

Looks Ok. parsenodes.h is fine for me.

>   2016  Simplify row pattern compilation by passing the
>         WindowClause                                   (= v50-0015)

> buildRPRPattern() took rpPattern, rpSkipTo, frameOptions, and a
> pre-built defineVariableList as separate arguments.  Pass the
> WindowClause directly instead: it carries all of these, and
> buildRPRPattern can walk wc->defineClause itself to collect the DEFINE
> variable names.  This removes the intermediate List that

I am not sure if replacing those arguments with WindowClause is a good
idea. This would simplify buildRPRPattern() but at the same time it
will make it hard to call the function from R010 implementation
because MATCH_RECOGNIZE node surely will not have WindowClause node. I
know R010 is out of scope of our work but thinking about re-usability is
courtesy for the future implementer of R010.

>   2017  Reword the row pattern variable-limit error    (= v50-0016)

OK.

>   2018  Reformat row pattern regression tests for
>         readability                                    (= v50-0017)

Ok.

>   2019  Add row pattern recognition coverage tests and tidy
>         unreachable code                               (= v50-0018)

I think we should not include following patch in our patch set. That
has nothing to do with RPR.

--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -4937,12 +4937,11 @@ WinCheckAndInitializeNullTreatment(WindowObject winobj,
 	{
 		const char *funcname = get_func_name(fcinfo->flinfo->fn_oid);
 
-		if (!funcname)
-			elog(ERROR, "could not get function name");
+		/* the executing function's name always resolves; stay safe regardless */
 		ereport(ERROR,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("function %s does not allow RESPECT/IGNORE NULLS",
-						funcname)));
+						funcname ? funcname : "?")));
 	}
 	else if (winobj->ignore_nulls == PARSER_IGNORE_NULLS)
 		winobj->ignore_nulls = IGNORE_NULLS;


>   2020  Free RPR NFA states with pfree() under
>         USE_VALGRIND                                   (= v50-0019)

Ok.

>   2021  Clarify row pattern recognition comments on "step" and
>         no_equal                                       (= v50-0020)

Ok.

>   2022  Extract the reduced-frame guard into ensure_reduced_frame()

Ok.

>   2023  Clean up row pattern recognition internals

> - Pass currentPos into nfa_match so the current row index is visible in a
>   debugger; it is the only NFA helper that otherwise lacks it.  The
>   parameter has no runtime consumer yet.

There's no instance in PostgreSQL code which uses
pg_attribute_unused() with function arguments for debugging
purpose. Can you clarify why this is necessary (except just for
debugging convenience)?

>   2024  Improve row pattern recognition comments and documentation

Ok.

>   2025  Expand row pattern recognition regression tests

Ok.

>   2026  Fix context absorption discarding matches on non-absorbable
>         branches
>       [behavior change -- wrong results]

Ok.

> You mentioned you would continue through 2016..2021; those, and 2022..2026,
> are unchanged from the 07-13 posting.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thanks for the 2015-2026 review. Just the three you flagged:

> ... it will make it hard to call the function from R010
> implementation because MATCH_RECOGNIZE node surely will not have
> WindowClause node.

Agreed -- reusability for R010 matters more. I'll keep the explicit
arguments rather than the WindowClause and revise 2016 so
buildRPRPattern() just walks defineClause for the DEFINE names.

> I think we should not include following patch in our patch set. That
> has nothing to do with RPR.

You're right, it doesn't belong with RPR. I'll remove the two
follow-up commits and drop it from 2019.

> There's no instance in PostgreSQL code which uses
> pg_attribute_unused() with function arguments for debugging purpose.

OK. I will remove the pg_attribute_unused().

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Tue, Jul 28, 2026 at 10:48 AM Tatsuo Ishii  wrote:
>
> I have created v50 RPR patches from patches (nocfbot-000*.txt and
> nocfbot-100*.txt) attached to the following email:
> https://www.postgresql.org/message-id/CAAAe_zDF-jqo=m+pcuPB1h_sG1t+nY08acjBEcfD=1KoQN4JOQ@mail.gmail.com
>

> The series of patches are to implement the row pattern recognition
> (SQL/RPR) feature. Currently the implementation is a subset of SQL/RPR
> (ISO/IEC 19075-2:2016). Namely, implementation of some features of
> R020 (WINDOW clause). R010 (MATCH_RECOGNIZE) is out of the scope of
> the patches.
>

Hi.

I had an offline discussion with Henson about this.

CREATE TABLE t1 (id int, val int);
CREATE TABLE t2 (id int);
CREATE VIEW v1 AS
SELECT FROM t1, t2 WHERE t1.id = t2.id
WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN
(A) DEFINE A AS val > 0 );

ALTER TABLE t2 add column val int;

The preceding ALTER TABLE ADD COLUMN succeeded,
After that, copying the view v1's SELECT definition and re-running the
SELECT statement will cause "ERROR:  column reference "val" is
ambiguous".

To make the preceding ALTER TABLE ADD COLUMN fail, we must recursively
find all directly and indirectly associated views that contain an RPR
query,
and that view's RPR DEFINE clause already references this new column name.
Making this bulletproof doesn't seem easy. We also need to consider
ALTER TABLE RENAME COLUMN.

The implication of the above is that pg_dump | pg_restore will fail to
restore view v1.
This seems unsolvable; also see standard 6.5: Row pattern variables
and other range variables
So I added a warning in doc/src/sgml/ref/select.sgml.

Because
ERROR:  cannot use CURRENT ROW as frame end with row pattern recognition

{ RANGE | ROWS | GROUPS } frame_start [ frame_exclusion ] [
row_pattern_common_syntax ]
is not supported. we can remove row_pattern_common_syntax from here.

The attached doc diff is based on
https://github.com/assam258-5892/postgres/commits/RPR



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Jian,

> Hi.
> 
> Please check the attached refactoring for nodeWindowAgg.c and execRPR.c.
> It's based on https://github.com/assam258-5892/postgres/commits/RPR.

Thank you for the patch. Unfortunately the patch does not apply to v50
+ current master branch (I tried against v50 + the master branch at
the point also fails). So just a quick comment.

> What is being changes:
> 1. ExecRPRFreeContext: we should also reset other field values.
> 2. nfa_update_absorption_flags() now takes the WindowAggState and walks
>    the context list itself. This is more intuitive, I think.
>    I did the similar thing for nfa_absorb_contexts.
> 3. Remove some duplicated Asserts; preceding callers have already done
> the equivalent Asserts.
> 4. Some local variable, used only once, should be just removed.
> 5. Add some elog(ERROR) to avoid circular winstate->nfaContext,
> RPRNFAContext->states.
> 6. Only ExecRPRProcessRow uses the variable frameOffset, refactor to
> make it as a local variable.
> 7. ExecRPRStartContext->nfa_context_make. nfa_context_make() used to return a
> bare struct, leaving the initial state, matchStartRow, and active-list linkage
> for the caller to fill in, that is not intuitive, it looks like a half-built
> context.  Have nfa_context_make() return a fully-formed one: allocate the
> initial state, set the start row, and append it to the list tail.
> 8. ExecRPRGetHeadContext(pos) external function can be removed.
> 9. Refactoring update_reduced_frame. Now update_reduced_frame code
> flow is more intuitive: look up or
>     create the context for pos, drive the NFA forward with
>     advance_reduced_frame_nfa(), then record the match result.
> 10. Restructure get_reduced_frame_status as a single decision tree: first
>     "no record" (start < 0), then "the record's own row" (pos == start),
>     where length alone gives the verdict (-1 unmatched, 0 empty match,
>     >= 1 frame head), then the range test for everything else.
> 
> Summary: The code flow in update_reduced_frame, advance_reduced_frame_nfa, and
> get_reduced_frame_status is now much more intuitive. Using elog(ERROR) prevents
> us from getting stuck in an infinite loop if something goes wrong.

For me, it's not clear why you add elog(ERROR), rather than Assert. If
the infinite loop should not happen when our program is correct, it
would be better to fix the problem and use Assert.

Also I noticed in nfa_update_absorption_flags() two local variables
hasAbsorbable and allAbsorbable are moved from very begging of the
function body. Why?

+nfa_update_absorption_flags(WindowAggState *winstate)
 {
-	RPRNFAState *state;
-	bool		hasAbsorbable = false;
-	bool		allAbsorbable = true;
-
-	/*
-	 * Optimization: Once hasAbsorbableState becomes false, it stays false. No
-	 * need to recalculate - both flags remain false permanently.
-	 */
-	if (!ctx->hasAbsorbableState)
-	{
-		ctx->allStatesAbsorbable = false;
+	if (!winstate->rpPattern->isAbsorbable)
 		return;
-	}
 
-	/* No states means no absorbable states */
-	if (ctx->states == NULL)
+	for (RPRNFAContext *ctx = winstate->nfaContext; ctx != NULL; ctx = ctx->next)
 	{
-		ctx->hasAbsorbableState = false;
-		ctx->allStatesAbsorbable = false;
-		return;
-	}
+		bool		hasAbsorbable = false;
+		bool		allAbsorbable = true;
 


Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo, Jian,

Attached as a wip patch is one change I would like an opinion on
before it goes into the series.  It is not in v51; it sits after that
posting on my branch.


The case

It is in the regression suite already, written down as a failure
rather than as a fix.  The commit that made get_rule_define() print
bare column names put it there, and said the ambiguity would be closed
later in the series by the commit that pins those names.  This is that
commit.

Two tables joined, a DEFINE that names a column of one of them, and
then the other side acquires a column of the same name:

  CREATE TEMP TABLE sa (id int, price int);
  CREATE TEMP TABLE sb (id int, qty int);

  CREATE TEMP VIEW sv AS
  SELECT a.id, count(*) OVER w AS cnt
  FROM sa a JOIN sb b ON a.id = b.id
  WINDOW w AS (ORDER BY a.id ROWS BETWEEN CURRENT ROW AND UNBOUNDED
               FOLLOWING PATTERN (UP+) DEFINE UP AS price > 0);

  ALTER TABLE sb ADD COLUMN price int;

pg_get_viewdef() then prints "up AS price > 0" unchanged, and that
text no longer means anything.  Feeding it back gives

  ERROR:  column reference "price" is ambiguous

The test carried that state deliberately: the comment on sv said it
is unrestorable and that is why it had to be temporary and dropped
at the end, sv3 showed the deparsed text being rejected on a fresh
CREATE VIEW, and sv4 showed the column alias list that a person would
have to write by hand for the view to survive.

The reason the deparser has nothing better to print is that the
standard gives the qualifier slot in a DEFINE expression to pattern
variables.  A qualified column is not something the parser reads back
there -- every qualified spelling is rejected -- which leaves the bare
name as the only re-parseable one, and that is why that earlier commit
sets varprefix to false for the clause.  So the bare name has to
resolve exactly as printed.  A column merged by USING is in the same
position, and that is where I took the implementation from.


What it prints now

The same query, under the names the patch's own test uses, with the
psql padding taken out:

  SELECT j1.id,
     count(*) OVER w AS cnt
    FROM rpr_pin_j1 j1
      JOIN rpr_pin_j2 j2(id, qty, price_1) ON j1.id = j2.id
   WINDOW w AS (ORDER BY j1.id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
   AFTER MATCH SKIP PAST LAST ROW
   INITIAL
   PATTERN (a+)
   DEFINE
   a AS price > 0);

The alias list sv4 had to carry by hand is what the deparser emits on
its own now: the newcomer moves aside to price_1, the DEFINE reference
keeps meaning what it meant, and the view restores.


How

set_using_names() already meets the same problem for a column merged
by USING: it too is printed bare, so it too has to keep resolving.  It
reserves the name -- no other relation of the query may be given it,
and the column itself is exempt from renaming -- and the rest of the
deparser reacts on its own.  The alias list above is that reaction,
not new code.

set_define_names() is the same reservation made for DEFINE references.
It runs once, right after set_using_names(), walks each DEFINE clause,
and pins the name of every column the clause reads.

The collision is then settled by machinery that was already there.  A
column whose name is reserved is passed over when aliases are assigned,
so it prints as written; and when the same pass reaches the relation
that acquired the colliding name, that name no longer passes the
uniqueness test, so it is treated as any other duplicate -- a digit is
appended, and a column alias list is printed for that relation so the
new name is declared where it is used.


Whether the direction taken here is the right one, whether there is a
defect in it, and whether it carries a side effect I have not seen --
I would be grateful for your opinion.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
> This is the increment on top of v51.  It is 27 patches, named
> nocfbot-XXXX-*.txt as before.

I will look into these after finishing post patch release review for
v51.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

> I will look into these after finishing post patch release review for
> v51.

Thank you.  I could use the pause myself, so please take the time you
need.

Looking back, while fixing a great many defects I have been sending
patches faster than I explained them.  That may have been a burden
for you, and I am sorry for it.

With this increment every problem we know about is resolved.  I think
what comes after it should be the finishing stage rather than another
round of fixes.

Rather than holding them for the next posting, I will write up
separately the things I am still not sure about -- whether they can be
improved, or whether they are limits of the design or of the structure
itself.

I will also carry on verifying the feature, to see whether there are
defects we have not found yet.

Beyond that, I think the maintainability side needs enough attention
to be properly finished:

- unifying the RP/RPR prefix
- separating the NFA matcher structures in preparation for R010
- polishing small usability details
- cleaning up the error messages
- cleaning up the comments and the documentation

There is no hurry on this.  Your view on which of these to take first
can wait until you post v52.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi jian,

Thank you for reading it that closely.

> IMHO, src/backend/executor/README.rpr should focus on something that's not easy
> to understand for users with some knowledge of the PostgreSQL codebase

Agreed.  A section earns its place when what it describes differs from
how the rest of the tree does the same thing.  Most of what you name
fails that.

> This process is quite common, since other nodes do something similar.

IV-6 goes.  It is already written beside the code -- above
RPRPatternElement in plannodes.h, and at the read in readfuncs.c.

> BTW, "serialization" is not the usual word here; we generally use
> "deparse" for ruleutils.

The section is gone, so the name goes with it.

> This part doesn't need mentioning; it should be fine even if omitted
> from the doc, i think.

IV-2a goes.  One sentence stays: the depth test runs on entry to each
node, so the one-byte RPRDepth cannot wrap.

> +XIII-5. Where Volatility Is Rejected
> Common routine; no need to mention in README.rpr

The first half goes; mainline moved the same check for the same
reason in a272a58b942.  What stays is why the restriction exists:
the NFA evaluates a DEFINE at most once per row and caches it, so the
number of evaluations is not something a query can rely on.

> +XIV-3. Pattern Variable Quoting
> Common routine; no need to mention in README.rpr.

This one stays.  quote_pattern_variable() quotes permute although
PERMUTE is unreserved, and the same variable prints bare in DEFINE and
quoted in PATTERN.

> +III-6. What a DEFINE Expression May Not Contain
> + III-7. Query Jumbling
> Common routine; it doesn't need mentioning in README.rpr.

III-6 goes; what the later phases lean on is already in the comment
above the pull_var_clause() call in allpaths.c.

III-7 stays.  TargetEntry.resname is query_jumble_ignore everywhere in
the tree, and RPR is the one place that has to jumble it; without that
two DEFINE clauses differing only in variable order share a
pg_stat_statements entry.

> Also some of the text seems AI-generated and less readable.

Point at the passages and I will rewrite them.

> Therefore, I think many of the sections in README.rpr can be removed.

Three of the four I am cutting were already said elsewhere.  The
README had drifted into repeating what the source carries.

Numbering moves a little.  III-7 becomes III-6, and VI-3a becomes VI-4
with the sections after it shifting up.

Attached as wip-readme-cut-duplicated-sections-rev-001.txt.  If
anything in it needs changing, could you amend it and send it back as
rev-002?

While we are settling this, how would it be to trade patches as
wip-*.txt with no numbers, and to number them 0XXX-*.txt in order once
we agree, for Tatsuo to review?

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

Following up on the second item in the "Known issues" list from the
last increment: partition tuplestore spills plus FIRST()/PREV(FIRST())
navigation in DEFINE turn quadratic once the partition spills. Here's
the reproduction and root cause.

Reproduction:

  SET work_mem='64kB';
  SELECT count(*) FROM (
    SELECT id, count(*) OVER w cnt
    FROM (SELECT g AS id, repeat('x', 50) AS pad, (g % 11) AS v
          FROM generate_series(0, 3999) g) t
    WINDOW w AS (ORDER BY id
      ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      AFTER MATCH SKIP PAST LAST ROW
      PATTERN (S A+) DEFINE S AS TRUE, A AS v >= FIRST(v))
  ) s WHERE cnt > 0;
  RESET work_mem;

work_mem=64kB (Storage: Disk), rows -> elapsed:

  2,000    0.84 s
  4,000    5.4  s
  8,000   24.3  s

4.5-6.4x per doubling. The same 8,000 rows in memory: 2.6 ms -- about
9,000x apart. Two controls rule out the obvious explanations: PREV()
in place of FIRST() on the same data stays at 3.3 ms spilled, and a
non-RPR last_value() reaching an equally distant frame under the same
work_mem costs 12.4 ms. So it isn't spilling itself, and it isn't
distance into the partition; it's specifically FIRST()-style
navigation to a fixed match-start row.

Root cause: once a partition's tuplestore spills, only one disk block
is ever resident in memory for it at a time. Re-reading a fixed row
while another position keeps advancing means walking that single
resident block back to the fixed row and out again every time, and
the cost grows with how far apart the two positions have drifted.

This isn't specific to RPR either -- I confirmed it against unpatched
core. Under work_mem=64kB, a plain `count(*), first_value(v),
last_value(v) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING)` -- first_value pinned at row 0, last_value at
the partition end -- takes temp read from 6 blocks (count(*) alone)
to 12,017 for the same 2,000 rows, and 8,000 rows goes from 1.9 ms to
24.7 ms just from adding those two fixed-but-distant functions. So
this disk I/O behavior isn't something RPR introduced -- it's a
tuplestore limitation that any query touching more than one position
at once runs into.

Short of a fix, the practical workaround today is to raise work_mem
enough that the whole partition stays in memory -- if it never
spills, none of this applies. Not a real answer for a large
partition, but worth saying plainly since it already makes the
problem disappear for anyone who hits this now.

I'm leaving this as a known limitation. Let me know if you see it
differently.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached is v53 RPR patches. The v53 is basically just a rebased
version of v52, due to recent large revert[1], except some very minor
error messages and comment fixes in gram.y.
v53 has been created against 999ce9bcd80.

[1] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=999ce9bcd80890c3d723e113bb0337c900f9f249

The series of patches are to implement the row pattern recognition
(SQL/RPR) feature. At present the implementation is a subset of
SQL/RPR (ISO/IEC 19075-2:2016). Namely, implementation of some
features of R020 (WINDOW clause). R010 (MATCH_RECOGNIZE) is out of the
scope of the patches.

Currently following features are implemented in the patches.

- PATTERN
- PATTERN regular expressions (+, *, ?)
  alternation (|), grouping () , {n}, {n,}, {n,m}, {,m}
  reluctant quantifiers (*? etc.),
  Empty pattern ("PATTERN ()") are not permitted by the standard
  Anchors (^, $) are not permitted in R020 by the standard
- DEFINE
- INITIAL
- AFTER MATCH SKIP TO PAST LAST ROW
- AFTER MATCH SKIP TO NEXT ROW
- Row pattern navigation (FIRST, LAST, PREV, NEXT and their compound forms)

Currently following features are not implemented in the patches.

- MEASURES
- Pattern variable name qualified column reference (e.g. A.price)
- SUBSET
- SEEK
- AFTER MATCH SKIP TO
- AFTER MATCH SKIP TO FIRST
- AFTER MATCH SKIP TO LAST
- PATTERN regular expression  {- and -}
- PERMUTE
- CLASSIFIER

Author: Tatsuo Ishii 
Author: Henson Choi 
Author: jian he 
Reviewed-by: Vik Fearing 
Reviewed-by: Jacob Champion 
Reviewed-by: Peter Eisentraut 
Reviewed-by: NINGWEI CHEN 
Reviewed-by: "David G. Johnston" 
Reviewed-by: Chao Li 
Reviewed-by: SungJun Jang 
Reviewed-by: Zsolt Parragi 
Reviewed-by: SeongJun Shin <

Discussion: https://postgr.es/m/20230625.210509.1276733411677577841.t-ishii%40sranhm.sra.co.jp

[1] https://www.postgresql.org/message-id/20260728.114746.1464988776774515403.ishii%40postgresql.org
[2] https://www.postgresql.org/message-id/CAAAe_zBEMn5DaqmCPZ-br51%3DorAJ3_HTOR%3DbHGmVDTggpMUYwA%40mail.gmail.com

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Jian, Tatsuo,

While auditing DEFINE clause behavior against the parse tree, I found a
case where RPR rejects a query that is valid on plain PostgreSQL, plus a
related case where a view using the same construct produces a deparse
output that doesn't round-trip. Here's how the gap arises, in order.

Trigger: a FULL JOIN's USING merged column, referenced from GROUP BY
using its expanded spelling (a COALESCE of both sides) rather than its
bare join name, while DEFINE also reads that column.

Setup:

CREATE TABLE g1 (id int primary key, cat text, val int);
CREATE TABLE g2 (id int, cat text, v2 int);
INSERT INTO g1 SELECT i, 'c'||(i%3), i*10 FROM generate_series(1,9) i;
INSERT INTO g2 SELECT i, 'c'||(i%3), i FROM generate_series(1,9) i;

Background -- why "id" is equivalent to COALESCE, without RPR:

"id" here is a reference to the join's own merged column (a join alias
Var). Unlike LEFT/RIGHT/INNER, a FULL JOIN has no side guaranteed to
survive (either can be NULL), so what that alias Var actually expands to
is the real two-column composite CoalesceExpr(g1.id, g2.id). So whether
GROUP BY spells it by the join's own name or by that expanded COALESCE,
core treats them as the same value:

SELECT id + 1 AS b, count(*) FROM g1 FULL JOIN g2 USING (id)
GROUP BY id + 1 ORDER BY 1;                              -- 9 rows
SELECT id + 1 AS b, count(*) FROM g1 FULL JOIN g2 USING (id)
GROUP BY COALESCE(g1.id, g2.id) + 1 ORDER BY 1;          -- 9 rows

The second query passes because core's grouping-validity check flattens
join alias Vars before comparing (flatten_join_alias_for_parser() when
hasJoinRTEs, then substitute_grouped_columns(), parse_agg.c). Once
SELECT's "id" is flattened, it has the same tree shape as GROUP BY's own
"COALESCE(g1.id, g2.id)".

(SELECT is bare "id" in both queries above -- this equivalence is about
GROUP BY's spelling, not something SELECT itself needs to adopt.)

Case 1 -- with DEFINE in the picture, that equivalence breaks:

First, spelling GROUP BY the same way as DEFINE ("id + 1") runs fine and
returns 9 rows:

SELECT id + 1 AS b, count(*) OVER w AS cnt
FROM g1 FULL JOIN g2 USING (id)
GROUP BY id + 1
WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
             PATTERN (A) DEFINE A AS (id + 1) > 0)
ORDER BY 1;

 b  | cnt
----+-----
  2 |   1
  3 |   1
  4 |   1
  5 |   1
  6 |   1
  7 |   1
  8 |   1
  9 |   1
 10 |   1
(9 rows)

Switching only GROUP BY to the expanded COALESCE spelling -- leaving
DEFINE's spelling as is -- reproduces it:

SELECT id + 1 AS b, count(*) OVER w AS cnt
FROM g1 FULL JOIN g2 USING (id)
GROUP BY COALESCE(g1.id, g2.id) + 1
WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
             PATTERN (A) DEFINE A AS (id + 1) > 0);

This query is currently rejected:

ERROR:  column "g1.id" must appear in the GROUP BY clause or be used in
an aggregate function

with no error position -- the reference at fault isn't anything the user
wrote, it's the resjunk entry that transformDefineClause()/
define_plant_walker() plants for what DEFINE reads.

Root cause: define_plant_walker() (parse_rpr.c) checks whether a DEFINE
subexpression is already computed by GROUP BY via plain equal() against
the collected groupExprs. The CoalesceExpr(g1.id, g2.id) from the
background above sits on the GROUP BY side, while DEFINE reads the same
column through the join's own bare Var; the two trees differ even though
they denote the same value, so the walker doesn't recognize the overlap
and plants a needless resjunk entry -- which then fails PostgreSQL's
normal grouping-validity check.

I wrote and validated a fix: flatten join alias Vars out of both sides
of the comparison (groupExprs, and the node being walked) with the
existing flatten_join_alias_for_parser(), whenever the range table has a
join RTE. Since transformDefineClause() runs before the Query is
assembled, there's no Query to hand that function yet -- a stack-local
stub carrying just p_rtable and p_hasSubLinks is enough (DEFINE can't
contain a SubLink). It passes all five RPR regression suites and
pgindent leaves it untouched.

Case 2 -- the same scenario, viewed, with that fix applied:

CREATE VIEW rpr_v2 AS
SELECT COALESCE(rpr_grp.id, rpr_sort.id) + 1 AS idp1, count(*) OVER w AS cnt
FROM rpr_grp FULL JOIN rpr_sort USING (id)
GROUP BY COALESCE(rpr_grp.id, rpr_sort.id) + 1
WINDOW w AS (
    ORDER BY COALESCE(rpr_grp.id, rpr_sort.id) + 1
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+)
    DEFINE A AS id + 1 > 0);

CREATE VIEW itself now succeeds (thanks to the fix). But pg_get_viewdef()
prints the DEFINE clause as:

DEFINE a AS (COALESCE(id, id) + 1) > 0

DEFINE forbids qualified references, so whatever prints the merged
column's two sides (l.id and r.id) has to print them the same way --
here, both as bare "id". Re-parsing that text doesn't recover the
original one-layer CoalesceExpr(l.id, r.id): it re-resolves the bare
"id" as the join's merged column again, producing a doubly-wrapped
COALESCE(id, id) around the join's own COALESCE(l.id, r.id). Re-parsing
fails on the **same** error as case 1 -- just on a tree that's now one
layer deeper.

DEFINE's ban on qualified references is presumably there because a
pattern-matching row doesn't have separate "sides" to qualify against,
and a FULL JOIN's USING column is a genuine exception: it's built from
two distinct columns. Still, the grammar doesn't need to change.

A qualified reference like "g1.id" can never appear inside DEFINE as the
user wrote it -- parse analysis rejects it outright ("range variable
qualified expression ... is not allowed in DEFINE clause"). So if
DEFINE's stored expression ever contains a qualified CoalesceExpr, it can
only have arrived via the GROUP BY substitution described above. And for
a FULL JOIN's USING column, that expanded form is exactly the join's own
merged-column definition (RangeTblEntry.joinaliasvars) -- the very
expression the join itself already records as "how this column is
computed."

So at deparse time, instead of printing what flatten_group_exprs()
expanded to as-is, I match it against every join RTE's joinaliasvars in
the range table, and when it matches exactly, fold it back into a plain
Var referencing that join column (collapse_define_join_vars_mutator(),
ruleutils.c). The fix stays inside deparse -- the grammar and DEFINE's
execution path are untouched.

pg_get_viewdef() now prints:

DEFINE a AS (id + 1) > 0

with no COALESCE, and recreating the view from that text produces an
identical pg_get_viewdef() output -- it round-trips cleanly. I've
applied case 1's fix alongside this, and all five RPR regression suites
(rpr, rpr_base, rpr_explain, rpr_integration, rpr_nfa) pass. I've added
both cases (query succeeds, view round-trips) as regression tests in
rpr_base.

Patch attached (includes the rpr_base regression tests).

I'm not sure whether applying this patch is the right call, though, versus
just fixing the error message instead. Even before RPR, I'm not confident
whether core flattening join alias Vars to recognize a mismatched GROUP BY
spelling is an intended guarantee, or just happens to work that way. If
it's the latter, DEFINE's current rejection might be the more honest
behavior, and the right fix might be turning today's positionless error
into a positioned one instead of this patch.

I'd appreciate your take.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson.

> Hi Tatsuo, Jian,
> 
> Following up on the second item in the "Known issues" list from the
> last increment: partition tuplestore spills plus FIRST()/PREV(FIRST())
> navigation in DEFINE turn quadratic once the partition spills. Here's
> the reproduction and root cause.
> 
> Reproduction:
> 
>   SET work_mem='64kB';
>   SELECT count(*) FROM (
>     SELECT id, count(*) OVER w cnt
>     FROM (SELECT g AS id, repeat('x', 50) AS pad, (g % 11) AS v
>           FROM generate_series(0, 3999) g) t
>     WINDOW w AS (ORDER BY id
>       ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>       AFTER MATCH SKIP PAST LAST ROW
>       PATTERN (S A+) DEFINE S AS TRUE, A AS v >= FIRST(v))
>   ) s WHERE cnt > 0;
>   RESET work_mem;
> 
> work_mem=64kB (Storage: Disk), rows -> elapsed:
> 
>   2,000    0.84 s
>   4,000    5.4  s
>   8,000   24.3  s
> 
> 4.5-6.4x per doubling. The same 8,000 rows in memory: 2.6 ms -- about
> 9,000x apart. Two controls rule out the obvious explanations: PREV()
> in place of FIRST() on the same data stays at 3.3 ms spilled, and a
> non-RPR last_value() reaching an equally distant frame under the same
> work_mem costs 12.4 ms. So it isn't spilling itself, and it isn't
> distance into the partition; it's specifically FIRST()-style
> navigation to a fixed match-start row.
> 
> Root cause: once a partition's tuplestore spills, only one disk block
> is ever resident in memory for it at a time. Re-reading a fixed row
> while another position keeps advancing means walking that single
> resident block back to the fixed row and out again every time, and
> the cost grows with how far apart the two positions have drifted.

Yes, I confirmed this too.  WindowAgg node uses
tuplestore_gettupleslot and it relies on buffile.c to read tuples from
disk once it switches to TSS_WRITEFILE/TSS_READFILE state. For reading
data from disk, BufFileLoadBuffer is used. It only keeps single buffer
in size of BLCKSZ.

> This isn't specific to RPR either -- I confirmed it against unpatched
> core. Under work_mem=64kB, a plain `count(*), first_value(v),
> last_value(v) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND
> UNBOUNDED FOLLOWING)` -- first_value pinned at row 0, last_value at
> the partition end -- takes temp read from 6 blocks (count(*) alone)
> to 12,017 for the same 2,000 rows, and 8,000 rows goes from 1.9 ms to
> 24.7 ms just from adding those two fixed-but-distant functions. So
> this disk I/O behavior isn't something RPR introduced -- it's a
> tuplestore limitation that any query touching more than one position
> at once runs into.
> 
> Short of a fix, the practical workaround today is to raise work_mem
> enough that the whole partition stays in memory -- if it never
> spills, none of this applies. Not a real answer for a large
> partition, but worth saying plainly since it already makes the
> problem disappear for anyone who hits this now.
> 
> I'm leaving this as a known limitation. Let me know if you see it
> differently.

+1.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Jian, Tatsuo,

While going over DEFINE clause behavior against the parse tree, I found
another case where a query that is valid on plain PostgreSQL dies with an
internal error under RPR. It takes a window whose ORDER BY and whose
DEFINE read the same composite value, with that value arriving through a
subquery.

Setup:

CREATE TABLE t (a int, b int);
INSERT INTO t SELECT g, g % 4 FROM generate_series(1, 10) g;

Reproduction:

SELECT count(*) OVER w AS c
FROM (SELECT ROW(a, b) AS x FROM t) s
WINDOW w AS (ORDER BY x
             ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
             INITIAL PATTERN (P Q+) DEFINE P AS TRUE, Q AS x IS NOT NULL);
ERROR:  variable not found in subplan target list

Control -- dropping the ORDER BY line alone makes it work:

SELECT count(*) OVER w AS c
FROM (SELECT ROW(a, b) AS x FROM t) s
WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
             INITIAL PATTERN (P Q+) DEFINE P AS TRUE, Q AS x IS NOT NULL);
 c
----
 10
  0
 ...
(10 rows)

What happens:

The planner rewrites IS NOT NULL on a ROW(...) into one test per field.
So DEFINE's

    x IS NOT NULL

effectively becomes

    a IS NOT NULL AND b IS NOT NULL

Ordinarily that is fine: the rewrite is visible early enough that a and
b, which DEFINE will end up reading, are made available in the window
input.

Here, though, x arrives through a subquery. At parse time x is just a
column of that subquery; the fact that it is ROW(a, b) only surfaces
later, when the subquery is pulled up. The rewrite happens only then --
by which point what goes into the window input has already been decided,
and a and b are not in it.

The ORDER BY copy of x, meanwhile, stays whole as ROW(a, b), because a
sort key has to be evaluated once. The split DEFINE side and the unsplit
ORDER BY side now need different things, and planning fails at the end
with the error above. Dropping the ORDER BY lets x be flattened the
ordinary way, so a and b do reach the window input and the query runs.

The fix is to not do that split for a DEFINE clause. I added
EXPRKIND_RPR_DEFINE for the defineClause preprocessing pass, and had that
path call eval_const_expressions_keep_row_nulltest() in place of
eval_const_expressions(). Unsplit, DEFINE's x keeps the same shape as the
ORDER BY side, and a and b are never looked for separately.

All RPR regression suites pass, and I added the reproduction and its
control to rpr_base. The same split reached through PARTITION BY (via a
subquery and via a view) is covered there too.

Patch attached.

My reading is that a DEFINE clause has no reason to be split in the first
place: it never feeds an index lookup, and is evaluated per row inside
the pattern matcher. I'd appreciate a check on whether that holds.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

DEFINE rejects a qualified column reference, citing ISO/IEC 19075-5
6.5, and the message reads as though the clause enforces that
absolutely:

  ERROR:  qualified expression "g1.thr" is not allowed in DEFINE clause
  HINT:  Write the name without its qualifier, or write "(x).field" to
  select a field of a composite value.

In PL/pgSQL, one pragma walks through it, and it reaches further than
I expected -- as far as the one spelling DEFINE reserves for a
pattern variable.  I went looking for a way to close that and came
away thinking we should not.  Below is what gets through, and why I
would leave it.

Setup:

CREATE TABLE t (i int, price int);
INSERT INTO t SELECT g, g*10 FROM generate_series(1, 10) g;
CREATE TYPE lim AS (thr int);

Rejected, as expected:

CREATE FUNCTION g1(thr int) RETURNS bigint AS $$
DECLARE r bigint;
BEGIN
  SELECT count(*) OVER (ORDER BY i
      ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      PATTERN (a+) DEFINE a AS price < g1.thr)
  INTO r FROM t LIMIT 1;
  RETURN r;
END$$ LANGUAGE plpgsql;

SELECT g1(55);
ERROR:  qualified expression "g1.thr" is not allowed in DEFINE clause

Add one line and the same function runs:

CREATE FUNCTION g2(thr int) RETURNS bigint AS $$
#variable_conflict use_variable
DECLARE r bigint;
BEGIN
  ... DEFINE a AS price < g2.thr ...
END$$ LANGUAGE plpgsql;

SELECT g2(55);          -- no error

A record variable's field goes through the same way, and so does a
whole-row reference:

  DECLARE r bigint; rec lim;
  ... rec.thr := 55; ...
  ... DEFINE a AS price < rec.thr ...    -- no error
  ... DEFINE a AS rec.* IS NOT NULL ...  -- no error

Then there is this one.  Give the record the name of a pattern
variable:

CREATE FUNCTION g5() RETURNS bigint AS $$
#variable_conflict use_variable
DECLARE r bigint; a lim;
BEGIN
  a.thr := 55;
  SELECT count(*) OVER (ORDER BY i
      ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
      PATTERN (a+) DEFINE a AS price < a.thr)
  INTO r FROM t LIMIT 1;
  RETURN r;
END$$ LANGUAGE plpgsql;

SELECT g5();            -- no error; a.thr reads the record

Drop the pragma from that same function and it is:

ERROR:  pattern variable qualified expression "a.thr" is not
        supported in DEFINE clause

So "a.thr" -- the one spelling DEFINE reserves for a pattern variable
-- quietly means a PL/pgSQL record instead, and nothing says so.

How it gets past:

transformColumnRef() calls p_pre_columnref_hook first and returns
with whatever it answers:

if (pstate->p_pre_columnref_hook != NULL)
{
node = pstate->p_pre_columnref_hook(pstate, cref);
if (node != NULL)
return node;
}

PL/pgSQL installs plpgsql_pre_column_ref(), which answers only under
"#variable_conflict use_variable" and returns NULL otherwise.  That
is why the default mode still rejects: there the name is resolved by
the post hook, and that result does reach DEFINE's checks.

DEFINE has three of them and all three are below that return.  Two
are after core resolution and have to be -- they ask what the
qualifier turned out to name.  The first asks nothing.  It is the
block that rejects a pattern variable qualifier and a whole-row
reference, and its own comment says why it needs no resolution:

* A whole-row reference is barred by its form alone: no qualifier
* makes one legal here, so resolving it first would only choose which
* rejection it gets.

That is the block g5 walks past.

Why not put a check above the hook:

This is the hook doing its job.  The obvious move -- lift the
form-based block above the pre hook call, since it asks nothing about
meaning -- does not hold up: "rec.*" and "a.thr" are PL/pgSQL's own
spellings, so reading the form already picks SQL's reading of text
belonging to the other scope.  A check above the hook does not avoid
the disagreement, it settles it without asking.  The switch at the
top of transformColumnRef() is no precedent for doing so: where it
bars column references outright -- a DEFAULT expression, a partition
bound -- no name resolution is on offer at all, so there is no scope
to defer to.

Nor is 6.5 being bent.  What it reserves is the qualifier slot of an
SQL name: in DEFINE that qualifier is a row pattern variable, which
is what rules out a range variable there.  A PL/pgSQL routine or
record name is neither, and the standard says nothing about it.  So
rejecting "g1.thr" is broader than 6.5 asks for -- our own choice,
and a conservative one.  It is easier to let an extension override a
rule we chose, in names it owns, than one the standard imposes.

The pattern variable case is not a new concession either.
"#variable_conflict use_variable" already outranks a table column,
and a pattern variable name is another name on the SQL side;
outranking it is the same rule applied once more.  The user wrote the
pragma to say so.

So I would document it rather than close it: the restriction is a
rule about how DEFINE resolves names, not a guarantee about how they
may be spelled.

Does that read right to you?

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo, Jian,

Two problems, and they came up together: the second is what let me
write the second reproduction of the first.

  1. A DEFINE clause can take the backend down.  Patch attached.
  2. A DEFINE can name what looks like a volatile function, when the
     same expression is in GROUP BY.  I read that as the existing
     conventions working rather than as a hole, but I would like to
     hear if anyone sees it differently.

Setup for everything below:

CREATE TABLE t (id int, val int);
INSERT INTO t VALUES (1, 10), (2, 20), (3, 15), (4, 30), (5, 5);


1. The crash

A navigation offset spelled the same as a window ORDER BY key:

SELECT id, val, count(*) OVER w AS cnt
FROM t
WINDOW w AS (
    ORDER BY (extract(hour from localtimestamp)::int * 0 + 1), id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A B+)
    DEFINE B AS val >
        PREV(val, (extract(hour from localtimestamp)::int * 0 + 1)));
server closed the connection unexpectedly

And spelled the same as a GROUP BY expression:

SELECT id, val, count(*) OVER w AS cnt
FROM t
GROUP BY GROUPING SETS ((id, val, ((random() * 0)::bigint + 1)),
                        (id,      ((random() * 0)::bigint + 1)))
WINDOW w AS (
    ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A B+)
    DEFINE B AS val > PREV(val, (random() * 0)::bigint + 1))
ORDER BY id, val;
server closed the connection unexpectedly

On a cassert + ASan build both abort with signal 6, frame for frame
the same:

    #0 CheckVarSlotCompatibility   execExprInterp.c:2431
    #1 CheckExprStillValid
    #2 ExecInterpExprStillValid    execExprInterp.c:2325
    #3 ExecEvalExprSwitchContext   executor.h:452
    #4 eval_nav_offset             nodeWindowAgg.c:4092
    #5 resolve_one_nav             nodeWindowAgg.c:4291
    #6 resolve_nav_offsets         nodeWindowAgg.c:4422
    #7 ExecWindowAgg               nodeWindowAgg.c:2473

That line reads slot->tts_tupleDescriptor.  The slot is null: UBSan
calls it a member access within a null pointer, and ASan reports the
read at 0x10, which is that member's offset.  Nothing is corrupted --
the slot simply is not set yet.

set_upper_references() hands the whole DEFINE expression to
fix_upper_expr(), which matches any subexpression against the
subplan's targetlist.  An offset spelled the same as something already
in the window input is therefore replaced with a Var(OUTER_VAR)
referencing it, and the compiled expression gets an EEOP_OUTER_VAR
step.  resolve_nav_offsets() then evaluates the offsets at the top of
ExecWindowAgg(), before the partition is opened and before
ecxt_outertuple has been pointed at anything.

The substitution does not get the value wrong -- the window input
holds the result of that same expression -- it gets the timing wrong.
An offset is resolved once per scan; a Var is a per-row read.

Two things have to line up, and it is worth saying which:

- the offset must be equal() to something in the window input, which
  is why both reproductions spell it twice.  Change one of the two and
  the query runs;
- it must not be a Const, because
  search_indexed_tlist_for_non_var() declines to match one
  ("replacing it with a Var is silly").  That is why the offset has to
  survive constant folding.

The "* 0" is not part of either condition.  It only pins the value so
the regression output does not move; without it the crash is the same.

The fix.  Only the navigated argument is read from the input, one row
at a time; the offsets are run-time constants.  set_plan_refs()
already draws that line for the frame offsets of the same node, a few
lines above the DEFINE block:

* Like Limit node limit/offset expressions, WindowAgg has
* frame offset expressions, which cannot contain subplan
* variable refs, so fix_scan_expr works for them.

So RPRNavExpr gets its own case in fix_upper_expr_mutator(): arg
recurses as before, the two offsets go to fix_scan_expr().  That is
the whole change, 22 lines in setrefs.c.

Both reproductions and a control are now in rpr_base.  With the case
taken back out they abort again, so they do hold the fix in place.
All five RPR suites pass, with no sanitizer output.


2. Why the second reproduction is accepted at all

DEFINE rejects volatile functions:

SELECT id, count(*) OVER w AS cnt
FROM t
WINDOW w AS (
    ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+) DEFINE A AS val > (random() * 0)::int);
ERROR:  DEFINE clause cannot contain volatile functions

Name the same expression in GROUP BY and the same DEFINE is accepted:

SELECT id, count(*) OVER w AS cnt
FROM t
GROUP BY id, val, ((random() * 0)::int)
WINDOW w AS (
    ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+) DEFINE A AS val > (random() * 0)::int);

The check is contain_volatile_functions() on wc->defineClause in
subquery_planner(), immediately after the clause is preprocessed.  At
that point a DEFINE expression that matched a GROUP BY expression is a
GROUP RTE Var, so there is no volatile function to find.
flatten_group_exprs() expands those Vars back into the grouping
expressions further down, after the check has run.

I think that is the convention rather than a gap, on two counts.  The
comment on the check states the first itself: volatility is examined
in the planner and not while parsing, and "a subquery the planner
discards before reaching this point is therefore not checked, which is
the same rule that lets a volatile fold away".  The planner does not
go back and re-ask about what it has rearranged.

The second is what actually runs.  In the accepted query above the
DEFINE condition reaches the executor as

    OPEXPR(>) { Var(OUTER_VAR, 2), Var(OUTER_VAR, 3) }

That is val, and the grouped column.  No volatile function is called
during matching: random() was evaluated once per row by the grouping,
and DEFINE reads the result the way it reads any other column.  If the
grouping expression is genuinely random, DEFINE sees a random value,
but it sees the one the group already has.

So I have left it alone.  If either of you reads the restriction as
covering this case, say so and I will write the extra check after the
flatten_group_exprs() loop.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

This is about the run condition block for RPR windows.

Around March we blocked two planner optimizations for RPR windows,
one after the other.

The first was yours.  I reported that "WHERE cnt > 0" returned no rows
at all because the filter had been pushed into the WindowAgg, and you
wrote back with the fix:

    /* allpaths.c, find_window_run_conditions() */
    if (wclause->defineClause != NIL)
        return false;

I took it into the series, and the comment above it is still your own
sentence from that mail: "a partition/frame is divided into multiple
reduced frames and each should be evaluated to the end of the
partition/frame".

The second came not long after:

    /* planner.c, optimize_window_clauses() */
    if (wc->defineClause != NIL)
        continue;

That one stops support functions from replacing an RPR window's frame
options with something the pattern matcher cannot use.

What a Run Condition buys, before RPR comes into it.  Take the plain
window:

  SELECT * FROM (
    SELECT i, row_number() OVER w AS rn
    FROM big
    WINDOW w AS (ORDER BY i
                 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)) s
  WHERE rn <= 3;

   WindowAgg (actual rows=3)
     Window: w AS (ORDER BY big.i ROWS UNBOUNDED PRECEDING)
     Run Condition: (row_number() OVER w <= 3)
     ->  Sort (actual rows=4)
           ->  Seq Scan on big (actual rows=200000)

The filter sits above the window, so it cannot become a scan qual.
What the planner can do instead is notice that row_number() only ever
goes up: once a row fails "rn <= 3", no later row can pass either.  So
the filter is handed to the WindowAgg as a Run Condition, and the
WindowAgg stops the moment it fails -- it stops pulling from below as
well, which is why the Sort emitted four rows instead of 200,000.  The
Seq Scan still read the whole table, because the Sort had to; what is
saved is everything the WindowAgg would have gone on to do.  With a
pattern to match, that is where the cost is.

Two things had to be asked of row_number() to get that plan, and both
are in it.  "Run Condition" is there because the function answered
SupportRequestWFuncMonotonic with "increasing".  And the frame reads
"ROWS UNBOUNDED PRECEDING" although the query said "BETWEEN CURRENT
ROW AND UNBOUNDED FOLLOWING", because the function also answered
SupportRequestOptimizeWindowClause: the frame does not matter to it,
so the planner replaced it with a cheaper one.

That second rewrite is exactly what we blocked for RPR windows, and
for good reason -- an RPR window cannot have its frame taken away.

Two shapes run into the block, and they want different things.

The first is where nothing on the window reads the reduced frame at
all:

  SELECT * FROM (
    SELECT i, row_number() OVER w AS rn
    FROM big
    WINDOW w AS (ORDER BY i
                 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                 PATTERN (a b+) DEFINE b AS v > PREV(v))) s
  WHERE rn <= 3;

The matcher expands 216,200 NFA states over the whole table and no one
reads the result, since row_number() is counting positions in the
partition.  The same query with PATTERN and DEFINE removed is the
plan at the top of this mail: a Run Condition, and actual rows=3.

This one would not need find_window_run_conditions() touched at all.
If the planner could see that no window function on the clause reads
the reduced frame, it could drop the RPR part of the window, and the
existing run condition rules would then apply on their own, because
defineClause is gone.

The second is where one function reads the reduced frame and another
does not:

  SELECT * FROM (
    SELECT i, count(*) OVER w AS cnt, row_number() OVER w AS rn
    FROM big
    WINDOW w AS (ORDER BY i
                 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                 PATTERN (a b+) DEFINE b AS v > PREV(v))) s
  WHERE rn <= 3;

count() is real RPR output, so the matching does have to happen -- but
only for three rows.  The plan expands the same 216,200 states, with
"Rows Removed by Filter: 199997" above it.  This is the one that would
need the guard itself narrowed.

I am not claiming the second one is safe.  The run condition puts the
WindowAgg into pass-through, and what changes under RPR is how far the
node still has to reach: not to the cut-off row, but out to wherever
the match that crossed it closes.

As things stand, neither shape is giving a wrong answer.  They just
take longer than they need to.  That is an optimization we have not
done rather than a defect, and the current series is about defects, so
I would rather push the fix down the list.

What do you think?

If we do come back to it, the two start from different places.  The
first starts with classifying window functions -- which of them are
affected by RPR at all.  If none of the ones on a clause is, that
window can quietly have its RPR turned off, and the run condition
code needs no change at all.  The second starts further back, with
going through the whole run condition matrix again under RPR: which
monotonic direction and which operators still hold once the frame is
a reduced one.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> As things stand, neither shape is giving a wrong answer.  They just
> take longer than they need to.  That is an optimization we have not
> done rather than a defect, and the current series is about defects, so
> I would rather push the fix down the list.
> 
> What do you think?

I agree. IMO stabilizing our code is the first priority.  We can
tackle the optimization later (probably after the first version of
RPR gets committed).

Also I think we should add this to the RPR restriction list to be
fair for those who are willing to evaluate/review RPR patches.

- Pushing down a run condition is disabled if DEFINE clause exists.

- Replacing frame options by support functions is disabled if DEFINE
  clause exists.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo, Jian,

> The fix is to not do that split for a DEFINE clause. I added
> EXPRKIND_RPR_DEFINE for the defineClause preprocessing pass, and had that
> path call eval_const_expressions_keep_row_nulltest() in place of
> eval_const_expressions().

I am withdrawing that. EXPRKIND_RPR_DEFINE and
eval_const_expressions_keep_row_nulltest() are both gone, and
clauses.c and optimizer.h are files this series does not touch again.

> My reading is that a DEFINE clause has no reason to be split in the first
> place: it never feeds an index lookup, and is evaluated per row inside
> the pattern matcher. I'd appreciate a check on whether that holds.

That was the wrong question. It is not whether a DEFINE clause may be
split, but who reads the result after it has been.

I had been looking at the target list from the DEFINE side. The
picture was that DEFINE puts what it reads into the target list, so I
wanted the shape settled by the time it went in, and turning off
constant folding was how I settled it. Turn it around and look from
the target list side, and DEFINE is one of several things that live
outside the target list and are evaluated by an upper planner node.
The core already has one of those. It is HAVING.

havingQual is boolean too, lives outside the target list too, and is
evaluated by an upper planner node, the Agg. The core solves it with
two sites and no more:

  build_base_rel_tlists()    -- mark the columns needed so they reach
                                the top of the join tree (initsplan.c)
  make_group_input_target()  -- ask for them again in that node's own
                                input target (planner.c)

And havingQual is never put in the target list at all.

DEFINE now goes through the same two sites. The DEFINE block sits
right below the HAVING block in build_base_rel_tlists(), and
make_window_input_target() asks for what the clause reads. The latter
runs after every rewrite, so what it reads is the shape the clause
will be executed with: split if it was split, whole if it stayed
whole. The reason to prevent the split is gone.

There is one rule HAVING does not need. The walk stops at an
expression the input target already computes whole; asking for the
Vars underneath would ask the grouping step for columns it cannot
produce. make_group_input_target() builds the input of the grouping
step and has no such problem, while the window input target sits above
it.

That left the parse-time planting of the Vars a DEFINE reads with
nothing to do, so it is gone. Planting was there to keep
remove_unused_subquery_outputs() and remove_useless_outer_joins() from
dropping the column, and build_base_rel_tlists() does the same thing
and runs before both. Parse analysis no longer rewrites the user's
target list at all.

The visible difference is in the rpr_integration expected output:

  -   Output: id, count(*) OVER w, val
  +   Output: id, count(*) OVER w

A column only a DEFINE clause reads used to ride on the WindowAgg's
own output and be carried to the top of the plan. It now stays on the
input. Five places lost it, and no result row changed.

Two tests are added. One is a DEFINE clause reading a compound GROUP
BY expression, which is the only place the stop rule above does any
work and was not covered. The other is a window function nested inside
a subquery output expression the upper query drops: the pass that
settles which windows are still live only looks at top-level nodes, so
it misses that one and a dead window's column is retained. That is an
over-retention rather than a wrong answer, and making the pass exact
is left to its own commit; the test records what happens today.

ExecInitWindowAgg() gets one Assert. The varId-to-list-position
invariant that buildRPRPattern() establishes and the executor consumes
had nothing checking it, and a reorder would evaluate one variable's
search condition for another -- a wrong answer with no crash and no
assert to show for it.

Patch attached.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
- Replacing frame options by support functions is disabled if DEFINE
  clause exists.

This part is about the optimization that reverses the direction of the frame option being disabled.
This is because this reversal of direction is a modification into a form that the standard does not allow. 

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Currently the keyword RUNNING with row pattern navigation in the
DEFINE clause is not supported.  (As FINAL can only be used in
MEASURES clause and we do not support MEASURES, we do not need to
worry about FINAL for now.)

So question is whether we should support RUNNING keyword.

Even if RUNNING keyword support is lacking, current patch effectively
supports RUNNING semantics with row pattern navigation (according to
the standard, the default is RUNNING). So supporting RUNNING keyword
gives users only minor benefit, for example in migration from other
DBMSs that use the RUNNING keyword in the target system.  In my
opinion, the effort to add support for the RUNNING keyword is not
worth the trouble. Thoughts?

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> So question is whether we should support RUNNING keyword.
> ...
> In my opinion, the effort to add support for the RUNNING keyword
> is not worth the trouble. Thoughts?

I agree, for two reasons.

First, in R020 the two keywords never change the result. In the
standard, FINAL is not permitted in DEFINE and RUNNING is the
default there; in a window's MEASURES there is no real difference
between running and final semantics. They only mark how much of the
set of rows mapped to a pattern variable is seen, and the places
they are written -- aggregates, FIRST/LAST over a pattern variable,
MEASURES -- are the three features the patch does not have. What
remains, RUNNING FIRST(x) and RUNNING LAST(x), is the same as the
expression without the keyword.

Second, it looks simple -- accept RUNNING/FINAL as unreserved
keywords in front of a function call and sort them out in parse
analysis -- but it actually carries a complication: the grammar of
DEFINE expressions would have to be built by copying the whole
existing expression grammar. The standard, too, uses the general
scalar expression syntax in DEFINE and writes the keyword before
the operator, as in RUNNING COUNT (A.*), so the prefix belongs in
the general expression grammar. But a RUNNING prefix in the general
a_expr, which DEFINE uses today, conflicts with an alias written
without AS: "SELECT running total FROM t" and
"SELECT running total(x) ..." cannot be told apart until the "("
arrives. Nothing follows a DEFINE expression as an alias, so a
grammar of DEFINE's own would not have this conflict, but it means
copying a_expr and everything below it. Even supporting only
RUNNING before FIRST/LAST, the forms usable today, through a lexer
lookahead as NULLS_LA does, would stop some existing queries from
working, such as "SELECT running first FROM t".

Pattern variables and the range variables of the FROM clause have
mutually exclusive scopes, so a qualifier in DEFINE has to be
resolved against a namespace that the ordinary column reference
resolution knows nothing about. The problems that came up while
handling the errors for those qualifiers made me wonder whether
DEFINE expressions should get a grammar of their own, copied from
the existing one. Because of the maintenance burden, I tried to
keep to a single grammar as far as possible. Unless the scope of
RPR grows, I think this part is best frozen as it is.

The migration benefit you mention would be small in practice, too.
Queries that use RUNNING in other DBMSs mostly use it because they
need those three features:

  MEASURES RUNNING LAST(price) AS last_price      -- MEASURES
  DEFINE B AS price > RUNNING LAST(A.price)       -- qualifier
  DEFINE B AS price > RUNNING AVG(price)          -- aggregate

So even if we supported RUNNING now, most of those queries would
still fail on the missing features.

In the end, both in meaning and in grammar, RUNNING/FINAL belong
with those three features. Every way to take the prefix today
either breaks existing queries or copies the expression grammar,
and neither is a choice to make for a keyword that changes nothing.
So when MEASURES, qualifiers, and aggregates in DEFINE are
developed, I think they need to be dealt with in depth, together
with the grammar of DEFINE expressions, as one of the architectural
considerations.

One direction worth weighing then is a grammar of DEFINE's own with
its own keyword categories, where RUNNING and FINAL are reserved
inside DEFINE but stay unreserved everywhere else. That removes the
conflicts by construction and breaks no existing query, though it
still costs the copy of the expression grammar, a split of the
keyword categories, and context-aware quoting in deparse, since a
column named "running" read in DEFINE would have to be printed
quoted.

That is too heavy to take on now. It changes the core grammar, the
keyword categories, and deparse, all of which are shared far beyond
RPR, so it would need agreement from a broad part of the community,
not just from this thread.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
From: Henson Choi 
Subject: Re: Row pattern recognition
Date: Sun, 27 Sep 2026 07:31:45 +0900
Message-ID: 

> Hi Tatsuo,
> 
>> So question is whether we should support RUNNING keyword.
>> ...
>> In my opinion, the effort to add support for the RUNNING keyword
>> is not worth the trouble. Thoughts?
> 
> I agree, for two reasons.
> 
> First, in R020 the two keywords never change the result. In the
> standard, FINAL is not permitted in DEFINE and RUNNING is the
> default there; in a window's MEASURES there is no real difference
> between running and final semantics. They only mark how much of the

You are right. In R020, RUNNING and FINAL for MEASURES are
semantically same.

In addition to ISO/IEC 19075, ISO/IEC 9075-2 stats:

"4.21.1 Running vs. final semantics
:
:
As for measures, if row pattern matching is performed in a window, or
if ONE ROW PER MATCH is specified, then expression evaluation is
performed in the last row of the row pattern match, so that running
and final semantics are the same."

BTW, I plan to add a note to "9.23. Window Functions" in the
PostgreSQL documentation, something like below to explicitly stat
that the patch does not support the RUNNING keyword. Comments?

-----------------------------------------------------------------
Note

The SQL standard allows to put a keyword RUNNING in front of row
pattern navigation functions FIRST and LAST.  This is not implemented
in PostgreSQL. However, the expected behavior is the same with or
without the RUNNING keyword according to the standard.
-----------------------------------------------------------------

> set of rows mapped to a pattern variable is seen, and the places
> they are written -- aggregates, FIRST/LAST over a pattern variable,
> MEASURES -- are the three features the patch does not have. What
> remains, RUNNING FIRST(x) and RUNNING LAST(x), is the same as the
> expression without the keyword.
> 
> Second, it looks simple -- accept RUNNING/FINAL as unreserved
> keywords in front of a function call and sort them out in parse
> analysis -- but it actually carries a complication: the grammar of
> DEFINE expressions would have to be built by copying the whole
> existing expression grammar. The standard, too, uses the general
> scalar expression syntax in DEFINE and writes the keyword before
> the operator, as in RUNNING COUNT (A.*), so the prefix belongs in
> the general expression grammar. But a RUNNING prefix in the general
> a_expr, which DEFINE uses today, conflicts with an alias written
> without AS: "SELECT running total FROM t" and
> "SELECT running total(x) ..." cannot be told apart until the "("
> arrives. Nothing follows a DEFINE expression as an alias, so a
> grammar of DEFINE's own would not have this conflict, but it means
> copying a_expr and everything below it. Even supporting only
> RUNNING before FIRST/LAST, the forms usable today, through a lexer
> lookahead as NULLS_LA does, would stop some existing queries from
> working, such as "SELECT running first FROM t".

Ouch.

> Pattern variables and the range variables of the FROM clause have
> mutually exclusive scopes, so a qualifier in DEFINE has to be
> resolved against a namespace that the ordinary column reference
> resolution knows nothing about. The problems that came up while
> handling the errors for those qualifiers made me wonder whether
> DEFINE expressions should get a grammar of their own, copied from
> the existing one. Because of the maintenance burden, I tried to
> keep to a single grammar as far as possible. Unless the scope of
> RPR grows, I think this part is best frozen as it is.

Agreed.

> The migration benefit you mention would be small in practice, too.
> Queries that use RUNNING in other DBMSs mostly use it because they
> need those three features:
> 
>   MEASURES RUNNING LAST(price) AS last_price      -- MEASURES
>   DEFINE B AS price > RUNNING LAST(A.price)       -- qualifier
>   DEFINE B AS price > RUNNING AVG(price)          -- aggregate
> 
> So even if we supported RUNNING now, most of those queries would
> still fail on the missing features.

Right.

> In the end, both in meaning and in grammar, RUNNING/FINAL belong
> with those three features. Every way to take the prefix today
> either breaks existing queries or copies the expression grammar,
> and neither is a choice to make for a keyword that changes nothing.
> So when MEASURES, qualifiers, and aggregates in DEFINE are
> developed, I think they need to be dealt with in depth, together
> with the grammar of DEFINE expressions, as one of the architectural
> considerations.
> 
> One direction worth weighing then is a grammar of DEFINE's own with
> its own keyword categories, where RUNNING and FINAL are reserved
> inside DEFINE but stay unreserved everywhere else. That removes the
> conflicts by construction and breaks no existing query, though it
> still costs the copy of the expression grammar, a split of the
> keyword categories, and context-aware quoting in deparse, since a
> column named "running" read in DEFINE would have to be printed
> quoted.
> 
> That is too heavy to take on now. It changes the core grammar, the
> keyword categories, and deparse, all of which are shared far beyond
> RPR, so it would need agreement from a broad part of the community,
> not just from this thread.

Yes, if someone want to continue the discussion, please create a new
thread.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> BTW, I plan to add a note to "9.23. Window Functions" in the
> PostgreSQL documentation, something like below to explicitly stat
> that the patch does not support the RUNNING keyword. Comments?

Looks good to me.  Just one sentence to suggest:

> The SQL standard allows to put a keyword RUNNING in front of row
> pattern navigation functions FIRST and LAST.

"allows to put" reads awkwardly in English.  How about matching the
first sentence of the nth_value note just above it ("The SQL standard
defines a FROM FIRST or FROM LAST option for nth_value."):

  The SQL standard defines a RUNNING prefix for the row pattern
  navigation functions FIRST and LAST.

Then the two notes also continue the same way, with "This is not
implemented in PostgreSQL."  The rest reads fine as is.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi jian,

This started as an offlist thread, but I'm posting this reply to
pgsql-hackers instead.  The reasoning behind the test count and
structure seems useful to whoever else is reviewing this patch, so I'd
rather have it on the CF record than in a private exchange between the
two of us.  Hope that's alright.

First, the concern and the convention.  Tests for existing features are
what one file per feature accumulated over decades (join.sql has 252
commits since 1999, window.sql 48 since 2008).  Recent large features
kept their cross-feature tests inside a feature-centered file too: MERGE
in merge.sql (1,841 lines), SQL/JSON in sqljson*.sql (about 2,400 lines
together).  RPR follows that same convention and is organized around
RPR, but because this volume arrived all at once it looks unusually
large in line count, and the tests that cross into other features are
concentrated on the RPR side.

So, separate from the answers below, I have three options in mind for
dealing with the file size without reducing the number of tests.  (1)
Move rpr_nfa.sql and rpr_explain.sql, which test the NFA engine itself,
into a separate test module.  (2) Rather than keeping the RPR tests that
cross into existing features (GROUP BY, subquery/CTE, JOIN, set
operations and so on) on the RPR side, rewrite them against the tables
and queries of each feature's existing tests (groupingsets.sql,
subselect.sql, join.sql, ...) and distribute them there -- a direction
that differs from the convention above, so it needs discussion.  (3)
Split a large file like rpr_base.sql into topical files along the
sections its own header already lists.  For example,
serialization/deserialization (1,697 lines, 23% of the file), navigation
functions (670), quantifiers and PATTERN syntax (about 800), pattern
optimization and absorption (about 930), error cases (about 520) and the
DEFINE clause (335) are each self-contained topics that can be moved as
they are, without rewriting, and moving serialization/deserialization
alone would bring rpr_base.sql down to about 5,650 lines.  All three
keep what the tests verify and only move it, though (2) comes with the
work of rewriting the queries against the existing tables.  I'll ask for
your view at the end.

> "argument of row pattern navigation operation must include at least
> one column reference"
> This error message in function define_walker appeared in rpr_base.out, rpr.out.
>
> How about we consolidate all these error cases into a single place?
>
> "argument of row pattern navigation operation must include at least
> one column reference"
> It appeared 11 times, which I would say is excessive.
> Is 11 times really necessary?

In the source there are only two call sites for this errmsg, in
parse_rpr.c: one for the case where the argument is a plain nav, one
that runs only after a compound nav like PREV/NEXT(FIRST/LAST()) has
been flattened into a single node.  They are mutually exclusive
branches, not the same code.  So there is nothing to consolidate there.

The 11 is how many regression cases hit those two sites, not how many
places raise the error.  They split cleanly into a combination:

  simple:   constant, expression, with-offset              (3)
  compound: constant, expression,
            inner offset, outer offset, both offsets       (5)
  literal:  string, NULL, prepared-statement parameter     (3)

3 + 5 + 3 = 11, and each cell is a different shape -- removing any one
leaves that cell uncovered.  I would rather keep all eleven than trade
coverage for a lower count.

> ```
> --
> -- Parser/planner tests: rpr_base.sql
> -- NFA engine tests: rpr_nfa.sql
> -- EXPLAIN statistics tests: rpr_explain.sql
> --
> ```
> I don't think the above comments are necessary.

That's the index at the top of rpr.sql, pointing at rpr_base.sql,
rpr_nfa.sql and rpr_explain.sql.  I'd rather keep it -- now that the
suite is split five ways, it tells a reader at a glance which file
covers what.

> https://github.com/assam258-5892/postgres/blob/ec3797180cb1ec6df48bc6633929b33b7f2aae4d/src/test/regress/sql/rpr_base.sql
> says "7373 lines".
> We should try to find ways to reduce the size of the tests.
> "7373 lines". is unmaintainable.

Same position as before, and here is the reasoning behind it: from the
code alone, two tests cover both call sites in parse_rpr.c.  But this
suite is not written against the code, it is written against the
DEFINE/PREV/NEXT interface as a black box, so a later rewrite of
parse_rpr.c is still caught if it changes what the interface accepts.
That is the same reason the matrix has eleven cells and not two.

Once that is the standard, every other RPR test is built the same way.
Cutting this one spot without changing the standard everywhere would
just leave it inconsistent with the rest of the suite -- I don't see a
narrower standard that still catches what these eleven catch, so I am
not planning to shrink this one.

The size does not come from an unusual number of tests, though: the
query count is in line with the existing features, and the size comes
from query length (see below).  Counting by the existing-feature areas
rpr_base.sql's own header lists under "planner layer", against each
feature's own dedicated test count (the RPR column counts queries using
OVER in rpr_base.sql, the dedicated column counts all queries in those
files, and the cross cases in rpr_integration.sql and rpr.sql are left
out):

  existing feature area        RPR cross-tests   dedicated tests (file)
  subquery/CTE                      5             495  (subselect.sql 260 + with.sql 235)
  JOIN                             11             605  (join.sql)
  complex expressions               5              31  (case.sql)
  set operations (UNION etc.)       4             156  (union.sql)
  sorting and grouping              52            265  (select_distinct 43+limit 40+
                                                        select_having 11+groupingsets 171)

No area exceeds that feature's own dedicated test count; subquery/CTE
and JOIN sit at 1-2%, set operations at 3%.  Complex expressions (16%)
and sorting and grouping (about 20%) are higher -- the first because its
baseline, case.sql, is only 31 queries, the second not by accident:
parseCheckAggregates() was originally built to substitute grouped
columns to point at the RTE_GROUP RTE in exactly two places, the target
list and the HAVING clause.  DEFINE is the only part of a WindowClause
whose expression tree can reference columns (PARTITION BY and ORDER BY
only point at target-list entries, and frame offsets must be Var-free),
so that substitution had to be taught a third place.  HAVING already
gets tested against every grouping shape because of this same
substitution (see groupingsets.sql's HAVING section); DEFINE needs the
same kind of checking for the same reason.  This area isn't large
because its scope grew -- it's the same requirement HAVING already
carries, applied to the new place that needed it.

One more point, about format rather than count: squeezing the WINDOW
clause onto one or two lines to save lines is its own kind of loss. RPR
adds PATTERN, DEFINE and INITIAL/SEEK on top of the ordinary PARTITION
BY / ORDER BY / frame a window clause already carries, so one keyword
per line is what keeps each sub-clause readable at a glance. Running
them together would make the file shorter and each query harder to read
at the same time -- shrinking for readability's sake while making it
less readable is not a trade I'd take.

What that trade-off actually looks like exists in insert.sql too:

  create or replace function donothingbrtrig_func() returns trigger as $$begin raise notice 'b: %', new.b; return NULL; end$$ language plpgsql;

A whole trigger function body squeezed onto one line.  The file total
goes down, but that one line isn't something I'd call readable -- not a
trade I want to import into the RPR tests.

It isn't just that clauses get added -- the frame and ORDER BY are
effectively required here too.  The frame is enforced by the parser:
rpr_frame_is_supported() rejects the default frame and requires ROWS
BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING (or ...offset FOLLOWING)
spelled out.  ORDER BY isn't checked by the parser, but PATTERN is a
sequential, time-series analysis -- leaving it out would put row order
at the mercy of whatever the plan happens to produce that day, not at
anything the query actually asked for.

The FROM side gets long for the same kind of reason.  The hardest
deparse bugs in this patch mostly came from DEFINE clashing with a
JOIN's USING list, and rpr_res_fa_v is the example:

  CREATE VIEW rpr_res_fa_v AS
  SELECT count(*) OVER w AS cnt
  FROM (rpr_res_fa FULL JOIN rpr_res_fb USING (x)),
       ((rpr_res_fc JOIN rpr_res_fa t4 USING (x)) AS j(x, x_1)
        JOIN rpr_res_fb t5 USING (x))
  WINDOW w AS (ORDER BY j.x
               ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
               PATTERN (A+)
               DEFINE A AS x_1 > 0);

DEFINE reads x_1, the name the alias list j(x, x_1) gives to
rpr_res_fc.y.  The anonymous FULL JOIN already takes the plain name x,
so when deparsing the second USING the deparser has to skip both x and
x_1 and picks x_2.  Running that nesting onto one line would make it
impossible to tell where each name came from -- the line breaks aren't
decoration, they're what lets a reader follow it.

In numbers (queries with an actual WINDOW clause (OVER) / total lines /
lines per query; select.sql has no query using OVER at all, so it's
counted by plain SELECT statements instead):

  select.sql          :  50 /  273 /  5.5
  window.sql          : 383 / 2311 /  6.0
  rpr.sql             : 152 / 2944 / 19.4
  rpr_base.sql        : 584 / 7345 / 12.6
  rpr_nfa.sql         : 213 / 5607 / 26.3
  rpr_explain.sql     : 321 / 4012 / 12.5
  rpr_integration.sql :  84 / 1568 / 18.7

select.sql (5.5) and window.sql (6.0) are the lowest.  All five RPR
files come in at 12.5 or higher -- even the lowest of them,
rpr_explain.sql (12.5), is more than double window.sql.  Once a frame,
ORDER BY, PATTERN and DEFINE all have to go into the same query, an RPR
query that uses windowing runs structurally longer than an ordinary one
that does.

As for run time, I measured on a dev machine (8 cores, assert-enabled
build) with test_setup run first (serial case repeated 5 times, full
suite 3 times):

  five RPR tests, serial       about  1.0 s  (about 6.6% of the 15.2 s wall time)
  five RPR tests, parallel     about  0.5 s  (about 3.3%)
  full regression suite (244)  about 15.2 s  (about 57 s summed over tests)

By lines, RPR is 14.2% of all regression-test SQL (150,946 lines); by
summed test time it is about 2%.  So the burden of this volume is in
reading and maintaining it, not in run time, and that is the angle from
which I'm asking about the options above.

To sum up:

- Against window.sql, rpr_base.sql has 1.5x the queries (584/383) and
  rpr.sql actually has fewer, 0.4x (152/383).  The files are still
  bigger because each query is longer by structure (frame, ORDER BY,
  PATTERN, DEFINE, or a USING merge) -- lines per query go from 6.0 in
  window.sql to 12.6 in rpr_base.sql (2.1x) and 19.4 in rpr.sql (3.2x),
  and that length multiple combined with the count multiple gives the
  total-line multiples (3.2x and 1.3x).  It is length, not count, that
  got multiplied.  Longer queries are a separate question from cutting
  the number of tests to compensate, and I'm not comfortable accepting
  that trade.

- Had the same number of tests been written at window.sql's density (6.0
  lines per query), the five RPR files would total about 8,100 lines
  (rpr_base.sql 3,504, rpr.sql 912, rpr_nfa.sql 1,278, rpr_explain.sql
  1,926, rpr_integration.sql 504) instead of the actual 21,476.  Holding
  the test count fixed, the files come out 2.1x bigger for rpr_base.sql
  and rpr_explain.sql, 3.1x for rpr_integration.sql, 3.2x for rpr.sql
  and 4.4x for rpr_nfa.sql, 2.6x overall -- and all of that multiple
  comes from the length of a single query.

- rpr_nfa.sql and rpr_explain.sql are their own group -- they look at
  the NFA engine itself (the matching itself, and the EXPLAIN output
  that reports on it), not surrounding features.  Within that pair, only
  rpr_nfa.sql (26.3) stands out on density, not rpr_explain.sql (12.5),
  but what they target is the same.  PostgreSQL already has a precedent
  for this: its own regex engine splits the same way, into ordinary
  feature tests (155 lines) and a dedicated module just for the engine's
  own correctness (1786 lines).  Verifying one internal state machine
  properly taking that much space on its own is an established practice
  in this codebase, not something RPR invented.  Option (1) above is
  simply following that precedent.

- rpr_integration.sql is the one place that checks how RPR interacts
  with the planner: section A has one guard test per planner
  optimization, section B has integration scenarios.  Some cases (e.g.
  B11 and the A5 join-removal ones) were added for bugs found in review.
  Its size, 84 queries and 1568 lines, is a cost worth paying.

Finally, a question: of the three options above -- moving the two
NFA-related files into a separate module, distributing the cross-feature
tests into each feature's existing tests, and splitting rpr_base.sql
into topical files -- which one, or which combination, do you think is
realistic?  If you see another direction, I'd like to hear that too.
Either way, I'd want what the tests verify kept as it is.

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
On Wed, Sep 30, 2026 at 2:13 PM Henson Choi  wrote:
>
> Finally, a question: of the three options above -- moving the two
> NFA-related files into a separate module, distributing the cross-feature
> tests into each feature's existing tests, and splitting rpr_base.sql
> into topical files -- which one, or which combination, do you think is
> realistic?  If you see another direction, I'd like to hear that too.
> Either way, I'd want what the tests verify kept as it is.
>

-- ============================================================
-- Subquery and CTE Tests
-- ============================================================
-- Tests RPR with subqueries and CTEs

-- RPR in Subquery (FROM clause)

SELECT * FROM (
    SELECT id, category, val,
           COUNT(*) OVER w as cnt
    FROM rpr_planner
    WINDOW w AS (
        ORDER BY id
        ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
        PATTERN (A+)
        DEFINE A AS val > 0
    )
) sub
WHERE cnt > 5
ORDER BY id;
---------------------------------------------
The above tests from src/test/regress/sql/rpr_base.sql
The RPR window runs inside the subquery and produces rows; the outer
query then filters and sorts them, which is ordinary subquery behavior
that has nothing to do with RPR.
Whether the rows come from a subquery, a CTE, a JOIN, or a plain table
is irrelevant to RPR, so the above test adds no coverage beyond what
the plain-table cases already give.

Moving tests from one file to another does not solve the problem.
We should first try harder to remove unnecessary test queries.
Consolidating all the error cases into one place would also be a good idea.

In src/test/regress/sql/rpr_base.sql, I saw comments like
```
-- Complex Multi-Level Nesting
-- Pattern: (((A B) | C)+ D)+

```
I don't think the above comments are really any helpful.
The pattern is the same as the SELECT query below.
If the test query changes, the above comments will become stale.
It also occupied an unnecessary blank line.



--
jian
https://www.enterprisedb.com/


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi jian,

Thanks for the concrete examples. Replies inline.

> The RPR window runs inside the subquery and produces rows; the outer
> query then filters and sorts them, which is ordinary subquery
> behavior that has nothing to do with RPR. Whether the rows come from
> a subquery, a CTE, a JOIN, or a plain table is irrelevant to RPR, so
> the above test adds no coverage beyond what the plain-table cases
> already give.

This is where I would like to explain how I think about these tests.
They are black-box tests. They do not ask whether the RPR code and the
subquery code are related; they ask whether the answer is right when
the two meet. The Subquery and CTE section of rpr_base.sql is the
mirror image of the tests where RPR sits on top of a subquery: here
the window is inside the subquery or CTE and the outer query consumes
its rows. The two directions may build different plans.

And several of the defects this patch fixed turned up around the
planner. For example, subquery pull-up could replace a navigation
argument by a constant, so PREV() no longer meant the target row.
Cases like that were not visible from inside RPR.

I should also be honest about where I stand. I have worked with many
other database systems, but my experience with the PostgreSQL planner
is thin. So for everything outside RPR itself, the interplay with the
planner and the deparser, I lean heavily on writing tests first (TDD),
and I ask for your understanding on that. It is like walking over snow
and probing ahead with a pole, because what lies under the snow may be
a cliff edge or a crevasse rather than ground. The tests reach a
little past the boundary of RPR on purpose, so that nothing slips
through. I lay the test results out as a matrix of cases against
variants, showing what works and what does not, and use it to find
what needs fixing and to decide which way to fix it. So the tests are
the most important clues I have. A request to cut the number of tests
feels to me like being asked to put down the probe I depend on before
I move ahead.

> Moving tests from one file to another does not solve the problem. We
> should first try harder to remove unnecessary test queries.
> Consolidating all the error cases into one place would also be a
> good idea.

Moving tests only moves the size around, but I do not agree that
removing has to come first. To avoid missing defects, I draw the scope
of verification a little wide at the boundary of RPR, and I weigh the
risk of missing a defect by misjudging that boundary slightly more
than the size of the tests. On gathering the error cases: the
top-level classification of these files is by test category (the
parser layer and the planner layer are listed at the top of
rpr_base.sql), and the error cases are already categories of their own
there, Error Cases Tests and Error Limit Tests. The other error cases
stay in the category they test, such as quantifiers or navigation
functions, next to the valid cases they contrast with. Across the RPR
test files, about 40% of the ERROR outputs are in those dedicated
sections and the rest are inside the categories. Some of the same
errors are tested in more than one of these places, so I went through
the overlap. By code coverage, many of them are redundant: removing
the 70 candidates one by one loses no line or branch coverage. As
black-box tests, though, they differ in the input they give (operator,
quantifier form, clause, arity, boundary value), and only one of the
70 was the same input under a different table name. A single duplicate
test does not seem worth a change by itself.

> In src/test/regress/sql/rpr_base.sql, I saw comments like
> ```
> -- Complex Multi-Level Nesting
> -- Pattern: (((A B) | C)+ D)+
> ```
> I don't think the above comments are really any helpful. The pattern
> is the same as the SELECT query below. If the test query changes,
> the above comments will become stale. It also occupied an
> unnecessary blank line.

As for the comments, I am preparing a local branch in which the
comments and the documentation are translated into my native language.
After I post the next patch series, I will go through the comments one
by one with that branch while I review the whole patch, and this kind
of comment will be looked at then.

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Thu, Sep 17, 2026 at 3:32 PM Tatsuo Ishii  wrote:
>
> Attached is v53 RPR patches. The v53 is basically just a rebased
> version of v52, due to recent large revert[1], except some very minor
> error messages and comment fixes in gram.y.
> v53 has been created against 999ce9bcd80.
>
> [1] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=999ce9bcd80890c3d723e113bb0337c900f9f249
>

Hi.

define_walker is kind of ugly, so i did the attached refactoring,
which make navigation expression check stay within ParseRPRNavCall.
Overall I feel it is more neat than define_walker.
It's based on v53.



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

Thank you for the v54-0001 refactoring.

On 2026-10-01 09:30 UTC, jian he wrote:
> define_walker is kind of ugly, so i did the attached refactoring,
> which make navigation expression check stay within ParseRPRNavCall.
> Overall I feel it is more neat than define_walker.
> It's based on v53.

I cannot take it in right now.  The code I am working on changes the
same parts of parse_rpr.c and parse_func.c, and the patch does not
apply on top of it.

I did read the diff, including the expected output changes, and
looked at the error positions (the caret).  Some get better and some
get worse.  These are taken from the expected output in your patch.

Better: the caret moves to where the actual problem is.  For a
nested navigation it moves from the outer call to the nested one.
For "must include at least one column reference" it moves from the
start of the call to the argument that lacks a column reference.

  Before:
    ERROR:  PREV and NEXT cannot contain PREV or NEXT
    LINE 7:     DEFINE A AS price > PREV(PREV(price))
                                    ^
  After:
    ERROR:  invalid row pattern navigation function form: PREV(PREV())
    LINE 7:     DEFINE A AS price > PREV(PREV(price))
                                         ^

  Before:
    ERROR:  PREV and NEXT cannot contain PREV or NEXT
    LINE 7:     DEFINE A AS price > NEXT(price * PREV(price))
                                    ^
  After:
    ERROR:  invalid row pattern navigation function form: NEXT(PREV())
    LINE 7:     DEFINE A AS price > NEXT(price * PREV(price))
                                                 ^

  Before:
    ERROR:  argument of row pattern navigation operation must include at least one column reference
    LINE 7:     DEFINE A AS PREV(1) > 0
                            ^
  After:
    ERROR:  argument of row pattern navigation operation must include at least one column reference
    LINE 7:     DEFINE A AS PREV(1) > 0
                                 ^

The caret stays on the outer call, but the message gets better.  The
new message names PREV, so the user knows which call to fix.  I think
this is a good direction for the error messages.

  Before:
    ERROR:  row pattern navigation operation must be a direct argument of the outer navigation
    LINE 6:     DEFINE A AS PREV(v + FIRST(v)) > 0
                            ^
  After:
    ERROR:  nested row pattern navigation operation must be the direct argument of PREV
    LINE 6:     DEFINE A AS PREV(v + FIRST(v)) > 0
                            ^

Worse: when a navigation call is inside an offset.  A navigation call
in the offset position is already the mistake; what is inside it is
secondary.  Before, the caret was on that call.  Now the inner call is
checked first, so the error is about its argument and the caret is on
that argument.  The message no longer says that the offset cannot
contain a navigation operation; when the inner call has no column
reference it asks for one, and adding one only leads to the run-time
constant error.

  Before:
    ERROR:  row pattern navigation offset cannot contain a row pattern navigation operation
    LINE 6:     DEFINE A AS PREV(val, FIRST(1)) > 0)
                                      ^
  After:
    ERROR:  argument of row pattern navigation operation must include at least one column reference
    LINE 6:     DEFINE A AS PREV(val, FIRST(1)) > 0)
                                            ^

  Before:
    ERROR:  row pattern navigation offset cannot contain a row pattern navigation operation
    LINE 4:     PATTERN (A+) DEFINE A AS PREV(v, NEXT(1, 0)) > 0);
                                                 ^
  After:
    ERROR:  argument of row pattern navigation operation must include at least one column reference
    LINE 4:     PATTERN (A+) DEFINE A AS PREV(v, NEXT(1, 0)) > 0);
                                                      ^

I think small improvements like the position of the caret are
good contributions, and they are needed now.  We look at the code
from different angles: you from its structure, I from what users
see.  I have found it hard to pay attention to small things like
this myself.  I think improvements of this kind may be a form of
contribution that many contributors can easily make from here on.

Once the next patch series is posted, could you rebase this on top
of it?  If it makes the error positions more helpful for users, that
would be an improvement.  I will check then that it does not
introduce any defects.

As a rule, the review and testing have to start over from the
beginning whenever the code changes.
The round in progress is quite expensive.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi hackers,

This is an increment on top of v53.  It is ten patches, named
nocfbot-XXXX-*.txt as before.

The fixed branch for this posting, which I will not rewrite, is:

  https://github.com/assam258-5892/postgres/tree/RPR-20260930

The base is v53 as Tatsuo posted it on 09-17 on top of master
999ce9bcd80, moved onto master 5bd2e236e21 of 09-28.  The ten patches
apply on it in number order, with nothing in between.

The 09-07 increment and the wip patches I attached to later mails are
included selectively: what is still needed is in these ten, some of it
in a different form.

The main change is structural.  DEFINE is now handled the way HAVING
is: the planner, not the parser, works out which columns it reads.  On
the deparse side I stopped working around the existing column-naming
machinery and fixed it at query level.  That replaced a series of
scattered fixes with a few changes at the root.

Each entry says what v53 gets wrong and what the patch does about it,
and the tag in brackets says what kind of problem it is.  The commit
messages have the details.  Five of the ten fix defects in today's
v53: wrong answers or false errors, input that the standard rejects,
and a view that cannot be dumped and restored.  With them in, our
tests find no wrong answer or false error left in this feature, apart
from the three defects the fourth mail reports and the window-name
deparse case under "Known issues"; what else remains is quality, and
is under "Known issues" at the end.

Those five are:

  - 0001 a window over grouped input fails with an internal error when
    a grouping set nulls a column its DEFINE reads
  - 0002 a DEFINE clause accepts a whole-row reference, ROW(t.*), or a
    name qualified by a function name or block label, which the
    standard reserves for a pattern variable
  - 0003 some patterns match different rows than the standard and Perl
    give
  - 0004 a DEFINE over subquery pull-up fails at plan time, or reads a
    constant where a navigation argument means the target row
  - 0005 a view holding a DEFINE clause can fail to dump and restore
    once another column carries a name that DEFINE reads

0001 and 0004 change planner code that other queries share, though
only row pattern queries behave differently there.  0005 changes the
deparser, and its output also changes for some queries without row
pattern recognition.  The commit messages say what and why.  For a
reader who knows those areas but not RPR, I will send the longer
reasoning as two separate mails, one on the planner changes and one on
the deparse changes, each as its own thread.  A third mail, as a reply
in this thread, explains the structure change in 0003, which changes
how a group is compiled.  What this mail says about these changes
stays as it is.  A fourth mail reports three defects found in these
ten after they were cut; this mail does not describe them.

Numbering

Numbers are reissued whenever the base version changes.  This one is
cut against v53 and does not continue the numbers of the 09-07 mail;
there the same number points at a different commit.

Application order is number order.

On authorship: all ten carry me as author, and five of them -- 0001,
0002, 0003, 0004 and 0009 -- also carry Jian as co-author, because
patches he wrote are merged into them.  I rebased and verified them
and wrote the messages.

What changed in the code

Removed because it was not needed:

  - the parser planting DEFINE's Vars into the target list
  - the RPR exception in remove_unused_subquery_outputs() (back to
    upstream)
  - rprPatternEqual() and rprPatternChildrenEqual(), which did what
    equal() does
  - four separate frame checks, now one (EXCLUDE is reported on its
    own)
  - two copies of the navigation name list, now one
  - ExecRPRGetHeadContext(), a small helper folded into its one caller
  - an unreachable overflow check, and a goto

Added, the key pieces:

  - add_define_inputs_walker(), called from
    make_window_input_target(), asks for what DEFINE reads, as for
    havingQual
  - mark_define_columns() and collapse_define_join_vars() in the
    deparser
  - ParseState.p_rpr_define and rpr_frame_is_supported()
  - nfa_mark_group_entered() and nfa_prune_skipped_contexts()
  - BEGIN.jump names the group's own END

Refactored:

  - RPRPattern copy, out and read share one contract
  - existing helpers replace hand-written code
  - the two RPRNavExpr_walker() functions are renamed
  - a few functions and macros are renamed or introduced

Where the 09-07 patches went:

  - 2008 (grouping) is in 0001
  - 2004, 2005, 2010, 2011, 2017, 2018 (name rules, diagnostics,
    cleanups) are in 0002
  - 2003 (frame report) is in 0002, rewritten
  - 2013-2016, 2019 (executor cleanups) are in 0003
  - 2002 (DEFINE context) is in 0003, done with ExecQual() instead
  - 2012 (navigation argument) is in 0004
  - 2009 (unreferenced window) is in 0004, in a different form: the
    RPR exception in remove_unused_subquery_outputs() is removed
    instead
  - 2001 (pinned column names) is in 0005
  - 2006 (RPRPattern contract) is in 0006
  - 2021, 2022 (comments, the two costs) are in 0007
  - 2007, 2020 (documentation) are in 0009
  - 9001 (EXCLUDE TIES test) is in 0008
  - 9002 (column names of relation RTEs outside FROM) is in 0005

  0001 Let a row pattern DEFINE clause take part in grouping
       [wrong result]
       v53 left DEFINE out of the GROUP BY substitution, so a grouping
       set that nulls a column made setrefs.c fail with "wrong
       varnullingrels".  DEFINE now goes through the same steps as the
       target list.  Also fixes PREV(k / 0) failing at plan time when
       k is a USING column of mixed types.

  0002 Tighten parse analysis of DEFINE clauses and row pattern
       syntax  [wrong result]
       Whole-row references, ROW(t.*), names qualified by a function
       name or block label, and the FILTER or ORDER BY of an aggregate
       got around the qualifier rule of ISO/IEC 19075-5 6.5.  They
       are rejected now, and a few SQLSTATEs change.

  0003 Fix DEFINE memory leak and empty-iteration looping in RPR
       executor  [wrong result]
       An empty first iteration kept a derivation the standard
       excludes, so some patterns matched different rows than Perl;
       query results change for such patterns.  Also fixes the DEFINE
       memory leak (94MB down to 18MB on 300k rows) and adds an
       interrupt check.

  0004 Move DEFINE input tracking from parse analysis to the planner
       [wrong result]
       Parse analysis planted DEFINE's Vars in the target list, and
       planning could fail with "variable not found in subplan target
       list".  DEFINE is now handled the way havingQual is.  Also
       stops subquery pull-up from folding a navigation argument, and
       fixes a crash on a navigation offset.

  0005 Make a deparsed DEFINE clause re-parse as written
       [wrong result]
       A view holding a DEFINE clause could not be dumped and restored
       once another column carried the same name.  The names DEFINE
       reads are now settled first and reserved.  Also changes
       pg_get_viewdef() output for some queries without row pattern
       recognition; the commit message lists them.

  0006 Tighten RPRPattern node I/O and reuse existing helpers in RPR
       code  [latent]
       A malformed node string now fails with an internal error
       instead of being misread.  Existing helpers replace
       hand-written code.

  0007 Record two RPR costs and correct comments the code no longer
       matches  [comments, asserts]
       Comments, plus five checks the executor cannot reach, now
       Asserts: two elog(ERROR) calls and three early returns.
       Records two known costs as XXX: the state comparison in
       nfa_states_equal(), and nav_winobj's shared read pointer.

  0008 Tidy and extend the row pattern recognition regression tests
       [tests]
       Tests only: rpr_ prefixes, fewer redundant ORDER BY, new tests,
       and fixes for tests that tested less than their comments said.

  0009 Bring the row pattern recognition documentation up to date
       [docs]
       Documentation only: SGML and README.rpr checked against the
       code.

  0010 Reorder README.rpr by processing order  [docs]
       Moves the chapters into the order a query goes through the
       code: parsing, DEFINE planning, PATTERN compilation, the
       executor, the worked example, deparse and EXPLAIN, and the
       summary last.  Text moves; section numbers and cross references
       follow, and the Chapter IV title is reworded.

Open questions

  Tatsuo, four items need your decision on the direction or on whether
  to go ahead:

  - State explosion.  To keep the preference order from giving wrong
    answers, the cycle guard marks only a nullable END, since marking
    anything else loses legitimate matches.  That bounds cycles but not
    cost: alternations whose branches are all nullable enumerate paths
    rather than states, as an XXX in nfa_advance_state() records.  A
    runtime bound, on the work in one expansion or on the states held,
    is the first answer; rejecting quantified subpatterns that can
    match empty, as Oracle does with ORA-62513, is the alternative.
  - Names.  You accepted the RPR* policy for the typedefs on 07-14 [1]
    and asked whether it reaches struct members too.  I would say yes:
    rpSkipTo becomes rprSkipTo along with the types, in one mechanical
    patch after the defects are settled.
  - WindowAggState.  On 05-31 [2] you agreed with Jian's idea [3] of
    putting the row pattern members behind one struct, for the size
    and for the move to R010, but not for v48.  On 07-14 [1] you asked
    when to do it, saying it has to be done to make the code
    committable.  I would group the members before the commit, since
    that only changes structure, and leave the R010 redesign for
    after.  The struct needs a name other than RPRContext, since
    rprContext is already the ExprContext DEFINE runs in.
  - sql_features.txt still says R020 is NO although the patch
    implements it.  It has to change before the commit.  Whether it
    says YES with a note or NO, partially supported is your call.

  None of these is urgent, and none is a structural problem that puts
  the quality of the patch at risk.  Each is a matter of direction or
  timing that can wait until the code has settled, and I will follow
  whichever way you decide.

Testing

  All of this ran on the tip of RPR-20260930.

  - make check-world passes on two setups:
      Linux, gcc, --enable-coverage --with-llvm
      macOS, clang, --enable-coverage --with-llvm
    On both the node-support GUCs debug_copy_parse_plan_trees,
    debug_write_read_parse_plan_trees and
    debug_raw_expression_coverage_test were on, and so was
    debug_parallel_query = regress.
  - A third build, macOS with clang and AddressSanitizer + UBSan, ran
    166 suites, and neither sanitizer reports anything.
  - Coverage of the modified lines, by gcov:
      whole feature, against master   Linux  98.6%  (2,795 / 2,836)
                                      macOS  98.3%  (3,145 / 3,201)
    The figure in my mail of 06-23 was 98.4% (2,635 / 2,679).  The
    two compilers count executable lines differently, so compare
    within a platform.
  - The generated node-support functions for the RPR and window nodes
    (copy, equal, out, read and query jumble) all ran.  Both the JIT
    and the interpreted path of the navigation steps ran; JIT is
    reached through the two tests in rpr.sql that turn it on.

Known issues

  The interplay with the planner, the deparser and the rest of the
  surrounding code was found test by test, and I believe it is in good
  shape now, but I cannot be sure of it.  So I will spend the next
  several months studying the related planner code, and I will keep
  quiet on this thread meanwhile, apart from replying to reviews and
  posting the fixes for the three defects in the fourth mail.

  One item waits for another CF entry.  CF 7056 (quoting of unreserved
  keywords used as window names, such as "rows") has to be committed
  first.  Row pattern recognition then adds pattern, after, initial
  and seek to the list that patch builds in appendWindowRefName(),
  with a round-trip test for each.  Until then a window named
  "pattern" that another window inherits deparses to text that does
  not re-parse.

Separate submissions

  Already in these ten.  I will submit them upstream as one patch, in
  its own thread and CF entry, and send another patch that reconciles
  the series with the submitted one:

    - deparse: column alias lists for TABLEFUNC RTEs, column names of
      relation RTEs outside FROM, and column alias lists of function
      RTEs (all from 0005).  The TABLEFUNC part
      reproduces without row pattern recognition on released
      branches (JSON_TABLE on 17 and later, XMLTABLE since 10); it
      comes from the printaliases = false exception that
      arrived with XMLTABLE (fcec6caafa2, 2017)

  Not in these ten, each to be posted in its own thread:

    - grouping sets do not null a grouping expression that has no Var
      (reproduces without row pattern recognition)
    - make_placeholder_expr() is not memoized across calls, so the
      same join alias expression can get two PlaceHolderVars (I expect
      it to reproduce without row pattern recognition, but I have not
      yet built a query that shows it)
    - Retry open() when it fails with EINTR
    - Put two typedefs.list entries back in sorted order

[1] https://postgr.es/m/20260714.212047.525303007784395461.ishii@postgresql.org
[2] https://postgr.es/m/20260531.091119.2213733238436650503.ishii@postgresql.org
[3] https://postgr.es/m/CACJufxGX17thWuEOq1tM5xbRHz2HXm1asooZC3GV25MYGmYqLQ@mail.gmail.com

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
On Tue, Oct 6, 2026 at 11:25 AM Henson Choi  wrote:
>
> Thank you for the v54-0001 refactoring.
>
> Worse: when a navigation call is inside an offset.  A navigation call
> in the offset position is already the mistake; what is inside it is
> secondary.  Before, the caret was on that call.  Now the inner call is
> checked first, so the error is about its argument and the caret is on
> that argument.  The message no longer says that the offset cannot
> contain a navigation operation; when the inner call has no column
> reference it asks for one, and adding one only leads to the run-time
> constant error.
>
>   Before:
>     ERROR:  row pattern navigation offset cannot contain a row pattern navigation operation
>     LINE 6:     DEFINE A AS PREV(val, FIRST(1)) > 0)
>                                       ^
>   After:
>     ERROR:  argument of row pattern navigation operation must include at least one column reference
>     LINE 6:     DEFINE A AS PREV(val, FIRST(1)) > 0)
>                                             ^

There is a different way to intrepert this.
If we first process FIRST, the error message saying
ERROR:  argument of row pattern navigation operation must include at
least one column reference

If we first process PREV, then
ERROR:  row pattern navigation offset cannot contain a row pattern
navigation operation

My patch uses a bottom-up approach.
DEFINE A AS PREV(val, FIRST(1)) > 0)
first process expression (FIRST(1))

Different ways of processing the navigation yield different error
messages, and therefore the error position also differs.
So i think this should be ok.


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

This follows the ten-patch increment on top of v53 that I posted for
row pattern recognition (RPR, SQL:2016 R020, CF 4460) in the thread
"Row pattern recognition" [1].  Patches 0001 and 0004 change planner
code in places that are not specific to RPR, so this mail explains
them for readers who know the planner but not RPR.

What the planner needs to know about RPR is small.  A window clause
can say

  WINDOW w AS (ORDER BY id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+ B)
    DEFINE A AS price > PREV(price), B AS price < PREV(price))

DEFINE gives each pattern variable a boolean expression over rows, and
PREV, NEXT, FIRST and LAST evaluate their argument at another row.
The expressions are held in WindowClause.defineClause.  The WindowAgg
evaluates them, but they are not in the target list and not quals of
any scan, so the code that works out which columns the plan has to
provide never asks for what they read.

The patches are the nocfbot-0001 and nocfbot-0004 files attached to
[1].  The same commits are in
https://github.com/assam258-5892/postgres/tree/RPR-20260930, on top of
v53.  Nothing here is meant to change what a query without a DEFINE
clause does, and neither patch changes an existing expected output
outside the rpr_base and rpr_integration tests.

What the patches do

The first five changes come from one idea.  A DEFINE clause is an
expression that does not sit where the planner normally looks, the
target list and the quals, so the planner handles the query without
knowing it is there.  The main line is to treat DEFINE as one more
consumer of the query's columns, the way HAVING is.  HAVING does two
things that matter here.  It makes the node below supply what it
reads, even though the target list does not mention it.  And an
expression that GROUP BY already computed is read as the computed
value, not computed again from the base columns.  A DEFINE clause is
evaluated by the WindowAgg on top of its input in the same way, so it
needs both.  Three things follow:

  - The planner has to find out which columns DEFINE reads and carry
    them down to the window's input.  Where the input already computes
    an expression, such as a GROUP BY expression, DEFINE reads that
    computed value instead of computing it again (1, 2).

  - Every step in which the planner rewrites the query's expressions
    has to treat DEFINE the same way, or its copy drifts out of step
    with the rest.  Grouping is the main case: an expression used in
    GROUP BY is first replaced by its computed value and later
    restored to the expression, and DEFINE has to go through both (2).
    Subquery pull-up and join alias expansion are rewrites of the same
    kind, with one exception: a navigation argument is evaluated at
    another row, so it has to stay an expression over the row and must
    not be folded into a constant (3).

  - A window that will not run should be dropped like any plain
    window, and its DEFINE must not stand in the way of other
    optimizations (4, 5).

The last item (6) is a separate crash fix that does not follow from
this line.

1. DEFINE is handled like havingQual (0004).

Before, parse analysis added the Vars a DEFINE clause reads to the
target list as resjunk entries.  That rewrote the user's target list,
and it was not enough.  When a composite value arrives through a
pulled-up subquery, eval_const_expressions() splits an IS [NOT] NULL
test on it into one test per field.  If the window's PARTITION BY or
ORDER BY holds the same value, its sortgroupref keeps the input target
from flattening it, so those fields never reach the WindowAgg input
and planning fails with "variable not found in subplan target list".

Now the patch asks for the columns in two places.  The planner records
for each column how far up the join tree it is needed (attr_needed),
and a join relation puts on its output only what is still needed above
it.  A DEFINE clause is in neither the target list nor any qual, so
nothing asked for what it reads, and a join could drop it on the way.
build_base_rel_tlists() now marks those columns as needed at the top
of the join tree, so they climb through the joins like the target
list's own columns.  The upper planner, however, builds the target of
each node explicitly instead of propagating attr_needed, so each
target above the join tree has to ask for them again, and for the
window's input that is the next step.

make_window_input_target() adds to the window input target whatever
the preprocessed clause reads that the target does not already offer.
The walk stops at an expression the target computes whole, since
setrefs.c resolves the DEFINE copy against that column.  Each DEFINE
condition is preprocessed as a qual, as havingQual is, and the
parser's Var planting is gone.  In EXPLAIN VERBOSE a column that only
a DEFINE clause reads now appears on the WindowAgg's input but no
longer on its output.

2. Grouped input (0001, and a part of 0004).

parseCheckAggregates() rewrote only the target list and HAVING, so
over grouped input a DEFINE clause kept plain relation Vars while the
target list copies of the same columns became Vars of the RTE_GROUP
RTE.  Plain GROUP BY hides this, but a grouping set that nulls a
column the DEFINE clause reads makes the two copies disagree in
varnullingrels, and setrefs.c fails:

  CREATE TABLE t (category text, val int);
  SELECT category, count(*) OVER w FROM t GROUP BY ROLLUP(category)
  WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
               PATTERN (A) DEFINE A AS category IS NOT NULL);
  ERROR:  wrong varnullingrels (b) (expected (b 2)) for Var 1/1

ISO/IEC 19075-5 6.4 makes the row pattern input table the result of
FROM, WHERE, GROUP BY and HAVING, so this shape has to work.
defineClause now goes through the same steps as the target list:
substitute_grouped_columns() in parseCheckAggregates() (after
flatten_join_alias_for_parser() when there are joins, so that the
merged column of a FULL JOIN USING matches its grouping item), and
flatten_group_exprs() in subquery_planner() and in get_query_def().
GROUPING() cannot appear in DEFINE, so finalize_grouping_exprs() is
not needed.  0004 also lets a DEFINE clause spell a GROUP BY
expression: under GROUP BY val + 1, one repeating val + 1 used to
offer the bare val to the grouping check and was rejected.

3. A navigation argument stays row-dependent (0001 and 0004).

The argument of PREV, NEXT, FIRST and LAST is evaluated at the row the
navigation lands on.  Pulling up a one-row VALUES list, a subquery or
a function RTE that folded to a constant replaced the column with that
value, and constant folding then raised at plan time an error that
execution would not reach on the row the navigation misses.  The
example is PREV(v / 0) with no previous row.

replace_rte_variables_mutator() now flags the argument of an
RPRNavExpr, and pullup_replace_vars_callback() treats a replacement
made there as needing a PlaceHolderVar, so a replacement that does not
read the row is wrapped instead of folded in; whether one that reads
the row is wrapped is left to the usual pull-up rules (a plain Var or
a strict expression over Vars is not) (0004).  A USING column whose
merged value is an expression, as in a FULL JOIN or when one side has
to be converted to the common type, resolves to the join's alias Var,
and flatten_join_alias_vars_mutator() could copy a pulled-up Const
into the argument the same way, so it flags the argument too.  It is
stricter, though: in planner calls it wraps any replacement other than
a plain Var or PlaceHolderVar, including a strict expression over Vars
such as the implicit cast (0001).

4. remove_unused_subquery_outputs() is back to its upstream form
(0004).

It refused to replace an unused window function output whose window
had a DEFINE clause, and kept every bare-Var output that a DEFINE
clause read.  Neither is needed.  select_active_windows() makes no
such exception, and with the tracking in 1 a DEFINE clause reads a
relation column of its own query level, never the subquery's output
entry.  A row pattern window in a subquery that nothing reads is now
removed with its WindowAgg, like a plain window.

5. The DEFINE clause of a window that will not run is emptied (0004).

grouping_planner() empties defineClause of every window clause that
will not run, right after select_active_windows().  For a subquery
that is when the subquery is planned, before its own join removal.
The reason is that 1 marks what a dead clause reads as needed, which
makes join removal keep the join, and query_tree_walker() visits
defineClause while join removal requires that no Var of a removed
relation remain anywhere in the tree.  An outer join to a relation
that only such a clause reads can now be removed.  Only defineClause
is cleared: winref indexes windowClause, so the clause itself must
stay, and rpPattern is what marks it as a row pattern window, which
find_window_run_conditions() and optimize_window_clauses() rely on.  A
comment in query_tree_walker() records the rule.

6. A crash on a navigation offset (0004).

A navigation offset spelled like an expression the window input
already carries, such as a window ORDER BY key, crashed.
fix_upper_expr() replaced the offset with a reference to that input
column, and the executor, which resolves offsets once per scan before
any input row is read, dereferenced a null slot.
fix_upper_expr_mutator() now handles RPRNavExpr itself and fixes the
offsets with fix_scan_expr(), as set_plan_refs() does for the frame
offsets of the WindowAgg.

What I would like to hear

I found these places test by test, so I cannot rule out cases the
tests do not reach.  I would value a look from anyone who knows these
functions, and three questions in particular:

  - Is flagging the argument in the two mutators,
    replace_rte_variables_mutator() and
    flatten_join_alias_vars_mutator(), and wrapping a replacement in a
    PlaceHolderVar the right way to keep a navigation argument
    row-dependent, or is there a better place or a mechanism I should
    use instead?

  - Is it acceptable to empty defineClause in grouping_planner() so
    that join removal sees no stale Var, rather than teaching
    query_tree_walker() or join removal to skip it?

  - Is there a case of an expression that the walk over what DEFINE
    reads handles wrongly when DEFINE is treated like havingQual?  I
    know of one already: a column that only DEFINE reads, below
    GROUP BY, is not asked for by the grouping input.

[1] https://postgr.es/m/CAAAe_zDsYugq506ou49PU+Ok+4Umn5n59Qs5wYofvKyfEpvZJQ@mail.gmail.com

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

This follows the ten-patch increment on top of v53 that I posted for
row pattern recognition (RPR, SQL:2016 R020, CF 4460) in the thread
"Row pattern recognition" [1].  Patch 0005 changes ruleutils.c.  Most
of it is about RPR, but three of its changes look like upstream
patches that have nothing to do with RPR: they also alter
pg_get_viewdef() and pg_get_ruledef() output for queries without RPR.
I will submit them upstream as a separate patch.  RPR may need further
changes on top of it, so I will send another patch that reconciles
0005 with the submitted one.  This mail explains 0005, those three
included, for readers who know the deparser but not RPR.

What the deparser needs to know about RPR is small.  A window clause
can say

  WINDOW w AS (ORDER BY id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+ B)
    DEFINE A AS price > PREV(price), B AS price < PREV(price))

A DEFINE clause can name a column only without a qualifier, since the
qualifier slot belongs to the pattern variable.  So get_rule_define()
prints it with varprefix off, and the bare name has to resolve exactly
as printed when a view or rule is re-parsed.

The patch is the nocfbot-0005 file attached to [1].  The same commit
is in https://github.com/assam258-5892/postgres/tree/RPR-20260930, on
top of v53.

The problems

Four things can break the trip from a view to its text and back.  The
first needs no RPR.  The other three concern the bare name a DEFINE
clause is printed with, which has to mean the same column when the
text is read back.  I ran the examples below on v53 and on the patched
series.  The COALESCE one was also run with 0004 applied and 0005 not.

  - A column alias list written on a TABLEFUNC (JSON_TABLE, XMLTABLE)
    is dropped.  This is the simplest failure, and it reproduces on
    released branches, with JSON_TABLE on 17 and later and with
    XMLTABLE since 10:

  CREATE VIEW v AS
  SELECT p, q
  FROM JSON_TABLE(jsonb '[1,2]', '$[*]'
         COLUMNS (a int PATH '$', b int PATH '$')) AS jt(p, q);

v53 prints the select list as p, q and the JSON_TABLE as jt, with no
alias list, and re-parsing that text fails with "column "p" does not
exist".  The reason is in the section below.

  - A column added or renamed later.  Once another column of the same
    query level came to carry the name, the pg_get_viewdef() output
    failed to re-parse, and the view could not be dumped and restored.
    ALTER TABLE ... ADD COLUMN or RENAME COLUMN can do it after the
    view is made.  For example:

  CREATE TABLE t1 (id int, price int);
  CREATE TABLE t2 (id int);
  CREATE VIEW v AS
  SELECT t1.id, count(*) OVER w AS c
  FROM t1 JOIN t2 ON t2.id = t1.id
  WINDOW w AS (ORDER BY t1.id
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+) DEFINE A AS price > 10);
  ALTER TABLE t2 ADD COLUMN price int;

v53 prints JOIN t2 ON t2.id = t1.id and the DEFINE clause as price >
10, and re-parsing that text fails with "column reference "price" is
ambiguous".

  - A column merged by USING.  The merged column keeps its natural
    name, and that name can collide with one a DEFINE clause reads,
    for example after a RENAME COLUMN.  For example:

  CREATE TABLE a (j int, p int);
  CREATE TABLE b (j int, q int);
  CREATE TABLE c (r int, s int);
  CREATE VIEW v AS
  SELECT count(*) OVER w AS cnt
  FROM a JOIN b USING (j) CROSS JOIN c
  WINDOW w AS (ORDER BY c.s
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    INITIAL PATTERN (X Y+) DEFINE X AS true, Y AS s > PREV(s));
  ALTER TABLE c RENAME COLUMN s TO j;

v53 prints JOIN b USING (j) and the DEFINE clause as y AS j > PREV(j).
The merged j and the renamed c.j now collide, and re-parsing fails
with "column reference "j" is ambiguous".

  - A column merged by FULL JOIN USING in a grouped query.  In the
    query below, the id in DEFINE is the merged column of l FULL JOIN
    r USING (id).  To match it with the GROUP BY item, the parser
    expands that column into the expression that defines it,
    COALESCE(l.id, r.id), so id + 1 becomes COALESCE(l.id, r.id) + 1
    and is replaced by a reference to the grouping column.  When the
    view is deparsed, that reference is expanded back into the
    grouping expression.  A DEFINE clause prints Vars without a
    qualifier, so both arms of the COALESCE come out as id.  For
    example:

  CREATE TABLE l (id int PRIMARY KEY, val int);
  CREATE TABLE r (id int, val int);
  CREATE VIEW v AS
  SELECT COALESCE(l.id, r.id) + 1 AS idp1, count(*) OVER w AS cnt
  FROM l FULL JOIN r USING (id)
  GROUP BY COALESCE(l.id, r.id) + 1
  WINDOW w AS (ORDER BY COALESCE(l.id, r.id) + 1
    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
    PATTERN (A+) DEFINE A AS id + 1 > 0);

Deparsed with 0004 applied and 0005 not, the DEFINE clause comes out
as a AS (COALESCE(id, id) + 1) > 0, which loses which input each arm
came from, and re-parsing fails with "column "l.id" must appear in the
GROUP BY clause or be used in an aggregate function".  With 0005 it is
printed as a AS (id + 1) > 0 and re-parses.  (v53 itself rejects the
original query; 0004 is what accepts it.)

Why the TABLEFUNC exception matters

The deparser has never printed a column alias list for a TABLEFUNC RTE
(JSON_TABLE, XMLTABLE).  The exception, printaliases = false, came
with XMLTABLE (fcec6caafa2, 2017), on the ground that the clause names
the columns itself, and JSON_TABLE reuses the RTE kind.  The names are
still changed like for any other RTE: a user-written alias wins, and
USING pushes names down.  The new names are used where the columns are
referenced, but the list that introduces them is not printed.

That stops being true once the user writes an alias list.  Create a
view with one on the JSON_TABLE:

  CREATE VIEW v AS
  SELECT p, q FROM JSON_TABLE( ... ) AS jt(p, q);

pg_get_viewdef('v') on v53 returns

  SELECT p, q
  FROM JSON_TABLE( ... ) jt;

The list is gone, so the text uses p and q, which nothing introduces.
The point is that the names the deparser settles on are not printed,
neither the ones it picks to avoid a collision nor the user's own.

What the patch does

The problems have three causes, and the patch answers each.  The
deparser chose column names without knowing which ones a DEFINE clause
reads, so the patch settles those names first and protects them.  Some
RTEs could not print a rename at all, so the patch lets an RTE that
needs a rename print it as a column alias list.  And in a grouped
query a merged column came back as the expression that defines it,
whose arms print alike without a qualifier, so the patch folds
expanded merge expressions back into the merged column.  In more
detail:

  - mark_define_columns() runs ahead of set_using_names().  It settles
    the names of the columns a DEFINE clause reads before any other
    column is named, and reserves them: those columns are exempt from
    renaming, and no other column can take their names.  This is what
    keeps the added-column problem away.

  - The reserved names are kept in using_names for the whole query
    level, so no other column can take them.  A colliding column is
    renamed to name_N and its RTE prints a column alias list.  In the
    added-column example that is the t2(id, price_1) the patch prints:

  JOIN t2 t2(id, price_1) ON t2.id = t1.id
  ...
  DEFINE
  a AS price > 10

In the USING example the merged column steps aside the same way, to
j_1 on both inputs, and the DEFINE clause keeps reading j:

  FROM a a(j_1, p)
    JOIN b b(j_1, q) USING (j_1)
    CROSS JOIN c
  ...
  y AS j > PREV(j)

  - When a USING clause merges a column a DEFINE clause reads,
    set_using_names() uses the name already settled instead of
    inventing one, and gives it to both inputs.

  - collapse_define_join_vars() folds the expanded merge expression
    back into the merged column, so that it is printed as the user
    wrote it.  This is for the FULL JOIN problem.

  - A TABLEFUNC RTE now prints a column alias list under the same rule
    as other non-relation RTEs (a function RTE always prints one):
    when the user wrote an alias list, or when one of its columns had
    to be renamed to avoid a name collision.  This reverses a decision
    made with XMLTABLE, and I would like to hear from anyone who knows
    whether there was a reason beyond the comment that the clause
    names its columns.

A query without a DEFINE clause is not affected by the above, except
through the three changes in the next section.  The reservation
itself adds no alias list unless a collision actually occurs.

Queries without RPR change too

Three changes to column naming are needed for the above to hold.  They
also change pg_get_viewdef() and pg_get_ruledef() output for queries
without RPR.  Each fixes output that failed to re-parse or re-parsed
to a different query.

  - A column of a relation RTE outside the FROM clause (a rule's NEW
    or OLD, or the target of an UPDATE or DELETE) is no longer
    renamed.  It has nowhere to print a column alias list, so a rename
    printed a reference such as new.x_1 to a column that does not
    exist.  For example:

  CREATE TABLE g (x int, y int);
  CREATE TABLE h (x int, z int);
  CREATE TABLE k (x int, w int);
  CREATE TABLE lg (x int);
  CREATE RULE r AS ON UPDATE TO g DO ALSO
    INSERT INTO lg
    SELECT g1.y FROM g g1, h FULL JOIN k USING (x)
    WHERE g1.x <> new.x;

Without 0005, pg_get_ruledef() prints g g1(x_1, y) and WHERE (g1.x_1
<> new.x_1), and re-running that text fails with:

  ERROR:  column new.x_1 does not exist
  LINE 6:           WHERE (g1.x_1 <> new.x_1);
                                     ^
  HINT:  Perhaps you meant to reference the column "g1.x_1".

With 0005 it prints new.x.

  - A TABLEFUNC RTE prints a column alias list, as explained above.

  - For a function RTE with a single function and no WITH ORDINALITY
    or column definition list, the column alias list now includes the
    columns its composite result type has gained since the query was
    parsed.  Alias lists are positional, so leaving them out made the
    list of an aliased join above apply to the wrong columns.

The tests add round trips for these cases.  In create_view and rules,
0005 only adds test cases; no existing expected output there changes.
In rpr_base, the tests that recorded the unrestorable deparse of added
join columns are replaced by round trips of the collision cases.

These cover views and rules.  A DEFINE clause in a SQL-standard
function body that reads a named parameter is not covered; a separate
mail reports it.

[1] https://postgr.es/m/CAAAe_zDsYugq506ou49PU+Ok+4Umn5n59Qs5wYofvKyfEpvZJQ@mail.gmail.com

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

This follows the ten-patch increment on top of v53 that I posted for
row pattern recognition (RPR, SQL:2016 R020, CF 4460) in this thread
[1], and my 07-16 report [2], where I cross-checked the matcher
against Oracle 23ai and Trino 471.  Patch 0003 of the increment fixes
another case of the empty-iteration rule that I described in item 1(b)
of that report.  It changes query results for some patterns, and it
changes how a group is compiled, so this mail explains the reason for
the structure change for readers of execRPR.c.  The other two fixes in
0003, a DEFINE memory leak and a missing interrupt check, are in its
commit message and not here.

The patch is the nocfbot-0003 file attached to [1].  The same commit
is in https://github.com/assam258-5892/postgres/tree/RPR-20260930, on
top of v53.

The rule

ISO/IEC 19075-5 7.2.8 says that once a quantifier's lower bound is
met and an iteration matches the empty string, the quantifier stops
looping.  This is the Perl rule.  Without it, a body that can match
empty, such as A? in (A? | B), could loop back without consuming a row
and derive the same position again.

How the matcher enforces it

The matcher is an NFA.  Between two rows it follows the epsilon
transitions by depth-first search, and no row is consumed in one such
expansion, so arriving twice at the END of a nullable group means the
body matched empty in that iteration.  The cycle guard marks a
nullable group's END when the search arrives there.  A second arrival
finds the mark, and if the count has reached the lower bound the state
leaves the group instead of looping back.

What was missing

A group entered through its BEGIN has not been to its END yet, so its
first iteration had no mark to find.  If that iteration matched empty
at a count between the lower bound and a finite upper bound, the empty
iteration went unrecognized, the state looped back, and the matcher
kept a derivation that the standard excludes.  Take these rows, each
listing the variables it satisfies:

  row 1: B     row 2: A, C     row 3: C

  PATTERN ((A? | B){1,2} C)

Matching from row 1, the standard and Perl give rows 1-3: B, then A,
then C.  The matcher gave rows 1-2.  A? may match empty at row 1,
which is an empty first iteration at count 1, the lower bound, and the
standard stops the quantifier there.  C does not match row 1, so that
derivation ends.  The matcher did not stop: it looped back, took B in
a second iteration, and C matched row 2.  Because A? comes first, that
derivation ranks above B, A, C, and it won.

A reluctant first branch shows the same defect.  ((B?? | B*){0,2} C)
over {B}, {B}, {B, C}, {C} matched rows 1-4 instead of rows 1-3.

The fix

Mark the END at the entry as well, so the first iteration is guarded
like the later ones.  That needs the BEGIN to find its END.
BEGIN.jump used to name the element after the group, the path taken
when the lower bound is 0, and the END cannot be found from there: for
a branch-terminal BEGIN, fillRPRPatternAlt() had redirected jump past
an enclosing alternation, so it need not be next to the END at all.

Now BEGIN.jump names the group's own END.  nfa_mark_group_entered()
marks it on entry when the END can loop on an empty match.  The skip
taken when the lower bound is 0 leaves through END.next, which already
points past an enclosing alternation, so the separate redirect in
fillRPRPatternAlt() is gone.

What changes

Query results change only for patterns whose group can match empty in
its first iteration with a lower bound of 0 or 1 and a finite upper
bound, as in the two examples.  The compiled pattern
changes in one place, the meaning of BEGIN.jump, which the
RPRPatternElement comment in plannodes.h now says.  EXPLAIN output,
error messages and deparse output are unchanged.  The new tests in
rpr_nfa cover the empty first iteration with lower
bound 0 and 1, with greedy and reluctant first branches, and with both
skip modes.

[1] https://postgr.es/m/CAAAe_zDsYugq506ou49PU+Ok+4Umn5n59Qs5wYofvKyfEpvZJQ@mail.gmail.com
[2] https://postgr.es/m/<Message-ID of the 07-16 report>

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

This follows the ten-patch increment on top of v53 that I posted for
row pattern recognition (RPR, SQL:2016 R020, CF 4460) in the thread
"Row pattern recognition" [1].  After the ten were done, a code audit
and runs on the tip of RPR-20260930 found three defects in them.  Two
make planning fail with an internal error, and one prints a function
body that does not run again.  None returns a wrong row.  Jian
reported the first one off-list on 09-22, with a patch.

The patch numbers below are those of the increment.  I will fold the
three fixes into the patches they belong to in the next posting, each
with a regression test.

1. A column only DEFINE reads is missing below GROUP BY (0004)

DEFINE may read a column that is not in GROUP BY but is functionally
dependent on a grouped primary key.  When the node below the aggregate
is a join or a Sort, not a plain scan, that column is not in its
target list and planning fails:

  CREATE TABLE g (id int PRIMARY KEY, val int);
  CREATE TABLE h (id int);
  SELECT g.id, count(*) OVER w FROM g JOIN h ON g.id = h.id
  GROUP BY g.id
  WINDOW w AS (ORDER BY g.id
               ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
               PATTERN (A+) DEFINE A AS val > 0);
  ERROR:  variable not found in subplan target list

Without the primary key, val is an error, and it has to stay one.  A
column that is not grouped and not functionally dependent on a grouped
one cannot be read after grouping, in a DEFINE clause as in HAVING or
ORDER BY.  This is the same query on tables without it, with the caret
under the column in the DEFINE clause:

  CREATE TABLE g2 (id int, val int);
  CREATE TABLE h2 (id int);
  SELECT g2.id, count(*) OVER w FROM g2 JOIN h2 ON g2.id = h2.id
  GROUP BY g2.id
  WINDOW w AS (ORDER BY g2.id
               ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
               PATTERN (A+) DEFINE A AS val > 0);
  ERROR:  column "g2.val" must appear in the GROUP BY clause or be
  used in an aggregate function
  LINE 5:              PATTERN (A+) DEFINE A AS val > 0);
                                                ^

A column that is not in GROUP BY can be read only if it has a single
value in each group.  A primary key identifies one row of its table.
If all its columns are in GROUP BY, every row of a group comes from
the same row of that table, so each other column of the table has one
value per group.  So only such a column reaches the planner.

The cause is in 0004, which stopped the parser from planting DEFINE's
Vars in the target list and let the planner find them, as it does for
HAVING.  It did so in make_window_input_target() but not in
make_group_input_target(), whose input never mentions what only DEFINE
reads.

Jian raised this off-list on 09-22 with a patch.  His example reads
from a plain scan, which hides the failure, but he was right that the
grouping input needs it.  The patch is not the right fix: it also
pulls out the columns under a grouped expression, which changes the
output of the rpr_gexp test.

2. A SQL function parameter in DEFINE does not deparse (0002, 0005)

get_parameter() qualifies a named parameter with the function name.
0002 rejects a two-part name in DEFINE.  So a function with a standard
body that reads a parameter in DEFINE cannot be dumped and restored:

  CREATE TABLE t (id int, v int);
  CREATE FUNCTION f(threshold int) RETURNS SETOF bigint
  LANGUAGE sql
  BEGIN ATOMIC
    SELECT count(*) OVER w FROM t
    WINDOW w AS (ORDER BY id
                 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                 PATTERN (A+) DEFINE A AS v > threshold);
  END;
  SELECT pg_get_functiondef('f(int)'::regprocedure);
    ... DEFINE a AS (v > f.threshold) ...
  -- run that text again:
  ERROR:  qualified expression "f.threshold" is not allowed in DEFINE
  clause

pg_dump fails the same way.  The same path prints PREV(v,
(f.n)::bigint) and (f.p).field too, and of eight forms I tried only an
unnamed parameter ($1) survives.  PL/pgSQL is not affected, since its
body is stored as text.

Dropping the qualifier would bind the name to a column of the same
name and change the query silently.  The fix is to print $N for a
parameter while deparsing DEFINE.  The same function then deparses as

    ... DEFINE a AS (v > $1) ...

which runs again and reads the parameter.

3. A function parameter inside PREV() under LATERAL (0001)

The argument of PREV, NEXT, FIRST and LAST is evaluated at another
row, so a value folded into a constant could raise at plan time an
error that execution would never reach.  Below, v becomes the constant
1 after pull-up, and 1 / 0 is never evaluated, since the first row has
no previous row.  Before 0004 this query failed at plan time:

  SELECT count(*) OVER w FROM (VALUES (1)) t(v)
  WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
               PATTERN (A) DEFINE A AS PREV(v / 0) > 0);
   count
  -------
       0

So 0004 keeps the argument dependent on the row.  0001 does the same
for the merged column of a USING join, which is an expression when the
join is a FULL JOIN, or when one side has to be converted to the
common type, as the left side of the LEFT JOIN below.  Before 0001
this one failed with "division by zero":

  SELECT count(*) OVER w
  FROM (VALUES (1)) a(k) LEFT JOIN (VALUES (1::bigint)) b(k) USING (k)
  WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
               PATTERN (A) DEFINE A AS PREV(k / 0) > 0);
   count
  -------
       0

The change in 0001 is a problem in one case, a SQL function that reads
its parameter inside PREV(), called under LATERAL over such a column:

  CREATE TABLE s (v int);
  INSERT INTO s SELECT generate_series(1, 6);
  CREATE TABLE a (k int);
  CREATE TABLE b (k bigint);
  INSERT INTO a VALUES (1), (2), (-10);
  INSERT INTO b VALUES (1), (2), (-10);
  CREATE FUNCTION f3(p bigint) RETURNS TABLE(v int, cnt bigint) AS $$
    SELECT v, count(*) OVER w FROM s
    WINDOW w AS (ORDER BY v
                 ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                 PATTERN (A B+) DEFINE B AS PREV(v + p) > 0)
  $$ LANGUAGE sql STABLE;
  SELECT * FROM a FULL JOIN b USING (k), LATERAL f3(k);
  ERROR:  plan should not reference subplan's variable

The function body names no outer column, only its own parameter, and a
parameter is a value.  The same function runs normally when it is not
inlined, and so does one that reads the parameter outside PREV(), so I
think this query should run.  ISO/IEC 19075-5 4.18.3 even suggests
this form: pass the values that are prohibited as outer references to
an SQL-invoked routine as arguments.  An internal error is a defect
either way.

I am not confident of this reading, though.  Should a function
parameter that DEFINE reads count as an outer reference once the
function is inlined?  I would like us to settle that together.

A plain LATERAL subquery that names an outer column in DEFINE is a
different case.  The standard prohibits outer references in DEFINE
(ISO/IEC 19075-5 4.18.1), and the parser rejects one:

  SELECT * FROM a FULL JOIN b USING (k),
  LATERAL (SELECT v, count(*) OVER w AS cnt FROM s
           WINDOW w AS (ORDER BY v
             ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
             PATTERN (A B+)
             DEFINE B AS PREV(v + k) > 0)) x;
  ERROR:  cannot use outer query column in DEFINE clause
  LINE 6:            DEFINE B AS PREV(v + k) > 0)) x;
                                          ^

The merged column has to be an expression for the error to occur: a
FULL JOIN, or a LEFT JOIN whose left side has to be converted to the
common type.  The query also has to read the merged column.  An INNER
JOIN, a LEFT JOIN whose left side is already the wider type, and a
parameter used outside PREV() as in PREV(v) + p, are fine.

What I checked

I ran each reproduction above on a build identical to the tip of
RPR-20260930.  There is no fix for any of the three yet.  I do not
know of another case of the same kind, but I found these by reading
and by trying shapes, so I cannot rule one out.

[1] https://postgr.es/m/CAAAe_zDsYugq506ou49PU+Ok+4Umn5n59Qs5wYofvKyfEpvZJQ@mail.gmail.com

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi hackers,

The link [2] in this mail went out as a placeholder.  The 07-16 report
is at the address below.

> This follows the ten-patch increment on top of v53 that I posted for
> row pattern recognition (RPR, SQL:2016 R020, CF 4460) in this thread
> [1], and my 07-16 report [2], where I cross-checked the matcher
> against Oracle 23ai and Trino 471.

> [2] https://postgr.es/m/<Message-ID of the 07-16 report>

[2] https://postgr.es/m/CAAAe_zBw5U=RNb39wGXyRC1FE0VG-m9zbvFeBpVGWUDDUVWRhQ@mail.gmail.com

Sorry for the noise.

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

Thank you for explaining.  I agree that the order
explains the message.

> Different ways of processing the navigation yield different error
> messages, and therefore the error position also differs.
> So i think this should be ok.

The error message should be decided from the user's side first, and
the implementation then built to produce it.  That an approach was
chosen first does not justify the message it produces.  If producing
the better message were costly, I would weigh that; here I expect the
cost to be small.  So the question is which message serves the user.

I think one rule answers it.  When two mistakes sit at the same
level, I see no reason to report one before the other.  But a
mistake inside something that is already wrong should not come
first.  Take PREV(val, FIRST(1)).  A navigation call in the
offset is already the mistake.  Your patch reports that FIRST(1)
has no column reference, so the user adds one, and only then
learns that the offset must be a run-time constant.  Fixing
the offset removes FIRST(1) altogether.  The nesting rows are a
structural case: PREV inside PREV is not allowed, and the code
before your patch and the other two engines say so first.

I ran these expressions on Oracle 23.26 and Trino 471, and on the
code before and after your patch ("before" and "yours").  "offset"
means the message is about the offset, "arg" that it is about the
argument of the inner call, and "nest" is a nesting error.  "*" marks
a message about the inner mistake when an outer one is there.  "**"
marks a message that differs from Oracle and Trino but is about
one of two mistakes at the same level, which I think is fine.

  DEFINE A AS val > <expression>

  expression             Oracle  Trino   before  yours
  -- inner mistake inside a mistaken offset
  PREV(val, FIRST(1))    offset  offset  offset  arg*
  PREV(val, PREV(1))     offset  offset  offset  arg*
  -- inner mistake inside a disallowed nesting
  PREV(PREV(1), 1)       nest    nest    nest    arg*
  FIRST(PREV(1), 1)      nest    nest    nest    arg*
  -- no inner mistake
  PREV(val, FIRST(val))  offset  offset  offset  offset
  PREV(val, val)         offset  offset  offset  offset
  PREV(PREV(val))        nest    nest    nest    nest
  -- mistakes at the same level
  PREV(FIRST(1), val)    offset  offset  arg**   arg**
  PREV(1, val)           offset  offset  arg**   offset

In the first four rows the code before your patch reports the
outer mistake, and yours reports the inner one.  Oracle and
Trino report the inner one in none of them.  Oracle has no
column-reference check at all, since it accepts PREV(FIRST(1)),
so for the first two rows only Trino, which has the check, shows
an order.  The standard does not say which error to report first,
so I do not claim their order as a rule.  The last two rows are
mistakes at the same level, and I make no claim about them.

The expected output of your patch shows the same thing.
Seven cases change from a message about the outer mistake
to one about the inner one: six where the offset contains
a navigation call, such as PREV(v, FIRST(1) + 1) and
PREV(FIRST(v), LAST(1)), and PREV(FIRST(v, LAST(1)), 2),
where the nesting depth was reported before.

Those seven need to report the outer mistake, as before.  As they
are, I would not include the patch in the series.  The way to do it
follows from how ParseRPRNavCall works: it receives its arguments
already transformed, so it has to be told, while the offset is
being transformed, that this is an offset, and, for an argument,
which call it sits in and whether that nesting is allowed.  I expect
the change to be small: a field in ParseState that is set while
the offset is transformed.  PostgreSQL passes the context down the
same way for an aggregate in a window frame offset, which reports
"aggregate functions are not allowed in window ROWS".  A name that
cannot be resolved still comes first there, as it must; this check
is about the shape of the call.  If you would rather not make this
change, I will make it myself when I put the patch on top of the
next series.  The rest of your patch can stay as it is.

Of the changed messages in the expected output, most only
move the caret or reword and are fine, and these seven got
worse.  With them fixed, I will include the patch in the next
series after verifying its quality, as I said earlier.

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

I always want to get rid of WindowAggState.nfaStateSize. It's ugly.

nfa_state_clone->nfa_state_make is hot path, but
ExecRPRStartContext->nfa_state_make is not.

In nfa_state_clone->nfa_state_make:
memset(state, 0, winstate->nfaStateSize)
is waste cycle, because nfa_state_clone would unconditionally memcpy
from (int32 *counts) later.

With that, we can get rid of memset in nfa_state_make conditionally,
once memset is removed, nfaStateSize is no longer needed.

Most of the row pattern code already works on WindowAggState, so
refactoring makes the remaining rpr routines take WindowAggState instead of
WindowObject as well. This looks more consistent.

based on https://github.com/assam258-5892/postgres/tree/RPR-20260930



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

Thank you for the three patches.  I answer them in order.

0001 Use WindowAggState instead of WindowObject in rpr routines
0002 minor, using palloc0_array instead of palloc0

> Most of the row pattern code already works on WindowAggState, so
> refactoring makes the remaining rpr routines take WindowAggState
> instead of WindowObject as well. This looks more consistent.

I will take 0001 and 0002.

0003 Remove WindowAggState.nfaStateSize

> I always want to get rid of WindowAggState.nfaStateSize. It's ugly.

I would like to keep that field.  The size depends only on the
pattern, so it is computed once, and I do not want to repeat the
same computation on a path this frequent just to save a field.  To
me the field is the cleaner choice.

> nfa_state_clone->nfa_state_make is hot path, but
> ExecRPRStartContext->nfa_state_make is not.
>
> In nfa_state_clone->nfa_state_make:
> memset(state, 0, winstate->nfaStateSize)
> is waste cycle, because nfa_state_clone would unconditionally memcpy
> from (int32 *counts) later.

I agree with this part, and I will take it.  I went one step
further.  nfa_state_clone calls nfa_state_make, so I would
merge the two into one, nfa_state_make:

  static RPRNFAState *nfa_state_make(WindowAggState *winstate,
                                     const RPRNFAState *src);

When src is NULL, it makes a new state on element 0 with counts[]
cleared (ExecRPRStartContext).  Otherwise it copies elemIdx,
isAbsorbable and counts[] from src as they are.  Of the 7 callers,
only the ALT branch sets elemIdx and isAbsorbable itself afterwards;
the others get them from nfa_state_exit_to() or stay on the same
element.

When Tatsuo prepares the next patch, I will make a patch for this
change on top of it and share it.  I will send the accumulated
patches slowly, over time.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson and Jian,

I confirmed following issue is resolved with RPR53 + 10 incremental
patches (to be RPR54). Before, the last line of pg_get_viewdef was "a
AS ttt.val < 0);"

SELECT pg_get_viewdef('v1'::regclass, true);
                         pg_get_viewdef                          
-----------------------------------------------------------------
  SELECT tt.id1,                                                +
     tt.val1,                                                   +
     ttt.id,                                                    +
     ttt.val,                                                   +
     count(*) OVER w AS count                                   +
    FROM ( SELECT t1.id AS id1,                                 +
             t1.val AS val1                                     +
            FROM t1) tt,                                        +
     t2 ttt                                                     +
   WHERE tt.id1 = ttt.id                                        +
   WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING+
   AFTER MATCH SKIP PAST LAST ROW                               +
   INITIAL                                                      +
   PATTERN (a)                                                  +
   DEFINE                                                       +
   a AS val < 0);	<-- "val" is not qualified as expected
(1 row)

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

From: Tatsuo Ishii 
Subject: Re: Row pattern recognition
Date: Sat, 15 Aug 2026 08:10:54 +0900 (JST)
Message-ID: <20260815.081054.1707950877428677644.ishii@postgresql.org>

> Hi Henson,
> 
>> Your case looks like the same shape.  It currently deparses to
>> 
>>    SELECT
>>      FROM t1,
>>       t2
>>     WHERE t1.id = t2.id
>>     WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>>     AFTER MATCH SKIP PAST LAST ROW
>>     INITIAL
>>     PATTERN (a)
>>     DEFINE
>>     a AS val > 0);
>> 
>> and that text does not reparse, exactly as you say
>> (ERROR: column reference "val" is ambiguous).  But with one column
>> alias list on t2,
>> 
>>       t2 t2(id, val_1)
>> 
>> the same text creates the view, a second deparse gives back the same
>> text, and DEFINE resolves to t1.val.  So what the deparser is missing
>> here is a single token.
> 
> I played with following SQL to check if the technique using subquery
> to resolve an ambiguity of column names in DEFINE clause explained in
> ISO/IEC 19075-5 section 6.5 "Row pattern variables and other range
> variables".
> 
> First create an ambiguous column "val" in DEFINE clause.
> 
> CREATE TABLE t1 (id int, val int);
> CREATE TABLE
> CREATE TABLE t2 (id int, val int);
> CREATE TABLE
> INSERT INTO t1 VALUES(1,1),(2,2);
> INSERT 0 2
> INSERT INTO t2 VALUES(1,-1),(2,-2);
> INSERT 0 2
> SELECT FROM t1, t2 WHERE t1.id = t2.id
> WINDOW w AS (
> ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
> PATTERN(A)
> DEFINE A AS val > 0
> );
> psql:ambiguous.sql:13: ERROR:  column reference "val" is ambiguous
> LINE 5: DEFINE A AS val > 0
>                     ^
> Next, use the subquery workaround:
> 
> SELECT tt.id1, tt.val1, ttt.id, ttt.val, count(*) OVER w
> FROM (SELECT id AS id1, val AS val1 FROM t1) AS tt, t2 AS ttt
> WHERE tt.id1 = ttt.id
> WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
> PATTERN(A)
> DEFINE A AS val < 0
> );
>  id1 | val1 | id | val | count 
> -----+------+----+-----+-------
>    1 |    1 |  1 |  -1 |     1
>    2 |    2 |  2 |  -2 |     1
> (2 rows)
> 
> Seems work. Now, create a view from the query.
> 
> CREATE VIEW v1 AS
> SELECT tt.id1, tt.val1, ttt.id, ttt.val, count(*) OVER w
> FROM (SELECT id AS id1, val AS val1 FROM t1) AS tt, t2 AS ttt
> WHERE tt.id1 = ttt.id
> WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
> PATTERN(A)
> DEFINE A AS val < 0
> );
> CREATE VIEW
> SELECT * FROM v1;
>  id1 | val1 | id | val | count 
> -----+------+----+-----+-------
>    1 |    1 |  1 |  -1 |     1
>    2 |    2 |  2 |  -2 |     1
> (2 rows)
> 
> Again, it works. Let's check the view definition.
> 
> SELECT pg_get_viewdef('v1'::regclass, true);
>                           pg_get_viewdef                          
> ------------------------------------------------------------------
>   SELECT tt.id1,                                                 +
>      tt.val1,                                                    +
>      ttt.id,                                                     +
>      ttt.val,                                                    +
>      count(*) OVER w AS count                                    +
>     FROM ( SELECT t1.id AS id1,                                  +
>              t1.val AS val1                                      +
>             FROM t1) tt,                                         +
>      t2 ttt                                                      +
>    WHERE tt.id1 = ttt.id                                         +
>    WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING +
>    AFTER MATCH SKIP PAST LAST ROW                                +
>    INITIAL                                                       +
>    PATTERN (a)                                                   +
>    DEFINE                                                        +
>    a AS ttt.val < 0 );
> (1 row)
> 
> Not good. The DEFINE clause uses a range variable declared in the FROM
> clause (ttt.val), which is not valid. Of course if we dump/restore
> this, restore will fail.
> 
> So, even if we do not use ALTER TABLE ADD COLULN/RENAME COLUMN, we
> have a problem with views using RPR. I have not checked how hard to
> fix this yet. If it's hard, probably we should add this as a
> limitation of RPR to the document.
> 
> Regards,
> --
> Tatsuo Ishii
> SRA OSS K.K.
> English: http://www.sraoss.co.jp/index_en/
> Japanese:http://www.sraoss.co.jp
> 
> 


Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Wed, Oct 14, 2026 at 8:35 AM Henson Choi  wrote:
>
> 0003 Remove WindowAggState.nfaStateSize
>
> > I always want to get rid of WindowAggState.nfaStateSize. It's ugly.
>
> I would like to keep that field.  The size depends only on the
> pattern, so it is computed once, and I do not want to repeat the
> same computation on a path this frequent just to save a field.  To
> me the field is the cleaner choice.
>
Hi.

Let's agree to disagree, at least now, removing
WindowAggState.nfaStateSize is not performance related.
Also as mentioned in
https://www.postgresql.org/message-id/688312.1782222788%40sss.pgh.pa.us
we should use size_t, not using Size

Please check attached 0001 and 0002.

0001: Remove RPRNavExpr.navno
navno spans all three stages: ParseRPRNavCall() initializes it,
compute_define_metadata() compute it while planning, and ExecInitExprRec() use
it. Tracking and keeping those in sync is not trivial.
It's doable to just remove it.

0002: Remove compute_define_metadata
IMHO compute_define_metadata() is complicated.
Instead, loop over the DEFINE clause with foreach, run an expression walker
on each variable's expression to check whether it depends on the match
start, and if it does, record that variable's index.



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson and Jian,

> This is an increment on top of v53.  It is ten patches, named
> nocfbot-XXXX-*.txt as before.

Thank you for the patches!

I looked through nocfbot-0001 to 0010. Since all the comments are
minor, I think I can build v54 from the ten patches as it is. If you
think differently, please let me know.

>   0001 Let a row pattern DEFINE clause take part in grouping
>        [wrong result]
>        v53 left DEFINE out of the GROUP BY substitution, so a grouping
>        set that nulls a column made setrefs.c fail with "wrong
>        varnullingrels".  DEFINE now goes through the same steps as the
>        target list.  Also fixes PREV(k / 0) failing at plan time when
>        k is a USING column of mixed types.

Looks good to me. Minor point.
+		/*
+		 * A row pattern DEFINE clause carries GROUP Vars of its own; expand
+		 * them, or the deparsed text would name the grouping step rather than
+		 * the expression the user wrote, and the view would not re-parse.
+		 */
+		foreach(lc, query->windowClause)

Can we use foreach_node instead or foreach? In the same patch
foreach_node is used.

>   0002 Tighten parse analysis of DEFINE clauses and row pattern
>        syntax  [wrong result]
>        Whole-row references, ROW(t.*), names qualified by a function
>        name or block label, and the FILTER or ORDER BY of an aggregate
>        got around the qualifier rule of ISO/IEC 19075-5 6.5.  They
>        are rejected now, and a few SQLSTATEs change.

Looks good to me.

>   0003 Fix DEFINE memory leak and empty-iteration looping in RPR
>        executor  [wrong result]
>        An empty first iteration kept a derivation the standard
>        excludes, so some patterns matched different rows than Perl;
>        query results change for such patterns.  Also fixes the DEFINE
>        memory leak (94MB down to 18MB on 300k rows) and adds an
>        interrupt check.

I briefly looked through this. No objection from me.

>   0004 Move DEFINE input tracking from parse analysis to the planner
>        [wrong result]
>        Parse analysis planted DEFINE's Vars in the target list, and
>        planning could fail with "variable not found in subplan target
>        list".  DEFINE is now handled the way havingQual is.  Also
>        stops subquery pull-up from folding a navigation argument, and
>        fixes a crash on a navigation offset.

I still need to learn more about planner, but the direction looks
right to me.

>   0005 Make a deparsed DEFINE clause re-parse as written
>        [wrong result]
>        A view holding a DEFINE clause could not be dumped and restored
>        once another column carried the same name.  The names DEFINE
>        reads are now settled first and reserved.  Also changes
>        pg_get_viewdef() output for some queries without row pattern
>        recognition; the commit message lists them.

+/*
+ * reserve_colname: keep any other RTE from being given this column name
+ */
+static void
+reserve_colname(deparse_namespace *dpns, char *colname)
+{
+	ListCell   *lc;
+
+	foreach(lc, dpns->using_names)
+	{
+		if (strcmp((char *) lfirst(lc), colname) == 0)
+			return;
+	}
+	dpns->using_names = lappend(dpns->using_names, colname);
+}

colname should be duplicated using pstrdup() before passing to
lappend? As some of callers of this function might pass a string
literal.

+		if (rte->rtekind == RTE_RELATION)
+			reserve_colname(dpns, get_rte_attribute_name(rte, attno));

> 
>   0006 Tighten RPRPattern node I/O and reuse existing helpers in RPR
>        code  [latent]
>        A malformed node string now fails with an internal error
>        instead of being misread.  Existing helpers replace
>        hand-written code.

Overall looks good. Minor point:

@@ -728,23 +727,27 @@ _outRPRPattern(StringInfo str, const RPRPattern *node)
 	WRITE_INT_FIELD(maxDepth);
 	WRITE_INT_FIELD(numElements);
 
-	/* Write varNames array as list of strings */
+	/*
+	 * Write varNames array as list of strings.  makeRPRPattern() guarantees
+	 * the array, so the list has exactly one spelling and the read side has
+	 * no second shape to interpret.
+	 */

I think "makeRPRPattern() guarantees the array" should be
"makeRPRPattern() guarantees the array exists." to make what it means
cleaner.

>   0007 Record two RPR costs and correct comments the code no longer
>        matches  [comments, asserts]
>        Comments, plus five checks the executor cannot reach, now
>        Asserts: two elog(ERROR) calls and three early returns.
>        Records two known costs as XXX: the state comparison in
>        nfa_states_equal(), and nav_winobj's shared read pointer.

I had no time to read the details.

>   0008 Tidy and extend the row pattern recognition regression tests
>        [tests]
>        Tests only: rpr_ prefixes, fewer redundant ORDER BY, new tests,
>        and fixes for tests that tested less than their comments said.

I had no time to read the details.

>   0009 Bring the row pattern recognition documentation up to date
>        [docs]
>        Documentation only: SGML and README.rpr checked against the
>        code.

Looks good except:
--- a/src/backend/executor/README.rpr
+++ b/src/backend/executor/README.rpr

+  Related code, by the phase each file serves.  A file appears once,
+  under the phase where its row pattern work belongs:
+
+    Parser

scan.l seems missed in the list.

In perform.sgml there are few lines using  tag for ANALYZE
command. The tag should be , rather than .

    Under ANALYZE, a node that was executed shows the
    bound resolved for its last scan instead of runtime:
    a row count, retain all or
    infinite.
   

   
    Under ANALYZE, further lines report counters for the

>   0010 Reorder README.rpr by processing order  [docs]
>        Moves the chapters into the order a query goes through the
>        code: parsing, DEFINE planning, PATTERN compilation, the
>        executor, the worked example, deparse and EXPLAIN, and the
>        summary last.  Text moves; section numbers and cross references
>        follow, and the Chapter IV title is reworded.

Looks good.

> Open questions
> 
>   Tatsuo, four items need your decision on the direction or on whether
>   to go ahead:
> 
>   - State explosion.  To keep the preference order from giving wrong
>     answers, the cycle guard marks only a nullable END, since marking
>     anything else loses legitimate matches.  That bounds cycles but not
>     cost: alternations whose branches are all nullable enumerate paths
>     rather than states, as an XXX in nfa_advance_state() records.  A
>     runtime bound, on the work in one expansion or on the states held,
>     is the first answer; rejecting quantified subpatterns that can
>     match empty, as Oracle does with ORA-62513, is the alternative.

I need more time to answer to the question.

>   - Names.  You accepted the RPR* policy for the typedefs on 07-14 [1]
>     and asked whether it reaches struct members too.  I would say yes:
>     rpSkipTo becomes rprSkipTo along with the types, in one mechanical
>     patch after the defects are settled.

Agreed on this direction.

>   - WindowAggState.  On 05-31 [2] you agreed with Jian's idea [3] of
>     putting the row pattern members behind one struct, for the size
>     and for the move to R010, but not for v48.  On 07-14 [1] you asked
>     when to do it, saying it has to be done to make the code
>     committable.  I would group the members before the commit, since
>     that only changes structure, and leave the R010 redesign for
>     after.  The struct needs a name other than RPRContext, since
>     rprContext is already the ExprContext DEFINE runs in.

In the last this is necessary but it does not need to be hurry.

>   - sql_features.txt still says R020 is NO although the patch
>     implements it.  It has to change before the commit.  Whether it
>     says YES with a note or NO, partially supported is your call.

When I implemented RPR alone, there were too many missing features. So
I thought the status should be "NO". Now many features in R020 are
implemneted in the current patch. However, we still miss a big
features: range variable qualified pattern variables and MEASURES
clause. So someone might say that the current patch is not eligible to
be marked as "R020 is supported". However I personally think even
without those two features, current patch is useful enough to enjoy
the split of R020.  This is really the community's decision. Until the
decision is made, I would like to change it "YES with a note".

>   None of these is urgent, and none is a structural problem that puts
>   the quality of the patch at risk.  Each is a matter of direction or
>   timing that can wait until the code has settled, and I will follow
>   whichever way you decide.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

Thank you for going through all ten patches.

> I looked through nocfbot-0001 to 0010. Since all the comments are
> minor, I think I can build v54 from the ten patches as it is. If you
> think differently, please let me know.

Then please go ahead and build v54 from the ten patches as they are.
It is not that I found nothing that needs fixing, but what we need now
is a patch that can serve as the basis for discussion. From here on,
I think putting consensus first, even if it is slower, is a faster way
to a commit than moving quickly. I will include the five fixes below
in the next increment.

Meanwhile, I am running a quality audit of the series as I expect v54
to be. Once v54 is posted, I would like to audit it again and share
the results with you.

>>   0001 Let a row pattern DEFINE clause take part in grouping
>>        [wrong result]
>
> Looks good to me. Minor point.
> + /*
> + * A row pattern DEFINE clause carries GROUP Vars of its own; expand
> + * them, or the deparsed text would name the grouping step rather than
> + * the expression the user wrote, and the view would not re-parse.
> + */
> + foreach(lc, query->windowClause)
>
> Can we use foreach_node instead or foreach? In the same patch
> foreach_node is used.

Agreed; that loop will use foreach_node like the others in the patch.

>>   0004 Move DEFINE input tracking from parse analysis to the planner
>>        [wrong result]
>>        Parse analysis planted DEFINE's Vars in the target list, and
>>        planning could fail with "variable not found in subplan target
>>        list".  DEFINE is now handled the way havingQual is.
>
> I still need to learn more about planner, but the direction looks
> right to me.

Thank you. I also think the planner is an area that takes a lot of
study, and it would be better to widen my knowledge a little more
before taking it further. The quality audit is turning up some
planner-related points as well; once v54 is out, I will put them
together and send them along with the results. I think they will give
us leads for future improvements.

>>   0005 Make a deparsed DEFINE clause re-parse as written
>>        [wrong result]
>
> +static void
> +reserve_colname(deparse_namespace *dpns, char *colname)
> +{
> ...
> + dpns->using_names = lappend(dpns->using_names, colname);
> +}
>
> colname should be duplicated using pstrdup() before passing to
> lappend? As some of callers of this function might pass a string
> literal.

Agreed. No current caller passes a literal, but the callers may
change, so copying with pstrdup() as you suggest is the safer way.

While we are on 0005: as I wrote on 10-08, I would like to pull
the generic ruleutils.c fixes inside it (TABLEFUNC column alias
lists, columns added to a function RTE after the view was created,
and relation RTEs that do not appear in FROM) out into a separate
prerequisite patch with its own thread and CF entry, and to rebase the
row pattern series on top of it. v54 can keep them as they are; I plan
to do the split in the next increment.

>>   0006 Tighten RPRPattern node I/O and reuse existing helpers in RPR
>>        code  [latent]
>
> + /*
> + * Write varNames array as list of strings.  makeRPRPattern() guarantees
> + * the array, so the list has exactly one spelling and the read side has
> + * no second shape to interpret.
> + */
>
> I think "makeRPRPattern() guarantees the array" should be
> "makeRPRPattern() guarantees the array exists." to make what it means
> cleaner.

Agreed.

>>   0007 Record two RPR costs and correct comments the code no longer
>>        matches  [comments, asserts]
>
> I had no time to read the details.

>>   0008 Tidy and extend the row pattern recognition regression tests
>>        [tests]
>
> I had no time to read the details.

No problem. I am reviewing these further on my side, and I will send
what I find along with the audit results.

>>   0009 Bring the row pattern recognition documentation up to date
>>        [docs]
>
> Looks good except:
> --- a/src/backend/executor/README.rpr
> +++ b/src/backend/executor/README.rpr
>
> +  Related code, by the phase each file serves.  A file appears once,
> +  under the phase where its row pattern work belongs:
> +
> +    Parser
>
> scan.l seems missed in the list.

Agreed. I will add scan.l, and mention psqlscan.l and pgc.l, which
have to follow it, on the same line.

> In perform.sgml there are few lines using <literal> tag for ANALYZE
> command. The tag should be <command>, rather than <literal>.
>
>     Under <literal>ANALYZE</literal>, a node that was executed shows the
>     bound resolved for its last scan instead of <literal>runtime</literal>:
>     a row count, <literal>retain all</literal> or
>     <literal>infinite</literal>.
>    </para>
>
>    <para>
>     Under <literal>ANALYZE</literal>, further lines report counters for the

Agreed on the direction. Throughout the docs, though,
<command>ANALYZE</command> alone always means the statistics command,
so I think it is better to follow one of the two existing precedents:
<command>EXPLAIN ANALYZE</command> for the command, or "the
<literal>ANALYZE</literal> option" for the option.

>>   - State explosion.  To keep the preference order from giving wrong
>>     answers, the cycle guard marks only a nullable END, since marking
>>     anything else loses legitimate matches.  That bounds cycles but not
>>     cost: alternations whose branches are all nullable enumerate paths
>>     rather than states, as an XXX in nfa_advance_state() records.  A
>>     runtime bound, on the work in one expansion or on the states held,
>>     is the first answer; rejecting quantified subpatterns that can
>>     match empty, as Oracle does with ORA-62513, is the alternative.
>
> I need more time to answer to the question.

Please take your time. On my side, I have found a few leads on how to
deal with the state explosion. Some are simple, and one is involved
enough that it takes understanding a paper first. I will come back to
you once they are in better shape.

>>   - Names.  You accepted the RPR* policy for the typedefs on 07-14 [1]
>>     and asked whether it reaches struct members too.  I would say yes:
>>     rpSkipTo becomes rprSkipTo along with the types, in one mechanical
>>     patch after the defects are settled.
>
> Agreed on this direction.

Thank you. I will put together a draft of the RPR* naming, struct
members included, so that we can agree on the direction.

>>   - WindowAggState.  On 05-31 [2] you agreed with Jian's idea [3] of
>>     putting the row pattern members behind one struct, for the size
>>     and for the move to R010, but not for v48.  On 07-14 [1] you asked
>>     when to do it, saying it has to be done to make the code
>>     committable.  I would group the members before the commit, since
>>     that only changes structure, and leave the R010 redesign for
>>     after.
>
> In the last this is necessary but it does not need to be hurry.

Understood. I will wait for the right time.

>>   - sql_features.txt still says R020 is NO although the patch
>>     implements it.  It has to change before the commit.  Whether it
>>     says YES with a note or NO, partially supported is your call.
>
> When I implemented RPR alone, there were too many missing features. So
> I thought the status should be "NO". Now many features in R020 are
> implemneted in the current patch. However, we still miss a big
> features: range variable qualified pattern variables and MEASURES
> clause. So someone might say that the current patch is not eligible to
> be marked as "R020 is supported". However I personally think even
> without those two features, current patch is useful enough to enjoy
> the split of R020.  This is really the community's decision. Until the
> decision is made, I would like to change it "YES with a note".

YES with a note sounds right to me. I think this change is yours to
make, so I will leave it out of my patches.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Attached is v54 RPR patches.

V54 includes many bug fixes and enhancements by applying 10 patches
[1] on top of v53.

[1] https://www.postgresql.org/message-id/CAAAe_zDsYugq506ou49PU%2BOk%2B4Umn5n59Qs5wYofvKyfEpvZJQ%40mail.gmail.com

Brief introduction to incremental patches cited from [1] below. More
details can be found in [1].

  0001 Let a row pattern DEFINE clause take part in grouping
       [wrong result]
       v53 left DEFINE out of the GROUP BY substitution, so a grouping
       set that nulls a column made setrefs.c fail with "wrong
       varnullingrels".  DEFINE now goes through the same steps as the
       target list.  Also fixes PREV(k / 0) failing at plan time when
       k is a USING column of mixed types.

  0002 Tighten parse analysis of DEFINE clauses and row pattern
       syntax  [wrong result]
       Whole-row references, ROW(t.*), names qualified by a function
       name or block label, and the FILTER or ORDER BY of an aggregate
       got around the qualifier rule of ISO/IEC 19075-5 6.5.  They
       are rejected now, and a few SQLSTATEs change.

  0003 Fix DEFINE memory leak and empty-iteration looping in RPR
       executor  [wrong result]
       An empty first iteration kept a derivation the standard
       excludes, so some patterns matched different rows than Perl;
       query results change for such patterns.  Also fixes the DEFINE
       memory leak (94MB down to 18MB on 300k rows) and adds an
       interrupt check.

  0004 Move DEFINE input tracking from parse analysis to the planner
       [wrong result]
       Parse analysis planted DEFINE's Vars in the target list, and
       planning could fail with "variable not found in subplan target
       list".  DEFINE is now handled the way havingQual is.  Also
       stops subquery pull-up from folding a navigation argument, and
       fixes a crash on a navigation offset.

  0005 Make a deparsed DEFINE clause re-parse as written
       [wrong result]
       A view holding a DEFINE clause could not be dumped and restored
       once another column carried the same name.  The names DEFINE
       reads are now settled first and reserved.  Also changes
       pg_get_viewdef() output for some queries without row pattern
       recognition; the commit message lists them.

  0006 Tighten RPRPattern node I/O and reuse existing helpers in RPR
       code  [latent]
       A malformed node string now fails with an internal error
       instead of being misread.  Existing helpers replace
       hand-written code.

  0007 Record two RPR costs and correct comments the code no longer
       matches  [comments, asserts]
       Comments, plus five checks the executor cannot reach, now
       Asserts: two elog(ERROR) calls and three early returns.
       Records two known costs as XXX: the state comparison in
       nfa_states_equal(), and nav_winobj's shared read pointer.

  0008 Tidy and extend the row pattern recognition regression tests
       [tests]
       Tests only: rpr_ prefixes, fewer redundant ORDER BY, new tests,
       and fixes for tests that tested less than their comments said.

  0009 Bring the row pattern recognition documentation up to date
       [docs]
       Documentation only: SGML and README.rpr checked against the
       code.

  0010 Reorder README.rpr by processing order  [docs]
       Moves the chapters into the order a query goes through the
       code: parsing, DEFINE planning, PATTERN compilation, the
       executor, the worked example, deparse and EXPLAIN, and the
       summary last.  Text moves; section numbers and cross references
       follow, and the Chapter IV title is reworded.

The series of patches are to implement the row pattern recognition
(SQL/RPR) feature. At present the implementation is a subset of
SQL/RPR (ISO/IEC 19075-2:2016). Namely, implementation of some
features of R020 (WINDOW clause). R010 (MATCH_RECOGNIZE) is out of the
scope of the patches.

Currently following features are implemented in the patches.

- PATTERN
- PATTERN regular expressions (+, *, ?)
  alternation (|), grouping () , {n}, {n,}, {n,m}, {,m}
  reluctant quantifiers (*? etc.),
  Empty pattern ("PATTERN ()") are not permitted by the standard
  Anchors (^, $) are not permitted in R020 by the standard
- DEFINE
- INITIAL
- AFTER MATCH SKIP TO PAST LAST ROW
- AFTER MATCH SKIP TO NEXT ROW
- Row pattern navigation (FIRST, LAST, PREV, NEXT and their compound forms)

Currently following features are not implemented in the patches.

- MEASURES
- Pattern variable name qualified column reference (e.g. A.price)
- SUBSET
- SEEK
- AFTER MATCH SKIP TO
- AFTER MATCH SKIP TO FIRST
- AFTER MATCH SKIP TO LAST
- PATTERN regular expression  {- and -}
- PERMUTE
- CLASSIFIER

Author: Tatsuo Ishii 
Author: Henson Choi 
Author: jian he 
Reviewed-by: Vik Fearing 
Reviewed-by: Jacob Champion 
Reviewed-by: Peter Eisentraut 
Reviewed-by: NINGWEI CHEN 
Reviewed-by: "David G. Johnston" 
Reviewed-by: Chao Li 
Reviewed-by: SungJun Jang 
Reviewed-by: Zsolt Parragi 
Reviewed-by: SeongJun Shin <

Discussion: https://postgr.es/m/20230625.210509.1276733411677577841.t-ishii%40sranhm.sra.co.jp

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
Hi.

based on https://github.com/assam258-5892/postgres/tree/RPR-20260930
I have made some non-trivial refactoring in nodeWindowAgg.c, see attached.

The attached patch commit message is as follows:
================
    Separate resolving the reduced frame from consuming it

    ExecWindowAgg() resolves the reduced frame for every row it emits,
by calling
    ensure_reduced_frame() before any window function or aggregate
runs; that is the
    only place the match is driven.  Everything after it should only
consumes the
    recorded match through get_reduced_frame_status(), which reports how any row
    position relates to it.

    row_is_in_reduced_frame should be removed.

    row_is_in_reduced_frame() blurred that division: it re-ran
    ensure_reduced_frame() and then get_reduced_frame_status() again,
so consumers
    looked as if they might resolve the match themselves.

    While at it, I found the change to WinGetFuncArgInFrame() hard to
review: the
    new WinGetSlotInFrame() mixes RPR logic into the existing frame
code.  IGNORE
    NULLS already it's own function: ignorenulls_getfuncarginframe().
Similarly we
    can left WinGetFuncArgInFrame() unchanged (same as the master
branch) and moved the RPR logic into a
    dedicated function, WinGetFuncArgInReducedFrame().  That
duplicates some code,
    but the result is much cleaner, and I think the duplication is worth it.

================



--
jian
https://www.enterprisedb.com/

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian, Tatsuo,

> based on https://github.com/assam258-5892/postgres/tree/RPR-20260930
> I have made some non-trivial refactoring in nodeWindowAgg.c, see attached.

Thank you for the refactoring.  Reading it, I came to think that for
the frame we should rethink the design before splitting the code.
There are two reasons.

- SEEK.  Under SEEK a match may start after the current row.  Today
  the reduced frame is laid over the frame on the assumption that it
  always starts at the current row, so there is no place to express
  that case.
- Inverse transition functions.  Today the aggregates of an RPR window
  are recomputed from scratch for every row, even under SKIP TO NEXT
  ROW where the frames of neighboring rows mostly overlap, so the time
  grows with the square of the number of rows.  While the frames
  overlap, the aggregates should be carried forward with the inverse
  transition function, as in an ordinary window.

Both come down to how the reduced frame is represented.

The standard (ISO/IEC 19075-5, 6.10.1) defines the window frame as a
subtractive process.  Starting from the partition, rows are removed
by the frame extent and then by EXCLUDE, which gives the full window
frame.  With row pattern recognition there is one more step: only the
rows mapped by the match remain, and that is the reduced window frame.

So instead of laying the reduced frame over the frame and checking it
separately, we could express it as the frame itself, by narrowing the
frame's start and end to the match.  For a window without RPR the last
step does nothing, so the reduced frame is simply the frame we have
today.  Window functions and aggregates would then only look at the
frame, hardly needing to know about RPR, and the RPR handling now
spread over frame access and aggregation would gather in the one place
that sets the frame positions plus a few short checks.

This settles both reasons.  The core already handles frames that do
not start at the current row (ROWS BETWEEN 1 FOLLOWING AND 3
FOLLOWING) and empty frames.  A match under SEEK can be handled like a
frame starting n rows after the current row, only with n differing
from row to row.  The aggregates take the ordinary moving-aggregate
path.  The only new property of the reduced frame is that its end can
move backward, for example when the next match is shorter under SKIP
TO NEXT ROW, and only then do they need a restart.

Part of your patch already goes this way.  Driving the match only from
ExecWindowAgg() and having everything else read the recorded result is
what this design needs first, since the current row's match has to be
resolved before any frame position is read, and making
WinGetFuncArgInFrame() the same as in master is where this design is
heading too.  The separate RPR accessor, however, is not needed in
this design and would have to be changed again anyway.  So rather
than add it with its duplication, how about taking enough time and
replacing that part with this design?

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

Thank you for 0001 and 0002. Both are clean changes, and I would
like to take them as they are.

> 0001: Remove RPRNavExpr.navno
> navno spans all three stages: ParseRPRNavCall() initializes it,
> compute_define_metadata() compute it while planning, and
> ExecInitExprRec() use it. Tracking and keeping those in sync is
> not trivial.
> It's doable to just remove it.

I like this a lot. The number only existed to find an entry in
rprNavOffsets, which needed the planner and the executor to walk
the navigations in the same order. Registering the entry right in
ExecInitExprRec() while the DEFINE clause is compiled, the way
WindowFunc is registered in winstate->funcs, is the right place
for it: there is nothing left to keep in step, and
nav_offsets_walker() and build_nav_offsets() go away with it.

> 0002: Remove compute_define_metadata
> IMHO compute_define_metadata() is complicated.
> Instead, loop over the DEFINE clause with foreach, run an
> expression walker on each variable's expression to check whether
> it depends on the match start, and if it does, record that
> variable's index.

Agreed. Without navno the context struct and the per-variable
bookkeeping have no job left, and a bool walker with a foreach_node()
loop says the same thing in far fewer lines.

I applied both and checked them: no build warnings, the regression
tests pass (also with debug_copy_parse_plan_trees and
debug_write_read_parse_plan_trees on), and 575 DEFINE shapes give
the same rows, errors, EXPLAIN output and absorption markers as a
build without the patches.

> Let's agree to disagree, at least now, removing
> WindowAggState.nfaStateSize is not performance related.

Fair enough, thank you.

> Also as mentioned in
> https://www.postgresql.org/message-id/688312.1782222788%40sss.pgh.pa.us
> we should use size_t, not using Size

Understood. I will switch the remaining Size uses in the RPR code
to size_t.

Once v54 is posted, I will merge 0001 and 0002 into the patch
series at a relaxed pace, after more quality checks and a more
detailed review.

A small request about naming. Your v54-0001 and v54-0002 share
their names with the series, and each new batch starts again at
0001, so they are hard to tell apart when I merge them. Could you
name your incremental patches by feature and number them within
each feature, for example nocfbot-feat1-0001, nocfbot-feat1-0002
and nocfbot-feat2-0001, so that the series keeps its own numbering?

Best regards,
Henson

Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Hi.

I'd like to remove RPRElemCanExit() and RPRElemCanLoop() and compare
the count with min and max directly.

RPRElemIsVar() and RPRElemIsEnd() are fine, because their names say
exactly what they test.
"Can exit" and "Can loop" don't: to understand them, the reader has to
work out what they mean for the count,
while ``(count < elem->min)`` or ``(count >= elem->max)`` needs no explanation.

Similarly, I also want to remove RPRCountIncrement and RPRElemWithinMax.
---------------
I'm still not convinced by how EXPLAIN shows context absorption (I may have
asked about this before). See append_rpr_quantifier.
The pattern is printed with markers on its elements, "#" for the
comparison point and "~" for the elements inside the absorbable
region,
for example:

   Pattern: (((a~ b~)+# c)+ d)+

This seems odd to me, because the pattern as the user wrote it no longer
appears anywhere in the plan.  The markers are compact, but they are hard to
read for anyone who does not already know the absorption design, and since
they change the pattern text itself, every EXPLAIN output that shows a
pattern carries them.

A single extra line could say the same thing:

   Pattern: (((a b)+ c)+ d)+
   Absorbable Pattern: (a b)+

and for a pattern that cannot be absorbed, the line would simply be absent:

   Pattern: s a+ b

Is there a reason the markers are preferable?



--
jian
https://www.enterprisedb.com/


Re: Row pattern recognition

От:
jian he <jian.universality@gmail.com>
Дата:
Hi.

CREATE VIEW v3 AS
SELECT
FROM (VALUES (1,'A'),(2,'B'),(3,'B')) t(id, v)
WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
  AFTER MATCH SKIP TO NEXT ROW
  PATTERN (A B C | B)
  DEFINE A AS true, b as true, c as true);

\sv v3

PATTERN (A B C | B)
can be interpreted as
PATTERN (A B (C | B))
or
PATTERN ((A B C) | B)

We need extra parentheses to disambiguate it.
(I searched for "parentheses"; it seems this issue has never been discussed.)

Another question:

PATTERN (A  B  ?c)
is interpreted as
PATTERN (A  B?  c)

Maybe one para in select.sgml is enough to explain this, no need to
use parentheses to wrap it as
PATTERN (A  (B?)  c)

While looking at it, i think the below paragraph is not necessary.
The manual is generally not the place to explain implementation
shortcomings, and the RPR documentation is already quite long.

   
    Two planner optimizations are not applied to a window that uses row
    pattern recognition.  A filter on the result of a monotonic window
    function, such as rn <= 3 on
    a row_number() computed in a subquery, is not
    pushed down into the window as a run condition, so the window is
    evaluated to the end of the partition instead of stopping early.  And
    the frame clause is not replaced with a cheaper one, even when the
    window functions using it do not depend on the frame.  Query results
    are not affected, only the cost of evaluating the window.
   



--
jian
https://www.enterprisedb.com/


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian, Tatsuo,

In my mail of 2026-10-22 I wrote:

> So rather than add it with its duplication, how about taking enough
> time and replacing that part with this design?

Jian, your refactoring is what led here.  Once it made ExecWindowAgg()
the only place where the match is resolved and left everything else to
read the result, it became clear that the readers need little beyond
the frame positions.  The rest of this mail follows from that.

Today the reduced frame sits apart from the frame, so techniques core
uses on frames are switched off or worked around for an RPR window.
The results are right, but at a cost:

- Aggregates are restarted on every row, so under SKIP TO NEXT ROW
  an aggregate such as sum() does a number of transitions quadratic
  in the run length, even with an inverse transition function.  The
  reason given is that the reduced frame can change entirely from one
  row to the next; as chapter 4 shows, it changes in only a few ways.
- With UNBOUNDED FOLLOWING the tail of the full frame is computed
  first and then cut to the match, so last_value() spools the whole
  partition into the tuplestore before returning its first row.
- Since the reduced frame is assumed to start at the current row, a
  match that starts later, as SEEK will need, cannot be expressed.

All of these come down to one thing: the frame positions need a new
contract with the code that reads them.

To make this concrete, I have written down how the frame works without
RPR, the contract its readers assume today, and the new one RPR needs.


0. Overview

The idea in one sentence: RPR sets the frame positions, and everything
else keeps reading them as it does today.

- In the executor the frame clause is mostly the input to
  update_frameheadpos() and update_frametailpos().  Window functions
  and aggregates read the result, frameheadpos and frametailpos (H and
  T below); the few places that still derive the end from frameOptions
  are covered in chapter 3.
- So if RPR sets H and T from the match of the current row, most
  readers see the reduced frame without knowing about RPR.
- What remains is moving the readers from what they assume about H and
  T today to a new contract.  Chapter 1 states both; chapters 2 to 7
  go through the differences.
- One item, the order in which rows enter and leave an aggregate's
  state, touches the contract of transition functions.  That one would
  be a separate proposal (chapters 5 and 6).
- The design is also faster, for a few reasons (chapters 4 and 8):
  aggregates with an inverse transition function are carried forward
  across overlapping frames instead of being restarted on every
  row; the frame end comes from the match, so a tail fetch such as
  last_value() does not spool the partition to find it; no frame
  mark lags behind the current row, so frame readers never hold back
  trimming; and empty frames share one precomputed result.

How the chapters fit together: chapter 2 is the base, and chapters
3 and 4 build on it.  As a first step I have in mind these three,
the hook of chapter 7, which needs no code until MEASURES, and the
frame side of chapter 6, H moving backward.  Chapter 5 is for its own
thread, and the match search of SEEK comes after.


1. The frame, end to end

Without RPR, ExecWindowAgg() handles one row like this:

  frame clause          frame positions          readers
  ------------          ---------------          -------
  frameOptions   ---->  frameheadpos (H)  ---->  first_value
  offsets               frametailpos (T)         last_value, nth_value
                          ^                      aggregates
                          |                      row_is_in_frame()
           update_frame*pos(), lazily,
           when a reader first asks

Below, frames are written as the rows they hold, first .. last.  H is
the first row and T the row after the last, as in the code.  The match
of the current row is the L rows M .. M+L-1.

With RPR the arrow into H and T comes from the match instead:

  match of the current row, rows M .. M+L-1  -->  H = M, T = M+L
  no match / empty match / skipped           -->  H = T = current row
                                                  (SEEK: chapter 6)
  (skipped: inside a previous match under SKIP PAST LAST ROW)

This is the last step of the subtractive definition I mentioned before
(ISO/IEC 19075-5, 6.10.1): of the full frame, only the rows mapped
by the match remain.

Core code relies on a few things about H and T.  They are not written
down in one place, but this is the contract the readers assume today:

  C1  H and T are computed from the frame clause, lazily, once per
      row, by update_frame*pos().
  C2  T follows from frameOptions, so a reader may work out the end
      without reading T.
  C3  T never decreases within a partition.
  C4  Rows leave an aggregate's state only at H, earliest first;
      that is what the inverse transition function receives.
  C5  H never decreases, so frame readers never go back before H;
      their marks sit at H or later, and trimming follows them.
  C6  H and T say all there is to know about the frame (EXCLUDE
      aside, which RPR forbids).

Empty frames (H >= T) are fine under all six.  RPR moves the readers
to a new contract:

  C1  H and T are assigned once per row, when the match is     ch. 2
      resolved.
  C2  Readers read T and never work it out from frameOptions;  ch. 3
      only the match search uses the full frame.
  C3  T may decrease from one row to the next.                 ch. 4
  C4  Rows leave an aggregate's state at H; when a non-empty   ch. 4
      frame ends before the last row already aggregated, or
      starts before the first (ch. 6), the state starts over.
      Avoiding that: ch. 5.
  C5  H may decrease under SEEK with a finite frame, so marks  ch. 6
      follow the current row there.
  C6  H and T say all a window function needs about the       ch. 7
      frame; the match status and inputs that depend on the
      match sit beside them.

The shapes RPR forbids (RANGE, GROUPS, EXCLUDE, a start other than
CURRENT ROW, an end other than FOLLOWING) are rejected at parse
analysis, and the planner leaves an RPR window's frame alone.  The
branches that only serve those shapes never run for an RPR window,
so they need no change.


2. Setting H and T: assign, do not update

Core computes H and T lazily and incrementally.  Lazily, because a
tail such as UNBOUNDED FOLLOWING requires reading ahead, up to the
whole partition, so it is put off until a reader asks.  Incrementally,
because under RANGE and GROUPS the bounds advance from where the
previous row left them.

Neither applies to a reduced frame.  H and T are known the moment the
match is resolved, and the NFA has read the rows it needs by then.
Nor can they be derived from the previous row:

  row r     r .................. E
  row r+1     r+1 ........ ?       not necessarily "r+1 .. E"

Under SKIP TO NEXT ROW the match for r+1 runs the pattern from
scratch, so it may end before E, after E, or not exist.  The NFA has
to run it.  (Under SKIP PAST LAST ROW, r+1 is skipped when r's match
covers it, and its frame is empty.)

So they are best assigned where the match is resolved.  In outline:

  ExecWindowAgg        NFA            H/T         functions, aggs
       |                |              |                |
       | advance row    |              |                |
       |--drive match-->|              |                |
       |<--M .. M+L-1---|              |                |
       |--set H, T, valid------------->|                |
       |--evaluate------------------------------------->|
       |                |              |<---read H/T----|

  if (rpr_is_defined(winstate))
  {
      ensure_reduced_frame(winstate);   /* drive the match */
      set_reduced_framepos(winstate);   /* H, T, *_valid = true */
  }
  /* else: core's lazy update_frame*pos() as today */

update_frameheadpos() and update_frametailpos() stay as they are on
master; with the valid flags already set they return immediately,
and for an RPR window they assert so.  H and T can then never be
read for a row whose match is not yet resolved, since they are set
only right after it is.


3. Ends inferred from frameOptions

Four places work out the frame end, or act before checking it,
without reading T:

  row_is_in_frame()      END CURRENT ROW and ROWS offsets are computed
                         on the spot; UNBOUNDED FOLLOWING has no end
                         check at all.
  reuse shortcut         reuses the previous result when the head has
                         not moved, the end is UNBOUNDED FOLLOWING or
                         CURRENT ROW, and the current row lies in the
                         previous frame.
  update_frametailpos()  UNBOUNDED FOLLOWING spools the partition.
  WinGetFuncArgInFrame() a HEAD fetch reads the row first and
                         asks row_is_in_frame() afterwards, so
                         nth_value(x, k) with a large k spools up to
                         row H+k-1 or the end of the partition.  v54
                         compares k with the match length first.

row_is_in_frame() matters most, because aggregates find their
end through it:

  aggregatedupto -->  fetch row, row_is_in_frame()?
                        1: add it   0: skip it   -1: stop

They never look at T.  So for RPR, row_is_in_frame() must return
-1 based on T, or aggregates would run past the match.  The reuse
shortcut assumes the end follows from frameOptions; in v54 it never
fires for RPR only because H moves on every row, so it gets an
explicit guard.  The tail spooling goes away with chapter 2.  The
HEAD fetch keeps the check v54 already has, now against T: for RPR, a
HEAD fetch at or past T is out of frame before any row is read.


4. T moving backward

Empty frames are nothing new.  Core has plenty of them:

  ROWS BETWEEN 7 PRECEDING AND 8 PRECEDING     H = T (the docs say
                                               it never selects rows)
  ROWS BETWEEN 3 PRECEDING AND 5 PRECEDING     H > T
  ROWS BETWEEN 1 FOLLOWING AND 3 FOLLOWING     H = T at the last row
  RANGE offsets with no value in range         H >= T

What is new is that T can go down from one row to the next.  In core
neither H nor T ever goes down within a partition.  Under RPR, with
SKIP TO NEXT ROW:

  PATTERN (A+), rows r to E are A
  r     r .............. E
  r+1     r+1 .......... E     H +1, T stays: one inverse transition

  PATTERN (A B C | B), rows r, r+1, r+2 are A, B, C
  r     r ......... r+2
  r+1     r+1 .. r+1           shorter match: T r+3 -> r+2, backward
  r+2       (empty)            no match starts at C: H = T = r+2

Two places assume that T never goes down:

  - aggregates: the restart test, an assertion that the end never
    moves backward, and skipping rows already aggregated;
  - the mark of a TAIL fetch (last_value) is set at T-1, so a later
    row with a smaller T would fetch before the mark and fail.  v54
    already puts it at H for RPR, and that stays.

Not about T, but in the same code: IGNORE NULLS from the tail marks
row 0 and, when the frame has too few non-null values, walks past H
toward row 0.  Rows before H are outside the frame, so it can stop
at H and mark H.  This is an inefficiency in core, with or without
RPR, and so is leaving the mark behind when an access finds the frame
empty; I will send a separate patch for the core side.

For aggregates the cheap fix is to restart when T moves back.  A
better one keeps the state across empty frames:

  PATTERN ((A B)+), ROWS BETWEEN CURRENT ROW AND 5 FOLLOWING,
  SKIP TO NEXT ROW, rows alternate A B A B ...

  row  frame     restart each time     keep the state
  0    0 .. 5    add 0..5              add 0..5
  1    (empty)   state dropped         keep, empty result
  2    2 .. 7    add 2..7              inverse 0, 1; add 6, 7
  3    (empty)   state dropped         keep, empty result
  4    4 .. 9    add 4..9              inverse 2, 3; add 8, 9
  5    (empty)   state dropped         keep, empty result
  6    6 .. 11   add 6..11             inverse 4, 5; add 10, 11
  per A row      6 forward             2 forward, 2 inverse

A rows start a match that fills the frame and B rows start none, so
frames alternate with empty ones and T falls back on every B row.
When the state is kept, each A row slides the frame by two rows.
With a frame of F rows, restarting costs about F transitions per
A row and keeping the state costs 4, so keeping wins for all but
the smallest frames.

The empty result (the final value of the initial state) is computed
once per aggregate and partition, or for every empty frame when the
final function is volatile.  Beyond the restarts core already makes,
a restart is then needed only when a non-empty frame ends before the
last row already aggregated, as at row r+1 of (A B C | B).  When
DEFINE looks only at a row and its neighbours, this is rare within a
run of a greedy quantifier, since matches that start later mostly end
at the same row or later; it happens with alternatives of different
lengths, or when DEFINE refers to the match start through FIRST().

Where a restart is not forced, it may still be cheaper.  The previous
state and the new frame are both known before the aggregates run:
keeping costs the rows that leave plus the rows that arrive, and
restarting costs the rows that stay plus the rows that arrive.  So
keep when fewer rows leave than stay, and restart otherwise.  Core
frames move a little at a time, so keeping almost always wins there;
RPR frames can jump.

Under SKIP PAST LAST ROW none of this arises: the next match starts
after the current one, so frames never overlap and there is nothing to
carry forward.  So moving aggregation is turned off there, and the
aggregates use their plain transition functions; v54 picks the moving
ones and restarts them on every row.


5. Removing rows at the end: inverse transition functions

To keep the state when a non-empty frame ends before the last row
already aggregated, we would have to remove rows from the end of the
state.  The contract in xaggr.sgml does not allow it: the inverse
function receives "the earliest row included in the current state".
It is a FIFO contract, and the executor trusts it without checking.

For the built-ins, the contract is stricter than needed.  Forty
built-in aggregates have an inverse function (count, sum, avg, the
var and stddev family, bool_and, bool_or, every), and all of them keep
only counts and sums, so none of them cares which row goes out:

  int4_avg_accum_inv:  count--;  sum -= newval;
  bool_accum_inv:      aggcount--;  if (newval) aggtrue--;

numeric's display-scale tracking may refuse a removal (the inverse
returns NULL), but the same way from either end.  A user-defined
aggregate, on the other hand, may rely on FIFO order, say a queue
whose inverse pops the front without looking at its argument.  Nothing
in the catalog tells the two apart.

RPR is not the only feature that would benefit.  Core recomputes
the aggregate for every row under EXCLUDE CURRENT ROW, GROUP or TIES
("we punt and recalculate for every row", eval_windowaggregates()),
because the row to take out is in the middle and the row to put back
comes out of order:

  EXCLUDE CURRENT ROW
  row r      h .. r-1, r+1 .. t
  row r+1    h .. r, r+2 .. t         add r back, take r+1 out

The options I can see:

  A. Change the contract: any row may be removed.  Silently wrong for
     FIFO aggregates that exist today.  No.
  B. A per-aggregate declaration, like FINALFUNC_MODIFY (4de2d4fba38),
     that the state depends only on the set of rows, not on their
     order.  FIFO stays the default; the 40 built-ins are marked.
     Covers EXCLUDE (middle rows, any order) and RPR (removing from
     the end, adding at the front).
  C. A second inverse function for the end.  Lets order-dependent
     aggregates with a deque state remove from both ends, but it
     cannot help EXCLUDE, and only RPR would use it.
  D. One inverse function with a position argument.  Breaks existing
     signatures; under a new name it is C.

B looks right to me, stored as an enum column so that C can be added
later if anyone needs it.  It belongs in its own thread with EXCLUDE
as the motivation, not in this patch.  Until then RPR restarts
in that rare case.


6. H moving backward: SEEK with a finite frame

SEEK is not in v54.  Under SEEK the match of row R is the first one
that starts at or after R.  The frame side of this chapter, H moving
backward, would go in the first step, so that SEEK later only has
to supply the match; the match search itself comes with SEEK.

Under SEEK an empty frame cannot simply sit at the current row: the
previous row's H may already be past it.  It sits at the later of the
two, so H does not go down on that account.

INITIAL keeps H from going down, and as far as I can see so does SEEK
with UNBOUNDED FOLLOWING.  SEEK with n FOLLOWING and SKIP TO NEXT ROW
does not, because the scan end is tied to the output row R (it is
R+n), not to the start of a match:

  n = 2, PATTERN (A B C | B), rows 4, 5, 6 are A, B, C,
  row 3 is neither

  row       3   4   5   6
  R = 3    [3   4   5]          start 4 (ABC) is cut before 6,
                    B           start 5 matches B:  H = 5
  R = 4        [4   5   6]      start 4 completes,
                A   B   C       earlier start wins: H = 4

This reads SKIP TO NEXT ROW as resuming at R+1, which is also what
Trino does.  Taken literally, the standard resumes "at the row after
the first row of the current match" (4.13), and under SEEK that row
is M+1, not R+1: rows R+1 .. M would be skipped (6.11) and H would
never go back.  The wording assumes a match that starts at the
current row, and I think it needs revising for SEEK.  This chapter
follows the R+1 reading.

So marks go at R, which only grows and never passes the H of
any later row.

H moving back pairs with T moving back in chapter 4, and the cheap
answer for aggregates is the same: when H moves before the first row
already aggregated, which core treats as an error, drop the
moving-aggregate state and restart.  In
the example, R = 4 aggregates 4 .. 6 from scratch.

The better answer is to add the earlier rows to the state.  In the
example, the state 5 .. 5 takes 4 at the front and 6 at the end.  This
is the same contract question as chapter 5: a transition function
sees rows in order, so feeding it a row that comes before rows
already aggregated is wrong for an aggregate that relies on order.
Option B of chapter 5, the declaration that the state depends only on
the set of rows, covers this case too; for such an aggregate, adding
a row at the front is an ordinary transition.  Until then aggregates
restart, and chapter 4's comparison of the cost of keeping against
restarting applies as is.


7. What H and T cannot say

Nothing to code for this now; it is where MEASURES will plug in.

MEASURES is written like DEFINE, with the same notation and the same
pattern variables in view, but it is evaluated where window functions
are.  The standard calls a measure with OVER and computes it
positioned on the last row of the match (19075-5, 6.9).  So as far as
the frame goes, a measure is a window function: it is evaluated after
H and T are assigned, over H .. T-1.  What H and T cannot say is
about the match, and two things sit beside them for that:

- The match status.  An empty match and no match both give an empty
  frame, yet COUNT(*) as a measure is 0 for one and null for the
  other (6.16).  So the per-row match status is kept.
- The variable each row maps to.  Under CLASSIFIER() or B.price the
  same row gives different values in different matches: with
  PATTERN (A B+) and SKIP TO NEXT ROW it can be B in the match
  starting at r and A in the one starting at r+1.  So the path the
  NFA chose is handed over.  Overlapping frames then give a row
  different inputs, so moving aggregation cannot apply; a check
  beside the one initialize_peragg() makes for volatile arguments
  turns it off.

Aggregates inside DEFINE are a separate matter.  v54 rejects them for
now, but they are to come later, and under the standard they are
evaluated while the match is being searched, over the rows mapped so
far (running semantics).  So once supported they live inside the NFA
and have nothing to do with the frame.


8. Cost, and what it buys

In v54, nodeWindowAgg.c grows by about 1300 lines.  About 150 of them
lay the reduced frame over the frame (row_is_in_reduced_frame() and
the RPR branches in the accessors, IGNORE NULLS and aggregation).
This design replaces them with the assignment of chapter 2, the
checks of chapters 3 and 4, and the empty-frame handling of chapter
4.  Navigation and the NFA itself are untouched.  The gain is in
shape and in speed.

In shape, the following go away or become exact:

- The clipping to the reduced frame, which today has a different shape
  in each of the two accessors (the plain path and IGNORE NULLS), is
  replaced by the one assignment of chapter 2.  The IGNORE NULLS path
  needs no knowledge of RPR: the T check of chapter 3 sets its end.
  The mark issue of chapter 4 is a core inefficiency unrelated to
  RPR; it only shows up more often under RPR, where empty frames are
  common.
- The workaround that gets past that assertion when T moves back
  goes away.  Empty frames take the precomputed result and never
  reach the aggregation loop, so the assertion holds unless the
  aggregates restart.
- The path that drives the NFA from inside the aggregation loop goes
  away.  It is already unreachable, since ExecWindowAgg() resolves
  the match first, and Jian's v55-0001 removes it as well.
- H and T of a row whose match is not yet resolved cannot be read; an
  attempt fails an Assert.
- The comment saying the inverse transition optimization is
  inapplicable, and the matching text in README.rpr, are rewritten
  along the lines of chapter 4.

The speed comes from mechanisms already in core:

- Aggregates move instead of restarting.  An RPR window restarts
  every aggregate on every row today.  With H and T in place,
  the overlapping frames of SKIP TO NEXT ROW take the ordinary
  moving-aggregate path, for aggregates that have an inverse
  transition function.  For a run of L rows under PATTERN (A+) and
  ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING, where the frames
  are r .. E, r+1 .. E, ...:

                           forward transitions    inverse transitions
    v54 (restart per row)  L + (L-1) + ... + 1    0
    this design            L                      L - 1

  Quadratic per run becomes linear.  Where the frame jumps, so that
  more rows leave than stay, keeping the state costs more than
  restarting; the choice of chapter 4 restarts there, so no row costs
  more transitions than it does in v54.  Under SKIP PAST LAST ROW
  matches never overlap, so moving aggregation is turned off there and
  the plain transition functions run instead.

- Nothing reads past the match.  Today the tail of the full frame
  is still computed before it is cut down to the match, and for
  UNBOUNDED FOLLOWING that spools the whole partition, for example
  for last_value().  T from the match is known from rows the NFA has
  already read, so the tuplestore holds only what the matches need and
  can stay in memory instead of spilling to disk.

- Frame marks never lag behind the current row.  Every frame access
  sets its mark at H (at the current row under SEEK, chapter 6),
  including the IGNORE NULLS fetch from the tail, which today pins
  row 0 and keeps the whole partition.  Only DEFINE navigation, as
  today, and an aggregate state kept across an empty frame hold rows
  before the current row.


I would like to settle this design as the end goal, and adjust in
steps what goes in when.  The first step in chapter 0 is only a
proposal too; whether to go this way at all is what I would like to
hear first.  The aggregate contract of chapters 5 and 6 and the SEEK
match search come after it.  Question 1 is about the goal; 2 and 3
are about the steps.

Questions:

1. Can we take this direction, chapter 2's assignment in place of a
   separate RPR accessor (WinGetFuncArgInReducedFrame()), as the end
   goal?
2. Is it fine to leave the aggregate contract (removing from the end,
   chapter 5; adding at the front, chapter 6) out of the first step
   and raise it in its own thread later?  Until then RPR restarts in
   those cases.
3. For SEEK, is it fine to handle only the frame side in the first
   step (H moving backward, chapter 6) and leave the match search
   for later?

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

> I'd like to remove RPRElemCanExit() and RPRElemCanLoop() and compare
> the count with min and max directly.
...
> Similarly, I also want to remove RPRCountIncrement and RPRElemWithinMax.

I'd rather keep all four.

RPRElemCanLoop() and RPRCountIncrement() are not just names for a
comparison.  A count saturates at RPR_COUNT_INF, which is the same
value as RPR_QUANTITY_INF, so a saturated count compares as
unbounded (README.rpr).  RPRCountIncrement() is the one place that
saturates, and RPRElemCanLoop() checks RPRElemIsUnbounded() first,
so an unbounded quantifier keeps looping after the count has
saturated.  (count >= elem->max) as the stop test gets exactly that
case wrong.  It is only reached after 2^31 iterations, but spelling
the tests out at each call site would mean repeating the saturation
rule everywhere.

RPRElemCanExit() and RPRElemWithinMax() are simpler, but they pair
with the other two.  "Loop" and "exit" are the two ways out of a
quantifier, and a test such as

    if (RPRElemCanLoop(elem, count) && RPRElemCanExit(elem, count))

reads as "both are possible", which the expanded form does not.
RPRElemWithinMax() keeps the same unbounded check as
RPRElemCanLoop(), for the Asserts.

> Is there a reason the markers are preferable?

Yes, three.

First, the Pattern line already shows the pattern after the
optimizer has rewritten it, not as the user wrote it.  For example,
PATTERN ((A B)+ A B (A B)+ A B) is shown as (a b){4,}, and
absorbability is computed on that rewritten form.  So a separate
line would not bring the user's text back either.

Second, the absorbable regions are tied to positions in the
pattern, and there can be more than one.  With alternation, each
branch is checked on its own:

    PATTERN ((A B)+ | (C D)+)
    Pattern: ((a~ b~)+# | (c~ d~)+#)

and the same subpattern can be absorbable in several branches:

    PATTERN (A+ | (A+ B+) | (A+ C+))
    Pattern: (a+# | a+# b+ | a+# c+)

A single "Absorbable Pattern: a+" line cannot say which branches
are absorbable, and a list such as "a+, a+, a+" cannot say which is
which.  Making it say that brings the markers back in words.

Third, the markers are what lets the regression tests check the
analysis itself.  computeAbsorbability() sets two flags per element:
"~" for an element inside a region and "#" for the point where
absorption is decided.  If a "#" ended up on the wrong element, or
a "~" were missing from part of a region, the inline form would
show it in the expected output, while "Absorbable Pattern: (a b)+"
would look the same.  EXPLAIN ANALYZE shows whether contexts were
absorbed, but not where the analysis put the flags.

I agree the markers are not obvious to someone who doesn't know the
absorption design.  How about showing them only with VERBOSE, or
with a separate EXPLAIN option?

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Jian,

> PATTERN (A B C | B)
> can be interpreted as
> PATTERN (A B (C | B))
> or
> PATTERN ((A B C) | B)
>
> We need extra parentheses to disambiguate it.

I don't think it is ambiguous.  In the standard grammar an
alternation is made of terms, and a term is a concatenation of
factors, so concatenation binds tighter than alternation.  It is
the same as in regular expressions, and as a product before a sum
in a * b * c + b.  Our gram.y has the same structure
(row_pattern_alt '|' row_pattern_seq), so A B C | B can only be
read as ((A B C) | B), and the \sv output reads back as the same
pattern.

Both printers rely on this precedence.  pg_get_viewdef() prints
only the parentheses the user wrote, and EXPLAIN brackets each
alternation but not a sequence branch inside it.  Anyone who reads
regular expressions knows this precedence, so I think the current
compact form is better than spelling out every level with
parentheses.

> PATTERN (A  B  ?c)
> is interpreted as
> PATTERN (A  B?  c)
>
> Maybe one para in select.sgml is enough to explain this

This is the standard reading too.  The lexer drops whitespace, so
B? C, B ? C and B ?C give the same tokens, and a quantifier applies
to the element just before it.  Whitespace means nothing in a
pattern except to separate pattern variables, as elsewhere in SQL.
Spacing that invites a misreading is up to whoever writes the
pattern, so I don't think it needs a paragraph of its own.

> While looking at it, i think the below paragraph is not necessary.

That paragraph was added because Tatsuo asked on September 20 to
list those two restrictions, to be fair to people evaluating and
reviewing the RPR patches.  For that purpose there may be a better
place than the manual.  The patch is large, so once the public
review gets going, reviewers will need a guide, and I think it
would be better to collect restrictions like these there, in the
form of an audit report.  The paragraph could then come out of the
manual.  Tatsuo, what do you think?

Best regards,
Henson

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Вложения:
Hi Tatsuo,

> Attached is v54 RPR patches.

Attached are six incremental patches on top of v54, as nocfbot so
that cfbot keeps testing v54 itself.  v54 still applies to master as
it is.

0001 fixes the cfbot failure of v54.  Since "Add memory/disk usage
for Function Scan nodes in EXPLAIN" was committed on 11-10, EXPLAIN
ANALYZE prints a Storage line under Function Scan, and rpr_explain
fails on every platform.  This updates rpr_explain.out and changes
nothing else.

0002-0006 take out of the series what is not specific to RPR:

  0002 Remove the column alias list fix for table functions
  0003 Remove the fix for columns of relations not printed in FROM
  0004 Test the system column name a DEFINE clause reads on a view
       column
  0005 Remove the fix for columns that function result types gained
  0006 Remove EXCLUDE TIES window tests

The three deparse fixes that 0002, 0003 and 0005 remove are bugs in
master as well, so I will submit them upstream on their own.  If
they cause conflicts or need further changes in the series once
they are committed, I will send a follow-up patch then.

0004 rewrites the one rpr_base test that depended on the fix 0005
removes.  0006 drops two window.sql tests that have nothing to do
with RPR.

Since 0001 needs a new version anyway, this seems a good moment to
fold all six into v55.  make check passes with all six applied.

Meanwhile, I am studying the planner side of the patch and auditing
v54 for defects.  I will group what I find by severity and send it
in follow-up mails.

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Вложения:
Hi Henson,

Thank you for the patches.

> Attached are six incremental patches on top of v54, as nocfbot so
> that cfbot keeps testing v54 itself.  v54 still applies to master as
> it is.
> 
> 0001 fixes the cfbot failure of v54.  Since "Add memory/disk usage
> for Function Scan nodes in EXPLAIN" was committed on 11-10, EXPLAIN
> ANALYZE prints a Storage line under Function Scan, and rpr_explain
> fails on every platform.  This updates rpr_explain.out and changes
> nothing else.
> 
> 0002-0006 take out of the series what is not specific to RPR:
> 
>   0002 Remove the column alias list fix for table functions
>   0003 Remove the fix for columns of relations not printed in FROM
>   0004 Test the system column name a DEFINE clause reads on a view
>        column
>   0005 Remove the fix for columns that function result types gained
>   0006 Remove EXCLUDE TIES window tests
> 
> The three deparse fixes that 0002, 0003 and 0005 remove are bugs in
> master as well, so I will submit them upstream on their own.  If
> they cause conflicts or need further changes in the series once
> they are committed, I will send a follow-up patch then.
> 
> 0004 rewrites the one rpr_base test that depended on the fix 0005
> removes.  0006 drops two window.sql tests that have nothing to do
> with RPR.
> 
> Since 0001 needs a new version anyway, this seems a good moment to
> fold all six into v55.  make check passes with all six applied.
> 
> Meanwhile, I am studying the planner side of the patch and auditing
> v54 for defects.  I will group what I find by severity and send it
> in follow-up mails.

OK, attached are the v55 patches based on the v54 plus your 6 patches.

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp

Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo, Jian,

> > Meanwhile, I am studying the planner side of the patch and auditing
> > v54 for defects.  I will group what I find by severity and send it
> > in follow-up mails.

Before I send the fixes, I would like to agree on one design point:
whether, and how, planning keeps the argument of a navigation such as
PREV() from raising an error at plan time.  Section 2 asks you to
choose between two options.  The fix changes how this is implemented,
so I want to explain the change, and the other ways I tried, before
you see the patch.

The problem:

  WITH t(id, v) AS (VALUES (1, 10))
  SELECT count(*) OVER w AS cnt
  FROM t
  WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
               PATTERN (A) DEFINE A AS PREV(v / 0) > 0);

A navigation evaluates its argument only at the row it moves to, and
not at all when there is no such row.  Here the only row has no
previous row, so the query should return 0.  But pull-up replaces v
with 10, and constant folding then raises division by zero at plan
time.

1. Two ways a column becomes a constant

A column in a navigation argument can turn into a constant during
planning in two ways, and they happen in different places.

Substitution.  A step that runs before constant folding puts
something else in the column's place.  These steps are spread over
the planner, and core keeps adding them: virtual generated column
expansion came in v18 (1e4351af329), SupportRequestInlineInFrom in
v19 (b140c8d7a3f).

  a. Subquery, VALUES and constant function pull-up:

       SELECT count(*) OVER w
       FROM (SELECT 1 AS id, 10 AS v) t
       WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                    PATTERN (A) DEFINE A AS PREV(v / 0) > 0);

     and the same with the VALUES of the opening example, or with
     FROM abs(10) AS t(v).

  b. Join alias expansion, where a merged column carries the constant
     of one side:

       CREATE TABLE rj (k bigint);
       INSERT INTO rj VALUES (10);
       SELECT count(*) OVER w
       FROM (SELECT 10 AS k) a LEFT JOIN rj USING (k)
       WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                    PATTERN (A) DEFINE A AS PREV(k / 0) > 0);

  c. Virtual generated columns with a constant expression:

       CREATE TABLE gv (id int, g int GENERATED ALWAYS AS (10) VIRTUAL);
       INSERT INTO gv (id) VALUES (1);
       SELECT id, count(*) OVER w FROM gv
       WINDOW w AS (ORDER BY id
                    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                    PATTERN (A) DEFINE A AS PREV(g / 0) > 0);

Simplification inside constant folding.  eval_const_expressions()
itself drops the column while it simplifies, and what is left is
then evaluated as a constant.  The output below is from v55.

  d. Inlining of a SQL function that does not use its argument:

       CREATE FUNCTION f_drop(x int) RETURNS int
         LANGUAGE sql IMMUTABLE AS 'SELECT 1 / 0';
       CREATE TABLE nt (id int, v int);
       INSERT INTO nt VALUES (1, 10);
       SELECT id, count(*) OVER w FROM nt
       WINDOW w AS (ORDER BY id
                    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                    PATTERN (A) DEFINE A AS PREV(f_drop(v)) > 0);
       ERROR:  division by zero
       CONTEXT:  SQL function "f_drop" during inlining

  e. IS NULL on a NOT NULL column, reduced by a not-null proof, which
     came in v19 (e2debb64380):

       CREATE TABLE nn (id int, v int NOT NULL);
       INSERT INTO nn VALUES (1, 10);
       SELECT id, count(*) OVER w FROM nn
       WINDOW w AS (ORDER BY id
                    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
                    PATTERN (A)
                    DEFINE A AS PREV(1 / (v IS NULL)::int) > 0);
       ERROR:  division by zero

The same happens with COALESCE(1, v), CASE WHEN true THEN 1 ELSE v
END, v > 0 AND false, a strict function given a null, a field taken
from a row, and a null test on a row.

How it has been handled so far:

  - Up to v53, the argument folded like any other expression, so
    every query above raised.
  - v54 and v55 guard the substitutions: pull-up, join alias
    expansion and virtual generated column expansion wrap the
    replacement in a PlaceHolderVar, so a, b and c return 0.  The
    second kind is left open, and d and e still raise.

The wrapping for join aliases also crashes or fails with internal
errors when a join alias is expanded below its join level, as when a
merged JOIN USING column is passed to an inlined SQL function:

  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;
  server closed the connection unexpectedly

On an assert-enabled build an assertion in alias_relid_set() fails:
the PlaceHolderVar is made at level zero with relids of the outer
query, so the function body reads them against its own range table.
Item 3 of my Oct 9 mail [1] is an internal error from the same
wrapping, and other shapes fail with other internal errors.

2. Should planning avoid the error at all?

One question comes before the proposal.

Folding does not change a result: a folded value is the value
execution would compute.  The one exception is a navigation that
falls outside the partition, or outside the match for FIRST and
LAST, and returns NULL without evaluating its argument.  If that
argument folds at plan time and raises, the error stands where
execution would have given that NULL.  This is the only case where a
plan-time error matters, and the opening example is one.

The v inside PREV() is the v of the previous row, and the only row
has none, so that v is not even NULL or UNKNOWN: it does not exist.
PREV() must then return NULL without evaluating its argument, so the
answer is 0.  Putting 10 in place of v and folding at plan time
evaluates the argument it must not evaluate, and raises.  With
option 1 below it raises; with option 2 it returns 0.

So there are two ways to go:

  1. Accept the plan-time error.  Remove the PlaceHolderVar wrapping,
     which also fixes the crash above, and document that the argument
     may fold at plan time.  The planner needs nothing else.
  2. Keep that NULL.  This is the proposal in section 3.  It costs a
     pre-pass in eval_const_expressions(), and care when that code
     changes.

Strictly, only option 2 gives the correct result.  Whether so small
a difference is worth the added code and its maintenance is a
matter of judgment, and I would like your call on it.  The rest of
this mail describes option 2, so that you can weigh it.

3. Proposal for option 2

The fix folds a navigation argument in DEFINE in two passes, one on
each side of the substitutions:

  - Before any substitution, a pre-pass folds each navigation
    argument as usual, except for the simplifications that can make
    a column disappear: inlining a SQL function that does not use
    its argument; COALESCE, CASE, AND and OR dropping an argument
    that reads a column when another argument is a deciding
    constant; a strict function given a null, a field taken from a
    row and a null test on a row; and not-null proofs.
  - After the substitutions, the main pass does below a navigation
    argument only the simplifications the pre-pass left out, and
    evaluates nothing.

Outside navigation arguments, folding is the same as before.

The comment in preprocess_expression() says that every expression
must go through eval_const_expressions(), because that is where named
arguments become positional and default arguments are filled in.  A
navigation argument still goes through all of that; only the
evaluation step is left out.

A substitution puts in either an expression over the same row or a
value that is the same on every row, so deferring the evaluation to
execution gives the same result.  Nothing is wrapped in a
PlaceHolderVar, so the join alias crash of section 1 cannot happen.

A change to the substitutions cannot introduce a defect: a new step
that replaces columns needs nothing, as long as it runs between the
two passes.  Only a change to the constant folding code in clauses.c
can.  A new place that evaluates must, as in the main pass, evaluate
nothing below a navigation argument, and a new simplification that
drops a column must be left out of the pre-pass.

4. Step by step

A separate commit makes EXPLAIN print the DEFINE conditions on a
Define line after the Pattern line; the Define lines below are its
output.

The opening example with 2 * 3 added, PREV(v / 0 + 2 * 3) over the
WITH VALUES, is a substitution by pull-up:

  1. The pre-pass folds 2 * 3, giving PREV(v / 0 + 6).  A 1 / 0
     written in the argument, as in PREV(v + 1 / 0), raises here.
  2. Pull-up of the VALUES puts 10 in place of v, giving
     PREV(10 / 0 + 6).
  3. The main pass expands join aliases, inlines SQL functions in
     expressions and simplifies, but evaluates nothing below a
     navigation argument:

       Define: a AS (PREV(((10 / 0) + 6)) > 0)

     On the only row PREV() points outside the partition, so the
     query returns 0.

PREV(g / 0 + 2 * 3) over table gv of case c in section 1, where g is
the virtual column generated as 10, is a substitution:

  1. The pre-pass folds 2 * 3, giving PREV(g / 0 + 6).
  2. Virtual generated column expansion puts 10 in place of g, giving
     PREV(10 / 0 + 6).
  3. The main pass again evaluates nothing below the navigation
     argument:

       Define: a AS (PREV(((10 / 0) + 6)) > 0)

     At execution, on a single row PREV() points outside the
     partition, so its argument is never evaluated, while
     LAST(g / 0 + 2 * 3) on the same row lands on that row and raises
     then.

PREV(f_drop(v)) over table nt of case d, where v is an ordinary
column, is a simplification:

  1. f_drop() does not use its argument, so the pre-pass does not
     inline it.
  2. Nothing replaces v.
  3. The main pass inlines f_drop(v) and leaves the result
     unevaluated:

       Define: a AS (PREV((1 / 0)) > 0)

PREV(f_inc(v)) over the same table nt, where f_inc(x) returns
x + 2 * 3, inlines a SQL function that uses its argument:

  1. The pre-pass inlines f_inc(v) and folds 2 * 3, giving
     PREV(v + 6).
  2. Nothing replaces v.
  3. The main pass evaluates nothing below the navigation argument:

       Define: a AS (PREV((v + 6)) > 0)

     Over the VALUES of the opening example, pull-up puts 10 in place
     of v at step 2, and PREV((10 + 6)) is left for execution.

PREV(1 / (v IS NULL)::int) over table nn of case e, where v is NOT
NULL:

  1. The pre-pass uses no not-null proof, and every other part reads
     v, so nothing folds and the argument stays as written.
  2. Nothing replaces v.
  3. The main pass reduces v IS NULL to false by the not-null proof,
     but leaves the cast and the division unevaluated:

       Define: a AS (PREV((1 / (false)::integer)) > 0)

PREV(COALESCE(1 + 1, v) + 1) IS NULL over table nt shows both passes:

  1. The pre-pass computes the written 1 + 1 to 2 but keeps v after
     it, giving PREV(COALESCE(2, v) + 1).
  2. Nothing replaces v.
  3. The main pass reduces COALESCE(2, v) to 2, but leaves 2 + 1
     unevaluated:

       Define: a AS (PREV((2 + 1)) IS NULL)

     Folding 2 + 1 to 3 there would be sound, but the main pass has
     no way to tell it from 2 / 0: both are calls on constants, and
     nothing records which functions cannot raise, so it evaluates
     neither.

The navigation argument code in var.c, rewriteManip.c, rewriteManip.h
and prepjointree.c goes away; what replaces it is in clauses.c and
planner.c, with a declaration in optimizer.h.  README.rpr gets a
section on the two passes.

5. What I tried on top of the v55 code, and did not send

  - Refusing to pull up an RTE that a navigation argument reads.  It
    covers only part of the first kind: it keeps the subquery and
    changes the plan of the whole query, it does not help virtual
    generated columns or inlining in FROM, and it does nothing for
    the second kind.  DEFINE is evaluated only in the window node and
    plays no part in choosing scans or joins, so keeping the subquery
    costs more than it protects.
  - On top of that refusal, a guard for each case as it was found:
    no inlining and no not-null proofs inside a navigation argument
    at all, and handling of its own for constant virtual generated
    columns.  It treats the second kind like the first: each guard
    gives a simplification up for good, one guard per case found,
    and the audit found d and e only one at a time.
  - Without a pre-pass, not folding a navigation argument in DEFINE
    at all, or simplifying it without evaluating anything.  Either
    covers both kinds, but written constants stop folding too:
    PREV(v + 2 * 3) stays as written, and the multiply is evaluated
    again at every row.

None of these was satisfactory.  Each either stopped more folding
than it should, or left a path open.

6. What still folds

The pre-pass runs before any substitution, so a value given in the
argument itself -- written, bound, or passed into a SQL function's
body -- is folded and may raise at plan time, inside a navigation as
outside:

  - PREV(v + 1 / 0)
  - PREV(v + $1 / 0) under a custom plan, as with PREPARE
  - PREV(v + x / 0) in the body of a SQL function f(x int), called
    as f(10)
  - PREV(f_err(v)), where f_err(x) returns x + 1 / 0: the function
    uses its argument, so the pre-pass inlines it and folds 1 / 0

In the same mail [1] I asked whether such a function parameter
should count as an outer reference.  With this fix it does not: it
is a value passed into the body, and it folds like $1.

With option 1 the fix will come in my next mail as two commits,
removing the wrapping, with tests for the shapes that crashed or
failed, and showing DEFINE in EXPLAIN; with option 2 as three,
adding the folding described here, with regression tests for a to e.

[1] https://postgr.es/m/CAAAe_zBno3aWzkJ6iu-Qsj-wniF+j+i3crZRs9DX9UCZZjG_Xg@mail.gmail.com

Best regards,
Henson

Re: Row pattern recognition

От:
Tatsuo Ishii <ishii@postgresql.org>
Дата:
Hi Henson,

> Before I send the fixes, I would like to agree on one design point:
> whether, and how, planning keeps the argument of a navigation such as
> PREV() from raising an error at plan time.  Section 2 asks you to
> choose between two options.  The fix changes how this is implemented,
> so I want to explain the change, and the other ways I tried, before
> you see the patch.
> 
> The problem:
> 
>   WITH t(id, v) AS (VALUES (1, 10))
>   SELECT count(*) OVER w AS cnt
>   FROM t
>   WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
>                PATTERN (A) DEFINE A AS PREV(v / 0) > 0);
> 
> A navigation evaluates its argument only at the row it moves to, and
> not at all when there is no such row.  Here the only row has no
> previous row, so the query should return 0.  But pull-up replaces v
> with 10, and constant folding then raises division by zero at plan
> time.

With v55 I don't see the error?

test=#\i test.sql
  WITH t(id, v) AS (VALUES (1, 10))
  SELECT count(*) OVER w AS cnt
  FROM t
  WINDOW w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
               PATTERN (A) DEFINE A AS PREV(v / 0) > 0);
 cnt 
-----
   0
(1 row)

Regards,
--
Tatsuo Ishii
SRA OSS K.K.
English: http://www.sraoss.co.jp/index_en/
Japanese:http://www.sraoss.co.jp


Re: Row pattern recognition

От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Tatsuo,

> With v55 I don't see the error?

Right, v55 returns 0.  As section 1 says under "How it has been
handled so far", v54 and v55 wrap what pull-up, join alias expansion
and virtual generated column expansion put in, in a PlaceHolderVar,
so this example and a, b and c return 0.  The example shows the
problem without that wrapping.

But the wrapping fixes it the wrong way.  When a join alias is
expanded below its join level, as in the JOIN USING example in the
same section, the backend crashes, and other shapes fail with
internal errors.  So the wrapping has to go either way, and that
leaves two ways:

  1. Remove the wrapping and accept the division by zero at plan
     time.
  2. Remove the wrapping and go with the other fix in section 3,
     folding in two passes.

Section 2 of my last mail asked you to choose between these two.
Which would you prefer, or do you see a better way?

Best regards,
Henson
FAQ