Bound semantic worker storage and add verified evidence closeout
This commit is contained in:
@@ -275,3 +275,24 @@ provenance и квитанции; raw в интерфейсе — геометр
|
|||||||
что продуктовые карты и ручные правки не изменились. Наличие лимита датасетов в
|
что продуктовые карты и ручные правки не изменились. Наличие лимита датасетов в
|
||||||
одном процессе не означает общей квоты всех исследовательских скриптов.
|
одном процессе не означает общей квоты всех исследовательских скриптов.
|
||||||
Подробные действующие границы: `docs/STORAGE_RETENTION.md`, раздел аудита 07.11.2026.
|
Подробные действующие границы: `docs/STORAGE_RETENTION.md`, раздел аудита 07.11.2026.
|
||||||
|
|
||||||
|
|
||||||
|
## Исполняемый Worker-closeout — 07.11.2026
|
||||||
|
|
||||||
|
Для новых полносценовых заданий `infrastructure_preparer` закрывает данные после
|
||||||
|
остановки собственных контейнеров и подтверждения Core: точный ZIP, SHA всех
|
||||||
|
членов, журнал намерений удаления, затем только собственные неизменившиеся
|
||||||
|
промежуточные файлы. Архив не является scratch. Лимиты профиля: 24 GiB на задание,
|
||||||
|
48 GiB рабочие задания, 128 GiB архив, резерв 40 GiB; переполнение блокирует новый
|
||||||
|
запуск, не удаляет карту или rollback. Незавершённая архивация сохраняет marker и
|
||||||
|
восстанавливается после перезапуска. Старый job без retention-ownership автоматически
|
||||||
|
не удаляется. Learning Store отдельно ограничивает рабочие данные 20 GiB и
|
||||||
|
именованные исследовательские данные 8 GiB, резерв 12 GiB. Внешний исследовательский
|
||||||
|
скрипт по-прежнему обязан соблюдать собственный лимит; это не квота файловой системы.
|
||||||
|
|
||||||
|
Закрытые исторические snapshots можно дедуплицировать по точному плану только при
|
||||||
|
остановленных writers. Сохраняются все пути, байты, права и защищённый CAS-якорь;
|
||||||
|
неизменяемые aliases нельзя открывать для записи. Восстановление для новой работы —
|
||||||
|
независимая копия в новый каталог. Отчёт текущей очистки, индексы и восстановления:
|
||||||
|
`outputs/storage-closeout-20261107/REPORT.md`. Эти операции не являются обучением,
|
||||||
|
приёмкой качества разметки или новым разрешением на управление питанием.
|
||||||
|
|||||||
+57
-10
@@ -344,17 +344,64 @@ by age or remove unknown files. The source-package helper remains source-only;
|
|||||||
its caller must remove its own transferred staging after remote identity checks.
|
its caller must remove its own transferred staging after remote identity checks.
|
||||||
This is an engineering closeout obligation, not an automatic whole-disk quota.
|
This is an engineering closeout obligation, not an automatic whole-disk quota.
|
||||||
|
|
||||||
Worker has different stores with different ownership: learning `datasets`,
|
Worker stores remain separate: learning `datasets`, `inbox`, `sources`, `work`;
|
||||||
`inbox`, `sources`, `work`; infrastructure `jobs` and generated source caches;
|
infrastructure `jobs` and generated source caches; historical qualifications and
|
||||||
and historical qualification directories. The learning Store's 20 GiB admission
|
explicitly pinned archives. Container removal never removes its data mounts.
|
||||||
quota/12 GiB reserve does not constrain arbitrary research writers. Infrastructure
|
|
||||||
has initial free-space and time checks but currently no aggregate output retention.
|
The November closeout adds bounded admission and terminal job handling:
|
||||||
Container removal does not remove the data mounts. Do not call those stores
|
|
||||||
bounded or erase them wholesale: current maps, shared observations, accepted
|
- Learning Store: 20 GiB operational data, 8 GiB explicitly named research roots
|
||||||
models/datasets, pending work and rollback require explicit preservation.
|
(`experiments`, `agent-reviews`, `audits`, `archives`, `reviews`, `verification`),
|
||||||
|
12 GiB free-space reserve. Unknown roots count as operational data. Both budgets
|
||||||
|
are checked; exceeding either refuses new data. This is application admission,
|
||||||
|
not a filesystem quota for arbitrary external research scripts.
|
||||||
|
- New infrastructure jobs: 24 GiB per job, 48 GiB aggregate working directory,
|
||||||
|
40 GiB free-space reserve. The coordinator checks output/free space at heartbeat
|
||||||
|
intervals; a writer can overshoot between checks. These are not OS hard quotas.
|
||||||
|
- The separate terminal-job archive has a 128 GiB admission limit. A new job
|
||||||
|
reserves room for its maximum output before starting. Existing results are
|
||||||
|
never silently evicted to admit new work. A full archive blocks admission and
|
||||||
|
requires an explicit retention decision.
|
||||||
|
- `simulation/ai-polygon/evidence_closeout.py` runs only after owned producers
|
||||||
|
stop and Core confirms delivery/rejection and lease release. It creates an
|
||||||
|
archive of the exact inventory, verifies every SHA-256 and member, then retires
|
||||||
|
only unchanged non-kept files through a durable intent journal. Root map,
|
||||||
|
publication request/failure and an archive pointer remain in the job directory.
|
||||||
|
A pending closeout retains its durable marker across coordinator restarts.
|
||||||
|
Pins, links, changed files, invalid journal records and insufficient reserve
|
||||||
|
fail closed. A published ZIP is recoverable even if the following state commit
|
||||||
|
was interrupted. Archives are persistent data, not another disposable cache.
|
||||||
|
- Previously created jobs do not acquire cleanup authority retroactively. Failed
|
||||||
|
learning work and legacy experiments require their own explicit inventory,
|
||||||
|
stopped-owner proof, archival check and receipt. Accepted datasets/models,
|
||||||
|
shared sources, pending edits and required rollback remain protected.
|
||||||
|
|
||||||
|
`scripts/compact_closed_evidence.py` is a separate maintenance tool for explicitly
|
||||||
|
closed immutable historical snapshots. It groups only eligible NPZ/PNG/JPG files
|
||||||
|
by full bytes and identical permissions, anchors one NTFS inode in a pinned store
|
||||||
|
and keeps every original path as a read-only hardlink. It changes neither logical
|
||||||
|
content nor reference paths; logical byte totals and application quotas therefore
|
||||||
|
remain unchanged. It refuses reparse paths, foreign links, alternate streams,
|
||||||
|
changed files and cross-volume stores. Read-only is an accidental-write guard,
|
||||||
|
not a security boundary: owners must not clear it and edit a shared snapshot.
|
||||||
|
The full plan retains original identity/mtime/mode and a per-alias receipt.
|
||||||
|
Recovery creates a NEW independent file; it never unlocks the shared inode.
|
||||||
|
Windows restoration verifies owner/group/ACEs/protection, allowing only the
|
||||||
|
recomputed `SE_DACL_AUTO_INHERITED` bookkeeping bit. CAS aliases themselves keep
|
||||||
|
the original raw descriptor exactly. Keep the canonical store pinned outside
|
||||||
|
all job/scratch cleanup roots. This same-volume optimization is optional;
|
||||||
|
ordinary copies on another filesystem retain the data but may use more space.
|
||||||
|
|
||||||
|
ZIP/JSON datasets and results remain portable. Storage paths and byte limits live
|
||||||
|
in the worker profile. Coordinators are immutable source releases using the
|
||||||
|
existing Windows Python/Scheduled Tasks; heavyweight inference runs in pinned
|
||||||
|
Docker images with external persistent data. Runtime-only patch activation
|
||||||
|
preserves credentials, task settings, network and the previous release for rollback.
|
||||||
|
|
||||||
The audit/cleanup index is `outputs/semantic-storage-audit-20261107/REPORT.md`.
|
The audit/cleanup index is `outputs/semantic-storage-audit-20261107/REPORT.md`.
|
||||||
The 19 October content-addressed experiment archive remains protected; November
|
The 19 October content-addressed experiment archive remains protected; November
|
||||||
cleanup retires only extra Mac copies verified against that archive, with a
|
cleanup retires only extra Mac copies verified against that archive, with a
|
||||||
one-file restoration helper. No Worker datasets or qualifications are deleted
|
one-file restoration helper. That local-only audit did not delete Worker datasets or qualifications. The
|
||||||
by this local cleanup.
|
subsequent explicit closeout is indexed separately at
|
||||||
|
`outputs/storage-closeout-20261107/REPORT.md`; do not add the two cleanup totals
|
||||||
|
without checking their distinct manifests.
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
param(
|
param(
|
||||||
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{16}$')][string]$Release,
|
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{16}$')][string]$Release,
|
||||||
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{16}$')][string]$ExpectedCurrentRelease,
|
[Parameter(Mandatory=$true)][ValidatePattern('^[a-f0-9]{16}$')][string]$ExpectedCurrentRelease,
|
||||||
|
[ValidateSet("ai-polygon","semantic-learning")][string]$Kind="ai-polygon",
|
||||||
[string]$EvidenceRoot,
|
[string]$EvidenceRoot,
|
||||||
[ValidateRange(0,6)][int]$ProjectLod,
|
[ValidateRange(0,6)][int]$ProjectLod,
|
||||||
[switch]$Apply
|
[switch]$Apply
|
||||||
@@ -9,22 +10,35 @@ param(
|
|||||||
# principal, task settings, credentials and tunnel configuration are preserved.
|
# principal, task settings, credentials and tunnel configuration are preserved.
|
||||||
$ErrorActionPreference='Stop'
|
$ErrorActionPreference='Stop'
|
||||||
$root='D:\NDC_MISSIONCORE\runtime\simulation'
|
$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')) {
|
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' }
|
if(Test-Path "$root\state\$marker") { throw 'Active simulation work prevents update' }
|
||||||
}
|
}
|
||||||
$task=Get-ScheduledTask -TaskName $name
|
$task=Get-ScheduledTask -TaskName $name
|
||||||
if(@($task.Actions).Count -ne 1) { throw 'Expected one installed worker action' }
|
if(@($task.Actions).Count -ne 1) { throw 'Expected one installed worker action' }
|
||||||
$old=$task.Actions[0]
|
$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) {
|
if($releaseMatches.Count -ne 1 -or $releaseMatches[0].Groups[1].Value -ne $ExpectedCurrentRelease) {
|
||||||
throw 'Installed worker identity changed'
|
throw 'Installed worker identity changed'
|
||||||
}
|
}
|
||||||
$source="$root\releases\ai-polygon-$Release"
|
$source="$root\releases\$Kind-$Release"
|
||||||
$manifestPath="$root\releases\ai-polygon-$Release.manifest.json"
|
$manifestPath=if($Kind -eq 'ai-polygon') {"$source.manifest.json"} else {"$source\release.json"}
|
||||||
$digest=(Get-FileHash $manifestPath -Algorithm SHA256).Hash.ToLower()
|
$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
|
$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
|
$count=0
|
||||||
foreach($entry in $manifest.PSObject.Properties) {
|
foreach($entry in $manifest.PSObject.Properties) {
|
||||||
$path=[IO.Path]::GetFullPath((Join-Path $source $entry.Name))
|
$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' }
|
if($count -eq 0) { throw 'Empty release' }
|
||||||
# Validate startup imports with the installed interpreter while the old service
|
# Validate startup imports with the installed interpreter while the old service
|
||||||
# still owns the runtime. --help cannot acquire a service lock or start models.
|
# 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' }
|
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) {
|
if($EvidenceRoot) {
|
||||||
$EvidenceRoot=[IO.Path]::GetFullPath($EvidenceRoot)
|
$EvidenceRoot=[IO.Path]::GetFullPath($EvidenceRoot)
|
||||||
if($EvidenceRoot -notmatch '^[A-Za-z]:\\' -or $EvidenceRoot -match '[&|<>^%!"\r\n]') {
|
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)
|
$arguments=[regex]::Replace($arguments,'--project-lod\s+\d+','--project-lod '+$ProjectLod)
|
||||||
} else { $arguments+=' --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;
|
$report=[ordered]@{utc=[DateTime]::UtcNow.ToString('o'); task=$name; previous=$ExpectedCurrentRelease;
|
||||||
release=$Release; manifest_sha256=$digest; verified_files=$count; applied=$false;
|
release=$Release; manifest_sha256=$digest; verified_files=$count; applied=$false;
|
||||||
network_changed=$false; credentials_changed=$false; principal_changed=$false}
|
network_changed=$false; credentials_changed=$false; principal_changed=$false}
|
||||||
@@ -64,7 +79,7 @@ if($Apply) {
|
|||||||
$backup="$root\preparations\worker-activation-$Release"
|
$backup="$root\preparations\worker-activation-$Release"
|
||||||
New-Item -ItemType Directory -Path $backup -ErrorAction Stop | Out-Null
|
New-Item -ItemType Directory -Path $backup -ErrorAction Stop | Out-Null
|
||||||
Export-ScheduledTask -TaskName $name | Set-Content -Encoding UTF8 "$backup\previous-task.xml"
|
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 {
|
try {
|
||||||
Stop-ScheduledTask -TaskName $name
|
Stop-ScheduledTask -TaskName $name
|
||||||
$deadline=[DateTime]::UtcNow.AddSeconds(10)
|
$deadline=[DateTime]::UtcNow.AddSeconds(10)
|
||||||
@@ -72,6 +87,16 @@ if($Apply) {
|
|||||||
if([DateTime]::UtcNow -ge $deadline) { throw 'Old worker did not stop' }
|
if([DateTime]::UtcNow -ge $deadline) { throw 'Old worker did not stop' }
|
||||||
Start-Sleep -Milliseconds 200
|
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
|
Set-ScheduledTask -TaskName $name -Action $action | Out-Null
|
||||||
Start-ScheduledTask -TaskName $name
|
Start-ScheduledTask -TaskName $name
|
||||||
Start-Sleep -Seconds 3
|
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):
|
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"]
|
previous = recipe["base_release"]
|
||||||
if not re.fullmatch("[a-f0-9]{16}", previous):
|
if not re.fullmatch("[a-f0-9]{16}", previous):
|
||||||
raise ValueError("Invalid base release")
|
raise ValueError("Invalid base release")
|
||||||
releases = runtime / "releases"
|
releases = runtime / "releases"
|
||||||
base = releases / ("ai-polygon-" + previous)
|
base = releases / (kind + "-" + previous)
|
||||||
manifest_path = releases / ("ai-polygon-" + previous + ".manifest.json")
|
manifest_path = (
|
||||||
if sha(manifest_path) != recipe["base_manifest_sha256"] or not sha(manifest_path).startswith(
|
base / "release.json"
|
||||||
previous
|
if kind == "semantic-learning"
|
||||||
):
|
else releases / ("ai-polygon-" + previous + ".manifest.json")
|
||||||
|
)
|
||||||
|
if sha(manifest_path) != recipe["base_manifest_sha256"]:
|
||||||
raise ValueError("Base manifest changed")
|
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():
|
for name, digest in before.items():
|
||||||
if sha(confined(base, name)) != digest:
|
if sha(confined(base, name)) != digest:
|
||||||
raise ValueError("Base file changed: " + name)
|
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()}}
|
after = {**before, **{name: hashlib.sha256(raw).hexdigest() for name, raw in overlays.items()}}
|
||||||
encoded = json.dumps(after, sort_keys=True, indent=2).encode()
|
encoded = json.dumps(after, sort_keys=True, indent=2).encode()
|
||||||
identity = hashlib.sha256(encoded).hexdigest()
|
identity = hashlib.sha256(encoded).hexdigest()
|
||||||
target = releases / ("ai-polygon-" + identity[:16])
|
if kind == "semantic-learning":
|
||||||
output_manifest = target.with_suffix(".manifest.json")
|
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():
|
if target.exists() or output_manifest.exists():
|
||||||
raise ValueError("Release already exists; inspect it instead of overwriting")
|
raise ValueError("Release already exists; inspect it instead of overwriting")
|
||||||
temporary = releases / (".staging-" + identity[:16])
|
temporary = releases / (".staging-" + kind + "-" + identity[:16])
|
||||||
temporary.mkdir()
|
temporary.mkdir()
|
||||||
for name, digest in after.items():
|
for name, digest in after.items():
|
||||||
dest = confined(temporary, name)
|
dest = confined(temporary, name)
|
||||||
@@ -80,7 +102,8 @@ def stage(runtime, recipe):
|
|||||||
result = dict(
|
result = dict(
|
||||||
previous=previous,
|
previous=previous,
|
||||||
release=identity[:16],
|
release=identity[:16],
|
||||||
manifest_sha256=identity,
|
manifest_sha256=hashlib.sha256(encoded).hexdigest(),
|
||||||
|
kind=kind,
|
||||||
files=len(after),
|
files=len(after),
|
||||||
changed=sorted(overlays),
|
changed=sorted(overlays),
|
||||||
activated=False,
|
activated=False,
|
||||||
|
|||||||
@@ -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 pathlib import Path
|
||||||
|
|
||||||
from core_client import CoreRequestRejected
|
from core_client import CoreRequestRejected
|
||||||
|
from evidence_closeout import canonical, closeout, usage
|
||||||
from infrastructure_containers import cleanup, docker, run_container
|
from infrastructure_containers import cleanup, docker, run_container
|
||||||
from infrastructure_gaussian_sources import prepare_native
|
from infrastructure_gaussian_sources import prepare_native
|
||||||
from infrastructure_pipeline import MODULE, run_pipeline
|
from infrastructure_pipeline import MODULE, run_pipeline
|
||||||
@@ -84,9 +85,24 @@ def reconcile(client, marker, hello=None):
|
|||||||
)
|
)
|
||||||
record.pop("completion")
|
record.pop("completion")
|
||||||
write_json(marker, record)
|
write_json(marker, record)
|
||||||
registered_request(
|
if not record.get("released"):
|
||||||
client, endpoint, dict(action="release", previous_owner=record["owner"]), hello=hello
|
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()
|
marker.unlink()
|
||||||
|
|
||||||
|
|
||||||
@@ -112,18 +128,36 @@ def prepare_infrastructure(client, row, state, marker, hello=None):
|
|||||||
if row["identity"]["provider_sha256"] != provider_identity():
|
if row["identity"]["provider_sha256"] != provider_identity():
|
||||||
raise ValueError("Infrastructure provider changed")
|
raise ValueError("Infrastructure provider changed")
|
||||||
runtime = state.parent
|
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)
|
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"]
|
endpoint = "/worker/infrastructure-analysis/" + row["key"]
|
||||||
last_pulse = -float("inf")
|
last_pulse = -float("inf")
|
||||||
connected = True
|
connected = True
|
||||||
|
last_storage_check = -float("inf")
|
||||||
phase = dict(phase="preparing", completed=0, total=0)
|
phase = dict(phase="preparing", completed=0, total=0)
|
||||||
|
|
||||||
def pulse():
|
def pulse():
|
||||||
nonlocal last_pulse, phase, connected
|
nonlocal last_pulse, phase, connected, last_storage_check
|
||||||
if time.monotonic() - last_pulse < 3:
|
if time.monotonic() - last_pulse < 3:
|
||||||
return
|
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"
|
progress = output / "progress.json"
|
||||||
if progress.exists():
|
if progress.exists():
|
||||||
with contextlib.suppress(ValueError, OSError):
|
with contextlib.suppress(ValueError, OSError):
|
||||||
@@ -139,6 +173,23 @@ def prepare_infrastructure(client, row, state, marker, hello=None):
|
|||||||
last_pulse = time.monotonic()
|
last_pulse = time.monotonic()
|
||||||
|
|
||||||
try:
|
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:
|
if shutil.disk_usage(output).free < profile["minimum_free_gib"] * 1024**3:
|
||||||
raise RuntimeError("Insufficient space for Gaussian analysis results")
|
raise RuntimeError("Insufficient space for Gaussian analysis results")
|
||||||
pulse()
|
pulse()
|
||||||
@@ -182,7 +233,13 @@ def prepare_infrastructure(client, row, state, marker, hello=None):
|
|||||||
write_json(marker, record)
|
write_json(marker, record)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logging.exception("Infrastructure analysis failed")
|
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:
|
try:
|
||||||
registered_request(client, endpoint, dict(action="fail"), hello=hello)
|
registered_request(client, endpoint, dict(action="fail"), hello=hello)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|||||||
@@ -272,8 +272,11 @@ def review_index(root):
|
|||||||
|
|
||||||
|
|
||||||
class Store:
|
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.root, self.quota, self.reserve = Path(root), quota, reserve
|
||||||
|
self.research_quota = research_quota
|
||||||
self.root.mkdir(parents=True, exist_ok=True)
|
self.root.mkdir(parents=True, exist_ok=True)
|
||||||
for folder in ("inbox", "datasets", "work", "sources", "logs"):
|
for folder in ("inbox", "datasets", "work", "sources", "logs"):
|
||||||
(self.root / folder).mkdir(exist_ok=True)
|
(self.root / folder).mkdir(exist_ok=True)
|
||||||
@@ -286,7 +289,26 @@ class Store:
|
|||||||
self.db.commit()
|
self.db.commit()
|
||||||
|
|
||||||
def capacity(self, additional):
|
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 (
|
if (
|
||||||
used + additional > self.quota
|
used + additional > self.quota
|
||||||
or shutil.disk_usage(self.root).free < self.reserve + additional
|
or shutil.disk_usage(self.root).free < self.reserve + additional
|
||||||
|
|||||||
@@ -9,5 +9,9 @@
|
|||||||
"producer_data": "D:/NDC_GAUSSIAN_PIPELINE/data",
|
"producer_data": "D:/NDC_GAUSSIAN_PIPELINE/data",
|
||||||
"sevenzip": "C:/Program Files/7-Zip/7z.exe",
|
"sevenzip": "C:/Program Files/7-Zip/7z.exe",
|
||||||
"splat_transform": "tools/splat-transform-3.4.0/node_modules/@playcanvas/splat-transform/bin/cli.mjs",
|
"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
|
||||||
|
}
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ def provider_identity():
|
|||||||
root / ("simulation/ai-polygon/" + n + ".py")
|
root / ("simulation/ai-polygon/" + n + ".py")
|
||||||
for n in (
|
for n in (
|
||||||
"infrastructure_preparer",
|
"infrastructure_preparer",
|
||||||
|
"evidence_closeout",
|
||||||
"infrastructure_transport",
|
"infrastructure_transport",
|
||||||
"infrastructure_sources",
|
"infrastructure_sources",
|
||||||
"infrastructure_survey_cache",
|
"infrastructure_survey_cache",
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import importlib.util
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
spec = importlib.util.spec_from_file_location(
|
||||||
|
"compact", Path(__file__).parents[1] / "scripts/compact_closed_evidence.py"
|
||||||
|
)
|
||||||
|
m = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(m)
|
||||||
|
|
||||||
|
|
||||||
|
def fixture(tmp_path, monkeypatch):
|
||||||
|
root = tmp_path / "closed"
|
||||||
|
root.mkdir()
|
||||||
|
store = tmp_path / "cas"
|
||||||
|
for name in ["first.npz", "second.npz"]:
|
||||||
|
(root / name).write_bytes(b"abcd" * 20000)
|
||||||
|
(root / "original.ply").write_bytes(b"abcd" * 20000)
|
||||||
|
monkeypatch.setattr(m.shutil, "disk_usage", lambda p: SimpleNamespace(free=1000 * 1024**3))
|
||||||
|
return root, store
|
||||||
|
|
||||||
|
|
||||||
|
def test_aliases_preserve_bytes_and_restore_independent_copy(tmp_path, monkeypatch):
|
||||||
|
root, store = fixture(tmp_path, monkeypatch)
|
||||||
|
plan = m.plan([root], store)
|
||||||
|
assert plan["duplicate_bytes"] == 80000
|
||||||
|
m.apply(plan)
|
||||||
|
first, second = root / "first.npz", root / "second.npz"
|
||||||
|
assert first.samefile(second) and first.read_bytes() == b"abcd" * 20000
|
||||||
|
assert not (root / "original.ply").samefile(first)
|
||||||
|
row = next(x for x in plan["groups"][0] if x["path"] == str(first))
|
||||||
|
blob = next(store.glob("*.blob"))
|
||||||
|
restored = m.restore_alias(row, blob, tmp_path / "restored.npz")
|
||||||
|
assert not restored.samefile(second)
|
||||||
|
assert first.samefile(second)
|
||||||
|
restored.write_bytes(b"changed")
|
||||||
|
assert second.read_bytes() == b"abcd" * 20000
|
||||||
|
|
||||||
|
|
||||||
|
def test_changed_candidate_refuses_group_before_replacement(tmp_path, monkeypatch):
|
||||||
|
root, store = fixture(tmp_path, monkeypatch)
|
||||||
|
plan = m.plan([root], store)
|
||||||
|
(root / "second.npz").write_bytes(b"changed")
|
||||||
|
with pytest.raises(ValueError, match="changed"):
|
||||||
|
m.apply(plan)
|
||||||
|
assert (root / "first.npz").stat().st_nlink == 1
|
||||||
|
assert (root / "second.npz").read_bytes() == b"changed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_restore_refuses_permissions_drift(tmp_path, monkeypatch):
|
||||||
|
root, store = fixture(tmp_path, monkeypatch)
|
||||||
|
document = m.plan([root], store)
|
||||||
|
m.apply(document)
|
||||||
|
blob = next(store.glob("*.blob"))
|
||||||
|
blob.chmod(0o600)
|
||||||
|
with pytest.raises(ValueError, match="matches"):
|
||||||
|
m.restore_alias(document["groups"][0][0], blob, tmp_path / "restored")
|
||||||
|
assert not (tmp_path / "restored").exists()
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
SPEC = importlib.util.spec_from_file_location(
|
||||||
|
"evidence_closeout", Path(__file__).parents[1] / "simulation/ai-polygon/evidence_closeout.py"
|
||||||
|
)
|
||||||
|
evidence = importlib.util.module_from_spec(SPEC)
|
||||||
|
SPEC.loader.exec_module(evidence)
|
||||||
|
|
||||||
|
|
||||||
|
def setup(tmp_path):
|
||||||
|
job, store = tmp_path / "job", tmp_path / "archives"
|
||||||
|
job.mkdir()
|
||||||
|
(job / "urban-map.json").write_text('{"features":[]}')
|
||||||
|
(job / "observations.bin").write_bytes(b"preserved observations" * 1000)
|
||||||
|
return job, store
|
||||||
|
|
||||||
|
|
||||||
|
def test_lossless_closeout_keeps_map_and_restores_exact_source(tmp_path):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
original = (job / "observations.bin").read_bytes()
|
||||||
|
result = evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||||
|
assert result["phase"] == "complete"
|
||||||
|
assert (job / "urban-map.json").exists()
|
||||||
|
assert not (job / "observations.bin").exists()
|
||||||
|
target = tmp_path / "restored.bin"
|
||||||
|
evidence.restore_file(store / "job-1/closeout.json", "observations.bin", target)
|
||||||
|
assert target.read_bytes() == original
|
||||||
|
assert evidence.closeout(job, store, "job-1", reserve=0) == result
|
||||||
|
|
||||||
|
|
||||||
|
def test_capacity_refusal_preserves_every_input(tmp_path):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
with pytest.raises(RuntimeError, match="quota"):
|
||||||
|
evidence.closeout(job, store, "job-1", limit=10, reserve=0)
|
||||||
|
assert (job / "observations.bin").exists()
|
||||||
|
assert not (store / "job-1/evidence.zip").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_link_and_pin_refused_without_removal(tmp_path):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
(job / "RETAIN.json").write_text("{}")
|
||||||
|
with pytest.raises(ValueError, match="pinned"):
|
||||||
|
evidence.closeout(job, store, "job-1", reserve=0)
|
||||||
|
(job / "RETAIN.json").unlink()
|
||||||
|
(job / "linked").symlink_to(tmp_path / "elsewhere")
|
||||||
|
with pytest.raises((ValueError, FileNotFoundError)):
|
||||||
|
evidence.closeout(job, store, "job-1", reserve=0)
|
||||||
|
assert (job / "observations.bin").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_crash_after_unlink_reconciles_only_journaled_path(tmp_path, monkeypatch):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
original = Path.unlink
|
||||||
|
|
||||||
|
def interrupted(path, *args, **kwargs):
|
||||||
|
original(path, *args, **kwargs)
|
||||||
|
if path == job / "observations.bin":
|
||||||
|
raise OSError("lost acknowledgement")
|
||||||
|
|
||||||
|
monkeypatch.setattr(Path, "unlink", interrupted)
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||||
|
monkeypatch.setattr(Path, "unlink", original)
|
||||||
|
assert evidence.closeout(job, store, "job-1", reserve=0)["phase"] == "complete"
|
||||||
|
|
||||||
|
|
||||||
|
def test_changed_source_and_corrupt_archive_are_preserved(tmp_path, monkeypatch):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
original = Path.unlink
|
||||||
|
|
||||||
|
def interrupted(path, *args, **kwargs):
|
||||||
|
if path == job / "observations.bin":
|
||||||
|
raise OSError("interrupted")
|
||||||
|
return original(path, *args, **kwargs)
|
||||||
|
|
||||||
|
monkeypatch.setattr(Path, "unlink", interrupted)
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||||
|
monkeypatch.setattr(Path, "unlink", original)
|
||||||
|
(job / "observations.bin").write_bytes(b"new evidence")
|
||||||
|
with pytest.raises(ValueError, match="changed after"):
|
||||||
|
evidence.closeout(job, store, "job-1", reserve=0)
|
||||||
|
assert (job / "observations.bin").read_bytes() == b"new evidence"
|
||||||
|
(store / "job-1/evidence.zip").write_bytes(b"broken")
|
||||||
|
with pytest.raises(ValueError, match="checksum"):
|
||||||
|
evidence.closeout(job, store, "job-1", reserve=0)
|
||||||
|
assert (job / "observations.bin").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_root_link_and_control_link_are_rejected(tmp_path):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
link = tmp_path / "job-alias"
|
||||||
|
link.symlink_to(job, target_is_directory=True)
|
||||||
|
with pytest.raises(ValueError, match="Linked"):
|
||||||
|
evidence.closeout(link, store, "job-1", reserve=0)
|
||||||
|
store.mkdir(exist_ok=True)
|
||||||
|
(store / "job-1").symlink_to(job, target_is_directory=True)
|
||||||
|
with pytest.raises(ValueError, match="Linked"):
|
||||||
|
evidence.closeout(job, store, "job-1", reserve=0)
|
||||||
|
assert (job / "observations.bin").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_resume_honors_new_pin_and_capacity(tmp_path, monkeypatch):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
original = evidence.zipfile.ZipFile
|
||||||
|
monkeypatch.setattr(
|
||||||
|
evidence.zipfile, "ZipFile", lambda *a, **kw: (_ for _ in ()).throw(OSError("interrupt"))
|
||||||
|
)
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
evidence.closeout(job, store, "job-1", reserve=0)
|
||||||
|
monkeypatch.setattr(evidence.zipfile, "ZipFile", original)
|
||||||
|
with pytest.raises(RuntimeError, match="quota"):
|
||||||
|
evidence.closeout(job, store, "job-1", limit=1, reserve=0)
|
||||||
|
(job / "RETAIN.json").write_text("{}")
|
||||||
|
with pytest.raises(ValueError, match="pinned"):
|
||||||
|
evidence.closeout(job, store, "job-1", reserve=0)
|
||||||
|
assert (job / "observations.bin").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_complete_retry_repairs_missing_archive_locator(tmp_path):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
evidence.closeout(job, store, "job-1", reserve=0)
|
||||||
|
(job / "ARCHIVED.json").unlink()
|
||||||
|
evidence.closeout(job, store, "job-1", reserve=0)
|
||||||
|
assert json.loads((job / "ARCHIVED.json").read_text())["owner"] == "job-1"
|
||||||
|
|
||||||
|
|
||||||
|
def test_partial_final_journal_record_is_recovered(tmp_path, monkeypatch):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
original = Path.unlink
|
||||||
|
|
||||||
|
def interrupted(path, *args, **kw):
|
||||||
|
original(path, *args, **kw)
|
||||||
|
if path == job / "observations.bin":
|
||||||
|
raise OSError("crash")
|
||||||
|
|
||||||
|
monkeypatch.setattr(Path, "unlink", interrupted)
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||||
|
monkeypatch.setattr(Path, "unlink", original)
|
||||||
|
with (store / "job-1/deletions.jsonl").open("ab") as f:
|
||||||
|
f.write(b'{"action":"rem')
|
||||||
|
assert evidence.closeout(job, store, "job-1", reserve=0)["phase"] == "complete"
|
||||||
|
|
||||||
|
|
||||||
|
def test_published_archive_before_state_commit_resumes_without_second_budget(tmp_path, monkeypatch):
|
||||||
|
job, store = setup(tmp_path)
|
||||||
|
original = evidence.atomic_json
|
||||||
|
|
||||||
|
def interrupted(path, value):
|
||||||
|
if path.name == "closeout.json" and value.get("phase") == "archived":
|
||||||
|
raise OSError("crash after zip publish")
|
||||||
|
return original(path, value)
|
||||||
|
|
||||||
|
monkeypatch.setattr(evidence, "atomic_json", interrupted)
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
evidence.closeout(job, store, "job-1", keep=("urban-map.json",), reserve=0)
|
||||||
|
monkeypatch.setattr(evidence, "atomic_json", original)
|
||||||
|
assert evidence.closeout(job, store, "job-1", limit=1, reserve=0)["phase"] == "complete"
|
||||||
@@ -246,3 +246,33 @@ def test_source_read_retries_transport_only(preparer):
|
|||||||
"source": "verified"
|
"source": "verified"
|
||||||
}
|
}
|
||||||
assert len(calls) == 5
|
assert len(calls) == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_closeout_failure_retains_released_marker_until_retry(preparer, monkeypatch, tmp_path):
|
||||||
|
marker, output = outbox(preparer, monkeypatch, tmp_path)
|
||||||
|
record = preparer.read_json(marker)
|
||||||
|
record["retention"] = dict(
|
||||||
|
root=str(output), archive_root=str(tmp_path / "archives"), archive_limit=1024**3, reserve=0
|
||||||
|
)
|
||||||
|
preparer.write_json(marker, record)
|
||||||
|
actions = []
|
||||||
|
|
||||||
|
class Client:
|
||||||
|
def request(self, path, body):
|
||||||
|
actions.append(body["action"])
|
||||||
|
return {}
|
||||||
|
|
||||||
|
close = preparer.closeout
|
||||||
|
monkeypatch.setattr(
|
||||||
|
preparer, "closeout", lambda *a, **kw: (_ for _ in ()).throw(OSError("archive unavailable"))
|
||||||
|
)
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
preparer.reconcile(Client(), marker)
|
||||||
|
assert preparer.read_json(marker)["released"] is True
|
||||||
|
assert (output / "urban-map.json").exists()
|
||||||
|
monkeypatch.setattr(preparer, "closeout", close)
|
||||||
|
preparer.reconcile(Client(), marker)
|
||||||
|
assert actions == ["complete", "release"]
|
||||||
|
assert not marker.exists()
|
||||||
|
assert (output / "urban-map.json").exists()
|
||||||
|
assert (output / "ARCHIVED.json").exists()
|
||||||
|
|||||||
@@ -168,3 +168,19 @@ def test_complete_collection_receipt_keeps_identity_and_terminal_invariants(tmp_
|
|||||||
assert edits.get(world)["learning"]["state"] == "draft-ready"
|
assert edits.get(world)["learning"]["state"] == "draft-ready"
|
||||||
with pytest.raises(RuntimeError):
|
with pytest.raises(RuntimeError):
|
||||||
edits.receipt(world, saved["revision"], {**receipt, "sample_count": 212})
|
edits.receipt(world, saved["revision"], {**receipt, "sample_count": 212})
|
||||||
|
|
||||||
|
|
||||||
|
def test_research_and_dataset_budgets_are_separate_and_bounded(tmp_path):
|
||||||
|
worker = ds.Store(tmp_path / "worker", quota=65536, reserve=0, research_quota=1024)
|
||||||
|
(worker.root / "experiments").mkdir()
|
||||||
|
(worker.root / "experiments/history.bin").write_bytes(b"x" * 1024)
|
||||||
|
worker.capacity(0)
|
||||||
|
(worker.root / "experiments/history.bin").write_bytes(b"x" * 1025)
|
||||||
|
with pytest.raises(RuntimeError, match="research storage"):
|
||||||
|
worker.capacity(0)
|
||||||
|
(worker.root / "experiments/history.bin").unlink()
|
||||||
|
(worker.root / "unknown-new-directory").mkdir()
|
||||||
|
(worker.root / "unknown-new-directory/data.bin").write_bytes(b"x" * 65536)
|
||||||
|
with pytest.raises(RuntimeError, match="learning storage"):
|
||||||
|
worker.capacity(0)
|
||||||
|
worker.db.close()
|
||||||
|
|||||||
@@ -62,3 +62,37 @@ def test_corrupted_predecessor_refuses_before_staging(tmp_path):
|
|||||||
def test_escape_rejected(tmp_path, path):
|
def test_escape_rejected(tmp_path, path):
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
module.confined(tmp_path, path)
|
module.confined(tmp_path, path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_learning_patch_keeps_image_and_unrelated_payload(tmp_path):
|
||||||
|
before = {
|
||||||
|
"dataset_store.py": hashlib.sha256(b"old").hexdigest(),
|
||||||
|
"templates.json": hashlib.sha256(b"templates").hexdigest(),
|
||||||
|
}
|
||||||
|
identity = hashlib.sha256(json.dumps(before, sort_keys=True).encode()).hexdigest()
|
||||||
|
base = tmp_path / "releases" / ("semantic-learning-" + identity[:16])
|
||||||
|
base.mkdir(parents=True)
|
||||||
|
(base / "dataset_store.py").write_bytes(b"old")
|
||||||
|
(base / "templates.json").write_bytes(b"templates")
|
||||||
|
manifest = {"id": identity, "files": before, "image": "pinned-image", "schema_version": "v1"}
|
||||||
|
encoded = json.dumps(manifest).encode()
|
||||||
|
(base / "release.json").write_bytes(encoded)
|
||||||
|
recipe = dict(
|
||||||
|
kind="semantic-learning",
|
||||||
|
base_release=identity[:16],
|
||||||
|
base_manifest_sha256=hashlib.sha256(encoded).hexdigest(),
|
||||||
|
overlays={
|
||||||
|
"dataset_store.py": dict(
|
||||||
|
base64=base64.b64encode(b"new").decode(), sha256=hashlib.sha256(b"new").hexdigest()
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
result = module.stage(tmp_path, recipe)
|
||||||
|
target = tmp_path / "releases" / ("semantic-learning-" + result["release"])
|
||||||
|
after = json.loads((target / "release.json").read_text())
|
||||||
|
assert (
|
||||||
|
after["image"] == "pinned-image"
|
||||||
|
and after["files"]["templates.json"] == before["templates.json"]
|
||||||
|
)
|
||||||
|
assert (base / "dataset_store.py").read_bytes() == b"old"
|
||||||
|
assert (target / "dataset_store.py").read_bytes() == b"new"
|
||||||
|
|||||||
Reference in New Issue
Block a user