forked from tensorflow/serving
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_manager_test.cc
More file actions
1556 lines (1389 loc) · 63 KB
/
Copy pathbasic_manager_test.cc
File metadata and controls
1556 lines (1389 loc) · 63 KB
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 2016 Google Inc. All Rights Reserved.
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.
==============================================================================*/
#include "tensorflow_serving/core/basic_manager.h"
#include <algorithm>
#include <functional>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/core/lib/core/blocking_counter.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow_serving/core/servable_state_monitor.h"
#include "tensorflow_serving/core/test_util/availability_test_util.h"
#include "tensorflow_serving/core/test_util/fake_loader.h"
#include "tensorflow_serving/core/test_util/manager_test_util.h"
#include "tensorflow_serving/core/test_util/mock_loader.h"
#include "tensorflow_serving/util/any_ptr.h"
#include "tensorflow_serving/util/event_bus.h"
#include "tensorflow_serving/util/threadpool_executor.h"
namespace tensorflow {
namespace serving {
namespace {
using ::testing::_;
using ::testing::AnyOf;
using ::testing::HasSubstr;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::InvokeWithoutArgs;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::UnorderedElementsAre;
using ::testing::UnorderedElementsAreArray;
using test_util::FakeLoader;
using test_util::WaitUntilServableManagerStateIsOneOf;
constexpr char kServableName[] = "kServableName";
constexpr char kServableName2[] = "kServableName2";
constexpr char kServableName3[] = "kServableName3";
constexpr int kNumVersionsPerServable = 2;
constexpr int kNumThreads = 10;
MATCHER_P(EqualsServableState, servable_state, servable_state.DebugString()) {
if (arg == servable_state) {
return true;
}
*result_listener << arg.DebugString();
return false;
}
// Creates a ServableData around a FakeLoader.
ServableData<std::unique_ptr<Loader>> CreateServable(
const ServableId& id, const Status load_status = Status::OK()) {
std::unique_ptr<Loader> loader(new FakeLoader(id.version, load_status));
return CreateServableData(id, std::move(loader));
}
// We parameterize this test with the number of load & unload threads. (Zero
// means use an in-line executor instead of a thread pool.)
struct ThreadPoolSizes {
uint64 num_load_threads;
uint64 num_unload_threads;
};
class BasicManagerTest : public ::testing::TestWithParam<ThreadPoolSizes> {
protected:
BasicManagerTest()
: thread_pool_sizes_(GetParam()),
servable_event_bus_(EventBus<ServableState>::CreateEventBus()),
servable_state_monitor_(servable_event_bus_.get()) {
BasicManager::Options options;
options.num_load_threads = thread_pool_sizes_.num_load_threads;
options.num_unload_threads = thread_pool_sizes_.num_unload_threads;
options.servable_event_bus = servable_event_bus_.get();
options.max_num_load_retries = 10;
options.load_retry_interval_micros = 0;
TF_CHECK_OK(BasicManager::Create(std::move(options), &basic_manager_));
}
void SetUp() override {
// We load the manager with two different servable streams, each with two
// versions 0 and 1.
std::set<ServableId> loaded_servables;
for (const char* servable_name : {kServableName, kServableName2}) {
for (int i = 1; i <= kNumVersionsPerServable; ++i) {
const ServableId id = {servable_name, i};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
loaded_servables.insert(id);
}
}
for (const ServableId& loaded_servable : loaded_servables) {
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, loaded_servable,
{ServableState::ManagerState::kAvailable});
}
}
ThreadPoolSizes thread_pool_sizes_;
std::shared_ptr<EventBus<ServableState>> servable_event_bus_;
ServableStateMonitor servable_state_monitor_;
std::unique_ptr<BasicManager> basic_manager_;
};
INSTANTIATE_TEST_CASE_P(
WithOrWithoutThreadPools, BasicManagerTest,
::testing::Values(
ThreadPoolSizes{0, 0} /* without load or unload threadpools */,
ThreadPoolSizes{2, 0} /* with just a load threadpool */,
ThreadPoolSizes{0, 2} /* with just an unload threadpool */,
ThreadPoolSizes{4, 4} /* with load and unload threadpools */));
TEST_P(BasicManagerTest, ServableHandleNotFoundMissingLoaderName) {
ServableHandle<int64> handle;
const Status status = basic_manager_->GetServableHandle(
ServableRequest::Latest(strings::StrCat(kServableName, "missing")),
&handle);
ASSERT_FALSE(status.ok()) << status;
EXPECT_EQ(error::NOT_FOUND, status.code());
}
TEST_P(BasicManagerTest, ServableHandleNotFoundMissingVersion) {
// This version is missing.
const int64 missing_version = 100;
ServableHandle<int64> handle;
const Status status = basic_manager_->GetServableHandle(
ServableRequest::Specific(kServableName, missing_version), &handle);
ASSERT_FALSE(status.ok()) << status;
EXPECT_EQ(error::NOT_FOUND, status.code());
}
TEST_P(BasicManagerTest, ServableHandleLatest) {
const ServableId id = {kServableName, kNumVersionsPerServable + 1};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kAvailable});
ServableHandle<int64> handle;
const Status status = basic_manager_->GetServableHandle(
ServableRequest::Latest(kServableName), &handle);
TF_ASSERT_OK(status);
EXPECT_EQ(kNumVersionsPerServable + 1, *handle);
}
TEST_P(BasicManagerTest, AlreadyManagedError) {
const ServableId id = {"banana", 42};
TF_ASSERT_OK(basic_manager_->ManageServable(CreateServable(id)));
EXPECT_FALSE(basic_manager_->ManageServable(CreateServable(id)).ok());
}
// Tests the case where the latest version of a servable available is 0.
TEST_P(BasicManagerTest, ServableHandleLatestVersionIsZero) {
const ServableId id = {kServableName3, 1};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kAvailable});
ServableHandle<int64> handle;
const Status status = basic_manager_->GetServableHandle(
ServableRequest::Latest(kServableName3), &handle);
TF_ASSERT_OK(status);
EXPECT_EQ(1, *handle);
EXPECT_EQ(id, handle.id());
}
TEST_P(BasicManagerTest, StopManagingUnknownId) {
const ServableId id = {kServableName3, 1};
EXPECT_FALSE(basic_manager_->StopManagingServable(id).ok());
}
TEST_P(BasicManagerTest, StopManagingActiveServable) {
const ServableId id = {kServableName3, 1};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_EXPECT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kAvailable});
EXPECT_FALSE(basic_manager_->StopManagingServable(id).ok());
}
TEST_P(BasicManagerTest, StopManagingDisabledServable) {
const ServableId id = {kServableName3, 1};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_EXPECT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kAvailable});
basic_manager_->UnloadServable(
id, [](const Status& status) { TF_EXPECT_OK(status); });
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_, id,
{ServableState::ManagerState::kEnd});
const optional<ServableStateSnapshot<>> snapshot =
basic_manager_->GetManagedServableStateSnapshot(id);
EXPECT_EQ(LoaderHarness::State::kDisabled, snapshot->state);
const ServableState expected_state = {id, ServableState::ManagerState::kEnd,
Status::OK()};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(expected_state));
TF_ASSERT_OK(basic_manager_->StopManagingServable(id));
EXPECT_FALSE(basic_manager_->GetManagedServableStateSnapshot(id));
}
TEST_P(BasicManagerTest, DontStopManagingOnError) {
const ServableId id = {kServableName, 7};
const Status error_status = errors::Internal("An error.");
std::unique_ptr<Loader> loader(new FakeLoader(7, error_status));
basic_manager_->ManageServable({id, std::move(loader)});
basic_manager_->LoadServable(id, [error_status](const Status& status) {
EXPECT_EQ(error_status, status);
});
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_, id,
{ServableState::ManagerState::kEnd});
const optional<ServableStateSnapshot<>> snapshot =
basic_manager_->GetManagedServableStateSnapshot(id);
EXPECT_EQ(LoaderHarness::State::kError, snapshot->state);
const ServableState expected_error_state = {
id, ServableState::ManagerState::kEnd, error_status};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(expected_error_state));
}
TEST_P(BasicManagerTest, ServableHandleSpecificVersion) {
ServableHandle<int64> handle;
const ServableId id = {kServableName2, 1};
const Status status =
basic_manager_->GetServableHandle(ServableRequest::FromId(id), &handle);
TF_ASSERT_OK(status);
EXPECT_EQ(1, *handle);
EXPECT_EQ(id, handle.id());
}
// Tests an edge-case when the serving map is updated and the last version of a
// stream is not in kReady state.
TEST_P(BasicManagerTest, UpdateServingMapServableHandleLatest) {
// Using kServableName3 which doesn't have any servables loaded in the
// manager, as opposed to kServableName which already has 2 loaded.
const ServableId id0 = {kServableName3, 0};
// Servable is int64 with value 0.
basic_manager_->ManageServable(CreateServable(id0));
basic_manager_->LoadServable(
id0, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id0, {ServableState::ManagerState::kAvailable});
test_util::MockLoader* notify_to_unload = new NiceMock<test_util::MockLoader>;
// Don't make it const otherwise servable types will mismatch: const int64 vs
// int64.
int64 servable = 1;
ON_CALL(*notify_to_unload, servable())
.WillByDefault(Return(AnyPtr(&servable)));
ON_CALL(*notify_to_unload, EstimateResources(_))
.WillByDefault(Return(Status::OK()));
ON_CALL(*notify_to_unload, Load()).WillByDefault(Return(Status::OK()));
const ServableId id1 = {kServableName3, 1};
basic_manager_->ManageServable(
{id1, std::unique_ptr<Loader>(notify_to_unload)});
basic_manager_->LoadServable(
id1, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id1, {ServableState::ManagerState::kAvailable});
// We have loaded both versions 0 and 1 of kServableName3, so the latest
// handle should be that of v1.
{
ServableHandle<int64> handle;
const Status status = basic_manager_->GetServableHandle(
ServableRequest::Latest(kServableName3), &handle);
TF_ASSERT_OK(status);
EXPECT_EQ(id1, handle.id());
}
// We will now try to unload v1, but we only allow it to move out from kReady
// state, and not complete the unload. Also, after it moves out from kReady,
// the serving map is also updated, so v0 would be the latest.
Notification unload_started;
Notification finish_unload;
EXPECT_CALL(*notify_to_unload, Unload()).WillOnce(Invoke([&]() {
unload_started.Notify();
finish_unload.WaitForNotification();
}));
Notification unload_finished;
std::unique_ptr<Thread> unload_last_servable(
Env::Default()->StartThread({}, "UnloadLastServable", [&]() {
basic_manager_->UnloadServable(id1, [&](const Status& status) {
TF_EXPECT_OK(status);
unload_finished.Notify();
});
}));
unload_started.WaitForNotification();
// Servable map should just have {kServableName3, 0} at this point.
{
ServableHandle<int64> handle;
const Status status = basic_manager_->GetServableHandle(
ServableRequest::Latest(kServableName3), &handle);
TF_EXPECT_OK(status);
EXPECT_EQ(id0, handle.id());
}
finish_unload.Notify();
// We have to ensure that the unload has finished completely, otherwise the
// address of the notifications could be invalid in the load when we exit from
// this scope.
unload_finished.WaitForNotification();
}
TEST_P(BasicManagerTest, ListAvailableServableIds) {
const std::vector<ServableId> expected_before = {{kServableName, 1},
{kServableName, 2},
{kServableName2, 1},
{kServableName2, 2}};
EXPECT_THAT(basic_manager_->ListAvailableServableIds(),
UnorderedElementsAreArray(expected_before));
// Set stream kServableName to have servables 7 and unload 0 & 1, but 7 errors
// on load, so never moves to a loaded state.
const ServableId id = {kServableName, 7};
std::unique_ptr<Loader> loader(
new FakeLoader(7, errors::Internal("An error.")));
basic_manager_->ManageServable(CreateServableData(id, std::move(loader)));
basic_manager_->LoadServable(id, [](const Status& status) {
EXPECT_EQ(errors::Internal("An error."), status);
});
basic_manager_->UnloadServable(
{kServableName, 1}, [](const Status& status) { TF_ASSERT_OK(status); });
basic_manager_->UnloadServable(
{kServableName, 2}, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_, id,
{ServableState::ManagerState::kEnd});
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_,
{kServableName, 1},
{ServableState::ManagerState::kEnd});
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_,
{kServableName, 2},
{ServableState::ManagerState::kEnd});
const std::vector<ServableId> expected_after = {{kServableName2, 1},
{kServableName2, 2}};
EXPECT_THAT(basic_manager_->ListAvailableServableIds(),
UnorderedElementsAreArray(expected_after));
}
TEST_P(BasicManagerTest, GetAvailableServableHandles) {
// Scoped to destruct handles at the end of it.
{
const std::map<ServableId, ServableHandle<int64>> handles_before =
basic_manager_->GetAvailableServableHandles<int64>();
ASSERT_EQ(kNumVersionsPerServable * 2, handles_before.size());
const std::vector<ServableId> expected_ids_before = {{kServableName, 1},
{kServableName, 2},
{kServableName2, 1},
{kServableName2, 2}};
for (const ServableId& expected_id : expected_ids_before) {
const auto found_it = handles_before.find(expected_id);
ASSERT_TRUE(found_it != handles_before.end());
EXPECT_EQ(expected_id.version, *found_it->second);
}
}
// Set stream kServableName to have servables 7 and unload 0 & 1, but 7 errors
// on load, so never moves to a loaded state.
const ServableId id = {kServableName, 7};
std::unique_ptr<Loader> loader(
new FakeLoader(7, errors::Internal("An error.")));
basic_manager_->ManageServable(CreateServableData(id, std::move(loader)));
basic_manager_->LoadServable(id, [](const Status& status) {
EXPECT_EQ(errors::Internal("An error."), status);
});
basic_manager_->UnloadServable(
{kServableName, 1}, [](const Status& status) { TF_ASSERT_OK(status); });
basic_manager_->UnloadServable(
{kServableName, 2}, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_, id,
{ServableState::ManagerState::kEnd});
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_,
{kServableName, 1},
{ServableState::ManagerState::kEnd});
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_,
{kServableName, 2},
{ServableState::ManagerState::kEnd});
{
const std::map<ServableId, ServableHandle<int64>> handles_after =
basic_manager_->GetAvailableServableHandles<int64>();
ASSERT_EQ(kNumVersionsPerServable, handles_after.size());
const std::vector<ServableId> expected_ids_after = {{kServableName2, 1},
{kServableName2, 2}};
for (const ServableId& expected_id : expected_ids_after) {
const auto found_it = handles_after.find(expected_id);
ASSERT_TRUE(found_it != handles_after.end());
EXPECT_EQ(expected_id.version, *found_it->second);
}
}
}
TEST_P(BasicManagerTest, GetAvailableServableHandlesWrongType) {
const std::map<ServableId, ServableHandle<int>> wrong_type_handles =
basic_manager_->GetAvailableServableHandles<int>();
EXPECT_EQ(0, wrong_type_handles.size());
}
TEST_P(BasicManagerTest, GetManagedServableNames) {
EXPECT_THAT(basic_manager_->GetManagedServableNames(),
UnorderedElementsAre(kServableName, kServableName2));
}
TEST_P(BasicManagerTest,
GetManagedServableStateSnapshotWithoutAdditionalState) {
const std::vector<ServableStateSnapshot<>> expected = {
{{kServableName, 1}, LoaderHarness::State::kReady, {}},
{{kServableName, 2}, LoaderHarness::State::kReady, {}}};
EXPECT_THAT(basic_manager_->GetManagedServableStateSnapshots(kServableName),
UnorderedElementsAreArray(expected));
}
TEST_P(BasicManagerTest, GetManagedServableStateSnapshot) {
// Check servable state snapshot corresponding to a servable-id that is in
// ready state.
const ServableId id_ready = {kServableName, 1};
const optional<ServableStateSnapshot<>> actual_ready_snapshot =
basic_manager_->GetManagedServableStateSnapshot(id_ready);
EXPECT_TRUE(actual_ready_snapshot);
const ServableStateSnapshot<> expected_ready_snapshot = {
id_ready, LoaderHarness::State::kReady, {}};
EXPECT_EQ(actual_ready_snapshot, expected_ready_snapshot);
// Check servable state snapshot corresponding to a servable-id that is not
// managed by the basic-manager.
const ServableId id_notmanaged = {kServableName, 8};
EXPECT_FALSE(basic_manager_->GetManagedServableStateSnapshot(id_notmanaged));
}
TEST_P(BasicManagerTest, GetManagedServableStateSnapshotsWithAdditionalState) {
basic_manager_->ManageServableWithAdditionalState(
CreateServable({kServableName3, 0}), std::unique_ptr<int>(new int(0)));
basic_manager_->ManageServableWithAdditionalState(
CreateServable({kServableName3, 1}), std::unique_ptr<int>(new int(1)));
const std::vector<ServableStateSnapshot<int>> expected = {
{{kServableName3, 0}, LoaderHarness::State::kNew, {0}},
{{kServableName3, 1}, LoaderHarness::State::kNew, {1}}};
EXPECT_THAT(
basic_manager_->GetManagedServableStateSnapshots<int>(kServableName3),
UnorderedElementsAreArray(expected));
}
TEST_P(BasicManagerTest, MultipleManageCallsUsesFirstServable) {
const ServableId id = {kServableName, 1};
std::unique_ptr<Loader> first_loader(
new FakeLoader(1, errors::Internal("An error.")));
basic_manager_->ManageServable(
CreateServableData(id, std::move(first_loader)));
// Different servable returned.
std::unique_ptr<Loader> second_loader(
new FakeLoader(2, errors::Internal("An error.")));
basic_manager_->ManageServable(
CreateServableData(id, std::move(second_loader)));
ServableHandle<int64> handle;
TF_ASSERT_OK(basic_manager_->GetServableHandle(
ServableRequest::Specific(kServableName, 1), &handle));
EXPECT_EQ(1, *handle);
}
// Tests to ensure the manager doesn't try to load or serve an incoming
// erroneous servable.
TEST_P(BasicManagerTest, ErroneousServable) {
const ServableId id = {kServableName, 3};
basic_manager_->ManageServable(
ServableData<std::unique_ptr<Loader>>(id, errors::Unknown("error")));
ServableHandle<int64> handle;
Status status = basic_manager_->GetServableHandle(
ServableRequest::Specific(kServableName, 3), &handle);
EXPECT_FALSE(status.ok()) << status;
basic_manager_->LoadServable(
id, [](const Status& status) { EXPECT_FALSE(status.ok()) << status; });
status = basic_manager_->GetServableHandle(
ServableRequest::Specific(kServableName, 3), &handle);
EXPECT_FALSE(status.ok()) << status;
}
// Tests to ensure that the deletion of a loader/servable occurs in a manager
// thread, and not a request thread.
TEST_P(BasicManagerTest, DestructOnNonServingThread) {
const ServableId id = {kServableName, 7};
basic_manager_->ManageServable(
CreateServableData(id, std::unique_ptr<Loader>(new FakeLoader(7))));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kAvailable});
std::unique_ptr<ServableHandle<int64>> latest_handle(
new ServableHandle<int64>());
const Status status = basic_manager_->GetServableHandle(
ServableRequest::Latest(kServableName), latest_handle.get());
TF_ASSERT_OK(status);
EXPECT_EQ(7, **latest_handle);
Notification done_unload_servable;
std::unique_ptr<Thread> unload_servable(
Env::Default()->StartThread({}, "UnloadServable", [&]() {
// Unload the servable.
basic_manager_->UnloadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kEnd});
basic_manager_->StopManagingServable(id);
// The servable has been deleted in this thread if there is no
// thread-pool for load/unload.
if (thread_pool_sizes_.num_load_threads == 0) {
EXPECT_TRUE(FakeLoader::was_deleted_in_this_thread());
}
done_unload_servable.Notify();
}));
// This will unblock the UnloadServable.
latest_handle.reset();
done_unload_servable.WaitForNotification();
// The servable wasn't deleted in this thread.
ASSERT_FALSE(FakeLoader::was_deleted_in_this_thread());
}
TEST_P(BasicManagerTest, AdditionalState) {
const ServableId id = {kServableName, 3};
std::unique_ptr<int> state(new int(1));
basic_manager_->ManageServableWithAdditionalState(CreateServable(id),
std::move(state));
EXPECT_EQ(1, *basic_manager_->GetAdditionalServableState<int>(id));
EXPECT_EQ(nullptr, basic_manager_->GetAdditionalServableState<float>(id));
}
TEST_P(BasicManagerTest, NoAdditionalState) {
const ServableId id = {kServableName, 3};
basic_manager_->ManageServable(CreateServable(id));
// Will return nullptr when there is no metadata set.
EXPECT_EQ(nullptr, basic_manager_->GetAdditionalServableState<int>(id));
EXPECT_EQ(nullptr, basic_manager_->GetAdditionalServableState<float>(id));
}
TEST_P(BasicManagerTest, OutOfOrderLoadServable) {
const ServableId id = {kServableName, 3};
basic_manager_->LoadServable(id, [](const Status& status) {
EXPECT_FALSE(status.ok());
EXPECT_EQ(error::NOT_FOUND, status.code());
EXPECT_THAT(status.error_message(), HasSubstr("is not being managed"));
});
}
TEST_P(BasicManagerTest, MultipleLoadServables) {
const ServableId id = {kServableName, 3};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kAvailable});
basic_manager_->LoadServable(id, [](const Status& status) {
EXPECT_FALSE(status.ok());
EXPECT_EQ(error::FAILED_PRECONDITION, status.code());
EXPECT_THAT(status.error_message(), HasSubstr("Duplicate load request"));
});
}
TEST_P(BasicManagerTest, MultipleUnloadServables) {
const ServableId id = {kServableName, 3};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kAvailable});
basic_manager_->UnloadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_, id,
{ServableState::ManagerState::kEnd});
basic_manager_->UnloadServable(id, [](const Status& status) {
EXPECT_FALSE(status.ok());
EXPECT_EQ(error::FAILED_PRECONDITION, status.code());
EXPECT_THAT(status.error_message(),
HasSubstr("unload already requested/ongoing"));
});
}
TEST_P(BasicManagerTest, UnloadWithoutManage) {
const ServableId id = {kServableName, 3};
basic_manager_->UnloadServable(id, [](const Status& status) {
EXPECT_FALSE(status.ok());
EXPECT_EQ(error::NOT_FOUND, status.code());
EXPECT_THAT(status.error_message(), HasSubstr("is not being managed"));
});
}
TEST_P(BasicManagerTest, UnloadWithoutLoad) {
const ServableId id = {kServableName, 3};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->UnloadServable(id, [](const Status& status) {
EXPECT_FALSE(status.ok());
EXPECT_EQ(error::FAILED_PRECONDITION, status.code());
EXPECT_THAT(status.error_message(), HasSubstr("Servable not loaded"));
});
}
TEST_P(BasicManagerTest, EventBusErroneousVersion) {
const ServableId id = {kServableName, 3};
basic_manager_->ManageServable(
ServableData<std::unique_ptr<Loader>>(id, errors::Unknown("error")));
const ServableState expected_published_state = {
id, ServableState::ManagerState::kEnd, errors::Unknown("error")};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(expected_published_state));
}
TEST_P(BasicManagerTest, EventBusErrorOnLoad) {
const ServableId id = {kServableName, 7};
std::unique_ptr<Loader> loader(
new FakeLoader(7, errors::Internal("Error on load.")));
basic_manager_->ManageServable({id, std::move(loader)});
const ServableState start_state = {id, ServableState::ManagerState::kStart,
Status::OK()};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(start_state));
basic_manager_->LoadServable(id, [](const Status& status) {});
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_, id,
{ServableState::ManagerState::kEnd});
const ServableState error_state = {id, ServableState::ManagerState::kEnd,
errors::Internal("Error on load.")};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(error_state));
}
TEST_P(BasicManagerTest, EventBusServableLifecycle) {
const ServableId id = {kServableName, 7};
test_util::MockLoader* loader = new NiceMock<test_util::MockLoader>();
basic_manager_->ManageServable({id, std::unique_ptr<Loader>(loader)});
const ServableState start_state = {id, ServableState::ManagerState::kStart,
Status::OK()};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(start_state));
Notification load_called;
Notification load_continue;
EXPECT_CALL(*loader, Load()).WillOnce(InvokeWithoutArgs([&]() {
load_called.Notify();
load_continue.WaitForNotification();
return Status::OK();
}));
std::unique_ptr<Thread> load_thread(
Env::Default()->StartThread(ThreadOptions(), "LoadThread", [&]() {
basic_manager_->LoadServable(id, [](const Status& status) {});
}));
load_called.WaitForNotification();
const ServableState loading_state = {
id, ServableState::ManagerState::kLoading, Status::OK()};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(loading_state));
load_continue.Notify();
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kAvailable});
const ServableState available_state = {
id, ServableState::ManagerState::kAvailable, Status::OK()};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(available_state));
Notification unload_called;
Notification unload_continue;
EXPECT_CALL(*loader, Unload())
.WillOnce(Invoke([&]() {
unload_called.Notify();
unload_continue.WaitForNotification();
}));
// Scoped to ensure UnloadServable() is scheduled.
std::unique_ptr<Thread> unload_thread(
Env::Default()->StartThread(ThreadOptions(), "UnloadThread", [&]() {
basic_manager_->UnloadServable(id, [](const Status& status) {});
}));
unload_called.WaitForNotification();
const ServableState unloading_state = {
id, ServableState::ManagerState::kUnloading, Status::OK()};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(unloading_state));
unload_continue.Notify();
WaitUntilServableManagerStateIsOneOf(servable_state_monitor_, id,
{ServableState::ManagerState::kEnd});
const ServableState end_state = {id, ServableState::ManagerState::kEnd,
Status::OK()};
EXPECT_THAT(*servable_state_monitor_.GetState(id),
EqualsServableState(end_state));
}
// Tests whether there are any errors if we don't have an event bus configured.
TEST_P(BasicManagerTest, NoEventBus) {
BasicManager::Options options;
// Single threaded execution.
options.num_load_threads = 0;
// No event bus.
options.servable_event_bus = nullptr;
std::unique_ptr<BasicManager> manager;
TF_ASSERT_OK(BasicManager::Create(std::move(options), &manager));
const ServableId id = {kServableName, 7};
std::unique_ptr<Loader> loader(new FakeLoader(7));
manager->ManageServable({id, std::move(loader)});
manager->LoadServable(id, [](const Status& status) { TF_ASSERT_OK(status); });
manager->UnloadServable(id,
[](const Status& status) { TF_ASSERT_OK(status); });
}
TEST_P(BasicManagerTest, LoadsThenUnloads) {
std::set<ServableId> servables;
// Scoped so that all loads can be scheduled before proceeding.
{
ThreadPoolExecutor load_executor(Env::Default(), "LoadServables",
kNumThreads);
for (int i = 0; i < 20; ++i) {
const ServableId id = {kServableName3, i};
servables.insert(id);
load_executor.Schedule([this, id, &servables]() {
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
});
}
}
// At this point, all loads may not have completed, so we wait for them.
for (const ServableId& servable : servables) {
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, servable,
{ServableState::ManagerState::kAvailable});
}
{
ThreadPoolExecutor unload_executor(Env::Default(), "UnloadServables",
kNumThreads);
// Doing in reverse.
for (int i = 19; i >= 0; --i) {
unload_executor.Schedule([this, i]() {
const ServableId id = {kServableName3, i};
basic_manager_->UnloadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
});
}
}
}
TEST_P(BasicManagerTest, InterleavedLoadsAndUnloads) {
ThreadPoolExecutor executor(Env::Default(), "InterleavedLoadsAndUnloads",
kNumThreads);
for (int i = 0; i < 20; ++i) {
executor.Schedule([this, i]() {
const ServableId id = {kServableName3, i};
basic_manager_->ManageServable(CreateServable(id));
Notification load_done;
basic_manager_->LoadServable(id, [&load_done](const Status& status) {
TF_ASSERT_OK(status);
load_done.Notify();
});
load_done.WaitForNotification();
basic_manager_->UnloadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
});
}
}
class SetNumLoadThreadsBasicManagerTest : public ::testing::Test {
protected:
SetNumLoadThreadsBasicManagerTest() {
BasicManager::Options options;
options.num_load_threads = 0;
options.max_num_load_retries = 10;
options.load_retry_interval_micros = 0;
TF_CHECK_OK(BasicManager::Create(std::move(options), &basic_manager_));
}
std::unique_ptr<BasicManager> basic_manager_;
};
TEST_F(SetNumLoadThreadsBasicManagerTest, ThreadPoolSwapped) {
test_util::BasicManagerTestAccess manager_test_access(basic_manager_.get());
manager_test_access.SetNumLoadThreads(2);
EXPECT_EQ(2, manager_test_access.num_load_threads());
const auto load_done_fn = [&](const Status& status) {
TF_ASSERT_OK(status);
// Tests whether the threadpools are actually swapped in
// SetNumLoadThreads().
static thread_local int per_thread_load_ctr = 0;
++per_thread_load_ctr;
EXPECT_EQ(1, per_thread_load_ctr);
};
const ServableId id0 = {kServableName3, 0};
basic_manager_->ManageServable(CreateServable(id0));
basic_manager_->LoadServable(id0, load_done_fn);
manager_test_access.SetNumLoadThreads(0);
EXPECT_EQ(0, manager_test_access.num_load_threads());
const ServableId id1 = {kServableName3, 1};
basic_manager_->ManageServable(CreateServable(id1));
basic_manager_->LoadServable(id1, load_done_fn);
// Force the manager to finish before deleting the notifications.
basic_manager_.reset();
}
TEST_F(SetNumLoadThreadsBasicManagerTest, ThreadPoolsNotAliveSimultaneously) {
test_util::BasicManagerTestAccess manager_test_access(basic_manager_.get());
manager_test_access.SetNumLoadThreads(1);
EXPECT_EQ(1, manager_test_access.num_load_threads());
std::set<string> data_race_set;
const auto data_race_fn = [&](const Status& status) {
// This line will cause a data race if both the loads happen simultaneously
// on different threads. This will be caught by the ThreadSanitizer, causing
// the test to fail.
data_race_set.insert("string");
};
const ServableId id0 = {kServableName3, 0};
basic_manager_->ManageServable(CreateServable(id0));
Notification notify_for_setting;
Notification continue_load;
basic_manager_->LoadServable(id0, [&](const Status& status) {
notify_for_setting.Notify();
continue_load.WaitForNotification();
data_race_fn(status);
});
{
ThreadPoolExecutor executor(Env::Default(), "SetNumLoadThreads",
kNumThreads);
executor.Schedule([&]() {
notify_for_setting.WaitForNotification();
manager_test_access.SetNumLoadThreads(1);
EXPECT_EQ(1, manager_test_access.num_load_threads());
});
executor.Schedule([&]() {
const ServableId id1 = {kServableName3, 1};
basic_manager_->ManageServable(CreateServable(id1));
continue_load.Notify();
basic_manager_->LoadServable(
id1, [&](const Status& status) { data_race_fn(status); });
});
}
// Force the manager to finish before deleting the notifications.
basic_manager_.reset();
}
// Tests whether the fast-load scenario works. In the fast-load scenario we try
// to load a bunch of servables as fast as possible using a lot of threads.
TEST_F(SetNumLoadThreadsBasicManagerTest, FastLoad) {
test_util::BasicManagerTestAccess manager_test_access(basic_manager_.get());
const uint32 prev_num_load_threads = manager_test_access.num_load_threads();
manager_test_access.SetNumLoadThreads(32);
EXPECT_EQ(32, manager_test_access.num_load_threads());
{
ThreadPoolExecutor executor(Env::Default(), "FirstThreadPoolLoads",
kNumThreads);
for (int i = 0; i < 20; ++i) {
executor.Schedule([this, i]() {
const ServableId id = {kServableName3, i};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
// We don't wait for load to be done here because we want to test that
// SetNumLoadThreads() waits properly till all queued loads are
// finished. If a queued load hasn't been finished the corresponding
// UnloadServable() will fail.
});
}
}
manager_test_access.SetNumLoadThreads(prev_num_load_threads);
EXPECT_EQ(prev_num_load_threads, manager_test_access.num_load_threads());
{
ThreadPoolExecutor executor(Env::Default(), "Unloads", kNumThreads);
for (int i = 0; i < 20; ++i) {
executor.Schedule([this, i]() {
const ServableId id = {kServableName3, i};
basic_manager_->UnloadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
});
}
}
}
TEST_P(BasicManagerTest, ConcurrentLoadsOnlyOneSucceeds) {
const ServableId id = {kServableName3, 0};
mutex status_mu;
std::vector<Status> statuses(4);
{
ThreadPoolExecutor load_executor(Env::Default(), "LoadServables",
kNumThreads);
for (int i = 0; i < 4; ++i) {
load_executor.Schedule([this, id, i, &statuses, &status_mu]() {
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [i, &statuses, &status_mu](const Status& status) {
mutex_lock l(status_mu);
statuses[i] = status;
});
});
}
}
// At this point, all loads may not have completed. Deleting BasicManager
// would wait for all the scheduled loads to complete before deleting it.
basic_manager_.reset();
int num_status_ok = 0;
for (int i = 0; i < 4; ++i) {
mutex_lock l(status_mu);
if (!statuses[i].ok()) {
EXPECT_EQ(error::FAILED_PRECONDITION, statuses[i].code());
EXPECT_THAT(statuses[i].error_message(),
HasSubstr("Duplicate load request"));
} else {
++num_status_ok;
}
}
EXPECT_EQ(1, num_status_ok);
}
TEST_P(BasicManagerTest, ConcurrentUnloadsOnlyOneSucceeds) {
const ServableId id = {kServableName3, 0};
basic_manager_->ManageServable(CreateServable(id));
basic_manager_->LoadServable(
id, [](const Status& status) { TF_ASSERT_OK(status); });
// At this point, all loads may not have completed, so we wait for them.
WaitUntilServableManagerStateIsOneOf(
servable_state_monitor_, id, {ServableState::ManagerState::kAvailable});
mutex status_mu;
std::vector<Status> statuses(4);
{
ThreadPoolExecutor load_executor(Env::Default(), "LoadServables",
kNumThreads);
for (int i = 0; i < 4; ++i) {
load_executor.Schedule([this, id, i, &statuses, &status_mu]() {
basic_manager_->UnloadServable(
id, [i, &statuses, &status_mu](const Status& status) {
mutex_lock l(status_mu);
statuses[i] = status;
});
});
}
}
// At this point, all unloads may not have completed. Deleting BasicManager
// would wait for all the scheduled unloads to complete before deleting it.
basic_manager_.reset();
int num_status_ok = 0;