Skip to content

mamut_routing_tools.bks_campaign

BKS campaigns: many solver runs whose winners become BKS and whose losers are data.

mamut-tools bks-campaign plan|baseline|run|harvest|report|status SPEC, driven by a TOML spec (spec). The steps, as the Mamut2026 campaigns ran them by hand:

  1. baseline: freeze the stored BKS before anything runs;
  2. run: a resumable, memory-aware process pool; each run is checked and archived as runs/<key>.json (winner or not), never written as a BKS;
  3. harvest: the single writer -- each instance's best run, unless clearly worse than the baseline, goes through the BKS store (exact costs: strictly better only, ties kept);
  4. report: ledger.csv and cross-solver.csv.

Distinct from mamut_routing_tools.campaign, which designs benchmark instances.

Task dataclass

Task(
    key: str,
    campaign: str,
    out: str,
    instance_id: str,
    instance_name: str,
    instance_path: str,
    num_customers: int,
    problem_type: str,
    objective: str,
    kind: str,
    solver: str,
    seed: int,
    time_limit_s: int,
    memory_gb: float,
    solvers_config: str | None = None,
    options: dict[str, Any] = dict(),
    warm_start: str = "none",
    nice: int | None = None,
)

group property

group: tuple[str, str]

What a warm start waits for: the other runs of this instance and objective.

harvest_history

harvest_history(out: Path) -> list[dict[str, Any]]

Every recorded harvest, oldest first: {"harvested": time, "results": [...]}.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/harvest.py
def harvest_history(out: Path) -> list[dict[str, Any]]:
    """Every recorded harvest, oldest first: ``{"harvested": time, "results": [...]}``."""
    history = sorted((out / "harvests").glob("[0-9][0-9][0-9][0-9]-*.json"))
    if history:
        return [json.loads(path.read_text(encoding="utf-8")) for path in history]
    latest = out / "harvest.json"  # a campaign harvested before the history existed
    if latest.is_file():
        return [{"harvested": None, "results": json.loads(latest.read_text(encoding="utf-8"))}]
    return []

write_baseline

write_baseline(
    spec: CampaignSpec, *, force: bool = False
) -> Path

Snapshot the stored BKS of the selected instances into baseline.csv.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/harvest.py
def write_baseline(spec: CampaignSpec, *, force: bool = False) -> Path:
    """Snapshot the stored BKS of the selected instances into ``baseline.csv``."""
    from mamut_routing_lib.artifacts import get_bks_path_for_instance, load_benchmark_instance, load_bks
    from mamut_routing_lib.objectives import base_objective
    from mamut_routing_lib.solvers.provenance import file_sha256

    from mamut_routing_tools.bks_campaign.plan import select_instances

    path = spec.out / "baseline.csv"
    if path.exists() and not force:
        raise FileExistsError(f"{path} exists: the baseline must predate the campaign (pass --force to replace it)")
    rows = []
    recorded = datetime.now(UTC).isoformat(timespec="seconds")
    for item in select_instances(spec):
        instance = load_benchmark_instance(item.instance_path)
        objective = spec.select.objective.get(item.problem_type) or base_objective(instance)
        bks_path = get_bks_path_for_instance(item.instance_path, objective)
        row = {
            "instance_id": item.instance_id,
            "objective_function": objective.value,
            "cost": "",
            "num_routes": "",
            "method": "",
            "bks_sha256": "",
            "bks_path": str(bks_path),
            "recorded": recorded,
        }
        if bks_path.is_file():
            bks = load_bks(bks_path)
            row.update(cost=bks.cost, num_routes=bks.num_routes, method=bks.metadata.get("method") or "", bks_sha256=file_sha256(bks_path))
        rows.append(row)
    spec.out.mkdir(parents=True, exist_ok=True)
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=BASELINE_FIELDS)
        writer.writeheader()
        writer.writerows(rows)
    return path

write_reports

write_reports(spec: CampaignSpec) -> tuple[Path, Path]

