138 policy: str =
None, keep_latest_checkpoint=
None,
139 workers: int =
None, retain=
None, drop=
None) -> dict:
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.
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)
161 worker_count = int(workers
or profile.get(
"workers", DEFAULT_STORAGE_WORKERS))
162 if worker_count <= 0:
164 compressed_range = _compression_size_range(inventory[
"total_bytes"], selected_compression)
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]},
176 "component": spec[
"component"],
177 "file_count": len(spec[
"entries"]),
178 "uncompressed_bytes": spec[
"uncompressed_bytes"],
246 compression: str =
None, prune_local: bool =
False,
247 policy: str =
None, keep_latest_checkpoint=
None,
248 workers: int =
None, notes: str =
None, retain=
None, drop=
None) -> dict:
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.
265 with storage_operation_lock(target[
"root_path"],
"offload" if prune_local
else "protect"):
267 target, profile, compression, policy=policy,
268 keep_latest_checkpoint=keep_latest_checkpoint, workers=workers,
269 retain=retain, drop=drop,
271 inventory = plan[
"inventory"]
272 _assert_archive_safe(inventory)
273 fingerprint = _inventory_fingerprint(inventory)
276 reusable = _find_reusable_archive(
277 profile, target, fingerprint,
278 compression=plan[
"compression"]
if compression
else None,
280 if reusable
is not None:
286 f
"[INFO] Reusing verified archive {reusable['archive_id']}: "
287 f
"{target['root_path']} is unchanged since it was archived."
289 return _register_existing_archive(
290 target, profile, reusable, inventory, plan, prune_local=prune_local,
291 label=label, tags=tags, notes=notes,
293 archive_id = uuid.uuid4().hex
294 specs = _build_chunk_specs(inventory, profile[
"chunk_size_bytes"])
295 staging_parent = profile.get(
"staging_directory")
297 staging_parent = os.path.abspath(os.path.expanduser(str(staging_parent)))
298 os.makedirs(staging_parent, exist_ok=
True)
303 concurrent_chunks = sorted(
304 (spec[
"uncompressed_bytes"]
for spec
in specs), reverse=
True
307 staging_parent
or tempfile.gettempdir(), sum(concurrent_chunks),
308 f
"stage {target['root_path']}",
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):
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.
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)
323 f
"[INFO] Packaging chunk {index + 1}/{len(specs)}: "
324 f
"{spec['component']} ({_human_bytes(spec['uncompressed_bytes'])})"
326 compressor = _write_tar_chunk(
327 target[
"root_path"], spec, local_chunk, plan[
"compression"],
328 workers=plan[
"workers"],
331 digest = _sha256_file(local_chunk)
335 if _remote_blob_present(profile, digest):
336 print(f
"[INFO] Chunk {index + 1}/{len(specs)} already stored; skipping upload.")
338 "sha256": digest,
"stored_bytes": os.path.getsize(local_chunk),
341 _transport._ensure_blob_directory(profile, digest)
342 verified = _transport._upload_verified(local_chunk, _blob_remote(profile, digest))
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,
355 os.remove(local_chunk)
356 except FileNotFoundError:
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)]
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"])
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"]),
383 "tags": _parse_tags(tags),
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"],
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),
409 "continuable": bool(inventory[
"checkpoint_steps"]),
410 "reprocessable": bool(inventory[
"checkpoint_steps"]),
411 "exact_binary_reproduction":
False,
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))
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": [],
435 _atomic_write_json(_state_path(target[
"root_path"]), state)
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)
448 f
"[SUCCESS] {'Offloaded' if prune_local else 'Protected'} {target['root_path']} "
449 f
"as archive {archive_id}."
540def _download_archive_components(profile: dict, manifest: dict, components: set,
541 destination: str, workers: int =
None) ->
None:
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.
552 chunk
for chunk
in manifest.get(
"chunks", [])
553 if str(chunk.get(
"component",
""))
in components
557 f
"Archive {manifest.get('archive_id')} has none of the requested components: "
558 +
", ".join(sorted(components))
560 worker_count = int(workers
or profile.get(
"workers", DEFAULT_STORAGE_WORKERS))
561 if worker_count <= 0:
563 os.makedirs(destination, exist_ok=
True)
566 extracted_bytes = sum(chunk.get(
"uncompressed_bytes", 0)
for chunk
in chunks)
568 destination, 2 * extracted_bytes, f
"restore archive {manifest.get('archive_id')} components"
570 with tempfile.TemporaryDirectory(prefix=
"picurv-component-restore-")
as staging:
571 def download_and_extract(index_chunk):
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.
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([
583 _chunk_remote_path(profile, manifest[
"archive_id"], chunk),
586 actual = _sha256_file(local_chunk)
587 if actual != chunk.get(
"sha256"):
589 f
"Downloaded chunk checksum mismatch: {chunk['name']} "
590 f
"(expected {chunk.get('sha256')}, got {actual})."
592 _extract_chunk(local_chunk, chunk_root)
593 return index, chunk_root
595 task_workers = min(worker_count, len(chunks))
596 if task_workers == 1:
597 extracted = [download_and_extract(item)
for item
in enumerate(chunks)]
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)
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.
612 requested = {str(value)
for value
in provider_spec_hashes
if value}
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))
619 for manifest
in sorted(
620 list_remote_manifests(profile), key=
lambda item: item.get(
"created_at",
""), reverse=
True
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):
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))
638 "initial-condition":
"initial_conditions",
639 "inlet-profiles":
"inlet_profiles",
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:
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
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"]
664 f
"Archived asset payload is missing or corrupt: {item['archived_path']}"
666 destination = object_staging /
"payload" / item[
"path"]
667 destination.parent.mkdir(parents=
True, exist_ok=
True)
668 shutil.copy2(source, destination)
670 "path": item[
"path"],
671 "bytes": destination.stat().st_size,
672 "sha256": _sha256_file(str(destination)),
674 _atomic_write_json(str(object_staging /
"asset.json"), {
676 "asset_id": asset_id,
678 "provider": reference.get(
"provider"),
679 "provider_spec_sha256": spec_hash,
680 "recovered_from_archive": group[
"manifest"][
"archive_id"],
684 os.replace(object_staging, object_root)
685 except OSError
as exc:
686 if exc.errno != errno.ENOTEMPTY
and not object_root.is_dir():
689 if object_staging.is_dir():
690 shutil.rmtree(object_staging, ignore_errors=
True)
691 restored[spec_hash] = {
692 "asset_id": asset_id,
694 "provider": reference.get(
"provider"),
695 "provider_spec_sha256": spec_hash,
696 "object": object_relative,
697 "files": reference.get(
"files", []),
699 print(f
"[INFO] Restored shared asset {kind}: {asset_id}")
704 checkpoints=
None, force: bool =
False,
705 workers: int =
None, components=
None) -> dict:
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.
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 [])}
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:
728 elif component.startswith(
"checkpoint:")
and int(component.split(
":", 1)[1])
in selected_steps:
730 elif component
in selected_components:
735 available = set(manifest.get(
"checkpoint_steps", []))
736 missing = selected_steps - available
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:
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."
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:
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.
757 return component
in already_local
or (
758 component.startswith(
"checkpoint:")
and "checkpoints" in already_local)
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",
"")))]
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)
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)
777 [f
"checkpoint:{step}" for step
in sorted(selected_steps)]
778 + sorted(selected_components)
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:
785 def download_and_extract(index_chunk):
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.
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,
799 actual = _sha256_file(local_chunk)
800 if actual != chunk.get(
"sha256"):
802 f
"Downloaded chunk checksum mismatch: {chunk['name']} "
803 f
"(expected {chunk.get('sha256')}, got {actual})."
805 _extract_chunk(local_chunk, chunk_root)
806 os.remove(local_chunk)
807 return index, chunk_root
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)]
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)
818 if os.path.isdir(destination_abs):
819 _merge_tree(materialized, destination_abs)
821 os.replace(materialized, destination_abs)
822 _restore_study_context(manifest, destination_abs)
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)
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),
844 _atomic_write_json(_state_path(destination_abs), state)
846 if os.path.isdir(temporary):
847 shutil.rmtree(temporary, ignore_errors=
True)
849 if os.path.isdir(temporary):
850 shutil.rmtree(temporary, ignore_errors=
True)
851 print(f
"[SUCCESS] Restored archive {archive_id} to {destination_abs}.")
853 print(f
"[INFO] Rebased {len(rebased)} generated text artifact(s) to the restored path.")
976 @brief Create or update a non-secret workspace storage profile.
977 @param[in] args Value supplied through the `args` argument.
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()
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)
991 f
"[INFO] A shared configuration exists at {inherited}, but it belongs to a "
992 "directory above this workspace."
995 f
" Writing this workspace's own configuration instead. To edit the "
996 f
"shared one, pass --storage-config {inherited}."
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
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)),
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']}")
1020 print(
"[INFO] Dry-run only. No configuration or remote directories were changed.")
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.")
1033 @brief Print local storage and lifecycle status for selected artifacts.
1034 @param[in] args Value supplied through the `args` argument.
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)
1042 path.name
for path
in sorted((Path(study_root) /
"cases").glob(
"case_*"))
if path.is_dir()
1044 targets = resolve_local_storage_targets(
None, study_root, case_ids)
if case_ids
else resolve_local_storage_targets(
None, study_root)
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),
1052 inventories = [inspect_artifact(target)
for target
in targets]
1053 if args.output_format ==
"json":
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))
1061 print(f
"{'ARTIFACT':<36} {'TYPE':<12} {'STATE':<10} {'LOCAL SIZE':>12} LABEL")
1062 for inventory
in inventories:
1063 _render_status(inventory)
1294def add_storage_parser(subparsers) -> argparse.ArgumentParser:
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.
1300 parser = subparsers.add_parser(
1302 help=
"Protect, offload, inspect, verify, and restore run/study artifacts.",
1303 formatter_class=argparse.RawTextHelpFormatter,
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"
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>"
1315 epilog=
"Use `picurv storage <action> --help` for action-specific controls.",
1317 actions = parser.add_subparsers(dest=
"storage_action", required=
True, help=
"Storage action")
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.")
1338 def add_profile_options(action_parser):
1340 @brief Attach shared storage-profile selectors to one action parser.
1341 @param[in] action_parser Value supplied through the `action_parser` argument.
1343 action_parser.add_argument(
"--profile", help=
"Configured storage profile name.")
1344 action_parser.add_argument(
"--storage-config", help=
"Explicit storage YAML path.")
1346 def add_local_target(action_parser, require=True, allow_workspace=True):
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.
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.")
1359 help=
"Workspace root: its configuration, catalog, and assets, not its "
1360 "runs and studies, which are their own artifacts.",
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.",
1366 action_parser.add_argument(
1367 "--completed", action=
"store_true",
1368 help=
"With --study-dir, select every finished member and skip the rest.",
1371 def add_retention_options(parser):
1373 @brief Add the per-component local-retention overrides to one action parser.
1374 @param[in] parser Action parser being configured.
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) +
".",
1382 parser.add_argument(
1383 "--drop", action=
"append", metavar=
"COMPONENT",
1384 help=
"Prune this component locally regardless of --policy; same names as --retain.",
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).")
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)
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."),
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/.",
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`."
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.")
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."
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.",
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.",
1459 restore.add_argument(
1460 "--component", dest=
"components", action=
"append",
1461 choices=STORAGE_RESTORE_COMPONENTS,
1462 help=
"Restore one semantic component; repeat as needed.",
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.")
1467 prune = actions.add_parser(
1468 "prune", help=
"Remove verified local asset objects that nothing local still needs."
1470 prune.add_argument(
"--workspace", help=
"Workspace root; defaults to discovery from the cwd.")
1472 "--assets", action=
"store_true", required=
True,
1473 help=
"Select the workspace asset store. Required: prune removes nothing else.",
1476 "--unused-locally", action=
"store_true", required=
True,
1477 help=
"Confirm that only objects with no active local run are removed.",
1479 prune.add_argument(
"--dry-run", action=
"store_true", help=
"Report the decision only.")
1480 add_profile_options(prune)
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)
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."
1498 list_parser.add_argument(
"--format", dest=
"output_format", choices=
list(CLI_OUTPUT_FORMATS), default=
"text",
1499 help=
"Output format (default: text).")
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)
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.