mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-03 12:20:05 +08:00
fix(limiter): handle stale clock samples and timestamp overflow
A caller could sample the clock at 1000 ms and pause while another caller was admitted at 2000 ms. On resuming, the first caller could load the newer last_run_ms, mistake its stale sample for a clock rollback, and replace 2000 with 1000. This reopened the 100 ms period and let another check at 2000 ms pass. Load last_run_ms before sampling the clock so the stale caller's compare-exchange fails if a newer admission has changed that value. Preserve sequential clock rollback behavior and the existing atomic orderings. The period check also added the period to last_run_ms. A last admission at u64::MAX - 55 with a 56 ms period overflowed on the next check: debug builds panicked and release builds wrapped the deadline to zero, admitting a duplicate timestamp. Compare elapsed time against the period only after confirming the clock has not moved backward, which makes the subtraction safe and preserves the exact period boundary. Enable the stale-sample and overflow regressions, keep the saved Proptest seed, and add Loom coverage for advancing time and multiple stale callers plus a deterministic test at u64::MAX.
This commit is contained in:
Generated
+206
-7
@@ -514,7 +514,16 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
|
||||
dependencies = [
|
||||
"bit-vec",
|
||||
"bit-vec 0.8.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"
|
||||
dependencies = [
|
||||
"bit-vec 0.10.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -523,6 +532,16 @@ version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0"
|
||||
dependencies = [
|
||||
"borsh",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.3.2"
|
||||
@@ -741,6 +760,30 @@ dependencies = [
|
||||
"static_assertions",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "borsh"
|
||||
version = "1.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"
|
||||
dependencies = [
|
||||
"borsh-derive",
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "borsh-derive"
|
||||
version = "1.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"proc-macro-crate 3.5.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli"
|
||||
version = "9.0.0"
|
||||
@@ -1187,6 +1230,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "clash-verge-limiter"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"loom",
|
||||
"proptest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-logging"
|
||||
@@ -1558,6 +1605,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core_detect"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
|
||||
|
||||
[[package]]
|
||||
name = "core_maths"
|
||||
version = "0.1.1"
|
||||
@@ -2127,7 +2180,7 @@ version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"bit-set 0.8.0",
|
||||
"cssparser",
|
||||
"foldhash 0.2.0",
|
||||
"html5ever",
|
||||
@@ -2719,6 +2772,18 @@ dependencies = [
|
||||
"x11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generator"
|
||||
version = "0.8.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "66831419d9074e766421508dff218bf79d99616bc5e56e34599d3b433714a4a4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"windows-core 0.100.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
@@ -4124,6 +4189,19 @@ version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "loom"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1611ddbf89dc6ae42cfbd51fc207836140130257646eab8d6d2fb16577db2d2"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"generator",
|
||||
"scoped-tls",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lru-slab"
|
||||
version = "0.1.2"
|
||||
@@ -5528,6 +5606,26 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proptest"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
|
||||
dependencies = [
|
||||
"bit-set 0.11.1",
|
||||
"bit-vec 0.10.2",
|
||||
"bitflags 2.13.2",
|
||||
"chacha20",
|
||||
"core_detect",
|
||||
"num-traits",
|
||||
"rand 0.10.2",
|
||||
"rand_xorshift",
|
||||
"regex-syntax",
|
||||
"rusty-fork",
|
||||
"tempfile",
|
||||
"unarray",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prost"
|
||||
version = "0.14.4"
|
||||
@@ -5582,6 +5680,12 @@ version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "2.0.1"
|
||||
@@ -5769,6 +5873,15 @@ dependencies = [
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_xorshift"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
|
||||
dependencies = [
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raw-window-handle"
|
||||
version = "0.6.2"
|
||||
@@ -6300,6 +6413,18 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "rusty-fork"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"quick-error 1.2.3",
|
||||
"tempfile",
|
||||
"wait-timeout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
@@ -8097,7 +8222,7 @@ dependencies = [
|
||||
"fax",
|
||||
"flate2",
|
||||
"half",
|
||||
"quick-error",
|
||||
"quick-error 2.0.1",
|
||||
"weezl",
|
||||
"zune-jpeg",
|
||||
]
|
||||
@@ -8728,6 +8853,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unarray"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.9.0"
|
||||
@@ -8882,6 +9013,15 @@ dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wait-timeout"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
@@ -9341,8 +9481,8 @@ version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-implement 0.60.2",
|
||||
"windows-interface 0.59.3",
|
||||
"windows-link 0.1.3",
|
||||
"windows-result 0.3.4",
|
||||
"windows-strings 0.4.2",
|
||||
@@ -9354,13 +9494,26 @@ version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-implement 0.60.2",
|
||||
"windows-interface 0.59.3",
|
||||
"windows-link 0.2.1",
|
||||
"windows-result 0.4.1",
|
||||
"windows-strings 0.5.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.100.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "803590c6856f51d15fa2e9fabe4f4703122c8737f72ef2741b4ac09d4c2192f5"
|
||||
dependencies = [
|
||||
"windows-implement 0.100.0",
|
||||
"windows-interface 0.100.0",
|
||||
"windows-link 0.100.0",
|
||||
"windows-result 0.100.0",
|
||||
"windows-strings 0.100.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-future"
|
||||
version = "0.2.1"
|
||||
@@ -9394,6 +9547,17 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.100.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1bc1bc82e5a1b1a4d7255861b07881a0407b552f50a4d8543c0c7276fa96f6e8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
@@ -9405,6 +9569,17 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.100.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3f7005c3b757b9b82c2f40c0e71094ff1080adddaf3e8b6ce99b545d3c48796"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.1.3"
|
||||
@@ -9417,6 +9592,12 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.100.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b39de7c7fe78858b0144c50c3fc000bab3be17d5e9b85b1053871693c7f7415"
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.2.0"
|
||||
@@ -9466,6 +9647,15 @@ dependencies = [
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.100.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44873a1ef61c85d5e2991db91fe656cfcf0731097e00dff1ac860f1cb3b752a0"
|
||||
dependencies = [
|
||||
"windows-link 0.100.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-service"
|
||||
version = "0.8.1"
|
||||
@@ -9495,6 +9685,15 @@ dependencies = [
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.100.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a70b590c684f1d2854f74999896f7c0558f1bdde62f599088599e20ea1d2f60"
|
||||
dependencies = [
|
||||
"windows-link 0.100.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.45.0"
|
||||
|
||||
@@ -68,6 +68,8 @@ tauri-plugin-clipboard-manager = "2.5.0"
|
||||
parking_lot = "0.13.0"
|
||||
anyhow = "1.0.105"
|
||||
futures = "0.3.34"
|
||||
loom = "0.7"
|
||||
proptest = "1.12.0"
|
||||
chrono = "0.4.45"
|
||||
criterion = { version = "0.8.2", features = ["async_tokio"] }
|
||||
tokio = { version = "1.54.1", features = [
|
||||
@@ -108,6 +110,9 @@ windows-sys = { version = "0.61.2", features = [
|
||||
] }
|
||||
# *********************************
|
||||
|
||||
[workspace.lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(loom)'] }
|
||||
|
||||
[workspace.lints.clippy]
|
||||
# fallible_impl_from = "deny" // 过于激进,暂时不开启
|
||||
# implicit_clone = "deny" // 可能会造成额外开销,暂时不开启
|
||||
|
||||
@@ -5,5 +5,11 @@ edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
|
||||
[target.'cfg(loom)'.dependencies]
|
||||
loom = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
#[cfg(loom)]
|
||||
use loom::sync::Arc;
|
||||
#[cfg(loom)]
|
||||
use loom::sync::atomic::AtomicU64;
|
||||
#[cfg(not(loom))]
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
#[cfg(not(loom))]
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub type SystemLimiter = Limiter<SystemClock>;
|
||||
@@ -38,6 +45,7 @@ pub struct Limiter<C: Clock = SystemClock> {
|
||||
}
|
||||
|
||||
impl<C: Clock> Limiter<C> {
|
||||
#[cfg(not(loom))]
|
||||
pub const fn new(period: Duration, clock: C) -> Self {
|
||||
Self {
|
||||
last_run_ms: AtomicU64::new(0),
|
||||
@@ -46,11 +54,21 @@ impl<C: Clock> Limiter<C> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check(&self) -> bool {
|
||||
let now = self.clock.now_ms();
|
||||
let last = self.last_run_ms.load(Ordering::Relaxed);
|
||||
#[cfg(loom)]
|
||||
pub fn new(period: Duration, clock: C) -> Self {
|
||||
Self {
|
||||
last_run_ms: AtomicU64::new(0),
|
||||
period_ms: period.as_millis() as u64,
|
||||
clock,
|
||||
}
|
||||
}
|
||||
|
||||
if now < last + self.period_ms && now >= last {
|
||||
pub fn check(&self) -> bool {
|
||||
// Load before sampling so a stale sample cannot move a newer admission backward.
|
||||
let last = self.last_run_ms.load(Ordering::Relaxed);
|
||||
let now = self.clock.now_ms();
|
||||
|
||||
if now >= last && now - last < self.period_ms {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -74,6 +92,22 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_clock_reports_unix_epoch_milliseconds() {
|
||||
const MAX_DRIFT_MS: u64 = 5 * 60 * 1_000;
|
||||
|
||||
let wall_clock_ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as u64;
|
||||
let clock_ms = SystemClock.now_ms();
|
||||
|
||||
assert!(
|
||||
clock_ms.abs_diff(wall_clock_ms) <= MAX_DRIFT_MS,
|
||||
"SystemClock::now_ms() should return Unix epoch milliseconds, got {clock_ms} while wall clock is {wall_clock_ms}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enforces_the_period_boundary() {
|
||||
let clock = MockClock(AtomicU64::new(1_000));
|
||||
@@ -100,7 +134,10 @@ mod tests {
|
||||
}
|
||||
let admitted = handles
|
||||
.into_iter()
|
||||
.map(|handle| handle.join().unwrap_or(false))
|
||||
.map(|handle| match handle.join() {
|
||||
Ok(admitted) => admitted,
|
||||
Err(panic) => std::panic::resume_unwind(panic),
|
||||
})
|
||||
.filter(|passed| *passed)
|
||||
.count();
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
#![cfg(loom)]
|
||||
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use clash_verge_limiter::{Clock, Limiter};
|
||||
use loom::sync::Arc;
|
||||
use loom::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize};
|
||||
|
||||
const PERIOD_MS: u64 = 100;
|
||||
const START_MS: u64 = 1_000;
|
||||
|
||||
struct MockClock(AtomicU64);
|
||||
|
||||
impl Clock for MockClock {
|
||||
fn now_ms(&self) -> u64 {
|
||||
self.0.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
type TestLimiter = Limiter<Arc<MockClock>>;
|
||||
|
||||
struct AdvancingClock(AtomicU64);
|
||||
|
||||
impl Clock for AdvancingClock {
|
||||
fn now_ms(&self) -> u64 {
|
||||
self.0.fetch_add(1, Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
fn limiter_at(now_ms: u64) -> (Arc<MockClock>, Arc<TestLimiter>) {
|
||||
let clock = Arc::new(MockClock(AtomicU64::new(now_ms)));
|
||||
let limiter = Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock));
|
||||
(clock, Arc::new(limiter))
|
||||
}
|
||||
|
||||
fn run_two_concurrent_checks<C: Clock + 'static>(limiter: &Arc<Limiter<C>>) -> usize {
|
||||
let handles: [_; 2] = std::array::from_fn(|_| {
|
||||
let limiter = Arc::clone(limiter);
|
||||
loom::thread::spawn(move || limiter.check())
|
||||
});
|
||||
|
||||
handles
|
||||
.into_iter()
|
||||
.map(|handle| match handle.join() {
|
||||
Ok(admitted) => admitted,
|
||||
Err(panic) => std::panic::resume_unwind(panic),
|
||||
})
|
||||
.filter(|admitted| *admitted)
|
||||
.count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admits_exactly_one_caller_in_an_eligible_window() {
|
||||
loom::model(|| {
|
||||
let (_clock, limiter) = limiter_at(START_MS);
|
||||
|
||||
assert_eq!(run_two_concurrent_checks(&limiter), 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_concurrent_callers_inside_the_restricted_period() {
|
||||
loom::model(|| {
|
||||
let (clock, limiter) = limiter_at(START_MS);
|
||||
assert!(limiter.check());
|
||||
|
||||
clock.0.store(START_MS + PERIOD_MS - 1, Ordering::SeqCst);
|
||||
|
||||
assert_eq!(run_two_concurrent_checks(&limiter), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admits_exactly_one_caller_at_the_period_boundary() {
|
||||
loom::model(|| {
|
||||
let (clock, limiter) = limiter_at(START_MS);
|
||||
assert!(limiter.check());
|
||||
|
||||
clock.0.store(START_MS + PERIOD_MS, Ordering::SeqCst);
|
||||
|
||||
assert_eq!(run_two_concurrent_checks(&limiter), 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_clock_advancement_admits_exactly_one_caller() {
|
||||
loom::model(|| {
|
||||
let clock = Arc::new(AdvancingClock(AtomicU64::new(START_MS)));
|
||||
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
|
||||
|
||||
assert_eq!(run_two_concurrent_checks(&limiter), 1);
|
||||
});
|
||||
}
|
||||
|
||||
struct StaleClock {
|
||||
current: AtomicU64,
|
||||
reads: AtomicUsize,
|
||||
stale_reads: usize,
|
||||
sampled: AtomicUsize,
|
||||
released: AtomicBool,
|
||||
}
|
||||
|
||||
impl StaleClock {
|
||||
fn new(now_ms: u64, stale_reads: usize) -> Self {
|
||||
Self {
|
||||
current: AtomicU64::new(now_ms),
|
||||
reads: AtomicUsize::new(0),
|
||||
stale_reads,
|
||||
sampled: AtomicUsize::new(0),
|
||||
released: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
self.released.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for StaleClock {
|
||||
fn now_ms(&self) -> u64 {
|
||||
if self.reads.fetch_add(1, Ordering::SeqCst) < self.stale_reads {
|
||||
let stale = self.current.load(Ordering::SeqCst);
|
||||
self.sampled.fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
// Parking can wake spuriously; re-check the release flag on each
|
||||
// wake. Unparking after setting the flag avoids a lost wakeup.
|
||||
while !self.released.load(Ordering::SeqCst) {
|
||||
loom::thread::park();
|
||||
}
|
||||
|
||||
stale
|
||||
} else {
|
||||
self.current.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Regression: a caller that sampled the clock before a newer admission must
|
||||
/// not overwrite that admission when it resumes.
|
||||
#[test]
|
||||
fn stale_clock_sample_does_not_reopen_the_period() {
|
||||
loom::model(|| {
|
||||
const LATER_MS: u64 = START_MS + PERIOD_MS * 10;
|
||||
|
||||
let clock = Arc::new(StaleClock::new(START_MS, 1));
|
||||
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
|
||||
|
||||
let stale_caller = {
|
||||
let limiter = Arc::clone(&limiter);
|
||||
loom::thread::spawn(move || limiter.check())
|
||||
};
|
||||
|
||||
while clock.sampled.load(Ordering::SeqCst) < 1 {
|
||||
loom::thread::yield_now();
|
||||
}
|
||||
clock.current.store(LATER_MS, Ordering::SeqCst);
|
||||
|
||||
let later_caller = {
|
||||
let limiter = Arc::clone(&limiter);
|
||||
loom::thread::spawn(move || limiter.check())
|
||||
};
|
||||
|
||||
let later_admitted = later_caller.join().unwrap();
|
||||
assert!(
|
||||
later_admitted,
|
||||
"the later caller must be admitted before the stale caller resumes"
|
||||
);
|
||||
|
||||
clock.release();
|
||||
stale_caller.thread().unpark();
|
||||
|
||||
let stale_admitted = stale_caller.join().unwrap();
|
||||
let reopened = limiter.check();
|
||||
|
||||
assert!(
|
||||
!stale_admitted,
|
||||
"stale caller must not be admitted after the later caller"
|
||||
);
|
||||
assert!(
|
||||
!reopened,
|
||||
"stale caller admitted={stale_admitted} moved last_run_ms from {LATER_MS} back to {START_MS}"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_stale_clock_samples_cannot_reopen_the_period() {
|
||||
loom::model(|| {
|
||||
const LATER_MS: u64 = START_MS + PERIOD_MS * 10;
|
||||
|
||||
let clock = Arc::new(StaleClock::new(START_MS, 2));
|
||||
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
|
||||
|
||||
let stale_callers: [_; 2] = std::array::from_fn(|_| {
|
||||
let limiter = Arc::clone(&limiter);
|
||||
loom::thread::spawn(move || limiter.check())
|
||||
});
|
||||
|
||||
while clock.sampled.load(Ordering::SeqCst) < 2 {
|
||||
loom::thread::yield_now();
|
||||
}
|
||||
clock.current.store(LATER_MS, Ordering::SeqCst);
|
||||
assert!(
|
||||
limiter.check(),
|
||||
"the later caller must be admitted before the stale callers resume"
|
||||
);
|
||||
|
||||
clock.release();
|
||||
for caller in &stale_callers {
|
||||
caller.thread().unpark();
|
||||
}
|
||||
|
||||
let stale_admitted = stale_callers
|
||||
.into_iter()
|
||||
.map(|caller| caller.join().unwrap())
|
||||
.filter(|admitted| *admitted)
|
||||
.count();
|
||||
assert_eq!(
|
||||
stale_admitted, 0,
|
||||
"stale callers must not be admitted after the later caller"
|
||||
);
|
||||
assert!(!limiter.check(), "stale callers reopened the period at {LATER_MS}");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Seeds for failure cases proptest has generated in the past. It is
|
||||
# automatically read and these particular cases re-run before any
|
||||
# novel cases are generated.
|
||||
#
|
||||
# It is recommended to check this file in to source control so that
|
||||
# everyone who runs the test benefits from these saved cases.
|
||||
cc 0139d921e3faaf32821ee0c596b0d495ffc72ce94200b8d5a795883db56305e6 # shrinks to period = 56, start = 18446744073709551560
|
||||
@@ -0,0 +1,211 @@
|
||||
#![cfg(not(loom))]
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use clash_verge_limiter::{Clock, Limiter};
|
||||
use proptest::prelude::*;
|
||||
use proptest::test_runner::FileFailurePersistence;
|
||||
|
||||
const CASES: u32 = 10_000;
|
||||
const MAX_PERIOD_MS: u64 = 100_000;
|
||||
const MAX_START_MS: u64 = 1_000_000;
|
||||
const MAX_DELTA_MS: u64 = 10_000;
|
||||
|
||||
/// Returns one clock value per call, in order. The test supplies exactly as
|
||||
/// many values as the limiter will read.
|
||||
struct SequenceClock {
|
||||
values: Vec<u64>,
|
||||
next: AtomicUsize,
|
||||
}
|
||||
|
||||
impl SequenceClock {
|
||||
const fn new(values: Vec<u64>) -> Self {
|
||||
Self {
|
||||
values,
|
||||
next: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for SequenceClock {
|
||||
fn now_ms(&self) -> u64 {
|
||||
let index = self.next.fetch_add(1, Ordering::SeqCst);
|
||||
self.values[index]
|
||||
}
|
||||
}
|
||||
|
||||
fn timestamps(start: u64, deltas: &[u64]) -> Vec<u64> {
|
||||
let mut now = start;
|
||||
let mut values = Vec::with_capacity(deltas.len() + 1);
|
||||
values.push(now);
|
||||
for delta in deltas {
|
||||
now += delta;
|
||||
values.push(now);
|
||||
}
|
||||
values
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig {
|
||||
cases: CASES,
|
||||
failure_persistence: Some(Box::new(FileFailurePersistence::Direct(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/tests/properties.proptest-regressions"
|
||||
)))),
|
||||
..ProptestConfig::default()
|
||||
})]
|
||||
|
||||
/// For positive periods and nondecreasing time, admission is equivalent to
|
||||
/// reaching the next allowed timestamp after the previous admission.
|
||||
#[test]
|
||||
fn sequential_results_match_the_next_allowed_time_contract(
|
||||
period in 1u64..=MAX_PERIOD_MS,
|
||||
start in MAX_PERIOD_MS..=MAX_START_MS,
|
||||
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
|
||||
) {
|
||||
let times = timestamps(start, &deltas);
|
||||
let clock = SequenceClock::new(times.clone());
|
||||
let limiter = Limiter::new(Duration::from_millis(period), &clock);
|
||||
let mut last_admitted = None;
|
||||
|
||||
for now in times {
|
||||
let expected = match last_admitted {
|
||||
None => true,
|
||||
Some(last) => now >= last + period,
|
||||
};
|
||||
let actual = limiter.check();
|
||||
prop_assert!(
|
||||
actual == expected,
|
||||
"period={} now={} last={:?}",
|
||||
period,
|
||||
now,
|
||||
last_admitted
|
||||
);
|
||||
if actual {
|
||||
last_admitted = Some(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An admission at the period boundary is accepted, while a repeated or
|
||||
/// pre-boundary check is rejected.
|
||||
#[test]
|
||||
fn period_boundary_and_repeated_checks_follow_the_period(
|
||||
period in 1u64..=MAX_PERIOD_MS,
|
||||
start in MAX_PERIOD_MS..=MAX_START_MS,
|
||||
) {
|
||||
let boundary = start + period;
|
||||
let clock = SequenceClock::new(vec![start, start, boundary - 1, boundary]);
|
||||
let limiter = Limiter::new(Duration::from_millis(period), &clock);
|
||||
|
||||
prop_assert!(limiter.check(), "first check at {}", start);
|
||||
prop_assert!(!limiter.check(), "repeated check at {}", start);
|
||||
prop_assert!(!limiter.check(), "pre-boundary check at {}", boundary - 1);
|
||||
prop_assert!(limiter.check(), "boundary check at {}", boundary);
|
||||
}
|
||||
|
||||
/// Any two admitted timestamps in a monotonic sequence are separated by at
|
||||
/// least one configured period.
|
||||
#[test]
|
||||
fn admitted_timestamps_are_at_least_one_period_apart(
|
||||
period in 1u64..=MAX_PERIOD_MS,
|
||||
start in MAX_PERIOD_MS..=MAX_START_MS,
|
||||
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
|
||||
) {
|
||||
let times = timestamps(start, &deltas);
|
||||
let clock = SequenceClock::new(times.clone());
|
||||
let limiter = Limiter::new(Duration::from_millis(period), &clock);
|
||||
let mut admitted = Vec::new();
|
||||
|
||||
for now in times {
|
||||
if limiter.check() {
|
||||
admitted.push(now);
|
||||
}
|
||||
}
|
||||
|
||||
for pair in admitted.windows(2) {
|
||||
prop_assert!(
|
||||
pair[1] - pair[0] >= period,
|
||||
"period={} admitted pair={:?}",
|
||||
period,
|
||||
pair
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A rejected duplicate at the current admission timestamp must not change
|
||||
/// the outcomes of later checks.
|
||||
#[test]
|
||||
fn rejected_checks_do_not_change_future_admissions(
|
||||
period in 1u64..=MAX_PERIOD_MS,
|
||||
start in MAX_PERIOD_MS..=MAX_START_MS,
|
||||
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
|
||||
) {
|
||||
let base_times = timestamps(start, &deltas);
|
||||
let base_clock = SequenceClock::new(base_times.clone());
|
||||
let base = Limiter::new(Duration::from_millis(period), &base_clock);
|
||||
let base_results: Vec<bool> = base_times.iter().map(|_| base.check()).collect();
|
||||
|
||||
let mut repeated_times = vec![start, start];
|
||||
repeated_times.extend_from_slice(&base_times[1..]);
|
||||
let repeated_len = repeated_times.len();
|
||||
let repeated_clock = SequenceClock::new(repeated_times);
|
||||
let repeated = Limiter::new(Duration::from_millis(period), &repeated_clock);
|
||||
let repeated_results: Vec<bool> = (0..repeated_len).map(|_| repeated.check()).collect();
|
||||
|
||||
prop_assert!(repeated_results[0]);
|
||||
prop_assert!(!repeated_results[1]);
|
||||
prop_assert_eq!(&base_results[1..], &repeated_results[2..]);
|
||||
}
|
||||
|
||||
/// Every sub-millisecond period is represented as zero milliseconds, so it
|
||||
/// must produce the same admissions as `Duration::ZERO`. This deliberately
|
||||
/// does not assert a policy for zero periods.
|
||||
#[test]
|
||||
fn zero_and_submillisecond_periods_are_equivalent(
|
||||
nanos in 0u64..1_000_000,
|
||||
start in 0u64..=MAX_START_MS,
|
||||
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
|
||||
) {
|
||||
let times = timestamps(start, &deltas);
|
||||
let zero_clock = SequenceClock::new(times.clone());
|
||||
let zero = Limiter::new(Duration::ZERO, &zero_clock);
|
||||
let submillisecond_clock = SequenceClock::new(times.clone());
|
||||
let submillisecond =
|
||||
Limiter::new(Duration::from_nanos(nanos), &submillisecond_clock);
|
||||
|
||||
for now in times {
|
||||
prop_assert_eq!(
|
||||
zero.check(),
|
||||
submillisecond.check(),
|
||||
"nanos={} now={}",
|
||||
nanos,
|
||||
now
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Regression: timestamp arithmetic must not overflow near `u64::MAX`.
|
||||
#[test]
|
||||
fn extreme_timestamp_and_period_do_not_overflow(
|
||||
period in 1u64..=1_000,
|
||||
start in (u64::MAX - 1_000)..=u64::MAX,
|
||||
) {
|
||||
let clock = SequenceClock::new(vec![start, start]);
|
||||
let limiter = Limiter::new(Duration::from_millis(period), &clock);
|
||||
|
||||
prop_assert!(limiter.check());
|
||||
prop_assert!(!limiter.check());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_timestamp_boundary_does_not_overflow() {
|
||||
let clock = SequenceClock::new(vec![u64::MAX - 1, u64::MAX, u64::MAX]);
|
||||
let limiter = Limiter::new(Duration::from_millis(1), &clock);
|
||||
|
||||
assert!(limiter.check());
|
||||
assert!(limiter.check());
|
||||
assert!(!limiter.check());
|
||||
}
|
||||
Reference in New Issue
Block a user