"""Two admitted JSON requests; large decoding/validation has a separate GIL. Only backend-chosen DTO classes enter the child. Its bounded pickle frames are trusted local results, never client pickle input. Admission outlives cancellation until the owner has joined disk I/O, reaped its child and removed its spool. """ import asyncio import importlib import json import pickle from pathlib import Path import struct import sys from threading import BoundedSemaphore JSON_SLOTS = BoundedSemaphore(2) INLINE_BYTES = 64 * 1024 FRAME_BYTES = 256 * 1024 async def owned_io(function, *args): """A cancelled owner must join a write before closing/deleting its file.""" task = asyncio.get_running_loop().run_in_executor(None, function, *args) try: return await asyncio.shield(task) except asyncio.CancelledError: while not task.done(): try: await asyncio.shield(task) except asyncio.CancelledError: continue task.result() raise def validate_json(body, model_cls): try: return model_cls.model_validate(json.loads(body.decode('utf-8'))) except (ValueError, UnicodeError, RecursionError): raise ValueError('VALIDATION_ERROR') from None async def validate_spool(path, model_cls): # No large process-pool argument/result pickling in the API process: input is # spooled, and validated flat DTO fields return in bounded batches. spawning = asyncio.create_task(asyncio.create_subprocess_exec( sys.executable, '-m', 'app.infrastructure.json_processing', model_cls.__module__, model_cls.__name__, str(path), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, limit=FRAME_BYTES, )) try: child = await asyncio.shield(spawning) except OSError: raise ValueError('DEPENDENCY_UNAVAILABLE') from None except asyncio.CancelledError: # Cancellation during process creation still owns the eventual child. while not spawning.done(): try: await asyncio.shield(spawning) except asyncio.CancelledError: continue child = spawning.result() if child.returncode is None: child.kill() reap = asyncio.create_task(child.wait()) while not reap.done(): try: await asyncio.shield(reap) except asyncio.CancelledError: continue reap.result() raise values, kinds, fields_set = {}, {}, None try: while True: length = struct.unpack('!I', await child.stdout.readexactly(4))[0] if length > FRAME_BYTES: raise ValueError('DEPENDENCY_UNAVAILABLE') name, kind, value = pickle.loads(await child.stdout.readexactly(length)) if name is None: if value is None: raise ValueError('VALIDATION_ERROR') fields_set = value break if kind == 0: values[name] = value else: values.setdefault(name, []).extend(value) kinds[name] = kind await asyncio.sleep(0) if await child.wait() != 0: raise ValueError('DEPENDENCY_UNAVAILABLE') for name, kind in kinds.items(): if kind == 2: values[name] = tuple(values[name]) # These exact values and fields_set were validated in our child. Repeating # validation here would put the expensive work back on the API's loop. return model_cls.model_construct(_fields_set=fields_set, **values) except (asyncio.IncompleteReadError, OSError, pickle.UnpicklingError): raise ValueError('DEPENDENCY_UNAVAILABLE') from None finally: if child.returncode is None: child.kill() reap = asyncio.create_task(child.wait()) while not reap.done(): try: await asyncio.shield(reap) except asyncio.CancelledError: continue reap.result() def _send(record): payload = pickle.dumps(record, protocol=5) if len(payload) > FRAME_BYTES: raise ValueError('Validated DTO field exceeds internal frame bound') sys.stdout.buffer.write(struct.pack('!I', len(payload))) sys.stdout.buffer.write(payload) def _worker(module, name, path): model_cls = getattr(importlib.import_module(module), name) try: model = validate_json(Path(path).read_bytes(), model_cls) except ValueError: _send((None, 0, None)) return for field in model_cls.model_fields: value = getattr(model, field) if isinstance(value, (tuple, list)): kind = 2 if isinstance(value, tuple) else 1 # 64 supported 500-character identifiers fit well below FRAME_BYTES, # even as raw four-byte UTF-8 scalars. Empty arrays still carry type. for offset in range(0, max(1, len(value)), 64): _send((field, kind, value[offset:offset + 64])) else: _send((field, 0, value)) _send((None, 0, model.model_fields_set)) if __name__ == '__main__': _worker(*sys.argv[1:])