Files
SkillFactory/tests/test_contact_cycle_repair.py
chenlin 9fe9d27865 feat: checkpoint contact-cycle evaluation and RootXY PPO progress
Consolidate next-stage docs, archive superseded narratives, and preserve frozen document inputs. Retain invalid P2 pairs, partial RootXY training, failed attempts and nonselectable checkpoints as explicit limitations.

Include supervised evaluation/training, desktop GPU admission, bounded evidence and atomic-publication monitor repairs with CPU regressions. Ignore local dotenv configuration.

Validation: 1403 passed, 6 skipped for contact-cycle and related contracts/CLI tests. Full-suite legacy ABI and registration tests require Python 3.12/Torch 2.10/pxr; no runtime checks relaxed. No new physical run or accepted skill.
2026-10-15 14:18:17 +08:00

173 lines
7.3 KiB
Python

"""Repair regression tests: fake clocks/physics signals; never robot optimization."""
import copy
import json
from pathlib import Path
import pytest
import torch
from SkillFactory.legs.contact_cycle.config import load_config, validate_config
from SkillFactory.legs.contact_cycle.mechanics import ContactLatch, SeparationLatch, WrenchSchedule
from SkillFactory.legs.contact_cycle.task import phase_objective
from SkillFactory.legs.contact_cycle.training import BudgetExceeded, BudgetLedger
ROOT = Path(__file__).resolve().parents[1]
def manifest():
return {"training": {"seeds": [1, 2, 3], "num_envs": 2, "horizon": 4, "updates_per_seed": 2048,
"max_total_transitions": 100, "max_total_wall_s": 100, "max_artifact_bytes": 100000}}
class Clocks:
wall, boot, boot_id = 1000., 100., "synthetic-boot"
def ledger(self, path):
return BudgetLedger(path, manifest(), lambda: self.wall, boot_now=lambda: self.boot, boot_id=self.boot_id)
def test_wall_corrections_do_not_change_deadline_or_refund_and_resume_counts_downtime(tmp_path):
c = Clocks()
with c.ledger(tmp_path) as b:
b.reserve_rollout(1, 1)
c.wall, c.boot = 900., 110. # UTC backwards, elapsed time forwards
b.guard()
assert b.data["clock"]["wall_rollbacks"] == 1
assert b.data["clock"]["last_wall_rollback"] == {"previous": 1000., "observed": 900., "boottime": 110.}
c.wall, c.boot = 1e9, 120. # forward wall step also cannot spend/extend boot-clock time
b.commit_update(1, 1)
assert b.data["clock"]["deadline_s"] == 200.
assert b.data["reserved_transitions"] == 8
c.wall, c.boot = 850., 190. # downtime (and suspend on Linux) is included
with c.ledger(tmp_path) as resumed:
assert resumed.data["clock"]["deadline_s"] == 200.
assert resumed.data["clock"]["wall_rollbacks"] == 2
assert resumed.data["updates"]["1"] == 1
c.boot = 200.
with pytest.raises(BudgetExceeded, match="wall-time.*boottime=200.*deadline=200"):
resumed.guard()
with pytest.raises(BudgetExceeded, match="wall-time"):
with c.ledger(tmp_path):
pass
@pytest.mark.parametrize("fault", ["reboot", "legacy", "deadline", "boot_rollback", "boot_nan", "wall_nan"])
def test_clock_faults_fail_closed_without_mutating_disk(tmp_path, fault):
c = Clocks()
with c.ledger(tmp_path) as b:
b.reserve_rollout(1, 1)
p = tmp_path/"budget.json"
value = json.loads(p.read_text())
if fault == "legacy":
del value["format"]
elif fault == "deadline":
value["clock"]["deadline_s"] += 1
elif fault == "reboot":
c.boot_id = "different-boot"
elif fault == "boot_rollback":
c.boot = 99.
elif fault == "boot_nan":
c.boot = float("nan")
else:
c.wall = float("nan")
p.write_text(json.dumps(value))
before = p.read_bytes()
with pytest.raises((ValueError, BudgetExceeded)):
with c.ledger(tmp_path):
pytest.fail("Invalid clock/ledger accepted")
assert p.read_bytes() == before
def test_live_boot_rollback_includes_observed_and_previous_values(tmp_path):
c = Clocks()
with c.ledger(tmp_path) as b:
c.boot = 99.
with pytest.raises(BudgetExceeded, match="observed=99.0, last=100.0, wall=1000.0"):
b.guard()
def latch(count=1):
return SeparationLatch(count, "cpu", on=0.001, off=0.0005, dwell=0.01)
def test_zero_load_is_not_liftoff_then_geometric_lift_delivers_full_pulse():
sep, load = latch(), ContactLatch(1, "cpu")
config = load_config(ROOT/"configs/contact_cycle/go2_fl_v1.json")
e = copy.deepcopy(config["events"][1])
schedule = WrenchSchedule([e], 1, "cpu")
edges, load_edges = [], []
for tick in range(601):
t = 3.8 + tick*0.002
phase = torch.tensor([1 if t < 4 else 2 if t < 4.6 else 3])
fn = torch.tensor([50. if t < 3.9 else 0.])
off, on = load.update(fn, 0.002)
# Remains on the plane after Fn drops below threshold; separates only during lift.
gap = torch.tensor([0. if t < 4.05 else 0.002])
edge = sep.update(gap, load.contact, phase, 0.002)
if off.item():
load_edges.append(t)
if edge.item():
edges.append(t)
schedule.step(torch.tensor([t]), phase, edge, on, torch.tensor([2]), 0.002, sep.edge_phase)
assert len(load_edges) == len(edges) == 1 and load_edges[0] < 4 < edges[0]
assert not sep.premature.any()
assert schedule.fired.all() and schedule.completed.all()
torch.testing.assert_close(schedule.integral, torch.tensor([[e["duration_s"]-e["ramp_s"]]]), atol=0.002, rtol=0)
def test_early_separation_straddling_phase_boundary_cannot_be_laundered_into_event():
sep = latch(2)
yes, no = torch.ones(2, dtype=torch.bool), torch.zeros(2, dtype=torch.bool)
sep.update(torch.zeros(2), yes, torch.ones(2, dtype=torch.long), 0.002)
for k in range(5):
phase = torch.tensor([1 if k == 0 else 2, 2])
edge = sep.update(torch.full((2,), 0.002), no, phase, 0.002)
assert edge.all() and sep.edge_phase.tolist() == [1, 2]
assert sep.premature.tolist() == [True, False]
cfg = load_config(ROOT/"configs/contact_cycle/go2_fl_v1.json")
b = WrenchSchedule([cfg["events"][1]], 2, "cpu")
b.step(torch.full((2,), 4.006), phase, edge, no, torch.full((2,), 2), 0.002, sep.edge_phase)
assert b.fired[:, 0].tolist() == [False, True]
for _ in range(10):
sep.update(torch.zeros(2), yes, phase, 0.002)
assert sep.premature.tolist() == [True, False] # grounding again cannot hide failure
sep.reset(torch.tensor([1]))
assert sep.premature.tolist() == [True, False]
sep.reset(torch.tensor([0]))
assert not sep.premature.any() and not sep.armed.any() and (sep.edge_phase == -1).all()
def test_gap_hysteresis_blip_and_unarmed_initial_flight():
s = latch()
yes, no, phase = torch.tensor([True]), torch.tensor([False]), torch.tensor([2])
for _ in range(5):
assert not s.update(torch.tensor([0.003]), no, phase, 0.002).any()
s.reset(torch.tensor([0]))
s.update(torch.zeros(1), yes, phase, 0.002)
for _ in range(4):
assert not s.update(torch.tensor([0.002]), no, phase, 0.002).any()
s.update(torch.zeros(1), yes, phase, 0.002) # sub-dwell excursion does not commit
assert not s.separated.any()
for _ in range(5):
edge = s.update(torch.tensor([0.002]), no, phase, 0.002)
assert edge.all()
for _ in range(20):
assert not s.update(torch.tensor([0.00075]), no, phase, 0.002).any()
assert s.separated.all()
def test_unload_reward_prefers_zero_load_on_plane_not_early_flight():
zero, phase = torch.zeros(2), torch.ones(2, dtype=torch.long)
reward, _ = phase_objective(phase, torch.full((2,), 0.98), torch.tensor([0., 0.005]),
torch.tensor([0., 0.005]), zero, zero, zero, zero, torch.full((2,), 50.))
assert reward[0] == 1 and reward[1] < 0.5
@pytest.mark.parametrize("key,value", [("separation_off_m", 0.001), ("separation_on_m", float("nan")),
("dwell_s", 0), ("unload_tracking_scale_m", True)])
def test_transition_config_rejected(key, value):
c = load_config(ROOT/"configs/contact_cycle/go2_fl_v1.json")
c["contact_transition"][key] = value
with pytest.raises(ValueError):
validate_config(c)