- 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
144 lines
6.5 KiB
Python
144 lines
6.5 KiB
Python
"""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())
|