Source code for jcmsuite.daemon.handler

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

"""Daemon lifecycle namespace for `jcmsuite`."""

from __future__ import annotations

import asyncio
import os
from collections.abc import Coroutine, Sequence
from logging import Logger
from pathlib import Path
from types import TracebackType
from typing import TYPE_CHECKING, Literal, cast, overload

from ..context import SolverContext, resolve_context
from ..exceptions import (
    BackendUnavailableError,
    ConfigMappingError,
    ContextConflictError,
    RuntimeContextError,
    SolveExecutionError,
)
from ..internal.diagnostics import trim_exception_traceback
from ..logging import TRACE, get_logger
from ..results import (
    BatchSolveResult,
    BatchSolveSubmission,
    BundledSolveResult,
    SolveExecutionLog,
    SolveResult,
    SolveSubmission,
)
from .internal.handler_helpers import WaitRequest as _WaitRequest
from .internal.handler_helpers import coerce_int as _coerce_int
from .internal.handler_helpers import coerce_log_message as _coerce_log_message
from .internal.handler_helpers import normalize_job_record as _normalize_job_record
from .internal.handler_helpers import (
    normalize_status_values as _normalize_status_values,
)
from .internal.handler_helpers import (
    resolve_result_base_dir as _resolve_result_base_dir,
)
from .internal.handler_resource_jobs import (
    add_resource_internal as _add_resource_internal_impl,
)
from .internal.handler_resource_jobs import (
    delete_resources_by_indices as _delete_resources_by_indices_impl,
)
from .internal.handler_resource_jobs import job_info_impl as _job_info_impl_internal
from .internal.handler_resource_jobs import kill_jobs_impl as _kill_jobs_impl_internal
from .internal.handler_resource_jobs import (
    register_resource_with_daemon as _register_resource_with_daemon_impl,
)
from .internal.handler_resource_jobs import (
    resource_info_impl as _resource_info_impl_internal,
)
from .internal.handler_resource_jobs import (
    synchronize_resources as _synchronize_resources_impl,
)
from .internal.handler_wait import resolve_job_ids as _resolve_job_ids_impl
from .internal.handler_wait import (
    restore_pending_jobs_from_submission as _restore_pending_jobs_from_submission_impl,
)
from .internal.handler_wait import (
    restore_single_pending_job as _restore_single_pending_job_impl,
)
from .internal.handler_wait import wait as _wait_impl_public
from .internal.handler_wait import wait_fallback_impl as _wait_fallback_impl_internal
from .internal.handler_wait import wait_impl as _wait_impl_internal
from .internal.handler_wait import wait_transport_impl as _wait_transport_impl_internal
from .internal.handler_wait import wait_with_request as _wait_with_request_impl
from .models import DaemonResource, DaemonStatus, PendingDaemonJob
from .namespaces import DaemonEnvironment, DaemonJobs, DaemonLifecycle
from .protocol import (
    build_daemon_status_command,
    build_shutdown_command,
    build_submit_job_command,
    extract_return_value,
)
from .resources import DaemonResources
from .scope import (
    _pop_current_daemon_handler,
    _push_current_daemon_handler,
    get_current_daemon_handler,
)
from .transport import (
    DaemonTransportConnection,
    close_daemon_connection,
    send_daemon_message,
    start_daemon_service,
)

_logger: Logger = get_logger(__name__)
_MODULE_PATCH_EXPORTS: tuple[object, ...] = (  # test patch points
    asyncio,
    _coerce_log_message,
    _normalize_job_record,
    _normalize_status_values,
    _resolve_result_base_dir,
)

WaitBreakWhen = Literal["all", "any"]
WaitOnTimeout = Literal["raise", "return"]
WaitOnError = Literal["raise", "collect"]


if TYPE_CHECKING:
    from ..results import Resultbag


