Skip to content

Refactor listener binding and tighten address tests#304

Merged
leynos merged 4 commits intomainfrom
codex/refactor-listener-logic-in-tests
Aug 12, 2025
Merged

Refactor listener binding and tighten address tests#304
leynos merged 4 commits intomainfrom
codex/refactor-listener-logic-in-tests

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 11, 2025

Summary

  • rename bind_listener to bind_existing_listener for clarity
  • add helpers for listener address and free port
  • assert bound ports and both addresses in server config tests

Testing

  • make fmt
  • make lint
  • make test

https://chatgpt.com/codex/tasks/task_e_6899c7dbc43c8322942d5a7d90e7cf04

Summary by Sourcery

Refactor listener binding API to clarify existing listener binding, introduce test utilities for listener addresses, and strengthen address assertions in server tests

New Features:

  • Add listener_addr utility to extract a listener's bound SocketAddr
  • Add free_addr utility to reserve a free port and return its address

Enhancements:

  • Rename bind_listener to bind_existing_listener throughout the server API and codebase

Documentation:

  • Update documentation comments to reference bind_existing_listener

Tests:

  • Tighten server config tests to assert full socket address equality
  • Update tests across modules to use listener_addr, free_addr, and bind_existing_listener

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 11, 2025

Reviewer's Guide

Renames the binding API from bind_listener to bind_existing_listener, introduces listener_addr and free_addr test utilities, and updates tests to leverage these helpers and perform strict SocketAddr equality checks.

Class diagram for updated WireframeServer binding API

classDiagram
    class WireframeServer {
        +bind(addr: SocketAddr): Result<WireframeServer, ServerError>
        +bind_existing_listener(std: StdTcpListener): Result<WireframeServer, ServerError>
    }
    class ServerError
    class StdTcpListener
    WireframeServer --> ServerError
    WireframeServer --> StdTcpListener
Loading

Class diagram for new test utilities: listener_addr and free_addr

classDiagram
    class TestUtil {
        +listener_addr(listener: StdTcpListener): SocketAddr
        +free_addr(): SocketAddr
    }
    TestUtil --> StdTcpListener
    TestUtil --> SocketAddr
Loading

File-Level Changes

Change Details Files
Refactor binding API by renaming bind_listener to bind_existing_listener
  • Rename method definitions in binding module
  • Update all bind_listener invocations in server implementation and docs
  • Adjust test call sites to use bind_existing_listener
src/server/config/binding.rs
src/server/mod.rs
src/server/config/mod.rs
src/server/connection.rs
src/server/runtime.rs
src/server/config/tests.rs
tests/preamble.rs
tests/server.rs
tests/world.rs
Add listener_addr and free_addr test utilities
  • Implement listener_addr to extract a listener's bound SocketAddr
  • Implement free_addr to reserve and release a free local port
  • Annotate helpers with cfg_attr and must_use
src/server/test_util.rs
Tighten address assertions in server config tests
  • Replace manual local_addr retrieval with listener_addr
  • Use free_addr for second address in multi-bind test
  • Assert equality of full SocketAddr instead of only IP
src/server/config/tests.rs

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 Aug 11, 2025

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.

Summary by CodeRabbit

  • New Features

    • None.
  • Refactor

    • Renamed the public server binding method from bind_listener to bind_existing_listener. Behaviour unchanged. Update your code to use bind_existing_listener when providing a pre-created listener. The bind(addr) flow is unaffected.
  • Documentation

    • Updated references and examples to the new method name.
  • Tests

    • Updated usages to the new API.
    • Added test utilities for obtaining a listener’s address and reserving a free port.

Walkthrough

Rename WireframeServer's builder method from bind_listener to bind_existing_listener across server config, runtime and tests. Update docs and examples to the new name. Add test utilities free_addr and listener_addr. No behavioural or control-flow changes.

Changes

Cohort / File(s) Summary
Binding API rename (core)
src/server/config/binding.rs, src/server/runtime.rs
Rename public builder method bind_listener(...)bind_existing_listener(...); preserve parameters, return types and behaviour.
Docs updates
src/server/config/mod.rs, src/server/mod.rs
Update doc comments and examples to reference bind_existing_listener; no code logic changes.
Test utilities
src/server/test_util.rs
Add free_addr() and listener_addr(...) helpers; switch bind_server helper to use bind_existing_listener(...).
Tests and internal usages
src/server/config/tests.rs, src/server/connection.rs, tests/preamble.rs, tests/server.rs, tests/world.rs
Replace bind_listener(...) calls with bind_existing_listener(...); adjust tests to use new helpers and compare full SocketAddr where applicable.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Poem

