Skip to content

fix(cache): release query runner on error in storeInCache - #12545

Merged
gioboa merged 2 commits into
typeorm:masterfrom
francisjohnjohnston-web:fix/cache-query-runner-leak
Jun 4, 2026
Merged

gioboa merged 2 commits into
typeorm:masterfrom
francisjohnjohnston-web:fix/cache-query-runner-leak

Conversation

@francisjohnjohnston-web

@francisjohnjohnston-web francisjohnjohnston-web commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

When storeInCache creates an internal master query runner (slave or undefined caller), a throwing execute() left the pooled connection unreleased. Wrap the execute block in try/finally so release always runs on the internally-created runner.

Description of change

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

🛡️ Security fixes: Do not submit security fixes as public PRs — the diff exposes the vulnerability. Use GitHub Security Advisories instead.

When storeInCache creates an internal master query runner (slave or
undefined caller), a throwing execute() left the pooled connection
unreleased. Wrap the execute block in try/finally so release always
runs on the internally-created runner.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented May 25, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (1)

Grey Divider


Remediation recommended

1. Release masks execute error 🐞 Bug ☼ Reliability ⭐ New
Description
In DbQueryResultCache.storeInCache, an exception thrown by queryRunner.release() inside
finally can override an earlier execute()/insert().execute() exception, changing the surfaced
failure and hiding the real DB error. This is possible because some QueryRunner.release()
implementations in this repo can throw (e.g., SAP driver rethrows disconnect failures).
Code

src/cache/DbQueryResultCache.ts[R296-299]

+        } finally {
+            if (shouldCreateQueryRunner) {
+                await queryRunner.release()
            }
-
-            // otherwise insert
-            await queryRunner.manager
-                .createQueryBuilder()
-                .insert()
-                .into(this.queryResultCacheTable)
-                .values(insertedValues)
-                .execute()
-        }
-
-        if (shouldCreateQueryRunner) {
-            await queryRunner.release()
Evidence
The new code awaits queryRunner.release() inside finally, which can override an earlier thrown
error. This matters because at least one QueryRunner.release() implementation in the repo (SAP)
explicitly rethrows failures during connection disconnect, proving release() can throw.

src/cache/DbQueryResultCache.ts[224-301]
src/driver/sap/SapQueryRunner.ts[90-104]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`DbQueryResultCache.storeInCache` always awaits `queryRunner.release()` in a `finally` block when it created the runner. If the DB operation throws (e.g. `qb.execute()`), and `release()` also throws, the `release()` error will mask the original DB failure.

### Issue Context
Some driver implementations can throw from `release()` (e.g. SAP uses `disconnect()` and rethrows on error), so masking is not theoretical.

### Fix
Restructure `storeInCache` to preserve the original error:
- Capture the “main” error from the cache write.
- In `finally`, wrap `release()` in its own `try/catch`.
- If there was already a main error, **do not throw** the release error (log it as `warn` instead); if there was no main error, rethrow the release error.

Pseudo-pattern:
```ts
let mainError: unknown
try {
 ...
} catch (e) {
 mainError = e
 throw e
} finally {
 if (shouldCreateQueryRunner) {
   try {
     await queryRunner.release()
   } catch (releaseError) {
     if (mainError) {
       this.dataSource.logger.log("warn", releaseError, queryRunner)
     } else {
       throw releaseError
     }
   }
 }
}
```

### Fix Focus Areas
- src/cache/DbQueryResultCache.ts[224-301]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. No functional test for leak 📘 Rule violation ☼ Reliability
Description
This PR fixes an internal query runner release leak in DbQueryResultCache.storeInCache by wrapping
the DB cache persistence path in a try/finally, but it does not add or update any functional tests
to prevent regressions. Without a regression test that covers the execute()-throws path, a future
refactor could reintroduce the pooled connection leak unnoticed.
Code

src/cache/DbQueryResultCache.ts[R249-300]

Evidence
PR Compliance ID 3 requires issue fixes to be covered by functional tests, and the diff shows a
bugfix-style change where storeInCache now uses a try/finally to ensure an internally-created
QueryRunner is released even when qb.execute() fails. However, there are no corresponding test
changes in the PR diff, and the described existing coverage focuses on Redis cache storage and
query-builder caching happy paths rather than asserting queryRunner.release() is invoked when DB
cache persistence fails (the original leak scenario).

Rule 3: Prefer functional tests over per-issue tests
src/cache/DbQueryResultCache.ts[249-300]
src/cache/DbQueryResultCache.ts[224-301]
src/query-builder/SelectQueryBuilder.ts[3831-3855]
test/unit/cache/redis-query-result-cache.test.ts[47-96]
test/functional/query-builder/cache/query-builder-cache.test.ts[12-93]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A resource-leak fix was added in `DbQueryResultCache.storeInCache` by releasing an internally-created master `QueryRunner` in a `finally` block, but there is no accompanying regression/functional test to ensure the query runner (and underlying pooled connection) is released when the DB cache write path fails (e.g., when `execute()` throws).
## Issue Context
- Per the checklist (PR Compliance ID 3), issue fixes should be covered by the functional test suite to prevent regressions.
- Production code reaches this path via `SelectQueryBuilder` calling `queryResultCache.storeInCache(...)`.
- Current tests are described as covering Redis `storeInCache` happy paths and query-builder caching success paths, but nothing asserts `QueryRunner.release()` is executed when DB cache persistence fails (the original leak scenario).
## Fix Focus Areas
- src/cache/DbQueryResultCache.ts[224-301]
- src/query-builder/SelectQueryBuilder.ts[3831-3855]
- test/unit/cache/redis-query-result-cache.test.ts[47-96]
- test/functional/query-builder/cache/query-builder-cache.test.ts[12-93]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Previous review results

Review updated until commit 35ab9a6

Results up to commit 1feec6a


🐞 Bugs (0) 📘 Rule violations (1)


Remediation recommended
1. No functional test for leak 📘 Rule violation ☼ Reliability
Description
This PR fixes an internal query runner release leak in DbQueryResultCache.storeInCache by wrapping
the DB cache persistence path in a try/finally, but it does not add or update any functional tests
to prevent regressions. Without a regression test that covers the execute()-throws path, a future
refactor could reintroduce the pooled connection leak unnoticed.
Code

src/cache/DbQueryResultCache.ts[R249-300]

Evidence
PR Compliance ID 3 requires issue fixes to be covered by functional tests, and the diff shows a
bugfix-style change where storeInCache now uses a try/finally to ensure an internally-created
QueryRunner is released even when qb.execute() fails. However, there are no corresponding test
changes in the PR diff, and the described existing coverage focuses on Redis cache storage and
query-builder caching happy paths rather than asserting queryRunner.release() is invoked when DB
cache persistence fails (the original leak scenario).

Rule 3: Prefer functional tests over per-issue tests
src/cache/DbQueryResultCache.ts[249-300]
src/cache/DbQueryResultCache.ts[224-301]
src/query-builder/SelectQueryBuilder.ts[3831-3855]
test/unit/cache/redis-query-result-cache.test.ts[47-96]
test/functional/query-builder/cache/query-builder-cache.test.ts[12-93]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A resource-leak fix was added in `DbQueryResultCache.storeInCache` by releasing an internally-created master `QueryRunner` in a `finally` block, but there is no accompanying regression/functional test to ensure the query runner (and underlying pooled connection) is released when the DB cache write path fails (e.g., when `execute()` throws).

## Issue Context
- Per the checklist (PR Compliance ID 3), issue fixes should be covered by the functional test suite to prevent regressions.
- Production code reaches this path via `SelectQueryBuilder` calling `queryResultCache.storeInCache(...)`.
- Current tests are described as covering Redis `storeInCache` happy paths and query-builder caching success paths, but nothing asserts `QueryRunner.release()` is executed when DB cache persistence fails (the original leak scenario).

## Fix Focus Areas
- src/cache/DbQueryResultCache.ts[224-301]
- src/query-builder/SelectQueryBuilder.ts[3831-3855]
- test/unit/cache/redis-query-result-cache.test.ts[47-96]
- test/functional/query-builder/cache/query-builder-cache.test.ts[12-93]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@gioboa
gioboa enabled auto-merge (squash) June 4, 2026 19:16
@pkg-pr-new

pkg-pr-new Bot commented Jun 4, 2026

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm@12545
    

commit: 35ab9a6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants