-
Notifications
You must be signed in to change notification settings - Fork 6
/
position_revise_sort.go
1523 lines (1426 loc) · 42.6 KB
/
position_revise_sort.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
package sort
import (
gocontext "context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"hash/crc32"
"math"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/alibaba/pairec/v2/abtest"
"github.com/alibaba/pairec/v2/context"
"github.com/alibaba/pairec/v2/log"
"github.com/alibaba/pairec/v2/module"
"github.com/alibaba/pairec/v2/persist/holo"
"github.com/alibaba/pairec/v2/recconf"
"github.com/alibaba/pairec/v2/utils"
"github.com/alibaba/pairec/v2/utils/sqlutil"
"github.com/aliyun/aliyun-pairec-config-go-sdk/v2/experiments"
"github.com/goburrow/cache"
"github.com/huandu/go-sqlbuilder"
"golang.org/x/exp/rand"
"gonum.org/v1/gonum/stat/sampleuv"
)
type PositionReviseSort struct {
config *recconf.PIDControllerConfig
exp2controllers map[string]map[int]*PIDController
clock sync.RWMutex
db *sql.DB
feaMu sync.RWMutex
feaStmtMap map[string]map[int]*sql.Stmt
itemCache cache.Cache
loadItemFeature bool
preloadItemFeature bool
cloneInstances map[string]*PositionReviseSort
name string
boostScoreSort *BoostScoreSort
}
var positionWeight []float64
var expTable []float64
var tanhTable []float64
var sigmoidTable []float64
func init() {
positionWeight = make([]float64, 500)
for i := 0; i < 500; i++ {
positionWeight[i] = math.Exp(-0.01 * float64(i))
}
expTable = make([]float64, 1000)
for i := 0; i < 1000; i++ {
expTable[i] = math.Exp(float64(i) / 1000.0)
}
tanhTable = make([]float64, 3000)
for i := 0; i < 3000; i++ {
tanhTable[i] = math.Tanh(float64(i) / 1000.0) // 值域范围 [0, 3)
}
sigmoidTable = make([]float64, 10000)
for i := 0; i < 10000; i++ {
x := float64(i)/1000.0 + 5.0 // 范围 [5, 15)
sigmoidTable[i] = 1.0 / (1.0 + math.Exp(10-x))
}
}
func tanh(x float64) float64 {
idx := int(x * 1000)
if idx < 0 {
idx = 0
} else if idx >= 3000 {
idx = 2999
}
return tanhTable[idx]
}
func sigmoid(x, rho float64) float64 {
idx := int(rho*x*1000.0) - 5000.0
if idx < 0 {
idx = 0
} else if idx >= 10000 {
return 1
}
return sigmoidTable[idx]
}
func NewPositionReviseSort(config recconf.SortConfig) *PositionReviseSort {
conf := config.PIDConf
var db *sql.DB = nil
if conf.LoadItemFeature {
hologres, err := holo.GetPostgres(conf.HologresName)
if err != nil {
log.Error(fmt.Sprintf("get hologres error=%v, name=%s", err, conf.HologresName))
return nil
}
db = hologres.DB
}
maxCacheSize := 100000
if conf.MaxItemCacheSize > 0 {
maxCacheSize = conf.MaxItemCacheSize
}
minCacheTime := 3600
if conf.MaxItemCacheTime > 0 {
minCacheTime = conf.MaxItemCacheTime
}
r := PositionReviseSort{
config: &conf,
exp2controllers: make(map[string]map[int]*PIDController),
db: db,
loadItemFeature: conf.LoadItemFeature,
preloadItemFeature: conf.PreloadItemFeature,
feaStmtMap: make(map[string]map[int]*sql.Stmt),
itemCache: cache.New(cache.WithMaximumSize(maxCacheSize),
cache.WithExpireAfterWrite(time.Duration(minCacheTime)*time.Second)),
name: config.Name,
cloneInstances: make(map[string]*PositionReviseSort),
}
if len(conf.BoostScoreConditions) > 0 {
boostConf := recconf.SortConfig{
Debug: config.Debug,
BoostScoreConditions: conf.BoostScoreConditions,
}
r.boostScoreSort = NewBoostScoreSort(boostConf)
}
go func() {
for {
// check for new control plans and new control targets
//r.loadFlowControlPlan("")
for expId := range r.exp2controllers {
r.loadFlowControlPlan(expId)
}
if r.preloadItemFeature {
r.loadAllItemFeature()
}
time.Sleep(time.Minute) // 这里需要更新频繁一点,不然web页面上meta信息的修改不能及时反应出来
}
}()
return &r
}
func (p *PositionReviseSort) loadAllItemFeature() {
client := abtest.GetExperimentClient()
ignoreTables := make(map[string]bool)
tableFields := make(map[string][]string)
tableIdField := make(map[string]string)
for _, dict := range p.exp2controllers {
for _, c := range dict {
planId := fmt.Sprintf("__%d__", c.plan.PlanId)
if _, processed := ignoreTables[planId]; !processed {
if c.plan.OnlineDatasourceType != "hologres" {
log.Error("Unsupported online datasource type: " + c.plan.OnlineDatasourceType)
continue
}
params := client.GetSceneParams(c.plan.SceneName)
ignoreFeaTable := params.GetString("ignore_feature_table", "")
if ignoreFeaTable != "" {
tables := strings.Split(ignoreFeaTable, ",")
for _, table := range tables {
table = strings.Trim(table, " \t")
if table != "" {
ignoreTables[table] = true
}
}
}
}
table := c.plan.OnlineTableName
if _, ok := ignoreTables[table]; ok {
continue
}
tableIdField[table] = c.plan.OnlineTableItemIdField
tableFields[table] = append(tableFields[table], c.plan.OnlineTableItemIdField)
fields := getFilterFields(c.plan.PlanScopeFilterJson)
if fields != nil && len(fields) > 0 {
for _, field := range fields {
tableFields[table] = append(tableFields[table], field)
}
}
fields = getFilterFields(c.target.TargetScopeFilterJson)
if fields != nil && len(fields) > 0 {
for _, field := range fields {
tableFields[table] = append(tableFields[table], field)
}
}
}
}
if len(tableFields) == 0 {
log.Warning("There's no item attribute table")
return
}
for table, fields := range tableFields {
idField, _ := tableIdField[table]
p.loadAllItemFeatureFromHolo(table, idField, fields)
}
}
func (p *PositionReviseSort) loadAllItemFeatureFromHolo(table string, idField string, fields []string) {
selectFields := utils.UniqueStrings(fields)
sb := sqlbuilder.PostgreSQL.NewSelectBuilder()
sb.Select(selectFields...)
sb.From(table)
sqlQuery, args := sb.Build()
log.Debug("module=PositionReviseSort\tfn=loadAllItemFeatureFromHolo\tquery:" + sqlQuery)
sort.Strings(selectFields)
cols := strings.Join(selectFields, ",")
hash := crc32.ChecksumIEEE([]byte(cols))
tableKey := fmt.Sprintf("%s_%d_%d", table, len(selectFields), hash)
numItems := 0
p.feaMu.RLock()
feaStmtMap := p.feaStmtMap[tableKey]
feaStmt := feaStmtMap[numItems]
p.feaMu.RUnlock()
if feaStmt == nil {
p.feaMu.Lock()
if feaStmtMap == nil {
feaStmtMap = p.feaStmtMap[tableKey]
if feaStmtMap == nil {
feaStmtMap = make(map[int]*sql.Stmt)
p.feaStmtMap[tableKey] = feaStmtMap
}
}
feaStmt = feaStmtMap[numItems]
if feaStmt == nil {
if stmt, err := p.db.Prepare(sqlQuery); err != nil {
log.Error(fmt.Sprintf("model=PositionReviseSort\tfn=loadAllItemFeatureFromHolo\terr=%v", err))
p.feaMu.Unlock()
return
} else {
feaStmt = stmt
feaStmtMap[numItems] = stmt
}
}
p.feaMu.Unlock()
}
cntx, cancel := gocontext.WithTimeout(gocontext.Background(), 300*time.Millisecond)
defer cancel()
rows, err := feaStmt.QueryContext(cntx, args...)
if err != nil {
if errors.Is(err, gocontext.DeadlineExceeded) {
log.Warning("module=PositionReviseSort\tevent=loadAllItemFeatureFromHolo\ttimeout=200")
return
}
log.Error(fmt.Sprintf("module=PositionReviseSort\terror=hologres error(%v)", err))
return
}
defer rows.Close()
columns, err := rows.ColumnTypes()
if err != nil {
log.Error(fmt.Sprintf("module=PositionReviseSort\terror=hologres error(%v)", err))
return
}
values := sqlutil.ColumnValues(columns)
count := 0
for rows.Next() {
if err = rows.Scan(values...); err == nil {
features := make(map[string]interface{})
for i, column := range columns {
name := column.Name()
val := values[i]
switch v := val.(type) {
case *sql.NullString:
if v.Valid {
features[name] = v.String
}
case *sql.NullInt32:
if v.Valid {
features[name] = v.Int32
}
case *sql.NullInt64:
if v.Valid {
features[name] = v.Int64
}
case *sql.NullFloat64:
if v.Valid {
features[name] = v.Float64
}
case *sql.NullBool:
if v.Valid {
features[name] = v.Bool
}
case *sql.NullTime:
if v.Valid {
features[name] = v.Time
}
default:
}
}
if id, ok := features[idField]; ok {
delete(features, idField)
itemId := utils.ToString(id, "")
cacheKey := table + "_" + itemId
p.itemCache.Put(cacheKey, features)
count++
} else {
log.Error(fmt.Sprintf("module=PositionReviseSort\tevent=loadAllItemFeatureFromHolo\tNo item id found"))
}
} else {
log.Error(fmt.Sprintf("module=PositionReviseSort\terror=hologres error(%v)", err))
}
}
log.Info(fmt.Sprintf("module=PositionReviseSort\tevent=loadAllItemFeatureFromHolo\tload %d item feature from table %s",
count, table))
}
func (p *PositionReviseSort) loadItemFeatures(items []*module.Item, ctx *context.RecommendContext, wg *sync.WaitGroup) {
defer wg.Done()
begin := time.Now()
defer func() {
ctx.LogInfo(fmt.Sprintf("module=PID_loadItemFeature\tcount=%d\tcost=%d",
len(items), utils.CostTime(begin)))
}()
if len(items) == 0 {
return
}
controllers := p.getPidControllers(ctx)
if controllers == nil || len(controllers) == 0 {
return
}
client := abtest.GetExperimentClient()
ignoreTables := make(map[string]bool)
tableFields := make(map[string][]string)
tableIdField := make(map[string]string)
for _, c := range controllers {
planId := fmt.Sprintf("__%d__", c.plan.PlanId)
if _, processed := ignoreTables[planId]; !processed {
if c.plan.OnlineDatasourceType != "hologres" {
log.Error("Unsupported online datasource type: " + c.plan.OnlineDatasourceType)
continue
}
params := client.GetSceneParams(c.plan.SceneName)
ignoreFeaTable := params.GetString("ignore_feature_table", "")
if ignoreFeaTable != "" {
tables := strings.Split(ignoreFeaTable, ",")
for _, table := range tables {
table = strings.Trim(table, " \t")
if table != "" {
ignoreTables[table] = true
}
}
}
}
table := c.plan.OnlineTableName
if _, ok := ignoreTables[table]; ok {
continue
}
tableIdField[table] = c.plan.OnlineTableItemIdField
tableFields[table] = append(tableFields[table], c.plan.OnlineTableItemIdField)
fields := getFilterFields(c.plan.PlanScopeFilterJson)
if fields != nil && len(fields) > 0 {
for _, field := range fields {
tableFields[table] = append(tableFields[table], field)
}
}
fields = getFilterFields(c.target.TargetScopeFilterJson)
if fields != nil && len(fields) > 0 {
for _, field := range fields {
tableFields[table] = append(tableFields[table], field)
}
}
}
if len(tableFields) == 0 {
ctx.LogWarning("There's no item attribute table and fields parsed")
return
}
for table, fields := range tableFields {
idField, _ := tableIdField[table]
p.loadItemFeatureFromHolo(table, idField, fields, items, ctx)
}
}
func getPaddingSize(n int) int {
var t = 32
for i := 5; i < n; i++ {
t = 1 << i
if t >= n {
break
}
}
return t - n
}
func (p *PositionReviseSort) loadItemFeatureFromHolo(table string, idField string, fields []string,
items []*module.Item, ctx *context.RecommendContext) {
itemIds := make([]interface{}, 0, len(items))
itemMap := make(map[string]*module.Item, len(items))
count := 0
for _, item := range items {
cacheKey := table + "_" + string(item.Id)
if attr, exist := p.itemCache.GetIfPresent(cacheKey); exist {
value := attr.(map[string]interface{})
if value != nil {
item.AddProperties(value)
}
count++
} else {
itemIds = append(itemIds, item.Id)
itemMap[string(item.Id)] = item
}
}
ctx.LogDebug(fmt.Sprintf("module=PositionReviseSort\tfn=loadItemFeatureFromHolo\tcache hit=%d", count))
if len(itemIds) == 0 || p.preloadItemFeature {
return
}
padNum := getPaddingSize(len(itemIds))
for i := 0; i < padNum; i++ {
itemIds = append(itemIds, "-1")
}
selectFields := utils.UniqueStrings(fields)
sb := sqlbuilder.PostgreSQL.NewSelectBuilder()
sb.Select(selectFields...)
sb.From(table)
sb.Where(sb.In(idField, itemIds...))
sqlQuery, args := sb.Build()
ctx.LogDebug("module=PositionReviseSort\tfn=loadItemFeatureFromHolo\tquery:" + sqlQuery)
ctx.LogDebug(fmt.Sprintf("args: %v", args))
sort.Strings(selectFields)
cols := strings.Join(selectFields, ",")
hash := crc32.ChecksumIEEE([]byte(cols))
tableKey := fmt.Sprintf("%s_%d_%d", table, len(selectFields), hash)
numItems := len(itemIds)
p.feaMu.RLock()
feaStmtMap := p.feaStmtMap[tableKey]
feaStmt := feaStmtMap[numItems]
p.feaMu.RUnlock()
if feaStmt == nil {
p.feaMu.Lock()
if feaStmtMap == nil {
feaStmtMap = p.feaStmtMap[tableKey]
if feaStmtMap == nil {
feaStmtMap = make(map[int]*sql.Stmt)
p.feaStmtMap[tableKey] = feaStmtMap
}
}
feaStmt = feaStmtMap[numItems]
if feaStmt == nil {
if stmt, err := p.db.Prepare(sqlQuery); err != nil {
ctx.LogError(fmt.Sprintf("model=PositionReviseSort\tfn=loadItemFeatureFromHolo\terr=%v", err))
p.feaMu.Unlock()
return
} else {
feaStmt = stmt
feaStmtMap[numItems] = stmt
}
}
p.feaMu.Unlock()
}
cntx, cancel := gocontext.WithTimeout(gocontext.Background(), 200*time.Millisecond)
defer cancel()
rows, err := feaStmt.QueryContext(cntx, args...)
if err != nil {
if errors.Is(err, gocontext.DeadlineExceeded) {
log.Warning("module=PositionReviseSort\tevent=loadItemFeatureFromHolo\ttimeout=200")
return
}
ctx.LogError(fmt.Sprintf("module=PositionReviseSort\terror=hologres error(%v)", err))
return
}
defer rows.Close()
columns, err := rows.ColumnTypes()
if err != nil {
ctx.LogError(fmt.Sprintf("module=PositionReviseSort\terror=hologres error(%v)", err))
return
}
values := sqlutil.ColumnValues(columns)
selected := make(map[string]bool, 0)
for rows.Next() {
if err = rows.Scan(values...); err == nil {
features := make(map[string]interface{})
for i, column := range columns {
name := column.Name()
val := values[i]
switch v := val.(type) {
case *sql.NullString:
if v.Valid {
features[name] = v.String
}
case *sql.NullInt32:
if v.Valid {
features[name] = v.Int32
}
case *sql.NullInt64:
if v.Valid {
features[name] = v.Int64
}
case *sql.NullFloat64:
if v.Valid {
features[name] = v.Float64
}
case *sql.NullBool:
if v.Valid {
features[name] = v.Bool
}
case *sql.NullTime:
if v.Valid {
features[name] = v.Time
}
default:
}
}
if id, ok := features[idField]; ok {
delete(features, idField)
itemId := utils.ToString(id, "")
cacheKey := table + "_" + itemId
p.itemCache.Put(cacheKey, features)
if item, okay := itemMap[itemId]; okay {
item.AddProperties(features)
selected[itemId] = true
} else {
ctx.LogError(fmt.Sprintf("module=PositionReviseSort\tInvalid item id: %s", itemId))
}
} else {
ctx.LogError(fmt.Sprintf("module=PositionReviseSort\tevent=loadItemFeatureFromHolo\tNo item id found"))
}
} else {
ctx.LogError(fmt.Sprintf("module=PositionReviseSort\terror=hologres error(%v)", err))
}
}
// add nil to cache, prevent to loading from holo again and again
var emptyMap map[string]interface{}
for id := range itemMap {
if _, ok := selected[id]; !ok {
cacheKey := table + "_" + id
p.itemCache.Put(cacheKey, emptyMap)
}
}
ctx.LogDebug(fmt.Sprintf("module=PositionReviseSort\tevent=loadItemFeatureFromHolo\tload %d item features", len(selected)))
}
func getFilterFields(filterJson string) []string {
if filterJson == "" {
return nil
}
var conditions []Expression
err := json.Unmarshal([]byte(filterJson), &conditions)
if err != nil {
log.Error(fmt.Sprintf("module=loadFlowControlPlan\tUnmarshal '%s' failed. err=%v", filterJson, err))
return nil
}
fields := make([]string, 0, len(conditions))
for _, expr := range conditions {
fields = append(fields, expr.Field)
}
return fields
}
func (p *PositionReviseSort) loadFlowControlPlan(expId string) map[int]*PIDController {
// 调用 SDK 获取调控计划的元信息, 创建 FlowControllers
client := abtest.GetExperimentClient()
if client == nil {
log.Error("module=loadFlowControlPlan\tGetExperimentClient failed.")
return nil
}
runEnv := os.Getenv("PAIREC_ENVIRONMENT")
timePoint := p.config.TestTimestamp
plans := client.GetFlowCtrlPlanMetaList(runEnv, timePoint)
if len(plans) == 0 {
log.Info(fmt.Sprintf("module=loadFlowControlPlan\tcurrent timestamp=%d\tNo Flow Control Plan.",
timePoint))
return nil
}
var oldControllers map[int]*PIDController
p.clock.RLock()
if ctrls, ok := p.exp2controllers[expId]; ok {
oldControllers = ctrls
}
p.clock.RUnlock()
controllers := make(map[int]*PIDController)
for _, plan := range plans {
// load plan traffic scope conditions
scope := plan.FlowScopeFilterJson
var conditions []Expression
if scope != "" {
err := json.Unmarshal([]byte(scope), &conditions)
if err != nil {
log.Error(fmt.Sprintf("module=loadFlowControlPlan\tUnmarshal '%s' failed. err=%v", scope, err))
continue
}
}
for _, target := range plan.Targets {
if target.Status == "disable" {
continue
}
params := client.GetSceneParams(plan.SceneName)
freeze := params.GetInt(fmt.Sprintf("pid_freeze_target_%d_minutes", target.TargetId), 0)
run := params.GetString(fmt.Sprintf("pid_run_with_zero_input_%d", target.PlanId), "true")
runWithZeroInput := strings.ToLower(run) == "true"
matchRules := target.ItemScopeFilterJson
var matchConditions []Expression
if matchRules != "" {
err := json.Unmarshal([]byte(matchRules), &matchConditions)
if err != nil {
log.Error(fmt.Sprintf("module=loadFlowControlPlan\tUnmarshal '%s' failed. err=%v", matchRules, err))
}
}
if oldControllers != nil {
if c, ok := oldControllers[target.TargetId]; ok {
// update meta info
c.plan = plan
c.target = target
controllers[target.TargetId] = c
if conditions != nil {
c.SetConditions(conditions)
}
if matchConditions != nil {
c.SetMatchConditions(matchConditions)
}
c.GenScopeConditions()
c.SetFreezeMinutes(freeze)
c.SetRunWithZeroInput(runWithZeroInput)
continue
}
}
c := NewPIDController(plan, target, p.config, expId)
if c != nil {
if conditions != nil {
c.SetConditions(conditions)
}
if matchConditions != nil {
c.SetMatchConditions(matchConditions)
}
c.SetFreezeMinutes(freeze)
c.SetRunWithZeroInput(runWithZeroInput)
controllers[target.TargetId] = c
}
}
}
p.clock.Lock()
p.exp2controllers[expId] = controllers
p.clock.Unlock()
log.Info(fmt.Sprintf("module=loadFlowControlPlan\tcurrent timestamp=%d\tload %d Flow Control Plan for exp=%s.",
timePoint, len(controllers), expId))
return controllers
}
func loadTargetItemTraffic(ctx *context.RecommendContext, items []*module.Item, controllers map[int]*PIDController) map[int]map[string]float64 {
client := abtest.GetExperimentClient()
if client == nil {
ctx.LogError("module=loadTargetItemTraffic\tGetExperimentClient failed.")
return nil
}
var scene string
var good bool
s := ctx.GetParameter("scene")
if scene, good = s.(string); !good {
ctx.LogError("failed to get scene name")
return nil
}
itemIds := make([]string, len(items), len(items))
for i, item := range items {
itemIds[i] = string(item.Id)
}
plans := make(map[int]bool)
targets := make(map[int]bool)
for t, c := range controllers {
targets[t] = true
if c.plan.LoadTrafficByPlan {
plans[c.plan.PlanId] = true
}
}
// sdk 可能会返回已过期的Target下Item的历史流量,这样的话取最大值就是不对的
result := make(map[int]map[string]float64)
runEnv := os.Getenv("PAIREC_ENVIRONMENT")
traffics := client.GetFlowCtrlPlanTargetTraffic(runEnv, scene, itemIds...)
hasTraffic := false
var volume float64
for _, traffic := range traffics {
if !targets[traffic.TargetId] {
continue
}
if _, ok := plans[traffic.PlanId]; ok {
volume = traffic.PlanTraffic
} else {
volume = traffic.TargetTraffic
}
if volume <= 0 {
continue
}
hasTraffic = true
if dict, ok := result[traffic.TargetId]; ok {
dict[traffic.ItemOrExpId] = volume
} else {
dict = make(map[string]float64)
dict[traffic.ItemOrExpId] = volume
result[traffic.TargetId] = dict
}
}
if hasTraffic {
ctx.LogDebug(fmt.Sprintf("item traffic:%v", result))
return result
}
return nil
}
// FlowControl 非单品(整体)目标流量调控,返回各个目标的调控力度
func FlowControl(controllers map[int]*PIDController, ctx *context.RecommendContext) (map[int]float64, int) {
// 获取(granularity="whole")类型的调控目标当前已累计完成的流量
planOutput := make(map[int]float64)
if controllers == nil || len(controllers) == 0 {
return planOutput, 0
}
client := abtest.GetExperimentClient()
if client == nil {
ctx.LogError("module=FlowControl\tGetExperimentClient failed.")
return planOutput, 0
}
var scene string
var good bool
s := ctx.GetParameter("scene")
if scene, good = s.(string); !good {
ctx.LogError("failed to get scene name")
return planOutput, 0
}
// 获取流量实时统计值
runEnv := os.Getenv("PAIREC_ENVIRONMENT")
expId := ctx.ExperimentResult.GetExpId()
traffics := client.GetFlowCtrlPlanTargetTraffic(runEnv, scene, expId, "ER_ALL")
allTrafficDict := make(map[int]experiments.FlowCtrlPlanTargetTraffic)
expTrafficDict := make(map[int]experiments.FlowCtrlPlanTargetTraffic)
for _, traffic := range traffics {
if traffic.ItemOrExpId == "ER_ALL" {
allTrafficDict[traffic.TargetId] = traffic
} else {
expTrafficDict[traffic.TargetId] = traffic
}
}
hasTraffic := false
retCh := make(chan struct {
int
float64
}, utils.MinInt(len(controllers), 64))
defer close(retCh)
gctx, cancel := gocontext.WithTimeout(gocontext.Background(), time.Millisecond*12)
defer cancel()
for t, c := range controllers {
go func(gctx gocontext.Context, t int, c *PIDController) {
defer func() {
if err := recover(); err != nil {
//stack := string(debug.Stack())
log.Warning(fmt.Sprintf("flow control timeout in background: <%d/%d>%s",
c.plan.PlanId, t, c.target.TargetName))
}
}()
planId := c.plan.PlanId
var traffic, planTraffic, output, setpoint float64
var binId = ""
var dict map[int]experiments.FlowCtrlPlanTargetTraffic
if c.plan.TargetValueInPercentageFormat {
if c.IsAllocateExpWise() {
dict = expTrafficDict
binId = expId
} else {
dict = allTrafficDict
}
if input, ok := dict[t]; ok {
traffic = input.TargetTraffic
planTraffic = input.PlanTraffic
} else {
traffic = float64(0)
planTraffic = float64(1)
}
if c.IsAllocateExpWise() && traffic < c.GetMinExpTraffic() {
// 用全局流量代替冷启动的实验流量
ctx.LogDebug(fmt.Sprintf("module=PositionReviseSort\tplan <%d/%d>[%s]\texp=%s\ttraffic=%f,"+
"change to global traffic", planId, t, c.target.TargetName, expId, traffic))
binId = ""
if input, ok := allTrafficDict[t]; ok {
traffic = input.TargetTraffic
planTraffic = input.PlanTraffic
} else {
traffic = float64(0)
planTraffic = float64(1)
}
}
trafficPercentage := traffic / planTraffic
output, setpoint = c.DoWithId(trafficPercentage, binId)
ctx.LogInfo(fmt.Sprintf("module=PositionReviseSort\tplan <%d/%d>[%s]\ttraffic=%f,"+
"percentage=%f,setpoint=%f,output=%f,exp=%s",
planId, t, c.target.TargetName, traffic, trafficPercentage, setpoint, output, binId))
if traffic > 0 {
hasTraffic = true
}
} else {
if input, ok := allTrafficDict[t]; ok {
traffic = input.TargetTraffic
} else {
traffic = float64(0)
}
output, setpoint = c.Do(traffic)
ctx.LogInfo(fmt.Sprintf("module=PositionReviseSort\tplan <%d/%d>[%s]\ttraffic=%f,setpoint=%f,output=%f",
planId, t, c.target.TargetName, traffic, setpoint, output))
if traffic > 0 {
hasTraffic = true
}
}
select {
case <-gctx.Done():
ctx.LogWarning(fmt.Sprintf("pid controller timeout in goruntine: <%d/%d>[%s]",
planId, t, c.target.TargetName))
return
case retCh <- struct {
int
float64
}{t, output}:
}
}(gctx, t, c)
}
cnt := 0
Loop:
for range controllers {
select {
case pair := <-retCh:
output := pair.float64
if output != 0 {
cnt++
planOutput[pair.int] = output
}
case <-gctx.Done():
if errors.Is(gctx.Err(), gocontext.DeadlineExceeded) {
ctx.LogWarning(fmt.Sprintf("pid controller timeout: %v", gctx.Err()))
}
break Loop
}
}
if !hasTraffic {
for k := range planOutput {
delete(planOutput, k)
}
cnt = 0
}
return planOutput, cnt
}
func setHyperParams(controllers map[int]*PIDController, ctx *context.RecommendContext) bool {
if nil == controllers || len(controllers) == 0 {
return false
}
params := ctx.ExperimentResult.GetExperimentParams()
on := params.GetInt("pid_control_enable", 1)
if on == 0 {
return false
}
offPrefix := params.GetString("pid_off_target_name_prefix", "")
if offPrefix != "" {
for _, c := range controllers {
if strings.HasPrefix(c.target.TargetName, offPrefix) {
c.SetOnline(false)
}
}
}
onPrefix := params.GetString("pid_on_target_name_prefix", "")
if onPrefix != "" {
for _, c := range controllers {
if strings.HasPrefix(c.target.TargetName, onPrefix) {
c.SetOnline(true)
}
}
}
planParams := params.Get("pid_plan_params", nil)
if planParams != nil {
if values, ok := planParams.(map[string]interface{}); ok {
for pid, args := range values {
planId, err := strconv.Atoi(pid)
if err != nil {
log.Error(fmt.Sprintf("parse experiment params failed. err=%v", err))
continue
}
if dict, good := args.(map[string]interface{}); good {
if _on, exist := dict["online"]; exist {
for _, c := range controllers {
if c.plan.PlanId == planId {
c.SetOnline(_on.(bool))
}
}
}
}
}
}
}
hyperParams := params.Get("pid_params", nil)
if hyperParams == nil {
return true
}
if values, ok := hyperParams.(map[string]interface{}); ok {
hasDefaultValue := false
var defaultKp, defaultKi, defaultKd, defaultSampleTime, defaultErrDiscount float64
var defaultStartPageNo = 0
if args, exist := values["default"]; exist {
if dict, good := args.(map[string]interface{}); good {
hasDefaultValue = true
if _kp, okay := dict["kp"]; okay {
defaultKp = _kp.(float64)
}
if _ki, okay := dict["ki"]; okay {
defaultKi = _ki.(float64)
}
if _kd, okay := dict["kd"]; okay {
defaultKd = _kd.(float64)
}
if _t, okay := dict["sample_time"]; okay {
defaultSampleTime = _t.(float64)
}
if _d, okay := dict["err_discount"]; okay {
defaultErrDiscount = _d.(float64)
}
if _s, okay := dict["start_page_num"]; okay {
defaultStartPageNo = int(_s.(float64))
}
}
}
if hasDefaultValue {
for _, c := range controllers {
if _, okay := values[strconv.Itoa(c.target.TargetId)]; !okay {
if defaultKp != 0 {
c.SetParameters(float32(defaultKp), float32(defaultKi), float32(defaultKd))
}
c.SetStartPageNum(defaultStartPageNo)
c.SetSampleTime(float32(defaultSampleTime))
c.SetErrDiscount(defaultErrDiscount)
}
}
}
for pid, args := range values {
if pid == "default" {
continue
}
targetId, err := strconv.Atoi(pid)
if err != nil {
log.Error(fmt.Sprintf("parse experiment params failed. err=%v", err))
continue
}
if c, okay := controllers[targetId]; okay {
dict, good := args.(map[string]interface{})
if !good {
if hasDefaultValue {
c.SetParameters(float32(defaultKp), float32(defaultKi), float32(defaultKd))
}
continue
}
var kp, ki, kd, sampleTime float64
if _kp, exist := dict["kp"]; exist {
kp = _kp.(float64)
}
if _ki, exist := dict["ki"]; exist {
ki = _ki.(float64)
}
if _kd, exist := dict["kd"]; exist {
kd = _kd.(float64)
}
c.SetParameters(float32(kp), float32(ki), float32(kd))
if _sampleTime, exist := dict["sample_time"]; exist {