You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Fix drivers not satisfying drivers.Lockable, which silently disabled locking - #37
Since #33, morph never takes the migration lock with the postgres or mysql drivers, and it gives no error about it.
drivers.Lockable declares
NewMutex(keystring, loggerLogger) (Locker, error)
but both drivers implement NewMutex(...) (*Mutex, error). Go needs the method signature to match exactly, so neither driver satisfies Lockable. The driver.(drivers.Lockable) check in morph.New returns false, and WithLock(...) is skipped silently. Nobody has hit this yet because #33 has never been released; Mattermost still pins v1.1.0.
This PR:
makes both drivers return drivers.Locker from NewMutex
adds compile-time assertions (var _ drivers.Lockable = (*Postgres)(nil) and the same for MySQL and Mutex) so the signatures can't drift again without breaking the build
makes morph.New return an error when WithLock(...) is set but the driver doesn't implement drivers.Lockable, instead of skipping the lock silently. The morph CLI always passes WithLock (via the --lock-key default), so it now leaves it out for the sqlite driver, which has no lock support. Mattermost only uses WithLock with postgres and mysql.
adds TestEngineAcquiresLock (postgres driver tests). It runs morph.New(..., WithLock(key)), checks that the db_lock row exists while the engine is open, and checks that Close() removes it. On current master it fails with pq: relation "db_lock" does not exist, because the lock code never runs.
This blocks tagging v1.2.0 from master, which the Mattermost server needs in order to pick up the MM-56321 lock-retry logging from #32.
Testing
make test (postgres 16 + mysql 8.0): all packages pass, including the new test
TestNewWithLockRequiresLockableDriver checks the new error
go test -tags=drivers ./drivers/mysql/: pass
Built the Mattermost server against this branch with a local replace and ran mattermost db migrate as a Postgres role without INSERT on db_lock. It now retries and logs Failed to acquire lock. Trying again: failed to lock mutex: pq: permission denied for table db_lock (42501). With current master the lock was skipped and migrations ran with no lock.
+85 -43 Production Changes (71%)
+52 -0 Test Changes (29%)
Regression Risk: The public NewMutex return type changes on both drivers, and morph.New now returns an error when WithLock targets a non-lockable driver. Callers that relied on silent lock skipping may fail. Migration locking protects data integrity, and the SQLite lock omission in commands/apply.go has no test in this diff.
…locking
The Lockable rewrite in #33 declared
NewMutex(key string, logger Logger) (Locker, error)
but the postgres and mysql drivers implement NewMutex returning (*Mutex, error).
Go requires an exact method signature match, so neither driver satisfies
drivers.Lockable and morph.New's type assertion fails. WithLock(...) is then
skipped without any error and no migration lock is ever taken.
Return drivers.Locker from both drivers, add compile-time assertions so the
signatures cannot drift again, and add an engine-level postgres test that
checks morph.New really holds the db_lock row and Close releases it. The test
fails on master ("relation db_lock does not exist") and passes with this fix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FpCfx4vHgXXz8FocntG7Y2
morph.New doesn't touch the migration source before migrations are applied,
so the test can pass a nil source and drop the custom logger and table setup.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FpCfx4vHgXXz8FocntG7Y2
morph.New skipped the lock silently when the driver did not implement
drivers.Lockable, which is how the NewMutex signature drift went unnoticed.
It now returns an error instead.
The CLI always passes WithLock via the --lock-key default, so it now skips
the lock for the sqlite driver, which has no lock support.
TestEngineAcquiresLock also checks that Close releases the lock.
MySQL and PostgreSQL now implement the lock interfaces and return drivers.Locker from NewMutex. Their lock operations use contexts, lock expiry-row reads, and refresh expiry to the current time plus drivers.TTL. When WithLock is set, New returns an error if the driver does not support locking. Close attempts driver closure even if unlocking fails. The apply command omits the lock option for SQLite. Tests cover unsupported drivers and PostgreSQL lock acquisition and release.
Merge Risk: Moderate · up to 8cfe9
This change makes migration locking actually apply for PostgreSQL and MySQL, which is a clear improvement. However, on MySQL a single slow lock renewal can permanently break renewal, so the lock can expire while a migration is still running. Lost leases are also not reported to the engine and lock ownership is not tracked. These should be resolved or explicitly accepted before merge.
Pre-merge checks: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
The title names the main change: drivers PostgreSQL and MySQL did not satisfy drivers.Lockable because NewMutex returned *Mutex instead of drivers.Locker, which caused morph.New to silently skip locki…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title names the main change: drivers PostgreSQL and MySQL did not satisfy drivers.Lockable because NewMutex returned *Mutex instead of drivers.Locker, which caused morph.New to silently skip locking. The changeset matches this: both drivers now return drivers.Locker, compile-time assertions are added, and morph.New returns an error when WithLock is set for a non-lockable driver. The title is specific and accurate, though it does not mention the new error or the SQLite CLI change.
The newly activated constructor reserves a connection before this statement. If CREATE TABLE fails, this return loses the connection without calling Close. With a caller-owned pool, repeated construction attempts can exhaust the pool. Close the connection on this error path in both drivers. Keep it reserved only when construction succeeds. (raw.githubusercontent.com)
Both drivers add TTL to the previous expiry. However, renewal runs every TTL/2. With TTL=15s, renewals at 7.5s and 15s move the expiry from 15s to 30s and then 45s. The remaining lease therefore grows throughout the engine's lifetime. After a crash, another engine can wait approximately as long as the previous engine ran. Set each renewed expiry to the current time plus TTL in both drivers. (raw.githubusercontent.com)
Propagate renewal failure to the engine.
drivers/postgres/lock.go, lines 205–206 · 🗄️ Data Integrity & Integration · 🏗️ Heavy lift
The renewal goroutine returns on its first error, at drivers/postgres/lock.go:198-212. Lock has already returned nil, so the caller receives no later signal. If the dedicated mutex connection fails while the pool connections used for migrations still work, the first engine can keep migrating after its lease expires. Another engine can then acquire the same key and run migrations concurrently.
Each driver needs a lease-loss path. The path must stop protected work before another engine can acquire the lease. Decide whether transient refresh errors are retried before the lease is treated as lost.
Enabling Lockable exposes the expired-lock takeover path. tryLock calls releaseLock after an INSERT fails on a duplicate key. releaseLock reads expireat without a row lock, checks that the row has expired, then runs UPDATE ... WHERE id = $2. The WHERE clause does not repeat the expiry check.
Two contenders can read the same expired row before either commits. Both pass the check. The second UPDATE waits for the first to commit, then re-evaluates only id, so it succeeds. Both releaseLock calls return nil, and both tryLock calls return true. Two engines then hold the same lock, and migrations can run concurrently. PostgreSQL 16 Read Committed allows this sequence (postgresql.org).
Lock the row before the expiry check, for example with SELECT ... FOR UPDATE in getExpireAt. Alternatively, make the update conditional on the observed value, such as WHERE id = $2 AND expireat = $3, and require one affected row.
- Bound the lock connection checkout by the setup timeout.
- Close the lock connection when table creation fails or Lock is canceled.
- Renew the lock expiry from the current time instead of the stored expiry,
which let the lease grow with the engine's lifetime.
- Lock the row in getExpireAt so two instances can't both take over an
expired lock.
Replies to the CodeRabbit findings that were posted outside the diff:
coderabbit
drivers/{postgres,mysql}/lock.go:59-60 Connection leaks when table creation fails: Fixed in 79a6f7d.
drivers/{postgres,mysql}/lock.go:159 Renewal expiry grows with the engine's lifetime: Fixed in 79a6f7d. Renewal now sets the expiry to now + TTL.
drivers/postgres/lock.go:205-206 Renewal failure isn't reported to the engine: Leaving as is for this PR. It needs a way to signal lost leases through drivers.Locker, which is better handled in a follow-up.
drivers/postgres/lock.go:120-121 Expired-lock takeover isn't atomic: Fixed in 79a6f7d with SELECT ... FOR UPDATE in getExpireAt, in both drivers.
- Refresh the lock on a context detached from the one passed to New, which
only bounds lock acquisition.
- Log a failed refresh and retry on the next tick instead of giving up.
- Stop the refresh ticker when the goroutine exits.
- Close the driver in Morph.Close even when Unlock fails.
- Close the driver in TestEngineAcquiresLock when New fails.
Expired-lock takeovers can commit a lease that has already lapsed.
drivers/postgres/lock.go, lines 121–122 · 🗄️ Data Integrity & Integration · 🏗️ Heavy lift
tryLock calls releaseLock after its INSERT fails with a duplicate key. This is the takeover path for an expired lease, not the renewal path. releaseLock writes t.Add(drivers.TTL), where t is sampled before the transaction begins. The function then waits on the locking read in getExpireAt, which uses FOR UPDATE and has no deadline of its own. It then commits. If the time from t to the commit is at least drivers.TTL (15 seconds), the committed expireat is already in the past. Another engine can then take over the lock while this engine has already returned from Lock and treats the lock as held. Two engines can hold the migration lock at once.
The wait depends on the caller's context and on database load, so this code does not bound it.
When releaseLock returns nil, the committed expiry must be later than the commit time. The clock source and the bound are open choices. The fix must bound the interval from the expiry calculation to the commit, or otherwise guarantee that the commit completes before the lease lapses. Reading the clock at the write does not satisfy this on its own, because the commit still follows the write.
The reason will be displayed to describe this comment to others. Learn more.
Major · Stability & Availability · Heavy lift
Make renewal cancellable by Unlock.
WithoutCancel removes both cancellation and deadlines. If MySQL stops responding during renewal's BeginTx, closing stopRefresh cannot interrupt that call. The renewal goroutine checks stopRefresh only between ticks. Unlock then waits at Line 238, so Morph.Close cannot close the driver. No timeout in this code bounds the blocked call. The same applies to the FOR UPDATE read and the Exec in refreshLock. (golang context)
Give renewal an engine-owned cancellation function. Call it before waiting for refreshDone in Unlock. Pass a bounded context to each SQL call in refreshLock, and use context-aware calls where the code now omits the context (tx.QueryRow in getExpireAt, tx.Exec in executeTx). Apply the same change to drivers/postgres/lock.go. Its SELECT ... FOR UPDATE can wait for another transaction and has the same unbounded wait. Keep renewal independent of acquisition-context cancellation, because the lock must stay alive until Unlock.
@hanzei Thanks. The timeout improves renewal, but it does not guarantee the stated bound:
PostgreSQL’s lib/pq v1.10.0 starts BEGIN before installing its cancellation watcher. A stalled BEGIN can still block renewal.
MySQL’s Commit runs without a context watcher. A stalled COMMIT can also block renewal.
If the ticker and stop are both ready, the refresh loop can select another renewal. After the loop stops, Unlock also runs its DELETE with context.Background().
Please bound these operations and test a stalled connection for both drivers. I’m not marking the finding as addressed.
The reason will be displayed to describe this comment to others. Learn more.
Major · Data Integrity & Integration · Heavy lift
Check lease ownership before retrying renewal.
If A's renewal fails until its lease expires, B can acquire the same key. A now retries instead of stopping. Its refreshLock accepts B's row and updates it using only the shared key. A's subsequent Unlock can also delete B's lease. FOR UPDATE serialises access but does not identify the owner. Both drivers have this path. (raw.githubusercontent.com)
Store a unique acquisition token. Require that token on renewal and deletion, and treat an ownership mismatch as lease loss. This protects a successor independently of the deferred engine notification work.
Reply to the CodeRabbit finding posted outside the diff in the latest review:
coderabbit
drivers/{postgres,mysql}/lock.go:104-122 Expired-lock takeover can commit a lease that has already lapsed: Won't fix: it needs a stall of more than 15s inside the takeover transaction, and the TTL scheme as a whole (the INSERT in tryLock and the renewals) assumes a database round trip finishes well within the TTL.
Run each renewal under a RefreshInterval timeout and pass the context to the
queries inside the lock transaction, which previously ignored cancellation.
The reason will be displayed to describe this comment to others. Learn more.
Major · Stability & Availability · Heavy lift
Handle connection invalidation before retrying renewal.
If a renewal exceeds RefreshInterval, the MySQL driver closes the connection that m.conn retains. A sql.Conn does not reconnect. After it closes, every later BeginTx and ExecContext returns ErrConnDone. The renewal loop therefore cannot restore the lease after the database recovers. Unlock cannot delete the row through that connection either. The lease then expires, and another contender can acquire the lock while this process still runs its migration.
Before this change, a slow renewal had no deadline and could finish. The new timeout turns a temporary delay into permanent renewal failure.
Keep the timeout. Replace the connection when a renewal fails because its context was cancelled. Before renewal resumes, the holder must treat an expired lease as lost. Normal renewals must keep the existing connection. Apply the same handling to drivers/postgres/lock.go after its cancellation behaviour is confirmed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Since #33, morph never takes the migration lock with the postgres or mysql drivers, and it gives no error about it.
drivers.Lockabledeclaresbut both drivers implement
NewMutex(...) (*Mutex, error). Go needs the method signature to match exactly, so neither driver satisfiesLockable. Thedriver.(drivers.Lockable)check inmorph.Newreturns false, andWithLock(...)is skipped silently. Nobody has hit this yet because #33 has never been released; Mattermost still pins v1.1.0.This PR:
drivers.LockerfromNewMutexvar _ drivers.Lockable = (*Postgres)(nil)and the same for MySQL andMutex) so the signatures can't drift again without breaking the buildmorph.Newreturn an error whenWithLock(...)is set but the driver doesn't implementdrivers.Lockable, instead of skipping the lock silently. The morph CLI always passesWithLock(via the--lock-keydefault), so it now leaves it out for the sqlite driver, which has no lock support. Mattermost only usesWithLockwith postgres and mysql.TestEngineAcquiresLock(postgres driver tests). It runsmorph.New(..., WithLock(key)), checks that thedb_lockrow exists while the engine is open, and checks thatClose()removes it. On current master it fails withpq: relation "db_lock" does not exist, because the lock code never runs.This blocks tagging v1.2.0 from master, which the Mattermost server needs in order to pick up the MM-56321 lock-retry logging from #32.
Testing
make test(postgres 16 + mysql 8.0): all packages pass, including the new testTestNewWithLockRequiresLockableDriverchecks the new errorgo test -tags=drivers ./drivers/mysql/: passreplaceand ranmattermost db migrateas a Postgres role without INSERT ondb_lock. It now retries and logsFailed to acquire lock. Trying again: failed to lock mutex: pq: permission denied for table db_lock (42501). With current master the lock was skipped and migrations ran with no lock.Ticket Link
https://mattermost.atlassian.net/browse/MM-72647 (blocks MM-72635; related: MM-70848, MM-56321)
https://claude.ai/code/session_01FpCfx4vHgXXz8FocntG7Y2
Generated by Claude Code
Change Impact: 🔴 High
Changes Breakdown:
+85 -43 Production Changes (71%)
+52 -0 Test Changes (29%)
Regression Risk: The public
NewMutexreturn type changes on both drivers, andmorph.Newnow returns an error whenWithLocktargets a non-lockable driver. Callers that relied on silent lock skipping may fail. Migration locking protects data integrity, and the SQLite lock omission incommands/apply.gohas no test in this diff.Generated by CodeRabbitAI