Title: Clock-usage audit: wall vs monotonic time issues across the SDK (converted to project) · Issue #5530 · getsentry/sentry-java · GitHub
Open Graph Title: Clock-usage audit: wall vs monotonic time issues across the SDK (converted to project) · Issue #5530 · getsentry/sentry-java
X Title: Clock-usage audit: wall vs monotonic time issues across the SDK (converted to project) · Issue #5530 · getsentry/sentry-java
Description: This issue has been converted to a project Clock semantics hardening across sentry-java Audit of clock usage across sentry-java (as of b988b37): wall clock used to measure intervals, monotonic time converted to dates, and the dual-semant...
Open Graph Description: This issue has been converted to a project Clock semantics hardening across sentry-java Audit of clock usage across sentry-java (as of b988b37): wall clock used to measure intervals, monotonic time...
X Description: This issue has been converted to a project Clock semantics hardening across sentry-java Audit of clock usage across sentry-java (as of b988b37): wall clock used to measure intervals, monotonic time...
Opengraph URL: https://github.com/getsentry/sentry-java/issues/5530
X: @github
Domain: github.com
IPv4 address: 140.82.112.4
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Clock-usage audit: wall vs monotonic time issues across the SDK (converted to project)","articleBody":"This issue has been converted to a project [Clock semantics hardening across sentry-java](\u003chttps://linear.app/getsentry/project/clock-semantics-hardening-across-sentry-java-24511e82f86d>)\n\n---\n\nAudit of clock usage across sentry-java (as of b988b37): wall clock used to measure intervals, monotonic time converted to dates, and the dual-semantics `ICurrentDateProvider` interface. Each finding is classified **actual bug** vs **theoretical** with an urgency rating.\n\nFound: **1 design flaw (root cause), 4 actual bugs, \\~10 theoretical issues.** Notably, every *current* `ICurrentDateProvider` pairing turned out to be correct — but only via careful manual wiring that nothing enforces.\n\n---\n\n## A. Root design hazard\n\n### A1. `ICurrentDateProvider` has two implementations with different clock semantics — **Design flaw · HIGH**\n\n[CurrentDateProvider](\u003chttps://github.com/getsentry/sentry-java/blob/main/sentry/src/main/java/io/sentry/transport/CurrentDateProvider.java>) returns `System.currentTimeMillis()` (wall/epoch); [AndroidCurrentDateProvider](\u003chttps://github.com/getsentry/sentry-java/blob/main/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/AndroidCurrentDateProvider.java>) returns `SystemClock.uptimeMillis()` (monotonic, pauses in deep sleep) — same method name `getCurrentTimeMillis()`.\n\nEvery consumer must hand-pick the impl matching whatever it compares against:\n\n* `AnrV2Integration` / `TombstoneIntegration` deliberately use the **wall** one (warning comment: \"AppExitInfo uses System.currentTimeMillis\") to compare against `ApplicationExitInfo.getTimestamp()`.\n* `LifecycleWatcher` needs **wall** because it seeds `lastUpdatedSession` from `Session.getStarted().getTime()` (epoch).\n* `AndroidEnvelopeCache` needs **uptime** because it subtracts `TimeSpan.getStartUptimeMs()` (uptime base) for startup-crash detection.\n* `ANRWatchDog` bypasses both with an inline `() -> SystemClock.uptimeMillis()` lambda.\n* `RateLimiter` and `ReplayIntegration` get the **wall** one even on Android (correct — both need epoch).\n\nA wrong wiring is silent (tests inject fakes) and catastrophic — e.g. uptime fed into `Timer.schedule(task, absoluteDate)` produces a 1970 date that fires instantly.\n\n**Fix:** split into two explicitly-named interfaces (e.g. wall `epochMillis()` vs monotonic `elapsedMillis()`), or rename methods per impl so a mismatch can't compile.\n\n---\n\n## B. Actual bugs\n\n### B1. `java.util.Timer` for transaction idle/deadline timeouts — **MEDIUM-HIGH**\n\n[SentryTracer.java#L102](\u003chttps://github.com/getsentry/sentry-java/blob/main/sentry/src/main/java/io/sentry/SentryTracer.java#L102>) (also `scheduleFinish`/`scheduleDeadlineTimeout`). `Timer` deadlines are wall-clock based and its internal `Object.wait()` does not progress during Android deep sleep:\n\n* App backgrounded mid-`ui.load` → device sleeps before the 30s deadline fires → timer fires **at wake (potentially hours later)**; `forceFinish` stamps unfinished spans with `dateProvider.now()` → multi-hour transactions/spans (the classic \"absurdly long ui.load transaction\" artifact).\n* Wall-clock steps (NTP/user) shift firing on any platform.\n\n**Fix:** schedule on `SentryExecutorService` (nanoTime-based delays); clamp finish timestamps when the deadline fires late.\n\n### B2. Session-end timer has the same `Timer` mechanics — **MEDIUM**\n\n[LifecycleWatcher.java#L121](\u003chttps://github.com/getsentry/sentry-java/blob/main/sentry-android-core/src/main/java/io/sentry/android/core/LifecycleWatcher.java#L121>). Device sleeps within the 30s background window → session ends only at wake; `Session.end()` stamps wake time → inflated session durations in release health; replay `stop()` and `ContinuousProfiler.close(false)` also run hours late. The foreground check `lastUpdatedSession + sessionIntervalMillis \u003c= now` is also a wall-clock interval (clock step → spurious or missed session rotation).\n\n### B3. Session Replay: wall clock used for all interval math — **MEDIUM** (actual bug when the clock steps mid-recording)\n\nEpoch is *required* for RRWeb payload timestamps (that part is correct), but the same wall values also drive windows/durations:\n\n* [SessionCaptureStrategy.kt#L81](\u003chttps://github.com/getsentry/sentry-java/blob/main/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/SessionCaptureStrategy.kt#L81>) (+L106, L162): segment durations and the 1h max-session deadline are `now - startEpoch` diffs.\n* `BufferCaptureStrategy` trim-to-last-30s and `ReplayCache.createVideoOf` iterate epoch-millis windows; frame files are named by epoch millis.\n* [ReplayGestureConverter.kt#L56](\u003chttps://github.com/getsentry/sentry-java/blob/main/sentry-android-replay/src/main/java/io/sentry/android/replay/gestures/ReplayGestureConverter.kt#L56>): `timeOffset = now - touchMoveBaseline`.\n\nA backward step mid-recording → frames \"newer than now\": trim can wipe valid frames, segment windows miss/duplicate frames, gesture offsets go negative. Forward step → premature 1h cutoff. NTP/carrier/user steps on phones are realistic.\n\n**Fix:** keep epoch in RRWeb payloads, drive windows/trim from a monotonic clock with one epoch anchor per segment.\n\n### B4. Cron check-in durations measured with wall clock — **LOW-MEDIUM**\n\n[CheckInUtils.java#L64](\u003chttps://github.com/getsentry/sentry-java/blob/main/sentry/src/main/java/io/sentry/util/CheckInUtils.java#L64>) and the same pattern in `SentryCheckInAdvice` (sentry-spring, -jakarta, -7): `duration = currentTimeMillis() - start`. Cron jobs run long → wide exposure to clock steps → wrong/negative durations. Pure interval → should be `System.nanoTime()`.\n\n---\n\n## C. Theoretical issues (need a clock step / edge condition)\n\n1. **AndroidProfiler measurement re-anchoring · LOW-MEDIUM** — [AndroidProfiler.java#L309](\u003chttps://github.com/getsentry/sentry-java/blob/main/sentry-android-core/src/main/java/io/sentry/android/core/AndroidProfiler.java#L309>): `timestampDiff` (elapsedRealtime↔wall offset) computed **once at profile end** and applied to every wall-stamped `PerformanceCollectionData` sample → a wall step during the profile shifts all earlier CPU/memory samples relative to the trace. Fix: stamp samples with `elapsedRealtimeNanos` on Android.\n2. **Session** `seq` **is raw epoch millis · LOW-MEDIUM** — [Session.java#L309](\u003chttps://github.com/getsentry/sentry-java/blob/main/sentry/src/main/java/io/sentry/Session.java#L309>): backward step between updates → newer update has smaller seq → server can discard the latest session state (lost end/error counts). Also `calculateDurationTime` uses `Math.abs`, masking negative durations. Fix: `seq = max(prevSeq + 1, now)`.\n3. **RateLimiter wall-clock deadlines · LOW** — retry-after stored as epoch `Date`s (self-consistent), but a backward step silently extends the drop window; the \"limit lifted\" observer callback is `Timer.schedule(task, absoluteDate)` → shifted by steps (continuous profilers resume late).\n4. **App-start anchor projection · LOW** — `TimeSpan` (uptime + wall anchor) is the right pattern, but the wall anchor is captured once and `setStartedAt()` back-projects assuming no step since process start; NTP sync shortly after boot shifts app-start span timestamps relative to later-anchored spans.\n5. `SpanFrameMetricsCollector.toNanoTime()` **· LOW** — re-anchors wall-based `SentryLongDate`s into the `nanoTime` base using the *current* offset; wrong by any step since the date was created, and across deep sleep → frames attributed to wrong span windows.\n6. **Wall-clock TTLs/cleanup · LOW** — `HostnameCache` 5h TTL; `Sentry.classCreationTimestamp` vs `File.lastModified()` for profiling-traces cleanup; `CacheStrategy` envelope rotation ordered by `lastModified()`; `DefaultCompositePerformanceCollector` 30s auto-stop via wall diff + sampling on `java.util.Timer`.\n7. **Informational** — `Breadcrumb.compareTo` orders by captured `System.nanoTime()` (restored-from-disk breadcrumbs get fresh nanos at parse → cross-restart ordering is parse-order); cross-type `SentryDate` arithmetic (`SentryNanotimeDate` vs `SentryLongDate`) silently degrades to ms-precision wall math.\n\n---\n\n## D. Checked and confirmed correct (coverage)\n\nANRWatchDog (all-uptime); AnrV2/Tombstone 90-day threshold (wall vs wall); AndroidEnvelopeCache startup-crash window (uptime vs uptime); AndroidConnectionStatusProvider cache TTL (uptime); Debouncer on uptime (no events during sleep anyway); DeviceInfoUtil boot time (`wall − elapsedRealtime`); AndroidCpuCollector (elapsedRealtimeNanos deltas); AndroidProfiler per-frame clock conversion; span/transaction `SentryNanotimeDate` anchor pattern; LoggerBatchProcessor/BackpressureMonitor (`ScheduledExecutorService`); OkHttp `HTTP_START/END_TIMESTAMP` (deliberately epoch for RRWeb). Swept clean: apollo*, graphql*, kafka, quartz, spotlight, reactor, ndk, fragment, navigation, distribution, jul/logback/log4j2, async-profiler.\n\n---\n\n## Suggested fix order\n\n1. **A1** — split/rename `ICurrentDateProvider` semantics (prevents all future regressions; internal API).\n2. **B1 + B2** — replace `java.util.Timer` with `SentryExecutorService` for tracer idle/deadline + session-end (and C3's observer timer); clamp late-fire timestamps.\n3. **B3** — monotonic windows in replay capture strategies.\n4. **B4** — `nanoTime` for check-in durations (CheckInUtils + 3 spring files).\n5. **C1/C2** — profiler measurement stamping; session seq monotonicity.\n6. Rest are doc comments / opportunistic.\n\nVerification idea for fixes: unit tests already inject `ICurrentDateProvider` fakes everywhere — add cases simulating backward/forward clock steps and assert intervals are unaffected.","author":{"url":"https://github.com/runningcode","@type":"Person","name":"runningcode"},"datePublished":"2026-06-11T13:56:24Z","url":"https://github.com/getsentry/sentry-java/issues/5530"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:a00c944c-f4cf-1cf5-a887-dbb23e711006 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | A36E:8181B:341198:4992B8:6B046D9F |
| html-safe-nonce | 02f73a29f8926797e42a5694c6fc5cd567daf51ff9706d2c775b7d4609c6ddac |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBMzZFOjgxODFCOjM0MTE5ODo0OTkyQjg6NkIwNDZEOUYiLCJ2aXNpdG9yX2lkIjoiMzQ4Mzk2MDUzNzUzMTA1MTQyNCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 1be80ffce6c0ba20abd4fa16f1e0503dcfcbc63aac50e6f0cdf528a9a2a3d664 |
| hovercard-subject-tag | issue:4641147384 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/getsentry/sentry-java/5530/issue_layout |
| twitter:image | https://opengraph.githubassets.com/d4dd716d2ee8e014f3cfd049056b26bf8416c692c7e4ec7a7a789fcfc77995c5/getsentry/sentry-java/issues/5530 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/d4dd716d2ee8e014f3cfd049056b26bf8416c692c7e4ec7a7a789fcfc77995c5/getsentry/sentry-java/issues/5530 |
| og:image:alt | This issue has been converted to a project Clock semantics hardening across sentry-java Audit of clock usage across sentry-java (as of b988b37): wall clock used to measure intervals, monotonic time... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | runningcode |
| hostname | github.com |
| expected-hostname | github.com |
| None | ae8802492f12d3ba4f6b0d814054e617a2a5616b6327bf8555c10cd5b0dc2a6f |
| turbo-cache-control | no-preview |
| go-import | github.com/getsentry/sentry-java git https://github.com/getsentry/sentry-java.git |
| octolytics-dimension-user_id | 1396951 |
| octolytics-dimension-user_login | getsentry |
| octolytics-dimension-repository_id | 3368190 |
| octolytics-dimension-repository_nwo | getsentry/sentry-java |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 3368190 |
| octolytics-dimension-repository_network_root_nwo | getsentry/sentry-java |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | cfb5f24c6e01d85f70804652a5107e5cac03a161 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width