File size: 2,187 Bytes
504d922
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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