diff --git a/AGENTS.md b/AGENTS.md index 5f582c5..6a2be76 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,7 +56,7 @@ 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 and chunking raw documents +- `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 @@ -76,6 +76,7 @@ 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 @@ -85,7 +86,7 @@ code, with short docstrings explaining why. ## 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 @@ -118,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 3c78792..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. @@ -56,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 | @@ -84,7 +86,7 @@ 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 and chunking raw documents + processing/ cleaning, chunking, and the process run db/ local Postgres connection and schema spots/ spot profiles tides/ LINZ tide predictions and tide state @@ -102,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/docs/plans/stage-3.md b/docs/plans/stage-3.md index 7ae81e8..e979dfb 100644 --- a/docs/plans/stage-3.md +++ b/docs/plans/stage-3.md @@ -16,7 +16,7 @@ - [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) -- [ ] Slice 6: `swellsense process` end to end +- [x] Slice 6: `swellsense process` end to end Slices are run one at a time, in the order above. diff --git a/src/swellsense/cli.py b/src/swellsense/cli.py index 4fbe63c..c5e0eab 100644 --- a/src/swellsense/cli.py +++ b/src/swellsense/cli.py @@ -6,6 +6,7 @@ ``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 @@ -13,6 +14,7 @@ from datetime import date, datetime, timedelta import httpx +import openai import psycopg from swellsense.conditions.rating import HourRating @@ -28,6 +30,9 @@ 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 ( @@ -55,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" ) @@ -114,6 +124,8 @@ def _main(argv: list[str] | None = None) -> int: 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": @@ -140,6 +152,29 @@ def _db_init() -> int: 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: @@ -439,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/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/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_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"}]