test_gms_runtime_flows.py 28.1 KB
Newer Older
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
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations

import asyncio
import itertools
import os
import signal
import socket
import subprocess
import sys
import textwrap
import threading
import time

import pynvml
import pytest
from gpu_memory_service.client import memory_manager as client_memory_manager
from gpu_memory_service.client.memory_manager import (
    GMSClientMemoryManager,
    StaleMemoryLayoutError,
)
from gpu_memory_service.client.rpc import _GMSRPCTransport
from gpu_memory_service.client.session import _GMSClientSession
from gpu_memory_service.common import cuda_utils
27
from gpu_memory_service.common.locks import GrantedLockType, RequestedLockType
28
29
30
31
32
33
34
35
from gpu_memory_service.common.protocol.messages import (
    GetEventHistoryRequest,
    GetEventHistoryResponse,
    GetRuntimeStateRequest,
    GetRuntimeStateResponse,
)
from gpu_memory_service.server import allocations as server_allocations
from gpu_memory_service.server.allocations import GMSAllocationManager
36
from gpu_memory_service.server.fsm import ServerState
37
38
39
40
41
42
43
from gpu_memory_service.server.rpc import GMSRPCServer

from tests.gms.harness.gms import ServerThread

pytestmark = [
    pytest.mark.pre_merge,
    pytest.mark.unit,
44
45
    pytest.mark.none,
    pytest.mark.gpu_1,
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
]


def _gpu_memory_free_bytes(device: int = 0) -> int:
    pynvml.nvmlInit()
    try:
        handle = pynvml.nvmlDeviceGetHandleByIndex(device)
        return int(pynvml.nvmlDeviceGetMemoryInfo(handle).free)
    finally:
        pynvml.nvmlShutdown()


def _drop_connection(session: _GMSClientSession) -> None:
    # Use a raw transport break here, not abort(), because these tests need to
    # simulate an unexpected socket loss while a request is still in flight.
    sock = session._transport._socket
    assert sock is not None
    try:
        sock.shutdown(socket.SHUT_RDWR)
    except OSError:
        pass
    sock.close()
    session._transport._socket = None


def _wait_for_server_state(
    server: GMSRPCServer,
    expected: ServerState,
    timeout: float = 2.0,
) -> None:
    deadline = time.monotonic() + timeout
    while server.state != expected:
        if time.monotonic() > deadline:
            raise TimeoutError(f"server did not reach {expected.name}")
        time.sleep(0.01)


def _wait_for_waiting_writers(
    server: GMSRPCServer,
    expected: int,
    timeout: float = 2.0,
) -> None:
    deadline = time.monotonic() + timeout
    while server._gms._sessions.snapshot().waiting_writers != expected:
        if time.monotonic() > deadline:
            raise TimeoutError(f"waiting writers did not reach {expected}")
        time.sleep(0.01)


def _wait_for_ro_session_count(
    server: GMSRPCServer,
    expected: int,
    timeout: float = 2.0,
) -> None:
    deadline = time.monotonic() + timeout
    while server._gms._sessions.snapshot().ro_session_count != expected:
        if time.monotonic() > deadline:
            raise TimeoutError(f"RO session count did not reach {expected}")
        time.sleep(0.01)


@pytest.fixture
def real_gms(monkeypatch, tmp_path):
    server_handles = itertools.count(1000)
    client_handles = itertools.count(10000)
    next_va = itertools.count(0x100000, 0x10000)

    monkeypatch.setattr(server_allocations, "cuda_ensure_initialized", lambda: None)
    monkeypatch.setattr(
        server_allocations,
        "cumem_get_allocation_granularity",
        lambda device: 4096,
    )
    monkeypatch.setattr(
        server_allocations,
        "cumem_create_tolerate_oom",
        lambda size, device: (True, next(server_handles)),
    )
    monkeypatch.setattr(server_allocations, "cumem_release", lambda handle: None)

    def export_fd(handle: int) -> int:
        read_fd, write_fd = os.pipe()
        os.close(write_fd)
        return read_fd

    monkeypatch.setattr(
        server_allocations, "cumem_export_to_shareable_handle", export_fd
    )

    monkeypatch.setattr(
        client_memory_manager, "cuda_set_current_device", lambda device: None
    )
    monkeypatch.setattr(
        client_memory_manager,
        "cumem_get_allocation_granularity",
        lambda device: 4096,
    )
    monkeypatch.setattr(client_memory_manager, "cuda_synchronize", lambda: None)
    monkeypatch.setattr(
        client_memory_manager,
        "cumem_address_reserve",
        lambda size, granularity: next(next_va),
    )
    monkeypatch.setattr(
        client_memory_manager,
        "cumem_address_free",
        lambda va, size: None,
    )
    monkeypatch.setattr(
        client_memory_manager, "cumem_map", lambda va, size, handle: None
    )
    monkeypatch.setattr(
        client_memory_manager,
        "cumem_set_access",
        lambda va, size, device, mode: None,
    )
    monkeypatch.setattr(client_memory_manager, "cumem_unmap", lambda va, size: None)
    monkeypatch.setattr(client_memory_manager, "cumem_release", lambda handle: None)
    monkeypatch.setattr(client_memory_manager, "cuda_validate_pointer", lambda va: True)

    def import_fd(fd: int) -> int:
        os.close(fd)
        return next(client_handles)

    monkeypatch.setattr(
        client_memory_manager,
        "cumem_import_from_shareable_handle_close_fd",
        import_fd,
    )

    socket_path = str(tmp_path / "gms.sock")
    server = GMSRPCServer(socket_path, device=0, allocation_retry_interval=0.01)
    thread = ServerThread(server, socket_path)
    thread.start()
    try:
        yield server, socket_path
    finally:
        thread.stop()


def test_rw_commit_publishes_allocations_metadata_and_layout_hash(real_gms):
    server, socket_path = real_gms

    writer = GMSClientMemoryManager(socket_path, device=0)
    writer.connect(RequestedLockType.RW)
    va = writer.create_mapping(size=4096, tag="weights")
    allocation_id = writer.mappings[va].allocation_id
    writer.metadata_put("tensor.0", allocation_id, 0, b"weights")
    assert writer.commit()

    reader = _GMSClientSession(socket_path, RequestedLockType.RO, None)
    try:
        assert reader.lock_type == GrantedLockType.RO
        assert reader.committed
        assert len(reader.list_allocations()) == 1
        assert reader.metadata_get("tensor.0") == (allocation_id, 0, b"weights")
        assert reader.get_memory_layout_hash()
    finally:
        reader.close()

    assert writer.is_unmapped
    assert not writer.is_connected
    _wait_for_server_state(server, ServerState.COMMITTED)


def test_rw_disconnect_aborts_layout_and_next_writer_starts_clean(real_gms):
    server, socket_path = real_gms

    writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    allocation_id, _ = writer.allocate(4096, "weights")
    writer.metadata_put("stale", allocation_id, 0, b"value")
    _drop_connection(writer)

    _wait_for_server_state(server, ServerState.EMPTY)

    next_writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    try:
        assert next_writer.list_allocations() == []
        assert next_writer.metadata_list() == []
    finally:
        next_writer.close()


def test_rw_or_ro_grants_rw_from_empty_and_ro_from_committed(real_gms):
    server, socket_path = real_gms

    session = _GMSClientSession(socket_path, RequestedLockType.RW_OR_RO, 100)
    assert session.lock_type == GrantedLockType.RW
    session.commit()

    _wait_for_server_state(server, ServerState.COMMITTED)

    session = _GMSClientSession(socket_path, RequestedLockType.RW_OR_RO, 100)
    try:
        assert session.lock_type == GrantedLockType.RO
        assert session.committed
    finally:
        session.close()


def test_runtime_state_and_event_history_are_side_effect_free(real_gms):
    server, socket_path = real_gms

    writer = GMSClientMemoryManager(socket_path, device=0)
    writer.connect(RequestedLockType.RW)
    writer.create_mapping(size=4096, tag="weights")
    assert writer.commit()

    assert server._gms._sessions.snapshot().ro_session_count == 0

    with _GMSRPCTransport(socket_path) as transport:
        transport.connect()
        state = transport.request(
            GetRuntimeStateRequest(),
            GetRuntimeStateResponse,
        )

    with _GMSRPCTransport(socket_path) as transport:
        transport.connect()
        history = transport.request(
            GetEventHistoryRequest(),
            GetEventHistoryResponse,
        )

    assert state.state == ServerState.COMMITTED.name
    assert state.committed
    assert state.is_ready
    assert state.ro_session_count == 0
    assert state.waiting_writers == 0
    assert state.allocation_count == 1
    assert state.memory_layout_hash
    assert [event.kind for event in history.events] == ["rw_connected", "committed"]
    assert server._gms._sessions.snapshot().ro_session_count == 0


def test_committed_layout_is_replaced_when_new_writer_connects(real_gms):
    server, socket_path = real_gms

    first_writer = GMSClientMemoryManager(socket_path, device=0)
    first_writer.connect(RequestedLockType.RW)
    first_writer.create_mapping(size=4096, tag="weights")
    assert first_writer.commit()

    _wait_for_server_state(server, ServerState.COMMITTED)
    assert server._gms.allocation_count == 1

    second_writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    try:
        assert second_writer.lock_type == GrantedLockType.RW
        assert second_writer.list_allocations() == []
        assert second_writer.metadata_list() == []
        assert server._gms.allocation_count == 0
        assert server.state == ServerState.RW
        assert not server._gms.committed
    finally:
        second_writer.close()


def test_reader_mapping_disconnect_then_next_writer_clears_old_layout(real_gms):
    server, socket_path = real_gms

    writer = GMSClientMemoryManager(socket_path, device=0)
    writer.connect(RequestedLockType.RW)
    va = writer.create_mapping(size=4096, tag="weights")
    allocation_id = writer.mappings[va].allocation_id
    assert writer.commit()

    reader = GMSClientMemoryManager(socket_path, device=0)
    reader.connect(RequestedLockType.RO)
    imported_va = reader.create_mapping(allocation_id=allocation_id)
    assert reader.mappings[imported_va].handle != 0

    next_writer_result: dict[str, object] = {}

    def open_writer() -> None:
        try:
            next_writer_result["session"] = _GMSClientSession(
                socket_path,
                RequestedLockType.RW,
                500,
            )
        except Exception as exc:
            next_writer_result["error"] = exc

    thread = threading.Thread(target=open_writer)
    thread.start()
    _wait_for_waiting_writers(server, 1)

    assert thread.is_alive()
    assert server.state == ServerState.RO
    assert server._gms.allocation_count == 1

    reader.unmap_all_vas()
    reader.abort()
    thread.join(timeout=2)

    next_writer = next_writer_result.get("session")
    assert isinstance(next_writer, _GMSClientSession)
    try:
        assert next_writer.lock_type == GrantedLockType.RW
        assert next_writer.list_allocations() == []
        assert server._gms.allocation_count == 0
        assert server.state == ServerState.RW
        assert not server._gms.committed
    finally:
        next_writer.close()


def test_waiting_writer_blocks_new_readers_until_last_reader_disconnects(real_gms):
    server, socket_path = real_gms

    writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    writer.commit()

    reader = _GMSClientSession(socket_path, RequestedLockType.RO, None)
    writer_result: dict[str, object] = {}

    def open_writer() -> None:
        try:
            writer_result["session"] = _GMSClientSession(
                socket_path,
                RequestedLockType.RW,
                500,
            )
        except Exception as exc:
            writer_result["error"] = exc

    thread = threading.Thread(target=open_writer)
    thread.start()
    _wait_for_waiting_writers(server, 1)

    with pytest.raises(TimeoutError, match="Timeout waiting for lock"):
        _GMSClientSession(socket_path, RequestedLockType.RO, 100)

    reader.close()
    thread.join(timeout=2)

    waiting_writer = writer_result.get("session")
    assert isinstance(waiting_writer, _GMSClientSession)
    try:
        assert waiting_writer.lock_type == GrantedLockType.RW
    finally:
        waiting_writer.close()


