pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
From: postsql (@postsql) <noreply+postsql@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] PR #1037: Avoid full detoasting in vector_dims and subvector for vector and hal…
Date: Sat, 03 Oct 2026 14:09:23 +0000
Message-ID: <gh-pgvector-pgvector-1037@github.com> (raw)

## Summary

High-dimensional embeddings (e.g., `vector(1536)` at ~6.1 KB, `vector(3072)` at ~12.3 KB, or `halfvec` up to 16,000 dimensions at ~32 KB) exceed PostgreSQL's `TOAST_TUPLE_THRESHOLD` (~2 KB) and are stored out-of-line in TOAST tables (`STORAGE = external`).

Currently, `vector_dims()` and `subvector()` for both `vector` and `halfvec` call `PG_GETARG_VECTOR_P(0)` / `PG_GETARG_HALFVEC_P(0)` (`PG_DETOAST_DATUM`), which unconditionally fetches and reassembles **all** TOAST chunks of a vector—even when only the dimension count is needed or when extracting a small prefix slice (such as in two-stage Matryoshka Representation Learning / MRL retrieval via `subvector(embedding, 1, 128)`).

This PR avoids full detoasting in `vector_dims` and `subvector` for both `vector` and `halfvec` using standard PostgreSQL `toast_raw_datum_size()` and `PG_DETOAST_DATUM_SLICE()`.

## Changes

