test: copy test databases by file and start test deadlines after setup (#32426)

## Summary

Mitigate Windows nightly timeout bursts caused by slow test database creation. Multiple tests were hitting `context deadline exceeded` because their 10-second deadlines started before database setup completed.

Refs https://linear.app/codercom/issue/CORE-615

## Changes

- Use `STRATEGY FILE_COPY` for test database creation on PostgreSQL 15+, avoiding the more expensive default `WAL_LOG` strategy. PostgreSQL 13/14 remain unchanged.
- Cache the PostgreSQL version lookup, preserving existing behavior if detection fails.
- Log database copies exceeding 2 seconds, including duration and strategy.
- Move context creation after database/server setup in affected WebPush, OIDC, notification, and prebuild tests, without changing timeout values.
- Add unit tests for PostgreSQL version-based strategy selection.

Test-only changes across 6 files; no production code changes.

## Validation

- Local PostgreSQL 17.10 tests pass, including WebPush, prebuild reconciliation, OIDC, and notifications.
- `go vet` and `golangci-lint` report no issues.
- Local OIDC comparison:
  - Default strategy: 3–5 failures/run.
  - `FILE_COPY` with partial context fixes: 1–2 failures/run.
  - **Final implementation: 0 failures across 5 runs**, with maximum database creation time reduced from 13.3s to 8.9s.

## Remaining Work

- Run `nightly-gauntlet` repeatedly to verify improvements on Windows and macOS.
- Compare WAL volume, checkpoint overhead, and test durations. `FILE_COPY` increases checkpoints, though local database creation was faster.
- Confirm PostgreSQL 13 and 17 Linux jobs pass.

**Status:** Draft pending nightly validation.
This commit is contained in:
Bobby Ho authored and GitHub committed 2026-11-23 10:58:04 -07:00
1 parent 54fc9e3e14
commit c5af20be31
6 files changed
+129 -43

No files matched your search

+69 -2
View File
@@ -184,7 +184,7 @@ func createDatabaseFromTemplate(t TBSubset, connParams ConnectionParams, db *sql
if emptyTemplateDBName {
templateDBName = fmt.Sprintf("tpl_%s", migrations.GetMigrationsHash()[:32])
}
_, err := db.Exec("CREATE DATABASE " + newDBName + " WITH TEMPLATE " + templateDBName)
err := copyDatabaseFromTemplate(t, db, newDBName, templateDBName)
if err == nil {
// Template database already exists and we successfully created the new database.
return nil
@@ -212,12 +212,79 @@ func createDatabaseFromTemplate(t TBSubset, connParams ConnectionParams, db *sql
}
// Try to create the database again now that a template exists.
if _, err = db.Exec("CREATE DATABASE " + newDBName + " WITH TEMPLATE " + templateDBName); err != nil {
if err = copyDatabaseFromTemplate(t, db, newDBName, templateDBName); err != nil {
return xerrors.Errorf("create db with template after migrations: %w", err)
}
return nil
}
// slowCopyThreshold is how long copying the template into a test database
// can take before it is logged. The time counts against any deadline the test
// started before asking for a database, and nothing else in the test output
// shows it.
const slowCopyThreshold = 2 * time.Second
// copyDatabaseFromTemplate creates newDBName as a copy of templateDBName. It
// times only the copy, so that building a missing template is not reported as
// a slow copy.
func copyDatabaseFromTemplate(t TBSubset, db *sql.DB, newDBName string, templateDBName string) error {
t.Helper()
clause := copyStrategyClause(t, db)
start := time.Now()
if _, err := db.Exec("CREATE DATABASE " + newDBName + " WITH TEMPLATE " + templateDBName + clause); err != nil {
return err
}
if elapsed := time.Since(start); elapsed > slowCopyThreshold {
strategy := "server default"
if clause != "" {
strategy = strings.TrimSpace(clause)
}
t.Logf("%s copying template into test database %q took %s (%s)",
time.Now().Format(time.StampMilli), newDBName, elapsed.Round(time.Millisecond), strategy)
}
return nil
}
var (
copyStrategyClauseOnce sync.Once
copyStrategyClauseValue string
)
// copyStrategyClause returns the STRATEGY clause to append to CREATE
// DATABASE ... WITH TEMPLATE. The server version is read through db on the
// first call and the result is kept for the rest of the process. If that
// read fails, the clause stays empty and the server default strategy is used.
func copyStrategyClause(t TBSubset, db *sql.DB) string {
t.Helper()
copyStrategyClauseOnce.Do(func() {
var versionNum int
if err := db.QueryRow("SELECT current_setting('server_version_num')::int").Scan(&versionNum); err != nil {
t.Logf("%s failed to read the server version, test databases will use the server default copy strategy: %s",
time.Now().Format(time.StampMilli), err.Error())
return
}
copyStrategyClauseValue = copyStrategyClauseForVersion(versionNum)
})
return copyStrategyClauseValue
}
// copyStrategyClauseForVersion returns the STRATEGY clause for a
// server_version_num, or an empty string if that version has no STRATEGY
// option.
func copyStrategyClauseForVersion(versionNum int) string {
// PostgreSQL 15 added the STRATEGY option and made WAL_LOG the default.
// WAL_LOG writes the whole template to the write-ahead log, so many tests
// creating databases at once wait on each other. FILE_COPY is what older
// versions always did. It forces a checkpoint before and after each copy,
// which is the cost to weigh if this is revisited.
if versionNum >= 150000 {
return " STRATEGY FILE_COPY"
}
return ""
}
func createAndInitDatabase(t TBSubset, connParams ConnectionParams, db *sql.DB, name string, initialize func(*sql.DB) error) error {
// We will use a tx to obtain a lock, so another test or process doesn't race with us.
tx, err := db.BeginTx(context.Background(), nil)
@@ -0,0 +1,28 @@
package dbtestutil
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyStrategyClauseForVersion(t *testing.T) {
t.Parallel()
tests := []struct {
name string
versionNum int
want string
}{
{name: "PostgreSQL13HasNoStrategyOption", versionNum: 130022, want: ""},
{name: "PostgreSQL14HasNoStrategyOption", versionNum: 140019, want: ""},
{name: "PostgreSQL15UsesFileCopy", versionNum: 150000, want: " STRATEGY FILE_COPY"},
{name: "PostgreSQL17UsesFileCopy", versionNum: 170006, want: " STRATEGY FILE_COPY"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
require.Equal(t, tc.want, copyStrategyClauseForVersion(tc.versionNum))
})
}
}