Skip to content

Implement panic handling improvements#215

Closed
leynos wants to merge 4 commits intomainfrom
26xd2p-codex/implement-advanced-error-handling
Closed

Implement panic handling improvements#215
leynos wants to merge 4 commits intomainfrom
26xd2p-codex/implement-advanced-error-handling

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 26, 2025

Summary

  • include connection address in panic logs for easier debugging
  • allow compatible updates for cucumber dev dependency
  • refactor panic scenario world with helper methods
  • rewrite behavioural steps to use the helpers
  • replace unwrap in panic world
  • mark advanced error handling complete
  • handle verification comments: consolidate tokio deps, document harness, adjust docs, and support repeated connect step

Testing

  • make fmt
  • make lint
  • make test
  • make markdownlint
  • make nixie (fails: ENOENT reading puppeteer-core)

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

Summary by Sourcery

Improve server resilience by wrapping connection tasks in panic handlers that log errors with peer addresses and prevent a single panic from terminating the server. Refactor panic test helpers and behavioural steps, add unit and cucumber tests to verify panic isolation, update dependencies, and complete related documentation.

New Features:

  • Wrap connection tasks with catch_unwind to log panics and peer addresses without crashing the server
  • Add a unit test to confirm connection panics are caught and logged
  • Introduce cucumber BDD tests (world, steps, feature) for connection panic resilience

Enhancements:

  • Refactor panic scenario test world using helper methods and consolidate behavioural step implementations
  • Update Cargo.toml to constrain cucumber versions and unify tokio features
  • Add cucumber test harness configuration

Build:

  • Enable tokio "test-util" feature and configure cucumber test harness in Cargo.toml

Documentation:

  • Mark advanced error handling as complete in roadmap and document panic handling improvements

Tests:

  • Add integration-style cucumber tests for panic resilience
  • Add async unit test for catching connection panics

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 26, 2025

Reviewer's Guide

This PR bolsters server stability by wrapping each connection task in a panic-safe boundary that logs peer addresses on failure, refactors and expands Cucumber-based behavioural tests with a PanicWorld helper API, updates the cucumber dependency and test harness config, and completes and clarifies panic-handling docs across multiple guides.

Sequence diagram for panic handling in connection tasks

sequenceDiagram
    participant Server
    participant TaskTracker
    participant ConnectionTask
    participant Logger
    Server->>TaskTracker: spawn connection task
    TaskTracker->>ConnectionTask: run process_stream (wrapped in catch_unwind)
    alt process_stream panics
        ConnectionTask->>Logger: log panic with peer_addr
    end
Loading

Class diagram for PanicWorld helper in Cucumber tests

classDiagram
    class PanicWorld {
        +setup_connection()
        +trigger_panic()
        +verify_panic_logged()
    }
    class StepDefinitions {
        +Given()
        +When()
        +Then()
    }
    StepDefinitions --> PanicWorld : uses
Loading

File-Level Changes

Change Details Files
Wrap connection tasks in catch_unwind to log and isolate panics
  • Wrap process_stream in AssertUnwindSafe.catch_unwind
  • Capture stream.peer_addr() for richer error context
  • Log panics and peer_addr using tracing::error
  • Add an async test to verify that connection panics are caught without crashing the server
src/server.rs
Refactor Cucumber behavioural tests using a PanicWorld helper API
  • Introduce PanicWorld with start, connect_once, and verify_and_shutdown methods
  • Rewrite Given/When/Then steps to call PanicWorld helpers
  • Add Cucumber test entry point and feature file for connection panic resilience
tests/world.rs
tests/steps/panic_steps.rs
tests/steps/mod.rs
tests/cucumber.rs
tests/features/connection_panic.feature
Update cucumber dependency constraints and test harness configuration
  • Set cucumber version to ">=0.20, <0.21" to allow compatible updates
  • Add a [[test]] entry for cucumber with harness=false
Cargo.toml
Revise documentation to mark and describe panic handling improvements
  • Mark advanced error handling items as complete in roadmap
  • Document catch_unwind usage and isolation in production-resilience guide
  • Add panic handling section in philosophy and capability maturity docs
docs/roadmap.md
docs/hardening-wireframe-a-guide-to-production-resilience.md
docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md

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 Jul 26, 2025

Summary by CodeRabbit

  • New Features

    • Added panic resilience to server connection handling, ensuring that panics in individual connections no longer crash the server.
    • Introduced a ready signal for the server to indicate when it is prepared to accept connections.
    • Added comprehensive behavioural tests using Cucumber to verify panic handling and server stability.
  • Bug Fixes

    • Panics during connection setup are now caught and logged, preventing server-wide crashes.
  • Documentation

    • Updated and expanded documentation to clarify panic handling strategies and mark advanced error handling as complete.
  • Tests

    • Added new behavioural and integration tests to validate server resilience against connection panics.
  • Chores

    • Updated dependencies and test configuration to support new testing frameworks and features.
    • Minor formatting improvements in project documentation.

Walkthrough

Update the dependency and test configuration in Cargo.toml to integrate Cucumber for behavioural testing and move Tokio's test-util feature to the main dependencies. Enhance documentation to describe the new panic handling strategy for connection tasks. Refactor the server to catch and log panics in connection tasks. Add Cucumber-based integration tests and supporting test modules to verify server resilience against panics during connection setup.

Changes

File(s) Change Summary
Cargo.toml Add Cucumber dependency and test config; move Tokio test-util feature to main dependencies.
docs/hardening-wireframe-a-guide-to-production-resilience.md Add note about panic handling in connection tasks using catch_unwind.
docs/roadmap.md Mark "Advanced Error Handling" and subtask for panic handling as complete.
docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md Add subsection on panic handling in connection tasks.
src/server.rs Wrap connection tasks with panic-catching boundary; log panics; add async test for panic resilience.
tests/cucumber.rs Add async entry point for Cucumber-based integration tests.
tests/features/connection_panic.feature Introduce feature test for connection panic resilience.
tests/steps/mod.rs Import new panic_steps module for Cucumber step definitions.
tests/steps/panic_steps.rs Implement Cucumber steps for panic resilience scenario.
tests/world.rs Define PanicWorld test context; implement server start, connect, and verification methods.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant ConnectionTask
    participant Logger

    Client->>Server: Connect
    Server->>ConnectionTask: Spawn process_stream (wrapped in catch_unwind)
    ConnectionTask->>ConnectionTask: Panic occurs
    ConnectionTask->>Logger: Log panic info and peer address
    ConnectionTask-->>Server: Task ends (panic caught, server continues)
    Client->>Server: Connect again
    Server->>ConnectionTask: Spawn process_stream (wrapped in catch_unwind)
    ConnectionTask-->>Server: Task ends (panic caught, server continues)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

When panics arise in the server’s domain,
Now they’re caught and logged, not left to reign.
Cucumber steps march in a test parade,
Ensuring resilience is robustly displayed.
With catch_unwind’s embrace and a roadmap now checked,
The server stands strong—no longer perplexed!
🥒🚦

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 26xd2p-codex/implement-advanced-error-handling

🪧 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 docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for 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.

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

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
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:

  • Move the cucumber dependency and related test harness entries to dev-dependencies so they aren’t compiled into production builds.
  • In the connection_panic_is_caught test, assert on the captured panic log (e.g. using a log test harness) to verify that the peer address context is actually emitted.
  • Consider exposing a metrics counter or hook for caught panics in connection tasks to help monitor how often user callbacks are failing in production.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Move the cucumber dependency and related test harness entries to dev-dependencies so they aren’t compiled into production builds.
- In the `connection_panic_is_caught` test, assert on the captured panic log (e.g. using a log test harness) to verify that the peer address context is actually emitted.
- Consider exposing a metrics counter or hook for caught panics in connection tasks to help monitor how often user callbacks are failing in production.

## Individual Comments

### Comment 1
<location> `src/server.rs:383` </location>
<code_context>
+                        .await
+                        {
+                            tracing::error!(
+                                ?panic,
+                                ?peer_addr,
+                                "connection task panicked"
+                            );
+                        }
</code_context>

<issue_to_address>
Logging the panic object directly may not always yield useful information.

Consider converting the panic payload to a string or formatting it for clearer log output, as logging it directly may be unclear if it's not a string.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
                            tracing::error!(
                                ?panic,
                                ?peer_addr,
                                "connection task panicked"
                            );
=======
                            let panic_msg = if let Some(s) = panic.downcast_ref::<&str>() {
                                s.to_string()
                            } else if let Some(s) = panic.downcast_ref::<String>() {
                                s.clone()
                            } else {
                                format!("{:?}", panic)
                            };
                            tracing::error!(
                                panic = %panic_msg,
                                ?peer_addr,
                                "connection task panicked"
                            );
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `tests/cucumber.rs:1` </location>
<code_context>
+mod steps;
+mod world;
+
</code_context>

<issue_to_address>
Consider replacing the Cucumber harness with a simple async test using #[tokio::test] to reduce boilerplate and complexity.

Consider dropping the full Cucumber harness for a single‐scenario test and instead using a simple `#[tokio::test]` in your `tests/` directory. This removes the extra `world`/`steps` modules and boilerplate.

Example `tests/panic_integration.rs`:

```rust
use tokio::process::Command;
use assert_cmd::prelude::*;

#[tokio::test]
async fn panic_world_should_run_and_fail() -> Result<(), Box<dyn std::error::Error>> {
    // Invokes the same binary as `cucumber::World::run`
    let mut cmd = Command::cargo_bin("your_binary_name")?;
    cmd.arg("--run-features").arg("tests/features");

    let output = cmd.output().await?;
    assert!(!output.status.success(), "expected panic scenario to fail");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("Expected panic message"),
        "got stdout: {}",
        stdout
    );

    Ok(())
}
```

Steps to migrate:
1. Remove `mod steps; mod world;` and the `main` entry in your repo root.
2. Add `assert_cmd = "2.0"` to your `[dev-dependencies]`.
3. Create `tests/panic_integration.rs` as above.
4. Adjust assertions to match your feature’s expected output.

This keeps the same behavior, but cuts out the Cucumber layer and its boilerplate.
</issue_to_address>

### Comment 3
<location> `tests/features/connection_panic.feature:1` </location>
<code_context>
+Feature: Connection panic resilience
+  Scenario: connection panic does not crash server
+    Given a running wireframe server with a panic in connection setup
</code_context>

<issue_to_address>
Consider replacing the BDD feature file with a focused async Rust test to streamline testing.

```markdown
It looks like this BDD feature is duplicating what you can achieve with a single async Rust test, and adds unnecessary indirection. Instead of keeping the `.feature` file, you can:

1. Remove the new `connection_panic_resilience.feature`  
2. Add a focused `#[tokio::test]` in your Rust test suite

For example, in `tests/connection_panic_resilience.rs`:

```rust
use wireframe::ServerBuilder;
use tokio::net::TcpStream;

#[tokio::test]
async fn connection_panic_resilience() {
    // Start the server with a panic in the first connection setup
    let server = ServerBuilder::new()
        .panic_on_setup(true)
        .spawn()
        .await;

    // First connection should recover from the panic
    let conn1 = TcpStream::connect(server.addr()).await;
    assert!(conn1.is_ok(), "first connection failed after panic");

    // Second connection should still succeed
    let conn2 = TcpStream::connect(server.addr()).await;
    assert!(conn2.is_ok(), "second connection failed");
}
```

This keeps all behavior in one place, removes the extra indirection, and keeps your test suite fully in Rust.
</issue_to_address>

### Comment 4
<location> `tests/world.rs:16` </location>
<code_context>
+use wireframe::{app::WireframeApp, server::WireframeServer};
+
+#[derive(Debug, Default, World)]
+pub struct PanicWorld {
+    pub addr: Option<SocketAddr>,
+    pub attempts: usize,
</code_context>

<issue_to_address>
Consider replacing the custom world state struct and Cucumber integration with a single self-contained async test function.

Here’s a way to collapse all of that “world” machinery into a single, self-contained `#[tokio::test]`, remove the global state entirely, and keep *exactly* the same panic-resilience check:

```rust
use std::net::SocketAddr;
use tokio::{
    net::TcpStream,
    sync::oneshot,
    task,
};
use wireframe::{app::WireframeApp, server::WireframeServer};

async fn start_panic_server() -> (SocketAddr, oneshot::Sender<()>) {
    // build a server that panics on each connection
    let factory = || {
        WireframeApp::new()
            .expect("WireframeApp::new failed")
            .on_connection_setup(|| async { panic!("boom") })
            .expect("set callback failed")
    };

    let server = WireframeServer::new(factory)
        .workers(1)
        .bind("127.0.0.1:0".parse().unwrap())
        .expect("bind failed");

    let addr = server.local_addr().unwrap();
    let (tx, rx) = oneshot::channel();

    task::spawn(async move {
        server
            .run_with_shutdown(async { let _ = rx.await; })
            .await
            .expect("server task failed");
    });

    // give the task a tick to start up
    task::yield_now().await;
    (addr, tx)
}

#[tokio::test]
async fn panic_resilience() {
    let (addr, shutdown) = start_panic_server().await;

    // both connections should panic the server, but still accept
    for _ in 0..2 {
        TcpStream::connect(addr)
            .await
            .expect("connect failed");
    }

    // now shut it down gracefully
    let _ = shutdown.send(());
    task::yield_now().await;
}
```

– removes the `#[derive(World)]` + global struct  
– keeps the same panic-in-accept loop & shutdown logic  
– no more `Option` state or Cucumber overhead
</issue_to_address>

### Comment 5
<location> `docs/hardening-wireframe-a-guide-to-production-resilience.md:166` </location>
<code_context>
 Initialization) pattern for safety.

+Connection tasks are wrapped with `catch_unwind` to log and discard panics.
+Each panicking connection is isolated so it cannot terminate the entire server.
+
 ### 3.2 Leak-Proof Registries with `Weak`/`Arc`
</code_context>

<issue_to_address>
This line is part of a paragraph that exceeds 80 columns and should be wrapped.

Ensure that this paragraph is wrapped to 80 columns for consistency with the documentation standards.
</issue_to_address>

### Comment 6
<location> `docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md:243` </location>
<code_context>
   system's overall resilience.
+- **Panic Handling:** Connection tasks are wrapped in a panic handler using
+  `catch_unwind`. A misbehaving connection can no longer terminate the entire
+  server.

 ### B. First-Class Developer Ergonomics
</code_context>

<issue_to_address>
This line is part of a bullet point that is not wrapped to 80 columns.

Ensure the entire bullet point is wrapped to 80 columns for consistency.
</issue_to_address>

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.

Comment thread src/server.rs Outdated
Comment thread tests/cucumber.rs
Comment thread tests/features/connection_panic.feature
Comment thread tests/world.rs
Comment thread docs/hardening-wireframe-a-guide-to-production-resilience.md
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: 6

🔭 Outside diff range comments (1)
tests/cucumber.rs (1)

1-9: Add required module-level documentation.

Every module must begin with a //! comment explaining the module's purpose and utility per the coding guidelines.

Add this at the top of the file:

+//! Cucumber test runner for panic resilience integration tests.
+//!
+//! Runs behavioral tests defined in `tests/features/` using the
+//! `PanicWorld` test context to verify server panic handling.
+
 mod steps;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a5c206 and ecf140c.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (10)
  • Cargo.toml (2 hunks)
  • docs/hardening-wireframe-a-guide-to-production-resilience.md (1 hunks)
  • docs/roadmap.md (1 hunks)
  • docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md (1 hunks)
  • src/server.rs (3 hunks)
  • tests/cucumber.rs (1 hunks)
  • tests/features/connection_panic.feature (1 hunks)
  • tests/steps/mod.rs (1 hunks)
  • tests/steps/panic_steps.rs (1 hunks)
  • tests/world.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Comments must use en-GB-oxendict spelling and grammar.
Function documentation must include clear examples.
Name things precisely. Use clear, descriptive variable and function names. For booleans, prefer names with is, has, or should.
Each file should encapsulate a coherent module. Group related code (e.g., models + utilities + fixtures) close together.
Group by feature, not layer. Colocate views, logic, fixtures, and helpers related to a domain concept rather than splitting by type.
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.
Place function attributes after doc comments.
Do not use return in single-line functions.
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.
Clippy warnings MUST be disallowed.
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.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Prefer .expect() over .unwrap().
Use predicate functions for conditional criteria with more than two branches.
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.

Files:

  • tests/steps/mod.rs
  • tests/cucumber.rs
  • tests/steps/panic_steps.rs
  • src/server.rs
  • tests/world.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.
  • 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:

  • tests/steps/mod.rs
  • tests/cucumber.rs
  • tests/steps/panic_steps.rs
  • src/server.rs
  • tests/world.rs
docs/**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

docs/**/*.md: Reference: Use the markdown files within the docs/ directory as a knowledge base and source of truth for project requirements, dependency choices, and architectural decisions.
Update: When new decisions are made, requirements change, libraries are added/removed, or architectural patterns evolve, proactively update the relevant file(s) in the docs/ directory to reflect the latest state. Ensure the documentation remains accurate and current.
Documentation must use en-GB-oxendict spelling and grammar (with the exception of 'license' which is to be left unchanged for community consistency).

Conventions for writing project documentation should be followed as described in the documentation style guide.

docs/**/*.md: Use British English based on the Oxford English Dictionary (en-oxendict) for documentation.
The word "outwith" is acceptable in documentation.
Keep US spelling when used in an API, for example color.
Use the Oxford comma in documentation lists and sentences.
Company names are treated as collective nouns (e.g., "Lille Industries are expanding").
Write headings in sentence case.
Use Markdown headings (#, ##, ###, etc.) in order without skipping levels.
Follow markdownlint recommendations.
Provide code blocks and lists using standard Markdown syntax.
Always provide a language identifier for fenced code blocks; use plaintext for non-code text.
Use - as the first level bullet and renumber lists when items change.
Prefer inline links using [text](url) or angle brackets around the URL.
Ensure blank lines before and after bulleted lists and fenced blocks.
Ensure tables have a delimiter line below the header row.
Expand any uncommon acronym on first use, for example, Continuous Integration (CI).
Wrap paragraphs at 80 columns.
Wrap code at 120 columns.
Do not wrap tables.
Use footnotes referenced with [^label].
Include Mermaid diagrams where they add clarity in documentation.
When embedding figures, use ![alt text](path/to/image) an...

Files:

  • docs/hardening-wireframe-a-guide-to-production-resilience.md
  • docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md
  • docs/roadmap.md
**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.md: Validate Markdown files using make markdownlint.
Run make fmt after any documentation changes to format all Markdown files and fix table markup.
Validate Mermaid diagrams in Markdown files by running make nixie.
Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks must be wrapped at 120 columns.
Tables and headings must not be wrapped.
Use dashes (-) for list bullets.
Use GitHub-flavoured Markdown footnotes ([^1]) for references.

Files:

  • docs/hardening-wireframe-a-guide-to-production-resilience.md
  • docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md
  • docs/roadmap.md

⚙️ CodeRabbit Configuration File

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • Paragraphs and bullets must be wrapped to 80 columns, except where a long URL would prevent this (in which case, silence MD013 for that line)
  • Code blocks should be wrapped to 120 columns.
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • docs/hardening-wireframe-a-guide-to-production-resilience.md
  • docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md
  • docs/roadmap.md
Cargo.toml

📄 CodeRabbit Inference Engine (AGENTS.md)

Use explicit version ranges in Cargo.toml and keep dependencies up-to-date.

Files:

  • Cargo.toml
🧠 Learnings (1)
tests/cucumber.rs (1)

Learnt from: CR
PR: leynos/netsuke#0
File: docs/behavioural-testing-in-rust-with-cucumber.md:0-0
Timestamp: 2025-07-20T02:48:36.265Z
Learning: Applies to docs/tests/cucumber.rs : The main test runner file (e.g., tests/cucumber.rs) must define an async fn main() annotated with #[tokio::main].

🔇 Additional comments (9)
Cargo.toml (2)

9-18: Avoid shipping test-only Tokio code in production builds

The test-util feature is now enabled under [dependencies]. This drags test helpers such as sync::Barrier into the release binary and increases compile times. Keep test-only features under [dev-dependencies] or behind an explicit crate feature.

-[dependencies]
-tokio = { version = "1", default-features = false, features = [
-    "net",
-    "signal",
-    "rt-multi-thread",
-    "macros",
-    "sync",
-    "time",
-    "io-util",
-    "test-util",
-] }
+[dependencies]
+tokio = { version = "1", default-features = false, features = [
+    "net",
+    "signal",
+    "rt-multi-thread",
+    "macros",
+    "sync",
+    "time",
+    "io-util",
+] }
+
+[dev-dependencies]
+tokio = { version = "1", default-features = false, features = ["test-util"] }

[ suggest_essential_refactor ]


36-38: Good: use an explicit, non-breaking version range for Cucumber

The bounded range >=0.20, <0.21 satisfies the guideline on explicit versions while permitting compatible patch updates.

docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md (1)

241-243: Wrap bullet text to 80 columns

The added bullet exceeds the mandated line length. Re-wrap to satisfy markdownlint.

- - **Panic Handling:** Connection tasks are wrapped in a panic handler using
-   `catch_unwind`. A misbehaving connection can no longer terminate the entire
-   server.
+- **Panic handling:** Connection tasks are wrapped in a panic handler using
+  `catch_unwind`. A misbehaving connection can no longer terminate the entire
+  server.
⛔ Skipped due to learnings
Learnt from: CR
PR: leynos/wireframe#0
File: docs/roadmap.md:0-0
Timestamp: 2025-07-21T13:21:45.715Z
Learning: Applies to docs/src/connection.rs : Implement panic handlers in connection tasks to prevent a single connection from crashing the server
docs/roadmap.md (1)

161-165: Maintain line-length discipline in roadmap bullets

Wrap the updated checklist items at 80 columns to conform with the documentation style guide.

-  - [x] Implement panic handlers in connection tasks to prevent a single
-    connection from crashing the server.
+  - [x] Implement panic handlers in connection tasks to prevent a single
+    connection from crashing the server.

Likely an incorrect or invalid review comment.

tests/cucumber.rs (1)

8-8: Format single-line function correctly.

The coding guidelines state "Do not use return in single-line functions." Apply proper formatting for the async main function.

-async fn main() { PanicWorld::run("tests/features").await; }
+async fn main() {
+    PanicWorld::run("tests/features").await;
+}

Likely an incorrect or invalid review comment.

tests/features/connection_panic.feature (1)

1-7: Well-structured behavioral test specification.

The feature file clearly defines the panic resilience scenario with appropriate Given-When-Then steps that align with the PR objectives.

src/server.rs (2)

372-388: Excellent panic handling implementation.

The panic catching logic is well-implemented with proper error context. Capturing the peer address before spawning the task provides valuable debugging information, and the use of AssertUnwindSafe with catch_unwind correctly prevents panics from crashing the server.


472-474: Leave test imports as-is

Test-only imports for TcpStream and oneshot reside inside the #[cfg(test)] module (lines 459–460) and don’t affect non-test builds. No changes required.

tests/steps/panic_steps.rs (1)

1-19: Well-implemented Cucumber step definitions.

The step implementations are clean, properly documented, and follow the coding guidelines. The duplicate #[when] attribute on line 14 correctly allows the same step to handle repeated connection attempts.

Comment thread Cargo.toml Outdated
Comment thread docs/hardening-wireframe-a-guide-to-production-resilience.md
Comment thread src/server.rs
Comment thread tests/steps/mod.rs
Comment thread tests/world.rs
Comment thread tests/world.rs
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: 1

♻️ Duplicate comments (1)
Cargo.toml (1)

45-48: Previous nitpick resolved – thank you.
The inline comment clarifies why harness = false is required, satisfying the earlier review.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ecf140c and 3921c1a.

📒 Files selected for processing (1)
  • Cargo.toml (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
Cargo.toml

📄 CodeRabbit Inference Engine (AGENTS.md)

Use explicit version ranges in Cargo.toml and keep dependencies up-to-date.

Files:

  • Cargo.toml
🔇 Additional comments (1)
Cargo.toml (1)

36-37: LGTM – version range follows the guideline.
The explanatory comment is helpful and the <0.21 upper bound guards against breaking changes.

Comment thread Cargo.toml
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 26, 2025

@coderabbitai please create GitHub issues for the following, providing as much context as possible and potential solutions:

  • In the connection_panic_is_caught test, assert on the captured panic log (e.g. using a log test harness) to verify that the peer address context is actually emitted.

  • Consider exposing a metrics counter or hook for caught panics in connection tasks to help monitor how often user callbacks are failing in production.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 26, 2025

Tip

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

🧩 Analysis chain

@leynos I'll create GitHub issues for both enhancement requests with relevant context from the current implementation.

Now I'll create the GitHub issues:

Both GitHub issues have been created with comprehensive context from the current implementation and detailed potential solutions. The issues include:

  1. Enhanced test assertions: Proposes using a log test harness to verify panic logs contain the expected peer address context
  2. Production metrics: Suggests multiple approaches (metrics counters, custom hooks, or enhanced structured logging) to monitor panic frequency in production

Each issue includes implementation examples, benefits, and acceptance criteria to guide future development.


🏁 Script executed:

#!/bin/bash
# First, let's examine the current panic handling implementation and test
echo "=== Current panic handling implementation ==="
cat src/server.rs | grep -A 20 -B 5 "catch_unwind"

echo -e "\n=== Current test implementation ==="
cat src/server.rs | grep -A 30 -B 5 "connection_panic_is_caught"

echo -e "\n=== Available logging/tracing setup ==="
rg "tracing::" src/server.rs

Length of output: 2430


🏁 Script executed:

#!/bin/bash
# Create first issue about improving the panic test with log assertions
gh issue create \
  --title "Enhance connection_panic_is_caught test to assert on panic log output" \
  --body "## Context

This issue is a follow-up to PR #215 which implemented panic handling improvements for connection tasks. The current test \`connection_panic_is_caught\` verifies that the server doesn't crash when connection tasks panic, but it doesn't verify that the panic logging works correctly.

## Current Implementation

The panic handling code in \`src/server.rs\` logs panics with peer address context:

\`\`\`rust
let peer_addr = stream.peer_addr().ok();
// ... spawn task with catch_unwind
tracing::error!(\"Connection task panicked: {:?}, peer_addr: {:?}\", panic_info, peer_addr);
\`\`\`

However, the test doesn't assert that this log message is actually emitted with the expected peer address.

## Proposed Solution

Enhance the test to capture and assert on log output:

1. **Use a test log harness** (e.g., \`tracing-test\` crate or similar) to capture log messages during the test
2. **Assert on log content** - verify that the panic log contains:
   - The expected panic message/info
   - The peer address of the connection that panicked
3. **Improve test reliability** - ensure the test validates the complete panic handling behavior

## Potential Implementation

\`\`\`rust
#[tokio::test]
async fn connection_panic_is_caught() {
    // Setup log capturing
    let (log_guard, log_receiver) = setup_test_logs();
    
    // Existing test setup...
    
    // Trigger panic scenarios...
    
    // Assert on captured logs
    let logs = log_receiver.try_recv().unwrap();
    assert!(logs.iter().any(|log| {
        log.level == Level::ERROR &&
        log.message.contains(\"Connection task panicked\") &&
        log.message.contains(\"127.0.0.1\") // or expected peer addr
    }));
}
\`\`\`

## Benefits

- **Test completeness**: Verifies the entire panic handling flow including logging
- **Regression prevention**: Ensures log format and content remain correct
- **Documentation**: Shows expected log output format for operators

## Related

- PR #215: Implement panic handling improvements
- Comment: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/215#issuecomment-$(date +%s)" \
  --assignee leynos

# Create second issue about metrics/monitoring for caught panics
gh issue create \
  --title "Add metrics/monitoring for caught panics in connection tasks" \
  --body "## Context

Following PR #215 which implemented panic handling for connection tasks, we should add production monitoring capabilities to track how often connection panics occur.

## Problem

Currently, panics in connection tasks are caught and logged, but there's no easy way for operators to:
- Monitor panic frequency in production
- Set up alerts for elevated panic rates
- Analyze trends in connection task failures
- Correlate panics with specific deployment changes or traffic patterns

## Proposed Solutions

### Option 1: Metrics Counter
Add a metrics counter using a standard metrics library:

\`\`\`rust
use metrics::counter;

// In the panic handling code
tracing::error!(\"Connection task panicked: {:?}, peer_addr: {:?}\", panic_info, peer_addr);
counter!(\"wireframe.connection.panics\", 1, \"peer_addr\" => peer_addr.to_string());
\`\`\`

### Option 2: Custom Hook/Callback
Expose a configurable hook for panic events:

\`\`\`rust
pub trait PanicHandler: Send + Sync {
    fn on_connection_panic(&self, peer_addr: Option<SocketAddr>, panic_info: &dyn Any);
}

// In server configuration
impl ServerBuilder {
    pub fn with_panic_handler<H: PanicHandler + 'static>(mut self, handler: H) -> Self {
        self.panic_handler = Some(Box::new(handler));
        self
    }
}
\`\`\`

### Option 3: Structured Logging Enhancement
Enhance the existing tracing with structured fields for easier monitoring:

\`\`\`rust
tracing::error!(
    peer_addr = ?peer_addr,
    panic_type = std::any::type_name_of_val(&**panic_info),
    \"Connection task panicked\"
);
\`\`\`

## Implementation Considerations

1. **Minimal overhead**: Metrics collection should not impact performance
2. **Configurable**: Allow disabling metrics collection if not needed
3. **Standard integration**: Use common metrics libraries (prometheus, statsd, etc.)
4. **Privacy**: Avoid logging sensitive connection data in metrics

## Benefits

- **Operational visibility**: Monitor connection stability in production
- **Proactive debugging**: Identify problematic connection patterns
- **Performance insights**: Correlate panics with system load/configuration
- **SLA monitoring**: Track reliability metrics for the server

## Acceptance Criteria

- [ ] Metrics are collected when connection tasks panic
- [ ] Metrics include relevant dimensions (peer_addr pattern, timestamp)
- [ ] Metrics collection can be disabled via configuration
- [ ] Documentation explains how to set up monitoring dashboards
- [ ] Minimal performance impact on happy path

## Related

- PR #215: Implement panic handling improvements  
- Comment: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/215#issuecomment-$(date +%s)" \
  --assignee leynos

Length of output: 5014


Perfect! I've successfully created both GitHub issues with comprehensive context and potential solutions:

Created Issues

Issue #216: Enhance connection_panic_is_caught test to assert on panic log output

  • Proposes using a test log harness (like tracing-test) to capture and verify panic log messages
  • Includes implementation example showing how to assert on log content including peer address
  • Addresses the gap where the current test only verifies the server doesn't crash but doesn't validate the logging behavior

Issue #217: Add metrics/monitoring for caught panics in connection tasks

  • Provides three different implementation approaches:
    1. Standard metrics counter integration
    2. Custom panic handler hook/callback system
    3. Enhanced structured logging for monitoring tools
  • Includes operational considerations like minimal overhead and configurability
  • Defines clear acceptance criteria for production monitoring capabilities

Both issues reference the current PR #215 and include relevant code snippets from the actual implementation. The issues provide actionable enhancement paths to improve both testing robustness and production observability of the panic handling feature.

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: 2

♻️ Duplicate comments (1)
tests/world.rs (1)

28-52: Fix server startup synchronisation.

The server startup lacks proper synchronisation, creating potential race conditions in tests. Replace the implicit startup timing with an explicit ready signal.

Add a ready channel to ensure the server is listening before returning:

 pub fn start_panic_server(&mut self) {
+    let (ready_tx, ready_rx) = oneshot::channel();
     let factory = || {
         WireframeApp::new()
             .expect("Failed to create WireframeApp")
             .on_connection_setup(|| async { panic!("boom") })
             .expect("Failed to set connection setup callback")
     };
     let server = WireframeServer::new(factory)
         .workers(1)
         .bind("127.0.0.1:0".parse().expect("Failed to parse address"))
         .expect("bind");

     self.addr = Some(server.local_addr().expect("Failed to get server address"));
     let (tx, rx) = oneshot::channel();
     self.shutdown = Some(tx);

-    self.handle = Some(tokio::spawn(async move {
+    self.handle = Some(tokio::spawn(async move {
+        let _ = ready_tx.send(());
         server
             .run_with_shutdown(async {
                 let _ = rx.await;
             })
             .await
             .expect("Server task failed");
     }));
+    
+    // This should be awaited in an async version of this method
+    // Consider making this method async or adding a separate wait method
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3921c1a and b1cfe86.

📒 Files selected for processing (3)
  • README.md (1 hunks)
  • tests/steps/panic_steps.rs (1 hunks)
  • tests/world.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.md: Validate Markdown files using make markdownlint.
Run make fmt after any documentation changes to format all Markdown files and fix table markup.
Validate Mermaid diagrams in Markdown files by running make nixie.
Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks must be wrapped at 120 columns.
Tables and headings must not be wrapped.
Use dashes (-) for list bullets.
Use GitHub-flavoured Markdown footnotes ([^1]) for references.

Files:

  • README.md

⚙️ CodeRabbit Configuration File

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • Paragraphs and bullets must be wrapped to 80 columns, except where a long URL would prevent this (in which case, silence MD013 for that line)
  • Code blocks should be wrapped to 120 columns.
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • README.md
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Comments must use en-GB-oxendict spelling and grammar.
Function documentation must include clear examples.
Name things precisely. Use clear, descriptive variable and function names. For booleans, prefer names with is, has, or should.
Each file should encapsulate a coherent module. Group related code (e.g., models + utilities + fixtures) close together.
Group by feature, not layer. Colocate views, logic, fixtures, and helpers related to a domain concept rather than splitting by type.
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.
Place function attributes after doc comments.
Do not use return in single-line functions.
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.
Clippy warnings MUST be disallowed.
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.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Prefer .expect() over .unwrap().
Use predicate functions for conditional criteria with more than two branches.
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.

Files:

  • tests/steps/panic_steps.rs
  • tests/world.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.
  • 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:

  • tests/steps/panic_steps.rs
  • tests/world.rs
🪛 LanguageTool
README.md

[grammar] ~87-~87: Please add a punctuation mark at the end of paragraph.
Context: ...a binary protocol server. See the [full example](docs/rust-binary-router-library-design...

(PUNCTUATION_PARAGRAPH_END)

🔇 Additional comments (8)
tests/steps/panic_steps.rs (3)

1-5: LGTM - Clear module documentation.

The module documentation effectively explains the purpose and follows the required format.


6-8: LGTM - Clean imports.

The imports are minimal and appropriate for the module's functionality.


16-21: LGTM - Well-structured step implementations.

The step functions properly delegate to world methods and use appropriate Cucumber patterns.

tests/world.rs (5)

1-5: LGTM - Clear module documentation.

The module documentation effectively explains the test world's purpose.


6-13: LGTM - Well-organised imports.

The imports are appropriate and cleanly organised.


15-21: LGTM - Appropriate struct design.

The PanicWorld struct correctly models the test state with appropriate optional fields.


54-63: LGTM - Well-implemented connection method.

The method properly handles connections and tracks attempts with appropriate error handling.


65-78: LGTM - Proper verification and cleanup.

The method correctly verifies connection attempts and performs proper server shutdown with task completion awaiting.

Comment thread README.md
Comment thread tests/steps/panic_steps.rs Outdated
leynos added 4 commits July 26, 2025 23:36
- add ready channel support in WireframeServer- synchronise PanicWorld server start- document cucumber modules and steps- clarify panic test assertions
@leynos leynos force-pushed the 26xd2p-codex/implement-advanced-error-handling branch from 3b3039a to c4dbd74 Compare July 26, 2025 22:36
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: 2

♻️ Duplicate comments (4)
README.md (1)

86-88: Inline the long-URL directive and finish the sentence.

Keep the suppression comment on the same line as the long URL and close the paragraph with a full stop. This keeps markdownlint happy and removes the stray line break.

-binary protocol server. See the
-[full example](docs/rust-binary-router-library-design.md#5-6-illustrative-api-usage-examples)
- <!-- markdownlint-disable-line MD013 --> in the design document for further
-details.
+binary protocol server. See the [full example](docs/rust-binary-router-library-design.md#5-6-illustrative-api-usage-examples) <!-- markdownlint-disable-line MD013 --> in the design document for further details.
Cargo.toml (1)

9-18: Repeat: pin Tokio and gate test-util behind advanced-tests.

The earlier feedback remains unresolved. Specify an explicit semver range (e.g., >=1.37, <2) and move test-util to a test-only feature or [dev-dependencies] to avoid bloating release builds.

src/server.rs (2)

387-406: Improve panic message extraction for clarity.

The current implementation extracts panic messages but could benefit from cleaner formatting as suggested in the previous review.


908-944: Enhance test documentation and clarity.

The test would benefit from the improvements suggested in the previous review, including better documentation and explicit assertions.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3b3039a and c4dbd74.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • Cargo.toml (3 hunks)
  • README.md (1 hunks)
  • docs/hardening-wireframe-a-guide-to-production-resilience.md (1 hunks)
  • docs/roadmap.md (1 hunks)
  • docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md (1 hunks)
  • src/server.rs (9 hunks)
  • tests/cucumber.rs (1 hunks)
  • tests/features/connection_panic.feature (1 hunks)
  • tests/steps/mod.rs (1 hunks)
  • tests/steps/panic_steps.rs (1 hunks)
  • tests/world.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
docs/**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

docs/**/*.md: Reference: Use the markdown files within the docs/ directory as a knowledge base and source of truth for project requirements, dependency choices, and architectural decisions.
Update: When new decisions are made, requirements change, libraries are added/removed, or architectural patterns evolve, proactively update the relevant file(s) in the docs/ directory to reflect the latest state. Ensure the documentation remains accurate and current.
Documentation must use en-GB-oxendict spelling and grammar (with the exception of 'license' which is to be left unchanged for community consistency).

Conventions for writing project documentation should be followed as described in the documentation style guide.

docs/**/*.md: Use British English based on the Oxford English Dictionary (en-oxendict) for documentation.
The word "outwith" is acceptable in documentation.
Keep US spelling when used in an API, for example color.
Use the Oxford comma in documentation lists and sentences.
Company names are treated as collective nouns (e.g., "Lille Industries are expanding").
Write headings in sentence case.
Use Markdown headings (#, ##, ###, etc.) in order without skipping levels.
Follow markdownlint recommendations.
Provide code blocks and lists using standard Markdown syntax.
Always provide a language identifier for fenced code blocks; use plaintext for non-code text.
Use - as the first level bullet and renumber lists when items change.
Prefer inline links using [text](url) or angle brackets around the URL.
Ensure blank lines before and after bulleted lists and fenced blocks.
Ensure tables have a delimiter line below the header row.
Expand any uncommon acronym on first use, for example, Continuous Integration (CI).
Wrap paragraphs at 80 columns.
Wrap code at 120 columns.
Do not wrap tables.
Use footnotes referenced with [^label].
Include Mermaid diagrams where they add clarity in documentation.
When embedding figures, use ![alt text](path/to/image) an...

Files:

  • docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md
  • docs/hardening-wireframe-a-guide-to-production-resilience.md
  • docs/roadmap.md
**/*.md

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.md: Validate Markdown files using make markdownlint.
Run make fmt after any documentation changes to format all Markdown files and fix table markup.
Validate Mermaid diagrams in Markdown files by running make nixie.
Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks must be wrapped at 120 columns.
Tables and headings must not be wrapped.
Use dashes (-) for list bullets.
Use GitHub-flavoured Markdown footnotes ([^1]) for references.

Files:

  • docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md
  • README.md
  • docs/hardening-wireframe-a-guide-to-production-resilience.md
  • docs/roadmap.md

⚙️ CodeRabbit Configuration File

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-GB-oxendict (-ize / -our) spelling and grammar
  • Paragraphs and bullets must be wrapped to 80 columns, except where a long URL would prevent this (in which case, silence MD013 for that line)
  • Code blocks should be wrapped to 120 columns.
  • Headings must not be wrapped.
  • Documents must start with a level 1 heading
  • Headings must correctly increase or decrease by no more than one level at a time
  • Use GitHub-flavoured Markdown style for footnotes and endnotes.
  • Numbered footnotes must be numbered by order of appearance in the document.

Files:

  • docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md
  • README.md
  • docs/hardening-wireframe-a-guide-to-production-resilience.md
  • docs/roadmap.md
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Comments must use en-GB-oxendict spelling and grammar.
Function documentation must include clear examples.
Name things precisely. Use clear, descriptive variable and function names. For booleans, prefer names with is, has, or should.
Each file should encapsulate a coherent module. Group related code (e.g., models + utilities + fixtures) close together.
Group by feature, not layer. Colocate views, logic, fixtures, and helpers related to a domain concept rather than splitting by type.
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.
Place function attributes after doc comments.
Do not use return in single-line functions.
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.
Clippy warnings MUST be disallowed.
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.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Prefer .expect() over .unwrap().
Use predicate functions for conditional criteria with more than two branches.
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.

Files:

  • tests/steps/mod.rs
  • tests/cucumber.rs
  • tests/steps/panic_steps.rs
  • tests/world.rs
  • src/server.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.
  • 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:

  • tests/steps/mod.rs
  • tests/cucumber.rs
  • tests/steps/panic_steps.rs
  • tests/world.rs
  • src/server.rs
Cargo.toml

📄 CodeRabbit Inference Engine (AGENTS.md)

Use explicit version ranges in Cargo.toml and keep dependencies up-to-date.

Files:

  • Cargo.toml
🪛 LanguageTool
README.md

[grammar] ~87-~87: Please add a punctuation mark at the end of paragraph.
Context: ...a binary protocol server. See the [full example](docs/rust-binary-router-library-design...

(PUNCTUATION_PARAGRAPH_END)

🔇 Additional comments (13)
Cargo.toml (1)

51-56: Good explanatory comment.

The note clearly justifies disabling the standard test harness.
No further action required.

docs/hardening-wireframe-a-guide-to-production-resilience.md (1)

165-167: Panic-handling note looks good.

The lines now respect the 80-column limit.
No further changes needed.

docs/roadmap.md (1)

161-165: Roadmap tick-box update acknowledged.

The completion status correctly reflects the new panic-handling work.

tests/steps/mod.rs (1)

1-7: Module structure and documentation look good.

The module properly aggregates step definitions with clear documentation explaining its purpose. The module-level doc comment correctly describes the module's role in exposing Given-When-Then steps for behaviour-driven tests.

tests/cucumber.rs (1)

1-13: Cucumber test runner implementation is correct.

The module provides clear documentation and a concise async entry point for running behavioural tests. The implementation correctly uses the PanicWorld context for test execution.

tests/features/connection_panic.feature (1)

1-7: Feature specification is clear and well-structured.

The Gherkin scenario effectively describes the panic resilience behaviour being tested. The two connection attempts properly verify that the server remains operational after a panic.

tests/steps/panic_steps.rs (1)

1-18: Step definitions are well-implemented.

The module provides clear documentation and concise step implementations. The reuse of the connect function for both "I connect to the server" and "I connect to the server again" steps through multiple #[when] attributes is good practice.

tests/world.rs (4)

1-22: Test world structure is well-designed.

The PanicWorld struct properly encapsulates test state with appropriate use of Option types for lifecycle management. The module documentation clearly explains its purpose in managing behavioural test state.


23-56: Server startup implementation is robust.

The method properly implements server startup with panic injection and includes proper synchronisation using the ready signal pattern. Error handling with descriptive messages aids debugging, and storing the task handle ensures proper cleanup.


58-67: Connection method is simple and effective.

The implementation correctly handles connection attempts with proper error reporting and attempt tracking.


69-82: Shutdown logic properly ensures task completion.

The method correctly validates connection attempts and implements graceful shutdown by awaiting the server task completion, which is more reliable than the previous yield_now approach.

src/server.rs (2)

196-202: Method implementation follows established patterns.

The ready_signal method correctly implements the builder pattern and provides clear documentation.


327-329: Ready signal correctly sent after listener setup.

The implementation properly signals readiness after binding but before accepting connections.

Comment on lines +241 to +243
- **Panic Handling:** Connection tasks are wrapped in a panic handler using
`catch_unwind`. A misbehaving connection can no longer terminate the entire
server.
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.

🧹 Nitpick (assertive)

Hard-wrap the bullet to ≤ 80 columns.

Break the long sentence to satisfy the documentation wrap rule.

-- **Panic Handling:** Connection tasks are wrapped in a panic handler using
-  `catch_unwind`. A misbehaving connection can no longer terminate the entire
-  server.
+- **Panic Handling:** Connection tasks are wrapped in a panic handler using
+  `catch_unwind`. A misbehaving connection can no longer terminate the
+  entire server.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- **Panic Handling:** Connection tasks are wrapped in a panic handler using
`catch_unwind`. A misbehaving connection can no longer terminate the entire
server.
- **Panic Handling:** Connection tasks are wrapped in a panic handler using
`catch_unwind`. A misbehaving connection can no longer terminate the
entire server.
🤖 Prompt for AI Agents
In
docs/the-road-to-wireframe-1-0-feature-set-philosophy-and-capability-maturity.md
around lines 241 to 243, the bullet point about Panic Handling exceeds 80
columns. Reformat the text to hard-wrap the lines so that no line exceeds 80
characters, breaking the sentence appropriately while preserving its meaning.

Comment thread src/server.rs
workers: usize,
on_preamble_success: Option<PreambleCallback<T>>,
on_preamble_failure: Option<PreambleErrorCallback>,
ready_tx: Option<oneshot::Sender<()>>,
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.

🧹 Nitpick (assertive)

Add documentation for the ready_tx field.

Document the purpose of this field to maintain consistency with other struct fields.

+    /// Optional channel to signal when the server is ready to accept connections.
     ready_tx: Option<oneshot::Sender<()>>,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ready_tx: Option<oneshot::Sender<()>>,
/// Optional channel to signal when the server is ready to accept connections.
ready_tx: Option<oneshot::Sender<()>>,
🤖 Prompt for AI Agents
In src/server.rs at line 61, the field `ready_tx` lacks documentation. Add a
comment above this field explaining its purpose, such as indicating that it is
an optional oneshot sender used to signal readiness, to maintain consistency
with the documentation style of other struct fields.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 26, 2025

Superseded

@leynos leynos closed this Jul 26, 2025
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