Bound semantic worker storage and add verified evidence closeout
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{16}$')][string]$Release,
|
||||
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{16}$')][string]$ExpectedCurrentRelease,
|
||||
[ValidateSet("ai-polygon","semantic-learning")][string]$Kind="ai-polygon",
|
||||
[string]$EvidenceRoot,
|
||||
[ValidateRange(0,6)][int]$ProjectLod,
|
||||
[switch]$Apply
|
||||
@@ -9,22 +10,35 @@ param(
|
||||
# principal, task settings, credentials and tunnel configuration are preserved.
|
||||
$ErrorActionPreference='Stop'
|
||||
$root='D:\NDC_MISSIONCORE\runtime\simulation'
|
||||
$name='ndc-ai-polygon-worker'
|
||||
$name="ndc-$Kind-worker"
|
||||
if($Kind -eq 'semantic-learning' -and ($EvidenceRoot -or $PSBoundParameters.ContainsKey('ProjectLod'))) { throw 'Simulation options cannot alter learning service' }
|
||||
foreach($marker in @('active.json','editor-active.json','route-active.json','infrastructure-active.json')) {
|
||||
if(Test-Path "$root\state\$marker") { throw 'Active simulation work prevents update' }
|
||||
}
|
||||
$task=Get-ScheduledTask -TaskName $name
|
||||
if(@($task.Actions).Count -ne 1) { throw 'Expected one installed worker action' }
|
||||
$old=$task.Actions[0]
|
||||
$releaseMatches=[regex]::Matches($old.Arguments,'ai-polygon-([a-f0-9]{16})[\\/]+simulation[\\/]+ai-polygon[\\/]+realtime_worker\.py')
|
||||
$entryPattern=if($Kind -eq 'ai-polygon') {'simulation[\\/]+ai-polygon[\\/]+realtime_worker\.py'} else {'worker\.py'}
|
||||
$releaseMatches=[regex]::Matches($old.Arguments,$Kind+'-([a-f0-9]{16})[\\/]+'+$entryPattern)
|
||||
if($releaseMatches.Count -ne 1 -or $releaseMatches[0].Groups[1].Value -ne $ExpectedCurrentRelease) {
|
||||
throw 'Installed worker identity changed'
|
||||
}
|
||||
$source="$root\releases\ai-polygon-$Release"
|
||||
$manifestPath="$root\releases\ai-polygon-$Release.manifest.json"
|
||||
$source="$root\releases\$Kind-$Release"
|
||||
$manifestPath=if($Kind -eq 'ai-polygon') {"$source.manifest.json"} else {"$source\release.json"}
|
||||
$digest=(Get-FileHash $manifestPath -Algorithm SHA256).Hash.ToLower()
|
||||
if(!$digest.StartsWith($Release)) { throw 'Manifest identity mismatch' }
|
||||
if($Kind -eq 'ai-polygon' -and !$digest.StartsWith($Release)) { throw 'Manifest identity mismatch' }
|
||||
$manifest=Get-Content $manifestPath -Raw | ConvertFrom-Json
|
||||
if($Kind -eq 'semantic-learning') {
|
||||
$identityCode="import json,hashlib; m=json.load(open(r'$manifestPath')); assert m['id']==hashlib.sha256(json.dumps(m['files'],sort_keys=True).encode()).hexdigest(); assert m['id'].startswith('$Release')"
|
||||
$encoded=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($identityCode))
|
||||
& $old.Execute -c ("exec(__import__('base64').b64decode('"+$encoded+"'))")
|
||||
if($LASTEXITCODE -ne 0) { throw 'Learning identity mismatch' }
|
||||
$idleCode="import sqlite3; d=sqlite3.connect('file:D:/NDC_MISSIONCORE/datasets/urban-learning/queue.sqlite3?mode=ro',uri=True); assert not list(d.execute(""select id from jobs where state not in ('failed','draft-ready')""))"
|
||||
$encoded=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($idleCode))
|
||||
& $old.Execute -c ("exec(__import__('base64').b64decode('"+$encoded+"'))")
|
||||
if($LASTEXITCODE -ne 0) { throw 'Learning work prevents update' }
|
||||
$manifest=$manifest.files
|
||||
}
|
||||
$count=0
|
||||
foreach($entry in $manifest.PSObject.Properties) {
|
||||
$path=[IO.Path]::GetFullPath((Join-Path $source $entry.Name))
|
||||
@@ -37,9 +51,10 @@ foreach($entry in $manifest.PSObject.Properties) {
|
||||
if($count -eq 0) { throw 'Empty release' }
|
||||
# Validate startup imports with the installed interpreter while the old service
|
||||
# still owns the runtime. --help cannot acquire a service lock or start models.
|
||||
$preflight = & $old.Execute "$source\simulation\ai-polygon\realtime_worker.py" --help 2>&1
|
||||
$workerScript=if($Kind -eq 'ai-polygon') {"$source\simulation\ai-polygon\realtime_worker.py"} else {"$source\worker.py"}
|
||||
$preflight = & $old.Execute $workerScript --help 2>&1
|
||||
if($LASTEXITCODE -ne 0) { throw 'Worker startup preflight failed; installed service preserved' }
|
||||
$arguments=$old.Arguments.Replace('ai-polygon-'+$ExpectedCurrentRelease,'ai-polygon-'+$Release)
|
||||
$arguments=$old.Arguments.Replace($Kind+'-'+$ExpectedCurrentRelease,$Kind+'-'+$Release)
|
||||
if($EvidenceRoot) {
|
||||
$EvidenceRoot=[IO.Path]::GetFullPath($EvidenceRoot)
|
||||
if($EvidenceRoot -notmatch '^[A-Za-z]:\\' -or $EvidenceRoot -match '[&|<>^%!"\r\n]') {
|
||||
@@ -53,7 +68,7 @@ if($PSBoundParameters.ContainsKey('ProjectLod')) {
|
||||
$arguments=[regex]::Replace($arguments,'--project-lod\s+\d+','--project-lod '+$ProjectLod)
|
||||
} else { $arguments+=' --project-lod '+$ProjectLod }
|
||||
}
|
||||
$action=New-ScheduledTaskAction -Execute $old.Execute -Argument $arguments -WorkingDirectory $old.WorkingDirectory
|
||||
$action=New-ScheduledTaskAction -Execute $old.Execute -Argument $arguments -WorkingDirectory $old.WorkingDirectory.Replace($Kind+'-'+$ExpectedCurrentRelease,$Kind+'-'+$Release)
|
||||
$report=[ordered]@{utc=[DateTime]::UtcNow.ToString('o'); task=$name; previous=$ExpectedCurrentRelease;
|
||||
release=$Release; manifest_sha256=$digest; verified_files=$count; applied=$false;
|
||||
network_changed=$false; credentials_changed=$false; principal_changed=$false}
|
||||
@@ -64,7 +79,7 @@ if($Apply) {
|
||||
$backup="$root\preparations\worker-activation-$Release"
|
||||
New-Item -ItemType Directory -Path $backup -ErrorAction Stop | Out-Null
|
||||
Export-ScheduledTask -TaskName $name | Set-Content -Encoding UTF8 "$backup\previous-task.xml"
|
||||
$oldPattern="ai-polygon-$ExpectedCurrentRelease[\\/]+simulation[\\/]+ai-polygon[\\/]+realtime_worker\.py"
|
||||
$oldPattern=$Kind+'-'+$ExpectedCurrentRelease+'[\\/]+'+$entryPattern
|
||||
try {
|
||||
Stop-ScheduledTask -TaskName $name
|
||||
$deadline=[DateTime]::UtcNow.AddSeconds(10)
|
||||
@@ -72,6 +87,16 @@ if($Apply) {
|
||||
if([DateTime]::UtcNow -ge $deadline) { throw 'Old worker did not stop' }
|
||||
Start-Sleep -Milliseconds 200
|
||||
}
|
||||
# Close the startup-preflight race: never switch release with work that
|
||||
# arrived while hashes/imports were being checked. Catch restores old action.
|
||||
foreach($marker in @('active.json','editor-active.json','route-active.json','infrastructure-active.json')) {
|
||||
if(Test-Path "$root\state\$marker") { throw 'Work arrived during update; restoring previous worker' }
|
||||
}
|
||||
if($Kind -eq 'semantic-learning') {
|
||||
$encoded=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($idleCode))
|
||||
& $old.Execute -c ("exec(__import__('base64').b64decode('"+$encoded+"'))")
|
||||
if($LASTEXITCODE -ne 0) { throw 'Learning work arrived during update; restoring previous worker' }
|
||||
}
|
||||
Set-ScheduledTask -TaskName $name -Action $action | Out-Null
|
||||
Start-ScheduledTask -TaskName $name
|
||||
Start-Sleep -Seconds 3
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
"""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")
|
||||
@@ -34,17 +34,32 @@ def confined(root, relative):
|
||||
|
||||
|
||||
def stage(runtime, recipe):
|
||||
kind = recipe.get("kind", "ai-polygon")
|
||||
if kind not in ("ai-polygon", "semantic-learning"):
|
||||
raise ValueError("Unsupported worker kind")
|
||||
previous = recipe["base_release"]
|
||||
if not re.fullmatch("[a-f0-9]{16}", previous):
|
||||
raise ValueError("Invalid base release")
|
||||
releases = runtime / "releases"
|
||||
base = releases / ("ai-polygon-" + previous)
|
||||
manifest_path = releases / ("ai-polygon-" + previous + ".manifest.json")
|
||||
if sha(manifest_path) != recipe["base_manifest_sha256"] or not sha(manifest_path).startswith(
|
||||
previous
|
||||
):
|
||||
base = releases / (kind + "-" + previous)
|
||||
manifest_path = (
|
||||
base / "release.json"
|
||||
if kind == "semantic-learning"
|
||||
else releases / ("ai-polygon-" + previous + ".manifest.json")
|
||||
)
|
||||
if sha(manifest_path) != recipe["base_manifest_sha256"]:
|
||||
raise ValueError("Base manifest changed")
|
||||
before = json.loads(manifest_path.read_text())
|
||||
original = json.loads(manifest_path.read_text())
|
||||
before = original["files"] if kind == "semantic-learning" else original
|
||||
base_identity = (
|
||||
hashlib.sha256(json.dumps(before, sort_keys=True).encode()).hexdigest()
|
||||
if kind == "semantic-learning"
|
||||
else sha(manifest_path)
|
||||
)
|
||||
if not base_identity.startswith(previous) or (
|
||||
kind == "semantic-learning" and original["id"] != base_identity
|
||||
):
|
||||
raise ValueError("Base release identity mismatch")
|
||||
for name, digest in before.items():
|
||||
if sha(confined(base, name)) != digest:
|
||||
raise ValueError("Base file changed: " + name)
|
||||
@@ -60,11 +75,18 @@ def stage(runtime, recipe):
|
||||
after = {**before, **{name: hashlib.sha256(raw).hexdigest() for name, raw in overlays.items()}}
|
||||
encoded = json.dumps(after, sort_keys=True, indent=2).encode()
|
||||
identity = hashlib.sha256(encoded).hexdigest()
|
||||
target = releases / ("ai-polygon-" + identity[:16])
|
||||
output_manifest = target.with_suffix(".manifest.json")
|
||||
if kind == "semantic-learning":
|
||||
identity = hashlib.sha256(json.dumps(after, sort_keys=True).encode()).hexdigest()
|
||||
encoded = json.dumps({**original, "id": identity, "files": after}, indent=2).encode()
|
||||
target = releases / (kind + "-" + identity[:16])
|
||||
output_manifest = (
|
||||
target / "release.json"
|
||||
if kind == "semantic-learning"
|
||||
else target.with_suffix(".manifest.json")
|
||||
)
|
||||
if target.exists() or output_manifest.exists():
|
||||
raise ValueError("Release already exists; inspect it instead of overwriting")
|
||||
temporary = releases / (".staging-" + identity[:16])
|
||||
temporary = releases / (".staging-" + kind + "-" + identity[:16])
|
||||
temporary.mkdir()
|
||||
for name, digest in after.items():
|
||||
dest = confined(temporary, name)
|
||||
@@ -80,7 +102,8 @@ def stage(runtime, recipe):
|
||||
result = dict(
|
||||
previous=previous,
|
||||
release=identity[:16],
|
||||
manifest_sha256=identity,
|
||||
manifest_sha256=hashlib.sha256(encoded).hexdigest(),
|
||||
kind=kind,
|
||||
files=len(after),
|
||||
changed=sorted(overlays),
|
||||
activated=False,
|
||||
|
||||
Reference in New Issue
Block a user