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,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())
|
||||
Reference in New Issue
Block a user