From: Siu Kwan Lam <1929845+sklam@users.noreply.github.com>
Origin: https://github.com/numba/numba/pull/8545
Date: Thu, 27 Oct 2022 11:30:21 -0500
Subject: Restore #7388 fixes

---
 numba/cloudpickle/cloudpickle.py      | 6 ++++++
 numba/cloudpickle/cloudpickle_fast.py | 5 +++++
 2 files changed, 11 insertions(+)

diff --git a/numba/cloudpickle/cloudpickle.py b/numba/cloudpickle/cloudpickle.py
index 317be69..53a7b2d 100644
--- a/numba/cloudpickle/cloudpickle.py
+++ b/numba/cloudpickle/cloudpickle.py
@@ -91,6 +91,7 @@ _PICKLE_BY_VALUE_MODULES = set()
 _DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary()
 _DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary()
 _DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock()
+_DYNAMIC_CLASS_TRACKER_REUSING = weakref.WeakSet()
 
 PYPY = platform.python_implementation() == "PyPy"
 
@@ -115,9 +116,14 @@ def _get_or_create_tracker_id(class_def):
 def _lookup_class_or_track(class_tracker_id, class_def):
     if class_tracker_id is not None:
         with _DYNAMIC_CLASS_TRACKER_LOCK:
+            orig_class_def = class_def
             class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(
                 class_tracker_id, class_def)
             _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
+            # Check if we are reusing a previous class_def
+            if orig_class_def is not class_def:
+                # Remember the class_def is being reused
+                _DYNAMIC_CLASS_TRACKER_REUSING.add(class_def)
     return class_def
 
 
diff --git a/numba/cloudpickle/cloudpickle_fast.py b/numba/cloudpickle/cloudpickle_fast.py
index 8741dcb..b023ff4 100644
--- a/numba/cloudpickle/cloudpickle_fast.py
+++ b/numba/cloudpickle/cloudpickle_fast.py
@@ -36,6 +36,7 @@ from .cloudpickle import (
     parametrized_type_hint_getinitargs, _create_parametrized_type_hint,
     builtin_code_type,
     _make_dict_keys, _make_dict_values, _make_dict_items, _make_function,
+    _DYNAMIC_CLASS_TRACKER_REUSING
 )
 
 
@@ -523,6 +524,10 @@ def _function_setstate(obj, state):
 
 
 def _class_setstate(obj, state):
+    # Check if class is being reused and needs bypass setstate logic.
+    if obj in _DYNAMIC_CLASS_TRACKER_REUSING:
+        return obj
+
     state, slotstate = state
     registry = None
     for attrname, attr in state.items():
