Files
SkillFactory/tests/test_contact_cycle_sim_config_preimports.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

358 lines
18 KiB
Python

"""CPU-only runner import phase: actual pinned string/configclass source, no Kit.
File-backed isolated test packages are fixtures only, never runtime substitutes.
The configclass dictionary conversion helpers are disabled as in binding tests.
"""
import ast
import dataclasses
import enum
import functools
import inspect
import sys
from pathlib import Path
from types import MappingProxyType, SimpleNamespace
from typing import ClassVar
import pytest
from test_contact_cycle_sim_evaluation_binding import binding, load
from test_contact_cycle_sim_evaluation_runner import cli
@pytest.fixture
def sources(tmp_path, monkeypatch):
installed = binding.ISAAC_ROOT
root = tmp_path / 'source/isaaclab/isaaclab'
for name, path in [('isaaclab', root), ('isaaclab.utils', root / 'utils')]:
path.mkdir(parents=True, exist_ok=True)
(path / '__init__.py').write_text('')
load(name, path / '__init__.py', monkeypatch)
for leaf in ('string', 'configclass'):
name = 'isaaclab.utils.' + leaf
relative, digest = binding.ISAAC_PINS[name]
text = (installed / relative).read_text()
assert binding.sha256(text.encode()) == digest
if leaf == 'configclass':
text = text.replace('from .dict import class_to_dict, update_class_from_dict',
'class_to_dict = update_class_from_dict = None')
path = root / 'utils' / (leaf + '.py')
path.write_text(text)
load(name, path, monkeypatch)
monkeypatch.setattr(binding, 'ISAAC_ROOT', tmp_path)
return SimpleNamespace(root=root, installed=installed,
rs=sys.modules['isaaclab.utils.string'].ResolvableString,
configclass=sys.modules['isaaclab.utils.configclass'].configclass)
def test_preimport_config_references_real_configclass_nested_no_cache_mutation(sources, monkeypatch):
@sources.configclass
class Nested:
references = {'nested': ['isaaclab.utils.string:to_snake_case',
('isaaclab.utils.string:to_camel_case',)]}
@dataclasses.dataclass(slots=True)
class Slotted:
nested: object
schema: ClassVar = sources.rs('isaaclab.utils.string:string_to_slice')
config = Slotted(Nested())
assert cli.stored_config_fields(config) == binding._config_fields(config)
refs = cli.config_references(config, binding)
before = [object.__getattribute__(r, '_resolved_callable') for r in refs]
imported = []
original = cli.importlib.import_module
def eager(name):
imported.append(name)
return original(name)
monkeypatch.setattr(cli.importlib, 'import_module', eager)
report = cli.preimport_config_references(config, binding)
assert imported == ['isaaclab.utils.string']
assert len(report['references']) == 3
path = sources.root / 'utils/string.py'
assert report['modules'] == {'isaaclab.utils.string': {
'path': str(path), 'sha256': binding.sha256(path.read_bytes())}}
assert [object.__getattribute__(r, '_resolved_callable') for r in refs] == before == [None] * 3
assert all(object.__getattribute__(r, '_resolve_error') is None for r in refs)
# The unchanged normalizer owns cache writes, not the eager import phase.
for obj, field, value in binding._reference_updates(config):
setattr(obj, field, value)
assert all(object.__getattribute__(r, '_resolved_callable') is not None for r in refs)
names = set()
binding._encode(refs, names, set())
assert 'isaaclab.utils.string' in names # enters the unchanged source/dependency closure
def test_config_references_actual_installed_material_cfg_strings(sources):
path = sources.installed / 'source/isaaclab/isaaclab/sim/spawners/materials/physics_materials_cfg.py'
tree = ast.parse(path.read_text())
reference = next(n.value for n in ast.walk(tree) if isinstance(n, ast.Constant)
and n.value == '{DIR}.physics_materials:spawn_rigid_body_material')
cls = type('MaterialCfg', (), {'__module__': 'isaaclab.sim.spawners.materials.physics_materials_cfg',
'__annotations__': {'func': str}, 'func': reference})
material = sources.configclass(cls)()
assert cli.config_references({'scene': [material]}, binding) == [material.func]
assert type(material.func) is sources.rs
assert str(material.func) == 'isaaclab.sim.spawners.materials.physics_materials:spawn_rigid_body_material'
assert object.__getattribute__(material.func, '_resolved_callable') is None
def test_config_references_all_encoder_containers_and_plain_strings(sources):
ref = sources.rs('isaaclab.utils.string:to_snake_case')
class Mode(enum.Enum):
VALUE = ref
value = MappingProxyType({'partial': functools.partial(str, ref, value=ref),
'slice': slice(ref), 'enum': Mode.VALUE,
'plain': 'outside.module:never_import', 'path': Path('/unused')})
assert len(cli.config_references(value, binding)) == 4
@pytest.mark.parametrize('bad', ['no_colon', 'x:y:z', ':name', 'a..b:name', 'a/b:name',
'a.b:with.dot', 'a.b:bad()', 'lambda x: x'])
def test_preimport_config_references_malformed_before_any_import(sources, monkeypatch, bad):
monkeypatch.setattr(cli.importlib, 'import_module', lambda _: pytest.fail('must not import'))
with pytest.raises(ValueError, match='Unsupported ResolvableString'):
cli.preimport_config_references([sources.rs('isaaclab.utils.string:to_snake_case'), sources.rs(bad)], binding)
@pytest.mark.parametrize('kind', ['cycle', 'unsupported', 'mapping_key', 'nonfinite', 'subclass'])
def test_preimport_config_references_invalid_graph_before_any_import(sources, monkeypatch, kind):
value = [sources.rs('isaaclab.utils.string:to_snake_case')]
if kind == 'cycle':
value.append(value)
elif kind == 'unsupported':
value.append(object())
elif kind == 'mapping_key':
value.append({1: 'bad'})
elif kind == 'nonfinite':
value.append(float('nan'))
else:
class FakeString(str):
pass
value.append(FakeString('isaaclab.utils.string:to_snake_case'))
monkeypatch.setattr(cli.importlib, 'import_module', lambda _: pytest.fail('must not import'))
with pytest.raises(ValueError):
cli.preimport_config_references(value, binding)
def test_preimport_config_references_rejects_property_without_evaluation(sources):
@dataclasses.dataclass
class Config:
field: object = None
cfg = Config()
del cfg.field
Config.field = property(lambda _: pytest.fail('property must not run'))
with pytest.raises(ValueError, match='descriptor'):
cli.preimport_config_references(cfg, binding)
@pytest.mark.parametrize('reference', ['os:system', 'isaaclab_evil.module:call', 'numpy:array'])
def test_preimport_config_references_external_requires_inventory(sources, monkeypatch, reference):
monkeypatch.setattr(cli.importlib, 'import_module', lambda _: pytest.fail('must not import'))
with pytest.raises(ValueError, match='explicit external inventory'):
cli.preimport_config_references(sources.rs(reference), binding)
def test_preimport_config_references_absent_module(sources):
with pytest.raises(ModuleNotFoundError, match='Missing installed config module') as caught:
cli.preimport_config_references(sources.rs('isaaclab.utils.absent:run'), binding)
assert caught.value.name == 'isaaclab.utils.absent'
@pytest.mark.parametrize('error', [ModuleNotFoundError('transitive', name='broken_dependency'),
ImportError('native failure')])
def test_preimport_config_references_import_failure_surfaces_unchanged(sources, monkeypatch, error):
def broken(_):
raise error
monkeypatch.setattr(cli.importlib, 'import_module', broken)
ref = sources.rs('isaaclab.utils.string:to_snake_case')
with pytest.raises(type(error)) as caught:
cli.preimport_config_references(ref, binding)
assert caught.value is error
assert object.__getattribute__(ref, '_resolved_callable') is None
assert object.__getattribute__(ref, '_resolve_error') is None
def test_preimport_config_references_imports_not_previously_loaded_module(sources, monkeypatch):
# A real source-backed CPU fixture whose function must never execute.
path = sources.root / 'utils/new_target.py'
path.write_text('from isaaclab.utils.string import to_snake_case\n'
'def spawn():\n raise AssertionError("must not execute")\n')
monkeypatch.delitem(sys.modules, 'isaaclab.utils.new_target', raising=False)
try:
ref = sources.rs('isaaclab.utils.new_target:spawn')
report = cli.preimport_config_references(ref, binding)
assert report['modules']['isaaclab.utils.new_target']['path'] == str(path)
module = sys.modules['isaaclab.utils.new_target']
assert inspect.isfunction(module.spawn)
assert module.to_snake_case is sys.modules['isaaclab.utils.string'].to_snake_case
assert object.__getattribute__(ref, '_resolved_callable') is None
finally:
sys.modules.pop('isaaclab.utils.new_target', None)
@pytest.mark.parametrize('mutation', ['path', 'package_search', 'cached_error', 'cached_conflict', 'not_callable'])
def test_preimport_config_references_identity_and_cache_fail_closed(sources, monkeypatch, mutation):
ref = sources.rs('isaaclab.utils.string:to_snake_case')
module = sys.modules['isaaclab.utils.string']
if mutation == 'path':
monkeypatch.setattr(module, '__file__', '/not/the/installed/source.py')
elif mutation == 'package_search':
monkeypatch.setattr(sys.modules['isaaclab.utils'], '__path__', ['/outside'])
elif mutation == 'cached_error':
ref._resolve_error = ValueError('prior failure')
elif mutation == 'cached_conflict':
ref._resolved_callable = str
else:
monkeypatch.setattr(module, 'to_snake_case', object())
with pytest.raises((ValueError, FileNotFoundError)):
cli.preimport_config_references(ref, binding)
def test_real_runtime_preimports_before_unchanged_normalizer():
source = inspect.getsource(cli.real_runtime)
assert source.index('preimport_config_references(cfg, binding)') < source.index('binding.normalize_config(cfg)')
assert source.count('binding.normalize_config(cfg)') == 1
def test_stored_config_fields_inherited_slots_extra_fields_and_properties(sources):
@dataclasses.dataclass
class Parent:
field: object
@property
def unrelated(self):
pytest.fail('unrelated property must not run')
class Child(Parent):
__slots__ = ('extra', 'uninitialized', '__private')
cfg = Child(sources.rs('isaaclab.utils.string:to_snake_case'))
cfg.extra = sources.rs('isaaclab.utils.string:to_camel_case')
cfg.dynamic = {'nested': cfg.field}
assert cli.stored_config_fields(cfg) == binding._config_fields(cfg)
assert len(cli.config_references(cfg, binding)) == 3
def test_preimport_config_references_real_transitive_failure_no_cache_write(sources, monkeypatch):
path = sources.root / 'utils/broken_target.py'
path.write_text('import missing_config_transitive_dependency\n')
monkeypatch.delitem(sys.modules, 'isaaclab.utils.broken_target', raising=False)
ref = sources.rs('isaaclab.utils.broken_target:spawn')
with pytest.raises(ModuleNotFoundError) as caught:
cli.preimport_config_references(ref, binding)
assert caught.value.name == 'missing_config_transitive_dependency'
assert object.__getattribute__(ref, '_resolved_callable') is None
assert object.__getattribute__(ref, '_resolve_error') is None
assert 'isaaclab.utils.broken_target' not in sys.modules
def test_preimport_config_references_explicit_dependency_role(sources, tmp_path, monkeypatch):
from test_contact_cycle_sim_evaluation_binding import numerical_inventory
for name in tuple(sys.modules):
if name.split('.')[0] in binding.NUMERICAL_ROOTS:
monkeypatch.delitem(sys.modules, name)
numerical_inventory(tmp_path, monkeypatch)
dependency_path = tmp_path / 'config_dependency.py'
dependency_path.write_text('def helper():\n raise AssertionError("must not execute")\n')
dependency = load('_config_reference_dependency', dependency_path, monkeypatch)
monkeypatch.setattr(binding, 'REQUIRED_RUNTIME', {**binding.REQUIRED_RUNTIME,
dependency.__name__: ('config-callable-provider', str(dependency_path),
binding.sha256(dependency_path.read_bytes()))})
path = sources.root / 'utils/target.py'
path.write_text('from _config_reference_dependency import helper\n'
'def spawn():\n raise AssertionError("must not execute")\n')
load('isaaclab.utils.target', path, monkeypatch)
ref = sources.rs('isaaclab.utils.target:spawn')
report = cli.preimport_config_references(ref, binding)
monkeypatch.setattr(binding, '_sources', lambda *_: ({}, set()))
# Only isolate unrelated installed-pin source scanning; retain real encoder,
# explicit dependency roles and the inventory validator.
captured = set()
def imported(names, _, *, diagnostics=None):
captured.update(names)
return {name: {'path': str(binding._module_file(name))} for name in names}
monkeypatch.setattr(binding, '_imports', imported)
proposal = cli.proposed_inventory(binding, ref)
assert set(report['modules']) <= captured
assert proposal['modules'][dependency.__name__] == {
'path': str(dependency_path), 'sha256': binding.sha256(dependency_path.read_bytes())}
assert binding._dependency_inventory(proposal, captured, set()) == proposal
@pytest.mark.parametrize('eye,lookat', [((1.2, 1.2, 1), (0, 0, .1672991751785088)),
((-2, 3, 4), (.2, .3, .4))])
def test_preforward_video_recorder_matches_pinned_constructor_idempotently(eye, lookat):
path = binding.ISAAC_ROOT / 'source/isaaclab/isaaclab/envs/manager_based_rl_env.py'
assert binding.sha256(path.read_bytes()) == 'a963cfcdb4cd60955cd022ed709d27c99a6935685b69180bb29d74f8983f6566'
tree = ast.parse(path.read_text())
constructor = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == '__init__')
forwarding = next(n for n in constructor.body if isinstance(n, ast.If)
and ast.unparse(n.test) == 'cfg.video_recorder is not None')
cfg = SimpleNamespace(viewer=SimpleNamespace(eye=eye, lookat=lookat),
video_recorder=SimpleNamespace(env_render_mode='rgb_array', eye=(7.5,) * 3,
lookat=(0.,) * 3))
checked = []
cli.preforward_video_recorder(cfg, SimpleNamespace(verify_installed_stepping=lambda p: checked.append(p)))
assert checked == [path.parent]
before = vars(cfg.video_recorder).copy()
assert before == {'env_render_mode': None, 'eye': tuple(map(float, eye)), 'lookat': tuple(map(float, lookat))}
# Execute only the installed forwarding AST, never instantiate Isaac/Kit.
exec(compile(ast.Module(body=[forwarding], type_ignores=[]), str(path), 'exec'),
{'cfg': cfg, 'render_mode': None})
assert vars(cfg.video_recorder) == before
cli.preforward_video_recorder(cfg, SimpleNamespace(verify_installed_stepping=lambda _: None))
assert vars(cfg.video_recorder) == before
cfg.viewer.eye = (9., 8., 7.)
# No after-the-fact normalization: real binding detects changed recorder config.
exec(compile(ast.Module(body=[forwarding], type_ignores=[]), str(path), 'exec'),
{'cfg': cfg, 'render_mode': None})
assert vars(cfg.video_recorder) != before
def test_preimport_constructor_modules_exact_diagnosed_sources(monkeypatch):
import json
path = Path('/home/cen/sf-runs/p1-01/row0-binding-diagnostics.json')
if not path.exists():
pytest.skip('P1 diagnostic not installed')
differences = json.loads(path.read_bytes())['distinct_diagnostic']['differences']
expected = {d['path'].removeprefix('/imports/'): d['actual']['value'] for d in differences
if d['path'].startswith('/imports/')}
assert len(expected) == 23
assert {k: (v['path'], v['sha256']) for k, v in expected.items()} == cli.CONSTRUCTOR_IMPORT_PINS
imported = []
monkeypatch.setattr(cli.importlib, 'import_module', lambda name: imported.append(name))
monkeypatch.setattr(binding, '_module_file', lambda name: Path(expected[name]['path']))
monkeypatch.setattr(cli, 'config_module_path', lambda name, _: Path(expected[name]['path']))
assert cli.preimport_constructor_modules(binding) == expected
assert imported == list(expected)
@pytest.mark.parametrize('drift', ['hash', 'resolved_path', 'imported_path', 'missing', 'transitive_failure'])
def test_preimport_constructor_modules_fail_closed(monkeypatch, tmp_path, drift):
path = tmp_path / 'reviewed.py'
path.write_text('reviewed = True\n')
name = 'isaaclab.reviewed'
monkeypatch.setattr(cli, 'CONSTRUCTOR_IMPORT_PINS', {name: (str(path), binding.sha256(path.read_bytes()))})
monkeypatch.setattr(cli, 'config_module_path', lambda *_: path if drift != 'resolved_path' else tmp_path)
monkeypatch.setattr(binding, '_module_file', lambda _: path if drift != 'imported_path' else tmp_path)
def eager(_):
if drift == 'transitive_failure':
raise ModuleNotFoundError('unexpected lazy dependency')
monkeypatch.setattr(cli.importlib, 'import_module', eager)
if drift == 'hash':
path.write_text('changed = True\n')
if drift == 'missing':
path.unlink()
with pytest.raises((ValueError, FileNotFoundError, ModuleNotFoundError)):
cli.preimport_constructor_modules(binding)