From cebdcac5ad97bd8ff8be6e6959035deef1392c93 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:09:09 +0100 Subject: [PATCH 1/3] feat(stresstest): Configure file sizes as a histogram of size buckets Add a second form of file_sizes: buckets of sizes with the cumulative count of objects at or below each size. A size is drawn by picking a bucket in proportion to the objects it adds, then log-uniformly within the bucket. The lognormal form with p50 and p99 keeps working unchanged. The lognormal fit guesses everything above p99, which put the average object size at 0.64x to 3.3x of production depending on the usecase. Buckets at every power of two, taken from the objectstore.put.size metric, bring the average within about 10% for all production usecases. Add production.example.yaml with one workload per production usecase, with rounded counts that are close to production, and document in the README how to pull the buckets from Datadog. --- stresstest/README.md | 147 ++++++++++++++++- stresstest/config/production.example.yaml | 182 ++++++++++++++++++++++ stresstest/src/config.rs | 82 +++++++++- stresstest/src/lib.rs | 10 +- stresstest/src/main.rs | 35 +++-- stresstest/src/workload.rs | 119 ++++++++++++++ 6 files changed, 552 insertions(+), 23 deletions(-) create mode 100644 stresstest/config/production.example.yaml diff --git a/stresstest/README.md b/stresstest/README.md index 13552fb3..8aba36d8 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,17 @@ 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. There are two ways +to describe them, and a workload uses one or the other: + +- [Percentiles](#percentiles): a rough shape from a median and a 99th + percentile. Use this for hand-written workloads. +- [Size buckets](#size-buckets): a histogram measured in production. Use this + to replay the real object sizes of a usecase. + +#### Percentiles + +Sizes are drawn from a LogNormal distribution fitted to `p50` and `p99`: | Field | Required | Description | |-------|----------|------------------------------------------| @@ -47,6 +58,138 @@ 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 | +This matches the two given percentiles, but everything above `p99` is a guess. +Large objects dominate the bytes written, so the average object size can be +several times off compared to a real usecase. Use size buckets when that matters. + +#### Size buckets + +`buckets` is a histogram of object sizes. Each line is a size and 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 # 6000 are at most 2 KiB, so 3500 are between 1 and 2 KiB + 4 KiB: 9900 # 3900 are between 2 and 4 KiB + 8 KiB: 10000 # 100 are between 4 and 8 KiB, and no object is larger +``` + +The rules are: + +- Counts are cumulative: each one includes all objects of the lines above it, + so counts never decrease from one line to the next. +- Only the ratio to the last count matters. Raw counts, counts per million and + percentages (ending at `100`) all describe the same distribution. +- Sizes must be in increasing order. Use a size that is twice the previous one + on every line. The histogram does not record where objects fall within a + bucket, so wider buckets make the generated sizes less accurate. +- The first bucket starts at half its size. In the example above, the first + 2500 objects are between 512 B and 1 KiB. +- A bucket that adds no objects generates no objects. Lines that repeat the + previous count are harmless, and so are leading lines with a count of `0`. + +To generate a size, the stresstest picks a bucket with a probability +proportional to the objects it adds, then picks a size within the bucket so that +every doubling of size is equally likely (log-uniform). + +`buckets` cannot be combined with `min`, `p50`, `p99` or `max`. + +#### Getting size buckets from Datadog + +Objectstore reports the size of every stored object in the +`objectstore.put.size` distribution metric, tagged by `usecase`. Datadog can +count the objects at or below a given size, which is the number that `buckets` +takes. For a size of 64 KiB (65536 bytes), the query is: + +``` +count(v: v<=65536):objectstore.put.size{sentry_region:us,environment:production} by {usecase}.as_count() +``` + +Summed over the time range, this returns the count for the `64 KiB` line of each +usecase. Getting all buckets means running this query once per size: + +1. Pick the scope (region and environment) and a time range. A week covers the + daily and weekly cycles. +2. Run the query for every power of two from `64` (64 B) to `8589934592` + (8 GiB), replacing `65536` with the size in bytes. Sum each result over the + whole time range. +3. Write the results under `buckets`, one line per size. Leading lines with a + count of `0` and trailing lines that repeat the final count can be left out. +4. Before committing the numbers to this repository, scale them to a fixed total + such as one million objects and round them, so that production data stays + private. The numbers in `config/production.example.yaml` are rounded this way. + +The quickest way to do all of this is to ask a coding agent that has the +[Datadog MCP server](https://docs.datadoghq.com/bits_ai/mcp_server/) to run the +script below with its `execute_code` tool. It needs no API key. It runs the +queries for all usecases and returns `workloads` entries that are scaled to one +million objects and ready to paste into a config. Change `scope` and `days` as +needed. + +```javascript +import { client, v2 } from "@datadog/datadog-api-client"; + +const scope = "{sentry_region:us,environment:production}"; +const days = 7; + +const api = new v2.MetricsApi(client.createConfiguration()); +const to = Date.parse(dd.time.hoursAgo(1)); +const from = to - days * 24 * 3600 * 1000; + +// Count the objects at or below every power of two from 64 B to 8 GiB. +const sizes = Array.from({ length: 28 }, (_, i) => 2 ** (i + 6)); +const counts = {}; +for (let i = 0; i < sizes.length; i += 7) { + const queries = sizes.slice(i, i + 7).map((size) => ({ + name: `${size}`, + dataSource: "metrics", + aggregator: "sum", + query: `count(v: v<=${size}):objectstore.put.size${scope} by {usecase}.as_count()`, + })); + 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; + 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 total = counts[usecase][sizes.at(-1)]; + const scaled = sizes.map((size) => [size, Math.round(((counts[usecase][size] ?? 0) / total) * 1e6)]); + const buckets = scaled.filter(([, count], i) => count > 0 && (i === 0 || scaled[i - 1][1] < 1e6)); + const lines = buckets.map(([size, count]) => ` ${unit(size)}: ${count}`); + return ` - name: ${usecase}\n file_sizes:\n buckets:\n${lines.join("\n")}`; +}); +const window = `${new Date(from).toISOString()} to ${new Date(to).toISOString()}`; +return `# objectstore.put.size${scope}, ${window}\nworkloads:\n${workloads.join("\n")}`; +``` + +Without an agent, run the query in the Datadog UI with a widget that reduces a +metric query to one value per group over the selected time range, such as a +table in a notebook, and sum the values over time. Threshold queries like +`count(v: v<=...)` need percentiles to be enabled for the metric, which is the +case for `objectstore.put.size`. + +Measured against one week of production data, sizes generated from these +buckets had an average within about 10% of the real average for every usecase, +and a p50 and p90 within 15%. Higher percentiles can be off by more, up to the +2x width of a bucket, when the largest objects of a usecase cluster in one part +of a bucket. + ### 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..759eca52 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; @@ -125,6 +206,7 @@ impl WorkloadBuilder { size_distribution, min_size: self.min_size, max_size: self.max_size, + size_buckets: self.size_buckets, action_distribution, start_time: None, @@ -162,6 +244,8 @@ pub struct Workload { min_size: u64, /// Optional maximum payload size in bytes. max_size: Option, + /// Size buckets that generate payload sizes instead of `size_distribution`, if configured. + size_buckets: Option, /// A distribution that generates actions, such as write/read/delete. action_distribution: WeightedIndex, @@ -186,6 +270,7 @@ impl Workload { p99_size: 1024 * 1024, min_size: 0, max_size: None, + size_buckets: None, write_weight: 33, read_weight: 33, @@ -195,6 +280,11 @@ impl Workload { fn get_payload(&self, seed: u64) -> Payload { let mut rng = SmallRng::seed_from_u64(seed); + if let Some(buckets) = &self.size_buckets { + let len = buckets.sample(&mut rng); + return Payload { len, rng }; + } + let mut len = (self.size_distribution.sample(&mut rng) as u64).saturating_add(self.min_size); @@ -392,6 +482,35 @@ 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_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") From 6d25b46ec65006d29665d30ad3425e6b46980c22 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:54:20 +0100 Subject: [PATCH 2/3] fix(stresstest): Validate percentiles and fit one size distribution A workload built with size buckets still fitted the lognormal distribution from the percentile settings, so settings that buckets replace could make build() panic. The workload now holds one distribution or the other. Percentiles were only checked when min was set, so a p99 below p50 gave a wrong distribution and a p50 of zero panicked. They are now always checked. The Datadog script in the README now reports a scope without data and objects above the largest bucket. The README section is shorter, and its field tables cover both forms of file_sizes. --- stresstest/README.md | 133 +++++++++++++------------------------ stresstest/src/config.rs | 19 +++++- stresstest/src/workload.rs | 88 +++++++++++++++--------- 3 files changed, 121 insertions(+), 119 deletions(-) diff --git a/stresstest/README.md b/stresstest/README.md index 8aba36d8..5a8f9c34 100644 --- a/stresstest/README.md +++ b/stresstest/README.md @@ -39,17 +39,14 @@ Each entry in `workloads` configures an independent, concurrent workload: ### File sizes -Controls the sizes of the objects that a workload writes. There are two ways -to describe them, and a workload uses one or the other: - -- [Percentiles](#percentiles): a rough shape from a median and a 99th - percentile. Use this for hand-written workloads. -- [Size buckets](#size-buckets): a histogram measured in production. Use this - to replay the real object sizes of a usecase. +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 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 | |-------|----------|------------------------------------------| @@ -58,101 +55,73 @@ Sizes are drawn from a LogNormal distribution fitted to `p50` and `p99`: | `min` | no | Minimum file size, below p50. The distribution is fitted above this floor. | | `max` | no | Hard cap on generated file sizes | -This matches the two given percentiles, but everything above `p99` is a guess. -Large objects dominate the bytes written, so the average object size can be -several times off compared to a real usecase. Use size buckets when that matters. - #### Size buckets -`buckets` is a histogram of object sizes. Each line is a size and the number of -objects **at or below** that size: +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 # 6000 are at most 2 KiB, so 3500 are between 1 and 2 KiB - 4 KiB: 9900 # 3900 are between 2 and 4 KiB - 8 KiB: 10000 # 100 are between 4 and 8 KiB, and no object is larger + 2 KiB: 6000 # 3500 more are between 1 and 2 KiB + 4 KiB: 9900 + 8 KiB: 10000 # no object is larger ``` -The rules are: - -- Counts are cumulative: each one includes all objects of the lines above it, - so counts never decrease from one line to the next. -- Only the ratio to the last count matters. Raw counts, counts per million and - percentages (ending at `100`) all describe the same distribution. -- Sizes must be in increasing order. Use a size that is twice the previous one - on every line. The histogram does not record where objects fall within a - bucket, so wider buckets make the generated sizes less accurate. -- The first bucket starts at half its size. In the example above, the first - 2500 objects are between 512 B and 1 KiB. -- A bucket that adds no objects generates no objects. Lines that repeat the - previous count are harmless, and so are leading lines with a count of `0`. +- 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. -To generate a size, the stresstest picks a bucket with a probability -proportional to the objects it adds, then picks a size within the bucket so that -every doubling of size is equally likely (log-uniform). - -`buckets` cannot be combined with `min`, `p50`, `p99` or `max`. +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 -Objectstore reports the size of every stored object in the -`objectstore.put.size` distribution metric, tagged by `usecase`. Datadog can -count the objects at or below a given size, which is the number that `buckets` -takes. For a size of 64 KiB (65536 bytes), the query is: +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() ``` -Summed over the time range, this returns the count for the `64 KiB` line of each -usecase. Getting all buckets means running this query once per size: - -1. Pick the scope (region and environment) and a time range. A week covers the - daily and weekly cycles. -2. Run the query for every power of two from `64` (64 B) to `8589934592` - (8 GiB), replacing `65536` with the size in bytes. Sum each result over the - whole time range. -3. Write the results under `buckets`, one line per size. Leading lines with a - count of `0` and trailing lines that repeat the final count can be left out. -4. Before committing the numbers to this repository, scale them to a fixed total - such as one million objects and round them, so that production data stays - private. The numbers in `config/production.example.yaml` are rounded this way. - -The quickest way to do all of this is to ask a coding agent that has the -[Datadog MCP server](https://docs.datadoghq.com/bits_ai/mcp_server/) to run the -script below with its `execute_code` tool. It needs no API key. It runs the -queries for all usecases and returns `workloads` entries that are scaled to one -million objects and ready to paste into a config. Change `scope` and `days` as -needed. +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 the objects at or below every power of two from 64 B to 8 GiB. -const sizes = Array.from({ length: 28 }, (_, i) => 2 ** (i + 6)); +// Count all objects, and the objects at or below each size. const counts = {}; for (let i = 0; i < sizes.length; i += 7) { - const queries = sizes.slice(i, i + 7).map((size) => ({ - name: `${size}`, - dataSource: "metrics", - aggregator: "sum", - query: `count(v: v<=${size}):objectstore.put.size${scope} by {usecase}.as_count()`, - })); + 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; + 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; @@ -168,28 +137,20 @@ const unit = (size) => // Scale to objects per million, then drop empty leading and repeated trailing buckets. const workloads = Object.keys(counts).sort().map((usecase) => { - const total = counts[usecase][sizes.at(-1)]; - const scaled = sizes.map((size) => [size, Math.round(((counts[usecase][size] ?? 0) / total) * 1e6)]); - const buckets = scaled.filter(([, count], i) => count > 0 && (i === 0 || scaled[i - 1][1] < 1e6)); - const lines = buckets.map(([size, count]) => ` ${unit(size)}: ${count}`); + 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")}`; }); -const window = `${new Date(from).toISOString()} to ${new Date(to).toISOString()}`; -return `# objectstore.put.size${scope}, ${window}\nworkloads:\n${workloads.join("\n")}`; +return `workloads:\n${workloads.join("\n")}`; ``` -Without an agent, run the query in the Datadog UI with a widget that reduces a -metric query to one value per group over the selected time range, such as a -table in a notebook, and sum the values over time. Threshold queries like -`count(v: v<=...)` need percentiles to be enabled for the metric, which is the -case for `objectstore.put.size`. - -Measured against one week of production data, sizes generated from these -buckets had an average within about 10% of the real average for every usecase, -and a p50 and p90 within 15%. Higher percentiles can be off by more, up to the -2x width of a bucket, when the largest objects of a usecase cluster in one part -of a bucket. - ### Actions Controls the mix of operations. Interpretation depends on the mode: diff --git a/stresstest/src/config.rs b/stresstest/src/config.rs index 56db0e16..c7deee75 100644 --- a/stresstest/src/config.rs +++ b/stresstest/src/config.rs @@ -107,10 +107,12 @@ impl Workload { self.name ); } - if let (Some(min), Some(p50), Some(p99)) = (sizes.min, sizes.p50, sizes.p99) { + if let (Some(p50), Some(p99)) = (sizes.p50, sizes.p99) { + let min = sizes.min.unwrap_or(ByteSize(0)); if min >= p50 || p99 < p50 { bail!( - "workload '{}': file sizes must satisfy min < p50 <= p99", + "workload '{}': file sizes must satisfy min < p50 <= p99, where min \ + defaults to 0", self.name ); } @@ -230,4 +232,17 @@ mod tests { } } } + + #[test] + fn percentiles_must_be_ordered() { + let validate = |file_sizes: &str| { + let yaml = format!("{{name: test, file_sizes: {file_sizes}}}"); + serde_yaml::from_str::(&yaml).unwrap().validate() + }; + + assert!(validate("{p50: 1 KiB, p99: 1 KiB}").is_ok()); + assert!(validate("{p50: 2 KiB, p99: 1 KiB}").is_err()); + assert!(validate("{p50: 0 B, p99: 1 KiB}").is_err()); + assert!(validate("{min: 1 KiB, p50: 1 KiB, p99: 2 KiB}").is_err()); + } } diff --git a/stresstest/src/workload.rs b/stresstest/src/workload.rs index 759eca52..3c6d359a 100644 --- a/stresstest/src/workload.rs +++ b/stresstest/src/workload.rs @@ -185,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(); @@ -203,10 +213,7 @@ impl WorkloadBuilder { mode: self.mode, rng, - size_distribution, - min_size: self.min_size, - max_size: self.max_size, - size_buckets: self.size_buckets, + sizes, action_distribution, start_time: None, @@ -224,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 { @@ -238,14 +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, - /// Size buckets that generate payload sizes instead of `size_distribution`, if configured. - size_buckets: 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, @@ -280,17 +294,17 @@ impl Workload { fn get_payload(&self, seed: u64) -> Payload { let mut rng = SmallRng::seed_from_u64(seed); - if let Some(buckets) = &self.size_buckets { - let len = buckets.sample(&mut rng); - return Payload { len, rng }; - } - - 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 } } @@ -503,6 +517,18 @@ mod tests { } } + #[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()); From 348849b381149b8d0805966ad666a5364e25f614 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:56:55 +0100 Subject: [PATCH 3/3] ref(stresstest): Restore the percentile validation The check of p50 and p99 without min is not related to size buckets, so this keeps the validation that main has. --- stresstest/src/config.rs | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/stresstest/src/config.rs b/stresstest/src/config.rs index c7deee75..56db0e16 100644 --- a/stresstest/src/config.rs +++ b/stresstest/src/config.rs @@ -107,12 +107,10 @@ impl Workload { self.name ); } - if let (Some(p50), Some(p99)) = (sizes.p50, sizes.p99) { - let min = sizes.min.unwrap_or(ByteSize(0)); + 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, where min \ - defaults to 0", + "workload '{}': file sizes must satisfy min < p50 <= p99", self.name ); } @@ -232,17 +230,4 @@ mod tests { } } } - - #[test] - fn percentiles_must_be_ordered() { - let validate = |file_sizes: &str| { - let yaml = format!("{{name: test, file_sizes: {file_sizes}}}"); - serde_yaml::from_str::(&yaml).unwrap().validate() - }; - - assert!(validate("{p50: 1 KiB, p99: 1 KiB}").is_ok()); - assert!(validate("{p50: 2 KiB, p99: 1 KiB}").is_err()); - assert!(validate("{p50: 0 B, p99: 1 KiB}").is_err()); - assert!(validate("{min: 1 KiB, p50: 1 KiB, p99: 2 KiB}").is_err()); - } }