Skip to content

Reset ConcurrencyDetector when a pooled context is returned - #38995

Merged
AndriySvyryd merged 2 commits into
dotnet:mainfrom
LuKuanTsen:fix/concurrency-detector-pool-reset
Sep 15, 2026
Merged

AndriySvyryd merged 2 commits into
dotnet:mainfrom
LuKuanTsen:fix/concurrency-detector-pool-reset

Conversation

@LuKuanTsen

Copy link
Copy Markdown
Contributor

Fixes #38983

ConcurrencyDetector was never reset when a pooled DbContext was returned to the pool, and EnterCriticalSection/ExitCriticalSection toggled _inCriticalSection around an allocating AsyncLocal<int> write. If that write threw (in practice OutOfMemoryException, see #22802), the flag stayed set, the context went back to the pool as usual, and every later lease of that instance failed with "A second operation was started on this context instance" for the life of the process.

Two independent changes, no behaviour change on the happy path and no public API change:

  1. Reset on return to pool. ConcurrencyDetector implements IResettableService, and StateManager.ResetState() resets it alongside _changeDetector. A context now always starts its next lease with a clear detector, whatever happened on the previous one. (The DI-registration variant, IConcurrencyDetector : IResettableService, is described in the issue; it is cleaner but changes public API, so this PR keeps the servicing-friendly shape. Happy to switch if preferred.)
  2. Don't leave the flag set if the AsyncLocal write throws. EnterCriticalSection releases the flag if ThreadAcquiredLocksCount.Value++ throws before a disposer is handed out (only when this call took the flag, i.e. it is not a re-entrant call). ExitCriticalSection clears the flag before the AsyncLocal decrement instead of after.

One behaviour note for reviewers: the reset in (1) is unconditional. A context returned to the pool while an operation is still genuinely in flight used to throw on the next lease; now the next lease proceeds. StateManager.ResetState() already clears tracked state under such an orphaned operation, so the old exception was late and attributed to the wrong request rather than a real guard.

Tests (ConcurrencyDetectorTest):

  • Pooled_context_can_be_reused_after_critical_section_was_never_exited: red before, green after.
  • ResetState_releases_critical_section_that_was_never_exited.
  • Nested_critical_sections_are_released_when_outermost_exits: regression fence for the Exit reorder.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Mq2nwPJvGQb6LEyRLVFWKP

Copilot AI left a comment

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.

🟡 Changes recommended

A critical concurrency race remains in ConcurrencyDetector exception cleanup.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Updates pooled DbContext reuse by resetting ConcurrencyDetector state and making critical-section bookkeeping exception-safe.

Changes:

  • Adds detector reset support.
  • Resets the detector through StateManager.
  • Adds pooling and nesting regression tests.
File summaries
File Summary
test/EFCore.Tests/Infrastructure/Internal/ConcurrencyDetectorTest.cs Adds regression coverage.
src/EFCore/Infrastructure/Internal/ConcurrencyDetector.cs Implements reset and safer enter/exit handling.
src/EFCore/ChangeTracking/Internal/StateManager.cs Resets the detector during context reset.
Review details

Suppressed comments (1)

src/EFCore/Infrastructure/Internal/ConcurrencyDetector.cs:80

  • Resetting these counters makes a disposer from the previous lease indistinguishable from one created by the next lease. If an async query is still in flight when the context is returned (the PR explicitly allows the next lease to proceed), its using var _ = EnterCriticalSection() will later call ExitCriticalSection; after the new lease has entered, that old exit can decrement the new _currentContextRefCount and clear _inCriticalSection while the new operation is active, disabling the guard. The reset/disposer protocol needs to invalidate old sections or otherwise prevent reuse until they exit.
    public virtual void ResetState()
    {
        _currentContextRefCount = 0;
        _inCriticalSection = 0;
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@LuKuanTsen

Copy link
Copy Markdown
Contributor Author

@dotnet-policy-service agree

@LuKuanTsen

Copy link
Copy Markdown
Contributor Author

On the suppressed note about ResetState() and a disposer from a previous lease exiting after the next lease has entered: that scenario requires the caller to still be using a context after it was returned to the pool, which is already a misuse (StateManager.ResetState() has cleared its tracked state underneath it). Its effect is confined to that one lease and is cleared by the next reset. Making stale disposers inert would need a lease token on ConcurrencyDetectorCriticalSectionDisposer / IConcurrencyDetector, i.e. a public API change; I have kept this PR servicing-friendly and left that as a follow-up if the team wants it.

Copilot AI left a comment

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.

🟡 Changes recommended

Active disposers from a prior lease can corrupt the detector state after pooled reuse.

Get a fresh assessment by requesting another Copilot review.

Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Lite

@AndriySvyryd AndriySvyryd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for your contribution!
However, since this is for an unsupported scenario, the fix won't be ported to earlier versions.

@AndriySvyryd
AndriySvyryd merged commit 1e4880b into dotnet:main Sep 15, 2026
15 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Sep 16, 2026
@LuKuanTsen

Copy link
Copy Markdown
Contributor Author

Hi @AndriySvyryd , why wouldn't this be ported on 10 and 11.
Given this is considering a bug and 10 is LTS version.

@AndriySvyryd

Copy link
Copy Markdown
Member

@LuKuanTsen It's not a supported scenario, so it doesn't meet the servicing bar

AndriySvyryd pushed a commit that referenced this pull request Sep 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

3 participants