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
24 changes: 14 additions & 10 deletions internal/requestlog/model_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ func ensureModelIndexesConcurrently(ctx context.Context, db sqlx.DB) {
return
}
for _, index := range modelIndexes(sqlx.PostgreSQL) {
if err := buildIndexConcurrently(ctx, db, index); err != nil {
create := "CREATE INDEX CONCURRENTLY IF NOT EXISTS " + index.name + " ON request_logs(" + index.columns + ")"
if err := buildIndexConcurrently(ctx, db, index.name, create); err != nil {
slog.Warn("requestlog: failed to create model index", "index", index.name, "error", err)
return
}
Expand All @@ -63,25 +64,28 @@ func ensureModelIndexesConcurrently(ctx context.Context, db sqlx.DB) {
}
}

// buildIndexConcurrently creates a PostgreSQL index with CREATE INDEX
// CONCURRENTLY, which keeps the table writable while it builds. A build
// interrupted midway leaves an invalid index behind; it is dropped and rebuilt.
func buildIndexConcurrently(ctx context.Context, db sqlx.DB, index requestLogIndex) error {
// buildIndexConcurrently runs create, a CREATE INDEX CONCURRENTLY IF NOT
// EXISTS statement for the named PostgreSQL index, which keeps the table
// writable while it builds. A build interrupted midway leaves an invalid index
// behind; it is dropped and rebuilt. The drop is CONCURRENTLY too: a plain one
// waits for every open transaction that has touched request_logs, and every
// write to the table queues behind it.
func buildIndexConcurrently(ctx context.Context, db sqlx.DB, name, create string) error {
var valid *bool
err := db.QueryRow(ctx, `SELECT i.indisvalid FROM pg_index i WHERE i.indexrelid = to_regclass(?)`, index.name).Scan(&valid)
err := db.QueryRow(ctx, `SELECT i.indisvalid FROM pg_index i WHERE i.indexrelid = to_regclass(?)`, name).Scan(&valid)
switch {
case err == nil && valid != nil && *valid:
return nil
case err == nil && valid != nil:
slog.Warn("requestlog: rebuilding interrupted index", "index", index.name)
if _, err := db.Exec(ctx, "DROP INDEX "+index.name); err != nil {
slog.Warn("requestlog: rebuilding interrupted index", "index", name)
if _, err := db.Exec(ctx, "DROP INDEX CONCURRENTLY IF EXISTS "+name); err != nil {
return err
}
}
started := time.Now()
if _, err := db.Exec(ctx, "CREATE INDEX CONCURRENTLY IF NOT EXISTS "+index.name+" ON request_logs("+index.columns+")"); err != nil {
if _, err := db.Exec(ctx, create); err != nil {
return err
}
slog.Info("requestlog: built index", "index", index.name, "duration", time.Since(started).Round(time.Millisecond))
slog.Info("requestlog: built index", "index", name, "duration", time.Since(started).Round(time.Millisecond))
return nil
}
23 changes: 4 additions & 19 deletions internal/requestlog/search_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"
"log/slog"
"strings"
"time"

"github.com/enterpilot/gomodel/internal/storage/sqlx"
)
Expand Down Expand Up @@ -46,8 +45,8 @@ func searchText(errorMessage string) string {
// in the window. It is best-effort: pg_trgm ships with PostgreSQL but the role
// may not be allowed to install it, in which case the search keeps its slow
// path and the reason is logged once. The index builds CONCURRENTLY so an
// existing large table keeps accepting writes while it builds; a build
// interrupted midway leaves an invalid index, which is dropped and rebuilt.
// existing large table keeps accepting writes while it builds (see
// buildIndexConcurrently).
func ensureTrigramSearchIndex(ctx context.Context, db sqlx.DB, errorMessage string) {
if db.Dialect() != sqlx.PostgreSQL {
return
Expand All @@ -61,25 +60,11 @@ func ensureTrigramSearchIndex(ctx context.Context, db sqlx.DB, errorMessage stri
slog.Warn("requestlog: failed to locate pg_trgm", "error", err)
return
}
var valid *bool
if err := db.QueryRow(ctx, `SELECT i.indisvalid FROM pg_index i WHERE i.indexrelid = to_regclass(?)`, trigramSearchIndex).Scan(&valid); err == nil && valid != nil && !*valid {
slog.Warn("requestlog: rebuilding interrupted trigram search index")
if _, err := db.Exec(ctx, "DROP INDEX "+trigramSearchIndex); err != nil {
slog.Warn("requestlog: failed to drop invalid trigram search index", "error", err)
return
}
}
if hasTrigramSearchIndex(ctx, db) {
return
}
statement := fmt.Sprintf(`CREATE INDEX CONCURRENTLY IF NOT EXISTS %s ON request_logs USING GIN (%s %s.gin_trgm_ops)`,
trigramSearchIndex, searchText(errorMessage), `"`+strings.ReplaceAll(schema, `"`, `""`)+`"`)
started := time.Now()
if _, err := db.Exec(ctx, statement); err != nil {
slog.Warn("requestlog: failed to create trigram search index", "error", err)
return
if err := buildIndexConcurrently(ctx, db, trigramSearchIndex, statement); err != nil {
slog.Warn("requestlog: failed to build trigram search index", "error", err)
}
slog.Info("requestlog: built trigram search index", "duration", time.Since(started).Round(time.Millisecond))
}

// hasTrigramSearchIndex reports whether the trigram index exists and is
Expand Down
81 changes: 80 additions & 1 deletion internal/requestlog/store_sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,10 +430,89 @@ func TestBuildIndexConcurrentlyRebuildsInvalidIndex(t *testing.T) {
if err != nil {
t.Skipf("cannot mark the index invalid on this server: %v", err)
}
require.NoError(t, buildIndexConcurrently(ctx, db, index))
ensureModelIndexesConcurrently(ctx, db)

var valid bool
require.NoError(t, db.QueryRow(ctx, `SELECT indisvalid FROM pg_index WHERE indexrelid = to_regclass(?)`, index.name).Scan(&valid))
assert.True(t, valid)
})
}

// Replacing an interrupted build must leave request_logs writable. A plain DROP
// INDEX waits for every open transaction that has touched the table, and the
// writes of the requests being logged queue behind it until that one ends.
func TestRebuildingInterruptedIndexKeepsRequestLogsWritable(t *testing.T) {
model := modelIndexes(sqlx.PostgreSQL)[0]
rebuilds := map[string]struct {
index string
rebuild func(ctx context.Context, session sqlx.DB)
}{
"model index": {model.name, func(ctx context.Context, session sqlx.DB) {
ensureModelIndexesConcurrently(ctx, session)
}},
"search index": {trigramSearchIndex, func(ctx context.Context, session sqlx.DB) {
ensureTrigramSearchIndex(ctx, session, postgresErrorMessage)
}},
}
for name, tc := range rebuilds {
t.Run(name, func(t *testing.T) {
sqlxtest.Run(t, func(t *testing.T, db sqlx.DB) {
if db.Dialect() != sqlx.PostgreSQL {
t.Skip("concurrent index builds are PostgreSQL only")
}
ctx := context.Background()
store, err := NewSQLStore(ctx, db, 0)
require.NoError(t, err)
t.Cleanup(func() { _ = store.Close() })
store.indexBuild.Wait()
if !hasValidIndex(ctx, t, db, tc.index) {
t.Skipf("%s is not built on this server", tc.index)
}
_, err = db.Exec(ctx, `UPDATE pg_index SET indisvalid = FALSE WHERE indexrelid = to_regclass(?)`, tc.index)
if err != nil {
t.Skipf("cannot mark the index invalid on this server: %v", err)
}

// A long-running reader: an open transaction that has read the table.
pool := sqlx.PostgreSQLPool(db)
reader, err := pool.Begin(ctx)
require.NoError(t, err)
conn, err := pool.Acquire(ctx)
require.NoError(t, err)
var rebuild sync.WaitGroup
// On every exit path: the reader ends first, which lets the
// rebuild finish before its connection goes back to the pool.
defer func() {
_ = reader.Rollback(ctx)
rebuild.Wait()
conn.Release()
}()
_, err = reader.Exec(ctx, `SELECT 1 FROM request_logs LIMIT 1`)
require.NoError(t, err)

var rebuilder int
require.NoError(t, conn.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&rebuilder))
session, err := sqlx.NewPostgreSQLConn(conn)
require.NoError(t, err)
rebuild.Go(func() { tc.rebuild(ctx, session) })

// The drop waits for the reader either way; what matters is
// whether a write can pass it meanwhile.
require.Eventually(t, func() bool {
var waiting bool
err := db.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM pg_locks WHERE pid = ? AND NOT granted)`, rebuilder).Scan(&waiting)
return err == nil && waiting
}, 10*time.Second, 10*time.Millisecond, "the rebuild waits for the reader")

writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
require.NoError(t, store.WriteBatch(writeCtx, []*LogEntry{testLogEntry("during-rebuild", time.Now())}),
"a request is logged while the rebuild waits")

require.NoError(t, reader.Rollback(ctx))
rebuild.Wait()
assert.True(t, hasValidIndex(ctx, t, db, tc.index))
})
})
}
}
Loading