Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions commands/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,18 @@ func parseEngineFlags(cmd *cobra.Command) []morph.EngineOption {
tableName, _ := cmd.Flags().GetString("migrations-table")
mutexKey, _ := cmd.Flags().GetString("lock-key")
dryRun, _ := cmd.Flags().GetBool("dry-run")
driverName, _ := cmd.Flags().GetString("driver")

return []morph.EngineOption{
options := []morph.EngineOption{
morph.SetMigrationTableName(tableName),
morph.SetStatementTimeoutInSeconds(timeout),
morph.WithLock(mutexKey),
morph.SetDryRun(dryRun),
}

// The sqlite driver doesn't support locking.
if driverName != "sqlite" {
options = append(options, morph.WithLock(mutexKey))
}

return options
}
46 changes: 30 additions & 16 deletions drivers/mysql/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ import (
"github.com/mattermost/morph/drivers"
)

// Compile-time checks: morph.New only acquires the migration lock when the driver
// satisfies drivers.Lockable, so a signature drift here would silently disable locking.
var (
_ drivers.Lockable = (*MySQL)(nil)
_ drivers.Locker = (*Mutex)(nil)
)

// Mutex is similar to sync.Mutex, except usable by morph to lock the db.
//
// Pick a unique name for each mutex your plugin requires.
Expand All @@ -34,7 +41,7 @@ type Mutex struct {
// NewMutex creates a mutex with the given key name.
//
// returns error if key is empty.
func (driver *MySQL) NewMutex(key string, logger drivers.Logger) (*Mutex, error) {
func (driver *MySQL) NewMutex(key string, logger drivers.Logger) (drivers.Locker, error) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
key, err := drivers.MakeLockKey(key)
if err != nil {
return nil, err
Expand All @@ -43,13 +50,14 @@ func (driver *MySQL) NewMutex(key string, logger drivers.Logger) (*Mutex, error)
ctx, cancel := context.WithTimeout(context.Background(), drivers.TTL)
defer cancel()

conn, err := driver.db.Conn(context.Background())
conn, err := driver.db.Conn(ctx)
if err != nil {
return nil, err
}

createTableIfNotExistsQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (Id varchar(64) NOT NULL, ExpireAt bigint(20) NOT NULL, PRIMARY KEY (Id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", drivers.MutexTableName)
if _, err = conn.ExecContext(ctx, createTableIfNotExistsQuery); err != nil {
_ = conn.Close()
return nil, err
}

Expand Down Expand Up @@ -101,7 +109,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error {
}
defer m.finalizeTx(tx)

e, err := m.getExpireAt(tx)
e, err := m.getExpireAt(ctx, tx)
if err != nil {
return err
}
Expand All @@ -111,7 +119,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error {
}

query := fmt.Sprintf("UPDATE %s SET ExpireAt = ? WHERE Id = ?", drivers.MutexTableName)
if err = executeTx(tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil {
if err = executeTx(ctx, tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil {
return err
}

Expand All @@ -123,10 +131,10 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error {
return nil
}

func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) {
func (m *Mutex) getExpireAt(ctx context.Context, tx *sql.Tx) (int64, error) {
var expireAt int64
query := fmt.Sprintf("SELECT ExpireAt FROM %s WHERE Id = ?", drivers.MutexTableName)
err := tx.QueryRow(query, m.key).Scan(&expireAt)
query := fmt.Sprintf("SELECT ExpireAt FROM %s WHERE Id = ? FOR UPDATE", drivers.MutexTableName)
err := tx.QueryRowContext(ctx, query, m.key).Scan(&expireAt)
if err != nil {
return -1, fmt.Errorf("failed to fetch mutex from db: %w", err)
}
Expand All @@ -136,20 +144,21 @@ func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) {

// refreshLock rewrites the lock key value with a new expiry, returning nil only if successful.
func (m *Mutex) refreshLock(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, drivers.RefreshInterval)
defer cancel()
Comment on lines +147 to +148

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.


tx, err := m.conn.BeginTx(ctx, nil)
if err != nil {
return err
}
defer m.finalizeTx(tx)

e, err := m.getExpireAt(tx)
if err != nil {
if _, err = m.getExpireAt(ctx, tx); err != nil {
return err
}

tmp := time.Unix(e, 0)
query := fmt.Sprintf("UPDATE %s SET ExpireAt = ? WHERE Id = ?", drivers.MutexTableName)
if err = executeTx(tx, query, tmp.Add(drivers.TTL).Unix(), m.key); err != nil {
if err = executeTx(ctx, tx, query, time.Now().Add(drivers.TTL).Unix(), m.key); err != nil {
return err
}

Expand All @@ -172,6 +181,7 @@ func (m *Mutex) Lock(ctx context.Context) error {
for {
select {
case <-ctx.Done():
_ = m.conn.Close()
return ctx.Err()
case <-time.After(waitInterval):
}
Expand All @@ -188,15 +198,19 @@ func (m *Mutex) Lock(ctx context.Context) error {

stop := make(chan bool)
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.

go func() {
defer close(done)
t := time.NewTicker(drivers.RefreshInterval)
defer t.Stop()
for {
select {
case <-t.C:
err := m.refreshLock(ctx)
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.

m.logger.Printf("Failed to refresh lock: %v\n", err)
}
case <-stop:
return
Expand Down Expand Up @@ -235,8 +249,8 @@ func (m *Mutex) Unlock() error {
return err
}

func executeTx(tx *sql.Tx, query string, args ...interface{}) error {
if _, err := tx.Exec(query, args...); err != nil {
func executeTx(ctx context.Context, tx *sql.Tx, query string, args ...interface{}) error {
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
return err
}

Expand Down
46 changes: 46 additions & 0 deletions drivers/postgres/engine_lock_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//go:build !sources && drivers
// +build !sources,drivers

package postgres_test

import (
"context"
"database/sql"
"testing"

"github.com/stretchr/testify/require"

"github.com/mattermost/morph"
"github.com/mattermost/morph/drivers/postgres"
)

// TestEngineAcquiresLock checks that morph.New takes the db lock through the
// postgres driver instead of silently skipping it.
func TestEngineAcquiresLock(t *testing.T) {
const connURL = "postgres://morph:morph@localhost:6432/morph_test?sslmode=disable"

driver, err := postgres.Open(connURL)
require.NoError(t, err)

engine, err := morph.New(context.Background(), driver, nil, morph.WithLock("engine-lock-test"))
if err != nil {
_ = driver.Close()
}
require.NoError(t, err)
Comment thread
hanzei marked this conversation as resolved.
Resolved

db, err := sql.Open("postgres", connURL)
require.NoError(t, err)
defer db.Close()

lockHeld := func() bool {
var held bool
err := db.QueryRow("SELECT EXISTS (SELECT 1 FROM db_lock WHERE id = 'engine-lock-test')").Scan(&held)
require.NoError(t, err)
return held
}

require.True(t, lockHeld(), "morph.New should hold the lock")

require.NoError(t, engine.Close())
require.False(t, lockHeld(), "Close should release the lock")
}
46 changes: 30 additions & 16 deletions drivers/postgres/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ import (
"github.com/mattermost/morph/drivers"
)

// Compile-time checks: morph.New only acquires the migration lock when the driver
// satisfies drivers.Lockable, so a signature drift here would silently disable locking.
var (
_ drivers.Lockable = (*Postgres)(nil)
_ drivers.Locker = (*Mutex)(nil)
)

// Mutex is similar to sync.Mutex, except usable by morph to lock the db.
//
// Pick a unique name for each mutex your plugin requires.
Expand All @@ -34,7 +41,7 @@ type Mutex struct {
// NewMutex creates a mutex with the given key name.
//
// returns error if key is empty.
func (pg *Postgres) NewMutex(key string, logger drivers.Logger) (*Mutex, error) {
func (pg *Postgres) NewMutex(key string, logger drivers.Logger) (drivers.Locker, error) {
key, err := drivers.MakeLockKey(key)
if err != nil {
return nil, err
Expand All @@ -43,13 +50,14 @@ func (pg *Postgres) NewMutex(key string, logger drivers.Logger) (*Mutex, error)
ctx, cancel := context.WithTimeout(context.Background(), drivers.TTL)
defer cancel()

conn, err := pg.db.Conn(context.Background())
conn, err := pg.db.Conn(ctx)
if err != nil {
return nil, err
}

createTableIfNotExistsQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id varchar(64) PRIMARY KEY, expireat bigint);", drivers.MutexTableName)
if _, err = conn.ExecContext(ctx, createTableIfNotExistsQuery); err != nil {
_ = conn.Close()
return nil, err
}

Expand Down Expand Up @@ -101,7 +109,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error {
}
defer m.finalizeTx(tx)

e, err := m.getExpireAt(tx)
e, err := m.getExpireAt(ctx, tx)
if err != nil {
return err
}
Expand All @@ -111,7 +119,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error {
}

query := fmt.Sprintf("UPDATE %s SET expireat = $1 WHERE id = $2", drivers.MutexTableName)
if err = executeTx(tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil {
if err = executeTx(ctx, tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil {
return err
}

Expand All @@ -123,10 +131,10 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error {
return nil
}

func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) {
func (m *Mutex) getExpireAt(ctx context.Context, tx *sql.Tx) (int64, error) {
var expireAt int64
query := fmt.Sprintf("SELECT expireat FROM %s WHERE id = $1", drivers.MutexTableName)
err := tx.QueryRow(query, m.key).Scan(&expireAt)
query := fmt.Sprintf("SELECT expireat FROM %s WHERE id = $1 FOR UPDATE", drivers.MutexTableName)
err := tx.QueryRowContext(ctx, query, m.key).Scan(&expireAt)
if err != nil {
return -1, fmt.Errorf("failed to fetch mutex from db: %w", err)
}
Expand All @@ -136,20 +144,21 @@ func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) {

// refreshLock rewrites the lock key value with a new expiry, returning nil only if successful.
func (m *Mutex) refreshLock(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, drivers.RefreshInterval)
defer cancel()

tx, err := m.conn.BeginTx(ctx, nil)
if err != nil {
return err
}
defer m.finalizeTx(tx)

e, err := m.getExpireAt(tx)
if err != nil {
if _, err = m.getExpireAt(ctx, tx); err != nil {
return err
}

tmp := time.Unix(e, 0)
query := fmt.Sprintf("UPDATE %s SET expireat = $1 WHERE id = $2", drivers.MutexTableName)
if err = executeTx(tx, query, tmp.Add(drivers.TTL).Unix(), m.key); err != nil {
if err = executeTx(ctx, tx, query, time.Now().Add(drivers.TTL).Unix(), m.key); err != nil {
return err
}

Expand All @@ -172,6 +181,7 @@ func (m *Mutex) Lock(ctx context.Context) error {
for {
select {
case <-ctx.Done():
_ = m.conn.Close()
return ctx.Err()
case <-time.After(waitInterval):
}
Expand All @@ -188,15 +198,19 @@ func (m *Mutex) Lock(ctx context.Context) error {

stop := make(chan bool)
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)
go func() {
defer close(done)
t := time.NewTicker(drivers.RefreshInterval)
defer t.Stop()
for {
select {
case <-t.C:
err := m.refreshLock(ctx)
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 {
m.logger.Printf("Failed to refresh lock: %v\n", err)
}
case <-stop:
return
Expand Down Expand Up @@ -235,8 +249,8 @@ func (m *Mutex) Unlock() error {
return err
}

func executeTx(tx *sql.Tx, query string, args ...interface{}) error {
if _, err := tx.Exec(query, args...); err != nil {
func executeTx(ctx context.Context, tx *sql.Tx, query string, args ...interface{}) error {
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
return err
}

Expand Down
25 changes: 16 additions & 9 deletions morph.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,9 @@ func SetDryRun(enable bool) EngineOption {
}

// New creates a new instance of the migrations engine from an existing db instance and a migrations source.
// If the driver implements the Lockable interface, it will also wait until it has acquired a lock.
// The context is propagated to the drivers lock method (if the driver implements divers.Locker interface) and
// it can be used to cancel the lock acquisition.
// If WithLock is set, it waits until it has acquired the lock, and returns an error if the driver
// does not implement the drivers.Lockable interface.
// The context is propagated to the lock method and it can be used to cancel the lock acquisition.
func New(ctx context.Context, driver drivers.Driver, source sources.Source, options ...EngineOption) (*Morph, error) {
engine := &Morph{
config: &Config{
Expand All @@ -114,7 +114,12 @@ func New(ctx context.Context, driver drivers.Driver, source sources.Source, opti
return nil, err
}

if impl, ok := driver.(drivers.Lockable); ok && engine.config.LockKey != "" {
if engine.config.LockKey != "" {
impl, ok := driver.(drivers.Lockable)
if !ok {
return nil, fmt.Errorf("driver %T does not support locking", driver)
}
Comment on lines +117 to +121

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

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

mx, err := impl.NewMutex(engine.config.LockKey, engine.config.Logger)
if err != nil {
return nil, err
Expand All @@ -132,14 +137,16 @@ func New(ctx context.Context, driver drivers.Driver, source sources.Source, opti

// Close closes the underlying database connection of the engine.
func (m *Morph) Close() error {
var unlockErr error
if m.mutex != nil {
err := m.mutex.Unlock()
if err != nil {
return err
}
unlockErr = m.mutex.Unlock()
}

if err := m.driver.Close(); err != nil {
return err
}

return m.driver.Close()
return unlockErr
}

func (m *Morph) apply(migration *models.Migration, saveVersion, dryRun bool) error {
Expand Down
Loading
Loading