PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Functions | Variables
picurv_cli.storage.operations Namespace Reference

Functions

list restore_cold_study_members (str study_path, case_ids, str profile_name=None, str storage_config=None)
 Restore named cold study members in place from their local markers.
 
dict build_storage_plan (dict target, dict profile, str compression=None, str policy=None, keep_latest_checkpoint=None, int workers=None, retain=None, drop=None)
 Build the read-only plan consumed by protect and offload.
 
None _render_plan (dict plan)
 Print a concise archive/offload plan.
 
dict archive_artifact (dict target, dict profile, str label=None, tags=None, str compression=None, bool prune_local=False, str policy=None, keep_latest_checkpoint=None, int workers=None, str notes=None, retain=None, drop=None)
 Package, upload, verify, register, and optionally prune one artifact.
 
dict _register_existing_archive (dict target, dict profile, dict manifest, dict inventory, dict plan, *bool prune_local, str label=None, tags=None, str notes=None)
 Point an artifact at an already-uploaded archive of its current content.
 
None _prune_archived_payload (str root, dict inventory, dict policy)
 Remove only verified heavy payload while retaining control-plane files.
 
None _download_archive_components (dict profile, dict manifest, set components, str destination, int workers=None)
 Download and safely merge selected semantic archive components.
 
dict restore_missing_workspace_assets (str workspace_root, provider_spec_hashes)
 Recover immutable workspace assets from archived run-local input copies.
 
dict restore_archive (dict profile, str archive_id, str destination=None, checkpoints=None, bool force=False, int workers=None, components=None)
 Download, verify, extract, and materialize an archive or selected checkpoints.
 
list _expand_checkpoint_selection (explicit, ranges)
 Combine repeated --checkpoint values with START:END[:STRIDE] ranges.
 
str _resolve_archive_id_from_args (args)
 Resolve an explicit archive ID or a local artifact marker.
 
None _render_status (dict inventory)
 Render one artifact status row and safety details.
 
dict report_storage_configuration (dict profile)
 State which configuration answered, and warn when it came from outside.
 
dict load_reported_storage_profile (args)
 Load the storage profile a command will act on, and report its origin.
 
None storage_setup_workflow (args)
 Create or update a non-secret workspace storage profile.
 
None storage_status_workflow (args)
 Print local storage and lifecycle status for selected artifacts.
 
None storage_plan_workflow (args)
 Render a read-only packaging and safety plan.
 
None storage_archive_workflow (args, bool prune_local)
 Execute protect or offload for one or more explicit local targets.
 
None storage_restore_workflow (args)
 Restore a remote archive by globally unique ID or local marker.
 
None storage_prune_workflow (args)
 Remove local asset objects nothing local needs and storage has verified.
 
None storage_verify_workflow (args)
 Verify all remote chunks for one archive.
 
None storage_list_workflow (args)
 Search the remote manifest catalog without local artifact state.
 
None storage_show_workflow (args)
 Show one complete remote archive manifest.
 
None storage_workflow (args)
 Dispatch nested storage actions using existing PICurv workflow conventions.
 
argparse.ArgumentParser add_storage_parser (subparsers)
 Attach the nested storage command parser to PICurv's top-level parser.
 

Variables

tuple COMPRESSION_HELP
 
tuple POLICY_HELP
 

Function Documentation

◆ restore_cold_study_members()

list picurv_cli.storage.operations.restore_cold_study_members ( str  study_path,
  case_ids,
str   profile_name = None,
str   storage_config = None 
)

Restore named cold study members in place from their local markers.

Parameters
[in]study_pathStudy directory owning the members.
[in]case_idsMember ids to restore.
[in]profile_nameOptional storage profile name.
[in]storage_configOptional explicit storage configuration path.
Returns
Restored member ids.
Exceptions
StorageErrorwhen a member carries no usable archive reference.

Definition at line 109 of file operations.py.

110 storage_config: str = None) -> list:
111 """!
112 @brief Restore named cold study members in place from their local markers.
113 @param[in] study_path Study directory owning the members.
114 @param[in] case_ids Member ids to restore.
115 @param[in] profile_name Optional storage profile name.
116 @param[in] storage_config Optional explicit storage configuration path.
117 @return Restored member ids.
118 @throws StorageError when a member carries no usable archive reference.
119 """
120 # This runs inside a staging workflow rather than a storage command, so the
121 # configuration answering it has had no chance to be named yet.
122 profile = report_storage_configuration(load_storage_profile(profile_name, storage_config))
123 restored = []
124 for case_id in case_ids:
125 member = os.path.join(study_path, "cases", case_id)
126 state = read_storage_state(member) or {}
127 archive_id = state.get("archive_id")
128 if not archive_id:
129 raise StorageError(
130 f"{case_id} is cold but its marker names no archive; restore it by id."
131 )
132 restore_archive(profile, archive_id, destination=member, force=True)
133 restored.append(case_id)
134 return restored
135
136
Here is the call graph for this function:

◆ build_storage_plan()

dict picurv_cli.storage.operations.build_storage_plan ( dict  target,
dict  profile,
str   compression = None,
str   policy = None,
  keep_latest_checkpoint = None,
int   workers = None,
  retain = None,
  drop = None 
)

Build the read-only plan consumed by protect and offload.

Parameters
[in]targetValue supplied through the target argument.
[in]profileValue supplied through the profile argument.
[in]compressionValue supplied through the compression argument.
[in]policyOptional semantic retention policy override.
[in]keep_latest_checkpointOptional newest-checkpoint retention override.
[in]workersOptional compression worker count override.
[in]retainComponents to retain locally regardless of the policy preset.
[in]dropComponents to prune locally regardless of the policy preset.
Returns
Result produced by this operation.

Definition at line 137 of file operations.py.

139 workers: int = None, retain=None, drop=None) -> dict:
140 """!
141 @brief Build the read-only plan consumed by protect and offload.
142 @param[in] target Value supplied through the `target` argument.
143 @param[in] profile Value supplied through the `profile` argument.
144 @param[in] compression Value supplied through the `compression` argument.
145 @param[in] policy Optional semantic retention policy override.
146 @param[in] keep_latest_checkpoint Optional newest-checkpoint retention override.
147 @param[in] workers Optional compression worker count override.
148 @param[in] retain Components to retain locally regardless of the policy preset.
149 @param[in] drop Components to prune locally regardless of the policy preset.
150 @return Result produced by this operation.
151 """
152 inventory = inspect_artifact(target)
153 selected_compression = _select_compression(compression, inventory["total_bytes"], profile)
154 specs = _build_chunk_specs(inventory, profile["chunk_size_bytes"])
155 retention = _resolve_offload_policy(profile, policy, keep_latest_checkpoint, retain, drop)
156 latest_step = max(inventory["checkpoint_steps"], default=None)
157 retained_bytes = sum(
158 entry["size"] for entry in inventory["entries"]
159 if entry["type"] != "directory" and _entry_retained_by_policy(entry, retention, latest_step)
160 )
161 worker_count = int(workers or profile.get("workers", DEFAULT_STORAGE_WORKERS))
162 if worker_count <= 0:
163 raise StorageError("Storage workers must be positive.")
164 compressed_range = _compression_size_range(inventory["total_bytes"], selected_compression)
165 return {
166 "inventory": inventory,
167 "compression": selected_compression,
168 "chunk_count": len(specs),
169 "workers": worker_count,
170 "offload_policy": retention,
171 "retained_local_bytes": retained_bytes,
172 "pruned_local_bytes": max(0, inventory["total_bytes"] - retained_bytes),
173 "estimated_stored_bytes": {"low": compressed_range[0], "high": compressed_range[1]},
174 "chunks": [
175 {
176 "component": spec["component"],
177 "file_count": len(spec["entries"]),
178 "uncompressed_bytes": spec["uncompressed_bytes"],
179 }
180 for spec in specs
181 ],
182 }
183
184
Here is the caller graph for this function:

◆ _render_plan()

None picurv_cli.storage.operations._render_plan ( dict  plan)
protected

Print a concise archive/offload plan.

Parameters
[in]planValue supplied through the plan argument.

Definition at line 185 of file operations.py.

185def _render_plan(plan: dict) -> None:
186 """!
187 @brief Print a concise archive/offload plan.
188 @param[in] plan Value supplied through the `plan` argument.
189 """
190 inventory = plan["inventory"]
191 target = inventory["target"]
192 print(f"[INFO] Artifact type : {target['artifact_type']}")
193 print(f"[INFO] Artifact path : {target['root_path']}")
194 print(f"[INFO] Local size : {_human_bytes(inventory['total_bytes'])}")
195 print(f"[INFO] Files : {inventory['file_count']}")
196 print(f"[INFO] Checkpoints : {len(inventory['checkpoint_steps'])}")
197 print(f"[INFO] Compression : {plan['compression']}")
198 print(f"[INFO] CPU workers : {plan['workers']}")
199 print(f"[INFO] Archive chunks: {plan['chunk_count']}")
200 estimate = plan["estimated_stored_bytes"]
201 print(
202 f"[INFO] Remote estimate: {_human_bytes(estimate['low'])}–"
203 f"{_human_bytes(estimate['high'])} (content-dependent)"
204 )
205 policy = plan["offload_policy"]
206 print(f"[INFO] Offload policy: {policy['name']}")
207 # The preset name alone no longer says what is kept once --retain/--drop adjust it,
208 # so the resolved component set is reported rather than left to be inferred.
209 print(f"[INFO] Kept components: {', '.join(policy['retained_components'])}")
210 if policy.get("explicit_retain"):
211 print(f"[INFO] Retained by flag: {', '.join(policy['explicit_retain'])}")
212 if policy.get("explicit_drop"):
213 print(f"[INFO] Dropped by flag: {', '.join(policy['explicit_drop'])}")
214 print(f"[INFO] Retained local: {_human_bytes(plan['retained_local_bytes'])}")
215 print(f"[INFO] Pruned local : {_human_bytes(plan['pruned_local_bytes'])}")
216 if "checkpoints" in policy["retained_components"]:
217 print(f"[INFO] Kept checkpoint: every committed step ({len(inventory['checkpoint_steps'])})")
218 elif policy["keep_latest_checkpoint"]:
219 latest = max(inventory["checkpoint_steps"], default=None)
220 print(f"[INFO] Kept checkpoint: {latest if latest is not None else 'none available'}")
221 if inventory["external_paths"]:
222 print("[WARNING] External configured paths are recorded but are not followed automatically:")
223 for item in inventory["external_paths"]:
224 print(f" - {item['source']}: {item['path']}")
225 if inventory["dependencies"]:
226 print("[WARNING] External run dependencies:")
227 for item in inventory["dependencies"]:
228 print(f" - {item['kind']}: {item['path']}")
229 unclassified = [
230 entry for entry in inventory["entries"]
231 if entry["type"] != "directory" and entry["component"] == UNCLASSIFIED_COMPONENT
232 ]
233 if unclassified:
234 print(
235 f"[WARNING] {len(unclassified)} file(s) are not part of any known component. "
236 "They are archived, and retained locally by every policy, because storage "
237 "does not delete files whose purpose it cannot state:"
238 )
239 for entry in unclassified[:10]:
240 print(f" - {entry['path']}")
241 if len(unclassified) > 10:
242 print(f" - ... and {len(unclassified) - 10} more")
243
244

◆ archive_artifact()

dict picurv_cli.storage.operations.archive_artifact ( dict  target,
dict  profile,
str   label = None,
  tags = None,
str   compression = None,
bool   prune_local = False,
str   policy = None,
  keep_latest_checkpoint = None,
int   workers = None,
str   notes = None,
  retain = None,
  drop = None 
)

Package, upload, verify, register, and optionally prune one artifact.

Parameters
[in]targetValue supplied through the target argument.
[in]profileValue supplied through the profile argument.
[in]labelValue supplied through the label argument.
[in]tagsValue supplied through the tags argument.
[in]compressionValue supplied through the compression argument.
[in]prune_localValue supplied through the prune_local argument.
[in]policyOptional semantic retention policy override.
[in]keep_latest_checkpointOptional newest-checkpoint retention override.
[in]workersOptional compression worker count override.
[in]notesOptional free-text note recorded with the archive.
[in]retainComponents to retain locally regardless of the policy preset.
[in]dropComponents to prune locally regardless of the policy preset.
Returns
Result produced by this operation.

Definition at line 245 of file operations.py.

248 workers: int = None, notes: str = None, retain=None, drop=None) -> dict:
249 """!
250 @brief Package, upload, verify, register, and optionally prune one artifact.
251 @param[in] target Value supplied through the `target` argument.
252 @param[in] profile Value supplied through the `profile` argument.
253 @param[in] label Value supplied through the `label` argument.
254 @param[in] tags Value supplied through the `tags` argument.
255 @param[in] compression Value supplied through the `compression` argument.
256 @param[in] prune_local Value supplied through the `prune_local` argument.
257 @param[in] policy Optional semantic retention policy override.
258 @param[in] keep_latest_checkpoint Optional newest-checkpoint retention override.
259 @param[in] workers Optional compression worker count override.
260 @param[in] notes Optional free-text note recorded with the archive.
261 @param[in] retain Components to retain locally regardless of the policy preset.
262 @param[in] drop Components to prune locally regardless of the policy preset.
263 @return Result produced by this operation.
264 """
265 with storage_operation_lock(target["root_path"], "offload" if prune_local else "protect"):
266 plan = build_storage_plan(
267 target, profile, compression, policy=policy,
268 keep_latest_checkpoint=keep_latest_checkpoint, workers=workers,
269 retain=retain, drop=drop,
270 )
271 inventory = plan["inventory"]
272 _assert_archive_safe(inventory)
273 fingerprint = _inventory_fingerprint(inventory)
274 # An explicitly requested compression must be honoured; without one, any
275 # current archive of the artifact will do (protect, then a plain offload).
276 reusable = _find_reusable_archive(
277 profile, target, fingerprint,
278 compression=plan["compression"] if compression else None,
279 )
280 if reusable is not None:
281 # `protect` then `offload` is the documented workflow for "back it up now,
282 # free the space later". Re-packaging and re-uploading an unchanged artifact
283 # would store a second full copy of it, which for a campaign-sized run is
284 # the most expensive thing this command can do for no benefit.
285 print(
286 f"[INFO] Reusing verified archive {reusable['archive_id']}: "
287 f"{target['root_path']} is unchanged since it was archived."
288 )
289 return _register_existing_archive(
290 target, profile, reusable, inventory, plan, prune_local=prune_local,
291 label=label, tags=tags, notes=notes,
292 )
293 archive_id = uuid.uuid4().hex
294 specs = _build_chunk_specs(inventory, profile["chunk_size_bytes"])
295 staging_parent = profile.get("staging_directory")
296 if staging_parent:
297 staging_parent = os.path.abspath(os.path.expanduser(str(staging_parent)))
298 os.makedirs(staging_parent, exist_ok=True)
299 # As many chunks as `plan["workers"]` can be staged (packaged, not yet
300 # uploaded) at once; each is deleted right after its verified upload, so
301 # staging never needs archive-sized space, only room for the largest
302 # concurrent handful of uncompressed chunks.
303 concurrent_chunks = sorted(
304 (spec["uncompressed_bytes"] for spec in specs), reverse=True
305 )[:plan["workers"]]
306 _require_free_space(
307 staging_parent or tempfile.gettempdir(), sum(concurrent_chunks),
308 f"stage {target['root_path']}",
309 )
310 print(f"[INFO] Creating archive {archive_id} for {target['root_path']}")
311 with tempfile.TemporaryDirectory(prefix="picurv-storage-", dir=staging_parent) as staging:
312 def package_and_upload(index_spec):
313 """!
314 @brief Package and verify one component chunk.
315 @param[in] index_spec Tuple of chunk index and inventory specification.
316 @return Uploaded chunk manifest entry.
317 """
318 index, spec = index_spec
319 component = _safe_component_name(spec["component"])
320 filename = f"{index:05d}_{component}{_chunk_extension(plan['compression'])}"
321 local_chunk = os.path.join(staging, filename)
322 print(
323 f"[INFO] Packaging chunk {index + 1}/{len(specs)}: "
324 f"{spec['component']} ({_human_bytes(spec['uncompressed_bytes'])})"
325 )
326 compressor = _write_tar_chunk(
327 target["root_path"], spec, local_chunk, plan["compression"],
328 workers=plan["workers"],
329 )
330 try:
331 digest = _sha256_file(local_chunk)
332 # Content-addressed: an identical chunk anywhere on this remote is
333 # already stored, so a rerun after a failed upload skips what
334 # succeeded, and two archives of the same checkpoint share one copy.
335 if _remote_blob_present(profile, digest):
336 print(f"[INFO] Chunk {index + 1}/{len(specs)} already stored; skipping upload.")
337 verified = {
338 "sha256": digest, "stored_bytes": os.path.getsize(local_chunk),
339 }
340 else:
341 _transport._ensure_blob_directory(profile, digest)
342 verified = _transport._upload_verified(local_chunk, _blob_remote(profile, digest))
343 return {
344 "name": filename,
345 "component": spec["component"],
346 "file_count": len(spec["entries"]),
347 "uncompressed_bytes": spec["uncompressed_bytes"],
348 "stored_bytes": verified["stored_bytes"],
349 "sha256": verified["sha256"],
350 "compressor": compressor,
351 "blob": True,
352 }
353 finally:
354 try:
355 os.remove(local_chunk)
356 except FileNotFoundError:
357 pass
358
359 # pigz/xz already use every requested CPU on one large chunk. The
360 # Python fallback instead gains parallelism across independent chunks.
361 native_parallel = (
362 plan["compression"] in _PARALLEL_GZIP_VALUES and shutil.which("pigz")
363 ) or (plan["compression"] == "maximum" and shutil.which("xz"))
364 task_workers = 1 if native_parallel else min(plan["workers"], max(1, len(specs)))
365 if task_workers == 1:
366 chunks = [package_and_upload(item) for item in enumerate(specs)]
367 else:
368 with concurrent.futures.ThreadPoolExecutor(max_workers=task_workers) as executor:
369 chunks = list(executor.map(package_and_upload, enumerate(specs)))
370 chunks.sort(key=lambda item: item["name"])
371
372 manifest = {
373 "storage_schema_version": STORAGE_SCHEMA_VERSION,
374 "archive_id": archive_id,
375 "created_at": _utc_now(),
376 "artifact_type": target["artifact_type"],
377 "run_id": target.get("run_id"),
378 "study_id": target.get("study_id"),
379 "case_id": target.get("case_id"),
380 "workspace_id": target.get("workspace_id"),
381 "label": label or os.path.basename(target["root_path"]),
382 "notes": notes,
383 "tags": _parse_tags(tags),
384 # What was actually solved, so `storage show` answers "which run was
385 # this?" without restoring anything.
386 "parameters": _capture_parameter_summary(target["root_path"]),
387 "original_path": target["original_path"],
388 "original_study_path": target.get("study_path"),
389 "profile": profile["name"],
390 "remote": profile["remote"],
391 "source_bytes": inventory["total_bytes"],
392 "source_file_count": inventory["file_count"],
393 "inventory_sha256": fingerprint,
394 "compression": plan["compression"],
395 "workers": plan["workers"],
396 "offload_policy": plan["offload_policy"],
397 "checkpoint_format_version": KNOWN_CHECKPOINT_VERSION,
398 "checkpoint_steps": inventory["checkpoint_steps"],
399 "chunks": chunks,
400 "config_sha256": _config_fingerprints(target["root_path"]),
401 "git": _git_provenance(target["root_path"]),
402 "external_paths": inventory["external_paths"],
403 "dependencies": inventory["dependencies"],
404 "study_context": _capture_study_context(target),
405 "run_assets": _capture_run_assets(target["root_path"]),
406 "workspace_assets": _capture_workspace_assets(target),
407 "capabilities": {
408 "restorable": True,
409 "continuable": bool(inventory["checkpoint_steps"]),
410 "reprocessable": bool(inventory["checkpoint_steps"]),
411 "exact_binary_reproduction": False,
412 },
413 }
414 manifest_path = os.path.join(staging, REMOTE_MANIFEST_FILENAME)
415 _atomic_write_json(manifest_path, manifest)
416 _transport._upload_verified(manifest_path, _object_remote(profile, archive_id, REMOTE_MANIFEST_FILENAME))
417 manifest_digest = _sha256_file(manifest_path)
418 complete_path = os.path.join(staging, REMOTE_COMPLETE_FILENAME)
419 with open(complete_path, "w", encoding="ascii") as stream:
420 stream.write(manifest_digest + "\n")
421 _transport._upload_verified(complete_path, _object_remote(profile, archive_id, REMOTE_COMPLETE_FILENAME))
422
423 state = {
424 "storage_schema_version": STORAGE_SCHEMA_VERSION,
425 "archive_id": archive_id,
426 "profile": profile["name"],
427 "remote": profile["remote"],
428 "label": manifest["label"],
429 "archived_at": manifest["created_at"],
430 "archived_checkpoints": manifest.get("checkpoint_steps") or [],
431 "local_pruned": False,
432 "restored_components": [],
433 "retained_components": [],
434 }
435 _atomic_write_json(_state_path(target["root_path"]), state)
436 if prune_local:
437 _prune_archived_payload(target["root_path"], inventory, plan["offload_policy"])
438 state["local_pruned"] = True
439 state["pruned_at"] = _utc_now()
440 state["offload_policy"] = plan["offload_policy"]
441 latest_step = max(inventory["checkpoint_steps"], default=None)
442 retained = list(plan["offload_policy"]["retained_components"])
443 if plan["offload_policy"]["keep_latest_checkpoint"] and latest_step is not None:
444 retained.append(f"checkpoint:{latest_step}")
445 state["retained_components"] = retained
446 _atomic_write_json(_state_path(target["root_path"]), state)
447 print(
448 f"[SUCCESS] {'Offloaded' if prune_local else 'Protected'} {target['root_path']} "
449 f"as archive {archive_id}."
450 )
451 return manifest
452
453
Head of a generic C-style linked list.
Definition variables.h:504
Here is the call graph for this function:
Here is the caller graph for this function:

◆ _register_existing_archive()

dict picurv_cli.storage.operations._register_existing_archive ( dict  target,
dict  profile,
dict  manifest,
dict  inventory,
dict  plan,
*bool  prune_local,
str   label = None,
  tags = None,
str   notes = None 
)
protected

Point an artifact at an already-uploaded archive of its current content.

Used when nothing has changed since a previous protect or offload. The remote object is immutable and is not rewritten; only this artifact's local marker is updated, and a label or tags supplied now are recorded there so the second invocation is not silently less descriptive than the first.

Parameters
[in]targetLocal artifact target.
[in]profileResolved storage profile.
[in]manifestRemote manifest being reused.
[in]inventoryCurrent local inventory.
[in]planStorage plan carrying the requested offload policy.
[in]prune_localWhether to prune the verified payload afterwards.
[in]labelOptional label supplied to this invocation.
[in]tagsOptional tags supplied to this invocation.
[in]notesOptional free-text note supplied to this invocation.
Returns
The reused remote manifest.

Definition at line 454 of file operations.py.

456 label: str = None, tags=None, notes: str = None) -> dict:
457 """!
458 @brief Point an artifact at an already-uploaded archive of its current content.
459
460 @details Used when nothing has changed since a previous `protect` or `offload`. The
461 remote object is immutable and is not rewritten; only this artifact's local
462 marker is updated, and a label or tags supplied now are recorded there so
463 the second invocation is not silently less descriptive than the first.
464 @param[in] target Local artifact target.
465 @param[in] profile Resolved storage profile.
466 @param[in] manifest Remote manifest being reused.
467 @param[in] inventory Current local inventory.
468 @param[in] plan Storage plan carrying the requested offload policy.
469 @param[in] prune_local Whether to prune the verified payload afterwards.
470 @param[in] label Optional label supplied to this invocation.
471 @param[in] tags Optional tags supplied to this invocation.
472 @param[in] notes Optional free-text note supplied to this invocation.
473 @return The reused remote manifest.
474 """
475 state = {
476 "storage_schema_version": STORAGE_SCHEMA_VERSION,
477 "archive_id": manifest["archive_id"],
478 "profile": profile["name"],
479 "remote": profile["remote"],
480 "label": label or manifest.get("label") or os.path.basename(target["root_path"]),
481 "archived_at": manifest.get("created_at"),
482 "archived_checkpoints": manifest.get("checkpoint_steps") or [],
483 "reused_existing_archive": True,
484 "local_pruned": False,
485 "restored_components": [],
486 "retained_components": [],
487 }
488 parsed_tags = _parse_tags(tags)
489 if parsed_tags:
490 state["tags"] = parsed_tags
491 if notes:
492 state["notes"] = notes
493 _atomic_write_json(_state_path(target["root_path"]), state)
494 if prune_local:
495 _prune_archived_payload(target["root_path"], inventory, plan["offload_policy"])
496 state["local_pruned"] = True
497 state["pruned_at"] = _utc_now()
498 state["offload_policy"] = plan["offload_policy"]
499 latest_step = max(inventory["checkpoint_steps"], default=None)
500 retained = list(plan["offload_policy"]["retained_components"])
501 if plan["offload_policy"]["keep_latest_checkpoint"] and latest_step is not None:
502 retained.append(f"checkpoint:{latest_step}")
503 state["retained_components"] = retained
504 _atomic_write_json(_state_path(target["root_path"]), state)
505 print(
506 f"[SUCCESS] {'Offloaded' if prune_local else 'Protected'} {target['root_path']} "
507 f"using existing archive {manifest['archive_id']}."
508 )
509 return manifest
510
511

◆ _prune_archived_payload()

None picurv_cli.storage.operations._prune_archived_payload ( str  root,
dict  inventory,
dict  policy 
)
protected

Remove only verified heavy payload while retaining control-plane files.

Parameters
[in]rootValue supplied through the root argument.
[in]inventoryValue supplied through the inventory argument.
[in]policyNormalized semantic retention policy.

Definition at line 512 of file operations.py.

512def _prune_archived_payload(root: str, inventory: dict, policy: dict) -> None:
513 """!
514 @brief Remove only verified heavy payload while retaining control-plane files.
515 @param[in] root Value supplied through the `root` argument.
516 @param[in] inventory Value supplied through the `inventory` argument.
517 @param[in] policy Normalized semantic retention policy.
518 """
519 latest_step = max(inventory["checkpoint_steps"], default=None)
520 for entry in sorted(inventory["entries"], key=lambda item: item["path"], reverse=True):
521 if entry["type"] == "directory" or _entry_retained_by_policy(entry, policy, latest_step):
522 continue
523 path = os.path.join(root, *entry["path"].split("/"))
524 try:
525 if os.path.islink(path) or os.path.isfile(path):
526 os.remove(path)
527 except FileNotFoundError:
528 pass
529 for entry in sorted(
530 (item for item in inventory["entries"] if item["type"] == "directory"),
531 key=lambda item: item["path"].count("/"), reverse=True,
532 ):
533 path = os.path.join(root, *entry["path"].split("/"))
534 try:
535 os.rmdir(path)
536 except OSError:
537 pass
538
539

◆ _download_archive_components()

None picurv_cli.storage.operations._download_archive_components ( dict  profile,
dict  manifest,
set  components,
str  destination,
int   workers = None 
)
protected

Download and safely merge selected semantic archive components.

Parameters
[in]profileActive storage profile.
[in]manifestVerified remote archive manifest.
[in]componentsSemantic components to retrieve.
[in]destinationDirectory receiving merged content.
[in]workersOptional parallel worker count.
Returns
None.

Definition at line 540 of file operations.py.

541 destination: str, workers: int = None) -> None:
542 """!
543 @brief Download and safely merge selected semantic archive components.
544 @param[in] profile Active storage profile.
545 @param[in] manifest Verified remote archive manifest.
546 @param[in] components Semantic components to retrieve.
547 @param[in] destination Directory receiving merged content.
548 @param[in] workers Optional parallel worker count.
549 @return None.
550 """
551 chunks = [
552 chunk for chunk in manifest.get("chunks", [])
553 if str(chunk.get("component", "")) in components
554 ]
555 if not chunks:
556 raise StorageError(
557 f"Archive {manifest.get('archive_id')} has none of the requested components: "
558 + ", ".join(sorted(components))
559 )
560 worker_count = int(workers or profile.get("workers", DEFAULT_STORAGE_WORKERS))
561 if worker_count <= 0:
562 raise StorageError("Restore workers must be positive.")
563 os.makedirs(destination, exist_ok=True)
564 # Each chunk is extracted in full before `_merge_tree` copies it into `destination`,
565 # so both copies exist on disk at once.
566 extracted_bytes = sum(chunk.get("uncompressed_bytes", 0) for chunk in chunks)
567 _require_free_space(
568 destination, 2 * extracted_bytes, f"restore archive {manifest.get('archive_id')} components"
569 )
570 with tempfile.TemporaryDirectory(prefix="picurv-component-restore-") as staging:
571 def download_and_extract(index_chunk):
572 """!
573 @brief Download, verify, and extract one selected chunk.
574 @param[in] index_chunk Tuple of chunk index and manifest entry.
575 @return Chunk index and extraction directory.
576 """
577 index, chunk = index_chunk
578 chunk_root = os.path.join(staging, f"extract-{index:05d}")
579 os.makedirs(chunk_root)
580 local_chunk = os.path.join(staging, chunk["name"])
581 _transport._run_rclone([
582 "copyto",
583 _chunk_remote_path(profile, manifest["archive_id"], chunk),
584 local_chunk,
585 ])
586 actual = _sha256_file(local_chunk)
587 if actual != chunk.get("sha256"):
588 raise StorageError(
589 f"Downloaded chunk checksum mismatch: {chunk['name']} "
590 f"(expected {chunk.get('sha256')}, got {actual})."
591 )
592 _extract_chunk(local_chunk, chunk_root)
593 return index, chunk_root
594
595 task_workers = min(worker_count, len(chunks))
596 if task_workers == 1:
597 extracted = [download_and_extract(item) for item in enumerate(chunks)]
598 else:
599 with concurrent.futures.ThreadPoolExecutor(max_workers=task_workers) as executor:
600 extracted = list(executor.map(download_and_extract, enumerate(chunks)))
601 for _, chunk_root in sorted(extracted):
602 _merge_tree(chunk_root, destination)
603
604

◆ restore_missing_workspace_assets()

dict picurv_cli.storage.operations.restore_missing_workspace_assets ( str  workspace_root,
  provider_spec_hashes 
)

Recover immutable workspace assets from archived run-local input copies.

Parameters
[in]workspace_rootInitialized workspace receiving recovered objects.
[in]provider_spec_hashesRequired provider-specification hashes.
Returns
Provider-specification hash to recovered asset-reference mapping.

Definition at line 605 of file operations.py.

605def restore_missing_workspace_assets(workspace_root: str, provider_spec_hashes) -> dict:
606 """!
607 @brief Recover immutable workspace assets from archived run-local input copies.
608 @param[in] workspace_root Initialized workspace receiving recovered objects.
609 @param[in] provider_spec_hashes Required provider-specification hashes.
610 @return Provider-specification hash to recovered asset-reference mapping.
611 """
612 requested = {str(value) for value in provider_spec_hashes if value}
613 if not requested:
614 return {}
615 workspace = Path(os.path.abspath(workspace_root))
616 (workspace / "assets").mkdir(parents=True, exist_ok=True)
617 profile = load_storage_profile(config_path=str(workspace / STORAGE_CONFIG_FILENAME))
618 matches = {}
619 for manifest in sorted(
620 list_remote_manifests(profile), key=lambda item: item.get("created_at", ""), reverse=True
621 ):
622 for reference in manifest.get("run_assets", []):
623 spec_hash = reference.get("provider_spec_sha256")
624 if spec_hash in requested and spec_hash not in matches:
625 matches[spec_hash] = (manifest, reference)
626 if requested <= set(matches):
627 break
628 if not matches:
629 return {}
630
631 restored = {}
632 by_archive = {}
633 for spec_hash, (manifest, reference) in matches.items():
634 group = by_archive.setdefault(manifest["archive_id"], {"manifest": manifest, "items": []})
635 group["items"].append((spec_hash, reference))
636 kind_directories = {
637 "grid": "grids",
638 "initial-condition": "initial_conditions",
639 "inlet-profiles": "inlet_profiles",
640 }
641 for group in by_archive.values():
642 with tempfile.TemporaryDirectory(prefix=".asset-restore-", dir=workspace / "assets") as temporary:
643 _download_archive_components(profile, group["manifest"], {"inputs"}, temporary)
644 for spec_hash, reference in group["items"]:
645 kind = reference.get("kind")
646 asset_id = reference.get("asset_id")
647 if kind not in kind_directories or not asset_id:
648 continue
649 object_relative = f"assets/objects/{kind_directories[kind]}/{asset_id}"
650 object_root = workspace / object_relative
651 if not object_root.is_dir():
652 object_root.parent.mkdir(parents=True, exist_ok=True)
653 object_staging = Path(tempfile.mkdtemp(
654 prefix=f".{asset_id[:12]}-", dir=object_root.parent
655 ))
656 try:
657 files = []
658 for item in reference.get("files", []):
659 source = Path(temporary, *item["archived_path"].split("/"))
660 if not source.is_file() or (
661 item.get("sha256") and _sha256_file(str(source)) != item["sha256"]
662 ):
663 raise StorageError(
664 f"Archived asset payload is missing or corrupt: {item['archived_path']}"
665 )
666 destination = object_staging / "payload" / item["path"]
667 destination.parent.mkdir(parents=True, exist_ok=True)
668 shutil.copy2(source, destination)
669 files.append({
670 "path": item["path"],
671 "bytes": destination.stat().st_size,
672 "sha256": _sha256_file(str(destination)),
673 })
674 _atomic_write_json(str(object_staging / "asset.json"), {
675 "schema_version": 1,
676 "asset_id": asset_id,
677 "kind": kind,
678 "provider": reference.get("provider"),
679 "provider_spec_sha256": spec_hash,
680 "recovered_from_archive": group["manifest"]["archive_id"],
681 "files": files,
682 })
683 try:
684 os.replace(object_staging, object_root)
685 except OSError as exc:
686 if exc.errno != errno.ENOTEMPTY and not object_root.is_dir():
687 raise
688 finally:
689 if object_staging.is_dir():
690 shutil.rmtree(object_staging, ignore_errors=True)
691 restored[spec_hash] = {
692 "asset_id": asset_id,
693 "kind": kind,
694 "provider": reference.get("provider"),
695 "provider_spec_sha256": spec_hash,
696 "object": object_relative,
697 "files": reference.get("files", []),
698 }
699 print(f"[INFO] Restored shared asset {kind}: {asset_id}")
700 return restored
701
702

◆ restore_archive()

dict picurv_cli.storage.operations.restore_archive ( dict  profile,
str  archive_id,
str   destination = None,
  checkpoints = None,
bool   force = False,
int   workers = None,
  components = None 
)

Download, verify, extract, and materialize an archive or selected checkpoints.

Parameters
[in]profileValue supplied through the profile argument.
[in]archive_idValue supplied through the archive_id argument.
[in]destinationValue supplied through the destination argument.
[in]checkpointsValue supplied through the checkpoints argument.
[in]forceValue supplied through the force argument.
[in]workersOptional parallel download and extraction worker count.
[in]componentsOptional semantic components to restore.
Returns
Result produced by this operation.

Definition at line 703 of file operations.py.

705 workers: int = None, components=None) -> dict:
706 """!
707 @brief Download, verify, extract, and materialize an archive or selected checkpoints.
708 @param[in] profile Value supplied through the `profile` argument.
709 @param[in] archive_id Value supplied through the `archive_id` argument.
710 @param[in] destination Value supplied through the `destination` argument.
711 @param[in] checkpoints Value supplied through the `checkpoints` argument.
712 @param[in] force Value supplied through the `force` argument.
713 @param[in] workers Optional parallel download and extraction worker count.
714 @param[in] components Optional semantic components to restore.
715 @return Result produced by this operation.
716 """
717 manifest = _load_remote_manifest(profile, archive_id)
718 original = os.path.abspath(manifest["original_path"])
719 destination_abs = os.path.abspath(destination or original)
720 selected_steps = {int(step) for step in (checkpoints or [])}
721 selected_components = {str(component) for component in (components or [])}
722 chunks = []
723 for chunk in manifest.get("chunks", []):
724 component = str(chunk.get("component", ""))
725 if selected_steps or selected_components:
726 if component in ALWAYS_RESTORED_COMPONENTS:
727 chunks.append(chunk)
728 elif component.startswith("checkpoint:") and int(component.split(":", 1)[1]) in selected_steps:
729 chunks.append(chunk)
730 elif component in selected_components:
731 chunks.append(chunk)
732 else:
733 chunks.append(chunk)
734 if selected_steps:
735 available = set(manifest.get("checkpoint_steps", []))
736 missing = selected_steps - available
737 if missing:
738 raise StorageError(f"Archive {archive_id} does not contain checkpoint step(s): {sorted(missing)}")
739 existing_state = read_storage_state(destination_abs) if os.path.isdir(destination_abs) else None
740 if os.path.exists(destination_abs) and not force:
741 if not existing_state or existing_state.get("archive_id") != archive_id:
742 raise StorageError(
743 f"Restore destination already exists and is not the matching cold artifact: {destination_abs}. "
744 "Choose --to or use --force after verifying the destination."
745 )
746 # Components this artifact already holds locally - restored earlier or never
747 # pruned - are not downloaded again; --force fetches everything.
748 already_local = (set(existing_state.get("restored_components") or [])
749 | set(existing_state.get("retained_components") or []))
750 def held_locally(component: str) -> bool:
751 """!
752 @brief Whether a chunk's component is already present in the destination.
753 @param[in] component Chunk component name.
754 @return True for a restored or retained component; a retained `checkpoints`
755 entry covers every committed step.
756 """
757 return component in already_local or (
758 component.startswith("checkpoint:") and "checkpoints" in already_local)
759
760 skipped = [chunk["component"] for chunk in chunks
761 if chunk.get("component") not in ALWAYS_RESTORED_COMPONENTS
762 and held_locally(str(chunk.get("component", "")))]
763 if skipped:
764 chunks = [chunk for chunk in chunks if chunk.get("component") not in skipped]
765 print(f"[INFO] Already local, not downloaded again: {', '.join(skipped)}")
766 parent = os.path.dirname(destination_abs)
767 os.makedirs(parent, exist_ok=True)
768 # Every selected chunk is extracted in full before `_merge_tree` copies it into
769 # `materialized`, so both copies exist on disk at once ahead of the final move.
770 extracted_bytes = sum(chunk.get("uncompressed_bytes", 0) for chunk in chunks)
771 _require_free_space(parent, 2 * extracted_bytes, f"restore archive {archive_id}")
772 temporary = tempfile.mkdtemp(prefix=f".picurv-restore-{archive_id[:8]}-", dir=parent)
773 materialized = os.path.join(temporary, "materialized")
774 os.makedirs(materialized)
775 try:
776 newly_restored = (
777 [f"checkpoint:{step}" for step in sorted(selected_steps)]
778 + sorted(selected_components)
779 )
780 prior_restored = (existing_state or {}).get("restored_components") or []
781 worker_count = int(workers or profile.get("workers", DEFAULT_STORAGE_WORKERS))
782 if worker_count <= 0:
783 raise StorageError("Restore workers must be positive.")
784
785 def download_and_extract(index_chunk):
786 """!
787 @brief Download, verify, and extract one archive chunk.
788 @param[in] index_chunk Tuple of chunk index and manifest entry.
789 @return Chunk index and extraction directory.
790 """
791 index, chunk = index_chunk
792 chunk_root = os.path.join(temporary, f"extract-{index:05d}")
793 os.makedirs(chunk_root)
794 local_chunk = os.path.join(temporary, chunk["name"])
795 print(f"[INFO] Restoring chunk {index + 1}/{len(chunks)}: {chunk['component']}")
796 _transport._run_rclone([
797 "copyto", _chunk_remote_path(profile, archive_id, chunk), local_chunk,
798 ])
799 actual = _sha256_file(local_chunk)
800 if actual != chunk.get("sha256"):
801 raise StorageError(
802 f"Downloaded chunk checksum mismatch: {chunk['name']} "
803 f"(expected {chunk.get('sha256')}, got {actual})."
804 )
805 _extract_chunk(local_chunk, chunk_root)
806 os.remove(local_chunk)
807 return index, chunk_root
808
809 task_workers = min(worker_count, max(1, len(chunks)))
810 if task_workers == 1:
811 extracted = [download_and_extract(item) for item in enumerate(chunks)]
812 else:
813 with concurrent.futures.ThreadPoolExecutor(max_workers=task_workers) as executor:
814 extracted = list(executor.map(download_and_extract, enumerate(chunks)))
815 for _, chunk_root in sorted(extracted):
816 _merge_tree(chunk_root, materialized)
817
818 if os.path.isdir(destination_abs):
819 _merge_tree(materialized, destination_abs)
820 else:
821 os.replace(materialized, destination_abs)
822 _restore_study_context(manifest, destination_abs)
823
824 replacements = [(original, destination_abs)]
825 original_study = manifest.get("original_study_path")
826 if original_study and manifest.get("artifact_type") == "study-case":
827 replacements.append((os.path.abspath(original_study), str(Path(destination_abs).parent.parent)))
828 rebased = _rebase_restored_text_paths(destination_abs, replacements)
829 state = {
830 "storage_schema_version": STORAGE_SCHEMA_VERSION,
831 "archive_id": archive_id,
832 "profile": profile["name"],
833 "remote": profile["remote"],
834 "label": manifest.get("label"),
835 "archived_at": manifest.get("created_at"),
836 "archived_checkpoints": manifest.get("checkpoint_steps") or [],
837 "restored_at": _utc_now(),
838 "local_pruned": bool(selected_steps or selected_components),
839 "restored_components": sorted(set(prior_restored) | set(newly_restored)),
840 "retained_components": (existing_state or {}).get("retained_components") or [],
841 "relocated_from": original if original != destination_abs else None,
842 "rebased_files": len(rebased),
843 }
844 _atomic_write_json(_state_path(destination_abs), state)
845 except Exception:
846 if os.path.isdir(temporary):
847 shutil.rmtree(temporary, ignore_errors=True)
848 raise
849 if os.path.isdir(temporary):
850 shutil.rmtree(temporary, ignore_errors=True)
851 print(f"[SUCCESS] Restored archive {archive_id} to {destination_abs}.")
852 if rebased:
853 print(f"[INFO] Rebased {len(rebased)} generated text artifact(s) to the restored path.")
854 return manifest
855
856
Here is the caller graph for this function:

◆ _expand_checkpoint_selection()

list picurv_cli.storage.operations._expand_checkpoint_selection (   explicit,
  ranges 
)
protected

Combine repeated --checkpoint values with START:END[:STRIDE] ranges.

Parameters
[in]explicitIndividually named steps, or None.
[in]rangesRange expressions, or None.
Returns
Sorted unique step list, or None when nothing was selected.

Definition at line 857 of file operations.py.

857def _expand_checkpoint_selection(explicit, ranges) -> list:
858 """!
859 @brief Combine repeated `--checkpoint` values with `START:END[:STRIDE]` ranges.
860 @param[in] explicit Individually named steps, or None.
861 @param[in] ranges Range expressions, or None.
862 @return Sorted unique step list, or None when nothing was selected.
863 """
864 selected = set(explicit or ())
865 for expression in ranges or ():
866 parts = str(expression).split(":")
867 if len(parts) not in (2, 3):
868 raise StorageError(
869 f"--checkpoints expects START:END or START:END:STRIDE, got {expression!r}."
870 )
871 try:
872 numbers = [int(part) for part in parts]
873 except ValueError:
874 raise StorageError(
875 f"--checkpoints expects integer steps, got {expression!r}."
876 ) from None
877 start, end = numbers[0], numbers[1]
878 stride = numbers[2] if len(numbers) == 3 else 1
879 if stride <= 0:
880 raise StorageError(f"--checkpoints stride must be positive, got {expression!r}.")
881 if end < start:
882 raise StorageError(f"--checkpoints end precedes start in {expression!r}.")
883 selected.update(range(start, end + 1, stride))
884 return sorted(selected) or None
885
886

◆ _resolve_archive_id_from_args()

str picurv_cli.storage.operations._resolve_archive_id_from_args (   args)
protected

Resolve an explicit archive ID or a local artifact marker.

Parameters
[in]argsValue supplied through the args argument.
Returns
Result produced by this operation.

Definition at line 887 of file operations.py.

887def _resolve_archive_id_from_args(args) -> str:
888 """!
889 @brief Resolve an explicit archive ID or a local artifact marker.
890 @param[in] args Value supplied through the `args` argument.
891 @return Result produced by this operation.
892 """
893 archive_id = getattr(args, "archive_id", None)
894 if archive_id:
895 return archive_id
896 workspace_id = getattr(args, "workspace_id", None)
897 if workspace_id:
898 return resolve_workspace_archive_id(
899 load_storage_profile(
900 getattr(args, "profile", None), getattr(args, "storage_config", None)
901 ),
902 workspace_id,
903 )
904 targets = resolve_local_storage_targets(
905 getattr(args, "run_dir", None), getattr(args, "study_dir", None), getattr(args, "case_ids", None),
906 workspace=getattr(args, "workspace", None),
907 )
908 if len(targets) != 1:
909 raise StorageError("Restore/verify by local marker requires exactly one target.")
910 state = read_storage_state(targets[0]["root_path"])
911 if not state or not state.get("archive_id"):
912 raise StorageError(f"No storage marker with an archive ID exists under {targets[0]['root_path']}.")
913 return state["archive_id"]
914
915

◆ _render_status()

None picurv_cli.storage.operations._render_status ( dict  inventory)
protected

Render one artifact status row and safety details.

Parameters
[in]inventoryValue supplied through the inventory argument.

Definition at line 916 of file operations.py.

916def _render_status(inventory: dict) -> None:
917 """!
918 @brief Render one artifact status row and safety details.
919 @param[in] inventory Value supplied through the `inventory` argument.
920 """
921 target = inventory["target"]
922 storage = inventory["storage"]
923 activity = "BUSY" if inventory["active_locks"] or inventory["slurm"]["active"] else storage["state"]
924 identity = (
925 target.get("case_id") or target.get("run_id") or target.get("study_id")
926 or target.get("workspace_id") or os.path.basename(target["root_path"])
927 )
928 print(
929 f"{identity:<36} {target['artifact_type']:<12} {activity:<10} "
930 f"{_human_bytes(inventory['total_bytes']):>12} {storage.get('label') or ''}"
931 )
932
933

◆ report_storage_configuration()

dict picurv_cli.storage.operations.report_storage_configuration ( dict  profile)

State which configuration answered, and warn when it came from outside.

Every command below acts on the remote this file names, and offload prunes local payload once that remote has verified the upload. Discovery searches upward past the workspace boundary, so the file that answered is not always the one the user thinks they are standing in; naming it here is what keeps an inherited configuration a choice rather than an accident.

Parameters
[in]profileResolved storage profile, carrying its config_path.
Returns
The profile, unchanged, so callers can wrap the load.

Definition at line 934 of file operations.py.

934def report_storage_configuration(profile: dict) -> dict:
935 """!
936 @brief State which configuration answered, and warn when it came from outside.
937
938 @details Every command below acts on the remote this file names, and `offload`
939 prunes local payload once that remote has verified the upload. Discovery
940 searches upward past the workspace boundary, so the file that answered is
941 not always the one the user thinks they are standing in; naming it here is
942 what keeps an inherited configuration a choice rather than an accident.
943 @param[in] profile Resolved storage profile, carrying its `config_path`.
944 @return The profile, unchanged, so callers can wrap the load.
945 """
946 config_path = profile.get("config_path")
947 origin = storage_config_origin(config_path)
948 # Provenance, not output: stderr keeps `list --format json` and `show` parseable.
949 print(f"[INFO] Storage config : {config_path}", file=sys.stderr)
950 print(f"[INFO] Storage profile: {profile['name']} -> {profile['remote']}", file=sys.stderr)
951 if origin == "shared":
952 print(
953 f"[WARNING] That configuration is outside this workspace; it is shared with "
954 f"everything below {os.path.dirname(os.path.abspath(config_path))}. Pass "
955 "--storage-config to choose another, or run 'picurv storage setup' here to "
956 "give this workspace its own.",
957 file=sys.stderr,
958 )
959 return profile
960
961
Here is the caller graph for this function:

◆ load_reported_storage_profile()

dict picurv_cli.storage.operations.load_reported_storage_profile (   args)

Load the storage profile a command will act on, and report its origin.

Parameters
[in]argsParsed storage command arguments.
Returns
Resolved storage profile.

Definition at line 962 of file operations.py.

962def load_reported_storage_profile(args) -> dict:
963 """!
964 @brief Load the storage profile a command will act on, and report its origin.
965 @param[in] args Parsed storage command arguments.
966 @return Resolved storage profile.
967 """
968 return report_storage_configuration(
969 load_storage_profile(getattr(args, "profile", None),
970 getattr(args, "storage_config", None))
971 )
972
973
Here is the call graph for this function:
Here is the caller graph for this function:

◆ storage_setup_workflow()

None picurv_cli.storage.operations.storage_setup_workflow (   args)

Create or update a non-secret workspace storage profile.

Parameters
[in]argsValue supplied through the args argument.

Definition at line 974 of file operations.py.

974def storage_setup_workflow(args) -> None:
975 """!
976 @brief Create or update a non-secret workspace storage profile.
977 @param[in] args Value supplied through the `args` argument.
978 """
979 explicit_config = getattr(args, "storage_config", None)
980 config_path = resolve_storage_config_path(explicit_config, require=False)
981 workspace_root = storage_workspace_root()
982 # Discovery walks past the workspace boundary, which is right for reading a shared
983 # configuration and wrong for writing one: `setup` inside a fresh workspace would
984 # otherwise rewrite the remote of the campaign directory above it, silently
985 # re-pointing every other workspace under it. Configure the workspace being stood
986 # in; editing a shared file stays available, but has to be asked for.
987 if not explicit_config and workspace_root and storage_config_origin(config_path, workspace_root) == "shared":
988 inherited = config_path
989 config_path = os.path.join(workspace_root, STORAGE_CONFIG_FILENAME)
990 print(
991 f"[INFO] A shared configuration exists at {inherited}, but it belongs to a "
992 "directory above this workspace."
993 )
994 print(
995 f" Writing this workspace's own configuration instead. To edit the "
996 f"shared one, pass --storage-config {inherited}."
997 )
998 payload = {}
999 if os.path.isfile(config_path):
1000 with open(config_path, "r", encoding="utf-8") as stream:
1001 payload = yaml.safe_load(stream) or {}
1002 profiles = payload.setdefault("profiles", {})
1003 profile_name = args.profile or DEFAULT_PROFILE_NAME
1004 profile = {
1005 "remote": args.remote.rstrip("/"),
1006 "compression": args.compression,
1007 "chunk_size_gib": args.chunk_size_gib,
1008 "workers": getattr(args, "workers", DEFAULT_STORAGE_WORKERS),
1009 "offload_policy": getattr(args, "offload_policy", "metadata-only"),
1010 "keep_latest_checkpoint": bool(getattr(args, "keep_latest_checkpoint", False)),
1011 }
1012 if args.staging_directory:
1013 profile["staging_directory"] = os.path.abspath(os.path.expanduser(args.staging_directory))
1014 payload["default_profile"] = profile_name
1015 profiles[profile_name] = profile
1016 print(f"[INFO] Storage config : {config_path}")
1017 print(f"[INFO] Profile : {profile_name}")
1018 print(f"[INFO] Remote : {profile['remote']}")
1019 if args.dry_run:
1020 print("[INFO] Dry-run only. No configuration or remote directories were changed.")
1021 return
1022 _transport._run_rclone(["mkdir", _remote_join(profile["remote"], REMOTE_OBJECTS_DIRECTORY)])
1023 os.makedirs(os.path.dirname(config_path), exist_ok=True)
1024 temporary = f"{config_path}.tmp.{os.getpid()}"
1025 with open(temporary, "w", encoding="utf-8") as stream:
1026 yaml.safe_dump(payload, stream, sort_keys=False)
1027 os.replace(temporary, config_path)
1028 print("[SUCCESS] Storage profile configured and remote access verified.")
1029
1030
Here is the caller graph for this function:

◆ storage_status_workflow()

None picurv_cli.storage.operations.storage_status_workflow (   args)

Print local storage and lifecycle status for selected artifacts.

Parameters
[in]argsValue supplied through the args argument.

Definition at line 1031 of file operations.py.

1031def storage_status_workflow(args) -> None:
1032 """!
1033 @brief Print local storage and lifecycle status for selected artifacts.
1034 @param[in] args Value supplied through the `args` argument.
1035 """
1036 if args.study_dir and not args.case_ids:
1037 study_root = os.path.abspath(args.study_dir)
1038 if getattr(args, "completed", False):
1039 case_ids = _select_completed_case_ids(study_root)
1040 else:
1041 case_ids = [
1042 path.name for path in sorted((Path(study_root) / "cases").glob("case_*")) if path.is_dir()
1043 ]
1044 targets = resolve_local_storage_targets(None, study_root, case_ids) if case_ids else resolve_local_storage_targets(None, study_root)
1045 else:
1046 targets = resolve_local_storage_targets(
1047 args.run_dir, args.study_dir, args.case_ids,
1048 workspace=getattr(args, "workspace", None),
1049 include_inputs=getattr(args, "include_inputs", False),
1050 completed=getattr(args, "completed", False),
1051 )
1052 inventories = [inspect_artifact(target) for target in targets]
1053 if args.output_format == "json":
1054 serializable = []
1055 for item in inventories:
1056 copy_item = dict(item)
1057 copy_item.pop("entries", None)
1058 serializable.append(copy_item)
1059 print(json.dumps(serializable, indent=2, sort_keys=True))
1060 return
1061 print(f"{'ARTIFACT':<36} {'TYPE':<12} {'STATE':<10} {'LOCAL SIZE':>12} LABEL")
1062 for inventory in inventories:
1063 _render_status(inventory)
1064
1065
Here is the caller graph for this function:

◆ storage_plan_workflow()

None picurv_cli.storage.operations.storage_plan_workflow (   args)

Render a read-only packaging and safety plan.

Parameters
[in]argsValue supplied through the args argument.

Definition at line 1066 of file operations.py.

1066def storage_plan_workflow(args) -> None:
1067 """!
1068 @brief Render a read-only packaging and safety plan.
1069 @param[in] args Value supplied through the `args` argument.
1070 """
1071 profile = load_reported_storage_profile(args)
1072 targets = resolve_local_storage_targets(
1073 args.run_dir, args.study_dir, args.case_ids,
1074 workspace=getattr(args, "workspace", None),
1075 include_inputs=getattr(args, "include_inputs", False),
1076 completed=getattr(args, "completed", False),
1077 )
1078 for index, target in enumerate(targets):
1079 if index:
1080 print()
1081 plan = build_storage_plan(
1082 target, profile, args.compression,
1083 policy=getattr(args, "policy", None),
1084 keep_latest_checkpoint=getattr(args, "keep_latest_checkpoint", None),
1085 workers=getattr(args, "workers", None),
1086 retain=getattr(args, "retain", None), drop=getattr(args, "drop", None),
1087 )
1088 _render_plan(plan)
1089 _assert_archive_safe(plan["inventory"])
1090
1091
Here is the call graph for this function:
Here is the caller graph for this function:

◆ storage_archive_workflow()

None picurv_cli.storage.operations.storage_archive_workflow (   args,
bool  prune_local 
)

Execute protect or offload for one or more explicit local targets.

Parameters
[in]argsValue supplied through the args argument.
[in]prune_localValue supplied through the prune_local argument.

Definition at line 1092 of file operations.py.

1092def storage_archive_workflow(args, prune_local: bool) -> None:
1093 """!
1094 @brief Execute protect or offload for one or more explicit local targets.
1095 @param[in] args Value supplied through the `args` argument.
1096 @param[in] prune_local Value supplied through the `prune_local` argument.
1097 """
1098 profile = load_reported_storage_profile(args)
1099 targets = resolve_local_storage_targets(
1100 args.run_dir, args.study_dir, args.case_ids,
1101 workspace=getattr(args, "workspace", None),
1102 include_inputs=getattr(args, "include_inputs", False),
1103 completed=getattr(args, "completed", False),
1104 )
1105 for target in targets:
1106 if args.dry_run:
1107 _render_plan(build_storage_plan(
1108 target, profile, args.compression,
1109 policy=getattr(args, "policy", None),
1110 keep_latest_checkpoint=getattr(args, "keep_latest_checkpoint", None),
1111 workers=getattr(args, "workers", None),
1112 retain=getattr(args, "retain", None), drop=getattr(args, "drop", None),
1113 ))
1114 print("[INFO] Dry-run only. No files were packaged, uploaded, or pruned.")
1115 continue
1116 archive_artifact(
1117 target,
1118 profile,
1119 label=args.label,
1120 tags=args.tags,
1121 compression=args.compression,
1122 prune_local=prune_local,
1123 policy=getattr(args, "policy", None),
1124 keep_latest_checkpoint=getattr(args, "keep_latest_checkpoint", None),
1125 workers=getattr(args, "workers", None),
1126 notes=getattr(args, "notes", None),
1127 retain=getattr(args, "retain", None),
1128 drop=getattr(args, "drop", None),
1129 )
1130
1131
Here is the call graph for this function:
Here is the caller graph for this function:

◆ storage_restore_workflow()

None picurv_cli.storage.operations.storage_restore_workflow (   args)

Restore a remote archive by globally unique ID or local marker.

Parameters
[in]argsValue supplied through the args argument.

Definition at line 1132 of file operations.py.

1132def storage_restore_workflow(args) -> None:
1133 """!
1134 @brief Restore a remote archive by globally unique ID or local marker.
1135 @param[in] args Value supplied through the `args` argument.
1136 """
1137 profile = load_reported_storage_profile(args)
1138 archive_id = _resolve_archive_id_from_args(args)
1139 restore_archive(
1140 profile,
1141 archive_id,
1142 destination=args.destination,
1143 checkpoints=_expand_checkpoint_selection(
1144 args.checkpoints, getattr(args, "checkpoint_ranges", None)
1145 ),
1146 force=args.force,
1147 workers=getattr(args, "workers", None),
1148 components=getattr(args, "components", None),
1149 )
1150
1151
Here is the call graph for this function:
Here is the caller graph for this function:

◆ storage_prune_workflow()

None picurv_cli.storage.operations.storage_prune_workflow (   args)

Remove local asset objects nothing local needs and storage has verified.

Parameters
[in]argsValue supplied through the args argument.

Definition at line 1152 of file operations.py.

1152def storage_prune_workflow(args) -> None:
1153 """!
1154 @brief Remove local asset objects nothing local needs and storage has verified.
1155 @param[in] args Value supplied through the `args` argument.
1156 """
1157 profile = load_reported_storage_profile(args)
1158 workspace_root = os.path.abspath(args.workspace) if args.workspace else _find_upwards(
1159 os.getcwd(), WORKSPACE_CONFIG_FILENAME
1160 )
1161 if workspace_root and os.path.isfile(workspace_root):
1162 workspace_root = os.path.dirname(workspace_root)
1163 if not workspace_root:
1164 raise StorageError(
1165 "No initialized workspace found. Pass --workspace, or run inside one."
1166 )
1167 decisions = prune_unused_workspace_assets(workspace_root, profile, dry_run=args.dry_run)
1168 if not decisions:
1169 print("[INFO] The workspace asset store holds no published objects.")
1170 return
1171 for decision in decisions:
1172 print(
1173 f"{decision['asset_id'][:16]} {decision['kind']}\n"
1174 f" referenced by remote runs {decision['cold_runs']}\n"
1175 f" referenced by active local runs {decision['active_local_runs']}\n"
1176 f" remote protection {decision['remote_protection']}\n"
1177 f" local removal {decision['local_removal']}"
1178 )
1179 removed = [item for item in decisions if item.get("removed")]
1180 failed = [item for item in decisions if item.get("error")]
1181 if args.dry_run:
1182 safe = [item for item in decisions if item["local_removal"] == "safe"]
1183 print(f"[INFO] Dry-run only. {len(safe)} object(s) would be removed.")
1184 else:
1185 for item in failed:
1186 print(f"[ERROR] Could not remove {item['object']}: {item['error']}", file=sys.stderr)
1187 print(f"[SUCCESS] Removed {len(removed)} local asset object(s).")
1188 if failed:
1189 raise StorageError(f"{len(failed)} asset object(s) could not be removed; see above.")
1190
1191
Here is the call graph for this function:
Here is the caller graph for this function:

◆ storage_verify_workflow()

None picurv_cli.storage.operations.storage_verify_workflow (   args)

Verify all remote chunks for one archive.

Parameters
[in]argsValue supplied through the args argument.

Definition at line 1192 of file operations.py.

1192def storage_verify_workflow(args) -> None:
1193 """!
1194 @brief Verify all remote chunks for one archive.
1195 @param[in] args Value supplied through the `args` argument.
1196 """
1197 profile = load_reported_storage_profile(args)
1198 archive_id = _resolve_archive_id_from_args(args)
1199 manifest = verify_remote_archive(profile, archive_id)
1200 print(
1201 f"[SUCCESS] Archive {archive_id} is complete; verified {len(manifest.get('chunks', []))} chunk(s)."
1202 )
1203
1204
Here is the call graph for this function:
Here is the caller graph for this function:

◆ storage_list_workflow()

None picurv_cli.storage.operations.storage_list_workflow (   args)

Search the remote manifest catalog without local artifact state.

Parameters
[in]argsValue supplied through the args argument.

Definition at line 1205 of file operations.py.

1205def storage_list_workflow(args) -> None:
1206 """!
1207 @brief Search the remote manifest catalog without local artifact state.
1208 @param[in] args Value supplied through the `args` argument.
1209 """
1210 profile = load_reported_storage_profile(args)
1211 manifests = list_remote_manifests(profile)
1212 workspace_label = getattr(args, "workspace_label", None)
1213 if workspace_label:
1214 manifests = [
1215 item for item in manifests
1216 if str(item.get("workspace_id") or "") == workspace_label
1217 ]
1218 query = str(args.search or "").lower()
1219 if query:
1220 manifests = [
1221 item for item in manifests
1222 if query in " ".join(
1223 str(item.get(key, "")) for key in (
1224 "archive_id", "label", "notes", "run_id", "study_id", "case_id",
1225 "workspace_id", "tags",
1226 )
1227 ).lower()
1228 ]
1229 if args.output_format == "json":
1230 print(json.dumps(manifests, indent=2, sort_keys=True))
1231 return
1232 print(f"{'ARCHIVE ID':<34} {'TYPE':<12} {'IDENTITY':<32} LABEL")
1233 for item in manifests:
1234 identity = (
1235 item.get("case_id") or item.get("run_id") or item.get("study_id")
1236 or item.get("workspace_id") or "-"
1237 )
1238 print(f"{item['archive_id']:<34} {item.get('artifact_type', '-'):<12} {identity:<32} {item.get('label', '')}")
1239
1240
Here is the call graph for this function:
Here is the caller graph for this function:

◆ storage_show_workflow()

None picurv_cli.storage.operations.storage_show_workflow (   args)

Show one complete remote archive manifest.

Parameters
[in]argsValue supplied through the args argument.

Definition at line 1241 of file operations.py.

1241def storage_show_workflow(args) -> None:
1242 """!
1243 @brief Show one complete remote archive manifest.
1244 @param[in] args Value supplied through the `args` argument.
1245 """
1246 profile = load_reported_storage_profile(args)
1247 manifest = _load_remote_manifest(profile, args.archive_id)
1248 print(json.dumps(manifest, indent=2, sort_keys=True))
1249
1250
Here is the call graph for this function:
Here is the caller graph for this function:

◆ storage_workflow()

None picurv_cli.storage.operations.storage_workflow (   args)

Dispatch nested storage actions using existing PICurv workflow conventions.

Parameters
[in]argsValue supplied through the args argument.

Definition at line 1251 of file operations.py.

1251def storage_workflow(args) -> None:
1252 """!
1253 @brief Dispatch nested storage actions using existing PICurv workflow conventions.
1254 @param[in] args Value supplied through the `args` argument.
1255 """
1256 try:
1257 action = args.storage_action
1258 if action == "setup":
1259 storage_setup_workflow(args)
1260 elif action == "status":
1261 storage_status_workflow(args)
1262 elif action == "plan":
1263 storage_plan_workflow(args)
1264 elif action == "protect":
1265 storage_archive_workflow(args, prune_local=False)
1266 elif action == "offload":
1267 storage_archive_workflow(args, prune_local=True)
1268 elif action == "restore":
1269 storage_restore_workflow(args)
1270 elif action == "prune":
1271 storage_prune_workflow(args)
1272 elif action == "verify":
1273 storage_verify_workflow(args)
1274 elif action == "list":
1275 storage_list_workflow(args)
1276 elif action == "show":
1277 storage_show_workflow(args)
1278 else:
1279 raise StorageError(f"Unsupported storage action: {action}")
1280 except StorageError as exc:
1281 print(f"[FATAL] {exc}", file=sys.stderr)
1282 raise SystemExit(1)
1283
1284
1285#: Help for --compression, from the policies in STORAGE_COMPRESSION_POLICIES.
Here is the call graph for this function:

◆ add_storage_parser()

argparse.ArgumentParser picurv_cli.storage.operations.add_storage_parser (   subparsers)

Attach the nested storage command parser to PICurv's top-level parser.

Parameters
[in]subparsersValue supplied through the subparsers argument.
Returns
Result produced by this operation.

Definition at line 1294 of file operations.py.

1294def add_storage_parser(subparsers) -> argparse.ArgumentParser:
1295 """!
1296 @brief Attach the nested storage command parser to PICurv's top-level parser.
1297 @param[in] subparsers Value supplied through the `subparsers` argument.
1298 @return Result produced by this operation.
1299 """
1300 parser = subparsers.add_parser(
1301 "storage",
1302 help="Protect, offload, inspect, verify, and restore run/study artifacts.",
1303 formatter_class=argparse.RawTextHelpFormatter,
1304 description=(
1305 "Manage PICurv run and study data through a configured rclone remote.\n"
1306 "Remote archives are checksum-verified before local payload can be pruned.\n\n"
1307 "Examples:\n"
1308 " picurv storage setup --remote labstore:picurv-data\n"
1309 " picurv storage status --run-dir runs/my_run\n"
1310 " picurv storage protect --run-dir runs/my_run --label 'baseline'\n"
1311 " picurv storage offload --study-dir studies/my_study --case-id case_0003\n"
1312 " picurv storage list --search '64-grid'\n"
1313 " picurv storage restore --archive-id <id>"
1314 ),
1315 epilog="Use `picurv storage <action> --help` for action-specific controls.",
1316 )
1317 actions = parser.add_subparsers(dest="storage_action", required=True, help="Storage action")
1318
1319 setup = actions.add_parser("setup", help="Configure a non-secret rclone storage profile.")
1320 setup.add_argument("--remote", required=True, help="Rclone remote and base path, such as labstore:picurv-data.")
1321 setup.add_argument("--profile", default=DEFAULT_PROFILE_NAME, help="Profile name (default: archive).")
1322 setup.add_argument("--storage-config", help=f"Storage YAML path (default: ./{STORAGE_CONFIG_FILENAME}).")
1323 setup.add_argument("--compression", choices=list(STORAGE_COMPRESSION_POLICIES), default="auto",
1324 help=COMPRESSION_HELP + " (default: auto).")
1325 setup.add_argument("--chunk-size-gib", type=float, default=DEFAULT_CHUNK_SIZE_GIB,
1326 help=f"Target archive chunk size in GiB (default: {DEFAULT_CHUNK_SIZE_GIB:g}); "
1327 "a larger file stays one chunk.")
1328 setup.add_argument("--workers", type=int, default=DEFAULT_STORAGE_WORKERS,
1329 help="CPU workers for compression and restoration.")
1330 setup.add_argument("--policy", "--offload-policy", dest="offload_policy",
1331 choices=list(STORAGE_OFFLOAD_POLICIES), default="metadata-only",
1332 help=POLICY_HELP + " The profile default (default: metadata-only).")
1333 setup.add_argument("--keep-latest-checkpoint", action="store_true",
1334 help="Retain the newest committed checkpoint after offload.")
1335 setup.add_argument("--staging-directory", help="Optional local directory for one archive chunk at a time.")
1336 setup.add_argument("--dry-run", action="store_true", help="Print the profile without writing it.")
1337
1338 def add_profile_options(action_parser):
1339 """!
1340 @brief Attach shared storage-profile selectors to one action parser.
1341 @param[in] action_parser Value supplied through the `action_parser` argument.
1342 """
1343 action_parser.add_argument("--profile", help="Configured storage profile name.")
1344 action_parser.add_argument("--storage-config", help="Explicit storage YAML path.")
1345
1346 def add_local_target(action_parser, require=True, allow_workspace=True):
1347 """!
1348 @brief Attach the standard run/study/workspace target selectors to one parser.
1349 @param[in] action_parser Value supplied through the `action_parser` argument.
1350 @param[in] require Value supplied through the `require` argument.
1351 @param[in] allow_workspace Whether a whole workspace is a valid target here.
1352 """
1353 group = action_parser.add_mutually_exclusive_group(required=require)
1354 group.add_argument("--run-dir", help="Standalone run directory.")
1355 group.add_argument("--study-dir", help="Sweep study directory.")
1356 if allow_workspace:
1357 group.add_argument(
1358 "--workspace",
1359 help="Workspace root: its configuration, catalog, and assets, not its "
1360 "runs and studies, which are their own artifacts.",
1361 )
1362 action_parser.add_argument(
1363 "--case-id", dest="case_ids", action="append",
1364 help="One numbered study member, such as case_0003; repeat to select several.",
1365 )
1366 action_parser.add_argument(
1367 "--completed", action="store_true",
1368 help="With --study-dir, select every finished member and skip the rest.",
1369 )
1370
1371 def add_retention_options(parser):
1372 """!
1373 @brief Add the per-component local-retention overrides to one action parser.
1374 @param[in] parser Action parser being configured.
1375 @return None.
1376 """
1377 parser.add_argument(
1378 "--retain", action="append", metavar="COMPONENT",
1379 help="Keep this component local regardless of --policy; repeatable and\n"
1380 "comma-separated. One of: " + ", ".join(STORAGE_RETENTION_COMPONENTS) + ".",
1381 )
1382 parser.add_argument(
1383 "--drop", action="append", metavar="COMPONENT",
1384 help="Prune this component locally regardless of --policy; same names as --retain.",
1385 )
1386
1387 status = actions.add_parser("status", help="Show local, protected, cold, and busy artifact state.")
1388 add_local_target(status)
1389 status.add_argument("--format", dest="output_format", choices=list(CLI_OUTPUT_FORMATS), default="text",
1390 help="Output format (default: text).")
1391
1392 plan = actions.add_parser("plan", help="Show packaging, dependencies, and safety checks without writing.")
1393 add_local_target(plan)
1394 add_profile_options(plan)
1395 plan.add_argument("--compression", choices=list(STORAGE_COMPRESSION_POLICIES),
1396 help=COMPRESSION_HELP + "; defaults to the profile's.")
1397 plan.add_argument("--policy", choices=list(STORAGE_OFFLOAD_POLICIES),
1398 help=POLICY_HELP + " Defaults to the profile's.")
1399 add_retention_options(plan)
1400 plan.add_argument("--workers", type=int, help="CPU workers; defaults to the profile's.")
1401 plan_checkpoint = plan.add_mutually_exclusive_group()
1402 plan_checkpoint.add_argument("--keep-latest-checkpoint", dest="keep_latest_checkpoint", action="store_true",
1403 help="Keep the newest committed checkpoint local under any policy.")
1404 plan_checkpoint.add_argument("--drop-all-checkpoints", dest="keep_latest_checkpoint", action="store_false",
1405 help="Keep no checkpoint local, overriding the profile.")
1406 plan.set_defaults(keep_latest_checkpoint=None)
1407
1408 for name, help_text in (
1409 ("protect", "Upload and verify an archive while retaining all local files."),
1410 ("offload", "Upload and verify an archive, then prune heavy local payload."),
1411 ):
1412 action_parser = actions.add_parser(name, help=help_text)
1413 add_local_target(action_parser)
1414 add_profile_options(action_parser)
1415 action_parser.add_argument(
1416 "--include-inputs", action="store_true",
1417 help="With --workspace, also archive user-supplied files under inputs/.",
1418 )
1419 action_parser.add_argument("--label", help="Human-readable searchable label.")
1420 action_parser.add_argument(
1421 "--notes", help="Free-text note recorded with the archive and shown by `show`."
1422 )
1423 action_parser.add_argument("--tag", dest="tags", action="append", help="Repeatable KEY=VALUE catalog tag.")
1424 action_parser.add_argument("--compression", choices=list(STORAGE_COMPRESSION_POLICIES),
1425 help=COMPRESSION_HELP + "; defaults to the profile's.")
1426 action_parser.add_argument("--policy", choices=list(STORAGE_OFFLOAD_POLICIES),
1427 help=POLICY_HELP + " Defaults to the profile's.")
1428 add_retention_options(action_parser)
1429 action_parser.add_argument("--workers", type=int, help="CPU workers; defaults to the profile's.")
1430 checkpoint_group = action_parser.add_mutually_exclusive_group()
1431 checkpoint_group.add_argument("--keep-latest-checkpoint", dest="keep_latest_checkpoint", action="store_true",
1432 help="Keep the newest committed checkpoint local under any policy.")
1433 checkpoint_group.add_argument("--drop-all-checkpoints", dest="keep_latest_checkpoint", action="store_false",
1434 help="Keep no checkpoint local, overriding the profile.")
1435 action_parser.set_defaults(keep_latest_checkpoint=None)
1436 action_parser.add_argument("--dry-run", action="store_true",
1437 help="Show the plan and safety checks without uploading.")
1438
1439 restore = actions.add_parser("restore", help="Restore a complete archive or selected checkpoints.")
1440 restore_source = restore.add_mutually_exclusive_group(required=True)
1441 restore_source.add_argument("--archive-id", help="Globally unique remote archive ID.")
1442 restore_source.add_argument(
1443 "--workspace-id", help="Restore a workspace archive by its recorded workspace identity."
1444 )
1445 restore_source.add_argument("--run-dir", help="Cold run containing a local storage marker.")
1446 restore_source.add_argument("--study-dir", help="Cold study containing a local storage marker.")
1447 restore.add_argument("--case-id", dest="case_ids", action="append",
1448 help="With --study-dir, one numbered member to restore; repeat to select several.")
1449 add_profile_options(restore)
1450 restore.add_argument("--to", dest="destination", help="Optional alternate restore destination.")
1451 restore.add_argument(
1452 "--checkpoint", dest="checkpoints", action="append", type=int,
1453 help="One committed step; repeat to select several.",
1454 )
1455 restore.add_argument(
1456 "--checkpoint-range", "--checkpoints", dest="checkpoint_ranges", action="append",
1457 help="An inclusive step range as START:END or START:END:STRIDE; repeatable.",
1458 )
1459 restore.add_argument(
1460 "--component", dest="components", action="append",
1461 choices=STORAGE_RESTORE_COMPONENTS,
1462 help="Restore one semantic component; repeat as needed.",
1463 )
1464 restore.add_argument("--force", action="store_true", help="Allow merge into a non-matching existing destination.")
1465 restore.add_argument("--workers", type=int, help="Parallel download/extraction workers.")
1466
1467 prune = actions.add_parser(
1468 "prune", help="Remove verified local asset objects that nothing local still needs."
1469 )
1470 prune.add_argument("--workspace", help="Workspace root; defaults to discovery from the cwd.")
1471 prune.add_argument(
1472 "--assets", action="store_true", required=True,
1473 help="Select the workspace asset store. Required: prune removes nothing else.",
1474 )
1475 prune.add_argument(
1476 "--unused-locally", action="store_true", required=True,
1477 help="Confirm that only objects with no active local run are removed.",
1478 )
1479 prune.add_argument("--dry-run", action="store_true", help="Report the decision only.")
1480 add_profile_options(prune)
1481
1482 verify = actions.add_parser("verify", help="Verify a remote archive completion marker and chunk checksums.")
1483 verify_source = verify.add_mutually_exclusive_group(required=True)
1484 verify_source.add_argument("--archive-id", help="Remote archive ID to verify.")
1485 verify_source.add_argument("--run-dir", help="Run whose recorded archive to verify.")
1486 verify_source.add_argument("--study-dir", help="Study whose recorded archive to verify.")
1487 verify_source.add_argument("--workspace", help="Workspace whose own archive to verify.")
1488 verify.add_argument("--case-id", dest="case_ids", action="append",
1489 help="With --study-dir, one numbered member to verify; repeat to select several.")
1490 add_profile_options(verify)
1491
1492 list_parser = actions.add_parser("list", help="List/search remote archives without local directories.")
1493 add_profile_options(list_parser)
1494 list_parser.add_argument("--search", help="Case-insensitive search across IDs, labels, identities, and tags.")
1495 list_parser.add_argument(
1496 "--workspace-label", help="Show only archives belonging to this workspace identity."
1497 )
1498 list_parser.add_argument("--format", dest="output_format", choices=list(CLI_OUTPUT_FORMATS), default="text",
1499 help="Output format (default: text).")
1500
1501 show = actions.add_parser("show", help="Print the complete manifest for one archive.")
1502 show.add_argument("--archive-id", required=True, help="Remote archive ID to show.")
1503 add_profile_options(show)
1504 return parser

Variable Documentation

◆ COMPRESSION_HELP

tuple picurv_cli.storage.operations.COMPRESSION_HELP
Initial value:
1= ("Archive compression: none, fast (gzip 1), balanced (gzip 6), maximum (xz 9), "
2 "or auto (by archive size)")

Definition at line 1286 of file operations.py.

◆ POLICY_HELP

tuple picurv_cli.storage.operations.POLICY_HELP
Initial value:
1= ("What offload keeps local: metadata-only (configuration, scheduler metadata, logs), "
2 "restart-ready (metadata-only plus inputs and the newest checkpoint), or "
3 "analysis-ready (metadata-only plus analysis and visualization).")

Definition at line 1289 of file operations.py.