Repository navigation
WTF: use GetSystemTimePreciseAsFileTime for WallTime and QPC for MonotonicTime on Windows - #304
Conversation
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.
There was a problem hiding this comment.
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:
epochBiassubtraction and/ 1e7for seconds,* 100for ns — both correct; Int128 cast before multiply avoids overflow. #if/#else/#endifnesting inside theOS(WINDOWS)block — upstream path preserved verbatim, outer#elif OS(HAIKU)chain intact.- Checked that
MonotonicTime::now()'s Windows fallback still clamps withlastTime, so losing the old 2s don't-go-backwards guard incurrentTime()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 = 116444736000000000ULLis the standard 1601→1970 offset in 100ns units.currentTime():(QuadPart - epochBias) / 10000000.0yields seconds-since-epoch as double. The divisor is adoubleconstant so the ULONGLONG numerator promotes correctly.currentTimeInNanoseconds(): cast toInt128before* 100— no overflow risk.- The
FILETIME→ULARGE_INTEGERcopy viamemcpySpan(asMutableByteSpan(...), asByteSpan(...))is byte-identical to the existinglowResUTCTime()pattern. - New path is stateless, so the thread-safety concern the PR describes (racy
staticqpcLast/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).
GetSystemTimePreciseAsFileTimeis 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.
WalkthroughChangesWindows timekeeping
🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
Source/WTF/wtf/CurrentTime.cpp
There was a problem hiding this comment.
LGTM — straightforward swap to GetSystemTimePreciseAsFileTime for Windows wall-clock, guarded behind USE(BUN_JSC_ADDITIONS).
What was reviewed:
- Unit conversions:
/ 1e7yields seconds,* 100yields nanoseconds — both match the contracts of the functions they replace. epochBiassubtraction and thememcpySpanFILETIME→ULARGE_INTEGER pattern are copied verbatim from the existinglowResUTCTime().#if / #else / #endifbracketing 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 = 10000000is correct (1s = 10⁷ × 100ns), socurrentTime()returns seconds — same unit the replaced function returned viautc / 1000.0.(QuadPart - epochBias) * 100correctly converts 100ns ticks to nanoseconds for theInt128path, and the subtraction happens inULONGLONGbefore widening so there is no overflow.- The
ULONGLONG → doubleconversion incurrentTime()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
memcpySpansequence is byte-for-byte identical to the existinglowResUTCTime()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.
There was a problem hiding this comment.
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 upstreamlowResUTCTime()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)/#endifpair 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) / 1e7yields seconds-since-1970;static_cast<Int128>(QuadPart - epochBias) * 100yields nanoseconds without overflow. ThememcpySpanFILETIME→ULARGE_INTEGER copy mirrors the existinglowResUTCTime()pattern. - The
static const double secondsPerTick = []{...}()pattern is safe here — grep confirms onlySource/JavaScriptCore/PlatformCocoa.cmakeandSource/bmalloc/PlatformCocoa.cmakeset-fno-threadsafe-statics; WTF does not. It also mirrorsmachTimebaseInfo()at line ~303. - One semantic note (not a bug):
ContinuousTime::now()now uses QPC, which does not advance during system sleep, whereasCLOCK_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 —MonotonicTimeis 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.
Preview Builds
|
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).
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).
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).
What
Under
USE(BUN_JSC_ADDITIONS)on Windows only, replace thecurrentTime()/currentTimeInNanoseconds()implementations (which backWallTime::now()) with a directGetSystemTimePreciseAsFileTimeread, and giveMonotonicTime::now()/ContinuousTime::now()/ContinuousApproximateTime::now()aQueryPerformanceCounter-based branch. The upstream code paths are kept verbatim under#elseso upstream merges stay mechanical.Why
WallTime: The upstream Windows path does
GetSystemTimeAsFileTime(15.6ms tick) plusQueryPerformanceCounterinterpolation 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 mutablestaticstate (qpcLast,syncedTime,lastUTCTime, ...) without synchronization even thoughWallTime::now()is reached from multiple threads. Bun's native wall clock already readsGetSystemTimePreciseAsFileTime(Rust'sstd::time::SystemTimeon Windows; Zig'sstd.time.milliTimestampbefore the Rust port viaRtlGetSystemTimePrecise, the ntdll call the kernel32 wrapper forwards to). Using the same API here makesDate.now()/new Date()/ Intl read the same clock asBun.randomUUIDv7(),File.lastModified, and the rest of the runtime, and drops the racy static state along with thetimeBeginPeriod(1)resolution toggle.MonotonicTime / ContinuousTime / ContinuousApproximateTime: On Windows these fall through to
#elsearms that callcurrentTime()and clamp with an unsynchronizedstatic 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 nolastTimeclamp is needed and there is no mutable static state. It also makes Windows consistent with Linux/macOS whereMonotonicTime::now()is boot-relative (CLOCK_MONOTONIC /mach_absolute_time), and aligns withperformance.now()which is already QPC-backed in Bun via Rust'sstd::time::Instant.Measured on Windows x64: with the upstream path,
Date.now()runs up to 1ms ahead ofGetSystemTimePreciseAsFileTimein ~81% of 200k back-to-back samples, which is what made Node'stest-crypto-randomuuidv7.jsflaky in oven-sh/bun#32623 (assert(uuidTimestamp >= Date.now())sampled just before the native call).GetSystemTimePreciseAsFileTimerequires Windows 8 / Server 2012, below Bun's minimum. The comment block notes aGetProcAddressfallback 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)ThreadingWincondition-variable timeout computationTimeWithDynamicClockType(ParkingLot timed waits)ConsoleMessagetimestamps,ProfilerDatabase,JSDollarVM, jsc shellCookie.cpp,BunProcess.cpp,BunCPUProfiler.cpp,BunProcessReportObjectWindows.cpp,JSMockFunction.cppcurrentTimeInNanoseconds()->ISO8601::ExactTime::now()(Temporal; this PR also makes the Windows value an integer 100ns read rather thandouble-seconds * 1e9, which is a precision improvement)MonotonicTime::now()/ContinuousTime::now()/ContinuousApproximateTime::now()(and via themApproximateTime::now()andUnbarrieredMonotonicTime::now()) move from wall-clock-clamped Unix-epoch values to QPC boot-relative values on Windows. All 54 JSC/WTFMonotonicTime::now()call sites use it for relative deltas only, and theapproximate<T>()cross-clock conversions are delta-based (this - From::now() + To::now()), so the epoch change cancels out.None of the
WallTimeconsumers depend on the 2s monotonic clamp (ECMAScript does not requireDate.now()to be monotonic, and the POSIX path here never had one). DFG/FTL modelDateNowasread(WallClock) write(WallClock)with resultSpecDoubleReal, 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
WallTimechange 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 fromjs/src/vm/Time.cpp; before it, SpiderMonkey had been dynamically loading the precise API since ~2014 with a Win7 fallback.Chromium's
base::Timewall-clock sample also callsGetSystemTimePreciseAsFileTimedirectly (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-loopTimeTicks; the wall clock path uses the precise API unconditionally. The upstream WTF path already issuesGetSystemTimeAsFileTime+QueryPerformanceCounter+GetTickCount64on 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=0x0A00inSource/cmake/OptionsWin.cmake).Benchmark
Microbenchmark of the full
currentTime()body (upstream path vs this PR),clang-cl /O2, 2M iters x 7 reps:GetSystemTimeAsFileTimeQueryPerformanceCountercurrentTime()upstreamcurrentTime()this PRThe upstream path issues three reads (
GetSystemTimeAsFileTime+QueryPerformanceCounter+GetTickCount64) plus arithmetic;GetSystemTimePreciseAsFileTimeis a single read that does the interpolation kernel-side. JS-levelDate.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 upstreamcurrentTime()+ a compare/store) to ~20.4 ns (bare QPC).