diff --git a/README.md b/README.md index f980a9b..eb91238 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,10 @@ make start # opens a demo project with six AI papers already ingested Nothing is sent anywhere unless you pick a provider that is not offline. +Ingestion analyzes up to two sources at a time by default. Set `ingestion_workers` +in your project's `settings/settings.json` to `1` for serial ingestion or `3` +to allow three sources at a time. Wiki updates are applied in queue order. + ## How it compares | | gknowledge | LLM Wiki | Tolaria | OpenKnowledge | Reor (archived) | Khoj | diff --git a/gknowledge/core/extraction.py b/gknowledge/core/extraction.py index 09cd76a..ec77594 100644 --- a/gknowledge/core/extraction.py +++ b/gknowledge/core/extraction.py @@ -283,9 +283,16 @@ def alias_of(key: str) -> str | None: # -- orchestration ------------------------------------------------------- def ingest_source(self, source: Source, text: str) -> ExtractionResult: analysis = self.analyze(text) + result = self.persist_analysis(source, text, analysis, fallback=self.last_fallback) + self.rebuild_catalog() + return result + + def persist_analysis(self, source: Source, text: str, analysis: dict, *, + fallback: str = "") -> ExtractionResult: + """Generate and write one source's pages against the current wiki.""" existing = {p.slug for p in self.project.store.list_pages()} result = self.generate(source, analysis, existing, text) - result.fallback = self.last_fallback + result.fallback = fallback source_slug = None for page in result.pages: @@ -303,8 +310,6 @@ def ingest_source(self, source: Source, text: str) -> ExtractionResult: for item in result.reviews: self.project.store.upsert_review(item) - self.writer.rebuild_index() - self.writer.rebuild_overview() self.writer.append_log( "ingest", f"{source.title}: {len(result.pages)} pages, {len(result.reviews)} reviews" @@ -313,6 +318,10 @@ def ingest_source(self, source: Source, text: str) -> ExtractionResult: ) return result + def rebuild_catalog(self) -> None: + self.writer.rebuild_index() + self.writer.rebuild_overview() + # -- helpers ----------------------------------------------------------------- def _render_source_summary(source: Source, analysis: dict, diff --git a/gknowledge/core/ingestion.py b/gknowledge/core/ingestion.py index 433fa81..a3efd84 100644 --- a/gknowledge/core/ingestion.py +++ b/gknowledge/core/ingestion.py @@ -1,10 +1,9 @@ """Ingestion queue: import → parse → extract, with persistence and recovery. Jobs live in the store, so a queue survives restarts and can be resumed. Import -is cache-aware: a file whose SHA-256 already exists is skipped (its job is -marked ``SKIPPED``) instead of re-spending an LLM call. Processing is serial to -avoid concurrent provider calls, and can run synchronously (tests, CLI) or on a -background thread (UI) via :meth:`process_pending`. +is cache-aware: a file whose SHA-256 already exists is skipped instead of +re-spending an LLM call. Sources are analyzed concurrently and applied to the +wiki in queue order. Processing can run synchronously or on a background thread. """ from __future__ import annotations @@ -13,6 +12,7 @@ import re import shutil import threading +from concurrent.futures import Future, ThreadPoolExecutor from dataclasses import dataclass from pathlib import Path from typing import Callable @@ -25,7 +25,7 @@ from .knowledge import KnowledgeWriter from .lint import origin_of from .models import Job, JobState, PageKind, Source, SourceStatus, new_id, now -from .project import Project +from .project import DEFAULT_INGESTION_WORKERS, Project # progress(event: str, job: Job, message: str) -> None Progress = Callable[[str, Job, str], None] @@ -42,13 +42,20 @@ class ImportOutcome: skipped: list[Source] # duplicate content (same hash) +class CatalogRefreshError(OSError): + def __init__(self, completed: int, cause: OSError): + super().__init__(f"Could not refresh the knowledge index and overview: {cause}") + self.completed = completed + + class IngestionManager: def __init__(self, project: Project, provider: LLMProvider | None = None): self.project = project self.store = project.store self.provider = provider or build_provider(project.settings.as_dict()) self._cancel = threading.Event() - self._thread: threading.Thread | None = None + self._run_lock = project._ingestion_lock + self._catalog_dirty = project.cache_dir / "ingestion-catalog-dirty" def set_provider(self, provider: LLMProvider) -> None: self.provider = provider @@ -261,30 +268,41 @@ def queue_all_pending_sources(self) -> int: return count # -- processing ---------------------------------------------------------- - def _process_job(self, job: Job, pipeline: ExtractionPipeline, progress: Progress | None): + def _start_job(self, job: Job, progress: Progress | None) -> Source | None: source = self.store.get_source(job.source_id) if source is None: job.state = JobState.FAILED job.error = "source missing" job.updated_at = now() self.store.upsert_job(job) - return + return None job.state = JobState.RUNNING job.attempts += 1 job.updated_at = now() self.store.upsert_job(job) _emit(progress, "start", job, source.title) + return source + + def _analyze_source(self, source: Source, provider: LLMProvider) -> tuple[str, dict, str]: + text = parsers.parse(self.project.sources_dir / source.rel_path) + if not text.strip(): + raise ValueError("no extractable text") + pipeline = ExtractionPipeline(self.project, provider) + return text, pipeline.analyze(text), pipeline.last_fallback + def _finish_job(self, job: Job, source: Source, analysis: Future[tuple[str, dict, str]], + pipeline: ExtractionPipeline, progress: Progress | None) -> bool: try: - fp = self.project.sources_dir / source.rel_path - text = parsers.parse(fp) - if not text.strip(): - raise ValueError("no extractable text") + text, data, fallback = analysis.result() source.status = SourceStatus.PARSED self.store.upsert_source(source) - result = pipeline.ingest_source(source, text) + # Keep catalog repair possible even if the process stops after this job. + if not self._catalog_dirty.exists(): + self._catalog_dirty.parent.mkdir(parents=True, exist_ok=True) + self._catalog_dirty.touch() + result = pipeline.persist_analysis(source, text, data, fallback=fallback) source.status = SourceStatus.INGESTED self.store.upsert_source(source) @@ -292,10 +310,6 @@ def _process_job(self, job: Job, pipeline: ExtractionPipeline, progress: Progres job.error = "" job.updated_at = now() self.store.upsert_job(job) - _emit(progress, "done", job, - f"{source.title}: {len(result.pages)} pages") - if result.fallback: - _emit(progress, "warning", job, f"{source.title}: {result.fallback}") except Exception as exc: # noqa: BLE001 - surface, don't crash the queue source.status = SourceStatus.FAILED self.store.upsert_source(source) @@ -305,45 +319,104 @@ def _process_job(self, job: Job, pipeline: ExtractionPipeline, progress: Progres job.updated_at = now() self.store.upsert_job(job) _emit(progress, "error", job, str(exc)) + return False + + _emit(progress, "done", job, f"{source.title}: {len(result.pages)} pages") + if result.fallback: + _emit(progress, "warning", job, f"{source.title}: {result.fallback}") + return True def process_pending(self, progress: Progress | None = None, *, max_jobs: int | None = None) -> int: - """Process queued jobs serially. Returns number of jobs completed.""" - pipeline = ExtractionPipeline(self.project, self.provider) + """Process queued jobs and return the number completed by this run.""" + if not self._run_lock.acquire(blocking=False): + return 0 + try: + return self._drain(progress, max_jobs) + finally: + self._run_lock.release() + + def _drain(self, progress: Progress | None, max_jobs: int | None) -> int: + provider = self.provider + pipeline = ExtractionPipeline(self.project, provider) + workers = self.project.settings.ingestion_workers + if type(workers) is not int or not 1 <= workers <= 3: + workers = DEFAULT_INGESTION_WORKERS done = 0 - while not self._cancel.is_set(): - pending = [j for j in self.store.pending_jobs() - if j.state != JobState.FAILED] - # Only pick genuinely queued jobs whose attempts are under the cap. - queued = [j for j in pending if j.attempts < 3] - if not queued: - break - job = queued[0] - self._process_job(job, pipeline, progress) - if job.state == JobState.DONE: - done += 1 - if max_jobs and done >= max_jobs: - break + with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="ingest-analysis") as executor: + while not self._cancel.is_set(): + # RUNNING rows from an interrupted run are eligible for retry. + queued = [job for job in self.store.pending_jobs() if job.attempts < 3] + if not queued: + break + # Reserve a completion slot for each job we start. + slots = min(workers, max(1, max_jobs - done)) if max_jobs else workers + batch = [] + for job in queued[:slots]: + if self._cancel.is_set(): + break + source = self._start_job(job, progress) + if source is not None: + future = executor.submit(self._analyze_source, source, provider) + batch.append((job, source, future)) + + # Apply in queue order, even if a source needs another attempt. + for job, source, future in batch: + while True: + if self._finish_job(job, source, future, pipeline, progress): + done += 1 + break + if job.state != JobState.QUEUED or self._cancel.is_set(): + break + source = self._start_job(job, progress) + if source is None: + break + future = executor.submit(self._analyze_source, source, provider) + if max_jobs and done >= max_jobs: + break + + try: + if self.needs_catalog_refresh(): + pipeline.rebuild_catalog() + self._catalog_dirty.unlink(missing_ok=True) + except OSError as exc: + raise CatalogRefreshError(done, exc) from exc return done # -- threaded (UI) ------------------------------------------------------- - def start(self, progress: Progress | None = None, on_finish: Callable[[int], None] | None = None) -> None: - if self._thread and self._thread.is_alive(): + def start(self, progress: Progress | None = None, on_finish: Callable[[int], None] | None = None, + *, on_error: Callable[[str], None] | None = None) -> None: + if not self._run_lock.acquire(blocking=False): return self._cancel.clear() def _run(): - count = self.process_pending(progress) - if on_finish: - on_finish(count) + count = 0 + try: + count = self._drain(progress, None) + except CatalogRefreshError as exc: + count = exc.completed + if on_error is None: + raise + on_error(str(exc)) + finally: + self._run_lock.release() + if on_finish: + on_finish(count) - self._thread = threading.Thread(target=_run, daemon=True, name="ingest") - self._thread.start() + try: + threading.Thread(target=_run, daemon=True, name="ingest").start() + except BaseException: + self._run_lock.release() + raise def cancel(self) -> None: self._cancel.set() def is_running(self) -> bool: - return bool(self._thread and self._thread.is_alive()) + return self._run_lock.locked() + + def needs_catalog_refresh(self) -> bool: + return self._catalog_dirty.exists() def _emit(progress: Progress | None, event: str, job: Job, message: str) -> None: diff --git a/gknowledge/core/project.py b/gknowledge/core/project.py index 080be18..a0140cc 100644 --- a/gknowledge/core/project.py +++ b/gknowledge/core/project.py @@ -23,6 +23,7 @@ from __future__ import annotations import json +import threading from dataclasses import asdict, dataclass, field from pathlib import Path @@ -31,6 +32,7 @@ MANIFEST = "gknowledge.json" FORMAT_VERSION = 1 +DEFAULT_INGESTION_WORKERS = 2 KNOWLEDGE_SUBDIRS = { PageKind.SOURCE: "sources", @@ -50,6 +52,7 @@ class Settings: model: str = "gpt-4o-mini" embed_model: str = "" language: str = "English" + ingestion_workers: int = DEFAULT_INGESTION_WORKERS def as_dict(self) -> dict: return asdict(self) @@ -64,6 +67,7 @@ class Project: def __init__(self, root: str | Path): self.root = Path(root) self.store = Store(self.index_dir / "knowledge.db") + self._ingestion_lock = threading.Lock() self._settings = self._load_settings() # -- lifecycle ----------------------------------------------------------- diff --git a/gknowledge/providers/chatgpt.py b/gknowledge/providers/chatgpt.py index dc3de22..2d39e23 100644 --- a/gknowledge/providers/chatgpt.py +++ b/gknowledge/providers/chatgpt.py @@ -360,11 +360,13 @@ def __init__(self, model: str = "", *, auth: ChatGPTAuth | None = None, self.api_base = api_base.rstrip("/") self.configured_model = model self._model: str | None = None + self._session_lock = threading.Lock() self.name = (f"ChatGPT plan · {model}" if model else "ChatGPT plan · automatic model") def available(self) -> bool: - return self.auth.store.load().sharing + with self._session_lock: + return self.auth.store.load().sharing # -- model resolution -------------------------------------------------------------- def list_models(self) -> list[dict]: @@ -373,9 +375,13 @@ def list_models(self) -> list[dict]: The endpoint returns ``{"models": [{slug, display_name, visibility, priority, ...}]}``; only ``visibility == "list"`` entries are shown. """ - acct = self.auth.valid_account() + with self._session_lock: + acct = self.auth.valid_account() + return self._list_models(acct.access_token) + + def _list_models(self, token: str) -> list[dict]: data = _http_json(f"{self.api_base}/models", - headers={"Authorization": f"Bearer {acct.access_token}"}, + headers={"Authorization": f"Bearer {token}"}, timeout=20) models = [m for m in data.get("models", []) if m.get("visibility", "list") == "list" and m.get("slug")] @@ -388,7 +394,7 @@ def _resolve_model(self, token: str) -> str: if self._model: return self._model try: - slugs = [m["slug"] for m in self.list_models()] + slugs = [m["slug"] for m in self._list_models(token)] except (ProviderError, KeyError): slugs = [] if self.configured_model and (not slugs or self.configured_model in slugs): @@ -405,7 +411,11 @@ def complete(self, messages: list[LLMMessage], *, json_object: bool = False, temperature: float = 0.2, max_tokens: int | None = None) -> LLMResponse: # Plan usage rejects explicit system items, temperature and # max_output_tokens: system text goes in `instructions`. - acct = self.auth.valid_account() + # Account refresh and model selection share state across requests. + # Streaming can proceed independently with the chosen token and model. + with self._session_lock: + acct = self.auth.valid_account() + model = self._resolve_model(acct.access_token) instructions = "\n\n".join(m.content for m in messages if m.role == "system") if json_object: instructions += "\n\nRespond with a single valid JSON object and nothing else." @@ -416,7 +426,7 @@ def complete(self, messages: list[LLMMessage], *, json_object: bool = False, ctype = "output_text" if m.role == "assistant" else "input_text" items.append({"role": m.role, "content": [{"type": ctype, "text": m.content}]}) - payload = {"model": self._resolve_model(acct.access_token), + payload = {"model": model, "instructions": instructions.strip() or "You are a helpful assistant.", "input": items, "store": False, "stream": True} @@ -426,7 +436,11 @@ def complete(self, messages: list[LLMMessage], *, json_object: bool = False, except _Unauthorized: if attempt: raise ProviderError("ChatGPT rejected the access token.") - acct = self.auth.refresh() + with self._session_lock: + current = self.auth.valid_account() + if current.access_token == acct.access_token: + current = self.auth.refresh() + acct = current raise ProviderError("Unreachable") # pragma: no cover def _stream(self, payload: dict, token: str) -> LLMResponse: diff --git a/gknowledge/ui/preferences.py b/gknowledge/ui/preferences.py index eabca6c..67cc6dc 100644 --- a/gknowledge/ui/preferences.py +++ b/gknowledge/ui/preferences.py @@ -433,6 +433,7 @@ def _on_save(self, *_a): api_key=self._api_key.get_text().strip(), model=model, language=_LANGS[self._lang.get_selected()], + ingestion_workers=self._project.settings.ingestion_workers, ) self._cancel.set() self._project.save_settings(settings) diff --git a/gknowledge/ui/window.py b/gknowledge/ui/window.py index 596d173..aa4677a 100644 --- a/gknowledge/ui/window.py +++ b/gknowledge/ui/window.py @@ -447,9 +447,13 @@ def _update_ingest_button(self): pending = [j for j in self.project.store.pending_jobs() if j.state != JobState.FAILED] n = len(pending) - self.ingest_btn.set_label(f"Ingest Queued ({n})" if n else "Ingest Queued") - self.ingest_btn.set_sensitive(n > 0 and not self.ingestion.is_running()) - if n > 0: + catalog_pending = self.ingestion.needs_catalog_refresh() + label = f"Ingest Queued ({n})" if n else "Ingest Queued" + if not n and catalog_pending: + label = "Refresh Knowledge Index" + self.ingest_btn.set_label(label) + self.ingest_btn.set_sensitive(bool(n or catalog_pending) and not self.ingestion.is_running()) + if n or catalog_pending: self.ingest_btn.add_css_class("suggested-action") else: self.ingest_btn.remove_css_class("suggested-action") @@ -824,6 +828,7 @@ def _remove_source(self, source_id: str): def _on_ingest(self, *_a): if not self.ingestion or self.ingestion.is_running(): return + catalog_pending = self.ingestion.needs_catalog_refresh() self.progress.set_visible(True) self.progress.set_fraction(0.0) self.ingest_btn.set_sensitive(False) @@ -846,12 +851,19 @@ def finished(count): def done(): self.progress.set_visible(False) self.refresh_all() - self.toast(f"Ingested {count} source(s)") + if count or not catalog_pending: + self.toast(f"Ingested {count} source(s)") + elif not self.ingestion.needs_catalog_refresh(): + self.toast("Knowledge index refreshed") self._update_ingest_button() return False GLib.idle_add(done) - self.ingestion.start(progress=progress, on_finish=finished) + self.ingestion.start( + progress=progress, + on_finish=finished, + on_error=lambda message: GLib.idle_add(self.toast, GLib.markup_escape_text(message)), + ) self._update_source_action_buttons() # -- drift --------------------------------------------------------------- diff --git a/tests/test_chatgpt.py b/tests/test_chatgpt.py index 35d12b1..d24d458 100644 --- a/tests/test_chatgpt.py +++ b/tests/test_chatgpt.py @@ -10,15 +10,17 @@ import time import urllib.parse import urllib.request +from concurrent.futures import ThreadPoolExecutor from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import pytest -from gknowledge.providers.base import LLMMessage, ProviderError +from gknowledge.providers import chatgpt +from gknowledge.providers.base import LLMMessage, LLMResponse, ProviderError from gknowledge.providers.chatgpt import ( - AccountStore, ChatGPTAuth, ChatGPTPlanProvider, SignInError) + AccountStore, ChatGPTAccount, ChatGPTAuth, ChatGPTPlanProvider, SignInError) def _jwt(claims: dict) -> str: @@ -185,6 +187,47 @@ def test_provider_streams_with_plan_rules(tmp_path): fake.close() +def test_overlapping_completions_reuse_refreshed_access_token(tmp_path, monkeypatch): + store = AccountStore(tmp_path / "chatgpt.json") + store.save(ChatGPTAccount( + host_id="test-host", client_id="test-client", access_token="rejected", + refresh_token="test-refresh", scope=chatgpt.SPEND_SCOPE, + expires_at=time.time() + 3600, + )) + auth = ChatGPTAuth(store) + provider = ChatGPTPlanProvider("gpt-test", auth=auth) + monkeypatch.setattr(chatgpt, "_http_json", lambda *_a, **_kw: {"models": [{"slug": "gpt-test"}]}) + + refreshes = [] + refresh_lock = threading.Lock() + + def refresh(): + with refresh_lock: + account = store.load() + refreshes.append(account.access_token) + account.access_token = "refreshed" + store.save(account) + return account + + both_streaming = threading.Barrier(2) + + def stream(payload, token): + assert payload["model"] == "gpt-test" + if token == "rejected": + both_streaming.wait(timeout=5) + raise chatgpt._Unauthorized() + return LLMResponse(content=token) + + monkeypatch.setattr(auth, "refresh", refresh) + monkeypatch.setattr(provider, "_stream", stream) + messages = [LLMMessage("user", "hello")] + with ThreadPoolExecutor(max_workers=2) as pool: + responses = list(pool.map(provider.complete, [messages, messages])) + + assert [response.content for response in responses] == ["refreshed", "refreshed"] + assert refreshes == ["rejected"] + + def test_usage_limit_is_reported(tmp_path): fake = FakeOpenAI(responses_status=429, responses_body='{"error":{"code":"subscription_sharing_usage_limit_exceeded"}}') diff --git a/tests/test_core.py b/tests/test_core.py index febf0da..c81f257 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -2,9 +2,12 @@ from __future__ import annotations +import json import sys import zipfile from pathlib import Path +from threading import Barrier, Event, Lock +from unittest.mock import patch sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) @@ -13,11 +16,12 @@ from gknowledge.core.knowledge import KnowledgeWriter from gknowledge.core.lint import ChangeDetector, stale_sources from gknowledge.core.models import ( - Page, PageKind, ReviewAction, ReviewItem, Source, SourceStatus, + JobState, Page, PageKind, ReviewAction, ReviewItem, Source, SourceStatus, ) from gknowledge.core.project import Project, Settings from gknowledge.core.query import QueryEngine from gknowledge.providers import build_provider +from gknowledge.providers.base import LLMProvider, LLMResponse SAMPLE = """# Solar Energy Basics @@ -154,6 +158,282 @@ def test_import_ingest_and_dedup(tmp_path): proj.close() +class _SharedEntityProvider(LLMProvider): + def __init__(self, overlapping_title_markers): + self.markers = overlapping_title_markers + self.barrier = Barrier(len(self.markers)) + self.second_finished = Event() + self.completed = [] + self.lock = Lock() + self.active = 0 + self.peak = 0 + + def available(self): + return True + + def complete(self, messages, **kwargs): + text = messages[-1].content + marker = next((marker for marker in self.markers if marker in text), None) + with self.lock: + self.active += 1 + self.peak = max(self.peak, self.active) + try: + if marker is not None: + self.barrier.wait(timeout=5) + if marker == self.markers[0] and not self.second_finished.wait(timeout=5): + raise TimeoutError("The second provider call did not finish.") + return LLMResponse(json.dumps({ + "summary": "A source about the local observatory.", + "entities": [{"name": "Lunar Observatory", + "description": "The observatory studies the Moon."}], + })) + finally: + with self.lock: + self.active -= 1 + self.completed.append(marker) + if marker is not None and marker == self.markers[1]: + self.second_finished.set() + + +def _import_numbered_sources(mgr, tmp_path, count): + sources = [] + for number in range(1, count + 1): + src_file = tmp_path / f"night-{number}.md" + src_file.write_text( + f"# Research Night {number}\n\nA unique observing report for night {number}.\n", + "utf-8", + ) + source = mgr.import_file(src_file) + assert source is not None + sources.append(source) + return sources + + +def test_ingestion_overlaps_analysis_and_rebuilds_once_in_queue_order(tmp_path): + proj = make_project(tmp_path) + try: + provider = _SharedEntityProvider(("Research Night 1", "Research Night 2")) + mgr = IngestionManager(proj, provider) + sources = _import_numbered_sources(mgr, tmp_path, 3) + completed = [] + + def progress(event, job, _message): + if event == "done": + completed.append(job.source_id) + + with ( + patch.object(KnowledgeWriter, "rebuild_index", autospec=True, + side_effect=KnowledgeWriter.rebuild_index) as rebuild_index, + patch.object(KnowledgeWriter, "rebuild_overview", autospec=True, + side_effect=KnowledgeWriter.rebuild_overview) as rebuild_overview, + ): + done = mgr.process_pending(progress) + + assert provider.peak == 2 + assert provider.completed.index("Research Night 2") < provider.completed.index("Research Night 1") + assert done == 3 + assert completed == [source.id for source in sources] + assert rebuild_index.call_count == rebuild_overview.call_count == 1 + entities = proj.store.list_pages(PageKind.ENTITY) + assert [page.slug for page in entities] == ["lunar-observatory"] + assert entities[0].sources == completed + assert {link.from_slug for link in proj.store.all_links() + if link.to_slug == entities[0].slug} == { + "research-night-1", "research-night-2", "research-night-3", + } + index = (proj.knowledge_dir / "index.md").read_text("utf-8") + assert all(f"[[research-night-{number}]]" in index for number in range(1, 4)) + finally: + proj.close() + + +def test_ingestion_uses_configured_worker_count(tmp_path): + proj = make_project(tmp_path) + try: + proj.save_settings(Settings(provider="offline", ingestion_workers=3)) + proj.close() + proj = Project.open(proj.root) + provider = _SharedEntityProvider(tuple(f"Research Night {n}" for n in range(1, 4))) + mgr = IngestionManager(proj, provider) + _import_numbered_sources(mgr, tmp_path, 4) + assert mgr.process_pending() == 4 + assert provider.peak == 3 + finally: + proj.close() + + +def test_ingestion_max_jobs_counts_successes_through_failed_source(tmp_path): + proj = make_project(tmp_path) + try: + mgr = IngestionManager(proj) + missing, good, later = _import_numbered_sources(mgr, tmp_path, 3) + (proj.sources_dir / missing.rel_path).unlink() + + assert mgr.process_pending(max_jobs=1) == 1 + jobs = {job.source_id: job for job in proj.store.list_jobs()} + assert jobs[missing.id].state == JobState.FAILED + assert jobs[missing.id].attempts == 3 + assert jobs[missing.id].error + assert jobs[good.id].state == JobState.DONE + assert jobs[good.id].attempts == 1 + assert jobs[later.id].state == JobState.QUEUED + assert jobs[later.id].attempts == 0 + # A persisted job from an interrupted run is eligible again on reopen. + jobs[later.id].state = JobState.RUNNING + jobs[later.id].attempts = 1 + proj.store.upsert_job(jobs[later.id]) + proj.close() + proj = Project.open(proj.root) + assert IngestionManager(proj).process_pending() == 1 + recovered = {job.source_id: job for job in proj.store.list_jobs()} + assert recovered[later.id].state == JobState.DONE + assert recovered[later.id].attempts == 2 + assert recovered[good.id].attempts == 1 + finally: + proj.close() + + +def test_ingestion_cancellation_finishes_started_jobs_without_starting_more(tmp_path): + class CancellingProvider(_SharedEntityProvider): + def complete(self, messages, **kwargs): + if "Research Night 2" in messages[-1].content: + mgr.cancel() + return super().complete(messages, **kwargs) + + proj = make_project(tmp_path) + try: + provider = CancellingProvider(("Research Night 1", "Research Night 2")) + mgr = IngestionManager(proj, provider) + first, second, later = _import_numbered_sources(mgr, tmp_path, 3) + + assert mgr.process_pending() == 2 + jobs = {job.source_id: job for job in proj.store.list_jobs()} + assert jobs[first.id].state == jobs[second.id].state == JobState.DONE + assert jobs[later.id].state == JobState.QUEUED + assert jobs[later.id].attempts == 0 + assert IngestionManager(proj, provider).process_pending() == 1 + finally: + proj.close() + + +def test_ingestion_retries_catalog_after_reopen_without_replaying_jobs(tmp_path): + proj = make_project(tmp_path) + try: + mgr = IngestionManager(proj) + source, = _import_numbered_sources(mgr, tmp_path, 1) + with patch.object(KnowledgeWriter, "rebuild_overview", + side_effect=OSError("catalog unavailable")): + try: + mgr.process_pending() + except OSError: + pass + else: + raise AssertionError("The catalog write failed without reporting an error.") + job, = proj.store.list_jobs() + assert job.state == JobState.DONE + + proj.close() + proj = Project.open(proj.root) + provider = _SharedEntityProvider(("Uncalled first", "Uncalled second")) + mgr = IngestionManager(proj, provider) + with ( + patch.object(KnowledgeWriter, "rebuild_index", autospec=True, + side_effect=KnowledgeWriter.rebuild_index) as rebuild_index, + patch.object(KnowledgeWriter, "rebuild_overview", autospec=True, + side_effect=KnowledgeWriter.rebuild_overview) as rebuild_overview, + ): + assert mgr.process_pending() == 0 + assert mgr.process_pending() == 0 + assert not provider.completed + assert rebuild_index.call_count == rebuild_overview.call_count == 1 + assert proj.store.get_source(source.id).status == SourceStatus.INGESTED + assert proj.store.list_jobs()[0].attempts == 1 + assert "[[research-night-1]]" in (proj.knowledge_dir / "index.md").read_text("utf-8") + assert "**1 sources**" in (proj.knowledge_dir / "overview.md").read_text("utf-8") + finally: + proj.close() + + +def test_ingestion_retries_early_source_before_publishing_later_source(tmp_path): + class TransientFailureProvider(LLMProvider): + def __init__(self): + self.alpha_attempts = 0 + + def available(self): + return True + + def complete(self, messages, **kwargs): + title = "Alpha" if "Alpha Report" in messages[-1].content else "Beta" + if title == "Alpha": + self.alpha_attempts += 1 + if self.alpha_attempts == 1: + raise RuntimeError("transient analysis failure") + return LLMResponse(json.dumps({ + "entities": [{"name": "Lunar Observatory", + "description": f"{title} documented the Lunar Observatory."}], + })) + + proj = make_project(tmp_path) + try: + provider = TransientFailureProvider() + mgr = IngestionManager(proj, provider) + sources = [] + for title in ("Alpha Report", "Beta Report"): + path = tmp_path / f"{title}.md" + path.write_text(f"# {title}\n\nObservations from the local site.\n", "utf-8") + source = mgr.import_file(path) + assert source is not None + sources.append(source) + + assert mgr.process_pending() == 2 + assert provider.alpha_attempts == 2 + shared = proj.store.get_page("lunar-observatory") + assert shared is not None + assert shared.sources == [source.id for source in sources] + assert shared.summary == "Alpha documented the Lunar Observatory." + finally: + proj.close() + + +def test_parallel_offline_ingestion_matches_serial_knowledge(tmp_path): + documents = ( + "# Dawn Report\n\nThe team at Lunar Observatory recorded the sunrise.\n", + "# Dusk Report\n\nThe staff at Lunar Observatory observed the falling light.\n", + ) + snapshots = [] + for workers in (1, 2): + proj = Project.create(tmp_path / f"workers-{workers}", name="Test KB") + try: + proj.save_settings(Settings(ingestion_workers=workers)) + note = proj.root / "notes" / "observations.md" + note.write_text("---\nsource: human\n---\n\nMy observations.\n", "utf-8") + original_note = note.read_bytes() + mgr = IngestionManager(proj) + titles = {} + for number, text in enumerate(documents): + path = tmp_path / f"report-{number}.md" + path.write_text(text, "utf-8") + source = mgr.import_file(path) + assert source is not None + titles[source.id] = source.title + assert mgr.process_pending() == len(documents) + assert note.read_bytes() == original_note + + writer = KnowledgeWriter(proj) + entity = proj.store.get_page("lunar-observatory") + assert entity is not None + assert [titles[source_id] for source_id in entity.sources] == [ + "Dawn Report", "Dusk Report", + ] + snapshots.append({ + page.slug: (writer.read_body(page), [titles[sid] for sid in page.sources]) + for page in proj.store.list_pages() + }) + finally: + proj.close() + assert snapshots[0] == snapshots[1] + + def test_reingest_clears_stale_pages_and_rebuilds_source(tmp_path): proj = make_project(tmp_path) src_file = tmp_path / "solar.md" @@ -443,7 +723,14 @@ def test_store_converts_a_wal_database(tmp_path): ("h", test_store_converts_a_wal_database), ("i", test_import_and_ingest_docx), ("j", test_parse_docx_returns_empty_on_corrupt_file), - ("k", test_import_folder_accepts_docx)): + ("k", test_import_folder_accepts_docx), + ("l", test_ingestion_overlaps_analysis_and_rebuilds_once_in_queue_order), + ("m", test_ingestion_uses_configured_worker_count), + ("n", test_ingestion_max_jobs_counts_successes_through_failed_source), + ("o", test_parallel_offline_ingestion_matches_serial_knowledge), + ("p", test_ingestion_cancellation_finishes_started_jobs_without_starting_more), + ("q", test_ingestion_retries_catalog_after_reopen_without_replaying_jobs), + ("r", test_ingestion_retries_early_source_before_publishing_later_source)): d = tmp / name d.mkdir(parents=True, exist_ok=True) fn(d)