File: test_socket.py

package info (click to toggle)
python-memray 1.17.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 24,396 kB
  • sloc: python: 28,451; ansic: 16,507; sh: 10,586; cpp: 8,494; javascript: 1,474; makefile: 822; awk: 12
file content (422 lines) | stat: -rw-r--r-- 12,499 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
"""Tests to exercise socket-based read and write operations in the Tracker."""

import os
import subprocess
import sys
import textwrap
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Iterator
from typing import Set
from typing import Tuple

import pytest

from memray import AllocatorType
from memray import SocketReader
from tests.utils import filter_relevant_allocations

TIMEOUT = 5
ALLOCATION_SIZE = 1234
MULTI_ALLOCATION_COUNT = 10

#
# Test helpers
#
_SCRIPT_TEMPLATE = """
import sys
from memray._test import MemoryAllocator
from memray._memray import SocketDestination
from memray._memray import Tracker

# Sanity checks
port = int(sys.argv[1])
assert sys.argv[2].endswith("allocations_made.event")
assert sys.argv[3].endswith("snapshot_taken.event")


def get_tracker():
    return Tracker(destination=SocketDestination(server_port=port))


def snapshot_point():
    print("[child] Notifying allocations made")
    with open(sys.argv[2], "w") as allocations_made:
        allocations_made.write("done")
    print("[child] Waiting on snapshot taken")
    with open(sys.argv[3], "r") as snapshot_taken:
        response = snapshot_taken.read()
    assert response == "done"
    print("[child] Continuing execution")

{body}
"""

ALLOCATE_THEN_FREE_THEN_SNAPSHOT = textwrap.dedent(
    f"""
        allocator = MemoryAllocator()

        with get_tracker():
            allocator.valloc({ALLOCATION_SIZE})
            allocator.free()
            snapshot_point()
    """
)
ALLOCATE_THEN_SNAPSHOT_THEN_FREE = textwrap.dedent(
    f"""
        allocator = MemoryAllocator()
        with get_tracker():
            allocator.valloc({ALLOCATION_SIZE})
            snapshot_point()
            allocator.free()
    """
)
ALLOCATE_MANY_THEN_SNAPSHOT_THEN_FREE_MANY = textwrap.dedent(
    f"""
        allocators = [MemoryAllocator() for _ in range({MULTI_ALLOCATION_COUNT})]
        with get_tracker():
            for allocator in allocators:
                allocator.valloc({ALLOCATION_SIZE})
            snapshot_point()
            for allocator in allocators:
                allocator.free()
    """
)


@contextmanager
def run_till_snapshot_point(
    program: str,
    *,
    reader: SocketReader,
    tmp_path: Path,
    free_port: int,
) -> Iterator[None]:
    allocations_made = tmp_path / "allocations_made.event"
    snapshot_taken = tmp_path / "snapshot_taken.event"
    os.mkfifo(allocations_made)
    os.mkfifo(snapshot_taken)

    script = _SCRIPT_TEMPLATE.format(body=program)

    env = os.environ.copy()
    env.pop("PYTHONMALLOC", None)
    proc = subprocess.Popen(
        [
            sys.executable,
            "-c",
            script,
            str(free_port),
            allocations_made,
            snapshot_taken,
        ],
        env=env,
    )

    try:
        with reader:
            print("[parent] Waiting on allocations made")
            with open(allocations_made, "r") as f1:
                assert f1.read() == "done"

            print("[parent] Deferring to caller")
            # Wait a bit of time, for background thread to receive + process the records.
            time.sleep(0.1)
            yield

            print("[parent] Notifying program to continue")
            with open(snapshot_taken, "w") as f2:
                f2.write("done")
            print("[parent] Will close socket reader now.")
    finally:
        print("[parent] Waiting on child to exit.")
        try:
            assert proc.wait(timeout=TIMEOUT) == 0
        except subprocess.TimeoutExpired:
            print("[parent] Killing child, after timeout.")
            proc.kill()
            raise


#
# Actual tests
#
class TestSocketReaderErrorHandling:
    @pytest.mark.valgrind
    def test_get_current_snapshot_raises_before_context(self, free_port: int) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)

        # WHEN / THEN
        with pytest.raises(StopIteration):
            next(reader.get_current_snapshot(merge_threads=False))

    def test_get_is_active_after_context(self, free_port: int, tmp_path: Path) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)
        program = ALLOCATE_THEN_SNAPSHOT_THEN_FREE

        # WHEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path,
            free_port=free_port,
        ):
            pass

        # THEN
        assert reader.is_active is False

    @pytest.mark.valgrind
    def test_get_current_snapshot_raises_after_context(
        self, free_port: int, tmp_path: Path
    ) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)
        program = ALLOCATE_THEN_SNAPSHOT_THEN_FREE

        # WHEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path,
            free_port=free_port,
        ):
            pass

        # THEN
        with pytest.raises(StopIteration):
            next(reader.get_current_snapshot(merge_threads=False))

    @pytest.mark.valgrind
    def test_get_current_snapshot_first_yield_after_context_raises(
        self, free_port: int, tmp_path: Path
    ) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)
        program = ALLOCATE_THEN_SNAPSHOT_THEN_FREE

        # WHEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path,
            free_port=free_port,
        ):
            snapshot = reader.get_current_snapshot(merge_threads=False)

        # THEN
        with pytest.raises(StopIteration):
            next(snapshot)

    @pytest.mark.valgrind
    def test_nested_context_is_diallowed(self, free_port: int, tmp_path: Path) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)
        program = ALLOCATE_THEN_FREE_THEN_SNAPSHOT

        # WHEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path,
            free_port=free_port,
        ):
            # THEN
            with pytest.raises(
                ValueError, match="Can not enter (.*)context (.*)more than once"
            ):
                with reader:
                    pass


class TestSocketReaderAccess:
    @pytest.mark.valgrind
    def test_empty_snapshot_after_free(self, free_port: int, tmp_path: Path) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)
        program = ALLOCATE_THEN_FREE_THEN_SNAPSHOT

        # WHEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path,
            free_port=free_port,
        ):
            unfiltered_snapshot = list(reader.get_current_snapshot(merge_threads=False))

        # THEN
        snapshot = list(filter_relevant_allocations(unfiltered_snapshot))
        assert snapshot == []

    @pytest.mark.valgrind
    def test_single_allocation_snapshot(self, free_port: int, tmp_path: Path) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)
        program = ALLOCATE_THEN_SNAPSHOT_THEN_FREE

        # WHEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path,
            free_port=free_port,
        ):
            unfiltered_snapshot = list(reader.get_current_snapshot(merge_threads=False))

        # THEN
        snapshot = list(filter_relevant_allocations(unfiltered_snapshot))
        assert len(snapshot) == 1

        allocation = snapshot[0]
        assert allocation.size == ALLOCATION_SIZE * 1
        assert allocation.allocator == AllocatorType.VALLOC

        symbol, filename, lineno = allocation.stack_trace()[0]
        assert symbol == "valloc"
        assert filename.endswith("/_test.py")
        assert 0 < lineno < 200

    @pytest.mark.valgrind
    def test_multi_allocation_snapshot(self, free_port: int, tmp_path: Path) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)
        program = ALLOCATE_MANY_THEN_SNAPSHOT_THEN_FREE_MANY

        # WHEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path,
            free_port=free_port,
        ):
            unfiltered_snapshot = list(reader.get_current_snapshot(merge_threads=False))

        # THEN
        snapshot = list(filter_relevant_allocations(unfiltered_snapshot))
        assert len(snapshot) == 1

        allocation = snapshot[0]
        assert allocation.size == ALLOCATION_SIZE * 10
        assert allocation.allocator == AllocatorType.VALLOC

        symbol, filename, lineno = allocation.stack_trace()[0]
        assert symbol == "valloc"
        assert filename.endswith("/_test.py")
        assert 0 < lineno < 200

    @pytest.mark.valgrind
    def test_multiple_context_entries_does_not_crash(
        self, free_port: int, tmp_path: Path
    ) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)
        program = ALLOCATE_THEN_FREE_THEN_SNAPSHOT
        tmp_path_one = tmp_path / "one"
        tmp_path_one.mkdir()
        tmp_path_two = tmp_path / "two"
        tmp_path_two.mkdir()

        # WHEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path_one,
            free_port=free_port,
        ):
            pass

        # THEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path_two,
            free_port=free_port,
        ):
            pass

    @pytest.mark.valgrind
    def test_command_line(self, free_port: int, tmp_path: Path) -> None:
        # GIVEN
        reader = SocketReader(port=free_port)
        program = ALLOCATE_THEN_FREE_THEN_SNAPSHOT

        # WHEN
        with run_till_snapshot_point(
            program,
            reader=reader,
            tmp_path=tmp_path,
            free_port=free_port,
        ):
            command_line = reader.command_line

        # THEN
        assert command_line
        assert command_line.startswith("-c")  # these samples run with `python -c`
        assert str(free_port) in command_line

    @pytest.mark.valgrind
    def test_reading_allocations_while_reading_stack_traces(
        self, free_port: int, tmp_path: Path
    ) -> None:
        """This test exist mainly to give valgrind/helgrind the opportunity to
        see races between fetching stack traces and the background thread
        fetching allocations. Therefore no interesting asserts are done in
        the test itself.

        The test will spawn a tracked process that is constantly creating new
        functions and code objects so the process is constantly sending new
        frames to the SocketReader, triggering tons of updates of the internal
        structures inside. We want to check that if we get the stack traces
        inside the allocations it won't crash/race with fetching new allocations
        """
        # GIVEN
        script = textwrap.dedent(
            f"""\
            from memray._test import MemoryAllocator
            from memray._memray import SocketDestination
            from memray._memray import Tracker
            from itertools import count
            import textwrap

            def foo(allocator, n):
                fname = f"blech_{{n}}"
                namespace = {{}}

                exec(textwrap.dedent(f'''
                def {{fname}}(allocator):
                    allocator.valloc(1024)
                    allocator.free()
                '''), namespace, namespace)

                func = namespace[fname]
                func(allocator)

            with Tracker(destination=SocketDestination(server_port={free_port})):
                allocator = MemoryAllocator()
                for n in count(0):
                    foo(allocator, n)
        """
        )
        code = [
            sys.executable,
            "-c",
            script,
        ]
        traces: Set[Tuple[str, str, int]] = set()
        MAX_TRACES = 10

        # WHEN
        with subprocess.Popen(code) as proc, SocketReader(port=free_port) as reader:
            while len(traces) < MAX_TRACES:
                for allocation in reader.get_current_snapshot(merge_threads=False):
                    traces.update(allocation.stack_trace())

            proc.terminate()

        # THEN
        assert len(traces) >= MAX_TRACES
        proc.returncode == 0