| 1 |
From d6cdc919ba40eb650ed29f4ef3ed2813528db28e Mon Sep 17 00:00:00 2001 |
| 2 |
From: Xuan Wang <[email protected]> |
| 3 |
Date: Mon, 14 Oct 2024 15:16:27 -0700 |
| 4 |
Subject: [PATCH 1/3] [Cython AIO] Fix Aio tests time out issue (#37917) |
| 5 |
|
| 6 |
### What's happening |
| 7 |
Some of our asyncio tests began timing out following a Cython upgrade to 3.0. This issue occurs consistently across both our Bazel and setup.py test environments. |
| 8 |
|
| 9 |
### Why the time out |
| 10 |
After some investigation, we found that our code here:https://github.com/grpc/grpc/blob/4ffcdd4ab7976cac397fcff25b6f952d0b5c8168/src/python/grpcio/grpc/_cython/_cygrpc/aio/completion_queue.pyx.pxi#L115-L116 |
| 11 |
|
| 12 |
Was translated to this in Cython 0.29: |
| 13 |
``` |
| 14 |
__pyx_f_7_cython_6cygrpc__unified_socket_write(__pyx_v_self->_write_fd); |
| 15 |
``` |
| 16 |
|
| 17 |
And it changed to this in Cython 3.0: |
| 18 |
``` |
| 19 |
__pyx_f_7_cython_6cygrpc__unified_socket_write(__pyx_v_self->_write_fd); if (unlikely(__Pyx_ErrOccurredWithGIL())) __PYX_ERR(7, 136, __pyx_L1_error) |
| 20 |
``` |
| 21 |
|
| 22 |
Which indicates that this `nogil` function `_unified_socket_write` now requires GIL. |
| 23 |
|
| 24 |
### What's new in Cython 3 |
| 25 |
* Cython 3 `cdef` functions with `void` return type will default to use `except *` as exception specification. |
| 26 |
* If function have `void` return type and defined as `nogil`, Cython will always re-acquire the GIL after the function call to check if an exception has been raised. |
| 27 |
* In some cases, this will cause a deadlock, especially if the function was called inside another `nogil` function. |
| 28 |
|
| 29 |
### What's the fix |
| 30 |
* This PR changes those functions to use `noexcept` as exception specification since we don't expect them to throw any exception, and this is also the suggested workarounds in Cython documentation: https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#error-return-values |
| 31 |
|
| 32 |
### Test |
| 33 |
* Tested locally by running `bazel test`, time our rate decreased from 5% to 0.3% in 3000 runs and 10s test time out. |
| 34 |
<!-- |
| 35 |
|
| 36 |
If you know who should review your pull request, please assign it to that |
| 37 |
person, otherwise the pull request would get assigned randomly. |
| 38 |
|
| 39 |
If your pull request is for a specific language, please add the appropriate |
| 40 |
lang label. |
| 41 |
|
| 42 |
--> |
| 43 |
|
| 44 |
Closes #37917 |
| 45 |
|
| 46 |
COPYBARA_INTEGRATE_REVIEW=https://github.com/grpc/grpc/pull/37917 from XuanWang-Amos:fix_cython_aio 063d27aee9192a26f36d16e6f056dcab1a48b9c9 |
| 47 |
PiperOrigin-RevId: 685851320 |
| 48 |
--- |
| 49 |
.../grpc/_cython/_cygrpc/aio/completion_queue.pxd.pxi | 4 ++-- |
| 50 |
.../grpc/_cython/_cygrpc/aio/completion_queue.pyx.pxi | 6 +++--- |
| 51 |
2 files changed, 5 insertions(+), 5 deletions(-) |
| 52 |
|
| 53 |
Origin: upstream, https://github.com/grpc/grpc/pull/38003 |
| 54 |
--- a/src/python/grpcio/grpc/_cython/_cygrpc/aio/completion_queue.pxd.pxi |
| 55 |
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/aio/completion_queue.pxd.pxi |
| 56 |
@@ -23,7 +23,7 @@ |
| 57 |
int win_socket_send "send" (WIN_SOCKET s, const char *buf, int len, int flags) |
| 58 |
|
| 59 |
|
| 60 |
-cdef void _unified_socket_write(int fd) nogil |
| 61 |
+cdef void _unified_socket_write(int fd) noexcept nogil |
| 62 |
|
| 63 |
|
| 64 |
cdef class BaseCompletionQueue: |
| 65 |
--- a/src/python/grpcio/grpc/_cython/_cygrpc/aio/completion_queue.pyx.pxi |
| 66 |
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/aio/completion_queue.pyx.pxi |
| 67 |
@@ -22,12 +22,12 @@ |
| 68 |
cdef bint _has_fd_monitoring = True |
| 69 |
|
| 70 |
IF UNAME_SYSNAME == "Windows": |
| 71 |
- cdef void _unified_socket_write(int fd) nogil: |
| 72 |
+ cdef void _unified_socket_write(int fd) noexcept nogil: |
| 73 |
win_socket_send(<WIN_SOCKET>fd, b"1", 1, 0) |
| 74 |
ELSE: |
| 75 |
from posix cimport unistd |
| 76 |
|
| 77 |
- cdef void _unified_socket_write(int fd) nogil: |
| 78 |
+ cdef void _unified_socket_write(int fd) noexcept nogil: |
| 79 |
unistd.write(fd, b"1", 1) |
| 80 |
|
| 81 |
|
| 82 |
--- a/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi |
| 83 |
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi |
| 84 |
@@ -26,9 +26,9 @@ |
| 85 |
grpc_credentials_plugin_metadata_cb cb, void *user_data, |
| 86 |
grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], |
| 87 |
size_t *num_creds_md, grpc_status_code *status, |
| 88 |
- const char **error_details) except * with gil |
| 89 |
+ const char **error_details) except -1 with gil |
| 90 |
|
| 91 |
-cdef void _destroy(void *state) except * with gil |
| 92 |
+cdef void _destroy(void *state) noexcept nogil |
| 93 |
|
| 94 |
|
| 95 |
cdef class MetadataPluginCallCredentials(CallCredentials): |
| 96 |
--- a/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi |
| 97 |
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi |
| 98 |
@@ -12,6 +12,7 @@ |
| 99 |
# See the License for the specific language governing permissions and |
| 100 |
# limitations under the License. |
| 101 |
|
| 102 |
+import atexit |
| 103 |
|
| 104 |
def _spawn_callback_in_thread(cb_func, args): |
| 105 |
t = ForkManagedThread(target=cb_func, args=args) |
| 106 |
@@ -41,7 +42,7 @@ |
| 107 |
grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX], |
| 108 |
size_t *num_creds_md, |
| 109 |
grpc_status_code *status, |
| 110 |
- const char **error_details) except * with gil: |
| 111 |
+ const char **error_details) except -1 with gil: |
| 112 |
cdef size_t metadata_count |
| 113 |
cdef grpc_metadata *c_metadata |
| 114 |
def callback(metadata, grpc_status_code status, bytes error_details): |
| 115 |
@@ -65,11 +66,59 @@ |
| 116 |
return 0 # Asynchronous return |
| 117 |
|
| 118 |
|
| 119 |
-cdef void _destroy(void *state) except * with gil: |
| 120 |
- cpython.Py_DECREF(<object>state) |
| 121 |
+# Protects access to GIL from _destroy() and to g_shutting_down. |
| 122 |
+# Do NOT hold this while holding GIL to prevent a deadlock. |
| 123 |
+cdef mutex g_shutdown_mu |
| 124 |
+# Number of C-core clean up calls in progress. Set to -1 when Python is shutting |
| 125 |
+# down. |
| 126 |
+cdef int g_shutting_down = 0 |
| 127 |
+ |
| 128 |
+# This is called by C-core when the plugin is destroyed, which may race between |
| 129 |
+# GIL destruction during process shutdown. Since GIL destruction happens after |
| 130 |
+# Python's exit handlers, we mark that Python is shutting down from an exit |
| 131 |
+# handler and don't grab GIL in this function afterwards using a C mutex. |
| 132 |
+cdef void _destroy(void *state) noexcept nogil: |
| 133 |
+ global g_shutdown_mu |
| 134 |
+ global g_shutting_down |
| 135 |
+ g_shutdown_mu.lock() |
| 136 |
+ if g_shutting_down > -1: |
| 137 |
+ g_shutting_down += 1 |
| 138 |
+ g_shutdown_mu.unlock() |
| 139 |
+ with gil: |
| 140 |
+ cpython.Py_DECREF(<object>state) |
| 141 |
+ g_shutdown_mu.lock() |
| 142 |
+ g_shutting_down -= 1 |
| 143 |
+ g_shutdown_mu.unlock() |
| 144 |
grpc_shutdown() |
| 145 |
|
| 146 |
|
| 147 |
+g_shutdown_handler_registered = False |
| 148 |
+ |
| 149 |
+def _maybe_register_shutdown_handler(): |
| 150 |
+ global g_shutdown_handler_registered |
| 151 |
+ if g_shutdown_handler_registered: |
| 152 |
+ return |
| 153 |
+ g_shutdown_handler_registered = True |
| 154 |
+ atexit.register(_on_shutdown) |
| 155 |
+ |
| 156 |
+cdef void _on_shutdown() noexcept nogil: |
| 157 |
+ global g_shutdown_mu |
| 158 |
+ global g_shutting_down |
| 159 |
+ # Wait for up to ~2s if C-core is still cleaning up. |
| 160 |
+ cdef int wait_ms = 10 |
| 161 |
+ while wait_ms < 1500: |
| 162 |
+ g_shutdown_mu.lock() |
| 163 |
+ if g_shutting_down == 0: |
| 164 |
+ g_shutting_down = -1 |
| 165 |
+ g_shutdown_mu.unlock() |
| 166 |
+ return |
| 167 |
+ g_shutdown_mu.unlock() |
| 168 |
+ with gil: |
| 169 |
+ time.sleep(wait_ms / 1000) |
| 170 |
+ wait_ms = wait_ms * 2 |
| 171 |
+ with gil: |
| 172 |
+ _LOGGER.error('Timed out waiting for C-core clean-up') |
| 173 |
+ |
| 174 |
cdef class MetadataPluginCallCredentials(CallCredentials): |
| 175 |
|
| 176 |
def __cinit__(self, metadata_plugin, name): |
| 177 |
@@ -83,6 +132,7 @@ |
| 178 |
c_metadata_plugin.state = <void *>self._metadata_plugin |
| 179 |
c_metadata_plugin.type = self._name |
| 180 |
cpython.Py_INCREF(self._metadata_plugin) |
| 181 |
+ _maybe_register_shutdown_handler() |
| 182 |
fork_handlers_and_grpc_init() |
| 183 |
# TODO(yihuazhang): Expose min_security_level via the Python API so that |
| 184 |
# applications can decide what minimum security level their plugins require. |
| 185 |
--- a/src/python/grpcio/grpc/_cython/_cygrpc/records.pxd.pxi |
| 186 |
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/records.pxd.pxi |
| 187 |
@@ -14,8 +14,8 @@ |
| 188 |
|
| 189 |
|
| 190 |
cdef bytes _slice_bytes(grpc_slice slice) |
| 191 |
-cdef grpc_slice _copy_slice(grpc_slice slice) nogil |
| 192 |
-cdef grpc_slice _slice_from_bytes(bytes value) nogil |
| 193 |
+cdef grpc_slice _copy_slice(grpc_slice slice) noexcept nogil |
| 194 |
+cdef grpc_slice _slice_from_bytes(bytes value) noexcept nogil |
| 195 |
|
| 196 |
|
| 197 |
cdef class CallDetails: |
| 198 |
--- a/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi |
| 199 |
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi |
| 200 |
@@ -18,12 +18,12 @@ |
| 201 |
cdef size_t length = grpc_slice_length(slice) |
| 202 |
return (<const char *>start)[:length] |
| 203 |
|
| 204 |
-cdef grpc_slice _copy_slice(grpc_slice slice) nogil: |
| 205 |
+cdef grpc_slice _copy_slice(grpc_slice slice) noexcept nogil: |
| 206 |
cdef void *start = grpc_slice_start_ptr(slice) |
| 207 |
cdef size_t length = grpc_slice_length(slice) |
| 208 |
return grpc_slice_from_copied_buffer(<const char *>start, length) |
| 209 |
|
| 210 |
-cdef grpc_slice _slice_from_bytes(bytes value) nogil: |
| 211 |
+cdef grpc_slice _slice_from_bytes(bytes value) noexcept nogil: |
| 212 |
cdef const char *value_ptr |
| 213 |
cdef size_t length |
| 214 |
with gil: |
| 215 |
--- a/src/python/grpcio/grpc/_cython/_cygrpc/security.pxd.pxi |
| 216 |
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/security.pxd.pxi |
| 217 |
@@ -14,4 +14,4 @@ |
| 218 |
|
| 219 |
|
| 220 |
cdef grpc_ssl_roots_override_result ssl_roots_override_callback( |
| 221 |
- char **pem_root_certs) nogil |
| 222 |
+ char **pem_root_certs) noexcept nogil |
| 223 |
--- a/src/python/grpcio/grpc/_cython/_cygrpc/security.pyx.pxi |
| 224 |
+++ b/src/python/grpcio/grpc/_cython/_cygrpc/security.pyx.pxi |
| 225 |
@@ -18,7 +18,7 @@ |
| 226 |
|
| 227 |
|
| 228 |
cdef grpc_ssl_roots_override_result ssl_roots_override_callback( |
| 229 |
- char **pem_root_certs) nogil: |
| 230 |
+ char **pem_root_certs) noexcept nogil: |
| 231 |
with gil: |
| 232 |
pkg = __name__ |
| 233 |
if pkg.endswith('.cygrpc'): |
| 234 |
--- a/tools/distrib/python/grpcio_tools/grpc_tools/_protoc_compiler.pyx |
| 235 |
+++ b/tools/distrib/python/grpcio_tools/grpc_tools/_protoc_compiler.pyx |
| 236 |
@@ -39,12 +39,12 @@ |
| 237 |
vector[string]* include_path, |
| 238 |
vector[pair[string, string]]* files_out, |
| 239 |
vector[cProtocError]* errors, |
| 240 |
- vector[cProtocWarning]* wrnings) nogil except + |
| 241 |
+ vector[cProtocWarning]* wrnings) except + nogil |
| 242 |
int protoc_get_services(char* protobuf_path, |
| 243 |
vector[string]* include_path, |
| 244 |
vector[pair[string, string]]* files_out, |
| 245 |
vector[cProtocError]* errors, |
| 246 |
- vector[cProtocWarning]* wrnings) nogil except + |
| 247 |
+ vector[cProtocWarning]* wrnings) except + nogil |
| 248 |
|
| 249 |
def run_main(list args not None): |
| 250 |
cdef char **argv = <char **>stdlib.malloc(len(args)*sizeof(char *)) |