[docs] class DaemonHandler: """Control the JCMsuite daemon. Parameters ---------- context : SolverContext JCMsuite settings for the daemon. Attributes ---------- context : SolverContext Context that supplies the daemon installation and runtime settings. lifecycle : DaemonLifecycle Namespace for starting, stopping, and inspecting the daemon lifecycle. resources : DaemonResources Namespace for adding, listing, inspecting, and deleting resources. jobs : DaemonJobs Namespace for waiting on and managing daemon jobs. Notes ----- Get a handler from `jcmsuite.daemon.handler(...)`. If you use the handler in a `with` block, the block starts and connects the daemon. The block also disconnects and stops the daemon when the block ends. """ context: SolverContext resources: DaemonResources lifecycle: DaemonLifecycle jobs: DaemonJobs def __init__(self, *, context: SolverContext) -> None: self.context: SolverContext = context self._started: bool = False self._connected: bool = False self._resources: list[DaemonResource] = [] self._resource_remote_ids: list[tuple[int, ...] | None] = [] self.resources: DaemonResources = DaemonResources(handler=self) self.lifecycle: DaemonLifecycle = DaemonLifecycle(handler=self) self.jobs: DaemonJobs = DaemonJobs(handler=self) self.environment: DaemonEnvironment = DaemonEnvironment(handler=self) self._transport_connection: DaemonTransportConnection | None = None self._pending_jobs: dict[int, PendingDaemonJob] = {} self._next_job_id: int = 1 self._completed_jobs: dict[int, tuple[PendingDaemonJob, str]] = {} def __enter__(self) -> "DaemonHandler": """Enter scoped daemon lifecycle context. The handler is started/connected and bound as task-local daemon scope. """ self.start() self.connect() _push_current_daemon_handler(self) return self def __exit__( self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, ) -> None: """Leave scoped daemon lifecycle context and shutdown connection.""" del exc_type, exc, tb _pop_current_daemon_handler() self.disconnect() self.shutdown()
[docs] def start(self) -> None: """Start the JCMsuite daemon service. Returns ------- None The daemon service is ready for a connection. Raises ------ RuntimeContextError If `JCMsolve` is not available. """ if self._started: return solve_binary: Path | None = self.context.jcm_solve if solve_binary is None or not solve_binary.is_file(): raise RuntimeContextError( "JCMsolve binary is not available; cannot start daemon service." ) try: self._transport_connection = start_daemon_service( jcm_solve_binary=solve_binary, calling_pid=os.getpid(), ) _logger.log( TRACE, "Daemon transport started at %s.", self._transport_connection.url, ) except Exception: # Unit tests and CI frequently run without a live daemon endpoint. # In that environment we keep deterministic in-memory behavior while # still exposing the real transport path when daemon startup succeeds. _logger.debug( "Daemon transport startup unavailable; using fallback daemon mode.", exc_info=True, ) self._transport_connection = None self._started = True
[docs] def connect(self) -> None: """Connect the handler to the daemon. This method starts the daemon first if necessary. It also registers resources that were added before the connection. Returns ------- None The handler is connected to the daemon. """ if not self._started: self.start() self._connected = True self._synchronize_resources()
[docs] def disconnect(self) -> None: """Disconnect from the daemon without removing resource settings. Returns ------- None The connection is closed. Registered resource settings remain in the handler. """ close_daemon_connection(self._transport_connection) self._transport_connection = None self._resource_remote_ids = [None for _ in self._resources] self._connected = False
def _submit_solve_job( self, *, result: object, project_file: Path | Sequence[Path], keys: dict[str, object] | None = None, resultbag: Resultbag | None = None, jcmt_pattern: str | None = None, source_project_mappings: tuple[tuple[Path, Path], ...] = (), mode: Literal["solve", "postprocess"] = "solve", ) -> int: """Submit one project or ordered bundle and track its pending result.""" if not self._connected: raise BackendUnavailableError( "Cannot submit daemon job: daemon handler is not connected." ) pending_job: PendingDaemonJob = PendingDaemonJob( result=result, keys=None if keys is None else dict(keys), resultbag=resultbag, jcmt_pattern=jcmt_pattern, source_project_mappings=source_project_mappings, ) if self._transport_connection is None: fallback_job_id: int = self._register_completed_job( pending_job=pending_job, log="Finished: project prepared and queued via fallback daemon mode.", ) self._track_resultbag_job_id( job_id=fallback_job_id, pending_job=pending_job, ) return fallback_job_id native_mode: str = "post_process" if mode == "postprocess" else "solve" submit_command: str = build_submit_job_command( project_file=project_file, mode=native_mode ) daemon_response: str = self._send_transport_command(submit_command) daemon_job_id: int = _coerce_int( extract_return_value(daemon_response), field_name="daemon job id", ) self._pending_jobs[daemon_job_id] = pending_job self._track_resultbag_job_id(job_id=daemon_job_id, pending_job=pending_job) return daemon_job_id
[docs] def status(self) -> DaemonStatus: """Return the current daemon status. Returns ------- DaemonStatus Information about the connection and registered resources. """ daemon_payload: object | None = None if self._connected and self._transport_connection is not None: try: daemon_payload = extract_return_value( self._send_transport_command(build_daemon_status_command()) ) except Exception: _logger.debug( "DaemonStatus command failed; returning local lifecycle snapshot.", exc_info=True, ) return DaemonStatus( started=self._started, connected=self._connected, resources=tuple(self._resources), daemon_payload=daemon_payload, )
@overload def wait( self, submission: SolveSubmission, *, asynchronous: Literal[False] = False, break_when: WaitBreakWhen = "all", timeout: float | None = None, on_timeout: WaitOnTimeout = "raise", on_error: WaitOnError = "raise", progress: bool = False, progress_label: str | None = None, ) -> SolveResult: ... @overload def wait( self, submission: BatchSolveSubmission, *, asynchronous: Literal[False] = False, break_when: WaitBreakWhen = "all", timeout: float | None = None, on_timeout: WaitOnTimeout = "raise", on_error: WaitOnError = "raise", progress: bool = False, progress_label: str | None = None, ) -> BatchSolveResult: ... @overload def wait( self, submission: SolveSubmission, *, asynchronous: Literal[True], break_when: WaitBreakWhen = "all", timeout: float | None = None, on_timeout: WaitOnTimeout = "raise", on_error: WaitOnError = "raise", progress: bool = False, progress_label: str | None = None, ) -> Coroutine[object, object, SolveResult]: ... @overload def wait( self, submission: BatchSolveSubmission, *, asynchronous: Literal[True], break_when: WaitBreakWhen = "all", timeout: float | None = None, on_timeout: WaitOnTimeout = "raise", on_error: WaitOnError = "raise", progress: bool = False, progress_label: str | None = None, ) -> Coroutine[object, object, BatchSolveResult]: ...
[docs] def wait( self, submission: SolveSubmission | BatchSolveSubmission, *, asynchronous: bool = False, break_when: WaitBreakWhen = "all", timeout: float | None = None, on_timeout: WaitOnTimeout = "raise", on_error: WaitOnError = "raise", progress: bool = False, progress_label: str | None = None, ) -> ( SolveResult | BatchSolveResult | Coroutine[object, object, SolveResult | BatchSolveResult] ): """Wait for a daemon submission and return its results. Parameters ---------- submission : SolveSubmission | BatchSolveSubmission submission returned by `solve(..., dispatch="submit")`. asynchronous : bool, optional If `True`, return a value that you must use with `await`. break_when : {"all", "any"}, optional Completion condition. `"all"` waits for all requested solves. `"any"` returns after the first requested solve finishes. timeout : float | None, optional Maximum number of seconds to wait. If omitted, wait without a time limit. on_timeout : {"raise", "return"}, optional Action at the time limit. `"raise"` raises an error. `"return"` returns the results that are available. on_error : {"raise", "collect"}, optional Action for a failed batch entry. `"raise"` raises an error. `"collect"` stores the failure in the batch result. progress : bool, optional If `True`, show progress for a batch wait. progress_label : str | None, optional Label for the progress display. Returns ------- SolveResult | BatchSolveResult | Coroutine[...] Result that matches the submission. If `asynchronous=True`, return a value that you must use with `await`. Raises ------ ConfigMappingError If the daemon reports an input error with a source position. The `SolveExecutionError` cause retains the solver diagnostics. SolveExecutionError If a solve fails and `on_error` is `"raise"`. The traceback omits deep internal daemon frames. """ if asynchronous: wait_coro: Coroutine[object, object, SolveResult | BatchSolveResult] = cast( Coroutine[object, object, SolveResult | BatchSolveResult], _wait_impl_public( self, submission, asynchronous=True, break_when=break_when, timeout=timeout, on_timeout=on_timeout, on_error=on_error, progress=progress, progress_label=progress_label, ), ) async def _wait_asynchronously() -> SolveResult | BatchSolveResult: try: return await wait_coro except ConfigMappingError as error: cause: BaseException | None = ( error.__cause__ if isinstance(error.__cause__, SolveExecutionError) else None ) raise trim_exception_traceback(error) from cause except SolveExecutionError as error: raise trim_exception_traceback(error) from None return _wait_asynchronously() try: return _wait_impl_public( self, submission, asynchronous=False, break_when=break_when, timeout=timeout, on_timeout=on_timeout, on_error=on_error, progress=progress, progress_label=progress_label, ) except SolveExecutionError as error: raise trim_exception_traceback(error) from None except ConfigMappingError as error: cause: BaseException | None = ( error.__cause__ if isinstance(error.__cause__, SolveExecutionError) else None ) raise trim_exception_traceback(error) from cause
[docs] def shutdown(self) -> None: """Disconnect and stop the JCMsuite daemon. Returns ------- None The daemon is stopped. """ if self._transport_connection is not None and self._connected: try: _ = self._send_transport_command( build_shutdown_command(), get_answer=False, ) except Exception: _logger.debug( "Daemon shutdown command failed; forcing local disconnect.", exc_info=True, ) self.disconnect() self._started = False
def _register_completed_job( self, *, pending_job: PendingDaemonJob, log: str ) -> int: """Register a completed daemon submission in the wait cache. This is an internal orchestration hook used by solve-daemon routing. """ job_id: int = self._next_job_id self._next_job_id += 1 self._completed_jobs[job_id] = (pending_job, log) return job_id def _job_info_impl( self, *, job_ids: Sequence[str | int] | None, status_only: bool, ) -> object: """Return submission information using daemon transport or fallback cache.""" return _job_info_impl_internal( self, job_ids=job_ids, status_only=status_only, ) def _resource_info_impl( self, *, resource_indices: Sequence[int], fallback_resources: tuple[DaemonResource, ...], ) -> object: """Return resource information payload from daemon or local fallback.""" return _resource_info_impl_internal( self, resource_indices=resource_indices, fallback_resources=fallback_resources, ) def _kill_jobs_impl( self, *, job_ids: Sequence[str | int] | None, ) -> tuple[int, ...]: """Close selected jobs and release local tracking handles.""" return _kill_jobs_impl_internal( self, job_ids=job_ids, ) def _restore_pending_jobs_from_submission(self, wait_request: _WaitRequest) -> None: """Rehydrate missing pending-cache entries from submission handles.""" _restore_pending_jobs_from_submission_impl(self, wait_request) def _restore_single_pending_job(self, submission: SolveSubmission) -> None: """Insert one pending-cache entry from a submitted solve handle.""" _restore_single_pending_job_impl(self, submission) async def _wait_with_request( self, *, wait_request: _WaitRequest, break_when: WaitBreakWhen, timeout: float | None, on_timeout: WaitOnTimeout, on_error: WaitOnError, progress: bool, progress_label: str | None, ) -> SolveResult | BatchSolveResult: """Wait and convert daemon outputs according to request input shape.""" return await _wait_with_request_impl( self, wait_request=wait_request, break_when=break_when, timeout=timeout, on_timeout=on_timeout, on_error=on_error, progress=progress, progress_label=progress_label, ) async def _wait_impl( self, *, job_ids: Sequence[str | int] | None, break_when: WaitBreakWhen, timeout: float | None, on_timeout: WaitOnTimeout, on_error: WaitOnError, progress: bool, progress_label: str | None, ) -> tuple[list[object], list[str | None]]: """Collect daemon submission results and release completed handles.""" return await _wait_impl_internal( self, job_ids=job_ids, break_when=break_when, timeout=timeout, on_timeout=on_timeout, on_error=on_error, progress=progress, progress_label=progress_label, ) def _wait_fallback_impl( self, *, job_ids: Sequence[str | int] | None, ) -> tuple[list[object], list[str | None]]: """Collect cached fallback daemon submission results and release them.""" return _wait_fallback_impl_internal(self, job_ids=job_ids) async def _wait_transport_impl( self, *, job_ids: Sequence[str | int] | None, break_when: WaitBreakWhen, timeout: float | None, on_timeout: WaitOnTimeout, on_error: WaitOnError, progress: bool, progress_label: str | None = None, ) -> tuple[list[object], list[str | None]]: """Collect daemon transport submission results through `JobInfo` polling.""" return await _wait_transport_impl_internal( self, job_ids=job_ids, break_when=break_when, timeout=timeout, on_timeout=on_timeout, on_error=on_error, progress=progress, progress_label=progress_label, ) def _resolve_job_ids( self, *, raw_job_ids: Sequence[str | int] | None, available_job_ids: Sequence[int], ) -> list[int]: """Normalize and validate requested daemon submission identifiers.""" return _resolve_job_ids_impl( self, raw_job_ids=raw_job_ids, available_job_ids=available_job_ids, ) def _synchronize_resources(self) -> None: """Register any local resources that are not yet registered remotely. Returns ------- None Updates ``_resource_remote_ids`` in-place when registrations succeed. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ _synchronize_resources_impl(self) def _register_resource_with_daemon( self, resource: DaemonResource, ) -> tuple[int, ...] | None: """Send one resource declaration to the daemon. Parameters ---------- resource : DaemonResource Resource description to register on the active daemon connection. Returns ------- tuple[int, ...] | None Remote resource identifier tuple returned by the daemon, or ``None`` when no transport is connected. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ return _register_resource_with_daemon_impl(self, resource) def _add_resource_internal(self, resource: DaemonResource) -> DaemonResource: """Store one resource declaration and register when connected.""" return _add_resource_internal_impl(self, resource) def _delete_resources_by_indices( self, indices: Sequence[int] ) -> tuple[DaemonResource, ...]: """Delete resources by absolute index values and return removed entries.""" return _delete_resources_by_indices_impl(self, indices) def _send_transport_command( self, command: str, *, get_answer: bool = True, ) -> str: """Send transport command. Parameters ---------- command : str Command tokens executed or forwarded to backend transport. get_answer : bool Whether the daemon should return a response payload for this command. Returns ------- str Normalized string value. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ if self._transport_connection is None: raise BackendUnavailableError( "Daemon transport is not available for command execution." ) daemon_answer: str | None = send_daemon_message( connection=self._transport_connection, message=command, get_answer=get_answer, ) return "" if daemon_answer is None else daemon_answer def _track_resultbag_job_id( self, *, job_id: int, pending_job: PendingDaemonJob, ) -> None: """Track a Resultbag submission identifier. Parameters ---------- job_id : int Submission identifier value(s) used for lookup and validation. pending_job : PendingDaemonJob Pending submission record that may carry Resultbag metadata and project keys. Returns ------- None Stores the daemon submission identifier in the configured Resultbag when project-key data is available. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ if pending_job.resultbag is None or pending_job.keys is None: return pending_job.resultbag.management.bind_job( keys=pending_job.keys, job_id=job_id, jcmt_pattern=pending_job.jcmt_pattern, ) def _persist_resultbag_entry_if_needed( self, *, job_id: int, pending_job: PendingDaemonJob, log_message: str, ) -> None: """Persist resultbag entry if needed. Parameters ---------- job_id : int Submission identifier value(s) used for lookup and validation. pending_job : PendingDaemonJob Pending submission record containing the solve result and optional resultbag handle. log_message : str Daemon log payload to persist alongside the stored result. Returns ------- None Persists and releases the resultbag entry when a resultbag is configured. Notes ----- Internal API: this helper is an implementation detail and may change without notice. """ if pending_job.resultbag is None: return pending_job.resultbag.management.store_job_result( job_id=job_id, result=pending_job.result, log=log_message, ) def _attach_daemon_log_to_result( self, *, pending_job: PendingDaemonJob, log_message: str, ) -> None: """Attach daemon execution log payload to tracked solve results.""" results: tuple[SolveResult, ...] if isinstance(pending_job.result, BundledSolveResult): results = tuple(pending_job.result) for result in results: result.refresh_artifacts() elif isinstance(pending_job.result, SolveResult): results = (pending_job.result,) else: return for result in results: result.log = SolveExecutionLog( backend="daemon", stdout=log_message, stderr="", return_code=0, streamed_to_console=False, )
[docs] def handler( *, context: SolverContext | None = None, ) -> DaemonHandler: """Return the daemon handler for a context. Parameters ---------- context : SolverContext | None, optional JCMsuite settings to use. If omitted, use the active context or the default context. Returns ------- DaemonHandler Daemon handler that belongs to the selected context. """ resolved_context: SolverContext = resolve_context(context) return resolved_context._get_or_create_daemon_handler()
def resolve_scoped_handler( *, context: SolverContext | None = None, ) -> DaemonHandler | None: """Resolve currently scoped daemon handler with optional context safety. Parameters ---------- context : SolverContext | None, optional Optional explicit context expected by the caller. Returns ------- DaemonHandler | None Currently scoped daemon handler, or ``None`` when no handler is active. Raises ------ ContextConflictError If a scoped handler exists and explicit `context` does not match it. """ scoped_handler: DaemonHandler | None = get_current_daemon_handler() if scoped_handler is None: return None if context is not None and scoped_handler.context is not context: raise ContextConflictError( "Explicit context conflicts with active daemon handler scope." ) return scoped_handler