Skip to content

: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.

feat(personhog): continuous traffic mode for the test harness (#73266)

Zach Browneed7f8a866d1
diff --git a/.github/rust-images.yml b/.github/rust-images.yml
index 3c37b44ef3a0..e32bafbe7a42 100644
--- a/.github/rust-images.yml
+++ b/.github/rust-images.yml
@@ -118,6 +118,10 @@
dockerfile: ./rust/Dockerfile
project: hj9nd3cg9w
+- image: personhog-test-harness
+ dockerfile: ./rust/Dockerfile
+ project: 6tl5lmb8l8
+
- image: kafka-assigner
dockerfile: ./rust/Dockerfile
project: 6kjc85bwm7
diff --git a/.github/workflows/rust-docker-build.yml b/.github/workflows/rust-docker-build.yml
index 9ddfb929534e..f42aacd731f0 100644
--- a/.github/workflows/rust-docker-build.yml
+++ b/.github/workflows/rust-docker-build.yml
@@ -192,6 +192,9 @@ jobs:
- release: personhog-writer
digest_key: personhog-writer
values_key: image
+ - release: personhog-test-harness
+ digest_key: personhog-test-harness
+ values_key: image
- release: kafka-assigner
digest_key: kafka-assigner
values_key: image
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 56e91ee66687..35975feffbea 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -7832,11 +7832,14 @@ version = "0.1.0"
dependencies = [
"anyhow",
"assignment-coordination",
+ "axum 0.7.9",
"chrono",
"clap",
+ "common-metrics",
"futures",
"hdrhistogram",
"humantime",
+ "metrics",
"personhog-coordination",
"personhog-proto",
"rand 0.8.5",
diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rs
index c64c7b152720..b9d5124ae750 100644
--- a/rust/personhog-leader/src/config.rs
+++ b/rust/personhog-leader/src/config.rs
@@ -196,6 +196,14 @@ pub struct Config {
#[envconfig(default = "")]
pub fallback_database_url: String,
+ /// Table the fallback reads. Must be the table the writer maintains
+ /// (its PG_TARGET_TABLE): the dirty index treats an unmarked person's
+ /// PG row as current, which is only true of the writer's own target.
+ /// Prod pairs posthog_person on both sides; the dev validation stack
+ /// pairs personhog_person_tmp on both — flip them together at cutover.
+ #[envconfig(default = "posthog_person")]
+ pub fallback_table: String,
+
#[envconfig(default = "5")]
pub fallback_pg_max_connections: u32,
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 3131728a751b..f7ea9aedb7a3 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -27,6 +27,7 @@ use personhog_leader::cache::{DirtyIndex, PartitionedCache};
use personhog_leader::config::Config;
use personhog_leader::coordination::LeaderHandoffHandler;
use personhog_leader::inflight::InflightTracker;
+use personhog_leader::pg::{validate_table_name, PgFallback};
use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::{sweep_idle_locks, PersonHogLeaderService, PropertySizeLimits};
use personhog_leader::warming::{
@@ -39,6 +40,7 @@ common_alloc::used!();
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = Config::init_from_env().expect("Invalid configuration");
+ validate_table_name(&config.fallback_table).expect("Invalid FALLBACK_TABLE");
// Initialize tracing
let log_layer = fmt::layer()
@@ -143,7 +145,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
};
// PG fallback pool for cache misses (optional, disabled if URL is empty)
- let fallback_pool = if config.fallback_database_url.is_empty() {
+ let fallback = if config.fallback_database_url.is_empty() {
tracing::info!("PG fallback disabled (no FALLBACK_DATABASE_URL)");
None
} else {
@@ -155,10 +157,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
statement_timeout_ms: Some(5_000),
..Default::default()
};
- Some(common_database::get_pool_with_config(
- &config.fallback_database_url,
- pool_config,
- )?)
+ Some(PgFallback {
+ pool: common_database::get_pool_with_config(
+ &config.fallback_database_url,
+ pool_config,
+ )?,
+ table: config.fallback_table.clone(),
+ })
};
// Connect to etcd for coordination and the partition count
@@ -201,7 +206,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Arc::clone(&cache),
kafka_producer.clone(),
config.kafka_person_state_topic.clone(),
- fallback_pool,
+ fallback,
Arc::clone(&locks),
Arc::clone(&inflight),
num_partitions,
diff --git a/rust/personhog-leader/src/pg.rs b/rust/personhog-leader/src/pg.rs
index d14ac0b294a2..a16d02d50600 100644
--- a/rust/personhog-leader/src/pg.rs
+++ b/rust/personhog-leader/src/pg.rs
@@ -5,10 +5,31 @@ use sqlx::Row;
use crate::cache::{CachedPerson, PersonCacheKey};
-/// Reads a person from the main Postgres `posthog_person` table.
-/// Used as a fallback when the leader's cache doesn't have the person.
+/// A configured PG fallback: the pool and the table it reads. The table
+/// must be the one the writer maintains (see FALLBACK_TABLE in
+/// config.rs for the pairing rule), so a fallback cannot be constructed
+/// without deciding it.
+#[derive(Clone)]
+pub struct PgFallback {
+ pub pool: PgPool,
+ pub table: String,
+}
+
+/// Validate a configured table identifier before it is interpolated into
+/// SQL (identifiers cannot be bound as parameters).
+pub fn validate_table_name(table: &str) -> Result<(), String> {
+ if table.is_empty() || !table.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
+ return Err(format!("invalid fallback table name: {table:?}"));
+ }
+ Ok(())
+}
+
+/// Reads a person from the configured fallback table — the table the
+/// writer maintains. Used as a fallback when the leader's cache doesn't
+/// have the person.
pub async fn load_person_from_pg(
pool: &PgPool,
+ table: &str,
key: &PersonCacheKey,
) -> Result<Option<CachedPerson>, sqlx::Error> {
let start = std::time::Instant::now();
@@ -21,12 +42,12 @@ pub async fn load_person_from_pg(
// whose PG-expanded rendering serde_json rejects, and the leniency
// lives in our parse step (see below). The cost is identical — sqlx's
// jsonb decode parses the same text under the hood.
- let row = sqlx::query(
+ let row = sqlx::query(&format!(
"SELECT id, team_id, uuid::text, properties::text AS properties, created_at, version, \
is_identified
- FROM posthog_person
+ FROM {table}
WHERE team_id = $1 AND id = $2",
- )
+ ))
.bind(team_id_i32)
.bind(key.person_id)
.fetch_optional(pool)
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index 133a3e7a3653..2fceaa100877 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -10,7 +10,6 @@ use personhog_proto::personhog::types::v1::{
UpdatePersonPropertiesResponse,
};
use rdkafka::producer::FutureProducer;
-use sqlx::postgres::PgPool;
use tokio::sync::Mutex;
use tonic::{Request, Response, Status};
use uuid::Uuid;
@@ -23,7 +22,7 @@ use crate::cache::{
use crate::inflight::InflightTracker;
use crate::kafka::produce_person_changelog;
use crate::person_update::{apply_property_updates, compute_event_property_updates};
-use crate::pg::load_person_from_pg;
+use crate::pg::{load_person_from_pg, PgFallback};
use crate::recovery::ChangelogRecovery;
use crate::warnings::{SizeViolationWarning, WarningsProducer};
use personhog_common::properties::{
@@ -67,8 +66,8 @@ pub struct PersonHogLeaderService {
locks: Arc<DashMap<PersonCacheKey, Arc<Mutex<()>>>>,
producer: FutureProducer<KafkaContext>,
changelog_topic: String,
- /// Read-only pool for PG fallback on cache miss.
- fallback_pool: Option<PgPool>,
+ /// Read-only PG fallback (pool + the table it reads) for cache miss.
+ fallback: Option<PgFallback>,
/// Per-partition inflight counter used to drive the handoff drain phase.
inflight: Arc<InflightTracker>,
/// Total changelog partition count, read from etcd at startup (the same
@@ -90,7 +89,7 @@ impl PersonHogLeaderService {
cache: Arc<PartitionedCache>,
producer: FutureProducer<KafkaContext>,
changelog_topic: String,
- fallback_pool: Option<PgPool>,
+ fallback: Option<PgFallback>,
locks: Arc<DashMap<PersonCacheKey, Arc<Mutex<()>>>>,
inflight: Arc<InflightTracker>,
num_partitions: u32,
@@ -104,7 +103,7 @@ impl PersonHogLeaderService {
locks,
producer,
changelog_topic,
- fallback_pool,
+ fallback,
inflight,
num_partitions,
dirty_index,
@@ -227,7 +226,7 @@ impl PersonHogLeaderService {
partition: u32,
key: &PersonCacheKey,
) -> Result<Arc<CachedPerson>, Status> {
- let Some(pool) = &self.fallback_pool else {
+ let Some(fallback) = &self.fallback else {
return Err(Status::not_found(format!(
"person not found: team_id={}, person_id={}",
key.team_id, key.person_id
@@ -235,7 +234,7 @@ impl PersonHogLeaderService {
};
let started = Instant::now();
- let result = load_person_from_pg(pool, key).await;
+ let result = load_person_from_pg(&fallback.pool, &fallback.table, key).await;
histogram!("personhog_leader_person_load_duration_ms", "source" => "pg")
.record(started.elapsed().as_secs_f64() * 1000.0);
match result {
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index 23c366649759..f2ccb3e6fd66 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -28,6 +28,7 @@ use personhog_common::partitioning::partition_for_person;
use personhog_leader::cache::{CachedPerson, DirtyIndex, PartitionedCache, PersonCacheKey};
use personhog_leader::coordination::LeaderHandoffHandler;
use personhog_leader::inflight::InflightTracker;
+use personhog_leader::pg::PgFallback;
use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::{PersonHogLeaderService, PropertySizeLimits};
use personhog_leader::warnings::WarningsProducer;
@@ -508,7 +509,10 @@ pub async fn start_leader_with_pg_fallback(
Arc::clone(&cache),
kafka_producer.clone(),
CHANGELOG_TOPIC.to_string(),
- Some(pool),
+ Some(PgFallback {
+ pool,
+ table: "posthog_person".to_string(),
+ }),
Arc::new(DashMap::new()),
Arc::new(InflightTracker::new()),
NUM_PARTITIONS,
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index fb1080848ec4..57e9d389f2c7 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -1245,7 +1245,7 @@ async fn pg_fallback_reads_numerics_the_leaders_parser_rejects() {
team_id: team_id as i64,
person_id: row.0,
};
- let person = personhog_leader::pg::load_person_from_pg(&pool, &key)
+ let person = personhog_leader::pg::load_person_from_pg(&pool, "posthog_person", &key)
.await
.expect("load must not fail")
.expect("person exists");
diff --git a/rust/personhog-test-harness/Cargo.toml b/rust/personhog-test-harness/Cargo.toml
index 47bd91692495..b268d874a0fb 100644
--- a/rust/personhog-test-harness/Cargo.toml
+++ b/rust/personhog-test-harness/Cargo.toml
@@ -6,12 +6,15 @@ publish = false
[dependencies]
personhog-proto = { path = "../personhog-proto" }
+common-metrics = { path = "../common/metrics" }
personhog-coordination = { path = "../personhog-coordination" }
assignment-coordination = { path = "../common/assignment-coordination" }
anyhow = { workspace = true }
+axum = { workspace = true }
+metrics = { workspace = true }
chrono = { workspace = true }
-clap = { workspace = true, features = ["derive"] }
+clap = { workspace = true, features = ["derive", "env"] }
futures = { workspace = true }
hdrhistogram = { workspace = true }
humantime = { workspace = true }
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index 982720d52232..8a51e0fec2db 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -31,6 +31,12 @@ pub enum Command {
Consistency(ConsistencyArgs),
/// Full e2e gate: stack up, seed, traffic, quiesce, verify, cleanup.
Gate(Box<GateArgs>),
+ /// Continuous synthetic traffic with epoch-based verification, for the
+ /// dev deployment. A startup sentinel round-trip refuses to send
+ /// traffic anywhere the router does not serve the database this harness
+ /// seeds, and every database operation is confined to the configured
+ /// validation table.
+ Traffic(TrafficArgs),
}
#[derive(Args, Clone)]
@@ -44,6 +50,11 @@ pub struct SeedArgs {
#[arg(long, default_value = DEFAULT_PERSONS_DB_URL)]
pub persons_db_url: String,
+
+ /// Table to seed into — the same table the stack's writer targets
+ /// and its leader's fallback reads.
+ #[arg(long, default_value = "personhog_person_tmp")]
+ pub pg_target_table: String,
}
#[derive(Args, Clone)]
@@ -53,6 +64,10 @@ pub struct CleanupArgs {
#[arg(long, default_value = DEFAULT_PERSONS_DB_URL)]
pub persons_db_url: String,
+
+ /// Table to delete the team's rows from.
+ #[arg(long, default_value = "personhog_person_tmp")]
+ pub pg_target_table: String,
}
#[derive(Args, Clone)]
@@ -155,11 +170,11 @@ pub struct GateArgs {
#[arg(long, default_value = DEFAULT_PERSONS_DB_URL)]
pub persons_db_url: String,
- /// The table the writer under test upserts into. Must match the
- /// writer's PG_TARGET_TABLE: spawned stacks run in posthog_person mode;
- /// the dev stack's writer defaults to personhog_person_tmp, so pass
- /// that with --external-router-url against dev.
- #[arg(long, default_value = "posthog_person")]
+ /// The table every stack component and harness operation uses:
+ /// spawned stacks set it as the writer's PG_TARGET_TABLE and the
+ /// leader's FALLBACK_TABLE, and the harness seeds, verifies, and
+ /// cleans up in it. posthog_person is deliberately never touched.
+ #[arg(long, default_value = "personhog_person_tmp")]
pub pg_target_table: String,
#[arg(long, default_value = "localhost:9092")]
@@ -272,3 +287,75 @@ pub struct GateArgs {
#[arg(long)]
pub bin_dir: Option<PathBuf>,
}
+
+#[derive(Args, Clone)]
+pub struct TrafficArgs {
+ /// Router serving the personhog stack under continuous test.
+ #[arg(long, env = "TRAFFIC_ROUTER_URL")]
+ pub router_url: String,
+
+ /// Master toggle. When false the process starts fully (guard, metrics,
+ /// liveness) but idles instead of driving traffic — so a deployed-but-
+ /// disabled harness is observably "off on purpose" rather than absent.
+ /// The chart ships false and flips it to start traffic; the CLI
+ /// defaults to true because invoking `traffic` means traffic.
+ #[arg(long, env = "TRAFFIC_ENABLED", default_value_t = true, action = clap::ArgAction::Set)]
+ pub enabled: bool,
+
+ /// Reserved harness team. The traffic mode owns every row on it.
+ #[arg(long, env = "TRAFFIC_TEAM_ID", default_value_t = 900_101)]
+ pub team_id: i64,
+
+ /// Dedicated team for the hostile lane, kept out of the exactness
+ /// journal (its outcomes are observed as metrics, not verified).
+ #[arg(long, env = "TRAFFIC_HOSTILE_TEAM_ID", default_value_t = 900_102)]
+ pub hostile_team_id: i64,
+
+ #[arg(long, env = "TRAFFIC_PERSONS_DB_URL", default_value = DEFAULT_PERSONS_DB_URL)]
+ pub persons_db_url: String,
+
+ /// The table the writer under test upserts into (the dev writer's
+ /// PG_TARGET_TABLE).
+ #[arg(
+ long,
+ env = "TRAFFIC_PG_TARGET_TABLE",
+ default_value = "personhog_person_tmp"
+ )]
+ pub pg_target_table: String,
+
+ /// Persons seeded per epoch. The pool rotates every epoch so journal
+ /// keys never grow a document toward the admission size ceiling.
+ #[arg(long, env = "TRAFFIC_POOL_SIZE", default_value_t = 200)]
+ pub pool_size: u32,
+
+ /// Verification epoch length: traffic runs, then the epoch's acked
+ /// writes are verified against strong reads and Postgres, then the
+ /// person pool rotates.
+ #[arg(long, env = "TRAFFIC_EPOCH", default_value = "5m", value_parser = humantime::parse_duration)]
+ pub epoch: Duration,
+
+ /// Each epoch draws its target write rate uniformly from this range
+ /// (writes/second), which also exercises the autoscaler.
+ #[arg(long, env = "TRAFFIC_RATE_MIN", default_value_t = 50.0)]
+ pub rate_min: f64,
+
+ #[arg(long, env = "TRAFFIC_RATE_MAX", default_value_t = 500.0)]
+ pub rate_max: f64,
+
+ /// Concurrent write workers sharing the epoch's target rate.
+ #[arg(long, env = "TRAFFIC_CONCURRENCY", default_value_t = 20)]
+ pub concurrency: usize,
+
+ /// Read-your-write probers running alongside the writers.
+ #[arg(long, env = "TRAFFIC_PROBERS", default_value_t = 2)]
+ pub probers: usize,
+
+ /// Hostile-lane writes per second (NUL and oversized payloads against
+ /// the hostile team). 0 disables.
+ #[arg(long, env = "TRAFFIC_HOSTILE_RATE", default_value_t = 1.0)]
+ pub hostile_rate: f64,
+
+ /// Prometheus metrics + liveness port.
+ #[arg(long, env = "TRAFFIC_METRICS_PORT", default_value_t = 9110)]
+ pub metrics_port: u16,
+}
diff --git a/rust/personhog-test-harness/src/main.rs b/rust/personhog-test-harness/src/main.rs
index 9d4c3890abe4..ec528f692823 100644
--- a/rust/personhog-test-harness/src/main.rs
+++ b/rust/personhog-test-harness/src/main.rs
@@ -10,6 +10,8 @@ mod seed;
mod stack;
mod state;
mod stats;
+mod traffic_metrics;
+mod verify;
use cli::{Cli, Command};
@@ -29,5 +31,6 @@ async fn main() -> Result<()> {
Command::Blast(args) => scenarios::blast::run(args).await,
Command::Consistency(args) => scenarios::consistency::run(args).await,
Command::Gate(args) => scenarios::gate::run(*args).await,
+ Command::Traffic(args) => scenarios::traffic::run(args).await,
}
}
diff --git a/rust/personhog-test-harness/src/scenarios/blast.rs b/rust/personhog-test-harness/src/scenarios/blast.rs
index d42a96c4dc49..20b5f59fe7d7 100644
--- a/rust/personhog-test-harness/src/scenarios/blast.rs
+++ b/rust/personhog-test-harness/src/scenarios/blast.rs
@@ -1,10 +1,15 @@
use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::{bail, Result};
+use metrics::{counter, histogram};
use personhog_proto::personhog::types::v1::ConsistencyLevel;
use rand::{Rng, SeedableRng};
+use serde_json::{json, Value};
+use tokio::time::{interval, sleep, MissedTickBehavior};
+use uuid::Uuid;
use crate::cli::BlastArgs;
use crate::client::HarnessClient;
@@ -31,9 +36,11 @@ pub async fn run(args: BlastArgs) -> Result<()> {
person_ids.clone(),
args.duration,
args.concurrency,
+ None,
&args.property_prefix,
&collector,
&state,
+ Arc::new(AtomicBool::new(false)),
)
.await?;
@@ -59,6 +66,14 @@ pub async fn run(args: BlastArgs) -> Result<()> {
/// Drive concurrent property updates against random targets until the
/// duration elapses, journaling every acked write into `state`.
+///
+/// With `rate_per_sec` set, the workers collectively pace to that target
+/// (each worker ticks at rate/concurrency); unset, they run flat out.
+/// `stop` ends the run early — shutdown must not wait out the full
+/// duration, or Kubernetes kills the process before the caller can verify
+/// what was acked. Metric emission is a no-op unless an exporter is
+/// installed (only the traffic mode installs one), so instrumenting here
+/// is free for the bounded modes.
#[allow(clippy::too_many_arguments)]
pub async fn run_traffic(
client: &HarnessClient,
@@ -66,11 +81,14 @@ pub async fn run_traffic(
person_ids: Arc<Vec<i64>>,
duration: Duration,
concurrency: usize,
+ rate_per_sec: Option<f64>,
property_prefix: &str,
collector: &Arc<StatsCollector>,
state: &PersonState,
+ stop: Arc<AtomicBool>,
) -> Result<()> {
let deadline = Instant::now() + duration;
+ let worker_tick = rate_per_sec.map(|rate| per_worker_tick(rate, concurrency));
let mut handles = Vec::new();
for worker_id in 0..concurrency {
@@ -79,26 +97,38 @@ pub async fn run_traffic(
let state = state.clone();
let person_ids = person_ids.clone();
let prefix = property_prefix.to_string();
+ let stop = stop.clone();
handles.push(tokio::spawn(async move {
let mut counter: u64 = 0;
let mut rng = rand::rngs::StdRng::from_entropy();
-
- while Instant::now() < deadline {
+ let mut pacer = worker_tick.map(|tick| {
+ let mut ticker = interval(tick);
+ ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
+ ticker
+ });
+
+ while Instant::now() < deadline && !stop.load(Ordering::Relaxed) {
+ if let Some(pacer) = pacer.as_mut() {
+ pacer.tick().await;
+ }
let person_id = person_ids[rng.gen_range(0..person_ids.len())];
counter += 1;
let key = format!("{prefix}{worker_id}_{counter}");
- let value = uuid::Uuid::new_v4().to_string();
- let props = serde_json::json!({ &key: &value });
+ let value = Uuid::new_v4().to_string();
+ let props = json!({ &key: &value });
let start = Instant::now();
match client
- .update_properties(team_id, person_id, props, serde_json::json!({}), vec![])
+ .update_properties(team_id, person_id, props, json!({}), vec![])
.await
{
Ok(resp) => {
collector.writes.record_success(start.elapsed());
+ counter!("personhog_traffic_writes_total", "outcome" => "ok").increment(1);
+ histogram!("personhog_traffic_write_seconds")
+ .record(start.elapsed().as_secs_f64());
let mut written = HashMap::new();
written.insert(key, serde_json::Value::String(value));
match resp.person {
@@ -110,6 +140,8 @@ pub async fn run_traffic(
}
Err(e) => {
collector.writes.record_failure();
+ counter!("personhog_traffic_writes_total", "outcome" => "failed")
+ .increment(1);
// `{:#}` prints the full anyhow chain — the outer
// context alone hides the gRPC status underneath.
tracing::warn!(person_id, error = format!("{e:#}"), "write failed");
@@ -125,6 +157,14 @@ pub async fn run_traffic(
Ok(())
}
+/// The tick interval each of `concurrency` workers needs so their
+/// combined rate hits `rate_per_sec`. Rates too low to represent tick at
+/// most once per hour rather than dividing by zero.
+pub fn per_worker_tick(rate_per_sec: f64, concurrency: usize) -> Duration {
+ let per_worker = (rate_per_sec / concurrency.max(1) as f64).max(1.0 / 3600.0);
+ Duration::from_secs_f64(1.0 / per_worker)
+}
+
/// Read every journaled person back with STRONG consistency and check that
/// all acked writes are visible. A person that cannot be read is a
/// violation, not a skip: NotFound for a person with acked writes means the
@@ -145,7 +185,7 @@ pub async fn verify_strong(
.get_person(team_id, person_id, ConsistencyLevel::Strong)
.await;
if result.is_err() {
- tokio::time::sleep(Duration::from_secs(2)).await;
+ sleep(Duration::from_secs(2)).await;
result = client
.get_person(team_id, person_id, ConsistencyLevel::Strong)
.await;
@@ -154,8 +194,8 @@ pub async fn verify_strong(
match result {
Ok(Some(person)) => {
collector.reads.record_success(start.elapsed());
- let props: serde_json::Value = if person.properties.is_empty() {
- serde_json::json!({})
+ let props: Value = if person.properties.is_empty() {
+ json!({})
} else {
serde_json::from_slice(&person.properties)?
};
@@ -167,8 +207,8 @@ pub async fn verify_strong(
all_violations.push(ConsistencyViolation {
person_id,
key: "__missing_person".to_string(),
- expected: serde_json::json!("person with acked writes exists"),
- actual: serde_json::Value::Null,
+ expected: json!("person with acked writes exists"),
+ actual: Value::Null,
});
}
Err(e) => {
@@ -176,8 +216,8 @@ pub async fn verify_strong(
all_violations.push(ConsistencyViolation {
person_id,
key: "__strong_read_failed".to_string(),
- expected: serde_json::json!("readable"),
- actual: serde_json::json!(e.to_string()),
+ expected: json!("readable"),
+ actual: json!(e.to_string()),
});
}
}
@@ -185,3 +225,19 @@ pub async fn verify_strong(
Ok(all_violations)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn per_worker_tick_divides_the_rate_across_workers() {
+ // 100 wps over 20 workers: each ticks every 200ms.
+ assert_eq!(per_worker_tick(100.0, 20), Duration::from_millis(200));
+ // One worker carries the whole rate.
+ assert_eq!(per_worker_tick(4.0, 1), Duration::from_millis(250));
+ // Degenerate inputs stay finite instead of dividing by zero.
+ assert!(per_worker_tick(0.0, 10) <= Duration::from_secs(3600));
+ assert!(per_worker_tick(10.0, 0) <= Duration::from_secs(1));
+ }
+}
diff --git a/rust/personhog-test-harness/src/scenarios/consistency.rs b/rust/personhog-test-harness/src/scenarios/consistency.rs
index 1cf9ea9fbee7..3210172ead98 100644
--- a/rust/personhog-test-harness/src/scenarios/consistency.rs
+++ b/rust/personhog-test-harness/src/scenarios/consistency.rs
@@ -1,5 +1,5 @@
use std::collections::HashMap;
-use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -173,6 +173,7 @@ pub async fn run(args: ConsistencyArgs) -> Result<()> {
/// violations. A failed read is likewise not a recency violation — reads
/// legitimately fail while a killed owner's partitions are in limbo, and
/// end-of-run verification owns readability.
+#[allow(clippy::too_many_arguments)]
pub async fn run_probers(
client: &HarnessClient,
team_id: i64,
@@ -181,6 +182,7 @@ pub async fn run_probers(
duration: Duration,
collector: &Arc<StatsCollector>,
state: &PersonState,
+ stop: Arc<AtomicBool>,
) -> Result<Vec<ConsistencyViolation>> {
let deadline = Instant::now() + duration;
@@ -190,12 +192,13 @@ pub async fn run_probers(
let collector = collector.clone();
let state = state.clone();
let person_ids = person_ids.clone();
+ let stop = stop.clone();
handles.push(tokio::spawn(async move {
let mut violations = Vec::new();
let mut iteration: usize = 0;
- while Instant::now() < deadline {
+ while Instant::now() < deadline && !stop.load(Ordering::Relaxed) {
let person_id = person_ids[(worker_id + iteration) % person_ids.len()];
iteration += 1;
let marker = uuid::Uuid::new_v4().to_string();
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index a26752580438..503adfa2ef5c 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -1,25 +1,21 @@
-use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
+use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::{bail, Context, Result};
use sqlx::postgres::PgPool;
-use sqlx::Row;
use crate::cli::GateArgs;
use crate::client::HarnessClient;
-use crate::report::{print_report, ConsistencyViolation};
+use crate::report::print_report;
use crate::scenarios::{blast, consistency};
use crate::seed;
use crate::stack::{Stack, StackConfig};
-use crate::state::{verify_properties, ExpectedPerson, PersonState};
+use crate::state::PersonState;
use crate::stats::StatsCollector;
-
-/// How long to wait for the writer to drain acked writes into Postgres
-/// before declaring them lost.
-const QUIESCE_DEADLINE: Duration = Duration::from_secs(60);
+use crate::verify::verify_postgres;
/// A chaos disruption scheduled relative to the start of the traffic phase.
enum ChaosEvent {
@@ -181,8 +177,10 @@ pub async fn run(args: GateArgs) -> Result<()> {
// A crashed prior run may have left rows behind; the team id belongs to
// the harness, so start from a clean slate.
- seed::cleanup_team(&pool, args.team_id).await?;
- let person_ids = Arc::new(seed::seed_persons(&pool, args.team_id, args.persons).await?);
+ seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;
+ let person_ids = Arc::new(
+ seed::seed_persons(&pool, &args.pg_target_table, args.team_id, args.persons).await?,
+ );
println!(
"Seeded {} persons for team {}",
person_ids.len(),
@@ -209,9 +207,11 @@ pub async fn run(args: GateArgs) -> Result<()> {
person_ids,
duration,
concurrency,
+ None,
"harness_gate_",
&collector,
&state,
+ Arc::new(AtomicBool::new(false)),
)
.await
})
@@ -234,6 +234,7 @@ pub async fn run(args: GateArgs) -> Result<()> {
duration,
&collector,
&state,
+ Arc::new(AtomicBool::new(false)),
)
.await
})
@@ -338,10 +339,7 @@ pub async fn run(args: GateArgs) -> Result<()> {
);
if !args.keep_data {
- let persons = seed::cleanup_team(&pool, args.team_id).await?;
- if args.pg_target_table != "posthog_person" {
- seed::cleanup_target_table(&pool, &args.pg_target_table, args.team_id).await?;
- }
+ let persons = seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;
println!("Cleaned up {persons} persons");
}
@@ -372,97 +370,6 @@ pub async fn run(args: GateArgs) -> Result<()> {
Ok(())
}
-/// Poll Postgres until every journaled person row contains all acked
-/// property writes at the acked version, or the quiesce deadline passes.
-/// Returns the outstanding violations (empty = converged).
-async fn verify_postgres(
- pool: &PgPool,
- table: &str,
- team_id: i64,
- journal: &HashMap<i64, ExpectedPerson>,
-) -> Result<Vec<ConsistencyViolation>> {
- let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
- let person_ids: Vec<i64> = journal.keys().copied().collect();
- if person_ids.is_empty() {
- return Ok(Vec::new());
- }
-
- let query = format!(
- "SELECT id, properties::text AS properties, version \
- FROM {table} WHERE team_id = $1 AND id = ANY($2)"
- );
- let deadline = Instant::now() + QUIESCE_DEADLINE;
- loop {
- let rows = sqlx::query(&query)
- .bind(team)
- .bind(&person_ids)
- .fetch_all(pool)
- .await
- .context("reading persons from Postgres")?;
-
- let mut by_id: HashMap<i64, (serde_json::Value, i64)> = HashMap::new();
- for row in rows {
- let id: i64 = row.get("id");
- let properties: Option<String> = row.get("properties");
- let version: Option<i64> = row.get("version");
- let props = properties
- .as_deref()
- .map(serde_json::from_str)
- .transpose()
- .context("parsing properties JSON")?
- .unwrap_or_else(|| serde_json::json!({}));
- by_id.insert(id, (props, version.unwrap_or(0)));
- }
-
- let mut violations = Vec::new();
- for (person_id, expected) in journal {
- match by_id.get(person_id) {
- Some((props, version)) => {
- violations.extend(verify_properties(
- *person_id,
- &expected.written_properties,
- props,
- ));
- // The highest acked version is a floor, not an exact
- // target: a write that produced its record but lost the
- // response (a drain, a client timeout) is unacked yet
- // still applied, legitimately leaving the row above the
- // floor. Below it, an acked write never reached
- // Postgres.
- if *version < expected.last_version {
- violations.push(ConsistencyViolation {
- person_id: *person_id,
- key: "__version".to_string(),
- expected: serde_json::json!(format!(">= {}", expected.last_version)),
- actual: serde_json::json!(version),
- });
- }
- }
- None => {
- violations.push(ConsistencyViolation {
- person_id: *person_id,
- key: "__row".to_string(),
- expected: serde_json::json!("present"),
- actual: serde_json::Value::Null,
- });
- }
- }
- }
-
- if violations.is_empty() {
- return Ok(violations);
- }
- if Instant::now() > deadline {
- tracing::error!(
- outstanding = violations.len(),
- "Postgres did not converge within {QUIESCE_DEADLINE:?}"
- );
- return Ok(violations);
- }
- tokio::time::sleep(Duration::from_millis(500)).await;
- }
-}
-
#[cfg(test)]
mod tests {
use clap::Parser;
diff --git a/rust/personhog-test-harness/src/scenarios/mod.rs b/rust/personhog-test-harness/src/scenarios/mod.rs
index cf036e04a2e0..35192c3ce004 100644
--- a/rust/personhog-test-harness/src/scenarios/mod.rs
+++ b/rust/personhog-test-harness/src/scenarios/mod.rs
@@ -2,3 +2,4 @@ pub mod blast;
pub mod consistency;
pub mod gate;
pub mod seed_cmd;
+pub mod traffic;
diff --git a/rust/personhog-test-harness/src/scenarios/seed_cmd.rs b/rust/personhog-test-harness/src/scenarios/seed_cmd.rs
index 32a8c9e9aed7..b7c3b968eb34 100644
--- a/rust/personhog-test-harness/src/scenarios/seed_cmd.rs
+++ b/rust/personhog-test-harness/src/scenarios/seed_cmd.rs
@@ -9,7 +9,7 @@ pub async fn run(args: SeedArgs) -> Result<()> {
.await
.context("connecting to persons DB")?;
- let ids = seed::seed_persons(&pool, args.team_id, args.count).await?;
+ let ids = seed::seed_persons(&pool, &args.pg_target_table, args.team_id, args.count).await?;
println!("Seeded {} persons for team {}", ids.len(), args.team_id);
println!();
@@ -26,7 +26,7 @@ pub async fn run_cleanup(args: CleanupArgs) -> Result<()> {
.await
.context("connecting to persons DB")?;
- let persons = seed::cleanup_team(&pool, args.team_id).await?;
+ let persons = seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;
println!("Deleted {persons} persons for team {}", args.team_id);
Ok(())
}
diff --git a/rust/personhog-test-harness/src/scenarios/traffic.rs b/rust/personhog-test-harness/src/scenarios/traffic.rs
new file mode 100644
index 000000000000..092510d07682
--- /dev/null
+++ b/rust/personhog-test-harness/src/scenarios/traffic.rs
@@ -0,0 +1,463 @@
+//! Continuous synthetic traffic for the dev deployment.
+//!
+//! Runs forever in verification epochs: seed a fresh person pool, drive
+//! paced blast traffic and read-your-write probers at an epoch-specific
+//! rate drawn from a configured range, then close the epoch — verify every
+//! acked write against strong reads and Postgres, export violations as
+//! metrics, rotate the pool, repeat. Pool rotation is load-bearing: blast
+//! journals each write under a unique key, so an unrotated person's
+//! document would grow into the admission size ceiling and legitimate
+//! trims would read as false violations.
+//!
+//! Rate variance doubles as the autoscaler driver in dev; violations
+//! surface exclusively through metrics and logs (a Deployment restart loop
+//! can't fix a consistency bug, so the process does not exit on them). A
+//! hostile lane sends NUL-bearing and oversized payloads against a
+//! dedicated team, observed as outcome metrics rather than verified — its
+//! expected behavior legitimately differs across stack versions as
+//! admission hardening lands.
+//!
+//! Every database operation — seeding, verification, cleanup — touches
+//! only the configured target table (the writer's validation table), never
+//! posthog_person; a startup sentinel round-trip proves the router serves
+//! that same table before any traffic flows. Shutdown cuts the in-flight
+//! epoch's load short and runs the normal close-out (verify what was
+//! acked, record, clean up) inside the termination grace window.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+use anyhow::{bail, Context, Result};
+use metrics::{counter, gauge};
+use personhog_proto::personhog::types::v1::ConsistencyLevel;
+use rand::{Rng, SeedableRng};
+use serde_json::{json, Value};
+use sqlx::postgres::PgPool;
+#[cfg(unix)]
+use tokio::signal::unix::{signal, SignalKind};
+use tokio::time::{interval, MissedTickBehavior};
+use uuid::Uuid;
+
+use crate::cli::TrafficArgs;
+use crate::client::HarnessClient;
+use crate::scenarios::{blast, consistency};
+use crate::seed;
+use crate::state::PersonState;
+use crate::stats::StatsCollector;
+use crate::traffic_metrics;
+use crate::verify::verify_postgres;
+
+/// Reject configurations that cannot produce the advertised coverage.
+fn validate_args(args: &TrafficArgs) -> Result<()> {
+ if args.rate_min <= 0.0 || args.rate_max < args.rate_min {
+ bail!(
+ "invalid rate range: {}..{} (need 0 < min <= max)",
+ args.rate_min,
+ args.rate_max
+ );
+ }
+ if args.pool_size == 0 || args.concurrency == 0 || args.probers == 0 {
+ // Zero workers or probers would produce vacuously green epochs —
+ // worse than a crash for a verification bed — and an empty pool
+ // panics at person selection.
+ bail!(
+ "pool_size ({}), concurrency ({}), and probers ({}) must all be nonzero",
+ args.pool_size,
+ args.concurrency,
+ args.probers
+ );
+ }
+ seed::validate_table_name(&args.pg_target_table)
+}
+
+pub async fn run(args: TrafficArgs) -> Result<()> {
+ validate_args(&args)?;
+
+ traffic_metrics::spawn_server(args.metrics_port)?;
+ gauge!("personhog_traffic_enabled").set(if args.enabled { 1.0 } else { 0.0 });
+ if !args.enabled {
+ // Deployed but switched off: stay alive and observable so the
+ // absence alarm keeps meaning "dead", never "disabled".
+ tracing::info!("traffic disabled by TRAFFIC_ENABLED=false; idling");
+ shutdown_signal().await;
+ return Ok(());
+ }
+ let client = HarnessClient::connect(&args.router_url).await?;
+ let pool = PgPool::connect(&args.persons_db_url)
+ .await
+ .context("connecting to persons DB")?;
+
+ // Refuse to send traffic anywhere the router provably doesn't serve
+ // this database. On failure the process exits and the Deployment's
+ // restart loop retries — which also rides out startup races where the
+ // leader hasn't claimed partitions yet.
+ sentinel_round_trip(&client, &pool, &args.pg_target_table, args.team_id).await?;
+
+ // A crashed prior run leaves rows behind (including the sentinel row
+ // just written); both teams belong to the harness, so boot from a
+ // clean slate.
+ for team in [args.team_id, args.hostile_team_id] {
+ seed::cleanup_team(&pool, &args.pg_target_table, team).await?;
+ }
+
+ // Hostile targets live for the process lifetime: their documents stay
+ // small (fixed keys, no journal growth) and their outcomes are only
+ // observed, never verified.
+ let hostile_ids = if args.hostile_rate > 0.0 {
+ Arc::new(seed::seed_persons(&pool, &args.pg_target_table, args.hostile_team_id, 4).await?)
+ } else {
+ Arc::new(Vec::new())
+ };
+
+ // A signal task flips the flag; the load tasks observe it and end
+ // early, and the epoch close-out below still verifies and cleans up
+ // whatever was acked before the process exits.
+ let shutdown = Arc::new(AtomicBool::new(false));
+ {
+ let shutdown = shutdown.clone();
+ tokio::spawn(async move {
+ shutdown_signal().await;
+ tracing::info!(
+ "shutdown signal received; cutting the epoch short to verify and clean up"
+ );
+ shutdown.store(true, Ordering::SeqCst);
+ });
+ }
+
+ let mut rng = rand::rngs::StdRng::from_entropy();
+ let mut epoch: u64 = 0;
+ loop {
+ epoch += 1;
+ let rate = rng.gen_range(args.rate_min..=args.rate_max);
+ counter!("personhog_traffic_epochs_total").increment(1);
+ gauge!("personhog_traffic_epoch_target_rps").set(rate);
+ tracing::info!(epoch, rate = format!("{rate:.0}"), "epoch starting");
+
+ let person_ids = Arc::new(
+ seed::seed_persons(&pool, &args.pg_target_table, args.team_id, args.pool_size).await?,
+ );
+ let collector = Arc::new(StatsCollector::new());
+ let state = PersonState::new();
+
+ let traffic = {
+ let client = client.clone();
+ let person_ids = person_ids.clone();
+ let collector = collector.clone();
+ let state = state.clone();
+ let (team_id, duration, concurrency) = (args.team_id, args.epoch, args.concurrency);
+ let prefix = format!("traffic_e{epoch}_");
+ let stop = shutdown.clone();
+ tokio::spawn(async move {
+ blast::run_traffic(
+ &client,
+ team_id,
+ person_ids,
+ duration,
+ concurrency,
+ Some(rate),
+ &prefix,
+ &collector,
+ &state,
+ stop,
+ )
+ .await
+ })
+ };
+ let probers = {
+ let client = client.clone();
+ let person_ids = person_ids.clone();
+ let collector = collector.clone();
+ let state = state.clone();
+ let (team_id, duration, prober_count) = (args.team_id, args.epoch, args.probers);
+ let stop = shutdown.clone();
+ tokio::spawn(async move {
+ consistency::run_probers(
+ &client,
+ team_id,
+ person_ids,
+ prober_count,
+ duration,
+ &collector,
+ &state,
+ stop,
+ )
+ .await
+ })
+ };
+ let hostile = {
+ let client = client.clone();
+ let hostile_ids = hostile_ids.clone();
+ let (team_id, duration, rate) = (args.hostile_team_id, args.epoch, args.hostile_rate);
+ let stop = shutdown.clone();
+ tokio::spawn(async move {
+ run_hostile(&client, team_id, hostile_ids, duration, rate, stop).await
+ })
+ };
+
+ traffic.await.context("traffic task panicked")??;
+ let prober_violations = probers.await.context("prober task panicked")??;
+ hostile.await.context("hostile task panicked")?;
+
+ // Close the epoch: everything acked in it must now be visible.
+ let mut violations = prober_violations;
+ violations.extend(state.take_anomalies().await);
+ violations.extend(blast::verify_strong(&client, &collector, &state, args.team_id).await?);
+ let journal = state.snapshot().await;
+ violations
+ .extend(verify_postgres(&pool, &args.pg_target_table, args.team_id, &journal).await?);
+ traffic_metrics::record_violations(epoch, &violations);
+
+ let writes = collector.writes.snapshot();
+ gauge!("personhog_traffic_last_epoch_completed_timestamp_seconds").set(
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs_f64(),
+ );
+ tracing::info!(
+ epoch,
+ writes = writes.successes,
+ failed = writes.failures,
+ violations = violations.len(),
+ "epoch closed"
+ );
+
+ // Rotate the pool: delete this epoch's persons so the next epoch
+ // starts from fresh documents.
+ seed::cleanup_team(&pool, &args.pg_target_table, args.team_id).await?;
+
+ if shutdown.load(Ordering::SeqCst) {
+ tracing::info!("cleaning up and exiting");
+ for team in [args.team_id, args.hostile_team_id] {
+ seed::cleanup_team(&pool, &args.pg_target_table, team).await?;
+ }
+ return Ok(());
+ }
+ }
+}
+
+/// The hostile lane: paced writes carrying payloads a correct stack must
+/// handle without corruption — NUL bytes (jsonb-hostile) and oversized
+/// values (admission/trim pressure). Outcomes are counted, not verified:
+/// what a given stack version does with them legitimately changes as
+/// admission hardening lands, so dashboards judge, the harness observes.
+async fn run_hostile(
+ client: &HarnessClient,
+ team_id: i64,
+ person_ids: Arc<Vec<i64>>,
+ duration: Duration,
+ rate_per_sec: f64,
+ stop: Arc<AtomicBool>,
+) {
+ if person_ids.is_empty() || rate_per_sec <= 0.0 {
+ return;
+ }
+ let deadline = Instant::now() + duration;
+ let mut ticker = interval(Duration::from_secs_f64(1.0 / rate_per_sec));
+ ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
+ let mut rng = rand::rngs::StdRng::from_entropy();
+ let mut counter: u64 = 0;
+
+ while Instant::now() < deadline && !stop.load(Ordering::Relaxed) {
+ ticker.tick().await;
+ counter += 1;
+ let person_id = person_ids[rng.gen_range(0..person_ids.len())];
+ let (payload_kind, props) = hostile_payload(counter);
+
+ let outcome = match client
+ .update_properties(team_id, person_id, props, json!({}), vec![])
+ .await
+ {
+ Ok(_) => "acked",
+ Err(e) => {
+ let rendered = format!("{e:#}");
+ if rendered.contains("size limit") || rendered.contains("InvalidArgument") {
+ "rejected"
+ } else {
+ "error"
+ }
+ }
+ };
+ counter!(
+ "personhog_traffic_hostile_total",
+ "payload" => payload_kind,
+ "outcome" => outcome
+ )
+ .increment(1);
+ }
+}
+
+/// Rotates through the hostile payload shapes. The `unset` cycle keeps the
+/// hostile documents from growing without bound across epochs.
+fn hostile_payload(counter: u64) -> (&'static str, Value) {
+ match counter % 4 {
+ 0 => (
+ "nul",
+ json!({ "hostile_nul": format!("x\u{0000}y_{counter}") }),
+ ),
+ 1 => (
+ "oversized_trimmable",
+ json!({ "hostile_blob": "x".repeat(700_000) }),
+ ),
+ 2 => (
+ "oversized_protected",
+ json!({ "email": "x".repeat(700_000) }),
+ ),
+ _ => ("reset", json!({ "hostile_nul": "clean" })),
+ }
+}
+
+/// Prove the router serves the same database this harness seeds and
+/// verifies before any traffic flows: insert one person whose properties
+/// carry a freshly minted UUID, strong-read it back through the router,
+/// and require an exact match. The router path terminates in the leader's
+/// PG fallback, so a router pointed at any other environment cannot
+/// return a value that was generated here moments ago. The row is
+/// removed by the boot cleanup that follows.
+async fn sentinel_round_trip(
+ client: &HarnessClient,
+ pool: &PgPool,
+ table: &str,
+ team_id: i64,
+) -> Result<()> {
+ let marker = Uuid::new_v4().to_string();
+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+ let person_id: i64 = sqlx::query_scalar(&format!(
+ r#"
+ INSERT INTO {table} (
+ team_id, uuid, properties, properties_last_updated_at,
+ properties_last_operation, created_at, version, is_identified
+ )
+ VALUES ($1, gen_random_uuid(), $2::jsonb, '{{}}'::jsonb, '{{}}'::jsonb, now(), 0, false)
+ RETURNING id
+ "#
+ ))
+ .bind(team)
+ .bind(json!({ "traffic_sentinel": &marker }).to_string())
+ .fetch_one(pool)
+ .await
+ .context("seeding the sentinel person")?;
+
+ let person = client
+ .get_person(team_id, person_id, ConsistencyLevel::Strong)
+ .await
+ .context("sentinel strong read through the router failed")?
+ .with_context(|| {
+ format!(
+ "sentinel person (team {team_id}, id {person_id}) not found through the \
+ router — the router does not serve the database this harness targets"
+ )
+ })?;
+ let props: Value = serde_json::from_slice(&person.properties).unwrap_or(Value::Null);
+ if props["traffic_sentinel"] != json!(marker) {
+ bail!(
+ "sentinel mismatch: the router returned a person without the freshly minted \
+ marker (team {team_id}, id {person_id}) — the router does not serve the \
+ database this harness targets"
+ );
+ }
+ tracing::info!("sentinel round-trip verified: router and database agree");
+ Ok(())
+}
+
+/// Resolves when SIGTERM (Kubernetes) or ctrl-c arrives.
+async fn shutdown_signal() {
+ let ctrl_c = tokio::signal::ctrl_c();
+ #[cfg(unix)]
+ {
+ let mut sigterm = signal(SignalKind::terminate()).expect("installing SIGTERM handler");
+ tokio::select! {
+ _ = ctrl_c => {}
+ _ = sigterm.recv() => {}
+ }
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = ctrl_c.await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn vacuous_or_panicking_configurations_are_rejected() {
+ let valid = TrafficArgs {
+ router_url: "http://localhost:1".to_string(),
+ enabled: true,
+ team_id: 900_101,
+ hostile_team_id: 900_102,
+ persons_db_url: "postgres://unused".to_string(),
+ pg_target_table: "personhog_person_tmp".to_string(),
+ pool_size: 200,
+ epoch: Duration::from_secs(300),
+ rate_min: 50.0,
+ rate_max: 500.0,
+ concurrency: 20,
+ probers: 2,
+ hostile_rate: 1.0,
+ metrics_port: 9110,
+ };
+ assert!(validate_args(&valid).is_ok());
+ // A disabled hostile lane is legal; zero traffic knobs are not.
+ assert!(validate_args(&TrafficArgs {
+ hostile_rate: 0.0,
+ ..valid.clone()
+ })
+ .is_ok());
+ for broken in [
+ TrafficArgs {
+ pool_size: 0,
+ ..valid.clone()
+ },
+ TrafficArgs {
+ concurrency: 0,
+ ..valid.clone()
+ },
+ TrafficArgs {
+ probers: 0,
+ ..valid.clone()
+ },
+ TrafficArgs {
+ rate_min: 0.0,
+ ..valid.clone()
+ },
+ TrafficArgs {
+ rate_max: 1.0,
+ ..valid.clone()
+ },
+ TrafficArgs {
+ pg_target_table: "bad; table".to_string(),
+ ..valid.clone()
+ },
+ ] {
+ assert!(validate_args(&broken).is_err());
+ }
+ }
+
+ #[test]
+ fn hostile_payloads_cycle_through_every_shape_and_reset() {
+ let kinds: Vec<&str> = (0..8).map(|i| hostile_payload(i).0).collect();
+ assert_eq!(
+ kinds,
+ [
+ "nul",
+ "oversized_trimmable",
+ "oversized_protected",
+ "reset",
+ "nul",
+ "oversized_trimmable",
+ "oversized_protected",
+ "reset"
+ ]
+ );
+ // The NUL payload really carries a NUL, and the reset payload
+ // replaces the same key so hostile documents stay bounded.
+ let (_, nul) = hostile_payload(0);
+ assert!(nul["hostile_nul"].as_str().unwrap().contains('\u{0000}'));
+ let (_, reset) = hostile_payload(3);
+ assert!(reset.get("hostile_nul").is_some());
+ }
+}
diff --git a/rust/personhog-test-harness/src/seed.rs b/rust/personhog-test-harness/src/seed.rs
index 3dd0f5f6df1e..a4eab6fcc7ea 100644
--- a/rust/personhog-test-harness/src/seed.rs
+++ b/rust/personhog-test-harness/src/seed.rs
@@ -1,9 +1,13 @@
use anyhow::{bail, Context, Result};
use sqlx::postgres::PgPool;
-/// Seed `count` persons for `team_id` directly in Postgres and return their
-/// ids. Ids come from the production sequence so they are unique against
-/// real data and spread across leader partitions exactly like organic ids.
+/// Seed `count` persons for `team_id` directly in `table` and return their
+/// ids, assigned by the table's own id default so they spread across
+/// leader partitions exactly like organic ids.
+///
+/// Every harness mode operates on one configured table (the writer's
+/// validation target by default) for seeding, verification, and cleanup
+/// alike — `posthog_person` is deliberately not reachable from here.
///
/// There is no team to seed: the persons database has no team table and no
/// foreign key on `team_id` — a team exists here only as an integer value
@@ -13,47 +17,41 @@ use sqlx::postgres::PgPool;
/// This writes SQL instead of calling CreatePerson because the create RPC's
/// future is still being settled; this function is the seam where the RPC
/// swaps in.
-pub async fn seed_persons(pool: &PgPool, team_id: i64, count: u32) -> Result<Vec<i64>> {
+pub async fn seed_persons(
+ pool: &PgPool,
+ table: &str,
+ team_id: i64,
+ count: u32,
+) -> Result<Vec<i64>> {
+ validate_table_name(table)?;
let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
- let ids: Vec<i64> =
- sqlx::query_scalar("SELECT nextval('posthog_person_id_seq') FROM generate_series(1, $1)")
- .bind(count as i32)
- .fetch_all(pool)
- .await
- .context("allocating person ids")?;
-
- let teams: Vec<i32> = vec![team; ids.len()];
- let uuids: Vec<String> = ids
- .iter()
- .map(|_| uuid::Uuid::new_v4().to_string())
- .collect();
-
- sqlx::query(
+ let ids: Vec<i64> = sqlx::query_scalar(&format!(
r#"
- INSERT INTO posthog_person (
- id, team_id, uuid, properties, properties_last_updated_at,
+ INSERT INTO {table} (
+ team_id, uuid, properties, properties_last_updated_at,
properties_last_operation, created_at, version, is_identified
)
- SELECT id, team_id, uuid::uuid, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, now(), 0, false
- FROM UNNEST($1::bigint[], $2::int[], $3::text[]) AS u(id, team_id, uuid)
- "#,
- )
- .bind(&ids)
- .bind(&teams)
- .bind(&uuids)
- .execute(pool)
+ SELECT $1, gen_random_uuid(), '{{}}'::jsonb, '{{}}'::jsonb, '{{}}'::jsonb, now(), 0, false
+ FROM generate_series(1, $2)
+ RETURNING id
+ "#
+ ))
+ .bind(team)
+ .bind(count as i32)
+ .fetch_all(pool)
.await
- .context("inserting seed persons")?;
+ .with_context(|| format!("seeding persons into {table}"))?;
Ok(ids)
}
-/// Delete a team's rows from a writer target table other than
-/// posthog_person (e.g. the dev stack's personhog_person_tmp validation
-/// table). The table name comes from the operator's CLI, but sanity-check
-/// it anyway since it is interpolated into SQL.
-pub async fn cleanup_target_table(pool: &PgPool, table: &str, team_id: i64) -> Result<u64> {
+/// Delete all of `team_id`'s rows from `table`. The harness owns its team
+/// ids outright, so a team-wide delete is the whole cleanup. Nothing
+/// writes distinct-id rows today (traffic is id-keyed), so nothing cleans
+/// them — that changes together when seeding grows a mechanism that
+/// writes them.
+pub async fn cleanup_team(pool: &PgPool, table: &str, team_id: i64) -> Result<u64> {
validate_table_name(table)?;
let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
let deleted = sqlx::query(&format!("DELETE FROM {table} WHERE team_id = $1"))
@@ -65,6 +63,8 @@ pub async fn cleanup_target_table(pool: &PgPool, table: &str, team_id: i64) -> R
Ok(deleted)
}
+/// The table name comes from the operator's CLI/env, but sanity-check it
+/// anyway since it is interpolated into SQL (identifiers cannot be bound).
pub fn validate_table_name(table: &str) -> Result<()> {
if table.is_empty() || !table.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
bail!("invalid table name: {table}");
@@ -72,23 +72,6 @@ pub fn validate_table_name(table: &str) -> Result<()> {
Ok(())
}
-/// Delete all persons for `team_id`. The harness owns its team ids
-/// outright, so a team-wide delete is the whole cleanup. Nothing writes
-/// distinct-id rows today (traffic is id-keyed), so nothing cleans them —
-/// that changes together when seeding grows a mechanism that writes them.
-pub async fn cleanup_team(pool: &PgPool, team_id: i64) -> Result<u64> {
- let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
-
- let persons = sqlx::query("DELETE FROM posthog_person WHERE team_id = $1")
- .bind(team)
- .execute(pool)
- .await
- .context("deleting persons")?
- .rows_affected();
-
- Ok(persons)
-}
-
#[cfg(test)]
mod tests {
use super::validate_table_name;
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index 3d41b81573c9..911b943e9c74 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -271,6 +271,10 @@ impl Stack {
"personhog-test-harness-writer".to_string(),
),
("FALLBACK_DATABASE_URL", self.config.persons_db_url.clone()),
+ // Pair the fallback with the spawned writer's target: the
+ // dirty index treats an unmarked person's PG row as
+ // current, which is only true of the writer's own table.
+ ("FALLBACK_TABLE", self.config.pg_target_table.clone()),
(
"METRICS_PORT",
(LEADER_METRICS_BASE_PORT + index as u16).to_string(),
diff --git a/rust/personhog-test-harness/src/traffic_metrics.rs b/rust/personhog-test-harness/src/traffic_metrics.rs
new file mode 100644
index 000000000000..7c312b1e0989
--- /dev/null
+++ b/rust/personhog-test-harness/src/traffic_metrics.rs
@@ -0,0 +1,99 @@
+//! Metrics for the continuous traffic mode.
+//!
+//! Only `traffic` installs the exporter; the bounded modes never call
+//! [`serve`], so the `metrics::` macros sprinkled through shared code are
+//! no-ops there. Violations are exported as counters by kind so a dev
+//! alert can fire on any increment — the continuous mode's whole point is
+//! that a consistency violation becomes a page-shaped signal rather than
+//! a process exit code.
+
+use std::process;
+
+use anyhow::Result;
+use axum::routing::get;
+use axum::Router;
+use metrics::counter;
+
+use crate::report::ConsistencyViolation;
+
+/// Serve liveness + Prometheus metrics; runs for the process lifetime.
+pub fn spawn_server(port: u16) -> Result<()> {
+ let router = Router::new().route("/_liveness", get(|| async { "ok" }));
+ let router = common_metrics::setup_metrics_routes(router);
+ let bind = format!("0.0.0.0:{port}");
+ tokio::spawn(async move {
+ if let Err(e) = common_metrics::serve(router, &bind).await {
+ // The exporter dying must not look like health: crash the
+ // process so the deployment restarts it and the absence alarm
+ // has something unambiguous to see.
+ tracing::error!(error = %e, "metrics server failed");
+ process::exit(1);
+ }
+ });
+ Ok(())
+}
+
+/// Stable metric label for a violation, derived from the journal's
+/// violation key vocabulary. Property-key violations (an acked write
+/// missing or mismatched on read-back) all classify as `missing_write`.
+pub fn violation_kind(violation: &ConsistencyViolation) -> &'static str {
+ match violation.key.as_str() {
+ "__ack_version_duplicate" => "duplicate_version",
+ "__strong_read_version" => "stale_read",
+ "__version" => "pg_below_ack",
+ "__row" | "__missing_person" => "missing_row",
+ "__strong_read_failed" => "read_failed",
+ "__ack_missing_person" => "ack_missing_person",
+ _ => "missing_write",
+ }
+}
+
+/// Record a batch of violations into the by-kind counter and log each one.
+pub fn record_violations(epoch: u64, violations: &[ConsistencyViolation]) {
+ for violation in violations {
+ let kind = violation_kind(violation);
+ counter!("personhog_traffic_violations_total", "kind" => kind).increment(1);
+ tracing::error!(
+ epoch,
+ kind,
+ person_id = violation.person_id,
+ key = %violation.key,
+ expected = %violation.expected,
+ actual = %violation.actual,
+ "consistency violation"
+ );
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::{json, Value};
+
+ use super::*;
+
+ fn violation(key: &str) -> ConsistencyViolation {
+ ConsistencyViolation {
+ person_id: 1,
+ key: key.to_string(),
+ expected: json!("x"),
+ actual: Value::Null,
+ }
+ }
+
+ #[test]
+ fn violation_kinds_cover_the_journal_vocabulary() {
+ let cases = [
+ ("__ack_version_duplicate", "duplicate_version"),
+ ("__strong_read_version", "stale_read"),
+ ("__version", "pg_below_ack"),
+ ("__row", "missing_row"),
+ ("__missing_person", "missing_row"),
+ ("__strong_read_failed", "read_failed"),
+ ("__ack_missing_person", "ack_missing_person"),
+ ("harness_gate_3_17", "missing_write"),
+ ];
+ for (key, kind) in cases {
+ assert_eq!(violation_kind(&violation(key)), kind, "{key}");
+ }
+ }
+}
diff --git a/rust/personhog-test-harness/src/verify.rs b/rust/personhog-test-harness/src/verify.rs
new file mode 100644
index 000000000000..b68d86154a07
--- /dev/null
+++ b/rust/personhog-test-harness/src/verify.rs
@@ -0,0 +1,109 @@
+//! Postgres-side verification shared by the gate and the continuous
+//! traffic mode.
+
+use std::collections::HashMap;
+use std::time::{Duration, Instant};
+
+use anyhow::{Context, Result};
+use serde_json::{json, Value};
+use sqlx::postgres::PgPool;
+use sqlx::Row;
+use tokio::time::sleep;
+
+use crate::report::ConsistencyViolation;
+use crate::state::{verify_properties, ExpectedPerson};
+
+/// How long to wait for the writer to drain acked writes into Postgres
+/// before declaring them lost.
+pub const QUIESCE_DEADLINE: Duration = Duration::from_secs(60);
+
+/// Poll Postgres until every journaled person row contains all acked
+/// property writes at the acked version, or the quiesce deadline passes.
+/// Returns the outstanding violations (empty = converged).
+pub async fn verify_postgres(
+ pool: &PgPool,
+ table: &str,
+ team_id: i64,
+ journal: &HashMap<i64, ExpectedPerson>,
+) -> Result<Vec<ConsistencyViolation>> {
+ let team: i32 = team_id.try_into().context("team_id out of i32 range")?;
+ let person_ids: Vec<i64> = journal.keys().copied().collect();
+ if person_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let query = format!(
+ "SELECT id, properties::text AS properties, version \
+ FROM {table} WHERE team_id = $1 AND id = ANY($2)"
+ );
+ let deadline = Instant::now() + QUIESCE_DEADLINE;
+ loop {
+ let rows = sqlx::query(&query)
+ .bind(team)
+ .bind(&person_ids)
+ .fetch_all(pool)
+ .await
+ .context("reading persons from Postgres")?;
+
+ let mut by_id: HashMap<i64, (serde_json::Value, i64)> = HashMap::new();
+ for row in rows {
+ let id: i64 = row.get("id");
+ let properties: Option<String> = row.get("properties");
+ let version: Option<i64> = row.get("version");
+ let props = properties
+ .as_deref()
+ .map(serde_json::from_str)
+ .transpose()
+ .context("parsing properties JSON")?
+ .unwrap_or_else(|| json!({}));
+ by_id.insert(id, (props, version.unwrap_or(0)));
+ }
+
+ let mut violations = Vec::new();
+ for (person_id, expected) in journal {
+ match by_id.get(person_id) {
+ Some((props, version)) => {
+ violations.extend(verify_properties(
+ *person_id,
+ &expected.written_properties,
+ props,
+ ));
+ // The highest acked version is a floor, not an exact
+ // target: a write that produced its record but lost the
+ // response (a drain, a client timeout) is unacked yet
+ // still applied, legitimately leaving the row above the
+ // floor. Below it, an acked write never reached
+ // Postgres.
+ if *version < expected.last_version {
+ violations.push(ConsistencyViolation {
+ person_id: *person_id,
+ key: "__version".to_string(),
+ expected: json!(format!(">= {}", expected.last_version)),
+ actual: json!(version),
+ });
+ }
+ }
+ None => {
+ violations.push(ConsistencyViolation {
+ person_id: *person_id,
+ key: "__row".to_string(),
+ expected: json!("present"),
+ actual: Value::Null,
+ });
+ }
+ }
+ }
+
+ if violations.is_empty() {
+ return Ok(violations);
+ }
+ if Instant::now() > deadline {
+ tracing::error!(
+ outstanding = violations.len(),
+ "Postgres did not converge within {QUIESCE_DEADLINE:?}"
+ );
+ return Ok(violations);
+ }
+ sleep(Duration::from_millis(500)).await;
+ }
+}