Skip to content

Conversation

@Stexxe
Copy link
Contributor

@Stexxe Stexxe commented Jun 3, 2025

To avoid the race condition, we will wait for Netty to finish discarding certain headers like Content-Length for informational and 204 responses.
https://youtrack.jetbrains.com/issue/KTOR-8528

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 3, 2025

Walkthrough

An internal suspend function was added to the Netty server response implementation to suspend coroutine processing for informational (1xx) or no-content (204) HTTP statuses after sending the response. A new test verifies that "Content-Length" and "Transfer-Encoding" headers are removed for 204 and 1xx responses.

Changes

File(s) Change Summary
.../ktor-server-netty/jvm/src/io/ktor/server/netty/NettyApplicationResponse.kt Added private suspend function to suspend after sending informational or no-content responses; updated import and usage of CancellationException.
.../ktor-server-netty/jvm/test/io/ktor/tests/server/netty/NettySpecificTest.kt Added test contentLengthAndTransferEncodingAreSafelyRemoved verifying absence of headers for 204 and 1xx responses.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bc96579 and 1018552.

📒 Files selected for processing (1)
  • ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyApplicationResponse.kt (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyApplicationResponse.kt
✨ Finishing Touches
  • 📝 Generate Docstrings

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

@Stexxe Stexxe marked this pull request as ready for review June 7, 2025 11:39
@Stexxe Stexxe requested review from bjhham and e5l June 7, 2025 11:41
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
ktor-server/ktor-server-netty/jvm/test/io/ktor/tests/server/netty/NettySpecificTest.kt (1)

90-171: Comprehensive test coverage with minor improvements needed.

The test effectively validates the race condition fix by verifying header removal for informational and no-content responses across different response mechanisms. The use of ResponseSent hook to assert header absence is well-designed.

Consider these improvements:

  1. Route path consistency: Some routes use leading slashes ("/no-content", "/info") while others don't ("no-content-channel-writer"). Standardize for consistency.

  2. Error handling: Add error handling for server startup failures in the launch block.

  3. Test scope cleanup: Consider using TestScope or ensure proper cleanup of the testScope coroutine context.

-                    get("no-content-channel-writer") {
+                    get("/no-content-channel-writer") {
                        call.respondBytesWriter(status = HttpStatusCode.NoContent) {}
                    }

-                    get("no-content-read-channel") {
+                    get("/no-content-read-channel") {
                        call.respond(object : OutgoingContent.ReadChannelContent() {
                            override val status: HttpStatusCode = HttpStatusCode.NoContent
                            override fun readFrom(): ByteReadChannel = ByteReadChannel.Empty
                        })
                    }

-                    get("info-channel-writer") {
+                    get("/info-channel-writer") {
                        call.respondBytesWriter(status = earlyHints) {}
                    }

-                    get("info-read-channel") {
+                    get("/info-read-channel") {
                        call.respond(object : OutgoingContent.ReadChannelContent() {
                            override val status: HttpStatusCode = earlyHints
                            override fun readFrom(): ByteReadChannel = ByteReadChannel.Empty
                        })
                    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd41f80 and 3526740.

📒 Files selected for processing (3)
  • ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyApplicationResponse.kt (4 hunks)
  • ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/NettyHttpResponsePipeline.kt (1 hunks)
  • ktor-server/ktor-server-netty/jvm/test/io/ktor/tests/server/netty/NettySpecificTest.kt (2 hunks)
🔇 Additional comments (5)
ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/NettyHttpResponsePipeline.kt (1)

74-76: LGTM: Proper synchronization for race condition fix.

The addition of sendCompleted.complete(Unit) for informational and no-content responses in the finally block correctly addresses the race condition described in KTOR-8528. This ensures that response methods awaiting sendCompleted are properly resumed after the response processing is complete.

ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyApplicationResponse.kt (4)

37-37: Well-designed lazy initialization for synchronization.

Using lazy for the sendCompleted deferred is efficient - it only creates the deferred when needed for informational or no-content responses.


73-76: Correct status code detection logic.

The isInfoOrNoContentStatus() function correctly identifies:

  • HTTP 204 No Content responses
  • Informational 1xx status codes (100-199 range)

This matches the HTTP specification requirements for responses that should not have content-related headers.


143-143: Improved exception specificity.

Using CancellationException instead of a generic exception provides better error semantics for response cancellation scenarios.


68-70:

✅ Verification successful

Verify sendCompleted is always completed to prevent hanging.

The synchronization logic correctly suspends response methods for special status codes until the pipeline completes processing. However, ensure that sendCompleted is always completed in all code paths to prevent indefinite suspension.

Also applies to: 83-85


🏁 Script executed:

#!/bin/bash
# Verify that sendCompleted.complete() is called in all relevant code paths
# Expected: Find completion calls in NettyHttpResponsePipeline and potential error handling paths

echo "=== Searching for sendCompleted.complete() calls ==="
rg -A 3 -B 3 "sendCompleted\.complete"

echo -e "\n=== Searching for sendCompleted usage ==="
rg -A 5 -B 2 "sendCompleted"

echo -e "\n=== Checking error handling in NettyHttpResponsePipeline ==="
rg -A 10 -B 5 "respondWithFailure.*NettyApplicationCall"

Length of output: 6966


sendCompleted completion verified
A search confirms that sendCompleted.complete(Unit) is invoked in the finally block of
ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/cio/NettyHttpResponsePipeline.kt
for all INFO and NO_CONTENT status paths, guaranteeing sendCompleted.await() will always resume.

@Stexxe Stexxe requested a review from bjhham June 9, 2025 14:06
@e5l e5l requested a review from Copilot June 10, 2025 07:24
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes a race condition in Netty where Content-Length and Transfer-Encoding headers could be removed too early for 204 (No Content) and 1xx (informational) responses by awaiting the response write job, and it adds a test to verify header removal.

  • Await responseWriteJob before headers are stripped in NettyApplicationResponse
  • Add contentLengthAndTransferEncodingAreSafelyRemoved test in NettySpecificTest

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
ktor-server/ktor-server-netty/jvm/test/io/ktor/tests/server/netty/NettySpecificTest.kt Added async test verifying headers are removed for 204 and 1xx responses
ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyApplicationResponse.kt Added waiting logic for responseWriteJob on info/NoContent statuses and streamlined CancellationException import
Comments suppressed due to low confidence (1)

ktor-server/ktor-server-netty/jvm/test/io/ktor/tests/server/netty/NettySpecificTest.kt:99

  • [nitpick] The plugin name 'CallLogging' duplicates an existing Ktor plugin, which may cause confusion or conflicts. Consider renaming it to something more descriptive like 'ContentHeaderRemovalVerifier'.
createApplicationPlugin("CallLogging") {

Comment on lines 65 to 69
if (isInfoOrNoContentStatus()) {
if (call is NettyApplicationCall) {
(call as NettyApplicationCall).responseWriteJob.join()
}
}
Copy link

Copilot AI Jun 10, 2025

Choose a reason for hiding this comment

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

The logic to await responseWriteJob for informational and NoContent statuses is duplicated in both sendResponse and responseChannel. Consider extracting this into a shared private method to reduce duplication and improve maintainability.

Suggested change
if (isInfoOrNoContentStatus()) {
if (call is NettyApplicationCall) {
(call as NettyApplicationCall).responseWriteJob.join()
}
}
awaitResponseWriteJobIfNeeded()

Copilot uses AI. Check for mistakes.
Comment on lines 66 to 68
if (call is NettyApplicationCall) {
(call as NettyApplicationCall).responseWriteJob.join()
}
Copy link

Copilot AI Jun 10, 2025

Choose a reason for hiding this comment

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

[nitpick] After checking 'call is NettyApplicationCall', you can simplify the cast by using a safe cast ('call as? NettyApplicationCall') and a safe call, eliminating the need for a separate instance check.

Suggested change
if (call is NettyApplicationCall) {
(call as NettyApplicationCall).responseWriteJob.join()
}
(call as? NettyApplicationCall)?.responseWriteJob?.join()

Copilot uses AI. Check for mistakes.
Copy link
Member

@e5l e5l left a comment

Choose a reason for hiding this comment

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

Could you explain in the PR body why the response headers were removed?

@Stexxe Stexxe requested review from bjhham and e5l June 10, 2025 08:52
@Stexxe Stexxe merged commit b55490f into main Jun 11, 2025
15 of 18 checks passed
@Stexxe Stexxe deleted the stexxe/netty-headers-removal-race branch June 11, 2025 07:52
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.

4 participants