From 71f3455f73eedef78ccf79c17ed5adbb36d11eeb Mon Sep 17 00:00:00 2001
From: YiFei Zhu <zhuyifei1999@gmail.com>
Date: Mon, 22 May 2023 15:54:24 -0700
Subject: [PATCH] nodegraph: Fix refcount sanity assertion for Python 3.11

Python 3.11 created immortal objects whose initial refcount is
999999999, larger than 0xa000000. This breaks the assertin here.

Caught by https://bugs.gentoo.org/906937

Fortunately I don't seem to need to do a new release with this fix
because the wheels are built with -DNDEBUG.
---
 src/heapy/nodegraph.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/src/heapy/nodegraph.c b/src/heapy/nodegraph.c
index 2fd9c83..765f5ee 100644
--- a/src/heapy/nodegraph.c
+++ b/src/heapy/nodegraph.c
@@ -148,8 +148,18 @@ NyNodeGraph_AddEdge(NyNodeGraphObject *ng, PyObject *src, PyObject *tgt)
         ng->edges[ng->used_size-1].tgt == tgt)
         return 0;
 
-    assert(Py_REFCNT(src) < 0xa000000 && (Py_uintptr_t)Py_TYPE(src) > 0x1000);
-    assert(Py_REFCNT(tgt) < 0xa000000 && (Py_uintptr_t)Py_TYPE(tgt) > 0x1000);
+#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 11
+    /* Py >= 3.11 _PyObject_IMMORTAL_INIT sets initial refcount of 999999999 */
+    assert((Py_uintptr_t)Py_TYPE(src) > 0x1000 &&
+            (Py_REFCNT(src) < 0xa000000 ||
+             (Py_REFCNT(src) >= 999999999 && Py_REFCNT(src) < 999999999 + 0xa000000)));
+    assert((Py_uintptr_t)Py_TYPE(tgt) > 0x1000 &&
+            (Py_REFCNT(tgt) < 0xa000000 ||
+             (Py_REFCNT(tgt) >= 999999999 && Py_REFCNT(tgt) < 999999999 + 0xa000000)));
+#else
+    assert((Py_uintptr_t)Py_TYPE(src) > 0x1000 && Py_REFCNT(src) < 0xa000000);
+    assert((Py_uintptr_t)Py_TYPE(tgt) > 0x1000 && Py_REFCNT(tgt) < 0xa000000);
+#endif
 
     if (ng->used_size >= ng->allo_size) {
         Py_ssize_t allo = roundupsize(ng->used_size + 1);
-- 
2.40.1

