Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for the "next_deadline" bug. #2

Merged
merged 3 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 22 additions & 13 deletions include/embedded_scheduler/scheduler.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -301,32 +301,41 @@ class EventLoop final
template <typename ExecutionMonitor = std::monostate>
[[nodiscard]] SpinResult<Clock> spin()
{
auto next = time_point::max();
auto now = Clock::now();
auto worst = duration::zero();
SpinResult<Clock> result{.next_deadline = time_point::max(),
.worst_lateness = duration::zero(),
.approx_now = time_point::min()};
if (tree_.empty())
{
result.approx_now = Clock::now();
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In original implementation, we always had 2 consecutive now() calls on the very first loop iteration for the future scheduled event. Now we do only minimum (1) call per iteration.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please tag this branch with [[unlikely]]. Maybe there are other places that could use this.

return result;
}

while (auto* const evt = static_cast<EventProxy*>(tree_.min()))
{
next = evt->getDeadline().value(); // The deadline is guaranteed to be set because it is in the tree.
auto lateness = now - next; // Positive if late, zero if on-time.
if (lateness < duration::zero()) // Too early -- either we need to sleep or the time sample is obsolete.
// The deadline is guaranteed to be set because it is in the tree.
const auto deadline = evt->getDeadline().value();
if (result.approx_now < deadline) // Too early -- either we need to sleep or the time sample is obsolete.
{
now = Clock::now(); // The number of calls to Clock::now() is minimized.
lateness = now - next;
if (lateness < duration::zero()) // Nope, even with the latest time sample we are still early -- exit.
result.approx_now = Clock::now(); // The number of calls to Clock::now() is minimized.
if (result.approx_now < deadline) // Nope, even with the latest time sample we are still early -- exit.
Copy link
Collaborator Author

@serges147 serges147 Aug 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note, that I also eliminated subtraction (which is over/under-flow prone strictly speaking). Now I subtract later, when I know for sure that now >= deadline (at line @ 333). Just in case, I will add separate unit test with deadline scheduling time near to timepoint::max - probably it will overflow even now...

{
result.next_deadline = deadline;
break;
}
}
{
ExecutionMonitor monitor{}; // RAII indication of the start and end of the event execution.
// Execution will remove the event from the tree and then possibly re-insert it with a new deadline.
evt->execute({.event = *evt, .deadline = next, .approx_now = now});
evt->execute({.event = *evt, .deadline = deadline, .approx_now = result.approx_now});
(void) monitor;
}
worst = std::max(lateness, worst);
result.next_deadline = time_point::max(); // Reset the next deadline to the maximum possible value.
result.worst_lateness = std::max(result.worst_lateness, result.approx_now - deadline);
}
assert(worst >= duration::zero());
return {.next_deadline = next, .worst_lateness = worst, .approx_now = now};

assert(result.approx_now > time_point::min());
assert(result.worst_lateness >= duration::zero());
return result;
}

/// True if there are no registered events.
Expand Down
68 changes: 63 additions & 5 deletions tests/test_embedded_scheduler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,16 @@
#include <cstdint>
#include <optional>
#include <ratio>
#include <string>
#include <tuple>
#include <vector>

using testing::Gt;
using testing::Le;
using testing::Ne;
using testing::IsNull;
using testing::NotNull;
using testing::ElementsAre;

// NOLINTBEGIN(bugprone-unchecked-optional-access)
// NOLINTBEGIN(readability-function-cognitive-complexity, misc-const-correctness)
Expand Down Expand Up @@ -90,6 +94,7 @@ TEST(TestEmbeddedScheduler, EventLoopBasic)
// semihost::log(__LINE__, " ", out);
EXPECT_THAT(out.next_deadline, SteadyClockMock::time_point::max());
EXPECT_THAT(out.worst_lateness, SteadyClockMock::duration::zero());
EXPECT_THAT(out.approx_now.time_since_epoch(), 10'000ms);
EXPECT_TRUE(evl->isEmpty());
EXPECT_THAT(evl->getTree()[0U], IsNull());

Expand Down Expand Up @@ -151,6 +156,7 @@ TEST(TestEmbeddedScheduler, EventLoopBasic)
// semihost::log(__LINE__, " ", out);
EXPECT_THAT(out.next_deadline.time_since_epoch(), 10'100ms);
EXPECT_THAT(out.worst_lateness, 0ms);
EXPECT_THAT(out.approx_now.time_since_epoch(), 10'000ms);
EXPECT_THAT(evl->getTree().size(), 4);
EXPECT_FALSE(a);
EXPECT_FALSE(b);
Expand All @@ -159,11 +165,12 @@ TEST(TestEmbeddedScheduler, EventLoopBasic)

// Make the first two expire. The one-shot two are still pending.
SteadyClockMock::advance(1100ms);
EXPECT_THAT(11'100ms, SteadyClockMock::now().time_since_epoch());
EXPECT_THAT(SteadyClockMock::now().time_since_epoch(), 11'100ms);
out = evl->spin();
// semihost::log(__LINE__, " ", out);
EXPECT_THAT(out.next_deadline.time_since_epoch(), 11'200ms);
EXPECT_THAT(out.worst_lateness, 1000ms);
EXPECT_THAT(out.approx_now.time_since_epoch(), 11'100ms);
EXPECT_THAT(evl->getTree().size(), 4);
EXPECT_TRUE(a);
EXPECT_THAT(a.value().deadline.time_since_epoch(), 11'000ms);
Expand All @@ -182,6 +189,7 @@ TEST(TestEmbeddedScheduler, EventLoopBasic)
// semihost::log(__LINE__, " ", out);
EXPECT_THAT(out.next_deadline.time_since_epoch(), 12'100ms);
EXPECT_THAT(out.worst_lateness, 800ms);
EXPECT_THAT(out.approx_now.time_since_epoch(), 12'000ms);
EXPECT_THAT(evl->getTree()[0U]->getDeadline().value().time_since_epoch(), 12'100ms);
EXPECT_THAT(evl->getTree().size(), 2); // C&D have left us.
EXPECT_TRUE(a);
Expand Down Expand Up @@ -214,12 +222,13 @@ TEST(TestEmbeddedScheduler, EventLoopBasic)
EXPECT_THAT(evl->getTree().size(), 1); // Ditto.
out = evl->spin();
// semihost::log(__LINE__, " ", out);
EXPECT_THAT(14'000ms, out.next_deadline.time_since_epoch()); // B removed so the next one is A.
EXPECT_THAT(50ms, out.worst_lateness);
EXPECT_THAT(14'000ms, evl->getTree()[0U]->getDeadline().value().time_since_epoch());
EXPECT_THAT(out.next_deadline.time_since_epoch(), 14'000ms); // B removed so the next one is A.
EXPECT_THAT(out.worst_lateness, 50ms);
EXPECT_THAT(out.approx_now.time_since_epoch(), 13'050ms);
EXPECT_THAT(evl->getTree()[0U]->getDeadline().value().time_since_epoch(), 14'000ms);
EXPECT_THAT(1, evl->getTree().size()); // Second dropped.
EXPECT_TRUE(a);
EXPECT_THAT(13'000ms, a.value().deadline.time_since_epoch());
EXPECT_THAT(a.value().deadline.time_since_epoch(), 13'000ms);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In gtest it is always first actual value, and 2nd-ly the expected - result output (in case of failure) explicitly mentions what was expected and was actually found).

EXPECT_FALSE(b);
EXPECT_FALSE(c);
EXPECT_FALSE(d);
Expand All @@ -230,6 +239,7 @@ TEST(TestEmbeddedScheduler, EventLoopBasic)
// semihost::log(__LINE__, " ", out);
EXPECT_THAT(out.next_deadline.time_since_epoch(), 14'000ms); // Same up.
EXPECT_THAT(out.worst_lateness, 0ms);
EXPECT_THAT(out.approx_now.time_since_epoch(), 13'050ms);
EXPECT_FALSE(a);
EXPECT_FALSE(b);
EXPECT_FALSE(c);
Expand Down Expand Up @@ -323,6 +333,54 @@ TEST(TestEmbeddedScheduler, EventLoopPoll)
EXPECT_THAT(evl.getTree()[0U]->getDeadline().value().time_since_epoch(), 210ms); // Skipped ahead!
}

TEST(TestEmbeddedScheduler, EventLoopDefer_single_overdue)
{
using time_point = SteadyClockMock::time_point;
using std::chrono_literals::operator""ms;
SteadyClockMock::reset();
EventLoop<SteadyClockMock> evl;

auto evt = evl.defer(SteadyClockMock::now() + 1000ms, [&](auto) {});
EXPECT_TRUE(evt);

// This is special case - only one deferred event (and no "repeat"-s!), and it is already overdue (by +30ms).
// So, `next_deadline` should be `time_point::max()` b/c there will be nothing left pending after spin.
SteadyClockMock::advance(1000ms + 30ms);
const auto out = evl.spin();
EXPECT_THAT(out.next_deadline.time_since_epoch(), time_point::max().time_since_epoch());
Copy link
Collaborator Author

@serges147 serges147 Aug 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At this line @ 350 we've got incorrect next deadline time before the fix (1000ms instead of correct max).

EXPECT_THAT(out.worst_lateness, 30ms);
EXPECT_THAT(out.approx_now.time_since_epoch(), 1030ms);
}

TEST(TestEmbeddedScheduler, EventLoopDefer_long_running_callback)
{
using duration = SteadyClockMock::duration;
using std::chrono_literals::operator""ms;
SteadyClockMock::reset();
EventLoop<SteadyClockMock> evl;

std::vector<std::tuple<std::string, duration, duration>> calls;

auto evt_a = evl.defer(SteadyClockMock::now() + 0ms, [&](const auto& arg) { //
// Emulate that it took whole 100ms to execute "a" callback,
// so it will be already overdue for the next "b" event - should be executed as well.
calls.emplace_back("a", arg.deadline.time_since_epoch(), arg.approx_now.time_since_epoch());
SteadyClockMock::advance(100ms);
});
auto evt_b = evl.defer(SteadyClockMock::now() + 20ms, [&](const auto& arg) { //
calls.emplace_back("b", arg.deadline.time_since_epoch(), arg.approx_now.time_since_epoch());
});

const auto out = evl.spin();
EXPECT_THAT(out.next_deadline.time_since_epoch(), duration::max());
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And @ 375 as well.

EXPECT_THAT(out.worst_lateness, 80ms);
EXPECT_THAT(out.approx_now.time_since_epoch(), 100ms);

EXPECT_THAT(calls,
ElementsAre(std::make_tuple("a", 0ms, 0ms), //
std::make_tuple("b", 20ms, 100ms)));
}

TEST(TestEmbeddedScheduler, HandleMovement)
{
using std::chrono_literals::operator""ms;
Expand Down