/
update.go
1635 lines (1544 loc) · 55.8 KB
/
update.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package handle
import (
"bytes"
"context"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/log"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/metrics"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/ranger"
"github.com/pingcap/tidb/util/sqlexec"
"github.com/pingcap/tidb/util/timeutil"
"go.uber.org/atomic"
"go.uber.org/zap"
"golang.org/x/exp/slices"
)
type tableDeltaMap map[int64]variable.TableDelta
func (m tableDeltaMap) update(id int64, delta int64, count int64, colSize *map[int64]int64) {
item := m[id]
item.Delta += delta
item.Count += count
if item.ColSize == nil {
item.ColSize = make(map[int64]int64)
}
if colSize != nil {
for key, val := range *colSize {
item.ColSize[key] += val
}
}
m[id] = item
}
func (m tableDeltaMap) merge(deltaMap tableDeltaMap) {
for id, item := range deltaMap {
m.update(id, item.Delta, item.Count, &item.ColSize)
}
}
type errorRateDelta struct {
PkID int64
PkErrorRate *statistics.ErrorRate
IdxErrorRate map[int64]*statistics.ErrorRate
}
type errorRateDeltaMap map[int64]errorRateDelta
func (m errorRateDeltaMap) update(tableID int64, histID int64, rate float64, isIndex bool) {
item := m[tableID]
if isIndex {
if item.IdxErrorRate == nil {
item.IdxErrorRate = make(map[int64]*statistics.ErrorRate)
}
if item.IdxErrorRate[histID] == nil {
item.IdxErrorRate[histID] = &statistics.ErrorRate{}
}
item.IdxErrorRate[histID].Update(rate)
} else {
if item.PkErrorRate == nil {
item.PkID = histID
item.PkErrorRate = &statistics.ErrorRate{}
}
item.PkErrorRate.Update(rate)
}
m[tableID] = item
}
func (m errorRateDeltaMap) merge(deltaMap errorRateDeltaMap) {
for tableID, item := range deltaMap {
tbl := m[tableID]
for histID, errorRate := range item.IdxErrorRate {
if tbl.IdxErrorRate == nil {
tbl.IdxErrorRate = make(map[int64]*statistics.ErrorRate)
}
if tbl.IdxErrorRate[histID] == nil {
tbl.IdxErrorRate[histID] = &statistics.ErrorRate{}
}
tbl.IdxErrorRate[histID].Merge(errorRate)
}
if item.PkErrorRate != nil {
if tbl.PkErrorRate == nil {
tbl.PkID = item.PkID
tbl.PkErrorRate = &statistics.ErrorRate{}
}
tbl.PkErrorRate.Merge(item.PkErrorRate)
}
m[tableID] = tbl
}
}
func (m errorRateDeltaMap) clear(tableID int64, histID int64, isIndex bool) {
item := m[tableID]
if isIndex {
delete(item.IdxErrorRate, histID)
} else {
item.PkErrorRate = nil
}
m[tableID] = item
}
// colStatsUsageMap maps (tableID, columnID) to the last time when the column stats are used(needed).
type colStatsUsageMap map[model.TableItemID]time.Time
func (m colStatsUsageMap) merge(other colStatsUsageMap) {
for id, t := range other {
if mt, ok := m[id]; !ok || mt.Before(t) {
m[id] = t
}
}
}
func merge(s *SessionStatsCollector, deltaMap tableDeltaMap, rateMap errorRateDeltaMap, feedback *statistics.QueryFeedbackMap, colMap colStatsUsageMap) {
deltaMap.merge(s.mapper)
s.mapper = make(tableDeltaMap)
rateMap.merge(s.rateMap)
s.rateMap = make(errorRateDeltaMap)
feedback.Merge(s.feedback)
s.feedback = statistics.NewQueryFeedbackMap()
colMap.merge(s.colMap)
s.colMap = make(colStatsUsageMap)
}
// SessionStatsCollector is a list item that holds the delta mapper. If you want to write or read mapper, you must lock it.
type SessionStatsCollector struct {
sync.Mutex
mapper tableDeltaMap
feedback *statistics.QueryFeedbackMap
rateMap errorRateDeltaMap
colMap colStatsUsageMap
next *SessionStatsCollector
// deleted is set to true when a session is closed. Every time we sweep the list, we will remove the useless collector.
deleted bool
}
// Delete only sets the deleted flag true, it will be deleted from list when DumpStatsDeltaToKV is called.
func (s *SessionStatsCollector) Delete() {
s.Lock()
defer s.Unlock()
s.deleted = true
}
// Update will updates the delta and count for one table id.
func (s *SessionStatsCollector) Update(id int64, delta int64, count int64, colSize *map[int64]int64) {
s.Lock()
defer s.Unlock()
s.mapper.update(id, delta, count, colSize)
}
var (
// MinLogScanCount is the minimum scan count for a feedback to be logged.
MinLogScanCount = atomic.NewInt64(1000)
// MinLogErrorRate is the minimum error rate for a feedback to be logged.
MinLogErrorRate = atomic.NewFloat64(0.5)
)
// StoreQueryFeedback merges the feedback into stats collector. Deprecated.
func (s *SessionStatsCollector) StoreQueryFeedback(feedback interface{}, h *Handle, enablePseudoForOutdatedStats bool) error {
q := feedback.(*statistics.QueryFeedback)
if !q.Valid.Load() || q.Hist == nil {
return nil
}
// if table locked, skip
if h.IsTableLocked(q.PhysicalID) {
return nil
}
err := h.RecalculateExpectCount(q, enablePseudoForOutdatedStats)
if err != nil {
return errors.Trace(err)
}
rate := q.CalcErrorRate()
minScanCnt := MinLogScanCount.Load()
minErrRate := MinLogErrorRate.Load()
if !(rate >= minErrRate && (q.Actual() >= minScanCnt || q.Expected >= minScanCnt)) {
return nil
}
metrics.SignificantFeedbackCounter.Inc()
metrics.StatsInaccuracyRate.Observe(rate)
if log.GetLevel() == zap.DebugLevel {
h.logDetailedInfo(q)
}
s.Lock()
defer s.Unlock()
isIndex := q.Tp == statistics.IndexType
s.rateMap.update(q.PhysicalID, q.Hist.ID, rate, isIndex)
s.feedback.Append(q)
return nil
}
// UpdateColStatsUsage updates the last time when the column stats are used(needed).
func (s *SessionStatsCollector) UpdateColStatsUsage(colMap colStatsUsageMap) {
s.Lock()
defer s.Unlock()
s.colMap.merge(colMap)
}
// NewSessionStatsCollector allocates a stats collector for a session.
func (h *Handle) NewSessionStatsCollector() *SessionStatsCollector {
h.listHead.Lock()
defer h.listHead.Unlock()
newCollector := &SessionStatsCollector{
mapper: make(tableDeltaMap),
rateMap: make(errorRateDeltaMap),
next: h.listHead.next,
feedback: statistics.NewQueryFeedbackMap(),
colMap: make(colStatsUsageMap),
}
h.listHead.next = newCollector
return newCollector
}
// IndexUsageInformation is the data struct to store index usage information.
type IndexUsageInformation struct {
QueryCount int64
RowsSelected int64
LastUsedAt string
}
// GlobalIndexID is the key type for indexUsageMap.
type GlobalIndexID struct {
TableID int64
IndexID int64
}
type indexUsageMap map[GlobalIndexID]IndexUsageInformation
// SessionIndexUsageCollector is a list item that holds the index usage mapper. If you want to write or read mapper, you must lock it.
type SessionIndexUsageCollector struct {
sync.Mutex
mapper indexUsageMap
next *SessionIndexUsageCollector
deleted bool
}
func (m indexUsageMap) updateByKey(id GlobalIndexID, value *IndexUsageInformation) {
item := m[id]
item.QueryCount += value.QueryCount
item.RowsSelected += value.RowsSelected
if item.LastUsedAt < value.LastUsedAt {
item.LastUsedAt = value.LastUsedAt
}
m[id] = item
}
func (m indexUsageMap) update(tableID int64, indexID int64, value *IndexUsageInformation) {
id := GlobalIndexID{TableID: tableID, IndexID: indexID}
m.updateByKey(id, value)
}
func (m indexUsageMap) merge(destMap indexUsageMap) {
for id := range destMap {
item := destMap[id]
m.updateByKey(id, &item)
}
}
// Update updates the mapper in SessionIndexUsageCollector.
func (s *SessionIndexUsageCollector) Update(tableID int64, indexID int64, value *IndexUsageInformation) {
value.LastUsedAt = time.Now().Format(types.TimeFSPFormat)
s.Lock()
defer s.Unlock()
s.mapper.update(tableID, indexID, value)
}
// Delete will set s.deleted to true which means it can be deleted from linked list.
func (s *SessionIndexUsageCollector) Delete() {
s.Lock()
defer s.Unlock()
s.deleted = true
}
// NewSessionIndexUsageCollector will add a new SessionIndexUsageCollector into linked list headed by idxUsageListHead.
// idxUsageListHead always points to an empty SessionIndexUsageCollector as a sentinel node. So we let idxUsageListHead.next
// points to new item. It's helpful to sweepIdxUsageList.
func (h *Handle) NewSessionIndexUsageCollector() *SessionIndexUsageCollector {
h.idxUsageListHead.Lock()
defer h.idxUsageListHead.Unlock()
newCollector := &SessionIndexUsageCollector{
mapper: make(indexUsageMap),
next: h.idxUsageListHead.next,
}
h.idxUsageListHead.next = newCollector
return newCollector
}
// sweepIdxUsageList will loop over the list, merge each session's local index usage information into handle
// and remove closed session's collector.
// For convenience, we keep idxUsageListHead always points to sentinel node. So that we don't need to consider corner case.
func (h *Handle) sweepIdxUsageList() indexUsageMap {
prev := h.idxUsageListHead
prev.Lock()
mapper := make(indexUsageMap)
for curr := prev.next; curr != nil; curr = curr.next {
curr.Lock()
mapper.merge(curr.mapper)
if curr.deleted {
prev.next = curr.next
curr.Unlock()
} else {
prev.Unlock()
curr.mapper = make(indexUsageMap)
prev = curr
}
}
prev.Unlock()
return mapper
}
// batchInsertSize is the batch size used by internal SQL to insert values to some system table.
const batchInsertSize = 10
// maxInsertLength is the length limit for internal insert SQL.
const maxInsertLength = 1024 * 1024
// DumpIndexUsageToKV will dump in-memory index usage information to KV.
func (h *Handle) DumpIndexUsageToKV() error {
ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnStats)
mapper := h.sweepIdxUsageList()
type FullIndexUsageInformation struct {
id GlobalIndexID
information IndexUsageInformation
}
indexInformationSlice := make([]FullIndexUsageInformation, 0, len(mapper))
for id, value := range mapper {
indexInformationSlice = append(indexInformationSlice, FullIndexUsageInformation{id: id, information: value})
}
for i := 0; i < len(mapper); i += batchInsertSize {
end := i + batchInsertSize
if end > len(mapper) {
end = len(mapper)
}
sql := new(strings.Builder)
sqlexec.MustFormatSQL(sql, "insert into mysql.SCHEMA_INDEX_USAGE (table_id,index_id,query_count,rows_selected,last_used_at) values")
for j := i; j < end; j++ {
index := indexInformationSlice[j]
sqlexec.MustFormatSQL(sql, "(%?, %?, %?, %?, %?)", index.id.TableID, index.id.IndexID,
index.information.QueryCount, index.information.RowsSelected, index.information.LastUsedAt)
if j < end-1 {
sqlexec.MustFormatSQL(sql, ",")
}
}
sqlexec.MustFormatSQL(sql, "on duplicate key update query_count=query_count+values(query_count),rows_selected=rows_selected+values(rows_selected),last_used_at=greatest(last_used_at, values(last_used_at))")
if _, _, err := h.execRestrictedSQL(ctx, sql.String()); err != nil {
return errors.Trace(err)
}
}
return nil
}
// GCIndexUsage will delete the usage information of those indexes that do not exist.
func (h *Handle) GCIndexUsage() error {
// For performance and implementation reasons, mysql.schema_index_usage doesn't handle DDL.
// We periodically delete the usage information of non-existent indexes through information_schema.tidb_indexes.
// This sql will delete the usage information of those indexes that not in information_schema.tidb_indexes.
sql := `delete from mysql.SCHEMA_INDEX_USAGE as stats where stats.index_id not in (select idx.index_id from information_schema.tidb_indexes as idx)`
_, _, err := h.execRestrictedSQL(context.Background(), sql)
return err
}
var (
// DumpStatsDeltaRatio is the lower bound of `Modify Count / Table Count` for stats delta to be dumped.
DumpStatsDeltaRatio = 1 / 10000.0
// dumpStatsMaxDuration is the max duration since last update.
dumpStatsMaxDuration = time.Hour
)
// needDumpStatsDelta returns true when only updates a small portion of the table and the time since last update
// do not exceed one hour.
func needDumpStatsDelta(h *Handle, id int64, item variable.TableDelta, currentTime time.Time) bool {
if item.InitTime.IsZero() {
item.InitTime = currentTime
}
tbl, ok := h.statsCache.Load().(statsCache).Get(id)
if !ok {
// No need to dump if the stats is invalid.
return false
}
if currentTime.Sub(item.InitTime) > dumpStatsMaxDuration {
// Dump the stats to kv at least once an hour.
return true
}
if tbl.Count == 0 || float64(item.Count)/float64(tbl.Count) > DumpStatsDeltaRatio {
// Dump the stats when there are many modifications.
return true
}
return false
}
type dumpMode bool
const (
// DumpAll indicates dump all the delta info in to kv.
DumpAll dumpMode = true
// DumpDelta indicates dump part of the delta info in to kv.
DumpDelta dumpMode = false
)
// sweepList will loop over the list, merge each session's local stats into handle
// and remove closed session's collector.
func (h *Handle) sweepList() {
deltaMap := make(tableDeltaMap)
errorRateMap := make(errorRateDeltaMap)
feedback := statistics.NewQueryFeedbackMap()
colMap := make(colStatsUsageMap)
prev := h.listHead
prev.Lock()
for curr := prev.next; curr != nil; curr = curr.next {
curr.Lock()
// Merge the session stats into deltaMap, errorRateMap and feedback respectively.
merge(curr, deltaMap, errorRateMap, feedback, colMap)
if curr.deleted {
prev.next = curr.next
// Since the session is already closed, we can safely unlock it here.
curr.Unlock()
} else {
// Unlock the previous lock, so we only holds at most two session's lock at the same time.
prev.Unlock()
prev = curr
}
}
prev.Unlock()
h.globalMap.Lock()
h.globalMap.data.merge(deltaMap)
h.globalMap.Unlock()
h.mu.Lock()
h.mu.rateMap.merge(errorRateMap)
h.mu.Unlock()
h.feedback.Lock()
h.feedback.data.Merge(feedback)
h.feedback.data.SiftFeedbacks()
h.feedback.Unlock()
h.colMap.Lock()
h.colMap.data.merge(colMap)
h.colMap.Unlock()
}
// DumpStatsDeltaToKV sweeps the whole list and updates the global map, then we dumps every table that held in map to KV.
// If the mode is `DumpDelta`, it will only dump that delta info that `Modify Count / Table Count` greater than a ratio.
func (h *Handle) DumpStatsDeltaToKV(mode dumpMode) error {
h.sweepList()
h.globalMap.Lock()
deltaMap := h.globalMap.data
h.globalMap.data = make(tableDeltaMap)
h.globalMap.Unlock()
defer func() {
h.globalMap.Lock()
deltaMap.merge(h.globalMap.data)
h.globalMap.data = deltaMap
h.globalMap.Unlock()
}()
currentTime := time.Now()
for id, item := range deltaMap {
if mode == DumpDelta && !needDumpStatsDelta(h, id, item, currentTime) {
continue
}
updated, err := h.dumpTableStatCountToKV(id, item)
if err != nil {
return errors.Trace(err)
}
if updated {
deltaMap.update(id, -item.Delta, -item.Count, nil)
}
if err = h.dumpTableStatColSizeToKV(id, item); err != nil {
delete(deltaMap, id)
return errors.Trace(err)
}
if updated {
delete(deltaMap, id)
} else {
m := deltaMap[id]
m.ColSize = nil
deltaMap[id] = m
}
}
return nil
}
// dumpTableStatDeltaToKV dumps a single delta with some table to KV and updates the version.
func (h *Handle) dumpTableStatCountToKV(id int64, delta variable.TableDelta) (updated bool, err error) {
statsVer := uint64(0)
defer func() {
if err == nil && statsVer != 0 {
err = h.recordHistoricalStatsMeta(id, statsVer)
}
}()
if delta.Count == 0 {
return true, nil
}
h.mu.Lock()
defer h.mu.Unlock()
ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnStats)
exec := h.mu.ctx.(sqlexec.SQLExecutor)
_, err = exec.ExecuteInternal(ctx, "begin")
if err != nil {
return false, errors.Trace(err)
}
defer func() {
err = finishTransaction(ctx, exec, err)
}()
txn, err := h.mu.ctx.Txn(true)
if err != nil {
return false, errors.Trace(err)
}
startTS := txn.StartTS()
updateStatsMeta := func(id int64) error {
var err error
if h.IsTableLocked(id) {
if delta.Delta < 0 {
_, err = exec.ExecuteInternal(ctx, "update mysql.stats_table_locked set version = %?, count = count - %?, modify_count = modify_count + %? where table_id = %? and count >= %?", startTS, -delta.Delta, delta.Count, id, -delta.Delta)
} else {
_, err = exec.ExecuteInternal(ctx, "update mysql.stats_table_locked set version = %?, count = count + %?, modify_count = modify_count + %? where table_id = %?", startTS, delta.Delta, delta.Count, id)
}
} else {
if delta.Delta < 0 {
_, err = exec.ExecuteInternal(ctx, "update mysql.stats_meta set version = %?, count = count - %?, modify_count = modify_count + %? where table_id = %? and count >= %?", startTS, -delta.Delta, delta.Count, id, -delta.Delta)
} else {
_, err = exec.ExecuteInternal(ctx, "update mysql.stats_meta set version = %?, count = count + %?, modify_count = modify_count + %? where table_id = %?", startTS, delta.Delta, delta.Count, id)
}
}
statsVer = startTS
return errors.Trace(err)
}
if err = updateStatsMeta(id); err != nil {
return
}
affectedRows := h.mu.ctx.GetSessionVars().StmtCtx.AffectedRows()
// if it's a partitioned table and its global-stats exists, update its count and modify_count as well.
is := h.mu.ctx.GetInfoSchema().(infoschema.InfoSchema)
if is == nil {
return false, errors.New("cannot get the information schema")
}
if tbl, _, _ := is.FindTableByPartitionID(id); tbl != nil {
if err = updateStatsMeta(tbl.Meta().ID); err != nil {
return
}
}
affectedRows += h.mu.ctx.GetSessionVars().StmtCtx.AffectedRows()
updated = affectedRows > 0
return
}
func (h *Handle) dumpTableStatColSizeToKV(id int64, delta variable.TableDelta) error {
if len(delta.ColSize) == 0 {
return nil
}
values := make([]string, 0, len(delta.ColSize))
for histID, deltaColSize := range delta.ColSize {
if deltaColSize == 0 {
continue
}
values = append(values, fmt.Sprintf("(%d, 0, %d, 0, %d)", id, histID, deltaColSize))
}
if len(values) == 0 {
return nil
}
ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnStats)
sql := fmt.Sprintf("insert into mysql.stats_histograms (table_id, is_index, hist_id, distinct_count, tot_col_size) "+
"values %s on duplicate key update tot_col_size = tot_col_size + values(tot_col_size)", strings.Join(values, ","))
_, _, err := h.execRestrictedSQL(ctx, sql)
return errors.Trace(err)
}
// DumpStatsFeedbackToKV dumps the stats feedback to KV. Deprecated.
func (h *Handle) DumpStatsFeedbackToKV() error {
h.feedback.Lock()
feedback := h.feedback.data
h.feedback.data = statistics.NewQueryFeedbackMap()
h.feedback.Unlock()
var err error
for _, fbs := range feedback.Feedbacks {
for _, fb := range fbs {
if fb.Tp == statistics.PkType {
err = h.DumpFeedbackToKV(fb)
} else {
t, ok := h.statsCache.Load().(statsCache).Get(fb.PhysicalID)
if !ok {
continue
}
idx, ok := t.Indices[fb.Hist.ID]
if !ok {
continue
}
if idx.StatsVer == statistics.Version1 {
err = h.DumpFeedbackForIndex(fb, t)
} else {
err = h.DumpFeedbackToKV(fb)
}
}
if err != nil {
// For simplicity, we just drop other feedbacks in case of error.
break
}
}
}
return errors.Trace(err)
}
// DumpFeedbackToKV dumps the given feedback to physical kv layer.
func (h *Handle) DumpFeedbackToKV(fb *statistics.QueryFeedback) error {
vals, err := statistics.EncodeFeedback(fb)
if err != nil {
logutil.BgLogger().Debug("error occurred when encoding feedback", zap.Error(err))
return nil
}
var isIndex int64
if fb.Tp == statistics.IndexType {
isIndex = 1
}
ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnStats)
const sql = "insert into mysql.stats_feedback (table_id, hist_id, is_index, feedback) values (%?, %?, %?, %?)"
h.mu.Lock()
_, err = h.mu.ctx.(sqlexec.SQLExecutor).ExecuteInternal(ctx, sql, fb.PhysicalID, fb.Hist.ID, isIndex, vals)
h.mu.Unlock()
if err != nil {
metrics.DumpFeedbackCounter.WithLabelValues(metrics.LblError).Inc()
} else {
metrics.DumpFeedbackCounter.WithLabelValues(metrics.LblOK).Inc()
}
return errors.Trace(err)
}
// UpdateStatsByLocalFeedback will update statistics by the local feedback.
// Currently, we dump the feedback with the period of 10 minutes, which means
// it takes 10 minutes for a feedback to take effect. However, we can use the
// feedback locally on this tidb-server, so it could be used more timely.
func (h *Handle) UpdateStatsByLocalFeedback(is infoschema.InfoSchema) {
h.sweepList()
h.feedback.Lock()
feedback := h.feedback.data
h.feedback.data = statistics.NewQueryFeedbackMap()
h.feedback.Unlock()
OUTER:
for _, fbs := range feedback.Feedbacks {
for _, fb := range fbs {
h.mu.Lock()
table, ok := h.getTableByPhysicalID(is, fb.PhysicalID)
h.mu.Unlock()
if !ok {
continue
}
if table.Meta().Partition != nil {
// If the table is partition table, the feedback will not work.
continue
}
tblStats := h.GetPartitionStats(table.Meta(), fb.PhysicalID)
newTblStats := tblStats.Copy()
if fb.Tp == statistics.IndexType {
idx, ok := tblStats.Indices[fb.Hist.ID]
if !ok || idx.Histogram.Len() == 0 {
continue
}
newIdx := *idx
eqFB, ranFB := statistics.SplitFeedbackByQueryType(fb.Feedback)
if idx.StatsVer >= statistics.Version2 {
// // For StatsVersion higher than Version1, the topn is extracted out of histogram. So we don't update the histogram if the feedback overlaps with some topn.
// ranFB = statistics.CleanRangeFeedbackByTopN(ranFB, idx.TopN)
continue OUTER
}
newIdx.CMSketch, newIdx.TopN = statistics.UpdateCMSketchAndTopN(idx.CMSketch, idx.TopN, eqFB)
newIdx.Histogram = *statistics.UpdateHistogram(&idx.Histogram, &statistics.QueryFeedback{Feedback: ranFB}, int(idx.StatsVer))
newIdx.Histogram.PreCalculateScalar()
newIdx.Flag = statistics.ResetAnalyzeFlag(newIdx.Flag)
newTblStats.Indices[fb.Hist.ID] = &newIdx
} else {
col, ok := tblStats.Columns[fb.Hist.ID]
if !ok || col.Histogram.Len() == 0 {
continue
}
if col.StatsVer >= statistics.Version2 {
// // For StatsVersion higher than Version1, the topn is extracted out of histogram. So we don't update the histogram if the feedback overlaps with some topn.
// ranFB = statistics.CleanRangeFeedbackByTopN(ranFB, idx.TopN)
continue OUTER
}
newCol := *col
// only use the range query to update primary key
_, ranFB := statistics.SplitFeedbackByQueryType(fb.Feedback)
newFB := &statistics.QueryFeedback{Feedback: ranFB}
newFB = newFB.DecodeIntValues()
newCol.Histogram = *statistics.UpdateHistogram(&col.Histogram, newFB, statistics.Version1)
newCol.Flag = statistics.ResetAnalyzeFlag(newCol.Flag)
newTblStats.Columns[fb.Hist.ID] = &newCol
}
for retry := updateStatsCacheRetryCnt; retry > 0; retry-- {
oldCache := h.statsCache.Load().(statsCache)
if h.updateStatsCache(oldCache.update([]*statistics.Table{newTblStats}, nil, oldCache.version)) {
break
}
}
}
}
}
// UpdateErrorRate updates the error rate of columns from h.rateMap to cache.
func (h *Handle) UpdateErrorRate(is infoschema.InfoSchema) {
h.mu.Lock()
tbls := make([]*statistics.Table, 0, len(h.mu.rateMap))
for id, item := range h.mu.rateMap {
table, ok := h.getTableByPhysicalID(is, id)
if !ok {
continue
}
tbl := h.GetPartitionStats(table.Meta(), id).Copy()
if item.PkErrorRate != nil && tbl.Columns[item.PkID] != nil {
col := *tbl.Columns[item.PkID]
col.ErrorRate.Merge(item.PkErrorRate)
tbl.Columns[item.PkID] = &col
}
for key, val := range item.IdxErrorRate {
if tbl.Indices[key] == nil {
continue
}
idx := *tbl.Indices[key]
idx.ErrorRate.Merge(val)
tbl.Indices[key] = &idx
}
tbls = append(tbls, tbl)
delete(h.mu.rateMap, id)
}
h.mu.Unlock()
for retry := updateStatsCacheRetryCnt; retry > 0; retry-- {
oldCache := h.statsCache.Load().(statsCache)
if h.updateStatsCache(oldCache.update(tbls, nil, oldCache.version)) {
break
}
}
}
// HandleUpdateStats update the stats using feedback.
func (h *Handle) HandleUpdateStats(is infoschema.InfoSchema) error {
ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnStats)
tables, _, err := h.execRestrictedSQL(ctx, "SELECT distinct table_id from mysql.stats_feedback")
if err != nil {
return errors.Trace(err)
}
if len(tables) == 0 {
return nil
}
for _, ptbl := range tables {
tableID, histID, isIndex := ptbl.GetInt64(0), int64(-1), int64(-1)
for {
// fetch at most 100000 rows each time to avoid OOM
const sql = "select table_id, hist_id, is_index, feedback from mysql.stats_feedback where table_id = %? and is_index >= %? and hist_id > %? order by is_index, hist_id limit 100000"
rows, _, err := h.execRestrictedSQL(ctx, sql, tableID, histID, isIndex)
if err != nil {
return errors.Trace(err)
}
if len(rows) == 0 {
break
}
startIdx := 0
for i, row := range rows {
if row.GetInt64(1) != histID || row.GetInt64(2) != isIndex {
if i > 0 {
if err = h.handleSingleHistogramUpdate(is, rows[startIdx:i]); err != nil {
return errors.Trace(err)
}
}
histID, isIndex = row.GetInt64(1), row.GetInt64(2)
startIdx = i
}
}
if err = h.handleSingleHistogramUpdate(is, rows[startIdx:]); err != nil {
return errors.Trace(err)
}
}
}
return nil
}
// handleSingleHistogramUpdate updates the Histogram and CM Sketch using these feedbacks. All the feedbacks for
// the same index or column are gathered in `rows`.
func (h *Handle) handleSingleHistogramUpdate(is infoschema.InfoSchema, rows []chunk.Row) (err error) {
physicalTableID, histID, isIndex := rows[0].GetInt64(0), rows[0].GetInt64(1), rows[0].GetInt64(2)
defer func() {
if err == nil {
err = errors.Trace(h.deleteOutdatedFeedback(physicalTableID, histID, isIndex))
}
}()
h.mu.Lock()
table, ok := h.getTableByPhysicalID(is, physicalTableID)
h.mu.Unlock()
// The table has been deleted.
if !ok {
return nil
}
var tbl *statistics.Table
// feedback for partition is not ready
if table.Meta().GetPartitionInfo() != nil {
return nil
}
tbl = h.GetTableStats(table.Meta())
var cms *statistics.CMSketch
var hist *statistics.Histogram
var topN *statistics.TopN
var statsVer int64 = statistics.Version1
if isIndex == 1 {
idx, ok := tbl.Indices[histID]
statsVer = idx.StatsVer
if statsVer >= 2 {
logutil.BgLogger().Warn("[stats] Feedback is discarded because statistics on this table is version 2, which is incompatible with feedback. "+
"Please consider setting feedback-probability to 0.0 in config file to disable query feedback.",
zap.Int64("table_id", physicalTableID), zap.Int64("hist_id", histID), zap.Int64("is_index", isIndex))
return err
}
if ok && idx.Histogram.Len() > 0 {
statsVer = idx.StatsVer
idxHist := idx.Histogram
hist = &idxHist
cms = idx.CMSketch.Copy()
topN = idx.TopN.Copy()
}
} else {
col, ok := tbl.Columns[histID]
if ok && col.StatsVer >= 2 {
logutil.BgLogger().Warn("[stats] Feedback is discarded because statistics on this table is version 2, which is incompatible with feedback. "+
"Please consider setting feedback-probability to 0.0 in config file to disable query feedback.",
zap.Int64("table_id", physicalTableID), zap.Int64("hist_id", histID), zap.Int64("is_index", isIndex))
return err
}
if ok && col.Histogram.Len() > 0 {
colHist := col.Histogram
hist = &colHist
}
}
// The column or index has been deleted.
if hist == nil {
return nil
}
q := &statistics.QueryFeedback{}
for _, row := range rows {
err1 := statistics.DecodeFeedback(row.GetBytes(3), q, cms, topN, hist.Tp)
if err1 != nil {
logutil.BgLogger().Debug("decode feedback failed", zap.Error(err1))
}
}
err = h.dumpStatsUpdateToKV(physicalTableID, isIndex, q, hist, cms, topN, statsVer)
return errors.Trace(err)
}
func (h *Handle) deleteOutdatedFeedback(tableID, histID, isIndex int64) error {
h.mu.Lock()
defer h.mu.Unlock()
hasData := true
ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnStats)
for hasData {
sql := "delete from mysql.stats_feedback where table_id = %? and hist_id = %? and is_index = %? limit 10000"
_, err := h.mu.ctx.(sqlexec.SQLExecutor).ExecuteInternal(ctx, sql, tableID, histID, isIndex)
if err != nil {
return errors.Trace(err)
}
hasData = h.mu.ctx.GetSessionVars().StmtCtx.AffectedRows() > 0
}
return nil
}
func (h *Handle) dumpStatsUpdateToKV(tableID, isIndex int64, q *statistics.QueryFeedback, hist *statistics.Histogram, cms *statistics.CMSketch, topN *statistics.TopN, statsVersion int64) error {
hist = statistics.UpdateHistogram(hist, q, int(statsVersion))
// feedback for partition is not ready.
err := h.SaveStatsToStorage(tableID, -1, 0, int(isIndex), hist, cms, topN, int(statsVersion), 0, false)
metrics.UpdateStatsCounter.WithLabelValues(metrics.RetLabel(err)).Inc()
return errors.Trace(err)
}
// DumpColStatsUsageToKV sweeps the whole list, updates the column stats usage map and dumps it to KV.
func (h *Handle) DumpColStatsUsageToKV() error {
if !variable.EnableColumnTracking.Load() {
return nil
}
h.sweepList()
h.colMap.Lock()
colMap := h.colMap.data
h.colMap.data = make(colStatsUsageMap)
h.colMap.Unlock()
defer func() {
h.colMap.Lock()
h.colMap.data.merge(colMap)
h.colMap.Unlock()
}()
type pair struct {
tblColID model.TableItemID
lastUsedAt string
}
pairs := make([]pair, 0, len(colMap))
for id, t := range colMap {
pairs = append(pairs, pair{tblColID: id, lastUsedAt: t.UTC().Format(types.TimeFormat)})
}
slices.SortFunc(pairs, func(i, j pair) bool {
if i.tblColID.TableID == j.tblColID.TableID {
return i.tblColID.ID < j.tblColID.ID
}
return i.tblColID.TableID < j.tblColID.TableID
})
// Use batch insert to reduce cost.
for i := 0; i < len(pairs); i += batchInsertSize {
end := i + batchInsertSize
if end > len(pairs) {
end = len(pairs)
}
sql := new(strings.Builder)
sqlexec.MustFormatSQL(sql, "INSERT INTO mysql.column_stats_usage (table_id, column_id, last_used_at) VALUES ")
for j := i; j < end; j++ {
// Since we will use some session from session pool to execute the insert statement, we pass in UTC time here and covert it
// to the session's time zone when executing the insert statement. In this way we can make the stored time right.
sqlexec.MustFormatSQL(sql, "(%?, %?, CONVERT_TZ(%?, '+00:00', @@TIME_ZONE))", pairs[j].tblColID.TableID, pairs[j].tblColID.ID, pairs[j].lastUsedAt)
if j < end-1 {
sqlexec.MustFormatSQL(sql, ",")
}
}
sqlexec.MustFormatSQL(sql, " ON DUPLICATE KEY UPDATE last_used_at = CASE WHEN last_used_at IS NULL THEN VALUES(last_used_at) ELSE GREATEST(last_used_at, VALUES(last_used_at)) END")
if _, _, err := h.execRestrictedSQL(context.Background(), sql.String()); err != nil {
return errors.Trace(err)
}
for j := i; j < end; j++ {
delete(colMap, pairs[j].tblColID)
}
}
return nil
}
const (
// StatsOwnerKey is the stats owner path that is saved to etcd.
StatsOwnerKey = "/tidb/stats/owner"
// StatsPrompt is the prompt for stats owner manager.
StatsPrompt = "stats"
)
// AutoAnalyzeMinCnt means if the count of table is less than this value, we needn't do auto analyze.
var AutoAnalyzeMinCnt int64 = 1000
// TableAnalyzed checks if the table is analyzed.
func TableAnalyzed(tbl *statistics.Table) bool {
for _, col := range tbl.Columns {
if col.IsAnalyzed() {
return true
}
}
for _, idx := range tbl.Indices {
if idx.IsAnalyzed() {
return true
}
}
return false
}
// NeedAnalyzeTable checks if we need to analyze the table:
// 1. If the table has never been analyzed, we need to analyze it when it has
// not been modified for a while.
// 2. If the table had been analyzed before, we need to analyze it when
// "tbl.ModifyCount/tbl.Count > autoAnalyzeRatio" and the current time is
// between `start` and `end`.
func NeedAnalyzeTable(tbl *statistics.Table, limit time.Duration, autoAnalyzeRatio float64) (bool, string) {
analyzed := TableAnalyzed(tbl)
if !analyzed {
return true, "table unanalyzed"
}
// Auto analyze is disabled.
if autoAnalyzeRatio == 0 {