Skip to content

Commit 1cfcbd7

Browse files
TMHSDigitalclaude
andcommitted
Stop handing out rate slots past -max-duration (#460)
-max-duration was checked only before a worker started a job, so under a low -rate every worker parked in the limiter when the deadline passed still sent its queries afterwards: a 2s budget at -rate 5 ran 43s. The scan now carries its deadline on the context (WithSendDeadline, attached after the pre-scan checks, which keep their exemption from #340). The limiter refuses a slot at or after it with ErrPastDeadline, which classifies as canceled. ResolveTypes reserves all of a name's slots at once, so a name is fully sent or not at all, and a job the deadline kept from its slots is reported as skipped, so it stays resumable. The lab repro now ends at the budget plus the checks. Fixes #460 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 5fbcd4b commit 1cfcbd7

5 files changed

Lines changed: 176 additions & 21 deletions

File tree

‎internal/dns/ratelimit.go‎

Lines changed: 68 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package dns
22

33
import (
44
"context"
5+
"errors"
56
"sync"
67
"time"
78
)
@@ -64,22 +65,55 @@ func (l *RateLimiter) Rate() int {
6465
return int(time.Second / l.interval)
6566
}
6667

67-
// Wait blocks until the caller's reserved slot arrives or ctx is done.
68-
func (l *RateLimiter) Wait(ctx context.Context) error {
69-
if l == nil {
70-
return ctx.Err()
68+
// ErrPastDeadline is returned by Wait when the caller's slot would come at or
69+
// after the send deadline on its context (WithSendDeadline): the query is
70+
// never sent. Classify maps it to OutcomeCanceled.
71+
var ErrPastDeadline = errors.New("rate slot past the send deadline")
72+
73+
type sendDeadlineKey struct{}
74+
75+
// WithSendDeadline attaches a send deadline to ctx: from then on, rate-limiter
76+
// waits under ctx return ErrPastDeadline instead of a slot at or after t, so a
77+
// -max-duration budget is not overrun by queries still queued for the rate
78+
// (#460). Lookups already sent finish under their own timeout. A zero t
79+
// returns ctx unchanged.
80+
func WithSendDeadline(ctx context.Context, t time.Time) context.Context {
81+
if t.IsZero() {
82+
return ctx
7183
}
84+
return context.WithValue(ctx, sendDeadlineKey{}, t)
85+
}
86+
87+
func sendDeadlineFrom(ctx context.Context) time.Time {
88+
t, _ := ctx.Value(sendDeadlineKey{}).(time.Time)
89+
return t
90+
}
91+
92+
// reserveN hands out n consecutive slots at once and returns the time of the
93+
// first one and the spacing, or ErrPastDeadline, reserving none, when the last
94+
// slot would come at or after the send deadline on ctx. A name's queries are
95+
// thus all sent or none are, so the deadline cannot strand a half-sent lookup
96+
// (#460).
97+
func (l *RateLimiter) reserveN(ctx context.Context, n int) (time.Time, time.Duration, error) {
98+
deadline := sendDeadlineFrom(ctx)
7299
l.mu.Lock()
73-
now := time.Now()
100+
defer l.mu.Unlock()
74101
slot := l.next
75-
if slot.Before(now) {
102+
if now := time.Now(); slot.Before(now) {
76103
slot = now
77104
}
78-
l.next = slot.Add(l.interval)
79-
l.reserved++
80-
l.mu.Unlock()
105+
last := slot.Add(l.interval * time.Duration(n-1))
106+
if !deadline.IsZero() && !last.Before(deadline) {
107+
return time.Time{}, 0, ErrPastDeadline
108+
}
109+
l.next = last.Add(l.interval)
110+
l.reserved += int64(n)
111+
return slot, l.interval, nil
112+
}
81113

82-
d := time.Until(slot)
114+
// sleepUntil blocks until t or until ctx is done.
115+
func sleepUntil(ctx context.Context, t time.Time) error {
116+
d := time.Until(t)
83117
if d <= 0 {
84118
return ctx.Err()
85119
}
@@ -93,6 +127,30 @@ func (l *RateLimiter) Wait(ctx context.Context) error {
93127
}
94128
}
95129

130+
// Wait blocks until the caller's reserved slot arrives or ctx is done. A slot
131+
// that would come at or after the send deadline on ctx is not reserved, and
132+
// Wait returns ErrPastDeadline at once.
133+
func (l *RateLimiter) Wait(ctx context.Context) error {
134+
if l == nil {
135+
return ctx.Err()
136+
}
137+
deadline := sendDeadlineFrom(ctx)
138+
l.mu.Lock()
139+
now := time.Now()
140+
slot := l.next
141+
if slot.Before(now) {
142+
slot = now
143+
}
144+
if !deadline.IsZero() && !slot.Before(deadline) {
145+
l.mu.Unlock()
146+
return ErrPastDeadline
147+
}
148+
l.next = slot.Add(l.interval)
149+
l.reserved++
150+
l.mu.Unlock()
151+
return sleepUntil(ctx, slot)
152+
}
153+
96154
type limiterKey struct{}
97155

98156
// WithLimiter attaches l to ctx. Every lookup ResolveTypes performs under that

‎internal/dns/ratelimit_test.go‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,44 @@ func TestRateLimiterCancel(t *testing.T) {
8282
}
8383
}
8484

85+
// TestRateLimiterSendDeadline covers #460: a slot at or after the send
86+
// deadline is refused at once and not reserved, and reserveN hands out all of
87+
// a name's slots or none.
88+
func TestRateLimiterSendDeadline(t *testing.T) {
89+
l := NewRateLimiter(10) // 100ms apart
90+
ctx := WithSendDeadline(context.Background(), time.Now().Add(250*time.Millisecond))
91+
for i := range 3 { // slots at about 0, 100 and 200ms
92+
if err := l.Wait(ctx); err != nil {
93+
t.Fatalf("slot %d: %v", i, err)
94+
}
95+
}
96+
start := time.Now()
97+
if err := l.Wait(ctx); !errors.Is(err, ErrPastDeadline) {
98+
t.Fatalf("slot past the deadline: %v, want ErrPastDeadline", err)
99+
}
100+
if waited := time.Since(start); waited > 50*time.Millisecond {
101+
t.Errorf("refusal took %v, want immediate", waited)
102+
}
103+
if l.reserved != 3 {
104+
t.Errorf("reserved %d slots, want the refused one left out", l.reserved)
105+
}
106+
if Classify(ErrPastDeadline) != OutcomeCanceled {
107+
t.Error("ErrPastDeadline must classify as canceled, not as a resolver failure")
108+
}
109+
110+
m := NewRateLimiter(10)
111+
ctx = WithSendDeadline(context.Background(), time.Now().Add(150*time.Millisecond))
112+
if _, _, err := m.reserveN(ctx, 3); !errors.Is(err, ErrPastDeadline) || m.reserved != 0 {
113+
t.Errorf("reserveN(3) past the deadline: err %v, reserved %d; want ErrPastDeadline and none", err, m.reserved)
114+
}
115+
if _, step, err := m.reserveN(ctx, 2); err != nil || step != 100*time.Millisecond || m.reserved != 2 {
116+
t.Errorf("reserveN(2): err %v, step %v, reserved %d", err, step, m.reserved)
117+
}
118+
if WithSendDeadline(context.Background(), time.Time{}) != context.Background() {
119+
t.Error("a zero send deadline must leave ctx unchanged")
120+
}
121+
}
122+
85123
// TestResolverPacesWireQueries covers #32: -rate must bound DNS messages on the
86124
// wire, not candidate names. Each name below costs two queries (A and AAAA),
87125
// so a per-name limiter would finish in half the time this test requires. The

‎internal/dns/resolver.go‎

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ func Classify(err error) Outcome {
9191
if err == nil {
9292
return OutcomeFound
9393
}
94-
if errors.Is(err, context.Canceled) {
94+
if errors.Is(err, context.Canceled) || errors.Is(err, ErrPastDeadline) {
9595
return OutcomeCanceled
9696
}
9797
var de *net.DNSError
@@ -364,14 +364,33 @@ func (l Lookup) ResolveTypes(ctx context.Context, domain string) ([]Record, time
364364
recs []Record
365365
err error
366366
}
367+
// Every type's rate slots are reserved together, so a send deadline lets
368+
// all of the name's queries go or none (#460). Each type then waits for
369+
// its own last slot.
370+
sendAt := make([]time.Time, len(types))
371+
if lim := limiterFrom(ctx); lim != nil {
372+
n := 0
373+
for _, t := range types {
374+
n += int(queriesPerType[t])
375+
}
376+
first, step, err := lim.reserveN(ctx, n)
377+
if err != nil {
378+
return nil, time.Since(start), err
379+
}
380+
k := 0
381+
for i, t := range types {
382+
k += int(queriesPerType[t])
383+
sendAt[i] = first.Add(step * time.Duration(k-1))
384+
}
385+
}
367386
answers := make([]answer, len(types))
368387
if len(types) == 1 {
369-
answers[0].recs, answers[0].err = l.lookupOne(ctx, domain, types[0])
388+
answers[0].recs, answers[0].err = l.lookupOne(ctx, domain, types[0], sendAt[0])
370389
} else {
371390
var wg sync.WaitGroup
372391
for i, t := range types {
373392
wg.Go(func() {
374-
answers[i].recs, answers[i].err = l.lookupOne(ctx, domain, t)
393+
answers[i].recs, answers[i].err = l.lookupOne(ctx, domain, t, sendAt[i])
375394
})
376395
}
377396
wg.Wait()
@@ -388,14 +407,12 @@ func (l Lookup) ResolveTypes(ctx context.Context, domain string) ([]Record, time
388407
return records, time.Since(start), worstErr
389408
}
390409

391-
// lookupOne is one type's lookup for ResolveTypes: its rate-limiter slots,
410+
// lookupOne is one type's lookup for ResolveTypes: a wait until sendAt, the
411+
// last of its reserved rate-limiter slots (zero when there is no limiter),
392412
// then the lookup under its own timeout and wire budget.
393-
func (l Lookup) lookupOne(ctx context.Context, domain, t string) ([]Record, error) {
394-
lim := limiterFrom(ctx)
395-
for range queriesPerType[t] {
396-
if err := lim.Wait(ctx); err != nil {
397-
return nil, err
398-
}
413+
func (l Lookup) lookupOne(ctx context.Context, domain, t string, sendAt time.Time) ([]Record, error) {
414+
if err := sleepUntil(ctx, sendAt); err != nil {
415+
return nil, err
399416
}
400417
b := &wireBudget{prepaid: queriesPerType[t]}
401418
lookupCtx, cancel := context.WithTimeout(context.WithValue(ctx, budgetKey{}, b), l.Timeout)

‎internal/scan/runner.go‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,9 @@ func Run(ctx context.Context, cfg Config, events chan<- Event) {
359359
// when the scan started (a later -dL target) stays spent.
360360
cfg.Deadline = cfg.Deadline.Add(time.Since(checksStarted))
361361
}
362+
// From here no rate slot is handed out past the deadline, so workers
363+
// parked in the limiter when it passes send nothing more (#460).
364+
ctx = dns.WithSendDeadline(ctx, cfg.Deadline)
362365
cfg.resumeDepth = resumeDepths(cfg)
363366

364367
st := &scanState{
@@ -590,6 +593,12 @@ func (s *scanState) runWorkers(ctx context.Context, workers int, jobs <-chan []j
590593
// candidates the dispatcher never handed out (#190).
591594
if !s.cfg.pastDeadline() {
592595
c = completion{root: j.root, finished: s.processJob(ctx, j)}
596+
// Unfinished without a cancellation means the limiter
597+
// had no slot left before the deadline: never looked
598+
// up either (#460).
599+
if !c.finished && ctx.Err() == nil && !s.cfg.Deadline.IsZero() {
600+
c.skipped = true
601+
}
593602
}
594603
done = append(done, c)
595604
}
@@ -676,7 +685,9 @@ func (s *scanState) processJob(ctx context.Context, j job) (finished bool) {
676685
// A lookup cut short by cancellation (Ctrl+C, or the reliability guard's own
677686
// cancel) says nothing about the resolver. Leave it out of every counter so
678687
// an interrupt cannot inflate the failure rate or trip the guard (#42).
679-
if settle(ctx, outcome) == dns.OutcomeCanceled {
688+
// So is one whose queries the -max-duration deadline kept from being sent
689+
// (#460).
690+
if settle(ctx, outcome) == dns.OutcomeCanceled || outcome == dns.OutcomeCanceled {
680691
return false
681692
}
682693

‎internal/scan/runner_test.go‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,37 @@ func TestRunDeadlineStopsAdmission(t *testing.T) {
642642
}
643643
}
644644

645+
// TestRunDeadlineBoundsRateWaits covers #460: under a low -rate every worker
646+
// is parked in the limiter when the budget runs out. None of them may send
647+
// after it: the scan ends close to the deadline, and the names that never got
648+
// a slot are skipped, not tested.
649+
func TestRunDeadlineBoundsRateWaits(t *testing.T) {
650+
const entries = 200
651+
start := time.Now()
652+
cfg := Config{
653+
Domain: "example.com", Entries: makeEntries(entries), Concurrency: 50,
654+
Timeout: time.Second, Simulate: true, Attempts: 1, Types: []string{"A"},
655+
Rate: 10, Deadline: start.Add(300 * time.Millisecond),
656+
resolveHook: func(context.Context, string) ([]dns.Record, dns.Outcome) {
657+
return nil, dns.OutcomeNXDomain
658+
},
659+
}
660+
events := make(chan Event, 256)
661+
go Run(context.Background(), cfg, events)
662+
done, errs, _ := collect(events)
663+
if len(errs) > 0 || done == nil {
664+
t.Fatalf("errors %v, done %v", errs, done)
665+
}
666+
// Unbounded, the 50 parked workers alone would take 5 s at 10/s.
667+
if elapsed := time.Since(start); elapsed > 2*time.Second {
668+
t.Errorf("scan took %v for a 300ms budget at -rate 10", elapsed)
669+
}
670+
if done.Processed > 4 || done.Processed+done.Stats.Skipped != entries || !done.Stats.Expired {
671+
t.Errorf("processed %d, skipped %d, expired %v; want at most 4 tested and the rest of %d skipped",
672+
done.Processed, done.Stats.Skipped, done.Stats.Expired, entries)
673+
}
674+
}
675+
645676
func TestRunMaxQueriesStopsAdmission(t *testing.T) {
646677
cfg := Config{
647678
Domain: "example.com",

0 commit comments

Comments
 (0)