Skip to content

Conversation

@jye326
Copy link

@jye326 jye326 commented Jan 18, 2026

Description

This PR fixes a potential memory leak in DataSourceObservationListener that can occur during query execution when ExecutionInfo loses its context (for example, due to connection eviction or forced closure).

It addresses the issue reported in #91


Changes

  • Fallback logic in stopQueryObservation
    If the Observation.Scope cannot be retrieved from ExecutionInfo, the listener now performs a defensive cleanup by ensuring that any active observation scope associated with the current thread is properly closed. This guarantees that the scope opened in beforeQuery is always closed, preventing ThreadLocal leaks.

  • Null safety improvement
    Added a null check for QueryContext before calling setAffectedRowCount to prevent a potential NullPointerException in edge cases where the context may be missing.

  • Test case added
    Added memoryLeakWhenConnectionForciblyClosedAndExecutionInfoLost to DataSourceObservationListenerTests.
    This test simulates a scenario where ExecutionInfo fails to return the stored scope and verifies that the fallback logic correctly cleans up the observation registry.


Verification

  • Added a new unit test:
    DataSourceObservationListenerTests#memoryLeakWhenConnectionForciblyClosedAndExecutionInfoLost

  • Verified that all tests pass by running:

    ./mvnw test

- Add fallback mechanism to retrieve `Observation.Scope` from the registry when unavailable in `ExecutionInfo`.
- Prevent potential memory leaks by checking for `QueryContext` nullability before setting `affectedRowCount`.
- Add test to reproduce and verify the fix for handling lost `ExecutionInfo` scenarios.
- Ensure `Observation.Scope` is closed if `addCustomValue` throws an exception in `beforeQuery`.
- Simplify logic in `afterQuery` by removing redundant fallback to registry scope.
- Add test to verify proper scope closure when `beforeQuery` fails.
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