12 KiB
M-TIME-03 — Injected-deadline domains: Async TimerQueue and clock saturation (step B1)
Task ID: M-TIME-03 Role: opus-implementer Status: READY
1. Context and baseline
- Wave 11 package step B1 (TimerQueue part). The
Async::retry_asyncpart of M-TIME-03 is a separate later step (B1b) after M-FUNCTIONAL-03 integrates (gate G1); it is OUT of this assignment. - Repo: VoidLibrary, branch
feat/roadmap-p2-wave11, HEAD7f95f89. You work in an isolated git worktree of7f95f89; cwd = worktree root. Never read the user's untracked files in the main checkout. - Baseline: full suite at
38436b1= 1,484 tests, 1,480 passed, 4 skipped, 0 failed. - Observed source:
include/Void/Time/Clock.hpp:MonotonicClock{ using time_point = steady_clock::time_point; now() }(:19-26),ManualClockstarts at epoch 0 and is atomic (:69-130),:188-208).remaining_until(src/Time/module.cmakehas no deps.include/Void/Async/Detail/Types.hpp:AdmissionError{overloaded, stopped, deadline_expired, invalid_argument, self_join}(:15-21),AsyncErrorCodeincl. NEWclosed = 9(→cancelled, added in7f95f89),OperationOptions{stop_token stop; optional<MonotonicClock::time_point> deadline}(:45-48),is_deadline_expired(options, clock = System)(:50-56),make_async_error.include/Void/Async/Operation.hpp(OperationState,ResumeTicket, backend refs, terminal state machine),Executor.hpp(Executor::post_completion,ManualExecutor,ScheduleStatusAwaiterchecks deadline only inawait_ready/await_resume~:304-359),Task.hpp(Coro::Task),TaskScope.hpp. No timer primitive exists ininclude/Void/Async.src/Async/module.cmake:INTERNAL_DEPS Functional Time LogState(unchanged by this task).
- Requirements: roadmap row M-TIME-03 ("Validate injected-deadline domains with Async and blocking retry adapters; advancing manual time plus explicit polling expires an operation once"); C-03/C-04 (one terminal result, injected clocks); decisions D-038 (F12), D-W11-01, D-W11-14.
2. Objective and deliverables
- NEW
include/Void/Async/Timer.hpp:TimerQueue,TimerHandle,TimerEvent,TimerCallback,TimerQueueOptions(header-only, like the rest of Async). - EDIT
include/Void/Time/Clock.hpp: NEWsaturating_add,deadline_afterhelpers. - NEW tests
tests/standalone/Async/TimerQueue.cpp,tests/standalone/Async/DeadlineDomains.cpp(schedule_on/scope admission part only),tests/standalone/Time/ClockSaturation.cpp.
3. Scope and non-goals
In: the above. Out: Async/Retry.hpp/retry_async and AsyncRetry.cpp (step B1b), any change to
existing Async/Time symbols or their default-argument clocks, Runtime-managed timer polling
(D-W11-14), build files.
4. Files to inspect
include/Void/Async/{Operation,Executor,Task,TaskScope}.hpp, include/Void/Async/Detail/Types.hpp,
include/Void/Time/Clock.hpp, tests/standalone/Async/{OperationScope,Executor}.cpp (test style and
ManualExecutor/ManualClock usage), src/IO/EpollDriver.cpp:739-834 (how IO settles deadline expiry via
an injected clock on poll — pattern to mirror), docs/agent-workflow/tasks/W11-PLAN-OUTPUT.md
§M-TIME-03 and W11-PLAN-REV1-OUTPUT.md F12 (design source).
5. Write ownership and coordination
Write scope: include/Void/Async/Timer.hpp (NEW), include/Void/Time/Clock.hpp,
tests/standalone/Async/TimerQueue.cpp (NEW), tests/standalone/Async/DeadlineDomains.cpp (NEW),
tests/standalone/Time/ClockSaturation.cpp (NEW).
Forbidden: everything else, notably Executor.hpp, Operation.hpp, TaskScope.hpp,
Detail/Types.hpp, Functional headers (M-FUNCTIONAL-03 is concurrently adding
Functional/RetryState.hpp in another worktree), build files, docs. No git commit/branch/stash/reset.
6. Implementation or investigation approach
- Add Clock helpers (overflow-safe;
saturating_addclamps totime_point::max()/min();deadline_after(clock, d)=saturating_add(clock.now(), d); negativedallowed and saturates low). - Implement
TimerQueueas a stable min-heap of(deadline, seq)entries holdingshared_ptr<detail::TimerEntry>; cancelled entries become tombstones; compact when tombstones exceedmax_timersso heap size never exceeds2 × max_timers. poll_expired()readsclock().now()once, pops all due live entries in(deadline, seq)order under the lock, transitions each entry pending→fired atomically, then invokes callbacks OUTSIDE the lock. Nothing fires without an explicitpoll_expired()call; no background thread.sleep_until/sleep_forawaitables: register a timer and a stop callback; settle throughOperationState(or an equivalent single-terminal-result guard) so exactly one of {expired →{}, stop →cancelled,options.deadlineearlier →timeout,close→stopped} wins; the continuation is always resumed viaexecutor().post_completion(handle), never inline from a stop callback or frompoll_expireditself. Stop/deadline checks before admission return immediately (still via the awaitable's result, no suspension needed).close(): marks closed; every pending entry's callback runs once withTimerEvent::closed(sleepers settlestopped); laterschedule_at/sleep_*returnstopped. Destructor = close. The executor must outlive the queue (document).- Tests per §10; build/run per §11.
7. Interfaces and data contracts
namespace Void::Time { // Clock.hpp additions (NEW)
[[nodiscard]] MonotonicClock::time_point saturating_add(MonotonicClock::time_point, std::chrono::nanoseconds) noexcept;
[[nodiscard]] MonotonicClock::time_point deadline_after(const MonotonicClock&, std::chrono::nanoseconds) noexcept;
}
namespace Void::Async { // Timer.hpp (NEW)
struct TimerQueueOptions { std::size_t max_timers{1024}; }; // 0 → invalid_argument
enum class TimerEvent : std::uint8_t { expired, closed };
using TimerCallback = std::move_only_function<void(TimerEvent) noexcept>;
class TimerHandle { // move-only; holds shared_ptr<detail::TimerEntry>
public: TimerHandle() noexcept = default;
bool cancel() noexcept; // true ⇒ callback never runs; safe after queue destroyed
[[nodiscard]] bool valid() const noexcept; };
class TimerQueue { // non-copyable, non-movable
public:
using time_point = Void::Time::MonotonicClock::time_point;
[[nodiscard]] static Void::Result::Result<std::unique_ptr<TimerQueue>>
create(Executor& completion_executor, const Void::Time::MonotonicClock& clock, TimerQueueOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_until(time_point when, OperationOptions = {});
[[nodiscard]] Coro::Task<Void::Result::Result<void>> sleep_for(std::chrono::nanoseconds, OperationOptions = {});
[[nodiscard]] std::expected<TimerHandle, AdmissionError> schedule_at(time_point when, TimerCallback on_event);
[[nodiscard]] std::size_t poll_expired(); // returns callbacks fired
[[nodiscard]] std::optional<time_point> next_deadline() const;
[[nodiscard]] std::chrono::nanoseconds wait_duration(std::chrono::nanoseconds max_wait) const noexcept; // 0 if due; uses injected now
[[nodiscard]] std::size_t active_timers() const noexcept;
void close() noexcept;
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept;
[[nodiscard]] Executor& executor() noexcept;
~TimerQueue(); // = close()
};
}
Result errors use make_async_error: overloaded (at max_timers live timers), stopped (after
close), cancelled (stop token), timeout (options.deadline reached first), invalid_argument.
schedule_at returns AdmissionError::{overloaded, stopped, invalid_argument}. Callback exactly-once
rule: runs exactly once with expired or closed, or never if cancel() returned true. If
std::move_only_function is unavailable in the toolchain, report it (do not substitute silently).
8. Dependencies and integration
Upstream: M-TIME-02, M-ASYNC-02/03 (done). Downstream consumers (later steps): AsyncChannel
deadlines (M-ASYNC-04, gate G2), retry_async (B1b), IO::PumpOptions::timers (S-IO-04). Keep the
interface exactly as written. Root integrates and commits.
9. Edge cases security and performance
Stop vs poll vs close races (TSan), equal deadlines FIFO by seq, when in the past (fires on next
poll), ManualClock starting at epoch 0 and at a far-future point, never compare manual-domain
deadlines with the host clock, cancel during callback dispatch, callback that schedules a new timer
(must not deadlock: callbacks run outside the lock), destruction with pending sleepers, tombstone
growth bounded, no busy loops, no allocation per poll beyond the due batch.
10. Acceptance criteria
TimerQueue.cpp:timer_manual_advance_and_poll_fires_exactly_once,timer_equal_deadlines_fire_in_submission_order,timer_not_fired_without_explicit_poll,timer_manual_epoch_deadline_not_compared_with_host_clock,timer_manual_clock_far_future_initial_point,timer_stop_before_admission_and_pending_cancelled_once,timer_stop_vs_poll_race_single_result_tsan,timer_capacity_overloaded_and_tombstone_bounded,timer_schedule_at_cancel_vs_fire_exclusive,timer_close_settles_pending_stopped,timer_wait_duration_uses_injected_now,timer_sleep_for_saturates,timer_handle_cancel_after_queue_destroyed_safe,timer_callback_schedules_new_timer_no_deadlock— all pass.DeadlineDomains.cpp:deadline_domain_schedule_on_and_scope_admission_injected_clockanddeadline_domain_timer_and_operation_deadline_same_manual_clock(anOperationOptions.deadlinein the ManualClock domain expires asleep_untilonce only after advance + poll) — pass.ClockSaturation.cpp:clock_saturating_add_and_deadline_after_bounds— passes.- Existing
Clock,Stopwatch,OperationScope,Executor,Corotests pass unchanged. -Werrorclean; Debug TSan run of the new suites reports 0 races; ASan+UBSan 0 errors.
11. Verification commands and evidence
Cwd = your worktree root. Run dev with the sandbox disabled (dangerouslyDisableSandbox) — nix
fetcher lock fails inside it. Confirm the new suites appear in output (tests needing unselected
modules are silently skipped).
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3 -G Ninja -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3 --parallel 8 && /tmp/void-w11-time3/tests/VoidTests --filter "^(TimerQueue|DeadlineDomains|ClockSaturation|Clock|Stopwatch|OperationScope|Executor|Coro)\." && ctest --test-dir /tmp/void-w11-time3 --output-on-failure --timeout 60'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3-tsan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3-tsan --parallel 8 && /tmp/void-w11-time3-tsan/tests/VoidTests --filter "^(TimerQueue|DeadlineDomains)\."'
dev cpp-gcc -c bash -lc 'cmake -S . -B /tmp/void-w11-time3-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DVOID_ENABLED_MODULES="Async;Testing" -DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w11-time3-asan --parallel 8 && /tmp/void-w11-time3-asan/tests/VoidTests --filter "^(TimerQueue|DeadlineDomains|ClockSaturation)\."'
12. Constraints and stop conditions
No edits outside write scope; no weakened assertions or disabled warnings; no changes to existing
Async/Time semantics. Stop and report BLOCKED if the contract needs an edit to a forbidden file (e.g.
Operation.hpp), if std::move_only_function is unavailable, or a failure originates outside your files.
13. Authorization and decisions
Root decisions D-034, D-038 under user decisions D-027/D-029/D-031. Listed files only; no commits, pushes or other side effects.
14. Return format
Task ID; DONE/BLOCKED/PARTIAL; summary; files changed; decisions/deviations; evidence per acceptance criterion; commands with cwd/results (test counts, TSan/ASan outcome); checks not run; residual risks; integration notes (worktree path). Do not spawn children.