From 66313dfb64cac411643a96e496c1bbd422419b9c Mon Sep 17 00:00:00 2001 From: Sylvester Kaczmarek <16242628+sylvesterkaczmarek@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:09:07 +0000 Subject: [PATCH] Release viewer traceback locals before forwarding exceptions --- python/mujoco/studio/launch_thread.py | 23 +++++++ python/mujoco/studio/launch_thread_test.py | 72 ++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 python/mujoco/studio/launch_thread_test.py diff --git a/python/mujoco/studio/launch_thread.py b/python/mujoco/studio/launch_thread.py index 29243c0ffe6..bdde874cf55 100644 --- a/python/mujoco/studio/launch_thread.py +++ b/python/mujoco/studio/launch_thread.py @@ -15,6 +15,7 @@ import queue import threading +import traceback from typing import Any, Callable from mujoco.studio import endpoints @@ -93,6 +94,24 @@ def make_thread_endpoints() -> ( ) +def _clear_exception_frames(error: BaseException) -> None: + """Releases worker-thread locals without discarding traceback locations.""" + pending = [error] + seen = set() + while pending: + exc = pending.pop() + if id(exc) in seen: + continue + seen.add(id(exc)) + traceback.clear_frames(exc.__traceback__) + if exc.__cause__ is not None: + pending.append(exc.__cause__) + if exc.__context__ is not None: + pending.append(exc.__context__) + if isinstance(exc, BaseExceptionGroup): + pending.extend(exc.exceptions) + + def launch_thread( target_fn: Callable[[endpoints.ViewerEndpoint], None], *, @@ -111,6 +130,10 @@ def run() -> None: try: target_fn(viewer_endpoint) except BaseException as e: # pylint: disable=broad-exception-caught + # A renderer can still be owned by an unwound frame even after close(). + # Release those references here, before handing the error to the sim + # thread: Filament requires destruction on the creating thread. + _clear_exception_frames(e) error = e def forward_error() -> None: diff --git a/python/mujoco/studio/launch_thread_test.py b/python/mujoco/studio/launch_thread_test.py new file mode 100644 index 00000000000..7b599397d29 --- /dev/null +++ b/python/mujoco/studio/launch_thread_test.py @@ -0,0 +1,72 @@ +# Copyright 2026 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for forwarding viewer-thread failures.""" + +import threading +import traceback +import weakref + +from absl.testing import absltest +from mujoco.studio import launch_thread + + +class LaunchThreadTest(absltest.TestCase): + + def test_exception_releases_frame_locals_on_viewer_thread(self): + created_on = [] + released_on = [] + + class Resource: + pass + + def fail_inner(): + resource = Resource() + weakref.finalize( + resource, lambda: released_on.append(threading.get_ident()) + ) + raise RuntimeError('inner') + + def target(unused_endpoint): + created_on.append(threading.get_ident()) + resource = Resource() + weakref.finalize( + resource, lambda: released_on.append(threading.get_ident()) + ) + try: + fail_inner() + except RuntimeError as exc: + raise ValueError('viewer failed') from exc + + handle = launch_thread.launch_thread(target) + try: + handle.close() + except ValueError as exc: + self.assertEqual(str(exc), 'viewer failed') + self.assertIsInstance(exc.__cause__, RuntimeError) + self.assertIn( + 'target', [f.name for f in traceback.extract_tb(exc.__traceback__)] + ) + self.assertIn( + 'fail_inner', + [f.name for f in traceback.extract_tb(exc.__cause__.__traceback__)], + ) + self.assertLen(created_on, 1) + self.assertEqual(released_on, created_on * 2) + else: + self.fail('Viewer error was not forwarded.') + handle.close() + + +if __name__ == '__main__': + absltest.main()