Files
rag-technical-docs-assistant/tests/integration/test_realtime_phase3_http.py
T
11linear11 a73a496c54 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.
2026-10-09 17:43:52 -04:00

516 lines
35 KiB
Python

"""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])