Skip to content
This repository was archived by the owner on Jan 21, 2026. It is now read-only.

refactor: refactor TransferQueue client and storage manager to use a single controller. - #89

Merged
0oshowero0 merged 4 commits into
TransferQueue:devfrom
jianjunzhong:refactor/1027
Oct 29, 2025
Merged

0oshowero0 merged 4 commits into
TransferQueue:devfrom
jianjunzhong:refactor/1027

Conversation

@jianjunzhong

@jianjunzhong jianjunzhong commented Oct 27, 2025 •

Copy link
Copy Markdown
Contributor
  1. Refactor TransferQueue client and storage manager to use a single controller.
  2. Update related configurations and method calls for consistency.

Summary by CodeRabbit

Release Notes

  • Refactor

    • Simplified system architecture to utilize a single controller instead of multiple controllers, streamlining initialization and reducing configuration complexity.
  • Configuration Updates

    • Updated configuration structure to reflect single-controller design for improved clarity and ease of setup.
  • Tests

    • Updated test suite to align with new simplified single-controller architecture.

@0oshowero0
0oshowero0 requested a review from Copilot October 27, 2025 08:10

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

This PR refactors the TransferQueue system to use a single controller instead of supporting multiple controllers, simplifying the architecture and reducing complexity.

  • Simplified client and storage manager to interact with a single controller instead of multiple controllers
  • Updated configuration parameters from controller_infos (plural/dict) to controller_info (singular)
  • Removed controller selection logic and multi-controller coordination code

Reviewed Changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
transfer_queue/storage.py Refactored storage manager to use single controller, simplified handshake and data update notification logic
transfer_queue/client.py Removed multi-controller support, simplified to single controller registration and communication
tests/test_client.py Updated tests to use single controller configuration and added mocking for storage manager operations
tests/test_async_simple_storage_manager.py Updated test fixtures to use controller_info instead of controller_infos and fixed mock socket methods
recipe/simple_use_case/sync_demo.py Updated demo to initialize single controller and removed num_data_controllers configuration
recipe/simple_use_case/async_demo.py Updated async demo to use single controller throughout all components

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread recipe/simple_use_case/async_demo.py Resolved
Comment thread recipe/simple_use_case/sync_demo.py Resolved
@coderabbitai

coderabbitai Bot commented Oct 27, 2025 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Refactored the transfer queue system from a multi-controller to single-controller architecture. Method signatures, constructor parameters, socket management, and handshake logic updated across client, storage, and demo modules to use singular controller references instead of collections.

Changes

Cohort / File(s) Summary
Demo applications
recipe/simple_use_case/async_demo.py, recipe/simple_use_case/sync_demo.py
Updated constructor signatures for AsyncvLLMServer, AsyncRolloutWorker, RolloutManager, and Trainer to accept data_system_controller_info (singular) instead of data_system_controller_infos. Simplified controller initialization from multi-controller orchestration to single TransferQueueController. Updated config wiring and client creation accordingly.
Test utilities
tests/test_async_simple_storage_manager.py, tests/test_client.py
Renamed config keys from controller_infos to controller_info. Replaced full ZMQ handshake mocking with lightweight AsyncSimpleStorageManager instantiation. Updated test assertions to verify single controller binding instead of controller collection membership. Restructured multi-controller test scenarios to single-controller/multi-storage approach.
Core client
transfer_queue/client.py
Removed _controllers dict and _register_controllers method; introduced single _controller attribute. Updated AsyncTransferQueueClient and TransferQueueClient constructor signatures to accept controller_info: ZMQServerInfo instead of controller_infos. Removed target_controller parameter and hard-coded ZMQ routing to self._controller.id. Updated process_zmq_server_info to accept single handler or dictionary via Union typing.
Core storage
transfer_queue/storage.py
Replaced multiple per-controller sockets (data_status_update_sockets, controller_handshake_sockets) with single instances. Renamed public attribute controller_infos to controller_info. Simplified handshake logic to target single controller; updated _send_handshake_requests signature from accepting controller_ids set to no-arg variant.

Sequence Diagram

sequenceDiagram
    actor Client as AsyncTransferQueueClient
    participant Controller as TransferQueueController
    participant Storage as TransferQueueStorageManager
    
    Note over Client,Storage: Simplified Single-Controller Flow
    
    rect rgb(100, 150, 200)
    Note over Client,Storage: Initialization Phase
    Client->>Controller: process_zmq_server_info(controller_info)
    Controller-->>Client: ZMQ socket ready
    end
    
    rect rgb(150, 180, 220)
    Note over Storage,Controller: Storage Handshake
    Storage->>Controller: _send_handshake_requests()
    Controller-->>Storage: ACK response
    Storage->>Storage: Register single controller_handshake_socket
    end
    
    rect rgb(100, 180, 150)
    Note over Client,Storage: Data Operations
    Client->>Storage: async_get_data(key)
    Storage-->>Client: data value
    Client->>Storage: async_put_data(key, value)
    Storage->>Controller: notify_data_update(single_controller_id)
    Controller-->>Storage: ACK
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Areas requiring extra attention:

  • ZMQ socket and handshake refactoring (transfer_queue/storage.py): Logic transitions from iterating over multiple controllers to targeting a single handshake socket; verify timeout, retry, and polling behavior remain correct
  • Client-storage controller binding (transfer_queue/client.py): Verify single _controller registration flow and message routing consistency across all async/sync paths
  • Configuration consistency: Ensure controller_info vs controller_infos wiring is uniform across demo, client, and storage initialization chains
  • Test mock strategy changes: New lightweight AsyncSimpleStorageManager instantiation pattern differs significantly from prior ZMQ mocking; validate mock socket behavior for both send and recv paths
  • Public API surface changes: Multiple constructor signatures and method parameters modified; check for any undocumented clients or downstream consumers

Poem

🐰 One controller now guides the queue,
Where once a circle danced askew!
With sockets slim and handshakes clean,
The simplest path we've ever seen.
A refactor's song, both bright and true—
From plural dreams to singular dew! 🌙

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "refactor: refactor TransferQueue client and storage manager to use a single controller" is directly related to the main changes in the changeset. The raw summary confirms that the primary objective across all modified files is to replace multi-controller orchestration with a single controller, updating method signatures, API calls, and configuration handling accordingly. The title accurately captures this core refactoring effort and clearly identifies the specific components affected (TransferQueue client and storage manager). While the title has minor stylistic redundancy with "refactor" appearing twice (as both the conventional prefix and in the message body), this does not diminish its clarity or relevance to the changeset.

Comment @coderabbitai help to get the list of available commands and usage tips.

@0oshowero0

Copy link
Copy Markdown
Member

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 27, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

1 similar comment
@coderabbitai

coderabbitai Bot commented Oct 27, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai 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.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
transfer_queue/storage.py (1)

989-1009: Add socket timeouts and fix double-close in dynamic socket wrapper.

Avoid indefinite awaits and duplicate close calls; set RCVTIMEO/SNDTIMEO and close once with LINGER=0.

Apply this diff:

@@
-                try:
+                try:
                     sock.connect(address)
+                    # Timeouts to avoid indefinite await on recv/send
+                    sock.setsockopt(zmq.RCVTIMEO, 10_000)  # 10s
+                    sock.setsockopt(zmq.SNDTIMEO, 10_000)  # 10s
@@
-                finally:
+                finally:
                     try:
-                        if not sock.closed:
-                            sock.setsockopt(zmq.LINGER, -1)
-                            sock.close()
-                        sock.close(linger=0)
+                        if not sock.closed:
+                            sock.setsockopt(zmq.LINGER, 0)
+                            sock.close()
                     except Exception as e:
                         logger.warning(
                             f"[{self.storage_manager_id}]: Error closing socket to StorageUnit {server_info.id}: {e}"
                         )
 
                     context.term()
tests/test_client.py (1)

212-216: Fix attribute typo in MockStorage exception handler.

