# SPDX-License-Identifier: MIT
# Copyright (c) 2001-{{ COPYRIGHT_END_YEAR }} JCMwave GmbH
"""submission handle models for daemon-dispatched solves."""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Coroutine, Iterator, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Literal, overload
from ....exceptions import (
ConfigMappingError,
InvalidConfigurationError,
SolveExecutionError,
)
from ....internal.diagnostics import trim_exception_traceback
from .batch import BatchSolveEntry, BatchSolveFailure, BatchSolveResult
from .bundle import BundledBatchSolveResult, BundledSolveResult
from .core import SolveResult
if TYPE_CHECKING:
from ....daemon.handler import DaemonHandler
from ...resultbag import Resultbag
[docs]
@dataclass(slots=True, frozen=True)
class SolveSubmission:
"""Represent one solve submitted to the daemon.
Parameters
----------
job_id : int
Daemon submission identifier for this submitted solve.
result : SolveResult
Result information associated with this submission.
keys : dict[str, object] | None, optional
Submitted project keys, if available.
index : int | None, optional
Position in the batched project keys, if applicable.
"""
job_id: int
result: SolveResult
keys: dict[str, object] | None = None
index: int | None = None
_waiter: DaemonHandler | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
_resultbag: Resultbag | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
_jcmt_pattern: str | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
_source_project_mappings: tuple[tuple[Path, Path], ...] = field(
default=(),
repr=False,
compare=False,
init=False,
)
def _bind_runtime(
self,
*,
waiter: DaemonHandler | None,
resultbag: Resultbag | None = None,
jcmt_pattern: str | None = None,
source_project_mappings: tuple[tuple[Path, Path], ...] = (),
) -> SolveSubmission:
"""Bind internal runtime handles not exposed in the public constructor.
Notes
-----
Internal API: this helper mutates frozen runtime-only fields to keep
constructor signatures clean in user-facing docs.
"""
object.__setattr__(self, "_waiter", waiter)
object.__setattr__(self, "_resultbag", resultbag)
object.__setattr__(self, "_jcmt_pattern", jcmt_pattern)
object.__setattr__(self, "_source_project_mappings", source_project_mappings)
return self
@overload
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: Literal[False] = False,
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> SolveResult: ...
@overload
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: Literal[True],
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> Coroutine[object, object, SolveResult]: ...
[docs]
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: bool = False,
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> SolveResult | Coroutine[object, object, SolveResult]:
"""Wait for this submission and return its result.
Parameters
----------
daemon : DaemonHandler | None, optional
Daemon handler to use. If `daemon` is `None`, use the handler that
created the submission.
asynchronous : bool, optional
If `True`, return a coroutine. The caller must await the coroutine.
break_when : {"all", "any"}, optional
Completion condition. `"all"` waits for all submitted solves.
`"any"` returns after the first submitted solve completes.
timeout : float | None, optional
Maximum wait time in seconds. `None` sets no time limit.
on_timeout : {"raise", "return"}, optional
Action at the time limit. `"raise"` raises an exception.
`"return"` returns the results that are available.
on_error : {"raise", "collect"}, optional
Action when a solve fails. `"raise"` raises an exception.
`"collect"` stores the failure information in the result.
progress : bool, optional
If `True`, show progress while more than one solve is pending.
progress_label : str | None, optional
Text for the progress indicator. If omitted, the wait operation
uses its default label.
Returns
-------
SolveResult | Coroutine[object, object, SolveResult]
Result for the project. If `asynchronous` is `True`, returns a
coroutine that produces the result.
"""
waiter: DaemonHandler | None = daemon if daemon is not None else self._waiter
if waiter is None:
raise InvalidConfigurationError(
"SolveSubmission is not bound to a daemon handler. Pass "
"`daemon=` explicitly or create the submission via "
"`jcmsuite.solve(..., dispatch='submit')`."
)
if asynchronous:
return waiter.wait(
self,
asynchronous=True,
break_when=break_when,
timeout=timeout,
on_timeout=on_timeout,
on_error=on_error,
progress=progress,
progress_label=progress_label,
)
return waiter.wait(
self,
asynchronous=False,
break_when=break_when,
timeout=timeout,
on_timeout=on_timeout,
on_error=on_error,
progress=progress,
)
[docs]
@dataclass(slots=True, frozen=True)
class BundledSolveSubmission:
"""Represent one ordered project bundle submitted as one daemon job.
Parameters
----------
job_id : int | None
One daemon job identifier, or `None` for a cached bundle.
project_files : tuple[Path, ...]
Prepared project files in execution order. Cached handles retain the
supplied project input paths instead.
keys : dict[str, object] | None, optional
Project Keys for the complete bundle.
Notes
-----
On a Slurm queue, all projects execute in order within one scheduler job.
Wait for the complete bundle before selecting individual project results.
This Submission does not support indexing or slicing. A
`BundledBatchSolveSubmission` supports both operations on complete bundles.
"""
#: One daemon job identifier, or ``None`` for a cached bundle.
job_id: int | None
#: Prepared project paths in execution order; supplied input paths for a cached bundle.
project_files: tuple[Path, ...] = ()
#: Project Keys for the complete bundle, or ``None`` when no Project Keys were supplied.
keys: dict[str, object] | None = None
_wait_task: asyncio.Task[BundledSolveResult] | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
_failure: ConfigMappingError | SolveExecutionError | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
_waiter: DaemonHandler | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
_wait_callback: (
Callable[..., Coroutine[object, object, BundledSolveResult]] | None
) = field(
default=None,
repr=False,
compare=False,
init=False,
)
_resolved_result: BundledSolveResult | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
def _bind_runtime(
self,
*,
waiter: DaemonHandler | None,
wait_callback: (
Callable[..., Coroutine[object, object, BundledSolveResult]] | None
) = None,
resolved_result: BundledSolveResult | None = None,
) -> BundledSolveSubmission:
"""Bind runtime waiter/callback state without exposing it publicly."""
object.__setattr__(self, "_waiter", waiter)
object.__setattr__(self, "_wait_callback", wait_callback)
object.__setattr__(self, "_resolved_result", resolved_result)
return self
@overload
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: Literal[False] = False,
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> BundledSolveResult: ...
@overload
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: Literal[True],
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> Coroutine[object, object, BundledSolveResult]: ...
[docs]
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: bool = False,
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> BundledSolveResult | Coroutine[object, object, BundledSolveResult]:
"""Wait for the one job that executes the complete ordered project bundle.
Parameters
----------
daemon : DaemonHandler | None, optional
Daemon handler to use. If `daemon` is `None`, use the handler that
created the submission.
asynchronous : bool, optional
If `True`, return a coroutine. The caller must await the coroutine.
break_when : {"all", "any"}, optional
Use `"all"` to wait for the complete bundle. `"any"` is rejected
because individual projects are not independently waitable.
timeout : float | None, optional
Maximum wait time in seconds. `None` sets no time limit.
on_timeout : {"raise", "return"}, optional
Use `"raise"` to raise a timeout without closing or resubmitting the
job. `"return"` is rejected because a bundle is one solve unit.
on_error : {"raise", "collect"}, optional
Use `"raise"` for a failed bundle. `"collect"` is supported only on
a bundled-batch wait.
progress : bool, optional
If `True`, show progress while more than one solve is pending.
progress_label : str | None, optional
Text for the progress indicator. If omitted, the wait operation
uses its default label.
Returns
-------
BundledSolveResult | Coroutine[object, object, BundledSolveResult]
Results in ordered project bundle order. If `asynchronous` is
`True`, returns a coroutine that produces the results.
Raises
------
TimeoutError
If the wait reaches its time limit before the bundle completes.
The daemon job remains submitted. Call `wait()` again to collect
the same bundle.
ConfigMappingError
If the daemon reports an input error with a source position. The
error identifies the source file. Its `SolveExecutionError` cause
contains the exit code and log, and daemon job metadata when available.
SolveExecutionError
If the daemon reports an execution failure without a source
position. The complete bundle fails, even if an earlier project
produced files.
InvalidConfigurationError
If a wait option is unsupported or the Submission is not bound to
its submitting daemon handler.
RuntimeError
If a synchronous wait is called from a running event loop.
Notes
-----
The complete bundle is already submitted. This method does not submit
further projects. After success, later waits return the completed
bundle. After a terminal daemon failure, later waits raise that failure.
"""
if break_when != "all":
raise InvalidConfigurationError(
"BundledSolveSubmission.wait() only supports `break_when='all'`."
)
if on_error != "raise":
raise InvalidConfigurationError(
"BundledSolveSubmission.wait() only supports `on_error='raise'`."
)
if on_timeout != "raise":
raise InvalidConfigurationError(
"BundledSolveSubmission.wait() only supports `on_timeout='raise'`."
)
if timeout is not None and timeout < 0.0:
raise InvalidConfigurationError("timeout must be non-negative.")
if (
daemon is not None
and self._waiter is not None
and daemon is not self._waiter
):
raise InvalidConfigurationError(
"Bundle wait must use its submitting daemon handler."
)
resolved_result: BundledSolveResult | None = self._resolved_result
if resolved_result is not None:
if asynchronous:
async def _return_resolved_result() -> BundledSolveResult:
return resolved_result
return _return_resolved_result()
return resolved_result
wait_callback = self._wait_callback
waiter: DaemonHandler | None = daemon if daemon is not None else self._waiter
if wait_callback is None or waiter is None:
raise InvalidConfigurationError(
"BundledSolveSubmission is not bound to a daemon handler. Pass "
"`daemon=` explicitly or create the submission via "
"`jcmsuite.solve(..., dispatch='submit')`."
)
async def _run_wait() -> BundledSolveResult:
try:
collected: BundledSolveResult = await wait_callback(
bundle_submission=self,
daemon=waiter,
break_when=break_when,
timeout=timeout,
on_timeout=on_timeout,
on_error=on_error,
progress=progress,
progress_label=progress_label,
)
except (ConfigMappingError, SolveExecutionError) as error:
object.__setattr__(self, "_failure", error)
raise
object.__setattr__(self, "_resolved_result", collected)
return collected
async def _collect_bundle() -> BundledSolveResult:
if self._resolved_result is not None:
return self._resolved_result
task: asyncio.Task[BundledSolveResult] | None = self._wait_task
try:
if self._failure is not None:
raise self._failure
if task is None or task.cancelled():
task = asyncio.create_task(_run_wait())
object.__setattr__(self, "_wait_task", task)
# Every batch slice references this same handle. Share collection
# even when callers start their waits concurrently.
return await asyncio.shield(task)
except (ConfigMappingError, SolveExecutionError) as error:
cause: BaseException | None = (
error.__cause__
if isinstance(error.__cause__, SolveExecutionError)
else None
)
raise trim_exception_traceback(error) from cause
finally:
if task is not None and task.done() and self._wait_task is task:
object.__setattr__(self, "_wait_task", None)
if asynchronous:
return _collect_bundle()
try:
asyncio.get_running_loop()
except RuntimeError:
try:
return asyncio.run(_collect_bundle())
except (ConfigMappingError, SolveExecutionError) as error:
cause: BaseException | None = (
error.__cause__
if isinstance(error.__cause__, SolveExecutionError)
else None
)
raise trim_exception_traceback(error) from cause
raise RuntimeError(
"BundledSolveSubmission.wait() called from a running event loop; use "
"`await submission.wait(..., asynchronous=True)`."
)
[docs]
@dataclass(slots=True, frozen=True)
class BundledBatchSolveSubmissionEntry:
"""Store one submitted ordered project bundle in a batch.
Parameters
----------
index : int
Position in the original batched project keys.
keys : dict[str, object]
project keys for this batch entry.
result : BundledSolveSubmission | None
submission for an ordered project bundle, if submission succeeded.
failure : BatchSolveFailure | None
Failure information if submission did not succeed.
project_files : tuple[Path, ...], optional
project files in ordered project bundle order.
"""
index: int
keys: dict[str, object]
result: BundledSolveSubmission | None
failure: BatchSolveFailure | None
project_files: tuple[Path, ...] = ()
[docs]
@dataclass(slots=True, frozen=True)
class BundledBatchSolveSubmission(Sequence[BundledSolveSubmission]):
"""Represent a batch of submitted ordered project bundles.
Parameters
----------
entries : tuple[BundledBatchSolveSubmissionEntry, ...]
Ordered project bundle submissions in batched project keys order.
Notes
-----
`submission[index]` returns one successful ordered project bundle
submission. A slice returns a new `BundledBatchSolveSubmission`. Iteration
yields successful bundle submissions in batched project keys order and
raises an error if an entry contains a collected failure.
Call `submission[index].wait()` to collect one complete bundle. Call
`submission[start:stop].wait()` to collect a subset. Slices retain the
original batch indices. Results use the project-first navigation of
`BundledBatchSolveResult`.
"""
entries: tuple[BundledBatchSolveSubmissionEntry, ...]
_waiter: DaemonHandler | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
_wait_callback: (
Callable[..., Coroutine[object, object, BundledBatchSolveResult]] | None
) = field(
default=None,
repr=False,
compare=False,
init=False,
)
def _bind_runtime(
self,
*,
waiter: DaemonHandler | None,
wait_callback: (
Callable[..., Coroutine[object, object, BundledBatchSolveResult]] | None
) = None,
) -> BundledBatchSolveSubmission:
"""Bind runtime waiter/callback state without exposing it publicly."""
object.__setattr__(self, "_waiter", waiter)
object.__setattr__(self, "_wait_callback", wait_callback)
return self
[docs]
def __len__(self) -> int:
"""Return the number of batch entries.
Returns
-------
int
Number of ordered project bundle submission entries.
"""
return len(self.entries)
[docs]
def __iter__(self) -> Iterator[BundledSolveSubmission]:
"""Iterate over successful bundle submissions in batch order.
Returns
-------
Iterator[BundledSolveSubmission]
Iterator over successful ordered project bundle submissions.
Raises
------
TypeError
If an entry contains a collected submission failure.
"""
entry: BundledBatchSolveSubmissionEntry
for entry in self.entries:
if entry.result is None:
raise TypeError(
"BundledBatchSolveSubmission iteration requires successful "
"bundle entries only; inspect `.entries` for collected failures."
)
yield entry.result
@overload
def __getitem__(self, index: int) -> BundledSolveSubmission: ...
@overload
def __getitem__(self, index: slice) -> BundledBatchSolveSubmission: ...
[docs]
def __getitem__(
self,
index: int | slice,
) -> BundledSolveSubmission | BundledBatchSolveSubmission:
"""Return one bundle submission or a sliced batch.
Parameters
----------
index : int | slice
Batch position or standard Python slice. Negative positions count
from the end of the batch.
Returns
-------
BundledSolveSubmission | BundledBatchSolveSubmission
One successful bundle submission for an integer position, or a new
batch submission for a slice.
Raises
------
TypeError
If the selected entry contains a collected submission failure.
IndexError
If an integer position is outside the batch.
"""
if isinstance(index, slice):
return BundledBatchSolveSubmission(
entries=self.entries[index]
)._bind_runtime(
waiter=self._waiter,
wait_callback=self._wait_callback,
)
result: BundledSolveSubmission | None = self.entries[index].result
if result is None:
raise TypeError(
"Selected batch solve bundle submission does not contain a "
"result; inspect `.entries[index].failure`."
)
return result
@property
def keys(self) -> tuple[dict[str, object], ...]:
"""Return the project keys in their original batch order.
Returns
-------
tuple[dict[str, object], ...]
project keys for each batch entry.
"""
return tuple(entry.keys for entry in self.entries)
@property
def results(self) -> tuple[BundledSolveSubmission | None, ...]:
"""Return the bundle submissions in batched project keys order.
A value is `None` if submission did not succeed for that batch entry.
Returns
-------
tuple[BundledSolveSubmission | None, ...]
Bundle submissions in batched project keys order.
"""
return tuple(entry.result for entry in self.entries)
@property
def failures(self) -> tuple[BatchSolveFailure, ...]:
"""Return collected failures in batched project keys order.
Returns
-------
tuple[BatchSolveFailure, ...]
Failures collected during submission.
"""
return tuple(
failure
for failure in (entry.failure for entry in self.entries)
if failure is not None
)
[docs]
def items(self) -> tuple[tuple[int, BundledBatchSolveSubmissionEntry], ...]:
"""Return each original batch position with its submission entry.
Returns
-------
tuple[tuple[int, BundledBatchSolveSubmissionEntry], ...]
Pairs in batched project keys order.
"""
return tuple((entry.index, entry) for entry in self.entries)
@overload
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: Literal[False] = False,
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> BundledBatchSolveResult: ...
@overload
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: Literal[True],
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> Coroutine[object, object, BundledBatchSolveResult]: ...
[docs]
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: bool = False,
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> BundledBatchSolveResult | Coroutine[object, object, BundledBatchSolveResult]:
"""Wait for the submitted batch of ordered project bundles.
Parameters
----------
daemon : DaemonHandler | None, optional
Daemon handler to use. If `daemon` is `None`, use the handler that
created the submission.
asynchronous : bool, optional
If `True`, return a coroutine. The caller must await the coroutine.
break_when : {"all", "any"}, optional
Use `"all"` to wait for all selected bundles. `"any"` is rejected.
Select one bundle or a slice before waiting for a subset.
timeout : float | None, optional
Maximum wait time in seconds. `None` sets no time limit.
on_timeout : {"raise", "return"}, optional
Use `"raise"` to raise a timeout. `"return"` is rejected.
on_error : {"raise", "collect"}, optional
Action when a solve fails. `"raise"` raises an exception.
`"collect"` stores the failure information in the result.
progress : bool, optional
If `True`, show progress while more than one solve is pending.
progress_label : str | None, optional
Text for the progress indicator. If omitted, the wait operation
uses its default label.
Returns
-------
BundledBatchSolveResult | Coroutine[object, object, BundledBatchSolveResult]
Results for the batched ordered project bundles. If `asynchronous`
is `True`, returns a coroutine that produces the results.
"""
wait_callback = self._wait_callback
waiter: DaemonHandler | None = daemon if daemon is not None else self._waiter
if wait_callback is None or waiter is None:
raise InvalidConfigurationError(
"BundledBatchSolveSubmission is not bound to a daemon handler. "
"Pass `daemon=` explicitly or create the submission via "
"`jcmsuite.solve(..., dispatch='submit')`."
)
wait_coro = wait_callback(
batch_submission=self,
daemon=waiter,
break_when=break_when,
timeout=timeout,
on_timeout=on_timeout,
on_error=on_error,
progress=progress,
progress_label=progress_label,
)
if asynchronous:
async def _wait_asynchronously() -> BundledBatchSolveResult:
try:
return await wait_coro
except (ConfigMappingError, SolveExecutionError) as error:
cause: BaseException | None = (
error.__cause__
if isinstance(error.__cause__, SolveExecutionError)
else None
)
raise trim_exception_traceback(error) from cause
return _wait_asynchronously()
try:
asyncio.get_running_loop()
except RuntimeError:
try:
return asyncio.run(wait_coro)
except (ConfigMappingError, SolveExecutionError) as error:
cause: BaseException | None = (
error.__cause__
if isinstance(error.__cause__, SolveExecutionError)
else None
)
raise trim_exception_traceback(error) from cause
raise RuntimeError(
"BundledBatchSolveSubmission.wait() called from a running event loop; "
"use `await submission.wait(..., asynchronous=True)`."
)
[docs]
@dataclass(slots=True, frozen=True)
class BatchSolveSubmission(Sequence[SolveSubmission]):
"""Represent batched project keys submitted to the daemon.
Parameters
----------
entries : tuple[SolveSubmission, ...]
submissions in batched project keys order.
Notes
-----
You can select an entry by position or select a range with a slice. A slice
returns another `BatchSolveSubmission`.
"""
entries: tuple[SolveSubmission, ...]
_resolved_result: BatchSolveResult | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
_waiter: DaemonHandler | None = field(
default=None,
repr=False,
compare=False,
init=False,
)
def _bind_runtime(
self,
*,
waiter: DaemonHandler | None,
resolved_result: BatchSolveResult | None = None,
) -> BatchSolveSubmission:
"""Bind internal waiter handle without exposing constructor internals.
Notes
-----
Internal API: this helper mutates frozen runtime-only fields to keep
constructor signatures clean in user-facing docs.
"""
object.__setattr__(self, "_waiter", waiter)
object.__setattr__(self, "_resolved_result", resolved_result)
return self
[docs]
def __len__(self) -> int:
"""Return the number of submission entries.
Returns
-------
int
Number of entries in the submitted batch.
"""
return len(self.entries)
[docs]
def __iter__(self) -> Iterator[SolveSubmission]:
"""Iterate over submissions in batched project keys order.
Returns
-------
Iterator[SolveSubmission]
Iterator over the submission entries.
"""
return iter(self.entries)
@overload
def __getitem__(self, index: int) -> SolveSubmission:
"""Return single submission entry by integer index.
Parameters
----------
index : int
Entry position.
Returns
-------
SolveSubmission
submission handle at ``index``.
Notes
-----
Internal API: overload declaration for typing and may change without
notice.
"""
...
@overload
def __getitem__(self, index: slice) -> BatchSolveSubmission:
"""Return a sliced submission view.
Parameters
----------
index : slice
Slice specification.
Returns
-------
BatchSolveSubmission
Sliced submission wrapper.
Notes
-----
Internal API: overload declaration for typing and may change without
notice.
"""
...
[docs]
def __getitem__(self, index: int | slice) -> SolveSubmission | BatchSolveSubmission:
"""Return one submission or a sliced batch submission.
Parameters
----------
index : int | slice
Batch position or standard Python slice. Negative positions count
from the end of the batch.
Returns
-------
SolveSubmission | BatchSolveSubmission
One submission for an integer position, or a new batch submission
for a slice.
Raises
------
IndexError
If an integer position is outside the batch.
"""
if isinstance(index, slice):
sliced_submission: BatchSolveSubmission = BatchSolveSubmission(
entries=self.entries[index]
)
sliced_resolved_result: BatchSolveResult | None = self._resolved_result
if sliced_resolved_result is not None:
selected_indices: set[int] = {
entry.index
for entry in sliced_submission.entries
if entry.index is not None
}
sliced_resolved_result = BatchSolveResult(
entries=tuple(
entry
for entry in sliced_resolved_result.entries
if entry.index in selected_indices
)
)
return sliced_submission._bind_runtime(
waiter=self._waiter,
resolved_result=sliced_resolved_result,
)
return self.entries[index]
[docs]
def job_ids(self) -> tuple[int, ...]:
"""Return daemon submission identifiers in batched project keys order.
Returns
-------
tuple[int, ...]
Daemon submission identifiers for the submitted solves.
"""
return tuple(entry.job_id for entry in self.entries)
@property
def successes(self) -> tuple[SolveResult, ...]:
"""Return results that are already available on the submissions.
Returns
-------
tuple[SolveResult, ...]
Available result information in batched project keys order.
"""
return tuple(entry.result for entry in self.entries)
@property
def failures(self) -> tuple[BatchSolveFailure, ...]:
"""Return no failures before `wait(...)` creates the batch result.
Returns
-------
tuple[BatchSolveFailure, ...]
Empty tuple. Read failures from the `BatchSolveResult` returned by
`wait(...)`.
"""
return ()
@overload
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: Literal[False] = False,
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> BatchSolveResult: ...
@overload
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: Literal[True],
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> Coroutine[object, object, BatchSolveResult]: ...
[docs]
def wait(
self,
*,
daemon: DaemonHandler | None = None,
asynchronous: bool = False,
break_when: Literal["all", "any"] = "all",
timeout: float | None = None,
on_timeout: Literal["raise", "return"] = "raise",
on_error: Literal["raise", "collect"] = "raise",
progress: bool = False,
progress_label: str | None = None,
) -> BatchSolveResult | Coroutine[object, object, BatchSolveResult]:
"""Wait for the submitted batched project keys.
Parameters
----------
daemon : DaemonHandler | None, optional
Daemon handler to use. If `daemon` is `None`, use the handler that
created the submission.
asynchronous : bool, optional
If `True`, return a coroutine. The caller must await the coroutine.
break_when : {"all", "any"}, optional
Completion condition. `"all"` waits for all submitted solves.
`"any"` returns after the first submitted solve completes.
timeout : float | None, optional
Maximum wait time in seconds. `None` sets no time limit.
on_timeout : {"raise", "return"}, optional
Action at the time limit. `"raise"` raises an exception.
`"return"` returns the results that are available.
on_error : {"raise", "collect"}, optional
Action when a solve fails. `"raise"` raises an exception.
`"collect"` stores the failure information in the result.
progress : bool, optional
If `True`, show progress while more than one solve is pending.
progress_label : str | None, optional
Text for the progress indicator. If omitted, the wait operation
uses its default label.
Returns
-------
BatchSolveResult | Coroutine[object, object, BatchSolveResult]
Results in batched project keys order. If `asynchronous` is `True`,
returns a coroutine that produces the results.
"""
waiter: DaemonHandler | None = daemon if daemon is not None else self._waiter
resolved_result: BatchSolveResult | None = self._resolved_result
if waiter is None and resolved_result is None:
raise InvalidConfigurationError(
"BatchSolveSubmission is not bound to a daemon handler. Pass "
"`daemon=` explicitly or create the submission via "
"`jcmsuite.solve(..., dispatch='submit')`."
)
resolved_waiter: DaemonHandler | None = waiter
if resolved_result is not None and len(self.entries) == 0:
if asynchronous:
async def _return_resolved_result() -> BatchSolveResult:
return resolved_result
return _return_resolved_result()
return resolved_result
async def _wait_and_merge() -> BatchSolveResult:
if waiter is None:
raise InvalidConfigurationError(
"BatchSolveSubmission is not bound to a daemon handler. Pass "
"`daemon=` explicitly or create the submission via "
"`jcmsuite.solve(..., dispatch='submit')`."
)
resolved_waiter: DaemonHandler = waiter
live_submission: BatchSolveSubmission = BatchSolveSubmission(
entries=self.entries
)._bind_runtime(waiter=resolved_waiter)
waited_result: BatchSolveResult = await resolved_waiter.wait(
live_submission,
asynchronous=True,
break_when=break_when,
timeout=timeout,
on_timeout=on_timeout,
on_error=on_error,
progress=progress,
progress_label=progress_label,
)
if resolved_result is None:
return waited_result
merged_entries: list[BatchSolveEntry] = [
*resolved_result.entries,
*waited_result.entries,
]
merged_entries.sort(key=lambda entry: entry.index)
return BatchSolveResult(entries=tuple(merged_entries))
if resolved_result is not None:
if asynchronous:
return _wait_and_merge()
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(_wait_and_merge())
raise RuntimeError(
"BatchSolveSubmission.wait() called from a running event loop; "
"use `await submission.wait(..., asynchronous=True)`."
)
if asynchronous:
assert resolved_waiter is not None
return resolved_waiter.wait(
self,
asynchronous=True,
break_when=break_when,
timeout=timeout,
on_timeout=on_timeout,
on_error=on_error,
progress=progress,
progress_label=progress_label,
)
assert resolved_waiter is not None
return resolved_waiter.wait(
self,
asynchronous=False,
break_when=break_when,
timeout=timeout,
on_timeout=on_timeout,
on_error=on_error,
progress=progress,
progress_label=progress_label,
)