Skip to content
Merged
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: 11 additions & 0 deletions docs/guides/updating.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,16 @@ 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 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. 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.

After v0.2.5 the request log's storage was renamed from `audit_logs` to
`request_logs`: the tables on SQLite and PostgreSQL, the collection on
MongoDB. The rename happens in place and copies no rows; on SQLite and
Expand Down Expand Up @@ -235,6 +245,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. 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
Expand Down
12 changes: 11 additions & 1 deletion internal/requestlog/store_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package requestlog

import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
Expand Down Expand Up @@ -241,8 +242,17 @@ func ensureSQLSchema(ctx context.Context, db sqlx.DB) error {
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 request_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.Exec(ctx, statement); err != nil {
err := db.Schema(ctx, statement)
if errors.Is(err, sqlx.ErrTableLocked) {
slog.Warn("request 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)
}
}
Expand Down
13 changes: 13 additions & 0 deletions internal/storage/sqlx/export_test.go
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
31 changes: 23 additions & 8 deletions internal/storage/sqlx/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import (
// Queries arrive with `?` placeholders and are rebound to $1, $2, ... on the
// way through.
type postgresDB struct {
session pgSession
session pgSession
lockWait lockWait
}

// pgSession is the part of *pgxpool.Pool and *pgxpool.Conn postgresDB uses.
Expand All @@ -28,7 +29,7 @@ func NewPostgreSQL(pool *pgxpool.Pool) (DB, error) {
if pool == nil {
return nil, fmt.Errorf("connection pool is required")
}
return &postgresDB{session: pool}, nil
return &postgresDB{session: pool, lockWait: defaultLockWait}, nil
}

// NewPostgreSQLConn wraps one pooled connection, for store code that must
Expand All @@ -39,7 +40,7 @@ func NewPostgreSQLConn(conn *pgxpool.Conn) (DB, error) {
if conn == nil {
return nil, fmt.Errorf("connection is required")
}
return &postgresDB{session: conn}, nil
return &postgresDB{session: conn, lockWait: defaultLockWait}, nil
}

func (p *postgresDB) Dialect() Dialect { return PostgreSQL }
Expand Down Expand Up @@ -68,7 +69,8 @@ func (p *postgresDB) QueryRow(ctx context.Context, query string, args ...any) Ro
return pgQueryRow(ctx, p.session, 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.
Expand All @@ -82,12 +84,25 @@ 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)
// 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
}
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, statements)
return execSchema(ctx, q, PostgreSQL, pending)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
})
}

Expand Down
140 changes: 140 additions & 0 deletions internal/storage/sqlx/postgres_schema.go
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)
Comment thread
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: namedEarlier matches arbitrary case-insensitive substrings, so a different earlier identifier such as idx_foo_old can keep an already-existing idx_foo CREATE in the pending batch. Parse earlier statements or match identifier boundaries and SQL identifier semantics; otherwise an up-to-date replica can still wait for the table lock and fail startup.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At internal/storage/sqlx/postgres_schema.go, line 129:

<comment>`namedEarlier` matches arbitrary case-insensitive substrings, so a different earlier identifier such as `idx_foo_old` can keep an already-existing `idx_foo` CREATE in the pending batch. Parse earlier statements or match identifier boundaries and SQL identifier semantics; otherwise an up-to-date replica can still wait for the table lock and fail startup.</comment>

<file context>
@@ -121,6 +124,12 @@ func pendingSchema(ctx context.Context, q Querier, statements []string) ([]strin
 
+func namedEarlier(statements []string, name string) bool {
+	return slices.ContainsFunc(statements, func(statement string) bool {
+		return strings.Contains(strings.ToLower(statement), strings.ToLower(name))
+	})
+}
</file context>

})
}

// 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)
}
50 changes: 50 additions & 0 deletions internal/storage/sqlx/postgres_schema_internal_test.go
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"""`))
}
Loading