Skip to content

Validate typed presets resolve against their backend during Hydra resolution - #5944

Merged
ooctipus merged 2 commits into
isaac-sim:developfrom
ooctipus:fix/hydra
Jun 6, 2026
Merged

ooctipus merged 2 commits into
isaac-sim:developfrom
ooctipus:fix/hydra

Conversation

@ooctipus

@ooctipus ooctipus commented Jun 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

alternative to #5939

  • Selecting a typed preset (e.g. presets=newton_mjwarp) on a task that does not declare that name on a PhysicsCfg/RendererCfg previously created a silent mixed configuration: the name would match an unrelated scalar/sensor preset that happens to share the name, tuning those fields while leaving the real backend (e.g. PhysX) untouched. This adds a post-resolution check that a selected reserved typed name actually landed on a config of its own type at least once, and raises a clear ValueError otherwise.
  • The set of reserved canonical names is declared per typed target in PresetTarget (preset_target.py) — PHYSICS = {newton_mjwarp, newton_kamino}, plus the known renderer backends. New solvers/renderers opt in by adding their name there; the resolver hardcodes nothing. physx/ovphysx are intentionally not reserved (PhysX is the default backend, so selecting it on a task without a physics preset is harmless rather than a silent mismatch).
  • Implementation is minimal: one typed_hits: set[str] threaded through _pick_alternative/_resolve_active_presets records when a reserved name resolves to a value of its target type; _validate_typed_presets then flags reserved-selected ∩ consumed − typed_hits. Truly-unknown names continue to flow to the existing "Unknown preset(s)" error path.

Behavior

Invocation Result
Isaac-Velocity-Flat-Anymal-C-v0 presets=newton_mjwarp resolves (lands on NewtonCfg)
Isaac-Navigation-Flat-Anymal-C-v0 presets=newton_mjwarp ValueError (no Newton physics; only matched a sensor/scalar)
Isaac-Navigation-Flat-Anymal-C-v0 presets=physx resolves (PhysX not reserved, benign)
Isaac-Navigation-Flat-Anymal-C-v0 presets=newton_kamino "Unknown preset(s)" (unchanged path)
legacy alias presets=newton on navigation ValueError (canonicalized to newton_mjwarp)

Test plan

  • ./isaaclab.sh -p -m pytest source/isaaclab_tasks/test/core/test_hydra.py (added 7 regression tests for the validator + end-to-end resolution; full file passes)
  • test_preset_cli.py, test_newton_solver_preset_names.py, test_preset_kit_decision.py pass
  • Config-resolution probes for the table above
  • pre-commit (ruff/format/codespell/rst/license) green
  • CI

A changelog fragment is included under source/isaaclab_tasks/changelog.d/.

@ooctipus
ooctipus requested a review from Mayankm96 as a code owner June 3, 2026 22:48
@github-actions github-actions Bot added bug Something isn't working isaac-lab Related to Isaac Lab team labels Jun 3, 2026

@isaaclab-review-bot isaaclab-review-bot Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Code Review — PR #5944

Validate typed presets resolve against their backend during Hydra resolution


Summary

Good, focused fix that closes a real silent-failure gap: selecting a backend-specific preset (e.g. newton_mjwarp) on a task whose configs only re-use that name for unrelated scalars/sensors would previously succeed while leaving the actual physics backend unchanged. The approach — threaded typed_hits set + post-resolution validation — is minimal and fits cleanly into the existing resolver flow.

This is a proper alternative to #5939, with a more general design (declared per-target rather than hardcoded in the resolver).


✅ Strengths

  1. Clean separation of concerns — PresetTarget owns the list of reserved names and their target types; the resolver only threads a set and calls a validator. Adding new typed targets requires zero resolver changes.
  2. Comprehensive test coverage — 7 new tests covering: happy path, silent-mix rejection, unconsumed-name passthrough, unreserved names, legacy alias canonicalization, and two end-to-end integration tests. Good edge-case thinking.
  3. Correct PhysX carve-out — explicitly not reserving physx/ovphysx since those are the default backend and asking for them is benign.
  4. Changelog fragment included — well-written rst, references the right classes/modules.

🟡 Suggestions & Observations

1. Set-expression precedence in _validate_typed_presets (minor correctness risk)

missing = sorted({i for raw in selected for i in [aliases.get(raw, raw)] if i in reserved} & consumed - typed_hits)

Python evaluates & before -, so this reads as (...) & (consumed - typed_hits). That happens to be correct here (the intent is reserved_selected ∩ consumed − typed_hits), but the lack of parentheses makes it easy to misread. Consider explicit grouping for clarity:

missing = sorted(({i for raw in selected for i in [aliases.get(raw, raw)] if i in reserved} & consumed) - typed_hits)

Same semantics, but makes the intent unambiguous for future readers.

2. Trailing space in error message

"The name only matched unrelated presets, which would silently mix backends. "

Minor: the trailing space before the closing quote is probably unintentional. Tests match on "silently mix backends" so they won't break either way, but it's a cosmetic nit.

3. RENDERER preset names declared but no test coverage

The RENDERER target now declares {"newton_renderer", "isaacsim_rtx_renderer", "ovrtx_renderer"}, but all tests only exercise PHYSICS targets. Consider adding at least one unit-level test calling _validate_typed_presets with a renderer name + RendererCfg miss to confirm the generalization works end-to-end for non-physics targets.

4. functools.cache on classmethod — Python 3.11 interaction

@classmethod @functools.cache stacking is fine on 3.9+ but the cache never invalidates (which is correct here since enum members are immutable). Worth a one-line comment noting the cache is safe precisely because preset_names is a frozen set assigned at class-construction time — saves future contributors from wondering.

5. Consider a frozenset for PresetTarget.PHYSICS declaration

The preset_names argument is currently passed as a mutable set literal {"newton_mjwarp", "newton_kamino"} in the enum member definition. While __new__ immediately wraps it in frozenset(), declaring it as frozenset({"newton_mjwarp", "newton_kamino"}) at the call site would signal immutability intent earlier and match the type annotation.


🔒 Safety & Error Handling

  • The validation runs after full resolution, so it cannot leave the config in a half-resolved state.
  • Unknown names still fall to the existing "Unknown preset(s)" error — no regression there.
  • The ValueError message is actionable: it names the offending presets and their expected target types.

CI Status

Pre-commit passes ✅. Docker/installation checks are still pending. No blocking failures observed.


Verdict

Well-structured fix for a subtle and dangerous silent failure. The suggestions above are minor improvements — none are blocking. Solid work, @ooctipus.


🔄 Update (71d080e — 2025-06-03)

New commits add an import-hygiene cleanup (moving eager submodule imports from __init__.py into .pyi stubs for isaaclab.envs and isaaclab.sensors.ray_caster). This is unrelated to the typed-preset validation logic and looks correct — no new issues.

Previous suggestions (set-expression parenthesization, trailing space, renderer test coverage, etc.) remain open — all non-blocking, deferring to author's judgment.

No new concerns. Review stance unchanged.

@greptile-apps

greptile-apps Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a post-resolution guard that prevents a silent backend mismatch when a user selects a "typed" preset name (e.g. newton_mjwarp, reserved for Newton physics) on a task that only declares that name on an unrelated scalar or sensor preset. A typed_hits set is threaded through _pick_alternative and _resolve_active_presets to record when a reserved name actually lands on a config of its own backend type; _validate_typed_presets then raises a descriptive ValueError when a reserved name was consumed but never hit its typed backend.

  • preset_target.py: PresetTarget enum members gain an optional preset_names set (e.g. {\"newton_mjwarp\", \"newton_kamino\"} for PHYSICS), plus a cached reserved_preset_targets() class method that inverts the sets into a flat {name → target} lookup.
  • hydra.py: _pick_alternative tracks reserved-name hits via isinstance on the immediate alternative value; _validate_typed_presets (new) raises when a reserved name was consumed but had no typed hit; register_task wires both through the existing env/agent resolution calls.
  • test_hydra.py: Seven new tests cover the happy path, the error path, legacy alias canonicalization, unconsumed names, and end-to-end _resolve_active_presets recording.

Confidence Score: 4/5

Safe to merge for all practical task configurations; the one edge case (reserved name mapping to a nested intermediate PresetCfg rather than directly to a PhysicsCfg) does not occur in current tasks but would produce a false-positive ValueError if introduced later.

The validation logic correctly handles the primary use cases — reserved physics/renderer names that only land on scalars or sensors — and the test suite covers the main paths including legacy alias canonicalization. The typed_hits check evaluates the immediate field value inside _pick_alternative rather than the final value returned by resolve_chain, so a physics preset that chains through an intermediate PresetCfg would not register a hit and validation would incorrectly reject a valid configuration. This is a latent issue, not a current breakage in the existing task library.

The typed-hit tracking block in _pick_alternative (lines 318-322 of hydra.py) deserves a second look for the chained-PresetCfg scenario.

Important Files Changed

Filename Overview
source/isaaclab_tasks/isaaclab_tasks/utils/hydra.py Core change: adds typed_hits set threading through _pick_alternative and _resolve_active_presets, plus new _validate_typed_presets function; the typed-hit check uses the immediate alternative value (not the final chain-resolved value), which can produce a false-positive error when a reserved name resolves through an intermediate PresetCfg.
source/isaaclab_tasks/isaaclab_tasks/utils/preset_target.py Adds preset_names field to the PresetTarget enum tuple and a cached reserved_preset_targets() class method; logic and design are clean.
source/isaaclab_tasks/test/core/test_hydra.py Seven new regression tests cover pass/fail paths, legacy alias canonicalization, unconsumed names, unreserved defaults, and end-to-end recording; no renderer-specific end-to-end test is included.
source/isaaclab_tasks/changelog.d/fix-hydra-typed-preset-validation.rst Accurate changelog fragment describing the fix; no issues.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["register_task()\nglobal_presets=['newton_mjwarp']"] --> B["_resolve_active_presets(env_cfg)"]
    B --> C{PresetCfg node found?}
    C -->|yes| D["_pick_alternative(preset_obj, selected)"]
    D --> E{"reserved name?\nreserved_preset_targets().get(name)"}
    E -->|yes| F{"isinstance(val, target.base_classes)?"}
    F -->|yes| G["typed_hits.add(name)"]
    F -->|no| H["(not recorded as typed hit)"]
    G --> I["consumed_selected.add(name)"]
    H --> I
    E -->|no| I
    I --> C
    C -->|no more| J["unknown_presets check\n(existing path)"]
    J --> K["_validate_typed_presets(global_presets, consumed, typed_hits)"]
    K --> L{"reserved & consumed\n- typed_hits != empty?"}
    L -->|yes| M["ValueError: 'never applied to physics config'"]
    L -->|no| N["return env_cfg, agent_cfg"]
Loading

Reviews (1): Last reviewed commit: "fix hydra issue" | Re-trigger Greptile

Comment on lines +565 to +566
f"Selected preset(s) {', '.join(missing)} never applied to a '{targets}' config for this task. "
"The name only matched unrelated presets, which would silently mix backends. "

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Trailing space after the period in the second string fragment of the error message. The extra space produces a sentence that ends with "backends. " (space after the full stop), which will appear in user-facing tracebacks and makes the message slightly awkward.

Suggested change
f"Selected preset(s) {', '.join(missing)} never applied to a '{targets}' config for this task. "
"The name only matched unrelated presets, which would silently mix backends. "
f"Selected preset(s) {', '.join(missing)} never applied to a '{targets}' config for this task. "
"The name only matched unrelated presets, which would silently mix backends."

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +318 to +322
if typed_hits is not None:
# mark a reserved typed name (e.g. newton_mjwarp) that landed on its own backend type
target = PresetTarget.reserved_preset_targets().get(name)
if target is not None and isinstance(val, target.base_classes):
typed_hits.add(name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Typed-hit recorded on intermediate value, not final resolved value

val = fields[name] is the direct field value from the current PresetCfg, but resolve_chain can loop and resolve that value further if it is itself a PresetCfg. When a reserved name maps to an intermediate PresetCfg (rather than directly to a PhysicsCfg), isinstance(val, target.base_classes) is False, so nothing is added to typed_hits — even though the chain will ultimately settle on a valid physics config. _validate_typed_presets then raises a ValueError for a configuration that is actually correct. A task that nests its physics preset one level deeper (e.g. newton_mjwarp: IntermPreset { default: NewtonCfg() }) would trigger this false positive. Moving the isinstance check to after resolve_chain returns — or tracking the resolved value inside resolve_chain — would close the gap.

Comment on lines +68 to +69
{"newton": "newton_mjwarp", "kamino": "newton_kamino"},
{"newton_mjwarp", "newton_kamino"},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this can reuse the values for legacy alias assuming it's 1 to 1. @AntoineRichard also suggested the legacy ones could be dropped as they might not be used yet?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To some extent, I don't think we can rely on fixed naming. It might need to be discovery based on PhysicsCfg(PresetCfg). So consuming typed presets might be needed. Otherwise, we would need to hardcode all names here. Legacy names does not enforce name but provides a alias.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree we should not hard code any naming

@ooctipus
ooctipus requested a review from kellyguo11 as a code owner June 4, 2026 00:11
if token == PresetTarget.DOMAIN.value:
global_presets.extend(v.strip() for v in val.split(",") if v.strip())
elif token in typed_labels:
for name in (v.strip() for v in val.split(",") if v.strip()):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so it looks like multiple targets are accepted for typed presets, but it will fail later?

Comment on lines +598 to 610
typed_labels = {target.value: target for target in PresetTarget if target.base_classes}
global_presets: list[str] = []
requested_targets: dict[PresetTarget, set[str]] = {}
override_items: list[tuple[str, str, str]] = []
hydra_args: list[str] = []
for arg in sys.argv[1:]:
if "=" not in arg:
hydra_args.append(arg)
continue
key, val = arg.split("=", 1)
if key.lstrip("-") == "presets":
token = key.lstrip("-")
if token == PresetTarget.DOMAIN.value:
global_presets.extend(v.strip() for v in val.split(",") if v.strip())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still lets presets=newton_mjwarp / presets=newton act as untyped broadcasts, so they can hit only scalar or sensor presets and leave PhysX active. Could we carry typed intent for the legacy Newton names even when they arrive through presets=?

That keeps ordinary domain broadcasts (presets=depth, presets=inference, etc.) unchanged, but makes the deprecated aliases and their canonical replacements go through the existing _validate_typed_presets() check.

Suggested change
typed_labels = {target.value: target for target in PresetTarget if target.base_classes}
global_presets: list[str] = []
requested_targets: dict[PresetTarget, set[str]] = {}
override_items: list[tuple[str, str, str]] = []
hydra_args: list[str] = []
for arg in sys.argv[1:]:
if "=" not in arg:
hydra_args.append(arg)
continue
key, val = arg.split("=", 1)
if key.lstrip("-") == "presets":
token = key.lstrip("-")
if token == PresetTarget.DOMAIN.value:
global_presets.extend(v.strip() for v in val.split(",") if v.strip())
typed_labels = {target.value: target for target in PresetTarget if target.base_classes}
legacy_typed_targets = {
name: target
for target in PresetTarget
if target.base_classes
for alias, replacement in target.legacy_aliases.items()
for name in (alias, replacement)
}
global_presets: list[str] = []
requested_targets: dict[PresetTarget, set[str]] = {}
override_items: list[tuple[str, str, str]] = []
hydra_args: list[str] = []
for arg in sys.argv[1:]:
if "=" not in arg:
hydra_args.append(arg)
continue
key, val = arg.split("=", 1)
token = key.lstrip("-")
if token == PresetTarget.DOMAIN.value:
for name in (v.strip() for v in val.split(",") if v.strip()):
global_presets.append(name)
target = legacy_typed_targets.get(name)
if target is not None:
requested_targets.setdefault(target, set()).add(name)

I'd also add regression coverage for presets=newton_mjwarp and presets=newton on a config where the name only appears on an unrelated scalar preset; both should raise the same way physics=newton_mjwarp does.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I discussed with @ooctipus yesterday. I think the main problem to also check the presets path is that we need to know the exact names that corresponds to the type, e.g. newton_mjwarp -> physics, which will need to be hardcoded. It's the standard convention in the repo, but might not be something used by users, where they can define anything.

The existing way tried to avoid that by going the discovery path: for the target class, the typed presets target must be resolved properly, then it can be broadcasted to the rest of the cfg tree.

@ooctipus ooctipus Jun 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you have two options there:
1.hard code the preset string then presets= behave the same way as physics=

2.zero hard code string, accept presets= as the dangerous path, and recommend user to use physics= for typing protected path.

current implementation does 2. which I think makes sense. 1. could also make sense then you would need to maintain a set of strings, and those set of strings won't protect the user's custom physics engine either.

@AntoineRichard AntoineRichard left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just tried ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Navigation-Flat-Anymal-C-v0 presets=newton_mjwarp on this branch and it does not raise as expected. ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Navigation-Flat-Anymal-C-v0 --physics=newton_mjwarp raised as expected. ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Navigation-Flat-Anymal-C-v0 --physics=newton raised. ./isaaclab.sh -p scripts/reinforcement_learning/skrl/train.py --task Isaac-Navigation-Flat-Anymal-C-v0 presets=newton did not raise. See suggested change

@ooctipus
ooctipus merged commit 8bbb038 into isaac-sim:develop Jun 6, 2026
60 of 61 checks passed
@ooctipus
ooctipus deleted the fix/hydra branch June 6, 2026 01:23
kellyguo11 added a commit that referenced this pull request Jun 7, 2026
… imports fixes, Newton 1.2.1rc2 pin (#6014)

# Description

Cherry pick fixes from develop:

- #5990 
- #5944 
- #5973
- #5935 
- #5948 
- #5932 
- #5966 
- #5927

---------

Signed-off-by: matthewtrepte <[email protected]>
Co-authored-by: sameerchavan0027 <[email protected]>
Co-authored-by: matthewtrepte <[email protected]>
Co-authored-by: Mustafa H <[email protected]>
Co-authored-by: Antoine Richard <[email protected]>
Co-authored-by: ooctipus <[email protected]>
Co-authored-by: mingxueg <[email protected]>
hujc7 added a commit to hujc7/IsaacLab that referenced this pull request Jun 9, 2026
Reconcile two conflicts from develop (45 commits):

- scripts/reinforcement_learning/rsl_rl/train.py: keep the --frontend=warp
  lazy-import build path; drop the branch-local fold_preset_tokens() call in
  favor of develop's verbatim remaining_args. isaac-sim#5944 reworked setup_preset_cli
  to resolve physics=/presets= tokens during Hydra resolution, so folding is
  no longer needed and the function was removed upstream.
- isaaclab_tasks_experimental .../direct/cartpole/__init__.py: keep the branch
  deletion (cartpole moved under core/); develop made no substantive change to
  the old-location file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants