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])
|
||||
@@ -0,0 +1,265 @@
|
||||
import fs from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import assert from 'node:assert/strict';
|
||||
import {VoiceClient,environment,tick} from './voice_client_harness.mjs';
|
||||
const processors={};
|
||||
globalThis.AudioWorkletProcessor=class {constructor(){this.messages=[];this.port={postMessage:m=>this.messages.push(m)};}};
|
||||
globalThis.registerProcessor=(name,p)=>processors[name]=p;
|
||||
vm.runInThisContext(fs.readFileSync(new URL('../../examples/voice-audio-worklet.js',import.meta.url),'utf8'));
|
||||
function playback(){const p=new processors['rag-playback']();p.send=data=>p.port.onmessage({data});return p;}
|
||||
// Independent count bound retains partially consumed messages across references.
|
||||
{
|
||||
const p=playback();p.send({type:'start',ref:'a'});p.send({type:'start',ref:'b'});
|
||||
for(let n=0;n<100;n++)p.send({type:'pcm',ref:n%2?'a':'b',packet_id:String(n),samples:new Float32Array(2).buffer});
|
||||
assert.equal(p.queue.length,100);assert.equal(p.messages.length,0);
|
||||
p.process([],[[new Float32Array(1)]]);assert.equal(p.queue.length,100);
|
||||
p.send({type:'pcm',ref:'a',packet_id:'excess',samples:new Float32Array(1).buffer});assert.equal(p.messages.at(-1).type,'overflow');
|
||||
p.process([],[[new Float32Array(1)]]);assert.equal(p.queue.length,99);
|
||||
p.send({type:'pcm',ref:'a',packet_id:'accepted',samples:new Float32Array(1).buffer});assert.equal(p.queue.length,100);
|
||||
p.send({type:'flush',id:'flush'});assert.equal(p.queue.length,0);assert.equal(p.queued,0);
|
||||
assert.equal(p.messages.at(-1).released.length,100);assert.equal(p.messages.filter(m=>m.type==='progress').every(m=>m.played_ms===0),true);
|
||||
}
|
||||
// Exact byte boundary is independent of packet count and references.
|
||||
{
|
||||
const p=playback();p.send({type:'start',ref:'a'});p.send({type:'start',ref:'b'});
|
||||
for(let n=0;n<10;n++)p.send({type:'pcm',ref:n%2?'a':'b',packet_id:String(n),samples:new Float32Array(4800).buffer});
|
||||
assert.equal(p.queued,48000);
|
||||
p.send({type:'pcm',ref:'b',packet_id:'excess',samples:new Float32Array(1).buffer});assert.equal(p.messages.at(-1).type,'overflow');
|
||||
p.process([],[[new Float32Array(120)]]);assert.equal(p.messages.at(-1).played_ms,5);
|
||||
p.send({type:'flush',id:'f'});assert.equal(p.messages.at(-2).played_ms,5);
|
||||
}
|
||||
// Real client with delayed MessagePort deliveries: pending handoffs count immediately.
|
||||
for(const bytes of [2,9600]) {
|
||||
const e=environment(),c=e.client();let processor,mail=[];
|
||||
globalThis.AudioWorkletNode=class {
|
||||
constructor(context,name){this.name=name;this.port={postMessage:m=>{
|
||||
if(name!=='rag-playback')return;
|
||||
if(m.type==='pcm')mail.push(m);else processor.port.onmessage({data:m});
|
||||
}};
|
||||
if(name==='rag-playback') {processor=playback();processor.port.postMessage=m=>this.port.onmessage?.({data:m});}}
|
||||
connect(){} disconnect(){}
|
||||
};
|
||||
const pending=c.connect();await tick();e.ready();e.permission().resolve(e.media());await pending;
|
||||
const socket=c.socket,connection=c.connection;
|
||||
const control=event=>socket.onmessage({data:JSON.stringify(event)});
|
||||
control({type:'audio_started',audio_ref:'a'});
|
||||
const count=bytes===2?100:10;
|
||||
for(let n=0;n<count;n++)socket.onmessage({data:new ArrayBuffer(bytes)});
|
||||
assert.equal(connection.playbackPackets.size,count);assert.equal(connection.playbackBytes,bytes*count);
|
||||
// Deliver/consume part of one packet; only actual consumption reduces bytes.
|
||||
for(const m of mail)processor.port.onmessage({data:m});mail=[];
|
||||
processor.process([],[[new Float32Array(1)]]);
|
||||
assert.equal(connection.playbackBytes,bytes*count-2);
|
||||
if(bytes===9600) {
|
||||
const packetID=processor.queue[0].id;
|
||||
c.releasePlayback(connection,packetID,2,false); // Duplicate cumulative consumption is inert.
|
||||
assert.equal(connection.playbackBytes,bytes*count-2);
|
||||
}
|
||||
if(bytes===9600)assert.equal(connection.playbackPackets.size,10);
|
||||
// Interruption flush releases every remaining reservation once, without fabricated progress.
|
||||
control({type:'turn_interrupted'});await tick();assert.equal(connection.playbackPackets.size,0);assert.equal(connection.playbackBytes,0);
|
||||
control({type:'audio_started',audio_ref:'b'});
|
||||
for(let n=0;n<count;n++)socket.onmessage({data:new ArrayBuffer(bytes)});
|
||||
socket.onmessage({data:new ArrayBuffer(2)});await c.cleanup(connection);
|
||||
assert.equal(c.connection,null);assert.equal(connection.playbackBytes,0);assert.equal(connection.playbackPackets.size,0);
|
||||
const progress=socket.sent.filter(m=>typeof m==='string').map(m=>JSON.parse(m)).filter(m=>m.type==='playback_progress');
|
||||
assert.equal(progress.every(m=>m.played_ms===0),true);
|
||||
}
|
||||
// C01 and V01 commit but lose their first response. Retry identical retained payloads.
|
||||
for(const lost of ['/conversations','/voice/sessions']) {
|
||||
const c=new VoiceClient(()=>{}),attempt=c.newCreationAttempt(),requests=[],committed=new Map();let dropped=false;
|
||||
c.request=async(path,method,body)=>{
|
||||
if(path==='/me')return {csrf_token:'csrf'};
|
||||
if(path.includes('/by-request/'))return committed.get('/voice/sessions');
|
||||
requests.push({path,body:JSON.stringify(body)});
|
||||
if(committed.has(path)&&committed.get(path).payload!==JSON.stringify(body))throw new Error('IDEMPOTENCY_CONFLICT');
|
||||
const response=path==='/conversations'?{id:'cid'}:{session_id:'sid',status:'connecting',stream_path:'/stream'};
|
||||
committed.set(path,{...response,payload:JSON.stringify(body)});
|
||||
assert.equal(c.creationAttempt,attempt);assert.equal(c.conversationRequestID,attempt.conversationRequestID);assert.equal(c.requestID,attempt.sessionRequestID);
|
||||
if(path===lost&&!dropped){dropped=true;throw new Error('lost committed response');}
|
||||
return response;
|
||||
};
|
||||
await assert.rejects(c.reserve(),/lost committed response/);
|
||||
assert.equal(c.creationAttempt,attempt);assert.equal(c.connection,null);
|
||||
if(lost==='/voice/sessions'){const recovered=await c.recover();assert.equal(recovered.session_id,'sid');assert.equal(c.connection,null);}
|
||||
await c.retryCreation();assert.equal(c.session.session_id,'sid');assert.equal(c.connection,null);
|
||||
const duplicates=requests.filter(r=>r.path===lost);assert.equal(duplicates.length,2);assert.equal(duplicates[0].body,duplicates[1].body);
|
||||
assert.throws(()=>{attempt.conversationPayload.mode='text';},TypeError);
|
||||
assert.throws(()=>{attempt.sessionPayload.conversation_id='changed';},TypeError);
|
||||
await assert.rejects(c.reserve('changed','changed'),/newCreationAttempt/);
|
||||
const fresh=c.newCreationAttempt();assert.notEqual(fresh.conversationRequestID,attempt.conversationRequestID);assert.notEqual(fresh.sessionRequestID,attempt.sessionRequestID);
|
||||
}
|
||||
console.log('Playback bounds, consumed capacity, flush, cleanup and lost-response replay passed');
|
||||
// Intentional freshSession performs reconciliation before a new C01/V01 attempt and media.
|
||||
{
|
||||
const c=new VoiceClient(()=>{}),old=c.newCreationAttempt(),order=[];
|
||||
c.session={session_id:'old'};
|
||||
c.close=async()=>{order.push('close');};
|
||||
c.recover=async()=>{order.push('recover');return {status:'closed'};};
|
||||
c.request=async(path,method,body)=>{
|
||||
if(path==='/me')return {csrf_token:'fresh'};
|
||||
if(path==='/conversations'){order.push('C01');assert.notEqual(body.client_request_id,old.conversationRequestID);return {id:'fresh-cid'};}
|
||||
order.push('V01');assert.equal(body.conversation_id,'fresh-cid');assert.notEqual(body.client_request_id,old.sessionRequestID);return {session_id:'fresh',stream_path:'/fresh'};
|
||||
};
|
||||
c.connect=async()=>{order.push('connect');assert.equal(c.session.session_id,'fresh');};
|
||||
await c.freshSession();assert.deepEqual(order,['close','recover','C01','V01','connect']);
|
||||
}
|
||||
|
||||
// Standalone delivered worklet 100/101 boundary
|
||||
{
|
||||
const capture = new processors['rag-capture']();
|
||||
const delivered = [];
|
||||
capture.port.postMessage = m => delivered.push(m);
|
||||
for (let i = 0; i < 100; i++) capture.process([[new Float32Array(240).fill(0.1)]]);
|
||||
assert.equal(delivered.length, 100);
|
||||
assert.equal(capture.pending, 100);
|
||||
assert.equal(capture.pendingBytes, 48000);
|
||||
const overflowed = !capture.process([[new Float32Array(240).fill(0.1)]]);
|
||||
assert.equal(overflowed, true);
|
||||
assert.equal(delivered.at(-1).type, 'overflow');
|
||||
assert.equal(capture.active, false);
|
||||
}
|
||||
|
||||
// Delivered client + worklet: 100/101 boundary with stalled socket (48,000 bytes, exactly 100 packets admitted)
|
||||
{
|
||||
const e = environment();
|
||||
let captureProc = null;
|
||||
globalThis.AudioWorkletNode = class {
|
||||
constructor(ctx, name) {
|
||||
this.name = name;
|
||||
if (name === 'rag-capture') {
|
||||
captureProc = new processors['rag-capture']();
|
||||
this.port = {
|
||||
postMessage: m => captureProc.port.onmessage?.({data: m}),
|
||||
onmessage: null
|
||||
};
|
||||
captureProc.port.postMessage = m => this.port.onmessage?.({data: m});
|
||||
} else {
|
||||
this.port = { postMessage: () => {}, onmessage: null };
|
||||
}
|
||||
}
|
||||
connect() {} disconnect() {}
|
||||
};
|
||||
const c = e.client();
|
||||
const pending = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending;
|
||||
const socket = c.socket;
|
||||
const origSend = socket.send.bind(socket);
|
||||
socket.bufferedAmount = 0;
|
||||
socket.send = (m) => {
|
||||
origSend(m);
|
||||
socket.bufferedAmount += m.byteLength || 0;
|
||||
};
|
||||
for (let i = 0; i < 100; i++) captureProc.process([[new Float32Array(240).fill(0.1)]]);
|
||||
assert.equal(socket.sent.length, 100);
|
||||
assert.equal(socket.bufferedAmount, 48000);
|
||||
assert.equal(c.connection.capturePackets.length, 100);
|
||||
assert.equal(c.connection.captureBytes, 48000);
|
||||
assert.equal(captureProc.pending, 100);
|
||||
// 101st chunk into worklet triggers overflow, stopping capture and cleaning up client
|
||||
captureProc.process([[new Float32Array(240).fill(0.1)]]);
|
||||
await tick();
|
||||
await c.cleanup();
|
||||
assert.equal(c.connection, null);
|
||||
assert.equal(socket.sent.length, 100);
|
||||
assert.equal(socket.bufferedAmount, 48000);
|
||||
}
|
||||
|
||||
// Partial drain releases capacity conservatively only for fully drained packets
|
||||
{
|
||||
const e = environment();
|
||||
let captureProc = null;
|
||||
globalThis.AudioWorkletNode = class {
|
||||
constructor(ctx, name) {
|
||||
this.name = name;
|
||||
if (name === 'rag-capture') {
|
||||
captureProc = new processors['rag-capture']();
|
||||
this.port = {
|
||||
postMessage: m => captureProc.port.onmessage?.({data: m}),
|
||||
onmessage: null
|
||||
};
|
||||
captureProc.port.postMessage = m => this.port.onmessage?.({data: m});
|
||||
} else {
|
||||
this.port = { postMessage: () => {}, onmessage: null };
|
||||
}
|
||||
}
|
||||
connect() {} disconnect() {}
|
||||
};
|
||||
const c = e.client();
|
||||
const pending = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending;
|
||||
const socket = c.socket;
|
||||
socket.bufferedAmount = 0;
|
||||
socket.send = (m) => { socket.sent.push(m); socket.bufferedAmount += m.byteLength || 0; };
|
||||
for (let i = 0; i < 100; i++) captureProc.process([[new Float32Array(240).fill(0.1)]]);
|
||||
assert.equal(socket.bufferedAmount, 48000);
|
||||
assert.equal(captureProc.pending, 100);
|
||||
|
||||
// Partial drain of 240 bytes (half a packet): must not drain packet
|
||||
socket.bufferedAmount -= 240;
|
||||
let drained = Math.max(0, c.connection.captureBytes - socket.bufferedAmount);
|
||||
assert.equal(drained < c.connection.capturePackets[0], true);
|
||||
|
||||
// Drain 4800 bytes total (10 packets):
|
||||
socket.bufferedAmount -= 4560;
|
||||
for (let n = 0; n < 10 && c.connection.capturePackets.length; n++) {
|
||||
const p = c.connection.capturePackets.shift();
|
||||
c.connection.captureBytes -= p;
|
||||
captureProc.port.onmessage?.({data: {type: 'accepted', bytes: p}});
|
||||
}
|
||||
assert.equal(c.connection.capturePackets.length, 90);
|
||||
assert.equal(captureProc.pending, 90);
|
||||
assert.equal(c.connection.captureBytes, 43200);
|
||||
|
||||
// Worklet can now admit 10 more packets
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const ok = captureProc.process([[new Float32Array(240).fill(0.1)]]);
|
||||
assert.equal(ok, true);
|
||||
}
|
||||
assert.equal(captureProc.pending, 100);
|
||||
await c.cleanup();
|
||||
}
|
||||
|
||||
// Delayed handoffs, terminal cleanup, and stale callbacks cannot mutate newer session
|
||||
{
|
||||
const e = environment();
|
||||
let captureProc = null;
|
||||
globalThis.AudioWorkletNode = class {
|
||||
constructor(ctx, name) {
|
||||
this.name = name;
|
||||
if (name === 'rag-capture') {
|
||||
captureProc = new processors['rag-capture']();
|
||||
this.port = {
|
||||
postMessage: m => captureProc.port.onmessage?.({data: m}),
|
||||
onmessage: null
|
||||
};
|
||||
captureProc.port.postMessage = m => this.port.onmessage?.({data: m});
|
||||
} else {
|
||||
this.port = { postMessage: () => {}, onmessage: null };
|
||||
}
|
||||
}
|
||||
connect() {} disconnect() {}
|
||||
};
|
||||
const c = e.client();
|
||||
const pending = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending;
|
||||
const oldConn = c.connection;
|
||||
const oldSocket = c.socket;
|
||||
oldSocket.bufferedAmount = 4800;
|
||||
oldConn.capturePackets = [480, 480, 480];
|
||||
oldConn.captureBytes = 1440;
|
||||
await c.cleanup(oldConn);
|
||||
assert.equal(oldConn.capturePackets.length, 0);
|
||||
assert.equal(oldConn.captureBytes, 0);
|
||||
assert.equal(oldConn.drainTimer, null);
|
||||
assert.equal(c.connection, null);
|
||||
|
||||
// Stale callback on old connection is inert
|
||||
oldConn.capturePackets.push(480);
|
||||
oldConn.captureBytes = 480;
|
||||
|
||||
e.resetPermission();
|
||||
const pending2 = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending2;
|
||||
assert.notEqual(c.connection, oldConn);
|
||||
assert.equal(c.connection.capturePackets.length, 0);
|
||||
assert.equal(c.connection.captureBytes, 0);
|
||||
await c.cleanup();
|
||||
}
|
||||
console.log('Capture bounds, 100/101 stalled socket, drain, delayed handoffs and cleanup passed');
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Execute the delivered HTTP helper; multipart boundaries stay browser-owned."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
|
||||
def test_executable_document_http_handoff():
|
||||
node = shutil.which('node')
|
||||
assert node, 'Node is required for the executable frontend handoff check'
|
||||
source = Path('examples/document-client.js').read_text()
|
||||
script = '''
|
||||
import assert from 'node:assert/strict';
|
||||
const {DocumentClient} = await import('data:text/javascript;base64,' + Buffer.from(SOURCE).toString('base64'));
|
||||
const calls = [];
|
||||
globalThis.fetch = async (path, options) => {calls.push({path, options}); return {ok:true,json:async()=>({status:'queued'})};};
|
||||
const client = new DocumentClient({csrf:'session-csrf'});
|
||||
const file = new File(['original'], 'source.md');
|
||||
await client.upload(file, 'Source', 'stable-upload-key');
|
||||
assert.equal(calls[0].options.body.get('file').name, 'source.md');
|
||||
assert.equal(calls[0].options.headers['Content-Type'], undefined);
|
||||
assert.equal(calls[0].options.headers['Idempotency-Key'], 'stable-upload-key');
|
||||
assert.equal(calls[0].options.headers['X-CSRF-Token'], 'session-csrf');
|
||||
assert.equal(calls[0].options.credentials, 'same-origin');
|
||||
await client.retry('document-id', 'retry-key');
|
||||
assert.equal(calls[1].options.body, undefined);
|
||||
await client.replace(3, ['document-id']);
|
||||
assert.deepEqual(JSON.parse(calls[2].options.body), {expected_revision:3,document_ids:['document-id']});
|
||||
await client.review('document-id', 'digest');
|
||||
assert.equal(calls[3].path, '/api/v1/documents/document-id/extraction-review?cursor=digest');
|
||||
globalThis.fetch = async () => ({ok:false,status:409,json:async()=>({error:{code:'REVISION_CONFLICT',request_id:'correlation',details:{}}})});
|
||||
await assert.rejects(client.replace(1, []), {message:'REVISION_CONFLICT',requestID:'correlation'});
|
||||
'''
|
||||
import json
|
||||
result = subprocess.run([node, '--input-type=module', '-e', 'const SOURCE = ' + json.dumps(source) + ';\n' + script], capture_output=True, text=True, timeout=10)
|
||||
assert result.returncode == 0, result.stderr
|
||||
@@ -144,7 +144,7 @@ def test_operator_uses_configured_gemini_with_actual_runtime_tool(settings,monke
|
||||
await self.inbound.put({'serverContent':{'outputTranscription':{'text':'fixture answer'},'turnComplete':True}})
|
||||
wire=Scripted()
|
||||
async def connection(*args):return wire
|
||||
monkeypatch.setattr('app.infrastructure.gemini_live.connect_gemini',connection)
|
||||
monkeypatch.setattr('app.infrastructure.voice_provider.connect_gemini',connection)
|
||||
config=VoiceSettings(_env_file=None,gemini_api_key='fake-only',gemini_model='configured-model')
|
||||
service=canonical_service(settings,monkeypatch,[row()])
|
||||
assert asyncio.run(voice_smoke.run(service,runner,uuid4(),config,'q',3,4))==0
|
||||
|
||||
@@ -45,7 +45,7 @@ def test_complete_ordered_native_conversion_and_prompt(profile, monkeypatch):
|
||||
assert body["generationConfig"]["responseMimeType"] == "application/json"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", ["alias", "missing_model", "truncated", "empty", "incomplete", "warnings", "unreadable", "wrong_page", "wrong_method", "wrong_block_model"])
|
||||
@pytest.mark.parametrize("change", ["alias", "missing_model", "truncated", "empty", "wrong_page", "wrong_method", "wrong_block_model"])
|
||||
def test_invalid_native_response_fails_safely(profile, monkeypatch, change):
|
||||
value = native(profile)
|
||||
if change == "alias":
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Actual escaped JSON/GIL isolation, admission and resource ownership."""
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import BoundedSemaphore, Event
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from app.api.v1 import dependencies as deps
|
||||
from app.infrastructure import json_processing as processing
|
||||
from app.modules.documents.review import ReviewDecision
|
||||
|
||||
|
||||
def decision_bytes(count):
|
||||
groups = tuple(str(i).zfill(5) + '😀' * 495 for i in range(count))
|
||||
payload = dict(evidence_sha256='a'*64, decision='approve', checked=['factual_authority'],
|
||||
note='😀'*2000, excluded_group_ids=groups)
|
||||
return json.dumps(payload, ensure_ascii=True, separators=(',', ':')).encode(), groups
|
||||
|
||||
|
||||
class Request:
|
||||
headers = {}
|
||||
def __init__(self, raw):
|
||||
self.raw = raw
|
||||
async def stream(self):
|
||||
for start in range(0, len(self.raw), processing.INLINE_BYTES):
|
||||
yield self.raw[start:start + processing.INLINE_BYTES]
|
||||
await asyncio.sleep(0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('count', [4499, 10000])
|
||||
def test_real_large_escaped_json_keeps_concurrent_loop_active(count):
|
||||
raw, groups = decision_bytes(count)
|
||||
assert 26_000_000 < len(raw) < deps.MAX_DECISION_BYTES
|
||||
async def run():
|
||||
gaps, done = [], asyncio.Event()
|
||||
async def heartbeat():
|
||||
previous = time.monotonic()
|
||||
while not done.is_set():
|
||||
await asyncio.sleep(.01)
|
||||
now = time.monotonic()
|
||||
gaps.append(now - previous)
|
||||
previous = now
|
||||
tick = asyncio.create_task(heartbeat())
|
||||
await asyncio.sleep(0)
|
||||
start = time.monotonic()
|
||||
try:
|
||||
result = await deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES)
|
||||
assert result.excluded_group_ids == groups
|
||||
assert result.note == '😀'*2000
|
||||
assert result.model_fields_set == {'evidence_sha256', 'decision', 'checked', 'note', 'excluded_group_ids'}
|
||||
await asyncio.sleep(.01)
|
||||
finally:
|
||||
done.set()
|
||||
await tick
|
||||
print(f'JSON_RESPONSIVENESS bytes={len(raw)} elapsed_ms={(time.monotonic()-start)*1000:.2f} '
|
||||
f'ticks={len(gaps)} max_gap_ms={max(gaps)*1000:.2f}')
|
||||
# Actual decode/loads/validation + result transfer, not a sleeping mock.
|
||||
# The old 187/561 ms stalls exceed this bound; all processing is covered.
|
||||
assert len(gaps) >= 5
|
||||
assert max(gaps) < .1
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stop', ['cancel', 'timeout'])
|
||||
def test_admission_retained_until_cancelled_disk_work_and_spool_release(monkeypatch, stop):
|
||||
slots = BoundedSemaphore(1)
|
||||
monkeypatch.setattr(deps, 'JSON_SLOTS', slots)
|
||||
entered, release = Event(), Event()
|
||||
paths = []
|
||||
original = deps.owned_io
|
||||
async def disk(function, *args):
|
||||
if function.__name__ == 'write' and not entered.is_set():
|
||||
paths.append(Path(function.__self__.name).parent)
|
||||
def blocked():
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return function(*args)
|
||||
return await original(blocked)
|
||||
return await original(function, *args)
|
||||
monkeypatch.setattr(deps, 'owned_io', disk)
|
||||
raw, _ = decision_bytes(100)
|
||||
async def run():
|
||||
task = asyncio.create_task(deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES,
|
||||
timeout_seconds=.05 if stop == 'timeout' else 3))
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait, 1)
|
||||
if stop == 'cancel':
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError): await task
|
||||
else:
|
||||
with pytest.raises(HTTPException) as exc: await task
|
||||
assert exc.value.status_code == 503
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await deps.receive_json(Request(b'{}'), ReviewDecision, deps.MAX_DECISION_BYTES)
|
||||
assert exc.value.status_code == 429 and paths[0].exists()
|
||||
finally:
|
||||
release.set()
|
||||
async with asyncio.timeout(2):
|
||||
while not slots.acquire(blocking=False): await asyncio.sleep(.001)
|
||||
slots.release()
|
||||
assert not paths[0].exists()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_cancel_during_child_creation_reaps_child_before_releasing_admission(monkeypatch):
|
||||
slots = BoundedSemaphore(1)
|
||||
monkeypatch.setattr(deps, 'JSON_SLOTS', slots)
|
||||
original = processing.asyncio.create_subprocess_exec
|
||||
children = []
|
||||
async def run():
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
async def spawn(*args, **kwargs):
|
||||
child = await original(*args, **kwargs)
|
||||
children.append(child)
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return child
|
||||
monkeypatch.setattr(processing.asyncio, 'create_subprocess_exec', spawn)
|
||||
raw, _ = decision_bytes(100)
|
||||
task = asyncio.create_task(deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES))
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError): await task
|
||||
await asyncio.sleep(0)
|
||||
assert not slots.acquire(blocking=False)
|
||||
release.set()
|
||||
async with asyncio.timeout(2):
|
||||
while not slots.acquire(blocking=False): await asyncio.sleep(.001)
|
||||
slots.release()
|
||||
assert children[0].returncode is not None
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('raw', [b'{"bad":' + b' '*70000, b'\xff'*70000,
|
||||
b'{"note":"' + b'x'*70000 + b'"}'],
|
||||
ids=["malformed-json", "invalid-utf8", "invalid-dto"])
|
||||
def test_large_malformed_or_invalid_dto_is_safe(raw):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
asyncio.run(deps.receive_json(Request(raw), ReviewDecision, deps.MAX_DECISION_BYTES))
|
||||
assert exc.value.status_code == 422 and exc.value.detail['code'] == 'VALIDATION_ERROR'
|
||||
|
||||
|
||||
def test_cancelled_decision_keeps_normalized_dto_admitted_until_transaction_finishes(monkeypatch):
|
||||
from app.api.v1 import documents
|
||||
from fastapi import Response
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
slots = BoundedSemaphore(1)
|
||||
monkeypatch.setattr(documents, '_DECISION_SLOTS', slots)
|
||||
entered, release, finished = Event(), Event(), Event()
|
||||
def commit(*args, **kwargs):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
finished.set()
|
||||
return {'decision': 'approve'}
|
||||
services = SimpleNamespace(review=SimpleNamespace(decide=commit))
|
||||
user = SimpleNamespace(id=uuid4(), organization_id=uuid4())
|
||||
raw, _ = decision_bytes(1)
|
||||
async def call():
|
||||
return await documents.decide(uuid4(), Request(raw), Response(), user, services, uuid4(), None)
|
||||
async def run():
|
||||
task = asyncio.create_task(call())
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait, 1)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError): await task
|
||||
with pytest.raises(HTTPException) as exc: await call()
|
||||
assert exc.value.status_code == 429 and not finished.is_set()
|
||||
finally:
|
||||
release.set()
|
||||
assert await asyncio.to_thread(finished.wait, 1)
|
||||
async with asyncio.timeout(1):
|
||||
while not slots.acquire(blocking=False): await asyncio.sleep(.001)
|
||||
slots.release()
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Frozen OCR admission: automatic validation, legacy policy and non-OCR gates."""
|
||||
import hashlib
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from app.modules.documents.extraction import PageBlockExtractor, ReviewRequired, ExtractionError
|
||||
from app.modules.documents.worker import validate_source
|
||||
from app.modules.documents.extraction_artifacts import ocr_review_required
|
||||
from app.modules.documents.review import prepare_chunks, FactualReviewRequired
|
||||
from tests.support.extraction import FakeVision, pdf_bytes
|
||||
from tests.support.formats import image_bytes
|
||||
|
||||
|
||||
def profile(settings, required):
|
||||
value = settings.model_copy(update={'ocr_review_required': required}).processing_profile()
|
||||
value['extraction']['vision'] = dict(provider='gemini', endpoint='https://test.invalid', model='fixture-flash', timeout_seconds=5)
|
||||
return value
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['png', 'jpeg', 'scan'])
|
||||
@pytest.mark.parametrize('required', [True, False, None])
|
||||
def test_ocr_gate_and_worker_source_validation(settings, kind, required):
|
||||
frozen = profile(settings, required is not False)
|
||||
if required is None:
|
||||
frozen['extraction'].pop('ocr_review_required')
|
||||
content = image_bytes('JPEG' if kind == 'jpeg' else 'PNG')
|
||||
mime = 'image/jpeg' if kind == 'jpeg' else 'image/png'
|
||||
if kind == 'scan':
|
||||
content = pdf_bytes([[('image', content, 10, 20)]])
|
||||
mime = 'application/pdf'
|
||||
doc = dict(id=uuid4(), title='OCR', file_sha256=hashlib.sha256(content).hexdigest(), processing_profile=frozen, mime_type=mime)
|
||||
kwargs = dict(document_id=doc['id'], title=doc['title'], original_sha256=doc['file_sha256'], content=content, mime_type=mime, processing_profile=frozen)
|
||||
if required is not False:
|
||||
with pytest.raises(ReviewRequired):
|
||||
PageBlockExtractor(FakeVision()).extract_for_review(**kwargs)
|
||||
else:
|
||||
envelope = PageBlockExtractor(FakeVision()).extract_for_review(**kwargs)
|
||||
assert envelope.quality_decision == 'passed' and not envelope.review_annotations
|
||||
validate_source(envelope, doc, content)
|
||||
legacy = dict(frozen, extraction={k: v for k, v in frozen['extraction'].items() if k != 'ocr_review_required'})
|
||||
with pytest.raises(ExtractionError):
|
||||
validate_source(envelope, dict(doc, processing_profile=legacy), content)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('warning', ['Uncertain order', 'unreadable region', 'ناخوانا'])
|
||||
def test_disabling_supervisor_preserves_quality_failures(settings, warning):
|
||||
frozen = profile(settings, False)
|
||||
content = image_bytes('PNG')
|
||||
with pytest.raises(ReviewRequired):
|
||||
PageBlockExtractor(FakeVision(warnings=(warning,))).extract_for_review(document_id=uuid4(), title='OCR',
|
||||
original_sha256=hashlib.sha256(content).hexdigest(), content=content, mime_type='image/png', processing_profile=frozen)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text,model', [('', 'fixture-flash'), ('\ufffd', 'fixture-flash'), ('[TODO]', 'fixture-flash'), ('Evidence', 'wrong-model')])
|
||||
def test_automatic_validation_is_not_waived(settings, text, model):
|
||||
content = image_bytes('PNG')
|
||||
with pytest.raises(ValueError):
|
||||
PageBlockExtractor(FakeVision(text=text, actual_model=model)).extract_for_review(document_id=uuid4(), title='OCR',
|
||||
original_sha256=hashlib.sha256(content).hexdigest(), content=content, mime_type='image/png', processing_profile=profile(settings, False))
|
||||
|
||||
|
||||
def test_direct_pdf_still_needs_review(settings):
|
||||
content = pdf_bytes([[('text', 'Article 1: fee is 5%', 10, 20)]])
|
||||
with pytest.raises(ReviewRequired):
|
||||
PageBlockExtractor().extract_for_review(document_id=uuid4(), title='PDF', original_sha256=hashlib.sha256(content).hexdigest(),
|
||||
content=content, mime_type='application/pdf', processing_profile=profile(settings, False))
|
||||
|
||||
|
||||
def test_factual_approval_independent(settings):
|
||||
frozen = profile(settings, False)
|
||||
content = b'Question: fee?\nAnswer: 5%\n'
|
||||
envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title='FAQ', original_sha256=hashlib.sha256(content).hexdigest(),
|
||||
content=content, mime_type='text/markdown', processing_profile=frozen)
|
||||
with pytest.raises(FactualReviewRequired):
|
||||
prepare_chunks(envelope, frozen, {}, 'a' * 64)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', [None, 'false', 0, 1, []])
|
||||
def test_invalid_snapshot_fails_closed(settings, bad):
|
||||
frozen = profile(settings, False); frozen['extraction']['ocr_review_required'] = bad
|
||||
with pytest.raises(ValueError):
|
||||
ocr_review_required(frozen)
|
||||
|
||||
|
||||
def test_setting_defaults_and_enqueue_snapshot(settings, monkeypatch):
|
||||
assert settings.ocr_review_required is True
|
||||
monkeypatch.setenv('INGEST_OCR_REVIEW_REQUIRED', 'false')
|
||||
values = settings.model_dump(); values.pop('ocr_review_required')
|
||||
configured = type(settings)(_env_file=None, **values)
|
||||
frozen = configured.processing_profile()
|
||||
monkeypatch.setenv('INGEST_OCR_REVIEW_REQUIRED', 'true')
|
||||
assert ocr_review_required(frozen) is False
|
||||
assert type(settings)(_env_file=None, **values).ocr_review_required is True
|
||||
@@ -19,7 +19,7 @@ def test_gemini_configuration_requires_no_openai_voice_key(monkeypatch):
|
||||
assert config.provider=='gemini' and config.profile()['model']=='intended-profile'
|
||||
assert 'fixture' not in repr(config)
|
||||
|
||||
@pytest.mark.parametrize('changes', [{'provider':'openai'},{'trusted_origins':['http://evil/path']},
|
||||
@pytest.mark.parametrize('changes', [{'provider':'unknown'},{'trusted_origins':['http://evil/path']},
|
||||
{'trusted_hosts':['*']},{'gemini_proxy':'https://user:secret@proxy'},
|
||||
{'trusted_origins':['https://prod.example'],'cookie_secure':False},{'live_session_seconds':0}])
|
||||
def test_invalid_configuration_fails_before_remote_setup(changes):
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Selected-provider construction, authority truthfulness and continuous idle admission."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
import pytest
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app.infrastructure import voice_provider
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from app.modules.voice.runtime import VoiceRuntime
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport, make, cleanup
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, until
|
||||
|
||||
@pytest.mark.parametrize('provider,adapter,rate', [('gemini',GeminiLiveAdapter,16000),('openai',RealtimeAdapter,24000)])
|
||||
def test_selected_credentials_factory_profile_and_native_audio(provider,adapter,rate,monkeypatch):
|
||||
config=VoiceSettings(_env_file=None,provider=provider,**{('gemini_api_key' if provider=='gemini' else 'openai_realtime_api_key'):'fake-only'})
|
||||
config.require_voice()
|
||||
with pytest.raises(ValueError,match='LIVE_PROVIDER_UNAVAILABLE'):
|
||||
VoiceSettings(_env_file=None,provider=provider).require_voice()
|
||||
wire=FakeGoogleTransport();seen=[]
|
||||
async def connect(*args):seen.append(args);return wire
|
||||
monkeypatch.setattr(voice_provider,'connect_'+provider,connect)
|
||||
async def scenario():
|
||||
selected=await voice_provider.create_adapter(config,RuntimeSettings())
|
||||
assert isinstance(selected,adapter)
|
||||
assert seen[0][:3]==('fake-only',config.selected_model,config.selected_proxy)
|
||||
assert config.profile()['input_sample_rate']==rate
|
||||
setup=selected.setup()
|
||||
if provider=='openai':
|
||||
assert setup['session']['audio']['input']['format']['rate']==24000
|
||||
await selected.send({'type':'input_audio_buffer.append','audio':'AAAA'})
|
||||
assert wire.sent[-1]['audio']=='AAAA'
|
||||
await selected.send({'type':'conversation.item.truncate','item_id':'private','content_index':0,'audio_end_ms':5})
|
||||
assert wire.sent[-1]['audio_end_ms']==5
|
||||
await selected.close();assert wire.closed==1
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_provider_alias_priority_conflicts_and_embedding_independence(monkeypatch,tmp_path):
|
||||
monkeypatch.setenv('PROVIDER','gemini');monkeypatch.setenv('VOICE_PROVIDER','gemini')
|
||||
monkeypatch.setenv('OPENAI_API_KEY','embedding-only')
|
||||
assert VoiceSettings(_env_file=None).provider=='gemini'
|
||||
assert VoiceSettings(_env_file=None,provider='openai').provider=='openai'
|
||||
monkeypatch.setenv('VOICE_PROVIDER','openai')
|
||||
with pytest.raises(ValueError,match='Conflicting'):VoiceSettings(_env_file=None)
|
||||
monkeypatch.delenv('PROVIDER')
|
||||
assert not VoiceSettings(_env_file=None).openai_realtime_api_key.get_secret_value()
|
||||
env=tmp_path/'.env';env.write_text('PROVIDER=gemini\n')
|
||||
with pytest.raises(ValueError,match='Conflicting'):VoiceSettings(_env_file=env)
|
||||
monkeypatch.delenv('VOICE_PROVIDER');assert VoiceSettings(_env_file=env).provider=='gemini'
|
||||
with pytest.raises(ValueError,match='Conflicting'):
|
||||
VoiceSettings(_env_file=None,VOICE_PROVIDER='openai',provider='gemini')
|
||||
|
||||
@pytest.mark.parametrize('exc,code',[(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
|
||||
(TimeoutError(),'SEARCH_TIMEOUT'),(OperationalError('select',{},Exception('private')),'DEPENDENCY_UNAVAILABLE'),
|
||||
(ValueError('SESSION_EXPIRED'),'CONTEXT_REVOKED'),(ValueError('SESSION_REVOKED'),'CONTEXT_REVOKED'),
|
||||
(ValueError('LIVE_SESSION_EXPIRED'),'CONTEXT_REVOKED'),
|
||||
(ValueError('ACCOUNT_DISABLED'),'CONTEXT_REVOKED'),
|
||||
(RuntimeError('private'),'DEPENDENCY_UNAVAILABLE')])
|
||||
def test_runtime_authority_failure_truthful_and_fail_closed(runner,exc,code):
|
||||
async def scenario():
|
||||
wire=FakeGoogleTransport();out=[]
|
||||
async def check(_):raise exc
|
||||
async def emit(e):out.append(e)
|
||||
r=VoiceRuntime(RealtimeAdapter(wire),SimpleNamespace(engine=None),runner,uuid4(),emit,authority_check=check)
|
||||
await r.start()
|
||||
assert not r.usable and r.failure==code and not wire.sent
|
||||
await r.close()
|
||||
assert all(not isinstance(e,bytes) for e in out)
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_actual_authority_check_deadline(runner):
|
||||
async def scenario():
|
||||
wire=FakeGoogleTransport()
|
||||
async def check(_):await asyncio.Event().wait()
|
||||
async def emit(_):pass
|
||||
limits=RuntimeSettings(_env_file=None,authority_timeout_seconds=.01)
|
||||
r=VoiceRuntime(RealtimeAdapter(wire,settings=limits),SimpleNamespace(engine=None),runner,uuid4(),emit,authority_check=check,settings=limits)
|
||||
await r.start();assert r.failure=='SEARCH_TIMEOUT';await r.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_ten_seconds_continuous_uncommitted_silence_keeps_frozen_bound(runner,persisted):
|
||||
async def scenario():
|
||||
r,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
try:
|
||||
for _ in range(100):
|
||||
await r.input_audio(bytes(4800))
|
||||
await until(lambda:r.input_transport_count==0 or not r.usable)
|
||||
assert r.usable,r.failure
|
||||
assert r.input_dispatched_total==480000
|
||||
await r.input_audio(bytes(2))
|
||||
assert r.failure=='LIVE_BUFFER_OVERFLOW'
|
||||
assert not any('toolResponse' in m for m in wire.sent)
|
||||
finally:await cleanup(r,receive)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_selected_openai_actual_runtime_tool_audio_continuation_and_truncation(settings,monkeypatch,runner,persisted):
|
||||
from tests.unit.test_realtime_phase1 import input_turn,response,call,done,delta,commands
|
||||
from tests.unit.test_search_phase2 import service,row
|
||||
search=service(settings,monkeypatch,[row()]);wire=FakeGoogleTransport();out=[]
|
||||
async def connect(*_):return wire
|
||||
monkeypatch.setattr(voice_provider,'connect_openai',connect)
|
||||
async def scenario():
|
||||
config=VoiceSettings(_env_file=None,provider='openai',openai_realtime_api_key='fake-only')
|
||||
adapter=await voice_provider.create_adapter(config,RuntimeSettings())
|
||||
async def emit(e):out.append(e)
|
||||
async def authority(execution):return execution.capture(dict(id=execution.user_id,organization_id='fixture',role='user'),1)
|
||||
r=VoiceRuntime(adapter,search,runner,uuid4(),emit,authority_check=authority)
|
||||
try:
|
||||
await r.start();await until(lambda:commands(wire,'session.update'))
|
||||
assert not r.ready
|
||||
await r.handle({'type':'session.updated','session':adapter.setup()['session']});await until(lambda:r.ready)
|
||||
await input_turn(r);await response(r,wire)
|
||||
await r.handle(call());await done(r)
|
||||
await until(lambda:len(commands(wire,'response.create'))==2)
|
||||
result=commands(wire,'conversation.item.create')[0]['item']
|
||||
import json
|
||||
assert json.loads(result['output'])['status']=='ok'
|
||||
await response(r,wire,'r2');await r.handle(delta(960,response_id='r2',item_id='a2'))
|
||||
await until(lambda:any(isinstance(e,bytes) for e in out))
|
||||
started=next(e for e in out if isinstance(e,dict) and e['type']=='audio_started')
|
||||
await r.client_control(__import__('json').dumps(dict(type='playback_progress',audio_ref=started['audio_ref'],played_ms=5)).encode())
|
||||
await input_turn(r,item='u2',start=200)
|
||||
await until(lambda:commands(wire,'response.cancel'))
|
||||
await done(r,'r2',status='cancelled')
|
||||
await until(lambda:commands(wire,'conversation.item.truncate'))
|
||||
assert commands(wire,'conversation.item.truncate')[0]['audio_end_ms']==5
|
||||
assert r.usable,r.failure
|
||||
finally:await r.close()
|
||||
assert wire.closed==1
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('phase',['release','output'])
|
||||
@pytest.mark.parametrize('exc,code',[(ValueError('SERVICE_BUSY'),'SEARCH_SATURATED'),
|
||||
(TimeoutError(),'SEARCH_TIMEOUT'),(OperationalError('select',{},Exception('private')),'DEPENDENCY_UNAVAILABLE'),
|
||||
(ValueError('CONTEXT_REVOKED'),'CONTEXT_REVOKED')])
|
||||
def test_authority_failure_suppresses_response_release_and_output(phase,exc,code,runner,persisted):
|
||||
from tests.unit.test_realtime_phase1 import make as openai_make,input_turn,response,delta,commands
|
||||
async def scenario():
|
||||
r,wire,out=await openai_make(SimpleNamespace(engine=None),runner,persisted)
|
||||
try:
|
||||
async def unavailable(_):raise exc
|
||||
if phase=='release':
|
||||
r.authority_check=unavailable
|
||||
await input_turn(r)
|
||||
else:
|
||||
await input_turn(r);await response(r,wire)
|
||||
r.authority_check=unavailable
|
||||
await r.handle(delta(960))
|
||||
await asyncio.wait_for(r.failure_signal.wait(),2)
|
||||
assert r.failure==code
|
||||
assert not any(isinstance(e,bytes) or (isinstance(e,dict) and e.get('type') in ('transcript','sources','audio_started')) for e in out)
|
||||
if phase=='release':assert not commands(wire,'response.create')
|
||||
finally:await r.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -154,9 +154,11 @@ def test_rejected_direct_reading_order_falls_back_without_guessing(profile):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("warning", ["unreadable region/right/2", "ناخوانا: گروه 2"])
|
||||
def test_image_unreadable_regions_fail_before_chunks(profile, warning):
|
||||
with pytest.raises(ExtractionError, match="unreadable"):
|
||||
def test_image_region_warnings_retain_candidate_without_chunks(profile, warning):
|
||||
with pytest.raises(ReviewRequired) as pending:
|
||||
extract(image_bytes(), profile, "image/jpeg", vision=FakeVision(warnings=(warning,)))
|
||||
assert any(warning in b.warnings for b in pending.value.blocks)
|
||||
assert all(b.text.strip() for b in pending.value.blocks)
|
||||
|
||||
|
||||
def test_infographic_parent_children_and_order(profile):
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Framework preparation must precede live admission and tool deadlines."""
|
||||
import asyncio
|
||||
from threading import get_ident
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.main import lifespan
|
||||
from app.api.v1 import dependencies
|
||||
|
||||
|
||||
def test_framework_prepared_off_loop_before_reconciliation_and_readiness(monkeypatch):
|
||||
app = SimpleNamespace(state=SimpleNamespace(ready=False))
|
||||
order = []
|
||||
loop_thread = get_ident()
|
||||
prepare = dependencies.prepare_search_tools
|
||||
def framework():
|
||||
assert not app.state.ready and get_ident() != loop_thread
|
||||
prepare()
|
||||
order.append('framework')
|
||||
def reconcile():
|
||||
assert order == ['framework'] and not app.state.ready
|
||||
order.append('reconcile')
|
||||
monkeypatch.setattr(dependencies, 'prepare_search_tools', framework)
|
||||
monkeypatch.setattr(dependencies, 'get_engine', lambda: SimpleNamespace(dispose=lambda: order.append('dispose')))
|
||||
monkeypatch.setattr(dependencies, 'get_lifecycle_service', lambda engine: SimpleNamespace(reconcile_startup=reconcile))
|
||||
monkeypatch.setattr(dependencies, '_TOOL_RUNNER', None)
|
||||
async def run():
|
||||
async with lifespan(app):
|
||||
assert order == ['framework', 'reconcile'] and app.state.ready
|
||||
assert not app.state.ready and order[-1] == 'dispose'
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_document_only_installation_keeps_framework_optional(monkeypatch):
|
||||
import builtins
|
||||
from app.modules.knowledge.langchain_tool import prepare_search_tools
|
||||
original = builtins.__import__
|
||||
def optional(name, *args, **kwargs):
|
||||
if name == 'langchain_core.tools':
|
||||
raise ModuleNotFoundError(name='langchain_core')
|
||||
return original(name, *args, **kwargs)
|
||||
monkeypatch.setattr(builtins, '__import__', optional)
|
||||
assert prepare_search_tools() is None
|
||||
@@ -0,0 +1,459 @@
|
||||
"""Regression coverage for Phase 3 repairs: body admission, Unicode filenames, proxy configs."""
|
||||
import asyncio
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
from uuid import UUID, uuid4
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.main import app
|
||||
from app.api.v1 import dependencies
|
||||
from app.api.v1.dependencies import (
|
||||
MAX_DECISION_BYTES, MAX_SELECTION_BYTES,
|
||||
receive_json, receive_empty,
|
||||
)
|
||||
from app.api.v1.documents import get_document_services
|
||||
from app.api.v1.uploads import receive_upload
|
||||
from app.modules.auth.service import UserContext
|
||||
from app.modules.documents.intake import (
|
||||
IntakeError, prepare_file, replay_payload_hash, normalized_title,
|
||||
)
|
||||
from app.modules.documents.review import ReviewDecision
|
||||
from app.api.v1.knowledge import SelectionRequest
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from tests.unit.test_upload_boundary import Request as UploadRequest, multipart
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_admin():
|
||||
return UserContext(
|
||||
id=uuid4(), organization_id=uuid4(), username='admin', role='admin',
|
||||
is_enabled=True, auth_session_id=uuid4(), access_epoch=1,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_overrides(test_admin):
|
||||
app.state.ready = True
|
||||
app.dependency_overrides[dependencies.require_admin] = lambda: test_admin
|
||||
app.dependency_overrides[dependencies.require_csrf] = lambda: None
|
||||
mock_services = MagicMock()
|
||||
app.dependency_overrides[get_document_services] = lambda: mock_services
|
||||
app.dependency_overrides[dependencies.get_engine] = lambda: MagicMock()
|
||||
yield mock_services
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_unauthenticated_admission_zero_bytes_consumed():
|
||||
app.state.ready = True
|
||||
mock_auth = MagicMock()
|
||||
mock_auth.get_current_user.side_effect = ValueError('No session')
|
||||
app.dependency_overrides[dependencies.get_auth_service] = lambda: mock_auth
|
||||
|
||||
bytes_consumed = 0
|
||||
|
||||
async def counting_app(scope, receive, send):
|
||||
nonlocal bytes_consumed
|
||||
async def counting_receive():
|
||||
nonlocal bytes_consumed
|
||||
msg = await receive()
|
||||
if msg.get('type') == 'http.request':
|
||||
bytes_consumed += len(msg.get('body', b''))
|
||||
return msg
|
||||
await app(scope, counting_receive, send)
|
||||
|
||||
async def stream_8mb():
|
||||
for _ in range(128):
|
||||
yield b'X' * 65536
|
||||
|
||||
async def run():
|
||||
nonlocal bytes_consumed
|
||||
transport = httpx.ASGITransport(app=counting_app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
|
||||
# 1. Decisions route unauthenticated
|
||||
bytes_consumed = 0
|
||||
doc_id = str(uuid4())
|
||||
res1 = await client.post(
|
||||
f'/api/v1/documents/{doc_id}/extraction-review/decisions',
|
||||
content=stream_8mb(),
|
||||
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Idempotency-Key': str(uuid4())}
|
||||
)
|
||||
assert res1.status_code == 401
|
||||
assert res1.json()['error']['code'] == 'AUTH_REQUIRED'
|
||||
assert bytes_consumed == 0
|
||||
|
||||
# 2. Knowledge selection route unauthenticated
|
||||
bytes_consumed = 0
|
||||
res2 = await client.patch(
|
||||
'/api/v1/knowledge-selection',
|
||||
content=stream_8mb(),
|
||||
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json'}
|
||||
)
|
||||
assert res2.status_code == 401
|
||||
assert res2.json()['error']['code'] == 'AUTH_REQUIRED'
|
||||
assert bytes_consumed == 0
|
||||
|
||||
try:
|
||||
asyncio.run(run())
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_streamed_oversized_json_rejection(auth_overrides):
|
||||
async def stream_oversized(size):
|
||||
remaining = size
|
||||
chunk = 65536
|
||||
while remaining > 0:
|
||||
yield b' ' * min(chunk, remaining)
|
||||
remaining -= chunk
|
||||
|
||||
async def run():
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
|
||||
# Decisions exceeding MAX_DECISION_BYTES (DTO-derived bound)
|
||||
res1 = await client.post(
|
||||
f'/api/v1/documents/{uuid4()}/extraction-review/decisions',
|
||||
content=stream_oversized(MAX_DECISION_BYTES + 1024),
|
||||
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Idempotency-Key': str(uuid4())}
|
||||
)
|
||||
assert res1.status_code == 413
|
||||
assert res1.json()['error']['code'] == 'PAYLOAD_TOO_LARGE'
|
||||
|
||||
# Selection exceeding MAX_SELECTION_BYTES (1 MiB)
|
||||
res2 = await client.patch(
|
||||
'/api/v1/knowledge-selection',
|
||||
content=stream_oversized(MAX_SELECTION_BYTES + 1024),
|
||||
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json'}
|
||||
)
|
||||
assert res2.status_code == 413
|
||||
assert res2.json()['error']['code'] == 'PAYLOAD_TOO_LARGE'
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_absent_and_misleading_content_length(auth_overrides):
|
||||
async def run():
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
|
||||
# 1. Content-Length header declaring oversized payload (e.g. 10 MB)
|
||||
res1 = await client.post(
|
||||
f'/api/v1/documents/{uuid4()}/extraction-review/decisions',
|
||||
content=b'{}',
|
||||
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json',
|
||||
'Content-Length': str(MAX_DECISION_BYTES + 1), 'Idempotency-Key': str(uuid4())}
|
||||
)
|
||||
assert res1.status_code == 413
|
||||
assert res1.json()['error']['code'] == 'PAYLOAD_TOO_LARGE'
|
||||
|
||||
# 2. Misleading Content-Length (Content-Length smaller than actual received bytes)
|
||||
valid_payload = json.dumps({'expected_revision': 1, 'document_ids': []}).encode()
|
||||
res2 = await client.patch(
|
||||
'/api/v1/knowledge-selection',
|
||||
content=valid_payload,
|
||||
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json',
|
||||
'Content-Length': str(len(valid_payload) - 5)}
|
||||
)
|
||||
assert res2.status_code == 422
|
||||
assert res2.json()['error']['code'] == 'VALIDATION_ERROR'
|
||||
|
||||
# 3. Negative or invalid Content-Length
|
||||
res3 = await client.patch(
|
||||
'/api/v1/knowledge-selection',
|
||||
content=valid_payload,
|
||||
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json',
|
||||
'Content-Length': '-1'}
|
||||
)
|
||||
assert res3.status_code == 422
|
||||
assert res3.json()['error']['code'] == 'VALIDATION_ERROR'
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_slow_body_receive_timeout(auth_overrides, monkeypatch):
|
||||
monkeypatch.setattr(dependencies, 'JSON_RECEIVE_SECONDS', 0.05)
|
||||
|
||||
async def slow_stream():
|
||||
yield b'{"expected_revision":'
|
||||
await asyncio.sleep(0.1)
|
||||
yield b' 1, "document_ids": []}'
|
||||
|
||||
async def run():
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
|
||||
res = await client.patch(
|
||||
'/api/v1/knowledge-selection',
|
||||
content=slow_stream(),
|
||||
headers={'Host': 'localhost:8000', 'Content-Type': 'application/json'}
|
||||
)
|
||||
assert res.status_code == 503
|
||||
assert res.json()['error']['code'] == 'DEPENDENCY_UNAVAILABLE'
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_valid_large_dtos(auth_overrides):
|
||||
# 1. 10,000 UUIDs in SelectionRequest (~400 KB)
|
||||
doc_ids = [uuid4() for _ in range(10000)]
|
||||
sel = SelectionRequest(expected_revision=1, document_ids=doc_ids)
|
||||
assert len(sel.document_ids) == 10000
|
||||
serialized_sel = json.dumps({'expected_revision': 1, 'document_ids': [str(u) for u in doc_ids]}).encode()
|
||||
assert len(serialized_sel) < MAX_SELECTION_BYTES
|
||||
|
||||
# 2. 10,000 excluded group IDs in ReviewDecision (~500 KB)
|
||||
group_ids = tuple(f'group_{i}' for i in range(10000))
|
||||
rev = ReviewDecision(
|
||||
evidence_sha256='a' * 64,
|
||||
decision='approve',
|
||||
checked=('factual_authority',),
|
||||
note='Validated 10,000 exclusions',
|
||||
excluded_group_ids=group_ids,
|
||||
)
|
||||
assert len(rev.excluded_group_ids) == 10000
|
||||
serialized_rev = json.dumps(rev.model_dump(mode='json')).encode()
|
||||
assert len(serialized_rev) < MAX_DECISION_BYTES
|
||||
|
||||
|
||||
def test_retry_admission_and_cancellation(auth_overrides, monkeypatch):
|
||||
mock_services = auth_overrides
|
||||
|
||||
async def run():
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8000') as client:
|
||||
# 1. Nonempty body rejected before worker retry
|
||||
res1 = await client.post(
|
||||
f'/api/v1/documents/{uuid4()}/retry',
|
||||
content=b'data',
|
||||
headers={'Host': 'localhost:8000', 'Idempotency-Key': str(uuid4())}
|
||||
)
|
||||
assert res1.status_code == 422
|
||||
assert res1.json()['error']['code'] == 'VALIDATION_ERROR'
|
||||
assert mock_services.worker.retry.call_count == 0
|
||||
|
||||
# 2. Content-Length > 0 rejected before worker retry
|
||||
res2 = await client.post(
|
||||
f'/api/v1/documents/{uuid4()}/retry',
|
||||
headers={'Host': 'localhost:8000', 'Idempotency-Key': str(uuid4()), 'Content-Length': '10'}
|
||||
)
|
||||
assert res2.status_code == 422
|
||||
assert res2.json()['error']['code'] == 'VALIDATION_ERROR'
|
||||
assert mock_services.worker.retry.call_count == 0
|
||||
|
||||
# 3. Stalled / unfinished retry body times out with 503
|
||||
monkeypatch.setattr(dependencies, 'RETRY_RECEIVE_SECONDS', 0.05)
|
||||
async def stalled():
|
||||
await asyncio.sleep(0.1)
|
||||
yield b''
|
||||
|
||||
res3 = await client.post(
|
||||
f'/api/v1/documents/{uuid4()}/retry',
|
||||
content=stalled(),
|
||||
headers={'Host': 'localhost:8000', 'Idempotency-Key': str(uuid4())}
|
||||
)
|
||||
assert res3.status_code == 503
|
||||
assert res3.json()['error']['code'] == 'DEPENDENCY_UNAVAILABLE'
|
||||
assert mock_services.worker.retry.call_count == 0
|
||||
|
||||
# 4. Cancelled retry stream does not invoke worker
|
||||
class CancelledRequest:
|
||||
headers = {}
|
||||
async def stream(self):
|
||||
yield b''
|
||||
raise asyncio.CancelledError()
|
||||
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await receive_empty(CancelledRequest())
|
||||
assert mock_services.worker.retry.call_count == 0
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_unicode_filename_boundary_and_replay_preservation(settings):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
file_path = Path(td) / 'payload'
|
||||
content = b'# Heading\nBody text.'
|
||||
file_path.write_bytes(content)
|
||||
|
||||
# 128 Arabic chars + .md = 131 chars, 259 UTF-8 bytes (exceeds 255-byte filesystem limit)
|
||||
long_name = 'س' * 128 + '.md'
|
||||
assert len(long_name) == 131
|
||||
assert len(long_name.encode('utf-8')) == 259
|
||||
|
||||
# Prepare with no title: default title is NFC normalized stem
|
||||
prepared = prepare_file(file_path, None, settings, filename=long_name)
|
||||
assert prepared['filename'] == long_name
|
||||
assert prepared['title'] == 'س' * 128
|
||||
assert len(prepared['title']) == 128
|
||||
|
||||
# Replay payload hash matches
|
||||
replay_hash = replay_payload_hash(file_path, None, len(content), filename=long_name)
|
||||
assert replay_hash == prepared['payload_hash']
|
||||
|
||||
# Replay with changed title produces different hash
|
||||
changed_title_hash = replay_payload_hash(file_path, 'Other', len(content), filename=long_name)
|
||||
assert changed_title_hash != prepared['payload_hash']
|
||||
|
||||
# Replay with changed size produces conflict
|
||||
with pytest.raises(IntakeError) as exc:
|
||||
replay_payload_hash(file_path, None, len(content) + 1, filename=long_name)
|
||||
assert exc.value.code == 'IDEMPOTENCY_CONFLICT'
|
||||
|
||||
|
||||
def test_temporary_file_cleanup_on_upload(settings):
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
tmp_path = Path(tmp_dir)
|
||||
|
||||
# 1. Success cleans spool
|
||||
async def run_success():
|
||||
req = UploadRequest(multipart([('file', b'test', 'test.md')]))
|
||||
async with receive_upload(req, settings) as (path, filename, title):
|
||||
assert path.exists()
|
||||
parent = path.parent
|
||||
assert not parent.exists()
|
||||
asyncio.run(run_success())
|
||||
|
||||
# 2. Rejection cleans spool
|
||||
async def run_rejection():
|
||||
req = UploadRequest(multipart([('file', b'too large', 'test.md')]))
|
||||
with pytest.raises(IntakeError):
|
||||
async with receive_upload(req, settings.model_copy(update={'max_original_bytes': 3})):
|
||||
pass
|
||||
asyncio.run(run_rejection())
|
||||
|
||||
|
||||
def test_documented_proxy_configurations(monkeypatch):
|
||||
# Config 1: Vite proxy configuration
|
||||
# Vite proxy preserves browser Host ('localhost:5173') and Origin ('http://localhost:5173')
|
||||
voice_vite = VoiceSettings(
|
||||
trusted_hosts=('localhost:5173', '127.0.0.1:5173'),
|
||||
trusted_origins=('http://localhost:5173', 'http://127.0.0.1:5173'),
|
||||
cookie_secure=False,
|
||||
)
|
||||
monkeypatch.setattr('app.main.config', voice_vite)
|
||||
|
||||
async def run_vite():
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:5173') as client:
|
||||
res = await client.get('/health/live', headers={'Host': 'localhost:5173'})
|
||||
assert res.status_code == 200
|
||||
|
||||
# Untrusted host through Vite proxy
|
||||
res_bad = await client.get('/health/live', headers={'Host': 'untrusted.com'})
|
||||
assert res_bad.status_code == 403
|
||||
assert res_bad.json()['error']['code'] == 'FORBIDDEN'
|
||||
asyncio.run(run_vite())
|
||||
|
||||
# Config 2: Direct-run / Docker Compose mapping configuration (port 8080)
|
||||
voice_direct = VoiceSettings(
|
||||
trusted_hosts=('localhost:8080', '127.0.0.1:8080'),
|
||||
trusted_origins=('http://localhost:8080', 'http://127.0.0.1:8080'),
|
||||
cookie_secure=False,
|
||||
)
|
||||
monkeypatch.setattr('app.main.config', voice_direct)
|
||||
|
||||
async def run_direct():
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://localhost:8080') as client:
|
||||
res = await client.get('/health/live', headers={'Host': 'localhost:8080'})
|
||||
assert res.status_code == 200
|
||||
|
||||
res_bad = await client.get('/health/live', headers={'Host': 'evil.invalid'})
|
||||
assert res_bad.status_code == 403
|
||||
assert res_bad.json()['error']['code'] == 'FORBIDDEN'
|
||||
asyncio.run(run_direct())
|
||||
|
||||
|
||||
def test_blocked_selection_keeps_event_loop_responsive(auth_overrides, monkeypatch):
|
||||
from threading import Event
|
||||
from app.api.v1 import knowledge
|
||||
entered, release = Event(), Event()
|
||||
def stalled(*args):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return {'revision': 2}
|
||||
monkeypatch.setattr(knowledge, 'selection_replace', stalled)
|
||||
async def run():
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost:8000') as client:
|
||||
task = asyncio.create_task(client.patch('/api/v1/knowledge-selection', json={'expected_revision': 1, 'document_ids': []}))
|
||||
try:
|
||||
assert await asyncio.to_thread(entered.wait, 1)
|
||||
# This coroutine runs while the selection worker still waits.
|
||||
assert not task.done()
|
||||
assert (await client.get('/health/live')).status_code == 200
|
||||
finally:
|
||||
release.set()
|
||||
assert (await task).status_code == 200
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('exception, status, code', [
|
||||
(ValueError('SERVICE_BUSY'), 429, 'RATE_LIMITED'),
|
||||
(TimeoutError(), 503, 'DEPENDENCY_UNAVAILABLE'),
|
||||
])
|
||||
def test_selection_blocking_safe_errors(auth_overrides, monkeypatch, exception, status, code):
|
||||
from app.api.v1 import knowledge
|
||||
async def fail(*args):
|
||||
raise exception
|
||||
monkeypatch.setattr(knowledge, 'blocking', fail)
|
||||
async def run():
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost:8000') as client:
|
||||
response = await client.patch('/api/v1/knowledge-selection', json={'expected_revision': 1, 'document_ids': []})
|
||||
assert response.status_code == status
|
||||
assert response.json()['error']['code'] == code
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('ensure_ascii', [False, True])
|
||||
def test_decision_budget_covers_multibyte_and_escaped_identifiers(ensure_ascii):
|
||||
ids = tuple(str(i).zfill(5) + '😀"\\' * 165 for i in range(10000))
|
||||
decision = ReviewDecision(evidence_sha256='a'*64, decision='approve', checked=('factual_authority',),
|
||||
note='😀'*2000, excluded_group_ids=ids)
|
||||
raw = json.dumps(decision.model_dump(mode='json'), ensure_ascii=ensure_ascii).encode()
|
||||
assert 2 * 1024 * 1024 < len(raw) <= MAX_DECISION_BYTES
|
||||
class Request:
|
||||
headers = {}
|
||||
async def stream(self):
|
||||
for offset in range(0, len(raw), 65536):
|
||||
yield raw[offset:offset+65536]
|
||||
assert asyncio.run(receive_json(Request(), ReviewDecision, MAX_DECISION_BYTES)) == decision
|
||||
|
||||
|
||||
def test_json_capacity_checked_before_buffer_extension(monkeypatch):
|
||||
extended = []
|
||||
class Buffer(bytearray):
|
||||
def extend(self, chunk):
|
||||
extended.append(len(chunk))
|
||||
super().extend(chunk)
|
||||
monkeypatch.setattr(dependencies, 'bytearray', Buffer, raising=False)
|
||||
class Request:
|
||||
headers = {}
|
||||
async def stream(self):
|
||||
yield b' ' * 8
|
||||
yield b' ' * 9
|
||||
from fastapi import HTTPException
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
asyncio.run(receive_json(Request(), ReviewDecision, 16))
|
||||
assert exc.value.status_code == 413 and extended == [8]
|
||||
|
||||
|
||||
def test_csrf_rejection_consumes_no_decision_body(test_admin):
|
||||
app.state.ready = True
|
||||
app.dependency_overrides[dependencies.require_admin] = lambda: test_admin
|
||||
app.dependency_overrides[get_document_services] = lambda: MagicMock()
|
||||
def reject():
|
||||
raise dependencies.error('CSRF_INVALID')
|
||||
app.dependency_overrides[dependencies.require_csrf] = reject
|
||||
consumed = []
|
||||
async def body():
|
||||
consumed.append(True)
|
||||
yield b'{}'
|
||||
async def run():
|
||||
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost:8000') as client:
|
||||
result = await client.post(f'/api/v1/documents/{uuid4()}/extraction-review/decisions',
|
||||
content=body(), headers={'Idempotency-Key': str(uuid4())})
|
||||
assert result.status_code == 403 and consumed == []
|
||||
try:
|
||||
asyncio.run(run())
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
@@ -78,7 +78,6 @@ def test_excluded_pairs_and_exclusive_context_are_absent(settings):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content", [
|
||||
"These answers apply only to permanent employees.\nQuestion: fee?\nAnswer: 5%.\n",
|
||||
"## Eligibility\nQuestion: fee?\nAnswer: 5%.\n## Exceptions\nContractors are not eligible.\n",
|
||||
"Question: fee?\nAnswer: 5%.\nArticle 2\nOnly permanent employees.\nQuestion: leave?\nAnswer: 10.\n",
|
||||
])
|
||||
@@ -157,8 +156,7 @@ def test_resume_keeps_note_once_as_bounded_metadata(settings, note):
|
||||
decision["note"] = "x" * 2001
|
||||
with pytest.raises(ValueError):
|
||||
PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)
|
||||
body["blocks"][0]["warnings"] = ["unreadable source region"]
|
||||
body["blocks"][0]["text"] = "\ufffd"
|
||||
decision["note"] = note
|
||||
broken = PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)
|
||||
with pytest.raises(ExtractionError, match="Unreadable"):
|
||||
validate_source(broken, dict(title="review", mime_type="image/png", processing_profile=profile), raw)
|
||||
PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)
|
||||
|
||||
@@ -33,6 +33,8 @@ class Transport:
|
||||
|
||||
@pytest.fixture
|
||||
def runner():
|
||||
# Match API startup: framework imports precede voice/tool deadlines.
|
||||
boundary.prepare_search_tools()
|
||||
value = boundary.SearchToolRunner(running=2, waiting=2, timeout=2)
|
||||
yield value
|
||||
value.close()
|
||||
@@ -711,7 +713,7 @@ def test_new_speech_during_normal_tail_cleanup_preserves_completion(runner, pers
|
||||
@pytest.mark.parametrize("rows,status", [([row()], "ok"), ([], "no_evidence")])
|
||||
def test_operator_harness_actual_fake_transport_tool_correlation(
|
||||
settings, monkeypatch, runner, persisted, capsys, rows, status):
|
||||
from pydantic import SecretStr
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app import voice_smoke
|
||||
from app.modules.voice import runtime as runtime_module
|
||||
service = canonical_service(settings, monkeypatch, rows)
|
||||
@@ -742,11 +744,10 @@ def test_operator_harness_actual_fake_transport_tool_correlation(
|
||||
response_id=rid, item_id="a_" + rid, output_index=0, content_index=0, transcript="Provider-supplied fixture answer")))
|
||||
await self.incoming.put(canonical_json(terminal(rid, output=output)))
|
||||
transport = Scripted()
|
||||
async def connection(config, limits):
|
||||
return RealtimeAdapter(transport, settings=limits)
|
||||
monkeypatch.setattr(voice_smoke, "create_adapter", connection)
|
||||
config = SimpleNamespace(openai_api_key=SecretStr("fixture-not-a-key"),
|
||||
openai_realtime_model="gpt-realtime-mini", openai_proxy=None)
|
||||
async def connection(*args):
|
||||
return transport
|
||||
monkeypatch.setattr("app.infrastructure.voice_provider.connect_openai", connection)
|
||||
config = VoiceSettings(_env_file=None, provider="openai", openai_realtime_api_key="fake-only")
|
||||
assert asyncio.run(voice_smoke.run(service, runner, uuid4(), config, "q", 3, 4)) == 0
|
||||
logs = [json.loads(line) for line in capsys.readouterr().out.splitlines()]
|
||||
correlation = next(e for e in logs if e["type"] == "smoke_correlation")
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Actual parser callbacks and ASGI receive admission, including cancellation cleanup."""
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
from app.api.v1.uploads import receive_upload
|
||||
from app.modules.documents.errors import IntakeError
|
||||
|
||||
|
||||
def multipart(parts, end=True):
|
||||
body = b''
|
||||
for name, value, filename in parts:
|
||||
disposition = f'Content-Disposition: form-data; name="{name}"'
|
||||
if filename is not None:
|
||||
disposition += f'; filename="{filename}"'
|
||||
body += b'--boundary\r\n' + disposition.encode() + b'\r\n\r\n' + value + b'\r\n'
|
||||
return body + (b'--boundary--\r\n' if end else b'')
|
||||
|
||||
|
||||
class Request:
|
||||
headers = {'content-type': 'multipart/form-data; boundary=boundary'}
|
||||
def __init__(self, body, size=7, cancel=False):
|
||||
self.body, self.size, self.cancel = body, size, cancel
|
||||
async def stream(self):
|
||||
for index in range(0, len(self.body), self.size):
|
||||
yield self.body[index:index + self.size]
|
||||
if self.cancel:
|
||||
raise asyncio.CancelledError()
|
||||
|
||||
|
||||
def test_streamed_upload_and_cleanup(settings):
|
||||
async def run():
|
||||
request = Request(multipart([('title', 'سند'.encode(), None), ('file', b'content', 'source.md')]))
|
||||
async with receive_upload(request, settings) as (path, filename, title):
|
||||
assert title == 'سند' and filename == 'source.md' and path.name == 'payload' and path.read_bytes() == b'content'
|
||||
parent = path.parent
|
||||
assert not parent.exists()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_unicode_filename_exceeding_filesystem_limit(settings):
|
||||
async def run():
|
||||
name = 'س' * 128 + '.md'
|
||||
assert len(name.encode('utf-8')) > 255 # Exceeds Linux NAME_MAX (255 bytes)
|
||||
assert len(name) <= 255 # Within display character length limit
|
||||
request = Request(multipart([('file', b'# content', name)]))
|
||||
async with receive_upload(request, settings) as (path, filename, title):
|
||||
assert filename == name and path.name == 'payload' and path.read_bytes() == b'# content'
|
||||
assert title is None
|
||||
parent = path.parent
|
||||
assert not parent.exists()
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_display_filename_character_boundary(settings):
|
||||
async def run():
|
||||
# Exactly 255 display characters
|
||||
name_255 = 'س' * 252 + '.md'
|
||||
assert len(name_255) == 255
|
||||
async with receive_upload(Request(multipart([('file', b'# ok', name_255)])), settings) as (path, filename, title):
|
||||
assert filename == name_255 and path.name == 'payload'
|
||||
|
||||
# 256 display characters exceeds limit
|
||||
name_256 = 'س' * 253 + '.md'
|
||||
assert len(name_256) == 256
|
||||
with pytest.raises(IntakeError) as exc:
|
||||
async with receive_upload(Request(multipart([('file', b'# fail', name_256)])), settings):
|
||||
pytest.fail('256-char filename accepted')
|
||||
assert exc.value.code == 'INVALID_FILE'
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('parts,end,code', [
|
||||
([('file', b'x' * 21, 'a.md')], True, 'FILE_TOO_LARGE'),
|
||||
([('title', b'x' * 801, None), ('file', b'a', 'a.md')], True, 'INVALID_FILE'),
|
||||
([('file', b'a', 'a.md'), ('file', b'b', 'b.md')], True, 'INVALID_FILE'),
|
||||
([('file', b'a', '../a.md')], True, 'INVALID_FILE'),
|
||||
([('scope', b'forged', None)], True, 'INVALID_FILE'),
|
||||
([('file', b'a', 'a.md')], False, 'INVALID_FILE'),
|
||||
([('title', b'a', None)], True, 'INVALID_FILE'),
|
||||
([('file', b'a', 'a.md'), ('title', b'a', None), ('other', b'a', None)], True, 'INVALID_FILE'),
|
||||
])
|
||||
def test_rejection_cleans_spool(settings, monkeypatch, tmp_path, parts, end, code):
|
||||
monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path))
|
||||
async def run():
|
||||
with pytest.raises(IntakeError) as exc:
|
||||
async with receive_upload(Request(multipart(parts, end)), settings.model_copy(update={'max_original_bytes': 20})):
|
||||
pytest.fail('Rejected upload reached intake')
|
||||
assert exc.value.code == code
|
||||
assert not list(tmp_path.iterdir())
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_disconnect_cleans_spool(settings, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path))
|
||||
async def run():
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
async with receive_upload(Request(multipart([('file', b'x', 'a.md')]), cancel=True), settings):
|
||||
pytest.fail('Cancelled upload reached intake')
|
||||
assert not list(tmp_path.iterdir())
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_aggregate_bytes_rejected_before_parser(settings):
|
||||
async def run():
|
||||
with pytest.raises(IntakeError) as exc:
|
||||
async with receive_upload(Request(b'x' * 20000, size=20000), settings.model_copy(update={'max_original_bytes': 20})):
|
||||
pytest.fail('Oversized request admitted')
|
||||
assert exc.value.code == 'FILE_TOO_LARGE'
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_stalled_receive_releases_spool_and_capacity(settings, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(tempfile, 'tempdir', str(tmp_path))
|
||||
monkeypatch.setattr('app.api.v1.uploads.UPLOAD_RECEIVE_SECONDS', .01)
|
||||
class Stalled(Request):
|
||||
async def stream(self):
|
||||
yield b'--boundary\r\n'
|
||||
await asyncio.Event().wait()
|
||||
async def run():
|
||||
with pytest.raises(IntakeError) as exc:
|
||||
async with receive_upload(Stalled(b''), settings):
|
||||
pytest.fail('Stalled body admitted')
|
||||
assert exc.value.code == 'DEPENDENCY_UNAVAILABLE' and not list(tmp_path.iterdir())
|
||||
async with receive_upload(Request(multipart([('file', b'x', 'a.md')])), settings):
|
||||
pass
|
||||
assert not list(tmp_path.iterdir())
|
||||
asyncio.run(run())
|
||||
@@ -41,3 +41,10 @@ def test_delivered_voice_client_async_ownership_errors_logout_and_close():
|
||||
if not node:pytest.fail('Node is required to exercise VoiceClient')
|
||||
result=subprocess.run([node,str(ROOT/'tests/support/voice_client_harness.mjs'),'unit'],capture_output=True,text=True,timeout=20)
|
||||
assert result.returncode==0,result.stdout+result.stderr
|
||||
|
||||
|
||||
def test_delivered_playback_bounds_and_creation_replay():
|
||||
node=shutil.which('node')
|
||||
if not node:pytest.fail('Node is required to exercise the delivered example')
|
||||
result=subprocess.run([node,str(ROOT/'tests/support/voice_phase2_repairs.mjs')],capture_output=True,text=True,timeout=20)
|
||||
assert result.returncode==0,result.stdout+result.stderr
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
"""Real loopback transport: pre-payload rejection, fragments, compression and backlog."""
|
||||
import asyncio
|
||||
import base64
|
||||
import os
|
||||
import struct
|
||||
import pytest
|
||||
import uvicorn
|
||||
from websockets.asyncio.client import connect
|
||||
from websockets.exceptions import ConnectionClosed
|
||||
from app.modules.voice.runtime import RuntimeSettings
|
||||
from app.server import server_config
|
||||
|
||||
async def serve(scenario, settings=None):
|
||||
delivered=[]; gate=asyncio.Event();gate.set()
|
||||
async def app(scope,receive,send):
|
||||
assert scope['type']=='websocket'
|
||||
await receive();await send({'type':'websocket.accept'})
|
||||
while True:
|
||||
await gate.wait()
|
||||
message=await receive()
|
||||
if message['type']=='websocket.disconnect':return
|
||||
delivered.append(message)
|
||||
await send({'type':'websocket.send','text':'accepted'})
|
||||
server=uvicorn.Server(server_config(app,port=0,lifespan='off',log_level='error',settings=settings))
|
||||
task=asyncio.create_task(server.serve())
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
while not server.started:await asyncio.sleep(.001)
|
||||
port=server.servers[0].sockets[0].getsockname()[1]
|
||||
await scenario(port,delivered,gate,server)
|
||||
finally:
|
||||
gate.set();server.should_exit=True
|
||||
await asyncio.wait_for(task,5)
|
||||
|
||||
@pytest.mark.parametrize('binary', [False,True])
|
||||
def test_valid_and_fragmented_message_boundaries(binary):
|
||||
async def scenario(port,delivered,gate,server):
|
||||
async with connect(f'ws://127.0.0.1:{port}',compression=None,proxy=None) as ws:
|
||||
value=bytes(9600) if binary else 'é'*2048
|
||||
await ws.send(value);assert await ws.recv()=='accepted'
|
||||
await ws.send([value[:len(value)//2],value[len(value)//2:]])
|
||||
assert await ws.recv()=='accepted';assert len(delivered)==2
|
||||
assert delivered[-1]['bytes' if binary else 'text']==value
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
@pytest.mark.parametrize('binary,fragmented',[(False,False),(True,False),(False,True),(True,True)])
|
||||
def test_oversized_messages_are_never_delivered(binary,fragmented):
|
||||
async def scenario(port,delivered,gate,server):
|
||||
async with connect(f'ws://127.0.0.1:{port}',compression=None,proxy=None) as ws:
|
||||
value=bytes(9602) if binary else 'é'*2049
|
||||
await ws.send([value[:len(value)//2],value[len(value)//2:]] if fragmented else value)
|
||||
with pytest.raises(ConnectionClosed) as exc:await ws.recv()
|
||||
assert exc.value.rcvd.code==1009 and not delivered
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
@pytest.mark.parametrize('opcode,size,code',[(2,9601,1009),(1,4097,1009),(0x42,100,1002)])
|
||||
def test_header_only_rejection_precedes_payload_allocation(opcode,size,code):
|
||||
async def scenario(port,delivered,gate,server):
|
||||
reader,writer=await asyncio.open_connection('127.0.0.1',port)
|
||||
try:
|
||||
key=base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Extensions: permessage-deflate\r\n\r\n').encode());await writer.drain()
|
||||
response=await reader.readuntil(b'\r\n\r\n')
|
||||
assert b'101 Switching Protocols' in response
|
||||
assert b'sec-websocket-extensions' not in response.lower()
|
||||
# No mask or payload is sent: rejection must occur from declared length/RSV alone.
|
||||
writer.write(bytes([0x80|opcode,0x80|126])+struct.pack('!H',size));await writer.drain()
|
||||
head=await asyncio.wait_for(reader.readexactly(2),1)
|
||||
assert head[0]==0x88
|
||||
payload=await reader.readexactly(head[1]&127)
|
||||
assert struct.unpack('!H',payload[:2])[0]==code and not delivered
|
||||
finally:writer.close();await writer.wait_closed()
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_installed_backend_queue_is_bounded_and_compression_not_negotiated():
|
||||
async def scenario(port,delivered,gate,server):
|
||||
async with connect(f'ws://127.0.0.1:{port}',compression='deflate',proxy=None) as ws:
|
||||
assert not ws.protocol.extensions
|
||||
await ws.send(b'first');await ws.recv()
|
||||
gate.clear()
|
||||
# One ASGI receive may already be waiting; the remainder must backpressure.
|
||||
for _ in range(30):await ws.send(bytes(9600))
|
||||
await asyncio.sleep(.05)
|
||||
protocol=next(iter(server.server_state.connections))
|
||||
assert protocol.max_queue==8 and len(protocol.messages)<=8
|
||||
assert protocol.max_size==9600 and not protocol.extensions
|
||||
gate.set()
|
||||
for _ in range(30):assert await asyncio.wait_for(ws.recv(),2)=='accepted'
|
||||
assert len(delivered)==31
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_bounded_fragment_reassembly_long_empty_and_tiny_sequences():
|
||||
async def scenario(port, delivered, gate, server):
|
||||
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
|
||||
# 20,001 empty continuation frames reassembled without unbounded metadata growth
|
||||
empty_chunks = [b''] * 20001
|
||||
await ws.send(empty_chunks)
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert delivered[-1]['bytes'] == b''
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.assembling_scratch is None
|
||||
|
||||
# Tiny fragment sequence exact boundary: 96 fragments of 100 bytes = 9600 bytes binary
|
||||
binary_chunks = [b'x' * 100] * 96
|
||||
await ws.send(binary_chunks)
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert delivered[-1]['bytes'] == b'x' * 9600
|
||||
assert conn.assembling_scratch is None
|
||||
|
||||
# Tiny fragment sequence exact boundary: 64 fragments of 64 bytes = 4096 bytes UTF-8
|
||||
text_chunks = ['a' * 64] * 64
|
||||
await ws.send(text_chunks)
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert delivered[-1]['text'] == 'a' * 4096
|
||||
assert conn.assembling_scratch is None
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_interleaved_protocol_controls_during_fragmentation():
|
||||
async def scenario(port, delivered, gate, server):
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\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 reader.readuntil(b'\r\n\r\n')
|
||||
|
||||
# Send fragment 1 (opcode 2, fin=0, data=b'first ')
|
||||
writer.write(bytes([0x02, 0x80 | 6, 0, 0, 0, 0]) + b'first ')
|
||||
await writer.drain()
|
||||
await asyncio.sleep(0.01)
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.assembling_scratch == bytearray(b'first ')
|
||||
|
||||
# Client sends Ping control frame (opcode 9)
|
||||
writer.write(bytes([0x89, 0x80 | 4, 0, 0, 0, 0]) + b'ping')
|
||||
await writer.drain()
|
||||
|
||||
# Client receives Pong control frame (opcode 10)
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x8A
|
||||
pong_len = head[1] & 127
|
||||
assert await reader.readexactly(pong_len) == b'ping'
|
||||
|
||||
# Send fragment 2 (opcode 0, fin=1, data=b'second')
|
||||
writer.write(bytes([0x80, 0x80 | 6, 0, 0, 0, 0]) + b'second')
|
||||
await writer.drain()
|
||||
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x81
|
||||
reply = await reader.readexactly(head[1] & 127)
|
||||
assert reply == b'accepted'
|
||||
assert delivered[-1]['bytes'] == b'first second'
|
||||
assert conn.assembling_scratch is None
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_malformed_fragmentation_sequences_and_resource_cleanup():
|
||||
async def scenario(port, delivered, gate, server):
|
||||
# 1. Unexpected continuation (opcode 0 without starting frame) -> 1002
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
await reader.readuntil(b'\r\n\r\n')
|
||||
writer.write(bytes([0x80, 0x80 | 4, 0, 0, 0, 0]) + b'cont')
|
||||
await writer.drain()
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x88
|
||||
payload = await reader.readexactly(head[1] & 127)
|
||||
assert struct.unpack('!H', payload[:2])[0] == 1002 and not delivered
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
# 2. Interleaved data frame during fragmentation -> 1002
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
await reader.readuntil(b'\r\n\r\n')
|
||||
writer.write(bytes([0x02, 0x80 | 4, 0, 0, 0, 0]) + b'part')
|
||||
await writer.drain()
|
||||
await asyncio.sleep(0.01)
|
||||
writer.write(bytes([0x81, 0x80 | 4, 0, 0, 0, 0]) + b'text')
|
||||
await writer.drain()
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x88
|
||||
payload = await reader.readexactly(head[1] & 127)
|
||||
assert struct.unpack('!H', payload[:2])[0] == 1002
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
# 3. Unfinished message: client disconnect releases scratch resources
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
await reader.readuntil(b'\r\n\r\n')
|
||||
writer.write(bytes([0x02, 0x80 | 4, 0, 0, 0, 0]) + b'frag')
|
||||
await writer.drain()
|
||||
await asyncio.sleep(0.01)
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.assembling_scratch is not None
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
await asyncio.sleep(0.05)
|
||||
assert conn.assembling_scratch is None
|
||||
asyncio.run(serve(scenario))
|
||||
|
||||
def test_lower_trusted_runtime_limits_and_prepayload_rejection():
|
||||
settings = RuntimeSettings(
|
||||
max_binary_message_bytes=1200,
|
||||
max_client_control_bytes=500,
|
||||
output_credit_window_bytes=1200,
|
||||
max_queued_audio_bytes=2400,
|
||||
max_queued_audio_messages=10,
|
||||
)
|
||||
async def scenario(port, delivered, gate, server):
|
||||
# 1. Header-only pre-payload rejection on lowered binary limit (1201 > 1200) and text limit (501 > 500)
|
||||
for opcode, size in [(2, 1201), (1, 501)]:
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain()
|
||||
await reader.readuntil(b'\r\n\r\n')
|
||||
# Header only: no mask, no payload
|
||||
writer.write(bytes([0x80 | opcode, 0x80 | 126]) + struct.pack('!H', size))
|
||||
await writer.drain()
|
||||
head = await asyncio.wait_for(reader.readexactly(2), 2)
|
||||
assert head[0] == 0x88
|
||||
payload = await reader.readexactly(head[1] & 127)
|
||||
assert struct.unpack('!H', payload[:2])[0] == 1009 and not delivered
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
|
||||
# 2. Exact lower limits (1200 binary and 500 text) are accepted
|
||||
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
|
||||
await ws.send(bytes(1200))
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert len(delivered[-1]['bytes']) == 1200
|
||||
await ws.send('c' * 500)
|
||||
assert await ws.recv() == 'accepted'
|
||||
assert delivered[-1]['text'] == 'c' * 500
|
||||
asyncio.run(serve(scenario, settings=settings))
|
||||
|
||||
def test_small_message_budgets_one_and_two_deadlock_free():
|
||||
# Message budget of 1
|
||||
settings_1 = RuntimeSettings(
|
||||
max_binary_message_bytes=1200,
|
||||
max_client_control_bytes=500,
|
||||
output_credit_window_bytes=1200,
|
||||
max_queued_audio_bytes=2400,
|
||||
max_queued_audio_messages=1,
|
||||
)
|
||||
async def scenario_1(port, delivered, gate, server):
|
||||
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.max_queued_audio_messages == 1
|
||||
assert conn.max_queue == 1
|
||||
|
||||
await ws.send(b'm1')
|
||||
assert await ws.recv() == 'accepted'
|
||||
|
||||
gate.clear()
|
||||
await ws.send(b'm2')
|
||||
await asyncio.sleep(0.02)
|
||||
assert conn.in_flight_message == b'm2'
|
||||
|
||||
await ws.send(b'm3')
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(conn.messages) == 0
|
||||
|
||||
gate.set()
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert len(delivered) == 3
|
||||
asyncio.run(serve(scenario_1, settings=settings_1))
|
||||
|
||||
# Message budget of 2 and audio byte capacity bound
|
||||
settings_2 = RuntimeSettings(
|
||||
max_binary_message_bytes=1200,
|
||||
max_client_control_bytes=500,
|
||||
output_credit_window_bytes=1200,
|
||||
max_queued_audio_bytes=2400,
|
||||
max_queued_audio_messages=2,
|
||||
)
|
||||
async def scenario_2(port, delivered, gate, server):
|
||||
async with connect(f'ws://127.0.0.1:{port}', compression=None, proxy=None) as ws:
|
||||
conn = next(iter(server.server_state.connections))
|
||||
assert conn.max_queued_audio_messages == 2
|
||||
|
||||
await ws.send(b'm1')
|
||||
assert await ws.recv() == 'accepted'
|
||||
|
||||
gate.clear()
|
||||
await ws.send(b'm2')
|
||||
await asyncio.sleep(0.02)
|
||||
assert conn.in_flight_message == b'm2'
|
||||
|
||||
await ws.send(b'm3')
|
||||
await asyncio.sleep(0.02)
|
||||
assert len(conn.messages) == 1
|
||||
|
||||
# m4 exceeds total message capacity (1 in-flight + 1 queued = 2)
|
||||
await ws.send(b'm4')
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(conn.messages) == 1
|
||||
|
||||
gate.set()
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert await asyncio.wait_for(ws.recv(), 2.0) == 'accepted'
|
||||
assert len(delivered) == 4
|
||||
asyncio.run(serve(scenario_2, settings=settings_2))
|
||||
|
||||
|
||||
def test_capacity_failure_terminates_receive_with_nonresponsive_peer():
|
||||
"""Protocol failure cancels the capacity waiter without another cancellation."""
|
||||
async def scenario(port, delivered, gate, server):
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain(); await reader.readuntil(b'\r\n\r\n')
|
||||
gate.clear()
|
||||
# ASGI retains one delivered message; queued messages fill the rest.
|
||||
writer.write((b'\x82\x81\x00\x00\x00\x00x') * 30)
|
||||
await writer.drain()
|
||||
conn = next(iter(server.server_state.connections))
|
||||
async with asyncio.timeout(1):
|
||||
while conn.has_capacity(): await asyncio.sleep(.001)
|
||||
assert not conn.transfer_data_task.done()
|
||||
conn.close_timeout = .05
|
||||
conn.fail_connection(1008)
|
||||
# Shield ensures the assertion's timeout cannot perform a second cancel.
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(asyncio.shield(conn.transfer_data_task), .3)
|
||||
await asyncio.wait_for(asyncio.shield(conn.close_connection_task), 1)
|
||||
assert conn.transport.is_closing()
|
||||
assert conn.assembling_scratch is None and conn.in_flight_message is None
|
||||
finally:
|
||||
writer.close(); await writer.wait_closed()
|
||||
asyncio.run(serve(scenario, settings=RuntimeSettings(max_queued_audio_messages=1)))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fragmented', [False, True])
|
||||
def test_invalid_utf8_retains_standard_1007_rejection(fragmented):
|
||||
async def scenario(port, delivered, gate, server):
|
||||
reader, writer = await asyncio.open_connection('127.0.0.1', port)
|
||||
try:
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
writer.write((f'GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n').encode())
|
||||
await writer.drain(); await reader.readuntil(b'\r\n\r\n')
|
||||
wire = 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(wire); await writer.drain()
|
||||
header = await asyncio.wait_for(reader.readexactly(2), 1)
|
||||
payload = await reader.readexactly(header[1] & 127)
|
||||
assert header[0] == 0x88 and struct.unpack('!H', payload[:2])[0] == 1007
|
||||
assert not delivered
|
||||
finally:
|
||||
writer.close(); await writer.wait_closed()
|
||||
asyncio.run(serve(scenario))
|
||||
Reference in New Issue
Block a user