"""Local intake acceptance against isolated PostgreSQL/pgvector.""" from concurrent.futures import ThreadPoolExecutor from threading import Barrier from uuid import uuid4 import pytest from sqlalchemy import text from sqlalchemy.exc import IntegrityError from app.infrastructure.file_store import LocalFileStore from app.infrastructure.intake_repository import SqlIntakeRepository from app.modules.documents.intake import IntakeError, import_document, reconcile, status from tests.support.formats import format_bytes, raw_docx @pytest.fixture def intake(migrated_db, settings, tmp_path): engine, _ = migrated_db org, actor = uuid4(), uuid4() with engine.begin() as connection: connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'intake')"), {"id": org}) connection.execute(text(""" INSERT INTO users(id,organization_id,username,password_hash,role) VALUES (:id,:org,:name,'test-only','admin') """), {"id": actor, "org": org, "name": str(actor)}) path = tmp_path / "source.md" path.write_bytes("# Intake\nOriginal bytes\n".encode()) store = LocalFileStore(tmp_path / "originals") def run(request=None, **kwargs): return import_document(SqlIntakeRepository(engine), store, settings, path=kwargs.pop("path", path), administrator_id=kwargs.pop("administrator_id", actor), request_id=request or uuid4(), **kwargs) return engine, settings, store, path, org, actor, run def counts(engine): with engine.connect() as connection: return tuple(connection.execute(text("SELECT count(*) FROM " + table)).scalar_one() for table in ("documents", "ingestion_jobs", "audit_events", "document_chunks")) def test_durable_intake_replay_independent_documents_and_profile(intake): engine, settings, store, path, org, actor, run = intake request = uuid4() first = run(request, title=" A title ") doc = first["document"] assert first["replayed"] is False assert doc["organization_id"] == org and doc["uploaded_by"] == actor assert doc["status"] == doc["job"]["status"] == "queued" assert doc["is_active"] is False and doc["chunk_count"] == 0 and not doc["searchable"] assert doc["processing_profile"] == settings.processing_profile() assert LocalFileStore(store.directory).read(doc["storage_key"]) == path.read_bytes() # Dispose all pooled connections to simulate application restart. engine.dispose() renamed = path.with_name("renamed.md") renamed.write_bytes(path.read_bytes()) second = run(request, title="A title", path=renamed) assert second["replayed"] is True assert second["document"]["id"] == doc["id"] assert second["document"]["job"]["id"] == doc["job"]["id"] assert second["document"]["original_filename"] == "source.md" third = run(title="A title") assert third["document"]["id"] != doc["id"] assert third["document"]["storage_key"] != doc["storage_key"] assert counts(engine) == (2, 2, 2, 0) assert status(SqlIntakeRepository(engine), administrator_id=actor, document_id=doc["id"])["job"]["id"] == doc["job"]["id"] assert reconcile(SqlIntakeRepository(engine), store)["orphan_files"] == [] assert store.inventory()["temporary_files"] == [] @pytest.mark.parametrize("change", ["bytes", "title"]) def test_payload_conflict(intake, change): engine, _, store, path, _, _, run = intake request = uuid4() original = run(request) if change == "bytes": path.write_bytes(b"Changed bytes") with pytest.raises(IntakeError) as error: run(request, **({"title": "Changed title"} if change == "title" else {})) assert error.value.code == "IDEMPOTENCY_CONFLICT" assert counts(engine) == (1, 1, 1, 0) assert store.read(original["document"]["storage_key"]) == b"# Intake\nOriginal bytes\n" assert len(store.inventory()["originals"]) == 1 @pytest.mark.parametrize("extension", [".md", ".docx", ".jpg", ".png"]) @pytest.mark.parametrize("changed", [False, True]) def test_concurrent_replay_and_conflict(intake, changed, extension): engine, settings, store, path, _, actor, _ = intake if extension != ".md": path = path.with_suffix(extension) path.write_bytes(format_bytes(extension)) barrier, request = Barrier(4), uuid4() class RacingStore(LocalFileStore): def put(self, content): key = super().put(content) barrier.wait(timeout=15) return key racing = RacingStore(store.directory) def run(index): try: return import_document(SqlIntakeRepository(engine), racing, settings, path=path, administrator_id=actor, request_id=request, title=str(index) if changed else "same") except IntakeError as error: return error.code with ThreadPoolExecutor(max_workers=4) as pool: results = list(pool.map(run, range(4))) successes = [result for result in results if isinstance(result, dict)] assert len(successes) == (1 if changed else 4) assert sum(not result["replayed"] for result in successes) == 1 assert len({result["document"]["id"] for result in successes}) == 1 assert len({result["document"]["job"]["id"] for result in successes}) == 1 if changed: assert results.count("IDEMPOTENCY_CONFLICT") == 3 assert counts(engine) == (1, 1, 1, 0) assert len(store.inventory()["originals"]) == 1 assert store.inventory()["temporary_files"] == [] @pytest.mark.parametrize("extension", [".md", ".docx", ".jpg", ".png"]) @pytest.mark.parametrize("failure_at", ["job", "audit"]) def test_database_rollback_never_acknowledges_and_reconciliation_reports(intake, failure_at, extension): engine, _, store, path, _, _, run = intake if extension != ".md": path = path.with_suffix(extension) path.write_bytes(format_bytes(extension)) with engine.begin() as connection: table = "ingestion_jobs" if failure_at == "job" else "audit_events" connection.execute(text(f"ALTER TABLE {table} ADD CONSTRAINT reject_intake CHECK (false)")) with pytest.raises(IntegrityError): run(path=path) assert counts(engine) == (0, 0, 0, 0) inventory = store.inventory() report = reconcile(SqlIntakeRepository(engine), store) assert report["orphan_files"] == inventory["originals"] and len(report["orphan_files"]) == 1 assert report["report_only"] and report["missing_originals"] == [] assert store.inventory() == inventory assert inventory["temporary_files"] == [] def test_missing_original_temporary_and_unexpected_entries_report_only(intake): engine, _, store, _, _, _, run = intake doc = run()["document"] # Simulated external loss, not a product purge operation. (store.directory / doc["storage_key"]).unlink() (store.directory / ".intake-abandoned").write_bytes(b"partial") (store.directory / "unexpected").write_bytes(b"unknown") before = store.inventory() report = reconcile(SqlIntakeRepository(engine), store) assert report["missing_originals"] == [{"document_id": str(doc["id"]), "storage_key": doc["storage_key"]}] assert report["temporary_files"] == [".intake-abandoned"] assert report["unexpected_entries"] == ["unexpected"] assert store.inventory() == before assert counts(engine) == (1, 1, 1, 0) @pytest.mark.parametrize("identity", ["disabled", "user", "unknown"]) def test_administrator_required_before_storage(intake, identity): engine, _, store, _, _, actor, run = intake if identity == "unknown": actor = uuid4() else: with engine.begin() as connection: connection.execute(text("UPDATE users SET is_enabled=:enabled,role=:role WHERE id=:id"), {"enabled": identity != "disabled", "role": "user" if identity == "user" else "admin", "id": actor}) with pytest.raises(IntakeError) as error: run(administrator_id=actor) assert error.value.code == "ADMINISTRATOR_REQUIRED" assert counts(engine) == (0, 0, 0, 0) and store.inventory()["originals"] == [] def test_administrator_rechecked_after_file_write(intake): engine, _, store, _, _, actor, run = intake original_put = store.put def disable(content): key = original_put(content) with engine.begin() as connection: connection.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), {"id": actor}) return key store.put = disable with pytest.raises(IntakeError): run() assert counts(engine) == (0, 0, 0, 0) assert len(reconcile(SqlIntakeRepository(engine), store)["orphan_files"]) == 1 def test_status_cannot_cross_organization(intake): engine, _, _, _, _, _, run = intake doc = run()["document"] other_org, other_actor = uuid4(), uuid4() with engine.begin() as connection: connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'other')"), {"id": other_org}) connection.execute(text(""" INSERT INTO users(id,organization_id,username,password_hash,role) VALUES (:id,:org,:name,'test-only','admin') """), {"id": other_actor, "org": other_org, "name": str(other_actor)}) with pytest.raises(IntakeError) as error: status(SqlIntakeRepository(engine), administrator_id=other_actor, document_id=doc["id"]) assert error.value.code == "DOCUMENT_NOT_FOUND" def test_file_finalization_failure_creates_no_database_rows(intake, monkeypatch): import os engine, _, store, _, _, _, run = intake def fail(*args): raise OSError("disk failure") monkeypatch.setattr(os, "link", fail) with pytest.raises(OSError): run() assert counts(engine) == (0, 0, 0, 0) assert store.inventory()["originals"] == store.inventory()["temporary_files"] == [] def test_ambiguous_commit_preserves_original_and_same_key_recovers(intake): from contextlib import contextmanager engine, settings, store, path, _, actor, _ = intake request = uuid4() class LostAcknowledgment: calls = 0 @contextmanager def begin(self): self.calls += 1 with engine.begin() as connection: yield connection if self.calls == 2: raise OSError("acknowledgment lost after commit") with pytest.raises(OSError): import_document(SqlIntakeRepository(LostAcknowledgment()), store, settings, path=path, administrator_id=actor, request_id=request) assert counts(engine) == (1, 1, 1, 0) assert reconcile(SqlIntakeRepository(engine), store)["orphan_files"] == [] result = import_document(SqlIntakeRepository(engine), store, settings, path=path, administrator_id=actor, request_id=request) assert result["replayed"] is True assert store.read(result["document"]["storage_key"]) == path.read_bytes() assert len(store.inventory()["originals"]) == 1 def test_cli_structured_import_status_and_reconciliation(intake, monkeypatch, capsys): import json import app.ingest as cli engine, settings, store, path, _, actor, _ = intake monkeypatch.setattr(cli, "IngestionSettings", lambda: settings) monkeypatch.setattr(cli, "create_database", lambda _: engine) monkeypatch.setattr(cli, "LocalFileStore", lambda _: store) request = str(uuid4()) args = ["import", str(path), "--administrator-id", str(actor), "--idempotency-key", request] assert cli.main(args) == 0 imported = json.loads(capsys.readouterr().out) doc = imported["document"] assert cli.main(["status", doc["id"], "--administrator-id", str(actor)]) == 0 assert json.loads(capsys.readouterr().out)["document"]["job"]["id"] == doc["job"]["id"] assert cli.main(args) == 0 assert json.loads(capsys.readouterr().out)["replayed"] assert cli.main(["reconcile"]) == 0 assert json.loads(capsys.readouterr().out)["orphan_files"] == [] assert cli.main(args + ["--title", "changed"]) == 1 captured = capsys.readouterr() assert captured.out == "" assert json.loads(captured.err)["error"]["code"] == "IDEMPOTENCY_CONFLICT" def test_replay_preserves_processing_snapshot_after_limit_changes(intake): engine, settings, store, path, _, actor, run = intake request = uuid4() first = run(request) changed = settings.model_copy(update={"chunk_size_characters": 1200}) replay = import_document(SqlIntakeRepository(engine), store, changed, path=path, administrator_id=actor, request_id=request) assert replay["replayed"] assert replay["document"]["processing_profile"] == first["document"]["processing_profile"] assert replay["document"]["processing_profile"] != changed.processing_profile() @pytest.mark.parametrize("policy", ["size", "format", "both"]) def test_replay_after_policy_changes_and_new_import_enforcement(intake, policy): engine, settings, store, path, _, actor, run = intake request = uuid4() first = run(request, title=" Stable title ") doc = first["document"] original_bytes = path.read_bytes() before_counts = counts(engine) with engine.connect() as connection: audits = connection.execute(text("SELECT * FROM audit_events")).mappings().all() overrides = {"chunk_size_characters": 1200} if policy in {"size", "both"}: overrides["max_original_bytes"] = 1 if policy in {"format", "both"}: overrides["accepted_formats"] = (".pdf",) changed = settings.model_copy(update=overrides) def submit(key, title="Stable title"): return import_document(SqlIntakeRepository(engine), store, changed, path=path, administrator_id=actor, request_id=key, title=title) replay = submit(request) assert replay["replayed"] and replay["document"] == doc assert replay["document"]["processing_profile"] != changed.processing_profile() assert store.read(doc["storage_key"]) == original_bytes assert store.inventory()["originals"] == [doc["storage_key"]] with pytest.raises(IntakeError) as error: submit(request, title="Different title") assert error.value.code == "IDEMPOTENCY_CONFLICT" for different in [b"", b"x" * len(original_bytes), b"x" * (len(original_bytes) + 100)]: path.write_bytes(different) with pytest.raises(IntakeError) as error: submit(request) assert error.value.code == "IDEMPOTENCY_CONFLICT" path.write_bytes(original_bytes) with pytest.raises(IntakeError) as error: submit(uuid4()) assert error.value.code == ("UNSUPPORTED_FILE_TYPE" if policy in {"format", "both"} else "FILE_TOO_LARGE") assert counts(engine) == before_counts == (1, 1, 1, 0) with engine.connect() as connection: assert connection.execute(text("SELECT * FROM audit_events")).mappings().all() == audits assert store.read(doc["storage_key"]) == original_bytes assert reconcile(SqlIntakeRepository(engine), store)["orphan_files"] == [] @pytest.mark.parametrize("conflict", [False, True]) def test_candidate_cleanup_failure_keeps_confirmed_cli_outcome(intake, monkeypatch, capsys, conflict): import json import app.ingest as cli engine, settings, store, path, _, actor, _ = intake request = uuid4() candidate_keys, winner = [], [] original_put = store.put def concurrent_winner(content): candidate_keys.append(original_put(content)) # Another importer commits after the outer request checked for an existing key. winner.append(import_document(SqlIntakeRepository(engine), LocalFileStore(store.directory), settings, path=path, administrator_id=actor, request_id=request, title="winner")["document"]) return candidate_keys[-1] def failed_discard(key): raise OSError("dummy-secret-path " + key) monkeypatch.setattr(store, "put", concurrent_winner) monkeypatch.setattr(store, "discard_unused", failed_discard) monkeypatch.setattr(cli, "IngestionSettings", lambda: settings) monkeypatch.setattr(cli, "create_database", lambda _: engine) monkeypatch.setattr(cli, "LocalFileStore", lambda _: store) result = cli.main(["import", str(path), "--administrator-id", str(actor), "--idempotency-key", str(request), "--title", "changed" if conflict else "winner"]) captured = capsys.readouterr() diagnostics = [json.loads(line) for line in captured.err.splitlines()] assert diagnostics[0]["warning"]["code"] == "UNUSED_CANDIDATE_CLEANUP_FAILED" assert "dummy-secret-path" not in captured.err and candidate_keys[0] not in captured.err if conflict: assert result == 1 and captured.out == "" assert diagnostics[1]["error"]["code"] == "IDEMPOTENCY_CONFLICT" else: assert result == 0 replay = json.loads(captured.out) assert replay["replayed"] and replay["document"]["id"] == str(winner[0]["id"]) assert len(diagnostics) == 1 assert counts(engine) == (1, 1, 1, 0) assert store.read(winner[0]["storage_key"]) == path.read_bytes() assert reconcile(SqlIntakeRepository(engine), store)["orphan_files"] == candidate_keys assert reconcile(SqlIntakeRepository(engine), store)["missing_originals"] == [] @pytest.mark.parametrize("guard", ["disabled", "embedding", "organization"]) def test_existing_key_does_not_bypass_identity_scope_or_compatibility(intake, guard): from app.infrastructure.database import CompatibilityError engine, settings, store, path, _, actor, run = intake request = uuid4() run(request) changed = settings.model_copy(update={"max_original_bytes": 1, "accepted_formats": (".pdf",)}) if guard == "disabled": with engine.begin() as connection: connection.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), {"id": actor}) expected, code = IntakeError, "ADMINISTRATOR_REQUIRED" elif guard == "embedding": changed = changed.model_copy(update={"embedding_model": "other-model"}) expected, code = CompatibilityError, None else: org, actor = uuid4(), uuid4() with engine.begin() as connection: connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'other')"), {"id": org}) connection.execute(text(""" INSERT INTO users(id,organization_id,username,password_hash,role) VALUES (:id,:org,:name,'test-only','admin') """), {"id": actor, "org": org, "name": str(actor)}) expected, code = IntakeError, "UNSUPPORTED_FILE_TYPE" with pytest.raises(expected) as error: import_document(SqlIntakeRepository(engine), store, changed, path=path, administrator_id=actor, request_id=request) if code: assert error.value.code == code assert counts(engine) == (1, 1, 1, 0) def test_replay_rechecks_enabled_administrator_after_payload_read(intake, monkeypatch): import app.modules.documents.intake as module engine, settings, store, path, _, actor, run = intake request = uuid4() original = run(request)["document"] hash_payload = module.replay_payload_hash def disable_after_read(*args, **kwargs): result = hash_payload(*args, **kwargs) with engine.begin() as connection: connection.execute(text("UPDATE users SET is_enabled=false WHERE id=:id"), {"id": actor}) return result monkeypatch.setattr(module, "replay_payload_hash", disable_after_read) with pytest.raises(IntakeError) as error: import_document(SqlIntakeRepository(engine), store, settings, path=path, administrator_id=actor, request_id=request) assert error.value.code == "ADMINISTRATOR_REQUIRED" assert counts(engine) == (1, 1, 1, 0) assert store.read(original["storage_key"]) == path.read_bytes() @pytest.mark.parametrize("extension", [".docx", ".jpg", ".jpeg", ".png"]) def test_new_format_transactions_and_profile_replay(intake, extension): engine, settings, store, path, _, actor, run = intake path = path.with_name("\u0633\u0646\u062f\u200c\u4e2d\U0001f600" + extension) path.write_bytes(format_bytes(extension)) request = uuid4() first = run(request, path=path)["document"] assert first["original_filename"] == path.name assert first["status"] == first["job"]["status"] == "queued" assert not first["is_active"] and first["chunk_count"] == 0 assert first["processing_profile"] == settings.processing_profile() changed = settings.model_copy(update={"accepted_formats": (".md",), "max_original_bytes": 1, "quality_policy": "new-quality", "vision_provider": "new", "vision_endpoint": "https://vision.invalid", "vision_model": "new-model", "vision_api_key": "dummy-secret"}) result = import_document(SqlIntakeRepository(engine), store, changed, path=path, administrator_id=actor, request_id=request) assert result["replayed"] and result["document"] == first assert store.read(first["storage_key"]) == path.read_bytes() assert counts(engine) == (1, 1, 1, 0) def test_legacy_snapshot_replays_byte_for_byte(intake): import json engine, settings, store, path, _, actor, run = intake request = uuid4() first = run(request)["document"] legacy = {"extractor": "pypdf-markdown-v1", "normalizer": "unicode-line-endings-v1", "chunker": "paragraph-v1", "chunk_size": 1000, "overlap": 200, "size_unit": "characters", "embedding": settings.processing_profile()["embedding"], "limits": settings.processing_profile()["limits"]} with engine.begin() as connection: connection.execute(text("UPDATE documents SET processing_profile=CAST(:profile AS jsonb) WHERE id=:id"), {"profile": json.dumps(legacy), "id": first["id"]}) changed = settings.model_copy(update={"max_original_bytes": 1, "accepted_formats": (".docx",)}) replay = import_document(SqlIntakeRepository(engine), store, changed, path=path, administrator_id=actor, request_id=request) assert replay["replayed"] and replay["document"]["id"] == first["id"] assert replay["document"]["job"]["id"] == first["job"]["id"] assert replay["document"]["processing_profile"] == legacy assert counts(engine) == (1, 1, 1, 0) def test_administrator_scope_change_during_file_io_is_rejected(intake): engine, settings, store, path, _, actor, _ = intake other = uuid4() with engine.begin() as connection: connection.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'other')"), {"id": other}) class ChangingStore(LocalFileStore): def put(self, content): key = super().put(content) with engine.begin() as connection: connection.execute(text("UPDATE users SET organization_id=:org WHERE id=:id"), {"org": other, "id": actor}) return key with pytest.raises(IntakeError) as error: import_document(SqlIntakeRepository(engine), ChangingStore(store.directory), settings, path=path, administrator_id=actor, request_id=uuid4()) assert error.value.code == "DOCUMENT_NOT_FOUND" and counts(engine) == (0, 0, 0, 0) assert len(reconcile(SqlIntakeRepository(engine), store)["orphan_files"]) == 1 @pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"]) @pytest.mark.parametrize("size", [20, 1024 * 1024]) def test_dishonest_docx_rejected_before_candidate_and_database_writes(intake, descriptor, size): engine, _, store, path, _, _, run = intake path = path.with_suffix(".docx") path.write_bytes(raw_docx(b"x" * size, declared_length=4, descriptor=descriptor)) with pytest.raises(IntakeError) as error: run(path=path) assert error.value.code == "INVALID_FILE" assert counts(engine) == (0, 0, 0, 0) assert store.inventory()["originals"] == [] @pytest.mark.parametrize("method", [0, 8]) @pytest.mark.parametrize("descriptor", ["signed", "unsigned"]) def test_descriptor_docx_atomic_intake_and_replay(intake, method, descriptor): engine, _, store, path, _, _, run = intake path = path.with_suffix(".docx") path.write_bytes(raw_docx(method=method, descriptor=descriptor)) request = uuid4() first = run(request, path=path) replay = run(request, path=path) assert replay["replayed"] and replay["document"] == first["document"] assert counts(engine) == (1, 1, 1, 0) assert store.read(first["document"]["storage_key"]) == path.read_bytes()