Coverage for tests/common/monero_utils/test_memory.py: 100%
131 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
1from __future__ import annotations
3import gc
4import logging
5import subprocess
6import sys
8import pytest
9from monero import (
10 MoneroBlock,
11 MoneroIncomingTransfer,
12 MoneroOutputWallet,
13 MoneroTx,
14 MoneroTxWallet,
15 MoneroUtils,
16)
18from utils import BaseTestClass
20if sys.platform != "win32":
21 import resource
23logger: logging.Logger = logging.getLogger("TestMoneroUtilsMemory")
26@pytest.mark.unit
27class TestMoneroUtilsMemory(BaseTestClass):
28 """Monero utilities memory unit tests."""
30 def test_free_block_breaks_tx_backlink(self) -> None:
31 block: MoneroBlock = MoneroBlock()
32 block.height = 100
33 tx: MoneroTxWallet = MoneroTxWallet()
34 tx.hash = "a" * 64
35 tx.block = block
36 block.txs = [tx]
38 MoneroUtils.free(block)
39 assert tx.block is None
41 def test_free_blocks_list(self) -> None:
42 block1: MoneroBlock = MoneroBlock()
43 block1.height = 1
44 tx1: MoneroTxWallet = MoneroTxWallet()
45 tx1.hash = "a" * 64
46 tx1.block = block1
47 block1.txs = [tx1]
49 block2: MoneroBlock = MoneroBlock()
50 block2.height = 2
51 tx2: MoneroTxWallet = MoneroTxWallet()
52 tx2.hash = "b" * 64
53 tx2.block = block2
54 block2.txs = [tx2]
56 MoneroUtils.free([block1, block2])
57 assert tx1.block is None
58 assert tx2.block is None
60 def test_free_tx_without_block_does_not_crash(self) -> None:
61 # free(tx) creates a throwaway placeholder block for an unconfirmed
62 # tx, then immediately frees it. Net no-op on tx.block, but exercises
63 # that code path safely
64 tx: MoneroTxWallet = MoneroTxWallet()
65 tx.hash = "a" * 64
66 assert tx.block is None
67 MoneroUtils.free(tx)
68 assert tx.block is None
70 def test_free_tx_with_block(self) -> None:
71 block: MoneroBlock = MoneroBlock()
72 block.height = 100
73 tx: MoneroTxWallet = MoneroTxWallet()
74 tx.hash = "a" * 64
75 tx.block = block
76 block.txs = [tx]
78 MoneroUtils.free(tx)
79 assert tx.block is None
81 def test_free_txs_list_confirmed_and_unconfirmed(self) -> None:
82 block: MoneroBlock = MoneroBlock()
83 block.height = 100
84 confirmed: MoneroTxWallet = MoneroTxWallet()
85 confirmed.hash = "a" * 64
86 confirmed.block = block
87 block.txs = [confirmed]
89 unconfirmed: MoneroTxWallet = MoneroTxWallet()
90 unconfirmed.hash = "b" * 64
92 MoneroUtils.free([confirmed, unconfirmed])
93 assert confirmed.block is None
94 assert unconfirmed.block is None
96 def test_free_transfers_list(self) -> None:
97 block: MoneroBlock = MoneroBlock()
98 block.height = 100
99 tx: MoneroTxWallet = MoneroTxWallet()
100 tx.hash = "a" * 64
101 tx.block = block
102 block.txs = [tx]
104 transfer: MoneroIncomingTransfer = MoneroIncomingTransfer()
105 transfer.tx = tx
107 MoneroUtils.free([transfer])
108 assert transfer.tx.block is None
110 def test_free_outputs_list(self) -> None:
111 block: MoneroBlock = MoneroBlock()
112 block.height = 100
113 tx: MoneroTxWallet = MoneroTxWallet()
114 tx.hash = "a" * 64
115 tx.block = block
116 block.txs = [tx]
118 output: MoneroOutputWallet = MoneroOutputWallet()
119 output.tx = tx
121 MoneroUtils.free([output])
122 assert output.tx.block is None
124 @pytest.mark.skipif(sys.platform == "win32", reason="resource module (RSS measurement) is not available on Windows")
125 def test_free_breaks_reference_cycle_avoids_leak(self) -> None:
126 # regression guard for the leak demonstrated manually: building
127 # block<->tx cycles and dropping every Python reference without
128 # calling free() leaves the C++ shared_ptr cycle permanently
129 # unreachable-but-alive (confirmed: 2,000,000 such tx objects grew
130 # RSS by ~2.4GB with gc.collect() unable to reclaim any of it). This
131 # test builds a much smaller-but-still-telling batch, always calling
132 # free() before dropping references, and asserts memory stays roughly flat.
133 def rss_mb() -> float:
134 return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024
136 def run_batch(rounds: int) -> None:
137 for _ in range(rounds):
138 for _ in range(50):
139 block: MoneroBlock = MoneroBlock()
140 block.height = 100
141 txs: list[MoneroTx] = []
142 for i in range(20):
143 tx: MoneroTxWallet = MoneroTxWallet()
144 tx.hash = "a" * 63 + str(i % 10)
145 tx.block = block
146 txs.append(tx)
147 block.txs = txs
148 MoneroUtils.free(block)
150 gc.disable()
151 try:
152 run_batch(20) # unmeasured warmup: absorb one-time allocator growth
153 baseline: float = rss_mb()
154 run_batch(200) # measured: 200 * 50 * 20 = 200,000 tx objects
155 after: float = rss_mb()
156 finally:
157 gc.enable()
159 growth_mb: float = after - baseline
160 logger.debug(f"RSS growth after freeing 200,000 tx objects (post-warmup): {growth_mb:.1f} MB")
161 # generous bound: a real leak of this shape grows ~1.2KB/tx (~240MB for
162 # 200,000 tx); this only needs to rule out that magnitude of leak, not
163 # pin down normal allocator noise
164 assert growth_mb < 100, f"RSS grew {growth_mb:.1f} MB after freeing 200,000 tx objects -- possible leak"
166 def test_free_none_does_not_crash(self) -> None:
167 script: str = "import monero\nmonero.MoneroUtils.free(None)\n"
168 result: subprocess.CompletedProcess[str] = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=30)
169 logger.debug(f"subprocess exit code: {result.returncode}, stderr: {result.stderr.strip()}")
170 assert result.returncode == 0, (
171 f"free(None) crashed the interpreter (exit code {result.returncode}) "
172 "instead of raising a Python exception (or being a documented no-op)"
173 )
175 def test_free_transfers_missing_tx_raises(self) -> None:
176 # free([transfers]) delegates to get_blocks_from_transfers(): a transfer
177 # with no tx must surface a catchable exception, not segfault
178 transfer: MoneroIncomingTransfer = MoneroIncomingTransfer()
179 transfer.amount = 500000
180 with pytest.raises(RuntimeError) as exc_info:
181 MoneroUtils.free([transfer])
182 assert str(exc_info.value) == "Transfer has no tx"
184 def test_free_outputs_missing_tx_raises(self) -> None:
185 # free([outputs]) delegates to get_blocks_from_outputs(): same guarantee
186 output: MoneroOutputWallet = MoneroOutputWallet()
187 output.amount = 1000000
188 with pytest.raises(RuntimeError) as exc_info:
189 MoneroUtils.free([output])
190 assert str(exc_info.value) == "Output has no tx"