Stop a wall-window roll billing the same request twice
Browse files at this commit095c34aa9df9bf242fdc833b9daaf9230bd1b8baParent: abe75ba- fix
- stop a wall-window roll billing the same request twice
1 changed file +104 -22
- src/rate_limit.rs +104 -22
src/rate_limit.rsmodified+104 -22
| @@ -146,18 +146,21 @@ struct Bucket { | |||
| 146 | window_start: Instant, | 146 | window_start: Instant, |
| 147 | /// Requests this process admitted in the current local window. | 147 | /// Requests this process admitted in the current local window. |
| 148 | count: u32, | 148 | count: u32, |
| 149 | - /// How many of `count` the sync task has already folded into the shared | 149 | + /// How many of `count` are accounted for against the *current* shared row |
| 150 | - /// row. Never above `count`, so `count - pushed` is what is still ours to | 150 | + /// — folded into it, or charged to an earlier one before the wall window |
| 151 | - /// report. | 151 | + /// rolled. Never above `count`, so `count - pushed` is what is still ours |
| 152 | + /// to report. | ||
| 152 | pushed: u32, | 153 | pushed: u32, |
| 153 | - /// The stored total the last sync read back — every admit in this window, | 154 | + /// The stored total the last sync read back — every admit in this wall |
| 154 | - /// `pushed` included. Zero until a sync lands, which is what makes an | 155 | + /// window, our `pushed` share included. Zero until a sync lands, which is |
| 155 | - /// unshared limiter behave exactly like the local-only one it replaced. | 156 | + /// what makes an unshared limiter behave exactly like the local-only one it |
| 157 | + /// replaced. | ||
| 156 | remote: u32, | 158 | remote: u32, |
| 157 | - /// The wall window (`RATE_LIMIT_TABLE` row) `pushed`/`remote` describe. | 159 | + /// The wall window (`RATE_LIMIT_TABLE` row) `pushed`/`remote` describe, or |
| 158 | - /// The local window rolls per client while the shared one is aligned to the | 160 | + /// `None` until the first sync. The local window rolls per client while the |
| 159 | - /// clock, so this says which shared row those two numbers came from. | 161 | + /// shared one is aligned to the clock, so this says which shared row those |
| 160 | - epoch: i64, | 162 | + /// two numbers came from. |
| 163 | + epoch: Option<i64>, | ||
| 161 | } | 164 | } |
| 162 | 165 | ||
| 163 | impl Bucket { | 166 | impl Bucket { |
| @@ -168,15 +171,22 @@ impl Bucket { | |||
| 168 | count: 0, | 171 | count: 0, |
| 169 | pushed: 0, | 172 | pushed: 0, |
| 170 | remote: 0, | 173 | remote: 0, |
| 171 | - epoch: 0, | 174 | + epoch: None, |
| 172 | } | 175 | } |
| 173 | } | 176 | } |
| 174 | 177 | ||
| 175 | - /// Requests spent in this window as far as this process can tell: what the | 178 | + /// Requests spent as far as this process can tell: what the shared row held |
| 176 | - /// shared row held at the last sync — this process's earlier life included — | 179 | + /// at the last sync — this process's earlier life included — plus our own |
| 177 | - /// plus our own admits since. Equals `count` until a sync lands. | 180 | + /// admits since, and never less than this local window's own count. Equals |
| 181 | + /// `count` until a sync lands. | ||
| 182 | + /// | ||
| 183 | + /// The local floor is what a wall-window roll needs: the admits it moves | ||
| 184 | + /// out of the shared reckoning (they belong to the row that has passed) | ||
| 185 | + /// must not come back as fresh budget inside a local window that is still | ||
| 186 | + /// running. | ||
| 178 | fn spent(&self) -> u32 { | 187 | fn spent(&self) -> u32 { |
| 179 | - self.remote.saturating_add(self.count - self.pushed) | 188 | + self.count |
| 189 | + .max(self.remote.saturating_add(self.count - self.pushed)) | ||
| 180 | } | 190 | } |
| 181 | } | 191 | } |
| 182 | 192 | ||
| @@ -453,12 +463,24 @@ async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>( | |||
| 453 | .filter(|(_, b)| b.count > 0 && now.duration_since(b.window_start) < window) | 463 | .filter(|(_, b)| b.count > 0 && now.duration_since(b.window_start) < window) |
| 454 | .take(RATE_SYNC_MAX_KEYS) | 464 | .take(RATE_SYNC_MAX_KEYS) |
| 455 | .map(|(key, b)| { | 465 | .map(|(key, b)| { |
| 456 | - if b.epoch != epoch { | 466 | + if b.epoch != Some(epoch) { |
| 457 | - // The shared window rolled: the row this bucket is about to | 467 | + // A different shared row from the one `pushed`/`remote` |
| 458 | - // write knows nothing of us, so the whole local count is | 468 | + // describe: that total is about a window that has passed. |
| 459 | - // the delta and the previous total describes a dead row. | 469 | + // What was already charged to it must not be charged again |
| 460 | - b.epoch = epoch; | 470 | + // here — every local window straddles a boundary, so |
| 461 | - b.pushed = 0; | 471 | + // re-reporting the whole count would bill each of those |
| 472 | + // requests to two rows and spend the client's next budget | ||
| 473 | + // before it began. Only a bucket that has never synced owes | ||
| 474 | + // its whole count, having been billed nowhere yet. | ||
| 475 | + // | ||
| 476 | + // ponytail: admits between the boundary and this round land | ||
| 477 | + // on the old row. Ceiling: RATE_SYNC_INTERVAL_SECS of one | ||
| 478 | + // client's traffic, charged once either way. Upgrade path: | ||
| 479 | + // stamp each admit with its epoch. | ||
| 480 | + if b.epoch.is_some() { | ||
| 481 | + b.pushed = b.count; | ||
| 482 | + } | ||
| 483 | + b.epoch = Some(epoch); | ||
| 462 | b.remote = 0; | 484 | b.remote = 0; |
| 463 | } | 485 | } |
| 464 | Pending { | 486 | Pending { |
| @@ -506,7 +528,7 @@ async fn sync_once<K: Eq + Hash + Clone + std::fmt::Display>( | |||
| 506 | }; | 528 | }; |
| 507 | // The window may have rolled while the query was in flight, in which | 529 | // The window may have rolled while the query was in flight, in which |
| 508 | // case this total is about a bucket that no longer exists. | 530 | // case this total is about a bucket that no longer exists. |
| 509 | - if bucket.epoch != epoch || bucket.window_start != p.window_start { | 531 | + if bucket.epoch != Some(epoch) || bucket.window_start != p.window_start { |
| 510 | continue; | 532 | continue; |
| 511 | } | 533 | } |
| 512 | bucket.pushed = p.counted; | 534 | bucket.pushed = p.counted; |
| @@ -824,6 +846,66 @@ mod tests { | |||
| 824 | ); | 846 | ); |
| 825 | } | 847 | } |
| 826 | 848 | ||
| 849 | + /// The wall window rolls under a live local one — every local window | ||
| 850 | + /// straddles exactly one boundary, since both are 60s and only the shared | ||
| 851 | + /// one is clock-aligned. Each request must land in exactly one shared row: | ||
| 852 | + /// re-reporting the whole local count to the new row charges the client | ||
| 853 | + /// twice and spends the next window's budget before it starts. | ||
| 854 | + /// | ||
| 855 | + /// `sync_once` takes the epoch, so the boundary is driven here instead of | ||
| 856 | + /// waited for — the sharing tests in `tests/rate_limit.rs` all run inside | ||
| 857 | + /// one real wall window (`current_epoch` reads the wall clock, which | ||
| 858 | + /// `tokio::time::pause` does not touch), which is why this path had no | ||
| 859 | + /// coverage at all. | ||
| 860 | + #[tokio::test] | ||
| 861 | + async fn a_wall_epoch_roll_charges_no_request_twice() { | ||
| 862 | + const MAX: u32 = 5; | ||
| 863 | + let db = crate::database::init_mem().await.expect("in-memory db"); | ||
| 864 | + let limiter = UserRateLimiter::per_user_minute(MAX); | ||
| 865 | + let window = Duration::from_secs(60); | ||
| 866 | + let epoch = current_epoch(window); | ||
| 867 | + assert_eq!(window.as_millis() as i64, 60_000, "epochs are 60s apart"); | ||
| 868 | + | ||
| 869 | + // A burst early in the client's local window, folded into row `epoch`. | ||
| 870 | + for _ in 0..MAX { | ||
| 871 | + assert!(limiter.enforce_user("user:a").is_ok()); | ||
| 872 | + } | ||
| 873 | + sync_once("test", &limiter.buckets, window, epoch, &db).await; | ||
| 874 | + | ||
| 875 | + // The wall clock rolls while that local window is still running. | ||
| 876 | + sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await; | ||
| 877 | + | ||
| 878 | + // The local window lapses, so the client opens a fresh one — inside the | ||
| 879 | + // *same* new wall window — and spends one request in it. | ||
| 880 | + tokio::time::pause(); | ||
| 881 | + tokio::time::advance(Duration::from_secs(61)).await; | ||
| 882 | + tokio::time::resume(); | ||
| 883 | + assert_eq!(admits(&limiter, "user:a", 1), 1, "a fresh local window"); | ||
| 884 | + sync_once("test", &limiter.buckets, window, epoch + 60_000, &db).await; | ||
| 885 | + | ||
| 886 | + let mut rows = db | ||
| 887 | + .query("SELECT VALUE hits FROM rate_limit ORDER BY window_start") | ||
| 888 | + .await | ||
| 889 | + .expect("read shared counters"); | ||
| 890 | + assert_eq!( | ||
| 891 | + rows.take::<Vec<i64>>(0).unwrap(), | ||
| 892 | + vec![i64::from(MAX), 1], | ||
| 893 | + "the new wall row may hold only what was admitted inside it" | ||
| 894 | + ); | ||
| 895 | + assert_eq!( | ||
| 896 | + admits(&limiter, "user:a", 4), | ||
| 897 | + 4, | ||
| 898 | + "the client spent 1 of {MAX} in this window and must keep the rest" | ||
| 899 | + ); | ||
| 900 | + } | ||
| 901 | + | ||
| 902 | + /// How many of `tries` requests the limiter admits for `user`. | ||
| 903 | + fn admits(limiter: &UserRateLimiter, user: &str, tries: usize) -> usize { | ||
| 904 | + (0..tries) | ||
| 905 | + .filter(|_| limiter.enforce_user(user).is_ok()) | ||
| 906 | + .count() | ||
| 907 | + } | ||
| 908 | + | ||
| 827 | /// The flood above was cheap to tell apart. This one is not: every flood | 909 | /// The flood above was cheap to tell apart. This one is not: every flood |
| 828 | /// key is driven to *exactly* the spend of the bucket it is trying to | 910 | /// key is driven to *exactly* the spend of the bucket it is trying to |
| 829 | /// free, so a cheapest-first cutoff of `<=` puts the victim inside the tie | 911 | /// free, so a cheapest-first cutoff of `<=` puts the victim inside the tie |