-- Copyright 2026 Manuel Reyes Bravo -- SPDX-License-Identifier: Apache-2.0 -- pg_recall_guard 0.2.11 -> 0.3.0 -- -- Two bugs found in review of 0.2.11, each with its tooth in test/audit.sh, and the object -- comments restated. -- -- * A table whose row level security applies to the caller is refused, not measured. Its -- policies removed rows after the index had chosen its candidates, so a healthy index read -- critical for a monitoring role with the grants the README lists (test/audit.sh RG-S2). -- measure() and evaluate_query() raise, and check() answers COULD NOT MEASURE. -- * vector_indexes reads the indexed column's name from the table, not from the index. -- RENAME COLUMN does not rename the index's own column, so after a rename measure() looked -- for a column that no longer exists, and check() answered COULD NOT MEASURE on a healthy -- index (RG-S3). An expression index now has no column name, and measure() refuses it before it -- samples the table, with the error evaluate_query() gives. -- * The object comments of vector_indexes, baselines and check() say what each one is, -- without the claim that the view works for any vector extension, and the comments inside -- measure() and evaluate_query() no longer carry the version that introduced each line. \echo Use "ALTER EXTENSION pg_recall_guard UPDATE TO '0.3.0'" to load this file. \quit CREATE OR REPLACE VIEW recall_guard.vector_indexes AS SELECT i.indexrelid AS index_oid, -- Qualified always, never regclass::text: that one depends on the reader's -- search_path, and this name is stored and read back by other sessions. -- format() over two `name` columns would come out with collation "C", and a -- view column cannot change collation: keep the one regclass::text had. pg_catalog.format('%I.%I', n.nspname, c.relname) COLLATE pg_catalog."default" AS index_name, n.nspname AS schema_name, t.relname AS table_name, a.attname AS column_name, am.amname AS access_method, op.oprname AS operator, -- The operator does NOT live in pg_catalog but wherever the extension that brings -- it was installed, so its schema is read from the catalog instead of assumed. -- Assuming pg_catalog gives "operator does not exist: vector pg_catalog.<=> vector". opn.nspname AS operator_schema, oc.opcname AS opclass, pg_catalog.pg_relation_size(i.indexrelid) AS index_bytes FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid JOIN pg_catalog.pg_class t ON t.oid = i.indrelid JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace JOIN pg_catalog.pg_am am ON am.oid = c.relam JOIN pg_catalog.pg_opclass oc ON oc.oid = i.indclass[0] -- The table's column, not the index's: RENAME COLUMN leaves the index's own -- column name as it was. An expression index has none. LEFT JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0] JOIN pg_catalog.pg_amop ao ON ao.amopfamily = oc.opcfamily AND ao.amoppurpose = 'o' JOIN pg_catalog.pg_operator op ON op.oid = ao.amopopr JOIN pg_catalog.pg_namespace opn ON opn.oid = op.oprnamespace WHERE i.indisvalid AND n.nspname NOT IN ('pg_catalog', 'information_schema'); CREATE OR REPLACE FUNCTION recall_guard.evaluate_query( p_index regclass, p_vector text, p_k integer DEFAULT 10, p_exclude tid DEFAULT NULL, p_exclude_table oid DEFAULT NULL) RETURNS numeric LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$ DECLARE v record; q_indexed text; q_exact text; plan_txt text; rows_idx text[]; dist_idx float8[]; rows_exact text[]; dist_exact float8[]; excluded text; prev_seq text := pg_catalog.current_setting('enable_seqscan'); prev_bmp text := pg_catalog.current_setting('enable_bitmapscan'); prev_idx text := pg_catalog.current_setting('enable_indexscan'); prev_ios text := pg_catalog.current_setting('enable_indexonlyscan'); family text[]; used text[]; v_from text; v_table oid; v_limit int; kth float8; hits int; n_exact int; BEGIN -- If the query comes from a row of the table, that row finds itself at distance 0 -- and gives away a hit in every query. One more is asked for -- and the row itself is dropped from both sides. v_limit := p_k + CASE WHEN p_exclude IS NULL THEN 0 ELSE 1 END; IF p_index IS NULL OR p_vector IS NULL OR p_k IS NULL THEN RAISE EXCEPTION 'pg_recall_guard: evaluate_query needs an index, a vector and k'; END IF; SELECT * INTO v FROM recall_guard.vector_indexes WHERE index_oid = p_index; IF NOT FOUND THEN RAISE EXCEPTION 'pg_recall_guard: % is not an index with an ordering operator', p_index USING HINT = 'See recall_guard.vector_indexes for the ones that are.'; END IF; -- What cannot be measured says so: an expression index has no column to compare -- against, and a partial index answers only the queries its predicate covers. IF EXISTS (SELECT 1 FROM pg_index i WHERE i.indexrelid = p_index AND (i.indkey[0] = 0 OR i.indpred IS NOT NULL)) THEN RAISE EXCEPTION 'pg_recall_guard: % is an expression or partial index, which this cannot measure', v.index_name; END IF; -- ONLY for a plain table: its index does not cover inheritance children. SELECT CASE WHEN t.relkind = 'p' THEN format('%I.%I', v.schema_name, v.table_name) ELSE format('ONLY %I.%I', v.schema_name, v.table_name) END, t.oid INTO v_from, v_table FROM pg_index i JOIN pg_class t ON t.oid = i.indrelid WHERE i.indexrelid = p_index; -- Under row level security the query would be the policy's, not the index's: -- rows the policy removes after the index has chosen read as misses. IF row_security_active(v_table) THEN RAISE EXCEPTION 'pg_recall_guard: row level security applies to % for this role', format('%I.%I', v.schema_name, v.table_name) USING HINT = 'Measure it as a role its policies do not apply to.'; END IF; -- Each neighbour with its distance: recall is judged by distance, so that two -- equidistant rows are interchangeable. A row is its table and ctid; the literal is -- cast to the column's base type, so a domain's CHECK never runs. q_indexed := format( 'SELECT array_agg(r ORDER BY d, r), array_agg(d ORDER BY d, r) FROM (' 'SELECT tableoid::text || '':'' || ctid::text AS r, ' '(%I OPERATOR(%I.%s) %L::%s)::float8 AS d FROM %s ' 'ORDER BY %I OPERATOR(%I.%s) %L::%s LIMIT %s) s', v.column_name, v.operator_schema, v.operator, p_vector, recall_guard._vector_type(p_index), v_from, v.column_name, v.operator_schema, v.operator, p_vector, recall_guard._vector_type(p_index), v_limit); q_exact := q_indexed; -- Indexed side: force the index and CHECK that it was used -- this index, no other. PERFORM set_config('enable_seqscan', 'off', true); PERFORM set_config('enable_bitmapscan', 'off', true); EXECUTE 'EXPLAIN (FORMAT JSON) ' || q_indexed INTO plan_txt; family := recall_guard._index_family(p_index); SELECT array_agg(m[1]) INTO used FROM regexp_matches(plan_txt, '"Index Name": "((?:[^"\\]|\\.)*)"', 'g') AS m; IF used IS NULL OR NOT used <@ family OR (SELECT count(*) FROM regexp_matches(plan_txt, '"Relation Name":', 'g')) <> array_length(used, 1) THEN RAISE EXCEPTION 'pg_recall_guard: the plan did not measure index %: it read %', v.index_name, coalesce(array_to_string(used, ', '), 'no index') USING DETAIL = plan_txt, HINT = 'Measuring another index, or the table without an index, would report a recall other than this one.'; END IF; EXECUTE q_indexed INTO rows_idx, dist_idx; -- The caller's values back, not the defaults: RESET would undo a SET LOCAL of theirs. PERFORM set_config('enable_seqscan', prev_seq, true); PERFORM set_config('enable_bitmapscan', prev_bmp, true); -- Ground truth: forbid every index access and CHECK that none was used. PERFORM set_config('enable_seqscan', 'on', true); PERFORM set_config('enable_indexscan', 'off', true); PERFORM set_config('enable_bitmapscan', 'off', true); PERFORM set_config('enable_indexonlyscan', 'off', true); EXECUTE 'EXPLAIN (FORMAT JSON) ' || q_exact INTO plan_txt; IF plan_txt ~ '"Node Type": "Index (Only )?Scan"' THEN RAISE EXCEPTION 'pg_recall_guard: could not get an exact ground truth for %', v.index_name USING DETAIL = plan_txt, HINT = 'The planner kept the index despite enable_*=off.'; END IF; EXECUTE q_exact INTO rows_exact, dist_exact; PERFORM set_config('enable_seqscan', prev_seq, true); PERFORM set_config('enable_indexscan', prev_idx, true); PERFORM set_config('enable_bitmapscan', prev_bmp, true); PERFORM set_config('enable_indexonlyscan', prev_ios, true); -- Drop the self-match from both sides, and only then cut to k. excluded := CASE WHEN p_exclude IS NULL THEN NULL WHEN p_exclude_table IS NULL THEN NULL ELSE p_exclude_table::text || ':' || p_exclude::text END; SELECT array_agg(d ORDER BY o) INTO dist_idx FROM (SELECT d, o FROM unnest(rows_idx, dist_idx) WITH ORDINALITY AS u(r, d, o) WHERE p_exclude IS NULL OR CASE WHEN excluded IS NULL THEN split_part(r, ':', 2) <> p_exclude::text ELSE r <> excluded END ORDER BY o LIMIT p_k) s; SELECT array_agg(d ORDER BY o) INTO dist_exact FROM (SELECT d, o FROM unnest(rows_exact, dist_exact) WITH ORDINALITY AS u(r, d, o) WHERE p_exclude IS NULL OR CASE WHEN excluded IS NULL THEN split_part(r, ':', 2) <> p_exclude::text ELSE r <> excluded END ORDER BY o LIMIT p_k) s; n_exact := coalesce(array_length(dist_exact, 1), 0); IF n_exact = 0 THEN RAISE EXCEPTION 'pg_recall_guard: the ground truth came back empty for %', v.index_name; END IF; -- A hit is a returned neighbour no farther than the k-th exact one. The tolerance -- absorbs the last bits of floating point, not a real difference in distance. kth := dist_exact[n_exact]; SELECT count(*) INTO hits FROM unnest(dist_idx) d WHERE d <= kth + greatest(abs(kth), 1) * 1e-9; RETURN round(least(hits, n_exact)::numeric / n_exact, 4); END; $$; CREATE OR REPLACE FUNCTION recall_guard.measure(p_index regclass, p_k integer DEFAULT 10, p_sample_size integer DEFAULT 30) RETURNS numeric LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $$ DECLARE v record; v_from text; v_table oid; est real; sampling text := ''; toids oid[]; ctids tid[]; vecs text[]; total numeric := 0; n int := 0; r numeric; BEGIN IF p_index IS NULL OR p_k IS NULL OR p_sample_size IS NULL THEN RAISE EXCEPTION 'pg_recall_guard: measure needs an index, k and a sample size'; END IF; IF p_k NOT BETWEEN 1 AND 1000 OR p_sample_size NOT BETWEEN 1 AND 10000 THEN RAISE EXCEPTION 'pg_recall_guard: k must be 1 to 1000 and sample_size 1 to 10000 (got % and %)', p_k, p_sample_size; END IF; SELECT * INTO v FROM recall_guard.vector_indexes WHERE index_oid = p_index; IF NOT FOUND THEN RAISE EXCEPTION 'pg_recall_guard: % is not a vector index', p_index; END IF; -- Before the table is read: the view gives an expression index no column. IF EXISTS (SELECT 1 FROM pg_index i WHERE i.indexrelid = p_index AND (i.indkey[0] = 0 OR i.indpred IS NOT NULL)) THEN RAISE EXCEPTION 'pg_recall_guard: % is an expression or partial index, which this cannot measure', v.index_name; END IF; SELECT CASE WHEN t.relkind = 'p' THEN format('%I.%I', v.schema_name, v.table_name) ELSE format('ONLY %I.%I', v.schema_name, v.table_name) END, t.reltuples, t.oid INTO v_from, est, v_table FROM pg_index i JOIN pg_class t ON t.oid = i.indrelid WHERE i.indexrelid = p_index; -- Under row level security the query would be the policy's, not the index's: -- rows the policy removes after the index has chosen read as misses. IF row_security_active(v_table) THEN RAISE EXCEPTION 'pg_recall_guard: row level security applies to % for this role', format('%I.%I', v.schema_name, v.table_name) USING HINT = 'Measure it as a role its policies do not apply to.'; END IF; -- At random, among the rows that have a vector. A large table is thinned with -- BERNOULLI first, four times the sample; if that comes back short, the whole -- table is drawn. IF est > 50000 THEN sampling := format('TABLESAMPLE BERNOULLI (%s)', least(100, greatest(0.001, 400.0 * p_sample_size / est))); END IF; LOOP EXECUTE format( 'SELECT array_agg(o), array_agg(c), array_agg(x) FROM (' 'SELECT tableoid AS o, ctid AS c, %I::text AS x FROM %s %s WHERE %I IS NOT NULL ' 'ORDER BY random() LIMIT %s) s', v.column_name, v_from, sampling, v.column_name, p_sample_size) INTO toids, ctids, vecs; EXIT WHEN sampling = '' OR coalesce(cardinality(vecs), 0) >= p_sample_size; sampling := ''; END LOOP; FOR i IN 1 .. coalesce(cardinality(vecs), 0) LOOP r := recall_guard.evaluate_query(p_index, vecs[i], p_k, ctids[i], toids[i]); total := total + r; n := n + 1; END LOOP; IF n = 0 THEN RAISE EXCEPTION 'pg_recall_guard: the sample came back empty for %', v.index_name USING HINT = 'Does the table have rows where that column is not null?'; END IF; INSERT INTO recall_guard.measurements (index_name, k, sample_size, recall, index_bytes, settings) VALUES (v.index_name, p_k, n, round(total / n, 4), v.index_bytes, recall_guard._search_settings()); RETURN round(total / n, 4); END; $$; COMMENT ON VIEW recall_guard.vector_indexes IS 'Indexes that can answer ORDER BY on a distance operator, found through the catalog ' 'rather than by extension name.'; COMMENT ON TABLE recall_guard.baselines IS 'The recall the owner accepted for each index; check() compares against it.'; COMMENT ON FUNCTION recall_guard.check() IS 'Measures every approved index again and compares it with its baseline. ' 'Meant to run on a schedule.';