Migrations 000609, 000611 and 000615 start with a lock-retry block (added in #30297 and #30412) that is meant to stop live chat traffic from deadlocking with the migration. On a release upgrade it cannot do that, and it can turn a failure into a 2-minute hang or cause a failure that would otherwise not happen. This PR removes the blocks. A release upgrade that runs 000607 to 000615 while chats are in use is unreliable with or without them, so it needs chat traffic stopped, for example by scaling the deployment to zero first. `coder server` runs all pending migrations in one transaction, so every migration's locks are held until the transaction commits. On a release upgrade (from v2.38 or earlier), 000607 and 000608 lock `chats` before any block runs. A chat request that writes `chat_messages` or `chat_queued_messages`, or that reads `users`, holds a lock that a later migration needs and then waits for `chats`. The block can release only the locks it took, so it can avoid this deadlock only when its migration takes the first chat lock of the upgrade. Postgres checks a waiting request for a deadlock once, after `deadlock_timeout` (1 second by default). The block pauses 100ms between 100ms lock attempts, so a check that lands in a pause finds no deadlock, the request keeps its lock, and the block retries until it fails the upgrade after 2 minutes, with the request stuck until then. Without the block, the outcome depends on timing. If the request's check fires after the migration starts waiting for it, Postgres cancels the request and the upgrade continues. If the request had already waited longer than `deadlock_timeout`, its check found no deadlock, so Postgres cancels the migration instead and the upgrade fails. Main does not finish those cases either: its block was still retrying after a minute, and it gives up at its 2-minute deadline. 000609 and 000611 return to their content before #30297, and 000615 loses the block in both directions. A block's migration takes the first chat lock of an upgrade only when upgrading from a build of main at 608 through 614: dogfood, where the #30297 deploy failed, or a `coder-preview` image built between 2026-10-02 and 2026-10-11. No release stops in that range, and dogfood is already past 615. v2.39 ships these migrations with the blocks. Editing them leaves every schema unchanged: databases on v2.39 or later already ran them and do not run them again, and `dump.sql` regenerates without a diff. The change affects only databases upgrading from v2.38 or earlier. WI-46 proposed the opposite direction: make the migrator survive live chat traffic. The v2.38 upgrade thread concluded instead that old replicas must be stopped before an upgrade runs migrations. So `TestMigrationChatTablesConcurrentTraffic`, which tested the blocks under chat traffic, is removed without a replacement, and its helpers `async` and `dedicatedConn` move to `migration000638_test.go`, their remaining caller. <details> <summary>Measurements</summary> Each run starts chat requests while the upgrade transaction is open, on the Postgres 13 test container with the default `deadlock_timeout`. "Request canceled" means Postgres canceled the chat request as the deadlock victim. "Stuck" means the migration was still retrying when the run was stopped, after 10 seconds unless noted. | Upgrade from | Migration | Chat requests | main | This PR | |---|---|---|---|---| | v2.38 (605) | 000609 | queued message insert | upgrade failed after 2m0s | request canceled after 1s, upgrade ok | | v2.38 (605) | 000609 | chat message insert | stuck | request canceled after 1s, upgrade ok | | v2.38 (605) | 000609 | chat message insert that waited 1.2s before 000609 started | stuck (stopped after 1 minute) | migration canceled after 1s | | v2.38 (605) | 000609 | chat message insert and queued message insert | stuck (stopped after 1 minute) | migration canceled after 2s | | v2.38 (605) | 000615 | read `users`, then `chats` | stuck | request canceled after 1s, upgrade ok | | v2.38 (605) | 000615 | read `users`, then `chats`, plus a chat message insert | stuck (stopped after 1 minute) | migration canceled after 2s | | 607 (main build) | 000609 | queued or chat message insert | stuck | request canceled after 1s, upgrade ok | | 610 (main build) | 000615 | queued message insert | stuck | request canceled after 1s, upgrade ok | | 608, 610, 614 (main build) | 000609, 000611, 000615 as the first chat lock | the four cases in `TestMigrationChatTablesConcurrentTraffic` | no deadlock | 2, 1 and 1 of 4 deadlock; in the 000615 case Postgres canceled the migration, in the others a chat request | </details> > 🤖 This PR was created with the help of Coder Agents, and has been reviewed by a human. 🏂🏻
277 lines
10 KiB
Go
277 lines
10 KiB
Go
package migrations_test
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"os"
|
|
"testing"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/lib/pq"
|
|
"github.com/stretchr/testify/require"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/testutil"
|
|
)
|
|
|
|
// TestMigration000638QueuedMessagesConcurrentTraffic runs migration 000638
|
|
// in both directions while other connections use chats and
|
|
// chat_queued_messages the way chatd does. Each case blocks the migration
|
|
// on an open application transaction, waits until pg_blocking_pids shows
|
|
// the migration waiting on it, then lets the application continue.
|
|
func TestMigration000638QueuedMessagesConcurrentTraffic(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
// Every chatstate transition reads the queue. New readers must not
|
|
// wait behind the migration while it waits for an open application
|
|
// transaction.
|
|
t.Run("UpReadQueueWhileMigrationWaits", func(t *testing.T) {
|
|
t.Parallel()
|
|
sqlDB := testSQLDB(t)
|
|
stepTo(t, sqlDB, 637)
|
|
migrationSQL, err := os.ReadFile("000638_chat_queued_messages_editing_since.up.sql")
|
|
require.NoError(t, err)
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
chatID, userID := seedChatWithStatus(ctx, t, sqlDB, "waiting")
|
|
|
|
// chatd queues a message on a locked chat. The insert trigger also
|
|
// bumps chats.queue_version.
|
|
conn, appPID := dedicatedConn(ctx, t, sqlDB)
|
|
tx, err := conn.BeginTx(ctx, nil)
|
|
require.NoError(t, err)
|
|
defer func() { _ = tx.Rollback() }()
|
|
_, err = tx.ExecContext(ctx, `SELECT id FROM chats WHERE id = $1 FOR UPDATE`, chatID)
|
|
require.NoError(t, err)
|
|
_, err = tx.ExecContext(ctx, `
|
|
INSERT INTO chat_queued_messages (chat_id, content, created_by)
|
|
VALUES ($1, '[]', $2)`, chatID, userID)
|
|
require.NoError(t, err)
|
|
|
|
pid, migrated := startRolledBackMigration(ctx, t, sqlDB, migrationSQL)
|
|
requireWaitsFor(ctx, t, sqlDB, pid, appPID)
|
|
|
|
// IntervalSlow is below the 5s lock_timeout startRolledBackMigration
|
|
// sets, so a stalled reader fails here before the timeout frees it.
|
|
reader, _ := dedicatedConn(ctx, t, sqlDB)
|
|
read := async(func() error {
|
|
var n int
|
|
return reader.QueryRowContext(ctx,
|
|
`SELECT count(*) FROM chat_queued_messages WHERE chat_id = $1`, chatID).Scan(&n)
|
|
})
|
|
readCtx, cancel := context.WithTimeout(ctx, testutil.IntervalSlow)
|
|
defer cancel()
|
|
select {
|
|
case err := <-read:
|
|
require.NoError(t, err, "reader")
|
|
case <-readCtx.Done():
|
|
t.Fatalf("reader of chat_queued_messages did not finish within %s while the application transaction was open", testutil.IntervalSlow)
|
|
}
|
|
select {
|
|
case err := <-migrated:
|
|
t.Fatalf("migration ended before the application transaction ended: %v", err)
|
|
default:
|
|
}
|
|
|
|
requireNoDeadlockVictim(ctx, t, "application", async(func() error {
|
|
_, err := tx.ExecContext(ctx, `DELETE FROM chat_queued_messages WHERE chat_id = $1`, chatID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}))
|
|
requireNoDeadlockVictim(ctx, t, "migration", migrated)
|
|
})
|
|
|
|
// chatd locks a chat row before its queued rows, so the down migration
|
|
// must not hold the queue while it waits for the chat row.
|
|
t.Run("DownLockChatThenTouchQueue", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx, sqlDB, migrationSQL, chatID, _ := setupEditingSinceDown(t)
|
|
|
|
conn, appPID := dedicatedConn(ctx, t, sqlDB)
|
|
tx, err := conn.BeginTx(ctx, nil)
|
|
require.NoError(t, err)
|
|
defer func() { _ = tx.Rollback() }()
|
|
_, err = tx.ExecContext(ctx, `SELECT id FROM chats WHERE id = $1 FOR UPDATE`, chatID)
|
|
require.NoError(t, err)
|
|
|
|
pid, migrated := startRolledBackMigration(ctx, t, sqlDB, migrationSQL)
|
|
requireWaitsFor(ctx, t, sqlDB, pid, appPID)
|
|
|
|
// The down migration keeps chats_expanded, so a reader of the view
|
|
// must get through while the migration waits for chats.
|
|
reader, _ := dedicatedConn(ctx, t, sqlDB)
|
|
requireNoDeadlockVictim(ctx, t, "reader", async(func() error {
|
|
var id uuid.UUID
|
|
return reader.QueryRowContext(ctx, `SELECT id FROM chats_expanded WHERE id = $1`, chatID).Scan(&id)
|
|
}))
|
|
|
|
// Promote the queued head: delete it, then update the chat.
|
|
requireNoDeadlockVictim(ctx, t, "application", async(func() error {
|
|
_, err := tx.ExecContext(ctx, `DELETE FROM chat_queued_messages WHERE chat_id = $1`, chatID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.ExecContext(ctx, `UPDATE chats SET status = 'running' WHERE id = $1`, chatID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}))
|
|
requireNoDeadlockVictim(ctx, t, "migration", migrated)
|
|
})
|
|
|
|
// An application transaction that has read the queue but holds no chats
|
|
// lock, then queues a message and updates the chat. The insert locks
|
|
// chats through its foreign key check and its queue_version trigger. If
|
|
// the migration takes chats and then waits for the queue, that insert
|
|
// closes a deadlock cycle.
|
|
t.Run("DownReadQueueThenQueueMessage", func(t *testing.T) {
|
|
t.Parallel()
|
|
ctx, sqlDB, migrationSQL, chatID, userID := setupEditingSinceDown(t)
|
|
|
|
conn, appPID := dedicatedConn(ctx, t, sqlDB)
|
|
tx, err := conn.BeginTx(ctx, nil)
|
|
require.NoError(t, err)
|
|
defer func() { _ = tx.Rollback() }()
|
|
_, err = tx.ExecContext(ctx, `SELECT id FROM chat_queued_messages WHERE chat_id = $1`, chatID)
|
|
require.NoError(t, err)
|
|
|
|
pid, migrated := startRolledBackMigration(ctx, t, sqlDB, migrationSQL)
|
|
requireWaitsFor(ctx, t, sqlDB, pid, appPID)
|
|
|
|
requireNoDeadlockVictim(ctx, t, "application", async(func() error {
|
|
_, err := tx.ExecContext(ctx, `
|
|
INSERT INTO chat_queued_messages (chat_id, content, created_by)
|
|
VALUES ($1, '[]', $2)`, chatID, userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = tx.ExecContext(ctx, `UPDATE chats SET status = 'running' WHERE id = $1`, chatID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}))
|
|
requireNoDeadlockVictim(ctx, t, "migration", migrated)
|
|
})
|
|
}
|
|
|
|
// setupEditingSinceDown steps a new database to 000638, seeds a paused
|
|
// chat with one queued message, and returns the down migration with the
|
|
// chat and owner IDs.
|
|
func setupEditingSinceDown(t *testing.T) (ctx context.Context, sqlDB *sql.DB, migrationSQL []byte, chatID, userID uuid.UUID) {
|
|
t.Helper()
|
|
sqlDB = testSQLDB(t)
|
|
stepTo(t, sqlDB, 638)
|
|
migrationSQL, err := os.ReadFile("000638_chat_queued_messages_editing_since.down.sql")
|
|
require.NoError(t, err)
|
|
|
|
ctx = testutil.Context(t, testutil.WaitLong)
|
|
chatID, userID = seedChatWithStatus(ctx, t, sqlDB, "paused")
|
|
_, err = sqlDB.ExecContext(ctx, `
|
|
INSERT INTO chat_queued_messages (chat_id, content, created_by)
|
|
VALUES ($1, '[]', $2)`, chatID, userID)
|
|
require.NoError(t, err)
|
|
return ctx, sqlDB, migrationSQL, chatID, userID
|
|
}
|
|
|
|
// seedChatWithStatus creates a chat with the given status, owned by a new
|
|
// user, and returns the chat and user IDs.
|
|
func seedChatWithStatus(ctx context.Context, t *testing.T, db *sql.DB, status string) (chatID, userID uuid.UUID) {
|
|
t.Helper()
|
|
orgID, modelID := uuid.New(), uuid.New()
|
|
chatID, userID = uuid.New(), uuid.New()
|
|
for _, q := range []struct {
|
|
sql string
|
|
args []any
|
|
}{
|
|
{`INSERT INTO organizations (id, name, display_name, description, created_at, updated_at, default_org_member_roles)
|
|
VALUES ($1, 'org-queue', 'org-queue', '', now(), now(), '{}')`, []any{orgID}},
|
|
{`INSERT INTO users (id, email, username, hashed_password, created_at, updated_at)
|
|
VALUES ($1, 'queue@example.com', 'queue', '\x', now(), now())`, []any{userID}},
|
|
{`INSERT INTO chat_model_configs (id, organization_id, model, context_limit, compression_threshold, deleted)
|
|
VALUES ($1, $2, 'model-queue', 1000, 50, true)`, []any{modelID, orgID}},
|
|
{`INSERT INTO chats (id, owner_id, organization_id, last_model_config_id, title, status)
|
|
VALUES ($1, $2, $3, $4, 'chat-queue', $5)`, []any{chatID, userID, orgID, modelID, status}},
|
|
} {
|
|
_, err := db.ExecContext(ctx, q.sql, q.args...)
|
|
require.NoError(t, err)
|
|
}
|
|
return chatID, userID
|
|
}
|
|
|
|
// startRolledBackMigration runs migrationSQL in a transaction on its own
|
|
// connection and rolls it back. It returns the backend PID and the
|
|
// migration's result, sent after the rollback.
|
|
func startRolledBackMigration(ctx context.Context, t *testing.T, db *sql.DB, migrationSQL []byte) (int, <-chan error) {
|
|
t.Helper()
|
|
conn, pid := dedicatedConn(ctx, t, db)
|
|
return pid, async(func() error {
|
|
tx, err := conn.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// The migration lowers lock_timeout while it takes its locks and
|
|
// must restore the caller's setting afterwards.
|
|
_, err = tx.ExecContext(ctx, `SET LOCAL lock_timeout = '5s'`)
|
|
if err == nil {
|
|
_, err = tx.ExecContext(ctx, string(migrationSQL))
|
|
}
|
|
if err == nil {
|
|
var lockTimeout string
|
|
err = tx.QueryRowContext(ctx, `SHOW lock_timeout`).Scan(&lockTimeout)
|
|
if err == nil && lockTimeout != "5s" {
|
|
err = xerrors.Errorf("lock_timeout after migration = %q, want 5s", lockTimeout)
|
|
}
|
|
}
|
|
return errors.Join(err, tx.Rollback())
|
|
})
|
|
}
|
|
|
|
// requireWaitsFor waits until pid waits for a lock held or requested by
|
|
// blocker.
|
|
func requireWaitsFor(ctx context.Context, t *testing.T, db *sql.DB, pid, blocker int) {
|
|
t.Helper()
|
|
require.Eventually(t, func() bool {
|
|
var blocked bool
|
|
err := db.QueryRowContext(ctx, `SELECT $2::int = ANY(pg_blocking_pids($1))`, pid, blocker).Scan(&blocked)
|
|
return err == nil && blocked
|
|
}, testutil.WaitMedium, testutil.IntervalFast, "pid %d never waited for pid %d", pid, blocker)
|
|
}
|
|
|
|
// requireNoDeadlockVictim receives the result from done and fails the
|
|
// test with the deadlock detail if PostgreSQL chose that side as a
|
|
// deadlock victim.
|
|
func requireNoDeadlockVictim(ctx context.Context, t *testing.T, who string, done <-chan error) {
|
|
t.Helper()
|
|
err := testutil.TryReceive(ctx, t, done)
|
|
var pqErr *pq.Error
|
|
if errors.As(err, &pqErr) && pqErr.Code == "40P01" {
|
|
t.Fatalf("%s: %v: %s", who, err, pqErr.Detail)
|
|
}
|
|
require.NoError(t, err, who)
|
|
}
|
|
|
|
// async runs fn in a goroutine and returns a channel that receives its
|
|
// result.
|
|
func async(fn func() error) <-chan error {
|
|
done := make(chan error, 1)
|
|
go func() { done <- fn() }()
|
|
return done
|
|
}
|
|
|
|
// dedicatedConn returns a connection that stays checked out for the test and
|
|
// its backend PID.
|
|
func dedicatedConn(ctx context.Context, t *testing.T, db *sql.DB) (*sql.Conn, int) {
|
|
t.Helper()
|
|
conn, err := db.Conn(ctx)
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() { _ = conn.Close() })
|
|
var pid int
|
|
require.NoError(t, conn.QueryRowContext(ctx, `SELECT pg_backend_pid()`).Scan(&pid))
|
|
return conn, pid
|
|
}
|