Files
NODEDC_MISSION_CORE/scripts/compact_closed_evidence.py
T

325 lines
13 KiB
Python

"""Explicit plan/apply deduplication of closed immutable evidence, never a sweep.
Preserves each logical path/content; historical snapshots become read-only.
Canonical copies are pinned outside working roots. This saves physical blocks,
not logical quota. No original scans, models, releases or live jobs are eligible.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import stat
from pathlib import Path
EXTENSIONS = {".npz", ".png", ".jpg"}
def sha(p):
with p.open("rb") as f:
return hashlib.file_digest(f, "sha256").hexdigest()
def canonical(path):
path = Path(path).absolute()
for p in [path, *path.parents]:
if p.is_symlink() or (p.exists() and getattr(p.lstat(), "st_file_attributes", 0) & 0x400):
raise ValueError("Linked evidence path")
return path
def control_file(path):
canonical(path)
if path.exists() and (not plain(path) or path.stat().st_nlink != 1):
raise ValueError("Unsafe compaction control file")
return path
def security(p, *, effective=False):
if os.name != "nt":
return [p.stat().st_uid, p.stat().st_gid, stat.S_IMODE(p.stat().st_mode)]
import ctypes
from ctypes import wintypes
needed = wintypes.DWORD()
get = ctypes.windll.advapi32.GetFileSecurityW
get.argtypes = [
wintypes.LPCWSTR,
wintypes.DWORD,
wintypes.LPVOID,
wintypes.DWORD,
ctypes.POINTER(wintypes.DWORD),
]
get(str(p), 7, None, 0, ctypes.byref(needed))
if not needed.value:
raise OSError("Cannot inventory evidence permissions")
buf = ctypes.create_string_buffer(needed.value)
if not get(str(p), 7, buf, needed.value, ctypes.byref(needed)):
raise OSError("Cannot read evidence permissions")
raw = bytearray(buf.raw)
if effective:
# Windows recomputes this bookkeeping bit when setting a new descriptor.
# Keep owner/group, ACEs, protection and every other control bit exact.
control = int.from_bytes(raw[2:4], "little") & ~0x400
raw[2:4] = control.to_bytes(2, "little")
return hashlib.sha256(raw).hexdigest()
def copy_security(source, target):
import ctypes
from ctypes import wintypes
needed = wintypes.DWORD()
get = ctypes.windll.advapi32.GetFileSecurityW
get.argtypes = [
wintypes.LPCWSTR,
wintypes.DWORD,
wintypes.LPVOID,
wintypes.DWORD,
ctypes.POINTER(wintypes.DWORD),
]
get(str(source), 7, None, 0, ctypes.byref(needed))
buf = ctypes.create_string_buffer(needed.value)
if not get(str(source), 7, buf, needed.value, ctypes.byref(needed)):
raise OSError("ACL read failed")
control = int.from_bytes(buf.raw[2:4], "little")
setter = ctypes.windll.advapi32.SetFileSecurityW
setter.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.LPVOID]
protection = 0x80000000 if control & 0x1000 else 0x20000000
if not setter(str(target), 7 | protection, buf):
raise OSError("ACL copy failed")
if security(source, effective=True) != security(target, effective=True):
raise ValueError("Restoration changed permissions; shared evidence preserved")
def plain(p):
s = p.lstat()
if not stat.S_ISREG(s.st_mode) or p.is_symlink() or getattr(s, "st_file_attributes", 0) & 0x400:
return False
if os.name == "nt":
import ctypes
from ctypes import wintypes
class Stream(ctypes.Structure):
_fields_ = [("size", ctypes.c_longlong), ("name", wintypes.WCHAR * 296)]
info = Stream()
find = ctypes.windll.kernel32.FindFirstStreamW
find.restype = wintypes.HANDLE
find.argtypes = [wintypes.LPCWSTR, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD]
ctypes.windll.kernel32.FindNextStreamW.argtypes = [wintypes.HANDLE, wintypes.LPVOID]
ctypes.windll.kernel32.FindClose.argtypes = [wintypes.HANDLE]
h = find(str(p), 0, ctypes.byref(info), 0)
if h == ctypes.c_void_p(-1).value:
raise OSError("Cannot inspect alternate streams")
try:
if info.name != "::$DATA" or ctypes.windll.kernel32.FindNextStreamW(
h, ctypes.byref(info)
):
return False
finally:
ctypes.windll.kernel32.FindClose(h)
return True
def plan(roots, store):
groups = {}
skipped = []
for root in roots:
if root.is_symlink() or getattr(root.lstat(), "st_file_attributes", 0) & 0x400:
raise ValueError("Linked root")
for base, dirs, files in os.walk(root, followlinks=False):
dirs[:] = [
n
for n in dirs
if not (Path(base) / n).is_symlink()
and not getattr((Path(base) / n).lstat(), "st_file_attributes", 0) & 0x400
]
for name in files:
p = Path(base) / name
s = p.lstat()
if p.suffix not in EXTENSIONS or s.st_size < 65536:
continue
if not plain(p) or s.st_nlink != 1 or getattr(s, "st_file_attributes", 0) & 1:
skipped.append(str(p))
continue
groups.setdefault(s.st_size, []).append(p)
identical = {}
for size, paths in groups.items():
if len(paths) < 2:
continue
for p in paths:
s = p.stat()
digest = sha(p)
acl = security(p)
key = (size, digest, json.dumps(acl))
identical.setdefault(key, []).append(
dict(
path=str(p),
size=size,
sha256=digest,
mtime_ns=s.st_mtime_ns,
inode=s.st_ino,
device=s.st_dev,
mode=stat.S_IMODE(s.st_mode),
security=acl,
)
)
rows = [v for v in identical.values() if len(v) > 1]
return dict(
schema="missioncore.closed-evidence-dedup/v1",
roots=[str(p) for p in roots],
store=str(store),
groups=rows,
duplicate_bytes=sum((len(v) - 1) * v[0]["size"] for v in rows),
canonical_bytes=sum(v[0]["size"] for v in rows),
skipped=skipped,
contract="explicitly closed snapshots; paths and bytes retained; no in-place rewrite",
)
def apply(document):
store = canonical(document["store"])
roots = [canonical(p) for p in document["roots"]]
if any(store == r or store.is_relative_to(r) or r.is_relative_to(store) for r in roots):
raise ValueError("CAS must be separately pinned")
if store.resolve() != store.absolute() or any(r.resolve() != r.absolute() for r in roots):
raise ValueError("Linked evidence owner")
store.mkdir(parents=True, exist_ok=True)
control_file(store / "PIN.json").write_text(
json.dumps(
{
"owner": "closed-urban-evidence",
"policy": "Explicit retention; never jobs/qualifications cleanup",
"source_roots": document["roots"],
}
)
)
if shutil.disk_usage(store).free < document["canonical_bytes"] + 40 * 1024**3:
raise RuntimeError("CAS staging reserve")
receipt = control_file(store / "aliases.jsonl")
control_file(store / "maintenance.lock")
# Exclusive maintenance lock. Existing lock never expires automatically.
with (store / "maintenance.lock").open("x"):
pass
try:
with receipt.open("a", encoding="utf-8") as log:
def record(event, **kw):
log.write(json.dumps(dict(event=event, **kw)) + "\n")
log.flush()
os.fsync(log.fileno())
for group in document["groups"]:
first = group[0]
digest = first["sha256"]
security_id = hashlib.sha256(json.dumps(first["security"]).encode()).hexdigest()[
:16
]
blob = canonical(store / (digest + "-" + security_id + ".blob"))
if blob.exists() and not plain(blob):
raise ValueError("Unsafe canonical evidence")
# Complete group validation precedes replacing any of its aliases.
for row in group:
p = canonical(row["path"])
if (
p.resolve() != p.absolute()
or not any(p.is_relative_to(r) for r in roots)
or not plain(p)
):
raise ValueError("Unsafe alias")
if p.stat().st_dev != store.stat().st_dev:
raise ValueError("Cross-volume alias")
expected = row["security"]
if os.name != "nt" and blob.exists() and os.path.samefile(p, blob):
expected = [*expected[:2], expected[2] & ~0o222]
if sha(p) != digest or security(p) != expected:
raise ValueError("Evidence/permissions changed")
if (not blob.exists() or not os.path.samefile(p, blob)) and (
p.stat().st_nlink != 1 or p.stat().st_mtime_ns != row["mtime_ns"]
):
raise ValueError("Evidence identity changed")
if not blob.exists():
# Anchor the verified inode in the pinned store. Native hardlinks
# preserve owner/DACL/protection exactly without ACL reconstruction.
os.link(first["path"], blob)
expected = first["security"]
readonly_expected = (
expected if os.name == "nt" else [*expected[:2], expected[2] & ~0o222]
)
if sha(blob) != digest or security(blob) not in (expected, readonly_expected):
raise ValueError("CAS content/permissions changed")
# Readonly is an accidental-write guard, not a security boundary.
os.chmod(blob, stat.S_IREAD if os.name == "nt" else first["mode"] & ~0o222)
for row in group:
p = canonical(row["path"])
if os.path.samefile(p, blob):
continue
if sha(p) != digest or p.stat().st_mtime_ns != row["mtime_ns"]:
raise ValueError("Alias changed at replacement")
tmp = p.with_name(p.name + ".dedup-link")
if tmp.exists():
raise ValueError("Unreconciled replacement")
record("intent", **row, canonical=str(blob))
os.link(blob, tmp)
os.replace(tmp, p)
if not os.path.samefile(p, blob) or sha(p) != digest:
raise ValueError("Alias acceptance failed")
record(
"linked", path=str(p), canonical=str(blob), sha256=digest, size=row["size"]
)
finally:
(store / "maintenance.lock").unlink()
def restore_alias(row, blob_path, destination):
"""Restore an independent copy to a new path; never unlock shared aliases."""
blob, destination = canonical(blob_path), canonical(destination)
expected = (
row["security"] if os.name == "nt" else [*row["security"][:2], row["security"][2] & ~0o222]
)
if not plain(blob) or sha(blob) != row["sha256"] or security(blob) != expected:
raise ValueError("Retained evidence no longer matches")
if os.name == "nt":
import ctypes
from ctypes import wintypes
copy = ctypes.windll.kernel32.CopyFileW
copy.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.BOOL]
if not copy(str(blob), str(destination), True):
raise OSError("Independent restoration failed")
copy_security(blob, destination)
else:
with blob.open("rb") as src, destination.open("xb") as dst:
shutil.copyfileobj(src, dst)
dst.flush()
os.fsync(dst.fileno())
if sha(destination) != row["sha256"]:
raise ValueError("Restoration changed bytes")
os.chmod(destination, row["mode"])
os.utime(destination, ns=(row["mtime_ns"], row["mtime_ns"]))
return destination
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("action", choices=["plan", "apply"])
p.add_argument("--root", action="append", type=Path)
p.add_argument("--store", type=Path)
p.add_argument("--plan", type=Path, required=True)
a = p.parse_args()
if a.action == "plan":
result = plan(a.root, a.store)
a.plan.write_text(json.dumps(result, indent=2))
print(
json.dumps(
{k: v for k, v in result.items() if k in ("duplicate_bytes", "canonical_bytes")}
)
)
else:
apply(json.loads(a.plan.read_text()))
print("Applied exact closed-evidence plan")