Skip to content

executor: keep analyze status remaining time in UTC#67229

Merged
ti-chi-bot[bot] merged 5 commits into
pingcap:masterfrom
0xPoe:fix/show-analyze-status-remaining-timezone
Apr 2, 2026
Merged

executor: keep analyze status remaining time in UTC#67229
ti-chi-bot[bot] merged 5 commits into
pingcap:masterfrom
0xPoe:fix/show-analyze-status-remaining-timezone

Conversation

@0xPoe
Copy link
Copy Markdown
Member

@0xPoe 0xPoe commented Mar 23, 2026

What problem does this PR solve?

Issue Number: close #67230

Problem Summary:

SHOW ANALYZE STATUS can report a negative Remaining_seconds when the session time_zone is ahead of UTC.

What changed and how does it work?

Keep the UTC start_time for remaining-time calculation and continue using the session-local time only for display. This PR also adds a regression test that reproduces the negative duration under +08:00.

Check List

Tests

  • Unit test
  • Integration test
  • Manual test (add detailed scripts or steps below)
  • No need to test
    • I checked and no code files have been changed.

Validation commands:

  • make failpoint-enable
  • go test -run '^TestShowAnalyzeStatus$' -tags=intest,deadlock ./pkg/executor
  • make failpoint-disable
  • make lint

Side effects

  • Performance regression: Consumes more CPU
  • Performance regression: Consumes more Memory
  • Breaking backward compatibility

Documentation

  • Affects user behaviors
  • Contains syntax changes
  • Contains variable changes
  • Contains experimental features
  • Changes MySQL compatibility

Release note

Please refer to Release Notes Language Style Guide to write a quality release note.

Fix negative Remaining_seconds in SHOW ANALYZE STATUS when the session time_zone is ahead of UTC.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed duration/remaining-time calculation for running analyze jobs by using a UTC-based start time and stricter validation to avoid negative or invalid remaining-time displays.
  • Tests

    • Added a test verifying analyze-job durations display correctly when the session time zone is non-default.

@ti-chi-bot ti-chi-bot Bot added the release-note Denotes a PR that will be considered when it comes time to generate release notes. label Mar 23, 2026
@pantheon-ai
Copy link
Copy Markdown

pantheon-ai Bot commented Mar 23, 2026

Review failed due to infrastructure/execution failure after retries. Please re-trigger review.

ℹ️ Learn more details on Pantheon AI.

@ti-chi-bot ti-chi-bot Bot added the size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. label Mar 23, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 23, 2026

📝 Walkthrough

Walkthrough

Keep a UTC copy of start_time for duration math while retaining the session-timezone start_time for display; compute remaining duration using UTC instants (time.Since on the UTC start) and require startTimeUTC non-nil for running analyze jobs to avoid negative remaining times in non-UTC sessions.

Changes

Cohort / File(s) Summary
Infoschema duration fix
pkg/executor/infoschema_reader.go
Introduce startTimeUTC *time.Time parsed from mysql.analyze_jobs.start_time; keep startTime (session TZ) for display; remove runtime types.Time assertion for running jobs; change getRemainDurationForAnalyzeStatusHelper to accept startTimeUTC and compute remaining duration with time.Since(*startTimeUTC); return error if startTimeUTC == nil.
Test for non-UTC sessions
pkg/executor/show_stats_test.go
Extend TestShowAnalyzeStatus with a scenario that sets @@time_zone = '+08:00', inserts a synthetic running job (start_time = CURRENT_TIMESTAMP - INTERVAL 1 MINUTE) into mysql.analyze_jobs, runs SHOW ANALYZE STATUS for that table, and asserts the reported remaining-duration is non-negative.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nibble clocks in morning light,
Kept UTC safe and display polite.
No more negatives hop or flee,
Durations now behave for me.
Hooray — time hops true! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: keeping analyze status remaining time in UTC for correct duration calculations.
Description check ✅ Passed The PR description includes all required sections: linked issue, clear problem statement, changes explained, completed tests, and release notes.
Linked Issues check ✅ Passed The PR directly addresses issue #67230 by fixing the negative Remaining_seconds bug by keeping UTC start_time for duration calculations while preserving session-local time for display.
Out of Scope Changes check ✅ Passed All changes are in-scope: modifications to infoschema_reader.go fix the core bug, and test additions in show_stats_test.go directly test the fix for the identified issue.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.11.4)

Command failed


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@0xPoe 0xPoe force-pushed the fix/show-analyze-status-remaining-timezone branch from 113c0ef to c35c7a2 Compare March 23, 2026 09:36
@ti-chi-bot ti-chi-bot Bot added size/M Denotes a PR that changes 30-99 lines, ignoring generated files. and removed size/XXL Denotes a PR that changes 1000+ lines, ignoring generated files. labels Mar 23, 2026
@0xPoe 0xPoe changed the title executor: keep analyze status remaining time in UTC WIP: executor: keep analyze status remaining time in UTC Mar 23, 2026
@ti-chi-bot ti-chi-bot Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Mar 23, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 23, 2026

Codecov Report

❌ Patch coverage is 88.88889% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 77.7781%. Comparing base (362aeba) to head (6d1ca89).
⚠️ Report is 85 commits behind head on master.

Additional details and impacted files
@@               Coverage Diff                @@
##             master     #67229        +/-   ##
================================================
+ Coverage   77.7710%   77.7781%   +0.0070%     
================================================
  Files          2022       1943        -79     
  Lines        554420     555803      +1383     
================================================
+ Hits         431178     432293      +1115     
- Misses       121500     123457      +1957     
+ Partials       1742         53      -1689     
Flag Coverage Δ
integration 40.9489% <0.0000%> (-7.1776%) ⬇️
unit 76.7400% <88.8888%> (+0.4344%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
dumpling 61.5065% <ø> (ø)
parser ∅ <ø> (∅)
br 48.5999% <ø> (-12.2675%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@0xPoe 0xPoe changed the title WIP: executor: keep analyze status remaining time in UTC executor: keep analyze status remaining time in UTC Apr 1, 2026
@ti-chi-bot ti-chi-bot Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Apr 1, 2026
Copy link
Copy Markdown
Member Author

@0xPoe 0xPoe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔢 Self-check (PR reviewed by myself and ready for feedback)

  • Code compiles successfully

  • Unit tests added

  • No AI-generated elegant nonsense in PR.

  • Bazel files updated

  • Comments added where necessary

  • PR title and description updated

  • Documentation PR created (or confirmed not needed)

  • PR size is reasonable

/cc @mjonss @winoros

return nil, err
}
startTimeUTC = &t
startTime = types.NewTime(types.FromGoTime(t.In(sctx.GetSessionVars().TimeZone)), mysql.TypeDatetime, 0)
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is where the original bug comes form. We use the session time, but we applied it as UTC in later usage.

) (_ *time.Duration, percentage, totalCnt float64, err error) {
remainingDuration := time.Duration(0)
if startTime != nil {
start, err := startTime.GoTime(time.UTC)
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Buggy code!

@ti-chi-bot ti-chi-bot Bot requested review from mjonss and winoros April 1, 2026 10:01
@0xPoe
Copy link
Copy Markdown
Member Author

0xPoe commented Apr 1, 2026

/retest

Comment thread pkg/executor/infoschema_reader.go
Signed-off-by: 0xPoe <techregister@pm.me>

fix

Signed-off-by: 0xPoe <techregister@pm.me>
@0xPoe 0xPoe force-pushed the fix/show-analyze-status-remaining-timezone branch from 8c94fd9 to cc47e0c Compare April 1, 2026 10:12
@0xPoe 0xPoe requested a review from winoros April 1, 2026 10:12
@ti-chi-bot ti-chi-bot Bot added approved needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Apr 1, 2026
Comment thread pkg/executor/infoschema_reader.go Outdated
Signed-off-by: 0xPoe <techregister@pm.me>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
pkg/executor/infoschema_reader.go (1)

2582-2586: Consider returning a warning instead of failing the entire query.

For a running job, returning an error if startTimeUTC is nil will cause the entire SHOW ANALYZE STATUS to fail. If there's any corrupted row in mysql.analyze_jobs with a null start_time for a running job, users won't be able to see any analyze status.

Consider logging a warning and either skipping the row or showing it with a nil remaining duration instead:

♻️ Suggested alternative approach
 if state == statistics.AnalyzeRunning && !strings.HasPrefix(jobInfo, "merge global stats") {
-    if startTimeUTC == nil {
-        return nil, errors.New("invalid start time")
-    }
-    remainingDuration, progress, estimatedRowCnt, remainDurationErr := getRemainDurationForAnalyzeStatusHelper(ctx, sctx, startTimeUTC,
-        dbName, tableName, partitionName, processedRows)
+    if startTimeUTC != nil {
+        remainingDuration, progress, estimatedRowCnt, remainDurationErr := getRemainDurationForAnalyzeStatusHelper(ctx, sctx, startTimeUTC,
+            dbName, tableName, partitionName, processedRows)
+    } else {
+        logutil.BgLogger().Warn("running analyze job has invalid start time",
+            zap.String("db", dbName),
+            zap.String("table", tableName))
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/executor/infoschema_reader.go` around lines 2582 - 2586, The code
currently returns an error when startTimeUTC is nil for a running analyze job
(inside the branch where state == statistics.AnalyzeRunning and
!strings.HasPrefix(jobInfo, "merge global stats")), which fails SHOW ANALYZE
STATUS; instead, replace the return nil, errors.New("invalid start time") with a
warning log and either skip that row (continue the loop) or populate the
remaining-duration-related outputs with nil/zero values and proceed without
calling getRemainDurationForAnalyzeStatusHelper; specifically, check
startTimeUTC, call the logger (e.g., log.Warn / logutil.BgLogger().Warn)
referencing jobInfo and any job id/context, and then either continue or set
remainingDuration=nil, progress=0, estimatedRowCnt=nil and remainDurationErr=nil
before the code continues to build the result row.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@pkg/executor/infoschema_reader.go`:
- Around line 2582-2586: The code currently returns an error when startTimeUTC
is nil for a running analyze job (inside the branch where state ==
statistics.AnalyzeRunning and !strings.HasPrefix(jobInfo, "merge global
stats")), which fails SHOW ANALYZE STATUS; instead, replace the return nil,
errors.New("invalid start time") with a warning log and either skip that row
(continue the loop) or populate the remaining-duration-related outputs with
nil/zero values and proceed without calling
getRemainDurationForAnalyzeStatusHelper; specifically, check startTimeUTC, call
the logger (e.g., log.Warn / logutil.BgLogger().Warn) referencing jobInfo and
any job id/context, and then either continue or set remainingDuration=nil,
progress=0, estimatedRowCnt=nil and remainDurationErr=nil before the code
continues to build the result row.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8afa0903-63fc-48e3-a5fe-b2bbf33e575b

📥 Commits

Reviewing files that changed from the base of the PR and between cc47e0c and 3239183.

📒 Files selected for processing (1)
  • pkg/executor/infoschema_reader.go

Signed-off-by: 0xPoe <techregister@pm.me>
Copy link
Copy Markdown
Contributor

@mjonss mjonss left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LTGM

@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Apr 1, 2026

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: mjonss, winoros

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@ti-chi-bot ti-chi-bot Bot added lgtm and removed needs-1-more-lgtm Indicates a PR needs 1 more LGTM. labels Apr 1, 2026
@ti-chi-bot
Copy link
Copy Markdown

ti-chi-bot Bot commented Apr 1, 2026

[LGTM Timeline notifier]

Timeline:

  • 2026-04-01 10:13:33.948210233 +0000 UTC m=+346419.153570300: ☑️ agreed by winoros.
  • 2026-04-01 11:08:25.288245106 +0000 UTC m=+349710.493605163: ☑️ agreed by mjonss.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
pkg/executor/infoschema_reader.go (1)

2583-2586: Consider a more descriptive error message.

The error "invalid start time" is returned when startTimeUTC is nil for a running job, but it lacks context about which job or table is affected. Consider including identifiers for easier debugging.

💡 Suggested improvement
 		if startTimeUTC == nil {
-			return nil, errors.New("invalid start time")
+			return nil, errors.Errorf("invalid start time for running analyze job on %s.%s", dbName, tableName)
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/executor/infoschema_reader.go` around lines 2583 - 2586, The current nil
check for startTimeUTC returns a generic error ("invalid start time"); update
the check in infoschema_reader.go so the error includes contextual identifiers
(e.g., job ID, table name, or analyze job info available in the surrounding
scope) and any relevant state so callers can identify which running job failed;
locate the check where startTimeUTC is validated before calling
getRemainDurationForAnalyzeStatusHelper and replace the plain error with a
formatted message that embeds those identifiers and the fact startTimeUTC was
nil.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@pkg/executor/infoschema_reader.go`:
- Around line 2583-2586: The current nil check for startTimeUTC returns a
generic error ("invalid start time"); update the check in infoschema_reader.go
so the error includes contextual identifiers (e.g., job ID, table name, or
analyze job info available in the surrounding scope) and any relevant state so
callers can identify which running job failed; locate the check where
startTimeUTC is validated before calling getRemainDurationForAnalyzeStatusHelper
and replace the plain error with a formatted message that embeds those
identifiers and the fact startTimeUTC was nil.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 63caa052-c79a-44b1-bfc8-1d8cc986ebd1

📥 Commits

Reviewing files that changed from the base of the PR and between 3239183 and 6d1ca89.

📒 Files selected for processing (1)
  • pkg/executor/infoschema_reader.go

@0xPoe
Copy link
Copy Markdown
Member Author

0xPoe commented Apr 1, 2026

/retest

4 similar comments
@0xPoe
Copy link
Copy Markdown
Member Author

0xPoe commented Apr 1, 2026

/retest

@0xPoe
Copy link
Copy Markdown
Member Author

0xPoe commented Apr 1, 2026

/retest

@0xPoe
Copy link
Copy Markdown
Member Author

0xPoe commented Apr 1, 2026

/retest

@0xPoe
Copy link
Copy Markdown
Member Author

0xPoe commented Apr 1, 2026

/retest

@0xPoe
Copy link
Copy Markdown
Member Author

0xPoe commented Apr 2, 2026

/test all

@0xPoe 0xPoe added the needs-cherry-pick-release-8.5 Should cherry pick this PR to release-8.5 branch. label Apr 2, 2026
@0xPoe
Copy link
Copy Markdown
Member Author

0xPoe commented Apr 2, 2026

/retest

1 similar comment
@0xPoe
Copy link
Copy Markdown
Member Author

0xPoe commented Apr 2, 2026

/retest

@tiprow
Copy link
Copy Markdown

tiprow Bot commented Apr 2, 2026

@0xPoe: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
fast_test_tiprow 6d1ca89 link true /test fast_test_tiprow
tidb_parser_test 6d1ca89 link true /test tidb_parser_test

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@ti-chi-bot ti-chi-bot Bot merged commit 4d20c4a into pingcap:master Apr 2, 2026
33 of 35 checks passed
ti-chi-bot pushed a commit to ti-chi-bot/tidb that referenced this pull request Apr 2, 2026
Signed-off-by: ti-chi-bot <ti-community-prow-bot@tidb.io>
@ti-chi-bot
Copy link
Copy Markdown
Member

In response to a cherrypick label: new pull request created to branch release-8.5: #67516.
But this PR has conflicts, please resolve them!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved lgtm needs-cherry-pick-release-8.5 Should cherry pick this PR to release-8.5 branch. release-note Denotes a PR that will be considered when it comes time to generate release notes. size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

show analyze status: Remaining_seconds can become negative in non-UTC sessions

4 participants