From d57d2708b371bda5e7212b0eca63091fa2d7ab42 Mon Sep 17 00:00:00 2001
From: Oleh Prypin <oprypin@google.com>
Date: Mon, 15 Sep 2025 13:31:08 -0700
Subject: [PATCH] Fix a crash that happens during shutdown due to looking up
 modules in the cache

The crash happens only since Python 3.13. Conveniently, Python 3.13 introduces a function to check if the interpreter is shutting down at the moment.

There was a related issue https://github.com/protocolbuffers/protobuf/issues/22067 and related commit https://github.com/protocolbuffers/protobuf/commit/87de6f795f794f207c19ea5c887328fcbe35d518
but it appears that the fix was incomplete. What actually causes a crash during shutdown is using `PyState_FindModule`, and `PyUpb_ModuleState_MaybeGet` still calls that anyway.

PiperOrigin-RevId: 807361381
---
 python/protobuf.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/python/protobuf.c b/python/protobuf.c
index ff6bf7c0d6654..a86fcaaf82e67 100644
--- a/python/protobuf.c
+++ b/python/protobuf.c
@@ -58,6 +58,12 @@ static struct PyModuleDef module_def = {PyModuleDef_HEAD_INIT,
 // -----------------------------------------------------------------------------
 
 PyUpb_ModuleState* PyUpb_ModuleState_MaybeGet(void) {
+#if PY_VERSION_HEX >= 0x030D0000  // >= 3.13
+  /* Calling `PyState_FindModule` during interpreter shutdown causes a crash. */
+  if (Py_IsFinalizing()) {
+    return NULL;
+  }
+#endif
   PyObject* module = PyState_FindModule(&module_def);
   return module ? PyModule_GetState(module) : NULL;
 }
