Skip to content

KTOR-9544 Apache: Attach response body channel to callContext#5566

Draft
osipxd wants to merge 1 commit intomainfrom
osipxd/apache-response-cancelling
Draft

KTOR-9544 Apache: Attach response body channel to callContext#5566
osipxd wants to merge 1 commit intomainfrom
osipxd/apache-response-cancelling

Conversation

@osipxd
Copy link
Copy Markdown
Member

@osipxd osipxd commented Apr 30, 2026

Subsystem
ktor-client-apache5

Motivation
KTOR-9544 Apache: body channel not cancelled when caller scope is cancelled

Solution
Attach the response body channel to callContext's job directly (matching CIO/OkHttp/Apache pattern) so caller-scope cancellation propagates the exact cause to closedCause. Previously the channel was attached to an intermediate consumerJob, causing cause wrapping that made closedCause unreachable.

Also silently discard data in consume() when the channel is closed instead of throwing. Throwing (even IOException per the interface contract) triggers Apache's error-recovery path mid-body-stream, which either corrupts connection pool state or causes a RejectedExecutionException on an already-shutdown scheduler.

…card data after cancellation

Attach the response body channel to `callContext`'s job directly (matching
CIO/OkHttp/Apache pattern) so caller-scope cancellation propagates the
exact cause to `closedCause`. Previously the channel was attached to an
intermediate `consumerJob`, causing cause wrapping that made `closedCause`
unreachable.

Also silently discard data in `consume()` when the channel is closed instead
of throwing. Throwing (even `IOException` per the interface contract) triggers
Apache's error-recovery path mid-body-stream, which either corrupts
connection pool state or causes a `RejectedExecutionException` on an
already-shutdown scheduler.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@osipxd osipxd self-assigned this Apr 30, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 30, 2026

📝 Walkthrough

Walkthrough

Adjustments to Apache5 client's coroutine job lifecycle and channel closure handling: internal job wiring now anchors to parentContext.job, and consume(ByteBuffer) no longer throws on closed channels. A test enabling Apache5 support for caller-scope cancellation was also activated.

Changes

Cohort / File(s) Summary
Apache5 Response Consumer Job Wiring
ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheResponseConsumer.kt
Modified coroutine job attachment to use parentContext.job directly instead of deriving from parentContext[Job]. Removed throwing of channel.closedCause in consume(ByteBuffer) to prevent mid-stream exceptions when channel is closed for write.
Content Test Configuration
ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt
Removed Apache5 exclusion from testBodyChannelCancelledWhenCallerScopeIsCancelled test and removed related KTOR-9544 flakiness comment.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • ktorio/ktor#5526: Modifies the same ApacheResponseConsumer class with result-callback handling and completion triggers that align with the job wiring changes.
  • ktorio/ktor#5564: Related approach to propagating caller-scope cancellation through response body channel lifecycle in a different HTTP client engine.

Suggested reviewers

  • bjhham
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately references the issue (KTOR-9544) and clearly describes the main fix: attaching the response body channel to callContext, which directly addresses the motivation.
Description check ✅ Passed The description follows the template with clear subsystem, motivation (linked to KTOR-9544), and detailed solution explaining both the job attachment fix and the silent buffer discard behavior.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 osipxd/apache-response-cancelling

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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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

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

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

Inline comments:
In
`@ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheResponseConsumer.kt`:
- Around line 104-107: The cancellation currently calls
responseChannel.cancel(cause) in parentContext.job.invokeOnCompletion which can
let already-queued payloads reach the writer and have writeFully throw, aborting
the queue coroutine before a CloseChannel is processed; to fix, change the
cancellation handler to close the channel (responseChannel.close(cause)) or
otherwise atomically mark it closed so queued items are protected, and harden
the queue/writer loop that calls writeFully to catch exceptions (including from
writes after cancellation), swallow or translate them into a terminal state, and
always enqueue/dispatch the CloseChannel sentinel; update the code paths around
parentContext.job.invokeOnCompletion, responseChannel usage, the writeFully
calls, and the CloseChannel enqueue logic so queued chunks cannot cause the
queue coroutine to abort before CloseChannel is consumed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a5467358-b0c2-4c9e-a2e1-e38a8ee02caf

📥 Commits

Reviewing files that changed from the base of the PR and between ff6cb6d and b306d09.

📒 Files selected for processing (2)
  • ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheResponseConsumer.kt
  • ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/ContentTest.kt

Comment on lines +104 to 107
parentContext.job.invokeOnCompletion(onCancelling = true) { cause ->
if (cause != null) {
responseChannel.cancel(cause)
}
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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Protect queued writes after cancellation to avoid coroutine abort before close callback.

Line [147] drops only new chunks. Chunks queued before cancellation can still hit Line [117] after Line [104] cancels the channel, where writeFully may throw and terminate the queue coroutine before CloseChannel is consumed.

💡 Proposed fix
                 is ByteBuffer -> {
+                    if (channel.isClosedForWrite) continue
                     val written = message.remaining()
-                    channel.writeFully(message)
-                    channel.flush()
+                    try {
+                        channel.writeFully(message)
+                        channel.flush()
+                    } catch (cause: Throwable) {
+                        if (channel.isClosedForWrite || cause is CancellationException) continue
+                        throw cause
+                    }
                     when (val channel = capacityChannel) {
                         null -> capacity.addAndGet(written)
                         else -> channel.update(written)
                     }
                 }

Also applies to: 115-118, 143-149

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@ktor-client/ktor-client-apache5/jvm/src/io/ktor/client/engine/apache5/ApacheResponseConsumer.kt`
around lines 104 - 107, The cancellation currently calls
responseChannel.cancel(cause) in parentContext.job.invokeOnCompletion which can
let already-queued payloads reach the writer and have writeFully throw, aborting
the queue coroutine before a CloseChannel is processed; to fix, change the
cancellation handler to close the channel (responseChannel.close(cause)) or
otherwise atomically mark it closed so queued items are protected, and harden
the queue/writer loop that calls writeFully to catch exceptions (including from
writes after cancellation), swallow or translate them into a terminal state, and
always enqueue/dispatch the CloseChannel sentinel; update the code paths around
parentContext.job.invokeOnCompletion, responseChannel usage, the writeFully
calls, and the CloseChannel enqueue logic so queued chunks cannot cause the
queue coroutine to abort before CloseChannel is consumed.

@osipxd osipxd marked this pull request as draft April 30, 2026 08:40
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.

1 participant