"""Parallel, memoized prompt-envelope preflight for the safety gate. ``_validate_prompt_envelope`` (in :mod:`backend`) is the safety gate that runs *before* a trainer can touch a GPU: it decodes every row's images through the real processor and rejects any row whose prompt/SFT envelope exceeds the frozen token budget. On the EVI-core-v2 matrix that is ~46k rows decoded serially per launch — several minutes of GPU-idle time that the lazy image loader does not reach (it is a separate code path from dataset materialization). This module keeps the gate *bit-identical* while removing the stall two ways: 1. **Parallelize.** The per-row check is independent, so a **thread** pool validates the rows concurrently. The per-row work (image decode, rust tokenization, torch image preprocessing) releases the GIL, so threads give real parallelism; and threads share the process, so they cannot deadlock on the torch/tokenizer locks the model-loaded parent already holds. (A fork process pool deadlocked here in practice — fork is unsafe once the VLM processor/model is loaded, even with CUDA still on CPU.) 2. **Memoize.** The verdict is keyed by the frozen dataset identity, arm, processor revision, limits, and row count. The release builder establishes that identity once; repeat launches do not serialize and hash all 46K prepared rows merely to decide whether a cached verdict can be reused. Correctness guarantees: * The check body is the exact logic of the original serial loop; the lowest- index failure is raised with the identical ``row {index} ...`` message. * On *any* pool infrastructure failure the gate falls back to the original serial scan, so the gate can never be weakened by a threading fault. * The cache key binds the frozen data identity/path, arm, row count, pinned model revision, token limits, SFT flag, and a schema version. A logic change bumps the schema version. This intentionally trusts the already-built release instead of replaying content authentication during training. """ from __future__ import annotations import copy import os import warnings from collections.abc import Mapping, Sequence from pathlib import Path from typing import Any from ..hashing import canonical_json_hash # Bump when the validation logic in ``_validate_one_row`` changes so a stale # verdict marker can never mask a logic change. PREFLIGHT_SCHEMA_VERSION = 3 def _validate_one_row( row: Mapping[str, Any], processor: Any, *, sft: bool, max_prompt_tokens: int, total_context_tokens: int, ) -> None: """Validate a single row's prompt/SFT envelope. Raises ``BackendContractError`` (detail without a row index) on any violation. The row index is attached by the caller so the lowest-index failure can be reported, matching the original serial loop's messages. """ from .backend import BackendContractError, _input_length raw_paths = row.get("image_paths") if not isinstance(raw_paths, list) or not raw_paths: raise BackendContractError("has no images for token preflight") prompt = copy.deepcopy(list(row["prompt"])) path_iterator = iter(str(path) for path in raw_paths) for message in prompt: content = message.get("content") if not isinstance(content, list): continue for item in content: if isinstance(item, dict) and item.get("type") == "image": try: item["path"] = next(path_iterator) except StopIteration as exc: raise BackendContractError( "has fewer images than placeholders" ) from exc try: next(path_iterator) except StopIteration: pass else: raise BackendContractError("has more images than prompt placeholders") prompt_tokens = _input_length(processor, prompt) if prompt_tokens > max_prompt_tokens: raise BackendContractError( f"prompt has {prompt_tokens}>{max_prompt_tokens} tokens" ) if sft: full_messages = prompt + list(row["completion"]) total = _input_length(processor, full_messages) if total > total_context_tokens: raise BackendContractError( f"SFT sequence has {total}>{total_context_tokens} tokens" ) def _validate_chunk( rows: Sequence[Mapping[str, Any]], processor: Any, chunk: tuple[int, int, bool, int, int], ) -> list[tuple[int, str]]: """Validate rows ``[start, end)``. Returns ``(index, detail)`` pairs for every violation in the chunk so the caller can raise the lowest-index failure with the serial loop's message. ``rows``/``processor`` are passed explicitly (not via module globals) so the worker is a pure function of its arguments. """ from .backend import BackendContractError start, end, sft, max_prompt_tokens, total_context_tokens = chunk errors: list[tuple[int, str]] = [] for index in range(start, end): try: _validate_one_row( rows[index], processor, sft=sft, max_prompt_tokens=max_prompt_tokens, total_context_tokens=total_context_tokens, ) except BackendContractError as exc: errors.append((index, str(exc))) return errors def _worker_count() -> int: env = os.environ.get("EXPLICIT_PREFLIGHT_WORKERS") if env and env.strip(): try: return max(1, int(env)) except ValueError: pass return min(os.cpu_count() or 8, 16) def validate_prompt_envelope_parallel( rows: Sequence[Mapping[str, Any]], processor: Any, *, sft: bool, max_prompt_tokens: int, total_context_tokens: int, ) -> None: """Validate every row, raising the lowest-index violation. Parallelized with a **thread** pool, not a process pool. The per-row work (image decode, rust tokenization, torch image preprocessing) releases the GIL, so threads give real parallelism here — and unlike a fork pool they share the process, so they cannot deadlock on the torch/tokenizer locks the model-loaded parent already holds. (A fork pool deadlocked here in practice; fork is unsafe once the VLM processor/model is loaded.) Torch's own thread pool is pinned to a single thread so the thread pool below is the only parallelism layer. Falls back to the serial scan on any pool fault so the gate is never weakened. """ from .backend import BackendContractError if not rows: return workers = _worker_count() count = len(rows) # ~8 chunks per worker for load balancing; rows are cheap to split. chunks_per_worker = 8 chunk_size = max(1, count // (workers * chunks_per_worker)) chunks: list[tuple[int, int, bool, int, int]] = [] for start in range(0, count, chunk_size): chunks.append( (start, min(start + chunk_size, count), sft, max_prompt_tokens, total_context_tokens) ) prior_intra = os.environ.get("TORCH_NUM_THREADS") prior_inter = os.environ.get("TORCH_NUM_INTRAOP_THREADS") os.environ["TORCH_NUM_THREADS"] = "1" os.environ["TORCH_NUM_INTRAOP_THREADS"] = "1" try: import torch torch.set_num_threads(1) except Exception: # noqa: BLE001 - torch optional at import time pass try: from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(max_workers=min(workers, len(chunks))) as pool: collected = list( pool.map( lambda chunk: _validate_chunk(rows, processor, chunk), chunks, ) ) except BackendContractError: raise except Exception as exc: # noqa: BLE001 - any pool fault falls back to serial warnings.warn( f"preflight parallel pool failed ({exc!r}); falling back to serial scan", stacklevel=2, ) _validate_prompt_envelope_serial( rows, processor, sft=sft, max_prompt_tokens=max_prompt_tokens, total_context_tokens=total_context_tokens, ) return finally: if prior_intra is None: os.environ.pop("TORCH_NUM_INTRAOP_THREADS", None) else: os.environ["TORCH_NUM_INTRAOP_THREADS"] = prior_intra if prior_inter is None: os.environ.pop("TORCH_NUM_THREADS", None) else: os.environ["TORCH_NUM_THREADS"] = prior_inter errors = [pair for batch in collected for pair in batch] if errors: index, detail = min(errors, key=lambda pair: pair[0]) raise BackendContractError(f"row {index} {detail}") def _validate_prompt_envelope_serial( rows: Sequence[Mapping[str, Any]], processor: Any, *, sft: bool, max_prompt_tokens: int, total_context_tokens: int, ) -> None: """The original serial scan — the bit-identical source of truth / fallback.""" from .backend import BackendContractError, _input_length for index, row in enumerate(rows): raw_paths = row.get("image_paths") if not isinstance(raw_paths, list) or not raw_paths: raise BackendContractError(f"row {index} has no images for token preflight") prompt = copy.deepcopy(list(row["prompt"])) path_iterator = iter(str(path) for path in raw_paths) for message in prompt: content = message.get("content") if not isinstance(content, list): continue for item in content: if isinstance(item, dict) and item.get("type") == "image": try: item["path"] = next(path_iterator) except StopIteration as exc: raise BackendContractError( f"row {index} has fewer images than placeholders" ) from exc try: next(path_iterator) except StopIteration: pass else: raise BackendContractError( f"row {index} has more images than prompt placeholders" ) prompt_tokens = _input_length(processor, prompt) if prompt_tokens > max_prompt_tokens: raise BackendContractError( f"row {index} prompt has {prompt_tokens}>{max_prompt_tokens} tokens" ) if sft: full_messages = prompt + list(row["completion"]) total = _input_length(processor, full_messages) if total > total_context_tokens: raise BackendContractError( f"row {index} SFT sequence has {total}>{total_context_tokens} tokens" ) def preflight_cache_key( runtime: Mapping[str, Any], rows: Sequence[Mapping[str, Any]], *, sft: bool, max_prompt_tokens: int, total_context_tokens: int, ) -> str: """Build a cheap cache key from frozen identities, never row contents.""" return canonical_json_hash( { "schema_version": PREFLIGHT_SCHEMA_VERSION, "sft": sft, "max_prompt_tokens": max_prompt_tokens, "total_context_tokens": total_context_tokens, "model_revision": runtime.get("model_revision"), "model_snapshot_sha256": runtime.get("model_snapshot_sha256"), "dataset_path": runtime.get("dataset_path"), "dataset_manifest_sha256": ( runtime.get("_launch_manifest", {}).get("dataset_manifest_sha256") if isinstance(runtime.get("_launch_manifest"), Mapping) else None ), "comparison_slot_manifest_sha256": runtime.get( "comparison_slot_manifest_sha256" ), "arm": runtime.get("arm"), "record_count": len(rows), } ) def _preflight_cache_dir() -> Path | None: explicit = os.environ.get("EXPLICIT_PREFLIGHT_CACHE_DIR", "").strip() if explicit: return Path(explicit) cache_root = os.environ.get("EXPLICIT_CACHE_ROOT", "").strip() if cache_root: return Path(cache_root) / "preflight-verdicts" return None def _read_marker(path: Path, expected_key: str, record_count: int) -> bool: """True iff ``path`` holds a valid verdict marker for this key/count.""" if not path.is_file(): return False try: import json with path.open("r", encoding="utf-8") as handle: marker = json.load(handle) except (OSError, ValueError): return False return ( isinstance(marker, Mapping) and marker.get("schema_version") == PREFLIGHT_SCHEMA_VERSION and marker.get("key") == expected_key and marker.get("record_count") == record_count ) def run_preflight( runtime: Mapping[str, Any], rows: Sequence[Mapping[str, Any]], processor: Any, *, sft: bool, max_prompt_tokens: int, total_context_tokens: int, ) -> bool: """Run the prompt-envelope gate with verdict memoization. Returns ``True`` on a cache hit (validation skipped), ``False`` when the full validation was run (cache miss). Always raises ``BackendContractError`` on any violating row, hit or miss. """ key = preflight_cache_key( runtime, rows, sft=sft, max_prompt_tokens=max_prompt_tokens, total_context_tokens=total_context_tokens, ) record_count = len(rows) cache_dir = _preflight_cache_dir() marker_path = cache_dir / f"preflight-{key}.json" if cache_dir is not None else None if marker_path is not None and _read_marker(marker_path, key, record_count): return True validate_prompt_envelope_parallel( rows, processor, sft=sft, max_prompt_tokens=max_prompt_tokens, total_context_tokens=total_context_tokens, ) if marker_path is not None: from ..atomic_io import atomic_write_json marker_path.parent.mkdir(parents=True, exist_ok=True) atomic_write_json( marker_path, { "schema_version": PREFLIGHT_SCHEMA_VERSION, "key": key, "record_count": record_count, "sft": sft, "max_prompt_tokens": max_prompt_tokens, "total_context_tokens": total_context_tokens, "model_revision": runtime.get("model_revision"), "model_snapshot_sha256": runtime.get("model_snapshot_sha256"), "comparison_slot_manifest_sha256": runtime.get( "comparison_slot_manifest_sha256" ), }, ) return False