Bound semantic worker storage and add verified evidence closeout
This commit is contained in:
@@ -0,0 +1,334 @@
|
||||
"""Lossless, restartable closeout for an explicitly terminal owned job.
|
||||
|
||||
No age-based discovery, shared source cleanup or archive eviction. The caller
|
||||
must release all producers and confirm delivery before calling closeout().
|
||||
Archive roots are separately retained persistent data, outside job roots.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import zipfile
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path, PurePosixPath
|
||||
from uuid import uuid4
|
||||
|
||||
GIB = 1024**3
|
||||
|
||||
|
||||
def digest(path):
|
||||
with Path(path).open("rb") as f:
|
||||
return hashlib.file_digest(f, "sha256").hexdigest()
|
||||
|
||||
|
||||
def regular(path):
|
||||
s = path.lstat()
|
||||
if not stat.S_ISREG(s.st_mode) or getattr(s, "st_file_attributes", 0) & 0x400:
|
||||
raise ValueError("Unsafe evidence file")
|
||||
return s
|
||||
|
||||
|
||||
def confined(root, relative):
|
||||
p = PurePosixPath(relative)
|
||||
if p.is_absolute() or not p.parts or ".." in p.parts or "\\" in relative or ":" in relative:
|
||||
raise ValueError("Unsafe evidence path")
|
||||
target = root.joinpath(*p.parts)
|
||||
if not target.resolve().is_relative_to(root.resolve()):
|
||||
raise ValueError("Evidence path escaped root")
|
||||
for parent in [target, *target.parents]:
|
||||
if parent == root.parent:
|
||||
break
|
||||
if parent.exists() and (
|
||||
parent.is_symlink() or getattr(parent.lstat(), "st_file_attributes", 0) & 0x400
|
||||
):
|
||||
raise ValueError("Evidence links are not owned files")
|
||||
return target
|
||||
|
||||
|
||||
def canonical(path):
|
||||
path = Path(path).expanduser().absolute()
|
||||
for part in [path, *path.parents]:
|
||||
if part.is_symlink() or (
|
||||
part.exists() and getattr(part.lstat(), "st_file_attributes", 0) & 0x400
|
||||
):
|
||||
raise ValueError("Linked evidence owner path")
|
||||
return path
|
||||
|
||||
|
||||
def atomic_json(path, value):
|
||||
canonical(path)
|
||||
if path.exists():
|
||||
regular(path)
|
||||
tmp = path.with_name(path.name + "." + uuid4().hex + ".tmp")
|
||||
with tmp.open("x", encoding="utf-8") as f:
|
||||
json.dump(value, f, ensure_ascii=False, sort_keys=True)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def lock(root):
|
||||
root = canonical(root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
path = root / "owner.lock"
|
||||
canonical(path)
|
||||
if path.exists():
|
||||
regular(path)
|
||||
with path.open("a+b") as f:
|
||||
if f.tell() == 0:
|
||||
f.write(b"0")
|
||||
f.flush()
|
||||
f.seek(0)
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
|
||||
else:
|
||||
import fcntl
|
||||
|
||||
fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
f.seek(0)
|
||||
if os.name == "nt":
|
||||
msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
else:
|
||||
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def usage(root):
|
||||
total = 0
|
||||
for base, dirs, files in os.walk(root, followlinks=False):
|
||||
for name in dirs:
|
||||
p = Path(base) / name
|
||||
if p.is_symlink() or getattr(p.lstat(), "st_file_attributes", 0) & 0x400:
|
||||
raise ValueError("Unexpected linked evidence directory")
|
||||
for name in files:
|
||||
total += regular(Path(base) / name).st_size
|
||||
return total
|
||||
|
||||
|
||||
def closeout(root, store, owner, *, keep=(), limit=128 * GIB, reserve=40 * GIB):
|
||||
"""Archive all files, verify every member, unlink exact non-kept copies.
|
||||
|
||||
Owner is a stable identity (job key/revision), never a caller-chosen path.
|
||||
Interrupted unlink resumes only from durable intent and a verified archive.
|
||||
"""
|
||||
root, store = canonical(root), canonical(store)
|
||||
if not owner or any(
|
||||
c not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_" for c in owner
|
||||
):
|
||||
raise ValueError("Invalid closeout owner")
|
||||
if root == store or store.is_relative_to(root) or root.is_relative_to(store):
|
||||
raise ValueError("Archive and working data must have separate ownership")
|
||||
control = canonical(store / owner)
|
||||
control.mkdir(parents=True, exist_ok=True)
|
||||
with lock(store):
|
||||
state_path = control / "closeout.json"
|
||||
archive = control / "evidence.zip"
|
||||
journal = control / "deletions.jsonl"
|
||||
for p in (state_path, archive, journal, control / "evidence.partial.zip"):
|
||||
canonical(p)
|
||||
if p.exists():
|
||||
regular(p)
|
||||
if (root / "RETAIN.json").exists():
|
||||
raise ValueError("Job is explicitly pinned")
|
||||
if state_path.exists():
|
||||
state = json.loads(state_path.read_text())
|
||||
if state["root"] != str(root) or state["owner"] != owner:
|
||||
raise ValueError("Closeout owner changed")
|
||||
if state["phase"] == "complete":
|
||||
if digest(archive) != state["archive_sha256"]:
|
||||
raise ValueError("Retained archive changed")
|
||||
atomic_json(
|
||||
root / "ARCHIVED.json",
|
||||
{k: state[k] for k in ("owner", "archive", "archive_sha256", "retention")},
|
||||
)
|
||||
return state
|
||||
else:
|
||||
files = []
|
||||
for base, dirs, names in os.walk(root, followlinks=False):
|
||||
for name in dirs:
|
||||
confined(root, (Path(base) / name).relative_to(root).as_posix())
|
||||
for name in names:
|
||||
p = Path(base) / name
|
||||
relative = p.relative_to(root).as_posix()
|
||||
confined(root, relative)
|
||||
s = regular(p)
|
||||
if relative in ("RETAIN.json", "CLOSEOUT-MANIFEST.json"):
|
||||
raise ValueError("Job is explicitly pinned")
|
||||
files.append(
|
||||
dict(
|
||||
path=relative,
|
||||
size=s.st_size,
|
||||
mtime_ns=s.st_mtime_ns,
|
||||
mode=stat.S_IMODE(s.st_mode),
|
||||
sha256=digest(p),
|
||||
keep=relative in keep,
|
||||
)
|
||||
)
|
||||
required = (
|
||||
sum(f["size"] + f["size"] // 100 for f in files) + len(files) * 1024 + 1024**2
|
||||
)
|
||||
if (
|
||||
usage(store) + required > limit
|
||||
or shutil.disk_usage(store).free < required + reserve
|
||||
):
|
||||
raise RuntimeError("Archive quota/reserve reached; job preserved")
|
||||
state = dict(
|
||||
schema="missioncore.evidence-closeout/v1",
|
||||
root=str(root),
|
||||
owner=owner,
|
||||
phase="planned",
|
||||
files=files,
|
||||
archive=str(archive),
|
||||
retention="explicit-pin-no-TTL",
|
||||
)
|
||||
atomic_json(state_path, state)
|
||||
if state["phase"] == "planned" and archive.exists():
|
||||
# Crash after publishing ZIP but before committing archived state.
|
||||
# Accept only this exact planned content, without reserving a second copy.
|
||||
with zipfile.ZipFile(archive) as z:
|
||||
if set(z.namelist()) != {r["path"] for r in state["files"]} | {
|
||||
"CLOSEOUT-MANIFEST.json"
|
||||
}:
|
||||
raise ValueError("Uncommitted archive inventory changed")
|
||||
if json.loads(z.read("CLOSEOUT-MANIFEST.json")) != state:
|
||||
raise ValueError("Uncommitted archive owner changed")
|
||||
for row in state["files"]:
|
||||
with z.open(row["path"]) as f:
|
||||
if (
|
||||
z.getinfo(row["path"]).file_size != row["size"]
|
||||
or hashlib.file_digest(f, "sha256").hexdigest() != row["sha256"]
|
||||
):
|
||||
raise ValueError("Uncommitted archive content changed")
|
||||
state.update(phase="archived", archive_sha256=digest(archive))
|
||||
atomic_json(state_path, state)
|
||||
if state["phase"] == "planned":
|
||||
temporary = control / "evidence.partial.zip"
|
||||
temporary.unlink(missing_ok=True) # Only this owner's unfinished archive.
|
||||
required = (
|
||||
sum(r["size"] + r["size"] // 100 for r in state["files"])
|
||||
+ len(state["files"]) * 1024
|
||||
+ 1024**2
|
||||
)
|
||||
if (
|
||||
usage(store) + required > limit
|
||||
or shutil.disk_usage(store).free < required + reserve
|
||||
):
|
||||
raise RuntimeError("Archive quota/reserve reached; job preserved")
|
||||
with zipfile.ZipFile(
|
||||
temporary, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=1
|
||||
) as z:
|
||||
for row in state["files"]:
|
||||
p = confined(root, row["path"])
|
||||
if regular(p).st_size != row["size"] or digest(p) != row["sha256"]:
|
||||
raise ValueError("Evidence changed before archival")
|
||||
z.write(p, row["path"])
|
||||
z.writestr("CLOSEOUT-MANIFEST.json", json.dumps(state, sort_keys=True))
|
||||
with temporary.open("rb+") as f:
|
||||
os.fsync(f.fileno())
|
||||
os.replace(temporary, archive)
|
||||
state.update(phase="archived", archive_sha256=digest(archive))
|
||||
atomic_json(state_path, state)
|
||||
if digest(archive) != state["archive_sha256"]:
|
||||
raise ValueError("Archive checksum changed")
|
||||
with zipfile.ZipFile(archive) as z:
|
||||
if set(z.namelist()) != {r["path"] for r in state["files"]} | {
|
||||
"CLOSEOUT-MANIFEST.json"
|
||||
}:
|
||||
raise ValueError("Archive inventory mismatch")
|
||||
for row in state["files"]:
|
||||
with z.open(row["path"]) as f:
|
||||
if (
|
||||
z.getinfo(row["path"]).file_size != row["size"]
|
||||
or hashlib.file_digest(f, "sha256").hexdigest() != row["sha256"]
|
||||
):
|
||||
raise ValueError("Archive member checksum mismatch")
|
||||
if (root / "RETAIN.json").exists():
|
||||
raise ValueError("Job was pinned during closeout")
|
||||
intents = set()
|
||||
if journal.exists():
|
||||
data = journal.read_bytes()
|
||||
# Only an uncommitted final fragment can be discarded. A corrupt
|
||||
# complete line still blocks recovery; durable intents are retained.
|
||||
prefix = data.rfind(b"\n") + 1
|
||||
for line in data[:prefix].splitlines():
|
||||
item = json.loads(line)
|
||||
if item["action"] == "intent":
|
||||
intents.add(item["path"])
|
||||
if prefix != len(data):
|
||||
with journal.open("r+b") as f:
|
||||
f.truncate(prefix)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
# Validate the complete deletion set before starting/resuming any unlink.
|
||||
for row in state["files"]:
|
||||
p = confined(root, row["path"])
|
||||
if not p.exists():
|
||||
if row["keep"] or row["path"] not in intents:
|
||||
raise ValueError("Unexplained missing evidence")
|
||||
elif regular(p).st_size != row["size"] or digest(p) != row["sha256"]:
|
||||
raise ValueError("Evidence changed after archival")
|
||||
with journal.open("a", encoding="utf-8") as log:
|
||||
|
||||
def record(action, row):
|
||||
log.write(
|
||||
json.dumps(
|
||||
dict(
|
||||
action=action, path=row["path"], sha256=row["sha256"], size=row["size"]
|
||||
)
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
log.flush()
|
||||
os.fsync(log.fileno())
|
||||
|
||||
for row in state["files"]:
|
||||
if row["keep"]:
|
||||
continue
|
||||
if (root / "RETAIN.json").exists():
|
||||
raise ValueError("Job was pinned during closeout")
|
||||
p = confined(root, row["path"])
|
||||
if not p.exists():
|
||||
record("reconciled", row)
|
||||
continue
|
||||
if regular(p).st_size != row["size"] or digest(p) != row["sha256"]:
|
||||
raise ValueError("Evidence changed at unlink")
|
||||
record("intent", row)
|
||||
p.unlink()
|
||||
record("removed", row)
|
||||
state.update(
|
||||
phase="complete", retired_bytes=sum(r["size"] for r in state["files"] if not r["keep"])
|
||||
)
|
||||
atomic_json(
|
||||
root / "ARCHIVED.json",
|
||||
{k: state[k] for k in ("owner", "archive", "archive_sha256", "retention")},
|
||||
)
|
||||
atomic_json(state_path, state)
|
||||
return state
|
||||
|
||||
|
||||
def restore_file(state_path, relative, destination):
|
||||
state = json.loads(Path(state_path).read_text())
|
||||
row = next(r for r in state["files"] if r["path"] == relative)
|
||||
archive = Path(state["archive"])
|
||||
if digest(archive) != state["archive_sha256"]:
|
||||
raise ValueError("Archive changed")
|
||||
with (
|
||||
zipfile.ZipFile(archive) as z,
|
||||
z.open(relative) as src,
|
||||
Path(destination).open("xb") as dst,
|
||||
):
|
||||
shutil.copyfileobj(src, dst)
|
||||
if digest(destination) != row["sha256"]:
|
||||
Path(destination).unlink()
|
||||
raise ValueError("Restoration checksum mismatch")
|
||||
os.chmod(destination, row["mode"])
|
||||
os.utime(destination, ns=(row["mtime_ns"], row["mtime_ns"]))
|
||||
@@ -9,6 +9,7 @@ import time
|
||||
from pathlib import Path
|
||||
|
||||
from core_client import CoreRequestRejected
|
||||
from evidence_closeout import canonical, closeout, usage
|
||||
from infrastructure_containers import cleanup, docker, run_container
|
||||
from infrastructure_gaussian_sources import prepare_native
|
||||
from infrastructure_pipeline import MODULE, run_pipeline
|
||||
@@ -84,9 +85,24 @@ def reconcile(client, marker, hello=None):
|
||||
)
|
||||
record.pop("completion")
|
||||
write_json(marker, record)
|
||||
registered_request(
|
||||
client, endpoint, dict(action="release", previous_owner=record["owner"]), hello=hello
|
||||
)
|
||||
if not record.get("released"):
|
||||
registered_request(
|
||||
client, endpoint, dict(action="release", previous_owner=record["owner"]), hello=hello
|
||||
)
|
||||
record["released"] = True
|
||||
write_json(marker, record)
|
||||
retention = record.get("retention")
|
||||
if retention:
|
||||
# Retain this durable marker across restart until archival and unlink
|
||||
# finish. Core ACK alone must never discard the cleanup obligation.
|
||||
closeout(
|
||||
Path(retention["root"]),
|
||||
Path(retention["archive_root"]),
|
||||
record["key"],
|
||||
keep=("urban-map.json", "publication-request.json", "failure.json"),
|
||||
limit=retention["archive_limit"],
|
||||
reserve=retention["reserve"],
|
||||
)
|
||||
marker.unlink()
|
||||
|
||||
|
||||
@@ -112,18 +128,36 @@ def prepare_infrastructure(client, row, state, marker, hello=None):
|
||||
if row["identity"]["provider_sha256"] != provider_identity():
|
||||
raise ValueError("Infrastructure provider changed")
|
||||
runtime = state.parent
|
||||
output = Path(profile["job_root"]) / row["key"]
|
||||
output = canonical(Path(profile["job_root"]) / row["key"])
|
||||
existing = output.exists() and any(output.iterdir())
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
write_json(marker, dict(key=row["key"], owner=client.instance, containers=[]))
|
||||
retention = None
|
||||
if not existing and profile.get("archive_root"):
|
||||
retention = dict(
|
||||
root=str(output),
|
||||
archive_root=profile["archive_root"],
|
||||
archive_limit=profile["archive_limit_gib"] * 1024**3,
|
||||
reserve=profile["minimum_free_gib"] * 1024**3,
|
||||
)
|
||||
write_json(
|
||||
marker, dict(key=row["key"], owner=client.instance, containers=[], retention=retention)
|
||||
)
|
||||
endpoint = "/worker/infrastructure-analysis/" + row["key"]
|
||||
last_pulse = -float("inf")
|
||||
connected = True
|
||||
last_storage_check = -float("inf")
|
||||
phase = dict(phase="preparing", completed=0, total=0)
|
||||
|
||||
def pulse():
|
||||
nonlocal last_pulse, phase, connected
|
||||
nonlocal last_pulse, phase, connected, last_storage_check
|
||||
if time.monotonic() - last_pulse < 3:
|
||||
return
|
||||
if time.monotonic() - last_storage_check >= 20 and profile.get("maximum_job_gib"):
|
||||
if usage(output) > profile["maximum_job_gib"] * 1024**3:
|
||||
raise RuntimeError("Infrastructure job storage limit reached")
|
||||
if shutil.disk_usage(output).free < profile["minimum_free_gib"] * 1024**3:
|
||||
raise RuntimeError("Infrastructure storage reserve reached")
|
||||
last_storage_check = time.monotonic()
|
||||
progress = output / "progress.json"
|
||||
if progress.exists():
|
||||
with contextlib.suppress(ValueError, OSError):
|
||||
@@ -139,6 +173,23 @@ def prepare_infrastructure(client, row, state, marker, hello=None):
|
||||
last_pulse = time.monotonic()
|
||||
|
||||
try:
|
||||
if existing:
|
||||
raise RuntimeError(
|
||||
"Existing infrastructure output is immutable; use a new job identity"
|
||||
)
|
||||
if profile.get("maximum_jobs_gib"):
|
||||
reserved = profile["maximum_job_gib"] * 1024**3
|
||||
if usage(output.parent) + reserved > profile["maximum_jobs_gib"] * 1024**3:
|
||||
raise RuntimeError("Infrastructure jobs storage quota reached")
|
||||
archive_root = Path(profile["archive_root"])
|
||||
archive_root.mkdir(parents=True, exist_ok=True)
|
||||
if usage(archive_root) + reserved > profile["archive_limit_gib"] * 1024**3:
|
||||
raise RuntimeError("Infrastructure archive quota reached")
|
||||
if (
|
||||
shutil.disk_usage(archive_root).free
|
||||
< reserved + profile["minimum_free_gib"] * 1024**3
|
||||
):
|
||||
raise RuntimeError("Infrastructure archive reserve reached")
|
||||
if shutil.disk_usage(output).free < profile["minimum_free_gib"] * 1024**3:
|
||||
raise RuntimeError("Insufficient space for Gaussian analysis results")
|
||||
pulse()
|
||||
@@ -182,7 +233,13 @@ def prepare_infrastructure(client, row, state, marker, hello=None):
|
||||
write_json(marker, record)
|
||||
except Exception as exc:
|
||||
logging.exception("Infrastructure analysis failed")
|
||||
write_json(output / "failure.json", dict(type=type(exc).__name__, message=str(exc)))
|
||||
failure = dict(type=type(exc).__name__, message=str(exc))
|
||||
if existing:
|
||||
record = read_json(marker)
|
||||
record["rejected_existing_output"] = failure
|
||||
write_json(marker, record)
|
||||
else:
|
||||
write_json(output / "failure.json", failure)
|
||||
try:
|
||||
registered_request(client, endpoint, dict(action="fail"), hello=hello)
|
||||
except Exception:
|
||||
|
||||
@@ -272,8 +272,11 @@ def review_index(root):
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, root, *, quota=20 * 1024**3, reserve=12 * 1024**3):
|
||||
def __init__(
|
||||
self, root, *, quota=20 * 1024**3, reserve=12 * 1024**3, research_quota=8 * 1024**3
|
||||
):
|
||||
self.root, self.quota, self.reserve = Path(root), quota, reserve
|
||||
self.research_quota = research_quota
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
for folder in ("inbox", "datasets", "work", "sources", "logs"):
|
||||
(self.root / folder).mkdir(exist_ok=True)
|
||||
@@ -286,7 +289,26 @@ class Store:
|
||||
self.db.commit()
|
||||
|
||||
def capacity(self, additional):
|
||||
used = sum(p.stat().st_size for p in self.root.rglob("*") if p.is_file())
|
||||
# Historical research has its own finite allowance. It must not consume
|
||||
# the dataset admission budget, nor disappear from all accounting.
|
||||
research_roots = {
|
||||
"experiments",
|
||||
"agent-reviews",
|
||||
"audits",
|
||||
"archives",
|
||||
"reviews",
|
||||
"verification",
|
||||
}
|
||||
used = research = 0
|
||||
for p in self.root.rglob("*"):
|
||||
if not p.is_file():
|
||||
continue
|
||||
if p.relative_to(self.root).parts[0] in research_roots:
|
||||
research += p.stat().st_size
|
||||
else:
|
||||
used += p.stat().st_size
|
||||
if research > self.research_quota:
|
||||
raise RuntimeError("Worker research storage quota reached; close completed experiments")
|
||||
if (
|
||||
used + additional > self.quota
|
||||
or shutil.disk_usage(self.root).free < self.reserve + additional
|
||||
|
||||
@@ -9,5 +9,9 @@
|
||||
"producer_data": "D:/NDC_GAUSSIAN_PIPELINE/data",
|
||||
"sevenzip": "C:/Program Files/7-Zip/7z.exe",
|
||||
"splat_transform": "tools/splat-transform-3.4.0/node_modules/@playcanvas/splat-transform/bin/cli.mjs",
|
||||
"job_root": "C:/NDC_MISSIONCORE_CACHE/urban-mapping/jobs"
|
||||
}
|
||||
"job_root": "C:/NDC_MISSIONCORE_CACHE/urban-mapping/jobs",
|
||||
"archive_root": "C:/NDC_MISSIONCORE_ARCHIVE/urban-mapping-job-results",
|
||||
"archive_limit_gib": 128,
|
||||
"maximum_job_gib": 24,
|
||||
"maximum_jobs_gib": 48
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user