Freeze temporary partial-extraction admission in new uploads. Bypass manual approval, retain recognition warnings, and accept ambiguous legal references during bounded chunking. Preserve strict defaults, immutable evidence and atomic publication. Expose effective policy and safe failure categories with regression coverage.
172 lines
12 KiB
Python
172 lines
12 KiB
Python
"""Real isolated database and ASGI evidence; synthetic providers only."""
|
|
import json
|
|
from uuid import UUID, uuid4
|
|
import pytest
|
|
from sqlalchemy import text
|
|
from app.api.v1 import dependencies, live
|
|
from tests.integration.test_phase2_postgres import seeded_env, api, login
|
|
from tests.integration.test_realtime_phase3_http import document_api, upload, process, polling
|
|
from tests.support.extraction import FakeVision
|
|
from tests.support.formats import image_bytes
|
|
from tests.unit.test_realtime_phase1 import until
|
|
|
|
@pytest.mark.parametrize('diagnostic', ['Uncertain order', 'unreadable margin'])
|
|
def test_warning_candidate_requires_decision_then_resumes_without_provider_repeat(document_api, diagnostic):
|
|
client, _, _, e = document_api; headers = login(client, e)
|
|
e.settings = e.settings.model_copy(update={'ocr_review_required':False,'vision_provider':'gemini',
|
|
'vision_endpoint':'https://test.invalid','vision_model':'fixture-flash'})
|
|
uploaded = upload(client, headers, image_bytes('PNG'), 'warning.png').json()
|
|
identifier = uploaded['document_id']; vision = FakeVision(warnings=(diagnostic,))
|
|
process(e, vision)
|
|
detail = polling(client, identifier)
|
|
assert detail['review_required'] and detail['review_state'] == 'pending'
|
|
assert not detail['searchable'] and not detail['job']['can_retry']
|
|
with e.engine.connect() as conn:
|
|
assert conn.execute(text('SELECT count(*) FROM document_chunks WHERE document_id=:id'),{'id':UUID(identifier)}).scalar_one() == 0
|
|
item, = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items']
|
|
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve',checked=item['required_checks'],note='Synthetic complete source inspection')
|
|
endpoint = f'/api/v1/documents/{identifier}/extraction-review/decisions'; key = str(uuid4())
|
|
assert client.post(endpoint,json=decision,headers=dict(headers,**{'Idempotency-Key':key})).status_code == 200
|
|
assert client.post(endpoint,json=decision,headers=dict(headers,**{'Idempotency-Key':key})).headers['Idempotency-Replayed'] == 'true'
|
|
retry = client.post(f'/api/v1/documents/{identifier}/retry',headers=dict(headers,**{'Idempotency-Key':str(uuid4())}))
|
|
assert retry.status_code == 202 and retry.json()['job_id'] == uploaded['job_id']
|
|
process(e, vision)
|
|
assert len(vision.calls) == 1
|
|
detail = polling(client,identifier)
|
|
assert detail['status'] == 'ready' and detail['extraction_quality_decision'] == 'reviewed'
|
|
assert not detail['is_active'] and not detail['searchable']
|
|
|
|
|
|
@pytest.mark.parametrize('api',['gemini','openai'],indirect=True)
|
|
def test_uncalibrated_transport_reservation_replay_stream_and_shared_search_error(api,monkeypatch,tmp_path):
|
|
client, wire, runner, e = api
|
|
e.search.cutoff = None
|
|
report = tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
|
|
config = e.voice_config.model_copy(update={'voice_transport_testing':True,'search_calibration_report':report})
|
|
client.app.dependency_overrides[dependencies.get_voice_settings] = lambda: config
|
|
monkeypatch.setattr(live,'capability',_real_capability)
|
|
monkeypatch.setattr(live,'IngestionSettings',lambda:e.settings)
|
|
monkeypatch.setattr(live,'get_search_service',lambda engine:e.search)
|
|
headers=login(client,e)
|
|
conversation=client.post('/api/v1/conversations',json={'mode':'voice','client_request_id':str(uuid4())},headers=headers).json()
|
|
body={'conversation_id':conversation['id'],'client_request_id':str(uuid4())}
|
|
response=client.post('/api/v1/voice/sessions',json=body,headers=headers)
|
|
assert response.status_code == 201, response.text
|
|
result=response.json(); sid=UUID(result['session_id'])
|
|
assert result['calibration_status'] == 'uncalibrated'
|
|
replay=client.post('/api/v1/voice/sessions',json=body,headers=headers)
|
|
assert replay.json()['session_id']==result['session_id'] and replay.headers['Idempotency-Replayed']=='true'
|
|
assert replay.json()['calibration_status']=='uncalibrated'
|
|
assert client.get(result['poll_url']).json()['calibration_status']=='uncalibrated'
|
|
disabled=config.model_copy(update={'voice_transport_testing':False})
|
|
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:disabled
|
|
# Creation replay precedes capability/embedding construction despite policy changes.
|
|
assert client.post('/api/v1/voice/sessions',json=body,headers=headers).json()['session_id']==result['session_id']
|
|
from starlette.websockets import WebSocketDisconnect
|
|
with pytest.raises(WebSocketDisconnect):
|
|
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}): pass
|
|
assert e.connections==[]
|
|
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config
|
|
# Policy cannot silently relabel an existing uncalibrated reservation.
|
|
with e.engine.connect() as conn:
|
|
profile=conn.execute(text('SELECT execution_profile FROM live_sessions WHERE id=:id'),{'id':sid}).scalar_one()
|
|
assert profile['search']['mode']=='transport_testing' and 'distance' not in profile['search']
|
|
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
|
|
from app.infrastructure.realtime import RealtimeAdapter
|
|
ack={'setupComplete':{}} if config.provider=='gemini' else {'type':'session.updated','session':RealtimeAdapter(wire).setup()['session']}
|
|
client.portal.call(wire.inbound.put,ack)
|
|
assert ws.receive_json()['type']=='session_ready'
|
|
assert len(e.connections)==1
|
|
ws.send_bytes(bytes(4800))
|
|
client.portal.call(until,lambda: any('realtimeInput' in m or m.get('type')=='input_audio_buffer.append' for m in wire.sent))
|
|
from app.modules.knowledge.evidence import SearchExecution
|
|
result=e.search.search(SearchExecution(e.actor),'source query')
|
|
assert result['status']=='error' and result['sources']==[] and result['error']['code']=='CALIBRATION_REQUIRED'
|
|
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config.model_copy(update={'voice_transport_testing':False})
|
|
new=client.post('/api/v1/conversations',json={'mode':'voice','client_request_id':str(uuid4())},headers=headers).json()
|
|
rejected=client.post('/api/v1/voice/sessions',json={'conversation_id':new['id'],'client_request_id':str(uuid4())},headers=headers)
|
|
assert rejected.status_code==503 and rejected.json()['error']['code']=='CALIBRATION_REQUIRED'
|
|
assert len(e.connections)==1
|
|
|
|
_real_capability=live.capability
|
|
|
|
@pytest.mark.parametrize('kind',['text','docx'])
|
|
def test_initial_faq_context_reaches_independent_review_and_atomic_publication(document_api,kind):
|
|
client,_,_,e=document_api; headers=login(client,e)
|
|
paragraphs=['Benefits title','Only permanent employees.','Question: rate?','Answer: 5%.','Question: leave?','Answer: 10 days.']
|
|
content=('\n'.join(paragraphs)+'\n').encode(); filename='faq.md'
|
|
if kind=='docx':
|
|
from tests.support.formats import docx_bytes
|
|
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()); filename='faq.docx'
|
|
uploaded=upload(client,headers,content,filename).json(); identifier=uploaded['document_id']
|
|
process(e)
|
|
detail=polling(client,identifier)
|
|
assert detail['review_required'] and detail['review_state']=='pending'
|
|
item,=client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items']
|
|
assert item['review_kind']=='factual_corpus'
|
|
assert 'Benefits title' in ''.join(b['text'] for b in item['blocks'])
|
|
assert len([b for b in item['blocks'] if b.get('group_id') and 'Question:' in b['text']])==2
|
|
with e.engine.connect() as conn:
|
|
assert conn.execute(text('SELECT count(*) FROM document_chunks WHERE document_id=:id'),{'id':UUID(identifier)}).scalar_one()==0
|
|
decision=dict(evidence_sha256=item['evidence_sha256'],decision='approve',checked=item['required_checks'],note='Synthetic factual authority check',excluded_group_ids=[])
|
|
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions',json=decision,
|
|
headers=dict(headers,**{'Idempotency-Key':str(uuid4())})).status_code==200
|
|
retry=client.post(f'/api/v1/documents/{identifier}/retry',headers=dict(headers,**{'Idempotency-Key':str(uuid4())}))
|
|
assert retry.status_code==202 and retry.json()['job_id']==uploaded['job_id']
|
|
process(e)
|
|
with e.engine.connect() as conn:
|
|
chunks=conn.execute(text('SELECT text FROM document_chunks WHERE document_id=:id ORDER BY ordinal'),{'id':UUID(identifier)}).scalars().all()
|
|
assert len(chunks)==2 and all('Benefits title' in c and 'Only permanent employees.' in c for c in chunks)
|
|
assert polling(client,identifier)['status']=='ready' and not polling(client,identifier)['searchable']
|
|
|
|
|
|
def test_configuration_reports_testing_availability_without_claiming_calibration(document_api,tmp_path):
|
|
from pydantic import SecretStr
|
|
client,_,_,e=document_api; login(client,e)
|
|
e.settings=e.settings.model_copy(update={'embedding_api_key':SecretStr('fixture-only')})
|
|
report=tmp_path/'pending.json'; report.write_text(json.dumps({'status':'pending','cutoff':None}))
|
|
config=e.voice_config.model_copy(update={'voice_transport_testing':True,'search_calibration_report':report})
|
|
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:config
|
|
response=client.get('/api/v1/configuration')
|
|
assert response.status_code==200
|
|
capabilities=response.json()['capabilities']
|
|
assert capabilities['voice'] and capabilities['voice_transport_testing']
|
|
assert capabilities['calibration_status']=='uncalibrated'
|
|
assert 'fixture-only' not in response.text and str(report) not in response.text
|
|
# A malformed embedding request policy still prevents configured availability.
|
|
e.settings=e.settings.model_copy(update={'embedding_limits':None})
|
|
assert not client.get('/api/v1/configuration').json()['capabilities']['voice']
|
|
|
|
|
|
@pytest.mark.parametrize('kind', ['image', 'direct_pdf', 'factual'])
|
|
def test_best_effort_upload_publishes_without_manual_approval(document_api, kind):
|
|
from tests.support.extraction import pdf_bytes
|
|
client, _, _, e = document_api
|
|
headers = login(client, e)
|
|
e.settings = e.settings.model_copy(update={'allow_partial_extraction': True,
|
|
'vision_provider': 'gemini', 'vision_endpoint': 'https://test.invalid',
|
|
'vision_model': 'fixture-flash'})
|
|
if kind == 'image':
|
|
content, name = image_bytes('PNG'), 'best-effort.png'
|
|
elif kind == 'direct_pdf':
|
|
content, name = pdf_bytes([[('text', 'Article 1: fee is 5%', 10, 20)]]), 'best-effort.pdf'
|
|
else:
|
|
content, name = b'Question: fee?\nAnswer: 5%\n', 'best-effort.md'
|
|
response = upload(client, headers, content, name)
|
|
assert response.status_code == 202, response.text
|
|
identifier = response.json()['document_id']
|
|
# Later deployment toggles must not reinterpret the admitted document.
|
|
e.settings = e.settings.model_copy(update={'allow_partial_extraction': False})
|
|
process(e, FakeVision(warnings=('Small unrecognized region',)))
|
|
detail = polling(client, identifier)
|
|
assert detail['status'] == 'ready' and not detail['review_required']
|
|
assert not detail['is_active'] and not detail['searchable']
|
|
if kind != 'factual':
|
|
assert detail['extraction_quality_decision'] == 'accepted_with_warnings'
|
|
with e.engine.connect() as conn:
|
|
assert conn.execute(text('SELECT count(*) FROM document_chunks WHERE document_id=:id'), {'id': UUID(identifier)}).scalar_one() > 0
|
|
snapshot = conn.execute(text('SELECT processing_profile FROM documents WHERE id=:id'), {'id': UUID(identifier)}).scalar_one()
|
|
assert snapshot['extraction']['allow_partial_extraction'] is True
|