Rename the hook, keep traffic the same,
Listeners hum, unchanged in their game.
free_addr finds ports, listener_addr shows,
Tests adjust paths where the new name goes.
bind_existing_listener wears the new name with pride.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2ac8484 and 6c86c54.

📒 Files selected for processing (2)
  • src/server/config/tests.rs (6 hunks)
  • src/server/test_util.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Use precise names; boolean names should start with is/has/should
Use en-GB-oxendict spelling and grammar in comments
Function documentation must include clear examples; test documentation should omit redundant examples
Keep code files ≤ 400 lines; split long switch/dispatch logic by feature; move large test data to external files
Disallow Clippy warnings
Fix warnings emitted during tests in code rather than silencing them
Extract helper functions for long functions; adhere to separation of concerns and CQRS
Group related parameters into meaningful structs when functions have many parameters
Consider using Arc for large error returns to reduce data size
Each Rust module must begin with a module-level //! comment describing purpose and utility
Document public APIs with Rustdoc /// comments to enable cargo doc generation
Prefer immutable data; avoid unnecessary mut
Handle errors with Result instead of panicking where feasible
Avoid unsafe code unless 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
Do not silence lints except as a last resort
Lint suppressions must be tightly scoped and include a clear reason
Prefer #[expect(..)] over #[allow(..)] for lints
Prefer .expect() over .unwrap()
Use concat!() to combine long string literals rather than escaping newlines
Prefer single-line function bodies where appropriate (e.g., pub fn new(id: u64) -> Self { Self(id) })
Prefer semantic error enums deriving std::error::Error via thiserror for inspectable conditions

Files:

  • src/server/test_util.rs
  • src/server/config/tests.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • 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 / -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()

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

Files:

  • src/server/test_util.rs
  • src/server/config/tests.rs
{src,tests}/**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

Write unit and behavioural tests for new functionality

Files:

  • src/server/test_util.rs
  • src/server/config/tests.rs
🧬 Code Graph Analysis (2)
src/server/test_util.rs (4)
src/server/config/tests.rs (2)
  • WireframeServer (61-61)
  • WireframeServer (140-142)
tests/preamble.rs (2)
  • WireframeServer (56-58)
  • WireframeServer (268-272)
src/server/config/mod.rs (1)
  • new (67-78)
src/server/config/binding.rs (2)
  • local_addr (37-37)
  • local_addr (121-121)
src/server/config/tests.rs (2)
src/server/test_util.rs (5)
  • listener_addr (74-78)
  • free_listener (32-35)
  • WireframeServer (94-94)
  • factory (23-25)
  • bind_server (80-87)
src/server/config/binding.rs (2)
  • local_addr (37-37)
  • local_addr (121-121)
🔍 MCP Research (1 server)

Deepwiki:

⏰ 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: build-test
🔇 Additional comments (4)
src/server/test_util.rs (2)

85-85: Excellent API clarity improvement!

The rename from bind_listener to bind_existing_listener significantly improves the API's expressiveness and aligns with the external documentation noting that the listener field is optional.


97-121: Excellent test coverage for the new utilities!

The tests properly validate that free_addr uses localhost, listener_addr matches the underlying socket address, and server_with_preamble correctly returns an unbound server. This provides good confidence in the utility functions.

src/server/config/tests.rs (2)

71-77: Excellent test precision improvement!

The test now uses listener_addr to derive the expected address and compares full SocketAddr values rather than just checking existence. This aligns perfectly with the PR objective to "tighten server configuration tests to assert full socket address equality".


73-73: Consistent API migration to bind_existing_listener.

All test cases correctly migrate from bind_listener to bind_existing_listener, maintaining consistency across the test suite.

Also applies to: 85-85, 151-151, 166-166, 190-190

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/refactor-listener-logic-in-tests

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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
Copy Markdown
Contributor

@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 @leynos - I've reviewed your changes - here's some feedback:

  • Dropping the temporary listener immediately in free_addr can lead to port‐collision race conditions in CI; consider returning the listener itself or holding it open until you actually bind to it to reduce flakiness.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- To ease the transition for downstream consumers, consider keeping a `bind_listener` alias marked `#[deprecated]` that forwards to `bind_existing_listener` rather than removing it outright.
- Dropping the temporary listener immediately in `free_addr` can lead to port‐collision race conditions in CI; consider returning the listener itself or holding it open until you actually bind to it to reduce flakiness.

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.

Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

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

10 files reviewed, no comments

Edit Code Review Bot Settings | Greptile

Copy link
Copy Markdown
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: 5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b172b34 and 2ac8484.

📒 Files selected for processing (10)
  • src/server/config/binding.rs (4 hunks)
  • src/server/config/mod.rs (2 hunks)
  • src/server/config/tests.rs (6 hunks)
  • src/server/connection.rs (1 hunks)
  • src/server/mod.rs (1 hunks)
  • src/server/runtime.rs (1 hunks)
  • src/server/test_util.rs (1 hunks)
  • tests/preamble.rs (1 hunks)
  • tests/server.rs (1 hunks)
  • tests/world.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Use precise names; boolean names should start with is/has/should
Use en-GB-oxendict spelling and grammar in comments
Function documentation must include clear examples; test documentation should omit redundant examples
Keep code files ≤ 400 lines; split long switch/dispatch logic by feature; move large test data to external files
Disallow Clippy warnings
Fix warnings emitted during tests in code rather than silencing them
Extract helper functions for long functions; adhere to separation of concerns and CQRS
Group related parameters into meaningful structs when functions have many parameters
Consider using Arc for large error returns to reduce data size
Each Rust module must begin with a module-level //! comment describing purpose and utility
Document public APIs with Rustdoc /// comments to enable cargo doc generation
Prefer immutable data; avoid unnecessary mut
Handle errors with Result instead of panicking where feasible
Avoid unsafe code unless 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
Do not silence lints except as a last resort
Lint suppressions must be tightly scoped and include a clear reason
Prefer #[expect(..)] over #[allow(..)] for lints
Prefer .expect() over .unwrap()
Use concat!() to combine long string literals rather than escaping newlines
Prefer single-line function bodies where appropriate (e.g., pub fn new(id: u64) -> Self { Self(id) })
Prefer semantic error enums deriving std::error::Error via thiserror for inspectable conditions

Files:

  • src/server/connection.rs
  • src/server/config/mod.rs
  • tests/server.rs
  • src/server/mod.rs
  • tests/preamble.rs
  • src/server/runtime.rs
  • src/server/config/binding.rs
  • tests/world.rs
  • src/server/test_util.rs
  • src/server/config/tests.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • 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 / -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()

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

Files:

  • src/server/connection.rs
  • src/server/config/mod.rs
  • tests/server.rs
  • src/server/mod.rs
  • tests/preamble.rs
  • src/server/runtime.rs
  • src/server/config/binding.rs
  • tests/world.rs
  • src/server/test_util.rs
  • src/server/config/tests.rs
{src,tests}/**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

Write unit and behavioural tests for new functionality

Files:

  • src/server/connection.rs
  • src/server/config/mod.rs
  • tests/server.rs
  • src/server/mod.rs
  • tests/preamble.rs
  • src/server/runtime.rs
  • src/server/config/binding.rs
  • tests/world.rs
  • src/server/test_util.rs
  • src/server/config/tests.rs
tests/**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

tests/**/*.rs: Use rstest fixtures for shared setup
Replace duplicated tests with #[rstest(...)] parameterised cases
Prefer mockall for mocks/stubs

Files:

  • tests/server.rs
  • tests/preamble.rs
  • tests/world.rs
🧬 Code Graph Analysis (3)
src/server/connection.rs (1)
src/server/test_util.rs (1)
  • free_listener (32-35)
src/server/runtime.rs (1)
src/server/test_util.rs (1)
  • free_listener (32-35)
src/server/config/tests.rs (2)
src/server/test_util.rs (6)
  • free_addr (75-80)
  • free_listener (32-35)
  • listener_addr (53-57)
  • WireframeServer (100-100)
  • factory (23-25)
  • bind_server (82-89)
