fix: keep earlier exception translators ahead of local fallbacks (#6255)

* fix: keep earlier exception translators ahead of local fallbacks

On non-libstdc++ platforms, each module that fetches existing internals
adds its translate_local_exception fallback. It was added at the front of
the global list, so it handled builtin_exception and std::exception
subclasses before translators that other modules had registered earlier.
Importing any pybind11 module after such a module broke its translations.

Insert the fallback ahead of the default translator at the end instead.

Assisted-by: ClaudeCode:claude-opus-5-5

* test: preserve FreeBSD xfail for later-import translator test

— codex on behalf of Ralf —

The new subprocess regression repeats the shared_exception translation
already marked as an expected failure on FreeBSD. PR #5925 documents an
RTTI mismatch between extension modules loaded with RTLD_LOCAL there.

The translator-order fix does not change that type matching. Preserve the
FreeBSD expectation in the new test so the known platform limitation does
not become a hard suite failure. Retain raises=RuntimeError because the
subprocess helper wraps child-process failures in RuntimeError.

Validation: prek -a --quiet; incremental GCC/C++20 builds with CPython
3.14.4 default and free-threaded. Pytest: 1458/1456 passed, 14/16 skipped;
Catch2: 31 cases and 1709 assertions passed in each environment. Native
FreeBSD was not available for validation.

---------

Co-authored-by: Ralf W. Grosse-Kunstleve <rgrossekunst@nvidia.com>
diff --git a/include/pybind11/detail/internals-inl.h b/include/pybind11/detail/internals-inl.h
index d7d5a66..29d743d 100644
--- a/include/pybind11/detail/internals-inl.h
+++ b/include/pybind11/detail/internals-inl.h
@@ -16,6 +16,8 @@
 
 #include "internals.h"
 
+#include <iterator>
+
 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
 PYBIND11_NAMESPACE_BEGIN(detail)
 
@@ -148,12 +150,19 @@
         // Not with_exception_translators(): that calls get_internals(), which runs this hook.
         pycritical_section lock(internals_ptr->exception_translator_mutex);
 #    endif
-        for (auto et : internals_ptr->registered_exception_translators) {
-            if (et == &translate_local_exception) {
+        auto &translators = internals_ptr->registered_exception_translators;
+        auto before_last = translators.before_begin();
+        for (auto it = translators.begin(); it != translators.end(); ++it) {
+            if (*it == &translate_local_exception) {
                 return;
             }
+            if (std::next(it) != translators.end()) {
+                before_last = it;
+            }
         }
-        internals_ptr->registered_exception_translators.push_front(&translate_local_exception);
+        // Insert ahead of the default translator at the end, not at the front: a fallback at the
+        // front would shadow translators that other modules registered earlier.
+        translators.insert_after(before_last, &translate_local_exception);
     }
 }
 #endif
diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py
index 96ca5e6..6d38c1e 100644
--- a/tests/test_exceptions.py
+++ b/tests/test_exceptions.py
@@ -1,6 +1,7 @@
 from __future__ import annotations
 
 import importlib
+import os
 import re
 import sys
 import threading
@@ -88,6 +89,29 @@
         m.throw_should_be_translated_to_key_error()
 
 
+@pytest.mark.xfail(
+    env.FREEBSD,
+    raises=RuntimeError,
+    reason="Cross-module exception RTTI mismatch on FreeBSD; see PR #5925",
+)
+def test_cross_module_exception_translator_after_later_import():
+    # A module imported later must not shadow translators registered earlier
+    env.check_script_success_in_subprocess(
+        f"""
+        import sys
+        sys.path.insert(0, {os.path.dirname(env.__file__)!r})
+        from pybind11_tests import exceptions as m
+        import pybind11_cross_module_tests
+        import mod_concurrent_import
+        try:
+            m.throw_should_be_translated_to_key_error()
+        except KeyError:
+            pass
+        """,
+        rerun=1,
+    )
+
+
 def test_python_call_in_catch():
     d = {}
     assert m.python_call_in_destructor(d) is True