178 lines
11 KiB
Python
178 lines
11 KiB
Python
"""Deterministic source/review and uncalibrated admission regressions."""
|
|
import hashlib
|
|
import json
|
|
from uuid import uuid4
|
|
import pytest
|
|
from app.modules.documents.extraction import PageBlockExtractor, ReviewRequired
|
|
from app.modules.documents.chunking import factual_review_blocks
|
|
from app.modules.documents.review import prepare_chunks, FactualReviewRequired
|
|
from tests.unit.test_phase5_repairs import factual
|
|
from tests.unit.test_gemini_vision import native, run
|
|
from tests.support.formats import docx_bytes, image_bytes
|
|
from tests.support.extraction import FakeVision
|
|
|
|
@pytest.mark.parametrize('heading', ['', '# Benefits\n'])
|
|
def test_initial_context_is_shared_and_requires_independent_factual_approval(settings, heading):
|
|
content = 'Benefits title\nOnly permanent employees; except contractors.\n' + heading
|
|
content += ''.join(f'Question: allowance {i}?\nAnswer: {i}% unless excluded.\n' for i in range(100))
|
|
raw, profile, envelope, state = factual(content, settings)
|
|
assert ''.join(b.text for b in envelope.blocks).encode() == raw
|
|
assert factual_review_blocks(envelope) == envelope.blocks
|
|
with pytest.raises(FactualReviewRequired):
|
|
prepare_chunks(envelope, profile, {}, 'a'*64)
|
|
chunks = prepare_chunks(envelope, profile, state, 'a'*64)
|
|
assert len(chunks) == 100
|
|
for i, chunk in enumerate(chunks):
|
|
assert 'Benefits title' in chunk.text and 'except contractors' in chunk.text
|
|
assert f'allowance {i}?' in chunk.text and f'{i}% unless excluded' in chunk.text
|
|
assert envelope.blocks[0].source_locator in chunk.section
|
|
|
|
|
|
def test_unstyled_word_title_preserves_all_pairs(settings):
|
|
paragraphs = ['Unstyled FAQ title', 'Question: rate?', 'Answer: 5%.', 'Question: leave?', 'Answer: 10 days.']
|
|
xml = '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>'
|
|
xml += ''.join('<w:p><w:r><w:t>'+p+'</w:t></w:r></w:p>' for p in paragraphs)
|
|
content = docx_bytes(document=(xml+'</w:body></w:document>').encode())
|
|
envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title='FAQ',
|
|
original_sha256=hashlib.sha256(content).hexdigest(), content=content,
|
|
mime_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
processing_profile=settings.processing_profile())
|
|
units = factual_review_blocks(envelope)
|
|
assert units == envelope.blocks and len([b for b in units if b.block_type == 'question']) == 2
|
|
|
|
|
|
@pytest.mark.parametrize('provider', ['gemini', 'openrouter'])
|
|
@pytest.mark.parametrize('diagnostic', ['incomplete', 'warning', 'region'])
|
|
@pytest.mark.parametrize('partial', [False, True])
|
|
def test_native_recognition_diagnostics_preserve_candidate_and_force_review(settings, monkeypatch, provider, diagnostic, partial):
|
|
profile = settings.model_copy(update={'ocr_review_required': False, 'allow_partial_extraction': partial, 'vision_provider': provider,
|
|
'vision_endpoint': 'https://example.invalid/v1beta', 'vision_model': 'fixture-flash'}).processing_profile()
|
|
payload = native(profile)
|
|
transcript = json.loads(payload['candidates'][0]['content']['parts'][0]['text'])
|
|
if diagnostic == 'incomplete': transcript['complete'] = False
|
|
if diagnostic == 'warning': transcript['warnings'] = ['Uncertain order']
|
|
if diagnostic == 'region': transcript['blocks'][1]['warnings'] = ['unreadable margin']
|
|
text = json.dumps(transcript)
|
|
if provider == 'gemini':
|
|
payload['candidates'][0]['content']['parts'][0]['text'] = text
|
|
blocks = run(profile, payload, monkeypatch)
|
|
else:
|
|
from io import BytesIO
|
|
from app.infrastructure.openrouter_vision import OpenRouterVision
|
|
class Opener:
|
|
def open(self, request, *, timeout):
|
|
return BytesIO(json.dumps({'choices':[{'message':{'content':text}}]}).encode())
|
|
monkeypatch.setattr('app.infrastructure.openrouter_vision.build_opener', lambda *a: Opener())
|
|
blocks = OpenRouterVision(endpoint='https://example.invalid/v1beta',model='fixture-flash',
|
|
api_key='fixture-only', timeout_seconds=60).transcribe(image_bytes(), page=None, section='image', processing_profile=profile)
|
|
assert [b.text for b in blocks] == [b['text'] for b in transcript['blocks']]
|
|
assert any(b.warnings for b in blocks)
|
|
class RetainedVision:
|
|
def transcribe(self, *args, **kw): return blocks
|
|
raw = image_bytes('PNG')
|
|
if partial:
|
|
result = PageBlockExtractor(RetainedVision()).extract_for_review(document_id=uuid4(),title='Image',
|
|
original_sha256=hashlib.sha256(raw).hexdigest(),content=raw,mime_type='image/png', processing_profile=profile)
|
|
assert result.quality_decision == 'accepted_with_warnings' and not result.review_annotations
|
|
assert result.blocks == blocks
|
|
return
|
|
with pytest.raises(ReviewRequired) as pending:
|
|
PageBlockExtractor(RetainedVision()).extract_for_review(document_id=uuid4(),title='Image',
|
|
original_sha256=hashlib.sha256(raw).hexdigest(),content=raw,mime_type='image/png', processing_profile=profile)
|
|
assert tuple(pending.value.blocks) == blocks
|
|
|
|
|
|
def test_pending_calibration_is_opt_in_transport_policy(settings, monkeypatch, tmp_path):
|
|
from app.api.v1 import live
|
|
from app.modules.voice.configuration import VoiceSettings
|
|
monkeypatch.setattr(live, 'IngestionSettings', lambda: settings.model_copy(update={'embedding_api_key': 'fixture'}))
|
|
report = tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
|
|
config = VoiceSettings(_env_file=None,gemini_api_key='fixture',search_calibration_report=report)
|
|
with pytest.raises(ValueError, match='CALIBRATION_REQUIRED'): live.capability(config)
|
|
assert live.capability(config.model_copy(update={'voice_transport_testing':True})) is None
|
|
assert live.search_profile(None, settings)['calibration_status'] == 'uncalibrated'
|
|
assert 'distance' not in live.search_profile(None, settings)
|
|
|
|
@pytest.mark.parametrize('testing',[False,True])
|
|
def test_search_dependency_pending_report_keeps_calibration_gate(settings,monkeypatch,tmp_path,testing):
|
|
from app.api.v1 import dependencies as d
|
|
from app.modules.voice.configuration import VoiceSettings
|
|
from app.modules.knowledge.evidence import SearchExecution
|
|
from fastapi import HTTPException
|
|
report=tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
|
|
config=VoiceSettings(_env_file=None,search_calibration_report=report,voice_transport_testing=testing)
|
|
monkeypatch.setattr(d,'VoiceSettings',lambda:config)
|
|
monkeypatch.setattr(d,'IngestionSettings',lambda:settings)
|
|
monkeypatch.setattr(d,'_SEARCH_SERVICE',None)
|
|
constructions=[]
|
|
def provider(profile):
|
|
constructions.append(profile)
|
|
return object(),None
|
|
monkeypatch.setattr('app.worker.factories',lambda settings:(None,provider))
|
|
if not testing:
|
|
with pytest.raises(HTTPException) as error: d.get_search_service(object())
|
|
assert error.value.status_code==503 and constructions==[]
|
|
else:
|
|
service=d.get_search_service(object())
|
|
assert service.cutoff is None and len(constructions)==1
|
|
result=service.search(SearchExecution(uuid4()),'source question')
|
|
assert result['sources']==[] and result['error']['code']=='CALIBRATION_REQUIRED'
|
|
|
|
|
|
@pytest.mark.parametrize('failure',['invalid_json','empty','truncated','unreadable_text'])
|
|
def test_openrouter_fatal_output_stays_fatal(settings,monkeypatch,failure):
|
|
from io import BytesIO
|
|
from app.infrastructure.openrouter_vision import OpenRouterVision
|
|
from app.modules.documents.extraction import ExtractionError
|
|
profile=settings.model_copy(update={'vision_provider':'openrouter','vision_endpoint':'https://example.invalid/v1beta','vision_model':'fixture-flash'}).processing_profile()
|
|
blocks=FakeVision().transcribe(b'',page=None,section='image',processing_profile=profile)
|
|
transcript={'complete':True,'warnings':[],'blocks':[b.model_dump(mode='json') for b in blocks]}
|
|
if failure=='empty': transcript['blocks']=[]
|
|
if failure=='unreadable_text': transcript['blocks'][1]['text']='\ufffd'
|
|
content='broken json' if failure=='invalid_json' else json.dumps(transcript)
|
|
value={'choices':[{'finish_reason':'length' if failure=='truncated' else 'stop','message':{'content':content}}]}
|
|
class Opener:
|
|
def open(self,request,*,timeout): return BytesIO(json.dumps(value).encode())
|
|
monkeypatch.setattr('app.infrastructure.openrouter_vision.build_opener',lambda *a:Opener())
|
|
with pytest.raises(ExtractionError):
|
|
OpenRouterVision(endpoint='https://example.invalid/v1beta',model='fixture-flash',api_key='fixture',timeout_seconds=60).transcribe(image_bytes(),page=None,section='image',processing_profile=profile)
|
|
|
|
|
|
@pytest.mark.parametrize("partial,variant,accepted", [
|
|
(True, "alias", True), (False, "alias", False),
|
|
(True, "same", True), (True, "conflict", False),
|
|
(True, "empty", False), (True, "wrong_type", False),
|
|
(True, "unknown_extra", False),
|
|
])
|
|
def test_openrouter_observed_text_alias_preserves_text_and_rejects_ambiguity(
|
|
settings, monkeypatch, partial, variant, accepted):
|
|
from io import BytesIO
|
|
from app.infrastructure.openrouter_vision import OpenRouterVision
|
|
from app.modules.documents.extraction import ExtractionError
|
|
profile = settings.model_copy(update={"allow_partial_extraction":partial,
|
|
"vision_provider":"openrouter", "vision_endpoint":"https://example.invalid/v1beta",
|
|
"vision_model":"fixture-flash"}).processing_profile()
|
|
transcript = json.loads(native(profile)["candidates"][0]["content"]["parts"][0]["text"])
|
|
original = [b["text"] for b in transcript["blocks"]]
|
|
for b in transcript["blocks"]:
|
|
b["text_content"] = b.pop("text")
|
|
if variant == "same": b["text"] = b["text_content"]
|
|
if variant == "conflict": b["text"] = "DIFFERENT SOURCE"
|
|
if variant == "empty": b["text_content"] = ""
|
|
if variant == "wrong_type": b["text_content"] = ["not a string"]
|
|
if variant == "unknown_extra": b["unknown_content"] = "unexpected"
|
|
class Opener:
|
|
def open(self, request, *, timeout):
|
|
return BytesIO(json.dumps({"choices":[{"message":{"content":json.dumps(transcript)}}]}).encode())
|
|
monkeypatch.setattr("app.infrastructure.openrouter_vision.build_opener", lambda *a: Opener())
|
|
adapter = OpenRouterVision(endpoint="https://example.invalid/v1beta", model="fixture-flash",
|
|
api_key="fixture-only", timeout_seconds=60)
|
|
if not accepted:
|
|
with pytest.raises(ExtractionError):
|
|
adapter.transcribe(image_bytes(),page=None,section="image",processing_profile=profile)
|
|
else:
|
|
blocks = adapter.transcribe(image_bytes(),page=None,section="image",processing_profile=profile)
|
|
assert [b.text for b in blocks] == original
|
|
assert all("Provider text_content field mapped verbatim to text" in b.warnings for b in blocks)
|
|
assert blocks[1].parent_block_id == blocks[0].block_id
|