Repository navigation
[Reshard] Add Transfer Engine execution and completion lifecycle - #3964
Conversation
| for (size_t alias_id = 0; alias_id < batch->task_list.size(); ++alias_id) { | ||
| auto& task = batch->task_list[alias_id]; | ||
| if (alias_id == owner_task_id || | ||
| (task.derived && task.physical_owner_task_id == owner_task_id) || | ||
| (task.type == owner.type && | ||
| task.sub_task_id == owner.sub_task_id)) { |
There was a problem hiding this comment.
The explicit physical_owner_task_id mapping appears sufficient to identify all merged aliases. Could we remove the (type, sub_task_id) fallback, or at least guard it against the default sub_task_id == -1 value? This would avoid accidentally marking unrelated tasks that happen to share the same transport and sub-task ID.
There was a problem hiding this comment.
Fixed in the current head. Merged aliases are now identified only through the explicit physical_owner_task_id mapping. The (type, sub_task_id) fallback has been removed, so unrelated tasks cannot be marked through a reused or default sub-task ID.
The derived-owner and unrelated-task cancellation cases are covered by TENT tests.
14ecec2 to
756e0b8
Compare
zxpdemonio
left a comment
There was a problem hiding this comment.
Request changes. I found the following correctness and API-lifecycle issues; details are attached inline.
| batch: TransferBatch, | ||
| direction: TransferDirection, | ||
| ) -> TransferBatchReceipt: | ||
| if not self._active: |
There was a problem hiding this comment.
P1: TransferSubmission remains usable after a batch enters completion-unknown. Admission is performed only when submission() is entered, while execute_batch() checks only _active. If the caller catches TransferCompletionUnknownError, hands the pending ticket to retain_pending_resources(), and then calls submission.execute_batch() again, the second transfer is submitted on the same engine while the first DMA may still hold buffers, registrations, or allocation tokens. This violates the completion fence described by this PR. Please poison the submission after an unknown/interrupted completion or re-check pending state before every batch, and add a regression test for this same-submission path.
There was a problem hiding this comment.
Fixed. TransferSubmission now enters a poisoned state after completion becomes unknown or completion waiting is interrupted. Further execute_batch() calls on that submission are rejected until the pending transfer is resolved through its owner.
| ) | ||
| try: | ||
| yield | ||
| except ( |
There was a problem hiding this comment.
P1: Nested registration contexts lose the pending-completion carrier. _handoff_pending_resources() converts _PendingCompletionWaitInterrupted into the raw KeyboardInterrupt/SystemExit before the outer context sees it. The outer registered_sources()/registered_targets() context therefore treats the interruption as an ordinary failure and unregisters its own buffers, even though the native transfer may still be using them. Please keep the internal carrier (or an equivalent public exception carrying the pending ID) through all nested resource contexts and only convert it at the outermost boundary.
There was a problem hiding this comment.
Fixed. Completion interruption is now propagated as the public TransferCompletionInterrupted, carrying the pending transfer ID, engine identity, and original interruption.
Nested registration frames belonging to the same engine are handed off together. Frames owned by another engine remain isolated.
| } | ||
| } | ||
|
|
||
| auto operation = std::make_shared<TransferEngine::ScatterTransferOperation>( |
There was a problem hiding this comment.
P1: This new Python entry point exposes a hang in the underlying scatter operation when getTransferStatus() returns a non-OK status. In mooncake-transfer-engine/src/transfer_engine.cpp:1276-1279, poll() calls requestAbort() and continues; for a transport without cancellation support, no request is marked done and remaining_ never reaches zero. The ticket keeps returning COMPLETION_UNKNOWN, and destroying the operation can block forever because ~Impl() calls an unconditional wait(). Please make status-poll errors drive the operation to a safe terminal/drainable state (or implement a guaranteed cancellation path) before exposing this API.
There was a problem hiding this comment.
Fixed. A legacy Scatter status-query failure no longer releases the batch immediately. The operation checks the underlying task counters and releases resources only after physical completion has been confirmed.
The regression test verifies that callbacks and batch cleanup do not occur before the transfer is physically drained.
| } | ||
| } | ||
|
|
||
| auto operation = std::make_shared<TransferEngine::ScatterTransferOperation>( |
There was a problem hiding this comment.
P1: The same new binding also exposes the legacy scatter timeout path. In mooncake-transfer-engine/src/transfer_engine.cpp:1315-1320, a TransferStatusEnum::TIMEOUT requests abort and then continues for the non-TENT backend. Legacy scatter has no cancellation here, so the request is never marked done and remaining_ cannot reach zero; wait() may loop forever. Please complete/fail the pending fragments and release the legacy batch only after the physical operation is safely drained, and add a regression test for a legacy scatter timeout.
There was a problem hiding this comment.
Fixed. The legacy timeout path now follows the same physical-drain rule: the batch remains retained while work may still be in flight and is released only after the underlying operation reaches a confirmed terminal state.
| ("size", self.sizes), | ||
| ): | ||
| for value in values: | ||
| if type(value) is not int or value <= 0 or value > _MAX_U64: |
There was a problem hiding this comment.
P2: Flat TransferBatch validates each address and size independently but does not validate the address range. For example, source_addresses=(2**64 - 1,) with sizes=(2,) is accepted and then forwarded through the flat compatibility path. Please reject address + size overflow for both source and target addresses, as TransferBatchRange already does for allocation bounds.
There was a problem hiding this comment.
Fixed. TransferBatch now rejects address + size overflow independently for both source and target ranges. Regression coverage includes both sides.
| f"quarantined as {pending_transfer_id}{suffix}", | ||
| pending_transfer_id=pending_transfer_id, | ||
| ) from error | ||
| except _CompletionWaitInterrupted as error: |
There was a problem hiding this comment.
P2: The public execute_batch() API leaks the private _PendingCompletionWaitInterrupted exception when ticket status/drain is interrupted by KeyboardInterrupt or SystemExit. This means a caller using the executor directly cannot catch the original interruption with except KeyboardInterrupt, and must depend on a private implementation type. Please expose a public interruption error carrying the pending transfer ID, or retain the pending state and re-raise the original interruption at this API boundary.
There was a problem hiding this comment.
Fixed. The public execute_batch() API now raises TransferCompletionInterrupted instead of leaking the private _PendingCompletionWaitInterrupted type.
The public exception carries the pending transfer ID, engine identity, and original KeyboardInterrupt or SystemExit, allowing callers to retain and drain the pending transfer without depending on private implementation details.
Regression tests cover both interruption types through the public executor API.
| "python/mooncake/reshard/weight/serde.py", | ||
| "python/mooncake/reshard/weight/_planner" | ||
| "python/mooncake/reshard/weight/_planner", | ||
| "python/mooncake/reshard/transfer_engine/registration.py" |
There was a problem hiding this comment.
Optional: The type-check project includes only transfer_engine/registration.py, although this PR adds completion.py, contracts.py, executor.py, and lifetime.py as public transfer-engine modules. Please include the whole transfer_engine package (or otherwise ensure all new public modules are directly covered) so CI strict type checking cannot miss errors in the executor/completion APIs.
There was a problem hiding this comment.
Fixed. The strict Pyright configuration now includes the entire mooncake.reshard.transfer_engine package, covering completion.py, contracts.py, executor.py, lifetime.py, and registration.py.
The full strict type-check suite passes on the current head.
756e0b8 to
e68ae3a
Compare
zxpdemonio
left a comment
There was a problem hiding this comment.
Static review of the current head. The completion and resource-lifetime paths still have several correctness issues that can hang the engine, misreport fragment results, or release memory while native DMA is pending.
| auto result = getStatus(batch_id_, task_id, status); | ||
| if (!result.ok()) { | ||
| requestAbort(result); | ||
| if (finishDrainedLegacyFailure(result)) return; |
There was a problem hiding this comment.
[P1] Make TENT status-query failures terminal when cancellation is unsupported
When getStatus() returns an error, requestAbort() ignores NotImplemented from cancelTransfer(). finishDrainedLegacyFailure() is disabled for TENT, so poll() keeps retrying without marking the operation terminal. The ticket can only remain COMPLETION_UNKNOWN, and destroying it enters ScatterTransferOperation::Impl::~Impl()'s unconditional wait(), which may block forever. Please add a TENT-safe terminal/drain path, or make cancellation mandatory for this API, and cover a transport with supportsCancellation() == false whose status query fails.
There was a problem hiding this comment.
Fixed. Scatter submissions through TENT now select and pin a direct route that supports cancellation before publishing transport work. Non-cancellable or staged routes are rejected before DMA submission, so a later status-query failure always has a valid cancellation and drain path.
Regression tests cover both rejection of non-cancellable routes and preservation of the validated route after submission.
| __atomic_load_n(&task.success_slice_count, __ATOMIC_ACQUIRE); | ||
| const auto failure_count = | ||
| __atomic_load_n(&task.failed_slice_count, __ATOMIC_ACQUIRE); | ||
| if (slice_count == 0 || success_count > slice_count || |
There was a problem hiding this comment.
[P1] Handle legacy tasks that fail before creating any slices
legacyBatchPhysicallyDrained() returns false when slice_count == 0. If a legacy transport reports a submit/status error before posting any slice, the batch remains live with is_finished == false; the poll loop cannot finish or free it, and the operation destructor waits forever without invoking fragment callbacks. Please distinguish an unpublished zero-slice task from a physically pending task and add a regression test for this path.
There was a problem hiding this comment.
Fixed. The legacy Scatter path now distinguishes a submit failure before publication from an operation with physical slices still in flight. A failed zero-slice task can reach a drained terminal state, invoke its callbacks, and release the batch safely.
A regression test covers failure before any slice is created.
| return false; | ||
| } | ||
| batch_id_ = INVALID_BATCH_ID; | ||
| failPending(status); |
There was a problem hiding this comment.
[P1] Preserve per-fragment results when draining a grouped legacy task
After legacyBatchPhysicallyDrained() succeeds, failPending(status) reports the same failure to every fragment. A grouped task can have mixed slice results, so this changes successful fragments into failures when the status-query/timeout path reaches this drain helper. The normal FAILED path already calls getScatterRequestStatuses() to preserve per-request results; the drain path should use the same information before freeing the batch, with a mixed-success/mixed-failure regression test.
There was a problem hiding this comment.
Fixed. The legacy drain path now reads the individual Scatter request statuses before releasing the batch and completes each fragment with its own result instead of applying one failure status to the entire group.
A mixed-success/mixed-failure regression test verifies that successful fragments remain successful.
| ): | ||
| raise _handoff_pending_resources(pending_owner, primary_error) | ||
|
|
||
| if not frame.handed_off: |
There was a problem hiding this comment.
[P1] Do not unregister allocations when a pending error is caught in the body
If the caller catches TransferCompletionUnknownError or TransferCompletionInterrupted inside the with registered_sources(...) body, the context manager observes no exception at yield, so frame.handed_off remains false and this branch unregisters the allocation. The pending ticket may still be issuing DMA against that address, which can cause use-after-free or data corruption. Resource handoff must not depend solely on the exception escaping the context manager, or this usage must be explicitly prevented and covered by a regression test. The target path has the same issue.
There was a problem hiding this comment.
Fixed. When completion becomes unknown or interrupted, the executor now immediately hands the active source and target registration frames to the pending-operation owner. Resource retention no longer depends on the exception escaping the registration context.
Regression tests cover callers catching the pending error inside both source and target registration contexts.
| class TransferSubmission: | ||
| """Execute batches while one resource submission owns the native engine.""" | ||
|
|
||
| def __init__(self, executor: MooncakeTransferEngineExecutor) -> None: |
There was a problem hiding this comment.
[P1] Prevent direct construction from bypassing submission fencing
TransferSubmission is publicly exported, but its constructor creates an ACTIVE handle without calling _reserve_submission(). A caller can construct TransferSubmission(executor) directly and submit concurrently with executor.submission(), bypassing the engine-wide single-submission invariant described by this PR. Please make construction private/token-gated, or remove this class from the public API and expose instances only through submission().
There was a problem hiding this comment.
Fixed. TransferSubmission can no longer be constructed directly. Instances are created only by the executor after acquiring its submission reservation, so callers cannot bypass the engine-wide submission fence.
A regression test verifies that direct construction is rejected.
| range.remote_segment = endpoint; | ||
| range.remote_base_offset = remote_base_addresses[i]; | ||
| range.remote_size = remote_capacities[i]; | ||
| range.local_buffer = reinterpret_cast<void*>(local_base_addresses[i]); |
There was a problem hiding this comment.
[P2] Validate local address ranges before pointer arithmetic
The binding validates vector shapes and fragment offsets, but it does not check whether local_base_addresses[i] + local_capacities[i] is representable. A direct caller can pass UINTPTR_MAX with capacity 1; build() then performs local_buffer + local_offset and submits an invalid pointer. TransferBatchRange catches this only for callers going through the Python contract, not for this public binding entry point. Please reject local address-range overflow here and add a direct binding regression test.
There was a problem hiding this comment.
Fixed. The Python binding now validates that each local base address plus capacity is representable before constructing a pointer or submitting work. Fragment offset and length bounds remain validated against the same allocation range.
Direct binding regression tests cover overflowing local ranges for both read and write paths and verify that invalid pointers never reach the transport.
0f90ac7 to
14b13e7
Compare
| pending_transfer_id = self._pending_manager._retain_pending_ticket( | ||
| error.ticket | ||
| ) | ||
| self._handoff_active_registration_frames(pending_transfer_id) |
There was a problem hiding this comment.
[P1] Seal or complete the pending resource handoff when no registration frame is active. _retain_pending_ticket() creates the pending transfer with resources_handed_off=false, and this call becomes a no-op when _handoff_active_registration_frames() finds no matching frames. In that standalone executor path, the caller gets a pending_transfer_id, but drain_pending_transfer() then always fails with “pending transfer resource handoff is incomplete”, and _reserve_submission() keeps blocking future submissions on the same engine. Please either seal the empty handoff here when there are no frames, or require/perform retain_pending_resources() before exposing the pending transfer so the engine remains recoverable.
There was a problem hiding this comment.
Fixed in the current head.
When no matching registration frame is active, the executor now explicitly seals the empty resource handoff before exposing the pending transfer. The returned pending transfer can therefore be drained normally, and the engine becomes reusable after reaching a terminal state.
The standalone unknown-completion and interruption tests now exercise the public API directly without manually calling retain_pending_resources().
14b13e7 to
6028246
Compare
6028246 to
5ea81e4
Compare
| QueueOwnerKind::User); | ||
| } | ||
|
|
||
| Status TransferEngineImpl::submitCancellableTransfer( |
There was a problem hiding this comment.
Why introducing submitCancellableTransfer? Essentially all transfers are cancellable before posting to RNICs.
There was a problem hiding this comment.
The requirement here is stronger than cancellation before work is posted to
the RNIC. Scatter completion tickets must remain recoverable when status
polling fails after submission, so this path pins a direct transport that
supports post-submit cancellation and disables staging, runtime queueing, and
failover before publishing the work.
A normal submit may currently select a path where cancelTransfer() returns
NotImplemented after publication, leaving the ticket in a completion-unknown
state. Weight transfers may retain source GPU allocations and registrations
until the transfer reaches a terminal state, so cancellation must explicitly
release that lifetime fence.
That said, I agree that submitCancellableTransfer is too broad as a public API.
I will keep this as an internal submit requirement for Scatter, named around
post-submit cancellation, while leaving the regular submitTransfer API
unchanged.
There was a problem hiding this comment.
Updated. The stronger post-submit cancellation requirement is now internal to
the Scatter path. The public submitCancellableTransfer API has been removed,
while regular submitTransfer remains unchanged.
Scatter still pins a direct transport that supports post-submit cancellation,
so completion-unknown transfers can be drained without releasing retained GPU
allocations or registrations prematurely.
7f9acc3 to
45c4661
Compare
staryxchen
left a comment
There was a problem hiding this comment.
Two behaviors need a decision before merge:
-
TENT
submitScatterno longer usessubmitTransfer. The new path requires a cancellable transport, rejects staging, and disables runtime-queue admission and auto failover. TCP and the other transports whosesupportsCancellation()is false fail the whole batch, andStatus::Contexthides theNotImplemented. Please document that contract onsubmitScatterand test it through the public API, or keep non-cancellable routes on the normal submit path. -
A drained one-fragment legacy task is always
failPending'd. Grouped tasks consult per-slice status; a single request whose slices already succeeded is still reported as failure, and its callback runs afterfreeBatch. Please derive that outcome from the slice counters.
The slice_count == 0 fast path, the USE_EVENT_DRIVEN_COMPLETION race on the forced is_finished store, and stale type / sub_task_id on derived tasks after poll-stage failover are inline. The first two are safe if the transport contract and the non-event-driven build are what you intend; the third is safe for the call sites this PR updates.
| type >= static_cast<TransportType>(kSupportedTransportTypes) || | ||
| !transport_list_[type] || | ||
| !transport_list_[type]->supportsCancellation()) { | ||
| return Status::NotImplemented( |
There was a problem hiding this comment.
This rejects the whole scatter submit unless every merged owner resolves to a cancellable transport. Today that is RDMA, UB, and HP-TCP; supportsCancellation() defaults to false, so TCP, SHM, and NVLink fail here. The same flag also zeroes failover just above (max_failover_attempts = 0, enable_auto_failover_on_poll = false) and makes shouldQueueSubmit return false.
submitScatter used to call submitTransfer. TENT + TCP, and any staged HP-TCP route (the check below), now fails the entire batch. TransferEngine::submitScatterTransfer then wraps this NotImplemented as Status::Context (transfer_engine.cpp:488), so callers cannot branch on the status code. Scatter still unwinds an unpublished batch by probing task 0, so this does not hang; it changes a working submit into a batch failure.
If this narrowing is the completion-fence contract, please document it on submitScatter and add a public submitScatter test that TENT TCP is rejected. The new coverage goes through TransferEngineImplTestPeer only. If existing TENT TCP scatter must keep working, TCP needs a cancellation implementation, or this path has to stay on the normal submit.
There was a problem hiding this comment.
Fixed. The public Scatter contract now documents that the TENT path pins a
direct transport with post-submit cancellation support and rejects unsupported
or staged routes before publishing work.
The public API now preserves NotImplemented instead of wrapping it as
Context. A regression test exercises TransferEngine::submitScatter() with
TENT TCP, verifies that no task is submitted, and confirms that the registered
memory remains releasable.
| for (size_t task_id = 0; task_id < task_sizes_.size(); ++task_id) { | ||
| const size_t request_start = request_index; | ||
| request_index += task_sizes_[task_id]; | ||
| if (done_[request_start] || task_sizes_[task_id] <= 1) continue; |
There was a problem hiding this comment.
task_sizes_ <= 1 skips getScatterRequestStatuses and falls through to failPending(status) after freeBatch. A persistent getTransferStatus error, or a TIMEOUT returned after the slice counters already match, is reported as failure even when success_slice_count == slice_count.
Grouped tasks keep per-fragment results. The common one-fragment scatter task does not, so a completed write can be surfaced as failed and retried.
Please resolve the single-request outcome from the slice counters, or from getScatterRequestStatuses, before failing the callback. Also, this callback runs after freeBatch has deleted the BatchDesc and its slices. Grouped callbacks above run while the batch is still alive. Either complete the single-request callback before freeBatch, or document that it must not touch batch state.
There was a problem hiding this comment.
Fixed. Single-request and grouped Scatter tasks now derive their outcomes from
the same per-slice completion evidence.
A physically successful single request is preserved as successful, and all
fragment callbacks run before the batch and its slices are released. Regression
coverage verifies both the reported status and the callback-before-release
ordering.
| __atomic_load_n(&task.success_slice_count, __ATOMIC_ACQUIRE); | ||
| const auto failure_count = | ||
| __atomic_load_n(&task.failed_slice_count, __ATOMIC_ACQUIRE); | ||
| if ((!legacy_submit_failed_ && slice_count == 0) || |
There was a problem hiding this comment.
With legacy_submit_failed_, slice_count == 0 is treated as already drained. The loop then marks every task is_finished and finishDrainedLegacyFailure frees the batch. That matches a submit that failed before publishing any slice (ScatterPrePublishFailureDoesNotWaitForPhysicalSlices).
It also assumes the transport will not publish slices after returning that submit error. A transport that returns failure and then increments slice_count from another thread will have its batch deleted while the post is still in flight.
Please state that contract next to legacy_submit_failed_, or treat slice_count == 0 as drained only when the task was never handed to submitTransferTask.
There was a problem hiding this comment.
Fixed by making the publication boundary explicit.
submitTransferTask() now requires every slice to be published synchronously
before the call returns; transports must not append or publish slices
afterwards. Under that contract, a failed submission with zero published slices
is safely drained. The current transport implementations were audited against
this requirement, and the pre-publication failure regression remains covered.
| return false; | ||
| if (success_count + failure_count != slice_count) return false; | ||
| } | ||
| for (auto& task : batch.task_list) |
There was a problem hiding this comment.
markSuccess / markFailed publish the slice counters and then, under USE_EVENT_DRIVEN_COMPLETION, check_batch_completion still writes batch_desc. Seeing success + failure == slice_count happens before that function returns. Storing is_finished here and letting finishDrainedLegacyFailure delete the batch races that completion thread.
When the macro is off, check_batch_completion is empty and the counter update is the last touch, so this drain is safe. On the event-driven build, please wait until the transport publishes is_finished itself, or skip this forced finish.
There was a problem hiding this comment.
Fixed. Counter completion no longer forces is_finished in event-driven
builds, because the completion thread may still be accessing the batch after
publishing the counters.
Event-driven execution now waits for the transport-published terminal flag.
Counter-derived completion remains limited to the non-event-driven path, where
the counter update is the final batch access. A delayed-publication regression
test verifies that the operation remains pending until the completion event is
published.
| return Status::InvalidArgument( | ||
| "derived task has no physical owner" LOC_MARK); | ||
| } | ||
| poll_task_id = public_task.physical_owner_task_id; |
There was a problem hiding this comment.
Redirecting poll and cancel through physical_owner_task_id fixes the two bugs the new tests cover: a derived poll running failover a second time, and cancel hitting the pre-failover RDMA slot.
updateTaskStatusAfterPoll still updates only the owner. After poll-stage failover the derived task keeps the old type, sub_task_id, and status. Submit-stage failover in commitPreparedSubmit copies those fields onto every alias; this path does not. The two call sites updated here follow physical_owner_task_id, so they stay correct. A later match on (type, sub_task_id) will pair the derived task with the abandoned slot.
Please mirror the owner's route onto its aliases after poll-stage failover, the same way submit-stage failover already does.
There was a problem hiding this comment.
Fixed. After poll-stage failover succeeds, the physical owner's route and
status state is mirrored to every derived alias.
This includes the transport type, sub-task ID, status, failover count, transport
priority, device mask, QP pool, and staging state. Derived-task failover and
cancellation tests continue to verify that aliases follow the canonical
physical owner.
Signed-off-by: Vincent Gao <vincentbo@linux.alibaba.com>
45c4661 to
243cfdd
Compare
ShangmingCai
left a comment
There was a problem hiding this comment.
Integration part LGTM since the diff are mainly additive.
Description
This PR adds the resource-neutral Transfer Engine execution and completion
foundation used by heterogeneous resharding.
It extends the native Scatter transfer path with completion tickets for both
read and write operations. A ticket distinguishes completed transfers,
drained failures, and completion-unknown outcomes. The TENT path also preserves
completion ownership when transfer tasks are merged.
The Reshard layer introduces backend-facing transfer batch contracts,
registration leases, completion fencing, pending-operation ownership,
restart-required quarantine, and a scoped
TransferSubmissionAPI. Resourcesand registrations are released only after a terminal outcome is known. An
unknown outcome remains fenced so callers cannot reuse or free affected memory
prematurely.
This layer is resource-neutral. Model-weight validation, N-D lowering,
Reader/Sink adapters, Store persistence, and framework integration are handled
by later PRs.
Related RFC: #3111
Module
mooncake-transfer-engine)mooncake-store)mooncake-reshard)mooncake-ep)mooncake-pg)mooncake-integration)mooncake-p2p-store)mooncake-wheel)mooncake-common)mooncake-rl)Type of Change
How Has This Been Tested?
Test commands:
Test results:
544 passed, 1 skippedtent_engine_failover_e2e_testpassed on ubuntu-toyko.enginemodule on H20;Pyright completed with zero errors. Changed-lines formatting and all applicable
pre-commit hooks passed.
Checklist
./scripts/code_format.shAI Assistance Disclosure
AI assistance was used for implementation support, test development, and code
review. The submitter reviewed the changes and is responsible for the final
design and implementation.