Skip to content

Commit 005fa73

Browse files
runningcodeclaude
andcommitted
feat(time): Add Timestamp, EpochClock and AnchoredClock (JAVA-572)
SentryDate is asked to be four things at once: an epoch instant to serialize, one endpoint of a monotonic interval, a carrier of a hidden System.nanoTime() reading, and an opaque foreign timestamp. Nothing in the type separates them, so the guarantees are decided by the runtime class of both operands -- SentryNanotimeDate.diff() is monotonic only when the other date is also a SentryNanotimeDate, and silently subtracts two wall-clock readings otherwise. On the JVM, where SentryAutoDateProvider picks SentryInstantDate, neither endpoint has a monotonic component and span durations are not monotonic at all. The fix is not to type the instants more carefully. It is to stop producing them independently. A group of instants that will be compared against each other -- the spans of a transaction, the samples of a profile chunk, the segments of a replay -- reads the epoch once and projects the rest through the monotonic clock: Timestamp an epoch instant, plus the anchor that projected it, or null when it was read or stated directly. No arithmetic between instants; equality is by instant. EpochClock the wall clock, for stamping a moment that leaves the process. Deliberately cannot report a duration. AnchoredClock one epoch reading pinned to one tick. now() and at(tick) project, tickOf() inverts exactly, driftNanos() reports how far the projection has fallen behind the wall clock. Subtracting two instants from one anchor is subtracting two ticks, so a duration is monotonic by construction rather than by convention, and a clock step cannot make a child span start before its parent. It also gives Android nanosecond resolution it cannot read directly, the epoch being millisecond-granular there -- the workaround SentryNanotimeDate describes, applied once per group instead of between each pair of readings. OpenTelemetry's SDK anchors per local root span for the same two reasons. tickOf() refusing an instant it did not project is what makes this safer rather than merely tidier: mixing domains becomes an exception instead of a plausible-looking wrong number, the same guard Deadline.isAfter applies to clocks. Timing is dropped rather than kept. It paired one Timestamp with one Stopwatch, which is what AnchoredClock does for a whole group, and no call site would have wanted the single-interval version. Nothing calls any of it yet. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent d7bc897 commit 005fa73

12 files changed

Lines changed: 437 additions & 0 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
### Internal
1212

1313
- Add an internal `MonotonicTicker` abstraction with `Deadline` and `Stopwatch` primitives ([#6028](https://github.com/getsentry/sentry-java/pull/6028))
14+
- Add internal `Timestamp`, `EpochClock` and `AnchoredClock`, so related instants project from one wall-clock reading instead of each reading the clock ([#6045](https://github.com/getsentry/sentry-java/pull/6045))
1415

1516
## 8.55.0
1617

sentry/api/sentry.api

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3707,6 +3707,7 @@ public class io/sentry/SentryOptions {
37073707
public fun getEnvelopeDiskCache ()Lio/sentry/cache/IEnvelopeCache;
37083708
public fun getEnvelopeReader ()Lio/sentry/IEnvelopeReader;
37093709
public fun getEnvironment ()Ljava/lang/String;
3710+
public fun getEpochClock ()Lio/sentry/time/EpochClock;
37103711
public fun getEventProcessors ()Ljava/util/List;
37113712
public fun getExecutorService ()Lio/sentry/ISentryExecutorService;
37123713
public fun getExperimental ()Lio/sentry/ExperimentalOptions;
@@ -7598,6 +7599,14 @@ public final class io/sentry/rrweb/RRWebVideoEvent$JsonKeys {
75987599
public fun <init> ()V
75997600
}
76007601

7602+
public final class io/sentry/time/AnchoredClock {
7603+
public fun at (J)Lio/sentry/time/Timestamp;
7604+
public static fun create (Lio/sentry/time/EpochClock;Lio/sentry/time/MonotonicTicker;)Lio/sentry/time/AnchoredClock;
7605+
public fun now ()Lio/sentry/time/Timestamp;
7606+
public fun origin ()Lio/sentry/time/Timestamp;
7607+
public fun tickOf (Lio/sentry/time/Timestamp;)J
7608+
}
7609+
76017610
public final class io/sentry/time/Deadline {
76027611
public static fun after (Lio/sentry/time/MonotonicTicker;JLjava/util/concurrent/TimeUnit;)Lio/sentry/time/Deadline;
76037612
public fun hasPassed ()Z
@@ -7606,6 +7615,10 @@ public final class io/sentry/time/Deadline {
76067615
public fun remaining (Ljava/util/concurrent/TimeUnit;)J
76077616
}
76087617

7618+
public abstract interface class io/sentry/time/EpochClock {
7619+
public abstract fun now ()Lio/sentry/time/Timestamp;
7620+
}
7621+
76097622
public final class io/sentry/time/JavaMonotonicTicker : io/sentry/time/MonotonicTicker {
76107623
public static fun getInstance ()Lio/sentry/time/MonotonicTicker;
76117624
public fun tickNanos ()J
@@ -7621,6 +7634,19 @@ public final class io/sentry/time/Stopwatch {
76217634
public static fun started (Lio/sentry/time/MonotonicTicker;)Lio/sentry/time/Stopwatch;
76227635
}
76237636

7637+
public final class io/sentry/time/SystemEpochClock : io/sentry/time/EpochClock {
7638+
public static fun getInstance ()Lio/sentry/time/EpochClock;
7639+
public fun now ()Lio/sentry/time/Timestamp;
7640+
}
7641+
7642+
public final class io/sentry/time/Timestamp {
7643+
public fun epochNanos ()J
7644+
public fun equals (Ljava/lang/Object;)Z
7645+
public fun hashCode ()I
7646+
public static fun ofEpochNanos (J)Lio/sentry/time/Timestamp;
7647+
public fun toString ()Ljava/lang/String;
7648+
}
7649+
76247650
public final class io/sentry/transport/AsyncHttpTransport : io/sentry/transport/ITransport {
76257651
public fun <init> (Lio/sentry/SentryOptions;Lio/sentry/transport/RateLimiter;Lio/sentry/transport/ITransportGate;Lio/sentry/RequestDetails;)V
76267652
public fun <init> (Lio/sentry/transport/QueuedThreadPoolExecutor;Lio/sentry/SentryOptions;Lio/sentry/transport/RateLimiter;Lio/sentry/transport/ITransportGate;Lio/sentry/transport/HttpConnection;)V

sentry/src/main/java/io/sentry/SentryOptions.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,10 @@
2121
import io.sentry.metrics.IMetricsBatchProcessorFactory;
2222
import io.sentry.protocol.SdkVersion;
2323
import io.sentry.protocol.SentryTransaction;
24+
import io.sentry.time.EpochClock;
2425
import io.sentry.time.JavaMonotonicTicker;
2526
import io.sentry.time.MonotonicTicker;
27+
import io.sentry.time.SystemEpochClock;
2628
import io.sentry.transport.ITransport;
2729
import io.sentry.transport.ITransportGate;
2830
import io.sentry.transport.NoOpEnvelopeCache;
@@ -3061,6 +3063,19 @@ public void setDateProvider(final @NotNull SentryDateProvider dateProvider) {
30613063
this.dateProvider.setValue(dateProvider);
30623064
}
30633065

3066+
/**
3067+
* Returns the wall clock, for stamping an instant that will be serialized.
3068+
*
3069+
* <p>Reports the same epoch as {@link #getDateProvider()}, but a {@link io.sentry.time.Timestamp}
3070+
* carries no {@link System#nanoTime()} tick of its own the way a {@link SentryNanotimeDate} does.
3071+
* Instants that will be subtracted from each other come from an {@link
3072+
* io.sentry.time.AnchoredClock} built on this and {@link #getMonotonicTicker()}.
3073+
*/
3074+
@ApiStatus.Internal
3075+
public @NotNull EpochClock getEpochClock() {
3076+
return SystemEpochClock.getInstance();
3077+
}
3078+
30643079
/**
30653080
* Returns the ticker used to measure elapsed time, such as rate-limit windows, cache expiry and
30663081
* ANR thresholds.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package io.sentry.time;
2+
3+
import org.jetbrains.annotations.ApiStatus;
4+
import org.jetbrains.annotations.NotNull;
5+
6+
/**
7+
* One wall-clock reading pinned to one monotonic tick, from which related instants are projected.
8+
*
9+
* <p>Exists because a group of instants that will be compared against each other — the spans of a
10+
* transaction, the samples of a profile chunk, the frames of a replay segment — must not each read
11+
* the wall clock. Two independent readings differ by whatever the device's clock did in between, so
12+
* a duration taken across them can shorten, lengthen or go negative, and a child can appear to
13+
* start before its parent. Reading the epoch once and projecting the rest through {@link
14+
* MonotonicTicker} makes every instant an image of the same tick, so subtracting any two of them
15+
* reports measured time. The span protocol needs exactly that: it carries a start and an end
16+
* instant and no duration field, so the server subtracts them.
17+
*
18+
* <p>Projection also buys resolution the wall clock does not have: on Android the epoch is
19+
* millisecond-granular, so an instant read directly is truncated, whereas one projected from a tick
20+
* carries nanoseconds. That is the workaround {@link io.sentry.SentryNanotimeDate} describes,
21+
* applied once per group rather than to every reading. OpenTelemetry's SDK anchors per local root
22+
* span for the same two reasons.
23+
*
24+
* <p>The cost is that a projection ages: it reports what the wall clock said when the anchor was
25+
* taken plus the time measured since, so a later correction to the device's clock — an NTP sync, or
26+
* the user setting the time — never reaches it. Anchor something short-lived.
27+
*/
28+
@ApiStatus.Internal
29+
public final class AnchoredClock {
30+
31+
private final @NotNull MonotonicTicker ticker;
32+
private final long epochNanos;
33+
private final long anchorTick;
34+
35+
private AnchoredClock(
36+
final @NotNull MonotonicTicker ticker, final long epochNanos, final long anchorTick) {
37+
this.ticker = ticker;
38+
this.epochNanos = epochNanos;
39+
this.anchorTick = anchorTick;
40+
}
41+
42+
/** Takes the anchor now: one epoch reading, one tick, as close together as a call allows. */
43+
public static @NotNull AnchoredClock create(
44+
final @NotNull EpochClock epoch, final @NotNull MonotonicTicker ticker) {
45+
return new AnchoredClock(ticker, epoch.now().epochNanos(), ticker.tickNanos());
46+
}
47+
48+
/**
49+
* The instant the anchor was taken — the one instant here that was read rather than projected.
50+
*
51+
* <p>Reads no clock and never changes. Every other instant this class returns is this one plus
52+
* measured time.
53+
*/
54+
public @NotNull Timestamp origin() {
55+
return Timestamp.anchoredAt(epochNanos, this);
56+
}
57+
58+
/** The current instant: {@link #origin()} plus the time the ticker has measured since. */
59+
public @NotNull Timestamp now() {
60+
return at(ticker.tickNanos());
61+
}
62+
63+
/**
64+
* The instant a tick corresponds to, for placing something already measured on this ticker — a
65+
* frame, a profiler sample — on the same timeline as the instants projected here.
66+
*/
67+
public @NotNull Timestamp at(final long tickNanos) {
68+
return Timestamp.anchoredAt(epochNanos + (tickNanos - anchorTick), this);
69+
}
70+
71+
/**
72+
* The tick an instant was projected from. Exact, and reads no clock: projection adds a tick
73+
* difference to a fixed epoch, so subtraction inverts it.
74+
*
75+
* @throws IllegalArgumentException if this clock did not project the instant. Its epoch bears no
76+
* arithmetic relation to these ticks, so converting it would silently produce a tick derived
77+
* from a wall-clock difference.
78+
*/
79+
public long tickOf(final @NotNull Timestamp timestamp) {
80+
if (timestamp.anchor() != this) {
81+
throw new IllegalArgumentException(
82+
"Timestamp was not projected by this AnchoredClock: " + timestamp);
83+
}
84+
return anchorTick + (timestamp.epochNanos() - epochNanos);
85+
}
86+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package io.sentry.time;
2+
3+
import org.jetbrains.annotations.ApiStatus;
4+
import org.jetbrains.annotations.NotNull;
5+
6+
/**
7+
* The source of wall-clock time.
8+
*
9+
* <p>Stamps a moment that will leave this process — an event, a breadcrumb, a session — and nothing
10+
* else. It deliberately cannot report a duration: measuring belongs to {@link Stopwatch}, and a
11+
* group of instants that will be subtracted from each other belongs to an {@link AnchoredClock},
12+
* which reads this once and projects the rest.
13+
*/
14+
@ApiStatus.Internal
15+
public interface EpochClock {
16+
17+
/** The current instant. Serialize it; do not subtract it from another one. */
18+
@NotNull
19+
Timestamp now();
20+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package io.sentry.time;
2+
3+
import io.sentry.DateUtils;
4+
import java.time.Instant;
5+
import org.jetbrains.annotations.ApiStatus;
6+
7+
/**
8+
* Reads the epoch from {@link Instant}.
9+
*
10+
* <p>A class of its own so the reference to {@code java.time} is loaded only where {@link
11+
* SystemEpochClock} decided to use it. Android's minSdk is below the API 26 that introduced {@code
12+
* Instant}.
13+
*/
14+
@ApiStatus.Internal
15+
@SuppressWarnings("NewApi")
16+
final class InstantEpochNanos {
17+
18+
private InstantEpochNanos() {}
19+
20+
static long read() {
21+
final Instant now = Instant.now();
22+
// No long overflow until year 2262
23+
return DateUtils.secondsToNanos(now.getEpochSecond()) + now.getNano();
24+
}
25+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package io.sentry.time;
2+
3+
import io.sentry.DateUtils;
4+
import io.sentry.util.Platform;
5+
import org.jetbrains.annotations.ApiStatus;
6+
import org.jetbrains.annotations.NotNull;
7+
8+
/**
9+
* The {@link EpochClock} backed by the system wall clock.
10+
*
11+
* <p>Reads the epoch at the best precision the platform offers: {@link java.time.Instant} where it
12+
* is sub-millisecond, {@link System#currentTimeMillis()} everywhere else. Android is always the
13+
* latter — {@code Instant} is millisecond-granular there whether or not the build desugars it, see
14+
* https://github.com/getsentry/sentry-java/pull/2451.
15+
*
16+
* <p>A millisecond anchor loses less than it looks: an {@link AnchoredClock} adds nanosecond ticks
17+
* to one anchor, so only the anchor is coarse.
18+
*/
19+
@ApiStatus.Internal
20+
public final class SystemEpochClock implements EpochClock {
21+
22+
private static final boolean INSTANT_IS_SUB_MILLISECOND =
23+
Platform.isJvm() && Platform.isJavaNinePlus();
24+
25+
private static final SystemEpochClock instance = new SystemEpochClock();
26+
27+
public static @NotNull EpochClock getInstance() {
28+
return instance;
29+
}
30+
31+
private SystemEpochClock() {}
32+
33+
@Override
34+
public @NotNull Timestamp now() {
35+
return Timestamp.ofEpochNanos(
36+
INSTANT_IS_SUB_MILLISECOND
37+
? InstantEpochNanos.read()
38+
: DateUtils.millisToNanos(System.currentTimeMillis()));
39+
}
40+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package io.sentry.time;
2+
3+
import org.jetbrains.annotations.ApiStatus;
4+
import org.jetbrains.annotations.NotNull;
5+
import org.jetbrains.annotations.Nullable;
6+
7+
/**
8+
* An instant on the wall clock, as nanoseconds since the Unix epoch.
9+
*
10+
* <p>Unlike a {@link MonotonicTicker} tick, a timestamp means something outside this process: it
11+
* can be serialized, stored, and compared against a value from another machine.
12+
*
13+
* <p>It deliberately offers no arithmetic between instants. Subtracting two independent wall-clock
14+
* readings gives a duration the device's clock can lengthen, shorten or make negative. Durations
15+
* come from a {@link Stopwatch}, or from two instants an {@link AnchoredClock} projected from the
16+
* same tick.
17+
*
18+
* <p>{@link #anchor()} records which of those this is. An instant read straight from the wall
19+
* clock, or stated by something outside this process, has no anchor and can only be serialized. One
20+
* an {@link AnchoredClock} produced references that clock, which lets {@link AnchoredClock#tickOf}
21+
* recover the tick it came from and reject instants it did not produce.
22+
*
23+
* <p>Nanoseconds since the epoch overflow a long in the year 2262.
24+
*/
25+
@ApiStatus.Internal
26+
public final class Timestamp {
27+
28+
private final long epochNanos;
29+
private final @Nullable AnchoredClock anchor;
30+
31+
private Timestamp(final long epochNanos, final @Nullable AnchoredClock anchor) {
32+
this.epochNanos = epochNanos;
33+
this.anchor = anchor;
34+
}
35+
36+
/** An instant read straight from a wall clock, or stated by something outside this process. */
37+
public static @NotNull Timestamp ofEpochNanos(final long epochNanos) {
38+
return new Timestamp(epochNanos, null);
39+
}
40+
41+
static @NotNull Timestamp anchoredAt(final long epochNanos, final @NotNull AnchoredClock anchor) {
42+
return new Timestamp(epochNanos, anchor);
43+
}
44+
45+
public long epochNanos() {
46+
return epochNanos;
47+
}
48+
49+
/** The clock that projected this instant, or null if it was read or stated directly. */
50+
@Nullable
51+
AnchoredClock anchor() {
52+
return anchor;
53+
}
54+
55+
/**
56+
* Equality is by instant. The anchor records how the instant was obtained, not what it denotes,
57+
* so two readings of the same moment are equal whether or not they were projected.
58+
*/
59+
@Override
60+
public boolean equals(final @Nullable Object other) {
61+
if (this == other) {
62+
return true;
63+
}
64+
if (!(other instanceof Timestamp)) {
65+
return false;
66+
}
67+
return epochNanos == ((Timestamp) other).epochNanos;
68+
}
69+
70+
@Override
71+
public int hashCode() {
72+
return (int) (epochNanos ^ (epochNanos >>> 32));
73+
}
74+
75+
@Override
76+
public @NotNull String toString() {
77+
return "Timestamp{epochNanos=" + epochNanos + '}';
78+
}
79+
}

0 commit comments

Comments
 (0)