diff --git a/.env.example b/.env.example index a75ec43..c43230f 100644 --- a/.env.example +++ b/.env.example @@ -2,5 +2,9 @@ LLM_BASE_URL=http://localhost:11434/v1 LLM_API_KEY=ollama LLM_MODEL=qwen3:8b LLM_REASONING_EFFORT=none +EMBEDDING_MODEL=nomic-embed-text +EMBEDDING_DIMENSIONS=768 +EMBEDDING_BATCH_SIZE=32 +DATABASE_URL=postgresql://swellsense:swellsense@127.0.0.1:5432/swellsense HTTP_USER_AGENT=SwellSense/0.1 (learning project; contact: set HTTP_USER_AGENT) REQUEST_DELAY_S=1.0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c377bad..1f6c028 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,6 +8,22 @@ on: jobs: check: runs-on: ubuntu-latest + env: + DATABASE_URL: postgresql://swellsense:swellsense@127.0.0.1:5432/swellsense + services: + postgres: + image: pgvector/pgvector:pg17 + env: + POSTGRES_USER: swellsense + POSTGRES_PASSWORD: swellsense + POSTGRES_DB: swellsense + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U swellsense -d swellsense" + --health-interval 10s + --health-timeout 5s + --health-retries 5 steps: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v6 diff --git a/AGENTS.md b/AGENTS.md index 52b5425..6a2be76 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,6 +56,8 @@ code, with short docstrings explaining why. - `src/swellsense/llm/`: the only code that talks to the LLM API - `src/swellsense/extraction/`: structured extraction (boards, unit parsing) - `src/swellsense/ingest/`: source registry, fetchers, raw document storage, ingest runs +- `src/swellsense/processing/`: cleaning, chunking, and the process run +- `src/swellsense/db/`: local Postgres connection and schema - `src/swellsense/spots/`: spot profiles and the registry that loads them - `src/swellsense/tides/`: LINZ Tauranga predictions and tide state at a time - `src/swellsense/forecast/`: Open-Meteo swell and wind for one spot @@ -74,15 +76,17 @@ code, with short docstrings explaining why. - Verify changes: `bash scripts/check.sh` (lint, format check, then tests; stops at the first failure) - Apply lint and format fixes: `uv run ruff check --fix && uv run ruff format` - Download sources: `uv run swellsense ingest` (or `--source ID` for one) +- Process raw pages: `uv run swellsense process` (reads `data/raw/`, embeds via the configured provider, upserts into local Postgres) - Tauranga tides: `uv run swellsense tides` (or `--date YYYY-MM-DD`) - Spot forecast: `uv run swellsense forecast SPOT` (or `--hours N`, default 12) - Conditions check: `uv run swellsense check SPOT` (or `--hours N`, default 12); `uv run swellsense check --all` ranks every spot, with ties shown as ties; `--skill LEVEL` lists harder spots separately - Chat: `uv run python -m swellsense.chatbot` (conditions questions use the spot tools) +- Local Postgres: `docker compose up -d`, then `uv run swellsense db init` ## Roadmap 1. [x] Foundations: provider-agnostic LLM client, structured extraction 2. [x] Knowledge ingestion: source registry, fetching, raw storage -3. [ ] Processing: cleaning, chunking, local embeddings, Postgres + pgvector (in progress) +3. [x] Processing: cleaning, chunking, local embeddings, Postgres + pgvector 4. [ ] Grounded chat: retrieval with citations 5. [ ] Live conditions: forecast, tides, classifiers, an explainable conditions check and a ranking are in. The chatbot answers a spot check or "where should I go" from those tools. Other answers are not grounded in sources yet. 6. [ ] Spots and maps: spot data and profiles, "where to surf" recommendations @@ -115,4 +119,5 @@ Work on the current roadmap stage unless asked otherwise. Don't build ahead. - Use `uv` for Python 3.13 (`.python-version`). The image's system Python may be older; `uv sync --locked` installs the pinned interpreter. - Checks: `bash scripts/check.sh`. Tests must not call the network or the LLM. - There is no dev server. `uv run swellsense ingest` downloads every source into `data/raw/` and writes `data/raw/_last_run.json`. `uv run swellsense ingest --source ID` downloads one source. `uv run swellsense tides` prints Tauranga high and low waters for today and caches the LINZ CSV under `data/cache/`. `uv run swellsense forecast SPOT` prints an Open-Meteo swell and wind table and caches it under `data/cache/forecast/` for one hour. `uv run swellsense check SPOT` rates the next 12 hours and `uv run swellsense check --all` ranks every spot (ties share a rank; `--skill LEVEL` lists harder spots as above your level); both use those caches. Loading `data/sources.yaml` with `swellsense.ingest.registry.load_sources` and parsing board dimensions with `swellsense.extraction.units.parse_dimension` exercises the current product path. +- `uv run swellsense process` reads `data/raw/`, embeds via the configured provider, and upserts into local Postgres (same Ollama embeddings endpoint as the LLM). Postgres is not started in Cloud; tests mock the database and embedder. - `uv run python -m swellsense.chatbot` expects a local OpenAI-compatible server (default `http://localhost:11434/v1`, see `.env.example`). The environment does not start that server. A conditions question also fetches the Open-Meteo forecast and LINZ tides; tests mock both. diff --git a/README.md b/README.md index 928affb..712d65b 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Early development. What works today: - **Terminal chat** with a local model through Ollama. Conditions questions ("is it worth surfing?", "where should I go?") are answered from the conditions check. The model chooses the tool and phrases the result; the score is computed in code. Other answers are not grounded in sources yet, so treat those with caution. - **Knowledge ingestion**: downloads surf knowledge from Wikipedia into local storage, keeping the source URL, license and attribution on every document. +- **Processing**: cleans and chunks ingested pages, embeds new or changed chunks via the configured provider, and stores them in local Postgres for retrieval. - **Tauranga tides**: prints LINZ high and low waters for a day, with the required acknowledgement. - **Spot forecast**: hourly swell, wind waves and wind for a Bay of Plenty spot, from Open-Meteo. - **Conditions check**: rates the next few hours at a spot from that forecast, the tide and the spot profile, or ranks every spot by its best hour. Tied scores share a rank, and a skill level leaves harder spots on a separate list. @@ -43,9 +44,11 @@ Requires macOS or Linux, [uv](https://docs.astral.sh/uv/) and [Ollama](https://o ollama pull qwen3:8b uv sync cp .env.example .env +docker compose up -d +uv run swellsense db init ``` -In `.env`, set `HTTP_USER_AGENT` to identify the project to source sites, for example `SwellSense/0.1 (https://github.com//swellsense)`. +In `.env`, set `HTTP_USER_AGENT` to identify the project to source sites, for example `SwellSense/0.1 (https://github.com//swellsense)`. Postgres runs locally via Docker Compose; `DATABASE_URL` in `.env.example` matches the compose service. ## Commands @@ -54,6 +57,7 @@ In `.env`, set `HTTP_USER_AGENT` to identify the project to source sites, for ex | `uv run python -m swellsense.chatbot` | Chat in the terminal (needs Ollama). Conditions questions use the live check | | `uv run swellsense ingest` | Download all sources into `data/raw/` | | `uv run swellsense ingest --source wikipedia` | Download a single source | +| `uv run swellsense process` | Clean, chunk and embed `data/raw/` into Postgres | | `uv run swellsense tides` | Print today's Tauranga highs and lows | | `uv run swellsense tides --date 2026-01-15` | Print one day's Tauranga tides | | `uv run swellsense forecast mount-main-beach` | Print 12 hours of swell and wind for a spot | @@ -61,6 +65,8 @@ In `.env`, set `HTTP_USER_AGENT` to identify the project to source sites, for ex | `uv run swellsense check mount-main-beach` | Rate the next 12 hours at a spot | | `uv run swellsense check --all` | Rank every spot by its best hour, showing ties as ties | | `uv run swellsense check --all --skill beginner` | Rank spots at a skill level, and list the harder ones | +| `docker compose up -d` | Start local Postgres with pgvector (localhost only) | +| `uv run swellsense db init` | Create the documents and chunks schema | | `bash scripts/check.sh` | Lint, format check and tests | ## Data and licensing @@ -80,6 +86,8 @@ src/swellsense/ llm/ the only code that talks to the LLM extraction/ structured extraction (board specs, unit parsing) ingest/ source registry, fetchers, storage, ingest runs + processing/ cleaning, chunking, and the process run + db/ local Postgres connection and schema spots/ spot profiles tides/ LINZ tide predictions and tide state forecast/ Open-Meteo swell and wind for one spot @@ -96,7 +104,7 @@ scripts/check.sh the single check command - [x] Foundations: provider-agnostic LLM client, structured extraction - [x] Knowledge ingestion: source registry, fetching, raw storage -- [ ] Processing: cleaning, chunking, embeddings, Postgres with pgvector +- [x] Processing: cleaning, chunking, embeddings, Postgres with pgvector - [ ] Grounded chat: retrieval with citations - [ ] Live conditions: forecast, tides, classifiers, an explainable conditions check and a ranking are in. The chatbot answers a spot check or "where should I go" from those tools. Other answers are not grounded in sources yet. - [ ] Spots and maps: spot profiles and "where to surf" recommendations diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..219844e --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,14 @@ +services: + postgres: + image: pgvector/pgvector:pg17 + ports: + - "127.0.0.1:5432:5432" + environment: + POSTGRES_USER: swellsense + POSTGRES_PASSWORD: swellsense + POSTGRES_DB: swellsense + volumes: + - swellsense_pgdata:/var/lib/postgresql/data + +volumes: + swellsense_pgdata: diff --git a/docs/plans/stage-3.md b/docs/plans/stage-3.md new file mode 100644 index 0000000..e979dfb --- /dev/null +++ b/docs/plans/stage-3.md @@ -0,0 +1,110 @@ +# Plan: roadmap stage 3 (processing: cleaning, chunking, embeddings, Postgres + pgvector) + +## Decisions (final) + +- Dependencies: add `psycopg[binary]` and `pgvector`. +- Embedding model: `nomic-embed-text` (768 dimensions). +- Local Postgres: Docker Compose. +- CI: a Postgres service container (slice 7), run right after slice 4. +- Chunking: 300 words, 50 words overlap. No intermediate files. No `swellsense search` command in this stage. + +## Progress (tick each box in the slice's own PR) + +- [x] Slice 1: Clean raw pages into sections +- [x] Slice 2: Chunk a document with its citation metadata +- [x] Slice 3: Embedding function in `swellsense.llm` +- [x] Slice 4: Local Postgres, schema and `swellsense db init` +- [x] Slice 7: Postgres service container in CI +- [x] Slice 5: Chunk store (upsert, prune, nearest) +- [x] Slice 6: `swellsense process` end to end + +Slices are run one at a time, in the order above. + +Based on `origin/develop` @ `6939762`. Nothing for stage 3 exists yet. There is no processing package, no DB code and no DB dependency, and no open PRs or branches. The only knowledge source is `wikipedia` (9 articles, CC BY-SA 4.0, `open`). Raw pages are `RawDocument` JSON in `data/raw//.json`, loaded with `ingest.store.load_all()`. + +## 1. Scope and non-goals + +**In scope** (stage 3 is done when this works end to end on a laptop): +- **Clean**: turn a `RawDocument`'s MediaWiki plain text into sections (heading plus body). Drop non-content sections (References, See also, External links, Further reading, Notes, Bibliography) and normalise whitespace. +- **Chunk**: split sections into overlapping chunks with a word budget. Each chunk carries its document's id, title, URL, section, license, attribution and usage, so stage 4 can cite it. +- **Embed**: add an `embed(texts)` function in `swellsense.llm`, calling the configured provider's OpenAI-compatible `/v1/embeddings` endpoint. Ollama supports this endpoint. It reuses the existing `openai` client, so the provider stays swappable and embedding needs no new library. +- **Store**: run Postgres with pgvector locally, using an idempotent `schema.sql` with `documents` and `chunks` tables, a `vector(N)` column and an HNSW `vector_cosine_ops` index. Provide upsert, stale-chunk deletion and a `nearest(embedding, k)` query. The query only proves the index works; stage 4 builds retrieval on it. +- **Run as its own stage**: `uv run swellsense process` reads `data/raw/`, cleans, chunks, embeds only new or changed chunks (skipped by content hash), upserts, removes chunks that no longer exist, and prints a run report. It can be rerun on its own without re-ingesting. +- README and AGENTS.md are updated (commands, layout, roadmap tick). + +**Non-goals** (later stages, or deliberately left out): +- Retrieval in the chatbot, citations in answers, prompt changes, reranking, hybrid or keyword search (stage 4). +- Any change to "How the bot must answer". +- New data sources or a `web` fetcher; changes to `data/sources.yaml`. +- Eval sets and retrieval-quality metrics (stage 10). Model choice is not tuned by evals yet. +- Migration frameworks (Alembic, an ORM), async DB access, connection pooling. +- Hosted or cloud Postgres, deployment, and anything public. The database is local only. +- Storing forecasts or tides in the DB (they stay live tools, per AGENTS.md). + +## 2. Decisions + +1. **New dependencies (approved).** `psycopg[binary]` (Psycopg 3) and `pgvector` (the Python adapter: `register_vector`, `Vector`). No embedding library: embeddings go through the existing `openai` client to Ollama. *Rejected alternative:* `sentence-transformers`, which pulls in torch, is a heavy install and bypasses `swellsense.llm`. +2. **Embedding model.** **Decided: `nomic-embed-text`** (768 dimensions, already installed locally). Switching to another 768-dimension model later means re-embedding, not a schema change. Comparing models belongs with the stage 10 evals. Avoid `all-minilm`, whose context is too short for our chunks. Avoid `qwen3-embedding:8b` at full size: its 4096 dimensions exceed pgvector's 2000-dimension HNSW limit. `nomic-embed-text` expects task prefixes (`search_document:` / `search_query:`), and the code applies the right one. +3. **Chunk size.** Use about **300 words, with 50 words of overlap**. Never cross a section boundary; split on paragraphs first, then sentences. A short trailing chunk is merged into the previous one. The limit is counted in words, using the existing `count_words`, so no tokenizer dependency is needed. ~300 words is roughly 400 tokens, well inside the model's context. Both numbers are settings, not constants. +4. **Postgres locally.** **Decided: `docker-compose.yml`** with the `pgvector/pgvector:pg17` image (pgvector 0.8.x), with the port bound to localhost only and data in a named Docker volume. A new `DATABASE_URL` setting goes in `.env` / `.env.example`, holding a local-only dev password. +5. **Postgres in CI.** **Decided: CI gets a Postgres service container (slice 7, right after slice 4).** Unit tests use fakes. DB integration tests are marked and **skipped unless `DATABASE_URL` is set**, so local runs without Postgres stay green. CI sets `DATABASE_URL` to a `pgvector/pgvector:pg17` service container, so the integration tests run there against a real database. Tests talk only to this localhost container, never the internet. +6. **Intermediate files.** **no** `data/processed/` JSON. Chunking is cheap and deterministic, so `process` goes straight from raw files to the DB. The expensive step (embedding) is skipped by chunk content hash and embedding model name. This keeps the stages separate (rerun `process` alone) with one less store to keep in sync. +7. **Private sources.** None exist today. storing the `usage` label on every chunk now, and making `nearest()` accept a `public_only` flag. Then stage 4 can never return `private` text in public output, without another schema change. +8. **A `swellsense search "query"` debug command?** **not in stage 3**. It is the first retrieval feature and belongs in stage 4. Stage 3 is verified with `nearest()` integration tests plus a manual `psql` row count. + +## 3. Vertical slices, in order + +Each slice is one Engineer task and one branch/PR, run strictly one at a time. Sizes include tests. Every slice must pass `bash scripts/check.sh` and update README/AGENTS.md where it adds a command, setting or folder. + +**Slice 1: Clean raw pages into sections** (~150 lines) +- Files: new `src/swellsense/processing/__init__.py`, `src/swellsense/processing/clean.py`, `tests/test_clean.py`; read `ingest/models.py`. +- Change: `clean_sections(text: str) -> list[Section]`, where `Section` is a Pydantic model (`heading`, `text`). Split on MediaWiki `== Heading ==` lines (any level), with the lead text as heading `""`. Drop the boilerplate sections listed above, collapse runs of blank lines and trailing whitespace, and drop empty sections. +- Acceptance: tests with small synthetic MediaWiki strings (no real pages) cover the lead section, nested headings, each dropped heading, an empty section, and whitespace normalisation. No I/O. + +**Slice 2: Chunk a document with its citation metadata** (~220 lines) +- Files: new `src/swellsense/processing/chunk.py`, `src/swellsense/processing/models.py`, `tests/test_chunk.py`; `config.py` gets `chunk_words=300` and `chunk_overlap_words=50`. +- Change: a `Chunk` model (`id = #`, `document_id`, `index`, `section`, `text`, `word_count`, `content_hash`, plus `title`, `url`, `license`, `attribution`, `usage` copied from the `RawDocument`). Add `chunk_document(doc, max_words, overlap_words) -> list[Chunk]` built on slice 1. +- Acceptance: tests check that no chunk exceeds `max_words` (except a single over-long sentence, which is kept whole), that overlap is exactly `overlap_words` between neighbours in a section, that no chunk crosses sections, that a short tail is merged, and that metadata matches the source doc. Ids and output must be deterministic, and the same input gives the same hashes. + +**Slice 3: Embedding function in `swellsense.llm`** (~130 lines) +- Files: `src/swellsense/llm/client.py` (or a new `llm/embeddings.py`, re-exported), `src/swellsense/config.py` (`embedding_model`, `embedding_dimensions=768`, `embedding_batch_size`), `.env.example`, `tests/test_llm.py`. +- Change: `embed(texts: list[str], kind: Literal["document", "query"]) -> list[list[float]]`. It adds the model's task prefix, batches requests, preserves order, and raises if any vector's length is not `embedding_dimensions`. +- Acceptance: tests mock the OpenAI client (as `test_llm.py` already does). They cover batching across 2+ calls, order, prefixes, the dimension mismatch error and empty input. No network. +- Model: `nomic-embed-text`, using its `search_document:` / `search_query:` prefixes. + +**Slice 4: Local Postgres + schema + `swellsense db init`** (~200 lines) +- Files: new `docker-compose.yml`, `src/swellsense/db/__init__.py`, `src/swellsense/db/schema.sql`, `src/swellsense/db/connection.py`, `tests/test_db_schema.py`; `config.py` (`database_url`), `.env.example`, `cli.py` (a `db init` subcommand), `pyproject.toml` + `uv.lock` (the two new deps), README, `tests/conftest.py` (marker plus skip-if-no-`DATABASE_URL`). +- Change: `connect()` opens a Psycopg 3 connection and calls `register_vector`. `init_schema()` runs `CREATE EXTENSION IF NOT EXISTS vector` and creates `documents` and `chunks` (`embedding vector(768)`, `embedding_model text`, `content_hash`, `usage`) plus an HNSW cosine index, all `IF NOT EXISTS`. At startup, check that the column's dimension equals `embedding_dimensions`, and fail with a clear message if not. +- Acceptance: a unit test checks the SQL file parses and names the expected tables, index and dimension (no DB). Integration tests, skipped without `DATABASE_URL`, check that `init_schema` is idempotent (runs twice) and that the vector type round-trips. Human smoke test: `docker compose up -d && uv run swellsense db init`. +- Decisions 1 and 4 are made (deps approved, Docker Compose). + +**Slice 5: Chunk store: upsert, prune, nearest** (~200 lines) +- Files: new `src/swellsense/db/chunks.py`, `tests/test_db_chunks.py`. +- Change: `upsert_document(conn, doc)`, `existing_hashes(conn, document_id) -> dict[chunk_id, (content_hash, embedding_model)]`, `upsert_chunks(conn, chunks, embeddings, model)`, `delete_chunks_except(conn, document_id, keep_ids)`, and `nearest(conn, embedding, k, public_only=True) -> list[ChunkHit]` using `<=>` (cosine distance). It returns the citation fields plus the distance. +- Acceptance: integration tests (skipped without `DATABASE_URL`) use tiny hand-made 768-dimension vectors to check that nearest returns the expected order, `public_only` hides `private` rows, upsert is idempotent and pruning removes stale chunks. Each test runs in a rolled-back transaction or its own schema, so it never touches real data. + +**Slice 6: `swellsense process`, the processing stage end to end** (~250 lines) +- Files: new `src/swellsense/processing/run.py`, `cli.py`, `tests/test_process_run.py`, README + AGENTS.md (commands, layout, roadmap stage 3 ticked). +- Change: `process(docs, embed_fn, store) -> ProcessReport`, with `embed_fn` and `store` injected so tests use fakes. For each `RawDocument`, it chunks the document, skips chunks whose hash and model are unchanged, embeds the rest in batches, upserts and prunes. One failing document is recorded and the run continues, mirroring `ingest/run.py`. The report counts documents, chunks embedded, unchanged and removed, plus failures. The CLI wires the real `load_all`, `embed` and DB connection. If Ollama or Postgres is unreachable, it prints a one-line error and exits non-zero. +- Acceptance: tests with a fake embedder (one deterministic vector per text) and an in-memory fake store cover the first run (everything embedded), the second run (0 embedded, all unchanged), a changed doc (only changed chunks re-embedded, removed ones pruned), a model change (everything re-embedded) and one failing doc. Human smoke test: `uv run swellsense ingest && uv run swellsense process`, run twice; the second run embeds 0. + +**Slice 7 (runs right after slice 4, before slices 5 and 6): Postgres service container in CI** (~20 lines, `.github/workflows/ci.yml` only). Add a `pgvector/pgvector:pg17` service with a health check and set `DATABASE_URL` for the `check` job, so DB integration tests run in CI. Acceptance: CI `check` passes with the DB tests executed, not skipped. Tests still never touch the internet or Ollama. + +That is 7 slices, which is above my ~5 threshold. The human confirmed the plan. + +## 4. Risks and mitigations + +- **Dependency gates.** Slices 4–6 add `psycopg[binary]` and `pgvector`, which are approved. Slices 1–3 need no new dependencies. +- **The Engineer and Reviewer may not have Docker, Postgres or Ollama running.** The DB integration tests would then be skipped, and SQL could merge without ever running. Mitigations: keep the SQL small and the logic in pure, faked code; give slices 4–6 a human smoke-test step before I mark them done; run the DB integration tests in CI (slice 7). +- **The embedding dimension is locked into the schema.** The column is `vector(768)`, and a model with a different size needs a re-create. Mitigations: `embedding_model` is stored per chunk, a mismatch makes `process` re-embed, and a dimension mismatch fails loudly at `db init`/`process` instead of storing junk. +- **Silent truncation by the model.** If a chunk is longer than the embedding context, the end is ignored. Mitigation: 300 words (~400 tokens) is far below the context, and the size is a setting. +- **MediaWiki text format assumptions.** Cleaning assumes `== Heading ==` markers in the `explaintext` output. Mitigation: tests use synthetic fixtures. Before slice 1 merges, the human (only you can read `data/raw/`) spot-checks one cleaned page. Nothing from `data/raw/` is copied into tests. +- **Licensing and citations.** CC BY-SA requires attribution. Mitigation: every chunk row has `url`, `license`, `attribution` and `usage`, and slice 5 tests that `public_only` filters `private`. The DB lives in a Docker volume, outside the repo, so nothing derived from raw data is committed. +- **Network in tests.** Slices 1–2 and 6 are pure, using fakes. Slice 3 mocks the OpenAI client. Slices 4–5 hit only a local DB, and only when `DATABASE_URL` is set; they are skipped locally by default, and run in CI against the service container. No test calls Ollama, Wikipedia or the internet. +- **Scope creep into stage 4.** The `nearest()` query is the boundary. Nothing in this stage touches `chatbot.py`, `chat/tools.py` or prompts. + +## 5. Team + +**Engineer + Reviewer is enough.** Every slice is a small, test-first Python change of the same kind they have shipped for stages 1–2 and 5. The new parts (SQL, pgvector) are covered by the docs and kept thin. A specialist (for example a retrieval/ML engineer) would mainly add value for tuning: model choice, chunking strategy and retrieval quality. That only makes sense once there are evals to tune against (stage 10, or stage 4 at the earliest). Adding one now would add coordination cost on a 9-document corpus. + +The one real gap is **end-to-end verification with live Postgres and Ollama**, which no agent can reliably do. I'm covering it with short human smoke-test steps on slices 4–6 rather than a new role. diff --git a/pyproject.toml b/pyproject.toml index 448c31c..cfb6b80 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,6 +10,8 @@ requires-python = ">=3.13" dependencies = [ "httpx>=0.28.1", "openai>=3.29.0", + "pgvector>=0.5.1", + "psycopg[binary]>=3.3.6", "pydantic>=2.14.1", "pydantic-settings>=2.15.0", "pyyaml>=6.0.3", diff --git a/src/swellsense/cli.py b/src/swellsense/cli.py index 4dff7b1..c5e0eab 100644 --- a/src/swellsense/cli.py +++ b/src/swellsense/cli.py @@ -5,6 +5,8 @@ ``forecast`` prints hourly swell and wind for one spot. ``check`` rates a spot, or ranks every spot by its best hour. Ties share a rank. ``--skill`` keeps harder spots in a separate list. +``db init`` creates the local Postgres schema (pgvector, documents, chunks). +``process`` cleans, chunks and embeds raw pages into Postgres. """ import argparse @@ -12,6 +14,8 @@ from datetime import date, datetime, timedelta import httpx +import openai +import psycopg from swellsense.conditions.rating import HourRating from swellsense.conditions.report import ( @@ -20,11 +24,15 @@ build_report, rank_spots, ) +from swellsense.db import connect, init_schema from swellsense.forecast.models import SpotForecast from swellsense.forecast.openmeteo import fetch_forecast from swellsense.ingest.fetchers.mediawiki import make_client from swellsense.ingest.registry import load_sources from swellsense.ingest.run import SourceReport, ingest +from swellsense.ingest.store import load_all +from swellsense.llm.embeddings import embed +from swellsense.processing.run import PostgresChunkStore, ProcessReport, process from swellsense.spots.models import Spot from swellsense.spots.registry import get_spot, load_spots from swellsense.tides.linz import ( @@ -52,6 +60,11 @@ def _main(argv: list[str] | None = None) -> int: "--source", metavar="ID", help="Download only this source" ) + subparsers.add_parser( + "process", + help="Clean, chunk and embed data/raw into Postgres", + ) + tides_parser = subparsers.add_parser( "tides", help="Print Tauranga high and low waters for one day" ) @@ -101,18 +114,67 @@ def _main(argv: list[str] | None = None) -> int: help="With --all, rank spots at or below this level and list the rest", ) + db_parser = subparsers.add_parser("db", help="Local Postgres setup") + db_subparsers = db_parser.add_subparsers(dest="db_command", required=True) + db_subparsers.add_parser( + "init", + help="Create pgvector extension and document/chunk tables", + ) + args = parser.parse_args(argv) if args.command == "ingest": return _ingest(args.source) + if args.command == "process": + return _process() if args.command == "tides": return _tides(args.date) if args.command == "forecast": return _forecast(args.spot_id, args.hours) if args.command == "check": return _check(args.spot_id, args.all, args.hours, args.skill) + if args.command == "db": + return _db_init() return 2 +def _db_init() -> int: + try: + conn = connect() + try: + init_schema(conn) + finally: + conn.commit() + conn.close() + except (psycopg.Error, ValueError) as exc: + print(str(exc), file=sys.stderr) + return 1 + print("database schema initialized") + return 0 + + +def _process() -> int: + try: + docs = load_all() + conn = connect() + try: + report = process( + docs, + lambda texts: embed(texts, "document"), + PostgresChunkStore(conn), + ) + conn.commit() + finally: + conn.close() + except (psycopg.Error, openai.APIError) as exc: + print(str(exc), file=sys.stderr) + return 1 + + print(_process_summary(report)) + if report.failed: + return 1 + return 0 + + def _ingest(source_id: str | None) -> int: sources = load_sources() if source_id is not None: @@ -412,6 +474,14 @@ def _print_tides(day: date, events: list[TideEvent]) -> None: print(LINZ_ATTRIBUTION) +def _process_summary(report: ProcessReport) -> str: + return ( + f"process: {report.documents} documents, {report.embedded} embedded, " + f"{report.unchanged} unchanged, {report.removed} removed, " + f"{len(report.failed)} failed" + ) + + def _summary(source_id: str, report: SourceReport) -> str: line = ( f"{source_id}: {report.saved} saved, {report.unchanged} unchanged, " diff --git a/src/swellsense/config.py b/src/swellsense/config.py index ed86514..fd8fc15 100644 --- a/src/swellsense/config.py +++ b/src/swellsense/config.py @@ -16,6 +16,14 @@ class Settings(BaseSettings): ) http_timeout_s: float = 30 request_delay_s: float = 1.0 + chunk_words: int = 300 + chunk_overlap_words: int = 50 + embedding_model: str = "nomic-embed-text" + embedding_dimensions: int = 768 + embedding_batch_size: int = 32 + database_url: SecretStr = SecretStr( + "postgresql://swellsense:swellsense@127.0.0.1:5432/swellsense" + ) @lru_cache diff --git a/src/swellsense/db/__init__.py b/src/swellsense/db/__init__.py new file mode 100644 index 0000000..b9a00a4 --- /dev/null +++ b/src/swellsense/db/__init__.py @@ -0,0 +1,22 @@ +"""Local Postgres access for processed documents and chunk embeddings.""" + +from swellsense.db.chunks import ( + ChunkHit, + delete_chunks_except, + existing_hashes, + nearest, + upsert_chunks, + upsert_document, +) +from swellsense.db.connection import connect, init_schema + +__all__ = [ + "ChunkHit", + "connect", + "delete_chunks_except", + "existing_hashes", + "init_schema", + "nearest", + "upsert_chunks", + "upsert_document", +] diff --git a/src/swellsense/db/chunks.py b/src/swellsense/db/chunks.py new file mode 100644 index 0000000..5d22803 --- /dev/null +++ b/src/swellsense/db/chunks.py @@ -0,0 +1,192 @@ +"""Upsert, prune, and nearest-neighbour search for chunk embeddings.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from pgvector import Vector +from pydantic import BaseModel + +from swellsense.config import get_settings +from swellsense.ingest.models import RawDocument +from swellsense.ingest.registry import Usage +from swellsense.processing.models import Chunk + +if TYPE_CHECKING: + import psycopg + + +class ChunkHit(BaseModel): + """One chunk row from a nearest-neighbour query, with citation fields and distance.""" + + id: str + document_id: str + index: int + section: str + text: str + title: str + url: str + license: str + attribution: str + usage: Usage + distance: float + + +def upsert_document(conn: psycopg.Connection, doc: RawDocument) -> None: + """Insert or update a document row from a raw page.""" + conn.execute( + """ + INSERT INTO documents ( + id, source_id, title, url, license, attribution, usage + ) VALUES (%s, %s, %s, %s, %s, %s, %s) + ON CONFLICT (id) DO UPDATE SET + source_id = EXCLUDED.source_id, + title = EXCLUDED.title, + url = EXCLUDED.url, + license = EXCLUDED.license, + attribution = EXCLUDED.attribution, + usage = EXCLUDED.usage + """, + ( + doc.id, + doc.source_id, + doc.title, + doc.url, + doc.license, + doc.attribution, + doc.usage, + ), + ) + + +def existing_hashes( + conn: psycopg.Connection, document_id: str +) -> dict[str, tuple[str, str]]: + """Map chunk id to (content_hash, embedding_model) for one document.""" + rows = conn.execute( + """ + SELECT id, content_hash, embedding_model + FROM chunks + WHERE document_id = %s + """, + (document_id,), + ).fetchall() + return {row[0]: (row[1], row[2]) for row in rows} + + +def upsert_chunks( + conn: psycopg.Connection, + chunks: list[Chunk], + embeddings: list[list[float]], + model: str, +) -> None: + """Insert or update chunk rows with embeddings; lengths must match settings.""" + if len(chunks) != len(embeddings): + msg = f"chunks length {len(chunks)} != embeddings length {len(embeddings)}" + raise ValueError(msg) + expected_dim = get_settings().embedding_dimensions + for chunk, embedding in zip(chunks, embeddings, strict=True): + if len(embedding) != expected_dim: + msg = ( + f"embedding for chunk {chunk.id!r} has length {len(embedding)}, " + f"expected {expected_dim}" + ) + raise ValueError(msg) + conn.execute( + """ + INSERT INTO chunks ( + id, document_id, "index", section, text, word_count, + content_hash, title, url, license, attribution, usage, + embedding, embedding_model + ) VALUES ( + %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s + ) + ON CONFLICT (id) DO UPDATE SET + document_id = EXCLUDED.document_id, + "index" = EXCLUDED.index, + section = EXCLUDED.section, + text = EXCLUDED.text, + word_count = EXCLUDED.word_count, + content_hash = EXCLUDED.content_hash, + title = EXCLUDED.title, + url = EXCLUDED.url, + license = EXCLUDED.license, + attribution = EXCLUDED.attribution, + usage = EXCLUDED.usage, + embedding = EXCLUDED.embedding, + embedding_model = EXCLUDED.embedding_model + """, + ( + chunk.id, + chunk.document_id, + chunk.index, + chunk.section, + chunk.text, + chunk.word_count, + chunk.content_hash, + chunk.title, + chunk.url, + chunk.license, + chunk.attribution, + chunk.usage, + Vector(embedding), + model, + ), + ) + + +def delete_chunks_except( + conn: psycopg.Connection, document_id: str, keep_ids: list[str] +) -> None: + """Remove chunks for one document whose ids are not in keep_ids.""" + conn.execute( + """ + DELETE FROM chunks + WHERE document_id = %s + AND NOT (id = ANY(%s)) + """, + (document_id, keep_ids), + ) + + +def nearest( + conn: psycopg.Connection, + embedding: list[float], + k: int, + public_only: bool = True, +) -> list[ChunkHit]: + """Return the k closest chunks by cosine distance (lower is closer).""" + expected_dim = get_settings().embedding_dimensions + if len(embedding) != expected_dim: + msg = f"query embedding length {len(embedding)}, expected {expected_dim}" + raise ValueError(msg) + usage_filter = "AND usage <> 'private'" if public_only else "" + rows = conn.execute( + f""" + SELECT + id, document_id, "index", section, text, + title, url, license, attribution, usage, + embedding <=> %s AS distance + FROM chunks + WHERE TRUE {usage_filter} + ORDER BY embedding <=> %s + LIMIT %s + """, + (Vector(embedding), Vector(embedding), k), + ).fetchall() + return [ + ChunkHit( + id=row[0], + document_id=row[1], + index=row[2], + section=row[3], + text=row[4], + title=row[5], + url=row[6], + license=row[7], + attribution=row[8], + usage=row[9], + distance=float(row[10]), + ) + for row in rows + ] diff --git a/src/swellsense/db/connection.py b/src/swellsense/db/connection.py new file mode 100644 index 0000000..5347833 --- /dev/null +++ b/src/swellsense/db/connection.py @@ -0,0 +1,81 @@ +"""Postgres connection and idempotent schema setup for chunk storage.""" + +from __future__ import annotations + +import re +from pathlib import Path + +import psycopg +from pgvector.psycopg import register_vector + +from swellsense.config import get_settings + +_SCHEMA_PATH = Path(__file__).with_name("schema.sql") +_VECTOR_DIM_RE = re.compile(r"^vector\((\d+)\)$") + + +def connect() -> psycopg.Connection: + """Open a Psycopg 3 connection with pgvector types registered.""" + conn = psycopg.connect(get_settings().database_url.get_secret_value()) + try: + register_vector(conn) + except psycopg.ProgrammingError as exc: + # Fresh databases have no vector type until init_schema runs CREATE EXTENSION. + if "vector type not found" not in str(exc): + raise + return conn + + +def init_schema(conn: psycopg.Connection) -> None: + """Apply schema.sql and verify the embedding column matches settings.""" + sql = _SCHEMA_PATH.read_text(encoding="utf-8") + for statement in _split_sql_statements(sql): + conn.execute(statement) + _check_embedding_dimension(conn) + register_vector(conn) + conn.commit() + + +def _split_sql_statements(sql: str) -> list[str]: + """Split SQL into statements for Psycopg's extended query protocol.""" + statements: list[str] = [] + for part in sql.split(";"): + statement = part.strip() + if statement: + statements.append(statement) + return statements + + +def _check_embedding_dimension(conn: psycopg.Connection) -> None: + expected = get_settings().embedding_dimensions + row = conn.execute( + """ + SELECT format_type(a.atttypid, a.atttypmod) + FROM pg_attribute AS a + JOIN pg_class AS c ON c.oid = a.attrelid + JOIN pg_namespace AS n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' + AND c.relname = 'chunks' + AND a.attname = 'embedding' + AND a.attnum > 0 + AND NOT a.attisdropped + """ + ).fetchone() + if row is None: + msg = "chunks.embedding column not found after schema init" + raise ValueError(msg) + actual = _parse_vector_dimension(row[0]) + if actual != expected: + msg = ( + f"chunks.embedding dimension is {actual}, expected {expected} " + f"(embedding_dimensions setting)" + ) + raise ValueError(msg) + + +def _parse_vector_dimension(pg_type: str) -> int: + match = _VECTOR_DIM_RE.match(pg_type.strip()) + if match is None: + msg = f"chunks.embedding has unexpected type {pg_type!r}" + raise ValueError(msg) + return int(match.group(1)) diff --git a/src/swellsense/db/schema.sql b/src/swellsense/db/schema.sql new file mode 100644 index 0000000..8e3ed1c --- /dev/null +++ b/src/swellsense/db/schema.sql @@ -0,0 +1,30 @@ +CREATE EXTENSION IF NOT EXISTS vector; + +CREATE TABLE IF NOT EXISTS documents ( + id TEXT PRIMARY KEY, + source_id TEXT NOT NULL, + title TEXT NOT NULL, + url TEXT NOT NULL, + license TEXT NOT NULL, + attribution TEXT NOT NULL, + usage TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS chunks ( + id TEXT PRIMARY KEY, + document_id TEXT NOT NULL REFERENCES documents (id), + "index" INTEGER NOT NULL, + section TEXT NOT NULL, + text TEXT NOT NULL, + word_count INTEGER NOT NULL, + content_hash TEXT NOT NULL, + title TEXT NOT NULL, + url TEXT NOT NULL, + license TEXT NOT NULL, + attribution TEXT NOT NULL, + usage TEXT NOT NULL, + embedding vector(768) NOT NULL, + embedding_model TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS chunks_embedding_hnsw ON chunks USING hnsw (embedding vector_cosine_ops); diff --git a/src/swellsense/llm/__init__.py b/src/swellsense/llm/__init__.py index 6e5c56a..c0b83fe 100644 --- a/src/swellsense/llm/__init__.py +++ b/src/swellsense/llm/__init__.py @@ -1,3 +1,4 @@ from swellsense.llm.client import chat, complete_message, extract, respond +from swellsense.llm.embeddings import embed -__all__ = ["chat", "complete_message", "extract", "respond"] +__all__ = ["chat", "complete_message", "embed", "extract", "respond"] diff --git a/src/swellsense/llm/embeddings.py b/src/swellsense/llm/embeddings.py new file mode 100644 index 0000000..75a2160 --- /dev/null +++ b/src/swellsense/llm/embeddings.py @@ -0,0 +1,49 @@ +"""OpenAI-compatible embeddings for chunk storage and retrieval.""" + +from typing import Literal + +from swellsense.config import get_settings +from swellsense.llm.client import get_client + +_PREFIX: dict[Literal["document", "query"], str] = { + "document": "search_document: ", + "query": "search_query: ", +} + + +def embed(texts: list[str], kind: Literal["document", "query"]) -> list[list[float]]: + """Return embedding vectors for ``texts``. + + ``nomic-embed-text`` expects task prefixes on each input; we apply the + document or query prefix before calling the API. Vector length is checked + in code because Ollama does not accept OpenAI's ``dimensions`` parameter. + """ + if not texts: + return [] + + settings = get_settings() + client = get_client() + prefix = _PREFIX[kind] + batch_size = settings.embedding_batch_size + expected = settings.embedding_dimensions + out: list[list[float]] = [] + + for start in range(0, len(texts), batch_size): + batch = texts[start : start + batch_size] + prefixed = [prefix + t for t in batch] + response = client.embeddings.create( + model=settings.embedding_model, + input=prefixed, + ) + items = sorted(response.data, key=lambda d: d.index) + if len(items) != len(batch): + raise ValueError(f"embedding count {len(items)} != expected {len(batch)}") + for item in items: + vector = list(item.embedding) + if len(vector) != expected: + raise ValueError( + f"embedding length {len(vector)} != expected {expected}" + ) + out.append(vector) + + return out diff --git a/src/swellsense/processing/__init__.py b/src/swellsense/processing/__init__.py new file mode 100644 index 0000000..0502533 --- /dev/null +++ b/src/swellsense/processing/__init__.py @@ -0,0 +1 @@ +"""Turn raw ingested pages into sections and chunks for retrieval.""" diff --git a/src/swellsense/processing/chunk.py b/src/swellsense/processing/chunk.py new file mode 100644 index 0000000..d0f7eeb --- /dev/null +++ b/src/swellsense/processing/chunk.py @@ -0,0 +1,176 @@ +"""Split cleaned sections into overlapping word-budget chunks with citation metadata.""" + +from __future__ import annotations + +import re + +from swellsense.ingest.models import RawDocument, count_words, hash_text +from swellsense.processing.clean import clean_sections +from swellsense.processing.models import Chunk + +# Splits after ., !, or ? when followed by whitespace. Misses abbreviations (Dr. Smith) +# and some quoted or parenthetical boundaries; good enough for plain Wikipedia prose. +_SENTENCE_SPLIT_RE = re.compile(r"(?<=[.!?])\s+") + + +def _split_paragraphs(section_text: str) -> list[str]: + blocks = re.split(r"\n\s*\n", section_text.strip()) + return [block.strip() for block in blocks if block.strip()] + + +def _split_sentences(paragraph: str) -> list[str]: + parts = _SENTENCE_SPLIT_RE.split(paragraph.strip()) + return [part for part in parts if part] + + +def _last_n_words(text: str, n: int) -> str: + words = text.split() + if n <= 0 or not words: + return "" + return " ".join(words[-n:]) + + +def _sentences_for_section(section_text: str) -> list[str]: + sentences: list[str] = [] + for paragraph in _split_paragraphs(section_text): + sentences.extend(_split_sentences(paragraph)) + return sentences + + +def _merge_short_tail( + chunk_texts: list[str], + prefix_lengths: list[int], + overlap_words: int, +) -> list[str]: + if len(chunk_texts) < 2: + return chunk_texts + last = chunk_texts[-1] + prev = chunk_texts[-2] + tail_prefix = prefix_lengths[-1] + last_word_list = last.split() + new_word_count = len(last_word_list) - tail_prefix + suffix = " ".join(last_word_list[tail_prefix:]) if tail_prefix else last + if new_word_count >= overlap_words: + return chunk_texts + if suffix: + chunk_texts[-2] = f"{prev} {suffix}".strip() + prefix_lengths.pop() + chunk_texts.pop() + return chunk_texts + + +def _chunk_section( + section_text: str, + max_words: int, + overlap_words: int, +) -> list[str]: + """Return chunk texts for one section; may exceed max_words only per documented rules.""" + if count_words(section_text) <= max_words: + return [section_text] + + sentences = _sentences_for_section(section_text) + if not sentences: + return [] + + chunk_texts: list[str] = [] + prefix_lengths: list[int] = [] + index = 0 + while index < len(sentences): + if not chunk_texts: + prefix = "" + prefix_words = 0 + else: + prefix = _last_n_words(chunk_texts[-1], overlap_words) + prefix_words = count_words(prefix) + + packed: list[str] = [] + packed_words = prefix_words + start = index + while index < len(sentences): + sentence = sentences[index] + sentence_words = count_words(sentence) + if sentence_words > max_words: + if packed_words == prefix_words and not packed: + chunk_texts.append(sentence) + prefix_lengths.append(0) + index += 1 + break + if packed_words + sentence_words > max_words: + break + packed.append(sentence) + packed_words += sentence_words + index += 1 + + if packed: + body = " ".join(packed) + chunk_texts.append(f"{prefix} {body}".strip() if prefix else body) + prefix_lengths.append(prefix_words) + elif start == index and index < len(sentences): + sentence = sentences[index] + sentence_words = count_words(sentence) + if sentence_words > max_words: + chunk_texts.append(sentence) + prefix_lengths.append(0) + index += 1 + elif prefix: + allowed_prefix = max(0, max_words - sentence_words) + if prefix_words > allowed_prefix: + prefix = _last_n_words(chunk_texts[-1], allowed_prefix) + prefix_words = allowed_prefix + chunk_texts.append( + f"{prefix} {sentence}".strip() if prefix else sentence + ) + prefix_lengths.append(prefix_words) + index += 1 + else: + break + + return _merge_short_tail(chunk_texts, prefix_lengths, overlap_words) + + +def chunk_document( + doc: RawDocument, + max_words: int, + overlap_words: int, +) -> list[Chunk]: + """Split a raw document into chunks that carry citation metadata for retrieval. + + Chunks never cross section boundaries. After the first chunk in a section, each + chunk normally starts with the last ``overlap_words`` words of the previous chunk + (word-based, so the boundary may fall mid-sentence). If that full overlap plus the + next sentence would exceed ``max_words``, the prefix is shortened so the chunk stays + within ``max_words`` (possibly to zero overlap words). A chunk may exceed + ``max_words`` only when a single sentence is longer than ``max_words``, or when a + short trailing chunk is merged into the previous one (by less than ``overlap_words`` + words). + """ + if overlap_words < 0 or overlap_words >= max_words: + raise ValueError("overlap_words must satisfy 0 <= overlap_words < max_words") + + sections = clean_sections(doc.text) + if not sections: + return [] + + chunks: list[Chunk] = [] + index = 0 + for section in sections: + for text in _chunk_section(section.text, max_words, overlap_words): + chunks.append( + Chunk( + id=f"{doc.id}#{index}", + document_id=doc.id, + index=index, + section=section.heading, + text=text, + word_count=count_words(text), + content_hash=hash_text(text), + title=doc.title, + url=doc.url, + license=doc.license, + attribution=doc.attribution, + usage=doc.usage, + ) + ) + index += 1 + + return chunks diff --git a/src/swellsense/processing/clean.py b/src/swellsense/processing/clean.py new file mode 100644 index 0000000..446af24 --- /dev/null +++ b/src/swellsense/processing/clean.py @@ -0,0 +1,77 @@ +"""Split MediaWiki plain text into content sections for chunking.""" + +from __future__ import annotations + +import re + +from pydantic import BaseModel + +# MediaWiki marks section levels with matching = runs on both sides. +_HEADING_RE = re.compile(r"^\s*(=+)\s*(.*?)\s*\1\s*$") + +# Boilerplate sections are dropped so chunks stay on surf-relevant prose. +_DROPPED_HEADINGS = frozenset( + { + "references", + "see also", + "external links", + "further reading", + "notes", + "bibliography", + } +) + + +class Section(BaseModel): + """One heading and its body after whitespace normalisation.""" + + heading: str + text: str + + +def _normalize_section_text(text: str) -> str: + """Strip line endings, collapse extra blank lines, trim the block.""" + lines = [line.rstrip() for line in text.splitlines()] + collapsed: list[str] = [] + blank_run = 0 + for line in lines: + if line == "": + blank_run += 1 + if blank_run == 1: + collapsed.append("") + else: + blank_run = 0 + collapsed.append(line) + return "\n".join(collapsed).strip() + + +def _drop_heading(heading: str) -> bool: + return heading.strip().casefold() in _DROPPED_HEADINGS + + +def clean_sections(text: str) -> list[Section]: + """Split plain MediaWiki text into sections, dropping boilerplate blocks.""" + if text == "": + return [] + + sections: list[Section] = [] + current_heading = "" + body_lines: list[str] = [] + + def flush() -> None: + nonlocal body_lines + body = _normalize_section_text("\n".join(body_lines)) + if not _drop_heading(current_heading) and body: + sections.append(Section(heading=current_heading, text=body)) + body_lines = [] + + for line in text.splitlines(): + match = _HEADING_RE.match(line) + if match: + flush() + current_heading = match.group(2).strip() + else: + body_lines.append(line) + + flush() + return sections diff --git a/src/swellsense/processing/models.py b/src/swellsense/processing/models.py new file mode 100644 index 0000000..6cb39a8 --- /dev/null +++ b/src/swellsense/processing/models.py @@ -0,0 +1,22 @@ +"""Pydantic models for processed chunks used in retrieval and citation.""" + +from pydantic import BaseModel + +from swellsense.ingest.registry import Usage + + +class Chunk(BaseModel): + """One searchable text span with citation fields copied from its source document.""" + + id: str + document_id: str + index: int + section: str + text: str + word_count: int + content_hash: str + title: str + url: str + license: str + attribution: str + usage: Usage diff --git a/src/swellsense/processing/run.py b/src/swellsense/processing/run.py new file mode 100644 index 0000000..72aa773 --- /dev/null +++ b/src/swellsense/processing/run.py @@ -0,0 +1,135 @@ +"""Clean, chunk, embed and store raw documents. + +One bad document is recorded and the rest still process, mirroring ingest runs. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Protocol + +import openai +import psycopg +from pydantic import BaseModel, Field + +from swellsense.config import get_settings +from swellsense.ingest.models import RawDocument +from swellsense.processing.chunk import chunk_document +from swellsense.processing.models import Chunk + + +class ChunkStore(Protocol): + """Persistence for documents and chunk rows; no commit (caller's job).""" + + def upsert_document(self, doc: RawDocument) -> None: ... + + def existing_hashes(self, document_id: str) -> dict[str, tuple[str, str]]: ... + + def upsert_chunks( + self, chunks: list[Chunk], embeddings: list[list[float]], model: str + ) -> None: ... + + def delete_chunks_except(self, document_id: str, keep_ids: list[str]) -> None: ... + + +class ProcessReport(BaseModel): + """Counts from one process run over a set of raw documents.""" + + documents: int + embedded: int = 0 + unchanged: int = 0 + removed: int = 0 + failed: list[dict[str, str]] = Field(default_factory=list) + + +class PostgresChunkStore: + """Forwards chunk store operations to ``swellsense.db.chunks``.""" + + def __init__(self, conn: psycopg.Connection) -> None: + self._conn = conn + + def upsert_document(self, doc: RawDocument) -> None: + from swellsense.db.chunks import upsert_document + + upsert_document(self._conn, doc) + + def existing_hashes(self, document_id: str) -> dict[str, tuple[str, str]]: + from swellsense.db.chunks import existing_hashes + + return existing_hashes(self._conn, document_id) + + def upsert_chunks( + self, chunks: list[Chunk], embeddings: list[list[float]], model: str + ) -> None: + from swellsense.db.chunks import upsert_chunks + + upsert_chunks(self._conn, chunks, embeddings, model) + + def delete_chunks_except(self, document_id: str, keep_ids: list[str]) -> None: + from swellsense.db.chunks import delete_chunks_except + + delete_chunks_except(self._conn, document_id, keep_ids) + + +def process( + docs: list[RawDocument], + embed_fn: Callable[[list[str]], list[list[float]]], + store: ChunkStore, +) -> ProcessReport: + """Chunk each document, embed only new or changed chunks, upsert and prune.""" + settings = get_settings() + report = ProcessReport(documents=len(docs)) + + for doc in docs: + try: + embedded, unchanged, removed = _process_document( + doc, + embed_fn, + store, + settings.chunk_words, + settings.chunk_overlap_words, + settings.embedding_model, + ) + except (openai.APIError, psycopg.Error): + raise + except Exception as exc: # noqa: BLE001 + report.failed.append({"id": doc.id, "error": str(exc)}) + continue + report.embedded += embedded + report.unchanged += unchanged + report.removed += removed + + return report + + +def _process_document( + doc: RawDocument, + embed_fn: Callable[[list[str]], list[list[float]]], + store: ChunkStore, + chunk_words: int, + chunk_overlap_words: int, + embedding_model: str, +) -> tuple[int, int, int]: + chunks = chunk_document(doc, chunk_words, chunk_overlap_words) + store.upsert_document(doc) + existing = store.existing_hashes(doc.id) + keep_ids = {chunk.id for chunk in chunks} + + to_embed: list[Chunk] = [] + for chunk in chunks: + prior = existing.get(chunk.id) + if prior == (chunk.content_hash, embedding_model): + continue + to_embed.append(chunk) + + unchanged = len(chunks) - len(to_embed) + embedded = 0 + if to_embed: + texts = [chunk.text for chunk in to_embed] + embeddings = embed_fn(texts) + store.upsert_chunks(to_embed, embeddings, embedding_model) + embedded = len(to_embed) + + removed = sum(1 for chunk_id in existing if chunk_id not in keep_ids) + store.delete_chunks_except(doc.id, [chunk.id for chunk in chunks]) + return embedded, unchanged, removed diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..b0d2101 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,32 @@ +"""Shared pytest configuration.""" + +import os + +import pytest + +from swellsense.config import get_settings + + +def pytest_configure(config: pytest.Config) -> None: + config.addinivalue_line( + "markers", + "db: integration test requiring Postgres (set DATABASE_URL)", + ) + + +def pytest_collection_modifyitems( + config: pytest.Config, items: list[pytest.Item] +) -> None: + if os.environ.get("DATABASE_URL"): + return + skip_db = pytest.mark.skip(reason="DATABASE_URL not set") + for item in items: + if item.get_closest_marker("db") is not None: + item.add_marker(skip_db) + + +@pytest.fixture +def clear_settings_cache(): + """Clear cached settings after tests that patch environment or settings.""" + yield + get_settings.cache_clear() diff --git a/tests/test_angles.py b/tests/test_angles.py new file mode 100644 index 0000000..d572b5b --- /dev/null +++ b/tests/test_angles.py @@ -0,0 +1,42 @@ +import pytest + +from swellsense.conditions.angles import angle_diff, in_window + + +@pytest.mark.parametrize( + ("a", "b", "expected"), + [ + (370, 10, 0), + (720, 0, 0), + (-10, 10, 20), + (-90, 90, 180), + (0, 181, 179), + (0, 190, 170), + (359.5, 0.5, 1.0), + ], +) +def test_angle_diff_edge_cases(a: float, b: float, expected: float) -> None: + assert angle_diff(a, b) == expected + assert angle_diff(b, a) == expected + + +@pytest.mark.parametrize( + ("deg", "start", "end", "expected"), + [ + (-10, 330, 60, True), + (-31, 330, 60, False), + (359.5, 330, 60, True), + (60.5, 330, 60, False), + (45, 390, 60, True), + (20, 390, 60, False), + (10, -30, 60, True), + (329, -30, 60, False), + (0, 0, 0, True), + (1, 0, 0, False), + (359, 0, 0, False), + ], +) +def test_in_window_edge_cases( + deg: float, start: float, end: float, expected: bool +) -> None: + assert in_window(deg, start, end) is expected diff --git a/tests/test_chunk.py b/tests/test_chunk.py new file mode 100644 index 0000000..d066da0 --- /dev/null +++ b/tests/test_chunk.py @@ -0,0 +1,211 @@ +import hashlib +import itertools +from datetime import UTC, datetime + +import pytest + +from swellsense.ingest.models import RawDocument, hash_text +from swellsense.ingest.store import slugify +from swellsense.processing.chunk import _chunk_section, chunk_document + + +def _document(**overrides) -> RawDocument: + text = overrides.pop("text", "Lead only.") + title = overrides.pop("title", "Chunk test") + source_id = overrides.pop("source_id", "wikipedia") + values = { + "id": f"{source_id}/{slugify(title)}", + "source_id": source_id, + "title": title, + "url": "https://example.com/wiki/chunk_test", + "license": "CC BY-SA 4.0", + "attribution": "Test contributors", + "usage": "open", + "fetched_at": datetime(2026, 10, 14, 12, 0, tzinfo=UTC), + "content_hash": hashlib.sha256(text.encode()).hexdigest(), + "word_count": len(text.split()), + "text": text, + } + values.update(overrides) + return RawDocument(**values) + + +def _words(n: int, prefix: str = "w") -> str: + return " ".join(f"{prefix}{i}" for i in range(n)) + + +def _sentences(word_counts: list[int]) -> str: + parts = [] + for count in word_counts: + parts.append(f"{_words(count)}.") + return " ".join(parts) + + +def test_no_sections_returns_empty_list(): + text = "== References ==\nA citation." + assert chunk_document(_document(text=text), max_words=10, overlap_words=2) == [] + + +def test_short_section_is_one_chunk(): + text = "One small section without headings." + doc = _document(text=text) + chunks = chunk_document(doc, max_words=20, overlap_words=3) + assert len(chunks) == 1 + assert chunks[0].text == text + assert chunks[0].section == "" + assert chunks[0].index == 0 + assert chunks[0].id == f"{doc.id}#0" + + +def test_section_at_max_words_is_one_chunk(): + body = _words(10) + text = f"== Surf ==\n{body}" + chunks = chunk_document(_document(text=text), max_words=10, overlap_words=2) + assert len(chunks) == 1 + assert chunks[0].section == "Surf" + assert chunks[0].text == body + + +def test_no_chunk_exceeds_max_words_except_documented_cases(): + max_words = 15 + overlap = 3 + cases = [ + [6, 6, 6, 6], + # Sentence lengths in (max - overlap, max]: prefix shrink must cap chunks. + [10, 10], + [12, 12], + [14, 14], + [15], + ] + for word_counts in cases: + text = f"== Body ==\n{_sentences(word_counts)}" + chunks = chunk_document( + _document(text=text), max_words=max_words, overlap_words=overlap + ) + for chunk in chunks: + if chunk.word_count > max_words: + # Over-long single sentence or merged tail exception. + assert chunk.word_count < max_words + overlap + + +def test_two_max_sized_sentences_stay_within_cap(): + max_words = 10 + overlap = 3 + text = f"== Cap ==\n{_sentences([10, 10])}" + chunks = chunk_document( + _document(text=text), max_words=max_words, overlap_words=overlap + ) + assert [c.word_count for c in chunks] == [10, 10] + + +def test_prefix_shrinks_when_overlap_plus_sentence_exceeds_max(): + max_words = 10 + overlap = 3 + section = _sentences([10, 10]) + chunks = _chunk_section(section, max_words=max_words, overlap_words=overlap) + assert len(chunks) == 2 + assert all(len(c.split()) <= max_words for c in chunks) + second = chunks[1].split() + first = chunks[0].split() + # Second chunk: 10-word sentence; only 0 prefix words fit (10 + 10 > max). + assert second[-10:] == first[-10:] + assert second[:3] != first[-3:] + + +def test_overlap_between_neighbours_in_section(): + max_words = 12 + overlap = 4 + text = f"== A ==\n{_sentences([5, 5, 5])}" + chunks = chunk_document( + _document(text=text), max_words=max_words, overlap_words=overlap + ) + section_chunks = [c for c in chunks if c.section == "A"] + assert len(section_chunks) >= 2 + for prev, nxt in itertools.pairwise(section_chunks): + prev_tail = prev.text.split()[-overlap:] + nxt_head = nxt.text.split()[:overlap] + assert prev_tail == nxt_head + + +def test_chunks_do_not_cross_sections(): + text = ( + "Lead text here.\n\n" + "== One ==\n" + f"{_sentences([8, 8])}\n" + "== Two ==\n" + f"{_sentences([8, 8])}" + ) + chunks = chunk_document(_document(text=text), max_words=10, overlap_words=2) + headings = [c.section for c in chunks] + assert "" in headings + assert "One" in headings + assert "Two" in headings + for chunk in chunks: + if chunk.section == "One": + assert "Two" not in chunk.text + if chunk.section == "Two": + assert "One" not in chunk.text.split()[0] + + +def test_short_tail_is_merged(): + max_words = 20 + overlap = 5 + # Splits then merges: [10, 9] in first chunk, tail has < overlap new words. + text = f"== Tail ==\n{_sentences([10, 9, 3])}" + chunks = chunk_document( + _document(text=text), max_words=max_words, overlap_words=overlap + ) + section_chunks = [c for c in chunks if c.section == "Tail"] + assert len(section_chunks) == 1 + merged = section_chunks[0] + assert max_words < merged.word_count < max_words + overlap + + +def test_overlong_single_sentence_is_kept_whole(): + max_words = 5 + overlap = 2 + long_sentence = f"{_words(12)}." + text = f"== Long ==\nIntro short. {long_sentence} After that." + chunks = chunk_document( + _document(text=text), max_words=max_words, overlap_words=overlap + ) + long_chunks = [c for c in chunks if long_sentence.rstrip(".") in c.text] + assert any(c.word_count > max_words for c in long_chunks) + + +def test_ids_run_zero_through_n_minus_one(): + text = f"Lead.\n== A ==\n{_sentences([6, 6, 6])}\n== B ==\nShort." + doc = _document(text=text) + chunks = chunk_document(doc, max_words=8, overlap_words=2) + assert [c.index for c in chunks] == list(range(len(chunks))) + assert [c.id for c in chunks] == [f"{doc.id}#{i}" for i in range(len(chunks))] + + +def test_metadata_matches_source_document(): + doc = _document(text="== Only ==\nSome body text here.") + chunk = chunk_document(doc, max_words=50, overlap_words=5)[0] + assert chunk.document_id == doc.id + assert chunk.title == doc.title + assert chunk.url == doc.url + assert chunk.license == doc.license + assert chunk.attribution == doc.attribution + assert chunk.usage == doc.usage + assert chunk.content_hash == hash_text(chunk.text) + + +def test_two_calls_are_identical(): + doc = _document(text=f"== Repeat ==\n{_sentences([7, 7, 7])}") + first = chunk_document(doc, max_words=10, overlap_words=3) + second = chunk_document(doc, max_words=10, overlap_words=3) + assert first == second + + +@pytest.mark.parametrize("overlap_words", [10, -1]) +def test_invalid_overlap_raises(overlap_words: int): + with pytest.raises(ValueError, match="overlap_words"): + chunk_document(_document(), max_words=10, overlap_words=overlap_words) + + +def test_overlap_equal_to_max_words_raises(): + with pytest.raises(ValueError, match="overlap_words"): + chunk_document(_document(), max_words=10, overlap_words=10) diff --git a/tests/test_clean.py b/tests/test_clean.py new file mode 100644 index 0000000..0fee1c9 --- /dev/null +++ b/tests/test_clean.py @@ -0,0 +1,89 @@ +import pytest + +from swellsense.processing.clean import Section, clean_sections + + +def test_empty_input_returns_no_sections(): + assert clean_sections("") == [] + + +def test_no_headings_is_single_lead_section(): + text = "Opening paragraph only." + assert clean_sections(text) == [Section(heading="", text="Opening paragraph only.")] + + +def test_lead_section_before_first_heading(): + text = "Lead line.\n\n== First ==\nFirst body." + assert clean_sections(text) == [ + Section(heading="", text="Lead line."), + Section(heading="First", text="First body."), + ] + + +def test_lead_section_heading_is_empty_string(): + text = "Only lead." + result = clean_sections(text) + assert len(result) == 1 + assert result[0].heading == "" + + +def test_nested_headings_levels_two_three_four(): + text = ( + "Lead.\n" + "== Level two ==\n" + "Two body.\n" + "=== Level three ===\n" + "Three body.\n" + "==== Level four ====\n" + "Four body." + ) + assert clean_sections(text) == [ + Section(heading="", text="Lead."), + Section(heading="Level two", text="Two body."), + Section(heading="Level three", text="Three body."), + Section(heading="Level four", text="Four body."), + ] + + +@pytest.mark.parametrize( + "heading", + [ + "References", + "SEE ALSO", + " external links ", + "Further Reading", + "NOTES", + "bibliography", + ], +) +def test_dropped_boilerplate_headings_are_removed(heading: str): + text = ( + f"== Intro ==\nKeep this.\n== {heading} ==\nDrop this.\n== After ==\nKeep too." + ) + assert clean_sections(text) == [ + Section(heading="Intro", text="Keep this."), + Section(heading="After", text="Keep too."), + ] + + +def test_empty_section_after_normalisation_is_dropped(): + text = "== Intro ==\nText.\n== Empty ==\n \n\n \n== Next ==\nMore." + assert clean_sections(text) == [ + Section(heading="Intro", text="Text."), + Section(heading="Next", text="More."), + ] + + +def test_nested_heading_under_dropped_section_is_kept(): + text = "== References ==\nRef list.\n=== Detail ===\nStill useful." + assert clean_sections(text) == [ + Section(heading="Detail", text="Still useful."), + ] + + +def test_whitespace_normalisation(): + text = "Line one. \n\n\n\nLine two. \n== Section ==\nBody. " + assert clean_sections(text) == [ + Section(heading="", text="Line one.\n\nLine two."), + Section(heading="Section", text="Body."), + ] diff --git a/tests/test_cli.py b/tests/test_cli.py index fe9624d..36aadfd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3,12 +3,15 @@ from pathlib import Path import httpx +import openai +import psycopg import pytest from swellsense.cli import main from swellsense.forecast.models import AUCKLAND, HourlyConditions, SpotForecast from swellsense.forecast.openmeteo import OPEN_METEO_ATTRIBUTION from swellsense.ingest.run import RunReport, SourceReport +from swellsense.processing.run import ProcessReport from swellsense.spots.models import Spot from swellsense.tides.linz import LINZ_ATTRIBUTION @@ -49,6 +52,83 @@ def test_summary_line_and_exit_1_when_an_article_fails(capsys, monkeypatch): ) +def test_process_summary_and_exit_0(capsys, monkeypatch): + report = ProcessReport(documents=3, embedded=5, unchanged=10, removed=1) + + monkeypatch.setattr("swellsense.cli.load_all", list) + monkeypatch.setattr("swellsense.cli.connect", lambda: _FakeConn()) + monkeypatch.setattr("swellsense.cli.process", lambda *args, **kwargs: report) + + with pytest.raises(SystemExit) as caught: + main(["process"]) + + assert caught.value.code == 0 + assert capsys.readouterr().out == ( + "process: 3 documents, 5 embedded, 10 unchanged, 1 removed, 0 failed\n" + ) + + +def test_process_exits_1_when_a_document_fails(capsys, monkeypatch): + report = ProcessReport( + documents=1, + failed=[{"id": "wikipedia/bad", "error": "boom"}], + ) + + monkeypatch.setattr("swellsense.cli.load_all", list) + monkeypatch.setattr("swellsense.cli.connect", lambda: _FakeConn()) + monkeypatch.setattr("swellsense.cli.process", lambda *args, **kwargs: report) + + with pytest.raises(SystemExit) as caught: + main(["process"]) + + assert caught.value.code == 1 + assert capsys.readouterr().out.endswith("1 failed\n") + + +def test_process_postgres_unreachable_exits_1(capsys, monkeypatch): + def fail(): + raise psycopg.OperationalError("connection refused") + + monkeypatch.setattr("swellsense.cli.load_all", list) + monkeypatch.setattr("swellsense.cli.connect", fail) + + with pytest.raises(SystemExit) as caught: + main(["process"]) + + assert caught.value.code == 1 + assert capsys.readouterr().err.strip() == "connection refused" + + +def test_process_ollama_unreachable_exits_1(capsys, monkeypatch): + conn = _FakeConn() + + def fail_process(*args, **kwargs): + del args, kwargs + raise openai.APIConnectionError(message="connection failed", request=None) + + monkeypatch.setattr("swellsense.cli.load_all", list) + monkeypatch.setattr("swellsense.cli.connect", lambda: conn) + monkeypatch.setattr("swellsense.cli.process", fail_process) + + with pytest.raises(SystemExit) as caught: + main(["process"]) + + assert caught.value.code == 1 + assert capsys.readouterr().err.strip() == "connection failed" + assert not conn.committed + + +class _FakeConn: + def __init__(self) -> None: + self.committed = False + + def commit(self) -> None: + self.committed = True + + def close(self) -> None: + return None + + def test_prints_one_line_per_source_and_exits_0(capsys, monkeypatch): report = _report( ("wikipedia", SourceReport(saved=8, missing=["Tide"])), diff --git a/tests/test_conditions_classifiers.py b/tests/test_conditions_classifiers.py index 40a6724..d82eee5 100644 --- a/tests/test_conditions_classifiers.py +++ b/tests/test_conditions_classifiers.py @@ -185,6 +185,12 @@ def test_missing_spot_does_not_crash(): (314, "outside"), (76, "outside"), (180, "outside"), + (329.9, "marginal"), # 0.1° outside 330° + (315.1, "marginal"), # 14.9° outside 330° + (314.9, "outside"), # 15.1° outside 330° + (60.1, "marginal"), # 0.1° outside 60° + (74.9, "marginal"), # 14.9° outside 60° + (75.1, "outside"), # 15.1° outside 60° ], ) def test_swell_window_crossing_north(direction: float, fit: str): @@ -205,6 +211,12 @@ def test_swell_window_crossing_north(direction: float, fit: str): (105, "marginal"), # 15° outside the end (344, "outside"), (106, "outside"), + (359.9, "marginal"), # 0.1° outside the start + (345.1, "marginal"), # 14.9° outside the start + (344.9, "outside"), # 15.1° outside the start + (90.1, "marginal"), # 0.1° outside the end + (104.9, "marginal"), # 14.9° outside the end + (105.1, "outside"), # 15.1° outside the end ], ) def test_swell_marginal_band_is_15_degrees(direction: float, fit: str): diff --git a/tests/test_db_chunks.py b/tests/test_db_chunks.py new file mode 100644 index 0000000..66ad749 --- /dev/null +++ b/tests/test_db_chunks.py @@ -0,0 +1,194 @@ +"""Integration tests for chunk store upsert, prune, and nearest.""" + +from __future__ import annotations + +from datetime import UTC, datetime + +import pytest + +from swellsense.db import ( + ChunkHit, + connect, + delete_chunks_except, + existing_hashes, + init_schema, + nearest, + upsert_chunks, + upsert_document, +) +from swellsense.ingest.models import RawDocument, count_words, hash_text +from swellsense.ingest.registry import Usage +from swellsense.ingest.store import slugify +from swellsense.processing.models import Chunk + +_DIM = 768 +_MODEL = "nomic-embed-text" + + +def _unit_vector(primary: int, sign: float = 1.0) -> list[float]: + vec = [0.0] * _DIM + vec[primary] = sign + return vec + + +def _raw_doc(source_id: str, title: str, *, usage: Usage = "open") -> RawDocument: + slug = slugify(title) + doc_id = f"{source_id}/{slug}" + text = f"Body text for {doc_id}." + return RawDocument( + id=doc_id, + source_id=source_id, + title=title, + url=f"https://example.test/{doc_id}", + license="CC BY-SA 4.0", + attribution="Test attribution", + usage=usage, + fetched_at=datetime(2026, 1, 1, tzinfo=UTC), + content_hash=hash_text(text), + word_count=count_words(text), + text=text, + ) + + +def _chunk( + doc: RawDocument, + index: int, + *, + section: str = "Intro", + text: str = "chunk text", + content_hash: str = "deadbeef", +) -> Chunk: + return Chunk( + id=f"{doc.id}#{index}", + document_id=doc.id, + index=index, + section=section, + text=text, + word_count=len(text.split()), + content_hash=content_hash, + title=doc.title, + url=doc.url, + license=doc.license, + attribution=doc.attribution, + usage=doc.usage, + ) + + +@pytest.fixture +def db_conn(): + conn = connect() + init_schema(conn) + conn.execute("BEGIN") + try: + yield conn + finally: + conn.execute("ROLLBACK") + conn.close() + + +@pytest.mark.db +def test_nearest_returns_closest_first(db_conn) -> None: + doc = _raw_doc("wikipedia", "Nearest Order Test") + upsert_document(db_conn, doc) + chunk_a = _chunk(doc, 0, text="alpha") + chunk_b = _chunk(doc, 1, text="beta") + vec_a = _unit_vector(0, 1.0) + vec_b = _unit_vector(1, 1.0) + upsert_chunks(db_conn, [chunk_a, chunk_b], [vec_a, vec_b], _MODEL) + + hits = nearest(db_conn, _unit_vector(0, 1.0), k=2) + + assert len(hits) == 2 + assert isinstance(hits[0], ChunkHit) + assert hits[0].id == chunk_a.id + assert hits[1].id == chunk_b.id + assert hits[0].distance <= hits[1].distance + + +@pytest.mark.db +def test_nearest_public_only_hides_private(db_conn) -> None: + open_doc = _raw_doc("wikipedia", "Nearest Open Test") + private_doc = _raw_doc("wikipedia", "Nearest Private Test", usage="private") + upsert_document(db_conn, open_doc) + upsert_document(db_conn, private_doc) + open_chunk = _chunk(open_doc, 0, text="open chunk") + private_chunk = _chunk(private_doc, 0, text="private chunk") + query = _unit_vector(2, 1.0) + upsert_chunks( + db_conn, + [open_chunk, private_chunk], + [_unit_vector(2, 1.0), _unit_vector(2, 1.0)], + _MODEL, + ) + + public_hits = nearest(db_conn, query, k=10, public_only=True) + all_hits = nearest(db_conn, query, k=10, public_only=False) + + assert {h.id for h in public_hits} == {open_chunk.id} + assert private_chunk.id in {h.id for h in all_hits} + + +@pytest.mark.db +def test_upsert_document_and_chunks_are_idempotent(db_conn) -> None: + doc = _raw_doc("wikipedia", "Idempotent Upsert Test") + chunk = _chunk(doc, 0) + embedding = _unit_vector(3) + upsert_document(db_conn, doc) + upsert_chunks(db_conn, [chunk], [embedding], _MODEL) + upsert_document(db_conn, doc) + upsert_chunks(db_conn, [chunk], [embedding], _MODEL) + + assert len(existing_hashes(db_conn, doc.id)) == 1 + count = db_conn.execute( + "SELECT COUNT(*) FROM chunks WHERE document_id = %s", + (doc.id,), + ).fetchone()[0] + assert count == 1 + + +@pytest.mark.db +def test_delete_chunks_except_prunes_stale_ids(db_conn) -> None: + doc = _raw_doc("wikipedia", "Prune Stale Test") + upsert_document(db_conn, doc) + keep = _chunk(doc, 0, content_hash="keep") + stale = _chunk(doc, 1, content_hash="stale") + vec = _unit_vector(4) + upsert_chunks(db_conn, [keep, stale], [vec, vec], _MODEL) + + delete_chunks_except(db_conn, doc.id, [keep.id]) + + remaining = { + row[0] + for row in db_conn.execute( + "SELECT id FROM chunks WHERE document_id = %s", + (doc.id,), + ).fetchall() + } + assert remaining == {keep.id} + + +@pytest.mark.db +def test_delete_chunks_except_empty_keep_removes_all_for_document_only( + db_conn, +) -> None: + doc_a = _raw_doc("wikipedia", "Prune Empty Doc A") + doc_b = _raw_doc("wikipedia", "Prune Empty Doc B") + upsert_document(db_conn, doc_a) + upsert_document(db_conn, doc_b) + chunk_a = _chunk(doc_a, 0) + chunk_b = _chunk(doc_b, 0) + vec = _unit_vector(5) + upsert_chunks(db_conn, [chunk_a, chunk_b], [vec, vec], _MODEL) + + delete_chunks_except(db_conn, doc_a.id, []) + + count_a = db_conn.execute( + "SELECT COUNT(*) FROM chunks WHERE document_id = %s", + (doc_a.id,), + ).fetchone()[0] + count_b = db_conn.execute( + "SELECT COUNT(*) FROM chunks WHERE document_id = %s", + (doc_b.id,), + ).fetchone()[0] + assert count_a == 0 + assert count_b == 1 diff --git a/tests/test_db_schema.py b/tests/test_db_schema.py new file mode 100644 index 0000000..097a77b --- /dev/null +++ b/tests/test_db_schema.py @@ -0,0 +1,163 @@ +"""Schema SQL checks and optional Postgres integration tests.""" + +from __future__ import annotations + +from pathlib import Path + +import psycopg +import pytest +from pgvector import Vector +from pgvector.psycopg import register_vector + +from swellsense.cli import main +from swellsense.db.connection import init_schema + +SCHEMA_PATH = Path(__file__).resolve().parents[1] / "src/swellsense/db/schema.sql" + + +def test_schema_sql_defines_tables_extension_and_index() -> None: + sql = SCHEMA_PATH.read_text(encoding="utf-8") + assert "CREATE EXTENSION IF NOT EXISTS vector" in sql + assert "IF NOT EXISTS" in sql + assert "documents" in sql + assert "chunks" in sql + assert "vector(768)" in sql + assert "chunks_embedding_hnsw" in sql + assert "vector_cosine_ops" in sql + + +def test_db_init_commits_before_close(capsys, monkeypatch) -> None: + calls: list[str] = [] + + class FakeConn: + def commit(self) -> None: + calls.append("commit") + + def close(self) -> None: + calls.append("close") + + fake = FakeConn() + + def fake_connect(): + return fake + + def fake_init_schema(conn) -> None: + assert conn is fake + + monkeypatch.setattr("swellsense.cli.connect", fake_connect) + monkeypatch.setattr("swellsense.cli.init_schema", fake_init_schema) + + with pytest.raises(SystemExit) as caught: + main(["db", "init"]) + + assert caught.value.code == 0 + assert calls == ["commit", "close"] + out = capsys.readouterr().out.strip() + assert out == "database schema initialized" + + +def test_db_init_connection_failure_exits_1(capsys, monkeypatch) -> None: + def fail_connect(): + raise psycopg.OperationalError("connection refused") + + monkeypatch.setattr("swellsense.cli.connect", fail_connect) + + with pytest.raises(SystemExit) as caught: + main(["db", "init"]) + + assert caught.value.code == 1 + err = capsys.readouterr().err.strip() + assert err + assert "\n" not in err + + +@pytest.mark.db +def test_db_init_persists_schema_on_new_connection(capsys) -> None: + from swellsense.config import get_settings + + with pytest.raises(SystemExit) as caught: + main(["db", "init"]) + assert caught.value.code == 0 + assert "database schema initialized" in capsys.readouterr().out + + conn = psycopg.connect(get_settings().database_url.get_secret_value()) + try: + chunks = conn.execute("SELECT to_regclass('public.chunks')").fetchone()[0] + documents = conn.execute("SELECT to_regclass('public.documents')").fetchone()[0] + assert chunks == "chunks" + assert documents == "documents" + finally: + conn.close() + + +@pytest.mark.db +def test_init_schema_is_idempotent_and_vector_round_trips() -> None: + from swellsense.config import get_settings + + url = get_settings().database_url.get_secret_value() + conn = psycopg.connect(url) + try: + init_schema(conn) + init_schema(conn) + finally: + conn.close() + + conn = psycopg.connect(url) + try: + register_vector(conn) + embedding = Vector([float(i) for i in range(768)]) + conn.execute("BEGIN") + try: + conn.execute( + """ + INSERT INTO documents ( + id, source_id, title, url, license, attribution, usage + ) VALUES (%s, %s, %s, %s, %s, %s, %s) + """, + ( + "doc-test", + "wikipedia", + "Test", + "https://example.test/doc", + "CC BY-SA 4.0", + "Example attribution", + "open", + ), + ) + conn.execute( + """ + INSERT INTO chunks ( + id, document_id, "index", section, text, word_count, + content_hash, title, url, license, attribution, usage, + embedding, embedding_model + ) VALUES ( + %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s + ) + """, + ( + "doc-test#0", + "doc-test", + 0, + "Intro", + "hello", + 1, + "abc123", + "Test", + "https://example.test/doc", + "CC BY-SA 4.0", + "Example attribution", + "open", + embedding, + "nomic-embed-text", + ), + ) + row = conn.execute( + "SELECT embedding FROM chunks WHERE id = %s", + ("doc-test#0",), + ).fetchone() + assert row is not None + assert row[0] == embedding + finally: + conn.execute("ROLLBACK") + finally: + conn.close() diff --git a/tests/test_llm.py b/tests/test_llm.py index fa1d753..c462c51 100644 --- a/tests/test_llm.py +++ b/tests/test_llm.py @@ -2,7 +2,9 @@ from types import SimpleNamespace -from swellsense.llm import chat, complete_message +import pytest + +from swellsense.llm import chat, complete_message, embed def _install(monkeypatch, message, created): @@ -47,3 +49,137 @@ def test_chat_returns_text(monkeypatch): assert chat("hi", system="be brief") == "hello" assert created["messages"][0] == {"role": "system", "content": "be brief"} assert created["messages"][1] == {"role": "user", "content": "hi"} + + +def _embed_settings(*, batch_size: int = 32, dimensions: int = 768): + return SimpleNamespace( + embedding_model="nomic-embed-text", + embedding_dimensions=dimensions, + embedding_batch_size=batch_size, + ) + + +def _vector(dimensions: int, seed: float) -> list[float]: + return [seed + i * 0.001 for i in range(dimensions)] + + +def _install_embed(monkeypatch, *, batch_size: int = 32, dimensions: int = 768): + create_calls: list[dict] = [] + + def create(**kwargs): + create_calls.append(kwargs) + prefixed: list[str] = kwargs["input"] + data = [ + SimpleNamespace( + index=i, + embedding=_vector(dimensions, float(len(create_calls)) + i * 0.1), + ) + for i in range(len(prefixed)) + ] + return SimpleNamespace(data=data) + + client = SimpleNamespace(embeddings=SimpleNamespace(create=create)) + monkeypatch.setattr("swellsense.llm.embeddings.get_client", lambda: client) + monkeypatch.setattr( + "swellsense.llm.embeddings.get_settings", + lambda: _embed_settings(batch_size=batch_size, dimensions=dimensions), + ) + return create_calls + + +def test_embed_empty_returns_without_api_call(monkeypatch): + create_calls = _install_embed(monkeypatch) + + assert embed([], "document") == [] + assert create_calls == [] + + +def test_embed_applies_document_prefix(monkeypatch): + create_calls = _install_embed(monkeypatch) + + embed(["alpha", "beta"], "document") + + assert len(create_calls) == 1 + assert create_calls[0]["model"] == "nomic-embed-text" + assert create_calls[0]["input"] == [ + "search_document: alpha", + "search_document: beta", + ] + assert "dimensions" not in create_calls[0] + + +def test_embed_applies_query_prefix(monkeypatch): + create_calls = _install_embed(monkeypatch) + + embed(["where to surf"], "query") + + assert create_calls[0]["input"] == ["search_query: where to surf"] + + +def test_embed_batches_across_multiple_create_calls(monkeypatch): + create_calls = _install_embed(monkeypatch, batch_size=2) + + texts = ["a", "b", "c", "d", "e"] + result = embed(texts, "document") + + assert len(create_calls) == 3 + assert [len(c["input"]) for c in create_calls] == [2, 2, 1] + assert len(result) == 5 + + +def test_embed_preserves_order_when_batch_indexes_shuffled(monkeypatch): + dimensions = 768 + create_calls: list[dict] = [] + + def create(**kwargs): + create_calls.append(kwargs) + # Return indexes out of order; embed() must sort by index. + data = [ + SimpleNamespace(index=1, embedding=_vector(dimensions, 1.0)), + SimpleNamespace(index=0, embedding=_vector(dimensions, 0.0)), + ] + return SimpleNamespace(data=data) + + client = SimpleNamespace(embeddings=SimpleNamespace(create=create)) + monkeypatch.setattr("swellsense.llm.embeddings.get_client", lambda: client) + monkeypatch.setattr( + "swellsense.llm.embeddings.get_settings", + lambda: _embed_settings(batch_size=32, dimensions=dimensions), + ) + + result = embed(["first", "second"], "document") + + assert result[0][0] == pytest.approx(0.0) + assert result[1][0] == pytest.approx(1.0) + + +def test_embed_raises_on_dimension_mismatch(monkeypatch): + _install_embed(monkeypatch, dimensions=768) + + def create(**kwargs): + return SimpleNamespace(data=[SimpleNamespace(index=0, embedding=[0.0] * 4)]) + + client = SimpleNamespace(embeddings=SimpleNamespace(create=create)) + monkeypatch.setattr("swellsense.llm.embeddings.get_client", lambda: client) + + with pytest.raises(ValueError, match="4 != expected 768"): + embed(["x"], "document") + + +def test_embed_raises_when_response_count_mismatch(monkeypatch): + dimensions = 768 + monkeypatch.setattr( + "swellsense.llm.embeddings.get_settings", + lambda: _embed_settings(batch_size=32, dimensions=dimensions), + ) + + def create(**kwargs): + return SimpleNamespace( + data=[SimpleNamespace(index=0, embedding=_vector(dimensions, 0.0))] + ) + + client = SimpleNamespace(embeddings=SimpleNamespace(create=create)) + monkeypatch.setattr("swellsense.llm.embeddings.get_client", lambda: client) + + with pytest.raises(ValueError, match="1 != expected 2"): + embed(["first", "second"], "document") diff --git a/tests/test_process_run.py b/tests/test_process_run.py new file mode 100644 index 0000000..4156700 --- /dev/null +++ b/tests/test_process_run.py @@ -0,0 +1,252 @@ +import hashlib +import struct +from datetime import UTC, datetime + +import openai +import pytest + +from swellsense.config import Settings +from swellsense.ingest.models import RawDocument +from swellsense.ingest.store import slugify +from swellsense.processing.run import process + +_DIM = 768 +_MODEL = "test-embed" + + +def _document(**overrides) -> RawDocument: + text = overrides.pop("text", "Lead only.") + title = overrides.pop("title", "Process test") + source_id = overrides.pop("source_id", "wikipedia") + values = { + "id": f"{source_id}/{slugify(title)}", + "source_id": source_id, + "title": title, + "url": "https://example.com/wiki/process_test", + "license": "CC BY-SA 4.0", + "attribution": "Test contributors", + "usage": "open", + "fetched_at": datetime(2026, 10, 14, 12, 0, tzinfo=UTC), + "content_hash": hashlib.sha256(text.encode()).hexdigest(), + "word_count": len(text.split()), + "text": text, + } + values.update(overrides) + return RawDocument(**values) + + +def _words(n: int, prefix: str = "w") -> str: + return " ".join(f"{prefix}{i}" for i in range(n)) + + +def _vector_for(text: str) -> list[float]: + digest = hashlib.sha256(text.encode()).digest() + out: list[float] = [] + while len(out) < _DIM: + for i in range(0, len(digest) - 3, 4): + value = struct.unpack(">I", digest[i : i + 4])[0] + out.append((value % 10_000) / 10_000.0) + if len(out) == _DIM: + break + digest = hashlib.sha256(digest).digest() + return out + + +class InMemoryChunkStore: + """Minimal ChunkStore for unit tests.""" + + def __init__(self) -> None: + self.chunks: dict[str, tuple[str, str]] = {} + + def upsert_document(self, doc: RawDocument) -> None: + del doc + + def existing_hashes(self, document_id: str) -> dict[str, tuple[str, str]]: + prefix = f"{document_id}#" + return { + chunk_id: pair + for chunk_id, pair in self.chunks.items() + if chunk_id.startswith(prefix) + } + + def upsert_chunks(self, chunks, embeddings: list[list[float]], model: str) -> None: + if len(chunks) != len(embeddings): + msg = "chunks and embeddings length mismatch" + raise ValueError(msg) + for chunk, embedding in zip(chunks, embeddings, strict=True): + if len(embedding) != _DIM: + msg = f"bad embedding length for {chunk.id}" + raise ValueError(msg) + self.chunks[chunk.id] = (chunk.content_hash, model) + + def delete_chunks_except(self, document_id: str, keep_ids: list[str]) -> None: + keep = set(keep_ids) + prefix = f"{document_id}#" + for chunk_id in list(self.chunks): + if chunk_id.startswith(prefix) and chunk_id not in keep: + del self.chunks[chunk_id] + + +@pytest.fixture +def chunk_settings(monkeypatch): + settings = Settings( + chunk_words=12, + chunk_overlap_words=2, + embedding_model=_MODEL, + embedding_dimensions=_DIM, + ) + monkeypatch.setattr("swellsense.processing.run.get_settings", lambda: settings) + return settings + + +def _multi_chunk_doc() -> RawDocument: + body = _words(24) + text = f"Short lead.\n\n== Surf ==\n{body}" + return _document(title="multi", text=text) + + +def _make_embed_fn(calls: list[list[str]], fail_if: str | None = None): + def embed_fn(texts: list[str]) -> list[list[float]]: + if fail_if is not None and any(fail_if in text for text in texts): + raise RuntimeError("embed failed") + calls.append(list(texts)) + return [_vector_for(text) for text in texts] + + return embed_fn + + +def test_empty_docs_returns_zeros(chunk_settings): + store = InMemoryChunkStore() + calls: list[list[str]] = [] + report = process([], _make_embed_fn(calls), store) + assert report.documents == 0 + assert report.embedded == 0 + assert report.unchanged == 0 + assert report.removed == 0 + assert report.failed == [] + assert calls == [] + + +def test_first_run_embeds_every_chunk(chunk_settings): + doc = _multi_chunk_doc() + store = InMemoryChunkStore() + calls: list[list[str]] = [] + report = process([doc], _make_embed_fn(calls), store) + assert report.failed == [] + assert report.documents == 1 + assert report.embedded > 0 + assert report.unchanged == 0 + assert report.removed == 0 + assert len(calls) == 1 + assert len(calls[0]) == report.embedded + + +def test_second_run_skips_embed(chunk_settings): + doc = _multi_chunk_doc() + store = InMemoryChunkStore() + calls: list[list[str]] = [] + embed_fn = _make_embed_fn(calls) + first = process([doc], embed_fn, store) + assert first.embedded > 0 + calls.clear() + second = process([doc], embed_fn, store) + assert second.failed == [] + assert second.embedded == 0 + assert second.unchanged == first.embedded + assert second.removed == 0 + assert calls == [] + + +def test_changed_doc_reembeds_and_prunes(chunk_settings): + doc = _multi_chunk_doc() + store = InMemoryChunkStore() + calls: list[list[str]] = [] + embed_fn = _make_embed_fn(calls) + process([doc], embed_fn, store) + old_ids = set(store.existing_hashes(doc.id)) + + new_text = _words(4) + changed = _document( + title="multi", + text=new_text, + content_hash=hashlib.sha256(new_text.encode()).hexdigest(), + ) + calls.clear() + second = process([changed], embed_fn, store) + new_ids = set(store.existing_hashes(doc.id)) + pruned = old_ids - new_ids + + assert second.failed == [] + assert pruned + assert second.removed == len(pruned) + assert second.embedded == len(new_ids) + assert calls and len(calls[0]) == second.embedded + + +def test_model_change_reembeds_all_chunks(chunk_settings, monkeypatch): + doc = _multi_chunk_doc() + store = InMemoryChunkStore() + calls: list[list[str]] = [] + first = process([doc], _make_embed_fn(calls), store) + assert first.embedded > 0 + + settings = Settings( + chunk_words=12, + chunk_overlap_words=2, + embedding_model="other-model", + embedding_dimensions=_DIM, + ) + monkeypatch.setattr("swellsense.processing.run.get_settings", lambda: settings) + calls.clear() + second = process([doc], _make_embed_fn(calls), store) + assert second.failed == [] + assert second.embedded == first.embedded + assert second.unchanged == 0 + assert len(calls) == 1 + assert len(calls[0]) == second.embedded + + +def test_one_failing_document_continues(chunk_settings): + good = _document(title="good", text="== Surf ==\n" + _words(10)) + bad = _document(title="bad", text="== Surf ==\n" + _words(10) + " FAILMARKER") + after = _document(title="after", text="== Surf ==\n" + _words(10)) + store = InMemoryChunkStore() + calls: list[list[str]] = [] + embed_fn = _make_embed_fn(calls, fail_if="FAILMARKER") + report = process([good, bad, after], embed_fn, store) + + assert len(report.failed) == 1 + assert report.failed[0]["id"] == bad.id + assert "embed failed" in report.failed[0]["error"] + assert store.existing_hashes(good.id) + assert store.existing_hashes(after.id) + assert not store.existing_hashes(bad.id) + + +def test_openai_api_error_propagates(chunk_settings): + first = _document(title="first", text="== Surf ==\n" + _words(10)) + second = _document(title="second", text="== Surf ==\n" + _words(10)) + store = InMemoryChunkStore() + calls: list[list[str]] = [] + + def embed_fn(texts: list[str]) -> list[list[float]]: + calls.append(list(texts)) + raise openai.APIConnectionError(message="connection failed", request=None) + + with pytest.raises(openai.APIConnectionError, match="connection failed"): + process([first, second], embed_fn, store) + + assert len(calls) == 1 + assert not store.existing_hashes(second.id) + + +def test_store_value_error_is_recorded(chunk_settings): + doc = _multi_chunk_doc() + + class BadStore(InMemoryChunkStore): + def upsert_chunks(self, chunks, embeddings, model): + raise ValueError("store rejected") + + store = BadStore() + report = process([doc], _make_embed_fn([]), store) + assert report.failed == [{"id": doc.id, "error": "store rejected"}] diff --git a/uv.lock b/uv.lock index 84319a8..d98ec9d 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.13" [[package]] @@ -238,6 +238,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, ] +[[package]] +name = "pgvector" +version = "0.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f8/23/96aa38899fbf8e103766db608d6e42acac269a96e08f3003fe9da3396fed/pgvector-0.5.1.tar.gz", hash = "sha256:94998a54b801b1075d623b8fa677fcb8210a7977b88f8e2203ab115c155af2e4", size = 35714, upload-time = "2026-10-09T01:50:22.779Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/8d/a9c2a531da0ebb54b4a7174450e8534a39db112a141ae3a437de28420111/pgvector-0.5.1-py3-none-any.whl", hash = "sha256:ec5bcd5ffaefe6ecb2dcc9564ca921d284564b969183bc837a144604773af8ea", size = 31056, upload-time = "2026-10-09T01:50:21.614Z" }, +] + [[package]] name = "pluggy" version = "1.6.0" @@ -247,6 +256,63 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] +[[package]] +name = "psycopg" +version = "3.3.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/26/3ea4ca5eaea1c0debcdf7ee7c1613fbe721dc27a03c461c0817ffd8a0601/psycopg-3.3.6.tar.gz", hash = "sha256:c081f2250df751a943036e42db6df4571c66cd0aabe8291a7a506512b12007d2", size = 168171, upload-time = "2026-09-18T13:22:55.152Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4e/de/748bd7609c71cae5d737f0ba9192f19329f70180ecda8fff3cac02c5abe3/psycopg-3.3.6-py3-none-any.whl", hash = "sha256:a1db9f7148b06a28606767efaca51fa6f9398c5c0a3810519be69d7000bdb631", size = 215490, upload-time = "2026-09-18T13:15:29.374Z" }, +] + +[package.optional-dependencies] +binary = [ + { name = "psycopg-binary", marker = "implementation_name != 'pypy'" }, +] + +[[package]] +name = "psycopg-binary" +version = "3.3.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b4/c3/c072584b69ad44a747b448cfc9766fecb8aae56e372a017e2ef668790057/psycopg_binary-3.3.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5ad8f35e67cc16d1fad1fa8c88972dc9b3a3141ea67897399904edab96a301b6", size = 4712284, upload-time = "2026-09-18T13:19:13.451Z" }, + { url = "https://files.pythonhosted.org/packages/0a/b9/4283b785339e8e2318d03048994b093d650ea6289fabaa806b765dc0d449/psycopg_binary-3.3.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:373704aea331d3f3e3402c125a1543f5875e2986ebb54f97d1647942161f803f", size = 4772031, upload-time = "2026-09-18T13:19:18.524Z" }, + { url = "https://files.pythonhosted.org/packages/6f/72/7a1321d359246769fff1affffbd0132785a28f7f63c18524c15a502398f4/psycopg_binary-3.3.6-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:b82491019b884d62318b5f30706c3d7e6d4e5a6cb7eabcb3edc0c1b0fdaceae9", size = 5556392, upload-time = "2026-09-18T13:19:24.418Z" }, + { url = "https://files.pythonhosted.org/packages/de/b0/c6f8a0585a5dacbea74e130bcfc66629390e8f5bbc79d2a8e806e8952150/psycopg_binary-3.3.6-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cec5ea900390897d0b46130f60bc2883bf19c314f9044235217c8be88b0ef269", size = 5237855, upload-time = "2026-09-18T13:19:31.257Z" }, + { url = "https://files.pythonhosted.org/packages/e2/fc/c3a7a8bbef7e945ec584ac61d460a612363ea398511cd0e220242b1d69f1/psycopg_binary-3.3.6-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:98c02090d88f2ebc0ec1e8da538f77d225ce0fffecf372aa39262e62a1b054ef", size = 6833856, upload-time = "2026-09-18T13:19:43.622Z" }, + { url = "https://files.pythonhosted.org/packages/a9/f2/8e80b921db728ebb68fc105bd7c4277f908210ad755bd6481d5ea7add740/psycopg_binary-3.3.6-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ee2c4728c691245e24501fcd7a97b5b381236b9985bc445bba88cdce7d1b5784", size = 5070730, upload-time = "2026-09-18T13:19:49.968Z" }, + { url = "https://files.pythonhosted.org/packages/54/6a/5b313e0c5348244f0e973aff3258bf86766656256d5ece8d541a53e35b4a/psycopg_binary-3.3.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f19cc87343eaa55255e76b31259a570072ac95d6ae82c92dd34b97691f5e49dc", size = 4598089, upload-time = "2026-09-18T13:19:56.426Z" }, + { url = "https://files.pythonhosted.org/packages/32/e9/db7f76ec24bf6699e92bf604e5c4bae10664a681a8999ef42aa0faf0f2c6/psycopg_binary-3.3.6-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:fdccb3a0e184b03e9baa673b15a809cf36c339c85dbda0ebc25a698846dfbee8", size = 4278481, upload-time = "2026-09-18T13:20:04.681Z" }, + { url = "https://files.pythonhosted.org/packages/61/83/72c67013656f4d6b547caabffb193e91d57e63f90eefdcc6d045c400e97d/psycopg_binary-3.3.6-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:9892188bb15e5803beb51afe8a25add6b56be391a53058e8bca03b74e1e6bf22", size = 4009229, upload-time = "2026-09-18T13:20:11.905Z" }, + { url = "https://files.pythonhosted.org/packages/82/35/5e4500df2c999eb0faed8b184e6958b834172128274f06167a5deef4c19c/psycopg_binary-3.3.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3af90f92769d8cc10f94515ee7a0aef36ea85ca733a0ce22858f6e0953f41138", size = 4321467, upload-time = "2026-09-18T13:20:17.949Z" }, + { url = "https://files.pythonhosted.org/packages/55/7f/e350e1cf498ba2565c3f87b12f429d2012eb86b76c2b3845a19ee5fbb4d6/psycopg_binary-3.3.6-cp313-cp313-win_amd64.whl", hash = "sha256:0ebfad5d131de9f892ae9e70cc7616207768b6714b66a52d4612b8ceaf78b372", size = 3658179, upload-time = "2026-09-18T13:20:22.691Z" }, + { url = "https://files.pythonhosted.org/packages/6d/b9/60711317c284a442511644ea7185b56ebe627606d6741e732cd16108c47b/psycopg_binary-3.3.6-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:b3f75dee0f9afafabe4edc52c4842f1e1878ed2069bd05b22d6fe961e97e4dba", size = 4720512, upload-time = "2026-09-18T13:20:29.278Z" }, + { url = "https://files.pythonhosted.org/packages/63/da/28befc84454cbc6374550de7746f591f8fe1b6165c1fce249652cc8291c4/psycopg_binary-3.3.6-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:5927b7ba63153cd8e9862987290a2b783a5c590daf2a4ef981700cc3569166d4", size = 4782318, upload-time = "2026-09-18T13:20:35.401Z" }, + { url = "https://files.pythonhosted.org/packages/a4/8a/0d21c2c833cdc0d4244c77e858e0ed37fa2abec2623be4fd686f617109ce/psycopg_binary-3.3.6-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:0bf08b749cc144f33b44a91b78e3f71c60eb07963746a0df5a100b36ce3d7475", size = 5567460, upload-time = "2026-09-18T13:20:41.902Z" }, + { url = "https://files.pythonhosted.org/packages/49/6d/7692d0d4e656b6cc9868d8acc2e3b42f17a0db4a625400a6d093cb0533a1/psycopg_binary-3.3.6-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:31cd942c23f613276b81a6e6598cefa12960058b0f46e1e874b540c793f6aca5", size = 5246902, upload-time = "2026-09-18T13:20:47.661Z" }, + { url = "https://files.pythonhosted.org/packages/d4/c1/b8a1f18fb1b7558a17f57f7cb3fc8bc93189feea2958925950b3acb15743/psycopg_binary-3.3.6-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4690cf67738f0e0e49a32aeec99bf0e4595cc2b4f1af984a4345394b1dcff91a", size = 6847192, upload-time = "2026-09-18T13:20:56.874Z" }, + { url = "https://files.pythonhosted.org/packages/a5/76/404f33519167c65cca88ec4998776f1dbebccc301ee977f0e62c47fb0826/psycopg_binary-3.3.6-cp314-cp314-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ad1c785e784cfd87e8436c6b7702f2d321fc39601bbaf29bc63a41a867091638", size = 5079573, upload-time = "2026-09-18T13:21:04.155Z" }, + { url = "https://files.pythonhosted.org/packages/f0/d9/79e8fbc8f37262a415f3550f0bcc5f98037442bf3d12ef6cbae2056655ae/psycopg_binary-3.3.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:79a2a1c3449f6c3409427078ed1cec10de79f3023cb5f2504f0597d350ad46c7", size = 4613633, upload-time = "2026-09-18T13:21:10.664Z" }, + { url = "https://files.pythonhosted.org/packages/d4/47/96225db74be7d2ce04b3a58678b53cda610225055edf5faa775c9f501d8b/psycopg_binary-3.3.6-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:86147cb5d140341c3363fb5bacce31f8d5543902a46699d3c536b101bbceaf9e", size = 4293375, upload-time = "2026-09-18T13:21:16.027Z" }, + { url = "https://files.pythonhosted.org/packages/2a/d2/18e9c779a5efd565250329adaf529ecc2b8b2ed5be5cb0f6ccee208cbfd9/psycopg_binary-3.3.6-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:7308c93cf0b19bbaf8e6ff0a6ad50d3c442385739245fe15a8d593bf841734a6", size = 4019883, upload-time = "2026-09-18T13:21:21.587Z" }, + { url = "https://files.pythonhosted.org/packages/ef/28/0cc654afc6c2cda982767f5679d3646b30b1ec86545bdaa9402202d6776c/psycopg_binary-3.3.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:05a83ac9fd52b9bca7cb5ab04b3691163170bd16f53defa27216ea3aa07ee781", size = 4332607, upload-time = "2026-09-18T13:21:27.63Z" }, + { url = "https://files.pythonhosted.org/packages/f1/3e/0a753a74fbd7aef120f286c016e09d3cc3f1daf7688f4a145d27281260b2/psycopg_binary-3.3.6-cp314-cp314-win_amd64.whl", hash = "sha256:1fbd30e537dab22cafdf080608f10148fe2a5f3a61294ddb5113caac8a623840", size = 3755671, upload-time = "2026-09-18T13:21:33.855Z" }, + { url = "https://files.pythonhosted.org/packages/0e/b1/a372b9c02aea50148e71c9853e19efca8fa5ae2010a8e27243b9b8f790c0/psycopg_binary-3.3.6-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:bf8c8481d026b85dd70c5fa7dde85b2333aed0b32a2602bcd38a900cbd78a49c", size = 4719571, upload-time = "2026-09-18T13:21:41.437Z" }, + { url = "https://files.pythonhosted.org/packages/65/7c/811e3828c6b82e2f10c6c9cdd963cfc66f3e024026e5a69ac18530bad984/psycopg_binary-3.3.6-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:b599defe9190b17e9907c8b4d114c181e702c87efcd1b8a0ad40971cdcc4634a", size = 4781230, upload-time = "2026-09-18T13:21:49.516Z" }, + { url = "https://files.pythonhosted.org/packages/3e/15/9a784eed813ea9e97c294af3ead63d02b7b203502c66380336c50065e441/psycopg_binary-3.3.6-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:b8ece331509f7a975b90501f41e83ad905e4141753fedf3f2711b2bc70a8efbc", size = 5566111, upload-time = "2026-09-18T13:21:58.089Z" }, + { url = "https://files.pythonhosted.org/packages/68/16/47194e002007c27337b11e49bf459c4b19727463f9aff2e1a90917bcc806/psycopg_binary-3.3.6-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c61617eaae0112ca154da87ffb99b73af2c74067acac28dfb9a4455b019dff2e", size = 5249963, upload-time = "2026-09-18T13:22:06.695Z" }, + { url = "https://files.pythonhosted.org/packages/53/84/5dcf9f310b11f0675cd860c6b2c70f58ce61798a3ee3f6f962b53fa358ca/psycopg_binary-3.3.6-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c6d19cb4999d03231e8730a5f66c8f5068bc3b532677eb39dab0f600bff3e312", size = 6847925, upload-time = "2026-09-18T13:22:13.088Z" }, + { url = "https://files.pythonhosted.org/packages/f3/06/1957a06dc22963c418c27b284929579de84f29c37ad1abe6dc6ee9e8cf25/psycopg_binary-3.3.6-cp315-cp315-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e8cbb54454dbf1bbf2ff08dd7693e8d94ac94b1a20f70f4b3b813d52ecb5cbc1", size = 5087720, upload-time = "2026-09-18T13:22:17.959Z" }, + { url = "https://files.pythonhosted.org/packages/21/43/ac07d042bae99b57bf123bb473632f29af544008094da0ffd285ab8011e2/psycopg_binary-3.3.6-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:dc75da5a20951049f7b773145f998f69d181adad9c58a0ff36e0cf1d73c10e10", size = 4613412, upload-time = "2026-09-18T13:22:26.719Z" }, + { url = "https://files.pythonhosted.org/packages/aa/b1/019156fbeafcefb4cccc9d109de4699493bceb8313c7545c8349e089dfbc/psycopg_binary-3.3.6-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:955e3dd94da361e052d2e49acf591017158dc8f8ed2c8a42c2e3943403c39dc2", size = 4292618, upload-time = "2026-09-18T13:22:33.042Z" }, + { url = "https://files.pythonhosted.org/packages/5d/0f/62113dc6b1df65983a1f2fc816c04b1edfa22f2ae9d4abee74ed267f4a96/psycopg_binary-3.3.6-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:c7753871eb57e6a5f4646f6168590c6653073dea5e9e720b201c8875332df4c8", size = 4027121, upload-time = "2026-09-18T13:22:38.334Z" }, + { url = "https://files.pythonhosted.org/packages/5d/d5/cf0cbd1ea5a7d8167fe2c6953efde19101f7b193bd61a23e6d622ad6854c/psycopg_binary-3.3.6-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:303732e798fe6729f8e12021b9c96107df8e95ecec4dd487c67b98ec2a59435e", size = 4336388, upload-time = "2026-09-18T13:22:45.576Z" }, + { url = "https://files.pythonhosted.org/packages/98/33/e2a5b36edf8aa422f6fa4b894756eb33dc93b36df5f65121280bb8b929c4/psycopg_binary-3.3.6-cp315-cp315-win_amd64.whl", hash = "sha256:2f122603f36050937982abf9668d8bc4769a79f7c93a65013b1c49f1cab7b56b", size = 3756154, upload-time = "2026-09-18T13:22:51.283Z" }, +] + [[package]] name = "pydantic" version = "2.14.1" @@ -474,6 +540,8 @@ source = { editable = "." } dependencies = [ { name = "httpx" }, { name = "openai" }, + { name = "pgvector" }, + { name = "psycopg", extra = ["binary"] }, { name = "pydantic" }, { name = "pydantic-settings" }, { name = "pyyaml" }, @@ -489,6 +557,8 @@ dev = [ requires-dist = [ { name = "httpx", specifier = ">=0.28.1" }, { name = "openai", specifier = ">=3.29.0" }, + { name = "pgvector", specifier = ">=0.5.1" }, + { name = "psycopg", extras = ["binary"], specifier = ">=3.3.6" }, { name = "pydantic", specifier = ">=2.14.1" }, { name = "pydantic-settings", specifier = ">=2.15.0" }, { name = "pyyaml", specifier = ">=6.0.3" }, @@ -529,3 +599,12 @@ sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c wheels = [ { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, ] + +[[package]] +name = "tzdata" +version = "2026.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/68/f1b440335057bfce71b6e50a9d09445aa2ecbd08359a337976627b8409e7/tzdata-2026.5.tar.gz", hash = "sha256:8cc73c0a0bfca7dbfa59235d60b2eff82231dee33f53d206db1acd9173cfc0a7", size = 200404, upload-time = "2026-10-03T09:23:14.143Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/21/1e5995a1c920cce14e4bffae20c665ec10e7ed03ab25e006cd741092b718/tzdata-2026.5-py2.py3-none-any.whl", hash = "sha256:b683bd1b6659ddcd810ff02ad09ba821d4bf1065072805063eb35c49617905ac", size = 347996, upload-time = "2026-10-03T09:23:12.535Z" }, +]