pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
From: leemeii (@leemeii) <noreply+leemeii@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #1048: sparsevec silently accepts duplicate coordinates when one value is explicitly zero
Date: Mon, 26 Oct 2026 12:55:07 +0000
Message-ID: <gh-pgvector-pgvector-1048@github.com> (raw)

## Summary

The `sparsevec` input parser silently accepts duplicate coordinates when one occurrence has an explicitly supplied zero value.

For example:

```sql
SELECT '{1:0,1:1}/3'::sparsevec::text;
```

returns:

```text
{1:1}/3
```

However, the parser explicitly rejects duplicate coordinates when both occurrences are non-zero.

This makes duplicate-coordinate validation dependent on the values supplied for the duplicated coordinate. Could the parser validate coordinate uniqueness before discarding zero-valued entries?

## Steps to Reproduce
```python

import math
import os

import psycopg


DSN = os.getenv(
    "PGVECTOR_DSN",
    "dbname=postgres user=postgres"
)

# Seed and mutated sparse vectors
seed = "{1:1}/3"

mutants = [
    "{1:0,1:1}/3",
    "{1:1,1:0}/3",
    "{1:1,1:1}/3",
]

# Query vector for L2 distance measurement
query = "{1:0.5,2:1}/3"


def parse_sparsevec(conn, value):
    with conn.cursor() as cur:
        cur.execute(
            "SELECT %s::sparsevec::text",
            (value,)
        )
        return cur.fetchone()[0]


def l2_distance(conn, vector, query_vector):
    with conn.cursor() as cur:
        cur.execute(
            """
            SELECT %s::sparsevec <-> %s::sparsevec
            """,
            (vector, query_vector)
        )
        return float(cur.fetchone()[0])


def reproduce():
    with psycopg.connect(DSN, autocommit=True) as conn:
        with conn.cursor() as cur:
            cur.execute(
                "CREATE EXTENSION IF NOT EXISTS vector"
            )

        # Baseline: valid sparsevec
        seed_parsed = parse_sparsevec(conn, seed)
        seed_distance = l2_distance(conn, seed, query)

        print("=== Baseline ===")
        print("Seed:", seed)
        print("Parsed:", seed_parsed)
        print("Metric: L2")
        print("L2 distance:", seed_distance)

        print("\n=== Mutated Inputs ===")

        for mutant in mutants:
            print("\nMutant:", mutant)

            try:
                parsed = parse_sparsevec(conn, mutant)
                distance = l2_distance(conn, mutant, query)

                print("Accepted: True")
                print("Parsed:", parsed)
                print("L2 distance:", distance)
                print(
                    "L2 equals baseline:",
                    math.isclose(
                        distance,
                        seed_distance,
                        rel_tol=1e-12,
                        abs_tol=1e-12
                    )
                )

                print(
                    "BUG: Duplicate coordinate "
                    "was silently accepted."
                )

            except psycopg.Error as exc:
                print("Accepted: False")
                print("Error:", exc.diag.message_primary)
                print(
                    "Expected: Duplicate coordinate rejected."
                )


if __name__ == "__main__":
    reproduce()

```

Run the following SQL with pgvector installed:

```sql
CREATE EXTENSION IF NOT EXISTS vector;

-- Case 1: Duplicate coordinate with an explicit zero.
SELECT '{1:0,1:1}/3'::sparsevec::text;

-- Case 2: The same coordinate duplicated with non-zero values.
SELECT '{1:1,1:1}/3'::sparsevec::text;

-- Case 3: A zero-valued duplicate appearing after a non-zero entry.
SELECT '{1:1,1:0}/3'::sparsevec::text;
```

## Actual Behavior

Case 1 succeeds and returns:

```text
{1:1}/3
```

Case 2 fails with:

```text
ERROR: sparsevec indices must not contain duplicates
```

Case 3 also succeeds because the zero-valued entry is discarded before duplicate validation.

## Expected Behavior

All three inputs should consistently reject duplicate coordinates, regardless of whether one occurrence has a zero value.

For example, Case 1 should raise an error indicating that the sparse vector contains duplicate indices, rather than silently normalizing the input to `{1:1}/3`.


view thread (3+ messages)  latest in thread

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