Skip to content

Commit

Permalink
backoff: Always wait a positive duration
Browse files Browse the repository at this point in the history
Fixes: #602
  • Loading branch information
gnprice committed Jun 5, 2024
1 parent 012b601 commit e85d6c5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/api/backoff.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ class BackoffMachine {
/// maximizes the range while preserving a capped exponential shape on
/// the expected value. Greg discusses this in more detail at:
/// https://github.com/zulip/zulip-mobile/pull/3841
///
/// The duration is always positive; [Duration] works in microseconds, so
/// we deviate from the idealized uniform distribution just by rounding
/// the smallest durations up to one microsecond instead of down to zero.
/// Because in the real world any delay takes nonzero time, this mainly
/// affects tests that use fake time, and keeps their behavior more realistic.
Future<void> wait() async {
_startTime ??= DateTime.now();

Expand All @@ -45,7 +51,8 @@ class BackoffMachine {
* min(_durationCeilingMs,
_firstDurationMs * pow(_base, _waitsCompleted));

await Future<void>.delayed(Duration(milliseconds: durationMs.round()));
await Future<void>.delayed(Duration(
microseconds: max(1, (1000 * durationMs).round())));

_waitsCompleted++;
}
Expand Down
21 changes: 21 additions & 0 deletions test/api/backoff_test.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:math';

import 'package:checks/checks.dart';
import 'package:clock/clock.dart';
Expand Down Expand Up @@ -51,4 +52,24 @@ void main() {
check(maxFromAllTrials).isGreaterThan(expectedMax * 0.75);
}
});

test('BackoffMachine timeouts are always positive', () {
// Regression test for: https://github.com/zulip/zulip-flutter/issues/602
// This is a randomized test with a false-failure rate of zero.

// In the pre-#602 implementation, the first timeout was zero
// when a random number from [0, 100] was below 0.5.
// [numTrials] is chosen so that an implementation with that behavior
// will fail the test with probability 99%.
const hypotheticalFailureRate = 0.5 / 100;
const numTrials = 2 * ln10 / hypotheticalFailureRate;

awaitFakeAsync((async) async {
for (int i = 0; i < numTrials; i++) {
final duration = await measureWait(BackoffMachine().wait());
check(duration).isGreaterThan(Duration.zero);
}
check(async.pendingTimers).isEmpty();
});
});
}

0 comments on commit e85d6c5

Please sign in to comment.