Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions tests/test_accept_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,6 @@ def test_unit_shutdown_stops_the_probe():
unit_class._shutdown_resources(
shutdown_event=threading.Event(),
worker_thread=None,
proxy_thread=None,
zmq_context=None,
put_get_socket=None,
accept_probe=probe,
Expand All @@ -215,7 +214,6 @@ def test_shutdown_without_a_probe_is_a_no_op():
unit_class._shutdown_resources(
shutdown_event=threading.Event(),
worker_thread=None,
proxy_thread=None,
zmq_context=None,
put_get_socket=None,
)
Expand Down
89 changes: 63 additions & 26 deletions tests/test_simple_storage_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

import errno
import pickle
import threading
import time
from pathlib import Path
from uuid import uuid4
Expand Down Expand Up @@ -63,8 +64,8 @@ class MockStorageClient:

def __init__(self, storage_put_get_address, storage_ip, identity=None):
self.context = zmq.Context()
# The storage proxy drops identities outside STORAGE_CLIENT_IDENTITY_PREFIXES, so mirror
# the prefix a real storage manager uses instead of letting ZMQ auto-assign one.
# The storage unit's ROUTER worker drops identities outside STORAGE_CLIENT_IDENTITY_PREFIXES,
# so mirror the prefix a real storage manager uses instead of letting ZMQ auto-assign one.
if identity is None:
identity = f"{STORAGE_MANAGER_IDENTITY_PREFIX}{uuid4().hex[:8]}".encode()
self.socket = create_zmq_socket(self.context, zmq.DEALER, storage_ip, identity=identity)
Expand Down Expand Up @@ -1198,14 +1199,14 @@ def test_storage_unit_checkpoint_load_missing_file(storage_setup, tmp_path):


def test_foreign_payload_dropped_and_unit_stays_usable(storage_setup):
"""A non-TransferQueue peer (e.g. a TLS probe) must not stop the proxy."""
"""A non-TransferQueue peer (e.g. a TLS probe) must not stop the unit worker."""
_, put_get_address, storage_ip = storage_setup

foreign = MockStorageClient(put_get_address, storage_ip, identity=b"foreign_probe")
foreign.socket.setsockopt(zmq.RCVTIMEO, 1000)
# A TLS ClientHello record header: what a port scanner sends to an unknown TCP port.
foreign.socket.send(b"\x16\x03\x01\x02\x00")
# Dropped before the worker, so unlike a decode failure it draws no reply at all.
# Dropped at the identity filter before decoding, so it draws no reply at all.
with pytest.raises(zmq.Again):
foreign.socket.recv_multipart()
foreign.close()
Expand All @@ -1217,7 +1218,7 @@ def test_foreign_payload_dropped_and_unit_stays_usable(storage_setup):


def test_undecodable_request_answered_and_worker_survives(storage_setup):
"""An allowed identity passes the proxy, so the worker itself must survive bad frames."""
"""An allowed identity passes the identity filter, so the worker itself must survive bad frames."""
_, put_get_address, storage_ip = storage_setup

client = MockStorageClient(put_get_address, storage_ip)
Expand All @@ -1230,31 +1231,67 @@ def test_undecodable_request_answered_and_worker_survives(storage_setup):
client.close()


def test_worker_survives_a_reply_failing_between_frames():
"""A reply that fails mid-message must neither end the only worker nor misroute the next reply."""
@pytest.mark.parametrize("failure_mode", ["before_send", "bad_frame_buffer", "mid_recv_multipart"])
def test_pre_send_worker_error_preserves_already_queued_concurrent_requests(failure_mode):
"""A request failing before any SNDMORE frame enters ROUTER keeps queued sibling requests intact."""
unit = SimpleStorageUnit.__ray_metadata__.modified_class({})
process_request = unit._process_one_worker_request
failed = []

def fail_after_identity_frame(worker_socket, monitor):
if not failed:
failed.append(True)
identity = worker_socket.recv_multipart()[0]
worker_socket.send(identity, zmq.SNDMORE)
raise MemoryError
process_request(worker_socket, monitor)

unit._process_one_worker_request = fail_after_identity_frame
initial_router = unit.put_get_socket
first_failed = False
first_arrived = threading.Event()
second_sent = threading.Event()

def fail_first_before_sndmore(router_socket, monitor):
nonlocal first_failed
if not first_failed:
first_failed = True
first_arrived.set()
assert second_sent.wait(timeout=2.0), "client_b did not send in time"
if failure_mode == "mid_recv_multipart":
# Pop identity + header so remaining payload frames stay queued with RCVMORE=1.
router_socket.recv(copy=False)
router_socket.recv(copy=False)
assert router_socket.getsockopt(zmq.RCVMORE)
raise MemoryError("simulated mid-recv_multipart OOM")
frames = router_socket.recv_multipart(copy=False)
assert router_socket.poll(2000, zmq.POLLIN), "second request did not queue on ROUTER in time"
if failure_mode == "bad_frame_buffer":
# Non-buffer object fails inside _send_multipart_reply's pre-send preparation.
return unit._send_multipart_reply(router_socket, frames[0], [object()])
raise RuntimeError("boom before reply send")
return process_request(router_socket, monitor)

unit._process_one_worker_request = fail_first_before_sndmore
address, ip = unit.zmq_server_info.to_addr("put_get_socket"), unit.zmq_server_info.ip
stranded, next_client = MockStorageClient(address, ip), MockStorageClient(address, ip)
stranded.socket.setsockopt(zmq.RCVTIMEO, 1000)
client_a, client_b = MockStorageClient(address, ip), MockStorageClient(address, ip)
client_a.socket.setsockopt(zmq.RCVTIMEO, 500)
client_b.socket.setsockopt(zmq.RCVTIMEO, 2000)
try:
# Prefix tensor bytes with an allowed identity prefix so un-drained RCVMORE frames would pass
# the identity filter and misparse if _worker_loop failed to drain them on error recovery.
spoof_like_tensor = torch.frombuffer(bytearray(b"TQ_STORAGE_spoof"), dtype=torch.uint8)
msg_a = ZMQMessage.create(
request_type=ZMQRequestType.PUT_DATA,
sender_id="mock_client_a",
body={"global_indexes": [0, 2], "data": {"val": [spoof_like_tensor, torch.tensor([1.0])]}},
)
msg_b = ZMQMessage.create(
request_type=ZMQRequestType.PUT_DATA,
sender_id="mock_client_b",
body={"global_indexes": [1], "data": {"val": [torch.tensor([2.0])]}},
)
client_a.socket.send_multipart(msg_a.serialize())
assert first_arrived.wait(timeout=2.0), "client_a request did not reach ROUTER in time"
client_b.socket.send_multipart(msg_b.serialize())
second_sent.set()

reply_b = ZMQMessage.deserialize(client_b.socket.recv_multipart(copy=False))
assert reply_b.request_type == ZMQRequestType.PUT_DATA_RESPONSE
torch.testing.assert_close(unit.storage_data.get_data(["val"], [1])["val"][0], torch.tensor([2.0]))
assert unit.put_get_socket is initial_router
with pytest.raises(zmq.Again):
stranded.send_put(0, [0], {"val": [torch.tensor([1.0])]})
response = next_client.send_put(1, [1], {"val": [torch.tensor([2.0])]})
assert response.request_type == ZMQRequestType.PUT_DATA_RESPONSE
assert not stranded.socket.poll(500), "the next reply was routed to the stranded caller"
client_a.socket.recv_multipart(copy=False)
finally:
stranded.close()
next_client.close()
client_a.close()
client_b.close()
unit.shutdown()
24 changes: 24 additions & 0 deletions tests/test_storage_request_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,30 @@ def test_log_heavy_operation_thresholds(caplog, elapsed, payload_bytes, should_l
assert "serialized_mb=" in caplog.records[0].message


@pytest.mark.asyncio
async def test_request_payload_logs_heavy_put_and_get_on_client(caplog):
large_bytes = 512 * 2**20
transfer = MagicMock(
request=AsyncMock(
side_effect=[
PayloadReply(wire_bytes=large_bytes),
PayloadReply(payload={"input_ids": [torch.tensor([1, 2])]}, wire_bytes=large_bytes),
]
)
)
manager = _manager(transfer=transfer)
manager.notify_data_update = AsyncMock(return_value=True)
data, metadata = _single_sample_batch()

with caplog.at_level(logging.WARNING):
await manager.put_data(data, metadata)
await manager.get_data(metadata)

messages = [r.message for r in caplog.records]
assert any("heavy put to unit_a at 10.0.0.7:5555" in m and "serialized_mb=512.0" in m for m in messages)
assert any("heavy get from unit_a at 10.0.0.7:5555" in m and "serialized_mb=512.0" in m for m in messages)


@pytest.mark.asyncio
@pytest.mark.parametrize(
"tcp_result, probe_result, expected",
Expand Down
144 changes: 114 additions & 30 deletions tests/test_storage_worker_death_exits.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,24 @@

"""The unit process must exit when the thread that answers requests dies.

Worker and proxy both run as daemon threads, so an exception in either only unwinds that
thread: the process stays up with its ROUTER still bound, keeps accepting connections and
never answers them, and every caller blocks until its own timeout. Exiting instead turns a
silent hang into a visible actor failure.
The worker runs as a daemon thread, so an unhandled exception in it only unwinds that thread:
the process stays up with its ROUTER still bound, keeps accepting connections and never answers
them, and every caller blocks until its own timeout. Exiting instead turns a silent hang into a
visible actor failure.
"""

import errno
import threading
from unittest.mock import MagicMock, patch

import pytest
import torch
import zmq
import zmq.utils.garbage

from transfer_queue.storage import simple_storage
from transfer_queue.storage.simple_storage import SimpleStorageUnit
from transfer_queue.utils import common

_StorageUnitClass = SimpleStorageUnit.__ray_metadata__.modified_class

Expand All @@ -38,6 +43,7 @@ def _unit():
unit.storage_unit_id = "TQ_STORAGE_UNIT_test0001"
unit._shutdown_event = threading.Event()
unit._storage_lock = threading.Lock()
unit._router_tainted = False
return unit


Expand Down Expand Up @@ -78,13 +84,9 @@ def test_unhandled_worker_exception_triggers_the_exit():
unit = _unit()
unit._metrics = None
unit._perf_monitor = MagicMock()
unit._node_ip = "127.0.0.1"
unit._inproc_addr = "inproc://worker_death_test"
unit.zmq_context = MagicMock()
unit.put_get_socket = MagicMock()

with (
patch.object(simple_storage, "create_zmq_socket", return_value=MagicMock()),
patch.object(simple_storage.zmq, "Poller", return_value=MagicMock()),
patch.object(_StorageUnitClass, "_worker_loop", side_effect=RuntimeError("boom")),
patch.object(simple_storage.os, "_exit") as exit_call,
):
Expand All @@ -94,43 +96,125 @@ def test_unhandled_worker_exception_triggers_the_exit():
exit_call.assert_called_once_with(simple_storage._WORKER_DEATH_EXIT_CODE)


def _failing_poller(shutdown_event: threading.Event | None = None) -> MagicMock:
"""A proxy poller whose poll raises, optionally after a shutdown has begun."""
def test_unrecoverable_poll_error_exits_on_first_failure():
"""A broken listening ROUTER (e.g. ENOTSOCK) must abort immediately rather than spin."""
unit = _unit()
unit._metrics = None
unit._perf_monitor = MagicMock()
unit.put_get_socket = MagicMock()
poller = MagicMock()
poller.poll.side_effect = zmq.ZMQError(errno.ENOTSOCK)

def poll(timeout):
if shutdown_event is not None:
shutdown_event.set()
raise RuntimeError("proxy boom")
with (
patch.object(simple_storage.zmq, "Poller", return_value=poller),
patch.object(simple_storage.os, "_exit") as exit_call,
):
with pytest.raises(zmq.ZMQError):
unit._worker_routine()

poller = MagicMock()
poller.poll.side_effect = poll
return poller
poller.poll.assert_called_once()
exit_call.assert_called_once_with(simple_storage._WORKER_DEATH_EXIT_CODE)


def test_proxy_death_exits_the_process():
"""Without the proxy nothing reaches the worker, so the unit is equally unreachable."""
def test_poll_error_during_shutdown_exits_cleanly():
unit = _unit()
unit._metrics = None
unit._perf_monitor = MagicMock()
unit.put_get_socket = MagicMock()
unit.worker_socket = MagicMock()

def poll_then_shutdown(_timeout):
unit._shutdown_event.set()
raise zmq.ZMQError(errno.ENOTSOCK)

poller = MagicMock()
poller.poll.side_effect = poll_then_shutdown

with (
patch.object(simple_storage.zmq, "Poller", return_value=_failing_poller()),
patch.object(simple_storage.zmq, "Poller", return_value=poller),
patch.object(simple_storage.os, "_exit") as exit_call,
):
unit._proxy_routine()
unit._worker_routine()

exit_call.assert_called_once_with(simple_storage._WORKER_DEATH_EXIT_CODE)
exit_call.assert_not_called()


def test_proxy_shutdown_does_not_exit():
@pytest.mark.parametrize("fail_on_frame_idx", [1, 2])
def test_mid_multipart_reply_failure_aborts_process_without_misrouting(fail_on_frame_idx):
"""Once a non-final SNDMORE frame entered ROUTER, a subsequent send failure aborts the unit."""
unit = _unit()
unit.put_get_socket = MagicMock()
unit.worker_socket = MagicMock()
unit._metrics = None
unit._perf_monitor = MagicMock()
router = MagicMock(copy_threshold=zmq.COPY_THRESHOLD)
calls = 0

def fail_after_sndmore(_frame, flags=0, **_kwargs):
nonlocal calls
if calls == fail_on_frame_idx:
raise MemoryError("simulated mid-multipart OOM")
calls += 1

router.send.side_effect = fail_after_sndmore
unit.put_get_socket = router
poller = MagicMock()
poller.poll.return_value = [(router, zmq.POLLIN)]

def trigger_partial_send(sock, _monitor):
unit._send_multipart_reply(sock, b"TQ_STORAGE_client", [b"header", b"payload"])

unit._process_one_worker_request = trigger_partial_send # type: ignore[method-assign]

with (
patch.object(simple_storage.zmq, "Poller", return_value=_failing_poller(unit._shutdown_event)),
patch.object(simple_storage.zmq, "Poller", return_value=poller),
patch.object(simple_storage.os, "_exit") as exit_call,
):
unit._proxy_routine()
with pytest.raises(MemoryError):
unit._worker_routine()

exit_call.assert_not_called()
assert unit._router_tainted is True
exit_call.assert_called_once_with(simple_storage._WORKER_DEATH_EXIT_CODE)


def test_set_pytorch_threads_falls_back_to_logical_cores_when_physical_is_none(monkeypatch, caplog):
"""Kunpeng ARM64 / container hosts where cpu_count(logical=False) is None must not clamp to 1 thread."""
monkeypatch.setattr(
common.psutil,
"cpu_count",
lambda logical=True: None if not logical else 64,
)
previous = torch.get_num_threads()
try:
chosen = common.set_pytorch_auto_parallel_threads(target_num_threads=8, info="arm64-test")
assert chosen == 8
assert torch.get_num_threads() == 8
assert "should not exceed" not in caplog.text
finally:
torch.set_num_threads(previous)


def test_send_multipart_reply_honors_copy_threshold_without_gc_on_small_frames():
"""Small reply frames must copy inline below copy_threshold instead of waking pyzmq's GC thread."""
unit = _unit()
ctx = zmq.Context()
router = ctx.socket(zmq.ROUTER)
dealer = ctx.socket(zmq.DEALER)
dealer.setsockopt(zmq.IDENTITY, b"TQ_STORAGE_client")
router.bind("inproc://copy-threshold-test")
dealer.connect("inproc://copy-threshold-test")
try:
dealer.send(b"ping")
identity = router.recv_multipart(copy=False)[0]

with patch.object(zmq.utils.garbage.gc, "store", wraps=zmq.utils.garbage.gc.store) as gc_store:
unit._send_multipart_reply(router, identity, [b"h" * 128, memoryview(b"p" * 1024)])
assert dealer.recv_multipart() == [b"h" * 128, b"p" * 1024]
gc_store.assert_not_called()

large_payload = memoryview(bytearray(router.copy_threshold + 1024))
unit._send_multipart_reply(router, identity, [b"h" * 128, large_payload])
received = dealer.recv_multipart()
assert len(received[1]) == len(large_payload)
assert gc_store.call_count == 1
finally:
dealer.close(linger=0)
router.close(linger=0)
ctx.term()
Loading
Loading