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