Repository navigation
Description
TL;DR
PR #228 removes the internalROUTER <-> proxy_thread <-> inproc DEALERforwarding layer inSimpleStorageUnitso its singleworker_threadpolls and serves the bound TCPROUTERsocket directly. Beyond removing two ZMQ hops per request and a hardcoded0.5sstartup sleep, this refactoring eliminates two subtle reliability hazards: (1) pre-send errors on one request closing theinproc://socket and silently destroying concurrent peers' queued requests, and (2) mid-SNDMOREreply failures misrouting subsequent replies across clients. This document records the wire invariants, failure mechanics, rejected recovery designs, and observability boundaries across related PRs for future maintainers.
Related PRs: #143, #145, #167, #168, #171, #172, #192, #201, #204, #214, #228
1. Underlying Wire Invariant: The ZMQ ROUTER Multipart Contract
SimpleStorageUnit serves multiple AsyncSimpleStorageManager peers (DEALER sockets) over a single bound TCP ROUTER socket (put_get_socket). Two libzmq / ZMTP 3.x rules govern every failure mode on this path:
- Sender-side
SNDMOREenvelope rule: When aROUTERsends a multipart reply, frame 0 is the target peer's routingidentity, every frame before the last carriesSNDMORE=1, and the final frame carriesSNDMORE=0:
[Frame 0: identity (SNDMORE=1)] -> [Frame 1: msgpack header (SNDMORE=1)] -> [Frame 2: tensor buffer (SNDMORE=0)]
Once frame 0 enters theROUTERwithSNDMORE=1, libzmq attaches every subsequent frame sent on that socket to the same peer's envelope until a frame withSNDMORE=0closes the envelope. libzmq exposes neither agetsockoptquery for outboundSNDMOREstate nor an API to roll back queued frames without closing the socket. - Receiver-side ZMTP atomic delivery rule: A receiving
DEALERholds incomingSNDMORE=1frames inside libzmq's C++ session buffer until the terminatingSNDMORE=0frame arrives. If the server process exits and drops the TCP connection before sendingSNDMORE=0, the client's libzmq discards the incomplete multipart message atomically and surfaces a cleanzmq.Again(TransferTimeout) to Python rather than exposing partial frames.
2. Four Reliability Problems Solved in PR #228
2.1 Silent Loss of Concurrent Queued Requests on Pre-Send Errors (inproc:// Pipe Drain Bug)
Prior to PR #228, an unhandled pre-send exception on one request silently destroyed concurrent requests from innocent peers that had already entered the unit process. Under the legacy two-thread architecture, proxy_thread forwarded frames between the TCP ROUTER and an inproc:// DEALER socket, while worker_thread read from a connected worker_socket (inproc:// DEALER, RCVHWM=0). To keep a single failed request from killing the sole worker, PR #204 caught Exception in _worker_loop, called worker_socket.close(linger=0), and connected a replacement worker_socket.
Consider two concurrent clients hitting the same SimpleStorageUnit:
Client Asends aGETrequest (req_A), andClient Bsimultaneously sends a non-idempotentUPDATErequest (req_B,max_attempts=1, never retried).proxy_threadimmediately drains bothreq_Aandreq_Bfrom the TCPROUTERand pushes both intoworker_socket'sinproc://receive queue.req_Bis now buffered insideworker_socket.worker_threadpopsreq_Aand hits an unexpected pre-send error before writing anything back toworker_socket(for example, an interrupted call or a non-buffer object raisingTypeError)._worker_loopexecutesworker_socket.close(linger=0)to reset socket state, destroyingreq_Bsitting unread in the oldworker_socket'sinproc://receive queue.- This failure creates an observability blind spot: because the TCP handshake succeeded,
AcceptQueueProbe(PR #172) reportssk_drops=0; becausereq_Bdied before decoding,requests_arrivednever increments; and by the timeClient Btimes out and runs_diagnose_storage_unit(PR #171), the replacementworker_socketis serving normally again—making an internal queue drop look identical to an external network packet loss (tcp=up, unit healthy, arrival missing).
PR #228 eliminates this failure path by serving put_get_socket (ROUTER) directly and validating all reply frames before touching the socket. req_B stays queued in put_get_socket until worker_thread finishes req_A, and _send_multipart_reply materializes every zmq.Frame before calling router_socket.send. Any error before the first SNDMORE frame leaves put_get_socket untainted, so _worker_loop logs the failure without closing put_get_socket and immediately serves req_B on the next iteration.
2.2 Cross-Client Reply Misrouting on Mid-SNDMORE Failures (and Why Naive Recovery Fails)
Reusing a ROUTER socket after a mid-SNDMORE failure routes the next client's reply into the previous client's open envelope. Suppose the worker sends send("Client_A", SNDMORE=1) and then raises (e.g., on an allocation failure) before sending the final SNDMORE=0 frame. If _worker_loop swallows that error and processes Client B's request next, calling send("Client_B", SNDMORE=1) followed by send(Reply_B, SNDMORE=0) appends "Client_B" and Reply_B onto Client A's unfinished envelope: Client A receives shifted, corrupt frames (surfacing as ZMQMessageDecodeError from PR #143), while Client B hangs until timeout.
sequenceDiagram
participant CA as Client A
participant R as ROUTER Socket
participant W as Worker Thread
participant CB as Client B
CA->>R: 1. Send req_A
CB->>R: 2. Send req_B
R->>W: Pop req_A
W->>R: send("Client_A", SNDMORE=1) [envelope opened, uncommitted]
W--xW: Exception on subsequent frame; SNDMORE=0 never sent
Note over W,R: Broken recovery: swallow error and reuse tainted ROUTER
R->>W: Pop req_B
W->>R: send("Client_B", SNDMORE=1) [appended into Client A's envelope]
W->>R: send(Reply_B, SNDMORE=0) [envelope sealed]
R-->>CA: Delivers Client B's reply to Client A (misrouted / shifted frames)
Note over CB: Hangs until receive timeout
Two seemingly attractive recovery strategies introduce worse failure modes and were deliberately rejected:
- Rejected Strategy A: Flush an empty
router_socket.send(b"")frame on error. If the failure happens after[identity (SNDMORE=1), header (SNDMORE=1)]on a multi-frameGETresponse, sendingb""seals and delivers[header, b""]to the client. Pairing valid non-empty tensor metadata with an emptyb""buffer frame previously hitif not buffer: return torch.empty(shape)inMsgpackDecoder, silently materializing uninitialized memory as tensor output. - Rejected Strategy B: Close
put_get_socket(linger=0)and rebind the same TCP port. Closing the shared listener turns one failed reply into a unit-wide outage: (1)close(linger=0)drops all queued requests and outbound replies across every connected peer; (2)put_get_socketbinds an OS ephemeral port fromget_free_port(), so during the asynchronous Reaper close window another localconnect()orbind()on the host can claim that port and fail rebind withEADDRINUSE; and (3) replacing the kernelLISTENsocket resets kernelsk_dropsto0, drivingAcceptQueueProbe.sk_drops_deltanegative.
PR #228 instead combines upfront frame preparation with fail-fast taint tracking:
- Upfront preparation before
SNDMORE:response_msg.serialize()andzmq.Frameconstruction for all frames run before the firstrouter_socket.sendcall, keeping bad userdata_parseroutputs or buffer errors strictly ahead of anySNDMOREstate change. - Fail-fast abort on
_router_tainted: Only ifrouter_socket.sendfails after a non-finalSNDMORE=1frame has enteredrouter_socket(which on anSNDHWM=0, non-mandatoryROUTERonly enqueues pre-builtzmq_msg_tstructs in memory and can only fail under process-level C++ heap exhaustion or context corruption) does_send_multipart_replysetself._router_tainted = True, causing_worker_loopto re-raise into_abort_process(exiting visibly with code70per PR #201). The unit never misroutes a subsequent reply, and the client's ZMTP layer rolls back the uncommitted frames automatically.
2.3 Busy-Spinning on Unrecoverable poller.poll() Faults
Previously, _worker_loop wrapped poller.poll() in except Exception: continue, causing fatal socket errors such as ENOTSOCK to spin at 100% CPU logging warnings inside an actor that Ray still considered healthy. PR #228 retries only errno.EINTR, exits cleanly on shutdown or ContextTerminated, and propagates unrecoverable ZMQErrors to _abort_process.
2.4 Startup Readiness Race and ARM64 / Container PyTorch Thread Initialization
- Startup race removal: Serving the already-bound
ROUTERsocket directly removes theinproc://connect ordering assumption previously masked bytime.sleep(0.5). - ARM64 / container core-count fallback and worker-local TLS setup: On
aarch64hosts (such as Kunpeng nodes) or containers that do not expose physical core topology,psutil.cpu_count(logical=False)returnsNone(raisingTypeErroronmain, or clampingTQ_NUM_THREADS=8down to1thread if defaulted naively to1).set_pytorch_auto_parallel_threads()now falls back viapsutil.cpu_count(logical=False) or psutil.cpu_count(logical=True) or os.cpu_count() or 1and runs once at the start of_worker_routine, configuring ATen / OpenMP's per-threadnthreads-vardirectly onworker_threadwithout per-request/proc/cpuinforeads or main-thread side effects during in-process tests.
3. End-to-End Fault Isolation and Observability Map
Across the ZMQ transport stack, root-cause fixes and residual diagnostics divide cleanly by layer:
- Client-side frame mixing & stale socket reuse -> Solved by long-lived
zmq.Context(PR #145) and exclusiveZMQSocketPoolleases that discard timed-out or cancelledDEALERsockets (PR #167). - Stray non-TransferQueue TCP traffic / port scanners -> Dropped silently before decoding via
STORAGE_CLIENT_IDENTITY_PREFIXES(PR #168, preserved at the top of_process_one_worker_requestin PR #228). - Unit-internal
inprocqueue drops, mid-SNDMOREreply misrouting, and poller busy-spins -> Eliminated by PR #228, escalating unrecoverable process/socket faults to_abort_process(PR #201). - External network drops, async
DEALERinitial handshake queuing, kernel accept-queue overflow, and future transport debugging -> Continue to rely on:describe_frames()inZMQMessage.deserialize(PR #143) to distinguish corrupt payloads from shifted frame boundaries immediately;- Unified client-side
log_heavy_operation(PR #171, unified acrossPUT,UPDATE, andGETin PR #228); AcceptQueueProbe,requests_arrived, and post-timeout_diagnose_storage_unitprobes (PR #171, PR #172, PR #192).
4. Implementation Notes for Future Changes
- Preserve
pyzmq'scopy_thresholdwhen constructingzmq.Frames: Callingzmq.Frame(memoryview(part), copy=False)unconditionally bypassesrouter_socket.copy_threshold(65536bytes), registering tiny ~100-byte response headers inzmq.utils.garbage.gc.refsand wakingpyzmq's backgroundGarbageCollectorThreadoverinproc://pyzmq.gc.01(acquiring the Python GIL) on every reply. Usezmq.Frame(memoryview(part), copy=None, copy_threshold=router_socket.copy_threshold)so< 64 KBcontrol frames copy inline in C while>= 64 KBtensor buffers remain zero-copy. - Inbound
RCVMOREsymmetry: If an exception ever interruptsrouter_socket.recv_multipart(copy=False)after frame 0 whilerouter_socket.getsockopt(zmq.RCVMORE)is non-zero and the worker loop continues, draining remainingRCVMOREframes (or treating mid-receive failure as fatal) prevents inbound frame-boundary shifts on the next request.
Activity
0oshowero0 commentedon Nov 26, 2026
中文版:SimpleStorageUnit 的 ZMQ 多帧边界、静默丢包根因与故障隔离机制
相关 PR:#143, #145, #167, #168, #171, #172, #192, #201, #204, #214, #228
1. 前置底层规则:ZMQ
ROUTER的多帧封箱契约SimpleStorageUnit通过单个 TCPROUTERsocket(put_get_socket)接收多个AsyncSimpleStorageManager(DEALERsocket)发来的请求并回包。理解所有故障模式只需记住两条 ZMQ / ZMTP 3.x 底层规则:SNDMORE封箱规则:ROUTER发送一条多帧回复时,第 0 帧必须是目标客户端的identity,除最后一帧外每一帧都带有SNDMORE=1标志,最后一帧带SNDMORE=0:[Frame 0: identity (SNDMORE=1)] -> [Frame 1: msgpack header (SNDMORE=1)] -> [Frame 2: tensor buffer (SNDMORE=0)]只要第 0 帧带着
SNDMORE=1进入了ROUTER,libzmq 就会把后续写入该 socket 的所有帧都归入同一个收件人信封,直到看见某一帧的SNDMORE=0才封箱发走。libzmq 没有提供查询“当前是否处于SNDMORE未封箱状态”的 API,也没有提供在不关闭 socket 的前提下回滚已入队帧的 API。DEALER在收到最后一帧(SNDMORE=0)之前,会把前面已到达的帧扣留在 libzmq 的 C++ 会话缓冲区内,不会向 Pythonrecv_multipart()暴露任何数据。如果服务端在发出SNDMORE=0之前进程退出并断开 TCP 连接,客户端 libzmq 会自动整包丢弃这半截未封箱的帧,Python 层只会收到干净的超时异常zmq.Again(TransferTimeout)。2. PR #228 解决的四类核心可靠性问题
2.1 单请求发送前异常连带吞掉其他并发请求(
inproc://队列静默丢包)旧架构中单个请求在发送响应前报错,会连带销毁同一时刻其他客户端已发入进程的所有排队请求。在 PR #228 之前,
SimpleStorageUnit包含两条后台线程:proxy_thread负责在外部 TCPROUTER与内部inproc://DEALER之间搬运帧,worker_thread连接worker_socket(inproc://DEALER,RCVHWM=0)处理业务。PR #204 为了让单次请求异常不杀死唯一的worker_thread,在except Exception分支中执行worker_socket.close(linger=0)并新建worker_socket重连。用一个双客户端并发的例子还原丢包全过程:
Client A发送GET请求req_A,同一时刻Client B发送非幂等的UPDATE请求req_B(max_attempts=1,不允许自动重试)。proxy_thread不会等待worker_thread空闲,而是立刻把req_A和req_B全部从 TCPROUTER抽出并塞进worker_socket的inproc://接收队列。此时req_B已经离开ROUTER,躺在worker_socket内部排队。worker_thread取出req_A处理,假设在调用send之前发生异常(例如瞬态EINTR或响应中包含非 buffer 对象触发TypeError)。_worker_loop捕获异常并执行worker_socket.close(linger=0),躺在旧worker_socket接收队列里尚未被读取的req_B随之被静默销毁。AcceptQueueProbe(PR #172)看到的内核sk_drops为0;req_B死在解码前,因此requests_arrived不会增加;等Client B超时后发起_diagnose_storage_unit探针(PR #171)时,新的worker_socket早已恢复响应,诊断日志只能报告tcp=up且存储节点服务正常,表现与网络层无故丢包完全一致。PR #228 通过去掉
inproc://转发层并前置帧校验彻底消除了这一丢包路径。现在req_B直接排在put_get_socket(ROUTER)自身的接收队列中,_send_multipart_reply在触碰router_socket.send之前先在内存中构造完所有zmq.Frame。任何发送前异常都不会向ROUTER写入SNDMORE帧,因此_worker_loop无需关闭put_get_socket,下一轮循环直接取出req_B正常处理。2.2
SNDMORE发送中途故障引发的跨客户端串包与修复陷阱多帧发送一旦在第 0 帧
identity (SNDMORE=1)入队后中断,继续复用同一个ROUTER会把下一个客户端的整包响应错寄给上一个客户端。假设服务端回复Client A时成功执行了send("Client_A", SNDMORE=1),但在发送后续帧时因底层内存分配失败抛错退出,没有发出SNDMORE=0。如果worker_thread捕获异常后继续处理Client B的请求并调用send("Client_B", SNDMORE=1)和send(Reply_B, SNDMORE=0),ROUTER会把"Client_B"和Reply_B当作Client A未封口信封的后续帧一并封箱发给Client A。结果是Client A收到帧边界错位的脏数据(触发 PR #143 记录的ZMQMessageDecodeError),而Client B永久挂死直到超时。sequenceDiagram participant CA as Client A participant R as ROUTER Socket participant W as Worker Thread participant CB as Client B CA->>R: 1. 发送 req_A CB->>R: 2. 发送 req_B R->>W: 取出 req_A W->>R: send("Client_A", SNDMORE=1) [信封已拆开,未封口] W--xW: 发送后续帧抛异常,未发 SNDMORE=0 Note over W,R: 错误做法:吞掉异常继续复用脏 ROUTER R->>W: 取出 req_B W->>R: send("Client_B", SNDMORE=1) [被拼入 Client A 的信封] W->>R: send(Reply_B, SNDMORE=0) [封口发送] R-->>CA: 把 Client B 的回复错发给 Client A(串包 / 帧错位) Note over CB: 永远收不到回包,超时失败在设计去掉
inproc://后的恢复方案时,有两个看似自然但实际会引入严重副作用的“陷阱方案”应当避免:except中补发空帧router_socket.send(b"")强行封口。如果异常发生在[identity (SNDMORE=1), header (SNDMORE=1)]之后、Tensor 数据帧之前,补发b""会把残缺消息[header, b""]正式封箱投递给客户端。客户端解码器看到非空 Tensor 元数据配上一帧空 bufferb"",此前甚至会命中if not buffer: return torch.empty(shape)分支,静默构造出一块未初始化的随机内存张量交给训练逻辑。except中put_get_socket.close(linger=0)并重新bind原端口。这种做法会把单请求故障放大为全节点故障:(1)close(linger=0)会瞬间丢弃该ROUTER上所有其他并发客户端已排队的请求及尚在发送缓冲区的响应;(2)put_get_socket绑定的是get_free_port()从操作系统临时端口段分配的端口,在异步释放 fd 到重新bind成功的空窗期内,同节点其他进程的出向connect()极易抢占该临时端口,导致重绑报EADDRINUSE失败;(3)新建内核LISTENsocket 会使内核sk_drops计数归零,导致AcceptQueueProbe算出负数的sk_drops_delta。PR #228 采用了“前置校验隔离常规错误 +
_router_tainted快速停机兜底极端错误”的两层设计:response_msg.serialize()和全部响应帧的zmq.Frame构造都在调用第一次router_socket.send之前完成。用户的data_parser返回非法对象或 buffer 转换失败全部在写入SNDMORE前拦截,put_get_socket不受污染。SNDMORE=1已经进入router_socket、且后续帧send抛错时(由于ROUTER配置了SNDHWM=0且ROUTER_MANDATORY=0,此处仅做内存无锁管道入队,只有进程级 C++ 堆耗尽或 Context 损坏才会失败),才将self._router_tainted置为True并上抛触发_abort_process(以退出码70终止进程,见 PR #201)。服务端拒绝带病发包杜绝了串包,客户端则依靠 ZMTP 原子多帧语义自动丢弃未封箱半包。2.3 不可恢复
poller.poll()故障下的死循环假活旧版
_worker_loop用宽泛的except Exception: continue包裹poller.poll(),一旦底层 socket 出现不可恢复故障(如ENOTSOCK),工作线程会占满单核 CPU 无限刷告警日志,而 Ray Actor 表面存活却永不响应任何请求。PR #228 将轮询异常处理收紧为仅在errno.EINTR时重试、在_shutdown_event置位或ContextTerminated时优雅退出,其余ZMQError直接上抛触发_abort_process让故障显式暴露。2.4 启动竞态消除与鲲鹏 ARM64 / 容器环境下的 PyTorch 线程初始化
0.5s启动竞态:去掉inproc://代理后,不再需要靠time.sleep(0.5)猜测worker_thread是否已连上inproc://后端 socket。aarch64节点或受限容器中,psutil.cpu_count(logical=False)会返回None(旧代码会触发TypeError;若简单回退为1,则会把默认的TQ_NUM_THREADS=8强行降级为单线程)。新实现提取了set_pytorch_auto_parallel_threads(),按psutil.cpu_count(logical=False) or psutil.cpu_count(logical=True) or os.cpu_count() or 1顺序回退,并放在_worker_routine入口执行一次——既直接在执行算子的工作线程上初始化 ATen / OpenMP 的线程局部nthreads-var,又消除了逐请求读取/proc/cpuinfo和改写进程全局线程数的开销。3. 全链路故障与可观测性全景对照
结合此前一系列稳定性 PR,当前
SimpleStorage在客户端、网络层与服务端各层的故障防护与可观测性分工如下:zmq.Context)与 PR #167(ZMQSocketPool独占租约,超时或取消立即销毁中毒DEALERsocket)根除。_process_one_worker_request入口的STORAGE_CLIENT_IDENTITY_PREFIXES白名单直接静默丢弃。inproc重连吞并发请求、多帧发送半包串包、Poller 坏死空转 -> 由 PR #228 根除;不可恢复故障统一收敛至 PR #201 的_abort_process(退出码70)。DEALER首次握手期排队、内核BACKLOG溢出与未来新传输协议排障 -> 继续依赖并保留以下可观测性机制:ZMQMessage.deserialize中的describe_frames()(PR #143):一旦未来修改编解码或传输层再次引发帧错位,第一时间输出每帧字节分布;log_heavy_operation(PR #171,在 PR #228 中统一覆盖客户端侧PUT/UPDATE/GET);AcceptQueueProbe、requests_arrived与客户端超时探针_diagnose_storage_unit(PR #171、PR #172、PR #192):用于区分外部建连丢包(request_lost_in_flight)与服务端慢请求阻塞(unit_not_serving)。4. 后续维护注意事项
后续修改
_send_multipart_reply或_worker_loop时需注意两个底层细节:pyzmq对小帧的内联拷贝阈值(copy_threshold):直接调用zmq.Frame(memoryview(part), copy=False)会绕过router_socket.copy_threshold(默认65536字节),导致百字节级的响应 header 也被注册进zmq.utils.garbage.gc.refs,拉起并频繁通过inproc://pyzmq.gc.01唤醒pyzmq内置的后台GarbageCollectorThread争抢 GIL。构造预备帧时应使用zmq.Frame(memoryview(part), copy=None, copy_threshold=router_socket.copy_threshold),使< 64 KB的控制帧走 C 层内联拷贝、>= 64 KB的大张量帧保持零拷贝。RCVMORE对称排空:如果在router_socket.recv_multipart(copy=False)读出第 0 帧后遭遇极端异常中断且循环继续,残留在put_get_socket头部的后续帧(getsockopt(zmq.RCVMORE) == 1)会导致下一轮读取发生接收侧帧边界偏移;在异常恢复分支排空RCVMORE(或将其视为不可恢复错误退出)可保持收发两侧边界对称。