Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions python/mujoco/studio/launch_thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import queue
import threading
import traceback
from typing import Any, Callable

from mujoco.studio import endpoints
Expand Down Expand Up @@ -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],
*,
Expand All @@ -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:
Expand Down
72 changes: 72 additions & 0 deletions python/mujoco/studio/launch_thread_test.py
Original file line number Diff line number Diff line change
@@ -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()
Loading