diff --git a/stresstest/README.md b/stresstest/README.md index 13552fb3..5a8f9c34 100644 --- a/stresstest/README.md +++ b/stresstest/README.md @@ -11,7 +11,8 @@ cargo run -p stresstest -- -c config/example.yaml ## Configuration The stresstest is configured via a YAML file. See `config/example.yaml` for a -full example. +full example, and `config/production.example.yaml` for workloads that replay +the object sizes of the production usecases. ### Top-level options @@ -38,7 +39,14 @@ Each entry in `workloads` configures an independent, concurrent workload: ### File sizes -Controls the LogNormal distribution used to generate object sizes: +Controls the sizes of the objects that a workload writes. A workload sets either +percentiles or size buckets, not both. + +#### Percentiles + +Sizes are drawn from a LogNormal distribution fitted to `p50` and `p99`. Sizes +above `p99` are a guess, so the average object size can be several times off +compared to a real usecase. | Field | Required | Description | |-------|----------|------------------------------------------| @@ -47,6 +55,102 @@ Controls the LogNormal distribution used to generate object sizes: | `min` | no | Minimum file size, below p50. The distribution is fitted above this floor. | | `max` | no | Hard cap on generated file sizes | +#### Size buckets + +Sizes are drawn from a histogram, which replays the object sizes that a usecase +has in production. See `config/production.example.yaml`. + +| Field | Required | Description | +|-----------|----------|------------------------------------------| +| `buckets` | yes | Sizes, each with the number of objects at or below that size | + +```yaml +file_sizes: + buckets: + 1 KiB: 2500 # 2500 objects are at most 1 KiB + 2 KiB: 6000 # 3500 more are between 1 and 2 KiB + 4 KiB: 9900 + 8 KiB: 10000 # no object is larger +``` + +- Counts are cumulative, and only their ratio to the last count matters. +- Make each size twice the previous one. A size is picked log-uniformly within + its bucket, so wider buckets are less accurate. +- The first bucket starts at half its size. + +With buckets from one week of production, the average generated size was within +about 10% of the real average for every usecase. + +#### Getting size buckets from Datadog + +The `objectstore.put.size` metric has the size of every stored object, tagged by +`usecase`. This query, summed over a time range, returns the count for the +`64 KiB` (65536 bytes) line of each usecase: + +``` +count(v: v<=65536):objectstore.put.size{sentry_region:us,environment:production} by {usecase}.as_count() +``` + +Run it for every power of two from 64 B to 8 GiB. An agent with the +[Datadog MCP server](https://docs.datadoghq.com/bits_ai/mcp_server/) can do this +without an API key: its `execute_code` tool runs the script below, which returns +`workloads` entries scaled to one million objects. Round the counts before you +commit them to this repository, so that production data stays private. + +```javascript +import { client, v2 } from "@datadog/datadog-api-client"; + +const scope = "{sentry_region:us,environment:production}"; +const days = 7; +const sizes = Array.from({ length: 28 }, (_, i) => 2 ** (i + 6)); // 64 B to 8 GiB + +const api = new v2.MetricsApi(client.createConfiguration()); +const to = Date.parse(dd.time.hoursAgo(1)); +const from = to - days * 24 * 3600 * 1000; +const metric = `objectstore.put.size${scope} by {usecase}.as_count()`; + +// Count all objects, and the objects at or below each size. +const counts = {}; +for (let i = 0; i < sizes.length; i += 7) { + const queries = [ + { name: "total", query: `count:${metric}` }, + ...sizes.slice(i, i + 7).map((size) => ({ name: `${size}`, query: `count(v: v<=${size}):${metric}` })), + ].map((query) => ({ ...query, dataSource: "metrics", aggregator: "sum" })); + const response = await api.queryScalarData({ + body: { data: { type: "scalar_request", attributes: { from, to, queries } } }, + }); + const columns = response.data.attributes.columns; + const usecases = columns.find((column) => column.type === "group")?.values; + if (!usecases) throw new Error(`no data for ${scope} in the last ${days} days`); + for (const column of columns.filter((column) => column.type !== "group")) { + usecases.forEach(([usecase], row) => { + (counts[usecase] ??= {})[column.name] = column.values[row] ?? 0; + }); + } +} + +const unit = (size) => + size >= 2 ** 30 ? `${size / 2 ** 30} GiB` + : size >= 2 ** 20 ? `${size / 2 ** 20} MiB` + : size >= 2 ** 10 ? `${size / 2 ** 10} KiB` + : `${size} B`; + +// Scale to objects per million, then drop empty leading and repeated trailing buckets. +const workloads = Object.keys(counts).sort().map((usecase) => { + const perMillion = (count) => Math.round((count / counts[usecase].total) * 1e6); + const scaled = sizes.map((size) => [size, perMillion(counts[usecase][size] ?? 0)]); + const [largest, last] = scaled.at(-1); + const lines = scaled + .filter(([, count], i) => count > 0 && (i === 0 || scaled[i - 1][1] < last)) + .map(([size, count]) => ` ${unit(size)}: ${count}`); + if (last < 1e6) { + lines.unshift(` # WARNING: ${1e6 - last} per million objects are above ${unit(largest)}, add larger sizes`); + } + return ` - name: ${usecase}\n file_sizes:\n buckets:\n${lines.join("\n")}`; +}); +return `workloads:\n${workloads.join("\n")}`; +``` + ### Actions Controls the mix of operations. Interpretation depends on the mode: diff --git a/stresstest/config/production.example.yaml b/stresstest/config/production.example.yaml new file mode 100644 index 00000000..958bd124 --- /dev/null +++ b/stresstest/config/production.example.yaml @@ -0,0 +1,182 @@ +# Replays the object sizes of the production usecases. +# +# The `buckets` of each workload approximate the cumulative size histogram of +# `objectstore.put.size` in Datadog. The counts are rounded and scaled to one +# million objects, so they are close to production but are not the real data. +# See "Size buckets" in the README for their meaning and for how to pull the +# real histogram of a usecase. + +remote: http://localhost:18888 + +duration: 5s + +workloads: + # The write rates roughly follow the ratio between usecases, rounded. The last + # four usecases see far fewer writes than this and are set to the minimum rate. + - name: attachments + mode: fixed-rate + organizations: 1000 + actions: + writes: 100 + reads: 0 + deletes: 0 + file_sizes: + buckets: + 64 B: 16000 + 128 B: 32000 + 256 B: 73000 + 512 B: 150000 + 1 KiB: 240000 + 2 KiB: 350000 + 4 KiB: 460000 + 8 KiB: 560000 + 16 KiB: 630000 + 32 KiB: 700000 + 64 KiB: 800000 + 128 KiB: 900000 + 256 KiB: 948000 + 512 KiB: 977000 + 1 MiB: 990000 + 2 MiB: 995400 + 4 MiB: 997000 + 8 MiB: 998500 + 16 MiB: 999310 + 32 MiB: 999890 + 64 MiB: 999956 + 128 MiB: 999990 + 256 MiB: 999998 + 512 MiB: 999999 + 1 GiB: 1000000 + - name: debug_files + mode: fixed-rate + organizations: 1000 + actions: + writes: 5 + reads: 0 + deletes: 0 + file_sizes: + buckets: + 64 B: 1 + 128 B: 20 + 256 B: 290 + 512 B: 12000 + 1 KiB: 22000 + 2 KiB: 40000 + 4 KiB: 65000 + 8 KiB: 100000 + 16 KiB: 170000 + 32 KiB: 300000 + 64 KiB: 390000 + 128 KiB: 470000 + 256 KiB: 550000 + 512 KiB: 620000 + 1 MiB: 720000 + 2 MiB: 790000 + 4 MiB: 850000 + 8 MiB: 890000 + 16 MiB: 939000 + 32 MiB: 963000 + 64 MiB: 981000 + 128 MiB: 990300 + 256 MiB: 995500 + 512 MiB: 998100 + 1 GiB: 999820 + 2 GiB: 999982 + 4 GiB: 1000000 + - name: preprod + mode: fixed-rate + organizations: 1000 + actions: + writes: 1 + reads: 0 + deletes: 0 + file_sizes: + buckets: + 64 B: 420 + 128 B: 420 + 256 B: 1000 + 512 B: 4000 + 1 KiB: 4400 + 2 KiB: 7200 + 4 KiB: 15000 + 8 KiB: 52000 + 16 KiB: 110000 + 32 KiB: 270000 + 64 KiB: 410000 + 128 KiB: 640000 + 256 KiB: 790000 + 512 KiB: 860000 + 1 MiB: 890000 + 2 MiB: 932000 + 4 MiB: 978000 + 8 MiB: 995200 + 16 MiB: 1000000 + - name: preprod_size + mode: fixed-rate + organizations: 1000 + actions: + writes: 1 + reads: 0 + deletes: 0 + file_sizes: + buckets: + 128 B: 42000 + 256 B: 79000 + 512 B: 190000 + 1 KiB: 390000 + 2 KiB: 460000 + 4 KiB: 600000 + 8 KiB: 700000 + 16 KiB: 902000 + 32 KiB: 989000 + 64 KiB: 1000000 + - name: preprod_snapshots + mode: fixed-rate + organizations: 1000 + actions: + writes: 1 + reads: 0 + deletes: 0 + file_sizes: + buckets: + 64 B: 120 + 128 B: 280000 + 256 B: 360000 + 512 B: 400000 + 1 KiB: 460000 + 2 KiB: 620000 + 4 KiB: 710000 + 8 KiB: 770000 + 16 KiB: 810000 + 32 KiB: 840000 + 64 KiB: 880000 + 128 KiB: 903000 + 256 KiB: 929000 + 512 KiB: 953000 + 1 MiB: 988000 + 2 MiB: 990000 + 4 MiB: 996300 + 8 MiB: 998700 + 16 MiB: 999984 + 32 MiB: 999984 + 64 MiB: 999999 + 128 MiB: 1000000 + - name: profile_attachments + mode: fixed-rate + organizations: 1000 + actions: + writes: 1 + reads: 0 + deletes: 0 + file_sizes: + buckets: + 4 KiB: 200 + 8 KiB: 1200 + 16 KiB: 52000 + 32 KiB: 100000 + 64 KiB: 120000 + 128 KiB: 150000 + 256 KiB: 220000 + 512 KiB: 350000 + 1 MiB: 890000 + 2 MiB: 1000000 diff --git a/stresstest/src/config.rs b/stresstest/src/config.rs index ae12cb3b..56db0e16 100644 --- a/stresstest/src/config.rs +++ b/stresstest/src/config.rs @@ -3,6 +3,7 @@ use std::time::Duration; use anyhow::bail; use bytesize::ByteSize; +use serde::de::{MapAccess, Visitor}; use serde::{Deserialize, Deserializer}; use stresstest::workload::WorkloadMode; @@ -92,14 +93,28 @@ pub struct Workload { impl Workload { pub fn validate(&self) -> anyhow::Result<()> { - if let Some(min) = self.file_sizes.min { - if min >= self.file_sizes.p50 || self.file_sizes.p99 < self.file_sizes.p50 { + let sizes = &self.file_sizes; + let valid = match sizes.buckets { + Some(_) => [sizes.min, sizes.p50, sizes.p99, sizes.max] + .iter() + .all(Option::is_none), + None => sizes.p50.is_some() && sizes.p99.is_some(), + }; + if !valid { + bail!( + "workload '{}': file_sizes needs either `buckets` alone, or `p50` and `p99` \ + with optional `min` and `max`", + self.name + ); + } + if let (Some(min), Some(p50), Some(p99)) = (sizes.min, sizes.p50, sizes.p99) { + if min >= p50 || p99 < p50 { bail!( "workload '{}': file sizes must satisfy min < p50 <= p99", self.name ); } - if self.file_sizes.max.is_some_and(|max| max < min) { + if sizes.max.is_some_and(|max| max < min) { bail!( "workload '{}': maximum file size is below the minimum", self.name @@ -135,12 +150,47 @@ fn default_organizations() -> u64 { 1 } +/// File size distribution of a workload. +/// +/// Sizes are either drawn from a lognormal distribution fitted to `p50` and `p99`, optionally +/// bounded by `min` and `max`, or from a histogram of size `buckets`. See +/// [`SizeBuckets`](stresstest::workload::SizeBuckets) for the meaning of buckets. #[derive(Debug, Deserialize)] pub struct FileSizes { pub min: Option, - pub p50: ByteSize, - pub p99: ByteSize, + pub p50: Option, + pub p99: Option, pub max: Option, + /// Bucket sizes in bytes with the cumulative count of objects at or below each size, in the + /// order they are written in the config. + #[serde(default, deserialize_with = "deserialize_buckets")] + pub buckets: Option>, +} + +/// Deserializes a map of sizes to counts into pairs, keeping the order of the map. +fn deserialize_buckets<'de, D>(deserializer: D) -> Result>, D::Error> +where + D: Deserializer<'de>, +{ + struct BucketsVisitor; + + impl<'de> Visitor<'de> for BucketsVisitor { + type Value = Vec<(u64, f64)>; + + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("a map of sizes to cumulative object counts") + } + + fn visit_map>(self, mut map: A) -> Result { + let mut buckets = Vec::new(); + while let Some((size, count)) = map.next_entry::()? { + buckets.push((size.0, count)); + } + Ok(buckets) + } + } + + deserializer.deserialize_map(BucketsVisitor).map(Some) } #[derive(Debug, Deserialize)] @@ -159,3 +209,25 @@ impl Default for Actions { } } } + +#[cfg(test)] +mod tests { + use stresstest::workload::SizeBuckets; + + use super::*; + + #[test] + fn example_configs_are_valid() { + for name in ["example.yaml", "production.example.yaml"] { + let path = format!("{}/config/{name}", env!("CARGO_MANIFEST_DIR")); + let config: Config = + serde_yaml::from_reader(std::fs::File::open(path).unwrap()).unwrap(); + for workload in config.workloads { + workload.validate().unwrap(); + if let Some(buckets) = workload.file_sizes.buckets { + SizeBuckets::new(buckets).unwrap(); + } + } + } + } +} diff --git a/stresstest/src/lib.rs b/stresstest/src/lib.rs index 49f2145f..cc2aa14c 100644 --- a/stresstest/src/lib.rs +++ b/stresstest/src/lib.rs @@ -1,10 +1,10 @@ //! This is a stresstest library which can run different [`Workload`]s against //! a backend storage service. //! -//! The [`Workload`] currently supports configuring a *LogNormal* distribution -//! of file sizes, defined by the `p50` and `p99` of file sizes. -//! This models our real-world distribution of many small files, with a long -//! tail of larger files as well. +//! The [`Workload`] supports two ways of configuring file sizes. A *LogNormal* +//! distribution, defined by the `p50` and `p99` of file sizes, models many +//! small files with a long tail of larger files. A histogram of [`SizeBuckets`] +//! replays a file size distribution that was measured in production. //! //! It also allows configuring a distribution of actions, such as write, read or delete. //! The goal is that we have a lot of *write-heavy* workloads which only write @@ -16,6 +16,8 @@ //! To run a stresstest, instantiate the [`Stresstest`] struct with a remote backend //! implementation, such as the [`HttpRemote`](http::HttpRemote) and configure it with //! the desired duration and workload. +//! +//! [`SizeBuckets`]: workload::SizeBuckets #![warn(missing_docs)] #![warn(missing_debug_implementations)] diff --git a/stresstest/src/main.rs b/stresstest/src/main.rs index 4a62fc12..93136d67 100644 --- a/stresstest/src/main.rs +++ b/stresstest/src/main.rs @@ -1,10 +1,10 @@ //! This is a stresstest binary which can run different [`Workload`]s against //! a backend storage service. //! -//! The [`Workload`] currently supports configuring a *LogNormal* distribution -//! of file sizes, defined by the `p50` and `p99` of file sizes. -//! This models our real-world distribution of many small files, with a long -//! tail of larger files as well. +//! The [`Workload`] supports two ways of configuring file sizes. A *LogNormal* +//! distribution, defined by the `p50` and `p99` of file sizes, models many +//! small files with a long tail of larger files. A histogram of [`SizeBuckets`] +//! replays a file size distribution that was measured in production. //! //! It also allows configuring a distribution of actions, such as write, read or delete. //! The goal is that we have a lot of *write-heavy* workloads which only write @@ -12,6 +12,8 @@ //! //! *Read* or *delete* actions are using a *zipfian* distribution, meaning that //! more recently written blobs are the ones that will be read/deleted. +//! +//! [`SizeBuckets`]: stresstest::workload::SizeBuckets #![warn(missing_docs)] #![warn(missing_debug_implementations)] @@ -23,6 +25,7 @@ use objectstore_client::{SecretKey, TokenGenerator}; use stresstest::Workload; use stresstest::http::HttpRemote; use stresstest::stresstest::Stresstest; +use stresstest::workload::SizeBuckets; use crate::config::Config; @@ -79,17 +82,25 @@ async fn main() -> anyhow::Result<()> { for w in config.workloads { w.validate()?; - let workload = Workload::builder(w.name) + let sizes = w.file_sizes; + let mut workload = Workload::builder(&w.name) .concurrency(w.concurrency) .organizations(w.organizations) .mode(w.mode) - .size_distribution(w.file_sizes.p50.0, w.file_sizes.p99.0) - .min_size(w.file_sizes.min.map_or(0, |b| b.0)) - .max_size(w.file_sizes.max.map(|b| b.0)) - .action_weights(w.actions.writes, w.actions.reads, w.actions.deletes) - .build(); - - stresstest = stresstest.workload(workload); + .min_size(sizes.min.map_or(0, |b| b.0)) + .max_size(sizes.max.map(|b| b.0)) + .action_weights(w.actions.writes, w.actions.reads, w.actions.deletes); + + if let (Some(p50), Some(p99)) = (sizes.p50, sizes.p99) { + workload = workload.size_distribution(p50.0, p99.0); + } + if let Some(buckets) = sizes.buckets { + let buckets = SizeBuckets::new(buckets) + .with_context(|| format!("workload '{}': invalid file size buckets", w.name))?; + workload = workload.size_buckets(buckets); + } + + stresstest = stresstest.workload(workload.build()); } stresstest.run().await?; diff --git a/stresstest/src/workload.rs b/stresstest/src/workload.rs index dae35434..3c6d359a 100644 --- a/stresstest/src/workload.rs +++ b/stresstest/src/workload.rs @@ -5,6 +5,7 @@ use std::thread::available_parallelism; use std::time::Instant; use std::{fmt, io, task}; +use anyhow::ensure; use objectstore_client::Usecase; use rand::rngs::SmallRng; use rand::{Rng, RngExt, SeedableRng}; @@ -35,6 +36,76 @@ pub enum WorkloadMode { Batch, } +/// Object sizes as a histogram of size buckets. +/// +/// Each bucket is the largest object size it holds, in bytes, with the number of objects at or +/// below that size. A bucket holds the sizes above the previous bucket's size, and the first +/// bucket starts at half its own size. Counts are cumulative and only their ratio to the last +/// count matters, so absolute counts, shares and percentages are equivalent. +/// +/// Sampling picks a bucket with a probability proportional to the objects it adds over the +/// previous bucket, then draws a size log-uniformly within that bucket. Buckets that add no +/// objects are never picked. +/// +/// ``` +/// # use stresstest::workload::SizeBuckets; +/// // Half of the objects are in (512, 1024] bytes, the other half in (1024, 2048] bytes. +/// let buckets = SizeBuckets::new(vec![(1024, 50.0), (2048, 100.0)]).unwrap(); +/// ``` +#[derive(Debug, Clone)] +pub struct SizeBuckets(Vec<(u64, f64)>); + +impl SizeBuckets { + /// Creates size buckets from `(size, cumulative count)` pairs. + /// + /// # Errors + /// + /// Fails unless sizes are positive and strictly increasing, counts do not decrease, and the + /// last count is greater than zero. + pub fn new(buckets: Vec<(u64, f64)>) -> anyhow::Result { + let (mut last_size, mut last_count) = (0, 0.0); + for &(size, count) in &buckets { + ensure!( + size > last_size, + "bucket sizes must be positive and strictly increasing, \ + but {size} bytes follows {last_size} bytes" + ); + ensure!( + count >= last_count && count.is_finite(), + "bucket counts are cumulative and must not decrease, \ + but {count} at {size} bytes follows {last_count}" + ); + (last_size, last_count) = (size, count); + } + ensure!(last_count > 0.0, "the last bucket count must be positive"); + + Ok(Self(buckets)) + } +} + +impl Distribution for SizeBuckets { + fn sample(&self, rng: &mut R) -> u64 { + let buckets = &self.0; + let total = buckets[buckets.len() - 1].1; + + // The rank of the sampled object in `(0, total]`, which falls into the first bucket with + // at least that many objects. + let rank = (1.0 - rng.random::()) * total; + let index = buckets.partition_point(|&(_, count)| count < rank); + + let (size, count) = buckets[index]; + let (lower_size, lower_count) = match index { + 0 => (size as f64 / 2.0, 0.0), + _ => (buckets[index - 1].0 as f64, buckets[index - 1].1), + }; + + // Spread the bucket's ranks log-uniformly over `(lower_size, size]`. + let position = (rank - lower_count) / (count - lower_count); + let sampled = lower_size * (size as f64 / lower_size).powf(position); + (sampled.ceil() as u64).min(size) + } +} + /// A builder for creating a [`Workload`]. #[derive(Debug)] pub struct WorkloadBuilder { @@ -48,6 +119,7 @@ pub struct WorkloadBuilder { p99_size: u64, min_size: u64, max_size: Option, + size_buckets: Option, write_weight: usize, read_weight: usize, @@ -92,6 +164,15 @@ impl WorkloadBuilder { self } + /// Draws file sizes for the `write` action from a histogram of size buckets. + /// + /// This replaces the distribution set by [`size_distribution`](Self::size_distribution), + /// including the minimum and maximum payload size. + pub fn size_buckets(mut self, buckets: SizeBuckets) -> Self { + self.size_buckets = Some(buckets); + self + } + /// The ratio between writes, reads and deletes. pub fn action_weights(mut self, writes: usize, reads: usize, deletes: usize) -> Self { self.write_weight = writes; @@ -104,14 +185,24 @@ impl WorkloadBuilder { pub fn build(self) -> Workload { let rng = SmallRng::seed_from_u64(self.seed); - // Inspired by - // Fit the distribution above the floor so shifting the samples preserves p50 and p99. - let p50 = (self.p50_size - self.min_size) as f64; - let p99 = (self.p99_size - self.min_size) as f64; - let mu = p50.ln(); - let sigma = (p99.ln() - mu) / 2.3263; - - let size_distribution = LogNormal::new(mu, sigma).unwrap(); + let sizes = match self.size_buckets { + Some(buckets) => SizeDistribution::Buckets(buckets), + None => { + // Inspired by + // Fit the distribution above the floor so shifting the samples preserves p50 and + // p99. + let p50 = (self.p50_size - self.min_size) as f64; + let p99 = (self.p99_size - self.min_size) as f64; + let mu = p50.ln(); + let sigma = (p99.ln() - mu) / 2.3263; + + SizeDistribution::LogNormal { + distribution: LogNormal::new(mu, sigma).unwrap(), + min: self.min_size, + max: self.max_size, + } + } + }; let action_distribution = WeightedIndex::new([self.write_weight, self.read_weight, self.delete_weight]).unwrap(); @@ -122,9 +213,7 @@ impl WorkloadBuilder { mode: self.mode, rng, - size_distribution, - min_size: self.min_size, - max_size: self.max_size, + sizes, action_distribution, start_time: None, @@ -142,6 +231,19 @@ struct Totals { deletes: usize, } +/// How a [`Workload`] generates payload sizes for the `write` action. +#[derive(Debug)] +enum SizeDistribution { + /// A lognormal distribution, with `min` added to each sampled size and capped at `max`. + LogNormal { + distribution: LogNormal, + min: u64, + max: Option, + }, + /// A histogram of size buckets. + Buckets(SizeBuckets), +} + /// Specification of a stresstest that can be run against a remote storage service. #[derive(Debug)] pub struct Workload { @@ -156,12 +258,8 @@ pub struct Workload { /// The RNG driving all our distributions. rng: SmallRng, - /// A distribution that generates payload sizes for the `write` action. - size_distribution: LogNormal, - /// Minimum payload size in bytes, added to each sampled size. - min_size: u64, - /// Optional maximum payload size in bytes. - max_size: Option, + /// The distribution that generates payload sizes for the `write` action. + sizes: SizeDistribution, /// A distribution that generates actions, such as write/read/delete. action_distribution: WeightedIndex, @@ -186,6 +284,7 @@ impl Workload { p99_size: 1024 * 1024, min_size: 0, max_size: None, + size_buckets: None, write_weight: 33, read_weight: 33, @@ -195,12 +294,17 @@ impl Workload { fn get_payload(&self, seed: u64) -> Payload { let mut rng = SmallRng::seed_from_u64(seed); - let mut len = - (self.size_distribution.sample(&mut rng) as u64).saturating_add(self.min_size); - - if let Some(max) = self.max_size { - len = len.min(max); - } + let len = match &self.sizes { + SizeDistribution::Buckets(buckets) => buckets.sample(&mut rng), + SizeDistribution::LogNormal { + distribution, + min, + max, + } => { + let len = (distribution.sample(&mut rng) as u64).saturating_add(*min); + max.map_or(len, |max| len.min(max)) + } + }; Payload { len, rng } } @@ -392,6 +496,47 @@ mod tests { } } + #[test] + fn size_buckets_match_configured_shares() { + // 10% up to 1 KiB, another 60% up to 2 KiB, nothing up to 4 KiB, the last 30% up to 8 KiB. + let counts = vec![(1024, 10.0), (2048, 70.0), (4096, 70.0), (8192, 100.0)]; + let workload = Workload::builder("test") + .size_buckets(SizeBuckets::new(counts.clone()).unwrap()) + .build(); + + const SAMPLES: u64 = 100_000; + let sizes: Vec<_> = (0..SAMPLES) + .map(|seed| workload.get_payload(seed).len) + .collect(); + + assert!(sizes.iter().all(|size| (513..=8192).contains(size))); + for (bound, count) in counts { + let at_or_below = sizes.iter().filter(|&&size| size <= bound).count(); + let share = at_or_below as f64 / SAMPLES as f64; + assert!((share - count / 100.0).abs() < 0.01, "{bound}: {share}"); + } + } + + #[test] + fn size_buckets_replace_percentile_settings() { + // These settings cannot be fitted to a lognormal distribution, and buckets ignore them. + let workload = Workload::builder("test") + .size_distribution(100, 10) + .min_size(1024) + .size_buckets(SizeBuckets::new(vec![(64, 1.0)]).unwrap()) + .build(); + + assert!((33..=64).contains(&workload.get_payload(0).len)); + } + + #[test] + fn size_buckets_reject_invalid_input() { + assert!(SizeBuckets::new(vec![]).is_err()); + assert!(SizeBuckets::new(vec![(1024, 0.0)]).is_err()); + assert!(SizeBuckets::new(vec![(2048, 1.0), (1024, 2.0)]).is_err()); + assert!(SizeBuckets::new(vec![(1024, 2.0), (2048, 1.0)]).is_err()); + } + #[test] fn lognormal_percentiles_work() { let workload = Workload::builder("test")