Debian Codegraph @

thirdparty/folly/folly/futures/test/TimekeeperTestLib.h

raw
1 /*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #pragma once
18
19 #include <thread>
20 #include <vector>
21
22 #include <fmt/format.h>
23 #include <glog/logging.h>
24 #include <folly/DefaultKeepAliveExecutor.h>
25 #include <folly/Random.h>
26 #include <folly/Singleton.h>
27 #include <folly/VirtualExecutor.h>
28 #include <folly/executors/GlobalExecutor.h>
29 #include <folly/executors/ManualExecutor.h>
30 #include <folly/executors/SerialExecutor.h>
31 #include <folly/futures/Future.h>
32 #include <folly/portability/GTest.h>
33
34 namespace folly {
35
36 using namespace std::chrono_literals;
37 using std::chrono::steady_clock;
38
39 template <class Tk>
40 class TimekeeperTest : public testing::Test {
41 protected:
42 void SetUp() override {
43 // Replace the default timekeeper with the class under test, and verify that
44 // the replacement was successful.
45 Singleton<Timekeeper, detail::TimekeeperSingletonTag>::make_mock(
46 [] { return new Tk; });
47 ASSERT_TRUE(
48 dynamic_cast<Tk*>(detail::getTimekeeperSingleton().get()) != nullptr);
49 }
50
51 void TearDown() override {
52 // Invalidate any mocks that were installed.
53 folly::SingletonVault::singleton()->destroyInstances();
54 folly::SingletonVault::singleton()->reenableInstances();
55 }
56 };
57
58 TYPED_TEST_SUITE_P(TimekeeperTest);
59
60 TYPED_TEST_P(TimekeeperTest, After) {
61 auto t1 = steady_clock::now();
62 auto f = detail::getTimekeeperSingleton()->after(10ms);
63 EXPECT_FALSE(f.isReady());
64 std::move(f).get();
65 auto t2 = steady_clock::now();
66
67 EXPECT_GE(t2 - t1, 10ms);
68 }
69
70 TYPED_TEST_P(TimekeeperTest, AfterUnsafe) {
71 auto t1 = steady_clock::now();
72 auto f = detail::getTimekeeperSingleton()->afterUnsafe(10ms);
73 EXPECT_FALSE(f.isReady());
74 std::move(f).get();
75 auto t2 = steady_clock::now();
76
77 EXPECT_GE(t2 - t1, 10ms);
78 }
79
80 TYPED_TEST_P(TimekeeperTest, FutureGet) {
81 Promise<int> p;
82 auto t = std::thread([&] { p.setValue(42); });
83 EXPECT_EQ(42, p.getFuture().get());
84 t.join();
85 }
86
87 TYPED_TEST_P(TimekeeperTest, FutureGetBeforeTimeout) {
88 Promise<int> p;
89 auto t = std::thread([&] { p.setValue(42); });
90 // Technically this is a race and if the test server is REALLY overloaded
91 // and it takes more than a second to do that thread it could be flaky. But
92 // I want a low timeout (in human terms) so if this regresses and someone
93 // runs it by hand they're not sitting there forever wondering why it's
94 // blocked, and get a useful error message instead. If it does get flaky,
95 // empirically increase the timeout to the point where it's very improbable.
96 EXPECT_EQ(42, p.getFuture().get(std::chrono::seconds(2)));
97 t.join();
98 }
99
100 TYPED_TEST_P(TimekeeperTest, FutureGetTimeout) {
101 Promise<int> p;
102 EXPECT_THROW(p.getFuture().get(1ms), folly::FutureTimeout);
103 }
104
105 TYPED_TEST_P(TimekeeperTest, FutureSleep) {
106 auto t1 = steady_clock::now();
107 futures::sleep(1ms).get();
108 EXPECT_GE(steady_clock::now() - t1, 1ms);
109 }
110
111 FOLLY_PUSH_WARNING
112 FOLLY_GNU_DISABLE_WARNING("-Wdeprecated-declarations")
113 TYPED_TEST_P(TimekeeperTest, FutureSleepUnsafe) {
114 auto t1 = steady_clock::now();
115 futures::sleepUnsafe(1ms).get();
116 EXPECT_GE(steady_clock::now() - t1, 1ms);
117 }
118 FOLLY_POP_WARNING
119
120 TYPED_TEST_P(TimekeeperTest, FutureDelayed) {
121 auto t1 = steady_clock::now();
122 auto dur = makeFuture()
123 .delayed(1ms)
124 .thenValue([=](auto&&) { return steady_clock::now() - t1; })
125 .get();
126
127 EXPECT_GE(dur, 1ms);
128 }
129
130 TYPED_TEST_P(TimekeeperTest, SemiFutureDelayed) {
131 auto t1 = steady_clock::now();
132 auto dur = makeSemiFuture()
133 .delayed(1ms)
134 .toUnsafeFuture()
135 .thenValue([=](auto&&) { return steady_clock::now() - t1; })
136 .get();
137
138 EXPECT_GE(dur, 1ms);
139 }
140
141 TYPED_TEST_P(TimekeeperTest, FutureDelayedStickyExecutor) {
142 // Check that delayed without an executor binds the inline executor.
143 {
144 auto t1 = steady_clock::now();
145 std::thread::id timekeeper_thread_id =
146 folly::detail::getTimekeeperSingleton()
147 // Ensure that the continuation is run almost certainly in the
148 // timekeeper's thread.
149 ->after(100ms)
150 .toUnsafeFuture()
151 .thenValue([](auto&&) { return std::this_thread::get_id(); })
152 .get();
153 std::thread::id task_thread_id{};
154 auto dur = makeFuture()
155 .delayed(1ms)
156 .thenValue([=, &task_thread_id](auto&&) {
157 task_thread_id = std::this_thread::get_id();
158 return steady_clock::now() - t1;
159 })
160 .get();
161
162 EXPECT_GE(dur, 1ms);
163 EXPECT_EQ(timekeeper_thread_id, task_thread_id);
164 }
165
166 // Check that delayed applied to an executor returns a future that binds
167 // to the same executor as was input.
168 {
169 auto t1 = steady_clock::now();
170 std::thread::id driver_thread_id{};
171 std::thread::id first_task_thread_id{};
172 std::thread::id second_task_thread_id{};
173 folly::ManualExecutor me;
174 std::atomic<bool> stop_signal{false};
175 std::thread me_driver{[&me, &driver_thread_id, &stop_signal] {
176 driver_thread_id = std::this_thread::get_id();
177 while (!stop_signal) {
178 me.run();
179 }
180 }};
181 auto dur = makeSemiFuture()
182 .via(&me)
183 .thenValue([&first_task_thread_id](auto&&) {
184 first_task_thread_id = std::this_thread::get_id();
185 })
186 .delayed(1ms)
187 .thenValue([=, &second_task_thread_id](auto&&) {
188 second_task_thread_id = std::this_thread::get_id();
189 return steady_clock::now() - t1;
190 })
191 .get();
192 stop_signal = true;
193 me_driver.join();
194 EXPECT_GE(dur, 1ms);
195 EXPECT_EQ(driver_thread_id, first_task_thread_id);
196 EXPECT_EQ(driver_thread_id, second_task_thread_id);
197 }
198 }
199
200 TYPED_TEST_P(TimekeeperTest, FutureWithinThrows) {
201 Promise<int> p;
202 auto f = p.getFuture().within(1ms).thenError(
203 tag_t<FutureTimeout>{}, [](auto&&) { return -1; });
204
205 EXPECT_EQ(-1, std::move(f).get());
206 }
207
208 TYPED_TEST_P(TimekeeperTest, SemiFutureWithinThrows) {
209 Promise<int> p;
210 auto f = p.getSemiFuture().within(1ms).toUnsafeFuture().thenError(
211 tag_t<FutureTimeout>{}, [](auto&&) { return -1; });
212
213 EXPECT_EQ(-1, std::move(f).get());
214 }
215
216 TYPED_TEST_P(TimekeeperTest, FutureWithinAlreadyComplete) {
217 auto f = makeFuture(42).within(1ms).thenError(
218 tag_t<FutureTimeout>{}, [&](auto&&) { return -1; });
219
220 EXPECT_EQ(42, std::move(f).get());
221 }
222
223 TYPED_TEST_P(TimekeeperTest, SemiFutureWithinAlreadyComplete) {
224 auto f = makeSemiFuture(42).within(1ms).toUnsafeFuture().thenError(
225 tag_t<FutureTimeout>{}, [&](auto&&) { return -1; });
226
227 EXPECT_EQ(42, std::move(f).get());
228 }
229
230 TYPED_TEST_P(TimekeeperTest, FutureWithinFinishesInTime) {
231 Promise<int> p;
232 auto f = p.getFuture()
233 .within(std::chrono::minutes(1))
234 .thenError(tag_t<FutureTimeout>{}, [&](auto&&) { return -1; });
235 p.setValue(42);
236
237 EXPECT_EQ(42, std::move(f).get());
238 }
239
240 TYPED_TEST_P(TimekeeperTest, SemiFutureWithinFinishesInTime) {
241 Promise<int> p;
242 auto f = p.getSemiFuture()
243 .within(std::chrono::minutes(1))
244 .toUnsafeFuture()
245 .thenError(tag_t<FutureTimeout>{}, [&](auto&&) { return -1; });
246 p.setValue(42);
247
248 EXPECT_EQ(42, std::move(f).get());
249 }
250
251 TYPED_TEST_P(TimekeeperTest, FutureWithinVoidSpecialization) {
252 makeFuture().within(1ms);
253 }
254
255 TYPED_TEST_P(TimekeeperTest, SemiFutureWithinVoidSpecialization) {
256 makeSemiFuture().within(1ms);
257 }
258
259 TYPED_TEST_P(TimekeeperTest, FutureWithinException) {
260 Promise<Unit> p;
261 auto f = p.getFuture().within(10ms, std::runtime_error("expected"));
262 EXPECT_THROW(std::move(f).get(), std::runtime_error);
263 }
264
265 TYPED_TEST_P(TimekeeperTest, SemiFutureWithinException) {
266 Promise<Unit> p;
267 auto f = p.getSemiFuture().within(10ms, std::runtime_error("expected"));
268 EXPECT_THROW(std::move(f).get(), std::runtime_error);
269 }
270
271 TYPED_TEST_P(TimekeeperTest, OnTimeout) {
272 bool flag = false;
273 makeFuture(42)
274 .delayed(10 * 1ms)
275 .onTimeout(
276 0ms,
277 [&] {
278 flag = true;
279 return -1;
280 })
281 .get();
282 EXPECT_TRUE(flag);
283 }
284
285 TYPED_TEST_P(TimekeeperTest, OnTimeoutComplete) {
286 bool flag = false;
287 makeFuture(42)
288 .onTimeout(
289 0ms,
290 [&] {
291 flag = true;
292 return -1;
293 })
294 .get();
295 EXPECT_FALSE(flag);
296 }
297
298 TYPED_TEST_P(TimekeeperTest, OnTimeoutReturnsFuture) {
299 bool flag = false;
300 makeFuture(42)
301 .delayed(10 * 1ms)
302 .onTimeout(
303 0ms,
304 [&] {
305 flag = true;
306 return makeFuture(-1);
307 })
308 .get();
309 EXPECT_TRUE(flag);
310 }
311
312 TYPED_TEST_P(TimekeeperTest, OnTimeoutVoid) {
313 makeFuture().delayed(1ms).onTimeout(0ms, [&] {});
314 makeFuture().delayed(1ms).onTimeout(
315 0ms, [&] { return makeFuture<Unit>(std::runtime_error("expected")); });
316 // just testing compilation here
317 }
318
319 TYPED_TEST_P(TimekeeperTest, InterruptDoesntCrash) {
320 auto f = futures::sleep(10s);
321 f.cancel();
322 }
323
324 TYPED_TEST_P(TimekeeperTest, ChainedInterruptTest) {
325 bool test = false;
326 auto f = futures::sleep(100ms).deferValue([&](auto&&) { test = true; });
327 f.cancel();
328 f.wait();
329 EXPECT_FALSE(test);
330 }
331
332 TYPED_TEST_P(TimekeeperTest, FutureWithinChainedInterruptTest) {
333 bool test = false;
334 Promise<Unit> p;
335 p.setInterruptHandler([&test, &p](const exception_wrapper& ex) {
336 ex.handle(
337 [&test](const FutureCancellation& /* cancellation */) { test = true; });
338 p.setException(ex);
339 });
340 auto f = p.getFuture().within(100ms);
341 EXPECT_FALSE(test) << "Sanity check";
342 f.cancel();
343 f.wait();
344 EXPECT_TRUE(test);
345 }
346
347 TYPED_TEST_P(TimekeeperTest, SemiFutureWithinChainedInterruptTest) {
348 bool test = false;
349 Promise<Unit> p;
350 p.setInterruptHandler([&test, &p](const exception_wrapper& ex) {
351 ex.handle(
352 [&test](const FutureCancellation& /* cancellation */) { test = true; });
353 p.setException(ex);
354 });
355 auto f = p.getSemiFuture().within(100ms);
356 EXPECT_FALSE(test) << "Sanity check";
357 f.cancel();
358 f.wait();
359 EXPECT_TRUE(test);
360 }
361
362 TYPED_TEST_P(TimekeeperTest, Executor) {
363 class ExecutorTester : public DefaultKeepAliveExecutor {
364 public:
365 virtual void add(Func f) override {
366 count++;
367 f();
368 }
369 void join() { joinKeepAlive(); }
370 std::atomic<int> count{0};
371 };
372
373 {
374 Promise<Unit> p;
375 ExecutorTester tester;
376 auto f = p.getFuture()
377 .via(&tester)
378 .within(std::chrono::seconds(10))
379 .thenValue([&](auto&&) {});
380 p.setValue();
381 std::move(f).get();
382 tester.join();
383 EXPECT_EQ(3, tester.count);
384 }
385
386 {
387 Promise<Unit> p;
388 ExecutorTester tester;
389 auto f = p.getFuture()
390 .via(&tester)
391 .within(std::chrono::milliseconds(10))
392 .thenValue([&](auto&&) {});
393 EXPECT_THROW(std::move(f).get(), FutureTimeout);
394 p.setValue();
395 tester.join();
396 EXPECT_EQ(3, tester.count);
397 }
398 }
399
400 // TODO(5921764)
401 /*
402 TYPED_TEST_P(TimekeeperTest, OnTimeoutPropagates) {
403 bool flag = false;
404 EXPECT_THROW(
405 makeFuture(42).delayed(1ms)
406 .onTimeout(0ms, [&]{ flag = true; })
407 .get(),
408 FutureTimeout);
409 EXPECT_TRUE(flag);
410 }
411 */
412
413 TYPED_TEST_P(TimekeeperTest, AtBeforeNow) {
414 auto f = detail::getTimekeeperSingleton()->at(steady_clock::now() - 10s);
415 EXPECT_TRUE(f.isReady());
416 EXPECT_FALSE(f.hasException());
417 }
418
419 TYPED_TEST_P(TimekeeperTest, HowToCastDuration) {
420 // I'm not sure whether this rounds up or down but it's irrelevant for the
421 // purpose of this example.
422 auto f = detail::getTimekeeperSingleton()->after(
423 std::chrono::duration_cast<Duration>(std::chrono::nanoseconds(1)));
424 }
425
426 TYPED_TEST_P(TimekeeperTest, Destruction) {
427 folly::Optional<TypeParam> tk{in_place};
428 auto f = tk->after(std::chrono::seconds(10));
429 EXPECT_FALSE(f.isReady());
430 tk.reset();
431 EXPECT_TRUE(f.isReady());
432 EXPECT_TRUE(f.hasException());
433 }
434
435 namespace {
436
437 template <class Tk>
438 void stressTest(
439 std::chrono::microseconds duration, std::chrono::microseconds period) {
440 using usec = std::chrono::microseconds;
441
442 folly::Optional<Tk> tk{in_place};
443 std::vector<std::thread> workers;
444
445 // Run continuations on a serial executor so we don't need synchronization to
446 // modify shared state.
447 folly::Optional<VirtualExecutor> continuationsThread{
448 in_place, SerialExecutor::create(folly::getGlobalCPUExecutor())};
449 size_t numCompletions = 0;
450 usec sumDelay{0};
451 usec maxDelay{0};
452
453 // Wait for any lazy initialization in the timekeeper and executor.
454 tk->after(1ms).via(&*continuationsThread).then([](auto&&) {}).get();
455
456 static const auto jitter = [](usec avg) {
457 // Center around average.
458 return usec(folly::Random::rand64(2 * avg.count()));
459 };
460
461 static const auto jitterSleep = [](steady_clock::time_point& now, usec avg) {
462 now += jitter(avg);
463 if (now - steady_clock::now() < 10us) {
464 // Busy-sleep if yielding the CPU would take too long.
465 while (now > steady_clock::now()) {
466 }
467 } else {
468 /* sleep override */ std::this_thread::sleep_until(now);
469 }
470 };
471
472 for (size_t i = 0; i < 8; ++i) {
473 workers.emplace_back([&] {
474 std::vector<Future<Unit>> futures;
475 for (auto start = steady_clock::now(), now = start;
476 now < start + duration;
477 jitterSleep(now, period)) {
478 // Use the test duration as rough range for the timeouts.
479 auto dur = jitter(duration);
480 auto expected = steady_clock::now() + dur;
481 futures.push_back(
482 tk->after(dur)
483 .toUnsafeFuture()
484 .thenValue([](auto&&) { return steady_clock::now(); })
485 .via(&*continuationsThread)
486 .thenValue([&, expected](auto fired) {
487 auto delay =
488 std::chrono::duration_cast<usec>(fired - expected);
489 // TODO(ott): HHWheelTimer-based timekeepers round down the
490 // timeout, so they may fire early, for now ignore this.
491 if (delay < 0us && delay > -1ms) {
492 delay = 0us;
493 }
494 ASSERT_GE(delay.count(), 0);
495 ++numCompletions;
496 sumDelay += delay;
497 maxDelay = std::max(maxDelay, delay);
498 }));
499 }
500
501 for (auto& f : futures) {
502 // While at it, check that canceling the future after it has been
503 // fulfilled has no effect. To do so, we wait non-destructively.
504 while (!f.isReady()) {
505 /* sleep override */ std::this_thread::sleep_for(1ms);
506 }
507 f.cancel();
508 EXPECT_NO_THROW(std::move(f).get());
509 }
510 });
511 }
512
513 // Add a worker that cancels all its futures.
514 size_t numAttemptedCancellations = 0;
515 size_t numCancellations = 0;
516 workers.emplace_back([&] {
517 std::vector<SemiFuture<Unit>> futures;
518 for (auto start = steady_clock::now(), now = start; now < start + duration;
519 jitterSleep(now, 1ms)) {
520 // Pick a wide range of durations to exercise various positions in the
521 // sequence of timeouts.
522 auto dur = 5ms + jitter(5s);
523 futures.push_back(tk->after(dur));
524 // Cancel the future scheduled in the previous iteration.
525 if (futures.size() > 1) {
526 futures[futures.size() - 2].cancel();
527 }
528 }
529
530 futures.back().cancel();
531 numAttemptedCancellations = futures.size();
532
533 for (auto& f : futures) {
534 if (std::move(f).getTry().hasException<FutureCancellation>()) {
535 ++numCancellations;
536 }
537 }
538 });
539
540 // Add a few timeouts that will not survive the timekeeper.
541 std::vector<SemiFuture<Unit>> shutdownFutures;
542 for (size_t i = 0; i < 10; ++i) {
543 shutdownFutures.push_back(tk->after(10min));
544 }
545
546 for (auto& worker : workers) {
547 worker.join();
548 }
549
550 continuationsThread.reset(); // Wait for all continuations.
551 ASSERT_GT(numCompletions, 0);
552
553 // In principle the delay is unbounded (depending on the state of the system),
554 // so we cannot have any upper bound that is both meaningful and reliable, but
555 // we can log it to manually inspect the behavior.
556 LOG(INFO) << fmt::format(
557 "Successful completions: {}, avg delay: {} us, max delay: {} us ",
558 numCompletions,
559 sumDelay.count() / numCompletions,
560 maxDelay.count());
561
562 // Similarly, a cancellation may be processed only after the future has fired,
563 // but in normal conditions this should never happen.
564 LOG(INFO) << fmt::format(
565 "Attempted cancellations: {}, successful: {}",
566 numAttemptedCancellations,
567 numCancellations);
568
569 tk.reset();
570 for (auto& f : shutdownFutures) {
571 EXPECT_TRUE(std::move(f).getTry().hasException<FutureNoTimekeeper>());
572 }
573 }
574
575 } // namespace
576
577 TYPED_TEST_P(TimekeeperTest, Stress) {
578 stressTest<TypeParam>(/* duration */ 1s, /* period */ 10ms);
579 }
580
581 TYPED_TEST_P(TimekeeperTest, StressHighContention) {
582 // Test that nothing breaks when scheduling a large number of timeouts
583 // concurrently. In this case the timekeeper thread will be overloaded, so the
584 // measured delays are going to be large.
585 stressTest<TypeParam>(/* duration */ 50ms, /* period */ 5us);
586 }
587
588 REGISTER_TYPED_TEST_SUITE_P(
589 TimekeeperTest,
590 After,
591 AfterUnsafe,
592 FutureGet,
593 FutureGetBeforeTimeout,
594 FutureGetTimeout,
595 FutureSleep,
596 FutureSleepUnsafe,
597 FutureDelayed,
598 SemiFutureDelayed,
599 FutureDelayedStickyExecutor,
600 FutureWithinThrows,
601 SemiFutureWithinThrows,
602 FutureWithinAlreadyComplete,
603 SemiFutureWithinAlreadyComplete,
604 FutureWithinFinishesInTime,
605 SemiFutureWithinFinishesInTime,
606 FutureWithinVoidSpecialization,
607 SemiFutureWithinVoidSpecialization,
608 FutureWithinException,
609 SemiFutureWithinException,
610 OnTimeout,
611 OnTimeoutComplete,
612 OnTimeoutReturnsFuture,
613 OnTimeoutVoid,
614 InterruptDoesntCrash,
615 ChainedInterruptTest,
616 FutureWithinChainedInterruptTest,
617 SemiFutureWithinChainedInterruptTest,
618 Executor,
619 AtBeforeNow,
620 HowToCastDuration,
621 Destruction,
622 Stress,
623 StressHighContention);
624
625 } // namespace folly