Skip to content

WTF: use GetSystemTimePreciseAsFileTime for WallTime and QPC for MonotonicTime on Windows - #304

Merged
dylan-conway merged 3 commits into
mainfrom
dylan/win-walltime-precise
Jul 17, 2026
Merged

dylan-conway merged 3 commits into
mainfrom
dylan/win-walltime-precise

Conversation

@robobun

@robobun robobun commented Jul 16, 2026 •

Copy link
Copy Markdown
Collaborator

What

Under USE(BUN_JSC_ADDITIONS) on Windows only, replace the currentTime() / currentTimeInNanoseconds() implementations (which back WallTime::now()) with a direct GetSystemTimePreciseAsFileTime read, and give MonotonicTime::now() / ContinuousTime::now() / ContinuousApproximateTime::now() a QueryPerformanceCounter-based branch. The upstream code paths are kept verbatim under #else so upstream merges stay mechanical.

Why

WallTime: The upstream Windows path does GetSystemTimeAsFileTime (15.6ms tick) plus QueryPerformanceCounter interpolation with a periodic re-sync and a 2s don't-go-backwards clamp. That interpolated value can disagree with the kernel's precise system clock by about a millisecond, and the implementation keeps mutable static state (qpcLast, syncedTime, lastUTCTime, ...) without synchronization even though WallTime::now() is reached from multiple threads. Bun's native wall clock already reads GetSystemTimePreciseAsFileTime (Rust's std::time::SystemTime on Windows; Zig's std.time.milliTimestamp before the Rust port via RtlGetSystemTimePrecise, the ntdll call the kernel32 wrapper forwards to). Using the same API here makes Date.now() / new Date() / Intl read the same clock as Bun.randomUUIDv7(), File.lastModified, and the rest of the runtime, and drops the racy static state along with the timeBeginPeriod(1) resolution toggle.

MonotonicTime / ContinuousTime / ContinuousApproximateTime: On Windows these fall through to #else arms that call currentTime() and clamp with an unsynchronized static double lastTime. That is the same bug class, and the callers (ParkingLot, SamplingProfiler, GC scheduler, DFG compiler thread) are the multi-threaded ones. Reading QPC directly is monotonic by construction so no lastTime clamp is needed and there is no mutable static state. It also makes Windows consistent with Linux/macOS where MonotonicTime::now() is boot-relative (CLOCK_MONOTONIC / mach_absolute_time), and aligns with performance.now() which is already QPC-backed in Bun via Rust's std::time::Instant.

Measured on Windows x64: with the upstream path, Date.now() runs up to 1ms ahead of GetSystemTimePreciseAsFileTime in ~81% of 200k back-to-back samples, which is what made Node's test-crypto-randomuuidv7.js flaky in oven-sh/bun#32623 (assert(uuidTimestamp >= Date.now()) sampled just before the native call).

GetSystemTimePreciseAsFileTime requires Windows 8 / Server 2012, below Bun's minimum. The comment block notes a GetProcAddress fallback is needed if Bun ever targets older Windows.

Blast radius

All of this only changes code that links into Bun (JSC + WTF, not WebCore). currentTime() reaches:

  • WallTime::now() and everything below it:
    • jsCurrentTime() (Date.now(), new Date(), Date(), Intl date-now default)
    • ThreadingWin condition-variable timeout computation
    • TimeWithDynamicClockType (ParkingLot timed waits)
    • inspector ConsoleMessage timestamps, ProfilerDatabase, JSDollarVM, jsc shell
    • Bun bindings: Cookie.cpp, BunProcess.cpp, BunCPUProfiler.cpp, BunProcessReportObjectWindows.cpp, JSMockFunction.cpp
  • currentTimeInNanoseconds() -> ISO8601::ExactTime::now() (Temporal; this PR also makes the Windows value an integer 100ns read rather than double-seconds * 1e9, which is a precision improvement)

MonotonicTime::now() / ContinuousTime::now() / ContinuousApproximateTime::now() (and via them ApproximateTime::now() and UnbarrieredMonotonicTime::now()) move from wall-clock-clamped Unix-epoch values to QPC boot-relative values on Windows. All 54 JSC/WTF MonotonicTime::now() call sites use it for relative deltas only, and the approximate<T>() cross-clock conversions are delta-based (this - From::now() + To::now()), so the epoch change cancels out.

