diff --git a/tests/test_accept_probe.py b/tests/test_accept_probe.py index 1a8b07a3..2381cdb0 100644 --- a/tests/test_accept_probe.py +++ b/tests/test_accept_probe.py @@ -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, @@ -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, ) diff --git a/tests/test_simple_storage_unit.py b/tests/test_simple_storage_unit.py index 33dbf7cc..023a266c 100644 --- a/tests/test_simple_storage_unit.py +++ b/tests/test_simple_storage_unit.py @@ -30,6 +30,7 @@ import errno import pickle +import threading import time from pathlib import Path from uuid import uuid4 @@ -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) @@ -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() @@ -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) @@ -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() diff --git a/tests/test_storage_request_retry.py b/tests/test_storage_request_retry.py index 121a2ed7..bbd5ac32 100644 --- a/tests/test_storage_request_retry.py +++ b/tests/test_storage_request_retry.py @@ -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", diff --git a/tests/test_storage_worker_death_exits.py b/tests/test_storage_worker_death_exits.py index 4680c1f8..3341f828 100644 --- a/tests/test_storage_worker_death_exits.py +++ b/tests/test_storage_worker_death_exits.py @@ -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 @@ -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 @@ -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, ): @@ -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() diff --git a/tests/test_zmq_payload_transfer.py b/tests/test_zmq_payload_transfer.py index 7d6992ae..a0e3145e 100644 --- a/tests/test_zmq_payload_transfer.py +++ b/tests/test_zmq_payload_transfer.py @@ -110,6 +110,7 @@ async def test_payload_roundtrip_dense_nested_and_object_fields(monkeypatch): } put_reply = await client.request(peer_info, put, send=payload) assert put_reply.payload is None + assert put_reply.wire_bytes > 0 update = RequestHeader( Operation.UPDATE, @@ -126,6 +127,7 @@ async def test_payload_roundtrip_dense_nested_and_object_fields(monkeypatch): # Read in reversed sample order and verify earlier tensor views survive later writes. get = RequestHeader(Operation.GET, {"global_indexes": [2, 10], "fields": ["dense", "ragged", "text"]}) get_reply = await client.request(peer_info, get) + assert get_reply.wire_bytes > 0 data = get_reply.payload assert data is not None held_view = data["ragged"][0][1:3] @@ -397,8 +399,6 @@ def test_storage_observability_without_zmq_dispatch(monkeypatch, metrics_enabled from transfer_queue.metrics import TQMetricsExporter monkeypatch.setattr("transfer_queue.storage.simple_storage.get_node_ip_address", lambda: "127.0.0.1") - heavy = MagicMock() - monkeypatch.setattr("transfer_queue.storage.simple_storage.log_heavy_operation", heavy) unit = SimpleStorageUnit.__ray_metadata__.modified_class({}) if metrics_enabled: unit._metrics = TQMetricsExporter(role="storage") @@ -419,7 +419,6 @@ def test_storage_observability_without_zmq_dispatch(monkeypatch, metrics_enabled assert real_error.value.missing_key is False assert unit._requests_arrived == 4 assert unit._arrivals_by_op == {"PUT_DATA": 2, "GET_DATA": 2} - heavy.assert_not_called() if metrics_enabled: assert unit._metrics.request_total.labels(op_type="GET_DATA")._value.get() == 2 assert unit._metrics.request_errors_total.labels(op_type="GET_DATA")._value.get() == 0 @@ -506,7 +505,6 @@ def handle(header, data): None, None, None, - None, payload_transfer=transfer, storage_data=storage, ) diff --git a/transfer_queue/metrics.py b/transfer_queue/metrics.py index 6f6c8ae2..ffa5653c 100644 --- a/transfer_queue/metrics.py +++ b/transfer_queue/metrics.py @@ -525,7 +525,7 @@ def _get_socket_pool(self) -> ZMQSocketPool: ) self._zmq_socket_pool = ZMQSocketPool( self._zmq_ctx, - # The storage proxy drops identities without this prefix, and the pool + # The storage unit drops identities without this prefix, and the pool # builds each socket's identity from the owner id. METRICS_COLLECTOR_IDENTITY_PREFIX.rstrip("_"), "put_get_socket", diff --git a/transfer_queue/storage/managers/simple_storage_manager.py b/transfer_queue/storage/managers/simple_storage_manager.py index fb03c9d3..a7053039 100644 --- a/transfer_queue/storage/managers/simple_storage_manager.py +++ b/transfer_queue/storage/managers/simple_storage_manager.py @@ -669,14 +669,14 @@ async def _request_payload( f"Failed to {op_name} data on storage unit {target} ({endpoint}): {type(exc).__name__}: {exc}" ) from exc - if data is not None: - log_heavy_operation( - self.storage_manager_id, - op_name, - time.perf_counter() - started, - reply.wire_bytes, - f"to {target} at {endpoint} {request_context}", - ) + direction = "from" if operation == Operation.GET else "to" + log_heavy_operation( + self.storage_manager_id, + op_name, + time.perf_counter() - started, + reply.wire_bytes, + f"{direction} {target} at {endpoint} {request_context}", + ) return reply async def _put_to_single_storage_unit( diff --git a/transfer_queue/storage/payload_transfer/zmq.py b/transfer_queue/storage/payload_transfer/zmq.py index f8b7ec8e..3fb61ef6 100644 --- a/transfer_queue/storage/payload_transfer/zmq.py +++ b/transfer_queue/storage/payload_transfer/zmq.py @@ -41,7 +41,6 @@ ZMQRequestType, ZMQServerInfo, ZMQSocketPool, - frame_nbytes, ) # Preserves the existing ZMQ GET_ERROR message convention across rolling upgrades. @@ -124,10 +123,14 @@ async def request(self, peer_info, header, *, send=None): ) frames = request.serialize() if send is not None: - wire_bytes = sum(frame_nbytes(frame) or 0 for frame in frames) + wire_bytes = sum(len(frame) for frame in frames) await socket.send_multipart(frames, copy=False) del frames - reply = ZMQMessage.deserialize(await socket.recv_multipart(copy=False)) + raw_reply = await socket.recv_multipart(copy=False) + if header.operation == Operation.GET: + wire_bytes = sum(len(frame) for frame in raw_reply) + reply = ZMQMessage.deserialize(raw_reply) + del raw_reply except zmq.error.Again as exc: raise TransferTimeout("ZMQ storage request timed out", wire_bytes=wire_bytes) from exc except zmq.ZMQError as exc: @@ -188,7 +191,7 @@ def handle_request(self, message): def shutdown(self): """Stop admitting new payload work and wait for any active handler call to finish. - Both the server-side ROUTER/worker sockets (owned by ``SimpleStorageUnit``) and the + Both the server-side ROUTER socket (owned by ``SimpleStorageUnit``) and the client-side ``ZMQSocketPool`` (shared with administrative RPCs such as ``CLEAR_DATA``) are closed by their respective owners after ``shutdown()`` returns. """ diff --git a/transfer_queue/storage/simple_storage.py b/transfer_queue/storage/simple_storage.py index 30ea4d21..f21704e3 100644 --- a/transfer_queue/storage/simple_storage.py +++ b/transfer_queue/storage/simple_storage.py @@ -28,13 +28,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +import errno import logging import math import os import pickle import shutil import sys -import time import weakref from collections import defaultdict from concurrent.futures import ThreadPoolExecutor @@ -64,7 +64,7 @@ ) from transfer_queue.storage.payload_transfer.zmq import KEY_NOT_FOUND_MARKER as KEY_NOT_FOUND_MARKER from transfer_queue.utils import compact_pickle -from transfer_queue.utils.common import get_env_bool, limit_pytorch_auto_parallel_threads, log_heavy_operation +from transfer_queue.utils.common import get_env_bool, set_pytorch_auto_parallel_threads from transfer_queue.utils.enum_utils import Role from transfer_queue.utils.logging_utils import get_logger from transfer_queue.utils.perf_utils import IntervalPerfMonitor @@ -75,7 +75,6 @@ ZMQServerInfo, create_zmq_socket, format_zmq_address, - frame_nbytes, get_free_port, get_node_ip_address, ) @@ -123,9 +122,9 @@ class _SSDValueRef: # Accept-queue sampling period in seconds; 0 disables the probe. Keep sub-second. TQ_ACCEPT_PROBE_INTERVAL = float(os.environ.get("TQ_ACCEPT_PROBE_INTERVAL", 0)) -# Exit the unit process when its worker or proxy thread dies, so the unit fails visibly. Both are -# daemon threads, so without this the process keeps accepting requests it can never answer and -# looks alive. Disable only to inspect a dead worker in place. +# Exit the unit process when its worker thread dies, so the unit fails visibly. The worker runs +# as a daemon thread, so without this the process keeps accepting requests on its ROUTER socket +# that it can never answer and looks alive. Disable only to inspect a dead worker in place. TQ_STORAGE_EXIT_ON_WORKER_DEATH = get_env_bool("TQ_STORAGE_EXIT_ON_WORKER_DEATH", True) # Distinguishes a worker-death abort from a normal exit in Ray's actor-failure logs. @@ -963,17 +962,14 @@ def __init__(self, config: dict[str, Any]): self._requests_arrived = 0 self._arrivals_by_op = {} self._storage_lock = Lock() - - # Internal communication address for proxy and workers - self._inproc_addr = f"inproc://simple_storage_workers_{self.storage_unit_id}" + self._router_tainted = False # Shutdown event for graceful termination self._shutdown_event = Event() - # Placeholder for zmq_context, proxy_thread and worker_threads + # Placeholder for zmq_context, put_get_socket and worker_thread self.zmq_context: zmq.Context | None = None self.put_get_socket: zmq.Socket | None = None - self.proxy_thread: Thread | None = None self.worker_thread: Thread | None = None self._metrics: TQMetricsExporter | None = None @@ -994,11 +990,9 @@ def __init__(self, config: dict[str, Any]): self._shutdown_resources, self._shutdown_event, self.worker_thread, - self.proxy_thread, self.zmq_context, self.put_get_socket, self._accept_probe, - self.worker_socket, self.storage_data, self.payload_transfer, ) @@ -1009,15 +1003,10 @@ def shutdown(self) -> None: self._finalizer() def _init_zmq_socket(self) -> None: - """ - Initialize ZMQ socket connections between storage unit and controller/clients: - - put_get_socket (ROUTER): Handle put/get requests from clients. - - worker_socket (DEALER): Backend socket for worker communication. - """ + """Initialize the unit's listening ZMQ ROUTER socket.""" self.zmq_context = zmq.Context() self._node_ip = get_node_ip_address() - # Frontend: ROUTER for receiving client requests self.put_get_socket = create_zmq_socket(self.zmq_context, zmq.ROUTER, self._node_ip) self.put_get_socket.setsockopt(zmq.BACKLOG, TQ_STORAGE_ZMQ_BACKLOG) @@ -1042,10 +1031,6 @@ def _init_zmq_socket(self) -> None: ) self._accept_probe.start() - # Backend: DEALER for worker communication (connected via zmq.proxy) - self.worker_socket = create_zmq_socket(self.zmq_context, zmq.DEALER, self._node_ip) - self.worker_socket.bind(self._inproc_addr) - self.zmq_server_info = ZMQServerInfo( role=Role.STORAGE, id=str(self.storage_unit_id), @@ -1054,9 +1039,7 @@ def _init_zmq_socket(self) -> None: ) def _start_process_put_get(self) -> None: - """Start worker threads and ZMQ proxy for handling requests.""" - - # Start worker thread + """Start the worker thread serving the ROUTER socket directly.""" self.worker_thread = Thread( target=self._worker_routine, name=f"StorageUnitWorkerThread-{self.storage_unit_id}", @@ -1064,61 +1047,13 @@ def _start_process_put_get(self) -> None: ) self.worker_thread.start() - time.sleep(0.5) # make sure worker thread is ready before zmq.proxy forwarding messages - - # Start proxy thread (ROUTER <-> DEALER) - self.proxy_thread = Thread( - target=self._proxy_routine, - name=f"StorageUnitProxyThread-{self.storage_unit_id}", - daemon=True, - ) - self.proxy_thread.start() - - def _proxy_routine(self) -> None: - """ZMQ proxy for message forwarding between frontend ROUTER and backend DEALER.""" - logger.info(f"[{self.storage_unit_id}]: start ZMQ proxy...") - assert self.put_get_socket is not None, "put_get_socket is not properly initialized" - front, back = self.put_get_socket, self.worker_socket - poller = zmq.Poller() - poller.register(front, zmq.POLLIN) - poller.register(back, zmq.POLLIN) - try: - # Forwarding by hand rather than via zmq.proxy() so a non-TransferQueue peer on - # this exposed TCP port cannot reach the worker and terminate its request loop. - while not self._shutdown_event.is_set(): - events = dict(poller.poll(1000)) - if front in events: - messages = front.recv_multipart(copy=False) - try: - identity = bytes(messages[0]) if messages else b"" - if not identity.startswith(STORAGE_CLIENT_IDENTITY_PREFIXES): - logger.warning( - "[%s]: dropping request with unrecognized ZMQ identity", - self.storage_unit_id, - ) - continue - back.send_multipart(messages, copy=False) - finally: - # This thread outlives each request, so drop forwarded payload frames while idle. - del messages - - if back in events: - front.send_multipart(back.recv_multipart(copy=False), copy=False) - except zmq.ContextTerminated: - logger.info(f"[{self.storage_unit_id}]: ZMQ Proxy stopped gracefully (Context Terminated)") - except Exception as e: - if self._shutdown_event.is_set(): - logger.info(f"[{self.storage_unit_id}]: ZMQ Proxy shutting down...") - else: - logger.exception(f"[{self.storage_unit_id}]: ZMQ Proxy unexpected error: {e}") - # Without the proxy nothing reaches the worker, so the unit is as unreachable - # as if the worker itself had died. - self._abort_process("the ZMQ proxy thread died") - def _worker_routine(self) -> None: """Worker thread for processing requests.""" logger.info(f"[{self.storage_unit_id}]: worker thread started...") try: + set_pytorch_auto_parallel_threads( + target_num_threads=TQ_NUM_THREADS, info=f"[{self.storage_unit_id}] worker" + ) self._worker_loop(self._perf_monitor) except BaseException: logger.critical( @@ -1133,8 +1068,8 @@ def _abort_process(self, reason: str) -> None: """Kill the whole unit process so it fails visibly instead of lingering as a dead unit. The worker runs as a daemon thread, so re-raising only unwinds that thread while the - process, its ROUTER and the proxy stay up and keep queueing requests nobody will ever - answer. ``os._exit`` skips atexit/flush handlers that could themselves block here. + process and its ROUTER stay up and keep queueing requests nobody will ever answer. + ``os._exit`` skips atexit/flush handlers that could themselves block here. """ if self._shutdown_event.is_set(): return @@ -1154,46 +1089,54 @@ def _abort_process(self, reason: str) -> None: _flush_log_output() os._exit(_WORKER_DEATH_EXIT_CODE) - def _connect_worker_socket(self, poller: zmq.Poller) -> zmq.Socket: - worker_socket = create_zmq_socket(self.zmq_context, zmq.DEALER, self._node_ip) - worker_socket.connect(self._inproc_addr) - poller.register(worker_socket, zmq.POLLIN) - return worker_socket - def _worker_loop(self, perf_monitor: Any) -> None: - """Poll for requests and answer them until shutdown is signalled.""" + """Poll the ROUTER socket directly and answer requests until shutdown is signalled.""" + assert self.put_get_socket is not None, "put_get_socket is not properly initialized" poller = zmq.Poller() - worker_socket = self._connect_worker_socket(poller) - try: - while not self._shutdown_event.is_set(): - monitor = self._metrics if self._metrics is not None else perf_monitor + poller.register(self.put_get_socket, zmq.POLLIN) + while not self._shutdown_event.is_set(): + monitor = self._metrics if self._metrics is not None else perf_monitor + try: + # The event cannot wake a ZMQ poll, so bound idle shutdown latency. + socks = dict(poller.poll(min(TQ_STORAGE_POLLER_TIMEOUT, 1) * 1000)) + except zmq.error.ContextTerminated: + logger.info(f"[{self.storage_unit_id}]: worker stopped gracefully (Context Terminated)") + break + except zmq.ZMQError as e: + if e.errno == errno.EINTR: + continue + if self._shutdown_event.is_set(): + break + raise + + if self._shutdown_event.is_set(): + break + + if self.put_get_socket in socks: + # Keep request handling in a separate scope so payload references are + # released before the worker waits for the next request. try: - # The event cannot wake a ZMQ poll, so bound idle shutdown latency. - socks = dict(poller.poll(min(TQ_STORAGE_POLLER_TIMEOUT, 1) * 1000)) + self._process_one_worker_request(self.put_get_socket, monitor) except zmq.error.ContextTerminated: - # ZMQ context was terminated, exit gracefully logger.info(f"[{self.storage_unit_id}]: worker stopped gracefully (Context Terminated)") break + except zmq.ZMQError as e: + if self._shutdown_event.is_set(): + break + if self._router_tainted or e.errno not in (errno.EAGAIN, errno.EINTR): + raise + while self.put_get_socket.getsockopt(zmq.RCVMORE): + self.put_get_socket.recv(copy=False) + logger.warning(f"[{self.storage_unit_id}]: transient ZMQ error on request: {e}") except Exception as e: - logger.warning(f"[{self.storage_unit_id}]: worker poll error: {e}") - continue - - if self._shutdown_event.is_set(): - break - - if worker_socket in socks: - # Keep request handling in a separate scope so payload references are - # released before the worker waits for the next request. - try: - self._process_one_worker_request(worker_socket, monitor) - except Exception as e: - logger.exception(f"[{self.storage_unit_id}]: worker failed a request: {type(e).__name__}: {e}") - # The socket may be left mid-message; a fresh one keeps the next reply routed correctly. - poller.unregister(worker_socket) - worker_socket.close(linger=0) - worker_socket = self._connect_worker_socket(poller) - finally: - worker_socket.close(linger=0) + if self._shutdown_event.is_set(): + break + if self._router_tainted: + raise + while self.put_get_socket.getsockopt(zmq.RCVMORE): + self.put_get_socket.recv(copy=False) + # No SNDMORE frame entered put_get_socket, so keep it bound to preserve queued requests. + logger.exception(f"[{self.storage_unit_id}]: worker failed a request: {type(e).__name__}: {e}") def _record_arrival(self, operation: str) -> None: with self._storage_lock: @@ -1215,36 +1158,33 @@ def _handle_payload(self, header: RequestHeader, data: dict[str, Any] | None) -> with self._measure_payload_op(op_type): try: indexes = params["global_indexes"] - with limit_pytorch_auto_parallel_threads( - target_num_threads=TQ_NUM_THREADS, info=f"[{self.storage_unit_id}] {operation.value}" - ): - if operation == Operation.GET: - fields = params["fields"] - with self._storage_lock: - result = self.storage_data.get_data(fields, indexes) - if (parser := params.get("data_parser")) is not None: - result = _apply_data_parser(result, parser, params.get("parser_args")) - return PayloadReply(payload=result) - if operation == Operation.PUT: - if data is None: - raise TypeError("PUT requires field data") - if (parser := params.get("data_parser")) is not None: - data = _apply_data_parser(data, parser) - with self._storage_lock: - self.storage_data.put_data(data, indexes) - return PayloadReply() - - merge_fn = params.get("merge_fn") - merge_plan = params.get("merge_plan") - if not callable(merge_fn): - raise TypeError(f"merge_fn must be callable, got {type(merge_fn).__name__}") - if not isinstance(data, dict) or not data: - raise TypeError("update data must be a non-empty dict") - if not isinstance(merge_plan, dict) or set(merge_plan) != set(data): - raise ValueError("merge_plan must describe every update field") + if operation == Operation.GET: + fields = params["fields"] with self._storage_lock: - stored_shapes = self.storage_data.apply_update(indexes, data, merge_fn, merge_plan) - return PayloadReply(meta={"stored_shapes": stored_shapes}) + result = self.storage_data.get_data(fields, indexes) + if (parser := params.get("data_parser")) is not None: + result = _apply_data_parser(result, parser, params.get("parser_args")) + return PayloadReply(payload=result) + if operation == Operation.PUT: + if data is None: + raise TypeError("PUT requires field data") + if (parser := params.get("data_parser")) is not None: + data = _apply_data_parser(data, parser) + with self._storage_lock: + self.storage_data.put_data(data, indexes) + return PayloadReply() + + merge_fn = params.get("merge_fn") + merge_plan = params.get("merge_plan") + if not callable(merge_fn): + raise TypeError(f"merge_fn must be callable, got {type(merge_fn).__name__}") + if not isinstance(data, dict) or not data: + raise TypeError("update data must be a non-empty dict") + if not isinstance(merge_plan, dict) or set(merge_plan) != set(data): + raise ValueError("merge_plan must describe every update field") + with self._storage_lock: + stored_shapes = self.storage_data.apply_update(indexes, data, merge_fn, merge_plan) + return PayloadReply(meta={"stored_shapes": stored_shapes}) except Exception as exc: missing_key = operation == Operation.GET and isinstance(exc, StorageKeyNotFoundError) if operation == Operation.GET: @@ -1256,11 +1196,37 @@ def _handle_payload(self, header: RequestHeader, data: dict[str, Any] | None) -> detail = str(exc) if missing_key else f"{type(exc).__name__}: {exc}" raise StorageRejected(detail, missing_key=missing_key) from exc - def _process_one_worker_request(self, worker_socket: zmq.Socket, monitor: Any) -> None: - """Process one storage request and send its response.""" - # Messages received from proxy: [identity, serialized_msg_frame1, ...] - messages = worker_socket.recv_multipart(copy=False) - identity = messages[0] + def _send_multipart_reply(self, router_socket: zmq.Socket, identity: Any, response_frames: list[Any]) -> None: + """Send ``[identity, *response_frames]``, marking ``_router_tainted`` if ``send`` fails mid-SNDMORE.""" + # Materialize all ZMQ frames before touching router_socket so buffer/allocation errors + # happen prior to queuing any SNDMORE frame, while honoring copy_threshold so small + # frames copy inline in C without waking pyzmq's zero-copy GarbageCollectorThread. + prepared = [ + part + if isinstance(part, zmq.Frame) + else zmq.Frame(memoryview(part), copy=None, copy_threshold=router_socket.copy_threshold) + for part in (identity, *response_frames) + ] + last = len(prepared) - 1 + sent_partial = False + try: + for idx, frame in enumerate(prepared): + router_socket.send(frame, zmq.SNDMORE if idx < last else 0, copy=False) + sent_partial = idx < last + except BaseException: + if sent_partial: + self._router_tainted = True + raise + + def _process_one_worker_request(self, router_socket: zmq.Socket, monitor: Any) -> None: + """Process one storage request from the ROUTER socket and send its response.""" + # Multipart frames from ROUTER: [identity, serialized_msg_frame1, ...] + messages = router_socket.recv_multipart(copy=False) + identity = messages[0] if messages else b"" + if not bytes(identity).startswith(STORAGE_CLIENT_IDENTITY_PREFIXES): + # Drop non-TransferQueue peers (e.g. port scanners) before decoding so they never draw a reply. + logger.warning("[%s]: dropping request with unrecognized ZMQ identity", self.storage_unit_id) + return serialized_msg = messages[1:] try: @@ -1277,11 +1243,10 @@ def _process_one_worker_request(self, worker_socket: zmq.Socket, monitor: Any) - sender_id=self.storage_unit_id, body={"message": f"undecodable request: {type(e).__name__}: {e}"}, ) - worker_socket.send_multipart([identity] + error_msg.serialize(), copy=False) + self._send_multipart_reply(router_socket, identity, error_msg.serialize()) return operation = request_msg.request_type - started = time.perf_counter() try: is_payload = isinstance(self.payload_transfer, ZmqPayloadTransfer) and self.payload_transfer.can_handle( @@ -1345,18 +1310,7 @@ def _process_one_worker_request(self, worker_socket: zmq.Socket, monitor: Any) - sender_id=self.storage_unit_id, body={"message": f"{self.storage_unit_id}: failed to serialize response: {type(e).__name__}: {e}"}, ).serialize() - else: - if operation == ZMQRequestType.GET_DATA: # type: ignore[arg-type] - # This end serializes the get response, so its frames give the true wire size. - log_heavy_operation( - self.storage_unit_id, - "get", - time.perf_counter() - started, - sum(frame_nbytes(frame) or 0 for frame in response_frames), - f"samples={len(request_msg.body.get('global_indexes', []))} " - f"fields={list(request_msg.body.get('fields', []))}", - ) - worker_socket.send_multipart([identity] + response_frames, copy=False) + self._send_multipart_reply(router_socket, identity, response_frames) def _handle_clear(self, data_parts: ZMQMessage) -> ZMQMessage: """ @@ -1371,12 +1325,7 @@ def _handle_clear(self, data_parts: ZMQMessage) -> ZMQMessage: try: global_indexes = data_parts.body["global_indexes"] - with ( - limit_pytorch_auto_parallel_threads( - target_num_threads=TQ_NUM_THREADS, info=f"[{self.storage_unit_id}] _handle_clear" - ), - self._storage_lock, - ): + with self._storage_lock: self.storage_data.clear(global_indexes, data_parts.body.get("fields")) response_msg = ZMQMessage.create( @@ -1544,7 +1493,7 @@ def _handle_load_rows(self, request: ZMQMessage) -> ZMQMessage: updates: list[dict[str, Any]] = [] bytes_read = 0 try: - with limit_pytorch_auto_parallel_threads(TQ_NUM_THREADS), self._storage_lock: + with self._storage_lock: for shard in request.body["shards"]: records = sorted(shard["records"], key=lambda row: row["offset"]) with open(shard["path"], "rb", buffering=0) as f: @@ -1680,11 +1629,9 @@ def _quantile_from_cumulative(hist, cumulative_counts: list[float], q: float) -> def _shutdown_resources( shutdown_event: Event, worker_thread: Thread | None, - proxy_thread: Thread | None, zmq_context: zmq.Context | None, put_get_socket: zmq.Socket | None, accept_probe: "AcceptQueueProbe | None" = None, - worker_socket: zmq.Socket | None = None, storage_data: StorageUnitData | None = None, payload_transfer: PayloadTransfer | None = None, ) -> None: @@ -1703,13 +1650,9 @@ def _shutdown_resources( if worker_thread and worker_thread.is_alive(): worker_thread.join() - if proxy_thread and proxy_thread.is_alive(): - proxy_thread.join() if put_get_socket: put_get_socket.close(linger=0) - if worker_socket: - worker_socket.close(linger=0) if zmq_context: zmq_context.term() if storage_data is not None: diff --git a/transfer_queue/utils/common.py b/transfer_queue/utils/common.py index 40574413..a655b223 100644 --- a/transfer_queue/utils/common.py +++ b/transfer_queue/utils/common.py @@ -86,32 +86,34 @@ def get_node_round_robin_scheduling_strategies( ] -@contextmanager -def limit_pytorch_auto_parallel_threads(target_num_threads: int | None = None, info: str = ""): - """Prevent PyTorch from overdoing the automatic parallelism during tensor aggregation operations.""" +def set_pytorch_auto_parallel_threads(target_num_threads: int | None = None, info: str = "") -> int: + """Configure PyTorch intra-op CPU parallelism once for the calling thread/process.""" pytorch_current_num_threads = torch.get_num_threads() - physical_cores = psutil.cpu_count(logical=False) + available_cores = psutil.cpu_count(logical=False) or psutil.cpu_count(logical=True) or os.cpu_count() or 1 pid = os.getpid() if target_num_threads is None: - # auto determine target_num_threads - if physical_cores >= 16: - target_num_threads = 16 - else: - target_num_threads = physical_cores - - if target_num_threads > physical_cores: + target_num_threads = 16 if available_cores >= 16 else available_cores + elif target_num_threads > available_cores: logger.warning( - f"target_num_threads {target_num_threads} should not exceed total " - f"physical CPU cores {physical_cores}. Setting to {physical_cores}." + f"target_num_threads {target_num_threads} should not exceed available " + f"CPU cores {available_cores}. Setting to {available_cores}." ) - target_num_threads = physical_cores + target_num_threads = available_cores + + torch.set_num_threads(target_num_threads) + logger.debug( + f"{info} (pid={pid}): torch.get_num_threads() is {pytorch_current_num_threads}, " + f"setting to {target_num_threads}." + ) + return target_num_threads + +@contextmanager +def limit_pytorch_auto_parallel_threads(target_num_threads: int | None = None, info: str = ""): + """Prevent PyTorch from overdoing the automatic parallelism during tensor aggregation operations.""" + pid = os.getpid() + set_pytorch_auto_parallel_threads(target_num_threads=target_num_threads, info=info) try: - torch.set_num_threads(target_num_threads) - logger.debug( - f"{info} (pid={pid}): torch.get_num_threads() is {pytorch_current_num_threads}, " - f"setting to {target_num_threads}." - ) yield finally: # Restore the original number of threads diff --git a/transfer_queue/utils/zmq_utils.py b/transfer_queue/utils/zmq_utils.py index bf5147aa..44b2e313 100644 --- a/transfer_queue/utils/zmq_utils.py +++ b/transfer_queue/utils/zmq_utils.py @@ -38,8 +38,8 @@ logger = get_logger(__name__) -# Identity prefixes of the peers allowed to reach a storage unit. The storage proxy drops -# anything else, so an identity built without these prefixes is silently unreachable. +# Identity prefixes of the peers allowed to reach a storage unit. The storage unit's ROUTER +# worker drops anything else, so an identity built without these prefixes is silently unreachable. STORAGE_MANAGER_IDENTITY_PREFIX = "TQ_STORAGE_" METRICS_COLLECTOR_IDENTITY_PREFIX = "metrics_collector_" STORAGE_CLIENT_IDENTITY_PREFIXES = (