diff --git a/src/JobQueue.cc b/src/JobQueue.cc index 36ce7d85..62777cc8 100644 --- a/src/JobQueue.cc +++ b/src/JobQueue.cc @@ -22,6 +22,7 @@ #include #include +#include JobQueue::JobQueue(JSContext *cx) { finalizationRegistryCallbacks = new JS::PersistentRooted(cx); // Leaks but it's OK since freed at process exit @@ -199,21 +200,17 @@ bool sendJobToMainLoop(PyObject *pyFunc) { return true; } -void JobQueue::promiseRejectionTracker(JSContext *cx, - bool mutedErrors, - JS::HandleObject promise, - JS::PromiseRejectionHandlingState state, - [[maybe_unused]] void *privateData) { - - // We only care about unhandled Promises - if (state != JS::PromiseRejectionHandlingState::Unhandled) { - return; - } - // If the `mutedErrors` option is set to True in `pm.eval`, eval errors or unhandled rejections should be ignored. - if (mutedErrors) { - return; - } +/** + * Rejected promises with no handler yet, reported by checkUnhandledRejections unless a handler is + * attached first. + */ +static std::vector *> pendingRejections; +static bool rejectionCheckScheduled = false; +/** + * Send an unhandled Promise rejection to the exception handler on the Python event-loop + */ +static void reportUnhandledRejection(JSContext *cx, JS::HandleObject promise) { // Test if there's no user-defined (or pmjs defined) exception handler on the Python event-loop PyEventLoop loop = PyEventLoop::getRunningLoop(); if (!loop.initialized()) return; @@ -228,7 +225,6 @@ void JobQueue::promiseRejectionTracker(JSContext *cx, } Py_DECREF(customHandler); - // Go ahead and send this unhandled Promise rejection to the exception handler on the Python event-loop PyObject *pyFuture = PromiseType::getPyObject(cx, promise); // ref count == 2 // Unhandled Future object calls the event-loop exception handler in its destructor (the `__del__` magic method) // See https://github.com/python/cpython/blob/v3.9.16/Lib/asyncio/futures.py#L108 @@ -236,6 +232,67 @@ void JobQueue::promiseRejectionTracker(JSContext *cx, Py_DECREF(pyFuture); // decreasing the reference count from 2 to 1, leaving one for the `onResolved` callback in `PromiseType::getPyObject`, which will be called very soon and clean up the reference } +// Reports the rejections still unhandled once the jobs queued around their rejection have run, so a +// handler attached a few jobs later (e.g. through Promise.prototype.finally) is not reported +static PyObject *checkUnhandledRejections(PyObject *closure, PyObject *Py_UNUSED(unused)) { + JSContext *cx = (JSContext *)PyLong_AsVoidPtr(closure); + std::vector *> rejections; + + rejections.swap(pendingRejections); + rejectionCheckScheduled = false; + for (auto *rootedPromise : rejections) { + JS::RootedObject promise(cx, rootedPromise->get()); + delete rootedPromise; + reportUnhandledRejection(cx, promise); + } + PyEventLoop::_locker->decCounter(); + Py_RETURN_NONE; +} + +static PyMethodDef checkUnhandledRejectionsDef = {"JsCheckUnhandledRejections", checkUnhandledRejections, METH_NOARGS, NULL}; + +void JobQueue::promiseRejectionTracker(JSContext *cx, + bool mutedErrors, + JS::HandleObject promise, + JS::PromiseRejectionHandlingState state, + [[maybe_unused]] void *privateData) { + + if (state == JS::PromiseRejectionHandlingState::Handled) { + for (auto it = pendingRejections.begin(); it != pendingRejections.end(); ++it) { + if ((*it)->get() == promise) { + delete *it; + pendingRejections.erase(it); + break; + } + } + return; + } + + // If the `mutedErrors` option is set to True in `pm.eval`, eval errors or unhandled rejections should be ignored. + if (mutedErrors) { + return; + } + + PyEventLoop loop = PyEventLoop::getRunningLoop(); + if (!loop.initialized()) return; + + pendingRejections.push_back(new JS::PersistentRooted(cx, promise)); + if (!rejectionCheckScheduled) { + // call_later(0) runs after the callbacks already ready on the event-loop, including the jobs + // queued while this rejection's job runs; counted so that pm.wait() waits for the check + PyObject *cxArg = PyLong_FromVoidPtr(cx); + PyObject *check = PyCFunction_New(&checkUnhandledRejectionsDef, cxArg); + Py_DECREF(cxArg); + PyObject *handle = PyObject_CallMethod(loop._loop, "call_later", "dO", 0.0, check); + Py_DECREF(check); + if (handle) { + Py_DECREF(handle); + PyEventLoop::_locker->incCounter(); + rejectionCheckScheduled = true; + } + } +} + void JobQueue::queueFinalizationRegistryCallback(JSFunction *callback) { (void)finalizationRegistryCallbacks->append(callback); } diff --git a/tests/js/finally-rejection-handled.simple b/tests/js/finally-rejection-handled.simple new file mode 100644 index 00000000..d69f6993 --- /dev/null +++ b/tests/js/finally-rejection-handled.simple @@ -0,0 +1,36 @@ +/** + * @file finally-rejection-handled.simple + * A rejection handled through Promise.prototype.finally() is not reported as + * uncaught: finally() rejects an internal promise that gets its handler a few jobs + * later, and the program exits 0 after the handler runs. + * @author Wes Garland, wes@distributive.network + * @date Nov 2026 + * + * timeout: 10 + */ +'use strict'; + +var handled = 0; + +function handler(error) +{ + handled++; + console.log('handled', error.message); +} + +const p = new Promise((resolve, reject) => setTimeout(() => reject(new Error('rejected')), 10)); +p.finally(() => {}).catch(handler); +p.finally(() => {}).then(null, handler); + +async function exec() +{ + await null; + return new Promise((resolve, reject) => setTimeout(() => reject(new Error('cancelled')), 20)) + .finally(() => {}); +} +exec().then(null, handler); + +setTimeout(() => { + if (handled !== 3) + throw new Error(`only ${handled} of 3 rejections were handled`); +}, 100); diff --git a/tests/js/unhandled-rejection.bash b/tests/js/unhandled-rejection.bash new file mode 100755 index 00000000..c8ba49fd --- /dev/null +++ b/tests/js/unhandled-rejection.bash @@ -0,0 +1,23 @@ +#! /bin/bash +# +# @file unhandled-rejection.bash +# A rejection that never gets a handler is still reported as uncaught, and pmjs +# exits non-zero. +# @author Wes Garland, wes@distributive.network +# @date Nov 2026 +# +# timeout: 10 + +panic() +{ + echo "FAIL: $*" >&2 + exit 2 +} + +tmpdir="$(mktemp -d)" +trap 'rm -rf "${tmpdir}"' EXIT +program="${tmpdir}/unhandled.js" +echo 'Promise.reject(new Error("nobody handles this"));' > "${program}" +output="$("${PMJS:-pmjs}" "${program}" 2>&1)" && panic "pmjs exited 0" +echo "${output}" | grep -q 'Uncaught.*nobody handles this' || panic "no Uncaught report: ${output}" +echo PASS