feat(ingestion): add Phase 6 operator tooling, smoke validation, and verification tests

- Add app/ingest.py CLI command for standalone document ingestion
- Add app/ingestion_smoke.py opt-in real-provider smoke test harness with redacted diagnostics
- Add unit and integration tests for Phase 6 operator tooling and audit import coverage
- Update tests/README.md with Phase 5/6 acceptance test results
This commit is contained in:
amirhosein mazaheri
2026-10-07 16:21:52 +03:30
parent 9663caf48e
commit ff9c32823c
6 changed files with 932 additions and 2 deletions
+96
View File
@@ -0,0 +1,96 @@
"""Trusted operator document intake. This does not authenticate HTTP requests."""
import argparse
from datetime import datetime
import json
import logging
from pathlib import Path
import sys
from uuid import UUID
from app.infrastructure.database import create_database
from app.infrastructure.file_store import LocalFileStore
from app.infrastructure.intake_repository import SqlIntakeRepository
from app.modules.documents.intake import (
IntakeError, import_document, logger as intake_logger, reconcile, status,
)
from app.modules.documents.settings import IngestionSettings
def json_value(value):
if isinstance(value, UUID):
return str(value)
if isinstance(value, datetime):
return value.isoformat()
raise TypeError("Unsupported output value")
class JsonDiagnosticFormatter(logging.Formatter):
def format(self, record):
return json.dumps({"warning": {"code": "UNUSED_CANDIDATE_CLEANUP_FAILED",
"message": record.getMessage()}})
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
intake = commands.add_parser("import")
intake.add_argument("file", type=Path)
intake.add_argument("--administrator-id", type=UUID, required=True)
intake.add_argument("--idempotency-key", type=UUID, required=True)
intake.add_argument("--title")
lookup = commands.add_parser("status")
lookup.add_argument("document_id", type=UUID)
lookup.add_argument("--administrator-id", type=UUID, required=True)
retry = commands.add_parser("retry")
retry.add_argument("document_id", type=UUID)
retry.add_argument("--administrator-id", type=UUID, required=True)
retry.add_argument("--idempotency-key", type=UUID, required=True)
commands.add_parser("reconcile", help="Report orphan files and missing originals; never delete")
args = parser.parse_args(argv)
engine = None
diagnostic_handler = logging.StreamHandler(sys.stderr)
diagnostic_handler.setFormatter(JsonDiagnosticFormatter())
original_propagate = intake_logger.propagate
intake_logger.addHandler(diagnostic_handler)
intake_logger.propagate = False
try:
settings = IngestionSettings()
engine = create_database(settings.database_url.get_secret_value())
repository = SqlIntakeRepository(engine)
store = LocalFileStore(settings.original_directory)
if args.command == "import":
result = import_document(repository, store, settings, path=args.file,
administrator_id=args.administrator_id,
request_id=args.idempotency_key, title=args.title)
elif args.command == "retry":
from app.infrastructure.worker_repository import SqlWorkerRepository
result = SqlWorkerRepository(engine, settings).retry(
administrator_id=args.administrator_id, document_id=args.document_id,
request_id=args.idempotency_key, store=store)
elif args.command == "status":
result = {"document": status(repository, administrator_id=args.administrator_id,
document_id=args.document_id)}
else:
result = reconcile(repository, store)
from app.infrastructure.extraction_candidates import LocalExtractionCandidates
result["extraction_inventory"] = LocalExtractionCandidates(
settings.extraction_directory, original_directory=settings.original_directory).inventory()
print(json.dumps(result, default=json_value, ensure_ascii=True))
return 0
except IntakeError as exc:
print(json.dumps({"error": {"code": exc.code, "message": str(exc)}}), file=sys.stderr)
return 1
except Exception:
print(json.dumps({"error": {"code": "INTAKE_FAILED",
"message": "Verify configuration, schema and storage; reconcile before retrying the same key."}}),
file=sys.stderr)
return 1
finally:
intake_logger.removeHandler(diagnostic_handler)
intake_logger.propagate = original_propagate
if engine is not None:
engine.dispose()
if __name__ == "__main__":
sys.exit(main())
+143
View File
@@ -0,0 +1,143 @@
"""Opt-in corpus extraction/provider compatibility probe; never publishes."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import sys
from uuid import uuid4
from app.modules.documents.embeddings import (
EmbeddingError, EmbeddingProviderError, stage_document, validated_limits, validate_counter,
)
from app.modules.documents.extraction import ReviewRequired
from app.modules.documents.intake import prepare_file
from app.modules.documents.review import FactualReviewRequired, prepare_chunks
from app.modules.documents.settings import IngestionSettings
from app.worker import factories
def harmless_probe(profile, counter):
"""Select bounded public ASCII evidence; never substitute corpus contents."""
limits = validated_limits(profile["embedding_request"]["limits"])
validate_counter(counter, limits)
# Each candidate is one UTF-8 byte. Token counts still depend on the frozen
# compatible counter, so try a bounded set instead of assuming one token.
for value in ("a", "0", ".", "x"):
try:
limits.validate_batch([value], counter)
except EmbeddingError:
continue
return value
raise EmbeddingError("No harmless probe fits the configured policy")
class ProbeCall:
"""Track the adapter invocation boundary without exposing provider objects."""
def __init__(self, provider):
self.provider = provider
self.called = False
self.returned = False
@property
def profile(self):
return self.provider.profile
@property
def request_policy(self):
return self.provider.request_policy
def embed(self, values):
self.called = True
result = self.provider.embed(values)
self.returned = True
return result
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--corpus", type=Path, action="append", required=True,
help="Explicit approved file; repeat for each file")
parser.add_argument("--allow-provider-calls", action="store_true", required=True,
help="Authorize sending these files to configured providers")
args = parser.parse_args(argv)
required = ("INGEST_EMBEDDING_PROVIDER", "INGEST_EMBEDDING_ENDPOINT",
"INGEST_EMBEDDING_MODEL", "INGEST_EMBEDDING_DIMENSIONS",
"INGEST_EMBEDDING_API_KEY", "INGEST_EMBEDDING_LIMITS")
if any(not os.environ.get(name, "").strip() for name in required):
print(json.dumps(dict(configuration="failed", category="explicit_provider_configuration_required")),
file=sys.stderr)
return 1
try:
# No deployment .env fallback and no database/storage initialization.
settings = IngestionSettings(_env_file=None,
database_url="postgresql+psycopg://unused/unused")
settings.require_embedding_credentials()
extractor_factory, provider_factory = factories(settings)
profile = settings.processing_profile()
provider, counter = provider_factory(profile)
except Exception:
print(json.dumps(dict(configuration="failed", category="invalid_configuration")), file=sys.stderr)
return 1
failed = False
# Compatibility is independent of corpus extraction and semantic quality.
compatible = False
probe_call = ProbeCall(provider)
try:
from app.modules.documents.types import ChunkDraft
probe = harmless_probe(profile, counter)
with stage_document(probe_call, document_id=uuid4(), chunks=[ChunkDraft(0, probe)],
processing_profile=profile, token_counter=counter):
compatible = True
print(json.dumps(dict(provider_compatibility="passed", dimensions=settings.embedding_dimensions,
semantic_quality="not_assessed")))
except Exception as error:
failed = True
category = ("probe_validation_failed" if not probe_call.called
else "provider_response_invalid" if probe_call.returned
else "provider_error" if isinstance(error, EmbeddingProviderError)
else "provider_check_failed")
print(json.dumps(dict(provider_compatibility="failed" if probe_call.called else "not_run",
category=category, semantic_quality="not_assessed")))
for index, path in enumerate(args.corpus):
result = dict(corpus_index=index, extraction_quality="not_assessed",
corpus_embedding="not_run", factual_authority="not_assessed", semantic_quality="manual_review_required")
stage = "input"
try:
source = prepare_file(path, None, settings)
stage = "extract"
envelope = extractor_factory(profile).extract_for_review(document_id=uuid4(),
title=source["title"], original_sha256=source["sha"], content=source["content"],
mime_type=source["mime"], processing_profile=profile)
result.update(extraction_quality="automated_checks_passed", blocks=len(envelope.blocks),
extraction_sha256=hashlib.sha256(envelope.model_dump_json().encode()).hexdigest())
artifact = dict(sha256=result["extraction_sha256"])
stage = "chunk"
chunks = prepare_chunks(envelope, profile, {}, artifact["sha256"])
result["factual_authority"] = "eligible"
if not compatible:
result["category"] = "provider_check_failed" if probe_call.called else "probe_validation_failed"
print(json.dumps(result))
continue
stage = "embed"
with stage_document(provider, document_id=envelope.document_id, chunks=chunks,
processing_profile=profile, token_counter=counter) as staged:
result.update(corpus_embedding="passed", chunks=len(staged.chunks))
except ReviewRequired:
failed = True
result.update(extraction_quality="review_required", category="review_required")
except FactualReviewRequired:
failed = True
result.update(factual_authority="review_required", category="factual_review_required")
except Exception:
failed = True
result["category"] = ("embedding_error" if stage == "embed"
else "chunking_error" if stage == "chunk" else "extraction_or_input_error")
print(json.dumps(result))
return int(failed)
if __name__ == "__main__":
sys.exit(main())
+33 -1
View File
@@ -14,7 +14,7 @@ Run ordinary tests:
~~~ ~~~
For database tests, configure an isolated TEST_DATABASE_URL as described in For database tests, configure an isolated TEST_DATABASE_URL as described in
[foundation setup](../docs/ingestion-foundation-setup.md), then run: [foundation setup](../docs/guides/ingestion-foundation-setup.md), then run:
~~~powershell ~~~powershell
.venv/Scripts/python -m tests.postgres_prerequisites .venv/Scripts/python -m tests.postgres_prerequisites
@@ -28,3 +28,35 @@ explicit acceptance; skipped database cases are not passing evidence.
Organization validation: installed environment full suite 163 passed; minimum Organization validation: installed environment full suite 163 passed; minimum
pgvector 0.3.6 PostgreSQL suite 48 passed. Both prerequisite checks passed. pgvector 0.3.6 PostgreSQL suite 48 passed. Both prerequisite checks passed.
Production code and migration history were unchanged. Production code and migration history were unchanged.
Phase 5 worker coverage is in unit/test_phase5.py and integration/test_phase5.py;
see [worker operations](../docs/guides/worker-orchestration.md). The 2026-10-07
provider-free full suite passed 1004 tests with 3 existing Windows symlink skips;
PostgreSQL acceptance passed 160 tests without skips on isolated PostgreSQL 16.15 /
pgvector 0.8.7. The final pointer guard rerun passed all 43 worker database tests.
Extended Phase 5 final acceptance (2026-10-07): provider-free **1050 passed,
3 existing Windows symlink skips**; isolated PostgreSQL **186 passed, no skips**.
New configuration/FAQ cases are in unit/test_phase5_review.py. The 69 worker/review
PostgreSQL cases include exact PDF/image/multi-page resume, concurrent decisions/
retry, source/lease races, revoked access, audit rollback and whole FAQ inclusion.
See [worker operations](../docs/guides/worker-orchestration.md) for the remaining
HTTP identity/Origin/CSRF dependency and real-provider limitations.
Phase 5 remaining-backend repair coverage is in unit/test_phase5_repairs.py and
integration/test_phase5.py: shared/section-specific FAQ conditions and exceptions,
excluded exclusive context, ambiguous/malformed relationship rejection, immutable
legacy factual review, identical versus conflicting attachment, stale/expired
fencing, bounded English/Persian review metadata, exact approved OCR resume,
genuine unreadability and context-preserving publication/mismatch rollback.
Latest full results: provider-free 1064 passed / 3 existing Windows symlink skips;
isolated PostgreSQL 196 passed, zero skips. See
[worker operations](../docs/guides/worker-orchestration.md) for exact commands,
database isolation and remaining HTTP/provider limitations.
Phase 6 integration proof lives in integration/test_phase6.py with real extraction
and support/embedding.py deterministic hash vectors. unit/test_phase6.py covers
opt-in provider smoke gates and redacted diagnostics. The real-provider command
python -m app.ingestion_smoke requires explicit corpus/provider configuration and
--allow-provider-calls; pytest never invokes a real provider. See the
[operator handoff](../docs/guides/ingestion-operator-handoff.md).
+397
View File
@@ -0,0 +1,397 @@
"""Operator-to-publication proof on disposable PostgreSQL and real extraction."""
from concurrent.futures import ThreadPoolExecutor
import json
import logging
from threading import Event
from uuid import uuid4
import pytest
from sqlalchemy import text
from app.infrastructure.extraction_candidates import LocalExtractionCandidates
from app.infrastructure.file_store import LocalFileStore
from app.infrastructure.intake_repository import SqlIntakeRepository
from app.infrastructure.worker_repository import SqlWorkerRepository
from app.modules.documents.chunking import chunk_extraction
from app.modules.documents.embeddings import EmbeddingLimits
from app.modules.documents.extraction import PageBlockExtractor
from app.modules.documents.intake import import_document, reconcile, status
from app.modules.documents.normalization import normalize_search_text
from app.modules.documents.worker import Worker
from tests.support.embedding import DeterministicEmbeddings
from tests.support.formats import docx_bytes
FIXTURE_PARAGRAPHS = ['Article 1\n'
'Pump pressure is 25 bar only when temperature is below 60 C. Do not open the bypass except '
'during shutdown.',
'Article 2\n'
'Flow is 40 liters per minute unless the inlet is blocked. Inspect seals every 30 days.',
'Article 3\nTorque is 15 Nm. Do not restart when leakage is present, except after inspection.']
# Literal rendered evidence, including paragraph separators; no chunker calls.
FIXTURE_ROWS = {'.md': [{'ordinal': 0,
'text': 'Article 1\n'
'Pump pressure is 25 bar only when temperature is below 60 C. Do not open the '
'bypass except during shutdown.\n',
'location': {'page': None, 'section': 'Article 1 | text/paragraph/1'}},
{'ordinal': 1,
'text': '\n'
'Article 2\n'
'Flow is 40 liters per minute unless the inlet is blocked. Inspect seals every '
'30 days.\n',
'location': {'page': None, 'section': 'text/paragraph/2'}},
{'ordinal': 2,
'text': '\n'
'Article 3\n'
'Torque is 15 Nm. Do not restart when leakage is present, except after '
'inspection.',
'location': {'page': None, 'section': 'text/paragraph/3'}}],
'.docx': [{'ordinal': 0,
'text': 'Article 1\n'
'Pump pressure is 25 bar only when temperature is below 60 C. Do not open the '
'bypass except during shutdown.\n',
'location': {'page': None, 'section': 'docx/paragraph/1'}},
{'ordinal': 1,
'text': 'Article 2\n'
'Flow is 40 liters per minute unless the inlet is blocked. Inspect seals every '
'30 days.\n',
'location': {'page': None, 'section': 'docx/paragraph/2'}},
{'ordinal': 2,
'text': 'Article 3\n'
'Torque is 15 Nm. Do not restart when leakage is present, except after '
'inspection.\n',
'location': {'page': None, 'section': 'docx/paragraph/3'}}]}
@pytest.fixture
def pipeline(migrated_db, settings, tmp_path):
engine, _ = migrated_db
settings = settings.model_copy(update=dict(
chunk_size_characters=256, chunk_overlap_characters=5, embedding_batch_size=2,
embedding_limits=EmbeddingLimits(unit="utf8_bytes", max_input_units=4096,
max_batch_units=8192, max_batch_inputs=2)))
org, actor = uuid4(), uuid4()
with engine.begin() as conn:
conn.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'phase6')"), dict(id=org))
conn.execute(text("""INSERT INTO users(id,organization_id,username,password_hash,role)
VALUES (:id,:org,:name,'test-only','admin')"""), dict(id=actor, org=org, name=str(actor)))
store = LocalFileStore(tmp_path / "originals")
candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=store.directory)
intake = SqlIntakeRepository(engine)
repo = SqlWorkerRepository(engine, settings)
return dict(engine=engine, settings=settings, store=store, candidates=candidates,
intake=intake, repo=repo, actor=actor, root=tmp_path)
def upload(p, suffix=".md", key=None):
source = p["root"] / ("corpus" + suffix)
paragraphs = FIXTURE_PARAGRAPHS
if suffix == ".docx":
xml = ('<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
'<w:body>' + ''.join('<w:p><w:r><w:t>' + value + '</w:t></w:r></w:p>'
for value in paragraphs) + '</w:body></w:document>')
source.write_bytes(docx_bytes(document=xml.encode()))
else:
source.write_bytes("\n\n".join(paragraphs).encode("utf-8"))
return import_document(p["intake"], p["store"], p["settings"], path=source,
administrator_id=p["actor"], request_id=key or uuid4())["document"]
def snapshot(p, document):
# All publication invariants are observed in one SQL statement/snapshot.
with p["engine"].connect() as conn:
value = conn.execute(text("""SELECT d.*, j.id AS job_id, j.status AS job_status,
j.stage AS job_stage, j.attempt_count, j.retry_generation, pg_backend_pid() AS observer_pid,
COALESCE((SELECT jsonb_agg(jsonb_build_object(
'ordinal',c.ordinal,'text',c.text,'location',c.location,
'dimension',vector_dims(c.embedding),'vector',c.embedding::text)
ORDER BY c.ordinal) FROM document_chunks c WHERE c.document_id=d.id),'[]'::jsonb) AS chunks,
(SELECT count(*) FROM document_chunks c WHERE c.document_id=d.id) AS actual_count
FROM documents d JOIN ingestion_jobs j ON j.document_id=d.id WHERE d.id=:id"""),
dict(id=document["id"])).mappings().one()
return dict(value)
def expected(p, document):
envelope = PageBlockExtractor().extract(document_id=document["id"], title=document["title"],
original_sha256=document["file_sha256"], content=p["store"].read(document["storage_key"]),
mime_type=document["mime_type"], processing_profile=document["processing_profile"])
drafts = tuple(chunk_extraction(envelope, document["processing_profile"]))
assert len(drafts) == 3
return drafts
def worker(p, provider):
return Worker(p["repo"], p["store"], p["candidates"], lambda _: PageBlockExtractor(),
lambda _: (provider, None), p["settings"])
def assert_fixed_fixture(state, document):
suffix = ".docx" if document["mime_type"].endswith("document") else ".md"
fixed = FIXTURE_ROWS[suffix]
observed = [{key: row[key] for key in ("ordinal", "text", "location")} for row in state["chunks"]]
assert observed == fixed, "Published rows differ from fixed fixture evidence"
# These requirements come from the source evidence, independently of drafts.
for phrase in ("25 bar", "below 60 C", "only when", "Do not open", "except during shutdown"):
assert phrase in observed[0]["text"]
for phrase in ("40 liters per minute", "unless the inlet is blocked", "30 days"):
assert phrase in observed[1]["text"]
for phrase in ("15 Nm", "Do not restart", "when leakage is present", "except after inspection"):
assert phrase in observed[2]["text"]
for row, evidence in zip(state["chunks"], fixed):
assert row["dimension"] == 3
assert json.loads(row["vector"]) == DeterministicEmbeddings.vector(evidence["text"])
def assert_published(p, document, drafts):
state = snapshot(p, document)
assert state["status"] == "ready" and state["job_status"] == "succeeded"
assert state["ready_at"] is not None and not state["is_active"]
assert state["actual_count"] == state["chunk_count"] == len(drafts)
assert state["processing_profile"] == document["processing_profile"]
assert_fixed_fixture(state, document)
rows = state["chunks"]
assert [row["ordinal"] for row in rows] == list(range(len(drafts)))
for row, draft in zip(rows, drafts):
assert row["text"] == draft.text
assert row["location"] == dict(page=draft.page, section=draft.section)
assert draft.section # actual source locators survive publication
assert row["dimension"] == document["processing_profile"]["embedding"]["dimensions"] == 3
assert json.loads(row["vector"]) == DeterministicEmbeddings.vector(normalize_search_text(draft.text))
@pytest.mark.parametrize("suffix", [".md", ".docx"])
def test_incomplete_batches_are_invisible_then_publish_exact_source_rows(pipeline, suffix, caplog):
p = pipeline
doc = upload(p, suffix)
drafts = expected(p, doc)
assert len(drafts) > 2
entered, release, heartbeat = Event(), Event(), Event()
class HeartbeatHandler(logging.Handler):
def emit(self, record):
if json.loads(record.getMessage())["category"] == "renewed":
heartbeat.set()
handler = HeartbeatHandler()
logger = logging.getLogger("app.modules.documents.worker")
logger.addHandler(handler)
p["settings"] = p["settings"].model_copy(update=dict(heartbeat_seconds=0.05, lease_seconds=5))
p["repo"].settings = p["settings"]
def observe(batch):
state = snapshot(p, doc)
assert state["actual_count"] == state["chunk_count"] == 0
assert state["status"] != "ready" and state["job_status"] == "processing"
assert state["ready_at"] is None and not state["is_active"]
if batch == 2:
entered.set()
assert release.wait(10)
provider = DeterministicEmbeddings(p["settings"], observe=observe)
caplog.set_level(logging.INFO, logger=logger.name)
try:
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(worker(p, provider).run_once, "phase6")
try:
assert entered.wait(10)
assert heartbeat.wait(5)
assert snapshot(p, doc)["actual_count"] == 0
finally:
release.set()
assert future.result(timeout=15)
finally:
logger.removeHandler(handler)
assert len(provider.calls) == (len(drafts) + 1) // 2
assert_published(p, doc, drafts)
records = [json.loads(r.getMessage()) for r in caplog.records if r.name == logger.name]
assert all(r["document_id"] == str(doc["id"]) for r in records)
assert all(r["job_id"] == str(snapshot(p, doc)["job_id"]) for r in records)
assert {r["stage"] for r in records} >= {"claim", "extract", "chunk", "embed", "publish", "heartbeat"}
assert records[-1]["category"] == "succeeded"
def test_failed_final_batch_retry_and_duplicate_imports(pipeline, caplog):
p = pipeline
key = uuid4()
doc = upload(p, key=key)
assert upload(p, key=key)["id"] == doc["id"]
independent = upload(p)
assert independent["id"] != doc["id"]
assert independent["file_sha256"] == doc["file_sha256"]
assert independent["storage_key"] != doc["storage_key"]
# Hold the independent upload out of the worker's eligible queue.
with p["engine"].begin() as conn:
conn.execute(text("UPDATE documents SET deleted_at=clock_timestamp() WHERE id=:id"),
dict(id=independent["id"]))
drafts = expected(p, doc)
provider = DeterministicEmbeddings(p["settings"], fail_at=(len(drafts) + 1) // 2,
observe=lambda _: assert_empty(p, doc))
caplog.set_level(logging.INFO, logger="app.modules.documents.worker")
assert worker(p, provider).run_once("failing")
state = snapshot(p, doc)
assert state["status"] == state["job_status"] == "failed"
assert state["job_stage"] == "embed" and state["actual_count"] == 0
assert len(provider.calls) == provider.fail_at > 1
assert "injected secret" not in caplog.text and "embedding_error" in caplog.text
retry_key = uuid4()
response = p["repo"].retry(administrator_id=p["actor"], document_id=doc["id"],
request_id=retry_key, store=p["store"])
replay = p["repo"].retry(administrator_id=p["actor"], document_id=doc["id"],
request_id=retry_key, store=p["store"])
assert not response["replayed"] and replay["replayed"]
queued = snapshot(p, doc)
assert queued["job_id"] == state["job_id"]
assert queued["retry_generation"] == 1 and queued["attempt_count"] == 0
assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("retried")
assert_published(p, doc, drafts)
assert p["repo"].retry(administrator_id=p["actor"], document_id=doc["id"],
request_id=retry_key, store=p["store"])["replayed"]
with p["engine"].connect() as conn:
assert conn.execute(text("SELECT count(*) FROM audit_events WHERE action='ingestion_retry'")).scalar_one() == 1
assert status(p["intake"], administrator_id=p["actor"], document_id=doc["id"])["status"] == "ready"
def assert_empty(p, doc):
state = snapshot(p, doc)
assert state["actual_count"] == state["chunk_count"] == 0 and state["status"] != "ready"
@pytest.mark.parametrize("boundary", ["before_publish", "after_commit", "expired", "deleted"])
def test_crash_and_late_publication_boundaries(pipeline, monkeypatch, boundary):
p = pipeline
doc = upload(p)
drafts = expected(p, doc)
original = p["repo"].publish
def intercepted(claim, staged, candidates, store):
assert_empty(p, doc)
if boundary == "before_publish":
raise RuntimeError("simulated process death")
if boundary in ("expired", "deleted"):
with p["engine"].begin() as conn:
conn.execute(text("UPDATE ingestion_jobs SET lease_expires_at=clock_timestamp()-interval '1 second'"
if boundary == "expired" else "UPDATE documents SET deleted_at=clock_timestamp()"))
result = original(claim, staged, candidates, store)
if boundary == "after_commit":
raise RuntimeError("simulated death after committed publication")
return result
monkeypatch.setattr(p["repo"], "publish", intercepted)
if boundary in ("before_publish", "after_commit"):
with pytest.raises(RuntimeError, match="simulated"):
worker(p, DeterministicEmbeddings(p["settings"])).run_once("crashed")
else:
assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("late")
monkeypatch.setattr(p["repo"], "publish", original)
if boundary == "after_commit":
assert_published(p, doc, drafts)
assert not worker(p, DeterministicEmbeddings(p["settings"])).run_once("restart")
assert_published(p, doc, drafts)
elif boundary == "deleted":
assert_empty(p, doc)
assert not worker(p, DeterministicEmbeddings(p["settings"])).run_once("restart")
else:
assert_empty(p, doc)
with p["engine"].begin() as conn:
conn.execute(text("UPDATE ingestion_jobs SET lease_expires_at=clock_timestamp()-interval '1 second'"))
assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("reclaimed")
assert_published(p, doc, drafts)
assert snapshot(p, doc)["attempt_count"] == 2
def test_missing_original_is_reported_and_never_published(pipeline):
p = pipeline
doc = upload(p)
p["store"]._path(doc["storage_key"]).unlink()
provider = DeterministicEmbeddings(p["settings"])
assert worker(p, provider).run_once("missing")
assert_empty(p, doc)
assert not provider.calls
report = reconcile(p["intake"], p["store"])
assert report["report_only"]
assert [r["document_id"] for r in report["missing_originals"]] == [str(doc["id"])]
@pytest.mark.parametrize("suffix", [".md", ".docx"])
def test_shared_chunker_number_mutation_is_detected(pipeline, monkeypatch, suffix):
# Both worker preparation and publication validation use the same altered
# chunker; an implementation-derived oracle alone accepts the wrong number.
from dataclasses import replace
from app.modules.documents import review
p = pipeline
doc = upload(p, suffix)
real_chunker = chunk_extraction
def changed_number(*args, **kwargs):
return tuple(replace(d, text=d.text.replace("25 bar", "26 bar"))
for d in real_chunker(*args, **kwargs))
monkeypatch.setattr(review, "chunk_extraction", changed_number)
drafts = tuple(replace(d, text=d.text.replace("25 bar", "26 bar")) for d in expected(p, doc))
assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("mutated")
state = snapshot(p, doc)
assert state["status"] == "ready" and state["job_status"] == "succeeded"
assert state["chunks"][0]["text"] == drafts[0].text
with pytest.raises(AssertionError, match="fixed fixture"):
assert_published(p, doc, drafts)
@pytest.mark.parametrize("suffix", [".md", ".docx"])
def test_publication_is_invisible_after_inserts_and_completion_updates(pipeline, suffix):
from sqlalchemy import event
p = pipeline
doc = upload(p, suffix)
drafts = expected(p, doc)
after_inserts, release_inserts, after_updates, release_updates = (Event() for _ in range(4))
inserted = []
publisher_pid = []
# Bounded barriers finish well before the first heartbeat; no background
# heartbeat needs to queue behind the intentionally paused document lock.
p["settings"] = p["settings"].model_copy(update=dict(heartbeat_seconds=60, lease_seconds=120))
p["repo"].settings = p["settings"]
def pause(conn, cursor, statement, parameters, context, executemany):
if statement.lstrip().startswith("INSERT INTO document_chunks"):
inserted.append(1)
if len(inserted) == len(drafts):
publisher_pid.append(conn.execute(text("SELECT pg_backend_pid()")).scalar_one())
after_inserts.set()
assert release_inserts.wait(10), "insert barrier timed out"
elif "UPDATE ingestion_jobs" in statement and "status='succeeded'" in statement:
# This callback runs after both document and job completion writes,
# still inside the production publication transaction.
after_updates.set()
assert release_updates.wait(10), "completion barrier timed out"
event.listen(p["engine"], "after_cursor_execute", pause)
try:
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(worker(p, DeterministicEmbeddings(p["settings"])).run_once, "atomic")
try:
assert after_inserts.wait(10), "publisher did not reach insert barrier"
before = snapshot(p, doc)
assert before["observer_pid"] != publisher_pid[0]
assert before["chunks"] == [] and before["actual_count"] == before["chunk_count"] == 0
assert before["status"] == before["job_status"] == "processing"
assert before["ready_at"] is None and not before["is_active"]
release_inserts.set()
assert after_updates.wait(10), "publisher did not reach completion barrier"
uncommitted = snapshot(p, doc)
assert uncommitted["observer_pid"] != publisher_pid[0]
assert uncommitted["chunks"] == [] and uncommitted["actual_count"] == uncommitted["chunk_count"] == 0
assert uncommitted["status"] == uncommitted["job_status"] == "processing"
assert uncommitted["ready_at"] is None and not uncommitted["is_active"]
finally:
release_inserts.set()
release_updates.set()
assert future.result(timeout=15)
finally:
release_inserts.set()
release_updates.set()
event.remove(p["engine"], "after_cursor_execute", pause)
assert len(inserted) == len(drafts)
assert_published(p, doc, drafts)
+14 -1
View File
@@ -18,7 +18,20 @@ def audit(event, args):
raise AssertionError("Unexpected I/O: " + event) raise AssertionError("Unexpected I/O: " + event)
sys.addaudithook(audit) sys.addaudithook(audit)
for name in ("app.modules.documents.settings", "app.modules.documents.types", for name in ("app.modules.documents.settings", "app.modules.documents.types",
"app.modules.documents.ports", "app.infrastructure.database", "app.bootstrap"): "app.modules.documents.ports", "app.infrastructure.database", "app.bootstrap", "app.ingest",
"app.infrastructure.file_store",
"app.modules.documents.intake", "app.modules.documents.formats",
"app.modules.documents.errors", "app.modules.documents.extraction_artifacts",
"app.modules.documents.normalization",
"app.modules.documents.extraction", "app.modules.documents.chunking",
"app.modules.documents.processing", "app.infrastructure.gemini_vision",
"app.infrastructure.extraction_candidates",
"app.infrastructure.intake_repository",
"app.modules.documents.embeddings", "app.infrastructure.openai_embeddings",
"app.modules.documents.worker", "app.infrastructure.worker_repository", "app.worker",
"app.modules.documents.review", "app.modules.documents.operational_limits",
"app.infrastructure.review_candidates", "app.infrastructure.review_repository",
"app.ingestion_smoke"):
importlib.import_module(name) importlib.import_module(name)
assert "app.core.config" not in sys.modules assert "app.core.config" not in sys.modules
""" """
+249
View File
@@ -0,0 +1,249 @@
"""Smoke stays opt-in; provider compatibility and extraction are distinct."""
import json
import logging
import subprocess
import sys
from uuid import uuid4
import pytest
from app import ingestion_smoke
from app.modules.documents.embeddings import EmbeddingLimits
from app.modules.documents.worker import Claim, report
from tests.support.embedding import DeterministicEmbeddings
def configure(monkeypatch, settings):
settings = settings.model_copy(update=dict(embedding_limits=EmbeddingLimits(
unit="utf8_bytes", max_input_units=4096, max_batch_units=8192, max_batch_inputs=2)))
for key, value in dict(embedding_provider=settings.embedding_provider,
embedding_endpoint=settings.embedding_endpoint, embedding_model=settings.embedding_model,
embedding_dimensions=str(settings.embedding_dimensions), embedding_api_key="private-secret",
embedding_limits=json.dumps(settings.embedding_limits.model_dump())).items():
monkeypatch.setenv("INGEST_" + key.upper(), value)
return settings
@pytest.mark.parametrize("args", [[], ["--corpus", "unapproved.md"], ["--allow-provider-calls"]])
def test_smoke_requires_explicit_opt_in_and_corpus(args):
result = subprocess.run([sys.executable, "-m", "app.ingestion_smoke", *args],
capture_output=True, text=True)
assert result.returncode == 2
assert "required" in result.stderr
def test_smoke_help_is_independent():
result = subprocess.run([sys.executable, "-m", "app.ingestion_smoke", "--help"],
capture_output=True, text=True)
assert result.returncode == 0 and "--allow-provider-calls" in result.stdout
def test_smoke_requires_explicit_environment_before_factories(monkeypatch, capsys):
monkeypatch.setattr(ingestion_smoke, "factories", lambda _: pytest.fail("No implicit provider work"))
assert ingestion_smoke.main(["--corpus", "unapproved.md", "--allow-provider-calls"]) == 1
assert "explicit_provider_configuration_required" in capsys.readouterr().err
@pytest.mark.parametrize("failure", [None, "input", "provider", "corpus_embedding"])
def test_smoke_reports_compatibility_and_quality_independently(settings, monkeypatch, tmp_path, capsys, failure):
settings = configure(monkeypatch, settings)
provider = DeterministicEmbeddings(settings, fail_at=1 if failure == "provider"
else 2 if failure == "corpus_embedding" else None)
from app.modules.documents.extraction import PageBlockExtractor
monkeypatch.setattr(ingestion_smoke, "factories",
lambda _: (lambda _: PageBlockExtractor(), lambda _: (provider, None)))
source = tmp_path / "approved.md"
source.write_text("Pump pressure remains 25 bar. Inspect seals every 30 days.", encoding="utf-8")
if failure == "input":
source.unlink()
code = ingestion_smoke.main(["--corpus", str(source), "--allow-provider-calls"])
output = capsys.readouterr()
records = [json.loads(line) for line in output.out.splitlines()]
assert code == int(failure is not None)
assert records[0]["provider_compatibility"] == ("failed" if failure == "provider" else "passed")
assert records[1]["extraction_quality"] == ("not_assessed" if failure == "input" else "automated_checks_passed")
assert records[1]["semantic_quality"] == "manual_review_required"
assert "private-secret" not in output.out + output.err
assert "injected secret" not in output.out + output.err
assert "Pump pressure" not in output.out + output.err
def test_worker_report_redacts_source_and_configuration(caplog):
claim = Claim(dict(id=uuid4(), title="private source", processing_profile={"key": "secret"}),
uuid4(), uuid4(), 1, 0)
caplog.set_level(logging.INFO, logger="app.modules.documents.worker")
report(claim, "embed", "embedding_error")
record = json.loads(caplog.records[0].getMessage())
assert record == dict(document_id=str(claim.document["id"]), job_id=str(claim.job_id),
stage="embed", category="embedding_error")
assert "private source" not in caplog.text and "secret" not in caplog.text
@pytest.mark.parametrize("kind", ["pdf", "faq"])
def test_smoke_keeps_review_quality_separate_from_provider_compatibility(settings, monkeypatch, tmp_path, capsys, kind):
settings = configure(monkeypatch, settings)
provider = DeterministicEmbeddings(settings)
from app.modules.documents.extraction import PageBlockExtractor
monkeypatch.setattr(ingestion_smoke, "factories",
lambda _: (lambda _: PageBlockExtractor(), lambda _: (provider, None)))
path = tmp_path / ("approved." + ("pdf" if kind == "pdf" else "md"))
if kind == "pdf":
import pymupdf
with pymupdf.open() as doc:
doc.new_page().insert_text((50, 50), "Pump pressure remains 25 bar. Inspect seals every 30 days.")
path.write_bytes(doc.tobytes())
else:
path.write_text("Question: What is the pump pressure?\n\nAnswer: The pump pressure is 25 bar.", encoding="utf-8")
assert ingestion_smoke.main(["--corpus", str(path), "--allow-provider-calls"]) == 1
records = [json.loads(line) for line in capsys.readouterr().out.splitlines()]
assert records[0]["provider_compatibility"] == "passed"
assert records[1]["corpus_embedding"] == "not_run"
assert records[1]["extraction_quality"] == ("review_required" if kind == "pdf" else "automated_checks_passed")
if kind == "faq":
assert records[1]["factual_authority"] == "review_required"
assert provider.calls == [("a",)]
@pytest.mark.parametrize("unit,input_limit,batch_limit", [
("utf8_bytes", 1, 1), ("utf8_bytes", 4, 4),
("tokens", 1, 1), ("tokens", 2, 2),
])
def test_probe_respects_restrictive_input_and_single_input_batch(settings, monkeypatch, tmp_path, capsys,
unit, input_limit, batch_limit):
settings = configure(monkeypatch, settings)
limits = EmbeddingLimits(unit=unit, max_input_units=input_limit,
max_batch_units=batch_limit, max_batch_inputs=1,
tokenizer="test:compatible" if unit == "tokens" else None)
settings = settings.model_copy(update={"embedding_limits": limits})
monkeypatch.setenv("INGEST_EMBEDDING_LIMITS", limits.model_dump_json())
frozen = settings.processing_profile()
measured = []
class Counter:
identity = "test:compatible"
def count(self, value):
measured.append(value)
return 1 if len(value) == 1 else 3
counter = Counter() if unit == "tokens" else None
provider = DeterministicEmbeddings(settings)
from app.modules.documents.extraction import PageBlockExtractor
monkeypatch.setattr(ingestion_smoke, "factories",
lambda _: (lambda _: PageBlockExtractor(), lambda _: (provider, counter)))
source = tmp_path / "approved.md"
source.write_text("a", encoding="utf-8")
assert ingestion_smoke.main(["--corpus", str(source), "--allow-provider-calls"]) == 0
records = [json.loads(line) for line in capsys.readouterr().out.splitlines()]
assert records[0]["provider_compatibility"] == "passed"
assert provider.calls and all(limits.validate_batch(call, counter) for call in provider.calls)
assert len(provider.calls[0]) == 1
assert settings.processing_profile() == frozen
if counter:
assert provider.calls[0][0] in measured
def test_one_byte_probe_reaches_hosted_provider_request(settings, monkeypatch, tmp_path, capsys):
from io import BytesIO
from app.infrastructure.openai_embeddings import OpenAICompatibleEmbeddings
from app.modules.documents.extraction import PageBlockExtractor
settings = configure(monkeypatch, settings)
limits = EmbeddingLimits(unit="utf8_bytes", max_input_units=1, max_batch_units=1, max_batch_inputs=1)
settings = settings.model_copy(update={"embedding_limits": limits})
monkeypatch.setenv("INGEST_EMBEDDING_LIMITS", limits.model_dump_json())
requests = []
class Opener:
def open(self, request, timeout):
requests.append(json.loads(request.data))
return BytesIO(json.dumps(dict(model=settings.embedding_model,
data=[dict(index=0, embedding=[1, 0, 0])])).encode())
monkeypatch.setattr("app.infrastructure.openai_embeddings.build_opener", lambda *args: Opener())
provider = OpenAICompatibleEmbeddings(profile=settings.embedding_profile,
api_key="test-only-key", limits=limits)
monkeypatch.setattr(ingestion_smoke, "factories",
lambda _: (lambda _: PageBlockExtractor(), lambda _: (provider, None)))
source = tmp_path / "approved.md"
source.write_text("a", encoding="utf-8")
assert ingestion_smoke.main(["--corpus", str(source), "--allow-provider-calls"]) == 0
records = [json.loads(line) for line in capsys.readouterr().out.splitlines()]
assert records[0]["provider_compatibility"] == "passed"
assert requests and len(requests[0]["input"][0].encode("utf-8")) == 1
assert requests[0]["input"] != ["compatibility probe"]
@pytest.mark.parametrize("failure", ["staging_budget", "counter_identity", "probe_too_large"])
def test_local_probe_failure_is_not_provider_incompatibility(settings, monkeypatch, tmp_path, capsys, failure):
settings = configure(monkeypatch, settings)
limits = EmbeddingLimits(unit="tokens", tokenizer="test:compatible",
max_input_units=1, max_batch_units=1, max_batch_inputs=1)
settings = settings.model_copy(update={"embedding_limits": limits})
monkeypatch.setenv("INGEST_EMBEDDING_LIMITS", limits.model_dump_json())
if failure == "staging_budget":
monkeypatch.setenv("INGEST_MAX_STAGED_BYTES", "1")
class Counter:
identity = "wrong:secret" if failure == "counter_identity" else "test:compatible"
def count(self, value):
return 2 if failure == "probe_too_large" else 1
provider = DeterministicEmbeddings(settings)
from app.modules.documents.extraction import PageBlockExtractor
monkeypatch.setattr(ingestion_smoke, "factories",
lambda _: (lambda _: PageBlockExtractor(), lambda _: (provider, Counter())))
source = tmp_path / "approved.md"
source.write_text("a", encoding="utf-8")
assert ingestion_smoke.main(["--corpus", str(source), "--allow-provider-calls"]) == 1
output = capsys.readouterr()
record = json.loads(output.out.splitlines()[0])
assert record["provider_compatibility"] == "not_run"
assert record["category"] == "probe_validation_failed"
assert not provider.calls
assert "wrong:secret" not in output.out + output.err
def test_bad_provider_vectors_remain_provider_failure(settings, monkeypatch, tmp_path, capsys):
settings = configure(monkeypatch, settings)
class BadVectors(DeterministicEmbeddings):
def embed(self, values):
super().embed(values)
return [[1, 0] for _ in values]
provider = BadVectors(settings)
from app.modules.documents.extraction import PageBlockExtractor
monkeypatch.setattr(ingestion_smoke, "factories",
lambda _: (lambda _: PageBlockExtractor(), lambda _: (provider, None)))
source = tmp_path / "approved.md"
source.write_text("a", encoding="utf-8")
assert ingestion_smoke.main(["--corpus", str(source), "--allow-provider-calls"]) == 1
record = json.loads(capsys.readouterr().out.splitlines()[0])
assert provider.calls
assert record["provider_compatibility"] == "failed"
assert record["category"] == "provider_response_invalid"
def test_token_probe_uses_counter_to_select_a_fitting_candidate(settings, monkeypatch, tmp_path, capsys):
settings = configure(monkeypatch, settings)
limits = EmbeddingLimits(unit="tokens", tokenizer="test:compatible",
max_input_units=1, max_batch_units=1, max_batch_inputs=1)
settings = settings.model_copy(update={"embedding_limits": limits})
monkeypatch.setenv("INGEST_EMBEDDING_LIMITS", limits.model_dump_json())
counted = []
class Counter:
identity = "test:compatible"
def count(self, value):
counted.append(value)
return 1 if value == "0" else 2
counter = Counter()
provider = DeterministicEmbeddings(settings)
from app.modules.documents.extraction import PageBlockExtractor
monkeypatch.setattr(ingestion_smoke, "factories",
lambda _: (lambda _: PageBlockExtractor(), lambda _: (provider, counter)))
source = tmp_path / "approved.md"
source.write_text("0", encoding="utf-8")
assert ingestion_smoke.main(["--corpus", str(source), "--allow-provider-calls"]) == 0
assert provider.calls[0] == ("0",)
assert counted[:2] == ["a", "0"]
assert json.loads(capsys.readouterr().out.splitlines()[0])["provider_compatibility"] == "passed"