Skip to content

[Reshard] Add Transfer Engine execution and completion lifecycle - #3964

Merged
Bo-Vincent merged 10 commits into
kvcache-ai:mainfrom
Bo-Vincent:vin/reshard-te-execution-core
Sep 23, 2026
Merged

Bo-Vincent merged 10 commits into
kvcache-ai:mainfrom
Bo-Vincent:vin/reshard-te-execution-core

Conversation

@Bo-Vincent

@Bo-Vincent Bo-Vincent commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator

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 TransferSubmission API. Resources
and 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

  • Transfer Engine (mooncake-transfer-engine)
  • Mooncake Store (mooncake-store)
  • Reshard (mooncake-reshard)
  • Mooncake EP (mooncake-ep)
  • Mooncake PG (mooncake-pg)
  • Integration (mooncake-integration)
  • P2P Store (mooncake-p2p-store)
  • Python Wheel (mooncake-wheel)
  • Common (mooncake-common)
  • Mooncake RL (mooncake-rl)
  • CI/CD
  • Docs
  • Other

Type of Change

  • Bug fix
  • New feature
  • Refactor
  • Breaking change
  • Documentation update
  • Performance improvement
  • Other

How Has This Been Tested?

Test commands:

PYTHONPATH=mooncake-reshard/python \
  python3 -m pytest -q mooncake-reshard/tests

npx --yes pyright --project mooncake-reshard/pyrightconfig.json

./scripts/code_format.sh --changed-lines --check \
  -b 2ca843e0073c4acd3c2beb224f82ff4df687c395

mapfile -t files < <(
  git diff --name-only --diff-filter=ACMR \
    2ca843e0073c4acd3c2beb224f82ff4df687c395...HEAD
)
pre-commit run --files "${files[@]}"

cmake -S . -B build-tent -G "Unix Makefiles" \
  -DCMAKE_BUILD_TYPE=Release \
  -DWITH_TE=ON \
  -DWITH_STORE=OFF \
  -DWITH_STORE_RUST=OFF \
  -DBUILD_UNIT_TESTS=ON \
  -DBUILD_EXAMPLES=OFF \
  -DBUILD_BENCHMARK=OFF \
  -DUSE_CUDA=OFF \
  -DUSE_TENT=ON
cmake --build build-tent --target tent_engine_failover_e2e_test -j 16
ctest --test-dir build-tent \
  -R '^tent_engine_failover_e2e_test$' --output-on-failure

Test results:

  • Unit tests pass: 544 passed, 1 skipped
  • Integration tests pass:
    • native Scatter write/read and rejection paths passed on H20;
    • TENT tent_engine_failover_e2e_test passed on ubuntu-toyko.
  • Manual testing done:
    • built the native CUDA-enabled engine module on H20;
    • verified completion tickets for successful and drained-failure outcomes.

Pyright completed with zero errors. Changed-lines formatting and all applicable
pre-commit hooks passed.

Checklist

AI Assistance Disclosure

  • No AI tools were used
  • AI tools were used (specified below)

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.

Comment on lines +2534 to +2539
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)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@Bo-Vincent
Bo-Vincent force-pushed the vin/reshard-te-execution-core branch from 14ecec2 to 756e0b8 Compare September 9, 2026 04:33

@zxpdemonio zxpdemonio left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Request changes. I found the following correctness and API-lifecycle issues; details are attached inline.

batch: TransferBatch,
direction: TransferDirection,
) -> TransferBatchReceipt:
if not self._active:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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>(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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>(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment thread mooncake-reshard/pyrightconfig.json Outdated
"python/mooncake/reshard/weight/serde.py",
"python/mooncake/reshard/weight/_planner"
"python/mooncake/reshard/weight/_planner",
"python/mooncake/reshard/transfer_engine/registration.py"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@Bo-Vincent
Bo-Vincent force-pushed the vin/reshard-te-execution-core branch from 756e0b8 to e68ae3a Compare September 9, 2026 08:39

@zxpdemonio zxpdemonio left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 ||

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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().

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@Bo-Vincent
Bo-Vincent force-pushed the vin/reshard-te-execution-core branch 3 times, most recently from 0f90ac7 to 14b13e7 Compare September 14, 2026 03:30
pending_transfer_id = self._pending_manager._retain_pending_ticket(
error.ticket
)
self._handoff_active_registration_frames(pending_transfer_id)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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().

@Bo-Vincent
Bo-Vincent force-pushed the vin/reshard-te-execution-core branch from 14b13e7 to 6028246 Compare September 14, 2026 07:16

@zxpdemonio zxpdemonio left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM.

@Bo-Vincent
Bo-Vincent force-pushed the vin/reshard-te-execution-core branch from 6028246 to 5ea81e4 Compare September 16, 2026 03:07
QueueOwnerKind::User);
}

Status TransferEngineImpl::submitCancellableTransfer(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why introducing submitCancellableTransfer? Essentially all transfers are cancellable before posting to RNICs.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@Bo-Vincent
Bo-Vincent force-pushed the vin/reshard-te-execution-core branch 3 times, most recently from 7f9acc3 to 45c4661 Compare September 20, 2026 08:41

@staryxchen staryxchen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Two behaviors need a decision before merge:

  1. TENT submitScatter no longer uses submitTransfer. The new path requires a cancellable transport, rejects staging, and disables runtime-queue admission and auto failover. TCP and the other transports whose supportsCancellation() is false fail the whole batch, and Status::Context hides the NotImplemented. Please document that contract on submitScatter and test it through the public API, or keep non-cancellable routes on the normal submit path.

  2. 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 after freeBatch. 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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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) ||

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@Bo-Vincent
Bo-Vincent force-pushed the vin/reshard-te-execution-core branch from 45c4661 to 243cfdd Compare September 22, 2026 12:28

@staryxchen staryxchen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM from TE side

@ShangmingCai ShangmingCai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Integration part LGTM since the diff are mainly additive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants