"""Synthetic/CPU qualification of functional-only runtime wiring and budgets.""" import copy import importlib.util import json import sys from pathlib import Path from types import ModuleType, SimpleNamespace import pytest import torch ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'scripts')) import functional_flow_launch_v2 as launch @pytest.fixture def recording(monkeypatch): name = '_functional_recording_test' directory = ROOT / 'source/SkillFactory/SkillFactory/tasks/manager_based/contact_cycle_sim' parent = ModuleType(name) parent.__path__ = [str(directory)] monkeypatch.setitem(sys.modules, name, parent) dummy = ModuleType(name + '.recording') dummy.SimCycleRecorder = object monkeypatch.setitem(sys.modules, name + '.recording', dummy) if 'SkillFactory' not in sys.modules: package = ModuleType('SkillFactory') package.__path__ = [str(ROOT / 'source/SkillFactory/SkillFactory')] monkeypatch.setitem(sys.modules, 'SkillFactory', package) spec = importlib.util.spec_from_file_location(name + '.functional_flow_recording_v2', directory / 'functional_flow_recording_v2.py') mod = importlib.util.module_from_spec(spec) monkeypatch.setitem(sys.modules, spec.name, mod) spec.loader.exec_module(mod) return mod def frames(local_tick): result = [] for tick in range(1, local_tick + 1): load = 50 if tick < 1500 else 25 if tick < 2000 else 0 travel = max(0, min(1, (tick - 2300) / 700)) xy = torch.tensor([[travel * .025, travel * .02, .02]]) result.append({'normal': torch.tensor([[0., 0., load]]), 'weight': torch.tensor([50.]), 'foot': xy, 'target': xy.clone(), 'gap': torch.tensor([.04])}) return result def recorder_with_frames(mod, n): cfg = json.loads((ROOT / 'configs/contact_cycle/functional_flow_v2.json').read_text()) r = mod.FunctionalFlowRecorder(cfg, None, lambda: None) r.capture = SimpleNamespace(frames=frames(n)) return r def test_phase_windows_do_not_need_full_cycle(recording): r = recorder_with_frames(recording, 1499) event = SimpleNamespace(clock=SimpleNamespace(local_tick=1499, cycle_index=0)) assert r._window_checks(event) == () r.capture.frames = frames(1999) event.clock.local_tick = 1999 assert r._window_checks(event) == () r.capture.frames = frames(2999) event.clock.local_tick = 2999 assert r._window_checks(event) == () @pytest.mark.parametrize('fault', ['support', 'unload', 'airless', 'static_xy']) def test_first_failed_phase_window_stops(recording, fault): n = {'support': 1499, 'unload': 1999}.get(fault, 2999) r = recorder_with_frames(recording, n) r.support_load = 1. if fault == 'support': for f in r.frames: f['normal'].zero_() elif fault == 'unload': for f in r.frames: f['normal'][0, 2] = 50 elif fault == 'airless': for f in r.frames: f['gap'].zero_() else: for f in r.frames: f['foot'] = torch.zeros(1, 3) event = SimpleNamespace(clock=SimpleNamespace(local_tick=n, cycle_index=0)) assert r._window_checks(event) def test_reverse_swing_is_signed_not_absolute(recording): r = recorder_with_frames(recording, 2999) for f in r.frames: f['target'] *= -1 f['foot'] *= -1 event = SimpleNamespace(clock=SimpleNamespace(local_tick=2999, cycle_index=0)) assert r._window_checks(event) == () def test_tensor_fingerprints_are_copied_and_exact(recording): value = torch.tensor([[1., 2.]]) before = recording.tensor_identity(value) assert before == recording.tensor_identity(value.clone()) value[0, 0] += .000001 assert before != recording.tensor_identity(value) def test_continuity_rejects_missing_seam_and_pose_writes(recording): r = recorder_with_frames(recording, 13500) r.initial_counters = {k: 0 for k in recording.COUNTERS} r.cycles = [{'audit': {'sim_functional_passed': True}}] * 3 h = SimpleNamespace(**{k: 0 for k in recording.COUNTERS}, violations=[]) h.rollout_steps = 13500 stop = SimpleNamespace(reason='protocol_complete', causes=()) assert not r.continuity(stop, h, 3)['runtime_continuity_verified'] r.seams = [{'same_carried_state': True, 'single_refresh': True}] * 2 assert r.continuity(stop, h, 3)['runtime_continuity_verified'] h.pose_write_calls = 1 assert not r.continuity(stop, h, 3)['runtime_continuity_verified'] def test_guard_deadline_reserves_cleanup_and_never_grants_physics(tmp_path, monkeypatch): monkeypatch.setattr(launch.b, 'boot_id', lambda: 'boot') monkeypatch.setattr(launch.b, 'boottime', lambda: 100.) g = launch.Guard(tmp_path, 100, 700) g.check() monkeypatch.setattr(launch.b, 'boottime', lambda: 580.) with pytest.raises(RuntimeError, match='deadline'): g.check() g.check(cleanup=True) monkeypatch.setattr(launch.b, 'boottime', lambda: 700.) with pytest.raises(RuntimeError): g.check(cleanup=True) def test_guard_all_publications_check_exact_pending_bytes(tmp_path, monkeypatch): monkeypatch.setattr(launch.b, 'boot_id', lambda: 'boot') monkeypatch.setattr(launch.b, 'boottime', lambda: 100.) g = launch.Guard(tmp_path, 100, 700) g.check() with pytest.raises(RuntimeError, match='storage'): g.check(launch.CAP) def test_no_old_authorization_routes_or_new_training(): source = (ROOT / launch.SCRIPT).read_text() assert 'launch.approval(' in source assert 'RuntimeHooks' in source assert 'before_physics' in source assert "row['success']" in source and 'break # first failure' in source assert 'train_cycle' not in source and 'optimizer.step' not in source assert 'prepare_binding(' not in source # old P1 binding cannot admit new task assert len(launch.SLOTS) == 5 assert sum(c * 4500 for _, c, _ in launch.SLOTS) == 36000 def test_approval_source_drift_rejected_before_root_created(tmp_path, monkeypatch): root = tmp_path / 'new-campaign' approval = tmp_path / 'approval.json' approval.write_text(json.dumps({'format': launch.FORMAT, 'artifact_root': str(root)})) import hashlib digest = hashlib.sha256(approval.read_bytes()).hexdigest() with pytest.raises(PermissionError): launch.approval(approval, digest, root) assert not root.exists()