Skip to content

fix(mysql): destroy connection when SET time_zone fails during connect - #18267

Closed
xianjianlf2 wants to merge 6 commits into
sequelize:mainfrom
xianjianlf2:fix/mysql-connect-timezone-leak-18266
Closed

xianjianlf2 wants to merge 6 commits into
sequelize:mainfrom
xianjianlf2:fix/mysql-connect-timezone-leak-18266

Conversation

@xianjianlf2

@xianjianlf2 xianjianlf2 commented Jul 18, 2026 •

Copy link
Copy Markdown

Pull Request Checklist

  • Have you added new tests to prevent regressions?
  • If a documentation update is necessary, have you opened a PR to the documentation repository? — n/a, no user-facing API change
  • Did you update the typescript typings accordingly (if applicable)? — n/a
  • Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
  • Does the name of your PR follow our conventions?

Description of Changes

Closes #18266

When the mysql dialect's connect() successfully creates the mysql2 connection but the subsequent SET time_zone query fails (as reported against RDS Aurora returning ER_OUT_OF_RESOURCES), the error propagated through the outer catch without the socket ever being closed. The pool never receives the connection, so every failed attempt orphans a live connection — a leak that compounds under retry.

The fix wraps the timezone query in a try/catch that calls connection.destroy() before rethrowing; the outer catch still wraps the error into ConnectionError exactly as before, so error semantics are unchanged. The code also documents why this uses destroy() instead of end(): the setup query failure leaves the connection state uncertain, and end() could reject and mask the original error.

Adds packages/mysql/src/connection-manager.test.ts (first unit coverage for this connection manager), injecting a fake mysql2Module via the documented dialect option: the new test was red before the fix (destroyCallCount 0, expected 1) and green after. It also asserts that end() is not called on the failed setup path, locking in the destroy-not-end behavior. Whole mysql unit suite passing after yarn build; tsc --noEmit, eslint, prettier clean.

MariaDB was checked and is unaffected by this PR's MySQL-specific path: its timezone initialization is routed through the driver's initSql, and the driver handles socket cleanup on init-SQL failure.

List of Breaking Changes

None.

Summary by CodeRabbit

  • Bug Fixes

    • Improved MySQL connection handling by ensuring connections are properly destroyed when session timezone initialization fails.
    • Preserved the original timezone setup error for clearer failure reporting.
  • Tests

    • Expanded coverage for MySQL connection setup success and failure scenarios.
    • Verified that failed setup uses connection destruction without unnecessarily calling the normal connection-ending flow.

Validation update (2026-09-22)

Merged current upstream main, including its database CI service updates. The PR diff remains limited to MySQL connection cleanup after a failed session time-zone query and its regression tests.

  • yarn install --immutable: passed.
  • yarn build: all 13 projects passed.
  • yarn workspace @sequelize/mysql test-unit: all 3 tests passed, including both connection setup success and failure paths.
  • MySQL TypeScript check, changed-file Prettier and ESLint: passed.
  • Full database integration CI is rerunning on the updated branch; no local MySQL/DB2 integration result is claimed.

This synchronization and validation were assisted by Codex.

When acquiring a new connection, connect() issues a SET time_zone query
right after mysql2 establishes the connection. If that query fails (e.g.
ER_OUT_OF_RESOURCES under server memory pressure), the error was wrapped
in a ConnectionError and thrown without closing the underlying mysql2
connection. Since the pool never receives the connection object, it can
never release or destroy it, so the socket is orphaned.

Destroy the connection before rethrowing so the socket is released.

Closes sequelize#18266
@xianjianlf2
xianjianlf2 requested a review from a team as a code owner July 18, 2026 03:00
@xianjianlf2
xianjianlf2 requested review from ephys and sdepold July 18, 2026 03:00
@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 8e691212-971f-4f31-ad8b-67909f106107

📥 Commits

Reviewing files that changed from the base of the PR and between eb511cd and ea03ee2.

📒 Files selected for processing (1)
  • packages/mysql/src/connection-manager.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/mysql/src/connection-manager.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

MySQL connection establishment now destroys connections when SET time_zone fails before the pool receives them. Tests cover successful setup, failure propagation as ConnectionError, and explicit cleanup.

Changes

MySQL connection setup

Layer / File(s) Summary
Timezone setup cleanup and validation
packages/mysql/src/connection-manager.ts, packages/mysql/src/connection-manager.test.ts
connect() destroys the connection when SET time_zone fails and rethrows the error. Tests verify successful setup, error wrapping, query execution, and cleanup.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to ea03e

The change cleans up failed MySQL connection setup without introducing an identified production risk and is ready to merge subject to normal checks.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue #18266 requires cleanup when the post-connect SET time_zone query fails. MySqlConnectionManager.connect now catches that query error, calls connection.destroy(), and rethrows it. The exist…
Out of Scope Changes check ✅ Passed The changes are limited to MySQL connection setup and regression tests for issue #18266. The destroy() versus end() assertions support the required cleanup behavior. No unrelated implementation or…
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 1…
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: destroying the MySQL connection when the SET time_zone query fails during connect.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

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

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

@xianjianlf2

Copy link
Copy Markdown
Author

I checked the single red CI job, mariadb latest (Node 20). The failure is outside this PR’s changed MySQL connection-manager path:

  • failing test: [MARIADB] Model > findOrCreate > should not deadlock with concurrency duplicate entries and no outer transaction
  • error: MariaDB 1020 / HY000, Record has changed since last read in table Users
  • changed PR scope: packages/mysql/src/connection-manager.ts cleanup when SET time_zone fails
  • related matrix signal: MySQL jobs are green, and mariadb latest is green on Node 22 and Node 24

This looks like an unrelated MariaDB concurrency/flaky failure rather than a regression from the connection cleanup change.

@WikiRik WikiRik 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.

Confirmed the leak and the fix. Traced end to end: a query-level error from SET time_zone emits no mysql2 'error' event, so it propagates to the outer catch — and sequelize-pool never calls destroy on a resource whose create factory rejected, so nothing closes the socket. Every failed attempt orphans a live connection, exactly as the description says.

destroy() is also the right choice over end(): mysql2's destroy → close is synchronous and non-throwing, whereas end() enqueues COM_QUIT and can itself reject, which would mask the original error. And the ConnectionError wrapping really is unchanged — I checked rather than taking it on trust.

The failing mariadb latest (Node 20) check is unrelated — it's the findOrCreate concurrency test hitting MariaDB error 1020, and the same job is green on Node 22/24. This PR only touches packages/mysql/src/.

Merge order matters here, and it's the main thing to coordinate. #18218 moves SET time_zone out of connect() and into afterConnect(), and the two conflict both textually (git apply --check fails at connection-manager.ts:107) and semantically. Importantly, #18218 does not itself fix this leak — afterConnect still runs inside the pool's create callback, so the orphaned-socket path survives. I applied #18218 to a worktree, dropped in this PR's test, and it fails.

So: this PR should land first, and whoever rebases #18218 must carry the try/catch + destroy() into afterConnect. Your test will catch it if they forget, which is a good reason for it to exist.

The same leak exists in two other dialects, unfixed: postgres (packages/postgres/src/connection-manager.ts:234 and :237) and snowflake (packages/snowflake/src/connection-manager.ts:95-107, plus a deterministic one at :90-92 for offset-style timezones). db2, ibmi and sqlite3 are clean. Would you be interested in taking those too? Entirely optional — it's beyond what you signed up for, and if you'd rather keep this PR tight a maintainer will file the follow-up instead. Worth noting that three instances of one bug argue for fixing it once at the pool/connection-manager layer rather than three times.

Two small asks inline. Also worth a line in the description that mariadb was checked and is unaffected — it routes the timezone through the driver's initSql, and the driver destroys the socket itself on init-SQL failure. That's the first question a reviewer will ask.


Reviewed by Opus 5 with Claude Code, supervised by @WikiRik.

} catch (error) {
// The pool never receives a connection whose setup failed, so it must
// be closed here or its socket would be leaked.
connection.destroy();

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.

Correct call, and worth a brief comment saying why destroy() rather than end() — the connection is in an unknown state after a failed query, destroy is synchronous and safe to call twice, and end() could reject and mask the original error. That reasoning is easy to lose in a later refactor.

One nuance you may want to know about, which doesn't change this fix: sequelize-pool's own Pool.destroy() short-circuits for a resource whose create() promise hasn't settled. That's this code path calling the driver's destroy directly, so it works — but it's the reason the analogous problem in #18218 isn't solved by pool-level destruction.

let caughtError: unknown;
try {
await sequelize.dialect.connectionManager.connect(connectionConfig);
} catch (error) {

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.

Would you add an assertion that end() was not called, alongside the existing destroy check? Something like an endCallCount === 0 on the fake connection.

It's the cheapest way to lock in the destroy-not-end decision. Without it, a future refactor could switch to end(), still pass this test, and silently reintroduce the masked-error problem.

@xianjianlf2

Copy link
Copy Markdown
Author

Updated the branch with latest main using a normal merge commit (no history rewrite), so CI can rerun on the current base.

Local check after the merge:

  • yarn mocha packages/mysql/src/connection-manager.test.ts

@WikiRik

WikiRik commented Jul 30, 2026

Copy link
Copy Markdown
Member

Thanks for keeping this up to date, could you also look at the additional test assertion that Opus recommended and if you are willing to create a follow up for other dialects with similar issues?

@xianjianlf2

Copy link
Copy Markdown
Author

Thanks, I addressed both asks here.

  • Added the endCallCount === 0 assertion next to the destroy assertion, so the test now locks in the destroy()-not-end() behavior.
  • Added a short code comment explaining why destroy() is intentional: after the failed setup query the connection state is uncertain, and end() could reject and hide the original error.
  • Updated the PR description with the MariaDB note.

Local check after the change:

  • yarn mocha packages/mysql/src/connection-manager.test.ts

And yes, I can take a follow-up for the similar postgres/snowflake paths. I’ll keep this PR focused on MySQL and open that separately so it’s easier to review/merge.

@xianjianlf2

Copy link
Copy Markdown
Author

Thanks for the pointer. I opened a follow-up PR for the Postgres and Snowflake cleanup cases here: #18293

@xianjianlf2

Copy link
Copy Markdown
Author

Synced this branch with the latest main (14 upstream commits; no overlap with the two MySQL files changed by this PR).

Validation after the merge:

  • yarn mocha packages/mysql/src/connection-manager.test.ts — 2 passing
  • ESLint on both changed files — passed
  • git diff --check upstream/main...HEAD — passed
  • @sequelize/core and @sequelize/mysql builds completed successfully as part of yarn build

The full workspace build then stopped in the unrelated CLI package because install scripts were disabled in this temporary checkout, so the local sqlite3 native binding was unavailable. The MySQL regression itself is green. The requested PostgreSQL/Snowflake follow-up was also completed separately in #18293.

wikirik-agent added a commit to Americas/sequelize that referenced this pull request Sep 17, 2026
…etup failures

- Rename AbstractConnectionManager#afterConnect to initializeConnection so it
  no longer shares a name with the afterConnect hook
- Convert the named time zone inside the mysql try block so an invalid time
  zone throws a ConnectionError and destroys the connection
- Clarify that pool.destroy() during initializeConnection does not throw but
  does not close the connection either
- Bring over the mysql connection manager tests from sequelize#18267, adapted to
  connect() + initializeConnection()

Co-Authored-By: Claude Opus 5 <[email protected]>
@WikiRik

WikiRik commented Sep 24, 2026

Copy link
Copy Markdown
Member

Fixed with #18218. Thanks for the contribution!

@WikiRik WikiRik closed this Sep 24, 2026
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.

Pool connection leak when SET time_zone fails in connect()

2 participants