ledger.csv (one row per run) and cross-solver.csv (per instance and objective).

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/harvest.py
def write_reports(spec: CampaignSpec) -> tuple[Path, Path]:
    """``ledger.csv`` (one row per run) and ``cross-solver.csv`` (per instance and objective)."""
    from mamut_routing_lib.solvers.report import solver_report_metadata

    spec.out.mkdir(parents=True, exist_ok=True)  # before any `run`: empty reports, not a traceback
    runs = load_runs(spec.out)
    current, _stale = _current_runs(runs)
    baseline = read_baseline(spec.out)
    harvested = _harvested_actions(spec.out)
    best = {group: record["key"] for group, record in _best_runs(current).items()}

    ledger = spec.out / "ledger.csv"
    with ledger.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=LEDGER_FIELDS, extrasaction="ignore")
        writer.writeheader()
        for record in sorted(runs, key=lambda item: (item.get("instance_id", ""), item.get("kind", ""), item.get("seed", 0))):
            group = (record.get("instance_id"), record.get("objective_function"))
            reference = baseline.get(group, {}).get("cost")
            cost = record.get("validated_cost")
            gap = None
            if cost is not None and reference not in (None, ""):
                gap = round(100.0 * (float(cost) - float(reference)) / float(reference), 4) if float(reference) else None
            writer.writerow({
                **record,
                "solver_cost": solver_report_metadata(record.get("solver_report")).get("solver_cost"),
                "baseline_cost": reference,
                "vs_baseline_pct": gap,
                "is_best": best.get(group) == record.get("key"),
                "bks_action": harvested.get(record.get("key"), ("", None))[0],
                "bks_action_at": harvested.get(record.get("key"), ("", None))[1] or "",
            })

    groups: dict[tuple[str, str], list[dict[str, Any]]] = {}
    for record in current:  # runs of an instance file that changed since are not compared
        groups.setdefault((record.get("instance_id"), record.get("objective_function")), []).append(record)
    kinds = sorted({record.get("kind") for record in runs if record.get("kind")})
    compare = spec.out / "cross-solver.csv"
    fields = ["instance_id", "objective_function", "baseline_cost", "overall_best", "winner"]
    for kind in kinds:
        fields += [f"{kind}_best", f"{kind}_routes", f"{kind}_gap_pct", f"{kind}_spread_pct", f"{kind}_valid_runs"]
    with compare.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields)
        writer.writeheader()
        for group, records in sorted(groups.items()):
            valid = [record for record in records if record.get("valid") and archived_cost(record) is not None]
            overall = min(valid, key=_objective_key, default=None)
            row: dict[str, Any] = {
                "instance_id": group[0],
                "objective_function": group[1],
                "baseline_cost": baseline.get(group, {}).get("cost"),
                "overall_best": overall["validated_cost"] if overall else None,
                "winner": overall["kind"] if overall else None,
            }
            for kind in kinds:
                kind_runs = [record for record in valid if record.get("kind") == kind]
                if not kind_runs:
                    row[f"{kind}_valid_runs"] = 0
                    continue
                costs = [record["validated_cost"] for record in kind_runs if record["validated_cost"] is not None]
                kind_best_run = min(kind_runs, key=_objective_key)
                kind_best = kind_best_run["validated_cost"]
                row[f"{kind}_best"] = kind_best
                row[f"{kind}_routes"] = kind_best_run.get("num_routes")
                row[f"{kind}_gap_pct"] = round(100.0 * (kind_best - float(overall["validated_cost"])) / float(overall["validated_cost"]), 4) if overall and overall["validated_cost"] and kind_best is not None else None
                row[f"{kind}_spread_pct"] = round(100.0 * (max(costs) - kind_best) / kind_best, 4) if costs and kind_best else None
                row[f"{kind}_valid_runs"] = len(kind_runs)
            writer.writerow(row)
    return ledger, compare

build_plan

build_plan(
    spec: CampaignSpec,
    *,
    only: str | None = None,
    retry_failed: bool = False,
) -> CampaignPlan