Uses self.is_running but the field is self.running.

Apply this diff:

-            except Exception as e:
-                if self.is_running:
+            except Exception as e:
+                if self.running:
                     print(f"MockStorage running exception: {e}")
                 else:
                     print(f"MockStorage ERROR: {e}")
                     raise
♻️ Duplicate comments (1)
tests/test_async_simple_storage_manager.py (1)

199-205: Clean up unused recv_multipart stub in handshake mocks.

Handshake uses recv(), not recv_multipart(); the extra stub is noise.

Remove mock_socket.recv_multipart assignments in these tests to reduce confusion.

Also applies to: 210-211, 219-220

🧹 Nitpick comments (6)
transfer_queue/storage.py (3)

125-138: Retry cadence is governed by POLLER timeout, not the intended interval.

With POLLER timeout at TQ_STORAGE_POLLER_TIMEOUT (default 5s), the 1s retry interval can’t be met; retransmit frequency is effectively >= poll timeout. Tighten the poll granularity or decouple retry timing from the blocking poll.

Example fix: use a shorter poll timeout (e.g., 200–500ms) and keep the retry interval at 1s for responsiveness.


71-72: Docstrings/naming still say “all controllers”; now it’s single.

Adjust wording to avoid confusion.

Update: “Initialize ZMQ sockets between storage unit and controller” and “Notify controller that new data is ready.”

Also applies to: 190-197


79-90: Provide explicit close() on manager to prevent ZMQ leaks.

Sockets created here are never closed; add a close() to release resources (and call it from factory/users).

Add outside this block:

def close(self) -> None:
    for sock in (self.controller_handshake_socket, self.data_status_update_socket):
        try:
            if sock:
                sock.setsockopt(zmq.LINGER, 0)
                sock.close()
        except Exception:
            pass
    try:
        if self.zmq_context:
            self.zmq_context.term()
    except Exception:
        pass
tests/test_async_simple_storage_manager.py (1)

140-149: Assert notify_data_update was called.

You already mock notify_data_update; assert it’s awaited to validate the end-to-end put flow.

Add after put_data:

@@
-    await manager.put_data(test_data, batch_meta)
+    await manager.put_data(test_data, batch_meta)
+    manager.notify_data_update.assert_awaited_once()
tests/test_client.py (1)

68-76: Optional: use TransferQueueRole for role consistency.

ZMQServerInfo.role is a role enum elsewhere; using the enum improves consistency in tests.

If convenient:

-from transfer_queue.utils.zmq_utils import (  # noqa: E402
+from transfer_queue.utils.zmq_utils import (  # noqa: E402
     ZMQMessage,
     ZMQRequestType,
     ZMQServerInfo,
 )
+from transfer_queue.utils.utils import TransferQueueRole  # noqa: E402
@@
-        self.zmq_server_info = ZMQServerInfo(
-            role="TransferQueueController",
+        self.zmq_server_info = ZMQServerInfo(
+            role=TransferQueueRole.CONTROLLER,
transfer_queue/client.py (1)

534-556: LGTM: Union type support is well-designed.

The function correctly handles both single handler and dictionary of handlers. The type annotations accurately describe the input and output types.

Consider adding a docstring example to illustrate both usage patterns:

 def process_zmq_server_info(
     handlers: dict[Any, Union["TransferQueueController", "TransferQueueStorageManager", "SimpleStorageUnit"]]
     | Union["TransferQueueController", "TransferQueueStorageManager", "SimpleStorageUnit"],
 ):  # noqa: UP007
     """Extract ZMQ server information from handler objects.

     Args:
         handlers: Dictionary of handler objects (controllers, storage managers, or storage units),
                   or a single handler object

     Returns:
         If handlers is a dictionary: Dictionary mapping handler names to their ZMQ server information
         If handlers is a single object: ZMQ server information for that object
+    
+    Examples:
+        >>> # Single handler
+        >>> controller = TransferQueueController.remote(...)
+        >>> info = process_zmq_server_info(controller)
+        >>> 
+        >>> # Multiple handlers
+        >>> handlers = {"controller": controller, "storage": storage_manager}
+        >>> info_dict = process_zmq_server_info(handlers)
     """
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fc92f03 and 0f8e74a.

📒 Files selected for processing (6)
  • recipe/simple_use_case/async_demo.py (7 hunks)
  • recipe/simple_use_case/sync_demo.py (3 hunks)
  • tests/test_async_simple_storage_manager.py (7 hunks)
  • tests/test_client.py (5 hunks)
  • transfer_queue/client.py (14 hunks)
  • transfer_queue/storage.py (3 hunks)
🔇 Additional comments (9)
recipe/simple_use_case/sync_demo.py (1)

58-65: No issues found—function correctly supports both cases.

The process_zmq_server_info signature already accepts both dict and single objects (lines 534–536). Implementation properly handles both: single objects return ZMQ info directly (line 550), dicts iterate and return mapped info (lines 551–555). Call sites are correct: controller passes single object (line 67), storage units pass dict (line 68).

recipe/simple_use_case/async_demo.py (1)

101-106: ****

The code is correct. process_zmq_server_info() returns a single ZMQServerInfo object when passed a single handler, and AsyncTransferQueueClient.__init__() correctly expects controller_info: ZMQServerInfo (singular). All usages in async_demo.py pass controller_info directly without indexing. No [0] dereferencing occurs.

Likely an incorrect or invalid review comment.

transfer_queue/client.py (7)

69-85: LGTM: Docstring correctly updated for single-controller.

The docstring correctly reflects the change from data_system_controller_infos (plural) to data_system_controller_info (singular), consistent with the single-controller refactor.


88-142: LGTM: Decorator correctly refactored for single controller.

The decorator properly handles the single-controller architecture. The check at line 109 (if not server_info) is defensive programming but would be redundant if the constructor properly validates controller_info (see earlier comment).


144-230: LGTM: Metadata fetching correctly updated for single controller.

All controller references properly updated to use self._controller.id. The method correctly routes requests to the single controller and handles responses appropriately.


336-359: LGTM: Clear operation correctly refactored for single controller.

The clear flow is logical and correct. The check at line 346 is defensive programming but would be redundant if the constructor properly validates controller_info.


361-391: LGTM: Clear metadata retrieval correctly updated.

The method properly routes the clear metadata request to self._controller.id and handles the response appropriately.


393-427: LGTM: Controller metadata clearing correctly updated.

All references to the controller properly updated to use self._controller.id. Error handling and logging are comprehensive.


458-472: LGTM: Synchronous wrapper correctly updated.

The synchronous client wrapper properly passes controller_info to the parent constructor. Note that it inherits the validation issue from the parent constructor (see earlier comment).

Comment thread transfer_queue/client.py Resolved
Comment thread transfer_queue/storage.py Resolved
Comment thread transfer_queue/storage.py Resolved
Comment thread transfer_queue/storage.py
Comment on lines +200 to +214
if not self.controller_info:
logger.warning(f"No controller connected for storage manager {self.storage_manager_id}")
return

# Create zmq poller for notifying data update information
poller = zmq.Poller()

# Connect data status update socket to all controllers
for controller_id, controller_info in self.controller_infos.items():
data_status_update_socket = self.data_status_update_sockets[controller_id]
data_status_update_socket.connect(controller_info.to_addr("data_status_update_socket"))
# Connect data status update socket to controller
self.data_status_update_socket.connect(self.controller_info.to_addr("data_status_update_socket"))
logger.debug(
f"[{self.storage_manager_id}]: Data status update connection from "
f"storage manager id #{self.storage_manager_id} to "
f"controller id #{self.controller_info.id} establish successfully."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Blocking synchronous ZMQ in async method will stall the event loop.

notify_data_update is async but uses sync sockets and blocking poller; this can block the loop up to TQ_DATA_UPDATE_RESPONSE_TIMEOUT seconds.

Two options:

  • Switch to zmq.asyncio sockets and an async poll (preferred).
  • Or wrap the whole notify path in asyncio.to_thread and keep it sync internally.

I can draft either change if you confirm the preferred direction.

Also applies to: 215-227, 253-270

🤖 Prompt for AI Agents
In transfer_queue/storage.py around lines 200-214 (also apply same change to
215-227 and 253-270), the async notify_data_update path uses synchronous pyzmq
sockets and a blocking zmq.Poller which can stall the event loop; replace the
sync ZMQ usage with zmq.asyncio (create an asyncio-compatible Context, use
zmq.asyncio.Socket and zmq.asyncio.Poller methods) and await the
receive/send/poll operations so the function stays fully async, or if you prefer
to keep the sync code, run the entire notify/update path inside
asyncio.to_thread(...) to offload blocking ZMQ calls to a worker thread—update
imports, socket creation, connect/send/recv and poll calls accordingly and
ensure proper socket closing in the chosen async or threaded approach.

Comment thread transfer_queue/storage.py
Comment on lines +229 to +247
self.data_status_update_socket.send(request_msg)
logger.debug(
f"[{self.storage_manager_id}]: Data status update connection from "
f"storage manager id #{self.storage_manager_id} to "
f"controller id #{controller_id} establish successfully."
f"[{self.storage_manager_id}]: Send data status update request "
f"from storage manager id #{self.storage_manager_id} "
f"to controller id #{self.controller_info.id} successfully."
)
except Exception as e:
request_msg = ZMQMessage.create(
request_type=ZMQRequestType.NOTIFY_DATA_UPDATE_ERROR,
sender_id=self.storage_manager_id,
body={
"message": f"Failed to notify data status update information from "
f"storage manager id #{self.storage_manager_id}, "
f"detail error message: {str(e)}"
},
).serialize()

try:
poller.register(data_status_update_socket, zmq.POLLIN)

request_msg = ZMQMessage.create(
request_type=ZMQRequestType.NOTIFY_DATA_UPDATE,
sender_id=self.storage_manager_id,
body={
"fields": fields,
"global_indexes": global_indexes,
"dtypes": dtypes,
"shapes": shapes,
},
).serialize()

data_status_update_socket.send(request_msg)
logger.debug(
f"[{self.storage_manager_id}]: Send data status update request "
f"from storage manager id #{self.storage_manager_id} "
f"to controller id #{controller_id} successfully."
)
except Exception as e:
request_msg = ZMQMessage.create(
request_type=ZMQRequestType.NOTIFY_DATA_UPDATE_ERROR,
sender_id=self.storage_manager_id,
body={
"message": f"Failed to notify data status update information from "
f"storage manager id #{self.storage_manager_id}, "
f"detail error message: {str(e)}"
},
).serialize()

data_status_update_socket.send(request_msg)

# Make sure all controllers successfully receive data status update information.
self.data_status_update_socket.send(request_msg)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Error path re-sends over the same socket and may rethrow; no escalation.

If send failed once, sending an ERROR message on the same socket may fail again; also the outer method still continues to wait for ACK.

  • Wrap the error-send in a best-effort try/except and then abort waiting for ACK (return early).
  • Consider surfacing the failure to callers (raise) so upstream can react.
🤖 Prompt for AI Agents
In transfer_queue/storage.py around lines 229 to 247, the current except handler
re-sends an ERROR message on the same socket (which may also fail) and then lets
the outer method continue waiting for an ACK; change the handler to (1) wrap the
error-send in its own try/except as a best-effort action so a failure to send
the ERROR does not raise, (2) after attempting the best-effort send immediately
abort waiting for the ACK by returning early from the method, and (3) surface
the original failure to callers by re-raising the exception (or raising a
wrapped exception) so upstream can react per guidelines.

Comment thread transfer_queue/storage.py Resolved
Comment thread transfer_queue/storage.py Resolved
Comment thread tests/test_client.py Resolved
@0oshowero0
0oshowero0 merged commit 26b4791 into TransferQueue:dev Oct 29, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants