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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions src/lore/ingest/doc_repo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import logging
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

from lore.ingest.chunker import SUPPORTED_EXTENSIONS
Expand All @@ -9,6 +10,7 @@
from lore.sync.parser import ParsedFile, compute_content_hash

log = logging.getLogger("lore.ingest")
DEFAULT_MAX_WORKERS = 4


class DocRepoIngester:
Expand All @@ -17,10 +19,15 @@ def __init__(
provider: LLMProvider,
doc_paths: list[str] | None = None,
exclude_paths: list[str] | None = None,
max_workers: int = DEFAULT_MAX_WORKERS,
) -> None:
if max_workers < 1:
raise ValueError("max_workers must be at least 1")

self._provider = provider
self._doc_paths = doc_paths
self._exclude_paths = exclude_paths or []
self._max_workers = max_workers

def scan_files(self, repo_path: Path) -> list[Path]:
candidates: list[Path] = []
Expand Down Expand Up @@ -89,11 +96,21 @@ def process_file(
return parsed_files

def scan_and_process(self, repo_path: Path) -> list[ParsedFile]:
files = self.scan_files(repo_path)
files = sorted(
self.scan_files(repo_path),
key=lambda path: path.relative_to(repo_path).as_posix(),
)
result: list[ParsedFile] = []
for f in files:
try:
result.extend(self.process_file(f, repo_path))
except Exception:
log.warning("Failed to process %s", f, exc_info=True)

with ThreadPoolExecutor(max_workers=self._max_workers) as executor:
futures = [
(file_path, executor.submit(self.process_file, file_path, repo_path))
for file_path in files
]
for file_path, future in futures:
try:
result.extend(future.result())
except Exception:
log.warning("Failed to process %s", file_path, exc_info=True)

return result
70 changes: 64 additions & 6 deletions tests/unit/test_ingest_doc_repo.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import threading
from pathlib import Path

from lore.ingest.doc_repo import DocRepoIngester
Expand Down Expand Up @@ -214,17 +215,74 @@ def test_scan_and_process_end_to_end(tmp_path):
assert "docs/ref.md" in file_paths


def test_scan_and_process_is_parallel_and_deterministic(tmp_path):
for name in ("c.md", "a.md", "b.md"):
_write_doc(tmp_path / name)

barrier = threading.Barrier(2)
lock = threading.Lock()
active = 0
max_active = 0

class _ConcurrentProvider(_MockProvider):
def extract_from_chunk(self, chunk_text, heading, source_file):
nonlocal active, max_active
with lock:
active += 1
max_active = max(max_active, active)
try:
if Path(source_file).name in {"a.md", "b.md"}:
barrier.wait(timeout=2)
return [DocChunkExtraction(key="guide:entry", summary="Entry.")]
finally:
with lock:
active -= 1

ingester = DocRepoIngester(
_ConcurrentProvider(),
doc_paths=["c.md", "a.md", "b.md"],
max_workers=2,
)
result = ingester.scan_and_process(tmp_path)

assert max_active >= 2
assert [parsed.file_path for parsed in result] == ["a.md", "b.md", "c.md"]


def test_scan_and_process_continues_after_file_failure(tmp_path, monkeypatch):
_write_doc(tmp_path / "bad.md")
_write_doc(tmp_path / "good.md")
ingester = DocRepoIngester(_MockProvider(), max_workers=2)

def process_file(file_path, repo_path):
if file_path.name == "bad.md":
raise RuntimeError("failed file")
return [
ParsedFile(
key="guide:good",
value="Good.",
tags=None,
locked=False,
created_by=None,
projects=None,
content_hash="sha256:test",
file_path=file_path.relative_to(repo_path).as_posix(),
)
]

monkeypatch.setattr(ingester, "process_file", process_file)

result = ingester.scan_and_process(tmp_path)

assert [parsed.file_path for parsed in result] == ["good.md"]


def test_scan_and_process_handles_errors(tmp_path):
_write_doc(tmp_path / "good.md")

class _FailProvider(_MockProvider):
def __init__(self):
super().__init__()
self._calls = 0

def extract_from_chunk(self, chunk_text, heading, source_file):
self._calls += 1
if self._calls == 1:
if Path(source_file).name == "good.md":
raise RuntimeError("LLM error")
return [DocChunkExtraction(key="guide:ok", summary="OK.")]

Expand Down