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:
@@ -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())
|
||||
@@ -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())
|
||||
Reference in New Issue
Block a user