Skip to content

[fix] Avoid blocking async KV calls and release manager resources - #242

Merged
ji-huazhong merged 6 commits into
Ascend:mainfrom
ji-huazhong:fix/kv-storage-async-cleanup
Dec 2, 2026
Merged

ji-huazhong merged 6 commits into
Ascend:mainfrom
ji-huazhong:fix/kv-storage-async-cleanup

Conversation

@ji-huazhong

Copy link
Copy Markdown
Collaborator

KVStorageManager.get_data() and clear_data() called synchronous backend SDK methods on the event-loop thread. While an SDK call waited, unrelated coroutines on the same loop could not progress. Closing the manager also left its packing executor and Mooncake transfer buffers allocated; the executor finalizer had captured None before the lazy pool was created.

This change runs PUT, GET, and CLEAR SDK calls in a manager-owned executor, preserving the caller's initialized CUDA/NPU device and stream. Closing the manager drains both executors and releases Mooncake receive/staging buffers through the existing close(unmount=False) method. The shared storage segment stays mounted so other clients can continue reading it; calling the storage client's close() without arguments retains its existing full-close behavior.

Before and after

The same regression tests were run against the base implementation and this change with real Mooncake TCP and GDR backends:

Scenario Before After
GET waits for another coroutine on the same loop Loop cannot release the SDK gate; fails after 5 s Other coroutine runs; the real SDK read completes and tensors match
CLEAR waits for another coroutine on the same loop Same 5 s failure Clear completes and the unselected field remains readable
Close a manager after reading Packing worker remains alive I/O and packing workers stop; transfer buffers are released; another client still reads shared data
GET on a non-default accelerator device and stream Passes Still passes on GDR

The 5 s gate is a deterministic blocking regression, not a storage latency benchmark.

Performance

Measured on the same Linux host with Mooncake 0.3.14, comparing base 3727c64 with ab87413. These are real SDK calls with no injected delay. Each GET reads 32 samples with two float32 fields of 8,192 elements each (2 MiB per request); CLEAR removes one field from the same 32 samples. TCP uses CPU tensors, and GDR uses CUDA tensors. Concurrency 8 submits eight disjoint requests with asyncio.gather. Each case has 5 warm-up rounds and 20 measured rounds. Values are medians across rounds; heartbeat delay is each round's maximum lateness of a 1 ms asyncio timer.

Backend Operation Concurrent requests Wall time before → after (ms) Heartbeat delay before → after (ms)
TCP GET 1 2.843 → 3.089 1.861 → 0.904
TCP GET 8 25.179 → 23.205 24.200 → 3.888
TCP CLEAR 1 0.294 → 0.337 0.374 → 0.407
TCP CLEAR 8 1.427 → 1.448 0.443 → 0.377
GDR GET 1 2.574 → 2.697 1.592 → 0.532
GDR GET 8 19.258 → 19.618 18.283 → 1.079
GDR CLEAR 1 0.314 → 0.453 0.391 → 0.532
GDR CLEAR 8 1.433 → 1.998 0.449 → 0.733

After manager.close(), both base runs still had 2 packing workers alive. With the fix, all manager-owned I/O and packing workers stopped (0 of 30 remaining for TCP, 0 of 34 for GDR).

This measures local backend calls and manager scheduling, not network bandwidth or training speed. Offloading adds overhead to short calls, including the measured CLEAR workload; the main benefit is keeping the event loop responsive during SDK waits. Result packing remains on the original calling side.

Validation

  • Focused KV manager, Mooncake thread-context, buffer-pool, and utility tests: 72 passed, 5 skipped.
  • Complete lifecycle integration module: TCP 13 passed, 3 skipped; GDR 16 passed.
  • All three bug regressions fail on the base implementation and pass with this change. Accelerator-context coverage is a preservation check and already passes on the base.
  • compileall and pre-commit checks passed.
  • Full regression: 974 passed, 20 skipped, with the same 4 failures and 6 setup errors as the base (checkpoint/Rust/worker-process tests and unavailable Yuanrong integration dependencies). The final cleanup adjustment is covered by the focused and real-backend runs above. NPU hardware validation was not performed.

Signed-off-by: ji-huazhong <hzji210@gmail.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 28, 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-29T04:57:00.784270Z ab87413 Draft marked ready
ℹ️ 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.

@ji-huazhong
ji-huazhong marked this pull request as draft November 29, 2026 03:50
@ji-huazhong
ji-huazhong marked this pull request as ready for review November 29, 2026 04:51

@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: ab87413735

ℹ️ 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".

