httk-workflow 2.1.0__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.
Files changed (142) hide show
  1. httk/registry/cli/job/__init__.py +9 -0
  2. httk/registry/cli/project/__init__.py +11 -0
  3. httk/registry/cli/workflow/__init__.py +9 -0
  4. httk/registry/cli/workspace/__init__.py +9 -0
  5. httk/workflow/__init__.py +84 -0
  6. httk/workflow/_launcher.py +36 -0
  7. httk/workflow/_logging.py +205 -0
  8. httk/workflow/_manager_cancellation.py +225 -0
  9. httk/workflow/_manager_commit.py +602 -0
  10. httk/workflow/_manager_joins.py +187 -0
  11. httk/workflow/_manager_requests.py +386 -0
  12. httk/workflow/_manager_runners.py +270 -0
  13. httk/workflow/_manager_scheduling.py +382 -0
  14. httk/workflow/_runner_builds.py +171 -0
  15. httk/workflow/_shell_bridge.py +1180 -0
  16. httk/workflow/_util.py +241 -0
  17. httk/workflow/adapter_protocol.py +37 -0
  18. httk/workflow/adapter_runtime.py +536 -0
  19. httk/workflow/adapter_templates/local/adapter +2 -0
  20. httk/workflow/adapter_templates/local/remote.json +1 -0
  21. httk/workflow/adapter_templates/ssh/adapter +2 -0
  22. httk/workflow/adapter_templates/ssh/remote.json +1 -0
  23. httk/workflow/adapters.py +697 -0
  24. httk/workflow/campaigns.py +450 -0
  25. httk/workflow/collecting.py +1708 -0
  26. httk/workflow/compat/__init__.py +19 -0
  27. httk/workflow/compat/v1/__init__.py +78 -0
  28. httk/workflow/compat/v1/reader.py +374 -0
  29. httk/workflow/compat/v1/templates.py +170 -0
  30. httk/workflow/compat/v1/v1_runtime/Execution/tasks/ht_tasks_api.sh +8 -0
  31. httk/workflow/compat/v1/v1_runtime/Execution/tasks/vasp/vasptools.sh +8 -0
  32. httk/workflow/compat/v1/v1_runtime/LICENSE +661 -0
  33. httk/workflow/compat/v1/v1_runtime/NOTICE +39 -0
  34. httk/workflow/compat/v1/v1_runtime/README.md +20 -0
  35. httk/workflow/compat/v1/v1_runtime/compat/ht_tasks_api_v1.sh +619 -0
  36. httk/workflow/compat/v1/v1_runtime/compat/vasptools_v1.sh +1336 -0
  37. httk/workflow/configuration.py +243 -0
  38. httk/workflow/errors.py +70 -0
  39. httk/workflow/executors.py +161 -0
  40. httk/workflow/fsck.py +475 -0
  41. httk/workflow/gc.py +1136 -0
  42. httk/workflow/hookapi.py +118 -0
  43. httk/workflow/hygiene.py +389 -0
  44. httk/workflow/id_keys.py +96 -0
  45. httk/workflow/introspection/__init__.py +210 -0
  46. httk/workflow/introspection/_debug.py +387 -0
  47. httk/workflow/introspection/_diagnosis.py +1199 -0
  48. httk/workflow/introspection/_reading.py +651 -0
  49. httk/workflow/introspection/_rendering.py +320 -0
  50. httk/workflow/journal.py +445 -0
  51. httk/workflow/languages/__init__.py +311 -0
  52. httk/workflow/languages/cwl/__init__.py +1055 -0
  53. httk/workflow/languages/cwl/cwl_runner.py +1045 -0
  54. httk/workflow/languages/httk_v1/__init__.py +277 -0
  55. httk/workflow/languages/httk_v1/v1_runner.py +543 -0
  56. httk/workflow/languages/jobflow/__init__.py +299 -0
  57. httk/workflow/languages/jobflow/_driver.py +433 -0
  58. httk/workflow/languages/jobflow/jobflow_runner.py +488 -0
  59. httk/workflow/languages/pwd/__init__.py +475 -0
  60. httk/workflow/languages/pwd/pwd_runner.py +392 -0
  61. httk/workflow/launch_runtime.py +271 -0
  62. httk/workflow/launch_templates/slurm/launcher +2 -0
  63. httk/workflow/launch_templates/slurm/launcher.json +1 -0
  64. httk/workflow/launchers.py +592 -0
  65. httk/workflow/manager.py +2736 -0
  66. httk/workflow/manifests.py +383 -0
  67. httk/workflow/models.py +1599 -0
  68. httk/workflow/monitor/__init__.py +5 -0
  69. httk/workflow/monitor/actions.py +204 -0
  70. httk/workflow/monitor/data.py +411 -0
  71. httk/workflow/monitor/ui.py +641 -0
  72. httk/workflow/native/ada/httk_workflow.adb +435 -0
  73. httk/workflow/native/ada/httk_workflow.ads +105 -0
  74. httk/workflow/native/c/httk_workflow.c +620 -0
  75. httk/workflow/native/c/httk_workflow.h +264 -0
  76. httk/workflow/native/cpp/httk_workflow.hpp +294 -0
  77. httk/workflow/native/fortran/httk_workflow.f90 +1001 -0
  78. httk/workflow/native/java/HttkWorkflow.java +607 -0
  79. httk/workflow/native/perl/HttkWorkflow.pm +320 -0
  80. httk/workflow/native/rust/Cargo.toml +13 -0
  81. httk/workflow/native/rust/src/lib.rs +741 -0
  82. httk/workflow/packages.py +1058 -0
  83. httk/workflow/postprocessing.py +222 -0
  84. httk/workflow/precheck.py +491 -0
  85. httk/workflow/project_member.py +300 -0
  86. httk/workflow/projects.py +172 -0
  87. httk/workflow/protocol.py +170 -0
  88. httk/workflow/provenance.py +169 -0
  89. httk/workflow/py.typed +1 -0
  90. httk/workflow/registry.py +584 -0
  91. httk/workflow/removal.py +297 -0
  92. httk/workflow/runners/__init__.py +97 -0
  93. httk/workflow/runtime.py +300 -0
  94. httk/workflow/runtime_builders.py +1074 -0
  95. httk/workflow/runtime_utils.py +199 -0
  96. httk/workflow/scaffold.py +2295 -0
  97. httk/workflow/sdk.py +1501 -0
  98. httk/workflow/seals.py +421 -0
  99. httk/workflow/shell/httk-vasp.sh +132 -0
  100. httk/workflow/shell/httk-workflow.sh +391 -0
  101. httk/workflow/shell_bridge.py +42 -0
  102. httk/workflow/supervision.py +856 -0
  103. httk/workflow/transactions.py +209 -0
  104. httk/workflow/transfers.py +1247 -0
  105. httk/workflow/vasp/__init__.py +156 -0
  106. httk/workflow/vasp/collect.py +119 -0
  107. httk/workflow/vasp/diagnostics.py +277 -0
  108. httk/workflow/vasp/inputs.py +798 -0
  109. httk/workflow/vasp/remedies.py +573 -0
  110. httk/workflow/vasp/reports.py +159 -0
  111. httk/workflow/vasp/runners/__init__.py +98 -0
  112. httk/workflow/vasp/runners/scripts/relaxation_plot +104 -0
  113. httk/workflow/vasp/runners/scripts/relaxation_report +55 -0
  114. httk/workflow/vasp/runners/vasp_relax.py +354 -0
  115. httk/workflow/vasp/runners/vasp_relax.sh +181 -0
  116. httk/workflow/vasp/runners/vasp_relax_static.py +426 -0
  117. httk/workflow/vasp/runners/vasp_static.py +357 -0
  118. httk/workflow/vasp/workflows.py +250 -0
  119. httk/workflow/workflow_cli/__init__.py +363 -0
  120. httk/workflow/workflow_cli/__main__.py +11 -0
  121. httk/workflow/workflow_cli/_build.py +261 -0
  122. httk/workflow/workflow_cli/_campaign.py +455 -0
  123. httk/workflow/workflow_cli/_collect.py +780 -0
  124. httk/workflow/workflow_cli/_common.py +643 -0
  125. httk/workflow/workflow_cli/_compat.py +117 -0
  126. httk/workflow/workflow_cli/_describe.py +377 -0
  127. httk/workflow/workflow_cli/_job.py +2108 -0
  128. httk/workflow/workflow_cli/_launcher.py +242 -0
  129. httk/workflow/workflow_cli/_manager.py +834 -0
  130. httk/workflow/workflow_cli/_monitor.py +77 -0
  131. httk/workflow/workflow_cli/_postprocess.py +191 -0
  132. httk/workflow/workflow_cli/_precheck.py +159 -0
  133. httk/workflow/workflow_cli/_project.py +167 -0
  134. httk/workflow/workflow_cli/_seal.py +118 -0
  135. httk/workflow/workflow_cli/_transfer.py +1363 -0
  136. httk/workflow/workflow_cli/_workspace.py +1239 -0
  137. httk/workflow/workspace.py +1891 -0
  138. httk_workflow-2.1.0.dist-info/METADATA +177 -0
  139. httk_workflow-2.1.0.dist-info/RECORD +142 -0
  140. httk_workflow-2.1.0.dist-info/WHEEL +5 -0
  141. httk_workflow-2.1.0.dist-info/licenses/LICENSE +661 -0
  142. httk_workflow-2.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,9 @@
