Skip to content

Commit 718f43e

Browse files
committed
Fix timeout deadlines across stalled clock publication and restarts
1 parent 03d34d8 commit 718f43e

2 files changed

Lines changed: 116 additions & 40 deletions

File tree

‎fastclock.go‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,13 @@ type fastclock struct {
2929
clockEnd atomicTime // When clock updater is supposed to stop (>= any existing deadline)
3030

3131
// current and clockEnd can be read via atomic loads.
32-
// Reads and writes of other fields require mu to be held.
32+
// start is immutable. Reads and writes of running require mu to be held.
3333
mu sync.Mutex
3434
start time.Time // Time corresponding to fasttime(0)
3535
running bool // Is a clock updater running?
3636
}
3737

38-
var fast fastclock
38+
var fast = fastclock{start: time.Now()}
3939

4040
// reached returns true if current time is at or past t.
4141
func (t fasttime) reached() bool {
@@ -44,9 +44,11 @@ func (t fasttime) reached() bool {
4444

4545
// makeDeadline returns a time that is approximately time.Now().Add(d)
4646
func makeDeadline(d time.Duration) fasttime {
47-
// Increase the deadline since the clock we are reading may be
48-
// just about to tick forwards.
49-
end := fast.current.read() + durationToTicks(d+clockPeriod)
47+
// The publisher may be stopped or descheduled. Only authoritative monotonic
48+
// time can establish a new deadline; the cached time is for polling only.
49+
// Round each term upwards and add ticks, not durations, so even a maximum
50+
// finite timeout cannot overflow or acquire an early deadline.
51+
end := durationToTicksCeil(time.Since(fast.start)) + durationToTicksCeil(d) + durationToTicksCeil(clockPeriod)
5052

5153
// Start or extend clock if necessary.
5254
if end > fast.clockEnd.read() {
@@ -60,10 +62,6 @@ func extendClock(end fasttime) {
6062
fast.mu.Lock()
6163
defer fast.mu.Unlock()
6264

63-
if fast.start.IsZero() {
64-
fast.start = time.Now()
65-
}
66-
6765
// Extend the running time to cover end as well as a bit of slop.
6866
if shutdown := end + durationToTicks(time.Second); shutdown > fast.clockEnd.read() {
6967
fast.clockEnd.write(shutdown)
@@ -102,6 +100,14 @@ func durationToTicks(d time.Duration) fasttime {
102100
return fasttime(d) >> 20
103101
}
104102

103+
func durationToTicksCeil(d time.Duration) fasttime {
104+
ticks := durationToTicks(d)
105+
if d&((1<<20)-1) != 0 {
106+
ticks++
107+
}
108+
return ticks
109+
}
110+
105111
const DefaultClockPeriod = 100 * time.Millisecond
106112

107113
// clockPeriod is the approximate interval between updates of approximateClock.

‎fastclock_test.go‎

Lines changed: 101 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package regexp2
22

33
import (
4-
"fmt"
4+
"math"
5+
"math/big"
6+
"sync"
57
"testing"
68
"time"
79
)
@@ -12,29 +14,29 @@ func init() {
1214
SetTimeoutCheckPeriod(time.Millisecond)
1315
}
1416
func TestDeadline(t *testing.T) {
15-
for _, delay := range []time.Duration{
16-
clockPeriod / 10,
17-
clockPeriod,
18-
clockPeriod * 5,
19-
clockPeriod * 10,
20-
} {
21-
delay := delay // Make copy for parallel sub-test.
22-
t.Run(fmt.Sprint(delay), func(t *testing.T) {
23-
t.Parallel()
24-
start := time.Now()
25-
d := makeDeadline(delay)
26-
if d.reached() {
27-
t.Fatalf("deadline (%v) unexpectedly expired immediately", delay)
28-
}
29-
time.Sleep(delay / 2)
30-
if d.reached() {
31-
t.Fatalf("deadline (%v) expired too soon (after %v)", delay, time.Since(start))
32-
}
33-
time.Sleep(delay/2 + 2*clockPeriod) // Give clock time to tick
34-
if !d.reached() {
35-
t.Fatalf("deadline (%v) did not expire within %v", delay, time.Since(start))
36-
}
37-
})
17+
StopTimeoutClock()
18+
t.Cleanup(StopTimeoutClock)
19+
fast.current.write(41)
20+
if fasttime(42).reached() {
21+
t.Fatal("deadline expired before its tick")
22+
}
23+
fast.current.write(42)
24+
if !fasttime(42).reached() {
25+
t.Fatal("deadline did not expire at its tick")
26+
}
27+
fast.current.write(durationToTicks(time.Since(fast.start)))
28+
29+
deadline := makeDeadline(clockPeriod)
30+
guard := time.NewTimer(time.Second)
31+
defer guard.Stop()
32+
poll := time.NewTicker(clockPeriod)
33+
defer poll.Stop()
34+
for !deadline.reached() {
35+
select {
36+
case <-poll.C:
37+
case <-guard.C:
38+
t.Fatal("updater failed to publish expiration")
39+
}
3840
}
3941
}
4042

@@ -44,15 +46,83 @@ func TestStopTimeoutClock(t *testing.T) {
4446
r := MustCompile(".", 0)
4547
r.MatchTimeout = time.Second * 10
4648

47-
r.MatchString("a")
48-
start := time.Now()
49-
StopTimeoutClock()
50-
stop := time.Now()
51-
52-
if want, got := clockPeriod*2, stop.Sub(start); want < got {
53-
t.Errorf("Expected duration less than %v, got %v", want, got)
49+
if matched, err := r.MatchString("a"); err != nil || !matched {
50+
t.Fatalf("match: %v, %v", matched, err)
5451
}
52+
StopTimeoutClock()
5553
if want, got := false, fast.running; want != got {
5654
t.Errorf("Expected isRunning to be %v, got %v", want, got)
5755
}
5856
}
57+
58+
// The clock publisher is deliberately absent: this is the state of a live
59+
// updater descheduled before it can publish another tick. No timing luck is
60+
// needed to exercise the deadline constructor.
61+
func TestDeadlineIgnoresStalledPublisher(t *testing.T) {
62+
StopTimeoutClock()
63+
fast.mu.Lock()
64+
originalEpoch := fast.start
65+
fast.start = time.Now().Add(-10 * time.Second)
66+
fast.current.write(0)
67+
fast.clockEnd.write(fasttime(math.MaxInt64))
68+
fast.running = true
69+
fast.mu.Unlock()
70+
t.Cleanup(func() {
71+
fast.mu.Lock()
72+
fast.running = false
73+
fast.start = originalEpoch
74+
fast.current.write(durationToTicks(time.Since(fast.start)))
75+
fast.clockEnd.write(0)
76+
fast.mu.Unlock()
77+
})
78+
for _, timeout := range []time.Duration{0, 1, 1<<20 - 1, 1 << 20, time.Second, math.MaxInt64} {
79+
before := time.Since(fast.start)
80+
deadline := makeDeadline(timeout)
81+
after := time.Since(fast.start)
82+
// Tick arithmetic also keeps the independent oracle from overflowing.
83+
minimum := new(big.Int).Add(big.NewInt(int64(before)), big.NewInt(int64(timeout)))
84+
represented := new(big.Int).Lsh(big.NewInt(int64(deadline)), 20)
85+
maximum := durationToTicks(after) + durationToTicks(timeout) + durationToTicks(clockPeriod) + 3
86+
if represented.Cmp(minimum) < 0 || deadline > maximum {
87+
t.Fatalf("timeout %v: deadline %d precedes %s ns or exceeds %d ticks", timeout, deadline, minimum, maximum)
88+
}
89+
}
90+
}
91+
92+
func TestDeadlineRestartsAndExtendsClock(t *testing.T) {
93+
StopTimeoutClock()
94+
originalEpoch := fast.start
95+
fast.start = time.Now().Add(-10 * time.Second)
96+
fast.current.write(0)
97+
fast.clockEnd.write(0)
98+
t.Cleanup(func() {
99+
StopTimeoutClock()
100+
fast.start = originalEpoch
101+
fast.current.write(durationToTicks(time.Since(fast.start)))
102+
fast.clockEnd.write(0)
103+
})
104+
var wg sync.WaitGroup
105+
deadlines := make([]fasttime, 16)
106+
for i := range deadlines {
107+
wg.Add(1)
108+
go func(i int) {
109+
defer wg.Done()
110+
before := durationToTicks(time.Since(fast.start))
111+
deadlines[i] = makeDeadline(time.Duration(i+1) * time.Second)
112+
if deadlines[i] < before+durationToTicks(time.Duration(i+1)*time.Second) {
113+
t.Errorf("deadline %d predates construction", deadlines[i])
114+
}
115+
}(i)
116+
}
117+
wg.Wait()
118+
fast.mu.Lock()
119+
defer fast.mu.Unlock()
120+
if !fast.running {
121+
t.Fatal("updater did not restart")
122+
}
123+
for _, deadline := range deadlines {
124+
if deadline > fast.clockEnd.read() {
125+
t.Fatalf("horizon lost deadline %d", deadline)
126+
}
127+
}
128+
}

0 commit comments

Comments
 (0)