Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download sinetti_data_reads/reader_runtime.py from Couscouskabyle/iscc-app: direct link, hf CLI and curl.
- Browser
- Download file 9.26 kB
-
https://huggingface.co/spaces/Couscouskabyle/iscc-app/resolve/main/sinetti_data_reads/reader_runtime.py
- Command line
-
hf download hf://spaces/Couscouskabyle/iscc-app/sinetti_data_reads/reader_runtime.py
-
curl -L -o reader_runtime.py https://huggingface.co/spaces/Couscouskabyle/iscc-app/resolve/main/sinetti_data_reads/reader_runtime.py
9.26 kB
| """Read-only process identity for a future coordinated foundation release. | |
| No manifest means unknown, not a repository-head fallback. The sealed build | |
| manifest excludes itself and deployment metadata from its source inventory, so | |
| neither its own digest nor an image digest is defined recursively. The complete | |
| retained image is identified independently by the release controller. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| import hashlib | |
| import importlib.metadata | |
| import json | |
| import os | |
| from pathlib import Path, PurePosixPath | |
| import platform | |
| import re | |
| import sys | |
| import threading | |
| from release_names import is_release_name | |
| MANIFEST = "reader_runtime_manifest.json" | |
| MARKER = "frontend/dist/assets/deploy_provenance.json" | |
| MAX_JSON = 4 * 1024 * 1024 | |
| _PROBE_LOCK = threading.Lock() | |
| _HEX64 = re.compile(r"[0-9a-f]{64}\Z") | |
| _HEX40 = re.compile(r"[0-9a-f]{40}\Z") | |
| _IMAGE = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*(?:/[a-z0-9]+(?:[._-][a-z0-9]+)*)*@sha256:[0-9a-f]{64}\Z") | |
| def _require(condition): | |
| if not condition: | |
| raise ValueError("reader_identity_unproven") | |
| def canonical(value): | |
| return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() | |
| def digest(value): | |
| return hashlib.sha256(canonical(value)).hexdigest() | |
| def _unique(pairs): | |
| result = {} | |
| for key, value in pairs: | |
| _require(key not in result) | |
| result[key] = value | |
| return result | |
| def _json(raw): | |
| _require(len(raw) <= MAX_JSON) | |
| return json.loads(raw, object_pairs_hook=_unique) | |
| def _regular(path): | |
| for parent in (path, *path.parents): | |
| _require(not parent.is_symlink() and not (hasattr(parent, "is_junction") and parent.is_junction())) | |
| _require(path.is_file()) | |
| return path | |
| def _sha(path): | |
| result, size = hashlib.sha256(), 0 | |
| with _regular(path).open("rb") as stream: | |
| for chunk in iter(lambda: stream.read(1024 * 1024), b""): | |
| size += len(chunk) | |
| _require(size <= 512 * 1024 * 1024) | |
| result.update(chunk) | |
| return result.hexdigest(), size | |
| def _read_metadata(path): | |
| with _regular(path).open("rb") as stream: | |
| raw = stream.read(MAX_JSON + 1) | |
| _require(len(raw) <= MAX_JSON) | |
| return raw | |
| def measure_files(root, expected): | |
| _require(isinstance(expected, dict) and 0 < len(expected) <= 20000) | |
| measured, folded = {}, set() | |
| for name, identity in sorted(expected.items()): | |
| _require(isinstance(name, str) and 0 < len(name) <= 240 and name not in {MANIFEST, MARKER}) | |
| path = PurePosixPath(name) | |
| _require(not path.is_absolute() and path.as_posix() == name and "\\" not in name | |
| and all(part not in {".", "..", ".git"} and ":" not in part | |
| and not part.casefold().startswith(".env") for part in path.parts) | |
| and name.casefold() not in folded) | |
| folded.add(name.casefold()) | |
| _require(isinstance(identity, dict) and set(identity) == {"sha256", "size_bytes"} | |
| and isinstance(identity["sha256"], str) and _HEX64.fullmatch(identity["sha256"]) | |
| and type(identity["size_bytes"]) is int and identity["size_bytes"] >= 0) | |
| target = root.joinpath(*path.parts) | |
| _require(target.resolve().is_relative_to(root)) | |
| checksum, size = _sha(target) | |
| measured[name] = {"sha256": checksum, "size_bytes": size} | |
| _require(measured[name] == identity) | |
| return digest(measured) | |
| def measure_runtime(image, dependencies, configuration): | |
| _require(isinstance(image, str) and len(image) <= 320 and _IMAGE.fullmatch(image)) | |
| _require(isinstance(configuration, dict) and not set(configuration) - {"LANG", "LC_ALL", "TZ", "PYTHONHASHSEED"}) | |
| _require(all(isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_./:+-]{0,80}", value) | |
| and os.environ.get(key) == value for key, value in configuration.items())) | |
| _require(isinstance(dependencies, dict) and len(dependencies) <= 2000) | |
| measured = {} | |
| providers = importlib.metadata.packages_distributions() if dependencies else {} | |
| for name in sorted(dependencies): | |
| _require(isinstance(name, str) and re.fullmatch(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*", name, re.ASCII)) | |
| choices = providers.get(name.split(".")[0], [name.replace("_", "-")]) | |
| _require(len(choices) == 1) | |
| distribution = importlib.metadata.distribution(choices[0]) | |
| files = [] | |
| for item in sorted(distribution.files or [], key=str): | |
| if "__pycache__" in item.parts or str(item).endswith((".pyc", ".pyo")): | |
| continue | |
| # Installed environments can resolve site-packages through a venv | |
| # link; identify the resolved bytes rather than rejecting that layout. | |
| path = Path(distribution.locate_file(item)).resolve() | |
| checksum, size = _sha(path) | |
| files.append([str(item).replace("\\", "/"), size, checksum]) | |
| _require(bool(files)) | |
| measured[name] = {"version": distribution.version, "sha256": digest(files)} | |
| architecture = {"x86_64": "amd64", "AMD64": "amd64", "aarch64": "arm64"}.get(platform.machine(), platform.machine().lower()) | |
| return {"format": "sinetti-jobs-runtime/1", "image": image, | |
| "interpreter": {"implementation": sys.implementation.name, "version": ".".join(map(str, sys.version_info[:3]))}, | |
| "platform": platform.system().lower() + "/" + architecture, "dependencies": measured, | |
| "configuration_sha256": digest(configuration)} | |
| class ReaderSnapshot: | |
| descriptor: bytes | |
| marker: bytes | |
| identity: bytes | |
| def _measure(root, descriptor, marker): | |
| _require(isinstance(descriptor, dict) and set(descriptor) == { | |
| "format", "source_sha", "release_name", "policy_sha256", "protected_inventory_sha256", "files", "runtime", "configuration"}) | |
| _require(descriptor["format"] == "sinetti-reader-runtime-manifest/1") | |
| _require(isinstance(descriptor["source_sha"], str) and _HEX40.fullmatch(descriptor["source_sha"])) | |
| _require(is_release_name(descriptor["release_name"])) | |
| _require(all(isinstance(descriptor[key], str) and _HEX64.fullmatch(descriptor[key]) | |
| for key in ("policy_sha256", "protected_inventory_sha256"))) | |
| _require(isinstance(marker, dict) and marker.get("source_head") == descriptor["source_sha"] | |
| and marker.get("release_name") == descriptor["release_name"] | |
| and isinstance(marker.get("deployment_id"), str) and re.fullmatch(r"[0-9a-f]{32}", marker["deployment_id"])) | |
| runtime = descriptor["runtime"] | |
| _require(isinstance(runtime, dict) and set(runtime) == { | |
| "format", "image", "interpreter", "platform", "dependencies", "configuration_sha256"}) | |
| measured_runtime = measure_runtime(runtime["image"], runtime["dependencies"], descriptor["configuration"]) | |
| _require(measured_runtime == runtime) | |
| return {"source_sha": descriptor["source_sha"], "release_name": descriptor["release_name"], | |
| "deployment_id": marker["deployment_id"], "artifact_sha256": measure_files(root, descriptor["files"]), | |
| "runtime_sha256": digest(measured_runtime), "policy_sha256": descriptor["policy_sha256"], | |
| "protected_inventory_sha256": descriptor["protected_inventory_sha256"]} | |
| def capture_reader(root): | |
| """Capture this process's boot artifact. Missing/unverifiable stays unknown.""" | |
| try: | |
| root = Path(root).resolve() | |
| descriptor = _read_metadata(root / MANIFEST) | |
| marker = _read_metadata(root / MARKER) | |
| identity = _measure(root, _json(descriptor), _json(marker)) | |
| return ReaderSnapshot(descriptor, marker, canonical(identity)) | |
| except (OSError, ValueError, TypeError, KeyError, RuntimeError, RecursionError, ImportError): | |
| return None | |
| def observe_reader(root, snapshot, *, nonce=None): | |
| """Only a new bounded challenge requests current files/runtime remeasurement.""" | |
| challenge = nonce if isinstance(nonce, str) and re.fullmatch(r"[0-9a-f]{32}", nonce) else "" | |
| unknown = {"format": "sinetti-reader-process/1", "known": False, "fresh": False, "nonce": challenge} | |
| if not isinstance(snapshot, ReaderSnapshot): | |
| return unknown | |
| try: | |
| if challenge: | |
| if not _PROBE_LOCK.acquire(blocking=False): | |
| return unknown | |
| try: | |
| root = Path(root).resolve() | |
| _require(_read_metadata(root / MANIFEST) == snapshot.descriptor | |
| and _read_metadata(root / MARKER) == snapshot.marker) | |
| _require(canonical(_measure(root, _json(snapshot.descriptor), _json(snapshot.marker))) == snapshot.identity) | |
| finally: | |
| _PROBE_LOCK.release() | |
| return {"format": "sinetti-reader-process/1", "known": True, "fresh": bool(challenge), | |
| "nonce": challenge, **_json(snapshot.identity)} | |
| except (OSError, ValueError, TypeError, KeyError, RuntimeError, RecursionError, ImportError): | |
| return unknown | |