src/server/config/binding.rs (2)
  • local_addr (37-37)
  • local_addr (121-121)
🔍 MCP Research (1 server)

Deepwiki:

⏰ 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: build-test
🔇 Additional comments (16)
src/server/mod.rs (1)

70-71: Documentation correctly updated to reflect API rename.

The documentation update appropriately reflects the rename from bind_listener to bind_existing_listener, maintaining consistency with the codebase-wide API changes.

src/server/config/mod.rs (1)

8-9: Documentation updates align with API rename.

The documentation correctly references both bind and bind_existing_listener methods, maintaining accurate API documentation following the rename.

Also applies to: 55-55

src/server/config/binding.rs (4)

59-59: Method call updated to use renamed API.

The internal call correctly uses the renamed bind_existing_listener method, maintaining consistency with the API changes.


80-83: API rename implemented correctly for Unbound state.

The method rename from bind_listener to bind_existing_listener maintains the same signature and functionality whilst providing clearer naming semantics.


145-145: Internal method call updated appropriately.

The call to the renamed bind_existing_listener method maintains consistency with the API changes.


168-182: API rename implemented correctly for Bound state.

The method rename maintains identical functionality whilst improving API clarity. The implementation correctly preserves all existing behaviour.

src/server/connection.rs (1)

170-170: Test updated to use renamed API method.

The test correctly uses the renamed bind_existing_listener method, maintaining test functionality whilst aligning with the API changes.

tests/preamble.rs (1)

72-72: Test correctly updated to use renamed API.

The test appropriately uses the renamed bind_existing_listener method, maintaining test functionality whilst reflecting the API changes.

src/server/runtime.rs (1)

276-276: Test updated appropriately to use renamed API.

The test correctly uses the renamed bind_existing_listener method, maintaining test functionality whilst aligning with the API refactoring.

tests/world.rs (1)

42-42: Test infrastructure correctly updated to use renamed API.

The test appropriately uses the renamed bind_existing_listener method, preserving test functionality whilst reflecting the API changes.

tests/server.rs (1)

45-45: Test correctly uses renamed API method.

The test appropriately uses the renamed bind_existing_listener method, maintaining test functionality for readiness receiver verification whilst aligning with the API changes.

src/server/config/tests.rs (4)

23-26: Import the new test helpers; alignment is correct.

Import free_addr and listener_addr to centralise address handling in tests. This removes ad hoc local_addr calls and improves readability.


72-79: Assert the exact bound SocketAddr and use the renamed API.

Derive expected via listener_addr and assert full equality with local_addr. Prefer expect over unwrap is already observed here. Good tightening per Deepwiki guidance.


150-151: Use bind_existing_listener in method chaining.

Update is correct and preserves chaining semantics.


165-166: Persist configuration via bind_existing_listener.

Rename is correctly applied; behaviour remains unchanged.

src/server/test_util.rs (1)

87-88: Update bind_server to use bind_existing_listener.

Rename is correctly applied; helper remains a thin, test-focused convenience.

Comment thread src/server/config/tests.rs
Comment thread src/server/config/tests.rs
Comment thread src/server/test_util.rs
Comment thread src/server/test_util.rs Outdated
Comment thread src/server/test_util.rs Outdated
Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

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

2 files reviewed, 1 comment

Edit Code Review Bot Settings | Greptile

Comment thread src/server/config/tests.rs Outdated
Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

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

2 files reviewed, 1 comment

Edit Code Review Bot Settings | Greptile

Comment thread src/server/test_util.rs Outdated
Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

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

1 file reviewed, no comments

Edit Code Review Bot Settings | Greptile

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Aug 12, 2025

@coderabbitai Has the following now been resolved?

Dropping the temporary listener immediately in free_addr can lead to port‐collision race conditions in CI; consider returning the listener itself or holding it open until you actually bind to it to reduce flakiness.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 12, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@leynos I need to understand what specific issues you're referring to when you ask about "the following." I don't see the list of items you're mentioning in the current context.

Could you please clarify what specific concerns or issues you'd like me to check the resolution status for? This will help me provide you with an accurate assessment.


🏁 Script executed:

