Review
Add tsmatch JSONPath operator for granular Full Text Search (v6)
- Proposal version
- 6
- CommitFest entry
- 6436
- Base commit
- 412848dac37f2e4455e1505f83f0af0f3d28a67d
Summary
The patch adds a tsmatch predicate to the jsonpath language
(expr tsmatch "tsquery" [tsconfig "name"] [tsqparser "pl"|"ph"|"w"])
that runs a full-text search match on each JSON string reached by a
path expression, modelled on like_regex. The motivation (per-object
FTS inside a filter, combinable with other predicates) is reasonable,
but the v6 implementation is not committable and the design has an
unresolved problem. I found four real bugs: a deterministic
wrong-results bug caused by caching the compiled tsquery under the
stack address of the current item; a jsonpath on-disk format break
(the new item type is inserted in the middle of JsonPathItemType,
so stored jsonpath values from a pre-patch cluster crash the server
or silently change meaning after pg_upgrade); a deparse regression
that makes every top-level like_regex predicate print without its
closing parenthesis (breaking pg_dump/restore of existing views);
and an unescaped tsconfig string in the printer. Independently of
the bugs, tsmatch makes the IMMUTABLE jsonb_path_* functions and
@?/@@ operators depend on default_text_search_config and on
search_path, which produces stale prepared-statement results and
inconsistent expression indexes, and JSON_EXISTS with tsmatch is
accepted in generated columns. The thread never discussed this.
What was reviewed
- Series: v6, 1 patch, from message CA+v5N432xJwp7MYLU2Gau3XkUFE6cgKDbS7fOFycKvZUdH-9MQ@mail.gmail.com (CommitFest entry 6436), author Florents Tselai.
- Applied on: 412848dac37f2e4455e1505f83f0af0f3d28a67d ("Treat any
negative ws_file as closed in xlogreader.c", master), cleanly (the
cfbot commit 523fc70a807 cherry-picks without conflict). The
original v6 attachment from the list does not apply with
git amon either the bot's base (061065e28f0) or current master: the hunk in src/backend/utils/adt/jsonpath_exec.c that deletes a blank line before thedefault:label ofexecuteBoolItem()has context from before f9fc9a78a36 ("Fix -Wshadow=local warnings", which renamedrestojper).patch -p1applies it with fuzz 2 and the resulting tree is byte-identical to the cfbot commit, so the bot's branch is what was reviewed. The hunk itself is a gratuitous whitespace change and should be dropped. - Built: meson,
-Dbuildtype=debug -Dcassert=true -Dinjection_points=true -Dtap_tests=enabledwith lz4, zstd, liburing, libnuma, icu and-Wtype-limits -Werror=missing-braces. New warnings: none. The grammar has%expect 0and bison reports no conflicts. A second build with-Dbuildtype=release -Dcassert=falsewas used for timing. - Ran:
meson test --suite setup --suite regress: 239/239 subtests passed, including the patch's additions tojsonpathandjsonb_jsonpath.xmllint --validon the patched documentation (thepostgres-full.xmltarget) passes. pgindent on the touched C files and header produces no diff. Ad-hoc SQL: keyword/key-name interaction, deparse round trips, lax/strict and non-string operands, error paths under@?andsilent => true, GUC andsearch_pathdependence, prepared statements, expression indexes, generated columns, GIN (jsonb_opsandjsonb_path_ops) plans and results, a simulated pg_upgrade of stored jsonpath values, and a 200k-row timing comparison. Results are below.
Motivation and scope
The use case is searching text inside nested JSON while keeping the
association between fields of the same object, e.g.
$.comments[*] ? (@.user == "Alice" && @.body tsmatch "performance").
Today one either flattens the document with jsonb_to_tsvector
(loses structure) or unnests with jsonb_array_elements /
jsonb_path_query in a LATERAL join (precise, verbose). The commit
message calls the LATERAL approach "high memory overhead"; the
author's own v1 benchmark (tsmatch_bench.out) shows the LATERAL
variant running faster than tsmatch (1055 ms vs 1324 ms on 1M
rows), and my measurements agree (see Performance). So the benefit
is expressiveness and the ability to combine the FTS test with other
predicates inside one filter, not performance.
Scope: three new jsonpath keywords, one new grammar production, a new
JsonPathItemType, binary (on-disk) encoding and decoding, printer,
executor, docs and tests; about 600 lines. The feature is not part
of SQL/JSON (ISO/IEC 9075-2); the author says so and nobody on the
thread discussed whether a non-standard, catalog-dependent predicate
belongs in the core jsonpath grammar. Since the jsonpath grammar is
not extensible, an extension cannot add such a predicate, so "core
or nothing" is the real choice; that argues for getting the design
right rather than for accepting it as is.
Design and alternatives
like_regex is a self-contained predicate: the pattern and flags
are literals, the regex is compiled and validated at jsonpath input
time (makeItemLikeRegex), and evaluation depends on nothing outside
the datum. tsmatch is different in every one of those respects:
- The text search configuration is resolved by name at execution
time via
get_ts_config_oid(stringToQualifiedNameList(...)), i.e. throughsearch_path, or, whentsconfigis omitted, from thedefault_text_search_configGUC viagetTSCurrentConfig(). - The tsquery is parsed at execution time (
to_tsquery_byidand friends), once perexecuteJsonPath()call, i.e. once per row. - The predicate's result depends on catalog contents (dictionaries,
configuration mappings), which is the same caveat the existing
to_tsvector(regconfig, text)family carries and is acceptable; the GUC andsearch_pathdependence is new.
All jsonpath SQL functions (jsonb_path_exists, jsonb_path_match,
jsonb_path_query*) and the @?/@@ operators are IMMUTABLE. The
existing solution for the analogous time-zone problem is the _tz
function family (STABLE) plus a hard error in the non-tz functions
when a conversion would need the session time zone
("cannot convert value from %s to %s without time zone usage"), and
jspIsMutable() so that JSON_EXISTS() etc. are classified STABLE
by contain_mutable_functions(). The patch does neither: it adds
jpiTsMatch to jspIsMutableWalker() as a non-mutable node and
provides no way for the IMMUTABLE functions to refuse a
session-dependent evaluation. The observable consequences are in
Correctness, finding 3. Options a redesign would have to choose
among:
- Require
tsconfigand resolve the name to an OID at jsonpath parse time, storing the OID (or the fully-qualified name) in the datum, asregconfiginput does. That makesjsonpath_incatalog-dependent (it is IMMUTABLE today and used in constant folding), and the stored form has pg_dump/pg_upgrade implications. - Keep run-time name resolution but treat any
tsmatchas mutable: makejspIsMutableWalker()setcxt->mutable, and make the IMMUTABLE jsonpath functions raise an error when they hitjpiTsMatch, with STABLE variants (as for_tz) that allow it. This is honest but meanstsmatchcannot be used in expression indexes at all, which removes much of the point. - Resolve the configuration name through
search_pathat run time but document it as "as stable asto_tsvector(text)" and mark the operators accordingly. Not possible without new STABLE operators.
None of these was discussed. The syntax also deserves discussion:
tsqparser with the magic strings "pl", "ph", "w" is cryptic
compared to, say, parser "websearch"; the comparison is
case-insensitive but the documentation does not say so; and tsmatch
operates on the document side with to_tsvector, so the configured
parser is used both for the document and the query, which is fine
but should be stated.
The author's claim in the commit message that caching is "respecting the stability requirements of prepared statements" is the opposite of what happens (finding 3c).
Correctness
1. Wrong results: compiled tsquery cached under a stack address
Location: src/backend/utils/adt/jsonpath_exec.c, executeTsMatch().
foreach(lc, cxt->tsmatch_cache)
{
JsonTsMatchCacheEntry *entry = (JsonTsMatchCacheEntry *) lfirst(lc);
if (entry->jsp_ptr == (void *) jsp)
jsp is the JsonPathItem * that executeBoolItem() received, and
for every nested item that is the address of a local variable
(larg/rarg) in the caller's stack frame (jspGetLeftArg(jsp, &larg); executeBoolItem(cxt, &larg, ...)). Two different tsmatch
nodes evaluated at the same stack depth within one
executeJsonPath() call therefore get the same key, and the second
one silently reuses the first one's compiled tsquery (and
configuration OID). Deterministic reproducer, no table needed:
select jsonb_path_match('{"a":"xxx","b":"banana"}',
'!($.a tsmatch "apple") && !($.b tsmatch "banana")');
-- returns t; b matches "banana", so the answer must be f
select jsonb_path_match('{"a":"xxx","b":"banana"}',
'!($.a like_regex "apple") && !($.b like_regex "banana")');
-- f (correct)
Other shapes that fail the same way (verified): (A && x) || (B && y),
exists(@.a ? (@ tsmatch "apple")) && exists(@.b ? (@ tsmatch "banana")), and the same forms under @? in a WHERE clause (row 2
of a three-row table was returned/omitted wrongly in both the AND
and the OR variants). The cache "works" for the author's tests only
because a $[*] loop re-enters the same frames at the same depth.
Fix: key the cache on something that identifies the item within the
path, e.g. jsp->base (which jspInitByBuffer() sets to the item's
address inside the JsonPath datum and is unique per item), not on
the transient JsonPathItem struct. Better still, do what
like_regex does and keep a small backend-level cache keyed by
(config OID, parser mode, query text), which also removes the
per-row recompilation and the NOTICE flood (finding 6).
2. jsonpath on-disk format changed: pg_upgrade crash / wrong results
Location: src/include/utils/jsonpath.h.
jpiLikeRegex, /* LIKE_REGEX predicate */
+ jpiTsMatch, /* TSMATCH predicate */
jpiBigint, /* .bigint() item method */
The item type is stored as one byte in the flattened jsonpath datum
(appendStringInfoChar(buf, (char) (item->type)) in
flattenJsonPathParseItem(), read_byte(v->type, ...) in
jspInitByBuffer()), the datum is stored as-is in tables, index
expressions, views, defaults and constraints (as a Const), and
pg_upgrade carries it over unchanged. Inserting a member shifts
jpiBigint and all later members (boolean, date, decimal,
integer, number, string, time*, timestamp*, replace,
lower, upper, *trim, initcap, split_part) by one. Both
previous additions, 66ea94e8e60 ("Implement various jsonpath
methods", PG17) and bd4f879a9cd ("Add additional jsonpath string
methods"), appended their new members at the end.
I simulated the upgrade with binary-coercible casts
(CREATE CAST (bytea AS jsonpath) WITHOUT FUNCTION) and the bytes an
unpatched server stores:
- old
$.a.bigint()(type byte 43): the patched server reads the item asjpiTsMatch, interprets the following bytes as offsets and string lengths, and the backend segfaults while printing it ("server process was terminated by signal 11"). - old
$.a.boolean()(44): read as$."a".bigint();jsonb_path_query('{"a":"1"}', ...)returns1instead oftrue.
Fix: append jpiTsMatch at the end of the enum. No version bump is
needed if that is done. A regression test that pins the numeric
values of existing enum members would be a good addition in any
case, since this trap is easy to fall into.
3. IMMUTABLE functions depend on session state
All of the following were verified on the patched build.
a. GUC dependence: jsonb_path_query_array('["running"]', '$[*] ? (@ tsmatch "run")') returns ["running"] with
default_text_search_config = pg_catalog.english and [] with
pg_catalog.simple.
b. search_path dependence even with an explicit configuration:
after CREATE TEXT SEARCH CONFIGURATION s1.english (COPY = pg_catalog.simple) and SET search_path = s1, pg_catalog, the
path '$[*] ? (@ tsmatch "run" tsconfig "english")' resolves to
s1.english and returns [] instead of ["running"].
c. Plan-time folding and plan caching: PREPARE p AS SELECT jsonb_path_query_array('["running"]', '$[*] ? (@ tsmatch "run")')
is constant-folded (EXPLAIN shows Output: '["running"]'::jsonb);
after SET default_text_search_config = 'pg_catalog.simple',
EXECUTE p still returns ["running"] while the same SELECT
typed fresh returns [].
d. Expression indexes: CREATE INDEX ON ti ((doc @? '$.a ? (@ tsmatch "run")')) is accepted (operator is IMMUTABLE). After changing the
GUC, the index scan reports 500 matching rows and a sequential
scan reports 0.
e. JSON_EXISTS: CREATE TABLE tg (doc jsonb, g bool GENERATED ALWAYS AS (JSON_EXISTS(doc, '$.a ? (@ tsmatch "run")')) STORED)
succeeds, whereas the time-zone-dependent equivalent is rejected
with "generation expression is not immutable" thanks to
jspIsMutable(). The patch's jspIsMutableWalker() case for
jpiTsMatch never sets cxt->mutable.
This is a design decision, not a one-line fix; see Design above.
4. Deparse regression: top-level like_regex loses its ")"
Location: src/backend/utils/adt/jsonpath.c, printJsonPathItem().
The new case jpiTsMatch: is inserted before the last two lines of
the jpiLikeRegex case, so like_regex now breaks before printing
its closing bracket, and those two lines (plus a second break;)
survive as unreachable code at the end of the jpiTsMatch case:
appendStringInfoChar(buf, '"');
}
+ break;
+ case jpiTsMatch:
...
+ if (printBracketes)
+ appendStringInfoChar(buf, ')');
+ break;
if (printBracketes)
appendStringInfoChar(buf, ')');
printBracketes is true for every top-level predicate (the printer
is called with printBracketes = true from jsonPathToCstring()),
so on the patched build:
select '$.a like_regex "x"'::jsonpath; -- ($."a" like_regex "x"
select ('$.a like_regex "x"'::jsonpath)::text::jsonpath;
-- ERROR: syntax error at end of jsonpath input
create view v as select jsonb_path_match('{"a":"x"}', '$.a like_regex "x"');
select pg_get_viewdef('v');
-- ... jsonb_path_match('{"a": "x"}'::jsonb, '($."a" like_regex "x"'::jsonpath)
Every existing view, index expression, constraint or column default
containing a top-level like_regex (the normal form for @@ /
jsonb_path_match) would fail to dump and restore, and pg_upgrade
would fail at the schema-restore step. The same loss happens when a
like_regex is the left operand of another like_regex/tsmatch.
Chao Li pointed at exactly this duplicated code in his v3 review
(item 11); v4 moved the break instead of deleting the duplicate.
No regression test prints a top-level like_regex, which is why the
suite still passes; one should be added.
5. tsconfig printed without escaping
Location: src/backend/utils/adt/jsonpath.c, printJsonPathItem(),
jpiTsMatch case: the configuration name is appended with
appendBinaryStringInfo() between literal double quotes, while the
tsquery string correctly uses escape_json_with_len().
select '$ ? (@ tsmatch "x" tsconfig "c\"d")'::jsonpath;
-- $?(@ tsmatch "x" tsconfig "c"d") -> does not re-parse
select '$ ? (@ tsmatch "x" tsconfig "a\\b")'::jsonpath;
-- $?(@ tsmatch "x" tsconfig "a\b") -> re-parses as a<BS>
Configuration names containing quotes or backslashes are unusual but
legal; the output of a type's output function must always re-parse.
Use escape_json_with_len() for tsconfig (and, for consistency,
for tsqparser).
6. Errors in the wrong place; NOTICE per row
- Duplicate options are rejected in the grammar actions with
ereport(ERROR), noterrsave(), so jsonpath input is no longer soft-error safe:pg_input_is_valid('$ ? (@ tsmatch "x" tsconfig "a" tsconfig "b")', 'jsonpath')raises an error instead of returning false (and would abortCOPY ... ON_ERROR ignore). The invalid-tsqparsercheck inmakeItemTsMatch()does it right. - The tsquery is only parsed at execution, so
'$ ? (@ tsmatch "x &")'::jsonpathis accepted byjsonpath_inand fails on every evaluation;like_regexvalidates its pattern at input time. Likewise a nonexistent configuration errors at execution. Both are hard errors even under@?andjsonb_path_exists(..., silent => true), which matcheslike_regex's behaviour for invalid regexes but, unlike there, cannot be caught up front. - Because the tsquery is recompiled per row,
to_tsquery's NOTICE for stop-word-only queries is emitted once per row:WHERE doc @? '$.a ? (@ tsmatch "the" tsconfig "english")'over 3 rows prints 3 NOTICEs; the SQL equivalent prints 1.
7. Minor
executeTsMatch()never frees the per-itemtextcopy and tsvector; in normal use the caller's per-tuple context bounds the leak, butjsonb_path_query()runs inmulti_call_memory_ctx, so a large array costs one tsvector per element until the SRF ends.- The
tsmatch_opts%unionmember leaves theJsonPathStringfields uninitialised in the empty production; harmless today because they are guarded byhas_*, but worth zeroing. jspInitByBuffer()carries a leftover "FIX: Read all integers first" comment.- Pre-existing, not caused by the patch but copied into it:
operationPriority()has no case forjpiLikeRegex(orjpiTsMatch), so'$ ? ((@.a like_regex "x").type() == "boolean")'already prints without the needed parentheses on master and does not re-parse. Worth fixing separately.
GIN interaction is fine: extract_jsp_bool_expr() returns NULL for
unknown predicate types, so a tsmatch filter is simply not used for
index pruning; with both jsonb_ops and jsonb_path_ops indexes the
planner chose a bitmap scan on @?/@@ queries containing tsmatch
and the results matched the sequential scan (1000 rows of 20000).
Lax/strict handling, non-string operands (jpbUnknown, hence
filtered out, ! yields unknown, is unknown yields true), nested
array unwrapping, keyword case-insensitivity, and using tsmatch,
tsconfig, tsqparser as key names ($."tsmatch") all behave like
like_regex.
Performance
200k rows of the author's benchmark document shape (two comments per
row, 5% of rows matching), release build without assertions,
max_parallel_workers_per_gather = 0, enable_memoize = off (the
author's data has only three distinct documents, so Memoize makes
the LATERAL form look 4x faster than it is; the author disabled it
too). Best of three runs:
| query (all over the same 200k rows) | ms |
|---|---|
A: @? '$.comments[*] ? (@.body tsmatch "performance" |
|
tsconfig "english")' |
531 |
B: A without tsconfig |
499 |
C: LATERAL jsonb_array_elements, to_tsvector @@ tsq |
440 |
D: to_tsvector(doc#>>'{comments,0,body}') @@ ... OR .. |
380 |
E: A with like_regex "performance" instead of tsmatch |
107 |
F: 200k non-foldable to_tsquery('english', ...) calls |
105 |
G: 200k regconfig name lookups |
26 |
tsmatch is about 20% slower than the LATERAL formulation it is
meant to replace and 40% slower than direct to_tsvector calls.
Roughly a fifth of its time is the per-row tsquery compilation that
a per-query cache would remove. The claim in the commit message that
the LATERAL approach has "high memory overhead" is not supported by
any measurement in the thread or here.
Compatibility
- On-disk jsonpath format: broken by the enum insertion (finding 2). Must be fixed before this can be considered.
- pg_dump/pg_upgrade: broken for existing top-level
like_regexpredicates (finding 4) and fortsconfignames needing escaping (finding 5). - SQL/grammar: three new keywords are recognised only inside
jsonpath strings and remain usable as key names; no conflict with
SQL.
%expect 0holds. jsonpath_send/recvare text-based and unaffected.JsonPathItemandJsonPathParseItemgrow (new union members); acceptable in a major release, no catversion change needed.- Semantics: results depend on
default_text_search_config,search_pathand catalog contents (finding 3); no other existing jsonpath construct does.
Code, tests, docs, style
- src/backend/utils/adt/jsonpath_gram.y:
git diff --checkflags five lines indented with spaces (thetsmatch_optsrule action braces at thepredicateproduction and the multi-line condition inmakeItemTsMatch()); the%unionstruct uses spaces for alignment; themakeItemTsMatch()prototype's continuation lines are misaligned (Chao Li's item 2, still present); the%tokenline now exceeds 120 columns. pgindent does not touch.yfiles, so these need manual fixing. - src/backend/utils/adt/jsonpath.c: unreachable code after
break(finding 4);tsqparsercomment claims no escaping is needed because the value is validated, which is fragile. - src/backend/utils/adt/jsonpath_exec.c: the
pg_unreachable()for an unknown parser mode is fine; several lines exceed 100 columns (pgindent leaves them). The blank-line removal beforedefault:inexecuteBoolItem()is unrelated noise. - Tests: none for
@@/jsonb_path_matchwithtsmatch, for the"pl"/"ph"parsers at execution, for duplicate or invalid options viapg_input_is_valid, for keywords used as key names, or for deparse of a top-level predicate; none would have caught findings 1, 2, 4 or 5. Add a test that pins existingJsonPathItemTypevalues (e.g. by printing a hand-built datum) or at least a comment in jsonpath.h saying "append only". - Docs: doc/src/sgml/func/func-json.sgml entry validates and is
placed with the other predicates. It should say the comparison of
tsqparservalues is case-insensitive, that the configuration name is resolved throughsearch_pathat evaluation time, and, as long as the behaviour stands, warn that the result of an IMMUTABLE operator depends ondefault_text_search_configand must not be used in index expressions withouttsconfig. The SQL/JSON conformance section (like_regexis marked as standard) should note thattsmatchis a PostgreSQL extension. - Commit message: describes the design goals well; the statement that caching respects "the stability requirements of prepared statements" is wrong (finding 3c), and the memory-overhead claim about the LATERAL alternative is unsupported.
Discussion and consensus
Eight messages between 2026-01-26 and 2026-04-05, all by the author
except two from Chao Li. Chao Li reviewed v3 with twelve code-level
points (doc wording, prototype alignment, grammar duplication,
naming consistency, include placement, an else that should be
unreachable, a cache that was not reused across array items, a
non-NUL-terminated string in an error message, the duplicated
closing-bracket code, and appendBinaryStringInfo NUL handling);
the author addressed most in v4/v5. v6 incorporates off-list
comments from Andrew Dunstan (soft-error path, prefix-match bug in
parser-mode validation, hard error for unknown configuration,
order-independent options). Nobody raised the SQL/JSON standard
question beyond the author's own sentence, the IMMUTABLE/GUC/
search_path dependence, the on-disk format, the per-row
compilation, or the keyword/syntax choices, and no committer has
expressed an opinion on whether the feature belongs in core. The
entry has been "Needs review" since creation, was moved
PG19-Final -> PG20-1 -> PG20-3, and still lists target version 19.
"Needs review" was accurate; after this review it should be
"Waiting on Author".
Verdict
Needs changes and needs design discussion; not ready for committer.
Findings 1 (wrong results from the stack-address cache key), 2
(on-disk format break) and 4 (like_regex deparse regression) are
each individually blocking and each would have been caught by a
targeted test; they drive the assessment score. Finding 3 is a
design hole that needs an on-list decision before more code is
written, because it determines where configuration resolution and
tsquery compilation happen and whether new STABLE entry points are
required. Specific changes needed:
- Append
jpiTsMatchat the end ofJsonPathItemType; add a test or comment guarding the numbering. - Restore the
jpiLikeRegexclosing bracket and delete the unreachable lines; add a deparse test for a top-levellike_regexand fortsmatchwith all options. - Replace the pointer-keyed per-execution cache with a cache keyed
by item position (or a backend-level cache keyed by config OID,
parser mode and query text, as
like_regexdoes). - Decide and implement the immutability story (require
tsconfigand/or resolve at parse time, or mark mutable and add STABLE variants); makejspIsMutableWalker()consistent with it. escape_json_with_len()fortsconfigandtsqparser; useerrsave()for duplicate options; validate what can be validated at input time.- Fix the
.yindentation, drop the unrelated blank-line hunk, and correct the commit message's performance and stability claims.
A committer should also double-check the keyword table ordering in src/backend/utils/adt/jsonpath_scan.l (binary search by length then name; the three insertions are in the right places) and the INTALIGN assumptions in the new flatten/read code (the integers are written before the strings and read in the same order; verified by the tests and by inspection, but an endianness/alignment buildfarm pass would be prudent).