def test_rw_or_ro_times_out_while_writer_waits_behind_reader(real_gms):
    server, socket_path = real_gms

    writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    writer.commit()

    reader = _GMSClientSession(socket_path, RequestedLockType.RO, None)
    waiting_writer: dict[str, object] = {}

    def block_writer() -> None:
        try:
            waiting_writer["session"] = _GMSClientSession(
                socket_path,
                RequestedLockType.RW,
                500,
            )
        except Exception as exc:
            waiting_writer["error"] = exc

    thread = threading.Thread(target=block_writer)
    thread.start()
    _wait_for_waiting_writers(server, 1)

    with pytest.raises(TimeoutError, match="Timeout waiting for lock"):
        _GMSClientSession(socket_path, RequestedLockType.RW_OR_RO, 100)

    reader.close()
    thread.join(timeout=2)
    granted_writer = waiting_writer.get("session")
    assert isinstance(granted_writer, _GMSClientSession)
    granted_writer.close()


def test_reader_can_acquire_after_waiting_writer_times_out(real_gms):
    server, socket_path = real_gms

    writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    writer.commit()

    reader = _GMSClientSession(socket_path, RequestedLockType.RO, None)
    writer_result: dict[str, BaseException | None] = {"error": None}

    def timeout_writer() -> None:
        try:
            _GMSClientSession(socket_path, RequestedLockType.RW, 100)
        except BaseException as exc:
            writer_result["error"] = exc

    thread = threading.Thread(target=timeout_writer)
    thread.start()
    _wait_for_waiting_writers(server, 1)
    thread.join(timeout=2)

    assert isinstance(writer_result["error"], TimeoutError)
    _wait_for_waiting_writers(server, 0)

    second_reader = _GMSClientSession(socket_path, RequestedLockType.RO, 200)
    try:
        assert second_reader.lock_type == GrantedLockType.RO
    finally:
        second_reader.close()
        reader.close()


def test_multiple_readers_hold_committed_state_until_last_disconnect(real_gms):
    server, socket_path = real_gms

    writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    writer.commit()

    reader_a = _GMSClientSession(socket_path, RequestedLockType.RO, None)
    reader_b = _GMSClientSession(socket_path, RequestedLockType.RO, None)

    _wait_for_server_state(server, ServerState.RO)
    assert server._gms._sessions.snapshot().ro_session_count == 2

    reader_a.close()
    _wait_for_ro_session_count(server, 1)
    assert server.state == ServerState.RO

    reader_b.close()
    _wait_for_server_state(server, ServerState.COMMITTED)


def test_ro_session_rejects_rw_only_requests(real_gms):
    _, socket_path = real_gms

    writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    writer.commit()

    reader = _GMSClientSession(socket_path, RequestedLockType.RO, None)
    try:
        with pytest.raises(RuntimeError, match="not allowed for RO session"):
            reader.allocate(4096, "weights")
        with pytest.raises(RuntimeError, match="not allowed for RO session"):
            reader.commit()
    finally:
        reader.close()


def test_lock_and_allocation_state_requests_reflect_real_server_state(real_gms):
    _, socket_path = real_gms

    writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    allocation_id, _ = writer.allocate(4096, "weights")

    lock_state = writer.get_lock_state()
    allocation_state = writer.get_allocation_state()

    assert lock_state.state == ServerState.RW.name
    assert lock_state.has_rw_session
    assert lock_state.ro_session_count == 0
    assert allocation_state.allocation_count == 1

    writer.metadata_put("tensor.0", allocation_id, 0, b"x")
    writer.commit()

    reader = _GMSClientSession(socket_path, RequestedLockType.RO, None)
    try:
        lock_state = reader.get_lock_state()
        allocation_state = reader.get_allocation_state()
        assert lock_state.state == ServerState.RO.name
        assert not lock_state.has_rw_session
        assert lock_state.ro_session_count == 1
        assert allocation_state.allocation_count == 1
    finally:
        reader.close()


def test_invalid_metadata_offset_is_rejected_without_mutating_state(real_gms):
    _, socket_path = real_gms

    writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    try:
        allocation_id, _ = writer.allocate(4096, "weights")
        with pytest.raises(RuntimeError, match="out of range"):
            writer.metadata_put("tensor.bad", allocation_id, 4096, b"x")
        assert writer.metadata_list() == []
    finally:
        writer.close()


def test_destroy_mapping_frees_allocation_and_metadata(real_gms):
    _, socket_path = real_gms

    writer = GMSClientMemoryManager(socket_path, device=0)
    writer.connect(RequestedLockType.RW)
    va = writer.create_mapping(size=4096, tag="weights")
    allocation_id = writer.mappings[va].allocation_id
    writer.metadata_put("tensor.0", allocation_id, 0, b"payload")

    writer.destroy_mapping(va)

    assert writer.list_handles() == []
    assert writer.metadata_list() == []
    writer.abort()


def test_remap_all_vas_succeeds_when_committed_layout_is_unchanged(real_gms):
    _, socket_path = real_gms

    writer = GMSClientMemoryManager(socket_path, device=0)
    writer.connect(RequestedLockType.RW)
    va = writer.create_mapping(size=4096, tag="weights")
    allocation_id = writer.mappings[va].allocation_id
    assert writer.commit()

    reader = GMSClientMemoryManager(socket_path, device=0)
    reader.connect(RequestedLockType.RO)
    imported_va = reader.create_mapping(allocation_id=allocation_id)
    imported_mapping = reader.mappings[imported_va]
    reader.unmap_all_vas()
    reader.abort()

    reader.connect(RequestedLockType.RO)
    reader.remap_all_vas()

    assert reader.mappings[imported_va].handle != 0
    assert reader.mappings[imported_va].allocation_id == imported_mapping.allocation_id
    reader.close()


def test_remap_all_vas_rejects_stale_layout_after_new_layout_commit(real_gms):
    _, socket_path = real_gms

    writer = GMSClientMemoryManager(socket_path, device=0)
    writer.connect(RequestedLockType.RW)
    va = writer.create_mapping(size=4096, tag="weights")
    allocation_id = writer.mappings[va].allocation_id
    assert writer.commit()

    reader = GMSClientMemoryManager(socket_path, device=0)
    reader.connect(RequestedLockType.RO)
    reader.create_mapping(allocation_id=allocation_id)
    reader.unmap_all_vas()
    reader.abort()

    next_writer = GMSClientMemoryManager(socket_path, device=0)
    next_writer.connect(RequestedLockType.RW)
    next_writer.create_mapping(size=8192, tag="weights")
    assert next_writer.commit()

    reader.connect(RequestedLockType.RO)
    with pytest.raises(StaleMemoryLayoutError, match="Layout changed"):
        reader.remap_all_vas()
    reader.abort()


def test_remap_all_vas_accepts_new_layout_with_same_structural_layout(real_gms):
    _, socket_path = real_gms

    first_writer = GMSClientMemoryManager(socket_path, device=0)
    first_writer.connect(RequestedLockType.RW)
    va = first_writer.create_mapping(size=4096, tag="weights")
    first_allocation_id = first_writer.mappings[va].allocation_id
    first_writer.metadata_put("tensor.0", first_allocation_id, 0, b"shape")
    assert first_writer.commit()

    reader = GMSClientMemoryManager(socket_path, device=0)
    reader.connect(RequestedLockType.RO)
    imported_va = reader.create_mapping(allocation_id=first_allocation_id)
    reader.unmap_all_vas()
    reader.abort()

    second_writer = GMSClientMemoryManager(socket_path, device=0)
    second_writer.connect(RequestedLockType.RW)
    second_va = second_writer.create_mapping(size=4096, tag="weights")
    second_allocation_id = second_writer.mappings[second_va].allocation_id
    assert second_allocation_id != first_allocation_id
    second_writer.metadata_put("tensor.0", second_allocation_id, 0, b"shape")
    assert second_writer.commit()

    reader.connect(RequestedLockType.RO)
    reader.remap_all_vas()

    assert reader.mappings[imported_va].va == imported_va
    assert reader.mappings[imported_va].allocation_id == second_allocation_id
    assert reader.metadata_get("tensor.0") == (second_allocation_id, 0, b"shape")
    reader.close()


def test_reallocate_all_handles_reuses_preserved_vas_in_new_layout(real_gms):
    server, socket_path = real_gms

    manager = GMSClientMemoryManager(socket_path, device=0)
    manager.connect(RequestedLockType.RW)
    va = manager.create_mapping(size=4096, tag="weights")
    old_allocation_id = manager.mappings[va].allocation_id
    assert manager.commit()

    _wait_for_server_state(server, ServerState.COMMITTED)
    manager.connect(RequestedLockType.RW)
    manager.reallocate_all_handles(tag="weights")

    assert manager.mappings[va].allocation_id != old_allocation_id
    assert manager.mappings[va].handle == 0

    manager.remap_all_vas()

    assert manager.mappings[va].va == va
    assert manager.mappings[va].handle != 0
    manager.close()
    _wait_for_server_state(server, ServerState.EMPTY)


def test_same_process_republish_remaps_against_new_committed_hash(real_gms):
    _, socket_path = real_gms

    manager = GMSClientMemoryManager(socket_path, device=0)
    manager.connect(RequestedLockType.RW)
    va = manager.create_mapping(size=4096, tag="weights")
    first_allocation_id = manager.mappings[va].allocation_id
    manager.metadata_put("tensor", first_allocation_id, 0, b"publish-1")
    assert manager.commit()

    manager.connect(RequestedLockType.RO)
    manager.remap_all_vas()
    manager.unmap_all_vas()
    manager.abort()

    manager.connect(RequestedLockType.RW)
    manager.reallocate_all_handles(tag="weights")
    second_allocation_id = manager.mappings[va].allocation_id
    assert second_allocation_id != first_allocation_id
    manager.remap_all_vas()
    manager.metadata_put("tensor", second_allocation_id, 0, b"publish-2")
    assert manager.commit()

    manager.connect(RequestedLockType.RO)
    manager.remap_all_vas()

    assert manager.mappings[va].va == va
    assert manager.mappings[va].allocation_id == second_allocation_id
    assert manager.metadata_get("tensor") == (second_allocation_id, 0, b"publish-2")

    manager.close()


def test_disconnect_during_allocation_retry_aborts_writer_and_unblocks_next_writer(
    real_gms,
    monkeypatch,
):
    server, socket_path = real_gms
    oom_attempts = 0
    allow_allocation = False

    def always_oom(size: int, device: int) -> tuple[bool, int]:
        nonlocal oom_attempts
        nonlocal allow_allocation
        if allow_allocation:
            return True, 4242
        oom_attempts += 1
        return False, 0

    monkeypatch.setattr(
        "gpu_memory_service.server.allocations.cumem_create_tolerate_oom",
        always_oom,
    )

    writer = _GMSClientSession(socket_path, RequestedLockType.RW, None)
    result: dict[str, BaseException] = {}

    def allocate() -> None:
        try:
            writer.allocate(4096, "weights")
        except BaseException as exc:
            result["error"] = exc

    thread = threading.Thread(target=allocate)
    thread.start()
    deadline = time.monotonic() + 2.0
    while oom_attempts == 0:
        if time.monotonic() > deadline:
            raise TimeoutError("allocation retry never reached CUDA OOM")
        time.sleep(0.01)

    _drop_connection(writer)

    thread.join(timeout=2)
    _wait_for_server_state(server, ServerState.EMPTY)

    allow_allocation = True
    next_writer = _GMSClientSession(socket_path, RequestedLockType.RW, 200)
    try:
        assert next_writer.lock_type == GrantedLockType.RW
        allocation_id, aligned_size = next_writer.allocate(4096, "weights")
        assert allocation_id
        assert aligned_size == 4096
    finally:
        next_writer.close()

    assert isinstance(result.get("error"), ConnectionError)


@pytest.mark.asyncio
@pytest.mark.timeout(180)
async def test_new_layout_large_allocation_waits_for_dead_writer_process(
    tmp_path,
    monkeypatch,
):
    free_before = _gpu_memory_free_bytes()
    size = int(free_before * 0.9)
    assert size > 0

    oom_failures = 0

    def count_oom(size: int, device: int) -> tuple[bool, int]:
        nonlocal oom_failures
        allocated, handle = cuda_utils.cumem_create_tolerate_oom(size, device)
        if not allocated:
            oom_failures += 1
        return allocated, handle

    monkeypatch.setattr(
        "gpu_memory_service.server.allocations.cumem_create_tolerate_oom",
        count_oom,
    )

    allocations = GMSAllocationManager(
        device=0,
        allocation_retry_interval=0.1,
        allocation_retry_timeout=120.0,
    )
    holder = None
    allocation_task = None

    try:
        first = await allocations.allocate(
            size=size,
            tag="weights",
            is_connected=lambda: True,
        )
        assert first.layout_slot == 0

        free_after_first = _gpu_memory_free_bytes()
        assert free_after_first < free_before - (size // 2)

        exported_fd = allocations.export_allocation(first.allocation_id)
        holder_ready = tmp_path / "holder.ready"
        holder_log = tmp_path / "holder.log"
        holder_script = tmp_path / "hold_import.py"
        holder_script.write_text(
            textwrap.dedent(
                """
                import sys
                import time
                from pathlib import Path

                fd = int(sys.argv[1])
                Path(sys.argv[2]).write_text(str(fd))

                while True:
                    time.sleep(1.0)
                """
            ),
            encoding="utf-8",
        )

        with holder_log.open("w", encoding="utf-8") as log_file:
            holder = subprocess.Popen(
                [
                    sys.executable,
                    str(holder_script),
                    str(exported_fd),
                    str(holder_ready),
                ],
                pass_fds=[exported_fd],
                stdout=log_file,
                stderr=subprocess.STDOUT,
                start_new_session=True,
            )
        os.close(exported_fd)

        deadline = time.monotonic() + 30.0
        while not holder_ready.exists():
            assert holder.poll() is None, holder_log.read_text(encoding="utf-8")
            assert time.monotonic() < deadline, holder_log.read_text(encoding="utf-8")
            await asyncio.sleep(0.1)

        allocations.clear_all()
        assert allocations.allocation_count == 0

        allocation_task = asyncio.create_task(
            allocations.allocate(
                size=size,
                tag="weights",
                is_connected=lambda: True,
            )
        )

        deadline = time.monotonic() + 30.0
        while oom_failures == 0:
            assert holder.poll() is None, holder_log.read_text(encoding="utf-8")
            assert not allocation_task.done()
            assert time.monotonic() < deadline
            await asyncio.sleep(0.1)

        assert oom_failures > 0
        assert not allocation_task.done()

        os.killpg(os.getpgid(holder.pid), signal.SIGKILL)
        holder.wait(timeout=30.0)

        second = await asyncio.wait_for(allocation_task, timeout=120.0)
        assert second.layout_slot == 0
        assert allocations.allocation_count == 1

        allocations.clear_all()
        assert allocations.allocation_count == 0

        deadline = time.monotonic() + 30.0
        while _gpu_memory_free_bytes() < free_before - (1 << 30):
            assert time.monotonic() < deadline
            await asyncio.sleep(0.1)
    finally:
        if allocation_task is not None and not allocation_task.done():
            allocation_task.cancel()
            try:
                await allocation_task
            except asyncio.CancelledError:
                pass
        if allocations.allocation_count > 0:
            allocations.clear_all()
        if holder is not None and holder.poll() is None:
            os.killpg(os.getpgid(holder.pid), signal.SIGKILL)
            holder.wait(timeout=30.0)