diff --git a/.github/workflows/orbit-python.yml b/.github/workflows/orbit-python.yml
new file mode 100644
index 0000000..10afc55
--- /dev/null
+++ b/.github/workflows/orbit-python.yml
@@ -0,0 +1,29 @@
+name: Orbit Python
+
+on:
+ push:
+ branches: ['**']
+ paths: ['src/**', 'libs/**', 'Makefile', 'packages/python/**', '.github/workflows/orbit-python.yml']
+ pull_request:
+ paths: ['src/**', 'libs/**', 'Makefile', 'packages/python/**', '.github/workflows/orbit-python.yml']
+ workflow_dispatch:
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ - name: Build the extension
+ run: make extension
+ - name: Test orbit.memory
+ working-directory: packages/python
+ run: |
+ pip install pytest
+ PYTHONPATH=src python -m pytest tests -q
+ - name: Build the wheel (compiles from src/)
+ run: |
+ pip install build
+ python -m build --wheel packages/python
diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml
deleted file mode 100644
index 2426a85..0000000
--- a/.github/workflows/python-package.yml
+++ /dev/null
@@ -1,104 +0,0 @@
-name: Build and Publish Python Package
-
-on:
- workflow_dispatch:
- inputs:
- version:
- description: "Version to use for the Python package (e.g. 0.9.9)"
- required: true
- type: string
- test-pypi:
- description: "Publish to Test PyPI"
- required: false
- type: boolean
- default: false
-
- push:
- tags:
- - '*.*.*'
-
-jobs:
- build-and-publish:
- runs-on: ${{ matrix.os }}
- permissions:
- id-token: write # mandatory for Pypi trusted publishing
- strategy:
- matrix:
- include:
- - os: ubuntu-latest
- platform: linux
- python-version: "3.10"
- arch: x86_64
- plat_name: manylinux2014_x86_64
- - os: ubuntu-latest
- platform: linux
- python-version: "3.10"
- arch: arm64
- plat_name: manylinux2014_aarch64
- - os: ubuntu-latest
- platform: windows
- python-version: "3.10"
- arch: x86_64
- plat_name: win_amd64
- - os: ubuntu-latest
- platform: macos
- python-version: "3.10"
- arch: x86_64
- plat_name: macosx_10_9_x86_64
- - os: ubuntu-latest
- platform: macos
- python-version: "3.10"
- arch: arm64
- plat_name: macosx_11_0_arm64
- defaults:
- run:
- shell: bash
- steps:
- - uses: actions/checkout@v4
- with:
- submodules: false
-
- - name: Set up Python
- uses: actions/setup-python@v5
- with:
- python-version: ${{ matrix.python-version }}
-
- - name: Install build dependencies
- run: |
- cd packages/python
- python3 -m pip install --upgrade pip
- python3 -m pip install -r requirements-dev.txt
-
- - name: Get version
- id: get_version
- run: |
- if [[ "${{ github.event_name }}" == "push" ]]; then
- VERSION=${GITHUB_REF#refs/tags/}
- else
- VERSION="${{ github.event.inputs.version }}"
- fi
- VERSION=${VERSION#v}
- echo "version=$VERSION" >> $GITHUB_OUTPUT
-
- - name: Download artifacts for current platform
- run: |
- cd packages/python
- python3 download_artifacts.py "${{ matrix.plat_name }}" "${{ steps.get_version.outputs.version }}"
-
- - name: Build wheel
- env:
- PACKAGE_VERSION: ${{ steps.get_version.outputs.version }}
- PLAT_NAME: ${{ matrix.plat_name }}
- run: |
- cd packages/python
- python -m build --wheel
-
- - name: Publish to PyPI
- uses: pypa/gh-action-pypi-publish@release/v1
- with:
- packages-dir: packages/python/dist
- verbose: true
- # Avoid workflow to fail if the version has already been published
- skip-existing: true
- # Upload to Test Pypi for testing
- repository-url: ${{ github.event.inputs.test-pypi == 'true' && 'https://test.pypi.org/legacy/' || '' }}
diff --git a/.gitignore b/.gitignore
index f52516e..cb5bfe3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,4 +51,8 @@ CLAUDE.md
pubspec.lock
.flutter-plugins
.flutter-plugins-dependencies
-packages/flutter/native_libraries/
\ No newline at end of file
+packages/flutter/native_libraries/
+# Python
+__pycache__/
+*.egg-info/
+.pytest_cache/
diff --git a/API.md b/API.md
index 755036f..fe52937 100644
--- a/API.md
+++ b/API.md
@@ -81,7 +81,9 @@ SELECT vector_turboquant_backend();
**Description:**
Initializes the vector extension for a given table and column. This is **mandatory** before performing any vector search or quantization.
-`vector_init` must be called in every database connection that needs to perform vector operations.
+The options are persisted in `_sqliteai_vector` (only when they change), so other connections can run
+`vector_full_scan` without calling `vector_init` again: the scan loads them. Calling it again in a
+connection where the table is already registered only checks consistency, without querying the schema.
The target table must have a **`rowid`** (an integer primary key, either explicit or implicit).
If the table was created using `WITHOUT ROWID`, it must have **exactly one primary key column of type `INTEGER`**.
@@ -118,7 +120,11 @@ This ensures that each vector can be uniquely identified and efficiently referen
inner loop; the query vector is normalized once per scan, so the reported distances are
unchanged. It is an assertion, not a request: if the stored vectors are *not* unit
length the distances will be wrong. Quantized scans ignore it, because the quantized
- index holds scaled integers whose norm is not 1. Default `0`.
+ index holds scaled integers whose norm is not 1. Works with `FLOAT32`, `FLOAT16` and
+ `FLOATB16`. Default `0`.
+* `partition`: A column of the same table (letters, digits and `_`) that a `vector_full_scan`
+ can be restricted to (see below). The scan then reads only that partition's rows, through an
+ index on the column if there is one, instead of the whole table. Not supported by quantized scans.
**Example:**
@@ -127,6 +133,9 @@ SELECT vector_init('documents', 'embedding', 'dimension=384,type=FLOAT32,distanc
-- embeddings already normalized by the model: faster cosine, same results
SELECT vector_init('documents', 'embedding', 'dimension=384,type=FLOAT32,distance=cosine,normalized=1');
+
+-- searches usually stay inside one conversation: let the scan read only its rows
+SELECT vector_init('messages', 'embedding', 'dimension=384,type=FLOAT16,distance=cosine,normalized=1,partition=conversation');
```
---
@@ -257,7 +266,7 @@ INSERT INTO compressed_vectors(embedding) VALUES(vector_as_u8(X'010203'));
---
-## π `vector_full_scan(table, column, vector [, k])`
+## π `vector_full_scan(table, column, vector [, k [, partition]])`
**Returns:** `Virtual Table (rowid, distance)`
@@ -271,6 +280,9 @@ Since this interface only returns rowid and distance, if you need to access addi
* `column` (TEXT): Column containing vectors.
* `vector` (BLOB or JSON): The query vector.
* `k` (INTEGER, optional): Number of nearest neighbors to return. When provided, the module collects the top-k results sorted by distance. When omitted, the module operates in **streaming mode** β rows are returned progressively as they are scanned, enabling standard SQL clauses such as `WHERE` and `LIMIT` to control filtering and result count.
+* `partition` (optional): Only rows whose `partition` column (declared in `vector_init`) equals this
+ value are scanned. In streaming mode, restrict with the hidden column instead: `WHERE v.part = ?`.
+ Measured with 100,000 rows in 200 partitions: one partition in 0.6β0.9 ms instead of ~45 ms.
**Examples:**
@@ -287,6 +299,19 @@ FROM vector_full_scan('documents', 'embedding', vector_as_f32('[0.1, 0.2, 0.3]')
LIMIT 5;
```
+```sql
+-- Top-k inside one partition (partition=conv in vector_init)
+SELECT rowid, distance
+FROM vector_full_scan('messages', 'embedding', vector_as_f32('[0.1, 0.2, 0.3]'), 5, 'chat-42');
+
+-- Streaming inside one partition, with more filters applied by SQL
+SELECT m.id, v.distance
+FROM vector_full_scan('messages', 'embedding', vector_as_f32('[0.1, 0.2, 0.3]')) AS v
+ JOIN messages m ON m.id = v.rowid
+WHERE v.part = 'chat-42' AND m.role = 'user'
+ORDER BY v.distance LIMIT 5;
+```
+
```sql
-- Streaming mode with JOIN and filtering
SELECT
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 360981c..6b9735f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,77 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
+## [Unreleased]
+
+### Added
+
+- **`orbit` for Python, built from this repository.** `packages/python` is now the
+ `astrolle-orbit` package: it compiles the extension from `src/` and ships it inside the
+ wheel (`orbit/lib/`), instead of downloading prebuilt binaries. `orbit.load(conn)` loads it.
+- **`orbit.memory`: conversational memory inside SQLite.** `add` chunks a message (β€ 450
+ characters, structured answers by their summary), embeds it with a function the caller
+ passes (Orbit loads no model) and stores it in `orbit_chunks` with its role, time and model.
+ `recall` finds what was said before: it strips the question's conversational wrapper, skips
+ the recent window, and only returns chunks that are very similar (β₯ 0.5) or similar and
+ sharing content words (β₯ 0.3) β cosine alone did not separate signal from noise.
+ `forget_conversation` and `missing_sources` (backfill) complete it. No runtime dependencies.
+- **`python -m orbit.eval`: a memory evaluation set** of 102 questions in Spanish, English and
+ Portuguese (same conversation, names and figures, another language, another conversation, by
+ date, changed facts, and questions that must recall nothing). Baseline with
+ paraphrase-multilingual-MiniLM-L12-v2: 57/80 positives, 21/22 negatives clean; 0/10 across
+ conversations, 1/8 by date and 3/6 changed facts are the known gaps.
+- **`packages/python/bench/bench_memory.py`**: search latency at realistic sizes. 20,000 chunks
+ in 50 conversations: ~10 ms median; 100,000 in 200: ~40 ms. Filtering by conversation does
+ not make it faster yet: the scan reads the whole table and filters afterwards.
+- **CI for the Python package** (`orbit-python.yml`): builds the extension, runs the tests and
+ builds the wheel.
+- **Hybrid recall.** An FTS5 index (`orbit_chunks_fts`, kept in sync by triggers, rebuilt for
+ chunks stored before it) is fused with the vector ranking by reciprocal rank fusion. A chunk
+ passes with similarity β₯ 0.6 on its own (was 0.5) or β₯ 0.3 with a full-text match. With 300
+ filler messages per conversation, positives go from 54/80 to 63/80 and clean negatives from
+ 18/22 to 20/22; with none, 57β64/80 and 21/22.
+- **Dates in words** (`orbit.dates`, es/en/pt): today, yesterday, last week, a weekday, "el martes
+ 25", "November 25th", "no dia 24"β¦ become a range in the caller's timezone (`recall(now=β¦)`).
+ They filter only questions about the conversation ("what did we talk aboutβ¦"); otherwise a
+ relative date leaves the topic and an absolute one stays in it. By-date recall: 1/8 β 8/8.
+- **Pairs.** Each recalled chunk carries `pair`: the answer to a question, or the question of an
+ answer.
+- **`python -m orbit.eval --noise N`** adds filler messages, like a long real conversation, and
+ `--min-score`/`--min-score-with-words` to calibrate.
+- **Partitions in `vector_full_scan`.** `vector_init(..., 'partition=')` declares a column a
+ scan can be restricted to: as a 5th argument in top-k mode, or `WHERE v.part = ?` in streaming
+ mode. The scan's own SELECT then reads only that partition (through its index). One conversation
+ of 100,000 chunks in 200: ~45 ms β 0.6β0.9 ms. Quantized scans refuse it explicitly.
+- **`vector_init` options are persisted** in `_sqliteai_vector` (only when they change) and a scan
+ in another connection loads them: `vector_init` is no longer needed per connection. Re-calling it
+ on a registered table returns before the three schema queries it used to run. Invalid persisted
+ rows are refused, not trusted.
+- **`normalized=1` works with `FLOAT16` and `FLOATB16`** (the `1 - dot` shortcut on the existing
+ DOT kernels; the query is normalized in its own format).
+- **`orbit.memory` stores FLOAT16 by default**: half the database (100,000 chunks: 210 β 108 MB),
+ identical recall in `orbit.eval`, and searches restricted to the conversation by partition.
+ Tables holding FLOAT32 vectors keep that format.
+
+- **`orbit.facts`: what Orbit knows about a person, across conversations.** `might_hold_fact` decides
+ without a model whether a message could state a fact (a statement with a personal cue, a name or a
+ figure); only then `learn` asks the caller's model (`llm(system, user) -> str`, no provider in Orbit)
+ for facts under stable keys, in the message's language. A new fact replaces an active one with its
+ key only when both are about the same thing (similarity β₯ 0.45: the model reuses keys for unrelated
+ facts, measured 0.06β0.39 for different facts and 0.50β0.73 for the same one). `recall` searches
+ every conversation; `forget` deletes the fact, its older versions and the messages (and answers) it
+ came from. `python -m orbit.eval --facts`: across conversations 0/10 β 9.3/10, changed facts 3/6 β
+ 4.7/6, positives 64/80 β 75.3/80 (3 runs), clean negatives unchanged (21/22).
+
+### Fixed
+
+- Every compiler warning (`-Wmisleading-indentation`, `-Wsign-compare`, `-Wstringop-overflow`).
+- **A recall's `pair` is dropped when the caller already has it** (it is in the window, is the
+ question, or came back as a result of its own): nothing enters the prompt twice.
+
+### Removed
+
+- The upstream `sqliteai-vector` Python package, its binary downloader and its PyPI workflow.
+
## [1.2.0] - 2026-11-01
A read-through of the sources, followed by a security review of all of `src/`, turned up
diff --git a/README.md b/README.md
index 9d6b4a8..0111365 100644
--- a/README.md
+++ b/README.md
@@ -1,74 +1,137 @@
-
-
-
-
-> **Building RAG or semantic search?** SQLite-Vector ships as an extension you can drop into any SQLite app. Need it managed with sync and auth? **[SQLite Cloud free tier](https://dashboard.sqlitecloud.io/auth/sign-in)** gives you 512 MB and 20 connections, no credit card.
+
+
+Orbit
+
+
+ Find what is related, right where your data lives.
+ Vector search inside SQLite, on the phone, in the browser, at the edge and on the server.
+
+
+
+
+
+
+
+
+
+
+
+
+ Star trails from the International Space Station, 2012. Photo: NASA/Don Pettit , public domain, via Wikimedia Commons.
+
+
+
+ How it works Β·
+ Install Β·
+ Benchmark Β·
+ API Β·
+ astrolle.com
+
---
-# SQLite Vector
-
-**SQLite Vector** is a cross-platform, ultra-efficient SQLite extension that brings vector search capabilities to your embedded database. It works seamlessly on **iOS, Android, Windows, Linux, and macOS**, using just **30MB of memory** by default. With support for **Float32, Float16, BFloat16, Int8, UInt8, 1Bit, and TurboQuant 2/3/4-bit quantization**, plus **highly optimized distance functions**, it's the ideal solution for **Edge AI** applications.
-
-SQLite-Vector includes **TurboQuant**, a compact data-oblivious vector quantizer inspired by the Google Research paper [TurboQuant: Online Vector Quantization with Near-Optimal Distortion Rate](https://arxiv.org/abs/2504.19874). It stores each vector as low-bit scalar codes plus one scale value, then scores directly from SIMD lookup-table kernels without reconstructing full vectors.
-
-## Highlights
-
-* **No virtual tables required** β store vectors directly as `BLOB`s in ordinary tables
-* **Blazing fast** β optimized C implementation with SIMD acceleration
-* **TurboQuant support** β SIMD 2-, 3-, and 4-bit quantization scans with `qtype=TURBO`
-* **Low memory footprint** β defaults to just 30MB of RAM usage
-* **Zero preindexing needed** β no long preprocessing or index-building phases
-* **Works offline** β perfect for on-device, privacy-preserving AI workloads
-* **Plug-and-play** β drop into existing SQLite workflows with minimal effort
-* **Cross-platform** β works out of the box on all major OSes
-
-
-## Why Use SQLite-Vector?
+**Orbit is [SQLite-Vector](https://github.com/sqliteai/sqlite-vector)**, the vector search extension created by [SQLite AI](https://sqlite.ai), adopted and maintained by **Astrolle**. From here on we simply call it Orbit.
+
+Orbit stores embeddings in ordinary SQLite tables and finds what is close in meaning, not just in spelling, inside the database your app already uses. No extra server, no index to rebuild, no data leaving the device.
+
+## Why Orbit
+
+
+
+
+ Everything connected
+ Vectors live as ordinary BLOB columns next to your clients, requests and tasks. One JOIN brings back the similar rows with all their context.
+
+
+ Ready the moment you are
+ No preindexing, no hours of HNSW builds. Insert a row and it can be found. Change a vector and nothing needs to be rebuilt.
+
+
+ Your data stays yours
+ Works offline, on device, in about 30 MB of memory. Privacy is the default, not a setting.
+
+
+
+
+### At a glance
+
+* **No virtual tables required**: store vectors directly as `BLOB`s in ordinary tables
+* **Fast**: optimized C with SIMD acceleration (NEON, SSE2, AVX2, AVX-512, RISC-V Vector)
+* **TurboQuant**: SIMD 2-, 3- and 4-bit quantized scans with `qtype=TURBO`
+* **Low memory footprint**: 30 MB of RAM by default, streamed or preloaded
+* **Zero preindexing**: no long preprocessing or index-building phases
+* **Works offline**: on-device, privacy-preserving AI workloads
+* **Plug and play**: drops into existing SQLite workflows
+* **Cross-platform**: iOS, Android, Windows, Linux, macOS and WASM
+
+Orbit stores **Float32, Float16, BFloat16, Int8, UInt8 and 1-bit** vectors and scans them with **L2, squared L2, L1, cosine, dot product and Hamming** distances. It includes **TurboQuant**, a compact data-oblivious quantizer inspired by the Google Research paper [TurboQuant: Online Vector Quantization with Near-Optimal Distortion Rate](https://arxiv.org/abs/2504.19874): each vector becomes low-bit codes plus one scale value, scored straight from SIMD lookup tables without rebuilding the full vector.
+
+| | Orbit | Traditional vector stores |
+| --- | :---: | --- |
+| Works with ordinary tables | β
| β usually special virtual tables |
+| No preindexing | β
| β can take hours on large datasets |
+| No external server | β
| β Redis, FAISS, Weaviateβ¦ |
+| Memory-efficient | β
| β |
+| TurboQuant low-bit scanning | β
| β |
+| Plain SQL | β
| β complex joins and subqueries |
+| Offline and edge ready | β
| β |
+| Cross-platform | β
| β |
+
+## How Orbit works
+
+Four steps, all in SQL, all inside your database:
+
+```mermaid
+%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF1EC','primaryBorderColor':'#FF6A3A','primaryTextColor':'#11151C','lineColor':'#FF6A3A','fontFamily':'Inter, Helvetica, Arial, sans-serif'}}}%%
+flowchart LR
+ A["π Your datatext, images, audio "] --> B["π§ Embedding modelany provider "]
+ B --> C["ποΈ BLOB columnordinary SQLite table "]
+ C --> D["βοΈ vector_inittype, dimension, distance "]
+ D --> E["ποΈ vector_quantizeINT8 Β· UINT8 Β· 1BIT Β· TURBO "]
+ E --> F["β‘ vector_quantize_scanSIMD, streamed or preloaded "]
+ Q["π Query vector"] --> F
+ F --> G["β
Nearest rowsJOIN with your table "]
+ classDef accent fill:#FF6A3A,stroke:#FF6A3A,color:#ffffff
+ class F,G accent
+```
-| Feature | SQLite-Vector | Traditional Solutions |
-| ---------------------------- | ------------- | ------------------------------------------ |
-| Works with ordinary tables | β
| β (usually require special virtual tables) |
-| Doesn't need preindexing | β
| β (can take hours for large datasets) |
-| Doesn't need external server | β
| β (often needs Redis/FAISS/Weaviate/etc.) |
-| Memory-efficient | β
| β |
-| TurboQuant low-bit scanning | β
| β |
-| Easy to use SQL | β
| β (often complex JOINs, subqueries) |
-| Offline/Edge ready | β
| β |
-| Cross-platform | β
| β |
+A query does not leave SQLite. Orbit reads the compact quantized index, ranks it with SIMD kernels and hands back `rowid`s you join with your own table, so the answer arrives with all its context:
+
+```mermaid
+%%{init: {'theme':'base','themeVariables':{'actorBkg':'#FFF1EC','actorBorder':'#FF6A3A','actorTextColor':'#11151C','signalColor':'#11151C','noteBkgColor':'#FFF8E1','noteBorderColor':'#ffc226','fontFamily':'Inter, Helvetica, Arial, sans-serif'}}}%%
+sequenceDiagram
+ participant App as Your app
+ participant SQL as SQLite
+ participant O as Orbit
+ App->>SQL: SELECT β¦ JOIN vector_quantize_scan(β¦, query, 20)
+ SQL->>O: scan the quantized index
+ Note over O: 30 MB buffer by default or the whole index preloaded
+ O-->>SQL: top 20 rowids + distances
+ SQL-->>App: rows with labels, owners, dates
+```
-Unlike other vector databases or extensions that require complex setup, SQLite-Vector **just works** with your existing database schema and tools.
+The same index can be deployed two ways. **Preloaded** keeps it in memory after `vector_quantize_preload()`; **streamed** walks it through a bounded buffer, which is what a device with less RAM than the index does:
+
+```mermaid
+%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF1EC','primaryBorderColor':'#FF6A3A','primaryTextColor':'#11151C','lineColor':'#11151C','fontFamily':'Inter, Helvetica, Arial, sans-serif'}}}%%
+flowchart TB
+ I[("INT8 index 740 MB for 1M Γ 768")]
+ I -->|vector_quantize_preload| P["π Preloaded 740 MB in RAM Β· 37.6 ms/query"]
+ I -->|max_memory=30MB| S["πͺΆ Streamed 30 MB in RAM Β· 114.4 ms/query"]
+ P --> R["Same results Β· recall@20 99.5%"]
+ S --> R
+ classDef accent fill:#FF6A3A,stroke:#FF6A3A,color:#ffffff
+ class R accent
+```
+**25Γ less memory for 3Γ the latency**, with the same answers. Numbers from the [benchmark](#benchmark) below.
## Installation
@@ -96,11 +159,11 @@ Or embed it directly into your application.
### WASM Version
-You can download the WebAssembly (WASM) version of SQLite with the SQLite Vector extension enabled from: https://www.npmjs.com/package/@sqliteai/sqlite-wasm
+You can download the WebAssembly (WASM) build of SQLite with Orbit enabled from: https://www.npmjs.com/package/@sqliteai/sqlite-wasm
## Example Usage
-Run this SQL after loading the SQLite Vector extension. For application code, you can also bind a Float32 BLOB instead of calling `vector_as_f32`.
+Run this SQL after loading Orbit. For application code, you can also bind a Float32 BLOB instead of calling `vector_as_f32`.
```sql
-- Create a regular SQLite table.
@@ -341,7 +404,7 @@ SQLiteDatabase db = SQLiteDatabase.openDatabase(config, null, null);
### Python Package
-Python developers can quickly get started using the ready-to-use `sqlite-vector` package available on PyPI:
+Python developers can quickly get started using the ready-to-use `sqliteai-vector` package available on PyPI:
```bash
pip install sqliteai-vector
@@ -372,15 +435,15 @@ For a complete example, see the [Flutter example](https://github.com/sqliteai/sq
## Documentation
-Extensive API documentation can be found in the [API page](https://github.com/sqliteai/sqlite-vector/blob/main/API.md).
+Extensive API documentation can be found in the [API page](./API.md).
-More information about the quantization process can be found in the [QUANTIZATION document](https://github.com/sqliteai/sqlite-vector/blob/main/QUANTIZATION.md).
+More information about the quantization process can be found in the [QUANTIZATION document](./QUANTIZATION.md).
## Features
### Instant Vector Search β No Preindexing Required
-Unlike other SQLite vector extensions that rely on complex indexing algorithms such as DiskANN, HNSW, or IVF, which often require **preprocessing steps that can take hours or even days**, `sqlite-vector` works out of the box with your existing data. Thereβs **no need to preindex your vectors**βyou can start performing fast, approximate or exact vector searches **immediately**.
+Unlike other SQLite vector extensions that rely on complex indexing algorithms such as DiskANN, HNSW, or IVF, which often require **preprocessing steps that can take hours or even days**, Orbit works out of the box with your existing data. Thereβs **no need to preindex your vectors**βyou can start performing fast, approximate or exact vector searches **immediately**.
This means:
@@ -389,7 +452,7 @@ This means:
* **Works directly with BLOB columns** in ordinary SQLite tables β no special schema or virtual table required
* **Ideal for edge and mobile use cases**, where preprocessing large datasets is not practical or possible
-By eliminating the need for heavyweight indexing, `sqlite-vector` offers a **simpler, faster, and more developer-friendly** approach to embedding vector search in your applications.
+By eliminating the need for heavyweight indexing, Orbit offers a **simpler, faster, and more developer-friendly** approach to embedding vector search in your applications.
### Supported Vector Types
@@ -455,7 +518,7 @@ In the AI era, embeddings are everywhere β from language models like GPT to vi
## Perfect for Edge AI
-SQLite-Vector is designed with the **Edge AI** use case in mind:
+Orbit is designed with the **Edge AI** use case in mind:
* Runs offline β no internet required
* Works on mobile devices β iOS/Android friendly
@@ -466,38 +529,31 @@ You can deploy powerful similarity search capabilities right inside your app or
---
-## License
-
-This project is licensed under the [Apache License 2.0](./LICENSE.md).
-
----
-
+## Relationship with Astrolle and SQLite AI
-## βοΈ Hosted version
+- **[SQLite AI](https://sqlite.ai)** created the extension Orbit is built on, [sqliteai/sqlite-vector](https://github.com/sqliteai/sqlite-vector), and keeps maintaining it alongside the rest of its SQLite stack. Release binaries and packages (`sqliteai-vector`, `ai.sqlite:vector`, `sqlite_vector`) are still theirs.
+- **Astrolle** maintains Orbit.
+- Fixes that are not specific to Astrolle go upstream first, so both projects benefit.
-Don't want to run it yourself? **[SQLite Cloud](https://sqlite.ai)** is the managed version of SQLite-Vector and the rest of the stack β with sync, backups, auth, edge functions, and multi-region support included.
+## License
-[**Start free β**](https://dashboard.sqlitecloud.io/auth/sign-in)
+Licensed under the [Apache License 2.0](./LICENSE.md). The original extension is the work of SQLite AI and its contributors.
---
-## Part of the SQLite AI stack
-
-SQLite-Vector is one piece of a larger ecosystem that turns SQLite into a runtime for intelligent, distributed data:
-
-**Data layer**
-- [**sqlite-vector**](https://github.com/sqliteai/sqlite-vector) β ANN vector search inside SQLite *(you are here)*
-- [sqlite-sync](https://github.com/sqliteai/sqlite-sync) β Offline-first CRDT sync across devices
-- [sqlite-columnar](https://github.com/sqliteai/sqlite-columnar) β Column-oriented analytics for OLAP queries
-- [sqlite-js](https://github.com/sqliteai/sqlite-js) β Custom SQLite functions written in JavaScript
-
-**AI layer**
-- [sqlite-ai](https://github.com/sqliteai/sqlite-ai) β On-device LLM inference and embeddings
-- [sqlite-agent](https://github.com/sqliteai/sqlite-agent) β Autonomous AI agents running inside SQLite
-- [sqlite-memory](https://github.com/sqliteai/sqlite-memory) β Persistent, searchable memory for agents
-- [sqlite-mcp](https://github.com/sqliteai/sqlite-mcp) β Call MCP tools directly from SQL queries
-
-**Managed platform**
-- [SQLite Cloud](https://sqlite.ai) β Hosted SQLite with sync, auth, edge functions, and analytics. [Free tier β](https://dashboard.sqlitecloud.io/auth/sign-in)
-
-Built by [SQLite AI](https://sqlite.ai). Questions? [Contact us](https://sqlite.ai/support).
+
+
+
+
+
+
+
+
+ Organize your company and automate the repetitive.
+ Less work chasing you. More room to move forward.
+
+ Let's talk β Β·
+ astrolle.com
+
+ MedellΓn, COL Β· Miami, USA
+
diff --git a/docs/assets/astrolle-logo-dark.svg b/docs/assets/astrolle-logo-dark.svg
new file mode 100644
index 0000000..27a78c8
--- /dev/null
+++ b/docs/assets/astrolle-logo-dark.svg
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/assets/astrolle-logo-light.svg b/docs/assets/astrolle-logo-light.svg
new file mode 100644
index 0000000..090ecbb
--- /dev/null
+++ b/docs/assets/astrolle-logo-light.svg
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/assets/orbit.jpg b/docs/assets/orbit.jpg
new file mode 100644
index 0000000..ede1547
Binary files /dev/null and b/docs/assets/orbit.jpg differ
diff --git a/packages/python/MANIFEST.in b/packages/python/MANIFEST.in
index eed0b21..c28ab72 100644
--- a/packages/python/MANIFEST.in
+++ b/packages/python/MANIFEST.in
@@ -1,3 +1,2 @@
include README.md
include LICENSE.md
-recursive-include src/sqlite_vector/binaries *
diff --git a/packages/python/README.md b/packages/python/README.md
index a2a76ab..41be286 100644
--- a/packages/python/README.md
+++ b/packages/python/README.md
@@ -1,46 +1,85 @@
-## SQLite Vector Python package
+## Orbit for Python
-This package provides the sqlite-vector extension prebuilt binaries for multiple platforms and architectures.
+Vector search and conversational memory inside SQLite. The package compiles the Orbit
+extension from this repository's `src/` and ships it inside the wheel: nothing is downloaded.
-### SQLite Vector
+```bash
+pip install "astrolle-orbit @ git+https://github.com/Astrolle/orbit.git@#subdirectory=packages/python"
+```
-SQLite Vector is a cross-platform, ultra-efficient SQLite extension that brings vector search capabilities to your embedded database. It works seamlessly on iOS, Android, Windows, Linux, and macOS, using just 30MB of memory by default. With support for Float32, Float16, BFloat16, Int8, and UInt8, and highly optimized distance functions, it's the ideal solution for Edge AI applications.
+Building needs a C compiler and `make`. To package an extension built elsewhere, set
+`ORBIT_EXTENSION=/path/to/vector.so`.
-More details on the official repository [sqliteai/sqlite-vector](https://github.com/sqliteai/sqlite-vector).
-
-### Documentation
-
-For detailed information on all available functions, their parameters, and examples, refer to the [comprehensive API Reference](https://github.com/sqliteai/sqlite-vector/blob/main/API.md).
-
-### Supported Platforms and Architectures
-
-| Platform | Arch | Subpackage name | Binary name |
-| ------------- | ------------ | ------------------------ | ------------ |
-| Linux (CPU) | x86_64/arm64 | sqlite_vector.binaries | vector.so |
-| Windows (CPU) | x86_64 | sqlite_vector.binaries | vector.dll |
-| macOS (CPU) | x86_64/arm64 | sqlite_vector.binaries | vector.dylib |
-
-## Usage
-
-> **Note:** Some SQLite installations on certain operating systems may have extension loading disabled by default.
-If you encounter issues loading the extension, refer to the [sqlite-extensions-guide](https://github.com/sqliteai/sqlite-extensions-guide/) for platform-specific instructions on enabling and using SQLite extensions.
+### The extension
```python
-import importlib.resources
-import sqlite3
+import sqlite3, orbit
-# Connect to your SQLite database
conn = sqlite3.connect("example.db")
+orbit.load(conn) # idempotent
+print(conn.execute("SELECT vector_version(), vector_backend()").fetchone())
+```
+
+See the [API reference](../../API.md) for the SQL functions.
-# Load the sqlite-vector extension
-# pip will install the correct binary package for your platform and architecture
-ext_path = importlib.resources.files("sqlite_vector.binaries") / "vector"
+### Memory
-conn.enable_load_extension(True)
-conn.load_extension(str(ext_path))
-conn.enable_load_extension(False)
+`orbit.memory` stores what was said in a conversation and finds it again. The caller passes
+the embedding model as a function, so Orbit loads no model:
+```python
+from orbit import memory
+
+embed = lambda texts: my_model.encode(texts) # list[str] -> list of vectors
+memory.add(conn, source_id=42, conversation="chat-1", role="user",
+ ts="2026-11-30T10:00:00Z", text="My boss is Laura MΓ©ndez", embed=embed, model="my-model")
+
+memory.recall(conn, "what is my boss's name?", embed=embed, model="my-model",
+ conversation="chat-1", window=recent_messages, now=datetime.now(ZoneInfo(tz)))
+# [{'source_id': 42, 'conversation': 'chat-1', 'role': 'user', 'ts': 'β¦', 'chunk': 'β¦',
+# 'score': 0.61, 'pair': {'role': 'assistant', 'chunk': 'β¦'}}]
+
+memory.forget_conversation(conn, "chat-1")
+```
+
+- One database per person keeps people apart: nothing crosses files.
+- `recall` is hybrid: vectors find what is said differently, full text (FTS5) finds names, codes
+ and figures a long conversation pushes out of the vector top; both are fused (reciprocal rank
+ fusion). A chunk comes back when it is very similar (β₯ 0.6), or similar (β₯ 0.3) and matched by
+ full text: cosine alone does not separate signal from noise.
+- It drops the question's wrapper ("what did I tell you aboutβ¦") and skips what is already in
+ `window`. Each result carries `pair`, the other half of its exchange.
+- With `now` (timezone-aware), dates said in words are read by code (`orbit.dates`, es/en/pt):
+ "what did we talk about yesterday?" returns that day; in "what happens on December 15th?" the
+ date is the topic, not a filter.
+- Vectors are stored with their `model`: changing models never mixes vector spaces.
+- Vectors are stored in FLOAT16 (half the size, same recall); tables already holding FLOAT32 keep it.
+ A search inside one conversation reads only that conversation's rows (a `partition` of the scan).
+
+### Facts about the person
+
+`orbit.facts` keeps what is true about the person ("their boss is Laura", "allergic to peanuts"), for
+every conversation. The caller passes its model as a function; Orbit only calls it when a message
+could state a fact:
-# Now you can use sqlite-vector features in your SQL queries
-print(conn.execute("SELECT vector_version();").fetchone())
-```
\ No newline at end of file
+```python
+from orbit import facts
+
+llm = lambda system, user: my_llm.complete(system, user) # returns the JSON text
+facts.learn(conn, "My boss is Laura MΓ©ndez", llm=llm, embed=embed, model="my-model",
+ source_id=42, conversation="chat-1", ts="2026-11-30T10:00:00Z")
+facts.recall(conn, "what's my boss's name?", embed=embed, model="my-model") # any conversation
+facts.forget(conn, "my boss", embed=embed, model="my-model") # and where it came from
+```
+
+A newer value replaces an older one when both are about the same thing ("al final, La Terraza").
+
+### Measuring
+
+```bash
+pip install sentence-transformers
+python -m orbit.eval --show # memory evaluation set (es/en/pt)
+python -m orbit.eval --facts # β¦learning facts with a real model (OPENAI_API_KEY)
+python bench/bench_memory.py # search latency at realistic sizes
+PYTHONPATH=src python -m pytest tests # after `make extension`
+```
diff --git a/packages/python/bench/bench_memory.py b/packages/python/bench/bench_memory.py
new file mode 100644
index 0000000..e41ffb4
--- /dev/null
+++ b/packages/python/bench/bench_memory.py
@@ -0,0 +1,75 @@
+"""
+Latency of orbit.memory search at realistic sizes, with random unit vectors (no model).
+
+ python bench/bench_memory.py [--chunks 20000] [--conversations 50] [--dim 384] [--runs 50]
+
+Reports median and p95 for a search inside one conversation and across all of them. The
+embedding time is not included: it is the caller's model, not Orbit.
+"""
+import argparse
+import math
+import random
+import sqlite3
+import statistics
+import tempfile
+import time
+from pathlib import Path
+
+from orbit import memory
+
+
+def unit(dim):
+ v = [random.gauss(0, 1) for _ in range(dim)]
+ n = math.sqrt(sum(x * x for x in v))
+ return [x / n for x in v]
+
+
+def main():
+ p = argparse.ArgumentParser()
+ p.add_argument("--chunks", type=int, default=20000)
+ p.add_argument("--conversations", type=int, default=50)
+ p.add_argument("--dim", type=int, default=384)
+ p.add_argument("--runs", type=int, default=50)
+ a = p.parse_args()
+ random.seed(7)
+
+ with tempfile.TemporaryDirectory() as d:
+ conn = sqlite3.connect(Path(d) / "bench.db")
+ memory.ensure_schema(conn)
+ rows = [(i, f"c{i % a.conversations}", "user", "2026-11-30T10:00:00Z", f"chunk {i}",
+ "bench", memory._pack(unit(a.dim), memory.DEFAULT_TYPE)) for i in range(a.chunks)]
+ conn.executemany(f"INSERT INTO {memory.TABLE} (source_id, conversation, role, ts, chunk, model, "
+ "embedding) VALUES (?, ?, ?, ?, ?, ?, ?)", rows)
+ conn.commit()
+ size_mb = (Path(d) / "bench.db").stat().st_size / 1e6
+
+ queries = [unit(a.dim) for _ in range(a.runs)]
+ embed = lambda texts: [queries[embed.i % len(queries)]] # noqa: E731
+ embed.i = 0
+
+ def timed(conversation, hybrid=False):
+ times = []
+ for i in range(a.runs):
+ embed.i = i
+ t = time.perf_counter()
+ if hybrid: # vectors + full text + pairs; "chunk" matches every row (worst case)
+ memory.recall(conn, f"chunk {i}", embed=embed, model="bench", conversation=conversation,
+ min_score_with_words=-1)
+ else:
+ memory.search(conn, "q", embed=embed, model="bench", conversation=conversation, k=4)
+ times.append((time.perf_counter() - t) * 1000)
+ times.sort()
+ return statistics.median(times), times[int(len(times) * 0.95) - 1]
+
+ one = timed("c1")
+ every = timed(None)
+ hybrid = timed("c1", hybrid=True)
+ print(f"{a.chunks} chunks Β· {a.conversations} conversations Β· dim {a.dim} Β· "
+ f"{memory.DEFAULT_TYPE} Β· db {size_mb:.1f} MB")
+ print(f" one conversation median {one[0]:6.2f} ms p95 {one[1]:6.2f} ms")
+ print(f" all conversations median {every[0]:6.2f} ms p95 {every[1]:6.2f} ms")
+ print(f" recall (hybrid) median {hybrid[0]:6.2f} ms p95 {hybrid[1]:6.2f} ms")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/python/download_artifacts.py b/packages/python/download_artifacts.py
deleted file mode 100644
index 1474ab2..0000000
--- a/packages/python/download_artifacts.py
+++ /dev/null
@@ -1,97 +0,0 @@
-import sys
-import zipfile
-import requests
-from pathlib import Path
-import shutil
-
-
-# == USAGE ==
-# python3 download_artifacts.py PLATFORM VERSION
-# eg: python3 download_artifacts.py linux_x86_64 "0.5.9"
-
-REPO = "sqliteai/sqlite-vector"
-RELEASE_URL = f"https://github.com/{REPO}/releases/download"
-
-# Map Python plat_name to artifact names
-ARTIFACTS = {
- "manylinux2014_x86_64": ["vector-linux-x86_64"],
- "manylinux2014_aarch64": [
- "vector-linux-arm64",
- ],
- "win_amd64": ["vector-windows-x86_64"],
- "macosx_10_9_x86_64": ["vector-macos"],
- "macosx_11_0_arm64": ["vector-macos"],
-}
-
-BINARY_NAME = {
- "manylinux2014_x86_64": "vector.so",
- "manylinux2014_aarch64": "vector.so",
- "win_amd64": "vector.dll",
- "macosx_10_9_x86_64": "vector.dylib",
- "macosx_11_0_arm64": "vector.dylib",
-}
-
-BINARIES_DIR = Path(__file__).parent / "src/sqlite_vector/binaries"
-
-
-def download_and_extract(artifact_name, bin_name, version):
- artifact = f"{artifact_name}-{version}.zip"
- url = f"{RELEASE_URL}/{version}/{artifact}"
- print(f"Downloading {url}")
-
- r = requests.get(url)
- if r.status_code != 200:
- print(f"Failed to download {artifact}: {r.status_code}")
- sys.exit(1)
-
- zip_path = BINARIES_DIR / artifact
- with open(zip_path, "wb") as f:
- f.write(r.content)
-
- out_dir = BINARIES_DIR
- out_dir.mkdir(parents=True, exist_ok=True)
-
- with zipfile.ZipFile(zip_path, "r") as zip_ref:
- for member in zip_ref.namelist():
- if member.endswith(bin_name):
- zip_ref.extract(member, out_dir)
-
- # Move to expected name/location
- src = out_dir / member
- dst = out_dir / bin_name
- src.rename(dst)
-
- print(f"Extracted {dst}")
-
- zip_path.unlink()
-
-
-def main():
- version = None
- platform = None
- if len(sys.argv) == 3:
- platform = sys.argv[1].lower()
- version = sys.argv[2]
-
- if not version or not platform:
- print(
- 'Error: Version is not specified.\nUsage: \n python3 download_artifacts.py linux_x86_64 "0.5.9"'
- )
- sys.exit(1)
-
- print(BINARIES_DIR)
- if BINARIES_DIR.exists():
- shutil.rmtree(BINARIES_DIR)
- BINARIES_DIR.mkdir(parents=True, exist_ok=True)
-
- platform_artifacts = ARTIFACTS.get(platform, [])
- if not platform_artifacts:
- print(f"Error: Unknown platform '{platform}'")
- sys.exit(1)
-
- for artifact_name in platform_artifacts:
- download_and_extract(artifact_name, BINARY_NAME[platform], version)
-
-
-if __name__ == "__main__":
- main()
diff --git a/packages/python/pyproject.toml b/packages/python/pyproject.toml
index 23a2fc1..934a71f 100644
--- a/packages/python/pyproject.toml
+++ b/packages/python/pyproject.toml
@@ -1,32 +1,29 @@
[build-system]
-requires = ["setuptools>=77.0.3", "build", "wheel"]
+requires = ["setuptools>=77.0.3", "wheel"]
build-backend = "setuptools.build_meta"
[project]
-name = "sqliteai-vector"
-dynamic = ["version", "classifiers"]
-description = "Python prebuilt binaries for SQLite Vector extension for all supported platforms and architectures."
-authors = [
- { name = "SQLite AI Team" }
-]
+name = "astrolle-orbit"
+version = "0.1.0"
+description = "Orbit: vector search and conversational memory inside SQLite."
+authors = [{ name = "Astrolle" }]
readme = "README.md"
license = "Apache-2.0"
license-files = ["LICENSE.md"]
-requires-python = ">=3"
+requires-python = ">=3.9"
+# No runtime dependencies on purpose: the embedding model is passed in by the caller.
+dependencies = []
+
+[project.optional-dependencies]
+test = ["pytest"]
+eval = ["sentence-transformers"]
[project.urls]
-Homepage = "https://sqlite.ai"
-Documentation = "https://github.com/sqliteai/sqlite-vector/blob/main/API.md"
-Repository = "https://github.com/sqliteai/sqlite-vector"
-Issues = "https://github.com/sqliteai/sqlite-vector/issues"
+Repository = "https://github.com/Astrolle/orbit"
[tool.setuptools]
-packages = {find = {where = ["src"]}}
+packages = { find = { where = ["src"] } }
include-package-data = true
-[tool.setuptools.dynamic]
-version = {attr = "sqlite_vector._version.__version__"}
-
-[tool.bdist_wheel]
-# Force platform-specific wheels
-universal = false
+[tool.setuptools.package-data]
+orbit = ["lib/*"]
diff --git a/packages/python/requirements-dev.txt b/packages/python/requirements-dev.txt
deleted file mode 100644
index 055c918..0000000
--- a/packages/python/requirements-dev.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-requests
-wheel
-build
diff --git a/packages/python/setup.py b/packages/python/setup.py
index 1759174..702d724 100644
--- a/packages/python/setup.py
+++ b/packages/python/setup.py
@@ -1,56 +1,54 @@
+"""
+Builds the Orbit SQLite extension from this repository's C sources and ships it inside the
+wheel (`orbit/lib/`). No prebuilt binaries are downloaded: what you install is what is in `src/`.
+
+Set ORBIT_EXTENSION=/path/to/vector.so to package an already built extension instead of
+running `make` (useful when the C toolchain lives in another build stage).
+"""
import os
+import shutil
+import subprocess
+from pathlib import Path
+
from setuptools import setup
from setuptools.command.bdist_wheel import bdist_wheel
+from setuptools.command.build_py import build_py
+ROOT = Path(__file__).resolve().parents[2]
+NAMES = ("vector.so", "vector.dylib", "vector.dll")
-class PlatformSpecificWheel(bdist_wheel):
- """Custom bdist_wheel to force platform-specific wheel."""
-
- def finalize_options(self):
- bdist_wheel.finalize_options(self)
- # Force platform-specific wheel
- self.root_is_pure = False
- # Set platform name from environment if provided
- plat_name = os.environ.get("PLAT_NAME")
- if plat_name:
- self.plat_name = plat_name
+def _extension() -> Path:
+ prebuilt = os.environ.get("ORBIT_EXTENSION")
+ if prebuilt:
+ return Path(prebuilt)
+ subprocess.run(["make", "-C", str(ROOT), "extension"], check=True)
+ for name in NAMES:
+ built = ROOT / "dist" / name
+ if built.exists():
+ return built
+ raise RuntimeError(f"make extension did not produce any of {NAMES} in {ROOT / 'dist'}")
- def get_tag(self):
- # Force platform-specific tags with broader compatibility
- python_tag, abi_tag, platform_tag = bdist_wheel.get_tag(self)
- # Override platform tag if specified
- plat_name = os.environ.get("PLAT_NAME")
- if plat_name:
- platform_tag = plat_name
+class BuildWithExtension(build_py):
+ def run(self):
+ super().run()
+ built = _extension()
+ target = Path(self.build_lib) / "orbit" / "lib"
+ target.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(built, target / built.name)
- # Use py3 for broader Python compatibility since we have pre-built binaries
- python_tag = "py3"
- abi_tag = "none"
- return python_tag, abi_tag, platform_tag
+class PlatformWheel(bdist_wheel):
+ """The wheel carries a native library: tag it for this platform, any Python 3."""
+ def finalize_options(self):
+ super().finalize_options()
+ self.root_is_pure = False
-def get_platform_classifiers():
- """Get platform-specific classifiers based on PLAT_NAME environment variable."""
- classifier_map = {
- "manylinux2014_x86_64": ["Operating System :: POSIX :: Linux"],
- "manylinux2014_aarch64": ["Operating System :: POSIX :: Linux"],
- "win_amd64": ["Operating System :: Microsoft :: Windows"],
- "macosx_10_9_x86_64": ["Operating System :: MacOS"],
- "macosx_11_0_arm64": ["Operating System :: MacOS"],
- }
-
- plat_name = os.environ.get("PLAT_NAME")
- if plat_name and plat_name in classifier_map:
- return ["Programming Language :: Python :: 3", classifier_map[plat_name][0]]
-
- raise ValueError(f"Unsupported or missing PLAT_NAME: {plat_name}")
+ def get_tag(self):
+ _python, _abi, platform = super().get_tag()
+ return "py3", "none", platform
-if __name__ == "__main__":
- setup(
- cmdclass={"bdist_wheel": PlatformSpecificWheel},
- classifiers=get_platform_classifiers(),
- )
+setup(cmdclass={"build_py": BuildWithExtension, "bdist_wheel": PlatformWheel})
diff --git a/packages/python/src/orbit/__init__.py b/packages/python/src/orbit/__init__.py
new file mode 100644
index 0000000..1b93ae3
--- /dev/null
+++ b/packages/python/src/orbit/__init__.py
@@ -0,0 +1,55 @@
+"""
+Orbit: vector search and conversational memory inside SQLite.
+
+ import sqlite3, orbit
+ conn = sqlite3.connect("person.db")
+ orbit.load(conn) # the C extension (vector_init, vector_full_scanβ¦)
+
+ from orbit import memory
+ memory.add(conn, source_id=1, conversation="c1", role="user", ts="2026-11-30T10:00:00Z",
+ text="My boss is Laura", embed=embed, model="my-model")
+ memory.recall(conn, "what is my boss's name?", embed=embed, model="my-model", conversation="c1")
+
+`embed(texts) -> list of vectors` is passed in by the caller: Orbit does not load models.
+"""
+import os
+import sqlite3
+from pathlib import Path
+
+__version__ = "0.1.0"
+
+_NAMES = ("vector.so", "vector.dylib", "vector.dll")
+
+
+def extension_path() -> str:
+ """
+ Where the compiled extension is, without its file suffix (as `load_extension` wants it).
+
+ Looked up in this order: ORBIT_EXTENSION, the copy shipped in the wheel (`orbit/lib`),
+ and `dist/` of the source tree (development, after `make extension`).
+ """
+ candidates = []
+ if os.environ.get("ORBIT_EXTENSION"):
+ candidates.append(Path(os.environ["ORBIT_EXTENSION"]))
+ here = Path(__file__).resolve().parent
+ candidates += [here / "lib" / n for n in _NAMES]
+ candidates += [p / "dist" / n for p in here.parents for n in _NAMES]
+ for path in candidates:
+ if path.is_file():
+ return str(path.with_suffix(""))
+ raise FileNotFoundError("Orbit extension not found: build it with `make extension` "
+ "or set ORBIT_EXTENSION")
+
+
+def load(conn: sqlite3.Connection) -> None:
+ """Loads the extension into `conn` once. Idempotent."""
+ try:
+ conn.execute("SELECT vector_version()")
+ return
+ except sqlite3.OperationalError:
+ pass
+ conn.enable_load_extension(True)
+ try:
+ conn.load_extension(extension_path())
+ finally:
+ conn.enable_load_extension(False)
diff --git a/packages/python/src/orbit/dates.py b/packages/python/src/orbit/dates.py
new file mode 100644
index 0000000..69cf1d5
--- /dev/null
+++ b/packages/python/src/orbit/dates.py
@@ -0,0 +1,133 @@
+"""
+Dates said in words ("yesterday", "el martes 25", "na semana passada") turned into a time range.
+
+Computed by code, never by a model: models get weekdays and relative dates wrong. Spanish,
+English and Portuguese. The range is half-open, [start, end), in the timezone of `now`.
+"""
+import re
+from datetime import date, datetime, time, timedelta
+from typing import Optional, Tuple
+
+from orbit.text import without_accents
+
+_MONTHS = {
+ **{m: i for i, m in enumerate(["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto",
+ "septiembre", "octubre", "noviembre", "diciembre"], 1)},
+ "setiembre": 9,
+ **{m: i for i, m in enumerate(["january", "february", "march", "april", "may", "june", "july", "august",
+ "september", "october", "november", "december"], 1)},
+ **{m: i for i, m in enumerate(["janeiro", "fevereiro", "marco", "abril", "maio", "junho", "julho", "agosto",
+ "setembro", "outubro", "novembro", "dezembro"], 1)},
+}
+_WEEKDAYS = {
+ **{d: i for i, d in enumerate(["lunes", "martes", "miercoles", "jueves", "viernes", "sabado", "domingo"])},
+ **{d: i for i, d in enumerate(["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"])},
+ # Portuguese weekdays only with "-feira" or after na/no: "segunda" is also "second" in Spanish.
+ **{d: i for i, d in enumerate(["segunda-feira", "terca-feira", "quarta-feira", "quinta-feira", "sexta-feira"])},
+}
+_PT_SHORT = {"segunda": 0, "terca": 1, "quarta": 2, "quinta": 3, "sexta": 4, "sabado": 5, "domingo": 6}
+
+_MONTH = "|".join(sorted(_MONTHS, key=len, reverse=True))
+_WEEKDAY = "|".join(sorted(_WEEKDAYS, key=len, reverse=True))
+_ORD = r"(?:st|nd|rd|th)?"
+
+_RULES = [
+ # relative days (longest first: "esta maΓ±ana" is today, "maΓ±ana" alone is tomorrow)
+ (r"\b(?:esta manana|this morning|hoje de manha|hoje cedo|esta tarde|this afternoon|tonight|esta noche)\b", "today"),
+ (r"\b(?:anteayer|antier|antes de ayer|the day before yesterday|anteontem)\b", "-2"),
+ (r"\b(?:pasado manana|the day after tomorrow|depois de amanha)\b", "+2"),
+ (r"\b(?:hoy|today|hoje)\b", "today"),
+ (r"\b(?:ayer|yesterday|ontem)\b", "-1"),
+ (r"\b(?:manana|tomorrow|amanha)\b", "+1"),
+ (r"\b(?:la )?(?:semana pasada|last week|semana passada)\b", "last-week"),
+ (r"\b(?:esta semana|this week)\b", "this-week"),
+ (r"\b(?:el )?(?:mes pasado|last month|mes passado)\b", "last-month"),
+ # a day of a month
+ (rf"\b(\d{{1,2}}){_ORD}\s+(?:de|of)\s+({_MONTH})\b", "day-month"),
+ (rf"\b({_MONTH})\s+(\d{{1,2}}){_ORD}\b", "month-day"),
+ # a weekday with its day number: "el martes 25"
+ (rf"\b(?:{_WEEKDAY})\s+(\d{{1,2}})\b(?!\s*%)", "day"),
+ (rf"\b(?:na|no)\s+(?:segunda|terca|quarta|quinta|sexta|sabado|domingo)\s+(\d{{1,2}})\b", "day"),
+ # a bare day number: "el dΓa 25", "the 26th", "no dia 24"
+ (r"\b(?:el dia|el|no dia|dia|on the|the)\s+(\d{1,2})(?:st|nd|rd|th)\b", "day"),
+ (r"\b(?:el dia|no dia|dia)\s+(\d{1,2})\b(?!\s*%)", "day"),
+ (r"\bel\s+(\d{1,2})\b(?!\s*(?:%|de\b|\d))", "day"),
+ # a weekday alone: its last occurrence before today
+ (rf"\b(?:el |on |last )?({_WEEKDAY})\b", "weekday"),
+ (r"\b(?:na|no)\s+(segunda|terca|quarta|quinta|sexta|sabado|domingo)\b", "weekday-pt"),
+]
+_COMPILED = [(re.compile(p), kind) for p, kind in _RULES]
+
+
+def _midnight(day: date, tz) -> datetime:
+ return datetime.combine(day, time(0), tzinfo=tz)
+
+
+def _past_date(day: int, today: date, month: Optional[int] = None) -> Optional[date]:
+ """The most recent date with that day (and month) that is not in the future."""
+ if month:
+ for year in (today.year, today.year - 1):
+ try:
+ d = date(year, month, day)
+ except ValueError:
+ return None
+ if d <= today:
+ return d
+ return None
+ year, month = today.year, today.month
+ for _ in range(12):
+ try:
+ d = date(year, month, day)
+ if d <= today:
+ return d
+ except ValueError:
+ pass
+ year, month = (year, month - 1) if month > 1 else (year - 1, 12)
+ return None
+
+
+_RELATIVE = {"today", "-1", "-2", "+1", "+2", "last-week", "this-week", "last-month", "weekday", "weekday-pt"}
+
+
+def find_range(text: str, now: datetime) -> Optional[Tuple[datetime, datetime, str, bool]]:
+ """
+ The first date expression in `text`: (start, end, text without it, relative), or None.
+ `relative` is True for "yesterday", "last week", "on Monday"β¦: words that are never a topic,
+ unlike "December 15th". `now` must be timezone-aware: "yesterday" depends on where one is.
+ """
+ normal = without_accents(text or "")
+ same_length = len(normal) == len(text or "")
+ tz, today = now.tzinfo, now.date()
+ for regex, kind in _COMPILED:
+ m = regex.search(normal)
+ if not m:
+ continue
+ start = end = None
+ if kind == "today":
+ start = today
+ elif kind in ("-1", "-2", "+1", "+2"):
+ start = today + timedelta(days=int(kind))
+ elif kind == "last-week":
+ start = today - timedelta(days=today.weekday() + 7)
+ end = start + timedelta(days=7)
+ elif kind == "this-week":
+ start, end = today - timedelta(days=today.weekday()), today + timedelta(days=1)
+ elif kind == "last-month":
+ first = today.replace(day=1)
+ start, end = (first - timedelta(days=1)).replace(day=1), first
+ elif kind in ("day-month", "month-day"):
+ day_s, month_s = m.groups() if kind == "day-month" else reversed(m.groups())
+ start = _past_date(int(day_s), today, _MONTHS[month_s])
+ elif kind == "day":
+ start = _past_date(int(m.group(1)), today)
+ elif kind in ("weekday", "weekday-pt"):
+ target = _PT_SHORT[m.group(1)] if kind == "weekday-pt" else _WEEKDAYS[m.group(1)]
+ back = (today.weekday() - target) % 7 or 7
+ start = today - timedelta(days=back)
+ if start is None:
+ continue
+ end = end or start + timedelta(days=1)
+ source = text if same_length else normal
+ rest = " ".join((source[:m.start()] + " " + source[m.end():]).split())
+ return _midnight(start, tz), _midnight(end, tz), rest, kind in _RELATIVE
+ return None
diff --git a/packages/python/src/sqlite_vector/__init__.py b/packages/python/src/orbit/eval/__init__.py
similarity index 100%
rename from packages/python/src/sqlite_vector/__init__.py
rename to packages/python/src/orbit/eval/__init__.py
diff --git a/packages/python/src/orbit/eval/__main__.py b/packages/python/src/orbit/eval/__main__.py
new file mode 100644
index 0000000..b9b7af0
--- /dev/null
+++ b/packages/python/src/orbit/eval/__main__.py
@@ -0,0 +1,131 @@
+"""
+Runs the memory evaluation with a real embedding model.
+
+ python -m orbit.eval [--model paraphrase-multilingual-MiniLM-L12-v2] [--noise 300] [--json out.json] [--show]
+
+`--noise N` adds N filler messages to every conversation, like a long real chat: it is where
+search quality shows (with ~20 messages per conversation almost anything ranks first).
+
+`--facts` also learns the person's facts (`orbit.facts`) from their messages with a real model
+and answers with facts first, then chunks. It needs OPENAI_API_KEY and spends a few cents: the
+OpenAI adapter lives only in this evaluation tool, never in the library.
+
+Needs `sentence-transformers` (extra `eval`). No network besides downloading the model once,
+no LLM. Prints hits per category; `--show` prints every miss.
+"""
+import argparse
+import json
+import sqlite3
+import tempfile
+from collections import defaultdict
+from pathlib import Path
+
+import os
+
+from orbit import facts as facts_module
+from orbit import memory
+from orbit.eval.dataset import CONVERSATIONS, NOW, QUESTIONS, noise
+
+
+def _embedder(name):
+ from sentence_transformers import SentenceTransformer
+
+ model = SentenceTransformer(name)
+ return lambda texts: model.encode(list(texts), normalize_embeddings=True, show_progress_bar=False).tolist()
+
+
+def _openai_llm():
+ """Evaluation only: Orbit itself receives the caller's model as a function (no provider)."""
+ from openai import OpenAI
+
+ client = OpenAI()
+ model = os.getenv("ORBIT_EVAL_LLM", "gpt-4o-mini")
+
+ def llm(system, user):
+ r = client.chat.completions.create(model=model, temperature=0, response_format={"type": "json_object"},
+ messages=[{"role": "system", "content": system},
+ {"role": "user", "content": user}])
+ llm.calls += 1
+ return r.choices[0].message.content or ""
+ llm.calls = 0
+ return llm
+
+
+def judge(item, found):
+ """True when the recall is correct for this item."""
+ if item.get("none"):
+ return not found
+ if "date" in item:
+ return any((f["ts"] or "").startswith(item["date"]) for f in found)
+ expect = item["expect"] if isinstance(item["expect"], list) else [item["expect"]]
+ has = lambda text: any(e.lower() in text.lower() for e in expect) # noqa: E731
+ ranks = [i for i, f in enumerate(found) if has(f["chunk"])]
+ if not ranks:
+ return False
+ stale = [i for i, f in enumerate(found) if item.get("stale") and item["stale"] in f["chunk"]
+ and not has(f["chunk"])]
+ return not stale or ranks[0] < stale[0]
+
+
+def run(embed, model, noise_per_conversation=0, llm=None, **thresholds):
+ results = []
+ with tempfile.TemporaryDirectory() as d:
+ conn = sqlite3.connect(Path(d) / "eval.db")
+ source = 0
+ for conversation, messages in CONVERSATIONS.items():
+ for role, text, ts in noise(conversation, noise_per_conversation) + messages:
+ source += 1
+ memory.add(conn, source_id=source, conversation=conversation, role=role, ts=ts,
+ text=text, embed=embed, model=model)
+ if llm and role == "user":
+ facts_module.learn(conn, text, llm=llm, embed=embed, model=model,
+ source_id=source, conversation=conversation, ts=ts)
+ for item in QUESTIONS:
+ found = memory.recall(conn, item["q"], embed=embed, model=model, conversation=item["scope"],
+ now=NOW, **thresholds)
+ if llm: # what is known about the person first, then what was said
+ known = facts_module.recall(conn, item["q"], embed=embed, model=model)
+ found = [{"chunk": f["statement"], "ts": f["ts"], "score": f["score"]} for f in known] + found
+ results.append({**item, "ok": judge(item, found),
+ "found": [(round(f["score"], 3), f["chunk"][:60]) for f in found]})
+ conn.close()
+ return results
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--model", default="paraphrase-multilingual-MiniLM-L12-v2")
+ parser.add_argument("--noise", type=int, default=0)
+ parser.add_argument("--min-score", type=float, default=memory.MIN_SCORE)
+ parser.add_argument("--min-score-with-words", type=float, default=memory.MIN_SCORE_WITH_WORDS)
+ parser.add_argument("--facts", action="store_true")
+ parser.add_argument("--json")
+ parser.add_argument("--show", action="store_true")
+ args = parser.parse_args()
+
+ llm = _openai_llm() if args.facts else None
+ results = run(_embedder(args.model), args.model, args.noise, llm=llm, min_score=args.min_score,
+ min_score_with_words=args.min_score_with_words)
+ by = defaultdict(lambda: [0, 0])
+ for r in results:
+ by[r["category"]][0] += r["ok"]
+ by[r["category"]][1] += 1
+ print(f"model: {args.model} Β· noise: {args.noise} per conversation Β· "
+ f"min_score {args.min_score} Β· with words {args.min_score_with_words}"
+ + (f" Β· facts ({llm.calls} model calls)" if llm else ""))
+ for category, (ok, total) in by.items():
+ print(f" {category:18} {ok:3}/{total}")
+ positives = [r for r in results if not r.get("none")]
+ negatives = [r for r in results if r.get("none")]
+ print(f" {'positives':18} {sum(r['ok'] for r in positives):3}/{len(positives)}")
+ print(f" {'negatives clean':18} {sum(r['ok'] for r in negatives):3}/{len(negatives)}")
+ if args.show:
+ for r in results:
+ if not r["ok"]:
+ print(f"\nMISS [{r['category']}] {r['q']}\n β {r['found']}")
+ if args.json:
+ Path(args.json).write_text(json.dumps(results, ensure_ascii=False, indent=1))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/python/src/orbit/eval/dataset.py b/packages/python/src/orbit/eval/dataset.py
new file mode 100644
index 0000000..9499654
--- /dev/null
+++ b/packages/python/src/orbit/eval/dataset.py
@@ -0,0 +1,310 @@
+"""
+The memory evaluation set: conversations, and questions about them.
+
+Neutral vocabulary, in Spanish, English and Portuguese. Each question says in which
+conversation it is asked (`scope`; None = every conversation, as when someone asks "in another
+chatβ¦") and what a correct recall must contain:
+
+ expect a substring of a recalled chunk (or a list of them: any counts, e.g. a translation)
+ date or: a recalled chunk said on that day (YYYY-MM-DD)
+ stale for changed facts: an outdated value that must not rank above `expect`
+ none for negatives: nothing should be recalled at all
+
+`baseline` is the set measured in Aimee before Orbit had a memory module (12/13 and 1/10):
+it must keep those numbers until something deliberately improves them.
+"""
+
+from datetime import datetime, timezone
+
+#: "Now" for every question: relative dates ("el martes 25", "the 26th") are read from here.
+NOW = datetime(2026, 11, 30, 12, 0, tzinfo=timezone.utc)
+
+# ββ Conversations: id β [(role, text, timestamp)] βββββββββββββββββββββββββββββ
+
+BASELINE_CONVERSATION = [
+ ("user", "El presupuesto para la remodelaciΓ³n de la bodega es de 12.000 dΓ³lares."),
+ ("assistant", "Anotado: 12.000 dΓ³lares para la remodelaciΓ³n de la bodega."),
+ ("user", "El proveedor de empaques se llama Distribuidora Andina y entrega los martes."),
+ ("assistant", "Perfecto, Distribuidora Andina entrega los martes."),
+ ("user", "La reuniΓ³n con el equipo de calidad quedΓ³ para el jueves a las 3 de la tarde."),
+ ("assistant", "Te recuerdo: reuniΓ³n con calidad el jueves a las 15:00."),
+ ("user", "Mi jefa se llama Laura MΓ©ndez y prefiere los informes en PDF."),
+ ("assistant", "Entendido, informes en PDF para Laura MΓ©ndez."),
+ ("user", "Estoy pensando en contratar dos personas mΓ‘s para el turno de noche."),
+ ("assistant", "Contratar dos personas para el turno nocturno ayudarΓa con la carga."),
+ ("user", "La meta de ventas de este trimestre es llegar a 500 unidades."),
+ ("assistant", "Meta del trimestre: 500 unidades vendidas."),
+ ("user", "My password manager is not the issue, the VPN keeps disconnecting every hour."),
+ ("assistant", "So the VPN drops hourly; that points to a session timeout on the server."),
+ ("user", "O contrato com o cliente Horizonte vence em marΓ§o do ano que vem."),
+ ("assistant", "Certo, o contrato do Horizonte vence em marΓ§o."),
+ ("user", "CambiΓ© de opiniΓ³n: el color de la nueva marca serΓ‘ verde oliva, no azul."),
+ ("assistant", "Listo, la marca nueva va en verde oliva."),
+ ("user", "El viaje a la feria de BogotΓ‘ es del 12 al 15 de febrero."),
+ ("assistant", "Feria de BogotΓ‘: del 12 al 15 de febrero."),
+ ("user", "hola"),
+ ("assistant", "Β‘Hola! ΒΏEn quΓ© te ayudo?"),
+ ("user", "Gracias por todo"),
+ ("assistant", "Β‘Con gusto!"),
+]
+
+
+def _day(day, messages, start_minute=0):
+ return [(role, text, f"{day}T09:{start_minute + i:02d}:00Z") for i, (role, text) in enumerate(messages)]
+
+
+CONVERSATIONS = {
+ "baseline": [(r, t, f"2026-11-30T10:{i:02d}:00Z") for i, (r, t) in enumerate(BASELINE_CONVERSATION)],
+ "work-es": (
+ _day("2026-11-24", [
+ ("user", "El cΓ³digo del pedido urgente es PX-4471 y llega el viernes."),
+ ("assistant", "Anotado el pedido PX-4471 para el viernes."),
+ ("user", "Mi compaΓ±ero de turno se llama Rodrigo Salcedo."),
+ ("assistant", "Perfecto, Rodrigo Salcedo es tu compaΓ±ero de turno."),
+ ("user", "La factura de mantenimiento saliΓ³ por 8.350 pesos."),
+ ("assistant", "Mantenimiento: 8.350 pesos."),
+ ("user", "Al principio pensΓ© en hacer la fiesta de fin de aΓ±o en el salΓ³n Aurora."),
+ ("assistant", "El salΓ³n Aurora suena bien para la fiesta."),
+ ])
+ + _day("2026-11-25", [
+ ("user", "El cliente FerreterΓa El Tornillo pidiΓ³ 40 cajas de tornillos de media pulgada."),
+ ("assistant", "FerreterΓa El Tornillo: 40 cajas de media pulgada."),
+ ("user", "La auditorΓa externa la hace la firma Ortega & Asociados el 15 de diciembre."),
+ ("assistant", "AuditorΓa de Ortega & Asociados el 15 de diciembre."),
+ ("user", "Prefiero que los reportes me lleguen los lunes a primera hora."),
+ ("assistant", "Entendido: reportes los lunes temprano."),
+ ])
+ + _day("2026-11-26", [
+ ("user", "El montacargas nΓΊmero 3 estΓ‘ en reparaciΓ³n hasta el miΓ©rcoles."),
+ ("assistant", "El montacargas 3 vuelve el miΓ©rcoles."),
+ ("user", "Mi hija cumple aΓ±os el 2 de enero y quiero pedir el dΓa libre."),
+ ("assistant", "Te ayudo a pedir el 2 de enero libre."),
+ ("user", "El presupuesto de capacitaciΓ³n para el prΓ³ximo aΓ±o es de 25 millones."),
+ ("assistant", "CapacitaciΓ³n del prΓ³ximo aΓ±o: 25 millones."),
+ ])
+ + _day("2026-11-27", [
+ ("user", "Al final la fiesta de fin de aΓ±o serΓ‘ en el restaurante La Terraza."),
+ ("assistant", "Cambio anotado: la fiesta serΓ‘ en La Terraza."),
+ ("user", "La meta de satisfacciΓ³n del cliente es 92 %."),
+ ("assistant", "Meta de satisfacciΓ³n: 92 %."),
+ ])
+ ),
+ "work-en": (
+ _day("2026-11-24", [
+ ("user", "Our warehouse manager is Priya Nair."),
+ ("assistant", "Noted, Priya Nair manages the warehouse."),
+ ("user", "Initially we planned to ship the new orders with DHL."),
+ ("assistant", "DHL for the new orders, got it."),
+ ("user", "The server migration is scheduled for January 14th."),
+ ("assistant", "Server migration on January 14th."),
+ ])
+ + _day("2026-11-25", [
+ ("user", "The new pricing tier will cost 49 dollars per month."),
+ ("assistant", "New tier: 49 dollars a month."),
+ ("user", "I'm allergic to peanuts, keep that in mind for the team lunch."),
+ ("assistant", "No peanuts at the team lunch."),
+ ("user", "Ticket number 5521 is about the broken printer on the second floor."),
+ ("assistant", "Ticket 5521: second-floor printer."),
+ ])
+ + _day("2026-11-26", [
+ ("user", "We switched the carrier: from now on we ship the new orders with FedEx."),
+ ("assistant", "Carrier changed to FedEx."),
+ ("user", "The quarterly review deck must be ready by Thursday."),
+ ("assistant", "Quarterly deck due Thursday."),
+ ])
+ ),
+ "work-pt": (
+ _day("2026-11-24", [
+ ("user", "A nossa fornecedora de embalagens Γ© a Embalagens Litoral."),
+ ("assistant", "Anotado: Embalagens Litoral."),
+ ("user", "Primeiro escolhemos o plano bΓ‘sico do software de estoque."),
+ ("assistant", "Plano bΓ‘sico, certo."),
+ ("user", "O estoque mΓnimo de luvas Γ© de 300 pares."),
+ ("assistant", "MΓnimo de 300 pares de luvas."),
+ ])
+ + _day("2026-11-25", [
+ ("user", "O responsΓ‘vel pela seguranΓ§a Γ© o Tiago Moreira."),
+ ("assistant", "Tiago Moreira cuida da seguranΓ§a."),
+ ("user", "Mudamos para o plano empresarial do software de estoque."),
+ ("assistant", "Agora Γ© o plano empresarial."),
+ ("user", "A entrega para Campinas atrasou dois dias."),
+ ("assistant", "Campinas com dois dias de atraso."),
+ ])
+ ),
+ "personal": _day("2026-11-29", [
+ ("user", "Hoy quiero organizar mi semana."),
+ ("assistant", "Claro, empecemos por lo mΓ‘s urgente."),
+ ("user", "RecuΓ©rdame revisar el correo despuΓ©s del almuerzo."),
+ ("assistant", "Lo tendrΓ© en cuenta."),
+ ]),
+}
+
+# ββ Noise: what a long, real conversation looks like around the facts βββββββββ
+
+_NOISE = {
+ "es": (["RevisΓ©", "ActualicΓ©", "OrganicΓ©", "ComentΓ©", "PreparΓ©", "OrdenΓ©"],
+ ["el tablero", "la agenda", "los pendientes", "la carpeta compartida", "el informe semanal",
+ "las notas de la reuniΓ³n", "el calendario", "los correos", "la lista de compras", "el archivo"],
+ ["con el equipo", "esta maΓ±ana", "antes del almuerzo", "por la tarde", "con calma", "otra vez"]),
+ "en": (["I reviewed", "I updated", "I sorted", "I discussed", "I prepared", "I cleaned up"],
+ ["the board", "the agenda", "the to-do list", "the shared folder", "the weekly report",
+ "the meeting notes", "the calendar", "the inbox", "the shopping list", "the file"],
+ ["with the team", "this morning", "before lunch", "in the afternoon", "calmly", "again"]),
+ "pt": (["Revisei", "Atualizei", "Organizei", "Comentei", "Preparei", "Arrumei"],
+ ["o quadro", "a agenda", "as pendΓͺncias", "a pasta compartilhada", "o relatΓ³rio semanal",
+ "as notas da reuniΓ£o", "o calendΓ‘rio", "os e-mails", "a lista de compras", "o arquivo"],
+ ["com a equipe", "hoje cedo", "antes do almoΓ§o", "Γ tarde", "com calma", "de novo"]),
+}
+_NOISE_LANG = {"baseline": "es", "work-es": "es", "work-en": "en", "work-pt": "pt", "personal": "es"}
+
+
+def noise(conversation, n):
+ """`n` filler messages for a conversation, deterministic, dated before every fact (Nov 1β20)."""
+ verbs, things, tails = _NOISE[_NOISE_LANG.get(conversation, "es")]
+ out = []
+ for i in range(n):
+ line = f"{verbs[i % len(verbs)]} {things[(i // len(verbs)) % len(things)]} {tails[(i // 7) % len(tails)]}."
+ day = 1 + (i % 20)
+ out.append(("user", line, f"2026-11-{day:02d}T{8 + i % 10:02d}:{i % 60:02d}:00Z"))
+ return out
+
+
+# ββ Questions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+QUESTIONS = [
+ # baseline: the set measured in Aimee (one conversation)
+ *[{"category": "baseline", "scope": "baseline", "q": q, "expect": e} for q, e in [
+ ("ΒΏcuΓ‘l era el presupuesto de la bodega?", "12.000"),
+ ("ΒΏquΓ© te dije del proveedor de empaques?", "Distribuidora Andina"),
+ ("ΒΏcuΓ‘ndo era la reuniΓ³n con calidad?", "jueves"),
+ ("ΒΏcΓ³mo se llama mi jefa?", "Laura"),
+ ("ΒΏen quΓ© formato quiere los informes?", "PDF"),
+ ("ΒΏcuΓ‘ntas personas iba a contratar?", "dos personas"),
+ ("recuerdas la meta de ventas que te dije", "500"),
+ ("what was the problem with my VPN?", "VPN"),
+ ("quando vence o contrato do Horizonte?", "marΓ§o"),
+ ("ΒΏde quΓ© color quedΓ³ la marca al final?", "verde oliva"),
+ ("ΒΏquΓ© fechas tiene el viaje a la feria?", "febrero"),
+ ("what color did I choose for the brand?", "verde oliva"),
+ ("qual era o orΓ§amento da reforma?", "12.000"),
+ ]],
+ *[{"category": "baseline-negative", "scope": "baseline", "q": q, "none": True} for q in [
+ "ΒΏcuΓ‘ntas cΓ‘psulas tengo?",
+ "ΒΏquΓ© tareas tengo vencidas hoy?",
+ "explΓcame la revoluciΓ³n francesa",
+ "ΒΏcΓ³mo se calcula el punto de equilibrio?",
+ "dame el clima de maΓ±ana",
+ "how many customers do we have per country?",
+ "quantos registros tem a cΓ‘psula de entregas?",
+ "escrΓbeme un poema sobre el mar",
+ "ΒΏquΓ© hora es en Tokio?",
+ "recomiΓ©ndame un libro de liderazgo",
+ ]],
+
+ # same conversation, same language
+ *[{"category": "same-chat", "scope": s, "q": q, "expect": e} for s, q, e in [
+ ("work-es", "ΒΏquiΓ©n es mi compaΓ±ero de turno?", "Rodrigo"),
+ ("work-es", "ΒΏcuΓ‘ndo llega el pedido urgente?", "viernes"),
+ ("work-es", "ΒΏquΓ© dΓa prefiero recibir los reportes?", "lunes"),
+ ("work-es", "ΒΏhasta cuΓ‘ndo estΓ‘ en reparaciΓ³n el montacargas?", "miΓ©rcoles"),
+ ("work-es", "ΒΏpor quΓ© querΓa pedir el dΓa libre?", "hija"),
+ ("work-es", "ΒΏcuΓ‘l es la meta de satisfacciΓ³n?", "92"),
+ ("work-en", "who manages the warehouse?", "Priya"),
+ ("work-en", "when is the server migration?", "January 14"),
+ ("work-en", "what am I allergic to?", "peanuts"),
+ ("work-en", "when is the quarterly deck due?", "Thursday"),
+ ("work-en", "what was the ticket about the printer?", "5521"),
+ ("work-en", "how much does the new pricing tier cost?", "49"),
+ ("work-pt", "quem Γ© a nossa fornecedora de embalagens?", "Litoral"),
+ ("work-pt", "qual Γ© o estoque mΓnimo de luvas?", "300"),
+ ("work-pt", "quem cuida da seguranΓ§a?", "Tiago"),
+ ("work-pt", "o que aconteceu com a entrega para Campinas?", "Campinas"),
+ ("work-es", "ΒΏquΓ© pidiΓ³ la ferreterΓa?", "40 cajas"),
+ ("work-es", "ΒΏquiΓ©n hace la auditorΓa externa?", "Ortega"),
+ ]],
+
+ # names, codes and figures: what embeddings handle worst
+ *[{"category": "names-numbers", "scope": s, "q": q, "expect": e} for s, q, e in [
+ ("work-es", "ΒΏquΓ© es PX-4471?", "PX-4471"),
+ ("work-es", "ΒΏquΓ© sabes de Rodrigo Salcedo?", "Rodrigo Salcedo"),
+ ("work-es", "ΒΏde cuΓ‘nto fue la factura de mantenimiento?", "8.350"),
+ ("work-es", "ΒΏquΓ© me dijiste de Ortega & Asociados?", "Ortega"),
+ ("work-es", "ΒΏcuΓ‘nto es el presupuesto de capacitaciΓ³n?", "25 millones"),
+ ("work-es", "ΒΏquΓ© pasa el 15 de diciembre?", "15 de diciembre"),
+ ("work-es", "ΒΏquΓ© hay del montacargas 3?", "montacargas"),
+ ("work-es", "FerreterΓa El Tornillo", "Tornillo"),
+ ("work-en", "what do you know about Priya Nair?", "Priya Nair"),
+ ("work-en", "what is ticket 5521?", "5521"),
+ ("work-en", "what happens on January 14th?", "January 14"),
+ ("work-en", "49 dollars?", "49"),
+ ("work-pt", "o que Γ© a Embalagens Litoral?", "Litoral"),
+ ("work-pt", "Tiago Moreira", "Tiago"),
+ ("work-pt", "300 pares de quΓͺ?", "300"),
+ ]],
+
+ # asked in another language than it was said
+ *[{"category": "cross-language", "scope": s, "q": q, "expect": e} for s, q, e in [
+ ("work-es", "who is my shift partner?", "Rodrigo"),
+ ("work-es", "quando chega o pedido urgente?", "viernes"),
+ ("work-es", "when is the external audit?", "15 de diciembre"),
+ ("work-es", "what is the customer satisfaction goal?", "92"),
+ ("work-en", "ΒΏquiΓ©n maneja la bodega?", "Priya"),
+ ("work-en", "ΒΏa quΓ© soy alΓ©rgico?", ["peanuts", "cacahuete", "manΓ"]),
+ ("work-en", "quando Γ© a migraΓ§Γ£o do servidor?", "January 14"),
+ ("work-pt", "ΒΏquiΓ©n es el responsable de seguridad?", "Tiago"),
+ ("work-pt", "what is the minimum stock of gloves?", "300"),
+ ("work-pt", "ΒΏquΓ© pasΓ³ con la entrega a Campinas?", "Campinas"),
+ ]],
+
+ # asked in another conversation, without saying so (Phase 2 target)
+ *[{"category": "cross-chat", "scope": "personal", "q": q, "expect": e} for q, e in [
+ ("ΒΏcΓ³mo se llama mi compaΓ±ero de turno?", "Rodrigo"),
+ ("ΒΏcuΓ‘ndo cumple aΓ±os mi hija?", "2 de enero"),
+ ("ΒΏquΓ© dΓa prefiero los reportes?", "lunes"),
+ ("ΒΏdΓ³nde serΓ‘ la fiesta de fin de aΓ±o?", "Terraza"),
+ ("ΒΏcuΓ‘l era el cΓ³digo del pedido urgente?", "PX-4471"),
+ ("ΒΏa quΓ© soy alΓ©rgico?", ["peanuts", "cacahuete", "manΓ"]),
+ ("ΒΏquiΓ©n maneja la bodega?", "Priya"),
+ ("ΒΏquiΓ©n es el responsable de seguridad?", "Tiago"),
+ ("ΒΏde cuΓ‘nto es el presupuesto de capacitaciΓ³n?", "25 millones"),
+ ("ΒΏquiΓ©n hace la auditorΓa?", "Ortega"),
+ ]],
+
+ # by date (Phase 1 target): a recalled chunk must be from that day
+ *[{"category": "by-date", "scope": s, "q": q, "date": d} for s, q, d in [
+ ("work-es", "ΒΏde quΓ© hablamos el martes 25?", "2026-11-25"),
+ ("work-es", "ΒΏquΓ© te contΓ© el 26 de noviembre?", "2026-11-26"),
+ ("work-es", "ΒΏquΓ© anotamos el lunes 24?", "2026-11-24"),
+ ("work-es", "ΒΏquΓ© me dijiste el jueves 27?", "2026-11-27"),
+ ("work-en", "what did we talk about on November 25th?", "2026-11-25"),
+ ("work-en", "what did I tell you on the 26th?", "2026-11-26"),
+ ("work-pt", "o que falamos no dia 25?", "2026-11-25"),
+ ("work-pt", "o que eu te disse no dia 24?", "2026-11-24"),
+ ]],
+
+ # a fact that changed: the current value must rank above the old one
+ *[{"category": "changed-fact", "scope": s, "q": q, "expect": e, "stale": st} for s, q, e, st in [
+ ("work-es", "ΒΏdΓ³nde serΓ‘ la fiesta de fin de aΓ±o?", "Terraza", "Aurora"),
+ ("work-es", "ΒΏen quΓ© lugar quedΓ³ la fiesta?", "Terraza", "Aurora"),
+ ("work-en", "which carrier do we ship the new orders with?", "FedEx", "DHL"),
+ ("work-en", "are we still using DHL?", "FedEx", "DHL"),
+ ("work-pt", "qual plano do software de estoque usamos?", "empresarial", "bΓ‘sico"),
+ ("work-pt", "ainda estamos no plano bΓ‘sico?", "empresarial", "bΓ‘sico"),
+ ]],
+
+ # nothing was said about these: nothing should come back
+ *[{"category": "negative", "scope": s, "q": q, "none": True} for s, q in [
+ ("work-es", "ΒΏcuΓ‘ntas cΓ‘psulas tengo?"),
+ ("work-es", "explΓcame la fotosΓntesis"),
+ ("work-es", "ΒΏcΓ³mo se llama mi perro?"),
+ ("work-es", "dame una receta de arepas"),
+ ("work-en", "what's the capital of Australia?"),
+ ("work-en", "what is my dog's name?"),
+ ("work-en", "write a haiku about autumn"),
+ ("work-en", "how many tasks are overdue?"),
+ ("work-pt", "qual Γ© a capital do Brasil?"),
+ ("work-pt", "como se chama o meu cachorro?"),
+ ("personal", "ΒΏquΓ© hora es en Tokio?"),
+ ("personal", "recomiΓ©ndame una pelΓcula"),
+ ]],
+]
diff --git a/packages/python/src/orbit/facts.py b/packages/python/src/orbit/facts.py
new file mode 100644
index 0000000..28e92d2
--- /dev/null
+++ b/packages/python/src/orbit/facts.py
@@ -0,0 +1,277 @@
+"""
+What Orbit knows about a person: durable facts, across every conversation.
+
+`orbit.memory` remembers what was *said*, chunk by chunk, inside a conversation. This module
+remembers what is *true* about the person ("their boss is Laura MΓ©ndez", "allergic to peanuts",
+"the year-end party moved to La Terraza"), in their database, for every conversation:
+
+- `might_hold_fact(text)` decides without a model whether a message could state a fact: most
+ messages are questions or requests, and only the rest is worth a model call.
+- `learn(...)` asks the caller's model (`llm(system, user) -> str`; Orbit knows no provider) to
+ extract the facts, each under a stable key. A fact replaces an active one with its key when both
+ are about the same thing (`SAME_FACT`): the newest value is the one that counts. The key alone is
+ not trusted, models reuse keys for unrelated facts.
+- `recall(...)` finds the facts that answer a question (vectors + full text, the same gate as
+ `orbit.memory`), in every conversation.
+- `forget(...)` deletes what matches ("forget what I told you about my boss"), with the chunks of
+ the messages it came from.
+"""
+import json
+import re
+import sqlite3
+from typing import Callable, Dict, List, Optional, Sequence
+
+from orbit import memory
+from orbit.text import content_words, strip_wrapper, without_accents
+
+LLM = Callable[[str, str], str]
+
+TABLE = "orbit_facts"
+FTS = f"{TABLE}_fts"
+
+#: The same gate as chunks: very similar on its own, or similar with a full-text match.
+MIN_SCORE = memory.MIN_SCORE
+MIN_SCORE_WITH_WORDS = memory.MIN_SCORE_WITH_WORDS
+#: Facts known to the extractor, so it can reuse their keys (newest first).
+KNOWN_FOR_EXTRACTION = 60
+#: A new fact replaces an active one with its key only if they are this similar. The model reuses
+#: keys for unrelated facts ("the packaging supplier" took the key of "the shipping carrier" and
+#: erased it). MEASURED (paraphrase-multilingual-MiniLM-L12-v2): the same fact restated or updated,
+#: 0.50β0.73; different facts, 0.06β0.39.
+SAME_FACT = 0.45
+
+_KEY = re.compile(r"^[a-z0-9_]+(?:\.[a-z0-9_]+)*$")
+
+# ββ Is it worth a model call? βββββββββββββββββββββββββββββββββββββββββββββββββ
+
+#: Words that announce something about the person or their world (accents removed).
+_CUE = re.compile(
+ r"\b(?:mi|mis|me llamo|mi nombre|soy|trabajo|vivo|prefiero|me gusta|me gustan|no me gusta|odio|"
+ r"alergic[oa]s?|alergia|cumpleanos|cumple|naci|tengo (?:un|una|dos|tres|\d+) (?:hij|perr|gat)|"
+ r"estoy casad[oa]|nuestro|nuestra|nuestros|nuestras|"
+ r"elegi|elegimos|decidi|decidimos|cambiamos|cambie|pense|planeamos|quedamos en|"
+ r"my|i'm|i am|i work|i live|i prefer|i like|i love|i hate|allergic|allergy|birthday|i was born|"
+ r"our|we use|we switched|we chose|we picked|we decided|we planned|we moved|i decided|i chose|"
+ r"meu|minha|meus|minhas|me chamo|sou|trabalho|moro|prefiro|gosto|odeio|aniversario|nasci|"
+ r"nosso|nossa|nossos|nossas|mudamos|escolhemos|escolhi|decidimos|decidi|planejamos)\b")
+_DIGIT = re.compile(r"\d")
+#: A capitalized word that does not start a sentence: a name ("Rodrigo", "La Terraza", "Priya"),
+#: or an acronym anywhere ("DHL", "PDF").
+_PROPER = re.compile(r"(? bool:
+ """
+ Could this message state a durable fact? A statement (not a question) with a personal cue,
+ a name inside the sentence or a figure. False negatives cost a fact; false positives, a short
+ model call that returns nothing.
+ """
+ t = (text or "").strip()
+ if len(t) < 15 or "?" in t or "ΒΏ" in t:
+ return False
+ return bool(_CUE.search(without_accents(t)) or _DIGIT.search(t) or _PROPER.search(t))
+
+
+# ββ Storage βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def ensure_schema(conn: sqlite3.Connection) -> None:
+ conn.execute(f"""
+ CREATE TABLE IF NOT EXISTS {TABLE} (
+ id INTEGER PRIMARY KEY,
+ key TEXT NOT NULL, -- stable name of the fact ("boss.name")
+ statement TEXT NOT NULL, -- the fact, in the person's language
+ source_id INTEGER, -- the message it came from
+ conversation TEXT,
+ ts TEXT,
+ model TEXT NOT NULL,
+ embedding BLOB NOT NULL,
+ active INTEGER NOT NULL DEFAULT 1 -- 0 once a newer value replaced it
+ )
+ """)
+ conn.execute(f"CREATE INDEX IF NOT EXISTS idx_{TABLE}_key ON {TABLE}(key, active)")
+ had_fts = conn.execute("SELECT 1 FROM sqlite_master WHERE name = ?", (FTS,)).fetchone()
+ conn.execute(f"CREATE VIRTUAL TABLE IF NOT EXISTS {FTS} USING fts5("
+ f"statement, content='{TABLE}', content_rowid='id', tokenize='unicode61 remove_diacritics 2')")
+ conn.execute(f"CREATE TRIGGER IF NOT EXISTS {TABLE}_ai AFTER INSERT ON {TABLE} BEGIN "
+ f"INSERT INTO {FTS}(rowid, statement) VALUES (new.id, new.statement); END")
+ conn.execute(f"CREATE TRIGGER IF NOT EXISTS {TABLE}_ad AFTER DELETE ON {TABLE} BEGIN "
+ f"INSERT INTO {FTS}({FTS}, rowid, statement) VALUES ('delete', old.id, old.statement); END")
+ if not had_fts:
+ conn.execute(f"INSERT INTO {FTS}({FTS}) VALUES ('rebuild')")
+
+
+def known(conn: sqlite3.Connection, limit: int = KNOWN_FOR_EXTRACTION) -> List[Dict[str, str]]:
+ """The current facts (newest first): what the extractor needs to reuse keys."""
+ if not _exists(conn):
+ return []
+ rows = conn.execute(f"SELECT key, statement, ts FROM {TABLE} WHERE active = 1 "
+ "ORDER BY COALESCE(ts, '') DESC, id DESC LIMIT ?", (limit,)).fetchall()
+ return [{"key": k, "statement": s, "ts": ts} for k, s, ts in rows]
+
+
+def _vector(blob: bytes, dimension: int) -> tuple:
+ return memory._unpack(blob, "FLOAT16" if len(blob) == 2 * dimension else "FLOAT32")
+
+
+def _cosine(a: Sequence[float], b: Sequence[float]) -> float:
+ return sum(x * y for x, y in zip(a, b)) if len(a) == len(b) else 0.0
+
+
+def remember(conn: sqlite3.Connection, facts: Sequence[Dict[str, str]], *, embed, model: str,
+ source_id: Optional[int] = None, conversation: Optional[str] = None,
+ ts: Optional[str] = None) -> int:
+ """
+ Stores facts. One replaces the active facts with its key that are about the same thing
+ (similarity β₯ SAME_FACT); a different fact under a reused key lives next to them.
+ Returns how many went in.
+ """
+ good = [f for f in facts if _KEY.match(f.get("key") or "") and (f.get("statement") or "").strip()]
+ if not good:
+ return 0
+ ensure_schema(conn)
+ vectors = [memory._unit(v) for v in embed([f["statement"].strip() for f in good])]
+ for f, v in zip(good, vectors):
+ for old_id, blob in conn.execute(f"SELECT id, embedding FROM {TABLE} WHERE key = ? AND active = 1 "
+ "AND model = ?", (f["key"], model)).fetchall():
+ if _cosine(v, _vector(blob, len(v))) >= SAME_FACT:
+ conn.execute(f"UPDATE {TABLE} SET active = 0 WHERE id = ?", (old_id,))
+ conn.execute(f"INSERT INTO {TABLE} (key, statement, source_id, conversation, ts, model, embedding) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (f["key"], f["statement"].strip()[:300], source_id, conversation, ts, model,
+ memory._pack(v, memory.DEFAULT_TYPE)))
+ conn.commit()
+ return len(good)
+
+
+# ββ Extraction ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+SYSTEM = "You extract durable facts from one message a person wrote to an assistant. Reply with JSON only."
+
+
+def extraction_prompt(message: str, known_facts: Sequence[Dict[str, str]]) -> str:
+ listed = "\n".join(f"- {f['key']}: {f['statement']}" for f in known_facts) or "(none)"
+ return f"""Facts already known about this person (key: statement):
+{listed}
+
+Message from the person:
+{message}
+
+Extract what this message states that will still be true next week, about the person or their world:
+names and roles of people around them, their preferences, allergies, birthdays and important dates,
+where they work or live, the tools, suppliers, plans and decisions they mention (and their figures,
+codes and dates). Not facts: requests, questions, greetings, what they are doing right now, opinions
+about the conversation.
+
+For each fact give a short stable key in English snake_case, with dots for parts (e.g. "boss.name",
+"allergy", "reports.preferred_day", "year_end_party.venue"), and a statement in third person and
+self-contained, written in THE SAME LANGUAGE AS THE MESSAGE, keeping its names and figures as written
+(an English message gives "The person is allergic to peanuts."; a Spanish one, "La jefa de la persona se
+llama Laura MΓ©ndez.").
+If the message updates or corrects a known fact, reuse its key exactly: the new value replaces it, and the
+statement also says what it replaces (e.g. "The company now ships new orders with FedEx (before: DHL).").
+
+Reply {{"facts": [{{"key": "...", "statement": "..."}}]}}, or {{"facts": []}} if there is nothing."""
+
+
+def parse(reply: str) -> List[Dict[str, str]]:
+ """The facts in the model's reply; anything malformed is dropped, never raised."""
+ try:
+ start, end = reply.index("{"), reply.rindex("}") + 1
+ data = json.loads(reply[start:end])
+ except (ValueError, TypeError):
+ return []
+ out = []
+ for f in (data.get("facts") or []) if isinstance(data, dict) else []:
+ if isinstance(f, dict) and isinstance(f.get("key"), str) and isinstance(f.get("statement"), str):
+ key = f["key"].strip().lower()
+ if _KEY.match(key) and f["statement"].strip():
+ out.append({"key": key, "statement": f["statement"].strip()})
+ return out
+
+
+def learn(conn: sqlite3.Connection, message: str, *, llm: LLM, embed, model: str,
+ source_id: Optional[int] = None, conversation: Optional[str] = None,
+ ts: Optional[str] = None) -> List[Dict[str, str]]:
+ """Extracts and stores the facts of one message of the person. Returns them."""
+ if not might_hold_fact(message):
+ return []
+ found = parse(llm(SYSTEM, extraction_prompt(message, known(conn))))
+ remember(conn, found, embed=embed, model=model, source_id=source_id,
+ conversation=conversation, ts=ts)
+ return found
+
+
+# ββ Recall and forgetting βββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def recall(conn: sqlite3.Connection, question: str, *, embed, model: str, k: int = 3,
+ min_score: float = MIN_SCORE, min_score_with_words: float = MIN_SCORE_WITH_WORDS) -> List[dict]:
+ """The current facts that answer `question`, from every conversation of this database."""
+ if not question or not _exists(conn):
+ return []
+ topic = strip_wrapper(question)
+ rows = conn.execute(f"SELECT id, key, statement, conversation, ts, embedding FROM {TABLE} "
+ "WHERE active = 1 AND model = ?", (model,)).fetchall()
+ if not rows:
+ return []
+ q = memory._unit(embed([topic or question])[0])
+ lexical = set()
+ words = sorted(content_words(topic))
+ if words:
+ ensure_schema(conn)
+ match = " OR ".join(f'"{w}"*' for w in words)
+ lexical = {r[0] for r in conn.execute(f"SELECT rowid FROM {FTS} WHERE {FTS} MATCH ?", (match,))}
+ found = []
+ for fid, key, statement, conversation, ts, blob in rows:
+ score = _cosine(q, _vector(blob, len(q)))
+ if score >= min_score or (fid in lexical and score >= min_score_with_words):
+ found.append({"id": fid, "key": key, "statement": statement, "conversation": conversation,
+ "ts": ts, "score": float(score)})
+ found.sort(key=lambda f: -f["score"])
+ found = found[:k]
+ for f in found:
+ f.pop("id")
+ return found
+
+
+def forget(conn: sqlite3.Connection, about: str, *, embed, model: str) -> List[str]:
+ """
+ Deletes the facts about `about` ("lo de mi jefa"), the older versions they replaced (same key
+ and about the same thing), and the chunks of the messages they came from: what is forgotten is
+ not recalled any other way. Returns the statements forgotten.
+ """
+ hits = recall(conn, about, embed=embed, model=model, k=10)
+ if not hits:
+ return []
+ by_statement = {h["statement"] for h in hits}
+ keys = sorted({h["key"] for h in hits})
+ rows = conn.execute(f"SELECT id, key, statement, source_id, embedding FROM {TABLE} "
+ f"WHERE key IN ({','.join('?' * len(keys))}) AND model = ?", (*keys, model)).fetchall()
+ dimension = len(embed([about])[0])
+ hit_vectors = [(r[1], _vector(r[4], dimension)) for r in rows if r[2] in by_statement]
+ doomed = [r for r in rows if r[2] in by_statement or any(
+ k == r[1] and _cosine(v, _vector(r[4], dimension)) >= SAME_FACT for k, v in hit_vectors)]
+ ids = [r[0] for r in doomed]
+ sources = sorted({r[3] for r in doomed if r[3] is not None})
+ conn.execute(f"DELETE FROM {TABLE} WHERE id IN ({','.join('?' * len(ids))})", ids)
+ if sources and memory.table_exists(conn):
+ memory.ensure_schema(conn)
+ # the message it came from and the answer to it ("Got it, PDF reports for Laura"): either
+ # would bring back what was just forgotten
+ answers = []
+ for source in sources:
+ row = conn.execute(f"SELECT conversation FROM {memory.TABLE} WHERE source_id = ? LIMIT 1", (source,)).fetchone()
+ if row:
+ nxt = conn.execute(f"SELECT MIN(source_id) FROM {memory.TABLE} WHERE conversation = ? AND source_id > ? "
+ "AND role = 'assistant'", (row[0], source)).fetchone()
+ if nxt and nxt[0] is not None:
+ answers.append(nxt[0])
+ gone = sources + answers
+ conn.execute(f"DELETE FROM {memory.TABLE} WHERE source_id IN ({','.join('?' * len(gone))})", gone)
+ conn.commit()
+ return [h["statement"] for h in hits]
+
+
+def _exists(conn: sqlite3.Connection) -> bool:
+ return conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (TABLE,)).fetchone() is not None
diff --git a/packages/python/src/orbit/memory.py b/packages/python/src/orbit/memory.py
new file mode 100644
index 0000000..380e530
--- /dev/null
+++ b/packages/python/src/orbit/memory.py
@@ -0,0 +1,327 @@
+"""
+Conversational memory inside SQLite: store what was said, find it again.
+
+Everything lives in the caller's database (one file per person keeps people apart), in the
+`orbit_chunks` table and its full-text index `orbit_chunks_fts` (FTS5, kept in sync by
+triggers). The caller passes:
+
+ embed(texts: list[str]) -> list of vectors # any model; Orbit normalizes them
+ model: str # stored with each vector, so a model
+ # change never mixes spaces
+
+Recall is hybrid. Vectors (`vector_full_scan`) find what is said differently; full text finds
+names, codes and figures that a long conversation pushes out of the vector top. Both rankings
+are fused (reciprocal rank fusion), and a chunk only comes back when it is very similar, or
+similar enough AND matched by full text: cosine alone does not separate signal from noise
+(measured with `python -m orbit.eval`). Dates said in words ("yesterday", "el martes 25") are
+turned into a time range by code (`orbit.dates`).
+"""
+import math
+import sqlite3
+import struct
+from datetime import datetime, timezone
+from typing import Callable, Dict, Iterable, List, Optional, Sequence
+
+import orbit
+from orbit import dates
+from orbit.text import asks_what_was_said, chunks, content_words, readable_text, strip_wrapper
+
+Embed = Callable[[List[str]], Sequence[Sequence[float]]]
+
+TABLE = "orbit_chunks"
+FTS = f"{TABLE}_fts"
+
+#: Similarity that lets a chunk in on its own, without any full-text match.
+MIN_SCORE = 0.6
+#: Similarity that lets a chunk in when full text also matched it.
+MIN_SCORE_WITH_WORDS = 0.3
+#: How many candidates each ranking contributes before fusing.
+CANDIDATES = 20
+#: Reciprocal rank fusion constant (the usual 60).
+RRF_K = 60
+
+#: How new tables store vectors. FLOAT16 halves the database (measured: 210 β 108 MB for
+#: 100,000 chunks of 384 dimensions) with the same recall (`orbit.eval` identical) and the
+#: same speed. A table that already holds FLOAT32 vectors keeps that format.
+DEFAULT_TYPE = "FLOAT16"
+_FORMATS = {"FLOAT16": ("e", 2), "FLOAT32": ("f", 4)}
+
+
+def ensure_schema(conn: sqlite3.Connection) -> None:
+ conn.execute(f"""
+ CREATE TABLE IF NOT EXISTS {TABLE} (
+ id INTEGER PRIMARY KEY,
+ source_id INTEGER NOT NULL, -- the caller's id for the message
+ conversation TEXT NOT NULL,
+ role TEXT, -- who said it
+ ts TEXT, -- when (ISO 8601, UTC)
+ chunk TEXT NOT NULL,
+ model TEXT NOT NULL,
+ embedding BLOB NOT NULL -- FLOAT16 (or FLOAT32 in older tables), unit length
+ )
+ """)
+ conn.execute(f"CREATE INDEX IF NOT EXISTS idx_{TABLE}_conversation ON {TABLE}(conversation)")
+ conn.execute(f"CREATE INDEX IF NOT EXISTS idx_{TABLE}_source ON {TABLE}(source_id)")
+ had_fts = conn.execute("SELECT 1 FROM sqlite_master WHERE name = ?", (FTS,)).fetchone()
+ conn.execute(f"CREATE VIRTUAL TABLE IF NOT EXISTS {FTS} USING fts5("
+ f"chunk, content='{TABLE}', content_rowid='id', tokenize='unicode61 remove_diacritics 2')")
+ conn.execute(f"CREATE TRIGGER IF NOT EXISTS {TABLE}_ai AFTER INSERT ON {TABLE} BEGIN "
+ f"INSERT INTO {FTS}(rowid, chunk) VALUES (new.id, new.chunk); END")
+ conn.execute(f"CREATE TRIGGER IF NOT EXISTS {TABLE}_ad AFTER DELETE ON {TABLE} BEGIN "
+ f"INSERT INTO {FTS}({FTS}, rowid, chunk) VALUES ('delete', old.id, old.chunk); END")
+ if not had_fts: # chunks stored before the index existed
+ conn.execute(f"INSERT INTO {FTS}({FTS}) VALUES ('rebuild')")
+
+
+def _unit(vector: Iterable[float]) -> List[float]:
+ v = [float(x) for x in vector]
+ norm = math.sqrt(sum(x * x for x in v))
+ return [x / norm for x in v] if norm else v
+
+
+def _vector_type(conn: sqlite3.Connection, model: str, dimension: int) -> str:
+ """The format this table already uses for `model` (from a stored vector's size), or the default."""
+ row = conn.execute(f"SELECT length(embedding) FROM {TABLE} WHERE model = ? LIMIT 1", (model,)).fetchone()
+ if row:
+ for name, (_code, size) in _FORMATS.items():
+ if row[0] == size * dimension:
+ return name
+ return DEFAULT_TYPE
+
+
+def _pack(v: Sequence[float], vector_type: str) -> bytes:
+ code, _size = _FORMATS[vector_type]
+ return struct.pack(f"<{len(v)}{code}", *v)
+
+
+def _unpack(blob: bytes, vector_type: str) -> tuple:
+ code, size = _FORMATS[vector_type]
+ return struct.unpack(f"<{len(blob) // size}{code}", blob)
+
+
+def _prepare(conn: sqlite3.Connection, dimension: int, vector_type: str) -> None:
+ """
+ The extension and `vector_init`. `normalized=1`: cosine becomes `1 - dot`.
+ `partition=conversation`: a search inside one conversation reads only its rows (through
+ the conversation index), instead of scanning every conversation and filtering after.
+ Once a table is registered in a connection, `vector_init` returns without touching the
+ database; the options are persisted, so other connections can scan without it.
+ """
+ orbit.load(conn)
+ ensure_schema(conn)
+ conn.execute("SELECT vector_init(?, 'embedding', ?)",
+ (TABLE, f"type={vector_type},dimension={dimension},distance=COSINE,normalized=1,"
+ "partition=conversation"))
+
+
+def _utc(moment: Optional[datetime]) -> Optional[str]:
+ """Comparable with stored `ts` strings ("2026-11-30T10:00:00Z", with or without fraction)."""
+ if moment is None:
+ return None
+ return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _filters(model, conversation, since, until, exclude_sources, alias="c"):
+ sql, params = f" AND {alias}.model = ?", [model]
+ if conversation:
+ sql += f" AND {alias}.conversation = ?"
+ params.append(conversation)
+ if since:
+ sql += f" AND {alias}.ts >= ?"
+ params.append(since)
+ if until:
+ sql += f" AND {alias}.ts < ?"
+ params.append(until)
+ if exclude_sources:
+ sql += f" AND {alias}.source_id NOT IN ({','.join('?' * len(exclude_sources))})"
+ params.extend(exclude_sources)
+ return sql, params
+
+
+_COLUMNS = "c.id, c.source_id, c.conversation, c.role, c.ts, c.chunk"
+
+
+def _row(r, score) -> dict:
+ return {"id": r[0], "source_id": r[1], "conversation": r[2], "role": r[3], "ts": r[4],
+ "chunk": r[5], "score": float(score)}
+
+
+def add(conn: sqlite3.Connection, *, source_id: int, conversation: str, text: str,
+ embed: Embed, model: str, role: Optional[str] = None, ts: Optional[str] = None) -> int:
+ """Chunks `text`, embeds it and stores it. Returns how many chunks went in."""
+ parts = chunks(text)
+ if not parts:
+ return 0
+ ensure_schema(conn)
+ vectors = [_unit(v) for v in embed(parts)]
+ vector_type = _vector_type(conn, model, len(vectors[0]))
+ conn.executemany(
+ f"INSERT INTO {TABLE} (source_id, conversation, role, ts, chunk, model, embedding) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
+ [(source_id, conversation, role, ts, c, model, _pack(v, vector_type)) for c, v in zip(parts, vectors)],
+ )
+ conn.commit()
+ return len(parts)
+
+
+def _vector_search(conn, q: List[float], model, conversation, k, since=None, until=None, exclude_sources=()):
+ vector_type = _vector_type(conn, model, len(q)) if table_exists(conn) else DEFAULT_TYPE
+ _prepare(conn, len(q), vector_type)
+ # the conversation goes to the scan itself (its partition), the rest is filtered by SQL
+ where, params = _filters(model, None, since, until, exclude_sources)
+ part = " AND s.part = ?" if conversation else ""
+ sql = (f"SELECT {_COLUMNS}, 1 - s.distance FROM vector_full_scan('{TABLE}', 'embedding', ?) AS s "
+ f"JOIN {TABLE} c ON c.id = s.rowid WHERE 1 = 1{part}{where} ORDER BY s.distance LIMIT ?")
+ args = [_pack(q, vector_type), *([conversation] if conversation else []), *params, k]
+ return [_row(r, r[6]) for r in conn.execute(sql, args).fetchall()]
+
+
+def _text_search(conn, topic: str, q: List[float], model, conversation, k, since=None, until=None,
+ exclude_sources=()):
+ """Full-text candidates (any content word, by prefix), each with its cosine to `q`."""
+ words = sorted(content_words(topic))
+ if not words:
+ return []
+ ensure_schema(conn)
+ match = " OR ".join(f'"{w}"*' for w in words)
+ where, params = _filters(model, conversation, since, until, exclude_sources)
+ sql = (f"SELECT {_COLUMNS}, c.embedding FROM {FTS} f JOIN {TABLE} c ON c.id = f.rowid "
+ f"WHERE {FTS} MATCH ?{where} ORDER BY bm25({FTS}) LIMIT ?")
+ vector_type = _vector_type(conn, model, len(q))
+ out = []
+ for r in conn.execute(sql, [match, *params, k]).fetchall():
+ v = _unpack(r[6], vector_type)
+ out.append(_row(r, sum(a * b for a, b in zip(q, v)) if len(v) == len(q) else 0.0))
+ return out
+
+
+def search(conn: sqlite3.Connection, query: str, *, embed: Embed, model: str,
+ conversation: Optional[str] = None, k: int = 4,
+ exclude_sources: Sequence[int] = ()) -> List[dict]:
+ """
+ The `k` chunks most similar to `query` by vectors alone, from one conversation or (without
+ it) from all of them. No threshold and no full text: `recall` is the hybrid one.
+ """
+ q = _unit(embed([query])[0])
+ found = _vector_search(conn, q, model, conversation, k, exclude_sources=exclude_sources)
+ for f in found:
+ f.pop("id")
+ return found
+
+
+def _pair(conn, found: dict, model: str) -> Optional[dict]:
+ """The other half of the exchange: the answer to a question, the question of an answer."""
+ if found["role"] not in ("user", "assistant"):
+ return None
+ after = found["role"] == "user"
+ row = conn.execute(
+ f"SELECT role, chunk FROM {TABLE} WHERE conversation = ? AND model = ? AND role != ? "
+ f"AND source_id {'>' if after else '<'} ? ORDER BY source_id {'ASC' if after else 'DESC'}, "
+ f"id {'ASC' if after else 'DESC'} LIMIT 1",
+ (found["conversation"], model, found["role"], found["source_id"])).fetchone()
+ return {"role": row[0], "chunk": row[1]} if row else None
+
+
+def recall(conn: sqlite3.Connection, question: str, *, embed: Embed, model: str,
+ conversation: Optional[str] = None, window: Sequence[str] = (), k: int = 4,
+ now: Optional[datetime] = None, min_score: float = MIN_SCORE,
+ min_score_with_words: float = MIN_SCORE_WITH_WORDS) -> List[dict]:
+ """
+ What was said before that answers `question`.
+
+ - The question loses its conversational wrapper ("what did I tell you aboutβ¦").
+ - With `now` (timezone-aware), a date in a question about the conversation ("what did we
+ talk about yesterday?") becomes a time range; if nothing else is asked, that day's chunks
+ come back in order. In any other question a relative date ("tomorrow") leaves the topic
+ and an absolute one ("December 15th") stays in it: it is what is being asked about.
+ - Vector and full-text candidates are fused; a chunk comes back when its similarity reaches
+ `min_score`, or `min_score_with_words` with a full-text match.
+ - Chunks already in `window` (the recent messages the caller sends anyway) and the question
+ itself are left out. Each result carries `pair`: the other half of its exchange.
+
+ `conversation=None` searches every conversation in this database.
+ """
+ if not question or not table_exists(conn):
+ return []
+ topic = strip_wrapper(question)
+ since = until = None
+ if now is not None:
+ found_range = dates.find_range(topic, now)
+ if found_range:
+ start, end, rest, relative = found_range
+ if asks_what_was_said(question):
+ since, until, topic = _utc(start), _utc(end), rest
+ elif relative:
+ topic = rest
+ seen = [readable_text(t) for t in [*window, question] if t]
+
+ def fresh(f):
+ return not any(f["chunk"] in s for s in seen)
+
+ ranged = None
+ if since:
+ ensure_schema(conn)
+ where, params = _filters(model, conversation, since, until, ())
+ ranged = [_row(r, 1.0) for r in conn.execute(
+ f"SELECT {_COLUMNS} FROM {TABLE} c WHERE 1 = 1{where} ORDER BY c.ts, c.id", params).fetchall()]
+ ranged = [f for f in ranged if fresh(f)]
+ if not content_words(topic):
+ return _with_pairs(conn, ranged[:k], model, seen)
+
+ q = _unit(embed([topic or question])[0])
+ by_vector = _vector_search(conn, q, model, conversation, CANDIDATES, since, until)
+ by_text = _text_search(conn, topic, q, model, conversation, CANDIDATES, since, until)
+
+ fused: Dict[int, dict] = {}
+ for ranking, lexical in ((by_vector, False), (by_text, True)):
+ for rank, f in enumerate(ranking):
+ entry = fused.setdefault(f["id"], {**f, "rrf": 0.0, "lexical": False})
+ entry["rrf"] += 1.0 / (RRF_K + rank + 1)
+ entry["lexical"] = entry["lexical"] or lexical
+ chosen = [f for f in sorted(fused.values(), key=lambda f: -f["rrf"])
+ if fresh(f) and (f["score"] >= min_score
+ or (f["lexical"] and f["score"] >= min_score_with_words))]
+ if not chosen and ranged:
+ # A date and a topic that matched nothing: what was said that day still answers.
+ chosen = ranged
+ for f in chosen:
+ f.pop("rrf", None)
+ f.pop("lexical", None)
+ return _with_pairs(conn, chosen[:k], model, seen)
+
+
+def _with_pairs(conn, found: List[dict], model: str, seen: Sequence[str] = ()) -> List[dict]:
+ """
+ Adds each result's `pair`, unless the caller already has it: a pair that is in the window
+ (or is the question) or that came back as a result of its own would enter the prompt twice.
+ """
+ chunks_found = {f["chunk"] for f in found}
+ for f in found:
+ pair = _pair(conn, f, model)
+ if pair and (pair["chunk"] in chunks_found or any(pair["chunk"] in s for s in seen)):
+ pair = None
+ f["pair"] = pair
+ f.pop("id", None)
+ return found
+
+
+def forget_conversation(conn: sqlite3.Connection, conversation: str) -> int:
+ """Removes every chunk of a conversation (and its full-text entries). Returns how many."""
+ if not table_exists(conn):
+ return 0
+ ensure_schema(conn)
+ n = conn.execute(f"DELETE FROM {TABLE} WHERE conversation = ?", (conversation,)).rowcount
+ conn.commit()
+ return n
+
+
+def missing_sources(conn: sqlite3.Connection, candidates: Sequence[int], model: str) -> List[int]:
+ """Which of `candidates` have no chunk for `model` yet (to backfill old messages)."""
+ ensure_schema(conn)
+ have = {r[0] for r in conn.execute(f"SELECT DISTINCT source_id FROM {TABLE} WHERE model = ?", (model,))}
+ return [c for c in candidates if c not in have]
+
+
+def table_exists(conn: sqlite3.Connection) -> bool:
+ return conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
+ (TABLE,)).fetchone() is not None
diff --git a/packages/python/src/orbit/text.py b/packages/python/src/orbit/text.py
new file mode 100644
index 0000000..36ce7fd
--- /dev/null
+++ b/packages/python/src/orbit/text.py
@@ -0,0 +1,115 @@
+"""
+Text helpers for memory: what is worth embedding, how to cut it, and which words carry meaning.
+
+Ported unchanged from Aimee (`talk/vectores_chat.py`, `talk/texto.py`), where every rule was
+measured: see the comments on each constant.
+"""
+import json
+import re
+import unicodedata
+from typing import List, Set
+
+#: Longest chunk. paraphrase-multilingual-MiniLM-L12-v2 truncates around 128 word pieces
+#: (~450 characters of Spanish): anything past that would not count for the vector.
+MAX_CHUNK = 450
+#: Shorter than this ("ok", "thanks") carries nothing worth finding later.
+MIN_CHUNK = 12
+
+_TAG = re.compile(r"<[^>]+>")
+_URL = re.compile(r"https?://\S+")
+_SENTENCE = re.compile(r"(?<=[.!?])\s+")
+
+#: Words that say nothing on their own and therefore never count as a match (es/en). Measured
+#: in Aimee: without it "gracias" matched "se estΓ‘ moviendo todo" through "todo".
+STOPWORDS = frozenset("""
+al algo ante aqui asi con como cual cuando de del desde donde el ella ello en es
+esa ese eso esta este esto estoy hasta hay la las le les lo los me mi mucho muy no
+nos para por porque que se ser sin sobre su sus todo una uno unos
+ya han hazle haz tengo hace mas pero cuanto cuanta cuantos cuantas dime dame
+necesito quiero puedes
+and for how the what
+""".split())
+#: Characters compared per word: a poor man's stemmer that pairs llamada/llamadas.
+STEM = 5
+#: Words shorter than this are ignored ("de", "un", "al").
+MIN_WORD = 3
+
+#: The conversational wrapper of a question about the past ("what did I tell you aboutβ¦",
+#: "ΒΏquΓ© te dije delβ¦"). It is not the topic and it dilutes the similarity: measured in Aimee,
+#: "ΒΏquΓ© te dije del proveedor de empaques?" scored 0.34 with it and 0.55 without it.
+_SAID = (r"(?:te dije|te hab[iΓ]a dicho|te cont[eΓ©]|te coment[eΓ©]|mencion[eΓ©]|me dijiste|me contaste|"
+ r"mencionaste|hablamos|dijimos|quedamos|"
+ r"anot[eΓ©]|anotamos|apunt[eΓ©]|apuntamos|"
+ r"i (?:told|said|mentioned|noted)|you (?:told|said|mentioned)|did i (?:tell|say|mention)|"
+ r"did you (?:tell|say|mention)|did we (?:talk|discuss|say|note)|we (?:talked|said|discussed|agreed|noted)|"
+ r"were we talking|wrote down|"
+ r"te disse|eu disse|voc[eΓͺ] (?:me )?disse|mencionei|mencionou|falamos|combinamos|anotamos)")
+_SAID_RE = re.compile(rf"\b{_SAID}\b", re.IGNORECASE)
+_WRAPPER = re.compile(rf"{_SAID}|^\s*ΒΏ?\s*(?:recuerdas|te acuerdas( de)?|do you remember|"
+ r"remember|(?:voc[eΓͺ] )?(?:se )?lembra( de)?)\b|\b(?:que|lo que|what|o que)\b",
+ re.IGNORECASE)
+
+
+def readable_text(message: str) -> str:
+ """
+ What a stored message says. A structured answer (a chart, a map) is stored as JSON:
+ its `summary`/`text` counts, never the raw figures. Tags and links are dropped.
+ """
+ text = (message or "").strip()
+ if text.startswith("{"):
+ try:
+ data = json.loads(text)
+ except ValueError:
+ data = None
+ if isinstance(data, dict):
+ text = str(data.get("summary") or data.get("text") or "")
+ text = _URL.sub(" ", _TAG.sub(" ", text))
+ return " ".join(text.split())
+
+
+def chunks(message: str) -> List[str]:
+ """Sentences grouped up to MAX_CHUNK; a longer sentence is cut by force."""
+ text = readable_text(message)
+ if len(text) < MIN_CHUNK:
+ return []
+ out, current = [], ""
+ for sentence in _SENTENCE.split(text):
+ while len(sentence) > MAX_CHUNK:
+ if current:
+ out.append(current)
+ current = ""
+ out.append(sentence[:MAX_CHUNK])
+ sentence = sentence[MAX_CHUNK:]
+ if current and len(current) + 1 + len(sentence) > MAX_CHUNK:
+ out.append(current)
+ current = sentence
+ else:
+ current = f"{current} {sentence}".strip()
+ if current:
+ out.append(current)
+ return [c for c in out if len(c) >= MIN_CHUNK]
+
+
+def without_accents(text: str) -> str:
+ decomposed = unicodedata.normalize("NFD", (text or "").lower())
+ return "".join(c for c in decomposed if unicodedata.category(c) != "Mn")
+
+
+def content_words(text: str) -> Set[str]:
+ """The words that actually say something, cut to their approximate stem."""
+ return {
+ w[:STEM]
+ for w in re.sub(r"[^a-z0-9\s+]", " ", without_accents(text)).split()
+ if w not in STOPWORDS and len(w) >= MIN_WORD
+ }
+
+
+def asks_what_was_said(question: str) -> bool:
+ """Is it about the conversation itself ("what did I tell you", "ΒΏde quΓ© hablamosβ¦")? Then a
+ date in it is *when it was said*; otherwise a date is part of the topic."""
+ return bool(_SAID_RE.search(question or ""))
+
+
+def strip_wrapper(question: str) -> str:
+ """The question without "what did I tell youβ¦": what is left is the topic."""
+ return " ".join(_WRAPPER.sub(" ", question or "").split()) or (question or "")
diff --git a/packages/python/src/sqlite_vector/_version.py b/packages/python/src/sqlite_vector/_version.py
deleted file mode 100644
index 99f716b..0000000
--- a/packages/python/src/sqlite_vector/_version.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import os
-
-__version__ = os.environ.get("PACKAGE_VERSION", "0.0.0")
\ No newline at end of file
diff --git a/packages/python/tests/test_facts.py b/packages/python/tests/test_facts.py
new file mode 100644
index 0000000..fd1eb3f
--- /dev/null
+++ b/packages/python/tests/test_facts.py
@@ -0,0 +1,145 @@
+"""
+orbit.facts: what Orbit knows about a person, across conversations.
+
+The model is fake (a function that returns canned JSON) and so are the embeddings: enough to
+pin the filter, the parsing, replacement by key, recall across conversations and forgetting.
+"""
+import json
+import sqlite3
+
+import pytest
+
+from orbit import facts, memory
+
+WORDS = ["boss", "laura", "peanuts", "allergic", "party", "terraza", "aurora", "budget"]
+MODEL = "fake"
+
+
+def fake_embed(texts):
+ return [[t.lower().count(w) + 1e-3 for w in WORDS] for t in texts]
+
+
+def llm_returning(*found):
+ calls = []
+
+ def llm(system, user):
+ calls.append(user)
+ return json.dumps({"facts": list(found)})
+ llm.calls = calls
+ return llm
+
+
+@pytest.fixture
+def conn(tmp_path):
+ c = sqlite3.connect(tmp_path / "person.db")
+ yield c
+ c.close()
+
+
+@pytest.mark.parametrize("text", [
+ "Mi jefa se llama Laura MΓ©ndez y prefiere los informes en PDF.",
+ "Al final la fiesta de fin de aΓ±o serΓ‘ en el restaurante La Terraza.",
+ "I'm allergic to peanuts, keep that in mind for the team lunch.",
+ "O responsΓ‘vel pela seguranΓ§a Γ© o Tiago Moreira.",
+ "El presupuesto de capacitaciΓ³n es de 25 millones.",
+])
+def test_statements_with_a_fact_pass_the_local_filter(text):
+ assert facts.might_hold_fact(text)
+
+
+@pytest.mark.parametrize("text", [
+ "hola", "Gracias por todo", "ΒΏcΓ³mo se llama mi jefa?", "what is my boss's name?",
+ "RevisΓ© el tablero con el equipo.", "dame el clima de maΓ±ana",
+])
+def test_questions_greetings_and_filler_never_reach_the_model(text):
+ assert not facts.might_hold_fact(text)
+
+
+def test_learn_calls_the_model_only_when_the_filter_lets_it(conn):
+ llm = llm_returning({"key": "boss.name", "statement": "The person's boss is Laura."})
+ assert facts.learn(conn, "hola", llm=llm, embed=fake_embed, model=MODEL) == []
+ assert llm.calls == []
+ facts.learn(conn, "My boss is Laura", llm=llm, embed=fake_embed, model=MODEL, conversation="c1")
+ assert len(llm.calls) == 1
+
+
+def test_the_model_sees_the_known_keys_to_reuse_them(conn):
+ facts.remember(conn, [{"key": "boss.name", "statement": "The person's boss is Laura."}],
+ embed=fake_embed, model=MODEL)
+ llm = llm_returning()
+ facts.learn(conn, "My new boss is Ana", llm=llm, embed=fake_embed, model=MODEL)
+ assert "boss.name: The person's boss is Laura." in llm.calls[0]
+
+
+def test_a_malformed_reply_is_dropped_not_raised():
+ assert facts.parse("no json here") == []
+ assert facts.parse('{"facts": [{"key": "Bad Key!", "statement": "x"}, {"key": "ok.key"}]}') == []
+ assert facts.parse('Sure: {"facts": [{"key": "Boss.Name", "statement": " Laura "}]}') == [
+ {"key": "boss.name", "statement": "Laura"}]
+
+
+def test_a_new_value_replaces_the_old_one(conn):
+ """The newest value is the one that counts: "al final, La Terraza" replaces "Aurora"."""
+ facts.remember(conn, [{"key": "year_end_party.venue", "statement": "The party is at Aurora."}],
+ embed=fake_embed, model=MODEL, ts="2026-11-24T09:00:00Z")
+ facts.remember(conn, [{"key": "year_end_party.venue", "statement": "The party moved to Terraza."}],
+ embed=fake_embed, model=MODEL, ts="2026-11-27T09:00:00Z")
+ found = facts.recall(conn, "where is the party?", embed=fake_embed, model=MODEL, min_score_with_words=0.0)
+ assert [f["statement"] for f in found] == ["The party moved to Terraza."]
+
+
+def test_a_reused_key_for_another_fact_does_not_erase_it(conn):
+ """MEASURED: the model gave "the packaging supplier" the key of "the shipping carrier"."""
+ facts.remember(conn, [{"key": "supplier", "statement": "The person is allergic to peanuts."}],
+ embed=fake_embed, model=MODEL)
+ facts.remember(conn, [{"key": "supplier", "statement": "The party is at Terraza."}],
+ embed=fake_embed, model=MODEL)
+ assert conn.execute(f"SELECT count(*) FROM {facts.TABLE} WHERE active = 1").fetchone()[0] == 2
+
+
+def test_facts_are_recalled_from_every_conversation(conn):
+ facts.remember(conn, [{"key": "allergy", "statement": "The person is allergic to peanuts."}],
+ embed=fake_embed, model=MODEL, conversation="work")
+ found = facts.recall(conn, "what am I allergic to?", embed=fake_embed, model=MODEL)
+ assert found and found[0]["conversation"] == "work"
+
+
+def test_nothing_comes_back_without_similarity_or_shared_words(conn):
+ facts.remember(conn, [{"key": "allergy", "statement": "The person is allergic to peanuts."}],
+ embed=fake_embed, model=MODEL)
+ assert facts.recall(conn, "what's the capital of Australia?", embed=fake_embed, model=MODEL) == []
+
+
+def test_forget_deletes_the_fact_every_version_and_its_chunks(conn):
+ """Β«Olvida lo de mi jefaΒ»: not recalled as a fact, nor as something said."""
+ memory.add(conn, source_id=7, conversation="c1", role="user", text="My boss is Laura and she is great",
+ embed=fake_embed, model=MODEL)
+ facts.remember(conn, [{"key": "boss.name", "statement": "The person's boss was Ana."}],
+ embed=fake_embed, model=MODEL, source_id=6)
+ facts.remember(conn, [{"key": "boss.name", "statement": "The person's boss is Laura."}],
+ embed=fake_embed, model=MODEL, source_id=7)
+ forgotten = facts.forget(conn, "my boss Laura", embed=fake_embed, model=MODEL)
+ assert forgotten == ["The person's boss is Laura."]
+ assert conn.execute(f"SELECT count(*) FROM {facts.TABLE}").fetchone()[0] == 0
+ assert memory.search(conn, "boss laura", embed=fake_embed, model=MODEL) == []
+
+
+def test_forget_also_drops_the_answer_that_repeated_it(conn):
+ memory.add(conn, source_id=7, conversation="c1", role="user", text="My boss is Laura and she is great",
+ embed=fake_embed, model=MODEL)
+ memory.add(conn, source_id=8, conversation="c1", role="assistant", text="Noted: your boss is Laura",
+ embed=fake_embed, model=MODEL)
+ memory.add(conn, source_id=9, conversation="c1", role="user", text="The budget is approved",
+ embed=fake_embed, model=MODEL)
+ facts.remember(conn, [{"key": "boss.name", "statement": "The person's boss is Laura."}],
+ embed=fake_embed, model=MODEL, source_id=7)
+ facts.forget(conn, "my boss Laura", embed=fake_embed, model=MODEL)
+ left = {r[0] for r in conn.execute(f"SELECT source_id FROM {memory.TABLE}")}
+ assert left == {9}
+
+
+def test_forget_without_a_match_forgets_nothing(conn):
+ facts.remember(conn, [{"key": "allergy", "statement": "The person is allergic to peanuts."}],
+ embed=fake_embed, model=MODEL)
+ assert facts.forget(conn, "the capital of Australia", embed=fake_embed, model=MODEL) == []
+ assert conn.execute(f"SELECT count(*) FROM {facts.TABLE}").fetchone()[0] == 1
diff --git a/packages/python/tests/test_memory.py b/packages/python/tests/test_memory.py
new file mode 100644
index 0000000..e9aeb31
--- /dev/null
+++ b/packages/python/tests/test_memory.py
@@ -0,0 +1,283 @@
+"""
+orbit.memory and orbit.text, against the real extension (build it first: `make extension`).
+
+The embedding model is fake on purpose: one dimension per known word. That is enough to pin
+chunking, filtering by conversation, the recall gate and forgetting, with no network or model.
+"""
+import sqlite3
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+import orbit
+from orbit import dates, memory, text
+
+WORDS = ["budget", "supplier", "weather", "rain", "invoice", "meeting"]
+MODEL = "fake"
+
+
+def fake_embed(texts):
+ """One dimension per known word, plus a little of everything (never a zero vector)."""
+ return [[t.lower().count(w) + 1e-3 for w in WORDS] for t in texts]
+
+
+@pytest.fixture
+def conn(tmp_path):
+ c = sqlite3.connect(tmp_path / "person.db")
+ yield c
+ c.close()
+
+
+@pytest.fixture
+def say(conn):
+ counter = iter(range(1, 10_000))
+
+ def _say(conversation, text_, role="user", ts="2026-11-30T10:00:00Z"):
+ return memory.add(conn, source_id=next(counter), conversation=conversation, role=role,
+ ts=ts, text=text_, embed=fake_embed, model=MODEL)
+ return _say
+
+
+def test_the_extension_loads():
+ c = sqlite3.connect(":memory:")
+ orbit.load(c)
+ orbit.load(c) # idempotent
+ assert c.execute("SELECT vector_version()").fetchone()[0]
+
+
+# ββ Text ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def test_a_long_message_is_several_chunks_none_over_the_limit():
+ """The model truncates near 128 tokens: past MAX_CHUNK nothing would count."""
+ long = " ".join(["This is a fairly normal test sentence."] * 40)
+ parts = text.chunks(long)
+ assert len(parts) > 1
+ assert all(len(p) <= text.MAX_CHUNK for p in parts)
+
+
+def test_a_structured_answer_counts_by_its_summary_not_its_json():
+ assert text.chunks('{"skill": "chart", "summary": "Monthly sales by supplier", '
+ '"options": {"series": [1, 2, 3]}}') == ["Monthly sales by supplier"]
+
+
+def test_short_text_tags_and_links_are_not_embedded():
+ assert text.chunks("ok") == []
+ assert text.chunks("https://media.giphy.com/x.gif") == []
+ assert text.chunks("hola ") == []
+
+
+def test_the_question_loses_its_wrapper():
+ """Measured in Aimee: the wrapper dropped the similarity from 0.55 to 0.34."""
+ topic = text.strip_wrapper("ΒΏquΓ© te dije del proveedor de empaques?")
+ assert "proveedor de empaques" in topic
+ assert "dije" not in topic
+
+
+# ββ Search βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def test_search_stays_in_the_requested_conversation(conn, say):
+ say("c1", "The budget for the supplier is 3,000")
+ say("c2", "The budget for the other supplier is higher")
+ say("c1", "Tomorrow there will be rain and bad weather")
+ found = memory.search(conn, "what was the budget?", embed=fake_embed, model=MODEL, conversation="c1")
+ assert {f["conversation"] for f in found} == {"c1"}
+ assert "budget" in found[0]["chunk"]
+
+
+def test_without_a_conversation_it_searches_all(conn, say):
+ say("c1", "Tomorrow there will be rain and bad weather")
+ say("c2", "The budget for the supplier is 3,000")
+ assert memory.search(conn, "budget", embed=fake_embed, model=MODEL, k=1)[0]["conversation"] == "c2"
+
+
+def test_vectors_of_another_model_are_never_mixed(conn, say):
+ say("c1", "The budget for the supplier is 3,000")
+ assert memory.search(conn, "budget", embed=fake_embed, model="other-model") == []
+
+
+def test_sources_can_be_excluded(conn, say):
+ say("c1", "The budget for the supplier is 3,000")
+ assert memory.search(conn, "budget", embed=fake_embed, model=MODEL, exclude_sources=(1,)) == []
+
+
+def test_role_and_time_come_back_with_the_chunk(conn, say):
+ say("c1", "The budget for the supplier is 3,000", role="assistant", ts="2026-11-29T09:00:00Z")
+ found = memory.search(conn, "budget", embed=fake_embed, model=MODEL)[0]
+ assert (found["role"], found["ts"]) == ("assistant", "2026-11-29T09:00:00Z")
+
+
+# ββ Recall βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def test_a_name_buried_in_a_long_conversation_is_found_by_full_text(conn, say):
+ """
+ Vectors alone rank a fact out of the top when many messages look alike; full text finds the
+ exact word. Here the fake model sees nothing of "Rodrigo" (not one of its words).
+ """
+ for i in range(30):
+ say("c1", f"The meeting about the budget number {i} went fine")
+ say("c1", "My shift partner is Rodrigo Salcedo")
+ found = memory.recall(conn, "who is Rodrigo?", embed=fake_embed, model=MODEL,
+ conversation="c1", min_score_with_words=0.0)
+ assert any("Rodrigo" in f["chunk"] for f in found)
+
+
+def test_without_a_full_text_match_it_needs_a_high_similarity(conn, say):
+ """Cosine alone did not separate (measured): below MIN_SCORE a full-text match is required."""
+ say("c1", "Tomorrow there will be rain")
+ found = memory.recall(conn, "weather forecast please", embed=fake_embed, model=MODEL,
+ min_score=1.01, min_score_with_words=0.0)
+ assert found == []
+
+
+def test_recall_skips_the_window_and_the_question_itself(conn, say):
+ """What is already in the prompt is not brought back, nor the message being answered."""
+ say("c1", "The budget for the supplier is 3,000")
+ say("c1", "The budget for the invoice is another one")
+ say("c1", "what was the budget for the supplier?")
+ found = memory.recall(conn, "what was the budget for the supplier?", embed=fake_embed,
+ model=MODEL, conversation="c1",
+ window=["The budget for the invoice is another one"])
+ chunks = [f["chunk"] for f in found]
+ assert "The budget for the supplier is 3,000" in chunks
+ assert "The budget for the invoice is another one" not in chunks
+ assert not any(c.startswith("what was") for c in chunks)
+
+
+def test_recall_on_an_empty_database_is_empty(conn):
+ assert memory.recall(conn, "anything", embed=fake_embed, model=MODEL) == []
+
+
+# ββ Dates ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+NOW = datetime(2026, 11, 30, 12, 0, tzinfo=timezone.utc) # a Monday
+
+
+@pytest.mark.parametrize("phrase,day", [
+ ("ΒΏde quΓ© hablamos ayer?", "2026-11-29"),
+ ("what did we talk about yesterday?", "2026-11-29"),
+ ("o que falamos ontem?", "2026-11-29"),
+ ("ΒΏquΓ© te dije el martes 25?", "2026-11-25"),
+ ("ΒΏquΓ© te contΓ© el 26 de noviembre?", "2026-11-26"),
+ ("what did I tell you on November 25th?", "2026-11-25"),
+ ("what did I tell you on the 26th?", "2026-11-26"),
+ ("o que eu te disse no dia 24?", "2026-11-24"),
+ ("ΒΏquΓ© anotamos el jueves?", "2026-11-26"),
+ ("ΒΏy anteayer?", "2026-11-28"),
+])
+def test_a_date_in_words_becomes_a_day(phrase, day):
+ start, end, _rest, _relative = dates.find_range(phrase, NOW)
+ assert start.date().isoformat() == day
+ assert end - start == timedelta(days=1)
+
+
+def test_a_date_is_never_in_the_future_unless_it_says_so():
+ """"el 15" on the 30th is the 15th of this month; "el 31" is last month's 31st."""
+ assert dates.find_range("ΒΏquΓ© te dije el dΓa 31?", NOW)[0].date().isoformat() == "2026-10-31"
+ assert dates.find_range("dame el clima de maΓ±ana", NOW)[0].date().isoformat() == "2026-12-01"
+
+
+def test_last_week_is_monday_to_sunday():
+ start, end, _rest, relative = dates.find_range("ΒΏquΓ© hablamos la semana pasada?", NOW)
+ assert (start.date().isoformat(), end.date().isoformat(), relative) == ("2026-11-23", "2026-11-30", True)
+
+
+def test_no_date_no_range():
+ assert dates.find_range("ΒΏcuΓ‘l era el presupuesto?", NOW) is None
+ assert dates.find_range("la segunda vez que lo pedΓ", NOW) is None # "segunda" is not Monday here
+
+
+def test_a_question_about_the_conversation_filters_by_the_day_it_was_said(conn, say):
+ say("c1", "The budget for the supplier is 3,000", ts="2026-11-25T10:00:00Z")
+ say("c1", "Tomorrow there will be rain", ts="2026-11-26T10:00:00Z")
+ found = memory.recall(conn, "what did we talk about on November 26th?", embed=fake_embed,
+ model=MODEL, conversation="c1", now=NOW)
+ assert [f["chunk"] for f in found] == ["Tomorrow there will be rain"]
+
+
+def test_a_date_that_is_the_topic_is_not_a_filter(conn, say):
+ """"ΒΏquΓ© pasa el 15 de diciembre?" asks about an event on that day, said on another one."""
+ say("c1", "The supplier audit is on December 15th", ts="2026-11-25T10:00:00Z")
+ found = memory.recall(conn, "what happens on December 15th?", embed=fake_embed, model=MODEL,
+ conversation="c1", now=NOW, min_score_with_words=0.0)
+ assert any("audit" in f["chunk"] for f in found)
+
+
+# ββ Pairs ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def test_each_recall_brings_the_other_half_of_its_exchange(conn, say):
+ say("c1", "How should I plan the budget?", role="user")
+ say("c1", "Split the budget by supplier and by month.", role="assistant")
+ found = memory.recall(conn, "what did you say about the supplier?", embed=fake_embed,
+ model=MODEL, conversation="c1", min_score_with_words=0.0)
+ assert [f["role"] for f in found] == ["assistant"]
+ answer = found[0]
+ assert answer["pair"] == {"role": "user", "chunk": "How should I plan the budget?"}
+
+
+def test_a_pair_the_caller_already_has_is_not_repeated(conn, say):
+ """Nothing enters the prompt twice: not a pair already in the window, nor one that is a result."""
+ say("c1", "How should I plan the budget?", role="user")
+ say("c1", "Split the budget by supplier and by month.", role="assistant")
+ in_window = memory.recall(conn, "what did you say about the budget by supplier?", embed=fake_embed,
+ model=MODEL, conversation="c1", min_score_with_words=0.0,
+ window=["How should I plan the budget?"])
+ assert all(f["pair"] is None for f in in_window)
+ both = memory.recall(conn, "budget", embed=fake_embed, model=MODEL, conversation="c1",
+ min_score_with_words=0.0)
+ assert len(both) == 2 and all(f["pair"] is None for f in both)
+
+
+# ββ Full-text index ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def test_chunks_stored_before_the_index_existed_get_indexed(conn, say):
+ say("c1", "My shift partner is Rodrigo Salcedo")
+ conn.execute(f"DROP TABLE {memory.FTS}")
+ memory.ensure_schema(conn)
+ rows = conn.execute(f"SELECT rowid FROM {memory.FTS} WHERE {memory.FTS} MATCH 'rodrigo'").fetchall()
+ assert len(rows) == 1
+
+
+# ββ Storage format βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def test_new_tables_store_half_precision(conn, say):
+ """FLOAT16 halves the database with the same recall (measured with orbit.eval)."""
+ say("c1", "The budget for the supplier is 3,000")
+ size = conn.execute(f"SELECT length(embedding) FROM {memory.TABLE}").fetchone()[0]
+ assert size == 2 * len(WORDS)
+
+
+def test_a_table_with_float32_vectors_keeps_working(conn):
+ """Chunks stored before FLOAT16 was the default keep their format: nothing to migrate."""
+ import struct
+ memory.ensure_schema(conn)
+ v = memory._unit(fake_embed(["The budget for the supplier is 3,000"])[0])
+ conn.execute(f"INSERT INTO {memory.TABLE} (source_id, conversation, role, ts, chunk, model, embedding) "
+ "VALUES (1, 'c1', 'user', '2026-11-30T10:00:00Z', 'The budget for the supplier is 3,000', ?, ?)",
+ (MODEL, struct.pack(f"<{len(v)}f", *v)))
+ memory.add(conn, source_id=2, conversation="c1", text="Tomorrow there will be rain",
+ embed=fake_embed, model=MODEL)
+ sizes = {r[0] for r in conn.execute(f"SELECT length(embedding) FROM {memory.TABLE}")}
+ assert sizes == {4 * len(WORDS)}
+ assert "budget" in memory.search(conn, "budget", embed=fake_embed, model=MODEL)[0]["chunk"]
+
+
+# ββ Forgetting βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+
+
+def test_a_forgotten_conversation_is_not_found(conn, say):
+ say("c1", "The budget for the supplier is 3,000")
+ say("c2", "The budget for the invoice is 50")
+ assert memory.forget_conversation(conn, "c1") == 1
+ assert {f["conversation"] for f in memory.search(conn, "budget", embed=fake_embed, model=MODEL)} == {"c2"}
+ assert conn.execute(f"SELECT count(*) FROM {memory.FTS} WHERE {memory.FTS} MATCH 'supplier'").fetchone()[0] == 0
+
+
+def test_missing_sources_lists_what_has_no_vector_yet(conn, say):
+ say("c1", "The budget for the supplier is 3,000") # source 1
+ assert memory.missing_sources(conn, [1, 2, 3], MODEL) == [2, 3]
diff --git a/src/distance-cpu.c b/src/distance-cpu.c
index 2916508..ba3cd92 100644
--- a/src/distance-cpu.c
+++ b/src/distance-cpu.c
@@ -186,10 +186,14 @@ static inline float bfloat16_distance_l2_impl_cpu (const void *v1, const void *v
float d0f = x0 - y0, d1f = x1 - y1, d2f = x2 - y2, d3f = x3 - y3;
// If any difference is NaN, ignore that lane (treat contribution as 0)
- if (isinf(d0f)) return INFINITY; if (!isnan(d0f)) LASSQ_UPDATE(fabs((double)d0f));
- if (isinf(d1f)) return INFINITY; if (!isnan(d1f)) LASSQ_UPDATE(fabs((double)d1f));
- if (isinf(d2f)) return INFINITY; if (!isnan(d2f)) LASSQ_UPDATE(fabs((double)d2f));
- if (isinf(d3f)) return INFINITY; if (!isnan(d3f)) LASSQ_UPDATE(fabs((double)d3f));
+ if (isinf(d0f)) return INFINITY;
+ if (!isnan(d0f)) LASSQ_UPDATE(fabs((double)d0f));
+ if (isinf(d1f)) return INFINITY;
+ if (!isnan(d1f)) LASSQ_UPDATE(fabs((double)d1f));
+ if (isinf(d2f)) return INFINITY;
+ if (!isnan(d2f)) LASSQ_UPDATE(fabs((double)d2f));
+ if (isinf(d3f)) return INFINITY;
+ if (!isnan(d3f)) LASSQ_UPDATE(fabs((double)d3f));
}
for (; i < n; ++i) {
diff --git a/src/sqlite-vector.c b/src/sqlite-vector.c
index 773b27d..dc3bc70 100644
--- a/src/sqlite-vector.c
+++ b/src/sqlite-vector.c
@@ -113,14 +113,24 @@ SQLITE_EXTENSION_INIT1
#define VECTOR_COLUMN_VECTOR 1
#define VECTOR_COLUMN_K 2
#define VECTOR_COLUMN_MEMIDX 3
-#define VECTOR_COLUMN_ROWID 4
-#define VECTOR_COLUMN_DISTANCE 5
+#define VECTOR_COLUMN_PART 4 // partition value (hidden)
+#define VECTOR_COLUMN_ROWID 5
+#define VECTOR_COLUMN_DISTANCE 6
+
+// idxNum flags chosen by xBestIndex and read back by xFilter: which hidden columns are
+// bound decides how argv is laid out, so it cannot be inferred from argc alone
+#define VECTOR_IDX_TOPK 1
+#define VECTOR_IDX_STREAM 2
+#define VECTOR_IDX_PART 4
+
+#define MAX_PARTITION_NAME 64
#define OPTION_KEY_TYPE "type"
#define OPTION_KEY_DIMENSION "dimension"
#define OPTION_KEY_NORMALIZED "normalized"
#define OPTION_KEY_MAXMEMORY "max_memory"
#define OPTION_KEY_DISTANCE "distance"
+#define OPTION_KEY_PARTITION "partition"
#define OPTION_KEY_QUANTTYPE "qtype"
#define OPTION_KEY_QUANTBITS "qbits"
#define OPTION_KEY_QUANTSCALE "qscale" // used only in serialize/unserialize
@@ -150,6 +160,8 @@ typedef struct {
vector_qtype q_type; // quantization type
int q_bits; // bit width for TurboQuant
uint64_t max_memory; // max memory
+
+ char partition[MAX_PARTITION_NAME]; // column a scan can be restricted to ("" = none)
} vector_options;
typedef struct {
@@ -214,6 +226,9 @@ typedef struct {
preload_index *preload_ref; // reference held while data points into it
} stream;
+ // partition value bound in WHERE part = ? (owned copy), NULL when the scan is unrestricted
+ sqlite3_value *partition;
+
// NON-STREAMING VT INTERFACE
int64_t *rowids;
double *distance;
@@ -541,9 +556,8 @@ static int sqlite_serialize (sqlite3_context *context, const char *table_name, c
return rc;
}
-static int sqlite_unserialize (sqlite3_context *context, table_context *ctx) {
+static int sqlite_unserialize (sqlite3 *db, table_context *ctx) {
const char *sql = "SELECT key, value FROM _sqliteai_vector WHERE tblname = ? AND colname = ?;";
- sqlite3 *db = sqlite3_context_db_handle(context);
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
@@ -840,7 +854,7 @@ static void quantize_binary (const float *input, uint8_t *output, int dim, bool
}
// quantize
- memset(output, 0, (dim + 7) / 8);
+ memset(output, 0, (size_t)(dim > 0 ? (dim + 7) / 8 : 0));
for (int i = 0; i < dim; i++) {
if (input[i] >= threshold) {
output[i / 8] |= (1 << (i % 8));
@@ -859,7 +873,7 @@ static void quantize_binary_f16 (const uint16_t *input, uint8_t *output, int dim
threshold = sum / dim;
}
- memset(output, 0, (dim + 7) / 8);
+ memset(output, 0, (size_t)(dim > 0 ? (dim + 7) / 8 : 0));
for (int i = 0; i < dim; i++) {
if (float16_to_float32(input[i]) >= threshold) {
output[i / 8] |= (1 << (i % 8));
@@ -878,7 +892,7 @@ static void quantize_binary_bf16 (const uint16_t *input, uint8_t *output, int di
threshold = sum / dim;
}
- memset(output, 0, (dim + 7) / 8);
+ memset(output, 0, (size_t)(dim > 0 ? (dim + 7) / 8 : 0));
for (int i = 0; i < dim; i++) {
if (bfloat16_to_float32(input[i]) >= threshold) {
output[i / 8] |= (1 << (i % 8));
@@ -888,7 +902,7 @@ static void quantize_binary_bf16 (const uint16_t *input, uint8_t *output, int di
static void quantize_binary_u8 (const uint8_t *input, uint8_t *output, int dim) {
// For unsigned 8-bit, threshold at 128 (midpoint)
- memset(output, 0, (dim + 7) / 8);
+ memset(output, 0, (size_t)(dim > 0 ? (dim + 7) / 8 : 0));
for (int i = 0; i < dim; i++) {
if (input[i] >= 128) {
output[i / 8] |= (1 << (i % 8));
@@ -898,7 +912,7 @@ static void quantize_binary_u8 (const uint8_t *input, uint8_t *output, int dim)
static void quantize_binary_i8 (const int8_t *input, uint8_t *output, int dim) {
// For signed 8-bit, threshold at 0 (sign-based)
- memset(output, 0, (dim + 7) / 8);
+ memset(output, 0, (size_t)(dim > 0 ? (dim + 7) / 8 : 0));
for (int i = 0; i < dim; i++) {
if (input[i] >= 0) {
output[i / 8] |= (1 << (i % 8));
@@ -1474,14 +1488,36 @@ static distance_function_t vector_lookup_distance_function (vector_distance dist
// For unit-length vectors cosine distance is exactly 1 - dot, so the two norm
// accumulators - two thirds of the arithmetic in the cosine kernels - drop out of the
// inner loop. The DOT kernels return the negated dot product, hence the addition.
-static float cosine_normalized_f32 (const void *v1, const void *v2, int n) {
- distance_function_t dot_fn = dispatch_distance_table[VECTOR_DISTANCE_DOT][VECTOR_TYPE_F32];
- float d = 1.0f + dot_fn(v1, v2, n);
+static inline float cosine_from_negated_dot (float negated_dot) {
+ float d = 1.0f + negated_dot;
if (d < 0.0f) return 0.0f;
if (d > 2.0f) return 2.0f;
return d;
}
+static float cosine_normalized_f32 (const void *v1, const void *v2, int n) {
+ return cosine_from_negated_dot(dispatch_distance_table[VECTOR_DISTANCE_DOT][VECTOR_TYPE_F32](v1, v2, n));
+}
+
+// The same shortcut for half precision: the DOT kernels for F16 and BF16 exist on every
+// backend, and storing unit vectors in 16 bits halves what a scan has to read.
+static float cosine_normalized_f16 (const void *v1, const void *v2, int n) {
+ return cosine_from_negated_dot(dispatch_distance_table[VECTOR_DISTANCE_DOT][VECTOR_TYPE_F16](v1, v2, n));
+}
+
+static float cosine_normalized_bf16 (const void *v1, const void *v2, int n) {
+ return cosine_from_negated_dot(dispatch_distance_table[VECTOR_DISTANCE_DOT][VECTOR_TYPE_BF16](v1, v2, n));
+}
+
+static distance_function_t cosine_normalized_for (vector_type type) {
+ switch (type) {
+ case VECTOR_TYPE_F32: return cosine_normalized_f32;
+ case VECTOR_TYPE_F16: return cosine_normalized_f16;
+ case VECTOR_TYPE_BF16: return cosine_normalized_bf16;
+ default: return NULL;
+ }
+}
+
// The stored vectors are unit length only because the caller said so with normalized=1,
// and only in full precision: the quantized index holds scaled integers whose norm is
// whatever the scale made it, so the shortcut is not valid there. The query is normalized
@@ -1491,8 +1527,9 @@ static bool vector_use_normalized_cosine (const table_context *t_ctx, bool quant
if (quantized) return false;
if (!t_ctx->options.v_normalized) return false;
if (t_ctx->options.v_distance != VECTOR_DISTANCE_COSINE) return false;
- if (t_ctx->options.v_type != VECTOR_TYPE_F32) return false;
- return (dispatch_distance_table[VECTOR_DISTANCE_DOT][VECTOR_TYPE_F32] != NULL);
+ vector_type type = t_ctx->options.v_type;
+ if (type != VECTOR_TYPE_F32 && type != VECTOR_TYPE_F16 && type != VECTOR_TYPE_BF16) return false;
+ return (dispatch_distance_table[VECTOR_DISTANCE_DOT][type] != NULL);
}
#if DEBUG_VECTOR_SERIALIZATION
@@ -1696,6 +1733,19 @@ bool vector_keyvalue_callback (sqlite3_context *context, void *xdata, const char
return true;
}
+ if (KEY_MATCH(OPTION_KEY_PARTITION)) {
+ // an identifier, not SQL: it is spliced into the scan's SELECT (quoted with %w),
+ // so anything but letters, digits and underscores is refused outright
+ size_t n = strlen(buffer);
+ if (n == 0 || n >= MAX_PARTITION_NAME) return context_result_error(context, SQLITE_ERROR, "Invalid partition column: expected a column name of 1 to %d characters", MAX_PARTITION_NAME - 1);
+ for (size_t i = 0; i < n; ++i) {
+ unsigned char ch = (unsigned char)buffer[i];
+ if (!(isalnum(ch) || ch == '_')) return context_result_error(context, SQLITE_ERROR, "Invalid partition column: '%s' must contain only letters, digits and underscores", buffer);
+ }
+ memcpy(options->partition, buffer, n + 1);
+ return true;
+ }
+
// means ignore unknown keys
return true;
}
@@ -1747,6 +1797,9 @@ static char *generate_quant_table_name (const char *table_name, const char *colu
// MARK: - Vector Context and Options -
+void vector_options_init (vector_options *options);
+table_context *vector_context_lookup (vector_context *ctx, const char *table_name, const char *column_name);
+
void *vector_context_create (void) {
vector_context *ctx = (vector_context *)sqlite3_malloc(sizeof(vector_context));
if (!ctx) return NULL;
@@ -1781,33 +1834,35 @@ table_context *vector_context_lookup (vector_context *ctx, const char *table_nam
return NULL;
}
-void vector_context_add (sqlite3_context *context, vector_context *ctx, const char *table_name, const char *column_name, vector_options *options) {
+// Registers a table in this connection's context. Errors go to `err`: it is called both
+// from vector_init (a function, with a sqlite3_context) and from a scan (a virtual table).
+static int vector_context_add_db (sqlite3 *db, vector_context *ctx, const char *table_name, const char *column_name, vector_options *options, char *err, int errlen) {
// check if there is a free slot
if (ctx->table_count >= MAX_TABLES) {
- context_result_error(context, SQLITE_ERROR, "Cannot add table: maximum number of allowed tables reached (%d)", MAX_TABLES);
- return;
+ sqlite3_snprintf(errlen, err, "Cannot add table: maximum number of allowed tables reached (%d)", MAX_TABLES);
+ return SQLITE_ERROR;
}
char *t_name = sqlite_strdup(table_name);
char *c_name = sqlite_strdup(column_name);
if (!t_name || !c_name) {
- context_result_error(context, SQLITE_NOMEM, "Out of memory: unable to duplicate table or column name");
+ sqlite3_snprintf(errlen, err, "Out of memory: unable to duplicate table or column name");
if (t_name) sqlite3_free(t_name);
if (c_name) sqlite3_free(c_name);
- return;
+ return SQLITE_NOMEM;
}
char *prikey = NULL;
- sqlite3 *db = sqlite3_context_db_handle(context);
bool is_without_rowid = sqlite_table_is_without_rowid(db, table_name);
prikey = (is_without_rowid == false) ? sqlite_strdup("rowid") : sqlite_get_int_prikey_column(db, table_name);
// sanity check primary key
if (!prikey) {
- (is_without_rowid) ? context_result_error(context, SQLITE_ERROR, "WITHOUT ROWID table '%s' must have exactly one PRIMARY KEY column of type INTEGER", table_name) : context_result_error(context, SQLITE_NOMEM, "Out of memory: unable to duplicate rowid column name");
+ if (is_without_rowid) sqlite3_snprintf(errlen, err, "WITHOUT ROWID table '%s' must have exactly one PRIMARY KEY column of type INTEGER", table_name);
+ else sqlite3_snprintf(errlen, err, "Out of memory: unable to duplicate rowid column name");
sqlite3_free(t_name);
sqlite3_free(c_name);
- return;
+ return is_without_rowid ? SQLITE_ERROR : SQLITE_NOMEM;
}
int index = ctx->table_count;
@@ -1817,18 +1872,103 @@ void vector_context_add (sqlite3_context *context, vector_context *ctx, const ch
ctx->tables[index].options = *options;
ctx->table_count++;
- int rc = sqlite_unserialize(context, &ctx->tables[index]);
+ int rc = sqlite_unserialize(db, &ctx->tables[index]);
if (rc != SQLITE_OK) {
- context_result_error(context, rc, "Unable to load vector metadata for '%s.%s'", table_name, column_name);
- return;
+ sqlite3_snprintf(errlen, err, "Unable to load vector metadata for '%s.%s'", table_name, column_name);
+ return rc;
}
if (ctx->tables[index].options.q_type == VECTOR_QUANT_TURBO) {
int bits = ctx->tables[index].options.q_bits;
int dim = ctx->tables[index].options.v_dim;
rc = table_context_ensure_turbo_codebook(&ctx->tables[index], bits, dim);
if (rc == SQLITE_OK) rc = table_context_ensure_turbo_plan(&ctx->tables[index], dim);
- if (rc != SQLITE_OK) context_result_error(context, rc, "Unable to initialize TurboQuant cache for '%s.%s'", table_name, column_name);
+ if (rc != SQLITE_OK) {
+ sqlite3_snprintf(errlen, err, "Unable to initialize TurboQuant cache for '%s.%s'", table_name, column_name);
+ return rc;
+ }
}
+ return SQLITE_OK;
+}
+
+void vector_context_add (sqlite3_context *context, vector_context *ctx, const char *table_name, const char *column_name, vector_options *options) {
+ char err[512] = {0};
+ int rc = vector_context_add_db(sqlite3_context_db_handle(context), ctx, table_name, column_name, options, err, (int)sizeof(err));
+ if (rc != SQLITE_OK) context_result_error(context, rc, "%s", err);
+}
+
+// The column options vector_init was given, as persisted in _sqliteai_vector. True only
+// when the two mandatory ones (type and dimension) are there.
+static bool vector_load_options (sqlite3 *db, const char *table_name, const char *column_name, vector_options *options) {
+ const char *sql = "SELECT key, value FROM _sqliteai_vector WHERE tblname = ? AND colname = ?;";
+ sqlite3_stmt *vm = NULL;
+ bool has_type = false, has_dim = false;
+ if (sqlite3_prepare_v2(db, sql, -1, &vm, NULL) != SQLITE_OK) return false;
+ sqlite3_bind_text(vm, 1, table_name, -1, SQLITE_STATIC);
+ sqlite3_bind_text(vm, 2, column_name, -1, SQLITE_STATIC);
+ while (sqlite3_step(vm) == SQLITE_ROW) {
+ const char *key = (const char *)sqlite3_column_text(vm, 0);
+ if (!key) continue;
+ if (strcmp(key, OPTION_KEY_TYPE) == 0) { options->v_type = (vector_type)sqlite3_column_int(vm, 1); has_type = true; }
+ else if (strcmp(key, OPTION_KEY_DIMENSION) == 0) { options->v_dim = sqlite3_column_int(vm, 1); has_dim = true; }
+ else if (strcmp(key, OPTION_KEY_DISTANCE) == 0) options->v_distance = (vector_distance)sqlite3_column_int(vm, 1);
+ else if (strcmp(key, OPTION_KEY_NORMALIZED) == 0) options->v_normalized = (sqlite3_column_int(vm, 1) != 0);
+ else if (strcmp(key, OPTION_KEY_PARTITION) == 0) {
+ const char *part = (const char *)sqlite3_column_text(vm, 1);
+ size_t n = part ? strlen(part) : 0;
+ if (n < MAX_PARTITION_NAME) memcpy(options->partition, part ? part : "", n + 1);
+ }
+ }
+ sqlite3_finalize(vm);
+ // a persisted row is ordinary writable data: refuse what vector_init would refuse
+ if (has_type && (vector_type_to_size(options->v_type) < 0 || options->v_type == 0)) return false;
+ if (has_dim && (options->v_dim <= 0 || options->v_dim > MAX_VECTOR_DIMENSION)) return false;
+ if (options->v_distance <= 0 || options->v_distance >= VECTOR_DISTANCE_MAX) return false;
+ return has_type && has_dim;
+}
+
+// Persists the options so other connections can scan without calling vector_init. Best
+// effort, and only when something changed: vector_init runs on every new connection and
+// must not turn each of them into a write.
+static void vector_persist_options (sqlite3 *db, const char *table_name, const char *column_name, const vector_options *options) {
+ vector_options stored;
+ vector_options_init(&stored);
+ if (vector_load_options(db, table_name, column_name, &stored) &&
+ stored.v_type == options->v_type && stored.v_dim == options->v_dim &&
+ stored.v_distance == options->v_distance && stored.v_normalized == options->v_normalized &&
+ strcmp(stored.partition, options->partition) == 0) return;
+
+ const char *sql = "REPLACE INTO _sqliteai_vector (tblname, colname, key, value) VALUES (?1, ?2, ?3, ?4);";
+ sqlite3_stmt *vm = NULL;
+ if (sqlite3_prepare_v2(db, sql, -1, &vm, NULL) != SQLITE_OK) return;
+ const char *keys[] = {OPTION_KEY_TYPE, OPTION_KEY_DIMENSION, OPTION_KEY_DISTANCE, OPTION_KEY_NORMALIZED, OPTION_KEY_PARTITION};
+ for (int i = 0; i < 5; ++i) {
+ sqlite3_bind_text(vm, 1, table_name, -1, SQLITE_STATIC);
+ sqlite3_bind_text(vm, 2, column_name, -1, SQLITE_STATIC);
+ sqlite3_bind_text(vm, 3, keys[i], -1, SQLITE_STATIC);
+ switch (i) {
+ case 0: sqlite3_bind_int(vm, 4, (int)options->v_type); break;
+ case 1: sqlite3_bind_int(vm, 4, options->v_dim); break;
+ case 2: sqlite3_bind_int(vm, 4, (int)options->v_distance); break;
+ case 3: sqlite3_bind_int(vm, 4, options->v_normalized ? 1 : 0); break;
+ case 4: sqlite3_bind_text(vm, 4, options->partition, -1, SQLITE_STATIC); break;
+ }
+ if (sqlite3_step(vm) != SQLITE_DONE) break;
+ sqlite3_reset(vm);
+ }
+ sqlite3_finalize(vm);
+}
+
+// A scan on a table this connection never initialized: register it from the persisted
+// options. SQLITE_OK with *out NULL means there was nothing persisted (not an error).
+static int vector_context_autoload (sqlite3 *db, vector_context *ctx, const char *table_name, const char *column_name, table_context **out, char *err, int errlen) {
+ *out = NULL;
+ vector_options options;
+ vector_options_init(&options);
+ if (!vector_load_options(db, table_name, column_name, &options)) return SQLITE_OK;
+ if (!sqlite_table_exists(db, table_name) || !sqlite_column_exists(db, table_name, column_name)) return SQLITE_OK;
+ int rc = vector_context_add_db(db, ctx, table_name, column_name, &options, err, errlen);
+ if (rc == SQLITE_OK) *out = vector_context_lookup(ctx, table_name, column_name);
+ return rc;
}
void vector_options_init (vector_options *options) {
@@ -2128,7 +2268,7 @@ static int vector_rebuild_quantization (sqlite3_context *context, const char *ta
VECTOR_PRINT((void *)data, qprint, dim);
#endif
- data += (qtype == VECTOR_QUANT_TURBO) ? turbo_bytes_for_dim(dim, q_bits) : ((qtype == VECTOR_QUANT_1BIT) ? ((dim + 7) / 8) : (dim * sizeof(uint8_t)));
+ data += (qtype == VECTOR_QUANT_TURBO) ? turbo_bytes_for_dim(dim, q_bits) : ((qtype == VECTOR_QUANT_1BIT) ? (size_t)((dim + 7) / 8) : (size_t)dim * sizeof(uint8_t));
max_rowid = rowid;
++n_processed;
++tot_processed;
@@ -2715,12 +2855,22 @@ static int vCursorFilterCommon (sqlite3_vtab_cursor *cur, int idxNum, const char
c->stream.preload_ref = NULL;
}
memset(&c->stream, 0, sizeof(c->stream));
+ if (c->partition) {
+ sqlite3_value_free(c->partition);
+ c->partition = NULL;
+ }
- if (argc != 3 && argc != 4) {
- return sqlite_vtab_set_error(&vtab->base, "%s expects 3 or 4 arguments, but %d were provided", fname, argc);
+ // idxNum says which hidden columns xBestIndex bound; 0 comes from builds that predate
+ // the flags, where argc alone decided (3 = streaming, 4 = top-k)
+ bool has_topk = (idxNum == 0) ? (argc == 4) : ((idxNum & VECTOR_IDX_TOPK) != 0);
+ bool has_part = (idxNum & VECTOR_IDX_PART) != 0;
+ int expected_argc = 3 + (has_topk ? 1 : 0) + (has_part ? 1 : 0);
+ if (argc != expected_argc) {
+ return sqlite_vtab_set_error(&vtab->base, "%s expects %d arguments, but %d were provided", fname, expected_argc, argc);
}
+ int part_index = has_topk ? 4 : 3;
- bool is_streaming = (argc == 3);
+ bool is_streaming = !has_topk;
bool is_quantized = quantized;
c->is_streaming = is_streaming;
c->is_quantized = is_quantized;
@@ -2739,7 +2889,7 @@ static int vCursorFilterCommon (sqlite3_vtab_cursor *cur, int idxNum, const char
return sqlite_vtab_set_error(&vtab->base, "%s: argument %d must be of type TEXT or BLOB (got %s)", fname, (i+1), sqlite_type_name(actual_type));
break;
case 3:
- if (actual_type != SQLITE_INTEGER)
+ if (has_topk && actual_type != SQLITE_INTEGER)
return sqlite_vtab_set_error(&vtab->base, "%s: argument %d must be of type INTEGER (got %s)", fname, (i+1), sqlite_type_name(actual_type));
break;
}
@@ -2749,9 +2899,27 @@ static int vCursorFilterCommon (sqlite3_vtab_cursor *cur, int idxNum, const char
const char *table_name = (const char *)sqlite3_value_text(argv[0]);
const char *column_name = (const char *)sqlite3_value_text(argv[1]);
table_context *t_ctx = vector_context_lookup(vtab->ctx, table_name, column_name);
+ if (!t_ctx) {
+ // not initialized in this connection: if vector_init ran once on this database its
+ // options were persisted, and the scan can register the table on its own
+ char err[256] = {0};
+ int arc = vector_context_autoload(vtab->db, vtab->ctx, table_name, column_name, &t_ctx, err, (int)sizeof(err));
+ if (arc != SQLITE_OK) return sqlite_vtab_set_error(&vtab->base, "%s: %s", fname, err);
+ }
if (!t_ctx) {
return sqlite_vtab_set_error(&vtab->base, "%s: unable to retrieve context", fname);
}
+
+ if (has_part) {
+ if (quantized) {
+ return sqlite_vtab_set_error(&vtab->base, "%s: a partition can only restrict vector_full_scan, not a quantized scan", fname);
+ }
+ if (t_ctx->options.partition[0] == 0) {
+ return sqlite_vtab_set_error(&vtab->base, "%s: '%s.%s' has no partition column: declare it with partition= in vector_init", fname, table_name, column_name);
+ }
+ c->partition = sqlite3_value_dup(argv[part_index]);
+ if (!c->partition) return SQLITE_NOMEM;
+ }
const void *vector = NULL;
bool vector_allocated = false;
@@ -2789,16 +2957,36 @@ static int vCursorFilterCommon (sqlite3_vtab_cursor *cur, int idxNum, const char
// once per scan costs one pass over a single vector
if (vector_use_normalized_cosine(t_ctx, quantized)) {
int dim = t_ctx->options.v_dim;
- float *qn = (float *)sqlite_memdup(vector, vsize);
+ vector_type vt = t_ctx->options.v_type;
+ void *qn = sqlite_memdup(vector, vsize);
if (!qn) {
if (vector_allocated) sqlite3_free((void *)vector);
return SQLITE_NOMEM;
}
- double norm_sq = 0.0;
- for (int i = 0; i < dim; ++i) norm_sq += (double)qn[i] * (double)qn[i];
- if (norm_sq > 0.0) {
- float inv = (float)(1.0 / sqrt(norm_sq));
- for (int i = 0; i < dim; ++i) qn[i] *= inv;
+ if (vt == VECTOR_TYPE_F32) {
+ float *q = (float *)qn;
+ double norm_sq = 0.0;
+ for (int i = 0; i < dim; ++i) norm_sq += (double)q[i] * (double)q[i];
+ if (norm_sq > 0.0) {
+ float inv = (float)(1.0 / sqrt(norm_sq));
+ for (int i = 0; i < dim; ++i) q[i] *= inv;
+ }
+ } else {
+ // half precision: normalize in float and store back in the column's format
+ uint16_t *q = (uint16_t *)qn;
+ bool is_f16 = (vt == VECTOR_TYPE_F16);
+ double norm_sq = 0.0;
+ for (int i = 0; i < dim; ++i) {
+ double x = is_f16 ? float16_to_float32(q[i]) : bfloat16_to_float32(q[i]);
+ norm_sq += x * x;
+ }
+ if (norm_sq > 0.0) {
+ double inv = 1.0 / sqrt(norm_sq);
+ for (int i = 0; i < dim; ++i) {
+ float x = (float)((is_f16 ? float16_to_float32(q[i]) : bfloat16_to_float32(q[i])) * inv);
+ q[i] = is_f16 ? float32_to_float16(x) : float32_to_bfloat16(x);
+ }
+ }
}
if (vector_allocated) sqlite3_free((void *)vector);
vector = qn;
@@ -2872,7 +3060,7 @@ static int vCursorFilterCommon (sqlite3_vtab_cursor *cur, int idxNum, const char
static int vFullScanConnect (sqlite3 *db, void *pAux, int argc, const char *const *argv, sqlite3_vtab **ppVtab, char **pzErr) {
// https://www.sqlite.org/vtab.html#table_valued_functions
- int rc = sqlite3_declare_vtab(db, "CREATE TABLE x(tbl hidden, vector hidden, k hidden, memidx hidden, id, distance);");
+ int rc = sqlite3_declare_vtab(db, "CREATE TABLE x(tbl hidden, vector hidden, k hidden, memidx hidden, part hidden, id, distance);");
if (rc != SQLITE_OK) return rc;
vFullScan *vtab = (vFullScan *)sqlite3_malloc(sizeof(vFullScan));
@@ -2893,56 +3081,63 @@ static int vFullScanDisconnect (sqlite3_vtab *pVtab) {
}
static int vFullScanBestIndex (sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo) {
- // With positional args to the table-valued function:
- // 3 args: f('tbl','col',vector) β columns 0,1,2 constrained (streaming)
- // 4 args: f('tbl','col',vector,k) β columns 0,1,2,3 constrained (top-k)
- // Column 2 (K) always receives the vector blob (positional arg 2).
- // Column 3 (MEMIDX) receives the actual k integer only with 4 args.
- // So top-k mode is determined by whether MEMIDX is constrained, not K.
- bool has_topk = false;
+ // Positional args to the table-valued function bind the hidden columns in order:
+ // f('tbl','col',vector) β columns 0,1,2 (streaming)
+ // f('tbl','col',vector,k) β columns 0,1,2,3 (top-k)
+ // f('tbl','col',vector,k,partition) β columns 0,1,2,3,4 (top-k in one partition)
+ // and WHERE s.part = ? binds column 4 without k (streaming in one partition).
+ // Column 2 (K) always receives the vector blob; column 3 (MEMIDX) the k integer.
+ // argvIndex has to be contiguous, so it is assigned in column order over the columns
+ // actually bound, and idxNum records which ones were, for xFilter to lay argv out.
+ int slot[VECTOR_COLUMN_PART + 1];
+ for (int i = 0; i <= VECTOR_COLUMN_PART; ++i) slot[i] = -1;
+ bool required_unusable = false;
const struct sqlite3_index_constraint *pConstraint = pIdxInfo->aConstraint;
- for(int i=0; inConstraint; i++, pConstraint++){
- if( pConstraint->usable == 0 ) continue;
- if( pConstraint->op != SQLITE_INDEX_CONSTRAINT_EQ ) continue;
- switch( pConstraint->iColumn ){
- case VECTOR_COLUMN_IDX:
- pIdxInfo->aConstraintUsage[i].argvIndex = 1;
- pIdxInfo->aConstraintUsage[i].omit = 1;
- break;
- case VECTOR_COLUMN_VECTOR:
- pIdxInfo->aConstraintUsage[i].argvIndex = 2;
- pIdxInfo->aConstraintUsage[i].omit = 1;
- break;
- case VECTOR_COLUMN_K:
- pIdxInfo->aConstraintUsage[i].argvIndex = 3;
- pIdxInfo->aConstraintUsage[i].omit = 1;
- break;
- case VECTOR_COLUMN_MEMIDX:
- has_topk = true;
- pIdxInfo->aConstraintUsage[i].argvIndex = 4;
- pIdxInfo->aConstraintUsage[i].omit = 1;
- break;
+ for (int i = 0; i < pIdxInfo->nConstraint; i++, pConstraint++) {
+ if (pConstraint->op != SQLITE_INDEX_CONSTRAINT_EQ) continue;
+ int col = pConstraint->iColumn;
+ if (col < VECTOR_COLUMN_IDX || col > VECTOR_COLUMN_PART) continue;
+ if (pConstraint->usable == 0) {
+ if (col <= VECTOR_COLUMN_K) required_unusable = true;
+ continue;
}
+ if (slot[col] < 0) slot[col] = i;
+ }
+ // a join order where the function's own arguments are not available yet is not a
+ // plan, it is an error waiting in xFilter: ask SQLite for another one
+ if (required_unusable && (slot[VECTOR_COLUMN_IDX] < 0 || slot[VECTOR_COLUMN_VECTOR] < 0 || slot[VECTOR_COLUMN_K] < 0)) {
+ return SQLITE_CONSTRAINT;
}
+ int argv_index = 0;
+ for (int col = VECTOR_COLUMN_IDX; col <= VECTOR_COLUMN_PART; ++col) {
+ if (slot[col] < 0) continue;
+ pIdxInfo->aConstraintUsage[slot[col]].argvIndex = ++argv_index;
+ pIdxInfo->aConstraintUsage[slot[col]].omit = 1;
+ }
+
+ bool has_topk = (slot[VECTOR_COLUMN_MEMIDX] >= 0);
+ bool has_part = (slot[VECTOR_COLUMN_PART] >= 0);
+
if (has_topk) {
- // top-k mode: 4 positional args, argv[3] has the k integer
- pIdxInfo->estimatedCost = (double)1;
+ // top-k mode: argv[3] has the k integer
+ pIdxInfo->estimatedCost = has_part ? 0.5 : 1.0;
pIdxInfo->estimatedRows = 100;
- pIdxInfo->idxNum = 1;
-
+ pIdxInfo->idxNum = VECTOR_IDX_TOPK;
+
// rows are emitted in ascending distance order, so that is the only ORDER BY we
// may claim: telling SQLite otherwise makes it drop a sorter we do not replace
pIdxInfo->orderByConsumed = (pIdxInfo->nOrderBy == 1 &&
pIdxInfo->aOrderBy[0].iColumn == VECTOR_COLUMN_DISTANCE &&
pIdxInfo->aOrderBy[0].desc == 0);
} else {
- // streaming mode: 3 positional args, no sorting guaranteed
- pIdxInfo->estimatedCost = 1e8;
- pIdxInfo->estimatedRows = 100000;
- pIdxInfo->idxNum = 2;
+ // streaming mode: no sorting guaranteed; a partition reads only its own rows
+ pIdxInfo->estimatedCost = has_part ? 1e6 : 1e8;
+ pIdxInfo->estimatedRows = has_part ? 1000 : 100000;
+ pIdxInfo->idxNum = VECTOR_IDX_STREAM;
}
+ if (has_part) pIdxInfo->idxNum |= VECTOR_IDX_PART;
return SQLITE_OK;
}
@@ -2965,6 +3160,7 @@ static int vFullScanCursorClose (sqlite3_vtab_cursor *cur){
if (c->stream.turbo_norm_lut) sqlite3_free(c->stream.turbo_norm_lut);
if (c->stream.vm) sqlite3_finalize(c->stream.vm);
preload_index_release(c->stream.preload_ref);
+ if (c->partition) sqlite3_value_free(c->partition);
sqlite3_free(c);
return SQLITE_OK;
}
@@ -3253,12 +3449,19 @@ static int vFullScanRun (sqlite3 *db, vFullScanCursor *c, const void *v1, int v1
const char *table_name = c->table->t_name;
int dimension = c->table->options.v_dim;
- char *sql = sqlite3_mprintf("SELECT \"%w\", \"%w\" FROM \"%w\";", pk_name, col_name, table_name);
+ // with a partition, the indexed WHERE reads only that partition's rows
+ char *sql = (c->partition)
+ ? sqlite3_mprintf("SELECT \"%w\", \"%w\" FROM \"%w\" WHERE \"%w\" = ?1;", pk_name, col_name, table_name, c->table->options.partition)
+ : sqlite3_mprintf("SELECT \"%w\", \"%w\" FROM \"%w\";", pk_name, col_name, table_name);
if (!sql) return SQLITE_NOMEM;
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto cleanup;
+ if (c->partition) {
+ rc = sqlite3_bind_value(vm, 1, c->partition);
+ if (rc != SQLITE_OK) goto cleanup;
+ }
// compute distance function
vector_distance vd = c->table->options.v_distance;
@@ -3269,7 +3472,7 @@ static int vFullScanRun (sqlite3 *db, vFullScanCursor *c, const void *v1, int v1
rc = sqlite_vtab_set_error(c->base.pVtab, "Distance '%s' is not supported for vector type '%s'", vector_distance_to_name(vd), vector_type_to_name(vt));
goto cleanup;
}
- if (vector_use_normalized_cosine(c->table, false)) distance_fn = cosine_normalized_f32;
+ if (vector_use_normalized_cosine(c->table, false)) distance_fn = cosine_normalized_for(c->table->options.v_type);
int dist_size = (vt == VECTOR_TYPE_BIT) ? ((dimension + 7) / 8) : dimension;
size_t expected_bytes = vector_bytes_for_dim(vt, dimension);
@@ -3307,7 +3510,7 @@ static int vQuantRunMemory(vFullScanCursor *c, const preload_index *idx, uint8_t
const int counter = idx->counter;
const uint8_t *data = idx->data;
const size_t rowid_size = sizeof(int64_t);
- const size_t vector_size = (qtype == VECTOR_QUANT_1BIT) ? ((dim + 7) / 8) : (dim * sizeof(uint8_t));
+ const size_t vector_size = (qtype == VECTOR_QUANT_1BIT) ? (size_t)((dim + 7) / 8) : (size_t)dim * sizeof(uint8_t);
const size_t total_stride = rowid_size + vector_size;
// the preloaded index is built from an ordinary writable table, so never trust its
@@ -3493,7 +3696,7 @@ static int vQuantRun (sqlite3 *db, vFullScanCursor *c, const void *v1, int v1siz
// quantize target vector
int dimension = c->table->options.v_dim;
vector_qtype qtype = c->table->options.q_type;
- size_t alloc_size = (qtype == VECTOR_QUANT_1BIT) ? ((dimension + 7) / 8) : (dimension * sizeof(int8_t));
+ size_t alloc_size = (qtype == VECTOR_QUANT_1BIT) ? (size_t)((dimension + 7) / 8) : (size_t)dimension * sizeof(int8_t);
uint8_t *v = (uint8_t *)sqlite3_malloc64(alloc_size);
if (!v) return SQLITE_NOMEM;
@@ -3544,7 +3747,7 @@ static int vQuantRun (sqlite3 *db, vFullScanCursor *c, const void *v1, int v1siz
// precompute constants
const size_t rowid_size = sizeof(int64_t);
- const size_t vector_size = (qtype == VECTOR_QUANT_1BIT) ? ((dimension + 7) / 8) : (dimension * sizeof(uint8_t));
+ const size_t vector_size = (qtype == VECTOR_QUANT_1BIT) ? (size_t)((dimension + 7) / 8) : (size_t)dimension * sizeof(uint8_t);
const size_t total_stride = rowid_size + vector_size;
// compute distance function
@@ -3625,7 +3828,9 @@ static int vStreamScanCursorRun (sqlite3 *db, vFullScanCursor *c, const void *v1
c->stream.vsize = v1size;
c->stream.vdim = dimension;
- char *sql = sqlite3_mprintf("SELECT \"%w\", \"%w\" FROM \"%w\";", pk_name, col_name, table_name);
+ char *sql = (c->partition)
+ ? sqlite3_mprintf("SELECT \"%w\", \"%w\" FROM \"%w\" WHERE \"%w\" = ?1;", pk_name, col_name, table_name, c->table->options.partition)
+ : sqlite3_mprintf("SELECT \"%w\", \"%w\" FROM \"%w\";", pk_name, col_name, table_name);
if (!sql) {
sqlite3_free(v);
c->stream.vector = NULL;
@@ -3635,6 +3840,10 @@ static int vStreamScanCursorRun (sqlite3 *db, vFullScanCursor *c, const void *v1
sqlite3_stmt *vm = NULL;
int rc = sqlite3_prepare_v2(db, sql, -1, &vm, NULL);
if (rc != SQLITE_OK) goto cleanup;
+ if (c->partition) {
+ rc = sqlite3_bind_value(vm, 1, c->partition);
+ if (rc != SQLITE_OK) goto cleanup;
+ }
// compute distance function
vector_distance vd = c->table->options.v_distance;
@@ -3645,7 +3854,7 @@ static int vStreamScanCursorRun (sqlite3 *db, vFullScanCursor *c, const void *v1
rc = sqlite_vtab_set_error(c->base.pVtab, "Distance '%s' is not supported for vector type '%s'", vector_distance_to_name(vd), vector_type_to_name(vt));
goto cleanup;
}
- if (vector_use_normalized_cosine(c->table, false)) distance_fn = cosine_normalized_f32;
+ if (vector_use_normalized_cosine(c->table, false)) distance_fn = cosine_normalized_for(c->table->options.v_type);
c->stream.distance_fn = distance_fn;
c->stream.vm = vm;
@@ -3750,7 +3959,7 @@ static int vStreamQuantCursorRun (sqlite3 *db, vFullScanCursor *c, const void *v
// quantize input vector
int dimension = c->table->options.v_dim;
vector_qtype qtype = c->table->options.q_type;
- size_t alloc_size = (qtype == VECTOR_QUANT_1BIT) ? ((dimension + 7) / 8) : (dimension * sizeof(int8_t));
+ size_t alloc_size = (qtype == VECTOR_QUANT_1BIT) ? (size_t)((dimension + 7) / 8) : (size_t)dimension * sizeof(int8_t);
uint8_t *v = (uint8_t *)sqlite3_malloc64(alloc_size);
if (!v) return SQLITE_NOMEM;
@@ -3896,9 +4105,6 @@ static void vector_init (sqlite3_context *context, int argc, sqlite3_value **arg
const char *column_name = (const char *)sqlite3_value_text(argv[1]);
const char *arg_options = (const char *)sqlite3_value_text(argv[2]);
- // sanity check table and column
- if (sqlite_sanity_check(context, table_name, column_name) == false) return;
-
// parse options
vector_options options = vector_options_create();
bool rc = parse_keyvalue_string(context, arg_options, vector_keyvalue_callback, &options);
@@ -3920,7 +4126,8 @@ static void vector_init (sqlite3_context *context, int argc, sqlite3_value **arg
return;
}
- // check if table is already loaded
+ // already registered in this connection (or autoloaded by a scan): check consistency
+ // and return before the table checks, which cost three pragma queries per call
vector_context *v_ctx = (vector_context *)sqlite3_user_data(context);
table_context *t_ctx = vector_context_lookup(v_ctx, table_name, column_name);
if (t_ctx) {
@@ -3939,12 +4146,29 @@ static void vector_init (sqlite3_context *context, int argc, sqlite3_value **arg
context_result_error(context, SQLITE_ERROR, "Inconsistent normalization flag for '%s.%s': existing=%s, provided=%s", table_name, column_name, t_ctx->options.v_normalized ? "true" : "false", options.v_normalized ? "true" : "false");
return;
}
+
+ if (strcmp(options.partition, t_ctx->options.partition) != 0) {
+ context_result_error(context, SQLITE_ERROR, "Inconsistent partition column for '%s.%s': existing='%s', provided='%s'", table_name, column_name, t_ctx->options.partition, options.partition);
+ return;
+ }
// no need to add a new entry
return;
}
+
+ // sanity check table and column
+ if (sqlite_sanity_check(context, table_name, column_name) == false) return;
+
+ sqlite3 *db = sqlite3_context_db_handle(context);
+ if (options.partition[0] && !sqlite_column_exists(db, table_name, options.partition)) {
+ context_result_error(context, SQLITE_ERROR, "Partition column '%s' does not exist in table '%s'", options.partition, table_name);
+ return;
+ }
vector_context_add(context, v_ctx, table_name, column_name, &options);
+ if (vector_context_lookup(v_ctx, table_name, column_name)) {
+ vector_persist_options(db, table_name, column_name, &options);
+ }
}
static void vector_version (sqlite3_context *context, int argc, sqlite3_value **argv) {
diff --git a/test/test_vector.c b/test/test_vector.c
index 93ba354..5fd0981 100644
--- a/test/test_vector.c
+++ b/test/test_vector.c
@@ -12,6 +12,7 @@
#include
#include
#include
+#include
#include
#include "sqlite3.h"
#include "sqlite-vector.h"
@@ -1283,6 +1284,184 @@ static void test_malformed_input(sqlite3 *db) {
/* ---------- Main ---------- */
+
+/* ---------- Test: partitions ---------- */
+
+static void test_partition(sqlite3 *db) {
+ printf("\n=== Partition ===\n");
+ char sql[1024];
+ char *err = NULL;
+
+ ASSERT(exec_sql(db, "CREATE TABLE tpart (id INTEGER PRIMARY KEY, conv TEXT, v BLOB);") == SQLITE_OK, "partition table created");
+ exec_sql(db, "CREATE INDEX tpart_conv ON tpart(conv);");
+ const char *rows[][2] = {
+ {"a", "[1, 0, 0, 0]"}, {"a", "[0.9, 0.1, 0, 0]"}, {"a", "[0, 1, 0, 0]"},
+ {"b", "[1, 0, 0, 0]"}, {"b", "[0.99, 0.01, 0, 0]"}, {"b", "[0, 0, 1, 0]"},
+ };
+ for (int i = 0; i < 6; ++i) {
+ snprintf(sql, sizeof(sql), "INSERT INTO tpart (conv, v) VALUES ('%s', vector_as_f32('%s'));", rows[i][0], rows[i][1]);
+ exec_sql(db, sql);
+ }
+
+ ASSERT(sqlite3_exec(db, "SELECT vector_init('tpart', 'v', 'type=f32,dimension=4,distance=L2,partition=nope');", NULL, NULL, &err) != SQLITE_OK,
+ "partition column must exist");
+ sqlite3_free(err); err = NULL;
+ ASSERT(sqlite3_exec(db, "SELECT vector_init('tpart', 'v', 'type=f32,dimension=4,distance=L2,partition=x y');", NULL, NULL, &err) != SQLITE_OK,
+ "partition column must be an identifier");
+ sqlite3_free(err); err = NULL;
+ ASSERT(exec_sql(db, "SELECT vector_init('tpart', 'v', 'type=f32,dimension=4,distance=L2,partition=conv');") == SQLITE_OK,
+ "vector_init with partition");
+ ASSERT(sqlite3_exec(db, "SELECT vector_init('tpart', 'v', 'type=f32,dimension=4,distance=L2,partition=id');", NULL, NULL, &err) != SQLITE_OK,
+ "re-init with another partition column is inconsistent");
+ sqlite3_free(err); err = NULL;
+
+ /* streaming, restricted with WHERE part = ? */
+ {
+ scan_result r = {0};
+ ASSERT(sqlite3_exec(db, "SELECT s.id, s.distance FROM vector_full_scan('tpart', 'v', vector_as_f32('[1,0,0,0]')) AS s "
+ "WHERE s.part = 'a' ORDER BY s.distance;", scan_cb, &r, &err) == SQLITE_OK, "streaming scan with partition runs");
+ if (err) { printf(" err: %s\n", err); sqlite3_free(err); err = NULL; }
+ ASSERT(r.count == 3, "streaming partition returns only its 3 rows");
+ bool only_a = true;
+ for (int i = 0; i < r.count && i < 64; ++i) if (r.ids[i] > 3) only_a = false;
+ ASSERT(only_a, "streaming partition never returns another partition's rows");
+ ASSERT(r.count > 0 && r.ids[0] == 1, "streaming partition nearest first after ORDER BY");
+ }
+
+ /* top-k with the partition as the 5th argument */
+ {
+ scan_result r = {0};
+ ASSERT(sqlite3_exec(db, "SELECT id, distance FROM vector_full_scan('tpart', 'v', vector_as_f32('[1,0,0,0]'), 2, 'b');",
+ scan_cb, &r, &err) == SQLITE_OK, "top-k scan with partition runs");
+ if (err) { printf(" err: %s\n", err); sqlite3_free(err); err = NULL; }
+ ASSERT(r.count == 2 && r.ids[0] == 4 && r.ids[1] == 5, "top-k partition returns its 2 nearest, sorted");
+ }
+
+ /* the same answer as scanning everything and filtering afterwards */
+ {
+ scan_result inside = {0}, after = {0};
+ sqlite3_exec(db, "SELECT id, distance FROM vector_full_scan('tpart', 'v', vector_as_f32('[0,1,0,0]'), 2, 'a');", scan_cb, &inside, NULL);
+ sqlite3_exec(db, "SELECT s.id, s.distance FROM vector_full_scan('tpart', 'v', vector_as_f32('[0,1,0,0]')) AS s "
+ "JOIN tpart t ON t.id = s.id WHERE t.conv = 'a' ORDER BY s.distance LIMIT 2;", scan_cb, &after, NULL);
+ bool same = (inside.count == after.count);
+ for (int i = 0; same && i < inside.count; ++i) same = (inside.ids[i] == after.ids[i]) && fabs(inside.distances[i] - after.distances[i]) < 1e-6;
+ ASSERT(same, "partition scan equals full scan filtered afterwards");
+ }
+
+ /* a value that matches nothing is an empty result, not an error */
+ {
+ scan_result r = {0};
+ ASSERT(sqlite3_exec(db, "SELECT id, distance FROM vector_full_scan('tpart', 'v', vector_as_f32('[1,0,0,0]'), 2, 'zzz');",
+ scan_cb, &r, NULL) == SQLITE_OK && r.count == 0, "unknown partition value returns nothing");
+ }
+
+ /* tables without a partition column refuse the restriction */
+ {
+ const char *vecs[] = {"[1,0,0,0]", "[0,1,0,0]"};
+ setup_table(db, "tnopart", "f32", "L2", 4, vecs, 2);
+ ASSERT(sqlite3_exec(db, "SELECT id FROM vector_full_scan('tnopart', 'v', vector_as_f32('[1,0,0,0]'), 1, 'a');", NULL, NULL, &err) != SQLITE_OK,
+ "partition on a table declared without one is an error");
+ ASSERT(err && strstr(err, "no partition column") != NULL, "error explains how to declare the partition");
+ sqlite3_free(err); err = NULL;
+ }
+
+ /* quantized scans do not support it */
+ {
+ exec_sql(db, "SELECT vector_quantize('tpart', 'v');");
+ ASSERT(sqlite3_exec(db, "SELECT id FROM vector_quantize_scan('tpart', 'v', vector_as_f32('[1,0,0,0]'), 1, 'a');", NULL, NULL, &err) != SQLITE_OK,
+ "partition on a quantized scan is an error");
+ sqlite3_free(err); err = NULL;
+ }
+ ASSERT(open_stmt_count(db) == 0, "partition tests leave no open statements");
+}
+
+/* ---------- Test: options persisted, scans without vector_init ---------- */
+
+static void test_autoload(void) {
+ printf("\n=== Autoload ===\n");
+ char path[256];
+ snprintf(path, sizeof(path), "/tmp/sqlite_vector_autoload_%ld.db", (long)getpid());
+ unlink(path);
+ char *errmsg = NULL, *err = NULL;
+ sqlite3 *db = NULL;
+
+ sqlite3_open(path, &db);
+ sqlite3_vector_init(db, &errmsg, NULL);
+ exec_sql(db, "CREATE TABLE tauto (id INTEGER PRIMARY KEY, conv TEXT, v BLOB);");
+ exec_sql(db, "INSERT INTO tauto (conv, v) VALUES ('a', vector_as_f32('[1,0,0,0]')), ('b', vector_as_f32('[0,1,0,0]'));");
+ ASSERT(exec_sql(db, "SELECT vector_init('tauto', 'v', 'type=f32,dimension=4,distance=COSINE,normalized=1,partition=conv');") == SQLITE_OK,
+ "autoload: first vector_init");
+ sqlite3_close(db);
+
+ /* a new connection scans without vector_init */
+ sqlite3_open(path, &db);
+ sqlite3_vector_init(db, &errmsg, NULL);
+ {
+ scan_result r = {0};
+ ASSERT(sqlite3_exec(db, "SELECT id, distance FROM vector_full_scan('tauto', 'v', vector_as_f32('[1,0,0,0]'), 1, 'b');",
+ scan_cb, &r, &err) == SQLITE_OK, "autoload: scan in a new connection without vector_init");
+ if (err) { printf(" err: %s\n", err); sqlite3_free(err); err = NULL; }
+ ASSERT(r.count == 1 && r.ids[0] == 2, "autoload: persisted partition and distance are used");
+ }
+ /* vector_init with the same options writes nothing */
+ int before = sqlite3_total_changes(db);
+ ASSERT(exec_sql(db, "SELECT vector_init('tauto', 'v', 'type=f32,dimension=4,distance=COSINE,normalized=1,partition=conv');") == SQLITE_OK,
+ "autoload: vector_init after autoload is consistent");
+ ASSERT(sqlite3_total_changes(db) == before, "autoload: unchanged options are not written again");
+ sqlite3_close(db);
+
+ /* persisted metadata is ordinary data: an invalid row is refused, not trusted */
+ sqlite3_open(path, &db);
+ sqlite3_vector_init(db, &errmsg, NULL);
+ exec_sql(db, "UPDATE _sqliteai_vector SET value = 0 WHERE tblname = 'tauto' AND key = 'dimension';");
+ ASSERT(sqlite3_exec(db, "SELECT id FROM vector_full_scan('tauto', 'v', vector_as_f32('[1,0,0,0]'), 1);", NULL, NULL, &err) != SQLITE_OK,
+ "autoload: an invalid persisted dimension is refused");
+ sqlite3_free(err); err = NULL;
+ ASSERT(open_stmt_count(db) == 0, "autoload: no open statements");
+ sqlite3_close(db);
+ unlink(path);
+}
+
+
+/* ---------- Test: normalized cosine shortcut in half precision ---------- */
+
+static void test_normalized_half(sqlite3 *db) {
+ printf("\n=== Normalized cosine, F16/BF16 ===\n");
+ /* unit vectors (and a query that is not: the scan normalizes it) */
+ const char *vecs[] = {
+ "[1, 0, 0, 0]", "[0.6, 0.8, 0, 0]", "[0, 0, 0.8, 0.6]", "[0.5, 0.5, 0.5, 0.5]",
+ };
+ const char *query = "[3, 1, 0, 0]";
+ const char *types[] = {"f16", "bf16"};
+ char sql[1024];
+ for (int t = 0; t < 2; ++t) {
+ char fast[64], full[64];
+ snprintf(fast, sizeof(fast), "tnorm_fast_%s", types[t]);
+ snprintf(full, sizeof(full), "tnorm_full_%s", types[t]);
+ setup_table(db, full, types[t], "COSINE", 4, vecs, 4);
+ /* same rows, initialized with normalized=1 */
+ snprintf(sql, sizeof(sql), "CREATE TABLE \"%s\" (id INTEGER PRIMARY KEY, v BLOB);", fast);
+ exec_sql(db, sql);
+ snprintf(sql, sizeof(sql), "INSERT INTO \"%s\" (id, v) SELECT id, v FROM \"%s\";", fast, full);
+ exec_sql(db, sql);
+ snprintf(sql, sizeof(sql), "SELECT vector_init('%s', 'v', 'type=%s,dimension=4,distance=COSINE,normalized=1');", fast, types[t]);
+ char label[128];
+ snprintf(label, sizeof(label), "%s: vector_init with normalized=1", types[t]);
+ ASSERT(exec_sql(db, sql) == SQLITE_OK, label);
+
+ scan_result a = {0}, b = {0};
+ snprintf(sql, sizeof(sql), "SELECT id, distance FROM vector_full_scan('%s', 'v', vector_as_%s('%s'), 4);", fast, types[t], query);
+ sqlite3_exec(db, sql, scan_cb, &a, NULL);
+ snprintf(sql, sizeof(sql), "SELECT id, distance FROM vector_full_scan('%s', 'v', vector_as_%s('%s'), 4);", full, types[t], query);
+ sqlite3_exec(db, sql, scan_cb, &b, NULL);
+ bool same = (a.count == 4 && b.count == 4);
+ for (int i = 0; same && i < 4; ++i) same = (a.ids[i] == b.ids[i]) && fabs(a.distances[i] - b.distances[i]) < 1e-2;
+ snprintf(label, sizeof(label), "%s: 1 - dot ranks and scores like the full cosine", types[t]);
+ ASSERT(same, label);
+ }
+ ASSERT(open_stmt_count(db) == 0, "normalized half tests leave no open statements");
+}
+
int main(void) {
sqlite3 *db;
int rc = sqlite3_open(":memory:", &db);
@@ -1495,6 +1674,11 @@ int main(void) {
/* 6. malformed input and failure paths */
test_malformed_input(db);
+ /* 7. partitions and options persisted across connections */
+ test_partition(db);
+ test_autoload();
+ test_normalized_half(db);
+
sqlite3_close(db);