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