Unsupported query shape with score() + NOT EXISTS only on generic plan (5th+ execution)
What happens?
What is wrong?
When using ParadeDB's pg_search extension with combined paradedb.score() + correlated NOT EXISTS I have error "Unsupported query shape".
It only appears once PostgreSQL switches a prepared statement from a custom to a generic plan (5th+ execution).
This is separate from #6022/#6239
We included a workaround, so users with this same issue may continue using ParadeDB extension
Environment
- PG extension ParadeDB
pg_search0.25.10 (also reproduced on 0.21.16, before upgrading — upgrading did not fix it) - PostgreSQL 18.6 (Ubuntu 18.6-1.pgdg24.04+2)
- Client:
asyncpg0.30.0 (Python), but this looks server-side / plan-shape driven, not client-specific —asyncpgjust happens to prepare+reuse each unique query text per connection, which is what exposes the custom→generic plan switch
Summary
In our production table (~4,400 rows, rag.chunks, one bm25 index over a text column), this query shape:
SELECT chunk_uuid, paradedb.score(chunk_uuid) AS score
FROM rag.chunks
WHERE texto @@@ $1
AND library_uuid = $2
AND NOT EXISTS (
SELECT 1 FROM rag.library_documents ld
WHERE ld.document_uuid = rag.chunks.doc_uuid
AND ld.library_uuid = rag.chunks.library_uuid
AND NOT ld.ativo
)
ORDER BY score DESC
LIMIT $3The above SQL script reliably works for the first 5 executions of the prepared statement on a session, then fails on the 6th and every following execution with:
ERROR: Unsupported query shape. Please report at https://github.com/paradedb/paradedb/issues/new/choose— with the exact same query text and parameter types each time (only the literal parameter values change: different search terms / library ids). This lines up with PostgreSQL's default plan_cache_mode=auto: a prepared statement is planned with a custom plan (built against the actual parameter values) for its first 5 executions; from the 6th on, PostgreSQL evaluates whether a generic plan (built without knowledge of the parameter values) is cheap enough to reuse, and once it decides to switch, every subsequent execution reuses that generic plan.
SET plan_cache_mode = force_custom_plan on the session makes the failure disappear completely — we ran 50+ consecutive executions of the same query after setting it, zero failures. That's strong evidence the custom-scan / query-shape detection behind paradedb.score() handles the custom-plan case but not the (structurally different, param-less) generic-plan case.
This looks related to #6022 (score() + correlated EXISTS/join filter), which was closed via #6239 — but that fix does not cover this: we hit this on 0.25.10, which already includes #6239. Reading the PR, #6239's fix eliminates non-determinism in the custom-plan join ordering; it doesn't appear to address the generic-plan path at all.
Why this is easy to miss (and possibly why it's unreported so far)
Any one-off reproduction attempt — a fresh psql session, a short script, a new connection per test — always prepares the statement fresh, which always gets a custom plan for its first (and often only) execution on that connection, so it never hits this. It only shows up on long-lived connections that execute the same query text repeatedly with different parameter values (an application connection pool being the obvious case), where the 5-execution threshold gets crossed as a matter of course. We only found this after our own multiple isolated repro attempts (fresh connections, new scripts) kept failing to reproduce a bug we could see happening reliably in production — until we tried looping the same connection.
WORKAROUND
We found a workaround, to be used in the same session:
SET plan_cache_mode = force_custom_plan;
-- all subsequent executions of the same query succeed indefinitelyThis solves the issue.
To Reproduce
Reproduction (against our real table — see note below on a minimal synthetic attempt)
import asyncpg, datetime
conn = await asyncpg.connect(...)
SQL = """
SELECT chunk_uuid, paradedb.score(chunk_uuid) AS score
FROM rag.chunks
WHERE texto @@@ $1 AND library_uuid = $2
AND NOT EXISTS (
SELECT 1 FROM rag.library_documents ld
WHERE ld.document_uuid = rag.chunks.doc_uuid
AND ld.library_uuid = rag.chunks.library_uuid
AND NOT ld.ativo
)
ORDER BY score DESC
LIMIT $3
"""
for i in range(1, 12):
try:
rows = await conn.fetch(SQL, 'some search terms', 'my-library', 10)
print(i, 'OK', len(rows))
except Exception as e:
print(i, 'FAILED', e)
# Output:
# 1 OK 10
# 2 OK 10
# 3 OK 10
# 4 OK 10
# 5 OK 10
# 6 FAILED Unsupported query shape. Please report at ...
# 7 FAILED Unsupported query shape. Please report at ...
# ... (fails from here on, forever, same connection)Workaround, same session:
SET plan_cache_mode = force_custom_plan;
-- all subsequent executions of the same query succeed indefinitelyOn a minimal synthetic repro
We tried to shrink this to a small, self-contained table+index anyone could paste in. A ~1,000-row synthetic table with a trivial bm25 index and the same query shape (including the correlated NOT EXISTS over a second small table) did not reproduce the failure at all — 9+ consecutive executions all succeeded, custom or generic plan. Scaling the synthetic table up to ~4,500 rows with more varied text content did reproduce a failure, but the failure pattern was different from what we see in production: it failed from the very first execution (not the 6th), and on some executions we got a second, distinct error instead:
ERROR: unrecognized node type: 1871472656which we haven't investigated further. We're flagging this because it suggests "Unsupported query shape" (and this generic/custom-plan-triggered variant specifically) may cover more than one underlying condition, sensitive to table size/cardinality/planner cost estimates in ways we don't fully understand yet — so we don't want to claim a clean minimal repro we can't back up. Our production case (above) is the one we can reproduce 100% reliably, and we're happy to share more about our actual schema/query/data distribution, run additional EXPLAIN variants, or test candidate fixes against it if that's useful.
We do have the EXPLAIN of the working custom plan (5 executions on our real table), for reference:
Limit (cost=1017.11..1018.48 rows=10 width=20)
-> Nested Loop Anti Join (cost=1017.11..1279.67 rows=1913 width=20)
Join Filter: (ld.document_uuid = chunks.doc_uuid)
-> Gather Merge (cost=1017.11..1243.95 rows=1962 width=77)
Workers Planned: 2
-> Sort (cost=17.08..17.46 rows=153 width=77)
Sort Key: (paradedb.score(chunks.chunk_uuid)) DESC
-> Parallel Custom Scan (ParadeDB Base Scan) on chunks (cost=10.00..11.53 rows=153 width=77)
Table: chunks
Index: rag_chunks_bm25_idx
Segment Count: 3
Exec Method: NormalScanExecState
Scores: true
Tantivy Query: {"boolean":{"must":[{"heap_filter":{"indexed_query":{"boolean":{"must":[{"with_index":{"query":{"parse_with_field":{"field":"texto","query_string":"...","lenient":null,"conjunction_mode":null}}}}]}},"always_filters":[{"heap_filter":"(library_uuid = '...'::text)"}]}}]}}
-> Materialize (cost=0.00..1.50 rows=1 width=58)
-> Seq Scan on library_documents ld (cost=0.00..1.50 rows=1 width=58)
Filter: ((NOT ativo) AND (library_uuid = '...'::text))We weren't able to get EXPLAIN (GENERIC_PLAN) to run through asyncpg's extended query protocol to compare directly (it kept trying to bind parameter values); happy to get that via psql if it'd help and someone can point us at the right invocation.
Expected behavior
paradedb.score() combined with an extra predicate should produce a supported query shape regardless of whether PostgreSQL chooses a custom or a generic plan for the underlying prepared statement — or, if a generic plan is fundamentally incompatible with the current custom-scan implementation, ParadeDB should make the planner avoid a generic plan for such queries (e.g. by costing the custom scan path in a way that keeps plan_cache_mode=auto from ever picking a generic plan for it), rather than surfacing a runtime error only once a real application's connection pool happens to cross the 5-execution threshold.
Related
- #6022 (closed via #6239) — same general symptom, but appears to be the custom-plan / join-ordering case specifically; doesn't cover what we're seeing here.
- #6417 — different trigger (redundant predicate eliminated inside an
OR).
OS:
Linux Ubuntu 24.04.01 7.0.0-34-generic x64
ParadeDB Version (e.g. output of SELECT * FROM paradedb.version_info();):
0.25.10 - pg_search extension
Are you using ParadeDB Docker, Helm, or the extension(s) standalone?
ParadeDB pg_search Extension
Full Name:
Alesssandro Borges
Affiliation:
CGU
Did you include all relevant data sets for reproducing the issue?
Yes
Did you include the code required to reproduce the issue?
- Yes, I have
Did you include all relevant configurations (e.g., CPU architecture, PostgreSQL version, Linux distribution) to reproduce the issue?
- Yes, I have
Source: paradedb/paradedb