Skip to content

7978: docs(runtime): document FD table pre-warming workaround#79

Open
martin-augment wants to merge 4 commits intomasterfrom
pr-7978-2026-03-20-20-41-45
Open

7978: docs(runtime): document FD table pre-warming workaround#79
martin-augment wants to merge 4 commits intomasterfrom
pr-7978-2026-03-20-20-41-45

Conversation

@martin-augment
Copy link
Copy Markdown
Owner

7978: To review by AI

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a significant performance optimization for Tokio applications running on Linux by providing a mechanism to pre-warm the kernel's file descriptor table. This addresses a known issue where lazy FD table growth can cause substantial latency spikes in multi-threaded environments. The changes include a new example demonstrating the workaround and updated runtime documentation to guide users on implementing this performance tuning technique.

Highlights

  • New Example for FD Table Pre-warming: A new example (prewarm-fd-table.rs) was introduced to demonstrate a Linux-specific workaround for pre-warming the file descriptor table, aiming to prevent latency spikes in multi-threaded applications.
  • Documentation Update: The tokio::runtime module documentation was updated with a new section on 'Performance tuning' that explains the issue of file descriptor table growth on Linux and references the new pre-warming example.
  • Dependency and Example Registration: The examples/Cargo.toml file was modified to include libc as a dev-dependency for Linux targets, which is required by the new example, and to register the new prewarm-fd-table example.
  • Spellcheck Dictionary Expansion: The spellcheck.dic file was updated to include the term 'RCU', which is relevant to the explanation of file descriptor table synchronization mechanisms.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 20, 2026

Walkthrough

This pull request introduces a new example demonstrating file descriptor (FD) table pre-warming on Linux systems. A new file examples/prewarm-fd-table.rs is added containing a function that uses libc::fcntl with F_DUPFD_CLOEXEC to pre-allocate FD slots. The example is registered in examples/Cargo.toml along with a conditional Linux dependency on libc = "0.2". Documentation is added to tokio/src/runtime/mod.rs under a "Performance tuning" section referencing the new example. The spellcheck dictionary is updated to include the term "RCU".

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pr-7978-2026-03-20-20-41-45

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Tip

CodeRabbit can generate a title for your PR based on the changes with custom instructions.

Set the reviews.auto_title_instructions setting to generate a title for your PR based on the changes in the PR with custom instructions.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces documentation and an example for a workaround to pre-warm the file descriptor table on Linux, which can help avoid latency spikes in multi-threaded applications. The changes include a new example file, updates to Cargo.toml to support it, and additions to the runtime module's documentation. My review focuses on the correctness and safety of the new example code. I've suggested a small improvement to ensure type safety at the FFI boundary.

Comment on lines +29 to +42
use std::os::unix::io::{FromRawFd, OwnedFd};

// Open /dev/null to get a base FD.
let dev_null = std::fs::File::open("/dev/null")?;

