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:
@@ -0,0 +1,140 @@
|
||||
"""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']
|
||||
@@ -172,7 +172,7 @@ def test_cross_organization_provisioning_preserves_account(seeded_env):
|
||||
assert conn.execute(text('SELECT password_hash,role,is_enabled FROM users WHERE id=:id'),{'id':e.actor}).one()==before
|
||||
|
||||
@pytest.fixture
|
||||
def api(seeded_env,monkeypatch):
|
||||
def api(seeded_env,monkeypatch,request):
|
||||
from app.main import app
|
||||
from app.api.v1 import dependencies as d
|
||||
from app.api.v1 import live
|
||||
@@ -180,7 +180,8 @@ def api(seeded_env,monkeypatch):
|
||||
e=seeded_env;settings=e.settings
|
||||
from app.api.v1.auth import _ATTEMPTS, _LOCK
|
||||
with _LOCK: _ATTEMPTS.clear()
|
||||
config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',trusted_hosts=('localhost:8000',),trusted_origins=('http://localhost:8000',),cookie_secure=False)
|
||||
provider=getattr(request,'param','gemini')
|
||||
config=VoiceSettings(_env_file=None,provider=provider,gemini_api_key='fake-only',openai_realtime_api_key='fake-only',trusted_hosts=('localhost:8000',),trusted_origins=('http://localhost:8000',),cookie_secure=False)
|
||||
cutoff=CalibratedCutoff(asdict(settings.embedding_profile),2,'deterministic-fixture-only')
|
||||
search=SearchService(e.engine,settings,DeterministicEmbeddings(settings),cutoff=cutoff)
|
||||
e.search = search
|
||||
@@ -191,7 +192,7 @@ def api(seeded_env,monkeypatch):
|
||||
async def connect(*args):
|
||||
e.connections.append(1)
|
||||
return wire
|
||||
monkeypatch.setattr(live,'connect_gemini',connect)
|
||||
monkeypatch.setattr('app.infrastructure.voice_provider.connect_'+provider,connect)
|
||||
monkeypatch.setattr(live,'capability',lambda config:cutoff)
|
||||
monkeypatch.setattr('app.main.config',config)
|
||||
app.dependency_overrides[d.get_engine]=lambda:e.engine
|
||||
@@ -282,6 +283,7 @@ def test_actual_asgi_gemini_ready_and_blocked_browser_cleanup(api,ending):
|
||||
saved=conn.execute(text('SELECT status,connected_at FROM live_sessions WHERE id=:id'),{'id':sid}).one()
|
||||
assert saved[0] in ('closed','failed') and saved[1] is not None
|
||||
|
||||
@pytest.mark.parametrize('api',['gemini','openai'],indirect=True)
|
||||
@pytest.mark.parametrize('outcome',['ok','no_evidence','error'])
|
||||
def test_actual_asgi_tool_dispatch_persistence_and_public_sources(api,outcome):
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
@@ -297,28 +299,52 @@ def test_actual_asgi_tool_dispatch_persistence_and_public_sources(api,outcome):
|
||||
def fail(*args,**kwargs):raise EmbeddingProviderError('fake remote unavailable',retryable=True)
|
||||
e.search.provider.embed=fail
|
||||
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
|
||||
client.portal.call(wire.inbound.put,{'setupComplete':{}})
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from tests.unit.test_realtime_phase1 import call as native_call,terminal,message
|
||||
ack={'setupComplete':{}} if e.voice_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'
|
||||
ws.send_bytes(bytes(4800));ws.send_bytes(bytes(4800))
|
||||
client.portal.call(until,lambda:len([m for m in wire.sent if 'realtimeInput' in m])==2)
|
||||
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_START','audioOffset':'0s'}})
|
||||
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_END','audioOffset':'0.1s'}})
|
||||
fn={'id':'private-google-call','name':'search_knowledge','args':{'query':query}}
|
||||
client.portal.call(wire.inbound.put,{'toolCall':{'functionCalls':[fn]}})
|
||||
if e.voice_config.provider=='gemini':
|
||||
client.portal.call(until,lambda:len([m for m in wire.sent if 'realtimeInput' in m])==2)
|
||||
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_START','audioOffset':'0s'}})
|
||||
client.portal.call(wire.inbound.put,{'voiceActivity':{'type':'ACTIVITY_END','audioOffset':'0.1s'}})
|
||||
fn={'id':'private-google-call','name':'search_knowledge','args':{'query':query}}
|
||||
client.portal.call(wire.inbound.put,{'toolCall':{'functionCalls':[fn]}})
|
||||
else:
|
||||
client.portal.call(until,lambda:len([m for m in wire.sent if m.get('type')=='input_audio_buffer.append'])==2)
|
||||
for event in [dict(type='input_audio_buffer.speech_started',item_id='u1',audio_start_ms=0),
|
||||
dict(type='input_audio_buffer.speech_stopped',item_id='u1',audio_end_ms=100),
|
||||
dict(type='input_audio_buffer.committed',item_id='u1')]:client.portal.call(wire.inbound.put,event)
|
||||
client.portal.call(until,lambda:any(m.get('type')=='response.create' for m in wire.sent))
|
||||
intent=next(m['response']['metadata'] for m in wire.sent if m.get('type')=='response.create')
|
||||
client.portal.call(wire.inbound.put,dict(type='response.created',response=dict(id='r1',metadata=intent)))
|
||||
tool=native_call(call_id='private-google-call',query=query)
|
||||
client.portal.call(wire.inbound.put,tool)
|
||||
client.portal.call(wire.inbound.put,terminal(output=[dict(type='function_call',id=tool['item_id'],call_id=tool['call_id'],name=tool['name'],arguments=tool['arguments'])]))
|
||||
events=[]
|
||||
while True:
|
||||
event=ws.receive_json();events.append(event)
|
||||
if event['type']=='sources':break
|
||||
client.portal.call(until,lambda:any('toolResponse' in m for m in wire.sent))
|
||||
client.portal.call(until,lambda:any('toolResponse' in m or (m.get('type')=='conversation.item.create' and m['item']['type']=='function_call_output') for m in wire.sent))
|
||||
with e.engine.connect() as conn:
|
||||
call=conn.execute(text('SELECT * FROM tool_calls WHERE live_session_id=:id'),{'id':sid}).mappings().one()
|
||||
assert call['arguments']['query']==query
|
||||
assert call['result_json']['status']==outcome
|
||||
assert call['knowledge_revision']==2 and call['access_epoch']==1
|
||||
assert str(call['public_ref'])==events[-1]['tool_call_id']!='private-google-call'
|
||||
answer=next(m['toolResponse']['functionResponses'][0] for m in wire.sent if 'toolResponse' in m)
|
||||
assert answer['id']=='private-google-call' and answer['response']==call['result_json']
|
||||
client.portal.call(wire.inbound.put,{'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
|
||||
if e.voice_config.provider=='gemini':
|
||||
answer=next(m['toolResponse']['functionResponses'][0] for m in wire.sent if 'toolResponse' in m)
|
||||
assert answer['id']=='private-google-call' and answer['response']==call['result_json']
|
||||
client.portal.call(wire.inbound.put,{'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
|
||||
else:
|
||||
answer=next(m['item'] for m in wire.sent if m.get('type')=='conversation.item.create' and m['item']['type']=='function_call_output')
|
||||
assert answer['call_id']=='private-google-call' and json.loads(answer['output'])==call['result_json']
|
||||
client.portal.call(until,lambda:len([m for m in wire.sent if m.get('type')=='response.create'])==2)
|
||||
intent=[m['response']['metadata'] for m in wire.sent if m.get('type')=='response.create'][-1]
|
||||
client.portal.call(wire.inbound.put,dict(type='response.created',response=dict(id='r2',metadata=intent)))
|
||||
client.portal.call(wire.inbound.put,dict(type='response.output_audio_transcript.done',response_id='r2',item_id='a_r2',output_index=0,content_index=0,transcript='fixture answer'))
|
||||
client.portal.call(wire.inbound.put,terminal('r2',output=[message('r2')]))
|
||||
while True:
|
||||
event=ws.receive_json()
|
||||
if event.get('role')=='assistant' and event['status']=='completed':break
|
||||
@@ -589,3 +615,100 @@ def test_real_database_dispatch_failure_is_durably_technical_not_revocation(api,
|
||||
row=e.lifecycle.get_live_session(e.user,sid)
|
||||
assert row['status']=='failed' and row['error_code']=='DEPENDENCY_UNAVAILABLE'
|
||||
assert not any('toolResponse' in m for m in wire.sent)
|
||||
|
||||
@pytest.mark.parametrize('api',['gemini','openai'],indirect=True)
|
||||
def test_selected_provider_reservation_ready_audio_and_pinned_replay(api,monkeypatch):
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from app.api.v1 import dependencies
|
||||
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
||||
with e.engine.connect() as conn:
|
||||
row=conn.execute(text('SELECT provider,model,execution_profile FROM live_sessions WHERE id=:id'),{'id':sid}).mappings().one()
|
||||
assert row['provider']==e.voice_config.provider and row['model']==e.voice_config.selected_model
|
||||
assert all(row['execution_profile'][k]==v for k,v in e.voice_config.profile().items())
|
||||
assert 'fake-only' not in json.dumps(dict(row)) and 'api_key' not in json.dumps(result)
|
||||
# Replay still returns the pinned reservation after backend configuration changes.
|
||||
other=VoiceSettings(_env_file=None,provider='openai' if e.voice_config.provider=='gemini' else 'gemini',gemini_api_key='fake-only',openai_realtime_api_key='fake-only',trusted_hosts=('localhost:8000',),trusted_origins=('http://localhost:8000',),cookie_secure=False)
|
||||
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:other
|
||||
replay=client.post('/api/v1/voice/sessions',json=body,headers=headers)
|
||||
assert replay.status_code==202 and replay.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 not e.connections
|
||||
client.app.dependency_overrides[dependencies.get_voice_settings]=lambda:e.voice_config
|
||||
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
|
||||
ack={'setupComplete':{}} if e.voice_config.provider=='gemini' else {'type':'session.updated','session':RealtimeAdapter(wire,model=e.voice_config.selected_model,voice=e.voice_config.selected_voice).setup()['session']}
|
||||
client.portal.call(wire.inbound.put,ack)
|
||||
assert ws.receive_json()['type']=='session_ready'
|
||||
client.portal.call(until,lambda:bool(wire.sent))
|
||||
ws.send_bytes(bytes(4800))
|
||||
if e.voice_config.provider=='gemini':
|
||||
client.portal.call(until,lambda:any('realtimeInput' in m for m in wire.sent))
|
||||
native=next(m['realtimeInput']['audio']['data'] for m in wire.sent if 'realtimeInput' in m and 'audio' in m['realtimeInput'])
|
||||
assert len(base64.b64decode(native))==3200
|
||||
else:
|
||||
client.portal.call(until,lambda:any(m.get('type')=='input_audio_buffer.append' for m in wire.sent))
|
||||
native=next(m['audio'] for m in wire.sent if m.get('type')=='input_audio_buffer.append')
|
||||
assert len(base64.b64decode(native))==4800
|
||||
assert client.post('/api/v1/voice/sessions/'+str(sid)+'/close',headers=headers).status_code==200
|
||||
try:
|
||||
while True:ws.receive_json()
|
||||
except WebSocketDisconnect:pass
|
||||
client.portal.call(until,lambda:sid not in ACTIVE_MEDIA_SESSIONS)
|
||||
assert wire.closed==1 and len(e.connections)==1
|
||||
with e.engine.connect() as conn:
|
||||
saved=conn.execute(text('SELECT status,close_reason,error_code FROM live_sessions WHERE id=:id'),{'id':sid}).one()
|
||||
assert saved==('closed','user_requested',None)
|
||||
|
||||
@pytest.mark.parametrize('failure,code',[('saturation','SEARCH_SATURATED'),('timeout','SEARCH_TIMEOUT'),('sql','DEPENDENCY_UNAVAILABLE'),('revocation','CONTEXT_REVOKED')])
|
||||
def test_authority_monitor_failure_classification_real_terminal_state(api,monkeypatch,failure,code):
|
||||
from threading import Event
|
||||
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
|
||||
from app.infrastructure.blocking import blocking
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
client,wire,runner,e=api;headers,result,body=session(client,e);sid=UUID(result['session_id'])
|
||||
released=Event();workers=[]
|
||||
with client.websocket_connect('ws://localhost:8000'+result['stream_path'],headers={'Origin':'http://localhost:8000'}) as ws:
|
||||
client.portal.call(wire.inbound.put,{'setupComplete':{}})
|
||||
assert ws.receive_json()['type']=='session_ready'
|
||||
with e.engine.connect() as conn: pass
|
||||
def connected():
|
||||
with e.engine.connect() as conn:return conn.execute(text('SELECT status FROM live_sessions WHERE id=:id'),{'id':sid}).scalar_one()=='connected'
|
||||
client.portal.call(until,connected)
|
||||
if failure=='saturation':
|
||||
entered=[Event() for _ in range(8)]
|
||||
def occupy(event):event.set();released.wait(5)
|
||||
async def saturate():
|
||||
tasks=[asyncio.create_task(blocking(occupy,event)) for event in entered]
|
||||
await until(lambda:all(event.is_set() for event in entered));return tasks
|
||||
workers=client.portal.call(saturate)
|
||||
elif failure=='revocation':
|
||||
# Change real authority without a registry notification: the monitor must verify it.
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text('UPDATE organization_settings SET access_epoch=access_epoch+1 WHERE organization_id=:org'),{'org':e.org})
|
||||
else:
|
||||
original=e.lifecycle.validate_stream
|
||||
def check(*args,**kwargs):
|
||||
if failure=='timeout':raise TimeoutError('private timeout')
|
||||
if failure=='sql':
|
||||
with e.engine.connect() as conn:conn.execute(text('SELECT * FROM intentionally_missing_authority_relation'))
|
||||
return original(*args,**kwargs)
|
||||
monkeypatch.setattr(e.lifecycle,'validate_stream',check)
|
||||
try:
|
||||
event=ws.receive_json();assert event['type']=='error' and event['error']['code']==code
|
||||
assert 'private' not in json.dumps(event)
|
||||
finally:released.set()
|
||||
try:
|
||||
while True:ws.receive_json()
|
||||
except WebSocketDisconnect:pass
|
||||
async def complete():
|
||||
await asyncio.gather(*workers,return_exceptions=True)
|
||||
await until(lambda:sid not in ACTIVE_MEDIA_SESSIONS)
|
||||
client.portal.call(complete)
|
||||
with e.engine.connect() as conn:
|
||||
saved=conn.execute(text('SELECT status,close_reason,error_code FROM live_sessions WHERE id=:id'),{'id':sid}).one()
|
||||
assert saved==('closed' if failure=='revocation' else 'failed',code,None if failure=='revocation' else code)
|
||||
assert wire.closed==1
|
||||
|
||||
@@ -1210,12 +1210,12 @@ def test_negated_unreadability_notes_resume_approved_ocr_without_repeating_it(wo
|
||||
assert (work["candidates"].directory / pointer["key"]).read_bytes() == candidate_bytes
|
||||
|
||||
|
||||
@pytest.mark.parametrize("warning", ["unreadable source region", "\u0646\u0627\u062e\u0648\u0627\u0646\u0627"])
|
||||
def test_genuine_unreadable_provider_warning_remains_terminal(work, warning):
|
||||
@pytest.mark.parametrize("text", ["\ufffd", "(cid:12)"])
|
||||
def test_corrupt_provider_source_text_remains_terminal(work, text):
|
||||
review_source(work)
|
||||
class UnreadableVision(ReviewedVision):
|
||||
def transcribe(self, *args, **kwargs):
|
||||
return tuple(b.model_copy(update={"warnings": (warning,)})
|
||||
return tuple(b.model_copy(update={"text": text})
|
||||
for b in super().transcribe(*args, **kwargs))
|
||||
review_worker(work, UnreadableVision()).run_once("unreadable")
|
||||
doc, job, count = rows(work)
|
||||
|
||||
@@ -0,0 +1,515 @@
|
||||
"""Authenticated Phase 3 HTTP workflows on real isolated PostgreSQL."""
|
||||
import json
|
||||
from uuid import UUID, uuid4
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from app.api.v1 import dependencies
|
||||
from app.modules.documents.worker import Worker
|
||||
from app.modules.documents.extraction import PageBlockExtractor
|
||||
from app.modules.documents.review import FACTUAL_CHECKS
|
||||
from app.modules.knowledge.service import selection_get
|
||||
from tests.support.embedding import DeterministicEmbeddings
|
||||
from tests.support.extraction import FakeVision, pdf_bytes
|
||||
from tests.support.formats import image_bytes
|
||||
from tests.integration.test_phase2_postgres import seeded_env, api, login, session
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def document_api(api, tmp_path):
|
||||
client, wire, runner, e = api
|
||||
e.settings = e.settings.model_copy(update={'original_directory': tmp_path / 'originals', 'extraction_directory': tmp_path / 'extractions'})
|
||||
client.app.dependency_overrides[dependencies.get_ingestion_settings] = lambda: e.settings
|
||||
return client, wire, runner, e
|
||||
|
||||
|
||||
def upload(client, headers, content=b'Article 1: fee is 5%.', filename='source.md', key=None, title='Source'):
|
||||
return client.post('/api/v1/documents', files={'file': (filename, content)}, data={'title': title},
|
||||
headers=dict(headers, **{'Idempotency-Key': str(key or uuid4())}))
|
||||
|
||||
|
||||
def process(e, vision=None, provider=None):
|
||||
from app.api.v1.documents import get_document_services
|
||||
services = get_document_services(e.engine, e.settings)
|
||||
worker = Worker(services[4], services[1], services[2], lambda _: PageBlockExtractor(vision),
|
||||
lambda _: (provider or DeterministicEmbeddings(e.settings), None), e.settings)
|
||||
assert worker.run_once('http-acceptance')
|
||||
return services
|
||||
|
||||
|
||||
def polling(client, identifier):
|
||||
response = client.get('/api/v1/documents/' + str(identifier))
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def test_upload_replay_independent_identity_polling_selection_configuration(document_api):
|
||||
client, _, _, e = document_api; headers = login(client, e); key = uuid4()
|
||||
first = upload(client, headers, key=key)
|
||||
assert first.status_code == 202, first.text
|
||||
identifier = first.json()['document_id']
|
||||
assert not first.json()['is_active'] and not first.json()['searchable']
|
||||
frozen = e.settings.processing_profile()
|
||||
e.settings = e.settings.model_copy(update={'ocr_review_required': False, 'max_original_bytes': 10})
|
||||
replay = upload(client, headers, key=key)
|
||||
assert replay.status_code == 202 and replay.json()['document_id'] == identifier
|
||||
assert replay.headers['Idempotency-Replayed'] == 'true'
|
||||
assert upload(client, headers, content=b'changed', key=key).status_code == 409
|
||||
assert upload(client, headers, content=b'x'*50, key=key).status_code == 409
|
||||
e.settings = e.settings.model_copy(update={'max_original_bytes': 20 * 1024 * 1024})
|
||||
assert upload(client, headers).json()['document_id'] != identifier
|
||||
with e.engine.connect() as conn:
|
||||
assert conn.execute(text('SELECT processing_profile FROM documents WHERE id=:id'), {'id': UUID(identifier)}).scalar_one() == frozen
|
||||
assert polling(client, identifier)['review_state'] == 'not_evaluated'
|
||||
cfg = client.get('/api/v1/configuration')
|
||||
assert cfg.status_code == 200, cfg.text
|
||||
assert cfg.json()['capabilities']['ocr_review_required'] is False
|
||||
assert cfg.json()['capabilities']['max_upload_bytes'] == e.settings.max_original_bytes
|
||||
assert not cfg.json()['capabilities']['text'] and not cfg.json()['capabilities']['voice']
|
||||
assert all(value not in cfg.text for value in ('database_url', 'storage_key', 'api_key', str(e.settings.original_directory)))
|
||||
pending = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': [identifier]}, headers=headers)
|
||||
assert pending.status_code == 409 and pending.json()['error']['code'] == 'DOCUMENT_NOT_READY'
|
||||
assert pending.json()['error']['details']['document_ids'] == [identifier]
|
||||
process(e)
|
||||
ready = polling(client, identifier)
|
||||
assert ready['status'] == 'ready' and not ready['is_active'] and not ready['searchable']
|
||||
assert ready['extraction_quality_decision'] == 'passed' and not ready['job']['can_retry']
|
||||
result = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': [identifier]}, headers=headers)
|
||||
assert result.status_code == 200 and result.json()['revision'] == 3 and result.json()['access_epoch'] == 2 # removes original fixture
|
||||
assert polling(client, identifier)['searchable']
|
||||
assert client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': []}, headers=headers).status_code == 409
|
||||
assert client.patch('/api/v1/knowledge-selection', json={'expected_revision': 3, 'document_ids': [identifier, identifier]}, headers=headers).status_code == 422
|
||||
assert client.patch('/api/v1/knowledge-selection', json={'expected_revision': 3, 'document_ids': [identifier], 'scope': 'forged'}, headers=headers).status_code == 422
|
||||
listed = client.get('/api/v1/documents?limit=1').json()
|
||||
assert len(listed['items']) == 1 and listed['next_cursor'] and listed['knowledge_revision'] == 3
|
||||
assert client.get('/api/v1/documents', params={'cursor': listed['next_cursor']}).status_code == 200
|
||||
assert client.get('/api/v1/documents?cursor=invalid').status_code == 422
|
||||
assert client.get('/api/v1/documents?limit=101').status_code == 422
|
||||
assert client.post('/api/v1/documents/'+identifier+'/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 409
|
||||
|
||||
|
||||
def test_unicode_filename_upload_persistence_and_replay(document_api):
|
||||
client, _, _, e = document_api
|
||||
headers = login(client, e)
|
||||
key = uuid4()
|
||||
long_filename = 'س' * 128 + '.md'
|
||||
content = b'# Persian Article\nContent.'
|
||||
res = client.post('/api/v1/documents', files={'file': (long_filename, content)},
|
||||
headers=dict(headers, **{'Idempotency-Key': str(key)}))
|
||||
assert res.status_code == 202, res.text
|
||||
identifier = res.json()['document_id']
|
||||
|
||||
# Detail query verifies stored original_filename is intact and not truncated
|
||||
detail = polling(client, identifier)
|
||||
assert detail['filename'] == long_filename
|
||||
assert detail['title'] == 'س' * 128
|
||||
|
||||
# Replay same upload with same key
|
||||
replay = client.post('/api/v1/documents', files={'file': (long_filename, content)},
|
||||
headers=dict(headers, **{'Idempotency-Key': str(key)}))
|
||||
assert replay.status_code == 202
|
||||
assert replay.headers['Idempotency-Replayed'] == 'true'
|
||||
assert replay.json()['document_id'] == identifier
|
||||
|
||||
|
||||
@pytest.mark.parametrize('required', [True, False])
|
||||
@pytest.mark.parametrize('kind', ['image', 'scan'])
|
||||
def test_ocr_snapshot_worker_publication_and_explicit_human_review(document_api, required, kind):
|
||||
client, _, _, e = document_api; headers = login(client, e)
|
||||
e.settings = e.settings.model_copy(update={'ocr_review_required': required, 'vision_provider': 'gemini',
|
||||
'vision_endpoint': 'https://test.invalid', 'vision_model': 'fixture-flash'})
|
||||
content = image_bytes('PNG')
|
||||
if kind == 'scan': content = pdf_bytes([[('image', content, 10, 20)]])
|
||||
result = upload(client, headers, content, 'scan.pdf' if kind == 'scan' else 'image.png')
|
||||
assert result.status_code == 202, result.text
|
||||
identifier, job = result.json()['document_id'], result.json()['job_id']
|
||||
e.settings = e.settings.model_copy(update={'ocr_review_required': not required})
|
||||
vision = FakeVision(); services = process(e, vision)
|
||||
detail = polling(client, identifier)
|
||||
assert detail['ocr_review_required'] is required
|
||||
if required:
|
||||
assert detail['status'] == 'failed' and detail['review_state'] == 'pending' and not detail['job']['can_retry']
|
||||
items = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items']
|
||||
assert len(items) == 1
|
||||
item = items[0]
|
||||
preview = client.get(item['preview_path'])
|
||||
assert preview.status_code == 200 and preview.headers['cache-control'] == 'no-store'
|
||||
retry_url = f'/api/v1/documents/{identifier}/retry'
|
||||
assert client.post(retry_url, headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 409
|
||||
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'], note='Fixture inspection')
|
||||
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=dict(decision, reviewer='forged'), headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 422
|
||||
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=dict(decision, checked=[]), headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 422
|
||||
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=dict(decision, evidence_sha256='a'*64), headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 409
|
||||
key = str(uuid4()); decision_headers = dict(headers, **{'Idempotency-Key': key})
|
||||
url = f'/api/v1/documents/{identifier}/extraction-review/decisions'
|
||||
assert client.post(url, json=decision, headers=decision_headers).status_code == 200
|
||||
replay = client.post(url, json=decision, headers=decision_headers)
|
||||
assert replay.status_code == 200 and replay.headers['Idempotency-Replayed'] == 'true'
|
||||
assert client.post(url, json=dict(decision, note='changed'), headers=decision_headers).status_code == 409
|
||||
assert polling(client, identifier)['status'] == 'failed' and polling(client, identifier)['job']['can_retry']
|
||||
retry_headers = dict(headers, **{'Idempotency-Key': str(uuid4())})
|
||||
retry = client.post(retry_url, headers=retry_headers)
|
||||
assert retry.status_code == 202 and retry.json()['job_id'] == job and retry.json()['retry_generation'] == 1
|
||||
assert client.post(retry_url, headers=retry_headers).headers['Idempotency-Replayed'] == 'true'
|
||||
process(e, vision)
|
||||
assert len(vision.calls) == 1 # resume exact retained evidence
|
||||
else:
|
||||
assert detail['review_state'] == 'not_required' and detail['extraction_quality_decision'] == 'passed'
|
||||
assert client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'] == []
|
||||
with e.engine.connect() as conn:
|
||||
assert conn.execute(text("SELECT count(*) FROM audit_events WHERE target_id=:id AND action='extraction_review'"), {'id': UUID(identifier)}).scalar_one() == 0
|
||||
detail = polling(client, identifier)
|
||||
assert detail['status'] == 'ready' and detail['job']['status'] == 'succeeded'
|
||||
assert detail['job']['id'] == job and not detail['is_active'] and not detail['searchable']
|
||||
|
||||
|
||||
def test_factual_review_remains_independent_and_rejection_stays_failed(document_api):
|
||||
client, _, _, e = document_api; headers = login(client, e)
|
||||
e.settings = e.settings.model_copy(update={'ocr_review_required': False})
|
||||
response = upload(client, headers, b'Question: fee?\nAnswer: 5%\n')
|
||||
identifier = response.json()['document_id']; process(e)
|
||||
assert polling(client, identifier)['review_required']
|
||||
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
|
||||
assert item['review_kind'] == 'factual_corpus' and item['preview_path'] is None
|
||||
decision = dict(evidence_sha256=item['evidence_sha256'], decision='reject', checked=[], note='Not authoritative')
|
||||
result = client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=decision,
|
||||
headers=dict(headers, **{'Idempotency-Key': str(uuid4())}))
|
||||
assert result.status_code == 200
|
||||
detail = polling(client, identifier)
|
||||
assert detail['review_state'] == 'rejected' and not detail['job']['can_retry'] and not detail['searchable']
|
||||
retry = client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())}))
|
||||
assert retry.status_code == 409
|
||||
|
||||
|
||||
def test_auth_roles_cross_organization_csrf_and_safe_upload_errors(document_api):
|
||||
client, _, _, e = document_api
|
||||
assert client.get('/api/v1/documents').status_code == 401
|
||||
headers = login(client, e)
|
||||
assert upload(client, {'Origin': headers['Origin']}).status_code == 403
|
||||
assert upload(client, dict(headers, Origin='https://untrusted.invalid')).status_code == 403
|
||||
assert client.post('/api/v1/documents', files={'file': ('source.md', b'a')}, headers=headers).status_code == 422
|
||||
assert upload(client, headers, b'not PDF', 'wrong.pdf').status_code == 422
|
||||
assert upload(client, headers, b'abc', 'file.exe').status_code == 415
|
||||
e.settings = e.settings.model_copy(update={'max_original_bytes': 10})
|
||||
assert upload(client, headers, b'a' * 11).status_code == 413
|
||||
identifier = upload(client, headers, b'abc').json()['document_id']
|
||||
other_org, other_actor = __import__('tests.support.search', fromlist=['administrator']).administrator(e.engine)
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text('UPDATE users SET organization_id=:org WHERE id=:id'), {'org': other_org, 'id': other_actor})
|
||||
# Real second administrator/session; cookie identity alone determines scope.
|
||||
from argon2 import PasswordHasher
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text('UPDATE users SET password_hash=:hash WHERE id=:id'), {'id': other_actor, 'hash': PasswordHasher().hash('fixture-password')})
|
||||
client.post('/api/v1/auth/logout', headers=headers)
|
||||
e.actor = other_actor; other_headers = login(client, e)
|
||||
assert client.get('/api/v1/documents/'+identifier).status_code == 404
|
||||
assert client.get(f'/api/v1/documents/{identifier}/extraction-review').status_code == 404
|
||||
assert client.get(f'/api/v1/documents/{identifier}/extraction-review/' + 'a'*64 + '/preview').status_code == 404
|
||||
assert client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(other_headers, **{'Idempotency-Key': str(uuid4())})).status_code == 404
|
||||
assert client.patch('/api/v1/knowledge-selection', json={'expected_revision': 1, 'document_ids': [identifier]}, headers=other_headers).status_code == 404
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text("UPDATE users SET role='user' WHERE id=:id"), {'id': other_actor})
|
||||
assert client.get('/api/v1/configuration').status_code == 200
|
||||
assert client.get('/api/v1/documents').status_code == 403
|
||||
assert upload(client, other_headers, b'abc').status_code == 403
|
||||
assert client.get('/api/v1/knowledge-selection').status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.parametrize('api', ['gemini', 'openai'], indirect=True)
|
||||
def test_authenticated_selection_removal_closes_active_voice_and_redacts_polling(document_api):
|
||||
client, wire, runner, e = document_api
|
||||
headers, result, _ = session(client, e)
|
||||
sid = result['session_id']
|
||||
with client.websocket_connect(f'ws://localhost:8000/api/v1/voice/sessions/{sid}/stream', headers={'Origin': headers['Origin']}) as ws:
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
ack = {'setupComplete': {}} if e.voice_config.provider == 'gemini' else {'type': 'session.updated', 'session': RealtimeAdapter(wire, model=e.voice_config.selected_model, voice=e.voice_config.selected_voice).setup()['session']}
|
||||
client.portal.call(wire.inbound.put, ack)
|
||||
assert ws.receive_json()['type'] == 'session_ready'
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
from app.modules.knowledge.evidence import SearchExecution
|
||||
from app.modules.auth.service import COOKIE_NAME
|
||||
user = e.auth.get_current_user(client.cookies.get(COOKIE_NAME))
|
||||
client.portal.call(until, lambda: e.lifecycle.get_live_session(user, UUID(sid))['status'] == 'connected')
|
||||
execution = SearchExecution(e.actor)
|
||||
call = e.lifecycle.admit_tool(user, UUID(sid), 'completed-before-removal', str(uuid4()), {'query': 'fee'}, execution)
|
||||
with e.engine.connect() as conn:
|
||||
chunk = conn.execute(text('SELECT id,text FROM document_chunks WHERE document_id=:id'), {'id': e.doc}).mappings().first()
|
||||
evidence = {'status': 'ok', 'sources': [dict(document_id=str(e.doc), chunk_id=str(chunk['id']), source_ref='S1', title='Pump', text=chunk['text'], location={'page': None, 'section': None})]}
|
||||
assert e.lifecycle.complete_tool(user, UUID(sid), call['id'], evidence, execution)
|
||||
running = e.lifecycle.admit_tool(user, UUID(sid), 'running-before-removal', str(uuid4()), {'query': 'fee'}, SearchExecution(e.actor))
|
||||
response = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': []}, headers=headers)
|
||||
assert response.status_code == 200 and response.json()['conversations_invalidated']
|
||||
assert response.json()['access_epoch'] == 2
|
||||
terminal = ws.receive_json()
|
||||
assert terminal['type'] == 'error' and terminal['error']['code'] == 'CONTEXT_REVOKED'
|
||||
poll = client.get('/api/v1/voice/sessions/' + sid).json()
|
||||
assert poll['status'] == 'closed' and poll['close_reason'] == 'epoch_invalidated'
|
||||
assert not poll['recent_tool_results'][0]['sources'][0]['available']
|
||||
assert 'text' not in poll['recent_tool_results'][0]['sources'][0]
|
||||
assert poll['recent_tool_results'][0]['sources'][0]['excerpt'] is None
|
||||
with e.engine.connect() as conn:
|
||||
assert conn.execute(text('SELECT status FROM tool_calls WHERE id=:id'), {'id': running['id']}).scalar_one() == 'failed'
|
||||
assert e.connections == [1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fragmented', [False, True])
|
||||
def test_real_parser_invalid_utf8_persists_protocol_error(document_api, fragmented):
|
||||
"""Raw complete/fragmented UTF-8 traverses the installed parser and real Live handler."""
|
||||
import asyncio
|
||||
import base64
|
||||
import os
|
||||
import struct
|
||||
import uvicorn
|
||||
from app.server import server_config
|
||||
from app.modules.auth.service import COOKIE_NAME
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
|
||||
client, wire, _, e = document_api
|
||||
headers, result, _ = session(client, e)
|
||||
sid = UUID(result['session_id'])
|
||||
async def run():
|
||||
server = uvicorn.Server(server_config(client.app, port=0, lifespan='off', log_level='error'))
|
||||
task = asyncio.create_task(server.serve())
|
||||
reader = writer = None
|
||||
try:
|
||||
await until(lambda: server.started)
|
||||
port = server.servers[0].sockets[0].getsockname()[1]
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET {result["stream_path"]} HTTP/1.1\r\nHost: localhost:8000\r\nOrigin: http://localhost:8000\r\nCookie: {COOKIE_NAME}={client.cookies.get(COOKIE_NAME)}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
assert b'101 Switching Protocols' in await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 2)
|
||||
await wire.inbound.put({'setupComplete': {}})
|
||||
await until(lambda: e.lifecycle.get_live_session(e.auth.get_current_user(client.cookies.get(COOKIE_NAME)), sid)['status'] == 'connected')
|
||||
bad = b'\x01\x81\0\0\0\0\xc3\x80\x81\0\0\0\0\x28' if fragmented else b'\x81\x82\0\0\0\0\xc3\x28'
|
||||
writer.write(bad); await writer.drain()
|
||||
# Drain readiness and then the protocol close. Never echo invalid text.
|
||||
while True:
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
size = head[1] & 127
|
||||
if size == 126: size = struct.unpack('!H', await reader.readexactly(2))[0]
|
||||
if size == 127: size = struct.unpack('!Q', await reader.readexactly(8))[0]
|
||||
payload = await reader.readexactly(size)
|
||||
if head[0] & 15 == 8:
|
||||
assert struct.unpack('!H', payload[:2])[0] == 1007
|
||||
writer.write(b'\x88\x82\0\0\0\0' + payload[:2]); await writer.drain()
|
||||
writer.close(); await writer.wait_closed()
|
||||
break
|
||||
async with asyncio.timeout(12):
|
||||
while sid in ACTIVE_MEDIA_SESSIONS: await asyncio.sleep(.005)
|
||||
finally:
|
||||
if writer:
|
||||
writer.close(); await writer.wait_closed()
|
||||
server.should_exit = True
|
||||
await asyncio.wait_for(task, 5)
|
||||
asyncio.run(run())
|
||||
poll = client.get('/api/v1/voice/sessions/' + str(sid)).json()
|
||||
assert poll['status'] == 'failed' and poll['error_code'] == 'LIVE_PROTOCOL_ERROR'
|
||||
|
||||
|
||||
def test_legacy_profile_keeps_gate_and_same_profile_on_retry(document_api, monkeypatch):
|
||||
from app.modules.documents.settings import IngestionSettings
|
||||
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'})
|
||||
original = IngestionSettings.processing_profile
|
||||
def legacy(self):
|
||||
value = original(self); value['extraction'].pop('ocr_review_required'); return value
|
||||
monkeypatch.setattr(IngestionSettings, 'processing_profile', legacy)
|
||||
response = upload(client, headers, image_bytes('PNG'), 'image.png')
|
||||
identifier = response.json()['document_id']; process(e, FakeVision())
|
||||
detail = polling(client, identifier)
|
||||
assert detail['ocr_review_required'] and detail['review_required'] and not detail['job']['can_retry']
|
||||
with e.engine.connect() as conn:
|
||||
frozen = conn.execute(text('SELECT processing_profile FROM documents WHERE id=:id'), {'id': UUID(identifier)}).scalar_one()
|
||||
monkeypatch.setattr(IngestionSettings, 'processing_profile', original)
|
||||
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
|
||||
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'], note='Legacy fixture inspection')
|
||||
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
|
||||
process(e, FakeVision())
|
||||
with e.engine.connect() as conn:
|
||||
assert conn.execute(text('SELECT processing_profile FROM documents WHERE id=:id'), {'id': UUID(identifier)}).scalar_one() == frozen
|
||||
assert polling(client, identifier)['status'] == 'ready'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['warnings', 'unreadable', 'model', 'placeholder'])
|
||||
def test_optional_ocr_validation_failure_never_publishes(document_api, failure):
|
||||
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'})
|
||||
response = upload(client, headers, image_bytes('PNG'), 'image.png')
|
||||
identifier = response.json()['document_id']
|
||||
vision = FakeVision(warnings=('uncertain order',) if failure == 'warnings' else (),
|
||||
actual_model='wrong' if failure == 'model' else 'fixture-flash',
|
||||
text='\ufffd' if failure == 'unreadable' else '[TODO]' if failure == 'placeholder' else 'Evidence')
|
||||
process(e, vision)
|
||||
detail = polling(client, identifier)
|
||||
assert detail['status'] == 'failed' and detail['chunk_count'] == 0 and not detail['searchable']
|
||||
if failure == 'warnings':
|
||||
assert detail['review_required'] 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
|
||||
|
||||
|
||||
def test_automatic_ocr_factual_candidate_requires_separate_approval(document_api):
|
||||
from app.modules.documents.types import ExtractedBlock
|
||||
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'})
|
||||
calls = []
|
||||
class FactualVision:
|
||||
def transcribe(self, image, *, page, section, processing_profile):
|
||||
calls.append(1)
|
||||
return tuple(ExtractedBlock(ordinal=i, block_id=f'{section}/{i}', source_locator=f'{section}/{i}',
|
||||
page=page, method='vision', actual_model='fixture-flash', text=value, block_type=role, group_id='faq-pair')
|
||||
for i, (role, value) in enumerate([('question', 'Question: fee?'), ('answer', 'Answer: 5%')]))
|
||||
response = upload(client, headers, image_bytes('PNG'), 'faq.png')
|
||||
identifier = response.json()['document_id']; process(e, FactualVision())
|
||||
detail = polling(client, identifier)
|
||||
assert detail['status'] == 'failed' and detail['extraction_quality_decision'] == 'passed' and detail['review_required']
|
||||
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
|
||||
assert item['review_kind'] == 'factual_corpus' and set(item['required_checks']) == set(FACTUAL_CHECKS)
|
||||
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'], note='Independent factual approval')
|
||||
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=decision, headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 200
|
||||
assert polling(client, identifier)['status'] == 'failed'
|
||||
assert client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 202
|
||||
process(e, FactualVision())
|
||||
detail = polling(client, identifier)
|
||||
assert detail['status'] == 'ready' and not detail['is_active'] and calls == [1]
|
||||
assert detail['extraction_quality_decision'] == 'passed'
|
||||
|
||||
|
||||
def test_selection_addition_preserves_active_epoch_and_noop_revision(document_api):
|
||||
client, _, _, e = document_api; headers = login(client, e)
|
||||
identifier = upload(client, headers).json()['document_id']; process(e)
|
||||
selection = client.get('/api/v1/knowledge-selection').json()
|
||||
ids = selection['document_ids'] + [identifier]
|
||||
result = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': ids}, headers=headers)
|
||||
assert result.status_code == 200 and result.json()['access_epoch'] == 1 and not result.json()['conversations_invalidated']
|
||||
result = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 3, 'document_ids': ids}, headers=headers)
|
||||
assert result.status_code == 200 and result.json()['revision'] == 3 and result.json()['access_epoch'] == 1
|
||||
|
||||
|
||||
def test_http_selection_removal_cancels_running_runtime_tool(document_api):
|
||||
from threading import Event
|
||||
from app.api.v1.live import ACTIVE_MEDIA_SESSIONS
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
client, wire, runner, e = document_api
|
||||
headers, result, _ = session(client, e); sid = UUID(result['session_id'])
|
||||
entered, release = Event(), Event()
|
||||
original = e.search.provider.embed
|
||||
def block(texts):
|
||||
entered.set()
|
||||
assert release.wait(5), 'Fixture provider release timed out'
|
||||
return original(texts)
|
||||
e.search.provider.embed = block
|
||||
with client.websocket_connect('ws://localhost:8000'+result['stream_path'], headers={'Origin': headers['Origin']}) as ws:
|
||||
try:
|
||||
client.portal.call(wire.inbound.put, {'setupComplete': {}})
|
||||
assert ws.receive_json()['type'] == 'session_ready'
|
||||
ws.send_bytes(bytes(4800)); ws.send_bytes(bytes(4800))
|
||||
client.portal.call(until, lambda: len([m for m in wire.sent if 'realtimeInput' in m]) == 2)
|
||||
client.portal.call(wire.inbound.put, {'voiceActivity': {'type': 'ACTIVITY_START', 'audioOffset': '0s'}})
|
||||
client.portal.call(wire.inbound.put, {'voiceActivity': {'type': 'ACTIVITY_END', 'audioOffset': '0.1s'}})
|
||||
client.portal.call(wire.inbound.put, {'toolCall': {'functionCalls': [{'id': 'blocked-tool', 'name': 'search_knowledge', 'args': {'query': 'Pump pressure?'}}]}})
|
||||
assert entered.wait(3)
|
||||
response = client.patch('/api/v1/knowledge-selection', json={'expected_revision': 2, 'document_ids': []}, headers=headers)
|
||||
assert response.status_code == 200
|
||||
release.set()
|
||||
while True:
|
||||
event = ws.receive_json()
|
||||
assert event['type'] != 'sources'
|
||||
if event['type'] == 'error':
|
||||
assert event['error']['code'] == 'CONTEXT_REVOKED'; break
|
||||
finally:
|
||||
release.set()
|
||||
client.portal.call(until, lambda: sid not in ACTIVE_MEDIA_SESSIONS)
|
||||
with e.engine.connect() as conn:
|
||||
saved = conn.execute(text('SELECT status,error_code,result_json FROM tool_calls WHERE live_session_id=:sid'), {'sid': sid}).mappings().one()
|
||||
assert saved['status'] == 'failed' and saved['error_code'] == 'CONTEXT_REVOKED' and saved['result_json'] is None
|
||||
assert not any('toolResponse' in m for m in wire.sent)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('required', [True, False])
|
||||
def test_f01_reports_configured_policy_and_only_available_capabilities(document_api, tmp_path, required):
|
||||
from pydantic import SecretStr
|
||||
client, _, _, e = document_api; login(client, e)
|
||||
e.settings = e.settings.model_copy(update={'ocr_review_required': required, 'embedding_api_key': SecretStr('fake-only')})
|
||||
report = tmp_path / 'calibration.json'
|
||||
report.write_text(json.dumps({'status': 'calibrated', 'calibration_id': 'fixture-only',
|
||||
'cutoff': {'profile': e.settings.processing_profile()['embedding'], 'distance': 1.0}}))
|
||||
config = e.voice_config.model_copy(update={'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
|
||||
capability = response.json()['capabilities']
|
||||
assert capability['ocr_review_required'] is required and capability['voice'] and capability['captions']
|
||||
assert not capability['text'] and 'fake-only' not in response.text and str(report) not in response.text
|
||||
report.write_text('{}')
|
||||
assert not client.get('/api/v1/configuration').json()['capabilities']['voice']
|
||||
assert client.patch('/api/v1/configuration', json={'ocr_review_required': not required}).status_code == 405
|
||||
assert client.post('/api/v1/documents/'+str(e.doc)+'/retry', json={'profile': 'forged'}, headers={'Origin':'http://localhost:8000','X-CSRF-Token':client.get('/api/v1/me').json()['csrf_token'], 'Idempotency-Key': str(uuid4())}).status_code == 422
|
||||
|
||||
|
||||
def test_mixed_pdf_never_labels_automatic_ocr_as_fully_reviewed(document_api):
|
||||
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'})
|
||||
content = pdf_bytes([[('image', image_bytes('PNG'), 10, 20)], [('text', 'Article 1: fee is 5%.', 10, 20)]])
|
||||
response = upload(client, headers, content, 'mixed.pdf')
|
||||
identifier = response.json()['document_id']; vision = FakeVision(); process(e, vision)
|
||||
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
|
||||
assert item['location']['page'] == 2
|
||||
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'], note='Inspected direct page only')
|
||||
assert client.post(f'/api/v1/documents/{identifier}/extraction-review/decisions', json=decision, headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 200
|
||||
assert client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 202
|
||||
services = process(e, vision)
|
||||
detail = polling(client, identifier)
|
||||
assert detail['status'] == 'ready' and not detail['is_active']
|
||||
assert detail['extraction_quality_decision'] == 'partially_reviewed'
|
||||
with e.engine.connect() as conn:
|
||||
doc = dict(conn.execute(text('SELECT * FROM documents WHERE id=:id'), {'id': UUID(identifier)}).mappings().one())
|
||||
envelope = services.candidates.inspect_pointer(doc['extraction_state']['complete_artifact'], document=doc)
|
||||
assert {annotation.locator for annotation in envelope.review_annotations} == {'pdf/page/2'}
|
||||
assert any(block.method == 'vision' and block.page == 1 for block in envelope.blocks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('escaped', [False, True])
|
||||
def test_large_eligible_review_persists_and_replays(document_api, escaped):
|
||||
from app.modules.documents.types import ExtractedBlock
|
||||
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'})
|
||||
suffix = ('😀"\\' * 165) if escaped else ('x' * 495)
|
||||
groups = [str(i).zfill(5) + suffix for i in range(4500)]
|
||||
calls = []
|
||||
class Vision:
|
||||
def transcribe(self, image, *, page, section, processing_profile):
|
||||
calls.append(1)
|
||||
return tuple(ExtractedBlock(ordinal=2*i+j, block_id=f'{section}/{2*i+j}',
|
||||
source_locator=f'{section}/{2*i+j}', page=page, method='vision', actual_model='fixture-flash',
|
||||
text=('Question: fee?' if j == 0 else 'Answer: 5%'),
|
||||
block_type=('question' if j == 0 else 'answer'), group_id=group)
|
||||
for i, group in enumerate(groups) for j in range(2))
|
||||
identifier = upload(client, headers, image_bytes('PNG'), 'large-faq.png').json()['document_id']
|
||||
process(e, Vision())
|
||||
item = client.get(f'/api/v1/documents/{identifier}/extraction-review').json()['items'][0]
|
||||
decision = dict(evidence_sha256=item['evidence_sha256'], decision='approve', checked=item['required_checks'],
|
||||
note='Generated retained evidence inspected', excluded_group_ids=groups[:-1])
|
||||
raw = json.dumps(decision, ensure_ascii=escaped, separators=(',', ':')).encode()
|
||||
assert len(raw) > 2 * 1024 * 1024
|
||||
url = f'/api/v1/documents/{identifier}/extraction-review/decisions'
|
||||
request_headers = dict(headers, **{'Idempotency-Key': str(uuid4()), 'Content-Type': 'application/json'})
|
||||
response = client.post(url, content=raw, headers=request_headers)
|
||||
assert response.status_code == 200, response.text
|
||||
replay = client.post(url, content=raw, headers=request_headers)
|
||||
assert replay.status_code == 200 and replay.headers['Idempotency-Replayed'] == 'true'
|
||||
assert client.post(f'/api/v1/documents/{identifier}/retry', headers=dict(headers, **{'Idempotency-Key': str(uuid4())})).status_code == 202
|
||||
process(e, Vision())
|
||||
detail = polling(client, identifier)
|
||||
assert detail['status'] == 'ready' and not detail['is_active'] and calls == [1]
|
||||
with e.engine.connect() as conn:
|
||||
state = conn.execute(text('SELECT extraction_state FROM documents WHERE id=:id'), {'id': identifier}).scalar_one()
|
||||
assert set(state['factual_inclusion']['excluded_group_ids']) == set(groups[:-1])
|
||||
Reference in New Issue
Block a user