Repository navigation
fix(mysql): destroy connection when SET time_zone fails during connect - #18267
xianjianlf2 wants to merge 6 commits into
Conversation
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
|
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 configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughMySQL connection establishment now destroys connections when ChangesMySQL connection setup
Priority: ➖ Normal Estimated code review effort: 2 (Simple) | ~10 minutes Change: Bug fix · Severity of issue fixed: Medium Merge Risk: ⚪ Minimal · up to 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)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
I checked the single red CI job,
This looks like an unrelated MariaDB concurrency/flaky failure rather than a regression from the connection cleanup change. |
WikiRik
left a comment
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
|
Updated the branch with latest Local check after the merge:
|
|
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? |
|
Thanks, I addressed both asks here.
Local check after the change:
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. |
|
Thanks for the pointer. I opened a follow-up PR for the Postgres and Snowflake cleanup cases here: #18293 |
…imezone-leak-18266
|
Synced this branch with the latest Validation after the merge:
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. |
…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]>
|
Fixed with #18218. Thanks for the contribution! |
Pull Request Checklist
Description of Changes
Closes #18266
When the mysql dialect's
connect()successfully creates the mysql2 connection but the subsequentSET time_zonequery fails (as reported against RDS Aurora returningER_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 intoConnectionErrorexactly as before, so error semantics are unchanged. The code also documents why this usesdestroy()instead ofend(): the setup query failure leaves the connection state uncertain, andend()could reject and mask the original error.Adds
packages/mysql/src/connection-manager.test.ts(first unit coverage for this connection manager), injecting a fakemysql2Modulevia the documented dialect option: the new test was red before the fix (destroyCallCount0, expected 1) and green after. It also asserts thatend()is not called on the failed setup path, locking in the destroy-not-end behavior. Whole mysql unit suite passing afteryarn 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
Tests
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.This synchronization and validation were assisted by Codex.