Skip to content

Commit 226e89c

Browse files
authored
Merge pull request #145490 from michae2/backport24.3-144316
release-24.3: sql: move job check back out of txn creating autostats job
2 parents c9f68f1 + 8aa523d commit 226e89c

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

pkg/sql/create_stats.go

+23-5
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,13 @@ var nonIndexJSONHistograms = settings.RegisterBoolSetting(
7575
true,
7676
settings.WithPublic)
7777

78+
var automaticJobCheckBeforeCreatingJob = settings.RegisterBoolSetting(
79+
settings.ApplicationLevel,
80+
"sql.stats.automatic_job_check_before_creating_job.enabled",
81+
"set to true to perform the autostats job check before creating the job, instead of in the same "+
82+
"transaction as creating the job",
83+
true)
84+
7885
const nonIndexColHistogramBuckets = 2
7986

8087
// StubTableStats generates "stub" statistics for a table which are missing
@@ -146,18 +153,29 @@ func (n *createStatsNode) runJob(ctx context.Context) error {
146153
}
147154
details := record.Details.(jobspb.CreateStatsDetails)
148155

149-
if n.Name != jobspb.AutoStatsName && n.Name != jobspb.AutoPartialStatsName {
156+
jobCheckBefore := automaticJobCheckBeforeCreatingJob.Get(n.p.ExecCfg().SV())
157+
if n.Name == jobspb.AutoStatsName || n.Name == jobspb.AutoPartialStatsName {
158+
if jobCheckBefore {
159+
// Don't start the job if there is already a CREATE STATISTICS job running.
160+
// (To handle race conditions we check this again after the job starts,
161+
// but this check is used to prevent creating a large number of jobs that
162+
// immediately fail).
163+
if err := checkRunningJobs(
164+
ctx, nil /* job */, n.p, n.Name == jobspb.AutoPartialStatsName, n.p.ExecCfg().JobRegistry,
165+
details.Table.ID,
166+
); err != nil {
167+
return err
168+
}
169+
}
170+
} else {
150171
telemetry.Inc(sqltelemetry.CreateStatisticsUseCounter)
151172
}
152173

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

0 commit comments

Comments
 (0)