Skip to content

Conversation

@jthomson04
Copy link
Contributor

@jthomson04 jthomson04 commented Jun 8, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a distributed leader-worker barrier synchronization mechanism for coordinated task execution using etcd.
    • Added a feature flag to enable tests requiring an active etcd server.
  • Tests
    • Added comprehensive asynchronous tests covering synchronization, error handling, and edge cases.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 8, 2025

Walkthrough

A new distributed leader-worker barrier synchronization mechanism using etcd has been introduced. This includes a new feature flag testing-etcd in the runtime crate, a new public module leader_worker_barrier, and its implementation. The mechanism provides leader and worker synchronization primitives with error handling and comprehensive asynchronous tests.

Changes

File(s) Change Summary
lib/runtime/Cargo.toml Added testing-etcd feature flag for tests requiring an active ETCD server.
lib/runtime/src/utils.rs Declared new public module leader_worker_barrier.
lib/runtime/src/utils/leader_worker_barrier.rs Implemented distributed leader-worker barrier using etcd; added structs, error enum, async methods, and tests.

Sequence Diagram(s)

sequenceDiagram
    participant Leader as LeaderBarrier
    participant Etcd as etcd
    participant Worker as WorkerBarrier

    Leader->>Etcd: Publish barrier data under barrier_id
    loop For each worker
        Worker->>Etcd: Wait for barrier data
        Worker->>Etcd: Register worker under barrier_id/workers/worker_id
    end
    Etcd-->>Leader: Notify when all workers have registered
    Leader->>Etcd: Signal completion or abort
    Worker->>Etcd: Wait for completion or abort signal
    Etcd-->>Worker: Return barrier result or error
Loading

Poem

In the warren of code, a new barrier stands tall,
With leader and worker, it synchronizes all.
Etcd is the burrow where rabbits now meet,
Awaiting each signal, their mission complete.
With features and modules, the changes are neat—
Distributed and tested, this hop can't be beat!
🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
lib/runtime/src/utils.rs (1)

18-19: Consider feature-gating the new module

leader_worker_barrier depends on the etcd transport. Compiling the crate without an ETCD backend will now always pull those deps in.
If “no-etcd” builds are still a supported target, guard the module behind the same feature that includes the transport, e.g.

#[cfg(feature = "etcd")]
pub mod leader_worker_barrier;

and re-export conditionally from root lib.rs.

lib/runtime/src/utils/leader_worker_barrier.rs (2)

81-90: Unchecked UTF-8 conversion may panic

kv.key_str().unwrap() will panic if the key contains non-UTF-8 bytes. Prefer graceful handling:

-let key = kv.key_str().unwrap().to_string();
+let key = String::from_utf8_lossy(kv.key()).into_owned();

(or propagate an error).


120-123: Avoid unwrap() in library code

serde_json::to_vec(&()).unwrap() cannot fail today but using expect("serialize unit") (or proper error propagation) avoids panics if upstream behaviour changes.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9281c95 and 5fa1d45.

📒 Files selected for processing (3)
  • lib/runtime/Cargo.toml (1 hunks)
  • lib/runtime/src/utils.rs (1 hunks)
  • lib/runtime/src/utils/leader_worker_barrier.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: pre-merge-rust (lib/runtime/examples)
  • GitHub Check: pre-merge-rust (lib/bindings/python)
  • GitHub Check: pre-merge-rust (.)
  • GitHub Check: Build and Test - vllm
🔇 Additional comments (2)
lib/runtime/Cargo.toml (1)

30-31: Feature naming & CI gating check

testing-etcd is introduced correctly, but make sure:

  1. CI pipelines activate this feature only when an ETCD instance is available; otherwise tests will silently be skipped.
  2. If you ever merge a non-test feature set that doesn’t pull in etcd-client, consider wrapping this feature behind a wider etcd/distributed feature to avoid unconditional compilation.

No code change required, just double-check the pipeline configuration.

lib/runtime/src/utils/leader_worker_barrier.rs (1)

314-323: Race condition when complete appears before worker key

If the leader finishes extremely quickly, complete may be written before the worker registration succeeds, yielding AlreadyCompleted.
Document this behaviour or consider retrying registration until either:

  1. registration succeeds, or
  2. the barrier is already completed with a matching worker set.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
lib/runtime/src/utils/leader_worker_barrier.rs (1)

105-112: Do not collapse every kv_create failure into BarrierIdNotUnique.

The TODO is still unresolved – all ETCD errors are mapped to BarrierIdNotUnique, masking network/auth failures and making troubleshooting impossible. Please inspect the returned error and convert only “already-exists” cases, propagating everything else as EtcdError (or a dedicated variant).

🧹 Nitpick comments (2)
lib/runtime/src/utils/leader_worker_barrier.rs (2)

81-85: Avoid unwrap() on possibly non-UTF-8 ETCD keys.

kv.key_str().unwrap() will panic if a rogue client writes non-UTF-8 keys under the same prefix. Convert the error into EtcdError instead:

-            let key = kv.key_str().unwrap().to_string();
+            let key = kv
+                .key_str()
+                .map(|s| s.to_owned())
+                .map_err(|e| LeaderWorkerBarrierError::EtcdError(e.into()))?;

60-67: Use tokio::time::timeout instead of re-creating a long sleep each loop.

Recomputing remaining_time and spawning a full-length sleep on every iteration is wasteful and makes the select harder to read. A cleaner pattern:

-        tokio::select! {
-            Some(watch_event) = rx.recv() => { … }
-            _ = tokio::time::sleep(remaining_time) => { /* timeout */ }
-        }
+        let recv = tokio::time::timeout(remaining_time, rx.recv());
+        match recv.await {
+            Ok(Some(watch_event)) => handle_watch_event(watch_event, &mut data)?,
+            Ok(None)             => return Err(LeaderWorkerBarrierError::EtcdError(anyhow::anyhow!("watch closed"))),
+            Err(_)               => {/* timed out, loop and check elapsed */},
+        }

Improves readability and removes the needless cancellation of the sleep future on every event.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5fa1d45 and b9ae957.

📒 Files selected for processing (3)
  • lib/runtime/Cargo.toml (1 hunks)
  • lib/runtime/src/utils.rs (1 hunks)
  • lib/runtime/src/utils/leader_worker_barrier.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • lib/runtime/src/utils.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/runtime/Cargo.toml
🧰 Additional context used
🧠 Learnings (1)
lib/runtime/src/utils/leader_worker_barrier.rs (1)
Learnt from: jthomson04
PR: ai-dynamo/dynamo#1429
File: lib/runtime/src/utils/leader_worker_barrier.rs:69-72
Timestamp: 2025-06-08T03:12:03.964Z
Learning: In the leader-worker barrier implementation in lib/runtime/src/utils/leader_worker_barrier.rs, the `wait_for_key_count` function correctly uses exact equality (`==`) instead of greater-than-or-equal (`>=`) because worker IDs must be unique (enforced by etcd create-only operations), ensuring exactly the expected number of workers can register.
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: pre-merge-rust (lib/runtime/examples)
  • GitHub Check: pre-merge-rust (lib/bindings/python)
  • GitHub Check: Build and Test - vllm
  • GitHub Check: pre-merge-rust (.)

@jthomson04 jthomson04 merged commit 74b858f into main Jun 9, 2025
13 of 14 checks passed
@jthomson04 jthomson04 deleted the jthomson04/leader-worker-sync branch June 9, 2025 17:39
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.

3 participants