None of the WallTime consumers depend on the 2s monotonic clamp (ECMAScript does not require Date.now() to be monotonic, and the POSIX path here never had one). DFG/FTL model DateNow as read(WallClock) write(WallClock) with result SpecDoubleReal, no assumption about monotonicity or precision. The Windows bun CI run against the preview build will be the real check.

Prior art

SpiderMonkey made the same WallTime change in July 2023 (bmo 1843842, commit): "Always use GetSystemTimePreciseAsFileTime on Windows. This was not supported on older Windows versions, but we now only support Windows 10+." That change deleted ~180 lines of the same QPC calibration machinery from js/src/vm/Time.cpp; before it, SpiderMonkey had been dynamically loading the precise API since ~2014 with a Win7 fallback.

Chromium's base::Time wall-clock sample also calls GetSystemTimePreciseAsFileTime directly (time_win.cc). Its header comment notes the API "is not always fast on some hardware and is slower than the performance counters", but that caveat is about hot-loop TimeTicks; the wall clock path uses the precise API unconditionally. The upstream WTF path already issues GetSystemTimeAsFileTime + QueryPerformanceCounter + GetTickCount64 on every call, which is more work than a single precise read.

The upstream WebKit Windows path dates to r36578 (Sep 2008); the API did not exist until Windows 8 (Oct 2012), and there are no WebKit Bugzilla entries or WebKit/WebKit issues that mention it. Upstream's minimum Windows is already Win10 1809 (_WIN32_WINNT=0x0A00 in Source/cmake/OptionsWin.cmake).

Benchmark

Microbenchmark of the full currentTime() body (upstream path vs this PR), clang-cl /O2, 2M iters x 7 reps:

GetSystemTimeAsFileTime QueryPerformanceCounter currentTime() upstream currentTime() this PR
Windows x64 (Server 2019, Hyper-V) 8.4 ns 20.4 ns 42.9 ns 32.9 ns (-23%)
Windows arm64 (Win11) 2.2 ns 26.8 ns 38.3 ns 33.8 ns (-12%)

The upstream path issues three reads (GetSystemTimeAsFileTime + QueryPerformanceCounter + GetTickCount64) plus arithmetic; GetSystemTimePreciseAsFileTime is a single read that does the interpolation kernel-side. JS-level Date.now() in the current release bun measures ~50.6 ns/op on the x64 box (Node: ~66.7 ns/op, which takes a mutex). MonotonicTime::now() goes from ~42.9 ns (same upstream currentTime() + a compare/store) to ~20.4 ns (bare QPC).

The upstream Windows implementation reads GetSystemTimeAsFileTime (15.6ms tick)
and corrects it with QueryPerformanceCounter, periodically re-syncing against
the low-resolution clock. That interpolation can disagree with the kernel's
precise system clock by about a millisecond, and it keeps mutable static state
(qpcLast, syncedTime, lastUTCTime, ...) without synchronization even though
WallTime::now() is reached from multiple threads (ThreadingWin condition-variable
timeouts, workers calling Date.now()).

Bun's native wall clock already uses GetSystemTimePreciseAsFileTime (Rust's
std::time::SystemTime on Windows, and Zig's std.time.milliTimestamp before the
Rust port via RtlGetSystemTimePrecise). Using the same API here makes
Date.now() / new Date() / Intl read the same clock as Bun.randomUUIDv7(),
File.lastModified, and the rest of the runtime, and drops the racy static state
along with the timeBeginPeriod(1) resolution toggle.

GetSystemTimePreciseAsFileTime is available on Windows 8 / Server 2012 and
later, which is already below Bun's minimum supported Windows version.

Gated behind USE(BUN_JSC_ADDITIONS); the upstream path is kept verbatim under
the #else so upstream merges stay mechanical.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find any bugs — the arithmetic checks out and the memcpySpan idiom matches lowResUTCTime(). Deferring to a human because this swaps the clock source behind WallTime::now() on Windows, which is a foundational path (Date.now(), ParkingLot timed waits, ThreadingWin CV timeouts), and on Windows MonotonicTime::now() / ContinuousTime::now() also fall through to currentTime() — a bit more blast radius than the description enumerates.

What was reviewed:

  • Unit conversions: epochBias subtraction and / 1e7 for seconds, * 100 for ns — both correct; Int128 cast before multiply avoids overflow.
  • #if/#else/#endif nesting inside the OS(WINDOWS) block — upstream path preserved verbatim, outer #elif OS(HAIKU) chain intact.
  • Checked that MonotonicTime::now()'s Windows fallback still clamps with lastTime, so losing the old 2s don't-go-backwards guard in currentTime() doesn't regress it.
Extended reasoning...

Overview

The PR replaces the Windows currentTime() / currentTimeInNanoseconds() implementation in Source/WTF/wtf/CurrentTime.cpp with a direct GetSystemTimePreciseAsFileTime read, gated under USE(BUN_JSC_ADDITIONS). The upstream QPC-interpolation path (with its unsynchronized static state and timeBeginPeriod toggle) is kept under #else. Net addition is ~35 lines, all Windows-only.

Correctness

The implementation is straightforward and I believe correct:

  • epochBias = 116444736000000000ULL is the standard 1601→1970 offset in 100ns units.
  • currentTime(): (QuadPart - epochBias) / 10000000.0 yields seconds-since-epoch as double. The divisor is a double constant so the ULONGLONG numerator promotes correctly.
  • currentTimeInNanoseconds(): cast to Int128 before * 100 — no overflow risk.
  • The FILETIME → ULARGE_INTEGER copy via memcpySpan(asMutableByteSpan(...), asByteSpan(...)) is byte-identical to the existing lowResUTCTime() pattern.
  • New path is stateless, so the thread-safety concern the PR describes (racy static qpcLast/syncedTime/lastUTCTime) is genuinely eliminated.

One thing the PR description's blast-radius list doesn't mention: on Windows, MonotonicTime::now(), ContinuousTime::now(), and ContinuousApproximateTime::now() all fall through to the final #else branch and call currentTime() (there is no QPC-based MonotonicTime on Windows in this file). So those also switch clock source. This isn't a regression — the old path was also wall-clock-derived and the static double lastTime clamp in those functions still handles backward jumps — but it widens the effective surface beyond WallTime::now().

Security risks

None. No untrusted input, no parsing, no allocation. Pure syscall + arithmetic.

Level of scrutiny

Medium-high. The code change is mechanically simple, but currentTime() sits under Date.now(), ThreadCondition::timedWait deadline computation, ParkingLot timed waits, and (on Windows) MonotonicTime::now(). Swapping the clock source for all of that is the kind of change a human maintainer should consciously sign off on, and the author themselves notes the Windows Bun CI run is "the real check".

Other factors

  • Well-motivated with measurements (81% of samples showed ~1ms skew vs the precise clock, causing real test flakiness).
  • GetSystemTimePreciseAsFileTime is the standard modern Win32 API for this; Rust's stdlib and Chromium both use it. Windows 8+ requirement is below Bun's minimum.
  • No prior review comments on the PR to consider.

Deferring rather than approving purely on blast-radius grounds; I have no correctness concerns with the diff itself.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Changes

Windows timekeeping

Layer / File(s) Summary
Precise FILETIME time path
Source/WTF/wtf/CurrentTime.cpp
Adds currentTime() and currentTimeInNanoseconds() implementations using GetSystemTimePreciseAsFileTime, FILETIME conversion, and epoch adjustment under USE(BUN_JSC_ADDITIONS).
🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change well, but it omits required template items like the Bugzilla link, Reviewed by line, and commit-message file list. Add the Bugzilla bug link/title, a Reviewed by line, and the template-style file/function list so the PR description matches the repository format.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the Windows timing change to use GetSystemTimePreciseAsFileTime for WallTime::now().

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Source/WTF/wtf/CurrentTime.cpp`:
- Line 95: Update the time conversion expressions in the relevant functions at
the lines corresponding to the shown return and the other conversions at 107 and
129 so dateTime.QuadPart and epochBias are converted to Int128 before
subtraction. Perform division or multiplication only after the signed
subtraction, preserving correct results for pre-1970 timestamps.
- Around line 86-95: Update MonotonicTime::now() and ContinuousTime::now() so
they no longer fall back to currentTime(), which is based on
GetSystemTimePreciseAsFileTime; restore or reuse a QueryPerformanceCounter-based
source for these APIs, while retaining currentTime() exclusively for WallTime.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 18ed7762-bed4-4013-a877-419b80822700

📥 Commits

Reviewing files that changed from the base of the PR and between e5f7fc2 and ca4595f.

📒 Files selected for processing (1)
  • Source/WTF/wtf/CurrentTime.cpp

Comment thread Source/WTF/wtf/CurrentTime.cpp Resolved
Comment thread Source/WTF/wtf/CurrentTime.cpp Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — straightforward swap to GetSystemTimePreciseAsFileTime for Windows wall-clock, guarded behind USE(BUN_JSC_ADDITIONS).

What was reviewed:

  • Unit conversions: / 1e7 yields seconds, * 100 yields nanoseconds — both match the contracts of the functions they replace.
  • epochBias subtraction and the memcpySpan FILETIME→ULARGE_INTEGER pattern are copied verbatim from the existing lowResUTCTime().
  • #if / #else / #endif bracketing leaves the upstream QPC path intact for non-Bun builds and closes cleanly before #elif OS(HAIKU).
  • Win8+ API requirement is documented; Bun's minimum is Win10 so no runtime fallback is needed.
Extended reasoning...

Overview

This PR replaces the Windows implementation of WTF::currentTime() and WTF::currentTimeInNanoseconds() (which back WallTime::now() and ultimately Date.now()) with direct calls to GetSystemTimePreciseAsFileTime, gated behind #if USE(BUN_JSC_ADDITIONS). The upstream implementation — a ~120-line dance combining GetSystemTimeAsFileTime (15.6ms resolution) with QueryPerformanceCounter drift correction and unsynchronized static state — is preserved verbatim in the #else branch. Only Source/WTF/wtf/CurrentTime.cpp is touched.

Security risks

None. This reads a system clock via a documented Win32 API with no inputs. There is no user-controlled data, no parsing, no allocation, and no shared mutable state (the new path actually removes the thread-unsafe statics present in the upstream path).

Level of scrutiny

Low-to-moderate. It is platform-utility code with well-defined semantics, and the change is essentially the same one SpiderMonkey (bmo-1843842) and V8 made years ago. The things that could go wrong are unit errors and preprocessor bracketing, both of which check out:

  • hundredsOfNanosecondsPerSecond = 10000000 is correct (1s = 10⁷ × 100ns), so currentTime() returns seconds — same unit the replaced function returned via utc / 1000.0.
  • (QuadPart - epochBias) * 100 correctly converts 100ns ticks to nanoseconds for the Int128 path, and the subtraction happens in ULONGLONG before widening so there is no overflow.
  • The ULONGLONG → double conversion in currentTime() loses at most ~1 bit at current timestamps (~200ns), well within the sub-microsecond precision claimed and far better than the 15.6ms/QPC hybrid it replaces.
  • The FILETIME → ULARGE_INTEGER memcpySpan sequence is byte-for-byte identical to the existing lowResUTCTime() body two lines below.

Other factors

The change is small (~40 lines added), additive (old code kept under #else), well-commented with rationale and an explicit note about the Win8+ requirement, and consistent with what Bun's Zig/Rust native side already uses — which is the stated motivation (making Date.now() agree with native timestamps). The bug-hunting pass found nothing. No PR timeline was available, but the two commits (implementation + follow-up comment about pre-Win8 fallback) are both reflected in the diff.

…() a QPC-based Windows branch

On Windows these three functions fall through to the #else arms, which call
currentTime() (wall clock) and clamp with an unsynchronized static double
lastTime. That is the same bug class as the one removed from currentTime()
in the previous commit, and the callers (ParkingLot, SamplingProfiler, GC
scheduler, DFG compiler thread) are the multi-threaded ones.

Under USE(BUN_JSC_ADDITIONS) on Windows, read QueryPerformanceCounter
directly for all three. QPC is monotonic by construction so no lastTime
clamp is needed, and there is no mutable static state (the frequency
reciprocal is a thread-safe-initialized const). This also makes Windows
consistent with Linux/macOS where MonotonicTime::now() is boot-relative
(CLOCK_MONOTONIC / mach_absolute_time), not Unix-epoch-relative, and
aligns with performance.now() which is already QPC-backed in Bun via
Rust's std::time::Instant.

The approximate<T>() clock conversions are delta-based
(this - FromClock::now() + ToClock::now()), so the epoch change cancels
out. All 54 JSC/WTF MonotonicTime::now() call sites use it for relative
deltas only.
@robobun robobun changed the title WTF: use GetSystemTimePreciseAsFileTime for WallTime::now() on Windows WTF: use GetSystemTimePreciseAsFileTime for WallTime and QPC for MonotonicTime on Windows Jul 16, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find any bugs — the arithmetic checks out and the thread-safe static pattern matches machTimebaseInfo() in the same file — but this swaps out the Windows implementation of WallTime::now() / MonotonicTime::now() and friends, which back Date.now(), GC/JIT timing, and the event loop. Given the blast radius, worth a human sign-off.

What was reviewed:

  • currentTime() / currentTimeInNanoseconds(): epoch-bias subtraction and 100ns→s / 100ns→ns conversions match the upstream lowResUTCTime() math.
  • qpcSeconds(): local-static init is thread-safe in WTF (only JSC/bmalloc build with -fno-threadsafe-statics), so no init race.
  • Preprocessor nesting: the #else // !USE(BUN_JSC_ADDITIONS) / #endif pair closes cleanly before #elif OS(HAIKU); non-Bun Windows path is unchanged.
Extended reasoning...

Overview

PR #304 adds a USE(BUN_JSC_ADDITIONS)-gated Windows branch to Source/WTF/wtf/CurrentTime.cpp. It replaces the upstream Windows wall-clock path (which stitches together GetSystemTimeAsFileTime + QueryPerformanceCounter with drift correction and unsynchronized mutable statics) with a direct call to GetSystemTimePreciseAsFileTime, and gives MonotonicTime / ContinuousTime / ContinuousApproximateTime a proper QueryPerformanceCounter-based implementation instead of the wall-clock-clamped fallback. The PR spans three commits and ~70 added lines in one file.

Security risks

None. These are read-only calls to standard Win32 time APIs with no user-controlled input, no allocation, and no external I/O.

Level of scrutiny

High. WallTime::now() backs Date.now() and MonotonicTime::now() is used pervasively for GC scheduling, JIT tier-up heuristics, sampling profiler timestamps, watchdog timeouts, and Bun's event loop timers. A subtle unit or epoch error here would affect every Windows Bun process. The code itself is straightforward and well-commented, but the blast radius means a maintainer familiar with Bun's Windows support (and its Windows 8+ minimum, given the GetSystemTimePreciseAsFileTime hard dependency) should confirm.

Other factors

  • The arithmetic was verified: (QuadPart - epochBias) / 1e7 yields seconds-since-1970; static_cast<Int128>(QuadPart - epochBias) * 100 yields nanoseconds without overflow. The memcpySpan FILETIME→ULARGE_INTEGER copy mirrors the existing lowResUTCTime() pattern.
  • The static const double secondsPerTick = []{...}() pattern is safe here — grep confirms only Source/JavaScriptCore/PlatformCocoa.cmake and Source/bmalloc/PlatformCocoa.cmake set -fno-threadsafe-statics; WTF does not. It also mirrors machTimebaseInfo() at line ~303.
  • One semantic note (not a bug): ContinuousTime::now() now uses QPC, which does not advance during system sleep, whereas CLOCK_BOOTTIME (the Linux branch) does. This is no worse than the prior wall-clock fallback and likely irrelevant for Bun's use, but worth the author being aware of.
  • MonotonicTime::now() changes epoch on Windows (from wall-clock-derived to boot-relative). This is fine — MonotonicTime is only meaningful as a delta — but it's a behavioral change nonetheless.
  • No PR timeline was available from the API, so I could not check for prior review comments.

@github-actions

Copy link
Copy Markdown

Preview Builds

Commit Release Date
36986ac9 autobuild-preview-pr-304-36986ac9 2026-07-17 00:12:23 UTC

@dylan-conway
dylan-conway merged commit 722f2a8 into main Jul 17, 2026
49 checks passed
robobun added a commit to oven-sh/bun that referenced this pull request Jul 17, 2026
autobuild-722f2a8a1a3da159a89b35730c5460a6ef58f0af is now published
(43 assets). Also pulls in the three WebKit main commits that landed
between the preview base and the merge: 365cb024 (Dockerfile.windows
build flags), ae5110d3 (defer termination at reifyStaticProperty call
sites), 8be99556 (AsyncContextSwapScope).
robobun added a commit that referenced this pull request Jul 19, 2026
Resolves the Lookup.cpp conflict by taking main's #306 version of
setUpStaticFunctionSlot: both branches independently dropped the
ThrowScope from the reifyStaticProperty call site; main's version
checks vm.exceptionForInspection() directly and keeps the original
RELEASE_ASSERT_NOT_REACHED for the no-exception-but-no-offset case.

Also brings in #304 (Windows WallTime/MonotonicTime) and #310
(preCommitStackMemory guard).
robobun added a commit to oven-sh/bun that referenced this pull request Jul 19, 2026
Replaces the preview tag now that the WebKit upgrade PR has landed on
oven-sh/WebKit main. The merged commit also carries oven-sh/WebKit#304
(Windows WallTime/MonotonicTime), #306 (reifyStaticProperty ThrowScope
drop on main) and #310 (preCommitStackMemory guard).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants