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): changelog generations on their own kafka cluster (#129706)

Zach Brown22a21f2e5d07
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index 09e9a18f7734..9e90090f8d09 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -568,7 +568,7 @@ jobs:
# changes, so unrelated rust PRs skip the job entirely.
if: needs.changes.outputs.rust == 'true' && contains(needs.affected.outputs.affected_crates, 'personhog-test-harness')
runs-on: depot-ubuntu-24.04-4
- timeout-minutes: 25
+ timeout-minutes: 35
permissions:
contents: read
env:
@@ -592,14 +592,15 @@ jobs:
username: ${{ vars.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- - name: Start Postgres, Kafka, and etcd
+ # kafka-secondary is a second, empty cluster for the cross-cluster changelog tests.
+ - name: Start Postgres, two Kafka clusters, and etcd
env:
COMPOSE_FILE: ../docker-compose.dev.yml:../docker-compose.profiles.yml
- COMPOSE_PROFILES: etcd
+ COMPOSE_PROFILES: etcd,personhog-secondary
WAIT_FOR_DOCKER_LAUNCH_RETRY_DELAY: 10
run: |
- ../bin/ci-wait-for-docker launch --down db kafka etcd
- ../bin/ci-wait-for-docker wait --only db kafka etcd
+ ../bin/ci-wait-for-docker launch --down db kafka kafka-secondary etcd
+ ../bin/ci-wait-for-docker wait --only db kafka kafka-secondary etcd
echo "127.0.0.1 db kafka" | sudo tee -a /etc/hosts
@@ -638,6 +639,16 @@ jobs:
- name: Test the harness verification logic
run: cargo test -p personhog-test-harness -- --include-ignored
+ # The leader warming, pruning, recovering and sealing a changelog generation
+ # on another cluster, against the second broker only this job
+ # starts. Elsewhere these tests run their single-cluster cases.
+ - name: Test the leader across two Kafka clusters
+ env:
+ PERSONHOG_TEST_SECONDARY_KAFKA: 127.0.0.1:29092
+ run: >-
+ cargo test -p personhog-leader --features test-support
+ --test warming_integration --test fencing_integration --test integration
+
- name: Run the e2e gate
run: |
./target/debug/personhog-test-harness gate \
@@ -790,11 +801,23 @@ jobs:
--migrate-after 8s --migrate-to-partitions 4 \
--migrate-kill-leader-at-sealing --migrate-slow-coordinator-ms 500
+ # A migration onto the second cluster: the leaders seal the old
+ # topic on the first and produce on the second, and the writer
+ # exits once it drains the old topic and is restarted onto the
+ # new cluster, as its pod would be. The gate fails if it never does.
+ - name: Run the e2e gate migrating the changelog onto another cluster
+ run: |
+ ./target/debug/personhog-test-harness gate \
+ --leaders 2 --partitions 4 --persons 200 --concurrency 10 --duration 30s \
+ --migrate-after 10s --migrate-to-partitions 8 \
+ --migrate-to-kafka-hosts 127.0.0.1:29092
+
- name: Dump service logs on failure
if: failure()
run: |
docker ps -a || true
docker logs --tail=200 rust-kafka-1 || true
+ docker logs --tail=200 rust-kafka-secondary-1 || true
docker logs --tail=200 rust-etcd-1 || true
- name: Upload harness logs on failure
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 1cd3f8dd228f..576b80d55fc1 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -951,6 +951,30 @@ services:
timeout: 5s
retries: 10
+ # A second, empty Kafka cluster for personhog's cross-cluster changelog
+ # tests; only the PersonHog e2e gate CI job starts it.
+ kafka-secondary:
+ image: docker.io/redpandadata/redpanda:v25.1.9
+ profiles: [personhog-secondary]
+ restart: on-failure
+ command:
+ - redpanda
+ - start
+ - --kafka-addr 0.0.0.0:29092
+ - --advertise-kafka-addr 127.0.0.1:29092
+ - --mode dev-container
+ - --smp 1
+ - --memory 1G
+ - --overprovisioned
+ - --set redpanda.auto_create_topics_enabled=true
+ ports:
+ - '127.0.0.1:29092:29092'
+ healthcheck:
+ test: curl -f http://localhost:9644/v1/status/ready || exit 1
+ interval: 3s
+ timeout: 10s
+ retries: 10
+
networks:
otel_network:
driver: bridge
diff --git a/rust/common/kafka/src/config.rs b/rust/common/kafka/src/config.rs
index 2e4fe91be810..7ce293a638f3 100644
--- a/rust/common/kafka/src/config.rs
+++ b/rust/common/kafka/src/config.rs
@@ -58,6 +58,16 @@ pub struct KafkaConfig {
pub kafka_producer_retries: Option<u32>,
}
+impl KafkaConfig {
+ pub fn with_endpoint(&self, hosts: &str, tls: bool) -> Self {
+ Self {
+ kafka_hosts: hosts.to_string(),
+ kafka_tls: tls,
+ ..self.clone()
+ }
+ }
+}
+
// Keep these values in sync with the `#[envconfig(default = ...)]` attributes
// above: `KafkaConfig::default()` must match `init_from_env()` with no env set,
// so callers that build a config with `..Default::default()` get the same base
diff --git a/rust/ingestion-control-plane/src/changelog.rs b/rust/ingestion-control-plane/src/changelog.rs
index fc95a30efb65..1534ac4fe646 100644
--- a/rust/ingestion-control-plane/src/changelog.rs
+++ b/rust/ingestion-control-plane/src/changelog.rs
@@ -309,6 +309,7 @@ pub async fn start_migration(
id: format!("m-{now_ms}"),
from: live.target(),
to: ChangelogTarget {
+ cluster: live.cluster.clone(),
topic: topic.to_string(),
partitions,
},
diff --git a/rust/personhog-changelog-relay/src/consumer.rs b/rust/personhog-changelog-relay/src/consumer.rs
index 89c8ce26da34..2b14fa7ec2cd 100644
--- a/rust/personhog-changelog-relay/src/consumer.rs
+++ b/rust/personhog-changelog-relay/src/consumer.rs
@@ -4,6 +4,7 @@ use std::sync::RwLock;
use common_kafka::config::KafkaConfig;
use personhog_coordination::follow::ChangelogSubscription;
+use personhog_coordination::types::ClusterEndpoint;
use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};
use rdkafka::error::KafkaError;
use rdkafka::message::{BorrowedMessage, Message};
@@ -63,6 +64,7 @@ impl Record {
pub struct ChangelogConsumer {
consumer: StreamConsumer,
topic: RwLock<String>,
+ cluster: Option<ClusterEndpoint>,
draining: AtomicBool,
}
@@ -73,10 +75,16 @@ impl ChangelogConsumer {
Ok(Self {
consumer,
topic: RwLock::new(topic),
+ cluster: None,
draining: AtomicBool::new(false),
})
}
+ pub fn on_cluster(mut self, cluster: Option<ClusterEndpoint>) -> Self {
+ self.cluster = cluster;
+ self
+ }
+
pub async fn recv(&self) -> Result<Record, KafkaError> {
self.consumer
.recv()
@@ -117,6 +125,10 @@ impl ChangelogSubscription for ChangelogConsumer {
self.topic.read().expect("topic lock poisoned").clone()
}
+ fn cluster(&self) -> Option<ClusterEndpoint> {
+ self.cluster.clone()
+ }
+
fn resubscribe(&self, topic: &str) -> Result<(), String> {
self.consumer
.subscribe(&[topic])
diff --git a/rust/personhog-changelog-relay/src/main.rs b/rust/personhog-changelog-relay/src/main.rs
index 45e986917264..f7e56b298886 100644
--- a/rust/personhog-changelog-relay/src/main.rs
+++ b/rust/personhog-changelog-relay/src/main.rs
@@ -4,14 +4,18 @@ use std::time::Duration;
use assignment_coordination::store::{EtcdStore, StoreConfig};
use axum::{http::StatusCode, routing::get, Router};
+use common_kafka::config::KafkaConfig;
use common_kafka::kafka_producer::{create_kafka_producer, spawn_bounded_flush_on_shutdown};
use common_metrics::setup_metrics_routes;
use envconfig::Envconfig;
use lifecycle::{ComponentOptions, Manager};
use metrics::counter;
use personhog_coordination::changelog::{load_changelog_config, CHANGELOG_BOOT_POLL_INTERVAL};
-use personhog_coordination::follow::{follow_changelog, ChangelogSubscription, Follower, Reporter};
+use personhog_coordination::follow::{
+ follow_changelog, ChangelogSubscription, FollowTarget, Follower, Reporter,
+};
use personhog_coordination::store::PersonhogStore;
+use personhog_coordination::types::ClusterEndpoint;
use tokio_util::sync::CancellationToken;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::layer::SubscriberExt;
@@ -133,13 +137,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
// Oldest undrained generation first, so a restart mid-drain resumes it.
let mut follower = Follower::default();
- let topic = follower
- .select_topic(&loaded, |topic| drained(&config, topic))
+ let FollowTarget { topic, cluster } = follower
+ .select_topic(&loaded, |target| drained(&config, target))
.await?;
- let consumer = Arc::new(ChangelogConsumer::new(
- &consumer_client_config(&config.kafka, &config.kafka_consumer_group),
- topic.clone(),
- )?);
+ let consumer = Arc::new(
+ ChangelogConsumer::new(
+ &consumer_client_config(
+ &changelog_kafka(&config.kafka, cluster.as_ref()),
+ &config.kafka_consumer_group,
+ ),
+ topic.clone(),
+ )?
+ .on_cluster(cluster.clone()),
+ );
consumer.set_draining(topic != loaded.topic);
tracing::info!(topic = %topic, draining = consumer.is_draining(), "subscribed to the changelog");
@@ -157,14 +167,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
loaded,
follower,
consumer,
- |topic: String| drained(&config, topic),
+ |target: FollowTarget| drained(&config, target),
Reporter::for_group(&config.kafka_consumer_group),
|_, _| counter!("personhog_changelog_relay_resubscriptions_total").increment(1),
cancel.clone(),
);
tokio::select! {
_ = changelog_handle.shutdown_signal() => cancel.cancel(),
- _ = follow => {}
+ rebind = follow => {
+ // The pod's restart subscribes on the next generation's cluster.
+ if rebind.is_some() {
+ changelog_handle.request_shutdown();
+ changelog_handle.shutdown_signal().await;
+ }
+ }
}
});
}
@@ -186,9 +202,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
-/// Whether the relay's group has read every partition of `topic` to its end.
-async fn drained(config: &Config, topic: String) -> Result<bool, String> {
- let base = base_client_config(&config.kafka);
+fn changelog_kafka(base: &KafkaConfig, cluster: Option<&ClusterEndpoint>) -> KafkaConfig {
+ match cluster {
+ Some(cluster) => base.with_endpoint(&cluster.hosts, cluster.tls),
+ None => base.clone(),
+ }
+}
+
+async fn drained(config: &Config, target: FollowTarget) -> Result<bool, String> {
+ let base = base_client_config(&changelog_kafka(&config.kafka, target.cluster.as_ref()));
+ let topic = target.topic;
let group = config.kafka_consumer_group.clone();
tokio::task::spawn_blocking(move || {
common_kafka::probe::group_drained(&base, &group, &topic, Duration::from_secs(10))
diff --git a/rust/personhog-changelog-relay/tests/relay.rs b/rust/personhog-changelog-relay/tests/relay.rs
index 2ba5fdd39ad7..b50ca8c581c0 100644
--- a/rust/personhog-changelog-relay/tests/relay.rs
+++ b/rust/personhog-changelog-relay/tests/relay.rs
@@ -7,7 +7,7 @@ use envconfig::Envconfig;
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use personhog_changelog_relay::consumer::{consumer_client_config, ChangelogConsumer};
use personhog_changelog_relay::relay::Relay;
-use personhog_coordination::follow::Follower;
+use personhog_coordination::follow::{FollowStep, Follower};
use personhog_coordination::types::{ChangelogConfig, Generation};
use personhog_proto::personhog::types::v1::Person;
use prost::Message as _;
@@ -293,12 +293,14 @@ async fn a_move_to_the_live_topic_relays_it_from_its_first_record() {
assert_eq!(read(1).await.unwrap(), vec![person(1).uuid]);
let flipped = ChangelogConfig {
+ cluster: None,
topic: new.clone(),
partitions: 1,
epoch: 2,
writer_group: "writer".to_string(),
retire_groups: vec![group],
draining: vec![Generation {
+ cluster: None,
topic: old.clone(),
partitions: 1,
epoch: 1,
@@ -308,7 +310,7 @@ async fn a_move_to_the_live_topic_relays_it_from_its_first_record() {
.follow_once(consumer.as_ref(), &flipped, |_| async { Ok(true) })
.await
.unwrap();
- assert_eq!(moved, Some(old));
+ assert_eq!(moved, FollowStep::Moved(old));
assert_eq!(read(2).await.unwrap(), vec![person(1).uuid, person(2).uuid]);
diff --git a/rust/personhog-coordination/src/changelog.rs b/rust/personhog-coordination/src/changelog.rs
index 80eb2e52bc91..09760bbd08a2 100644
--- a/rust/personhog-coordination/src/changelog.rs
+++ b/rust/personhog-coordination/src/changelog.rs
@@ -10,7 +10,7 @@ use tokio_util::sync::CancellationToken;
use crate::error::{Error, Result};
use crate::store::PersonhogStore;
-use crate::types::ChangelogConfig;
+use crate::types::{ChangelogConfig, ClusterEndpoint};
use crate::util;
/// Whether boot keeps polling through `err`: any etcd error, since there is
@@ -155,14 +155,16 @@ pub struct KeyFilter {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WarmSource {
pub topic: Arc<str>,
+ pub cluster: Option<ClusterEndpoint>,
pub partition: u32,
pub keep: Option<KeyFilter>,
}
impl WarmSource {
- pub fn live(topic: &str, partition: u32) -> Self {
+ pub fn live(topic: &str, cluster: Option<&ClusterEndpoint>, partition: u32) -> Self {
Self {
topic: Arc::from(topic),
+ cluster: cluster.cloned(),
partition,
keep: None,
}
@@ -189,6 +191,7 @@ pub fn warm_sources(config: &ChangelogConfig, partition: u32) -> Vec<WarmSource>
for q in (0..generation.partitions).filter(|q| q % g == partition % g) {
sources.push(WarmSource {
topic: Arc::from(generation.topic.as_str()),
+ cluster: generation.cluster.clone(),
partition: q,
keep: Some(KeyFilter {
modulus: config.partitions,
@@ -197,7 +200,11 @@ pub fn warm_sources(config: &ChangelogConfig, partition: u32) -> Vec<WarmSource>
});
}
}
- sources.push(WarmSource::live(&config.topic, partition));
+ sources.push(WarmSource::live(
+ &config.topic,
+ config.cluster.as_ref(),
+ partition,
+ ));
sources
}
@@ -398,6 +405,7 @@ mod tests {
fn config(partitions: u32, draining: Vec<(u32, u64)>) -> ChangelogConfig {
ChangelogConfig {
+ cluster: None,
topic: "new".to_string(),
partitions,
epoch: 9,
@@ -406,6 +414,7 @@ mod tests {
draining: draining
.into_iter()
.map(|(partitions, epoch)| Generation {
+ cluster: None,
topic: format!("old{epoch}"),
partitions,
epoch,
@@ -510,6 +519,17 @@ mod tests {
let live = sources.last().unwrap();
assert!(live.keep.is_none());
assert_eq!(live.partition, 1);
+ let mut moved = config(8, vec![(4, 2)]);
+ let dedicated = ClusterEndpoint {
+ name: "dedicated".to_string(),
+ hosts: "dedicated:9092".to_string(),
+ tls: false,
+ };
+ moved.cluster = Some(dedicated.clone());
+ let moved_sources = warm_sources(&moved, 1);
+ let clusters: Vec<Option<&ClusterEndpoint>> =
+ moved_sources.iter().map(|s| s.cluster.as_ref()).collect();
+ assert_eq!(clusters, vec![None, Some(&dedicated)]);
assert!(sources[0]
.keep
.as_ref()
diff --git a/rust/personhog-coordination/src/follow.rs b/rust/personhog-coordination/src/follow.rs
index 721c8d0b1a41..8b0207413bd2 100644
--- a/rust/personhog-coordination/src/follow.rs
+++ b/rust/personhog-coordination/src/follow.rs
@@ -13,15 +13,33 @@ use tracing::info;
use crate::changelog::{watch_changelog_config_loop, CHANGELOG_RECONCILE_INTERVAL};
use crate::store::PersonhogStore;
-use crate::types::{ChangelogConfig, DrainReport};
+use crate::types::{ChangelogConfig, ClusterEndpoint, DrainReport};
/// How often a consumer on a sealed generation re-checks its group's drain.
/// Each check reads every partition of the generation under a probe group.
pub const DRAIN_POLL_INTERVAL: Duration = Duration::from_secs(2);
+pub const REBIND_LOG: &str =
+ "the next changelog generation lives on another cluster; restarting to subscribe there";
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FollowTarget {
+ pub topic: String,
+ pub cluster: Option<ClusterEndpoint>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub enum FollowStep {
+ Stayed,
+ Moved(String),
+ /// The next topic lives on another cluster; the process restarts to subscribe there.
+ Rebind(FollowTarget),
+}
+
/// The consumer side of a followed subscription.
pub trait ChangelogSubscription {
fn topic(&self) -> String;
+ fn cluster(&self) -> Option<ClusterEndpoint>;
/// Only called once the group has drained the current topic.
fn resubscribe(&self, topic: &str) -> Result<(), String>;
fn set_draining(&self, draining: bool);
@@ -43,9 +61,9 @@ impl Follower {
&mut self,
changelog: &ChangelogConfig,
drained: F,
- ) -> Result<String, String>
+ ) -> Result<FollowTarget, String>
where
- F: Fn(String) -> Fut,
+ F: Fn(FollowTarget) -> Fut,
Fut: Future<Output = Result<bool, String>>,
{
let mut generations = changelog.draining.clone();
@@ -54,52 +72,67 @@ impl Follower {
if self.drained.contains(&generation.topic) {
continue;
}
- if !drained(generation.topic.clone()).await? {
- return Ok(generation.topic);
+ let target = FollowTarget {
+ topic: generation.topic.clone(),
+ cluster: generation.cluster.clone(),
+ };
+ if !drained(target.clone()).await? {
+ return Ok(target);
}
self.unreported.push(generation.topic.clone());
self.drained.insert(generation.topic);
}
- Ok(changelog.topic.clone())
+ Ok(FollowTarget {
+ topic: changelog.topic.clone(),
+ cluster: changelog.cluster.clone(),
+ })
}
- /// One pass of the follow loop; returns the topic it moved off, if it moved.
- /// The draining flag follows the config before the subscription is touched,
- /// so it holds whether or not the subscription moved.
+ /// One pass of the follow loop. The draining flag follows the config
+ /// before the subscription is touched, so it holds whether or not the
+ /// subscription moved.
pub async fn follow_once<S, F, Fut>(
&mut self,
subscription: &S,
changelog: &ChangelogConfig,
drained: F,
- ) -> Result<Option<String>, String>
+ ) -> Result<FollowStep, String>
where
S: ChangelogSubscription + ?Sized,
- F: Fn(String) -> Fut,
+ F: Fn(FollowTarget) -> Fut,
Fut: Future<Output = Result<bool, String>>,
{
let wanted = self.select_topic(changelog, &drained).await?;
let subscribed = subscription.topic();
// A generation can leave the config before this group drains it, when
// retire stops waiting on the group; finish reading it before moving on.
- if subscribed != wanted
+ if subscribed != wanted.topic
&& subscribed != changelog.topic
&& !self.drained.contains(&subscribed)
{
- if !drained(subscribed.clone()).await? {
+ let current = FollowTarget {
+ topic: subscribed.clone(),
+ cluster: subscription.cluster(),
+ };
+ if !drained(current).await? {
subscription.set_draining(true);
- return Ok(None);
+ return Ok(FollowStep::Stayed);
}
self.drained.insert(subscribed.clone());
}
- subscription.set_draining(wanted != changelog.topic);
- if wanted == subscribed {
- return Ok(None);
+ subscription.set_draining(wanted.topic != changelog.topic);
+ if wanted.topic == subscribed {
+ return Ok(FollowStep::Stayed);
+ }
+ // Every move follows a proven drain, so nothing is left to commit on the old cluster.
+ if wanted.cluster != subscription.cluster() {
+ return Ok(FollowStep::Rebind(wanted));
}
subscription
- .resubscribe(&wanted)
- .map_err(|e| format!("re-subscribe to {wanted}: {e}"))?;
- info!(from = %subscribed, to = %wanted, "moved the subscription");
- Ok(Some(subscribed))
+ .resubscribe(&wanted.topic)
+ .map_err(|e| format!("re-subscribe to {}: {e}", wanted.topic))?;
+ info!(from = %subscribed, to = %wanted.topic, "moved the subscription");
+ Ok(FollowStep::Moved(subscribed))
}
/// Writes a drain report for every generation proven drained since the
@@ -159,9 +192,10 @@ pub async fn follow_changelog<S, F, Fut, M>(
reporter: Reporter,
on_move: M,
cancel: CancellationToken,
-) where
+) -> Option<FollowTarget>
+where
S: ChangelogSubscription + ?Sized,
- F: Fn(String) -> Fut,
+ F: Fn(FollowTarget) -> Fut,
Fut: Future<Output = Result<bool, String>>,
M: Fn(&str, &str),
{
@@ -185,8 +219,18 @@ pub async fn follow_changelog<S, F, Fut, M>(
.follow_once(subscription.as_ref(), &current, &drained)
.await
{
- Ok(Some(from)) => on_move(&from, &subscription.topic()),
- Ok(None) => {}
+ Ok(FollowStep::Moved(from)) => on_move(&from, &subscription.topic()),
+ Ok(FollowStep::Stayed) => {}
+ Ok(FollowStep::Rebind(next)) => {
+ // Reports first, so the drain this move rests on is recorded before the restart.
+ follower.report(&store, &reporter).await;
+ tracing::warn!(
+ topic = %next.topic,
+ cluster = ?next.cluster.as_ref().map(|c| &c.name),
+ "{REBIND_LOG}"
+ );
+ return Some(next);
+ }
Err(e) => tracing::warn!(
error = %e,
"could not follow the changelog config; keeping the subscription"
@@ -201,7 +245,7 @@ pub async fn follow_changelog<S, F, Fut, M>(
tokio::select! {
changed = config_rx.changed() => {
if changed.is_err() {
- return;
+ return None;
}
}
_ = tokio::time::sleep(poll) => {}
@@ -209,9 +253,9 @@ pub async fn follow_changelog<S, F, Fut, M>(
}
};
tokio::select! {
- _ = cancel.cancelled() => {}
- _ = watch => {}
- _ = follow => {}
+ _ = cancel.cancelled() => None,
+ _ = watch => None,
+ next = follow => next,
}
}
@@ -224,6 +268,7 @@ mod tests {
struct Subscription {
topic: Mutex<String>,
+ cluster: Option<ClusterEndpoint>,
draining: AtomicBool,
}
@@ -232,6 +277,10 @@ mod tests {
self.topic.lock().unwrap().clone()
}
+ fn cluster(&self) -> Option<ClusterEndpoint> {
+ self.cluster.clone()
+ }
+
fn resubscribe(&self, topic: &str) -> Result<(), String> {
*self.topic.lock().unwrap() = topic.to_string();
Ok(())
@@ -250,6 +299,7 @@ mod tests {
async fn a_generation_retired_before_the_group_drained_it_is_read_to_the_end() {
let subscription = Subscription {
topic: Mutex::new("old".to_string()),
+ cluster: None,
draining: AtomicBool::new(true),
};
let live = ChangelogConfig::new("new", 8);
@@ -259,7 +309,7 @@ mod tests {
.follow_once(&subscription, &live, |_| async { Ok(false) })
.await
.unwrap();
- assert_eq!(moved, None);
+ assert_eq!(moved, FollowStep::Stayed);
assert_eq!(subscription.topic(), "old");
assert!(subscription.is_draining());
@@ -267,8 +317,61 @@ mod tests {
.follow_once(&subscription, &live, |_| async { Ok(true) })
.await
.unwrap();
- assert_eq!(moved, Some("old".to_string()));
+ assert_eq!(moved, FollowStep::Moved("old".to_string()));
assert_eq!(subscription.topic(), "new");
assert!(!subscription.is_draining());
}
+
+ #[tokio::test]
+ async fn a_successor_on_another_cluster_rebinds_instead_of_resubscribing() {
+ let subscription = Subscription {
+ topic: Mutex::new("old".to_string()),
+ cluster: None,
+ draining: AtomicBool::new(true),
+ };
+ let mut live = ChangelogConfig::new("new", 8);
+ let dedicated = ClusterEndpoint {
+ name: "dedicated".to_string(),
+ hosts: "dedicated:9092".to_string(),
+ tls: false,
+ };
+ live.cluster = Some(dedicated.clone());
+ // The subscription predates the recorded cluster, so the probe must use the generation's.
+ let ingestion = ClusterEndpoint {
+ name: "ingestion".to_string(),
+ hosts: "ingestion:9092".to_string(),
+ tls: false,
+ };
+ live.draining.push(crate::types::Generation {
+ topic: "old".to_string(),
+ partitions: 4,
+ epoch: 1,
+ cluster: Some(ingestion.clone()),
+ });
+ let probed = Mutex::new(Vec::new());
+ let mut follower = Follower::default();
+
+ let step = follower
+ .follow_once(&subscription, &live, |target| {
+ probed.lock().unwrap().push(target);
+ async { Ok(true) }
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ step,
+ FollowStep::Rebind(FollowTarget {
+ topic: "new".to_string(),
+ cluster: Some(dedicated),
+ })
+ );
+ assert_eq!(subscription.topic(), "old");
+ assert_eq!(
+ probed.lock().unwrap().first(),
+ Some(&FollowTarget {
+ topic: "old".to_string(),
+ cluster: Some(ingestion),
+ })
+ );
+ }
}
diff --git a/rust/personhog-coordination/src/store.rs b/rust/personhog-coordination/src/store.rs
index 7ac123d76789..a828de949571 100644
--- a/rust/personhog-coordination/src/store.rs
+++ b/rust/personhog-coordination/src/store.rs
@@ -8,9 +8,9 @@ use etcd_client::{
use crate::error::{Error, Result};
use crate::types::{
- AssignmentPrecondition, AssignmentStatus, ChangelogConfig, HandoffReplacement, HandoffState,
- LeaderInfo, MigrationState, PartitionAssignment, PodDrainedAck, PodStatus, PodWarmedAck,
- RegisteredPod, RegisteredRouter, RouterFreezeAck,
+ AssignmentPrecondition, AssignmentStatus, ChangelogConfig, ClusterEndpoint, HandoffReplacement,
+ HandoffState, LeaderInfo, MigrationState, PartitionAssignment, PodDrainedAck, PodStatus,
+ PodWarmedAck, RegisteredPod, RegisteredRouter, RouterFreezeAck,
};
mod migration;
@@ -1470,10 +1470,22 @@ impl PersonhogStore {
topic: &str,
partitions: u32,
writer_group: &str,
+ ) -> Result<bool> {
+ self.seed_changelog_config_on(topic, partitions, writer_group, None)
+ .await
+ }
+
+ pub async fn seed_changelog_config_on(
+ &self,
+ topic: &str,
+ partitions: u32,
+ writer_group: &str,
+ cluster: Option<ClusterEndpoint>,
) -> Result<bool> {
count_call("seed_changelog_config");
let config = ChangelogConfig {
writer_group: writer_group.to_string(),
+ cluster,
..ChangelogConfig::new(topic, partitions)
};
self.create_changelog_config(serde_json::to_vec(&config)?)
diff --git a/rust/personhog-coordination/src/store/migration.rs b/rust/personhog-coordination/src/store/migration.rs
index 849c108e7141..2885fd13594e 100644
--- a/rust/personhog-coordination/src/store/migration.rs
+++ b/rust/personhog-coordination/src/store/migration.rs
@@ -5,8 +5,8 @@ use etcd_client::{Compare, CompareOp, DeleteOptions, Txn, TxnOp, WatchStream};
use super::{count_call, PersonhogStore, StoreKey};
use crate::error::Result;
use crate::types::{
- ChangelogConfig, DrainReport, Generation, MigrationPhase, MigrationRequest, MigrationState,
- SealAck,
+ ChangelogConfig, ClusterEndpoint, DrainReport, Generation, MigrationPhase, MigrationRequest,
+ MigrationState, SealAck,
};
impl PersonhogStore {
@@ -146,10 +146,12 @@ impl PersonhogStore {
topic: migration.from.topic.clone(),
partitions: migration.from.partitions,
epoch: config.epoch,
+ cluster: migration.from.cluster.clone(),
});
let flipped = ChangelogConfig {
topic: migration.to.topic.clone(),
partitions: migration.to.partitions,
+ cluster: migration.to.cluster.clone(),
epoch: config.epoch + 1,
writer_group: config.writer_group.clone(),
retire_groups: config.retire_groups.clone(),
@@ -319,6 +321,33 @@ impl PersonhogStore {
Ok(self.inner.txn(txn).await?.succeeded())
}
+ /// Records the cluster of a live config that has none, at its epoch. Refused while a
+ /// migration is requested or running, since a request names the live config as it was.
+ pub async fn set_changelog_cluster(
+ &self,
+ config: &ChangelogConfig,
+ mod_revision: i64,
+ cluster: &ClusterEndpoint,
+ ) -> Result<bool> {
+ count_call("set_changelog_cluster");
+ if config.cluster.is_some() {
+ return Ok(false);
+ }
+ let named = ChangelogConfig {
+ cluster: Some(cluster.clone()),
+ ..config.clone()
+ };
+ let key = self.key(StoreKey::ChangelogConfig);
+ let txn = Txn::new()
+ .when(vec![
+ Compare::mod_revision(key.clone(), CompareOp::Equal, mod_revision),
+ Compare::create_revision(self.key(StoreKey::Migration), CompareOp::Equal, 0),
+ Compare::create_revision(self.key(StoreKey::MigrationRequest), CompareOp::Equal, 0),
+ ])
+ .and_then(vec![TxnOp::put(key, serde_json::to_vec(&named)?, None)]);
+ Ok(self.inner.txn(txn).await?.succeeded())
+ }
+
pub async fn put_drain_report(&self, report: &DrainReport) -> Result<()> {
count_call("put_drain_report");
let key = self.key(StoreKey::DrainReport {
diff --git a/rust/personhog-coordination/src/types.rs b/rust/personhog-coordination/src/types.rs
index 4e1dd76a1ca3..fa4d18cbcca6 100644
--- a/rust/personhog-coordination/src/types.rs
+++ b/rust/personhog-coordination/src/types.rs
@@ -323,6 +323,9 @@ pub struct LeaderInfo {
pub struct ChangelogConfig {
pub topic: String,
pub partitions: u32,
+ /// The Kafka cluster holding `topic`; unset is each process's own `KAFKA_HOSTS`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cluster: Option<ClusterEndpoint>,
/// Monotonic from 1.
pub epoch: u64,
/// The writer's consumer group; a generation retires only once it has read it to the end.
@@ -340,6 +343,8 @@ pub struct Generation {
pub topic: String,
pub partitions: u32,
pub epoch: u64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cluster: Option<ClusterEndpoint>,
}
impl ChangelogConfig {
@@ -348,6 +353,7 @@ impl ChangelogConfig {
Self {
topic: topic.to_string(),
partitions,
+ cluster: None,
epoch: 1,
writer_group: String::new(),
retire_groups: Vec::new(),
@@ -365,6 +371,7 @@ impl ChangelogConfig {
ChangelogTarget {
topic: self.topic.clone(),
partitions: self.partitions,
+ cluster: self.cluster.clone(),
}
}
@@ -373,6 +380,8 @@ impl ChangelogConfig {
/// late. A `retire_groups` edit also changes the object within an epoch
/// and is never adopted from a watch; nothing reads that list from an
/// adopted copy, since the coordinator and the control plane read etcd.
+ /// Recording the live cluster is the same: running processes see it only
+ /// at the next flip.
pub fn supersedes(&self, adopted: &ChangelogConfig) -> bool {
self.epoch > adopted.epoch
|| (self.epoch == adopted.epoch && self.draining.len() < adopted.draining.len())
@@ -383,6 +392,17 @@ impl ChangelogConfig {
pub struct ChangelogTarget {
pub topic: String,
pub partitions: u32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cluster: Option<ClusterEndpoint>,
+}
+
+/// Carried in the record so every process reads the same endpoint.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct ClusterEndpoint {
+ pub name: String,
+ pub hosts: String,
+ #[serde(default)]
+ pub tls: bool,
}
/// Sealing is the point of no return: the old topic's ids are re-initialized there.
@@ -516,9 +536,28 @@ mod tests {
assert_eq!(h.config_epoch, 0);
}
+ #[test]
+ fn pre_cluster_changelog_records_read_as_the_default_cluster() {
+ let config: ChangelogConfig = serde_json::from_str(
+ r#"{"topic":"t2","partitions":8,"epoch":2,"writer_group":"w",
+ "draining":[{"topic":"t1","partitions":4,"epoch":1}]}"#,
+ )
+ .unwrap();
+ assert_eq!(config.cluster, None);
+ assert_eq!(config.draining[0].cluster, None);
+ let request: MigrationRequest = serde_json::from_str(
+ r#"{"id":"m","from":{"topic":"t2","partitions":8},
+ "to":{"topic":"t3","partitions":8},"requested_at_ms":1}"#,
+ )
+ .unwrap();
+ assert_eq!(request.from, config.target());
+ assert!(!serde_json::to_string(&config).unwrap().contains("cluster"));
+ }
+
#[test]
fn a_config_supersedes_by_epoch_then_by_retired_generations() {
let generation = |epoch| Generation {
+ cluster: None,
topic: format!("g{epoch}"),
partitions: 64,
epoch,
diff --git a/rust/personhog-coordination/tests/changelog.rs b/rust/personhog-coordination/tests/changelog.rs
index 483d5639051b..bdd8c08b23b6 100644
--- a/rust/personhog-coordination/tests/changelog.rs
+++ b/rust/personhog-coordination/tests/changelog.rs
@@ -150,6 +150,7 @@ async fn the_watch_delivers_newer_epochs_and_retires_but_nothing_stale() {
assert_eq!(next_adopted(&mut rx).await.epoch, 1);
let flipped = ChangelogConfig {
+ cluster: None,
topic: "personhog_updates_128".into(),
partitions: 128,
epoch: 2,
@@ -171,6 +172,7 @@ async fn the_watch_delivers_newer_epochs_and_retires_but_nothing_stale() {
let newer = ChangelogConfig {
epoch: 3,
draining: vec![Generation {
+ cluster: None,
topic: "personhog_updates_128".into(),
partitions: 128,
epoch: 2,
@@ -239,6 +241,7 @@ async fn a_severed_watch_still_adopts_the_flip_through_reconcile() {
proxy.sever();
direct
.put_changelog_config(&ChangelogConfig {
+ cluster: None,
topic: "personhog_updates_128".into(),
partitions: 128,
epoch: 2,
diff --git a/rust/personhog-coordination/tests/migration.rs b/rust/personhog-coordination/tests/migration.rs
index 9611427e4b82..47f0a08903ef 100644
--- a/rust/personhog-coordination/tests/migration.rs
+++ b/rust/personhog-coordination/tests/migration.rs
@@ -9,9 +9,9 @@ use personhog_coordination::pod::{PodConfig, PodHandle};
use personhog_coordination::store::PersonhogStore;
use personhog_coordination::strategy::StickyBalancedStrategy;
use personhog_coordination::types::{
- AssignmentPrecondition, AssignmentStatus, ChangelogConfig, ChangelogTarget, DrainReport,
- Generation, HandoffPhase, HandoffState, MigrationPhase, MigrationRequest, MigrationState,
- PartitionAssignment, SealAck,
+ AssignmentPrecondition, AssignmentStatus, ChangelogConfig, ChangelogTarget, ClusterEndpoint,
+ DrainReport, Generation, HandoffPhase, HandoffState, MigrationPhase, MigrationRequest,
+ MigrationState, PartitionAssignment, SealAck,
};
use tokio_util::sync::CancellationToken;
@@ -175,6 +175,7 @@ async fn an_acquisition_parks_until_the_config_reaches_the_handoffs_epoch() {
store
.put_changelog_config(&ChangelogConfig {
+ cluster: None,
topic: TOPIC.to_string(),
partitions: PARTITIONS,
epoch: 2,
@@ -196,16 +197,31 @@ async fn an_acquisition_parks_until_the_config_reaches_the_handoffs_epoch() {
// ── The saga ────────────────────────────────────────────────────
const TOPIC_V2: &str = "personhog_updates_test_v2";
+const TOPIC_V3: &str = "personhog_updates_test_v3";
+
+fn endpoint(name: &str) -> ClusterEndpoint {
+ ClusterEndpoint {
+ name: name.to_string(),
+ hosts: format!("{name}:9092"),
+ tls: false,
+ }
+}
+
+fn dedicated() -> ClusterEndpoint {
+ endpoint("dedicated")
+}
fn migration(id: &str, to_partitions: u32) -> MigrationState {
let now_ms = now_ms();
MigrationState {
id: id.to_string(),
from: ChangelogTarget {
+ cluster: None,
topic: TOPIC.to_string(),
partitions: PARTITIONS,
},
to: ChangelogTarget {
+ cluster: None,
topic: TOPIC_V2.to_string(),
partitions: to_partitions,
},
@@ -362,7 +378,37 @@ async fn a_grow_migration_restarts_every_partition_over_the_new_changelog() {
assert!(store.remove_changelog_retire_group(group).await.unwrap());
}
- assert!(store.create_migration(&migration("m-1", 8)).await.unwrap());
+ let (live, rev) = store
+ .get_changelog_config_with_mod_revision()
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(!store
+ .set_changelog_cluster(&live, rev - 1, &endpoint("ingestion"))
+ .await
+ .unwrap());
+ assert!(store
+ .set_changelog_cluster(&live, rev, &endpoint("ingestion"))
+ .await
+ .unwrap());
+ let (named, rev) = store
+ .get_changelog_config_with_mod_revision()
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ (named.cluster.clone(), named.epoch),
+ (Some(endpoint("ingestion")), 1)
+ );
+ assert!(!store
+ .set_changelog_cluster(&named, rev, &dedicated())
+ .await
+ .unwrap());
+
+ let mut grow = migration("m-1", 8);
+ grow.from = named.target();
+ grow.to.cluster = Some(dedicated());
+ assert!(store.create_migration(&grow).await.unwrap());
wait_for_phase(&store, MigrationPhase::Sealing).await;
for h in store.list_handoffs().await.unwrap() {
assert_eq!(h.held_by.as_deref(), Some("m-1"), "{h:?}");
@@ -389,12 +435,14 @@ async fn a_grow_migration_restarts_every_partition_over_the_new_changelog() {
let config = store.get_changelog_config().await.unwrap().unwrap();
assert_eq!(config.topic, TOPIC_V2);
assert_eq!(config.partitions, 8);
+ assert_eq!(config.cluster, Some(dedicated()));
assert_eq!(config.epoch, 2);
assert_eq!(config.writer_group, "writer");
assert_eq!(config.retire_groups, vec!["relay".to_string()]);
assert_eq!(
config.draining,
vec![Generation {
+ cluster: Some(endpoint("ingestion")),
topic: TOPIC.to_string(),
partitions: PARTITIONS,
epoch: 1,
@@ -448,6 +496,35 @@ async fn a_grow_migration_restarts_every_partition_over_the_new_changelog() {
.unwrap()
.draining
.is_empty());
+
+ let live = store.get_changelog_config().await.unwrap().unwrap();
+ let mut onward = migration("m-2", 8);
+ onward.from = live.target();
+ onward.to = ChangelogTarget {
+ cluster: Some(endpoint("onward")),
+ topic: TOPIC_V3.to_string(),
+ partitions: 8,
+ };
+ assert!(store.create_migration(&onward).await.unwrap());
+ wait_for_phase(&store, MigrationPhase::Sealing).await;
+ for pod in ["writer-0", "writer-1"] {
+ ack_seal(&store, "m-2", pod, 0..8).await;
+ }
+ assert_eq!(
+ wait_for_archive(&store, "m-2").await.phase,
+ MigrationPhase::Complete
+ );
+ let config = store.get_changelog_config().await.unwrap().unwrap();
+ assert_eq!(config.cluster, Some(endpoint("onward")));
+ assert_eq!(
+ config.draining,
+ vec![Generation {
+ cluster: Some(dedicated()),
+ topic: TOPIC_V2.to_string(),
+ partitions: 8,
+ epoch: 2,
+ }]
+ );
cancel.cancel();
}
@@ -467,6 +544,15 @@ async fn a_shrink_migration_dissolves_the_partitions_past_the_new_space() {
wait_for_steady_state(&store, PARTITIONS).await;
assert!(store.create_migration(&migration("m-1", 2)).await.unwrap());
+ let (live, rev) = store
+ .get_changelog_config_with_mod_revision()
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(!store
+ .set_changelog_cluster(&live, rev, &dedicated())
+ .await
+ .unwrap());
wait_for_phase(&store, MigrationPhase::Sealing).await;
ack_seal_all(&store, "m-1", &["writer-0", "writer-1"]).await;
@@ -675,12 +761,14 @@ const TOPIC_V0: &str = "personhog_updates_test_v0";
fn draining_config(retire_groups: &[&str]) -> ChangelogConfig {
ChangelogConfig {
+ cluster: None,
topic: TOPIC.to_string(),
partitions: PARTITIONS,
epoch: 1,
writer_group: "writer".to_string(),
retire_groups: retire_groups.iter().map(|g| g.to_string()).collect(),
draining: vec![Generation {
+ cluster: None,
topic: TOPIC_V0.to_string(),
partitions: PARTITIONS,
epoch: 0,
@@ -938,6 +1026,7 @@ async fn a_plan_lands_only_on_the_basis_it_was_read_on() {
// The saga flips and is archived: the migration key is absent again.
let flipped = ChangelogConfig {
+ cluster: None,
topic: TOPIC_V2.to_string(),
partitions: 8,
epoch: 2,
@@ -1038,10 +1127,12 @@ fn request(id: &str, to_partitions: u32) -> MigrationRequest {
MigrationRequest {
id: id.to_string(),
from: ChangelogTarget {
+ cluster: None,
topic: TOPIC.to_string(),
partitions: PARTITIONS,
},
to: ChangelogTarget {
+ cluster: None,
topic: TOPIC_V2.to_string(),
partitions: to_partitions,
},
@@ -1173,6 +1264,15 @@ async fn a_request_waits_holding_nothing_until_the_fleet_is_quiet() {
.unwrap()
.iter()
.all(|h| !h.is_held()));
+ let (live, rev) = store
+ .get_changelog_config_with_mod_revision()
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(!store
+ .set_changelog_cluster(&live, rev, &endpoint("ingestion"))
+ .await
+ .unwrap());
// The stand-in dies; the planner clears its handoffs, then the saga starts quiet.
store.revoke_lease(lease).await.unwrap();
@@ -1252,6 +1352,7 @@ async fn a_request_from_a_skewed_clock_is_not_expired_on_arrival() {
async fn only_a_completed_migration_retires_its_source_topic() {
let Fleet { store, cancel, .. } = fleet("migration-retired-topic").await;
let target = |topic: &str| ChangelogTarget {
+ cluster: None,
topic: topic.to_string(),
partitions: 8,
};
@@ -1414,7 +1515,7 @@ async fn a_follower_reports_each_generation_it_proves_drained() {
.select_topic(&draining_config(&[]), |_| async { Ok(true) })
.await
.unwrap();
- assert_eq!(topic, TOPIC);
+ assert_eq!(topic.topic, TOPIC);
let reporter = Reporter {
group: "writer".to_string(),
diff --git a/rust/personhog-leader/src/cache/dirty_index.rs b/rust/personhog-leader/src/cache/dirty_index.rs
index ab96e2e18e3d..bae29a8b6490 100644
--- a/rust/personhog-leader/src/cache/dirty_index.rs
+++ b/rust/personhog-leader/src/cache/dirty_index.rs
@@ -4,6 +4,7 @@ use std::sync::{Arc, Mutex};
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
+use personhog_coordination::types::ClusterEndpoint;
use super::PersonCacheKey;
@@ -11,6 +12,7 @@ use super::PersonCacheKey;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Stream {
pub topic: Arc<str>,
+ pub cluster: Option<Arc<ClusterEndpoint>>,
pub partition: u32,
}
@@ -367,6 +369,7 @@ mod tests {
fn stream(partition: u32) -> Stream {
Stream {
+ cluster: None,
topic: Arc::from("personhog_updates"),
partition,
}
@@ -603,6 +606,7 @@ mod tests {
fn streams_under_one_partition_prune_apart_and_clear_together() {
let index = DirtyIndex::new(1_000);
let old = Stream {
+ cluster: None,
topic: Arc::from("personhog_updates_old"),
partition: 1,
};
@@ -630,6 +634,7 @@ mod tests {
#[test]
fn pruning_a_stream_terminates_when_a_key_was_re_marked_on_a_newer_stream() {
let old = Stream {
+ cluster: None,
topic: Arc::from("personhog_updates_old"),
partition: 0,
};
@@ -667,6 +672,7 @@ mod tests {
fn a_key_that_moved_home_survives_the_old_homes_clear_and_prune() {
// Shrink 8 -> 4: old partition 5 and new partition 1 share keys.
let old5 = Stream {
+ cluster: None,
topic: Arc::from("personhog_updates_old"),
partition: 5,
};
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index 6c6b38db9273..c5931b6fd8bf 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -9,7 +9,7 @@ use personhog_coordination::authority::AuthorityClock;
use personhog_coordination::changelog::{warm_sources, LiveChangelog};
use personhog_coordination::error::{Error, Result};
use personhog_coordination::pod::HandoffHandler;
-use personhog_coordination::types::ChangelogConfig;
+use personhog_coordination::types::{ChangelogConfig, ClusterEndpoint};
use tracing::{error, info};
use crate::cache::{DirtyIndex, PartitionedCache};
@@ -30,6 +30,7 @@ pub struct Capture {
pub config: ChangelogConfig,
/// The config's topic, shared so the write path names it without allocating.
pub topic: Arc<str>,
+ pub cluster: Option<Arc<ClusterEndpoint>>,
}
/// Per-partition captures, shared by the handler and the service.
@@ -258,6 +259,7 @@ impl HandoffHandler for LeaderHandoffHandler {
partition,
Capture {
topic: Arc::from(config.topic.as_str()),
+ cluster: config.cluster.clone().map(Arc::new),
config: config.clone(),
},
);
@@ -636,6 +638,7 @@ mod tests {
let handler = handler();
let config = |topic: &str, partitions: u32, epoch: u64| ChangelogConfig {
+ cluster: None,
topic: topic.to_string(),
partitions,
epoch,
@@ -648,6 +651,7 @@ mod tests {
handler.captures.insert(
partition,
Capture {
+ cluster: None,
topic: Arc::from(cfg.topic.as_str()),
config: cfg,
},
@@ -661,6 +665,7 @@ mod tests {
.find(|k| partition_for_person(k.team_id, k.person_id, 8) == 5)
.unwrap();
let old5 = Stream {
+ cluster: None,
topic: Arc::from("old"),
partition: 5,
};
diff --git a/rust/personhog-leader/src/fencing.rs b/rust/personhog-leader/src/fencing.rs
index 0baa41e3edc7..84936bb47e2a 100644
--- a/rust/personhog-leader/src/fencing.rs
+++ b/rust/personhog-leader/src/fencing.rs
@@ -64,6 +64,7 @@ use personhog_coordination::authority::AuthorityClock;
use crate::config::{FENCING_ABORT_ATTEMPTS, FENCING_COMMIT_ATTEMPTS};
use crate::inflight::InflightTracker;
use crate::kafka::changelog_message_key;
+use crate::warming::changelog_kafka;
/// The fencing scope is the partition: every owner of partition `p`
/// shares its lane ids, so a new owner's init fences the old one.
@@ -947,17 +948,15 @@ impl FencedChangelogProducers {
/// Each producer's queue is its share of the aggregate under the generation's partition count.
fn dial(&self, partition: u32, target: &ChangelogTarget) -> Dial {
let producers = fenced_producer_count(target.partitions, self.lanes);
+ let kafka = changelog_kafka(&self.kafka, target.cluster.as_ref());
Dial {
kafka: KafkaConfig {
- kafka_producer_queue_mib: queue_share(
- self.kafka.kafka_producer_queue_mib,
- producers,
- ),
+ kafka_producer_queue_mib: queue_share(kafka.kafka_producer_queue_mib, producers),
kafka_producer_queue_messages: queue_share(
- self.kafka.kafka_producer_queue_messages,
+ kafka.kafka_producer_queue_messages,
producers,
),
- ..self.kafka.clone()
+ ..kafka
},
topic: target.topic.clone(),
partition,
@@ -2523,7 +2522,7 @@ mod tests {
use envconfig::Envconfig;
#[test]
- fn a_producer_queue_is_its_share_under_the_generation_it_dials() {
+ fn a_producer_dials_its_generations_cluster_with_its_queue_share() {
let mut kafka = KafkaConfig::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
kafka.kafka_producer_queue_mib = 1024;
kafka.kafka_producer_queue_messages = 64_000;
@@ -2541,6 +2540,7 @@ mod tests {
let target = ChangelogTarget {
topic: format!("g{partitions}"),
partitions,
+ cluster: None,
};
let dial = producers.dial(0, &target);
assert_eq!(
@@ -2552,6 +2552,24 @@ mod tests {
"{partitions} partitions"
);
}
+ let moved = ChangelogTarget {
+ topic: "g8".to_string(),
+ partitions: 8,
+ cluster: Some(personhog_coordination::types::ClusterEndpoint {
+ name: "dedicated".to_string(),
+ hosts: "d:9092".to_string(),
+ tls: true,
+ }),
+ };
+ let dial = producers.dial(0, &moved);
+ assert_eq!(
+ (
+ dial.kafka.kafka_hosts.as_str(),
+ dial.kafka.kafka_tls,
+ dial.kafka.kafka_producer_queue_mib
+ ),
+ ("d:9092", true, 64)
+ );
}
/// The verdict the caller acts on, as a truth table over the two
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index 3ee80987c3c0..add1cd4842ba 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -48,7 +48,7 @@ use personhog_leader::recovery::{ChangelogRecovery, RecoveryConfig};
use personhog_leader::service::{sweep_idle_locks, PersonHogLeaderService, PropertySizeLimits};
use personhog_leader::settle::{prune_and_settle_tick, retired_topic};
use personhog_leader::warming::{
- changelog_partition_count, WarmClientPools, WarmingConfig, WarmingRetryPolicy,
+ changelog_kafka, changelog_partition_count, WarmClientPools, WarmingConfig, WarmingRetryPolicy,
};
use personhog_leader::warnings;
@@ -380,10 +380,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
};
let changelog_topic = loaded.topic.clone();
let num_partitions = loaded.partitions;
- let topic_partitions =
- changelog_partition_count(&config.kafka, &changelog_topic, Duration::from_secs(10))
- .await
- .expect("Failed to read the changelog topic's metadata");
+ let live_cluster = loaded.cluster.clone();
+ let topic_partitions = changelog_partition_count(
+ &changelog_kafka(&config.kafka, live_cluster.as_ref()),
+ &changelog_topic,
+ Duration::from_secs(10),
+ )
+ .await
+ .expect("Failed to read the changelog topic's metadata");
assert_eq!(
topic_partitions, num_partitions,
"changelog topic {changelog_topic} has {topic_partitions} partitions but the config says {num_partitions}"
@@ -662,10 +666,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// this stays best-effort.
{
let warm_slots = pod_config.warm_concurrency;
+ let live_pools = warm_pools.on(live_cluster.as_ref());
let warm_up = async {
tokio::join!(
- warm_pools.offsets.warm_up(warm_slots),
- warm_pools.warming.warm_up(warm_slots),
+ live_pools.offsets.warm_up(warm_slots),
+ live_pools.warming.warm_up(warm_slots),
);
};
if timeout(POOL_WARM_UP_DEADLINE, warm_up).await.is_err() {
@@ -836,7 +841,7 @@ async fn run_dirty_index_prune_loop(
&dirty_index,
&cache,
&locks,
- &pools.offsets,
+ &pools,
offsets_timeout,
|topic| retired_topic(&changelog.current(), &writer_group, topic),
)
diff --git a/rust/personhog-leader/src/migration.rs b/rust/personhog-leader/src/migration.rs
index 631b65331721..b3b10de296a7 100644
--- a/rust/personhog-leader/src/migration.rs
+++ b/rust/personhog-leader/src/migration.rs
@@ -199,6 +199,7 @@ impl SealDuty {
let overdue = seal_overdue(migration, assignment_coordination::util::now_millis());
let targets = self.targets(migration, overdue).await?;
let topic = migration.from.topic.as_str();
+ let cluster = migration.from.cluster.as_ref().map(|c| c.name.as_str());
let pending: Vec<u32> = targets
.iter()
.copied()
@@ -224,14 +225,16 @@ impl SealDuty {
let (partition, result) = joined.map_err(|e| format!("seal join: {e}"))?;
match result {
Ok(path) => {
- info!(partition, %topic, path, "sealed the old changelog partition");
+ info!(partition, %topic, ?cluster, path, "sealed the old changelog partition");
sealed.insert((migration.id.clone(), partition));
// Acked as it lands; a failed write is retried by the next ack.
if let Err(e) = self.ack(migration, sealed, acked).await {
warn!(partition, error = %e, "seal ack failed; the next ack carries it");
}
}
- Err(e) => warn!(partition, %topic, error = %e, "seal failed; retrying"),
+ Err(e) => {
+ warn!(partition, %topic, ?cluster, error = %e, "seal failed; retrying")
+ }
}
}
}
diff --git a/rust/personhog-leader/src/recovery.rs b/rust/personhog-leader/src/recovery.rs
index 486f28dbec7d..a342cc652bf6 100644
--- a/rust/personhog-leader/src/recovery.rs
+++ b/rust/personhog-leader/src/recovery.rs
@@ -1,5 +1,5 @@
-use std::collections::VecDeque;
-use std::sync::Mutex;
+use std::collections::{HashMap, VecDeque};
+use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use common_kafka::config::KafkaConfig;
@@ -11,10 +11,11 @@ use rdkafka::{Offset, TopicPartitionList};
use tokio::sync::Semaphore;
use tokio::time::timeout;
+use personhog_coordination::types::ClusterEndpoint;
use personhog_proto::personhog::types::v1::Person;
use crate::cache::{CachedPerson, DirtyMark, PersonCacheKey};
-use crate::warming::make_consumer;
+use crate::warming::{changelog_kafka, make_consumer};
/// How long to wait before retrying a transiently failed fetch.
const RETRY_BACKOFF: Duration = Duration::from_millis(100);
@@ -73,8 +74,10 @@ enum FetchError {
/// empty pool.
pub struct ChangelogRecovery {
recv_timeout: Duration,
- idle: Mutex<VecDeque<StreamConsumer>>,
+ idle: Mutex<HashMap<Option<Arc<ClusterEndpoint>>, VecDeque<StreamConsumer>>>,
permits: Semaphore,
+ kafka: KafkaConfig,
+ group: String,
}
impl ChangelogRecovery {
@@ -92,8 +95,10 @@ impl ChangelogRecovery {
}
Ok(Self {
recv_timeout: cfg.recv_timeout,
- idle: Mutex::new(idle),
+ idle: Mutex::new(HashMap::from([(None, idle)])),
permits: Semaphore::new(cfg.pool_size),
+ kafka: cfg.kafka,
+ group,
})
}
@@ -103,7 +108,10 @@ impl ChangelogRecovery {
/// tail), returns it to the idle deque, and only then releases the
/// permit — so a slot never opens before its consumer is home, on
/// every path including cancellation of the awaiting future.
- async fn checkout(&self) -> Result<PooledConsumer<'_>, String> {
+ async fn checkout(
+ &self,
+ cluster: Option<&Arc<ClusterEndpoint>>,
+ ) -> Result<PooledConsumer<'_>, String> {
let wait_start = Instant::now();
let permit = self
.permits
@@ -112,14 +120,25 @@ impl ChangelogRecovery {
.map_err(|_| "recovery pool closed".to_string())?;
histogram!("personhog_leader_recovery_pool_wait_ms")
.record(wait_start.elapsed().as_secs_f64() * 1000.0);
- let consumer = self
+ let idle = self
.idle
.lock()
.expect("recovery pool lock poisoned")
- .pop_front()
- .expect("a permit guarantees an idle consumer");
+ .get_mut(&cluster.cloned())
+ .and_then(VecDeque::pop_front);
+ // The default deque never runs dry under a permit: only default
+ // checkouts take from it, and at most pool_size are out at once.
+ let consumer = match (idle, cluster) {
+ (Some(consumer), _) => consumer,
+ (None, None) => unreachable!("a permit guarantees an idle default consumer"),
+ (None, Some(other)) => {
+ make_consumer(&changelog_kafka(&self.kafka, Some(other)), &self.group)
+ .map_err(|e| format!("create recovery consumer for {}: {e}", other.name))?
+ }
+ };
Ok(PooledConsumer {
pool: self,
+ cluster: cluster.cloned(),
consumer: Some(consumer),
_permit: permit,
})
@@ -142,7 +161,7 @@ impl ChangelogRecovery {
let partition_i32 = i32::try_from(partition)
.map_err(|_| format!("partition {partition} exceeds i32::MAX"))?;
- let consumer = self.checkout().await?;
+ let consumer = self.checkout(mark.stream.cluster.as_ref()).await?;
// Each attempt repositions with a fresh assign: it starts fetching
// at the target immediately (repositioning a live stream via seek
@@ -232,6 +251,7 @@ impl ChangelogRecovery {
/// field drops last).
struct PooledConsumer<'a> {
pool: &'a ChangelogRecovery,
+ cluster: Option<Arc<ClusterEndpoint>>,
consumer: Option<StreamConsumer>,
_permit: tokio::sync::SemaphorePermit<'a>,
}
@@ -254,6 +274,8 @@ impl Drop for PooledConsumer<'_> {
.idle
.lock()
.expect("recovery pool lock poisoned")
+ .entry(self.cluster.take())
+ .or_default()
.push_back(consumer);
}
}
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index 85d860bc0d20..59cd697dcabb 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -665,12 +665,16 @@ impl Committer {
/// The producer was acquired on the capture's topic, so its records land there.
#[allow(clippy::result_large_err)]
fn stream_of(&self, partition: u32) -> Result<Stream, Status> {
- let topic = self
+ let (topic, cluster) = self
.captures
.get(&partition)
- .map(|c| Arc::clone(&c.topic))
+ .map(|c| (Arc::clone(&c.topic), c.cluster.clone()))
.ok_or_else(|| not_served(partition))?;
- Ok(Stream { topic, partition })
+ Ok(Stream {
+ topic,
+ cluster,
+ partition,
+ })
}
async fn commit(
@@ -2128,6 +2132,7 @@ mod tests {
Arc::new(DashMap::from_iter([(
0,
crate::coordination::Capture {
+ cluster: None,
topic: Arc::from("personhog_updates"),
config: personhog_coordination::types::ChangelogConfig::new(
"personhog_updates",
diff --git a/rust/personhog-leader/src/settle.rs b/rust/personhog-leader/src/settle.rs
index 6bcbbe4484c8..69bbd85276ce 100644
--- a/rust/personhog-leader/src/settle.rs
+++ b/rust/personhog-leader/src/settle.rs
@@ -7,13 +7,15 @@ use std::time::{Duration, Instant};
use dashmap::DashMap;
use metrics::{counter, histogram};
-use personhog_coordination::types::ChangelogConfig;
+use personhog_coordination::types::{ChangelogConfig, ClusterEndpoint};
use tokio::sync::Mutex;
use crate::cache::{
CachedVersion, DirtyIndex, DirtyMark, PartitionedCache, PersonCacheKey, Stream,
};
-use crate::warming::{fetch_writer_committed_offsets, ConsumerPool};
+use crate::warming::{fetch_writer_committed_offsets, WarmClientPools};
+
+type MarkedTopic = (Option<Arc<ClusterEndpoint>>, Vec<u32>);
/// A topic listed neither live nor draining was retired, which proves the config's
/// writer group applied it. The proof covers this leader only when that group is its own.
@@ -30,7 +32,7 @@ pub async fn prune_and_settle_tick(
dirty_index: &DirtyIndex,
cache: &PartitionedCache,
locks: &DashMap<PersonCacheKey, Arc<Mutex<()>>>,
- offsets_pool: &ConsumerPool,
+ pools: &WarmClientPools,
offsets_timeout: Duration,
retired: impl Fn(&str) -> bool,
) -> Vec<StreamLag> {
@@ -46,18 +48,21 @@ pub async fn prune_and_settle_tick(
.or_insert_with(|| retired(&stream.topic));
}
// One OffsetFetch per topic a live mark lives on.
- let mut by_topic: HashMap<Arc<str>, Vec<u32>> = HashMap::new();
+ let mut by_topic: HashMap<Arc<str>, MarkedTopic> = HashMap::new();
for (_, stream) in &targets {
if retired_topics[&stream.topic] {
continue;
}
- let partitions = by_topic.entry(Arc::clone(&stream.topic)).or_default();
+ let (_, partitions) = by_topic
+ .entry(Arc::clone(&stream.topic))
+ .or_insert_with(|| (stream.cluster.clone(), Vec::new()));
if !partitions.contains(&stream.partition) {
partitions.push(stream.partition);
}
}
let mut committed: HashMap<Arc<str>, HashMap<u32, i64>> = HashMap::new();
- for (topic, partitions) in by_topic {
+ for (topic, (cluster, partitions)) in by_topic {
+ let offsets_pool = &pools.on(cluster.as_deref()).offsets;
match fetch_writer_committed_offsets(offsets_pool, &topic, &partitions, offsets_timeout)
.await
{
@@ -183,9 +188,11 @@ mod tests {
epoch: 2,
writer_group: writer_group.to_string(),
retire_groups: vec![],
+ cluster: None,
draining: draining
.iter()
.map(|t| Generation {
+ cluster: None,
topic: t.to_string(),
partitions: 4,
epoch: 1,
@@ -257,6 +264,7 @@ mod tests {
partition: 0,
stream: Stream {
topic: Arc::from("personhog_updates"),
+ cluster: None,
partition: 0,
},
is_deleted: true,
diff --git a/rust/personhog-leader/src/warming.rs b/rust/personhog-leader/src/warming.rs
index 2267faede44d..92e75014025e 100644
--- a/rust/personhog-leader/src/warming.rs
+++ b/rust/personhog-leader/src/warming.rs
@@ -15,6 +15,7 @@ use tokio::time::{sleep, timeout};
use personhog_common::partitioning::partition_for_person;
use personhog_coordination::changelog::WarmSource;
use personhog_coordination::error::{Error as CoordError, Result as CoordResult};
+use personhog_coordination::types::ClusterEndpoint;
use personhog_proto::personhog::types::v1::Person;
use crate::cache::{CachedPerson, DirtyIndex, DirtyMark, PartitionedCache, PersonCacheKey, Stream};
@@ -308,17 +309,24 @@ impl ConsumerPool {
}
}
-/// The two client pools the warm path and the dirty-index prune share.
+pub fn changelog_kafka(base: &KafkaConfig, cluster: Option<&ClusterEndpoint>) -> KafkaConfig {
+ match cluster {
+ Some(cluster) => base.with_endpoint(&cluster.hosts, cluster.tls),
+ None => base.clone(),
+ }
+}
+
+/// One cluster's two client pools, which the warm path and the dirty-index prune share.
/// Separate pools because a client's group id is fixed at construction:
/// offset queries must carry the writer's group id to OffsetFetch its
/// committed offsets, while warming consumers carry their own.
-pub struct WarmClientPools {
+pub struct ClusterPools {
pub offsets: ConsumerPool,
pub warming: ConsumerPool,
}
-impl WarmClientPools {
- pub fn new(kafka: &KafkaConfig, pod_name: &str, writer_group: &str) -> Self {
+impl ClusterPools {
+ fn new(kafka: &KafkaConfig, pod_name: &str, writer_group: &str) -> Self {
Self {
offsets: ConsumerPool::new(kafka.clone(), writer_group.to_string(), "offsets"),
warming: ConsumerPool::new(
@@ -330,6 +338,41 @@ impl WarmClientPools {
}
}
+pub struct WarmClientPools {
+ base: KafkaConfig,
+ pod_name: String,
+ writer_group: String,
+ default: Arc<ClusterPools>,
+ named: StdMutex<HashMap<ClusterEndpoint, Arc<ClusterPools>>>,
+}
+
+impl WarmClientPools {
+ pub fn new(kafka: &KafkaConfig, pod_name: &str, writer_group: &str) -> Self {
+ Self {
+ base: kafka.clone(),
+ pod_name: pod_name.to_string(),
+ writer_group: writer_group.to_string(),
+ default: Arc::new(ClusterPools::new(kafka, pod_name, writer_group)),
+ named: StdMutex::new(HashMap::new()),
+ }
+ }
+
+ pub fn on(&self, cluster: Option<&ClusterEndpoint>) -> Arc<ClusterPools> {
+ let Some(cluster) = cluster else {
+ return Arc::clone(&self.default);
+ };
+ let mut named = self.named.lock().unwrap();
+ let pools = named.entry(cluster.clone()).or_insert_with(|| {
+ Arc::new(ClusterPools::new(
+ &changelog_kafka(&self.base, Some(cluster)),
+ &self.pod_name,
+ &self.writer_group,
+ ))
+ });
+ Arc::clone(pools)
+ }
+}
+
/// Query the writer consumer group's committed offset for a partition.
/// Returns `None` if the writer has no commit yet for the partition
/// (typical for a freshly-created topic).
@@ -463,8 +506,10 @@ async fn warm_source(
})?;
let stream = Stream {
topic: Arc::clone(&source.topic),
+ cluster: source.cluster.clone().map(Arc::new),
partition: source.partition,
};
+ let pools = pools.on(source.cluster.as_ref());
// Arc because the watermark retry closure needs its own handle for
// the blocking pool; sole ownership returns once the retries finish.
@@ -712,10 +757,11 @@ pub async fn warm_from_sources(
// that generation's marked tail.
let mut committed = Vec::with_capacity(sources.len());
for source in sources {
+ let source_pools = pools.on(source.cluster.as_ref());
committed.push(
with_warm_retry("committed_offset", partition, cfg.retry, || async {
fetch_writer_committed_offset(
- &pools.offsets,
+ &source_pools.offsets,
&source.topic,
source.partition,
cfg.committed_offsets_timeout,
@@ -765,6 +811,21 @@ mod tests {
use super::*;
+ #[test]
+ fn a_named_cluster_gets_its_own_pools_once() {
+ use envconfig::Envconfig;
+ let kafka = KafkaConfig::init_from_hashmap(&HashMap::new()).unwrap();
+ let pools = WarmClientPools::new(&kafka, "pod", "writer");
+ let dedicated = ClusterEndpoint {
+ name: "dedicated".to_string(),
+ hosts: "d:9092".to_string(),
+ tls: false,
+ };
+ let named = pools.on(Some(&dedicated));
+ assert!(Arc::ptr_eq(&named, &pools.on(Some(&dedicated))));
+ assert!(!Arc::ptr_eq(&named, &pools.on(None)));
+ }
+
const TEST_RETRY_POLICY: WarmingRetryPolicy = WarmingRetryPolicy {
max_attempts: 3,
initial_backoff: Duration::from_millis(500),
@@ -817,6 +878,7 @@ mod tests {
partition: 0,
stream: Stream {
topic: Arc::from("personhog_updates"),
+ cluster: None,
partition: 0,
},
is_deleted: false,
@@ -865,6 +927,7 @@ mod tests {
partition: 0,
stream: Stream {
topic: Arc::from("personhog_updates"),
+ cluster: None,
partition: 0,
},
is_deleted: false,
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index 8d1d867ae2a2..74f7e2e62d36 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -59,6 +59,14 @@ use tonic::transport::{Channel, Server};
pub const ETCD_ENDPOINT: &str = "http://localhost:2379";
// Not `localhost`: it also resolves to `::1`, where the broker refuses, and readers fail on that.
pub const KAFKA_BOOTSTRAP: &str = "127.0.0.1:9092";
+
+/// A second broker; only the e2e gate job starts one, so cross-cluster cases run only when it is set.
+pub fn secondary_kafka_bootstrap() -> Option<String> {
+ std::env::var("PERSONHOG_TEST_SECONDARY_KAFKA")
+ .ok()
+ .filter(|hosts| !hosts.is_empty())
+}
+
pub const PERSONS_DB_URL: &str = "postgres://posthog:posthog@localhost:5432/posthog_persons";
pub const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
pub const POLL_INTERVAL: Duration = Duration::from_millis(100);
@@ -331,6 +339,10 @@ pub fn test_recovery(kafka_bootstrap: &str) -> Arc<ChangelogRecovery> {
/// Create a producer against local Kafka for e2e tests.
pub async fn create_local_kafka_producer() -> FutureProducer<KafkaContext> {
+ create_kafka_producer_on(KAFKA_BOOTSTRAP).await
+}
+
+pub async fn create_kafka_producer_on(bootstrap: &str) -> FutureProducer<KafkaContext> {
let registry = HealthRegistry::new("test");
let handle = registry
.register("kafka".to_string(), Duration::from_secs(30))
@@ -340,7 +352,7 @@ pub async fn create_local_kafka_producer() -> FutureProducer<KafkaContext> {
kafka_producer_queue_mib: 50,
kafka_message_timeout_ms: 5000,
kafka_compression_codec: "none".to_string(),
- kafka_hosts: KAFKA_BOOTSTRAP.to_string(),
+ kafka_hosts: bootstrap.to_string(),
kafka_tls: false,
kafka_producer_queue_messages: 1000,
kafka_client_rack: String::new(),
@@ -383,12 +395,13 @@ pub async fn local_warnings_producer(topic: &str, throttle: WarningThrottle) ->
/// of a shared one would fence each other.
pub struct TestTopic {
pub topic: String,
+ bootstrap: String,
}
impl TestTopic {
/// The shape `MockCluster` offered, so call sites keep working.
pub fn bootstrap_servers(&self) -> String {
- KAFKA_BOOTSTRAP.to_string()
+ self.bootstrap.clone()
}
}
@@ -398,12 +411,13 @@ impl TestTopic {
impl Drop for TestTopic {
fn drop(&mut self) {
let topic = self.topic.clone();
+ let bootstrap = self.bootstrap.clone();
let cleanup = std::thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("cleanup runtime");
- runtime.block_on(delete_broker_topic(&topic));
+ runtime.block_on(delete_broker_topic_on(&bootstrap, &topic));
});
drop(cleanup.join());
}
@@ -412,8 +426,12 @@ impl Drop for TestTopic {
/// Best effort: a leftover topic costs the next run partitions, not
/// correctness, and a failing test has already said what went wrong.
pub async fn delete_broker_topic(topic: &str) {
+ delete_broker_topic_on(KAFKA_BOOTSTRAP, topic).await;
+}
+
+pub async fn delete_broker_topic_on(bootstrap: &str, topic: &str) {
let Ok(admin) = ClientConfig::new()
- .set("bootstrap.servers", KAFKA_BOOTSTRAP)
+ .set("bootstrap.servers", bootstrap)
.create::<AdminClient<DefaultClientContext>>()
else {
return;
@@ -452,16 +470,21 @@ pub async fn create_test_kafka() -> TestTopic {
/// `create_test_kafka` with a partition count the caller pins.
pub async fn create_test_kafka_with_partitions(partitions: i32) -> TestTopic {
- let topic = unique_topic();
- create_broker_topic(&topic, partitions).await;
- TestTopic { topic }
+ owned_broker_topic(partitions).await
}
/// A topic of this test's own, deleted when the handle drops.
pub async fn owned_broker_topic(partitions: i32) -> TestTopic {
+ owned_broker_topic_on(KAFKA_BOOTSTRAP, partitions).await
+}
+
+pub async fn owned_broker_topic_on(bootstrap: &str, partitions: i32) -> TestTopic {
let topic = unique_topic();
- create_broker_topic(&topic, partitions).await;
- TestTopic { topic }
+ create_broker_topic_on(bootstrap, &topic, partitions).await;
+ TestTopic {
+ topic,
+ bootstrap: bootstrap.to_string(),
+ }
}
/// A topic name no other test shares.
@@ -472,8 +495,12 @@ pub fn unique_topic() -> String {
/// Auto-creation would use the broker's default partition count, which
/// is not the one routing and warming expect.
pub async fn create_broker_topic(topic: &str, partitions: i32) {
+ create_broker_topic_on(KAFKA_BOOTSTRAP, topic, partitions).await;
+}
+
+pub async fn create_broker_topic_on(bootstrap: &str, topic: &str, partitions: i32) {
let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
- .set("bootstrap.servers", KAFKA_BOOTSTRAP)
+ .set("bootstrap.servers", bootstrap)
.create()
.expect("admin client");
let new_topic = NewTopic::new(topic, partitions, TopicReplication::Fixed(1));
@@ -498,6 +525,7 @@ pub async fn fenced_producers_acquired(
) -> Arc<personhog_leader::fencing::FencedChangelogProducers> {
let fenced = Arc::new(test_fenced_producers());
let target = ChangelogTarget {
+ cluster: None,
topic: topic.to_string(),
partitions: partitions as u32,
};
@@ -963,6 +991,7 @@ pub fn live_changelog(topic: &str) -> LiveChangelog {
pub fn target(topic: &str) -> ChangelogTarget {
ChangelogTarget {
+ cluster: None,
topic: topic.to_string(),
partitions: NUM_PARTITIONS,
}
@@ -975,6 +1004,7 @@ pub fn served_captures(topic: &str, partitions: u32) -> ChangelogCaptures {
(0..partitions)
.map(|partition| {
let capture = Capture {
+ cluster: None,
topic: Arc::from(topic),
config: config.clone(),
};
diff --git a/rust/personhog-leader/tests/fencing_integration.rs b/rust/personhog-leader/tests/fencing_integration.rs
index d05640131e56..6d821e2f9a9e 100644
--- a/rust/personhog-leader/tests/fencing_integration.rs
+++ b/rust/personhog-leader/tests/fencing_integration.rs
@@ -12,6 +12,7 @@ use std::time::Duration;
use envconfig::Envconfig;
use personhog_coordination::authority::AuthorityClock;
use personhog_coordination::pod::HandoffHandler;
+use personhog_coordination::types::{ChangelogTarget, ClusterEndpoint};
use personhog_leader::fencing::{
heal_fence, FenceGuard, FencedChangelogProducers, FencedProduceError, FencedProducerConfig,
HealOutcome,
@@ -37,11 +38,15 @@ fn test_person(version: i64) -> Person {
/// Count the records a `read_committed` consumer can see on partition 0
/// — the same isolation the warming path uses.
async fn read_committed_count(topic: &str) -> usize {
+ read_committed_count_on(KAFKA_BOOTSTRAP, topic).await
+}
+
+async fn read_committed_count_on(bootstrap: &str, topic: &str) -> usize {
use rdkafka::consumer::{Consumer, StreamConsumer};
use rdkafka::{ClientConfig, Message, Offset, TopicPartitionList};
let consumer: StreamConsumer = ClientConfig::new()
- .set("bootstrap.servers", KAFKA_BOOTSTRAP)
+ .set("bootstrap.servers", bootstrap)
.set(
"group.id",
format!("fence-abort-probe-{}", uuid::Uuid::new_v4()),
@@ -146,16 +151,31 @@ async fn acquiring_on_another_topic_produces_there_and_discards_a_stale_preconne
}
/// Sealing claims every lane's id on the old topic, so a holder still producing
-/// there is fenced and nothing more lands, on the cold and the prepared path.
+/// there is fenced and nothing more lands, on the cold and the prepared path,
+/// and on the old topic's own cluster when it is not the default one.
#[tokio::test]
async fn a_seal_fences_the_holder_on_the_old_topic() {
- for prepared in [false, true] {
+ let secondary = common::secondary_kafka_bootstrap();
+ let mut cases = vec![(false, None), (true, None)];
+ if let Some(hosts) = &secondary {
+ let old_cluster = ClusterEndpoint {
+ name: "old-cluster".to_string(),
+ hosts: hosts.clone(),
+ tls: false,
+ };
+ cases.extend([
+ (false, Some(old_cluster.clone())),
+ (true, Some(old_cluster)),
+ ]);
+ }
+ for (prepared, cluster) in cases {
let topic = format!("fence_seal_{}", uuid::Uuid::new_v4().simple());
+ let old = ChangelogTarget {
+ cluster: cluster.clone(),
+ ..target(&topic)
+ };
let holder = fenced_producers(2);
- holder
- .acquire(0, &target(&topic))
- .await
- .expect("holder acquires");
+ holder.acquire(0, &old).await.expect("holder acquires");
holder
.produce(0, &test_person(1))
.await
@@ -163,22 +183,27 @@ async fn a_seal_fences_the_holder_on_the_old_topic() {
let sealer = fenced_producers(2);
if prepared {
- sealer.preconnect(0, &target(&topic)).await;
+ sealer.preconnect(0, &old).await;
}
let path = sealer
- .seal(0, &target(&topic))
+ .seal(0, &old)
.await
.expect("the seal claims every lane");
assert_eq!(path, if prepared { "prepared" } else { "cold" });
match holder.produce(0, &test_person(2)).await {
Err(FencedProduceError::Fenced) | Err(FencedProduceError::NotAcquired) => {}
- other => panic!("prepared={prepared}: the holder must be fenced, got {other:?}"),
+ other => panic!(
+ "prepared={prepared} cluster={cluster:?}: the holder must be fenced, got {other:?}"
+ ),
}
+ let bootstrap = cluster
+ .as_ref()
+ .map_or(KAFKA_BOOTSTRAP, |c| c.hosts.as_str());
assert_eq!(
- read_committed_count(&topic).await,
+ read_committed_count_on(bootstrap, &topic).await,
1,
- "prepared={prepared}: nothing lands after the seal"
+ "prepared={prepared} cluster={cluster:?}: nothing lands after the seal"
);
}
}
diff --git a/rust/personhog-leader/tests/integration.rs b/rust/personhog-leader/tests/integration.rs
index 535807270f59..10015eadaf65 100644
--- a/rust/personhog-leader/tests/integration.rs
+++ b/rust/personhog-leader/tests/integration.rs
@@ -2078,6 +2078,7 @@ async fn cancelled_recovery_returns_its_consumer_to_the_pool() {
offset: 0,
partition: 0,
stream: personhog_leader::cache::Stream {
+ cluster: None,
topic: std::sync::Arc::from(mock_cluster.topic.as_str()),
partition: 0,
},
@@ -2133,6 +2134,68 @@ async fn cancelled_recovery_returns_its_consumer_to_the_pool() {
assert_eq!(recovered.id, 7);
}
+#[tokio::test]
+async fn a_mark_on_another_cluster_recovers_from_its_broker() {
+ use personhog_coordination::types::ClusterEndpoint;
+ use rdkafka::producer::FutureRecord;
+
+ let Some(secondary) = common::secondary_kafka_bootstrap() else {
+ return;
+ };
+ let old_topic = common::owned_broker_topic_on(&secondary, 1).await;
+ let producer = common::create_kafka_producer_on(&secondary).await;
+ let person = Person {
+ id: 7,
+ uuid: "00000000-0000-0000-0000-000000000007".to_string(),
+ team_id: 1,
+ properties: b"{}".to_vec(),
+ properties_last_updated_at: Vec::new(),
+ properties_last_operation: Vec::new(),
+ created_at: 1_700_000_000,
+ version: 1,
+ is_identified: false,
+ is_user_id: None,
+ last_seen_at: None,
+ is_deleted: false,
+ };
+ producer
+ .send(
+ FutureRecord::to(&old_topic.topic)
+ .key("1:7")
+ .partition(0)
+ .payload(&person.encode_to_vec()),
+ Duration::from_secs(5),
+ )
+ .await
+ .expect("produce");
+
+ let recovery = test_recovery(KAFKA_BOOTSTRAP);
+ let mark = DirtyMark {
+ version: person.version,
+ offset: 0,
+ partition: 0,
+ stream: personhog_leader::cache::Stream {
+ cluster: Some(std::sync::Arc::new(ClusterEndpoint {
+ name: "old-cluster".to_string(),
+ hosts: secondary,
+ tls: false,
+ })),
+ topic: std::sync::Arc::from(old_topic.topic.as_str()),
+ partition: 0,
+ },
+ is_deleted: false,
+ };
+ let key = PersonCacheKey {
+ team_id: 1,
+ person_id: 7,
+ };
+ let recovered = recovery
+ .fetch_person_at(&mark, &key)
+ .await
+ .expect("recovers from the mark's cluster");
+ assert_eq!(recovered.id, 7);
+}
+
// ============================================================
// Admission-time property size enforcement, mirroring the Node
// pipeline's policy: an update that would newly push a within-limit
diff --git a/rust/personhog-leader/tests/seal_duty_integration.rs b/rust/personhog-leader/tests/seal_duty_integration.rs
index 5fad725d6e34..f7b57f09b640 100644
--- a/rust/personhog-leader/tests/seal_duty_integration.rs
+++ b/rust/personhog-leader/tests/seal_duty_integration.rs
@@ -60,10 +60,12 @@ async fn a_pod_seals_the_partitions_it_owns_by_assignment_without_a_capture() {
let migration = MigrationState {
id: "m-1".to_string(),
from: ChangelogTarget {
+ cluster: None,
topic: old.topic.clone(),
partitions: 2,
},
to: ChangelogTarget {
+ cluster: None,
topic: format!("{}_g2", old.topic),
partitions: 4,
},
@@ -117,10 +119,12 @@ async fn a_registered_peers_partition_is_sealed_once_the_seal_is_overdue() {
let migration = MigrationState {
id: "m-2".to_string(),
from: ChangelogTarget {
+ cluster: None,
topic: old.topic.clone(),
partitions: 2,
},
to: ChangelogTarget {
+ cluster: None,
topic: format!("{}_g2", old.topic),
partitions: 4,
},
@@ -185,10 +189,12 @@ async fn each_seal_is_acked_before_the_pass_ends() {
let migration = MigrationState {
id: "m-1".to_string(),
from: ChangelogTarget {
+ cluster: None,
topic: old.topic.clone(),
partitions: 2,
},
to: ChangelogTarget {
+ cluster: None,
topic: format!("{}_g2", old.topic),
partitions: 4,
},
@@ -245,10 +251,12 @@ async fn a_swept_preconnect_is_dialed_again_on_the_next_pass() {
let migration = MigrationState {
id: "m-1".to_string(),
from: ChangelogTarget {
+ cluster: None,
topic: old.topic.clone(),
partitions: 1,
},
to: ChangelogTarget {
+ cluster: None,
topic: format!("{}_g2", old.topic),
partitions: 2,
},
diff --git a/rust/personhog-leader/tests/settle_integration.rs b/rust/personhog-leader/tests/settle_integration.rs
index fb93edd9d559..a57c862dab5b 100644
--- a/rust/personhog-leader/tests/settle_integration.rs
+++ b/rust/personhog-leader/tests/settle_integration.rs
@@ -48,6 +48,7 @@ fn pruned(key: &PersonCacheKey, version: i64) -> Vec<(PersonCacheKey, DirtyMark)
offset: 9,
partition: PARTITION,
stream: personhog_leader::cache::Stream {
+ cluster: None,
topic: std::sync::Arc::from("personhog_updates"),
partition: PARTITION,
},
diff --git a/rust/personhog-leader/tests/warming_integration.rs b/rust/personhog-leader/tests/warming_integration.rs
index 5dddb1e264e8..cad41ed6b86e 100644
--- a/rust/personhog-leader/tests/warming_integration.rs
+++ b/rust/personhog-leader/tests/warming_integration.rs
@@ -99,7 +99,7 @@ async fn warm_live(
dirty_index: &DirtyIndex,
partition: u32,
) -> personhog_coordination::error::Result<()> {
- let sources = [WarmSource::live(CHANGELOG_TOPIC, partition)];
+ let sources = [WarmSource::live(CHANGELOG_TOPIC, None, partition)];
warm_from_sources(cfg, pools, cache, dirty_index, partition, &sources).await
}
@@ -171,13 +171,13 @@ async fn warming_handles_empty_partition() {
// The empty path must return its consumer to the pool, not drop it —
// a second empty warm reuses the same client instead of creating one.
- let created_after_first = pools.warming.created_count();
+ let created_after_first = pools.on(None).warming.created_count();
cache.drop_partition(0);
warm_live(&cfg, &pools, &cache, &DirtyIndex::new(1_000_000), 0)
.await
.expect("second empty warm should succeed");
assert_eq!(
- pools.warming.created_count(),
+ pools.on(None).warming.created_count(),
created_after_first,
"an empty warm must give its pooled consumer back"
);
@@ -591,6 +591,7 @@ async fn warming_seeds_dirty_index_when_writer_has_no_commits() {
);
// Marks carry the record offsets: 3 records at offsets 0..=2.
let stream = personhog_leader::cache::Stream {
+ cluster: None,
topic: std::sync::Arc::from(CHANGELOG_TOPIC),
partition: 0,
};
@@ -623,12 +624,12 @@ async fn sequential_warms_reuse_pooled_clients() {
}
assert_eq!(
- pools.warming.created_count(),
+ pools.on(None).warming.created_count(),
1,
"four sequential warms must reuse one pooled warming consumer"
);
assert_eq!(
- pools.offsets.created_count(),
+ pools.on(None).offsets.created_count(),
1,
"four offset queries must reuse one pooled offsets client"
);
@@ -643,10 +644,10 @@ async fn warm_up_fills_every_slot() {
let (cluster, _producer) = create_mock_kafka().await;
let (_cfg, pools) = warming_config_for("warmer-prewarm", &cluster);
- pools.warming.warm_up(3).await;
+ pools.on(None).warming.warm_up(3).await;
assert_eq!(
- pools.warming.created_count(),
+ pools.on(None).warming.created_count(),
3,
"prewarming three slots must create three distinct clients"
);
@@ -815,6 +816,7 @@ async fn the_prune_tick_settles_published_partitions_only() {
offset: 0,
partition,
stream: personhog_leader::cache::Stream {
+ cluster: None,
topic: std::sync::Arc::from("personhog_updates"),
partition,
},
@@ -844,7 +846,7 @@ async fn the_prune_tick_settles_published_partitions_only() {
&dirty_index,
&cache,
&locks,
- &pools.offsets,
+ &pools,
Duration::from_secs(5),
|_| false,
)
@@ -866,7 +868,7 @@ async fn the_prune_tick_settles_published_partitions_only() {
&dirty_index,
&cache,
&locks,
- &pools.offsets,
+ &pools,
Duration::from_secs(5),
|_| false,
)
@@ -899,6 +901,7 @@ async fn the_prune_tick_settles_a_retired_streams_marks_without_offsets() {
offset: 0,
partition: 0,
stream: personhog_leader::cache::Stream {
+ cluster: None,
topic: std::sync::Arc::from(topic),
partition,
},
@@ -931,7 +934,7 @@ async fn the_prune_tick_settles_a_retired_streams_marks_without_offsets() {
&dirty_index,
&cache,
&locks,
- &pools.offsets,
+ &pools,
Duration::from_secs(5),
|topic| topic == RETIRED_TOPIC,
),
@@ -990,6 +993,7 @@ async fn the_prune_tick_drains_a_multi_chunk_death_backlog() {
offset,
partition: 0,
stream: personhog_leader::cache::Stream {
+ cluster: None,
topic: std::sync::Arc::from("personhog_updates"),
partition: 0,
},
@@ -1003,7 +1007,7 @@ async fn the_prune_tick_drains_a_multi_chunk_death_backlog() {
&dirty_index,
&cache,
&locks,
- &pools.offsets,
+ &pools,
Duration::from_secs(5),
|_| false,
)
@@ -1062,12 +1066,20 @@ fn commit_group_offset(bootstrap: &str, group: &str, topic: &str, partition: i32
async fn a_restart_warms_the_old_generations_congruent_tail_for_its_keys() {
use personhog_common::partitioning::partition_for_person;
use personhog_coordination::changelog::KeyFilter;
+ use personhog_coordination::types::ClusterEndpoint;
use personhog_leader::cache::Stream;
+ let secondary = common::secondary_kafka_bootstrap();
+ let old_cluster = secondary.as_ref().map(|hosts| ClusterEndpoint {
+ name: "old-cluster".to_string(),
+ hosts: hosts.clone(),
+ tls: false,
+ });
let new_topic = common::create_test_kafka_with_partitions(4).await;
- let producer = common::create_local_kafka_producer().await;
- let old_topic = common::owned_broker_topic(2).await;
let bootstrap = new_topic.bootstrap_servers();
+ let old_bootstrap = secondary.clone().unwrap_or_else(|| bootstrap.clone());
+ let producer = common::create_kafka_producer_on(&old_bootstrap).await;
+ let old_topic = common::owned_broker_topic_on(&old_bootstrap, 2).await;
// Keys whose home under 4 partitions is 1 or 3 all live in old partition 1.
let mut inherited = Vec::new();
@@ -1089,7 +1101,7 @@ async fn a_restart_warms_the_old_generations_congruent_tail_for_its_keys() {
// A group of this test's own: the shared broker may host live writers.
let writer_group = format!("restart-writer-{}", uuid::Uuid::now_v7());
// One record already applied by the writer: below its commit, no mark.
- commit_group_offset(&bootstrap, &writer_group, &old_topic.topic, 1, 1);
+ commit_group_offset(&old_bootstrap, &writer_group, &old_topic.topic, 1, 1);
let mut cfg = common::test_warming_config("restarter", &bootstrap);
cfg.writer_consumer_group = writer_group.clone();
@@ -1098,6 +1110,7 @@ async fn a_restart_warms_the_old_generations_congruent_tail_for_its_keys() {
let dirty_index = DirtyIndex::new(1_000_000);
let sources = [
WarmSource {
+ cluster: old_cluster.clone(),
topic: Arc::from(old_topic.topic.as_str()),
partition: 1,
keep: Some(KeyFilter {
@@ -1105,13 +1118,14 @@ async fn a_restart_warms_the_old_generations_congruent_tail_for_its_keys() {
target: 1,
}),
},
- WarmSource::live(&new_topic.topic, 1),
+ WarmSource::live(&new_topic.topic, None, 1),
];
warm_from_sources(&cfg, &pools, &cache, &dirty_index, 1, &sources)
.await
.expect("warm from the old tail");
let old_stream = Stream {
+ cluster: old_cluster.clone().map(Arc::new),
topic: Arc::from(old_topic.topic.as_str()),
partition: 1,
};
@@ -1164,13 +1178,13 @@ async fn a_restart_warms_the_old_generations_congruent_tail_for_its_keys() {
);
// The writer finishes the old partition: its marks settle.
- commit_group_offset(&bootstrap, &writer_group, &old_topic.topic, 1, 1_000);
+ commit_group_offset(&old_bootstrap, &writer_group, &old_topic.topic, 1, 1_000);
let locks = dashmap::DashMap::new();
personhog_leader::settle::prune_and_settle_tick(
&dirty_index,
&cache,
&locks,
- &pools.offsets,
+ &pools,
Duration::from_secs(5),
|_| false,
)
@@ -1213,6 +1227,7 @@ async fn an_applied_old_record_never_shadows_a_newer_applied_live_one() {
let dirty_index = DirtyIndex::new(1_000_000);
let sources = [
WarmSource {
+ cluster: None,
topic: Arc::from(old_topic.topic.as_str()),
partition: 0,
keep: Some(KeyFilter {
@@ -1220,7 +1235,7 @@ async fn an_applied_old_record_never_shadows_a_newer_applied_live_one() {
target: 0,
}),
},
- WarmSource::live(&new_topic.topic, 0),
+ WarmSource::live(&new_topic.topic, None, 0),
];
warm_from_sources(&cfg, &pools, &cache, &dirty_index, 0, &sources)
.await
diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rs
index b566f1de432a..8ea1b600cb46 100644
--- a/rust/personhog-router/tests/stash_integration.rs
+++ b/rust/personhog-router/tests/stash_integration.rs
@@ -244,12 +244,14 @@ async fn born_partition_write_parks(retired_first: bool) {
.insert(owned, "leader-0".to_string());
}
let changelog = LiveChangelog::new(ChangelogConfig {
+ cluster: None,
topic: "personhog_updates_v2".to_string(),
partitions: NUM_PARTITIONS,
epoch: 2,
writer_group: String::new(),
retire_groups: vec![],
draining: vec![Generation {
+ cluster: None,
topic: "personhog_updates_v1".to_string(),
partitions: old_count,
epoch: 1,
diff --git a/rust/personhog-stateright/src/model.rs b/rust/personhog-stateright/src/model.rs
index 879bac6308fd..3eef90268b0e 100644
--- a/rust/personhog-stateright/src/model.rs
+++ b/rust/personhog-stateright/src/model.rs
@@ -88,6 +88,7 @@ fn production_handoff(p: Partition, h: &Handoff) -> HandoffState {
fn production_config(config: &Config) -> ChangelogConfig {
ChangelogConfig {
+ cluster: None,
topic: generation_topic(config.live.epoch),
partitions: config.live.partitions as u32,
epoch: config.live.epoch as u64,
@@ -96,6 +97,7 @@ fn production_config(config: &Config) -> ChangelogConfig {
draining: config
.draining
.map(|g| ProductionGeneration {
+ cluster: None,
topic: generation_topic(g.epoch),
partitions: g.partitions as u32,
epoch: g.epoch as u64,
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index e1f661154972..49513421f824 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -315,6 +315,11 @@ pub struct GateArgs {
#[arg(long)]
pub migrate_to_partitions: Option<u32>,
+ /// Run the migration onto a second Kafka cluster at these bootstrap
+ /// servers. The writer must exit to follow it and is restarted.
+ #[arg(long)]
+ pub migrate_to_kafka_hosts: Option<String>,
+
/// SIGKILL the coordinator router once the saga reaches Sealing. Requires --routers >= 3.
#[arg(long, default_value_t = false)]
pub migrate_kill_coordinator: bool,
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index 7a5a63f1abe3..9509e3111b0c 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -5,7 +5,7 @@ use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::{Duration, Instant};
-use anyhow::{bail, Context, Result};
+use anyhow::{bail, ensure, Context, Result};
use sqlx::postgres::PgPool;
use personhog_coordination::types::MigrationPhase;
@@ -232,6 +232,9 @@ pub async fn run(args: GateArgs) -> Result<()> {
if args.migrate_after.is_some() && args.migrate_to_partitions.is_none_or(|n| n == 0) {
bail!("--migrate-after needs --migrate-to-partitions >= 1");
}
+ if args.migrate_to_kafka_hosts.is_some() && args.migrate_after.is_none() {
+ bail!("--migrate-to-kafka-hosts needs --migrate-after");
+ }
if args.migrate_again_after.is_some() && args.migrate_again_to_partitions.is_none_or(|n| n == 0)
{
bail!("--migrate-again-after needs --migrate-again-to-partitions >= 1");
@@ -319,6 +322,7 @@ pub async fn run(args: GateArgs) -> Result<()> {
routers: args.routers,
partitions: args.partitions,
kafka_hosts: args.kafka_hosts.clone(),
+ secondary_kafka_hosts: args.migrate_to_kafka_hosts.clone(),
etcd_endpoints: args.etcd_endpoints.clone(),
persons_db_url: args.persons_db_url.clone(),
writer_flush_interval_ms: 1000,
@@ -763,6 +767,7 @@ async fn run_gate(
pause_writer: args
.migrate_pause_writer
.then_some(args.writer_pause_duration),
+ to_secondary: args.migrate_to_kafka_hosts.is_some(),
},
// The second migration runs clean; the first carries the chaos.
_ => MigrationChaos {
@@ -774,6 +779,7 @@ async fn run_gate(
restart_leader: false,
stall: None,
pause_writer: None,
+ to_secondary: false,
},
};
let took = stack.migrate(chaos).await?;
@@ -814,6 +820,13 @@ async fn run_gate(
let mut prober_violations = probers.await.context("prober task panicked")??;
if let Some(stack) = stack.as_mut() {
stack.retire_drained().await?;
+ // A cross-cluster migration the writer never followed would pass vacuously.
+ if args.migrate_to_kafka_hosts.is_some() {
+ ensure!(
+ stack.writer_rebinds() > 0,
+ "the changelog moved to another cluster but the writer never exited to follow it"
+ );
+ }
}
let mut unresolved_merges = Vec::new();
if let Some(merges) = merges {
diff --git a/rust/personhog-test-harness/src/scenarios/stack_cmd.rs b/rust/personhog-test-harness/src/scenarios/stack_cmd.rs
index f69757036994..e125b6c6de27 100644
--- a/rust/personhog-test-harness/src/scenarios/stack_cmd.rs
+++ b/rust/personhog-test-harness/src/scenarios/stack_cmd.rs
@@ -84,6 +84,7 @@ pub async fn run(args: StackArgs) -> Result<()> {
routers: args.routers,
partitions: args.partitions,
kafka_hosts: args.kafka_hosts.clone(),
+ secondary_kafka_hosts: None,
etcd_endpoints: args.etcd_endpoints.clone(),
persons_db_url: args.persons_db_url.clone(),
writer_flush_interval_ms: 1000,
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index a2030b7bfa09..acac675c2120 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -4,9 +4,10 @@ use std::path::PathBuf;
use std::time::{Duration, Instant};
use anyhow::{bail, ensure, Context, Result};
+use personhog_coordination::follow::REBIND_LOG;
use personhog_coordination::store::PersonhogStore;
use personhog_coordination::types::{
- ChangelogTarget, HandoffPhase, MigrationPhase, MigrationRequest,
+ ChangelogTarget, ClusterEndpoint, HandoffPhase, MigrationPhase, MigrationRequest,
};
mod etcd;
@@ -64,6 +65,7 @@ pub struct StackConfig {
pub routers: u32,
pub partitions: u32,
pub kafka_hosts: String,
+ pub secondary_kafka_hosts: Option<String>,
pub etcd_endpoints: String,
pub persons_db_url: String,
/// Writer flush cadence. Short by default so gate quiesce is quick.
@@ -142,6 +144,8 @@ pub struct Stack {
topic: String,
/// Topics a migration moved off; deleted with the live one at teardown.
retired_topics: Vec<String>,
+ secondary_topics: HashSet<String>,
+ writer_rebinds: usize,
/// Old generations awaiting the writer's drain and the retire op, with the saga's end.
pending_retire: Vec<(String, Instant)>,
pub router_url: String,
@@ -483,6 +487,8 @@ impl Stack {
store,
topic,
retired_topics: Vec::new(),
+ secondary_topics: HashSet::new(),
+ writer_rebinds: 0,
pending_retire: Vec::new(),
router_url,
identity_url,
@@ -1011,13 +1017,33 @@ impl Stack {
/// Fail if any spawned service has exited (retired and paused
/// processes excluded — their state is chaos-induced).
pub fn check_alive(&mut self) -> Result<()> {
+ let mut writer_rebinds = self.writer_rebinds;
let procs = self
.infra
.iter_mut()
.chain(self.routers.iter_mut().map(|(_, proc)| proc))
.chain(self.leaders.iter_mut().map(|(_, proc)| proc));
for proc in procs {
- if let Some(status) = proc.exited() {
+ if let Some(exit) = proc.exited() {
+ let clean = exit.as_ref().is_ok_and(|status| status.success());
+ let status = match exit {
+ Ok(status) => status.to_string(),
+ Err(e) => format!("unknown ({e})"),
+ };
+ let logged = if proc.name() == "writer" {
+ std::fs::read_to_string(proc.log_path())
+ .unwrap_or_default()
+ .matches(REBIND_LOG)
+ .count()
+ } else {
+ 0
+ };
+ if logged > writer_rebinds && clean {
+ writer_rebinds = logged;
+ proc.restart_exited()?;
+ println!("Migration: the writer exited ({status}) to follow the changelog onto another cluster; restarted it");
+ continue;
+ }
let tail = proc.log_tail(30);
bail!(
"service {} exited ({status}); last log lines:\n{tail}",
@@ -1025,9 +1051,18 @@ impl Stack {
);
}
}
+ self.writer_rebinds = writer_rebinds;
Ok(())
}
+ pub fn writer_rebinds(&self) -> usize {
+ self.writer_rebinds
+ }
+
+ fn hosts_of(&self, topic: &str) -> String {
+ topic_hosts(&self.config, &self.secondary_topics, topic).to_string()
+ }
+
fn dump_recent_logs(&self) {
let procs = self
.infra
@@ -1069,7 +1104,8 @@ impl Stack {
}
let mut first_error = None;
for topic in topics {
- if let Err(e) = kafka::delete_topic(&self.config.kafka_hosts, topic).await {
+ let hosts = topic_hosts(&self.config, &self.secondary_topics, topic);
+ if let Err(e) = kafka::delete_topic(hosts, topic).await {
first_error.get_or_insert(e);
}
}
@@ -1086,18 +1122,48 @@ impl Stack {
if !self.pending_retire.is_empty() {
self.retire_drained().await?;
}
- let from = self
+ let (mut from, revision) = self
.store
- .get_changelog_config()
+ .get_changelog_config_with_mod_revision()
.await?
.context("config/changelog must be seeded")?;
+ if chaos.to_secondary && from.cluster.is_none() {
+ let primary = ClusterEndpoint {
+ name: PRIMARY_CLUSTER.to_string(),
+ hosts: self.config.kafka_hosts.clone(),
+ tls: false,
+ };
+ ensure!(
+ self.store
+ .set_changelog_cluster(&from, revision, &primary)
+ .await?,
+ "recording the live changelog's cluster lost a race"
+ );
+ from.cluster = Some(primary);
+ }
let generation = self.retired_topics.len() + 2;
let to_topic = format!("{}_g{generation}", self.topic);
- kafka::create_topic(&self.config.kafka_hosts, &to_topic, chaos.to_partitions).await?;
+ let to_cluster = if chaos.to_secondary {
+ let hosts = self
+ .config
+ .secondary_kafka_hosts
+ .clone()
+ .context("a migration onto the secondary cluster needs its hosts")?;
+ self.secondary_topics.insert(to_topic.clone());
+ Some(ClusterEndpoint {
+ name: SECONDARY_CLUSTER.to_string(),
+ hosts,
+ tls: false,
+ })
+ } else {
+ None
+ };
+ kafka::create_topic(&self.hosts_of(&to_topic), &to_topic, chaos.to_partitions).await?;
let migration = MigrationRequest {
id: format!("harness-g{generation}"),
from: from.target(),
to: ChangelogTarget {
+ cluster: to_cluster,
topic: to_topic.clone(),
partitions: chaos.to_partitions,
},
@@ -1304,7 +1370,7 @@ impl Stack {
archived.blocking.join("; ")
);
if expected == MigrationPhase::Cancelled {
- kafka::delete_topic(&self.config.kafka_hosts, &to_topic).await?;
+ kafka::delete_topic(&self.hosts_of(&to_topic), &to_topic).await?;
return Ok(saga);
}
self.config.partitions = chaos.to_partitions;
@@ -1329,6 +1395,7 @@ impl Stack {
if !draining {
break;
}
+ self.check_alive()?;
ensure!(
waited_from.elapsed() < RETIREMENT_DEADLINE,
"the coordinator did not retire {old_topic} within {RETIREMENT_DEADLINE:?}"
@@ -1345,7 +1412,7 @@ impl Stack {
let moved_at = Instant::now();
loop {
if kafka::group_has_committed_offsets(
- &self.config.kafka_hosts,
+ &self.hosts_of(&self.topic),
WRITER_CONSUMER_GROUP,
&self.topic,
)
@@ -1353,6 +1420,7 @@ impl Stack {
{
break;
}
+ self.check_alive()?;
ensure!(
moved_at.elapsed() < WRITER_MOVE_DEADLINE,
"the writer did not commit on {} within {WRITER_MOVE_DEADLINE:?}",
@@ -1391,6 +1459,21 @@ pub struct MigrationChaos {
pub stall: Option<StallAt>,
/// Pause the writer for this long as the migration starts.
pub pause_writer: Option<Duration>,
+ pub to_secondary: bool,
+}
+
+pub const PRIMARY_CLUSTER: &str = "harness-primary";
+pub const SECONDARY_CLUSTER: &str = "harness-secondary";
+
+fn topic_hosts<'a>(
+ config: &'a StackConfig,
+ secondary_topics: &HashSet<String>,
+ topic: &str,
+) -> &'a str {
+ match &config.secondary_kafka_hosts {
+ Some(secondary) if secondary_topics.contains(topic) => secondary,
+ _ => &config.kafka_hosts,
+ }
}
fn now_millis() -> i64 {
diff --git a/rust/personhog-test-harness/src/stack/process.rs b/rust/personhog-test-harness/src/stack/process.rs
index 4da2c62ca134..4b25f6311848 100644
--- a/rust/personhog-test-harness/src/stack/process.rs
+++ b/rust/personhog-test-harness/src/stack/process.rs
@@ -104,13 +104,13 @@ impl ServiceProcess {
&self.spec.log_path
}
- /// Whether the process has exited. Returns the exit description if so.
- pub fn exited(&mut self) -> Option<String> {
- match self.child.try_wait() {
- Ok(Some(status)) => Some(status.to_string()),
- Ok(None) => None,
- Err(e) => Some(format!("unknown ({e})")),
- }
+ pub fn exited(&mut self) -> Option<std::io::Result<std::process::ExitStatus>> {
+ self.child.try_wait().transpose()
+ }
+
+ pub fn restart_exited(&mut self) -> Result<()> {
+ self.child = self.spec.spawn()?;
+ Ok(())
}
/// Kill the current process (if still running) and start a fresh one
diff --git a/rust/personhog-writer/src/kafka.rs b/rust/personhog-writer/src/kafka.rs
index cccfe759abb0..89c4b25285d6 100644
--- a/rust/personhog-writer/src/kafka.rs
+++ b/rust/personhog-writer/src/kafka.rs
@@ -5,6 +5,7 @@ use std::sync::{Arc, Mutex, RwLock};
use common_kafka::config::KafkaConfig;
use metrics::counter;
use personhog_coordination::follow::ChangelogSubscription;
+use personhog_coordination::types::ClusterEndpoint;
use rdkafka::consumer::{
BaseConsumer, CommitMode, Consumer, ConsumerContext, Rebalance, StreamConsumer,
};
@@ -87,6 +88,7 @@ impl ConsumerContext for RebalanceContext {
pub struct PersonConsumer {
consumer: StreamConsumer<RebalanceContext>,
topic: RwLock<String>,
+ cluster: Option<ClusterEndpoint>,
/// Set while the subscribed topic is a sealed generation.
draining: AtomicBool,
revoked: Arc<Mutex<Vec<Source>>>,
@@ -153,12 +155,18 @@ impl PersonConsumer {
Ok(Self {
consumer,
topic: RwLock::new(topic),
+ cluster: None,
draining: AtomicBool::new(false),
revoked,
joined,
})
}
+ pub fn on_cluster(mut self, cluster: Option<ClusterEndpoint>) -> Self {
+ self.cluster = cluster;
+ self
+ }
+
/// Only called once the group has drained the current topic.
pub fn resubscribe(&self, topic: String) -> Result<(), rdkafka::error::KafkaError> {
self.consumer.subscribe(&[&topic])?;
@@ -269,6 +277,10 @@ impl ChangelogSubscription for PersonConsumer {
PersonConsumer::topic(self)
}
+ fn cluster(&self) -> Option<ClusterEndpoint> {
+ self.cluster.clone()
+ }
+
fn resubscribe(&self, topic: &str) -> Result<(), String> {
PersonConsumer::resubscribe(self, topic.to_string()).map_err(|e| e.to_string())
}
diff --git a/rust/personhog-writer/src/main.rs b/rust/personhog-writer/src/main.rs
index 89d04660c269..55b42950cdd4 100644
--- a/rust/personhog-writer/src/main.rs
+++ b/rust/personhog-writer/src/main.rs
@@ -4,13 +4,15 @@ use std::time::Duration;
use assignment_coordination::store::{EtcdStore, StoreConfig};
use axum::{routing::get, Router};
use common_database::{get_pool_with_config, PoolConfig};
+use common_kafka::config::KafkaConfig;
use common_metrics::{setup_metrics_routes_with_overrides, Matcher};
use envconfig::Envconfig;
use lifecycle::{ComponentOptions, Manager};
use metrics::counter;
use personhog_coordination::changelog::{load_changelog_config, CHANGELOG_BOOT_POLL_INTERVAL};
-use personhog_coordination::follow::{follow_changelog, Follower, Reporter};
+use personhog_coordination::follow::{follow_changelog, FollowTarget, Follower, Reporter};
use personhog_coordination::store::PersonhogStore;
+use personhog_coordination::types::ClusterEndpoint;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::level_filters::LevelFilter;
@@ -86,8 +88,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
// Oldest undrained generation first, so a restart mid-drain resumes it.
let mut follower = Follower::default();
- let topic = follower
- .select_topic(&loaded, |topic| drained(&config, topic))
+ let FollowTarget { topic, cluster } = follower
+ .select_topic(&loaded, |target| drained(&config, target))
.await?;
let mut manager = Manager::builder("personhog-writer")
@@ -188,11 +190,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
});
}
- let kafka_consumer = Arc::new(PersonConsumer::from_config(
- &config.kafka,
- &config.kafka_consumer_group,
- topic.clone(),
- )?);
+ let kafka_consumer = Arc::new(
+ PersonConsumer::from_config(
+ &changelog_kafka(&config.kafka, cluster.as_ref()),
+ &config.kafka_consumer_group,
+ topic.clone(),
+ )?
+ .on_cluster(cluster.clone()),
+ );
kafka_consumer.set_draining(topic != loaded.topic);
tracing::info!(topic = %topic, draining = kafka_consumer.is_draining(), "Subscribed to Kafka topic");
@@ -258,14 +263,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
loaded,
follower,
consumer,
- |topic: String| drained(&config, topic),
+ |target: FollowTarget| drained(&config, target),
Reporter::for_group(&config.kafka_consumer_group),
|_, _| counter!("personhog_writer_resubscriptions_total").increment(1),
cancel.clone(),
);
tokio::select! {
_ = handle.shutdown_signal() => cancel.cancel(),
- _ = follow => {}
+ rebind = follow => {
+ // The pod's restart subscribes on the next generation's cluster.
+ if rebind.is_some() {
+ handle.request_shutdown();
+ handle.shutdown_signal().await;
+ }
+ }
}
});
}
@@ -274,9 +285,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
-/// Whether the writer group has read every partition of `topic` to its end.
-async fn drained(config: &Config, topic: String) -> Result<bool, String> {
- let base = base_client_config(&config.kafka);
+fn changelog_kafka(base: &KafkaConfig, cluster: Option<&ClusterEndpoint>) -> KafkaConfig {
+ match cluster {
+ Some(cluster) => base.with_endpoint(&cluster.hosts, cluster.tls),
+ None => base.clone(),
+ }
+}
+
+async fn drained(config: &Config, target: FollowTarget) -> Result<bool, String> {
+ let base = base_client_config(&changelog_kafka(&config.kafka, target.cluster.as_ref()));
+ let topic = target.topic;
let group = config.kafka_consumer_group.clone();
tokio::task::spawn_blocking(move || {
common_kafka::probe::group_drained(&base, &group, &topic, Duration::from_secs(10))
diff --git a/rust/personhog-writer/tests/integration.rs b/rust/personhog-writer/tests/integration.rs
index 6a908d53d762..b62626c6151a 100644
--- a/rust/personhog-writer/tests/integration.rs
+++ b/rust/personhog-writer/tests/integration.rs
@@ -1221,12 +1221,14 @@ async fn the_draining_flag_follows_the_subscribed_topic_not_the_move() {
let member = plain_member_config(&mock_cluster.bootstrap_servers(), "test-follow");
let consumer = PersonConsumer::new(&member, TOPIC.to_string()).unwrap();
let flipped = ChangelogConfig {
+ cluster: None,
topic: NEXT_TOPIC.to_string(),
partitions: 1,
epoch: 2,
writer_group: "test-follow".to_string(),
retire_groups: vec![],
draining: vec![Generation {
+ cluster: None,
topic: TOPIC.to_string(),
partitions: 1,
epoch: 1,