| 1 |
""" |
| 2 |
Integration tests for memory leak issue #8882. |
| 3 |
|
| 4 |
These tests reproduce memory leak scenarios that occur when Celery tasks |
| 5 |
raise unhandled exceptions, causing ExceptionInfo objects to not be |
| 6 |
properly garbage collected. |
| 7 |
""" |
| 8 |
|
| 9 |
import gc |
| 10 |
import logging |
| 11 |
import os |
| 12 |
import tracemalloc |
| 13 |
|
| 14 |
from celery import Celery |
| 15 |
|
| 16 |
logger = logging.getLogger(__name__) |
| 17 |
|
| 18 |
|
| 19 |
class MemoryLeakUnhandledExceptionsTest: |
| 20 |
"""Test class for memory leak scenarios with unhandled exceptions.""" |
| 21 |
|
| 22 |
def __init__(self): |
| 23 |
self.app = Celery('test_memory_leak') |
| 24 |
self.app.conf.update( |
| 25 |
broker_url='memory://', |
| 26 |
result_backend='cache+memory://', |
| 27 |
task_always_eager=True, |
| 28 |
task_eager_propagates=True, |
| 29 |
task_store_eager_result=True, |
| 30 |
) |
| 31 |
self.setup_tasks() |
| 32 |
|
| 33 |
def setup_tasks(self): |
| 34 |
"""Setup test tasks.""" |
| 35 |
|
| 36 |
@self.app.task |
| 37 |
def task_success(): |
| 38 |
"""Task that completes successfully - baseline for memory comparison.""" |
| 39 |
return "success" |
| 40 |
|
| 41 |
@self.app.task |
| 42 |
def task_unhandled_exception(): |
| 43 |
"""Task that raises an unhandled RuntimeError exception.""" |
| 44 |
raise RuntimeError("Unhandled exception for memory leak test") |
| 45 |
|
| 46 |
@self.app.task(bind=True, max_retries=3) |
| 47 |
def task_retry_then_fail(self): |
| 48 |
"""Task that retries multiple times and eventually fails with unhandled exception.""" |
| 49 |
if self.request.retries < self.max_retries: |
| 50 |
raise self.retry(countdown=0.001) |
| 51 |
raise RuntimeError("Final retry failure - unhandled exception") |
| 52 |
|
| 53 |
@self.app.task |
| 54 |
def task_nested_exception_stack(): |
| 55 |
"""Task that raises exception through deeply nested function calls.""" |
| 56 |
def deep_level_5(): |
| 57 |
local_data = {"level": 5, "data": list(range(100))} # noqa: F841 |
| 58 |
raise ValueError("Deep nested exception at level 5") |
| 59 |
|
| 60 |
def deep_level_4(): |
| 61 |
local_data = {"level": 4, "nested": {"data": list(range(50))}} # noqa: F841 |
| 62 |
deep_level_5() |
| 63 |
|
| 64 |
def deep_level_3(): |
| 65 |
local_data = [1, 2, 3, {"nested": True}] # noqa: F841 |
| 66 |
deep_level_4() |
| 67 |
|
| 68 |
def deep_level_2(): |
| 69 |
deep_level_3() |
| 70 |
|
| 71 |
def deep_level_1(): |
| 72 |
deep_level_2() |
| 73 |
|
| 74 |
deep_level_1() |
| 75 |
|
| 76 |
self.task_success = task_success |
| 77 |
self.task_unhandled_exception = task_unhandled_exception |
| 78 |
self.task_retry_then_fail = task_retry_then_fail |
| 79 |
self.task_nested_exception_stack = task_nested_exception_stack |
| 80 |
|
| 81 |
|
| 82 |
def get_memory_usage(): |
| 83 |
""" |
| 84 |
Get current memory usage in bytes. |
| 85 |
|
| 86 |
Returns RSS (total process memory) if psutil is available, |
| 87 |
otherwise returns Python heap allocations via tracemalloc. |
| 88 |
Note: These measurements are not directly comparable. |
| 89 |
""" |
| 90 |
try: |
| 91 |
import psutil |
| 92 |
process = psutil.Process(os.getpid()) |
| 93 |
return process.memory_info().rss |
| 94 |
except ImportError: |
| 95 |
# Fallback to tracemalloc if psutil not available |
| 96 |
current, peak = tracemalloc.get_traced_memory() |
| 97 |
return current |
| 98 |
|
| 99 |
|
| 100 |
def test_mem_leak_unhandled_exceptions(): |
| 101 |
"""Test that reproduces the memory leak when tasks raise unhandled exceptions.""" |
| 102 |
|
| 103 |
# Setup |
| 104 |
test_instance = MemoryLeakUnhandledExceptionsTest() |
| 105 |
|
| 106 |
# Enable memory tracing |
| 107 |
tracemalloc.start() |
| 108 |
|
| 109 |
# Warm up - run some successful tasks first |
| 110 |
for _ in range(50): |
| 111 |
try: |
| 112 |
test_instance.task_success.apply() |
| 113 |
except Exception: |
| 114 |
pass |
| 115 |
|
| 116 |
# Force garbage collection and get baseline memory |
| 117 |
gc.collect() |
| 118 |
baseline_memory = get_memory_usage() |
| 119 |
|
| 120 |
# Run many failing tasks - this should demonstrate the leak |
| 121 |
exception_count = 0 |
| 122 |
for _ in range(500): # Reduced from 1000 to make test faster |
| 123 |
try: |
| 124 |
test_instance.task_unhandled_exception.apply() |
| 125 |
except Exception: |
| 126 |
exception_count += 1 |
| 127 |
|
| 128 |
# Force garbage collection |
| 129 |
gc.collect() |
| 130 |
after_exceptions_memory = get_memory_usage() |
| 131 |
|
| 132 |
# Run successful tasks again to ensure the leak is from exceptions |
| 133 |
for _ in range(50): |
| 134 |
try: |
| 135 |
test_instance.task_success.apply() |
| 136 |
except Exception: |
| 137 |
pass |
| 138 |
|
| 139 |
gc.collect() |
| 140 |
final_memory = get_memory_usage() |
| 141 |
|
| 142 |
# Calculate memory increase |
| 143 |
memory_increase = after_exceptions_memory - baseline_memory |
| 144 |
|
| 145 |
# Stop tracing |
| 146 |
tracemalloc.stop() |
| 147 |
|
| 148 |
# Log memory statistics for debugging |
| 149 |
logger.debug("--- Memory Statistics ---") # Separator for better readability |
| 150 |
logger.debug(f"Baseline memory: {baseline_memory / 1024 / 1024:.2f} MB") |
| 151 |
logger.debug(f"After exceptions: {after_exceptions_memory / 1024 / 1024:.2f} MB") |
| 152 |
logger.debug(f"Final memory: {final_memory / 1024 / 1024:.2f} MB") |
| 153 |
logger.debug(f"Memory increase: {memory_increase / 1024 / 1024:.2f} MB") |
| 154 |
logger.debug(f"Exceptions processed: {exception_count}") |
| 155 |
|
| 156 |
# The test should demonstrate a significant memory increase |
| 157 |
# This threshold may need adjustment based on the system |
| 158 |
memory_increase_mb = memory_increase / 1024 / 1024 |
| 159 |
|
| 160 |
# Verify the memory leak is fixed - memory increase should be minimal |
| 161 |
# Before fix: >70MB for 1000 tasks (~70KB/task) |
| 162 |
# After fix: <5MB for 500 tasks (<10KB/task) |
| 163 |
threshold_percent = float(os.getenv("MEMORY_LEAK_THRESHOLD_PERCENT", 10)) # Default: 10% increase |
| 164 |
memory_threshold_mb = baseline_memory / 1024 / 1024 * (threshold_percent / 100) |
| 165 |
assert memory_increase_mb < memory_threshold_mb, ( |
| 166 |
f"Memory leak still exists! Expected <{memory_threshold_mb:.2f}MB increase " |
| 167 |
f"(based on {threshold_percent}% of baseline), " |
| 168 |
f"but got {memory_increase_mb:.2f}MB. " |
| 169 |
f"This indicates the memory leak fix is not working properly." |
| 170 |
) |
| 171 |
|
| 172 |
|
| 173 |
def test_mem_leak_retry_failures(): |
| 174 |
"""Test memory leak with task retry and eventual failure scenarios.""" |
| 175 |
|
| 176 |
test_instance = MemoryLeakUnhandledExceptionsTest() |
| 177 |
|
| 178 |
# Enable memory tracing |
| 179 |
tracemalloc.start() |
| 180 |
|
| 181 |
# Get baseline |
| 182 |
gc.collect() |
| 183 |
baseline_memory = get_memory_usage() |
| 184 |
|
| 185 |
# Run tasks that retry and eventually fail |
| 186 |
for _ in range(100): # Fewer iterations since retries are expensive |
| 187 |
try: |
| 188 |
test_instance.task_retry_then_fail.apply() |
| 189 |
except Exception: |
| 190 |
pass |
| 191 |
|
| 192 |
gc.collect() |
| 193 |
after_retries_memory = get_memory_usage() |
| 194 |
|
| 195 |
# Stop tracing |
| 196 |
tracemalloc.stop() |
| 197 |
|
| 198 |
# Calculate memory increase |
| 199 |
memory_increase = after_retries_memory - baseline_memory |
| 200 |
memory_increase_mb = memory_increase / 1024 / 1024 |
| 201 |
|
| 202 |
logger.debug("") # New line for better readability |
| 203 |
logger.debug(f"Baseline memory: {baseline_memory / 1024 / 1024:.2f} MB") |
| 204 |
logger.debug(f"After retries: {after_retries_memory / 1024 / 1024:.2f} MB") |
| 205 |
logger.debug(f"Memory increase: {memory_increase_mb:.2f} MB") |
| 206 |
|
| 207 |
# Retries should not show significant memory increase if fix is working |
| 208 |
assert memory_increase_mb < 3, ( |
| 209 |
f"Memory leak in retry scenarios! Expected <3MB increase for 100 retry tasks, " |
| 210 |
f"but got {memory_increase_mb:.2f}MB" |
| 211 |
) |
| 212 |
|
| 213 |
|
| 214 |
def test_mem_leak_nested_exception_stacks(): |
| 215 |
"""Test memory leak with deeply nested exception stacks and local variables.""" |
| 216 |
|
| 217 |
test_instance = MemoryLeakUnhandledExceptionsTest() |
| 218 |
|
| 219 |
# Enable memory tracing |
| 220 |
tracemalloc.start() |
| 221 |
|
| 222 |
# Get baseline |
| 223 |
gc.collect() |
| 224 |
baseline_memory = get_memory_usage() |
| 225 |
|
| 226 |
# Run tasks with complex exception stacks |
| 227 |
for _ in range(200): |
| 228 |
try: |
| 229 |
test_instance.task_nested_exception_stack.apply() |
| 230 |
except Exception: |
| 231 |
pass |
| 232 |
|
| 233 |
gc.collect() |
| 234 |
after_complex_memory = get_memory_usage() |
| 235 |
|
| 236 |
# Stop tracing |
| 237 |
tracemalloc.stop() |
| 238 |
|
| 239 |
# Calculate memory increase |
| 240 |
memory_increase = after_complex_memory - baseline_memory |
| 241 |
memory_increase_mb = memory_increase / 1024 / 1024 |
| 242 |
|
| 243 |
logger.debug("Memory usage results:") |
| 244 |
logger.debug(f"Baseline memory: {baseline_memory / 1024 / 1024:.2f} MB") |
| 245 |
logger.debug(f"After complex exceptions: {after_complex_memory / 1024 / 1024:.2f} MB") |
| 246 |
logger.debug(f"Memory increase: {memory_increase_mb:.2f} MB") |
| 247 |
|
| 248 |
# Complex exceptions should not show significant memory increase if fix is working |
| 249 |
assert memory_increase_mb < 4, ( |
| 250 |
f"Memory leak in nested exception scenarios! Expected <4MB increase for 200 nested tasks, " |
| 251 |
f"but got {memory_increase_mb:.2f}MB" |
| 252 |
) |
| 253 |
|
| 254 |
|
| 255 |
if __name__ == "__main__": |
| 256 |
# Allow running these tests standalone for debugging |
| 257 |
print("Running memory leak integration tests...") |
| 258 |
test_mem_leak_unhandled_exceptions() |
| 259 |
test_mem_leak_retry_failures() |
| 260 |
test_mem_leak_nested_exception_stacks() |
| 261 |
print("Memory leak integration tests completed") |