1
+ """Register the top-level job command."""
2
+
3
+ from httk.core.register import register_cli_command
4
+
5
+ register_cli_command(
6
+ "job",
7
+ "httk.workflow.workflow_cli:job_command",
8
+ "create and inspect workflow jobs",
9
+ )
@@ -0,0 +1,11 @@
1
+ """Teach core's project verbs how to handle a workflow workspace member.
2
+
3
+ Core owns ``httk project doctor|manifest|seal|unseal|verify-seal`` and delegates
4
+ a member's internals to the handler its kind registers. Registering the
5
+ ``"workspace"`` kind is what makes a workflow workspace a first-class project
6
+ member those verbs seal, exclude, verify, and check.
7
+ """
8
+
9
+ from httk.core.register.members import register_project_member_kind
10
+
11
+ register_project_member_kind("workspace", "httk.workflow.project_member:handler")
@@ -0,0 +1,9 @@
1
+ """Register CLI commands implemented by :mod:`httk.workflow`."""
2
+
3
+ from httk.core.register import register_cli_command
4
+
5
+ register_cli_command(
6
+ "workflow",
7
+ "httk.workflow.workflow_cli:workflow_command",
8
+ "manage filesystem-native workflows and projects",
9
+ )
@@ -0,0 +1,9 @@
1
+ """Register the top-level workspace command."""
2
+
3
+ from httk.core.register import register_cli_command
4
+
5
+ register_cli_command(
6
+ "workspace",
7
+ "httk.workflow.workflow_cli:workspace_command",
8
+ "manage workflow workspaces",
9
+ )
@@ -0,0 +1,84 @@
1
+ """Expose filesystem-native workflow execution for httk₂.
2
+
3
+ The package presents three layers, each with its own import home:
4
+
5
+ * **Filesystem protocol** — the language-neutral on-disk contract lives in
6
+ :mod:`httk.workflow.protocol`. Independent tools read and verify a workspace
7
+ through it and the specification alone.
8
+ * **Execution / authoring** — the surface a runner author uses. :class:`Runner`,
9
+ :class:`Attempt`, and the small set of job and result types below are exported
10
+ here; the lower-level runtime helpers live in :mod:`httk.workflow.runtime` and
11
+ :mod:`httk.workflow.runtime_utils`, and job scaffolding in
12
+ :mod:`httk.workflow.scaffold`.
13
+ * **Orchestration and management** — :class:`Workspace`, :class:`TaskManager`,
14
+ and :func:`job_records` drive and inspect a running workspace. The management
15
+ operations that surround them (transfers, manifests, hygiene, configuration,
16
+ adapters, supervision, and the VASP and v1 compatibility surfaces) live in
17
+ their own named submodules rather than in this root.
18
+
19
+ The normal lifecycle is instantiate a job, run it, then collect its outputs.
20
+ Only the deliberate top-level surface is re-exported here; everything else is
21
+ reached through its submodule.
22
+ """
23
+
24
+ from .collecting import CollectedJob, JobRecord, collect, job_records
25
+ from .errors import (
26
+ FormatError,
27
+ RunnerResolutionError,
28
+ TransactionError,
29
+ TransitionLostError,
30
+ UnsupportedExtensionError,
31
+ WorkflowError,
32
+ WorkspaceCorruptionError,
33
+ WorkspaceUnavailableError,
34
+ )
35
+ from .id_keys import UnstableIdentityError, ledger_key
36
+ from .manager import NotIdleError, TaskManager, WorkCensus
37
+ from .runtime_builders import JobState
38
+ from .scaffold import ScaffoldedJob, new_job, new_jobs, scaffold_job
39
+ from .sdk import (
40
+ Attempt,
41
+ ChildrenView,
42
+ ChildResult,
43
+ ChildSpec,
44
+ InstantiateHandler,
45
+ Runner,
46
+ RunnerRef,
47
+ )
48
+ from .workspace import Workspace
49
+
50
+ __all__ = [
51
+ "Attempt",
52
+ "ChildResult",
53
+ "ChildSpec",
54
+ "ChildrenView",
55
+ "CollectedJob",
56
+ "FormatError",
57
+ "InstantiateHandler",
58
+ "JobRecord",
59
+ "JobState",
60
+ "NotIdleError",
61
+ # Execution / authoring surface.
62
+ "Runner",
63
+ "RunnerRef",
64
+ "RunnerResolutionError",
65
+ "ScaffoldedJob",
66
+ "TaskManager",
67
+ "TransactionError",
68
+ "TransitionLostError",
69
+ "UnstableIdentityError",
70
+ "UnsupportedExtensionError",
71
+ # Orchestration and management entry points.
72
+ "WorkCensus",
73
+ # The public exception family.
74
+ "WorkflowError",
75
+ "Workspace",
76
+ "WorkspaceCorruptionError",
77
+ "WorkspaceUnavailableError",
78
+ "collect",
79
+ "job_records",
80
+ "ledger_key",
81
+ "new_job",
82
+ "new_jobs",
83
+ "scaffold_job",
84
+ ]
@@ -0,0 +1,36 @@
1
+ """Internal exec gate used to close the running-to-process crash window."""
2
+
3
+ import os
4
+ import sys
5
+
6
+
7
+ def main() -> int:
8
+ """Wait for the parent commit token, then replace this process with the runner."""
9
+
10
+ if len(sys.argv) < 4 or sys.argv[2] != "--":
11
+ return 125
12
+ gate_fd: int | None = None
13
+ try:
14
+ gate_fd = int(sys.argv[1])
15
+ token = os.read(gate_fd, 1)
16
+ except (OSError, ValueError):
17
+ return 125
18
+ finally:
19
+ if gate_fd is not None:
20
+ try:
21
+ os.close(gate_fd)
22
+ except OSError:
23
+ pass
24
+ if token != b"R":
25
+ return 125
26
+ command = sys.argv[3:]
27
+ if not command:
28
+ return 125
29
+ try:
30
+ os.execvpe(command[0], command, os.environ)
31
+ except OSError:
32
+ return 127
33
+
34
+
35
+ if __name__ == "__main__":
36
+ raise SystemExit(main())
@@ -0,0 +1,205 @@
1
+ """Logging configuration for the :mod:`httk.workflow` logger hierarchy.
2
+
3
+ The implementation lives in :mod:`httk.core.report`. Library code only ever
4
+ calls :func:`logging.getLogger` and never installs a handler. A manager
5
+ process opts into diagnostics by calling :func:`configure_logging` once and,
6
+ when the manager identity is known, :func:`add_log_file`.
7
+
8
+ When this module's handlers are installed, ``httk.workflow`` has
9
+ ``propagate = False``, so records do not reach a ``"httk"``-level collector
10
+ (:func:`httk.core.report.collect_reports`). That is fine for CLI processes and
11
+ is intentional.
12
+ """
13
+
14
+ import fcntl
15
+ import logging
16
+ import logging.handlers
17
+ import os
18
+ from pathlib import Path
19
+
20
+ from httk.core.report import (
21
+ DEFAULT_BACKUP_COUNT,
22
+ DEFAULT_MAXIMUM_BYTES,
23
+ LOG_LEVELS,
24
+ JsonFormatter,
25
+ add_report_file,
26
+ configure_reporting,
27
+ reset_reporting,
28
+ resolve_level,
29
+ )
30
+
31
+ __all__ = [
32
+ "DEFAULT_BACKUP_COUNT",
33
+ "DEFAULT_MAXIMUM_BYTES",
34
+ "LOG_LEVELS",
35
+ "PACKAGE_LOGGER",
36
+ "JsonFormatter",
37
+ "add_log_file",
38
+ "configure_logging",
39
+ "reset_logging",
40
+ "resolve_level",
41
+ ]
42
+
43
+ PACKAGE_LOGGER = "httk.workflow"
44
+ _LOGGER = logging.getLogger(__name__)
45
+ #: A shared manager log is rotated once it exceeds this size.
46
+ MANAGER_LOG_ROTATION_BYTES = 16 * 1024 * 1024
47
+ MANAGER_LOG_ROTATION_RECORDS = 1000
48
+ _rotation_warnings: set[Path] = set()
49
+
50
+
51
+ def _rotate_manager_log(path: Path) -> None:
52
+ """Link an oversized shared manager log into its one retained backup."""
53
+
54
+ descriptor: int | None = None
55
+ locked = False
56
+ try:
57
+ try:
58
+ descriptor = os.open(path, os.O_RDONLY)
59
+ except FileNotFoundError:
60
+ return
61
+ fcntl.flock(descriptor, fcntl.LOCK_EX)
62
+ locked = True
63
+ current = os.fstat(descriptor)
64
+ named = os.stat(path)
65
+ if (current.st_dev, current.st_ino) != (named.st_dev, named.st_ino):
66
+ return
67
+ if current.st_size <= MANAGER_LOG_ROTATION_BYTES:
68
+ return
69
+ backup = path.with_name(f"{path.name}.1")
70
+ try:
71
+ os.unlink(backup)
72
+ except FileNotFoundError:
73
+ pass
74
+ try:
75
+ os.link(path, backup)
76
+ except FileExistsError:
77
+ # Another manager won the rotation race.
78
+ return
79
+ os.unlink(path)
80
+ except OSError as exc:
81
+ _warn_rotation_error(path, exc)
82
+ finally:
83
+ if descriptor is not None:
84
+ if locked:
85
+ try:
86
+ fcntl.flock(descriptor, fcntl.LOCK_UN)
87
+ except OSError as exc:
88
+ _warn_rotation_error(path, exc)
89
+ try:
90
+ os.close(descriptor)
91
+ except OSError as exc:
92
+ _warn_rotation_error(path, exc)
93
+
94
+
95
+ def _warn_rotation_error(path: Path, error: OSError) -> None:
96
+ """Warn once when a best-effort manager-log rotation cannot proceed."""
97
+
98
+ if path in _rotation_warnings:
99
+ return
100
+ _rotation_warnings.add(path)
101
+ _LOGGER.warning("could not rotate manager log %s: %s", path, error)
102
+
103
+
104
+ def configure_logging(*, level: str | int = "warning", json_logs: bool = False) -> None:
105
+ """Install one console handler for the workflow logger hierarchy."""
106
+
107
+ configure_reporting(level=level, json_logs=json_logs, logger=PACKAGE_LOGGER)
108
+
109
+
110
+ def add_log_file(
111
+ path: Path,
112
+ *,
113
+ level: str | int = "info",
114
+ json_logs: bool = False,
115
+ manager_id: str | None = None,
116
+ maximum_bytes: int = DEFAULT_MAXIMUM_BYTES,
117
+ backup_count: int = DEFAULT_BACKUP_COUNT,
118
+ ) -> Path:
119
+ """Add a file handler and return the path it writes.
120
+
121
+ When *manager_id* is supplied, the handler is an append-only manager log:
122
+ text records begin with the id and JSON records carry it as
123
+ ``manager_id``. The shared manager log is rotated to one ``.1`` backup
124
+ when it exceeds 16 MiB. The legacy rotating handler remains available to
125
+ callers that do not identify a manager.
126
+ """
127
+
128
+ if manager_id is not None:
129
+ path.parent.mkdir(parents=True, exist_ok=True)
130
+ _rotate_manager_log(path)
131
+ handler = _ManagerLogHandler(path)
132
+ handler.setLevel(resolve_level(level))
133
+ handler.addFilter(_ManagerLogFilter(manager_id))
134
+ handler.setFormatter(_ManagerJsonFormatter() if json_logs else _ManagerTextFormatter())
135
+ setattr(handler, "_httk_report_handler", True) # noqa: B010 - matches the shared reset marker
136
+ target = logging.getLogger(PACKAGE_LOGGER)
137
+ target.addHandler(handler)
138
+ target.propagate = False
139
+ if target.level == logging.NOTSET or handler.level < target.level:
140
+ target.setLevel(handler.level)
141
+ return path
142
+
143
+ return add_report_file(
144
+ path,
145
+ level=level,
146
+ json_logs=json_logs,
147
+ maximum_bytes=maximum_bytes,
148
+ backup_count=backup_count,
149
+ logger=PACKAGE_LOGGER,
150
+ )
151
+
152
+
153
+ class _ManagerLogFilter(logging.Filter):
154
+ """Attach the owning manager id to every record handled by its file."""
155
+
156
+ def __init__(self, manager_id: str) -> None:
157
+ super().__init__()
158
+ self.manager_id = manager_id
159
+
160
+ def filter(self, record: logging.LogRecord) -> bool:
161
+ """Set the manager identity and accept the record."""
162
+
163
+ record.manager_id = self.manager_id
164
+ return True
165
+
166
+
167
+ class _ManagerTextFormatter(logging.Formatter):
168
+ """Render text manager records with the manager id as a line prefix."""
169
+
170
+ def __init__(self) -> None:
171
+ super().__init__("%(manager_id)s %(asctime)s %(levelname)-7s %(name)s: %(message)s")
172
+
173
+
174
+ class _ManagerJsonFormatter(JsonFormatter):
175
+ """Render JSON manager records using the shared report representation."""
176
+
177
+
178
+ class _ManagerLogHandler(logging.handlers.WatchedFileHandler):
179
+ """Watch and periodically rotate the shared manager log."""
180
+
181
+ def __init__(self, path: Path) -> None:
182
+ super().__init__(path, mode="a", encoding="utf-8")
183
+ self._records = 0
184
+
185
+ def _open(self):
186
+ """Open the log in append mode and secure the opened stream."""
187
+
188
+ stream = super()._open()
189
+ os.fchmod(stream.fileno(), 0o600)
190
+ return stream
191
+
192
+ def emit(self, record: logging.LogRecord) -> None:
193
+ """Rotate an oversized log periodically, then emit the record."""
194
+
195
+ self._records += 1
196
+ if self._records >= MANAGER_LOG_ROTATION_RECORDS:
197
+ self._records = 0
198
+ _rotate_manager_log(Path(self.baseFilename))
199
+ super().emit(record)
200
+
201
+
202
+ def reset_logging() -> None:
203
+ """Remove the handlers this module installed."""
204
+
205
+ reset_reporting(PACKAGE_LOGGER)
@@ -0,0 +1,225 @@
1
+ """Private cancellation evidence and fencing decisions."""
2
+
3
+ import signal
4
+ import time
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ from .models import StateFrame, validate_process
9
+
10
+
11
+ def evidence(
12
+ manager: Any,
13
+ state: Any,
14
+ *,
15
+ utc_now: Any,
16
+ ) -> dict[str, object] | None:
17
+ """Assess whether the fenced attempt is proven to have stopped."""
18
+
19
+ process = validate_process(state.members.get("process"))
20
+ if process is None:
21
+ return None
22
+
23
+ attempt_id = state.attempt_id or ""
24
+ local = manager._running.get(attempt_id)
25
+ if local is not None:
26
+ exit_status = local.process.poll()
27
+ if exit_status is None:
28
+ return None
29
+ return {
30
+ "verified": "process_exited",
31
+ "hostname": manager.hostname,
32
+ "pid": local.process.pid,
33
+ "exit_status": exit_status,
34
+ "verified_at": utc_now(),
35
+ }
36
+ if process.get("hostname") != manager.hostname:
37
+ return None
38
+ group = process["process_group"]
39
+ if manager._process_group_alive(group):
40
+ return None
41
+ return {
42
+ "verified": "process_group_absent",
43
+ "hostname": manager.hostname,
44
+ "process_group": group,
45
+ "verified_at": utc_now(),
46
+ }
47
+
48
+
49
+ def should_kill(now: float, kill_at: float | None) -> bool:
50
+ return kill_at is not None and now >= kill_at
51
+
52
+
53
+ def fence_members(state: Any, members: tuple[str, ...], request: Mapping[str, Any], operator_key: str | None) -> Any:
54
+ audited = state.select(members)
55
+ updates = {
56
+ "operator": request.get("operator"),
57
+ "operator_reason": request.get("reason"),
58
+ "request_id": request.get("request_id"),
59
+ }
60
+ result = type(state).replace(audited, **updates)
61
+ if operator_key is not None:
62
+ result = type(state).replace(result, operator_key=operator_key)
63
+ return result
64
+
65
+
66
+ def finish(manager: Any, marker: Any, state: Any, members: tuple[str, ...], *, utc_now: Any, logger: Any) -> bool:
67
+ attempt_id = state.attempt_id or ""
68
+ now = time.monotonic()
69
+ kill_at = manager._cancel_kill_at.get(attempt_id)
70
+ if kill_at is None:
71
+ manager._cancel_kill_at[attempt_id] = now + manager.cancel_grace_seconds
72
+ manager._terminate_attempt(marker, state)
73
+ elif should_kill(now, kill_at):
74
+ logger.warning(
75
+ "cancelled attempt %s of %s did not exit within %.0fs; killing its process group",
76
+ attempt_id or "-",
77
+ marker.job_key,
78
+ manager.cancel_grace_seconds,
79
+ extra=manager._event("cancel_kill", marker, attempt_id=attempt_id),
80
+ )
81
+ manager._terminate_attempt(marker, state, signal.SIGKILL)
82
+ proof = manager._cancellation_evidence(state)
83
+ if proof is None:
84
+ manager._report_unverifiable_cancellation(marker, state)
85
+ return False
86
+ local = manager._running.pop(attempt_id, None)
87
+ if local is not None:
88
+ return_code = local.process.poll()
89
+ if return_code is None:
90
+ return_code = -signal.SIGKILL
91
+ manager._write_attempt_end(local, return_code)
92
+ manager._cancel_kill_at.pop(attempt_id, None)
93
+ manager._cancel_unverified.discard(attempt_id)
94
+ manager._transition(
95
+ marker, "cancelled", StateFrame.replace(state.select(members), cancellation=proof, reason="operator_cancel")
96
+ )
97
+ logger.warning(
98
+ "cancelled %s: attempt %s is %s",
99
+ marker.job_key,
100
+ attempt_id or "-",
101
+ proof.get("verified"),
102
+ extra=manager._event("cancel_completed", marker, attempt_id=attempt_id, **proof),
103
+ )
104
+ return True
105
+
106
+
107
+ def request_cancel(
108
+ manager: Any,
109
+ marker: Any,
110
+ state: Any,
111
+ request: Mapping[str, Any],
112
+ operator_key: str | None,
113
+ members: tuple[str, ...],
114
+ *,
115
+ utc_now: Any,
116
+ logger: Any,
117
+ ) -> str | None:
118
+ audited = StateFrame.replace(
119
+ state.select(members),
120
+ operator=request.get("operator"),
121
+ operator_reason=request.get("reason"),
122
+ request_id=request.get("request_id"),
123
+ )
124
+ if operator_key is not None:
125
+ audited = StateFrame.replace(audited, operator_key=operator_key)
126
+ if marker.kind == "cancelling":
127
+ return "the job is already being cancelled"
128
+ if marker.kind == "running":
129
+ fenced = manager._transition(marker, "cancelling", StateFrame.replace(audited, reason="operator_cancel"))
130
+ logger.warning(
131
+ "cancelling %s: attempt %s is fenced and will be stopped",
132
+ fenced.job_key,
133
+ state.attempt_id or "-",
134
+ extra=manager._event("cancel_fenced", fenced, attempt_id=state.attempt_id),
135
+ )
136
+ local = manager._running.get(state.attempt_id or "")
137
+ if local is not None:
138
+ local.cancelling = True
139
+ local.fenced = True
140
+ return None
141
+ manager._terminate_attempt(marker, state)
142
+ manager._transition(
143
+ marker,
144
+ "cancelled",
145
+ StateFrame.replace(
146
+ audited,
147
+ cancellation={"verified": "no_live_attempt", "from_kind": marker.kind, "verified_at": utc_now()},
148
+ reason="operator_cancel",
149
+ ),
150
+ )
151
+ return None
152
+
153
+
154
+ def report_unverifiable(
155
+ manager: Any, marker: Any, state: Any, members: tuple[str, ...], *, utc_now: Any, logger: Any
156
+ ) -> None:
157
+ attempt_id = state.attempt_id or ""
158
+ if attempt_id in manager._cancel_unverified:
159
+ logger.debug("cancellation of %s is still unverifiable here", marker.job_key)
160
+ return
161
+ manager._cancel_unverified.add(attempt_id)
162
+ process = state.members.get("process")
163
+ if isinstance(process, Mapping):
164
+ detail = "its process identity is missing or malformed, so this manager cannot prove that it stopped"
165
+ if process.get("hostname") != manager.hostname:
166
+ detail = "its process is recorded on another host, so this manager cannot prove that it stopped"
167
+ else:
168
+ detail = "its running frame has no process identity, so this manager cannot prove that it stopped"
169
+ logger.warning(
170
+ "cancellation of %s is not finished: %s",
171
+ marker.job_key,
172
+ detail,
173
+ extra=manager._event("cancel_unverified", marker, attempt_id=attempt_id),
174
+ )
175
+ try:
176
+ manager._transition(
177
+ marker,
178
+ "cancelling",
179
+ StateFrame.replace(
180
+ state.select(members),
181
+ cancellation={
182
+ "verified": None,
183
+ "problem": "unverifiable_here",
184
+ "detail": detail,
185
+ "observed_by": manager.manager_id,
186
+ "observed_at": utc_now(),
187
+ },
188
+ reason="cancel_unverified",
189
+ ),
190
+ )
191
+ except Exception as exc:
192
+ from .errors import TransitionLostError
193
+
194
+ if isinstance(exc, TransitionLostError):
195
+ logger.debug("cancellation note for %s was lost to another actor", marker.job_key)
196
+ else:
197
+ raise
198
+
199
+
200
+ def process(manager: Any, logger: Any) -> bool:
201
+ from .errors import TransitionLostError, WorkflowError
202
+
203
+ changed = False
204
+ for marker in manager._window("process_cancelling", "cancelling"):
205
+ manager._pace()
206
+ loaded = manager._load_job_and_state(marker, "process_cancelling")
207
+ if loaded is None:
208
+ continue
209
+ job, state = loaded
210
+ if manager._executor_for(job) is None:
211
+ logger.debug(
212
+ "skipping cancelling job %s: runner executor %s is not served here", marker.job_key, job.runner_executor
213
+ )
214
+ continue
215
+ try:
216
+ changed |= manager._finish_cancellation(marker, state)
217
+ except TransitionLostError:
218
+ logger.debug("cancellation of %s was completed by another actor", marker.job_key)
219
+ except (WorkflowError, OSError) as exc:
220
+ manager._report_anomaly(
221
+ f"cancelling:{marker.job_key}",
222
+ f"cannot complete the cancellation of {marker.job_key}: {exc}",
223
+ manager._event("cancel_error", marker),
224
+ )
225
+ return changed