Files
Library/tests/standalone/Scheduler/Scheduler.cpp

308 lines
10 KiB
C++

#include <Void/Scheduler/Calendar.hpp>
#include <Void/Scheduler/Scheduler.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
Void::Testing::Test scheduler_fake_clock_ordering_retries_and_dead_letter()
{
using namespace Void::Scheduler;
using namespace std::chrono_literals;
Void::Time::ManualClock mono{};
Void::Time::ManualCivilClock civil{
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
// Deterministic RNG yielding 500ms full-jitter delay (500 % (1000+1) = 500).
std::uint64_t rng_val = 500ULL;
auto sched = Scheduler::create(SchedulerOptions{
.owner_id = "unit-1",
.monotonic_clock = &mono,
.civil_clock = &civil,
.rng = [&]() { return rng_val; },
});
Void::Testing::require(sched.has_value());
std::vector<std::string> order;
Void::Testing::require(
sched
->register_handler(
"record",
[&](const OccurrenceContext& ctx, std::span<const std::byte>,
Void::Async::OperationOptions) -> Result<void> {
order.push_back(ctx.id.job_id);
return {};
})
.has_value());
int fail_calls = 0;
OccurrenceId failed_id{};
Void::Testing::require(
sched
->register_handler(
"always_fail",
[&](const OccurrenceContext& ctx, std::span<const std::byte>,
Void::Async::OperationOptions) -> Result<void> {
++fail_calls;
failed_id = ctx.id;
return Void::Result::fail(make_scheduler_error(
SchedulerErrorCode::HandlerFailed, "boom"));
})
.has_value());
// Add later job first, earlier job second -> heap must order by due_time.
JobSpec late{};
late.id = "job-late";
late.handler_id = "record";
late.schedule = Schedule::one_shot_monotonic(mono.now() + 5s);
Void::Testing::require(sched->add_job(late).has_value());
JobSpec early{};
early.id = "job-early";
early.handler_id = "record";
early.schedule = Schedule::one_shot_monotonic(mono.now() + 2s);
Void::Testing::require(sched->add_job(early).has_value());
// Clock jumps past both -> must run early before late!
Void::Testing::require(mono.advance(10s).has_value());
auto ran = sched->tick();
Void::Testing::require(ran.has_value());
Void::Testing::expect_eq(*ran, 2ULL);
Void::Testing::require(order.size() == 2U);
Void::Testing::expect_eq(order[0], std::string{"job-early"});
Void::Testing::expect_eq(order[1], std::string{"job-late"});
// Retry exhaustion -> Dead status keeping same OccurrenceId!
JobSpec flaky{};
flaky.id = "job-flaky";
flaky.handler_id = "always_fail";
flaky.schedule = Schedule::one_shot_monotonic(mono.now());
flaky.retry.max_attempts = 3;
flaky.retry.base_delay = 1s;
flaky.retry.max_delay = 10s;
flaky.retry.multiplier = 2;
Void::Testing::require(sched->add_job(flaky).has_value());
for (int i = 0; i < 3; ++i) {
auto r = sched->tick();
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(*r, 1ULL);
Void::Testing::require(mono.advance(10s).has_value());
}
Void::Testing::expect_eq(fail_calls, 3);
auto st = sched->stats();
Void::Testing::require(st.has_value());
Void::Testing::expect_eq(st->dead, 1ULL);
// Dead records cannot be pruned until explicitly acknowledged.
auto prune0 = sched->prune_completed();
Void::Testing::require(prune0.has_value());
Void::Testing::expect_eq(*prune0, 0ULL);
Void::Testing::require(sched->acknowledge_dead(failed_id).has_value());
auto prune1 = sched->prune_completed();
Void::Testing::require(prune1.has_value());
Void::Testing::expect_eq(*prune1, 1ULL);
auto report = sched->close_and_join();
Void::Testing::require(report.has_value());
Void::Testing::expect(report->complete);
}
Void::Testing::Test scheduler_calendar_dst_misfire_and_unknown_tz()
{
using namespace Void::Scheduler;
TimezoneRegistry tz{};
// Reject unknown timezone without silent UTC fallback.
auto bad_tz = tz.validate_timezone("Mars/Olympus_Mons");
Void::Testing::expect(!bad_tz.has_value());
Void::Testing::expect_eq(
bad_tz.error().code().value,
static_cast<std::int32_t>(SchedulerErrorCode::UnsupportedTimezone));
// Fixed offset +02:00 works cleanly.
Void::Testing::expect(tz.validate_timezone("UTC+02:00").has_value());
// Register deterministic DST zone:
// Gap: 2026-03-08 02:00..03:00 local (spring forward -05:00 -> -04:00)
// Fold: 2026-11-01 01:00..02:00 local (fall back -04:00 -> -05:00)
DstTransitionRule rule{};
rule.name = "Test/DST";
rule.standard_offset_minutes = -300;
rule.dst_offset_minutes = -240;
rule.gap_start_local_min = civil_to_epoch_minute(2026, 3, 8, 2, 0);
rule.gap_end_local_min = civil_to_epoch_minute(2026, 3, 8, 3, 0);
rule.fold_start_local_min = civil_to_epoch_minute(2026, 11, 1, 1, 0);
rule.fold_end_local_min = civil_to_epoch_minute(2026, 11, 1, 2, 0);
tz.register_dst_zone(rule);
// Gap policy Skip omits 02:30 on 2026-03-08.
const std::int64_t gap_min = civil_to_epoch_minute(2026, 3, 8, 2, 30);
auto skipped = tz.resolve_local_minute("Test/DST", gap_min,
DstGapPolicy::Skip,
DstFoldPolicy::First);
Void::Testing::require(skipped.has_value());
Void::Testing::expect(skipped->empty());
// Fold policy First yields fold_index=0; Twice yields both fold 0 and 1!
const std::int64_t fold_min = civil_to_epoch_minute(2026, 11, 1, 1, 30);
auto first_only = tz.resolve_local_minute("Test/DST", fold_min,
DstGapPolicy::Skip,
DstFoldPolicy::First);
Void::Testing::require(first_only.has_value());
Void::Testing::require(first_only->size() == 1U);
Void::Testing::expect_eq(first_only->front().fold_index,
static_cast<std::uint8_t>(0));
auto twice = tz.resolve_local_minute("Test/DST", fold_min,
DstGapPolicy::Skip,
DstFoldPolicy::Twice);
Void::Testing::require(twice.has_value());
Void::Testing::require(twice->size() == 2U);
Void::Testing::expect_eq((*twice)[0].fold_index,
static_cast<std::uint8_t>(0));
Void::Testing::expect_eq((*twice)[1].fold_index,
static_cast<std::uint8_t>(1));
Void::Testing::expect_eq((*twice)[1].utc_ms - (*twice)[0].utc_ms,
3600LL * 1000LL);
// CoalesceLatest over >2,000,000 missed minutes executes immediately in
// bounded time and returns the single latest slot!
auto every_min = CalendarExpression::parse("* * * * *");
Void::Testing::require(every_min.has_value());
const std::int64_t t0 =
civil_to_epoch_minute(2020, 1, 1, 0, 0) * 60000LL;
const std::int64_t t1 =
civil_to_epoch_minute(2025, 1, 1, 0, 0) * 60000LL; // ~2.63M minutes!
CalendarSpec cspec{.expression = "* * * * *", .timezone = "UTC"};
auto coalesced = every_min->materialize_range(
cspec, tz, t0, t1, MisfirePolicy::CoalesceLatest, 100);
Void::Testing::require(coalesced.has_value());
Void::Testing::require(coalesced->slots.size() == 1U);
Void::Testing::expect_eq(coalesced->slots[0].utc_ms, t1);
// CatchUpBounded caps strictly at 100 slots/pass preserving cursor state!
auto bounded = every_min->materialize_range(
cspec, tz, t0, t1, MisfirePolicy::CatchUpBounded, 100);
Void::Testing::require(bounded.has_value());
Void::Testing::expect_eq(bounded->slots.size(), 100ULL);
Void::Testing::expect(bounded->more_pending);
Void::Testing::expect_eq(bounded->next_cursor_utc_ms,
t0 + 100LL * 60000LL);
}
Void::Testing::Test scheduler_overlap_revision_edit_and_shutdown_timeout()
{
using namespace Void::Scheduler;
using namespace std::chrono_literals;
Void::Time::ManualClock mono{};
Void::Time::ManualCivilClock civil{
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
auto sched = Scheduler::create(SchedulerOptions{
.owner_id = "unit-overlap",
.monotonic_clock = &mono,
.civil_clock = &civil,
});
Void::Testing::require(sched.has_value());
std::mutex gate_mu;
std::condition_variable gate_cv;
bool entered = false;
bool release = false;
std::atomic<int> concurrent_now{0};
std::atomic<int> max_concurrent_seen{0};
Void::Testing::require(
sched
->register_handler(
"slow",
[&](const OccurrenceContext&, std::span<const std::byte>,
Void::Async::OperationOptions) -> Result<void> {
const int c = ++concurrent_now;
int prev = max_concurrent_seen.load();
while (c > prev &&
!max_concurrent_seen.compare_exchange_weak(prev, c)) {
}
{
std::lock_guard lk{gate_mu};
entered = true;
}
gate_cv.notify_all();
{
std::unique_lock lk{gate_mu};
gate_cv.wait(lk, [&] { return release; });
}
--concurrent_now;
return {};
})
.has_value());
JobSpec job{};
job.id = "j-forbid";
job.handler_id = "slow";
job.schedule = Schedule::fixed_rate(1s, mono.now());
job.misfire = MisfirePolicy::CatchUpBounded;
job.overlap = OverlapPolicy::Forbid;
Void::Testing::require(sched->add_job(job).has_value());
// Advance 3s -> materializes multiple due slots, but Overlap::Forbid must
// never allow 2 concurrent executions of the same job.
Void::Testing::require(mono.advance(2s).has_value());
std::thread worker([&] { (void)sched->tick(); });
{
std::unique_lock lk{gate_mu};
gate_cv.wait(lk, [&] { return entered; });
}
// Second concurrent dispatch_one must be blocked by Overlap::Forbid!
auto blocked = sched->dispatch_one();
Void::Testing::require(blocked.has_value());
Void::Testing::expect(!*blocked);
Void::Testing::expect_eq(max_concurrent_seen.load(), 1);
// Invalid update_job must fail without mutating active policy.
JobSpec bad_update = job;
bad_update.schedule = Schedule::calendar_schedule(
CalendarSpec{.expression = "bad cron", .timezone = "UTC"});
Void::Testing::expect(!sched->update_job(bad_update).has_value());
// Valid update_job bumps revision to 2 and invalidates unstarted rev-1
// pending occurrences!
JobSpec good_update = job;
good_update.payload = {std::byte{0x42}};
auto rev2 = sched->update_job(good_update);
Void::Testing::require(rev2.has_value());
Void::Testing::expect_eq(*rev2, 2ULL);
// close_and_join with already-expired deadline returns incomplete report
// listing the live occurrence instead of erasing running state!
auto inc = sched->close_and_join(
Void::Async::OperationOptions{.deadline = mono.now()});
Void::Testing::require(inc.has_value());
Void::Testing::expect(!inc->complete);
Void::Testing::expect_eq(inc->live_occurrences.size(), 1ULL);
// Unblock active handler and join cleanly.
{
std::lock_guard lk{gate_mu};
release = true;
}
gate_cv.notify_all();
worker.join();
auto done = sched->close_and_join();
Void::Testing::require(done.has_value());
Void::Testing::expect(done->complete);
}