1. **`vector_dims(vector)` & `vector_dims(halfvec)`** ([`src/vector.c`](file:///usr/local/google/home/hannuk/pgvector/src/vector.c#L756-L765), [`src/halfvec.c`](file:///usr/local/google/home/hannuk/pgvector/src/halfvec.c#L692-L701)):
   - Since `Vector` and `HalfVector` have a fixed 8-byte header (`offsetof(Vector, x) == 8`) followed by `dim` fixed-width elements (`sizeof(float)` or `sizeof(half)`), the dimension count can be computed directly from `toast_raw_datum_size(PG_GETARG_DATUM(0))`:
     ```c
     Datum raw_datum = PG_GETARG_DATUM(0);
     Size  raw_size  = toast_raw_datum_size(raw_datum);
     int32 dim       = (int32) ((raw_size - offsetof(Vector, x)) / sizeof(float));
     ```
   - For out-of-line toasted datums, `toast_raw_datum_size()` reads `va_rawsize` directly from the 18-byte inline TOAST pointer on the main heap tuple with **zero TOAST index or TOAST heap buffer pins**.

2. **`subvector(vector, int, int)` & `subvector(halfvec, int, int)`** ([`src/vector.c`](file:///usr/local/google/home/hannuk/pgvector/src/vector.c#L984-L1038), [`src/halfvec.c`](file:///usr/local/google/home/hannuk/pgvector/src/halfvec.c#L940-L994)):
   - Computes the input dimension `a_dim` via `toast_raw_datum_size(raw_datum)` and preserves the exact existing bounds and overflow checks.
   - Fetches only the required byte range `[sliceoffset, sliceoffset + slicelength)` via `PG_DETOAST_DATUM_SLICE(raw_datum, sliceoffset, slicelength)`:
     ```c
     sliceoffset = (offsetof(Vector, x) - VARHDRSZ) + (start - 1) * sizeof(float);
     slicelength = dim * sizeof(float);
     sliced = PG_DETOAST_DATUM_SLICE(raw_datum, sliceoffset, slicelength);
     memcpy(result->x, VARDATA_ANY(sliced), slicelength);
     if ((Pointer) sliced != DatumGetPointer(raw_datum))
         pfree(sliced);
     ```
   - Because `vector` and `halfvec` default to `STORAGE = external` (uncompressed), PostgreSQL's `toast_fetch_datum_slice()` only fetches the TOAST chunks overlapping the requested slice (e.g., 1 chunk instead of 4–16 chunks for MRL prefix queries). If a column has been altered to `STORAGE EXTENDED` (compressed), `PG_DETOAST_DATUM_SLICE()` transparently handles prefix decompression as well.

## Benchmark Results

Measured over 10 iterations on out-of-line toasted vectors (standard PostgreSQL TOAST):

| Workload | Before (Full Detoast) | After (Slice-Aware) | Speedup | TOAST Heap Chunks Read / Row |
| :--- | ---: | ---: | ---: | :--- |
| `vector_dims(emb)` (`1,000` rows, `vector(5376)`, `21.5 KB`/row) | 173.55 ms | **1.34 ms** | **129×** | `11` → **`0`** |
| `subvector(emb, 1, 128)` (`2,000` rows, `vector(1536)`, `6.1 KB`/row) | 168.22 ms | **105.54 ms** | **1.60×** | `4` → **`1`** |
| `subvector(emb, 1, 256)` (`1,000` rows, `vector(5376)`, `21.5 KB`/row) | 173.55 ms | **53.50 ms** | **3.24×** | `11` → **`1`** |

*(On PostgreSQL builds with [Direct TOAST](https://commitfest.postgresql.org/patch/7267/) , the same `subvector` queries run **2.33×–3.72× faster** on `vector(1536)` and **6.62× faster** on `vector(5376)` by also eliminating the TOAST B-tree index probe.)*

## Testing

Extended [`test/sql/vector_type.sql`](file:///usr/local/google/home/hannuk/pgvector/test/sql/vector_type.sql#L143-L153) and [`test/sql/halfvec.sql`](file:///usr/local/google/home/hannuk/pgvector/test/sql/halfvec.sql#L137-L147) with table-backed test cases covering all three on-disk varlena layouts:
- Short 1-byte inline varlenas (`VARATT_IS_SHORT`, 5 dimensions),
- Multi-chunk uncompressed `STORAGE EXTERNAL` TOAST tuples (`1000`-dim `vector` and `2000`-dim `halfvec`) across prefix slices, cross-chunk middle slices, suffix slices, negative start indices, and out-of-bounds error checks,
- Compressed `STORAGE EXTENDED` TOAST tuples (`VARATT_IS_COMPRESSED`).

inline patch 1: src/halfvec.c, src/vector.c, test/expected/halfvec.out and 3 more (+116/-22 lines) download inline-1.patchdiff --git a/src/halfvec.c b/src/halfvec.c index 47f5464c3..6adf49236 100644 --- a/src/halfvec.c +++ b/src/halfvec.c @@ -2,6 +2,7 @@ #include <math.h> +#include "access/detoast.h" #include "bitvec.h" #include "catalog/pg_type.h" #include "common/shortest_dec.h" @@ -692,9 +693,11 @@ FUNCTION_PREFIX PG_FUNCTION_INFO_V1(halfvec_vector_dims); Datum halfvec_vector_dims(PG_FUNCTION_ARGS) { - HalfVector *a = PG_GETARG_HALFVEC_P(0); + Datum raw_datum = PG_GETARG_DATUM(0); + Size raw_size = toast_raw_datum_size(raw_datum); + int32 dim = (int32) ((raw_size - offsetof(HalfVector, x)) / sizeof(half)); - PG_RETURN_INT32(a->dim); + PG_RETURN_INT32(dim); } /* @@ -940,13 +943,17 @@ FUNCTION_PREFIX PG_FUNCTION_INFO_V1(halfvec_subvector); Datum halfvec_subvector(PG_FUNCTION_ARGS) { - HalfVector *a = PG_GETARG_HALFVEC_P(0); + Datum raw_datum = PG_GETARG_DATUM(0); int32 start = PG_GETARG_INT32(1); int32 count = PG_GETARG_INT32(2); + Size raw_size = toast_raw_datum_size(raw_datum); + int32 a_dim = (int32) ((raw_size - offsetof(HalfVector, x)) / sizeof(half)); int32 end; - half *ax = a->x; HalfVector *result; int32 dim; + int32 sliceoffset; + int32 slicelength; + struct varlena *sliced; if (count < 1) ereport(ERROR, @@ -954,18 +961,18 @@ halfvec_subvector(PG_FUNCTION_ARGS) errmsg("halfvec must have at least 1 dimension"))); /* - * Check if (start + count > a->dim), avoiding integer overflow. a->dim - * and count are both positive, so a->dim - count won't overflow. + * Check if (start + count > a_dim), avoiding integer overflow. a_dim + * and count are both positive, so a_dim - count won't overflow. */ - if (start > a->dim - count) - end = a->dim + 1; + if (start > a_dim - count) + end = a_dim + 1; else end = start + count; /* Indexing starts at 1, like substring */ if (start < 1) start = 1; - else if (start > a->dim) + else if (start > a_dim) ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("halfvec must have at least 1 dimension"))); @@ -974,8 +981,14 @@ halfvec_subvector(PG_FUNCTION_ARGS) CheckDim(dim); result = InitHalfVector(dim); - for (int i = 0; i < dim; i++) - result->x[i] = ax[start - 1 + i]; + sliceoffset = (offsetof(HalfVector, x) - VARHDRSZ) + (start - 1) * sizeof(half); + slicelength = dim * sizeof(half); + sliced = PG_DETOAST_DATUM_SLICE(raw_datum, sliceoffset, slicelength); + + memcpy(result->x, VARDATA_ANY(sliced), slicelength); + + if ((Pointer) sliced != DatumGetPointer(raw_datum)) + pfree(sliced); PG_RETURN_POINTER(result); } diff --git a/src/vector.c b/src/vector.c index ebd78c14a..139f885ac 100644 --- a/src/vector.c +++ b/src/vector.c @@ -2,6 +2,7 @@ #include <math.h> +#include "access/detoast.h" #include "bitutils.h" #include "bitvec.h" #include "catalog/pg_type.h" @@ -756,9 +757,11 @@ FUNCTION_PREFIX PG_FUNCTION_INFO_V1(vector_dims); Datum vector_dims(PG_FUNCTION_ARGS) { - Vector *a = PG_GETARG_VECTOR_P(0); + Datum raw_datum = PG_GETARG_DATUM(0); + Size raw_size = toast_raw_datum_size(raw_datum); + int32 dim = (int32) ((raw_size - offsetof(Vector, x)) / sizeof(float)); - PG_RETURN_INT32(a->dim); + PG_RETURN_INT32(dim); } /* @@ -984,13 +987,17 @@ FUNCTION_PREFIX PG_FUNCTION_INFO_V1(subvector); Datum subvector(PG_FUNCTION_ARGS) { - Vector *a = PG_GETARG_VECTOR_P(0); + Datum raw_datum = PG_GETARG_DATUM(0); int32 start = PG_GETARG_INT32(1); int32 count = PG_GETARG_INT32(2); + Size raw_size = toast_raw_datum_size(raw_datum); + int32 a_dim = (int32) ((raw_size - offsetof(Vector, x)) / sizeof(float)); int32 end; - float *ax = a->x; Vector *result; int dim; + int32 sliceoffset; + int32 slicelength; + struct varlena *sliced; if (count < 1) ereport(ERROR, @@ -998,18 +1005,18 @@ subvector(PG_FUNCTION_ARGS) errmsg("vector must have at least 1 dimension"))); /* - * Check if (start + count > a->dim), avoiding integer overflow. a->dim - * and count are both positive, so a->dim - count won't overflow. + * Check if (start + count > a_dim), avoiding integer overflow. a_dim + * and count are both positive, so a_dim - count won't overflow. */ - if (start > a->dim - count) - end = a->dim + 1; + if (start > a_dim - count) + end = a_dim + 1; else end = start + count; /* Indexing starts at 1, like substring */ if (start < 1) start = 1; - else if (start > a->dim) + else if (start > a_dim) ereport(ERROR, (errcode(ERRCODE_DATA_EXCEPTION), errmsg("vector must have at least 1 dimension"))); @@ -1018,8 +1025,14 @@ subvector(PG_FUNCTION_ARGS) CheckDim(dim); result = InitVector(dim); - for (int i = 0; i < dim; i++) - result->x[i] = ax[start - 1 + i]; + sliceoffset = (offsetof(Vector, x) - VARHDRSZ) + (start - 1) * sizeof(float); + slicelength = dim * sizeof(float); + sliced = PG_DETOAST_DATUM_SLICE(raw_datum, sliceoffset, slicelength); + + memcpy(result->x, VARDATA_ANY(sliced), slicelength); + + if ((Pointer) sliced != DatumGetPointer(raw_datum)) + pfree(sliced); PG_RETURN_POINTER(result); } diff --git a/test/expected/halfvec.out b/test/expected/halfvec.out index c7891508b..a5e136685 100644 --- a/test/expected/halfvec.out +++ b/test/expected/halfvec.out @@ -590,6 +590,29 @@ SELECT subvector('[1,2,3,4,5]'::halfvec, -2147483644, 2147483647); [1,2] (1 row) +CREATE TABLE t (id int, val halfvec); +INSERT INTO t (id, val) VALUES (1, '[1,2,3,4,5]'); +INSERT INTO t (id, val) SELECT 2, array_agg(n)::halfvec FROM generate_series(1, 2000) n; +ALTER TABLE t ALTER COLUMN val SET STORAGE EXTENDED; +INSERT INTO t (id, val) SELECT 3, array_agg(1)::halfvec FROM generate_series(1, 2000) n; +SELECT id, vector_dims(val), subvector(val, 1, 3), subvector(val, 995, 4), subvector(val, 1998, 5), subvector(val, -1, 5) FROM t WHERE id >= 2 ORDER BY id; + id | vector_dims | subvector | subvector | subvector | subvector +----+-------------+-----------+-------------------+------------------+----------- + 2 | 2000 | [1,2,3] | [995,996,997,998] | [1998,1999,2000] | [1,2,3] + 3 | 2000 | [1,1,1] | [1,1,1,1] | [1,1,1] | [1,1,1] +(2 rows) + +SELECT vector_dims(val), subvector(val, 2, 3) FROM t WHERE id = 1; + vector_dims | subvector +-------------+----------- + 5 | [2,3,4] +(1 row) + +SELECT subvector(val, 1, 0) FROM t WHERE id = 2; +ERROR: halfvec must have at least 1 dimension +SELECT subvector(val, 2001, 1) FROM t WHERE id = 2; +ERROR: halfvec must have at least 1 dimension +DROP TABLE t; SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::halfvec, '[3,5,7]']) v; avg ----------- diff --git a/test/expected/vector_type.out b/test/expected/vector_type.out index 38e388135..e8900221c 100644 --- a/test/expected/vector_type.out +++ b/test/expected/vector_type.out @@ -626,6 +626,29 @@ SELECT subvector('[1,2,3,4,5]'::vector, -2147483644, 2147483647); [1,2] (1 row) +CREATE TABLE t (id int, val vector); +INSERT INTO t (id, val) VALUES (1, '[1,2,3,4,5]'); +INSERT INTO t (id, val) SELECT 2, array_agg(n)::vector FROM generate_series(1, 1000) n; +ALTER TABLE t ALTER COLUMN val SET STORAGE EXTENDED; +INSERT INTO t (id, val) SELECT 3, array_agg(1)::vector FROM generate_series(1, 1000) n; +SELECT id, vector_dims(val), subvector(val, 1, 3), subvector(val, 498, 4), subvector(val, 998, 5), subvector(val, -1, 5) FROM t WHERE id >= 2 ORDER BY id; + id | vector_dims | subvector | subvector | subvector | subvector +----+-------------+-----------+-------------------+----------------+----------- + 2 | 1000 | [1,2,3] | [498,499,500,501] | [998,999,1000] | [1,2,3] + 3 | 1000 | [1,1,1] | [1,1,1,1] | [1,1,1] | [1,1,1] +(2 rows) + +SELECT vector_dims(val), subvector(val, 2, 3) FROM t WHERE id = 1; + vector_dims | subvector +-------------+----------- + 5 | [2,3,4] +(1 row) + +SELECT subvector(val, 1, 0) FROM t WHERE id = 2; +ERROR: vector must have at least 1 dimension +SELECT subvector(val, 1001, 1) FROM t WHERE id = 2; +ERROR: vector must have at least 1 dimension +DROP TABLE t; SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v; avg ----------- diff --git a/test/sql/halfvec.sql b/test/sql/halfvec.sql index edfd10262..aef04f4bd 100644 --- a/test/sql/halfvec.sql +++ b/test/sql/halfvec.sql @@ -134,6 +134,17 @@ SELECT subvector('[1,2,3,4,5]'::halfvec, 2147483647, 10); SELECT subvector('[1,2,3,4,5]'::halfvec, 3, 2147483647); SELECT subvector('[1,2,3,4,5]'::halfvec, -2147483644, 2147483647); +CREATE TABLE t (id int, val halfvec); +INSERT INTO t (id, val) VALUES (1, '[1,2,3,4,5]'); +INSERT INTO t (id, val) SELECT 2, array_agg(n)::halfvec FROM generate_series(1, 2000) n; +ALTER TABLE t ALTER COLUMN val SET STORAGE EXTENDED; +INSERT INTO t (id, val) SELECT 3, array_agg(1)::halfvec FROM generate_series(1, 2000) n; +SELECT id, vector_dims(val), subvector(val, 1, 3), subvector(val, 995, 4), subvector(val, 1998, 5), subvector(val, -1, 5) FROM t WHERE id >= 2 ORDER BY id; +SELECT vector_dims(val), subvector(val, 2, 3) FROM t WHERE id = 1; +SELECT subvector(val, 1, 0) FROM t WHERE id = 2; +SELECT subvector(val, 2001, 1) FROM t WHERE id = 2; +DROP TABLE t; + SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::halfvec, '[3,5,7]']) v; SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::halfvec, '[3,5,7]', NULL]) v; SELECT avg(v) FROM unnest(ARRAY[]::halfvec[]) v; diff --git a/test/sql/vector_type.sql b/test/sql/vector_type.sql index 565ec043b..d61c481e3 100644 --- a/test/sql/vector_type.sql +++ b/test/sql/vector_type.sql @@ -140,6 +140,17 @@ SELECT subvector('[1,2,3,4,5]'::vector, 2147483647, 10); SELECT subvector('[1,2,3,4,5]'::vector, 3, 2147483647); SELECT subvector('[1,2,3,4,5]'::vector, -2147483644, 2147483647); +CREATE TABLE t (id int, val vector); +INSERT INTO t (id, val) VALUES (1, '[1,2,3,4,5]'); +INSERT INTO t (id, val) SELECT 2, array_agg(n)::vector FROM generate_series(1, 1000) n; +ALTER TABLE t ALTER COLUMN val SET STORAGE EXTENDED; +INSERT INTO t (id, val) SELECT 3, array_agg(1)::vector FROM generate_series(1, 1000) n; +SELECT id, vector_dims(val), subvector(val, 1, 3), subvector(val, 498, 4), subvector(val, 998, 5), subvector(val, -1, 5) FROM t WHERE id >= 2 ORDER BY id; +SELECT vector_dims(val), subvector(val, 2, 3) FROM t WHERE id = 1; +SELECT subvector(val, 1, 0) FROM t WHERE id = 2; +SELECT subvector(val, 1001, 1) FROM t WHERE id = 2; +DROP TABLE t; + SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]']) v; SELECT avg(v) FROM unnest(ARRAY['[1,2,3]'::vector, '[3,5,7]', NULL]) v; SELECT avg(v) FROM unnest(ARRAY[]::vector[]) v;

view thread (3+ messages)  latest in thread

Message-ID: <gh-pgvector-pgvector-1037@github.com>
Permalink:  ../gh-pgvector-pgvector-1037@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