#!/bin/bash
# Search for any previous review comments or issues in the PR
gh pr view 304 --comments --json comments,reviews | jq '.reviews[].body, .comments[].body' | grep -v null

Length of output: 43462


🏁 Script executed:

#!/bin/bash
# Check the current implementation of free_addr function
cat src/server/test_util.rs

Length of output: 3340


@leynos No, the race condition issue in free_addr has not been resolved.

Looking at the current implementation in src/server/test_util.rs on line 45:

pub fn free_addr() -> SocketAddr { listener_addr(&free_listener()) }

This still follows the problematic pattern:

  1. free_listener() creates a temporary TcpListener bound to a free port
  2. listener_addr() extracts the socket address from that listener
  3. The temporary listener is immediately dropped when the function returns
  4. The address is returned for later binding

The documentation even acknowledges this race condition on lines 41-43:

/// Creates a temporary listener to obtain an ephemeral port, then immediately
/// drops it so the port may be rebound. This is inherently subject to a
/// time-of-check/time-of-use race; only use in tests.

The race condition window still exists between dropping the temporary listener and when the caller attempts to bind to the returned address. In CI environments, another process could claim that port during this window, leading to test flakiness.

To resolve this, you'd need to either:

  • Return the TcpListener itself instead of just its address
  • Modify the calling pattern to hold the listener open until binding

🐰 ears droop slightly

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 12, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

I need to examine the current implementation of the free_addr function to see if the race condition issue has been addressed.

Based on my examination of the code, no, this issue has not been resolved.

Looking at the current implementation in src/server/test_util.rs, the free_addr() function still exhibits the same problematic pattern:

pub fn free_addr() -> SocketAddr {
    let listener = StdTcpListener::bind("localhost:0").expect("Failed to bind to free port");
    let addr = listener_addr(&listener);
    drop(listener); // <- This is the problem!
    addr
}

The function still:

  1. Creates a temporary listener
  2. Captures its address
  3. Immediately drops the listener
  4. Returns just the address

This creates exactly the race condition you mentioned - between the time the listener is dropped and when the returned address is used to bind a new listener, another process could potentially grab that same port.

Your original suggestion to either return the listener itself or hold it open until binding would indeed resolve this race condition. A safer approach would be:

// Option 1: Return the listener instead of just the address
pub fn free_listener() -> StdTcpListener {
    StdTcpListener::bind("localhost:0").expect("Failed to bind to free port")
}

// Option 2: Keep existing function but document the race condition risk

The current implementation maintains the race condition vulnerability in CI environments where port reuse can happen quickly.


🏁 Script executed:

#!/bin/bash
# Let's look at the current implementation of free_addr in test_util.rs
cat src/server/test_util.rs

Length of output: 3340


🏁 Script executed:

#!/bin/bash
# Let's also see how free_addr is being used in the tests to understand the usage pattern
rg "free_addr" -A 3 -B 1

Length of output: 908


@leynos No, this issue has not been resolved.

Looking at the current implementation, the race condition still exists in free_addr():

pub fn free_addr() -> SocketAddr { listener_addr(&free_listener()) }

While the implementation has changed slightly (it now calls free_listener() and extracts the address), the fundamental problem remains: the temporary listener returned by free_listener() is immediately dropped when the expression completes, creating the same time-of-check/time-of-use race condition you identified.

However, I notice the codebase has introduced a solution: the free_listener() fixture that returns a bound TcpListener:

#[fixture]
/// Returns a bound [`TcpListener`] on a free port for use in tests.
///
/// Keeping the listener bound prevents race conditions where another
/// process could claim the port between discovery and use.
pub fn free_listener() -> StdTcpListener {
    let addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0);
    StdTcpListener::bind(addr).expect("Failed to bind free port listener")
}

The documentation even explicitly mentions that keeping the listener bound prevents race conditions. To fully resolve the issue, tests should use free_listener() instead of free_addr() where possible, since it keeps the port reserved until the listener is actually used.

The free_addr() function acknowledges the race condition in its documentation but continues to exist for cases where only the address is needed, accepting the inherent race condition risk.

@leynos leynos merged commit d60bb20 into main Aug 12, 2025
5 checks passed
@leynos leynos deleted the codex/refactor-listener-logic-in-tests branch August 12, 2025 08:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant