Metadata-Version: 2.5
Name: pgshrink
Version: 0.4.2
Summary: Measure how much smaller your pgvector embeddings can get on your own data, and get the SQL to do it.
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: numpy>=1.26
Requires-Dist: pgvector>=0.4
Requires-Dist: psycopg[binary]>=3.2
Description-Content-Type: text/markdown

# pgshrink

**How much smaller can your pgvector index get without changing your search results? Measure it on your own data in seconds, then get the SQL.**

[![CI](https://github.com/alessandroamormino/pgshrink/actions/workflows/ci.yml/badge.svg)](https://github.com/alessandroamormino/pgshrink/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/pgshrink.svg)](https://pypi.org/project/pgshrink/)
[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
![Python](https://img.shields.io/badge/python-3.10%2B-blue)
![pgvector](https://img.shields.io/badge/pgvector-0.7%2B-336791)

![pgshrink demo](docs/demo.gif)

pgvector can store and index vectors as `halfvec` (16-bit), as `bit` via `binary_quantize()`, or truncated with `subvector()`. The docs say to quantize at scale, but they can't tell you how much quality *your* embeddings lose. That depends on your model and your data.

`pgshrink` reads your vector column and tries every layout pgvector supports. For each one it tells you:

- **fidelity**: how often you get the same top-k results as today, with a 95% confidence interval;
- **index size**: how large the HNSW index would be, from a model fitted on real pgvector indexes;
- **a verdict**: whether shrinking is worth doing *now*, based on whether today's index already fits in the memory Postgres uses, plus how much smaller the index could get;
- **the SQL**: the index and the query to switch to the recommended layout.

It needs no labels and no test queries, and it **never writes to your database**.

## Example: 171k documents, 1024-dim embeddings

The demo above runs on TREC-COVID embedded with Qwen3-Embedding-0.6B. We then built every recommended index and queried it through real pgvector HNSW to check the predictions ([full method](docs/validation.md)):

| layout | HNSW index | pgshrink fidelity (predicted) | real HNSW fidelity | p50 query |
|---|---|---|---|---|
| `vector` (today) | 1338 MB | 100% | 100% | 324 ms\* |
| `halfvec` | **446 MB** | 100.0% | 98.1% | 2.2 ms |
| `binary_quantize` + rerank ×10 | **70 MB** | 98.9% | 97.6% | 2.0 ms |

\* The 1.3 GB index did not fit in this server's memory and the compressed ones did. The speedup depends on your hardware and settings, so measure it on yours. The index sizes and fidelity numbers are what pgshrink predicts.

Two things people usually don't expect:
- **`halfvec` makes the index ~3× smaller, not 2×.** pgvector packs whole rows into 8 KB pages, so a 4 KB `vector` fills a page alone, while three `halfvec` rows fit in one.
- **Binary + rerank shrinks the index ~19× and keeps ~98% of results.** The rerank reads the original column, so the *table* stays the same size. Only the index, which is what needs to stay in RAM, shrinks.

## Install

```bash
pip install pgshrink        # or: uv tool install pgshrink
```

You need Python 3.10+ and network access to your Postgres. Nothing is installed in the database.

## Quick start

```bash
pgshrink analyze "postgresql://user@host:5432/db" --table documents --column embedding
```

Pass the password via `PGPASSWORD` or `~/.pgpass` rather than in the URL. pgshrink reads the distance (cosine, inner product or L2) from your existing vector index; if there is none, add `--metric cosine`.

To get the full report as JSON (for CI, dashboards or scripts):

```bash
pgshrink analyze "$DATABASE_URL" --table documents --column embedding --json > pgshrink.json
```

## How it works

```mermaid
flowchart LR
    A[(your table)] -->|"200 random rows<br/>as queries"| Q[queries]
    A -->|"COPY ... BINARY<br/>whole column, streamed"| S[exact search<br/>on current vectors]
    Q --> S
    S --> T[true top-k<br/>per query]
    A --> L["each layout:<br/>halfvec · subvector · binary_quantize<br/>± rerank"]
    Q --> L
    L --> C{same top-k<br/>as today?}
    T --> C
    C --> R[report + SQL]
```

1. **Queries.** About 200 random rows from your table serve as queries, and each one is excluded from its own results.
2. **Ground truth.** pgshrink streams the whole column with `COPY ... (FORMAT BINARY)` (about 700 MB for 171k × 1024 dims, read in ~6 s locally) and computes the exact top-k for every query. It compares against the full table on purpose: a sample would make reranking look better than it is, because 100 candidates cover far more of 5,000 rows than of 1,000,000.
3. **Layouts.** It reproduces in numpy exactly what pgvector computes (`halfvec` rounding, `subvector` truncation, `binary_quantize` signs, Hamming ranking, reranking on the original vectors). The integration tests check this against a real pgvector.
4. **Fidelity.** For each layout, it reports the share of the true top-k found in the layout's top-k, averaged over queries, with a bootstrap 95% CI. A result as close as the k-th true neighbor counts as found, so another copy of a duplicated vector is not a miss.
5. **Recommendation.** Among the layouts whose *lower* CI bound reaches `--target` (default 95%), sizes within 25% of the smallest count as equal, and the one with the least rerank work wins. This avoids trading fidelity and twice the rerank cost for a few MB.
6. **Verdict.** It compares today's index with the server's `shared_buffers` and `effective_cache_size`:

| verdict | when | what it means |
|---|---|---|
| `NOT NEEDED NOW` | index ≤ `shared_buffers` | searches already run from memory; a smaller index saves RAM but won't make them noticeably faster. The SQL is printed for later. |
| `OPTIONAL` | index ≤ `effective_cache_size` | the OS may already cache it; shrinking frees memory and keeps searches fast as the table grows |
| `RECOMMENDED` | index > `effective_cache_size` | searches likely read from disk; an index that fits in memory can make them much faster |

`effective_cache_size` is a setting your admin chose, not measured RAM, so read the verdict together with what you know about your server.

The verdict also says **how many rows each index can grow to** before it outgrows `shared_buffers` and `effective_cache_size`. For TREC-COVID, today's index stops fitting in `effective_cache_size` at ~524k rows, while the binary one fits up to ~10M. This counts index size only: rerank fidelity drops as the table grows, so re-run pgshrink when you get close.

## Applying the recommendation

pgshrink prints the SQL but never runs it. **Try it on a copy or a replica first.**

**1. Build the new index next to the old one.** `CONCURRENTLY` doesn't block writes.

```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS documents_embedding_binary1024_idx
  ON documents USING hnsw ((binary_quantize(embedding)::bit(1024)) bit_hamming_ops);
```

**2. Change your search query to use the same expression.** The planner only uses an expression index when the query matches it exactly. With reranking, fetch `k × rerank` candidates from the small index, then order them with the original vectors:

```sql
SET hnsw.ef_search = 200;                -- 2x the candidates: the graph misses fewer of them
SET hnsw.iterative_scan = relaxed_order; -- pgvector 0.8+: keeps 100 candidates under a WHERE filter
SELECT * FROM (
  SELECT * FROM documents                -- put any WHERE filter here, inside the subquery
  ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
  LIMIT 100
) candidates
ORDER BY embedding <=> $1::vector(1024)
LIMIT 10;
```

In Python (psycopg 3 + pgvector):

```python
from pgvector.psycopg import register_vector

SEARCH = """
SELECT id, title FROM (
  SELECT id, title, embedding FROM documents
  ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize(%(q)s::vector(1024))::bit(1024)
  LIMIT 100
) c ORDER BY embedding <=> %(q)s::vector(1024) LIMIT 10
"""

register_vector(conn)
with conn.transaction():
    conn.execute("SET LOCAL hnsw.ef_search = 200")
    conn.execute("SET LOCAL hnsw.iterative_scan = relaxed_order")  # pgvector 0.8+
    rows = conn.execute(SEARCH, {"q": query_embedding}).fetchall()
```

In Node.js (`pg` + `pgvector`):

```js
import pgvector from 'pgvector/pg';

const SEARCH = `
SELECT id, title FROM (
  SELECT id, title, embedding FROM documents
  ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
  LIMIT 100
) c ORDER BY embedding <=> $1::vector(1024) LIMIT 10`;

await client.query('BEGIN');
await client.query('SET LOCAL hnsw.ef_search = 200');
await client.query('SET LOCAL hnsw.iterative_scan = relaxed_order'); // pgvector 0.8+
const { rows } = await client.query(SEARCH, [pgvector.toSql(queryEmbedding)]);
await client.query('COMMIT');
```

**Filters.** HNSW applies a `WHERE` filter *after* searching. With a selective filter (one tenant, one category), the subquery can get far fewer than 100 candidates and fidelity drops, which pgshrink can't see because it simulates exact search. Put the filter inside the subquery and, on pgvector 0.8+, set `hnsw.iterative_scan = relaxed_order` (pgshrink prints it when your server supports it): the scan keeps going until it has enough candidates, and the outer `ORDER BY` restores the exact order. The new index keeps your current index's `m`, which the size estimate assumes.

**3. Check it on your traffic.** Run `EXPLAIN` on the new query and look for the new index. Then compare results against the old query for a sample of real searches.

**4. Drop the old index** once the new queries are live, to free its memory. To roll back, switch the query back; the old index is untouched until you drop it.

## Options

| option | default | meaning |
|---|---|---|
| `--table` | required | table name, optionally `schema.table` |
| `--column` | required | a `vector(n)` column |
| `--metric` | from the index | `cosine`, `ip` or `l2` |
| `--k` | 10 | top-k to compare |
| `--queries` | 200 | random rows used as queries |
| `--target` | 0.95 | minimum lower 95% bound of fidelity for a recommendation |
| `--max-rows` | 2,000,000 | rows scanned; above this a random subset is used (reported). Raise it for bigger tables |
| `--rerank` | 4,10 | rerank oversampling factors to try, e.g. `--rerank 10,20,40` on millions of rows |
| `--seed` | 0 | same seed, same queries and same results |
| `--json` | off | machine-readable report |

## Safety

- Every transaction is opened with `default_transaction_read_only = on`, and a test checks that writes fail.
- It reads the vector column and `ctid`, plus catalog metadata: column type, row estimate, index names, sizes and predicates. It reads no other columns, except those in a partial index's `WHERE`, which it uses as a filter.
- It writes nothing to disk and never logs the connection string.
- `statement_timeout` defaults to 5 minutes.
- On a managed database, scanning the column costs one sequential read of it. Run it against a replica if you can.

## What it does not tell you

- **Rerank gets harder as the table grows.** The same number of candidates covers a smaller share of the rows, so re-run pgshrink when the table has grown a few times.
- **Fidelity is not retrieval quality.** It measures "same results as today". If today's results are wrong, they stay wrong. That is also why it needs no labels.
- **The queries are your stored rows.** If your model embeds queries differently from documents (e5's `query:` prefix, instruction prompts), real queries may behave a little differently.
- **HNSW adds its own approximation** on top of compression, and it grows with the table: about −1 point at 171k rows and −3 to −4 at 1M rows in our validation ([details](docs/validation.md#6-one-million-rows)). The printed SQL sets `hnsw.ef_search` to 2× the candidates, which recovers about a point. On millions of rows, raise `--target` (e.g. `--target 0.99`) so pgshrink picks a bigger rerank: ×20 kept 97.5% at 1M rows.
- **Truncation (`subvector`) only makes sense for Matryoshka-trained models.** pgshrink measures it either way, and a large drop is the signal that your model isn't one.
- **The index size is an estimate** from a page-packing model fitted on real pgvector HNSW indexes: within 3% at `m = 16`, and within 2% from `m = 8` to `m = 32` ([validation](docs/validation.md#4-other-m-values-and-ivfflat)). `m` matters a lot for binary indexes (about 2× from `m = 8` to `m = 32`), and not at all for 1024-dim `halfvec` (3 rows per page either way). It counts what the index holds: rows with a vector, only those matching a partial index's `WHERE`, and identical vectors once ([validation](docs/validation.md#7-which-rows-the-index-holds)).
- **One row set per run.** If the vector indexes on the column cover different rows (say, one partial index per tenant), pgshrink stops instead of guessing.
- **It doesn't measure write cost.** In our test the binary index took about 6× more inserts and updates per second than `vector` and vacuumed 7× faster, while `halfvec` was only about 1.3× faster ([validation](docs/validation.md#5-write-cost)). `VACUUM` on HNSW stays slow with every layout, so if your table changes a lot, check it under your real write rate.
- **It sizes HNSW indexes only.** For 1024-dim `halfvec`, an IVFFlat index came out the same size as HNSW in our tests, so it doesn't save memory there.
- For now it supports `vector(n)` columns on pgvector 0.7+ (needed for `halfvec` and `binary_quantize`).

## Development

```bash
git clone https://github.com/alessandroamormino/pgshrink && cd pgshrink
uv sync
uv run pytest                                  # unit tests

docker run -d --name pgshrink-test -e POSTGRES_PASSWORD=pg -p 55432:5432 pgvector/pgvector:pg17
PGSHRINK_TEST_DSN=postgresql://postgres:pg@localhost:55432/postgres uv run pytest   # + integration tests
```

The integration tests run every printed SQL statement against a real pgvector. They check that it returns the neighbors that pgshrink's numpy model predicts, and that the connection really is read-only.

Issues and pull requests are welcome, especially reports of how the numbers compare with your production results.

## License

[Apache-2.0](LICENSE)
