#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::Scheduler { namespace { [[nodiscard]] bool is_valid_id(std::string_view s) noexcept { if (s.empty() || s.size() > 256U) { return false; } for (unsigned char c : s) { if (c < 0x21U || c > 0x7EU) { return false; } } return true; } struct SlotDedupKey { std::string job_id{}; std::uint64_t revision{0}; std::int64_t intended_utc_ms{0}; std::uint8_t fold_index{0}; [[nodiscard]] auto operator<=>(const SlotDedupKey&) const noexcept = default; }; [[nodiscard]] std::size_t count_retained_map(const std::map& occs) noexcept { return occs.size(); } class InMemoryJobStore final : public JobStore { public: explicit InMemoryJobStore(SchedulerLimits limits) : m_limits(limits) { } Result acquire_ownership(std::string_view owner_id) override { std::lock_guard lk{m_mu}; if (m_owner.has_value() && *m_owner != owner_id) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::OwnershipLocked, "InMemoryJobStore already owned by '" + *m_owner + "'")); } m_owner = std::string{owner_id}; return {}; } Result release_ownership() override { std::lock_guard lk{m_mu}; m_owner.reset(); return {}; } Result put_job(const JobRecord& job) override { std::lock_guard lk{m_mu}; if (m_jobs.contains(job.spec.id)) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Conflict, "Scheduler: job already exists: " + job.spec.id)); } if (m_jobs.size() >= m_limits.max_jobs) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Overloaded, "Scheduler: max_jobs limit reached")); } if (count_retained_map(m_occurrences) >= m_limits.max_retained_occurrences) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::RetentionFull, "Scheduler: occurrence retention cap saturated")); } m_jobs.emplace(job.spec.id, job); return {}; } Result update_job(const JobRecord& updated, std::uint64_t expected_revision) override { std::lock_guard lk{m_mu}; auto it = m_jobs.find(updated.spec.id); if (it == m_jobs.end() || it->second.tombstoned) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::NotFound, "Scheduler: job not found: " + updated.spec.id)); } if (it->second.revision != expected_revision) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Conflict, "Scheduler: concurrent revision conflict on update")); } it->second = updated; return {}; } Result tombstone_job(std::string_view job_id) override { std::lock_guard lk{m_mu}; auto it = m_jobs.find(job_id); if (it == m_jobs.end()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::NotFound, "Scheduler: job not found")); } it->second.tombstoned = true; return {}; } Result> load_jobs() const override { std::lock_guard lk{m_mu}; std::vector out; out.reserve(m_jobs.size()); for (const auto& [k, v] : m_jobs) { (void)k; out.push_back(v); } return out; } Result> load_occurrences() const override { std::lock_guard lk{m_mu}; std::vector out; out.reserve(m_occurrences.size()); for (const auto& [k, v] : m_occurrences) { (void)k; out.push_back(v); } return out; } Result materialize_occurrences( std::string_view job_id, std::uint64_t expected_revision, std::int64_t new_cursor_utc_ms, std::int64_t new_cursor_monotonic_ns, bool cursor_initialized, bool one_shot_materialized, std::uint64_t next_sequence, const std::vector& records) override { std::lock_guard lk{m_mu}; auto jit = m_jobs.find(job_id); if (jit == m_jobs.end() || jit->second.tombstoned) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::NotFound, "Scheduler: job missing or tombstoned")); } if (jit->second.revision != expected_revision) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Conflict, "Scheduler: job revision mismatch during " "materialization")); } // Filter out duplicates via unique slot index first, then // reserve retention capacity before advancing cursor. std::vector to_insert; to_insert.reserve(records.size()); for (const auto& rec : records) { SlotDedupKey dk{rec.id.job_id, rec.id.revision, rec.intended_utc_ms, rec.fold_index}; if (jit->second.spec.schedule.kind == ScheduleKind::Calendar && m_slot_index.contains(dk)) { continue; } if (m_occurrences.contains(rec.id)) { continue; } to_insert.push_back(rec); } if (m_occurrences.size() + to_insert.size() > m_limits.max_retained_occurrences) { // Never advance cursor when retention is saturated! return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::RetentionFull, "Scheduler: occurrence retention cap reached; " "pausing materialization without advancing cursor")); } for (const auto& rec : to_insert) { if (jit->second.spec.schedule.kind == ScheduleKind::Calendar) { m_slot_index.insert(SlotDedupKey{ rec.id.job_id, rec.id.revision, rec.intended_utc_ms, rec.fold_index}); } m_occurrences.emplace(rec.id, rec); } jit->second.cursor_utc_ms = new_cursor_utc_ms; jit->second.cursor_monotonic_ns = new_cursor_monotonic_ns; jit->second.cursor_initialized = cursor_initialized; jit->second.one_shot_materialized = one_shot_materialized; jit->second.next_sequence = next_sequence; return to_insert.size(); } Result claim_occurrence(const OccurrenceId& id, std::uint32_t expected_attempt) override { std::lock_guard lk{m_mu}; auto jit = m_jobs.find(id.job_id); if (jit == m_jobs.end() || jit->second.tombstoned) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Cancelled, "Scheduler: job tombstoned before claim")); } if (id.revision < jit->second.invalidated_before_revision) { auto oit = m_occurrences.find(id); if (oit != m_occurrences.end() && oit->second.status == OccurrenceStatus::Pending) { oit->second.status = OccurrenceStatus::Cancelled; } return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Cancelled, "Scheduler: occurrence invalidated by newer job " "revision")); } auto oit = m_occurrences.find(id); if (oit == m_occurrences.end()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::NotFound, "Scheduler: occurrence not found")); } if (oit->second.status != OccurrenceStatus::Pending || oit->second.attempt != expected_attempt) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Conflict, "Scheduler: occurrence state changed before claim")); } oit->second.status = OccurrenceStatus::Running; oit->second.attempt += 1U; return oit->second; } Result complete_occurrence( const OccurrenceId& id, std::uint32_t attempt, std::int64_t completed_utc_ms, std::optional fixed_delay_next_monotonic_ns) override { std::lock_guard lk{m_mu}; auto oit = m_occurrences.find(id); if (oit == m_occurrences.end()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::NotFound, "Scheduler: occurrence not found on complete")); } if (oit->second.status != OccurrenceStatus::Running || oit->second.attempt != attempt) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Conflict, "Scheduler: stale attempt on complete")); } oit->second.status = OccurrenceStatus::Completed; oit->second.completed_utc_ms = completed_utc_ms; if (fixed_delay_next_monotonic_ns.has_value()) { auto jit = m_jobs.find(id.job_id); if (jit != m_jobs.end() && !jit->second.tombstoned && jit->second.revision == id.revision) { jit->second.cursor_monotonic_ns = *fixed_delay_next_monotonic_ns; jit->second.cursor_initialized = true; } } return {}; } Result fail_occurrence( const OccurrenceId& id, std::uint32_t attempt, std::int64_t next_due_monotonic_ns, std::int64_t next_due_utc_ms, bool mark_dead, std::string diagnostic_category) override { std::lock_guard lk{m_mu}; auto oit = m_occurrences.find(id); if (oit == m_occurrences.end()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::NotFound, "Scheduler: occurrence not found on fail")); } if (oit->second.status != OccurrenceStatus::Running || oit->second.attempt != attempt) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Conflict, "Scheduler: stale attempt on fail")); } oit->second.diagnostic_category = std::move(diagnostic_category); if (mark_dead) { oit->second.status = OccurrenceStatus::Dead; } else { oit->second.status = OccurrenceStatus::Pending; oit->second.due_monotonic_ns = next_due_monotonic_ns; oit->second.intended_utc_ms = next_due_utc_ms; } return {}; } Result requeue_on_shutdown(const OccurrenceId& id, std::uint32_t attempt) override { std::lock_guard lk{m_mu}; auto oit = m_occurrences.find(id); if (oit == m_occurrences.end()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::NotFound, "Scheduler: occurrence not found on shutdown " "requeue")); } if (oit->second.status != OccurrenceStatus::Running || oit->second.attempt != attempt) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Conflict, "Scheduler: stale attempt on shutdown requeue")); } oit->second.status = OccurrenceStatus::Pending; if (oit->second.attempt > 0U) { oit->second.attempt -= 1U; } return {}; } Result recover_running_occurrences() override { std::lock_guard lk{m_mu}; std::size_t recovered = 0; for (auto& [id, rec] : m_occurrences) { (void)id; if (rec.status == OccurrenceStatus::Running) { rec.status = OccurrenceStatus::Pending; ++recovered; } } return recovered; } Result acknowledge_dead(const OccurrenceId& id) override { std::lock_guard lk{m_mu}; auto oit = m_occurrences.find(id); if (oit == m_occurrences.end()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::NotFound, "Scheduler: occurrence not found")); } if (oit->second.status != OccurrenceStatus::Dead) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidArgument, "Scheduler: occurrence is not in Dead status")); } oit->second.dead_acknowledged = true; return {}; } Result prune_completed(std::int64_t before_utc_ms, std::size_t max_count) override { std::lock_guard lk{m_mu}; std::size_t pruned = 0; for (auto it = m_occurrences.begin(); it != m_occurrences.end() && pruned < max_count;) { const bool prunable_completed = it->second.status == OccurrenceStatus::Completed && it->second.completed_utc_ms <= before_utc_ms; const bool prunable_dead = it->second.status == OccurrenceStatus::Dead && it->second.dead_acknowledged; if (prunable_completed || prunable_dead) { it = m_occurrences.erase(it); ++pruned; } else { ++it; } } return pruned; } Result reclaim_invalidated(std::size_t max_count) override { std::lock_guard lk{m_mu}; std::size_t reclaimed = 0; for (auto it = m_occurrences.begin(); it != m_occurrences.end() && reclaimed < max_count;) { bool invalid = it->second.status == OccurrenceStatus::Cancelled; if (!invalid && it->second.status == OccurrenceStatus::Pending) { auto jit = m_jobs.find(it->first.job_id); if (jit != m_jobs.end() && (jit->second.tombstoned || it->first.revision < jit->second.invalidated_before_revision)) { invalid = true; } } if (invalid) { it = m_occurrences.erase(it); ++reclaimed; } else { ++it; } } return reclaimed; } Result stats() const override { std::lock_guard lk{m_mu}; StoreStats s{}; s.jobs = m_jobs.size(); for (const auto& [id, rec] : m_occurrences) { (void)id; switch (rec.status) { case OccurrenceStatus::Pending: ++s.pending; break; case OccurrenceStatus::Running: ++s.running; break; case OccurrenceStatus::Completed: ++s.completed; break; case OccurrenceStatus::Dead: ++s.dead; break; case OccurrenceStatus::Cancelled: ++s.cancelled; break; } } s.total_retained = m_occurrences.size(); s.retention_saturated = s.total_retained >= m_limits.max_retained_occurrences; return s; } private: SchedulerLimits m_limits{}; mutable std::mutex m_mu{}; std::optional m_owner{}; std::map> m_jobs{}; std::map m_occurrences{}; std::set m_slot_index{}; }; struct HeapEntry { std::int64_t due_monotonic_ns{0}; std::uint64_t sequence{0}; OccurrenceId id{}; // Min-heap comparator (priority_queue pops largest, so invert). [[nodiscard]] bool operator>(const HeapEntry& o) const noexcept { if (due_monotonic_ns != o.due_monotonic_ns) { return due_monotonic_ns > o.due_monotonic_ns; } if (sequence != o.sequence) { return sequence > o.sequence; } return id > o.id; } }; struct ActiveExecution { OccurrenceId id{}; std::stop_source stop_source{}; std::thread::id worker_thread{}; }; [[nodiscard]] std::int64_t compute_retry_delay_ms( const RetryPolicy& policy, std::uint32_t attempt, const RandomU64Fn& rng) { const std::int64_t base_ms = std::max( 0LL, policy.base_delay.count()); const std::int64_t max_ms = std::max( base_ms, policy.max_delay.count()); if (max_ms == 0LL) { return 0LL; } std::int64_t cap_ms = base_ms; const std::uint32_t mult = std::max(1U, policy.multiplier); for (std::uint32_t i = 1U; i < attempt; ++i) { if (cap_ms > max_ms / static_cast(mult)) { cap_ms = max_ms; break; } cap_ms *= static_cast(mult); } cap_ms = std::min(cap_ms, max_ms); if (cap_ms <= 0LL) { return 0LL; } const std::uint64_t r = rng ? rng() : 0ULL; return static_cast( r % (static_cast(cap_ms) + 1ULL)); } } // namespace std::shared_ptr make_in_memory_job_store(SchedulerLimits limits) { return std::make_shared(limits); } struct Scheduler::State { std::string owner_id{}; std::shared_ptr store{}; const Void::Time::MonotonicClock* monotonic_clock{ &Void::Time::SystemMonotonicClock::instance()}; const Void::Time::CivilClock* civil_clock{ &Void::Time::SystemCivilClock::instance()}; TimezoneRegistry timezones{}; SchedulerLimits limits{}; RandomU64Fn rng{}; ObservationHook observer{}; mutable std::mutex mu{}; std::condition_variable active_cv{}; bool closing{false}; bool closed_cleanly{false}; std::map> handlers{}; std::map> jobs{}; std::map> parsed_calendars{}; std::map pending_cache{}; std::priority_queue, std::greater> heap{}; std::map> active{}; std::map> active_per_job{}; void emit(ObservationKind kind, std::size_t count = 1, std::int64_t lag_ms = 0) const { if (observer) { observer(ObservationEvent{ .kind = kind, .count = count, .lag_ms = lag_ms, }); } } [[nodiscard]] Result> validate_job_spec(const JobSpec& spec) const { if (!is_valid_id(spec.id)) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidArgument, "Scheduler: invalid job id")); } if (!is_valid_id(spec.handler_id)) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidArgument, "Scheduler: invalid handler_id")); } if (spec.payload.size() > limits.max_payload_bytes) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidArgument, "Scheduler: job payload exceeds max_payload_bytes")); } if (spec.retry.max_attempts == 0U || spec.retry.base_delay < std::chrono::milliseconds{0} || spec.retry.max_delay < spec.retry.base_delay || spec.retry.multiplier == 0U) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidArgument, "Scheduler: invalid RetryPolicy")); } if (spec.overlap == OverlapPolicy::AllowBounded && spec.max_concurrent == 0U) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidArgument, "Scheduler: AllowBounded overlap requires " "max_concurrent >= 1")); } switch (spec.schedule.kind) { case ScheduleKind::OneShot: return std::optional{std::nullopt}; case ScheduleKind::FixedDelay: case ScheduleKind::FixedRate: if (spec.schedule.interval <= std::chrono::milliseconds{0}) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler: fixed interval must be positive")); } return std::optional{std::nullopt}; case ScheduleKind::Calendar: { if (auto tz_ok = timezones.validate_timezone( spec.schedule.calendar.timezone); !tz_ok.has_value()) { return Void::Result::fail(tz_ok.error()); } auto expr = CalendarExpression::parse( spec.schedule.calendar.expression); if (!expr.has_value()) { return Void::Result::fail(expr.error()); } return std::optional{ std::move(*expr)}; } } return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidRule, "Scheduler: unknown schedule kind")); } [[nodiscard]] std::size_t pending_for_job_locked(std::string_view job_id, std::uint64_t rev) const noexcept { std::size_t n = 0; for (const auto& [oid, rec] : pending_cache) { if (oid.job_id == job_id && oid.revision == rev && rec.status == OccurrenceStatus::Pending) { ++n; } } return n; } [[nodiscard]] std::size_t active_for_job_locked(std::string_view job_id) const noexcept { auto it = active_per_job.find(job_id); return it == active_per_job.end() ? 0U : it->second; } [[nodiscard]] std::size_t allowed_concurrency_for_job(const JobSpec& spec) const noexcept { switch (spec.overlap) { case OverlapPolicy::Forbid: case OverlapPolicy::QueueOne: return 1U; case OverlapPolicy::AllowBounded: return std::max(1U, spec.max_concurrent); } return 1U; } void push_pending_locked(const OccurrenceRecord& rec) { pending_cache[rec.id] = rec; heap.push(HeapEntry{ .due_monotonic_ns = rec.due_monotonic_ns, .sequence = rec.id.sequence, .id = rec.id, }); } Result materialize_all_due() { std::vector snapshot_jobs; { std::lock_guard lk{mu}; if (closing) { return 0U; } snapshot_jobs.reserve(jobs.size()); for (const auto& [k, j] : jobs) { (void)k; if (!j.tombstoned) { snapshot_jobs.push_back(j); } } } const auto now_mono = monotonic_clock->now(); const std::int64_t now_mono_ns = to_ns(now_mono); const std::int64_t now_utc_ms = to_utc_ms(civil_clock->now()); std::size_t total_created = 0; for (auto& job : snapshot_jobs) { std::vector batch_records; std::int64_t next_cursor_utc = job.cursor_utc_ms; std::int64_t next_cursor_mono = job.cursor_monotonic_ns; bool next_cursor_init = job.cursor_initialized; bool next_one_shot_done = job.one_shot_materialized; std::uint64_t next_seq = job.next_sequence; bool should_commit = false; auto make_occ = [&](std::int64_t due_ns, std::int64_t intended_utc, std::uint8_t fold) { OccurrenceRecord rec{}; rec.id = OccurrenceId{job.spec.id, job.revision, next_seq++}; rec.intended_utc_ms = intended_utc; rec.due_monotonic_ns = due_ns; rec.fold_index = fold; rec.status = OccurrenceStatus::Pending; rec.attempt = 0; rec.handler_id = job.spec.handler_id; rec.payload_schema = job.spec.payload_schema; rec.payload = job.spec.payload; return rec; }; switch (job.spec.schedule.kind) { case ScheduleKind::OneShot: { if (job.one_shot_materialized) { break; } std::int64_t due_ns = now_mono_ns; std::int64_t intended_utc = now_utc_ms; if (job.spec.schedule.due_monotonic.has_value()) { due_ns = to_ns(*job.spec.schedule.due_monotonic); intended_utc = now_utc_ms + (due_ns - now_mono_ns) / 1000000LL; } else { intended_utc = job.spec.schedule.start_utc_ms; due_ns = now_mono_ns + (intended_utc - now_utc_ms) * 1000000LL; } if (due_ns <= now_mono_ns) { batch_records.push_back( make_occ(due_ns, intended_utc, 0)); next_one_shot_done = true; next_cursor_mono = due_ns; next_cursor_utc = intended_utc; next_cursor_init = true; should_commit = true; } break; } case ScheduleKind::FixedDelay: { std::size_t live_for_job = 0; { std::lock_guard lk{mu}; live_for_job = pending_for_job_locked(job.spec.id, job.revision) + active_for_job_locked(job.spec.id); } if (live_for_job > 0U) { break; } std::int64_t due_ns = now_mono_ns; if (job.cursor_initialized) { due_ns = job.cursor_monotonic_ns; } else if (job.spec.schedule.due_monotonic .has_value()) { due_ns = to_ns(*job.spec.schedule.due_monotonic); } if (due_ns <= now_mono_ns) { const std::int64_t intended_utc = now_utc_ms + (due_ns - now_mono_ns) / 1000000LL; batch_records.push_back( make_occ(due_ns, intended_utc, 0)); next_cursor_mono = due_ns; next_cursor_utc = intended_utc; next_cursor_init = true; should_commit = true; } break; } case ScheduleKind::FixedRate: { const std::int64_t interval_ns = std::chrono::duration_cast< std::chrono::nanoseconds>( job.spec.schedule.interval) .count(); std::int64_t first_due = now_mono_ns; if (job.cursor_initialized) { first_due = job.cursor_monotonic_ns + interval_ns; } else if (job.spec.schedule.due_monotonic .has_value()) { first_due = to_ns(*job.spec.schedule.due_monotonic); } if (first_due > now_mono_ns) { break; } const std::int64_t missed = (now_mono_ns - first_due) / interval_ns + 1LL; if (job.spec.misfire == MisfirePolicy::Skip) { next_cursor_mono = first_due + (missed - 1LL) * interval_ns; next_cursor_init = true; should_commit = true; } else if (job.spec.misfire == MisfirePolicy::CoalesceLatest) { const std::int64_t latest = first_due + (missed - 1LL) * interval_ns; const std::int64_t intended_utc = now_utc_ms + (latest - now_mono_ns) / 1000000LL; batch_records.push_back( make_occ(latest, intended_utc, 0)); next_cursor_mono = latest; next_cursor_utc = intended_utc; next_cursor_init = true; should_commit = true; } else { const std::size_t cap = std::min( static_cast(missed), limits.max_catch_up_per_job_per_pass); for (std::size_t k = 0; k < cap; ++k) { const std::int64_t due = first_due + static_cast(k) * interval_ns; const std::int64_t intended_utc = now_utc_ms + (due - now_mono_ns) / 1000000LL; batch_records.push_back( make_occ(due, intended_utc, 0)); next_cursor_mono = due; next_cursor_utc = intended_utc; } next_cursor_init = true; should_commit = true; } break; } case ScheduleKind::Calendar: { std::optional expr{}; { std::lock_guard lk{mu}; auto cit = parsed_calendars.find(job.spec.id); if (cit != parsed_calendars.end()) { expr = cit->second; } } if (!expr.has_value()) { auto parsed = CalendarExpression::parse( job.spec.schedule.calendar.expression); if (!parsed.has_value()) { return Void::Result::fail(parsed.error()); } expr = *parsed; } const std::int64_t after_utc = job.cursor_initialized ? job.cursor_utc_ms : (now_utc_ms - 60000LL); auto mat = expr->materialize_range( job.spec.schedule.calendar, timezones, after_utc, now_utc_ms, job.spec.misfire, limits.max_catch_up_per_job_per_pass); if (!mat.has_value()) { return Void::Result::fail(mat.error()); } if (!mat->slots.empty() || mat->next_cursor_utc_ms != job.cursor_utc_ms) { for (const auto& s : mat->slots) { const std::int64_t due_ns = now_mono_ns + (s.utc_ms - now_utc_ms) * 1000000LL; batch_records.push_back( make_occ(due_ns, s.utc_ms, s.fold_index)); } next_cursor_utc = mat->next_cursor_utc_ms; next_cursor_init = true; should_commit = true; } break; } } if (!should_commit) { continue; } // QueueOne overlap: if a job is currently running and // already has a queued pending slot, retain only the latest // slot (do not pile up unbounded pending records). if (job.spec.overlap == OverlapPolicy::QueueOne && batch_records.size() > 1U) { OccurrenceRecord latest = std::move(batch_records.back()); batch_records.clear(); batch_records.push_back(std::move(latest)); } if (job.spec.overlap == OverlapPolicy::QueueOne) { std::lock_guard lk{mu}; if (active_for_job_locked(job.spec.id) > 0U && pending_for_job_locked(job.spec.id, job.revision) >= 1U) { batch_records.clear(); } } auto res = store->materialize_occurrences( job.spec.id, job.revision, next_cursor_utc, next_cursor_mono, next_cursor_init, next_one_shot_done, next_seq, batch_records); if (!res.has_value()) { if (res.error().code().value == static_cast( SchedulerErrorCode::RetentionFull)) { emit(ObservationKind::RetentionPause, 1); // Pause materialization cleanly without advancing // cursor or failing the entire tick. continue; } if (res.error().code().value == static_cast( SchedulerErrorCode::Conflict)) { continue; } return Void::Result::fail(res.error()); } total_created += *res; { std::lock_guard lk{mu}; auto jit = jobs.find(job.spec.id); if (jit != jobs.end() && jit->second.revision == job.revision) { jit->second.cursor_utc_ms = next_cursor_utc; jit->second.cursor_monotonic_ns = next_cursor_mono; jit->second.cursor_initialized = next_cursor_init; jit->second.one_shot_materialized = next_one_shot_done; jit->second.next_sequence = next_seq; } for (const auto& rec : batch_records) { push_pending_locked(rec); } } if (*res > 0U) { emit(ObservationKind::Materialize, *res); } } return total_created; } Result dispatch_one(Void::Async::OperationOptions options) { if (options.stop.stop_requested()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Cancelled, "Scheduler::dispatch_one cancelled")); } if (Void::Async::is_deadline_expired(options, *monotonic_clock)) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Cancelled, "Scheduler::dispatch_one deadline expired")); } const std::int64_t now_mono_ns = to_ns(monotonic_clock->now()); OccurrenceRecord candidate{}; JobSpec job_spec{}; HandlerFn handler{}; std::shared_ptr exec_slot{}; bool found = false; { std::lock_guard lk{mu}; if (closing) { return false; } if (active.size() >= limits.max_active_handlers) { return false; } std::vector deferred; while (!heap.empty()) { HeapEntry top = heap.top(); if (top.due_monotonic_ns > now_mono_ns) { break; } heap.pop(); auto pit = pending_cache.find(top.id); if (pit == pending_cache.end() || pit->second.status != OccurrenceStatus::Pending) { continue; } // Ignore stale heap entry superseded by retry re-push. if (pit->second.due_monotonic_ns > now_mono_ns) { deferred.push_back(HeapEntry{ .due_monotonic_ns = pit->second.due_monotonic_ns, .sequence = top.sequence, .id = top.id, }); continue; } auto jit = jobs.find(top.id.job_id); if (jit == jobs.end() || jit->second.tombstoned || top.id.revision < jit->second.invalidated_before_revision) { pending_cache.erase(pit); continue; } const std::size_t running_for_job = active_for_job_locked(top.id.job_id); if (running_for_job >= allowed_concurrency_for_job(jit->second.spec)) { deferred.push_back(top); continue; } auto hit = handlers.find(pit->second.handler_id); if (hit == handlers.end()) { // Keep pending until handler is registered or // explicitly fail? Defer so caller can register // handler before running. deferred.push_back(top); continue; } candidate = pit->second; job_spec = jit->second.spec; handler = hit->second; pending_cache.erase(pit); exec_slot = std::make_shared(); exec_slot->id = candidate.id; exec_slot->worker_thread = std::this_thread::get_id(); active.emplace(candidate.id, exec_slot); active_per_job[candidate.id.job_id] += 1U; found = true; break; } for (auto& d : deferred) { heap.push(std::move(d)); } } if (!found) { return false; } auto release_active = [&]() { std::lock_guard lk{mu}; active.erase(candidate.id); auto it = active_per_job.find(candidate.id.job_id); if (it != active_per_job.end()) { if (it->second <= 1U) { active_per_job.erase(it); } else { it->second -= 1U; } } active_cv.notify_all(); }; // Atomically claim Pending -> Running in store before running // handler! auto claimed = store->claim_occurrence(candidate.id, candidate.attempt); if (!claimed.has_value()) { release_active(); if (claimed.error().code().value == static_cast( SchedulerErrorCode::Cancelled) || claimed.error().code().value == static_cast( SchedulerErrorCode::Conflict)) { return false; } return Void::Result::fail(claimed.error()); } const std::int64_t lag_ms = std::max(0LL, (now_mono_ns - claimed->due_monotonic_ns) / 1000000LL); emit(ObservationKind::Dispatch, 1, lag_ms); // Build merged stop token linking caller stop + execution stop. std::stop_callback caller_fwd( options.stop, [&] { exec_slot->stop_source.request_stop(); }); Void::Async::OperationOptions handler_opts{}; handler_opts.stop = exec_slot->stop_source.get_token(); handler_opts.deadline = options.deadline; OccurrenceContext ctx{}; ctx.id = claimed->id; ctx.attempt = claimed->attempt; ctx.payload_schema = claimed->payload_schema; ctx.intended_utc_ms = claimed->intended_utc_ms; ctx.fold_index = claimed->fold_index; // Invoke handler strictly OUTSIDE scheduler and store locks! Result handler_res{}; try { handler_res = handler(ctx, claimed->payload, handler_opts); } catch (...) { handler_res = Void::Result::fail(make_scheduler_error( SchedulerErrorCode::HandlerFailed, "Scheduler: handler threw an exception")); } bool is_closing = false; { std::lock_guard lk{mu}; is_closing = closing; } if (handler_res.has_value()) { const std::int64_t done_utc_ms = to_utc_ms(civil_clock->now()); std::optional fixed_delay_next{}; if (job_spec.schedule.kind == ScheduleKind::FixedDelay) { fixed_delay_next = to_ns(monotonic_clock->now()) + std::chrono::duration_cast< std::chrono::nanoseconds>( job_spec.schedule.interval) .count(); } auto cr = store->complete_occurrence( claimed->id, claimed->attempt, done_utc_ms, fixed_delay_next); if (cr.has_value() && fixed_delay_next.has_value()) { std::lock_guard lk{mu}; auto jit = jobs.find(claimed->id.job_id); if (jit != jobs.end() && jit->second.revision == claimed->id.revision) { jit->second.cursor_monotonic_ns = *fixed_delay_next; jit->second.cursor_initialized = true; } } release_active(); if (!cr.has_value()) { return Void::Result::fail(cr.error()); } emit(ObservationKind::Complete, 1); return true; } // Handler failed or stopped. if (is_closing && (exec_slot->stop_source.stop_requested() || handler_res.error().kind() == Void::Result::ErrorKind::cancelled)) { // Host shutdown: preserve Pending intent without consuming // a retry attempt! auto rq = store->requeue_on_shutdown(claimed->id, claimed->attempt); release_active(); if (!rq.has_value()) { return Void::Result::fail(rq.error()); } return true; } const bool exhausted = claimed->attempt >= job_spec.retry.max_attempts; const std::int64_t retry_delay_ms = exhausted ? 0LL : compute_retry_delay_ms( job_spec.retry, claimed->attempt, rng); const std::int64_t next_mono_ns = to_ns(monotonic_clock->now()) + retry_delay_ms * 1000000LL; const std::int64_t next_utc_ms = to_utc_ms(civil_clock->now()) + retry_delay_ms; auto fr = store->fail_occurrence( claimed->id, claimed->attempt, next_mono_ns, next_utc_ms, exhausted, std::string{ Void::Result::to_string(handler_res.error().kind())}); if (fr.has_value() && !exhausted) { OccurrenceRecord retry_rec = *claimed; retry_rec.status = OccurrenceStatus::Pending; retry_rec.due_monotonic_ns = next_mono_ns; retry_rec.intended_utc_ms = next_utc_ms; std::lock_guard lk{mu}; push_pending_locked(retry_rec); } release_active(); if (!fr.has_value()) { return Void::Result::fail(fr.error()); } emit(exhausted ? ObservationKind::DeadLetter : ObservationKind::Retry, 1); return true; } }; Scheduler::Scheduler(std::shared_ptr state) noexcept : m_state(std::move(state)) { } Scheduler::Scheduler(Scheduler&&) noexcept = default; Scheduler& Scheduler::operator=(Scheduler&&) noexcept = default; Scheduler::~Scheduler() noexcept { if (!m_state) { return; } bool release = false; { std::lock_guard lk{m_state->mu}; m_state->closing = true; for (auto& [id, exec] : m_state->active) { (void)id; if (exec) { exec->stop_source.request_stop(); } } release = !m_state->closed_cleanly && m_state->active.empty(); if (release) { m_state->closed_cleanly = true; } } if (release && m_state->store) { (void)m_state->store->release_ownership(); } } Result Scheduler::create(SchedulerOptions options) { auto st = std::make_shared(); st->owner_id = options.owner_id.empty() ? "scheduler-default" : options.owner_id; st->limits = options.limits; st->store = options.store ? std::move(options.store) : make_in_memory_job_store(st->limits); st->monotonic_clock = options.monotonic_clock != nullptr ? options.monotonic_clock : &Void::Time::SystemMonotonicClock::instance(); st->civil_clock = options.civil_clock != nullptr ? options.civil_clock : &Void::Time::SystemCivilClock::instance(); st->timezones = std::move(options.timezones); st->observer = std::move(options.observer); if (options.rng) { st->rng = std::move(options.rng); } else { auto prng = std::make_shared(0x9E3779B97F4A7C15ULL); auto prng_mu = std::make_shared(); st->rng = [prng, prng_mu]() -> std::uint64_t { std::lock_guard lk{*prng_mu}; return (*prng)(); }; } if (auto own = st->store->acquire_ownership(st->owner_id); !own.has_value()) { return Void::Result::fail(own.error()); } auto rec_count = st->store->recover_running_occurrences(); if (!rec_count.has_value()) { (void)st->store->release_ownership(); return Void::Result::fail(rec_count.error()); } if (*rec_count > 0U) { st->emit(ObservationKind::Recover, *rec_count); } auto jobs = st->store->load_jobs(); if (!jobs.has_value()) { (void)st->store->release_ownership(); return Void::Result::fail(jobs.error()); } for (auto& j : *jobs) { if (j.spec.schedule.kind == ScheduleKind::Calendar) { if (auto expr = CalendarExpression::parse( j.spec.schedule.calendar.expression); expr.has_value()) { st->parsed_calendars.emplace(j.spec.id, std::move(*expr)); } } st->jobs.emplace(j.spec.id, std::move(j)); } auto occs = st->store->load_occurrences(); if (!occs.has_value()) { (void)st->store->release_ownership(); return Void::Result::fail(occs.error()); } const std::int64_t now_mono_ns = to_ns(st->monotonic_clock->now()); const std::int64_t now_utc_ms = to_utc_ms(st->civil_clock->now()); for (auto& o : *occs) { if (o.status == OccurrenceStatus::Pending) { // Re-anchor recovered occurrences into current monotonic domain // based on their persisted intended UTC instant. o.due_monotonic_ns = now_mono_ns + (o.intended_utc_ms - now_utc_ms) * 1000000LL; st->push_pending_locked(o); } } return Scheduler{std::move(st)}; } Result Scheduler::register_handler(std::string handler_id, HandlerFn handler) { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } if (!is_valid_id(handler_id) || !handler) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::InvalidArgument, "Scheduler::register_handler requires valid id and function")); } std::lock_guard lk{m_state->mu}; m_state->handlers[std::move(handler_id)] = std::move(handler); return {}; } Result Scheduler::add_job(JobSpec spec, Void::Async::OperationOptions options) { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } if (options.stop.stop_requested()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Cancelled, "Scheduler::add_job cancelled")); } auto parsed_cal = m_state->validate_job_spec(spec); if (!parsed_cal.has_value()) { return Void::Result::fail(parsed_cal.error()); } JobRecord rec{}; rec.spec = std::move(spec); rec.revision = 1; rec.invalidated_before_revision = 1; rec.tombstoned = false; rec.next_sequence = 1; if (rec.spec.schedule.kind == ScheduleKind::Calendar) { rec.cursor_utc_ms = rec.spec.schedule.start_utc_ms != 0 ? rec.spec.schedule.start_utc_ms : to_utc_ms(m_state->civil_clock->now()); rec.cursor_initialized = true; } { std::lock_guard lk{m_state->mu}; if (m_state->closing) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler is closing")); } } if (auto pr = m_state->store->put_job(rec); !pr.has_value()) { return Void::Result::fail(pr.error()); } { std::lock_guard lk{m_state->mu}; if (parsed_cal->has_value()) { m_state->parsed_calendars[rec.spec.id] = **parsed_cal; } m_state->jobs[rec.spec.id] = rec; } return rec.revision; } Result Scheduler::update_job(JobSpec spec, Void::Async::OperationOptions options) { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } if (options.stop.stop_requested()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Cancelled, "Scheduler::update_job cancelled")); } // Validate completely BEFORE touching existing policy! auto parsed_cal = m_state->validate_job_spec(spec); if (!parsed_cal.has_value()) { return Void::Result::fail(parsed_cal.error()); } JobRecord next{}; std::uint64_t expected_rev = 0; { std::lock_guard lk{m_state->mu}; if (m_state->closing) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler is closing")); } auto it = m_state->jobs.find(spec.id); if (it == m_state->jobs.end() || it->second.tombstoned) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::NotFound, "Scheduler::update_job job not found: " + spec.id)); } expected_rev = it->second.revision; next = it->second; next.spec = std::move(spec); next.revision = expected_rev + 1U; // Atomically invalidate unstarted occurrences from older revisions. next.invalidated_before_revision = next.revision; next.one_shot_materialized = false; if (next.spec.schedule.kind == ScheduleKind::Calendar && !next.cursor_initialized) { next.cursor_utc_ms = next.spec.schedule.start_utc_ms != 0 ? next.spec.schedule.start_utc_ms : to_utc_ms(m_state->civil_clock->now()); next.cursor_initialized = true; } } if (auto ur = m_state->store->update_job(next, expected_rev); !ur.has_value()) { return Void::Result::fail(ur.error()); } { std::lock_guard lk{m_state->mu}; if (parsed_cal->has_value()) { m_state->parsed_calendars[next.spec.id] = **parsed_cal; } else { m_state->parsed_calendars.erase(next.spec.id); } m_state->jobs[next.spec.id] = next; } return next.revision; } Result Scheduler::remove_job(std::string_view job_id, Void::Async::OperationOptions options) { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } if (options.stop.stop_requested()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Cancelled, "Scheduler::remove_job cancelled")); } if (auto tr = m_state->store->tombstone_job(job_id); !tr.has_value()) { return tr; } std::lock_guard lk{m_state->mu}; auto jit = m_state->jobs.find(job_id); if (jit != m_state->jobs.end()) { jit->second.tombstoned = true; } for (auto& [oid, exec] : m_state->active) { if (oid.job_id == job_id && exec) { exec->stop_source.request_stop(); } } return {}; } Result Scheduler::tick(Void::Async::OperationOptions options) { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } if (auto mr = m_state->materialize_all_due(); !mr.has_value()) { return Void::Result::fail(mr.error()); } std::size_t executed = 0; const std::size_t max_dispatches = m_state->limits.max_ready_dispatches; while (executed < max_dispatches) { auto d = m_state->dispatch_one(options); if (!d.has_value()) { return Void::Result::fail(d.error()); } if (!*d) { break; } ++executed; } return executed; } Result Scheduler::dispatch_one(Void::Async::OperationOptions options) { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } return m_state->dispatch_one(options); } Result Scheduler::close_and_join(Void::Async::OperationOptions options) { if (!m_state) { return ShutdownReport{.complete = true}; } { std::lock_guard lk{m_state->mu}; for (const auto& [oid, exec] : m_state->active) { (void)oid; if (exec && exec->worker_thread == std::this_thread::get_id()) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::SelfJoin, "Scheduler::close_and_join cannot be called from an " "active handler thread")); } } m_state->closing = true; for (auto& [oid, exec] : m_state->active) { (void)oid; if (exec) { exec->stop_source.request_stop(); } } } std::unique_lock lk{m_state->mu}; while (!m_state->active.empty()) { if (options.deadline.has_value()) { const auto rem = Void::Time::remaining_until( *m_state->monotonic_clock, *options.deadline); if (rem <= std::chrono::nanoseconds{0}) { ShutdownReport report{}; report.complete = false; for (const auto& [oid, _] : m_state->active) { report.live_occurrences.push_back(oid); } return report; } const auto slice = std::min(rem, std::chrono::duration_cast< std::chrono::nanoseconds>( std::chrono::milliseconds{5})); m_state->active_cv.wait_for(lk, slice, [this] { return m_state->active.empty(); }); } else { m_state->active_cv.wait( lk, [this] { return m_state->active.empty(); }); } } if (!m_state->closed_cleanly) { m_state->closed_cleanly = true; lk.unlock(); if (auto rel = m_state->store->release_ownership(); !rel.has_value()) { return Void::Result::fail(rel.error()); } } return ShutdownReport{.complete = true}; } Result> Scheduler::list_jobs() const { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } return m_state->store->load_jobs(); } Result> Scheduler::list_occurrences() const { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } return m_state->store->load_occurrences(); } Result Scheduler::acknowledge_dead(const OccurrenceId& id) { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } return m_state->store->acknowledge_dead(id); } Result Scheduler::prune_completed(std::size_t max_count) { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } const std::int64_t cutoff = to_utc_ms(m_state->civil_clock->now()) - m_state->limits.completed_retention.count(); return m_state->store->prune_completed(cutoff, max_count); } Result Scheduler::reclaim_invalidated(std::size_t max_count) { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } return m_state->store->reclaim_invalidated(max_count); } Result Scheduler::stats() const { if (!m_state) { return Void::Result::fail(make_scheduler_error( SchedulerErrorCode::Closed, "Scheduler moved-from")); } return m_state->store->stats(); } } // namespace Void::Scheduler