Download simulation/service.py from tmepass000/matter-os: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/tmepass000/matter-os/resolve/main/simulation/service.py
- Command line
-
hf download hf://tmepass000/matter-os/simulation/service.py
-
curl -L -o service.py https://huggingface.co/tmepass000/matter-os/resolve/main/simulation/service.py
11 kB
| """Simulation service: list_compatible_solvers, estimate_cost, submit_run, get_status, fetch_artifacts (section 14). | |
| Every execution - isolated worker or in-process screening - produces an immutable, checksummed, | |
| signed RunRecord with solver/version, input hash, parameters, environment, budget, timestamps, | |
| exit status, convergence, observables, uncertainty, artifacts, logs, provenance and replication links. | |
| """ | |
| from __future__ import annotations | |
| import time | |
| from pathlib import Path | |
| from typing import Any, Optional | |
| from core.errors import ErrorCode, MatterOSError | |
| from core.provenance import environment_manifest, jsonable, provenance_record, redact, sha256_obj, utcnow | |
| from core.representation import MatterStructure | |
| from core.schemas import RunRecord | |
| from evidence.uncertainty import build_record | |
| from orchestration.failures import classify, record_failure | |
| from orchestration.jobs import JobRunner | |
| from simulation.contract import CancelledByUser, RunContext, SolverOutput | |
| from simulation.router import SimulationRouter | |
| from storage.artifacts import ArtifactStore | |
| from storage.projects import Repository | |
| _ENV = None | |
| def env_manifest() -> dict: | |
| global _ENV | |
| if _ENV is None: | |
| _ENV = environment_manifest() | |
| return _ENV | |
| class SimulationService: | |
| def __init__(self, repo: Repository, artifacts: ArtifactStore, jobs: JobRunner, router: SimulationRouter, gates: dict, | |
| knowledge=None): | |
| self.repo = repo | |
| self.db = repo.db | |
| self.artifacts = artifacts | |
| self.jobs = jobs | |
| self.router = router | |
| self.registry = router.registry | |
| self.gates = gates | |
| self.knowledge = knowledge | |
| # ------------- API ------------- | |
| def list_compatible_solvers(self, candidate_id: str, observable: str) -> list[dict]: | |
| ms = MatterStructure.from_candidate(self.repo.get_candidate(candidate_id)) | |
| return self.router.list_compatible(ms, observable) | |
| def estimate_cost(self, candidate_id: str, solver_id: str, observable: str, params: dict | None = None) -> dict: | |
| ms = MatterStructure.from_candidate(self.repo.get_candidate(candidate_id)) | |
| ad = self.registry.get(solver_id) | |
| ok, reasons = ad.compatible(ms, observable) | |
| return {"solver_id": solver_id, "compatible": ok, "reasons": reasons, **ad.estimate_cost(ms, observable, params)} | |
| def get_status(self, job_id: str) -> dict: | |
| return self.jobs.get(job_id) | |
| def fetch_artifacts(self, run_id: str) -> list[dict]: | |
| rec = self.repo.get_run(run_id) | |
| return rec.artifact_refs | |
| def submit_run(self, candidate_id: str, solver_id: str, observable: str, params: dict | None = None, *, | |
| mission_id: Optional[str] = None, priority: str = "normal", budget: dict | None = None, seed: int = 0, | |
| isolated: bool = True, replication_of: Optional[str] = None, router_rationale: Optional[str] = None, | |
| structure: Optional[MatterStructure] = None) -> RunRecord: | |
| cand = self.repo.get_candidate(candidate_id) | |
| if mission_id: | |
| self._enforce_mission_budget(mission_id, priority) | |
| ms = structure or MatterStructure.from_candidate(cand) | |
| params = dict(params or {}) | |
| adapter = self.registry.get(solver_id) | |
| entry = self.registry.entries[solver_id] | |
| budget = self.jobs.resources.enforce_quota(budget or {}) | |
| input_payload = {"candidate_hash": cand.content_hash, "positions": ms.positions.round(10).tolist(), "cell": None if ms.cell is None else ms.cell.round(10).tolist(), | |
| "symbols": ms.symbols, "charge": ms.charge, "mult": ms.spin_multiplicity, "observable": observable, | |
| "params": params, "parameter_set": entry.get("parameter_set"), "solver": solver_id} | |
| input_hash = sha256_obj(input_payload) | |
| started = utcnow(); retries = [] | |
| job_id = None | |
| if isolated: | |
| job_id = self.jobs.enqueue(candidate_id=candidate_id, method_id=solver_id, observable=observable, params=params, | |
| mission_id=mission_id, priority=priority, budget=budget, seed=seed) | |
| res = self.jobs.execute(job_id, ms) | |
| out: Optional[SolverOutput] = res.get("output") | |
| timing = res.get("timing", {}) | |
| if out is None: | |
| out = SolverOutput(status=res["status"] if res["status"] in ("TIMEOUT", "CANCELLED") else "FAILED", | |
| error_code=res.get("error_code"), logs=str(res.get("error", "")), | |
| convergence={"status": "unknown", "reason": res.get("error")}) | |
| else: | |
| t0 = time.time() | |
| wd = Path(self.jobs.jobs_dir) / "inline"; wd.mkdir(parents=True, exist_ok=True) | |
| ctx = RunContext(workdir=wd, seed=seed, wall_time_s=budget["wall_time_s"]) | |
| try: | |
| out = adapter.run(ms, observable, params, ctx) | |
| except CancelledByUser: | |
| out = SolverOutput(status="CANCELLED", error_code=ErrorCode.CANCELLED.value) | |
| except TimeoutError as e: | |
| out = SolverOutput(status="TIMEOUT", error_code=ErrorCode.TIMEOUT.value, logs=str(e)) | |
| except Exception as e: # noqa: BLE001 - recorded, never swallowed silently | |
| out = SolverOutput(status="FAILED", error_code=ErrorCode.SOLVER_FAILURE.value, logs=repr(e)) | |
| timing = {"wall_s": round(time.time() - t0, 4)} | |
| return self._record(cand, ms, solver_id, adapter, entry, observable, params, budget, input_hash, started, timing, | |
| out, mission_id, replication_of, router_rationale, retries, job_id, seed) | |
| def _enforce_mission_budget(self, mission_id: str, priority: str) -> None: | |
| """Hard per-mission run budget with reserved validation capacity (decisions 22, 50).""" | |
| try: | |
| m = self.repo.get_mission(mission_id) | |
| except MatterOSError: | |
| return | |
| n = self.db.one("SELECT COUNT(*) n FROM run_records WHERE mission_id=?", (mission_id,))["n"] | |
| cap = int(m.budget.max_runs) | |
| general_cap = int(cap * (1.0 - float(m.budget.reserved_validation_fraction))) | |
| if n >= cap or (priority != "validation" and n >= general_cap): | |
| self.db.audit("resource_manager", "mission_budget_refused", mission_id, {"runs": n, "cap": cap, "general_cap": general_cap, "priority": priority}) | |
| raise MatterOSError(ErrorCode.RESOURCE_LIMIT, f"mission run budget exhausted ({n} runs; cap {cap}, non-validation cap {general_cap})") | |
| # ------------- record ------------- | |
| def _record(self, cand, ms, solver_id, adapter, entry, observable, params, budget, input_hash, started, timing, out: SolverOutput, | |
| mission_id, replication_of, router_rationale, retries, job_id, seed) -> RunRecord: | |
| from core.schemas import new_id | |
| run_id = new_id("run") | |
| cap = adapter.capabilities() | |
| arts = [] | |
| if out.input_deck: | |
| arts.append(self.artifacts.put_bytes(out.input_deck.encode(), "input_deck", "input.txt", run_id)) | |
| if out.logs: | |
| arts.append(self.artifacts.put_bytes(redact(out.logs).encode(), "raw_log", "solver.log", run_id)) | |
| for name, data, kind in out.artifacts: | |
| arts.append(self.artifacts.put_bytes(data, kind, name, run_id)) | |
| out.observables = jsonable(out.observables); out.sanity = jsonable(out.sanity) | |
| out.electronic = jsonable(out.electronic); out.uncertainty = jsonable(out.uncertainty) | |
| conv = jsonable(out.convergence or {"status": "unknown"}) | |
| conv_status = conv.get("status", "unknown") | |
| if conv_status not in ("converged", "not_converged", "not_applicable", "unknown"): | |
| conv_status = "unknown" | |
| unc = [] | |
| rt = self.gates.get("uncertainty", {}).get("retest_relative_threshold") | |
| main_key = next(iter(out.observables), None) | |
| for key, q in list(out.observables.items())[:3]: | |
| if not isinstance(q, dict) or not isinstance(q.get("value"), (int, float)) or isinstance(q.get("value"), bool): | |
| continue | |
| comps = [c for c in out.uncertainty if c.get("unit") in (None, q.get("unit"))] if key == main_key else [] | |
| unc.append(build_record(key, comps, cap.limitations, q["value"], rt)) | |
| exit_status = out.status if out.status in ("SUCCESS", "FAILED", "NOT_SUPPORTED", "NEEDS_METHOD", "CANCELLED", "TIMEOUT") else "FAILED" | |
| rec = RunRecord( | |
| run_id=run_id, mission_id=mission_id, candidate_id=cand.candidate_id, method_id=f"{solver_id}:{observable}", | |
| solver_version=f"{cap.engine} {cap.engine_version}", input_hash=input_hash, | |
| parameter_set={"registry": entry.get("parameter_set"), "run_params": params, "seed": seed}, | |
| environment=env_manifest(), resource_budget=budget, | |
| timestamps={"submitted_at": started, "finished_at": utcnow(), **{k: str(v) for k, v in timing.items()}}, | |
| exit_status=exit_status, error_code=out.error_code, convergence_status=conv_status, | |
| convergence_details={**conv, "sanity": out.sanity, "resumed_from_checkpoint": out.resumed_from_checkpoint}, | |
| observables={**out.observables, **({"electronic_descriptors": {"value": out.electronic, "unit": "mixed"}} if out.electronic else {})}, | |
| uncertainty=unc, artifact_refs=arts, logs=redact(out.logs[-2000:]), | |
| provenance={**provenance_record(f"matter_os:run:{solver_id}", license="internal-computed", version=cap.engine_version, | |
| transformations=[f"candidate {cand.candidate_id} -> {solver_id}:{observable}"], | |
| parsing_method="in-memory adapter output"), | |
| "candidate_content_hash": cand.content_hash, "limitations": cap.limitations, "job_id": job_id}, | |
| replication_links=[replication_of] if replication_of else [], | |
| retries=retries, router_rationale=router_rationale) | |
| self.repo.insert_run(rec) | |
| self.db.metric("run_wall_s", float(timing.get("wall_s", 0) or 0), solver=solver_id, status=exit_status) | |
| self.db.audit("simulation_service", "run_recorded", run_id, {"candidate": cand.candidate_id, "method": rec.method_id, | |
| "status": exit_status, "convergence": conv_status}) | |
| if exit_status != "SUCCESS" and exit_status != "NOT_SUPPORTED": | |
| diag = classify(exit_status=exit_status, error_code=out.error_code, convergence=conv, sanity=out.sanity, | |
| observables=out.observables, logs=out.logs) | |
| record_failure(self.db, diag, mission_id=mission_id, candidate_id=cand.candidate_id, run_id=run_id) | |
| if self.knowledge is not None: | |
| self.knowledge.record_run(rec) | |
| return rec | |