Skip to content

Prioritize shutdown in wait_or_shutdown select#123

Merged
leynos merged 1 commit intomainfrom
issue-87-prioritize-shutdown-when-both-events-ready
Dec 24, 2025
Merged

Prioritize shutdown in wait_or_shutdown select#123
leynos merged 1 commit intomainfrom
issue-87-prioritize-shutdown-when-both-events-ready

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Dec 24, 2025

Add biased; directive to the tokio::select! macro and reorder the arms so the shutdown branch is checked first. This ensures that when both the sleep timer and shutdown signal are ready simultaneously, shutdown is always selected, providing more responsive graceful shutdown behaviour.

Fixes #87

🤖 Generated with Claude Code

Summary by Sourcery

Enhancements:

  • Ensure the worker wait_or_shutdown helper always prefers the shutdown signal when both the shutdown and sleep branches are ready.

Add `biased;` directive to the tokio::select! macro and reorder the
arms so the shutdown branch is checked first. This ensures that when
both the sleep timer and shutdown signal are ready simultaneously,
shutdown is always selected, providing more responsive graceful
shutdown behaviour.

Fixes #87

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Dec 24, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Makes the worker wait_or_shutdown helper prefer reacting to shutdown signals over completing its sleep delay by using a biased tokio::select! with the shutdown branch first.

Sequence diagram for biased wait_or_shutdown shutdown prioritization

sequenceDiagram
    actor Worker
    participant WaitOrShutdown
    participant ShutdownSignal
    participant Timer

    Worker->>WaitOrShutdown: wait_or_shutdown(secs, shutdown)
    WaitOrShutdown->>Timer: start sleep(secs)
    WaitOrShutdown->>ShutdownSignal: listen for changed()

    rect rgb(230,230,255)
        note over WaitOrShutdown: tokio::select! with biased and shutdown branch first
        alt shutdown signal becomes ready (possibly with timer also ready)
            ShutdownSignal-->>WaitOrShutdown: changed() ready
            Timer-->>WaitOrShutdown: sleep may also be ready
            WaitOrShutdown-->>Worker: return due to shutdown
        else only timer becomes ready
            Timer-->>WaitOrShutdown: sleep finished
            WaitOrShutdown-->>Worker: return due to timeout
        end
    end
Loading

State diagram for worker wait_or_shutdown behavior

stateDiagram-v2
    [*] --> Waiting

    state Waiting {
        [*] --> Pending
        Pending --> ShuttingDown: shutdown.changed ready
        Pending --> TimedOut: sleep finished
    }

    ShuttingDown --> [*]
    TimedOut --> [*]
Loading

File-Level Changes

Change Details Files
Ensure wait_or_shutdown always prioritizes the shutdown signal when both the sleep timer and shutdown notification are ready.
  • Add the biased; directive to the tokio::select! in wait_or_shutdown so branch evaluation order is deterministic.
  • Reorder the select branches so shutdown.changed() is evaluated before the sleep future, guaranteeing graceful shutdown wins over timeout when both are ready.
crates/comenqd/src/worker.rs

Assessment against linked issues

Issue Objective Addressed Explanation
#87 Modify wait_or_shutdown in crates/comenqd/src/worker.rs so that the tokio::select! is biased toward shutdown, always preferring the shutdown branch when both the sleep timer and shutdown signal are ready in the same tick.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 24, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved worker timeout and shutdown signal handling to optimise operation scheduling during concurrent scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Modify WorkerHooks::wait_or_shutdown to prioritise shutdown signals over timeout expiry. Add biased; directive to the tokio::select! macro and reorder the arms so shutdown is evaluated first, ensuring shutdown is selected when both futures are ready concurrently.

Changes

Cohort / File(s) Summary
Shutdown prioritisation
crates/comenqd/src/worker.rs
Add biased; directive and reorder tokio::select! arms to evaluate shutdown signal before sleep timeout, preferring shutdown when both branches are ready simultaneously

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Possibly related issues

Poem

⚡ When futures race to be embraced,
Shutdown now wins the favoured place—
With biased; guard and reordered cheer,
Graceful exit draws most near! 🛑

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title accurately reflects the main change: adding bias to prioritise shutdown in the wait_or_shutdown select macro.
Description check ✅ Passed The description is directly related to the changeset, clearly explaining the addition of the biased directive and reordering to prioritise shutdown in the tokio::select! macro.
Linked Issues check ✅ Passed The code changes align with the requirements in issue #87: adding biased; and reordering the tokio::select! arms so the shutdown branch is evaluated first.
Out of Scope Changes check ✅ Passed All changes are scoped to the stated objective of prioritising shutdown in the wait_or_shutdown function; no unrelated modifications are present.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch issue-87-prioritize-shutdown-when-both-events-ready

📜 Recent review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8df915c and e51262f.

📒 Files selected for processing (1)
  • crates/comenqd/src/worker.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Every module must begin with a module level (//! ) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Use rstest fixtures for shared setup.
Replace duplicated tests with #[rstest(...)] parameterised cases.
Prefer mockall for mocks/stubs.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums. Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary. Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library. Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • crates/comenqd/src/worker.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cognitive complexity of functions no more than 9.

  • Adhere to single responsibility and CQRS
  • Place function attributes after doc comments.
  • Do not use return in single-line functions.
  • Move conditionals with >2 branches into a predicate function.
  • Avoid unsafe unless absolutely necessary.
  • Every module must begin with a //! doc comment that explains the module's purpose and utility.
  • Comments and docs must follow en-GB-oxendict (-ize / -yse / -our) spelling and grammar
  • Lints must not be silenced except as a last resort.
    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.
  • Replace duplicated tests with #[rstest(...)] parameterised cases.
  • Prefer mockall for mocks/stubs.
  • Prefer .expect() over .unwrap() in tests.
  • .expect() and .unwrap() are forbidden outside of tests. Errors must be propagated.
  • Ensure that any API or behavioural changes are reflected in the documentation in docs/
  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/
  • Files must not exceed 400 lines in length
    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such
    • For testing of functionality depending upon environment variables, dependency injection and...

Files:

  • crates/comenqd/src/worker.rs
🔍 Remote MCP

Let me search for more specific information about the tokio::select! macro and the biased directive to help evaluate the PR:Based on the comprehensive context I've gathered, here's a concise summary of relevant context for reviewing this PR:

PR Review Context Summary

System Architecture Context

The comenq system is a GitHub comment management service with a client-daemon architecture. The daemon implements a three-task concurrent architecture using tokio::spawn with tasks for handling socket connections (run_listener), queue operations (queue_writer), and processing requests (run_worker).

Change Location and Scope

The PR modifies the daemon's task coordination logic. The run_worker function implements an infinite loop that dequeues comment requests, attempts to post them to GitHub, then enforces a cooldown period using tokio::time::sleep.

Current Behavior and Issue

The issue (#87) describes that tokio::select! in wait_or_shutdown does not bias toward shutdown; if sleep and shutdown are ready simultaneously, selection is arbitrary. This can cause delays in graceful shutdown when both a timeout and shutdown signal are ready at the same time.

Proposed Solution Analysis

The PR implements two key changes:

  1. Adds biased; directive - This tells tokio::select! to check branches in declaration order instead of using fair random selection
  2. Reorders branches - Places the shutdown branch before the sleep branch, ensuring it's checked first when both are ready

Related System Context

The daemon uses tokio::select! to monitor task completion and coordinate shutdown, with the main run function using tokio::select! to detect if either listener or worker tasks exit unexpectedly. When either critical task exits, the tokio::select! block will detect it and log an error, then initiate a shutdown sequence.

Rate Limiting Context

The daemon enforces rate limiting through a fixed cooldown period after each request attempt using tokio::time::sleep, with the cooldown applied regardless of request outcome to provide consistent rate limiting.

Code Quality Considerations

The project enforces strict code quality through Clippy linting rules including panic prevention with unwrap_used restrictions, error handling requirements using semantic error enums with thiserror, and comprehensive test coverage with both unit tests and behavioral validation.

⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (2)
crates/comenqd/src/worker.rs (2)

123-129: AI summary incorrectly describes the change.

The AI-generated summary claims "the sleep branch to be chosen first" and that "shutdown signals may be deprioritized", but this is backwards. With biased; and the shutdown branch declared first (line 126), shutdown is prioritized when both futures are ready concurrently. The summary also incorrectly states that a sleep branch is being added; in reality, only the biased; directive is new.

The actual behavior: when both shutdown.changed() and the sleep timer are ready, the biased select! will check the shutdown branch first and select it, ensuring immediate shutdown responsiveness—exactly as intended by issue #87.


124-128: Implementation correctly prioritizes shutdown.

The addition of biased; with the shutdown branch first ensures that when both the sleep timer and shutdown signal are ready simultaneously, shutdown is selected. This directly addresses issue #87's requirement for immediate shutdown responsiveness.

Verify that behavioral tests exist to confirm the biased shutdown priority. The coding guidelines mandate tests for functionality changes, and this alters the selection behavior from fair (random) to deterministic (shutdown-first).

#!/bin/bash
# Description: Find tests for wait_or_shutdown and check if biased behavior is tested.

# Search for test functions covering wait_or_shutdown
rg -n --type rust -A 20 '#\[.*test.*\]' | rg -C 10 'wait_or_shutdown'

# Search for test modules in worker test files
fd -e rs -p 'worker.*test' --exec cat {}

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

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Dec 24, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 24, 2025

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

@leynos leynos merged commit 2d80375 into main Dec 24, 2025
2 of 3 checks passed
@leynos leynos deleted the issue-87-prioritize-shutdown-when-both-events-ready branch December 24, 2025 01:09
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.

Prioritise shutdown when both events are ready in wait_or_shutdown

1 participant