keys = self._generate_keys(metadata.field_names, metadata.global_indexes)
_, _, custom_meta = self._get_shape_type_custom_backend_meta_list(metadata)
self.storage_client.clear(keys=keys, custom_backend_meta=custom_meta)
await self._run_storage_operation(self.storage_client.clear, keys=keys, custom_backend_meta=custom_meta)

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 Make offloaded clears cancellation-safe

When async_clear_partition() or async_clear_samples() is timed out or cancelled after the SDK call starts, cancelling this run_in_executor await only cancels the asyncio wrapper; the worker keeps running and can still delete the keys. Those public flows mark controller rows as clearing before this call and remove their metadata only afterward (transfer_queue/client.py:542-549 and 571-578), so cancellation can leave rows stuck unready even after their payloads are gone until a caller explicitly retries. Defer cancellation until both the worker and controller cleanup have completed, rather than allowing the storage mutation to outlive the clear transaction.

AGENTS.md reference: AGENTS.md:L7-L9

Useful? React with 👍 / 👎.

@0oshowero0

Copy link
Copy Markdown
Collaborator

[AI Review] Review of ab87413:

Overall this is a clean and well-motivated fix: offloading get_data() and clear_data() onto a manager-owned executor fixes event-loop starvation, gating accelerator stream capture on is_initialized() avoids accidental CUDA/NPU initialization on CPU workers (and also fixes put_data() losing device/stream context), and removing the broken weakref.finalize(..., None) finalizer in favor of explicit close() teardown cleanly drains workers before releasing Mooncake transfer buffers.

A few concrete findings to consider before merging:

1. [High] Cancellation safety on offloaded clear_data() (data-loss race on async_kv_clear_fields, stuck state on async_clear_*)

  • Where: KVStorageManager.clear_data() / _run_storage_operation() in transfer_queue/storage/managers/base.py, called by async_clear_partition(), async_clear_samples(), async_clear_unlinked_public(), and async_kv_clear_fields() in transfer_queue/client.py.
  • Issue: Previously KVStorageManager.clear_data() had no await suspension point. Now that it awaits run_in_executor(...), cancelling or timing out (asyncio.wait_for) that await only cancels the asyncio wrapper future — the KVStorageIO thread continues running storage_client.clear() in the background.
    • Beyond the stuck clearing-row state noted in the earlier review comment (async_clear_partition / async_clear_samples / async_clear_unlinked_public skip _clear_*_in_controller()), there is a stronger race in async_kv_clear_fields() (transfer_queue/client.py:846-854): the controller clears the fields in place while keeping the same global_index reusable (controller.py:1992-1994). If clear_data() is cancelled mid-flight and a subsequent write stores a new value under the same {global_index}@{field} key, the orphaned background clear thread can finish afterward and silently delete the newly written payload while the controller reports the field as ready.
  • Suggestion: Defer cancellation around in-flight clear_data() mutations (and the surrounding clear transaction) so an already-submitted storage delete finishes before propagating CancelledError.

