From b0068ebd7638ce7dd37e11751f4e05b0f92acc69 Mon Sep 17 00:00:00 2001 From: "Jakub A. W." Date: Thu, 12 Nov 2026 15:44:28 +0100 Subject: [PATCH 1/7] fix(storage): stop locking PostgreSQL tables at startup for columns that already exist --- internal/auditlog/recent_writes_test.go | 2 +- internal/auditlog/store_sql.go | 37 +----- internal/auditlog/store_sql_test.go | 2 +- internal/storage/sqlx/conformance_test.go | 86 ++++++++++++++ internal/storage/sqlx/schema.go | 136 ++++++++++++++++++++-- internal/storage/sqlx/schema_test.go | 28 +++++ internal/usage/store_sql_migrate_test.go | 51 ++++++++ 7 files changed, 295 insertions(+), 47 deletions(-) create mode 100644 internal/usage/store_sql_migrate_test.go diff --git a/internal/auditlog/recent_writes_test.go b/internal/auditlog/recent_writes_test.go index e22609f14..76553e740 100644 --- a/internal/auditlog/recent_writes_test.go +++ b/internal/auditlog/recent_writes_test.go @@ -203,7 +203,7 @@ func TestSQLStoreAddsWriteStampColumns(t *testing.T) { t.Cleanup(func() { _ = store.Close() }) store.indexBuild.Wait() - columns, err := auditColumns(ctx, db, auditLogTable) + columns, err := sqlx.Columns(ctx, db, auditLogTable) require.NoError(t, err) assert.True(t, columns["writer_id"]) assert.True(t, columns["written_at"]) diff --git a/internal/auditlog/store_sql.go b/internal/auditlog/store_sql.go index 6fb9d3037..cffad32d0 100644 --- a/internal/auditlog/store_sql.go +++ b/internal/auditlog/store_sql.go @@ -469,7 +469,7 @@ func (s *SQLStore) cleanup() { // renameAuditColumn renames a column when the old name is still present and // the new one is not, so the rename runs once and is a no-op thereafter. func renameAuditColumn(ctx context.Context, db sqlx.DB, table, from, to string) error { - columns, err := auditColumns(ctx, db, table) + columns, err := sqlx.Columns(ctx, db, table) if err != nil { return err } @@ -479,38 +479,3 @@ func renameAuditColumn(ctx context.Context, db sqlx.DB, table, from, to string) _, err = db.Exec(ctx, fmt.Sprintf("ALTER TABLE %s RENAME COLUMN %s TO %s", table, from, to)) return err } - -// auditColumns reports the table's current column names, lowercased. -func auditColumns(ctx context.Context, db sqlx.DB, table string) (map[string]bool, error) { - var query string - var args []any - switch db.Dialect() { - case sqlx.SQLite: - query = fmt.Sprintf(`SELECT name FROM pragma_table_info('%s')`, table) - case sqlx.PostgreSQL: - query = `SELECT column_name FROM information_schema.columns - WHERE table_schema = current_schema() AND table_name = ?` - args = []any{table} - default: - return nil, fmt.Errorf("unsupported dialect %q", db.Dialect()) - } - - rows, err := db.Query(ctx, query, args...) - if err != nil { - return nil, fmt.Errorf("inspect %s columns: %w", table, err) - } - defer rows.Close() - - columns := make(map[string]bool) - for rows.Next() { - var name string - if err := rows.Scan(&name); err != nil { - return nil, fmt.Errorf("inspect %s columns: %w", table, err) - } - columns[strings.ToLower(name)] = true - } - if err := rows.Err(); err != nil { - return nil, fmt.Errorf("inspect %s columns: %w", table, err) - } - return columns, nil -} diff --git a/internal/auditlog/store_sql_test.go b/internal/auditlog/store_sql_test.go index aa8956b83..1211f1b54 100644 --- a/internal/auditlog/store_sql_test.go +++ b/internal/auditlog/store_sql_test.go @@ -162,7 +162,7 @@ func TestNewSQLStoreRenamesLegacyModelColumn(t *testing.T) { _, err = NewSQLStore(ctx, db, 0) require.NoError(t, err) - columns, err := auditColumns(ctx, db, auditLogTable) + columns, err := sqlx.Columns(ctx, db, auditLogTable) require.NoError(t, err) assert.False(t, columns["model"], "legacy model column still present") diff --git a/internal/storage/sqlx/conformance_test.go b/internal/storage/sqlx/conformance_test.go index ce8b2d4a7..b8591e7f0 100644 --- a/internal/storage/sqlx/conformance_test.go +++ b/internal/storage/sqlx/conformance_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "strconv" + "strings" "testing" "github.com/enterpilot/gomodel/internal/storage/sqlx" @@ -66,6 +67,91 @@ func TestAddColumnsIsIdempotent(t *testing.T) { }) } +// execRecorder records every statement Exec runs. +type execRecorder struct { + sqlx.DB + execs []string +} + +func (r *execRecorder) Exec(ctx context.Context, query string, args ...any) (int64, error) { + r.execs = append(r.execs, query) + return r.DB.Exec(ctx, query, args...) +} + +func TestAddColumnsRunsOnlyMissingColumns(t *testing.T) { + note := `ALTER TABLE conformance ADD COLUMN note TEXT` + enabled := `ALTER TABLE conformance ADD COLUMN enabled ` + sqlx.TypeBool + ` NOT NULL DEFAULT FALSE` + existing := `ALTER TABLE conformance ADD COLUMN amount ` + sqlx.TypeFloat + rename := `ALTER TABLE conformance_extra RENAME TO conformance_renamed` + + tests := []struct { + name string + applied []string // run before the measured call + statements []string + wantRun []string // statements expected to reach Exec, unexpanded + }{ + { + name: "fresh columns all run", + statements: []string{note, enabled}, + wantRun: []string{note, enabled}, + }, + { + name: "up-to-date schema runs nothing", + applied: []string{note, enabled}, + statements: []string{note, enabled}, + }, + { + name: "column from CREATE TABLE is skipped", + statements: []string{existing}, + }, + { + name: "only the missing column runs", + applied: []string{note}, + statements: []string{note, enabled}, + wantRun: []string{enabled}, + }, + { + name: "other statement shapes always run", + applied: []string{note}, + statements: []string{note, rename}, + wantRun: []string{rename}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sqlxtest.Run(t, func(t *testing.T, db sqlx.DB) { + ctx := context.Background() + db = newConformanceDB(t, db) + _, err := db.Exec(ctx, `CREATE TABLE conformance_extra (id TEXT)`) + require.NoError(t, err) + require.NoError(t, sqlx.AddColumns(ctx, db, tt.applied...)) + + recorder := &execRecorder{DB: db} + require.NoError(t, sqlx.AddColumns(ctx, recorder, tt.statements...)) + + var wantRun []string + for _, statement := range tt.wantRun { + want := db.Dialect().ExpandTypes(statement) + if db.Dialect() == sqlx.PostgreSQL && statement != rename { + want = strings.Replace(want, "ADD COLUMN ", "ADD COLUMN IF NOT EXISTS ", 1) + } + wantRun = append(wantRun, want) + } + assert.Equal(t, wantRun, recorder.execs) + + columns, err := sqlx.Columns(ctx, db, "conformance") + require.NoError(t, err) + added := map[string]string{note: "note", enabled: "enabled", existing: "amount"} + for _, statement := range tt.statements { + if column, ok := added[statement]; ok { + assert.True(t, columns[column], "column %s present", column) + } + } + }) + }) + } +} + func TestScalarRoundTrip(t *testing.T) { sqlxtest.Run(t, func(t *testing.T, db sqlx.DB) { ctx := context.Background() diff --git a/internal/storage/sqlx/schema.go b/internal/storage/sqlx/schema.go index 9b54ff8f1..ea572582a 100644 --- a/internal/storage/sqlx/schema.go +++ b/internal/storage/sqlx/schema.go @@ -22,18 +22,27 @@ func execSchema(ctx context.Context, q Querier, dialect Dialect, statements []st return nil } -// AddColumns applies ALTER TABLE ... ADD COLUMN migrations, expanding type -// tokens and ignoring the error each engine returns when the column is already -// present. +// AddColumns applies `ALTER TABLE ADD COLUMN ...` migrations, +// expanding type tokens and running only those whose column is missing. // -// Tolerating the error is the portable form: SQLite has no ADD COLUMN IF NOT -// EXISTS, and both engines reject a duplicate add with a recognisable message, -// so one list serves both. PostgreSQL still gets the IF NOT EXISTS spelling -// (see addColumnStatement) so that re-running applied migrations on every -// start does not write an ERROR line per column to the server log. +// Store constructors call this on every start, so on an up-to-date schema it +// must not run any ALTER: PostgreSQL takes an ACCESS EXCLUSIVE lock for +// `ALTER TABLE ... ADD COLUMN IF NOT EXISTS` even when the column exists, and +// a waiting ALTER queues every later read and write on the table behind +// whatever long query it is waiting for. Each table's columns are read once +// (see Columns) and applied migrations are skipped. +// +// A statement that does not have that shape always runs. The duplicate-column +// error is still tolerated, and PostgreSQL still gets the IF NOT EXISTS +// spelling (see addColumnStatement), because replicas starting together can +// all see a column missing and race to add it. func AddColumns(ctx context.Context, db DB, statements ...string) error { + pending, err := missingColumnStatements(ctx, db, statements) + if err != nil { + return err + } dialect := db.Dialect() - for _, statement := range statements { + for _, statement := range pending { _, err := db.Exec(ctx, dialect.addColumnStatement(statement)) if err != nil && !IsDuplicateColumnError(err) { return fmt.Errorf("apply migration %q: %w", statement, err) @@ -42,6 +51,115 @@ func AddColumns(ctx context.Context, db DB, statements ...string) error { return nil } +// missingColumnStatements drops the statements whose column already exists, +// reading each table's columns at most once. +func missingColumnStatements(ctx context.Context, db DB, statements []string) ([]string, error) { + existing := make(map[string]map[string]bool) + pending := make([]string, 0, len(statements)) + for _, statement := range statements { + table, column, ok := parseAddColumn(statement) + if !ok { + pending = append(pending, statement) + continue + } + columns, seen := existing[table] + if !seen { + var err error + if columns, err = Columns(ctx, db, table); err != nil { + return nil, err + } + existing[table] = columns + } + if !columns[column] { + pending = append(pending, statement) + } + } + return pending, nil +} + +// parseAddColumn extracts the lowercased table and column from an +// `ALTER TABLE
ADD COLUMN [IF NOT EXISTS] ...` statement. +// ok is false for any other shape, and for quoted or schema-qualified names. +func parseAddColumn(statement string) (table, column string, ok bool) { + f := strings.Fields(statement) + if len(f) < 6 || !keywords(f[:2], "ALTER", "TABLE") || !keywords(f[3:5], "ADD", "COLUMN") { + return "", "", false + } + table, column = f[2], f[5] + if len(f) >= 9 && keywords(f[5:8], "IF", "NOT", "EXISTS") { + column = f[8] + } + if !isPlainIdentifier(table) || !isPlainIdentifier(column) { + return "", "", false + } + return strings.ToLower(table), strings.ToLower(column), true +} + +func keywords(fields []string, want ...string) bool { + for i, w := range want { + if !strings.EqualFold(fields[i], w) { + return false + } + } + return true +} + +// isPlainIdentifier reports whether name is an unquoted SQL identifier, which +// both engines match case-insensitively. +func isPlainIdentifier(name string) bool { + if name == "" { + return false + } + for i, r := range name { + switch { + case r == '_', r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z': + case r >= '0' && r <= '9' && i > 0: + default: + return false + } + } + return true +} + +// Columns reports table's current column names, lowercased; a missing table +// has none. On PostgreSQL the table is looked up in current_schema(), where +// unqualified store SQL resolves it. +// +// The SQLite query interpolates table, so it must be a fixed identifier. +func Columns(ctx context.Context, db DB, table string) (map[string]bool, error) { + var query string + var args []any + switch db.Dialect() { + case SQLite: + query = fmt.Sprintf(`SELECT name FROM pragma_table_info('%s')`, table) + case PostgreSQL: + query = `SELECT column_name FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = ?` + args = []any{table} + default: + return nil, fmt.Errorf("unsupported dialect %q", db.Dialect()) + } + + rows, err := db.Query(ctx, query, args...) + if err != nil { + return nil, fmt.Errorf("inspect %s columns: %w", table, err) + } + defer rows.Close() + + columns := make(map[string]bool) + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return nil, fmt.Errorf("inspect %s columns: %w", table, err) + } + columns[strings.ToLower(name)] = true + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("inspect %s columns: %w", table, err) + } + return columns, nil +} + // addColumnStatement expands type tokens and, on PostgreSQL, turns // `ADD COLUMN` into `ADD COLUMN IF NOT EXISTS`. func (d Dialect) addColumnStatement(statement string) string { diff --git a/internal/storage/sqlx/schema_test.go b/internal/storage/sqlx/schema_test.go index 578cc21d3..f1ed4ff10 100644 --- a/internal/storage/sqlx/schema_test.go +++ b/internal/storage/sqlx/schema_test.go @@ -38,3 +38,31 @@ func TestAddColumnStatement(t *testing.T) { }) } } + +func TestParseAddColumn(t *testing.T) { + tests := []struct { + name string + statement string + table string + column string + ok bool + }{ + {"plain", `ALTER TABLE usage ADD COLUMN user_path TEXT`, "usage", "user_path", true}, + {"type token", `ALTER TABLE t ADD COLUMN flag ` + TypeBool + ` NOT NULL DEFAULT FALSE`, "t", "flag", true}, + {"if not exists", `ALTER TABLE t ADD COLUMN IF NOT EXISTS note TEXT`, "t", "note", true}, + {"mixed case and whitespace", "alter table Audit_Logs\n\tadd column Session_ID TEXT", "audit_logs", "session_id", true}, + {"rename is not an add", `ALTER TABLE t RENAME TO t_old`, "", "", false}, + {"drop column", `ALTER TABLE t DROP COLUMN note`, "", "", false}, + {"quoted column", `ALTER TABLE t ADD COLUMN "Note" TEXT`, "", "", false}, + {"schema-qualified table", `ALTER TABLE s.t ADD COLUMN note TEXT`, "", "", false}, + {"too short", `ALTER TABLE t ADD COLUMN`, "", "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + table, column, ok := parseAddColumn(tt.statement) + assert.Equal(t, tt.ok, ok) + assert.Equal(t, tt.table, table) + assert.Equal(t, tt.column, column) + }) + } +} diff --git a/internal/usage/store_sql_migrate_test.go b/internal/usage/store_sql_migrate_test.go new file mode 100644 index 000000000..268a0a3d8 --- /dev/null +++ b/internal/usage/store_sql_migrate_test.go @@ -0,0 +1,51 @@ +package usage + +import ( + "context" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/enterpilot/gomodel/internal/storage/sqlx" + "github.com/enterpilot/gomodel/internal/storage/sqlx/sqlxtest" +) + +// alterRecorder records the ALTER TABLE statements a store runs. +type alterRecorder struct { + sqlx.DB + alters []string +} + +func (r *alterRecorder) Exec(ctx context.Context, query string, args ...any) (int64, error) { + if strings.HasPrefix(strings.TrimSpace(query), "ALTER TABLE") { + r.alters = append(r.alters, query) + } + return r.DB.Exec(ctx, query, args...) +} + +// Every start re-runs the column migrations. On PostgreSQL even a no-op +// ADD COLUMN IF NOT EXISTS takes an exclusive lock on the table, so a restart +// against an up-to-date schema must issue no ALTER at all. +func TestEnsureUsageSchemaSkipsAppliedColumns(t *testing.T) { + sqlxtest.Run(t, func(t *testing.T, db sqlx.DB) { + ctx := context.Background() + require.NoError(t, ensureUsageSchema(ctx, db)) + + restart := &alterRecorder{DB: db} + require.NoError(t, ensureUsageSchema(ctx, restart)) + assert.Empty(t, restart.alters, "restart against an up-to-date schema") + + _, err := db.Exec(ctx, "ALTER TABLE usage DROP COLUMN costs_calculation_caveat") + require.NoError(t, err) + upgrade := &alterRecorder{DB: db} + require.NoError(t, ensureUsageSchema(ctx, upgrade)) + require.Len(t, upgrade.alters, 1) + assert.Contains(t, upgrade.alters[0], "costs_calculation_caveat") + + columns, err := sqlx.Columns(ctx, db, "usage") + require.NoError(t, err) + assert.True(t, columns["costs_calculation_caveat"], "missing column is added back") + }) +} From c4c64f9605b47c418a44ac12bc4ac7462c894117 Mon Sep 17 00:00:00 2001 From: "Jakub A. W." Date: Thu, 12 Nov 2026 15:53:44 +0100 Subject: [PATCH 2/7] fix(storage): always run multi-action column migrations --- internal/storage/sqlx/schema.go | 6 ++++-- internal/storage/sqlx/schema_test.go | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/storage/sqlx/schema.go b/internal/storage/sqlx/schema.go index ea572582a..eddcc71dd 100644 --- a/internal/storage/sqlx/schema.go +++ b/internal/storage/sqlx/schema.go @@ -79,7 +79,9 @@ func missingColumnStatements(ctx context.Context, db DB, statements []string) ([ // parseAddColumn extracts the lowercased table and column from an // `ALTER TABLE
ADD COLUMN [IF NOT EXISTS] ...` statement. -// ok is false for any other shape, and for quoted or schema-qualified names. +// ok is false for any other shape, for quoted or schema-qualified names, and +// for a statement holding a comma: it may carry further ALTER actions, and +// judging it by its first column alone could skip a missing one. func parseAddColumn(statement string) (table, column string, ok bool) { f := strings.Fields(statement) if len(f) < 6 || !keywords(f[:2], "ALTER", "TABLE") || !keywords(f[3:5], "ADD", "COLUMN") { @@ -89,7 +91,7 @@ func parseAddColumn(statement string) (table, column string, ok bool) { if len(f) >= 9 && keywords(f[5:8], "IF", "NOT", "EXISTS") { column = f[8] } - if !isPlainIdentifier(table) || !isPlainIdentifier(column) { + if strings.Contains(statement, ",") || !isPlainIdentifier(table) || !isPlainIdentifier(column) { return "", "", false } return strings.ToLower(table), strings.ToLower(column), true diff --git a/internal/storage/sqlx/schema_test.go b/internal/storage/sqlx/schema_test.go index f1ed4ff10..c9cc1c490 100644 --- a/internal/storage/sqlx/schema_test.go +++ b/internal/storage/sqlx/schema_test.go @@ -56,6 +56,8 @@ func TestParseAddColumn(t *testing.T) { {"quoted column", `ALTER TABLE t ADD COLUMN "Note" TEXT`, "", "", false}, {"schema-qualified table", `ALTER TABLE s.t ADD COLUMN note TEXT`, "", "", false}, {"too short", `ALTER TABLE t ADD COLUMN`, "", "", false}, + {"several actions", `ALTER TABLE t ADD COLUMN a TEXT, ADD COLUMN b TEXT`, "", "", false}, + {"comma in a type", `ALTER TABLE t ADD COLUMN amount NUMERIC(10,2)`, "", "", false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { From 8cb660ce9bf49dc03d3ddbd4b5386ac1153e5d35 Mon Sep 17 00:00:00 2001 From: "Jakub A. W." Date: Thu, 12 Nov 2026 16:10:30 +0100 Subject: [PATCH 3/7] fix(storage): skip existing indexes at PostgreSQL startup and bound the wait for table locks --- docs/guides/updating.mdx | 8 ++ internal/auditlog/store_sql.go | 5 +- internal/storage/sqlx/export_test.go | 9 ++ internal/storage/sqlx/postgres.go | 22 ++- internal/storage/sqlx/postgres_schema.go | 126 ++++++++++++++++++ .../sqlx/postgres_schema_internal_test.go | 48 +++++++ internal/storage/sqlx/postgres_schema_test.go | 99 ++++++++++++++ internal/storage/sqlx/schema.go | 16 ++- 8 files changed, 324 insertions(+), 9 deletions(-) create mode 100644 internal/storage/sqlx/export_test.go create mode 100644 internal/storage/sqlx/postgres_schema.go create mode 100644 internal/storage/sqlx/postgres_schema_internal_test.go create mode 100644 internal/storage/sqlx/postgres_schema_test.go diff --git a/docs/guides/updating.mdx b/docs/guides/updating.mdx index 0b191ec11..ed630f091 100644 --- a/docs/guides/updating.mdx +++ b/docs/guides/updating.mdx @@ -169,6 +169,13 @@ transform storage instead — when budgets and rate limits gained scopes, their tables were rebuilt and the old ones dropped. Both are safe going forward, which is what makes the reverse direction worth care. +On PostgreSQL, a start that finds the schema up to date changes nothing and +takes no table locks, so starting or restarting a replica does not stall the +others. A migration that does add a column or an index waits for its table half +a second at a time, for about a minute in total. If a long-running statement +holds the table for that whole minute, the start fails instead of queueing +traffic behind it. + ## Pinning a version Updates default to the latest release. To stay on a known version, pin it: @@ -221,6 +228,7 @@ docker run --rm -v gomodel_data:/data -v "$PWD":/backup alpine \ | --- | --- | | Dashboard is empty after the update: no keys, no usage, no logs | The database was not on a volume, or `SQLITE_PATH` resolved somewhere else. Compare the `storage configured` path before and after. | | Gateway will not start after the update | Read the first error line. Configuration that was previously ignored can become validated; the release notes list breaking changes. | +| Start fails with `schema change could not lock its table` | A long-running statement or index build held the table for the minute the migration waited. Start again once it has finished; nothing was half applied. | | The version did not change | The old container is still running (`docker ps`), or a second `gomodel` binary earlier in `PATH` is being launched. | Still stuck? Ask on [Discord](https://discord.gg/gaEB9BQSPH) or open a diff --git a/internal/auditlog/store_sql.go b/internal/auditlog/store_sql.go index cffad32d0..0614cf4f7 100644 --- a/internal/auditlog/store_sql.go +++ b/internal/auditlog/store_sql.go @@ -181,8 +181,11 @@ func NewSQLStore(ctx context.Context, db sqlx.DB, retentionDays int) (*SQLStore, if db.Dialect() != sqlx.PostgreSQL { indexes = append(indexes, modelIndexStatements(db.Dialect())...) } + // One Schema call per statement keeps them best-effort, and on PostgreSQL + // skips the indexes that already exist instead of queueing each for a + // lock on audit_logs. for _, statement := range indexes { - if _, err := db.Exec(ctx, statement); err != nil { + if err := db.Schema(ctx, statement); err != nil { slog.Warn("failed to create index", "error", err) } } diff --git a/internal/storage/sqlx/export_test.go b/internal/storage/sqlx/export_test.go new file mode 100644 index 000000000..7993a9c96 --- /dev/null +++ b/internal/storage/sqlx/export_test.go @@ -0,0 +1,9 @@ +package sqlx + +import "time" + +// SetLockWait shortens how long db's schema changes wait for a table lock, so +// a test of a blocked change does not wait out the production bounds. +func SetLockWait(db DB, timeout, pause time.Duration, attempts int) { + db.(*postgresDB).lockWait = lockWait{timeout: timeout, pause: pause, attempts: attempts} +} diff --git a/internal/storage/sqlx/postgres.go b/internal/storage/sqlx/postgres.go index 85305f7b9..98f04ea6a 100644 --- a/internal/storage/sqlx/postgres.go +++ b/internal/storage/sqlx/postgres.go @@ -13,7 +13,8 @@ import ( // postgresDB adapts a pgx connection pool to DB. Queries arrive with `?` // placeholders and are rebound to $1, $2, ... on the way through. type postgresDB struct { - pool *pgxpool.Pool + pool *pgxpool.Pool + lockWait lockWait } // NewPostgreSQL wraps a pgx pool. The caller retains ownership of the pool. @@ -21,7 +22,7 @@ func NewPostgreSQL(pool *pgxpool.Pool) (DB, error) { if pool == nil { return nil, fmt.Errorf("connection pool is required") } - return &postgresDB{pool: pool}, nil + return &postgresDB{pool: pool, lockWait: defaultLockWait}, nil } func (p *postgresDB) Dialect() Dialect { return PostgreSQL } @@ -63,12 +64,19 @@ const postgresSchemaLockKey int64 = 0x676f6d6f64656c // fresh database hit exactly that. The transaction-scoped lock serializes // them: the second replica waits, then finds every table present. // PostgreSQL DDL is transactional, so a failure leaves nothing half-applied. +// +// Indexes that already exist are skipped, and the rest wait only briefly for +// a table lock; see postgres_schema.go. func (p *postgresDB) Schema(ctx context.Context, statements ...string) error { - return p.InTx(ctx, func(q Querier) error { - if _, err := q.Exec(ctx, "SELECT pg_advisory_xact_lock(?)", postgresSchemaLockKey); err != nil { - return fmt.Errorf("acquire schema lock: %w", err) - } - return execSchema(ctx, q, PostgreSQL, statements) + pending, err := p.pendingSchema(ctx, statements) + if err != nil { + return err + } + if len(pending) == 0 { + return nil + } + return p.changeSchema(ctx, func(q Querier) error { + return execSchema(ctx, q, PostgreSQL, pending) }) } diff --git a/internal/storage/sqlx/postgres_schema.go b/internal/storage/sqlx/postgres_schema.go new file mode 100644 index 000000000..8c75ccb30 --- /dev/null +++ b/internal/storage/sqlx/postgres_schema.go @@ -0,0 +1,126 @@ +package sqlx + +import ( + "context" + "errors" + "fmt" + "log/slog" + "regexp" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgconn" +) + +// Store constructors re-apply their whole schema on every start, and several +// replicas start against one database. AddColumns already leaves out the +// columns that exist. A `CREATE INDEX IF NOT EXISTS` that changes nothing has +// the same problem: it still queues for a SHARE lock on its table first, which +// waits for every write in progress, and every later write on the table then +// queues behind it. So the index statements that would change nothing are not +// sent at all, and the schema changes that are needed stop waiting for their +// lock after lockWait rather than hold the table's traffic up behind them. + +// lockWait bounds how long a schema change waits for a table lock. +type lockWait struct { + // timeout is how long one attempt waits. It stays below PostgreSQL's + // default deadlock_timeout of one second: a schema change and a + // CREATE INDEX CONCURRENTLY wait on each other, and the deadlock check + // would cancel the build, which loses minutes of work, rather than the + // schema change, which loses nothing. + timeout time.Duration + // pause lets the statements that queued behind a failed attempt run + // before the next one. + pause time.Duration + attempts int +} + +var defaultLockWait = lockWait{timeout: 500 * time.Millisecond, pause: time.Second, attempts: 40} + +// lockNotAvailable is the SQLSTATE of a statement cancelled by lock_timeout. +const lockNotAvailable = "55P03" + +const pgIdentifier = `(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)` + +var createIndexPattern = regexp.MustCompile(`(?is)^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+IF\s+NOT\s+EXISTS\s+(` + + pgIdentifier + `)\s+ON\s+(` + pgIdentifier + `(?:\.` + pgIdentifier + `)?)`) + +// changeSchema runs fn in a transaction that holds the schema advisory lock +// and gives up waiting for a table lock after lockWait.timeout, retrying the +// whole transaction when it does. +func (p *postgresDB) changeSchema(ctx context.Context, fn func(Querier) error) error { + var err error + for attempt := 1; ; attempt++ { + err = p.InTx(ctx, func(q Querier) error { + if _, err := q.Exec(ctx, "SELECT pg_advisory_xact_lock(?)", postgresSchemaLockKey); err != nil { + return fmt.Errorf("acquire schema lock: %w", err) + } + // Set after the advisory lock: lock_timeout bounds that wait + // too, and replicas queueing to apply their schema is expected. + timeout := fmt.Sprintf("SET LOCAL lock_timeout = %d", p.lockWait.timeout.Milliseconds()) + if _, err := q.Exec(ctx, timeout); err != nil { + return fmt.Errorf("set lock timeout: %w", err) + } + return fn(q) + }) + if !isLockTimeout(err) || attempt >= p.lockWait.attempts { + break + } + if attempt == 1 { + slog.Warn("schema change is waiting for a table lock; retrying", "error", err) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(p.lockWait.pause): + } + } + if isLockTimeout(err) { + return fmt.Errorf("schema change could not lock its table in %d attempts; a long-running statement or index build holds it: %w", + p.lockWait.attempts, err) + } + return err +} + +func isLockTimeout(err error) bool { + pgErr, ok := errors.AsType[*pgconn.PgError](err) + return ok && pgErr.Code == lockNotAvailable +} + +// pendingSchema drops the CREATE INDEX IF NOT EXISTS statements whose index +// already exists. A statement it cannot parse is kept, so it runs as written. +func (p *postgresDB) pendingSchema(ctx context.Context, statements []string) ([]string, error) { + pending := make([]string, 0, len(statements)) + for _, statement := range statements { + match := createIndexPattern.FindStringSubmatch(statement) + if match == nil { + pending = append(pending, statement) + continue + } + // IF NOT EXISTS looks for any relation of that name in the table's + // schema, so this does too. + var exists bool + err := p.QueryRow(ctx, ` + SELECT EXISTS ( + SELECT 1 FROM pg_class i + JOIN pg_class t ON t.relnamespace = i.relnamespace + WHERE t.oid = to_regclass(?) AND i.relname = ? + )`, match[2], identifierName(match[1])).Scan(&exists) + if err != nil { + return nil, fmt.Errorf("look up index %s: %w", match[1], err) + } + if !exists { + pending = append(pending, statement) + } + } + return pending, nil +} + +// identifierName is the name PostgreSQL stores for an identifier as written +// in SQL: a quoted one verbatim, an unquoted one folded to lower case. +func identifierName(identifier string) string { + if strings.HasPrefix(identifier, `"`) { + return strings.ReplaceAll(identifier[1:len(identifier)-1], `""`, `"`) + } + return strings.ToLower(identifier) +} diff --git a/internal/storage/sqlx/postgres_schema_internal_test.go b/internal/storage/sqlx/postgres_schema_internal_test.go new file mode 100644 index 000000000..72fc1e93d --- /dev/null +++ b/internal/storage/sqlx/postgres_schema_internal_test.go @@ -0,0 +1,48 @@ +package sqlx + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCreateIndexPattern(t *testing.T) { + tests := []struct { + name string + statement string + index string + table string + }{ + {name: "plain", statement: `CREATE INDEX IF NOT EXISTS idx_usage_model ON usage(model)`, index: "idx_usage_model", table: "usage"}, + {name: "unique across lines", statement: "\n\tCREATE UNIQUE INDEX IF NOT EXISTS idx_scope\n\t\tON workflow_versions (scope_key) WHERE active", index: "idx_scope", table: "workflow_versions"}, + {name: "access method", statement: `CREATE INDEX IF NOT EXISTS idx_gin ON usage USING GIN (raw_data)`, index: "idx_gin", table: "usage"}, + {name: "quoted", statement: `CREATE INDEX IF NOT EXISTS "Cache_idx" ON "my ""cache""" (expires_at)`, index: `"Cache_idx"`, table: `"my ""cache"""`}, + {name: "schema qualified", statement: `create index if not exists idx_a on public.items(a)`, index: "idx_a", table: "public.items"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + match := createIndexPattern.FindStringSubmatch(tt.statement) + require.NotNil(t, match) + assert.Equal(t, tt.index, match[1]) + assert.Equal(t, tt.table, match[2]) + }) + } + + // Without IF NOT EXISTS the statement must run: a skipped duplicate + // would hide the error the caller asked for. + for _, statement := range []string{ + `CREATE INDEX idx_usage_model ON usage(model)`, + `CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_model ON usage(model)`, + `DROP INDEX IF EXISTS idx_usage_model`, + `CREATE TABLE IF NOT EXISTS usage (id TEXT)`, + } { + assert.Nil(t, createIndexPattern.FindStringSubmatch(statement), statement) + } +} + +func TestIdentifierName(t *testing.T) { + assert.Equal(t, "idx_usage_model", identifierName("IDX_Usage_Model")) + assert.Equal(t, "Cache_idx", identifierName(`"Cache_idx"`)) + assert.Equal(t, `my "cache"`, identifierName(`"my ""cache"""`)) +} diff --git a/internal/storage/sqlx/postgres_schema_test.go b/internal/storage/sqlx/postgres_schema_test.go new file mode 100644 index 000000000..0136c5fa4 --- /dev/null +++ b/internal/storage/sqlx/postgres_schema_test.go @@ -0,0 +1,99 @@ +package sqlx_test + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/enterpilot/gomodel/internal/storage/sqlx" + "github.com/enterpilot/gomodel/internal/storage/sqlx/sqlxtest" +) + +const lockedTable = `CREATE TABLE IF NOT EXISTS locked (id TEXT PRIMARY KEY, model TEXT)` + +// newLockedTable returns a PostgreSQL DB whose `locked` table has a row +// inserted by a transaction that stays open until release is called: the +// state of a table under a long-running write on another replica. +func newLockedTable(t *testing.T) (db sqlx.DB, release func()) { + t.Helper() + pool := sqlxtest.NewPostgresPool(t) + if pool == nil { + return nil, nil + } + db, err := sqlx.NewPostgreSQL(pool) + require.NoError(t, err) + ctx := context.Background() + require.NoError(t, db.Schema(ctx, lockedTable, `CREATE INDEX IF NOT EXISTS idx_locked_model ON locked(model)`)) + require.NoError(t, sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN note TEXT`)) + + tx, err := pool.Begin(ctx) + require.NoError(t, err) + _, err = tx.Exec(ctx, `INSERT INTO locked (id) VALUES ('held')`) + require.NoError(t, err) + var once sync.Once + release = func() { + once.Do(func() { assert.NoError(t, tx.Rollback(ctx)) }) + } + t.Cleanup(release) + return db, release +} + +// A replica starting against an up-to-date schema must not queue for a table +// lock: the statements waiting behind it would stall every other replica. +func TestAppliedSchemaDoesNotWaitForTableLock(t *testing.T) { + db, _ := newLockedTable(t) + if db == nil { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + started := time.Now() + require.NoError(t, db.Schema(ctx, lockedTable, `CREATE INDEX IF NOT EXISTS idx_locked_model ON locked(model)`)) + require.NoError(t, sqlx.AddColumns(ctx, db, + `ALTER TABLE locked ADD COLUMN note TEXT`, + `ALTER TABLE locked ADD COLUMN IF NOT EXISTS model TEXT`, + )) + assert.Less(t, time.Since(started), 2*time.Second) +} + +func TestSchemaChangeGivesUpOnAHeldTableLock(t *testing.T) { + db, release := newLockedTable(t) + if db == nil { + return + } + sqlx.SetLockWait(db, 50*time.Millisecond, 10*time.Millisecond, 3) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + err := sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN enabled `+sqlx.TypeBool+` NOT NULL DEFAULT FALSE`) + require.ErrorContains(t, err, "could not lock its table") + err = db.Schema(ctx, `CREATE INDEX IF NOT EXISTS idx_locked_note ON locked(note)`) + require.ErrorContains(t, err, "could not lock its table") + + // Nothing was left half-applied, and both go through once the table is free. + release() + require.NoError(t, sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN enabled `+sqlx.TypeBool+` NOT NULL DEFAULT FALSE`)) + require.NoError(t, db.Schema(ctx, `CREATE INDEX IF NOT EXISTS idx_locked_note ON locked(note)`)) + _, err = db.Exec(ctx, `INSERT INTO locked (id, enabled, note) VALUES (?, ?, ?)`, "a", true, "n") + require.NoError(t, err) +} + +func TestSchemaChangeRetriesUntilTheTableLockIsFree(t *testing.T) { + db, release := newLockedTable(t) + if db == nil { + return + } + sqlx.SetLockWait(db, 50*time.Millisecond, 10*time.Millisecond, 200) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + time.AfterFunc(300*time.Millisecond, release) + require.NoError(t, sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN enabled `+sqlx.TypeBool+` NOT NULL DEFAULT FALSE`)) + _, err := db.Exec(ctx, `INSERT INTO locked (id, enabled) VALUES (?, ?)`, "a", true) + require.NoError(t, err) +} diff --git a/internal/storage/sqlx/schema.go b/internal/storage/sqlx/schema.go index eddcc71dd..53689689e 100644 --- a/internal/storage/sqlx/schema.go +++ b/internal/storage/sqlx/schema.go @@ -43,7 +43,7 @@ func AddColumns(ctx context.Context, db DB, statements ...string) error { } dialect := db.Dialect() for _, statement := range pending { - _, err := db.Exec(ctx, dialect.addColumnStatement(statement)) + err := execAddColumn(ctx, db, dialect.addColumnStatement(statement)) if err != nil && !IsDuplicateColumnError(err) { return fmt.Errorf("apply migration %q: %w", statement, err) } @@ -51,6 +51,20 @@ func AddColumns(ctx context.Context, db DB, statements ...string) error { return nil } +// execAddColumn runs one column migration. On PostgreSQL it bounds the wait +// for the table lock (see postgresDB.changeSchema), one transaction per +// statement so a tolerated duplicate-column error ends only its own. +func execAddColumn(ctx context.Context, db DB, statement string) error { + if p, ok := db.(*postgresDB); ok { + return p.changeSchema(ctx, func(q Querier) error { + _, err := q.Exec(ctx, statement) + return err + }) + } + _, err := db.Exec(ctx, statement) + return err +} + // missingColumnStatements drops the statements whose column already exists, // reading each table's columns at most once. func missingColumnStatements(ctx context.Context, db DB, statements []string) ([]string, error) { From a0dd1f9d65cf2b68192639f274206a04dc81275b Mon Sep 17 00:00:00 2001 From: "Jakub A. W." Date: Fri, 13 Nov 2026 21:12:31 +0100 Subject: [PATCH 4/7] fix(storage): recheck pending schema changes once the schema lock is held --- docs/guides/updating.mdx | 12 +-- internal/auditlog/store_sql.go | 11 ++- internal/storage/sqlx/export_test.go | 4 + internal/storage/sqlx/postgres.go | 19 ++-- internal/storage/sqlx/postgres_schema.go | 17 ++-- internal/storage/sqlx/postgres_schema_test.go | 89 ++++++++++++++++++- internal/storage/sqlx/schema.go | 42 ++++++--- 7 files changed, 160 insertions(+), 34 deletions(-) diff --git a/docs/guides/updating.mdx b/docs/guides/updating.mdx index ed630f091..075572444 100644 --- a/docs/guides/updating.mdx +++ b/docs/guides/updating.mdx @@ -171,10 +171,12 @@ is what makes the reverse direction worth care. On PostgreSQL, a start that finds the schema up to date changes nothing and takes no table locks, so starting or restarting a replica does not stall the -others. A migration that does add a column or an index waits for its table half -a second at a time, for about a minute in total. If a long-running statement -holds the table for that whole minute, the start fails instead of queueing -traffic behind it. +others. A migration that does add a table, column, or index waits for its table +half a second at a time, for about a minute per statement. If a long-running +statement holds the table for that whole minute, a table or column migration +fails the start instead of queueing traffic behind it. An audit log index that +cannot get its table is skipped with a logged warning, along with the audit +indexes after it, and the start continues; the next start creates them. ## Pinning a version @@ -228,7 +230,7 @@ docker run --rm -v gomodel_data:/data -v "$PWD":/backup alpine \ | --- | --- | | Dashboard is empty after the update: no keys, no usage, no logs | The database was not on a volume, or `SQLITE_PATH` resolved somewhere else. Compare the `storage configured` path before and after. | | Gateway will not start after the update | Read the first error line. Configuration that was previously ignored can become validated; the release notes list breaking changes. | -| Start fails with `schema change could not lock its table` | A long-running statement or index build held the table for the minute the migration waited. Start again once it has finished; nothing was half applied. | +| Start fails with `schema change could not lock its table` | A long-running statement or index build held the table for the minute the migration waited. Start again once it has finished. Columns added earlier in the same start stay in place and are skipped next time. | | The version did not change | The old container is still running (`docker ps`), or a second `gomodel` binary earlier in `PATH` is being launched. | Still stuck? Ask on [Discord](https://discord.gg/gaEB9BQSPH) or open a diff --git a/internal/auditlog/store_sql.go b/internal/auditlog/store_sql.go index 0614cf4f7..e929a8664 100644 --- a/internal/auditlog/store_sql.go +++ b/internal/auditlog/store_sql.go @@ -2,6 +2,7 @@ package auditlog import ( "context" + "errors" "fmt" "log/slog" "strings" @@ -183,9 +184,15 @@ func NewSQLStore(ctx context.Context, db sqlx.DB, retentionDays int) (*SQLStore, } // One Schema call per statement keeps them best-effort, and on PostgreSQL // skips the indexes that already exist instead of queueing each for a - // lock on audit_logs. + // lock on audit_logs. A statement that gave up on that lock ends the + // loop: each of the rest would wait it out again, a minute at a time. for _, statement := range indexes { - if err := db.Schema(ctx, statement); err != nil { + err := db.Schema(ctx, statement) + if errors.Is(err, sqlx.ErrTableLocked) { + slog.Warn("audit log table is locked; the remaining indexes are left for the next start", "error", err) + break + } + if err != nil { slog.Warn("failed to create index", "error", err) } } diff --git a/internal/storage/sqlx/export_test.go b/internal/storage/sqlx/export_test.go index 7993a9c96..f594c5730 100644 --- a/internal/storage/sqlx/export_test.go +++ b/internal/storage/sqlx/export_test.go @@ -7,3 +7,7 @@ import "time" func SetLockWait(db DB, timeout, pause time.Duration, attempts int) { db.(*postgresDB).lockWait = lockWait{timeout: timeout, pause: pause, attempts: attempts} } + +// SchemaLockKey is the advisory lock a schema change holds, for a test that +// plays the replica holding it. +const SchemaLockKey = postgresSchemaLockKey diff --git a/internal/storage/sqlx/postgres.go b/internal/storage/sqlx/postgres.go index 98f04ea6a..ada46f3de 100644 --- a/internal/storage/sqlx/postgres.go +++ b/internal/storage/sqlx/postgres.go @@ -50,7 +50,8 @@ func (p *postgresDB) QueryRow(ctx context.Context, query string, args ...any) Ro return pgQueryRow(ctx, p.pool, query, args...) } -// postgresSchemaLockKey is the advisory lock every Schema call takes. One key +// postgresSchemaLockKey is the advisory lock every schema change takes; a +// Schema call that finds nothing to change takes none. One key // for the whole gateway is deliberate: each store's DDL is short, and the // alternative (a key per store) buys nothing while making the lock easy to // forget in a new store. @@ -68,14 +69,20 @@ const postgresSchemaLockKey int64 = 0x676f6d6f64656c // Indexes that already exist are skipped, and the rest wait only briefly for // a table lock; see postgres_schema.go. func (p *postgresDB) Schema(ctx context.Context, statements ...string) error { - pending, err := p.pendingSchema(ctx, statements) - if err != nil { + // Checked without the lock first, so that a start against an up-to-date + // schema takes none. + pending, err := pendingSchema(ctx, p, statements) + if err != nil || len(pending) == 0 { return err } - if len(pending) == 0 { - return nil - } return p.changeSchema(ctx, func(q Querier) error { + // Checked again under the lock, on every attempt: a replica that + // queued here behind another one finds the index built, and must not + // queue for the table to create nothing. + pending, err := pendingSchema(ctx, q, statements) + if err != nil { + return err + } return execSchema(ctx, q, PostgreSQL, pending) }) } diff --git a/internal/storage/sqlx/postgres_schema.go b/internal/storage/sqlx/postgres_schema.go index 8c75ccb30..fb91dc7fb 100644 --- a/internal/storage/sqlx/postgres_schema.go +++ b/internal/storage/sqlx/postgres_schema.go @@ -37,6 +37,10 @@ type lockWait struct { var defaultLockWait = lockWait{timeout: 500 * time.Millisecond, pause: time.Second, attempts: 40} +// ErrTableLocked reports a schema change that gave up waiting for its table +// lock: a long-running statement or index build held the table throughout. +var ErrTableLocked = errors.New("schema change could not lock its table") + // lockNotAvailable is the SQLSTATE of a statement cancelled by lock_timeout. const lockNotAvailable = "55P03" @@ -55,8 +59,9 @@ func (p *postgresDB) changeSchema(ctx context.Context, fn func(Querier) error) e if _, err := q.Exec(ctx, "SELECT pg_advisory_xact_lock(?)", postgresSchemaLockKey); err != nil { return fmt.Errorf("acquire schema lock: %w", err) } - // Set after the advisory lock: lock_timeout bounds that wait - // too, and replicas queueing to apply their schema is expected. + // Set only once the advisory lock is held, so that it bounds + // the wait for a table and not the wait above: replicas queueing + // there to apply their schema is expected. timeout := fmt.Sprintf("SET LOCAL lock_timeout = %d", p.lockWait.timeout.Milliseconds()) if _, err := q.Exec(ctx, timeout); err != nil { return fmt.Errorf("set lock timeout: %w", err) @@ -76,8 +81,8 @@ func (p *postgresDB) changeSchema(ctx context.Context, fn func(Querier) error) e } } if isLockTimeout(err) { - return fmt.Errorf("schema change could not lock its table in %d attempts; a long-running statement or index build holds it: %w", - p.lockWait.attempts, err) + return fmt.Errorf("%w in %d attempts; a long-running statement or index build holds it: %w", + ErrTableLocked, p.lockWait.attempts, err) } return err } @@ -89,7 +94,7 @@ func isLockTimeout(err error) bool { // pendingSchema drops the CREATE INDEX IF NOT EXISTS statements whose index // already exists. A statement it cannot parse is kept, so it runs as written. -func (p *postgresDB) pendingSchema(ctx context.Context, statements []string) ([]string, error) { +func pendingSchema(ctx context.Context, q Querier, statements []string) ([]string, error) { pending := make([]string, 0, len(statements)) for _, statement := range statements { match := createIndexPattern.FindStringSubmatch(statement) @@ -100,7 +105,7 @@ func (p *postgresDB) pendingSchema(ctx context.Context, statements []string) ([] // IF NOT EXISTS looks for any relation of that name in the table's // schema, so this does too. var exists bool - err := p.QueryRow(ctx, ` + err := q.QueryRow(ctx, ` SELECT EXISTS ( SELECT 1 FROM pg_class i JOIN pg_class t ON t.relnamespace = i.relnamespace diff --git a/internal/storage/sqlx/postgres_schema_test.go b/internal/storage/sqlx/postgres_schema_test.go index 0136c5fa4..18cbea7af 100644 --- a/internal/storage/sqlx/postgres_schema_test.go +++ b/internal/storage/sqlx/postgres_schema_test.go @@ -72,10 +72,18 @@ func TestSchemaChangeGivesUpOnAHeldTableLock(t *testing.T) { err := sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN enabled `+sqlx.TypeBool+` NOT NULL DEFAULT FALSE`) require.ErrorContains(t, err, "could not lock its table") + require.ErrorIs(t, err, sqlx.ErrTableLocked) err = db.Schema(ctx, `CREATE INDEX IF NOT EXISTS idx_locked_note ON locked(note)`) require.ErrorContains(t, err, "could not lock its table") + require.ErrorIs(t, err, sqlx.ErrTableLocked) - // Nothing was left half-applied, and both go through once the table is free. + // The failed change left nothing behind: read from the catalog, which + // needs no lock on the table, while it is still held. + columns, err := sqlx.Columns(ctx, db, "locked") + require.NoError(t, err) + require.NotContains(t, columns, "enabled") + + // Both go through once the table is free. release() require.NoError(t, sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN enabled `+sqlx.TypeBool+` NOT NULL DEFAULT FALSE`)) require.NoError(t, db.Schema(ctx, `CREATE INDEX IF NOT EXISTS idx_locked_note ON locked(note)`)) @@ -97,3 +105,82 @@ func TestSchemaChangeRetriesUntilTheTableLockIsFree(t *testing.T) { _, err := db.Exec(ctx, `INSERT INTO locked (id, enabled) VALUES (?, ?)`, "a", true) require.NoError(t, err) } + +// Two replicas start during a migration. One applies it while the other waits +// its turn; a long write then takes the table. The second replica must see +// that there is nothing left to do rather than queue for the table, stall the +// writes behind it and fail its start on a change that is already applied. +func TestSchemaChangeRechecksAfterWaitingForAnotherReplica(t *testing.T) { + tests := []struct { + name string + statement string + apply func(ctx context.Context, db sqlx.DB, statement string) error + }{ + { + name: "index", + statement: `CREATE INDEX IF NOT EXISTS idx_locked_note ON locked(note)`, + apply: func(ctx context.Context, db sqlx.DB, statement string) error { return db.Schema(ctx, statement) }, + }, + { + name: "column", + statement: `ALTER TABLE locked ADD COLUMN IF NOT EXISTS enabled BOOLEAN NOT NULL DEFAULT FALSE`, + apply: func(ctx context.Context, db sqlx.DB, statement string) error { + return sqlx.AddColumns(ctx, db, statement) + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + pool := sqlxtest.NewPostgresPool(t) + if pool == nil { + return + } + db, err := sqlx.NewPostgreSQL(pool) + require.NoError(t, err) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + require.NoError(t, db.Schema(ctx, lockedTable)) + require.NoError(t, sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN note TEXT`)) + sqlx.SetLockWait(db, 50*time.Millisecond, 10*time.Millisecond, 3) + waiting := func(query string, args ...any) func() bool { + return func() bool { + var count int + err := pool.QueryRow(ctx, query, args...).Scan(&count) + return err == nil && count > 0 + } + } + + // The other replica holds the schema lock, and this one queues. + other, err := pool.Begin(ctx) + require.NoError(t, err) + defer func() { _ = other.Rollback(context.Background()) }() + _, err = other.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, sqlx.SchemaLockKey) + require.NoError(t, err) + applied := make(chan error, 1) + go func() { applied <- tt.apply(ctx, db, tt.statement) }() + require.Eventually(t, waiting( + `SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' AND NOT granted AND objid = $1::bigint & 4294967295`, + sqlx.SchemaLockKey), 10*time.Second, 10*time.Millisecond, "this replica waits for the schema lock") + + // The other replica applies the change. A write queues for the + // table behind it, and holds the table from the moment it commits. + _, err = other.Exec(ctx, tt.statement) + require.NoError(t, err) + writer, err := pool.Begin(ctx) + require.NoError(t, err) + defer func() { _ = writer.Rollback(context.Background()) }() + wrote := make(chan error, 1) + go func() { + _, err := writer.Exec(ctx, `INSERT INTO locked (id) VALUES ('held')`) + wrote <- err + }() + require.Eventually(t, waiting( + `SELECT count(*) FROM pg_locks WHERE relation = 'locked'::regclass AND NOT granted`), + 10*time.Second, 10*time.Millisecond, "the write waits for the table") + require.NoError(t, other.Commit(ctx)) + require.NoError(t, <-wrote) + + require.NoError(t, <-applied, "a change another replica applied meanwhile is not attempted again") + }) + } +} diff --git a/internal/storage/sqlx/schema.go b/internal/storage/sqlx/schema.go index 53689689e..03432ae8c 100644 --- a/internal/storage/sqlx/schema.go +++ b/internal/storage/sqlx/schema.go @@ -37,11 +37,11 @@ func execSchema(ctx context.Context, q Querier, dialect Dialect, statements []st // spelling (see addColumnStatement), because replicas starting together can // all see a column missing and race to add it. func AddColumns(ctx context.Context, db DB, statements ...string) error { - pending, err := missingColumnStatements(ctx, db, statements) + dialect := db.Dialect() + pending, err := missingColumnStatements(ctx, db, dialect, statements) if err != nil { return err } - dialect := db.Dialect() for _, statement := range pending { err := execAddColumn(ctx, db, dialect.addColumnStatement(statement)) if err != nil && !IsDuplicateColumnError(err) { @@ -55,19 +55,27 @@ func AddColumns(ctx context.Context, db DB, statements ...string) error { // for the table lock (see postgresDB.changeSchema), one transaction per // statement so a tolerated duplicate-column error ends only its own. func execAddColumn(ctx context.Context, db DB, statement string) error { - if p, ok := db.(*postgresDB); ok { - return p.changeSchema(ctx, func(q Querier) error { - _, err := q.Exec(ctx, statement) - return err - }) + p, ok := db.(*postgresDB) + if !ok { + _, err := db.Exec(ctx, statement) + return err } - _, err := db.Exec(ctx, statement) - return err + return p.changeSchema(ctx, func(q Querier) error { + // Checked again under the lock, on every attempt: a replica that + // queued here behind another one finds the column added, and must + // not queue for the table to add nothing. + pending, err := missingColumnStatements(ctx, q, PostgreSQL, []string{statement}) + if err != nil || len(pending) == 0 { + return err + } + _, err = q.Exec(ctx, statement) + return err + }) } // missingColumnStatements drops the statements whose column already exists, // reading each table's columns at most once. -func missingColumnStatements(ctx context.Context, db DB, statements []string) ([]string, error) { +func missingColumnStatements(ctx context.Context, q Querier, dialect Dialect, statements []string) ([]string, error) { existing := make(map[string]map[string]bool) pending := make([]string, 0, len(statements)) for _, statement := range statements { @@ -79,7 +87,7 @@ func missingColumnStatements(ctx context.Context, db DB, statements []string) ([ columns, seen := existing[table] if !seen { var err error - if columns, err = Columns(ctx, db, table); err != nil { + if columns, err = columnsOf(ctx, q, dialect, table); err != nil { return nil, err } existing[table] = columns @@ -143,9 +151,15 @@ func isPlainIdentifier(name string) bool { // // The SQLite query interpolates table, so it must be a fixed identifier. func Columns(ctx context.Context, db DB, table string) (map[string]bool, error) { + return columnsOf(ctx, db, db.Dialect(), table) +} + +// columnsOf is Columns on any Querier, so it can also read inside a +// transaction. +func columnsOf(ctx context.Context, q Querier, dialect Dialect, table string) (map[string]bool, error) { var query string var args []any - switch db.Dialect() { + switch dialect { case SQLite: query = fmt.Sprintf(`SELECT name FROM pragma_table_info('%s')`, table) case PostgreSQL: @@ -153,10 +167,10 @@ func Columns(ctx context.Context, db DB, table string) (map[string]bool, error) WHERE table_schema = current_schema() AND table_name = ?` args = []any{table} default: - return nil, fmt.Errorf("unsupported dialect %q", db.Dialect()) + return nil, fmt.Errorf("unsupported dialect %q", dialect) } - rows, err := db.Query(ctx, query, args...) + rows, err := q.Query(ctx, query, args...) if err != nil { return nil, fmt.Errorf("inspect %s columns: %w", table, err) } From 0389194d363d61433d0fc8721b9199a2c8fbf33f Mon Sep 17 00:00:00 2001 From: "Jakub A. W." Date: Fri, 13 Nov 2026 21:27:54 +0100 Subject: [PATCH 5/7] test(storage): match the schema lock exactly when waiting for a queued replica --- internal/storage/sqlx/postgres_schema_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/internal/storage/sqlx/postgres_schema_test.go b/internal/storage/sqlx/postgres_schema_test.go index 18cbea7af..81bd94c97 100644 --- a/internal/storage/sqlx/postgres_schema_test.go +++ b/internal/storage/sqlx/postgres_schema_test.go @@ -159,7 +159,10 @@ func TestSchemaChangeRechecksAfterWaitingForAnotherReplica(t *testing.T) { applied := make(chan error, 1) go func() { applied <- tt.apply(ctx, db, tt.statement) }() require.Eventually(t, waiting( - `SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' AND NOT granted AND objid = $1::bigint & 4294967295`, + `SELECT count(*) FROM pg_locks + WHERE locktype = 'advisory' AND NOT granted + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()) + AND classid = ($1::bigint >> 32) AND objid = ($1::bigint & 4294967295) AND objsubid = 1`, sqlx.SchemaLockKey), 10*time.Second, 10*time.Millisecond, "this replica waits for the schema lock") // The other replica applies the change. A write queues for the From d308c2d94721fd38c7b027ba87bdd44ae520f2e0 Mon Sep 17 00:00:00 2001 From: "Jakub A. W." Date: Wed, 18 Nov 2026 22:15:20 +0100 Subject: [PATCH 6/7] fix(requestlog): name request logs in the skipped-index warning and docs --- docs/guides/updating.mdx | 7 ++++--- internal/requestlog/store_sql.go | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/guides/updating.mdx b/docs/guides/updating.mdx index bf024be33..59a3b2eb5 100644 --- a/docs/guides/updating.mdx +++ b/docs/guides/updating.mdx @@ -174,9 +174,10 @@ takes no table locks, so starting or restarting a replica does not stall the others. A migration that does add a table, column, or index waits for its table half a second at a time, for about a minute per statement. If a long-running statement holds the table for that whole minute, a table or column migration -fails the start instead of queueing traffic behind it. An audit log index that -cannot get its table is skipped with a logged warning, along with the audit -indexes after it, and the start continues; the next start creates them. +fails the start instead of queueing traffic behind it. A request log index +that cannot get its table is skipped with a logged warning, along with the +request log indexes after it, and the start continues; the next start creates +them. ## Pinning a version diff --git a/internal/requestlog/store_sql.go b/internal/requestlog/store_sql.go index be37a5e2e..146421bbd 100644 --- a/internal/requestlog/store_sql.go +++ b/internal/requestlog/store_sql.go @@ -235,7 +235,7 @@ func ensureSQLSchema(ctx context.Context, db sqlx.DB) error { for _, statement := range indexes { err := db.Schema(ctx, statement) if errors.Is(err, sqlx.ErrTableLocked) { - slog.Warn("audit log table is locked; the remaining indexes are left for the next start", "error", err) + slog.Warn("request log table is locked; the remaining indexes are left for the next start", "error", err) break } if err != nil { From 3184c86138f94fb79b2f4e9f2417196bc6b63a05 Mon Sep 17 00:00:00 2001 From: "Jakub A. W." Date: Fri, 27 Nov 2026 17:28:19 +0100 Subject: [PATCH 7/7] fix(storage): keep an index statement that an earlier one in the batch names or that is only partly parsed --- internal/storage/sqlx/postgres_schema.go | 17 ++++++++++---- .../sqlx/postgres_schema_internal_test.go | 2 ++ internal/storage/sqlx/postgres_schema_test.go | 22 +++++++++++++++++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/internal/storage/sqlx/postgres_schema.go b/internal/storage/sqlx/postgres_schema.go index fb91dc7fb..9a09e4d6a 100644 --- a/internal/storage/sqlx/postgres_schema.go +++ b/internal/storage/sqlx/postgres_schema.go @@ -6,6 +6,7 @@ import ( "fmt" "log/slog" "regexp" + "slices" "strings" "time" @@ -47,7 +48,7 @@ const lockNotAvailable = "55P03" const pgIdentifier = `(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)` var createIndexPattern = regexp.MustCompile(`(?is)^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+IF\s+NOT\s+EXISTS\s+(` + - pgIdentifier + `)\s+ON\s+(` + pgIdentifier + `(?:\.` + pgIdentifier + `)?)`) + pgIdentifier + `)\s+ON\s+(` + pgIdentifier + `(?:\.` + pgIdentifier + `)?)\s*(?:\(|USING\b)`) // changeSchema runs fn in a transaction that holds the schema advisory lock // and gives up waiting for a table lock after lockWait.timeout, retrying the @@ -93,12 +94,14 @@ func isLockTimeout(err error) bool { } // pendingSchema drops the CREATE INDEX IF NOT EXISTS statements whose index -// already exists. A statement it cannot parse is kept, so it runs as written. +// already exists. A statement it cannot parse is kept, so it runs as written, +// and so is an index an earlier statement of the batch names: that statement +// may drop it, and the catalog is read before any of them runs. func pendingSchema(ctx context.Context, q Querier, statements []string) ([]string, error) { pending := make([]string, 0, len(statements)) - for _, statement := range statements { + for i, statement := range statements { match := createIndexPattern.FindStringSubmatch(statement) - if match == nil { + if match == nil || namedEarlier(statements[:i], identifierName(match[1])) { pending = append(pending, statement) continue } @@ -121,6 +124,12 @@ func pendingSchema(ctx context.Context, q Querier, statements []string) ([]strin return pending, nil } +func namedEarlier(statements []string, name string) bool { + return slices.ContainsFunc(statements, func(statement string) bool { + return strings.Contains(strings.ToLower(statement), strings.ToLower(name)) + }) +} + // identifierName is the name PostgreSQL stores for an identifier as written // in SQL: a quoted one verbatim, an unquoted one folded to lower case. func identifierName(identifier string) string { diff --git a/internal/storage/sqlx/postgres_schema_internal_test.go b/internal/storage/sqlx/postgres_schema_internal_test.go index 72fc1e93d..487a4c9a7 100644 --- a/internal/storage/sqlx/postgres_schema_internal_test.go +++ b/internal/storage/sqlx/postgres_schema_internal_test.go @@ -36,6 +36,8 @@ func TestCreateIndexPattern(t *testing.T) { `CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_model ON usage(model)`, `DROP INDEX IF EXISTS idx_usage_model`, `CREATE TABLE IF NOT EXISTS usage (id TEXT)`, + // Names tenant.events, not the table tenant. + `CREATE INDEX IF NOT EXISTS uq_events ON tenant . events(id)`, } { assert.Nil(t, createIndexPattern.FindStringSubmatch(statement), statement) } diff --git a/internal/storage/sqlx/postgres_schema_test.go b/internal/storage/sqlx/postgres_schema_test.go index 81bd94c97..e98d2e436 100644 --- a/internal/storage/sqlx/postgres_schema_test.go +++ b/internal/storage/sqlx/postgres_schema_test.go @@ -187,3 +187,25 @@ func TestSchemaChangeRechecksAfterWaitingForAnotherReplica(t *testing.T) { }) } } + +// A batch that drops an index and creates it again must create it: the +// catalog is read before the drop runs, so the index still looks present. +func TestSchemaRecreatesAnIndexDroppedEarlierInTheBatch(t *testing.T) { + pool := sqlxtest.NewPostgresPool(t) + if pool == nil { + return + } + db, err := sqlx.NewPostgreSQL(pool) + require.NoError(t, err) + ctx := context.Background() + require.NoError(t, db.Schema(ctx, lockedTable, `CREATE INDEX IF NOT EXISTS idx_locked_model ON locked(model)`)) + + require.NoError(t, db.Schema(ctx, + `DROP INDEX IF EXISTS idx_locked_model`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_locked_model ON locked(model)`)) + + var unique bool + require.NoError(t, db.QueryRow(ctx, + `SELECT indisunique FROM pg_index WHERE indexrelid = to_regclass('idx_locked_model')`).Scan(&unique)) + assert.True(t, unique) +}