JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(server): add a per-stage timer for hot-path breakdowns
alan_chengf5d805ed13fb
diff --git a/jiuwenswarm/common/stage_timer.py b/jiuwenswarm/common/stage_timer.pynew file mode 100644index 0000000000..2712686a0a--- /dev/null+++ b/jiuwenswarm/common/stage_timer.py@@ -0,0 +1,69 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Per-stage timing for a linear sequence of steps on a hot path.++Written for the places where a single log line reports one aggregate number+("prepare_ms=136.1") and the next question is always "which step". Marking each+step turns that one number into a breakdown without scattering timestamp+bookkeeping through the code being measured.++The renderer emits stages in execution order and keeps the whole breakdown on+one line, so a slow turn can be read straight out of the log stream.+"""++from __future__ import annotations++import time+++class StageTimer:+ """Accumulate elapsed time per named stage of one pass through a code path.++ Not thread-safe and not reusable across passes: construct one per pass, at+ the point where the measured work begins.+ """++ def __init__(self) -> None:+ """Start the clock for the first stage."""+ self._started_at = time.monotonic()+ self._stage_started_at = self._started_at+ self._stages: list[tuple[str, float]] = []++ def mark(self, stage: str) -> None:+ """Close the current stage and open the next one.++ Args:+ stage: Name of the stage that just finished. Repeat names are kept+ as separate entries rather than merged, so a loop that marks the+ same name shows each pass.+ """+ now = time.monotonic()+ self._stages.append((stage, (now - self._stage_started_at) * 1000))+ self._stage_started_at = now++ def total_ms(self) -> float:+ """Return milliseconds elapsed since construction.++ Returns:+ Total elapsed time, including any work after the last ``mark``.+ """+ return (time.monotonic() - self._started_at) * 1000++ def render(self, *, slowest_first: bool = False) -> str:+ """Render the recorded stages as a single-line ``name=ms`` breakdown.++ Args:+ slowest_first: Order stages by descending duration instead of+ execution order. Useful when the caller only logs a breakdown+ because something was slow.++ Returns:+ Space-separated ``name=ms`` pairs, empty when nothing was marked.+ """+ stages = list(self._stages)+ if slowest_first:+ stages.sort(key=lambda item: item[1], reverse=True)+ return " ".join(f"{name}={elapsed_ms:.1f}" for name, elapsed_ms in stages)+++__all__ = ["StageTimer"]diff --git a/tests/unit_tests/common/test_stage_timer.py b/tests/unit_tests/common/test_stage_timer.pynew file mode 100644index 0000000000..00d4791782--- /dev/null+++ b/tests/unit_tests/common/test_stage_timer.py@@ -0,0 +1,75 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for the per-stage hot-path timer."""++from __future__ import annotations++import pytest++from jiuwenswarm.common.stage_timer import StageTimer++[email protected](name="fake_clock")+def _fake_clock(monkeypatch: pytest.MonkeyPatch):+ """Drive the timer off a hand-advanced clock so timings are exact."""+ now = {"t": 100.0}+ monkeypatch.setattr("jiuwenswarm.common.stage_timer.time.monotonic", lambda: now["t"])++ def advance(seconds: float) -> None:+ now["t"] += seconds++ return advance+++def test_stages_render_in_execution_order(fake_clock) -> None:+ """The breakdown reads in the order the code ran, not by size."""+ timer = StageTimer()+ fake_clock(0.010)+ timer.mark("first")+ fake_clock(0.250)+ timer.mark("second")+ fake_clock(0.005)+ timer.mark("third")++ assert timer.render() == "first=10.0 second=250.0 third=5.0"+++def test_slowest_first_reorders_by_duration(fake_clock) -> None:+ """The slow-path log wants the offender first."""+ timer = StageTimer()+ fake_clock(0.010)+ timer.mark("first")+ fake_clock(0.250)+ timer.mark("second")++ assert timer.render(slowest_first=True) == "second=250.0 first=10.0"+++def test_total_includes_work_after_the_last_mark(fake_clock) -> None:+ """Trailing work must not vanish from the total."""+ timer = StageTimer()+ fake_clock(0.010)+ timer.mark("first")+ fake_clock(0.040)++ assert timer.total_ms() == pytest.approx(50.0)+++def test_render_is_empty_when_nothing_was_marked(fake_clock) -> None:+ """A pass that fails before the first mark still renders cleanly."""+ timer = StageTimer()+ fake_clock(0.030)++ assert timer.render() == ""+ assert timer.total_ms() == pytest.approx(30.0)+++def test_repeated_stage_names_are_kept_separate(fake_clock) -> None:+ """A loop marking one name shows each pass rather than merging them."""+ timer = StageTimer()+ fake_clock(0.001)+ timer.mark("step")+ fake_clock(0.002)+ timer.mark("step")++ assert timer.render() == "step=1.0 step=2.0"