Expand the spec into tasks, skipping done runs and unsupported (instance, solver) pairs.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/plan.py
def build_plan(spec: CampaignSpec, *, only: str | None = None, retry_failed: bool = False) -> CampaignPlan:
    """Expand the spec into tasks, skipping done runs and unsupported (instance, solver) pairs."""
    from mamut_routing_lib.artifacts import load_benchmark_instance
    from mamut_routing_lib.objectives import base_objective
    from mamut_routing_lib.solvers import get_solver, profile_instance
    from mamut_routing_lib.solvers.provenance import file_sha256

    only_pattern = re.compile(only) if only else None
    config = str(spec.campaign.solvers_config) if spec.campaign.solvers_config else None
    solvers = {}
    unavailable: dict[str, str] = {}
    for run in spec.runs:
        if run.solver in solvers or run.solver in unavailable:
            continue
        solver = get_solver(run.solver, config=config)
        availability = solver.availability()
        if not availability.available:
            unavailable[run.solver] = availability.describe()
            continue
        if run.warm_start == "best" and not solver.capabilities.warm_start:
            raise ValueError(f"[[runs]] {run.run_kind}: {run.solver} does not take warm starts")
        solvers[run.solver] = solver

    tasks: list[Task] = []
    done: list[str] = []
    retried: list[str] = []
    stale: list[str] = []
    planned: set[str] = set()
    unsupported: list[tuple[str, str, str]] = []
    archive: ArchiveIndex | None = None  # read once, on the first warm start
    for item in select_instances(spec):
        if only_pattern and not (only_pattern.search(item.instance_id) or only_pattern.search(item.instance_name)):
            continue
        instance = load_benchmark_instance(item.instance_path)
        problem = getattr(item.problem_type, "value", str(item.problem_type))
        objective = spec.select.objective.get(item.problem_type) or base_objective(instance)
        profile = profile_instance(instance, item.instance_path)
        n = int(instance.num_customers)
        current_sha = file_sha256(item.instance_path)
        cold_planned = False  # a run of this instance is still to do: a warm start can wait for it
        # Cold entries first, whatever their order in the spec: a warm start needs to know of them.
        for run in sorted(spec.runs, key=lambda entry: entry.warm_start == "best"):
            solver = solvers.get(run.solver)
            if solver is None:
                continue
            support = solver.supports(profile, objective)
            if not support.supported:
                unsupported.append((item.instance_id, run.solver, "; ".join(support.reasons)))
                continue
            budget = spec.budget.seconds(n, run.budget_factor)
            if run.warm_start == "best" and not cold_planned:
                # Nothing of this instance will run first: there must be something to start from already.
                if archive is None:
                    archive = _valid_runs_by_group(spec)
                known, _ = best_known_routes(
                    spec.out, item.instance_path, item.instance_id, objective, current_sha, archive=archive
                )
                if known is None:
                    unsupported.append(
                        (item.instance_id, run.solver, "warm_start = best but no archived run, stored BKS or planned run to start from")
                    )
                    continue
            for seed in run.seed_list():
                key = run_key(item.instance_id, objective.value, run.run_kind, seed, budget)
                if key in planned:  # the same run listed twice would share its raw directory
                    continue
                planned.add(key)
                record_path = run_path(spec.out, key)
                if record_path.is_file():
                    record = _read_record(record_path)
                    if record.get("instance_sha256") not in (None, current_sha):
                        stale.append(key)  # a run of an older instance file: run it again
                    elif retry_failed and _failed(record):
                        retried.append(key)
                    else:
                        done.append(key)
                        continue
                tasks.append(
                    Task(
                        key=key,
                        campaign=spec.campaign.name,
                        out=str(spec.out),
                        instance_id=item.instance_id,
                        instance_name=item.instance_name,
                        instance_path=str(item.instance_path),
                        num_customers=n,
                        problem_type=problem,
                        objective=objective.value,
                        kind=run.run_kind,
                        solver=run.solver,
                        seed=seed,
                        time_limit_s=budget,
                        memory_gb=run.memory_gb if run.memory_gb is not None else default_memory_gb(run.solver, n),
                        solvers_config=config,
                        options=dict(run.options),
                        warm_start=run.warm_start,
                        nice=spec.resources.nice,
                    )
                )
                cold_planned = cold_planned or run.warm_start != "best"
    # Warm starts last (they start from the other runs' results); longest budgets first within each.
    tasks.sort(key=lambda task: (task.warm_start == "best", -task.time_limit_s, task.key))
    return CampaignPlan(
        tasks=tasks, done=done, unsupported=unsupported, unavailable=unavailable, retried=retried, stale=stale
    )

select_instances

select_instances(spec: CampaignSpec) -> list[Any]

The instances the spec selects (DiscoveredBenchmarkInstance), static and TD alike.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/plan.py
def select_instances(spec: CampaignSpec) -> list[Any]:
    """The instances the spec selects (``DiscoveredBenchmarkInstance``), static and TD alike."""
    from mamut_routing_lib.artifacts import discover_benchmark_instances

    select = spec.select
    found = discover_benchmark_instances(
        select.benchmarks_dir,
        problem_types=select.problem_types or None,
        benchmark_names=select.families or None,
        metric_variants=select.metrics or None,
        instance_ids=select.instance_ids or None,
    )
    pattern = re.compile(select.name_regex) if select.name_regex else None
    chosen = []
    for item in found:
        n = item.num_customers
        if n is None:
            n = int(item.load().num_customers)
        if select.min_n is not None and n < select.min_n:
            continue
        if select.max_n is not None and n > select.max_n:
            continue
        if pattern is not None and not (pattern.search(item.instance_name) or pattern.search(item.instance_id)):
            continue
        chosen.append(item)
    return chosen

