Files
ARCADIA-Studio/harness/experiments/navigation-native-440-20260913/raw/helpers/checkpoint-navigation-palette-20260913.py
T

172 lines
10 KiB
Python

"""Freeze one active-trial fixture, optionally compare its saved bytes and model.
No import-time execution. No UI, writer, build or Git action.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import traceback
import uuid
ROOT = Path(__file__).resolve().parent.parent
TRIAL = ROOT / '.local/native-qa/navigation-palette-20260913-01'
ENTRIES = {'source': 'project.arcadia', 'compact': 'project.arcadia',
'topology': 'project.arcadia', 'lifecycle': 'lifecycle-native.arcadia'}
RUNNER = ROOT / '.local/run-navigation-palette-oracle.py'
RUNNER_SHA = 'b1d56ec226d7b6d5d5d1d00e4bc8727c016e44a6208831ea8d35ae142c097288'
BUILD = ROOT / '.local/native-qa/navigation-oracle-e124029/build.json'
BUILD_SHA = '27ff0d612a5b9e4c378ae135745f266acfbf498af9f503d9e04f45ceed19a35a'
INTENT = TRIAL / 'source-rename-expected/intent.json'
INTENT_SHA = 'e15b26cda4e282643eb098d9ada6b0b2ade387957d5b7a49a67e28b78a05c88a'
PREPARATIONS = {
'preparation.json': '4ede523041af6367571e866f8d50d07befd12bbe8e96bf0c6a60230b58d6e156',
'source-example-preparation.json': 'd57250523090b40b81c07409fef99028d25903903d88a08d79842c6361d32c69'}
def require(ok, reason):
if not ok: raise RuntimeError(reason)
def identity(raw):
return {'bytes': len(raw), 'sha256': hashlib.sha256(raw).hexdigest()}
def ordinary(path):
require(path.is_absolute() and path.is_relative_to(ROOT), 'Path outside checkout')
for p in (path, *path.parents):
require(not p.is_symlink() and not p.is_junction(), 'Reparse path refused: ' + str(p))
return path
def tree(folder):
ordinary(folder); require(folder.is_dir(), 'Missing fixture tree')
files = {}; directories = []; payloads = {}
for path in sorted(folder.rglob('*')):
ordinary(path); relative = path.relative_to(folder).as_posix()
if path.is_dir(): directories.append(relative)
else:
require(path.is_file(), 'Non-file fixture member')
payloads[relative] = path.read_bytes(); files[relative] = identity(payloads[relative])
require(files, 'Empty fixture refused')
return {'directories': directories, 'files': files}, payloads
def save(path, value):
with path.open('x', encoding='utf-8', newline='\n') as stream:
json.dump(value, stream, indent=2); stream.write('\n')
def main():
require(sys.flags.optimize == 0 and __debug__, 'Optimized Python execution refused')
require(os.name == 'nt', 'Reviewed Windows trial only')
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('fixture', choices=ENTRIES)
parser.add_argument('label')
parser.add_argument('--mode', choices=('same', 'renamed', 'removed'))
parser.add_argument('--target')
parser.add_argument('--alias')
args = parser.parse_args()
require(re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9-]{0,63}', args.label), 'Unique simple label required')
require(bool(args.target) == (args.mode in ('renamed', 'removed')), 'Target required only for renamed/removed')
require(bool(args.alias) == (args.mode == 'renamed'), 'Alias required only for renamed')
if args.target: require(str(uuid.UUID(args.target)) == args.target, 'Canonical target UUID')
if args.alias: require(re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', args.alias), 'Alias token required')
work = ordinary(TRIAL / (args.fixture + '-work'))
baseline = ordinary(TRIAL / (args.fixture + '-baseline'))
entry = ENTRIES[args.fixture]
require((work / entry).is_file() and (baseline / entry).is_file(), 'Observed fixture entry missing')
label = 'checkpoint-' + args.fixture + '-' + args.label
destination = ordinary(TRIAL / 'checkpoints' / (args.fixture + '-' + args.label))
oracle_dir = ordinary(TRIAL / label)
require(not destination.exists() and not oracle_dir.exists(), 'Checkpoint/oracle label already exists')
require(destination.parent.is_dir(), 'Existing active trial checkpoints directory required')
destination.mkdir() # Exclusive; failed attempts are preserved, never removed or overwritten.
record = {'status': 'FAIL', 'started': datetime.now(timezone.utc).isoformat(),
'fixture': args.fixture, 'label': args.label, 'mode': args.mode,
'work': str(work), 'baseline_entry': str(baseline / entry),
'helper': identity(Path(__file__).read_bytes()),
'scope': 'Saved disk snapshot and optional comparator only; native actions are separate.'}
watched = {}
try:
record['baseline_before'], _ = tree(baseline)
prep = TRIAL / ('source-example-preparation.json' if args.fixture == 'source' else 'preparation.json')
prep_raw = ordinary(prep).read_bytes()
require(identity(prep_raw)['sha256'] == PREPARATIONS[prep.name], 'Original fixture preparation binding')
watched[str(prep)] = identity(prep_raw)
prefix = args.fixture + '-baseline/'
expected_baseline = {row['path'][len(prefix):]: {k: row[k] for k in ('bytes', 'sha256')}
for row in json.loads(prep_raw)['files'] if row['path'].startswith(prefix)}
require(expected_baseline and record['baseline_before']['files'] == expected_baseline, 'Exact prepared baseline file inventory/bytes')
record['before'], payloads = tree(work)
copied = destination / 'tree'; copied.mkdir()
for name in record['before']['directories']: (copied / name).mkdir()
for name, raw in payloads.items():
with (copied / name).open('xb') as stream: stream.write(raw)
record['copy'], _ = tree(copied)
record['after'], _ = tree(work)
require(record['before'] == record['copy'] == record['after'], 'Entire work inventory/bytes changed during snapshot')
if args.mode == 'same':
require(record['copy'] == record['baseline_before'], 'Exact baseline bytes and inventory required for same')
record['exact_baseline_bytes'] = True
if args.fixture == 'source' and args.mode == 'renamed':
raw = ordinary(INTENT).read_bytes(); require(identity(raw)['sha256'] == INTENT_SHA, 'Reviewed independent rename intent pin')
watched[str(INTENT)] = identity(raw); intent = json.loads(raw)
require(args.target == intent['target_uuid'] and args.alias == 'assess_report_union', 'Only independently prepared source rename admitted')
expected = ordinary(TRIAL / 'source-rename-expected/expected')
record['independent_expected'], _ = tree(expected)
rows = lambda key: {r['path']: {k: r[k] for k in ('bytes', 'sha256')} for r in intent[key]}
require(record['baseline_before']['files'] == rows('inputs'), 'Independent rename baseline binding')
require(record['independent_expected']['files'] == rows('expected'), 'Independent expected source binding')
require(record['copy'] == record['independent_expected'], 'Entire saved source equals independent six-token rename bytes')
record['exact_independent_rename_bytes'] = True
(destination / 'rename-intent.json').write_bytes(raw)
if args.mode:
for path, expected_sha in ((RUNNER, RUNNER_SHA), (BUILD, BUILD_SHA)):
actual = identity(ordinary(path).read_bytes()); require(actual['sha256'] == expected_sha, 'Reviewed oracle input pin')
watched[str(path)] = actual
command = [sys.executable, '-B', str(RUNNER), str(BUILD), label, args.mode,
str(baseline / entry), str(copied / entry)]
if args.target: command.append(args.target)
if args.alias: command.append(args.alias)
env = os.environ.copy(); env.pop('PYTHONOPTIMIZE', None)
with (destination / 'oracle-launch.stdout.log').open('xb') as out, (destination / 'oracle-launch.stderr.log').open('xb') as err:
run = subprocess.run(command, cwd=ROOT, env=env, stdin=subprocess.DEVNULL,
stdout=out, stderr=err, creationflags=subprocess.CREATE_NO_WINDOW)
record['oracle'] = {'command': command, 'exit': run.returncode, 'directory': str(oracle_dir)}
receipt_raw = (oracle_dir / 'run.json').read_bytes(); receipt = json.loads(receipt_raw)
record['oracle']['receipt'] = identity(receipt_raw)
(destination / 'oracle-run.json').write_bytes(receipt_raw)
require(run.returncode == 0 and receipt['exit'] == 0 and receipt['outcome'] == 'passed'
and receipt['failure'] is None and receipt['changed_inputs'] == [], 'Actual oracle failed or changed inputs')
record['status'] = 'PASS'
except Exception:
record['error'] = traceback.format_exc()
finally:
try:
record['final_work'], _ = tree(work)
record['final_baseline'], _ = tree(baseline)
if (destination / 'tree').is_dir(): record['final_copy'], _ = tree(destination / 'tree')
require(record['before'] == record['final_work'] == record['final_copy'], 'Final work/copy bytes or inventory changed')
require(record['baseline_before'] == record['final_baseline'], 'Baseline changed')
for path, wanted in watched.items(): require(identity(Path(path).read_bytes()) == wanted, 'Pinned input changed')
if 'independent_expected' in record:
final_expected, _ = tree(TRIAL / 'source-rename-expected/expected')
require(final_expected == record['independent_expected'], 'Independent expected source changed')
record['inputs_unchanged'] = True
except Exception:
record.update(status='FAIL', inputs_unchanged=False, final_error=traceback.format_exc())
record['watched_inputs'] = watched
record['finished'] = datetime.now(timezone.utc).isoformat()
save(destination / 'checkpoint.json', record)
print(json.dumps({'status': record['status'], 'checkpoint': str(destination)}))
return 0 if record['status'] == 'PASS' else 1
if __name__ == '__main__':
sys.exit(main())