2. [Medium] Unbounded max_workers on self._io_executor

  • Where: KVStorageManager.__init__() in transfer_queue/storage/managers/base.py:
    self._io_executor = ThreadPoolExecutor(thread_name_prefix="KVStorageIO")
  • Issue: Unlike _multi_threads_executor in the same class (which explicitly caps workers to LIMIT_THREADS_PER_MANAGER_IN_RAY_ACTOR = 4 / LIMIT_THREADS_PER_MANAGER_IN_DRIVER = 8), _io_executor leaves max_workers unset, defaulting to min(32, (os.cpu_count() or 1) + 4). Even the PR's own concurrency-8 benchmark reports 30–34 manager-owned threads created.
    • On multi-actor nodes this multiplies thread counts per manager, and for MooncakeStoreClient it stacks with the per-call inner ThreadPoolExecutor(max_workers=MAX_BATCH_WORKER_THREADS) (4 threads) while competing for a BufferPool sized for max_regions=4 (mooncake_client.py:230-244), increasing fallback to per-read register_buffer/unregister_buffer under concurrency.
  • Suggestion: Pass an explicit bounded max_workers (e.g., aligned with the manager's driver/Ray-actor thread limits).

3. [Low] Concrete MooncakeStoreClient coupling in generic KVStorageManager.close()

  • Where: transfer_queue/storage/managers/base.py (from transfer_queue.storage.clients.mooncake_client import MooncakeStoreClient and isinstance(client, MooncakeStoreClient)).
  • Issue: KVStorageManager is the backend-agnostic KV manager base class, while MooncakeStorageManager already exists in transfer_queue/storage/managers/mooncake_manager.py. Hardcoding MooncakeStoreClient in base.py ties the generic layer to one backend.
  • Suggestion: Move the Mooncake-specific client.close(unmount=False) step into MooncakeStorageManager (preserving the ordering: drain executors → release Mooncake buffers → super().close()), or expose a backend-neutral client cleanup hook.

4. [Low] Exception isolation in MooncakeStoreClient.close() and unit-test coverage on CPU CI

  • Where: transfer_queue/storage/clients/mooncake_client.py (close) and tests/test_kv_storage_manager.py.
  • Issue:
    • In MooncakeStoreClient.close(), if self._buffer_pool.close() raises, self._gdr_staging.close(self._store) (and self._store.close() when unmount=True) is skipped, potentially leaking the GPU staging buffer. Wrapping cleanup steps with try/finally makes teardown more resilient.
    • The new E2E tests are solid, but test_async_get_preserves_accelerator_context is skipped on CPU-only CI. Adding lightweight unit tests in tests/test_kv_storage_manager.py for _run_storage_operation (non-blocking execution + mocked accelerator stream restoration + skipping uninitialized devices) and KVStorageManager.close() (draining _io_executor + calling close(unmount=False)) would keep this guarded on every CI run.

ji-huazhong added a commit that referenced this pull request Nov 30, 2026
Clearing tag-only keys can raise an error on KV backends. Cleanup can
also leave payloads behind when it uses read metadata: heterogeneous
rows have no common fields, and metadata containing only selected fields
does not describe everything stored in a row.

Have the Python and Rust controllers return complete deletion metadata
from `MARK_CLEARING`, grouped by partition and including stored fields
that are not ready yet. The client deletes payloads using this metadata
before releasing controller metadata and indexes. KV storage calls are
skipped only when the controller confirms that no payload fields exist;
the storage manager retains its guard against ambiguous empty-field
metadata.

Apply the same field selection to unlinked public-data cleanup.
Whole-partition cleanup gets its metadata directly from `MARK_CLEARING`,
eliminating one RPC and the separate partition-metadata fetch. Normal
reads, field-only deletion, and public-reference protection retain their
existing behavior.

Extend the existing tests for tag-only keys, heterogeneous rows, direct
sample cleanup with partial fields across partitions, unfinalized
fields, and public-data cleanup. Verify each stored field is removed
while neighboring data remains readable. Require Yuanrong's `Key not
found` error when reading a deleted field; other read errors still fail
the assertion.

Validation:

- All 16 GitHub CI checks passed, including unit tests and Python- and
Rust-controller E2E suites with SimpleStorage, MooncakeStore, and
Yuanrong.
- 98 focused tests passed, including client, controller, checkpoint, and
KV manager coverage.
- 42 Rust-controller cleanup and public-reference integration tests
passed; 18 Rust unit tests passed.
- Real Mooncake TCP: all 24 cleanup tests passed. On the previous PR
head, six synchronous/asynchronous cases fail because payloads remain
after cleanup.
- `python -m compileall -q transfer_queue tutorial tests` and all
pre-commit checks passed.

The local full suite finished with 992 passed and 16 skipped, plus one
previously reproduced worker-exit test failure and six Yuanrong fixture
errors caused by the missing optional dependency. The corresponding CI
unit tests and real Yuanrong integration passed.

This PR is based directly on `main` and is independent of #242.

---------

Signed-off-by: ji-huazhong <hzji210@gmail.com>
Signed-off-by: ji-huazhong <hzji210@gmail.com>
Signed-off-by: ji-huazhong <hzji210@gmail.com>
Signed-off-by: ji-huazhong <hzji210@gmail.com>
@ji-huazhong

Copy link
Copy Markdown
Collaborator Author

Addressed the cancellation, worker-budget, and backend-layering findings in 800b7bf, 0b6af12, and e0ae380.

  • Cancellation safety: the four public clear operations now defer cancellation until the complete clear operation finishes, including SDK deletion and controller metadata cleanup. Repeated cancellation cannot leave the delete running after the caller regains control. This also prevents a cancelled field clear from deleting a subsequent value written under the same key. The documented consequence is that cancellation/timeouts can take longer while an in-flight clear finishes.
  • Worker budget: the I/O executor now uses the existing manager CPU budget, capped at 4 workers inside Ray actors/tasks and 8 in the driver. The packing executor uses the same limit independently; these are per-pool caps, not a combined thread cap. Computing the budget does not initialize Ray when it is not already running.
  • Backend ownership: Mooncake buffer cleanup now lives in the existing MooncakeStorageManager.close(). It first drains the manager executors, then calls storage_client.close(unmount=False). The generic KV manager no longer imports or checks the concrete Mooncake client.

I did not apply unconditional finally cleanup in MooncakeStoreClient.close(): buffer-pool closure can fail because a lease is still active. Closing the underlying store anyway could free memory still in use. The existing buffer-pool tests cover this guard. For CPU coverage, I extended the existing worker-lifecycle test to check that the SDK operation runs on another thread and that the thread stops on close. Accelerator context is covered by the real GDR test rather than another mocked stream test.

Validation

  • One parameterized lifecycle regression covers partition, sample, field, and unlinked-public cleanup. It delays the real delete, cancels twice, then checks controller state and rewrites/reads the same keys. All four cases fail on the previous PR head (ab87413) with both TCP and GDR, and pass with these changes.
  • Real Mooncake TCP: 17 passed, 3 skipped. Real GDR: 20 passed, including accelerator-context coverage.
  • Focused local tests: 97 passed, 8 skipped. Compilation and Ruff checks passed.
  • Full suite: 978 passed, 20 skipped, 4 failed, 6 errors. A fresh full run of ab87413 produced 974 passed, 20 skipped, 4 failed, 6 errors, with exactly the same failing tests (checkpoint/Rust/worker-process tests and unavailable Yuanrong integration dependencies). There are no additional failures, but the full local suite is not all green.

Resource and timing comparison

Compared the already-offloaded previous PR head ab87413 with e0ae380 on the same host, using real SDK calls: 32 samples, two float32 fields of 8,192 elements each (2 MiB/request), concurrency 8 with disjoint requests, 5 warm-up rounds and 20 measured rounds. Times are medians; heartbeat delay is the round's maximum lateness of a 1 ms asyncio timer.

Metric Previous PR head Current
TCP manager I/O + packing workers 23 10
GDR manager I/O + packing workers 34 10
Workers alive after close, either backend 0 0
TCP GET wall time 23.077 ms 24.834 ms
TCP GET heartbeat delay 4.626 ms 4.938 ms
GDR GET wall time 19.654 ms 17.766 ms
GDR GET heartbeat delay 1.420 ms 0.842 ms
TCP CLEAR wall time 1.403 ms 1.539 ms
GDR CLEAR wall time 1.960 ms 1.670 ms

Worker counts include both manager-owned pools, not all process threads. This single-host sample supports the reduced thread budget; it does not show a universal throughput gain. TCP GET was about 7.6% slower and GDR GET about 9.6% faster in this run.

Signed-off-by: ji-huazhong <hzji210@gmail.com>
@ji-huazhong

Copy link
Copy Markdown
Collaborator Author

Fixed the CI failure in 12b994f.

test_core_consistency assumed that fetched samples had the same positional order as the original write. Recycled global indexes can make those orders differ. The test now reorders the complete fetched metadata using the global indexes returned by PUT, keeping shapes and backend metadata aligned. All existing field/value assertions remain unchanged; production code is unchanged.

Reproduced with real SimpleStorage through public APIs: write two rows, release them in reverse order, then run the existing consistency test. The previous test fails with tensor_f32 mismatch at index 0; the corrected test passes.

Validation:

  • All 16 GitHub CI checks passed, including Python- and Rust-controller E2E tests with SimpleStorage, Mooncake, and Yuanrong.
  • Compilation and Ruff checks passed.
  • Local full suite: 978 passed, 20 skipped, 4 failed, 6 errors. The failing tests are identical to the previously verified baseline.

@0oshowero0

Copy link
Copy Markdown
Collaborator

[AI Review] Follow-up review of 12b994f:

Thanks for the thorough follow-up — the cancellation handling (_finish_before_cancelling), bounded _io_executor worker budget, MooncakeStorageManager.close() ownership, and test_core_consistency index-order fix all look clean, and keeping the active-lease guard in MooncakeStoreClient.close() makes complete sense.

One small non-blocking test-hygiene nit:

  • tests/e2e/test_e2e_lifecycle_consistency.py: test_async_storage_wait_allows_other_coroutines (L164–193) and test_async_get_preserves_accelerator_context (L330–348) still compare fetched rows positionally against data[index] / tensor[index] without aligning fetched metadata to the written global_indexes. In full-module order they happen to pass, but under filtered runs (e.g., -k "test_cancelled_clear or test_async_get_preserves_accelerator_context") recycled indexes can come back in reversed order ([1, 0] written vs [0, 1] fetched), hitting the same mismatch fixed in 800b7bf and 12b994f. Reordering fetched metadata with recover_local_index(written.global_indexes, metadata.global_indexes) in both tests would keep the module order-independent.

No blocking issues remain — LGTM.

Signed-off-by: ji-huazhong <hzji210@gmail.com>
@ji-huazhong
ji-huazhong merged commit b94115e into Ascend:main Dec 2, 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.

2 participants