jcmsuite 7.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of jcmsuite might be problematic. Click here for more details.

Files changed (119) hide show
  1. jcmsuite/__init__.py +22 -0
  2. jcmsuite/_build_info.py +4 -0
  3. jcmsuite/context/__init__.py +44 -0
  4. jcmsuite/context/interface_metadata.py +158 -0
  5. jcmsuite/context/models.py +213 -0
  6. jcmsuite/context/scope.py +210 -0
  7. jcmsuite/context/solver_context.py +569 -0
  8. jcmsuite/context/subprocess_tools.py +172 -0
  9. jcmsuite/contract.py +47 -0
  10. jcmsuite/daemon/__init__.py +19 -0
  11. jcmsuite/daemon/handler.py +925 -0
  12. jcmsuite/daemon/internal/__init__.py +4 -0
  13. jcmsuite/daemon/internal/bundle_protocol.py +64 -0
  14. jcmsuite/daemon/internal/handler_helpers.py +368 -0
  15. jcmsuite/daemon/internal/handler_resource_jobs.py +227 -0
  16. jcmsuite/daemon/internal/handler_wait.py +564 -0
  17. jcmsuite/daemon/models.py +349 -0
  18. jcmsuite/daemon/namespaces.py +250 -0
  19. jcmsuite/daemon/protocol.py +801 -0
  20. jcmsuite/daemon/resources.py +407 -0
  21. jcmsuite/daemon/scope.py +53 -0
  22. jcmsuite/daemon/transport.py +223 -0
  23. jcmsuite/editing/__init__.py +10 -0
  24. jcmsuite/editing/editor.py +274 -0
  25. jcmsuite/exceptions/__init__.py +32 -0
  26. jcmsuite/exceptions/errors.py +173 -0
  27. jcmsuite/geo/__init__.py +10 -0
  28. jcmsuite/geo/mesh.py +302 -0
  29. jcmsuite/info/__init__.py +10 -0
  30. jcmsuite/info/runtime_info.py +45 -0
  31. jcmsuite/internal/__init__.py +2 -0
  32. jcmsuite/internal/diagnostics.py +74 -0
  33. jcmsuite/internal/progress.py +80 -0
  34. jcmsuite/loaders/__init__.py +18 -0
  35. jcmsuite/loaders/blob_header.py +315 -0
  36. jcmsuite/loaders/cartesian_field_reader.py +249 -0
  37. jcmsuite/loaders/cartesian_fields.py +324 -0
  38. jcmsuite/loaders/nested_mapping.py +69 -0
  39. jcmsuite/loaders/powerflux.py +136 -0
  40. jcmsuite/loaders/table.py +637 -0
  41. jcmsuite/logging/__init__.py +22 -0
  42. jcmsuite/logging/runtime.py +210 -0
  43. jcmsuite/results/__init__.py +126 -0
  44. jcmsuite/results/artifacts.py +806 -0
  45. jcmsuite/results/discovery.py +82 -0
  46. jcmsuite/results/field_exports.py +1062 -0
  47. jcmsuite/results/field_payloads.py +453 -0
  48. jcmsuite/results/internal/__init__.py +4 -0
  49. jcmsuite/results/internal/export/__init__.py +4 -0
  50. jcmsuite/results/internal/export/common.py +56 -0
  51. jcmsuite/results/internal/export/pandas/__init__.py +4 -0
  52. jcmsuite/results/internal/export/pandas/common.py +165 -0
  53. jcmsuite/results/internal/export/pandas/payload.py +480 -0
  54. jcmsuite/results/internal/export/pandas/rows.py +484 -0
  55. jcmsuite/results/internal/export/preview.py +178 -0
  56. jcmsuite/results/internal/export/xarray/__init__.py +4 -0
  57. jcmsuite/results/internal/export/xarray/export.py +688 -0
  58. jcmsuite/results/internal/export/xarray/grouped.py +608 -0
  59. jcmsuite/results/internal/export/xarray/headers.py +290 -0
  60. jcmsuite/results/internal/export/xarray/runtime.py +99 -0
  61. jcmsuite/results/internal/export/xarray/shared.py +246 -0
  62. jcmsuite/results/internal/export/xarray/tabular.py +304 -0
  63. jcmsuite/results/internal/export/xarray/types.py +28 -0
  64. jcmsuite/results/internal/models/__init__.py +4 -0
  65. jcmsuite/results/internal/models/batch.py +1081 -0
  66. jcmsuite/results/internal/models/batch_postprocess.py +1728 -0
  67. jcmsuite/results/internal/models/bundle.py +343 -0
  68. jcmsuite/results/internal/models/core.py +556 -0
  69. jcmsuite/results/internal/models/submission.py +1157 -0
  70. jcmsuite/results/internal/resultbag/__init__.py +4 -0
  71. jcmsuite/results/internal/resultbag/access.py +489 -0
  72. jcmsuite/results/internal/resultbag/iteration.py +199 -0
  73. jcmsuite/results/internal/resultbag/query.py +226 -0
  74. jcmsuite/results/internal/resultbag/raw.py +407 -0
  75. jcmsuite/results/internal/resultbag/source_files.py +142 -0
  76. jcmsuite/results/internal/resultbag/store.py +881 -0
  77. jcmsuite/results/internal/resultbag/utils.py +258 -0
  78. jcmsuite/results/models.py +76 -0
  79. jcmsuite/results/opening.py +55 -0
  80. jcmsuite/results/pandas_export.py +325 -0
  81. jcmsuite/results/payloads.py +478 -0
  82. jcmsuite/results/postprocess.py +97 -0
  83. jcmsuite/results/postprocess_payloads.py +757 -0
  84. jcmsuite/results/postprocess_record.py +418 -0
  85. jcmsuite/results/resultbag.py +279 -0
  86. jcmsuite/results/resultbag_management.py +433 -0
  87. jcmsuite/results/structured_derivatives.py +387 -0
  88. jcmsuite/solve/__init__.py +10 -0
  89. jcmsuite/solve/daemon_bundle_staging.py +100 -0
  90. jcmsuite/solve/daemon_bundle_wait.py +89 -0
  91. jcmsuite/solve/orchestration.py +1576 -0
  92. jcmsuite/solve/orchestration_execution.py +180 -0
  93. jcmsuite/solve/orchestration_routing.py +128 -0
  94. jcmsuite/solve/orchestration_support.py +323 -0
  95. jcmsuite/solve/path_resolution.py +98 -0
  96. jcmsuite/solve/progress.py +20 -0
  97. jcmsuite/solve/solver.py +709 -0
  98. jcmsuite/solve/staging.py +264 -0
  99. jcmsuite/solve/types.py +25 -0
  100. jcmsuite/solve/working_dirs.py +227 -0
  101. jcmsuite/templates/__init__.py +11 -0
  102. jcmsuite/templates/converter.py +71 -0
  103. jcmsuite/templates/formatting.py +335 -0
  104. jcmsuite/templates/formatting_cli.py +47 -0
  105. jcmsuite/templates/rendering.py +666 -0
  106. jcmsuite/torch/__init__.py +25 -0
  107. jcmsuite/torch/autograd.py +488 -0
  108. jcmsuite/torch/coordinate_policy.py +82 -0
  109. jcmsuite/torch/core.py +312 -0
  110. jcmsuite/torch/results/__init__.py +51 -0
  111. jcmsuite/torch/types.py +84 -0
  112. jcmsuite/torch/validation.py +208 -0
  113. jcmsuite/torch/wrappers.py +4332 -0
  114. jcmsuite/view/__init__.py +10 -0
  115. jcmsuite/view/viewer.py +122 -0
  116. jcmsuite-7.4.2.dist-info/METADATA +180 -0
  117. jcmsuite-7.4.2.dist-info/RECORD +119 -0
  118. jcmsuite-7.4.2.dist-info/WHEEL +4 -0
  119. jcmsuite-7.4.2.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,925 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2001-2026 JCMwave GmbH
3
+
4
+ """Daemon lifecycle namespace for `jcmsuite`."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import os
10
+ from collections.abc import Coroutine, Sequence
11
+ from logging import Logger
12
+ from pathlib import Path
13
+ from types import TracebackType
14
+ from typing import TYPE_CHECKING, Literal, cast, overload
15
+
16
+ from ..context import SolverContext, resolve_context
17
+ from ..exceptions import (
18
+ BackendUnavailableError,
19
+ ConfigMappingError,
20
+ ContextConflictError,
21
+ RuntimeContextError,
22
+ SolveExecutionError,
23
+ )
24
+ from ..internal.diagnostics import trim_exception_traceback
25
+ from ..logging import TRACE, get_logger
26
+ from ..results import (
27
+ BatchSolveResult,
28
+ BatchSolveSubmission,
29
+ BundledSolveResult,
30
+ SolveExecutionLog,
31
+ SolveResult,
32
+ SolveSubmission,
33
+ )
34
+ from .internal.handler_helpers import WaitRequest as _WaitRequest
35
+ from .internal.handler_helpers import coerce_int as _coerce_int
36
+ from .internal.handler_helpers import coerce_log_message as _coerce_log_message
37
+ from .internal.handler_helpers import normalize_job_record as _normalize_job_record
38
+ from .internal.handler_helpers import (
39
+ normalize_status_values as _normalize_status_values,
40
+ )
41
+ from .internal.handler_helpers import (
42
+ resolve_result_base_dir as _resolve_result_base_dir,
43
+ )
44
+ from .internal.handler_resource_jobs import (
45
+ add_resource_internal as _add_resource_internal_impl,
46
+ )
47
+ from .internal.handler_resource_jobs import (
48
+ delete_resources_by_indices as _delete_resources_by_indices_impl,
49
+ )
50
+ from .internal.handler_resource_jobs import job_info_impl as _job_info_impl_internal
51
+ from .internal.handler_resource_jobs import kill_jobs_impl as _kill_jobs_impl_internal
52
+ from .internal.handler_resource_jobs import (
53
+ register_resource_with_daemon as _register_resource_with_daemon_impl,
54
+ )
55
+ from .internal.handler_resource_jobs import (
56
+ resource_info_impl as _resource_info_impl_internal,
57
+ )
58
+ from .internal.handler_resource_jobs import (
59
+ synchronize_resources as _synchronize_resources_impl,
60
+ )
61
+ from .internal.handler_wait import resolve_job_ids as _resolve_job_ids_impl
62
+ from .internal.handler_wait import (
63
+ restore_pending_jobs_from_submission as _restore_pending_jobs_from_submission_impl,
64
+ )
65
+ from .internal.handler_wait import (
66
+ restore_single_pending_job as _restore_single_pending_job_impl,
67
+ )
68
+ from .internal.handler_wait import wait as _wait_impl_public
69
+ from .internal.handler_wait import wait_fallback_impl as _wait_fallback_impl_internal
70
+ from .internal.handler_wait import wait_impl as _wait_impl_internal
71
+ from .internal.handler_wait import wait_transport_impl as _wait_transport_impl_internal
72
+ from .internal.handler_wait import wait_with_request as _wait_with_request_impl
73
+ from .models import DaemonResource, DaemonStatus, PendingDaemonJob
74
+ from .namespaces import DaemonEnvironment, DaemonJobs, DaemonLifecycle
75
+ from .protocol import (
76
+ build_daemon_status_command,
77
+ build_shutdown_command,
78
+ build_submit_job_command,
79
+ extract_return_value,
80
+ )
81
+ from .resources import DaemonResources
82
+ from .scope import (
83
+ _pop_current_daemon_handler,
84
+ _push_current_daemon_handler,
85
+ get_current_daemon_handler,
86
+ )
87
+ from .transport import (
88
+ DaemonTransportConnection,
89
+ close_daemon_connection,
90
+ send_daemon_message,
91
+ start_daemon_service,
92
+ )
93
+
94
+ _logger: Logger = get_logger(__name__)
95
+ _MODULE_PATCH_EXPORTS: tuple[object, ...] = ( # test patch points
96
+ asyncio,
97
+ _coerce_log_message,
98
+ _normalize_job_record,
99
+ _normalize_status_values,
100
+ _resolve_result_base_dir,
101
+ )
102
+
103
+ WaitBreakWhen = Literal["all", "any"]
104
+ WaitOnTimeout = Literal["raise", "return"]
105
+ WaitOnError = Literal["raise", "collect"]
106
+
107
+
108
+ if TYPE_CHECKING:
109
+ from ..results import Resultbag
110
+
111
+
112
+ class DaemonHandler:
113
+ """Control the JCMsuite daemon.
114
+
115
+ Parameters
116
+ ----------
117
+ context : SolverContext
118
+ JCMsuite settings for the daemon.
119
+
120
+ Attributes
121
+ ----------
122
+ context : SolverContext
123
+ Context that supplies the daemon installation and runtime settings.
124
+ lifecycle : DaemonLifecycle
125
+ Namespace for starting, stopping, and inspecting the daemon lifecycle.
126
+ resources : DaemonResources
127
+ Namespace for adding, listing, inspecting, and deleting resources.
128
+ jobs : DaemonJobs
129
+ Namespace for waiting on and managing daemon jobs.
130
+
131
+ Notes
132
+ -----
133
+ Get a handler from `jcmsuite.daemon.handler(...)`. If you use the handler
134
+ in a `with` block, the block starts and connects the daemon. The block also
135
+ disconnects and stops the daemon when the block ends.
136
+ """
137
+
138
+ context: SolverContext
139
+ resources: DaemonResources
140
+ lifecycle: DaemonLifecycle
141
+ jobs: DaemonJobs
142
+
143
+ def __init__(self, *, context: SolverContext) -> None:
144
+ self.context: SolverContext = context
145
+ self._started: bool = False
146
+ self._connected: bool = False
147
+ self._resources: list[DaemonResource] = []
148
+ self._resource_remote_ids: list[tuple[int, ...] | None] = []
149
+ self.resources: DaemonResources = DaemonResources(handler=self)
150
+ self.lifecycle: DaemonLifecycle = DaemonLifecycle(handler=self)
151
+ self.jobs: DaemonJobs = DaemonJobs(handler=self)
152
+ self.environment: DaemonEnvironment = DaemonEnvironment(handler=self)
153
+ self._transport_connection: DaemonTransportConnection | None = None
154
+ self._pending_jobs: dict[int, PendingDaemonJob] = {}
155
+ self._next_job_id: int = 1
156
+ self._completed_jobs: dict[int, tuple[PendingDaemonJob, str]] = {}
157
+
158
+ def __enter__(self) -> "DaemonHandler":
159
+ """Enter scoped daemon lifecycle context.
160
+
161
+ The handler is started/connected and bound as task-local daemon scope.
162
+ """
163
+
164
+ self.start()
165
+ self.connect()
166
+ _push_current_daemon_handler(self)
167
+ return self
168
+
169
+ def __exit__(
170
+ self,
171
+ exc_type: type[BaseException] | None,
172
+ exc: BaseException | None,
173
+ tb: TracebackType | None,
174
+ ) -> None:
175
+ """Leave scoped daemon lifecycle context and shutdown connection."""
176
+
177
+ del exc_type, exc, tb
178
+ _pop_current_daemon_handler()
179
+ self.disconnect()
180
+ self.shutdown()
181
+
182
+ def start(self) -> None:
183
+ """Start the JCMsuite daemon service.
184
+
185
+ Returns
186
+ -------
187
+ None
188
+ The daemon service is ready for a connection.
189
+
190
+ Raises
191
+ ------
192
+ RuntimeContextError
193
+ If `JCMsolve` is not available.
194
+ """
195
+
196
+ if self._started:
197
+ return
198
+
199
+ solve_binary: Path | None = self.context.jcm_solve
200
+ if solve_binary is None or not solve_binary.is_file():
201
+ raise RuntimeContextError(
202
+ "JCMsolve binary is not available; cannot start daemon service."
203
+ )
204
+
205
+ try:
206
+ self._transport_connection = start_daemon_service(
207
+ jcm_solve_binary=solve_binary,
208
+ calling_pid=os.getpid(),
209
+ )
210
+ _logger.log(
211
+ TRACE,
212
+ "Daemon transport started at %s.",
213
+ self._transport_connection.url,
214
+ )
215
+ except Exception:
216
+ # Unit tests and CI frequently run without a live daemon endpoint.
217
+ # In that environment we keep deterministic in-memory behavior while
218
+ # still exposing the real transport path when daemon startup succeeds.
219
+ _logger.debug(
220
+ "Daemon transport startup unavailable; using fallback daemon mode.",
221
+ exc_info=True,
222
+ )
223
+ self._transport_connection = None
224
+ self._started = True
225
+
226
+ def connect(self) -> None:
227
+ """Connect the handler to the daemon.
228
+
229
+ This method starts the daemon first if necessary. It also registers
230
+ resources that were added before the connection.
231
+
232
+ Returns
233
+ -------
234
+ None
235
+ The handler is connected to the daemon.
236
+ """
237
+
238
+ if not self._started:
239
+ self.start()
240
+ self._connected = True
241
+ self._synchronize_resources()
242
+
243
+ def disconnect(self) -> None:
244
+ """Disconnect from the daemon without removing resource settings.
245
+
246
+ Returns
247
+ -------
248
+ None
249
+ The connection is closed. Registered resource settings remain in
250
+ the handler.
251
+ """
252
+
253
+ close_daemon_connection(self._transport_connection)
254
+ self._transport_connection = None
255
+ self._resource_remote_ids = [None for _ in self._resources]
256
+ self._connected = False
257
+
258
+ def _submit_solve_job(
259
+ self,
260
+ *,
261
+ result: object,
262
+ project_file: Path | Sequence[Path],
263
+ keys: dict[str, object] | None = None,
264
+ resultbag: Resultbag | None = None,
265
+ suffix_pattern: str | None = None,
266
+ source_project_mappings: tuple[tuple[Path, Path], ...] = (),
267
+ mode: Literal["solve", "postprocess"] = "solve",
268
+ ) -> int:
269
+ """Submit one project or ordered bundle and track its pending result."""
270
+
271
+ if not self._connected:
272
+ raise BackendUnavailableError(
273
+ "Cannot submit daemon job: daemon handler is not connected."
274
+ )
275
+ pending_job: PendingDaemonJob = PendingDaemonJob(
276
+ result=result,
277
+ keys=None if keys is None else dict(keys),
278
+ resultbag=resultbag,
279
+ suffix_pattern=suffix_pattern,
280
+ source_project_mappings=source_project_mappings,
281
+ )
282
+ if self._transport_connection is None:
283
+ fallback_job_id: int = self._register_completed_job(
284
+ pending_job=pending_job,
285
+ log="Finished: project prepared and queued via fallback daemon mode.",
286
+ )
287
+ self._track_resultbag_job_id(
288
+ job_id=fallback_job_id,
289
+ pending_job=pending_job,
290
+ )
291
+ return fallback_job_id
292
+
293
+ native_mode: str = "post_process" if mode == "postprocess" else "solve"
294
+ submit_command: str = build_submit_job_command(
295
+ project_file=project_file, mode=native_mode
296
+ )
297
+ daemon_response: str = self._send_transport_command(submit_command)
298
+ daemon_job_id: int = _coerce_int(
299
+ extract_return_value(daemon_response),
300
+ field_name="daemon job id",
301
+ )
302
+ self._pending_jobs[daemon_job_id] = pending_job
303
+ self._track_resultbag_job_id(job_id=daemon_job_id, pending_job=pending_job)
304
+ return daemon_job_id
305
+
306
+ def status(self) -> DaemonStatus:
307
+ """Return the current daemon status.
308
+
309
+ Returns
310
+ -------
311
+ DaemonStatus
312
+ Information about the connection and registered resources.
313
+ """
314
+
315
+ daemon_payload: object | None = None
316
+ if self._connected and self._transport_connection is not None:
317
+ try:
318
+ daemon_payload = extract_return_value(
319
+ self._send_transport_command(build_daemon_status_command())
320
+ )
321
+ except Exception:
322
+ _logger.debug(
323
+ "DaemonStatus command failed; returning local lifecycle snapshot.",
324
+ exc_info=True,
325
+ )
326
+ return DaemonStatus(
327
+ started=self._started,
328
+ connected=self._connected,
329
+ resources=tuple(self._resources),
330
+ daemon_payload=daemon_payload,
331
+ )
332
+
333
+ @overload
334
+ def wait(
335
+ self,
336
+ submission: SolveSubmission,
337
+ *,
338
+ asynchronous: Literal[False] = False,
339
+ break_when: WaitBreakWhen = "all",
340
+ timeout: float | None = None,
341
+ on_timeout: WaitOnTimeout = "raise",
342
+ on_error: WaitOnError = "raise",
343
+ progress: bool = False,
344
+ progress_label: str | None = None,
345
+ ) -> SolveResult: ...
346
+
347
+ @overload
348
+ def wait(
349
+ self,
350
+ submission: BatchSolveSubmission,
351
+ *,
352
+ asynchronous: Literal[False] = False,
353
+ break_when: WaitBreakWhen = "all",
354
+ timeout: float | None = None,
355
+ on_timeout: WaitOnTimeout = "raise",
356
+ on_error: WaitOnError = "raise",
357
+ progress: bool = False,
358
+ progress_label: str | None = None,
359
+ ) -> BatchSolveResult: ...
360
+
361
+ @overload
362
+ def wait(
363
+ self,
364
+ submission: SolveSubmission,
365
+ *,
366
+ asynchronous: Literal[True],
367
+ break_when: WaitBreakWhen = "all",
368
+ timeout: float | None = None,
369
+ on_timeout: WaitOnTimeout = "raise",
370
+ on_error: WaitOnError = "raise",
371
+ progress: bool = False,
372
+ progress_label: str | None = None,
373
+ ) -> Coroutine[object, object, SolveResult]: ...
374
+
375
+ @overload
376
+ def wait(
377
+ self,
378
+ submission: BatchSolveSubmission,
379
+ *,
380
+ asynchronous: Literal[True],
381
+ break_when: WaitBreakWhen = "all",
382
+ timeout: float | None = None,
383
+ on_timeout: WaitOnTimeout = "raise",
384
+ on_error: WaitOnError = "raise",
385
+ progress: bool = False,
386
+ progress_label: str | None = None,
387
+ ) -> Coroutine[object, object, BatchSolveResult]: ...
388
+
389
+ def wait(
390
+ self,
391
+ submission: SolveSubmission | BatchSolveSubmission,
392
+ *,
393
+ asynchronous: bool = False,
394
+ break_when: WaitBreakWhen = "all",
395
+ timeout: float | None = None,
396
+ on_timeout: WaitOnTimeout = "raise",
397
+ on_error: WaitOnError = "raise",
398
+ progress: bool = False,
399
+ progress_label: str | None = None,
400
+ ) -> (
401
+ SolveResult
402
+ | BatchSolveResult
403
+ | Coroutine[object, object, SolveResult | BatchSolveResult]
404
+ ):
405
+ """Wait for a daemon submission and return its results.
406
+
407
+ Parameters
408
+ ----------
409
+ submission : SolveSubmission | BatchSolveSubmission
410
+ submission returned by `solve(..., dispatch="submit")`.
411
+ asynchronous : bool, optional
412
+ If `True`, return a value that you must use with `await`.
413
+ break_when : {"all", "any"}, optional
414
+ Completion condition. `"all"` waits for all requested solves.
415
+ `"any"` returns after the first requested solve finishes.
416
+ timeout : float | None, optional
417
+ Maximum number of seconds to wait. If omitted, wait without a time
418
+ limit.
419
+ on_timeout : {"raise", "return"}, optional
420
+ Action at the time limit. `"raise"` raises an error. `"return"`
421
+ returns the results that are available.
422
+ on_error : {"raise", "collect"}, optional
423
+ Action for a failed batch entry. `"raise"` raises an error.
424
+ `"collect"` stores the failure in the batch result.
425
+ progress : bool, optional
426
+ If `True`, show progress for a batch wait.
427
+ progress_label : str | None, optional
428
+ Label for the progress display.
429
+
430
+ Returns
431
+ -------
432
+ SolveResult | BatchSolveResult | Coroutine[...]
433
+ Result that matches the submission. If `asynchronous=True`, return
434
+ a value that you must use with `await`.
435
+
436
+ Raises
437
+ ------
438
+ ConfigMappingError
439
+ If the daemon reports an input error with a source position. The
440
+ `SolveExecutionError` cause retains the solver diagnostics.
441
+ SolveExecutionError
442
+ If a solve fails and `on_error` is `"raise"`. The traceback omits
443
+ deep internal daemon frames.
444
+ """
445
+
446
+ if asynchronous:
447
+ wait_coro: Coroutine[object, object, SolveResult | BatchSolveResult] = cast(
448
+ Coroutine[object, object, SolveResult | BatchSolveResult],
449
+ _wait_impl_public(
450
+ self,
451
+ submission,
452
+ asynchronous=True,
453
+ break_when=break_when,
454
+ timeout=timeout,
455
+ on_timeout=on_timeout,
456
+ on_error=on_error,
457
+ progress=progress,
458
+ progress_label=progress_label,
459
+ ),
460
+ )
461
+
462
+ async def _wait_asynchronously() -> SolveResult | BatchSolveResult:
463
+ try:
464
+ return await wait_coro
465
+ except ConfigMappingError as error:
466
+ cause: BaseException | None = (
467
+ error.__cause__
468
+ if isinstance(error.__cause__, SolveExecutionError)
469
+ else None
470
+ )
471
+ raise trim_exception_traceback(error) from cause
472
+ except SolveExecutionError as error:
473
+ raise trim_exception_traceback(error) from None
474
+
475
+ return _wait_asynchronously()
476
+
477
+ try:
478
+ return _wait_impl_public(
479
+ self,
480
+ submission,
481
+ asynchronous=False,
482
+ break_when=break_when,
483
+ timeout=timeout,
484
+ on_timeout=on_timeout,
485
+ on_error=on_error,
486
+ progress=progress,
487
+ progress_label=progress_label,
488
+ )
489
+ except SolveExecutionError as error:
490
+ raise trim_exception_traceback(error) from None
491
+ except ConfigMappingError as error:
492
+ cause: BaseException | None = (
493
+ error.__cause__
494
+ if isinstance(error.__cause__, SolveExecutionError)
495
+ else None
496
+ )
497
+ raise trim_exception_traceback(error) from cause
498
+
499
+ def shutdown(self) -> None:
500
+ """Disconnect and stop the JCMsuite daemon.
501
+
502
+ Returns
503
+ -------
504
+ None
505
+ The daemon is stopped.
506
+ """
507
+
508
+ if self._transport_connection is not None and self._connected:
509
+ try:
510
+ _ = self._send_transport_command(
511
+ build_shutdown_command(),
512
+ get_answer=False,
513
+ )
514
+ except Exception:
515
+ _logger.debug(
516
+ "Daemon shutdown command failed; forcing local disconnect.",
517
+ exc_info=True,
518
+ )
519
+ self.disconnect()
520
+ self._started = False
521
+
522
+ def _register_completed_job(
523
+ self, *, pending_job: PendingDaemonJob, log: str
524
+ ) -> int:
525
+ """Register a completed daemon submission in the wait cache.
526
+
527
+ This is an internal orchestration hook used by solve-daemon routing.
528
+ """
529
+
530
+ job_id: int = self._next_job_id
531
+ self._next_job_id += 1
532
+ self._completed_jobs[job_id] = (pending_job, log)
533
+ return job_id
534
+
535
+ def _job_info_impl(
536
+ self,
537
+ *,
538
+ job_ids: Sequence[str | int] | None,
539
+ status_only: bool,
540
+ ) -> object:
541
+ """Return submission information using daemon transport or fallback cache."""
542
+
543
+ return _job_info_impl_internal(
544
+ self,
545
+ job_ids=job_ids,
546
+ status_only=status_only,
547
+ )
548
+
549
+ def _resource_info_impl(
550
+ self,
551
+ *,
552
+ resource_indices: Sequence[int],
553
+ fallback_resources: tuple[DaemonResource, ...],
554
+ ) -> object:
555
+ """Return resource information payload from daemon or local fallback."""
556
+
557
+ return _resource_info_impl_internal(
558
+ self,
559
+ resource_indices=resource_indices,
560
+ fallback_resources=fallback_resources,
561
+ )
562
+
563
+ def _kill_jobs_impl(
564
+ self,
565
+ *,
566
+ job_ids: Sequence[str | int] | None,
567
+ ) -> tuple[int, ...]:
568
+ """Close selected jobs and release local tracking handles."""
569
+
570
+ return _kill_jobs_impl_internal(
571
+ self,
572
+ job_ids=job_ids,
573
+ )
574
+
575
+ def _restore_pending_jobs_from_submission(self, wait_request: _WaitRequest) -> None:
576
+ """Rehydrate missing pending-cache entries from submission handles."""
577
+
578
+ _restore_pending_jobs_from_submission_impl(self, wait_request)
579
+
580
+ def _restore_single_pending_job(self, submission: SolveSubmission) -> None:
581
+ """Insert one pending-cache entry from a submitted solve handle."""
582
+
583
+ _restore_single_pending_job_impl(self, submission)
584
+
585
+ async def _wait_with_request(
586
+ self,
587
+ *,
588
+ wait_request: _WaitRequest,
589
+ break_when: WaitBreakWhen,
590
+ timeout: float | None,
591
+ on_timeout: WaitOnTimeout,
592
+ on_error: WaitOnError,
593
+ progress: bool,
594
+ progress_label: str | None,
595
+ ) -> SolveResult | BatchSolveResult:
596
+ """Wait and convert daemon outputs according to request input shape."""
597
+
598
+ return await _wait_with_request_impl(
599
+ self,
600
+ wait_request=wait_request,
601
+ break_when=break_when,
602
+ timeout=timeout,
603
+ on_timeout=on_timeout,
604
+ on_error=on_error,
605
+ progress=progress,
606
+ progress_label=progress_label,
607
+ )
608
+
609
+ async def _wait_impl(
610
+ self,
611
+ *,
612
+ job_ids: Sequence[str | int] | None,
613
+ break_when: WaitBreakWhen,
614
+ timeout: float | None,
615
+ on_timeout: WaitOnTimeout,
616
+ on_error: WaitOnError,
617
+ progress: bool,
618
+ progress_label: str | None,
619
+ ) -> tuple[list[object], list[str | None]]:
620
+ """Collect daemon submission results and release completed handles."""
621
+
622
+ return await _wait_impl_internal(
623
+ self,
624
+ job_ids=job_ids,
625
+ break_when=break_when,
626
+ timeout=timeout,
627
+ on_timeout=on_timeout,
628
+ on_error=on_error,
629
+ progress=progress,
630
+ progress_label=progress_label,
631
+ )
632
+
633
+ def _wait_fallback_impl(
634
+ self,
635
+ *,
636
+ job_ids: Sequence[str | int] | None,
637
+ ) -> tuple[list[object], list[str | None]]:
638
+ """Collect cached fallback daemon submission results and release them."""
639
+
640
+ return _wait_fallback_impl_internal(self, job_ids=job_ids)
641
+
642
+ async def _wait_transport_impl(
643
+ self,
644
+ *,
645
+ job_ids: Sequence[str | int] | None,
646
+ break_when: WaitBreakWhen,
647
+ timeout: float | None,
648
+ on_timeout: WaitOnTimeout,
649
+ on_error: WaitOnError,
650
+ progress: bool,
651
+ progress_label: str | None = None,
652
+ ) -> tuple[list[object], list[str | None]]:
653
+ """Collect daemon transport submission results through `JobInfo` polling."""
654
+
655
+ return await _wait_transport_impl_internal(
656
+ self,
657
+ job_ids=job_ids,
658
+ break_when=break_when,
659
+ timeout=timeout,
660
+ on_timeout=on_timeout,
661
+ on_error=on_error,
662
+ progress=progress,
663
+ progress_label=progress_label,
664
+ )
665
+
666
+ def _resolve_job_ids(
667
+ self,
668
+ *,
669
+ raw_job_ids: Sequence[str | int] | None,
670
+ available_job_ids: Sequence[int],
671
+ ) -> list[int]:
672
+ """Normalize and validate requested daemon submission identifiers."""
673
+
674
+ return _resolve_job_ids_impl(
675
+ self,
676
+ raw_job_ids=raw_job_ids,
677
+ available_job_ids=available_job_ids,
678
+ )
679
+
680
+ def _synchronize_resources(self) -> None:
681
+ """Register any local resources that are not yet registered remotely.
682
+
683
+ Returns
684
+ -------
685
+ None
686
+ Updates ``_resource_remote_ids`` in-place when registrations
687
+ succeed.
688
+
689
+ Notes
690
+ -----
691
+ Internal API: this helper is an implementation detail and may change
692
+ without notice.
693
+ """
694
+
695
+ _synchronize_resources_impl(self)
696
+
697
+ def _register_resource_with_daemon(
698
+ self,
699
+ resource: DaemonResource,
700
+ ) -> tuple[int, ...] | None:
701
+ """Send one resource declaration to the daemon.
702
+
703
+ Parameters
704
+ ----------
705
+ resource : DaemonResource
706
+ Resource description to register on the active daemon connection.
707
+
708
+ Returns
709
+ -------
710
+ tuple[int, ...] | None
711
+ Remote resource identifier tuple returned by the daemon, or
712
+ ``None`` when no transport is connected.
713
+
714
+ Notes
715
+ -----
716
+ Internal API: this helper is an implementation detail and may change
717
+ without notice.
718
+ """
719
+
720
+ return _register_resource_with_daemon_impl(self, resource)
721
+
722
+ def _add_resource_internal(self, resource: DaemonResource) -> DaemonResource:
723
+ """Store one resource declaration and register when connected."""
724
+
725
+ return _add_resource_internal_impl(self, resource)
726
+
727
+ def _delete_resources_by_indices(
728
+ self, indices: Sequence[int]
729
+ ) -> tuple[DaemonResource, ...]:
730
+ """Delete resources by absolute index values and return removed entries."""
731
+
732
+ return _delete_resources_by_indices_impl(self, indices)
733
+
734
+ def _send_transport_command(
735
+ self,
736
+ command: str,
737
+ *,
738
+ get_answer: bool = True,
739
+ ) -> str:
740
+ """Send transport command.
741
+
742
+ Parameters
743
+ ----------
744
+ command : str
745
+ Command tokens executed or forwarded to backend transport.
746
+ get_answer : bool
747
+ Whether the daemon should return a response payload for this
748
+ command.
749
+
750
+ Returns
751
+ -------
752
+ str
753
+ Normalized string value.
754
+
755
+ Notes
756
+ -----
757
+ Internal API: this helper is an implementation detail and may change
758
+ without notice.
759
+ """
760
+
761
+ if self._transport_connection is None:
762
+ raise BackendUnavailableError(
763
+ "Daemon transport is not available for command execution."
764
+ )
765
+ daemon_answer: str | None = send_daemon_message(
766
+ connection=self._transport_connection,
767
+ message=command,
768
+ get_answer=get_answer,
769
+ )
770
+ return "" if daemon_answer is None else daemon_answer
771
+
772
+ def _track_resultbag_job_id(
773
+ self,
774
+ *,
775
+ job_id: int,
776
+ pending_job: PendingDaemonJob,
777
+ ) -> None:
778
+ """Track a Resultbag submission identifier.
779
+
780
+ Parameters
781
+ ----------
782
+ job_id : int
783
+ Submission identifier value(s) used for lookup and validation.
784
+ pending_job : PendingDaemonJob
785
+ Pending submission record that may carry Resultbag metadata and project keys.
786
+
787
+ Returns
788
+ -------
789
+ None
790
+ Stores the daemon submission identifier in the configured Resultbag when project-key data
791
+ is available.
792
+
793
+ Notes
794
+ -----
795
+ Internal API: this helper is an implementation detail and may change
796
+ without notice.
797
+ """
798
+
799
+ if pending_job.resultbag is None or pending_job.keys is None:
800
+ return
801
+ pending_job.resultbag.management.bind_job(
802
+ keys=pending_job.keys,
803
+ job_id=job_id,
804
+ suffix_pattern=pending_job.suffix_pattern,
805
+ )
806
+
807
+ def _persist_resultbag_entry_if_needed(
808
+ self,
809
+ *,
810
+ job_id: int,
811
+ pending_job: PendingDaemonJob,
812
+ log_message: str,
813
+ ) -> None:
814
+ """Persist resultbag entry if needed.
815
+
816
+ Parameters
817
+ ----------
818
+ job_id : int
819
+ Submission identifier value(s) used for lookup and validation.
820
+ pending_job : PendingDaemonJob
821
+ Pending submission record containing the solve result and optional
822
+ resultbag handle.
823
+ log_message : str
824
+ Daemon log payload to persist alongside the stored result.
825
+
826
+ Returns
827
+ -------
828
+ None
829
+ Persists and releases the resultbag entry when a resultbag is
830
+ configured.
831
+
832
+ Notes
833
+ -----
834
+ Internal API: this helper is an implementation detail and may change
835
+ without notice.
836
+ """
837
+
838
+ if pending_job.resultbag is None:
839
+ return
840
+ pending_job.resultbag.management.store_job_result(
841
+ job_id=job_id,
842
+ result=pending_job.result,
843
+ log=log_message,
844
+ )
845
+
846
+ def _attach_daemon_log_to_result(
847
+ self,
848
+ *,
849
+ pending_job: PendingDaemonJob,
850
+ log_message: str,
851
+ ) -> None:
852
+ """Attach daemon execution log payload to tracked solve results."""
853
+
854
+ results: tuple[SolveResult, ...]
855
+ if isinstance(pending_job.result, BundledSolveResult):
856
+ results = tuple(pending_job.result)
857
+ for result in results:
858
+ result.refresh_artifacts()
859
+ elif isinstance(pending_job.result, SolveResult):
860
+ results = (pending_job.result,)
861
+ else:
862
+ return
863
+ for result in results:
864
+ result.log = SolveExecutionLog(
865
+ backend="daemon",
866
+ stdout=log_message,
867
+ stderr="",
868
+ return_code=0,
869
+ streamed_to_console=False,
870
+ )
871
+
872
+
873
+ def handler(
874
+ *,
875
+ context: SolverContext | None = None,
876
+ ) -> DaemonHandler:
877
+ """Return the daemon handler for a context.
878
+
879
+ Parameters
880
+ ----------
881
+ context : SolverContext | None, optional
882
+ JCMsuite settings to use. If omitted, use the active context or the
883
+ default context.
884
+
885
+ Returns
886
+ -------
887
+ DaemonHandler
888
+ Daemon handler that belongs to the selected context.
889
+ """
890
+
891
+ resolved_context: SolverContext = resolve_context(context)
892
+ return resolved_context._get_or_create_daemon_handler()
893
+
894
+
895
+ def resolve_scoped_handler(
896
+ *,
897
+ context: SolverContext | None = None,
898
+ ) -> DaemonHandler | None:
899
+ """Resolve currently scoped daemon handler with optional context safety.
900
+
901
+ Parameters
902
+ ----------
903
+ context : SolverContext | None, optional
904
+ Optional explicit context expected by the caller.
905
+
906
+ Returns
907
+ -------
908
+ DaemonHandler | None
909
+ Currently scoped daemon handler, or ``None`` when no handler is active.
910
+
911
+ Raises
912
+ ------
913
+ ContextConflictError
914
+ If a scoped handler exists and explicit `context` does not match it.
915
+ """
916
+
917
+ scoped_handler: DaemonHandler | None = get_current_daemon_handler()
918
+ if scoped_handler is None:
919
+ return None
920
+
921
+ if context is not None and scoped_handler.context is not context:
922
+ raise ContextConflictError(
923
+ "Explicit context conflicts with active daemon handler scope."
924
+ )
925
+ return scoped_handler