feat(research): preserve urban geometry pipelines and qualification suites

Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 5d56237124
commit 69dc566665
611 changed files with 52016 additions and 28 deletions
@@ -0,0 +1,40 @@
# Pipeline evaluation
This directory evaluates the existing detector. It is not another detector
stage and is deliberately absent from `pipeline/definition.json`.
`ablation.py` validates a counterfactual tail, rejects omitted producers named
in explicit `input_files`, compares all feature geometry/properties, and checks
source/location leakage. Existing implicit alias inputs still require inspection
and the actual runtime replay; this is not a complete static dependency proof.
`geometry_metrics.py` reports descriptive geometry and class-wise differences.
Neither module calls unchanged output "accurate", or a feature-count increase
"recall". Precision and recall require independently annotated observations.
For an omission experiment, freeze the installed source manifest, source images,
initial map, model/container versions and experiment matrix. Run a control and
each omission from the same prefix. Rerun every retained downstream stage,
including semantic proposals: do not read a removed producer's prior artifacts
or replay a candidate over the already accepted final map. Record actual mounts,
per-stage wall time, exact feature changes and a visual review of differences.
Immutable images before the cut may be shared read-only. Source hashes and
queue/container ownership follow the normal Worker006 contract.
The nine locations previously used to develop this pipeline remain development
data. Additional segments of the same street are transfer checks, not an
independent street holdout. Keep every segment of a held-out street in the same
split. Select the candidate before reviewing its holdout output. Annotate
visible reference objects from Gaussian images independently; ambiguous and
unobserved areas have their own labels and do not become empty ground. If a
holdout result influences tuning, retire that holdout into development.
Report missed/labeled objects, false positives, position/shape error, unexpected
overlaps and observed-boundary continuity separately. Open ends at the survey
boundary are valid. Report processing cost alongside quality; do not infer peak
memory from wall time. A globally empty change on one scene does not establish
that a module is redundant on other scenes.
Current frozen study: `pipeline-ablation-20261015T152212Z` under the canonical
`.runtime/simulation-qualifications/` and `outputs/`. Its local manifests record
the exact experiment matrix, data split and acceptance rules. Production maps
remain unchanged until a candidate passes the declared comparisons.
@@ -0,0 +1,71 @@
"""Counterfactual plans and exact feature comparisons, without model dependencies.
An unchanged map is evidence of preservation on that input, never recall or
generalization. Every retained stage after the first omission must be rerun.
"""
import hashlib
import json
def digest(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False,
separators=(',', ':')).encode()).hexdigest()
def features(document):
result = {f['id']: f for f in document['features']}
if len(result) != len(document['features']):
raise ValueError('Duplicate feature identity')
digest(result) # Reject NaN, including unchanged invalid input.
return result
def compare(reference, candidate):
a, b = features(reference), features(candidate)
shared = a.keys() & b.keys()
changed = sorted(k for k in shared if a[k] != b[k])
nonmarking = lambda fs: {k: v for k, v in fs.items()
if v['properties']['class'] != 'road_marking'}
return dict(features_equal=a == b, reference_features=len(a),
candidate_features=len(b), added_ids=sorted(b.keys() - a.keys()),
removed_ids=sorted(a.keys() - b.keys()), changed_ids=changed,
non_marking_equal=nonmarking(a) == nonmarking(b),
reference_sha256=digest(a), candidate_sha256=digest(b),
recall_measured=False, accuracy_measured=False)
def tail_plan(definition, start, omitted):
groups = definition['groups']
names = [g['group'] for g in groups]
if len(names) != len(set(names)) or start not in names:
raise ValueError('Invalid group definition/start')
omitted = set(omitted)
tail = groups[names.index(start):]
if not omitted <= {g['group'] for g in tail}:
raise ValueError('Omission outside replay tail')
# Explicit named inputs cannot silently fall back to frozen artifacts of a
# removed producer. Implicit alias consumers are additionally reviewed by
# the frozen input manifest and the read-only mount census.
for group in tail:
if group['group'] in omitted:
continue
dependencies = set(group.get('input_files', {}).values())
if group.get('extra_coverage'):
dependencies.add(group['extra_coverage'])
if dependencies & omitted:
raise ValueError('Removed named producer: ' + group['group'])
return dict(start=start, omitted=sorted(omitted),
groups=[g['group'] for g in tail if g['group'] not in omitted],
stages=sum(len(g['stages']) for g in tail if g['group'] not in omitted),
skipped_stages=sum(len(g['stages']) for g in tail if g['group'] in omitted),
downstream_cache_reuse=False)
def validate_split(development, holdout):
"""Reject exact-source and same-location leakage, not just duplicate IDs."""
for key in ('source_sha256', 'location_group'):
if any(not x.get(key) for x in development + holdout):
raise ValueError('Missing split provenance: ' + key)
if {x[key] for x in development} & {x[key] for x in holdout}:
raise ValueError('Evaluation leakage: ' + key)
return True
@@ -0,0 +1,65 @@
"""Summarize external observations without treating sampling as kernel timing."""
import argparse
import json
import statistics
from collections import defaultdict
from contextlib import suppress
from pathlib import Path
def analyze(root):
summary = json.loads((root / "summary.json").read_text())
profile = summary["execution_profile"]
observations = defaultdict(list)
for line in (root / "resource-samples.jsonl").read_text().splitlines():
row = json.loads(line)
if row["same_phase_at_completion"] and row["docker"]:
stats = json.loads(row["docker"])
observations[row["phase"]].append((row, stats))
stages = []
for stage in profile["stages"]:
rows = observations[stage["phase"]]
cpu = [float(stats["CPUPerc"].removesuffix("%")) for _, stats in rows]
gpu = []
for row, _ in rows:
if row["gpu_host_csv"]:
fields = row["gpu_host_csv"].splitlines()[0].split(",")
with suppress(ValueError, IndexError):
gpu.append(float(fields[1]))
stages.append(
dict(
**stage,
samples=len(rows),
cpu_core_equivalents_median=statistics.median(cpu) / 100 if cpu else None,
gpu_host_utilization_median=statistics.median(gpu) if gpu else None,
)
)
wall = summary["wall_seconds"]
stage_total = sum(s["seconds"] for s in stages)
return dict(
schema="missioncore.execution-profile-analysis/v1",
wall_seconds=wall,
stage_seconds=stage_total,
outside_stage_seconds=wall - stage_total,
completed_stages=summary["completed_stages"],
orchestration_hashes=profile["orchestration_hashes"],
sampler_stopped=profile["sampler_stopped"],
errors=profile["errors"],
caveats=[
"GPU utilization is host-wide and includes durable operator services.",
"Docker BlockIO can omit Windows bind-mount I/O; zero is not proof of no disk work.",
"Resource samples locate bottlenecks but are not CPU/GPU kernel timing.",
"Fresh scene analysis retains the normal shared model/compiler and OS caches.",
"The full execution timer excludes queue wait and engineering preflight.",
],
stages=stages,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("root", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
args.output.write_text(json.dumps(analyze(args.root), indent=2))
@@ -0,0 +1,107 @@
"""Bounded A/B serialization benchmark on frozen semantic observations.
No inference, geometry, sampling, dtype conversion, or acceptance is performed.
Each pair receives the same arrays. Read-back compares complete uncompressed
NPY members, including dtype, shape, layout, signed zeros and NaN payloads.
Only owned temporary output archives are removed. Inputs are read-only.
"""
import argparse
import hashlib
import json
import time
import zipfile
from pathlib import Path
import numpy as np
from array_archive import save
def members(path):
with zipfile.ZipFile(path) as archive:
return [(n, hashlib.sha256(archive.read(n)).hexdigest()) for n in archive.namelist()]
def run(reference, output, limit=None):
output.mkdir(exist_ok=False)
index = json.loads((reference / "ortho/survey/tile-index.json").read_text())
tiles = [t["id"] for t in index["tiles"] if t["status"] == "surveyed"]
paths = []
for tile in tiles:
paths.extend(
reference / f"ortho/evidence/{tile}.{kind}.npz" for kind in ["normal", "ground"]
)
paths.extend(
reference / f"ortho/evidence/road-prompt/{tile}.{kind}.npz"
for kind in ["normal", "ground"]
)
paths.append(reference / f"full_plan/evidence/{tile}.npz")
if limit is not None:
paths = paths[:limit]
rows = []
for i, source in enumerate(paths):
with np.load(source, allow_pickle=False) as archive:
arrays = {key: archive[key] for key in archive.files}
expected = members(source)
row = dict(
path=source.relative_to(reference).as_posix(),
source_sha256=hashlib.sha256(source.read_bytes()).hexdigest(),
array_bytes=sum(a.nbytes for a in arrays.values()),
trials=[],
)
for repeat in range(2):
# Balance ordering; OS/file cache state is shared, never flushed.
order = ["legacy", "level1"] if (i + repeat) % 2 == 0 else ["level1", "legacy"]
for kind in order:
target = output / (kind + ".npz")
begin = time.perf_counter()
(np.savez_compressed if kind == "legacy" else save)(target, **arrays)
write_seconds = time.perf_counter() - begin
begin = time.perf_counter()
actual = members(target)
verify_seconds = time.perf_counter() - begin
assert actual == expected, f"Serialized observation changed: {source}, {kind}"
row["trials"].append(
dict(
kind=kind,
repeat=repeat,
write_seconds=write_seconds,
read_verify_seconds=verify_seconds,
bytes=target.stat().st_size,
npy_payloads_exact=True,
)
)
target.unlink()
rows.append(row)
print("ARCHIVE", i + 1, "/", len(paths), row["path"], flush=True)
totals = {}
for kind in ["legacy", "level1"]:
selected = [t for r in rows for t in r["trials"] if t["kind"] == kind]
totals[kind] = {
key: sum(t[key] for t in selected) / 2
for key in ["write_seconds", "read_verify_seconds", "bytes"]
}
report = dict(
schema="missioncore.array-serialization-benchmark/v1",
observation_files=len(rows),
survey_tiles=len(tiles),
scope="five semantic archives per structural survey tile; coverage carry excluded",
repeats=2,
complete_survey=limit is None,
frozen_observations=True,
cold_pipeline=False,
numeric_operations_changed=False,
totals=totals,
rows=rows,
)
(output / "report.json").write_text(json.dumps(report, indent=2))
return report
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("reference", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--limit", type=int)
args = parser.parse_args()
print(json.dumps(run(args.reference, args.output, args.limit)["totals"]), flush=True)
@@ -0,0 +1,157 @@
"""Compare completed runs without tolerances or deserializing numeric arrays.
NPZ/GZIP containers may carry different packaging metadata. Their uncompressed
members must still match byte for byte, including dtype, layout and float bits.
This is equivalence to a baseline, not a claim of ground-truth accuracy.
"""
import argparse
import gzip
import hashlib
import json
import zipfile
from pathlib import Path
def stream_digest(stream):
digest = hashlib.sha256()
size = 0
while block := stream.read(1024 * 1024):
digest.update(block)
size += len(block)
return digest.hexdigest(), size
def file_digest(path):
with path.open("rb") as stream:
return stream_digest(stream)[0]
def payload_digest(path):
if path.suffix == ".npz":
with zipfile.ZipFile(path) as archive:
names = archive.namelist()
if len(names) != len(set(names)):
raise ValueError("Duplicate NPZ member")
if sum(i.file_size for i in archive.infolist()) > 4 * 1024**3:
raise ValueError("Numeric archive exceeds verification envelope")
members = []
for name in names:
if not name.endswith(".npy"):
raise ValueError("Unexpected NPZ member")
with archive.open(name) as stream:
members.append((name, stream_digest(stream)))
return members
if path.suffix == ".gz":
with gzip.open(path, "rb") as stream:
return stream_digest(stream)
return file_digest(path)
def inventory(root):
paths = sorted(
p for p in root.rglob("*")
if p.is_file() and p.suffix in {".npz", ".npy", ".png", ".gz"}
)
if len(paths) > 5000 or sum(p.stat().st_size for p in paths) > 20 * 1024**3:
raise ValueError("Run exceeds the bounded verification envelope")
if any(p.is_symlink() or not p.resolve().is_relative_to(root.resolve()) for p in paths):
raise ValueError("Evidence path escapes the frozen run")
return {p.relative_to(root).as_posix(): p for p in paths}
def compare(baseline, candidate, expected_baseline, expected_candidate, output):
for root, expected in [(baseline, expected_baseline), (candidate, expected_candidate)]:
assert not (root / "active.json").exists(), "Run is still active"
assert file_digest(root / "summary.json") == expected, "Summary changed"
a = json.loads((baseline / "summary.json").read_text())
b = json.loads((candidate / "summary.json").read_text())
assert a["cold_run"] and b["cold_run"]
assert a["completed_stages"] == b["completed_stages"] == 30
ma = json.loads((baseline / "manifest.json").read_text())
mb = json.loads((candidate / "manifest.json").read_text())
sa, sb = ma["source_files"], mb["source_files"]
changed = sorted(k for k in sa.keys() | sb.keys() if sa.get(k) != sb.get(k))
assert changed == ["simulation/urban-plan-research/systematic/refine_markings.py"], changed
checks = {
"worker_source_exact": ma["worker_sha256"] == mb["worker_sha256"],
"same_release_support": ma["release"] == mb["release"],
"historical_geometry_not_an_input": (
ma["old_geometry_as_input"] is False and mb["old_geometry_as_input"] is False
),
"gaussian_exact": a["gaussian_sha256"] == b["gaussian_sha256"],
"poses_exact": a["poses_sha256"] == b["poses_sha256"],
"final_map_file_exact": a["final_map_sha256"] == b["final_map_sha256"],
"final_map_content_exact": a["final_map"] == b["final_map"],
"same_stage_resources": [
(r["phase"], r["resources"], r["gpu"])
for r in a["execution_profile"]["stages"]
] == [
(r["phase"], r["resources"], r["gpu"])
for r in b["execution_profile"]["stages"]
],
}
left, right = inventory(baseline / "run"), inventory(candidate / "run")
assert left and right, "No numeric or image evidence to compare"
checks["same_numeric_and_image_inventory"] = left.keys() == right.keys()
rows = []
for name in sorted(left.keys() & right.keys()):
ah, bh = file_digest(left[name]), file_digest(right[name])
row = dict(path=name, baseline_sha256=ah, candidate_sha256=bh, file_exact=ah == bh)
row["payload_exact"] = row["file_exact"] or (
payload_digest(left[name]) == payload_digest(right[name])
)
rows.append(row)
if len(rows) % 200 == 0:
print("EVIDENCE_COMPARED", len(rows), "/", len(left), flush=True)
checks["all_numeric_and_image_payloads_exact"] = all(r["payload_exact"] for r in rows)
json_checks = {}
for name in [
"primary_search/observations.json",
"primary_search/search-proposals.json",
"primary_search/symbol-patches.json",
"marking_pass/full-map.json",
"marking_pass/marking-rows.json",
"marking_pass/finite-stroke-admission.json",
"marking_pass/configuration-bank.json",
]:
pa, pb = baseline / "run" / name, candidate / "run" / name
assert pa.is_file() and pb.is_file(), name
json_checks[name] = file_digest(pa) == file_digest(pb)
checks["decisions_and_primary_manifests_exact"] = all(json_checks.values())
report = dict(
schema="missioncore.frozen-full-run-equivalence/v1",
baseline=baseline.name,
candidate=candidate.name,
baseline_summary_sha256=expected_baseline,
candidate_summary_sha256=expected_candidate,
changed_sources=changed,
checks=checks,
json_artifacts=json_checks,
artifact_count=len(rows),
baseline_artifact_bytes=sum(p.stat().st_size for p in left.values()),
packaging_only_differences=[
r["path"] for r in rows if not r["file_exact"] and r["payload_exact"]
],
payload_differences=[r["path"] for r in rows if not r["payload_exact"]],
artifacts=rows,
accuracy_or_recall_measured=False,
passed=all(checks.values()),
)
output.write_text(json.dumps(report, indent=2))
assert report["passed"], "Frozen runs differ; inspect the evidence report"
return report
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("baseline", type=Path)
parser.add_argument("candidate", type=Path)
parser.add_argument("baseline_sha256")
parser.add_argument("candidate_sha256")
parser.add_argument("output", type=Path)
args = parser.parse_args()
result = compare(
args.baseline, args.candidate, args.baseline_sha256, args.candidate_sha256, args.output
)
print("FULL_EQUIVALENCE", result["passed"], result["artifact_count"], flush=True)
@@ -0,0 +1,59 @@
"""Compare cold candidate geometry to an immutable algorithmic control.
The control is not ground truth. Do not label these measurements recall or
precision of the real street. Split/join changes are measured as coverage as
well as object matches; counts alone cannot demonstrate preservation.
"""
from collections import Counter
import hashlib,json,sys
from pathlib import Path
import numpy as np,shapely
from shapely.geometry import shape
def kind(f):
p=f['properties'];return p.get('subtype') if p['class']=='road_marking' else p['class']
def geometry(f):return shapely.force_2d(shape(f['geometry']))
def fraction(a,b,tolerance=0.):
if a.is_empty:return 0.
if a.area>0:return float(a.intersection(b.buffer(tolerance) if tolerance else b).area/a.area)
return float(a.intersection(b.buffer(max(tolerance,1e-7))).length/max(a.length,1e-9))
def compare(control,candidate):
old=control['features'];new=candidate['features'];by_class={};rows=[]
for cls in sorted({kind(f)for f in old+new}):
a=[f for f in old if kind(f)==cls];b=[f for f in new if kind(f)==cls]
A=shapely.union_all([geometry(f)for f in a]);B=shapely.union_all([geometry(f)for f in b]);matches=[]
for f in a:
p=geometry(f);scores=[]
for q in b:
g=geometry(q)
iou=p.intersection(g).area/max(p.union(g).area,1e-9) if p.area else fraction(p,g,.1)
scores.append((iou,q['id'],float(p.hausdorff_distance(g)),float(p.centroid.distance(g.centroid))))
best=max(scores,default=(0,None,None,None));cover=fraction(p,B,.1)
# Symbols stay whole; linear paint may legitimately split or join.
matched=best[0]>=.5 if cls.endswith('_arrow')or cls in {'bicycle','letter_A'} else cover>=.95
record=dict(class_name=cls,id=f['id'],best_iou_or_line_coverage=best[0],best_id=best[1],best_hausdorff_m=best[2],best_centroid_distance_m=best[3],covered_fraction_10cm=cover,covered_fraction_exact=fraction(p,B),matched=matched,bounds_xy=list(p.bounds))
rows.append(record);matches.append(matched)
by_class[cls]=dict(control_objects=len(a),candidate_objects=len(b),matched_control_objects=sum(matches),control_retention_fraction=sum(matches)/len(a)if a else None,control_coverage_exact=fraction(A,B),control_coverage_5cm=fraction(A,B,.05),control_coverage_10cm=fraction(A,B,.1),candidate_coverage_by_control_10cm=fraction(B,A,.1))
def line_quality(doc):
features=[f for f in doc['features']if kind(f)=='linear_marking'];area=0.;sums=Counter();unassessed=0;fully=0
for f in features:
p=geometry(f);area+=p.area;ev=f['properties'].get('linear_support')
if not ev:unassessed+=1;continue
fully+=ev.get('measured_fraction',0)>=.98
for k,v in ev.get('area_fractions',{}).items():sums[k]+=v*p.area
return dict(objects=len(features),fully_measured_objects=fully,unassessed_objects=unassessed,paint_area_m2=area,area_fractions={k:v/max(area,1e-9)for k,v in sums.items()})
invalid=[]
for f in new:
p=shape(f['geometry']);xyz=shapely.get_coordinates(p,include_z=True)
if p.is_empty or not p.is_valid or not np.isfinite(xyz).all():invalid.append(f['id'])
return dict(reference_role='completed previous algorithm; not independently labelled ground truth',thresholds=dict(paint_coverage_tolerance_m=.1,paint_coverage_fraction=.95,whole_symbol_iou=.5),classes=by_class,rows=rows,unmatched_control_ids=[r['id']for r in rows if not r['matched']],invalid_candidate_ids=invalid,duplicate_candidate_ids=[i for i,n in Counter(f['id']for f in new).items()if n>1],control_linear_evidence=line_quality(control),candidate_linear_evidence=line_quality(candidate),complete_recall_measured=False)
def main():
a,b,out=map(Path,sys.argv[1:]);old=json.loads(a.read_text());new=json.loads(b.read_text())
old=old.get('final_map',old);new=new.get('final_map',new)
result=compare(old,new);result['input_sha256']={str(p):hashlib.sha256(p.read_bytes()).hexdigest()for p in[a,b]}
out.write_text(json.dumps(result,indent=2,allow_nan=False));print(json.dumps({k:v for k,v in result.items()if k!='rows'},indent=2))
if __name__=='__main__':main()
@@ -0,0 +1,112 @@
"""Empty-observation end-to-end contracts: exercise every downstream writer/reader."""
from pathlib import Path
import json,shutil,hashlib
def qualify_numeric_invariants(root, modules, marker, profile, run_container):
"""Keep identity and partition invariance mandatory for future candidates."""
checked = []
for name, entry in [
('observed-geometry-identity', 'test_observed_geometry.py'),
('object-evidence-partition', 'test_object_evidence.py'),
]:
assert (modules / 'marking_pass' / entry).is_file(), 'Missing numeric contract: ' + entry
output = root / name
output.mkdir()
run_container(
marker, 'contract-' + name, profile['mapper_image'],
[(modules / 'marking_pass', '/candidate', True), (output, '/out', False)],
['-B', '/candidate/' + entry], output, lambda: None, 60,
gpu=False, executable='python3', readonly=True,
environment=dict(PYTHONPATH='/candidate', OPENBLAS_NUM_THREADS='3', OMP_NUM_THREADS='3'),
)
checked.append(name)
print('CONTRACT_OK', name, flush=True)
return checked
def run(root,definition,modules,original,marker,profile,runtime,release,run_container,write_json):
preflight=root/'contracts';preflight.mkdir();primary=preflight/'primary';primary.mkdir()
empty=preflight/'empty';empty.mkdir();write_json(empty/'full-map.json',dict(type='FeatureCollection',features=[]))
digest=hashlib.sha256((original/'full_plan/fields.npz').read_bytes()).hexdigest()
for name,doc in {
'observations.json':dict(paint=[],crossbars=[]),
'search-proposals.json':dict(lines=[],glyphs=[],source_fields_sha256=digest),
'catalog-proposals.json':dict(glyphs=[],source_fields_sha256=digest),
'arrow-gates.json':[], 'crossing-seeds.json':[],
'symbol-patches.json':dict(patches=[]),
}.items():write_json(primary/name,doc)
write_json(primary/'symbol-semantics.json',dict(records=[],patch_manifest_sha256=hashlib.sha256((primary/'symbol-patches.json').read_bytes()).hexdigest()))
previous=empty;results=[];locations={}
base=next(g for g in definition['groups']if g['group']=='base')
if 'test_initial_views.py'in base['files']:
coverage=preflight/'initial-views';coverage.mkdir()
run_container(marker,'contract-initial-views',profile['mapper_image'],
[(modules/'base','/candidate',True),(coverage,'/out',False)],
['-B','/candidate/test_initial_views.py'],coverage,lambda:None,60,gpu=False,executable='python3',
environment=dict(PYTHONPATH='/candidate',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3'),readonly=True)
results.append('initial-view-cover');print('CONTRACT_OK initial-view-cover',flush=True)
if 'test_survey_index.py'in base['files']:
reader=preflight/'survey-index';reader.mkdir()
run_container(marker,'contract-survey-index',profile['mapper_image'],
[(modules/'base','/candidate',True),(reader,'/out',False)],
['-B','/candidate/test_survey_index.py'],reader,lambda:None,60,gpu=False,executable='python3',
environment=dict(PYTHONPATH='/candidate'),readonly=True)
results.append('survey-manifest-identity');print('CONTRACT_OK survey-manifest-identity',flush=True)
primary_group=next(g for g in definition['groups']if g['group']=='primary_search')
if 'test_connected_ridges.py'in primary_group['files']:
branches=preflight/'connected-ridges';branches.mkdir()
run_container(marker,'contract-connected-ridges',profile['mapper_image'],
[(modules/'primary_search','/candidate',True),(branches,'/out',False)],
['-B','/candidate/test_connected_ridges.py'],branches,lambda:None,60,gpu=False,executable='python3',
environment=dict(PYTHONPATH='/candidate',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3'),readonly=True)
results.append('connected-ridges');print('CONTRACT_OK connected-ridges',flush=True)
continuation=next(g for g in definition['groups']if g['group']=='continuation_pass')
if 'test_shared_surface_edges.py'in continuation['files']:
surface=preflight/'surface-structure';surface.mkdir()
run_container(marker,'contract-shared-surface-edges',profile['mapper_image'],
[(modules/'continuation_pass','/candidate',True),(surface,'/out',False)],
['-B','/candidate/test_shared_surface_edges.py'],surface,lambda:None,60,gpu=False,executable='python3',
environment=dict(PYTHONPATH='/candidate',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3'),readonly=True)
results.append('shared-surface-edges');print('CONTRACT_OK shared-surface-edges',flush=True)
marking=next(g for g in definition['groups']if g['group']=='marking_pass')
if 'test_joint_choice.py'in marking['files']:
joint=preflight/'joint-assembly';joint.mkdir()
run_container(marker,'contract-joint-assembly',profile['mapper_image'],
[(modules/'marking_pass','/candidate',True),(joint,'/out',False)],
['-B','/candidate/test_joint_choice.py'],joint,lambda:None,60,gpu=False,executable='python3',
environment=dict(PYTHONPATH='/candidate',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3'),readonly=True)
results.append('joint-assembly');print('CONTRACT_OK joint-assembly',flush=True)
results.extend(qualify_numeric_invariants(preflight,modules,marker,profile,run_container))
fixture=Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/topdown-writer-queue-20261016101327/maroseyka/observations')
begin=next(i for i,g in enumerate(definition['groups'])if g['group']=='paint_assembly')
for group in definition['groups'][begin:]:
name=group['group'];out=preflight/name;out.mkdir()
if (previous/'crosswalk-standard-check.json').exists():shutil.copyfile(previous/'crosswalk-standard-check.json',out/'crosswalk-standard-check.json')
for stage in group['stages']:
mounts=[(modules/name,'/candidate',True),(previous,'/fullplan',True),(out,'/out',False),
(original/'full_plan','/evidence_plan',True),(original/'ortho/survey','/survey',True),
(original/'ortho','/ortho',True),(primary,'/primary',True),
(primary,'/symbolplan',True),(primary,'/gateplan',True),(primary,'/uniformplan',True),(primary,'/searchplan',True)]
if name=='primary_arrows':
mounts=[m for m in mounts if m[1]not in {'/ortho','/survey'}]
mounts += [(fixture,'/ortho',True),(fixture/'survey','/survey',True),(fixture/'native-geometry','/native_geometry',True)]
if 'primary_arrows'in locations:mounts.append((locations['primary_arrows'],'/primaryarrows',True))
for wheel in (release/'simulation/urban-plan-research/pipeline/vendor').glob('*.whl'):mounts.append((wheel,'/candidate/'+wheel.name,True))
env=dict(PYTHONPATH='/candidate:/candidate/mapping',SCENE='scene',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3',WINDOW_SOURCE='/candidate/linear_window_support.py')
if name=='primary_arrows' and stage==group['stages'][0]:
fixture_mounts=[m for m in mounts if m[1]!='/symbolplan']+[(primary,'/symbolplan',False)]
code="from pathlib import Path;import json,hashlib;from ground_observations import GroundObservations;p=Path('/symbolplan');d=json.loads((p/'symbol-patches.json').read_text());d['observation_snapshot']=GroundObservations().inventory()['snapshot'];(p/'symbol-patches.json').write_text(json.dumps(d));(p/'symbol-semantics.json').write_text(json.dumps(dict(records=[],patch_manifest_sha256=hashlib.sha256((p/'symbol-patches.json').read_bytes()).hexdigest())))"
run_container(marker,'contract-native-fixture',profile['mapper_image'],fixture_mounts,['-B','-c',code],out,lambda:None,180,gpu=False,executable='python3',environment=env,readonly=True)
entry='import runpy;'
if stage=='final_symbol_admission':entry+="import sys;sys.argv=['final_symbol_admission','/fullplan/full-map.json','/candidate/symbol_rules.py','/out'];"
entry+="runpy.run_path('/candidate/"+stage+".py',run_name='__main__')"
run_container(marker,'contract-'+stage,profile['mapper_image'],mounts,['-B','-c',entry],out,lambda:None,180 if name=='primary_arrows' else 60,gpu=False,executable='python3',environment=env,readonly=True)
results.append(stage);print('CONTRACT_OK',stage,flush=True)
if group.get('map_file'):shutil.copyfile(out/group['map_file'],out/'full-map.json')
assert json.loads((out/'full-map.json').read_text())['features']==[]
previous=out;locations[name]=out
write_json(preflight/'contract-fixture.json',dict(native_observations=fixture.as_posix(),read_only=True,scope='empty-observation contracts; not a cold result'))
write_json(preflight/'contract-report.json',dict(passed=True,stages=results,empty_input_remains_empty=True))
return results
@@ -0,0 +1,139 @@
"""Bounded external profiling; never wrap numeric or model operations.
Container CPU/memory/I/O and host GPU utilization are observations, not GPU
kernel timings. Hash timing covers orchestration only. The sampler never
changes entrypoints, environments, resource limits, arrays, cameras or gates.
"""
import datetime
import json
import subprocess
import threading
import time
from collections import Counter
class ExecutionProfile:
def __init__(self, root, pipeline, interval=5.0):
self.root = root
self.pipeline = pipeline
self.interval = interval
self.stages = []
self.hashes = Counter()
self.samples = 0
self.sample_seconds = 0.0
self.errors = Counter()
self.phase = None
self.stop_event = threading.Event()
self.original_run = pipeline.run_container
self.original_checksum = pipeline.checksum
self.thread = None
def start(self):
self.started = time.monotonic()
self.pipeline.run_container = self.run_container
self.pipeline.checksum = self.checksum
self.thread = threading.Thread(target=self.observe, daemon=True)
self.thread.start()
return self
def checksum(self, path):
started = time.monotonic()
result = self.original_checksum(path)
self.hashes["calls"] += 1
self.hashes["bytes"] += path.stat().st_size
self.hashes["seconds"] += time.monotonic() - started
return result
def run_container(self, marker, phase, *args, **kwargs):
record = json.loads(marker.read_text())
name = "ndc-infrastructure-" + record["key"][:16] + "-" + phase
self.phase = (phase, name)
started = time.monotonic()
row = dict(
phase=phase,
started_utc=datetime.datetime.now(datetime.UTC).isoformat(),
started_monotonic=started,
resources=kwargs.get("resources") or dict(cpus=4, memory_gib=16),
gpu=kwargs.get("gpu", True),
passed=False,
)
try:
result = self.original_run(marker, phase, *args, **kwargs)
row["passed"] = True
return result
finally:
row["seconds"] = time.monotonic() - started
self.stages.append(row)
self.phase = None
(self.root / "stage-profile.json").write_text(json.dumps(self.stages, indent=2))
def command(self, args):
try:
result = subprocess.run(args, capture_output=True, text=True, timeout=3)
if result.returncode:
self.errors[args[0] + ":exit"] += 1
return None
return result.stdout.strip()
except (OSError, subprocess.TimeoutExpired):
self.errors[args[0] + ":unavailable"] += 1
return None
def observe(self):
# At most 720 samples and a bounded lifetime, even after a caller error.
with (self.root / "resource-samples.jsonl").open("w") as output:
while self.samples < 720 and not self.stop_event.wait(self.interval):
phase = self.phase
if phase is None:
continue
begin = time.monotonic()
stats = self.command(
["docker", "stats", "--no-stream", "--format", "{{json .}}", phase[1]]
)
gpu = self.command(
[
"nvidia-smi",
"--query-gpu=index,utilization.gpu,utilization.memory,memory.used,power.draw",
"--format=csv,noheader,nounits",
]
)
elapsed = time.monotonic() - begin
output.write(
json.dumps(
dict(
utc=datetime.datetime.now(datetime.UTC).isoformat(),
since_start_seconds=begin - self.started,
phase=phase[0],
same_phase_at_completion=self.phase == phase,
docker=stats,
gpu_host_csv=gpu,
observation_seconds=elapsed,
)
)
+ "\n"
)
output.flush()
self.samples += 1
self.sample_seconds += elapsed
def stop(self):
self.stop_event.set()
if self.thread is not None:
self.thread.join(timeout=10)
self.pipeline.run_container = self.original_run
self.pipeline.checksum = self.original_checksum
report = dict(
schema="missioncore.external-execution-profile/v1",
stages=self.stages,
orchestration_hashes=dict(self.hashes),
samples=self.samples,
observer_command_wall_seconds=self.sample_seconds,
errors=dict(self.errors),
sampler_stopped=self.thread is None or not self.thread.is_alive(),
numeric_functions_wrapped=False,
gpu_measurement_scope="host utilization; includes unrelated durable GPU services",
sample_interval_seconds=self.interval,
observer_wall_is_not_pipeline_overhead=True,
)
(self.root / "execution-profile.json").write_text(json.dumps(report, indent=2))
return report
@@ -0,0 +1,163 @@
"""Explain elapsed-time metadata separately from exact physical evidence.
No tolerance, array conversion, geometry normalization or generic field ignore
is allowed. The original failed raw-file comparison is retained unchanged.
"""
import gzip
import hashlib
import json
import math
import pickle
import struct
from collections import Counter
from pathlib import Path
import numpy as np
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def exact(a, b, counts, path="root"):
assert type(a) is type(b), (path, "type")
if isinstance(a, np.ndarray):
assert not a.dtype.hasobject, (path, "unqualified object array")
assert a.dtype == b.dtype and a.shape == b.shape and a.strides == b.strides, path
assert a.tobytes(order="A") == b.tobytes(order="A"), (path, "array bits")
counts["arrays"] += 1
elif isinstance(a, np.generic):
assert a.dtype == b.dtype and a.tobytes() == b.tobytes(), (path, "scalar bits")
counts["numpy_scalars"] += 1
elif type(a).__module__.startswith("shapely."):
assert a.wkb == b.wkb, (path, "geometry WKB")
counts["geometries"] += 1
elif isinstance(a, dict):
assert list(a) == list(b), (path, "dictionary ordering")
for key in a:
exact(a[key], b[key], counts, path + "/" + str(key))
elif isinstance(a, (tuple, list)):
assert len(a) == len(b), (path, "length")
for index, (x, y) in enumerate(zip(a, b, strict=True)):
exact(x, y, counts, path + "/" + str(index))
elif isinstance(a, float):
assert struct.pack("!d", a) == struct.pack("!d", b), (path, "float bits")
counts["python_floats"] += 1
elif a is None or isinstance(a, (str, bytes, int, bool)):
assert a == b, (path, "value")
counts["other_scalars"] += 1
else:
raise TypeError((path, type(a)))
def elapsed(value):
assert type(value) is float and math.isfinite(value) and value >= 0
return value
def proposal_data(document):
# observation_tiles.collect_tile writes exactly these monotonic durations.
result = {**document, "tile_reports": []}
times = []
for row in document["tile_reports"]:
assert set(row["detectors"]) == {"linear", "appearance", "catalog", "compact", "crossing"}
times.append(dict(
tile=row["tile"], seconds=elapsed(row["seconds"]),
detectors={k: elapsed(v) for k, v in row["detectors"].items()},
))
result["tile_reports"].append({
k: v for k, v in row.items() if k not in {"seconds", "detectors"}
})
return result, times
def run():
source = Path("/raw-proof")
proof = json.loads((source / "equivalence.json").read_text())
assert not proof["passed"]
assert {k for k, v in proof["checks"].items() if not v} == {
"all_numeric_and_image_payloads_exact", "decisions_and_primary_manifests_exact",
}
assert proof["payload_differences"] == ["marking_pass/measured-bank.pkl.gz"]
assert {k for k, v in proof["json_artifacts"].items() if not v} == {
"primary_search/search-proposals.json", "primary_search/symbol-patches.json",
}
for name, key in [
("/baseline", "baseline_summary_sha256"), ("/candidate-run", "candidate_summary_sha256")
]:
assert sha(Path(name) / "summary.json") == proof[key]
counts = Counter()
runs = [Path("/baseline/run"), Path("/candidate-run/run")]
proposals = [json.loads((r / "primary_search/search-proposals.json").read_text()) for r in runs]
physical, times = zip(*(proposal_data(d) for d in proposals), strict=True)
exact(physical[0], physical[1], counts, "search-proposals")
patches = [json.loads((r / "primary_search/symbol-patches.json").read_text()) for r in runs]
patch_times = [elapsed(p.pop("seconds")) for p in patches]
exact(patches[0], patches[1], counts, "symbol-patches")
manifests = [
("ortho/observation-coverage.json", "/ortho/observation-coverage.json", "solver"),
(
"ortho/native-geometry/native-geometry.json",
"/ortho/native-geometry/native-geometry.json", None,
),
]
manifest_times = {}
for relative, _, parent in manifests:
documents = [json.loads((r / relative).read_text()) for r in runs]
manifest_times[relative] = [
elapsed((d[parent] if parent else d).pop("seconds")) for d in documents
]
exact(documents[0], documents[1], counts, relative)
bank_row = next(r for r in proof["artifacts"] if r["path"] == proof["payload_differences"][0])
banks = []
identities = []
for root, key in zip(runs, ["baseline_sha256", "candidate_sha256"], strict=True):
path = root / bank_row["path"]
assert sha(path) == bank_row[key]
# Only our hash-verified qualification artifact is deserialized.
bank = pickle.loads(gzip.decompress(path.read_bytes()))
inputs = bank["observation_inputs"]
expected = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest()
assert bank["observation_identity"] == expected
timing_hashes = {
"/searchplan/search-proposals.json": sha(root / "primary_search/search-proposals.json")
}
timing_hashes.update({key: sha(root / relative) for relative, key, _ in manifests})
for key, digest in timing_hashes.items():
assert inputs[key] == digest
identities.append(dict(bank_identity=expected, verified_input_file_hashes=timing_hashes))
physical_bank = {k: v for k, v in bank.items() if k != "observation_identity"}
physical_bank["observation_inputs"] = {
k: v for k, v in inputs.items() if k not in timing_hashes
}
banks.append(physical_bank)
exact(banks[0], banks[1], counts, "measured-bank")
assert counts["arrays"] and counts["geometries"]
report = dict(
schema="missioncore.elapsed-metadata-explanation/v1",
passed=True, raw_proof_sha256=sha(source / "equivalence.json"),
unchanged_numeric_image_artifacts=proof["artifact_count"] - 1,
measured_bank_physical_content_exact=True, comparison_counts=dict(counts),
proposal_timing_records=[len(t) for t in times], proposal_timings=times,
patch_elapsed_seconds=patch_times, manifest_elapsed_seconds=manifest_times,
verified_provenance_links=identities,
excluded_fields=[
"search-proposals: tile_reports[i].seconds and .detectors (monotonic durations)",
"symbol-patches: seconds (monotonic duration)",
"observation-coverage: solver.seconds (monotonic duration)",
"native-geometry: seconds (monotonic duration)",
"bank: observation_inputs[/searchplan/search-proposals.json] (verified file hash)",
"bank: observation_inputs[/ortho/observation-coverage.json] (verified file hash)",
"bank: observation_inputs[/ortho/native-geometry/native-geometry.json] (verified hash)",
"bank: observation_identity (verified hash of all original observation_inputs)",
],
unknown_differences_allowed=False, numeric_tolerance=None, artifacts_mutated=False,
model_or_acceptance_changed=False,
)
Path("/out/metadata-explanation.json").write_text(json.dumps(report, indent=2))
print("PHYSICAL_EVIDENCE_EXACT", json.dumps(dict(counts)), flush=True)
if __name__ == "__main__":
run()
@@ -0,0 +1,52 @@
"""Descriptive geometry metrics; these are not labeled accuracy measurements."""
from collections import Counter
import numpy as np
import shapely
from shapely.geometry import shape
def inspect(document):
rows = [(f, shape(f['geometry'])) for f in document['features']]
classes = sorted({f['properties']['class'] for f, _ in rows})
result = dict(invalid_ids=[], nonfinite_ids=[], classes={},
marking_subtypes=dict(Counter(f['properties'].get('subtype', 'unknown')
for f, _ in rows if f['properties']['class'] == 'road_marking')),
ground_truth_used=False)
for f, g in rows:
if g.is_empty or not g.is_valid:
result['invalid_ids'].append(f['id'])
coordinates = shapely.get_coordinates(g, include_z=g.has_z)
if not np.isfinite(coordinates).all():
result['nonfinite_ids'].append(f['id'])
for cls in classes:
geometries = [shapely.force_2d(g) for f, g in rows
if f['properties']['class'] == cls and g.is_valid]
polygons = [g for g in geometries if g.geom_type in ('Polygon', 'MultiPolygon')]
union = shapely.union_all(polygons)
result['classes'][cls] = dict(features=len(geometries),
polygon_area_m2=float(sum(g.area for g in polygons)),
union_area_m2=float(union.area),
overlap_excess_m2=float(max(0, sum(g.area for g in polygons) - union.area)),
line_length_m=float(sum(g.length for g in geometries
if g.geom_type in ('LineString', 'MultiLineString'))),
holes=sum(len(p.interiors) for g in polygons
for p in (list(g.geoms) if g.geom_type == 'MultiPolygon' else [g])))
return result
def difference(reference, candidate):
classes = {f['properties']['class'] for d in [reference, candidate] for f in d['features']}
result = {}
for cls in sorted(classes):
unions = []
for doc in [reference, candidate]:
geometries = [shapely.force_2d(shape(f['geometry'])) for f in doc['features']
if f['properties']['class'] == cls]
unions.append(shapely.union_all([g for g in geometries if g.is_valid]))
a, b = unions
delta = a.symmetric_difference(b)
result[cls] = dict(symmetric_difference_area_m2=float(delta.area),
symmetric_difference_length_m=float(delta.length),
union_equal=bool(a.equals(b)))
return result
@@ -0,0 +1,248 @@
"""Causal diagnostic on frozen rejected junctions, never a map producer.
Change only the background operator. Preserve the original body coordinates,
readers, RGB, validity and the legacy contrast cut. A 2-D opening is an
experimental measurement, not a new acceptance rule. No search or fitting.
"""
import gzip
import hashlib
import json
import pickle
import time
from pathlib import Path
import cv2
import numpy as np
import shapely
import stroke_observations
from beta_profiles import describe
from object_context import measure
from observation_cache import ObservationCache
from PIL import Image, ImageDraw
from scipy.ndimage import gaussian_filter1d
from shapely.geometry import mapping, shape
def digest(a):
return hashlib.sha256(a.tobytes()).hexdigest()
def qualify_operator():
"""A causal synthetic control, not an acceptance qualification."""
yy, xx = np.mgrid[-60:61, -60:61]
base = np.full(xx.shape, 40, dtype=np.float32)
cases = {}
cases["empty"] = base.copy()
cases["straight"] = np.where(abs(xx) <= 2, 220, base).astype("float32")
cases["junction"] = np.where((abs(xx) <= 2) | (abs(yy) <= 2), 220, base).astype("float32")
cases["gap"] = np.where((abs(xx) <= 2) & (abs(yy) >= 9), 220, base).astype("float32")
cases["broad_bright_surface"] = np.where((abs(xx) <= 30) & (abs(yy) <= 30), 220, base).astype(
"float32"
)
values = {}
for name, gray in cases.items():
a = gray - cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((1, 35), np.uint8))
b = gray - cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((35, 35), np.uint8))
assert np.all(a[gray == 40] == 0) and np.all(b[gray == 40] == 0)
values[name] = dict(legacy_center=float(a[60, 60]), opening_2d_center=float(b[60, 60]))
assert values["junction"] == dict(legacy_center=0.0, opening_2d_center=180.0)
assert values["straight"] == dict(legacy_center=180.0, opening_2d_center=180.0)
for name in ["empty", "gap", "broad_bright_surface"]:
assert values[name] == dict(legacy_center=0.0, opening_2d_center=0.0)
return dict(passed=True, cases=values, real_world_accuracy_measured=False)
def support(mask, valid, contrast, cut, gray, background):
if not mask.any():
return dict(samples=0)
return dict(
samples=int(mask.sum()),
valid=float(valid[mask].mean()),
paint=float((contrast[mask] > cut).mean()),
gray_median=float(np.median(gray[mask])),
background_median=float(np.median(background[mask])),
contrast_median=float(np.median(contrast[mask])),
)
def probe(polygon, shared, object_region, reader, expected, output):
d = describe(polygon)
ts = np.arange(-d["length"] / 2 + 0.04, d["length"] / 2 - 0.04, 0.025)
ns = np.arange(-0.7, 0.701, 0.025)
normal = np.array([-d["axis"][1], d["axis"][0]])
xy = d["origin"] + ts[:, None, None] * d["axis"] + ns[None, :, None] * normal
rgb, valid = reader(xy.reshape(-1, 2))
rgb = rgb.reshape(len(ts), len(ns), 3).astype("uint8")
valid = valid.reshape(len(ts), len(ns))
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype("float32")
old_bg = cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((1, 35), np.uint8))
old = gaussian_filter1d(np.maximum(gray - old_bg, 0), 0.8, axis=1)
core = abs(ns) <= max(0.025, min(0.04, d["width"] * 0.2))
cut = max(15.0, 0.35 * float(np.median(np.median(old[:, core], axis=1))))
body = np.broadcast_to(abs(ns) <= d["width"] / 2, gray.shape).copy()
body &= shapely.intersects_xy(polygon, xy[..., 0], xy[..., 1])
joint = body & shapely.intersects_xy(shared, xy[..., 0], xy[..., 1])
exterior = ~shapely.intersects_xy(object_region, xy[..., 0], xy[..., 1])
assert np.array_equal((old[body] > cut), expected["paint"])
assert np.array_equal(valid[body], expected["valid"])
# Opening is erosion then dilation: 34 samples of context on each side
# avoid importing an artificial strip boundary into a 35x35 operator.
pad = 34
def extend(a):
return np.r_[a[0] - np.arange(pad, 0, -1) * 0.025, a, a[-1] + np.arange(1, pad + 1) * 0.025]
et, en = extend(ts), extend(ns)
extended_xy = d["origin"] + et[:, None, None] * d["axis"] + en[None, :, None] * normal
extended_rgb, extended_valid = reader(extended_xy.reshape(-1, 2))
extended_rgb = extended_rgb.reshape(len(et), len(en), 3).astype("uint8")
extended_valid = extended_valid.reshape(len(et), len(en))
center = np.s_[pad:-pad, pad:-pad]
assert np.array_equal(extended_xy[center], xy)
assert np.array_equal(extended_rgb[center], rgb)
assert np.array_equal(extended_valid[center], valid)
extended_gray = cv2.cvtColor(extended_rgb, cv2.COLOR_RGB2GRAY).astype("float32")
extended_bg = cv2.morphologyEx(extended_gray, cv2.MORPH_OPEN, np.ones((35, 35), np.uint8))
new_bg = extended_bg[center]
# Keep the same smoothing and crop as the legacy calculation.
new = gaussian_filter1d(np.maximum(gray - new_bg, 0), 0.8, axis=1)
# The final transverse Gaussian also reads three samples on either side.
context_valid = cv2.erode(
extended_valid.astype("uint8"),
np.ones((69, 75), np.uint8),
borderType=cv2.BORDER_CONSTANT,
borderValue=0,
)[center].astype(bool)
groups = {
"body": body,
"joint": joint,
"joint_with_valid_2d_context": joint & context_valid,
"body_with_valid_2d_context": body & context_valid,
"exterior": exterior,
"previously_dark_exterior": exterior & (old <= cut),
}
report = dict(
cut=cut,
original_geometry=mapping(polygon),
xy_sha256=digest(xy),
rgb_sha256=digest(rgb),
valid_sha256=digest(valid),
shared_samples_identical=True,
legacy_body_reproduced=True,
context_valid_in_joint=float(context_valid[joint].mean()) if joint.any() else None,
evidence={
name: {
"legacy": support(mask, valid, old, cut, gray, old_bg),
"opening_2d": support(mask, valid, new, cut, gray, new_bg),
}
for name, mask in groups.items()
},
)
output.mkdir()
np.savez_compressed(
output / "observations.npz",
xy=xy,
rgb=rgb,
valid=valid,
gray=gray,
background_1d=old_bg,
background_2d=new_bg,
contrast_1d=old,
contrast_2d=new,
body=body,
joint=joint,
context_valid=context_valid,
)
# A fixed physical margin around every joint, not a selected success crop.
if joint.any():
ii, jj = np.where(joint)
crop = np.s_[
max(0, ii.min() - 16) : min(len(ts), ii.max() + 17),
max(0, jj.min() - 16) : min(len(ns), jj.max() + 17),
]
panels = [
("RGB", rgb[crop]),
("background 1D", old_bg[crop]),
("background 2D", new_bg[crop]),
("contrast 1D", old[crop]),
("contrast 2D", new[crop]),
]
images = []
for title, array in panels:
a = np.clip(array, 0, 255).astype("uint8")
image = Image.fromarray(a).convert("RGB")
pixels = np.asarray(image).copy()
edge = cv2.morphologyEx(
joint[crop].astype("uint8"), cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8)
).astype(bool)
pixels[edge] = [255, 80, 80]
image = Image.fromarray(pixels).resize(
(image.width * 5, image.height * 5), Image.Resampling.NEAREST
)
panel = Image.new("RGB", (image.width, image.height + 25), "black")
panel.paste(image, (0, 25))
ImageDraw.Draw(panel).text((4, 6), title, fill="white")
images.append(panel)
sheet = Image.new(
"RGB", (sum(i.width for i in images), max(i.height for i in images)), "black"
)
x = 0
for image in images:
sheet.paste(image, (x, 0))
x += image.width
sheet.save(output / "diagnostic.png")
return report
def run():
out = Path("/out/background")
out.mkdir(exist_ok=False)
begin = time.monotonic()
synthetic = qualify_operator()
trace_path = Path("/trace/comparison/matrix-trace.json")
trace = json.loads(trace_path.read_text())
raw = Path("/reference/run/marking_pass/measured-bank.pkl.gz").read_bytes()
bank = pickle.loads(gzip.decompress(raw))
stroke_observations.initialize()
views = stroke_observations.views
views.inputs = ObservationCache(views.inputs, 6 * 1024**3)
reports = []
for case, failure in enumerate(trace["failures"]):
shared = shape(failure["shared_geometry"])
object_region = shapely.union_all([shape(m["geometry"]) for m in failure["members"]])
record = dict(case=case, indices=failure["indices"], views=[])
for member, index in enumerate(failure["indices"]):
r = bank["candidates"][index]
p = r["polygons"][0]
assert mapping(p) == mapping(shape(failure["members"][member]["geometry"]))
readers, used = views.readers(r["origin"], r["axis"])
measured = measure(p, readers)
assert measured["legacy_evidence"] == failure["members"][member]["legacy_evidence"]
for view, reader in enumerate(readers):
name = f"case-{case:02d}-member-{member}-view-{view}"
report = probe(
p, shared, object_region, reader, measured["bodies"][view], out / name
)
report.update(member=member, view=view, source_views=used[view], directory=name)
record["views"].append(report)
reports.append(record)
print("BACKGROUND", case + 1, "/", len(trace["failures"]), flush=True)
result = dict(
schema="missioncore.background-cause-probe/v1",
seconds=time.monotonic() - begin,
bank_sha256=hashlib.sha256(raw).hexdigest(),
trace_sha256=hashlib.sha256(trace_path.read_bytes()).hexdigest(),
fixed_cut=True,
map_produced=False,
production_admission_changed=False,
new_candidates=0,
independent_ground_truth=False,
synthetic=synthetic,
cases=reports,
)
(out / "report.json").write_text(json.dumps(result, indent=2, allow_nan=False))
if __name__ == "__main__":
run()
@@ -0,0 +1,63 @@
"""Locate repeated work on a frozen bank; profiled time is not a speed claim."""
import cProfile
import hashlib
import json
import runpy
import time
from pathlib import Path
def run():
output = Path("/out")
profiler = cProfile.Profile()
begin = time.monotonic()
profiler.enable()
try:
runpy.run_path("/candidate/refine_markings.py", run_name="__main__")
finally:
profiler.disable()
profiler.dump_stats(str(output / "assembly-profile.pstats"))
rows = []
for entry in profiler.getstats():
code = entry.code
rows.append(
dict(
function=code if isinstance(code, str) else code.co_name,
file=None if isinstance(code, str) else code.co_filename,
line=None if isinstance(code, str) else code.co_firstlineno,
calls=entry.callcount,
recursive_calls=entry.reccallcount,
cumulative_seconds=entry.totaltime,
own_seconds=entry.inlinetime,
)
)
checks = {}
for name in [
"full-map.json",
"marking-rows.json",
"finite-stroke-admission.json",
"configuration-bank.json",
]:
actual = output / name
reference = Path("/reference/run/marking_pass") / name
checks[name] = dict(
exact=actual.read_bytes() == reference.read_bytes(),
actual_sha256=hashlib.sha256(actual.read_bytes()).hexdigest(),
reference_sha256=hashlib.sha256(reference.read_bytes()).hexdigest(),
)
result = dict(
schema="missioncore.frozen-assembly-profile/v1",
seconds=time.monotonic() - begin,
profiling_enabled=True,
cold_pipeline=False,
checks=checks,
passed=all(c["exact"] for c in checks.values()),
functions=sorted(rows, key=lambda r: -r["cumulative_seconds"]),
)
(output / "profile-report.json").write_text(json.dumps(result, indent=2))
assert result["passed"], "Profiling changed frozen assembly results"
if __name__ == "__main__":
run()
@@ -0,0 +1,50 @@
"""Reserve Worker and complete the frozen control tail in an owned sandbox."""
from pathlib import Path
import base64
import hashlib
import json
import subprocess
import sys
import uuid
repo = Path(__file__).resolve().parents[3]
config = json.loads(Path(sys.argv[1]).read_text())
session = config['session']
if not session.startswith('pipeline-control-') or any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789-' for c in session):
raise ValueError('Invalid session')
root = repo / '.runtime/simulation-qualifications' / session
root.mkdir(exist_ok=False)
worker = Path(__file__).with_name('run_control_tail.py').read_bytes()
(root/'worker.py').write_bytes(worker)
(root/'builder.py').write_bytes(Path(__file__).read_bytes())
config['worker_sha256'] = hashlib.sha256(worker).hexdigest()
(root/'config.json').write_text(json.dumps(config,indent=2))
sys.path.insert(0,str(repo/'src'))
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
queue = ObservatoryRecordedJobQueue(repo/'.runtime/mission-core', definitions=None)
owner = 'airun-' + uuid.uuid4().hex
queue.reserve_simulation(owner)
receipt = dict(owner=owner,state='reserved')
(root/'reservation.json').write_text(json.dumps(receipt))
ssh = ['ssh','-T','-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','-o','ConnectTimeout=12',
'mission-gpu','D:/NDC_MISSIONCORE/runtime/simulation/isaac-sim-6.1.0/kit/python/python.exe -u -B -']
code = 'import json,base64\nCONFIG=json.loads(base64.b64decode(' + repr(base64.b64encode(json.dumps(config).encode()).decode()) + '))\n' + worker.decode()
try:
p = subprocess.Popen(ssh,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,errors='replace')
p.stdin.write(code);p.stdin.close(); info=None
with (root/'execution.log').open('w') as log:
for line in p.stdout:
log.write(line);log.flush();print(line,end='',flush=True)
if line.startswith('COLLECTION '):info=json.loads(line[11:])
if p.wait()!=0 or not info:raise RuntimeError('Control tail failed; see frozen evidence')
assert info['bytes'] < 20*1024**2
target=root/'summary.json'
subprocess.run(['scp','-q','mission-gpu:'+info['path'].replace('\\','/'),str(target)],check=True)
assert hashlib.sha256(target.read_bytes()).hexdigest()==info['sha256']
print('COLLECTED',root,flush=True)
finally:
check = subprocess.run(ssh,input="from pathlib import Path\nprint(Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/"+session+"/active.json').exists())",capture_output=True,text=True,timeout=30)
if check.returncode==0 and check.stdout.strip()=='False':
queue.release_simulation(owner);receipt['state']='released'
else:receipt['state']='cleanup-unconfirmed'
(root/'reservation.json').write_text(json.dumps(receipt))
@@ -0,0 +1,58 @@
"""Exact-output qualification of scheduling changes on one frozen real run.
Reference outputs are read only after candidate execution. These benchmark
outputs never enter a subsequent cold run or a published urban map.
"""
from pathlib import Path
import hashlib,json,time,shutil
def run(root,modules,reference,expected_sha,marker,profile,runtime,artifact,run_container,write_json):
digest=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
assert digest(reference/'summary.json')==expected_sha
prior=json.loads((reference/'summary.json').read_text())
assert prior['cold_run'] and prior['completed_stages']==30
source=reference/'run';out=root/'execution-reuse';out.mkdir()
search=out/'search';search.mkdir()
env=dict(PYTHONPATH='/candidate:/candidate/mapping:/release/simulation/ai-polygon',SCENE='scene',
OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='2',OBSERVATION_WORKERS='4',
HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HOME='/tmp/hf',TORCH_HOME='/tmp/torch')
started=time.monotonic()
run_container(marker,'parallel-extraction',profile['mapper_image'],
[(modules/'primary_search','/candidate',True),(source/'ortho','/ortho',True),
(source/'ortho/survey','/survey',True),(source/'full_plan','/evidence_plan',True),(search,'/out',False)],
['-B','/candidate/extract_observations.py'],search,lambda:None,900,gpu=False,executable='python3',
environment=env,readonly=True,resources=dict(cpus=8,memory_gib=24))
parallel_seconds=time.monotonic()-started
checks={}
for name in ['search-proposals.json','catalog-proposals.json','compact-seeds.json','crossing-seeds.json','observations.json']:
a=json.loads((source/'primary_search'/name).read_text());b=json.loads((search/name).read_text())
# Timing is deliberately excluded; order, geometry, scores, source
# identities and candidate ownership must be exactly unchanged.
if isinstance(a,dict):a.pop('tile_reports',None);b.pop('tile_reports',None)
checks[name]=a==b
report=dict(reference=reference.name,reference_sha256=expected_sha,outputs_used_by_cold_run=False,
extraction=dict(seconds=parallel_seconds,files_equal=checks))
write_json(out/'execution-qualification.json',report)
assert all(checks.values()),'Parallel extraction changed candidate evidence'
symbols=out/'symbols';symbols.mkdir()
shutil.copy2(source/'primary_search/symbol-patches.json',symbols/'symbol-patches.json')
started=time.monotonic()
run_container(marker,'semantic-lifecycle',profile['semantic_image'],
[(modules/'primary_search','/candidate',True),(artifact,'/release',True),
(runtime/profile['semantic_model'],'/assets',True),(symbols,'/out',False),
(source/'primary_search/symbol-patches','/out/symbol-patches',True)],
['-B','/candidate/semantic_symbols.py'],symbols,lambda:None,900,gpu=True,executable='python3',
environment=env,readonly=True)
semantic_seconds=time.monotonic()-started
a=json.loads((source/'primary_search/symbol-semantics.json').read_text())
b=json.loads((symbols/'symbol-semantics.json').read_text())
same=a['records']==b['records']
hashes=all(r['sha256'] is None or digest(symbols/'symbol-masks'/(r['id']+'.npz'))==r['sha256'] for r in b['records'])
report['semantics']=dict(seconds=semantic_seconds,patches=len(b['records']),records_equal=same,masks_sha256_verified=hashes,
cuda_peak_allocated_bytes=b.get('cuda_peak_allocated_bytes'),host_peak_rss_bytes=b.get('host_peak_rss_bytes'))
report['passed']=all(checks.values()) and same and hashes
write_json(out/'execution-qualification.json',report)
assert report['passed'],'Semantic scheduling changed masks, classes or scores'
print('EXACT_EXECUTION_QUALIFIED',json.dumps(report),flush=True)
return report
@@ -0,0 +1,116 @@
"""Run frozen control/shared semantics with the Core's exclusive GPU owner."""
import base64
import hashlib
import json
import subprocess
import sys
import uuid
from pathlib import Path
repo = Path(__file__).resolve().parents[3]
module = repo / "simulation/urban-plan-research"
config = json.loads(Path(sys.argv[1]).read_text())
session = config["session"]
if not session.startswith("shared-survey-") or any(
c not in "abcdefghijklmnopqrstuvwxyz0123456789-" for c in session
):
raise ValueError("Invalid qualification session")
root = repo / ".runtime/simulation-qualifications" / session
root.mkdir(exist_ok=False)
aliases = {p.name: p for p in (module / "shared_survey").glob("*.py")}
aliases["legacy_ortho_segment.py"] = module / "orthophoto/ortho_segment.py"
aliases["legacy_semantic_layers.py"] = module / "full_plan/semantic_layers.py"
aliases["ortho_windows.py"] = module / "orthophoto/ortho_windows.py"
files = {}
for name, path in aliases.items():
data = path.read_bytes()
files[name] = dict(
source=path.relative_to(repo).as_posix(),
sha256=hashlib.sha256(data).hexdigest(),
content=base64.b64encode(data).decode(),
)
config["files"] = files
worker = module / "evaluation/run_shared_survey_worker.py"
worker_bytes = worker.read_bytes()
(root / "worker.py").write_bytes(worker_bytes)
(root / "builder.py").write_bytes(Path(__file__).read_bytes())
config["worker_sha256"] = hashlib.sha256(worker_bytes).hexdigest()
(root / "source-manifest.json").write_text(
json.dumps({k: {n: v[n] for n in ["source", "sha256"]} for k, v in files.items()}, indent=2)
)
(root / "config.json").write_text(
json.dumps({k: v for k, v in config.items() if k != "files"}, indent=2)
)
sys.path.insert(0, str(repo / "src"))
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue # noqa: E402
queue = ObservatoryRecordedJobQueue(repo / ".runtime/mission-core", definitions=None)
owner = "airun-" + uuid.uuid4().hex
queue.reserve_simulation(owner)
receipt = dict(owner=owner, state="reserved")
(root / "reservation.json").write_text(json.dumps(receipt))
ssh = [
"ssh",
"-T",
"-o",
"BatchMode=yes",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"ConnectTimeout=15",
"mission-gpu",
"D:/NDC_MISSIONCORE/runtime/simulation/isaac-sim-6.1.0/kit/python/python.exe -",
]
code = (
"import json,base64\nCONFIG=json.loads(base64.b64decode("
+ repr(base64.b64encode(json.dumps(config).encode()).decode())
+ "))\n"
+ worker_bytes.decode()
)
try:
p = subprocess.Popen(
ssh,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
errors="replace",
)
p.stdin.write(code)
p.stdin.close()
info = None
with (root / "execution.log").open("w") as log:
for line in p.stdout:
log.write(line)
log.flush()
print(line, end="", flush=True)
if line.startswith("COLLECTION "):
info = json.loads(line[11:])
if p.wait() != 0 or not info:
raise RuntimeError("Qualification failed; inspect owned evidence")
assert info["bytes"] < 10 * 1024**2
summary = root / "summary.json"
subprocess.run(["scp", "-q", "mission-gpu:" + info["path"], str(summary)], check=True)
assert hashlib.sha256(summary.read_bytes()).hexdigest() == info["sha256"]
print("COLLECTED", root, flush=True)
finally:
try:
check = subprocess.run(
ssh,
input="from pathlib import Path\nprint(Path("
"'C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/"
+ session
+ "/active.json').exists())",
text=True,
capture_output=True,
timeout=30,
)
if check.returncode == 0 and check.stdout.strip() == "False":
queue.release_simulation(owner)
receipt["state"] = "released"
else:
receipt["state"] = "cleanup-unconfirmed"
except subprocess.SubprocessError:
receipt["state"] = "cleanup-unconfirmed"
(root / "reservation.json").write_text(json.dumps(receipt))
@@ -0,0 +1,31 @@
"""Execute all measured axes concurrently; compare the complete serial result."""
from pathlib import Path
import json,time
from infrastructure_sources import checksum
from infrastructure_containers import run_container
from local_state import write_json
def run(root,modules,reference,expected_sha,marker,profile):
assert checksum(reference/'summary.json')==expected_sha
prior=json.loads((reference/'summary.json').read_text())
observations=Path(prior.get('observation_run',str(reference/'run')))
assert observations.resolve().is_relative_to(reference.parent.resolve())
source=reference/'run';out=root/'stroke-execution';out.mkdir()
mounts=[(modules/'marking_pass','/candidate',True),(out,'/out',False),
(observations/'ortho','/ortho',True),(observations/'ortho/survey','/survey',True),
(observations/'full_plan','/evidence_plan',True),(observations/'primary_search','/searchplan',True),
(observations/'primary_search','/primary',True),(source/'bicycles','/fullplan',True)]
start=time.monotonic()
run_container(marker,'parallel-strokes',profile['mapper_image'],mounts,['-B','/candidate/refine_markings.py'],out,lambda:None,1200,
gpu=False,executable='python3',environment=dict(PYTHONPATH='/candidate:/candidate/mapping',SCENE='scene',OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='2',STROKE_WORKERS='4'),readonly=True,resources=dict(cpus=8,memory_gib=24))
seconds=time.monotonic()-start
checks={name:json.loads((out/name).read_text())==json.loads((source/'marking_pass'/name).read_text())
for name in ['full-map.json','marking-rows.json','finite-stroke-admission.json']}
a=json.loads((out/'marking-report.json').read_text());b=json.loads((source/'marking_pass/marking-report.json').read_text())
a.pop('seconds');b.pop('seconds');checks['marking-report.json']=a==b
report=dict(reference=reference.name,reference_sha256=expected_sha,seconds=seconds,checks=checks,passed=all(checks.values()),outputs_used_by_cold_run=False)
write_json(out/'execution-qualification.json',report)
print('STROKE_EXECUTION_QUALIFIED',json.dumps(report),flush=True)
assert report['passed'],'Parallel measurements changed geometry or admission evidence'
return report
@@ -0,0 +1,54 @@
"""Freeze a candidate source closure, reserve Worker, run and collect evidence."""
from pathlib import Path
import base64,hashlib,json,subprocess,sys,uuid,ast
repo=Path(__file__).resolve().parents[3];module=repo/'simulation/urban-plan-research'
config=json.loads(Path(sys.argv[1]).read_text());session=config['session']
if not session.startswith('systematic-')or any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789-'for c in session):raise ValueError('Invalid session')
root=repo/'.runtime/simulation-qualifications'/session;root.mkdir(exist_ok=False)
definition=json.loads((module/'systematic/definition.json').read_text());paths={v for g in definition['groups']for v in g['files'].values()}
paths.add('evaluation/contract_preflight.py')
paths.add('evaluation/execution_profile.py')
paths.add('evaluation/qualify_execution_reuse.py')
paths.add('evaluation/run_frozen_tail.py')
paths.add('evaluation/qualify_stroke_execution.py')
paths.add('systematic/qualify_primary_plan.py')
paths.update('pipeline/'+p for p in ['config-ortho.json','config-mv.json','worker-profile.json'])
files={}
for relative in sorted(paths):
path=module/relative
assert not path.is_symlink() and path.resolve().is_relative_to(module.resolve())
data=path.read_bytes()
if path.suffix=='.py':ast.parse(data)
files['simulation/urban-plan-research/'+relative]=dict(sha256=hashlib.sha256(data).hexdigest(),content=base64.b64encode(data).decode())
for relative in ['simulation/ai-polygon/infrastructure_containers.py','simulation/ai-polygon/infrastructure_pipeline.py']:
data=(repo/relative).read_bytes();ast.parse(data)
files[relative]=dict(sha256=hashlib.sha256(data).hexdigest(),content=base64.b64encode(data).decode())
data=(module/'systematic/definition.json').read_bytes()
files['simulation/urban-plan-research/pipeline/definition.json']=dict(sha256=hashlib.sha256(data).hexdigest(),content=base64.b64encode(data).decode())
config['files']=files
worker=Path(__file__).with_name('run_systematic_worker.py').read_bytes();config['worker_sha256']=hashlib.sha256(worker).hexdigest()
(root/'worker.py').write_bytes(worker);(root/'builder.py').write_bytes(Path(__file__).read_bytes())
(root/'config.json').write_text(json.dumps({k:v for k,v in config.items()if k!='files'},indent=2))
(root/'source-manifest.json').write_text(json.dumps({k:v['sha256']for k,v in files.items()},indent=2))
sys.path.insert(0,str(repo/'src'))
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
queue=ObservatoryRecordedJobQueue(repo/'.runtime/mission-core',definitions=None);owner='airun-'+uuid.uuid4().hex
queue.reserve_simulation(owner);receipt=dict(owner=owner,state='reserved');(root/'reservation.json').write_text(json.dumps(receipt))
ssh=['ssh','-T','-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','-o','ConnectTimeout=15','-o','ServerAliveInterval=15','-o','ServerAliveCountMax=8','mission-gpu','D:/NDC_MISSIONCORE/runtime/simulation/isaac-sim-6.1.0/kit/python/python.exe -u -B -']
code='import json,base64\nCONFIG=json.loads(base64.b64decode('+repr(base64.b64encode(json.dumps(config).encode()).decode())+'))\n'+worker.decode()
try:
p=subprocess.Popen(ssh,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,errors='replace');p.stdin.write(code);p.stdin.close();info=None
with (root/'execution.log').open('w')as log:
for line in p.stdout:
log.write(line);log.flush();print(line,end='',flush=True)
if line.startswith('COLLECTION '):info=json.loads(line[11:])
if p.wait()!=0 or not info:raise RuntimeError('Candidate failed; see frozen evidence')
assert info['bytes']<30*1024**2
target=root/'summary.json';subprocess.run(['scp','-q','mission-gpu:'+info['path'].replace('\\','/'),str(target)],check=True)
assert hashlib.sha256(target.read_bytes()).hexdigest()==info['sha256']
print('COLLECTED',root,flush=True)
finally:
check=subprocess.run(ssh,input="from pathlib import Path\nprint(Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/"+session+"/active.json').exists())",text=True,capture_output=True,timeout=30)
if check.returncode==0 and check.stdout.strip()=='False':queue.release_simulation(owner);receipt['state']='released'
else:receipt['state']='cleanup-unconfirmed'
(root/'reservation.json').write_text(json.dumps(receipt))
@@ -0,0 +1,127 @@
"""Build a bounded import closure and run one owned Worker006 qualification.
Usage: repository .venv/bin/python evaluation/qualify_topdown.py CONFIG.json
Config names a fresh session, pinned worker release/definition and development
scene observation paths. Optional symbols path replays saved inference inputs.
"""
from pathlib import Path
import ast
import base64
import hashlib
import json
import subprocess
import sys
import tarfile
import uuid
repo = Path(__file__).resolve().parents[3]
module = repo/'simulation/urban-plan-research'
config = json.loads(Path(sys.argv[1]).read_text())
session = config['session']
if not session.startswith('topdown-') or any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789-' for c in session):
raise ValueError('Invalid qualification session')
root = repo/'.runtime/simulation-qualifications'/session
root.mkdir(exist_ok=False)
definition = json.loads((module/'pipeline/definition.json').read_text())
aliases = next(g for g in definition['groups'] if g['group'] == 'uniform_arrows')['files'].copy()
aliases.update({p.name: p.relative_to(module).as_posix() for p in (module/'topdown').glob('*.py')})
pending = ['verify_topdown.py','reconstruct_topdown.py','prepare_topdown.py','semantic_symbols.py','test_topdown.py','merge_arrow_artwork.json']
if any(s.get('render_native_geometry') or s.get('render_parallel_observations') for s in config['scenes']):
pending.append('render_native_geometry.py')
if config.get('audit') or any(s.get('audit') for s in config['scenes']):
pending.append('audit_topdown.py')
if any(s.get('contract_audit') for s in config['scenes']):
pending.append('audit_contract.py')
if any(s.get('assemble_from') for s in config['scenes']):
pending.append('assemble_reviewed_state.py')
if any(s.get('conditional_contract_audit') for s in config['scenes']):
pending.append('conditional_contract_audit.py')
if any(s.get('pose_domain_audit') for s in config['scenes']):
pending.append('pose_domain_audit.py')
if any(s.get('endpoint_cause_audit') for s in config['scenes']):
pending.append('endpoint_cause_audit.py')
if any(s.get('depth_audit') for s in config['scenes']):
pending.append('depth_audit.py')
if any(s.get('feasibility_audit') for s in config['scenes']):
pending.append('feasibility_audit.py')
if config.get('camera_tests'):
pending.append('test_orthographic_colour.py')
if config.get('retire_mapper_builds'):
aliases['retire_mapper_builds.py']='evaluation/retire_mapper_builds.py'
pending.append('retire_mapper_builds.py')
if config.get('queue_canary'):
aliases.update({'queue_worker_canary.py':'evaluation/queue_worker_canary.py',
'queue_persistence.py':'../../src/k1link/simulation/ai_polygon/worlds.py',
'infrastructure_jobs.py':'../../src/k1link/simulation/ai_polygon/infrastructure_jobs.py',
'infrastructure_progress.py':'../../src/k1link/simulation/ai_polygon/infrastructure_progress.py'})
pending.extend(['queue_worker_canary.py','queue_persistence.py','infrastructure_jobs.py','infrastructure_progress.py'])
files = {}
while pending:
name = pending.pop()
if name in files:
continue
path = module/aliases[name]; data = path.read_bytes()
files[name] = dict(source=path.relative_to(module).as_posix(), sha256=hashlib.sha256(data).hexdigest(),
content=base64.b64encode(data).decode())
if path.suffix == '.py':
for node in ast.walk(ast.parse(data)):
imports = ([node.module] if isinstance(node, ast.ImportFrom) and node.module
else [a.name for a in node.names] if isinstance(node, ast.Import) else [])
for imported in imports:
dependency = imported.split('.')[0]+'.py'
if dependency in aliases:
pending.append(dependency)
for spec in config['scenes']:
if spec.get('confirmed_reference_path'):
data=Path(spec.pop('confirmed_reference_path')).read_bytes()
spec['confirmed_reference']=dict(sha256=hashlib.sha256(data).hexdigest(),content=base64.b64encode(data).decode())
config['files'] = files
builder_bytes=Path(__file__).read_bytes()
worker_bytes=(module/'evaluation/run_topdown_worker.py').read_bytes()
(root/'builder.py').write_bytes(builder_bytes);(root/'worker.py').write_bytes(worker_bytes)
config['builder_sha256'] = hashlib.sha256(builder_bytes).hexdigest()
config['worker_sha256'] = hashlib.sha256(worker_bytes).hexdigest()
(root/'source-manifest.json').write_text(json.dumps({k:{n:v[n] for n in ['source','sha256']} for k,v in files.items()}, indent=2))
(root/'config.json').write_text(json.dumps({k:v for k,v in config.items() if k != 'files'}, indent=2))
sys.path.insert(0, str(repo/'src'))
from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
queue = ObservatoryRecordedJobQueue(repo/'.runtime/mission-core', definitions=None)
owner = 'airun-'+uuid.uuid4().hex
queue.reserve_simulation(owner)
receipt = dict(owner=owner, state='reserved')
(root/'reservation.json').write_text(json.dumps(receipt))
ssh = ['ssh', '-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', 'mission-gpu',
'D:/NDC_MISSIONCORE/runtime/simulation/isaac-sim-6.1.0/kit/python/python.exe -']
worker = module/'evaluation/run_topdown_worker.py'
code = 'import json,base64\nCONFIG=json.loads(base64.b64decode('+repr(base64.b64encode(json.dumps(config).encode()).decode())+'))\n'+worker_bytes.decode()
try:
p = subprocess.Popen(ssh, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, errors='replace')
p.stdin.write(code); p.stdin.close(); info = None
with (root/'execution.log').open('w') as log:
for line in p.stdout:
log.write(line); log.flush(); print(line, end='', flush=True)
if line.startswith('COLLECTION '):
info = json.loads(line[11:])
if p.wait() != 0 or not info:
raise RuntimeError('Worker qualification failed; inspect execution.log')
assert info['bytes'] < 100*1024**2
archive = root/'evidence.tgz'
subprocess.run(['scp', '-q', 'mission-gpu:'+info['path'], str(archive)], check=True)
assert hashlib.sha256(archive.read_bytes()).hexdigest() == info['sha256']
evidence = root/'evidence'; evidence.mkdir()
with tarfile.open(archive) as tar:
for member in tar.getmembers():
assert member.isfile() and (evidence/member.name).resolve().is_relative_to(evidence)
tar.extractall(evidence, filter='data')
for name, digest in json.loads((evidence/'collection.json').read_text()).items():
assert hashlib.sha256((evidence/name).read_bytes()).hexdigest() == digest
print('COLLECTED', root, flush=True)
finally:
check = subprocess.run(ssh, input="from pathlib import Path\nprint(Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/"+session+"/active.json').exists())",
text=True, capture_output=True, timeout=30)
if check.returncode == 0 and check.stdout.strip() == 'False':
queue.release_simulation(owner); receipt['state'] = 'released'
else:
receipt['state'] = 'cleanup-unconfirmed'
(root/'reservation.json').write_text(json.dumps(receipt))
@@ -0,0 +1,166 @@
"""Real bounded Docker lifecycle with the candidate durable FIFO, isolated from operator jobs."""
import hashlib
import importlib.util
import json
import sys
import time
from pathlib import Path
def run(root, sources, release, profile):
from infrastructure_containers import docker, run_container
from infrastructure_preparer import reconcile
from local_state import write_json
package = "k1link.simulation.ai_polygon."
for name in ["infrastructure_progress", "infrastructure_jobs"]:
spec = importlib.util.spec_from_file_location(package + name, sources / (name + ".py"))
mod = importlib.util.module_from_spec(spec)
sys.modules[package + name] = mod
spec.loader.exec_module(mod)
candidate = sys.modules[package + "infrastructure_jobs"]
candidate.provider_identity = lambda: "f" * 64
# Load the exact Core atomic-write function without importing its unrelated
# Gaussian/Numpy reader on the native Windows coordinator. No I/O mock.
import ast
import os
import uuid
persistence = sources / "queue_persistence.py"
tree = ast.parse(persistence.read_text(encoding="utf-8"))
function = next(
n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "write_json"
)
namespace = dict(Path=Path, json=json, os=os, uuid4=uuid.uuid4)
exec(compile(ast.Module(body=[function], type_ignores=[]), str(persistence), "exec"), namespace)
candidate.write_json = namespace["write_json"]
store = candidate.InfrastructureJobs(root / "data")
rows = [
store.request(
dict(
world_id="qualification-" + str(i),
sha256=format(i, "064x"),
collider_sha256=None,
local_scene={"fixture": True},
)
)
for i in range(1, 21)
]
marker = root / "queue-active.json"
events = []
cancelled = False
class Lease:
owner = None
def reserve_simulation(self, owner):
assert self.owner in (None, owner)
self.owner = owner
lease = Lease()
class Client:
instance = "qualification-worker"
def request(self, path, body):
row = store.update(path.rsplit("/", 1)[-1], body, self.instance)
if body.get("action") == "release":
assert lease.owner == "aicache-" + row["key"]
lease.owner = None
return row
client = Client()
store.cancel(rows[7]["key"])
for i, expected in enumerate(rows):
if i == 7:
continue
row = store.pending()
assert row["key"] == expected["key"]
key = row["key"]
claimed = store.dispatch(client.instance, lease, "f" * 64)
assert claimed["key"] == key
out = root / str(i)
out.mkdir()
write_json(marker, dict(key=key, owner=client.instance, containers=[]))
def pulse(i=i, store=store, key=key):
nonlocal cancelled
if i == 1 and not cancelled:
store.cancel(key)
cancelled = True
store.update(
key, dict(action="progress", phase="survey", completed=0, total=1), client.instance
)
start = time.monotonic()
outcome = "ready"
failure_type = None
try:
# Failure and cancellation use actual containers, no inferred release.
code = (
"raise SystemExit(7)"
if i == 0
else "import time; time.sleep(30)"
if i in (1, 3)
else "print('QUEUE_OK')"
)
run_container(
marker,
"queue-canary",
profile["mapper_image"],
[],
["-B", "-c", code],
out,
pulse,
0.5 if i == 3 else 60,
gpu=False,
executable="python3",
readonly=True,
)
store.update(key, dict(action="complete", result={}), client.instance)
except (RuntimeError, TimeoutError) as exc:
failure_type = type(exc).__name__
assert i in (0, 1, 3)
if i == 0:
assert json.loads((out / "queue-canary-exit.json").read_text())["ExitCode"] == 7
if i == 1:
assert store.get(key).get("cancel_requested")
if i == 3:
assert isinstance(exc, TimeoutError)
store.update(key, dict(action="fail"), client.instance)
outcome = "cancelled" if i == 1 else "failed"
finally:
assert store.pending()["key"] == key
reconcile(client, marker)
assert store.get(key)["released"] and not marker.exists() and lease.owner is None
assert not docker(
"ps", "-aq", "--filter", "label=com.nodedc.analysis=" + key
).stdout.strip()
events.append(
dict(
sequence=i + 1,
key=key,
status=outcome,
failure_type=failure_type,
seconds=time.monotonic() - start,
containers_remaining=0,
)
)
if i == 2:
store = candidate.InfrastructureJobs(root / "data")
assert store.pending() is None
report = dict(
submitted=20,
waiting_cancelled=1,
events=events,
finished=True,
persistence_source_sha256=hashlib.sha256(persistence.read_bytes()).hexdigest(),
scope=(
"isolated queue store with real bounded Worker containers; no operator maps or requests"
),
after_failure_next=events[1]["sequence"] == 2,
after_cancel_next=events[2]["sequence"] == 3,
)
write_json(root / "queue-canary.json", report)
print("QUEUE_CANARY", json.dumps(report), flush=True)
@@ -0,0 +1,106 @@
"""Project a qualified map onto predeclared, hash-pinned Gaussian observations."""
import hashlib
import json
from collections import Counter
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import shapely
from fit_scene import project
from matplotlib.lines import Line2D
from PIL import Image
from shapely.geometry import box, shape
COLORS = {
"road_boundary": "#ff981f",
"pedestrian_boundary": "#00e5a8",
"pedestrian_area": "#00e5a8",
"building_facade": "#52a8ff",
"road_marking": "#fff02a",
}
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def draw(ax, geometry, camera, scale, color):
if geometry.geom_type == "Polygon":
for ring in [geometry.exterior, *geometry.interiors]:
uv = (project(np.asarray(ring.coords), camera) + 0.5) * scale - 0.5
ax.plot(uv[:, 0], uv[:, 1], color=color, linewidth=0.8)
elif geometry.geom_type in {"LineString", "LinearRing"}:
uv = (project(np.asarray(geometry.coords), camera) + 0.5) * scale - 0.5
ax.plot(uv[:, 0], uv[:, 1], color=color, linewidth=0.8)
else:
for part in getattr(geometry, "geoms", []):
draw(ax, part, camera, scale, color)
def run():
root, output = Path("/control"), Path("/out")
controls = json.loads((root / "control.json").read_text())
result = json.loads((root / "final-map.json").read_text())
features = [(f, shape(f["geometry"])) for f in result["features"]]
records = []
for item in controls["controls"]:
name = item["source_tile"]
camera_path = Path("/controlsource/ortho/survey") / name / "top.geometry.npz"
assert sha(camera_path) == item["camera_sha256"]
with np.load(camera_path) as arrays:
camera = {key: arrays[key] for key in arrays.files}
domain = box(*item["bounds_xy"][0], *item["bounds_xy"][1])
selected = [(f, g) for f, g in features if shapely.force_2d(g).intersects(domain)]
counts = Counter(
f["properties"].get("subtype", f["properties"]["class"]) for f, _ in selected
)
fig, axes = plt.subplots(2, 2, figsize=(12, 12), squeeze=False)
for row, kind in enumerate(["ground", "context"]):
image_path = Path("/controlsource/ortho/evidence") / (name + "." + kind + ".png")
assert sha(image_path) == item["files"][kind]["sha256"]
with Image.open(image_path) as original:
image = original.convert("RGB")
image.thumbnail((1024, 1024), Image.Resampling.LANCZOS)
pixels = np.asarray(image).copy()
image.close()
h, w = pixels.shape[:2]
scale = w / camera["alpha"].shape[1]
for column in [0, 1]:
ax = axes[row, column]
ax.imshow(pixels)
ax.set_xlim(-0.5, w - 0.5)
ax.set_ylim(h - 0.5, -0.5)
ax.axis("off")
ax.set_title(kind + (" / original" if column == 0 else " / qualified map"))
for feature, geometry in selected:
color = COLORS.get(feature["properties"]["class"], "white")
draw(axes[row, 1], geometry, camera, scale, color)
fig.suptitle("Frozen control " + item["control_id"] + " / " + name)
fig.legend(
handles=[Line2D([0], [0], color=color, label=kind) for kind, color in COLORS.items()],
loc="lower center", ncol=3,
)
fig.tight_layout(rect=(0, 0.05, 1, 0.97))
target = output / (item["control_id"] + ".png")
fig.savefig(target, dpi=130)
plt.close(fig)
records.append(dict(
control_id=item["control_id"], source_tile=name, bounds_xy=item["bounds_xy"],
feature_ids=[f["id"] for f, _ in selected], counts=dict(counts),
camera_sha256=sha(camera_path), image_sha256=sha(target),
))
(output / "review.json").write_text(json.dumps(dict(
schema="missioncore.frozen-spatial-review/v1", controls=records,
source_map_sha256=sha(root / "final-map.json"),
selection_manifest_sha256=sha(root / "control.json"),
geometry_mutated=False, evaluation_only=True, independent_ground_truth=False,
), indent=2))
if __name__ == "__main__":
run()
@@ -0,0 +1,48 @@
"""Retire duplicate compiler build caches after a qualified runtime is retained."""
import hashlib
import json
import shutil
from pathlib import Path
def run(receipt_path, sessions, destination):
receipt_path = Path(receipt_path)
base = receipt_path.parents[2]
receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
retained = receipt_path.parent / "gsplat_cuda.so"
digest = hashlib.sha256(retained.read_bytes()).hexdigest()
assert digest == receipt["compiled"]["sha256"]
retired = []
for session in sessions:
assert session in (
"topdown-performance-20261016093055",
"topdown-performance-20261016093417",
)
root = base / session
assert root != receipt_path.parent.parent and not (root / "active.json").exists()
manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
assert manifest["session"] == session
assert manifest["images"]["mapper_image"] == receipt["base_image"]
binary = root / "mapper-runtime/gsplat_cuda.so"
assert hashlib.sha256(binary.read_bytes()).hexdigest() == digest
cache = root / "mapper-runtime/extensions"
cache_bytes = sum(p.stat().st_size for p in cache.rglob("*") if p.is_file())
retired.append(
dict(
session=session,
duplicate_binary_sha256=digest,
bytes=binary.stat().st_size + cache_bytes,
)
)
if cache.exists():
shutil.rmtree(cache)
binary.unlink()
result = dict(
retained_binary=str(retained),
retained_image=receipt["image"],
retired=retired,
historical_manifests_and_logs_retained=True,
)
destination.write_text(json.dumps(result, indent=2), encoding="utf-8")
return result
@@ -0,0 +1,137 @@
"""Frozen, isolated completion of a cancelled control. Never a cold-run claim."""
from pathlib import Path
import datetime
import hashlib
import json
import shutil
import sys
import time
CONFIG = globals()['CONFIG']
sys.stdout.reconfigure(encoding='utf-8')
runtime = Path('D:/NDC_MISSIONCORE/runtime/simulation')
release = runtime / 'releases' / ('ai-polygon-' + CONFIG['release'])
original = Path(CONFIG['original_job'])
root = Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications') / CONFIG['session']
assert not root.exists()
assert not list((runtime / 'state').glob('*active.json'))
assert shutil.disk_usage(root.parent).free > 40 * 1024**3
sys.path[:0] = [str(release / 'simulation/ai-polygon')]
from infrastructure_containers import run_container, cleanup
from infrastructure_pipeline import SEMANTIC_STAGES, output_inventory
from infrastructure_sources import checksum
from local_state import write_json
module = release / 'simulation/urban-plan-research'
definition_path = module / 'pipeline/definition.json'
assert checksum(definition_path) == CONFIG['definition_sha256']
definition = json.loads(definition_path.read_text())
profile = json.loads((module / 'pipeline/worker-profile.json').read_text())
source_manifest = json.loads((original / 'source-manifest.json').read_text())
assert source_manifest['snapshot'] == CONFIG['snapshot']
modules = original / 'modules' / source_manifest['snapshot']
groups = definition['groups']
start = next(i for i, g in enumerate(groups) if g['group'] == 'uniform_fixed_refit')
assert [g['group'] for g in groups[start:]] == CONFIG['tail_groups']
for group in groups:
for alias, relative in group['files'].items():
assert checksum(modules / group['group'] / alias) == source_manifest['files'][relative]
root.mkdir()
marker = root / 'active.json'
write_json(marker, dict(key=hashlib.sha256(CONFIG['session'].encode()).hexdigest(),
owner=CONFIG['session'], containers=[]))
write_json(root / 'manifest.json', CONFIG | dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),
reuse_scope='Immutable completed prefix; fresh remaining control stages',
published=False, cold_run=False))
locations = {g['group']: original / g['group'] for g in groups[:start] if (original / g['group']).exists()}
previous = original / 'zigzag_terminals'
source = json.loads((original / 'request.json').read_text())['source']
package = runtime / 'state/infrastructure-sources' / source['adapter_key']
assert checksum(package / source['ply']) == source['sha256']
journal = []
inputs = {}
def frozen(path):
"""Bind tree content before first use; don't copy or mutate the saved prefix."""
if path.is_file():
inputs[str(path)] = checksum(path)
else:
for p in path.rglob('*'):
if p.is_file() and p.suffix in {'.json', '.npz', '.png'}:
inputs.setdefault(str(p), checksum(p))
try:
for group in groups[start:]:
name = group['group']
out = root / name
out.mkdir()
if (previous / 'crosswalk-standard-check.json').exists():
shutil.copyfile(previous / 'crosswalk-standard-check.json', out / 'crosswalk-standard-check.json')
for stage in group['stages']:
mounts = [(modules / name, '/candidate', True), (package, '/input', True),
(original / 'base-survey', '/base_survey', True),
(original / 'ortho', '/ortho', True), (original / 'ortho/survey', '/survey', True),
(original / 'geometry', '/base', True), (original / 'multiview', '/multiview', True),
(previous, '/fullplan', True), (out, '/out', False)]
for producer, alias in definition['aliases'].items():
if producer != name and producer in locations:
mounts.append((locations[producer], '/' + alias, True))
for destination, relative in group.get('input_files', {}).items():
assert relative in locations
mounts = [m for m in mounts if m[1] != destination]
mounts.append((locations[relative], destination, True))
if stage in group.get('self_symbol_stages', []):
mounts = [m for m in mounts if m[1] != '/symbolplan']
mounts.append((out, '/symbolplan', True))
for wheel in (module / 'pipeline/vendor').glob('*.whl'):
mounts.append((wheel, '/candidate/' + wheel.name, True))
semantic = stage in SEMANTIC_STAGES
if semantic:
mounts += [(release, '/release', True), (runtime / profile['semantic_model'], '/assets', True)]
env = dict(SCENE='scene', ORTHO_SCENE='scene', MV_MODEL='mapillary',
PYTHONPATH='/candidate:/candidate/mapping:/release/simulation/ai-polygon',
OPENBLAS_NUM_THREADS='3', OMP_NUM_THREADS='3', HF_HUB_OFFLINE='1',
TRANSFORMERS_OFFLINE='1', HF_HOME='/tmp/hf', MPLCONFIGDIR='/tmp/matplotlib',
XDG_CACHE_HOME='/tmp/cache', TORCH_HOME='/tmp/torch',
WINDOW_SOURCE='/candidate/linear_window_support.py')
env.update(group.get('environment', {}))
entry = 'import runpy;'
if stage == 'final_symbol_admission':
entry += "import sys;sys.argv=['final_symbol_admission','/fullplan/full-map.json','/candidate/symbol_rules.py','/out'];"
entry += "runpy.run_path('/candidate/" + stage + ".py',run_name='__main__')"
if stage == 'semantic_compact_symbols' and not json.loads((out/'symbol-patches.json').read_text())['patches']:
write_json(out/'symbol-semantics.json', dict(records=[],patch_manifest_sha256=checksum(out/'symbol-patches.json'),
class_labels=['bicycle'],prompts=['bicycle','bike symbol','bicycle road marking'],class_ids=[0,0,0],manual_rois=[],empty_search=True))
journal.append(dict(group=name, stage=stage, seconds=0, skipped='empty manifest'))
continue
started = time.monotonic()
print('BEGIN', name, stage, flush=True)
run_container(marker, name + '-' + stage, profile['semantic_image' if semantic else 'mapper_image'],
mounts, ['-B', '-c', entry], out, lambda: None, 1200,
gpu=semantic, executable='python3', environment=env, readonly=True)
journal.append(dict(group=name, stage=stage, seconds=time.monotonic()-started))
write_json(root/'journal.json', journal)
print('END', name, stage, round(journal[-1]['seconds'], 3), flush=True)
if group.get('map_file'):
shutil.copyfile(out/group['map_file'], out/'full-map.json')
locations[name] = out
previous = out
final = json.loads((previous/'full-map.json').read_text())
summary = dict(session=CONFIG['session'], published=False, cold_run=False,
prefix_job=CONFIG['original_job'], prefix_completed_stages=77,
tail_stages=journal, tail_seconds=sum(r['seconds'] for r in journal),
final_map=final, final_map_sha256=checksum(previous/'full-map.json'),
source_manifest=source_manifest['snapshot'], input_gaussian_sha256=source['sha256'])
write_json(root/'summary.json', summary)
print('SUMMARY', json.dumps({k:v for k,v in summary.items() if k not in ['final_map','tail_stages']}), flush=True)
except Exception:
for p in root.rglob('*.log'):
print('LOG', str(p), p.read_text(encoding='utf-8', errors='replace')[-2500:], flush=True)
raise
finally:
cleanup(marker)
if not json.loads(marker.read_text())['containers']:
marker.unlink()
if (root/'summary.json').exists():
p=root/'summary.json'
print('COLLECTION', json.dumps(dict(path=str(p),bytes=p.stat().st_size,sha256=checksum(p))), flush=True)
@@ -0,0 +1,92 @@
"""Replay a declared suffix against read-only fresh-candidate observations.
Engineering qualification only. This does not restore a production cache,
claim cold timing, or feed reference-map geometry to discovery.
"""
from pathlib import Path
import json,time,shutil
from infrastructure_containers import run_container
from infrastructure_pipeline import SEMANTIC_STAGES,prepare_layout,output_inventory
from infrastructure_sources import checksum
from local_state import write_json
def run(root,module,marker,profile,runtime,source,package,config):
reference=root.parent/config['replay_prefix']
assert checksum(reference/'summary.json')==config['replay_prefix_sha256']
proof=json.loads((reference/'summary.json').read_text())
assert proof['cold_run'] and proof['gaussian_sha256']==source['sha256']
original=reference/'run';output=root/'run'
definition,modules,snapshot=prepare_layout(output,module)
prior=json.loads((original/'source-manifest.json').read_text())
start=next(i for i,g in enumerate(definition['groups'])if g['group']==config.get('replay_from','paint_assembly'))
assert start>=3
prefix=definition['groups'][:start]
# Declare every changed producer rather than silently treating its outputs
# as those of the new implementation. They are fixed experimental inputs.
changed={rel for g in prefix for rel in g['files'].values()if prior['files'].get(rel)!=checksum(module/rel)}
write_json(root/'prefix-provenance.json',dict(session=reference.name,summary_sha256=config['replay_prefix_sha256'],
frozen_inputs_from_changed_producers=sorted(changed),cold_run=False,old_geometry_as_input=False))
locations={g['group']:original/('geometry'if g['group']=='base'else g['group'])for g in prefix}
previous=next(locations[g['group']]for g in reversed(prefix)if g.get('map_output',True)and g['group']!='base')
journal=[];started=time.monotonic()
def resolve(relative):
name,*parts=Path(relative).parts
return (locations[name]/Path(*parts))if name in locations else original/relative
for group in definition['groups'][start:]:
name=group['group'];out=output/name;out.mkdir(exist_ok=True)
assert not group.get('stage_outputs') and not group.get('extra_coverage')
if (previous/'crosswalk-standard-check.json').exists():shutil.copyfile(previous/'crosswalk-standard-check.json',out/'crosswalk-standard-check.json')
stages=group['stages'][:1]if name=='primary_search'and config.get('replay_primary_observations')else group['stages']
for stage in stages:
mounts=[(modules/name,'/candidate',True),(package,'/input',True),(original/'base-survey','/base_survey',True),
(original/'ortho','/ortho',True),(original/'ortho/survey','/survey',True),(original/'geometry','/base',True),
(original/'multiview','/multiview',True),(previous,'/fullplan',True),(out,'/out',False)]
for producer,alias in definition['aliases'].items():
if producer!=name and producer in locations:mounts.append((locations[producer],'/'+alias,True))
for destination,relative in group.get('input_files',{}).items():
mounts=[m for m in mounts if m[1]!=destination];mounts.append((resolve(relative),destination,True))
if stage in group.get('self_symbol_stages',[]):
mounts=[m for m in mounts if m[1]!='/symbolplan'];mounts.append((out,'/symbolplan',True))
for wheel in(module/'pipeline/vendor').glob('*.whl'):mounts.append((wheel,'/candidate/'+wheel.name,True))
semantic=stage in SEMANTIC_STAGES
if semantic:mounts.extend([(module.parents[1],'/release',True),(runtime/profile['semantic_model'],'/assets',True)])
env=dict(SCENE='scene',ORTHO_SCENE='scene',MV_MODEL='mapillary',PYTHONPATH='/candidate:/candidate/mapping:/release/simulation/ai-polygon',
OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HOME='/tmp/hf',
MPLCONFIGDIR='/tmp/matplotlib',XDG_CACHE_HOME='/tmp/cache',TORCH_HOME='/tmp/torch',WINDOW_SOURCE='/candidate/linear_window_support.py')
env.update(group.get('environment',{}))
entry='import runpy;'
if stage=='final_symbol_admission':entry+="import sys;sys.argv=['final_symbol_admission','/fullplan/full-map.json','/candidate/symbol_rules.py','/out'];"
entry+="runpy.run_path('/candidate/"+stage+".py',run_name='__main__')"
t=time.monotonic();print('BEGIN',name,stage,flush=True)
run_container(marker,name+'-'+stage,profile['semantic_image'if semantic else'mapper_image'],mounts,['-B','-c',entry],out,lambda:None,1200,
gpu=semantic,executable='python3',environment=env,readonly=True,resources=group.get('stage_resources',{}).get(stage))
receipt=dict(group=name,stage=stage,seconds=time.monotonic()-t,exit_code=0,snapshot=snapshot)
journal.append(receipt);write_json(out/(stage+'-execution.json'),receipt);write_json(root/'journal.json',journal)
print('END',name,stage,round(receipt['seconds'],3),flush=True)
if name=='primary_search'and config.get('replay_primary_observations'):
original_primary=original/'primary_search'
for filename in ['compact-seeds.json','catalog-proposals.json','crossing-seeds.json','observations.json']:
a=json.loads((out/filename).read_text());b=json.loads((original_primary/filename).read_text())
if isinstance(a,dict):a.pop('tile_reports',None);b.pop('tile_reports',None)
assert a==b,'Symbol observation inputs changed: '+filename
copied={}
for filename in ['symbol-patches.json','symbol-semantics.json','ground-observation-inventory.json','coverage-ledger.json']:
shutil.copy2(original_primary/filename,out/filename);copied[filename]=checksum(out/filename)
for folder in ['symbol-patches','symbol-masks']:
shutil.copytree(original_primary/folder,out/folder)
write_json(root/'reused-symbol-observations.json',dict(session=reference.name,reason='identical compact seeds, native observations and semantic proposal inputs',files=copied,cold_run=False))
locations[name]=out
if group.get('map_output',True):
if group.get('map_file'):shutil.copyfile(out/group['map_file'],out/'full-map.json')
previous=out;write_json(out/'group-inventory.json',dict(files=output_inventory(out)))
final=previous/'full-map.json'
summary=dict(session=root.name,cold_run=False,published=False,replay_prefix=reference.name,
prefix_summary_sha256=config['replay_prefix_sha256'],observation_run=original.as_posix(),
wall_seconds=time.monotonic()-started,stage_seconds=sum(r['seconds']for r in journal),completed_stages=len(journal),
source_snapshot=snapshot,gaussian_sha256=source['sha256'],poses_sha256=source['poses_sha256'],
final_map=json.loads(final.read_text()),final_map_sha256=checksum(final),receipts=journal,
reports={p.relative_to(output).as_posix():json.loads(p.read_text())for p in output.glob('*/*.json')
if p.name.endswith(('report.json','audit.json'))and p.stat().st_size<4*1024**2})
write_json(root/'summary.json',summary)
print('TAIL_COMPLETE',summary['wall_seconds'],len(journal),summary['final_map_sha256'],flush=True)
@@ -0,0 +1,243 @@
"""Frozen, artifact-owned control/candidate comparison on Worker 006."""
import base64
import datetime
import hashlib
import json
import shutil
import sys
import time
from pathlib import Path
CONFIG = globals()["CONFIG"]
sys.stdout.reconfigure(encoding="utf-8")
runtime = Path("D:/NDC_MISSIONCORE/runtime/simulation")
release = runtime / "releases" / ("ai-polygon-" + CONFIG["release"])
root = Path("C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications") / CONFIG["session"]
assert not root.exists(), "Session already exists"
assert not list((runtime / "state").glob("*active.json")), "Active simulation workflow"
assert shutil.disk_usage(root.parent).free > 40 * 1024**3
sys.path[:0] = [str(release / "simulation/ai-polygon"), str(release / "src")]
from infrastructure_containers import ( # noqa: E402 - installed release selected above
cleanup,
run_container,
)
from infrastructure_sources import checksum # noqa: E402 - installed release selected above
from local_state import write_json # noqa: E402 - installed release selected above
module = release / "simulation/urban-plan-research"
assert checksum(module / "pipeline/definition.json") == CONFIG["definition_sha256"]
profile = json.loads((module / "pipeline/worker-profile.json").read_text())
root.mkdir()
sources = root / "modules"
sources.mkdir()
for name, entry in CONFIG["files"].items():
assert Path(name).name == name
data = base64.b64decode(entry["content"])
assert hashlib.sha256(data).hexdigest() == entry["sha256"]
(sources / name).write_bytes(data)
for wheel in (module / "pipeline/vendor").glob("*.whl"):
(sources / wheel.name).touch()
write_json(
root / "manifest.json",
{k: v for k, v in CONFIG.items() if k != "files"}
| dict(
files={k: dict(source=v["source"], sha256=v["sha256"]) for k, v in CONFIG["files"].items()},
utc=datetime.datetime.now(datetime.UTC).isoformat(),
images=profile,
published=False,
),
)
marker = root / "active.json"
write_json(
marker,
dict(
key=hashlib.sha256(CONFIG["session"].encode()).hexdigest(),
owner=CONFIG["session"],
containers=[],
),
)
journal = []
def stage(name, entry, out, mounts=(), semantic=False):
out.mkdir(exist_ok=True, parents=True)
bindings = [(sources, "/candidate", True), (out, "/out", False), *mounts]
bindings += [
(p, "/candidate/" + p.name, True) for p in (module / "pipeline/vendor").glob("*.whl")
]
if semantic:
bindings += [
(release, "/release", True),
(runtime / profile["semantic_model"], "/assets", True),
]
env = dict(
SCENE="scene",
ORTHO_SCENE="scene",
PYTHONPATH="/candidate:/release/simulation/ai-polygon",
OPENBLAS_NUM_THREADS="3",
OMP_NUM_THREADS="3",
HF_HUB_OFFLINE="1",
TRANSFORMERS_OFFLINE="1",
HF_HOME="/tmp/hf",
MPLCONFIGDIR="/tmp/matplotlib",
XDG_CACHE_HOME="/tmp/cache",
TORCH_HOME="/tmp/torch",
SURVEY_EVIDENCE_INPUT="/input_evidence",
)
started = time.monotonic()
print("BEGIN", name, flush=True)
try:
run_container(
marker,
name,
profile["semantic_image" if semantic else "mapper_image"],
bindings,
["-B", "-c", entry],
out,
lambda: None,
2400,
gpu=semantic,
executable="python3",
environment=env,
readonly=True,
)
except Exception:
for p in out.glob("*.log"):
print(p.read_text(errors="replace")[-4500:], flush=True)
raise
journal.append(dict(stage=name, seconds=time.monotonic() - started))
write_json(root / "journal.json", journal)
print("END", name, round(journal[-1]["seconds"], 2), flush=True)
try:
if CONFIG.get("tests", True):
stage(
"tests",
"import unittest; r=unittest.TextTestRunner(verbosity=2).run("
"unittest.defaultTestLoader.loadTestsFromName('test_semantic_survey')); "
"assert r.wasSuccessful()",
root / "tests",
)
for spec in CONFIG["scenes"]:
ortho = Path(spec["ortho"])
case = root / spec["name"]
case.mkdir()
control = case / "control"
candidate = case / "candidate"
control.mkdir()
candidate.mkdir()
idx = json.loads((ortho / "survey/tile-index.json").read_text())
tiles = [t for t in idx["tiles"] if t["status"] == "surveyed"]
if spec.get("tile_limit"):
tiles = tiles[: spec["tile_limit"]]
write_json(case / "tile-index.json", {**idx, "tiles": tiles})
frozen = []
copies = []
for dest in [control, candidate]:
(dest / "ortho/evidence").mkdir(parents=True)
(dest / "layers").mkdir()
shutil.copyfile(ortho / "config.json", dest / "ortho/config.json")
try:
for tile in tiles:
for suffix in [".context.png", ".ground.png", ".ground-dc.geometry.npz"]:
src = ortho / "evidence" / (tile["id"] + suffix)
dst = control / "ortho/evidence" / src.name
digest = checksum(src)
shutil.copyfile(src, dst)
assert checksum(dst) == digest
frozen.append(dict(path=str(src), sha256=digest, bytes=src.stat().st_size))
copies.append(dst)
geo = ortho / "survey" / tile["id"] / "top.geometry.npz"
frozen.append(dict(path=str(geo), sha256=checksum(geo), bytes=geo.stat().st_size))
write_json(
case / "input-manifest.json",
dict(
files=frozen,
tile_index=checksum(case / "tile-index.json"),
config=checksum(ortho / "config.json"),
),
)
shared = [
(ortho / "survey", "/survey", True),
(case / "tile-index.json", "/survey/tile-index.json", True),
]
stage(
spec["name"] + "-control-surfaces",
"import runpy;runpy.run_path('/candidate/legacy_ortho_segment.py',"
"run_name='__main__')",
control / "ortho",
[
*shared,
(control / "ortho", "/run", False),
(control / "ortho/evidence", "/evidence", False),
],
True,
)
stage(
spec["name"] + "-control-layers",
"import runpy;runpy.run_path('/candidate/legacy_semantic_layers.py',"
"run_name='__main__')",
control / "layers",
[*shared, (ortho, "/ortho", True)],
True,
)
finally:
# Only this run's verified input copies; retain all newly computed evidence.
for p in copies:
p.unlink()
stage(
spec["name"] + "-shared",
"import semantic_survey_stage;semantic_survey_stage.run()",
candidate,
[
*shared,
(candidate / "ortho", "/run", False),
(candidate / "ortho/evidence", "/evidence", False),
(candidate / "layers", "/layers", False),
(ortho / "evidence", "/input_evidence", True),
],
True,
)
stage(
spec["name"] + "-compare",
"import compare_semantic_survey;compare_semantic_survey.run()",
case / "comparison",
[(control, "/control", True), (candidate, "/candidate_result", True)],
)
for row in frozen:
assert checksum(Path(row["path"])) == row["sha256"], "Input changed"
result = json.loads((case / "comparison/comparison.json").read_text())
print("COMPARISON", spec["name"], json.dumps(result), flush=True)
if CONFIG.get("consumer_comparison"):
sys.path.insert(0, str(sources))
import semantic_consumers
semantic_consumers.run(stage, root, runtime, release, profile, CONFIG)
finally:
cleanup(marker)
marker.unlink()
# Keep full evidence remotely, return bounded reports and execution receipts only.
collected = {}
for p in root.rglob("*"):
if (
p.is_file()
and p.suffix == ".json"
and "modules" not in p.parts
and p.stat().st_size < 2 * 1024**2
):
collected[p.relative_to(root).as_posix()] = json.loads(p.read_text())
write_json(root / "summary.json", collected)
print(
"COLLECTION",
json.dumps(
dict(
path=(root / "summary.json").as_posix(),
sha256=checksum(root / "summary.json"),
bytes=(root / "summary.json").stat().st_size,
)
),
flush=True,
)
@@ -0,0 +1,170 @@
"""Execute a frozen whole-pipeline candidate in an isolated Worker directory."""
from pathlib import Path
import base64,datetime,hashlib,json,shutil,sys,time
CONFIG=globals()['CONFIG'];sys.stdout.reconfigure(encoding='utf-8')
runtime=Path('D:/NDC_MISSIONCORE/runtime/simulation')
release=runtime/'releases'/('ai-polygon-'+CONFIG['release'])
root=Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications')/CONFIG['session']
assert not root.exists();assert not list((runtime/'state').glob('*active.json'))
assert shutil.disk_usage(root.parent).free>40*1024**3
sys.path.insert(0,str(release/'simulation/ai-polygon'))
from infrastructure_sources import checksum
from local_state import write_json
original=Path(CONFIG['original_job']);source=json.loads((original/'request.json').read_text())['source']
assert source['sha256']==CONFIG['gaussian_sha256']
package=runtime/'state/infrastructure-sources'/source['adapter_key']
assert checksum(package/source['ply'])==source['sha256']
assert checksum(package/'poses.json')==source['poses_sha256']
root.mkdir();artifact=root/'artifact';module=artifact/'simulation/urban-plan-research'
for name,item in CONFIG['files'].items():
path=Path(name)
assert not path.is_absolute()and '..'not in path.parts and '\\'not in name
data=base64.b64decode(item['content']);assert hashlib.sha256(data).hexdigest()==item['sha256']
target=artifact/path;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data)
sys.path.insert(0,str(artifact/'simulation/ai-polygon'))
from infrastructure_containers import run_container,cleanup
from infrastructure_pipeline import run_pipeline,prepare_layout
# Pinned immutable model-loading support and wheels from the installed release.
for rel in ['simulation/ai-polygon/sam3-research','simulation/urban-plan-research/pipeline/vendor']:
assert (release/rel).is_dir()
shutil.copytree(release/rel,artifact/rel)
profile=json.loads((module/'pipeline/worker-profile.json').read_text())
profile['maximum_stage_seconds']=1200;profile['maximum_seconds']=3600
marker=root/'active.json';write_json(marker,dict(key=hashlib.sha256(CONFIG['session'].encode()).hexdigest(),owner=CONFIG['session'],containers=[]))
manifest={k:v for k,v in CONFIG.items()if k!='files'}
manifest.update(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),cold_run=not CONFIG.get('preflight_only',False)and not CONFIG.get('replay_prefix')and not CONFIG.get('execution_only'),published=False,old_geometry_as_input=False,source_files={k:v['sha256']for k,v in CONFIG['files'].items()})
write_json(root/'manifest.json',manifest)
output=root/'run';output.mkdir();last=None;started=time.monotonic();execution_observer=None
def pulse():
global last
p=output/'progress.json'
if p.exists():
d=json.loads(p.read_text())
if d!=last:print('PROGRESS',json.dumps(d),flush=True);last=d
try:
# Runtime smoke exercises the new pure tile detectors on a frozen control
# observation. Its outputs are isolated and never inputs to the cold run.
definition,modules,snapshot=prepare_layout(output,module)
if CONFIG.get('execution_only'):
sys.path.insert(0,str(module/'evaluation'))
from qualify_stroke_execution import run as qualify_stroke_execution
checked=qualify_stroke_execution(root,modules,root.parent/CONFIG['execution_stroke_reference'],CONFIG['execution_stroke_reference_sha256'],marker,profile)
write_json(root/'summary.json',dict(session=root.name,cold_run=False,published=False,execution_only=True,stroke_execution=checked))
else:
if not CONFIG.get('qualified_preflight'):
smoke=root/'smoke';smoke.mkdir()
mounts=[(modules/'primary_search','/candidate',True),(original/'full_plan','/evidence_plan',True),
(original/'ortho/survey','/survey',True),(original/'ortho','/ortho',True),(smoke,'/out',False)]
code="""
import json,numpy as np
from pathlib import Path
from search_views import SearchViews
from paint_observations import collect as paint
from catalog_observations import collect as catalog
from compact_observations import collect as compact
from crossing_discovery import primitives
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds']
tiles=[t for t in json.loads(Path('/survey/tile-index.json').read_text())['tiles']if t['status']=='surveyed']
v=SearchViews(tiles,labels,low,high,None);t=tiles[len(tiles)//2];n=t['id'];g=v.geometry(n);rgb,vehicle=v.inputs(n)
with np.load('/evidence_plan/evidence/'+n+'.npz')as z:marking=z['road marking'];cross=z['crosswalk']
a,b=paint(rgb,vehicle,g,marking,cross,labels==1,low,high,t)
c=catalog(rgb,vehicle,g,labels,low,high,n);d=compact(rgb,vehicle,g,labels,low,high,n);e=primitives(rgb,cross,vehicle,g,labels,low,high)
print('SMOKE_OK',n,len(a),len(b),len(c),len(d),len(e))
"""
code=__import__('textwrap').dedent(code)
env=dict(PYTHONPATH='/candidate:/candidate/mapping',SCENE='scene',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3')
run_container(marker,'detector-smoke',profile['mapper_image'],mounts,['-B','-c',code],smoke,lambda:None,180,gpu=False,executable='python3',environment=env,readonly=True)
print('SMOKE_OK',flush=True)
# Reordering visibility work may improve I/O only; selected windows and
# pixels must match the previously qualified planner exactly.
fixture=Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/topdown-writer-queue-20261016101327/maroseyka')
plancheck=root/'plan-contract';plancheck.mkdir()
mounts=[(modules/'primary_search','/candidate',True),(module/'systematic/qualify_primary_plan.py','/qualify.py',True),
(fixture/'observations','/ortho',True),(fixture/'observations/native-geometry','/native_geometry',True),
(fixture/'survey','/reference-symbols',True),(plancheck,'/out',False)]
run_container(marker,'primary-plan-contract',profile['mapper_image'],mounts,['-B','/qualify.py'],plancheck,lambda:None,300,
gpu=False,executable='python3',environment=env,readonly=True)
print('PRIMARY_PLAN_CONTRACT_OK',flush=True)
sys.path.insert(0,str(module/'evaluation'))
from contract_preflight import run as preflight
checked=preflight(root,definition,modules,original,marker,profile,runtime,release,run_container,write_json)
unit=root/'initial-contract';unit.mkdir()
run_container(marker,'initial-observation-contract',profile['mapper_image'],[(modules/'primary_search','/candidate',True),(unit,'/out',False)],['-B','/candidate/qualify_initial_observations.py'],unit,lambda:None,90,gpu=False,executable='python3',environment=env,readonly=True)
print('INITIAL_OBSERVATION_CONTRACT_OK',flush=True)
crossing_unit=root/'crossing-fit-contract';crossing_unit.mkdir()
crossing_env={**env,'PYTHONPATH':'/candidate:/candidate/mapping'}
run_container(marker,'crossing-fit-contract',profile['mapper_image'],[(modules/'paint_assembly','/candidate',True),(crossing_unit,'/out',False)],['-B','/candidate/qualify_crossing_fit.py'],crossing_unit,lambda:None,90,gpu=False,executable='python3',environment=crossing_env,readonly=True)
print('CROSSING_FIT_CONTRACT_OK',flush=True)
stroke_unit=root/'stroke-contract';stroke_unit.mkdir()
run_container(marker,'stroke-contract',profile['mapper_image'],[(modules/'marking_pass','/candidate',True),(stroke_unit,'/out',False)],['-B','/candidate/qualify_strokes.py'],stroke_unit,lambda:None,90,gpu=False,executable='python3',environment=env,readonly=True)
print('STROKE_CONTRACT_OK',flush=True)
else:
qualified=root.parent/CONFIG['qualified_preflight']
prior=json.loads((qualified/'summary.json').read_text())
proof=json.loads((qualified/'manifest.json').read_text())
needed={relative for group in definition['groups'] if group['group']!='base' for relative in group['files'].values()}
needed.update(['evaluation/contract_preflight.py','systematic/qualify_primary_plan.py'])
for relative in needed:
name='simulation/urban-plan-research/'+relative
assert proof['source_files'][name]==CONFIG['files'][name]['sha256'], 'Preflight source changed: '+relative
assert (prior.get('preflight_only')or(prior.get('replay_prefix')and not prior['cold_run'])) and json.loads((qualified/'contracts/contract-report.json').read_text())['passed']
assert json.loads((qualified/'plan-contract/primary-plan-qualification.json').read_text())['passed']
checked=prior['contracts']
write_json(root/'reused-preflight.json',dict(session=qualified.name,summary_sha256=checksum(qualified/'summary.json'),
unchanged_contract_sources=len(needed),outputs_used_by_cold_run=False))
print('QUALIFIED_PREFLIGHT_REUSED',qualified.name,flush=True)
if CONFIG.get('preflight_only'):
concept=root/'concepts';concept.mkdir()
mounts=[(modules/'primary_search','/candidate',True),(release,'/release',True),(runtime/profile['semantic_model'],'/assets',True),(original/'uniform_search','/symbolplan',True),(concept,'/out',False)]
env=dict(PYTHONPATH='/candidate:/release/simulation/ai-polygon',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HOME='/tmp/hf',TORCH_HOME='/tmp/torch')
run_container(marker,'concept-qualification',profile['semantic_image'],mounts,['-B','/candidate/qualify_concept_decoding.py'],concept,lambda:None,180,gpu=True,executable='python3',environment=env,readonly=True)
execution=None
if CONFIG.get('execution_reference'):
from qualify_execution_reuse import run as qualify_execution
execution=qualify_execution(root,modules,root.parent/CONFIG['execution_reference'],CONFIG['execution_reference_sha256'],marker,profile,runtime,artifact,run_container,write_json)
stroke_execution=None
if CONFIG.get('execution_stroke_reference'):
from qualify_stroke_execution import run as qualify_stroke_execution
stroke_execution=qualify_stroke_execution(root,modules,root.parent/CONFIG['execution_stroke_reference'],CONFIG['execution_stroke_reference_sha256'],marker,profile)
summary=dict(session=CONFIG['session'],cold_run=False,preflight_only=True,contracts=checked,concepts=json.loads((concept/'concept-qualification.json').read_text()),execution_reuse=execution,stroke_execution=stroke_execution,published=False)
write_json(root/'summary.json',summary)
elif CONFIG.get('replay_prefix'):
sys.path.insert(0,str(module/'evaluation'))
from run_frozen_tail import run as replay_tail
replay_tail(root,module,marker,profile,runtime,source,package,CONFIG)
summary=json.loads((root/'summary.json').read_text());summary['contracts']=checked;write_json(root/'summary.json',summary)
else:
if CONFIG.get('profile_execution'):
sys.path.insert(0,str(module/'evaluation'))
import infrastructure_pipeline
from execution_profile import ExecutionProfile
execution_observer=ExecutionProfile(root,infrastructure_pipeline).start()
started=time.monotonic()
final,snapshot=run_pipeline(package,source,output,marker,profile,runtime,pulse,module=module)
elapsed=time.monotonic()-started
execution_profile=execution_observer.stop() if execution_observer else None
execution_observer=None
receipts=[dict(group=p.parent.name,**json.loads(p.read_text()))for p in output.glob('*/*-execution.json')]
reports={}
for p in output.glob('*/*.json'):
if p.name.endswith(('report.json','audit.json')) and p.stat().st_size<4*1024**2:reports[p.relative_to(output).as_posix()]=json.loads(p.read_text())
summary=dict(session=CONFIG['session'],cold_run=True,published=False,wall_seconds=elapsed,stage_seconds=sum(r['seconds']for r in receipts),completed_stages=len(receipts),source_snapshot=snapshot,gaussian_sha256=source['sha256'],poses_sha256=source['poses_sha256'],final_map=json.loads(final.read_text()),final_map_sha256=checksum(final),receipts=receipts,reports=reports,execution_profile=execution_profile)
write_json(root/'summary.json',summary)
print('COMPLETE',elapsed,len(receipts),checksum(final),flush=True)
except Exception:
for p in root.rglob('*-execution.json'):
try:
rec=json.loads(p.read_text())
if rec.get('exit_code'):print('FAILED_RECEIPT',p,json.dumps(rec),flush=True)
except Exception:pass
logs=sorted(root.rglob('*.log'),key=lambda p:p.stat().st_mtime)
for p in logs[-2:]:print('LOG',p,p.read_text(errors='replace')[-5000:],flush=True)
raise
finally:
if execution_observer is not None:execution_observer.stop()
cleanup(marker)
if not json.loads(marker.read_text())['containers']:marker.unlink()
if (root/'summary.json').exists():
p=root/'summary.json';print('COLLECTION',json.dumps(dict(path=p.as_posix(),bytes=p.stat().st_size,sha256=checksum(p))),flush=True)
@@ -0,0 +1,234 @@
"""Artifact-owned Worker006 qualification. CONFIG is injected by the local builder."""
from pathlib import Path
import base64
import datetime
import hashlib
import json
import shutil
import sys
import tarfile
import time
sys.stdout.reconfigure(encoding='utf-8')
runtime = Path('D:/NDC_MISSIONCORE/runtime/simulation')
release = runtime/'releases'/('ai-polygon-'+CONFIG['release'])
root = Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications')/CONFIG['session']
assert not root.exists(), 'Immutable session already exists'
assert not list((runtime/'state').glob('*active.json')), 'Active simulation workflow'
assert shutil.disk_usage(root.parent).free > 8*1024**3
sys.path[:0] = [str(release/'simulation/ai-polygon'), str(release/'src')]
from infrastructure_sources import checksum
from infrastructure_containers import run_container, cleanup
from local_state import write_json
module = release/'simulation/urban-plan-research'
assert checksum(module/'pipeline/definition.json') == CONFIG['definition_sha256']
profile = json.loads((module/'pipeline/worker-profile.json').read_text(encoding='utf-8'))
root.mkdir(); sources = root/'modules'; sources.mkdir()
for name, entry in CONFIG['files'].items():
assert Path(name).name == name
data = base64.b64decode(entry['content'])
assert hashlib.sha256(data).hexdigest() == entry['sha256']
(sources/name).write_bytes(data)
for wheel in (module/'pipeline/vendor').glob('*.whl'):
(sources/wheel.name).touch()
write_json(root/'manifest.json', {k:v for k,v in CONFIG.items() if k != 'files'} | dict(
files={k:dict(source=v['source'], sha256=v['sha256']) for k,v in CONFIG['files'].items()},
utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), monotonic=time.monotonic(),
images={k:profile[k] for k in ['mapper_image','semantic_image']}, published=False))
marker = root/'active.json'
write_json(marker, dict(key=hashlib.sha256(CONFIG['session'].encode()).hexdigest(),
owner=CONFIG['session'], containers=[]))
journal = []
def stage(name, entry, out, extra=(), semantic=False, timeout=1200, gpu=False):
out.mkdir(parents=True, exist_ok=True)
mounts = [(sources, '/candidate', True), (out, '/out', False)] + list(extra)
mounts += [(p, '/candidate/'+p.name, True) for p in (module/'pipeline/vendor').glob('*.whl')]
if semantic:
mounts += [(release, '/release', True), (runtime/profile['semantic_model'], '/assets', True)]
env = dict(SCENE='scene', ORTHO_SCENE='scene', PYTHONPATH='/candidate:/candidate/mapping:/release/simulation/ai-polygon',
OPENBLAS_NUM_THREADS='3', OMP_NUM_THREADS='3', HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1',
HF_HOME='/tmp/hf', MPLCONFIGDIR='/tmp/matplotlib', XDG_CACHE_HOME='/tmp/cache', TORCH_HOME='/tmp/torch')
begin = time.monotonic(); utc = datetime.datetime.now(datetime.timezone.utc).isoformat()
print('BEGIN', name, flush=True)
try:
run_container(marker, name, profile['semantic_image' if semantic else 'mapper_image'], mounts,
['-B', '-c', entry], out, lambda: None, timeout, gpu=semantic or gpu,
executable='python3', environment=env, readonly=True)
except Exception:
for log in out.glob('*.log'):
print(log.read_text(encoding='utf-8', errors='replace')[-7000:], flush=True)
raise
row = dict(stage=name, utc=utc, monotonic=begin, seconds=time.monotonic()-begin)
journal.append(row); write_json(root/'journal.json', journal)
print('END', name, round(row['seconds'], 2), flush=True)
try:
if CONFIG.get('prepared_mapper_runtime'):
prior=Path(CONFIG['prepared_mapper_runtime']);receipt=json.loads(prior.read_text())
assert receipt['base_image']==profile['mapper_image']
assert checksum(prior.parent/'gsplat_cuda.so')==receipt['compiled']['sha256']
from infrastructure_containers import docker
assert docker('image','inspect',receipt['image'],'--format','{{.Id}}').stdout.strip()==receipt['image']
profile['mapper_image']=receipt['image']
write_json(root/'effective-runtime.json',dict(mapper_image=profile['mapper_image'],semantic_image=profile['semantic_image']))
if CONFIG.get('queue_canary'):
sys.path.insert(0,str(sources))
import queue_worker_canary
canary=root/'queue-canary';canary.mkdir()
queue_worker_canary.run(canary,sources,release,profile)
if CONFIG.get('retire_mapper_builds'):
sys.path.insert(0,str(sources))
import retire_mapper_builds
retire_mapper_builds.run(CONFIG['prepared_mapper_runtime'],CONFIG['retire_mapper_builds'],root/'build-retention.json')
if CONFIG.get('runtime_probe'):
stage('runtime-probe', "import importlib.util,pathlib,json; p=pathlib.Path(importlib.util.find_spec('gsplat').origin).parent; print((p/'cuda/_backend.py').read_text())", root/'runtime-probe')
if CONFIG.get('precompile_mapper'):
# Owned one-time build artifact, excluded from per-location inference.
# Same upstream compiler flags and base image; only library packaging changes.
import subprocess,os
target=root/'mapper-runtime';target.mkdir()
compile_code="""import os,pathlib,json,hashlib,shutil,time
os.environ['TORCH_EXTENSIONS_DIR']='/out/extensions'
t=time.monotonic()
from gsplat.cuda._backend import _C
assert _C is not None
p=pathlib.Path(_C.__file__);shutil.copyfile(p,'/out/gsplat_cuda.so')
pathlib.Path('/out/compiled.json').write_text(json.dumps(dict(seconds=time.monotonic()-t,sha256=hashlib.sha256(p.read_bytes()).hexdigest(),architecture='8.9')))
"""
if CONFIG.get('compiled_runtime'):
prior=Path(CONFIG['compiled_runtime']);receipt=json.loads((prior/'compiled.json').read_text())
assert checksum(prior/'gsplat_cuda.so')==receipt['sha256']
assert json.loads((prior.parent/'manifest.json').read_text())['images']['mapper_image']==profile['mapper_image']
for filename in ['gsplat_cuda.so','compiled.json']:shutil.copyfile(prior/filename,target/filename)
else:
stage('mapper-runtime-compile',compile_code,target,gpu=True,timeout=900)
base_tag='ndc-mission-core-mapper-base:'+profile['mapper_image'].split(':')[1][:16]
subprocess.run(['docker','tag',profile['mapper_image'],base_tag],check=True)
assert subprocess.check_output(['docker','image','inspect',base_tag,'--format','{{.Id}}'],text=True).strip()==profile['mapper_image']
(target/'csrc.py').write_text("import importlib.util,sys\nspec=importlib.util.spec_from_file_location('gsplat_cuda','/opt/ndc/gsplat_cuda.so')\nmodule=importlib.util.module_from_spec(spec)\nspec.loader.exec_module(module)\nsys.modules[__name__]=module\n")
dockerfile="FROM "+base_tag+"\nLABEL com.nodedc.product=mission-core com.nodedc.stack=urban-mapping com.nodedc.role=prepared-mapper com.nodedc.managed-by=qualification-artifact\nCOPY gsplat_cuda.so /opt/ndc/gsplat_cuda.so\nCOPY csrc.py /opt/ndc/csrc.py\nRUN python3 -c \"import importlib.util,pathlib,shutil; p=pathlib.Path(importlib.util.find_spec('gsplat').origin).parent; assert not (p/'csrc.py').exists(); shutil.copyfile('/opt/ndc/csrc.py',p/'csrc.py')\"\n"
(target/'Dockerfile').write_text(dockerfile)
(target/'.dockerignore').write_text('*\n!Dockerfile\n!csrc.py\n!gsplat_cuda.so\n')
tag='ndc-mission-core-prepared-mapper:'+CONFIG['session']
result=subprocess.run(['docker','build','--network=none','--pull=false','-t',tag,str(target)],capture_output=True,text=True,timeout=120,env={**os.environ,'DOCKER_BUILDKIT':'0'})
(target/'build.log').write_text(result.stdout+result.stderr)
if result.returncode:raise RuntimeError('Prepared mapper image build failed')
image_id=subprocess.check_output(['docker','image','inspect',tag,'--format','{{.Id}}'],text=True).strip()
write_json(target/'runtime.json',dict(base_image=profile['mapper_image'],image=image_id,tag=tag,compiled= json.loads((target/'compiled.json').read_text())))
profile['mapper_image']=image_id
write_json(root/'effective-runtime.json',dict(mapper_image=image_id,semantic_image=profile['semantic_image']))
# A new read-only container has no compilation cache. Import must succeed
# directly through the packaged binary, not JIT or a previous session.
stage('mapper-runtime-check',"import pathlib,json; from gsplat.cuda._backend import _C; assert _C.__file__=='/opt/ndc/gsplat_cuda.so'; print('PRECOMPILED',_C.__file__)",root/'mapper-runtime-check',gpu=True)
if CONFIG.get('tests', True):
stage('tests', "import unittest; r=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromName('test_topdown')); assert r.wasSuccessful()", root/'tests')
if CONFIG.get('camera_tests'):
stage('camera-tests','import test_orthographic_colour; test_orthographic_colour.run()',root/'camera-tests',gpu=True)
for spec in CONFIG['scenes']:
name = spec['name']; ortho = Path(spec['ortho'])
assert ortho.is_dir()
scene = root/name
confirmed_mount=[]
if spec.get('confirmed_reference'):
scene.mkdir(parents=True,exist_ok=True)
data=base64.b64decode(spec['confirmed_reference']['content'])
assert hashlib.sha256(data).hexdigest()==spec['confirmed_reference']['sha256']
reference=scene/'confirmed-reference.json';reference.write_bytes(data)
confirmed_mount=[(reference,'/confirmed-reference.json',True)]
if spec.get('assemble_from'):
previous=Path(spec['assemble_from'])
stage(name+'-assemble','import assemble_reviewed_state; assemble_reviewed_state.run()',scene/'assembly',
[(Path(spec['base_map']),'/base-map.json',True),(previous/'reconstruction','/result',True),
(previous/'verification','/verification',True)]+confirmed_mount)
continue
geometry_mount=[]
if spec.get('render_parallel_observations'):
generated=scene/'observations'
stage(name+'-orthographic-observations','import render_native_geometry; render_native_geometry.run(parallel_rays=True)',generated,
[(ortho,'/ortho',True),(Path(spec['input']),'/input',True)],gpu=True,timeout=1800)
ortho=generated
geometry_mount=[(generated/'native-geometry','/native_geometry',True)]
elif spec.get('render_native_geometry'):
native=scene/'native-geometry'
stage(name+'-native-geometry', 'import render_native_geometry; render_native_geometry.run()',native,
[(ortho,'/ortho',True),(Path(spec['input']),'/input',True)],gpu=True,timeout=1800)
if spec.get('native_only'):continue
geometry_mount=[(native,'/native_geometry',True)]
elif spec.get('native_geometry'):
native=Path(spec['native_geometry']);assert json.loads((native/'native-geometry.json').read_text())['complete']
geometry_mount=[(native,'/native_geometry',True)]
if spec.get('conditional_contract_audit'):
stage(name+'-conditional-contract','import conditional_contract_audit; conditional_contract_audit.run('+repr(spec['focus_groups'])+')',scene/'conditional-contract',
[(ortho,'/ortho',True),(Path(spec['result']),'/result',True),(Path(spec['symbols']),'/symbolplan',True),
(Path(spec['depth_audit_path']),'/depth_audit',True)]+geometry_mount)
continue
if spec.get('pose_domain_audit'):
stage(name+'-pose-domain','import pose_domain_audit; pose_domain_audit.run('+repr(spec['focus_groups'])+')',scene/'pose-domain',
[(ortho,'/ortho',True),(Path(spec['result']),'/result',True),(Path(spec['symbols']),'/symbolplan',True)]+geometry_mount,timeout=900)
continue
if spec.get('endpoint_cause_audit'):
stage(name+'-endpoint-cause','import endpoint_cause_audit; endpoint_cause_audit.run('+repr(spec['focus_groups'][0])+')',scene/'endpoint-cause',
[(ortho,'/ortho',True),(Path(spec['result']),'/result',True),(Path(spec['symbols']),'/symbolplan',True),
(Path(spec['pose_audit']),'/pose_audit',True),(Path(spec['input']),'/input',True)]+geometry_mount,gpu=True,timeout=900)
continue
if spec.get('depth_audit'):
stage(name+'-depth-audit','import depth_audit; depth_audit.run('+repr(spec['tiles'])+')',scene/'depth-audit',
[(ortho,'/ortho',True),(Path(spec['input']),'/input',True)]+geometry_mount,gpu=True,timeout=900)
continue
if spec.get('feasibility_audit'):
stage(name+'-feasibility-audit','import feasibility_audit; feasibility_audit.run('+repr(spec['focus_groups'])+')',scene/'feasibility-audit',
[(ortho,'/ortho',True),(Path(spec['result']),'/result',True),(Path(spec['symbols']),'/symbolplan',True)]+geometry_mount,timeout=900)
continue
if spec.get('contract_audit'):
stage(name+'-contract-audit', 'import audit_contract; audit_contract.run(focus_groups='+repr(spec.get('focus_groups'))+')',scene/'contract-audit',
[(ortho,'/ortho',True),(Path(spec['result']),'/result',True),
(Path(spec['reference']),'/reference.json',True)]+geometry_mount)
continue
if CONFIG.get('audit') or spec.get('audit'):
stage(name+'-audit', "import audit_topdown; audit_topdown.audit()", scene/'audit',
[(ortho, '/ortho', True), (Path(spec['symbols']), '/symbolplan', True),
(Path(spec['result']), '/result', True), (Path(spec['reference']), '/reference.json', True)] + geometry_mount +
([(Path(spec['previous']), '/previous.json', True)] if spec.get('previous') else []))
continue
if spec.get('result'):
stage(name+'-verify', "import verify_topdown; verify_topdown.verify_result()", scene/'verification',
[(ortho, '/ortho', True), (Path(spec['symbols']), '/symbolplan', True),
(Path(spec['result']), '/result', True)] + confirmed_mount + geometry_mount +
([(Path(spec.get('preservation_base',spec['reference'])), '/reference.json', True)] if spec.get('reference') else []))
continue
if spec.get('symbols'):
symbols = Path(spec['symbols'])
else:
symbols = scene/'survey'
stage(name+'-survey', "import prepare_topdown; prepare_topdown.prepare('/out')", symbols,
[(ortho, '/ortho', True)]+geometry_mount)
stage(name+'-semantic', "import runpy; runpy.run_path('/candidate/semantic_symbols.py', run_name='__main__')", symbols, semantic=True)
extra = [(ortho, '/ortho', True), (symbols, '/symbolplan', True)]+geometry_mount
if spec.get('registry'):
extra.append((Path(spec['registry']), '/registry.json', True))
entry = "import reconstruct_topdown; reconstruct_topdown.run(registry_path=" + ("'/registry.json'" if spec.get('registry') else 'None') + ", focus_groups=" + repr(spec.get('focus_groups')) + ")"
stage(name+'-reconstruct', entry, scene/'reconstruction', extra, timeout=1800)
verify_mounts = [(ortho, '/ortho', True), (symbols, '/symbolplan', True), (scene/'reconstruction', '/result', True)]
if spec.get('reference'):
verify_mounts.append((Path(spec.get('preservation_base',spec['reference'])), '/reference.json', True))
stage(name+'-verify', "import verify_topdown; verify_topdown.verify_result()", scene/'verification', verify_mounts+confirmed_mount+geometry_mount)
finally:
for queue_marker in root.glob('queue-canary/queue-active.json'):
cleanup(queue_marker);queue_marker.unlink()
cleanup(marker)
marker.unlink()
files = [p for p in root.rglob('*') if p.is_file() and p.suffix in ['.json', '.log', '.png'] and 'symbol-patches' not in p.parts
and 'modules' not in p.parts and not (p.suffix=='.png' and 'observations' in p.relative_to(root).parts)
and p.stat().st_size < 20*1024**2]
write_json(root/'collection.json', {p.relative_to(root).as_posix(): checksum(p) for p in files})
files.append(root/'collection.json'); archive = root/'evidence.tgz'
with tarfile.open(archive, 'w:gz') as tar:
for p in files:
tar.add(p, arcname=p.relative_to(root).as_posix(), recursive=False)
print('COLLECTION', json.dumps(dict(path=archive.as_posix(), sha256=checksum(archive), bytes=archive.stat().st_size)), flush=True)
@@ -0,0 +1,38 @@
"""Numeric archive identity includes signed zeros, NaN bits and array layout."""
import importlib.util
import zipfile
from pathlib import Path
import numpy as np
import pytest
_path = Path(__file__).resolve().parents[1] / "systematic/array_archive.py"
_spec = importlib.util.spec_from_file_location("qualified_array_archive", _path)
_module = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_module)
def test_compression_changes_no_npy_payload_bits(tmp_path):
arrays = {
"float32": np.array([0, 0x80000000, 0x7FC00001, 0x7FC00123], np.uint32).view(np.float32),
"float16": np.array([0, -0.0, np.inf, -np.inf, np.nan], np.float16),
"fortran": np.asfortranarray(np.arange(24, dtype=np.float64).reshape(4, 6)),
"strided": np.arange(36, dtype=np.int16).reshape(6, 6)[::2, ::2],
"big_endian": np.arange(8, dtype=">f8"),
"empty": np.empty((0, 4), dtype=np.float32),
"scalar": np.array(True),
}
legacy, candidate = tmp_path / "legacy.npz", tmp_path / "candidate.npz"
np.savez_compressed(legacy, **arrays)
_module.save(candidate, **arrays)
with zipfile.ZipFile(legacy) as a, zipfile.ZipFile(candidate) as b:
assert a.namelist() == b.namelist()
assert all(a.read(name) == b.read(name) for name in a.namelist())
def test_archive_rejects_objects_and_escaped_member_names(tmp_path):
with pytest.raises(ValueError, match="Object arrays"):
_module.save(tmp_path / "objects.npz", value=np.array([object()], dtype=object))
with pytest.raises(ValueError, match="Invalid array key"):
_module.save(tmp_path / "escaped.npz", **{"../value": np.zeros(1)})
@@ -0,0 +1,43 @@
import hashlib
import json
from types import SimpleNamespace
from execution_profile import ExecutionProfile
def test_profiler_preserves_arguments_result_and_exception(tmp_path):
token = object()
calls = []
def run(*args, **kwargs):
calls.append((args, kwargs))
if kwargs.get("fail"):
raise ValueError("original failure")
return token
def checksum(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
pipeline = SimpleNamespace(run_container=run, checksum=checksum)
marker = tmp_path / "active.json"
marker.write_text(json.dumps(dict(key="abcdef0123456789abcd")))
payload = tmp_path / "data.bin"
payload.write_bytes(b"unchanged physical observations")
profile = ExecutionProfile(tmp_path, pipeline, interval=60).start()
try:
assert pipeline.run_container(marker, "stage", token, gpu=False) is token
assert calls[-1] == ((marker, "stage", token), dict(gpu=False))
assert pipeline.checksum(payload) == checksum(payload)
try:
pipeline.run_container(marker, "failed", fail=True)
except ValueError as error:
assert str(error) == "original failure"
else:
raise AssertionError("Profiler hid an original failure")
finally:
report = profile.stop()
assert pipeline.run_container is run and pipeline.checksum is checksum
assert report["sampler_stopped"]
assert [r["passed"] for r in report["stages"]] == [True, False]
assert report["orchestration_hashes"]["bytes"] == payload.stat().st_size
assert not report["numeric_functions_wrapped"]
@@ -0,0 +1,45 @@
from collections import Counter
import numpy as np
import pytest
from explain_run_metadata import exact, proposal_data
def test_exact_bank_comparison_rejects_float_and_array_bit_changes():
with pytest.raises(AssertionError):
exact(0.0, -0.0, Counter())
a = np.array([0.0, -0.0], dtype="float32")
b = np.array([0.0, 0.0], dtype="float32")
with pytest.raises(AssertionError):
exact(a, b, Counter())
with pytest.raises(AssertionError):
exact(a, a.astype("float64"), Counter())
def test_timing_separation_keeps_geometry_counts_and_field_order_exact():
def document(seconds=1.0, length=2.0, count=1):
return dict(lines=[dict(length=length)], tile_reports=[dict(
tile="tile-a", seconds=seconds, linear=count,
detectors={
k: seconds for k in ["linear", "appearance", "catalog", "compact", "crossing"]
},
)])
baseline, _ = proposal_data(document())
changed_time, _ = proposal_data(document(seconds=2.0))
exact(baseline, changed_time, Counter())
for changed in [document(length=2.000001), document(count=2)]:
physical, _ = proposal_data(changed)
with pytest.raises(AssertionError):
exact(baseline, physical, Counter())
with pytest.raises(AssertionError):
exact(dict(a=1, b=2), dict(b=2, a=1), Counter())
def test_unknown_or_invalid_timing_field_fails_closed():
with pytest.raises(AssertionError):
proposal_data(dict(tile_reports=[dict(tile="a", seconds=1.0, detectors={"quality": 0.9})]))
with pytest.raises(AssertionError):
proposal_data(dict(tile_reports=[dict(tile="a", seconds=float("nan"), detectors={
k: 1.0 for k in ["linear", "appearance", "catalog", "compact", "crossing"]
})]))
@@ -0,0 +1,41 @@
import zipfile
import numpy as np
from compare_frozen_runs import payload_digest
def test_packaging_changes_do_not_hide_or_create_a_numeric_difference(tmp_path):
source = tmp_path / "source.npz"
repacked = tmp_path / "repacked.npz"
changed = tmp_path / "changed.npz"
values = np.array([0x00000000, 0x80000000, 0x7FC00001], dtype="uint32").view("float32")
np.savez_compressed(source, values=values)
with zipfile.ZipFile(source) as original, zipfile.ZipFile(repacked, "w") as target:
for name in original.namelist():
target.writestr(name, original.read(name), compress_type=zipfile.ZIP_STORED)
assert source.read_bytes() != repacked.read_bytes()
assert payload_digest(source) == payload_digest(repacked)
different_bits = values.copy()
different_bits[1] = 0.0
np.savez_compressed(changed, values=different_bits)
np.testing.assert_array_equal(values, different_bits)
assert payload_digest(source) != payload_digest(changed)
def test_dtype_and_memory_order_remain_part_of_the_comparison(tmp_path):
a, b, c = [tmp_path / name for name in ["a.npz", "b.npz", "c.npz"]]
values = np.arange(12, dtype="float32").reshape(3, 4)
np.savez(a, values=values)
np.savez(b, values=values.astype("float64"))
np.savez(c, values=np.asfortranarray(values))
assert payload_digest(a) != payload_digest(b)
assert payload_digest(a) != payload_digest(c)
def test_archive_iteration_order_is_preserved(tmp_path):
a, b = tmp_path / "a.npz", tmp_path / "b.npz"
np.savez(a, road=np.arange(3), paint=np.arange(4))
with zipfile.ZipFile(a) as source, zipfile.ZipFile(b, "w") as target:
for name in reversed(source.namelist()):
target.writestr(name, source.read(name))
assert payload_digest(a) != payload_digest(b)