/
api_trials.go
1480 lines (1319 loc) · 45.6 KB
/
api_trials.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 internal
import (
"context"
"fmt"
"math"
"slices"
"sort"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/determined-ai/determined/master/internal/api"
"github.com/determined-ai/determined/master/internal/db"
expauth "github.com/determined-ai/determined/master/internal/experiment"
"github.com/determined-ai/determined/master/internal/grpcutil"
"github.com/determined-ai/determined/master/internal/sproto"
"github.com/determined-ai/determined/master/internal/task"
"github.com/determined-ai/determined/master/internal/trials"
"github.com/determined-ai/determined/master/pkg/actor"
"github.com/determined-ai/determined/master/pkg/model"
"github.com/determined-ai/determined/master/pkg/protoutils"
"github.com/determined-ai/determined/master/pkg/protoutils/protoconverter"
"github.com/determined-ai/determined/master/pkg/protoutils/protoless"
"github.com/determined-ai/determined/master/pkg/ptrs"
"github.com/determined-ai/determined/master/pkg/searcher"
"github.com/determined-ai/determined/proto/pkg/apiv1"
"github.com/determined-ai/determined/proto/pkg/checkpointv1"
"github.com/determined-ai/determined/proto/pkg/commonv1"
"github.com/determined-ai/determined/proto/pkg/experimentv1"
"github.com/determined-ai/determined/proto/pkg/trialv1"
)
const (
batches = "batches"
trialLogsBatchSize = 1000
trialProfilerMetricsBatchSize = 100
)
var (
trialLogsBatchMissWaitTime = time.Second
distinctFieldBatchWaitTime = 5 * time.Second
trialProfilerMetricsBatchMissWaitTime = 5 * time.Second
// TrialAvailableSeriesBatchWaitTime is exported to be changed by tests.
TrialAvailableSeriesBatchWaitTime = 15 * time.Second
)
// TrialLogBackend is an interface trial log backends, such as elastic or postgres,
// must support to provide the features surfaced in API. This is deprecated, note it
// no longer supports adding logs in favor of unified logs.
type TrialLogBackend interface {
TrialLogs(
trialID, limit int, filters []api.Filter, order apiv1.OrderBy, state interface{},
) ([]*model.TrialLog, interface{}, error)
TrialLogsCount(trialID int, filters []api.Filter) (int, error)
TrialLogsFields(trialID int) (*apiv1.TrialLogsFieldsResponse, error)
DeleteTrialLogs(trialIDs []int) error
}
// Catches information on active running trials.
type trialAllocation struct {
Pulling bool
Running bool
Starting bool
Task model.TaskID
}
func getLatestTaskIDFromTrialProto(t *trialv1.Trial) model.TaskID {
if len(t.TaskIds) == 0 {
panic(fmt.Sprintf("trial proto object %+v was without associated task", t))
}
return model.TaskID(t.TaskIds[len(t.TaskIds)-1])
}
func (a *apiServer) enrichTrialState(trials ...*trialv1.Trial) error {
// filter allocations by TaskIDs on this page of trials
taskFilter := make([]string, 0, len(trials))
for _, trial := range trials {
taskFilter = append(taskFilter, string(getLatestTaskIDFromTrialProto(trial)))
}
// get active trials by TaskId
tasks := []trialAllocation{}
err := a.m.db.Query(
"aggregate_allocation_state_by_task",
&tasks,
strings.Join(taskFilter, ","),
)
if err != nil {
return err
}
// Collect state information by TaskID
byTaskID := make(map[model.TaskID]trialv1.State, len(tasks))
for _, task := range tasks {
switch {
case task.Running:
byTaskID[task.Task] = trialv1.State_STATE_RUNNING
case task.Starting:
byTaskID[task.Task] = trialv1.State_STATE_STARTING
case task.Pulling:
byTaskID[task.Task] = trialv1.State_STATE_PULLING
default:
byTaskID[task.Task] = trialv1.State_STATE_QUEUED
}
}
// Active trials converted to Queued, Pulling, Starting, or Running
for _, trial := range trials {
if trial.State == trialv1.State_STATE_ACTIVE {
if setState, ok := byTaskID[getLatestTaskIDFromTrialProto(trial)]; ok {
trial.State = setState
} else {
trial.State = trialv1.State_STATE_QUEUED
}
}
}
return nil
}
func (a *apiServer) TrialLogs(
req *apiv1.TrialLogsRequest, resp apiv1.Determined_TrialLogsServer,
) error {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(resp.Context(), int(req.TrialId),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return err
}
trialTaskIDs, err := db.TrialTaskIDsByTrialID(resp.Context(), int(req.TrialId))
if err != nil {
return fmt.Errorf("retreiving task IDs for trial log: %w", err)
}
if len(trialTaskIDs) == 0 {
return fmt.Errorf("no task IDs associated with trial ID %d", req.TrialId)
}
var tasks []*model.Task
for _, t := range trialTaskIDs {
task, err := db.TaskByID(resp.Context(), t.TaskID)
if err != nil {
return fmt.Errorf("getting task version for trial logs for task ID %s: %w", t.TaskID, err)
}
tasks = append(tasks, task)
}
ctx, cancel := context.WithCancel(resp.Context())
defer cancel()
// First stream legacy logs.
if tasks[0].LogVersion == model.TaskLogVersion0 {
res := make(chan api.BatchResult, taskLogsChanBuffer)
go a.legacyTrialLogs(ctx, req, res)
if err := processBatches(res, func(b api.Batch) error {
return b.ForEach(func(i interface{}) error {
l, err := i.(*model.TrialLog).Proto()
if err != nil {
return err
}
return resp.Send(l)
})
}); err != nil {
return err
}
// Don't return here. Continue in case this task spanned the upgrade. If it did not,
// it will return quickly anyway.
}
for i, task := range tasks {
switch task.LogVersion {
case model.TaskLogVersion0, model.TaskLogVersion1:
// Translate the request.
res := make(chan api.BatchResult, taskLogsChanBuffer)
go a.taskLogs(ctx, &apiv1.TaskLogsRequest{
TaskId: string(task.TaskID),
Limit: req.Limit,
// Only follow on the final task log. We should at most only have
// one non terminal task per trial. But if this assumption is violated
// users will be prevented from seeing future logs on running tasks without this
// hack here.
Follow: req.Follow && i == len(trialTaskIDs)-1,
AllocationIds: nil,
AgentIds: req.AgentIds,
ContainerIds: req.ContainerIds,
RankIds: req.RankIds,
Levels: req.Levels,
Stdtypes: req.Stdtypes,
Sources: req.Sources,
TimestampBefore: req.TimestampBefore,
TimestampAfter: req.TimestampAfter,
OrderBy: req.OrderBy,
SearchText: req.SearchText,
}, res)
err := processBatches(res, func(b api.Batch) error {
return b.ForEach(func(i interface{}) error {
l, err := i.(*model.TaskLog).Proto()
if err != nil {
return err
}
return resp.Send(&apiv1.TrialLogsResponse{
Id: l.Id,
TrialId: req.TrialId,
Timestamp: l.Timestamp,
Message: l.Message, //nolint: staticcheck // l.Message is deprecated.
Level: l.Level,
AgentId: l.AgentId,
ContainerId: l.ContainerId,
RankId: l.RankId,
Log: &l.Log,
Source: l.Source,
Stdtype: l.Stdtype,
})
})
})
if err != nil {
return fmt.Errorf("getting trial logs for task ID %s: %w", task.TaskID, err)
}
default:
panic(fmt.Errorf("unknown task log version: %d, please report this bug", task.LogVersion))
}
}
return nil
}
func (a *apiServer) legacyTrialLogs(
ctx context.Context, req *apiv1.TrialLogsRequest, res chan api.BatchResult,
) {
if err := grpcutil.ValidateRequest(
grpcutil.ValidateLimit(req.Limit),
grpcutil.ValidateFollow(req.Limit, req.Follow),
); err != nil {
res <- api.ErrBatchResult(err)
return
}
filters, err := constructTrialLogsFilters(req)
if err != nil {
res <- api.ErrBatchResult(errors.Wrap(err, "unsupported filter"))
return
}
var followState interface{}
trialLogsTimeSinceLastAuth := time.Now() // time.Now() to avoid recheck from a.TrialLogs.
fetch := func(r api.BatchRequest) (api.Batch, error) {
if time.Now().Sub(trialLogsTimeSinceLastAuth) >= recheckAuthPeriod {
if err = trials.CanGetTrialsExperimentAndCheckCanDoAction(ctx, int(req.TrialId),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return nil, err
}
trialLogsTimeSinceLastAuth = time.Now()
}
switch {
case r.Follow, r.Limit > trialLogsBatchSize:
r.Limit = trialLogsBatchSize
case r.Limit <= 0:
return nil, nil
}
b, state, fErr := a.m.trialLogBackend.TrialLogs(
int(req.TrialId), r.Limit, filters, req.OrderBy, followState)
if fErr != nil {
return nil, fErr
}
followState = state
return model.TrialLogBatch(b), nil
}
total, err := a.m.trialLogBackend.TrialLogsCount(int(req.TrialId), filters)
if err != nil {
res <- api.ErrBatchResult(fmt.Errorf("failed to get trial count from backend: %w", err))
return
}
effectiveLimit := api.EffectiveLimit(int(req.Limit), 0, total)
api.NewBatchStreamProcessor(
api.BatchRequest{Limit: effectiveLimit, Follow: req.Follow},
fetch,
a.isTrialTerminalFunc(int(req.TrialId), a.m.taskLogBackend.MaxTerminationDelay()),
false,
nil,
&trialLogsBatchMissWaitTime,
).Run(ctx, res)
}
func constructTrialLogsFilters(req *apiv1.TrialLogsRequest) ([]api.Filter, error) {
var filters []api.Filter
addInFilter := func(field string, values interface{}, count int) {
if values != nil && count > 0 {
filters = append(filters, api.Filter{
Field: field,
Operation: api.FilterOperationIn,
Values: values,
})
}
}
addInFilter("agent_id", req.AgentIds, len(req.AgentIds))
addInFilter("container_id", req.ContainerIds, len(req.ContainerIds))
addInFilter("rank_id", req.RankIds, len(req.RankIds))
addInFilter("stdtype", req.Stdtypes, len(req.Stdtypes))
addInFilter("source", req.Sources, len(req.Sources))
addInFilter("level", func() interface{} {
var levels []string
for _, l := range req.Levels {
levels = append(levels, model.TaskLogLevelFromProto(l))
}
return levels
}(), len(req.Levels))
if req.TimestampBefore != nil {
if err := req.TimestampBefore.CheckValid(); err != nil {
return nil, err
}
filters = append(filters, api.Filter{
Field: "timestamp",
Operation: api.FilterOperationLessThanEqual,
Values: req.TimestampBefore.AsTime(),
})
}
if req.TimestampAfter != nil {
if err := req.TimestampAfter.CheckValid(); err != nil {
return nil, err
}
filters = append(filters, api.Filter{
Field: "timestamp",
Operation: api.FilterOperationGreaterThan,
Values: req.TimestampAfter.AsTime(),
})
}
return filters, nil
}
func (a *apiServer) TrialLogsFields(
req *apiv1.TrialLogsFieldsRequest, resp apiv1.Determined_TrialLogsFieldsServer,
) error {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(resp.Context(), int(req.TrialId),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return err
}
trialTaskIDs, err := db.TrialTaskIDsByTrialID(resp.Context(), int(req.TrialId))
if err != nil {
return fmt.Errorf("retreiving task IDs for trial log fields: %w", err)
}
ctx, cancel := context.WithCancel(resp.Context())
defer cancel()
// Stream fields from trial logs table, just to support pre-task-logs trials with old logs.
trialLogsTimeSinceLastAuth := time.Now() // time.Now() to avoid recheck from above.
resOld := make(chan api.BatchResult)
go api.NewBatchStreamProcessor(
api.BatchRequest{Follow: req.Follow},
func(lr api.BatchRequest) (api.Batch, error) {
if time.Now().Sub(trialLogsTimeSinceLastAuth) >= recheckAuthPeriod {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(resp.Context(),
int(req.TrialId),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return nil, err
}
trialLogsTimeSinceLastAuth = time.Now()
}
fields, err := a.m.trialLogBackend.TrialLogsFields(int(req.TrialId))
return api.ToBatchOfOne(fields), err
},
a.isTrialTerminalFunc(int(req.TrialId), a.m.taskLogBackend.MaxTerminationDelay()),
true,
&distinctFieldBatchWaitTime,
&distinctFieldBatchWaitTime,
).Run(ctx, resOld)
for i, trialTaskID := range trialTaskIDs {
// Also stream fields from task logs table, for ordinary logs (as they are written now).
taskLogsTimeSinceLastAuth := time.Now() // time.Now() to avoid recheck from above.
resNew := make(chan api.BatchResult)
go api.NewBatchStreamProcessor(
api.BatchRequest{Follow: req.Follow && i == len(trialTaskIDs)-1},
func(lr api.BatchRequest) (api.Batch, error) {
if time.Now().Sub(taskLogsTimeSinceLastAuth) >= recheckAuthPeriod {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(resp.Context(),
int(req.TrialId),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return nil, err
}
taskLogsTimeSinceLastAuth = time.Now()
}
fields, err := a.m.taskLogBackend.TaskLogsFields(trialTaskID.TaskID)
return api.ToBatchOfOne(&apiv1.TrialLogsFieldsResponse{
AgentIds: fields.AgentIds,
ContainerIds: fields.ContainerIds,
RankIds: fields.RankIds,
Stdtypes: fields.Stdtypes,
Sources: fields.Sources,
}), err
},
a.isTaskTerminalFunc(trialTaskID.TaskID, a.m.taskLogBackend.MaxTerminationDelay()),
true,
&distinctFieldBatchWaitTime,
&distinctFieldBatchWaitTime,
).Run(ctx, resNew)
// First iterate merge with legacy trial logs fields.
if i == 0 {
if err := zipBatches(resOld, resNew, func(b1, b2 api.Batch) error {
r1 := b1.(api.BatchOfOne).Inner.(*apiv1.TrialLogsFieldsResponse)
r2 := b2.(api.BatchOfOne).Inner.(*apiv1.TrialLogsFieldsResponse)
return resp.Send(&apiv1.TrialLogsFieldsResponse{
AgentIds: setString(append(r1.AgentIds, r2.AgentIds...)...),
ContainerIds: setString(append(r1.ContainerIds, r2.ContainerIds...)...),
RankIds: setInt32(append(r1.RankIds, r2.RankIds...)...),
Stdtypes: setString(append(r1.Stdtypes, r2.Stdtypes...)...),
Sources: setString(append(r1.Sources, r2.Sources...)...),
})
}); err != nil {
return fmt.Errorf("merging and sending trial log field batches for task id %s: %w",
trialTaskID.TaskID, err)
}
} else {
// Any past the first is always version 2 and above.
err := processBatches(resNew, func(b api.Batch) error {
return b.ForEach(func(i interface{}) error {
return resp.Send(i.(*apiv1.TrialLogsFieldsResponse))
})
})
if err != nil {
return fmt.Errorf("sending trial log field batches for task id %s: %w",
trialTaskID.TaskID, err)
}
}
}
return nil
}
func (a *apiServer) GetTrialCheckpoints(
ctx context.Context, req *apiv1.GetTrialCheckpointsRequest,
) (*apiv1.GetTrialCheckpointsResponse, error) {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(ctx, int(req.Id),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return nil, err
}
resp := &apiv1.GetTrialCheckpointsResponse{}
resp.Checkpoints = []*checkpointv1.Checkpoint{}
switch err := a.m.db.QueryProto("get_checkpoints_for_trial", &resp.Checkpoints, req.Id); {
case err == db.ErrNotFound:
return nil, status.Errorf(
codes.NotFound, "no checkpoints found for trial %d", req.Id)
case err != nil:
return nil,
errors.Wrapf(err, "error fetching checkpoints for trial %d from database", req.Id)
}
api.Where(&resp.Checkpoints, func(i int) bool {
v := resp.Checkpoints[i]
found := false
for _, state := range req.States {
if state == v.State {
found = true
break
}
}
if len(req.States) != 0 && !found {
return false
}
return true
})
sort.Slice(resp.Checkpoints, func(i, j int) bool {
ai, aj := resp.Checkpoints[i], resp.Checkpoints[j]
if req.OrderBy == apiv1.OrderBy_ORDER_BY_DESC {
aj, ai = ai, aj
}
switch req.GetSortBy().(type) {
case *apiv1.GetTrialCheckpointsRequest_SortByAttr:
switch req.GetSortByAttr() {
case checkpointv1.SortBy_SORT_BY_BATCH_NUMBER:
return protoless.CheckpointStepsCompletedLess(ai, aj)
case checkpointv1.SortBy_SORT_BY_UUID:
return ai.Uuid < aj.Uuid
case checkpointv1.SortBy_SORT_BY_TRIAL_ID:
return protoless.CheckpointTrialIDLess(ai, aj)
case checkpointv1.SortBy_SORT_BY_END_TIME:
return protoless.CheckpointReportTimeLess(ai, aj)
case checkpointv1.SortBy_SORT_BY_STATE:
return ai.State.Number() < aj.State.Number()
case checkpointv1.SortBy_SORT_BY_SEARCHER_METRIC:
return protoless.CheckpointSearcherMetricLess(ai, aj)
case checkpointv1.SortBy_SORT_BY_UNSPECIFIED:
fallthrough
default:
return protoless.CheckpointTrialIDLess(ai, aj)
}
case *apiv1.GetTrialCheckpointsRequest_SortByMetric:
return protoless.CheckpointMetricNameLess(ai, aj, req.GetSortByMetric())
default:
return protoless.CheckpointTrialIDLess(ai, aj)
}
})
return resp, api.Paginate(&resp.Pagination, &resp.Checkpoints, req.Offset, req.Limit)
}
func (a *apiServer) KillTrial(
ctx context.Context, req *apiv1.KillTrialRequest,
) (*apiv1.KillTrialResponse, error) {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(ctx, int(req.Id),
expauth.AuthZProvider.Get().CanEditExperiment); err != nil {
return nil, err
}
eID, rID, err := a.m.db.TrialExperimentAndRequestID(int(req.Id))
if err != nil {
return nil, err
}
exp := actor.Addr("experiments", eID)
s := patchTrialState{
requestID: rID,
state: model.StateWithReason{
State: model.StoppingKilledState,
InformationalReason: "user requested kill",
},
}
if err = a.ask(exp, s, nil); err != nil {
log.WithError(err).Error("error killing trial")
return nil, err
}
return &apiv1.KillTrialResponse{}, nil
}
func (a *apiServer) GetExperimentTrials(
ctx context.Context, req *apiv1.GetExperimentTrialsRequest,
) (resp *apiv1.GetExperimentTrialsResponse, err error) {
if _, _, err = a.getExperimentAndCheckCanDoActions(ctx, int(req.ExperimentId),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return nil, err
}
// Construct the trial filtering expression.
var allStates []string
for _, state := range req.States {
allStates = append(allStates, strings.TrimPrefix(state.String(), "STATE_"))
}
stateFilterExpr := strings.Join(allStates, ",")
// Construct the ordering expression.
orderColMap := map[apiv1.GetExperimentTrialsRequest_SortBy]string{
apiv1.GetExperimentTrialsRequest_SORT_BY_UNSPECIFIED: "id",
apiv1.GetExperimentTrialsRequest_SORT_BY_ID: "id",
apiv1.GetExperimentTrialsRequest_SORT_BY_START_TIME: "start_time",
apiv1.GetExperimentTrialsRequest_SORT_BY_END_TIME: "end_time",
apiv1.GetExperimentTrialsRequest_SORT_BY_STATE: "state",
apiv1.GetExperimentTrialsRequest_SORT_BY_BEST_VALIDATION_METRIC: "best_signed_search_metric",
apiv1.GetExperimentTrialsRequest_SORT_BY_LATEST_VALIDATION_METRIC: "latest_signed_search_metric",
apiv1.GetExperimentTrialsRequest_SORT_BY_BATCHES_PROCESSED: "total_batches_processed",
apiv1.GetExperimentTrialsRequest_SORT_BY_DURATION: "duration",
apiv1.GetExperimentTrialsRequest_SORT_BY_RESTARTS: "restarts",
apiv1.GetExperimentTrialsRequest_SORT_BY_CHECKPOINT_SIZE: "checkpoint_size",
}
sortByMap := map[apiv1.OrderBy]string{
apiv1.OrderBy_ORDER_BY_UNSPECIFIED: "ASC",
apiv1.OrderBy_ORDER_BY_ASC: "ASC",
apiv1.OrderBy_ORDER_BY_DESC: "DESC",
}
orderExpr := ""
switch _, ok := orderColMap[req.SortBy]; {
case !ok:
return nil, fmt.Errorf("unsupported sort by %s", req.SortBy)
case orderColMap[req.SortBy] != "id":
orderExpr = fmt.Sprintf(
"%s %s, id %s",
orderColMap[req.SortBy], sortByMap[req.OrderBy], sortByMap[req.OrderBy],
)
default:
orderExpr = fmt.Sprintf("id %s", sortByMap[req.OrderBy])
}
resp = &apiv1.GetExperimentTrialsResponse{}
if err = a.m.db.QueryProtof(
"proto_get_trial_ids_for_experiment",
[]interface{}{orderExpr},
resp,
req.ExperimentId,
stateFilterExpr,
req.Offset,
req.Limit,
); err != nil {
return nil, errors.Wrapf(err, "failed to get trial ids for experiment %d", req.ExperimentId)
} else if len(resp.Trials) == 0 {
return resp, nil
}
// Of the form "($1, $2), ($3, $4), ... ($N, $N+1)". Used in a VALUES expression in Postgres.
valuesExpr := make([]string, 0, len(resp.Trials))
trialIDsWithOrdering := make([]any, 0, len(resp.Trials))
trialIDs := make([]int32, 0, len(resp.Trials))
for i, trial := range resp.Trials {
valuesExpr = append(valuesExpr, fmt.Sprintf("($%d::int, $%d::int)", i*2+1, i*2+2))
trialIDsWithOrdering = append(trialIDsWithOrdering, trial.Id, i)
trialIDs = append(trialIDs, trial.Id)
}
switch err = a.m.db.QueryProtof(
"proto_get_trials_plus",
[]any{strings.Join(valuesExpr, ", ")},
&resp.Trials,
trialIDsWithOrdering...,
); {
case err == db.ErrNotFound:
return nil, status.Errorf(codes.NotFound, "trials %v not found:", trialIDs)
case err != nil:
return nil, errors.Wrapf(err, "failed to get trials detail for experiment %d", req.ExperimentId)
}
if err = a.enrichTrialState(resp.Trials...); err != nil {
return nil, err
}
return resp, nil
}
func (a *apiServer) GetTrial(ctx context.Context, req *apiv1.GetTrialRequest) (
*apiv1.GetTrialResponse, error,
) {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(ctx, int(req.TrialId),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return nil, err
}
resp := &apiv1.GetTrialResponse{Trial: &trialv1.Trial{}}
if err := a.m.db.QueryProtof(
"proto_get_trials_plus",
[]any{"($1::int, $2::int)"},
resp.Trial,
req.TrialId,
1,
); err != nil {
return nil, errors.Wrapf(err, "failed to get trial %d", req.TrialId)
}
if resp.Trial.State == trialv1.State_STATE_ACTIVE {
if err := a.enrichTrialState(resp.Trial); err != nil {
return nil, err
}
}
return resp, nil
}
func (a *apiServer) formatMetrics(
m *apiv1.DownsampledMetrics, metricMeasurements []db.MetricMeasurements,
) error {
for _, in := range metricMeasurements {
valueMap, err := structpb.NewStruct(in.Values) // in.Value is a map.
if err != nil {
return errors.Wrapf(err, "error formatting metrics")
}
out := apiv1.DataPoint{
Time: timestamppb.New(in.Time),
Batches: int32(in.Batches),
Values: valueMap,
Epoch: in.Epoch,
}
m.Data = append(m.Data, &out)
}
return nil
}
func (a *apiServer) parseMetricGroupArgs(
legacyType apiv1.MetricType, newType model.MetricGroup,
) (model.MetricGroup, error) {
if legacyType != apiv1.MetricType_METRIC_TYPE_UNSPECIFIED && newType != "" {
return "", status.Errorf(codes.InvalidArgument, "cannot specify both legacy and new metric group")
}
if newType != "" {
return newType, nil
}
conv := &protoconverter.ProtoConverter{}
convertedLegacyType := conv.ToMetricGroup(legacyType)
if cErr := conv.Error(); cErr != nil {
return "", status.Errorf(codes.InvalidArgument, "converting metric group: %s", cErr)
}
return convertedLegacyType, nil
}
func (a *apiServer) multiTrialSample(trialID int32, metricNames []string,
metricGroup model.MetricGroup, maxDatapoints int, startBatches int,
endBatches int, timeSeriesFilter *commonv1.PolymorphicFilter,
metricIds []string,
) ([]*apiv1.DownsampledMetrics, error) {
var startTime time.Time
var metrics []*apiv1.DownsampledMetrics
// For now "epoch" is the only custom xAxis metric label supported so we
// build the `MetricSeriesEpoch` array. In the future this logic should
// be updated to support any number of xAxis metric options
xAxisLabelMetrics := []string{"epoch"}
if err := db.ValidatePolymorphicFilter(timeSeriesFilter); err != nil {
return nil, err
}
if len(metricNames) > 0 && len(metricIds) > 0 {
return nil, fmt.Errorf(`error fetching time series of metrics cannot specify
both metric ids and metric names`)
}
if endBatches == 0 {
endBatches = math.MaxInt32
}
if maxDatapoints == 0 {
maxDatapoints = 200
}
var timeSeriesColumn *string
// If no time series filter column name is supplied then default to batches.
defaultTimeSeriesColumn := batches
if timeSeriesFilter == nil || timeSeriesFilter.Name == nil {
timeSeriesColumn = &defaultTimeSeriesColumn
} else {
timeSeriesColumn = timeSeriesFilter.Name
}
metricGroupToNames := make(map[model.MetricGroup][]string)
if len(metricNames) > 0 {
if metricGroup == "" {
// to keep backwards compatibility.
metricGroupToNames[model.TrainingMetricGroup] = metricNames
metricGroupToNames[model.ValidationMetricGroup] = metricNames
} else {
metricGroupToNames[metricGroup] = metricNames
}
}
for _, metricIDStr := range metricIds {
metricID, err := model.DeserializeMetricIdentifier(metricIDStr)
if err != nil {
return nil, errors.Wrapf(err, "error parsing metric id %s", metricIDStr)
}
metricGroupToNames[metricID.Group] = append(metricGroupToNames[metricID.Group],
string(metricID.Name))
}
getDownSampledMetric := func(aMetricNames []string, aMetricGroup model.MetricGroup,
) (*apiv1.DownsampledMetrics, error) {
var metric apiv1.DownsampledMetrics
metricMeasurements, err := trials.MetricsTimeSeries(
trialID, startTime, aMetricNames, startBatches, endBatches,
xAxisLabelMetrics,
maxDatapoints, *timeSeriesColumn, timeSeriesFilter, aMetricGroup)
if err != nil {
return nil, errors.Wrapf(err, fmt.Sprintf("error fetching time series of %s metrics",
aMetricGroup))
}
//nolint:staticcheck // SA1019: backward compatibility
metric.Type = aMetricGroup.ToProto()
metric.Group = aMetricGroup.ToString()
if len(metricMeasurements) > 0 {
if err = a.formatMetrics(&metric, metricMeasurements); err != nil {
return nil, err
}
return &metric, nil
}
return nil, nil
}
metricGroups := make([]model.MetricGroup, 0, len(metricGroupToNames))
for metricGroup := range metricGroupToNames {
metricGroups = append(metricGroups, metricGroup)
}
sort.Slice(metricGroups, func(i, j int) bool {
return metricGroups[i] < metricGroups[j]
})
for _, mGroup := range metricGroups {
metricNames := metricGroupToNames[mGroup]
metric, err := getDownSampledMetric(metricNames, mGroup)
if err != nil {
return nil, err
}
if metric != nil {
metrics = append(metrics, metric)
}
}
return metrics, nil
}
func (a *apiServer) CompareTrials(ctx context.Context,
req *apiv1.CompareTrialsRequest,
) (*apiv1.CompareTrialsResponse, error) {
trialsList := make([]*apiv1.ComparableTrial, 0, len(req.TrialIds))
for _, trialID := range req.TrialIds {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(ctx, int(trialID),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return nil, err
}
container := &apiv1.ComparableTrial{Trial: &trialv1.Trial{}}
switch err := a.m.db.QueryProto("get_trial_basic", container.Trial, trialID); {
case err == db.ErrNotFound:
return nil, status.Errorf(codes.NotFound, "trial %d not found:", trialID)
case err != nil:
return nil, errors.Wrapf(err, "failed to get trial %d", trialID)
}
//nolint:staticcheck // SA1019: backward compatibility
metricGroup, err := a.parseMetricGroupArgs(req.MetricType, model.MetricGroup(req.Group))
if err != nil {
return nil, err
}
tsample, err := a.multiTrialSample(trialID, req.MetricNames, metricGroup,
int(req.MaxDatapoints), int(req.StartBatches), int(req.EndBatches),
req.TimeSeriesFilter, req.MetricIds)
if err != nil {
return nil, errors.Wrapf(err, "failed sampling")
}
container.Metrics = tsample
trialsList = append(trialsList, container)
}
return &apiv1.CompareTrialsResponse{Trials: trialsList}, nil
}
func (a *apiServer) GetMetrics(
req *apiv1.GetMetricsRequest, resp apiv1.Determined_GetMetricsServer,
) error {
sendFunc := func(m []*trialv1.MetricsReport) error {
return resp.Send(&apiv1.GetMetricsResponse{Metrics: m})
}
if err := a.streamMetrics(resp.Context(), req.TrialIds, sendFunc,
model.MetricGroup(req.Group)); err != nil {
return err
}
return nil
}
func (a *apiServer) GetTrainingMetrics(
req *apiv1.GetTrainingMetricsRequest, resp apiv1.Determined_GetTrainingMetricsServer,
) error {
sendFunc := func(m []*trialv1.MetricsReport) error {
return resp.Send(&apiv1.GetTrainingMetricsResponse{Metrics: m})
}
if err := a.streamMetrics(resp.Context(), req.TrialIds, sendFunc,
model.TrainingMetricGroup); err != nil {
return err
}
return nil
}
func (a *apiServer) GetValidationMetrics(
req *apiv1.GetValidationMetricsRequest, resp apiv1.Determined_GetValidationMetricsServer,
) error {
sendFunc := func(m []*trialv1.MetricsReport) error {
return resp.Send(&apiv1.GetValidationMetricsResponse{Metrics: m})
}
if err := a.streamMetrics(resp.Context(), req.TrialIds, sendFunc,
model.ValidationMetricGroup); err != nil {
return err
}
return nil
}
func (a *apiServer) streamMetrics(ctx context.Context,
trialIDs []int32, sendFunc func(m []*trialv1.MetricsReport) error, metricGroup model.MetricGroup,
) error {
if len(trialIDs) == 0 {
return status.Error(codes.InvalidArgument, "must specify at least one trialId")
}
ids := make(map[int32]bool)
for _, id := range trialIDs {
if ids[id] {
return status.Errorf(codes.InvalidArgument, "duplicate id=%d specified", id)
}
}
slices.Sort(trialIDs)
for _, trialID := range trialIDs {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(ctx, int(trialID),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return err
}
}
const size = 1000
trialIDIndex := 0
key := -1
mGroup := metricGroup.ToString()
for {
res, err := db.GetMetrics(ctx, int(trialIDs[trialIDIndex]), key, size, &mGroup)
if err != nil {
return err
}
if len(res) > 0 {
if err := ctx.Err(); err != nil {
return err
}
if err := sendFunc(res); err != nil {
return err
}
key = int(res[len(res)-1].TotalBatches)
}
if len(res) != size {
trialIDIndex++
if trialIDIndex >= len(trialIDs) {
break
}
key = -1
}
}
return nil
}
func (a *apiServer) GetTrialWorkloads(ctx context.Context, req *apiv1.GetTrialWorkloadsRequest) (
*apiv1.GetTrialWorkloadsResponse, error,
) {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(ctx, int(req.TrialId),
expauth.AuthZProvider.Get().CanGetExperimentArtifacts); err != nil {
return nil, err
}
resp := &apiv1.GetTrialWorkloadsResponse{}
limit := &req.Limit
if *limit == 0 {
limit = ptrs.Ptr[int32](-1)
}
sortCode := "total_batches"
if req.SortKey != "" && req.SortKey != batches {
sortCode = fmt.Sprintf("sort_metrics->'avg_metrics'->>'%s'",
strings.ReplaceAll(req.SortKey, "'", ""))
}
switch err := a.m.db.QueryProtof(
"proto_get_trial_workloads",
[]interface{}{
sortCode,
db.OrderByToSQL(req.OrderBy),
db.OrderByToSQL(req.OrderBy),
db.OrderByToSQL(req.OrderBy),
},
resp,
req.TrialId,
req.Offset,
limit,
req.Filter.String(),
req.IncludeBatchMetrics,
//nolint:staticcheck // SA1019: backward compatibility
req.MetricType.String(),
req.RemoveDeletedCheckpoints,
); {
case err == db.ErrNotFound:
return nil, status.Errorf(codes.NotFound, "trial %d workloads not found:", req.TrialId)
case err != nil:
return nil, errors.Wrapf(err, "failed to get trial %d workloads", req.TrialId)
}
return resp, nil
}
func (a *apiServer) GetTrialProfilerMetrics(
req *apiv1.GetTrialProfilerMetricsRequest,
resp apiv1.Determined_GetTrialProfilerMetricsServer,
) error {
labelsJSON, err := protojson.Marshal(req.Labels)
if err != nil {
return fmt.Errorf("failed to marshal labels: %w", err)
}
var timeSinceLastAuth time.Time
fetch := func(lr api.BatchRequest) (api.Batch, error) {
if time.Now().Sub(timeSinceLastAuth) >= recheckAuthPeriod {
if err := trials.CanGetTrialsExperimentAndCheckCanDoAction(resp.Context(),