Repository navigation
fix(storage): skip existing indexes at PostgreSQL startup and bound the wait for table locks #1461
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
b0068eb
c4c64f9
8cb660c
6f24852
a0dd1f9
0389194
a969431
afd7092
d308c2d
745d0bb
417195f
3184c86
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| 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} | ||
| } | ||
|
|
||
| // SchemaLockKey is the advisory lock a schema change holds, for a test that | ||
| // plays the replica holding it. | ||
| const SchemaLockKey = postgresSchemaLockKey |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| package sqlx | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "log/slog" | ||
| "regexp" | ||
| "slices" | ||
| "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} | ||
|
|
||
| // 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" | ||
|
|
||
| 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 + `)?)\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 | ||
| // 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 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) | ||
| } | ||
| 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("%w in %d attempts; a long-running statement or index build holds it: %w", | ||
| ErrTableLocked, 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, | ||
| // 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 i, statement := range statements { | ||
| match := createIndexPattern.FindStringSubmatch(statement) | ||
| if match == nil || namedEarlier(statements[:i], identifierName(match[1])) { | ||
| 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 := q.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) | ||
|
SantiagoDePolonia marked this conversation as resolved.
Resolved
|
||
| } | ||
| } | ||
| 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)) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: Prompt for AI agents |
||
| }) | ||
| } | ||
|
|
||
| // 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) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| 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)`, | ||
| // 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) | ||
| } | ||
| } | ||
|
|
||
| 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"""`)) | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.