feat(backend): deliver Phase 3 document and voice integration

Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
This commit is contained in:
11linear11
2026-10-09 17:43:52 -04:00
parent 9be47191d6
commit a73a496c54
67 changed files with 5988 additions and 234 deletions
@@ -0,0 +1,131 @@
"""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'])
def test_native_recognition_diagnostics_preserve_candidate_and_force_review(settings, monkeypatch, provider, diagnostic):
profile = settings.model_copy(update={'ocr_review_required': False, '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')
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)