Source code for jcmsuite.solve.solver

# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH

"""Public solve entrypoint for `jcmsuite`."""

from __future__ import annotations

import asyncio
from collections.abc import Coroutine
from pathlib import Path
from typing import Literal, overload

from ..context import BackendMode, SolverContext
from ..exceptions import SolveExecutionError, SourceMappingError
from ..internal.diagnostics import trim_exception_traceback
from ..results import (
    BatchSolveResult,
    BatchSolveSubmission,
    BundledBatchSolveResult,
    BundledBatchSolveSubmission,
    BundledSolveResult,
    BundledSolveSubmission,
    Resultbag,
    SolveResult,
    SolveSubmission,
)
from .orchestration import solve_impl
from .path_resolution import resolve_solve_call_site_file
from .types import (
    BatchOnError,
    BatchSolveKeysInput,
    DispatchMode,
    ProjectBundleInput,
    ProjectPathInput,
    SolveKeysInput,
    SolveMode,
    WaitBreakWhen,
    WaitOnTimeout,
    WorkingDirInput,
)


@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: SolveKeysInput = None,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: str | Path | None = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["wait"] = "wait",
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[False] = False,
) -> SolveResult: ...


@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: SolveKeysInput = None,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: str | Path | None = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["submit"],
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[False] = False,
) -> SolveSubmission: ...


@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: BatchSolveKeysInput,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: WorkingDirInput = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["wait"] = "wait",
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[False] = False,
) -> BatchSolveResult: ...


@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: BatchSolveKeysInput,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: WorkingDirInput = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["submit"],
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[False] = False,
) -> BatchSolveSubmission: ...


@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: SolveKeysInput = None,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: str | Path | None = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["wait"] = "wait",
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[True],
) -> Coroutine[object, object, SolveResult]: ...


@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: SolveKeysInput = None,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: str | Path | None = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["submit"],
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[True],
) -> Coroutine[object, object, SolveSubmission]: ...


@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: BatchSolveKeysInput,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: WorkingDirInput = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["wait"] = "wait",
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[True],
) -> Coroutine[object, object, BatchSolveResult]: ...


@overload
def solve(
    project_file: ProjectPathInput,
    *,
    keys: BatchSolveKeysInput,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: WorkingDirInput = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["submit"],
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[True],
) -> Coroutine[object, object, BatchSolveSubmission]: ...


@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: SolveKeysInput = None,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: str | Path | None = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["wait"] = "wait",
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[False] = False,
) -> BundledSolveResult: ...


@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: SolveKeysInput = None,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: str | Path | None = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["submit"],
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[False] = False,
) -> BundledSolveSubmission: ...


@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: BatchSolveKeysInput,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: WorkingDirInput = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["wait"] = "wait",
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[False] = False,
) -> BundledBatchSolveResult: ...


@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: BatchSolveKeysInput,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: WorkingDirInput = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["submit"],
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[False] = False,
) -> BundledBatchSolveSubmission: ...


@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: SolveKeysInput = None,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: str | Path | None = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["wait"] = "wait",
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[True],
) -> Coroutine[object, object, BundledSolveResult]: ...


@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: BatchSolveKeysInput,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: WorkingDirInput = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["submit"],
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[True],
) -> Coroutine[object, object, BundledBatchSolveSubmission]: ...


@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: SolveKeysInput = None,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: str | Path | None = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["submit"],
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[True],
) -> Coroutine[object, object, BundledSolveSubmission]: ...


@overload
def solve(
    project_file: ProjectBundleInput,
    *,
    keys: BatchSolveKeysInput,
    resultbag: Resultbag | None = None,
    recompute: bool = False,
    max_retries: int = 0,
    on_error: BatchOnError = "raise",
    context: SolverContext | None = None,
    backend: BackendMode | None = None,
    working_dir: WorkingDirInput = None,
    jcmt_pattern: str | None = None,
    temporary: bool = False,
    dispatch: Literal["wait"] = "wait",
    wait_break_when: WaitBreakWhen = "all",
    wait_timeout: float | None = None,
    wait_on_timeout: WaitOnTimeout = "raise",
    wait_progress: bool = False,
    wait_progress_label: str | None = None,
    quiet: bool = False,
    mode: SolveMode = "solve",
    asynchronous: Literal[True],
) -> Coroutine[object, object, BundledBatchSolveResult]: ...


[docs] def solve( project_file: ProjectPathInput | ProjectBundleInput, *, keys: SolveKeysInput | BatchSolveKeysInput = None, resultbag: Resultbag | None = None, recompute: bool = False, max_retries: int = 0, on_error: BatchOnError = "raise", context: SolverContext | None = None, backend: BackendMode | None = None, working_dir: WorkingDirInput = None, jcmt_pattern: str | None = None, temporary: bool = False, dispatch: DispatchMode = "wait", wait_break_when: WaitBreakWhen = "all", wait_timeout: float | None = None, wait_on_timeout: WaitOnTimeout = "raise", wait_progress: bool = False, wait_progress_label: str | None = None, quiet: bool = False, mode: SolveMode = "solve", asynchronous: bool = False, ) -> ( SolveResult | BatchSolveResult | BundledSolveResult | BundledBatchSolveResult | SolveSubmission | BundledSolveSubmission | BundledBatchSolveSubmission | BatchSolveSubmission | Coroutine[ object, object, SolveResult | BatchSolveResult | BundledSolveResult | BundledBatchSolveResult | SolveSubmission | BundledSolveSubmission | BundledBatchSolveSubmission | BatchSolveSubmission, ] ): """Solve one project or one ordered project bundle. Parameters ---------- project_file : str | Path | Sequence[str | Path] project file (`.jcmp` or `.jcm`) or one ordered project bundle. You can give an ordered project bundle as a list or tuple of project files. JCMsuite runs the projects in the given order. If `keys` contains batched project keys, JCMsuite runs the complete bundle for each set of project keys. JCMsuite first resolves a relative path from the Python file that calls `solve(...)`. If this is not possible, it resolves the path from the current working directory. keys : Mapping[str, object] | Sequence[Mapping[str, object]] | None, optional One set of project keys, batched project keys, or `None` if the project does not use project keys. resultbag : Resultbag | None, optional Resultbag in which to store and find results. An ordered project bundle is one Resultbag entry for each set of project keys. recompute : bool, optional If `False`, reuse matching Resultbag entries. If `True`, run the solve again. max_retries : int, optional Number of times to try a failed solve again. Use `0` to disable retries. For a daemon-backed ordered project bundle, an execution failure retries the complete bundle. A timeout does not resubmit the bundle. This option requires `dispatch="wait"`. on_error : {"raise", "collect"}, optional Error policy for batched project keys. `"raise"` stops at the first failed entry. `"collect"` stores failures as `BatchSolveFailure` records and continues with the remaining entries. context : SolverContext | None, optional JCMsuite settings to use. If omitted, use the active context or the default context. backend : BackendMode | None, optional Execution method to use. If omitted, use the method from `context`. working_dir : WorkingDirInput, optional Directory in which to run each solve. For batched project keys, give one directory for each set of project keys. For a batch with one entry, one directory is also valid. For an ordered project bundle, one directory contains all project working directories. JCMsuite preserves the relative project paths and copies shared project support files into this directory. If you set `working_dir`, JCMsuite uses it even if `temporary=True`. For a daemon-backed bundle batch, omitted directories create separate temporary roots for uncached entries. Explicit live roots must not overlap. If several entries execute, their roots must not contain the source project files. jcmt_pattern : str | None, optional JCMT pattern for project support files. The solve first tries `name.<suffix>.jcmt` or `name.<suffix>.jcm`, then uses the unsuffixed file. temporary : bool, optional If `True` and `working_dir` is omitted, create a temporary working directory for each solve entry. If the context defines a temporary directory root, the solve creates the directories below that root. If `False` and `working_dir` is omitted, the solve runs in the project directory, except for daemon-backed bundle batches, which use separate temporary roots for uncached entries. dispatch : {"wait", "submit"}, optional Daemon return behavior. `"wait"` waits for the solve and returns its result. `"submit"` returns a submission before the solve is complete. For an ordered project bundle, both options submit the complete bundle as one daemon job. `"submit"` returns its Submission after all projects are prepared and submitted. A subsequent `wait()` collects the bundle results without submitting further projects. wait_break_when : {"all", "any"}, optional Condition that ends a daemon wait. `"all"` waits for all requested solves. `"any"` returns after the first requested solve finishes. Daemon-backed ordered bundles and bundle batches require `"all"`. wait_timeout : float | None, optional Maximum number of seconds to wait for daemon results. If omitted, wait without a time limit. wait_on_timeout : {"raise", "return"}, optional Action at the daemon time limit. `"raise"` raises an error. `"return"` returns the results that are available. Daemon-backed ordered bundles and bundle batches require `"raise"`. wait_progress : bool, optional If `True`, show progress while waiting for a batch. wait_progress_label : str | None, optional Text to show with the progress display. If omitted, use `"daemon.wait"` for a daemon wait or `"solve(batch)"` for a local batch. quiet : bool, optional If `True`, do not show output from a local solve. mode : Literal["solve", "postprocess"], optional Defaults to ``"solve"``; use ``"postprocess"`` to run only declared postprocesses with accessible saved fieldbags. Resultbag is not supported in postprocess mode. asynchronous : bool, optional If `True`, return a value that you must use with `await`. Returns ------- SolveResult | BatchSolveResult | BundledSolveResult | BundledBatchSolveResult | SolveSubmission | BatchSolveSubmission | BundledSolveSubmission | BundledBatchSolveSubmission | Coroutine[...] One project with one set of project keys returns `SolveResult`. One project with batched project keys returns `BatchSolveResult`. An ordered project bundle returns `BundledSolveResult` or `BundledBatchSolveResult`. If `dispatch="submit"`, the function returns the corresponding submission. If `asynchronous=True`, the function returns a value that you must use with `await`. Raises ------ RuntimeError If asynchronous code calls the function without `asynchronous=True`. SourceMappingError If a template or JCMsuite input error identifies a source position. SolveExecutionError If JCMsuite reports a solve failure. The call trims internal traceback frames and preserves the solver's diagnostic details. InvalidConfigurationError If the project input or option combination is not valid. """ if asynchronous: caller_file: Path | None = resolve_solve_call_site_file() async def _solve_asynchronously() -> ( SolveResult | BatchSolveResult | BundledSolveResult | BundledBatchSolveResult | SolveSubmission | BundledSolveSubmission | BundledBatchSolveSubmission | BatchSolveSubmission ): try: return await solve_impl( project_file=project_file, caller_file=caller_file, keys=keys, resultbag=resultbag, recompute=recompute, max_retries=max_retries, on_error=on_error, context=context, backend=backend, working_dir=working_dir, jcmt_pattern=jcmt_pattern, temporary=temporary, dispatch=dispatch, wait_break_when=wait_break_when, wait_timeout=wait_timeout, wait_on_timeout=wait_on_timeout, wait_progress=wait_progress, wait_progress_label=wait_progress_label, quiet=quiet, mode=mode, ) except SolveExecutionError as error: raise trim_exception_traceback(error) from None except SourceMappingError as error: cause: BaseException | None = ( error.__cause__ if isinstance(error.__cause__, SolveExecutionError) else None ) raise trim_exception_traceback(error) from cause return _solve_asynchronously() try: asyncio.get_running_loop() except RuntimeError: try: caller_file = resolve_solve_call_site_file() return asyncio.run( solve_impl( project_file=project_file, caller_file=caller_file, keys=keys, resultbag=resultbag, recompute=recompute, max_retries=max_retries, on_error=on_error, context=context, backend=backend, working_dir=working_dir, jcmt_pattern=jcmt_pattern, temporary=temporary, dispatch=dispatch, wait_break_when=wait_break_when, wait_timeout=wait_timeout, wait_on_timeout=wait_on_timeout, wait_progress=wait_progress, wait_progress_label=wait_progress_label, quiet=quiet, mode=mode, ) ) except SolveExecutionError as error: # Keep solver diagnostics available while removing the internal # async execution stack from the synchronous public boundary. raise trim_exception_traceback(error) from None except SourceMappingError as error: # Keep user-facing diagnostics concise in sync mode by removing # deep internal async/template call stacks. cause: BaseException | None = ( error.__cause__ if isinstance(error.__cause__, SolveExecutionError) else None ) raise trim_exception_traceback(error) from cause raise RuntimeError( "solve() called from a running event loop; use `await solve(..., asynchronous=True)`." )