Skip to content

Fix asymmetric Observation scope propagation in Kotlin Coroutines - #36955

Closed
arnabnandy7 wants to merge 1 commit into
spring-projects:mainfrom
arnabnandy7:fix/issue-36929-propagation-scope
Closed

arnabnandy7 wants to merge 1 commit into
spring-projects:mainfrom
arnabnandy7:fix/issue-36929-propagation-scope

Conversation

@arnabnandy7

Copy link
Copy Markdown

Summary

This PR addresses issue #36929 where Kotlin flow-to-flux subscriptions using PropagationContextElement open Observation scopes asymmetrically, causing AssertionError crashes in ObservationThreadLocalAccessor.restore.

Cause of the Issue

During undispatched coroutine context modifications (e.g., from ChannelFlowKt.withContextUndispatched nested inside the flow's execution path), updateThreadContext is called nestedly on the same thread. When a coroutine suspends within the nested block:

  1. The execution pauses, meaning the finally block of the nested block (which calls restoreThreadContext to close the nested scope) is NOT executed.
  2. The outer coroutine dispatcher's suspension cleanup runs and executes the outer restoreThreadContext.
  3. Because the nested scope was never closed, the outer restoreThreadContext attempts to close the outer scope but finds a dirty thread-local observation stack (with the nested scope still on top), causing Micrometer's assertion to trip.

Solution

We introduce a static ThreadLocal<Integer> nestingDepth tracker inside PropagationContextElement:

  • When updateThreadContext is called, we increment nestingDepth.
  • If the depth is greater than 1 (meaning propagation is already active on the current thread), we return a no-op Scope implementation, avoiding nested/asymmetric thread-local scope pushes.
  • For the outermost update (depth = 1), we return a WrapperScope that delegates to the original snapshot scope and resets the nestingDepth to 0 when closed.

Verification

Added a unit test nestedInvocations in PropagationContextElementTests which simulates nested context updates and outer/nested restorations, verifying that no assertion errors are thrown and the Observation stack remains balanced. All tests in spring-core compiled and passed.

@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Jun 20, 2026
Introduce a ThreadLocal nesting check inside PropagationContextElement to prevent duplicate/asymmetric thread-local scope updates during nested undispatched coroutine context changes.

Closes spring-projects#36929

Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
@arnabnandy7
arnabnandy7 force-pushed the fix/issue-36929-propagation-scope branch from 384f831 to 40ce895 Compare June 20, 2026 19:55
@bclozel bclozel added the in: core Issues in core modules (aop, beans, core, context, expression) label Sep 4, 2026
@bclozel

bclozel commented Sep 7, 2026

Copy link
Copy Markdown
Member

@arnabnandy7 I would you like to get your personal opinion on the matter.

Why do you consider this to be an issue in Spring Framework and suggest a fix here? In your experience, is this coroutines should behave with regards to the PropagationContextElement implemented in Spring? Can you elaborate?

Your PR currently suggests to maintain a thread local value on the carrier thread on a per element basis. Given that Framework is using Dispatchers.Unconfined by default, wouldn't this cause issues on a thread pool?

Thanks

@bclozel bclozel self-assigned this Sep 7, 2026
@bclozel bclozel added the status: waiting-for-feedback We need additional information before we can continue label Sep 7, 2026
@arnabnandy7

Copy link
Copy Markdown
Author

Thanks @bclozel, those are fair concerns. I focused on Spring because the report linked the regression to adding PropagationContextElement to the Flow-to-Flux adapter in #36667. Looking at it again, that explains where the failure became visible, but doesn’t establish that the underlying bug belongs in Spring.

I took the reported two updates followed by one restore as a reason to suppress nested updates. That was too strong an assumption without reproducing the coroutine lifecycle. Nested updates can be legitimate, and I haven’t established why the corresponding restoration is missing or delayed.

Your thread-pool concern also exposes a weakness in this approach. The counter is actually static, so it is shared across all element instances on a thread. A nested invocation carrying a different context would be skipped too. With Dispatchers.Unconfined allowing execution to resume on different threads, I don’t think the current test gives enough confidence in this guard.

The test only exercises a manually constructed update/restore sequence. I’d like to revisit this with an actual Flow subscription reproduction, including suspension and different nested contexts, before proposing a revised fix. I agree the current implementation needs more investigation.

@spring-projects-issues spring-projects-issues added status: feedback-provided Feedback has been provided and removed status: waiting-for-feedback We need additional information before we can continue labels Sep 7, 2026
@bclozel bclozel added status: waiting-for-feedback We need additional information before we can continue and removed status: feedback-provided Feedback has been provided labels Sep 7, 2026
@arnabnandy7

Copy link
Copy Markdown
Author

Closing this PR as we've confirmed the root cause is in kotlinx.coroutines's withContextUndispatched scope lifetime across suspensions.

I've submitted an upstream fix with reproduction tests here: Kotlin/kotlinx.coroutines#4756 (addressing Kotlin/kotlinx.coroutines#4754).

cc @bclozel

@bclozel bclozel added status: invalid An issue that we don't feel is valid and removed status: waiting-for-feedback We need additional information before we can continue status: waiting-for-triage An issue we've not yet triaged or decided on labels Sep 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

in: core Issues in core modules (aop, beans, core, context, expression) status: invalid An issue that we don't feel is valid

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants