|
21 | 21 | from __future__ import annotations |
22 | 22 |
|
23 | 23 | import copy |
24 | | -import gc |
| 24 | +import functools |
| 25 | +import itertools |
25 | 26 | import logging |
26 | 27 | import sys |
27 | 28 | import threading |
|
48 | 49 | _DEFAULT_MAX_PENDING_BYTES = 16_000_000 |
49 | 50 |
|
50 | 51 |
|
51 | | -_RETAINED_GRAPH_BOUNDARIES = ( |
| 52 | +_UNSUPPORTED_RETAINED_GRAPH = object() |
| 53 | +_ATOMIC_RETAINED_TYPES = ( |
| 54 | + str, |
| 55 | + bytes, |
| 56 | + bytearray, |
| 57 | + int, |
| 58 | + float, |
| 59 | + complex, |
| 60 | + bool, |
| 61 | + type(None), |
| 62 | + range, |
| 63 | + slice, |
52 | 64 | type, |
53 | 65 | types.ModuleType, |
54 | | - types.FunctionType, |
55 | | - types.BuiltinFunctionType, |
56 | 66 | types.CodeType, |
| 67 | + types.WrapperDescriptorType, |
| 68 | + types.MethodDescriptorType, |
57 | 69 | ) |
58 | 70 |
|
59 | 71 |
|
| 72 | +class _RetainedChildren: |
| 73 | + __slots__ = ("iterator",) |
| 74 | + |
| 75 | + def __init__(self, items: Any) -> None: |
| 76 | + self.iterator = iter(items) |
| 77 | + |
| 78 | + |
| 79 | +def _custom_retained_children(value: Any) -> list[Any]: |
| 80 | + children: list[Any] = [] |
| 81 | + try: |
| 82 | + children.append(object.__getattribute__(value, "__dict__")) |
| 83 | + except Exception: # noqa: BLE001 - custom objects may use slots only |
| 84 | + pass |
| 85 | + for cls in type(value).__mro__: |
| 86 | + slots = vars(cls).get("__slots__", ()) |
| 87 | + if isinstance(slots, str): |
| 88 | + slots = (slots,) |
| 89 | + for slot in slots: |
| 90 | + if slot in {"__dict__", "__weakref__"}: |
| 91 | + continue |
| 92 | + if slot.startswith("__") and not slot.endswith("__"): |
| 93 | + slot = f"_{cls.__name__.lstrip('_')}{slot}" |
| 94 | + try: |
| 95 | + children.append(object.__getattribute__(value, slot)) |
| 96 | + except Exception: # noqa: BLE001 - unset/custom slots are best-effort |
| 97 | + pass |
| 98 | + return children |
| 99 | + |
| 100 | + |
| 101 | +def _retained_children(value: Any) -> Any: |
| 102 | + custom = _custom_retained_children(value) |
| 103 | + if isinstance(value, dict): |
| 104 | + return itertools.chain(dict.__iter__(value), dict.values(value), custom) |
| 105 | + if isinstance(value, list): |
| 106 | + return itertools.chain(list.__iter__(value), custom) |
| 107 | + if isinstance(value, tuple): |
| 108 | + return itertools.chain(tuple.__iter__(value), custom) |
| 109 | + if isinstance(value, set): |
| 110 | + return itertools.chain(set.__iter__(value), custom) |
| 111 | + if isinstance(value, frozenset): |
| 112 | + return itertools.chain(frozenset.__iter__(value), custom) |
| 113 | + if isinstance(value, deque): |
| 114 | + return itertools.chain(deque.__iter__(value), custom) |
| 115 | + if isinstance(value, memoryview): |
| 116 | + return (value.obj,) |
| 117 | + if isinstance(value, functools.partial): |
| 118 | + return (value.func, value.args, value.keywords) |
| 119 | + if isinstance(value, types.FunctionType): |
| 120 | + closure = [] |
| 121 | + for cell in value.__closure__ or (): |
| 122 | + try: |
| 123 | + closure.append(cell.cell_contents) |
| 124 | + except ValueError: |
| 125 | + pass |
| 126 | + return itertools.chain(closure, (value.__defaults__, value.__kwdefaults__)) |
| 127 | + if isinstance(value, types.MethodType): |
| 128 | + return (value.__self__, value.__func__) |
| 129 | + if isinstance(value, types.BuiltinFunctionType): |
| 130 | + owner = value.__self__ |
| 131 | + return () if owner is None or isinstance(owner, types.ModuleType) else (owner,) |
| 132 | + if isinstance(value, types.MethodWrapperType): |
| 133 | + return (value.__self__,) |
| 134 | + if isinstance(value, types.GeneratorType): |
| 135 | + frame = value.gi_frame |
| 136 | + return () if frame is None else (frame.f_locals, value.gi_yieldfrom) |
| 137 | + if isinstance(value, _ATOMIC_RETAINED_TYPES): |
| 138 | + return () |
| 139 | + if custom: |
| 140 | + return custom |
| 141 | + return _UNSUPPORTED_RETAINED_GRAPH |
| 142 | + |
| 143 | + |
| 144 | +def _retained_shallow_size(value: Any) -> int: |
| 145 | + try: |
| 146 | + size = sys.getsizeof(value) |
| 147 | + except Exception: # noqa: BLE001 - estimation must never break a hook |
| 148 | + size = 1_024 |
| 149 | + try: |
| 150 | + if isinstance(value, dict): |
| 151 | + size = max(size, dict.__sizeof__(value)) |
| 152 | + elif isinstance(value, list): |
| 153 | + size = max(size, list.__sizeof__(value)) |
| 154 | + elif isinstance(value, tuple): |
| 155 | + size = max(size, tuple.__sizeof__(value)) |
| 156 | + elif isinstance(value, set): |
| 157 | + size = max(size, set.__sizeof__(value)) |
| 158 | + elif isinstance(value, frozenset): |
| 159 | + size = max(size, frozenset.__sizeof__(value)) |
| 160 | + elif isinstance(value, deque): |
| 161 | + size = max(size, deque.__sizeof__(value)) |
| 162 | + except Exception: # noqa: BLE001 - base sizing remains best-effort |
| 163 | + pass |
| 164 | + return size |
| 165 | + |
| 166 | + |
60 | 167 | def _estimate_retained_size(value: Any, max_size: int | None = None) -> int: |
61 | | - """Estimate a bounded retained graph without serializing or calling render().""" |
| 168 | + """Estimate retained memory with bounded, non-overridable traversal.""" |
62 | 169 | total = 0 |
63 | 170 | seen: set[int] = set() |
64 | 171 | stack: list[Any] = [value] |
65 | 172 | while stack: |
66 | 173 | item = stack.pop() |
| 174 | + if isinstance(item, _RetainedChildren): |
| 175 | + try: |
| 176 | + child = next(item.iterator) |
| 177 | + except StopIteration: |
| 178 | + continue |
| 179 | + except Exception: # noqa: BLE001 - fail closed on malformed iterators |
| 180 | + return max_size + 1 if max_size is not None else total + 1_024 |
| 181 | + stack.append(item) |
| 182 | + stack.append(child) |
| 183 | + continue |
67 | 184 | identity = id(item) |
68 | 185 | if identity in seen: |
69 | 186 | continue |
70 | 187 | seen.add(identity) |
71 | | - try: |
72 | | - total += sys.getsizeof(item) |
73 | | - except Exception: # noqa: BLE001 - estimation must never break a hook |
74 | | - total += 1_024 |
| 188 | + total += _retained_shallow_size(item) |
75 | 189 | if max_size is not None and total > max_size: |
76 | 190 | return max_size + 1 |
77 | | - try: |
78 | | - referents = gc.get_referents(item) |
79 | | - except Exception: # noqa: BLE001 - estimation must never break a hook |
80 | | - continue |
81 | | - for referent in referents: |
82 | | - # Type/module/function/code objects lead into process-global graphs, |
83 | | - # not memory retained specifically by this record. Bound methods, |
84 | | - # partial args, generator iterators, slots, buffers, and container |
85 | | - # subclasses remain traversable through their other referents. |
86 | | - if isinstance(referent, _RETAINED_GRAPH_BOUNDARIES): |
87 | | - continue |
88 | | - stack.append(referent) |
| 191 | + children = _retained_children(item) |
| 192 | + if children is _UNSUPPORTED_RETAINED_GRAPH: |
| 193 | + return max_size + 1 if max_size is not None else total + 1_024 |
| 194 | + stack.append(_RetainedChildren(children)) |
89 | 195 | return total |
90 | 196 |
|
91 | 197 |
|
|
0 commit comments