:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(flags): remodel flags cdc store schema (#72746)
Matheus Batistaaa4a203014b7
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex c01b909016e7..927a8dc09e59 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3994,6 +3994,7 @@ dependencies = ["common-kafka","common-metrics","envconfig",+ "hdrhistogram","lifecycle","metrics","metrics-exporter-prometheus",diff --git a/rust/Dockerfile.sqlx-migrate b/rust/Dockerfile.sqlx-migrateindex a8fd9c4edfa3..e010e51dfd41 100644--- a/rust/Dockerfile.sqlx-migrate+++ b/rust/Dockerfile.sqlx-migrate@@ -22,6 +22,7 @@ COPY ./persons_migrations ./persons_migrationsCOPY ./cyclotron-core/migrations ./cyclotron-core/migrationsCOPY ./behavioral_cohorts_migrations ./behavioral_cohorts_migrationsCOPY ./cyclotron-node-migrations ./cyclotron-node-migrations+COPY ./flags_read_store_migrations ./flags_read_store_migrationsCOPY ./bin/migrate-persons ./bin/migrate-personsCOPY ./bin/migrate-cyclotron ./bin/migrate-cyclotrondiff --git a/rust/flags-consumer/Cargo.toml b/rust/flags-consumer/Cargo.tomlindex ef6510193c6f..0247ed1bf057 100644--- a/rust/flags-consumer/Cargo.toml+++ b/rust/flags-consumer/Cargo.toml@@ -17,6 +17,7 @@ metrics-exporter-prometheus = { workspace = true }axum = { workspace = true }chrono = { workspace = true }envconfig = { workspace = true }+hdrhistogram = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }diff --git a/rust/flags-consumer/README.md b/rust/flags-consumer/README.mdnew file mode 100644index 000000000000..ff7a318dc42e--- /dev/null+++ b/rust/flags-consumer/README.md@@ -0,0 +1,80 @@+# Flags consumer++`flags-consumer` builds the dedicated feature-flag read store from person and distinct ID CDC topics. It applies version-guarded batches so replayed or out-of-order messages cannot replace newer state.++## Read-store schema++The store uses two tables, each hash-partitioned by `team_id`:++- `flags_person` stores one properties row per `(team_id, person_uuid)`.+- `flags_distinct_id_map` stores one owner per `(team_id, distinct_id)`.++Both tables use primary-key B-tree indexes. Deletes are versioned tombstones. A canonical lookup uses one round trip and two primary-key probes:++```sql+SELECT p.person_uuid, p.properties+FROM flags_distinct_id_map AS m+JOIN flags_person AS p+ ON p.team_id = m.team_id+ AND p.person_uuid = m.person_uuid+WHERE m.team_id = $1+ AND m.distinct_id = $2+ AND m.deleted_at IS NULL+ AND p.deleted_at IS NULL;+```++`rust/flags_read_store_migrations` owns this DDL. It replaces an earlier `flags_person_lookup` draft that used a `distinct_ids` array with a GIN index; that draft never ran outside a local checkout, so it was rewritten in place rather than retired by a second migration. If your local `flags_read_store` database applied the draft, `sqlx migrate run` reports a checksum mismatch — drop and recreate the database, then re-run `bin/migrate --scope=flags-read-store`.++## Schema benchmark++The benchmark populates the two tables, runs `VACUUM ANALYZE` and `CHECKPOINT`, verifies every storage query plan, then runs six phases:++1. `baseline_reads` sends average-rate reads only.+2. `steady_mix` sends every class at its average production rate.+3. `peak_mix` sends every class at its measured five-minute peak rate.+4. `merge_storm` adds ten times the peak merge rate to the steady mix.+5. `recovery` vacuums both table groups before measuring the steady mix again.+6. `catch_up` keeps reads open-loop while write classes use independent backpressured feeds to measure sustainable throughput.++Creation traffic produces one person upsert and one distinct ID assignment. In open-loop phases, the independent distinct ID schedule is reduced by the paired creation rate so the total class rate stays at the requested target. Catch-up disables paired creation so each closed write feed measures its class independently.++The gate profile checks every open feed's deadline-scoped rate and backlog, zero shedding and operation errors in every phase, peak and storm read latency, interval drift, storm-drain-inclusive recovery time, catch-up write headroom, and load-generator dispatch latency. The smoke profile prints the same diagnostics but does not fail on production thresholds.++Warning: unless `--skip-populate` is passed, the benchmark drops `flags_person_lookup`, `flags_person`, and `flags_distinct_id_map`, then recreates the current tables. Use a dedicated benchmark database. Destructive setup requires the explicit `--allow-destructive-reset` flag. `--skip-populate` inspects the existing partition layout but cannot verify that its rows match the supplied scale, team count, and seed; run metadata records the population as unverified.++Set `FLAGS_READ_STORE_DATABASE_URL` for the dedicated benchmark database. The benchmark does not fall back to `DATABASE_URL`. Run these commands from `rust/`.++Local smoke run:++```sh+FLAGS_READ_STORE_DATABASE_URL=postgres://posthog:posthog@localhost:5432/flags_read_store \+ cargo run -p flags-consumer --release -- benchmark \+ --profile smoke --scale 400000 --partitions 8 --allow-destructive-reset+```++Single partition at target density:++```sh+FLAGS_READ_STORE_DATABASE_URL="$BENCHMARK_DATABASE_URL" \+ cargo run -p flags-consumer --release -- benchmark \+ --profile smoke --partitions 1 --scale 45000000 --allow-destructive-reset+```++Aurora gate run on the production-candidate instance:++```sh+FLAGS_READ_STORE_DATABASE_URL="$AURORA_BENCHMARK_DATABASE_URL" \+ cargo run -p flags-consumer --release -- benchmark \+ --profile gate --scale 45000000 --partitions 64 \+ --allow-destructive-reset \+ --out tmp/flags-read-store-aurora-gate.jsonl+```++The output path defaults to `tmp/flags-read-store-benchmark.jsonl`. JSONL records include run metadata, actual schema metadata, 10-second latency intervals, PostgreSQL table and WAL samples, phase summaries, and the automated gate result. The console report shows deadline-scoped scheduled and achieved rates alongside eventual completion totals, deadline backlog, post-deadline and executor-drain time, latency percentiles, retries, deadlocks, table statistics, WAL volume, catch-up headroom against peak, and each gate decision.++An automated pass is only part of the go/no-go decision. The report lists the remaining manual qualifications: bloat equilibrium and per-partition autovacuum progress, bootstrap extrapolation, production-candidate working-set size, and guaranteed load-generator CPU.++## Follow-ups outside this repository++- Amend the RFC in `requests-for-comments-internal` to describe the mapping-table design and correct the legacy `= ANY` read query.+- Give the benchmark load generator guaranteed CPU in `cloud-infra` before using it for production-candidate latency gates.diff --git a/rust/flags-consumer/src/benchmark/collector.rs b/rust/flags-consumer/src/benchmark/collector.rsnew file mode 100644index 000000000000..1f330e967613--- /dev/null+++ b/rust/flags-consumer/src/benchmark/collector.rs@@ -0,0 +1,517 @@+use std::array;+use std::fs::File;+use std::io::{BufWriter, Write};+use std::path::Path;++use hdrhistogram::Histogram;+use serde::Serialize;++use super::ops::{CompletionOutcome, CompletionRecord, OpClass, PhaseId, PhaseMismatch};+use super::scheduler::{DispatchOutcome, DispatchRecord};++const HISTOGRAM_SIGNIFICANT_DIGITS: u8 = 3;+pub const DEFAULT_INTERVAL_SECS: u64 = 10;++#[derive(Debug)]+struct LatencyHistograms {+ service: Histogram<u64>,+ schedule: Histogram<u64>,+ queue: Histogram<u64>,+ dispatch_lag: Histogram<u64>,+}++impl LatencyHistograms {+ fn new() -> Self {+ Self {+ service: new_histogram(),+ schedule: new_histogram(),+ queue: new_histogram(),+ dispatch_lag: new_histogram(),+ }+ }++ fn record(&mut self, completion: &CompletionRecord) {+ record_latency(&mut self.service, completion.service_latency_nanos());+ record_latency(&mut self.schedule, completion.schedule_latency_nanos());+ record_latency(&mut self.queue, completion.queue_latency_nanos());+ }++ fn merge_from(&mut self, other: &Self) {+ self.service+ .add(&other.service)+ .expect("histograms share configuration");+ self.schedule+ .add(&other.schedule)+ .expect("histograms share configuration");+ self.queue+ .add(&other.queue)+ .expect("histograms share configuration");+ self.dispatch_lag+ .add(&other.dispatch_lag)+ .expect("histograms share configuration");+ }+}++fn new_histogram() -> Histogram<u64> {+ Histogram::new(HISTOGRAM_SIGNIFICANT_DIGITS).expect("valid benchmark histogram precision")+}++fn record_latency(histogram: &mut Histogram<u64>, nanos: u64) {+ histogram+ .record(nanos.max(1))+ .expect("auto-resizing histogram accepts all latency values");+}++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]+pub struct OperationCounts {+ pub scheduled: u64,+ pub completed: u64,+ pub achieved: u64,+ pub shed: u64,+ pub closed: u64,+ pub errors: u64,+ pub retry_affected: u64,+ pub deadlock_affected: u64,+ pub retry_attempts: u64,+ pub deadlock_attempts: u64,+}++impl OperationCounts {+ fn merge_from(&mut self, other: Self) {+ self.scheduled = self.scheduled.saturating_add(other.scheduled);+ self.completed = self.completed.saturating_add(other.completed);+ self.achieved = self.achieved.saturating_add(other.achieved);+ self.shed = self.shed.saturating_add(other.shed);+ self.closed = self.closed.saturating_add(other.closed);+ self.errors = self.errors.saturating_add(other.errors);+ self.retry_affected = self.retry_affected.saturating_add(other.retry_affected);+ self.deadlock_affected = self+ .deadlock_affected+ .saturating_add(other.deadlock_affected);+ self.retry_attempts = self.retry_attempts.saturating_add(other.retry_attempts);+ self.deadlock_attempts = self+ .deadlock_attempts+ .saturating_add(other.deadlock_attempts);+ }++ fn record_dispatch(&mut self, dispatch: DispatchRecord) {+ self.scheduled = self.scheduled.saturating_add(1);+ match dispatch.outcome {+ DispatchOutcome::Enqueued => {}+ DispatchOutcome::Shed => self.shed = self.shed.saturating_add(1),+ DispatchOutcome::Closed => self.closed = self.closed.saturating_add(1),+ }+ }++ fn record_completion(&mut self, completion: &CompletionRecord) {+ self.completed = self.completed.saturating_add(1);+ match completion.outcome {+ CompletionOutcome::Success => self.achieved = self.achieved.saturating_add(1),+ CompletionOutcome::Error { .. } => self.errors = self.errors.saturating_add(1),+ }+ if completion.retry_affected {+ self.retry_affected = self.retry_affected.saturating_add(1);+ }+ if completion.deadlock_affected {+ self.deadlock_affected = self.deadlock_affected.saturating_add(1);+ }+ self.retry_attempts = self+ .retry_attempts+ .saturating_add(u64::from(completion.retry_attempts));+ self.deadlock_attempts = self+ .deadlock_attempts+ .saturating_add(u64::from(completion.deadlock_attempts));+ }+}++#[derive(Debug)]+struct ClassAccumulator {+ counts: OperationCounts,+ latencies: LatencyHistograms,+}++impl ClassAccumulator {+ fn new() -> Self {+ Self {+ counts: OperationCounts::default(),+ latencies: LatencyHistograms::new(),+ }+ }++ fn record_dispatch(&mut self, dispatch: DispatchRecord) {+ self.counts.record_dispatch(dispatch);+ record_latency(+ &mut self.latencies.dispatch_lag,+ dispatch.dispatch_lag_nanos(),+ );+ }++ fn record_completion(&mut self, completion: &CompletionRecord) {+ self.counts.record_completion(completion);+ self.latencies.record(completion);+ }++ fn merge_from(&mut self, other: &Self) {+ self.counts.merge_from(other.counts);+ self.latencies.merge_from(&other.latencies);+ }++ fn snapshot(&self, class: OpClass) -> ClassMetrics {+ ClassMetrics {+ class,+ counts: self.counts,+ service: LatencySummary::from_histogram(&self.latencies.service),+ schedule: LatencySummary::from_histogram(&self.latencies.schedule),+ queue: LatencySummary::from_histogram(&self.latencies.queue),+ dispatch_lag: LatencySummary::from_histogram(&self.latencies.dispatch_lag),+ }+ }+}++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]+pub struct LatencySummary {+ pub count: u64,+ pub min_nanos: u64,+ pub p50_nanos: u64,+ pub p95_nanos: u64,+ pub p99_nanos: u64,+ pub max_nanos: u64,+}++impl LatencySummary {+ fn from_histogram(histogram: &Histogram<u64>) -> Self {+ if histogram.is_empty() {+ return Self::default();+ }+ Self {+ count: histogram.len(),+ min_nanos: histogram.min(),+ p50_nanos: histogram.value_at_quantile(0.50),+ p95_nanos: histogram.value_at_quantile(0.95),+ p99_nanos: histogram.value_at_quantile(0.99),+ max_nanos: histogram.max(),+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+pub struct ClassMetrics {+ pub class: OpClass,+ pub counts: OperationCounts,+ pub service: LatencySummary,+ pub schedule: LatencySummary,+ pub queue: LatencySummary,+ pub dispatch_lag: LatencySummary,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct IntervalRecord {+ pub record_type: &'static str,+ pub phase_id: PhaseId,+ pub interval_index: u64,+ pub started_at_nanos: u64,+ pub ended_at_nanos: u64,+ pub classes: [ClassMetrics; OpClass::COUNT],+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct PhaseSummaryRecord {+ pub record_type: &'static str,+ pub phase_id: PhaseId,+ pub duration_nanos: u64,+ pub drain_duration_nanos: u64,+ pub post_deadline_duration_nanos: u64,+ pub deadline_counts: [OperationCounts; OpClass::COUNT],+ pub classes: [ClassMetrics; OpClass::COUNT],+}++#[derive(Debug)]+pub struct PhaseCollector {+ phase_id: PhaseId,+ interval_index: u64,+ interval_started_at_nanos: u64,+ interval: [ClassAccumulator; OpClass::COUNT],+ totals: [ClassAccumulator; OpClass::COUNT],+ workload_deadline_nanos: u64,+ deadline_counts: [OperationCounts; OpClass::COUNT],+}++impl PhaseCollector {+ pub fn new(phase_id: PhaseId) -> Self {+ Self::with_deadline(phase_id, u64::MAX)+ }++ pub fn with_deadline(phase_id: PhaseId, workload_deadline_nanos: u64) -> Self {+ Self {+ phase_id,+ interval_index: 0,+ interval_started_at_nanos: 0,+ interval: array::from_fn(|_| ClassAccumulator::new()),+ totals: array::from_fn(|_| ClassAccumulator::new()),+ workload_deadline_nanos,+ deadline_counts: [OperationCounts::default(); OpClass::COUNT],+ }+ }++ pub fn record_dispatch(&mut self, dispatch: DispatchRecord) -> Result<(), CollectorError> {+ self.ensure_phase(dispatch.scheduled_at().phase_id())?;+ self.interval[dispatch.class.index()].record_dispatch(dispatch);+ if dispatch.scheduled_at().as_nanos() <= self.workload_deadline_nanos {+ self.deadline_counts[dispatch.class.index()].record_dispatch(dispatch);+ }+ Ok(())+ }++ pub fn record_completion(+ &mut self,+ completion: &CompletionRecord,+ ) -> Result<(), CollectorError> {+ self.ensure_phase(completion.timestamps.scheduled_at().phase_id())?;+ self.interval[completion.class.index()].record_completion(completion);+ if completion.timestamps.completed_at().as_nanos() <= self.workload_deadline_nanos {+ self.deadline_counts[completion.class.index()].record_completion(completion);+ }+ Ok(())+ }++ pub fn finish_interval(&mut self, ended_at_nanos: u64) -> IntervalRecord {+ let completed = std::mem::replace(+ &mut self.interval,+ array::from_fn(|_| ClassAccumulator::new()),+ );+ for (total, interval) in self.totals.iter_mut().zip(&completed) {+ total.merge_from(interval);+ }+ let record = IntervalRecord {+ record_type: "interval",+ phase_id: self.phase_id,+ interval_index: self.interval_index,+ started_at_nanos: self.interval_started_at_nanos,+ ended_at_nanos,+ classes: class_snapshots(&completed),+ };+ self.interval_index = self.interval_index.saturating_add(1);+ self.interval_started_at_nanos = ended_at_nanos;+ record+ }++ pub fn finish_phase(+ mut self,+ duration_nanos: u64,+ drain_duration_nanos: u64,+ post_deadline_duration_nanos: u64,+ ) -> PhaseSummaryRecord {+ for (total, interval) in self.totals.iter_mut().zip(&self.interval) {+ total.merge_from(interval);+ }+ PhaseSummaryRecord {+ record_type: "phase_summary",+ phase_id: self.phase_id,+ duration_nanos,+ drain_duration_nanos,+ post_deadline_duration_nanos,+ deadline_counts: self.deadline_counts,+ classes: class_snapshots(&self.totals),+ }+ }++ fn ensure_phase(&self, phase_id: PhaseId) -> Result<(), CollectorError> {+ if phase_id == self.phase_id {+ return Ok(());+ }+ Err(CollectorError::PhaseMismatch(PhaseMismatch {+ expected: self.phase_id,+ actual: phase_id,+ }))+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CollectorError {+ PhaseMismatch(PhaseMismatch),+}++impl std::fmt::Display for CollectorError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::PhaseMismatch(error) => error.fmt(formatter),+ }+ }+}++impl std::error::Error for CollectorError {}++fn class_snapshots(+ accumulators: &[ClassAccumulator; OpClass::COUNT],+) -> [ClassMetrics; OpClass::COUNT] {+ array::from_fn(|index| accumulators[index].snapshot(OpClass::ALL[index]))+}++#[derive(Debug)]+pub struct JsonlSink {+ writer: BufWriter<File>,+}++impl JsonlSink {+ pub fn create(path: impl AsRef<Path>) -> std::io::Result<Self> {+ let file = File::create(path)?;+ Ok(Self {+ writer: BufWriter::new(file),+ })+ }++ pub fn write<T: Serialize>(&mut self, record: &T) -> anyhow::Result<()> {+ serde_json::to_writer(&mut self.writer, record)?;+ self.writer.write_all(b"\n")?;+ Ok(())+ }++ pub fn flush(&mut self) -> std::io::Result<()> {+ self.writer.flush()+ }+}++#[cfg(test)]+mod tests {+ use std::num::NonZeroUsize;++ use super::*;+ use crate::benchmark::ops::{+ CanonicalReadPayload, CompletionTimestamps, NanosSincePhaseStart, OpDescriptor, OpPayload,+ OperationId, ReadExpectation,+ };+ use crate::benchmark::scheduler::BoundedDispatcher;++ fn at(nanos: u64) -> NanosSincePhaseStart {+ NanosSincePhaseStart::from_nanos(PhaseId::new(1), nanos)+ }++ fn completion(retry_attempts: u32, deadlock_attempts: u32) -> CompletionRecord {+ CompletionRecord {+ operation_id: OperationId(1),+ class: OpClass::CanonicalRead,+ timestamps: CompletionTimestamps::try_new(at(10), at(12), at(15), at(20))+ .expect("ordered timestamps"),+ outcome: CompletionOutcome::Success,+ retry_affected: retry_attempts > 0,+ deadlock_affected: deadlock_attempts > 0,+ retry_attempts,+ deadlock_attempts,+ }+ }++ #[test]+ fn interval_flush_resets_interval_and_preserves_phase_totals() {+ let mut collector = PhaseCollector::new(PhaseId::new(1));+ let (mut dispatcher, _receiver) =+ BoundedDispatcher::channel(NonZeroUsize::new(1).expect("nonzero"));+ let dispatch = dispatcher+ .try_dispatch_at(+ OpDescriptor::new(+ OperationId(2),+ at(10),+ OpPayload::CanonicalRead(CanonicalReadPayload {+ team_id: 1,+ distinct_id: "[email protected]".into(),+ expectation: ReadExpectation::Hit,+ }),+ ),+ at(12),+ )+ .expect("valid dispatch");+ collector.record_dispatch(dispatch).expect("matching phase");+ collector+ .record_completion(&completion(2, 1))+ .expect("matching phase");+ let mut failed = completion(0, 0);+ failed.operation_id = OperationId(4);+ failed.outcome = CompletionOutcome::Error {+ message: "terminal".into(),+ };+ collector+ .record_completion(&failed)+ .expect("matching phase");+ let other_phase = NanosSincePhaseStart::from_nanos(PhaseId::new(2), 20);+ let mixed_phase = CompletionRecord {+ operation_id: OperationId(3),+ class: OpClass::CanonicalRead,+ timestamps: CompletionTimestamps::try_new(+ other_phase,+ other_phase,+ other_phase,+ other_phase,+ )+ .expect("ordered timestamps"),+ outcome: CompletionOutcome::Success,+ retry_affected: false,+ deadlock_affected: false,+ retry_attempts: 0,+ deadlock_attempts: 0,+ };+ assert!(matches!(+ collector.record_completion(&mixed_phase),+ Err(CollectorError::PhaseMismatch(_))+ ));++ let first = collector.finish_interval(10_000_000_000);+ let second = collector.finish_interval(20_000_000_000);+ let summary = collector.finish_phase(20_000_000_000, 0, 0);+ let class = OpClass::CanonicalRead.index();++ assert_eq!(first.classes[class].counts.achieved, 1);+ assert_eq!(first.classes[class].counts.completed, 2);+ assert_eq!(first.classes[class].counts.scheduled, 1);+ assert_eq!(first.classes[class].counts.errors, 1);+ assert_eq!(first.classes[class].counts.retry_attempts, 2);+ assert_eq!(first.classes[class].counts.deadlock_affected, 1);+ assert_eq!(first.classes[class].dispatch_lag.count, 1);+ assert_eq!(second.classes[class].counts.achieved, 0);+ assert_eq!(summary.classes[class], first.classes[class]);+ assert_eq!(summary.deadline_counts[class].achieved, 1);+ }++ #[test]+ fn deadline_counts_exclude_completions_from_the_drain_window() {+ let mut collector = PhaseCollector::with_deadline(PhaseId::new(1), 20);+ let (mut dispatcher, _receiver) =+ BoundedDispatcher::channel(NonZeroUsize::new(1).expect("nonzero"));+ let dispatch = dispatcher+ .try_dispatch_at(+ OpDescriptor::new(+ OperationId(2),+ at(10),+ OpPayload::CanonicalRead(CanonicalReadPayload {+ team_id: 1,+ distinct_id: "[email protected]".into(),+ expectation: ReadExpectation::Hit,+ }),+ ),+ at(12),+ )+ .expect("valid dispatch");+ collector.record_dispatch(dispatch).expect("matching phase");+ let late_completion = CompletionRecord {+ operation_id: OperationId(2),+ class: OpClass::CanonicalRead,+ timestamps: CompletionTimestamps::try_new(at(10), at(12), at(15), at(25))+ .expect("ordered timestamps"),+ outcome: CompletionOutcome::Success,+ retry_affected: false,+ deadlock_affected: false,+ retry_attempts: 0,+ deadlock_attempts: 0,+ };+ collector+ .record_completion(&late_completion)+ .expect("matching phase");++ let summary = collector.finish_phase(20, 5, 7);+ let class = OpClass::CanonicalRead.index();+ assert_eq!(summary.deadline_counts[class].scheduled, 1);+ assert_eq!(summary.deadline_counts[class].completed, 0);+ assert_eq!(summary.deadline_counts[class].achieved, 0);+ assert_eq!(summary.classes[class].counts.achieved, 1);+ assert_eq!(summary.drain_duration_nanos, 5);+ assert_eq!(summary.post_deadline_duration_nanos, 7);+ }+}diff --git a/rust/flags-consumer/src/benchmark/data_gen.rs b/rust/flags-consumer/src/benchmark/data_gen.rsdeleted file mode 100644index 36081e436ad4..000000000000--- a/rust/flags-consumer/src/benchmark/data_gen.rs+++ /dev/null@@ -1,178 +0,0 @@-use std::collections::HashMap;-use std::sync::Arc;--use rand::Rng;-use serde_json::Value;-use uuid::Uuid;--use super::BenchmarkArgs;--pub struct PersonRegistry {- pub persons: Vec<(i32, Uuid)>,- pub distinct_ids: Vec<(i32, Uuid, String)>,-}--pub struct BenchmarkData {- pub persons: Arc<Vec<(i32, Uuid)>>,- pub distinct_ids: Arc<Vec<(i32, Uuid, String)>>,- /// team_id -> indices into `distinct_ids` for the first distinct_id per person.- pub team_person_indices: Arc<HashMap<i32, Vec<usize>>>,- /// Weighted CDF for team selection: (cumulative_probability, team_id).- pub team_cdf: Arc<Vec<(f64, i32)>>,-}--pub fn build_benchmark_data(registry: PersonRegistry) -> BenchmarkData {- let team_person_indices = build_team_person_indices(®istry.distinct_ids);- let team_cdf = build_team_cdf(&team_person_indices);-- BenchmarkData {- persons: Arc::new(registry.persons),- distinct_ids: Arc::new(registry.distinct_ids),- team_person_indices: Arc::new(team_person_indices),- team_cdf: Arc::new(team_cdf),- }-}--fn build_team_person_indices(distinct_ids: &[(i32, Uuid, String)]) -> HashMap<i32, Vec<usize>> {- let mut seen_persons = std::collections::HashSet::new();- let mut map: HashMap<i32, Vec<usize>> = HashMap::new();-- for (idx, (team_id, person_uuid, _)) in distinct_ids.iter().enumerate() {- if seen_persons.insert((*team_id, *person_uuid)) {- map.entry(*team_id).or_default().push(idx);- }- }-- map-}--/// Only teams with >= 2 persons are included since merges require two distinct persons.-fn build_team_cdf(team_person_indices: &HashMap<i32, Vec<usize>>) -> Vec<(f64, i32)> {- let mut entries: Vec<(i32, usize)> = team_person_indices- .iter()- .filter(|(_, v)| v.len() >= 2)- .map(|(&tid, v)| (tid, v.len()))- .collect();-- entries.sort_by_key(|(tid, _)| *tid);-- let eligible_total: f64 = entries.iter().map(|(_, count)| *count as f64).sum();- if eligible_total == 0.0 {- return Vec::new();- }-- let mut cumulative = 0.0;- let mut cdf = Vec::with_capacity(entries.len());-- for (tid, count) in &entries {- cumulative += *count as f64 / eligible_total;- cdf.push((cumulative, *tid));- }-- if let Some(last) = cdf.last_mut() {- last.0 = 1.0;- }-- cdf-}--pub fn select_team_weighted(cdf: &[(f64, i32)], rng: &mut impl Rng) -> Option<i32> {- if cdf.is_empty() {- return None;- }- let r: f64 = rng.gen();- let idx = cdf.partition_point(|(cum, _)| *cum < r);- Some(cdf[idx.min(cdf.len() - 1)].1)-}--/// Generate a JSONB properties object padded to approximately `target_bytes`.-pub fn generate_properties(rng: &mut impl Rng, target_bytes: usize) -> Value {- const KEYS: &[&str] = &[- "$browser",- "$os",- "$initial_referrer",- "$initial_referring_domain",- "$geoip_city_name",- "$geoip_country_code",- "$geoip_time_zone",- "email",- "name",- "plan",- "company",- "role",- "signup_date",- "last_login",- ];-- let mut obj = serde_json::Map::with_capacity(KEYS.len() + 1);-- for &key in KEYS {- let val_len: usize = rng.gen_range(4..30);- let val: String = (0..val_len)- .map(|_| rng.gen_range(b'a'..=b'z') as char)- .collect();- obj.insert(key.to_string(), Value::String(val));- }-- let current = serde_json::to_string(&Value::Object(obj.clone()))- .unwrap()- .len();- if current < target_bytes {- let padding_needed = target_bytes - current;- let pad_val_len = padding_needed.saturating_sub(12);- let pad: String = (0..pad_val_len)- .map(|_| rng.gen_range(b'a'..=b'z') as char)- .collect();- obj.insert("_pad".to_string(), Value::String(pad));- }-- Value::Object(obj)-}--/// Zipf-weighted team sizes (weight = 1/rank^1.5) so a few teams dominate.-/// 86% of persons get 1 distinct_id, 14% get 2 (matching the measured ~1.14 ratio).-pub fn generate_person_registry(args: &BenchmarkArgs, rng: &mut impl Rng) -> PersonRegistry {- let scale = args.scale as usize;- let teams = args.teams;-- let weights: Vec<f64> = (1..=teams).map(|i| 1.0 / (i as f64).powf(1.5)).collect();- let total_weight: f64 = weights.iter().sum();-- let mut team_counts: Vec<usize> = weights- .iter()- .map(|w| ((w / total_weight) * scale as f64).round() as usize)- .collect();-- let total: usize = team_counts.iter().sum();- match total.cmp(&scale) {- std::cmp::Ordering::Greater => team_counts[0] -= total - scale,- std::cmp::Ordering::Less => team_counts[0] += scale - total,- std::cmp::Ordering::Equal => {}- }-- let mut persons = Vec::with_capacity(scale);- let mut distinct_ids = Vec::with_capacity((scale as f64 * 1.14) as usize);-- for (team_idx, &count) in team_counts.iter().enumerate() {- let team_id = (team_idx as i32) + 1;- for _ in 0..count {- let person_uuid = Uuid::new_v4();- persons.push((team_id, person_uuid));-- let mut bytes = [0u8; 16];- rng.fill(&mut bytes);- distinct_ids.push((team_id, person_uuid, Uuid::from_bytes(bytes).to_string()));-- if rng.gen_ratio(14, 100) {- let mut bytes2 = [0u8; 16];- rng.fill(&mut bytes2);- distinct_ids.push((team_id, person_uuid, Uuid::from_bytes(bytes2).to_string()));- }- }- }-- PersonRegistry {- persons,- distinct_ids,- }-}diff --git a/rust/flags-consumer/src/benchmark/executor.rs b/rust/flags-consumer/src/benchmark/executor.rsnew file mode 100644index 000000000000..c6971dc84bde--- /dev/null+++ b/rust/flags-consumer/src/benchmark/executor.rs@@ -0,0 +1,1198 @@+use std::collections::btree_map::Entry;+use std::collections::BTreeMap;+use std::future::Future;+use std::num::NonZeroUsize;+use std::sync::Arc;+use std::time::Duration;++use anyhow::Context;+use common_database::is_transient_error;+use tokio::sync::{mpsc, Mutex};+use tokio::task::JoinHandle;+use tokio_util::sync::CancellationToken;++use crate::storage::postgres::PostgresStorage;+use crate::storage::types::{DistinctIdAssignmentData, PersonDeletionData, PersonUpdateData};++use super::ops::{+ CompletionOutcome, CompletionRecord, DispatchedOperation, FullMergePayload, OpClass, OpPayload,+ ReadExpectation,+};+use super::scheduler::{BoundedDispatcher, PhaseClock};++const DEFAULT_READ_CAPACITY: usize = 28_948;+const DEFAULT_MERGE_CAPACITY: usize = 110;+const DEFAULT_PERSON_CAPACITY: usize = 11_576;+const DEFAULT_DISTINCT_ID_CAPACITY: usize = 7_188;++#[derive(Debug, Clone)]+pub struct ExecutorConfig {+ pub read_workers: NonZeroUsize,+ pub merge_workers: NonZeroUsize,+ pub person_batch_workers: NonZeroUsize,+ pub distinct_id_batch_workers: NonZeroUsize,+ pub batch_size: NonZeroUsize,+ pub batch_flush: Duration,+ pub batch_queue_capacity: NonZeroUsize,+ pub completion_queue_capacity: NonZeroUsize,+ pub ingress_capacities: IngressCapacities,+ pub retry: RetryConfig,+}++impl Default for ExecutorConfig {+ fn default() -> Self {+ Self {+ read_workers: nonzero(64),+ merge_workers: nonzero(16),+ person_batch_workers: nonzero(8),+ distinct_id_batch_workers: nonzero(8),+ batch_size: nonzero(500),+ batch_flush: Duration::from_millis(100),+ batch_queue_capacity: nonzero(32),+ completion_queue_capacity: nonzero(50_000),+ ingress_capacities: IngressCapacities::default(),+ retry: RetryConfig::default(),+ }+ }+}++const fn nonzero(value: usize) -> NonZeroUsize {+ match NonZeroUsize::new(value) {+ Some(value) => value,+ None => panic!("executor constants are nonzero"),+ }+}++#[derive(Debug, Clone, Copy)]+pub struct IngressCapacities {+ pub person_upsert: NonZeroUsize,+ pub distinct_id_assignment: NonZeroUsize,+ pub merge: NonZeroUsize,+ pub canonical_read: NonZeroUsize,+}++impl Default for IngressCapacities {+ fn default() -> Self {+ Self {+ person_upsert: nonzero(DEFAULT_PERSON_CAPACITY),+ distinct_id_assignment: nonzero(DEFAULT_DISTINCT_ID_CAPACITY),+ merge: nonzero(DEFAULT_MERGE_CAPACITY),+ canonical_read: nonzero(DEFAULT_READ_CAPACITY),+ }+ }+}++#[derive(Debug, Clone, Copy)]+pub struct RetryConfig {+ pub max_retries: u32,+ pub backoff_base: Duration,+ pub attempt_timeout: Duration,+}++impl Default for RetryConfig {+ fn default() -> Self {+ Self {+ max_retries: 3,+ backoff_base: Duration::from_millis(50),+ attempt_timeout: Duration::from_secs(30),+ }+ }+}++#[derive(Debug)]+pub struct ExecutorIngress {+ dispatchers: [BoundedDispatcher; OpClass::COUNT],+}++impl ExecutorIngress {+ pub fn dispatcher_mut(&mut self, class: OpClass) -> &mut BoundedDispatcher {+ &mut self.dispatchers[class.index()]+ }++ pub fn shed_count(&self, class: OpClass) -> u64 {+ self.dispatchers[class.index()].shed_count()+ }++ pub fn into_dispatchers(self) -> ExecutorDispatchers {+ let [person_upserts, distinct_id_assignments, merges, canonical_reads] = self.dispatchers;+ ExecutorDispatchers {+ person_upserts,+ distinct_id_assignments,+ merges,+ canonical_reads,+ }+ }+}++#[derive(Debug)]+pub struct ExecutorDispatchers {+ pub person_upserts: BoundedDispatcher,+ pub distinct_id_assignments: BoundedDispatcher,+ pub merges: BoundedDispatcher,+ pub canonical_reads: BoundedDispatcher,+}++#[derive(Debug)]+pub struct ExecutorTasks {+ handles: Vec<JoinHandle<anyhow::Result<()>>>,+}++impl ExecutorTasks {+ pub async fn join(self) -> anyhow::Result<()> {+ let mut first_error = None;+ for handle in self.handles {+ match handle.await {+ Ok(Ok(())) => {}+ Ok(Err(error)) => {+ first_error.get_or_insert(error);+ }+ Err(error) => {+ first_error.get_or_insert_with(|| {+ anyhow::Error::new(error).context("benchmark executor task panicked")+ });+ }+ }+ }+ match first_error {+ Some(error) => Err(error),+ None => Ok(()),+ }+ }+}++#[derive(Debug)]+pub struct ExecutorRuntime {+ completion_receiver: mpsc::Receiver<CompletionRecord>,+ tasks: ExecutorTasks,+ cancellation: CancellationToken,+}++impl ExecutorRuntime {+ pub fn completion_receiver_mut(&mut self) -> &mut mpsc::Receiver<CompletionRecord> {+ &mut self.completion_receiver+ }++ pub fn is_cancelled(&self) -> bool {+ self.cancellation.is_cancelled()+ }++ pub fn cancellation_token(&self) -> CancellationToken {+ self.cancellation.clone()+ }++ /// Drains completions until the workers exit. Callers must have dropped every+ /// ingress or dispatcher handle first, otherwise the workers never see a close.+ pub async fn drain<F>(mut self, mut record_completion: F) -> anyhow::Result<()>+ where+ F: FnMut(CompletionRecord) -> anyhow::Result<()>,+ {+ let mut drain_error = None;+ while let Some(completion) = self.completion_receiver.recv().await {+ if let Err(error) = record_completion(completion) {+ drain_error.get_or_insert(error);+ }+ }+ let task_result = self.tasks.join().await;+ task_result?;+ match drain_error {+ Some(error) => Err(error).context("record drained benchmark completion"),+ None => Ok(()),+ }+ }+}++pub fn start(+ storage: Arc<PostgresStorage>,+ clock: PhaseClock,+ config: ExecutorConfig,+) -> (ExecutorIngress, ExecutorRuntime) {+ let (person_dispatcher, person_receiver) =+ BoundedDispatcher::channel(config.ingress_capacities.person_upsert);+ let (distinct_id_dispatcher, distinct_id_receiver) =+ BoundedDispatcher::channel(config.ingress_capacities.distinct_id_assignment);+ let (merge_dispatcher, merge_receiver) =+ BoundedDispatcher::channel(config.ingress_capacities.merge);+ let (read_dispatcher, read_receiver) =+ BoundedDispatcher::channel(config.ingress_capacities.canonical_read);+ let ingress = ExecutorIngress {+ dispatchers: [+ person_dispatcher,+ distinct_id_dispatcher,+ merge_dispatcher,+ read_dispatcher,+ ],+ };++ let (completion_sender, completion_receiver) =+ mpsc::channel(config.completion_queue_capacity.get());+ let cancellation = CancellationToken::new();+ let (person_batch_sender, person_batch_receiver) =+ mpsc::channel(config.batch_queue_capacity.get());+ let (distinct_id_batch_sender, distinct_id_batch_receiver) =+ mpsc::channel(config.batch_queue_capacity.get());+ let mut handles = vec![+ tokio::spawn(run_batcher(+ person_receiver,+ person_batch_sender,+ config.batch_size,+ config.batch_flush,+ cancellation.clone(),+ )),+ tokio::spawn(run_batcher(+ distinct_id_receiver,+ distinct_id_batch_sender,+ config.batch_size,+ config.batch_flush,+ cancellation.clone(),+ )),+ ];++ let context = WorkerContext {+ storage,+ completion_sender,+ clock,+ retry: config.retry,+ cancellation: cancellation.clone(),+ };++ let person_batches = Arc::new(Mutex::new(person_batch_receiver));+ for _ in 0..config.person_batch_workers.get() {+ handles.push(tokio::spawn(run_batch_worker(+ context.clone(),+ Arc::clone(&person_batches),+ dedupe_person_updates,+ async |storage: &PostgresStorage, updates| storage.batch_upsert_persons(updates).await,+ )));+ }+ let distinct_id_batches = Arc::new(Mutex::new(distinct_id_batch_receiver));+ for _ in 0..config.distinct_id_batch_workers.get() {+ handles.push(tokio::spawn(run_batch_worker(+ context.clone(),+ Arc::clone(&distinct_id_batches),+ dedupe_distinct_id_assignments,+ async |storage: &PostgresStorage, assignments| {+ storage.batch_upsert_distinct_ids(assignments).await+ },+ )));+ }+ let merge_receiver = Arc::new(Mutex::new(merge_receiver));+ for _ in 0..config.merge_workers.get() {+ handles.push(tokio::spawn(run_merge_worker(+ context.clone(),+ Arc::clone(&merge_receiver),+ )));+ }+ let read_receiver = Arc::new(Mutex::new(read_receiver));+ for _ in 0..config.read_workers.get() {+ handles.push(tokio::spawn(run_read_worker(+ context.clone(),+ Arc::clone(&read_receiver),+ )));+ }+ drop(context);++ (+ ingress,+ ExecutorRuntime {+ completion_receiver,+ tasks: ExecutorTasks { handles },+ cancellation,+ },+ )+}++/// Plumbing every worker needs, so worker signatures carry only their own inputs.+#[derive(Clone)]+struct WorkerContext {+ storage: Arc<PostgresStorage>,+ completion_sender: mpsc::Sender<CompletionRecord>,+ clock: PhaseClock,+ retry: RetryConfig,+ cancellation: CancellationToken,+}++async fn run_batcher(+ mut receiver: mpsc::Receiver<DispatchedOperation>,+ sender: mpsc::Sender<Vec<DispatchedOperation>>,+ batch_size: NonZeroUsize,+ flush_after: Duration,+ cancellation: CancellationToken,+) -> anyhow::Result<()> {+ loop {+ let first = tokio::select! {+ biased;+ () = cancellation.cancelled() => break,+ operation = receiver.recv() => match operation {+ Some(operation) => operation,+ None => break,+ },+ };+ let mut batch = Vec::with_capacity(batch_size.get());+ batch.push(first);+ let deadline = tokio::time::Instant::now() + flush_after;+ while batch.len() < batch_size.get() {+ tokio::select! {+ biased;+ () = cancellation.cancelled() => return Ok(()),+ next = receiver.recv() => match next {+ Some(operation) => batch.push(operation),+ None => break,+ },+ () = tokio::time::sleep_until(deadline) => break,+ }+ }+ tokio::select! {+ biased;+ () = cancellation.cancelled() => break,+ result = sender.send(batch) => if result.is_err() {+ break;+ },+ }+ }+ Ok(())+}++async fn receive_shared<T>(+ receiver: &Mutex<mpsc::Receiver<T>>,+ cancellation: &CancellationToken,+) -> Option<T> {+ tokio::select! {+ biased;+ () = cancellation.cancelled() => None,+ item = async { receiver.lock().await.recv().await } => item,+ }+}++/// Shared batch-worker loop. `prepare` collapses a dispatched batch into the write+/// payload (dedupe rules differ per class) and `execute` issues the storage call.+async fn run_batch_worker<T, Prepare, Execute>(+ context: WorkerContext,+ receiver: Arc<Mutex<mpsc::Receiver<Vec<DispatchedOperation>>>>,+ prepare: Prepare,+ execute: Execute,+) -> anyhow::Result<()>+where+ Prepare: Fn(&[DispatchedOperation]) -> Result<Vec<T>, BatchPayloadError>,+ Execute: AsyncFn(&PostgresStorage, &[T]) -> Result<u64, sqlx::Error>,+{+ let WorkerContext {+ storage,+ completion_sender,+ clock,+ retry,+ cancellation,+ } = context;+ while let Some(batch) = receive_shared(&receiver, &cancellation).await {+ let payload = prepare(&batch);+ let started_at = clock.now()?;+ let execution = match payload {+ Ok(payload) => with_retry(retry, &cancellation, || execute(&storage, &payload)).await,+ Err(error) => RetryResult::<u64>::terminal(error.to_string()),+ };+ if execution.cancelled {+ return Ok(());+ }+ let terminal_error = execution.error.clone();+ let emission =+ emit_batch_completions(&batch, started_at, &execution, &clock, &completion_sender)+ .await;+ cancel_on_error(&emission, &cancellation);+ emission?;+ abort_after_terminal(terminal_error.as_deref(), &cancellation)?;+ }+ Ok(())+}++async fn run_read_worker(+ context: WorkerContext,+ receiver: Arc<Mutex<mpsc::Receiver<DispatchedOperation>>>,+) -> anyhow::Result<()> {+ let WorkerContext {+ storage,+ completion_sender,+ clock,+ retry,+ cancellation,+ } = context;+ while let Some(operation) = receive_shared(&receiver, &cancellation).await {+ let prepared = match &operation.descriptor().payload {+ OpPayload::CanonicalRead(payload) => Ok(payload.clone()),+ payload => Err(format!(+ "read worker received {:?} operation",+ payload.class()+ )),+ };+ let started_at = clock.now()?;+ let execution = match prepared {+ Ok(payload) => {+ with_retry(retry, &cancellation, || {+ storage.get_person_by_distinct_id(payload.team_id, &payload.distinct_id)+ })+ .await+ }+ Err(error) => RetryResult::terminal(error),+ };+ if execution.cancelled {+ return Ok(());+ }+ let mut terminal_error = execution.error.clone();+ if terminal_error.is_none() {+ let payload = match &operation.descriptor().payload {+ OpPayload::CanonicalRead(payload) => payload,+ _ => unreachable!("prepared canonical read"),+ };+ let found = execution+ .value+ .as_ref()+ .expect("successful retry result has a value")+ .is_some();+ terminal_error = validate_read_expectation(&payload.expectation, found).err();+ }+ let emission = emit_completion(+ &operation,+ started_at,+ terminal_error.as_deref(),+ execution.stats,+ &clock,+ &completion_sender,+ )+ .await;+ cancel_on_error(&emission, &cancellation);+ emission?;+ abort_after_terminal(terminal_error.as_deref(), &cancellation)?;+ }+ Ok(())+}++async fn run_merge_worker(+ context: WorkerContext,+ receiver: Arc<Mutex<mpsc::Receiver<DispatchedOperation>>>,+) -> anyhow::Result<()> {+ let WorkerContext {+ storage,+ completion_sender,+ clock,+ retry,+ cancellation,+ } = context;+ while let Some(operation) = receive_shared(&receiver, &cancellation).await {+ let prepared = match &operation.descriptor().payload {+ OpPayload::FullMerge(payload) => Ok(prepare_merge(payload)),+ payload => Err(format!(+ "merge worker received {:?} operation",+ payload.class()+ )),+ };+ let started_at = clock.now()?;+ let execution = match prepared {+ Ok(prepared) => execute_merge(&storage, &prepared, retry, &cancellation).await,+ Err(error) => RetryResult::<u64>::terminal(error),+ };+ if execution.cancelled {+ return Ok(());+ }+ let terminal_error = execution.error.clone();+ let emission = emit_completion(+ &operation,+ started_at,+ execution.error.as_deref(),+ execution.stats,+ &clock,+ &completion_sender,+ )+ .await;+ cancel_on_error(&emission, &cancellation);+ emission?;+ abort_after_terminal(terminal_error.as_deref(), &cancellation)?;+ }+ Ok(())+}++async fn execute_merge(+ storage: &PostgresStorage,+ merge: &PreparedMerge,+ retry: RetryConfig,+ cancellation: &CancellationToken,+) -> RetryResult<u64> {+ // Production commits these version-guarded batches independently as well;+ // replay converges a partial merge after a later step fails.+ let mut result = with_retry(retry, cancellation, || {+ storage.batch_upsert_distinct_ids(&merge.assignments)+ })+ .await;+ if result.error.is_none() {+ let next = with_retry(retry, cancellation, || {+ storage.batch_upsert_persons(&merge.target)+ })+ .await;+ result.merge_from(next);+ }+ if result.error.is_none() && !result.cancelled {+ let next = with_retry(retry, cancellation, || {+ storage.batch_delete_persons(&merge.source)+ })+ .await;+ result.merge_from(next);+ }+ result+}++#[derive(Debug)]+struct PreparedMerge {+ assignments: Vec<DistinctIdAssignmentData>,+ target: [PersonUpdateData; 1],+ source: [PersonDeletionData; 1],+}++fn prepare_merge(payload: &FullMergePayload) -> PreparedMerge {+ let mut assignments = payload+ .distinct_id_moves+ .iter()+ .map(|distinct_id| DistinctIdAssignmentData {+ team_id: payload.team_id,+ person_uuid: payload.target_person_uuid,+ distinct_id: distinct_id.distinct_id.clone(),+ version: distinct_id.version,+ })+ .collect::<Vec<_>>();+ assignments.sort_by(|left, right| {+ (left.team_id, left.distinct_id.as_ref()).cmp(&(right.team_id, right.distinct_id.as_ref()))+ });+ PreparedMerge {+ assignments,+ target: [PersonUpdateData {+ team_id: payload.team_id,+ person_uuid: payload.target_person_uuid,+ properties: payload.target_properties.clone(),+ version: payload.target_version,+ }],+ source: [PersonDeletionData {+ team_id: payload.team_id,+ person_uuid: payload.source_person_uuid,+ version: payload.source_tombstone_version,+ }],+ }+}++fn validate_read_expectation(expectation: &ReadExpectation, found: bool) -> Result<(), String> {+ match (expectation, found) {+ (ReadExpectation::Hit, true) | (ReadExpectation::Miss, false) => Ok(()),+ (ReadExpectation::Hit, false) => {+ Err("canonical read expected a hit but returned no person".to_owned())+ }+ (ReadExpectation::Miss, true) => {+ Err("canonical read expected a miss but returned a person".to_owned())+ }+ }+}++fn abort_after_terminal(+ terminal_error: Option<&str>,+ cancellation: &CancellationToken,+) -> anyhow::Result<()> {+ let Some(error) = terminal_error else {+ return Ok(());+ };+ cancellation.cancel();+ Err(anyhow::anyhow!(+ "terminal benchmark operation failure: {error}"+ ))+}++fn cancel_on_error<T>(result: &anyhow::Result<T>, cancellation: &CancellationToken) {+ if result.is_err() {+ cancellation.cancel();+ }+}++#[derive(Debug, Clone, Copy, Default)]+struct RetryStats {+ retries: u32,+ deadlocks: u32,+}++impl RetryStats {+ fn merge(&mut self, other: Self) {+ self.retries = self.retries.saturating_add(other.retries);+ self.deadlocks = self.deadlocks.saturating_add(other.deadlocks);+ }+}++#[derive(Debug)]+struct RetryResult<T> {+ value: Option<T>,+ error: Option<String>,+ stats: RetryStats,+ cancelled: bool,+}++impl<T> RetryResult<T> {+ fn terminal(error: String) -> Self {+ Self {+ value: None,+ error: Some(error),+ stats: RetryStats::default(),+ cancelled: false,+ }+ }++ fn cancelled(stats: RetryStats) -> Self {+ Self {+ value: None,+ error: None,+ stats,+ cancelled: true,+ }+ }++ fn merge_from<U>(&mut self, other: RetryResult<U>) {+ self.stats.merge(other.stats);+ self.cancelled |= other.cancelled;+ if self.error.is_none() {+ self.error = other.error;+ }+ }+}++async fn with_retry<T, F, Fut>(+ retry: RetryConfig,+ cancellation: &CancellationToken,+ mut operation: F,+) -> RetryResult<T>+where+ F: FnMut() -> Fut,+ Fut: Future<Output = Result<T, sqlx::Error>>,+{+ let mut stats = RetryStats::default();+ loop {+ let result = tokio::select! {+ biased;+ () = cancellation.cancelled() => return RetryResult::cancelled(stats),+ result = tokio::time::timeout(retry.attempt_timeout, operation()) => result,+ };+ let result = match result {+ Ok(result) => result,+ Err(_) => {+ return RetryResult {+ value: None,+ error: Some(format!(+ "database attempt timed out after {:.1}s",+ retry.attempt_timeout.as_secs_f64()+ )),+ stats,+ cancelled: false,+ }+ }+ };+ match result {+ Ok(value) => {+ return RetryResult {+ value: Some(value),+ error: None,+ stats,+ cancelled: false,+ }+ }+ Err(error) => {+ if is_deadlock(&error) {+ stats.deadlocks = stats.deadlocks.saturating_add(1);+ }+ if !is_transient_error(&error) || stats.retries >= retry.max_retries {+ return RetryResult {+ value: None,+ error: Some(error.to_string()),+ stats,+ cancelled: false,+ };+ }+ let multiplier = 1u32 << stats.retries.min(31);+ stats.retries = stats.retries.saturating_add(1);+ tokio::select! {+ biased;+ () = cancellation.cancelled() => return RetryResult::cancelled(stats),+ () = tokio::time::sleep(retry.backoff_base.saturating_mul(multiplier)) => {}+ }+ }+ }+ }+}++fn is_deadlock(error: &sqlx::Error) -> bool {+ match error {+ sqlx::Error::Database(database_error) => {+ database_error+ .code()+ .is_some_and(|code| code.as_ref() == "40P01")+ || database_error.message().to_lowercase().contains("deadlock")+ }+ _ => false,+ }+}++async fn emit_batch_completions(+ batch: &[DispatchedOperation],+ started_at: super::ops::NanosSincePhaseStart,+ execution: &RetryResult<u64>,+ clock: &PhaseClock,+ sender: &mpsc::Sender<CompletionRecord>,+) -> anyhow::Result<()> {+ let completed_at = clock.now()?;+ for (index, operation) in batch.iter().enumerate() {+ let attributed_stats = if index == 0 {+ execution.stats+ } else {+ RetryStats::default()+ };+ let completion = build_completion(+ operation,+ started_at,+ completed_at,+ execution.error.as_deref(),+ execution.stats,+ attributed_stats,+ )?;+ sender+ .send(completion)+ .await+ .map_err(|_| anyhow::anyhow!("benchmark completion collector closed"))?;+ }+ Ok(())+}++async fn emit_completion(+ operation: &DispatchedOperation,+ started_at: super::ops::NanosSincePhaseStart,+ error: Option<&str>,+ stats: RetryStats,+ clock: &PhaseClock,+ sender: &mpsc::Sender<CompletionRecord>,+) -> anyhow::Result<()> {+ let completed_at = clock.now()?;+ let completion = build_completion(operation, started_at, completed_at, error, stats, stats)?;+ sender+ .send(completion)+ .await+ .map_err(|_| anyhow::anyhow!("benchmark completion collector closed"))+}++fn build_completion(+ operation: &DispatchedOperation,+ started_at: super::ops::NanosSincePhaseStart,+ completed_at: super::ops::NanosSincePhaseStart,+ error: Option<&str>,+ affected_stats: RetryStats,+ attributed_stats: RetryStats,+) -> anyhow::Result<CompletionRecord> {+ let timestamps = operation.completion_timestamps(started_at, completed_at)?;+ let outcome = match error {+ Some(message) => CompletionOutcome::Error {+ message: message.into(),+ },+ None => CompletionOutcome::Success,+ };+ Ok(CompletionRecord {+ operation_id: operation.operation_id(),+ class: operation.class(),+ timestamps,+ outcome,+ retry_affected: affected_stats.retries > 0,+ deadlock_affected: affected_stats.deadlocks > 0,+ retry_attempts: attributed_stats.retries,+ deadlock_attempts: attributed_stats.deadlocks,+ })+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum BatchPayloadError {+ Person,+ DistinctId,+}++impl std::fmt::Display for BatchPayloadError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Person => formatter.write_str("person batch received a non-person operation"),+ Self::DistinctId => {+ formatter.write_str("distinct ID batch received a non-assignment operation")+ }+ }+ }+}++fn dedupe_person_updates(+ batch: &[DispatchedOperation],+) -> Result<Vec<PersonUpdateData>, BatchPayloadError> {+ let mut updates = BTreeMap::<(i32, uuid::Uuid), PersonUpdateData>::new();+ for operation in batch {+ let OpPayload::PersonUpsert(payload) = &operation.descriptor().payload else {+ return Err(BatchPayloadError::Person);+ };+ let candidate = PersonUpdateData {+ team_id: payload.team_id,+ person_uuid: payload.person_uuid,+ properties: payload.properties.clone(),+ version: payload.version,+ };+ match updates.entry((payload.team_id, payload.person_uuid)) {+ Entry::Vacant(entry) => {+ entry.insert(candidate);+ }+ Entry::Occupied(mut entry) if candidate.version > entry.get().version => {+ entry.insert(candidate);+ }+ Entry::Occupied(_) => {}+ }+ }+ Ok(updates.into_values().collect())+}++fn dedupe_distinct_id_assignments(+ batch: &[DispatchedOperation],+) -> Result<Vec<DistinctIdAssignmentData>, BatchPayloadError> {+ let mut assignments = BTreeMap::<(i32, Box<str>), DistinctIdAssignmentData>::new();+ for operation in batch {+ let OpPayload::DistinctIdAssignment(payload) = &operation.descriptor().payload else {+ return Err(BatchPayloadError::DistinctId);+ };+ let candidate = DistinctIdAssignmentData {+ team_id: payload.team_id,+ person_uuid: payload.person_uuid,+ distinct_id: payload.distinct_id.clone(),+ version: payload.version,+ };+ let key = (payload.team_id, payload.distinct_id.clone());+ match assignments.entry(key) {+ Entry::Vacant(entry) => {+ entry.insert(candidate);+ }+ Entry::Occupied(mut entry)+ if (candidate.version, candidate.person_uuid)+ > (entry.get().version, entry.get().person_uuid) =>+ {+ entry.insert(candidate);+ }+ Entry::Occupied(_) => {}+ }+ }+ Ok(assignments.into_values().collect())+}++#[cfg(test)]+mod tests {+ use std::sync::atomic::{AtomicUsize, Ordering};++ use serde_json::json;++ use super::*;+ use crate::benchmark::ops::{+ DistinctIdAssignmentPayload, DistinctIdMove, FullMergePayload, MergeShape,+ NanosSincePhaseStart, OpDescriptor, OperationId, PersonUpsertPayload, PhaseId,+ };++ const TEST_PHASE: PhaseId = PhaseId::new(1);++ fn dispatched(id: u64, payload: OpPayload) -> DispatchedOperation {+ let scheduled_at = NanosSincePhaseStart::from_nanos(TEST_PHASE, 0);+ DispatchedOperation::try_new(+ OpDescriptor::new(OperationId(id), scheduled_at, payload),+ scheduled_at,+ )+ .expect("on-time dispatch")+ }++ #[test]+ fn batch_dedupe_matches_processor_order_and_tie_breaks() {+ let first_person = uuid::Uuid::from_u128(1);+ let second_person = uuid::Uuid::from_u128(2);+ let person_batch = [+ dispatched(+ 1,+ OpPayload::PersonUpsert(PersonUpsertPayload {+ team_id: 2,+ person_uuid: second_person,+ properties: json!({"winner": "team_two"}),+ version: 1,+ }),+ ),+ dispatched(+ 2,+ OpPayload::PersonUpsert(PersonUpsertPayload {+ team_id: 1,+ person_uuid: second_person,+ properties: json!({"winner": "high_version"}),+ version: 3,+ }),+ ),+ dispatched(+ 3,+ OpPayload::PersonUpsert(PersonUpsertPayload {+ team_id: 1,+ person_uuid: second_person,+ properties: json!({"winner": "equal_version_late"}),+ version: 3,+ }),+ ),+ dispatched(+ 4,+ OpPayload::PersonUpsert(PersonUpsertPayload {+ team_id: 1,+ person_uuid: first_person,+ properties: json!({}),+ version: 1,+ }),+ ),+ ];+ let persons = dedupe_person_updates(&person_batch).expect("person payloads");++ assert_eq!(persons.len(), 3);+ assert_eq!(+ persons+ .iter()+ .map(|person| (person.team_id, person.person_uuid))+ .collect::<Vec<_>>(),+ vec![(1, first_person), (1, second_person), (2, second_person)]+ );+ assert_eq!(persons[1].properties, json!({"winner": "high_version"}));++ let did_batch = [+ dispatched(+ 5,+ OpPayload::DistinctIdAssignment(DistinctIdAssignmentPayload {+ team_id: 2,+ person_uuid: first_person,+ distinct_id: "z".into(),+ version: 1,+ }),+ ),+ dispatched(+ 6,+ OpPayload::DistinctIdAssignment(DistinctIdAssignmentPayload {+ team_id: 1,+ person_uuid: first_person,+ distinct_id: "a".into(),+ version: 4,+ }),+ ),+ dispatched(+ 7,+ OpPayload::DistinctIdAssignment(DistinctIdAssignmentPayload {+ team_id: 1,+ person_uuid: second_person,+ distinct_id: "a".into(),+ version: 4,+ }),+ ),+ ];+ let distinct_ids =+ dedupe_distinct_id_assignments(&did_batch).expect("distinct ID payloads");++ assert_eq!(distinct_ids.len(), 2);+ assert_eq!(&*distinct_ids[0].distinct_id, "a");+ assert_eq!(distinct_ids[0].person_uuid, second_person);+ assert_eq!(+ (distinct_ids[1].team_id, &*distinct_ids[1].distinct_id),+ (2, "z")+ );+ }++ #[test]+ fn read_expectation_rejects_both_correctness_mismatches() {+ for (expectation, found, message) in [+ (ReadExpectation::Hit, false, "expected a hit"),+ (ReadExpectation::Miss, true, "expected a miss"),+ ] {+ let error = validate_read_expectation(&expectation, found)+ .expect_err("mismatched read must fail");+ assert!(error.contains(message));+ }+ assert!(validate_read_expectation(&ReadExpectation::Hit, true).is_ok());+ assert!(validate_read_expectation(&ReadExpectation::Miss, false).is_ok());+ }++ #[test]+ fn merge_preparation_sorts_distinct_id_moves_by_primary_key() {+ let payload = FullMergePayload {+ team_id: 7,+ source_person_uuid: uuid::Uuid::from_u128(1),+ target_person_uuid: uuid::Uuid::from_u128(2),+ distinct_id_moves: vec![+ DistinctIdMove {+ distinct_id: "z".into(),+ version: 2,+ },+ DistinctIdMove {+ distinct_id: "a".into(),+ version: 3,+ },+ DistinctIdMove {+ distinct_id: "m".into(),+ version: 4,+ },+ ]+ .into_boxed_slice(),+ target_properties: json!({}),+ target_version: 5,+ source_tombstone_version: 101,+ shape: MergeShape::Standard,+ };++ let prepared = prepare_merge(&payload);++ assert_eq!(+ prepared+ .assignments+ .iter()+ .map(|assignment| assignment.distinct_id.as_ref())+ .collect::<Vec<_>>(),+ vec!["a", "m", "z"]+ );+ }++ #[tokio::test(start_paused = true)]+ async fn batch_retry_attempts_are_attributed_once_without_losing_affected_flags() {+ let batch = [+ dispatched(+ 10,+ OpPayload::PersonUpsert(PersonUpsertPayload {+ team_id: 1,+ person_uuid: uuid::Uuid::from_u128(1),+ properties: json!({}),+ version: 1,+ }),+ ),+ dispatched(+ 11,+ OpPayload::PersonUpsert(PersonUpsertPayload {+ team_id: 1,+ person_uuid: uuid::Uuid::from_u128(2),+ properties: json!({}),+ version: 1,+ }),+ ),+ ];+ let execution = RetryResult {+ value: Some(2),+ error: None,+ stats: RetryStats {+ retries: 2,+ deadlocks: 1,+ },+ cancelled: false,+ };+ let clock = PhaseClock::start_now(TEST_PHASE);+ let (sender, mut receiver) = mpsc::channel(2);++ emit_batch_completions(+ &batch,+ clock.now().expect("phase time"),+ &execution,+ &clock,+ &sender,+ )+ .await+ .expect("emit completions");+ let first = receiver.recv().await.expect("first completion");+ let second = receiver.recv().await.expect("second completion");++ assert!(first.retry_affected && second.retry_affected);+ assert!(first.deadlock_affected && second.deadlock_affected);+ assert_eq!(first.retry_attempts + second.retry_attempts, 2);+ assert_eq!(first.deadlock_attempts + second.deadlock_attempts, 1);+ }++ #[tokio::test]+ async fn coordinated_close_drains_more_completions_than_channel_capacity() {+ let mut dispatchers = Vec::with_capacity(OpClass::COUNT);+ for _ in 0..OpClass::COUNT {+ let (dispatcher, receiver) = BoundedDispatcher::channel(nonzero(1));+ drop(receiver);+ dispatchers.push(dispatcher);+ }+ let ingress = ExecutorIngress {+ dispatchers: dispatchers.try_into().expect("four dispatchers"),+ };+ let (sender, receiver) = mpsc::channel(1);+ let producer = tokio::spawn(async move {+ for operation_id in 1..=3 {+ let operation = dispatched(+ operation_id,+ OpPayload::PersonUpsert(PersonUpsertPayload {+ team_id: 1,+ person_uuid: uuid::Uuid::from_u128(operation_id as u128),+ properties: json!({}),+ version: 1,+ }),+ );+ let completion = build_completion(+ &operation,+ NanosSincePhaseStart::from_nanos(TEST_PHASE, 0),+ NanosSincePhaseStart::from_nanos(TEST_PHASE, 0),+ None,+ RetryStats::default(),+ RetryStats::default(),+ )?;+ sender+ .send(completion)+ .await+ .map_err(|_| anyhow::anyhow!("receiver closed"))?;+ }+ Ok(())+ });+ let runtime = ExecutorRuntime {+ completion_receiver: receiver,+ tasks: ExecutorTasks {+ handles: vec![producer],+ },+ cancellation: CancellationToken::new(),+ };+ let mut drained = 0;++ drop(ingress);+ tokio::time::timeout(+ Duration::from_secs(1),+ runtime.drain(|_| {+ drained += 1;+ Ok(())+ }),+ )+ .await+ .expect("coordinated drain must not deadlock")+ .expect("normal shutdown");++ assert_eq!(drained, 3);+ }++ #[tokio::test]+ async fn cancellation_stops_before_starting_another_database_attempt() {+ let cancellation = CancellationToken::new();+ cancellation.cancel();+ let attempts = AtomicUsize::new(0);++ let result: RetryResult<()> = with_retry(RetryConfig::default(), &cancellation, || async {+ attempts.fetch_add(1, Ordering::Relaxed);+ Ok::<(), sqlx::Error>(())+ })+ .await;++ assert!(result.cancelled);+ assert_eq!(attempts.load(Ordering::Relaxed), 0);+ }++ #[tokio::test]+ async fn database_attempts_have_a_finite_timeout() {+ let cancellation = CancellationToken::new();+ let retry = RetryConfig {+ attempt_timeout: Duration::from_millis(1),+ ..RetryConfig::default()+ };++ let result: RetryResult<()> = with_retry(retry, &cancellation, || async {+ std::future::pending::<Result<(), sqlx::Error>>().await+ })+ .await;++ assert!(result+ .error+ .is_some_and(|error| error.contains("database attempt timed out")));+ }+}diff --git a/rust/flags-consumer/src/benchmark/metrics.rs b/rust/flags-consumer/src/benchmark/metrics.rsdeleted file mode 100644index 4134b2f2b6a5..000000000000--- a/rust/flags-consumer/src/benchmark/metrics.rs+++ /dev/null@@ -1,160 +0,0 @@-use std::time::Duration;--use sqlx::PgPool;--#[derive(Debug, Clone)]-pub struct PgSnapshot {- pub n_tup_upd: i64,- pub n_tup_hot_upd: i64,- pub n_dead_tup: i64,- pub table_bytes: i64,- pub index_bytes: i64,- pub wal_lsn: Option<String>,-}--pub struct PhaseDelta {- pub hot_pct: f64,- pub dead_tuples: i64,-}--#[derive(Debug)]-pub struct LatencyStats {- pub count: usize,- pub p50: Duration,- pub p95: Duration,- pub p99: Duration,- pub max: Duration,-}--pub async fn capture_snapshot(pool: &PgPool) -> anyhow::Result<PgSnapshot> {- let stats: (i64, i64, i64) = sqlx::query_as(- "SELECT \- COALESCE(SUM(n_tup_upd), 0)::bigint, \- COALESCE(SUM(n_tup_hot_upd), 0)::bigint, \- COALESCE(SUM(n_dead_tup), 0)::bigint \- FROM pg_stat_user_tables \- WHERE relname LIKE 'flags_person_lookup_p%'",- )- .fetch_one(pool)- .await?;-- let sizes: (i64, i64) = sqlx::query_as(- "SELECT \- COALESCE(SUM(pg_relation_size(oid)), 0)::bigint, \- COALESCE(SUM(pg_indexes_size(oid)), 0)::bigint \- FROM pg_class \- WHERE relname LIKE 'flags_person_lookup_p%'",- )- .fetch_one(pool)- .await?;-- // Requires pg_monitor role; returns None on permission error.- let wal_lsn: Option<String> =- match sqlx::query_as::<_, (String,)>("SELECT pg_current_wal_lsn()::text")- .fetch_one(pool)- .await- {- Ok((lsn,)) => Some(lsn),- Err(e) => {- tracing::debug!("WAL LSN unavailable (need pg_monitor role): {e}");- None- }- };-- Ok(PgSnapshot {- n_tup_upd: stats.0,- n_tup_hot_upd: stats.1,- n_dead_tup: stats.2,- table_bytes: sizes.0,- index_bytes: sizes.1,- wal_lsn,- })-}--pub fn compute_delta(before: &PgSnapshot, after: &PgSnapshot) -> PhaseDelta {- let updates = after.n_tup_upd - before.n_tup_upd;- let hot_updates = after.n_tup_hot_upd - before.n_tup_hot_upd;- let hot_pct = if updates > 0 {- (hot_updates as f64 / updates as f64) * 100.0- } else {- 0.0- };-- PhaseDelta {- hot_pct,- dead_tuples: after.n_dead_tup - before.n_dead_tup,- }-}--pub async fn compute_wal_delta(- pool: &PgPool,- before: &PgSnapshot,- after: &PgSnapshot,-) -> Option<i64> {- let (before_lsn, after_lsn) = match (&before.wal_lsn, &after.wal_lsn) {- (Some(b), Some(a)) => (b.clone(), a.clone()),- _ => return None,- };-- match sqlx::query_as::<_, (i64,)>("SELECT pg_wal_lsn_diff($1::pg_lsn, $2::pg_lsn)::bigint")- .bind(&after_lsn)- .bind(&before_lsn)- .fetch_one(pool)- .await- {- Ok((diff,)) => Some(diff),- Err(e) => {- tracing::debug!("WAL diff query failed: {e}");- None- }- }-}--/// Requires pg_stat_scan_tables role. Logs a warning and returns early if unavailable.-pub async fn reset_stats(pool: &PgPool) {- for i in 0..super::schema::PARTITION_COUNT {- let table = format!("flags_person_lookup_p{i}");- let result = sqlx::query(- "SELECT pg_stat_reset_single_table_counters(oid) FROM pg_class WHERE relname = $1",- )- .bind(&table)- .execute(pool)- .await;- if let Err(e) = result {- tracing::warn!(- "could not reset pg_stat counters for {table} (need pg_stat_scan_tables role): {e}"- );- return;- }- }- tracing::info!("pg_stat counters reset for all partitions");-}--/// Sorts the slice in place.-pub fn compute_percentiles(latencies: &mut [Duration]) -> LatencyStats {- let count = latencies.len();- if count == 0 {- return LatencyStats {- count: 0,- p50: Duration::ZERO,- p95: Duration::ZERO,- p99: Duration::ZERO,- max: Duration::ZERO,- };- }-- latencies.sort_unstable();-- let p = |pct: f64| -> Duration {- let idx = ((count as f64 * pct) as usize).min(count - 1);- latencies[idx]- };-- LatencyStats {- count,- p50: p(0.50),- p95: p(0.95),- p99: p(0.99),- max: latencies[count - 1],- }-}diff --git a/rust/flags-consumer/src/benchmark/mod.rs b/rust/flags-consumer/src/benchmark/mod.rsindex 7f3b4aacb3c0..431b31040d71 100644--- a/rust/flags-consumer/src/benchmark/mod.rs+++ b/rust/flags-consumer/src/benchmark/mod.rs@@ -1,168 +1,1640 @@-pub mod data_gen;-pub mod metrics;+pub mod collector;+pub mod executor;+pub mod ops;+pub mod pg_sampler;+pub mod plancheck;pub mod population;+pub mod rates;pub mod report;+pub mod scheduler;pub mod schema;-pub mod workloads;+pub mod world;-use std::time::Instant;+use std::collections::BTreeMap;+use std::num::NonZeroUsize;+use std::path::{Path, PathBuf};+use std::sync::Arc;+use std::time::{Duration, Instant};+use anyhow::Context;use common_database::{get_pool_with_config, PoolConfig};-use rand::SeedableRng;+use rand::rngs::StdRng;+use rand::{Rng, SeedableRng};+use serde::Serialize;+use sqlx::PgPool;+use tokio::sync::mpsc;+use tokio::task::JoinHandle;+use tokio_util::sync::CancellationToken;use crate::storage::postgres::PostgresStorage;-use data_gen::build_benchmark_data;+use collector::{JsonlSink, PhaseCollector};+use executor::{ExecutorConfig, ExecutorDispatchers, ExecutorIngress, ExecutorRuntime};+use ops::{CompletionOutcome, CompletionRecord, OpClass, OpDescriptor, OperationId, PhaseId};+use pg_sampler::{PgDeltaRecord, PgSampler};+use rates::{standard_phases, BenchmarkProfile, Hook, PhaseSpec, RatePerSecond, RateSpec};+use report::{GateEvaluation, GateThresholds, PhaseResult};+use scheduler::{ArrivalSchedule, BoundedDispatcher, DispatchOutcome, DispatchRecord, PhaseClock};+use world::{+ AssignmentMode, PendingCreationToken, PendingDistinctIdToken, PersonCreationCount, ReadMode,+ ReplayMode, WorldConfig, WorldError, WorldGrowth, WorldMemoryEstimate, WorldState,+};-#[derive(clap::Args)]+const DEFAULT_OUTPUT: &str = "tmp/flags-read-store-benchmark.jsonl";+const PG_SAMPLE_INTERVAL: Duration = Duration::from_secs(10);+const GROWTH_PREFLIGHT_HEADROOM: f64 = 1.20;+const WORKLOAD_SEED_MIX: u64 = 0xe703_7ed1_a0b4_28db;++#[derive(Debug, Clone, Serialize, clap::Args)]pub struct BenchmarkArgs {- #[arg(long, default_value = "100000")]+ #[arg(long, value_enum, default_value_t = BenchmarkProfile::Smoke)]+ pub profile: BenchmarkProfile,++ #[arg(long, default_value_t = 100_000)]pub scale: u64,- #[arg(long, default_value = "100")]+ #[arg(long, default_value_t = 100)]pub teams: i32,- #[arg(long, default_value = "60")]- pub duration_secs: u64,+ #[arg(long)]+ pub duration_secs: Option<u64>,- #[arg(long, default_value = "4")]- pub concurrency: usize,+ #[arg(long, default_value_t = 64)]+ pub partitions: usize,- #[arg(long, default_value = "10")]- pub burst_factor: usize,+ #[arg(long, default_value_t = 100)]+ pub person_fillfactor: u8,- #[arg(long, default_value = "500")]+ #[arg(long, default_value_t = 100)]+ pub map_fillfactor: u8,++ #[arg(long, default_value_t = 500)]pub batch_size: usize,+ #[arg(long, default_value_t = 700)]+ pub prop_bytes: usize,++ #[arg(long, default_value_t = 42)]+ pub seed: u64,++ #[arg(long, default_value = DEFAULT_OUTPUT)]+ pub out: PathBuf,+#[arg(long)]pub skip_populate: bool,++ #[arg(long)]+ pub allow_destructive_reset: bool,++ #[arg(long, default_value_t = 64)]+ pub read_workers: usize,++ #[arg(long, default_value_t = 16)]+ pub merge_workers: usize,++ #[arg(long, default_value_t = 8)]+ pub person_batch_workers: usize,++ #[arg(long, default_value_t = 8)]+ pub distinct_id_batch_workers: usize,++ #[arg(long, default_value_t = 6_144)]+ pub max_world_memory_mib: u64,++ #[arg(long, default_value_t = 5)]+ pub creation_percent: u8,++ #[arg(long, default_value_t = 1)]+ pub stale_replay_percent: u8,++ #[arg(long, default_value_t = 1)]+ pub read_miss_percent: u8,++ #[arg(long, default_value_t = 1)]+ pub whale_merge_percent: u8,++ #[arg(long, default_value_t = 50)]+ pub recent_target_percent: u8,++ #[arg(long, default_value_t = 1.0)]+ pub gate_read_p50_ms: f64,++ #[arg(long, default_value_t = 5.0)]+ pub gate_read_p99_ms: f64,++ #[arg(long, default_value_t = 10.0)]+ pub gate_storm_read_p99_ms: f64,++ #[arg(long, default_value_t = 900)]+ pub gate_recovery_max_secs: u64,++ #[arg(long, default_value_t = 5.0)]+ pub gate_catch_up_headroom: f64,++ #[arg(long, default_value_t = 5.0)]+ pub gate_dispatch_p99_ms: f64,++ #[arg(long, default_value_t = 1.0)]+ pub gate_rate_tolerance_percent: f64,++ #[arg(long, default_value_t = 1.2)]+ pub gate_max_read_drift_ratio: f64,++ #[arg(long, default_value_t = 1.0)]+ pub gate_max_backlog_secs: f64,+}++impl BenchmarkArgs {+ fn validate(&self) -> anyhow::Result<()> {+ anyhow::ensure!(self.scale > 0, "--scale must be greater than zero");+ anyhow::ensure!(self.teams > 0, "--teams must be greater than zero");+ anyhow::ensure!(+ self.skip_populate || self.allow_destructive_reset,+ "schema recreation requires --allow-destructive-reset"+ );+ anyhow::ensure!(+ self.batch_size > 0,+ "--batch-size must be greater than zero"+ );+ anyhow::ensure!(+ self.prop_bytes > 0,+ "--prop-bytes must be greater than zero"+ );+ anyhow::ensure!(+ self.max_world_memory_mib > 0,+ "--max-world-memory-mib must be greater than zero"+ );+ for (name, value) in [+ ("--creation-percent", self.creation_percent),+ ("--stale-replay-percent", self.stale_replay_percent),+ ("--read-miss-percent", self.read_miss_percent),+ ("--whale-merge-percent", self.whale_merge_percent),+ ("--recent-target-percent", self.recent_target_percent),+ ] {+ anyhow::ensure!(value <= 100, "{name} must be between 0 and 100");+ }+ for (name, value) in [+ ("--gate-read-p50-ms", self.gate_read_p50_ms),+ ("--gate-read-p99-ms", self.gate_read_p99_ms),+ ("--gate-storm-read-p99-ms", self.gate_storm_read_p99_ms),+ ("--gate-catch-up-headroom", self.gate_catch_up_headroom),+ ("--gate-dispatch-p99-ms", self.gate_dispatch_p99_ms),+ (+ "--gate-rate-tolerance-percent",+ self.gate_rate_tolerance_percent,+ ),+ (+ "--gate-max-read-drift-ratio",+ self.gate_max_read_drift_ratio,+ ),+ ("--gate-max-backlog-secs", self.gate_max_backlog_secs),+ ] {+ anyhow::ensure!(+ value.is_finite() && value > 0.0,+ "{name} must be finite and positive"+ );+ }+ self.executor_config()?;+ Ok(())+ }++ fn duration_override(&self) -> Option<Duration> {+ self.duration_secs.map(Duration::from_secs)+ }++ fn world_config(&self) -> anyhow::Result<WorldConfig> {+ Ok(WorldConfig {+ seed: self.seed,+ team_count: self.teams,+ initial_person_count: usize::try_from(self.scale).context("--scale exceeds usize")?,+ recent_capacity_per_team: 4_096,+ recent_target_percent: self.recent_target_percent,+ property_bytes: self.prop_bytes,+ })+ }++ fn executor_config(&self) -> anyhow::Result<ExecutorConfig> {+ Ok(ExecutorConfig {+ read_workers: nonzero("--read-workers", self.read_workers)?,+ merge_workers: nonzero("--merge-workers", self.merge_workers)?,+ person_batch_workers: nonzero("--person-batch-workers", self.person_batch_workers)?,+ distinct_id_batch_workers: nonzero(+ "--distinct-id-batch-workers",+ self.distinct_id_batch_workers,+ )?,+ batch_size: nonzero("--batch-size", self.batch_size)?,+ ..ExecutorConfig::default()+ })+ }++ fn gate_thresholds(&self) -> GateThresholds {+ GateThresholds {+ steady_read_p50_ms: self.gate_read_p50_ms,+ steady_read_p99_ms: self.gate_read_p99_ms,+ storm_read_p99_ms: self.gate_storm_read_p99_ms,+ recovery_max_secs: self.gate_recovery_max_secs,+ catch_up_headroom: self.gate_catch_up_headroom,+ dispatch_p99_ms: self.gate_dispatch_p99_ms,+ rate_tolerance_percent: self.gate_rate_tolerance_percent,+ max_read_drift_ratio: self.gate_max_read_drift_ratio,+ max_backlog_secs: self.gate_max_backlog_secs,+ }+ }++ fn world_memory_limit_bytes(&self) -> anyhow::Result<u64> {+ self.max_world_memory_mib+ .checked_mul(1024 * 1024)+ .context("--max-world-memory-mib overflows bytes")+ }+}++fn nonzero(name: &'static str, value: usize) -> anyhow::Result<NonZeroUsize> {+ NonZeroUsize::new(value).with_context(|| format!("{name} must be greater than zero"))+}++#[derive(Debug, Serialize)]+struct RunMetaRecord<'a> {+ record_type: &'static str,+ postgres_version: &'a str,+ settings: &'a [(String, String)],+ args: &'a BenchmarkArgs,+ seed: u64,+ population: Option<population::PopulationSummary>,+ schema: &'a schema::SchemaMetadata,+ initial_world_memory: WorldMemoryEstimate,+ projected_world_memory: WorldMemoryEstimate,+ phases: &'a [PhaseSpec],+ plan_evidence: &'a [plancheck::NamedPlanEvidence],+}++#[derive(Debug, Default)]+struct RuntimeGrowth {+ person_creations: u64,+ distinct_id_assignments: u64,+}++#[derive(Debug, Clone, Copy)]+struct PhaseTimings {+ pre_hook: Duration,+ drain: Duration,+}++impl RuntimeGrowth {+ fn creation(&mut self) {+ self.person_creations = self.person_creations.saturating_add(1);+ }++ fn distinct_id(&mut self) {+ self.distinct_id_assignments = self.distinct_id_assignments.saturating_add(1);+ }++ fn as_world_growth(&self) -> WorldGrowth {+ WorldGrowth::new(+ PersonCreationCount::new(self.person_creations),+ world::DistinctIdAssignmentCount::new(self.distinct_id_assignments),+ )+ }+}++#[derive(Debug, Clone, Copy)]+enum PendingReference {+ Creation(u64),+ DistinctId(PendingDistinctIdToken),+}++#[derive(Debug, Clone, Copy)]+struct PendingCreation {+ token: PendingCreationToken,+ remaining: u8,+}++#[derive(Debug, Default)]+struct ActivationTracker {+ next_creation: u64,+ by_operation: BTreeMap<OperationId, PendingReference>,+ creations: BTreeMap<u64, PendingCreation>,+}++impl ActivationTracker {+ fn register_creation(+ &mut self,+ token: PendingCreationToken,+ person_operation: OperationId,+ distinct_id_operation: OperationId,+ ) -> anyhow::Result<()> {+ let creation_id = self.next_creation;+ self.next_creation = self+ .next_creation+ .checked_add(1)+ .context("pending creation identifier exhausted")?;+ self.creations.insert(+ creation_id,+ PendingCreation {+ token,+ remaining: 2,+ },+ );+ for operation_id in [person_operation, distinct_id_operation] {+ anyhow::ensure!(+ self.by_operation+ .insert(operation_id, PendingReference::Creation(creation_id))+ .is_none(),+ "duplicate pending operation {}",+ operation_id.0+ );+ }+ Ok(())+ }++ fn register_distinct_id(+ &mut self,+ operation_id: OperationId,+ token: PendingDistinctIdToken,+ ) -> anyhow::Result<()> {+ anyhow::ensure!(+ self.by_operation+ .insert(operation_id, PendingReference::DistinctId(token))+ .is_none(),+ "duplicate pending operation {}",+ operation_id.0+ );+ Ok(())+ }++ fn record_completion(+ &mut self,+ world: &mut WorldState,+ completion: &CompletionRecord,+ ) -> anyhow::Result<()> {+ if let CompletionOutcome::Error { message } = &completion.outcome {+ anyhow::bail!(+ "{:?} operation {} failed: {message}",+ completion.class,+ completion.operation_id.0+ );+ }+ let Some(reference) = self.by_operation.remove(&completion.operation_id) else {+ return Ok(());+ };+ match reference {+ PendingReference::DistinctId(token) => world.activate_distinct_id(token)?,+ PendingReference::Creation(creation_id) => {+ let pending = self+ .creations+ .get_mut(&creation_id)+ .context("pending creation completion lost its state")?;+ pending.remaining = pending+ .remaining+ .checked_sub(1)+ .context("pending creation completed more than twice")?;+ if pending.remaining == 0 {+ let pending = self+ .creations+ .remove(&creation_id)+ .context("pending creation disappeared before activation")?;+ world.activate_creation(pending.token)?;+ }+ }+ }+ Ok(())+ }++ fn record_failed_dispatch(+ &mut self,+ world: &mut WorldState,+ operation_id: OperationId,+ outcome: DispatchOutcome,+ ) -> anyhow::Result<()> {+ let reference = self.by_operation.remove(&operation_id);+ if matches!(outcome, DispatchOutcome::Closed) {+ anyhow::bail!(+ "executor closed while dispatching operation {}",+ operation_id.0+ );+ }+ if let Some(PendingReference::Creation(_)) = reference {+ anyhow::bail!("creation operation {} was shed", operation_id.0);+ }+ if let Some(PendingReference::DistinctId(token)) = reference {+ world.abandon_distinct_id(token)?;+ }+ Ok(())+ }++ fn ensure_empty(&self) -> anyhow::Result<()> {+ anyhow::ensure!(+ self.by_operation.is_empty() && self.creations.is_empty(),+ "phase ended with {} pending activations",+ self.by_operation.len()+ );+ Ok(())+ }+}++/// The read-store handles every phase connects through.+struct StoreHandles<'a> {+ database_url: &'a str,+ pool: &'a PgPool,+ storage: &'a Arc<PostgresStorage>,+}++/// The mutable world plus the knobs that shape generated operations. Lives for the+/// whole run: entity versions must never restart between phases, or merges of+/// untouched entities degenerate into no-ops.+struct WorkloadContext<'a> {+ world: &'a mut WorldState,+ rng: &'a mut StdRng,+ growth: &'a mut RuntimeGrowth,+ world_config: &'a WorldConfig,+ memory_limit: u64,+ args: &'a BenchmarkArgs,+ /// Each phase asserts this is empty before it finishes, so it carries no state+ /// across phases beyond a monotonic creation counter.+ tracker: ActivationTracker,+}++/// The recording surfaces a phase accumulates into and hands to `finish_phase`.+struct PhaseMetrics<'a> {+ collector: PhaseCollector,+ intervals: Vec<collector::IntervalRecord>,+ pg_records: Vec<PgDeltaRecord>,+ pg_receiver: mpsc::Receiver<PgSample>,+ sink: &'a mut JsonlSink,}pub async fn run(args: BenchmarkArgs) -> anyhow::Result<()> {- let database_url = std::env::var("FLAGS_READ_STORE_DATABASE_URL")- .or_else(|_| std::env::var("DATABASE_URL"))- .map_err(|_| {- anyhow::anyhow!(- "FLAGS_READ_STORE_DATABASE_URL or DATABASE_URL must be set for benchmark mode"- )- })?;-- tracing::info!(- scale = args.scale,- teams = args.teams,- concurrency = args.concurrency,- burst_factor = args.burst_factor,- duration_secs = args.duration_secs,- "starting GIN index benchmark"+ args.validate()?;+ let phases = standard_phases(args.profile, args.duration_override());+ let world_config = args.world_config()?;+ let initial_world_memory = WorldState::estimate_initial_memory(&world_config)?;+ let projected_growth = projected_growth(&args, &phases)?;+ let projected_world_memory = WorldState::estimate_memory(&world_config, projected_growth)?;+ let memory_limit = args.world_memory_limit_bytes()?;+ anyhow::ensure!(+ projected_world_memory.total_bytes <= memory_limit,+ "projected world state requires {:.1} MiB, above --max-world-memory-mib {}",+ bytes_mib(projected_world_memory.total_bytes),+ args.max_world_memory_mib);- // Burst phase needs concurrency * burst_factor + reader tasks + headroom.- let max_conns = (args.concurrency * args.burst_factor + args.concurrency + 4) as u32;- let max_conns = max_conns.max(64);+ ensure_output_parent(&args.out)?;+ let mut sink = JsonlSink::create(&args.out)+ .with_context(|| format!("create benchmark output {}", args.out.display()))?;+ let database_url = benchmark_database_url()?;+ let executor_config = args.executor_config()?;+ let pool = benchmark_pool(&database_url, &executor_config)?;+ let storage = Arc::new(PostgresStorage::new(pool.clone()));+ storage+ .ping()+ .await+ .context("connect read-store database")?;- let pool = get_pool_with_config(- &database_url,+ let mut world = WorldState::new(world_config.clone())?;+ world.reserve_person_growth(projected_growth.person_creations)?;+ let (population, schema_source) = if args.skip_populate {+ anyhow::ensure!(+ schema::table_exists(&pool).await?,+ "--skip-populate requires existing flags_person and flags_distinct_id_map tables"+ );+ (None, schema::SchemaSource::Existing)+ } else {+ schema::create_schema(+ &pool,+ args.partitions,+ args.person_fillfactor,+ args.map_fillfactor,+ )+ .await?;+ let population = population::populate_world(+ &pool,+ storage.as_ref(),+ world.population(),+ args.batch_size,+ )+ .await?;+ (Some(population), schema::SchemaSource::Created)+ };+ let schema = schema::inspect_schema(&pool, schema_source).await?;++ let plan_evidence = plancheck::verify_storage_plans(&pool).await?;+ let postgres_version: String = sqlx::query_scalar("SELECT version()")+ .fetch_one(&pool)+ .await+ .context("read PostgreSQL version")?;+ let settings = load_postgres_settings(&pool).await?;+ sink.write(&RunMetaRecord {+ record_type: "run_meta",+ postgres_version: &postgres_version,+ settings: &settings,+ args: &args,+ seed: args.seed,+ population,+ schema: &schema,+ initial_world_memory,+ projected_world_memory,+ phases: &phases,+ plan_evidence: &plan_evidence,+ })?;++ let mut phase_results = Vec::with_capacity(phases.len());+ let mut growth = RuntimeGrowth::default();+ let mut workload_rng = StdRng::seed_from_u64(args.seed ^ WORKLOAD_SEED_MIX);+ let store = StoreHandles {+ database_url: &database_url,+ pool: &pool,+ storage: &storage,+ };+ let mut workload = WorkloadContext {+ world: &mut world,+ rng: &mut workload_rng,+ growth: &mut growth,+ world_config: &world_config,+ memory_limit,+ args: &args,+ tracker: ActivationTracker::default(),+ };+ for (index, phase) in phases.iter().enumerate() {+ let phase_id = PhaseId::new(u64::try_from(index + 1).context("phase ID overflow")?);+ let result = run_phase(+ &store,+ &mut workload,+ phase_id,+ phase,+ executor_config.clone(),+ &mut sink,+ )+ .await+ .with_context(|| format!("run {} phase", phase.name.as_str()))?;+ phase_results.push(result);+ }++ let gates = report::evaluate_gates(&phase_results, args.gate_thresholds());+ #[derive(Serialize)]+ struct GateRecord<'a> {+ record_type: &'static str,+ evaluation: &'a GateEvaluation,+ }+ sink.write(&GateRecord {+ record_type: "gate_evaluation",+ evaluation: &gates,+ })?;+ sink.flush()?;+ report::print_report(+ &postgres_version,+ &settings,+ args.seed,+ &phase_results,+ &gates,+ );+ enforce_gate_result(args.profile, &gates, &args.out)+}++async fn run_phase(+ store: &StoreHandles<'_>,+ workload: &mut WorkloadContext<'_>,+ phase_id: PhaseId,+ phase: &PhaseSpec,+ executor_config: ExecutorConfig,+ sink: &mut JsonlSink,+) -> anyhow::Result<PhaseResult> {+ if phase.name == rates::PhaseName::CatchUp {+ run_catch_up_phase(store, workload, phase_id, phase, executor_config, sink).await+ } else {+ run_open_phase(store, workload, phase_id, phase, executor_config, sink).await+ }+}++async fn run_open_phase(+ store: &StoreHandles<'_>,+ workload: &mut WorkloadContext<'_>,+ phase_id: PhaseId,+ phase: &PhaseSpec,+ executor_config: ExecutorConfig,+ sink: &mut JsonlSink,+) -> anyhow::Result<PhaseResult> {+ let args = workload.args;+ let (pre_hook_duration, pg_records) =+ run_pre_hooks(store, phase_id, &phase.pre_hooks, sink).await?;+ let clock = PhaseClock::start_now(phase_id);+ let (mut ingress, mut runtime) =+ executor::start(Arc::clone(store.storage), clock, executor_config);+ let cancellation = runtime.cancellation_token();+ let rates = adjusted_open_rates(phase, args.creation_percent)?;+ let mut schedule = ArrivalSchedule::new(+ phase_id,+ args.seed ^ phase_id.get().wrapping_mul(WORKLOAD_SEED_MIX),+ &rates,+ )?;+ let duration_nanos = duration_as_nanos(phase.duration);+ let (sampler_cancellation, pg_receiver, sampler_task) =+ spawn_pg_sampler(store.database_url.to_owned(), phase_id);+ let mut metrics = PhaseMetrics {+ collector: PhaseCollector::with_deadline(phase_id, duration_nanos),+ intervals: Vec::new(),+ pg_records,+ pg_receiver,+ sink,+ };++ let load_result = drive_open_load(+ &clock,+ phase.duration,+ &mut schedule,+ &mut ingress,+ &mut runtime,+ workload,+ &mut metrics,+ )+ .await;+ let workload_interval_result = flush_interval(duration_nanos, &mut metrics);+ if load_result.is_err() || workload_interval_result.is_err() {+ cancellation.cancel();+ }+ let drain_started = Instant::now();+ drop(ingress);+ let drain_result = runtime+ .drain(|completion| record_completion(&mut metrics.collector, workload, completion))+ .await;+ let drain_duration = drain_started.elapsed();+ sampler_cancellation.cancel();+ let sampler_result = sampler_task.await.context("join PostgreSQL sampler task");+ let pg_sample_result = drain_pg_samples(&mut metrics);++ load_result?;+ workload_interval_result?;+ sampler_result?;+ pg_sample_result?;+ drain_result?;+ workload.tracker.ensure_empty()?;+ finish_phase(+ phase,+ PhaseTimings {+ pre_hook: pre_hook_duration,+ drain: drain_duration,+ },+ clock,+ metrics,+ )+}++async fn run_catch_up_phase(+ store: &StoreHandles<'_>,+ workload: &mut WorkloadContext<'_>,+ phase_id: PhaseId,+ phase: &PhaseSpec,+ executor_config: ExecutorConfig,+ sink: &mut JsonlSink,+) -> anyhow::Result<PhaseResult> {+ let args = workload.args;+ let (pre_hook_duration, pg_records) =+ run_pre_hooks(store, phase_id, &phase.pre_hooks, sink).await?;+ let clock = PhaseClock::start_now(phase_id);+ let (ingress, mut runtime) = executor::start(Arc::clone(store.storage), clock, executor_config);+ let cancellation = runtime.cancellation_token();+ let ExecutorDispatchers {+ person_upserts,+ distinct_id_assignments,+ merges,+ canonical_reads,+ } = ingress.into_dispatchers();+ let mut canonical_reads = Some(canonical_reads);+ let writer_stop = CancellationToken::new();+ let (request_sender, mut request_receiver) = mpsc::channel(16);+ let (dispatch_sender, mut dispatch_receiver) = mpsc::channel(16);+ let (person_sender, person_receiver) = mpsc::channel(1);+ let (distinct_id_sender, distinct_id_receiver) = mpsc::channel(1);+ let (merge_sender, merge_receiver) = mpsc::channel(1);+ let person_task = spawn_writer_pump(+ OpClass::PersonUpsert,+ person_upserts,+ person_receiver,+ request_sender.clone(),+ dispatch_sender.clone(),+ clock,+ writer_stop.clone(),+ );+ let distinct_id_task = spawn_writer_pump(+ OpClass::DistinctIdAssignment,+ distinct_id_assignments,+ distinct_id_receiver,+ request_sender.clone(),+ dispatch_sender.clone(),+ clock,+ writer_stop.clone(),+ );+ let merge_task = spawn_writer_pump(+ OpClass::Merge,+ merges,+ merge_receiver,+ request_sender.clone(),+ dispatch_sender.clone(),+ clock,+ writer_stop.clone(),+ );+ drop(request_sender);+ drop(dispatch_sender);+ let writer_senders = WriterOperationSenders {+ person: person_sender,+ distinct_id: distinct_id_sender,+ merge: merge_sender,+ };++ let mut read_schedule = ArrivalSchedule::new(+ phase_id,+ args.seed ^ phase_id.get().wrapping_mul(WORKLOAD_SEED_MIX),+ &phase.rates,+ )?;+ let duration_nanos = duration_as_nanos(phase.duration);+ let (sampler_cancellation, pg_receiver, sampler_task) =+ spawn_pg_sampler(store.database_url.to_owned(), phase_id);+ let mut metrics = PhaseMetrics {+ collector: PhaseCollector::with_deadline(phase_id, duration_nanos),+ intervals: Vec::new(),+ pg_records,+ pg_receiver,+ sink,+ };++ let load_result = drive_catch_up_load(+ &clock,+ phase.duration,+ &mut read_schedule,+ canonical_reads+ .as_mut()+ .expect("read dispatcher is present"),+ &writer_senders,+ &mut request_receiver,+ &mut dispatch_receiver,+ &mut runtime,+ workload,+ &mut metrics,+ )+ .await;+ let workload_interval_result = flush_interval(duration_nanos, &mut metrics);+ if load_result.is_err() || workload_interval_result.is_err() {+ cancellation.cancel();+ }+ let drain_started = Instant::now();+ writer_stop.cancel();+ drop(writer_senders);+ drop(request_receiver);++ let pump_result = join_writer_pumps(+ person_task,+ distinct_id_task,+ merge_task,+ &mut dispatch_receiver,+ &mut runtime,+ &mut metrics.collector,+ workload,+ )+ .await;+ let (dispatchers, pump_error) = match pump_result {+ Ok((person_upserts, distinct_id_assignments, merges)) => (+ Some(ExecutorDispatchers {+ person_upserts,+ distinct_id_assignments,+ merges,+ canonical_reads: canonical_reads.take().expect("read dispatcher is present"),+ }),+ None,+ ),+ Err(error) => {+ cancellation.cancel();+ drop(canonical_reads.take());+ (None, Some(error))+ }+ };+ // Releasing every dispatcher is what lets the workers finish; on the pump's error+ // path they are already gone, so this is a no-op there.+ drop(dispatchers);+ let drain_result = runtime+ .drain(|completion| record_completion(&mut metrics.collector, workload, completion))+ .await;+ let drain_duration = drain_started.elapsed();+ sampler_cancellation.cancel();+ let sampler_result = sampler_task.await.context("join PostgreSQL sampler task");+ let pg_sample_result = drain_pg_samples(&mut metrics);++ load_result?;+ workload_interval_result?;+ if let Some(error) = pump_error {+ return Err(error);+ }+ sampler_result?;+ pg_sample_result?;+ drain_result?;+ workload.tracker.ensure_empty()?;+ finish_phase(+ phase,+ PhaseTimings {+ pre_hook: pre_hook_duration,+ drain: drain_duration,+ },+ clock,+ metrics,+ )+}++fn benchmark_database_url() -> anyhow::Result<String> {+ std::env::var("FLAGS_READ_STORE_DATABASE_URL").map_err(|_| {+ anyhow::anyhow!("FLAGS_READ_STORE_DATABASE_URL must be set for benchmark mode")+ })+}++fn benchmark_pool(database_url: &str, config: &ExecutorConfig) -> anyhow::Result<PgPool> {+ let worker_connections = config+ .read_workers+ .get()+ .saturating_add(config.merge_workers.get())+ .saturating_add(config.person_batch_workers.get())+ .saturating_add(config.distinct_id_batch_workers.get());+ let max_connections = u32::try_from(worker_connections.saturating_add(4))+ .context("worker count exceeds PostgreSQL pool limit")?;+ Ok(get_pool_with_config(+ database_url,PoolConfig {- max_connections: max_conns,+ max_connections,min_connections: 2,- acquire_timeout: std::time::Duration::from_secs(30),+ acquire_timeout: Duration::from_secs(30),..Default::default()},- )?;+ )?)+}- let storage = PostgresStorage::new(pool.clone());- storage.ping().await?;- tracing::info!("database connected");+fn ensure_output_parent(path: &Path) -> anyhow::Result<()> {+ if let Some(parent) = path+ .parent()+ .filter(|parent| !parent.as_os_str().is_empty())+ {+ std::fs::create_dir_all(parent)+ .with_context(|| format!("create output directory {}", parent.display()))?;+ }+ Ok(())+}- let mut rng = rand::rngs::StdRng::seed_from_u64(42);- let registry = data_gen::generate_person_registry(&args, &mut rng);+async fn load_postgres_settings(pool: &PgPool) -> anyhow::Result<Vec<(String, String)>> {+ let mut settings = Vec::new();+ for name in [+ "server_version",+ "max_connections",+ "shared_buffers",+ "work_mem",+ "maintenance_work_mem",+ "effective_cache_size",+ "max_wal_size",+ "checkpoint_timeout",+ "autovacuum",+ "autovacuum_naptime",+ "autovacuum_max_workers",+ ] {+ let value: String = sqlx::query_scalar("SELECT current_setting($1)")+ .bind(name)+ .fetch_one(pool)+ .await+ .with_context(|| format!("read PostgreSQL setting {name}"))?;+ settings.push((name.to_owned(), value));+ }+ Ok(settings)+}- if args.skip_populate {- if !schema::table_exists(&pool).await? {- anyhow::bail!("--skip-populate but flags_person_lookup table does not exist");+fn adjusted_open_rates(+ phase: &PhaseSpec,+ creation_percent: u8,+) -> anyhow::Result<[RateSpec; OpClass::COUNT]> {+ let mut rates = phase.rates;+ if phase.name == rates::PhaseName::CatchUp || creation_percent == 0 {+ return Ok(rates);+ }+ let creation_rate =+ rates[OpClass::PersonUpsert.index()].target.get() * f64::from(creation_percent) / 100.0;+ let distinct_id = &mut rates[OpClass::DistinctIdAssignment.index()];+ anyhow::ensure!(+ distinct_id.target.get() >= creation_rate,+ "creation rate {creation_rate:.1}/s exceeds distinct ID target {:.1}/s in {}",+ distinct_id.target.get(),+ phase.name.as_str()+ );+ distinct_id.target = RatePerSecond::new(distinct_id.target.get() - creation_rate);+ Ok(rates)+}++fn projected_growth(args: &BenchmarkArgs, phases: &[PhaseSpec]) -> anyhow::Result<WorldGrowth> {+ let mut person_creations = 0.0;+ let mut distinct_id_assignments = 0.0;+ let fresh_fraction = 1.0 - f64::from(args.stale_replay_percent) / 100.0;+ for phase in phases {+ // Catch-up mutates existing entities so its closed feeds stay memory-bounded.+ if phase.name == rates::PhaseName::CatchUp {+ continue;}- tracing::info!("skipping population");- } else {- schema::create_schema(&pool).await?;+ let duration = phase.duration.as_secs_f64();+ let rates = adjusted_open_rates(phase, args.creation_percent)?;+ person_creations += phase.rate_for(OpClass::PersonUpsert).target.get()+ * f64::from(args.creation_percent)+ / 100.0+ * duration;+ distinct_id_assignments +=+ rates[OpClass::DistinctIdAssignment.index()].target.get() * fresh_fraction * duration;+ }+ Ok(WorldGrowth::new(+ PersonCreationCount::new(with_preflight_headroom(person_creations)),+ world::DistinctIdAssignmentCount::new(with_preflight_headroom(distinct_id_assignments)),+ ))+}- let pop_start = Instant::now();- population::populate(&pool, &storage, ®istry, args.batch_size).await?;- tracing::info!(- elapsed_secs = pop_start.elapsed().as_secs(),- "population complete"- );+fn with_preflight_headroom(value: f64) -> u64 {+ (value * GROWTH_PREFLIGHT_HEADROOM)+ .ceil()+ .min(u64::MAX as f64) as u64+}++fn bytes_mib(bytes: u64) -> f64 {+ bytes as f64 / (1024.0 * 1024.0)+}++fn enforce_gate_result(+ profile: BenchmarkProfile,+ gates: &GateEvaluation,+ output: &Path,+) -> anyhow::Result<()> {+ if profile == BenchmarkProfile::Gate && !gates.passed {+ anyhow::bail!("benchmark gate failed; see {}", output.display());}+ Ok(())+}- let data = build_benchmark_data(registry);- tracing::info!(- teams_with_merges = data.team_cdf.len(),- "benchmark data ready"+async fn drive_open_load(+ clock: &PhaseClock,+ duration: Duration,+ schedule: &mut ArrivalSchedule,+ ingress: &mut ExecutorIngress,+ runtime: &mut ExecutorRuntime,+ workload: &mut WorkloadContext<'_>,+ metrics: &mut PhaseMetrics<'_>,+) -> anyhow::Result<()> {+ let deadline = tokio::time::Instant::now() + duration;+ let mut interval = tokio::time::interval_at(+ tokio::time::Instant::now() + Duration::from_secs(collector::DEFAULT_INTERVAL_SECS),+ Duration::from_secs(collector::DEFAULT_INTERVAL_SECS),);+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);- metrics::reset_stats(&pool).await;+ loop {+ let next_arrival = schedule.peek_next_at();+ tokio::select! {+ () = tokio::time::sleep_until(deadline) => break,+ completion = runtime.completion_receiver_mut().recv() => {+ let completion = completion.context("executor completion stream closed during phase")?;+ record_completion(&mut metrics.collector, workload, completion)?;+ }+ result = wait_for_arrival(clock, next_arrival) => {+ result?;+ let now = clock.now()?;+ while let Some(arrival) = schedule.pop_due(now)? {+ let operations =+ resolve_arrival(workload, arrival.class, arrival.scheduled_at, true)?;+ for operation in operations {+ dispatch_open(clock, ingress, workload, &mut metrics.collector, operation)?;+ }+ }+ }+ _ = interval.tick() => {+ flush_interval(+ clock.now()?.as_nanos().min(duration_as_nanos(duration)),+ metrics,+ )?;+ }+ sample = metrics.pg_receiver.recv() => {+ let sample = sample.context("PostgreSQL sampler stopped during phase")?;+ record_pg_sample(sample, metrics)?;+ }+ }+ }+ Ok(())+}- let mut results = Vec::new();+#[derive(Debug)]+struct WriterOperationSenders {+ person: mpsc::Sender<OpDescriptor>,+ distinct_id: mpsc::Sender<OpDescriptor>,+ merge: mpsc::Sender<OpDescriptor>,+}++impl WriterOperationSenders {+ async fn send(&self, class: OpClass, operation: OpDescriptor) -> anyhow::Result<()> {+ let sender = match class {+ OpClass::PersonUpsert => &self.person,+ OpClass::DistinctIdAssignment => &self.distinct_id,+ OpClass::Merge => &self.merge,+ OpClass::CanonicalRead => anyhow::bail!("canonical reads cannot use a writer pump"),+ };+ sender+ .send(operation)+ .await+ .map_err(|_| anyhow::anyhow!("{:?} writer pump stopped", class))+ }+}++fn spawn_writer_pump(+ class: OpClass,+ dispatcher: BoundedDispatcher,+ mut operation_receiver: mpsc::Receiver<OpDescriptor>,+ request_sender: mpsc::Sender<OpClass>,+ dispatch_sender: mpsc::Sender<DispatchRecord>,+ clock: PhaseClock,+ stop: CancellationToken,+) -> JoinHandle<anyhow::Result<BoundedDispatcher>> {+ tokio::spawn(async move {+ loop {+ tokio::select! {+ biased;+ () = stop.cancelled() => break,+ result = request_sender.send(class) => {+ if result.is_err() {+ break;+ }+ }+ }+ let Some(operation) = operation_receiver.recv().await else {+ break;+ };+ let dispatch = dispatcher+ .dispatch_with_backpressure(operation, &clock)+ .await?;+ if dispatch_sender.send(dispatch).await.is_err() {+ break;+ }+ }+ Ok(dispatcher)+ })+}++#[allow(clippy::too_many_arguments)]+async fn drive_catch_up_load(+ clock: &PhaseClock,+ duration: Duration,+ read_schedule: &mut ArrivalSchedule,+ read_dispatcher: &mut BoundedDispatcher,+ writer_senders: &WriterOperationSenders,+ request_receiver: &mut mpsc::Receiver<OpClass>,+ dispatch_receiver: &mut mpsc::Receiver<DispatchRecord>,+ runtime: &mut ExecutorRuntime,+ workload: &mut WorkloadContext<'_>,+ metrics: &mut PhaseMetrics<'_>,+) -> anyhow::Result<()> {+ let deadline = tokio::time::Instant::now() + duration;+ let mut interval = tokio::time::interval_at(+ tokio::time::Instant::now() + Duration::from_secs(collector::DEFAULT_INTERVAL_SECS),+ Duration::from_secs(collector::DEFAULT_INTERVAL_SECS),+ );+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);- tracing::info!("=== Phase 1: Sustained property updates ===");- let r = workloads::phase_property_updates(&pool, &data, &args).await?;- tracing::info!(ops = r.latency.count, errors = r.errors, "phase 1 complete");- results.push(r);+ loop {+ let next_read = read_schedule.peek_next_at();+ tokio::select! {+ () = tokio::time::sleep_until(deadline) => break,+ completion = runtime.completion_receiver_mut().recv() => {+ let completion = completion.context("executor completion stream closed during catch-up")?;+ record_completion(&mut metrics.collector, workload, completion)?;+ }+ result = wait_for_arrival(clock, next_read) => {+ result?;+ let now = clock.now()?;+ while let Some(arrival) = read_schedule.pop_due(now)? {+ anyhow::ensure!(arrival.class == OpClass::CanonicalRead, "closed writer entered the open arrival schedule");+ let operations =+ resolve_arrival(workload, arrival.class, arrival.scheduled_at, false)?;+ for operation in operations {+ dispatch_bounded(+ clock,+ read_dispatcher,+ workload,+ &mut metrics.collector,+ operation,+ )?;+ }+ }+ }+ request = request_receiver.recv() => {+ let class = request.context("all catch-up writer pumps stopped")?;+ let scheduled_at = clock.now()?;+ let operations = resolve_arrival(workload, class, scheduled_at, false)?;+ anyhow::ensure!(operations.len() == 1, "catch-up writer generated a paired operation");+ writer_senders+ .send(+ class,+ operations+ .into_iter()+ .next()+ .expect("one catch-up operation"),+ )+ .await?;+ }+ dispatch = dispatch_receiver.recv() => {+ let dispatch = dispatch.context("all catch-up dispatch streams stopped")?;+ record_dispatch(&mut metrics.collector, workload, dispatch)?;+ }+ _ = interval.tick() => {+ flush_interval(+ clock.now()?.as_nanos().min(duration_as_nanos(duration)),+ metrics,+ )?;+ }+ sample = metrics.pg_receiver.recv() => {+ let sample = sample.context("PostgreSQL sampler stopped during catch-up")?;+ record_pg_sample(sample, metrics)?;+ }+ }+ }+ Ok(())+}- metrics::reset_stats(&pool).await;+async fn join_writer_pumps(+ person_task: JoinHandle<anyhow::Result<BoundedDispatcher>>,+ distinct_id_task: JoinHandle<anyhow::Result<BoundedDispatcher>>,+ merge_task: JoinHandle<anyhow::Result<BoundedDispatcher>>,+ dispatch_receiver: &mut mpsc::Receiver<DispatchRecord>,+ runtime: &mut ExecutorRuntime,+ collector: &mut PhaseCollector,+ workload: &mut WorkloadContext<'_>,+) -> anyhow::Result<(BoundedDispatcher, BoundedDispatcher, BoundedDispatcher)> {+ let joins = async move {+ let (person, distinct_id, merge) = tokio::join!(person_task, distinct_id_task, merge_task);+ Ok::<_, anyhow::Error>((+ person.context("join person writer pump")??,+ distinct_id.context("join distinct ID writer pump")??,+ merge.context("join merge writer pump")??,+ ))+ };+ tokio::pin!(joins);+ let mut first_error = None;+ let dispatchers = loop {+ tokio::select! {+ result = &mut joins => break result?,+ completion = runtime.completion_receiver_mut().recv() => {+ if let Some(completion) = completion {+ if let Err(error) = record_completion(collector, workload, completion) {+ first_error.get_or_insert(error);+ }+ }+ }+ dispatch = dispatch_receiver.recv() => {+ if let Some(dispatch) = dispatch {+ if let Err(error) = record_dispatch(collector, workload, dispatch) {+ first_error.get_or_insert(error);+ }+ }+ }+ }+ };+ while let Ok(dispatch) = dispatch_receiver.try_recv() {+ if let Err(error) = record_dispatch(collector, workload, dispatch) {+ first_error.get_or_insert(error);+ }+ }+ match first_error {+ Some(error) => Err(error),+ None => Ok(dispatchers),+ }+}- tracing::info!("=== Phase 2: Identification appends ===");- let r = workloads::phase_identification_appends(&pool, &data, &args).await?;- tracing::info!(ops = r.latency.count, errors = r.errors, "phase 2 complete");- results.push(r);+async fn wait_for_arrival(+ clock: &PhaseClock,+ next_arrival: Option<ops::NanosSincePhaseStart>,+) -> anyhow::Result<()> {+ match next_arrival {+ Some(next_arrival) => clock.wait_until(next_arrival).await.map_err(Into::into),+ None => std::future::pending().await,+ }+}- metrics::reset_stats(&pool).await;+fn dispatch_open(+ clock: &PhaseClock,+ ingress: &mut ExecutorIngress,+ workload: &mut WorkloadContext<'_>,+ collector: &mut PhaseCollector,+ operation: OpDescriptor,+) -> anyhow::Result<()> {+ let class = operation.class();+ let dispatch = ingress+ .dispatcher_mut(class)+ .try_dispatch_at(operation, clock.now()?)?;+ record_dispatch(collector, workload, dispatch)+}- tracing::info!("=== Phase 3: Merge workload ===");- let r = workloads::phase_merges(&pool, &data, &args, "Merges", None, None).await?;- tracing::info!(ops = r.latency.count, errors = r.errors, "phase 3 complete");- results.push(r);+fn dispatch_bounded(+ clock: &PhaseClock,+ dispatcher: &mut BoundedDispatcher,+ workload: &mut WorkloadContext<'_>,+ collector: &mut PhaseCollector,+ operation: OpDescriptor,+) -> anyhow::Result<()> {+ let dispatch = dispatcher.try_dispatch_at(operation, clock.now()?)?;+ record_dispatch(collector, workload, dispatch)+}- metrics::reset_stats(&pool).await;+fn record_dispatch(+ collector: &mut PhaseCollector,+ workload: &mut WorkloadContext<'_>,+ dispatch: DispatchRecord,+) -> anyhow::Result<()> {+ collector.record_dispatch(dispatch)?;+ if dispatch.outcome != DispatchOutcome::Enqueued {+ workload.tracker.record_failed_dispatch(+ workload.world,+ dispatch.operation_id,+ dispatch.outcome,+ )?;+ }+ Ok(())+}- tracing::info!(- burst_concurrency = args.concurrency * args.burst_factor,- "=== Phase 4: Burst merge storm ==="- );- let burst_concurrency = args.concurrency * args.burst_factor;- let burst_duration = args.duration_secs / 4;- let burst_name = format!("Burst merges ({}x)", args.burst_factor);- let r = workloads::phase_merges(- &pool,- &data,- &args,- &burst_name,- Some(burst_concurrency),- Some(burst_duration),- )- .await?;- tracing::info!(ops = r.latency.count, errors = r.errors, "phase 4 complete");- results.push(r);-- metrics::reset_stats(&pool).await;-- tracing::info!("=== Phase 5: Concurrent reads + writes ===");- let (write_r, read_r, query_plan) =- workloads::phase_concurrent_reads_writes(&pool, &data, &args).await?;- tracing::info!(- write_ops = write_r.latency.count,- read_ops = read_r.latency.count,- "phase 5 complete"+fn resolve_arrival(+ workload: &mut WorkloadContext<'_>,+ class: OpClass,+ scheduled_at: ops::NanosSincePhaseStart,+ allow_creation: bool,+) -> anyhow::Result<ResolvedOperations> {+ let WorkloadContext {+ world,+ rng,+ growth,+ world_config,+ memory_limit,+ args,+ tracker,+ } = workload;+ let memory_limit = *memory_limit;+ let mut grew = false;+ let operations = match class {+ OpClass::PersonUpsert if allow_creation && chance(rng, args.creation_percent) => {+ let creation = world.resolve_creation(scheduled_at)?;+ tracker.register_creation(+ creation.activation,+ creation.person_upsert.operation_id,+ creation.distinct_id_assignment.operation_id,+ )?;+ growth.creation();+ grew = true;+ ResolvedOperations::Pair(creation.person_upsert, creation.distinct_id_assignment)+ }+ OpClass::PersonUpsert => {+ let replay = if chance(rng, args.stale_replay_percent) {+ ReplayMode::Stale+ } else {+ ReplayMode::Fresh+ };+ ResolvedOperations::One(world.resolve_person_upsert(scheduled_at, replay)?)+ }+ OpClass::DistinctIdAssignment => {+ let mode = if chance(rng, args.stale_replay_percent) {+ AssignmentMode::StaleReplay+ } else if allow_creation {+ AssignmentMode::New+ } else {+ AssignmentMode::FreshExisting+ };+ let assignment = world.resolve_distinct_id_assignment(scheduled_at, mode)?;+ if let Some(token) = assignment.activation {+ tracker.register_distinct_id(assignment.operation.operation_id, token)?;+ growth.distinct_id();+ grew = true;+ }+ ResolvedOperations::One(assignment.operation)+ }+ OpClass::Merge => {+ let operation = if chance(rng, args.whale_merge_percent) {+ match world.resolve_whale_merge(scheduled_at) {+ Ok(operation) => operation,+ Err(WorldError::NoEligiblePerson) => world.resolve_full_merge(scheduled_at)?,+ Err(error) => return Err(error.into()),+ }+ } else {+ world.resolve_full_merge(scheduled_at)?+ };+ ResolvedOperations::One(operation)+ }+ OpClass::CanonicalRead => {+ let mode = if chance(rng, args.read_miss_percent) {+ ReadMode::Miss+ } else {+ ReadMode::Hit+ };+ ResolvedOperations::One(world.resolve_read(scheduled_at, mode)?)+ }+ };+ if grew {+ ensure_runtime_memory(world_config, growth, memory_limit)?;+ }+ Ok(operations)+}++#[derive(Debug)]+enum ResolvedOperations {+ One(OpDescriptor),+ Pair(OpDescriptor, OpDescriptor),+}++impl ResolvedOperations {+ const fn len(&self) -> usize {+ match self {+ Self::One(_) => 1,+ Self::Pair(_, _) => 2,+ }+ }+}++impl IntoIterator for ResolvedOperations {+ type Item = OpDescriptor;+ type IntoIter = std::iter::Flatten<std::array::IntoIter<Option<OpDescriptor>, 2>>;++ fn into_iter(self) -> Self::IntoIter {+ match self {+ Self::One(operation) => [Some(operation), None],+ Self::Pair(first, second) => [Some(first), Some(second)],+ }+ .into_iter()+ .flatten()+ }+}++fn chance(rng: &mut impl Rng, percent: u8) -> bool {+ rng.gen_ratio(u32::from(percent), 100)+}++fn ensure_runtime_memory(+ world_config: &WorldConfig,+ growth: &RuntimeGrowth,+ memory_limit: u64,+) -> anyhow::Result<()> {+ let estimate = WorldState::estimate_memory(world_config, growth.as_world_growth())?;+ anyhow::ensure!(+ estimate.total_bytes <= memory_limit,+ "world state reached {:.1} MiB, above the configured limit {:.1} MiB",+ bytes_mib(estimate.total_bytes),+ bytes_mib(memory_limit));- results.push(write_r);- results.push(read_r);+ Ok(())+}++fn record_completion(+ collector: &mut PhaseCollector,+ workload: &mut WorkloadContext<'_>,+ completion: CompletionRecord,+) -> anyhow::Result<()> {+ collector.record_completion(&completion)?;+ workload+ .tracker+ .record_completion(workload.world, &completion)+}++async fn run_pre_hooks(+ store: &StoreHandles<'_>,+ phase_id: PhaseId,+ hooks: &[Hook],+ sink: &mut JsonlSink,+) -> anyhow::Result<(Duration, Vec<PgDeltaRecord>)> {+ let (database_url, pool) = (store.database_url, store.pool);+ let started = Instant::now();+ let mut records = Vec::new();+ for hook in hooks {+ match hook {+ Hook::Vacuum => {+ let sampler = PgSampler::connect(database_url, phase_id).await?;+ let before = sampler.sample().await?;+ population::vacuum_analyze_checkpoint(pool).await?;+ let after = sampler.sample().await?;+ let record = pg_sampler::delta(&before, &after)?;+ sink.write(&record)?;+ records.push(record);+ sampler.close().await;+ }+ }+ }+ Ok((started.elapsed(), records))+}++type PgSample = PgDeltaRecord;++fn spawn_pg_sampler(+ database_url: String,+ phase_id: PhaseId,+) -> (CancellationToken, mpsc::Receiver<PgSample>, JoinHandle<()>) {+ let cancellation = CancellationToken::new();+ let task_cancellation = cancellation.clone();+ let (sender, receiver) = mpsc::channel(1_024);+ let task = tokio::spawn(async move {+ let mut sampler = match PgSampler::connect(&database_url, phase_id).await {+ Ok(sampler) => sampler,+ Err(error) => {+ tracing::warn!(+ error = %error,+ phase_id = phase_id.get(),+ "PostgreSQL sampler unavailable for benchmark phase"+ );+ task_cancellation.cancelled().await;+ return;+ }+ };+ if !sample_pg_delta(&mut sampler, &sender, phase_id).await {+ sampler.close().await;+ return;+ }+ let mut interval = tokio::time::interval(PG_SAMPLE_INTERVAL);+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ interval.tick().await;+ loop {+ tokio::select! {+ () = task_cancellation.cancelled() => {+ sample_pg_delta(&mut sampler, &sender, phase_id).await;+ break;+ }+ _ = interval.tick() => {+ if !sample_pg_delta(&mut sampler, &sender, phase_id).await {+ break;+ }+ }+ }+ }+ sampler.close().await;+ });+ (cancellation, receiver, task)+}++async fn sample_pg_delta(+ sampler: &mut PgSampler,+ sender: &mpsc::Sender<PgSample>,+ phase_id: PhaseId,+) -> bool {+ match sampler.sample_delta().await {+ Ok(Some(record)) => try_send_pg_sample(sender, record, phase_id),+ Ok(None) => true,+ Err(error) => {+ tracing::warn!(+ error = %error,+ phase_id = phase_id.get(),+ "PostgreSQL benchmark sample failed"+ );+ true+ }+ }+}++fn try_send_pg_sample(+ sender: &mpsc::Sender<PgSample>,+ sample: PgSample,+ phase_id: PhaseId,+) -> bool {+ match sender.try_send(sample) {+ Ok(()) => true,+ Err(mpsc::error::TrySendError::Closed(_)) => false,+ Err(mpsc::error::TrySendError::Full(_)) => {+ tracing::warn!(+ phase_id = phase_id.get(),+ "PostgreSQL benchmark sample dropped because the channel is full"+ );+ true+ }+ }+}- metrics::reset_stats(&pool).await;+fn drain_pg_samples(metrics: &mut PhaseMetrics<'_>) -> anyhow::Result<()> {+ while let Ok(sample) = metrics.pg_receiver.try_recv() {+ record_pg_sample(sample, metrics)?;+ }+ Ok(())+}- tracing::info!("=== Phase 6: Post-burst steady-state recovery ===");- let r = workloads::phase_merges(&pool, &data, &args, "Post-burst merges", None, None).await?;- tracing::info!(ops = r.latency.count, errors = r.errors, "phase 6 complete");- results.push(r);+fn record_pg_sample(sample: PgSample, metrics: &mut PhaseMetrics<'_>) -> anyhow::Result<()> {+ metrics.sink.write(&sample)?;+ metrics.pg_records.push(sample);+ Ok(())+}- report::print_report(&args, &results, &query_plan);+fn finish_phase(+ phase: &PhaseSpec,+ timings: PhaseTimings,+ clock: PhaseClock,+ mut metrics: PhaseMetrics<'_>,+) -> anyhow::Result<PhaseResult> {+ let ended_at = clock.now()?.as_nanos();+ flush_interval(ended_at, &mut metrics)?;+ let duration_nanos = duration_as_nanos(phase.duration);+ let post_deadline_duration_nanos = ended_at.saturating_sub(duration_nanos);+ let summary = metrics.collector.finish_phase(+ duration_nanos,+ duration_as_nanos(timings.drain),+ post_deadline_duration_nanos,+ );+ metrics.sink.write(&summary)?;+ Ok(PhaseResult {+ name: phase.name,+ duration: phase.duration,+ pre_hook_duration: timings.pre_hook,+ targets: phase.rates,+ summary,+ intervals: metrics.intervals,+ pg: metrics.pg_records,+ })+}+fn flush_interval(ended_at_nanos: u64, metrics: &mut PhaseMetrics<'_>) -> anyhow::Result<()> {+ let last_interval_end = metrics+ .intervals+ .last()+ .map_or(0, |interval| interval.ended_at_nanos);+ if ended_at_nanos <= last_interval_end {+ return Ok(());+ }+ let interval = metrics.collector.finish_interval(ended_at_nanos);+ metrics.sink.write(&interval)?;+ metrics.intervals.push(interval);Ok(())}++fn duration_as_nanos(duration: Duration) -> u64 {+ u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::benchmark::ops::{CompletionTimestamps, NanosSincePhaseStart};++ fn success(operation_id: OperationId, class: OpClass) -> CompletionRecord {+ let at = NanosSincePhaseStart::from_nanos(PhaseId::new(1), 0);+ CompletionRecord {+ operation_id,+ class,+ timestamps: CompletionTimestamps::try_new(at, at, at, at).expect("ordered timestamps"),+ outcome: CompletionOutcome::Success,+ retry_affected: false,+ deadlock_affected: false,+ retry_attempts: 0,+ deadlock_attempts: 0,+ }+ }++ #[test]+ fn paired_creation_rate_preserves_the_total_distinct_id_target() {+ let phase = standard_phases(BenchmarkProfile::Gate, None)+ .into_iter()+ .find(|phase| phase.name == rates::PhaseName::PeakMix)+ .expect("peak phase");+ let adjusted = adjusted_open_rates(&phase, 5).expect("valid paired rate");+ let paired_rate = phase.rate_for(OpClass::PersonUpsert).target.get() * 0.05;++ assert_eq!(+ adjusted[OpClass::DistinctIdAssignment.index()].target.get() + paired_rate,+ phase.rate_for(OpClass::DistinctIdAssignment).target.get()+ );+ }++ #[test]+ fn creation_tracker_activates_only_after_both_successes() {+ let mut world = WorldState::new(WorldConfig {+ team_count: 1,+ initial_person_count: 2,+ ..WorldConfig::default()+ })+ .expect("world");+ let before = world.live_person_count();+ let scheduled_at = NanosSincePhaseStart::from_nanos(PhaseId::new(1), 0);+ let creation = world.resolve_creation(scheduled_at).expect("creation");+ let person_id = creation.person_upsert.operation_id;+ let distinct_id = creation.distinct_id_assignment.operation_id;+ let mut tracker = ActivationTracker::default();+ tracker+ .register_creation(creation.activation, person_id, distinct_id)+ .expect("pending creation");++ tracker+ .record_completion(&mut world, &success(person_id, OpClass::PersonUpsert))+ .expect("first half");+ assert_eq!(world.live_person_count(), before);++ tracker+ .record_completion(+ &mut world,+ &success(distinct_id, OpClass::DistinctIdAssignment),+ )+ .expect("second half");+ assert_eq!(world.live_person_count(), before + 1);+ tracker.ensure_empty().expect("all activations resolved");+ }++ #[test]+ fn smoke_reports_failed_gates_but_gate_profile_returns_an_error() {+ let evaluation = GateEvaluation {+ passed: false,+ harness_limited: true,+ checks: Vec::new(),+ unverified_qualifications: Vec::new(),+ };+ let output = Path::new("tmp/result.jsonl");++ enforce_gate_result(BenchmarkProfile::Smoke, &evaluation, output)+ .expect("smoke remains diagnostic");+ assert!(enforce_gate_result(BenchmarkProfile::Gate, &evaluation, output).is_err());+ }+}diff --git a/rust/flags-consumer/src/benchmark/ops.rs b/rust/flags-consumer/src/benchmark/ops.rsnew file mode 100644index 000000000000..bb2c808c3064--- /dev/null+++ b/rust/flags-consumer/src/benchmark/ops.rs@@ -0,0 +1,470 @@+use std::fmt;++use serde::{Deserialize, Serialize};+use serde_json::Value;+use uuid::Uuid;++#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum OpClass {+ PersonUpsert,+ DistinctIdAssignment,+ Merge,+ CanonicalRead,+}++impl OpClass {+ pub const COUNT: usize = 4;+ pub const ALL: [Self; Self::COUNT] = [+ Self::PersonUpsert,+ Self::DistinctIdAssignment,+ Self::Merge,+ Self::CanonicalRead,+ ];+ pub const WRITE_CLASSES: [Self; 3] =+ [Self::PersonUpsert, Self::DistinctIdAssignment, Self::Merge];++ pub const fn index(self) -> usize {+ match self {+ Self::PersonUpsert => 0,+ Self::DistinctIdAssignment => 1,+ Self::Merge => 2,+ Self::CanonicalRead => 3,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]+#[serde(transparent)]+pub struct OperationId(pub u64);++#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]+#[serde(transparent)]+pub struct PhaseId(u64);++impl PhaseId {+ pub const fn new(value: u64) -> Self {+ Self(value)+ }++ pub const fn get(self) -> u64 {+ self.0+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]+pub struct NanosSincePhaseStart {+ phase_id: PhaseId,+ nanos: u64,+}++impl NanosSincePhaseStart {+ pub(super) const fn from_nanos(phase_id: PhaseId, nanos: u64) -> Self {+ Self { phase_id, nanos }+ }++ pub const fn phase_id(self) -> PhaseId {+ self.phase_id+ }++ pub const fn as_nanos(self) -> u64 {+ self.nanos+ }++ pub(super) const fn checked_add(self, nanos: u64) -> Option<Self> {+ match self.nanos.checked_add(nanos) {+ Some(value) => Some(Self::from_nanos(self.phase_id, value)),+ None => None,+ }+ }++ pub fn ensure_same_phase(self, other: Self) -> Result<(), PhaseMismatch> {+ if self.phase_id == other.phase_id {+ return Ok(());+ }+ Err(PhaseMismatch {+ expected: self.phase_id,+ actual: other.phase_id,+ })+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct PhaseMismatch {+ pub expected: PhaseId,+ pub actual: PhaseId,+}++impl fmt::Display for PhaseMismatch {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(+ formatter,+ "phase {} does not match phase {}",+ self.actual.get(),+ self.expected.get()+ )+ }+}++impl std::error::Error for PhaseMismatch {}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct PersonUpsertPayload {+ pub team_id: i32,+ pub person_uuid: Uuid,+ pub properties: Value,+ pub version: i64,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct DistinctIdAssignmentPayload {+ pub team_id: i32,+ pub person_uuid: Uuid,+ pub distinct_id: Box<str>,+ pub version: i64,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct DistinctIdMove {+ pub distinct_id: Box<str>,+ pub version: i64,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum MergeShape {+ Standard,+ Whale,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct FullMergePayload {+ pub team_id: i32,+ pub source_person_uuid: Uuid,+ pub target_person_uuid: Uuid,+ pub distinct_id_moves: Box<[DistinctIdMove]>,+ pub target_properties: Value,+ pub target_version: i64,+ pub source_tombstone_version: i64,+ pub shape: MergeShape,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "result", rename_all = "snake_case")]+pub enum ReadExpectation {+ Hit,+ Miss,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct CanonicalReadPayload {+ pub team_id: i32,+ pub distinct_id: Box<str>,+ pub expectation: ReadExpectation,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "type", content = "payload", rename_all = "snake_case")]+pub enum OpPayload {+ PersonUpsert(PersonUpsertPayload),+ DistinctIdAssignment(DistinctIdAssignmentPayload),+ FullMerge(FullMergePayload),+ CanonicalRead(CanonicalReadPayload),+}++impl OpPayload {+ pub const fn class(&self) -> OpClass {+ match self {+ Self::PersonUpsert(_) => OpClass::PersonUpsert,+ Self::DistinctIdAssignment(_) => OpClass::DistinctIdAssignment,+ Self::FullMerge(_) => OpClass::Merge,+ Self::CanonicalRead(_) => OpClass::CanonicalRead,+ }+ }+}++#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct OpDescriptor {+ pub operation_id: OperationId,+ pub scheduled_at: NanosSincePhaseStart,+ pub payload: OpPayload,+}++impl OpDescriptor {+ pub fn new(+ operation_id: OperationId,+ scheduled_at: NanosSincePhaseStart,+ payload: OpPayload,+ ) -> Self {+ Self {+ operation_id,+ scheduled_at,+ payload,+ }+ }++ pub const fn class(&self) -> OpClass {+ self.payload.class()+ }+}++#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct DispatchedOperation {+ descriptor: OpDescriptor,+ dispatched_at: NanosSincePhaseStart,+}++impl DispatchedOperation {+ pub fn try_new(+ descriptor: OpDescriptor,+ dispatched_at: NanosSincePhaseStart,+ ) -> Result<Self, TimestampOrderError> {+ descriptor+ .scheduled_at+ .ensure_same_phase(dispatched_at)+ .map_err(TimestampOrderError::PhaseMismatch)?;+ if descriptor.scheduled_at.as_nanos() > dispatched_at.as_nanos() {+ return Err(TimestampOrderError::DispatchBeforeSchedule);+ }+ Ok(Self {+ descriptor,+ dispatched_at,+ })+ }++ pub const fn descriptor(&self) -> &OpDescriptor {+ &self.descriptor+ }++ pub const fn operation_id(&self) -> OperationId {+ self.descriptor.operation_id+ }++ pub const fn class(&self) -> OpClass {+ self.descriptor.class()+ }++ pub const fn scheduled_at(&self) -> NanosSincePhaseStart {+ self.descriptor.scheduled_at+ }++ pub const fn dispatched_at(&self) -> NanosSincePhaseStart {+ self.dispatched_at+ }++ pub fn into_parts(self) -> (OpDescriptor, NanosSincePhaseStart) {+ (self.descriptor, self.dispatched_at)+ }++ pub fn completion_timestamps(+ &self,+ started_at: NanosSincePhaseStart,+ completed_at: NanosSincePhaseStart,+ ) -> Result<CompletionTimestamps, TimestampOrderError> {+ CompletionTimestamps::try_new(+ self.scheduled_at(),+ self.dispatched_at,+ started_at,+ completed_at,+ )+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+pub struct CompletionTimestamps {+ scheduled_at: NanosSincePhaseStart,+ dispatched_at: NanosSincePhaseStart,+ started_at: NanosSincePhaseStart,+ completed_at: NanosSincePhaseStart,+}++impl CompletionTimestamps {+ pub fn try_new(+ scheduled_at: NanosSincePhaseStart,+ dispatched_at: NanosSincePhaseStart,+ started_at: NanosSincePhaseStart,+ completed_at: NanosSincePhaseStart,+ ) -> Result<Self, TimestampOrderError> {+ scheduled_at+ .ensure_same_phase(dispatched_at)+ .and_then(|()| scheduled_at.ensure_same_phase(started_at))+ .and_then(|()| scheduled_at.ensure_same_phase(completed_at))+ .map_err(TimestampOrderError::PhaseMismatch)?;+ let timestamps = Self {+ scheduled_at,+ dispatched_at,+ started_at,+ completed_at,+ };+ if scheduled_at.as_nanos() > dispatched_at.as_nanos() {+ return Err(TimestampOrderError::DispatchBeforeSchedule);+ }+ if dispatched_at.as_nanos() > started_at.as_nanos() {+ return Err(TimestampOrderError::StartBeforeDispatch);+ }+ if started_at.as_nanos() > completed_at.as_nanos() {+ return Err(TimestampOrderError::CompletionBeforeStart);+ }+ Ok(timestamps)+ }++ pub const fn scheduled_at(self) -> NanosSincePhaseStart {+ self.scheduled_at+ }++ pub const fn dispatched_at(self) -> NanosSincePhaseStart {+ self.dispatched_at+ }++ pub const fn started_at(self) -> NanosSincePhaseStart {+ self.started_at+ }++ pub const fn completed_at(self) -> NanosSincePhaseStart {+ self.completed_at+ }++ pub const fn service_latency_nanos(self) -> u64 {+ self.completed_at.as_nanos() - self.started_at.as_nanos()+ }++ pub const fn schedule_latency_nanos(self) -> u64 {+ self.completed_at.as_nanos() - self.scheduled_at.as_nanos()+ }++ pub const fn queue_latency_nanos(self) -> u64 {+ self.started_at.as_nanos() - self.dispatched_at.as_nanos()+ }++ pub const fn dispatch_lag_nanos(self) -> u64 {+ self.dispatched_at.as_nanos() - self.scheduled_at.as_nanos()+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TimestampOrderError {+ PhaseMismatch(PhaseMismatch),+ DispatchBeforeSchedule,+ StartBeforeDispatch,+ CompletionBeforeStart,+}++impl fmt::Display for TimestampOrderError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ let message = match self {+ Self::PhaseMismatch(error) => return error.fmt(formatter),+ Self::DispatchBeforeSchedule => "dispatch timestamp precedes schedule timestamp",+ Self::StartBeforeDispatch => "start timestamp precedes dispatch timestamp",+ Self::CompletionBeforeStart => "completion timestamp precedes start timestamp",+ };+ formatter.write_str(message)+ }+}++impl std::error::Error for TimestampOrderError {}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(tag = "status", rename_all = "snake_case")]+pub enum CompletionOutcome {+ Success,+ Error { message: Box<str> },+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct CompletionRecord {+ pub operation_id: OperationId,+ pub class: OpClass,+ pub timestamps: CompletionTimestamps,+ pub outcome: CompletionOutcome,+ pub retry_affected: bool,+ pub deadlock_affected: bool,+ pub retry_attempts: u32,+ pub deadlock_attempts: u32,+}++impl CompletionRecord {+ pub const fn service_latency_nanos(&self) -> u64 {+ self.timestamps.service_latency_nanos()+ }++ pub const fn schedule_latency_nanos(&self) -> u64 {+ self.timestamps.schedule_latency_nanos()+ }++ pub const fn queue_latency_nanos(&self) -> u64 {+ self.timestamps.queue_latency_nanos()+ }++ pub const fn dispatch_lag_nanos(&self) -> u64 {+ self.timestamps.dispatch_lag_nanos()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn at(nanos: u64) -> NanosSincePhaseStart {+ NanosSincePhaseStart::from_nanos(PhaseId::new(1), nanos)+ }++ #[test]+ fn completion_timestamps_reject_every_out_of_order_boundary() {+ for (timestamps, expected) in [+ (+ (at(2), at(1), at(3), at(4)),+ TimestampOrderError::DispatchBeforeSchedule,+ ),+ (+ (at(1), at(3), at(2), at(4)),+ TimestampOrderError::StartBeforeDispatch,+ ),+ (+ (at(1), at(2), at(4), at(3)),+ TimestampOrderError::CompletionBeforeStart,+ ),+ ] {+ assert_eq!(+ CompletionTimestamps::try_new(+ timestamps.0,+ timestamps.1,+ timestamps.2,+ timestamps.3,+ ),+ Err(expected)+ );+ }++ assert!(matches!(+ CompletionTimestamps::try_new(+ at(1),+ NanosSincePhaseStart::from_nanos(PhaseId::new(2), 2),+ at(3),+ at(4),+ ),+ Err(TimestampOrderError::PhaseMismatch(_))+ ));+ }++ #[test]+ fn dispatched_operation_carries_the_validated_scheduler_timestamp() {+ let descriptor = OpDescriptor::new(+ OperationId(7),+ at(10),+ OpPayload::CanonicalRead(CanonicalReadPayload {+ team_id: 1,+ distinct_id: "[email protected]".into(),+ expectation: ReadExpectation::Hit,+ }),+ );+ let dispatched = DispatchedOperation::try_new(descriptor, at(12)).expect("valid dispatch");++ let timestamps = dispatched+ .completion_timestamps(at(15), at(20))+ .expect("ordered timestamps");++ assert_eq!(timestamps.dispatch_lag_nanos(), 2);+ assert_eq!(timestamps.queue_latency_nanos(), 3);+ assert_eq!(timestamps.service_latency_nanos(), 5);+ }+}diff --git a/rust/flags-consumer/src/benchmark/pg_sampler.rs b/rust/flags-consumer/src/benchmark/pg_sampler.rsnew file mode 100644index 000000000000..2d8ca043c7b2--- /dev/null+++ b/rust/flags-consumer/src/benchmark/pg_sampler.rs@@ -0,0 +1,423 @@+use std::time::Duration;++use anyhow::Context;+use chrono::{DateTime, Utc};+use serde::Serialize;+use sqlx::postgres::PgPoolOptions;+use sqlx::PgPool;++use super::ops::{PhaseId, PhaseMismatch};++const TABLE_STATS_SQL: &str = r#"+ WITH target(parent_name) AS (+ VALUES ('flags_person'::text), ('flags_distinct_id_map'::text)+ )+ SELECT+ target.parent_name,+ COALESCE(SUM(stats.n_tup_ins), 0)::bigint,+ COALESCE(SUM(stats.n_tup_upd), 0)::bigint,+ COALESCE(SUM(stats.n_tup_del), 0)::bigint,+ COALESCE(SUM(stats.n_tup_hot_upd), 0)::bigint,+ COALESCE(SUM(stats.n_dead_tup), 0)::bigint,+ COALESCE(SUM(stats.vacuum_count), 0)::bigint,+ COALESCE(SUM(stats.autovacuum_count), 0)::bigint,+ COALESCE(SUM(pg_relation_size(child.oid)), 0)::bigint,+ COALESCE(SUM(pg_indexes_size(child.oid)), 0)::bigint,+ COUNT(child.oid)::bigint+ FROM target+ LEFT JOIN pg_class parent+ ON parent.relname = target.parent_name+ AND parent.relnamespace = current_schema()::regnamespace+ LEFT JOIN pg_inherits inheritance ON inheritance.inhparent = parent.oid+ LEFT JOIN pg_class child+ ON child.oid = inheritance.inhrelid AND child.relkind = 'r'+ LEFT JOIN pg_stat_user_tables stats ON stats.relid = child.oid+ GROUP BY target.parent_name+ ORDER BY target.parent_name+"#;++const WAL_POSITION_SQL: &str =+ "SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), '0/0'::pg_lsn)::bigint";+const SAMPLE_QUERY_TIMEOUT: Duration = Duration::from_secs(30);++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum TableGroup {+ Person,+ DistinctIdMap,+}++impl TableGroup {+ const ALL: [Self; 2] = [Self::Person, Self::DistinctIdMap];++ const fn table_name(self) -> &'static str {+ match self {+ Self::Person => "flags_person",+ Self::DistinctIdMap => "flags_distinct_id_map",+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+pub struct TableSnapshot {+ pub group: TableGroup,+ pub inserts: u64,+ pub updates: u64,+ pub deletes: u64,+ pub hot_updates: u64,+ pub dead_tuples: u64,+ pub vacuums: u64,+ pub autovacuums: u64,+ pub heap_bytes: u64,+ pub index_bytes: u64,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(tag = "status", rename_all = "snake_case")]+pub enum WalSnapshot {+ Available { bytes_from_origin: u64 },+ Unavailable { reason: Box<str> },+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct PgSnapshot {+ pub phase_id: PhaseId,+ pub sampled_at: DateTime<Utc>,+ pub tables: [TableSnapshot; 2],+ pub wal: WalSnapshot,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+pub struct TableDelta {+ pub group: TableGroup,+ pub inserts: u64,+ pub updates: u64,+ pub deletes: u64,+ pub hot_updates: u64,+ pub dead_tuples: u64,+ pub vacuums: u64,+ pub autovacuums: u64,+ pub heap_bytes: u64,+ pub index_bytes: u64,+ pub stats_reset_detected: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(tag = "status", rename_all = "snake_case")]+pub enum WalDelta {+ Available { bytes: u64 },+ Unavailable { reason: Box<str> },+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct PgDeltaRecord {+ pub record_type: &'static str,+ pub phase_id: PhaseId,+ pub sampled_at: DateTime<Utc>,+ pub elapsed_millis: u64,+ pub tables: [TableDelta; 2],+ pub wal: WalDelta,+}++#[derive(Debug)]+pub struct PgSampler {+ pool: PgPool,+ phase_id: PhaseId,+ previous: Option<PgSnapshot>,+}++impl PgSampler {+ pub async fn connect(database_url: &str, phase_id: PhaseId) -> anyhow::Result<Self> {+ let pool = PgPoolOptions::new()+ .max_connections(1)+ .min_connections(1)+ .acquire_timeout(Duration::from_secs(30))+ .connect(database_url)+ .await+ .context("connect PostgreSQL sampler pool")?;+ Ok(Self {+ pool,+ phase_id,+ previous: None,+ })+ }++ pub async fn sample(&self) -> anyhow::Result<PgSnapshot> {+ let rows = tokio::time::timeout(+ SAMPLE_QUERY_TIMEOUT,+ sqlx::query_as::<_, (String, i64, i64, i64, i64, i64, i64, i64, i64, i64, i64)>(+ TABLE_STATS_SQL,+ )+ .fetch_all(&self.pool),+ )+ .await+ .context("PostgreSQL table statistics sample timed out")?+ .context("sample PostgreSQL table statistics")?;+ let mut tables = Vec::with_capacity(TableGroup::ALL.len());+ for row in rows {+ let group = table_group(&row.0)?;+ anyhow::ensure!(+ row.10 > 0,+ "PostgreSQL sampler found no leaf partitions for {}",+ row.0+ );+ tables.push(TableSnapshot {+ group,+ inserts: nonnegative(row.1),+ updates: nonnegative(row.2),+ deletes: nonnegative(row.3),+ hot_updates: nonnegative(row.4),+ dead_tuples: nonnegative(row.5),+ vacuums: nonnegative(row.6),+ autovacuums: nonnegative(row.7),+ heap_bytes: nonnegative(row.8),+ index_bytes: nonnegative(row.9),+ });+ }+ let tables = TableGroup::ALL.map(|group| {+ tables+ .iter()+ .find(|table| table.group == group)+ .copied()+ .unwrap_or(TableSnapshot {+ group,+ inserts: 0,+ updates: 0,+ deletes: 0,+ hot_updates: 0,+ dead_tuples: 0,+ vacuums: 0,+ autovacuums: 0,+ heap_bytes: 0,+ index_bytes: 0,+ })+ });++ let wal = match tokio::time::timeout(+ SAMPLE_QUERY_TIMEOUT,+ sqlx::query_scalar::<_, i64>(WAL_POSITION_SQL).fetch_one(&self.pool),+ )+ .await+ .context("PostgreSQL WAL sample timed out")?+ {+ Ok(bytes) => WalSnapshot::Available {+ bytes_from_origin: nonnegative(bytes),+ },+ Err(error) if is_permission_denied(&error) => WalSnapshot::Unavailable {+ reason: format!("WAL sampling unavailable: insufficient privilege ({error})")+ .into_boxed_str(),+ },+ Err(error) => return Err(error).context("sample PostgreSQL WAL position"),+ };++ Ok(PgSnapshot {+ phase_id: self.phase_id,+ sampled_at: Utc::now(),+ tables,+ wal,+ })+ }++ pub async fn sample_delta(&mut self) -> anyhow::Result<Option<PgDeltaRecord>> {+ let current = self.sample().await?;+ let delta = self+ .previous+ .as_ref()+ .map(|previous| delta(previous, ¤t))+ .transpose()?;+ self.previous = Some(current);+ Ok(delta)+ }++ pub async fn close(self) {+ self.pool.close().await;+ }+}++pub fn delta(previous: &PgSnapshot, current: &PgSnapshot) -> Result<PgDeltaRecord, PgDeltaError> {+ if previous.phase_id != current.phase_id {+ return Err(PgDeltaError::PhaseMismatch(PhaseMismatch {+ expected: previous.phase_id,+ actual: current.phase_id,+ }));+ }+ let elapsed_millis = current+ .sampled_at+ .signed_duration_since(previous.sampled_at)+ .num_milliseconds()+ .max(0) as u64;+ let tables = TableGroup::ALL.map(|group| {+ let previous = snapshot_for(previous, group);+ let current = snapshot_for(current, group);+ let stats_reset_detected = [+ (previous.inserts, current.inserts),+ (previous.updates, current.updates),+ (previous.deletes, current.deletes),+ (previous.hot_updates, current.hot_updates),+ (previous.vacuums, current.vacuums),+ (previous.autovacuums, current.autovacuums),+ ]+ .into_iter()+ .any(|(before, after)| after < before);+ TableDelta {+ group,+ inserts: current.inserts.saturating_sub(previous.inserts),+ updates: current.updates.saturating_sub(previous.updates),+ deletes: current.deletes.saturating_sub(previous.deletes),+ hot_updates: current.hot_updates.saturating_sub(previous.hot_updates),+ dead_tuples: current.dead_tuples,+ vacuums: current.vacuums.saturating_sub(previous.vacuums),+ autovacuums: current.autovacuums.saturating_sub(previous.autovacuums),+ heap_bytes: current.heap_bytes,+ index_bytes: current.index_bytes,+ stats_reset_detected,+ }+ });+ let wal = match (&previous.wal, ¤t.wal) {+ (+ WalSnapshot::Available {+ bytes_from_origin: before,+ },+ WalSnapshot::Available {+ bytes_from_origin: after,+ },+ ) => WalDelta::Available {+ bytes: after.saturating_sub(*before),+ },+ (_, WalSnapshot::Unavailable { reason })+ | (WalSnapshot::Unavailable { reason }, WalSnapshot::Available { .. }) => {+ WalDelta::Unavailable {+ reason: reason.clone(),+ }+ }+ };+ Ok(PgDeltaRecord {+ record_type: "pg",+ phase_id: current.phase_id,+ sampled_at: current.sampled_at,+ elapsed_millis,+ tables,+ wal,+ })+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PgDeltaError {+ PhaseMismatch(PhaseMismatch),+}++impl std::fmt::Display for PgDeltaError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::PhaseMismatch(error) => error.fmt(formatter),+ }+ }+}++impl std::error::Error for PgDeltaError {}++fn snapshot_for(snapshot: &PgSnapshot, group: TableGroup) -> TableSnapshot {+ snapshot+ .tables+ .iter()+ .find(|table| table.group == group)+ .copied()+ .unwrap_or(TableSnapshot {+ group,+ inserts: 0,+ updates: 0,+ deletes: 0,+ hot_updates: 0,+ dead_tuples: 0,+ vacuums: 0,+ autovacuums: 0,+ heap_bytes: 0,+ index_bytes: 0,+ })+}++fn table_group(table_name: &str) -> anyhow::Result<TableGroup> {+ TableGroup::ALL+ .into_iter()+ .find(|group| group.table_name() == table_name)+ .ok_or_else(|| anyhow::anyhow!("unexpected PostgreSQL sampler table {table_name}"))+}++fn nonnegative(value: i64) -> u64 {+ u64::try_from(value).unwrap_or(0)+}++fn is_permission_denied(error: &sqlx::Error) -> bool {+ matches!(+ error,+ sqlx::Error::Database(database_error)+ if database_error.code().is_some_and(|code| code.as_ref() == "42501")+ )+}++#[cfg(test)]+mod tests {+ use chrono::TimeDelta;++ use super::*;++ fn table(group: TableGroup, inserts: u64, updates: u64) -> TableSnapshot {+ TableSnapshot {+ group,+ inserts,+ updates,+ deletes: 0,+ hot_updates: updates / 2,+ dead_tuples: updates,+ vacuums: 1,+ autovacuums: 2,+ heap_bytes: 100,+ index_bytes: 50,+ }+ }++ #[test]+ fn deltas_keep_table_groups_independent_and_surface_stat_resets() {+ let sampled_at = Utc::now();+ let previous = PgSnapshot {+ phase_id: PhaseId::new(1),+ sampled_at,+ tables: [+ table(TableGroup::Person, 10, 20),+ table(TableGroup::DistinctIdMap, 100, 200),+ ],+ wal: WalSnapshot::Available {+ bytes_from_origin: 1_000,+ },+ };+ let current = PgSnapshot {+ phase_id: PhaseId::new(1),+ sampled_at: sampled_at + TimeDelta::seconds(10),+ tables: [+ table(TableGroup::Person, 2, 3),+ table(TableGroup::DistinctIdMap, 110, 240),+ ],+ wal: WalSnapshot::Available {+ bytes_from_origin: 1_500,+ },+ };++ let result = delta(&previous, ¤t).expect("matching phase");++ assert!(result.tables[0].stats_reset_detected);+ assert_eq!(result.tables[0].updates, 0);+ assert!(!result.tables[1].stats_reset_detected);+ assert_eq!(+ (result.tables[1].inserts, result.tables[1].updates),+ (10, 40)+ );+ assert_eq!(result.wal, WalDelta::Available { bytes: 500 });++ let mut next_phase = current;+ next_phase.phase_id = PhaseId::new(2);+ assert!(matches!(+ delta(&previous, &next_phase),+ Err(PgDeltaError::PhaseMismatch(_))+ ));+ }+}diff --git a/rust/flags-consumer/src/benchmark/plancheck.rs b/rust/flags-consumer/src/benchmark/plancheck.rsnew file mode 100644index 000000000000..09910b9d1d73--- /dev/null+++ b/rust/flags-consumer/src/benchmark/plancheck.rs@@ -0,0 +1,329 @@+use anyhow::Context;+use serde::Serialize;+use serde_json::{json, Value};+use sqlx::PgPool;+use uuid::Uuid;++use crate::storage::postgres::{+ CANONICAL_READ_SQL, DISTINCT_ID_DELETE_SQL, DISTINCT_ID_UPSERT_SQL, PERSON_DELETE_SQL,+ PERSON_UPSERT_SQL,+};++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct PlanNodeEvidence {+ pub node_type: Box<str>,+ pub relation_name: Option<Box<str>>,+ pub index_name: Option<Box<str>>,+}++#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct NamedPlanEvidence {+ pub name: &'static str,+ pub nodes: Vec<PlanNodeEvidence>,+ pub conflict_arbiter_indexes: Vec<Box<str>>,+ pub plan: Value,+}++#[derive(Debug, Clone, Copy)]+enum PlanRequirement {+ CanonicalRead,+ Write { table: &'static str },+}++pub async fn verify_storage_plans(pool: &PgPool) -> anyhow::Result<Vec<NamedPlanEvidence>> {+ let person_uuid = Uuid::from_u128(1);+ let team_ids = vec![1i32];+ let person_uuids = vec![person_uuid];+ let properties = vec![json!({"plancheck": true})];+ let versions = vec![2i64];+ let distinct_ids = vec!["plancheck-distinct-id"];++ let canonical_read = sqlx::query_scalar::<_, Value>(&explain(CANONICAL_READ_SQL))+ .bind(1i32)+ .bind("plancheck-distinct-id")+ .fetch_one(pool)+ .await+ .context("EXPLAIN canonical read")?;+ let canonical_read = validate_plan(+ "canonical_read",+ canonical_read,+ PlanRequirement::CanonicalRead,+ )?;+ let person_upsert = sqlx::query_scalar::<_, Value>(&explain(PERSON_UPSERT_SQL))+ .bind(&team_ids)+ .bind(&person_uuids)+ .bind(&properties)+ .bind(&versions)+ .fetch_one(pool)+ .await+ .context("EXPLAIN person upsert")?;+ let person_delete = sqlx::query_scalar::<_, Value>(&explain(PERSON_DELETE_SQL))+ .bind(&team_ids)+ .bind(&person_uuids)+ .bind(&versions)+ .fetch_one(pool)+ .await+ .context("EXPLAIN person tombstone")?;+ let distinct_id_upsert = sqlx::query_scalar::<_, Value>(&explain(DISTINCT_ID_UPSERT_SQL))+ .bind(&team_ids)+ .bind(&distinct_ids)+ .bind(&person_uuids)+ .bind(&versions)+ .fetch_one(pool)+ .await+ .context("EXPLAIN distinct ID upsert")?;+ let distinct_id_delete = sqlx::query_scalar::<_, Value>(&explain(DISTINCT_ID_DELETE_SQL))+ .bind(&team_ids)+ .bind(&distinct_ids)+ .bind(&person_uuids)+ .bind(&versions)+ .fetch_one(pool)+ .await+ .context("EXPLAIN owner-guarded distinct ID tombstone")?;++ let mut evidence = vec![canonical_read];+ evidence.extend(+ [+ (+ "person_upsert",+ person_upsert,+ PlanRequirement::Write {+ table: "flags_person",+ },+ ),+ (+ "person_tombstone",+ person_delete,+ PlanRequirement::Write {+ table: "flags_person",+ },+ ),+ (+ "distinct_id_upsert",+ distinct_id_upsert,+ PlanRequirement::Write {+ table: "flags_distinct_id_map",+ },+ ),+ (+ "distinct_id_tombstone",+ distinct_id_delete,+ PlanRequirement::Write {+ table: "flags_distinct_id_map",+ },+ ),+ ]+ .into_iter()+ .map(|(name, plan, requirement)| validate_plan(name, plan, requirement))+ .collect::<anyhow::Result<Vec<_>>>()?,+ );+ Ok(evidence)+}++fn explain(sql: &str) -> String {+ format!("EXPLAIN (FORMAT JSON) {sql}")+}++fn validate_plan(+ name: &'static str,+ plan: Value,+ requirement: PlanRequirement,+) -> anyhow::Result<NamedPlanEvidence> {+ let mut nodes = Vec::new();+ let mut conflict_arbiter_indexes = Vec::new();+ collect_evidence(&plan, &mut nodes, &mut conflict_arbiter_indexes);++ let sequential_scans = nodes+ .iter()+ .filter(|node| node.node_type.as_ref() == "Seq Scan")+ .map(|node| node.relation_name.as_deref().unwrap_or("unknown"))+ .collect::<Vec<_>>();+ if !sequential_scans.is_empty() {+ anyhow::bail!(+ "plancheck {name} rejected sequential scans on: {}",+ sequential_scans.join(", ")+ );+ }++ match requirement {+ PlanRequirement::CanonicalRead => {+ for table in ["flags_distinct_id_map", "flags_person"] {+ if !nodes.iter().any(|node| is_index_access_for(node, table)) {+ anyhow::bail!(+ "plancheck {name} requires index access for {table}; nodes: {}",+ format_nodes(&nodes)+ );+ }+ }+ }+ PlanRequirement::Write { table } => {+ if conflict_arbiter_indexes.is_empty() {+ anyhow::bail!(+ "plancheck {name} did not expose a conflict arbiter index for {table}"+ );+ }+ if !conflict_arbiter_indexes+ .iter()+ .all(|index| is_primary_key_for(index, table))+ {+ anyhow::bail!(+ "plancheck {name} exposed unexpected conflict arbiter indexes for {table}: {}",+ conflict_arbiter_indexes+ .iter()+ .map(AsRef::as_ref)+ .collect::<Vec<&str>>()+ .join(", ")+ );+ }+ }+ }++ Ok(NamedPlanEvidence {+ name,+ nodes,+ conflict_arbiter_indexes,+ plan,+ })+}++fn collect_evidence(+ value: &Value,+ nodes: &mut Vec<PlanNodeEvidence>,+ conflict_arbiter_indexes: &mut Vec<Box<str>>,+) {+ match value {+ Value::Object(object) => {+ if let Some(node_type) = object.get("Node Type").and_then(Value::as_str) {+ nodes.push(PlanNodeEvidence {+ node_type: node_type.into(),+ relation_name: object+ .get("Relation Name")+ .and_then(Value::as_str)+ .map(Into::into),+ index_name: object+ .get("Index Name")+ .and_then(Value::as_str)+ .map(Into::into),+ });+ }+ if let Some(indexes) = object+ .get("Conflict Arbiter Indexes")+ .and_then(Value::as_array)+ {+ conflict_arbiter_indexes+ .extend(indexes.iter().filter_map(Value::as_str).map(Into::into));+ }+ for child in object.values() {+ collect_evidence(child, nodes, conflict_arbiter_indexes);+ }+ }+ Value::Array(values) => {+ for child in values {+ collect_evidence(child, nodes, conflict_arbiter_indexes);+ }+ }+ _ => {}+ }+}++fn is_index_access_for(node: &PlanNodeEvidence, table: &str) -> bool {+ matches!(+ node.node_type.as_ref(),+ "Index Scan" | "Index Only Scan" | "Bitmap Index Scan"+ ) && (node+ .relation_name+ .as_deref()+ .is_some_and(|relation| relation.starts_with(table))+ || node+ .index_name+ .as_deref()+ .is_some_and(|index| index.starts_with(table)))+}++fn is_primary_key_for(index: &str, table: &str) -> bool {+ index == format!("{table}_pkey") || (index.starts_with(table) && index.ends_with("_pkey"))+}++fn format_nodes(nodes: &[PlanNodeEvidence]) -> String {+ nodes+ .iter()+ .map(|node| {+ format!(+ "{}({})",+ node.node_type,+ node.relation_name.as_deref().unwrap_or("no relation")+ )+ })+ .collect::<Vec<_>>()+ .join(", ")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn recursive_validation_rejects_scans_and_requires_both_read_indexes() {+ let scan = json!([{"Plan": {+ "Node Type": "Nested Loop",+ "Plans": [{"Node Type": "Seq Scan", "Relation Name": "flags_person_p0"}]+ }}]);+ let error = validate_plan("canonical_read", scan, PlanRequirement::CanonicalRead)+ .expect_err("sequential scan must fail");+ assert!(error.to_string().contains("flags_person_p0"));++ let indexed = json!([{"Plan": {+ "Node Type": "Nested Loop",+ "Plans": [+ {"Node Type": "Index Scan", "Relation Name": "flags_distinct_id_map_p0", "Index Name": "flags_distinct_id_map_p0_pkey"},+ {"Node Type": "Index Scan", "Relation Name": "flags_person_p0", "Index Name": "flags_person_p0_pkey"}+ ]+ }}]);+ let evidence = validate_plan("canonical_read", indexed, PlanRequirement::CanonicalRead)+ .expect("both probes use indexes");+ assert_eq!(evidence.nodes.len(), 3);+ }++ #[test]+ fn write_validation_requires_the_expected_primary_key_arbiter() {+ let no_arbiter = json!([{"Plan": {"Node Type": "ModifyTable"}}]);+ assert!(validate_plan(+ "person_upsert",+ no_arbiter,+ PlanRequirement::Write {+ table: "flags_person"+ }+ )+ .expect_err("missing arbiter must fail")+ .to_string()+ .contains("did not expose"));++ let wrong_arbiter = json!([{"Plan": {+ "Node Type": "ModifyTable",+ "Conflict Arbiter Indexes": ["unrelated_key"]+ }}]);+ assert!(validate_plan(+ "person_upsert",+ wrong_arbiter,+ PlanRequirement::Write {+ table: "flags_person"+ }+ )+ .expect_err("wrong arbiter must fail")+ .to_string()+ .contains("unexpected conflict arbiter"));++ let correct_arbiter = json!([{"Plan": {+ "Node Type": "ModifyTable",+ "Conflict Arbiter Indexes": ["flags_person_pkey"]+ }}]);+ validate_plan(+ "person_upsert",+ correct_arbiter,+ PlanRequirement::Write {+ table: "flags_person",+ },+ )+ .expect("primary key arbiter");+ }+}diff --git a/rust/flags-consumer/src/benchmark/population.rs b/rust/flags-consumer/src/benchmark/population.rsindex 7de4c0653324..b0352613818f 100644--- a/rust/flags-consumer/src/benchmark/population.rs+++ b/rust/flags-consumer/src/benchmark/population.rs@@ -1,121 +1,82 @@-use crate::storage::{postgres::PostgresStorage, types::PersonUpdateData};+use crate::storage::{+ postgres::PostgresStorage,+ types::{DistinctIdAssignmentData, PersonUpdateData},+};use rand::rngs::StdRng;use rand::SeedableRng;+use serde::Serialize;use sqlx::PgPool;-use uuid::Uuid;-use super::data_gen::{generate_properties, PersonRegistry};+use super::world::{generate_properties as generate_world_properties, PopulationView};-/// Uses a separate seeded RNG (seed 43) for properties so the structural-/// distribution (persons, distinct_ids) is independent of property generation.-pub async fn populate(+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+pub struct PopulationSummary {+ pub persons: u64,+ pub distinct_ids: u64,+}++pub async fn populate_world(pool: &PgPool,storage: &PostgresStorage,- registry: &PersonRegistry,+ population: PopulationView<'_>,batch_size: usize,-) -> anyhow::Result<()> {- let total = registry.persons.len();- tracing::info!(total, "populating person rows");-- let mut prop_rng = StdRng::seed_from_u64(43);-- for (batch_idx, chunk) in registry.persons.chunks(batch_size).enumerate() {- let updates: Vec<PersonUpdateData> = chunk- .iter()- .map(|(team_id, uuid)| PersonUpdateData {- team_id: *team_id,- person_uuid: *uuid,- properties: generate_properties(&mut prop_rng, 700),- version: 1,- })- .collect();-+) -> anyhow::Result<PopulationSummary> {+ anyhow::ensure!(batch_size > 0, "population batch size must be positive");++ let mut property_rng = StdRng::seed_from_u64(population.property_seed());+ let mut updates = Vec::with_capacity(batch_size);+ let mut person_count = 0u64;+ for person in population.persons() {+ updates.push(PersonUpdateData {+ team_id: person.team_id,+ person_uuid: person.person_uuid,+ properties: generate_world_properties(&mut property_rng, population.property_bytes()),+ version: person.version,+ });+ person_count = person_count.saturating_add(1);+ if updates.len() == batch_size {+ storage.batch_upsert_persons(&updates).await?;+ updates.clear();+ }+ }+ if !updates.is_empty() {storage.batch_upsert_persons(&updates).await?;+ }- let done = ((batch_idx + 1) * batch_size).min(total);- if done % (total / 10).max(1) < batch_size {- tracing::info!(done, total, "persons inserted");+ let mut assignments = Vec::with_capacity(batch_size);+ let mut distinct_id_count = 0u64;+ for distinct_id in population.distinct_ids() {+ assignments.push(DistinctIdAssignmentData {+ team_id: distinct_id.team_id,+ person_uuid: distinct_id.person_uuid,+ distinct_id: distinct_id.distinct_id,+ version: distinct_id.version,+ });+ distinct_id_count = distinct_id_count.saturating_add(1);+ if assignments.len() == batch_size {+ storage.batch_upsert_distinct_ids(&assignments).await?;+ assignments.clear();}}-- assign_distinct_ids_bulk(pool, registry).await?;-- tracing::info!(total, "population complete");- Ok(())-}--/// Bulk-assigns distinct_ids via UNNEST instead of the single-row transactional-/// upsert_distinct_id, which would be too slow for initial population.-async fn assign_distinct_ids_bulk(pool: &PgPool, registry: &PersonRegistry) -> anyhow::Result<()> {- let total = registry.distinct_ids.len();- tracing::info!(total, "assigning distinct_ids");-- let mut person_dids: std::collections::HashMap<(i32, Uuid), Vec<String>> =- std::collections::HashMap::new();- for (team_id, person_uuid, did) in ®istry.distinct_ids {- person_dids- .entry((*team_id, *person_uuid))- .or_default()- .push(did.clone());+ if !assignments.is_empty() {+ storage.batch_upsert_distinct_ids(&assignments).await?;}- let entries: Vec<((i32, Uuid), Vec<String>)> = person_dids.into_iter().collect();- let batch_size = 500;-- for (batch_idx, chunk) in entries.chunks(batch_size).enumerate() {- let team_ids: Vec<i32> = chunk.iter().map(|((tid, _), _)| *tid).collect();- let person_uuids: Vec<Uuid> = chunk.iter().map(|((_, uuid), _)| *uuid).collect();- let primary_dids: Vec<String> = chunk.iter().map(|(_, dids)| dids[0].clone()).collect();+ vacuum_analyze_checkpoint(pool).await?;+ Ok(PopulationSummary {+ persons: person_count,+ distinct_ids: distinct_id_count,+ })+}- sqlx::query(- r#"- UPDATE flags_person_lookup AS f- SET distinct_ids = ARRAY[t.did]::text[],- distinct_id_version = 1- FROM UNNEST($1::int[], $2::uuid[], $3::text[]) AS t(team_id, person_uuid, did)- WHERE f.team_id = t.team_id AND f.person_uuid = t.person_uuid- "#,- )- .bind(&team_ids)- .bind(&person_uuids)- .bind(&primary_dids)+pub async fn vacuum_analyze_checkpoint(pool: &PgPool) -> anyhow::Result<()> {+ tracing::info!("vacuuming populated tables");+ sqlx::query("VACUUM (ANALYZE) flags_person").execute(pool).await?;-- let mut extra_team_ids = Vec::new();- let mut extra_uuids = Vec::new();- let mut extra_dids = Vec::new();- for ((tid, uuid), dids) in chunk {- if dids.len() > 1 {- for extra_did in &dids[1..] {- extra_team_ids.push(*tid);- extra_uuids.push(*uuid);- extra_dids.push(extra_did.clone());- }- }- }-- if !extra_dids.is_empty() {- sqlx::query(- r#"- UPDATE flags_person_lookup AS f- SET distinct_ids = f.distinct_ids || t.did- FROM UNNEST($1::int[], $2::uuid[], $3::text[]) AS t(team_id, person_uuid, did)- WHERE f.team_id = t.team_id AND f.person_uuid = t.person_uuid- "#,- )- .bind(&extra_team_ids)- .bind(&extra_uuids)- .bind(&extra_dids)- .execute(pool)- .await?;- }-- let done = ((batch_idx + 1) * batch_size).min(entries.len());- if done % (entries.len() / 10).max(1) < batch_size {- tracing::info!(done, total = entries.len(), "distinct_ids assigned");- }- }-+ sqlx::query("VACUUM (ANALYZE) flags_distinct_id_map")+ .execute(pool)+ .await?;+ sqlx::query("CHECKPOINT").execute(pool).await?;Ok(())}diff --git a/rust/flags-consumer/src/benchmark/rates.rs b/rust/flags-consumer/src/benchmark/rates.rsnew file mode 100644index 000000000000..6d3d614d8aeb--- /dev/null+++ b/rust/flags-consumer/src/benchmark/rates.rs@@ -0,0 +1,307 @@+use std::time::Duration;++use serde::{Deserialize, Serialize};++use super::ops::OpClass;++#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)]+#[serde(transparent)]+pub struct RatePerSecond(f64);++impl RatePerSecond {+ pub const ZERO: Self = Self(0.0);++ pub const fn new(value: f64) -> Self {+ Self(value)+ }++ pub const fn get(self) -> f64 {+ self.0+ }++ pub fn is_active(self) -> bool {+ self.0 > 0.0+ }++ pub fn scaled(self, factor: f64) -> Self {+ Self(self.0 * factor)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+pub struct ClassRates {+ pub average: RatePerSecond,+ pub five_minute_peak: RatePerSecond,+}++impl ClassRates {+ const fn new(average: f64, five_minute_peak: f64) -> Self {+ Self {+ average: RatePerSecond::new(average),+ five_minute_peak: RatePerSecond::new(five_minute_peak),+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+pub struct ProdRates {+ pub person_upsert: ClassRates,+ pub distinct_id_assignment: ClassRates,+ pub merge: ClassRates,+ pub canonical_read: ClassRates,+}++pub const PROD_US_RATES: ProdRates = ProdRates {+ person_upsert: ClassRates::new(2_204.0, 5_788.0),+ distinct_id_assignment: ClassRates::new(981.0, 3_594.0),+ merge: ClassRates::new(17.2, 54.6),+ canonical_read: ClassRates::new(5_373.0, 14_474.0),+};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum FeedMode {+ Open,+ Closed,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Hook {+ Vacuum,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]+#[serde(rename_all = "snake_case")]+pub enum BenchmarkProfile {+ Smoke,+ Gate,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum PhaseName {+ BaselineReads,+ SteadyMix,+ PeakMix,+ MergeStorm,+ Recovery,+ CatchUp,+}++impl PhaseName {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::BaselineReads => "baseline_reads",+ Self::SteadyMix => "steady_mix",+ Self::PeakMix => "peak_mix",+ Self::MergeStorm => "merge_storm",+ Self::Recovery => "recovery",+ Self::CatchUp => "catch_up",+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+pub struct RateSpec {+ pub class: OpClass,+ pub target: RatePerSecond,+ pub feed: FeedMode,+}++impl RateSpec {+ const fn open(class: OpClass, target: RatePerSecond) -> Self {+ Self {+ class,+ target,+ feed: FeedMode::Open,+ }+ }++ const fn closed(class: OpClass, target: RatePerSecond) -> Self {+ Self {+ class,+ target,+ feed: FeedMode::Closed,+ }+ }+}++#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct PhaseSpec {+ pub name: PhaseName,+ pub duration: Duration,+ pub rates: [RateSpec; OpClass::COUNT],+ pub pre_hooks: Vec<Hook>,+}++impl PhaseSpec {+ pub fn rate_for(&self, class: OpClass) -> &RateSpec {+ &self.rates[class.index()]+ }+}++pub fn standard_phases(+ profile: BenchmarkProfile,+ duration_override: Option<Duration>,+) -> Vec<PhaseSpec> {+ let average = rate_specs(+ PROD_US_RATES.person_upsert.average,+ PROD_US_RATES.distinct_id_assignment.average,+ PROD_US_RATES.merge.average,+ PROD_US_RATES.canonical_read.average,+ FeedMode::Open,+ );+ let peak = rate_specs(+ PROD_US_RATES.person_upsert.five_minute_peak,+ PROD_US_RATES.distinct_id_assignment.five_minute_peak,+ PROD_US_RATES.merge.five_minute_peak,+ PROD_US_RATES.canonical_read.five_minute_peak,+ FeedMode::Open,+ );+ let mut storm = average;+ storm[OpClass::Merge.index()].target = PROD_US_RATES.merge.five_minute_peak.scaled(10.0);+ let mut catch_up = peak;+ for class in OpClass::WRITE_CLASSES {+ catch_up[class.index()] = RateSpec::closed(class, catch_up[class.index()].target);+ }++ let baseline_reads = rate_specs(+ RatePerSecond::ZERO,+ RatePerSecond::ZERO,+ RatePerSecond::ZERO,+ PROD_US_RATES.canonical_read.average,+ FeedMode::Open,+ );++ [+ (PhaseName::BaselineReads, baseline_reads, Vec::new()),+ (PhaseName::SteadyMix, average, Vec::new()),+ (PhaseName::PeakMix, peak, Vec::new()),+ (PhaseName::MergeStorm, storm, Vec::new()),+ (PhaseName::Recovery, average, vec![Hook::Vacuum]),+ (PhaseName::CatchUp, catch_up, Vec::new()),+ ]+ .into_iter()+ .map(|(name, rates, pre_hooks)| PhaseSpec {+ name,+ duration: duration_override.unwrap_or_else(|| profile_duration(profile, name)),+ rates,+ pre_hooks,+ })+ .collect()+}++fn rate_specs(+ person_upsert: RatePerSecond,+ distinct_id_assignment: RatePerSecond,+ merge: RatePerSecond,+ canonical_read: RatePerSecond,+ write_feed: FeedMode,+) -> [RateSpec; OpClass::COUNT] {+ let write_spec = |class, target| match write_feed {+ FeedMode::Open => RateSpec::open(class, target),+ FeedMode::Closed => RateSpec::closed(class, target),+ };++ [+ write_spec(OpClass::PersonUpsert, person_upsert),+ write_spec(OpClass::DistinctIdAssignment, distinct_id_assignment),+ write_spec(OpClass::Merge, merge),+ RateSpec::open(OpClass::CanonicalRead, canonical_read),+ ]+}++const fn profile_duration(profile: BenchmarkProfile, phase: PhaseName) -> Duration {+ if matches!(profile, BenchmarkProfile::Smoke) {+ return Duration::from_secs(60);+ }++ match phase {+ PhaseName::BaselineReads => Duration::from_secs(5 * 60),+ PhaseName::SteadyMix => Duration::from_secs(30 * 60),+ PhaseName::PeakMix => Duration::from_secs(60 * 60),+ PhaseName::MergeStorm | PhaseName::Recovery | PhaseName::CatchUp => {+ Duration::from_secs(15 * 60)+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn standard_phases_encode_the_production_workload_and_feed_modes() {+ let phases = standard_phases(BenchmarkProfile::Gate, None);++ assert_eq!(+ phases.iter().map(|phase| phase.name).collect::<Vec<_>>(),+ vec![+ PhaseName::BaselineReads,+ PhaseName::SteadyMix,+ PhaseName::PeakMix,+ PhaseName::MergeStorm,+ PhaseName::Recovery,+ PhaseName::CatchUp,+ ]+ );++ let baseline = &phases[0];+ assert_eq!(+ baseline.rate_for(OpClass::CanonicalRead).target,+ PROD_US_RATES.canonical_read.average+ );+ for class in OpClass::WRITE_CLASSES {+ assert_eq!(baseline.rate_for(class).target, RatePerSecond::ZERO);+ }++ let steady = &phases[1];+ let peak = &phases[2];+ for (class, production) in [+ (OpClass::PersonUpsert, PROD_US_RATES.person_upsert),+ (+ OpClass::DistinctIdAssignment,+ PROD_US_RATES.distinct_id_assignment,+ ),+ (OpClass::Merge, PROD_US_RATES.merge),+ (OpClass::CanonicalRead, PROD_US_RATES.canonical_read),+ ] {+ assert_eq!(steady.rate_for(class).target, production.average);+ assert_eq!(peak.rate_for(class).target, production.five_minute_peak);+ }++ assert_eq!(+ phases[3].rate_for(OpClass::Merge).target,+ RatePerSecond::new(546.0)+ );+ assert_eq!(phases[4].pre_hooks, vec![Hook::Vacuum]);+ assert_eq!(phases[1].duration, Duration::from_secs(30 * 60));+ assert_eq!(phases[2].duration, Duration::from_secs(60 * 60));+ assert_eq!(phases[3].duration, Duration::from_secs(15 * 60));+ assert_eq!(phases[4].duration, Duration::from_secs(15 * 60));++ let catch_up = &phases[5];+ for class in OpClass::WRITE_CLASSES {+ assert_eq!(catch_up.rate_for(class).feed, FeedMode::Closed);+ }+ assert_eq!(+ catch_up.rate_for(OpClass::CanonicalRead).feed,+ FeedMode::Open+ );+ }++ #[test]+ fn smoke_and_override_durations_are_bounded_for_local_runs() {+ let smoke = standard_phases(BenchmarkProfile::Smoke, None);+ assert!(smoke+ .iter()+ .all(|phase| phase.duration == Duration::from_secs(60)));++ let override_duration = Duration::from_secs(3);+ let overridden = standard_phases(BenchmarkProfile::Gate, Some(override_duration));+ assert!(overridden+ .iter()+ .all(|phase| phase.duration == override_duration));+ }+}diff --git a/rust/flags-consumer/src/benchmark/report.rs b/rust/flags-consumer/src/benchmark/report.rsindex 0320da254482..c5925624883b 100644--- a/rust/flags-consumer/src/benchmark/report.rs+++ b/rust/flags-consumer/src/benchmark/report.rs@@ -1,96 +1,930 @@-use super::metrics::compute_delta;-use super::workloads::{PhaseResult, QueryPlanInfo};-use super::BenchmarkArgs;--fn fmt_duration_ms(d: std::time::Duration) -> String {- let ms = d.as_secs_f64() * 1000.0;- if ms < 1.0 {- format!("{:.2}ms", ms)- } else if ms < 100.0 {- format!("{:.1}ms", ms)+use std::time::Duration;++use serde::Serialize;++use super::collector::{ClassMetrics, IntervalRecord, LatencySummary, PhaseSummaryRecord};+use super::ops::OpClass;+use super::pg_sampler::{PgDeltaRecord, TableGroup, WalDelta};+use super::rates::{FeedMode, PhaseName, RateSpec, PROD_US_RATES};++const NANOS_PER_MILLISECOND: f64 = 1_000_000.0;++#[derive(Debug, Clone, Copy, Serialize)]+pub struct GateThresholds {+ pub steady_read_p50_ms: f64,+ pub steady_read_p99_ms: f64,+ pub storm_read_p99_ms: f64,+ pub recovery_max_secs: u64,+ pub catch_up_headroom: f64,+ pub dispatch_p99_ms: f64,+ pub rate_tolerance_percent: f64,+ pub max_read_drift_ratio: f64,+ pub max_backlog_secs: f64,+}++#[derive(Debug, Clone, Serialize)]+pub struct PhaseResult {+ pub name: PhaseName,+ pub duration: Duration,+ pub pre_hook_duration: Duration,+ pub targets: [RateSpec; OpClass::COUNT],+ pub summary: PhaseSummaryRecord,+ pub intervals: Vec<IntervalRecord>,+ pub pg: Vec<PgDeltaRecord>,+}++#[derive(Debug, Clone, Serialize)]+pub struct GateCheck {+ pub name: String,+ pub passed: bool,+ pub detail: String,+}++#[derive(Debug, Clone, Serialize)]+pub struct GateEvaluation {+ pub passed: bool,+ pub harness_limited: bool,+ pub checks: Vec<GateCheck>,+ pub unverified_qualifications: Vec<String>,+}++pub fn evaluate_gates(phases: &[PhaseResult], thresholds: GateThresholds) -> GateEvaluation {+ let mut checks = Vec::new();+ add_phase_integrity_checks(&mut checks, phases, thresholds);++ let peak = phase(phases, PhaseName::PeakMix);+ if let Some(peak) = peak {+ let read = class_metrics(peak, OpClass::CanonicalRead);+ checks.push(max_latency_check(+ "steady read p50",+ read.schedule.count,+ read.schedule.p50_nanos,+ thresholds.steady_read_p50_ms,+ ));+ checks.push(max_latency_check(+ "steady read p99",+ read.schedule.count,+ read.schedule.p99_nanos,+ thresholds.steady_read_p99_ms,+ ));+ let interval_reads = peak+ .intervals+ .iter()+ .filter(|interval| interval.started_at_nanos < peak.summary.duration_nanos)+ .map(|interval| &interval.classes[OpClass::CanonicalRead.index()])+ .filter(|read| read.counts.scheduled > 0)+ .collect::<Vec<_>>();+ let interval_slo = !interval_reads.is_empty()+ && interval_reads.iter().all(|read| {+ nanos_millis(read.schedule.p50_nanos) <= thresholds.steady_read_p50_ms+ && nanos_millis(read.schedule.p99_nanos) <= thresholds.steady_read_p99_ms+ });+ checks.push(GateCheck {+ name: "steady interval read SLO".to_owned(),+ passed: interval_slo,+ detail: "every non-empty 10s interval must meet read p50 and p99 limits".to_owned(),+ });+ let drift = read_drift_ratio(peak);+ checks.push(GateCheck {+ name: "steady read drift".to_owned(),+ passed: drift.is_some_and(|ratio| ratio <= thresholds.max_read_drift_ratio),+ detail: drift.map_or_else(+ || "fewer than five non-empty workload intervals".to_owned(),+ |ratio| {+ format!(+ "late/early median interval p99 {ratio:.2}x, limit {:.2}x",+ thresholds.max_read_drift_ratio+ )+ },+ ),+ });} else {- format!("{:.0}ms", ms)+ checks.push(missing_phase("steady gate", PhaseName::PeakMix));}-}-fn fmt_bytes_mib(bytes: i64) -> String {- let mib = bytes as f64 / (1024.0 * 1024.0);- format!("{:.1}", mib)+ if let Some(storm) = phase(phases, PhaseName::MergeStorm) {+ let read = class_metrics(storm, OpClass::CanonicalRead);+ checks.push(max_latency_check(+ "storm read p99",+ read.schedule.count,+ read.schedule.p99_nanos,+ thresholds.storm_read_p99_ms,+ ));+ } else {+ checks.push(missing_phase("storm gate", PhaseName::MergeStorm));+ }++ if let (Some(storm), Some(recovery)) = (+ phase(phases, PhaseName::MergeStorm),+ phase(phases, PhaseName::Recovery),+ ) {+ let recovery_outcome = recovery_time(+ recovery,+ Duration::from_nanos(storm.summary.post_deadline_duration_nanos),+ thresholds,+ );+ checks.push(GateCheck {+ name: "recovery time".to_owned(),+ passed: matches!(+ recovery_outcome,+ RecoveryOutcome::Recovered(elapsed)+ if elapsed <= Duration::from_secs(thresholds.recovery_max_secs)+ ),+ detail: match recovery_outcome {+ RecoveryOutcome::Recovered(elapsed) => {+ format!(+ "{:.1}s from storm end, limit {}s",+ elapsed.as_secs_f64(),+ thresholds.recovery_max_secs+ )+ }+ RecoveryOutcome::NoReadTraffic => {+ "no read traffic was observed during recovery".to_owned()+ }+ RecoveryOutcome::NotRecovered => {+ "read SLO was not restored for the remainder of recovery".to_owned()+ }+ },+ });+ let vacuumed = [TableGroup::Person, TableGroup::DistinctIdMap]+ .into_iter()+ .all(|group| {+ recovery.pg.iter().any(|record| {+ record+ .tables+ .iter()+ .any(|table| table.group == group && table.vacuums > 0)+ })+ });+ checks.push(GateCheck {+ name: "recovery vacuum observed".to_owned(),+ passed: vacuumed,+ detail: if vacuumed {+ "manual vacuum counters advanced for both table groups".to_owned()+ } else {+ "manual vacuum counters did not advance for both table groups".to_owned()+ },+ });+ } else if phase(phases, PhaseName::Recovery).is_none() {+ checks.push(missing_phase("recovery gate", PhaseName::Recovery));+ } else {+ checks.push(missing_phase("recovery gate", PhaseName::MergeStorm));+ }++ if let Some(catch_up) = phase(phases, PhaseName::CatchUp) {+ for (class, average) in [+ (OpClass::PersonUpsert, PROD_US_RATES.person_upsert.average),+ (+ OpClass::DistinctIdAssignment,+ PROD_US_RATES.distinct_id_assignment.average,+ ),+ (OpClass::Merge, PROD_US_RATES.merge.average),+ ] {+ let headroom = achieved_rate(catch_up, class) / average.get();+ checks.push(GateCheck {+ name: catch_up_check_name(class).to_owned(),+ passed: headroom >= thresholds.catch_up_headroom,+ detail: format!(+ "{headroom:.2}x average, required {:.2}x",+ thresholds.catch_up_headroom+ ),+ });+ }+ let read = class_metrics(catch_up, OpClass::CanonicalRead);+ checks.push(max_latency_check(+ "catch-up read p99",+ read.schedule.count,+ read.schedule.p99_nanos,+ thresholds.steady_read_p99_ms,+ ));+ checks.push(max_latency_check(+ "catch-up read p50",+ read.schedule.count,+ read.schedule.p50_nanos,+ thresholds.steady_read_p50_ms,+ ));+ } else {+ checks.push(missing_phase("catch-up gate", PhaseName::CatchUp));+ }++ let dispatch_limit_nanos = millis_to_nanos(thresholds.dispatch_p99_ms);+ let harness_limited = phases.iter().any(|phase| {+ phase+ .intervals+ .iter()+ .filter(|interval| interval.started_at_nanos < phase.summary.duration_nanos)+ .any(|interval| {+ phase.targets.iter().any(|target| {+ target.feed == FeedMode::Open+ && target.target.is_active()+ && interval.classes[target.class.index()].dispatch_lag.count > 0+ && interval.classes[target.class.index()]+ .dispatch_lag+ .p99_nanos+ > dispatch_limit_nanos+ })+ })+ });+ checks.push(GateCheck {+ name: "load generator dispatch p99".to_owned(),+ passed: !harness_limited,+ detail: if harness_limited {+ format!(+ "at least one class exceeded {:.2}ms; result is harness-limited",+ thresholds.dispatch_p99_ms+ )+ } else {+ format!(+ "all classes at or below {:.2}ms",+ thresholds.dispatch_p99_ms+ )+ },+ });+ let passed = checks.iter().all(|check| check.passed);+ GateEvaluation {+ passed,+ harness_limited,+ checks,+ unverified_qualifications: vec![+ "dead tuples and index size plateau, with autovacuum keeping up per partition"+ .to_owned(),+ "bootstrap throughput extrapolates to the accepted full-backfill window".to_owned(),+ "production-candidate instance uses a working set at least 3-5x RAM".to_owned(),+ "load generator has guaranteed CPU and is not externally throttled".to_owned(),+ ],+ }}-fn print_phase_row(result: &PhaseResult, show_pg_metrics: bool) {- let delta = compute_delta(&result.before, &result.after);+fn add_phase_integrity_checks(+ checks: &mut Vec<GateCheck>,+ phases: &[PhaseResult],+ thresholds: GateThresholds,+) {+ for phase in phases {+ let shed = phase+ .summary+ .classes+ .iter()+ .map(|class| class.counts.shed.saturating_add(class.counts.closed))+ .sum::<u64>();+ checks.push(GateCheck {+ name: format!("{} zero shed", phase.name.as_str()),+ passed: shed == 0,+ detail: format!("{shed} operations shed or sent to a closed executor"),+ });- let wal_mib = match result.wal_bytes {- Some(b) => fmt_bytes_mib(b),- None => "N/A".into(),- };+ let errors = phase+ .summary+ .classes+ .iter()+ .map(|class| class.counts.errors)+ .sum::<u64>();+ checks.push(GateCheck {+ name: format!("{} zero errors", phase.name.as_str()),+ passed: errors == 0,+ detail: format!("{errors} operation errors"),+ });++ for target in phase+ .targets+ .iter()+ .filter(|target| target.feed == FeedMode::Open && target.target.is_active())+ {+ let class = target.class;+ let target_rate = target.target.get();+ let scheduled = scheduled_rate(phase, class);+ let achieved = achieved_rate(phase, class);+ let scheduled_error = rate_error_percent(scheduled, target_rate);+ let schedule_tolerance = poisson_rate_tolerance_percent(+ target_rate,+ phase.duration,+ thresholds.rate_tolerance_percent,+ );+ let deadline_counts = phase.summary.deadline_counts[class.index()];+ let achieved_error =+ completion_shortfall_percent(deadline_counts.achieved, deadline_counts.scheduled);+ checks.push(GateCheck {+ name: format!(+ "{} {} scheduled rate",+ phase.name.as_str(),+ class_name(class)+ ),+ passed: scheduled_error <= schedule_tolerance,+ detail: format!(+ "{scheduled:.1}/s scheduled vs {target_rate:.1}/s target ({scheduled_error:.2}% error, {schedule_tolerance:.2}% Poisson limit)"+ ),+ });+ checks.push(GateCheck {+ name: format!(+ "{} {} achieved rate",+ phase.name.as_str(),+ class_name(class)+ ),+ passed: achieved_error <= thresholds.rate_tolerance_percent,+ detail: format!(+ "{achieved:.1}/s completed by deadline vs {scheduled:.1}/s scheduled ({achieved_error:.2}% shortfall, {:.2}% limit)",+ thresholds.rate_tolerance_percent+ ),+ });++ let outstanding = outstanding_at_deadline(phase, class);+ let backlog_secs = outstanding as f64 / target_rate;+ checks.push(GateCheck {+ name: format!(+ "{} {} deadline backlog",+ phase.name.as_str(),+ class_name(class)+ ),+ passed: backlog_secs <= thresholds.max_backlog_secs,+ detail: format!(+ "{outstanding} outstanding ({backlog_secs:.3}s at target), limit {:.3}s",+ thresholds.max_backlog_secs+ ),+ });+ }+ }+}++pub fn print_report(+ postgres_version: &str,+ settings: &[(String, String)],+ seed: u64,+ phases: &[PhaseResult],+ gates: &GateEvaluation,+) {+ println!("\n=== Read-store schema benchmark report ===");+ println!("PostgreSQL: {postgres_version}");+ println!("Seed: {seed}");+ for (name, value) in settings {+ println!("{name}: {value}");+ }- if show_pg_metrics {+ for phase in phases {println!(- " {:<24} | {:>6} | {:>7} | {:>7} | {:>7} | {:>7} | {:>6} | {:>6.1}% | {:>11} | {:>9} | {:>9} | {:>7}",- result.name,- result.latency.count,- fmt_duration_ms(result.latency.p50),- fmt_duration_ms(result.latency.p95),- fmt_duration_ms(result.latency.p99),- fmt_duration_ms(result.latency.max),- result.errors,- delta.hot_pct,- delta.dead_tuples,- fmt_bytes_mib(result.after.table_bytes),- fmt_bytes_mib(result.after.index_bytes),- wal_mib,+ "\n{} ({:.1}s workload + {:.3}s post-deadline, including {:.3}s executor drain)",+ phase.name.as_str(),+ phase.duration.as_secs_f64(),+ Duration::from_nanos(phase.summary.post_deadline_duration_nanos).as_secs_f64(),+ Duration::from_nanos(phase.summary.drain_duration_nanos).as_secs_f64(),);- } else {println!(- " {:<24} | {:>6} | {:>7} | {:>7} | {:>7} | {:>7} | {:>6} | {:>7} | {:>11} | {:>9} | {:>9} | {:>7}",- result.name,- result.latency.count,- fmt_duration_ms(result.latency.p50),- fmt_duration_ms(result.latency.p95),- fmt_duration_ms(result.latency.p99),- fmt_duration_ms(result.latency.max),- result.errors,- "",- "",- "",- "",- "",+ " {:<23} {:>10} {:>10} {:>9} {:>11} {:>8} {:>8} {:>8} {:>8} {:>23} {:>23} {:>23} {:>23} {:>13}",+ "Class",+ "Sched/s",+ "Done/s",+ "Complete",+ "Deadline q",+ "Errors",+ "Shed",+ "Retry",+ "Deadlock",+ "Service p50/p95/p99/max",+ "Schedule p50/p95/p99/max",+ "Queue p50/p95/p99/max",+ "Dispatch p50/p95/p99/max",+ "Headroom/peak");+ for class in &phase.summary.classes {+ let headroom = catch_up_headroom(phase, class.class);+ println!(+ " {:<23} {:>10.1} {:>10.1} {:>9} {:>11} {:>8} {:>8} {:>8} {:>8} {:>23} {:>23} {:>23} {:>23} {:>12}",+ class_name(class.class),+ scheduled_rate(phase, class.class),+ achieved_rate(phase, class.class),+ class.counts.completed,+ outstanding_at_deadline(phase, class.class),+ class.counts.errors,+ class.counts.shed + class.counts.closed,+ format!("{}/{}", class.counts.retry_affected, class.counts.retry_attempts),+ format!("{}/{}", class.counts.deadlock_affected, class.counts.deadlock_attempts),+ latency_set(class.service),+ latency_set(class.schedule),+ latency_set(class.queue),+ latency_set(class.dispatch_lag),+ headroom.map_or_else(|| "-".to_owned(), |value| format!("{value:.2}x")),+ );+ }+ print_pg_summary(&phase.pg);}-}-pub fn print_report(args: &BenchmarkArgs, results: &[PhaseResult], query_plan: &QueryPlanInfo) {- println!();- println!("=== GIN Index Benchmark Report ===");println!(- "Scale: {} rows | Teams: {} | Concurrency: {} | Burst: {}x | Duration: {}s/phase",- args.scale, args.teams, args.concurrency, args.burst_factor, args.duration_secs+ "\nAutomated gate result: {}",+ if gates.passed { "PASS" } else { "FAIL" });- println!(- "GIN index used for reads: {}",- if query_plan.gin_index_used {- "yes"+ for check in &gates.checks {+ println!(+ " {} {:<30} {}",+ if check.passed { "PASS" } else { "FAIL" },+ check.name,+ check.detail+ );+ }+ println!("Manual qualifications still required:");+ for qualification in &gates.unverified_qualifications {+ println!(" - {qualification}");+ }+}++fn phase(phases: &[PhaseResult], name: PhaseName) -> Option<&PhaseResult> {+ phases.iter().find(|phase| phase.name == name)+}++fn class_metrics(phase: &PhaseResult, class: OpClass) -> &ClassMetrics {+ &phase.summary.classes[class.index()]+}++fn achieved_rate(phase: &PhaseResult, class: OpClass) -> f64 {+ phase.summary.deadline_counts[class.index()].achieved as f64 / phase.duration.as_secs_f64()+}++fn scheduled_rate(phase: &PhaseResult, class: OpClass) -> f64 {+ phase.summary.deadline_counts[class.index()].scheduled as f64 / phase.duration.as_secs_f64()+}++fn outstanding_at_deadline(phase: &PhaseResult, class: OpClass) -> u64 {+ let counts = phase.summary.deadline_counts[class.index()];+ counts+ .scheduled+ .saturating_sub(counts.shed)+ .saturating_sub(counts.closed)+ .saturating_sub(counts.completed)+}++fn rate_error_percent(actual: f64, target: f64) -> f64 {+ ((actual - target).abs() / target) * 100.0+}++fn poisson_rate_tolerance_percent(+ target_rate: f64,+ duration: Duration,+ configured_tolerance: f64,+) -> f64 {+ let expected_count = target_rate * duration.as_secs_f64();+ configured_tolerance.max(400.0 / expected_count.sqrt())+}++fn completion_shortfall_percent(achieved: u64, scheduled: u64) -> f64 {+ if scheduled == 0 {+ return 100.0;+ }+ scheduled.saturating_sub(achieved) as f64 / scheduled as f64 * 100.0+}++fn catch_up_headroom(phase: &PhaseResult, class: OpClass) -> Option<f64> {+ if phase.name != PhaseName::CatchUp || class == OpClass::CanonicalRead {+ return None;+ }+ let peak = match class {+ OpClass::PersonUpsert => PROD_US_RATES.person_upsert.five_minute_peak,+ OpClass::DistinctIdAssignment => PROD_US_RATES.distinct_id_assignment.five_minute_peak,+ OpClass::Merge => PROD_US_RATES.merge.five_minute_peak,+ OpClass::CanonicalRead => unreachable!(),+ };+ Some(achieved_rate(phase, class) / peak.get())+}++fn read_drift_ratio(phase: &PhaseResult) -> Option<f64> {+ let values = phase+ .intervals+ .iter()+ .filter_map(|interval| {+ let read = &interval.classes[OpClass::CanonicalRead.index()];+ (interval.started_at_nanos < phase.summary.duration_nanos && read.schedule.count > 0)+ .then_some(read.schedule.p99_nanos)+ })+ .collect::<Vec<_>>();+ if values.len() < 5 {+ return None;+ }+ let settled = &values[1..];+ let middle = settled.len() / 2;+ let early = median(&settled[..middle])?;+ let late = median(&settled[middle..])?;+ Some(late as f64 / early as f64)+}++fn median(values: &[u64]) -> Option<u64> {+ let mut values = values.to_vec();+ values.sort_unstable();+ values.get(values.len() / 2).copied()+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum RecoveryOutcome {+ Recovered(Duration),+ NoReadTraffic,+ NotRecovered,+}++fn recovery_time(+ phase: &PhaseResult,+ storm_post_deadline: Duration,+ thresholds: GateThresholds,+) -> RecoveryOutcome {+ let active_intervals = phase+ .intervals+ .iter()+ .filter(|interval| {+ interval.started_at_nanos < phase.summary.duration_nanos+ && interval.classes[OpClass::CanonicalRead.index()]+ .counts+ .scheduled+ > 0+ })+ .collect::<Vec<_>>();+ if active_intervals.is_empty() {+ return RecoveryOutcome::NoReadTraffic;+ }+ let recovered_interval = active_intervals+ .iter()+ .enumerate()+ .find_map(|(index, interval)| {+ let remains_recovered = active_intervals[index..].iter().all(|candidate| {+ let read = &candidate.classes[OpClass::CanonicalRead.index()];+ nanos_millis(read.schedule.p50_nanos) <= thresholds.steady_read_p50_ms+ && nanos_millis(read.schedule.p99_nanos) <= thresholds.steady_read_p99_ms+ });+ remains_recovered.then_some(*interval)+ });+ let Some(recovered_interval) = recovered_interval else {+ return RecoveryOutcome::NotRecovered;+ };+ RecoveryOutcome::Recovered(+ storm_post_deadline+ + phase.pre_hook_duration+ + Duration::from_nanos(recovered_interval.ended_at_nanos),+ )+}++fn max_latency_check(+ name: impl Into<String>,+ sample_count: u64,+ actual_nanos: u64,+ limit_ms: f64,+) -> GateCheck {+ let actual_ms = nanos_millis(actual_nanos);+ GateCheck {+ name: name.into(),+ passed: sample_count > 0 && actual_ms <= limit_ms,+ detail: if sample_count == 0 {+ "no latency samples".to_owned()} else {- "NO (planner chose sequential scan)"+ format!("{actual_ms:.3}ms, limit {limit_ms:.3}ms ({sample_count} samples)")+ },+ }+}++fn nanos_millis(nanos: u64) -> f64 {+ nanos as f64 / NANOS_PER_MILLISECOND+}++fn missing_phase(name: &'static str, phase: PhaseName) -> GateCheck {+ GateCheck {+ name: name.to_owned(),+ passed: false,+ detail: format!("missing {} phase", phase.as_str()),+ }+}++fn millis_to_nanos(millis: f64) -> u64 {+ (millis * NANOS_PER_MILLISECOND) as u64+}++fn latency_set(summary: LatencySummary) -> String {+ format!(+ "{}/{}/{}/{}",+ latency_ms(summary.p50_nanos),+ latency_ms(summary.p95_nanos),+ latency_ms(summary.p99_nanos),+ latency_ms(summary.max_nanos)+ )+}++fn latency_ms(nanos: u64) -> String {+ format!("{:.2}", nanos as f64 / NANOS_PER_MILLISECOND)+}++fn class_name(class: OpClass) -> &'static str {+ match class {+ OpClass::PersonUpsert => "person_upsert",+ OpClass::DistinctIdAssignment => "distinct_id_assignment",+ OpClass::Merge => "merge",+ OpClass::CanonicalRead => "canonical_read",+ }+}++fn catch_up_check_name(class: OpClass) -> &'static str {+ match class {+ OpClass::PersonUpsert => "catch-up person headroom",+ OpClass::DistinctIdAssignment => "catch-up distinct ID headroom",+ OpClass::Merge => "catch-up merge headroom",+ OpClass::CanonicalRead => "catch-up read headroom",+ }+}++fn print_pg_summary(records: &[PgDeltaRecord]) {+ for group in [TableGroup::Person, TableGroup::DistinctIdMap] {+ let deltas = records+ .iter()+ .flat_map(|record| record.tables.iter())+ .filter(|table| table.group == group)+ .collect::<Vec<_>>();+ let Some(last) = deltas.last() else {+ continue;+ };+ let inserts = deltas.iter().map(|table| table.inserts).sum::<u64>();+ let updates = deltas.iter().map(|table| table.updates).sum::<u64>();+ let deletes = deltas.iter().map(|table| table.deletes).sum::<u64>();+ let hot = deltas.iter().map(|table| table.hot_updates).sum::<u64>();+ let vacuums = deltas.iter().map(|table| table.vacuums).sum::<u64>();+ let autovacuums = deltas.iter().map(|table| table.autovacuums).sum::<u64>();+ let stats_reset = deltas.iter().any(|table| table.stats_reset_detected);+ let hot_percent = if updates == 0 {+ 0.0+ } else {+ hot as f64 / updates as f64 * 100.0+ };+ println!(+ " PG {:?}: ins {} | upd {} | del {} | HOT {:.1}% | dead {} | vacuum {}/{} | heap {:.1} MiB | index {:.1} MiB{}",+ group,+ inserts,+ updates,+ deletes,+ hot_percent,+ last.dead_tuples,+ vacuums,+ autovacuums,+ bytes_mib(last.heap_bytes),+ bytes_mib(last.index_bytes),+ if stats_reset { " | stats reset" } else { "" },+ );+ }+ let unavailable = records.iter().find_map(|record| match &record.wal {+ WalDelta::Unavailable { reason } => Some(reason.as_ref()),+ WalDelta::Available { .. } => None,+ });+ let wal = records+ .iter()+ .filter_map(|record| match record.wal {+ WalDelta::Available { bytes } => Some(bytes),+ WalDelta::Unavailable { .. } => None,+ })+ .sum::<u64>();+ match unavailable {+ Some(reason) => println!(" PG WAL: unavailable ({reason})"),+ None => println!(" PG WAL: {:.1} MiB", bytes_mib(wal)),+ }+}++fn bytes_mib(bytes: u64) -> f64 {+ bytes as f64 / (1024.0 * 1024.0)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::benchmark::collector::{LatencySummary, OperationCounts};+ use crate::benchmark::ops::PhaseId;+ use crate::benchmark::rates::{FeedMode, RatePerSecond};++ fn metrics(class: OpClass, achieved: u64, schedule_p99_ms: u64) -> ClassMetrics {+ ClassMetrics {+ class,+ counts: OperationCounts {+ scheduled: achieved,+ completed: achieved,+ achieved,+ ..OperationCounts::default()+ },+ service: LatencySummary::default(),+ schedule: LatencySummary {+ count: achieved,+ p50_nanos: 500_000,+ p99_nanos: schedule_p99_ms * 1_000_000,+ ..LatencySummary::default()+ },+ queue: LatencySummary::default(),+ dispatch_lag: LatencySummary::default(),}- );- println!();+ }- let header = format!(- " {:<24} | {:>6} | {:>7} | {:>7} | {:>7} | {:>7} | {:>6} | {:>7} | {:>11} | {:>9} | {:>9} | {:>7}",- "Phase", "Ops", "p50", "p95", "p99", "max", "Errors", "HOT%", "Dead Tuples", "Table MiB", "Index MiB", "WAL MiB"- );- let separator = "-".repeat(header.len());+ fn result(name: PhaseName, duration_secs: u64) -> PhaseResult {+ let duration = Duration::from_secs(duration_secs);+ let rates = [+ (OpClass::PersonUpsert, 5_788.0),+ (OpClass::DistinctIdAssignment, 3_594.0),+ (OpClass::Merge, 54.6),+ (OpClass::CanonicalRead, 14_474.0),+ ];+ let classes =+ rates.map(|(class, rate)| metrics(class, (rate * duration_secs as f64) as u64, 1));+ let deadline_counts = classes.map(|class| class.counts);+ PhaseResult {+ name,+ duration,+ pre_hook_duration: Duration::from_secs(1),+ targets: rates.map(|(class, rate)| RateSpec {+ class,+ target: RatePerSecond::new(rate),+ feed: if name == PhaseName::CatchUp && class != OpClass::CanonicalRead {+ FeedMode::Closed+ } else {+ FeedMode::Open+ },+ }),+ summary: PhaseSummaryRecord {+ record_type: "phase_summary",+ phase_id: PhaseId::new(name as u64 + 1),+ duration_nanos: duration.as_nanos() as u64,+ drain_duration_nanos: 0,+ post_deadline_duration_nanos: 0,+ deadline_counts,+ classes,+ },+ intervals: Vec::new(),+ pg: Vec::new(),+ }+ }++ fn thresholds() -> GateThresholds {+ GateThresholds {+ steady_read_p50_ms: 1.0,+ steady_read_p99_ms: 5.0,+ storm_read_p99_ms: 10.0,+ recovery_max_secs: 900,+ catch_up_headroom: 5.0,+ dispatch_p99_ms: 5.0,+ rate_tolerance_percent: 2.0,+ max_read_drift_ratio: 1.2,+ max_backlog_secs: 1.0,+ }+ }++ #[test]+ fn gates_reject_latency_and_catch_up_capacity_regressions() {+ let mut phases = vec![+ result(PhaseName::PeakMix, 10),+ result(PhaseName::MergeStorm, 10),+ result(PhaseName::Recovery, 10),+ result(PhaseName::CatchUp, 10),+ ];+ phases[1].summary.classes[OpClass::CanonicalRead.index()]+ .schedule+ .p99_nanos = 11_000_000;+ phases[3].summary.deadline_counts[OpClass::Merge.index()].achieved = 1;+ let evaluation = evaluate_gates(&phases, thresholds());++ assert!(!evaluation.passed);+ assert!(evaluation+ .checks+ .iter()+ .any(|check| check.name == "storm read p99" && !check.passed));+ assert!(evaluation+ .checks+ .iter()+ .any(|check| check.name == "catch-up merge headroom" && !check.passed));+ }++ #[test]+ fn post_deadline_completions_do_not_satisfy_an_open_rate_gate() {+ let mut peak = result(PhaseName::PeakMix, 10);+ let read = OpClass::CanonicalRead.index();+ peak.summary.deadline_counts[read].completed = 0;+ peak.summary.deadline_counts[read].achieved = 0;++ let evaluation = evaluate_gates(&[peak], thresholds());++ assert!(evaluation.checks.iter().any(|check| {+ check.name == "peak_mix canonical_read achieved rate" && !check.passed+ }));+ assert!(evaluation.checks.iter().any(|check| {+ check.name == "peak_mix canonical_read deadline backlog" && !check.passed+ }));+ }- println!("{header}");- println!("{separator}");+ #[test]+ fn closed_feed_dispatch_wait_is_not_a_harness_failure() {+ let mut catch_up = result(PhaseName::CatchUp, 10);+ let mut classes = catch_up.summary.classes;+ classes[OpClass::Merge.index()].dispatch_lag = LatencySummary {+ count: 1,+ p99_nanos: 100_000_000,+ ..LatencySummary::default()+ };+ catch_up.intervals.push(IntervalRecord {+ record_type: "interval",+ phase_id: catch_up.summary.phase_id,+ interval_index: 0,+ started_at_nanos: 0,+ ended_at_nanos: 10_000_000_000,+ classes,+ });- for result in results {- let is_read = result.name.contains("reads");- print_phase_row(result, !is_read);+ let evaluation = evaluate_gates(&[catch_up], thresholds());++ assert!(!evaluation.harness_limited);+ }++ #[test]+ fn low_rate_poisson_variance_uses_a_statistical_schedule_limit() {+ let mut recovery = result(PhaseName::Recovery, 60);+ recovery.targets[OpClass::Merge.index()].target = RatePerSecond::new(17.2);+ recovery.summary.deadline_counts[OpClass::Merge.index()] = OperationCounts {+ scheduled: 966,+ completed: 966,+ achieved: 966,+ ..OperationCounts::default()+ };++ let evaluation = evaluate_gates(&[recovery], thresholds());++ assert!(evaluation+ .checks+ .iter()+ .any(|check| { check.name == "recovery merge scheduled rate" && check.passed }));+ }++ #[test]+ fn storm_post_deadline_work_is_charged_to_recovery() {+ let mut storm = result(PhaseName::MergeStorm, 60);+ storm.summary.post_deadline_duration_nanos = Duration::from_secs(901).as_nanos() as u64;+ let mut recovery = result(PhaseName::Recovery, 60);+ recovery.pre_hook_duration = Duration::ZERO;+ let mut classes = recovery.summary.classes;+ let read = &mut classes[OpClass::CanonicalRead.index()];+ read.counts.scheduled = 100;+ read.schedule = LatencySummary {+ count: 100,+ p50_nanos: 500_000,+ p99_nanos: 1_000_000,+ ..LatencySummary::default()+ };+ recovery.intervals.push(IntervalRecord {+ record_type: "interval",+ phase_id: recovery.summary.phase_id,+ interval_index: 0,+ started_at_nanos: 0,+ ended_at_nanos: 10_000_000_000,+ classes,+ });++ let evaluation = evaluate_gates(&[storm, recovery], thresholds());++ assert!(evaluation+ .checks+ .iter()+ .any(|check| check.name == "recovery time" && !check.passed));}- println!();+ #[test]+ fn recovery_ignores_the_pure_drain_interval() {+ let mut recovery = result(PhaseName::Recovery, 10);+ recovery.pre_hook_duration = Duration::ZERO;+ let mut workload_classes = recovery.summary.classes;+ let read = &mut workload_classes[OpClass::CanonicalRead.index()];+ read.counts.scheduled = 100;+ read.schedule = LatencySummary {+ count: 100,+ p50_nanos: 500_000,+ p99_nanos: 1_000_000,+ ..LatencySummary::default()+ };+ recovery.intervals.push(IntervalRecord {+ record_type: "interval",+ phase_id: recovery.summary.phase_id,+ interval_index: 0,+ started_at_nanos: 0,+ ended_at_nanos: 10_000_000_000,+ classes: workload_classes,+ });++ let mut drain_classes = workload_classes;+ let drain_read = &mut drain_classes[OpClass::CanonicalRead.index()];+ drain_read.counts.scheduled = 1;+ drain_read.schedule.p50_nanos = 100_000_000;+ drain_read.schedule.p99_nanos = 100_000_000;+ recovery.intervals.push(IntervalRecord {+ record_type: "interval",+ phase_id: recovery.summary.phase_id,+ interval_index: 1,+ started_at_nanos: 10_000_000_000,+ ended_at_nanos: 11_000_000_000,+ classes: drain_classes,+ });++ assert_eq!(+ recovery_time(&recovery, Duration::ZERO, thresholds()),+ RecoveryOutcome::Recovered(Duration::from_secs(10))+ );+ }++ #[test]+ fn recovery_reports_no_read_traffic_separately() {+ let recovery = result(PhaseName::Recovery, 10);++ assert_eq!(+ recovery_time(&recovery, Duration::ZERO, thresholds()),+ RecoveryOutcome::NoReadTraffic+ );+ }}diff --git a/rust/flags-consumer/src/benchmark/scheduler.rs b/rust/flags-consumer/src/benchmark/scheduler.rsnew file mode 100644index 000000000000..54c9c92bb967--- /dev/null+++ b/rust/flags-consumer/src/benchmark/scheduler.rs@@ -0,0 +1,548 @@+use std::cmp::Reverse;+use std::collections::BinaryHeap;+use std::fmt;+use std::num::NonZeroUsize;+use std::time::Duration;++use rand::rngs::StdRng;+use rand::{Rng, SeedableRng};+use serde::Serialize;+use tokio::sync::mpsc;++use super::ops::{+ DispatchedOperation, NanosSincePhaseStart, OpClass, OpDescriptor, OperationId, PhaseId,+ PhaseMismatch, TimestampOrderError,+};+use super::rates::{FeedMode, RatePerSecond, RateSpec};++const NANOS_PER_SECOND: f64 = 1_000_000_000.0;+const CLASS_SEED_MIX: u64 = 0x9e37_79b9_7f4a_7c15;++#[derive(Debug)]+struct ClassSchedule {+ rate: RatePerSecond,+ rng: StdRng,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+struct HeapEntry {+ scheduled_at: NanosSincePhaseStart,+ class: OpClass,+}++impl Ord for HeapEntry {+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {+ self.scheduled_at+ .as_nanos()+ .cmp(&other.scheduled_at.as_nanos())+ .then_with(|| self.class.cmp(&other.class))+ }+}++impl PartialOrd for HeapEntry {+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {+ Some(self.cmp(other))+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct ScheduledArrival {+ pub class: OpClass,+ pub scheduled_at: NanosSincePhaseStart,+}++#[derive(Debug)]+pub struct ArrivalSchedule {+ phase_id: PhaseId,+ classes: [Option<ClassSchedule>; OpClass::COUNT],+ heap: BinaryHeap<Reverse<HeapEntry>>,+}++impl ArrivalSchedule {+ pub fn new(phase_id: PhaseId, seed: u64, rates: &[RateSpec]) -> Result<Self, ArrivalError> {+ let mut classes: [Option<ClassSchedule>; OpClass::COUNT] = std::array::from_fn(|_| None);+ let mut heap = BinaryHeap::new();+ let mut seen = [false; OpClass::COUNT];++ for rate in rates {+ let index = rate.class.index();+ if seen[index] {+ return Err(ArrivalError::DuplicateClass(rate.class));+ }+ seen[index] = true;+ if !rate.target.get().is_finite() || rate.target.get() < 0.0 {+ return Err(ArrivalError::InvalidRate {+ class: rate.class,+ rate: rate.target.get(),+ });+ }+ if !rate.target.is_active() || rate.feed == FeedMode::Closed {+ continue;+ }++ let class_seed =+ seed ^ CLASS_SEED_MIX.wrapping_mul(u64::try_from(index + 1).unwrap_or(u64::MAX));+ let mut class_schedule = ClassSchedule {+ rate: rate.target,+ rng: StdRng::seed_from_u64(class_seed),+ };+ let first_at = sample_interval_nanos(&mut class_schedule.rng, rate.target);+ heap.push(Reverse(HeapEntry {+ scheduled_at: NanosSincePhaseStart::from_nanos(phase_id, first_at),+ class: rate.class,+ }));+ classes[index] = Some(class_schedule);+ }++ Ok(Self {+ phase_id,+ classes,+ heap,+ })+ }++ pub fn phase_id(&self) -> PhaseId {+ self.phase_id+ }++ pub fn peek_next_at(&self) -> Option<NanosSincePhaseStart> {+ self.heap.peek().map(|entry| entry.0.scheduled_at)+ }++ pub fn next_arrival(&mut self) -> Option<ScheduledArrival> {+ let Reverse(entry) = self.heap.pop()?;+ self.advance(entry);+ Some(ScheduledArrival {+ class: entry.class,+ scheduled_at: entry.scheduled_at,+ })+ }++ pub fn pop_due(+ &mut self,+ now: NanosSincePhaseStart,+ ) -> Result<Option<ScheduledArrival>, ArrivalError> {+ if now.phase_id() != self.phase_id {+ return Err(ArrivalError::PhaseMismatch(PhaseMismatch {+ expected: self.phase_id,+ actual: now.phase_id(),+ }));+ }+ let Some(next_at) = self.peek_next_at() else {+ return Ok(None);+ };+ if next_at.as_nanos() > now.as_nanos() {+ return Ok(None);+ }+ Ok(self.next_arrival())+ }++ fn advance(&mut self, entry: HeapEntry) {+ let class_schedule = self.classes[entry.class.index()]+ .as_mut()+ .expect("heap entries always have class state");+ let interval = sample_interval_nanos(&mut class_schedule.rng, class_schedule.rate);+ let Some(next_at) = entry.scheduled_at.checked_add(interval) else {+ self.classes[entry.class.index()] = None;+ return;+ };+ self.heap.push(Reverse(HeapEntry {+ scheduled_at: next_at,+ class: entry.class,+ }));+ }+}++#[derive(Debug, Clone, PartialEq)]+pub enum ArrivalError {+ PhaseMismatch(PhaseMismatch),+ DuplicateClass(OpClass),+ InvalidRate { class: OpClass, rate: f64 },+}++impl fmt::Display for ArrivalError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::PhaseMismatch(error) => error.fmt(formatter),+ Self::DuplicateClass(class) => write!(formatter, "duplicate rate for {class:?}"),+ Self::InvalidRate { class, rate } => {+ write!(formatter, "invalid arrival rate {rate} for {class:?}")+ }+ }+ }+}++impl std::error::Error for ArrivalError {}++fn sample_interval_nanos(rng: &mut impl Rng, rate: RatePerSecond) -> u64 {+ // Inverse exponential CDF; 1 - U keeps ln's input in (0, 1].+ let open_unit_interval = 1.0 - rng.gen::<f64>();+ let nanos = -open_unit_interval.ln() / rate.get() * NANOS_PER_SECOND;+ if !nanos.is_finite() || nanos >= u64::MAX as f64 {+ return u64::MAX;+ }+ (nanos.ceil() as u64).max(1)+}++#[derive(Debug, Clone, Copy)]+pub struct PhaseClock {+ phase_id: PhaseId,+ epoch: tokio::time::Instant,+}++impl PhaseClock {+ pub fn new(phase_id: PhaseId, epoch: tokio::time::Instant) -> Self {+ Self { phase_id, epoch }+ }++ pub fn start_now(phase_id: PhaseId) -> Self {+ Self::new(phase_id, tokio::time::Instant::now())+ }++ pub fn phase_id(&self) -> PhaseId {+ self.phase_id+ }++ pub fn now(&self) -> Result<NanosSincePhaseStart, ClockError> {+ let now = tokio::time::Instant::now();+ if now < self.epoch {+ return Err(ClockError::BeforePhaseEpoch);+ }+ let elapsed = now.duration_since(self.epoch);+ let nanos = u64::try_from(elapsed.as_nanos()).map_err(|_| ClockError::OutOfRange)?;+ Ok(NanosSincePhaseStart::from_nanos(self.phase_id, nanos))+ }++ pub async fn wait_until(&self, scheduled_at: NanosSincePhaseStart) -> Result<(), ClockError> {+ if scheduled_at.phase_id() != self.phase_id {+ return Err(ClockError::PhaseMismatch(PhaseMismatch {+ expected: self.phase_id,+ actual: scheduled_at.phase_id(),+ }));+ }+ let deadline = self+ .epoch+ .checked_add(Duration::from_nanos(scheduled_at.as_nanos()))+ .ok_or(ClockError::OutOfRange)?;+ tokio::time::sleep_until(deadline).await;+ Ok(())+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ClockError {+ PhaseMismatch(PhaseMismatch),+ BeforePhaseEpoch,+ OutOfRange,+}++impl fmt::Display for ClockError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::PhaseMismatch(error) => error.fmt(formatter),+ Self::BeforePhaseEpoch => formatter.write_str("clock precedes the phase epoch"),+ Self::OutOfRange => formatter.write_str("phase timestamp is outside the timer range"),+ }+ }+}++impl std::error::Error for ClockError {}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum DispatchOutcome {+ Enqueued,+ Shed,+ Closed,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+pub struct DispatchRecord {+ pub operation_id: OperationId,+ pub class: OpClass,+ scheduled_at: NanosSincePhaseStart,+ dispatched_at: NanosSincePhaseStart,+ pub outcome: DispatchOutcome,+}++impl DispatchRecord {+ pub fn scheduled_at(self) -> NanosSincePhaseStart {+ self.scheduled_at+ }++ pub fn dispatched_at(self) -> NanosSincePhaseStart {+ self.dispatched_at+ }++ pub fn dispatch_lag_nanos(self) -> u64 {+ self.dispatched_at.as_nanos() - self.scheduled_at.as_nanos()+ }+}++#[derive(Debug)]+pub struct BoundedDispatcher {+ sender: mpsc::Sender<DispatchedOperation>,+ shed: u64,+}++impl BoundedDispatcher {+ pub fn channel(capacity: NonZeroUsize) -> (Self, mpsc::Receiver<DispatchedOperation>) {+ let (sender, receiver) = mpsc::channel(capacity.get());+ (Self { sender, shed: 0 }, receiver)+ }++ pub fn shed_count(&self) -> u64 {+ self.shed+ }++ pub fn try_dispatch_at(+ &mut self,+ descriptor: OpDescriptor,+ dispatched_at: NanosSincePhaseStart,+ ) -> Result<DispatchRecord, DispatchError> {+ let operation_id = descriptor.operation_id;+ let class = descriptor.class();+ let scheduled_at = descriptor.scheduled_at;+ let dispatched = DispatchedOperation::try_new(descriptor, dispatched_at)+ .map_err(DispatchError::Timestamp)?;+ let outcome = match self.sender.try_send(dispatched) {+ Ok(()) => DispatchOutcome::Enqueued,+ Err(mpsc::error::TrySendError::Full(_)) => {+ self.shed = self.shed.saturating_add(1);+ DispatchOutcome::Shed+ }+ Err(mpsc::error::TrySendError::Closed(_)) => DispatchOutcome::Closed,+ };+ Ok(DispatchRecord {+ operation_id,+ class,+ scheduled_at,+ dispatched_at,+ outcome,+ })+ }++ pub async fn dispatch_with_backpressure(+ &self,+ descriptor: OpDescriptor,+ clock: &PhaseClock,+ ) -> Result<DispatchRecord, DispatchError> {+ let operation_id = descriptor.operation_id;+ let class = descriptor.class();+ if class == OpClass::CanonicalRead {+ return Err(DispatchError::ClosedLoopRead);+ }+ let scheduled_at = descriptor.scheduled_at;+ clock+ .wait_until(scheduled_at)+ .await+ .map_err(DispatchError::Clock)?;+ let permit = match self.sender.reserve().await {+ Ok(permit) => permit,+ Err(_) => {+ let dispatched_at = clock.now().map_err(DispatchError::Clock)?;+ DispatchedOperation::try_new(descriptor, dispatched_at)+ .map_err(DispatchError::Timestamp)?;+ return Ok(DispatchRecord {+ operation_id,+ class,+ scheduled_at,+ dispatched_at,+ outcome: DispatchOutcome::Closed,+ });+ }+ };+ let dispatched_at = clock.now().map_err(DispatchError::Clock)?;+ let dispatched = DispatchedOperation::try_new(descriptor, dispatched_at)+ .map_err(DispatchError::Timestamp)?;+ permit.send(dispatched);+ Ok(DispatchRecord {+ operation_id,+ class,+ scheduled_at,+ dispatched_at,+ outcome: DispatchOutcome::Enqueued,+ })+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DispatchError {+ ClosedLoopRead,+ Timestamp(TimestampOrderError),+ Clock(ClockError),+}++impl fmt::Display for DispatchError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::ClosedLoopRead => formatter.write_str("canonical reads must remain open-loop"),+ Self::Timestamp(error) => error.fmt(formatter),+ Self::Clock(error) => error.fmt(formatter),+ }+ }+}++impl std::error::Error for DispatchError {}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use super::*;+ use crate::benchmark::ops::{OpPayload, PersonUpsertPayload};++ const PHASE: PhaseId = PhaseId::new(1);++ fn open_rate(class: OpClass, target: f64) -> RateSpec {+ RateSpec {+ class,+ target: RatePerSecond::new(target),+ feed: FeedMode::Open,+ }+ }++ fn descriptor(id: u64, scheduled_at: u64) -> OpDescriptor {+ descriptor_in_phase(PHASE, id, scheduled_at)+ }++ fn descriptor_in_phase(phase_id: PhaseId, id: u64, scheduled_at: u64) -> OpDescriptor {+ OpDescriptor::new(+ OperationId(id),+ NanosSincePhaseStart::from_nanos(phase_id, scheduled_at),+ OpPayload::PersonUpsert(PersonUpsertPayload {+ team_id: 1,+ person_uuid: uuid::Uuid::nil(),+ properties: json!({}),+ version: 1,+ }),+ )+ }++ #[test]+ fn poisson_schedule_is_monotonic_and_independent_of_wakeup_delay() {+ let rates = [open_rate(OpClass::CanonicalRead, 14_474.0)];+ let mut direct = ArrivalSchedule::new(PHASE, 42, &rates).expect("valid schedule");+ let expected = (0..512)+ .map(|_| direct.next_arrival().expect("arrival"))+ .collect::<Vec<_>>();+ assert!(expected.windows(2).all(|window| {+ window[0].scheduled_at.as_nanos() < window[1].scheduled_at.as_nanos()+ }));++ let mut delayed = ArrivalSchedule::new(PHASE, 42, &rates).expect("valid schedule");+ let wakeup = NanosSincePhaseStart::from_nanos(+ PHASE,+ expected+ .last()+ .expect("last arrival")+ .scheduled_at+ .as_nanos()+ + 1_000_000,+ );+ let mut actual = Vec::with_capacity(expected.len());+ while actual.len() < expected.len() {+ actual.push(+ delayed+ .pop_due(wakeup)+ .expect("same phase")+ .expect("overdue arrival"),+ );+ }+ assert_eq!(actual, expected);+ }++ #[test]+ fn full_open_loop_channel_sheds_without_growing() {+ let capacity = NonZeroUsize::new(1).expect("nonzero");+ let (mut dispatcher, receiver) = BoundedDispatcher::channel(capacity);++ let accepted = dispatcher+ .try_dispatch_at(+ descriptor(1, 10),+ NanosSincePhaseStart::from_nanos(PHASE, 10),+ )+ .expect("on-time dispatch");+ let shed = dispatcher+ .try_dispatch_at(+ descriptor(2, 11),+ NanosSincePhaseStart::from_nanos(PHASE, 12),+ )+ .expect("late dispatch");++ assert_eq!(accepted.outcome, DispatchOutcome::Enqueued);+ assert_eq!(shed.outcome, DispatchOutcome::Shed);+ assert_eq!(shed.dispatch_lag_nanos(), 1);+ assert_eq!(dispatcher.shed_count(), 1);+ assert_eq!(receiver.len(), 1);+ }++ #[test]+ fn early_dispatch_is_rejected_before_touching_the_queue() {+ let capacity = NonZeroUsize::new(1).expect("nonzero");+ let (mut dispatcher, receiver) = BoundedDispatcher::channel(capacity);++ let result = dispatcher.try_dispatch_at(+ descriptor(1, 10),+ NanosSincePhaseStart::from_nanos(PHASE, 9),+ );++ assert!(matches!(+ result,+ Err(DispatchError::Timestamp(+ TimestampOrderError::DispatchBeforeSchedule+ ))+ ));+ assert_eq!(receiver.len(), 0);+ assert_eq!(dispatcher.shed_count(), 0);++ let mixed_phase = dispatcher.try_dispatch_at(+ descriptor(2, 10),+ NanosSincePhaseStart::from_nanos(PhaseId::new(2), 10),+ );+ assert!(matches!(+ mixed_phase,+ Err(DispatchError::Timestamp(+ TimestampOrderError::PhaseMismatch(_)+ ))+ ));+ assert_eq!(receiver.len(), 0);+ }++ #[tokio::test(start_paused = true)]+ async fn backpressured_dispatch_publishes_only_after_its_scheduled_time() {+ let phase_id = PhaseId::new(7);+ let clock = PhaseClock::start_now(phase_id);+ let capacity = NonZeroUsize::new(1).expect("nonzero");+ let (dispatcher, mut receiver) = BoundedDispatcher::channel(capacity);+ let task = tokio::spawn(async move {+ dispatcher+ .dispatch_with_backpressure(descriptor_in_phase(phase_id, 1, 10), &clock)+ .await+ });++ tokio::task::yield_now().await;+ assert!(matches!(+ receiver.try_recv(),+ Err(mpsc::error::TryRecvError::Empty)+ ));+ tokio::time::advance(Duration::from_nanos(10)).await;+ let received = receiver.recv().await.expect("published descriptor");+ let record = task.await.expect("dispatch task").expect("dispatch record");++ assert_eq!(received.operation_id(), OperationId(1));+ assert!(record.dispatched_at().as_nanos() >= record.scheduled_at().as_nanos());+ }++ #[test]+ fn invalid_arrival_rates_are_rejected_instead_of_disabled() {+ for invalid_rate in [-1.0, f64::NAN, f64::INFINITY] {+ let result = ArrivalSchedule::new(+ PHASE,+ 42,+ &[open_rate(OpClass::CanonicalRead, invalid_rate)],+ );+ assert!(matches!(result, Err(ArrivalError::InvalidRate { .. })));+ }+ }+}diff --git a/rust/flags-consumer/src/benchmark/schema.rs b/rust/flags-consumer/src/benchmark/schema.rsindex 7302b21501b4..8eb7b86d9ab2 100644--- a/rust/flags-consumer/src/benchmark/schema.rs+++ b/rust/flags-consumer/src/benchmark/schema.rs@@ -1,29 +1,83 @@+use std::collections::BTreeMap;++use anyhow::Context;+use serde::Serialize;use sqlx::PgPool;-pub const PARTITION_COUNT: usize = 64;+const PERSON_TABLE: &str = "flags_person";+const DISTINCT_ID_MAP_TABLE: &str = "flags_distinct_id_map";++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum SchemaSource {+ Created,+ Existing,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum PartitionStrategy {+ Hash,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct TableMetadata {+ pub name: String,+ pub partition_strategy: PartitionStrategy,+ pub partition_count: usize,+ pub partition_fillfactors: Vec<u8>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct SchemaMetadata {+ pub source: SchemaSource,+ pub requested_schema_arguments_applied: bool,+ pub person: TableMetadata,+ pub distinct_id_map: TableMetadata,+}++pub async fn create_schema(+ pool: &PgPool,+ partition_count: usize,+ person_fillfactor: u8,+ map_fillfactor: u8,+) -> anyhow::Result<()> {+ anyhow::ensure!(+ partition_count > 0,+ "--partitions must be greater than zero"+ );+ anyhow::ensure!(+ (10..=100).contains(&person_fillfactor),+ "--person-fillfactor must be between 10 and 100"+ );+ anyhow::ensure!(+ (10..=100).contains(&map_fillfactor),+ "--map-fillfactor must be between 10 and 100"+ );-pub async fn create_schema(pool: &PgPool) -> anyhow::Result<()> {tracing::info!("dropping existing schema (if any)");sqlx::query("DROP TABLE IF EXISTS flags_person_lookup CASCADE").execute(pool).await?;-- tracing::info!("creating btree_gin extension");- sqlx::query("CREATE EXTENSION IF NOT EXISTS btree_gin")+ sqlx::query("DROP TABLE IF EXISTS flags_distinct_id_map CASCADE")+ .execute(pool)+ .await?;+ sqlx::query("DROP TABLE IF EXISTS flags_person CASCADE").execute(pool).await?;- tracing::info!("creating flags_person_lookup table (hash-partitioned, 64 partitions)");+ tracing::info!(+ partition_count,+ "creating hash-partitioned read-store tables"+ );sqlx::query(r#"- CREATE TABLE IF NOT EXISTS flags_person_lookup (- team_id INTEGER NOT NULL,- person_uuid UUID NOT NULL,- distinct_ids TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],- properties JSONB NOT NULL DEFAULT '{}'::jsonb,- person_version BIGINT NOT NULL DEFAULT 0,- distinct_id_version BIGINT NOT NULL DEFAULT 0,- deleted_at TIMESTAMPTZ,+ CREATE TABLE flags_person (+ team_id INTEGER NOT NULL,+ person_uuid UUID NOT NULL,+ properties JSONB NOT NULL DEFAULT '{}'::JSONB,+ person_version BIGINT NOT NULL DEFAULT 0,+ deleted_at TIMESTAMPTZ,PRIMARY KEY (team_id, person_uuid)) PARTITION BY HASH (team_id)"#,@@ -31,35 +85,116 @@ pub async fn create_schema(pool: &PgPool) -> anyhow::Result<()> {.execute(pool).await?;- for i in 0..PARTITION_COUNT {- let ddl = format!(- "CREATE TABLE IF NOT EXISTS flags_person_lookup_p{i} \- PARTITION OF flags_person_lookup \- FOR VALUES WITH (MODULUS {PARTITION_COUNT}, REMAINDER {i})"- );- sqlx::query(&ddl).execute(pool).await?;- }-- tracing::info!("creating GIN index on (team_id, distinct_ids) WHERE deleted_at IS NULL");sqlx::query(- "CREATE INDEX IF NOT EXISTS idx_flags_person_gin \- ON flags_person_lookup USING GIN (team_id, distinct_ids) \- WHERE deleted_at IS NULL",+ r#"+ CREATE TABLE flags_distinct_id_map (+ team_id INTEGER NOT NULL,+ distinct_id TEXT NOT NULL,+ person_uuid UUID NOT NULL,+ version BIGINT NOT NULL DEFAULT 0,+ deleted_at TIMESTAMPTZ,+ PRIMARY KEY (team_id, distinct_id)+ ) PARTITION BY HASH (team_id)+ "#,).execute(pool).await?;+ for i in 0..partition_count {+ let person_ddl = format!(+ "CREATE TABLE flags_person_p{i} \+ PARTITION OF flags_person \+ FOR VALUES WITH (MODULUS {partition_count}, REMAINDER {i}) \+ WITH (fillfactor = {person_fillfactor})"+ );+ sqlx::query(&person_ddl).execute(pool).await?;++ let map_ddl = format!(+ "CREATE TABLE flags_distinct_id_map_p{i} \+ PARTITION OF flags_distinct_id_map \+ FOR VALUES WITH (MODULUS {partition_count}, REMAINDER {i}) \+ WITH (fillfactor = {map_fillfactor})"+ );+ sqlx::query(&map_ddl).execute(pool).await?;+ }+tracing::info!("schema created");Ok(())}pub async fn table_exists(pool: &PgPool) -> anyhow::Result<bool> {let row: (bool,) = sqlx::query_as(- "SELECT EXISTS (- SELECT 1 FROM pg_class WHERE relname = 'flags_person_lookup' AND relkind = 'p'- )",+ "SELECT to_regclass('flags_person') IS NOT NULL \+ AND to_regclass('flags_distinct_id_map') IS NOT NULL",).fetch_one(pool).await?;Ok(row.0)}++pub async fn inspect_schema(pool: &PgPool, source: SchemaSource) -> anyhow::Result<SchemaMetadata> {+ let rows = sqlx::query_as::<_, (String, String, String, i32)>(+ r#"+ SELECT+ parent.relname,+ partitioned.partstrat::text,+ child.relname,+ COALESCE(+ (+ SELECT split_part(option, '=', 2)::INTEGER+ FROM unnest(COALESCE(child.reloptions, ARRAY[]::TEXT[])) AS option+ WHERE option LIKE 'fillfactor=%'+ ),+ 100+ ) AS fillfactor+ FROM pg_inherits+ JOIN pg_class AS parent ON parent.oid = pg_inherits.inhparent+ JOIN pg_partitioned_table AS partitioned ON partitioned.partrelid = parent.oid+ JOIN pg_class AS child ON child.oid = pg_inherits.inhrelid+ WHERE parent.oid IN (+ to_regclass('flags_person'),+ to_regclass('flags_distinct_id_map')+ )+ ORDER BY parent.relname, child.relname+ "#,+ )+ .fetch_all(pool)+ .await+ .context("inspect benchmark schema partitions")?;++ let mut tables = BTreeMap::<String, Vec<u8>>::new();+ for (parent, strategy, _child, fillfactor) in rows {+ anyhow::ensure!(+ strategy == "h",+ "{parent} must use hash partitioning, found strategy {strategy}"+ );+ let fillfactor = u8::try_from(fillfactor)+ .with_context(|| format!("invalid fillfactor {fillfactor} on {parent}"))?;+ tables.entry(parent).or_default().push(fillfactor);+ }++ let person = take_table_metadata(&mut tables, PERSON_TABLE)?;+ let distinct_id_map = take_table_metadata(&mut tables, DISTINCT_ID_MAP_TABLE)?;+ anyhow::ensure!(tables.is_empty(), "unexpected benchmark table metadata");+ Ok(SchemaMetadata {+ source,+ requested_schema_arguments_applied: source == SchemaSource::Created,+ person,+ distinct_id_map,+ })+}++fn take_table_metadata(+ tables: &mut BTreeMap<String, Vec<u8>>,+ name: &str,+) -> anyhow::Result<TableMetadata> {+ let partition_fillfactors = tables+ .remove(name)+ .with_context(|| format!("{name} is missing or has no partitions"))?;+ Ok(TableMetadata {+ name: name.to_owned(),+ partition_strategy: PartitionStrategy::Hash,+ partition_count: partition_fillfactors.len(),+ partition_fillfactors,+ })+}diff --git a/rust/flags-consumer/src/benchmark/workloads.rs b/rust/flags-consumer/src/benchmark/workloads.rsdeleted file mode 100644index 61df301d1291..000000000000--- a/rust/flags-consumer/src/benchmark/workloads.rs+++ /dev/null@@ -1,439 +0,0 @@-use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};-use std::sync::Arc;-use std::time::{Duration, Instant};--use crate::storage::{- postgres::PostgresStorage,- types::{DistinctIdAssignmentData, PersonUpdateData},-};-use rand::rngs::StdRng;-use rand::{Rng, SeedableRng};-use sqlx::PgPool;-use uuid::Uuid;--use super::data_gen::{generate_properties, select_team_weighted, BenchmarkData};-use super::metrics::{self, LatencyStats, PgSnapshot};-use super::BenchmarkArgs;--pub struct PhaseResult {- pub name: String,- pub latency: LatencyStats,- pub before: PgSnapshot,- pub after: PgSnapshot,- pub wal_bytes: Option<i64>,- pub errors: u64,-}--fn spawn_merge_writers(- pool: &PgPool,- data: &BenchmarkData,- concurrency: usize,- deadline: Instant,- seed_offset: u64,- version_counter: Arc<AtomicI64>,- error_counter: Arc<AtomicU64>,-) -> Vec<tokio::task::JoinHandle<Vec<Duration>>> {- let mut handles = Vec::with_capacity(concurrency);-- for task_id in 0..concurrency {- let storage = PostgresStorage::new(pool.clone());- let distinct_ids = data.distinct_ids.clone();- let team_indices = data.team_person_indices.clone();- let team_cdf = data.team_cdf.clone();- let version_counter = version_counter.clone();- let error_counter = error_counter.clone();-- handles.push(tokio::spawn(async move {- let mut latencies = Vec::with_capacity(10_000);- let mut rng = StdRng::seed_from_u64(seed_offset + task_id as u64);-- while Instant::now() < deadline {- let team_id = match select_team_weighted(&team_cdf, &mut rng) {- Some(tid) => tid,- None => continue,- };-- let indices = match team_indices.get(&team_id) {- Some(idx) if idx.len() >= 2 => idx,- _ => continue,- };-- let src_local = rng.gen_range(0..indices.len());- let mut tgt_local = rng.gen_range(0..indices.len());- while tgt_local == src_local {- tgt_local = rng.gen_range(0..indices.len());- }-- let (_, _, src_did) = &distinct_ids[indices[src_local]];- let (_, tgt_uuid, _) = &distinct_ids[indices[tgt_local]];-- let assignment = DistinctIdAssignmentData {- team_id,- person_uuid: *tgt_uuid,- distinct_id: src_did.clone().into_boxed_str(),- version: version_counter.fetch_add(1, Ordering::Relaxed),- };-- let start = Instant::now();- match storage.upsert_distinct_id(&assignment).await {- Ok(_) => latencies.push(start.elapsed()),- Err(_) => {- error_counter.fetch_add(1, Ordering::Relaxed);- }- }- }- latencies- }));- }-- handles-}--/// Property-only updates. Does not mutate distinct_ids, so the GIN index is untouched-/// and updates should be HOT-eligible.-pub async fn phase_property_updates(- pool: &PgPool,- data: &BenchmarkData,- args: &BenchmarkArgs,-) -> anyhow::Result<PhaseResult> {- let before = metrics::capture_snapshot(pool).await?;- let deadline = Instant::now() + Duration::from_secs(args.duration_secs);- let version_counter = Arc::new(AtomicI64::new(100));- let error_counter = Arc::new(AtomicU64::new(0));-- let mut handles = Vec::with_capacity(args.concurrency);-- for task_id in 0..args.concurrency {- let storage = PostgresStorage::new(pool.clone());- let persons = data.persons.clone();- let batch_size = args.batch_size;- let version_counter = version_counter.clone();- let error_counter = error_counter.clone();-- handles.push(tokio::spawn(async move {- let mut latencies = Vec::with_capacity(10_000);- let mut rng = StdRng::seed_from_u64(task_id as u64);-- while Instant::now() < deadline {- // Unique persons per batch to avoid "ON CONFLICT DO UPDATE cannot affect- // row a second time". Sorted by (team_id, person_uuid) to prevent deadlocks.- let actual_batch = batch_size.min(persons.len());- let mut seen = std::collections::HashSet::with_capacity(actual_batch);- let mut batch = Vec::with_capacity(actual_batch);- while batch.len() < actual_batch {- let idx = rng.gen_range(0..persons.len());- if seen.insert(idx) {- let (team_id, person_uuid) = &persons[idx];- batch.push(PersonUpdateData {- team_id: *team_id,- person_uuid: *person_uuid,- properties: generate_properties(&mut rng, 700),- version: version_counter.fetch_add(1, Ordering::Relaxed),- });- }- }- batch.sort_by(|a, b| {- a.team_id- .cmp(&b.team_id)- .then(a.person_uuid.cmp(&b.person_uuid))- });-- let start = Instant::now();- match storage.batch_upsert_persons(&batch).await {- Ok(_) => latencies.push(start.elapsed()),- Err(e) => {- tracing::warn!("batch_upsert_persons error: {e}");- error_counter.fetch_add(1, Ordering::Relaxed);- }- }- }- latencies- }));- }-- let mut all_latencies = Vec::new();- for handle in handles {- all_latencies.extend(handle.await?);- }-- let after = metrics::capture_snapshot(pool).await?;- let wal_bytes = metrics::compute_wal_delta(pool, &before, &after).await;-- Ok(PhaseResult {- name: "Property updates".into(),- latency: metrics::compute_percentiles(&mut all_latencies),- before,- after,- wal_bytes,- errors: error_counter.load(Ordering::Relaxed),- })-}--/// Assign new distinct_ids to existing persons. Each operation appends to the-/// distinct_ids array and forces a GIN index update.-pub async fn phase_identification_appends(- pool: &PgPool,- data: &BenchmarkData,- args: &BenchmarkArgs,-) -> anyhow::Result<PhaseResult> {- let before = metrics::capture_snapshot(pool).await?;- let deadline = Instant::now() + Duration::from_secs(args.duration_secs);- let version_counter = Arc::new(AtomicI64::new(1_000_000));- let error_counter = Arc::new(AtomicU64::new(0));-- let mut handles = Vec::with_capacity(args.concurrency);-- for task_id in 0..args.concurrency {- let storage = PostgresStorage::new(pool.clone());- let persons = data.persons.clone();- let version_counter = version_counter.clone();- let error_counter = error_counter.clone();-- handles.push(tokio::spawn(async move {- let mut latencies = Vec::with_capacity(10_000);- let mut rng = StdRng::seed_from_u64(1000 + task_id as u64);-- while Instant::now() < deadline {- let idx = rng.gen_range(0..persons.len());- let (team_id, person_uuid) = &persons[idx];-- let mut did_bytes = [0u8; 16];- rng.fill(&mut did_bytes);-- let assignment = DistinctIdAssignmentData {- team_id: *team_id,- person_uuid: *person_uuid,- distinct_id: Uuid::from_bytes(did_bytes).to_string().into_boxed_str(),- version: version_counter.fetch_add(1, Ordering::Relaxed),- };-- let start = Instant::now();- match storage.upsert_distinct_id(&assignment).await {- Ok(_) => latencies.push(start.elapsed()),- Err(_) => {- error_counter.fetch_add(1, Ordering::Relaxed);- }- }- }- latencies- }));- }-- let mut all_latencies = Vec::new();- for handle in handles {- all_latencies.extend(handle.await?);- }-- let after = metrics::capture_snapshot(pool).await?;- let wal_bytes = metrics::compute_wal_delta(pool, &before, &after).await;-- Ok(PhaseResult {- name: "ID appends".into(),- latency: metrics::compute_percentiles(&mut all_latencies),- before,- after,- wal_bytes,- errors: error_counter.load(Ordering::Relaxed),- })-}--/// Reassign a distinct_id from one person to another within the same team.-/// Each merge triggers array_remove on the source and array_append on the target,-/// causing two GIN index updates per operation.-pub async fn phase_merges(- pool: &PgPool,- data: &BenchmarkData,- args: &BenchmarkArgs,- name: &str,- concurrency_override: Option<usize>,- duration_override: Option<u64>,-) -> anyhow::Result<PhaseResult> {- let before = metrics::capture_snapshot(pool).await?;- let concurrency = concurrency_override.unwrap_or(args.concurrency);- let duration = duration_override.unwrap_or(args.duration_secs);- let deadline = Instant::now() + Duration::from_secs(duration);- let version_counter = Arc::new(AtomicI64::new(10_000_000));- let error_counter = Arc::new(AtomicU64::new(0));-- let handles = spawn_merge_writers(- pool,- data,- concurrency,- deadline,- 2000,- version_counter,- error_counter.clone(),- );-- let mut all_latencies = Vec::new();- for handle in handles {- all_latencies.extend(handle.await?);- }-- let after = metrics::capture_snapshot(pool).await?;- let wal_bytes = metrics::compute_wal_delta(pool, &before, &after).await;-- Ok(PhaseResult {- name: name.into(),- latency: metrics::compute_percentiles(&mut all_latencies),- before,- after,- wal_bytes,- errors: error_counter.load(Ordering::Relaxed),- })-}--pub struct QueryPlanInfo {- pub gin_index_used: bool,- pub plan_text: String,-}--/// Merge writers alongside GIN-indexed read queries to measure whether-/// GIN maintenance degrades read latency.-pub async fn phase_concurrent_reads_writes(- pool: &PgPool,- data: &BenchmarkData,- args: &BenchmarkArgs,-) -> anyhow::Result<(PhaseResult, PhaseResult, QueryPlanInfo)> {- let plan_info = check_read_query_plan(pool, data).await;-- let before = metrics::capture_snapshot(pool).await?;- let deadline = Instant::now() + Duration::from_secs(args.duration_secs);- let version_counter = Arc::new(AtomicI64::new(100_000_000));- let write_errors = Arc::new(AtomicU64::new(0));- let read_errors = Arc::new(AtomicU64::new(0));-- let write_handles = spawn_merge_writers(- pool,- data,- args.concurrency,- deadline,- 5000,- version_counter,- write_errors.clone(),- );-- let mut read_handles = Vec::with_capacity(args.concurrency);-- for task_id in 0..args.concurrency {- let pool = pool.clone();- let distinct_ids = data.distinct_ids.clone();- let read_errors = read_errors.clone();-- read_handles.push(tokio::spawn(async move {- let mut latencies = Vec::with_capacity(50_000);- let mut rng = StdRng::seed_from_u64(6000 + task_id as u64);-- while Instant::now() < deadline {- let idx = rng.gen_range(0..distinct_ids.len());- let (team_id, _, did) = &distinct_ids[idx];-- let start = Instant::now();- let result = sqlx::query(- "SELECT person_uuid, distinct_ids, properties \- FROM flags_person_lookup \- WHERE team_id = $1 AND distinct_ids @> ARRAY[$2]::text[] \- AND deleted_at IS NULL \- LIMIT 1",- )- .bind(team_id)- .bind(did)- .fetch_optional(&pool)- .await;-- match result {- Ok(_) => latencies.push(start.elapsed()),- Err(_) => {- read_errors.fetch_add(1, Ordering::Relaxed);- }- }- }- latencies- }));- }-- let mut write_latencies = Vec::new();- for handle in write_handles {- write_latencies.extend(handle.await?);- }- let mut read_latencies = Vec::new();- for handle in read_handles {- read_latencies.extend(handle.await?);- }-- let after = metrics::capture_snapshot(pool).await?;- let wal_bytes = metrics::compute_wal_delta(pool, &before, &after).await;-- let write_result = PhaseResult {- name: "Reads+Writes (writes)".into(),- latency: metrics::compute_percentiles(&mut write_latencies),- before: before.clone(),- after: after.clone(),- wal_bytes,- errors: write_errors.load(Ordering::Relaxed),- };-- let read_result = PhaseResult {- name: "Reads+Writes (reads)".into(),- latency: metrics::compute_percentiles(&mut read_latencies),- before,- after,- wal_bytes: None,- errors: read_errors.load(Ordering::Relaxed),- };-- Ok((write_result, read_result, plan_info))-}--/// Run EXPLAIN on the read query and check whether the GIN index is used.-/// After heavy mutations the planner might fall back to sequential scans.-async fn check_read_query_plan(pool: &PgPool, data: &BenchmarkData) -> QueryPlanInfo {- if data.distinct_ids.is_empty() {- return QueryPlanInfo {- gin_index_used: false,- plan_text: "no data".into(),- };- }-- let (team_id, _, did) = &data.distinct_ids[0];-- let plan: Result<Vec<(String,)>, _> = sqlx::query_as(- "EXPLAIN (ANALYZE, BUFFERS) \- SELECT person_uuid, distinct_ids, properties \- FROM flags_person_lookup \- WHERE team_id = $1 AND distinct_ids @> ARRAY[$2]::text[] \- AND deleted_at IS NULL \- LIMIT 1",- )- .bind(team_id)- .bind(did)- .fetch_all(pool)- .await;-- match plan {- Ok(rows) => {- let plan_text = rows- .into_iter()- .map(|(line,)| line)- .collect::<Vec<_>>()- .join("\n");- // The migration names the parent GIN index `idx_flags_person_gin`,- // but Postgres auto-names partition-local indexes as- // `<partition>_team_id_distinct_ids_idx`, so we match either form.- let gin_index_used = plan_text.contains("idx_flags_person_gin")- || plan_text.contains("team_id_distinct_ids_idx");- tracing::info!(gin_index_used, "Phase 5 read query plan:\n{plan_text}");- QueryPlanInfo {- gin_index_used,- plan_text,- }- }- Err(e) => {- tracing::warn!("could not run EXPLAIN for read query: {e}");- QueryPlanInfo {- gin_index_used: false,- plan_text: format!("EXPLAIN failed: {e}"),- }- }- }-}diff --git a/rust/flags-consumer/src/benchmark/world.rs b/rust/flags-consumer/src/benchmark/world.rsnew file mode 100644index 000000000000..c504f49cf28f--- /dev/null+++ b/rust/flags-consumer/src/benchmark/world.rs@@ -0,0 +1,1833 @@+use std::collections::{BTreeMap, VecDeque};+use std::fmt;+use std::mem::size_of;++use rand::rngs::StdRng;+use rand::{Rng, SeedableRng};+use serde::Serialize;+use serde_json::Value;+use uuid::Uuid;++use super::ops::{+ CanonicalReadPayload, DistinctIdAssignmentPayload, DistinctIdMove, FullMergePayload,+ MergeShape, NanosSincePhaseStart, OpDescriptor, OpPayload, OperationId, PersonUpsertPayload,+ ReadExpectation,+};++const ZIPF_EXPONENT: f64 = 1.5;+const RECENT_SELECTION_ATTEMPTS: usize = 8;+const FANOUT_ROLLS: u32 = 100_000;+const WHALE_MIN_FANOUT: u32 = 101;+const PROPERTY_SEED_MIX: u64 = 0xa076_1d64_78bd_642f;+const NONE_INDEX: u32 = u32::MAX;+const PENDING_INDEX: u32 = u32::MAX - 1;+const ARENA_CHUNK_CAPACITY: usize = 65_536;++// RFC sample: 95% single-DID, almost all remaining at 2, with rare large tails.+const FANOUT_BUCKETS: [FanoutBucket; 4] = [+ FanoutBucket::new(95_000, 1, 1),+ FanoutBucket::new(99_990, 2, 2),+ FanoutBucket::new(99_999, 3, 100),+ FanoutBucket::new(FANOUT_ROLLS, 101, 1_000),+];++#[derive(Debug, Clone, Copy)]+struct FanoutBucket {+ upper_roll_exclusive: u32,+ min: u32,+ max: u32,+}++impl FanoutBucket {+ const fn new(upper_roll_exclusive: u32, min: u32, max: u32) -> Self {+ Self {+ upper_roll_exclusive,+ min,+ max,+ }+ }+}++#[derive(Debug, Clone)]+pub struct WorldConfig {+ pub seed: u64,+ pub team_count: i32,+ pub initial_person_count: usize,+ pub recent_capacity_per_team: usize,+ pub recent_target_percent: u8,+ pub property_bytes: usize,+}++impl Default for WorldConfig {+ fn default() -> Self {+ Self {+ seed: 42,+ team_count: 100,+ initial_person_count: 100_000,+ recent_capacity_per_team: 4_096,+ recent_target_percent: 50,+ property_bytes: 700,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ReplayMode {+ Fresh,+ Stale,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AssignmentMode {+ New,+ FreshExisting,+ StaleReplay,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ReadMode {+ Hit,+ Miss,+}++#[derive(Debug, Clone, PartialEq)]+pub struct CreationDescriptors {+ pub person_upsert: OpDescriptor,+ pub distinct_id_assignment: OpDescriptor,+ pub activation: PendingCreationToken,+}++#[derive(Debug, Clone, PartialEq)]+pub struct AssignmentDescriptor {+ pub operation: OpDescriptor,+ pub activation: Option<PendingDistinctIdToken>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct PendingCreationToken {+ person: PersonKey,+ distinct_id: DistinctIdKey,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct PendingDistinctIdToken {+ distinct_id: DistinctIdKey,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+#[repr(transparent)]+struct PersonKey(u32);++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[repr(transparent)]+struct DistinctIdKey(u32);++#[derive(Debug)]+struct ChunkedArena<T> {+ chunks: Vec<Vec<T>>,+ len: u32,+}++impl<T> ChunkedArena<T> {+ fn new() -> Self {+ Self {+ chunks: Vec::new(),+ len: 0,+ }+ }++ fn push(&mut self, value: T) -> Option<u32> {+ if self.len >= PENDING_INDEX {+ return None;+ }+ if self+ .chunks+ .last()+ .is_none_or(|chunk| chunk.len() == ARENA_CHUNK_CAPACITY)+ {+ self.chunks.push(Vec::with_capacity(ARENA_CHUNK_CAPACITY));+ }+ let index = self.len;+ self.chunks.last_mut()?.push(value);+ self.len += 1;+ Some(index)+ }++ fn can_push(&self, count: u32) -> bool {+ self.len+ .checked_add(count)+ .is_some_and(|len| len <= PENDING_INDEX)+ }++ fn len(&self) -> usize {+ self.len as usize+ }++ fn get(&self, index: u32) -> &T {+ let index = index as usize;+ &self.chunks[index / ARENA_CHUNK_CAPACITY][index % ARENA_CHUNK_CAPACITY]+ }++ fn get_mut(&mut self, index: u32) -> &mut T {+ let index = index as usize;+ &mut self.chunks[index / ARENA_CHUNK_CAPACITY][index % ARENA_CHUNK_CAPACITY]+ }++ fn iter(&self) -> impl Iterator<Item = &T> {+ self.chunks.iter().flat_map(|chunk| chunk.iter())+ }++ #[cfg(test)]+ fn chunk_count(&self) -> usize {+ self.chunks.len()+ }+}++#[derive(Debug)]+#[repr(C)]+struct PersonState {+ version: i64,+ first_distinct_id: u32,+ last_distinct_id: u32,+ distinct_id_count: u32,+ team_index: u32,+ live_index: u32,+ whale_index: u32,+}++impl PersonState {+ fn new(team_index: u32, live_index: u32) -> Self {+ Self {+ version: 1,+ first_distinct_id: NONE_INDEX,+ last_distinct_id: NONE_INDEX,+ distinct_id_count: 0,+ team_index,+ live_index,+ whale_index: NONE_INDEX,+ }+ }++ fn first_distinct_id(&self) -> Option<DistinctIdKey> {+ (self.first_distinct_id != NONE_INDEX).then_some(DistinctIdKey(self.first_distinct_id))+ }++ fn last_distinct_id(&self) -> Option<DistinctIdKey> {+ (self.last_distinct_id != NONE_INDEX).then_some(DistinctIdKey(self.last_distinct_id))+ }++ fn live_index(&self) -> Option<usize> {+ (self.live_index != NONE_INDEX).then_some(self.live_index as usize)+ }++ fn whale_index(&self) -> Option<usize> {+ (self.whale_index != NONE_INDEX).then_some(self.whale_index as usize)+ }++ fn clear_distinct_ids(&mut self) {+ self.first_distinct_id = NONE_INDEX;+ self.last_distinct_id = NONE_INDEX;+ self.distinct_id_count = 0;+ }+}++#[derive(Debug)]+#[repr(C)]+struct DistinctIdState {+ version: i64,+ owner: PersonKey,+ next: u32,+}++impl DistinctIdState {+ fn next(&self) -> Option<DistinctIdKey> {+ (self.next < PENDING_INDEX).then_some(DistinctIdKey(self.next))+ }++ fn is_pending(&self) -> bool {+ self.next == PENDING_INDEX+ }+}++#[derive(Debug)]+struct TeamState {+ team_id: i32,+ live_persons: Vec<PersonKey>,+ whales: Vec<PersonKey>,+ recent: VecDeque<PersonKey>,+ pending_persons: u32,+}++impl TeamState {+ fn new(team_id: i32, initial_person_count: usize) -> Self {+ Self {+ team_id,+ live_persons: Vec::with_capacity(initial_person_count),+ whales: Vec::new(),+ recent: VecDeque::new(),+ pending_persons: 0,+ }+ }+}++#[derive(Debug)]+pub struct WorldState {+ topology_rng: StdRng,+ property_rng: StdRng,+ seed: u64,+ property_bytes: usize,+ recent_capacity_per_team: usize,+ recent_target_percent: u8,+ team_cdf: Vec<f64>,+ teams: Vec<TeamState>,+ persons: ChunkedArena<PersonState>,+ distinct_ids: ChunkedArena<DistinctIdState>,+ pending_distinct_ids_by_person: BTreeMap<PersonKey, u32>,+ growth_reservation_enabled: bool,+ next_miss_counter: u64,+ next_operation_id: u64,+}++impl WorldState {+ pub fn new(config: WorldConfig) -> Result<Self, WorldError> {+ if config.team_count <= 0 {+ return Err(WorldError::InvalidTeamCount(config.team_count));+ }+ if config.recent_target_percent > 100 {+ return Err(WorldError::InvalidRecentTargetPercent(+ config.recent_target_percent,+ ));+ }+ if u64::try_from(config.initial_person_count).unwrap_or(u64::MAX) >= u64::from(u32::MAX) {+ return Err(WorldError::PopulationTooLarge(config.initial_person_count));+ }++ let weights: Vec<f64> = (1..=config.team_count)+ .map(|rank| 1.0 / f64::from(rank).powf(ZIPF_EXPONENT))+ .collect();+ let team_counts = allocate_zipf_counts(&weights, config.initial_person_count);+ let total_weight: f64 = weights.iter().sum();+ let mut cumulative = 0.0;+ let team_cdf = weights+ .iter()+ .map(|weight| {+ cumulative += weight / total_weight;+ cumulative+ })+ .collect::<Vec<_>>();++ let teams = team_counts+ .iter()+ .enumerate()+ .map(|(team_index, count)| TeamState::new(team_index as i32 + 1, *count))+ .collect();+ let mut world = Self {+ topology_rng: StdRng::seed_from_u64(config.seed),+ property_rng: StdRng::seed_from_u64(config.seed ^ PROPERTY_SEED_MIX),+ seed: config.seed,+ property_bytes: config.property_bytes,+ recent_capacity_per_team: config.recent_capacity_per_team,+ recent_target_percent: config.recent_target_percent,+ team_cdf,+ teams,+ persons: ChunkedArena::new(),+ distinct_ids: ChunkedArena::new(),+ pending_distinct_ids_by_person: BTreeMap::new(),+ growth_reservation_enabled: false,+ next_miss_counter: 1,+ next_operation_id: 1,+ };++ for (team_index, count) in team_counts.into_iter().enumerate() {+ for _ in 0..count {+ let fanout = world.sample_fanout();+ world.create_person(team_index, fanout)?;+ }+ }+ Ok(world)+ }++ pub fn population(&self) -> PopulationView<'_> {+ PopulationView { world: self }+ }++ pub fn live_person_count(&self) -> usize {+ self.teams.iter().map(|team| team.live_persons.len()).sum()+ }++ pub fn distinct_id_count(&self) -> usize {+ self.distinct_ids.len()+ }++ pub fn reserve_person_growth(+ &mut self,+ person_creations: PersonCreationCount,+ ) -> Result<(), WorldError> {+ let total = usize::try_from(person_creations.get())+ .map_err(|_| WorldError::MemoryEstimateOverflow)?;+ let mut previous = 0.0;+ let weights = self+ .team_cdf+ .iter()+ .map(|cumulative| {+ let weight = cumulative - previous;+ previous = *cumulative;+ weight+ })+ .collect::<Vec<_>>();+ for (team, additional) in self+ .teams+ .iter_mut()+ .zip(allocate_zipf_counts(&weights, total))+ {+ team.live_persons+ .try_reserve_exact(additional)+ .map_err(|_| WorldError::AllocationFailed("team live person"))?;+ }+ self.growth_reservation_enabled = true;+ Ok(())+ }++ pub fn estimate_initial_memory(+ config: &WorldConfig,+ ) -> Result<WorldMemoryEstimate, WorldError> {+ Self::estimate_memory(config, WorldGrowth::default())+ }++ pub fn estimate_memory(+ config: &WorldConfig,+ growth: WorldGrowth,+ ) -> Result<WorldMemoryEstimate, WorldError> {+ if config.team_count <= 0 {+ return Err(WorldError::InvalidTeamCount(config.team_count));+ }+ let initial_person_count = u64::try_from(config.initial_person_count)+ .map_err(|_| WorldError::MemoryEstimateOverflow)?;+ let person_count = initial_person_count+ .checked_add(growth.person_creations.get())+ .ok_or(WorldError::MemoryEstimateOverflow)?;+ let distinct_id_count = expected_distinct_id_count(initial_person_count)?+ .checked_add(growth.person_creations.get())+ .and_then(|count| count.checked_add(growth.distinct_id_assignments.get()))+ .ok_or(WorldError::MemoryEstimateOverflow)?;+ let person_chunks = chunk_count(person_count)?;+ let distinct_id_chunks = chunk_count(distinct_id_count)?;+ let person_arena_bytes = chunk_allocation_bytes(person_chunks, size_of::<PersonState>())?;+ let distinct_id_arena_bytes =+ chunk_allocation_bytes(distinct_id_chunks, size_of::<DistinctIdState>())?;+ let live_person_index_bytes = checked_product(person_count, size_of::<PersonKey>() as u64)?;+ let recent_capacity = checked_product(+ config.team_count as u64,+ config.recent_capacity_per_team as u64,+ )?;+ let recent_index_bytes = checked_product(recent_capacity, size_of::<PersonKey>() as u64)?;+ let initial_whale_count = div_ceil(+ checked_product(initial_person_count, whale_bucket_rolls())?,+ u64::from(FANOUT_ROLLS),+ )?;+ let whale_count = initial_whale_count+ .checked_add(growth.distinct_id_assignments.get().min(person_count))+ .ok_or(WorldError::MemoryEstimateOverflow)?+ .min(person_count);+ let whale_index_bytes = checked_product(whale_count, size_of::<PersonKey>() as u64)?;+ let team_state_bytes =+ checked_product(config.team_count as u64, size_of::<TeamState>() as u64)?;+ let chunk_metadata_bytes = checked_product(+ person_chunks+ .checked_add(distinct_id_chunks)+ .ok_or(WorldError::MemoryEstimateOverflow)?,+ size_of::<Vec<PersonState>>() as u64,+ )?;+ let total_bytes = [+ person_arena_bytes,+ distinct_id_arena_bytes,+ live_person_index_bytes,+ recent_index_bytes,+ whale_index_bytes,+ team_state_bytes,+ chunk_metadata_bytes,+ ]+ .into_iter()+ .try_fold(0u64, |total, bytes| {+ total+ .checked_add(bytes)+ .ok_or(WorldError::MemoryEstimateOverflow)+ })?;++ Ok(WorldMemoryEstimate {+ growth,+ person_count,+ expected_distinct_id_count: distinct_id_count,+ person_slot_bytes: size_of::<PersonState>(),+ distinct_id_slot_bytes: size_of::<DistinctIdState>(),+ person_arena_bytes,+ distinct_id_arena_bytes,+ live_person_index_bytes,+ recent_index_bytes,+ whale_index_bytes,+ chunk_metadata_bytes,+ total_bytes,+ })+ }++ pub fn resolve_person_upsert(+ &mut self,+ scheduled_at: NanosSincePhaseStart,+ replay: ReplayMode,+ ) -> Result<OpDescriptor, WorldError> {+ let team_index = self.select_team(|team| !team.live_persons.is_empty())?;+ let person_key = self.select_person(team_index, None, false, false)?;+ let current_version = self.person(person_key).version;+ let version = match replay {+ ReplayMode::Fresh => {+ let version = increment_version(current_version)?;+ self.person_mut(person_key).version = version;+ version+ }+ ReplayMode::Stale => stale_version(current_version),+ };+ let payload = PersonUpsertPayload {+ team_id: self.teams[team_index].team_id,+ person_uuid: self.person_uuid(person_key),+ properties: generate_properties(&mut self.property_rng, self.property_bytes),+ version,+ };+ self.touch_person(person_key);+ self.describe(scheduled_at, OpPayload::PersonUpsert(payload))+ }++ pub fn resolve_distinct_id_assignment(+ &mut self,+ scheduled_at: NanosSincePhaseStart,+ mode: AssignmentMode,+ ) -> Result<AssignmentDescriptor, WorldError> {+ let team_index = self.select_team(|team| !team.live_persons.is_empty())?;+ let person_key = self.select_person(team_index, None, false, false)?;+ let distinct_id_key = match mode {+ AssignmentMode::New => self.reserve_distinct_id(person_key)?,+ AssignmentMode::FreshExisting | AssignmentMode::StaleReplay => {+ self.select_distinct_id(person_key)?+ }+ };+ let version = match mode {+ AssignmentMode::New => self.distinct_id(distinct_id_key).version,+ AssignmentMode::FreshExisting => {+ let version = increment_version(self.distinct_id(distinct_id_key).version)?;+ self.distinct_id_mut(distinct_id_key).version = version;+ version+ }+ AssignmentMode::StaleReplay => stale_version(self.distinct_id(distinct_id_key).version),+ };+ let payload = DistinctIdAssignmentPayload {+ team_id: self.teams[team_index].team_id,+ person_uuid: self.person_uuid(person_key),+ distinct_id: self.distinct_id_value(distinct_id_key),+ version,+ };+ self.touch_person(person_key);+ let operation = self.describe(scheduled_at, OpPayload::DistinctIdAssignment(payload))?;+ Ok(AssignmentDescriptor {+ operation,+ activation: (mode == AssignmentMode::New).then_some(PendingDistinctIdToken {+ distinct_id: distinct_id_key,+ }),+ })+ }++ pub fn resolve_creation(+ &mut self,+ scheduled_at: NanosSincePhaseStart,+ ) -> Result<CreationDescriptors, WorldError> {+ let enforce_reservation = self.growth_reservation_enabled;+ let team_index = self.select_team(|team| {+ !enforce_reservation+ || team+ .live_persons+ .len()+ .saturating_add(team.pending_persons as usize)+ < team.live_persons.capacity()+ })?;+ let person_key = self.reserve_person(team_index)?;+ let distinct_id_key = self.reserve_distinct_id(person_key)?;+ let team_id = self.teams[team_index].team_id;+ let person_uuid = self.person_uuid(person_key);+ let person_version = self.person(person_key).version;+ let distinct_id_value = self.distinct_id_value(distinct_id_key);+ let distinct_id_version = self.distinct_id(distinct_id_key).version;+ let properties = generate_properties(&mut self.property_rng, self.property_bytes);++ let person_upsert = self.describe(+ scheduled_at,+ OpPayload::PersonUpsert(PersonUpsertPayload {+ team_id,+ person_uuid,+ properties,+ version: person_version,+ }),+ )?;+ let distinct_id_assignment = self.describe(+ scheduled_at,+ OpPayload::DistinctIdAssignment(DistinctIdAssignmentPayload {+ team_id,+ person_uuid,+ distinct_id: distinct_id_value,+ version: distinct_id_version,+ }),+ )?;+ Ok(CreationDescriptors {+ person_upsert,+ distinct_id_assignment,+ activation: PendingCreationToken {+ person: person_key,+ distinct_id: distinct_id_key,+ },+ })+ }++ pub fn activate_creation(&mut self, token: PendingCreationToken) -> Result<(), WorldError> {+ if self.person(token.person).live_index().is_some()+ || !self.distinct_id(token.distinct_id).is_pending()+ || self.distinct_id(token.distinct_id).owner != token.person+ {+ return Err(WorldError::InvalidPendingActivation);+ }+ self.activate_person(token.person)?;+ self.activate_distinct_id_key(token.distinct_id)?;+ self.touch_person(token.person);+ Ok(())+ }++ pub fn activate_distinct_id(+ &mut self,+ token: PendingDistinctIdToken,+ ) -> Result<(), WorldError> {+ self.activate_distinct_id_key(token.distinct_id)+ }++ pub fn abandon_distinct_id(&mut self, token: PendingDistinctIdToken) -> Result<(), WorldError> {+ if !self.distinct_id(token.distinct_id).is_pending() {+ return Err(WorldError::InvalidPendingActivation);+ }+ let person_key = self.distinct_id(token.distinct_id).owner;+ self.remove_pending_distinct_id(person_key)+ }++ pub fn resolve_full_merge(+ &mut self,+ scheduled_at: NanosSincePhaseStart,+ ) -> Result<OpDescriptor, WorldError> {+ self.resolve_merge(scheduled_at, MergeShape::Standard)+ }++ pub fn resolve_whale_merge(+ &mut self,+ scheduled_at: NanosSincePhaseStart,+ ) -> Result<OpDescriptor, WorldError> {+ self.resolve_merge(scheduled_at, MergeShape::Whale)+ }++ pub fn resolve_read(+ &mut self,+ scheduled_at: NanosSincePhaseStart,+ mode: ReadMode,+ ) -> Result<OpDescriptor, WorldError> {+ let team_index = self.select_team(|team| !team.live_persons.is_empty())?;+ let team_id = self.teams[team_index].team_id;+ let payload = match mode {+ ReadMode::Hit => {+ let person_key = self.select_person(team_index, None, false, false)?;+ let distinct_id_key = self.select_distinct_id(person_key)?;+ let payload = CanonicalReadPayload {+ team_id,+ distinct_id: self.distinct_id_value(distinct_id_key),+ expectation: ReadExpectation::Hit,+ };+ self.touch_person(person_key);+ payload+ }+ ReadMode::Miss => CanonicalReadPayload {+ team_id,+ distinct_id: self.next_miss_distinct_id()?,+ expectation: ReadExpectation::Miss,+ },+ };+ self.describe(scheduled_at, OpPayload::CanonicalRead(payload))+ }++ fn resolve_merge(+ &mut self,+ scheduled_at: NanosSincePhaseStart,+ shape: MergeShape,+ ) -> Result<OpDescriptor, WorldError> {+ let eligible_teams = self+ .teams+ .iter()+ .map(|team| {+ let sources = if shape == MergeShape::Whale {+ &team.whales+ } else {+ &team.live_persons+ };+ team.live_persons.len() >= 2+ && sources+ .iter()+ .any(|source| !self.pending_distinct_ids_by_person.contains_key(source))+ })+ .collect::<Vec<_>>();+ let team_index = self.select_eligible_team(&eligible_teams)?;+ let source = self.select_person(team_index, None, shape == MergeShape::Whale, true)?;+ let target = self.select_person(team_index, Some(source), false, false)?;++ let source_version = self.person(source).version;+ let target_version = self.person(target).version;+ let merged_target_version = source_version+ .max(target_version)+ .checked_add(1)+ .ok_or(WorldError::VersionExhausted)?;+ let source_tombstone_version = source_version+ .checked_add(100)+ .ok_or(WorldError::VersionExhausted)?;+ let source_first = self.person(source).first_distinct_id();+ let source_last = self.person(source).last_distinct_id();+ let source_count = self.person(source).distinct_id_count;+ let target_first = self.person(target).first_distinct_id();+ let target_last = self.person(target).last_distinct_id();+ let merged_count = self+ .person(target)+ .distinct_id_count+ .checked_add(source_count)+ .ok_or(WorldError::FanoutExhausted)?;++ let mut planned_moves = Vec::with_capacity(source_count as usize);+ let mut current = source_first;+ while let Some(distinct_id_key) = current {+ let distinct_id = self.distinct_id(distinct_id_key);+ let version = increment_version(distinct_id.version)?;+ planned_moves.push((+ distinct_id_key,+ version,+ self.distinct_id_value(distinct_id_key),+ ));+ current = distinct_id.next();+ }++ if let (Some(target_last), Some(source_first)) = (target_last, source_first) {+ self.distinct_id_mut(target_last).next = source_first.0;+ }+ let mut moves = Vec::with_capacity(planned_moves.len());+ for (distinct_id_key, version, distinct_id) in planned_moves {+ let state = self.distinct_id_mut(distinct_id_key);+ state.owner = target;+ state.version = version;+ moves.push(DistinctIdMove {+ distinct_id,+ version,+ });+ }++ {+ let target_state = self.person_mut(target);+ target_state.first_distinct_id = target_first+ .or(source_first)+ .map_or(NONE_INDEX, |key| key.0);+ target_state.last_distinct_id =+ source_last.or(target_last).map_or(NONE_INDEX, |key| key.0);+ target_state.distinct_id_count = merged_count;+ target_state.version = merged_target_version;+ }+ {+ let source_state = self.person_mut(source);+ source_state.clear_distinct_ids();+ source_state.version = source_tombstone_version;+ }++ let source_uuid = self.person_uuid(source);+ let target_uuid = self.person_uuid(target);+ self.ensure_whale(target);+ self.remove_live_person(source);+ self.touch_person(target);++ let payload = FullMergePayload {+ team_id: self.teams[team_index].team_id,+ source_person_uuid: source_uuid,+ target_person_uuid: target_uuid,+ distinct_id_moves: moves.into_boxed_slice(),+ target_properties: generate_properties(&mut self.property_rng, self.property_bytes),+ target_version: merged_target_version,+ source_tombstone_version,+ shape,+ };+ self.describe(scheduled_at, OpPayload::FullMerge(payload))+ }++ fn describe(+ &mut self,+ scheduled_at: NanosSincePhaseStart,+ payload: OpPayload,+ ) -> Result<OpDescriptor, WorldError> {+ let operation_id = OperationId(self.next_operation_id);+ self.next_operation_id = self+ .next_operation_id+ .checked_add(1)+ .ok_or(WorldError::IdentifierExhausted("operation"))?;+ Ok(OpDescriptor::new(operation_id, scheduled_at, payload))+ }++ fn create_person(&mut self, team_index: usize, fanout: u32) -> Result<PersonKey, WorldError> {+ if !self.distinct_ids.can_push(fanout) {+ return Err(WorldError::ArenaExhausted("distinct ID"));+ }+ let person_key = self.reserve_person(team_index)?;+ self.activate_person(person_key)?;+ for _ in 0..fanout {+ self.create_distinct_id(person_key)?;+ }+ self.ensure_whale(person_key);+ self.touch_person(person_key);+ Ok(person_key)+ }++ fn reserve_person(&mut self, team_index: usize) -> Result<PersonKey, WorldError> {+ let pending_persons = self.teams[team_index]+ .pending_persons+ .checked_add(1)+ .ok_or(WorldError::IndexExhausted("pending person"))?;+ let team_index =+ u32::try_from(team_index).map_err(|_| WorldError::IndexExhausted("team"))?;+ let person_index = self+ .persons+ .push(PersonState::new(team_index, NONE_INDEX))+ .ok_or(WorldError::ArenaExhausted("person"))?;+ self.teams[team_index as usize].pending_persons = pending_persons;+ Ok(PersonKey(person_index))+ }++ fn activate_person(&mut self, person_key: PersonKey) -> Result<(), WorldError> {+ if self.person(person_key).live_index().is_some() {+ return Err(WorldError::InvalidPendingActivation);+ }+ let team_index = self.person(person_key).team_index as usize;+ let live_index = u32::try_from(self.teams[team_index].live_persons.len())+ .map_err(|_| WorldError::IndexExhausted("team live person"))?;+ self.teams[team_index].pending_persons = self.teams[team_index]+ .pending_persons+ .checked_sub(1)+ .ok_or(WorldError::InvalidPendingActivation)?;+ self.teams[team_index].live_persons.push(person_key);+ self.person_mut(person_key).live_index = live_index;+ Ok(())+ }++ fn create_distinct_id(&mut self, person_key: PersonKey) -> Result<DistinctIdKey, WorldError> {+ let distinct_id_key = self.reserve_distinct_id(person_key)?;+ self.activate_distinct_id_key(distinct_id_key)?;+ Ok(distinct_id_key)+ }++ fn reserve_distinct_id(&mut self, person_key: PersonKey) -> Result<DistinctIdKey, WorldError> {+ let distinct_id_index = self+ .distinct_ids+ .push(DistinctIdState {+ version: 1,+ owner: person_key,+ next: PENDING_INDEX,+ })+ .ok_or(WorldError::ArenaExhausted("distinct ID"))?;+ let pending = self+ .pending_distinct_ids_by_person+ .entry(person_key)+ .or_default();+ *pending = pending.checked_add(1).ok_or(WorldError::FanoutExhausted)?;+ Ok(DistinctIdKey(distinct_id_index))+ }++ fn activate_distinct_id_key(+ &mut self,+ distinct_id_key: DistinctIdKey,+ ) -> Result<(), WorldError> {+ if !self.distinct_id(distinct_id_key).is_pending() {+ return Err(WorldError::InvalidPendingActivation);+ }+ let person_key = self.distinct_id(distinct_id_key).owner;+ if self.person(person_key).live_index().is_none() {+ return Err(WorldError::InvalidPendingActivation);+ }+ let count = self+ .person(person_key)+ .distinct_id_count+ .checked_add(1)+ .ok_or(WorldError::FanoutExhausted)?;+ self.remove_pending_distinct_id(person_key)?;+ let previous_last = self.person(person_key).last_distinct_id();+ self.distinct_id_mut(distinct_id_key).next = NONE_INDEX;+ if let Some(previous_last) = previous_last {+ self.distinct_id_mut(previous_last).next = distinct_id_key.0;+ }+ let person = self.person_mut(person_key);+ if person.first_distinct_id == NONE_INDEX {+ person.first_distinct_id = distinct_id_key.0;+ }+ person.last_distinct_id = distinct_id_key.0;+ person.distinct_id_count = count;+ self.ensure_whale(person_key);+ Ok(())+ }++ fn remove_pending_distinct_id(&mut self, person_key: PersonKey) -> Result<(), WorldError> {+ let remove_entry = {+ let pending = self+ .pending_distinct_ids_by_person+ .get_mut(&person_key)+ .ok_or(WorldError::InvalidPendingActivation)?;+ *pending = pending+ .checked_sub(1)+ .ok_or(WorldError::InvalidPendingActivation)?;+ *pending == 0+ };+ if remove_entry {+ self.pending_distinct_ids_by_person.remove(&person_key);+ }+ Ok(())+ }++ fn person(&self, key: PersonKey) -> &PersonState {+ self.persons.get(key.0)+ }++ fn person_mut(&mut self, key: PersonKey) -> &mut PersonState {+ self.persons.get_mut(key.0)+ }++ fn distinct_id(&self, key: DistinctIdKey) -> &DistinctIdState {+ self.distinct_ids.get(key.0)+ }++ fn distinct_id_mut(&mut self, key: DistinctIdKey) -> &mut DistinctIdState {+ self.distinct_ids.get_mut(key.0)+ }++ fn person_uuid(&self, person_key: PersonKey) -> Uuid {+ Uuid::from_u128((u128::from(self.seed) << 64) | u128::from(person_key.0).saturating_add(1))+ }++ fn distinct_id_value(&self, distinct_id_key: DistinctIdKey) -> Box<str> {+ format!(+ "bench-{:016x}-{:016x}",+ self.seed,+ u64::from(distinct_id_key.0) + 1+ )+ .into_boxed_str()+ }++ fn next_miss_distinct_id(&mut self) -> Result<Box<str>, WorldError> {+ let counter = self.next_miss_counter;+ self.next_miss_counter = counter+ .checked_add(1)+ .ok_or(WorldError::IdentifierExhausted("read miss"))?;+ Ok(format!("bench-miss-{:016x}-{counter:016x}", self.seed).into_boxed_str())+ }++ fn sample_fanout(&mut self) -> u32 {+ let bucket_roll = self.topology_rng.gen_range(0..FANOUT_ROLLS);+ let within_bucket_roll = self.topology_rng.gen::<u64>();+ fanout_for_roll(bucket_roll, within_bucket_roll)+ }++ fn select_team<F>(&mut self, eligible: F) -> Result<usize, WorldError>+ where+ F: Fn(&TeamState) -> bool,+ {+ let eligible = self.teams.iter().map(eligible).collect::<Vec<_>>();+ self.select_eligible_team(&eligible)+ }++ fn select_eligible_team(&mut self, eligible: &[bool]) -> Result<usize, WorldError> {+ for _ in 0..self.teams.len().saturating_mul(2).max(1) {+ let roll = self.topology_rng.gen::<f64>();+ let team_index = self+ .team_cdf+ .partition_point(|cumulative| *cumulative < roll)+ .min(self.teams.len() - 1);+ if eligible[team_index] {+ return Ok(team_index);+ }+ }+ eligible+ .iter()+ .position(|eligible| *eligible)+ .ok_or(WorldError::NoEligiblePerson)+ }++ fn select_person(+ &mut self,+ team_index: usize,+ exclude: Option<PersonKey>,+ whale_only: bool,+ exclude_pending: bool,+ ) -> Result<PersonKey, WorldError> {+ if !whale_only+ && self+ .topology_rng+ .gen_ratio(u32::from(self.recent_target_percent), 100)+ && !self.teams[team_index].recent.is_empty()+ {+ for _ in 0..RECENT_SELECTION_ATTEMPTS {+ let index = self+ .topology_rng+ .gen_range(0..self.teams[team_index].recent.len());+ let candidate = self.teams[team_index].recent[index];+ if self.person(candidate).live_index().is_some()+ && Some(candidate) != exclude+ && (!exclude_pending+ || !self.pending_distinct_ids_by_person.contains_key(&candidate))+ {+ return Ok(candidate);+ }+ }+ }++ let candidates = if whale_only {+ &self.teams[team_index].whales+ } else {+ &self.teams[team_index].live_persons+ };+ if candidates.is_empty() {+ return Err(WorldError::NoEligiblePerson);+ }+ let start = self.topology_rng.gen_range(0..candidates.len());+ for offset in 0..candidates.len() {+ let candidate = candidates[(start + offset) % candidates.len()];+ if Some(candidate) != exclude+ && (!exclude_pending+ || !self.pending_distinct_ids_by_person.contains_key(&candidate))+ {+ return Ok(candidate);+ }+ }+ Err(WorldError::NoEligiblePerson)+ }++ fn select_distinct_id(&mut self, person_key: PersonKey) -> Result<DistinctIdKey, WorldError> {+ let (head, tail, count) = {+ let person = self.person(person_key);+ (+ person+ .first_distinct_id()+ .ok_or(WorldError::NoEligibleDistinctId)?,+ person.last_distinct_id(),+ person.distinct_id_count,+ )+ };+ if count > 1 {+ let tail = tail.ok_or(WorldError::NoEligibleDistinctId)?;+ let next = self+ .distinct_id(head)+ .next()+ .ok_or(WorldError::NoEligibleDistinctId)?;+ self.distinct_id_mut(tail).next = head.0;+ self.distinct_id_mut(head).next = NONE_INDEX;+ let person = self.person_mut(person_key);+ person.first_distinct_id = next.0;+ person.last_distinct_id = head.0;+ }+ Ok(head)+ }++ fn touch_person(&mut self, person_key: PersonKey) {+ if self.recent_capacity_per_team == 0 || self.person(person_key).live_index().is_none() {+ return;+ }+ let team_index = self.person(person_key).team_index as usize;+ let recent = &mut self.teams[team_index].recent;+ recent.push_back(person_key);+ if recent.len() > self.recent_capacity_per_team {+ recent.pop_front();+ }+ }++ fn ensure_whale(&mut self, person_key: PersonKey) {+ let person = self.person(person_key);+ if person.distinct_id_count < WHALE_MIN_FANOUT+ || person.whale_index().is_some()+ || person.live_index().is_none()+ {+ return;+ }+ let team_index = person.team_index as usize;+ let Ok(whale_index) = u32::try_from(self.teams[team_index].whales.len()) else {+ return;+ };+ self.teams[team_index].whales.push(person_key);+ self.person_mut(person_key).whale_index = whale_index;+ }++ fn remove_live_person(&mut self, person_key: PersonKey) {+ let team_index = self.person(person_key).team_index as usize;+ let live_index = self+ .person(person_key)+ .live_index()+ .expect("only live persons can be merged");+ let moved_live = {+ let live_persons = &mut self.teams[team_index].live_persons;+ live_persons.swap_remove(live_index);+ live_persons.get(live_index).copied()+ };+ if let Some(moved) = moved_live {+ self.person_mut(moved).live_index = live_index as u32;+ }++ if let Some(whale_index) = self.person(person_key).whale_index() {+ let moved_whale = {+ let whales = &mut self.teams[team_index].whales;+ whales.swap_remove(whale_index);+ whales.get(whale_index).copied()+ };+ if let Some(moved) = moved_whale {+ self.person_mut(moved).whale_index = whale_index as u32;+ }+ }+ let person = self.person_mut(person_key);+ person.live_index = NONE_INDEX;+ person.whale_index = NONE_INDEX;+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct PopulationPerson {+ pub team_id: i32,+ pub person_uuid: Uuid,+ pub version: i64,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PopulationDistinctId {+ pub team_id: i32,+ pub person_uuid: Uuid,+ pub distinct_id: Box<str>,+ pub version: i64,+}++#[derive(Debug, Clone, Copy)]+pub struct PopulationView<'a> {+ world: &'a WorldState,+}++impl PopulationView<'_> {+ pub const fn property_bytes(&self) -> usize {+ self.world.property_bytes+ }++ pub const fn property_seed(&self) -> u64 {+ self.world.seed ^ PROPERTY_SEED_MIX+ }++ pub fn persons(&self) -> impl Iterator<Item = PopulationPerson> + '_ {+ self.world+ .persons+ .iter()+ .enumerate()+ .filter_map(|(index, person)| {+ person.live_index().map(|_| {+ let person_key = PersonKey(index as u32);+ PopulationPerson {+ team_id: self.world.teams[person.team_index as usize].team_id,+ person_uuid: self.world.person_uuid(person_key),+ version: person.version,+ }+ })+ })+ }++ pub fn distinct_ids(&self) -> impl Iterator<Item = PopulationDistinctId> + '_ {+ self.world+ .distinct_ids+ .iter()+ .enumerate()+ .filter(|(_, distinct_id)| !distinct_id.is_pending())+ .map(|(index, distinct_id)| {+ let owner = self.world.person(distinct_id.owner);+ PopulationDistinctId {+ team_id: self.world.teams[owner.team_index as usize].team_id,+ person_uuid: self.world.person_uuid(distinct_id.owner),+ distinct_id: self.world.distinct_id_value(DistinctIdKey(index as u32)),+ version: distinct_id.version,+ }+ })+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[repr(transparent)]+pub struct PersonCreationCount(u64);++impl PersonCreationCount {+ pub const fn new(count: u64) -> Self {+ Self(count)+ }++ pub const fn get(self) -> u64 {+ self.0+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[repr(transparent)]+pub struct DistinctIdAssignmentCount(u64);++impl DistinctIdAssignmentCount {+ pub const fn new(count: u64) -> Self {+ Self(count)+ }++ pub const fn get(self) -> u64 {+ self.0+ }+}++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]+pub struct WorldGrowth {+ pub person_creations: PersonCreationCount,+ pub distinct_id_assignments: DistinctIdAssignmentCount,+}++impl WorldGrowth {+ pub const fn new(+ person_creations: PersonCreationCount,+ distinct_id_assignments: DistinctIdAssignmentCount,+ ) -> Self {+ Self {+ person_creations,+ distinct_id_assignments,+ }+ }+}++impl Default for PersonCreationCount {+ fn default() -> Self {+ Self::new(0)+ }+}++impl Default for DistinctIdAssignmentCount {+ fn default() -> Self {+ Self::new(0)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+pub struct WorldMemoryEstimate {+ pub growth: WorldGrowth,+ pub person_count: u64,+ pub expected_distinct_id_count: u64,+ pub person_slot_bytes: usize,+ pub distinct_id_slot_bytes: usize,+ pub person_arena_bytes: u64,+ pub distinct_id_arena_bytes: u64,+ pub live_person_index_bytes: u64,+ pub recent_index_bytes: u64,+ pub whale_index_bytes: u64,+ pub chunk_metadata_bytes: u64,+ pub total_bytes: u64,+}++impl WorldMemoryEstimate {+ pub const fn headroom_bytes(self, limit_bytes: u64) -> Option<u64> {+ limit_bytes.checked_sub(self.total_bytes)+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum WorldError {+ InvalidTeamCount(i32),+ InvalidRecentTargetPercent(u8),+ PopulationTooLarge(usize),+ NoEligiblePerson,+ NoEligibleDistinctId,+ VersionExhausted,+ FanoutExhausted,+ ArenaExhausted(&'static str),+ IndexExhausted(&'static str),+ IdentifierExhausted(&'static str),+ AllocationFailed(&'static str),+ MemoryEstimateOverflow,+ InvalidPendingActivation,+}++impl fmt::Display for WorldError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::InvalidTeamCount(team_count) => {+ write!(formatter, "team count must be positive, got {team_count}")+ }+ Self::InvalidRecentTargetPercent(percent) => {+ write!(+ formatter,+ "recent target percent must be at most 100, got {percent}"+ )+ }+ Self::PopulationTooLarge(count) => {+ write!(formatter, "population of {count} exceeds the u32 arena")+ }+ Self::NoEligiblePerson => formatter.write_str("no eligible live person"),+ Self::NoEligibleDistinctId => formatter.write_str("no eligible distinct ID"),+ Self::VersionExhausted => formatter.write_str("entity version exhausted"),+ Self::FanoutExhausted => formatter.write_str("person fanout exhausted"),+ Self::ArenaExhausted(kind) => write!(formatter, "{kind} arena exhausted"),+ Self::IndexExhausted(kind) => write!(formatter, "{kind} index exhausted"),+ Self::IdentifierExhausted(kind) => write!(formatter, "{kind} identifier exhausted"),+ Self::AllocationFailed(kind) => write!(formatter, "allocate {kind} index capacity"),+ Self::MemoryEstimateOverflow => formatter.write_str("memory estimate overflowed"),+ Self::InvalidPendingActivation => {+ formatter.write_str("pending world activation is invalid or already applied")+ }+ }+ }+}++impl std::error::Error for WorldError {}++fn increment_version(version: i64) -> Result<i64, WorldError> {+ version.checked_add(1).ok_or(WorldError::VersionExhausted)+}++fn stale_version(version: i64) -> i64 {+ version.saturating_sub(1)+}++fn allocate_zipf_counts(weights: &[f64], total: usize) -> Vec<usize> {+ let total_weight: f64 = weights.iter().sum();+ let exact = weights+ .iter()+ .map(|weight| weight / total_weight * total as f64)+ .collect::<Vec<_>>();+ let mut counts = exact+ .iter()+ .map(|value| value.floor() as usize)+ .collect::<Vec<_>>();+ let assigned: usize = counts.iter().sum();+ let mut remainders = exact+ .iter()+ .enumerate()+ .map(|(index, value)| (index, value.fract()))+ .collect::<Vec<_>>();+ remainders.sort_by(|left, right| {+ right+ .1+ .total_cmp(&left.1)+ .then_with(|| left.0.cmp(&right.0))+ });+ for (index, _) in remainders.into_iter().take(total.saturating_sub(assigned)) {+ counts[index] += 1;+ }+ counts+}++fn fanout_for_roll(bucket_roll: u32, within_bucket_roll: u64) -> u32 {+ let bucket = FANOUT_BUCKETS+ .iter()+ .find(|bucket| bucket_roll < bucket.upper_roll_exclusive)+ .unwrap_or(&FANOUT_BUCKETS[FANOUT_BUCKETS.len() - 1]);+ let width = u64::from(bucket.max - bucket.min + 1);+ bucket.min + (within_bucket_roll % width) as u32+}++fn whale_bucket_rolls() -> u64 {+ let previous_upper = FANOUT_BUCKETS[FANOUT_BUCKETS.len() - 2].upper_roll_exclusive;+ u64::from(FANOUT_ROLLS - previous_upper)+}++fn expected_distinct_id_count(person_count: u64) -> Result<u64, WorldError> {+ let weighted_doubled_fanout =+ FANOUT_BUCKETS+ .iter()+ .enumerate()+ .try_fold(0u64, |total, (index, bucket)| {+ let lower = if index == 0 {+ 0+ } else {+ FANOUT_BUCKETS[index - 1].upper_roll_exclusive+ };+ let rolls = u64::from(bucket.upper_roll_exclusive - lower);+ let doubled_mean = u64::from(bucket.min + bucket.max);+ total+ .checked_add(+ rolls+ .checked_mul(doubled_mean)+ .ok_or(WorldError::MemoryEstimateOverflow)?,+ )+ .ok_or(WorldError::MemoryEstimateOverflow)+ })?;+ let numerator = person_count+ .checked_mul(weighted_doubled_fanout)+ .ok_or(WorldError::MemoryEstimateOverflow)?;+ div_ceil(numerator, u64::from(FANOUT_ROLLS) * 2)+}++fn chunk_count(items: u64) -> Result<u64, WorldError> {+ div_ceil(items, ARENA_CHUNK_CAPACITY as u64)+}++fn chunk_allocation_bytes(chunks: u64, item_bytes: usize) -> Result<u64, WorldError> {+ checked_product(+ checked_product(chunks, ARENA_CHUNK_CAPACITY as u64)?,+ item_bytes as u64,+ )+}++fn checked_product(left: u64, right: u64) -> Result<u64, WorldError> {+ left.checked_mul(right)+ .ok_or(WorldError::MemoryEstimateOverflow)+}++fn div_ceil(numerator: u64, denominator: u64) -> Result<u64, WorldError> {+ let adjusted = numerator+ .checked_add(denominator - 1)+ .ok_or(WorldError::MemoryEstimateOverflow)?;+ Ok(adjusted / denominator)+}++/// Generate a JSONB properties object padded to approximately `target_bytes`.+pub fn generate_properties(rng: &mut impl Rng, target_bytes: usize) -> Value {+ const KEYS: &[&str] = &[+ "$browser",+ "$os",+ "$initial_referrer",+ "$initial_referring_domain",+ "$geoip_city_name",+ "$geoip_country_code",+ "$geoip_time_zone",+ "email",+ "name",+ "plan",+ "company",+ "role",+ "signup_date",+ "last_login",+ ];++ let mut object = serde_json::Map::with_capacity(KEYS.len() + 1);+ for key in KEYS {+ let value_len = rng.gen_range(4..30);+ let value = (0..value_len)+ .map(|_| rng.gen_range(b'a'..=b'z') as char)+ .collect::<String>();+ object.insert((*key).to_owned(), Value::String(value));+ }+ let current_bytes = Value::Object(object.clone()).to_string().len();+ if current_bytes < target_bytes {+ let value_len = (target_bytes - current_bytes).saturating_sub(12);+ let padding = (0..value_len)+ .map(|_| rng.gen_range(b'a'..=b'z') as char)+ .collect::<String>();+ object.insert("_pad".to_owned(), Value::String(padding));+ }+ Value::Object(object)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::benchmark::ops::PhaseId;++ const TEST_PHASE: PhaseId = PhaseId::new(1);++ fn at(nanos: u64) -> NanosSincePhaseStart {+ at_in_phase(TEST_PHASE, nanos)+ }++ fn at_in_phase(phase_id: PhaseId, nanos: u64) -> NanosSincePhaseStart {+ NanosSincePhaseStart::from_nanos(phase_id, nanos)+ }++ fn empty_world() -> WorldState {+ WorldState::new(WorldConfig {+ seed: 7,+ team_count: 1,+ initial_person_count: 0,+ recent_capacity_per_team: 8,+ recent_target_percent: 50,+ property_bytes: 32,+ })+ .expect("valid world")+ }++ #[test]+ fn versions_survive_phases_and_full_merge_matches_producer_versions() {+ let mut world = empty_world();+ world.create_person(0, 3).expect("first person");++ let update_one = world+ .resolve_person_upsert(at(10), ReplayMode::Fresh)+ .expect("first update");+ let update_two = world+ .resolve_person_upsert(at_in_phase(PhaseId::new(2), 0), ReplayMode::Fresh)+ .expect("next phase update");+ let version = |descriptor: &OpDescriptor| match &descriptor.payload {+ OpPayload::PersonUpsert(payload) => payload.version,+ _ => panic!("expected person upsert"),+ };+ assert!(version(&update_two) > version(&update_one));++ world.create_person(0, 2).expect("second person");+ let before = world+ .persons+ .iter()+ .enumerate()+ .filter(|(_, person)| person.live_index().is_some())+ .map(|(index, person)| {+ (+ world.person_uuid(PersonKey(index as u32)),+ person.version,+ person.distinct_id_count,+ )+ })+ .collect::<Vec<_>>();+ let merge = world.resolve_full_merge(at(20)).expect("full merge");+ let payload = match merge.payload {+ OpPayload::FullMerge(payload) => payload,+ _ => panic!("expected full merge"),+ };++ let (_, source_version, source_fanout) = before+ .iter()+ .find(|(uuid, _, _)| *uuid == payload.source_person_uuid)+ .expect("source existed");+ let (_, target_version, _) = before+ .iter()+ .find(|(uuid, _, _)| *uuid == payload.target_person_uuid)+ .expect("target existed");+ assert_eq!(payload.distinct_id_moves.len(), *source_fanout as usize);+ assert_eq!(+ payload.target_version,+ (*source_version).max(*target_version) + 1+ );+ assert_eq!(payload.source_tombstone_version, source_version + 100);+ assert_eq!(world.live_person_count(), 1);++ let source_key = before+ .iter()+ .position(|(uuid, _, _)| *uuid == payload.source_person_uuid)+ .map(|index| PersonKey(index as u32))+ .expect("source key");+ let target_key = before+ .iter()+ .position(|(uuid, _, _)| *uuid == payload.target_person_uuid)+ .map(|index| PersonKey(index as u32))+ .expect("target key");+ assert_eq!(+ world.person(source_key).version,+ payload.source_tombstone_version+ );+ assert_eq!(world.person(target_key).version, payload.target_version);+ assert!(world.person(source_key).live_index().is_none());+ assert_eq!(world.person(source_key).distinct_id_count, 0);++ let population = world.population();+ for moved in &payload.distinct_id_moves {+ let mapping = population+ .distinct_ids()+ .find(|mapping| mapping.distinct_id == moved.distinct_id)+ .expect("moved mapping");+ assert_eq!(mapping.person_uuid, payload.target_person_uuid);+ }+ }++ #[test]+ fn read_misses_and_fanout_edges_are_explicit() {+ assert_eq!(fanout_for_roll(0, 0), 1);+ assert_eq!(fanout_for_roll(94_999, u64::MAX), 1);+ assert_eq!(fanout_for_roll(95_000, 0), 2);+ assert_eq!(fanout_for_roll(99_989, u64::MAX), 2);+ assert_eq!(fanout_for_roll(99_990, 0), 3);+ assert_eq!(fanout_for_roll(99_998, 97), 100);+ assert_eq!(fanout_for_roll(99_999, 0), 101);+ assert_eq!(fanout_for_roll(99_999, 899), 1_000);++ let mut world = empty_world();+ world.create_person(0, 101).expect("whale person");+ world.create_person(0, 1).expect("merge target");+ let miss = world+ .resolve_read(at(0), ReadMode::Miss)+ .expect("read miss");+ let miss_payload = match miss.payload {+ OpPayload::CanonicalRead(payload) => payload,+ _ => panic!("expected read"),+ };+ assert_eq!(miss_payload.expectation, ReadExpectation::Miss);+ assert!(world+ .population()+ .distinct_ids()+ .all(|mapping| mapping.distinct_id != miss_payload.distinct_id));++ let whale_merge = world.resolve_whale_merge(at(1)).expect("whale merge");+ let merge_payload = match whale_merge.payload {+ OpPayload::FullMerge(payload) => payload,+ _ => panic!("expected merge"),+ };+ assert_eq!(merge_payload.shape, MergeShape::Whale);+ assert_eq!(merge_payload.distinct_id_moves.len(), 101);+ }++ #[test]+ fn forty_five_million_person_estimate_stays_below_five_gibibytes() {+ let config = WorldConfig {+ initial_person_count: 45_000_000,+ ..WorldConfig::default()+ };+ let estimate = WorldState::estimate_initial_memory(&config).expect("memory estimate");++ assert_eq!(estimate.person_slot_bytes, 32);+ assert_eq!(estimate.distinct_id_slot_bytes, 16);+ assert_eq!(size_of::<PersonKey>(), 4);+ assert_eq!(estimate.expected_distinct_id_count, 47_697_300);+ assert!(estimate.total_bytes < 5 * 1024 * 1024 * 1024);+ }++ #[test]+ fn memory_estimate_accounts_for_growth_and_creation_primary_ids() {+ let config = WorldConfig::default();+ let initial = WorldState::estimate_initial_memory(&config).expect("initial estimate");+ assert_eq!(+ initial,+ WorldState::estimate_memory(&config, WorldGrowth::default())+ .expect("zero-growth estimate")+ );++ let growth = WorldGrowth::new(+ PersonCreationCount::new(1_000),+ DistinctIdAssignmentCount::new(2_000),+ );+ let grown = WorldState::estimate_memory(&config, growth).expect("growth estimate");++ assert_eq!(grown.person_count, initial.person_count + 1_000);+ assert_eq!(+ initial.recent_index_bytes,+ config.team_count as u64+ * config.recent_capacity_per_team as u64+ * size_of::<PersonKey>() as u64+ );+ assert_eq!(+ grown.expected_distinct_id_count,+ initial.expected_distinct_id_count + 3_000+ );+ assert!(grown.total_bytes >= initial.total_bytes);+ assert!(+ initial.headroom_bytes(grown.total_bytes).expect("headroom")+ >= grown.headroom_bytes(grown.total_bytes).expect("exact fit")+ );+ assert!(grown.headroom_bytes(grown.total_bytes - 1).is_none());+ }++ #[test]+ fn person_growth_is_reserved_before_the_workload() {+ let mut world = WorldState::new(WorldConfig {+ team_count: 4,+ initial_person_count: 100,+ ..WorldConfig::default()+ })+ .expect("world");+ world+ .reserve_person_growth(PersonCreationCount::new(50))+ .expect("growth reservation");++ let reserved_slots = world+ .teams+ .iter()+ .map(|team| team.live_persons.capacity() - team.live_persons.len())+ .sum::<usize>();+ assert!(reserved_slots >= 50);+ assert!(world.growth_reservation_enabled);+ }++ #[test]+ fn distinct_id_selection_rotates_the_intrusive_list() {+ let mut world = empty_world();+ let person = world.create_person(0, 3).expect("person");+ let first = world+ .person(person)+ .first_distinct_id()+ .expect("first distinct ID");+ let second = world.distinct_id(first).next().expect("second distinct ID");+ let third = world.distinct_id(second).next().expect("third distinct ID");++ let selected = (0..4)+ .map(|_| {+ world+ .select_distinct_id(person)+ .expect("selected distinct ID")+ })+ .collect::<Vec<_>>();++ assert_eq!(selected, vec![first, second, third, first]);+ assert_eq!(world.person(person).first_distinct_id(), Some(second));+ assert_eq!(world.person(person).last_distinct_id(), Some(first));+ }++ #[test]+ fn person_creation_preflights_distinct_id_capacity() {+ let mut world = empty_world();+ let person_count = world.persons.len();+ let live_count = world.teams[0].live_persons.len();+ let recent_count = world.teams[0].recent.len();+ world.distinct_ids.len = u32::MAX;++ assert_eq!(+ world.create_person(0, 1),+ Err(WorldError::ArenaExhausted("distinct ID"))+ );+ assert_eq!(world.persons.len(), person_count);+ assert_eq!(world.teams[0].live_persons.len(), live_count);+ assert_eq!(world.teams[0].recent.len(), recent_count);+ }++ #[test]+ fn pending_creation_is_invisible_until_both_writes_activate_it() {+ let mut world = empty_world();+ let creation = world.resolve_creation(at(0)).expect("pending creation");+ let distinct_id = match &creation.distinct_id_assignment.payload {+ OpPayload::DistinctIdAssignment(payload) => payload.distinct_id.clone(),+ _ => panic!("expected distinct ID assignment"),+ };++ assert_eq!(world.live_person_count(), 0);+ assert_eq!(world.population().persons().count(), 0);+ assert_eq!(world.population().distinct_ids().count(), 0);+ assert_eq!(+ world.resolve_read(at(1), ReadMode::Hit),+ Err(WorldError::NoEligiblePerson)+ );++ world+ .activate_creation(creation.activation)+ .expect("both writes completed");+ let read = world.resolve_read(at(2), ReadMode::Hit).expect("live read");+ let read_distinct_id = match read.payload {+ OpPayload::CanonicalRead(payload) => payload.distinct_id,+ _ => panic!("expected canonical read"),+ };+ assert_eq!(read_distinct_id, distinct_id);+ assert_eq!(world.live_person_count(), 1);+ assert_eq!(+ world.activate_creation(creation.activation),+ Err(WorldError::InvalidPendingActivation)+ );+ }++ #[test]+ fn new_distinct_id_is_invisible_until_its_write_activates_it() {+ let mut world = empty_world();+ world.create_person(0, 1).expect("live person");+ let assignment = world+ .resolve_distinct_id_assignment(at(0), AssignmentMode::New)+ .expect("pending assignment");+ let pending_distinct_id = match &assignment.operation.payload {+ OpPayload::DistinctIdAssignment(payload) => payload.distinct_id.clone(),+ _ => panic!("expected distinct ID assignment"),+ };++ assert_eq!(world.population().distinct_ids().count(), 1);+ let before = world+ .resolve_read(at(1), ReadMode::Hit)+ .expect("existing read");+ assert_ne!(+ match before.payload {+ OpPayload::CanonicalRead(payload) => payload.distinct_id,+ _ => panic!("expected canonical read"),+ },+ pending_distinct_id+ );++ world+ .activate_distinct_id(assignment.activation.expect("new assignment token"))+ .expect("assignment completed");+ assert_eq!(world.population().distinct_ids().count(), 2);+ let reads = (0..2)+ .map(|offset| {+ let read = world+ .resolve_read(at(2 + offset), ReadMode::Hit)+ .expect("live read");+ match read.payload {+ OpPayload::CanonicalRead(payload) => payload.distinct_id,+ _ => panic!("expected canonical read"),+ }+ })+ .collect::<Vec<_>>();+ assert!(reads.contains(&pending_distinct_id));+ }++ #[test]+ fn fresh_existing_assignment_reuses_a_slot_and_advances_its_version() {+ let mut world = empty_world();+ world.create_person(0, 1).expect("live person");+ let before = world+ .population()+ .distinct_ids()+ .next()+ .expect("existing distinct ID");++ let assignment = world+ .resolve_distinct_id_assignment(at(0), AssignmentMode::FreshExisting)+ .expect("fresh existing assignment");+ let payload = match assignment.operation.payload {+ OpPayload::DistinctIdAssignment(payload) => payload,+ _ => panic!("expected distinct ID assignment"),+ };++ assert!(assignment.activation.is_none());+ assert_eq!(world.distinct_id_count(), 1);+ assert_eq!(payload.distinct_id, before.distinct_id);+ assert_eq!(payload.version, before.version + 1);+ }++ #[test]+ fn merge_does_not_remove_the_owner_of_a_pending_distinct_id() {+ let mut world = empty_world();+ world.create_person(0, 1).expect("first live person");+ world.create_person(0, 1).expect("second live person");+ let assignment = world+ .resolve_distinct_id_assignment(at(0), AssignmentMode::New)+ .expect("pending assignment");+ let (pending_owner, pending_distinct_id) = match &assignment.operation.payload {+ OpPayload::DistinctIdAssignment(payload) => {+ (payload.person_uuid, payload.distinct_id.clone())+ }+ _ => panic!("expected distinct ID assignment"),+ };++ let merge = world.resolve_full_merge(at(1)).expect("merge");+ let merge = match merge.payload {+ OpPayload::FullMerge(payload) => payload,+ _ => panic!("expected merge"),+ };+ assert_ne!(merge.source_person_uuid, pending_owner);+ assert_eq!(merge.target_person_uuid, pending_owner);++ world+ .activate_distinct_id(assignment.activation.expect("pending assignment token"))+ .expect("assignment completed");+ let mapping = world+ .population()+ .distinct_ids()+ .find(|mapping| mapping.distinct_id == pending_distinct_id)+ .expect("activated mapping");+ assert_eq!(mapping.person_uuid, pending_owner);+ }++ #[test]+ fn chunk_growth_keeps_existing_allocations_stable() {+ let mut arena = ChunkedArena::new();+ arena.push(0u32).expect("first item");+ let first_address: *const u32 = arena.get(0);+ for value in 1..=ARENA_CHUNK_CAPACITY as u32 {+ arena.push(value).expect("arena item");+ }++ assert_eq!(arena.chunk_count(), 2);+ let current_first_address: *const u32 = arena.get(0);+ assert_eq!(first_address, current_first_address);+ assert_eq!(+ *arena.get(ARENA_CHUNK_CAPACITY as u32),+ ARENA_CHUNK_CAPACITY as u32+ );+ }+}diff --git a/rust/flags-consumer/src/main.rs b/rust/flags-consumer/src/main.rsindex 26ba82c2f168..9fb95901a03d 100644--- a/rust/flags-consumer/src/main.rs+++ b/rust/flags-consumer/src/main.rs@@ -39,7 +39,7 @@ struct Cli {#[derive(Subcommand)]enum Command {- /// Run the GIN index benchmark against the configured database+ /// Run the read-store schema benchmark against the configured databaseBenchmark(BenchmarkArgs),}diff --git a/rust/flags-consumer/src/pipeline/processor.rs b/rust/flags-consumer/src/pipeline/processor.rsindex 016c1762baf3..3b530f78201e 100644--- a/rust/flags-consumer/src/pipeline/processor.rs+++ b/rust/flags-consumer/src/pipeline/processor.rs@@ -1,3 +1,5 @@+use std::collections::btree_map::Entry;+use std::collections::BTreeMap;use std::future::Future;use std::time::Duration;@@ -14,51 +16,192 @@ use crate::storage::types::{};use crate::types::CdcEvent;-/// Classify events into operation types, execute DB writes, return offsets.-///-/// Returns offsets only on success — the caller stores them to advance-/// the consumer group. On failure, offsets are dropped so Kafka redelivers-/// the batch on restart.-pub async fn process_batch(- items: impl Iterator<Item = EventWithOffset>,- size_hint: usize,- storage: &PostgresStorage,- config: &Config,-) -> anyhow::Result<Vec<Offset>> {- let start = std::time::Instant::now();+#[derive(Debug)]+enum PersonMutation {+ Update(PersonUpdateData),+ Deletion(PersonDeletionData),+}- let mut offsets = Vec::with_capacity(size_hint);- let mut person_updates: Vec<PersonUpdateData> = Vec::new();- let mut person_deletions: Vec<PersonDeletionData> = Vec::new();- let mut did_assignments: Vec<DistinctIdAssignmentData> = Vec::new();- let mut did_deletions: Vec<DistinctIdDeletionData> = Vec::new();+type DistinctIdKey = (i32, Box<str>);- for item in items {- offsets.push(item.offset);- match item.event {+trait VersionedMutation {+ fn version(&self) -> i64;+ fn is_deletion(&self) -> bool;+}++impl VersionedMutation for PersonMutation {+ fn version(&self) -> i64 {+ match self {+ Self::Update(data) => data.version,+ Self::Deletion(data) => data.version,+ }+ }++ fn is_deletion(&self) -> bool {+ matches!(self, Self::Deletion(_))+ }+}++trait DistinctIdWrite {+ fn version(&self) -> i64;+ fn person_uuid(&self) -> uuid::Uuid;+}++impl DistinctIdWrite for DistinctIdAssignmentData {+ fn version(&self) -> i64 {+ self.version+ }++ fn person_uuid(&self) -> uuid::Uuid {+ self.person_uuid+ }+}++impl DistinctIdWrite for DistinctIdDeletionData {+ fn version(&self) -> i64 {+ self.version+ }++ fn person_uuid(&self) -> uuid::Uuid {+ self.person_uuid+ }+}++fn insert_latest<K: Ord, V: VersionedMutation>(+ mutations: &mut BTreeMap<K, V>,+ key: K,+ candidate: V,+) {+ match mutations.entry(key) {+ Entry::Vacant(entry) => {+ entry.insert(candidate);+ }+ Entry::Occupied(mut entry) => {+ let current = entry.get();+ // Tombstones win version ties so an ambiguous batch cannot resurrect a key.+ if (candidate.version(), candidate.is_deletion())+ > (current.version(), current.is_deletion())+ {+ entry.insert(candidate);+ }+ }+ }+}++fn insert_latest_distinct_id<T: DistinctIdWrite>(+ writes: &mut BTreeMap<DistinctIdKey, T>,+ key: DistinctIdKey,+ candidate: T,+) {+ match writes.entry(key) {+ Entry::Vacant(entry) => {+ entry.insert(candidate);+ }+ Entry::Occupied(mut entry) => {+ let current = entry.get();+ if (candidate.version(), candidate.person_uuid())+ > (current.version(), current.person_uuid())+ {+ entry.insert(candidate);+ }+ }+ }+}++fn reconcile_distinct_id_writes(+ assignments: &mut BTreeMap<DistinctIdKey, DistinctIdAssignmentData>,+ deletions: &mut BTreeMap<DistinctIdKey, DistinctIdDeletionData>,+) {+ let shared_keys: Vec<DistinctIdKey> = assignments+ .keys()+ .filter(|key| deletions.contains_key(*key))+ .cloned()+ .collect();++ for key in shared_keys {+ let assignment = &assignments[&key];+ let deletion = &deletions[&key];+ if assignment.person_uuid != deletion.person_uuid {+ // Snapshot deletes can race moves; keep both so the owner guard decides after assignment.+ continue;+ }++ if assignment.version > deletion.version {+ deletions.remove(&key);+ } else {+ assignments.remove(&key);+ }+ }+}++#[derive(Default)]+struct InputCounts {+ person_updates: u64,+ person_deletions: u64,+ did_assignments: u64,+ did_deletions: u64,+}++impl InputCounts {+ fn record_success(&self) {+ for (operation, count) in [+ ("person_upsert", self.person_updates),+ ("person_delete", self.person_deletions),+ ("did_assign", self.did_assignments),+ ("did_delete", self.did_deletions),+ ] {+ if count > 0 {+ metrics::counter!(metric_consts::MESSAGES_PROCESSED, "operation" => operation)+ .increment(count);+ }+ }+ }+}++#[derive(Default)]+struct PendingWrites {+ person_mutations: BTreeMap<(i32, uuid::Uuid), PersonMutation>,+ did_assignments: BTreeMap<DistinctIdKey, DistinctIdAssignmentData>,+ did_deletions: BTreeMap<DistinctIdKey, DistinctIdDeletionData>,+ input_counts: InputCounts,+}++impl PendingWrites {+ fn push(&mut self, event: CdcEvent) {+ match event {CdcEvent::PersonUpdate {team_id,person_uuid,properties,version,} => {- person_updates.push(PersonUpdateData {- team_id,- person_uuid,- properties,- version,- });+ self.input_counts.person_updates += 1;+ insert_latest(+ &mut self.person_mutations,+ (team_id, person_uuid),+ PersonMutation::Update(PersonUpdateData {+ team_id,+ person_uuid,+ properties,+ version,+ }),+ );}CdcEvent::PersonDeletion {team_id,person_uuid,version,} => {- person_deletions.push(PersonDeletionData {- team_id,- person_uuid,- version,- });+ self.input_counts.person_deletions += 1;+ insert_latest(+ &mut self.person_mutations,+ (team_id, person_uuid),+ PersonMutation::Deletion(PersonDeletionData {+ team_id,+ person_uuid,+ version,+ }),+ );}CdcEvent::DistinctIdAssignment {team_id,@@ -66,12 +209,17 @@ pub async fn process_batch(distinct_id,version,} => {- did_assignments.push(DistinctIdAssignmentData {- team_id,- person_uuid,- distinct_id,- version,- });+ self.input_counts.did_assignments += 1;+ insert_latest_distinct_id(+ &mut self.did_assignments,+ (team_id, distinct_id.clone()),+ DistinctIdAssignmentData {+ team_id,+ person_uuid,+ distinct_id,+ version,+ },+ );}CdcEvent::DistinctIdDeletion {team_id,@@ -79,84 +227,115 @@ pub async fn process_batch(distinct_id,version,} => {- did_deletions.push(DistinctIdDeletionData {- team_id,- person_uuid,- distinct_id,- version,- });+ self.input_counts.did_deletions += 1;+ insert_latest_distinct_id(+ &mut self.did_deletions,+ (team_id, distinct_id.clone()),+ DistinctIdDeletionData {+ team_id,+ person_uuid,+ distinct_id,+ version,+ },+ );+ }+ }+ }++ fn finish(mut self) -> BatchWrites {+ reconcile_distinct_id_writes(&mut self.did_assignments, &mut self.did_deletions);++ let mut writes = BatchWrites {+ did_assignments: self.did_assignments.into_values().collect(),+ did_deletions: self.did_deletions.into_values().collect(),+ input_counts: self.input_counts,+ ..Default::default()+ };++ for mutation in self.person_mutations.into_values() {+ match mutation {+ PersonMutation::Update(data) => writes.person_updates.push(data),+ PersonMutation::Deletion(data) => writes.person_deletions.push(data),}}+ writes+ }+}++#[derive(Default)]+struct BatchWrites {+ person_updates: Vec<PersonUpdateData>,+ person_deletions: Vec<PersonDeletionData>,+ did_assignments: Vec<DistinctIdAssignmentData>,+ did_deletions: Vec<DistinctIdDeletionData>,+ input_counts: InputCounts,+}++#[cfg(test)]+fn dedupe_events(events: impl IntoIterator<Item = CdcEvent>) -> BatchWrites {+ let mut pending = PendingWrites::default();+ for event in events {+ pending.push(event);+ }+ pending.finish()+}++/// Classify events into operation types, execute DB writes, return offsets.+///+/// Returns offsets only on success — the caller stores them to advance+/// the consumer group. On failure, offsets are dropped so Kafka redelivers+/// the batch on restart.+pub async fn process_batch(+ items: impl Iterator<Item = EventWithOffset>,+ size_hint: usize,+ storage: &PostgresStorage,+ config: &Config,+) -> anyhow::Result<Vec<Offset>> {+ let start = std::time::Instant::now();++ let mut offsets = Vec::with_capacity(size_hint);+ let mut pending = PendingWrites::default();++ for item in items {+ offsets.push(item.offset);+ pending.push(item.event);}- let result = execute_writes(- storage,- config,- &person_updates,- &person_deletions,- &did_assignments,- &did_deletions,- )- .await;+ let writes = pending.finish();+ let result = execute_writes(storage, config, &writes).await;let elapsed_ms = start.elapsed().as_millis() as f64;metrics::histogram!(metric_consts::BATCH_PROCESS_DURATION_MS).record(elapsed_ms);result?;+ writes.input_counts.record_success();tracing::debug!(batch_size = offsets.len(), "batch processed successfully");Ok(offsets)}-/// Execute storage writes: person upserts/deletes (batched via UNNEST),-/// then distinct-ID assignments/deletes (individual transactions).+/// Execute all four storage batches with retry handling.async fn execute_writes(storage: &PostgresStorage,config: &Config,- person_updates: &[PersonUpdateData],- person_deletions: &[PersonDeletionData],- did_assignments: &[DistinctIdAssignmentData],- did_deletions: &[DistinctIdDeletionData],+ writes: &BatchWrites,) -> anyhow::Result<()> {- if !person_updates.is_empty() {- with_retry(config, || storage.batch_upsert_persons(person_updates)).await?;- metrics::counter!(- metric_consts::MESSAGES_PROCESSED,- "operation" => "person_upsert"- )- .increment(person_updates.len() as u64);- }-- if !person_deletions.is_empty() {- with_retry(config, || storage.batch_delete_persons(person_deletions)).await?;- metrics::counter!(- metric_consts::MESSAGES_PROCESSED,- "operation" => "person_delete"- )- .increment(person_deletions.len() as u64);- }-- for assignment in did_assignments {- with_retry(config, || storage.upsert_distinct_id(assignment)).await?;- }- if !did_assignments.is_empty() {- metrics::counter!(- metric_consts::MESSAGES_PROCESSED,- "operation" => "did_assign"- )- .increment(did_assignments.len() as u64);- }-- for deletion in did_deletions {- with_retry(config, || storage.delete_distinct_id(deletion)).await?;- }- if !did_deletions.is_empty() {- metrics::counter!(- metric_consts::MESSAGES_PROCESSED,- "operation" => "did_delete"- )- .increment(did_deletions.len() as u64);- }+ with_retry(config, || {+ storage.batch_upsert_persons(&writes.person_updates)+ })+ .await?;+ with_retry(config, || {+ storage.batch_delete_persons(&writes.person_deletions)+ })+ .await?;+ with_retry(config, || {+ storage.batch_upsert_distinct_ids(&writes.did_assignments)+ })+ .await?;+ with_retry(config, || {+ storage.batch_delete_distinct_ids(&writes.did_deletions)+ })+ .await?;Ok(())}@@ -203,3 +382,183 @@ where}}}++#[cfg(test)]+mod tests {+ use super::*;++ fn did_assignment(person_uuid: uuid::Uuid, distinct_id: &str, version: i64) -> CdcEvent {+ CdcEvent::DistinctIdAssignment {+ team_id: 1,+ person_uuid,+ distinct_id: distinct_id.into(),+ version,+ }+ }++ fn did_deletion(person_uuid: uuid::Uuid, distinct_id: &str, version: i64) -> CdcEvent {+ CdcEvent::DistinctIdDeletion {+ team_id: 1,+ person_uuid,+ distinct_id: distinct_id.into(),+ version,+ }+ }++ #[test]+ fn dedupes_person_mutations_by_primary_key_and_version() {+ let update_wins = uuid::Uuid::from_u128(1);+ let deletion_wins = uuid::Uuid::from_u128(2);+ let tied = uuid::Uuid::from_u128(3);+ let writes = dedupe_events([+ CdcEvent::PersonUpdate {+ team_id: 1,+ person_uuid: update_wins,+ properties: serde_json::json!({"version": 1}),+ version: 1,+ },+ CdcEvent::PersonDeletion {+ team_id: 1,+ person_uuid: update_wins,+ version: 3,+ },+ CdcEvent::PersonUpdate {+ team_id: 1,+ person_uuid: update_wins,+ properties: serde_json::json!({"version": 4}),+ version: 4,+ },+ CdcEvent::PersonUpdate {+ team_id: 1,+ person_uuid: deletion_wins,+ properties: serde_json::json!({}),+ version: 5,+ },+ CdcEvent::PersonDeletion {+ team_id: 1,+ person_uuid: deletion_wins,+ version: 6,+ },+ CdcEvent::PersonUpdate {+ team_id: 1,+ person_uuid: tied,+ properties: serde_json::json!({}),+ version: 7,+ },+ CdcEvent::PersonDeletion {+ team_id: 1,+ person_uuid: tied,+ version: 7,+ },+ ]);++ assert_eq!(writes.person_updates.len(), 1);+ assert_eq!(writes.person_updates[0].person_uuid, update_wins);+ assert_eq!(writes.person_updates[0].version, 4);+ assert_eq!(writes.person_deletions.len(), 2);+ assert_eq!(writes.person_deletions[0].person_uuid, deletion_wins);+ assert_eq!(writes.person_deletions[0].version, 6);+ assert_eq!(writes.person_deletions[1].person_uuid, tied);+ assert_eq!(writes.person_deletions[1].version, 7);+ }++ #[test]+ fn cross_owner_assignment_and_deletion_survive_in_both_orders() {+ let old_owner = uuid::Uuid::from_u128(1);+ let new_owner = uuid::Uuid::from_u128(2);+ for order in [[0, 1], [1, 0]] {+ let writes = dedupe_events(order.map(|index| match index {+ 0 => did_assignment(new_owner, "did", 11),+ _ => did_deletion(old_owner, "did", 110),+ }));++ assert_eq!(writes.did_assignments.len(), 1);+ assert_eq!(writes.did_assignments[0].person_uuid, new_owner);+ assert_eq!(writes.did_deletions.len(), 1);+ assert_eq!(writes.did_deletions[0].person_uuid, old_owner);+ }+ }++ #[test]+ fn three_cycle_resolves_after_per_operation_dedupe() {+ let owner_a = uuid::Uuid::from_u128(1);+ let owner_b = uuid::Uuid::from_u128(2);+ for order in [+ [0, 1, 2],+ [0, 2, 1],+ [1, 0, 2],+ [1, 2, 0],+ [2, 0, 1],+ [2, 1, 0],+ ] {+ let writes = dedupe_events(order.map(|index| match index {+ 0 => did_assignment(owner_a, "did", 1),+ 1 => did_deletion(owner_b, "did", 100),+ _ => did_assignment(owner_b, "did", 2),+ }));++ assert!(writes.did_assignments.is_empty());+ assert_eq!(writes.did_deletions.len(), 1);+ assert_eq!(writes.did_deletions[0].person_uuid, owner_b);+ assert_eq!(writes.did_deletions[0].version, 100);+ }+ }++ #[test]+ fn stale_cross_owner_assignment_and_latest_deletion_survive() {+ let stale_owner = uuid::Uuid::from_u128(1);+ let current_owner = uuid::Uuid::from_u128(2);+ for order in [+ [0, 1, 2],+ [0, 2, 1],+ [1, 0, 2],+ [1, 2, 0],+ [2, 0, 1],+ [2, 1, 0],+ ] {+ let writes = dedupe_events(order.map(|index| match index {+ 0 => did_assignment(stale_owner, "did", 5),+ 1 => did_deletion(current_owner, "did", 100),+ _ => did_deletion(current_owner, "did", 110),+ }));++ assert_eq!(writes.did_assignments.len(), 1);+ assert_eq!(writes.did_assignments[0].person_uuid, stale_owner);+ assert_eq!(writes.did_assignments[0].version, 5);+ assert_eq!(writes.did_deletions.len(), 1);+ assert_eq!(writes.did_deletions[0].person_uuid, current_owner);+ assert_eq!(writes.did_deletions[0].version, 110);+ }+ }++ #[test]+ fn same_owner_assignment_and_deletion_choose_max_version() {+ let owner = uuid::Uuid::from_u128(1);+ for (assignment_version, deletion_version, deletion_wins) in+ [(12, 11, false), (11, 12, true), (13, 13, true)]+ {+ for deletion_first in [false, true] {+ let events = if deletion_first {+ [+ did_deletion(owner, "did", deletion_version),+ did_assignment(owner, "did", assignment_version),+ ]+ } else {+ [+ did_assignment(owner, "did", assignment_version),+ did_deletion(owner, "did", deletion_version),+ ]+ };+ let writes = dedupe_events(events);++ assert_eq!(writes.did_assignments.len(), usize::from(!deletion_wins));+ assert_eq!(writes.did_deletions.len(), usize::from(deletion_wins));+ if deletion_wins {+ assert_eq!(writes.did_deletions[0].version, deletion_version);+ } else {+ assert_eq!(writes.did_assignments[0].version, assignment_version);+ }+ }+ }+ }+}diff --git a/rust/flags-consumer/src/storage/postgres.rs b/rust/flags-consumer/src/storage/postgres.rsindex 70aeec0f035e..b03c49ca5484 100644--- a/rust/flags-consumer/src/storage/postgres.rs+++ b/rust/flags-consumer/src/storage/postgres.rs@@ -6,7 +6,8 @@ use uuid::Uuid;use crate::metric_consts;use crate::storage::types::{- DistinctIdAssignmentData, DistinctIdDeletionData, PersonDeletionData, PersonUpdateData,+ DistinctIdAssignmentData, DistinctIdDeletionData, PersonDeletionData, PersonLookupData,+ PersonUpdateData,};static LABELS_PERSON_UPSERT: LazyLock<[(String, String); 1]> =@@ -17,9 +18,86 @@ static LABELS_DID_ASSIGN: LazyLock<[(String, String); 1]> =LazyLock::new(|| [("operation".to_string(), "did_assign".to_string())]);static LABELS_DID_DELETE: LazyLock<[(String, String); 1]> =LazyLock::new(|| [("operation".to_string(), "did_delete".to_string())]);+static LABELS_PERSON_LOOKUP: LazyLock<[(String, String); 1]> =+ LazyLock::new(|| [("operation".to_string(), "person_lookup".to_string())]);static LABELS_HEARTBEAT: LazyLock<[(String, String); 1]> =LazyLock::new(|| [("operation".to_string(), "heartbeat".to_string())]);+pub(crate) const PERSON_UPSERT_SQL: &str = r#"+ INSERT INTO flags_person (team_id, person_uuid, properties, person_version)+ SELECT * FROM UNNEST($1::int[], $2::uuid[], $3::jsonb[], $4::bigint[])+ ON CONFLICT (team_id, person_uuid) DO UPDATE SET+ properties = EXCLUDED.properties,+ person_version = EXCLUDED.person_version,+ deleted_at = NULL+ WHERE flags_person.person_version < EXCLUDED.person_version+"#;++pub(crate) const PERSON_DELETE_SQL: &str = r#"+ INSERT INTO flags_person+ (team_id, person_uuid, properties, person_version, deleted_at)+ SELECT team_id, person_uuid, '{}'::jsonb, version, NOW()+ FROM UNNEST($1::int[], $2::uuid[], $3::bigint[])+ AS t(team_id, person_uuid, version)+ ON CONFLICT (team_id, person_uuid) DO UPDATE SET+ properties = '{}'::jsonb,+ person_version = EXCLUDED.person_version,+ deleted_at = NOW()+ WHERE flags_person.person_version < EXCLUDED.person_version+ OR (+ flags_person.person_version = EXCLUDED.person_version+ AND flags_person.deleted_at IS NULL+ )+"#;++pub(crate) const DISTINCT_ID_UPSERT_SQL: &str = r#"+ INSERT INTO flags_distinct_id_map (team_id, distinct_id, person_uuid, version)+ SELECT * FROM UNNEST($1::int[], $2::text[], $3::uuid[], $4::bigint[])+ ON CONFLICT (team_id, distinct_id) DO UPDATE SET+ person_uuid = EXCLUDED.person_uuid,+ version = EXCLUDED.version,+ deleted_at = NULL+ WHERE flags_distinct_id_map.version < EXCLUDED.version+ OR (+ flags_distinct_id_map.deleted_at IS NOT NULL+ AND flags_distinct_id_map.person_uuid <> EXCLUDED.person_uuid+ -- Deletions carry the producer's owner version plus 100. Compare+ -- cross-owner assignments with that underlying owner version.+ AND flags_distinct_id_map.version::numeric < EXCLUDED.version::numeric + 100+ )+"#;++pub(crate) const DISTINCT_ID_DELETE_SQL: &str = r#"+ INSERT INTO flags_distinct_id_map+ (team_id, distinct_id, person_uuid, version, deleted_at)+ SELECT team_id, distinct_id, person_uuid, version, NOW()+ FROM UNNEST($1::int[], $2::text[], $3::uuid[], $4::bigint[])+ AS t(team_id, distinct_id, person_uuid, version)+ ON CONFLICT (team_id, distinct_id) DO UPDATE SET+ person_uuid = EXCLUDED.person_uuid,+ version = GREATEST(flags_distinct_id_map.version, EXCLUDED.version),+ deleted_at = NOW()+ WHERE flags_distinct_id_map.person_uuid = EXCLUDED.person_uuid+ AND (+ flags_distinct_id_map.version < EXCLUDED.version+ OR (+ flags_distinct_id_map.version = EXCLUDED.version+ AND flags_distinct_id_map.deleted_at IS NULL+ )+ )+"#;++pub(crate) const CANONICAL_READ_SQL: &str = r#"+ SELECT p.person_uuid, p.properties+ FROM flags_distinct_id_map m+ JOIN flags_person p+ ON p.team_id = m.team_id AND p.person_uuid = m.person_uuid+ WHERE m.team_id = $1+ AND m.distinct_id = $2+ AND m.deleted_at IS NULL+ AND p.deleted_at IS NULL+"#;+/// PostgreSQL handle for the dedicated `flags_read_store` database.pub struct PostgresStorage {pub pool: PgPool,@@ -55,27 +133,16 @@ impl PostgresStorage {let team_ids: Vec<i32> = updates.iter().map(|u| u.team_id).collect();let person_uuids: Vec<Uuid> = updates.iter().map(|u| u.person_uuid).collect();- let properties: Vec<serde_json::Value> =- updates.iter().map(|u| u.properties.clone()).collect();+ let properties: Vec<&serde_json::Value> = updates.iter().map(|u| &u.properties).collect();let versions: Vec<i64> = updates.iter().map(|u| u.version).collect();- let result = sqlx::query(- r#"- INSERT INTO flags_person_lookup (team_id, person_uuid, properties, person_version)- SELECT * FROM UNNEST($1::int[], $2::uuid[], $3::jsonb[], $4::bigint[])- ON CONFLICT (team_id, person_uuid) DO UPDATE SET- properties = EXCLUDED.properties,- person_version = EXCLUDED.person_version,- deleted_at = NULL- WHERE flags_person_lookup.person_version < EXCLUDED.person_version- "#,- )- .bind(&team_ids)- .bind(&person_uuids)- .bind(&properties)- .bind(&versions)- .execute(&self.pool)- .await?;+ let result = sqlx::query(PERSON_UPSERT_SQL)+ .bind(&team_ids)+ .bind(&person_uuids)+ .bind(&properties)+ .bind(&versions)+ .execute(&self.pool)+ .await?;Ok(result.rows_affected())}@@ -83,7 +150,6 @@ impl PostgresStorage {/// Soft-delete: keep the row so the upsert's version guard can still/// reject stale `PersonUpdate` messages arriving after the delete./// The incoming version includes a +100 bump from the producer for deletions.- /// `distinct_ids` is cleared so the GIN index can't surface tombstoned rows.pub async fn batch_delete_persons(&self,deletions: &[PersonDeletionData],@@ -101,109 +167,94 @@ impl PostgresStorage {let person_uuids: Vec<Uuid> = deletions.iter().map(|d| d.person_uuid).collect();let versions: Vec<i64> = deletions.iter().map(|d| d.version).collect();- let result = sqlx::query(- r#"- INSERT INTO flags_person_lookup- (team_id, person_uuid, distinct_ids, properties, person_version, deleted_at)- SELECT team_id, person_uuid, ARRAY[]::text[], '{}'::jsonb, version, NOW()- FROM UNNEST($1::int[], $2::uuid[], $3::bigint[])- AS t(team_id, person_uuid, version)- ON CONFLICT (team_id, person_uuid) DO UPDATE SET- distinct_ids = ARRAY[]::text[],- properties = '{}'::jsonb,- person_version = EXCLUDED.person_version,- deleted_at = NOW()- WHERE flags_person_lookup.person_version < EXCLUDED.person_version- "#,- )- .bind(&team_ids)- .bind(&person_uuids)- .bind(&versions)- .execute(&self.pool)- .await?;+ let result = sqlx::query(PERSON_DELETE_SQL)+ .bind(&team_ids)+ .bind(&person_uuids)+ .bind(&versions)+ .execute(&self.pool)+ .await?;Ok(result.rows_affected())}- /// Assign a distinct_id to a person within a transaction.- /// Removes it from any previous owner first (handles person merges).- pub async fn upsert_distinct_id(+ /// Batch-assign distinct IDs via their primary key.+ pub async fn batch_upsert_distinct_ids(&self,- assignment: &DistinctIdAssignmentData,- ) -> Result<(), sqlx::Error> {+ assignments: &[DistinctIdAssignmentData],+ ) -> Result<u64, sqlx::Error> {+ if assignments.is_empty() {+ return Ok(0);+ }+let _timer =common_metrics::timing_guard(metric_consts::DB_QUERY_DURATION_MS, &*LABELS_DID_ASSIGN);- let mut tx = self.pool.begin().await?;+ let team_ids: Vec<i32> = assignments.iter().map(|a| a.team_id).collect();+ let distinct_ids: Vec<&str> = assignments.iter().map(|a| &*a.distinct_id).collect();+ let person_uuids: Vec<Uuid> = assignments.iter().map(|a| a.person_uuid).collect();+ let versions: Vec<i64> = assignments.iter().map(|a| a.version).collect();- sqlx::query(- r#"- UPDATE flags_person_lookup- SET distinct_ids = array_remove(distinct_ids, $1)- WHERE team_id = $2- AND distinct_ids @> ARRAY[$1]::text[]- AND person_uuid != $3- "#,- )- .bind(&*assignment.distinct_id)- .bind(assignment.team_id)- .bind(assignment.person_uuid)- .execute(&mut *tx)- .await?;-- sqlx::query(- r#"- INSERT INTO flags_person_lookup (team_id, person_uuid, distinct_ids, distinct_id_version)- VALUES ($1, $2, ARRAY[$3]::text[], $4)- ON CONFLICT (team_id, person_uuid) DO UPDATE SET- distinct_ids = CASE- WHEN $3 = ANY(flags_person_lookup.distinct_ids)- THEN flags_person_lookup.distinct_ids- ELSE flags_person_lookup.distinct_ids || $3- END,- distinct_id_version = GREATEST(flags_person_lookup.distinct_id_version, $4)- WHERE flags_person_lookup.deleted_at IS NULL- AND (flags_person_lookup.distinct_id_version < $4- OR NOT ($3 = ANY(flags_person_lookup.distinct_ids)))- "#,- )- .bind(assignment.team_id)- .bind(assignment.person_uuid)- .bind(&*assignment.distinct_id)- .bind(assignment.version)- .execute(&mut *tx)- .await?;+ let result = sqlx::query(DISTINCT_ID_UPSERT_SQL)+ .bind(&team_ids)+ .bind(&distinct_ids)+ .bind(&person_uuids)+ .bind(&versions)+ .execute(&self.pool)+ .await?;- tx.commit().await?;- Ok(())+ Ok(result.rows_affected())}- /// Remove a distinct_id from its owner's array.- pub async fn delete_distinct_id(+ /// Tombstone distinct IDs so stale assignments cannot resurrect them.+ /// The incoming version includes a +100 bump from the producer for deletions.+ pub async fn batch_delete_distinct_ids(&self,- deletion: &DistinctIdDeletionData,- ) -> Result<(), sqlx::Error> {+ deletions: &[DistinctIdDeletionData],+ ) -> Result<u64, sqlx::Error> {+ if deletions.is_empty() {+ return Ok(0);+ }+let _timer =common_metrics::timing_guard(metric_consts::DB_QUERY_DURATION_MS, &*LABELS_DID_DELETE);- sqlx::query(- r#"- UPDATE flags_person_lookup- SET distinct_ids = array_remove(distinct_ids, $1),- distinct_id_version = GREATEST(distinct_id_version, $3)- WHERE team_id = $2- AND person_uuid = $4- AND $1 = ANY(distinct_ids)- "#,- )- .bind(&*deletion.distinct_id)- .bind(deletion.team_id)- .bind(deletion.version)- .bind(deletion.person_uuid)- .execute(&self.pool)- .await?;+ let team_ids: Vec<i32> = deletions.iter().map(|d| d.team_id).collect();+ let distinct_ids: Vec<&str> = deletions.iter().map(|d| &*d.distinct_id).collect();+ let person_uuids: Vec<Uuid> = deletions.iter().map(|d| d.person_uuid).collect();+ let versions: Vec<i64> = deletions.iter().map(|d| d.version).collect();- Ok(())+ let result = sqlx::query(DISTINCT_ID_DELETE_SQL)+ .bind(&team_ids)+ .bind(&distinct_ids)+ .bind(&person_uuids)+ .bind(&versions)+ .execute(&self.pool)+ .await?;++ Ok(result.rows_affected())+ }++ /// Resolve a live distinct ID and person in one round trip.+ pub async fn get_person_by_distinct_id(+ &self,+ team_id: i32,+ distinct_id: &str,+ ) -> Result<Option<PersonLookupData>, sqlx::Error> {+ let _timer = common_metrics::timing_guard(+ metric_consts::DB_QUERY_DURATION_MS,+ &*LABELS_PERSON_LOOKUP,+ );++ let row: Option<(Uuid, serde_json::Value)> = sqlx::query_as(CANONICAL_READ_SQL)+ .bind(team_id)+ .bind(distinct_id)+ .fetch_optional(&self.pool)+ .await?;++ Ok(row.map(|(person_uuid, properties)| PersonLookupData {+ person_uuid,+ properties,+ }))}/// Write a heartbeat record for lag monitoring.diff --git a/rust/flags-consumer/src/storage/types.rs b/rust/flags-consumer/src/storage/types.rsindex 2d97068aa5fb..1b64a318377a 100644--- a/rust/flags-consumer/src/storage/types.rs+++ b/rust/flags-consumer/src/storage/types.rs@@ -1,5 +1,6 @@use uuid::Uuid;+#[derive(Debug)]pub struct PersonUpdateData {pub team_id: i32,pub person_uuid: Uuid,@@ -7,12 +8,14 @@ pub struct PersonUpdateData {pub version: i64,}+#[derive(Debug)]pub struct PersonDeletionData {pub team_id: i32,pub person_uuid: Uuid,pub version: i64,}+#[derive(Debug)]pub struct DistinctIdAssignmentData {pub team_id: i32,pub person_uuid: Uuid,@@ -20,9 +23,16 @@ pub struct DistinctIdAssignmentData {pub version: i64,}+#[derive(Debug)]pub struct DistinctIdDeletionData {pub team_id: i32,pub person_uuid: Uuid,pub distinct_id: Box<str>,pub version: i64,}++#[derive(Debug, PartialEq)]+pub struct PersonLookupData {+ pub person_uuid: Uuid,+ pub properties: serde_json::Value,+}diff --git a/rust/flags-consumer/tests/postgres_storage.rs b/rust/flags-consumer/tests/postgres_storage.rsnew file mode 100644index 000000000000..1accdba198f6--- /dev/null+++ b/rust/flags-consumer/tests/postgres_storage.rs@@ -0,0 +1,311 @@+use chrono::{DateTime, Utc};+use flags_consumer::benchmark::plancheck;+use flags_consumer::storage::{+ postgres::PostgresStorage,+ types::{+ DistinctIdAssignmentData, DistinctIdDeletionData, PersonDeletionData, PersonLookupData,+ PersonUpdateData,+ },+};+use serde_json::{json, Value};+use sqlx::PgPool;+use uuid::Uuid;++async fn upsert_person(+ storage: &PostgresStorage,+ team_id: i32,+ person_uuid: Uuid,+ properties: Value,+ version: i64,+) -> u64 {+ storage+ .batch_upsert_persons(&[PersonUpdateData {+ team_id,+ person_uuid,+ properties,+ version,+ }])+ .await+ .unwrap()+}++async fn person_row(+ pool: &PgPool,+ team_id: i32,+ person_uuid: Uuid,+) -> (Value, i64, Option<DateTime<Utc>>) {+ sqlx::query_as(+ "SELECT properties, person_version, deleted_at FROM flags_person WHERE team_id = $1 AND person_uuid = $2",+ )+ .bind(team_id)+ .bind(person_uuid)+ .fetch_one(pool)+ .await+ .unwrap()+}++async fn assign_distinct_id(+ storage: &PostgresStorage,+ team_id: i32,+ person_uuid: Uuid,+ distinct_id: &str,+ version: i64,+) -> u64 {+ storage+ .batch_upsert_distinct_ids(&[DistinctIdAssignmentData {+ team_id,+ person_uuid,+ distinct_id: distinct_id.into(),+ version,+ }])+ .await+ .unwrap()+}++async fn delete_distinct_id(+ storage: &PostgresStorage,+ team_id: i32,+ person_uuid: Uuid,+ distinct_id: &str,+ version: i64,+) -> u64 {+ storage+ .batch_delete_distinct_ids(&[DistinctIdDeletionData {+ team_id,+ person_uuid,+ distinct_id: distinct_id.into(),+ version,+ }])+ .await+ .unwrap()+}++#[sqlx::test(migrations = "../flags_read_store_migrations")]+async fn person_write_guards_preserve_newer_state_and_tombstone_ties(pool: PgPool) {+ let storage = PostgresStorage::new(pool.clone());+ let team_id = 1;++ let deleted_person_uuid = Uuid::new_v4();+ let deleted = storage+ .batch_delete_persons(&[PersonDeletionData {+ team_id,+ person_uuid: deleted_person_uuid,+ version: 110,+ }])+ .await+ .unwrap();+ let stale_update = upsert_person(+ &storage,+ team_id,+ deleted_person_uuid,+ json!({ "stale": true }),+ 10,+ )+ .await;++ // A tombstone outranks an update carrying the same version, mirroring the delete guard.+ let tied_update = upsert_person(+ &storage,+ team_id,+ deleted_person_uuid,+ json!({ "tied": true }),+ 110,+ )+ .await;++ assert_eq!(deleted, 1);+ assert_eq!(stale_update, 0);+ assert_eq!(tied_update, 0);+ let (properties, version, deleted_at) = person_row(&pool, team_id, deleted_person_uuid).await;+ assert_eq!(properties, json!({}));+ assert_eq!(version, 110);+ assert!(deleted_at.is_some());++ let tied_person_uuid = Uuid::new_v4();+ upsert_person(+ &storage,+ team_id,+ tied_person_uuid,+ json!({ "live": true }),+ 20,+ )+ .await;+ let equal_version_delete = storage+ .batch_delete_persons(&[PersonDeletionData {+ team_id,+ person_uuid: tied_person_uuid,+ version: 20,+ }])+ .await+ .unwrap();+ assert_eq!(equal_version_delete, 1);+ assert!(person_row(&pool, team_id, tied_person_uuid)+ .await+ .2+ .is_some());++ let live_person_uuid = Uuid::new_v4();+ upsert_person(+ &storage,+ team_id,+ live_person_uuid,+ json!({ "newer": true }),+ 30,+ )+ .await;+ let stale_delete = storage+ .batch_delete_persons(&[PersonDeletionData {+ team_id,+ person_uuid: live_person_uuid,+ version: 29,+ }])+ .await+ .unwrap();+ assert_eq!(stale_delete, 0);+ let (properties, version, deleted_at) = person_row(&pool, team_id, live_person_uuid).await;+ assert_eq!(properties, json!({ "newer": true }));+ assert_eq!(version, 30);+ assert!(deleted_at.is_none());+}++#[sqlx::test(migrations = "../flags_read_store_migrations")]+async fn distinct_id_write_guards_are_order_independent(pool: PgPool) {+ let storage = PostgresStorage::new(pool.clone());+ let team_id = 1;+ let old_person_uuid = Uuid::new_v4();+ let new_person_uuid = Uuid::new_v4();+ let new_properties = json!({ "owner": "new" });+ upsert_person(+ &storage,+ team_id,+ old_person_uuid,+ json!({ "owner": "old" }),+ 10,+ )+ .await;+ upsert_person(+ &storage,+ team_id,+ new_person_uuid,+ new_properties.clone(),+ 11,+ )+ .await;++ assign_distinct_id(&storage, team_id, old_person_uuid, "assign-first", 10).await;+ assign_distinct_id(&storage, team_id, new_person_uuid, "assign-first", 11).await;+ let old_owner_delete =+ delete_distinct_id(&storage, team_id, old_person_uuid, "assign-first", 110).await;+ assert_eq!(old_owner_delete, 0);++ assign_distinct_id(&storage, team_id, old_person_uuid, "delete-first", 10).await;+ delete_distinct_id(&storage, team_id, old_person_uuid, "delete-first", 110).await;+ let replacement =+ assign_distinct_id(&storage, team_id, new_person_uuid, "delete-first", 11).await;+ assert_eq!(replacement, 1);++ for distinct_id in ["assign-first", "delete-first"] {+ assert_eq!(+ storage+ .get_person_by_distinct_id(team_id, distinct_id)+ .await+ .unwrap(),+ Some(PersonLookupData {+ person_uuid: new_person_uuid,+ properties: new_properties.clone(),+ })+ );+ }++ assign_distinct_id(&storage, team_id, old_person_uuid, "version-guard", 20).await;+ let stale_assignment =+ assign_distinct_id(&storage, team_id, old_person_uuid, "version-guard", 19).await;+ let stale_delete =+ delete_distinct_id(&storage, team_id, old_person_uuid, "version-guard", 19).await;+ let tied_delete =+ delete_distinct_id(&storage, team_id, old_person_uuid, "version-guard", 20).await;+ assert_eq!(stale_assignment, 0);+ assert_eq!(stale_delete, 0);+ assert_eq!(tied_delete, 1);+ assert_eq!(+ storage+ .get_person_by_distinct_id(team_id, "version-guard")+ .await+ .unwrap(),+ None+ );+}++/// A tombstone carries the old owner's version plus 100, so a later assignment to a+/// different person only wins while its own version outruns that underlying version.+#[sqlx::test(migrations = "../flags_read_store_migrations")]+async fn cross_owner_assignment_wins_only_against_an_older_tombstone(pool: PgPool) {+ let storage = PostgresStorage::new(pool.clone());+ let team_id = 1;+ let old_person_uuid = Uuid::new_v4();+ let new_person_uuid = Uuid::new_v4();+ upsert_person(&storage, team_id, new_person_uuid, json!({}), 1).await;++ // (assignment version, whether it should replace a tombstone left at owner version 10)+ for (version, expected) in [(9, 0), (10, 0), (11, 1)] {+ let distinct_id = format!("bound-{version}");+ assign_distinct_id(&storage, team_id, old_person_uuid, &distinct_id, 10).await;+ delete_distinct_id(&storage, team_id, old_person_uuid, &distinct_id, 110).await;++ let replacement =+ assign_distinct_id(&storage, team_id, new_person_uuid, &distinct_id, version).await;++ assert_eq!(replacement, expected, "assignment at version {version}");+ assert_eq!(+ storage+ .get_person_by_distinct_id(team_id, &distinct_id)+ .await+ .unwrap()+ .is_some(),+ expected == 1,+ "visibility after assignment at version {version}"+ );+ }+}++#[sqlx::test(migrations = "../flags_read_store_migrations")]+async fn migrated_schema_passes_storage_plan_checks(pool: PgPool) {+ sqlx::query(+ r#"+ INSERT INTO flags_person (team_id, person_uuid, properties, person_version)+ SELECT 1, md5(value::text)::uuid, '{}'::jsonb, 1+ FROM generate_series(1, 10000) AS value+ "#,+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query(+ r#"+ INSERT INTO flags_distinct_id_map (team_id, distinct_id, person_uuid, version)+ SELECT 1, 'seed-' || value, md5(value::text)::uuid, 1+ FROM generate_series(1, 10000) AS value+ "#,+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query("ANALYZE flags_person, flags_distinct_id_map")+ .execute(&pool)+ .await+ .unwrap();++ let evidence = plancheck::verify_storage_plans(&pool).await.unwrap();++ assert_eq!(evidence.len(), 5);+ assert_eq!(+ evidence.iter().map(|plan| plan.name).collect::<Vec<_>>(),+ vec![+ "canonical_read",+ "person_upsert",+ "person_tombstone",+ "distinct_id_upsert",+ "distinct_id_tombstone",+ ]+ );+}diff --git a/rust/flags_read_store_migrations/20260411000001_create_flags_person_lookup.sql b/rust/flags_read_store_migrations/20260411000001_create_flags_person_lookup.sqldeleted file mode 100644index 3280918bfbaf..000000000000--- a/rust/flags_read_store_migrations/20260411000001_create_flags_person_lookup.sql+++ /dev/null@@ -1,60 +0,0 @@--- One row per person, keyed on (team_id, person_uuid), with a distinct_ids TEXT[]--- column indexed by GIN so the flags service can replace its two-table JOIN with a--- single PK / GIN read. HASH-partitioned by team_id (64 partitions) to mirror the--- posthog_person table in the shared persons database.---- btree_gin is required so the GIN index can include the scalar team_id column--- alongside the distinct_ids array. A single hash partition can hold rows from--- multiple teams, so keeping team_id in the GIN index is necessary for selective--- lookups within a partition.-CREATE EXTENSION IF NOT EXISTS btree_gin;---- `deleted_at` keeps tombstoned rows around so the upsert's version guard--- still has a row to compare against and can reject stale PersonUpdate--- messages arriving after a delete. Reads must filter `deleted_at IS NULL`.-CREATE TABLE IF NOT EXISTS flags_person_lookup (- team_id INTEGER NOT NULL,- person_uuid UUID NOT NULL,- distinct_ids TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],- properties JSONB NOT NULL DEFAULT '{}'::jsonb,- person_version BIGINT NOT NULL DEFAULT 0,- distinct_id_version BIGINT NOT NULL DEFAULT 0,- deleted_at TIMESTAMPTZ,- PRIMARY KEY (team_id, person_uuid)-) PARTITION BY HASH (team_id);---- Create 64 hash partitions. This matches posthog_person's partition count so the--- two tables stay aligned for future bootstrap / hash key override work.-DO $$-DECLARE- num_partitions INTEGER := 64;- i INTEGER;-BEGIN- FOR i IN 0..(num_partitions - 1) LOOP- EXECUTE format(- 'CREATE TABLE IF NOT EXISTS flags_person_lookup_p%s PARTITION OF flags_person_lookup FOR VALUES WITH (MODULUS %s, REMAINDER %s)',- i, num_partitions, i- );- END LOOP;-END $$;---- GIN index on (team_id, distinct_ids), partial on live rows. Postgres propagates--- the index definition to every hash partition automatically. The partial predicate--- mirrors the read-path filter so tombstoned rows never produce GIN entries, which--- shrinks the index and avoids write amplification as deletions accumulate.-CREATE INDEX IF NOT EXISTS idx_flags_person_gin- ON flags_person_lookup- USING GIN (team_id, distinct_ids)- WHERE deleted_at IS NULL;---- Heartbeat / lag-monitoring table. The CDC consumer will write one row per (source, partition) with--- the last Kafka offset / event timestamp it processed; the shadow read path will--- join against this for staleness checks. Table-only in Step 1; no writes yet.-CREATE TABLE IF NOT EXISTS flags_read_store_heartbeat (- source TEXT NOT NULL,- partition INTEGER NOT NULL,- last_offset BIGINT NOT NULL DEFAULT 0,- last_event_ts TIMESTAMPTZ,- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- PRIMARY KEY (source, partition)-);diff --git a/rust/flags_read_store_migrations/20260411000001_create_flags_read_store.sql b/rust/flags_read_store_migrations/20260411000001_create_flags_read_store.sqlnew file mode 100644index 000000000000..db011b765b2b--- /dev/null+++ b/rust/flags_read_store_migrations/20260411000001_create_flags_read_store.sql@@ -0,0 +1,55 @@+-- Replaces the earlier `flags_person_lookup` array-plus-GIN draft, which never ran+-- outside a local checkout. Near-unique distinct IDs behind an inverted index stall+-- on the GIN pending list, cannot enforce "one distinct ID maps to one person per+-- team", and couple the person and distinct ID write streams onto the same row. Two+-- PK btrees give both properties structurally and keep `person_uuid` remaps on the+-- mapping table HOT-eligible.++-- Versioned tombstones keep stale CDC replays from restoring deleted rows.+CREATE TABLE IF NOT EXISTS flags_person (+ team_id INTEGER NOT NULL,+ person_uuid UUID NOT NULL,+ properties JSONB NOT NULL DEFAULT '{}'::JSONB,+ person_version BIGINT NOT NULL DEFAULT 0,+ deleted_at TIMESTAMPTZ,+ PRIMARY KEY (team_id, person_uuid)+) PARTITION BY HASH (team_id);++CREATE TABLE IF NOT EXISTS flags_distinct_id_map (+ team_id INTEGER NOT NULL,+ distinct_id TEXT NOT NULL,+ person_uuid UUID NOT NULL,+ version BIGINT NOT NULL DEFAULT 0,+ deleted_at TIMESTAMPTZ,+ PRIMARY KEY (team_id, distinct_id)+) PARTITION BY HASH (team_id);++-- Both tables keep the default fillfactor. The benchmark sweeps `--person-fillfactor`+-- and `--map-fillfactor` to measure HOT headroom; ship a follow-up migration if the+-- sweep lands on a lower value.+DO $$+DECLARE+ num_partitions INTEGER := 64;+ i INTEGER;+BEGIN+ FOR i IN 0..(num_partitions - 1) LOOP+ EXECUTE format(+ 'CREATE TABLE IF NOT EXISTS flags_person_p%s PARTITION OF flags_person FOR VALUES WITH (MODULUS %s, REMAINDER %s)',+ i, num_partitions, i+ );+ EXECUTE format(+ 'CREATE TABLE IF NOT EXISTS flags_distinct_id_map_p%s PARTITION OF flags_distinct_id_map FOR VALUES WITH (MODULUS %s, REMAINDER %s)',+ i, num_partitions, i+ );+ END LOOP;+END $$;++-- The CDC consumer records the latest observed Kafka offset per source partition.+CREATE TABLE IF NOT EXISTS flags_read_store_heartbeat (+ source TEXT NOT NULL,+ partition INTEGER NOT NULL,+ last_offset BIGINT NOT NULL DEFAULT 0,+ last_event_ts TIMESTAMPTZ,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ PRIMARY KEY (source, partition)+);