// Use F_DUPFD_CLOEXEC to duplicate to a slot >= target. This forces the
// kernel to expand the FD table in a single syscall, without clobbering
// existing FDs. CLOEXEC prevents leaking to child processes.
let raw = unsafe {
libc::fcntl(
std::os::unix::io::AsRawFd::as_raw_fd(&dev_null),
libc::F_DUPFD_CLOEXEC,
target,
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The target parameter is a u32, but fcntl's third argument for F_DUPFD_CLOEXEC is a c_int (i32 on Linux). Passing a u32 value that is larger than i32::MAX will be interpreted as a negative number, causing fcntl to fail. It's safer to validate the input and use the correct type.

    use std::convert::TryInto;
    use std::os::unix::io::{FromRawFd, OwnedFd};

    let target = target.try_into().map_err(|e| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, e)
    })?;

    // Open /dev/null to get a base FD.
    let dev_null = std::fs::File::open("/dev/null")?;

    // Use F_DUPFD_CLOEXEC to duplicate to a slot >= target. This forces the
    // kernel to expand the FD table in a single syscall, without clobbering
    // existing FDs. CLOEXEC prevents leaking to child processes.
    let raw = unsafe {
        libc::fcntl(
            std::os::unix::io::AsRawFd::as_raw_fd(&dev_null),
            libc::F_DUPFD_CLOEXEC,
            target,
        )

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

value:good-to-have; category:bug; feedback: The Gemini AI reviewer is correct! FFI with libc uses c_int, which is i32 in Rust. Using other integer types may work or not. It is better to use the same types as the libc's APIs.

@claude
Copy link
Copy Markdown

claude bot commented Mar 20, 2026

Code Review

This is a well-focused documentation/example PR. Overall the changes are clean and correct.

Strengths:

  • Correct unsafe usage: fcntl(F_DUPFD_CLOEXEC) is appropriately wrapped in unsafe, with OwnedFd used as a RAII drop-guard. The CLOEXEC flag is good security practice.
  • Graceful fallback: The non-Linux no-op stub and warning-on-error in main are appropriate.
  • Accurate doc comment: The RCU stall explanation in the module doc is correct and helpful.
  • Correct platform scoping: libc is gated under cfg(target_os = "linux") in Cargo.toml.

Issues and Suggestions:

  1. Missing AsRawFd in use statement (prewarm-fd-table.rs, line 35)
    The current code calls std::os::unix::io::AsRawFd::as_raw_fd(&dev_null) via the fully qualified path. The idiomatic Rust pattern is to add AsRawFd to the use import and call dev_null.as_raw_fd() directly.

  2. Misleading variable name (prewarm-fd-table.rs, line 51)
    The name _owned suggests an unused binding, but here the drop is intentional — it closes the FD. A name like _dup_fd more clearly signals this is a deliberate drop-guard rather than dead code.

  3. Hardcoded master branch in doc link (tokio/src/runtime/mod.rs, line 395)
    This is consistent with other examples in this file, so it is acceptable. Just noting that it will always reflect the latest master rather than a pinned version.

  4. Consider documenting the RLIMIT_NOFILE constraint
    The fcntl call fails with EMFILE if target >= RLIMIT_NOFILE (the soft limit). The example already handles this gracefully with a warning, but a comment near FD_TARGET = 10_000 would help users understand why pre-warming can silently fail in constrained environments. Docker containers default to a 1024 fd limit, making this a common real-world gotcha.

Summary: Items 1 and 2 are minor style nits. Item 4 is the most practically impactful for users deploying in containers. The core logic, safety model, and documentation are all correct.

Copy link
Copy Markdown

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

libc::F_DUPFD_CLOEXEC,
target,
)
};
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Wrong type passed to variadic FFI fcntl call

Low Severity

The target parameter is typed u32 but is passed directly as a variadic argument to libc::fcntl, which expects c_int (i32) for F_DUPFD_CLOEXEC. Passing a mismatched type to a C variadic function is undefined behavior per the C standard. While harmless for the hardcoded value of 10,000, this example is designed to be copied by users who might supply larger values — any u32 above i32::MAX would be UB. The parameter type (and FD_TARGET const) would be more correct as libc::c_int or i32.

Fix in Cursor Fix in Web

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

value:good-to-have; category:bug; feedback: The Bugbot AI reviewer is correct! FFI with libc uses c_int, which is i32 in Rust. Using other integer types may work or not. It is better to use the same types as the libc's APIs.

@augmentcode
Copy link
Copy Markdown

augmentcode bot commented Mar 20, 2026

🤖 Augment PR Summary

Summary: Adds docs + a runnable example for a Linux workaround that pre-warms the kernel FD table to avoid RCU-related stalls on Tokio worker threads.

What changed: Introduces a new prewarm-fd-table example that forces FD table growth via fcntl(F_DUPFD_CLOEXEC) before building a runtime.

Dependencies: Registers the example in examples/Cargo.toml and adds a Linux-only libc dev-dependency for the example’s fcntl call.

Docs: Links the new example from the runtime module documentation under a performance-tuning section.

Housekeeping: Adds “RCU” to the spellcheck dictionary.

Why: Reduces latency spikes seen when the FD table grows lazily under load in multi-threaded services.

🤖 Was this summary useful? React with 👍 or 👎

Copy link
Copy Markdown

@augmentcode augmentcode bot left a comment

Choose a reason for hiding this comment

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

Review completed. 2 suggestions posted.

Fix All in Augment

Comment augment review to trigger a new review at any time.

