rhombus-materials 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rhombus/__init__.py +62 -0
- rhombus/_safe_io.py +90 -0
- rhombus/atomistics/__init__.py +0 -0
- rhombus/atomistics/campaign_dynamics.py +187 -0
- rhombus/atomistics/manual_import.py +8 -0
- rhombus/atomistics/manual_import_v2.py +138 -0
- rhombus/atomistics/manual_thermal.py +112 -0
- rhombus/atomistics/phase_stability_p1.py +56 -0
- rhombus/atomistics/thermal_study.py +225 -0
- rhombus/atomistics/thermal_trace.py +160 -0
- rhombus/automation/__init__.py +1 -0
- rhombus/automation/archive.py +56 -0
- rhombus/automation/campaign_worker_v3.py +250 -0
- rhombus/automation/cli.py +117 -0
- rhombus/automation/controller.py +119 -0
- rhombus/automation/kaggle.py +170 -0
- rhombus/automation/ledger.py +146 -0
- rhombus/automation/mcp_server.py +68 -0
- rhombus/automation/verify.py +77 -0
- rhombus/automation/worker.py +74 -0
- rhombus/benchmark/__init__.py +4 -0
- rhombus/benchmark/fp_deerr_calibration_loader.py +302 -0
- rhombus/benchmark/fp_deerr_cohort_audit.py +192 -0
- rhombus/benchmark/fp_deerr_gate0_freeze.py +362 -0
- rhombus/benchmark/fp_deerr_gate2_runner.py +521 -0
- rhombus/benchmark/fp_deerr_preregistration.py +859 -0
- rhombus/benchmark/fp_deerr_selective_evaluation.py +366 -0
- rhombus/benchmark/li2s_geometry_preflight.py +81 -0
- rhombus/benchmark/li2s_qe_resource_probe.py +43 -0
- rhombus/benchmark/linux_noescape_seccomp.py +130 -0
- rhombus/benchmark/qe_passive_inventory.py +39 -0
- rhombus/benchmark/reference_evidence.py +139 -0
- rhombus/benchmark/synthetic_container_supervisor.py +340 -0
- rhombus/benchmark/synthetic_hop_comparison.py +89 -0
- rhombus/benchmark/tier_a_budget_contract.py +338 -0
- rhombus/benchmark/tier_a_calculator_hook.py +98 -0
- rhombus/benchmark/tier_a_checkpoint_supply.py +189 -0
- rhombus/benchmark/tier_a_energy_pilot.py +88 -0
- rhombus/benchmark/tier_a_geometry_parser.py +76 -0
- rhombus/benchmark/tier_a_geometry_residual.py +131 -0
- rhombus/benchmark/tier_a_geometry_source.py +80 -0
- rhombus/benchmark/tier_a_initial_geometry.py +219 -0
- rhombus/benchmark/tier_a_input_pin.py +103 -0
- rhombus/benchmark/tier_a_local_meter.py +259 -0
- rhombus/benchmark/tier_a_matpes_checkpoint.py +55 -0
- rhombus/benchmark/tier_a_matpes_comparison.py +20 -0
- rhombus/benchmark/tier_a_model_neb_preflight.py +316 -0
- rhombus/benchmark/tier_a_observable_diagnostic.py +31 -0
- rhombus/benchmark/tier_a_power_envelope.py +141 -0
- rhombus/benchmark/tier_a_preflight.py +295 -0
- rhombus/benchmark/tier_a_preregistration.py +259 -0
- rhombus/benchmark/tier_a_publisher_method_audit.py +251 -0
- rhombus/benchmark/tier_a_relaxed_geometry_audit.py +88 -0
- rhombus/benchmark/tier_a_selective_design.py +239 -0
- rhombus/benchmark/tier_a_train_common_mode.py +204 -0
- rhombus/benchmark/tier_a_train_profile_diagnostics.py +279 -0
- rhombus/benchmark/tier_a_train_reference_semantics.py +125 -0
- rhombus/benchmark/tier_a_train_relaxed_zip_reader.py +423 -0
- rhombus/benchmark/tier_a_train_shape_only.py +209 -0
- rhombus/benchmark/tier_a_upstream_model_assets.py +61 -0
- rhombus/cli.py +394 -0
- rhombus/domain/__init__.py +115 -0
- rhombus/domain/applicability.py +115 -0
- rhombus/domain/archetypes.py +182 -0
- rhombus/domain/calibration.py +116 -0
- rhombus/domain/checkpoint_bundle.py +145 -0
- rhombus/domain/checkpoint_restore.py +75 -0
- rhombus/domain/checkpoint_staging.py +111 -0
- rhombus/domain/context.py +133 -0
- rhombus/domain/coverage.py +94 -0
- rhombus/domain/descriptors.py +63 -0
- rhombus/domain/distance.py +105 -0
- rhombus/domain/durable_shards.py +360 -0
- rhombus/domain/empirical.py +107 -0
- rhombus/domain/kaggle_recovery.py +68 -0
- rhombus/domain/lineage_readiness.py +235 -0
- rhombus/domain/membership.py +247 -0
- rhombus/domain/mpa0_publisher_digest.py +92 -0
- rhombus/domain/mpa0_training_lineage.py +102 -0
- rhombus/domain/mptrj.py +217 -0
- rhombus/domain/mptrj_artifact_zip.py +114 -0
- rhombus/domain/mptrj_energy_labels.py +81 -0
- rhombus/domain/mptrj_integrity.py +149 -0
- rhombus/domain/mptrj_probe_receipt.py +131 -0
- rhombus/domain/mptrj_run_metadata.py +107 -0
- rhombus/domain/mptrj_source_overlap.py +329 -0
- rhombus/domain/overlap.py +307 -0
- rhombus/domain/profiles.py +18 -0
- rhombus/domain/salex.py +266 -0
- rhombus/domain/shard_artifact.py +115 -0
- rhombus/domain/shard_attestation.py +52 -0
- rhombus/domain/shard_contract.py +129 -0
- rhombus/domain/shard_resume.py +63 -0
- rhombus/domain/structure_protocols.py +275 -0
- rhombus/domain/training_manifest.py +335 -0
- rhombus/domain/wbm.py +137 -0
- rhombus/domain/wbm_audit.py +324 -0
- rhombus/evidence/__init__.py +40 -0
- rhombus/evidence/identity.py +98 -0
- rhombus/evidence/legacy.py +567 -0
- rhombus/evidence/receipts.py +168 -0
- rhombus/evidence/registry.py +123 -0
- rhombus/evidence/runtime_provenance.py +72 -0
- rhombus/evidence/schema.py +285 -0
- rhombus/generation/__init__.py +1 -0
- rhombus/generation/autonomous_generator.py +84 -0
- rhombus/generation/defect_engine.py +280 -0
- rhombus/literature/__init__.py +1 -0
- rhombus/literature/cold_sintering.py +105 -0
- rhombus/literature/density_diagnostic.py +135 -0
- rhombus/literature/harvest.py +710 -0
- rhombus/literature/microwave.py +194 -0
- rhombus/literature/model_evidence_robustness.py +156 -0
- rhombus/literature/niobium_sintering.py +158 -0
- rhombus/literature/pretreatment_interaction.py +112 -0
- rhombus/literature/prior_exposure.py +101 -0
- rhombus/literature/process_features.py +287 -0
- rhombus/literature/retrospective.py +129 -0
- rhombus/literature/source_choice_gate.py +136 -0
- rhombus/literature/source_parsers.py +184 -0
- rhombus/literature/supplement.py +388 -0
- rhombus/literature/table4.py +208 -0
- rhombus/literature/workbook.py +231 -0
- rhombus/mcp/__init__.py +1 -0
- rhombus/mcp/catalog_v3.py +133 -0
- rhombus/paper_repro.py +51 -0
- rhombus/pipeline/__init__.py +4 -0
- rhombus/pipeline/funnel.py +90 -0
- rhombus/pipeline/scientific_adapters.py +191 -0
- rhombus/py.typed +0 -0
- rhombus/qualification/__init__.py +1 -0
- rhombus/qualification/cross_falsifier.py +20 -0
- rhombus/qualification/digital.py +56 -0
- rhombus/qualification/electrochemical_window.py +110 -0
- rhombus/qualification/electronic_insulation.py +43 -0
- rhombus/qualification/group_exclusion.py +228 -0
- rhombus/qualification/measurement_identity.py +383 -0
- rhombus/qualification/obelix_benchmark_intake.py +284 -0
- rhombus/qualification/observation_budget.py +204 -0
- rhombus/qualification/opinion_synthesizer.py +46 -0
- rhombus/qualification/pilot_artifacts.py +74 -0
- rhombus/qualification/process_choice_stability.py +250 -0
- rhombus/qualification/reference_phases.py +84 -0
- rhombus/qualification/sealed_evaluation.py +339 -0
- rhombus/qualification/steward_envelope.py +135 -0
- rhombus/qualification/steward_trust_registry.py +167 -0
- rhombus/qualification/transport_scoreability.py +316 -0
- rhombus/reporting.py +137 -0
- rhombus/tools/__init__.py +47 -0
- rhombus/tools/adaptive_replay.py +240 -0
- rhombus/tools/evidence_gap.py +170 -0
- rhombus/tools/evidence_manifest.py +120 -0
- rhombus/tools/evidence_query.py +200 -0
- rhombus/tools/mcp_server.py +342 -0
- rhombus/tools/read_only_analysis.py +373 -0
- rhombus/tools/selective_hop_decision.py +359 -0
- rhombus/tools/task_proposal.py +136 -0
- rhombus/tools/task_status.py +147 -0
- rhombus/tools/universal_cascade_mcp.py +94 -0
- rhombus/transport/__init__.py +23 -0
- rhombus/transport/admission.py +50 -0
- rhombus/transport/arrhenius_ensemble.py +58 -0
- rhombus/transport/bvse_parameters.py +162 -0
- rhombus/transport/bvse_percolation.py +428 -0
- rhombus/transport/calibration.py +88 -0
- rhombus/transport/certified_segment_bound.py +480 -0
- rhombus/transport/cif_probe.py +38 -0
- rhombus/transport/classify.py +72 -0
- rhombus/transport/cohort_audit.py +257 -0
- rhombus/transport/cohort_evidence.py +52 -0
- rhombus/transport/continuous_path_diagnostic.py +67 -0
- rhombus/transport/extension.py +66 -0
- rhombus/transport/neb_pathway.py +271 -0
- rhombus/transport/path_numerical_audit.py +22 -0
- rhombus/transport/periodic_clearance.py +48 -0
- rhombus/transport/periodic_string.py +36 -0
- rhombus/transport/segment_percolation.py +66 -0
- rhombus/transport/soft_clearance.py +20 -0
- rhombus/transport/static_assessment.py +449 -0
- rhombus/transport/static_channels.py +57 -0
- rhombus/transport/window_diagnostics.py +65 -0
- rhombus/validation/__init__.py +110 -0
- rhombus/validation/cascade_router.py +416 -0
- rhombus/validation/epistemic_qualification.py +342 -0
- rhombus/validation/pathway_forensics.py +608 -0
- rhombus/validation/physics_interceptor.py +540 -0
- rhombus/validation/sample_size_planner.py +69 -0
- rhombus/validation/universal_cascade.py +754 -0
- rhombus/validation/wbm_hull_cascade_0228.py +120 -0
- rhombus_materials-1.0.0.dist-info/METADATA +270 -0
- rhombus_materials-1.0.0.dist-info/RECORD +196 -0
- rhombus_materials-1.0.0.dist-info/WHEEL +5 -0
- rhombus_materials-1.0.0.dist-info/entry_points.txt +2 -0
- rhombus_materials-1.0.0.dist-info/licenses/LICENSE +184 -0
- rhombus_materials-1.0.0.dist-info/licenses/NOTICE +20 -0
- rhombus_materials-1.0.0.dist-info/top_level.txt +1 -0
rhombus/__init__.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Rhombus: Fail-closed evidence verification and compute-bounded selective routing."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
__version__ = "1.0.0"
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"__version__",
|
|
10
|
+
"FrozenCascadeContract",
|
|
11
|
+
"SequentialRiskMartingale",
|
|
12
|
+
"audit_neb_pathway_file_zero_label",
|
|
13
|
+
"audit_neb_pathways_zero_label",
|
|
14
|
+
"bound_fixed_potential_segment_maximum",
|
|
15
|
+
"bound_fixed_potential_segments_batch",
|
|
16
|
+
"bound_periodic_3d_percolation_bottleneck",
|
|
17
|
+
"bound_piecewise_linear_path_maximum",
|
|
18
|
+
"build_compact_agent_digest",
|
|
19
|
+
"build_fp_deerr_calibration_cascade_pareto",
|
|
20
|
+
"build_frozen_cascade_contract",
|
|
21
|
+
"calibrate_neyman_pearson_cascade",
|
|
22
|
+
"clopper_pearson_upper_bound",
|
|
23
|
+
"conformal_risk_upper_bound",
|
|
24
|
+
"decide_universal_cascade_batch",
|
|
25
|
+
"decide_universal_cascade_single",
|
|
26
|
+
"evaluate_two_stage_cascade_policy",
|
|
27
|
+
"load_frozen_cascade_contract",
|
|
28
|
+
"profile_cascade_pareto_grid",
|
|
29
|
+
"reproduce_diagonal_edge_counterexample",
|
|
30
|
+
"RhombusCascadeCalculator",
|
|
31
|
+
"TamperEvidentHashChainLedger",
|
|
32
|
+
"TrajectoryAbortedError",
|
|
33
|
+
"TrajectoryEarlyStopper",
|
|
34
|
+
"audit_nonconservative_work_mismatch",
|
|
35
|
+
"audit_trajectory_stream_payload",
|
|
36
|
+
"cascade_guard",
|
|
37
|
+
"split_structures_leak_free",
|
|
38
|
+
"audit_streaming_v2_composition_overlap",
|
|
39
|
+
"audit_streaming_v2_overlap_files",
|
|
40
|
+
"qualify_vasp_neb_bundle",
|
|
41
|
+
"verify_ledger_jsonl_file",
|
|
42
|
+
"min_accepted_samples_for_cp_bound",
|
|
43
|
+
"plan_prospective_cohort_sample_size",
|
|
44
|
+
"audit_cohort_sample_size_readiness",
|
|
45
|
+
"audit_fp_deerr_0212_release_readiness",
|
|
46
|
+
"audit_wbm_0228_release_readiness",
|
|
47
|
+
"stage1_hull_uncertainty",
|
|
48
|
+
"reproduce_paper_tables",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def __getattr__(name: str) -> Any:
|
|
53
|
+
if name in ("bound_fixed_potential_segment_maximum", "bound_fixed_potential_segments_batch", "bound_periodic_3d_percolation_bottleneck", "bound_piecewise_linear_path_maximum", "reproduce_diagonal_edge_counterexample"):
|
|
54
|
+
from .transport import certified_segment_bound
|
|
55
|
+
return getattr(certified_segment_bound, name)
|
|
56
|
+
if name == "reproduce_paper_tables":
|
|
57
|
+
from . import paper_repro
|
|
58
|
+
return paper_repro.reproduce_paper_tables
|
|
59
|
+
if name in __all__ and name != "__version__":
|
|
60
|
+
from . import validation
|
|
61
|
+
return getattr(validation, name)
|
|
62
|
+
raise AttributeError(f"module 'rhombus' has no attribute {name!r}")
|
rhombus/_safe_io.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Fail-closed regular-file O_NOFOLLOW/reparse readers and depth-bounded strict JSON."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import json, os, stat
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Iterator, Mapping
|
|
6
|
+
|
|
7
|
+
MAX_JSON_DEPTH = 64
|
|
8
|
+
_REP_SYM = getattr(stat, "IO_REPARSE_TAG_SYMLINK", 0xA000000C)
|
|
9
|
+
_REP_MNT = getattr(stat, "IO_REPARSE_TAG_MOUNT_POINT", 0xA0000003)
|
|
10
|
+
|
|
11
|
+
def _is_reparse(st: os.stat_result) -> bool:
|
|
12
|
+
return bool(stat.S_ISLNK(st.st_mode) or getattr(st, "st_reparse_tag", 0) in (_REP_SYM, _REP_MNT))
|
|
13
|
+
|
|
14
|
+
def verify_no_symlink_or_junction(p: Path, *, label: str) -> None:
|
|
15
|
+
if p.is_symlink(): raise ValueError(f"symlink {label} denied")
|
|
16
|
+
par = p.parent
|
|
17
|
+
if par and par != p:
|
|
18
|
+
if par.is_symlink(): raise ValueError(f"symlink parent directory for {label} denied")
|
|
19
|
+
try: pst = os.stat(par, follow_symlinks=False)
|
|
20
|
+
except FileNotFoundError: pst = None
|
|
21
|
+
if pst is not None and _is_reparse(pst): raise ValueError(f"reparse parent directory for {label} denied")
|
|
22
|
+
|
|
23
|
+
def check_json_depth(value: Any, *, max_depth: int = MAX_JSON_DEPTH, context: str = "JSON") -> None:
|
|
24
|
+
stk: list[tuple[Any, int]] = [(value, 0)]
|
|
25
|
+
while stk:
|
|
26
|
+
cur, d = stk.pop()
|
|
27
|
+
if isinstance(cur, Mapping):
|
|
28
|
+
if d + 1 > max_depth: raise ValueError(f"invalid {context}: nesting depth exceeds {max_depth}")
|
|
29
|
+
stk.extend((v, d + 1) for v in cur.values() if isinstance(v, (Mapping, list, tuple)))
|
|
30
|
+
elif isinstance(cur, (list, tuple)):
|
|
31
|
+
if d + 1 > max_depth: raise ValueError(f"invalid {context}: nesting depth exceeds {max_depth}")
|
|
32
|
+
stk.extend((v, d + 1) for v in cur if isinstance(v, (Mapping, list, tuple)))
|
|
33
|
+
|
|
34
|
+
def loads_strict_json(raw: bytes | str, *, context: str = "JSON", max_depth: int = MAX_JSON_DEPTH) -> Any:
|
|
35
|
+
def _u(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
36
|
+
d: dict[str, Any] = {}
|
|
37
|
+
for k, v in pairs:
|
|
38
|
+
if k in d: raise ValueError(f"duplicate JSON key: {k}")
|
|
39
|
+
d[k] = v
|
|
40
|
+
return d
|
|
41
|
+
def _c(tok: str) -> Any:
|
|
42
|
+
raise ValueError(f"non-finite JSON constant denied: {tok}")
|
|
43
|
+
try:
|
|
44
|
+
s = raw.decode("utf-8", "strict") if isinstance(raw, bytes) else raw
|
|
45
|
+
parsed = json.loads(s, object_pairs_hook=_u, parse_constant=_c)
|
|
46
|
+
except RecursionError as exc:
|
|
47
|
+
raise ValueError(f"invalid {context}: nesting depth limit exceeded") from exc
|
|
48
|
+
except (UnicodeError, json.JSONDecodeError, ValueError) as exc:
|
|
49
|
+
raise ValueError(f"invalid {context}: {exc}") from exc
|
|
50
|
+
check_json_depth(parsed, max_depth=max_depth, context=context)
|
|
51
|
+
return parsed
|
|
52
|
+
|
|
53
|
+
def _open_reg(p: Path, mb: int, lbl: str, m_exc: type[Exception], m_msg: str):
|
|
54
|
+
verify_no_symlink_or_junction(p, label=lbl)
|
|
55
|
+
try: s0 = os.stat(p, follow_symlinks=False)
|
|
56
|
+
except FileNotFoundError as exc: raise m_exc(m_msg or f"{lbl} not present") from exc
|
|
57
|
+
if _is_reparse(s0): raise ValueError(f"symlink or junction {lbl} denied")
|
|
58
|
+
if not stat.S_ISREG(s0.st_mode): raise ValueError(f"non-regular {lbl} denied")
|
|
59
|
+
if s0.st_size > mb: raise ValueError(f"{lbl} exceeds size budget")
|
|
60
|
+
try: fd = os.open(p, os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0))
|
|
61
|
+
except FileNotFoundError as exc: raise m_exc(m_msg or f"{lbl} not present") from exc
|
|
62
|
+
except OSError as exc: raise ValueError(f"{lbl} cannot be safely opened") from exc
|
|
63
|
+
f = os.fdopen(fd, "rb")
|
|
64
|
+
try:
|
|
65
|
+
s1 = os.fstat(f.fileno())
|
|
66
|
+
if not stat.S_ISREG(s1.st_mode) or (s0.st_ino and s1.st_ino and s0.st_ino != s1.st_ino) or (s0.st_dev and s1.st_dev and s0.st_dev != s1.st_dev):
|
|
67
|
+
raise ValueError(f"non-regular or swapped {lbl} denied")
|
|
68
|
+
if s1.st_size > mb: raise ValueError(f"{lbl} exceeds size budget")
|
|
69
|
+
except Exception:
|
|
70
|
+
f.close(); raise
|
|
71
|
+
return f
|
|
72
|
+
|
|
73
|
+
def read_regular_nofollow(p: Path, *, max_bytes: int, label: str, missing_exc: type[Exception] = FileNotFoundError, missing_msg: str = "") -> bytes:
|
|
74
|
+
with _open_reg(p, max_bytes, label, missing_exc, missing_msg) as f: b = f.read(max_bytes + 1)
|
|
75
|
+
if len(b) > max_bytes: raise ValueError(f"{label} exceeds size budget")
|
|
76
|
+
return b
|
|
77
|
+
|
|
78
|
+
def iter_regular_lines_nofollow(p: Path, *, max_source_bytes: int, max_line_bytes: int, label: str, missing_exc: type[Exception] = FileNotFoundError, missing_msg: str = "") -> Iterator[tuple[int, bytes]]:
|
|
79
|
+
with _open_reg(p, max_source_bytes, label, missing_exc, missing_msg) as f:
|
|
80
|
+
tot = ln = 0
|
|
81
|
+
while raw := f.readline(max_line_bytes + 1):
|
|
82
|
+
ln += 1
|
|
83
|
+
if len(raw) > max_line_bytes: raise ValueError(f"{label} record exceeds size budget at line {ln}")
|
|
84
|
+
tot += len(raw)
|
|
85
|
+
if tot > max_source_bytes: raise ValueError(f"{label} exceeds size budget")
|
|
86
|
+
yield ln, raw
|
|
87
|
+
|
|
88
|
+
def preflight_jsonl_snapshot(p: Path, *, max_source_bytes: int, max_line_bytes: int, label: str = "evidence snapshot") -> None:
|
|
89
|
+
for ln, raw in iter_regular_lines_nofollow(p, max_source_bytes=max_source_bytes, max_line_bytes=max_line_bytes, label=label, missing_msg="trusted EvidenceRecord snapshot not present"):
|
|
90
|
+
loads_strict_json(raw, context=f"evidence JSONL at line {ln}")
|
|
File without changes
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Kaggle-only MACE stages reusing canonical P2/P2.5, never dispatched by MCP."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import importlib.metadata
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def block_diffusivity(unwrapped_mobile, times_ps, *, seed, blocks=4, bootstrap=200):
|
|
11
|
+
"""Block-resample time origins of host-corrected MSD; SI D variance."""
|
|
12
|
+
positions, times = np.asarray(unwrapped_mobile, float), np.asarray(times_ps, float)
|
|
13
|
+
if (positions.ndim != 3 or positions.shape[2] != 3 or not positions.shape[1]
|
|
14
|
+
or len(positions) != len(times) or len(times) < 64
|
|
15
|
+
or not np.isfinite(positions).all() or not np.isfinite(times).all()
|
|
16
|
+
or not np.allclose(np.diff(times), times[1]-times[0]) or times[1] <= times[0]
|
|
17
|
+
or not 4 <= blocks <= 16 or not 50 <= bootstrap <= 1000):
|
|
18
|
+
raise ValueError('bounded uniformly sampled block trajectory required')
|
|
19
|
+
lags = np.arange(1, len(times)//4+1)
|
|
20
|
+
origins = np.arange(len(times)-lags[-1])
|
|
21
|
+
curves = []
|
|
22
|
+
for chunk in np.array_split(origins, blocks):
|
|
23
|
+
if len(chunk) < 8:
|
|
24
|
+
raise ValueError('insufficient independent origin blocks')
|
|
25
|
+
curves.append([np.mean(np.sum((positions[chunk+k]-positions[chunk])**2, axis=2)) for k in lags])
|
|
26
|
+
curves = np.array(curves)
|
|
27
|
+
fit = slice(len(lags)//3, None)
|
|
28
|
+
lag_times = lags*(times[1]-times[0])
|
|
29
|
+
estimate = lambda curve: float(np.polyfit(lag_times[fit], curve[fit], 1)[0]/6*1e-8)
|
|
30
|
+
d = estimate(curves.mean(axis=0))
|
|
31
|
+
rng = np.random.default_rng(seed)
|
|
32
|
+
samples = [estimate(curves[rng.integers(0, blocks, blocks)].mean(axis=0)) for _ in range(bootstrap)]
|
|
33
|
+
variance = float(np.var(samples, ddof=1))
|
|
34
|
+
if d <= 0 or variance <= 0 or not math.isfinite(d+variance):
|
|
35
|
+
raise ValueError('unresolved diffusivity or variance')
|
|
36
|
+
return {'diffusivity_m2_s': d, 'diffusivity_variance': variance,
|
|
37
|
+
'method': 'HOST_CORRECTED_MSD_BLOCK_ORIGIN_BOOTSTRAP',
|
|
38
|
+
'block_count': blocks, 'bootstrap_count': bootstrap, 'qualification': 'ABSTAIN'}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class KaggleMACEStages:
|
|
42
|
+
def __init__(self, protocol, *, checkpoint, output_dir, binding):
|
|
43
|
+
if not Path('/kaggle/working').is_dir() or not Path('/kaggle/input').is_dir():
|
|
44
|
+
raise PermissionError('Kaggle runtime required; no local MLIP fallback')
|
|
45
|
+
self.protocol, self.checkpoint, self.binding = protocol, checkpoint, binding
|
|
46
|
+
self.output = Path(output_dir)
|
|
47
|
+
self.output.mkdir(exist_ok=False)
|
|
48
|
+
self.calc = None
|
|
49
|
+
temperatures = protocol['temperatures_K']; seeds = protocol['seeds']
|
|
50
|
+
if (not 3 <= len(temperatures) <= 6 or len(set(temperatures)) != len(temperatures)
|
|
51
|
+
or not all(isinstance(t, (float, int)) and 0 < t <= 1500 for t in temperatures)
|
|
52
|
+
or max(temperatures)-min(temperatures) < 150
|
|
53
|
+
or not 2 <= len(seeds) <= 4 or len(set(seeds)) != len(seeds)
|
|
54
|
+
or any(type(s) is not int or not 0 <= s < 2**31 for s in seeds)):
|
|
55
|
+
raise ValueError('explicit bounded multi-temperature/multi-seed protocol required')
|
|
56
|
+
md = protocol['md']
|
|
57
|
+
if (set(md) != {'equil_steps', 'production_steps', 'timestep_fs', 'sample_interval_steps'}
|
|
58
|
+
or any(type(md[k]) is not int for k in ('equil_steps', 'production_steps', 'sample_interval_steps'))
|
|
59
|
+
or not 1 <= md['equil_steps'] <= 2000 or not 1 <= md['production_steps'] <= 10000
|
|
60
|
+
or not .1 <= md['timestep_fs'] <= 2 or not 1 <= md['sample_interval_steps'] <= 100
|
|
61
|
+
or not 1 <= protocol['relaxation_max_steps'] <= 200 or not 1 <= protocol['mep_max_steps'] <= 20):
|
|
62
|
+
raise ValueError('bounded new campaign scientific protocol required')
|
|
63
|
+
model = Path(protocol['model_path'])
|
|
64
|
+
if (model.is_symlink() or not model.resolve().is_relative_to(Path('/kaggle/input').resolve())
|
|
65
|
+
or model.stat().st_size > 80000000
|
|
66
|
+
or protocol['model_sha256'] != '75428afe3a1d7d8062e19bcaabd5c433623cabf308242ec9fb493e38604fb638'
|
|
67
|
+
or hashlib.sha256(model.read_bytes()).hexdigest() != protocol['model_sha256']):
|
|
68
|
+
raise ValueError('frozen MACE model mismatch before deserialization')
|
|
69
|
+
if not {'torch', 'mace-torch', 'numpy', 'ase', 'pymatgen'} <= set(protocol.get('runtime_pins', {})):
|
|
70
|
+
raise ValueError('exact runtime pins required')
|
|
71
|
+
for package, version in protocol['runtime_pins'].items():
|
|
72
|
+
if importlib.metadata.version(package) != version:
|
|
73
|
+
raise ValueError('runtime pin mismatch: '+package)
|
|
74
|
+
|
|
75
|
+
def calculator(self):
|
|
76
|
+
if self.calc is None:
|
|
77
|
+
import torch
|
|
78
|
+
torch.set_num_threads(2)
|
|
79
|
+
from mace.calculators import MACECalculator
|
|
80
|
+
self.calc = MACECalculator(model_paths=self.protocol['model_path'], device='cpu', default_dtype='float64')
|
|
81
|
+
self.checkpoint()
|
|
82
|
+
return self.calc
|
|
83
|
+
|
|
84
|
+
def adapters(self):
|
|
85
|
+
return {'P1': self.relax, 'P1_5': self.mep, 'P2': self.dynamics}
|
|
86
|
+
|
|
87
|
+
def relax(self, context):
|
|
88
|
+
from rhombus.pipeline.scientific_adapters import current_structure
|
|
89
|
+
from rhombus.atomistics.phase_stability_p1 import assess_phase_stability
|
|
90
|
+
from pymatgen.io.ase import AseAtomsAdaptor
|
|
91
|
+
from ase.optimize import FIRE
|
|
92
|
+
if not context.get('phase_references'):
|
|
93
|
+
return {'decision': 'ABSTAIN', 'gate_verdict': 'COMPETING_PHASE_REFERENCE_ENERGIES_REQUIRED'}
|
|
94
|
+
structure = current_structure(context)
|
|
95
|
+
atoms = AseAtomsAdaptor.get_atoms(structure)
|
|
96
|
+
atoms.calc = self.calculator()
|
|
97
|
+
optimizer = FIRE(atoms, logfile=None)
|
|
98
|
+
optimizer.attach(self.checkpoint, interval=1)
|
|
99
|
+
converged = optimizer.run(fmax=.05, steps=self.protocol['relaxation_max_steps'])
|
|
100
|
+
relaxed = AseAtomsAdaptor.get_structure(atoms)
|
|
101
|
+
energy = {'composition': relaxed.composition.element_composition.as_dict(),
|
|
102
|
+
'energy_eV': float(atoms.get_potential_energy()),
|
|
103
|
+
'energy_model_id': self.protocol['model_sha256'], 'reference_id': context['candidate_id']+'-relaxed'}
|
|
104
|
+
result = assess_phase_stability(energy, context['phase_references'])
|
|
105
|
+
result.update(structure=relaxed.as_dict(), phase_energy=energy, relaxation_converged=bool(converged),
|
|
106
|
+
relaxation_scope='FIXED_CELL_ATOMIC_RELAXATION')
|
|
107
|
+
if not converged:
|
|
108
|
+
result['decision'] = 'ABSTAIN'
|
|
109
|
+
self.checkpoint({'kind': 'relaxation', 'candidate_id': context['candidate_id'], 'result': result})
|
|
110
|
+
return result
|
|
111
|
+
|
|
112
|
+
def mep(self, context):
|
|
113
|
+
from pymatgen.io.ase import AseAtomsAdaptor
|
|
114
|
+
from rhombus.pipeline.scientific_adapters import current_structure
|
|
115
|
+
from rhombus.transport.neb_pathway import ASEMobileIonEvaluator, ClimbingImageMEPSolver
|
|
116
|
+
s = current_structure(context)
|
|
117
|
+
targets = context['G']['defect'].get('vacant_fractional_targets', [])
|
|
118
|
+
if not targets:
|
|
119
|
+
return {'decision': 'ABSTAIN', 'gate_verdict': 'VACANCY_TARGET_REQUIRED'}
|
|
120
|
+
index = min((i for i, a in enumerate(s) if a.specie.symbol == 'Li'),
|
|
121
|
+
key=lambda i: s.lattice.get_distance_and_image(s[i].frac_coords, targets[0])[0])
|
|
122
|
+
_, image = s.lattice.get_distance_and_image(s[index].frac_coords, targets[0])
|
|
123
|
+
evaluator = ASEMobileIonEvaluator(AseAtomsAdaptor.get_atoms(s), index, self.calculator(), allow_evaluation=True)
|
|
124
|
+
def forces(points):
|
|
125
|
+
self.checkpoint()
|
|
126
|
+
return evaluator(points)
|
|
127
|
+
result = ClimbingImageMEPSolver().solve(s[index].coords, s.lattice.get_cartesian_coords(np.array(targets[0])+image),
|
|
128
|
+
forces, max_steps=self.protocol['mep_max_steps'])
|
|
129
|
+
result['decision'] = 'ABSTAIN' if not result['converged'] else 'REJECT' if result['barrier_ev'] > 1 else 'CONTINUE'
|
|
130
|
+
self.checkpoint({'kind': 'mep', 'candidate_id': context['candidate_id'], 'result': result})
|
|
131
|
+
return result
|
|
132
|
+
|
|
133
|
+
def dynamics(self, context):
|
|
134
|
+
from rhombus.pipeline.scientific_adapters import current_structure
|
|
135
|
+
from rhombus.atomistics.thermal_trace import build_thermal_trace, write_thermal_trace
|
|
136
|
+
from rhombus.transport.classify import classify_transport_regime
|
|
137
|
+
from rhombus.transport.window_diagnostics import multi_origin_msd
|
|
138
|
+
from rudeus.mlip.p2 import P2_PROTOCOL_DEFAULTS, DiagnosticStall, run_nvt, build_p2_result, protocol_config_hash, unwrap_trajectory
|
|
139
|
+
from rudeus.mlip.sharding import structure_dict_sha256
|
|
140
|
+
structure = current_structure(context)
|
|
141
|
+
records = []
|
|
142
|
+
for temperature in self.protocol['temperatures_K']:
|
|
143
|
+
for seed in self.protocol['seeds']:
|
|
144
|
+
self.checkpoint()
|
|
145
|
+
cfg = dict(P2_PROTOCOL_DEFAULTS, **self.protocol['md'])
|
|
146
|
+
cfg.update(temperature_K=temperature, base_seed=seed)
|
|
147
|
+
def budget(step, phase):
|
|
148
|
+
from rhombus.automation.campaign_worker_v3 import CampaignBudgetStop
|
|
149
|
+
try:
|
|
150
|
+
self.checkpoint()
|
|
151
|
+
except CampaignBudgetStop as exc:
|
|
152
|
+
raise DiagnosticStall('campaign sealing deadline') from exc
|
|
153
|
+
raw_structure = structure.as_dict()
|
|
154
|
+
record = run_nvt(raw_structure, self.calculator(), cfg, seed, step_hook=budget, retain_thermal_trace=True)
|
|
155
|
+
binding = {'task_id': self.binding['task_id'], 'candidate_id': context['candidate_id'],
|
|
156
|
+
'source_sha256': context.get('source_sha256') or structure_dict_sha256(raw_structure),
|
|
157
|
+
'relaxed_structure_sha256': structure_dict_sha256(raw_structure),
|
|
158
|
+
'model_sha256': self.protocol['model_sha256'], 'protocol_sha256': self.binding['protocol_sha256'],
|
|
159
|
+
'source_commit': self.binding['source_commit'], 'runtime': self.protocol['runtime_pins']}
|
|
160
|
+
trace = write_thermal_trace(self.output, build_thermal_trace(record, binding, cfg))
|
|
161
|
+
batch = hashlib.sha256(f'{context["candidate_id"]}-{temperature}-{seed}'.encode()).hexdigest()[:24]
|
|
162
|
+
job = {'batch_id': batch, 'child_material_id': context['candidate_id'], 'parent_id': context['template_id'],
|
|
163
|
+
'relaxed_structure_sha256': binding['relaxed_structure_sha256'], 'p2_protocol': cfg,
|
|
164
|
+
'p2_config_hash': protocol_config_hash(cfg), 'seed': seed}
|
|
165
|
+
result = build_p2_result(job, record, {'checkpoint_name': 'medium-mpa-0', 'checkpoint_sha256': self.protocol['model_sha256']},
|
|
166
|
+
traj_artifact_dir=self.output)
|
|
167
|
+
unit = {'kind': 'trajectory', 'candidate_id': context['candidate_id'], 'temperature_K': temperature,
|
|
168
|
+
'seed': seed, 'trace': trace, 'P2': result, 'termination_completed': record['completed']}
|
|
169
|
+
# Preserve raw output before budget or scientific insufficiency stops analysis.
|
|
170
|
+
self.checkpoint(unit)
|
|
171
|
+
if result['p2_verdict'] != 'PASS':
|
|
172
|
+
return {'decision': 'ABSTAIN', 'gate_verdict': 'P2_NOT_PASSED', 'thermal_records': records}
|
|
173
|
+
classification = classify_transport_regime(stability_payload={'batch_id': batch, 'result': result})
|
|
174
|
+
frames = [f for f in record['frames'] if f['phase'] == 'production']
|
|
175
|
+
x = unwrap_trajectory(np.array([f['positions'] for f in frames]), np.array(record['cell']))
|
|
176
|
+
indices = np.array([s == 'Li' for s in record['species']])
|
|
177
|
+
times = np.array([f['md_step'] for f in frames])*record['timestep_fs']/1000
|
|
178
|
+
diagnostic = multi_origin_msd(x[:, indices], x[:, ~indices], times, host_limit_angstrom=.5)
|
|
179
|
+
if classification['transport_state'] != 'DIFFUSIVE' or diagnostic['regime'] != 'DIFFUSIVE_FICKIAN':
|
|
180
|
+
self.checkpoint({'kind': 'regime', 'candidate_id': context['candidate_id'], 'legacy': classification, 'diagnostic': diagnostic})
|
|
181
|
+
return {'decision': 'ABSTAIN', 'gate_verdict': 'DIFFUSIVE_SAMPLING_NOT_ESTABLISHED', 'thermal_records': records}
|
|
182
|
+
corrected = x[:, indices]-(x[:, ~indices].mean(axis=1)-x[0, ~indices].mean(axis=0))[:, None, :]
|
|
183
|
+
estimate = block_diffusivity(corrected, times, seed=seed)
|
|
184
|
+
row = dict(estimate, temperature_K=temperature, seed=seed, p2_verdict='PASS', regime='DIFFUSIVE_FICKIAN')
|
|
185
|
+
records.append(row)
|
|
186
|
+
self.checkpoint({'kind': 'diffusivity', 'candidate_id': context['candidate_id'], 'record': row})
|
|
187
|
+
return {'decision': 'CONTINUE', 'gate_verdict': 'MEASURED_P2_PASSED', 'thermal_records': records}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Compatibility alias for the corrected version 2 manual importer.
|
|
2
|
+
|
|
3
|
+
Historical v1 remains in the immutable 0202 execution commit. Its partial
|
|
4
|
+
records require revalidation from the original archive.
|
|
5
|
+
"""
|
|
6
|
+
from rhombus.atomistics.manual_import_v2 import import_manual_result
|
|
7
|
+
|
|
8
|
+
__all__ = ('import_manual_result',)
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Version 2 manual importer; execution source and verifier remain separate."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import stat
|
|
6
|
+
import zipfile
|
|
7
|
+
import rhombus.atomistics.manual_thermal as manual_thermal_module
|
|
8
|
+
import rhombus.atomistics.thermal_study as thermal_study_module
|
|
9
|
+
import rhombus.atomistics.thermal_trace as thermal_trace_module
|
|
10
|
+
|
|
11
|
+
IMPORT_VERSION = 'rhombus-owner-manual-import-v2'
|
|
12
|
+
|
|
13
|
+
from rhombus.atomistics.manual_thermal import validate_manual_request
|
|
14
|
+
from rhombus.atomistics.thermal_study import verify_thermal_result_artifacts
|
|
15
|
+
from rhombus.atomistics.thermal_trace import canonical_bytes, sha256
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def import_manual_result(archive_path, request, destination, *, root, expected_archive_sha256=None):
|
|
19
|
+
validate_manual_request(request,root)
|
|
20
|
+
archive_path=Path(archive_path);destination=Path(destination)
|
|
21
|
+
limit=request['protocol']['resource_budget']['output_bytes']+1048576
|
|
22
|
+
if archive_path.stat().st_size>limit:raise ValueError('archive size budget')
|
|
23
|
+
archive_sha=sha256(archive_path.read_bytes())
|
|
24
|
+
if expected_archive_sha256 is not None and archive_sha!=expected_archive_sha256:
|
|
25
|
+
raise ValueError('download archive digest mismatch')
|
|
26
|
+
if destination.exists():raise FileExistsError('preserve prior import')
|
|
27
|
+
with zipfile.ZipFile(archive_path) as z:
|
|
28
|
+
members=z.infolist();names=[i.filename for i in members]
|
|
29
|
+
if (len(members)>100 or len(names)!=len(set(names)) or sum(i.file_size for i in members)>limit
|
|
30
|
+
or any(Path(i.filename).name!=i.filename or '\\' in i.filename or i.filename in ('.','..')
|
|
31
|
+
or i.is_dir() or stat.S_ISLNK(i.external_attr>>16) or i.flag_bits&1 for i in members)):
|
|
32
|
+
raise ValueError('unsafe/duplicate/traversal/archive budget')
|
|
33
|
+
if 'download-manifest.json' not in names:raise ValueError('missing download manifest')
|
|
34
|
+
d=json.loads(z.read('download-manifest.json'))
|
|
35
|
+
if (d.get('schema_version')!='rhombus-owner-download-v1' or d['request_sha256']!=sha256(canonical_bytes(request))
|
|
36
|
+
or d['task_id']!=request['task_id'] or d['launch_id']!=request['launch_id']
|
|
37
|
+
or d.get('provider_attestation')!='UNAVAILABLE'
|
|
38
|
+
or set(names)!=set(d['files'])|{'download-manifest.json'}):
|
|
39
|
+
raise ValueError('download/request inventory mismatch')
|
|
40
|
+
for name,row in d['files'].items():
|
|
41
|
+
raw=z.read(name)
|
|
42
|
+
if len(raw)!=row['size_bytes'] or sha256(raw)!=row['sha256']:
|
|
43
|
+
raise ValueError('download artifact digest mismatch')
|
|
44
|
+
# Bound the inner NPZ too before numpy decompresses it.
|
|
45
|
+
if name.endswith('.npz'):
|
|
46
|
+
import io
|
|
47
|
+
with zipfile.ZipFile(io.BytesIO(raw)) as npz:
|
|
48
|
+
if sum(i.file_size for i in npz.infolist())>limit:
|
|
49
|
+
raise ValueError('nested trajectory decompression budget')
|
|
50
|
+
if z.read('request.json')!=canonical_bytes(request):raise ValueError('returned request changed')
|
|
51
|
+
destination.mkdir(parents=True)
|
|
52
|
+
for member in members:
|
|
53
|
+
with (destination/member.filename).open('xb') as out:out.write(z.read(member))
|
|
54
|
+
verifier_sha256 = sha256(Path(__file__).read_bytes())
|
|
55
|
+
dependencies = {module.__name__: sha256(Path(module.__file__).read_bytes())
|
|
56
|
+
for module in (manual_thermal_module, thermal_study_module, thermal_trace_module)}
|
|
57
|
+
state={'schema_version': IMPORT_VERSION, 'importer_sha256': verifier_sha256,
|
|
58
|
+
'verifier_dependency_sha256': dependencies,
|
|
59
|
+
'execution_source_commit': request['task']['code_revision'],
|
|
60
|
+
'launch_mode':'OWNER_MANUAL_LAUNCH','artifact_integrity':'VERIFIED',
|
|
61
|
+
'provider_identity_independently_verified':False,'provider_attestation':'UNAVAILABLE',
|
|
62
|
+
'remote_execution':'OWNER_REPORTED_NOT_INDEPENDENTLY_OBSERVED',
|
|
63
|
+
'archive_sha256':archive_sha,'qualification':'ABSTAIN','conductivity_S_cm':None}
|
|
64
|
+
manifest_path=destination/'manifest.json'
|
|
65
|
+
if not d['scientific_manifest_present']:
|
|
66
|
+
if manifest_path.exists() or 'failure.json' not in d['files']:
|
|
67
|
+
raise ValueError('false no-science receipt')
|
|
68
|
+
state.update(scientific_result='NO_SCIENTIFIC_OUTPUT',evidence_records=[])
|
|
69
|
+
else:
|
|
70
|
+
m=json.loads(manifest_path.read_bytes())
|
|
71
|
+
origin=m.get('execution_origin',{})
|
|
72
|
+
if (origin.get('mode')!='OWNER_MANUAL_LAUNCH' or origin.get('provider_attestation')!='UNAVAILABLE'
|
|
73
|
+
or origin.get('launch_id')!=request['launch_id'] or m.get('job_id') is not None
|
|
74
|
+
or m.get('qualification')!='ABSTAIN' or m.get('conductivity_S_cm') is not None):
|
|
75
|
+
raise ValueError('manual origin cannot masquerade as authenticated dispatch or qualification')
|
|
76
|
+
receipt=json.loads((destination/'owner-launch.json').read_bytes())
|
|
77
|
+
if (receipt['request_sha256']!=sha256(canonical_bytes(request)) or receipt['launch_id']!=request['launch_id']
|
|
78
|
+
or receipt.get('task_id')!=request['task_id']
|
|
79
|
+
or receipt.get('execution_mode')!='OWNER_MANUAL_LAUNCH'
|
|
80
|
+
or receipt.get('free_cpu_owner_declared') is not True
|
|
81
|
+
or receipt.get('provider_attestation')!='UNAVAILABLE'
|
|
82
|
+
or receipt.get('global_atomic_consumption')!='NOT_ESTABLISHED'
|
|
83
|
+
or receipt.get('provider_identity_independently_verified') is not False
|
|
84
|
+
or receipt.get('provider_job_id') is not None):
|
|
85
|
+
raise ValueError('invalid manual launch receipt')
|
|
86
|
+
if not m['runs']:
|
|
87
|
+
if m['status']!='PARTIAL' or not m.get('error_type'):
|
|
88
|
+
raise ValueError('empty successful scientific manifest')
|
|
89
|
+
state.update(scientific_result='NO_COMPLETE_THERMAL_RUNS',evidence_records=[])
|
|
90
|
+
else:
|
|
91
|
+
checked=verify_thermal_result_artifacts(destination,request,
|
|
92
|
+
expected_manifest_sha256=d['files']['manifest.json']['sha256'],expected_job_id=None,
|
|
93
|
+
transport_metadata=('download-manifest.json',))
|
|
94
|
+
if (checked['operational_status'] != m['status'] or
|
|
95
|
+
(m['status'] == 'COMPLETE' and any(run.get('operational_status') != 'COMPLETE'
|
|
96
|
+
for run in checked['runs']))):
|
|
97
|
+
raise ValueError('complete workload contains incomplete run')
|
|
98
|
+
state.update(scientific_result='ARTIFACT_MATHEMATICS_VERIFIED_ORIGIN_UNATTESTED',
|
|
99
|
+
numerical_verification=checked,evidence_records=_evidence_records(m,checked,request))
|
|
100
|
+
with (destination/'import-report-v2.json').open('xb') as out:out.write(canonical_bytes(state))
|
|
101
|
+
with (destination/'evidence-v2.jsonl').open('xb') as out:
|
|
102
|
+
for row in state['evidence_records']:out.write(canonical_bytes(row))
|
|
103
|
+
return state
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _evidence_records(manifest,checked,request):
|
|
107
|
+
from rhombus.evidence import (Applicability,DomainStatus,EvidenceRecord,OperationalStatus,
|
|
108
|
+
ScientificVerdict,Uncertainty)
|
|
109
|
+
from rhombus.evidence.identity import ArtifactBinding,ModelIdentity,ProtocolIdentity,SourceBinding
|
|
110
|
+
rows=[]
|
|
111
|
+
root=Path(__file__).resolve().parents[2]
|
|
112
|
+
parent=json.loads((root/request['protocol']['parent_report']).read_bytes())
|
|
113
|
+
sources={c['candidate_id']:c['source'] for c in parent['candidates']}
|
|
114
|
+
for candidate in sorted({r['binding']['candidate_id'] for r in manifest['runs']}):
|
|
115
|
+
indexed=[(i,r) for i,r in enumerate(manifest['runs']) if r['binding']['candidate_id']==candidate]
|
|
116
|
+
bindings=tuple(ArtifactBinding('artifact:sha256:'+v['sha256'],v['sha256']) for v in manifest['files'].values())
|
|
117
|
+
model=request['protocol']['model_sha256'];protocol=request['task']['protocol_hash']
|
|
118
|
+
operation = OperationalStatus.SUCCEEDED if checked['operational_status'] == 'COMPLETE' else OperationalStatus.ERROR
|
|
119
|
+
rows.append(EvidenceRecord.create(candidate_id=candidate,evidence_kind='OWNER_MANUAL_THERMAL_DIAGNOSTICS',
|
|
120
|
+
capability='assess_finite_temperature_stability',operational_status=operation,
|
|
121
|
+
scientific_verdict=ScientificVerdict.INDETERMINATE,
|
|
122
|
+
applicability=Applicability('digital_ionic_transport',DomainStatus.UNQUALIFIED),
|
|
123
|
+
uncertainty=Uncertainty(status='UNKNOWN',reason='Manual execution origin unverified; model, time and finite-size convergence unqualified'),
|
|
124
|
+
limitations=('PROVIDER_ATTESTATION_UNAVAILABLE','Artifact mathematics verified, execution origin not independently attested',
|
|
125
|
+
'NVT energy trend is not NVE conservation evidence','No P2.5/P3 transport qualification'),
|
|
126
|
+
artifact_bindings=bindings,artifact_ids=tuple(b.artifact_id for b in bindings),
|
|
127
|
+
source_bindings=(SourceBinding('RETAINED_COD_REFERENCE_CIF',sources[candidate]['source_id'],
|
|
128
|
+
sources[candidate]['pinned_locator'],indexed[0][1]['binding']['source_sha256']),),
|
|
129
|
+
model_identity=ModelIdentity('medium-mpa-0','MACE-MPA-0',checkpoint_sha256=model,dtype='float64',framework='torch-2.14.1+cpu'),
|
|
130
|
+
protocol_id='thermal-study-0201-v1',protocol_identity=ProtocolIdentity('thermal-study-0201-v1','assess_finite_temperature_stability','v1',protocol),
|
|
131
|
+
provenance={'task_id':request['task_id'],'launch_id':request['launch_id'],'source_commit':request['task']['code_revision'],
|
|
132
|
+
'execution_mode':'OWNER_MANUAL_LAUNCH','provider_identity_independently_verified':False,
|
|
133
|
+
'importer_version': IMPORT_VERSION, 'importer_sha256': sha256(Path(__file__).read_bytes())},
|
|
134
|
+
payload={'provider_attestation':'UNAVAILABLE','operational_scope':'OFFLINE_IMPORT_DIAGNOSTICS',
|
|
135
|
+
'remote_workload_status':manifest['status'],'scientific_GO':False,'qualification':'ABSTAIN',
|
|
136
|
+
'conductivity_S_cm':None,'runs':[{'label':r['label'],'P2_verdict':r['P2']['p2_verdict'],
|
|
137
|
+
'offline_diagnostics':checked['runs'][i]} for i,r in indexed]}).to_dict())
|
|
138
|
+
return rows
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""One owner-operated notebook launch, separate from trusted-host dispatch."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from rudeus.execution.contracts import TaskSpec
|
|
9
|
+
from rudeus.science.contracts import digest
|
|
10
|
+
from rhombus.atomistics.thermal_study import (PROTOCOL_PATH, build_study_task, load_protocol,
|
|
11
|
+
prepare_thermal_study, source_inventory)
|
|
12
|
+
from rhombus.atomistics.thermal_trace import canonical_bytes, sha256
|
|
13
|
+
|
|
14
|
+
PRIOR_REQUEST = 'data/development/digital0201/prepared_request_v1.json'
|
|
15
|
+
MANUAL_VERSION = 'rhombus-owner-manual-thermal-v1'
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def build_manual_request(root, revision):
|
|
19
|
+
request = prepare_thermal_study(root, revision)
|
|
20
|
+
request.update(manual_version=MANUAL_VERSION, execution_mode='OWNER_MANUAL_LAUNCH',
|
|
21
|
+
prior_request_sha256=sha256((Path(root)/PRIOR_REQUEST).read_bytes()),
|
|
22
|
+
launch_id=digest({'task_id':request['task_id'], 'path':MANUAL_VERSION}),
|
|
23
|
+
owner_launch_required=True, provider_attestation='UNAVAILABLE',
|
|
24
|
+
duplicate_scope='Exclusive persistent working-directory marker only; no cross-session provider ledger')
|
|
25
|
+
return request
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def validate_manual_request(request, root):
|
|
29
|
+
task = TaskSpec.from_dict(request['task']); task.validate()
|
|
30
|
+
inventory = source_inventory(root, task.code_revision)
|
|
31
|
+
protocol = load_protocol(root)
|
|
32
|
+
if (request.get('manual_version') != MANUAL_VERSION or request.get('execution_mode') != 'OWNER_MANUAL_LAUNCH'
|
|
33
|
+
or request.get('owner_launch_required') is not True
|
|
34
|
+
or request.get('provider_attestation') != 'UNAVAILABLE'
|
|
35
|
+
or request.get('provider_job_id') is not None or request.get('submission_gate') != 'CLOSED'
|
|
36
|
+
or request.get('state') != 'PREPARED_NOT_SUBMITTED'
|
|
37
|
+
or request['task_id'] != task.task_id or request['protocol'] != protocol
|
|
38
|
+
or request['source_inventory'] != inventory
|
|
39
|
+
or task.to_dict() != build_study_task(protocol, task.code_revision, inventory).to_dict()
|
|
40
|
+
or request['prior_request_sha256'] != sha256((Path(root)/PRIOR_REQUEST).read_bytes())
|
|
41
|
+
or request['launch_id'] != digest({'task_id':task.task_id, 'path':MANUAL_VERSION})
|
|
42
|
+
or inventory[PROTOCOL_PATH] != sha256((Path(root)/PROTOCOL_PATH).read_bytes())):
|
|
43
|
+
raise ValueError('manual request/source/prior/protocol identity mismatch')
|
|
44
|
+
required = {'scripts/kaggle/owner_thermal_run.py', 'scripts/kaggle/build_owner_thermal_notebook.py'}
|
|
45
|
+
if not required <= inventory.keys():
|
|
46
|
+
raise ValueError('manual entry points must be committed')
|
|
47
|
+
return task
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def consume_owner_launch(marker_dir, request, *, confirmation, free_cpu_confirmed):
|
|
51
|
+
"""A local one-shot marker, NOT authenticated global atomic consumption.
|
|
52
|
+
|
|
53
|
+
The owner must not launch the same request in a fresh session/notebook.
|
|
54
|
+
Reissuing a consumed/failed request requires a separately reviewed request.
|
|
55
|
+
"""
|
|
56
|
+
if confirmation != request['launch_id'] or free_cpu_confirmed is not True:
|
|
57
|
+
raise PermissionError('explicit owner launch and free CPU confirmation required')
|
|
58
|
+
target = Path(marker_dir) / ('rhombus-once-' + request['launch_id'] + '.json')
|
|
59
|
+
receipt = {'schema_version':MANUAL_VERSION, 'execution_mode':'OWNER_MANUAL_LAUNCH',
|
|
60
|
+
'task_id':request['task_id'], 'launch_id':request['launch_id'],
|
|
61
|
+
'request_sha256':sha256(canonical_bytes(request)), 'free_cpu_owner_declared':True,
|
|
62
|
+
'provider_job_id':None, 'provider_identity_independently_verified':False,
|
|
63
|
+
'provider_attestation':'UNAVAILABLE', 'global_atomic_consumption':'NOT_ESTABLISHED'}
|
|
64
|
+
fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
65
|
+
with os.fdopen(fd, 'wb') as out:
|
|
66
|
+
out.write(canonical_bytes(receipt)); out.flush(); os.fsync(out.fileno())
|
|
67
|
+
return receipt
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def package_manual_result(output, request, log_path, archive_path):
|
|
71
|
+
"""Finalize a downloadable bounded package after the child has stopped."""
|
|
72
|
+
import zipfile
|
|
73
|
+
output=Path(output);output.mkdir(parents=True,exist_ok=True)
|
|
74
|
+
archive_path=Path(archive_path)
|
|
75
|
+
if archive_path.exists():raise FileExistsError('preserve earlier download package')
|
|
76
|
+
marker=output.parent/('rhombus-once-'+request['launch_id']+'.json')
|
|
77
|
+
if marker.exists() and not (output/'owner-launch.json').exists():
|
|
78
|
+
with (output/'owner-launch.json').open('xb') as out:out.write(marker.read_bytes())
|
|
79
|
+
for name,raw in [('request.json',canonical_bytes(request))]:
|
|
80
|
+
with (output/name).open('xb') as out:out.write(raw)
|
|
81
|
+
log_path=Path(log_path)
|
|
82
|
+
if log_path.exists():
|
|
83
|
+
with log_path.open('rb') as source:
|
|
84
|
+
source.seek(max(0,log_path.stat().st_size-1048576))
|
|
85
|
+
with (output/'execution.log').open('xb') as out:out.write(source.read(1048576))
|
|
86
|
+
manifest_path=output/'manifest.json'
|
|
87
|
+
if manifest_path.exists():
|
|
88
|
+
m=json.loads(manifest_path.read_bytes())
|
|
89
|
+
if m.get('execution_origin',{}).get('mode')!='OWNER_MANUAL_LAUNCH' or m.get('job_id') is not None:
|
|
90
|
+
raise ValueError('manual package cannot carry controlled-host receipt')
|
|
91
|
+
m['files']={p.name:{'sha256':sha256(p.read_bytes()),'size_bytes':p.stat().st_size}
|
|
92
|
+
for p in output.iterdir() if p.is_file() and p.name!='manifest.json'}
|
|
93
|
+
manifest_path.write_bytes(canonical_bytes(m))
|
|
94
|
+
else:
|
|
95
|
+
with (output/'failure.json').open('xb') as out:
|
|
96
|
+
out.write(canonical_bytes({'status':'NO_SCIENTIFIC_OUTPUT', 'task_id':request['task_id'],
|
|
97
|
+
'execution_mode':'OWNER_MANUAL_LAUNCH','provider_attestation':'UNAVAILABLE'}))
|
|
98
|
+
files={p.name:{'sha256':sha256(p.read_bytes()),'size_bytes':p.stat().st_size}
|
|
99
|
+
for p in output.iterdir() if p.is_file()}
|
|
100
|
+
if sum(r['size_bytes'] for r in files.values())>request['protocol']['resource_budget']['output_bytes']:
|
|
101
|
+
raise ValueError('download package exceeds frozen output budget; retain raw files')
|
|
102
|
+
download={'schema_version':'rhombus-owner-download-v1','request_sha256':sha256(canonical_bytes(request)),
|
|
103
|
+
'task_id':request['task_id'],'launch_id':request['launch_id'], 'files':files,
|
|
104
|
+
'scientific_manifest_present':manifest_path.exists(),'provider_attestation':'UNAVAILABLE',
|
|
105
|
+
'execution_log_tail_limit_bytes':1048576}
|
|
106
|
+
with (output/'download-manifest.json').open('xb') as out:out.write(canonical_bytes(download))
|
|
107
|
+
with zipfile.ZipFile(archive_path,'x',compression=zipfile.ZIP_DEFLATED) as archive:
|
|
108
|
+
for path in sorted(output.iterdir()):
|
|
109
|
+
if path.is_file():archive.write(path,path.name)
|
|
110
|
+
return {'archive':str(archive_path),'archive_sha256':sha256(archive_path.read_bytes()),
|
|
111
|
+
'manifest_sha256':sha256(manifest_path.read_bytes()) if manifest_path.exists() else None,
|
|
112
|
+
'provider_attestation':'UNAVAILABLE'}
|