This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new e5b81f7a02d1 CAMEL-26949: camel-test-dst - let a world move the wall 
clock apart from the monotonic clock (#29994)
e5b81f7a02d1 is described below

commit e5b81f7a02d131330d9829370dd1317e602d3416
Author: allthingssecurity <[email protected]>
AuthorDate: Sun Nov 15 14:15:14 2026 +0530

    CAMEL-26949: camel-test-dst - let a world move the wall clock apart from 
the monotonic clock (#29994)
    
    In a DST run the wall clock was the fixed epoch plus the virtual monotonic 
time, so it could only move forward together with the monotonic clock, and a 
world could not model an NTP step, a resumed VM or a changed system time.
    
    Dst gains jumpWallClock(deltaMillis), jumpWallClockBetween(from, to, 
minDelta, maxDelta), which draws the time and size of the jump from the seed so 
a failing seed replays exactly, and wallClockOffset(). The jump reaches the 
rewritten wall clock reads of the code under test and 
TimeSource.currentTimeMillis()/instant() of Camel core; nothing monotonic 
moves. test-dst.adoc gets a Wall clock jumps section with a DefaultTimeoutMap 
example. New DstWallClockJumpTest.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../org/apache/camel/catalog/docs/test-dst.adoc    |  65 ++++-
 .../camel-test-dst/src/main/docs/test-dst.adoc     |  65 ++++-
 .../main/java/org/apache/camel/test/dst/Dst.java   |  96 +++++++-
 .../camel/test/dst/DstWallClockJumpTest.java       | 267 +++++++++++++++++++++
 4 files changed, 479 insertions(+), 14 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/test-dst.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/test-dst.adoc
index b0b386725d6f..549386f731d8 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/test-dst.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/test-dst.adoc
@@ -17,7 +17,8 @@ with the same step trace.
   (`DstThreadPoolFactory`). Tasks run one at a time; when several can run, the 
seed picks one.
 * Time is virtual: it jumps to the next due task. The time reads, sleeps and 
blocking waits of the code under test are
   rewritten at test time (`@DstInstrument`), and the Camel core code that 
waits, times tasks or throttles reads the
-  virtual clock through its internal time source, so "wait 30 seconds" costs 
nothing.
+  virtual clock through its internal time source, so "wait 30 seconds" costs 
nothing. A world can move the wall clock
+  forward or backward apart from the monotonic clock (see 
<<_wall_clock_jumps,Wall clock jumps>>).
 * A fake of the external system (a queue, a checkpoint store, a web API) 
injects faults chosen by the same seed.
 * Invariants are checked at the end of each run.
 * `@DstTest(seeds = 1000)` runs a test method once per seed. A failing seed is 
printed with its trace and is replayed
@@ -121,7 +122,9 @@ a|* the polling consumer with maxResults and naturalOrder
 runnable tasks to the seed.
 |Time reads |`System.currentTimeMillis()`, `System.nanoTime()`, `new Date()`, 
`Instant.now()`, `Clock.systemUTC()`,
 `Clock.systemDefaultZone()`, `Clock.system(ZoneId)` and `now()` / 
`now(ZoneId)` of `LocalDateTime`, `ZonedDateTime`,
-`OffsetDateTime`, `LocalDate`, `LocalTime` and `OffsetTime`, in the packages 
of `@DstInstrument`.
+`OffsetDateTime`, `LocalDate`, `LocalTime` and `OffsetTime`, in the packages 
of `@DstInstrument`. The wall clock is
+`Dst.EPOCH_MILLIS` plus the virtual time, moved by the wall clock jumps of the 
run; `System.nanoTime()` is the
+monotonic clock and never jumps.
 |Sleeps |`Thread.sleep` and `TimeUnit.sleep`: on the loop thread a sleep is a 
virtual wait. The sleeping task keeps
 its thread and the other tasks run meanwhile.
 |Blocking waits |`CompletableFuture.get/join`, `Future.get`, 
`CountDownLatch.await`, `Semaphore.acquire/tryAcquire`,
@@ -158,6 +161,55 @@ rewriting of the code under test to classes outside it, 
for example `org.apache.
 clock of an exchange) or a library the component calls. It is not needed for 
the core classes listed above, except for
 the permit queue of `TotalRequestsThrottler` (see below).
 
+=== Wall clock jumps
+
+Without a jump the wall clock moves only forward, together with the monotonic 
clock. A world can move the wall clock
+forward or backward, as an NTP step or an operator who sets the system time 
does, to test code that keeps times of the
+wall clock: expiring entries, caches, deadlines and schedules.
+
+* `dst.jumpWallClock(deltaMillis)` moves it at once (back when the value is 
negative). Call it on the loop thread: in
+  the test body, or in a task of the run.
+* `dst.jumpWallClockBetween(fromMillis, toMillis, minDeltaMillis, 
maxDeltaMillis)` lets the seed choose: it draws when
+  the jump happens (between `fromMillis` and `toMillis` of virtual time from 
now) and how big it is, and schedules it.
+  The same seed makes the same jump at the same time, so a failing seed 
replays exactly. The trace says when the jump
+  is scheduled (its time and size) and when it happens, and the returned task 
has the delta as its result once the
+  jump has happened. The jump is a pending task of the run, so 
`dst.dropPending()` drops it.
+* A jump moves the wall clock at most 100 years 
(`Dst.MAX_WALL_CLOCK_JUMP_MILLIS`) away from the monotonic clock.
+
+After a jump, the wall clock reads see it: the rewritten reads of the code 
under test (`System.currentTimeMillis()`,
+`new Date()`, `Instant.now()`, the `java.time` reads) and, in Camel core, 
`TimeSource.currentTimeMillis()` and
+`TimeSource.instant()` (for example the expiry of `DefaultTimeoutMap` and the 
failure window and open state of
+`ThrottlingExceptionRoutePolicy`, and the created time of a `MonotonicClock`). 
The monotonic clock
+(`System.nanoTime()`, `TimeSource.nanoTime()`, `StopWatch`, 
`MonotonicClock.elapsed()`), `dst.now()`, the sleeps and
+waits, and the due times of the tasks do not: a task scheduled 10 seconds 
ahead still runs 10 seconds later.
+`dst.wallClockOffset()` is how far the jumps have moved the wall clock. Each 
run starts without a jump.
+
+`dst.currentTimeMillis()` follows the jumps; `Dst.EPOCH_MILLIS + dst.now()` 
does not. Give the fake the one that
+matches the external system: a server keeps its own clock, so a jump of the 
clock of the Camel host leaves the
+timestamps of the server as they were.
+
+An example: an entry with a timeout of 30 seconds in a `DefaultTimeoutMap` 
(the expiring map behind request-reply
+timeouts), under a backward jump of an hour 10 seconds after it was put:
+
+[source,java]
+----
+DefaultTimeoutMap<String, String> map = new 
DefaultTimeoutMap<>(dst.executor("purge", 1), 1_000);
+map.start();
+map.put("order-1", "pending", 30_000);
+dst.runFor(10_000);
+dst.jumpWallClock(-3_600_000);
+dst.runFor(60_000);
+// 70 s after the put the entry is still there: its expiry is a wall clock 
time, so it now expires an hour late
+assertEquals(1, map.size());
+----
+
+The example asks `size()` and not `get()`, because `get()` refreshes the 
expiry of the entry, from the wall clock as it
+is after the jump. After a forward jump of an hour instead, the entry is 
evicted by the next purge after the jump (here
+1 second later). In a world, let the seed choose the jump 
(`dst.jumpWallClockBetween(0, 60_000, -3_600_000, 3_600_000)`,
+which writes it to the trace), and decide from the contract of the component 
what a jump may change: an entry that
+expires late or early by the size of the jump can be what the component 
documents, while an exchange that is lost or
+completed twice is not. As for any fault, record which jump excuses which 
violation.
+
 === Escapes and strict mode
 
 Before the first seed, the harness scans the packages under test and writes 
every *escape point* to
@@ -418,8 +470,9 @@ component's JSON (built with the component), and its copy 
in the catalog and thi
 Agents wrote nine worlds with this guide (not all of them are in the code 
base). These mistakes came up:
 
 * *Timestamps at 0.* Give the times of the fake virtual wall clock time 
(`Dst.EPOCH_MILLIS + dst.now()`, or
-  `dst.currentTimeMillis()`), not 0. A Service Bus fake with lock times in 
1970 made the lock renewer renew on every run,
-  so the world could not fail. The self-check (fail on the code before the 
fix) caught it.
+  `dst.currentTimeMillis()`, which follows the wall clock jumps of the run), 
not 0. A Service Bus fake with lock times
+  in 1970 made the lock renewer renew on every run, so the world could not 
fail. The self-check (fail on the code
+  before the fix) caught it.
 * *No end to the run.* A consumer that loops forever needs an unwind at the 
end of the run, or the run never ends:
   cancel its task through the task registry, or stop the route at the end of 
the drain phase. A consumer task that
   never returns (a pull loop) sits above the test thread on the one stack, so 
a `dst.runFor` or `dst.runUntil` in the
@@ -548,8 +601,8 @@ CAMEL-25737), `dst.replayCheckSeed` (the seed of the in-JVM 
replay test of the E
 
 [cols="1,3"]
 |===
-|`Dst` |the event loop: virtual clock, seeded random source, step trace with 
its SHA-256, timed and untimed waits,
-strict mode
+|`Dst` |the event loop: virtual clock, wall clock jumps, seeded random source, 
step trace with its SHA-256, timed and
+untimed waits, strict mode
 |`DstThreadPoolFactory`, `DstExecutor`, `DstTask` |Camel's pools and 
schedulers backed by the loop
 |`DstInstrumentation`, `DstClock`, `DstWaits` |the byte code rewrite of the 
code under test: time reads, sleeps and
 blocking waits go to the loop; `DstClock` is also the `TimeSource` provider of 
Camel core during a run
diff --git a/components/camel-test/camel-test-dst/src/main/docs/test-dst.adoc 
b/components/camel-test/camel-test-dst/src/main/docs/test-dst.adoc
index b0b386725d6f..549386f731d8 100644
--- a/components/camel-test/camel-test-dst/src/main/docs/test-dst.adoc
+++ b/components/camel-test/camel-test-dst/src/main/docs/test-dst.adoc
@@ -17,7 +17,8 @@ with the same step trace.
   (`DstThreadPoolFactory`). Tasks run one at a time; when several can run, the 
seed picks one.
 * Time is virtual: it jumps to the next due task. The time reads, sleeps and 
blocking waits of the code under test are
   rewritten at test time (`@DstInstrument`), and the Camel core code that 
waits, times tasks or throttles reads the
-  virtual clock through its internal time source, so "wait 30 seconds" costs 
nothing.
+  virtual clock through its internal time source, so "wait 30 seconds" costs 
nothing. A world can move the wall clock
+  forward or backward apart from the monotonic clock (see 
<<_wall_clock_jumps,Wall clock jumps>>).
 * A fake of the external system (a queue, a checkpoint store, a web API) 
injects faults chosen by the same seed.
 * Invariants are checked at the end of each run.
 * `@DstTest(seeds = 1000)` runs a test method once per seed. A failing seed is 
printed with its trace and is replayed
@@ -121,7 +122,9 @@ a|* the polling consumer with maxResults and naturalOrder
 runnable tasks to the seed.
 |Time reads |`System.currentTimeMillis()`, `System.nanoTime()`, `new Date()`, 
`Instant.now()`, `Clock.systemUTC()`,
 `Clock.systemDefaultZone()`, `Clock.system(ZoneId)` and `now()` / 
`now(ZoneId)` of `LocalDateTime`, `ZonedDateTime`,
-`OffsetDateTime`, `LocalDate`, `LocalTime` and `OffsetTime`, in the packages 
of `@DstInstrument`.
+`OffsetDateTime`, `LocalDate`, `LocalTime` and `OffsetTime`, in the packages 
of `@DstInstrument`. The wall clock is
+`Dst.EPOCH_MILLIS` plus the virtual time, moved by the wall clock jumps of the 
run; `System.nanoTime()` is the
+monotonic clock and never jumps.
 |Sleeps |`Thread.sleep` and `TimeUnit.sleep`: on the loop thread a sleep is a 
virtual wait. The sleeping task keeps
 its thread and the other tasks run meanwhile.
 |Blocking waits |`CompletableFuture.get/join`, `Future.get`, 
`CountDownLatch.await`, `Semaphore.acquire/tryAcquire`,
@@ -158,6 +161,55 @@ rewriting of the code under test to classes outside it, 
for example `org.apache.
 clock of an exchange) or a library the component calls. It is not needed for 
the core classes listed above, except for
 the permit queue of `TotalRequestsThrottler` (see below).
 
+=== Wall clock jumps
+
+Without a jump the wall clock moves only forward, together with the monotonic 
clock. A world can move the wall clock
+forward or backward, as an NTP step or an operator who sets the system time 
does, to test code that keeps times of the
+wall clock: expiring entries, caches, deadlines and schedules.
+
+* `dst.jumpWallClock(deltaMillis)` moves it at once (back when the value is 
negative). Call it on the loop thread: in
+  the test body, or in a task of the run.
+* `dst.jumpWallClockBetween(fromMillis, toMillis, minDeltaMillis, 
maxDeltaMillis)` lets the seed choose: it draws when
+  the jump happens (between `fromMillis` and `toMillis` of virtual time from 
now) and how big it is, and schedules it.
+  The same seed makes the same jump at the same time, so a failing seed 
replays exactly. The trace says when the jump
+  is scheduled (its time and size) and when it happens, and the returned task 
has the delta as its result once the
+  jump has happened. The jump is a pending task of the run, so 
`dst.dropPending()` drops it.
+* A jump moves the wall clock at most 100 years 
(`Dst.MAX_WALL_CLOCK_JUMP_MILLIS`) away from the monotonic clock.
+
+After a jump, the wall clock reads see it: the rewritten reads of the code 
under test (`System.currentTimeMillis()`,
+`new Date()`, `Instant.now()`, the `java.time` reads) and, in Camel core, 
`TimeSource.currentTimeMillis()` and
+`TimeSource.instant()` (for example the expiry of `DefaultTimeoutMap` and the 
failure window and open state of
+`ThrottlingExceptionRoutePolicy`, and the created time of a `MonotonicClock`). 
The monotonic clock
+(`System.nanoTime()`, `TimeSource.nanoTime()`, `StopWatch`, 
`MonotonicClock.elapsed()`), `dst.now()`, the sleeps and
+waits, and the due times of the tasks do not: a task scheduled 10 seconds 
ahead still runs 10 seconds later.
+`dst.wallClockOffset()` is how far the jumps have moved the wall clock. Each 
run starts without a jump.
+
+`dst.currentTimeMillis()` follows the jumps; `Dst.EPOCH_MILLIS + dst.now()` 
does not. Give the fake the one that
+matches the external system: a server keeps its own clock, so a jump of the 
clock of the Camel host leaves the
+timestamps of the server as they were.
+
+An example: an entry with a timeout of 30 seconds in a `DefaultTimeoutMap` 
(the expiring map behind request-reply
+timeouts), under a backward jump of an hour 10 seconds after it was put:
+
+[source,java]
+----
+DefaultTimeoutMap<String, String> map = new 
DefaultTimeoutMap<>(dst.executor("purge", 1), 1_000);
+map.start();
+map.put("order-1", "pending", 30_000);
+dst.runFor(10_000);
+dst.jumpWallClock(-3_600_000);
+dst.runFor(60_000);
+// 70 s after the put the entry is still there: its expiry is a wall clock 
time, so it now expires an hour late
+assertEquals(1, map.size());
+----
+
+The example asks `size()` and not `get()`, because `get()` refreshes the 
expiry of the entry, from the wall clock as it
+is after the jump. After a forward jump of an hour instead, the entry is 
evicted by the next purge after the jump (here
+1 second later). In a world, let the seed choose the jump 
(`dst.jumpWallClockBetween(0, 60_000, -3_600_000, 3_600_000)`,
+which writes it to the trace), and decide from the contract of the component 
what a jump may change: an entry that
+expires late or early by the size of the jump can be what the component 
documents, while an exchange that is lost or
+completed twice is not. As for any fault, record which jump excuses which 
violation.
+
 === Escapes and strict mode
 
 Before the first seed, the harness scans the packages under test and writes 
every *escape point* to
@@ -418,8 +470,9 @@ component's JSON (built with the component), and its copy 
in the catalog and thi
 Agents wrote nine worlds with this guide (not all of them are in the code 
base). These mistakes came up:
 
 * *Timestamps at 0.* Give the times of the fake virtual wall clock time 
(`Dst.EPOCH_MILLIS + dst.now()`, or
-  `dst.currentTimeMillis()`), not 0. A Service Bus fake with lock times in 
1970 made the lock renewer renew on every run,
-  so the world could not fail. The self-check (fail on the code before the 
fix) caught it.
+  `dst.currentTimeMillis()`, which follows the wall clock jumps of the run), 
not 0. A Service Bus fake with lock times
+  in 1970 made the lock renewer renew on every run, so the world could not 
fail. The self-check (fail on the code
+  before the fix) caught it.
 * *No end to the run.* A consumer that loops forever needs an unwind at the 
end of the run, or the run never ends:
   cancel its task through the task registry, or stop the route at the end of 
the drain phase. A consumer task that
   never returns (a pull loop) sits above the test thread on the one stack, so 
a `dst.runFor` or `dst.runUntil` in the
@@ -548,8 +601,8 @@ CAMEL-25737), `dst.replayCheckSeed` (the seed of the in-JVM 
replay test of the E
 
 [cols="1,3"]
 |===
-|`Dst` |the event loop: virtual clock, seeded random source, step trace with 
its SHA-256, timed and untimed waits,
-strict mode
+|`Dst` |the event loop: virtual clock, wall clock jumps, seeded random source, 
step trace with its SHA-256, timed and
+untimed waits, strict mode
 |`DstThreadPoolFactory`, `DstExecutor`, `DstTask` |Camel's pools and 
schedulers backed by the loop
 |`DstInstrumentation`, `DstClock`, `DstWaits` |the byte code rewrite of the 
code under test: time reads, sleeps and
 blocking waits go to the loop; `DstClock` is also the `TimeSource` provider of 
Camel core during a run
diff --git 
a/components/camel-test/camel-test-dst/src/main/java/org/apache/camel/test/dst/Dst.java
 
b/components/camel-test/camel-test-dst/src/main/java/org/apache/camel/test/dst/Dst.java
index 7df58495f69e..f4af330429fa 100644
--- 
a/components/camel-test/camel-test-dst/src/main/java/org/apache/camel/test/dst/Dst.java
+++ 
b/components/camel-test/camel-test-dst/src/main/java/org/apache/camel/test/dst/Dst.java
@@ -28,6 +28,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Random;
 import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
 import java.util.function.BooleanSupplier;
 
 import org.apache.camel.util.TimeSource;
@@ -53,6 +54,8 @@ public final class Dst {
 
     /** Virtual time 0 is this wall clock instant, so code that prints times 
sees plausible values. */
     public static final long EPOCH_MILLIS = 1_700_000_000_000L;
+    /** The largest wall clock jump, back or forward: 100 years. */
+    public static final long MAX_WALL_CLOCK_JUMP_MILLIS = 
TimeUnit.DAYS.toMillis(36_525);
 
     private static final int MAX_NESTING = 64;
     /** An untimed wait that has not ended after this much virtual time is 
reported as a hang. */
@@ -73,6 +76,9 @@ public final class Dst {
     private final List<DstTask<?>> running = new ArrayList<>();
     private final DstExecutor wakeups;
     private long now;
+    /** How far the wall clock jumps of this run moved the wall clock away 
from the monotonic clock. */
+    private long wallClockOffset;
+    private DstExecutor wallClock;
     private long sequence;
     private long steps;
     private int nesting;
@@ -150,9 +156,95 @@ public final class Dst {
         return now;
     }
 
-    /** Virtual wall clock time in milliseconds. */
+    /**
+     * Virtual wall clock time in milliseconds: {@link #EPOCH_MILLIS} plus 
{@link #now()}, moved by the wall clock jumps
+     * of the run ({@link #wallClockOffset()}). Without a jump it moves only 
forward, together with the monotonic clock.
+     */
     public long currentTimeMillis() {
-        return EPOCH_MILLIS + now;
+        return EPOCH_MILLIS + now + wallClockOffset;
+    }
+
+    /**
+     * How far the wall clock jumps of the run ({@link #jumpWallClock(long)}) 
have moved the wall clock from the
+     * monotonic clock, in milliseconds: negative when the wall clock was 
moved back. 0 when the run made no jump.
+     */
+    public long wallClockOffset() {
+        return wallClockOffset;
+    }
+
+    /**
+     * Moves the wall clock of the run by {@code deltaMillis}, forward when 
positive and backward when negative, as an
+     * NTP step or an operator who sets the system time does. The monotonic 
clock does not move.
+     * <p>
+     * From now on the wall clock reads see the jump: the rewritten reads of 
the code under test
+     * ({@code @DstInstrument}: {@code System.currentTimeMillis()}, {@code new 
Date()}, {@code Instant.now()} and the
+     * other {@code java.time} reads), and {@code 
TimeSource.currentTimeMillis()} and {@code TimeSource.instant()} in
+     * Camel core (for example the expiry of {@code DefaultTimeoutMap}, and 
the created time of a
+     * {@code MonotonicClock}). {@code System.nanoTime()}, {@code 
TimeSource.nanoTime()}, {@code StopWatch},
+     * {@code MonotonicClock.elapsed()}, {@link #now()}, the sleeps and waits, 
and the due times of the tasks do not see
+     * it: a task due in 10 seconds still runs 10 seconds later.
+     * <p>
+     * The jump is written to the trace. Call it from the loop thread, in the 
deterministic order of the run, or let the
+     * seed choose the jump with {@link #jumpWallClockBetween(long, long, 
long, long)}.
+     *
+     * @throws IllegalArgumentException if the wall clock would be moved more 
than {@link #MAX_WALL_CLOCK_JUMP_MILLIS}
+     *                                  away from the monotonic clock
+     */
+    public void jumpWallClock(long deltaMillis) {
+        checkLoopThread("jumpWallClock");
+        // both bounded, so the sum cannot overflow
+        boolean tooFar = deltaMillis < -MAX_WALL_CLOCK_JUMP_MILLIS || 
deltaMillis > MAX_WALL_CLOCK_JUMP_MILLIS;
+        long offset = tooFar ? 0 : wallClockOffset + deltaMillis;
+        if (tooFar || offset < -MAX_WALL_CLOCK_JUMP_MILLIS || offset > 
MAX_WALL_CLOCK_JUMP_MILLIS) {
+            throw new IllegalArgumentException(
+                    "a wall clock jump of " + deltaMillis + "ms would move the 
wall clock more than "
+                                               + MAX_WALL_CLOCK_JUMP_MILLIS + 
"ms away from the monotonic clock");
+        }
+        wallClockOffset = offset;
+        trace("wall clock jump " + (deltaMillis >= 0 ? "+" : "") + deltaMillis 
+ "ms (wall clock offset " + wallClockOffset
+              + "ms)");
+    }
+
+    /**
+     * A wall clock jump chosen by the seed: draws when it happens, between 
{@code fromMillis} and {@code toMillis} of
+     * virtual time from now, and how big it is, between {@code 
minDeltaMillis} and {@code maxDeltaMillis} (a negative
+     * value moves the wall clock back), and schedules it. Both values come 
from the seeded random source when this is
+     * called, so the same seed makes the same jump at the same time; when the 
jump is due at the same time as other
+     * tasks, the seed picks the order as for any task. The trace says when 
the jump is scheduled (its time and size)
+     * and when it happens. A drawn delta of 0 makes no jump.
+     * <p>
+     * The jump is a pending task of the run: a run that waits until nothing 
is pending runs to it, and
+     * {@link #dropPending()} or {@link #close()} drop it, after which its 
task never completes. When it happens, it
+     * fails like {@link #jumpWallClock(long)} if the wall clock would end up 
more than
+     * {@link #MAX_WALL_CLOCK_JUMP_MILLIS} away from the monotonic clock 
(after other jumps).
+     *
+     * @return the scheduled jump; its result is the delta in milliseconds 
once it has happened
+     */
+    public DstTask<Long> jumpWallClockBetween(long fromMillis, long toMillis, 
long minDeltaMillis, long maxDeltaMillis) {
+        checkLoopThread("jumpWallClockBetween");
+        if (fromMillis < 0 || toMillis < fromMillis || toMillis > 
MAX_WAIT_MILLIS * 365) {
+            throw new IllegalArgumentException(
+                    "the time of the jump must be 0 <= from <= to <= a year: " 
+ fromMillis + ", " + toMillis);
+        }
+        if (maxDeltaMillis < minDeltaMillis || minDeltaMillis < 
-MAX_WALL_CLOCK_JUMP_MILLIS
+                || maxDeltaMillis > MAX_WALL_CLOCK_JUMP_MILLIS) {
+            throw new IllegalArgumentException(
+                    "the size of the jump must be -" + 
MAX_WALL_CLOCK_JUMP_MILLIS + " <= min <= max <= "
+                                               + MAX_WALL_CLOCK_JUMP_MILLIS + 
": " + minDeltaMillis + ", "
+                                               + maxDeltaMillis);
+        }
+        long at = between(fromMillis, toMillis);
+        long delta = between(minDeltaMillis, maxDeltaMillis);
+        trace("wall clock jump of " + (delta >= 0 ? "+" : "") + delta + "ms 
scheduled at t=" + (now + at));
+        if (wallClock == null) {
+            wallClock = new DstExecutor(this, "wall-clock", Integer.MAX_VALUE);
+        }
+        return wallClock.schedule("wall clock jump " + (delta >= 0 ? "+" : "") 
+ delta + "ms", at, () -> {
+            if (delta != 0) {
+                jumpWallClock(delta);
+            }
+            return delta;
+        });
     }
 
     public long steps() {
diff --git 
a/components/camel-test/camel-test-dst/src/test/java/org/apache/camel/test/dst/DstWallClockJumpTest.java
 
b/components/camel-test/camel-test-dst/src/test/java/org/apache/camel/test/dst/DstWallClockJumpTest.java
new file mode 100644
index 000000000000..8b1037dfede3
--- /dev/null
+++ 
b/components/camel-test/camel-test-dst/src/test/java/org/apache/camel/test/dst/DstWallClockJumpTest.java
@@ -0,0 +1,267 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.test.dst;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.support.DefaultTimeoutMap;
+import org.apache.camel.support.MonotonicClock;
+import org.apache.camel.test.dst.sample.SampleClock;
+import org.apache.camel.util.StopWatch;
+import org.apache.camel.util.TimeSource;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A run can move its wall clock forward or backward apart from the monotonic 
clock: the wall clock reads of the code
+ * under test and of Camel core (through {@code TimeSource}) see the jump, the 
monotonic clock and the due times of the
+ * tasks do not, and a jump chosen by the seed replays exactly.
+ */
+@DstInstrument("org.apache.camel.test.dst.sample")
+class DstWallClockJumpTest {
+
+    @Test
+    void aBackwardJumpMovesOnlyTheWallClock() {
+        Dst dst = new Dst(1);
+        try {
+            long[] wall = new long[4];
+            long[] mono = new long[2];
+            StopWatch[] watch = new StopWatch[1];
+            MonotonicClock[] clock = new MonotonicClock[1];
+            DstExecutor ex = dst.executor("ex", 1);
+            ex.schedule("before", 1_000, () -> {
+                wall[0] = TimeSource.currentTimeMillis();
+                mono[0] = TimeSource.nanoTime();
+                watch[0] = new StopWatch();
+                clock[0] = new MonotonicClock();
+                dst.jumpWallClock(-3_600_000);
+                wall[1] = TimeSource.currentTimeMillis();
+            });
+            ex.schedule("after", 11_000, () -> {
+                wall[2] = TimeSource.currentTimeMillis();
+                wall[3] = TimeSource.instant().toEpochMilli();
+                mono[1] = TimeSource.nanoTime();
+            });
+            dst.runUntilQuiet();
+            assertEquals(Dst.EPOCH_MILLIS + 1_000, wall[0]);
+            assertEquals(Dst.EPOCH_MILLIS + 1_000 - 3_600_000, wall[1], "the 
wall clock went back an hour at once");
+            assertEquals(Dst.EPOCH_MILLIS + 11_000 - 3_600_000, wall[2], "and 
moves on from there");
+            assertEquals(wall[2], wall[3]);
+            assertEquals(10_000_000_000L, mono[1] - mono[0], "the monotonic 
clock did not jump");
+            assertEquals(11_000, dst.now(), "the task was due 10 s after the 
jump, as scheduled");
+            assertEquals(10_000, watch[0].taken());
+            assertEquals(10_000, clock[0].elapsed());
+            assertEquals(Dst.EPOCH_MILLIS + 1_000, clock[0].getCreated(), "its 
created time is a wall clock time");
+            assertEquals(-3_600_000, dst.wallClockOffset());
+            assertEquals(dst.currentTimeMillis(), Dst.EPOCH_MILLIS + dst.now() 
+ dst.wallClockOffset());
+            assertTrue(dst.traceLines().stream().anyMatch(l -> 
l.contains("wall clock jump -3600000ms")),
+                    String.join("\n", dst.traceLines()));
+        } finally {
+            dst.close();
+        }
+    }
+
+    @Test
+    void theRewrittenWallClockReadsSeeAForwardJump() {
+        Dst dst = new Dst(1);
+        try {
+            List<List<Long>> seen = new ArrayList<>();
+            long[] millis = new long[1];
+            DstExecutor ex = dst.executor("ex", 1);
+            ex.schedule("jump", 1_000, () -> dst.jumpWallClock(86_400_000));
+            ex.schedule("read", 2_000, () -> {
+                seen.add(SampleClock.javaTimeReads());
+                millis[0] = SampleClock.now();
+            });
+            dst.runUntilQuiet();
+            long expected = Dst.EPOCH_MILLIS + 2_000 + 86_400_000;
+            assertEquals(expected, millis[0]);
+            for (long read : seen.get(0)) {
+                assertEquals(expected, read, seen.toString());
+            }
+        } finally {
+            dst.close();
+        }
+    }
+
+    @Test
+    void anExpiringEntryUnderABackwardJump() throws Exception {
+        // the example of the guide: an entry with a timeout of 30 s in a 
DefaultTimeoutMap, which reads the wall clock
+        // (size() does not refresh the expiry of an entry, get() would)
+        Dst dst = new Dst(1);
+        try {
+            DefaultTimeoutMap<String, String> map = new 
DefaultTimeoutMap<>(dst.executor("purge", 1), 1_000);
+            map.start();
+            map.put("order-1", "pending", 30_000);
+            dst.runFor(10_000);
+            dst.jumpWallClock(-3_600_000);
+            dst.runFor(60_000);
+            assertEquals(1, map.size(), "70 s after the put the entry is still 
there: it now expires an hour late");
+            dst.runFor(3_600_000 - 70_000 + 30_000);
+            assertEquals(1, map.size(), "still there when its expiry, an hour 
late, is reached");
+            dst.runFor(1_000);
+            assertEquals(0, map.size(), "evicted by the next purge, an hour 
late");
+            map.stop();
+        } finally {
+            dst.close();
+        }
+    }
+
+    @Test
+    void anExpiringEntryUnderAForwardJump() throws Exception {
+        Dst dst = new Dst(1);
+        try {
+            DefaultTimeoutMap<String, String> map = new 
DefaultTimeoutMap<>(dst.executor("purge", 1), 1_000);
+            map.start();
+            map.put("order-1", "pending", 30_000);
+            dst.runFor(10_000);
+            assertEquals(1, map.size(), "the purge at t=10 s ran before the 
jump");
+            dst.jumpWallClock(3_600_000);
+            dst.runFor(999);
+            assertEquals(1, map.size());
+            dst.runFor(1);
+            assertEquals(0, map.size(), "evicted by the next purge after the 
jump, at t=11 s");
+            map.stop();
+        } finally {
+            dst.close();
+        }
+    }
+
+    @Test
+    void theSeedChoosesWhenAndHowFarTheWallClockJumps() throws Exception {
+        List<String> first = jumpRun(42);
+        List<String> again = jumpRun(42);
+        assertEquals(first, again, "the same seed makes the same jump at the 
same time");
+        Set<String> differing = new HashSet<>();
+        for (long seed = 1; seed <= 20; seed++) {
+            List<String> run = jumpRun(seed);
+            differing.add(run.get(0));
+            long at = Long.parseLong(run.get(1));
+            long delta = Long.parseLong(run.get(2));
+            assertTrue(at >= 5_000 && at <= 65_000, "jump at " + at);
+            assertTrue(delta >= -7_200_000 && delta <= 7_200_000, "jump of " + 
delta);
+        }
+        assertTrue(differing.size() > 15, "consecutive seeds draw different 
jumps: " + differing);
+    }
+
+    /** One run with a seeded jump; returns the trace hash, the time of the 
jump and its size. */
+    private static List<String> jumpRun(long seed) throws Exception {
+        Dst dst = new Dst(seed);
+        try {
+            DstTask<Long> jump = dst.jumpWallClockBetween(5_000, 65_000, 
-7_200_000, 7_200_000);
+            dst.executor("tick", 1).scheduleAtFixedRate(() -> dst.trace("tick 
wall=" + dst.currentTimeMillis()),
+                    0, 1_000, TimeUnit.MILLISECONDS);
+            dst.runFor(70_000);
+            assertTrue(jump.isDone());
+            long delta = jump.get();
+            assertEquals(delta, dst.wallClockOffset());
+            assertEquals(Dst.EPOCH_MILLIS + dst.now() + delta, 
dst.currentTimeMillis());
+            String at = dst.traceLines().stream()
+                    .filter(l -> l.contains("run wall clock jump"))
+                    .map(l -> l.substring(l.indexOf("t=") + 2, l.indexOf(' ', 
l.indexOf("t="))))
+                    .findFirst().orElseThrow();
+            return List.of(dst.traceHash(), at, String.valueOf(delta));
+        } finally {
+            dst.close();
+        }
+    }
+
+    @Test
+    void aDrawnDeltaOfZeroMakesNoJumpAndAOneValueRangeIsExact() throws 
Exception {
+        Dst dst = new Dst(7);
+        try {
+            DstTask<Long> none = dst.jumpWallClockBetween(1_000, 1_000, 0, 0);
+            DstTask<Long> exact = dst.jumpWallClockBetween(2_000, 2_000, 
-5_000, -5_000);
+            dst.runFor(1_500);
+            assertTrue(none.isDone());
+            assertEquals(0L, none.get());
+            assertEquals(0, dst.wallClockOffset(), "no jump");
+            dst.runFor(1_000);
+            assertEquals(-5_000L, exact.get());
+            assertEquals(-5_000, dst.wallClockOffset());
+            assertEquals(1, dst.traceLines().stream().filter(l -> 
l.contains("(wall clock offset")).count(),
+                    String.join("\n", dst.traceLines()));
+        } finally {
+            dst.close();
+        }
+    }
+
+    @Test
+    void eachRunStartsWithoutAJump() {
+        Dst dst = new Dst(1);
+        try {
+            dst.jumpWallClock(-60_000);
+        } finally {
+            dst.close();
+        }
+        Dst next = new Dst(1);
+        try {
+            assertEquals(0, next.wallClockOffset());
+            assertEquals(Dst.EPOCH_MILLIS, next.currentTimeMillis());
+            assertEquals(Dst.EPOCH_MILLIS, TimeSource.currentTimeMillis());
+        } finally {
+            next.close();
+        }
+        assertTrue(Math.abs(TimeSource.currentTimeMillis() - 
System.currentTimeMillis()) < 60_000,
+                "the system clock is back after the run");
+    }
+
+    @Test
+    void aJumpIsMadeOnTheLoopThreadOnly() throws Exception {
+        Dst dst = new Dst(1);
+        try {
+            Throwable[] failed = new Throwable[1];
+            Thread outside = new Thread(() -> {
+                try {
+                    dst.jumpWallClock(1_000);
+                } catch (Throwable e) {
+                    failed[0] = e;
+                }
+            }, "outside-jump");
+            outside.start();
+            outside.join();
+            assertNotNull(failed[0]);
+            assertInstanceOf(IllegalStateException.class, failed[0]);
+            assertEquals(0, dst.wallClockOffset());
+            assertThrows(IllegalArgumentException.class, () -> 
dst.jumpWallClockBetween(10, 5, 0, 1));
+            assertThrows(IllegalArgumentException.class, () -> 
dst.jumpWallClockBetween(0, 5, 1, 0));
+            assertThrows(IllegalArgumentException.class, () -> 
dst.jumpWallClockBetween(-1, 5, 0, 1));
+            assertThrows(IllegalArgumentException.class, () -> 
dst.jumpWallClockBetween(0, Long.MAX_VALUE, 0, 1));
+            assertThrows(IllegalArgumentException.class, () -> 
dst.jumpWallClockBetween(0, 5, Long.MIN_VALUE, 0));
+            assertThrows(IllegalArgumentException.class, () -> 
dst.jumpWallClock(Long.MAX_VALUE));
+            assertThrows(IllegalArgumentException.class, () -> 
dst.jumpWallClock(Long.MIN_VALUE));
+            dst.jumpWallClock(Dst.MAX_WALL_CLOCK_JUMP_MILLIS);
+            assertThrows(IllegalArgumentException.class, () -> 
dst.jumpWallClock(1), "the offset is bounded too");
+            assertEquals(Dst.MAX_WALL_CLOCK_JUMP_MILLIS, 
dst.wallClockOffset());
+            assertEquals(1, dst.traceLines().stream().filter(l -> 
l.contains("wall clock jump")).count(),
+                    "only the jump that was made is traced");
+            assertEquals(Instant.ofEpochMilli(Dst.EPOCH_MILLIS + 
Dst.MAX_WALL_CLOCK_JUMP_MILLIS), TimeSource.instant());
+        } finally {
+            dst.close();
+        }
+    }
+}

Reply via email to