graphrag icon indicating copy to clipboard operation
graphrag copied to clipboard

[Bug]: WorkflowProfiler reports zero elapsed time on Windows with Python <= 3.12

Open yuee3 opened this issue 1 month ago • 1 comments

Describe the bug

WorkflowProfiler (and the pipeline total_runtime in run_pipeline.py) measure elapsed time with time.time(). On Windows, time.time() has a 15.6 ms resolution with Python <= 3.12 (it uses GetSystemTimeAsFileTime); CPython 3.13 switched to GetSystemTimePreciseAsFileTime with a 1 microsecond resolution (What's New in Python 3.13 - time).

Since pyproject.toml declares requires-python = ">=3.11,<3.14" but the unit-test CI matrix only runs Python 3.13, this bug is invisible to CI and affects every Windows user on Python 3.11/3.12:

  1. context.stats.workflows[name] = profiler.metrics writes overall = 0.0 for any workflow body shorter than one scheduler tick, so stats.json reports 0 ms per workflow on Windows with Python 3.11/3.12.
  2. tests/unit/indexing/test_profiling.py::TestWorkflowProfiler::test_handles_exception_in_context fails deterministically (assert 0.0 > 0), because the test body is microsecond-scale.
  3. time.time() is also a wall clock, so NTP adjustments can make elapsed/total_runtime negative or inflated; time.perf_counter() is the documented clock for measuring elapsed durations.

Steps to reproduce

On Windows with Python 3.11 or 3.12:

uv sync --all-packages
uv run pytest tests/unit/indexing/test_profiling.py

test_handles_exception_in_context fails with assert 0.0 > 0 on both 3.11.15 and 3.12.4 (verified: 11/11 pytest runs across both versions). A 300-iteration measurement of the exact try/with/raise block used by the test reports 298/300 zero elapsed values (99.3%), median 0.0, max 1.0 ms. The same test passes on Python 3.13 (3/3), which is exactly why the CI matrix (Python 3.13 only x ubuntu/windows) stays green while the supported versions fail.

Minimal clock probe on Windows, Python 3.12.4:

import time
zero = sum(
    (lambda t0: ([0] * 1000, time.time() - t0)[1] == 0.0)(time.time())
    for _ in range(200)
)
# -> 200/200 zero samples for a microsecond-scale body

Expected Behavior

WorkflowProfiler.overall and pipeline.total_runtime must be positive and monotonic regardless of Python version or OS. Elapsed-time measurement should use time.perf_counter() (high-resolution monotonic clock), per the Python docs recommendation for benchmarking.

GraphRAG Config Used

Not config-dependent; reproducible with the unit test suite alone.

Logs and screenshots

FAILED tests/unit/indexing/test_profiling.py::TestWorkflowProfiler::test_handles_exception_in_context - assert 0.0 > 0
 +  where 0.0 = WorkflowMetrics(overall=0.0, peak_memory_bytes=8480, memory_delta_bytes=8480, tracemalloc_overhead_bytes=1104).overall

Additional Information

  • GraphRAG Version: main (5faaaf4f5, post-3.3.0)
  • Operating System: Windows 11 (24H2, x64)
  • Python Version: 3.11.15, 3.12.4 (failing), 3.13.x (passing)
  • Related Issues: none found for this failure mode

I have a minimal fix ready (time.perf_counter() in profiling.py + run_pipeline.py, plus a regression test guarding positive elapsed time for sub-tick bodies) and will open a PR referencing this issue.

yuee3 avatar Oct 12 '26 05:10 yuee3

Update: the fix is ready and fully verified, but GitHub is currently blocking pull-request creation from my account (cross-fork PR requests return 404, and the web UI shows "You can't perform that action at this time"), so here is the complete patch in the meantime. I will open a proper PR as soon as the restriction lifts.

Changes (4 files, +17/-4): switch WorkflowProfiler start/elapsed capture and the pipeline total_runtime from time.time() to time.perf_counter(), add a regression test guarding positive elapsed time for sub-tick bodies, and include the semversioner patch file.

Verification on Windows 11 x64:

Environment Before After
Python 3.11.15 + Windows test_handles_exception_in_context fails 3/3 full suite green
Python 3.12.4 + Windows fails 11/11; a 300-iteration measurement of the documented block shows 99.3% zero elapsed pytest ./tests/unit = 362 passed, 1 skipped, 0 failed
Python 3.13 + Windows passes (CI) passes
uv run poe check (ruff format, ruff check, pyright) - all green

The patch below was verified to apply cleanly with git apply on current main (5faaaf4f5).

--- a/packages/graphrag/graphrag/index/run/profiling.py
+++ b/packages/graphrag/graphrag/index/run/profiling.py
@@ -34,7 +34,7 @@
     def __enter__(self) -> Self:
         """Start profiling: begin tracemalloc and record start time."""
         tracemalloc.start()
-        self._start_time = time.time()
+        self._start_time = time.perf_counter()
         return self
 
     def __exit__(
@@ -44,7 +44,7 @@
         exc_tb: TracebackType | None,
     ) -> None:
         """Stop profiling: capture metrics and stop tracemalloc."""
-        self._elapsed = time.time() - self._start_time
+        self._elapsed = time.perf_counter() - self._start_time
         self._current_memory, self._peak_memory = tracemalloc.get_traced_memory()
         self._tracemalloc_overhead = tracemalloc.get_tracemalloc_memory()
         tracemalloc.stop()

--- a/packages/graphrag/graphrag/index/run/run_pipeline.py
+++ b/packages/graphrag/graphrag/index/run/run_pipeline.py
@@ -119,7 +119,7 @@
     config: GraphRagConfig,
     context: PipelineRunContext,
 ) -> AsyncIterable[PipelineRunResult]:
-    start_time = time.time()
+    start_time = time.perf_counter()
 
     last_workflow = "<startup>"
 
@@ -145,7 +145,7 @@
                 logger.info("Halting pipeline at workflow request")
                 break
 
-        context.stats.total_runtime = time.time() - start_time
+        context.stats.total_runtime = time.perf_counter() - start_time
         logger.info("Indexing pipeline complete.")
         await _dump_stats_json(context)
         await _dump_context_json(context)

--- a/tests/unit/indexing/test_profiling.py
+++ b/tests/unit/indexing/test_profiling.py
@@ -83,6 +83,19 @@
         assert metrics.overall > 0
         assert metrics.peak_memory_bytes > 0
 
+    def test_captures_elapsed_for_fast_bodies(self):
+        """Verify a microsecond-scale body still yields positive elapsed time.
+
+        Guards against wall-clock timing: time.time() on Windows with
+        Python <= 3.12 has a 15.6 ms resolution, which collapses
+        microsecond-scale bodies to 0.0. Elapsed timing must rely on a
+        high-resolution monotonic clock.
+        """
+        with WorkflowProfiler() as profiler:
+            _ = [0] * 1000  # microsecond-scale body
+
+        assert profiler.metrics.overall > 0
+
     def test_multiple_profilers_independent(self):
         """Verify multiple profiler instances don't interfere."""
         with WorkflowProfiler() as profiler1:

--- a/.semversioner/next-release/patch-20261012031836734547.json
+++ b/.semversioner/next-release/patch-20261012031836734547.json
@@ -0,0 +1,4 @@
+{
+  "type": "patch",
+  "description": "Use time.perf_counter() for WorkflowProfiler and pipeline total_runtime so elapsed metrics stay positive and monotonic on Windows/Python <= 3.12"
+}

yuee3 avatar Oct 13 '26 04:10 yuee3