Files
Library/docs/roadmap/modules/Time.md

147 lines
9.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Time, injected clocks and measurement
Status: planning only; all feature work is **PLANNED**. Source baseline:
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
## Current source
[Time](../../../src/Time/module.cmake) has no declared dependencies.
[Stopwatch](../../../include/Void/Time/Stopwatch.hpp) uses `steady_clock`, mutable
single-writer state and an unbounded vector of laps. [Format](../../../include/Void/Time/Format.hpp)
supplies duration formatting/parsing, UTC strings and an ISO-8601 duration subset;
fractional interval seconds are truncated and calendar years/months are unsupported.
Some allocating format functions are `noexcept`, which requires migration review.
[Bench](../../../include/Void/Time/Bench.hpp) lives in `Void::Bench`, distinct from
`Void::Time`, and calls a `std::function<void()>` between two clock reads per iteration.
It records total/min/max/mean/operations-per-second and a vector-backed Suite. There
are no existing per-sample percentile, injected-clock or managed-timer contracts here.
`run_for` measures each body but checks the wall budget outside it; a body can exceed
the budget and cannot be forcibly stopped. `run` with zero iterations leaves min/max
sentinels, unlike `run_for`'s normalized empty result.
[Stopwatch](../../../tests/standalone/Time/Stopwatch.cpp),
[Time](../../../tests/standalone/Time/Time.cpp) and
[Bench](../../../tests/standalone/Time/Bench.cpp) tests cover existing behavior. Some
tests sleep/use real time; future deterministic tests must supplement those, not claim
that elapsed-time nonnegativity proves clock injection. Scoped graph coverage reported
no recorded gaps; relevant implementation and tests were read directly.
## Clock ownership and NEW shape
Time owns clocks under [C-03/C-04](../ARCHITECTURE.md); Async owns waiting, operation
options and completion. Scheduler owns calendar jobs. Runtime may retain clock objects
but Time never imports these modules. Native `std::chrono` is the initial backend.
No external timer thread or timezone service starts on inclusion or construction.
Illustrative NEW API, proposed NEW `include/Void/Time/Clock.hpp`:
```cpp
namespace Void::Time {
enum class ClockError { negative_step, overflow };
class MonotonicClock {
public:
using time_point = std::chrono::steady_clock::time_point;
virtual time_point now() const noexcept = 0;
virtual ~MonotonicClock() = default;
};
class CivilClock {
public:
virtual std::chrono::system_clock::time_point now() const noexcept = 0;
virtual ~CivilClock() = default;
};
class ManualClock final : public MonotonicClock {
public:
time_point now() const noexcept override;
std::expected<void, ClockError> advance(std::chrono::nanoseconds);
};
}
```
Native adapters return standard steady/system clock points. ManualClock starts at the
steady epoch, rejects backward steps and overflow, and publishes atomic ticks for tests.
The injected clock must have a stable lifetime through final operation shutdown. It
does not itself wake executors: a manual-time test advances the clock then explicitly
drives Async's timer backend. Backends must not compare manual clock deadlines with
the host's steady `now()`. Conversion to OS waits uses `deadline - injected.now()`;
native absolute OS deadlines are used only for a verified matching clock domain.
An expired deadline at admission fails without submitting work. This preserves Async's
standard steady time-point operation options while making clock-domain ownership explicit.
Stopwatch gains a borrowed MonotonicClock constructor and a maximum 4,096 retained laps;
`try_lap()` reports full without growing storage. Existing convenience stopwatch uses
the native adapter. Stop/start/reset semantics are specified independently: start clears
elapsed and laps, resume accumulates, and split restarts at the same sampled instant.
No operation pretends a civil-clock adjustment changes monotonic elapsed time.
## Duration, civil time and calendar work
NEW parsing accepts bounded spans (256 bytes default), uses checked accumulation in
integer nanoseconds, and returns precise error offset, invalid-unit, overflow and
unsupported-calendar-unit classifications. Preserve the old truncating ISO interval
parser as a compatibility profile; NEW exact parsing never silently truncates fractions.
Separate elapsed durations from calendar periods. UTC timestamp parse/format has fixed
precision policies (seconds/milliseconds/nanoseconds), explicit offset handling and
overflow checks. Do not persist `steady_clock::time_point`; persist civil instants,
durations or Scheduler occurrence identities with a versioned schema.
Calendar conversion uses the standard chrono timezone facility through an optional
adapter, with explicit `unsupported` if the selected toolchain/environment has no
usable database. No network download is performed. Record the timezone database version
in reproducible scheduling fixtures. Ambiguous local times require earliest/latest/reject
policy; nonexistent local times reject by default. Leap-second handling is explicit UTC
conversion policy, not hidden normalization. Scheduler owns next-occurrence recurrence
algorithms and durable admission; Time owns the conversions and their diagnostics.
## Measurement design
NEW benchmark options default to 10 warmup batches, 100 measured batches, 1,000 operations
per batch and at most 65,536 retained raw samples. Templates accept the callable directly,
avoiding mandatory `std::function` dispatch. Record both batch elapsed time and operation
count. Two modes are separate: throughput batching reports amortized time/op; latency
sampling clocks individual operations and reports p50/p95/p99 of those samples. Batch
means are never labeled individual latency percentiles.
Measure the empty harness/clock-read pair and type-erased versus templated call overhead
alongside raw results. Do not automatically subtract a noisy overhead estimate or publish
negative corrected latencies. Retain the raw baseline and explain resolution limits.
Warmup is excluded from measured samples but still charged to total wall/CPU resource
use. Exceptions stop a run with a failure and partial-run metadata. Zero iterations and
nonpositive budgets are invalid in the NEW API; the old API gets normalized zero results
for compatibility. A maximum total admission budget defaults to 30 seconds per case,
checked between batches; one arbitrary callback may overrun and this is reported.
Allocation/RSS/CPU probes are optional injected observers outside timed regions, not
global interception. Result sets cap at 1,024 cases and 16 MiB retained metadata.
## Ordered tasks
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| M-TIME-01 | P0; current source | Record parser precision, exception and bench semantics; capture empty/zero and stopwatch transition fixtures. | sol_implementer |
| M-TIME-02 | P1; M-TIME-01 | Add native/manual MonotonicClock and CivilClock adapters plus bounded stopwatch; deterministic start/resume/split and overflow tests pass. | sol_implementer |
| M-TIME-03 | P1; M-TIME-02; Functional pure retry contract | Validate injected-deadline domains with Async and blocking retry adapters; advancing manual time plus explicit polling expires an operation once. | astra_implementer |
| M-TIME-04 | P2; M-TIME-01 | Add exact duration/UTC parsing and optional timezone conversions; fractions, offsets, DST folds/gaps and unsupported database paths are explicit. | sol_implementer |
| M-TIME-05 | P2; M-TIME-02 | Add templated bounded benchmark runs, separate latency/throughput results and overhead baselines; synthetic sample quantiles and empty runs have deterministic tests. | sol_implementer |
| M-TIME-06 | P3; M-TIME-03–05 | Publish measurement methodology, compatibility adapters and isolated consumers; observed results include environment, harness cost and resource probes. | sol_implementer |
## Validation and compatibility
CURRENT verification is the linked source/tests and the parent baseline; no benchmark
or C++ test was rerun. PROPOSED tests use manual clocks, fixed sample arrays for quantile
rank definitions (nearest-rank, documented), clock-domain adapters, integer overflow,
maximum lap/sample caps and throwing bodies. Keep a small real-clock smoke test with
tolerances; do not use sleeps for logical deadline assertions. Timezone tests pin their
database fixtures and skip only with an explicit capability reason.
[PERFORMANCE](../PERFORMANCE.md) requires p50/p95/p99, throughput, allocations, peak RSS/CPU
and build cost. Benchmark infrastructure must report its own clock resolution and
overhead before supporting other modules' performance claims. Instrumentation overhead
is measured separately; passing a benchmark test establishes semantics, not speed.
[Migration](../MIGRATION.md) retains `Void::Bench` convenience names through adapters,
documents changed empty-run and allocating-noexcept behavior, and versions benchmark
output schemas. Rollback selects the prior package; persisted civil timestamps must keep
their precision/schema marker and cannot be replaced by monotonic ticks. See
[VALIDATION](../VALIDATION.md), [DELIVERY](../DELIVERY.md),
[DEPENDENCIES](../DEPENDENCIES.md), [requirements](../REQUIREMENTS.md),
[Async](Async.md) and [Scheduler](../subsystems/Scheduler.md).