Skip to content

Fix drivers not satisfying drivers.Lockable, which silently disabled locking - #37

Open
hanzei wants to merge 6 commits into
masterfrom
ccr-03c49cdd-dkvs8j
Open

hanzei wants to merge 6 commits into
masterfrom
ccr-03c49cdd-dkvs8j

Conversation

@hanzei

@hanzei hanzei commented Dec 3, 2026 •

Copy link
Copy Markdown

Summary

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(key string, logger Logger) (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.

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

Generated by CodeRabbitAI

…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
@hanzei
hanzei requested a review from isacikgoz December 3, 2026 20:17
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
@hanzei hanzei mentioned this pull request Dec 3, 2026
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.
Comment thread morph.go
Comment on lines +117 to +121
if engine.config.LockKey != "" {
impl, ok := driver.(drivers.Lockable)
if !ok {
return nil, fmt.Errorf("driver %T does not support locking", driver)
}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

This avoids that people shoot themself in the foot by not locking

@hanzei
hanzei marked this pull request as ready for review December 4, 2026 04:08
@hanzei hanzei added the 2: Dev Review Requires review by a core committer label Dec 4, 2026
@coderabbitai

coderabbitai Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Explain Change →

Walkthrough

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: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed 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 Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments

Major 1
  1. Bound the second connection checkout.
Minor 2
  1. Register fallback cleanup after engine creation.
  2. Release the lock connection when acquisition is canceled.
Outside diff 4
  1. Return the reserved connection when table creation fails.
    drivers/mysql/lock.go, lines 59–60 · 🩺 Stability & Availability · ⚡ Quick win
    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)
  2. Calculate renewal expiry from the current time.
    drivers/postgres/lock.go, lines 159 · 🩺 Stability & Availability · ⚡ Quick win
    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)
  3. 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.
  4. Make expired-lock takeover atomic.
    drivers/postgres/lock.go, lines 120–121 · 🗄️ Data Integrity & Integration · ⚡ Quick win
    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.

Comment thread drivers/mysql/lock.go Resolved
Comment thread drivers/postgres/engine_lock_test.go Resolved
Comment thread morph.go Resolved
- 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.
@hanzei

hanzei commented Dec 4, 2026

Copy link
Copy Markdown
Author

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments

Major 2
  1. Check lease ownership before retrying renewal.
  2. Make renewal cancellable by Unlock.
Outside diff 1
  1. 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.

Comment thread drivers/mysql/lock.go
done := make(chan bool)
// The refresh must outlive the caller's context: it is only meant to bound lock
// acquisition, and the lock has to stay alive until Unlock.
refreshCtx := context.WithoutCancel(ctx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 8cfe9d5: each renewal now runs under a RefreshInterval timeout and the tx queries take the context, so Unlock waits at most one interval.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '--- Revision ---'
git rev-parse HEAD
git show --format=fuller --stat --oneline 8cfe9d5 -- drivers/mysql/lock.go drivers/postgres/lock.go 2>&1
printf '%s\n' '--- Applicable instructions ---'
fd -HI -t f '^(AGENTS\.md|CLAUDE\.md|\.coderabbit\.yaml|\.coderabbit\.yml)$' . -E .git | while IFS= read -r file; do printf '\n--- %s ---\n' "$file"; cat "$file"; done
for file in drivers/mysql/lock.go drivers/postgres/lock.go; do
  printf '\n--- Outline: %s ---\n' "$file"
  ast-grep outline "$file" --items all 2>&1
  printf '\n--- Numbered source: %s ---\n' "$file"
  cat -n "$file" | sed -n '1,285p'
done
printf '\n--- Lock constants and related tests ---\n'
rg -n -C 3 'RefreshInterval|func Test.*(Lock|Mutex|Refresh|Unlock)' drivers
printf '\n--- Module versions ---\n'
fd -t f '^go\.mod$' . -E .git | while IFS= read -r file; do cat -n "$file" | sed -n '1,90p'; done

Length of output: 26748


Script executed:

#!/bin/bash
set -u
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
fetch() {
  local file="$1" url="$2"
  if ! curl -fsSL --max-time 20 "$url" -o "$tmp/$file"; then
    printf 'FAILED fetching %s\n' "$url"
  fi
}
fetch sql.go https://raw.githubusercontent.com/golang/go/go1.22.0/src/database/sql/sql.go
fetch pq_conn.go https://raw.githubusercontent.com/lib/pq/v1.10.0/conn.go
fetch pq_conn_go18.go https://raw.githubusercontent.com/lib/pq/v1.10.0/conn_go18.go
fetch mysql_transaction.go https://raw.githubusercontent.com/go-sql-driver/mysql/v1.6.0/transaction.go
fetch mysql_connection.go https://raw.githubusercontent.com/go-sql-driver/mysql/v1.6.0/connection.go
fetch mysql_connection_go18.go https://raw.githubusercontent.com/go-sql-driver/mysql/v1.6.0/connection_go18.go
for file in "$tmp"/*; do
  printf '\n--- %s ---\n' "${file##*/}"
  rg -n -A 35 -B 4 'func \((tx \*Tx|.*\*mysqlTx|.*\*mysqlConn|.*\*conn)\) (Commit|Rollback|BeginTx|Begin|watchCancel|finish|simpleExec|ExecContext)\(' "$file" || true
done

Length of output: 17026


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

You are interacting with an AI system.

Comment thread drivers/mysql/lock.go
if err != nil {
return
// Keep trying on errors: giving up would let the lock expire while it's held.
if err := m.refreshLock(refreshCtx); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Leaving as is for this PR: an owner token needs a schema change to db_lock, so it goes into a follow-up together with lease-loss handling.

@hanzei

hanzei commented Dec 4, 2026

Copy link
Copy Markdown
Author

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Comment thread drivers/mysql/lock.go
Comment on lines +147 to +148
ctx, cancel := context.WithTimeout(ctx, drivers.RefreshInterval)
defer cancel()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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.

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

Labels

2: Dev Review Requires review by a core committer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants