Repository navigation
[Fix] Surface the real error when environment construction fails, instead of an AttributeError from __del__ - #7373
Conversation
The environment destructors read `_is_closed` unconditionally. A subclass may run fallible setup before delegating to the base `__init__` that assigns the flag: `ManagerBasedRLEnv` allocates `episode_length_buf` and `reset_buf` before calling `super().__init__()`, so an allocation failure there leaves the attribute unset. `__del__` then raises `AttributeError`, which Python reports as an ignored exception in place of the original construction error, making the real failure materially harder to diagnose. Default the lookup to `True` so an environment that never finished initializing is treated as already closed and needs no teardown. The buffer allocation cannot simply move after `super().__init__()`: manager construction calls every observation term once to measure its output shape, and some terms read `episode_length_buf`.
The inline comment restated rationale already carried by the previous commit message; keep only the fact that forces the `getattr`. The changelog claimed the destructor masked the original error, but the original exception still propagates to the caller: the spurious `AttributeError` is printed ahead of it, not in place of it.
|
run-ci |
There was a problem hiding this comment.
Isaac Lab Review Bot
The patch consistently guards the three environment destructors against a missing _is_closed attribute, preventing a secondary AttributeError after early construction failure. It includes focused parametrized regression coverage and an appropriate changelog fragment.
- Design and architecture: Treating a missing
_is_closedflag as already closed is a narrowly scoped cleanup decision that avoids invoking teardown on an incompletely initialized object. Applying the same guard toManagerBasedEnv,DirectRLEnv, andDirectMARLEnvpreserves their shared destructor behavior. - API: No public signatures, exports, or construction interfaces change. Fully initialized environments retain the existing close and interpreter-shutdown behavior because their
_is_closedattribute remains authoritative. - Implementation: The changed destructors use
getattr(self, "_is_closed", True)to eliminate the demonstrated missing-attribute path while preserving cleanup when the flag is present and false. The regression test directly covers all three modified classes. The change is intentionally limited to destructor behavior; explicitclose()handling for partially initialized objects remains outside this patch.
No blocking issues. No inline issue met the actionable-evidence threshold; the assessment above records the review feedback.
Automated review; human maintainers own approval decisions.
Greptile SummaryThe PR prevents environment destructors from obscuring construction failures when
Confidence Score: 5/5The PR appears safe to merge with no actionable correctness or security issues identified. The guarded lookup preserves cleanup for fully initialized open environments while avoiding teardown on objects that failed before establishing their lifecycle state, and the regression test covers each changed destructor. Important Files Changed
Reviews (1): Last reviewed commit: "Merge remote-tracking branch 'upstream/d..." | Re-trigger Greptile |
|
Backported to |
…tead of an AttributeError from __del__ (#7373) # Description When environment construction fails partway through `__init__`, the destructor emits a *second*, misleading traceback ahead of the real failure: ``` Exception ignored in: <function ManagerBasedEnv.__del__ at 0x...> AttributeError: 'ManagerBasedRLEnv' object has no attribute '_is_closed' ``` `ManagerBasedEnv.__del__` (and the `DirectRLEnv` / `DirectMARLEnv` equivalents) read `self._is_closed` unconditionally. That attribute is assigned by `ManagerBasedEnv.__init__`, but a **subclass may run fallible setup before delegating to it**: `ManagerBasedRLEnv.__init__` allocates `episode_length_buf` and `reset_buf` on `cfg.sim.device` before calling `super().__init__()`. A CUDA OOM, an invalid device, or a malformed config raises there, leaving `_is_closed` unset. The original exception still propagates to the caller — it is not swallowed. But Python cannot raise out of `__del__`, so it routes the `AttributeError` to `sys.unraisablehook`, which prints it on unbuffered stderr. The spurious traceback therefore lands *first*, naming a different exception type at a different location, which is what makes the real failure hard to find. This defaults the lookup to `True`, so an environment that never finished initializing is treated as already closed and needs no teardown. That matches the existing contract: `_is_closed = True` is already the first statement of `ManagerBasedEnv.__init__` for exactly this reason, and genuine partial-init cleanup is handled explicitly by the `try/except` around `_init_sim()` that releases the `SimulationContext` singleton. Applied to all three env classes, which share an identical destructor. **Why not move the allocation after `super().__init__()`?** Manager construction calls every observation term once to measure its output shape (`ManagerBase.__init__` -> `_prepare_terms` -> `term_cfg.func(env)`), and terms such as `mdp.observations.current_time_s` read `env.episode_length_buf`. The early allocation was introduced deliberately in #2332 for that reason. Guarding the destructor is the change that does not perturb construction order. Fixes NVBugs 6604738. Related: 6591313 (`AssetBase.__del__`) and 6311065 (`direct_rl_env.__del__`) — both fixed, neither covers this path; `AssetBase` uses a different attribute (`_is_initialized`). ## Type of change - Bug fix (non-breaking change which fixes an issue) ## Release backport - [x] <!-- backport-active-release --> Backport this pull request to the active release branch after it merges into `develop` ## Validation `test_env_destructors.py` gains one parametrized case covering a partially constructed env. Verified it fails before the fix and passes after: | | Result | | --- | --- | | Without the fix | `3 failed` — `AttributeError` at `manager_based_env.py:248` | | With the fix | `14 passed` (11 existing + 3 new) | ```bash uv run --extra test python -m pytest source/isaaclab/test/envs/test_env_destructors.py -q ``` ## Known gap This guards `__del__` only. `_is_closed` is also read unguarded in `close()` at `manager_based_env.py:605`, `direct_rl_env.py:591`, `direct_marl_env.py:593`, `manager_based_rl_env.py:358` and `leapp_deployment_env.py:427`, so `try: env = ManagerBasedRLEnv(cfg) finally: env.close()` still raises. A follow-up declaring `_is_closed: bool = True` as a class attribute would cover every read site at once. ## Checklist - [x] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `./isaaclab.sh --format` - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] I have added a changelog fragment under `source/<pkg>/changelog.d/` for every touched package - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there (cherry picked from commit d7e6341)
Description
When environment construction fails partway through
__init__, the destructor emits a second,misleading traceback ahead of the real failure:
ManagerBasedEnv.__del__(and theDirectRLEnv/DirectMARLEnvequivalents) readself._is_closedunconditionally. That attribute is assigned by
ManagerBasedEnv.__init__, but a subclass may runfallible setup before delegating to it:
ManagerBasedRLEnv.__init__allocatesepisode_length_bufand
reset_bufoncfg.sim.devicebefore callingsuper().__init__(). A CUDA OOM, an invalid device,or a malformed config raises there, leaving
_is_closedunset.The original exception still propagates to the caller — it is not swallowed. But Python cannot raise
out of
__del__, so it routes theAttributeErrortosys.unraisablehook, which prints it onunbuffered stderr. The spurious traceback therefore lands first, naming a different exception type
at a different location, which is what makes the real failure hard to find.
This defaults the lookup to
True, so an environment that never finished initializing is treated asalready closed and needs no teardown. That matches the existing contract:
_is_closed = Trueisalready the first statement of
ManagerBasedEnv.__init__for exactly this reason, and genuinepartial-init cleanup is handled explicitly by the
try/exceptaround_init_sim()that releases theSimulationContextsingleton. Applied to all three env classes, which share an identical destructor.Why not move the allocation after
super().__init__()? Manager construction calls everyobservation term once to measure its output shape (
ManagerBase.__init__->_prepare_terms->term_cfg.func(env)), and terms such asmdp.observations.current_time_sreadenv.episode_length_buf. The early allocation was introduced deliberately in #2332 for that reason.Guarding the destructor is the change that does not perturb construction order.
Fixes NVBugs 6604738. Related: 6591313 (
AssetBase.__del__) and 6311065 (direct_rl_env.__del__) —both fixed, neither covers this path;
AssetBaseuses a different attribute (_is_initialized).Type of change
Release backport
developValidation
test_env_destructors.pygains one parametrized case covering a partially constructed env. Verified itfails before the fix and passes after:
3 failed—AttributeErroratmanager_based_env.py:24814 passed(11 existing + 3 new)uv run --extra test python -m pytest source/isaaclab/test/envs/test_env_destructors.py -qKnown gap
This guards
__del__only._is_closedis also read unguarded inclose()atmanager_based_env.py:605,direct_rl_env.py:591,direct_marl_env.py:593,manager_based_rl_env.py:358andleapp_deployment_env.py:427, sotry: env = ManagerBasedRLEnv(cfg) finally: env.close()still raises. A follow-up declaring_is_closed: bool = Trueas a class attribute would cover every read site at once.Checklist
pre-commitchecks with./isaaclab.sh --formatsource/<pkg>/changelog.d/for every touched packageCONTRIBUTORS.mdor my name already exists there