51def require_storage_payload_local(
54 checkpoint: int =
None,
58 @brief Reject a workflow that requires payload currently held in cold storage.
59 @param[in] root_path Run or study-member directory checked by an existing workflow.
60 @param[in] operation Human-readable consuming operation.
61 @param[in] checkpoint Optional single required checkpoint step.
62 @param[in] checkpoints Optional iterable of every required checkpoint step.
64 state = read_storage_state(root_path)
65 if not state
or not state.get(
"local_pruned"):
67 required_steps = set()
68 if checkpoint
is not None:
69 required_steps.add(int(checkpoint))
70 if checkpoints
is not None:
71 required_steps.update(int(step)
for step
in checkpoints)
72 restored = set(state.get(
"restored_components")
or [])
73 restored.update(state.get(
"retained_components")
or [])
76 archived = state.get(
"archived_checkpoints")
77 missing_steps = sorted(
78 step
for step
in required_steps
79 if f
"checkpoint:{step}" not in restored
and (archived
is None or step
in archived)
81 if required_steps
and not missing_steps:
83 archive_id = state.get(
"archive_id",
"<archive-id>")
84 if missing_steps
and len(missing_steps) <= 8:
85 suffix =
"".join(f
" --checkpoint {step}" for step
in missing_steps)
90 f
"{operation} requires payload archived from {os.path.abspath(root_path)}. Restore it first with:\n"
91 f
" picurv storage restore --archive-id {archive_id}{suffix}"
120def _lock_owner_active(metadata_path: str) -> bool:
122 @brief Conservatively determine whether a solver/post/storage owner marker is active.
123 @param[in] metadata_path Value supplied through the `metadata_path` argument.
124 @return Result produced by this operation.
126 owner = _read_json(metadata_path)
129 host = owner.get(
"host")
130 pid = owner.get(
"pid")
131 if host
and host != socket.gethostname():
135 except (TypeError, ValueError):
139 except ProcessLookupError:
141 except (PermissionError, OSError):
146def _collect_job_ids(payload) -> set:
148 @brief Recursively collect submitted Slurm job IDs from scheduler metadata.
149 @param[in] payload Value supplied through the `payload` argument.
150 @return Result produced by this operation.
153 if isinstance(payload, dict):
154 if payload.get(
"submitted")
and payload.get(
"job_id")
is not None:
155 result.add(str(payload[
"job_id"]).strip())
156 for value
in payload.values():
157 result.update(_collect_job_ids(value))
158 elif isinstance(payload, list):
159 for value
in payload:
160 result.update(_collect_job_ids(value))
161 return {item
for item
in result
if item}
164def _slurm_activity(root: str) -> dict:
166 @brief Query live Slurm state for every job recorded below an artifact scheduler directory.
167 @param[in] root Value supplied through the `root` argument.
168 @return Result produced by this operation.
171 scheduler_dirs = [Path(root) /
"scheduler"]
172 if (Path(root) /
"cases").is_dir():
173 scheduler_dirs.extend((Path(root) /
"cases").glob(
"*/scheduler"))
174 for scheduler
in scheduler_dirs:
175 if not scheduler.is_dir():
177 for path
in scheduler.glob(
"submission*.json"):
178 job_ids.update(_collect_job_ids(_read_json(str(path))))
180 return {
"job_ids": [],
"active": [],
"unknown":
False}
181 squeue = shutil.which(
"squeue")
183 return {
"job_ids": sorted(job_ids),
"active": [],
"unknown":
True}
186 for recorded_id
in sorted(job_ids):
187 result = subprocess.run(
188 [squeue,
"-h",
"-j", recorded_id,
"-o",
"%i|%T"],
189 text=
True, capture_output=
True, check=
False,
191 if result.returncode != 0:
192 detail = (result.stderr
or result.stdout
or "").lower()
195 if "invalid job id" in detail
or "invalid job/step" in detail:
197 unknown_ids.append(recorded_id)
199 for line
in result.stdout.splitlines():
202 job_id, _, state = line.partition(
"|")
203 active.append({
"job_id": job_id.strip(),
"state": state.strip()
or "UNKNOWN"})
205 "job_ids": sorted(job_ids),
207 "unknown": bool(unknown_ids),
208 "unknown_job_ids": unknown_ids,
237def storage_operation_lock(root_path: str, operation: str):
239 @brief Hold an exclusive local storage-operation marker for one artifact.
240 @param[in] root_path Value supplied through the `root_path` argument.
241 @param[in] operation Value supplied through the `operation` argument.
243 root = os.path.abspath(root_path)
244 lock_path = os.path.join(root, STORAGE_LOCK_FILENAME)
245 if os.path.exists(lock_path):
246 if _lock_owner_active(lock_path):
247 raise StorageError(f
"Another storage operation owns {lock_path}.")
250 except OSError
as exc:
251 raise StorageError(f
"Unable to remove stale storage lock {lock_path}: {exc}")
from exc
252 payload = {
"operation": operation,
"pid": os.getpid(),
"host": socket.gethostname(),
"started_at": _utc_now()}
253 flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
255 descriptor = os.open(lock_path, flags, 0o600)
256 with os.fdopen(descriptor,
"w", encoding=
"utf-8")
as stream:
257 json.dump(payload, stream, indent=2, sort_keys=
True)
263 except FileNotFoundError:
267@contextlib.contextmanager
268def runtime_stage_lock(root_path: str, stage: str):
270 @brief Mark a locally executed solver/post stage as active for storage safety.
271 @param[in] root_path Run directory used as the runtime working directory.
272 @param[in] stage Runtime stage label; storage currently uses this for solver execution.
274 scheduler = os.path.join(os.path.abspath(root_path),
"scheduler")
275 os.makedirs(scheduler, exist_ok=
True)
276 lock_path = os.path.join(scheduler, f
"{stage}.lock.json")
277 if os.path.exists(lock_path):
278 if _lock_owner_active(lock_path):
279 raise StorageError(f
"A {stage} runtime stage already owns {lock_path}.")
281 payload = {
"stage": stage,
"pid": os.getpid(),
"host": socket.gethostname(),
"started_at": _utc_now()}
282 flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
283 descriptor = os.open(lock_path, flags, 0o600)
284 with os.fdopen(descriptor,
"w", encoding=
"utf-8")
as stream:
285 json.dump(payload, stream, indent=2, sort_keys=
True)
292 except FileNotFoundError: