BUG #19885: pg_input_is_valid(tsquery) throws stack depth error instead of returning false

Started by PG Bug reporting form11 days ago2 messagesbugs
Jump to latest
#1PG Bug reporting form
noreply@postgresql.org

The following bug has been logged on the website:

Bug reference: 19885
Logged by: Noah
Email address: imchifan8@gmail.com
PostgreSQL version: 18.6
Operating system: Linux/amd64
Description:

pg_input_is_valid() throws SQLSTATE 54001 while validating a deeply
parenthesized tsquery when max_stack_depth is 100kB. Ordinary malformed
tsquery input returns false through the soft-error interface, but the
recursive nesting path raises “stack depth limit exceeded.” Both inputs are
invalid, so pg_input_is_valid() should return false for both rather than
letting the input function's error escape.

How to repeat:

Save the following as case.sql and run it with `psql -X -f case.sql`:

```
\set ON_ERROR_STOP on
SET max_stack_depth = '100kB';

DO $case$
DECLARE
result boolean;
BEGIN
-- Control: ordinary bad input is reported through the soft-error API.
BEGIN
result := pg_input_is_valid(
'word &',
'tsquery');
RAISE NOTICE 'control=returned value=%', result;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'control=threw sqlstate=% message=%',
SQLSTATE, SQLERRM;
END;

-- Candidate: equivalent user-controlled complexity through recursion.
BEGIN
result := pg_input_is_valid(
repeat('(', 1000) || 'word' || repeat(')', 1000),
'tsquery');
RAISE NOTICE 'nested=returned value=%', result;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'nested=threw sqlstate=% message=%',
SQLSTATE, SQLERRM;
END;
END
$case$;

RESET max_stack_depth;
```

The recorded result was:

```
SET
NOTICE: control=returned value=f
NOTICE: nested=threw sqlstate=54001 message=stack depth limit exceeded
DO
RESET
```

The issue was reproduced on PostgreSQL 18.6 on Linux/amd64. The server
remained available after the statement, and no server-log error accompanied
the caught exception. This occurs when pg_input_is_valid checks a deeply
parenthesized tsquery under a low max_stack_depth setting.

#2Tom Lane
tgl@sss.pgh.pa.us
In reply to: PG Bug reporting form (#1)
Re: BUG #19885: pg_input_is_valid(tsquery) throws stack depth error instead of returning false

PG Bug reporting form <noreply@postgresql.org> writes:

pg_input_is_valid() throws SQLSTATE 54001 while validating a deeply
parenthesized tsquery when max_stack_depth is 100kB.

I do not think this is a bug. pg_input_is_valid() does not promise
to avoid throwing a hard error for resource-exhaustion cases.
As a counterexample, if you hit OOM while constructing the input
string, it'd fail before ever reaching pg_input_is_valid().
Also, if we were to accept this as a case that should be handled,
there are many many more in the same class.

regards, tom lane