libc::fcntl(
std::os::unix::io::AsRawFd::as_raw_fd(&dev_null),
libc::F_DUPFD_CLOEXEC,
target,
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Because libc::fcntl is varargs, passing target as a u32 can be ABI-incorrect on some platforms; consider casting to the exact expected C type for F_DUPFD_CLOEXEC (typically libc::c_int) to avoid UB in this unsafe call.

Severity: medium

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

value:good-to-have; category:bug; feedback: The Augment AI reviewer is correct! FFI with libc uses c_int, which is i32 in Rust. Using other integer types may work or not. It is better to use the same types as the libc's APIs.

if let Err(e) = prewarm_fd_table(FD_TARGET) {
eprintln!("Warning: failed to pre-warm FD table: {e}");
} else {
println!("FD table pre-warmed successfully.");
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

On non-Linux targets prewarm_fd_table is a no-op that returns Ok(()), so this “pre-warmed successfully” message can be misleading when the example is run on macOS/Windows.

Severity: low

Fix This in Augment

🤖 Was this useful? React with 👍 or 👎, or 🚀 if it prevented an incident/outage.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

value:good-to-have; category:bug; feedback: The Augment AI reviewer is correct! The whole example does not make sense for non-Linux runs. It would be better to return early in main() with a message printed on the stdout that the example does nothing on non-Linux. Currently it prints success messages even when it did nothing and this may confuse the users.

Copy link
Copy Markdown

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@examples/prewarm-fd-table.rs`:
- Around line 65-69: The code prints "FD table pre-warmed successfully." even on
non-Linux where prewarm_fd_table(FD_TARGET) is a no-op; change the logic so the
success message is only emitted when the pre-warm actually ran (e.g., guard the
println! with cfg!(target_os = "linux") or adjust prewarm_fd_table to return a
boolean/enum indicating it performed work and print only when that indicates
success). Update the branch around the call to prewarm_fd_table(FD_TARGET) (and
the associated success println!) to rely on that condition so non-Linux
platforms no longer show a false success.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 338934f7-af4d-4511-8ea7-baa4c9afff15

📥 Commits

Reviewing files that changed from the base of the PR and between 0a86787 and 8c7612d.

📒 Files selected for processing (4)
  • examples/Cargo.toml
  • examples/prewarm-fd-table.rs
  • spellcheck.dic
  • tokio/src/runtime/mod.rs

Comment on lines +65 to +69
if let Err(e) = prewarm_fd_table(FD_TARGET) {
eprintln!("Warning: failed to pre-warm FD table: {e}");
} else {
println!("FD table pre-warmed successfully.");
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Non-Linux path reports a false success message.

On non-Linux, prewarm_fd_table is a no-op but this branch still prints FD table pre-warmed successfully. which is misleading.

Suggested adjustment
 fn main() {
     const FD_TARGET: u32 = 10_000;

     println!("Pre-warming FD table to {FD_TARGET} entries...");
-    if let Err(e) = prewarm_fd_table(FD_TARGET) {
-        eprintln!("Warning: failed to pre-warm FD table: {e}");
-    } else {
-        println!("FD table pre-warmed successfully.");
-    }
+    #[cfg(target_os = "linux")]
+    {
+        if let Err(e) = prewarm_fd_table(FD_TARGET) {
+            eprintln!("Warning: failed to pre-warm FD table: {e}");
+        } else {
+            println!("FD table pre-warmed successfully.");
+        }
+    }
+    #[cfg(not(target_os = "linux"))]
+    {
+        let _ = prewarm_fd_table(FD_TARGET);
+        println!("Skipping FD table pre-warm (Linux-only workaround).");
+    }

     // Build the runtime *after* pre-warming.
📝 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
if let Err(e) = prewarm_fd_table(FD_TARGET) {
eprintln!("Warning: failed to pre-warm FD table: {e}");
} else {
println!("FD table pre-warmed successfully.");
}
#[cfg(target_os = "linux")]
{
if let Err(e) = prewarm_fd_table(FD_TARGET) {
eprintln!("Warning: failed to pre-warm FD table: {e}");
} else {
println!("FD table pre-warmed successfully.");
}
}
#[cfg(not(target_os = "linux"))]
{
let _ = prewarm_fd_table(FD_TARGET);
println!("Skipping FD table pre-warm (Linux-only workaround).");
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/prewarm-fd-table.rs` around lines 65 - 69, The code prints "FD table
pre-warmed successfully." even on non-Linux where prewarm_fd_table(FD_TARGET) is
a no-op; change the logic so the success message is only emitted when the
pre-warm actually ran (e.g., guard the println! with cfg!(target_os = "linux")
or adjust prewarm_fd_table to return a boolean/enum indicating it performed work
and print only when that indicates success). Update the branch around the call
to prewarm_fd_table(FD_TARGET) (and the associated success println!) to rely on
that condition so non-Linux platforms no longer show a false success.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

value:good-to-have; category:bug; feedback: The CodeRabbit AI reviewer is correct! The whole example does not make sense for non-Linux runs. It would be better to return early in main() with a message printed on the stdout that the example does nothing on non-Linux. Currently it prints success messages even when it did nothing and this may confuse the users.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants