-- phrase_pos_budget (1.18.4, ROADMAP I37): a positional phrase/NEAR filter whose -- per-segment positional decode would exceed pg_fts.phrase_pos_budget_mb falls -- back to evaluating the phrase as AND (candidates only) with a heap recheck -- that enforces adjacency, bounding memory. The result must be identical to -- the positional path. -- -- A positional phrase decodes every phrase term's full position list for a -- segment at once (bm25_lookup_term_pos), so a common-word phrase takes memory -- proportional to the terms' document frequency times positions-per-document -- -- tens of GB at corpus scale, and eight concurrent such queries OOM a container -- (txfs19260817, 150M). The budget cap routes an oversized segment to the -- heap-recheck path, which is the same correct path a positions=off index -- always uses. A small corpus cannot reach the gigabyte peak, so this guards -- the behaviour the cap must preserve: identical results on the fast path and -- the fallback, across phrase, NEAR and phrase-in-boolean shapes, with -- tombstones and pending rows present. SET client_min_messages = warning; CREATE EXTENSION IF NOT EXISTS pg_fts; CREATE TABLE ppb (id int PRIMARY KEY, body text); INSERT INTO ppb SELECT g, (SELECT string_agg('w' || ((g * 7 + i * 13) % 120), ' ') FROM generate_series(1, 6) i) || CASE WHEN g % 3 = 0 THEN ' quick brown' ELSE '' END || CASE WHEN g % 7 = 2 THEN ' brown fox' ELSE '' END || CASE WHEN g % 5 = 1 THEN ' lazy dog' ELSE '' END FROM generate_series(1, 50000) g; CREATE INDEX ppb_idx ON ppb USING fts (to_ftsdoc('simple', body)) WITH (positions = on); VACUUM ANALYZE ppb; -- tombstones across the id range, then VACUUM; pending rows after DELETE FROM ppb WHERE id % 13 = 0; VACUUM ppb; INSERT INTO ppb SELECT g, 'quick brown fox lazy dog' FROM generate_series(100001, 100040) g; -- count under the positional fast path (generous budget) and under the forced -- heap-recheck fallback (budget = 1 MB); the two must agree for every shape. CREATE FUNCTION ppb_count(q text, budget_mb int) RETURNS bigint LANGUAGE plpgsql AS $$ DECLARE n bigint; BEGIN EXECUTE 'SET LOCAL pg_fts.phrase_pos_budget_mb = ' || budget_mb; EXECUTE format('SELECT count(*) FROM ppb WHERE to_ftsdoc(''simple'', body) @@@ to_ftsquery(''simple'', %L)', q) INTO n; RETURN n; END $$; SELECT q, ppb_count(q, 256) AS positional, ppb_count(q, 256) = ppb_count(q, 1) AS fallback_agrees FROM unnest(ARRAY[ 'quick <-> brown', 'brown <-> fox', 'quick <2> fox', 'lazy <-> dog', '(quick <-> brown) & fox', 'brown & !fox', 'quick <-> brown <-> fox' ]) AS q ORDER BY q; q | positional | fallback_agrees -------------------------+------------+----------------- (quick <-> brown) & fox | 2238 | t brown & !fox | 13186 | t brown <-> fox | 6634 | t lazy <-> dog | 9271 | t quick <-> brown | 15424 | t quick <-> brown <-> fox | 40 | t quick <2> fox | 40 | t (7 rows)