Skip to content

Exceptions raised in Python callbacks are swallowed #423

Backlog

Description

@b-long

When a Python callback that Go calls raises, gopy prints the traceback and hands Go the zero value. The
Python caller of the bound function never sees the exception. This happens on every backend.

import sys, callbacks   # _examples/callbacks

callbacks.Sum(3, lambda i: 1/0 if i == 1 else 10)
# prints the ZeroDivisionError, then returns 20: a wrong answer, and no exception

try:
    callbacks.Apply(1.5, lambda x: sys.exit(3))
except SystemExit:
    pass  # never reached: except on cffi, the process exits with status 3 from inside the Go call

Details

  1. pybindgen, capi, pybind11 and nanobind report through PyErr_Print(): gopy_err_handle in
    bind/gen.go, and the gopy_cb_N trampolines in bind/pybind11_build.py and
    bind/nanobind_build.py. PyErr_Print() handles SystemExit by exiting the process, so finally
    blocks and except SystemExit handlers never run. cffi's ffi.callback already reports these errors
    as "Exception ignored" and keeps going; its result is still wrong (Sum returns 20).
  2. Step 1 (small): in those four backends, replace PyErr_Print() with
    PyErr_WriteUnraisable(callable), so they behave like cffi. This is CPython's API for errors that
    can't propagate. It doesn't exit on SystemExit, and it goes through sys.unraisablehook, so pytest
    and other tools can catch these errors.
  3. Step 2 (the real fix): have the trampoline save the first exception instead of reporting it, and
    re-raise it in the caller once the Go call returns and the wrapper has the GIL again. Callbacks that
    Go runs on another goroutine, or after the outer call has returned, still need Step 1 as a fallback.

Note: this is a follow-up to #401, which ships in 0.6.1 (#422).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions