Skip to content

[refactor, transfer] Introduce PayloadTransfer abstraction for SimpleStorage - #214

Merged
0oshowero0 merged 18 commits into
Ascend:mainfrom
shun001:208-nixl
Nov 26, 2026
Merged

0oshowero0 merged 18 commits into
Ascend:mainfrom
shun001:208-nixl

Conversation

@shun001

@shun001 shun001 commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Introduce a pluggable PayloadTransfer data-plane interface (listen, request, shutdown) for SimpleStorage and adapt the existing ZMQ backend (ZmqPayloadTransfer) to it, following the direction proposed in RFC #208.

PUT, GET, and UPDATE now share await transfer.request(peer_info, header, *, send=None) -> PayloadReply. Write requests pass unencoded field values in send, and GET (send=None) returns decoded field values in reply.payload. This preserves the existing zero-copy multipart codec path without introducing an extra encode/decode round trip.

Each backend manages its own peer connection reuse, single-request cancellation isolation, and teardown in one layer (ZMQSocketPool for ZMQ), while peer discovery descriptors are wrapped in an opaque PayloadPeerInfo object (fetched alongside control-plane ZMQ info in a single batched get_bootstrap_info() RPC at startup) so OmegaConf stores them without ${...} interpolation or verbose binary descriptor logs.

Changes

  • Data-plane SPI (transfer_queue/storage/payload_transfer/):
    • Define Operation (PUT, GET, UPDATE), PayloadPeerInfo, RequestHeader, PayloadReply, and the 3-method PayloadTransfer interface in base.py, clarifying owned vs. host-shared listener and pool lifecycles.
    • Extract transport fault contracts into errors.py: TransferError(message, *, transient=False), TransferTimeout(transient=True, wire_bytes=...), and StorageRejected(missing_key=...).
    • Implement ZmqPayloadTransfer in zmq.py: defer ZMQMessage.serialize() until after acquiring a ZMQSocketPool.alease permit so queued PUT callers keep zero-copy views rather than materializing contiguous copies early; exit the lease cleanly when closed while queued so rejected queued writes do not churn healthy pooled sockets; and whitelist transient resource/syscall ZMQError errnos (_TRANSIENT_ZMQ_ERRNOS) so deterministic protocol, decode (ZMQMessageDecodeError), or endpoint configuration (EINVAL) errors fail immediately without retries.
  • Manager retry & error translation (AsyncSimpleStorageManager):
    • Normalize _payload_peers once in __init__ and consolidate retry handling and public exception translation into _request_payload (defaulting max_attempts=1 Fail-Closed for UPDATE and parser-backed operations, preserving TQ_SIMPLE_STORAGE_MAX_ATTEMPTS timeout recovery for plain GET and PUT, and running _diagnose_storage_unit only on StorageUnitTimeout).
  • StorageUnit handler, concurrency & observability (SimpleStorageUnit, TQMetricsExporter, IntervalPerfMonitor):
    • Consolidate PUT, GET, and UPDATE execution into SimpleStorageUnit._handle_payload with fine-grained _storage_lock synchronization (PUT/GET data_parser callbacks run outside _storage_lock, while UPDATE read-merge-write runs atomically under _storage_lock), thread-safe IntervalPerfMonitor locking, and empty-frame ZMQMessage.deserialize([]) validation.
    • Add optional count_error predicate support to TQMetricsExporter.measure() so expected concurrent clear vs. GET missing-key races record request count and latency without inflating tq_storage_request_errors, while genuine storage rejections increment error counters.
  • Rolling-upgrade compatibility (transfer_queue/storage/exceptions.py):
    • Extract public StorageKeyNotFoundError to transfer_queue.storage.exceptions while preserving StorageKeyNotFoundError.__module__ = "transfer_queue.storage.simple_storage" (for Ray worker/driver pickle compatibility) and [TQKeyNotFound] ZMQ wire-message compatibility in both directions.

Validation

Automated unit, type, and sanity checks

  • 194 unit tests passing across test_zmq_payload_transfer.py, test_storage_request_retry.py, test_storage_key_race.py, test_async_simple_storage_manager.py, test_simple_storage_unit.py, test_simple_storage_scheduling.py, test_accept_probe.py, test_storage_worker_death_exits.py, test_metrics.py, and test_data_dump.py, alongside mypy, ruff, docstring, and license checks.
  • Dedicated regression coverage includes:
    • Cancelled in-flight ZMQ request isolating its late reply from subsequent callers on a maxsize=1 pool;
    • Committed PUT with a corrupt ACK failing once without replaying over a newer concurrent write;
    • 32 queued PUTs aborted after shutdown() with zero extra writes and zero healthy-socket churn;
    • Malformed ZMQ endpoint (port=-1, EINVAL) failing on the first attempt without retries or unit probing;
    • Concurrent PUT, CLEAR_DATA, and GET_METRICS completing while a slow GET data_parser runs unlocked;
    • PayloadPeerInfo preserving unclosed ${...} strings and summarizing binary descriptors in OmegaConf;
    • Bidirectional [TQKeyNotFound] wire compatibility and StorageKeyNotFoundError pickle module path preservation.

Cross-host fault injection

Cross-host fault injection passed in both directions between two Linux hosts, covering:

  • Delayed replies arriving after a timeout.
  • Server socket closure and recovery after rebinding the same port.
  • Request cancellation while a reply remains outstanding.
  • An UPDATE applied successfully with its reply deliberately dropped.
  • Eight concurrent GET requests after faults with a pool capacity of one.

The checks confirmed that failed sockets were discarded, late replies were isolated from subsequent requests, and the pool remained usable. The lost-reply UPDATE was applied once, reported a timeout, and its result was verified by subsequent GET requests.

Performance comparison

The dual-node comparison used identical benchmark code and configuration for main and this implementation.

  • Writer and reader on one host; two StorageUnits on the other.
  • CPU data, eight threads, metrics disabled, and a 1 Gb/s network.
  • Four workloads: 1 MiB, 288 MiB, 1 GiB, and approximately 240 MiB of mixed tensor and string fields.
  • Six steady-state samples per version and workload.
Workload PUT median latency change GET median latency change
1 MiB +0.20% +1.19%
288 MiB −0.09% −0.98%
1 GiB −0.02% −0.09%
Mixed fields +0.43% −0.19%

Positive values indicate higher latency. Median changes remained within −0.98% to +1.19% across the tested operations and workloads. The largest mean latency increase was 3.09% for mixed-field PUT.

No material end-to-end performance regression was observed in the tested dual-node configuration. These measurements describe the current network and workloads; large transfers are constrained by the 1 Gb/s link.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T07:12:10.015103Z d394bf9 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d394bf99bd

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

raise TransferTimeout("NIXL storage request timed out", wire_bytes=wire_bytes)
await asyncio.sleep(0.001)
response = reply.result()
except Exception as exc:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Treat cancelled writes as outcome-unknown after sending

When a PUT/UPDATE task is cancelled after send_notification but before the reply, asyncio.CancelledError inherits BaseException and therefore bypasses this except Exception; the storage unit may still apply the write while the caller sees only cancellation. A caller using asyncio.wait_for and retrying can consequently apply a non-idempotent UPDATE twice, so this post-send cancellation path needs to finish determining the outcome or surface WriteOutcomeUnknown just like the timeout path.

Useful? React with 👍 / 👎.

logger.exception("NIXL storage request %s failed", request_id)
reply["error"] = str(exc)[:4096]
try:
packed = self._pack_control(reply)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Prevent oversized update acknowledgements after committing

When an UPDATE produces enough per-sample stored_shapes to make its reply exceed MAX_CONTROL_BYTES (1 MiB), _handle has already called apply_update before this packing attempt. _pack_control then falls into the outcome-unknown reply, so AsyncSimpleStorageManager.update_data raises before notify_data_update; for a newly added or shape-changing field, storage is committed while controller metadata remains stale. Large valid updates therefore deterministically leave the planes inconsistent; reject or preflight before applying, or carry the acknowledgement body outside the capped notification.

Useful? React with 👍 / 👎.

@ji-huazhong

Copy link
Copy Markdown
Collaborator

cc @Ginray

@shun001 shun001 changed the title [WIP]Support nixl PayloadTransfer for SimpleStorage Support ZMQ PayloadTransfer for SimpleStorage Nov 20, 2026
@0oshowero0 0oshowero0 changed the title Support ZMQ PayloadTransfer for SimpleStorage [refactor, transfer] Introduce PayloadTransfer abstraction for SimpleStorage Nov 20, 2026
Signed-off-by: lanzeshun <[email protected]>
- Simplify PayloadTransfer.request recv to Spans | None = None, add FieldData/HeaderBody aliases, separate server/client roles, and export core symbols from payload_transfer.__init__.
- Synchronize SimpleStorageUnit state and counter access with _storage_lock while keeping PUT/GET data_parser execution outside the lock, and retry transient TransferError failures on fresh connections.
- Replace KEY_NOT_FOUND_MARKER string prefixing with structured missing_key metadata, condense ZMQ wire-type mappings, and streamline tests around end-to-end payload contracts.

Signed-off-by: 0oshowero0 <[email protected]>
…queued put memory

- Extract PayloadClient to encapsulate per-loop peer handshakes, connection caching/eviction, and shutdown outside AsyncSimpleStorageManager, and move StorageKeyNotFoundError to transfer_queue.storage.exceptions.
- Replace body/data tuple returns and alias indirections with RequestHeader.params and PayloadReply(meta, payload, wire_bytes), and clarify write vs read semantics on PayloadTransfer.request.
- Defer ZMQ request serialization inside pool.alease so queued writers retain zero-copy views, restore [TQKeyNotFound] wire compatibility across rolling upgrades, and add dual copyright headers.

Signed-off-by: 0oshowero0 <[email protected]>
…ispatch

- Keep StorageKeyNotFoundError.__module__ on transfer_queue.storage.simple_storage so rolling-upgrade Ray peers unpickle and catch missing-key errors cleanly.
- Remove top-level is_zmq_payload_request export in favor of ZmqPayloadTransfer.can_handle.
- Make the concurrent parser metrics check deterministic by awaiting PUT and CLEAR before sampling active_keys while the GET parser remains blocked.

Signed-off-by: 0oshowero0 <[email protected]>
- Remove PayloadClient and PayloadTransfer.connect() so each backend owns peer connection reuse, single-request cancellation isolation, and teardown in one layer; revert orphaned handshake drain in TransferQueueClient._start_loop

- Introduce opaque PayloadPeerInfo so OmegaConf stores peer descriptors as atomic AnyNode objects without interpolation errors or verbose binary logs

- Normalize _payload_peers once in AsyncSimpleStorageManager.__init__ and keep shared storage_rpc_pool teardown in AsyncSimpleStorageManager.close()

Signed-off-by: 0oshowero0 <[email protected]>
…tries

- Add DeliveryState (UNSENT, REJECTED, IN_DOUBT) and transient flag to TransferError so deterministic protocol/decode/config errors never retry large payloads or trigger misleading unit diagnostics

- Prevent PUT retries once delivery enters IN_DOUBT so a committed write with a lost or corrupt ACK cannot overwrite a concurrent update

- Decouple StorageUnitTimeout diagnosis from retry eligibility so non-retried PUT/UPDATE/parser timeouts still report TCP and probe verdicts

Signed-off-by: 0oshowero0 <[email protected]>
- Add optional count_error predicate to TQMetricsExporter.measure (and IntervalPerfMonitor.measure)

- Exempt StorageRejected(missing_key=True) from tq_storage_request_errors while keeping request count, latency histogram, and real storage error accounting intact

Signed-off-by: 0oshowero0 <[email protected]>
…QError errnos

- Align PayloadTransfer.shutdown() contract with AsyncTransferQueueClient.close() and re-check _closed after acquiring a pooled socket so queued PUTs never send after shutdown()

- Replace ETERM blacklist with an explicit _TRANSIENT_ZMQ_ERRNOS whitelist so deterministic ZMQ errors such as EINVAL fail once without retries, and restrict _diagnose_storage_unit to StorageUnitTimeout

Signed-off-by: 0oshowero0 <[email protected]>
- Extract TransferError, TransferTimeout, and StorageRejected into payload_transfer/errors.py, drop DeliveryState, and restore plain PUT timeout retries (PR Ascend#171) while keeping deterministic protocol/decode/config errors non-retryable

- Flatten retry and error translation into AsyncSimpleStorageManager._request_payload, removing _request_with_retry, __cause__ unwrapping, _payload_closed, and unimplemented recv parameters

- Fetch ZMQ and payload peer descriptors in a single batched get_bootstrap_info() RPC, initialize ZmqPayloadTransfer._handle, remove defensive getattr wrappers, and keep measure() signature pure

Signed-off-by: 0oshowero0 <[email protected]>
…d inline storage callback

- Exit ZMQSocketPool.alease cleanly when closed while queued (and on decoded unexpected responses) so queued PUT rejections do not churn healthy pooled sockets

- Default _request_payload to Fail-Closed max_attempts=1 and merge TransferTimeout and TransferError into a single retry/logging flow

- Fold handle_storage_request into SimpleStorageUnit._handle_payload with explicit _measure_payload_op accounting, and clarify listen()/shutdown() resource ownership

Signed-off-by: 0oshowero0 <[email protected]>
@0oshowero0
0oshowero0 merged commit a906942 into Ascend:main Nov 26, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants