pg.ddx.io pgvector/pgvector GitHub issues and pull requests
help / color / mirror / Atom feedFrom: binarycleric (@binarycleric) <noreply+binarycleric@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] PR #863: Adding optional in-memory tracking of recall metrics
Date: Fri, 27 Jun 2025 19:31:11 +0000
Message-ID: <gh-pgvector-pgvector-863@github.com> (raw)
Add recall tracking functionality to monitor the quality of approximate vector indexes without the performance overhead of exact searches. It is disabled by default and must be explicity enabled by a user. Recall tracking can also be disabled in the event of bugs or performance impacts.
Statistical recall tracking monitors index performance without expensive exact searches. The recall estimation works by counting how many tuples in the table fall within the distance of the K-th result, providing a practical approximation of search quality without the cost of brute-force comparison.
This should give users a fairly decent idea of recall without adding significant performance overhead and can be useful in observability pipelines or during development. This information is only stored in memory right now but can be persisted to disk as a future enhancement.
### Configuration
```sql
SET pgvector.track_recall = on;
SET pgvector.recall_sample_rate = 50; -- Sample every 50th query
SET pgvector.recall_max_scan_tuples = 10000 -- How many tuples to scan before exiting.
```
### Usage
View recall summary with index names:
```sql
SELECT * FROM pg_vector_recall_summary();
```
Get raw statistics:
```sql
SELECT * FROM pg_vector_recall_stats();
```
Get statistics for a specific index:
```sql
SELECT pg_vector_recall_get(index_oid);
```
Reset stats for a specific index:
```sql
SELECT pg_vector_recall_reset(index_oid);
```
inline patch 1: Makefile, Makefile.win, README.md and 12 more (+715/-5 lines) download inline-1.patch
diff --git a/Makefile b/Makefile
index 7a4b88caf..14e15391d 100644
--- a/Makefile
+++ b/Makefile
@@ -1,10 +1,10 @@
EXTENSION = vector
-EXTVERSION = 0.8.0
+EXTVERSION = 0.9.0
MODULE_big = vector
DATA = $(wildcard sql/*--*--*.sql)
DATA_built = sql/$(EXTENSION)--$(EXTVERSION).sql
-OBJS = src/bitutils.o src/bitvec.o src/halfutils.o src/halfvec.o src/hnsw.o src/hnswbuild.o src/hnswinsert.o src/hnswscan.o src/hnswutils.o src/hnswvacuum.o src/ivfbuild.o src/ivfflat.o src/ivfinsert.o src/ivfkmeans.o src/ivfscan.o src/ivfutils.o src/ivfvacuum.o src/sparsevec.o src/vector.o
+OBJS = src/bitutils.o src/bitvec.o src/halfutils.o src/halfvec.o src/hnsw.o src/hnswbuild.o src/hnswinsert.o src/hnswscan.o src/hnswutils.o src/hnswvacuum.o src/ivfbuild.o src/ivfflat.o src/ivfinsert.o src/ivfkmeans.o src/ivfscan.o src/ivfutils.o src/ivfvacuum.o src/sparsevec.o src/vector.o src/vector_recall.o
HEADERS = src/halfvec.h src/sparsevec.h src/vector.h
TESTS = $(wildcard test/sql/*.sql)
diff --git a/Makefile.win b/Makefile.win
index 8c62f9d5f..c4d36bb71 100644
--- a/Makefile.win
+++ b/Makefile.win
@@ -1,8 +1,8 @@
EXTENSION = vector
-EXTVERSION = 0.8.0
+EXTVERSION = 0.9.0
DATA_built = sql\$(EXTENSION)--$(EXTVERSION).sql
-OBJS = src\bitutils.obj src\bitvec.obj src\halfutils.obj src\halfvec.obj src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\sparsevec.obj src\vector.obj
+OBJS = src\bitutils.obj src\bitvec.obj src\halfutils.obj src\halfvec.obj src\hnsw.obj src\hnswbuild.obj src\hnswinsert.obj src\hnswscan.obj src\hnswutils.obj src\hnswvacuum.obj src\ivfbuild.obj src\ivfflat.obj src\ivfinsert.obj src\ivfkmeans.obj src\ivfscan.obj src\ivfutils.obj src\ivfvacuum.obj src\sparsevec.obj src\vector.obj src\vector_recall.obj
HEADERS = src\halfvec.h src\sparsevec.h src\vector.h
REGRESS = bit btree cast copy halfvec hnsw_bit hnsw_halfvec hnsw_sparsevec hnsw_vector ivfflat_bit ivfflat_halfvec ivfflat_vector sparsevec vector_type
diff --git a/README.md b/README.md
index 344971611..62518fdb3 100644
--- a/README.md
+++ b/README.md
@@ -653,6 +653,82 @@ SELECT * FROM (
) ORDER BY embedding <=> '[1,2,3,4,5]' LIMIT 5;
```
+## Observability
+
+### Recall Tracking
+
+Monitor the quality of your approximate indexes by tracking recall metrics. Recall
+measures how many of the true nearest neighbors are found by your index - a
+recall of 1.0 (100%) means perfect accuracy, while lower values indicate the
+index is missing some nearest neighbors.
+
+pgvector estimates recall using statistical sampling without expensive exact
+searches. When enabled, it tracks query patterns and uses distance-threshold
+counting to estimate how many relevant results exist in your data.
+
+#### Enable Recall Tracking
+
+Enable recall tracking for all vector indexes
+
+```sql
+SET pgvector.track_recall = on;
+```
+
+Control sampling frequency to balance monitoring detail with performance impact
+
+```sql
+SET pgvector.recall_sample_rate = 100; -- Sample every 100th query
+```
+
+Control the maximum number of tuples scanned during recall estimation
+
+```sql
+SET pgvector.recall_max_scan_tuples = 10000; -- Default: scan up to 10,000 tuples
+SET pgvector.recall_max_scan_tuples = -1; -- Unlimited: scan entire table
+```
+
+#### View Recall Statistics
+
+Get recall statistics for all indexes
+
+```sql
+SELECT * FROM pg_vector_recall_stats();
+```
+
+Get a summary with human-readable index names
+
+```sql
+SELECT * FROM pg_vector_recall_summary();
+```
+
+Get current recall for a specific index
+
+```sql
+SELECT pg_vector_recall_get('index_name'::regclass::oid);
+```
+
+Reset statistics for an index
+
+```sql
+SELECT pg_vector_recall_reset('index_name'::regclass::oid);
+```
+
+#### Function Differences
+
+- `pg_vector_recall_stats()` returns raw statistics with index OIDs
+- `pg_vector_recall_summary()` adds schema and index names for easier interpretation
+
+Both functions return the same metrics, but the summary function joins with
+PostgreSQL's system catalogs to provide human-readable names instead of just
+numeric OIDs.
+
+#### Performance Considerations
+
+For production use, a sample rate of 100-1000 typically provides good insight
+with minimal impact. The default scan limit of 10,000 tuples works well for most
+tables, but you can increase it or set it to -1 for maximum accuracy on smaller
+datasets.
+
## Performance
### Tuning
diff --git a/sql/vector--0.8.0--0.9.0.sql b/sql/vector--0.8.0--0.9.0.sql
new file mode 100644
index 000000000..3d41e070d
--- /dev/null
+++ b/sql/vector--0.8.0--0.9.0.sql
@@ -0,0 +1,62 @@
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "ALTER EXTENSION vector UPDATE TO '0.9.0'" to load this file. \quit
+
+-- Function to get recall statistics for all vector indexes
+CREATE OR REPLACE FUNCTION pg_vector_recall_stats()
+RETURNS TABLE (
+ indexoid oid,
+ total_queries bigint,
+ sampled_queries bigint,
+ total_results_returned bigint,
+ correct_matches bigint,
+ total_expected bigint,
+ current_recall double precision,
+ last_updated timestamptz
+)
+AS 'MODULE_PATHNAME', 'pg_vector_recall_stats'
+LANGUAGE C STRICT VOLATILE;
+
+-- Function to reset recall statistics for a specific index
+CREATE OR REPLACE FUNCTION pg_vector_recall_reset(indexoid oid)
+RETURNS void
+AS 'MODULE_PATHNAME', 'pg_vector_recall_reset'
+LANGUAGE C STRICT VOLATILE;
+
+-- Function to get current recall for a specific index
+CREATE OR REPLACE FUNCTION pg_vector_recall_get(indexoid oid)
+RETURNS double precision
+AS 'MODULE_PATHNAME', 'pg_vector_recall_get'
+LANGUAGE C STRICT VOLATILE;
+
+-- Function to get recall statistics summary with index names
+CREATE OR REPLACE FUNCTION pg_vector_recall_summary()
+RETURNS TABLE (
+ indexoid oid,
+ schema_name name,
+ index_name name,
+ total_queries bigint,
+ sampled_queries bigint,
+ total_results_returned bigint,
+ correct_matches bigint,
+ total_expected bigint,
+ current_recall double precision,
+ last_updated timestamptz
+)
+AS $$
+SELECT
+ s.indexoid,
+ n.nspname AS schema_name,
+ c.relname AS index_name,
+ s.total_queries,
+ s.sampled_queries,
+ s.total_results_returned,
+ s.correct_matches,
+ s.total_expected,
+ s.current_recall,
+ s.last_updated
+FROM pg_vector_recall_stats() s
+JOIN pg_class c ON s.indexoid = c.oid
+JOIN pg_namespace n ON c.relnamespace = n.oid
+WHERE c.relkind = 'i'
+ORDER BY schema_name, index_name;
+$$ LANGUAGE SQL STRICT VOLATILE;
diff --git a/sql/vector.sql b/sql/vector.sql
index 7fc36712b..dd26e588c 100644
--- a/sql/vector.sql
+++ b/sql/vector.sql
@@ -916,3 +916,63 @@ CREATE OPERATOR CLASS sparsevec_l1_ops
OPERATOR 1 <+> (sparsevec, sparsevec) FOR ORDER BY float_ops,
FUNCTION 1 l1_distance(sparsevec, sparsevec),
FUNCTION 3 hnsw_sparsevec_support(internal);
+
+-- Function to get recall statistics for all vector indexes
+CREATE OR REPLACE FUNCTION pg_vector_recall_stats()
+RETURNS TABLE (
+ indexoid oid,
+ total_queries bigint,
+ sampled_queries bigint,
+ total_results_returned bigint,
+ correct_matches bigint,
+ total_expected bigint,
+ current_recall double precision,
+ last_updated timestamptz
+)
+AS 'MODULE_PATHNAME', 'pg_vector_recall_stats'
+LANGUAGE C STRICT VOLATILE;
+
+-- Function to reset recall statistics for a specific index
+CREATE OR REPLACE FUNCTION pg_vector_recall_reset(indexoid oid)
+RETURNS void
+AS 'MODULE_PATHNAME', 'pg_vector_recall_reset'
+LANGUAGE C STRICT VOLATILE;
+
+-- Function to get current recall for a specific index
+CREATE OR REPLACE FUNCTION pg_vector_recall_get(indexoid oid)
+RETURNS double precision
+AS 'MODULE_PATHNAME', 'pg_vector_recall_get'
+LANGUAGE C STRICT VOLATILE;
+
+-- Function to get recall statistics summary with index names
+CREATE OR REPLACE FUNCTION pg_vector_recall_summary()
+RETURNS TABLE (
+ indexoid oid,
+ schema_name name,
+ index_name name,
+ total_queries bigint,
+ sampled_queries bigint,
+ total_results_returned bigint,
+ correct_matches bigint,
+ total_expected bigint,
+ current_recall double precision,
+ last_updated timestamptz
+)
+AS $$
+SELECT
+ s.indexoid,
+ n.nspname AS schema_name,
+ c.relname AS index_name,
+ s.total_queries,
+ s.sampled_queries,
+ s.total_results_returned,
+ s.correct_matches,
+ s.total_expected,
+ s.current_recall,
+ s.last_updated
+FROM pg_vector_recall_stats() s
+JOIN pg_class c ON s.indexoid = c.oid
+JOIN pg_namespace n ON c.relnamespace = n.oid
+WHERE c.relkind = 'i'
+ORDER BY schema_name, index_name;
+$$ LANGUAGE SQL STRICT VOLATILE;
diff --git a/src/hnsw.h b/src/hnsw.h
index 5102bfb5a..5195bfa23 100644
--- a/src/hnsw.h
+++ b/src/hnsw.h
@@ -11,6 +11,7 @@
#include "utils/relptr.h"
#include "utils/sampling.h"
#include "vector.h"
+#include "vector_recall.h"
#define HNSW_MAX_DIM 2000
#define HNSW_MAX_NNZ 1000
@@ -378,6 +379,9 @@ typedef struct HnswScanOpaqueData
/* Support functions */
HnswSupport support;
+
+ /* Recall tracking */
+ VectorRecallTracker recall_tracker;
} HnswScanOpaqueData;
typedef HnswScanOpaqueData * HnswScanOpaque;
diff --git a/src/hnswscan.c b/src/hnswscan.c
index 955998a52..14daa8266 100644
--- a/src/hnswscan.c
+++ b/src/hnswscan.c
@@ -7,6 +7,7 @@
#include "storage/lmgr.h"
#include "utils/float.h"
#include "utils/memutils.h"
+#include "vector_recall.h"
/*
* Algorithm 5 from paper
@@ -144,6 +145,11 @@ hnswbeginscan(Relation index, int nkeys, int norderbys)
maxMemory = (double) work_mem * hnsw_scan_mem_multiplier * 1024.0 + 256;
so->maxMemory = Min(maxMemory, (double) SIZE_MAX);
+ /* Initialize recall tracking */
+ so->recall_tracker.query_value = (Datum) 0;
+ so->recall_tracker.result_count = 0;
+ so->recall_tracker.max_distance = 0.0;
+
scan->opaque = so;
return scan;
@@ -217,6 +223,10 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
/* Release shared lock */
UnlockPage(scan->indexRelation, HNSW_SCAN_LOCK, ShareLock);
+ /* Store query value for recall tracking */
+ so->recall_tracker.query_value = value;
+ so->recall_tracker.result_count = 0;
+
so->first = false;
#if defined(HNSW_MEMORY)
@@ -305,6 +315,15 @@ hnswgettuple(IndexScanDesc scan, ScanDirection dir)
MemoryContextSwitchTo(oldCtx);
+ /* Track for potential recall calculation only if enabled */
+ if (pgvector_track_recall)
+ {
+ if (sc->distance > so->recall_tracker.max_distance)
+ so->recall_tracker.max_distance = sc->distance;
+
+ so->recall_tracker.result_count++;
+ }
+
scan->xs_heaptid = *heaptid;
scan->xs_recheck = false;
scan->xs_recheckorderby = false;
@@ -323,6 +342,9 @@ hnswendscan(IndexScanDesc scan)
{
HnswScanOpaque so = (HnswScanOpaque) scan->opaque;
+ /* Track recall if enabled */
+ TrackVectorQuery(scan->indexRelation, &so->recall_tracker, so->support.procinfo, so->support.collation);
+
MemoryContextDelete(so->tmpCtx);
pfree(so);
diff --git a/src/ivfflat.h b/src/ivfflat.h
index 76608f334..b7518c2d8 100644
--- a/src/ivfflat.h
+++ b/src/ivfflat.h
@@ -12,6 +12,7 @@
#include "utils/sampling.h"
#include "utils/tuplesort.h"
#include "vector.h"
+#include "vector_recall.h"
#if PG_VERSION_NUM >= 150000
#include "common/pg_prng.h"
@@ -282,6 +283,9 @@ typedef struct IvfflatScanOpaqueData
BlockNumber *listPages;
int listIndex;
IvfflatScanList *lists;
+
+ /* Recall tracking */
+ VectorRecallTracker recall_tracker;
} IvfflatScanOpaqueData;
typedef IvfflatScanOpaqueData * IvfflatScanOpaque;
diff --git a/src/ivfscan.c b/src/ivfscan.c
index 6cc5d2efd..a7606023d 100644
--- a/src/ivfscan.c
+++ b/src/ivfscan.c
@@ -11,6 +11,7 @@
#include "pgstat.h"
#include "storage/bufmgr.h"
#include "utils/memutils.h"
+#include "vector_recall.h"
#define GetScanList(ptr) pairingheap_container(IvfflatScanList, ph_node, ptr)
#define GetScanListConst(ptr) pairingheap_const_container(IvfflatScanList, ph_node, ptr)
@@ -307,6 +308,11 @@ ivfflatbeginscan(Relation index, int nkeys, int norderbys)
so->listIndex = 0;
so->lists = palloc(maxProbes * sizeof(IvfflatScanList));
+ /* Initialize recall tracking */
+ so->recall_tracker.query_value = (Datum) 0;
+ so->recall_tracker.result_count = 0;
+ so->recall_tracker.max_distance = 0.0;
+
MemoryContextSwitchTo(oldCtx);
scan->opaque = so;
@@ -342,6 +348,8 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
ItemPointer heaptid;
bool isnull;
+ bool dnull = false;
+ Datum distDatum;
/*
* Index can be used to scan backward, but Postgres doesn't support
@@ -370,6 +378,9 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
IvfflatBench("GetScanItems", GetScanItems(scan, value));
so->first = false;
so->value = value;
+
+ /* Store query value for recall tracking */
+ so->recall_tracker.query_value = value;
}
while (!tuplesort_gettupleslot(so->sortstate, true, false, so->mslot, NULL))
@@ -380,6 +391,21 @@ ivfflatgettuple(IndexScanDesc scan, ScanDirection dir)
IvfflatBench("GetScanItems", GetScanItems(scan, so->value));
}
+ /* Track for potential recall calculation only if enabled */
+ if (pgvector_track_recall)
+ {
+ distDatum = slot_getattr(so->mslot, 1, &dnull);
+ if (!dnull)
+ {
+ double distance = DatumGetFloat8(distDatum);
+
+ if (distance > so->recall_tracker.max_distance)
+ so->recall_tracker.max_distance = distance;
+
+ so->recall_tracker.result_count++;
+ }
+ }
+
heaptid = (ItemPointer) DatumGetPointer(slot_getattr(so->mslot, 2, &isnull));
scan->xs_heaptid = *heaptid;
@@ -396,6 +422,9 @@ ivfflatendscan(IndexScanDesc scan)
{
IvfflatScanOpaque so = (IvfflatScanOpaque) scan->opaque;
+ /* Track recall if enabled */
+ TrackVectorQuery(scan->indexRelation, &so->recall_tracker, so->procinfo, so->collation);
+
/* Free any temporary files */
tuplesort_end(so->sortstate);
diff --git a/src/vector.c b/src/vector.c
index d2312e042..4bc6b861f 100644
--- a/src/vector.c
+++ b/src/vector.c
@@ -48,6 +48,7 @@ _PG_init(void)
HalfvecInit();
HnswInit();
IvfflatInit();
+ InitVectorRecallTracking();
}
/*
diff --git a/src/vector_recall.c b/src/vector_recall.c
new file mode 100644
index 000000000..4bfb0cbd9
--- /dev/null
+++ b/src/vector_recall.c
@@ -0,0 +1,357 @@
+#include "postgres.h"
+
+#include <float.h>
+
+#include "access/heapam.h" /* for heap_getnext / heap_getattr */
+#include "access/table.h"
+#include "catalog/pg_type.h"
+#include "executor/spi.h" /* for ReturnSetInfo, SFRM_Materialize */
+#include "executor/tuptable.h"
+#include "fmgr.h"
+#include "miscadmin.h" /* for work_mem */
+#include "utils/builtins.h"
+#include "utils/guc.h"
+#include "utils/hsearch.h"
+#include "utils/memutils.h"
+#include "utils/relcache.h"
+#include "utils/snapmgr.h"
+#include "utils/timestamp.h"
+#include "vector.h"
+#include "vector_recall.h"
+
+/* GUC variables */
+bool pgvector_track_recall = false;
+int pgvector_recall_sample_rate = 100; /* Sample every 100th query */
+int pgvector_recall_max_scan_tuples = 10000; /* Max tuples to scan for recall estimation */
+
+static HTAB *recall_stats_hash = NULL;
+static MemoryContext recall_context = NULL;
+
+void
+InitVectorRecallTracking(void)
+{
+ HASHCTL info;
+
+ if (recall_context == NULL)
+ {
+ recall_context = AllocSetContextCreate(TopMemoryContext,
+ "Vector Recall Tracking",
+ ALLOCSET_DEFAULT_SIZES);
+ }
+
+ if (recall_stats_hash == NULL)
+ {
+ MemSet(&info, 0, sizeof(info));
+ info.keysize = sizeof(Oid);
+ info.entrysize = sizeof(RecallStatsEntry);
+ info.hcxt = recall_context;
+
+ recall_stats_hash = hash_create("Vector Recall Stats",
+ 32,
+ &info,
+ HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
+ }
+
+ /* Define GUC parameters */
+ DefineCustomBoolVariable("pgvector.track_recall",
+ "Enables recall tracking for vector queries",
+ "When enabled, pgvector will sample queries to measure recall quality.",
+ &pgvector_track_recall,
+ false,
+ PGC_USERSET,
+ 0,
+ NULL, NULL, NULL);
+
+ DefineCustomIntVariable("pgvector.recall_sample_rate",
+ "Sets the sampling rate for recall tracking (1 in N queries)",
+ "Higher values mean less frequent sampling, lower overhead.",
+ &pgvector_recall_sample_rate,
+ 100, 1, 10000,
+ PGC_USERSET,
+ 0,
+ NULL, NULL, NULL);
+
+ DefineCustomIntVariable("pgvector.recall_max_scan_tuples",
+ "Sets the maximum number of tuples to scan for recall estimation",
+ "Higher values provide more accurate recall estimates but may impact performance on large tables. Set to -1 for unlimited scanning.",
+ &pgvector_recall_max_scan_tuples,
+ 10000, -1, INT_MAX,
+ PGC_USERSET,
+ 0,
+ NULL, NULL, NULL);
+}
+
+/*
+ * Track a vector query with safe recall estimation
+ */
+void
+TrackVectorQuery(Relation index, VectorRecallTracker *tracker, FmgrInfo *distance_proc, Oid collation)
+{
+ RecallStatsEntry *entry;
+ bool found;
+
+ /* Early exits for disabled tracking or invalid data */
+ if (!pgvector_track_recall || recall_stats_hash == NULL)
+ return;
+
+ if (tracker->result_count == 0)
+ return;
+
+ entry = (RecallStatsEntry *) hash_search(recall_stats_hash,
+ &index->rd_id,
+ HASH_ENTER,
+ &found);
+
+ if (!found)
+ {
+ MemSet(&entry->stats, 0, sizeof(VectorRecallStats));
+ entry->stats.last_updated = GetCurrentTimestamp();
+ }
+
+ entry->stats.total_queries++;
+ entry->stats.total_results_returned += tracker->result_count;
+
+ if (entry->stats.total_queries % pgvector_recall_sample_rate == 0)
+ {
+ int estimated_expected = tracker->result_count;
+ int estimated_correct = tracker->result_count;
+
+ entry->stats.sampled_queries++;
+
+ /* Enhanced estimation using distance-threshold scan */
+ if (tracker->max_distance > 0)
+ {
+ /* Identify heap relation and attribute number */
+ Oid heapOid = index->rd_index->indrelid;
+ int16 attnum = index->rd_index->indkey.values[0];
+ Relation heapRel = NULL;
+ TableScanDesc heapScan = NULL;
+ volatile int count_within = 0;
+ volatile bool exceeded = false;
+ volatile int tuples_scanned = 0;
+
+ PG_TRY();
+ {
+ HeapTuple tuple;
+ TupleDesc tupDesc;
+ Datum distanceDatum;
+ bool isnull;
+ double dist;
+
+ heapRel = table_open(heapOid, AccessShareLock);
+ heapScan = table_beginscan(heapRel, GetActiveSnapshot(), 0, NULL);
+ tupDesc = RelationGetDescr(heapRel);
+
+ while ((tuple = heap_getnext(heapScan, ForwardScanDirection)) != NULL)
+ {
+ Datum value;
+
+ tuples_scanned++;
+
+ /* Limit scan size to prevent performance issues on large tables */
+ if (pgvector_recall_max_scan_tuples > 0 && tuples_scanned > pgvector_recall_max_scan_tuples)
+ break;
+
+ value = heap_getattr(tuple, attnum, tupDesc, &isnull);
+ if (isnull)
+ continue;
+
+ if (distance_proc != NULL) {
+ distanceDatum = FunctionCall2Coll(distance_proc, collation, tracker->query_value, value);
+ dist = DatumGetFloat8(distanceDatum);
+ if (dist <= tracker->max_distance + DBL_EPSILON)
+ {
+ count_within++;
+
+ /*
+ * Early termination: we only need to know if there
+ * are more than K matches
+ */
+ if (count_within > tracker->result_count)
+ {
+ exceeded = true;
+ break;
+ }
+ }
+ } else {
+ elog(ERROR, "distance_proc is NULL");
+ }
+ }
+
+ if (exceeded)
+ estimated_expected = tracker->result_count + 1; /* conservative lower bound */
+ else
+ estimated_expected = count_within;
+
+ /*
+ * Correct matches is the minimum of what we returned vs what
+ * exists within threshold
+ */
+ estimated_correct = (estimated_expected < tracker->result_count) ? estimated_expected : tracker->result_count;
+ }
+ PG_CATCH();
+ {
+ /* Ensure cleanup on error */
+ if (heapScan != NULL)
+ table_endscan(heapScan);
+ if (heapRel != NULL)
+ table_close(heapRel, AccessShareLock);
+
+ PG_RE_THROW();
+ }
+ PG_END_TRY();
+
+ /* Clean up resources */
+ if (heapScan != NULL)
+ table_endscan(heapScan);
+ if (heapRel != NULL)
+ table_close(heapRel, AccessShareLock);
+ }
+
+ entry->stats.correct_matches += estimated_correct;
+ entry->stats.total_expected += estimated_expected;
+
+ if (entry->stats.total_expected > 0)
+ entry->stats.current_recall = (double) entry->stats.correct_matches / entry->stats.total_expected;
+
+ entry->stats.last_updated = GetCurrentTimestamp();
+ }
+}
+
+double
+GetCurrentRecall(Oid indexoid)
+{
+ RecallStatsEntry *entry;
+
+ if (recall_stats_hash == NULL)
+ return -1.0;
+
+ entry = (RecallStatsEntry *) hash_search(recall_stats_hash,
+ &indexoid,
+ HASH_FIND,
+ NULL);
+
+ if (entry == NULL || entry->stats.total_expected == 0)
+ return -1.0;
+
+ return entry->stats.current_recall;
+}
+
+void
+ResetRecallStats(Oid indexoid)
+{
+ RecallStatsEntry *entry;
+
+ if (recall_stats_hash == NULL)
+ return;
+
+ entry = (RecallStatsEntry *) hash_search(recall_stats_hash,
+ &indexoid,
+ HASH_FIND,
+ NULL);
+
+ if (entry != NULL)
+ {
+ MemSet(&entry->stats, 0, sizeof(VectorRecallStats));
+ entry->stats.last_updated = GetCurrentTimestamp();
+ }
+}
+
+/*
+ * SQL function to get recall statistics
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(pg_vector_recall_stats);
+Datum
+pg_vector_recall_stats(PG_FUNCTION_ARGS)
+{
+ ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
+ TupleDesc tupdesc;
+ Tuplestorestate *tupstore;
+ MemoryContext per_query_ctx;
+ MemoryContext oldcontext;
+ HASH_SEQ_STATUS status;
+ RecallStatsEntry *entry;
+
+ if (!(rsinfo->allowedModes & SFRM_Materialize))
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("materialize mode required, but it is not allowed in this context")));
+
+ tupdesc = CreateTemplateTupleDesc(8);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "indexoid", OIDOID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "total_queries", INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "sampled_queries", INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "total_results_returned", INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "correct_matches", INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "total_expected", INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "current_recall", FLOAT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "last_updated", TIMESTAMPTZOID, -1, 0);
+
+ per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
+ oldcontext = MemoryContextSwitchTo(per_query_ctx);
+
+ tupstore = tuplestore_begin_heap(true, false, work_mem);
+ rsinfo->returnMode = SFRM_Materialize;
+ rsinfo->setResult = tupstore;
+ rsinfo->setDesc = tupdesc;
+
+ MemoryContextSwitchTo(oldcontext);
+
+ if (recall_stats_hash == NULL)
+ return (Datum) 0;
+
+ hash_seq_init(&status, recall_stats_hash);
+ while ((entry = hash_seq_search(&status)) != NULL)
+ {
+ Datum values[8];
+ bool nulls[8];
+
+ MemSet(values, 0, sizeof(values));
+ MemSet(nulls, false, sizeof(nulls));
+
+ values[0] = ObjectIdGetDatum(entry->indexoid);
+ values[1] = Int64GetDatum(entry->stats.total_queries);
+ values[2] = Int64GetDatum(entry->stats.sampled_queries);
+ values[3] = Int64GetDatum(entry->stats.total_results_returned);
+ values[4] = Int64GetDatum(entry->stats.correct_matches);
+ values[5] = Int64GetDatum(entry->stats.total_expected);
+ values[6] = Float8GetDatum(entry->stats.current_recall);
+ values[7] = TimestampTzGetDatum(entry->stats.last_updated);
+
+ tuplestore_putvalues(tupstore, tupdesc, values, nulls);
+ }
+
+ return (Datum) 0;
+}
+
+/*
+ * SQL function to reset recall statistics for a specific index
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(pg_vector_recall_reset);
+Datum
+pg_vector_recall_reset(PG_FUNCTION_ARGS)
+{
+ Oid indexoid = PG_GETARG_OID(0);
+
+ ResetRecallStats(indexoid);
+
+ PG_RETURN_VOID();
+}
+
+/*
+ * SQL function to get current recall for a specific index
+ */
+FUNCTION_PREFIX PG_FUNCTION_INFO_V1(pg_vector_recall_get);
+Datum
+pg_vector_recall_get(PG_FUNCTION_ARGS)
+{
+ Oid indexoid = PG_GETARG_OID(0);
+ double recall;
+
+ recall = GetCurrentRecall(indexoid);
+
+ if (recall < 0)
+ PG_RETURN_NULL();
+
+ PG_RETURN_FLOAT8(recall);
+}
diff --git a/src/vector_recall.h b/src/vector_recall.h
new file mode 100644
index 000000000..0d572978f
--- /dev/null
+++ b/src/vector_recall.h
@@ -0,0 +1,44 @@
+#ifndef VECTOR_RECALL_H
+#define VECTOR_RECALL_H
+
+#include "postgres.h"
+
+typedef struct VectorRecallStats
+{
+ int64 total_queries;
+ int64 sampled_queries;
+ int64 total_results_returned;
+ int64 correct_matches;
+ int64 total_expected;
+ double current_recall;
+ TimestampTz last_updated;
+} VectorRecallStats;
+
+double GetCurrentRecall(Oid indexoid);
+void ResetRecallStats(Oid indexoid);
+
+typedef struct RecallStatsEntry
+{
+ Oid indexoid;
+ VectorRecallStats stats;
+} RecallStatsEntry;
+
+typedef struct VectorRecallTracker
+{
+ Datum query_value;
+ int result_count; /* number of results returned */
+ double max_distance; /* distance of the farthest (k-th) result */
+} VectorRecallTracker;
+
+/*
+ * Recall tracking configuration
+ */
+extern bool pgvector_track_recall;
+extern int pgvector_recall_sample_rate;
+extern int pgvector_recall_max_scan_tuples;
+
+void InitVectorRecallTracking(void);
+
+void TrackVectorQuery(Relation index, VectorRecallTracker *tracker, FmgrInfo *distance_proc, Oid collation);
+
+#endif
diff --git a/test/expected/track_recall.out b/test/expected/track_recall.out
new file mode 100644
index 000000000..468ff6758
--- /dev/null
+++ b/test/expected/track_recall.out
@@ -0,0 +1,32 @@
+SET pgvector.track_recall = on;
+SET pgvector.recall_sample_rate = 1;
+SET pgvector.recall_max_scan_tuples = -1;
+SELECT pg_vector_recall_stats();
+ pg_vector_recall_stats
+------------------------
+(0 rows)
+
+SELECT pg_vector_recall_summary();
+ pg_vector_recall_summary
+--------------------------
+(0 rows)
+
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX t_idx ON t USING hnsw (val vector_l2_ops);
+SELECT pg_vector_recall_get('t_idx'::regclass::oid);
+ pg_vector_recall_get
+----------------------
+
+(1 row)
+
+SELECT pg_vector_recall_reset('t_idx'::regclass::oid);
+ pg_vector_recall_reset
+------------------------
+
+(1 row)
+
+DROP TABLE t;
+SET pgvector.track_recall = off;
+SET pgvector.recall_sample_rate = 100;
+SET pgvector.recall_max_scan_tuples = 10000;
diff --git a/test/sql/track_recall.sql b/test/sql/track_recall.sql
new file mode 100644
index 000000000..9749d05f7
--- /dev/null
+++ b/test/sql/track_recall.sql
@@ -0,0 +1,19 @@
+SET pgvector.track_recall = on;
+SET pgvector.recall_sample_rate = 1;
+SET pgvector.recall_max_scan_tuples = -1;
+
+SELECT pg_vector_recall_stats();
+SELECT pg_vector_recall_summary();
+
+CREATE TABLE t (val vector(3));
+INSERT INTO t (val) VALUES ('[0,0,0]'), ('[1,2,3]'), ('[1,1,1]'), (NULL);
+CREATE INDEX t_idx ON t USING hnsw (val vector_l2_ops);
+
+SELECT pg_vector_recall_get('t_idx'::regclass::oid);
+SELECT pg_vector_recall_reset('t_idx'::regclass::oid);
+
+DROP TABLE t;
+
+SET pgvector.track_recall = off;
+SET pgvector.recall_sample_rate = 100;
+SET pgvector.recall_max_scan_tuples = 10000;
diff --git a/vector.control b/vector.control
index 7bfc0f1fa..5b2013348 100644
--- a/vector.control
+++ b/vector.control
@@ -1,4 +1,4 @@
comment = 'vector data type and ivfflat and hnsw access methods'
-default_version = '0.8.0'
+default_version = '0.9.0'
module_pathname = '$libdir/vector'
relocatable = true
view thread (3+ messages) latest in thread
Message-ID: <gh-pgvector-pgvector-863@github.com>
Permalink: ../gh-pgvector-pgvector-863@github.com/
· ·
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox