Repository navigation
Updated timestamp handling and API - #414
Merged
Merged
Conversation
Drop quark_update_boottime() and quark_time_to_wallclock(). Callers should fetch the epoch once per batch with quark_get_boottime() and translate to wallclock with plain addition. This puts the freshness burden on the library instead of the user, but still allows external handling of boottime without needing to call quark_get_boottime() for callers that want this (e.g. freeze boottime to a particular boot id). The epoch is now CLOCK_REALTIME minus CLOCK_BOOTTIME instead of btime from /proc/stat which is the same quantity truncated to seconds. Wallclock translations are no longer biased for up to one second, improving event correlation accuracy. Refreshing the epoch no longer costs a /proc/stat read and parse. quark_get_boottime() keeps itself fresh: it resamples at most every 10ms, timed with CLOCK_MONOTONIC_COARSE since CLOCK_BOOTTIME is a syscall on kernels before 5.3, and only adopts a sample that strays more than 10ms from the adopted epoch, filtering jitter across calls. Concurrent adopters converge through a compare-and-swap. quark_init() primes the epoch and fails the queue open if it cannot be sampled, as it did with btime. clock_diff() replaces fetch_boottime() and the kprobe boot_offset() logic.
The C functions behind them are gone, quark_get_boottime() now keeps the epoch fresh on its own. Boottime() remains and is the whole API: fetch it once per batch and add it to the boottime timestamps. This also removes the per-event TimeToWallclock cgo call overhead.
Co-authored-by: Nicholas Berlin <56366649+nicholasberlin@users.noreply.github.com>
nicholasberlin
previously approved these changes
Sep 4, 2026
Member
Author
|
Let's keep this PR unmerged for now, until I open -at least- a PR for Cloud Defend. |
3 of 6 tasks
Member
Author
|
@nicholasberlin I think we can merge this now, all the dependent PRs are open, and then I can work towards a 0.9 release. |
nicholasberlin
approved these changes
Sep 23, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Most event times quark hands out are nanoseconds-since-boot (
CLOCK_BOOTTIME). To translate them to wallclock (CLOCK_REALTIME) one needs to add the boottime epoch, which is the wallclock time at which the machine booted. Previously, this was retrieved from thebtimefield in /proc/stat which encodes seconds-since-the-epoch. This PR simplifies the boottime epoch API to a single self-maintaining function:quark_update_boottime(3)andquark_time_to_wallclock(3)are removed.quark_get_boottime(3)remains and is the whole API: fetch the epoch, add it to a time-since-boot.CLOCK_REALTIMEminusCLOCK_BOOTTIMEinstead of thebtimefield of /proc/stat. It gains nanosecond resolution and no longer needs a refresh call to track clock steps.UpdateBoottimeandTimeToWallclock.Boottimeremains, callers can fetch it once per batch and add it to time-since-boot timestamps.clock_diffhelper replaces both the epoch fetch and the kprobe backend's suspend offset loop. The kprobe refresh in populate is throttled the same way as the epoch.Motivation
Accuracy:
btimeis the same realtime minus boottime difference, truncated to whole seconds. Every wallclock time quark produced was therefore inaccurate by a fixed amount between 0 and 1s (due to truncation) for the lifetime of the boot (there used to be an additional source of potential inaccuracy that could exceed 1s, due to the tight coupling betweenupdate_boottimeandtime_to_wallclock, see "Freshness" below). When correlating quark events against anything stamped withCLOCK_REALTIMEthis is enough to invert the order of nearby events. The new epoch carries the full sub-second resolution.Freshness: Quark fetched the old epoch once when the first queue opened and updated it only if the caller remembered to call the update function. An agent that starts before NTP syncs, which is the normal boot order, would convert every time wrongly by the size of the correction until the update function was called. Now there is no update function to call, as this happens inside the self-maintaining
quark_get_boottimethat the user who wants to translate boot-to-wallclock with the help of this library has to call anyway. Most importantly, the class of errors where the update function isn't called or called late disappears.Cost: A
/proc/statopen-read-parse is far more expensive than it looks. On older kernels, it allocates a buffer sized by CPU and IRQ count, walks every possible CPU, and sums every IRQ over every CPU, under a global mutex. This cost was paid on every refresh. The Go bindings additionally paid a cgo call for every converted timestamp./proc/stat, old refreshquark_get_boottime()common path, newquark_time_to_wallclock(), old, atomic load and addSimplicity: Three public functions become one, with no ordering constraint.
Flexibility: One can still manage boottime externally in an entirely custom manner (this excludes the ECS logic which performs boottime-to-wallclock conversions internally, I did not change that in this PR to avoid further API changes).
Trade-offs
CLOCK_MONOTONIC_COARSEread plus an atomic load. This is the price of self-maintenance and is negligible next to any per-event work. Callers converting a batch should still fetch once, as documented.CLOCK_BOOTTIMEis a syscall on kernels before 5.3, which is why we throttle sampling: with continuousquark_get_boottimecalls, three syscalls per 10 ms is about 0.03% of one CPU, versus three per call without the throttle. Of course, one has no reason to continuously callquark_get_boottimeas the output is highly stable, but the throttling is there for a worst-case bound. Static linking does not affect this, the vDSO is found through the auxiliary vector either way.Cloud Defendonce we have consensus about this PR.How
quark_get_boottimebehavesIt keeps a single process-wide epoch and maintains it in three steps:
CLOCK_MONOTONIC_COARSEand returns the adopted epoch unless 10 ms have passed since the last sample. This is the common path, one vDSO read and one atomic load, about 8 ns.CLOCK_MONOTONIC_COARSEis present in the vDSO in all Linux kernel versions Quark is expected to run on.clock_diffreadsCLOCK_BOOTTIMEthenCLOCK_REALTIMEand takes the smallest of three differences. Tens of nanoseconds if served from the vDSO (kernels 5.3+).Slew versus step: Time daemons correct clocks by slewing: the rate of the shared clock base is changed so that
REALTIME,BOOTTIMEandMONOTONICall move together. The difference between them does not change by a single nanosecond regardless of how much correction is applied over the day. Clock drift, in other words, never moves the epoch. Only an explicit clock step does: a settimeofday, an ADJ_SETOFFSET, a leap second, a VM migration or snapshot restore or a daemon stepping a clock that was badly off at boot or after a long suspend. A healthy server sees zero or one of those per boot, typically in the first minute. Thequark_get_boottimereturn value is otherwise expected to be constant for weeks.Stability measurements
One million calls of
clock_diff(CLOCK_REALTIME, CLOCK_BOOTTIME)back to back, before hysteresis (this shows cross-call jitter and sampling noise that we filter out):/proc/statbtimequark_get_boottimewith hysteresis, 60 million calls over 494 ms, spanning about 49 resample intervals:Go
TestBoottime, three subtests, run 274 times back to back over five minutes under the race detector: zero failures. The subtests check that the seconds match/proc/statbtime, that a non-zero sub-second part exists, that a thousand calls spanning a resample return one value and that eight goroutines calling for 50 ms observe exactly one value.Additionally, there is a clock diffing test written in C here that I've been running for the last week to measure variance, jitter (there's a minimum filter of 10ns) and stability across VM suspends.
Notes for reviewers
Initially, I entertained removing
quark_get_boottimetoo, but decided against it due to:clock_gettimecalls in Go (e.g. via "golang.org/x/sys/unix") are proper syscalls and NOT served from the vDSO. This is true even in the latest Golang version.runtime.nanotimeis served from the vDSO but that'sCLOCK_MONOTONICand doesn't help us. I didn't check whether callingclock_gettimevia cgo results in execution via vDSO, I suspect it might, but it'd introduce cgo call overhead for each one of multiple clock reads. With this PR, there's a single cgo call forquark_get_boottimewhich is a win for both performance and convenience.quark_get_boottimeand tracking that offset themselves.