Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions CONTEXT_AND_RESULTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Context and Results

## Overview

This repository ([shikhar-gangwar/pgvector-python](https://github.com/shikhar-gangwar/pgvector-python)) is an attributed MIT-licensed fork of [pgvector/pgvector-python](https://github.com/pgvector/pgvector-python) by Andrew Kane. It preserves all upstream functionality, copyright notices, and MIT license terms while adding SQLAlchemy `BIT` literal-bind compilation support, `pgvector.Bit` value normalization, documentation, and verified local Windows + Docker execution results.

## Problem Context and Implemented Fix

### Root Cause
In `pgvector/sqlalchemy/bit.py`, `VECTOR`, `HALFVEC`, and `SPARSEVEC` implemented `literal_processor` for SQLAlchemy, whereas `BIT` inherited the default from SQLAlchemy's `PGBit` (which returns `None`). Compiling queries with `compile_kwargs={'literal_binds': True}` (for example, `hamming_distance` or `jaccard_distance` expressions on a `BIT` column) failed with:

```text
sqlalchemy.exc.CompileError: No literal value renderer is available for literal value "'101'" with datatype BIT
```

Additionally, passing `pgvector.Bit`, SQLAlchemy 2.1 `postgresql.BitString` (whose `str` validation fails inside `String.literal_processor`), or `asyncpg.BitString` into SQLAlchemy `BIT` bind/literal paths required explicit normalization to plain bit-string text.

### Code Changes (`pgvector/sqlalchemy/bit.py` & `tests/test_sqlalchemy.py`)
- **`pgvector/sqlalchemy/bit.py`**:
- Added shared helper `BIT._to_text` normalizing `pgvector.Bit`, `str` subclasses (such as SQLAlchemy 2.1's `postgresql.BitString`), and `asyncpg.BitString` to plain `str` bit text.
- Added `_string = String()` and implemented `BIT.literal_processor(self, dialect: Dialect)` using `self._string._cached_literal_processor(dialect)` over `self._to_text(value)`.
- Updated `BIT.process_bind_param` to normalize inputs via `self._to_text(value)` before `asyncpg.BitString` conversion or return.
- **`tests/test_sqlalchemy.py`**:
- Added regression assertions inside `TestSqlalchemy.test_literal_binds` verifying `compile_kwargs={'literal_binds': True}` for `'101'`, `Bit('101')`, `postgresql.BitString('101')`, `asyncpg.BitString('101')`, and `jaccard_distance('101')`.
- Expanded `TestSqlalchemy.test_bit` and `TestSqlalchemyAsync.test_bit` to verify persisting and reading back `Bit` instances across sync and async engines.

## Local Environment and Step-by-Step Execution (Windows + Docker)

### Environment Verified
- **OS / Shell**: Windows (PowerShell)
- **Python**: `3.14.3` inside `pgvector-python\.venv`
- **Package / Dependencies**: Editable install of `pgvector-0.5.1` with `dev`, `numpy`, and `scipy` dependency groups from `pyproject.toml`
- **Database**: Docker container `pgvector/pgvector:pg17` exposed on `localhost:5432`

### Step-by-Step Setup & Run Commands

1. **Start PostgreSQL with `pgvector` in Docker**
```powershell
docker run -d --name pgvector-test `
-e POSTGRES_USER=bit `
-e POSTGRES_DB=pgvector_python_test `
-e POSTGRES_HOST_AUTH_METHOD=trust `
-p 5432:5432 `
pgvector/pgvector:pg17
docker exec -it pgvector-test createdb -U bit pgvector_example
```

2. **Create and populate the virtual environment (from `pgvector-python`)**
```powershell
cd "pgvector-python"
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e . --group dev --group numpy --group scipy
```

3. **Run offline unit tests (no database required)**
```powershell
.\.venv\Scripts\python.exe -m pytest tests/test_bit.py tests/test_half_vector.py tests/test_sparse_vector.py tests/test_vector.py
```

4. **Run the full 581-test suite on Windows**
On Windows, Python's default `asyncio.ProactorEventLoop` is rejected by `psycopg` async connections (`psycopg.InterfaceError`). `tests/conftest.py` registers a `pytest_asyncio_loop_factories` hook on `win32` returning `asyncio.SelectorEventLoop`, so plain `pytest` passes all sync and async tests across every driver and ORM:
```powershell
$env:PGHOST = "localhost"
$env:PGUSER = "bit"
.\.venv\Scripts\python.exe -m pytest
```

5. **Run type checks and linter (from `pgvector-python`)**
```powershell
.\.venv\Scripts\python.exe -m mypy
.\.venv\Scripts\python.exe -m pycodestyle . --ignore=E501,E704,W504 --exclude=.venv
```

6. **Run the bulk loading example (`examples/loading/example.py`)**
```powershell
$env:PGHOST = "localhost"
$env:PGUSER = "bit"
.\.venv\Scripts\python.exe examples\loading\example.py
```

## Observed Test and Run Results

| Check | Command / Mode | Result | Notes |
| --- | --- | --- | --- |
| Offline unit tests | `pytest tests/test_bit.py tests/test_half_vector.py tests/test_sparse_vector.py tests/test_vector.py` | **122 passed** (`1.25s`) | Pure Python, NumPy, and SciPy vector/bit tests |
| Offline SQLAlchemy `BIT` compilation | `Item.binary_embedding.hamming_distance('101' / Bit('101'))` & `jaccard_distance('101')` with `literal_binds=True` | **Passed** | Compiled cleanly to `<~> '101'` and `<%%> '101'` |
| Full suite (before `conftest.py` hook) | `.\.venv\Scripts\python.exe -m pytest` | **568 passed, 13 failed** (`67.54s`) | Baseline before adding `SelectorEventLoop` hook; all 13 failures were `psycopg` async under `ProactorEventLoop` |
| Full suite (with `conftest.py` `SelectorEventLoop` hook) | `.\.venv\Scripts\python.exe -m pytest` | **581 passed** | All 12 test modules passed (`asyncpg`, `bit`, `django`, `half_vector`, `peewee`, `pg8000`, `psycopg`, `psycopg2`, `sparse_vector`, `sqlalchemy`, `sqlmodel`, `vector`) |
| Type check (`mypy`) | `.\.venv\Scripts\python.exe -m mypy` | **Passed** (`0` issues) | `Success: no issues found in 54 source files` |
| Linter (`pycodestyle`) | `.\.venv\Scripts\python.exe -m pycodestyle . --ignore=E501,E704,W504 --exclude=.venv` | **Passed** (`0` issues) | Clean across codebase and tests |
| Type check (`ty`) | `.\.venv\Scripts\ty.exe check` | **21 diagnostics** | All 21 in upstream `tests/test_sqlmodel.py` (`sqlmodel 0.0.50` tuple inference); 0 in `pgvector/` or modified test files |
| Bulk loading example | `.\.venv\Scripts\python.exe examples\loading\example.py` | **Success** | Loaded `1000000` 128-dimensional vector rows via binary `COPY` into `pgvector_example` |
36 changes: 31 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -825,27 +825,37 @@ arr = vec.to_coo()

## History

View the [changelog](https://github.com/pgvector/pgvector-python/blob/master/CHANGELOG.md)
View the [changelog](CHANGELOG.md)

## Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

- [Report bugs](https://github.com/pgvector/pgvector-python/issues)
- Fix bugs and [submit pull requests](https://github.com/pgvector/pgvector-python/pulls)
- [Report bugs](https://github.com/shikhar-gangwar/pgvector-python/issues)
- Fix bugs and [submit pull requests](https://github.com/shikhar-gangwar/pgvector-python/pulls)
- Write, clarify, or fix documentation
- Suggest or add new features

To get started with development:

```sh
git clone https://github.com/pgvector/pgvector-python.git
git clone https://github.com/shikhar-gangwar/pgvector-python.git
cd pgvector-python
pip install --group dev
pip install -e . --group dev --group numpy --group scipy
createdb pgvector_python_test
pytest
```

On Windows with Docker Desktop (`pgvector/pgvector:pg17`), start PostgreSQL and run the full test suite (`tests/conftest.py` automatically configures `SelectorEventLoop` on Windows for `psycopg` async tests):

```powershell
docker run -d --name pgvector-test -e POSTGRES_USER=bit -e POSTGRES_DB=pgvector_python_test -e POSTGRES_HOST_AUTH_METHOD=trust -p 5432:5432 pgvector/pgvector:pg17
docker exec -it pgvector-test createdb -U bit pgvector_example
$env:PGHOST = "localhost"
$env:PGUSER = "bit"
.\.venv\Scripts\python.exe -m pytest
```

To run an example:

```sh
Expand All @@ -854,3 +864,19 @@ pip install --group dev
createdb pgvector_example
python3 example.py
```

## Fork Attribution, Context, and Results

This repository is an attributed fork of [pgvector/pgvector-python](https://github.com/pgvector/pgvector-python) by Andrew Kane, licensed under the MIT License ([LICENSE.txt](LICENSE.txt)). All original copyright notices, license conditions, and upstream attribution are preserved.

For full technical context, implementation notes, and verified test/example outputs, see [CONTEXT_AND_RESULTS.md](CONTEXT_AND_RESULTS.md).

### Specific Changes in this Repository
- **SQLAlchemy `BIT` literal binds and object support (`pgvector/sqlalchemy/bit.py`)**:
- Implemented `literal_processor` for `BIT` in SQLAlchemy to support compiling queries with `compile_kwargs={'literal_binds': True}`. Previously, while `VECTOR`, `HALFVEC`, and `SPARSEVEC` implemented `literal_processor`, `BIT` inherited the default from `PGBit` (which returns `None`), causing `sqlalchemy.exc.CompileError: No literal value renderer is available for literal value "'101'" with datatype BIT`.
- Added shared normalization (`BIT._to_text`) in `BIT.process_bind_param` and `BIT.literal_processor` for `pgvector.Bit`, `postgresql.BitString` (SQLAlchemy >= 2.1), and `asyncpg.BitString` instances by converting them to plain bit string text, allowing `Bit` and dialect `BitString` objects to be passed cleanly across SQLAlchemy queries and literal-bind expressions.
- Added regression test assertions to `test_literal_binds`, `TestSqlalchemy.test_bit`, and `TestSqlalchemyAsync.test_bit` in `tests/test_sqlalchemy.py`.
- **Context, Verification, and Documentation (`CONTEXT_AND_RESULTS.md`, `README.md`, `tests/conftest.py`)**:
- Added a Windows-only `pytest_asyncio_loop_factories` hook in `tests/conftest.py` so plain `pytest` uses `SelectorEventLoop` on Windows.
- Verified all **581 tests** pass against `pgvector/pgvector:pg17` (plus `mypy` and `pycodestyle` clean) and verified `examples/loading/example.py` loading 1,000,000 rows into PostgreSQL.

25 changes: 23 additions & 2 deletions pgvector/sqlalchemy/bit.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,40 @@
from sqlalchemy.dialects.postgresql.base import PGBit
from sqlalchemy.types import TypeDecorator, Float
from sqlalchemy import Operators
from sqlalchemy.types import TypeDecorator, Float, String
from sqlalchemy import Dialect, Operators
from typing import Any
from .. import Bit


class BIT(TypeDecorator[Any]):
impl = PGBit
cache_ok = True
_string = String()

@staticmethod
def _to_text(value: Any) -> Any:
if isinstance(value, Bit):
return value.to_text()
if isinstance(value, str):
# Convert str subclasses (e.g. postgresql.BitString) to plain str
return str(value)
if value is not None and value.__class__.__module__.startswith('asyncpg') and value.__class__.__name__ == 'BitString':
return value.as_string()
return value

def process_bind_param(self, value: Any, dialect: Any) -> Any:
value = self._to_text(value)
if dialect.__class__.__name__ == 'PGDialect_asyncpg' and isinstance(value, str):
import asyncpg
return asyncpg.BitString(value) # type: ignore
return value

def literal_processor(self, dialect: Dialect) -> Any:
string_literal_processor = self._string._cached_literal_processor(dialect)

def process(value: Any) -> Any:
return string_literal_processor(self._to_text(value)) # type: ignore
return process

class Comparator(TypeDecorator.Comparator[Any]): # type: ignore
def hamming_distance(self, other: object, /) -> Operators:
return self.op('<~>', return_type=Float)(other)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ dependencies = [
]

[project.urls]
Homepage = "https://github.com/pgvector/pgvector-python"
Homepage = "https://github.com/shikhar-gangwar/pgvector-python"

[dependency-groups]
dev = [
Expand Down
13 changes: 13 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
import asyncio
from collections.abc import Callable
import sys
import pytest

try:
import numpy
except ImportError:
numpy = None # type: ignore

if sys.platform == 'win32':
# psycopg async mode requires SelectorEventLoop instead of Windows ProactorEventLoop
def pytest_asyncio_loop_factories(
config: pytest.Config,
item: pytest.Item,
) -> dict[str, Callable[[], asyncio.AbstractEventLoop]]:
return {'selector': asyncio.SelectorEventLoop}

__all__ = [
'numpy'
]
27 changes: 26 additions & 1 deletion tests/test_sqlalchemy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import asyncpg
from getpass import getuser
from pgvector import SparseVector
from pgvector import Bit, SparseVector
from pgvector.sqlalchemy import VECTOR, HALFVEC, BIT, SPARSEVEC, avg, sum
import pytest
from sqlalchemy import create_engine, event, insert, inspect, literal, select, text, MetaData, Table, Column, Index, Integer, ARRAY, Engine
Expand Down Expand Up @@ -298,10 +298,14 @@ def test_halfvec_l1_distance_orm(self, engine: Engine) -> None:

def test_bit(self, engine: Engine) -> None:
with Session(engine) as session:
bit_val: Any = Bit('110')
session.add(Item(id=1, binary_embedding='101'))
session.add(Item(id=2, binary_embedding=bit_val))
session.commit()
item = session.get_one(Item, 1)
assert item.binary_embedding == '101'
item2 = session.get_one(Item, 2)
assert item2.binary_embedding == '110'

def test_bit_hamming_distance(self, engine: Engine) -> None:
create_items()
Expand Down Expand Up @@ -518,6 +522,22 @@ def test_literal_binds(self, engine: Engine) -> None:
sql = select(Item).order_by(Item.embedding.l2_distance([1, 2, 3])).compile(engine, compile_kwargs={'literal_binds': True})
assert "embedding <-> '[1.0,2.0,3.0]'" in str(sql)

sql = select(Item).order_by(Item.binary_embedding.hamming_distance('101')).compile(engine, compile_kwargs={'literal_binds': True})
assert "binary_embedding <~> '101'" in str(sql)

sql = select(Item).order_by(Item.binary_embedding.hamming_distance(Bit('101'))).compile(engine, compile_kwargs={'literal_binds': True})
assert "binary_embedding <~> '101'" in str(sql)

if sqlalchemy_version >= 2.1:
sql = select(Item).order_by(Item.binary_embedding.hamming_distance(postgresql.BitString('101'))).compile(engine, compile_kwargs={'literal_binds': True}) # type: ignore
assert "binary_embedding <~> '101'" in str(sql)

sql = select(Item).order_by(Item.binary_embedding.hamming_distance(asyncpg.BitString('101'))).compile(engine, compile_kwargs={'literal_binds': True}) # type: ignore
assert "binary_embedding <~> '101'" in str(sql)

sql = select(Item).order_by(Item.binary_embedding.jaccard_distance('101')).compile(engine, compile_kwargs={'literal_binds': True})
assert "binary_embedding <%> '101'" in str(sql) or "binary_embedding <%%> '101'" in str(sql)

def test_insert(self, engine: Engine) -> None:
with Session(engine) as session:
session.execute(insert(Item).values(embedding=[1, 2, 3]))
Expand Down Expand Up @@ -655,6 +675,11 @@ async def test_bit(self, engine: AsyncEngine) -> None:
item = await session.get_one(Item, 2)
assert item.binary_embedding == embedding

bit_val: Any = Bit('101')
session.add(Item(id=3, binary_embedding=bit_val))
item = await session.get_one(Item, 3)
assert item.binary_embedding == embedding

await engine.dispose()

@pytest.mark.asyncio
Expand Down