execute_task

execute_task(payload: dict[str, Any]) -> dict[str, Any]

Worker: solve one task, check it, write its record; returns a short summary.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/runner.py
def execute_task(payload: dict[str, Any]) -> dict[str, Any]:
    """Worker: solve one task, check it, write its record; returns a short summary."""
    from importlib.metadata import version

    from mamut_routing_lib.enums import ObjectiveFunction
    from mamut_routing_lib.solvers import SolveMonitor, run_solver
    from mamut_routing_lib.solvers.report import solver_report_metadata

    task = Task(**payload)
    out = Path(task.out)
    record = _base_record(task, datetime.now(UTC).isoformat(timespec="seconds"))
    try:
        record["tools_version"] = version("mamut-routing-tools")
    except Exception:  # noqa: BLE001
        record["tools_version"] = None
    monitor = SolveMonitor(None, interval_s=3600.0, record_trajectory=True)
    workdir = raw_dir(out, task.key)
    objective = ObjectiveFunction(task.objective)
    initial_routes = None
    if task.warm_start == "best":
        # Looked up now, not when the plan was made: the runs this one starts from have finished.
        initial_routes, origin = best_known_routes(
            out, Path(task.instance_path), task.instance_id, objective, record["instance_sha256"]
        )
        if initial_routes is None:
            record.update(
                status="failed",
                valid=False,
                error="warm_start = best: no valid archived run or stored BKS to start from",
                finished=datetime.now(UTC).isoformat(timespec="seconds"),
                loadavg_end=_loadavg(),
            )
            atomic_write_json(run_path(out, task.key), record)
            return _summary(record)
        record["warm_start_key"] = origin
        record["warm_start_sha256"] = hashlib.sha256(json.dumps(initial_routes, separators=(",", ":")).encode()).hexdigest()
    try:
        solved = run_solver(
            task.solver,
            task.instance_path,
            time_limit_s=task.time_limit_s,
            seed=task.seed,
            objective_function=objective,
            monitor=monitor,
            initial_routes=initial_routes,
            workdir=workdir,
            keep_artifacts=True,
            options=task.options,
            config=task.solvers_config,
        )
        result = solved.result
        if solved.valid:
            evaluation = solved.check.exact_evaluation
            record.update(check_profile=evaluation["profile"], authoritative_cost=evaluation["authoritative_cost"])
        record.update(
            method=result.method,
            solver_version=result.solver_version,
            status=result.status,
            error=result.error,
            wall_time=round(result.wall_time, 3),
            valid=solved.valid,
            validated_cost=solved.cost,
            num_routes=len(result.routes) if result.routes else 0,
            check_status=solved.validation_status,
            check_error=(solved.check.error_message or None) if solved.check is not None else None,
            cost_scale=result.cost_scale,
            iterations=monitor.iterations or result.metadata.get("iterations"),
            trajectory=[list(point) for point in monitor.trajectory],
            routes=result.routes,
            provenance={key: value for key, value in result.provenance.items() if key not in ("host",)},
            **solver_report_metadata(result.solver_report),
        )
    except Exception as error:  # noqa: BLE001 - one bad run must not take the pool down
        import traceback

        record.update(status="failed", valid=False, error=f"{type(error).__name__}: {error}", traceback=traceback.format_exc())
    finally:
        for name in _INPUT_FILES:
            (workdir / name).unlink(missing_ok=True)
    record.update(finished=datetime.now(UTC).isoformat(timespec="seconds"), loadavg_end=_loadavg())
    atomic_write_json(run_path(out, task.key), record)
    return _summary(record)

memory_budget_gb

memory_budget_gb(setting: float | str) -> float

