:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(cohorts): carry membership origin and drop shadow topic naming (#88189)
posthog[bot]290d6dbdc40d
diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.test.tsindex 3b279603c8c5..9c3b48592d0b 100644--- a/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.test.ts@@ -208,6 +208,53 @@ describe('CdpCohortMembershipConsumer', () => {expect(result.rows[0].in_cohort).toBe(false)})+ it.each([+ ['seed' as const, new UUIDT().toString()],+ ['reconcile' as const, new UUIDT().toString()],+ ])('should carry origin=%s and run_id through parsing', (origin, runId) => {+ const message = createKafkaMessage(+ createCohortMembershipEvent({+ person_id: personId1,+ cohort_id: 456,+ team_id: 1,+ origin,+ run_id: runId,+ }),+ { topic: KAFKA_COHORT_MEMBERSHIP_CHANGED, offset: 0 }+ )++ const [change] = consumer['_parseAndValidateBatch']([message])++ expect(change.origin).toBe(origin)+ expect(change.run_id).toBe(runId)+ })++ it('should carry an unknown origin through parsing without rejecting the batch', () => {+ const runId = new UUIDT().toString()+ const message = createKafkaMessage(+ createCohortMembershipEvent({+ person_id: personId1,+ cohort_id: 456,+ team_id: 1,+ status: 'entered',+ origin: 'snapshot',+ run_id: runId,+ }),+ { topic: KAFKA_COHORT_MEMBERSHIP_CHANGED, offset: 0 }+ )++ const [change] = consumer['_parseAndValidateBatch']([message])++ expect(change.origin).toBe('snapshot')+ expect(change.run_id).toBe(runId)+ expect(change).toMatchObject({+ person_id: personId1,+ cohort_id: 456,+ team_id: 1,+ status: 'entered',+ })+ })+it('should reject entire batch when invalid messages are present', async () => {const validEvent = {person_id: personId1,diff --git a/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts b/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.tsindex 68df09d79cea..12095a0300b1 100644--- a/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cohort-membership.consumer.ts@@ -11,13 +11,16 @@ import { logger } from '~/common/utils/logger'import { HealthCheckResult } from '../../types'import { CdpConsumerBase, CdpConsumerBaseConfig, CdpConsumerBaseDeps } from './cdp-base.consumer'-// Zod schema for validation+// `origin` is a loose string, not an enum: nothing branches on it, and rejecting a value the+// processor added later would throw the whole batch and crash-loop on redelivery.const CohortMembershipChangeSchema = z.object({person_id: z.guid(),cohort_id: z.number(),team_id: z.number(),status: z.enum(['entered', 'left']),last_updated: z.string().optional(),+ origin: z.string().optional(),+ run_id: z.guid().optional(),})export type CohortMembershipChange = z.infer<typeof CohortMembershipChangeSchema>diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rsindex b9ada9afb2aa..cec4eda0c17e 100644--- a/rust/cohort-stream-processor/src/config.rs+++ b/rust/cohort-stream-processor/src/config.rs@@ -306,7 +306,8 @@ pub struct Config {#[envconfig(from = "HOSTNAME")]pub pod_hostname: Option<String>,- /// The shadow output topic for membership changes.+ /// The output topic for membership changes. Defaulting to the shadow topic keeps the cut-over+ /// a config-only change, so no code deploy can redirect production output.#[envconfig(default = "cohort_membership_changed_shadow")]pub cohort_membership_changed_topic: String,@@ -1675,6 +1676,28 @@ mod tests {);}+ #[test]+ fn membership_topic_defaults_to_the_shadow_and_overrides_from_env() {+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();+ assert_eq!(+ defaults.cohort_membership_changed_topic, "cohort_membership_changed_shadow",+ "a code deploy must not redirect membership output to the production topic",+ );++ let env: std::collections::HashMap<String, String> = [(+ "COHORT_MEMBERSHIP_CHANGED_TOPIC",+ "cohort_membership_changed",+ )]+ .into_iter()+ .map(|(key, value)| (key.to_string(), value.to_string()))+ .collect();+ let config = Config::init_from_hashmap(&env).unwrap();+ assert_eq!(+ config.cohort_membership_changed_topic, "cohort_membership_changed",+ "the cut-over must be reachable as a config-only change",+ );+ }+#[test]fn durable_restore_defaults_off_and_overrides_from_env() {let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rsindex bfc493354f86..0e4028f29522 100644--- a/rust/cohort-stream-processor/src/main.rs+++ b/rust/cohort-stream-processor/src/main.rs@@ -178,7 +178,7 @@ async fn async_main(config: Config) -> Result<()> {config.cohort_membership_changed_topic.clone(),).await- .context("creating shadow producer")?,+ .context("creating membership producer")?,);// The transfer and marker sinks get the shorter `message.timeout.ms`: both produce inline on adiff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex e7b75534107b..ede4684f62dd 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -363,12 +363,14 @@ pub const COHORT_STREAM_ROUTE_ERRORS: &str = "cohort_stream_route_errors_total";/// Events accumulated per consume → route cycle (histogram).pub const COHORT_STREAM_CONSUME_BATCH_SIZE: &str = "cohort_stream_consume_batch_size";-/// Membership changes produced to `cohort_membership_changed_shadow`, labelled by `status`+/// Membership changes produced to the membership output topic, labelled by `status`/// (counter). Counted only after a fully-acked flush.pub const OUTPUT_MEMBERSHIP_CHANGES_EMITTED: &str = "output_membership_changes_emitted_total";/// Leaf transitions that mapped to zero output cohorts, labelled by `reason` (counter).pub const OUTPUT_TRANSITIONS_UNMAPPED: &str = "output_transitions_unmapped_total";-/// Produce failures to `cohort_membership_changed_shadow` (counter).+/// Produce failures on the membership output topic (counter). Not every failure loses data: most+/// paths hold or reschedule the offset for replay. Sweep stage 2 and merge drop the change,+/// because their state is already committed.pub const OUTPUT_PRODUCE_ERRORS: &str = "output_produce_errors_total";/// Sweep cycles that fired, labelled by `loop`diff --git a/rust/cohort-stream-processor/src/producer/kafka.rs b/rust/cohort-stream-processor/src/producer/kafka.rsindex 7adb40778154..f52194e3c3fd 100644--- a/rust/cohort-stream-processor/src/producer/kafka.rs+++ b/rust/cohort-stream-processor/src/producer/kafka.rs@@ -1,4 +1,4 @@-//! Kafka producer for `cohort_membership_changed_shadow`.+//! Kafka producer for the membership-changes output topic.use anyhow::{Context, Result};use async_trait::async_trait;@@ -29,7 +29,7 @@ impl KafkaMembershipSink {pub async fn new(kafka_config: &KafkaConfig, topic: String) -> Result<Self> {let producer = create_kafka_producer(kafka_config, AlwaysHealthy).await- .context("creating cohort_membership_changed_shadow producer")?;+ .context("creating membership sink producer")?;Ok(Self { producer, topic })}}diff --git a/rust/cohort-stream-processor/src/producer/mod.rs b/rust/cohort-stream-processor/src/producer/mod.rsindex fc481d366147..9c8c613be9bf 100644--- a/rust/cohort-stream-processor/src/producer/mod.rs+++ b/rust/cohort-stream-processor/src/producer/mod.rs@@ -40,7 +40,7 @@ pub use merge::{};pub use seed::{CaptureSeedTileSink, KafkaSeedTileSink, NoopSeedTileSink, SeedTileSink};-/// One per-cohort membership change on `cohort_membership_changed_shadow`.+/// One per-cohort membership change on the membership output topic.////// `origin`/`run_id` are additive and absent on the live path, so live emissions stay/// byte-identical to the pre-field contract.@@ -321,7 +321,7 @@ mod tests {map_transition(&filters, &transition(lsk, TransitionKind::Entered), TS).collect();assert!(changes.is_empty(),- "a leaf owned only by a multi-leaf cohort produces no shadow output",+ "a leaf owned only by a multi-leaf cohort produces no membership output",);}diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rsindex d5c1f205d7aa..0fd3446d5b90 100644--- a/rust/cohort-stream-processor/src/workers/worker.rs+++ b/rust/cohort-stream-processor/src/workers/worker.rs@@ -425,8 +425,7 @@ async fn run_worker(if errors > 0 {warn!(partition_id,- errors,- "produce to cohort_membership_changed_shadow failed; holding offset for replay",+ errors, "produce to the membership topic failed; holding offset for replay",);continue;}@@ -508,7 +507,7 @@ async fn flush_event_changes_before_inline(*held = true;warn!(partition_id,- errors, "produce to cohort_membership_changed_shadow failed; holding offset for replay",+ errors, "produce to the membership topic failed; holding offset for replay",);return true;}@@ -841,8 +840,7 @@ async fn handle_sweep(if errors > 0 {warn!(partition_id,- errors,- "sweep produce to cohort_membership_changed_shadow failed; rescheduling for replay",+ errors, "sweep produce to the membership topic failed; rescheduling for replay",);reschedule_all(queue, &popped);return;@@ -939,7 +937,7 @@ async fn handle_sweep(warn!(partition_id,errors,- "sweep stage 2 produce to cohort_membership_changed_shadow failed; dropping (cf_stage2 already committed, at-most-once)",+ "sweep stage 2 produce to the membership topic failed; dropping (cf_stage2 already committed, at-most-once)",);return;}