fix(import): converge on resume and survive server pauses (wy-sbgucn)

A 30,740-issue `bd import` into a fresh dolt sql-server never converged
(wyvern rollback drill wy-9we0jf): two defects, one symptom.

1. The shared pool's 10s per-I/O ReadTimeout killed a chunk COMMIT whenever
   the server paused — a stock server's auto_gc took 16.5s mid-import — and
   every pause surfaced as "i/o timeout" then "write commit result
   indeterminate". `bd import` now gets a 5m pool read-timeout FALLBACK
   (dolt.Config.PoolReadTimeoutFallback, applied in buildServerDSN only when
   neither the caller, BEADS_DOLT_POOL_READ_TIMEOUT nor dolt.pool-read-timeout
   set one), so an operator's explicit setting still wins.

2. A re-run rewrote every row from chunk 1: the stale pre-filter kept tie rows
   (same updated_at, same columns) in the write set so their aux data could
   merge additively (bd-hj85c). Under any bounded wall clock each attempt
   re-spent its whole budget reaching the same chunk — the drill's
   "deterministic chunk 44" was a ~300s wrapper kill (rootCtx cancels only on
   a signal, hence "context canceled"), not a stall. filterStaleImportIssues
   now proves a tie row unchanged when every incoming label, comment and
   dependency is already stored (bulk-loaded through the optional
   importRelationLookup seam; typed opt-out errImportRelationsUnavailable)
   and leaves it out of the write set, reported as Unchanged. A fresh import
   pays nothing; a resume skips the committed prefix and converges.

Tests: resume fast path (proven row skipped, any missing aux row keeps the
row, opt-in/opt-out, read failure surfaces, result accounting) and the DSN
fallback precedence.
This commit is contained in:
homer 2026-09-01 01:20:59 -07:00
commit e05000d644
6 changed files with 381 additions and 4 deletions

View file

@ -9,6 +9,7 @@ import (
"os"
"path/filepath"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
@ -116,6 +117,28 @@ func init() {
rootCmd.AddCommand(importCmd)
}
// importPoolReadTimeout is the per-I/O read deadline a `bd import` gets on
// its shared-pool connections when neither the caller, BEADS_DOLT_POOL_READ_TIMEOUT
// nor dolt.pool-read-timeout set one. The pool default (10s) is a fast-fail
// tuned for interactive commands; an import's chunk COMMIT of 250 rows with
// their aux tables legitimately outlives it whenever the server pauses — a
// stock dolt sql-server's auto_gc took 16.5s mid-import in the wy-9we0jf
// rollback drill, and every such pause surfaced as "i/o timeout" followed by
// "write commit result indeterminate" (wy-sbgucn). 5m matches the repo's
// other known-long operations (execWithLongTimeout, withReadTxLongTimeout).
const importPoolReadTimeout = 5 * time.Minute
// bulkLoadPoolReadTimeout returns the pool read-timeout fallback for cmd: the
// bulk-load deadline for `bd import`, zero (keep the pool default) otherwise.
// It is a FALLBACK, not an override — an operator's explicit setting still wins
// (see dolt.Config.PoolReadTimeoutFallback).
func bulkLoadPoolReadTimeout(cmd *cobra.Command) time.Duration {
if cmd != nil && cmd.Name() == "import" {
return importPoolReadTimeout
}
return 0
}
func runImport(cmd *cobra.Command, args []string) error {
// Explicit call, not inherited from CheckReadonly: runImport doesn't call
// CheckReadonly at all (a separate, pre-existing gap — readonlyMode
@ -397,6 +420,7 @@ func applyImportDryRunClassification(result *importResultJSON, classification *I
func applyImportOutcome(result *importResultJSON, importResult *ImportResult) {
result.Created = importResult.Created
result.Updated = importResult.Updated
result.Unchanged = importResult.Unchanged
result.Skipped += importResult.Skipped
result.SkippedDependencies = append(result.SkippedDependencies, importResult.SkippedDependencies...)
result.IDs = append(result.IDs, importResult.ImportedIDs...)
@ -447,6 +471,9 @@ func renderImportOutcome(result importResultJSON, source string, dedupHits int)
if staleSkipped := result.Skipped - dedupHits; staleSkipped > 0 {
fmt.Fprintf(os.Stderr, " (%d stale skipped; use --allow-stale to restore older rows)", staleSkipped) //nolint:gosec // G705: stderr, not a browser context
}
if result.Unchanged > 0 {
fmt.Fprintf(os.Stderr, " (%d already present, unchanged)", result.Unchanged) //nolint:gosec // G705: stderr, not a browser context
}
fmt.Fprintln(os.Stderr)
if len(result.UpdatedIssues) > 0 {
fmt.Fprintf(os.Stderr, "Updated %d existing issue(s):\n", len(result.UpdatedIssues))

View file

@ -4,9 +4,11 @@ import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"sort"
"strings"
"time"
@ -112,6 +114,27 @@ type importIssueLookup interface {
GetIssuesByIDs(ctx context.Context, ids []string) ([]*types.Issue, error)
}
// importRelationLookup is the OPTIONAL read seam behind the resume fast path
// (wy-sbgucn). A re-run of an interrupted chunked import used to rewrite every
// row from the first chunk, so under any bounded wall clock (a timeout wrapper,
// a session budget) each attempt re-spent its whole budget reaching the same
// chunk and the import never converged — the rollback drill's "deterministic
// chunk 44" (wy-9we0jf). The pre-filter now proves a tie row unchanged when its
// columns, labels, comments and dependencies are all already stored, and leaves
// it out of the write set. Proof needs the aux rows, hence these bulk loaders;
// a store without them (the proxied unit of work, test fakes) keeps the old
// behavior and rewrites every tie row.
type importRelationLookup interface {
GetCommentsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Comment, error)
GetDependencyRecordsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Dependency, error)
}
// errImportRelationsUnavailable is the typed opt-out a lookup returns from
// either bulk loader when it cannot supply aux rows: the fast path then proves
// nothing and every tie row is rewritten (safe — it is the pre-fast-path
// behavior). Any other error is a real read failure and stops the import.
var errImportRelationsUnavailable = errors.New("import relation lookup unavailable")
// importIssuesCore imports issues into the Dolt store.
// This is a bridge function that delegates to the Dolt store's batch creation.
func importIssuesCore(ctx context.Context, _ string, store storage.DoltStorage, issues []*types.Issue, opts ImportOptions) (*ImportResult, error) {
@ -136,7 +159,7 @@ func importIssuesCore(ctx context.Context, _ string, store storage.DoltStorage,
staleSkippedIDs = skipped
changePlan = plan
if len(issues) == 0 {
return &ImportResult{Skipped: len(staleSkippedIDs), StaleSkippedIDs: staleSkippedIDs}, nil
return &ImportResult{Skipped: len(staleSkippedIDs), StaleSkippedIDs: staleSkippedIDs, Unchanged: len(changePlan.Unchanged)}, nil
}
}
@ -207,6 +230,7 @@ func assembleImportResult(issues []*types.Issue, staleSkippedIDs []string, chang
return &ImportResult{
Created: len(importedIDs),
Updated: updatedCount,
Unchanged: len(changePlan.Unchanged),
Skipped: len(staleSkippedIDs),
ImportedIDs: importedIDs,
StaleSkippedIDs: staleSkippedIDs,
@ -659,6 +683,12 @@ type importChangePlan struct {
// every stored column for these (second-granularity timestamp tie),
// while their aux data still merges.
TieKeptLocal []string
// Unchanged lists incoming rows proven identical to the stored row —
// same updated_at, same columns, and every incoming label, comment and
// dependency already stored — and therefore left out of the write set
// (wy-sbgucn). This is what lets a re-run of an interrupted import skip
// the committed prefix instead of rewriting it.
Unchanged []string
// NewIDs lists incoming rows with no local match (would-create), deduped
// by ID for display and excluding title-only rows that carry no ID at
// all. NewCount is the authoritative row count for those same rows: it
@ -736,6 +766,9 @@ func filterStaleImportIssues(ctx context.Context, store importIssueLookup, issue
filtered := make([]*types.Issue, 0, len(issues))
skippedIDs := make([]string, 0)
// Positions in filtered whose row ties the local one with identical
// columns; proveUnchangedImportRows decides which of them leave the set.
tieIdentical := make(map[int]struct{})
for _, issue := range issues {
if issue == nil {
filtered = append(filtered, issue)
@ -778,10 +811,127 @@ func filterStaleImportIssues(ctx context.Context, store importIssueLookup, issue
} else {
plan.Updates = append(plan.Updates, ImportChange{ID: issue.ID, Changes: summary})
}
} else if incomingAt.Equal(localAt) {
// Same second, same columns: a candidate for the resume fast
// path, decided below once the aux rows are loaded.
tieIdentical[len(filtered)] = struct{}{}
}
filtered = append(filtered, issue)
}
return filtered, skippedIDs, plan, nil
if len(tieIdentical) == 0 {
return filtered, skippedIDs, plan, nil
}
unchanged, err := proveUnchangedImportRows(ctx, store, filtered, tieIdentical, localByID)
if err != nil {
return nil, nil, plan, err
}
if len(unchanged) == 0 {
return filtered, skippedIDs, plan, nil
}
kept := make([]*types.Issue, 0, len(filtered)-len(unchanged))
for pos, issue := range filtered {
if _, skip := unchanged[pos]; skip {
plan.Unchanged = append(plan.Unchanged, issue.ID)
continue
}
kept = append(kept, issue)
}
return kept, skippedIDs, plan, nil
}
// proveUnchangedImportRows returns the positions in filtered (drawn from the
// candidate set) whose incoming row is provably a no-op write: the tie already
// proved the columns equal, and every incoming label, comment and dependency
// is already stored. The aux writes are all additive (INSERT IGNORE labels,
// existence-checked comments, dedup'd dependency rows), so incoming ⊆ stored
// is exactly the condition under which the rewrite would change nothing.
// Anything short of proof — a store without bulk loaders, a comment with no
// timestamp, an untyped dependency, an aux row not yet stored — keeps the row
// in the write set, i.e. today's behavior. Comments are keyed the way
// PersistComments checks existence (author, created_at as stored, text).
func proveUnchangedImportRows(ctx context.Context, store importIssueLookup, filtered []*types.Issue, candidates map[int]struct{}, localByID map[string]*types.Issue) (map[int]struct{}, error) {
rel, ok := store.(importRelationLookup)
if !ok {
return nil, nil
}
ids := make([]string, 0, len(candidates))
seen := make(map[string]struct{}, len(candidates))
for pos := range candidates {
id := filtered[pos].ID
if _, dup := seen[id]; dup {
continue
}
seen[id] = struct{}{}
ids = append(ids, id)
}
sort.Strings(ids)
comments, err := rel.GetCommentsForIssues(ctx, ids)
if errors.Is(err, errImportRelationsUnavailable) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("check existing comments before import: %w", err)
}
deps, err := rel.GetDependencyRecordsForIssues(ctx, ids)
if errors.Is(err, errImportRelationsUnavailable) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("check existing dependencies before import: %w", err)
}
unchanged := make(map[int]struct{})
for pos := range candidates {
issue := filtered[pos]
local := localByID[issue.ID]
if local == nil {
continue
}
if importAuxAlreadyStored(issue, local, comments[issue.ID], deps[issue.ID]) {
unchanged[pos] = struct{}{}
}
}
return unchanged, nil
}
func importAuxAlreadyStored(incoming, local *types.Issue, storedComments []*types.Comment, storedDeps []*types.Dependency) bool {
stored := make(map[string]struct{}, len(local.Labels))
for _, l := range local.Labels {
stored[l] = struct{}{}
}
for _, l := range incoming.Labels {
if _, ok := stored[l]; !ok {
return false
}
}
commentKey := func(c *types.Comment) string {
return c.Author + "\x00" + issueops.FormatAuxTime(c.CreatedAt) + "\x00" + c.Text
}
stored = make(map[string]struct{}, len(storedComments))
for _, c := range storedComments {
stored[commentKey(c)] = struct{}{}
}
for _, c := range incoming.Comments {
if c == nil || c.CreatedAt.IsZero() {
return false // would be stamped live on write: not provably a no-op
}
if _, ok := stored[commentKey(c)]; !ok {
return false
}
}
depKey := func(d *types.Dependency) string { return d.DependsOnID + "\x00" + string(d.Type) }
stored = make(map[string]struct{}, len(storedDeps))
for _, d := range storedDeps {
stored[depKey(d)] = struct{}{}
}
for _, d := range incoming.Dependencies {
if d == nil || d.Type == "" {
return false
}
if _, ok := stored[depKey(d)]; !ok {
return false
}
}
return true
}
// classifyImportIssuesExistence classifies incoming rows as created or
@ -879,7 +1029,7 @@ func classifyDryRunImport(ctx context.Context, store importIssueLookup, issues [
return &ImportResult{
Created: created,
Updated: updated,
Unchanged: len(filtered) - created - updated,
Unchanged: len(filtered) - created - updated + len(plan.Unchanged),
Skipped: len(staleSkippedIDs),
ImportedIDs: plan.NewIDs,
StaleSkippedIDs: staleSkippedIDs,
@ -1176,7 +1326,9 @@ func importFromLocalJSONLWithOpts(ctx context.Context, store storage.DoltStorage
if err != nil {
return nil, err
}
result.Issues = importResult.Created
// Rows the resume fast path proved already present count as imported
// here: this is "rows the file put in the store", not "rows written".
result.Issues = importResult.Created + importResult.Unchanged
}
return result, nil

View file

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
@ -26,6 +27,16 @@ func (f *fakeImportIssueLookupStore) GetIssuesByIDs(_ context.Context, _ []strin
return f.issues, nil
}
// The embedded nil storage.DoltStorage would satisfy importRelationLookup and
// panic on call; opt the plain fake out explicitly so tie rows are rewritten.
func (f *fakeImportIssueLookupStore) GetCommentsForIssues(_ context.Context, _ []string) (map[string][]*types.Comment, error) {
return nil, errImportRelationsUnavailable
}
func (f *fakeImportIssueLookupStore) GetDependencyRecordsForIssues(_ context.Context, _ []string) (map[string][]*types.Dependency, error) {
return nil, errImportRelationsUnavailable
}
func (f *fakeImportIssueLookupStore) CreateIssuesWithFullOptions(_ context.Context, issues []*types.Issue, _ string, opts storage.BatchCreateOptions) error {
f.created = append(f.created, issues...)
f.createOpts = append(f.createOpts, opts)
@ -630,3 +641,148 @@ func TestRunImportInnerRejectsRedirectedStdinWithoutSource(t *testing.T) {
}
})
}
// fakeImportRelationStore adds the optional bulk aux loaders the resume fast
// path (wy-sbgucn) proves rows unchanged with.
type fakeImportRelationStore struct {
fakeImportIssueLookupStore
comments map[string][]*types.Comment
deps map[string][]*types.Dependency
loads int
}
func (f *fakeImportRelationStore) GetCommentsForIssues(_ context.Context, _ []string) (map[string][]*types.Comment, error) {
f.loads++
return f.comments, nil
}
func (f *fakeImportRelationStore) GetDependencyRecordsForIssues(_ context.Context, _ []string) (map[string][]*types.Dependency, error) {
f.loads++
return f.deps, nil
}
// wy-sbgucn: a re-run of an interrupted chunked import must not rewrite the
// committed prefix. A tie row (same updated_at, same columns) whose labels,
// comments and dependencies are all already stored is provably a no-op write
// and leaves the write set; any aux row not yet stored keeps the row in.
func TestFilterStaleImportIssuesSkipsProvenUnchangedRowsOnResume(t *testing.T) {
base := time.Date(2026, 8, 31, 14, 0, 0, 0, time.UTC)
commentAt := base.Add(-time.Hour)
mk := func(id string) *types.Issue {
return &types.Issue{
ID: id, Title: "row " + id, UpdatedAt: base,
Labels: []string{"lane:beads", "tier:fable"},
Comments: []*types.Comment{{ID: "c-" + id, Author: "cat", Text: "drill", CreatedAt: commentAt}},
Dependencies: []*types.Dependency{{IssueID: id, DependsOnID: "bd-root", Type: types.DepBlocks}},
}
}
incoming := []*types.Issue{mk("bd-same"), mk("bd-nocomment"), mk("bd-nodep"), mk("bd-nolabel"), mk("bd-new")}
local := func(id string, labels ...string) *types.Issue {
return &types.Issue{ID: id, Title: "row " + id, UpdatedAt: base, Labels: labels}
}
storedComment := []*types.Comment{{ID: "other-id", IssueID: "x", Author: "cat", Text: "drill", CreatedAt: commentAt.Add(500 * time.Millisecond)}}
storedDep := []*types.Dependency{{DependsOnID: "bd-root", Type: types.DepBlocks}}
store := &fakeImportRelationStore{
fakeImportIssueLookupStore: fakeImportIssueLookupStore{issues: []*types.Issue{
local("bd-same", "tier:fable", "lane:beads"),
local("bd-nocomment", "lane:beads", "tier:fable"),
local("bd-nodep", "lane:beads", "tier:fable"),
local("bd-nolabel", "lane:beads"),
}},
comments: map[string][]*types.Comment{"bd-same": storedComment, "bd-nodep": storedComment, "bd-nolabel": storedComment},
deps: map[string][]*types.Dependency{"bd-same": storedDep, "bd-nocomment": storedDep, "bd-nolabel": storedDep},
}
filtered, skippedIDs, plan, err := filterStaleImportIssues(context.Background(), store, incoming)
if err != nil {
t.Fatalf("filterStaleImportIssues: %v", err)
}
if len(skippedIDs) != 0 {
t.Fatalf("skippedIDs = %#v, want none (nothing is stale)", skippedIDs)
}
var kept []string
for _, issue := range filtered {
kept = append(kept, issue.ID)
}
want := []string{"bd-nocomment", "bd-nodep", "bd-nolabel", "bd-new"}
if strings.Join(kept, ",") != strings.Join(want, ",") {
t.Fatalf("write set = %v, want %v (only the provably stored row leaves it, order preserved)", kept, want)
}
if len(plan.Unchanged) != 1 || plan.Unchanged[0] != "bd-same" {
t.Fatalf("plan.Unchanged = %#v, want [bd-same]", plan.Unchanged)
}
if len(plan.TieKeptLocal) != 0 || len(plan.Updates) != 0 {
t.Fatalf("plan = %+v, want no tie conflicts or updates", plan)
}
if store.loads != 2 {
t.Fatalf("aux loads = %d, want exactly one comment load + one dependency load", store.loads)
}
}
// A fresh import (no local match) must not pay for the aux loads at all, and
// a store without the bulk loaders keeps the pre-wy-sbgucn behavior: every
// tie row stays in the write set.
func TestFilterStaleImportIssuesResumeFastPathIsOptIn(t *testing.T) {
base := time.Date(2026, 8, 31, 14, 0, 0, 0, time.UTC)
incoming := []*types.Issue{{ID: "bd-tie", Title: "t", UpdatedAt: base}, {ID: "bd-new", Title: "n", UpdatedAt: base}}
fresh := &fakeImportRelationStore{}
filtered, _, plan, err := filterStaleImportIssues(context.Background(), fresh, incoming)
if err != nil {
t.Fatalf("fresh: %v", err)
}
if len(filtered) != 2 || fresh.loads != 0 || len(plan.Unchanged) != 0 {
t.Fatalf("fresh import: kept %d rows, %d aux loads, unchanged %v; want 2 rows, 0 loads, none", len(filtered), fresh.loads, plan.Unchanged)
}
plain := &fakeImportIssueLookupStore{issues: []*types.Issue{{ID: "bd-tie", Title: "t", UpdatedAt: base}}}
filtered, _, plan, err = filterStaleImportIssues(context.Background(), plain, incoming)
if err != nil {
t.Fatalf("plain: %v", err)
}
if len(filtered) != 2 || len(plan.Unchanged) != 0 {
t.Fatalf("store without bulk loaders: kept %d rows, unchanged %v; want both rows rewritten", len(filtered), plan.Unchanged)
}
// A real read failure is not an opt-out: it stops the import.
broken := &failingImportRelationStore{fakeImportIssueLookupStore: plain}
if _, _, _, err := filterStaleImportIssues(context.Background(), broken, incoming); err == nil || !strings.Contains(err.Error(), "check existing comments before import") {
t.Fatalf("read failure: err = %v, want the comment-load failure surfaced", err)
}
}
type failingImportRelationStore struct{ *fakeImportIssueLookupStore }
func (f *failingImportRelationStore) GetCommentsForIssues(_ context.Context, _ []string) (map[string][]*types.Comment, error) {
return nil, errors.New("connection lost")
}
// The real import's result carries the skipped-as-unchanged count so the
// resume reports what it did not have to rewrite.
func TestImportIssuesCoreReportsUnchangedRowsOnResume(t *testing.T) {
base := time.Date(2026, 8, 31, 14, 0, 0, 0, time.UTC)
incoming := []*types.Issue{{ID: "bd-same", Title: "t", UpdatedAt: base}, {ID: "bd-new", Title: "n", UpdatedAt: base}}
store := &fakeImportRelationStore{fakeImportIssueLookupStore: fakeImportIssueLookupStore{issues: []*types.Issue{{ID: "bd-same", Title: "t", UpdatedAt: base}}}}
result, err := importIssuesCore(context.Background(), "", store, incoming, ImportOptions{SkipPrefixValidation: true})
if err != nil {
t.Fatalf("importIssuesCore: %v", err)
}
if result.Created != 1 || result.Unchanged != 1 || len(result.ImportedIDs) != 1 || result.ImportedIDs[0] != "bd-new" {
t.Fatalf("result = %+v, want Created 1 (bd-new), Unchanged 1", result)
}
if len(store.created) != 1 || store.created[0].ID != "bd-new" {
t.Fatalf("written rows = %v, want only bd-new", store.created)
}
}
func TestBulkLoadPoolReadTimeoutOnlyForImport(t *testing.T) {
if got := bulkLoadPoolReadTimeout(importCmd); got != importPoolReadTimeout {
t.Fatalf("import fallback = %v, want %v", got, importPoolReadTimeout)
}
if got := bulkLoadPoolReadTimeout(exportCmd); got != 0 {
t.Fatalf("export fallback = %v, want 0 (pool default)", got)
}
if got := bulkLoadPoolReadTimeout(nil); got != 0 {
t.Fatalf("nil cmd fallback = %v, want 0", got)
}
}

View file

@ -1476,6 +1476,9 @@ var rootCmd = &cobra.Command{
DisableAutoStart: policy.disableAutoStart,
BeadsDir: beadsDir,
LenientOpen: isWorkingSetReconcileCommand(cmd),
// Bulk loads outlive the pool's 10s fast-fail on every server
// pause (wy-sbgucn); explicit env/config settings still win.
PoolReadTimeoutFallback: bulkLoadPoolReadTimeout(cmd),
}
// Load config to get database name and server connection settings.

View file

@ -486,6 +486,15 @@ type Config struct {
// execWithLongTimeout/openLongTimeoutConn instead.
PoolReadTimeout time.Duration
PoolWriteTimeout time.Duration
// PoolReadTimeoutFallback replaces the built-in 10s pool read deadline
// ONLY when nothing else set PoolReadTimeout — not the caller, not
// BEADS_DOLT_POOL_READ_TIMEOUT, not dolt.pool-read-timeout. It lets a
// command whose ordinary statements are known to run long (bd import's
// chunk commits, which a server-side auto_gc pause stretches past 10s —
// wy-sbgucn) raise its own default without overriding an operator's
// explicit choice. 0 = keep the built-in default.
PoolReadTimeoutFallback time.Duration
}
// Defaults for the *sql.DB connection pool. Exported for tests/callers that
@ -2207,6 +2216,9 @@ func buildServerDSN(cfg *Config, database string) string {
return base.String()
}
parsed.ReadTimeout = defaultPoolReadTimeout
if cfg.PoolReadTimeoutFallback > 0 {
parsed.ReadTimeout = cfg.PoolReadTimeoutFallback
}
if cfg.PoolReadTimeout > 0 {
parsed.ReadTimeout = cfg.PoolReadTimeout
}

View file

@ -799,3 +799,30 @@ func TestShouldStopAutoStartedServerOnClose(t *testing.T) {
}
})
}
// wy-sbgucn: PoolReadTimeoutFallback replaces the built-in 10s pool read
// deadline only when nothing set PoolReadTimeout; an explicit setting wins.
func TestBuildServerDSN_PoolReadTimeoutFallback(t *testing.T) {
base := &Config{ServerHost: "127.0.0.1", ServerPort: 13390, ServerUser: "root", Database: "wy"}
parse := func(cfg *Config) time.Duration {
t.Helper()
parsed, err := mysql.ParseDSN(buildServerDSN(cfg, cfg.Database))
if err != nil {
t.Fatalf("ParseDSN: %v", err)
}
return parsed.ReadTimeout
}
if got := parse(base); got != defaultPoolReadTimeout {
t.Fatalf("no settings: ReadTimeout = %v, want built-in %v", got, defaultPoolReadTimeout)
}
fb := *base
fb.PoolReadTimeoutFallback = 5 * time.Minute
if got := parse(&fb); got != 5*time.Minute {
t.Fatalf("fallback only: ReadTimeout = %v, want 5m", got)
}
explicit := fb
explicit.PoolReadTimeout = 20 * time.Second
if got := parse(&explicit); got != 20*time.Second {
t.Fatalf("explicit + fallback: ReadTimeout = %v, want the explicit 20s", got)
}
}