resources.memory_gb: a number, or auto = 80 % of MemAvailable (Linux; 8 GB elsewhere).

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/runner.py
def memory_budget_gb(setting: float | str) -> float:
    """``resources.memory_gb``: a number, or ``auto`` = 80 % of MemAvailable (Linux; 8 GB elsewhere)."""
    if setting != "auto":
        return float(setting)
    try:
        for line in Path("/proc/meminfo").read_text().splitlines():
            if line.startswith("MemAvailable:"):
                return 0.8 * int(line.split()[1]) / (1024 * 1024)
    except OSError:  # pragma: no cover
        pass
    return 8.0  # pragma: no cover

run_tasks

run_tasks(
    plan: CampaignPlan,
    *,
    out: Path,
    workers: int,
    memory_gb: float,
    progress: Callable[[str], None] = print,
    max_tasks: int | None = None,
) -> dict[str, Any]

Run the plan's tasks; returns (and writes to run.DONE) a summary.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/runner.py
def run_tasks(
    plan: CampaignPlan,
    *,
    out: Path,
    workers: int,
    memory_gb: float,
    progress: Callable[[str], None] = print,
    max_tasks: int | None = None,
) -> dict[str, Any]:
    """Run the plan's tasks; returns (and writes to ``run.DONE``) a summary."""
    tasks = list(plan.tasks[:max_tasks] if max_tasks is not None else plan.tasks)
    out.mkdir(parents=True, exist_ok=True)
    started = time.monotonic()
    state = {"stop": False, "abort": False}
    results: list[dict[str, Any]] = []
    failures: list[dict[str, Any]] = []
    context = mp.get_context("spawn")

    def _handle(signum: int, frame: Any) -> None:
        if signum == signal.SIGTERM:
            # Whoever sends SIGTERM expects the process gone soon (often SIGKILL follows): abort now.
            state["stop"] = state["abort"] = True
            progress("SIGTERM: aborting the running tasks (they leave no record; the next run redoes them)")
        elif state["stop"]:
            state["abort"] = True
            progress("second interrupt: aborting the running tasks")
        else:
            state["stop"] = True
            progress("interrupt: no new task starts; the running ones finish (interrupt again to abort)")

    previous = {sig: signal.signal(sig, _handle) for sig in (signal.SIGINT, signal.SIGTERM)}
    nice = tasks[0].nice if tasks else None
    running: dict[Any, _Worker] = {}
    pending = list(tasks)
    # Runs of each (instance, objective) that a warm start waits for: not started, or running.
    cold_open: dict[tuple[str, str], int] = {}
    for task in tasks:
        if task.warm_start != "best":
            cold_open[task.group] = cold_open.get(task.group, 0) + 1

    def _ready(task: Task) -> bool:
        return task.warm_start != "best" or not cold_open.get(task.group)

    def _start(task: Task) -> None:
        receiver, sender = context.Pipe(duplex=False)
        # Run keys also occur in other campaigns and retries. Only this launch owns its descendants.
        marker = f"{uuid4().hex}:{task.key}"
        process = context.Process(
            target=_task_main, args=(task.to_payload(), nice, sender, marker), name=f"bks-campaign {task.key}"
        )
        with _signals_blocked():
            process.start()
        sender.close()
        running[process.sentinel] = _Worker(task=task, marker=marker, process=process, connection=receiver)
        progress(f"start {task.key} ({task.time_limit_s}s, ~{task.memory_gb:.1f} GB)")

    def _finish(worker: _Worker) -> None:
        worker.process.join()
        summary = worker.summary()
        worker.connection.close()
        task = worker.task
        if task.warm_start != "best":
            cold_open[task.group] -= 1  # whatever its outcome, nobody waits for it any more
        if summary is None:
            killed = _kill_orphans(worker.marker)
            terminated = worker.process.exitcode in (-signal.SIGTERM, 128 + signal.SIGTERM)
            if state["abort"] or terminated:
                # An aborted or terminated run (SIGTERM to the whole group: systemd, a scheduler)
                # leaves no record: the next `run` picks it up.
                progress(f"stop  {task.key}: interrupted, no record")
                return
            reason = _death_reason(worker.process.exitcode)
            if killed:
                reason += f"; its solver was left running and has been killed ({killed} process group(s))"
            record = _base_record(task, datetime.now(UTC).isoformat(timespec="seconds"))
            record.update(status="failed", valid=False, error=reason, finished=datetime.now(UTC).isoformat(timespec="seconds"))
            atomic_write_json(run_path(out, task.key), record)
            summary = _summary(record)
            failures.append(summary)
        results.append(summary)
        cost = summary.get("validated_cost")
        detail = f" cost {cost}" if cost is not None else (f" ({summary['error']})" if summary.get("error") else "")
        progress(f"done  {task.key}: {summary.get('status')}{detail}")

    try:
        while pending or running:
            if state["abort"]:
                break
            while pending and not state["stop"] and len(running) < workers:
                in_use = sum(worker.task.memory_gb for worker in running.values())
                candidate = next((task for task in pending if _ready(task)), None)
                if candidate is None:
                    break  # only warm starts are left, waiting for the runs they start from
                if running and in_use + candidate.memory_gb > memory_gb:
                    # The longest task does not fit: start the first smaller one that does.
                    fitting = next((task for task in pending if _ready(task) and in_use + task.memory_gb <= memory_gb), None)
                    if fitting is None:
                        break
                    candidate = fitting
                pending.remove(candidate)
                _start(candidate)
            if not running:
                break
            for sentinel in mp.connection.wait(list(running), timeout=1.0):
                _finish(running.pop(sentinel))
    finally:
        if running:
            # Abort (or an unexpected error here): SIGTERM lets each worker kill its solver's group.
            for worker in running.values():
                with contextlib.suppress(ProcessLookupError, PermissionError):
                    os.kill(worker.process.pid, signal.SIGTERM)
            deadline = time.monotonic() + ABORT_GRACE_S
            for worker in running.values():
                worker.process.join(max(0.0, deadline - time.monotonic()))
                if worker.process.is_alive():
                    worker.process.kill()
                    worker.process.join()
                _kill_orphans(worker.marker)
                worker.connection.close()
        for sig, handler in previous.items():
            signal.signal(sig, handler)
    summary = {
        "finished": datetime.now(UTC).isoformat(timespec="seconds"),
        "host": socket.gethostname(),
        "planned": len(tasks),
        "completed": len(results),
        "valid": sum(1 for item in results if item.get("valid")),
        "failed_workers": len(failures),
        "interrupted": bool(state["stop"] or state["abort"]),
        "aborted": bool(state["abort"]),
        "not_started": len(pending),
        "wall_time_s": round(time.monotonic() - started, 1),
    }
    (out / "run.DONE").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8")
    return summary

load_spec

load_spec(path: str | Path) -> CampaignSpec

Read and validate a campaign spec; paths become absolute, out is refused inside a collection.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/spec.py
def load_spec(path: str | Path) -> CampaignSpec:
    """Read and validate a campaign spec; paths become absolute, ``out`` is refused inside a collection."""
    from mamut_routing_lib.sidecars import find_collection_root

    spec_path = Path(path).resolve()
    data = tomllib.loads(spec_path.read_text(encoding="utf-8"))
    spec = CampaignSpec.model_validate({**data, "path": spec_path}).resolved(spec_path.parent)
    out = spec.campaign.out
    try:
        inside = find_collection_root(out)
    except Exception:  # noqa: BLE001 - no collection marker above the out directory
        inside = None
    benchmarks = spec.select.benchmarks_dir
    if inside is not None or (benchmarks is not None and _is_within(out, benchmarks)):
        raise ValueError(f"campaign.out ({out}) must not lie inside a benchmark tree: workers never write next to instances")
    if not math.isfinite(spec.budget.time_scale) or spec.budget.time_scale <= 0:
        raise ValueError("budget.time_scale must be positive")
    return spec

parse_seeds

parse_seeds(value: str | int | list[int]) -> list[int]

"1-5,7" -> [1, 2, 3, 4, 5, 7]; a list or an int passes through.

Source code in MAMUT-routing-tools/src/mamut_routing_tools/bks_campaign/spec.py
def parse_seeds(value: str | int | list[int]) -> list[int]:
    """``"1-5,7"`` -> ``[1, 2, 3, 4, 5, 7]``; a list or an int passes through."""
    if isinstance(value, int):
        return [value]
    if isinstance(value, list):
        return list(dict.fromkeys(int(item) for item in value))
    seeds: list[int] = []
    for part in str(value).split(","):
        part = part.strip()
        if not part:
            continue
        if "-" in part:
            low, high = part.split("-", 1)
            if int(high) < int(low):
                raise ValueError(f"empty seed range {part!r}")
            seeds.extend(range(int(low), int(high) + 1))
        else:
            seeds.append(int(part))
    if not seeds:
        raise ValueError(f"no seeds in {value!r}")
    return list(dict.fromkeys(seeds))  # "1-3,2" is seeds 1, 2, 3: a repeated seed would be a duplicate run