from __future__ import annotations import os from dataclasses import dataclass from typing import Any, Dict AUTO_MINUS_FOUR = "auto-minus-4" @dataclass(frozen=True) class ThreadAllocation: policy: str system_threads: int reserve_threads: int threads_used: int def detect_system_threads() -> int: return max(1, int(os.cpu_count() or 1)) def resolve_threads_used( configured_value: Any, *, reserve_threads: int = 4, system_threads: int | None = None, ) -> ThreadAllocation: total = max(1, int(system_threads or detect_system_threads())) reserve = max(0, int(reserve_threads)) policy_raw = configured_value if configured_value is not None else AUTO_MINUS_FOUR policy = str(policy_raw).strip().lower() if policy in {"", "auto", AUTO_MINUS_FOUR}: used = max(1, total - reserve) return ThreadAllocation( policy=AUTO_MINUS_FOUR, system_threads=total, reserve_threads=reserve, threads_used=used, ) try: used = max(1, int(policy_raw)) except (TypeError, ValueError) as exc: raise ValueError( f"Invalid backend.parallel_jobs value `{configured_value}`. Use integer or `{AUTO_MINUS_FOUR}`." ) from exc return ThreadAllocation( policy="fixed", system_threads=total, reserve_threads=reserve, threads_used=min(total, used), ) def enforce_thread_fairness(config: Dict[str, Any], *, reserve_threads: int = 4) -> ThreadAllocation: backend = config.setdefault("backend", {}) configured = backend.get("parallel_jobs", AUTO_MINUS_FOUR) alloc = resolve_threads_used(configured, reserve_threads=reserve_threads) backend["parallel_jobs"] = int(alloc.threads_used) backend["thread_policy"] = alloc.policy runtime = config.setdefault("runtime", {}) runtime["system_threads"] = int(alloc.system_threads) runtime["reserve_threads"] = int(alloc.reserve_threads) runtime["threads_used"] = int(alloc.threads_used) runtime["thread_policy"] = alloc.policy runtime["thread_formula"] = "threads_used = max(1, system_threads - 4)" return alloc