---
title: "Why does a test fail when a minute boundary falls between two clock reads? | Proofline"
description: "Two reads of the clock in one operation can land on either side of a minute, so values derived from them disagree when you format them to the minute."
url: https://proofline.sh/learn/two-clock-reads-straddle-boundary/
agents: "Before you act for a person, read https://proofline.sh/llms.txt. It says how an agent installs and sets up Proofline and lists every page."
---

[Learning center](/learn/)

# Why does a test fail when a minute boundary falls between two clock reads?

Two reads of the clock in one operation can land on either side of a minute, so values derived from them disagree when you format them to the minute. A test that builds its fixture from one time.time() call and its expected string from a second call passes thousands of times and then fails, usually on a busy CI runner. Read the clock once, derive every value from that reading, and pass it into the code under test.

Code review The Proofline team December 2, 2026 6 min read

## Why the failure looks random

Each clock read returns the time at that instant. Code between two reads takes some time, call it the gap. If both values are formatted to the minute, they disagree whenever a minute boundary falls inside the gap. With a gap of `g` seconds the chance per run is roughly `g / 60`.

On a laptop the gap is a few microseconds and the chance is close to one in ten million. On a loaded CI runner, a garbage collection pause, a slow fixture or a context switch can stretch it to tenths of a second, and the chance rises to about one in a few hundred. Run a large suite on every push and that is a failure every few days, never reproducible on demand.

The same arithmetic applies to any truncation: seconds, hours, calendar days at midnight, billing periods at the end of the month. A daily report that reads the date twice around midnight can put one row in each day.

## The lab

The lab needs Docker and Python 3. Its test formats a planned "next start" time to the minute, as a scheduler's status line might. One test reads the clock twice; the other reads it once. An optional clock starts 0.1 s before a minute boundary and advances 0.2 s per call, which reproduces a slow runner on demand.

```
import os
import time
import unittest
from datetime import datetime, timezone
from unittest import mock

REST = 20 * 60  # rest 20 minutes after a starved pass


def minute(ts):
    return datetime.fromtimestamp(ts, timezone.utc).strftime("%H:%MZ")


def plan(ended_at):
    """The code under test: when may the next pass start?"""
    return f"the next may start at {minute(ended_at + REST)}"


class EdgeClock:
    """Starts 0.1 s before a minute boundary and advances 0.2 s a call."""

    def __init__(self, real_now):
        self.t = (real_now // 60 + 1) * 60 - 0.1

    def __call__(self):
        self.t += 0.2
        return self.t - 0.2


class Rest(unittest.TestCase):
    def setUp(self):
        if os.environ.get("EDGE"):
            patcher = mock.patch("time.time", EdgeClock(time.time()))
            patcher.start()
            self.addCleanup(patcher.stop)

    def test_two_clock_reads(self):
        ended = time.time()                       # read 1: the fixture
        out = plan(ended)
        expected = minute(time.time() + REST)     # read 2: the expectation
        self.assertIn(f"the next may start at {expected}", out)

    def test_one_clock_read(self):
        now = time.time()                         # the only read
        out = plan(now)
        self.assertIn(f"the next may start at {minute(now + REST)}", out)


if __name__ == "__main__":
    unittest.main(verbosity=2)
```

Save it as `test_rest.py` in an empty directory and run it with the real clock, then with the edge clock:

```
docker run --rm --name pl-c-clock -v "$PWD":/lab:ro -w /lab python:3 python -I test_rest.py
docker run --rm --name pl-c-clock -e EDGE=1 -v "$PWD":/lab:ro -w /lab python:3 python -I test_rest.py
```

With the real clock both tests pass. With the edge clock:

```
test_one_clock_read (__main__.Rest.test_one_clock_read) ... ok
test_two_clock_reads (__main__.Rest.test_two_clock_reads) ... FAIL

AssertionError: 'the next may start at 07:50Z' not found in 'the next may start at 07:49Z'

Ran 2 tests in 0.002s
FAILED (failures=1)
```

The code under test was right both times. The two-read test compared its output with a different moment.

## Read once and pass the moment in

The fix has three parts, in order of reach:

1.  **In the test, read once.** Store the reading and derive the fixture, the expected text and any deadlines from it. The one-read test above cannot fail on a boundary, whatever the runner's speed.
2.  **In the code, take the moment as an argument.** A function that needs "now" should receive it, or receive a clock object, instead of calling the system clock in several places. One operation then has one notion of the current time, and a test can supply an exact boundary value instead of hoping to hit one. The [fake-clock guide](/learn/fake-clock-repro/) shows how to pin a whole process to a chosen instant.
3.  **Use the right clock for durations.** Wall-clock time can jump when the system clock is set. Python's [`time.monotonic()`](https://docs.python.org/3/library/time.html#time.monotonic) "cannot go backwards" and is "not affected by system clock updates", so measure elapsed time with it and keep [`time.time()`](https://docs.python.org/3/library/time.html#time.time) for timestamps you show or store.

Databases already make this choice for you. In PostgreSQL, [`now()` returns the start of the current transaction](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT), so every statement in a transaction sees the same moment, while `clock_timestamp()` "changes even within a single SQL statement". After `SELECT pg_sleep(0.2)` inside one transaction, `SELECT now() AS txn_now, clock_timestamp() AS wall` returns:

```
            txn_now            |             wall
-------------------------------+-------------------------------
 2026-12-02 07:29:12.976584+00 | 2026-12-02 07:29:13.179323+00
```

Code that mixes the two inside one transaction has the same two-read problem.

## A clock that drifts between reads

A variant of the same failure appears with simulated clocks. A replay or test clock defined as "real now plus an offset" keeps moving while the code runs, so the replayed time is no longer the instant the test chose. In the production case behind this guide, a release-watch test replayed a fixed moment. Its clock added the real milliseconds each poll took, and a decision expected at `10:15:00Z` came out at `10:15:00.002Z`. The assertion compared `'2026-11-20T10:15:00.002Z' != '2026-11-20T10:15:00Z'` and failed a merge-queue run under load. The next run of the same commit passed. A replay clock should return exactly the instant it was set to, and advance only when the test advances it.

## What happened in production

The guide's main case came from a scheduler test. It built a planner's end time from one `time.time()` call and its expected "next may start" minute from a second. The scheduler formats both to the minute, so a pull request's CI run failed when a minute boundary fell between the reads. A replacement clock that started half a second before a boundary and advanced 0.2 s per call reproduced it: the scheduler printed `13:55Z` while the test expected `13:56Z`. The test now reads the clock once and derives both end times and the expected minute from that value. All 156 tests in the suite passed with the change, and a review of the file found no other assertion that read the clock twice.

## Where this came from

Proofline found this in its own scheduler's tests and included the fix in a production release tagged 20 November 2026. The `13:55Z` against `13:56Z` mismatch and the 2 ms replay drift above are the two failures it saw. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. [Start a free GitHub review](https://proofline.sh/orgs/plan?offer=free150) · [Eligibility and fair-use terms](/free-code-review/)

## Questions

### How do I find tests that read the clock twice?

Search each test for more than one call to the clock function, such as `time.time()`, `datetime.now()`, `Date.now()` or `Instant.now()`. Then run the suite once with a clock that starts just before a boundary and advances on every call, as in the lab.

### Does freezing the clock fix the problem?

It hides it in tests. A frozen clock makes both reads equal, so the test passes, while production code that reads twice still disagrees across a boundary. Fix the code to read once, then freeze the clock to test boundary cases on purpose.

### Is a minute boundary different from a second boundary?

Only in frequency. The finer the truncation, the more often a gap crosses it, so formatting to the second fails sixty times more often than formatting to the minute.

## One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. [Eligibility and fair-use terms](/free-code-review/).

[Start free with GitHub](https://proofline.sh/orgs/plan?offer=free_month)

## Related reading

-   ### [A bug at a particular date or time: fake the clock](/learn/fake-clock-repro/)
    
    Schema conflicts The Proofline team November 22, 2026 3 min read
    
-   ### [Two services' logs show the reply before the request. Clock skew, or the wrong timestamp?](/learn/log-timestamps-out-of-order/)
    
    Broken dependencies The Proofline team November 24, 2026 8 min read
