@@ -65,6 +65,22 @@ func TestGetAverageAnalysisDuration(t *testing.T) {
6565 require .Equal (t , time .Duration (3600 )* time .Second , avgDuration )
6666}
6767
68+ func TestGetAverageAnalysisDurationNegativeRecord (t * testing.T ) {
69+ store := testkit .CreateMockStore (t )
70+ tk := testkit .NewTestKit (t , store )
71+ tk .MustExec ("use test" )
72+ tk .MustExec (metadef .CreateAnalyzeJobsTable )
73+
74+ // Insert a finished record with end_time earlier than start_time to force a negative duration.
75+ // This could happen if the system clock is adjusted backward (rare in practice).
76+ insertFinishedJob (tk , "neg_schema" , "neg_table" , "" , "2024-01-01 10:00:00" , "2024-01-01 09:00:00" )
77+
78+ sctx := tk .Session ().(sessionctx.Context )
79+ avgDuration , err := priorityqueue .GetAverageAnalysisDuration (sctx , "neg_schema" , "neg_table" )
80+ require .NoError (t , err )
81+ require .Equal (t , time .Duration (priorityqueue .NoRecord ), avgDuration )
82+ }
83+
6884func insertMultipleFinishedJobs (tk * testkit.TestKit , tableName string , partitionName string ) {
6985 jobs := []struct {
7086 dbName string
@@ -130,6 +146,21 @@ func TestGetLastFailedAnalysisDuration(t *testing.T) {
130146 require .GreaterOrEqual (t , lastFailedDuration , time .Duration (24 )* time .Hour )
131147}
132148
149+ func TestGetLastFailedAnalysisDurationNegativeRecord (t * testing.T ) {
150+ store := testkit .CreateMockStore (t )
151+ tk := testkit .NewTestKit (t , store )
152+ tk .MustExec ("use test" )
153+ tk .MustExec (metadef .CreateAnalyzeJobsTable )
154+
155+ // Insert a failed record whose start_time is in the future to force a negative duration.
156+ insertFailedJobWithStartTime (tk , "neg_schema" , "neg_table" , "" , "2037-01-01 00:00:00" )
157+
158+ sctx := tk .Session ().(sessionctx.Context )
159+ lastFailedDuration , err := priorityqueue .GetLastFailedAnalysisDuration (sctx , "neg_schema" , "neg_table" )
160+ require .NoError (t , err )
161+ require .Equal (t , 30 * time .Minute , lastFailedDuration )
162+ }
163+
133164func initJobs (tk * testkit.TestKit ) {
134165 tk .MustExec (`
135166 INSERT INTO mysql.analyze_jobs (
0 commit comments