Skip to content

Updated timestamp handling and API - #414

Merged
christos68k merged 13 commits into
mainfrom
ck/timestamps
Sep 23, 2026
Merged

christos68k merged 13 commits into
mainfrom
ck/timestamps

Conversation

@christos68k

@christos68k christos68k commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

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 the btime field 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) and quark_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.
  • The epoch is now a direct calculation of CLOCK_REALTIME minus CLOCK_BOOTTIME instead of the btime field of /proc/stat. It gains nanosecond resolution and no longer needs a refresh call to track clock steps.
  • The Go bindings lose UpdateBoottime and TimeToWallclock. Boottime remains, callers can fetch it once per batch and add it to time-since-boot timestamps.
  • A shared clock_diff helper 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: btime is 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 between update_boottime and time_to_wallclock, see "Freshness" below). When correlating quark events against anything stamped with CLOCK_REALTIME this 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_boottime that 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/stat open-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.

Operation Cost
Read /proc/stat, old refresh tens to hundreds of µs
Sample REALTIME minus BOOTTIME, new refresh ~50 ns
quark_get_boottime() common path, new 8 ns
quark_time_to_wallclock(), old, atomic load and add ~1 ns

Simplicity: 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

  • The common path costs 8 ns instead of 1 ns: The old atomic load is replaced by a CLOCK_MONOTONIC_COARSE read 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.
  • Steps under 10 ms are absorbed until they accumulate past 10 ms, so the epoch error is bounded at 10 ms in that case. No default NTP daemon configuration produces steps that small, they slew such corrections, and the old code had a permanent error of up to one second.
  • Clock steps are reflected within 10 ms rather than instantly: Conversions in that window use the previous epoch. The old window was unbounded and reliant on the user detecting clock steps and then calling the update function.
  • CLOCK_BOOTTIME is a syscall on kernels before 5.3, which is why we throttle sampling: with continuous quark_get_boottime calls, 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 call quark_get_boottime as 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.
  • API break: Callers of the two removed functions must switch to fetch and add. The Go change is the same. I will make such changes in Cloud Defend once we have consensus about this PR.

How quark_get_boottime behaves

It keeps a single process-wide epoch and maintains it in three steps:

  1. Throttle: It reads CLOCK_MONOTONIC_COARSE and 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_COARSE is present in the vDSO in all Linux kernel versions Quark is expected to run on.
  2. Sample: clock_diff reads CLOCK_BOOTTIME then CLOCK_REALTIME and takes the smallest of three differences. Tens of nanoseconds if served from the vDSO (kernels 5.3+).
  3. Hysteresis: A sample is adopted only if it differs from the adopted epoch (the previously adopted sample) by more than 10 ms, through a compare-and-swap so that concurrent adopters converge on one value. Anything below that is sampling noise / jitter which we filter out.

Slew versus step: Time daemons correct clocks by slewing: the rate of the shared clock base is changed so that REALTIME, BOOTTIME and MONOTONIC all 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. The quark_get_boottime return 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):

Metric Value
Spread between smallest and largest sample 15 to 28 ns
Agreement with /proc/stat btime exact, at second resolution

quark_get_boottime with hysteresis, 60 million calls over 494 ms, spanning about 49 resample intervals:

Metric Value
Cost per call 8.2 ns
Distinct values returned 1
Spread 0 ns

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/stat btime, 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_boottime too, but decided against it due to:

  1. It's still needed internally for ECS boot-to-wallclock conversions.
  2. Coming up with an accurate sampler that takes into account edge cases (like the preemption in-between clock reads) is not trivial. We can do that work, once, in quark and let all users benefit.
  3. Most importantly: All clock_gettime calls 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.nanotime is served from the vDSO but that's CLOCK_MONOTONIC and doesn't help us. I didn't check whether calling clock_gettime via 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 for quark_get_boottime which is a win for both performance and convenience.
  4. We don't lose flexibility, users that want to take over how boottime is managed, can do so by never calling quark_get_boottime and tracking that offset themselves.

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.
@christos68k
christos68k requested a review from a team as a code owner September 2, 2026 20:48
@christos68k christos68k changed the title DRAFT: Updated timestamp handling and API Updated timestamp handling and API Sep 3, 2026
Comment thread quark.c Resolved
Co-authored-by: Nicholas Berlin <56366649+nicholasberlin@users.noreply.github.com>
nicholasberlin
nicholasberlin previously approved these changes Sep 4, 2026
@christos68k

christos68k commented Sep 4, 2026 •

Copy link
Copy Markdown
Member Author

Let's keep this PR unmerged for now, until I open -at least- a PR for Cloud Defend.

@christos68k

christos68k commented Sep 23, 2026 •

Copy link
Copy Markdown
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.

  1. Update to quark 0.9 go-quark#43
  2. https://github.com/elastic/otel-quark-receiver/pull/91
  3. auditbeat: update for quark 0.9 changes beats#53284

@christos68k
christos68k merged commit 2a0d7ee into main Sep 23, 2026
2 checks passed
@christos68k
christos68k deleted the ck/timestamps branch September 23, 2026 17:27
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