-- ranked_plan_order (1.18.2, reported by txfs19260817): the README ranked query -- must return rows in BM25 order even when the planner would otherwise choose a -- bitmap heap scan + Sort. -- -- ORDER BY d <=> q ranks by BM25 only through the fts index's ordering scan, -- which reads the corpus statistics. The bare <=> a Sort node evaluates has no -- corpus statistics (every term weighted as if rare, the document's own length -- as the average) and ranks differently. Once the match set is small enough -- that sorting it is cheap (LIMIT >= the match count), the planner used to pick -- the Sort and silently return rows out of BM25 order (the README example did). -- A planner-stage rewrite converts that plan back to the ordering index scan. -- -- Every other ranked regression test forces the index scan with -- enable_bitmapscan/enable_seqscan off, so none of them exercises the plan the -- planner actually picks for a user. This one runs UNFORCED and asserts both -- the plan node and the resulting order against the forced-index-scan truth. SET client_min_messages = warning; CREATE EXTENSION IF NOT EXISTS pg_fts; -- The planner-stage rewrite (and the older score-reuse / LIMIT-hint passes) live -- in pg_fts's planner_hook, which installs when the library loads. LOAD forces -- that now so the first ranked query in this backend already sees the hook; a -- normal session installs it on its first fts query, like those other passes. LOAD 'pg_fts'; CREATE TABLE rpo (id int PRIMARY KEY, body text); -- 4000 docs of filler words. 'alpha' appears in ~250 rows, 'beta' in ~50; the -- query 'alpha | beta' matches ~290. The two terms have very different document -- frequency, so the true BM25 (real per-term df) weights a 'beta' hit far above -- an 'alpha' hit, while the corpus-free fallback (both terms df=1) weights them -- equally -- the two orders genuinely differ. Document lengths also vary. INSERT INTO rpo SELECT g, (SELECT string_agg('w' || (1 + (g * 7919 + i * 104729) % 199), ' ') FROM generate_series(1, 5 + (g * 37) % 60) i) || CASE WHEN g % 16 = 1 THEN repeat(' alpha', 1 + (g % 3)) ELSE '' END || CASE WHEN g % 80 = 3 THEN repeat(' beta', 1 + (g % 2)) ELSE '' END FROM generate_series(1, 4000) g; CREATE INDEX rpo_idx ON rpo USING fts (to_ftsdoc('simple', body)); VACUUM ANALYZE rpo; SET max_parallel_workers_per_gather = 0; -- warm the planner hook: it installs on first use of a pg_fts object in a -- backend, so touch the index before the ranked query under test. SELECT count(*) AS matches FROM rpo WHERE to_ftsdoc('simple', body) @@@ to_ftsquery('simple', 'alpha | beta'); -- The planner's own order must equal the forced ordering-scan order (the BM25 -- truth). Capture each plan's output in strict row order (row_number() over -- the ordered subquery), at a LIMIT well past the match count, and compare the -- id-by-position sequences. Before the fix the planner's plan was a Sort over -- the corpus-free fallback, so this differed; now both are the ordering scan. CREATE TEMP TABLE planner_order AS SELECT id, row_number() OVER () n FROM (SELECT id FROM rpo WHERE to_ftsdoc('simple', body) @@@ to_ftsquery('simple', 'alpha | beta') ORDER BY to_ftsdoc('simple', body) <=> to_ftsquery('simple', 'alpha | beta') LIMIT 1000) s; SET enable_bitmapscan = off; SET enable_seqscan = off; CREATE TEMP TABLE forced_order AS SELECT id, row_number() OVER () n FROM (SELECT id FROM rpo WHERE to_ftsdoc('simple', body) @@@ to_ftsquery('simple', 'alpha | beta') ORDER BY to_ftsdoc('simple', body) <=> to_ftsquery('simple', 'alpha | beta') LIMIT 1000) s; RESET enable_bitmapscan; RESET enable_seqscan; SELECT (SELECT array_agg(id ORDER BY n) FROM planner_order) = (SELECT array_agg(id ORDER BY n) FROM forced_order) AS planner_order_is_bm25_order, (SELECT count(*) FROM planner_order) = (SELECT count(*) FROM forced_order) AS same_row_count; -- The commuted spelling (ftsquery <=> ftsdoc, the declared commutator) is the -- same ranked query and must rank the same way. Its planner-chosen order must -- equal the canonical ftsdoc <=> ftsquery order. CREATE TEMP TABLE commuted_order AS SELECT id, row_number() OVER () n FROM (SELECT id FROM rpo WHERE to_ftsdoc('simple', body) @@@ to_ftsquery('simple', 'alpha | beta') ORDER BY to_ftsquery('simple', 'alpha | beta') <=> to_ftsdoc('simple', body) LIMIT 1000) s; SELECT (SELECT array_agg(id ORDER BY n) FROM commuted_order) = (SELECT array_agg(id ORDER BY n) FROM forced_order) AS commuted_order_is_bm25_order; -- A DESC ranked query (least relevant first) must NOT be rewritten: the -- ordering scan emits only ascending distance, so the rewrite would corrupt a -- DESC order. The planner keeps its Sort and returns the correct descending -- order. Compare the planner's own DESC result to the seq-scan + Sort truth. CREATE TEMP TABLE desc_planner AS SELECT id, row_number() OVER () n FROM (SELECT id FROM rpo WHERE to_ftsdoc('simple', body) @@@ to_ftsquery('simple', 'alpha | beta') ORDER BY to_ftsdoc('simple', body) <=> to_ftsquery('simple', 'alpha | beta') DESC LIMIT 20) s; SET enable_indexscan = off; SET enable_bitmapscan = off; CREATE TEMP TABLE desc_truth AS SELECT id, row_number() OVER () n FROM (SELECT id FROM rpo WHERE to_ftsdoc('simple', body) @@@ to_ftsquery('simple', 'alpha | beta') ORDER BY to_ftsdoc('simple', body) <=> to_ftsquery('simple', 'alpha | beta') DESC LIMIT 20) s; RESET enable_indexscan; RESET enable_bitmapscan; SELECT (SELECT array_agg(id ORDER BY n) FROM desc_planner) = (SELECT array_agg(id ORDER BY n) FROM desc_truth) AS desc_order_correct; -- A SCROLL cursor over the rewritten plan must serve rows backward correctly. -- The fts access method cannot scan backward (amcanbackward = false), so the -- planner places a Materialize above the scan for a scroll cursor; the rewrite -- swaps the Sort below that Materialize, and FETCH BACKWARD reads from the -- tuplestore. The forward rows (positions 1-4) and a backward re-fetch -- (position 3 after moving to 4) are printed; they must be consistent with a -- single BM25-ordered sequence (position 3 fetched backward == the 3rd forward -- row). BEGIN; DECLARE rpo_sc SCROLL CURSOR FOR SELECT id FROM rpo WHERE to_ftsdoc('simple', body) @@@ to_ftsquery('simple', 'alpha | beta') ORDER BY to_ftsdoc('simple', body) <=> to_ftsquery('simple', 'alpha | beta') LIMIT 1000; FETCH 4 FROM rpo_sc; FETCH BACKWARD 2 FROM rpo_sc; COMMIT;