Skip to content

sql: move job check back out of txn creating autostats job #144316

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

Merged
merged 1 commit into from
Apr 21, 2025
Merged
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
26 changes: 21 additions & 5 deletions pkg/sql/create_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,13 @@ var nonIndexJSONHistograms = settings.RegisterBoolSetting(
false,
settings.WithPublic)

var automaticJobCheckBeforeCreatingJob = settings.RegisterBoolSetting(
settings.ApplicationLevel,
"sql.stats.automatic_job_check_before_creating_job.enabled",
"set to true to perform the autostats job check before creating the job, instead of in the same "+
"transaction as creating the job",
true)

const nonIndexColHistogramBuckets = 2

// StubTableStats generates "stub" statistics for a table which are missing
Expand Down Expand Up @@ -148,18 +155,27 @@ func (n *createStatsNode) runJob(ctx context.Context) error {
}
details := record.Details.(jobspb.CreateStatsDetails)

if n.Name != jobspb.AutoStatsName && n.Name != jobspb.AutoPartialStatsName {
jobCheckBefore := automaticJobCheckBeforeCreatingJob.Get(n.p.ExecCfg().SV())
if (n.Name == jobspb.AutoStatsName || n.Name == jobspb.AutoPartialStatsName) && jobCheckBefore {
// Don't start the job if there is already a CREATE STATISTICS job running.
// (To handle race conditions we check this again after the job starts,
// but this check is used to prevent creating a large number of jobs that
// immediately fail).
if err := checkRunningJobs(
ctx, nil /* job */, n.p, n.Name == jobspb.AutoPartialStatsName, n.p.ExecCfg().JobRegistry,
details.Table.ID,
); err != nil {
return err
}
} else {
telemetry.Inc(sqltelemetry.CreateStatisticsUseCounter)
}

var job *jobs.StartableJob
jobID := n.p.ExecCfg().JobRegistry.MakeJobID()
if err := n.p.ExecCfg().InternalDB.Txn(ctx, func(ctx context.Context, txn isql.Txn) (err error) {
if n.Name == jobspb.AutoStatsName || n.Name == jobspb.AutoPartialStatsName {
if (n.Name == jobspb.AutoStatsName || n.Name == jobspb.AutoPartialStatsName) && !jobCheckBefore {
// Don't start the job if there is already a CREATE STATISTICS job running.
// (To handle race conditions we check this again after the job starts,
// but this check is used to prevent creating a large number of jobs that
// immediately fail).
if err := checkRunningJobsInTxn(
ctx, n.p.EvalContext().Settings, jobspb.InvalidJobID, txn,
); err != nil {
Expand Down
Loading