Python
fix(observability): time steps with perf_counter, which ticks every millisecond on Windows (OPE-244)
Devika Verma22e8c889c043
diff --git a/coworker/observability/recorder.py b/coworker/observability/recorder.pyindex 86c86a56..11012e46 100644--- a/coworker/observability/recorder.py+++ b/coworker/observability/recorder.py@@ -130,8 +130,11 @@ def _merge_top(into: dict[str, Any], new: Optional[dict[str, Any]]) -> None:def now_ms() -> tuple[int, int]:- """(at_ms, mono_ms) for an event sent now."""- return time.time_ns() // 1_000_000, time.monotonic_ns() // 1_000_000+ """(at_ms, mono_ms) for an event sent now.++ `mono_ms` uses `perf_counter`, which is monotonic too: on Windows `time.monotonic` only+ ticks every 15.6 ms, so a short tool step read 0 or 16 ms there."""+ return time.time_ns() // 1_000_000, time.perf_counter_ns() // 1_000_000def new_turn_id() -> str:diff --git a/tests/test_observability_store.py b/tests/test_observability_store.pyindex 9501c108..6c22d960 100644--- a/tests/test_observability_store.py+++ b/tests/test_observability_store.py@@ -11,6 +11,7 @@ import pytestfrom coworker.observability import Recorder, RecordingStore, new_ulidfrom coworker.observability import store as store_mod+from coworker.observability.recorder import now_msDAY_MS = 24 * 60 * 60 * 1000@@ -262,3 +263,12 @@ def test_ulids_sort_by_creation_and_never_repeat():assert len(set(ids)) == 5000assert ids == sorted(ids)assert all(len(i) == 26 for i in ids)+++def test_the_step_clock_ticks_every_millisecond():+ # Windows' time.monotonic ticks every 15.6 ms; durations need millisecond steps.+ first = now_ms()[1]+ deadline = time.perf_counter() + 0.2+ while (tick := now_ms()[1]) == first and time.perf_counter() < deadline:+ pass+ assert tick - first == 1