Repository navigation
refactor: refactor TransferQueue client and storage manager to use a single controller. - #89
Conversation
…single controller. Signed-off-by: jianjunzhong <[email protected]>
There was a problem hiding this comment.
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) tocontroller_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.
…bjects Signed-off-by: jianjunzhong <[email protected]>
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughRefactored 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
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Areas requiring extra attention:
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
Comment |
Signed-off-by: jianjunzhong <[email protected]>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
1 similar comment
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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: passtests/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
📒 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_infosignature 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 singleZMQServerInfoobject when passed a single handler, andAsyncTransferQueueClient.__init__()correctly expectscontroller_info: ZMQServerInfo(singular). All usages in async_demo.py passcontroller_infodirectly 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) todata_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 validatescontroller_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.idand 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_infoto the parent constructor. Note that it inherits the validation issue from the parent constructor (see earlier comment).
| 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." | ||
| ) | ||
|
|
There was a problem hiding this comment.
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.
| 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) | ||
|
|
There was a problem hiding this comment.
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.
Signed-off-by: jianjunzhong <[email protected]>
Summary by CodeRabbit
Release Notes
Refactor
Configuration Updates
Tests