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(cohorts): stream-native cohorts mvp (#61317)

Matheus Batista26784364e1cf
diff --git a/bin/dump_hogvmrs_stl b/bin/dump_hogvmrs_stl
index d2d994842e52..543ad957dee7 100755
--- a/bin/dump_hogvmrs_stl
+++ b/bin/dump_hogvmrs_stl
@@ -10,4 +10,4 @@ if ! cd "$SCRIPT_DIR/../rust/common/hogvm"; then
fi
# Run cargo command with script location as parameter
-cargo run stl_dump -- "$SCRIPT_DIR/../posthog/models/error_tracking/hogvm_stl.py"
+cargo run --bin stl_dump -- "$SCRIPT_DIR/../products/error_tracking/backend/hogvm_stl.py"
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index b4890a192d82..ad34852bbc19 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -475,6 +475,30 @@ procs:
capability: personhog
ready_pattern: 'Metrics server listening on *'
+ # Behavioral Cohorts stream rebuild (Rust). The shuffler keys clickhouse_events_json into
+ # cohort_stream_events; the processor consumes that and emits membership changes. Both are gated
+ # behind the `behavioral_cohorts` capability (wired into the `cohorts` intent) so they only run
+ # when a dev opts in — the default no-intent manifest is unchanged.
+ cohort-event-shuffler:
+ shell: |-
+ bin/wait-for-docker && \
+ bin/start-rust-service cohort-event-shuffler
+ capability: behavioral_cohorts
+ ready_pattern: 'observability server starting'
+ groups:
+ layer: Product services
+ tech: Rust
+
+ cohort-stream-processor:
+ shell: |-
+ bin/wait-for-docker && \
+ bin/start-rust-service cohort-stream-processor
+ capability: behavioral_cohorts
+ ready_pattern: 'observability server starting'
+ groups:
+ layer: Product services
+ tech: Rust
+
llm-gateway:
sandbox: true
shell: 'bin/wait-for-docker && bin/start-llm-gateway'
diff --git a/bin/start-rust-service b/bin/start-rust-service
index 5de7202bcc54..e4670736cdab 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -278,6 +278,34 @@ case "$RS_SVC" in
export DEBUG=1
;;
+ cohort-event-shuffler)
+ SQLX_QUERY_LEVEL=${SQLX_QUERY_LEVEL:-warn}
+ export RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warn
+ export RUST_BACKTRACE=1
+ export KAFKA_HOSTS="$DEFAULT_KAFKA"
+ export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PG}" # reads posthog_cohort for the realtime team gate
+ # Code default gates to team 2 (the parity baseline); dev uses the local team, so open the gate.
+ export REALTIME_COHORT_TEAM_ALLOWLIST="${REALTIME_COHORT_TEAM_ALLOWLIST:-all}"
+ # earliest replays existing local events; prod defaults to "latest".
+ export KAFKA_CONSUMER_OFFSET_RESET="${KAFKA_CONSUMER_OFFSET_RESET:-earliest}"
+ export BIND_PORT=3310
+ export DEBUG=1
+ ;;
+
+ cohort-stream-processor)
+ SQLX_QUERY_LEVEL=${SQLX_QUERY_LEVEL:-warn}
+ export RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warn
+ export RUST_BACKTRACE=1
+ export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PG}" # reads posthog_cohort for the realtime filter catalog
+ # Code default gates to team 2 (the parity baseline); dev uses the local team, so open the gate.
+ export REALTIME_COHORT_TEAM_ALLOWLIST="${REALTIME_COHORT_TEAM_ALLOWLIST:-all}"
+ # Fast refresh in dev so window/threshold edits surface a new LeafStateKey quickly.
+ export FILTER_CATALOG_REFRESH_SECS="${FILTER_CATALOG_REFRESH_SECS:-30}"
+ export FILTER_CATALOG_REFRESH_JITTER_SECS="${FILTER_CATALOG_REFRESH_JITTER_SECS:-5}"
+ export BIND_PORT=3311
+ export DEBUG=1
+ ;;
+
personhog-router-leader)
export RUST_LOG=debug
export RUST_BACKTRACE=1
diff --git a/devenv/intent-map.yaml b/devenv/intent-map.yaml
index cb4e56723f29..b070f96e9c8d 100644
--- a/devenv/intent-map.yaml
+++ b/devenv/intent-map.yaml
@@ -152,6 +152,11 @@ capabilities:
requires: [event_ingestion]
docker_profiles: []
+ behavioral_cohorts:
+ description: 'Behavioral Cohorts stream rebuild (Rust cohort-event-shuffler + cohort-stream-processor)'
+ requires: [event_ingestion]
+ docker_profiles: []
+
nodejs_session_replay:
description: 'Node.js Session Replay - recording ingestion'
requires: [event_ingestion]
@@ -335,6 +340,7 @@ intents:
celery_workers,
celery_scheduler,
nodejs_realtime_cohorts,
+ behavioral_cohorts,
]
pipelines:
diff --git a/nodejs/src/common/outputs/persons.ts b/nodejs/src/common/outputs/persons.ts
index 20b1505c0fd1..512241ae8970 100644
--- a/nodejs/src/common/outputs/persons.ts
+++ b/nodejs/src/common/outputs/persons.ts
@@ -4,3 +4,6 @@ export type PersonsOutput = typeof PERSONS_OUTPUT
export const PERSON_DISTINCT_IDS_OUTPUT = 'person_distinct_ids' as const
export type PersonDistinctIdsOutput = typeof PERSON_DISTINCT_IDS_OUTPUT
+
+export const PERSON_MERGE_EVENTS_OUTPUT = 'person_merge_events' as const
+export type PersonMergeEventsOutput = typeof PERSON_MERGE_EVENTS_OUTPUT
diff --git a/nodejs/src/common/outputs/types.ts b/nodejs/src/common/outputs/types.ts
index 1dfa146ef9c7..557fd40f6a70 100644
--- a/nodejs/src/common/outputs/types.ts
+++ b/nodejs/src/common/outputs/types.ts
@@ -6,6 +6,8 @@ export type IngestionOutputMessage = {
key?: MessageKey
headers?: Record<string, string>
teamId?: number
+ /** Explicit target partition. Required for topics whose consumer pins a non-default partitioner. */
+ partition?: number
}
/**
diff --git a/nodejs/src/config/kafka-topics.ts b/nodejs/src/config/kafka-topics.ts
index 81f4df04fec2..1a6adfaf5e66 100644
--- a/nodejs/src/config/kafka-topics.ts
+++ b/nodejs/src/config/kafka-topics.ts
@@ -56,6 +56,8 @@ export const KAFKA_CDP_CLICKHOUSE_BEHAVIORAL_COHORTS_MATCHES = `${prefix}clickho
export const KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS = `${prefix}clickhouse_prefiltered_events${suffix}`
export const KAFKA_CDP_CLICKHOUSE_PRECALCULATED_PERSON_PROPERTIES = `${prefix}clickhouse_precalculated_person_properties${suffix}`
export const KAFKA_COHORT_MEMBERSHIP_CHANGED = `${prefix}cohort_membership_changed${suffix}`
+// Cross-partition merge protocol trigger consumed by the cohort-stream-processor (Rust).
+export const KAFKA_PERSON_MERGE_EVENTS = `${prefix}person_merge_events${suffix}`
export const KAFKA_CDP_BATCH_HOGFLOW_REQUESTS = `${prefix}cdp_batch_hogflow_requests${suffix}`
// Error tracking topics
diff --git a/nodejs/src/ingestion/common/ai-subpipeline.contract.ts b/nodejs/src/ingestion/common/ai-subpipeline.contract.ts
index e79516059301..054778d6ef2f 100644
--- a/nodejs/src/ingestion/common/ai-subpipeline.contract.ts
+++ b/nodejs/src/ingestion/common/ai-subpipeline.contract.ts
@@ -8,6 +8,7 @@ import {
EventOutput,
IngestionWarningsOutput,
PersonDistinctIdsOutput,
+ PersonMergeEventsOutput,
PersonsOutput,
} from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
@@ -34,7 +35,12 @@ export interface AiEventSubpipelineInput {
export interface AiEventSubpipelineConfig {
options: EventPipelineRunnerOptions
outputs: IngestionOutputs<
- EventOutput | AiEventOutput | IngestionWarningsOutput | PersonsOutput | PersonDistinctIdsOutput
+ | EventOutput
+ | AiEventOutput
+ | IngestionWarningsOutput
+ | PersonsOutput
+ | PersonDistinctIdsOutput
+ | PersonMergeEventsOutput
>
teamManager: TeamManager
groupTypeManager: GroupTypeManager
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
index ecdafcf285f3..60b85b6da9d2 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts
@@ -1,7 +1,7 @@
import { DateTime } from 'luxon'
import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
-import { PERSONS_OUTPUT, PersonDistinctIdsOutput, PersonsOutput } from '~/common/outputs'
+import { PERSONS_OUTPUT, PersonDistinctIdsOutput, PersonMergeEventsOutput, PersonsOutput } from '~/common/outputs'
import {
personProfileBatchIgnoredPropertiesCounter,
personProfileBatchUpdateOutcomeCounter,
@@ -50,7 +50,7 @@ describe('BatchWritingPersonStore', () => {
let mockIngestionWarningsOutputs: jest.Mocked<
ReturnType<
typeof createMockIngestionOutputs<
- PersonsOutput | PersonDistinctIdsOutput | typeof INGESTION_WARNINGS_OUTPUT
+ PersonsOutput | PersonDistinctIdsOutput | typeof INGESTION_WARNINGS_OUTPUT | PersonMergeEventsOutput
>
>
>
@@ -85,7 +85,7 @@ describe('BatchWritingPersonStore', () => {
} as unknown as PostgresRouter
mockIngestionWarningsOutputs = createMockIngestionOutputs<
- PersonsOutput | PersonDistinctIdsOutput | typeof INGESTION_WARNINGS_OUTPUT
+ PersonsOutput | PersonDistinctIdsOutput | typeof INGESTION_WARNINGS_OUTPUT | PersonMergeEventsOutput
>()
mockRepo = createMockRepository()
diff --git a/nodejs/src/ingestion/common/persons/person-context.ts b/nodejs/src/ingestion/common/persons/person-context.ts
index e2eb6e5e2fb9..ed4f3780b246 100644
--- a/nodejs/src/ingestion/common/persons/person-context.ts
+++ b/nodejs/src/ingestion/common/persons/person-context.ts
@@ -1,16 +1,27 @@
import { DateTime } from 'luxon'
-import { IngestionWarningsOutput } from '~/common/outputs'
-import { PersonDistinctIdsOutput, PersonsOutput } from '~/common/outputs'
+import {
+ IngestionWarningsOutput,
+ PERSON_MERGE_EVENTS_OUTPUT,
+ PersonDistinctIdsOutput,
+ PersonMergeEventsOutput,
+ PersonsOutput,
+} from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PersonMessage } from '~/common/persons/person-message'
import { PluginEvent, Properties } from '~/plugin-scaffold'
-import { Team } from '~/types'
+import { InternalPerson, Team } from '~/types'
+import { buildPersonMergeEventMessage } from './person-merge-event'
import { MergeMode } from './person-merge-types'
import { PersonsStoreForBatch } from './persons-store-for-batch'
-export type PersonOutputs = IngestionOutputs<PersonsOutput | PersonDistinctIdsOutput | IngestionWarningsOutput>
+export type PersonOutputs = IngestionOutputs<
+ PersonsOutput | PersonDistinctIdsOutput | IngestionWarningsOutput | PersonMergeEventsOutput
+>
+
+/** Gate + partition-count for the cross-partition merge-event producer. */
+export type MergeEventsConfig = { enabled: boolean; partitionCount: number }
/**
* Lightweight data holder containing all the context needed for person processing.
@@ -31,7 +42,8 @@ export class PersonContext {
public readonly measurePersonJsonbSize: number = 0,
public readonly mergeMode: MergeMode,
public readonly updateAllProperties: boolean = false, // When true, all property changes trigger person updates
- public readonly shouldUpdateLastSeenAt: boolean = false
+ public readonly shouldUpdateLastSeenAt: boolean = false,
+ public readonly mergeEventsConfig: MergeEventsConfig = { enabled: false, partitionCount: 64 }
) {
this.eventProperties = event.properties!
}
@@ -43,4 +55,28 @@ export class PersonContext {
)
)
}
+
+ /**
+ * Emit a person_merge_events message for the cohort-stream-processor. Resolved no-op when the
+ * gate is off. The message is explicitly partitioned by `(team_id, P_old)` so it reaches the
+ * worker holding P_old's state — see `buildPersonMergeEventMessage`.
+ */
+ async producePersonMergeEvent(sourcePerson: InternalPerson, targetPerson: InternalPerson): Promise<void> {
+ if (!this.mergeEventsConfig.enabled) {
+ return
+ }
+ const { key, partition, value } = buildPersonMergeEventMessage(
+ this.team.id,
+ sourcePerson.uuid,
+ targetPerson.uuid,
+ Date.now(),
+ this.mergeEventsConfig.partitionCount
+ )
+ await this.outputs.produce(PERSON_MERGE_EVENTS_OUTPUT, {
+ value,
+ key,
+ partition,
+ teamId: this.team.id,
+ })
+ }
}
diff --git a/nodejs/src/ingestion/common/persons/person-merge-event.test.ts b/nodejs/src/ingestion/common/persons/person-merge-event.test.ts
new file mode 100644
index 000000000000..861405f9ad18
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/person-merge-event.test.ts
@@ -0,0 +1,65 @@
+import { murmur2Partition } from '~/kafka/murmur2'
+import { parseJSON } from '~/utils/json-parse'
+
+import { MERGE_EVENT_SCHEMA_VERSION, buildPersonMergeEventMessage } from './person-merge-event'
+
+describe('buildPersonMergeEventMessage', () => {
+ const teamId = 2
+ const oldPersonUuid = '01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee'
+ const newPersonUuid = '01928bbb-cccc-dddd-eeee-ffffffffffff'
+ const mergedAtMs = 1716800000000
+
+ function build() {
+ return buildPersonMergeEventMessage(teamId, oldPersonUuid, newPersonUuid, mergedAtMs, 64)
+ }
+
+ function decode(value: Buffer): Record<string, unknown> {
+ return parseJSON(value.toString())
+ }
+
+ it('keys by team_id and P_old (the deleted person)', () => {
+ expect(build().key).toBe(`${teamId}:${oldPersonUuid}`)
+ })
+
+ it('partitions with Kafka murmur2 over the key', () => {
+ const { key, partition } = build()
+ expect(partition).toBe(murmur2Partition(key, 64))
+ // The Rust partitioner places this exact key at partition 58 (see murmur2.test.ts fixture).
+ expect(partition).toBe(58)
+ })
+
+ it('serializes exactly the keys the Rust PersonMergeEvent decodes', () => {
+ const decoded = decode(build().value)
+ expect(Object.keys(decoded).sort()).toEqual([
+ 'merged_at_ms',
+ 'new_person_uuid',
+ 'old_person_uuid',
+ 'schema_version',
+ 'team_id',
+ ])
+ })
+
+ it('pins schema_version to 1', () => {
+ expect(decode(build().value).schema_version).toBe(1)
+ expect(MERGE_EVENT_SCHEMA_VERSION).toBe(1)
+ })
+
+ it('carries the merge identities and timestamp verbatim', () => {
+ const decoded = decode(build().value)
+ expect(decoded.team_id).toBe(teamId)
+ expect(decoded.old_person_uuid).toBe(oldPersonUuid)
+ expect(decoded.new_person_uuid).toBe(newPersonUuid)
+ expect(decoded.merged_at_ms).toBe(mergedAtMs)
+ })
+
+ it('encodes numeric fields as numbers, not strings (serde i32/i64/u32 reject strings)', () => {
+ const decoded = decode(build().value)
+ expect(typeof decoded.team_id).toBe('number')
+ expect(typeof decoded.merged_at_ms).toBe('number')
+ expect(typeof decoded.schema_version).toBe('number')
+ })
+
+ it('is partition-stable for the same inputs', () => {
+ expect(build().partition).toBe(build().partition)
+ })
+})
diff --git a/nodejs/src/ingestion/common/persons/person-merge-event.ts b/nodejs/src/ingestion/common/persons/person-merge-event.ts
new file mode 100644
index 000000000000..e5e50e6b7c4d
--- /dev/null
+++ b/nodejs/src/ingestion/common/persons/person-merge-event.ts
@@ -0,0 +1,63 @@
+import { murmur2Partition } from '~/kafka/murmur2'
+
+/**
+ * Wire shape of a committed `P_old -> P_new` person merge event.
+ *
+ * This MUST decode by the Rust `PersonMergeEvent` struct in
+ * `rust/cohort-stream-processor/src/merge/transfer.rs` (pinned by its
+ * `person_merge_event_shape_is_pinned` test). Field names and types are load-bearing: serde reads
+ * `team_id` as i32, `merged_at_ms` as i64, `schema_version` as u32, so they must serialize as JSON
+ * numbers — stringified numbers are rejected on the Rust side.
+ */
+export interface PersonMergeKafkaEvent {
+ team_id: number
+ /** P_old — the person deleted by the merge. Also the partition key. */
+ old_person_uuid: string
+ /** P_new — the merge target. */
+ new_person_uuid: string
+ merged_at_ms: number
+ schema_version: number
+}
+
+/** Mirrors `MERGE_EVENT_SCHEMA_VERSION` in transfer.rs. */
+export const MERGE_EVENT_SCHEMA_VERSION = 1
+
+export interface PersonMergeEventMessage {
+ key: string
+ partition: number
+ value: Buffer
+}
+
+/**
+ * Build the Kafka message for a committed person merge.
+ *
+ * The key is `"{team_id}:{old_person_uuid}"` (P_old) so the message lands on the worker that owns
+ * P_old's Stage-1 state — matches `merge_partition_key` in partitioner.rs.
+ *
+ * The partition is computed explicitly with Kafka-Java murmur2 rather than left to the producer's
+ * default partitioner: (1) librdkafka defaults to CRC32 `consistent_random`, which would route to
+ * the wrong worker; (2) node-rdkafka silently discards a global-config `partitioner` key (its
+ * client always passes a topicConf to the native ctor, replacing librdkafka's default_topic_conf),
+ * so there is no config-only way to switch it.
+ */
+export function buildPersonMergeEventMessage(
+ teamId: number,
+ oldPersonUuid: string,
+ newPersonUuid: string,
+ mergedAtMs: number,
+ partitionCount: number
+): PersonMergeEventMessage {
+ const key = `${teamId}:${oldPersonUuid}`
+ const event: PersonMergeKafkaEvent = {
+ team_id: teamId,
+ old_person_uuid: oldPersonUuid,
+ new_person_uuid: newPersonUuid,
+ merged_at_ms: mergedAtMs,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ }
+ return {
+ key,
+ partition: murmur2Partition(key, partitionCount),
+ value: Buffer.from(JSON.stringify(event)),
+ }
+}
diff --git a/nodejs/src/ingestion/common/persons/person-merge-service.ts b/nodejs/src/ingestion/common/persons/person-merge-service.ts
index 95d6f7c9be2c..29f59f4daa81 100644
--- a/nodejs/src/ingestion/common/persons/person-merge-service.ts
+++ b/nodejs/src/ingestion/common/persons/person-merge-service.ts
@@ -42,6 +42,11 @@ export const mergeTxnSuccessCounter = new Counter({
help: 'Number of person merges that succeeded.',
labelNames: ['call', 'oldPersonIdentified', 'newPersonIdentified'],
})
+
+export const personMergeEventProducedCounter = new Counter({
+ name: 'person_merge_event_produced_total',
+ help: 'Number of person_merge_events produce attempts after a committed merge (gate-on merges only).',
+})
// used to prevent identify from being used with generic IDs
// that we can safely assume stem from a bug or mistake
const BARE_CASE_INSENSITIVE_ILLEGAL_IDS = [
@@ -516,7 +521,16 @@ export class PersonMergeService {
})
.inc()
- const kafkaAck = this.context.produceMessages(kafkaMessages)
+ // Produce-after-commit: the merge event is emitted only after the Postgres txn commits,
+ // alongside the clickhouse_person messages. A crash between commit and ack loses it; the
+ // downstream protocol is idempotent on replay but cannot recover a never-produced event.
+ if (this.context.mergeEventsConfig.enabled) {
+ personMergeEventProducedCounter.inc()
+ }
+ const kafkaAck = Promise.all([
+ this.context.produceMessages(kafkaMessages),
+ this.context.producePersonMergeEvent(currentSourcePerson, mergedPerson),
+ ]).then(() => undefined)
return mergeSuccess(mergedPerson, kafkaAck, true)
} catch (error) {
// Map exceptions to result types - these will cause transaction rollback
diff --git a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts
index d652fb54d6d4..b2473f0d2835 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/event-pipeline-options.ts
@@ -3,6 +3,8 @@ export interface EventPipelineRunnerOptions {
PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: number
PERSON_MERGE_ASYNC_ENABLED: boolean
PERSON_MERGE_SYNC_BATCH_SIZE: number
+ PERSON_MERGE_EVENTS_ENABLED: boolean
+ PERSON_MERGE_EVENTS_PARTITION_COUNT: number
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: number
PERSON_PROPERTIES_UPDATE_ALL: boolean
/** Teams whose $feature_flag_called events default to personless: '*' for all, '' to disable, or comma-separated team IDs */
diff --git a/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.test.ts
index 5308be206cb5..6240ee804c45 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.test.ts
@@ -1,5 +1,5 @@
import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
-import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs'
+import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'
import { BatchWritingGroupStore } from '~/ingestion/common/groups/batch-writing-group-store'
import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
import { PersonOutputs } from '~/ingestion/common/persons/person-context'
@@ -66,7 +66,10 @@ describe('flush-batch-stores-step', () => {
} as any
mockOutputs = createMockIngestionOutputs<
- typeof PERSONS_OUTPUT | typeof PERSON_DISTINCT_IDS_OUTPUT | typeof INGESTION_WARNINGS_OUTPUT
+ | typeof PERSONS_OUTPUT
+ | typeof PERSON_DISTINCT_IDS_OUTPUT
+ | typeof INGESTION_WARNINGS_OUTPUT
+ | typeof PERSON_MERGE_EVENTS_OUTPUT
>()
storesConfig = {
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts
index 6affd8df984b..92bf9092812b 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.test.ts
@@ -3,11 +3,11 @@ import { mockProducer } from '~/tests/helpers/mocks/producer.mock'
import { DateTime } from 'luxon'
import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
-import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs'
+import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'
-import { KAFKA_PERSON, KAFKA_PERSON_DISTINCT_ID } from '~/config/kafka-topics'
+import { KAFKA_PERSON, KAFKA_PERSON_DISTINCT_ID, KAFKA_PERSON_MERGE_EVENTS } from '~/config/kafka-topics'
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { BatchBoundPersonsStore } from '~/ingestion/common/persons/persons-store-for-batch'
import { PipelineResultType, isOkResult } from '~/ingestion/framework/results'
@@ -98,6 +98,12 @@ describe('createProcessPersonlessStep', () => {
mockProducer,
'test'
),
+ [PERSON_MERGE_EVENTS_OUTPUT]: new SingleIngestionOutput(
+ PERSON_MERGE_EVENTS_OUTPUT,
+ KAFKA_PERSON_MERGE_EVENTS,
+ mockProducer,
+ 'test'
+ ),
})
personsStore = new BatchWritingPersonsStore(personRepository, storeOutputs)
diff --git a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts
index 95160691b8db..15ce470b99cd 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/process-persons-step.ts
@@ -58,7 +58,11 @@ export function createProcessPersonsStep<TInput extends ProcessPersonsInput>(
options.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,
mergeMode,
options.PERSON_PROPERTIES_UPDATE_ALL,
- shouldUpdateLastSeenAt
+ shouldUpdateLastSeenAt,
+ {
+ enabled: options.PERSON_MERGE_EVENTS_ENABLED,
+ partitionCount: options.PERSON_MERGE_EVENTS_PARTITION_COUNT,
+ }
)
const processor = new PersonEventProcessor(
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index d678ffcc5ad9..b8ef283b119b 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -122,6 +122,10 @@ export type IngestionConsumerConfig = {
PERSON_MERGE_ASYNC_TOPIC: string
PERSON_MERGE_ASYNC_ENABLED: boolean
PERSON_MERGE_SYNC_BATCH_SIZE: number
+ // Kill switch for emitting person_merge_events to the cohort-stream-processor.
+ PERSON_MERGE_EVENTS_ENABLED: boolean
+ // Must equal the person_merge_events topic partition count and the Rust COHORT_PARTITION_COUNT.
+ PERSON_MERGE_EVENTS_PARTITION_COUNT: number
// Group batch writing config
GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES: number
@@ -248,6 +252,8 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_ASYNC_TOPIC: '',
PERSON_MERGE_ASYNC_ENABLED: false,
PERSON_MERGE_SYNC_BATCH_SIZE: 0,
+ PERSON_MERGE_EVENTS_ENABLED: false,
+ PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
// Group batch writing config
GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES: 10,
@@ -355,6 +361,9 @@ export type IngestionOutputsConfig = {
INGESTION_OUTPUT_PERSON_DISTINCT_IDS_TOPIC: string
INGESTION_OUTPUT_PERSON_DISTINCT_IDS_PRODUCER: ProducerName
+ INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC: string
+ INGESTION_OUTPUT_PERSON_MERGE_EVENTS_PRODUCER: ProducerName
+
INGESTION_OUTPUT_APP_METRICS_TOPIC: string
INGESTION_OUTPUT_APP_METRICS_PRODUCER: ProducerName
@@ -387,6 +396,9 @@ export function getDefaultIngestionOutputsConfig(): IngestionOutputsConfig {
INGESTION_OUTPUT_PERSONS_PRODUCER: INGESTION_DOWNSTREAM_PRODUCER,
INGESTION_OUTPUT_PERSON_DISTINCT_IDS_TOPIC: KAFKA_PERSON_DISTINCT_ID,
INGESTION_OUTPUT_PERSON_DISTINCT_IDS_PRODUCER: INGESTION_DOWNSTREAM_PRODUCER,
+ // Empty topic skips the startup topic-existence check.
+ INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC: '',
+ INGESTION_OUTPUT_PERSON_MERGE_EVENTS_PRODUCER: INGESTION_DOWNSTREAM_PRODUCER,
INGESTION_OUTPUT_APP_METRICS_TOPIC: KAFKA_APP_METRICS_2,
INGESTION_OUTPUT_APP_METRICS_PRODUCER: INGESTION_DOWNSTREAM_PRODUCER,
INGESTION_OUTPUT_LOG_ENTRIES_TOPIC: KAFKA_LOG_ENTRIES,
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index fd5d036443d6..114420689405 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -14,7 +14,14 @@ import {
OverflowOutput,
TophogOutput,
} from '~/common/outputs'
-import { AiEventOutput, AsyncOutput, EventOutput, PersonDistinctIdsOutput, PersonsOutput } from '~/common/outputs'
+import {
+ AiEventOutput,
+ AsyncOutput,
+ EventOutput,
+ PersonDistinctIdsOutput,
+ PersonMergeEventsOutput,
+ PersonsOutput,
+} from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PersonRepository } from '~/common/persons/repositories/person-repository'
import { instrumentFn } from '~/common/tracing/tracing-utils'
@@ -74,6 +81,7 @@ export interface IngestionConsumerDeps {
| GroupsOutput
| PersonsOutput
| PersonDistinctIdsOutput
+ | PersonMergeEventsOutput
| AppMetricsOutput
| TophogOutput
>
@@ -281,6 +289,8 @@ export class IngestionConsumer {
PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: this.config.PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT,
PERSON_MERGE_ASYNC_ENABLED: this.config.PERSON_MERGE_ASYNC_ENABLED,
PERSON_MERGE_SYNC_BATCH_SIZE: this.config.PERSON_MERGE_SYNC_BATCH_SIZE,
+ PERSON_MERGE_EVENTS_ENABLED: this.config.PERSON_MERGE_EVENTS_ENABLED,
+ PERSON_MERGE_EVENTS_PARTITION_COUNT: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,
PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
diff --git a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
index f7e15b2c112e..659fb2ceac3f 100644
--- a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
@@ -24,7 +24,14 @@ import { PluginEvent } from '~/plugin-scaffold'
import { EventHeaders, Team } from '~/types'
import { TeamManager } from '~/utils/team-manager'
-import { AsyncOutput, EVENTS_OUTPUT, EventOutput, PersonDistinctIdsOutput, PersonsOutput } from './outputs'
+import {
+ AsyncOutput,
+ EVENTS_OUTPUT,
+ EventOutput,
+ PersonDistinctIdsOutput,
+ PersonMergeEventsOutput,
+ PersonsOutput,
+} from './outputs'
export interface EventSubpipelineInput {
message: Message
@@ -37,7 +44,9 @@ export interface EventSubpipelineInput {
export interface EventSubpipelineConfig {
options: EventPipelineRunnerOptions
- outputs: IngestionOutputs<EventOutput | IngestionWarningsOutput | PersonsOutput | PersonDistinctIdsOutput>
+ outputs: IngestionOutputs<
+ EventOutput | IngestionWarningsOutput | PersonsOutput | PersonDistinctIdsOutput | PersonMergeEventsOutput
+ >
teamManager: TeamManager
groupTypeManager: GroupTypeManager
hogTransformer: HogTransformer
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index 138cfb6d7fc8..ae4bccbc0e26 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -49,7 +49,14 @@ import { EventSchemaEnforcementManager } from '~/utils/event-schema-enforcement-
import { PromiseScheduler } from '~/utils/promise-scheduler'
import { TeamManager } from '~/utils/team-manager'
-import { AiEventOutput, AsyncOutput, EventOutput, PersonDistinctIdsOutput, PersonsOutput } from './outputs'
+import {
+ AiEventOutput,
+ AsyncOutput,
+ EventOutput,
+ PersonDistinctIdsOutput,
+ PersonMergeEventsOutput,
+ PersonsOutput,
+} from './outputs'
import {
PerDistinctIdPipelineConfig,
PerDistinctIdPipelineInput,
@@ -76,6 +83,7 @@ export interface JoinedIngestionPipelineConfig {
| GroupsOutput
| PersonsOutput
| PersonDistinctIdsOutput
+ | PersonMergeEventsOutput
| AppMetricsOutput
>
splitAiEventsConfig: SplitAiEventsStepConfig
diff --git a/nodejs/src/ingestion/pipelines/analytics/outputs/registry.ts b/nodejs/src/ingestion/pipelines/analytics/outputs/registry.ts
index 0e570b8bd968..0e555b7e8e1c 100644
--- a/nodejs/src/ingestion/pipelines/analytics/outputs/registry.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/outputs/registry.ts
@@ -1,4 +1,11 @@
-import { AI_EVENTS_OUTPUT, ASYNC_OUTPUT, EVENTS_OUTPUT, PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '.'
+import {
+ AI_EVENTS_OUTPUT,
+ ASYNC_OUTPUT,
+ EVENTS_OUTPUT,
+ PERSONS_OUTPUT,
+ PERSON_DISTINCT_IDS_OUTPUT,
+ PERSON_MERGE_EVENTS_OUTPUT,
+} from '.'
import {
APP_METRICS_OUTPUT,
@@ -13,53 +20,60 @@ import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-buil
/** Register all analytics ingestion outputs on the builder. Call `.build(registry, config)` to resolve. */
export function createOutputsRegistry() {
- return new IngestionOutputsBuilder()
- .register(EVENTS_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_EVENTS_TOPIC',
- producerKey: 'INGESTION_OUTPUT_EVENTS_PRODUCER',
- })
- .register(AI_EVENTS_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_AI_EVENTS_TOPIC',
- producerKey: 'INGESTION_OUTPUT_AI_EVENTS_PRODUCER',
- })
- .register(INGESTION_WARNINGS_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_TOPIC',
- producerKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_PRODUCER',
- })
- .register(DLQ_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_DLQ_TOPIC',
- producerKey: 'INGESTION_OUTPUT_DLQ_PRODUCER',
- })
- .register(OVERFLOW_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_OVERFLOW_TOPIC',
- producerKey: 'INGESTION_OUTPUT_OVERFLOW_PRODUCER',
- })
- .register(ASYNC_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_ASYNC_TOPIC',
- producerKey: 'INGESTION_OUTPUT_ASYNC_PRODUCER',
- })
- .register(GROUPS_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_GROUPS_TOPIC',
- producerKey: 'INGESTION_OUTPUT_GROUPS_PRODUCER',
- })
- .register(PERSONS_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_PERSONS_TOPIC',
- producerKey: 'INGESTION_OUTPUT_PERSONS_PRODUCER',
- })
- .register(PERSON_DISTINCT_IDS_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_PERSON_DISTINCT_IDS_TOPIC',
- producerKey: 'INGESTION_OUTPUT_PERSON_DISTINCT_IDS_PRODUCER',
- })
- .register(APP_METRICS_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_APP_METRICS_TOPIC',
- producerKey: 'INGESTION_OUTPUT_APP_METRICS_PRODUCER',
- })
- .register(LOG_ENTRIES_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_LOG_ENTRIES_TOPIC',
- producerKey: 'INGESTION_OUTPUT_LOG_ENTRIES_PRODUCER',
- })
- .register(TOPHOG_OUTPUT, {
- topicKey: 'INGESTION_OUTPUT_TOPHOG_TOPIC',
- producerKey: 'INGESTION_OUTPUT_TOPHOG_PRODUCER',
- })
+ return (
+ new IngestionOutputsBuilder()
+ .register(EVENTS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_EVENTS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_EVENTS_PRODUCER',
+ })
+ .register(AI_EVENTS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_AI_EVENTS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_AI_EVENTS_PRODUCER',
+ })
+ .register(INGESTION_WARNINGS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_INGESTION_WARNINGS_PRODUCER',
+ })
+ .register(DLQ_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_DLQ_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_DLQ_PRODUCER',
+ })
+ .register(OVERFLOW_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_OVERFLOW_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_OVERFLOW_PRODUCER',
+ })
+ .register(ASYNC_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_ASYNC_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_ASYNC_PRODUCER',
+ })
+ .register(GROUPS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_GROUPS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_GROUPS_PRODUCER',
+ })
+ .register(PERSONS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_PERSONS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_PERSONS_PRODUCER',
+ })
+ .register(PERSON_DISTINCT_IDS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_PERSON_DISTINCT_IDS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_PERSON_DISTINCT_IDS_PRODUCER',
+ })
+ // Single-target: consumed by the cohort-stream-processor (Rust), not ClickHouse, so no dual-write.
+ .register(PERSON_MERGE_EVENTS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_PERSON_MERGE_EVENTS_PRODUCER',
+ })
+ .register(APP_METRICS_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_APP_METRICS_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_APP_METRICS_PRODUCER',
+ })
+ .register(LOG_ENTRIES_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_LOG_ENTRIES_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_LOG_ENTRIES_PRODUCER',
+ })
+ .register(TOPHOG_OUTPUT, {
+ topicKey: 'INGESTION_OUTPUT_TOPHOG_TOPIC',
+ producerKey: 'INGESTION_OUTPUT_TOPHOG_PRODUCER',
+ })
+ )
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
index 52109c257dff..6ee8a1ee4486 100644
--- a/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/per-distinct-id-pipeline.ts
@@ -15,14 +15,26 @@ import { Team } from '~/types'
import { TeamManager } from '~/utils/team-manager'
import { EventSubpipelineInput, createEventSubpipeline } from './event-subpipeline'
-import { AiEventOutput, AsyncOutput, EventOutput, PersonDistinctIdsOutput, PersonsOutput } from './outputs'
+import {
+ AiEventOutput,
+ AsyncOutput,
+ EventOutput,
+ PersonDistinctIdsOutput,
+ PersonMergeEventsOutput,
+ PersonsOutput,
+} from './outputs'
export type PerDistinctIdPipelineInput = EventSubpipelineInput & AiEventSubpipelineInput
export interface PerDistinctIdPipelineConfig {
options: EventPipelineRunnerOptions
outputs: IngestionOutputs<
- EventOutput | AiEventOutput | IngestionWarningsOutput | PersonsOutput | PersonDistinctIdsOutput
+ | EventOutput
+ | AiEventOutput
+ | IngestionWarningsOutput
+ | PersonsOutput
+ | PersonDistinctIdsOutput
+ | PersonMergeEventsOutput
>
splitAiEventsConfig: SplitAiEventsStepConfig
aiSubpipelineFactory: AiEventSubpipelineFactory
diff --git a/nodejs/src/kafka/murmur2.test.ts b/nodejs/src/kafka/murmur2.test.ts
new file mode 100644
index 000000000000..b165138ad06a
--- /dev/null
+++ b/nodejs/src/kafka/murmur2.test.ts
@@ -0,0 +1,49 @@
+import { murmur2, murmur2Partition } from './murmur2'
+
+describe('murmur2', () => {
+ // Published Kafka murmur2 vectors, identical to the Rust pin in
+ // rust/cohort-stream-processor/src/partitions/partitioner.rs. Expected values are signed i32, so
+ // we compare the unsigned hash reinterpreted with `| 0`.
+ const publishedVectors: [string, number][] = [
+ ['21', -973932308],
+ ['foobar', -790332482],
+ ['a-little-bit-long-string', -985981536],
+ ['a-little-bit-longer-string', -1486304829],
+ ['lkjh234lh9fiuh90y23oiuhsafujhadof229phr9h19h89h8', -58897971],
+ ['abc', 479470107],
+ ]
+
+ it.each(publishedVectors)('matches the published Kafka vector for %p', (input, expected) => {
+ expect(murmur2(Buffer.from(input, 'utf8')) | 0).toBe(expected)
+ })
+
+ it('reproduces the negative-hash vector through the positivity mask', () => {
+ // Raw hash is negative (high bit set); the mask must clear it before modulo.
+ const raw = murmur2(Buffer.from('a-little-bit-long-string', 'utf8'))
+ expect(raw | 0).toBeLessThan(0)
+ expect(murmur2Partition('a-little-bit-long-string', 64)).toBeGreaterThanOrEqual(0)
+ expect(murmur2Partition('a-little-bit-long-string', 64)).toBeLessThan(64)
+ })
+
+ it('produces identical output for a string key and its UTF-8 Buffer', () => {
+ const key = '2:01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee'
+ expect(murmur2Partition(key, 64)).toBe(murmur2Partition(Buffer.from(key, 'utf8'), 64))
+ })
+
+ // Cross-language fixture: the partition partitioner.rs::partition_for computes for this key at
+ // 64 partitions (raw murmur2 = 989609914, 989609914 % 64 = 58). A CRC32 regression would land
+ // elsewhere.
+ it('matches the Rust partitioner for the merge-key fixture', () => {
+ const key = '2:01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee'
+ expect(murmur2(Buffer.from(key, 'utf8')) | 0).toBe(989609914)
+ expect(murmur2Partition(key, 64)).toBe(58)
+ })
+
+ it('always returns a partition within range', () => {
+ for (const [input] of publishedVectors) {
+ const partition = murmur2Partition(input, 64)
+ expect(partition).toBeGreaterThanOrEqual(0)
+ expect(partition).toBeLessThan(64)
+ }
+ })
+})
diff --git a/nodejs/src/kafka/murmur2.ts b/nodejs/src/kafka/murmur2.ts
new file mode 100644
index 000000000000..4e66828c818f
--- /dev/null
+++ b/nodejs/src/kafka/murmur2.ts
@@ -0,0 +1,63 @@
+/**
+ * Kafka-compatible `murmur2` partitioner: `(murmur2(key) & 0x7fffffff) % partitions`.
+ *
+ * This is the Kafka-Java / python-kafka default, NOT the CRC32 `consistent_random` default of
+ * librdkafka clients (node-rdkafka). The cohort-stream-processor routes a merge to the worker that
+ * owns `murmur2(key) mod 64`, so producers feeding it must reproduce this exact math. Mirrors the
+ * Rust side at `rust/cohort-stream-processor/src/partitions/partitioner.rs`; both are pinned to the
+ * published Kafka test vectors.
+ *
+ * `Math.imul` + `>>> 0` reproduce Rust's wrapping `u32` arithmetic (`wrapping_mul` and unsigned
+ * reinterpretation).
+ */
+
+const MURMUR2_SEED = 0x9747b28c
+const MURMUR2_M = 0x5bd1e995
+const MURMUR2_R = 24
+
+/**
+ * Kafka `murmur2` hash. Returns the raw hash as an unsigned 32-bit integer; `murmur2Partition`
+ * applies the positivity mask and modulo. For the signed Kafka-vector form, use `murmur2(data) | 0`.
+ */
+export function murmur2(data: Buffer): number {
+ const len = data.length
+ let h = (MURMUR2_SEED ^ len) >>> 0
+
+ const nblocks = Math.floor(len / 4)
+ for (let block = 0; block < nblocks; block++) {
+ const i = block * 4
+ let k = (data[i] | (data[i + 1] << 8) | (data[i + 2] << 16) | (data[i + 3] << 24)) >>> 0
+ k = Math.imul(k, MURMUR2_M) >>> 0
+ k = (k ^ (k >>> MURMUR2_R)) >>> 0
+ k = Math.imul(k, MURMUR2_M) >>> 0
+ h = Math.imul(h, MURMUR2_M) >>> 0
+ h = (h ^ k) >>> 0
+ }
+
+ const tail = nblocks * 4
+ const remainder = len & 3
+ if (remainder >= 3) {
+ h = (h ^ (data[tail + 2] << 16)) >>> 0
+ }
+ if (remainder >= 2) {
+ h = (h ^ (data[tail + 1] << 8)) >>> 0
+ }
+ if (remainder >= 1) {
+ h = (h ^ data[tail]) >>> 0
+ h = Math.imul(h, MURMUR2_M) >>> 0
+ }
+
+ h = (h ^ (h >>> 13)) >>> 0
+ h = Math.imul(h, MURMUR2_M) >>> 0
+ h = (h ^ (h >>> 15)) >>> 0
+ return h >>> 0
+}
+
+/**
+ * The partition `key` lands on: `(murmur2(key) & 0x7fffffff) % partitionCount`. Mirrors
+ * `partitioner.rs::partition_for`. `partitionCount` must be > 0.
+ */
+export function murmur2Partition(key: string | Buffer, partitionCount: number): number {
+ const buffer = Buffer.isBuffer(key) ? key : Buffer.from(key, 'utf8')
+ return (murmur2(buffer) & 0x7fffffff) % partitionCount
+}
diff --git a/nodejs/src/kafka/producer.test.ts b/nodejs/src/kafka/producer.test.ts
new file mode 100644
index 000000000000..79ea66d69a9b
--- /dev/null
+++ b/nodejs/src/kafka/producer.test.ts
@@ -0,0 +1,38 @@
+import { HighLevelProducer } from 'node-rdkafka'
+
+import { KafkaProducerWrapper } from './producer'
+
+describe('KafkaProducerWrapper.produce', () => {
+ let produceMock: jest.Mock
+ let wrapper: KafkaProducerWrapper
+
+ beforeEach(() => {
+ // node-rdkafka invokes the trailing (error, offset) callback; call it so produce() resolves.
+ produceMock = jest.fn((...args: any[]) => {
+ const cb = args[args.length - 1]
+ cb(null, 0)
+ })
+ const mockHighLevelProducer = {
+ produce: produceMock,
+ on: jest.fn(),
+ } as unknown as HighLevelProducer
+ wrapper = new KafkaProducerWrapper(mockHighLevelProducer)
+ })
+
+ it('passes an explicit partition as the second argument to HighLevelProducer.produce', async () => {
+ await wrapper.produce({ topic: 't', key: Buffer.from('k'), value: Buffer.from('v'), partition: 7 })
+ expect(produceMock).toHaveBeenCalledTimes(1)
+ expect(produceMock.mock.calls[0][1]).toBe(7)
+ })
+
+ it('passes null partition when none is supplied (backwards compatible)', async () => {
+ await wrapper.produce({ topic: 't', key: Buffer.from('k'), value: Buffer.from('v') })
+ expect(produceMock).toHaveBeenCalledTimes(1)
+ expect(produceMock.mock.calls[0][1]).toBeNull()
+ })
+
+ it('treats partition 0 as explicit, not as a missing value', async () => {
+ await wrapper.produce({ topic: 't', key: Buffer.from('k'), value: Buffer.from('v'), partition: 0 })
+ expect(produceMock.mock.calls[0][1]).toBe(0)
+ })
+})
diff --git a/nodejs/src/kafka/producer.ts b/nodejs/src/kafka/producer.ts
index a26b79f2eccb..b7fc05ce6933 100644
--- a/nodejs/src/kafka/producer.ts
+++ b/nodejs/src/kafka/producer.ts
@@ -130,11 +130,14 @@ export class KafkaProducerWrapper {
key,
topic,
headers,
+ partition,
}: {
value: MessageValue
key: MessageKey
topic: string
headers?: Record<string, string>
+ /** Explicit target partition. When omitted, librdkafka's default partitioner picks one. */
+ partition?: number
}): Promise<void> {
const labels: Record<string, string> = { topic_name: topic }
if (this.name) {
@@ -166,7 +169,7 @@ export class KafkaProducerWrapper {
new Promise((resolve, reject) => {
this.producer.produce(
topic,
- null,
+ partition ?? null,
value,
key,
Date.now(),
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index 333c7a1a34d8..1018100a0466 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -375,6 +375,8 @@ export class IngestionApiServer implements NodeServer {
PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: this.config.PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT,
PERSON_MERGE_ASYNC_ENABLED: this.config.PERSON_MERGE_ASYNC_ENABLED,
PERSON_MERGE_SYNC_BATCH_SIZE: this.config.PERSON_MERGE_SYNC_BATCH_SIZE,
+ PERSON_MERGE_EVENTS_ENABLED: this.config.PERSON_MERGE_EVENTS_ENABLED,
+ PERSON_MERGE_EVENTS_PARTITION_COUNT: this.config.PERSON_MERGE_EVENTS_PARTITION_COUNT,
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,
PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: this.config.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
diff --git a/nodejs/tests/helpers/ingestion-outputs.ts b/nodejs/tests/helpers/ingestion-outputs.ts
index c99379e6568c..0a910a7c5e42 100644
--- a/nodejs/tests/helpers/ingestion-outputs.ts
+++ b/nodejs/tests/helpers/ingestion-outputs.ts
@@ -13,6 +13,7 @@ import {
EVENTS_OUTPUT,
PERSONS_OUTPUT,
PERSON_DISTINCT_IDS_OUTPUT,
+ PERSON_MERGE_EVENTS_OUTPUT,
} from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
@@ -32,6 +33,7 @@ import {
KAFKA_LOG_ENTRIES,
KAFKA_PERSON,
KAFKA_PERSON_DISTINCT_ID,
+ KAFKA_PERSON_MERGE_EVENTS,
} from '../../src/config/kafka-topics'
import { KafkaProducerWrapper } from '../../src/kafka/producer'
@@ -58,6 +60,7 @@ export function createTestIngestionOutputs(kafkaProducer: KafkaProducerWrapper)
[GROUPS_OUTPUT]: testOutput(GROUPS_OUTPUT, KAFKA_GROUPS, kafkaProducer),
[PERSONS_OUTPUT]: testOutput(PERSONS_OUTPUT, KAFKA_PERSON, kafkaProducer),
[PERSON_DISTINCT_IDS_OUTPUT]: testOutput(PERSON_DISTINCT_IDS_OUTPUT, KAFKA_PERSON_DISTINCT_ID, kafkaProducer),
+ [PERSON_MERGE_EVENTS_OUTPUT]: testOutput(PERSON_MERGE_EVENTS_OUTPUT, KAFKA_PERSON_MERGE_EVENTS, kafkaProducer),
[APP_METRICS_OUTPUT]: testOutput(APP_METRICS_OUTPUT, KAFKA_APP_METRICS_2, kafkaProducer),
[LOG_ENTRIES_OUTPUT]: testOutput(LOG_ENTRIES_OUTPUT, KAFKA_LOG_ENTRIES, kafkaProducer),
[TOPHOG_OUTPUT]: testOutput(TOPHOG_OUTPUT, KAFKA_CLICKHOUSE_TOPHOG, kafkaProducer),
diff --git a/nodejs/tests/helpers/kafka.ts b/nodejs/tests/helpers/kafka.ts
index 2550d797206d..6b68bd61bcfd 100644
--- a/nodejs/tests/helpers/kafka.ts
+++ b/nodejs/tests/helpers/kafka.ts
@@ -27,6 +27,7 @@ import {
KAFKA_PERSON,
KAFKA_PERSON_DISTINCT_ID,
KAFKA_PERSON_DISTINCT_ID_OVERRIDES,
+ KAFKA_PERSON_MERGE_EVENTS,
KAFKA_PERSON_UNIQUE_ID,
KAFKA_PLUGIN_LOG_ENTRIES,
KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_EVENTS,
@@ -97,6 +98,7 @@ export const TEST_KAFKA_TOPICS = [
KAFKA_CDP_CLICKHOUSE_BEHAVIORAL_COHORTS_MATCHES,
KAFKA_CDP_CLICKHOUSE_PREFILTERED_EVENTS,
KAFKA_COHORT_MEMBERSHIP_CHANGED,
+ KAFKA_PERSON_MERGE_EVENTS,
KAFKA_CLICKHOUSE_TOPHOG,
]
diff --git a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
index f14b38b531c8..b5c2c6a5211a 100644
--- a/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
+++ b/nodejs/tests/ingestion/common/steps/event-processing/process-persons-step.integration.test.ts
@@ -4,11 +4,16 @@ import { DateTime } from 'luxon'
import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
import { ASYNC_OUTPUT } from '~/common/outputs'
-import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs'
+import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'
-import { KAFKA_INGESTION_WARNINGS, KAFKA_PERSON, KAFKA_PERSON_DISTINCT_ID } from '~/config/kafka-topics'
+import {
+ KAFKA_INGESTION_WARNINGS,
+ KAFKA_PERSON,
+ KAFKA_PERSON_DISTINCT_ID,
+ KAFKA_PERSON_MERGE_EVENTS,
+} from '~/config/kafka-topics'
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { PersonOutputs } from '~/ingestion/common/persons/person-context'
import { BatchBoundPersonsStore } from '~/ingestion/common/persons/persons-store-for-batch'
@@ -41,6 +46,8 @@ describe('createProcessPersonsStep', () => {
PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: 100,
PERSON_MERGE_ASYNC_ENABLED: false,
PERSON_MERGE_SYNC_BATCH_SIZE: 1,
+ PERSON_MERGE_EVENTS_ENABLED: false,
+ PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,
PERSON_PROPERTIES_UPDATE_ALL: false,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',
@@ -68,6 +75,12 @@ describe('createProcessPersonsStep', () => {
mockProducer,
'test'
),
+ [PERSON_MERGE_EVENTS_OUTPUT]: new SingleIngestionOutput(
+ PERSON_MERGE_EVENTS_OUTPUT,
+ KAFKA_PERSON_MERGE_EVENTS,
+ mockProducer,
+ 'test'
+ ),
})
personsStore = new BatchWritingPersonsStore(personRepository, personOutputs)
diff --git a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
index 93cfe5a18e2f..fc28ab67ee27 100644
--- a/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/ai/pipelines/ai-event-subpipeline.integration.test.ts
@@ -1,7 +1,13 @@
import { DateTime } from 'luxon'
import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
-import { AI_EVENTS_OUTPUT, EVENTS_OUTPUT, PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs'
+import {
+ AI_EVENTS_OUTPUT,
+ EVENTS_OUTPUT,
+ PERSONS_OUTPUT,
+ PERSON_DISTINCT_IDS_OUTPUT,
+ PERSON_MERGE_EVENTS_OUTPUT,
+} from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { GroupStoreForBatch } from '~/ingestion/common/groups/group-store-for-batch'
import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
@@ -88,6 +94,8 @@ function buildPipeline(configOverrides: Partial<AiEventSubpipelineConfig> = {})
PERSON_MERGE_MOVE_DISTINCT_ID_LIMIT: 0,
PERSON_MERGE_ASYNC_ENABLED: false,
PERSON_MERGE_SYNC_BATCH_SIZE: 0,
+ PERSON_MERGE_EVENTS_ENABLED: false,
+ PERSON_MERGE_EVENTS_PARTITION_COUNT: 64,
PERSON_JSONB_SIZE_ESTIMATE_ENABLE: 0,
PERSON_PROPERTIES_UPDATE_ALL: false,
FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS: '*',
@@ -136,6 +144,7 @@ type AiOutputs =
| typeof INGESTION_WARNINGS_OUTPUT
| typeof PERSONS_OUTPUT
| typeof PERSON_DISTINCT_IDS_OUTPUT
+ | typeof PERSON_MERGE_EVENTS_OUTPUT
function getProduceCall(mockOutputs: jest.Mocked<IngestionOutputs<AiOutputs>>) {
expect(mockOutputs.produce).toHaveBeenCalledTimes(1)
diff --git a/nodejs/tests/worker/ingestion/person-state-batch.test.ts b/nodejs/tests/worker/ingestion/person-state-batch.test.ts
index d6601de8d8e8..08f5b08ce76f 100644
--- a/nodejs/tests/worker/ingestion/person-state-batch.test.ts
+++ b/nodejs/tests/worker/ingestion/person-state-batch.test.ts
@@ -3,14 +3,19 @@ import { KafkaProducerObserver } from '~/tests/helpers/mocks/producer.spy'
import { DateTime } from 'luxon'
import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
-import { ASYNC_OUTPUT, PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT } from '~/common/outputs'
+import { ASYNC_OUTPUT, PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
import { PersonMessage } from '~/common/persons/person-message'
import { fromInternalPerson } from '~/common/persons/person-update-batch'
import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'
import { fetchDistinctIdValues } from '~/common/persons/repositories/test-helpers'
-import { KAFKA_INGESTION_WARNINGS, KAFKA_PERSON, KAFKA_PERSON_DISTINCT_ID } from '~/config/kafka-topics'
+import {
+ KAFKA_INGESTION_WARNINGS,
+ KAFKA_PERSON,
+ KAFKA_PERSON_DISTINCT_ID,
+ KAFKA_PERSON_MERGE_EVENTS,
+} from '~/config/kafka-topics'
import { uuidFromDistinctId } from '~/ingestion/common/person-uuid'
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { PersonOutputs } from '~/ingestion/common/persons/person-context'
@@ -25,10 +30,12 @@ import {
import { PersonPropertyService } from '~/ingestion/common/persons/person-property-service'
import { BatchBoundPersonsStore, PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
import { PipelineResultType, isDlqResult, isOkResult, isRedirectResult } from '~/ingestion/framework/results'
+import { murmur2Partition } from '~/kafka/murmur2'
import { KafkaProducerWrapper } from '~/kafka/producer'
import { PluginEvent, Properties } from '~/plugin-scaffold'
import { Clickhouse } from '~/tests/helpers/clickhouse'
import { ensureKafkaTopics } from '~/tests/helpers/kafka'
+import { parseJSON } from '~/utils/json-parse'
import {
ClickHousePerson,
@@ -74,6 +81,12 @@ function createPersonOutputs(kafkaProducer: KafkaProducerWrapper): PersonOutputs
kafkaProducer,
'test'
),
+ [PERSON_MERGE_EVENTS_OUTPUT]: new SingleIngestionOutput(
+ PERSON_MERGE_EVENTS_OUTPUT,
+ KAFKA_PERSON_MERGE_EVENTS,
+ kafkaProducer,
+ 'test'
+ ),
})
}
@@ -282,6 +295,7 @@ describe('PersonState.processEvent()', () => {
timestampParam = timestamp,
team = mainTeam,
mergeMode = createDefaultSyncMergeMode(),
+ mergeEventsConfig?: { enabled: boolean; partitionCount: number },
customPersonsStore?: BatchWritingPersonsStore
) {
const fullEvent = {
@@ -309,7 +323,8 @@ describe('PersonState.processEvent()', () => {
0,
mergeMode,
false,
- false
+ false,
+ mergeEventsConfig ?? { enabled: false, partitionCount: 64 }
)
return new PersonMergeService(context)
}
@@ -2903,6 +2918,173 @@ describe('PersonState.processEvent()', () => {
expect(clickHouseDistinctIds).toEqual(expect.arrayContaining([firstUserDistinctId, secondUserDistinctId]))
})
+ const getMergeEventMessages = () =>
+ mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_PERSON_MERGE_EVENTS)
+
+ it(`does not emit a person_merge_events message when the gate is off (default)`, async () => {
+ mockProducerObserver.resetKafkaProducer()
+ const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {
+ distinctId: firstUserDistinctId,
+ })
+ const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {
+ distinctId: secondUserDistinctId,
+ })
+
+ // No mergeEventsConfig → gate defaults off.
+ const mergeService = personMergeService({}, hub, personRepository)
+ const result = await mergeService.mergePeople({
+ mergeInto: first,
+ mergeIntoDistinctId: firstUserDistinctId,
+ otherPerson: second,
+ otherPersonDistinctId: secondUserDistinctId,
+ })
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Merge should have succeeded')
+ }
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ expect(getMergeEventMessages()).toHaveLength(0)
+ })
+
+ it(`emits exactly one person_merge_events message with correct key, partition, and payload when the gate is on`, async () => {
+ const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {
+ distinctId: firstUserDistinctId,
+ })
+ const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {
+ distinctId: secondUserDistinctId,
+ })
+
+ // The local test broker has no 64-partition person_merge_events topic, so resolve that
+ // produce in-process while routing every other message to the real broker via the
+ // prototype method (the instance method would recurse through this spy). We inspect the
+ // spy's call args directly rather than the shared observer.
+ const realProduce = KafkaProducerWrapper.prototype.produce
+ const produceSpy = jest
+ .spyOn(kafkaProducer, 'produce')
+ .mockImplementation((message) =>
+ message.topic === KAFKA_PERSON_MERGE_EVENTS
+ ? Promise.resolve()
+ : realProduce.call(kafkaProducer, message)
+ )
+
+ const mergeService = personMergeService(
+ {},
+ hub,
+ personRepository,
+ true,
+ timestamp,
+ mainTeam,
+ createDefaultSyncMergeMode(),
+ { enabled: true, partitionCount: 64 }
+ )
+ const result = await mergeService.mergePeople({
+ mergeInto: first,
+ mergeIntoDistinctId: firstUserDistinctId,
+ otherPerson: second,
+ otherPersonDistinctId: secondUserDistinctId,
+ })
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Merge should have succeeded')
+ }
+ // kafkaAck wraps both the person messages and the merge event; it must resolve.
+ await flushPersonStoreToKafka(kafkaProducer, mergeService.getContext().personStore, result.kafkaAck)
+
+ const mergeProduceCalls = produceSpy.mock.calls.filter(
+ (call) => call[0].topic === KAFKA_PERSON_MERGE_EVENTS
+ )
+ expect(mergeProduceCalls).toHaveLength(1)
+
+ // second (P_old) is the deleted source; first (P_new) is the target.
+ const expectedKey = `${teamId}:${secondUserUuid}`
+ const mergeMessage = mergeProduceCalls[0][0]
+ expect(mergeMessage.key).toBe(expectedKey)
+ expect(mergeMessage.partition).toBe(murmur2Partition(expectedKey, 64))
+
+ const payload = parseJSON((mergeMessage.value as Buffer).toString())
+ expect(payload).toMatchObject({
+ team_id: teamId,
+ old_person_uuid: secondUserUuid,
+ new_person_uuid: firstUserUuid,
+ schema_version: 1,
+ })
+ expect(typeof payload.merged_at_ms).toBe('number')
+ })
+
+ it(`does not emit a person_merge_events message when the merge rolls back (moveDistinctIds throws)`, async () => {
+ mockProducerObserver.resetKafkaProducer()
+ const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {
+ distinctId: firstUserDistinctId,
+ })
+ const second = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, secondUserUuid, {
+ distinctId: secondUserDistinctId,
+ })
+
+ const mergeService = personMergeService(
+ {},
+ hub,
+ personRepository,
+ true,
+ timestamp,
+ mainTeam,
+ createDefaultSyncMergeMode(),
+ { enabled: true, partitionCount: 64 }
+ )
+ // Force the transaction to fail before the post-commit emission point.
+ jest.spyOn(BatchWritingPersonsStore.prototype, 'inTransaction').mockRejectedValueOnce(
+ new Error('moveDistinctIds blew up')
+ )
+
+ await expect(
+ mergeService.mergePeople({
+ mergeInto: first,
+ mergeIntoDistinctId: firstUserDistinctId,
+ otherPerson: second,
+ otherPersonDistinctId: secondUserDistinctId,
+ })
+ ).rejects.toThrow()
+
+ expect(getMergeEventMessages()).toHaveLength(0)
+ })
+
+ it(`does not emit a person_merge_events message when the merge is not allowed (already identified)`, async () => {
+ mockProducerObserver.resetKafkaProducer()
+ // Both persons already identified → $identify refuses the merge (isMergeAllowed=false).
+ await createPerson(hub, timestamp, {}, {}, {}, teamId, null, true, oldUserUuid, {
+ distinctId: oldUserDistinctId,
+ })
+ await createPerson(hub, timestamp2, {}, {}, {}, teamId, null, true, newUserUuid, {
+ distinctId: newUserDistinctId,
+ })
+
+ const result = await personMergeService(
+ {
+ event: '$identify',
+ distinct_id: newUserDistinctId,
+ properties: { $anon_distinct_id: oldUserDistinctId },
+ },
+ hub,
+ personRepository,
+ true,
+ timestamp,
+ mainTeam,
+ createDefaultSyncMergeMode(),
+ { enabled: true, partitionCount: 64 }
+ ).handleIdentifyOrAlias()
+ expect(result.success).toBe(true)
+ if (!result.success) {
+ throw new Error('Refused merges still return a success result')
+ }
+ await kafkaProducer.flush()
+ await result.kafkaAck
+
+ // Both persons survive; no merge happened, so no merge event.
+ const persons = sortPersons(await fetchPostgresPersonsH())
+ expect(persons.length).toEqual(2)
+ expect(getMergeEventMessages()).toHaveLength(0)
+ })
+
it(`hitting the move limit drops the event: no merge, no IDs moved, goes to DLQ`, async () => {
const first = await createPerson(hub, timestamp, {}, {}, {}, teamId, null, false, firstUserUuid, {
distinctId: firstUserDistinctId,
@@ -3426,6 +3608,7 @@ describe('PersonState.processEvent()', () => {
undefined,
undefined,
undefined,
+ undefined,
batchStore
)
diff --git a/posthog/management/commands/survey_cohort_bytecode_stl.py b/posthog/management/commands/survey_cohort_bytecode_stl.py
new file mode 100644
index 000000000000..c4c64af743a0
--- /dev/null
+++ b/posthog/management/commands/survey_cohort_bytecode_stl.py
@@ -0,0 +1,372 @@
+"""Survey HogVM bytecode (STL functions + opcodes) across realtime cohorts, flagging Rust HogVM gaps."""
+
+import json
+from collections import Counter, defaultdict
+from collections.abc import Iterable, Iterator
+from datetime import UTC, datetime
+from typing import Any
+
+from django.core.management.base import BaseCommand
+
+import structlog
+
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+
+from common.hogvm.python.operation import HOGQL_BYTECODE_IDENTIFIER, HOGQL_BYTECODE_IDENTIFIER_V0, Operation
+
+logger = structlog.get_logger(__name__)
+
+# Inline operands following each opcode in the flat bytecode list (CLOSURE is variable-length, handled separately).
+FIXED_OPERAND_COUNTS: dict[Operation, int] = {
+ Operation.GET_GLOBAL: 1,
+ Operation.CALL_GLOBAL: 2,
+ Operation.AND: 1,
+ Operation.OR: 1,
+ Operation.NOT: 0,
+ Operation.PLUS: 0,
+ Operation.MINUS: 0,
+ Operation.MULTIPLY: 0,
+ Operation.DIVIDE: 0,
+ Operation.MOD: 0,
+ Operation.EQ: 0,
+ Operation.NOT_EQ: 0,
+ Operation.GT: 0,
+ Operation.GT_EQ: 0,
+ Operation.LT: 0,
+ Operation.LT_EQ: 0,
+ Operation.LIKE: 0,
+ Operation.ILIKE: 0,
+ Operation.NOT_LIKE: 0,
+ Operation.NOT_ILIKE: 0,
+ Operation.IN: 0,
+ Operation.NOT_IN: 0,
+ Operation.REGEX: 0,
+ Operation.NOT_REGEX: 0,
+ Operation.IREGEX: 0,
+ Operation.NOT_IREGEX: 0,
+ Operation.IN_COHORT: 0,
+ Operation.NOT_IN_COHORT: 0,
+ Operation.TRUE: 0,
+ Operation.FALSE: 0,
+ Operation.NULL: 0,
+ Operation.STRING: 1,
+ Operation.INTEGER: 1,
+ Operation.FLOAT: 1,
+ Operation.POP: 0,
+ Operation.GET_LOCAL: 1,
+ Operation.SET_LOCAL: 1,
+ Operation.RETURN: 0,
+ Operation.JUMP: 1,
+ Operation.JUMP_IF_FALSE: 1,
+ Operation.DECLARE_FN: 3,
+ Operation.DICT: 1,
+ Operation.ARRAY: 1,
+ Operation.TUPLE: 1,
+ Operation.GET_PROPERTY: 0,
+ Operation.SET_PROPERTY: 0,
+ Operation.JUMP_IF_STACK_NOT_NULL: 1,
+ Operation.GET_PROPERTY_NULLISH: 0,
+ Operation.THROW: 0,
+ Operation.TRY: 1,
+ Operation.POP_TRY: 0,
+ Operation.CALLABLE: 4,
+ Operation.CALL_LOCAL: 1,
+ Operation.GET_UPVALUE: 1,
+ Operation.SET_UPVALUE: 1,
+ Operation.CLOSE_UPVALUE: 0,
+}
+
+# Snapshot of rust/common/hogvm/src/stl.rs (regenerate via `bin/dump_hogvmrs_stl`); a snapshot avoids a cross-product import.
+RUST_NATIVE_STL: frozenset[str] = frozenset(
+ {
+ "toString",
+ "typeof",
+ "isNull",
+ "values",
+ "length",
+ "arrayPushBack",
+ "arrayPushFront",
+ "arrayPopBack",
+ "arrayPopFront",
+ "arraySort",
+ "arrayReverse",
+ "arrayReverseSort",
+ "arrayStringConcat",
+ "has",
+ "indexOf",
+ "notEmpty",
+ "match",
+ "extractRegex",
+ "JSONExtract",
+ "toDateTime",
+ "toDate",
+ "multiSearchAnyCaseInsensitive",
+ "randomFloat",
+ }
+)
+RUST_HOG_STL: frozenset[str] = frozenset(
+ {"arrayCount", "arrayExists", "arrayFilter", "arrayMap", "arrayReduce", "sortableSemver"}
+)
+RUST_SUPPORTED_STL: frozenset[str] = RUST_NATIVE_STL | RUST_HOG_STL
+
+# `sortableSemver`'s hog body calls these unregistered natives, transitively blocking any SEMVER_* cohort.
+SORTABLE_SEMVER_TRANSITIVE_DEPS: frozenset[str] = frozenset({"empty", "splitByString", "toInt"})
+
+RUST_NOT_IMPLEMENTED_OPCODES: frozenset[Operation] = frozenset(
+ {Operation.DECLARE_FN, Operation.IN_COHORT, Operation.NOT_IN_COHORT}
+)
+
+
+def iter_instructions(bytecode: list[Any]) -> Iterator[tuple[Operation, list[Any]]]:
+ """Disassemble a HogVM bytecode program, yielding (opcode, operands) per instruction.
+
+ Raises ValueError on an unknown opcode or truncated instruction so a malformed program is
+ recorded as a walk failure rather than silently miscounted.
+ """
+ n = len(bytecode)
+ ip = 0
+ # "_H" carries a trailing version int; "_h" (v0) does not.
+ if n > 0 and bytecode[0] == HOGQL_BYTECODE_IDENTIFIER:
+ ip = 2
+ elif n > 0 and bytecode[0] == HOGQL_BYTECODE_IDENTIFIER_V0:
+ ip = 1
+
+ while ip < n:
+ raw = bytecode[ip]
+ try:
+ op = Operation(raw)
+ except ValueError as e:
+ raise ValueError(f"unknown opcode {raw!r} at index {ip}") from e
+
+ if op == Operation.CLOSURE:
+ if ip + 1 >= n:
+ raise ValueError(f"truncated CLOSURE at index {ip}")
+ upvalue_count = bytecode[ip + 1]
+ if not isinstance(upvalue_count, int):
+ raise ValueError(f"CLOSURE upvalue count is not an int at index {ip + 1}")
+ consumed = 1 + 2 * upvalue_count
+ elif op == Operation.CALLABLE:
+ # 4 fixed operands; operand[3] (bytecode[ip+4]) is the inline body length the VM skips.
+ if ip + 4 >= n:
+ raise ValueError(f"truncated CALLABLE at index {ip}")
+ body_length = bytecode[ip + 4]
+ if not isinstance(body_length, int):
+ raise ValueError(f"CALLABLE body length is not an int at index {ip + 4}")
+ consumed = 4 + body_length
+ elif op == Operation.DECLARE_FN:
+ # 3 fixed operands; operand[2] (bytecode[ip+3]) is the inline body length the VM skips.
+ if ip + 3 >= n:
+ raise ValueError(f"truncated DECLARE_FN at index {ip}")
+ body_len = bytecode[ip + 3]
+ if not isinstance(body_len, int):
+ raise ValueError(f"DECLARE_FN body length is not an int at index {ip + 3}")
+ consumed = 3 + body_len
+ else:
+ consumed = FIXED_OPERAND_COUNTS[op]
+
+ if ip + 1 + consumed > n:
+ raise ValueError(f"truncated operands for {op.name} at index {ip}")
+
+ operands = bytecode[ip + 1 : ip + 1 + consumed]
+ yield op, operands
+ ip += 1 + consumed
+
+
+def iter_bytecode_leaves(properties: Any) -> Iterator[dict[str, Any]]:
+ """Walk a cohort's `filters.properties` AND/OR tree, yielding leaves with populated bytecode."""
+ if not isinstance(properties, dict):
+ return
+ if properties.get("type") in ("AND", "OR") and isinstance(properties.get("values"), list):
+ for child in properties["values"]:
+ yield from iter_bytecode_leaves(child)
+ return
+ if properties.get("bytecode"):
+ yield properties
+
+
+def _normalize_bytecode(raw: Any) -> list[Any] | None:
+ """Coerce an inline `bytecode` value to a list; cohorts store a list, but tolerate a JSON string."""
+ if isinstance(raw, list):
+ return raw
+ if isinstance(raw, str):
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError:
+ return None
+ return parsed if isinstance(parsed, list) else None
+ return None
+
+
+def aggregate_survey(cohort_rows: Iterable[tuple[int, int, dict[str, Any] | None]]) -> dict[str, Any]:
+ """Aggregate opcode + STL-function histograms across cohort bytecode. Pure (no DB / I/O)."""
+ opcode_counts: Counter[str] = Counter()
+ opcode_cohorts: dict[str, set[int]] = defaultdict(set)
+ stl_counts: Counter[str] = Counter()
+ stl_cohorts: dict[str, set[int]] = defaultdict(set)
+
+ teams_scanned: set[int] = set()
+ cohorts_scanned = 0
+ cohorts_with_bytecode: set[int] = set()
+ leaves_with_bytecode = 0
+ leaves_walked_ok = 0
+ leaves_walk_failed = 0
+ unique_condition_hashes: set[str] = set()
+ leaf_type_counts: Counter[str] = Counter()
+ walk_failures: list[dict[str, Any]] = []
+
+ for cohort_id, team_id, filters in cohort_rows:
+ cohorts_scanned += 1
+ teams_scanned.add(team_id)
+ properties = (filters or {}).get("properties") if isinstance(filters, dict) else None
+
+ for leaf in iter_bytecode_leaves(properties):
+ leaves_with_bytecode += 1
+ cohorts_with_bytecode.add(cohort_id)
+ leaf_type_counts[str(leaf.get("type", "unknown"))] += 1
+ condition_hash = leaf.get("conditionHash")
+ if isinstance(condition_hash, str):
+ unique_condition_hashes.add(condition_hash)
+
+ bytecode = _normalize_bytecode(leaf.get("bytecode"))
+ if bytecode is None:
+ leaves_walk_failed += 1
+ walk_failures.append(
+ {"cohort_id": cohort_id, "team_id": team_id, "error": "bytecode is not a list/JSON-array"}
+ )
+ continue
+
+ try:
+ # Materialize first so a mid-walk failure doesn't half-count this leaf.
+ instructions = list(iter_instructions(bytecode))
+ except ValueError as e:
+ leaves_walk_failed += 1
+ walk_failures.append({"cohort_id": cohort_id, "team_id": team_id, "error": str(e)})
+ continue
+
+ leaves_walked_ok += 1
+ for op, operands in instructions:
+ opcode_counts[op.name] += 1
+ opcode_cohorts[op.name].add(cohort_id)
+ if op == Operation.CALL_GLOBAL and operands and isinstance(operands[0], str):
+ name = operands[0]
+ stl_counts[name] += 1
+ stl_cohorts[name].add(cohort_id)
+
+ stl_functions = [
+ {
+ "name": name,
+ "call_count": count,
+ "distinct_cohorts": len(stl_cohorts[name]),
+ "in_rust_stl": name in RUST_SUPPORTED_STL,
+ }
+ for name, count in stl_counts.most_common()
+ ]
+ opcodes = [
+ {
+ "opcode": name,
+ "id": int(Operation[name].value),
+ "count": count,
+ "distinct_cohorts": len(opcode_cohorts[name]),
+ "rust_not_implemented": Operation[name] in RUST_NOT_IMPLEMENTED_OPCODES,
+ }
+ for name, count in opcode_counts.most_common()
+ ]
+
+ missing_natives = sorted({name for name in stl_counts if name not in RUST_SUPPORTED_STL})
+ transitive_semver = sorted(SORTABLE_SEMVER_TRANSITIVE_DEPS) if "sortableSemver" in stl_counts else []
+ not_implemented_used = sorted({name for name in opcode_counts if Operation[name] in RUST_NOT_IMPLEMENTED_OPCODES})
+
+ return {
+ "totals": {
+ "cohorts_scanned": cohorts_scanned,
+ "teams_scanned": len(teams_scanned),
+ "cohorts_with_bytecode_leaves": len(cohorts_with_bytecode),
+ "leaves_with_bytecode": leaves_with_bytecode,
+ "leaves_walked_ok": leaves_walked_ok,
+ "leaves_walk_failed": leaves_walk_failed,
+ "unique_condition_hashes": len(unique_condition_hashes),
+ },
+ "leaf_types": dict(leaf_type_counts.most_common()),
+ "stl_functions": stl_functions,
+ "opcodes": opcodes,
+ "rust_gaps": {
+ "missing_stl_natives": missing_natives,
+ "sortable_semver_transitive_deps": transitive_semver,
+ "not_implemented_opcodes_used": not_implemented_used,
+ },
+ "walk_failures": walk_failures,
+ }
+
+
+class Command(BaseCommand):
+ help = "Survey HogVM bytecode (STL functions + opcodes) across production realtime cohorts (M0)"
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument(
+ "--output",
+ type=str,
+ default="cohort_bytecode_survey.json",
+ help="Path to write the survey JSON (default: cohort_bytecode_survey.json)",
+ )
+ parser.add_argument(
+ "--team-id",
+ type=int,
+ default=None,
+ help="Restrict the survey to a single team_id (optional)",
+ )
+ parser.add_argument(
+ "--include-deleted",
+ action="store_true",
+ help="Include soft-deleted cohorts (default: only deleted=false)",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ output_path: str = options["output"]
+ team_id: int | None = options.get("team_id")
+ include_deleted: bool = options.get("include_deleted", False)
+
+ queryset = Cohort.objects.filter(cohort_type=CohortType.REALTIME)
+ if not include_deleted:
+ queryset = queryset.filter(deleted=False)
+ if team_id is not None:
+ queryset = queryset.filter(team_id=team_id)
+
+ rows = queryset.values_list("id", "team_id", "filters").iterator(chunk_size=500)
+ result = aggregate_survey((cohort_id, tid, filters) for cohort_id, tid, filters in rows)
+
+ result["generated_at"] = datetime.now(UTC).isoformat()
+ result["scope"] = {
+ "cohort_type": str(CohortType.REALTIME),
+ "deleted": None if include_deleted else False,
+ "team_id": team_id,
+ }
+
+ with open(output_path, "w") as f:
+ json.dump(result, f, indent=2, sort_keys=False)
+
+ totals = result["totals"]
+ logger.info(
+ "cohort_bytecode_survey_complete",
+ output=output_path,
+ cohorts_scanned=totals["cohorts_scanned"],
+ leaves_walked_ok=totals["leaves_walked_ok"],
+ leaves_walk_failed=totals["leaves_walk_failed"],
+ missing_stl_natives=result["rust_gaps"]["missing_stl_natives"],
+ not_implemented_opcodes_used=result["rust_gaps"]["not_implemented_opcodes_used"],
+ )
+
+ self.stdout.write(self.style.SUCCESS(f"Wrote survey to {output_path}"))
+ self.stdout.write(
+ f" cohorts scanned: {totals['cohorts_scanned']} "
+ f"({totals['cohorts_with_bytecode_leaves']} with bytecode leaves)"
+ )
+ self.stdout.write(
+ f" bytecode leaves: {totals['leaves_with_bytecode']} "
+ f"(walked ok: {totals['leaves_walked_ok']}, failed: {totals['leaves_walk_failed']})"
+ )
+ self.stdout.write(f" unique conditionHashes: {totals['unique_condition_hashes']}")
+ gaps = result["rust_gaps"]
+ self.stdout.write(f" rust missing STL natives: {gaps['missing_stl_natives'] or 'none'}")
+ if gaps["sortable_semver_transitive_deps"]:
+ self.stdout.write(f" sortableSemver transitive deps needed: {gaps['sortable_semver_transitive_deps']}")
+ self.stdout.write(f" rust NotImplemented opcodes used: {gaps['not_implemented_opcodes_used'] or 'none'}")
diff --git a/posthog/management/commands/test/test_survey_cohort_bytecode_stl.py b/posthog/management/commands/test/test_survey_cohort_bytecode_stl.py
new file mode 100644
index 000000000000..858d131426de
--- /dev/null
+++ b/posthog/management/commands/test/test_survey_cohort_bytecode_stl.py
@@ -0,0 +1,351 @@
+import os
+import json
+import tempfile
+
+from posthog.test.base import BaseTest
+
+from django.core.management import call_command
+
+from parameterized import parameterized
+
+from posthog.management.commands.survey_cohort_bytecode_stl import (
+ aggregate_survey,
+ iter_bytecode_leaves,
+ iter_instructions,
+)
+
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+
+from common.hogvm.python.operation import Operation
+
+# Opcode values mirror common/hogvm/python/operation.py.
+GET_GLOBAL, CALL_GLOBAL, AND, PLUS = 1, 2, 3, 6
+GT, IN_COHORT = 13, 27
+TRUE, NULL, STRING, INTEGER, RETURN = 29, 31, 32, 33, 38
+DECLARE_FN, CALLABLE = 41, 52
+
+
+class TestBytecodeWalker(BaseTest):
+ @parameterized.expand(
+ [
+ (
+ "string_then_return",
+ ["_H", 1, STRING, "hello", RETURN],
+ [(Operation.STRING, ["hello"]), (Operation.RETURN, [])],
+ ),
+ (
+ "integer_plus",
+ ["_H", 1, INTEGER, 2, INTEGER, 1, PLUS, RETURN],
+ [
+ (Operation.INTEGER, [2]),
+ (Operation.INTEGER, [1]),
+ (Operation.PLUS, []),
+ (Operation.RETURN, []),
+ ],
+ ),
+ (
+ "call_global_is_null",
+ ["_H", 1, NULL, CALL_GLOBAL, "isNull", 1, RETURN],
+ [
+ (Operation.NULL, []),
+ (Operation.CALL_GLOBAL, ["isNull", 1]),
+ (Operation.RETURN, []),
+ ],
+ ),
+ (
+ "get_global_chain",
+ ["_H", 1, STRING, "x", GET_GLOBAL, 1, RETURN],
+ [
+ (Operation.STRING, ["x"]),
+ (Operation.GET_GLOBAL, [1]),
+ (Operation.RETURN, []),
+ ],
+ ),
+ (
+ "and_with_count_operand",
+ ["_H", 1, TRUE, TRUE, AND, 2, RETURN],
+ [
+ (Operation.TRUE, []),
+ (Operation.TRUE, []),
+ (Operation.AND, [2]),
+ (Operation.RETURN, []),
+ ],
+ ),
+ (
+ "v0_header_single_slot_skip",
+ ["_h", TRUE, RETURN],
+ [(Operation.TRUE, []), (Operation.RETURN, [])],
+ ),
+ (
+ "callable_body_skipped_and_next_opcode_reached",
+ ["_H", 1, CALLABLE, "fn", 0, 0, 2, TRUE, RETURN, STRING, "after"],
+ [
+ (Operation.CALLABLE, ["fn", 0, 0, 2, TRUE, RETURN]),
+ (Operation.STRING, ["after"]),
+ ],
+ ),
+ (
+ "declare_fn_body_skipped_and_next_opcode_reached",
+ ["_H", 1, DECLARE_FN, "fn", 0, 2, TRUE, RETURN, STRING, "after"],
+ [
+ (Operation.DECLARE_FN, ["fn", 0, 2, TRUE, RETURN]),
+ (Operation.STRING, ["after"]),
+ ],
+ ),
+ ]
+ )
+ def test_iter_instructions_disassembles(self, _name, bytecode, expected):
+ self.assertEqual(list(iter_instructions(bytecode)), expected)
+
+ @parameterized.expand(
+ [
+ ("truncated_operand", ["_H", 1, STRING], "truncated operands for STRING"),
+ ("unknown_opcode", ["_H", 1, 9999], "unknown opcode 9999"),
+ (
+ "declare_fn_non_int_body_length",
+ ["_H", 1, DECLARE_FN, "fn", 0, "notanint"],
+ "DECLARE_FN body length is not an int",
+ ),
+ (
+ "callable_non_int_body_length",
+ ["_H", 1, CALLABLE, "fn", 0, 0, "notanint"],
+ "CALLABLE body length is not an int",
+ ),
+ ]
+ )
+ def test_iter_instructions_raises_on_malformed(self, _name, bytecode, expected_msg):
+ with self.assertRaises(ValueError) as ctx:
+ list(iter_instructions(bytecode))
+ self.assertIn(expected_msg, str(ctx.exception))
+
+ def test_iter_bytecode_leaves_walks_and_or_tree(self):
+ properties = {
+ "type": "AND",
+ "values": [
+ {"type": "person", "conditionHash": "h1", "bytecode": ["_H", 1, TRUE, RETURN]},
+ {
+ "type": "OR",
+ "values": [
+ {"type": "behavioral", "conditionHash": "h2", "bytecode": ["_H", 1, TRUE, RETURN]},
+ {"type": "person", "conditionHash": "h3"},
+ ],
+ },
+ ],
+ }
+ leaves = list(iter_bytecode_leaves(properties))
+ self.assertEqual([leaf["conditionHash"] for leaf in leaves], ["h1", "h2"])
+
+
+class TestAggregateSurvey(BaseTest):
+ def test_aggregates_histograms_and_rust_gaps(self):
+ rows = [
+ (
+ 1,
+ 2,
+ {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "person",
+ "conditionHash": "h1",
+ "bytecode": ["_H", 1, NULL, CALL_GLOBAL, "isNull", 1, RETURN],
+ },
+ ],
+ }
+ },
+ ),
+ (
+ 2,
+ 2,
+ {
+ "properties": {
+ "type": "OR",
+ "values": [
+ {
+ "type": "cohort",
+ "conditionHash": "h2",
+ "bytecode": ["_H", 1, STRING, "x", CALL_GLOBAL, "inCohort", 1, RETURN],
+ },
+ ],
+ }
+ },
+ ),
+ (
+ 3,
+ 7,
+ {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "cohort",
+ "conditionHash": "h3",
+ "bytecode": ["_H", 1, INTEGER, 5, IN_COHORT, RETURN],
+ },
+ ],
+ }
+ },
+ ),
+ (
+ 4,
+ 7,
+ {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "person",
+ "conditionHash": "h4",
+ "bytecode": ["_H", 1, STRING, "1.2.3", CALL_GLOBAL, "sortableSemver", 1, RETURN],
+ },
+ ],
+ }
+ },
+ ),
+ (
+ 5,
+ 7,
+ {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {"type": "person", "conditionHash": "h5", "bytecode": ["_H", 1, STRING]},
+ ],
+ }
+ },
+ ),
+ ]
+
+ result = aggregate_survey(rows)
+
+ totals = result["totals"]
+ self.assertEqual(totals["cohorts_scanned"], 5)
+ self.assertEqual(totals["teams_scanned"], 2)
+ self.assertEqual(totals["leaves_with_bytecode"], 5)
+ self.assertEqual(totals["leaves_walked_ok"], 4)
+ self.assertEqual(totals["leaves_walk_failed"], 1)
+ self.assertEqual(totals["unique_condition_hashes"], 5)
+
+ stl_by_name = {entry["name"]: entry for entry in result["stl_functions"]}
+ self.assertTrue(stl_by_name["isNull"]["in_rust_stl"])
+ self.assertFalse(stl_by_name["inCohort"]["in_rust_stl"])
+ self.assertTrue(stl_by_name["sortableSemver"]["in_rust_stl"])
+ self.assertEqual(stl_by_name["isNull"]["distinct_cohorts"], 1)
+
+ gaps = result["rust_gaps"]
+ self.assertEqual(gaps["missing_stl_natives"], ["inCohort"])
+ self.assertEqual(gaps["sortable_semver_transitive_deps"], ["empty", "splitByString", "toInt"])
+ self.assertEqual(gaps["not_implemented_opcodes_used"], ["IN_COHORT"])
+
+ self.assertEqual(len(result["walk_failures"]), 1)
+ self.assertEqual(result["walk_failures"][0]["cohort_id"], 5)
+
+ def test_declare_fn_body_is_walked_ok_and_flagged_as_not_implemented(self):
+ # A leaf with an inline DECLARE_FN body must walk OK (body skipped, not mis-walked) so the
+ # survey counts the DECLARE_FN opcode in not_implemented_opcodes_used instead of recording
+ # the whole leaf as a walk failure.
+ rows = [
+ (
+ 1,
+ 2,
+ {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "person",
+ "conditionHash": "h1",
+ "bytecode": ["_H", 1, DECLARE_FN, "fn", 0, 2, TRUE, RETURN, TRUE, RETURN],
+ },
+ ],
+ }
+ },
+ ),
+ ]
+
+ result = aggregate_survey(rows)
+
+ self.assertEqual(result["totals"]["leaves_walked_ok"], 1)
+ self.assertEqual(result["totals"]["leaves_walk_failed"], 0)
+ self.assertEqual(result["walk_failures"], [])
+
+ opcode_names = {entry["opcode"] for entry in result["opcodes"]}
+ self.assertIn("DECLARE_FN", opcode_names)
+ self.assertIn("DECLARE_FN", result["rust_gaps"]["not_implemented_opcodes_used"])
+
+ def test_real_compiler_bytecode_is_walked_and_isnull_is_supported(self):
+ from posthog.api.cohort import generate_cohort_filter_bytecode
+
+ bytecode, error, condition_hash = generate_cohort_filter_bytecode(
+ {"key": "age", "type": "person", "value": 13, "operator": "gt"}, self.team
+ )
+ self.assertIsNone(error)
+ assert bytecode is not None
+
+ row = (
+ 101,
+ self.team.id,
+ {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {"type": "person", "conditionHash": condition_hash, "bytecode": bytecode},
+ ],
+ }
+ },
+ )
+ result = aggregate_survey([row])
+
+ self.assertEqual(result["totals"]["leaves_walked_ok"], 1)
+ self.assertEqual(result["totals"]["leaves_walk_failed"], 0)
+
+ stl_names = {entry["name"] for entry in result["stl_functions"]}
+ self.assertIn("isNull", stl_names)
+ opcode_names = {entry["opcode"] for entry in result["opcodes"]}
+ self.assertIn("GT", opcode_names)
+
+ self.assertEqual(result["rust_gaps"]["missing_stl_natives"], [])
+ self.assertEqual(result["rust_gaps"]["not_implemented_opcodes_used"], [])
+
+
+class TestSurveyCommand(BaseTest):
+ def test_command_writes_survey_json_for_realtime_cohorts(self):
+ from posthog.api.cohort import generate_cohort_filter_bytecode
+
+ bytecode, _error, condition_hash = generate_cohort_filter_bytecode(
+ {"key": "age", "type": "person", "value": 13, "operator": "gt"}, self.team
+ )
+ Cohort.objects.create(
+ team=self.team,
+ name="survey-test-realtime",
+ cohort_type=CohortType.REALTIME,
+ deleted=False,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "person",
+ "key": "age",
+ "value": 13,
+ "operator": "gt",
+ "conditionHash": condition_hash,
+ "bytecode": bytecode,
+ },
+ ],
+ }
+ },
+ )
+
+ output_path = os.path.join(tempfile.mkdtemp(), "survey.json")
+ call_command("survey_cohort_bytecode_stl", "--team-id", str(self.team.id), "--output", output_path)
+
+ with open(output_path) as f:
+ result = json.load(f)
+
+ self.assertEqual(result["totals"]["cohorts_scanned"], 1)
+ self.assertEqual(result["totals"]["leaves_walked_ok"], 1)
+ self.assertIn("isNull", {entry["name"] for entry in result["stl_functions"]})
+ self.assertEqual(result["rust_gaps"]["missing_stl_natives"], [])
+ self.assertEqual(result["scope"]["team_id"], self.team.id)
diff --git a/products/error_tracking/backend/hogvm_stl.py b/products/error_tracking/backend/hogvm_stl.py
index 88593ebd2563..0b009481aa32 100644
--- a/products/error_tracking/backend/hogvm_stl.py
+++ b/products/error_tracking/backend/hogvm_stl.py
@@ -1,6 +1,7 @@
RUST_HOGVM_STL = [
"toString",
"typeof",
+ "isNull",
"values",
"length",
"arrayPushBack",
@@ -17,6 +18,8 @@ RUST_HOGVM_STL = [
"match",
"extractRegex",
"JSONExtract",
+ "toDateTime",
+ "toDate",
"multiSearchAnyCaseInsensitive",
"randomFloat",
"arrayCount",
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index cd632b5f7bdf..565791be0629 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2127,6 +2127,73 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7ee2cfacbd29706479902b06d75ad8f1362900836aa32799eabc7e004bfd854"
+[[package]]
+name = "cohort-event-shuffler"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "arc-swap",
+ "axum 0.7.9",
+ "common-alloc",
+ "common-database",
+ "common-kafka",
+ "common-liveness",
+ "common-types",
+ "envconfig",
+ "lifecycle",
+ "metrics",
+ "metrics-exporter-prometheus",
+ "rand 0.8.5",
+ "rdkafka",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "tokio",
+ "tracing",
+ "tracing-subscriber",
+ "uuid",
+]
+
+[[package]]
+name = "cohort-stream-processor"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "arc-swap",
+ "async-trait",
+ "axum 0.7.9",
+ "chrono",
+ "chrono-tz",
+ "common-alloc",
+ "common-database",
+ "common-kafka",
+ "common-liveness",
+ "common-types",
+ "dashmap 6.1.0",
+ "envconfig",
+ "futures",
+ "hogvm",
+ "lifecycle",
+ "metrics",
+ "metrics-exporter-prometheus",
+ "object_store",
+ "petgraph 0.8.3",
+ "rand 0.8.5",
+ "rdkafka",
+ "rocksdb",
+ "serde",
+ "serde_json",
+ "sha2",
+ "sqlx",
+ "tempfile",
+ "thiserror 2.0.18",
+ "tokio",
+ "tokio-util",
+ "tracing",
+ "tracing-subscriber",
+ "uuid",
+]
+
[[package]]
name = "colorchoice"
version = "1.0.4"
@@ -4391,6 +4458,8 @@ dependencies = [
name = "hogvm"
version = "0.1.0"
dependencies = [
+ "chrono",
+ "chrono-tz",
"rand 0.8.5",
"regex",
"serde",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 0c660c12aa2e..3fcefff7c3be 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -6,6 +6,8 @@ members = [
"batch-import-worker",
"capture",
"capture-logs",
+ "cohort-event-shuffler",
+ "cohort-stream-processor",
"common/alloc",
"common/assignment-coordination",
"common/k8s-awareness",
diff --git a/rust/affected-services/tests/integration.rs b/rust/affected-services/tests/integration.rs
index a35f9d4384e0..da9e6de3605a 100644
--- a/rust/affected-services/tests/integration.rs
+++ b/rust/affected-services/tests/integration.rs
@@ -105,8 +105,17 @@ fn multi_file_is_union() {
#[test]
fn every_deployable_binary_has_an_image_entry() {
- let non_deployable: HashSet<&str> =
- ["affected-services", "debug_rule", "stl_dump", "hermes"].into();
+ let non_deployable: HashSet<&str> = [
+ "affected-services",
+ "debug_rule",
+ "stl_dump",
+ "run", // hogvm dev/diff CLI, not a service
+ "hermes",
+ // Not yet in .github/rust-images.yml — no production Depot/chart image build.
+ "cohort-event-shuffler",
+ "cohort-stream-processor",
+ ]
+ .into();
let (graph, images) = load_test_fixtures();
let bin_to_crate = build_binary_to_crate_map(&graph);
diff --git a/rust/cohort-event-shuffler/Cargo.toml b/rust/cohort-event-shuffler/Cargo.toml
new file mode 100644
index 000000000000..651060d744e7
--- /dev/null
+++ b/rust/cohort-event-shuffler/Cargo.toml
@@ -0,0 +1,30 @@
+[package]
+name = "cohort-event-shuffler"
+version = "0.1.0"
+edition = "2021"
+
+[lints]
+workspace = true
+
+[dependencies]
+anyhow = { workspace = true }
+arc-swap = { workspace = true }
+axum = { workspace = true }
+common-alloc = { path = "../common/alloc" }
+common-database = { path = "../common/database" }
+common-kafka = { path = "../common/kafka" }
+common-liveness = { path = "../common/liveness" }
+common-types = { path = "../common/types" }
+envconfig = { workspace = true }
+lifecycle = { path = "../common/lifecycle" }
+metrics = { workspace = true }
+metrics-exporter-prometheus = { workspace = true }
+rand = { workspace = true }
+rdkafka = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true }
+tokio = { workspace = true }
+tracing = { workspace = true }
+tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
+uuid = { workspace = true }
diff --git a/rust/cohort-event-shuffler/src/config.rs b/rust/cohort-event-shuffler/src/config.rs
new file mode 100644
index 000000000000..63e0ceae12e9
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/config.rs
@@ -0,0 +1,225 @@
+//! Service configuration, loaded from environment variables via `envconfig`.
+
+use std::time::Duration;
+
+use common_database::PoolConfig;
+use common_kafka::config::{ConsumerConfig, KafkaConfig};
+use common_types::cohort::TeamAllowlist;
+use envconfig::Envconfig;
+
+const POOL_NAME: &str = "posthog_cohort";
+
+#[derive(Envconfig, Clone, Debug)]
+pub struct Config {
+ #[envconfig(default = "0.0.0.0")]
+ pub bind_host: String,
+
+ #[envconfig(default = "3322")]
+ pub bind_port: u16,
+
+ #[envconfig(default = "true")]
+ pub export_prometheus: bool,
+
+ #[envconfig(default = "localhost:9092")]
+ pub kafka_hosts: String,
+
+ #[envconfig(default = "false")]
+ pub kafka_tls: bool,
+
+ #[envconfig(default = "")]
+ pub kafka_client_rack: String,
+
+ #[envconfig(default = "")]
+ pub kafka_client_id: String,
+
+ #[envconfig(default = "clickhouse_events_json")]
+ pub input_topic: String,
+
+ #[envconfig(default = "cohort-event-shuffler")]
+ pub kafka_consumer_group: String,
+
+ /// Start at the tail: historical population is the seed topic's job, not a days-long replay.
+ #[envconfig(default = "latest")]
+ pub kafka_consumer_offset_reset: String,
+
+ #[envconfig(default = "cohort_stream_events")]
+ pub output_topic: String,
+
+ /// Must be `murmur2_random` to co-partition `(team_id, person_id)` identically to the
+ /// Node-produced `person_merge_events`; other values silently break cross-runtime affinity.
+ #[envconfig(default = "murmur2_random")]
+ pub kafka_producer_partitioner: String,
+
+ #[envconfig(default = "none")]
+ pub kafka_compression_codec: String,
+
+ #[envconfig(default = "postgres://posthog:posthog@localhost:5432/posthog")]
+ pub database_url: String,
+
+ #[envconfig(default = "1")]
+ pub min_pg_connections: u32,
+
+ #[envconfig(default = "5")]
+ pub max_pg_connections: u32,
+
+ #[envconfig(default = "10")]
+ pub pg_acquire_timeout_secs: u64,
+
+ /// `0` → database default.
+ #[envconfig(default = "5000")]
+ pub pg_statement_timeout_ms: u64,
+
+ #[envconfig(default = "300")]
+ pub team_index_refresh_secs: u64,
+
+ #[envconfig(default = "60")]
+ pub team_index_refresh_jitter_secs: u64,
+
+ /// Teams whose events are forwarded into the shadow pipeline. Defaults to team 2 (the parity
+ /// baseline's gate); set `all` to disable the gate. See [`TeamAllowlist`].
+ #[envconfig(from = "REALTIME_COHORT_TEAM_ALLOWLIST", default = "2")]
+ pub team_allowlist: TeamAllowlist,
+
+ #[envconfig(default = "1000")]
+ pub recv_batch_size: usize,
+
+ #[envconfig(default = "500")]
+ pub recv_batch_timeout_ms: u64,
+}
+
+impl Config {
+ pub fn bind_address(&self) -> String {
+ format!("{}:{}", self.bind_host, self.bind_port)
+ }
+
+ pub fn recv_batch_timeout(&self) -> Duration {
+ Duration::from_millis(self.recv_batch_timeout_ms)
+ }
+
+ pub fn team_index_refresh_interval(&self) -> Duration {
+ Duration::from_secs(self.team_index_refresh_secs)
+ }
+
+ pub fn team_index_refresh_jitter(&self) -> Duration {
+ Duration::from_secs(self.team_index_refresh_jitter_secs)
+ }
+
+ fn pg_statement_timeout(&self) -> Option<u64> {
+ (self.pg_statement_timeout_ms != 0).then_some(self.pg_statement_timeout_ms)
+ }
+
+ pub fn pool_config(&self) -> PoolConfig {
+ PoolConfig {
+ min_connections: self.min_pg_connections,
+ max_connections: self.max_pg_connections,
+ acquire_timeout: Duration::from_secs(self.pg_acquire_timeout_secs),
+ idle_timeout: Some(Duration::from_secs(300)),
+ test_before_acquire: true,
+ statement_timeout_ms: self.pg_statement_timeout(),
+ pool_name: Some(POOL_NAME.to_string()),
+ }
+ }
+
+ pub fn build_kafka_config(&self) -> KafkaConfig {
+ KafkaConfig {
+ kafka_hosts: self.kafka_hosts.clone(),
+ kafka_tls: self.kafka_tls,
+ kafka_client_rack: self.kafka_client_rack.clone(),
+ kafka_client_id: self.kafka_client_id.clone(),
+ kafka_compression_codec: self.kafka_compression_codec.clone(),
+ kafka_producer_partitioner: Some(self.kafka_producer_partitioner.clone()),
+ kafka_producer_linger_ms: 20,
+ kafka_producer_queue_mib: 400,
+ kafka_producer_queue_messages: 10_000_000,
+ kafka_message_timeout_ms: 20_000,
+ kafka_producer_batch_size: None,
+ kafka_producer_batch_num_messages: None,
+ kafka_producer_enable_idempotence: None,
+ kafka_producer_max_in_flight_requests_per_connection: None,
+ kafka_producer_topic_metadata_refresh_interval_ms: None,
+ kafka_producer_message_max_bytes: None,
+ kafka_producer_sticky_partitioning_linger_ms: None,
+ }
+ }
+
+ /// Auto-commit is disabled: the loop stores offsets manually only after envelopes are ack'd,
+ /// then commits per batch (at-least-once ordering).
+ pub fn build_consumer_config(&self) -> ConsumerConfig {
+ ConsumerConfig {
+ kafka_consumer_group: self.kafka_consumer_group.clone(),
+ kafka_consumer_topic: self.input_topic.clone(),
+ kafka_consumer_offset_reset: self.kafka_consumer_offset_reset.clone(),
+ kafka_consumer_auto_commit: false,
+ kafka_consumer_auto_commit_interval_ms: 5000,
+ kafka_consumer_fetch_wait_max_ms: None,
+ kafka_consumer_fetch_min_bytes: None,
+ kafka_consumer_fetch_max_bytes: None,
+ kafka_consumer_max_partition_fetch_bytes: None,
+ kafka_consumer_group_instance_id: None,
+ kafka_consumer_partition_strategy: None,
+ kafka_consumer_socket_send_buffer_bytes: None,
+ kafka_consumer_socket_receive_buffer_bytes: None,
+ kafka_consumer_metadata_refresh_interval_ms: None,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn test_config() -> Config {
+ Config {
+ bind_host: "0.0.0.0".to_string(),
+ bind_port: 3322,
+ export_prometheus: true,
+ kafka_hosts: "localhost:9092".to_string(),
+ kafka_tls: false,
+ kafka_client_rack: String::new(),
+ kafka_client_id: String::new(),
+ input_topic: "clickhouse_events_json".to_string(),
+ kafka_consumer_group: "cohort-event-shuffler".to_string(),
+ kafka_consumer_offset_reset: "latest".to_string(),
+ output_topic: "cohort_stream_events".to_string(),
+ kafka_producer_partitioner: "murmur2_random".to_string(),
+ kafka_compression_codec: "none".to_string(),
+ database_url: "postgres://posthog:posthog@localhost:5432/posthog".to_string(),
+ min_pg_connections: 1,
+ max_pg_connections: 5,
+ pg_acquire_timeout_secs: 10,
+ pg_statement_timeout_ms: 5000,
+ team_index_refresh_secs: 300,
+ team_index_refresh_jitter_secs: 60,
+ team_allowlist: TeamAllowlist::All,
+ recv_batch_size: 1000,
+ recv_batch_timeout_ms: 500,
+ }
+ }
+
+ #[test]
+ fn kafka_config_pins_the_partitioner() {
+ let config = test_config();
+ assert_eq!(
+ config
+ .build_kafka_config()
+ .kafka_producer_partitioner
+ .as_deref(),
+ Some("murmur2_random"),
+ );
+ }
+
+ #[test]
+ fn consumer_disables_auto_commit_for_manual_offset_control() {
+ let config = test_config();
+ let consumer = config.build_consumer_config();
+ assert!(!consumer.kafka_consumer_auto_commit);
+ assert_eq!(consumer.kafka_consumer_topic, "clickhouse_events_json");
+ }
+
+ #[test]
+ fn statement_timeout_zero_means_database_default() {
+ let mut config = test_config();
+ config.pg_statement_timeout_ms = 0;
+ assert!(config.pool_config().statement_timeout_ms.is_none());
+ }
+}
diff --git a/rust/cohort-event-shuffler/src/consumer.rs b/rust/cohort-event-shuffler/src/consumer.rs
new file mode 100644
index 000000000000..90bce0fc2d22
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/consumer.rs
@@ -0,0 +1,264 @@
+//! Consume → filter → re-key → produce loop for `clickhouse_events_json`.
+//!
+//! Drops events with no `person_id`, skips teams with no realtime cohorts, then re-keys the
+//! survivors by `(team_id, person_id)` to match the Node CDP precalculated-filters gating.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+use common_kafka::kafka_consumer::{RecvErr, SingleTopicConsumer};
+use common_types::ClickHouseEvent;
+use lifecycle::Handle;
+use metrics::counter;
+use tracing::{debug, error, info, warn};
+
+use crate::event::CohortStreamEvent;
+use crate::filter_team_index::TeamIndex;
+use crate::observability::metrics::{
+ EVENTS_CONSUMED, EVENTS_DROPPED_NO_PERSON_ID, EVENTS_FORWARDED, EVENTS_SKIPPED_TEAM_GATE,
+ PRODUCE_ERRORS,
+};
+use crate::producer::CohortStreamProducer;
+
+/// `Forward` carries the moved-out `person_id` so the forward path needs no clone.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ForwardDecision {
+ Forward { person_id: String },
+ DropNoPersonId,
+ SkipTeamGate,
+}
+
+/// Takes `person_id` by `take()` to avoid a clone; `person_id` is checked first because a missing
+/// routing key disqualifies the event regardless of the team gate.
+pub fn classify(event: &mut ClickHouseEvent, team_index: &TeamIndex) -> ForwardDecision {
+ let Some(person_id) = event.person_id.take() else {
+ return ForwardDecision::DropNoPersonId;
+ };
+ if !team_index.contains(event.team_id) {
+ return ForwardDecision::SkipTeamGate;
+ }
+ ForwardDecision::Forward { person_id }
+}
+
+pub struct EventShuffler {
+ consumer: SingleTopicConsumer,
+ producer: CohortStreamProducer,
+ team_index: Arc<TeamIndex>,
+ handle: Handle,
+ batch_size: usize,
+ batch_timeout: Duration,
+}
+
+impl EventShuffler {
+ pub fn new(
+ consumer: SingleTopicConsumer,
+ producer: CohortStreamProducer,
+ team_index: Arc<TeamIndex>,
+ handle: Handle,
+ batch_size: usize,
+ batch_timeout: Duration,
+ ) -> Self {
+ Self {
+ consumer,
+ producer,
+ team_index,
+ handle,
+ batch_size,
+ batch_timeout,
+ }
+ }
+
+ /// A successful batch (even an empty poll) heartbeats liveness, so an idle topic stays healthy
+ /// and only a wedged loop or a persistent produce failure trips the stall detector.
+ pub async fn process(self) {
+ let _guard = self.handle.process_scope();
+ info!("shuffler consume loop starting");
+
+ loop {
+ tokio::select! {
+ _ = self.handle.shutdown_recv() => {
+ info!("shutdown signal received, stopping consume loop");
+ break;
+ }
+ result = self.process_batch() => match result {
+ Ok(_) => self.handle.report_healthy(),
+ Err(err) => {
+ error!(error = %err, "batch processing failed; backing off");
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ }
+ },
+ }
+ }
+
+ info!("shuffler consume loop stopped");
+ }
+
+ async fn process_batch(&self) -> Result<usize> {
+ // Fail-closed until the team index loads once: don't consume — and advance offsets past —
+ // events while the gate would forward nothing.
+ if !self.team_index.is_loaded() {
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ return Ok(0);
+ }
+
+ let results = self
+ .consumer
+ .json_recv_batch::<ClickHouseEvent>(self.batch_size, self.batch_timeout)
+ .await;
+ if results.is_empty() {
+ return Ok(0);
+ }
+
+ let mut consumed = 0u64;
+ let mut dropped = 0u64;
+ let mut skipped = 0u64;
+ let mut forwardable = Vec::new();
+ let mut offsets = Vec::with_capacity(results.len());
+
+ for result in results {
+ let (mut event, offset) = match result {
+ Ok(pair) => pair,
+ Err(err) => {
+ // Poison pills are already offset-stored by the consumer; just log.
+ log_recv_error(&err);
+ continue;
+ }
+ };
+
+ consumed += 1;
+ let source_partition = offset.partition();
+ let source_offset = offset.get_value();
+
+ match classify(&mut event, &self.team_index) {
+ ForwardDecision::Forward { person_id } => {
+ forwardable.push(CohortStreamEvent::from_clickhouse(
+ event,
+ person_id,
+ source_partition,
+ source_offset,
+ ))
+ }
+ ForwardDecision::DropNoPersonId => dropped += 1,
+ ForwardDecision::SkipTeamGate => skipped += 1,
+ }
+
+ offsets.push(offset);
+ }
+
+ counter!(EVENTS_CONSUMED).increment(consumed);
+ if dropped > 0 {
+ counter!(EVENTS_DROPPED_NO_PERSON_ID).increment(dropped);
+ }
+ if skipped > 0 {
+ counter!(EVENTS_SKIPPED_TEAM_GATE).increment(skipped);
+ }
+
+ // At-least-once: produce and await acks BEFORE storing source offsets, and bail without
+ // committing on any produce failure. A transient produce failure that recovers gets
+ // committed over by a later batch, dropping those events — accepted tradeoff; the downstream
+ // processor dedups replays via source_offset/source_partition.
+ let forward_count = forwardable.len();
+ if forward_count > 0 {
+ let produce_results = self.producer.forward(forwardable).await;
+ let errors = produce_results.iter().filter(|r| r.is_err()).count();
+ if errors > 0 {
+ counter!(PRODUCE_ERRORS).increment(errors as u64);
+ let first_error = produce_results
+ .iter()
+ .find_map(|r| r.as_ref().err())
+ .map(ToString::to_string)
+ .unwrap_or_default();
+ anyhow::bail!(
+ "{errors}/{forward_count} produces to cohort_stream_events failed: {first_error}"
+ );
+ }
+ counter!(EVENTS_FORWARDED).increment(forward_count as u64);
+ }
+
+ for offset in offsets {
+ if let Err(err) = offset.store() {
+ warn!(error = %err, "failed to store consumer offset");
+ }
+ }
+ self.consumer
+ .commit()
+ .context("committing consumer offsets after forwarding batch")?;
+
+ Ok(consumed as usize)
+ }
+}
+
+fn log_recv_error(err: &RecvErr) {
+ match err {
+ RecvErr::Empty => debug!("skipped message with empty payload"),
+ RecvErr::Serde(e) => debug!(error = %e, "skipped undeserializable event"),
+ RecvErr::Kafka(e) => warn!(error = %e, "kafka recv error during batch"),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::event::sample_clickhouse_event;
+
+ fn index_with(teams: &[i32]) -> TeamIndex {
+ TeamIndex::from_teams(teams.iter().copied())
+ }
+
+ #[test]
+ fn classify_covers_every_gate_outcome() {
+ let cases = [
+ (
+ "forward",
+ Some("p"),
+ 2,
+ vec![2],
+ ForwardDecision::Forward {
+ person_id: "p".to_string(),
+ },
+ ),
+ (
+ "no person",
+ None,
+ 2,
+ vec![2],
+ ForwardDecision::DropNoPersonId,
+ ),
+ (
+ "team gate",
+ Some("p"),
+ 99,
+ vec![2],
+ ForwardDecision::SkipTeamGate,
+ ),
+ (
+ "no person precedence",
+ None,
+ 99,
+ vec![2],
+ ForwardDecision::DropNoPersonId,
+ ),
+ (
+ "empty index",
+ Some("p"),
+ 2,
+ vec![],
+ ForwardDecision::SkipTeamGate,
+ ),
+ ];
+
+ for (name, person_id, team_id, teams, expected) in cases {
+ let mut event = sample_clickhouse_event(team_id, person_id);
+ let index = index_with(&teams);
+ assert_eq!(classify(&mut event, &index), expected, "case: {name}");
+ }
+ }
+
+ #[test]
+ fn unloaded_index_forwards_nothing() {
+ let index = TeamIndex::new();
+ let mut event = sample_clickhouse_event(2, Some("p"));
+ assert_eq!(classify(&mut event, &index), ForwardDecision::SkipTeamGate);
+ }
+}
diff --git a/rust/cohort-event-shuffler/src/event.rs b/rust/cohort-event-shuffler/src/event.rs
new file mode 100644
index 000000000000..0ea0135c88b9
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/event.rs
@@ -0,0 +1,206 @@
+//! The `cohort_stream_events` envelope and the canonical re-key derivation.
+//!
+//! Forwards only the fields the downstream bytecode evaluation needs; group properties,
+//! `person_mode`, `created_at`, `project_id` and similar are intentionally dropped.
+
+use common_types::ClickHouseEvent;
+use serde::{Deserialize, Serialize};
+
+/// Single source of truth for the re-key string. Every producer targeting a topic co-partitioned
+/// with `cohort_stream_events` must use this so a given `(team_id, person_id)` lands on the same
+/// partition — and downstream worker — across topics and runtimes (Rust here, Node for
+/// `person_merge_events`), given the shared `murmur2_random` partitioner and 64-partition count.
+#[inline]
+pub fn partition_key(team_id: i32, person_id: &str) -> String {
+ format!("{team_id}:{person_id}")
+}
+
+/// `source_partition` / `source_offset` carry the upstream `clickhouse_events_json` coordinates so
+/// the downstream processor can make counter increments replay-safe via per-key offset tracking.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CohortStreamEvent {
+ pub team_id: i32,
+ pub person_id: String,
+ pub distinct_id: String,
+ pub uuid: String,
+ pub event: String,
+ pub timestamp: String,
+ pub properties: Option<String>,
+ pub person_properties: Option<String>,
+ pub elements_chain: Option<String>,
+ pub source_offset: i64,
+ pub source_partition: i32,
+}
+
+impl CohortStreamEvent {
+ /// Moves every owned field out of `event` rather than cloning; `person_id` is already extracted
+ /// by [`crate::consumer::classify`].
+ pub fn from_clickhouse(
+ event: ClickHouseEvent,
+ person_id: String,
+ source_partition: i32,
+ source_offset: i64,
+ ) -> Self {
+ Self {
+ team_id: event.team_id,
+ person_id,
+ distinct_id: event.distinct_id,
+ uuid: event.uuid.to_string(),
+ event: event.event,
+ timestamp: event.timestamp,
+ properties: event.properties,
+ person_properties: event.person_properties,
+ elements_chain: event.elements_chain,
+ source_offset,
+ source_partition,
+ }
+ }
+
+ pub fn partition_key(&self) -> String {
+ partition_key(self.team_id, &self.person_id)
+ }
+}
+
+#[cfg(test)]
+pub(crate) fn sample_clickhouse_event(team_id: i32, person_id: Option<&str>) -> ClickHouseEvent {
+ use common_types::PersonMode;
+ use uuid::Uuid;
+
+ ClickHouseEvent {
+ uuid: Uuid::from_u128(0x0192_8aaa_bbbb_cccc_dddd_eeee_eeee_eeee),
+ team_id,
+ project_id: Some(7),
+ event: "$pageview".to_string(),
+ distinct_id: "[email protected]".to_string(),
+ properties: Some(r#"{"$current_url":"/pricing"}"#.to_string()),
+ person_id: person_id.map(str::to_string),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ created_at: "2026-05-26 12:34:57.000000".to_string(),
+ captured_at: None,
+ elements_chain: Some("a:href=\"/x\"".to_string()),
+ person_created_at: None,
+ person_properties: Some(r#"{"email":"[email protected]"}"#.to_string()),
+ group0_properties: Some("{}".to_string()),
+ group1_properties: None,
+ group2_properties: None,
+ group3_properties: None,
+ group4_properties: None,
+ group0_created_at: None,
+ group1_created_at: None,
+ group2_created_at: None,
+ group3_created_at: None,
+ group4_created_at: None,
+ person_mode: PersonMode::Full,
+ historical_migration: None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample_event(team_id: i32, person_id: Option<&str>) -> ClickHouseEvent {
+ sample_clickhouse_event(team_id, person_id)
+ }
+
+ #[test]
+ fn partition_key_is_team_colon_person() {
+ assert_eq!(partition_key(42, "abc"), "42:abc");
+ assert_eq!(partition_key(-1, ""), "-1:");
+ }
+
+ #[test]
+ fn partition_key_is_deterministic_across_calls() {
+ let a = partition_key(2, "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee");
+ let b = partition_key(2, "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee");
+ assert_eq!(a, b);
+ }
+
+ #[test]
+ fn from_clickhouse_maps_every_field() {
+ let event = sample_event(42, Some("01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee"));
+ // from_clickhouse consumes the event, so capture the uuid first.
+ let expected_uuid = event.uuid.to_string();
+ let envelope = CohortStreamEvent::from_clickhouse(
+ event,
+ "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ 17,
+ 12345,
+ );
+
+ assert_eq!(envelope.team_id, 42);
+ assert_eq!(envelope.person_id, "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee");
+ assert_eq!(envelope.distinct_id, "[email protected]");
+ assert_eq!(envelope.uuid, expected_uuid);
+ assert_eq!(envelope.event, "$pageview");
+ assert_eq!(envelope.timestamp, "2026-05-26 12:34:56.789000");
+ assert_eq!(
+ envelope.properties.as_deref(),
+ Some(r#"{"$current_url":"/pricing"}"#)
+ );
+ assert_eq!(
+ envelope.person_properties.as_deref(),
+ Some(r#"{"email":"[email protected]"}"#)
+ );
+ assert_eq!(envelope.elements_chain.as_deref(), Some("a:href=\"/x\""));
+ assert_eq!(envelope.source_partition, 17);
+ assert_eq!(envelope.source_offset, 12345);
+ }
+
+ #[test]
+ fn from_clickhouse_preserves_null_optionals() {
+ let mut event = sample_event(1, Some("p"));
+ event.properties = None;
+ event.person_properties = None;
+ event.elements_chain = None;
+
+ let envelope = CohortStreamEvent::from_clickhouse(event, "p".to_string(), 0, 0);
+ assert!(envelope.properties.is_none());
+ assert!(envelope.person_properties.is_none());
+ assert!(envelope.elements_chain.is_none());
+ }
+
+ #[test]
+ fn envelope_partition_key_matches_free_function() {
+ let event = sample_event(99, Some("xyz"));
+ let envelope = CohortStreamEvent::from_clickhouse(event, "xyz".to_string(), 3, 9);
+ assert_eq!(envelope.partition_key(), "99:xyz");
+ assert_eq!(envelope.partition_key(), partition_key(99, "xyz"));
+ }
+
+ #[test]
+ fn serialized_envelope_has_tdd_4_3_keys() {
+ let event = sample_event(42, Some("p1"));
+ let envelope = CohortStreamEvent::from_clickhouse(event, "p1".to_string(), 17, 12345);
+ let value: serde_json::Value = serde_json::to_value(&envelope).unwrap();
+ let obj = value.as_object().unwrap();
+
+ for key in [
+ "team_id",
+ "person_id",
+ "distinct_id",
+ "uuid",
+ "event",
+ "timestamp",
+ "properties",
+ "person_properties",
+ "elements_chain",
+ "source_offset",
+ "source_partition",
+ ] {
+ assert!(obj.contains_key(key), "envelope is missing key `{key}`");
+ }
+ // Replay coordinates must serialize numeric, not as strings.
+ assert_eq!(obj["source_offset"], serde_json::json!(12345));
+ assert_eq!(obj["source_partition"], serde_json::json!(17));
+ }
+
+ #[test]
+ fn envelope_round_trips_through_json() {
+ let event = sample_event(42, Some("p1"));
+ let envelope = CohortStreamEvent::from_clickhouse(event, "p1".to_string(), 17, 12345);
+ let json = serde_json::to_string(&envelope).unwrap();
+ let decoded: CohortStreamEvent = serde_json::from_str(&json).unwrap();
+ assert_eq!(envelope, decoded);
+ }
+}
diff --git a/rust/cohort-event-shuffler/src/filter_team_index.rs b/rust/cohort-event-shuffler/src/filter_team_index.rs
new file mode 100644
index 000000000000..f01dc9a2541d
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/filter_team_index.rs
@@ -0,0 +1,236 @@
+//! In-memory index of teams with ≥1 realtime-supported cohort, consulted by the consumer's team
+//! gate. Refreshed on a `refresh_secs ± jitter` poll and swapped atomically via
+//! [`arc_swap::ArcSwap`] so hot-path reads are lock-free and a refresh never blocks the consumer.
+//!
+//! Staleness is safe: the gate is defense-in-depth and the downstream processor re-checks
+//! membership, so a stale snapshot only over-forwards briefly. The index starts empty and unloaded
+//! so nothing is forwarded until the first refresh — avoiding a cold-start flood if the DB is
+//! briefly unreachable at boot.
+
+use std::collections::HashSet;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+use arc_swap::ArcSwap;
+use common_types::cohort::TeamAllowlist;
+use lifecycle::Handle;
+use metrics::gauge;
+use rand::Rng;
+use sqlx::PgPool;
+use tracing::{debug, info, warn};
+
+use crate::observability::metrics::ACTIVE_TEAMS;
+
+/// Must match the Node filter manager's predicate (`cohort_type='realtime'`, not deleted, non-null
+/// `filters`); projected to `DISTINCT team_id` since the shuffler only needs the gate.
+const TEAMS_WITH_REALTIME_COHORTS_SQL: &str = "SELECT DISTINCT team_id \
+ FROM posthog_cohort \
+ WHERE cohort_type = 'realtime' AND deleted = false AND filters IS NOT NULL";
+
+pub struct TeamIndex {
+ teams: ArcSwap<HashSet<i32>>,
+ loaded: AtomicBool,
+ /// Applied at [`refresh`](Self::refresh) time: teams the DB reports as realtime but outside this
+ /// allowlist never enter the snapshot, so the hot-path gate and the `ACTIVE_TEAMS` gauge both
+ /// reflect the scoped set for free.
+ allowlist: TeamAllowlist,
+}
+
+impl TeamIndex {
+ pub fn new() -> Self {
+ Self::with_allowlist(TeamAllowlist::All)
+ }
+
+ pub fn with_allowlist(allowlist: TeamAllowlist) -> Self {
+ Self {
+ teams: ArcSwap::from_pointee(HashSet::new()),
+ loaded: AtomicBool::new(false),
+ allowlist,
+ }
+ }
+
+ pub fn contains(&self, team_id: i32) -> bool {
+ self.teams.load().contains(&team_id)
+ }
+
+ /// False until the first refresh succeeds, while the set is empty and nothing should forward.
+ pub fn is_loaded(&self) -> bool {
+ self.loaded.load(Ordering::Acquire)
+ }
+
+ pub fn len(&self) -> usize {
+ self.teams.load().len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ /// Test seam: an already-loaded index without a DB. Production loads via [`refresh`](Self::refresh).
+ pub fn from_teams(teams: impl IntoIterator<Item = i32>) -> Self {
+ let index = Self::new();
+ index.store(teams.into_iter().collect());
+ index
+ }
+
+ fn store(&self, teams: HashSet<i32>) {
+ gauge!(ACTIVE_TEAMS).set(teams.len() as f64);
+ self.teams.store(Arc::new(teams));
+ self.loaded.store(true, Ordering::Release);
+ }
+
+ pub async fn refresh(&self, pool: &PgPool) -> Result<usize> {
+ let fetched: Vec<i32> = sqlx::query_scalar(TEAMS_WITH_REALTIME_COHORTS_SQL)
+ .fetch_all(pool)
+ .await
+ .context("querying posthog_cohort for realtime teams")?;
+ let fetched_count = fetched.len();
+ let kept = filter_by_allowlist(fetched, &self.allowlist);
+ if kept.len() != fetched_count {
+ debug!(
+ fetched = fetched_count,
+ kept = kept.len(),
+ excluded = fetched_count - kept.len(),
+ "team index filtered realtime teams by the allowlist",
+ );
+ }
+ let count = kept.len();
+ self.store(kept);
+ Ok(count)
+ }
+}
+
+/// Keep only the teams in scope. Separated from [`TeamIndex::refresh`] so the allowlist filter is
+/// testable without a database.
+fn filter_by_allowlist(fetched: Vec<i32>, allowlist: &TeamAllowlist) -> HashSet<i32> {
+ fetched
+ .into_iter()
+ .filter(|team_id| allowlist.includes(*team_id))
+ .collect()
+}
+
+impl Default for TeamIndex {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Sleeps `interval ± jitter` between refreshes to spread DB load across pods. On failure it keeps
+/// serving the previous snapshot — staleness is safe — and retries next tick.
+///
+/// Registered without a liveness deadline: a refresh outage must not kill the service (that stops
+/// forwarding entirely, worse than a stale gate). An unexpected exit still drops the process-scope
+/// guard and signals the manager.
+pub async fn run_refresh_loop(
+ index: Arc<TeamIndex>,
+ pool: PgPool,
+ interval: Duration,
+ jitter: Duration,
+ handle: Handle,
+) {
+ let _guard = handle.process_scope();
+
+ loop {
+ let sleep_for = next_interval(interval, jitter);
+ tokio::select! {
+ _ = handle.shutdown_recv() => break,
+ _ = tokio::time::sleep(sleep_for) => match index.refresh(&pool).await {
+ Ok(0) => {
+ warn!(
+ "team index has zero in-scope teams (no realtime cohorts, or all filtered \
+ by REALTIME_COHORT_TEAM_ALLOWLIST); forwarding nothing",
+ );
+ }
+ Ok(count) => info!(active_teams = count, "team index refreshed"),
+ Err(err) => warn!(
+ error = %err,
+ "team index refresh failed; keeping previous snapshot",
+ ),
+ },
+ }
+ }
+}
+
+fn next_interval(interval: Duration, jitter: Duration) -> Duration {
+ if jitter.is_zero() {
+ return interval;
+ }
+ let lo = interval.saturating_sub(jitter).as_millis() as u64;
+ let hi = interval.saturating_add(jitter).as_millis() as u64;
+ // Drop the non-Send `ThreadRng` before returning so it never spans an await.
+ let millis = rand::thread_rng().gen_range(lo..=hi);
+ Duration::from_millis(millis)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn new_index_is_unloaded_and_empty() {
+ let index = TeamIndex::new();
+ assert!(!index.is_loaded());
+ assert!(index.is_empty());
+ assert!(!index.contains(2));
+ }
+
+ #[test]
+ fn store_marks_loaded_and_updates_membership() {
+ let index = TeamIndex::new();
+ index.store(HashSet::from([1, 2, 42]));
+
+ assert!(index.is_loaded());
+ assert_eq!(index.len(), 3);
+ assert!(index.contains(1));
+ assert!(index.contains(42));
+ assert!(!index.contains(3));
+ }
+
+ #[test]
+ fn store_replaces_the_previous_snapshot() {
+ let index = TeamIndex::new();
+ index.store(HashSet::from([1, 2]));
+ index.store(HashSet::from([3]));
+
+ assert!(!index.contains(1));
+ assert!(index.contains(3));
+ assert_eq!(index.len(), 1);
+ }
+
+ #[test]
+ fn filter_by_allowlist_all_keeps_everything() {
+ let kept = filter_by_allowlist(vec![1, 2, 99], &TeamAllowlist::All);
+ assert_eq!(kept, HashSet::from([1, 2, 99]));
+ }
+
+ #[test]
+ fn filter_by_allowlist_only_drops_out_of_scope_teams() {
+ let kept = filter_by_allowlist(vec![1, 2, 99], &TeamAllowlist::Only(HashSet::from([2])));
+ assert_eq!(kept, HashSet::from([2]));
+ }
+
+ #[test]
+ fn filter_by_allowlist_empty_scope_keeps_nothing() {
+ let kept = filter_by_allowlist(vec![1, 2, 99], &TeamAllowlist::Only(HashSet::new()));
+ assert!(kept.is_empty());
+ }
+
+ #[test]
+ fn next_interval_without_jitter_is_exact() {
+ let interval = Duration::from_secs(300);
+ assert_eq!(next_interval(interval, Duration::ZERO), interval);
+ }
+
+ #[test]
+ fn next_interval_stays_within_jitter_band() {
+ let interval = Duration::from_secs(300);
+ let jitter = Duration::from_secs(60);
+ for _ in 0..1000 {
+ let d = next_interval(interval, jitter);
+ assert!(d >= Duration::from_secs(240), "{d:?} below lower bound");
+ assert!(d <= Duration::from_secs(360), "{d:?} above upper bound");
+ }
+ }
+}
diff --git a/rust/cohort-event-shuffler/src/lib.rs b/rust/cohort-event-shuffler/src/lib.rs
new file mode 100644
index 000000000000..d736a07121cf
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/lib.rs
@@ -0,0 +1,13 @@
+//! Stateless Kafka re-keying service for the Behavioral Cohorts stream pipeline.
+//!
+//! Consumes `clickhouse_events_json` (keyed by `event.uuid`) and re-publishes events for teams
+//! with realtime cohorts to `cohort_stream_events`, keyed by `hash(team_id, person_id)`. The
+//! re-key gives `cohort-stream-processor` per-`(team_id, person_id)` state affinity so it can
+//! scale horizontally.
+
+pub mod config;
+pub mod consumer;
+pub mod event;
+pub mod filter_team_index;
+pub mod observability;
+pub mod producer;
diff --git a/rust/cohort-event-shuffler/src/main.rs b/rust/cohort-event-shuffler/src/main.rs
new file mode 100644
index 000000000000..0c9052d9ecd9
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/main.rs
@@ -0,0 +1,188 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+use common_database::get_pool_with_config;
+use common_kafka::kafka_consumer::SingleTopicConsumer;
+use envconfig::Envconfig;
+use lifecycle::{ComponentOptions, Manager};
+use tokio::net::TcpListener;
+use tracing::{info, warn};
+use tracing_subscriber::layer::SubscriberExt;
+use tracing_subscriber::util::SubscriberInitExt;
+use tracing_subscriber::{fmt, EnvFilter, Layer};
+
+use cohort_event_shuffler::config::Config;
+use cohort_event_shuffler::consumer::EventShuffler;
+use cohort_event_shuffler::filter_team_index::{run_refresh_loop, TeamIndex};
+use cohort_event_shuffler::observability;
+use cohort_event_shuffler::producer::CohortStreamProducer;
+
+common_alloc::used!();
+
+const SERVICE_NAME: &str = "cohort-event-shuffler";
+
+fn main() -> Result<()> {
+ let config = Config::init_from_env()
+ .context("Failed to load configuration from environment variables")?;
+
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .context("Failed to build tokio runtime")?;
+
+ runtime.block_on(async_main(config))
+}
+
+async fn async_main(config: Config) -> Result<()> {
+ init_tracing();
+ log_startup(&config);
+
+ let mut manager = Manager::builder(SERVICE_NAME)
+ .with_global_shutdown_timeout(Duration::from_secs(30))
+ .build();
+
+ let metrics_handle =
+ manager.register("metrics", ComponentOptions::new().is_observability(true));
+ // The consumer owns the liveness deadline: no successful batch within deadline × stall_threshold
+ // trips coordinated shutdown.
+ let consumer_handle = manager.register(
+ "consumer",
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(15))
+ .with_liveness_deadline(Duration::from_secs(60))
+ .with_stall_threshold(3),
+ );
+ // No liveness deadline: a refresh outage must not kill the service (staleness is safe). An
+ // unexpected exit still signals the manager via the process-scope guard.
+ let team_index_handle = manager.register(
+ "team-index",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),
+ );
+
+ let readiness = manager.readiness_handler();
+ let liveness = manager.liveness_handler();
+
+ let recorder_handle = if config.export_prometheus {
+ Some(observability::metrics::install_recorder())
+ } else {
+ None
+ };
+
+ // Build infrastructure before starting the monitor: a failure here returns before the monitor
+ // runs, so dropped handles are harmless no-ops and the process exits non-zero.
+ let pool = get_pool_with_config(&config.database_url, config.pool_config())
+ .context("creating posthog_cohort database pool")?;
+
+ let team_index = Arc::new(TeamIndex::with_allowlist(config.team_allowlist.clone()));
+ match team_index.refresh(&pool).await {
+ Ok(count) => info!(active_teams = count, "initial team index loaded"),
+ Err(err) => warn!(
+ error = %err,
+ "initial team index load failed; consumer forwards nothing until the refresh task succeeds",
+ ),
+ }
+
+ let kafka_config = config.build_kafka_config();
+ let producer = CohortStreamProducer::new(&kafka_config, config.output_topic.clone())
+ .await
+ .context("creating cohort_stream_events producer")?;
+ let consumer = SingleTopicConsumer::new(kafka_config, config.build_consumer_config())
+ .context("creating clickhouse_events_json consumer")?;
+
+ let guard = manager.monitor_background();
+
+ let refresh_index = team_index.clone();
+ let refresh_pool = pool.clone();
+ let refresh_interval = config.team_index_refresh_interval();
+ let refresh_jitter = config.team_index_refresh_jitter();
+ tokio::spawn(async move {
+ run_refresh_loop(
+ refresh_index,
+ refresh_pool,
+ refresh_interval,
+ refresh_jitter,
+ team_index_handle,
+ )
+ .await;
+ });
+
+ let shuffler = EventShuffler::new(
+ consumer,
+ producer,
+ team_index,
+ consumer_handle,
+ config.recv_batch_size,
+ config.recv_batch_timeout(),
+ );
+ tokio::spawn(async move {
+ shuffler.process().await;
+ });
+
+ let app = observability::health::router(SERVICE_NAME, readiness, liveness, recorder_handle);
+ let bind = config.bind_address();
+ info!(address = %bind, "observability server starting");
+
+ let listener = TcpListener::bind(&bind)
+ .await
+ .with_context(|| format!("failed to bind observability server to {bind}"))?;
+ axum::serve(listener, app)
+ .with_graceful_shutdown(metrics_handle.shutdown_signal())
+ .await
+ .context("observability server error")?;
+ metrics_handle.work_completed();
+
+ guard.wait().await?;
+
+ info!(service = SERVICE_NAME, "service stopped");
+ Ok(())
+}
+
+/// Deliberately omits `database_url`, which carries credentials.
+fn log_startup(config: &Config) {
+ info!(
+ service = SERVICE_NAME,
+ input_topic = %config.input_topic,
+ output_topic = %config.output_topic,
+ consumer_group = %config.kafka_consumer_group,
+ partitioner = %config.kafka_producer_partitioner,
+ offset_reset = %config.kafka_consumer_offset_reset,
+ recv_batch_size = config.recv_batch_size,
+ team_index_refresh_secs = config.team_index_refresh_secs,
+ team_allowlist = ?config.team_allowlist,
+ "starting cohort-event-shuffler",
+ );
+}
+
+/// JSON structured logging by default; human-readable when `RUST_LOG` contains `debug`.
+fn init_tracing() {
+ let is_debug = std::env::var("RUST_LOG")
+ .map(|v| v.contains("debug"))
+ .unwrap_or(false);
+
+ let log_layer = if is_debug {
+ fmt::layer()
+ .with_target(true)
+ .with_level(true)
+ .with_ansi(true)
+ .with_filter(
+ EnvFilter::builder()
+ .with_default_directive(tracing::level_filters::LevelFilter::INFO.into())
+ .from_env_lossy(),
+ )
+ .boxed()
+ } else {
+ fmt::layer()
+ .json()
+ .flatten_event(true)
+ .with_current_span(true)
+ .with_filter(
+ EnvFilter::builder()
+ .with_default_directive(tracing::level_filters::LevelFilter::INFO.into())
+ .from_env_lossy(),
+ )
+ .boxed()
+ };
+
+ tracing_subscriber::registry().with(log_layer).init();
+}
diff --git a/rust/cohort-event-shuffler/src/observability/health.rs b/rust/cohort-event-shuffler/src/observability/health.rs
new file mode 100644
index 000000000000..0f7e538e1f54
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/observability/health.rs
@@ -0,0 +1,44 @@
+//! Observability HTTP surface.
+//!
+//! `/_health` always returns 200: the `lifecycle` monitor owns health internally and triggers
+//! coordinated shutdown on stall rather than relying on K8s liveness kills. `/_ready` flips to 503
+//! once graceful shutdown begins.
+
+use std::future::ready;
+
+use axum::response::IntoResponse;
+use axum::routing::get;
+use axum::Router;
+use lifecycle::{LivenessHandler, ReadinessHandler};
+use metrics_exporter_prometheus::PrometheusHandle;
+
+/// `metrics = None` omits the `/metrics` route.
+pub fn router(
+ service_name: &'static str,
+ readiness: ReadinessHandler,
+ liveness: LivenessHandler,
+ metrics: Option<PrometheusHandle>,
+) -> Router {
+ let mut app = Router::new()
+ .route("/", get(move || async move { service_name }))
+ .route(
+ "/_health",
+ get(move || {
+ let liveness = liveness.clone();
+ async move { liveness.check().into_response() }
+ }),
+ )
+ .route(
+ "/_ready",
+ get(move || {
+ let readiness = readiness.clone();
+ async move { readiness.check().await }
+ }),
+ );
+
+ if let Some(handle) = metrics {
+ app = app.route("/metrics", get(move || ready(handle.render())));
+ }
+
+ app
+}
diff --git a/rust/cohort-event-shuffler/src/observability/metrics.rs b/rust/cohort-event-shuffler/src/observability/metrics.rs
new file mode 100644
index 000000000000..113aaa54a1f3
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/observability/metrics.rs
@@ -0,0 +1,19 @@
+//! Prometheus recorder setup and the shuffler's metric-name constants.
+
+use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};
+
+/// Every consumed message, forwarded or not.
+pub const EVENTS_CONSUMED: &str = "shuffler_events_consumed_total";
+pub const EVENTS_FORWARDED: &str = "shuffler_events_forwarded_total";
+pub const EVENTS_DROPPED_NO_PERSON_ID: &str = "shuffler_events_dropped_no_person_id_total";
+pub const EVENTS_SKIPPED_TEAM_GATE: &str = "shuffler_events_skipped_team_gate_total";
+pub const PRODUCE_ERRORS: &str = "shuffler_produce_errors_total";
+pub const ACTIVE_TEAMS: &str = "shuffler_active_teams";
+
+/// # Panics
+/// Panics if a global metrics recorder has already been installed.
+pub fn install_recorder() -> PrometheusHandle {
+ PrometheusBuilder::new()
+ .install_recorder()
+ .expect("failed to install Prometheus recorder")
+}
diff --git a/rust/cohort-event-shuffler/src/observability/mod.rs b/rust/cohort-event-shuffler/src/observability/mod.rs
new file mode 100644
index 000000000000..6c4f2e4ac531
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/observability/mod.rs
@@ -0,0 +1,2 @@
+pub mod health;
+pub mod metrics;
diff --git a/rust/cohort-event-shuffler/src/producer.rs b/rust/cohort-event-shuffler/src/producer.rs
new file mode 100644
index 000000000000..fc6b7befa7cb
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/producer.rs
@@ -0,0 +1,53 @@
+//! Kafka producer for `cohort_stream_events`. The `murmur2_random` partitioner is pinned in
+//! [`crate::config`]; this module only supplies the [`partition_key`].
+
+use anyhow::{Context, Result};
+use common_kafka::config::KafkaConfig;
+use common_kafka::kafka_producer::{
+ create_kafka_producer, send_keyed_iter_to_kafka_with_headers, KafkaContext, KafkaProduceError,
+};
+use common_liveness::SyncLivenessReporter;
+use rdkafka::producer::FutureProducer;
+
+use crate::event::{partition_key, CohortStreamEvent};
+
+/// A producer stall blocks the consumer's `forward().await`, which stops the consumer (owner of
+/// the liveness deadline) from heartbeating and trips the stall detector. So the producer reports
+/// always-healthy rather than feeding its stats into the consumer's health and masking that stall.
+#[derive(Clone, Copy)]
+struct AlwaysHealthy;
+
+impl SyncLivenessReporter for AlwaysHealthy {
+ fn report_healthy(&self) {}
+ fn report_unhealthy(&self) {}
+}
+
+pub struct CohortStreamProducer {
+ producer: FutureProducer<KafkaContext>,
+ topic: String,
+}
+
+impl CohortStreamProducer {
+ pub async fn new(kafka_config: &KafkaConfig, topic: String) -> Result<Self> {
+ let producer = create_kafka_producer(kafka_config, AlwaysHealthy)
+ .await
+ .context("creating cohort_stream_events producer")?;
+ Ok(Self { producer, topic })
+ }
+
+ /// Produces and awaits all acks. Results are returned in input order so the caller can gate
+ /// offset commits on full success.
+ pub async fn forward(
+ &self,
+ events: Vec<CohortStreamEvent>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ send_keyed_iter_to_kafka_with_headers(
+ &self.producer,
+ &self.topic,
+ |event: &CohortStreamEvent| Some(partition_key(event.team_id, &event.person_id)),
+ |_| None,
+ events,
+ )
+ .await
+ }
+}
diff --git a/rust/cohort-event-shuffler/tests/integration.rs b/rust/cohort-event-shuffler/tests/integration.rs
new file mode 100644
index 000000000000..3baf7984ac75
--- /dev/null
+++ b/rust/cohort-event-shuffler/tests/integration.rs
@@ -0,0 +1,314 @@
+//! End-to-end shuffler test against an in-process rdkafka `MockCluster` (no external broker or DB).
+//! Asserts that only forwardable events land, that each `(team_id, person_id)` lands on a single
+//! partition, and that the envelope payload maps every field.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use cohort_event_shuffler::config::Config;
+use cohort_event_shuffler::consumer::EventShuffler;
+use cohort_event_shuffler::event::CohortStreamEvent;
+use cohort_event_shuffler::filter_team_index::TeamIndex;
+use cohort_event_shuffler::producer::CohortStreamProducer;
+use common_kafka::kafka_consumer::SingleTopicConsumer;
+use common_types::cohort::TeamAllowlist;
+use common_types::{ClickHouseEvent, PersonMode};
+use lifecycle::{ComponentOptions, Manager};
+use rdkafka::consumer::{Consumer, StreamConsumer};
+use rdkafka::producer::{FutureProducer, FutureRecord};
+use rdkafka::{ClientConfig, Message};
+use uuid::Uuid;
+
+const INPUT_TOPIC: &str = "clickhouse_events_json";
+const OUTPUT_TOPIC: &str = "cohort_stream_events";
+const OUTPUT_PARTITIONS: i32 = 8;
+
+struct InputSpec {
+ team_id: i32,
+ person_id: Option<&'static str>,
+ event: &'static str,
+ forwardable: bool,
+}
+
+fn test_config(bootstrap: &str) -> Config {
+ Config {
+ bind_host: "0.0.0.0".to_string(),
+ bind_port: 0,
+ export_prometheus: false,
+ kafka_hosts: bootstrap.to_string(),
+ kafka_tls: false,
+ kafka_client_rack: String::new(),
+ kafka_client_id: String::new(),
+ input_topic: INPUT_TOPIC.to_string(),
+ kafka_consumer_group: "shuffler-itest".to_string(),
+ kafka_consumer_offset_reset: "earliest".to_string(),
+ output_topic: OUTPUT_TOPIC.to_string(),
+ kafka_producer_partitioner: "murmur2_random".to_string(),
+ kafka_compression_codec: "none".to_string(),
+ database_url: String::new(), // unused: test loads the team index directly
+ min_pg_connections: 0,
+ max_pg_connections: 1,
+ pg_acquire_timeout_secs: 5,
+ pg_statement_timeout_ms: 0,
+ team_index_refresh_secs: 300,
+ team_index_refresh_jitter_secs: 0,
+ team_allowlist: TeamAllowlist::All,
+ recv_batch_size: 100,
+ recv_batch_timeout_ms: 200,
+ }
+}
+
+fn clickhouse_event(uuid: Uuid, spec: &InputSpec) -> ClickHouseEvent {
+ ClickHouseEvent {
+ uuid,
+ team_id: spec.team_id,
+ project_id: Some(spec.team_id as i64),
+ event: spec.event.to_string(),
+ distinct_id: format!("did-{}", spec.person_id.unwrap_or("anon")),
+ properties: Some(r#"{"$current_url":"/pricing"}"#.to_string()),
+ person_id: spec.person_id.map(str::to_string),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ created_at: "2026-05-26 12:34:57.000000".to_string(),
+ captured_at: None,
+ elements_chain: Some("a:href".to_string()),
+ person_created_at: None,
+ person_properties: Some(r#"{"email":"[email protected]"}"#.to_string()),
+ group0_properties: None,
+ group1_properties: None,
+ group2_properties: None,
+ group3_properties: None,
+ group4_properties: None,
+ group0_created_at: None,
+ group1_created_at: None,
+ group2_created_at: None,
+ group3_created_at: None,
+ group4_created_at: None,
+ person_mode: PersonMode::Full,
+ historical_migration: None,
+ }
+}
+
+/// Drains until `expected` envelopes arrive, then reads a short grace window to catch
+/// over-forwarding, bounded by `deadline`.
+async fn collect_output(
+ bootstrap: &str,
+ expected: usize,
+ deadline: Duration,
+) -> Vec<(i32, CohortStreamEvent)> {
+ let consumer: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap)
+ .set("group.id", "shuffler-itest-output-reader")
+ .set("auto.offset.reset", "earliest")
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("failed to create output reader");
+ consumer
+ .subscribe(&[OUTPUT_TOPIC])
+ .expect("failed to subscribe to output topic");
+
+ let mut collected = Vec::new();
+ let start = Instant::now();
+ let mut grace_until: Option<Instant> = None;
+
+ while start.elapsed() < deadline {
+ if let Some(grace) = grace_until {
+ if Instant::now() >= grace {
+ break;
+ }
+ }
+ match tokio::time::timeout(Duration::from_millis(250), consumer.recv()).await {
+ Ok(Ok(msg)) => {
+ if let Some(payload) = msg.payload() {
+ let envelope: CohortStreamEvent = serde_json::from_slice(payload)
+ .expect("output payload must be an envelope");
+ collected.push((msg.partition(), envelope));
+ if collected.len() >= expected && grace_until.is_none() {
+ grace_until = Some(Instant::now() + Duration::from_secs(1));
+ }
+ }
+ }
+ Ok(Err(err)) => panic!("output consumer error: {err}"),
+ Err(_) => {}
+ }
+ }
+ collected
+}
+
+#[tokio::test]
+async fn shuffler_forwards_only_gated_events_with_stable_partitioning() {
+ let (cluster, input_producer): (_, FutureProducer<_>) =
+ common_kafka::test::create_mock_kafka().await;
+ cluster
+ .create_topic(INPUT_TOPIC, 1, 1)
+ .expect("create input topic");
+ cluster
+ .create_topic(OUTPUT_TOPIC, OUTPUT_PARTITIONS, 1)
+ .expect("create output topic");
+ let bootstrap = cluster.bootstrap_servers();
+ let config = test_config(&bootstrap);
+
+ let team_index = Arc::new(TeamIndex::from_teams([2, 7])); // team 99 is absent (no realtime cohorts)
+
+ let inputs = [
+ InputSpec {
+ team_id: 2,
+ person_id: Some("pA"),
+ event: "$pageview",
+ forwardable: true,
+ },
+ InputSpec {
+ team_id: 2,
+ person_id: Some("pA"),
+ event: "$click",
+ forwardable: true,
+ },
+ InputSpec {
+ team_id: 99,
+ person_id: Some("pX"),
+ event: "$pageview",
+ forwardable: false,
+ },
+ InputSpec {
+ team_id: 2,
+ person_id: None,
+ event: "$pageview",
+ forwardable: false,
+ },
+ InputSpec {
+ team_id: 7,
+ person_id: Some("pB"),
+ event: "$pageview",
+ forwardable: true,
+ },
+ InputSpec {
+ team_id: 2,
+ person_id: Some("pA"),
+ event: "$identify",
+ forwardable: true,
+ },
+ InputSpec {
+ team_id: 99,
+ person_id: None,
+ event: "$autocapture",
+ forwardable: false,
+ },
+ InputSpec {
+ team_id: 7,
+ person_id: Some("pC"),
+ event: "$pageview",
+ forwardable: true,
+ },
+ ];
+
+ let mut uuid_by_index = Vec::new();
+ for (index, spec) in inputs.iter().enumerate() {
+ let uuid = Uuid::from_u128(0xC0_0000 + index as u128);
+ uuid_by_index.push(uuid);
+ let payload = serde_json::to_string(&clickhouse_event(uuid, spec)).unwrap();
+ let key = uuid.to_string();
+ input_producer
+ .send_result(FutureRecord::to(INPUT_TOPIC).key(&key).payload(&payload))
+ .expect("enqueue input")
+ .await
+ .expect("input produce canceled")
+ .expect("input produce failed");
+ }
+
+ let expected_forwardable: usize = inputs.iter().filter(|s| s.forwardable).count();
+
+ let mut manager = Manager::builder("shuffler-itest")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),
+ );
+ let _monitor = manager.monitor_background();
+
+ let consumer =
+ SingleTopicConsumer::new(config.build_kafka_config(), config.build_consumer_config())
+ .expect("create shuffler consumer");
+ let producer =
+ CohortStreamProducer::new(&config.build_kafka_config(), OUTPUT_TOPIC.to_string())
+ .await
+ .expect("create shuffler producer");
+ let shuffler = EventShuffler::new(
+ consumer,
+ producer,
+ team_index,
+ handle,
+ config.recv_batch_size,
+ config.recv_batch_timeout(),
+ );
+ tokio::spawn(async move { shuffler.process().await });
+
+ // MockCluster group coordination can be slow to start; collect_output returns early once the
+ // expected count arrives.
+ let output = collect_output(&bootstrap, expected_forwardable, Duration::from_secs(40)).await;
+
+ assert_eq!(
+ output.len(),
+ expected_forwardable,
+ "expected {expected_forwardable} forwarded events, got {}",
+ output.len(),
+ );
+
+ let forwardable_uuids: std::collections::HashSet<String> = inputs
+ .iter()
+ .enumerate()
+ .filter(|(_, s)| s.forwardable)
+ .map(|(i, _)| uuid_by_index[i].to_string())
+ .collect();
+ let output_uuids: std::collections::HashSet<String> =
+ output.iter().map(|(_, e)| e.uuid.clone()).collect();
+ assert_eq!(
+ output_uuids, forwardable_uuids,
+ "wrong set of forwarded events"
+ );
+
+ use std::collections::HashMap;
+ let mut partitions_by_key: HashMap<(i32, String), std::collections::HashSet<i32>> =
+ HashMap::new();
+ for (partition, envelope) in &output {
+ assert!(
+ (0..OUTPUT_PARTITIONS).contains(partition),
+ "partition {partition} out of range",
+ );
+ partitions_by_key
+ .entry((envelope.team_id, envelope.person_id.clone()))
+ .or_default()
+ .insert(*partition);
+ }
+ let pa_partitions = &partitions_by_key[&(2, "pA".to_string())];
+ assert_eq!(
+ pa_partitions.len(),
+ 1,
+ "events for (2, pA) split across partitions {pa_partitions:?}",
+ );
+ for ((team, person), partitions) in &partitions_by_key {
+ assert_eq!(
+ partitions.len(),
+ 1,
+ "({team}, {person}) split across partitions {partitions:?}",
+ );
+ }
+
+ let first = output
+ .iter()
+ .map(|(_, e)| e)
+ .find(|e| e.uuid == uuid_by_index[0].to_string())
+ .expect("first forwardable event must be present");
+ assert_eq!(first.team_id, 2);
+ assert_eq!(first.person_id, "pA");
+ assert_eq!(first.event, "$pageview");
+ assert_eq!(first.distinct_id, "did-pA");
+ assert_eq!(
+ first.properties.as_deref(),
+ Some(r#"{"$current_url":"/pricing"}"#)
+ );
+ assert_eq!(first.source_partition, 0);
+ assert_eq!(
+ first.source_offset, 0,
+ "first produced event has input offset 0"
+ );
+}
diff --git a/rust/cohort-stream-processor/Cargo.toml b/rust/cohort-stream-processor/Cargo.toml
new file mode 100644
index 000000000000..12cce1095305
--- /dev/null
+++ b/rust/cohort-stream-processor/Cargo.toml
@@ -0,0 +1,77 @@
+[package]
+name = "cohort-stream-processor"
+version = "0.1.0"
+edition = "2021"
+
+[lints]
+workspace = true
+
+[dependencies]
+anyhow = { workspace = true }
+arc-swap = { workspace = true }
+# `#[async_trait]` on the `MembershipSink` output seam, so the worker holds an
+# `Arc<dyn MembershipSink>` and tests swap in an in-process capture sink with no broker.
+async-trait = { workspace = true }
+axum = { workspace = true }
+chrono = { workspace = true }
+# Team-timezone-aware calendar-day bucket math (`stage1::bucket_tz`): `Tz` resolves
+# `posthog_team.timezone` and is `Copy`, so it rides on the hot path inside the frozen `TeamFilters`.
+chrono-tz = { workspace = true }
+common-alloc = { path = "../common/alloc" }
+common-database = { path = "../common/database" }
+common-types = { path = "../common/types" }
+# Shadow-topic output producer: `create_kafka_producer` + `send_keyed_iter_to_kafka_*`
+# and the `KafkaConfig`/`KafkaProduceError` types, shared with `cohort-event-shuffler`.
+common-kafka = { path = "../common/kafka" }
+# `SyncLivenessReporter` for the producer's rdkafka client context (the always-healthy sink, since
+# the consumer owns the liveness deadline) — mirrors the shuffler's producer.
+common-liveness = { path = "../common/liveness" }
+# Same version `rust/kafka-deduplicator` uses; lets the partition router and offset tracker
+# hold their per-partition maps behind sharded locks (no global mutex on the hot path).
+dashmap = { workspace = true }
+envconfig = { workspace = true }
+# `join_all` for routing each poll's per-partition sub-batches concurrently, so a full channel on
+# one partition can't head-of-line-block the sends to the others. Same version dedup uses.
+futures = { workspace = true }
+hogvm = { path = "../common/hogvm" }
+lifecycle = { path = "../common/lifecycle" }
+metrics = { workspace = true }
+metrics-exporter-prometheus = { workspace = true }
+# Streaming `BufWriter` and prefix-list (`list_with_delimiter`) S3 for multi-MB checkpoint files.
+object_store = { version = "0.13.0", features = ["aws"] }
+# Tarjan SCC (`tarjan_scc`) for the per-team cohort-reference cycle defense at filter freeze
+# (`filters::cohort_graph`). Pinned to the same 0.8 line as `rust/feature-flags/Cargo.toml` so the
+# workspace resolves a single copy.
+petgraph = "0.8"
+rand = { workspace = true }
+# Raw `StreamConsumer` for `cohort_stream_events`. The consume loop and manual offset commit are
+# driven directly (mirroring `rust/kafka-deduplicator`) rather than through `common-kafka`'s
+# `SingleTopicConsumer`, because the processor's per-partition `OffsetTracker` commits a
+# `TopicPartitionList` the wrapper cannot express. Same workspace version (0.37) as the sibling
+# crates, so `librdkafka` links once.
+rdkafka = { workspace = true }
+# Pinned to match `rust/kafka-deduplicator` so the workspace links a single
+# `librocksdb-sys` version (two would conflict at link time).
+rocksdb = "0.24.0"
+serde = { workspace = true }
+serde_json = { workspace = true }
+sha2 = { workspace = true }
+sqlx = { workspace = true }
+thiserror = { workspace = true }
+tokio = { workspace = true }
+# `CancellationToken` for the rebalance worker's shutdown signal (from `lifecycle::Handle`), the
+# same primitive the sibling consumers use for cooperative cancellation.
+tokio-util = { workspace = true }
+tracing = { workspace = true }
+tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
+uuid = { workspace = true }
+
+[dev-dependencies]
+# Integration tests in `tests/` build `TeamFilters` via `freeze(UTC)`, so they name `chrono_tz::UTC`
+# directly (a normal dependency is not in scope for the separate integration-test crates).
+chrono-tz = { workspace = true }
+serde_json = { workspace = true }
+tempfile = "3"
+# `test-util` enables the paused clock (`start_paused` / `tokio::time::advance`) the sweep timer
+# tests drive; resolver 2 keeps this dev-only feature out of the normal build.
+tokio = { workspace = true, features = ["test-util"] }
diff --git a/rust/cohort-stream-processor/src/cascade/decision.rs b/rust/cohort-stream-processor/src/cascade/decision.rs
new file mode 100644
index 000000000000..a8e832653b82
--- /dev/null
+++ b/rust/cohort-stream-processor/src/cascade/decision.rs
@@ -0,0 +1,211 @@
+//! Pure cascade decision logic: no Kafka, no storage, no metrics, no clock — every function takes
+//! data and returns data. The caller performs the produce and supplies `new_last_updated`.
+
+use crate::cascade::message::{CascadeDecision, CascadeMessage, DropReason};
+use crate::filters::CohortId;
+use crate::producer::{CohortMembershipChange, MembershipStatus};
+
+/// Decide whether `next` — which just flipped to `new_status` at `new_last_updated` — cascades onward.
+///
+/// Depth is checked before the chain, so a message at the cap drops as `DepthExceeded` even when
+/// `next` is also already in the chain.
+pub fn should_emit(
+ incoming: &CascadeMessage,
+ next: CohortId,
+ new_status: MembershipStatus,
+ new_last_updated: &str,
+ depth_cap: u8,
+) -> CascadeDecision {
+ if incoming.depth >= depth_cap {
+ return CascadeDecision::Drop {
+ reason: DropReason::DepthExceeded,
+ };
+ }
+ if incoming.cascade_chain.contains(&next.0) {
+ return CascadeDecision::Drop {
+ reason: DropReason::CycleDetectedRuntime,
+ };
+ }
+
+ let mut cascade_chain = incoming.cascade_chain.clone();
+ cascade_chain.push(next.0);
+ CascadeDecision::Emit {
+ outgoing: CascadeMessage {
+ change: CohortMembershipChange {
+ team_id: incoming.change.team_id,
+ cohort_id: next.0,
+ person_id: incoming.change.person_id.clone(),
+ last_updated: new_last_updated.to_string(),
+ status: new_status,
+ },
+ // Carried forward so the chain keeps one stable replay identity across hops.
+ source_offset: incoming.source_offset,
+ // depth < depth_cap <= u8::MAX after the guard above, so this cannot overflow.
+ depth: incoming.depth + 1,
+ originating_cohort_id: incoming.originating_cohort_id,
+ cascade_chain,
+ },
+ }
+}
+
+/// Build the first cascade in a chain from a just-emitted membership change: `depth = 1`, with the
+/// flipped cohort as both `originating_cohort_id` and the sole `cascade_chain` entry.
+pub fn first_cascade(change: CohortMembershipChange, source_offset: i64) -> CascadeMessage {
+ let originating_cohort_id = change.cohort_id;
+ CascadeMessage {
+ change,
+ source_offset,
+ depth: 1,
+ originating_cohort_id,
+ cascade_chain: vec![originating_cohort_id],
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const TS_IN: &str = "2026-05-26 12:34:56.789123";
+ const TS_OUT: &str = "2026-06-16 00:00:00.000000";
+
+ fn change(cohort_id: i32, status: MembershipStatus) -> CohortMembershipChange {
+ CohortMembershipChange {
+ team_id: 42,
+ cohort_id,
+ person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ last_updated: TS_IN.to_string(),
+ status,
+ }
+ }
+
+ /// An incoming cascade message at `depth` with the given `chain`.
+ fn incoming(cohort_id: i32, depth: u8, chain: Vec<i32>) -> CascadeMessage {
+ CascadeMessage {
+ change: change(cohort_id, MembershipStatus::Entered),
+ source_offset: 777,
+ depth,
+ originating_cohort_id: chain.first().copied().unwrap_or(cohort_id),
+ cascade_chain: chain,
+ }
+ }
+
+ #[test]
+ fn normal_hop_increments_depth_and_extends_the_chain_carrying_fields() {
+ let incoming = incoming(10, 1, vec![10]);
+ let decision = should_emit(&incoming, CohortId(20), MembershipStatus::Left, TS_OUT, 8);
+
+ let CascadeDecision::Emit { outgoing } = decision else {
+ panic!("expected Emit, got {decision:?}");
+ };
+ assert_eq!(outgoing.depth, 2, "depth 1 → 2");
+ assert_eq!(
+ outgoing.cascade_chain,
+ vec![10, 20],
+ "chain [10] → [10, 20]"
+ );
+ // `change` is rebuilt for `next`.
+ assert_eq!(outgoing.change.cohort_id, 20);
+ assert_eq!(outgoing.change.status, MembershipStatus::Left);
+ assert_eq!(outgoing.change.last_updated, TS_OUT);
+ // team / person / source_offset / originating carry from `incoming`.
+ assert_eq!(outgoing.change.team_id, incoming.change.team_id);
+ assert_eq!(outgoing.change.person_id, incoming.change.person_id);
+ assert_eq!(outgoing.source_offset, incoming.source_offset);
+ assert_eq!(outgoing.originating_cohort_id, 10);
+ }
+
+ #[test]
+ fn depth_one_below_the_cap_still_emits() {
+ let incoming = incoming(10, 7, vec![1, 2, 3, 4, 5, 6, 7]);
+ let decision = should_emit(
+ &incoming,
+ CohortId(99),
+ MembershipStatus::Entered,
+ TS_OUT,
+ 8,
+ );
+ let CascadeDecision::Emit { outgoing } = decision else {
+ panic!("expected Emit at depth 7, got {decision:?}");
+ };
+ assert_eq!(outgoing.depth, 8);
+ assert_eq!(outgoing.cascade_chain.len(), 8);
+ }
+
+ #[test]
+ fn depth_at_the_cap_drops_depth_exceeded() {
+ let incoming = incoming(10, 8, vec![1, 2, 3, 4, 5, 6, 7, 8]);
+ let decision = should_emit(
+ &incoming,
+ CohortId(99),
+ MembershipStatus::Entered,
+ TS_OUT,
+ 8,
+ );
+ assert_eq!(
+ decision,
+ CascadeDecision::Drop {
+ reason: DropReason::DepthExceeded,
+ },
+ );
+ }
+
+ #[test]
+ fn next_already_in_chain_drops_cycle_detected_under_the_cap() {
+ let incoming = incoming(10, 2, vec![10, 20]);
+ let decision = should_emit(
+ &incoming,
+ CohortId(20),
+ MembershipStatus::Entered,
+ TS_OUT,
+ 8,
+ );
+ assert_eq!(
+ decision,
+ CascadeDecision::Drop {
+ reason: DropReason::CycleDetectedRuntime,
+ },
+ );
+ }
+
+ #[test]
+ fn depth_is_checked_before_the_chain_when_both_would_fire() {
+ // At the cap and `next` already in the chain: depth wins.
+ let incoming = incoming(10, 8, vec![10, 20]);
+ let decision = should_emit(
+ &incoming,
+ CohortId(20),
+ MembershipStatus::Entered,
+ TS_OUT,
+ 8,
+ );
+ assert_eq!(
+ decision,
+ CascadeDecision::Drop {
+ reason: DropReason::DepthExceeded,
+ },
+ );
+ }
+
+ #[test]
+ fn first_cascade_seeds_depth_one_and_a_singleton_chain() {
+ let cascade = first_cascade(change(91204, MembershipStatus::Entered), 555);
+ assert_eq!(cascade.depth, 1);
+ assert_eq!(cascade.cascade_chain, vec![91204]);
+ assert_eq!(cascade.originating_cohort_id, 91204);
+ assert_eq!(cascade.source_offset, 555);
+ assert_eq!(cascade.change.cohort_id, 91204);
+ assert_eq!(cascade.change.status, MembershipStatus::Entered);
+ }
+
+ #[test]
+ fn first_cascade_then_one_hop_yields_depth_two_chain_of_two() {
+ let first = first_cascade(change(10, MembershipStatus::Entered), 1);
+ let decision = should_emit(&first, CohortId(20), MembershipStatus::Entered, TS_OUT, 8);
+ let CascadeDecision::Emit { outgoing } = decision else {
+ panic!("expected Emit, got {decision:?}");
+ };
+ assert_eq!(outgoing.depth, 2);
+ assert_eq!(outgoing.cascade_chain, vec![10, 20]);
+ assert_eq!(outgoing.originating_cohort_id, 10);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/cascade/message.rs b/rust/cohort-stream-processor/src/cascade/message.rs
new file mode 100644
index 000000000000..f56f135386d0
--- /dev/null
+++ b/rust/cohort-stream-processor/src/cascade/message.rs
@@ -0,0 +1,142 @@
+//! Cascade wire types for the `cohort_cascade_events` topic.
+//!
+//! [`CascadeMessage`] embeds [`CohortMembershipChange`] via `#[serde(flatten)]` so the inner `change`
+//! is produced verbatim to `cohort_membership_changed` while the full message carries the extra
+//! cascade fields — one source of truth for the shared keys.
+
+use serde::{Deserialize, Serialize};
+
+use crate::producer::CohortMembershipChange;
+
+/// One `cohort_cascade_events` message: a membership change plus the depth and chain state used to
+/// bound and cycle-check cascade re-evaluation.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CascadeMessage {
+ /// Produced verbatim to `cohort_membership_changed`; flattened into this message's JSON.
+ #[serde(flatten)]
+ pub change: CohortMembershipChange,
+ /// Offset of the triggering input message, carried for replay idempotence. The partition is
+ /// implicit in the cascade consumer's assignment.
+ pub source_offset: i64,
+ /// Hops since the originating flip; `1` for the first cascade, capped at `cohort_cascade_depth_cap`.
+ pub depth: u8,
+ /// The cohort that initiated this chain; constant across every hop.
+ pub originating_cohort_id: i32,
+ /// Ordered cohort ids visited in this chain; a hop whose cohort id is already present is dropped
+ /// as a cycle.
+ pub cascade_chain: Vec<i32>,
+}
+
+/// The outcome of a per-hop cascade decision.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum CascadeDecision {
+ /// Produce `outgoing` to `cohort_cascade_events` and continue the chain.
+ Emit { outgoing: CascadeMessage },
+ /// Stop the chain here without cascading further.
+ Drop { reason: DropReason },
+}
+
+/// Why a cascade hop was dropped.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DropReason {
+ /// `incoming.depth >= depth_cap`.
+ DepthExceeded,
+ /// The next cohort id is already in `cascade_chain`.
+ CycleDetectedRuntime,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::{json, Value};
+
+ use crate::producer::MembershipStatus;
+
+ const TS: &str = "2026-05-26 12:34:56.789123";
+
+ fn message() -> CascadeMessage {
+ CascadeMessage {
+ change: CohortMembershipChange {
+ team_id: 42,
+ cohort_id: 91204,
+ person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ last_updated: TS.to_string(),
+ status: MembershipStatus::Entered,
+ },
+ source_offset: 12345,
+ depth: 2,
+ originating_cohort_id: 91204,
+ cascade_chain: vec![91204, 91205],
+ }
+ }
+
+ #[test]
+ fn round_trips_through_json() {
+ let msg = message();
+ let encoded = serde_json::to_string(&msg).unwrap();
+ let decoded: CascadeMessage = serde_json::from_str(&encoded).unwrap();
+ assert_eq!(decoded, msg);
+ }
+
+ #[test]
+ fn flattens_to_exactly_the_nine_keys() {
+ let value = serde_json::to_value(message()).unwrap();
+ let object = value.as_object().unwrap();
+
+ let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
+ keys.sort_unstable();
+ assert_eq!(
+ keys,
+ vec![
+ "cascade_chain",
+ "cohort_id",
+ "depth",
+ "last_updated",
+ "originating_cohort_id",
+ "person_id",
+ "source_offset",
+ "status",
+ "team_id",
+ ],
+ );
+ }
+
+ #[test]
+ fn status_and_chain_serialize_in_their_wire_shapes() {
+ let value = serde_json::to_value(message()).unwrap();
+ let object = value.as_object().unwrap();
+ assert_eq!(object["status"], json!("entered"));
+ assert_eq!(object["cascade_chain"], json!([91204, 91205]));
+ assert!(object["cascade_chain"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .all(Value::is_i64));
+ }
+
+ #[test]
+ fn left_status_flattens_to_snake_case() {
+ let mut msg = message();
+ msg.change.status = MembershipStatus::Left;
+ let value = serde_json::to_value(msg).unwrap();
+ assert_eq!(value["status"], json!("left"));
+ }
+
+ #[test]
+ fn the_external_five_keys_are_byte_identical_to_serializing_change_alone() {
+ // The external keys embedded in the cascade message must equal serializing `change` alone, so
+ // the same struct can feed both produces.
+ let msg = message();
+ let change_only = serde_json::to_value(&msg.change).unwrap();
+ let full = serde_json::to_value(&msg).unwrap();
+ let full_object = full.as_object().unwrap();
+
+ let extracted: serde_json::Map<String, Value> = change_only
+ .as_object()
+ .unwrap()
+ .keys()
+ .map(|key| (key.clone(), full_object[key].clone()))
+ .collect();
+ assert_eq!(Value::Object(extracted), change_only);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/cascade/mod.rs b/rust/cohort-stream-processor/src/cascade/mod.rs
new file mode 100644
index 000000000000..605398affb89
--- /dev/null
+++ b/rust/cohort-stream-processor/src/cascade/mod.rs
@@ -0,0 +1,11 @@
+//! Pure decision logic for cohort-of-cohort cascade re-evaluation.
+//!
+//! [`should_emit`] and [`first_cascade`] are pure functions over [`CascadeMessage`]; the module
+//! depends only on the data types [`CohortId`](crate::filters::CohortId) and
+//! [`CohortMembershipChange`](crate::producer::CohortMembershipChange), never on I/O or Stage 2 state.
+
+pub mod decision;
+pub mod message;
+
+pub use decision::{first_cascade, should_emit};
+pub use message::{CascadeDecision, CascadeMessage, DropReason};
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
new file mode 100644
index 000000000000..342c1bf9ae97
--- /dev/null
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -0,0 +1,1384 @@
+//! Service configuration, loaded from environment variables via `envconfig`.
+
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::ensure;
+use common_database::PoolConfig;
+use common_kafka::config::KafkaConfig;
+use common_types::cohort::TeamAllowlist;
+use envconfig::Envconfig;
+use rdkafka::ClientConfig;
+use tracing::warn;
+
+use crate::store::durability::DurabilityConfig;
+use crate::store::StoreConfig;
+use crate::workers::{CascadeConfig, TransferRetryPolicy};
+
+const POOL_NAME: &str = "posthog_cohort";
+
+#[derive(Envconfig, Clone, Debug)]
+pub struct Config {
+ /// Host for the observability HTTP server (`/_health`, `/_ready`, `/metrics`).
+ #[envconfig(default = "0.0.0.0")]
+ pub bind_host: String,
+
+ /// Port for the observability HTTP server.
+ #[envconfig(default = "3323")]
+ pub bind_port: u16,
+
+ /// Install the Prometheus recorder and expose `/metrics`.
+ #[envconfig(default = "true")]
+ pub export_prometheus: bool,
+
+ /// DSN for the main PostHog database that owns `posthog_cohort`.
+ #[envconfig(default = "postgres://posthog:posthog@localhost:5432/posthog")]
+ pub database_url: String,
+
+ #[envconfig(default = "1")]
+ pub min_pg_connections: u32,
+
+ #[envconfig(default = "5")]
+ pub max_pg_connections: u32,
+
+ #[envconfig(default = "10")]
+ pub pg_acquire_timeout_secs: u64,
+
+ /// Statement timeout for the catalog SELECT (ms). `0` → database default.
+ #[envconfig(default = "5000")]
+ pub pg_statement_timeout_ms: u64,
+
+ #[envconfig(default = "300")]
+ pub filter_catalog_refresh_secs: u64,
+
+ #[envconfig(default = "60")]
+ pub filter_catalog_refresh_jitter_secs: u64,
+
+ /// Teams the filter catalog is scoped to. Set `all` to disable the gate. See [`TeamAllowlist`].
+ #[envconfig(from = "REALTIME_COHORT_TEAM_ALLOWLIST", default = "2")]
+ pub team_allowlist: TeamAllowlist,
+
+ /// Bounded buffer (in sub-batches) per per-partition worker channel.
+ /// Routing to a partition this far behind blocks rather than growing memory unbounded.
+ #[envconfig(default = "1024")]
+ pub partition_channel_buffer: usize,
+
+ #[envconfig(default = "localhost:9092")]
+ pub kafka_hosts: String,
+
+ #[envconfig(default = "false")]
+ pub kafka_tls: bool,
+
+ #[envconfig(default = "")]
+ pub kafka_client_id: String,
+
+ #[envconfig(default = "")]
+ pub kafka_client_rack: String,
+
+ /// The hot-path input topic.
+ #[envconfig(default = "cohort_stream_events")]
+ pub cohort_stream_events_topic: String,
+
+ #[envconfig(default = "cohort-stream-processor")]
+ pub kafka_consumer_group: String,
+
+ /// Start at the tail, not the topic's retention.
+ #[envconfig(default = "latest")]
+ pub kafka_consumer_offset_reset: String,
+
+ /// How long the broker waits for heartbeats before declaring this consumer dead. With static
+ /// membership, a restart within this window reclaims partitions with no rebalance.
+ #[envconfig(default = "60000")]
+ pub kafka_session_timeout_ms: u64,
+
+ /// The person-merge trigger topic, keyed by `hash(team_id, old_person_uuid)` so a merge lands on
+ /// P_old's worker.
+ #[envconfig(default = "person_merge_events")]
+ pub person_merge_events_topic: String,
+
+ /// The internal state-transfer topic, keyed by `hash(team_id, new_person_uuid)` so a packaged
+ /// drain lands on P_new's worker. Must be co-partitioned with `cohort_stream_events`.
+ #[envconfig(default = "cohort_merge_state_transfer")]
+ pub cohort_merge_state_transfer_topic: String,
+
+ /// Group for the `person_merge_events` follower — separate so drain-path lag is observable.
+ #[envconfig(default = "cohort-stream-merges")]
+ pub kafka_merge_consumer_group: String,
+
+ /// Group for the `cohort_merge_state_transfer` follower.
+ #[envconfig(default = "cohort-stream-merge-apply")]
+ pub kafka_merge_apply_consumer_group: String,
+
+ /// Inline retries after the first transfer-produce attempt. The default budget
+ /// (5 x 0.5/1/2/4/8 s) keeps a blocked worker inside the liveness and graceful-shutdown
+ /// windows; exhaustion leaves the transfer staged for the periodic redrive.
+ #[envconfig(default = "5")]
+ pub merge_transfer_max_retries: u32,
+
+ /// First retry backoff (ms); doubles per retry.
+ #[envconfig(default = "500")]
+ pub merge_transfer_retry_base_ms: u64,
+
+ /// Backoff ceiling (ms).
+ #[envconfig(default = "8000")]
+ pub merge_transfer_retry_cap_ms: u64,
+
+ /// `message.timeout.ms` for the transfer producer alone — much shorter than the shared 20 s so a
+ /// single produce attempt fast-fails against a black-hole broker instead of stalling a worker.
+ /// The inline retry loop wraps `merge_transfer_max_retries + 1` attempts; the budget only holds
+ /// inside the 30 s graceful-shutdown window if each attempt itself fast-fails. See
+ /// `build_transfer_kafka_config` and the budget arithmetic in `workers::merge_path`.
+ #[envconfig(default = "2000")]
+ pub merge_transfer_message_timeout_ms: u32,
+
+ /// How often the redrive scans `cf_pending_transfers` and re-produces staged transfers whose
+ /// inline retry budget was exhausted.
+ #[envconfig(default = "60000")]
+ pub merge_redrive_interval_ms: u64,
+
+ // STANDING COUPLING: these floors are derived from the Kafka topic `retention.ms` values
+ // (`person_merge_events`/`cohort_merge_state_transfer` = 7d, `cohort_stream_events` = 24h,
+ // `clickhouse_events_json` = 7d). If any of those `retention.ms` values change, these knobs
+ // MUST follow — a marker evicted before its source topic's retention lapses re-opens the
+ // replay-dedup window it exists to close. `cf_pending_transfers` is NEVER GC'd here.
+ /// Retention floor for both merge marker CFs (`cf_merge_drains_applied`, `cf_merge_applied`). A
+ /// marker is GC'd once its `drained_at_ms` / `applied_at_ms` is older than `now − this`. Default
+ /// 8d = 7d merge-topic retention + 1d safety: a marker must outlive every replay of the
+ /// 7d-retention `person_merge_events` / `cohort_merge_state_transfer` topics.
+ #[envconfig(default = "691200000")]
+ pub merge_marker_retention_ms: u64,
+
+ /// Retention floor for `cf_merge_tombstones`. A tombstone is GC'd once its `merged_at_ms` is
+ /// older than `now − this`. Default 9d = `clickhouse_events_json` 7d + `cohort_stream_events`
+ /// 24h + 1d safety: a tombstone must outlive every straggler event the redirect closes.
+ #[envconfig(default = "777600000")]
+ pub merge_tombstone_retention_ms: u64,
+
+ /// How often the merge-CF GC sweep fires. Default 1h.
+ #[envconfig(default = "3600000")]
+ pub merge_gc_interval_ms: u64,
+
+ /// Max keys scanned (and at most deleted) per CF, per partition, per GC tick. Bounds the GC's
+ /// per-tick work; the per-CF resume cursor continues where the last tick stopped. Default 10k —
+ /// at the prod merge rate (~16k markers/day/partition) that is ~15× headroom over the 1h cadence.
+ #[envconfig(default = "10000")]
+ pub merge_gc_scan_limit: usize,
+
+ /// Whether the `cf_stage2` orphan GC pass runs on each merge-GC tick — reclaims composed-membership
+ /// rows whose cohort has left the composable set. Default-on kill-switch; reuses `merge_gc_scan_limit`
+ /// as the page cap.
+ #[envconfig(from = "STAGE2_ORPHAN_GC_ENABLED", default = "true")]
+ pub stage2_orphan_gc_enabled: bool,
+
+ /// Max cascade hops before an outgoing cascade is dropped (`incoming.depth >= this`). Default 8.
+ #[envconfig(default = "8")]
+ pub cohort_cascade_depth_cap: u8,
+
+ /// Max referrer re-evaluations per upstream flip. Default 1000.
+ #[envconfig(default = "1000")]
+ pub cohort_cascade_fanout_cap: usize,
+
+ /// Promote resolvable, cycle-free cohort-of-cohort cohorts to composition. Default off:
+ /// ref-bearing cohorts stay excluded.
+ #[envconfig(from = "COHORT_CASCADE_ENABLED", default = "false")]
+ pub cohort_cascade_enabled: bool,
+
+ /// The internal cascade topic, keyed by `hash(team_id, person_id)` so a flip lands on the worker
+ /// owning that person's `cf_stage2`. Must be co-partitioned with `cohort_stream_events`.
+ #[envconfig(default = "cohort_cascade_events")]
+ pub cohort_cascade_events_topic: String,
+
+ /// Group for the `cohort_cascade_events` follower — separate so cascade-path lag is observable.
+ #[envconfig(default = "cohort-stream-cascade")]
+ pub kafka_cascade_consumer_group: String,
+
+ /// Stable per-pod identity for `group.instance.id` + `client.id`, enabling static membership.
+ /// Read from `POD_NAME`, else `HOSTNAME`. Absent means no static membership.
+ #[envconfig(from = "POD_NAME")]
+ pub pod_name: Option<String>,
+
+ #[envconfig(from = "HOSTNAME")]
+ pub pod_hostname: Option<String>,
+
+ /// The shadow output topic for membership changes.
+ #[envconfig(default = "cohort_membership_changed_shadow")]
+ pub cohort_membership_changed_topic: String,
+
+ /// `murmur2_random` co-partitions a `person_id` key identically to the Node/Python producers.
+ #[envconfig(default = "murmur2_random")]
+ pub kafka_producer_partitioner: String,
+
+ /// Partition count of the co-partitioned cohort topics. Production is 64; test lanes lower it
+ /// (e.g. 8) to fit many merge lanes on a single-node broker. The merge protocol's partition
+ /// arithmetic must use this value, not a literal.
+ #[envconfig(default = "64")]
+ pub cohort_partition_count: u32,
+
+ #[envconfig(default = "none")]
+ pub kafka_compression_codec: String,
+
+ /// Max events pulled per consume-route cycle.
+ #[envconfig(default = "1000")]
+ pub recv_batch_size: usize,
+
+ /// Max wait before a partial batch is routed.
+ #[envconfig(default = "500")]
+ pub recv_batch_timeout_ms: u64,
+
+ /// How often processed offsets are committed back to Kafka.
+ #[envconfig(default = "5000")]
+ pub offset_commit_interval_ms: u64,
+
+ /// How often the sweep fires to evict state whose eviction deadline has passed.
+ #[envconfig(default = "30000")]
+ pub sweep_interval_ms: u64,
+
+ /// Grace period added to every eviction deadline before the sweep acts. The sweep evicts a key
+ /// only once `deadline + safety_margin < now`, absorbing consumer-lag spikes.
+ #[envconfig(default = "300000")]
+ pub sweep_safety_margin_ms: u64,
+
+ /// On-disk path for the per-process RocksDB state store.
+ #[envconfig(default = "cohort-store")]
+ pub store_path: String,
+
+ /// Destroy any existing store at `store_path` before opening, so re-acquiring a partition never
+ /// serves stale state left by a previous owner.
+ #[envconfig(default = "true")]
+ pub wipe_store_on_start: bool,
+
+ /// When on, reopen the existing store on restart instead of wiping it: recent Stage 1 state is
+ /// restored and only the gap since the last committed offset is replayed (idempotent via per-key
+ /// `AppliedOffsets`). Refused alongside `cohort_cascade_enabled` — merge column families are not
+ /// restored yet. See [`Self::effective_wipe_on_start`].
+ #[envconfig(from = "DURABLE_RESTORE_ENABLED", default = "false")]
+ pub durable_restore_enabled: bool,
+
+ /// Operator assertion that this is a single-pod, static-membership shadow deploy. Default off.
+ ///
+ /// Required to run `DURABLE_RESTORE_ENABLED` together with `COHORT_CASCADE_ENABLED`: a single pod
+ /// with static membership reclaims its own partitions on a restart and never triggers a live
+ /// rebalance. `pod_identity()` cannot gate this because it is set on every k8s pod (single or
+ /// multi), so the single-vs-multi assertion needs its own flag.
+ #[envconfig(from = "DURABLE_RESTORE_SINGLE_POD", default = "false")]
+ pub durable_restore_single_pod: bool,
+
+ /// Master gate for the whole-DB checkpoint + S3 backup/restore layer. Default off.
+ #[envconfig(from = "CHECKPOINT_ENABLED", default = "false")]
+ pub checkpoint_enabled: bool,
+
+ /// How often a local PVC checkpoint is taken (ms).
+ #[envconfig(default = "300000")]
+ pub checkpoint_interval_ms: u64,
+
+ /// How often the local checkpoint is also uploaded to S3 (ms). The upload rides every Nth local
+ /// tick (`N = max(1, this / checkpoint_interval_ms)`), so the checkpoint is taken once and
+ /// conditionally uploaded — never two racing `create_checkpoint`s.
+ #[envconfig(default = "900000")]
+ pub checkpoint_s3_upload_interval_ms: u64,
+
+ /// Base directory for local checkpoints. Must be a subtree separate from `store_path` on the same
+ /// filesystem (RocksDB refuses to checkpoint into its own directory and hard-links SSTs).
+ #[envconfig(default = "cohort-checkpoints")]
+ pub checkpoint_local_dir: String,
+
+ /// S3 bucket for checkpoint uploads. Empty (default) makes the uploader unavailable, so uploads
+ /// no-op.
+ #[envconfig(default = "")]
+ pub checkpoint_s3_bucket: String,
+
+ /// S3 key prefix (bucket namespace) under which checkpoint attempts are stored.
+ #[envconfig(default = "cohort-stream-checkpoints")]
+ pub checkpoint_s3_prefix: String,
+
+ /// AWS region for S3 (None → SDK default / IRSA-provided region).
+ #[envconfig(from = "CHECKPOINT_S3_REGION")]
+ pub checkpoint_s3_region: Option<String>,
+
+ /// S3 endpoint override for S3-compatible stores (MinIO/SeaweedFS in dev). None → real AWS S3.
+ #[envconfig(from = "CHECKPOINT_S3_ENDPOINT")]
+ pub checkpoint_s3_endpoint: Option<String>,
+
+ /// S3 access key id for local dev without an IAM role. None → IRSA → env → default chain.
+ #[envconfig(from = "CHECKPOINT_S3_ACCESS_KEY_ID")]
+ pub checkpoint_s3_access_key_id: Option<String>,
+
+ /// S3 secret access key for local dev without an IAM role.
+ #[envconfig(from = "CHECKPOINT_S3_SECRET_ACCESS_KEY")]
+ pub checkpoint_s3_secret_access_key: Option<String>,
+
+ /// Force path-style S3 URLs (required for MinIO/SeaweedFS).
+ #[envconfig(default = "false")]
+ pub checkpoint_s3_force_path_style: bool,
+
+ /// Max concurrent S3 file uploads during a checkpoint export.
+ #[envconfig(default = "40")]
+ pub checkpoint_max_concurrent_uploads: usize,
+
+ /// Max concurrent S3 file downloads during a checkpoint import.
+ #[envconfig(default = "40")]
+ pub checkpoint_max_concurrent_downloads: usize,
+
+ /// Max upload futures actively polled per export (bounds memory: each holds read + write
+ /// buffers).
+ #[envconfig(default = "40")]
+ pub checkpoint_max_upload_buffers: usize,
+
+ /// Retries per S3 operation before giving up.
+ #[envconfig(default = "3")]
+ pub checkpoint_s3_max_retries: usize,
+
+ /// Total timeout for one S3 operation including retries (secs).
+ #[envconfig(default = "120")]
+ pub checkpoint_s3_operation_timeout_secs: u64,
+
+ /// Timeout for a single S3 operation attempt (secs).
+ #[envconfig(default = "20")]
+ pub checkpoint_s3_attempt_timeout_secs: u64,
+
+ /// Max age of a local PVC checkpoint before it is distrusted on restore and the service falls
+ /// back to S3 (secs). Tighter than the S3 listing window: if a pod was down longer than this,
+ /// another pod likely consumed the partitions and the local copy is behind.
+ #[envconfig(default = "7200")]
+ pub checkpoint_local_max_staleness_secs: u64,
+
+ /// Hours prior to now the S3 importer searches for checkpoint attempts in a PVC-lost recovery.
+ #[envconfig(default = "24")]
+ pub checkpoint_import_window_hours: u32,
+
+ /// Historical S3 checkpoint attempts to try (newest first) before giving up on import.
+ #[envconfig(default = "10")]
+ pub checkpoint_import_attempt_depth: usize,
+
+ /// Max time for a complete S3 checkpoint import — list + metadata + all files + fallbacks (secs).
+ /// Kept under `max.poll.interval.ms` so a long restore does not get the consumer kicked.
+ #[envconfig(default = "240")]
+ pub checkpoint_import_timeout_secs: u64,
+}
+
+impl Config {
+ pub fn bind_address(&self) -> String {
+ format!("{}:{}", self.bind_host, self.bind_port)
+ }
+
+ pub fn filter_catalog_refresh_interval(&self) -> Duration {
+ Duration::from_secs(self.filter_catalog_refresh_secs)
+ }
+
+ pub fn filter_catalog_refresh_jitter(&self) -> Duration {
+ Duration::from_secs(self.filter_catalog_refresh_jitter_secs)
+ }
+
+ fn pg_statement_timeout(&self) -> Option<u64> {
+ (self.pg_statement_timeout_ms != 0).then_some(self.pg_statement_timeout_ms)
+ }
+
+ pub fn pool_config(&self) -> PoolConfig {
+ PoolConfig {
+ min_connections: self.min_pg_connections,
+ max_connections: self.max_pg_connections,
+ acquire_timeout: Duration::from_secs(self.pg_acquire_timeout_secs),
+ idle_timeout: Some(Duration::from_secs(300)),
+ test_before_acquire: true,
+ statement_timeout_ms: self.pg_statement_timeout(),
+ pool_name: Some(POOL_NAME.to_string()),
+ }
+ }
+
+ pub fn recv_batch_timeout(&self) -> Duration {
+ Duration::from_millis(self.recv_batch_timeout_ms)
+ }
+
+ pub fn offset_commit_interval(&self) -> Duration {
+ Duration::from_millis(self.offset_commit_interval_ms)
+ }
+
+ pub fn sweep_interval(&self) -> Duration {
+ Duration::from_millis(self.sweep_interval_ms)
+ }
+
+ pub fn sweep_safety_margin(&self) -> Duration {
+ Duration::from_millis(self.sweep_safety_margin_ms)
+ }
+
+ pub fn transfer_retry_policy(&self) -> TransferRetryPolicy {
+ TransferRetryPolicy {
+ max_retries: self.merge_transfer_max_retries,
+ base: Duration::from_millis(self.merge_transfer_retry_base_ms),
+ cap: Duration::from_millis(self.merge_transfer_retry_cap_ms),
+ }
+ }
+
+ pub fn merge_redrive_interval(&self) -> Duration {
+ Duration::from_millis(self.merge_redrive_interval_ms)
+ }
+
+ pub fn cascade_config(&self) -> CascadeConfig {
+ CascadeConfig {
+ enabled: self.cohort_cascade_enabled,
+ depth_cap: self.cohort_cascade_depth_cap,
+ fanout_cap: self.cohort_cascade_fanout_cap,
+ }
+ }
+
+ pub fn merge_gc_interval(&self) -> Duration {
+ Duration::from_millis(self.merge_gc_interval_ms)
+ }
+
+ pub fn checkpoint_interval(&self) -> Duration {
+ Duration::from_millis(self.checkpoint_interval_ms)
+ }
+
+ pub fn checkpoint_s3_upload_interval(&self) -> Duration {
+ Duration::from_millis(self.checkpoint_s3_upload_interval_ms)
+ }
+
+ pub fn checkpoint_local_max_staleness(&self) -> Duration {
+ Duration::from_secs(self.checkpoint_local_max_staleness_secs)
+ }
+
+ pub fn durability_config(&self) -> DurabilityConfig {
+ DurabilityConfig {
+ local_checkpoint_dir: self.checkpoint_local_dir.clone(),
+ s3_bucket: self.checkpoint_s3_bucket.clone(),
+ s3_key_prefix: self.checkpoint_s3_prefix.clone(),
+ aws_region: self.checkpoint_s3_region.clone(),
+ s3_endpoint: self.checkpoint_s3_endpoint.clone(),
+ s3_access_key_id: self.checkpoint_s3_access_key_id.clone(),
+ s3_secret_access_key: self.checkpoint_s3_secret_access_key.clone(),
+ s3_force_path_style: self.checkpoint_s3_force_path_style,
+ checkpoint_import_window_hours: self.checkpoint_import_window_hours,
+ s3_operation_timeout: Duration::from_secs(self.checkpoint_s3_operation_timeout_secs),
+ s3_attempt_timeout: Duration::from_secs(self.checkpoint_s3_attempt_timeout_secs),
+ s3_max_retries: self.checkpoint_s3_max_retries,
+ checkpoint_import_attempt_depth: self.checkpoint_import_attempt_depth,
+ max_concurrent_checkpoint_file_downloads: self.checkpoint_max_concurrent_downloads,
+ max_concurrent_checkpoint_file_uploads: self.checkpoint_max_concurrent_uploads,
+ max_upload_buffers: self.checkpoint_max_upload_buffers,
+ checkpoint_import_timeout: Duration::from_secs(self.checkpoint_import_timeout_secs),
+ local_checkpoint_max_staleness: self.checkpoint_local_max_staleness(),
+ }
+ }
+
+ /// Refuse unsafe durability startup combinations. Pure (no I/O), so unit-testable without a broker.
+ ///
+ /// Guards:
+ /// - `checkpoint_enabled` requires `durable_restore_enabled`: without it the restored DB is wiped
+ /// on open, silently discarding the restore.
+ /// - `durable_restore_enabled` + `cohort_cascade_enabled` requires `durable_restore_single_pod`
+ /// and a pod identity: `pod_identity()` alone is not a single-pod signal (set on every k8s pod).
+ pub fn validate_durability_startup(&self) -> anyhow::Result<()> {
+ ensure!(
+ !self.checkpoint_enabled || self.durable_restore_enabled,
+ "CHECKPOINT_ENABLED requires DURABLE_RESTORE_ENABLED: restoring a checkpoint without \
+ reopen-live is meaningless.",
+ );
+
+ if self.durable_restore_enabled && self.cohort_cascade_enabled {
+ let single_pod_static =
+ self.durable_restore_single_pod && self.pod_identity().is_some();
+ ensure!(
+ single_pod_static,
+ "DURABLE_RESTORE_ENABLED=true is unsafe with COHORT_CASCADE_ENABLED=true: merge \
+ column families are not restored yet. Disable one of them, or set \
+ DURABLE_RESTORE_SINGLE_POD=true on a single-pod static-membership (POD_NAME/HOSTNAME \
+ set) shadow deploy.",
+ );
+ warn!(
+ durable_restore_single_pod = self.durable_restore_single_pod,
+ pod_identity = self.pod_identity().unwrap_or("<none>"),
+ "DURABLE_RESTORE_ENABLED + COHORT_CASCADE_ENABLED allowed on a single-pod \
+ static-membership shadow. RESIDUALS deferred to Slice 3: multi-pod rebalance \
+ F3-on-revoke and the post-join↔delete REVOKE race are NOT covered (single-pod \
+ membership sidesteps them); merge column-family *content* resume after an S3 restore \
+ is validated only on this shadow, NOT production multi-pod merge durability.",
+ );
+ }
+
+ Ok(())
+ }
+
+ /// Whether to wipe the store on start, folding in the durable-restore gate: keep the live store
+ /// only when restore is on and one already exists on disk. Touches the filesystem (`.exists()`) —
+ /// a one-shot decision evaluated once at store open.
+ pub fn effective_wipe_on_start(&self) -> bool {
+ let db_dir_exists = PathBuf::from(&self.store_path).exists();
+ self.wipe_store_on_start && !(self.durable_restore_enabled && db_dir_exists)
+ }
+
+ pub fn store_config(&self) -> StoreConfig {
+ StoreConfig {
+ path: PathBuf::from(&self.store_path),
+ wipe_on_start: self.effective_wipe_on_start(),
+ ..StoreConfig::default()
+ }
+ }
+
+ /// Stable per-pod identity for static group membership, `POD_NAME` preferred over `HOSTNAME`.
+ /// `None` leaves static membership off.
+ pub fn pod_identity(&self) -> Option<&str> {
+ [self.pod_name.as_deref(), self.pod_hostname.as_deref()]
+ .into_iter()
+ .flatten()
+ .find(|id| !id.is_empty())
+ }
+
+ /// Build the `rdkafka` client config for the `cohort_stream_events` group consumer.
+ ///
+ /// Auto-commit and auto-offset-store are off: the consume loop marks offsets only after a
+ /// sub-batch is routed and produced. `cooperative-sticky` + static membership ensure a
+ /// membership change revokes only the partitions that move.
+ pub fn consumer_client_config(&self) -> ClientConfig {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", &self.kafka_hosts)
+ .set("group.id", &self.kafka_consumer_group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", &self.kafka_consumer_offset_reset)
+ .set("partition.assignment.strategy", "cooperative-sticky")
+ .set("socket.timeout.ms", "10000")
+ .set(
+ "session.timeout.ms",
+ self.kafka_session_timeout_ms.to_string(),
+ )
+ .set("heartbeat.interval.ms", "5000")
+ .set("max.poll.interval.ms", "300000");
+
+ // Static membership; an explicit `kafka_client_id` overrides `client.id` below.
+ if let Some(id) = self.pod_identity() {
+ config.set("group.instance.id", id).set("client.id", id);
+ }
+ if !self.kafka_client_id.is_empty() {
+ config.set("client.id", &self.kafka_client_id);
+ }
+ if !self.kafka_client_rack.is_empty() {
+ config.set("client.rack", &self.kafka_client_rack);
+ }
+ if self.kafka_tls {
+ config
+ .set("security.protocol", "ssl")
+ .set("enable.ssl.certificate.verification", "false");
+ }
+ config
+ }
+
+ /// Build the `rdkafka` client config for a merge-protocol follower consumer.
+ ///
+ /// Followers never `subscribe()` — the events group's rebalance mirrors assignments onto them —
+ /// so there is no assignment strategy and no static membership; `group.id` exists only so
+ /// commits land on an observable group. `auto.offset.reset` is hard-coded to `earliest`: a
+ /// never-subscribing group is `Empty` to the broker, so its committed offsets are pruned after
+ /// `offsets.retention.minutes`, and a tail reset after pruning would silently skip the merge
+ /// backlog.
+ pub fn follower_client_config(&self, group: &str) -> ClientConfig {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", &self.kafka_hosts)
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "earliest")
+ .set("socket.timeout.ms", "10000");
+
+ // `client.id` for observability only; no `group.instance.id` (no membership to make static).
+ if let Some(id) = self.pod_identity() {
+ config.set("client.id", id);
+ }
+ if !self.kafka_client_id.is_empty() {
+ config.set("client.id", &self.kafka_client_id);
+ }
+ if !self.kafka_client_rack.is_empty() {
+ config.set("client.rack", &self.kafka_client_rack);
+ }
+ if self.kafka_tls {
+ config
+ .set("security.protocol", "ssl")
+ .set("enable.ssl.certificate.verification", "false");
+ }
+ config
+ }
+
+ pub fn build_kafka_config(&self) -> KafkaConfig {
+ KafkaConfig {
+ kafka_hosts: self.kafka_hosts.clone(),
+ kafka_tls: self.kafka_tls,
+ kafka_client_rack: self.kafka_client_rack.clone(),
+ kafka_client_id: self.kafka_client_id.clone(),
+ kafka_compression_codec: self.kafka_compression_codec.clone(),
+ kafka_producer_partitioner: Some(self.kafka_producer_partitioner.clone()),
+ kafka_producer_linger_ms: 20,
+ kafka_producer_queue_mib: 400,
+ kafka_producer_queue_messages: 10_000_000,
+ kafka_message_timeout_ms: 20_000,
+ kafka_producer_batch_size: None,
+ kafka_producer_batch_num_messages: None,
+ kafka_producer_enable_idempotence: None,
+ kafka_producer_max_in_flight_requests_per_connection: None,
+ kafka_producer_topic_metadata_refresh_interval_ms: None,
+ kafka_producer_message_max_bytes: None,
+ kafka_producer_sticky_partitioning_linger_ms: None,
+ }
+ }
+
+ /// Producer config for the merge state-transfer sink: the shared config with a shorter
+ /// `message.timeout.ms`. The transfer produce runs inline on a partition worker under a bounded
+ /// retry loop, so a long per-attempt timeout multiplies into a worst-case worker hold that blows
+ /// the 30 s graceful-shutdown window (see the budget arithmetic in `workers::merge_path`).
+ pub fn build_transfer_kafka_config(&self) -> KafkaConfig {
+ KafkaConfig {
+ kafka_message_timeout_ms: self.merge_transfer_message_timeout_ms,
+ ..self.build_kafka_config()
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn test_config() -> Config {
+ Config {
+ bind_host: "0.0.0.0".to_string(),
+ bind_port: 3323,
+ export_prometheus: true,
+ database_url: "postgres://posthog:posthog@localhost:5432/posthog".to_string(),
+ min_pg_connections: 1,
+ max_pg_connections: 5,
+ pg_acquire_timeout_secs: 10,
+ pg_statement_timeout_ms: 5000,
+ filter_catalog_refresh_secs: 300,
+ filter_catalog_refresh_jitter_secs: 60,
+ team_allowlist: TeamAllowlist::All,
+ partition_channel_buffer: 1024,
+ kafka_hosts: "localhost:9092".to_string(),
+ kafka_tls: false,
+ kafka_client_id: String::new(),
+ kafka_client_rack: String::new(),
+ cohort_stream_events_topic: "cohort_stream_events".to_string(),
+ kafka_consumer_group: "cohort-stream-processor".to_string(),
+ kafka_consumer_offset_reset: "latest".to_string(),
+ person_merge_events_topic: "person_merge_events".to_string(),
+ cohort_merge_state_transfer_topic: "cohort_merge_state_transfer".to_string(),
+ kafka_merge_consumer_group: "cohort-stream-merges".to_string(),
+ kafka_merge_apply_consumer_group: "cohort-stream-merge-apply".to_string(),
+ merge_transfer_max_retries: 5,
+ merge_transfer_retry_base_ms: 500,
+ merge_transfer_retry_cap_ms: 8000,
+ merge_transfer_message_timeout_ms: 2000,
+ merge_redrive_interval_ms: 60_000,
+ merge_marker_retention_ms: 691_200_000,
+ merge_tombstone_retention_ms: 777_600_000,
+ merge_gc_interval_ms: 3_600_000,
+ merge_gc_scan_limit: 10_000,
+ stage2_orphan_gc_enabled: true,
+ cohort_cascade_depth_cap: 8,
+ cohort_cascade_fanout_cap: 1000,
+ cohort_cascade_enabled: false,
+ cohort_cascade_events_topic: "cohort_cascade_events".to_string(),
+ kafka_cascade_consumer_group: "cohort-stream-cascade".to_string(),
+ kafka_session_timeout_ms: 60000,
+ pod_name: None,
+ pod_hostname: None,
+ cohort_membership_changed_topic: "cohort_membership_changed_shadow".to_string(),
+ kafka_producer_partitioner: "murmur2_random".to_string(),
+ cohort_partition_count: 64,
+ kafka_compression_codec: "none".to_string(),
+ recv_batch_size: 1000,
+ recv_batch_timeout_ms: 500,
+ offset_commit_interval_ms: 5000,
+ sweep_interval_ms: 30000,
+ sweep_safety_margin_ms: 300000,
+ store_path: "cohort-store".to_string(),
+ wipe_store_on_start: true,
+ durable_restore_enabled: false,
+ durable_restore_single_pod: false,
+ checkpoint_enabled: false,
+ checkpoint_interval_ms: 300_000,
+ checkpoint_s3_upload_interval_ms: 900_000,
+ checkpoint_local_dir: "cohort-checkpoints".to_string(),
+ checkpoint_s3_bucket: String::new(),
+ checkpoint_s3_prefix: "cohort-stream-checkpoints".to_string(),
+ checkpoint_s3_region: None,
+ checkpoint_s3_endpoint: None,
+ checkpoint_s3_access_key_id: None,
+ checkpoint_s3_secret_access_key: None,
+ checkpoint_s3_force_path_style: false,
+ checkpoint_max_concurrent_uploads: 40,
+ checkpoint_max_concurrent_downloads: 40,
+ checkpoint_max_upload_buffers: 40,
+ checkpoint_s3_max_retries: 3,
+ checkpoint_s3_operation_timeout_secs: 120,
+ checkpoint_s3_attempt_timeout_secs: 20,
+ checkpoint_local_max_staleness_secs: 7200,
+ checkpoint_import_window_hours: 24,
+ checkpoint_import_attempt_depth: 10,
+ checkpoint_import_timeout_secs: 240,
+ }
+ }
+
+ #[test]
+ fn refresh_interval_and_jitter_map_from_seconds() {
+ let config = test_config();
+ assert_eq!(
+ config.filter_catalog_refresh_interval(),
+ Duration::from_secs(300)
+ );
+ assert_eq!(
+ config.filter_catalog_refresh_jitter(),
+ Duration::from_secs(60)
+ );
+ }
+
+ #[test]
+ fn sweep_interval_and_safety_margin_map_from_millis() {
+ let config = test_config();
+ assert_eq!(config.sweep_interval(), Duration::from_millis(30_000));
+ assert_eq!(config.sweep_safety_margin(), Duration::from_millis(300_000));
+ }
+
+ #[test]
+ fn statement_timeout_zero_means_database_default() {
+ let mut config = test_config();
+ config.pg_statement_timeout_ms = 0;
+ assert!(config.pool_config().statement_timeout_ms.is_none());
+ }
+
+ #[test]
+ fn pool_config_uses_the_named_pool() {
+ let config = test_config();
+ assert_eq!(config.pool_config().pool_name.as_deref(), Some(POOL_NAME));
+ }
+
+ #[test]
+ fn consumer_config_disables_auto_commit_and_offset_store() {
+ let config = test_config();
+ let client = config.consumer_client_config();
+ assert_eq!(client.get("enable.auto.commit"), Some("false"));
+ assert_eq!(client.get("enable.auto.offset.store"), Some("false"));
+ assert_eq!(client.get("group.id"), Some("cohort-stream-processor"));
+ assert_eq!(client.get("auto.offset.reset"), Some("latest"));
+ assert_eq!(client.get("bootstrap.servers"), Some("localhost:9092"));
+ }
+
+ #[test]
+ fn consumer_config_uses_cooperative_sticky_and_the_configured_session_timeout() {
+ let mut config = test_config();
+ config.kafka_session_timeout_ms = 45000;
+ let client = config.consumer_client_config();
+ assert_eq!(
+ client.get("partition.assignment.strategy"),
+ Some("cooperative-sticky"),
+ );
+ assert_eq!(client.get("session.timeout.ms"), Some("45000"));
+ }
+
+ #[test]
+ fn consumer_config_sets_static_membership_only_when_pod_identity_is_present() {
+ let mut config = test_config();
+ assert_eq!(
+ config.consumer_client_config().get("group.instance.id"),
+ None,
+ );
+
+ config.pod_hostname = Some("cohort-stream-processor-2".to_string());
+ let client = config.consumer_client_config();
+ assert_eq!(
+ client.get("group.instance.id"),
+ Some("cohort-stream-processor-2"),
+ );
+ assert_eq!(client.get("client.id"), Some("cohort-stream-processor-2"));
+ }
+
+ #[test]
+ fn pod_identity_prefers_pod_name_and_ignores_blanks() {
+ let mut config = test_config();
+ config.pod_name = Some("pod-from-downward-api".to_string());
+ config.pod_hostname = Some("hostname".to_string());
+ assert_eq!(config.pod_identity(), Some("pod-from-downward-api"));
+
+ config.pod_name = Some(String::new());
+ assert_eq!(config.pod_identity(), Some("hostname"));
+
+ config.pod_hostname = None;
+ assert_eq!(config.pod_identity(), None);
+ }
+
+ #[test]
+ fn explicit_client_id_overrides_pod_identity() {
+ let mut config = test_config();
+ config.pod_hostname = Some("hostname".to_string());
+ config.kafka_client_id = "explicit-client".to_string();
+ let client = config.consumer_client_config();
+ // Static membership still keyed on the pod identity, but client.id is the explicit override.
+ assert_eq!(client.get("group.instance.id"), Some("hostname"));
+ assert_eq!(client.get("client.id"), Some("explicit-client"));
+ }
+
+ #[test]
+ fn store_config_threads_the_wipe_on_start_flag() {
+ let mut config = test_config();
+ config.wipe_store_on_start = true;
+ assert!(config.store_config().wipe_on_start);
+ config.wipe_store_on_start = false;
+ assert!(!config.store_config().wipe_on_start);
+ }
+
+ #[test]
+ fn consumer_config_sets_tls_keys_only_when_enabled() {
+ let mut config = test_config();
+ assert_eq!(
+ config.consumer_client_config().get("security.protocol"),
+ None
+ );
+
+ config.kafka_tls = true;
+ assert_eq!(
+ config.consumer_client_config().get("security.protocol"),
+ Some("ssl"),
+ );
+ }
+
+ #[test]
+ fn durable_restore_defaults_off_and_overrides_from_env() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert!(
+ !defaults.durable_restore_enabled,
+ "durable restore defaults off"
+ );
+
+ let env: std::collections::HashMap<String, String> = [("DURABLE_RESTORE_ENABLED", "true")]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert!(config.durable_restore_enabled);
+ }
+
+ #[test]
+ fn durable_restore_single_pod_defaults_off_and_overrides_from_env() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert!(
+ !defaults.durable_restore_single_pod,
+ "the single-pod assertion defaults off (inert)",
+ );
+
+ let env: std::collections::HashMap<String, String> =
+ [("DURABLE_RESTORE_SINGLE_POD", "true")]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert!(config.durable_restore_single_pod);
+ }
+
+ #[test]
+ fn durability_startup_guard_passes_for_the_default_config() {
+ assert!(test_config().validate_durability_startup().is_ok());
+ }
+
+ #[test]
+ fn durability_startup_guard_passes_for_a_plain_durable_restore() {
+ let mut config = test_config();
+ config.durable_restore_enabled = true;
+ assert!(config.validate_durability_startup().is_ok());
+ }
+
+ #[test]
+ fn durability_startup_guard_refuses_durable_plus_cascade_without_the_opt_in() {
+ let mut config = test_config();
+ config.durable_restore_enabled = true;
+ config.cohort_cascade_enabled = true;
+ config.pod_name = Some("pod-0".to_string());
+ let err = config
+ .validate_durability_startup()
+ .expect_err("durable + cascade without the opt-in must be refused");
+ assert!(
+ err.to_string().contains("DURABLE_RESTORE_SINGLE_POD"),
+ "the refusal points the operator at the single-pod opt-in: {err}",
+ );
+ }
+
+ #[test]
+ fn durability_startup_guard_refuses_durable_plus_cascade_with_opt_in_but_no_pod_identity() {
+ let mut config = test_config();
+ config.durable_restore_enabled = true;
+ config.cohort_cascade_enabled = true;
+ config.durable_restore_single_pod = true;
+ config.pod_name = None;
+ config.pod_hostname = None;
+ assert!(
+ config.validate_durability_startup().is_err(),
+ "single-pod opt-in without a pod identity must still refuse the combo",
+ );
+ }
+
+ #[test]
+ fn durability_startup_guard_allows_durable_plus_cascade_with_opt_in_and_pod_identity() {
+ let mut config = test_config();
+ config.durable_restore_enabled = true;
+ config.cohort_cascade_enabled = true;
+ config.durable_restore_single_pod = true;
+ config.pod_name = Some("cohort-stream-processor-0".to_string());
+ assert!(
+ config.validate_durability_startup().is_ok(),
+ "durable + cascade is allowed on a single-pod static-membership deploy",
+ );
+ }
+
+ #[test]
+ fn durability_startup_guard_refuses_checkpoint_without_durable_restore() {
+ let mut config = test_config();
+ config.checkpoint_enabled = true;
+ config.durable_restore_enabled = false;
+ let err = config
+ .validate_durability_startup()
+ .expect_err("checkpoint without durable restore must be refused");
+ assert!(
+ err.to_string().contains("DURABLE_RESTORE_ENABLED"),
+ "the refusal names the durable-restore requirement: {err}",
+ );
+ }
+
+ #[test]
+ fn durability_startup_guard_allows_checkpoint_with_durable_restore() {
+ let mut config = test_config();
+ config.checkpoint_enabled = true;
+ config.durable_restore_enabled = true;
+ assert!(config.validate_durability_startup().is_ok());
+ }
+
+ #[test]
+ fn checkpoint_config_defaults_off_and_overrides_from_env() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert!(
+ !defaults.checkpoint_enabled,
+ "the checkpoint master gate defaults off",
+ );
+ assert_eq!(
+ defaults.checkpoint_interval(),
+ Duration::from_millis(300_000)
+ );
+ assert_eq!(
+ defaults.checkpoint_s3_upload_interval(),
+ Duration::from_millis(900_000),
+ );
+ assert_eq!(defaults.checkpoint_local_dir, "cohort-checkpoints");
+ assert!(
+ defaults.checkpoint_s3_bucket.is_empty(),
+ "no S3 bucket by default → uploader inert",
+ );
+ assert_eq!(
+ defaults.checkpoint_local_max_staleness(),
+ Duration::from_secs(7200),
+ );
+ assert_eq!(defaults.checkpoint_import_window_hours, 24);
+ assert_eq!(defaults.checkpoint_import_attempt_depth, 10);
+
+ let env: std::collections::HashMap<String, String> = [
+ ("CHECKPOINT_ENABLED", "true"),
+ ("CHECKPOINT_INTERVAL_MS", "60000"),
+ ("CHECKPOINT_S3_UPLOAD_INTERVAL_MS", "120000"),
+ ("CHECKPOINT_LOCAL_DIR", "/data/ckpt"),
+ ("CHECKPOINT_S3_BUCKET", "my-bucket"),
+ ("CHECKPOINT_S3_PREFIX", "ckpt-prefix"),
+ ("CHECKPOINT_S3_REGION", "us-east-1"),
+ ("CHECKPOINT_S3_ENDPOINT", "http://minio:9000"),
+ ("CHECKPOINT_S3_ACCESS_KEY_ID", "ak"),
+ ("CHECKPOINT_S3_SECRET_ACCESS_KEY", "sk"),
+ ("CHECKPOINT_S3_FORCE_PATH_STYLE", "true"),
+ ("CHECKPOINT_MAX_CONCURRENT_UPLOADS", "8"),
+ ("CHECKPOINT_MAX_CONCURRENT_DOWNLOADS", "9"),
+ ("CHECKPOINT_MAX_UPLOAD_BUFFERS", "10"),
+ ("CHECKPOINT_S3_MAX_RETRIES", "5"),
+ ("CHECKPOINT_S3_OPERATION_TIMEOUT_SECS", "60"),
+ ("CHECKPOINT_S3_ATTEMPT_TIMEOUT_SECS", "11"),
+ ("CHECKPOINT_LOCAL_MAX_STALENESS_SECS", "3600"),
+ ("CHECKPOINT_IMPORT_WINDOW_HOURS", "12"),
+ ("CHECKPOINT_IMPORT_ATTEMPT_DEPTH", "4"),
+ ("CHECKPOINT_IMPORT_TIMEOUT_SECS", "90"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert!(config.checkpoint_enabled);
+ assert_eq!(config.checkpoint_interval(), Duration::from_millis(60_000));
+ assert_eq!(
+ config.checkpoint_s3_upload_interval(),
+ Duration::from_millis(120_000),
+ );
+ assert_eq!(config.checkpoint_local_dir, "/data/ckpt");
+ assert_eq!(config.checkpoint_s3_bucket, "my-bucket");
+ assert_eq!(config.checkpoint_import_window_hours, 12);
+ assert_eq!(config.checkpoint_import_attempt_depth, 4);
+ }
+
+ #[test]
+ fn durability_config_maps_the_checkpoint_fields() {
+ let mut config = test_config();
+ config.checkpoint_local_dir = "/data/ckpt".to_string();
+ config.checkpoint_s3_bucket = "bkt".to_string();
+ config.checkpoint_s3_prefix = "pfx".to_string();
+ config.checkpoint_s3_region = Some("eu-central-1".to_string());
+ config.checkpoint_s3_endpoint = Some("http://seaweedfs:8333".to_string());
+ config.checkpoint_s3_access_key_id = Some("ak".to_string());
+ config.checkpoint_s3_secret_access_key = Some("sk".to_string());
+ config.checkpoint_s3_force_path_style = true;
+ config.checkpoint_max_concurrent_uploads = 7;
+ config.checkpoint_max_concurrent_downloads = 8;
+ config.checkpoint_max_upload_buffers = 9;
+ config.checkpoint_s3_max_retries = 2;
+ config.checkpoint_s3_operation_timeout_secs = 60;
+ config.checkpoint_s3_attempt_timeout_secs = 11;
+ config.checkpoint_local_max_staleness_secs = 3600;
+ config.checkpoint_import_window_hours = 6;
+ config.checkpoint_import_attempt_depth = 4;
+ config.checkpoint_import_timeout_secs = 90;
+
+ let durability = config.durability_config();
+ assert_eq!(durability.local_checkpoint_dir, "/data/ckpt");
+ assert_eq!(durability.s3_bucket, "bkt");
+ assert_eq!(durability.s3_key_prefix, "pfx");
+ assert_eq!(durability.aws_region.as_deref(), Some("eu-central-1"));
+ assert_eq!(
+ durability.s3_endpoint.as_deref(),
+ Some("http://seaweedfs:8333"),
+ );
+ assert_eq!(durability.s3_access_key_id.as_deref(), Some("ak"));
+ assert!(durability.s3_force_path_style);
+ assert_eq!(durability.max_concurrent_checkpoint_file_uploads, 7);
+ assert_eq!(durability.max_concurrent_checkpoint_file_downloads, 8);
+ assert_eq!(durability.max_upload_buffers, 9);
+ assert_eq!(durability.s3_max_retries, 2);
+ assert_eq!(durability.s3_operation_timeout, Duration::from_secs(60));
+ assert_eq!(durability.s3_attempt_timeout, Duration::from_secs(11));
+ assert_eq!(
+ durability.local_checkpoint_max_staleness,
+ Duration::from_secs(3600),
+ );
+ assert_eq!(durability.checkpoint_import_window_hours, 6);
+ assert_eq!(durability.checkpoint_import_attempt_depth, 4);
+ assert_eq!(
+ durability.checkpoint_import_timeout,
+ Duration::from_secs(90)
+ );
+ }
+
+ #[test]
+ fn effective_wipe_on_start_truth_table() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let existing = dir.path().join("db");
+ std::fs::create_dir_all(&existing).unwrap();
+ let missing = dir.path().join("does-not-exist");
+
+ // (wipe_store_on_start, durable_restore_enabled, store exists) -> effective wipe.
+ let cases = [
+ (true, false, true, true, "wipe-on + restore-off + present"),
+ (true, false, false, true, "wipe-on + restore-off + absent"),
+ (
+ false,
+ false,
+ true,
+ false,
+ "wipe-off + restore-off + present",
+ ),
+ (
+ true,
+ true,
+ true,
+ false,
+ "wipe-on + restore-on + present → reopen-live",
+ ),
+ (
+ true,
+ true,
+ false,
+ true,
+ "wipe-on + restore-on + absent → fresh wipe (no-op)",
+ ),
+ (false, true, true, false, "wipe-off + restore-on + present"),
+ ];
+ for (wipe, durable, exists, expected, why) in cases {
+ let mut config = test_config();
+ config.wipe_store_on_start = wipe;
+ config.durable_restore_enabled = durable;
+ config.store_path = if exists {
+ existing.to_string_lossy().into_owned()
+ } else {
+ missing.to_string_lossy().into_owned()
+ };
+ assert_eq!(config.effective_wipe_on_start(), expected, "{why}");
+ assert_eq!(
+ config.store_config().wipe_on_start,
+ expected,
+ "store_config must thread the effective wipe: {why}",
+ );
+ }
+ }
+
+ #[test]
+ fn store_config_threads_through_the_configured_path() {
+ let mut config = test_config();
+ config.store_path = "/var/lib/cohort/state".to_string();
+ assert_eq!(
+ config.store_config().path,
+ std::path::PathBuf::from("/var/lib/cohort/state"),
+ );
+ }
+
+ #[test]
+ fn merge_envs_default_to_the_expected_topology() {
+ let config = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert_eq!(config.person_merge_events_topic, "person_merge_events");
+ assert_eq!(
+ config.cohort_merge_state_transfer_topic,
+ "cohort_merge_state_transfer",
+ );
+ assert_eq!(config.kafka_merge_consumer_group, "cohort-stream-merges");
+ assert_eq!(
+ config.kafka_merge_apply_consumer_group,
+ "cohort-stream-merge-apply",
+ );
+ assert_eq!(
+ config.transfer_retry_policy(),
+ TransferRetryPolicy::default()
+ );
+ assert_eq!(
+ config.merge_redrive_interval(),
+ Duration::from_millis(60_000)
+ );
+ // The transfer sink fast-fails per attempt; the shared sink keeps the 20 s timeout.
+ assert_eq!(config.merge_transfer_message_timeout_ms, 2000);
+ assert_eq!(
+ config
+ .build_transfer_kafka_config()
+ .kafka_message_timeout_ms,
+ 2000,
+ );
+ assert_eq!(config.build_kafka_config().kafka_message_timeout_ms, 20_000);
+ }
+
+ #[test]
+ fn merge_gc_defaults_match_the_tdd_retention_floors() {
+ let config = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ // 8d = 7d merge-topic retention + 1d safety — covers both marker CFs.
+ assert_eq!(config.merge_marker_retention_ms, 691_200_000);
+ assert_eq!(
+ config.merge_marker_retention_ms,
+ (7 + 1) * 24 * 60 * 60 * 1000,
+ );
+ // 9d = events 7d + stream 24h + 1d safety.
+ assert_eq!(config.merge_tombstone_retention_ms, 777_600_000);
+ assert_eq!(
+ config.merge_tombstone_retention_ms,
+ (7 * 24 + 24 + 24) * 60 * 60 * 1000,
+ );
+ assert_eq!(config.merge_gc_interval(), Duration::from_millis(3_600_000));
+ assert_eq!(config.merge_gc_scan_limit, 10_000);
+ assert!(
+ config.stage2_orphan_gc_enabled,
+ "the cf_stage2 orphan GC defaults on",
+ );
+ }
+
+ #[test]
+ fn merge_gc_knobs_override_from_env() {
+ let env: std::collections::HashMap<String, String> = [
+ ("MERGE_MARKER_RETENTION_MS", "123"),
+ ("MERGE_TOMBSTONE_RETENTION_MS", "456"),
+ ("MERGE_GC_INTERVAL_MS", "789"),
+ ("MERGE_GC_SCAN_LIMIT", "5"),
+ ("STAGE2_ORPHAN_GC_ENABLED", "false"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert_eq!(config.merge_marker_retention_ms, 123);
+ assert_eq!(config.merge_tombstone_retention_ms, 456);
+ assert_eq!(config.merge_gc_interval(), Duration::from_millis(789));
+ assert_eq!(config.merge_gc_scan_limit, 5);
+ assert!(
+ !config.stage2_orphan_gc_enabled,
+ "the kill-switch disables the cf_stage2 orphan GC",
+ );
+ }
+
+ #[test]
+ fn cascade_caps_default_and_override_from_env() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert_eq!(defaults.cohort_cascade_depth_cap, 8);
+ assert_eq!(defaults.cohort_cascade_fanout_cap, 1000);
+ assert!(
+ !defaults.cohort_cascade_enabled,
+ "the cascade gate defaults off",
+ );
+ assert_eq!(
+ defaults.cohort_cascade_events_topic,
+ "cohort_cascade_events"
+ );
+ assert_eq!(
+ defaults.kafka_cascade_consumer_group,
+ "cohort-stream-cascade"
+ );
+
+ let env: std::collections::HashMap<String, String> = [
+ ("COHORT_CASCADE_DEPTH_CAP", "3"),
+ ("COHORT_CASCADE_FANOUT_CAP", "50"),
+ ("COHORT_CASCADE_ENABLED", "true"),
+ ("COHORT_CASCADE_EVENTS_TOPIC", "cascade_test"),
+ ("KAFKA_CASCADE_CONSUMER_GROUP", "cascade-group-test"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert_eq!(config.cohort_cascade_depth_cap, 3);
+ assert_eq!(config.cohort_cascade_fanout_cap, 50);
+ assert!(config.cohort_cascade_enabled);
+ assert_eq!(config.cohort_cascade_events_topic, "cascade_test");
+ assert_eq!(config.kafka_cascade_consumer_group, "cascade-group-test");
+ assert_eq!(
+ config.cascade_config(),
+ CascadeConfig {
+ enabled: true,
+ depth_cap: 3,
+ fanout_cap: 50,
+ },
+ );
+ }
+
+ #[test]
+ fn build_transfer_kafka_config_overrides_only_the_message_timeout() {
+ let config = test_config();
+ let shared = config.build_kafka_config();
+ let transfer = config.build_transfer_kafka_config();
+ // Only `message.timeout.ms` differs; every other producer knob is inherited.
+ assert_eq!(transfer.kafka_message_timeout_ms, 2000);
+ assert_eq!(shared.kafka_message_timeout_ms, 20_000);
+ assert_eq!(
+ transfer.kafka_producer_partitioner,
+ shared.kafka_producer_partitioner,
+ );
+ assert_eq!(transfer.kafka_hosts, shared.kafka_hosts);
+ assert_eq!(
+ transfer.kafka_compression_codec,
+ shared.kafka_compression_codec
+ );
+ assert_eq!(
+ transfer.kafka_producer_linger_ms,
+ shared.kafka_producer_linger_ms
+ );
+ assert_eq!(
+ transfer.kafka_producer_queue_mib,
+ shared.kafka_producer_queue_mib
+ );
+ }
+
+ #[test]
+ fn merge_envs_override_the_defaults() {
+ let env: std::collections::HashMap<String, String> = [
+ ("PERSON_MERGE_EVENTS_TOPIC", "pme_test"),
+ ("COHORT_MERGE_STATE_TRANSFER_TOPIC", "transfer_test"),
+ ("KAFKA_MERGE_CONSUMER_GROUP", "merges-test"),
+ ("KAFKA_MERGE_APPLY_CONSUMER_GROUP", "apply-test"),
+ ("MERGE_TRANSFER_MAX_RETRIES", "2"),
+ ("MERGE_TRANSFER_RETRY_BASE_MS", "100"),
+ ("MERGE_TRANSFER_RETRY_CAP_MS", "400"),
+ ("MERGE_TRANSFER_MESSAGE_TIMEOUT_MS", "750"),
+ ("MERGE_REDRIVE_INTERVAL_MS", "5000"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert_eq!(config.person_merge_events_topic, "pme_test");
+ assert_eq!(config.cohort_merge_state_transfer_topic, "transfer_test");
+ assert_eq!(config.kafka_merge_consumer_group, "merges-test");
+ assert_eq!(config.kafka_merge_apply_consumer_group, "apply-test");
+ assert_eq!(
+ config.transfer_retry_policy(),
+ TransferRetryPolicy {
+ max_retries: 2,
+ base: Duration::from_millis(100),
+ cap: Duration::from_millis(400),
+ },
+ );
+ assert_eq!(config.merge_redrive_interval(), Duration::from_millis(5000));
+ assert_eq!(config.merge_transfer_message_timeout_ms, 750);
+ assert_eq!(
+ config
+ .build_transfer_kafka_config()
+ .kafka_message_timeout_ms,
+ 750,
+ );
+ }
+
+ #[test]
+ fn follower_config_hard_codes_earliest_regardless_of_the_events_reset() {
+ let mut config = test_config();
+ config.kafka_consumer_offset_reset = "latest".to_string();
+ let client = config.follower_client_config("cohort-stream-merges");
+ assert_eq!(client.get("auto.offset.reset"), Some("earliest"));
+ assert_eq!(client.get("group.id"), Some("cohort-stream-merges"));
+ assert_eq!(client.get("enable.auto.commit"), Some("false"));
+ assert_eq!(client.get("enable.auto.offset.store"), Some("false"));
+ assert_eq!(client.get("bootstrap.servers"), Some("localhost:9092"));
+ }
+
+ #[test]
+ fn follower_config_never_joins_the_group_protocol() {
+ let mut config = test_config();
+ config.pod_hostname = Some("cohort-stream-processor-2".to_string());
+ let client = config.follower_client_config("cohort-stream-merge-apply");
+ assert_eq!(client.get("partition.assignment.strategy"), None);
+ assert_eq!(client.get("group.instance.id"), None);
+ assert_eq!(client.get("client.id"), Some("cohort-stream-processor-2"));
+ }
+
+ #[test]
+ fn follower_config_sets_tls_keys_only_when_enabled() {
+ let mut config = test_config();
+ assert_eq!(
+ config.follower_client_config("g").get("security.protocol"),
+ None,
+ );
+ config.kafka_tls = true;
+ assert_eq!(
+ config.follower_client_config("g").get("security.protocol"),
+ Some("ssl"),
+ );
+ }
+
+ #[test]
+ fn cohort_partition_count_defaults_to_64_and_overrides_from_env() {
+ let defaults = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ assert_eq!(
+ defaults.cohort_partition_count, 64,
+ "production default is 64 so behavior stays byte-identical",
+ );
+
+ let env: std::collections::HashMap<String, String> = [("COHORT_PARTITION_COUNT", "8")]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+ let config = Config::init_from_hashmap(&env).unwrap();
+ assert_eq!(config.cohort_partition_count, 8);
+ }
+
+ #[test]
+ fn build_kafka_config_pins_the_murmur2_partitioner() {
+ let kafka = test_config().build_kafka_config();
+ assert_eq!(
+ kafka.kafka_producer_partitioner.as_deref(),
+ Some("murmur2_random"),
+ );
+ assert_eq!(kafka.kafka_compression_codec, "none");
+ assert_eq!(kafka.kafka_hosts, "localhost:9092");
+ }
+}
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
new file mode 100644
index 000000000000..356d53f7bcc5
--- /dev/null
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -0,0 +1,3328 @@
+//! The `cohort_stream_events` wire envelope and the group consumer that drives it.
+//!
+//! [`CohortStreamEvent`] is the processor's own deserialize struct, deliberately decoupled from
+//! `cohort-event-shuffler`'s producer type: the two services share only the JSON field names, so a
+//! private copy means neither can break the other by adding a one-sided field.
+//!
+//! The Kafka-free routing core lives in [`EventDispatcher`] so it can be unit-tested with an
+//! in-process router/store/catalog and no broker.
+
+use std::collections::{HashMap, HashSet};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, OnceLock};
+use std::time::{Duration, Instant};
+
+use dashmap::mapref::entry::Entry;
+use dashmap::{DashMap, DashSet};
+use lifecycle::Handle;
+use metrics::{counter, gauge, histogram};
+use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, StreamConsumer};
+use rdkafka::message::Message;
+use rdkafka::{Offset, TopicPartitionList};
+use serde::{Deserialize, Serialize};
+use tracing::{debug, info, warn};
+
+use crate::consumers::merges::{ConsumedCascade, ConsumedMerge, ConsumedTransfer};
+use crate::filters::manager::CatalogHandle;
+use crate::merge::transfer::PendingTransfer;
+use crate::observability::metrics::{
+ CASCADE_HELD_OFFSET_GAUGE, COHORT_STREAM_CASCADES_SKIPPED_NOT_OWNED,
+ COHORT_STREAM_CONSUME_BATCH_SIZE, COHORT_STREAM_DESERIALIZE_ERRORS,
+ COHORT_STREAM_EMPTY_PAYLOAD, COHORT_STREAM_EVENTS_CONSUMED, COHORT_STREAM_EVENTS_DISPATCHED,
+ COHORT_STREAM_EVENTS_SKIPPED_NOT_OWNED, COHORT_STREAM_KAFKA_RECV_ERRORS,
+ COHORT_STREAM_MERGES_SKIPPED_NOT_OWNED, COHORT_STREAM_OFFSET_COMMITS,
+ COHORT_STREAM_OFFSET_COMMIT_ERRORS, COHORT_STREAM_ROUTE_ERRORS,
+ COHORT_STREAM_TRANSFERS_SKIPPED_NOT_OWNED, COHORT_STREAM_WORKERS_SPAWNED,
+ DURABLE_RESTORE_PARTITIONS_KEPT_TOTAL, DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL,
+ DURABLE_RESTORE_PENDING_TRANSFERS_RECOVERED_PARTITIONS_TOTAL, MERGE_HELD_OFFSET_GAUGE,
+ MERGE_PENDING_TRANSFERS_GAUGE, PARTITIONS_ASSIGNED_TOTAL, PARTITIONS_REVOKED_TOTAL,
+ PARTITION_STATE_DELETED_TOTAL, REBALANCE_CLEANUP_SKIPPED_TOTAL, REVOKE_DRAIN_DURATION_SECONDS,
+};
+use crate::partitions::offset_tracker::OffsetTracker;
+use crate::partitions::rebalance::{CohortConsumerContext, ConsumerCommandReceiver};
+use crate::partitions::router::PartitionRouter;
+use crate::partitions::shuffle_message::ShuffleMessage;
+use crate::producer::MembershipSink;
+use crate::store::durability::OffsetManifest;
+use crate::store::CohortStore;
+use crate::workers::{MergeWorkerDeps, Stage1Worker};
+
+/// Back-off after a Kafka transport error so a fast-failing `recv()` can't spin a consume loop.
+pub(crate) const RECV_ERROR_BACKOFF: Duration = Duration::from_millis(500);
+
+/// Timeout for the one-shot restore seek of the events topic. A local fetch-position reposition, so a
+/// few seconds is ample; a timeout is a seek failure and retries (never resumes from the broker offset).
+const RESTORE_SEEK_TIMEOUT: Duration = Duration::from_secs(10);
+
+/// Page size for the eager boot redrive's paginated scan of `cf_pending_transfers`. The outbox only
+/// ever holds transfers stranded by inline-retry exhaustion (rare), so this large page drains a
+/// typical outbox in a single round; a larger backlog is drained across successive pages, bounding
+/// peak memory per page.
+const EAGER_BOOT_REDRIVE_PAGE_SIZE: usize = 100_000;
+
+/// One re-keyed event as published to `cohort_stream_events`. Field names mirror the shuffler
+/// envelope exactly.
+///
+/// `properties` / `person_properties` are raw JSON strings parsed lazily in globals construction.
+/// `source_partition` / `source_offset` are the upstream coordinates for replay-safe counter
+/// increments.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CohortStreamEvent {
+ pub team_id: i32,
+ pub person_id: String,
+ pub distinct_id: String,
+ pub uuid: String,
+ pub event: String,
+ /// ClickHouse wire format `"YYYY-MM-DD HH:MM:SS.ffffff"`; normalized to ISO 8601 in globals.
+ pub timestamp: String,
+ pub properties: Option<String>,
+ pub person_properties: Option<String>,
+ pub elements_chain: Option<String>,
+ pub source_offset: i64,
+ pub source_partition: i32,
+ /// The merge origin person, set when a post-merge straggler is redirected to the merged-into
+ /// person. `None` for a normal event. Stage 1 routes replay-dedup through
+ /// `redirect_dedup[origin]` when set, preventing double-fold.
+ #[serde(default)]
+ pub redirected_from: Option<String>,
+ /// Cross-partition re-produce hops this straggler has taken through the tombstone redirect.
+ /// `0` for a normal event; incremented on each re-key produce. At the cap
+ /// (`MAX_CROSS_PARTITION_REDIRECT_HOPS`) the worker degrades to an inline fold to break cycles.
+ #[serde(default)]
+ pub redirect_hops: u8,
+}
+
+/// One event consumed from `cohort_stream_events`, paired with its commit coordinates on that topic.
+///
+/// `partition`/`offset` here are commit coordinates, distinct from the event's upstream
+/// `source_partition`/`source_offset` which drive per-key replay idempotence.
+#[derive(Debug)]
+pub struct ConsumedEvent {
+ pub event: CohortStreamEvent,
+ pub partition: i32,
+ pub offset: i64,
+}
+
+/// The Kafka-free routing core: dispatches consumed batches to per-partition workers, tracks
+/// processed offsets, and owns the partition lifecycle the rebalance handler drives.
+pub struct EventDispatcher {
+ router: Arc<PartitionRouter>,
+ tracker: Arc<OffsetTracker>,
+ workers: Arc<DashMap<i32, Stage1Worker>>,
+ /// Partitions currently assigned to this consumer.
+ owned: Arc<DashSet<i32>>,
+ store: CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: Arc<dyn MembershipSink>,
+ merge: Arc<MergeWorkerDeps>,
+ /// Prevents post-shutdown worker registration that would hang the join. The structural guarantee
+ /// is the router's terminal closed state, which refuses registration after `clear()`.
+ draining: AtomicBool,
+ /// When set, workers rebuild their `EvictionQueue` on spawn and boot/assign paths reclaim stale
+ /// on-disk slices. Set once at startup before any worker spawns.
+ durable_restore: AtomicBool,
+ /// Settled boot assignment, recorded once. The assign path reclaims only partitions that move in
+ /// after boot. `OnceLock` is `Sync`; the only race (get sees `None` before set) resolves to
+ /// "skip", so a boot partition is never wiped.
+ boot_assignment: OnceLock<HashSet<i32>>,
+}
+
+impl EventDispatcher {
+ pub fn new(
+ router: PartitionRouter,
+ tracker: Arc<OffsetTracker>,
+ store: CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: Arc<dyn MembershipSink>,
+ merge: Arc<MergeWorkerDeps>,
+ ) -> Self {
+ Self {
+ router: Arc::new(router),
+ tracker,
+ workers: Arc::new(DashMap::new()),
+ owned: Arc::new(DashSet::new()),
+ store,
+ catalog,
+ sink,
+ merge,
+ draining: AtomicBool::new(false),
+ durable_restore: AtomicBool::new(false),
+ boot_assignment: OnceLock::new(),
+ }
+ }
+
+ /// Enable crash-restart durability. Must be called before any worker spawns.
+ pub fn enable_durable_restore(&self) {
+ self.durable_restore.store(true, Ordering::SeqCst);
+ }
+
+ pub fn durable_restore_enabled(&self) -> bool {
+ self.durable_restore.load(Ordering::SeqCst)
+ }
+
+ pub(crate) fn store(&self) -> &CohortStore {
+ &self.store
+ }
+
+ /// Route a consumed batch to per-partition workers, lazily spawning on first delivery.
+ ///
+ /// The dispatch ceiling is raised before routing so a `RouteError` leaves the offset
+ /// uncommittable and Kafka replays it. Events for unowned partitions are dropped before any
+ /// ceiling bump.
+ pub async fn dispatch(&self, batch: Vec<ConsumedEvent>) {
+ if batch.is_empty() {
+ return;
+ }
+ let items = batch
+ .into_iter()
+ .map(|consumed| {
+ (
+ consumed.partition,
+ consumed.offset,
+ ShuffleMessage::Event {
+ event: consumed.event,
+ cse_offset: consumed.offset,
+ },
+ )
+ })
+ .collect();
+ let stats = self.dispatch_to_workers(items, &self.tracker).await;
+ counter!(COHORT_STREAM_EVENTS_SKIPPED_NOT_OWNED).increment(stats.not_owned_skipped);
+ counter!(COHORT_STREAM_EVENTS_DISPATCHED).increment(stats.dispatched);
+ }
+
+ /// Route a consumed `person_merge_events` batch to per-partition workers, ceiling on the merge
+ /// tracker. Spawns workers (unlike sweep) because merges are durable external input.
+ pub async fn dispatch_merges(&self, batch: Vec<ConsumedMerge>) {
+ if batch.is_empty() {
+ return;
+ }
+ let items = batch
+ .into_iter()
+ .map(|consumed| {
+ (
+ consumed.partition,
+ consumed.offset,
+ ShuffleMessage::Merge {
+ event: consumed.event,
+ offset: consumed.offset,
+ },
+ )
+ })
+ .collect();
+ let stats = self
+ .dispatch_to_workers(items, &self.merge.merge_tracker)
+ .await;
+ counter!(COHORT_STREAM_MERGES_SKIPPED_NOT_OWNED).increment(stats.not_owned_skipped);
+ }
+
+ /// Route a consumed `cohort_merge_state_transfer` batch to per-partition workers, ceiling on the
+ /// transfer tracker. Spawns workers because a dropped transfer is unrecoverable.
+ pub async fn dispatch_transfers(&self, batch: Vec<ConsumedTransfer>) {
+ if batch.is_empty() {
+ return;
+ }
+ let items = batch
+ .into_iter()
+ .map(|consumed| {
+ (
+ consumed.partition,
+ consumed.offset,
+ ShuffleMessage::Transfer {
+ transfer: Box::new(consumed.transfer),
+ offset: consumed.offset,
+ },
+ )
+ })
+ .collect();
+ let stats = self
+ .dispatch_to_workers(items, &self.merge.transfer_tracker)
+ .await;
+ counter!(COHORT_STREAM_TRANSFERS_SKIPPED_NOT_OWNED).increment(stats.not_owned_skipped);
+ }
+
+ /// Route a consumed `cohort_cascade_events` batch to per-partition workers, ceiling on the
+ /// cascade tracker. Spawns workers because a dropped cascade silently fails to propagate a flip.
+ pub async fn dispatch_cascade(&self, batch: Vec<ConsumedCascade>) {
+ if batch.is_empty() {
+ return;
+ }
+ let items = batch
+ .into_iter()
+ .map(|consumed| {
+ (
+ consumed.partition,
+ consumed.offset,
+ ShuffleMessage::Cascade {
+ message: Box::new(consumed.message),
+ offset: consumed.offset,
+ },
+ )
+ })
+ .collect();
+ let stats = self
+ .dispatch_to_workers(items, &self.merge.cascade_tracker)
+ .await;
+ counter!(COHORT_STREAM_CASCADES_SKIPPED_NOT_OWNED).increment(stats.not_owned_skipped);
+ }
+
+ async fn dispatch_to_workers(
+ &self,
+ items: Vec<(i32, i64, ShuffleMessage)>,
+ tracker: &OffsetTracker,
+ ) -> DispatchStats {
+ let mut stats = DispatchStats::default();
+ if self.draining.load(Ordering::SeqCst) {
+ stats.not_owned_skipped = items.len() as u64;
+ debug!(
+ dropped = items.len(),
+ "dispatch after shutdown began; dropping batch for replay"
+ );
+ return stats;
+ }
+
+ let mut messages: Vec<(i32, ShuffleMessage)> = Vec::with_capacity(items.len());
+ for (partition, offset, message) in items {
+ if !self.owned.contains(&partition) {
+ stats.not_owned_skipped += 1;
+ continue;
+ }
+ self.ensure_worker(partition);
+ tracker.mark_dispatched(partition, offset + 1); // next-to-consume convention
+ messages.push((partition, message));
+ }
+ stats.dispatched = messages.len() as u64;
+
+ let errors = self.router.route_batch(messages).await;
+ if !errors.is_empty() {
+ counter!(COHORT_STREAM_ROUTE_ERRORS).increment(errors.len() as u64);
+ }
+ stats
+ }
+
+ /// Spawn a worker the first time an owned partition delivers; no-op if the worker exists or the
+ /// partition is unowned. The ownership check and insert are atomic under the DashMap shard guard.
+ fn ensure_worker(&self, partition: i32) {
+ match self.workers.entry(partition) {
+ Entry::Occupied(_) => {}
+ Entry::Vacant(slot) => {
+ // No `.await` in this arm — the DashMap shard guard is held.
+ if !self.owned.contains(&partition) {
+ return;
+ }
+ if self.draining.load(Ordering::SeqCst) {
+ return;
+ }
+ // Durable restart only: wipe a post-boot move-in's stale on-disk slice (left by a
+ // revoke-delete that failed before the partition returned to this pod) before the
+ // worker rebuilds its eviction queue from it. Runs under the shard guard, so the wipe
+ // strictly precedes the spawn. `reclaim_stale_slice` must never touch `self.workers` —
+ // a `contains_key`/`entry` on the same shard while this write guard is held deadlocks.
+ if self.durable_restore_enabled() {
+ self.reclaim_stale_slice(partition);
+ }
+ match self.router.add_partition(partition) {
+ Some(receiver) => {
+ let worker = Stage1Worker::spawn(
+ partition as u16,
+ receiver,
+ self.store.clone(),
+ self.catalog.clone(),
+ self.sink.clone(),
+ self.tracker.clone(),
+ self.merge.clone(),
+ self.durable_restore_enabled(),
+ );
+ slot.insert(worker);
+ counter!(COHORT_STREAM_WORKERS_SPAWNED).increment(1);
+ info!(
+ partition,
+ "spawned stage 1 worker for newly-delivered partition"
+ );
+ }
+ None if self.router.is_closed() => {
+ debug!(
+ partition,
+ "router closed by shutdown; skipping worker spawn"
+ )
+ }
+ None => warn!(
+ partition,
+ "router holds a live channel but no worker is registered; skipping spawn",
+ ),
+ }
+ }
+ }
+ }
+
+ pub fn owns(&self, partition: i32) -> bool {
+ self.owned.contains(&partition)
+ }
+
+ /// Snapshot of the partitions currently owned by this consumer.
+ pub fn owned_partitions(&self) -> Vec<i32> {
+ self.owned.iter().map(|entry| *entry).collect()
+ }
+
+ pub(crate) fn merge_deps(&self) -> &MergeWorkerDeps {
+ &self.merge
+ }
+
+ /// Route a sweep tick to every owned partition's worker without spawning, so a revoked partition
+ /// is never resurrected.
+ pub async fn route_sweep(&self, due_before_ms: i64) {
+ self.route_to_owned(|| ShuffleMessage::Sweep { due_before_ms })
+ .await;
+ }
+
+ /// Route a redrive tick to every owned partition's worker without spawning; each worker
+ /// re-produces any `cf_pending_transfers` entries stranded by inline-retry exhaustion.
+ pub async fn route_redrive(&self) {
+ self.route_to_owned(|| ShuffleMessage::RedrivePendingTransfers)
+ .await;
+ }
+
+ /// Route a merge-GC tick to every owned partition's worker without spawning. Cutoffs are
+ /// computed by the sweeper and passed verbatim, keeping workers clock-free.
+ pub async fn route_merge_gc(&self, marker_cutoff_ms: i64, tombstone_cutoff_ms: i64) {
+ self.route_to_owned(|| ShuffleMessage::MergeCfGc {
+ marker_cutoff_ms,
+ tombstone_cutoff_ms,
+ })
+ .await;
+ }
+
+ async fn route_to_owned(&self, make_message: impl Fn() -> ShuffleMessage) {
+ if self.draining.load(Ordering::SeqCst) {
+ return;
+ }
+ let messages: Vec<(i32, ShuffleMessage)> = self
+ .owned_partitions()
+ .into_iter()
+ .map(|partition| (partition, make_message()))
+ .collect();
+ if messages.is_empty() {
+ return;
+ }
+ let errors = self.router.route_batch(messages).await;
+ if !errors.is_empty() {
+ counter!(COHORT_STREAM_ROUTE_ERRORS).increment(errors.len() as u64);
+ }
+ }
+
+ pub fn assign_partition(&self, partition: i32) {
+ self.owned.insert(partition);
+ counter!(PARTITIONS_ASSIGNED_TOTAL).increment(1);
+ }
+
+ /// Synchronous half of a revoke: mark the partition un-owned. The worker channel is left intact
+ /// for rapid revoke-then-reassign; teardown is decided in the async drain.
+ pub fn revoke_partition_sync(&self, partition: i32) {
+ self.owned.remove(&partition);
+ counter!(PARTITIONS_REVOKED_TOTAL).increment(1);
+ }
+
+ /// Asynchronous half of a revoke: reclaim the partition unless a reassign re-acquired it.
+ /// Re-checks ownership at entry and after the worker join to handle rapid revoke-then-assign.
+ pub async fn revoke_partition_drain(&self, partition: i32) {
+ if self.owned.contains(&partition) {
+ counter!(REBALANCE_CLEANUP_SKIPPED_TOTAL, "phase" => "entry").increment(1);
+ debug!(
+ partition,
+ "skipping revoke cleanup: partition re-assigned before cleanup ran"
+ );
+ return;
+ }
+
+ self.router.remove_partition(partition);
+ if let Some((_, worker)) = self.workers.remove(&partition) {
+ let started = Instant::now();
+ if let Err(err) = worker.join().await {
+ warn!(partition, error = %err, "stage 1 worker panicked during revoke drain");
+ }
+ histogram!(REVOKE_DRAIN_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
+ }
+
+ if self.owned.contains(&partition) {
+ // re-acquired during the join — skip cleanup
+ counter!(REBALANCE_CLEANUP_SKIPPED_TOTAL, "phase" => "post_join").increment(1);
+ debug!(
+ partition,
+ "skipping revoke cleanup post-join: partition re-acquired during the worker drain"
+ );
+ return;
+ }
+
+ self.tracker.forget_partition(partition);
+ self.merge.merge_tracker.forget_partition(partition);
+ self.merge.transfer_tracker.forget_partition(partition);
+ self.merge.cascade_tracker.forget_partition(partition);
+
+ // Reset per-partition gauges. Held-offset gauges in particular are alerted on a sustained
+ // non-zero level — without this, a hold that cleared on revoke would keep the alert firing.
+ gauge!(MERGE_PENDING_TRANSFERS_GAUGE, "partition" => partition.to_string()).set(0.0);
+ gauge!(MERGE_HELD_OFFSET_GAUGE, "partition" => partition.to_string()).set(0.0);
+ gauge!(CASCADE_HELD_OFFSET_GAUGE, "partition" => partition.to_string()).set(0.0);
+
+ let Some(partition_id) = partition_to_store_id(partition) else {
+ warn!(
+ partition,
+ "revoked partition out of u16 range; skipping state delete"
+ );
+ return;
+ };
+ match self.store.delete_partition(partition_id) {
+ Ok(()) => counter!(PARTITION_STATE_DELETED_TOTAL).increment(1),
+ Err(err) => {
+ warn!(partition, error = %err, "failed to delete revoked partition state")
+ }
+ }
+ }
+
+ /// Delete a moving-in partition's stale on-disk slice so the worker cold-rebuilds from the
+ /// committed offset. Called from [`Self::ensure_worker`] under the partition's shard guard, right
+ /// before the worker spawns, so the wipe deterministically precedes the eviction-queue rebuild.
+ ///
+ /// Boot-snapshot partitions are kept (the boot sweep is the authority and reopen-live is intact),
+ /// and pre-boot calls (snapshot not yet recorded) are kept too — only genuine post-boot move-ins
+ /// are reclaimed. Must not touch `self.workers`: the caller holds a DashMap shard write guard for
+ /// `partition`, so a `contains_key`/`entry` on the same shard would deadlock.
+ fn reclaim_stale_slice(&self, partition: i32) {
+ match self.boot_assignment.get() {
+ // Pre-boot: the sweep is the authority — never wipe.
+ None => return,
+ Some(boot) if boot.contains(&partition) => return,
+ Some(_) => {}
+ }
+ let Some(partition_id) = partition_to_store_id(partition) else {
+ warn!(
+ partition,
+ "assigned partition out of u16 range; skipping stale-slice reclaim"
+ );
+ return;
+ };
+ match self.store.delete_partition(partition_id) {
+ Ok(()) => counter!(DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL).increment(1),
+ Err(err) => warn!(
+ partition,
+ error = %err, "failed to reclaim stale assigned-partition state"
+ ),
+ }
+ }
+
+ /// Delete on-disk slices for partitions in `0..partition_count` not in `assignment`: they
+ /// moved away while this pod was down. `assignment` must be the settled (non-empty) assignment
+ /// — an empty set would delete all slices.
+ pub(crate) fn reclaim_unassigned_partitions_on_boot(
+ &self,
+ assignment: &std::collections::HashSet<i32>,
+ partition_count: usize,
+ ) {
+ let mut kept = 0u64;
+ let mut wiped = 0u64;
+ for partition in 0..partition_count as i32 {
+ if assignment.contains(&partition) {
+ kept += 1;
+ continue;
+ }
+ if let Some(partition_id) = partition_to_store_id(partition) {
+ match self.store.delete_partition(partition_id) {
+ Ok(()) => wiped += 1,
+ Err(err) => warn!(
+ partition,
+ error = %err, "failed to reclaim unassigned-partition state at boot"
+ ),
+ }
+ }
+ }
+ counter!(DURABLE_RESTORE_PARTITIONS_KEPT_TOTAL).increment(kept);
+ counter!(DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL).increment(wiped);
+ info!(
+ kept,
+ wiped, partition_count, "durable restore: boot staleness sweep complete"
+ );
+ }
+
+ /// Record the boot assignment snapshot, then sweep stale on-disk slices. Recording first makes
+ /// the assign path defer to the boot decision and reclaim only post-boot move-ins.
+ pub(crate) fn reconcile_boot_assignment(
+ &self,
+ assignment: &HashSet<i32>,
+ partition_count: usize,
+ ) {
+ if self.boot_assignment.set(assignment.clone()).is_err() {
+ debug!("boot assignment snapshot already recorded; keeping the first");
+ }
+ self.reclaim_unassigned_partitions_on_boot(assignment, partition_count);
+ }
+
+ /// Re-produce every staged `cf_pending_transfers` entry for the owned partitions at boot,
+ /// without spawning workers. An idle partition never spawns a worker — and the periodic redrive
+ /// routes through `route_to_owned` → `NoWorker` for worker-less partitions, so it never fires for
+ /// one either; this paginates the whole outbox directly and re-produces every entry regardless of
+ /// backlog size.
+ ///
+ /// Produce + clear only — no `mark_processed`: a fresh tenure starts at `dispatched_offset == 0`
+ /// so marking would clamp to 0 and trip `CappedAheadOfDispatch`. A per-entry produce failure
+ /// leaves that entry for the periodic redrive. Must run after the boot staleness reconcile.
+ pub async fn eager_redrive_pending_transfers_on_boot(&self, assignment: &HashSet<i32>) {
+ for &partition in assignment {
+ let Some(store_partition) = partition_to_store_id(partition) else {
+ warn!(
+ partition,
+ "eager boot redrive: partition out of u16 range; skipping"
+ );
+ continue;
+ };
+ let recovered = self
+ .eager_redrive_partition(partition, store_partition, EAGER_BOOT_REDRIVE_PAGE_SIZE)
+ .await;
+ if recovered > 0 {
+ counter!(DURABLE_RESTORE_PENDING_TRANSFERS_RECOVERED_PARTITIONS_TOTAL).increment(1);
+ info!(
+ partition,
+ recovered, "eager boot redrive: re-produced stranded pending transfers",
+ );
+ }
+ }
+ }
+
+ /// Paginate one partition's `cf_pending_transfers` outbox, re-producing and clearing each entry;
+ /// returns the count re-produced. `page_size` is a parameter so tests can force multi-page
+ /// pagination without seeding a full [`EAGER_BOOT_REDRIVE_PAGE_SIZE`] page.
+ async fn eager_redrive_partition(
+ &self,
+ partition: i32,
+ store_partition: u16,
+ page_size: usize,
+ ) -> usize {
+ let mut cursor: Option<Vec<u8>> = None;
+ let mut recovered = 0usize;
+ loop {
+ let page = match self.store.scan_pending_transfers(
+ store_partition,
+ cursor.as_deref(),
+ page_size,
+ ) {
+ Ok(page) => page,
+ Err(error) => {
+ warn!(
+ partition,
+ error = %error,
+ "eager boot redrive: pending-transfer scan failed; the periodic redrive retries it",
+ );
+ break;
+ }
+ };
+ if page.is_empty() {
+ break;
+ }
+ let page_len = page.len();
+ // Advance past the whole page before processing it: an entry left in place (decode or
+ // produce failure) is never re-scanned this boot, so the loop always terminates and the
+ // stranded entry defers to the periodic redrive.
+ let next_cursor = page.last().map(|(key, _)| key.encode().to_vec());
+
+ for (key, bytes) in page {
+ let pending = match PendingTransfer::decode(&bytes) {
+ Ok(pending) => pending,
+ Err(error) => {
+ warn!(
+ partition,
+ team_id = key.team_id,
+ old_person = %key.old_person,
+ error = %error,
+ "eager boot redrive: undecodable pending transfer; leaving it in place",
+ );
+ continue;
+ }
+ };
+ let team_id = pending.transfer.team_id;
+ let old_person = pending.transfer.old_person_uuid;
+ let acks = self
+ .merge
+ .transfer_sink
+ .produce(vec![pending.transfer])
+ .await;
+ if !acks.iter().all(Result::is_ok) {
+ warn!(
+ partition,
+ team_id,
+ old_person = %old_person,
+ "eager boot redrive: transfer produce failed; leaving the entry for the periodic redrive",
+ );
+ continue;
+ }
+ if let Err(error) = self.store.clear_pending_transfer(&key) {
+ warn!(
+ partition,
+ team_id,
+ old_person = %old_person,
+ error = %error,
+ "eager boot redrive: outbox clear failed after an acked produce; the periodic redrive re-produces it idempotently",
+ );
+ }
+ recovered += 1;
+ }
+
+ cursor = next_cursor;
+ if page_len < page_size {
+ break;
+ }
+ }
+ recovered
+ }
+
+ fn tracker(&self) -> &OffsetTracker {
+ self.tracker.as_ref()
+ }
+
+ fn owned_committable_offsets(&self) -> HashMap<i32, i64> {
+ self.tracker
+ .committable_offsets()
+ .into_iter()
+ .filter(|(partition, _)| self.owned.contains(partition))
+ .collect()
+ }
+
+ /// Drain all workers and return the tracker for the caller's final sync commit.
+ async fn shutdown(&self) -> Arc<OffsetTracker> {
+ self.draining.store(true, Ordering::SeqCst);
+ self.router.clear();
+ let partitions: Vec<i32> = self.workers.iter().map(|entry| *entry.key()).collect();
+ for partition in partitions {
+ if let Some((_, worker)) = self.workers.remove(&partition) {
+ if let Err(err) = worker.join().await {
+ warn!(partition, error = %err, "stage 1 worker panicked during shutdown drain");
+ }
+ }
+ }
+ self.tracker.clone()
+ }
+}
+
+#[derive(Debug, Default)]
+struct DispatchStats {
+ dispatched: u64,
+ not_owned_skipped: u64,
+}
+
+fn partition_to_store_id(partition: i32) -> Option<u16> {
+ u16::try_from(partition).ok()
+}
+
+/// Returns `true` once the same non-empty assignment is seen on two consecutive polls. An empty or
+/// changing assignment is not yet settled; a cooperative-incremental assign re-baselines until stable.
+fn boot_assignment_settled(assignment: &HashSet<i32>, prev: &mut Option<HashSet<i32>>) -> bool {
+ if assignment.is_empty() {
+ return false;
+ }
+ if prev.as_ref() != Some(assignment) {
+ *prev = Some(assignment.clone());
+ return false;
+ }
+ true
+}
+
+/// The `cohort_stream_events` group consumer: consume, route, commit.
+///
+/// Uses a raw `StreamConsumer` with manual commit because the per-partition `OffsetTracker`
+/// commits a `TopicPartitionList` that the `common-kafka` wrapper can't express.
+pub struct CohortStreamEventsConsumer {
+ consumer: StreamConsumer<CohortConsumerContext>,
+ topic: String,
+ dispatcher: Arc<EventDispatcher>,
+ handle: Handle,
+ recv_batch_size: usize,
+ recv_batch_timeout: Duration,
+ offset_commit_interval: Duration,
+ /// Partition count of `cohort_stream_events`, used by the boot staleness sweep.
+ events_partitions: usize,
+ #[allow(dead_code)]
+ consumer_command_rx: ConsumerCommandReceiver,
+ /// Offset manifest from a disaster restore. When set, the consume loop runs a one-shot seek of
+ /// the events topic to the manifest positions once the boot assignment settles.
+ restore_manifest: Option<OffsetManifest>,
+}
+
+impl CohortStreamEventsConsumer {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ consumer: StreamConsumer<CohortConsumerContext>,
+ topic: String,
+ dispatcher: Arc<EventDispatcher>,
+ handle: Handle,
+ recv_batch_size: usize,
+ recv_batch_timeout: Duration,
+ offset_commit_interval: Duration,
+ events_partitions: usize,
+ consumer_command_rx: ConsumerCommandReceiver,
+ restore_manifest: Option<OffsetManifest>,
+ ) -> Self {
+ Self {
+ consumer,
+ topic,
+ dispatcher,
+ handle,
+ recv_batch_size,
+ recv_batch_timeout,
+ offset_commit_interval,
+ events_partitions,
+ consumer_command_rx,
+ restore_manifest,
+ }
+ }
+
+ /// Run until the lifecycle handle signals shutdown. Commit is deadline-driven, not a `select!`
+ /// arm, to avoid cancelling an in-flight `consume_batch` and dropping buffered events.
+ pub async fn process(self) {
+ let _guard = self.handle.process_scope();
+ info!(topic = %self.topic, "cohort_stream_events consume loop starting");
+
+ let mut commit_deadline = tokio::time::Instant::now() + self.offset_commit_interval;
+ // One-shot guards; each pre-marked done when its gate is off, keeping the non-durable path unchanged.
+ let mut boot_sweep_done = !self.dispatcher.durable_restore_enabled();
+ let mut eager_redrive_done = !self.dispatcher.durable_restore_enabled();
+ let mut restore_seek_done = self.restore_manifest.is_none();
+ let mut prev_assignment: Option<HashSet<i32>> = None;
+
+ loop {
+ tokio::select! {
+ biased;
+ _ = self.handle.shutdown_recv() => {
+ info!("shutdown signal received, stopping consume loop");
+ break;
+ }
+ outcome = self.consume_batch() => {
+ // Sweep before dispatching, so the reclaim never races a worker spawn.
+ if !boot_sweep_done {
+ boot_sweep_done = self.run_boot_staleness_sweep(&mut prev_assignment);
+ }
+ // Redrive after the boot sweep settles. Skip dispatching this batch so boot
+ // recovery completes before any fold work.
+ if !eager_redrive_done && boot_sweep_done {
+ let owned: HashSet<i32> =
+ self.dispatcher.owned_partitions().into_iter().collect();
+ self.dispatcher
+ .eager_redrive_pending_transfers_on_boot(&owned)
+ .await;
+ eager_redrive_done = true;
+ continue;
+ }
+ // Seek after the boot sweep settles. Skip dispatching the pre-seek batch so no
+ // ahead-of-seek event is folded first. Fail-stop: retry without dispatching on
+ // failure; never fold from the broker-stored offset.
+ if !restore_seek_done && boot_sweep_done {
+ restore_seek_done = self.run_restore_seek();
+ continue;
+ }
+ self.handle_outcome(outcome).await;
+ let now = tokio::time::Instant::now();
+ if now >= commit_deadline {
+ fsync_then_commit(
+ self.dispatcher.store(),
+ &self.consumer,
+ self.dispatcher.tracker(),
+ self.dispatcher.owned_committable_offsets(),
+ &self.topic,
+ CommitMode::Async,
+ );
+ commit_deadline = now + self.offset_commit_interval;
+ }
+ }
+ }
+ }
+
+ let tracker = self.dispatcher.shutdown().await;
+ let offsets = self.dispatcher.owned_committable_offsets();
+ fsync_then_commit(
+ self.dispatcher.store(),
+ &self.consumer,
+ &tracker,
+ offsets,
+ &self.topic,
+ CommitMode::Sync,
+ );
+ info!(topic = %self.topic, "cohort_stream_events consume loop stopped");
+ }
+
+ /// Returns `true` once the boot snapshot is reconciled, `false` while the assignment is unsettled.
+ fn run_boot_staleness_sweep(&self, prev: &mut Option<HashSet<i32>>) -> bool {
+ let assignment = self.assigned_partitions();
+ if !boot_assignment_settled(&assignment, prev) {
+ return false;
+ }
+ self.dispatcher
+ .reconcile_boot_assignment(&assignment, self.events_partitions);
+ true
+ }
+
+ /// Seek the owned events partitions to the manifest's committed offsets. A no-op when
+ /// `restore_manifest` is `None`. Returns `true` only once every targeted partition is sought;
+ /// `false` on any failure so the caller retries without dispatching. A persistent failure stalls
+ /// and surfaces as consumer lag, never silent event loss.
+ fn run_restore_seek(&self) -> bool {
+ let Some(manifest) = self.restore_manifest.as_ref() else {
+ return true;
+ };
+ let owned = self.dispatcher.owned_partitions();
+ let Some((tpl, sought)) = restore_seek_tpl(&self.topic, &owned, manifest) else {
+ info!(
+ topic = %self.topic,
+ "restore seek: manifest carried no committed offset for any owned events partition; nothing to seek",
+ );
+ return true;
+ };
+
+ let result = match self.consumer.seek_partitions(tpl, RESTORE_SEEK_TIMEOUT) {
+ Ok(result) => result,
+ Err(err) => {
+ warn!(
+ topic = %self.topic,
+ offsets = ?sought,
+ error = %err,
+ "restore seek failed; holding off dispatch and retrying (no progress until it succeeds)",
+ );
+ return false;
+ }
+ };
+
+ let failed: Vec<i32> = result
+ .elements_for_topic(&self.topic)
+ .iter()
+ .filter(|elem| elem.error().is_err())
+ .map(|elem| elem.partition())
+ .collect();
+ if !failed.is_empty() {
+ warn!(
+ topic = %self.topic,
+ failed_partitions = ?failed,
+ offsets = ?sought,
+ "restore seek failed for some partitions; holding off dispatch and retrying (no progress until it succeeds)",
+ );
+ return false;
+ }
+
+ info!(
+ topic = %self.topic,
+ partitions = sought.len(),
+ offsets = ?sought,
+ "restore seek: sought owned events partitions to their committed manifest offsets",
+ );
+ true
+ }
+
+ fn assigned_partitions(&self) -> HashSet<i32> {
+ match self.consumer.assignment() {
+ Ok(tpl) => tpl
+ .elements_for_topic(&self.topic)
+ .iter()
+ .map(|elem| elem.partition())
+ .collect(),
+ Err(err) => {
+ warn!(error = %err, "failed to read consumer assignment for the boot staleness sweep");
+ HashSet::new()
+ }
+ }
+ }
+
+ async fn handle_outcome(&self, outcome: ConsumeOutcome) {
+ histogram!(COHORT_STREAM_CONSUME_BATCH_SIZE).record(outcome.events.len() as f64);
+ if !outcome.events.is_empty() {
+ counter!(COHORT_STREAM_EVENTS_CONSUMED).increment(outcome.events.len() as u64);
+ }
+ if outcome.deserialize_errors > 0 {
+ counter!(COHORT_STREAM_DESERIALIZE_ERRORS).increment(outcome.deserialize_errors);
+ }
+ if outcome.empty_payloads > 0 {
+ counter!(COHORT_STREAM_EMPTY_PAYLOAD).increment(outcome.empty_payloads);
+ }
+
+ self.dispatcher.dispatch(outcome.events).await;
+
+ if outcome.transport_error {
+ tokio::time::sleep(RECV_ERROR_BACKOFF).await;
+ } else {
+ self.handle.report_healthy();
+ }
+ }
+
+ async fn consume_batch(&self) -> ConsumeOutcome {
+ let mut outcome = ConsumeOutcome {
+ events: Vec::with_capacity(self.recv_batch_size),
+ deserialize_errors: 0,
+ empty_payloads: 0,
+ transport_error: false,
+ };
+
+ tokio::select! {
+ _ = tokio::time::sleep(self.recv_batch_timeout) => {}
+ _ = async {
+ while outcome.events.len() < self.recv_batch_size {
+ match self.consumer.recv().await {
+ Ok(message) => {
+ let partition = message.partition();
+ let offset = message.offset();
+ match message.payload() {
+ None => {
+ outcome.empty_payloads += 1;
+ debug!(
+ partition, offset,
+ "skipping cohort_stream_events message with empty payload",
+ );
+ }
+ Some(payload) => match serde_json::from_slice::<CohortStreamEvent>(payload) {
+ Ok(event) => outcome.events.push(ConsumedEvent { event, partition, offset }),
+ Err(err) => {
+ outcome.deserialize_errors += 1;
+ debug!(
+ partition, offset, error = %err,
+ "skipping undeserializable cohort_stream_events message",
+ );
+ }
+ },
+ }
+ }
+ Err(err) => {
+ outcome.transport_error = true;
+ counter!(COHORT_STREAM_KAFKA_RECV_ERRORS).increment(1);
+ warn!(error = %err, "kafka recv error while consuming cohort_stream_events");
+ break;
+ }
+ }
+ }
+ } => {}
+ }
+
+ outcome
+ }
+}
+
+struct ConsumeOutcome {
+ events: Vec<ConsumedEvent>,
+ deserialize_errors: u64,
+ empty_payloads: u64,
+ transport_error: bool,
+}
+
+/// Build the seek list for a disaster restore: owned partitions with a committed offset in
+/// `manifest`, at `Offset::Offset(next_offset)` (next-to-consume convention). Returns the TPL and
+/// logged pairs, or `None` when no owned partition has a manifest offset.
+fn restore_seek_tpl(
+ topic: &str,
+ owned: &[i32],
+ manifest: &OffsetManifest,
+) -> Option<(TopicPartitionList, Vec<(i32, i64)>)> {
+ let mut tpl = TopicPartitionList::new();
+ let mut sought: Vec<(i32, i64)> = Vec::new();
+ for &partition in owned {
+ let Some(next_offset) = manifest.offset_for(topic, partition) else {
+ continue;
+ };
+ if let Err(err) = tpl.add_partition_offset(topic, partition, Offset::Offset(next_offset)) {
+ warn!(topic, partition, next_offset, error = %err, "skipping partition in restore seek list");
+ continue;
+ }
+ sought.push((partition, next_offset));
+ }
+ (tpl.count() > 0).then_some((tpl, sought))
+}
+
+pub(crate) fn build_commit_tpl(topic: &str, offsets: &HashMap<i32, i64>) -> TopicPartitionList {
+ let mut tpl = TopicPartitionList::new();
+ for (&partition, &next_offset) in offsets {
+ if let Err(err) = tpl.add_partition_offset(topic, partition, Offset::Offset(next_offset)) {
+ warn!(topic, partition, next_offset, error = %err, "skipping partition in commit list");
+ }
+ }
+ tpl
+}
+
+pub(crate) fn commit_offsets<C: ConsumerContext>(
+ consumer: &StreamConsumer<C>,
+ tracker: &OffsetTracker,
+ offsets: HashMap<i32, i64>,
+ topic: &str,
+ mode: CommitMode,
+) {
+ if offsets.is_empty() {
+ return;
+ }
+ let tpl = build_commit_tpl(topic, &offsets);
+ match consumer.commit(&tpl, mode) {
+ Ok(()) => {
+ counter!(COHORT_STREAM_OFFSET_COMMITS).increment(1);
+ for (&partition, &next_offset) in &offsets {
+ tracker.mark_committed(partition, next_offset);
+ }
+ }
+ Err(err) => {
+ counter!(COHORT_STREAM_OFFSET_COMMIT_ERRORS).increment(1);
+ warn!(topic, error = %err, "failed to commit consumer offsets");
+ }
+ }
+}
+
+/// fsync the store's WAL before committing offsets, upholding `committed <= durable`. Unconditional
+/// so reopen-live is safe whenever the durability gate is flipped. A fsync error skips the commit.
+pub(crate) fn fsync_then_commit<C: ConsumerContext>(
+ store: &CohortStore,
+ consumer: &StreamConsumer<C>,
+ tracker: &OffsetTracker,
+ offsets: HashMap<i32, i64>,
+ topic: &str,
+ mode: CommitMode,
+) {
+ if offsets.is_empty() {
+ return;
+ }
+ if store.flush_wal_sync().is_err() {
+ return; // store counted the error; skip commit so `committed` never outruns `durable`
+ }
+ commit_offsets(consumer, tracker, offsets, topic, mode);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::UTC;
+ use serde_json::json;
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder, TeamId};
+ use crate::merge::transfer::{
+ MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, TransferLeaf,
+ MERGE_EVENT_SCHEMA_VERSION,
+ };
+ use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};
+ use crate::producer::{
+ CaptureSink, CaptureStreamEventSink, CaptureTransferSink, MembershipStatus,
+ };
+ use crate::stage1::state::AppliedOffsets;
+ use crate::stage1::{Stage1State, StatefulRecord};
+ use crate::store::{
+ LeafStateKey, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage1Key, StoreConfig,
+ TombstoneKey,
+ };
+ use crate::workers::TransferRetryPolicy;
+
+ const TEAM: i32 = 7;
+ const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";
+ const BASE_TS: &str = "2026-05-26 12:34:56.789000";
+
+ #[test]
+ fn deserializes_a_full_shuffler_envelope() {
+ let value = json!({
+ "team_id": 42,
+ "person_id": "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ "distinct_id": "[email protected]",
+ "uuid": "0192f00d-f00d-f00d-f00d-f00df00df00d",
+ "event": "$pageview",
+ "timestamp": "2026-05-26 12:34:56.789000",
+ "properties": "{\"$browser\":\"Chrome\"}",
+ "person_properties": "{\"email\":\"[email protected]\"}",
+ "elements_chain": "a:href=\"/x\"",
+ "source_offset": 12345,
+ "source_partition": 17,
+ });
+
+ let event: CohortStreamEvent = serde_json::from_value(value).unwrap();
+ assert_eq!(event.team_id, 42);
+ assert_eq!(event.person_id, "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee");
+ assert_eq!(event.event, "$pageview");
+ assert_eq!(
+ event.properties.as_deref(),
+ Some("{\"$browser\":\"Chrome\"}")
+ );
+ assert_eq!(event.source_offset, 12345);
+ assert_eq!(event.source_partition, 17);
+ }
+
+ #[test]
+ fn null_optional_payloads_deserialize_to_none() {
+ let value = json!({
+ "team_id": 1,
+ "person_id": "p",
+ "distinct_id": "d",
+ "uuid": "u",
+ "event": "$pageview",
+ "timestamp": "2026-05-26 12:34:56.789000",
+ "properties": null,
+ "person_properties": null,
+ "elements_chain": null,
+ "source_offset": 0,
+ "source_partition": 0,
+ });
+
+ let event: CohortStreamEvent = serde_json::from_value(value).unwrap();
+ assert!(event.properties.is_none());
+ assert!(event.person_properties.is_none());
+ assert!(event.elements_chain.is_none());
+ }
+
+ #[test]
+ fn shuffler_envelope_without_redirected_from_deserializes_to_none() {
+ let value = json!({
+ "team_id": 7,
+ "person_id": "p",
+ "distinct_id": "d",
+ "uuid": "u",
+ "event": "$pageview",
+ "timestamp": BASE_TS,
+ "properties": null,
+ "person_properties": null,
+ "elements_chain": null,
+ "source_offset": 0,
+ "source_partition": 0,
+ });
+ let event: CohortStreamEvent = serde_json::from_slice(&serde_json::to_vec(&value).unwrap())
+ .expect("an envelope without redirected_from deserializes");
+ assert!(event.redirected_from.is_none());
+ assert_eq!(event.redirect_hops, 0);
+ }
+
+ #[test]
+ fn redirected_from_round_trips_for_the_c2_re_produce() {
+ let event = matching_event(Uuid::from_u128(1), 3, 9);
+ let with_origin = CohortStreamEvent {
+ redirected_from: Some("01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string()),
+ ..event
+ };
+ let bytes = serde_json::to_vec(&with_origin).unwrap();
+ let decoded: CohortStreamEvent = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(
+ decoded.redirected_from.as_deref(),
+ Some("01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee"),
+ );
+ }
+
+ #[test]
+ fn envelope_round_trips_through_wire_bytes() {
+ let envelope = json!({
+ "team_id": 7,
+ "person_id": "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ "distinct_id": "d",
+ "uuid": "u",
+ "event": "$pageview",
+ "timestamp": BASE_TS,
+ "properties": "{}",
+ "person_properties": null,
+ "elements_chain": null,
+ "source_offset": 99,
+ "source_partition": 3,
+ });
+ let bytes = serde_json::to_vec(&envelope).unwrap();
+
+ let event: CohortStreamEvent = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(event.team_id, 7);
+ assert_eq!(event.source_offset, 99);
+ assert_eq!(event.source_partition, 3);
+ assert!(event.person_properties.is_none());
+ }
+
+ #[test]
+ fn build_commit_tpl_maps_each_partition_to_its_next_offset() {
+ let mut offsets = HashMap::new();
+ offsets.insert(3, 100);
+ offsets.insert(7, 250);
+
+ let tpl = build_commit_tpl("cohort_stream_events", &offsets);
+
+ assert_eq!(tpl.count(), 2);
+ assert_eq!(
+ tpl.find_partition("cohort_stream_events", 3)
+ .unwrap()
+ .offset(),
+ Offset::Offset(100),
+ );
+ assert_eq!(
+ tpl.find_partition("cohort_stream_events", 7)
+ .unwrap()
+ .offset(),
+ Offset::Offset(250),
+ );
+ }
+
+ #[test]
+ fn build_commit_tpl_for_no_offsets_is_empty() {
+ let tpl = build_commit_tpl("cohort_stream_events", &HashMap::new());
+ assert_eq!(tpl.count(), 0);
+ }
+
+ fn manifest_for(topic: &str, committed: &[(i32, i64)]) -> OffsetManifest {
+ let tracker = OffsetTracker::new();
+ let owned: Vec<i32> = committed.iter().map(|(p, _)| *p).collect();
+ for &(partition, next) in committed {
+ tracker.mark_dispatched(partition, next);
+ let _ = tracker.mark_processed(partition, next);
+ tracker.mark_committed(partition, next);
+ }
+ OffsetManifest::capture(&owned, &[(topic, &tracker)])
+ }
+
+ #[test]
+ fn restore_seek_tpl_targets_owned_partitions_with_a_manifest_offset() {
+ let manifest = manifest_for("cohort_stream_events", &[(0, 100), (3, 250)]);
+ let (tpl, sought) = restore_seek_tpl("cohort_stream_events", &[0, 3, 7], &manifest)
+ .expect("a non-empty seek");
+ assert_eq!(tpl.count(), 2);
+ assert_eq!(
+ tpl.find_partition("cohort_stream_events", 0)
+ .unwrap()
+ .offset(),
+ Offset::Offset(100),
+ );
+ assert_eq!(
+ tpl.find_partition("cohort_stream_events", 3)
+ .unwrap()
+ .offset(),
+ Offset::Offset(250),
+ );
+ assert!(tpl.find_partition("cohort_stream_events", 7).is_none());
+ let mut sought_sorted = sought;
+ sought_sorted.sort_unstable();
+ assert_eq!(sought_sorted, vec![(0, 100), (3, 250)]);
+ }
+
+ #[test]
+ fn restore_seek_tpl_is_none_for_an_empty_manifest_topic() {
+ let empty = manifest_for("cohort_stream_events", &[]);
+ assert!(restore_seek_tpl("cohort_stream_events", &[0, 1, 2], &empty).is_none());
+ }
+
+ #[test]
+ fn restore_seek_tpl_is_none_when_no_owned_partition_matches() {
+ let manifest = manifest_for("cohort_stream_events", &[(0, 100), (3, 250)]);
+ assert!(restore_seek_tpl("cohort_stream_events", &[5, 9], &manifest).is_none());
+ }
+
+ #[test]
+ fn restore_seek_tpl_is_none_for_a_missing_topic() {
+ let manifest = manifest_for("cohort_stream_events", &[(0, 100)]);
+ assert!(restore_seek_tpl("person_merge_events", &[0], &manifest).is_none());
+ }
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let config = StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ };
+ let store = CohortStore::open(&config).expect("open store");
+ (dir, store)
+ }
+
+ fn behavioral_catalog() -> Arc<CatalogHandle> {
+ let behavioral_leaf = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ });
+ let cohort = json!({ "properties": { "type": "AND", "values": [behavioral_leaf] } });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(TEAM), &cohort)
+ .expect("add cohort");
+ let filters = builder.freeze(UTC);
+ Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ filters,
+ )])))
+ }
+
+ fn dispatcher_with(store: &CohortStore, catalog: Arc<CatalogHandle>) -> EventDispatcher {
+ dispatcher_and_sink(store, catalog).0
+ }
+
+ fn dispatcher_and_sink(
+ store: &CohortStore,
+ catalog: Arc<CatalogHandle>,
+ ) -> (EventDispatcher, Arc<CaptureSink>) {
+ let (dispatcher, sink, _, _) = dispatcher_full(
+ store,
+ catalog,
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+ (dispatcher, sink)
+ }
+
+ fn dispatcher_full(
+ store: &CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: CaptureSink,
+ transfer_sink: CaptureTransferSink,
+ ) -> (
+ EventDispatcher,
+ Arc<CaptureSink>,
+ Arc<CaptureTransferSink>,
+ Arc<MergeWorkerDeps>,
+ ) {
+ let sink = Arc::new(sink);
+ let transfer_sink = Arc::new(transfer_sink);
+ let transfer_sink_dyn: Arc<dyn crate::producer::TransferSink> = transfer_sink.clone();
+ let merge = Arc::new(MergeWorkerDeps {
+ transfer_sink: transfer_sink_dyn,
+ stream_event_sink: Arc::new(CaptureStreamEventSink::new()),
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: crate::workers::DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink: Arc::new(crate::producer::CaptureCascadeSink::new()),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: crate::workers::CascadeConfig::default(),
+ partition_count: COHORT_PARTITION_COUNT,
+ });
+ let dispatcher = EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store.clone(),
+ catalog,
+ sink.clone(),
+ merge.clone(),
+ );
+ (dispatcher, sink, transfer_sink, merge)
+ }
+
+ fn behavioral_lsk(catalog: &CatalogHandle) -> LeafStateKey {
+ let snapshot = catalog.load();
+ let team = snapshot.team(TeamId(TEAM)).expect("team in catalog");
+ team.by_condition_to_lsk[&BEHAVIORAL_HASH][0]
+ }
+
+ fn person(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+ }
+
+ fn matching_event(
+ person: Uuid,
+ source_partition: i32,
+ source_offset: i64,
+ ) -> CohortStreamEvent {
+ CohortStreamEvent {
+ team_id: TEAM,
+ person_id: person.to_string(),
+ distinct_id: "d".to_string(),
+ uuid: Uuid::from_u128(0xE0_0000 + source_offset as u128).to_string(),
+ event: "$pageview".to_string(),
+ timestamp: BASE_TS.to_string(),
+ properties: Some("{}".to_string()),
+ person_properties: None,
+ elements_chain: None,
+ source_offset,
+ source_partition,
+ redirected_from: None,
+ redirect_hops: 0,
+ }
+ }
+
+ fn consumed(person: Uuid, topic_partition: i32, topic_offset: i64) -> ConsumedEvent {
+ ConsumedEvent {
+ event: matching_event(person, topic_partition, topic_offset),
+ partition: topic_partition,
+ offset: topic_offset,
+ }
+ }
+
+ fn behavioral_state(
+ store: &CohortStore,
+ partition_id: u16,
+ person: Uuid,
+ lsk: LeafStateKey,
+ ) -> Option<Stage1State> {
+ let key = Stage1Key {
+ partition_id,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person,
+ };
+ store
+ .get_stage1(&key)
+ .unwrap()
+ .map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)
+ }
+
+ fn seed_slice(store: &CohortStore, partition: u16, lsk: LeafStateKey) {
+ store
+ .write_batch(|b| {
+ b.put_stage1(
+ &Stage1Key {
+ partition_id: partition,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person(1),
+ },
+ b"state",
+ )
+ })
+ .unwrap();
+ }
+
+ fn slice_present(store: &CohortStore, partition: u16, lsk: LeafStateKey) -> bool {
+ store
+ .get_stage1(&Stage1Key {
+ partition_id: partition,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person(1),
+ })
+ .unwrap()
+ .is_some()
+ }
+
+ #[tokio::test]
+ async fn reclaim_stale_slice_wipes_move_in_keeps_boot_partition() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let dispatcher = dispatcher_with(&store, catalog);
+ seed_slice(&store, 5, lsk);
+ seed_slice(&store, 6, lsk);
+
+ // Boot snapshot includes 6 (reopen-live) but not 5 (post-boot move-in); partition_count 5
+ // keeps the boot sweep off both 5 and 6.
+ dispatcher.reconcile_boot_assignment(&[6].into_iter().collect(), 5);
+
+ dispatcher.reclaim_stale_slice(5);
+ assert!(
+ !slice_present(&store, 5, lsk),
+ "a post-boot move-in has its stale slice wiped",
+ );
+
+ dispatcher.reclaim_stale_slice(6);
+ assert!(
+ slice_present(&store, 6, lsk),
+ "a boot-snapshot partition keeps its slice (the boot sweep is the authority)",
+ );
+ }
+
+ #[tokio::test]
+ async fn ensure_worker_wipes_stale_move_in_slice_before_spawn() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let dispatcher = dispatcher_with(&store, catalog);
+ dispatcher.enable_durable_restore();
+
+ seed_slice(&store, 5, lsk);
+ // Boot excludes 5 (a post-boot move-in); partition_count 5 keeps the boot sweep off 5.
+ dispatcher.reconcile_boot_assignment(&[6].into_iter().collect(), 5);
+ dispatcher.assign_partition(5);
+
+ dispatcher.ensure_worker(5);
+ assert!(
+ dispatcher.workers.contains_key(&5),
+ "the moved-in partition spawned a worker",
+ );
+ assert!(
+ !slice_present(&store, 5, lsk),
+ "the stale slice was wiped before the worker read it (cold rebuild)",
+ );
+
+ // A second delivery finds the worker already live: the Entry::Occupied arm is a no-op, so a
+ // freshly-written (current, not stale) slice is never re-wiped.
+ seed_slice(&store, 5, lsk);
+ dispatcher.ensure_worker(5);
+ assert!(
+ slice_present(&store, 5, lsk),
+ "an existing worker keeps its current slice (ensure_worker does not re-reclaim)",
+ );
+
+ dispatcher.shutdown().await;
+ }
+
+ #[tokio::test]
+ async fn ensure_worker_with_durable_restore_off_keeps_slice() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let dispatcher = dispatcher_with(&store, catalog);
+ // Durable restore left off: ensure_worker must never reclaim — wipe-on-start handles staleness.
+
+ seed_slice(&store, 5, lsk);
+ dispatcher.reconcile_boot_assignment(&[6].into_iter().collect(), 5);
+ dispatcher.assign_partition(5);
+
+ dispatcher.ensure_worker(5);
+ assert!(dispatcher.workers.contains_key(&5), "the worker spawned");
+ assert!(
+ slice_present(&store, 5, lsk),
+ "with durable restore off, ensure_worker leaves the on-disk slice untouched",
+ );
+
+ dispatcher.shutdown().await;
+ }
+
+ #[test]
+ fn boot_assignment_settled_requires_a_stable_non_empty_assignment() {
+ let mut prev: Option<HashSet<i32>> = None;
+
+ assert!(!boot_assignment_settled(&HashSet::new(), &mut prev));
+ assert_eq!(prev, None);
+
+ let first: HashSet<i32> = [0].into_iter().collect();
+ assert!(!boot_assignment_settled(&first, &mut prev));
+ assert_eq!(prev.as_ref(), Some(&first));
+
+ let second: HashSet<i32> = [0, 1].into_iter().collect();
+ assert!(!boot_assignment_settled(&second, &mut prev));
+ assert_eq!(prev.as_ref(), Some(&second));
+
+ assert!(boot_assignment_settled(&second, &mut prev));
+ }
+
+ #[tokio::test]
+ async fn reclaim_unassigned_partitions_on_boot_wipes_only_unassigned_slices() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let dispatcher = dispatcher_with(&store, catalog);
+ for partition in 0..3u16 {
+ seed_slice(&store, partition, lsk);
+ }
+
+ let assignment: HashSet<i32> = [0, 2].into_iter().collect();
+ dispatcher.reclaim_unassigned_partitions_on_boot(&assignment, 3);
+
+ assert!(
+ slice_present(&store, 0, lsk),
+ "assigned 0 is kept (reopen-live)",
+ );
+ assert!(
+ !slice_present(&store, 1, lsk),
+ "unassigned 1 is wiped (stale slice from a previous tenure)",
+ );
+ assert!(
+ slice_present(&store, 2, lsk),
+ "assigned 2 is kept (reopen-live)",
+ );
+ }
+
+ #[tokio::test]
+ async fn dispatch_lazily_spawns_one_worker_per_partition_and_marks_next_offsets() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let dispatcher = dispatcher_with(&store, catalog);
+
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+
+ let batch = vec![
+ consumed(person(1), 0, 10),
+ consumed(person(2), 0, 11),
+ consumed(person(3), 1, 5),
+ ];
+ dispatcher.dispatch(batch).await;
+
+ assert_eq!(dispatcher.workers.len(), 2);
+
+ let tracker = dispatcher.shutdown().await;
+
+ let committable = tracker.committable_offsets();
+ assert_eq!(committable.get(&0), Some(&12));
+ assert_eq!(committable.get(&1), Some(&6));
+
+ assert!(
+ matches!(
+ behavioral_state(&store, 0, person(1), lsk),
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ),
+ "person 1 should have entered under partition 0",
+ );
+ assert!(
+ matches!(
+ behavioral_state(&store, 0, person(2), lsk),
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ),
+ "person 2 should have entered under partition 0",
+ );
+ assert!(
+ matches!(
+ behavioral_state(&store, 1, person(3), lsk),
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ),
+ "person 3 should have entered under partition 1",
+ );
+ }
+
+ #[tokio::test]
+ async fn dispatch_reuses_an_existing_worker_for_a_known_partition() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+
+ dispatcher.dispatch(vec![consumed(person(1), 0, 1)]).await;
+ assert_eq!(dispatcher.workers.len(), 1);
+
+ dispatcher.dispatch(vec![consumed(person(2), 0, 2)]).await;
+ assert_eq!(dispatcher.workers.len(), 1);
+
+ let tracker = dispatcher.shutdown().await;
+ assert_eq!(tracker.committable_offsets().get(&0), Some(&3));
+ }
+
+ #[tokio::test]
+ async fn dispatch_route_error_does_not_advance_the_offset() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(9);
+ dispatcher.ensure_worker(9);
+ dispatcher.router.remove_partition(9);
+
+ dispatcher.dispatch(vec![consumed(person(1), 9, 100)]).await;
+
+ let tracker = dispatcher.shutdown().await;
+ assert_eq!(
+ tracker.committable_offsets().get(&9),
+ None,
+ "a route error leaves the offset unmarked for Kafka to replay",
+ );
+ assert_eq!(tracker.partition_count(), 1);
+ }
+
+ #[tokio::test]
+ async fn dispatch_empty_batch_is_a_noop() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.dispatch(vec![]).await;
+
+ assert_eq!(dispatcher.workers.len(), 0);
+ assert!(dispatcher.tracker().committable_offsets().is_empty());
+ let _tracker = dispatcher.shutdown().await;
+ }
+
+ #[tokio::test]
+ async fn revoke_partition_drains_produces_evicts_and_deletes_state() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let (dispatcher, sink) = dispatcher_and_sink(&store, catalog);
+
+ dispatcher.assign_partition(0);
+ dispatcher.dispatch(vec![consumed(person(1), 0, 10)]).await;
+
+ dispatcher.revoke_partition_sync(0);
+ assert!(!dispatcher.owns(0));
+ assert_eq!(dispatcher.router.partition_count(), 1);
+
+ dispatcher.revoke_partition_drain(0).await;
+
+ let changes = sink.changes();
+ assert_eq!(changes.len(), 1);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[0].person_id, person(1).to_string());
+
+ assert_eq!(dispatcher.workers.len(), 0, "worker evicted");
+ assert_eq!(dispatcher.router.partition_count(), 0, "sender removed");
+ assert!(
+ behavioral_state(&store, 0, person(1), lsk).is_none(),
+ "the partition's state slice was deleted",
+ );
+ }
+
+ #[tokio::test]
+ async fn reassign_after_a_full_revoke_respawns_and_advances_offsets() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+ dispatcher.dispatch(vec![consumed(person(1), 0, 10)]).await;
+ dispatcher.revoke_partition_sync(0);
+ dispatcher.revoke_partition_drain(0).await;
+ assert_eq!(dispatcher.workers.len(), 0);
+
+ dispatcher.assign_partition(0);
+ dispatcher.dispatch(vec![consumed(person(2), 0, 20)]).await;
+ assert_eq!(
+ dispatcher.workers.len(),
+ 1,
+ "a reassigned partition respawns"
+ );
+
+ let tracker = dispatcher.shutdown().await;
+ assert_eq!(tracker.committable_offsets().get(&0), Some(&21));
+ }
+
+ #[tokio::test]
+ async fn rapid_revoke_then_assign_skips_cleanup_and_keeps_the_live_worker() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let dispatcher = dispatcher_with(&store, catalog);
+
+ dispatcher.assign_partition(0);
+ dispatcher.dispatch(vec![consumed(person(1), 0, 10)]).await;
+
+ dispatcher.revoke_partition_sync(0);
+ dispatcher.assign_partition(0);
+ dispatcher.revoke_partition_drain(0).await;
+
+ assert!(dispatcher.owns(0), "re-owned partition stays owned");
+ assert_eq!(dispatcher.workers.len(), 1, "worker preserved");
+ assert_eq!(dispatcher.router.partition_count(), 1, "sender preserved");
+
+ dispatcher.dispatch(vec![consumed(person(2), 0, 11)]).await;
+ let tracker = dispatcher.shutdown().await;
+ assert_eq!(tracker.committable_offsets().get(&0), Some(&12));
+ assert!(
+ behavioral_state(&store, 0, person(1), lsk).is_some(),
+ "state survived the skipped cleanup",
+ );
+ }
+
+ #[tokio::test]
+ async fn revoke_then_shutdown_drain_each_worker_exactly_once() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, sink) = dispatcher_and_sink(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+ dispatcher
+ .dispatch(vec![consumed(person(1), 0, 10), consumed(person(2), 1, 20)])
+ .await;
+ assert_eq!(dispatcher.workers.len(), 2);
+
+ dispatcher.revoke_partition_sync(0);
+ dispatcher.revoke_partition_drain(0).await;
+ assert_eq!(dispatcher.workers.len(), 1);
+
+ let tracker = dispatcher.shutdown().await;
+ assert_eq!(dispatcher.workers.len(), 0);
+
+ assert_eq!(
+ sink.changes()
+ .iter()
+ .filter(|change| change.person_id == person(1).to_string())
+ .count(),
+ 1,
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&0),
+ None,
+ "the revoked partition's offset was forgotten on drain, not left to re-commit",
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&1),
+ Some(&21),
+ "the survivor drained on shutdown",
+ );
+ }
+
+ #[tokio::test]
+ async fn revoke_partition_drain_forgets_the_offset_so_it_is_not_recommitted() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, sink) = dispatcher_and_sink(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+ dispatcher
+ .dispatch(vec![consumed(person(1), 0, 10), consumed(person(2), 1, 20)])
+ .await;
+
+ dispatcher.revoke_partition_sync(0);
+ dispatcher.revoke_partition_drain(0).await;
+
+ assert_eq!(
+ sink.changes()
+ .iter()
+ .filter(|change| change.person_id == person(1).to_string())
+ .count(),
+ 1,
+ );
+ assert_eq!(dispatcher.tracker().committable_offsets().get(&0), None);
+ assert!(!dispatcher.owned_committable_offsets().contains_key(&0));
+
+ let tracker = dispatcher.shutdown().await;
+ assert_eq!(tracker.committable_offsets().get(&1), Some(&21));
+ }
+
+ #[tokio::test]
+ async fn owned_committable_offsets_excludes_unowned_partitions() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ for (partition, next) in [(0, 11), (1, 21)] {
+ dispatcher.assign_partition(partition);
+ dispatcher.tracker().mark_dispatched(partition, next);
+ let _ = dispatcher.tracker().mark_processed(partition, next);
+ }
+ assert_eq!(dispatcher.owned_committable_offsets().get(&0), Some(&11));
+
+ dispatcher.revoke_partition_sync(0);
+
+ assert_eq!(
+ dispatcher.tracker().committable_offsets().get(&0),
+ Some(&11),
+ "the entry lingers in the tracker until the async drain forgets it",
+ );
+ assert!(!dispatcher.owned_committable_offsets().contains_key(&0));
+ assert_eq!(dispatcher.owned_committable_offsets().get(&1), Some(&21));
+ }
+
+ #[tokio::test]
+ async fn assign_and_revoke_track_ownership() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ assert!(!dispatcher.owns(3));
+ dispatcher.assign_partition(3);
+ assert!(dispatcher.owns(3));
+ dispatcher.revoke_partition_sync(3);
+ assert!(!dispatcher.owns(3));
+ }
+
+ #[tokio::test]
+ async fn owned_partitions_reflects_assign_and_revoke() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ assert!(dispatcher.owned_partitions().is_empty());
+ dispatcher.assign_partition(3);
+ dispatcher.assign_partition(7);
+ let mut owned = dispatcher.owned_partitions();
+ owned.sort_unstable();
+ assert_eq!(owned, vec![3, 7]);
+
+ dispatcher.revoke_partition_sync(3);
+ assert_eq!(dispatcher.owned_partitions(), vec![7]);
+ }
+
+ #[tokio::test]
+ async fn route_sweep_delivers_the_cutoff_to_each_owned_worker() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+ let mut rx0 = dispatcher.router.add_partition(0).unwrap();
+ let mut rx1 = dispatcher.router.add_partition(1).unwrap();
+
+ let cutoff = 1_700_000_000_000;
+ dispatcher.route_sweep(cutoff).await;
+
+ for rx in [&mut rx0, &mut rx1] {
+ let batch = rx.recv().await.expect("a sweep was routed");
+ assert_eq!(batch.len(), 1);
+ match &batch[0] {
+ ShuffleMessage::Sweep { due_before_ms } => assert_eq!(*due_before_ms, cutoff),
+ other => panic!("expected Sweep, got {other:?}"),
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn route_sweep_is_benign_for_workerless_or_no_owned_partitions() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+ dispatcher.route_sweep(123).await;
+ assert_eq!(dispatcher.workers.len(), 0, "a sweep never spawns a worker");
+ assert_eq!(
+ dispatcher.router.partition_count(),
+ 0,
+ "no channel registered"
+ );
+
+ dispatcher.revoke_partition_sync(0);
+ dispatcher.route_sweep(123).await;
+ }
+
+ #[tokio::test]
+ async fn dispatch_after_full_revoke_does_not_resurrect_partition() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let dispatcher = dispatcher_with(&store, catalog);
+
+ dispatcher.assign_partition(0);
+ dispatcher.dispatch(vec![consumed(person(1), 0, 10)]).await;
+ dispatcher.revoke_partition_sync(0);
+ dispatcher.revoke_partition_drain(0).await;
+
+ assert_eq!(dispatcher.workers.len(), 0);
+ assert_eq!(dispatcher.router.partition_count(), 0);
+ assert!(behavioral_state(&store, 0, person(1), lsk).is_none());
+
+ dispatcher.dispatch(vec![consumed(person(2), 0, 11)]).await;
+
+ assert_eq!(
+ dispatcher.workers.len(),
+ 0,
+ "no worker respawned for the unowned partition",
+ );
+ assert_eq!(
+ dispatcher.router.partition_count(),
+ 0,
+ "no sender re-registered",
+ );
+ assert!(
+ behavioral_state(&store, 0, person(2), lsk).is_none(),
+ "no fresh slice written for the reclaimed partition",
+ );
+ assert_eq!(
+ dispatcher.tracker().partition_count(),
+ 0,
+ "the dropped event raised no dispatch ceiling",
+ );
+ assert!(!dispatcher.tracker().committable_offsets().contains_key(&0));
+ assert!(!dispatcher.owned_committable_offsets().contains_key(&0));
+ }
+
+ #[tokio::test]
+ async fn ensure_worker_does_not_spawn_for_an_unowned_partition() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.ensure_worker(5);
+ assert_eq!(
+ dispatcher.workers.len(),
+ 0,
+ "no worker for an unowned partition",
+ );
+ assert_eq!(
+ dispatcher.router.partition_count(),
+ 0,
+ "no channel registered",
+ );
+
+ dispatcher.assign_partition(5);
+ dispatcher.ensure_worker(5);
+ assert_eq!(dispatcher.workers.len(), 1);
+ assert_eq!(dispatcher.router.partition_count(), 1);
+
+ let _tracker = dispatcher.shutdown().await;
+ }
+
+ #[tokio::test]
+ async fn dispatch_routes_owned_and_drops_revoked_without_raising_its_ceiling() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let dispatcher = dispatcher_with(&store, catalog);
+
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+ dispatcher.revoke_partition_sync(1);
+ dispatcher.revoke_partition_drain(1).await;
+
+ dispatcher
+ .dispatch(vec![consumed(person(1), 0, 10), consumed(person(2), 1, 20)])
+ .await;
+
+ assert_eq!(dispatcher.workers.len(), 1);
+ assert!(dispatcher.workers.contains_key(&0));
+ assert!(!dispatcher.workers.contains_key(&1));
+ assert!(
+ dispatcher.tracker().committed_offset(1).is_none(),
+ "the dropped partition's dispatch ceiling was never raised",
+ );
+
+ let tracker = dispatcher.shutdown().await;
+ assert_eq!(
+ tracker.committable_offsets().get(&0),
+ Some(&11),
+ "the owned partition advanced",
+ );
+ assert!(behavioral_state(&store, 0, person(1), lsk).is_some());
+ assert!(
+ behavioral_state(&store, 1, person(2), lsk).is_none(),
+ "the revoked partition wrote no state",
+ );
+ }
+
+ #[tokio::test]
+ async fn revoke_drain_of_a_never_spawned_partition_is_a_clean_noop() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(3);
+ dispatcher.revoke_partition_sync(3);
+ dispatcher.revoke_partition_drain(3).await;
+
+ assert_eq!(dispatcher.workers.len(), 0);
+ assert_eq!(dispatcher.router.partition_count(), 0);
+ assert!(!dispatcher.owns(3));
+ assert_eq!(dispatcher.tracker().partition_count(), 0);
+ }
+
+ #[tokio::test]
+ async fn shutdown_drains_a_late_dispatch_without_stranding_its_worker() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, sink) = dispatcher_and_sink(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+ dispatcher.dispatch(vec![consumed(person(1), 0, 10)]).await;
+ assert_eq!(
+ dispatcher.workers.len(),
+ 1,
+ "the late dispatch spawned a worker",
+ );
+
+ let tracker = dispatcher.shutdown().await;
+
+ assert_eq!(
+ dispatcher.workers.len(),
+ 0,
+ "shutdown joined the late worker rather than stranding it",
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&0),
+ Some(&11),
+ "its produced tail's offset is committable, so a crash here would replay",
+ );
+ assert_eq!(sink.changes().len(), 1, "the worker flushed before exiting");
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+ async fn concurrent_revoke_and_dispatch_never_resurrects_an_unowned_partition() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let dispatcher = Arc::new(dispatcher_with(&store, catalog));
+
+ const P: i32 = 0;
+ for round in 0..200u128 {
+ dispatcher.assign_partition(P);
+
+ let dispatch = {
+ let dispatcher = dispatcher.clone();
+ tokio::spawn(async move {
+ dispatcher
+ .dispatch(vec![consumed(person(round + 1), P, round as i64)])
+ .await;
+ })
+ };
+
+ dispatcher.revoke_partition_sync(P);
+ let drain = {
+ let dispatcher = dispatcher.clone();
+ tokio::spawn(async move {
+ dispatcher.revoke_partition_drain(P).await;
+ })
+ };
+
+ dispatch.await.unwrap();
+ drain.await.unwrap();
+
+ assert!(!dispatcher.owns(P));
+ assert!(
+ !dispatcher.workers.contains_key(&P),
+ "round {round}: a worker survived an unowned partition",
+ );
+ assert_eq!(
+ dispatcher.router.partition_count(),
+ 0,
+ "round {round}: a sender survived an unowned partition",
+ );
+ assert!(
+ behavioral_state(&store, P as u16, person(round + 1), lsk).is_none(),
+ "round {round}: a state slice survived an unowned partition",
+ );
+ }
+ }
+
+ const MERGED_AT: i64 = 1_716_800_000_000;
+
+ fn composable_catalog() -> Arc<CatalogHandle> {
+ let behavioral_leaf = |days: i64| {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": days,
+ "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ };
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": [behavioral_leaf(7)] } }),
+ )
+ .expect("add single-leaf cohort");
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": [behavioral_leaf(7), behavioral_leaf(30)] } }),
+ )
+ .expect("add composable cohort");
+ Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ builder.freeze(UTC),
+ )])))
+ }
+
+ fn absent_team_catalog() -> Arc<CatalogHandle> {
+ Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])))
+ }
+
+ fn person_hashing_to(partition: u16, start: u128) -> Uuid {
+ (start..start + 100_000)
+ .map(Uuid::from_u128)
+ .find(|p| partition_of(TeamId(TEAM), p, COHORT_PARTITION_COUNT) as u16 == partition)
+ .expect("some person hashes to the partition")
+ }
+
+ fn person_hashing_away_from(partition: u16, start: u128) -> Uuid {
+ (start..start + 100_000)
+ .map(Uuid::from_u128)
+ .find(|p| partition_of(TeamId(TEAM), p, COHORT_PARTITION_COUNT) as u16 != partition)
+ .expect("some person hashes to another partition")
+ }
+
+ fn consumed_merge(p_old: Uuid, p_new: Uuid, partition: i32, offset: i64) -> ConsumedMerge {
+ ConsumedMerge {
+ event: PersonMergeEvent {
+ team_id: TEAM,
+ old_person_uuid: p_old,
+ new_person_uuid: p_new,
+ merged_at_ms: MERGED_AT,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ },
+ partition,
+ offset,
+ }
+ }
+
+ fn behavioral_match_record() -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: MERGED_AT - 1_000,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ AppliedOffsets::default(),
+ )
+ }
+
+ fn transfer_with(
+ p_old: Uuid,
+ p_new: Uuid,
+ source: (i32, i64),
+ leaves: Vec<TransferLeaf>,
+ ) -> MergeStateTransfer {
+ MergeStateTransfer {
+ team_id: TEAM,
+ old_person_uuid: p_old,
+ new_person_uuid: p_new,
+ merged_at_ms: MERGED_AT,
+ source_partition: source.0,
+ source_offset: source.1,
+ leaves,
+ forward_hops: 0,
+ }
+ }
+
+ fn pending_key_of(partition: i32, p_old: Uuid) -> PendingTransferKey {
+ PendingTransferKey {
+ partition_id: partition as u16,
+ team_id: TEAM as u64,
+ old_person: p_old,
+ }
+ }
+
+ #[tokio::test]
+ async fn dispatch_merges_fast_path_composes_membership_and_marks_only_the_merge_tracker() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ composable_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let p_new = person(2);
+ let partition = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as i32;
+ let p_old = person(1);
+ dispatcher.assign_partition(partition);
+
+ dispatcher
+ .dispatch(vec![consumed(p_old, partition, 10)])
+ .await;
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(p_old, p_new, partition, 3)])
+ .await;
+ let tracker = dispatcher.shutdown().await;
+
+ let mut p_new_changes: Vec<(i32, MembershipStatus)> = sink
+ .changes()
+ .iter()
+ .filter(|change| change.person_id == p_new.to_string())
+ .map(|change| (change.cohort_id, change.status))
+ .collect();
+ p_new_changes.sort_unstable_by_key(|(cohort_id, _)| *cohort_id);
+ assert_eq!(
+ p_new_changes,
+ vec![
+ (1, MembershipStatus::Entered),
+ (2, MembershipStatus::Entered)
+ ],
+ );
+
+ assert!(
+ transfer_sink.transfers().is_empty(),
+ "the fast path produces no transfer",
+ );
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ Some(&4),
+ "the merge offset marks on the merge tracker",
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&partition),
+ Some(&11),
+ "the events tracker only ever carries the event's own offset",
+ );
+ assert_eq!(merge.transfer_tracker.partition_count(), 0);
+ }
+
+ #[tokio::test]
+ async fn dispatch_merges_slow_path_produces_the_transfer_clears_the_outbox_and_marks() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let p_old = person(1);
+ let partition = partition_of(TeamId(TEAM), &p_old, COHORT_PARTITION_COUNT) as i32;
+ let p_new = person_hashing_away_from(partition as u16, 100);
+ dispatcher.assign_partition(partition);
+
+ dispatcher
+ .dispatch(vec![consumed(p_old, partition, 10)])
+ .await;
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(p_old, p_new, partition, 5)])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ let transfers = transfer_sink.transfers();
+ assert_eq!(transfers.len(), 1);
+ assert_eq!(transfers[0].new_person_uuid, p_new);
+ assert_eq!(
+ (transfers[0].source_partition, transfers[0].source_offset),
+ (partition, 5),
+ "the transfer carries the merge message's source coordinates",
+ );
+ assert!(
+ !transfers[0].leaves.is_empty(),
+ "P_old's state was packaged"
+ );
+ assert!(
+ store
+ .get_pending_transfer(&pending_key_of(partition, p_old))
+ .unwrap()
+ .is_none(),
+ "the outbox was cleared after the ack",
+ );
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ Some(&6),
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn transfer_produce_retries_inline_on_the_paused_clock_and_succeeds() {
+ let wall = std::time::Instant::now();
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::failing_first(2),
+ );
+
+ let p_old = person(1);
+ let partition = partition_of(TeamId(TEAM), &p_old, COHORT_PARTITION_COUNT) as i32;
+ let p_new = person_hashing_away_from(partition as u16, 100);
+ dispatcher.assign_partition(partition);
+
+ dispatcher
+ .dispatch(vec![consumed(p_old, partition, 0)])
+ .await;
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(p_old, p_new, partition, 7)])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ assert_eq!(
+ transfer_sink.transfers().len(),
+ 1,
+ "the third attempt acked"
+ );
+ assert!(store
+ .get_pending_transfer(&pending_key_of(partition, p_old))
+ .unwrap()
+ .is_none(),);
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ Some(&8),
+ );
+ assert!(
+ wall.elapsed() < Duration::from_secs(2),
+ "backoff ran on the paused clock, not the wall clock",
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn transfer_produce_exhaustion_leaves_the_outbox_pending_and_does_not_wedge() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ catalog.clone(),
+ CaptureSink::new(),
+ CaptureTransferSink::failing_always(),
+ );
+
+ let p_old = person(1);
+ let partition = partition_of(TeamId(TEAM), &p_old, COHORT_PARTITION_COUNT) as i32;
+ let p_new = person_hashing_away_from(partition as u16, 100);
+ dispatcher.assign_partition(partition);
+
+ dispatcher
+ .dispatch(vec![consumed(p_old, partition, 0)])
+ .await;
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(p_old, p_new, partition, 10)])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ assert!(transfer_sink.transfers().is_empty());
+ let pending = PendingTransfer::decode(
+ &store
+ .get_pending_transfer(&pending_key_of(partition, p_old))
+ .unwrap()
+ .expect("the pending entry survives exhaustion"),
+ )
+ .unwrap();
+ assert_eq!(pending.transfer.old_person_uuid, p_old);
+ assert!(!pending.transfer.leaves.is_empty());
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ None,
+ "exhaustion skips the mark",
+ );
+
+ // A later merge on the same partition still processes (no wedge).
+ let dispatcher_b = EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store.clone(),
+ catalog,
+ Arc::new(CaptureSink::new()),
+ merge.clone(),
+ );
+ let p_new_b = person_hashing_to(partition as u16, 200);
+ let p_old_b = person(50);
+ dispatcher_b.assign_partition(partition);
+ dispatcher_b
+ .dispatch_merges(vec![consumed_merge(p_old_b, p_new_b, partition, 11)])
+ .await;
+ let _tracker_b = dispatcher_b.shutdown().await;
+
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ Some(&12),
+ "the subsequent merge processed and marked",
+ );
+ assert!(
+ store
+ .get_pending_transfer(&pending_key_of(partition, p_old))
+ .unwrap()
+ .is_some(),
+ "the failed merge's outbox entry is untouched",
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn redelivered_merge_re_produces_the_staged_outbox_entry_and_marks() {
+ let (_dir, store) = temp_store();
+ let budget = TransferRetryPolicy::default().max_retries as usize + 1;
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::failing_first(budget),
+ );
+
+ let p_old = person(1);
+ let partition = partition_of(TeamId(TEAM), &p_old, COHORT_PARTITION_COUNT) as i32;
+ let p_new = person_hashing_away_from(partition as u16, 100);
+ dispatcher.assign_partition(partition);
+ dispatcher
+ .dispatch(vec![consumed(p_old, partition, 0)])
+ .await;
+
+ dispatcher
+ .dispatch_merges(vec![
+ consumed_merge(p_old, p_new, partition, 10),
+ consumed_merge(p_old, p_new, partition, 10),
+ ])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ let transfers = transfer_sink.transfers();
+ assert_eq!(transfers.len(), 1, "exactly one copy was ever acked");
+ assert_eq!(
+ (transfers[0].source_partition, transfers[0].source_offset),
+ (partition, 10),
+ "the re-produced copy carries the original source coordinates (the apply-side dedup key)",
+ );
+ assert!(
+ store
+ .get_pending_transfer(&pending_key_of(partition, p_old))
+ .unwrap()
+ .is_none(),
+ "the outbox was cleared after the redelivered produce acked",
+ );
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ Some(&11),
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn route_redrive_recovers_an_inline_exhausted_transfer_within_the_tenure() {
+ let budget = TransferRetryPolicy::default().max_retries as usize + 1;
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::failing_first(budget),
+ );
+
+ let p_old = person(1);
+ let partition = partition_of(TeamId(TEAM), &p_old, COHORT_PARTITION_COUNT) as i32;
+ let p_new = person_hashing_away_from(partition as u16, 100);
+ dispatcher.assign_partition(partition);
+
+ dispatcher
+ .dispatch(vec![consumed(p_old, partition, 0)])
+ .await;
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(p_old, p_new, partition, 10)])
+ .await;
+ dispatcher.route_redrive().await;
+ let _tracker = dispatcher.shutdown().await;
+
+ let transfers = transfer_sink.transfers();
+ assert_eq!(transfers.len(), 1, "the redrive's single attempt acked");
+ assert_eq!(
+ (transfers[0].source_partition, transfers[0].source_offset),
+ (partition, 10),
+ "the redriven copy carries the original source coordinates",
+ );
+ assert!(
+ store
+ .get_pending_transfer(&pending_key_of(partition, p_old))
+ .unwrap()
+ .is_none(),
+ "the redrive cleared the outbox after the ack",
+ );
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ Some(&11),
+ "the stored merge-message coords marked past the exhausted merge",
+ );
+ }
+
+ #[tokio::test]
+ async fn route_redrive_duplicate_of_an_already_acked_transfer_applies_once() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ catalog.clone(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let p_old = person(1);
+ let partition = partition_of(TeamId(TEAM), &p_old, COHORT_PARTITION_COUNT) as i32;
+ let p_new = person_hashing_away_from(partition as u16, 100);
+ dispatcher.assign_partition(partition);
+ dispatcher
+ .dispatch(vec![consumed(p_old, partition, 0)])
+ .await;
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(p_old, p_new, partition, 5)])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+ let copy_1 = {
+ let transfers = transfer_sink.transfers();
+ assert_eq!(transfers.len(), 1, "copy 1 acked inline");
+ transfers.into_iter().next().unwrap()
+ };
+
+ // Simulate a crash between produce ack and outbox clear.
+ store
+ .write_batch(|batch| {
+ batch.put_pending_transfer(
+ &pending_key_of(partition, p_old),
+ &PendingTransfer {
+ transfer: copy_1,
+ merge_msg_partition: partition,
+ merge_msg_offset: 5,
+ }
+ .encode(),
+ )
+ })
+ .unwrap();
+
+ let dispatcher_b = EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store.clone(),
+ catalog.clone(),
+ Arc::new(CaptureSink::new()),
+ merge.clone(),
+ );
+ dispatcher_b.assign_partition(partition);
+ dispatcher_b
+ .dispatch(vec![consumed(person(2), partition, 1)])
+ .await;
+ dispatcher_b.route_redrive().await;
+ let _tracker_b = dispatcher_b.shutdown().await;
+
+ let copies = transfer_sink.transfers();
+ assert_eq!(copies.len(), 2, "the redrive minted the duplicate copy");
+ assert_eq!(copies[0], copies[1], "byte-identical source coordinates");
+ assert!(store
+ .get_pending_transfer(&pending_key_of(partition, p_old))
+ .unwrap()
+ .is_none());
+
+ let target = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as i32;
+ let apply_sink = CaptureSink::new();
+ let dispatcher_c = EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store.clone(),
+ catalog,
+ Arc::new(apply_sink.clone()),
+ merge.clone(),
+ );
+ dispatcher_c.assign_partition(target);
+ dispatcher_c
+ .dispatch_transfers(vec![
+ ConsumedTransfer {
+ transfer: copies[0].clone(),
+ partition: target,
+ offset: 0,
+ },
+ ConsumedTransfer {
+ transfer: copies[1].clone(),
+ partition: target,
+ offset: 1,
+ },
+ ])
+ .await;
+ let _tracker_c = dispatcher_c.shutdown().await;
+
+ let changes = apply_sink.changes();
+ assert_eq!(changes.len(), 1, "exactly one membership change end to end");
+ assert_eq!(changes[0].person_id, p_new.to_string());
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(
+ merge.transfer_tracker.committable_offsets().get(&target),
+ Some(&2),
+ "both copies settled (applied + AlreadyApplied)",
+ );
+ }
+
+ #[tokio::test]
+ async fn route_merge_gc_is_benign_with_no_workers_or_unowned_partitions() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+ dispatcher.route_merge_gc(1_000, 500).await;
+ assert_eq!(dispatcher.workers.len(), 0, "GC never spawns a worker");
+ assert_eq!(
+ dispatcher.router.partition_count(),
+ 0,
+ "no channel registered"
+ );
+
+ dispatcher.revoke_partition_sync(0);
+ dispatcher.route_merge_gc(1_000, 500).await;
+ }
+
+ #[tokio::test]
+ async fn route_merge_gc_round_trip_deletes_expired_markers_and_keeps_fresh_ones() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let dispatcher = dispatcher_with(&store, catalog);
+
+ let partition = 3i32;
+ let partition_id = partition as u16;
+ dispatcher.assign_partition(partition);
+
+ dispatcher
+ .dispatch(vec![consumed(person(1), partition, 0)])
+ .await;
+
+ let marker_cutoff = 10_000;
+ let tombstone_cutoff = 5_000;
+ let expired = TombstoneKey {
+ partition_id,
+ team_id: TEAM as u64,
+ person: person(10),
+ };
+ let fresh = TombstoneKey {
+ partition_id,
+ team_id: TEAM as u64,
+ person: person(11),
+ };
+ store
+ .write_batch(|batch| {
+ batch.put_tombstone(
+ &expired,
+ &Tombstone {
+ new_person: person(99),
+ merged_at_ms: tombstone_cutoff - 1,
+ }
+ .encode(),
+ );
+ batch.put_tombstone(
+ &fresh,
+ &Tombstone {
+ new_person: person(99),
+ merged_at_ms: tombstone_cutoff + 1,
+ }
+ .encode(),
+ );
+ })
+ .unwrap();
+
+ dispatcher
+ .route_merge_gc(marker_cutoff, tombstone_cutoff)
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ assert!(
+ store.get_tombstone(&expired).unwrap().is_none(),
+ "the expired tombstone was GC'd end to end",
+ );
+ assert!(
+ store.get_tombstone(&fresh).unwrap().is_some(),
+ "the in-retention tombstone survived",
+ );
+ }
+
+ #[tokio::test]
+ async fn mixed_batch_marks_each_tracker_and_membership_produce_failure_holds_only_events() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, sink, _transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::failing_first(1),
+ CaptureTransferSink::new(),
+ );
+
+ let p_new = person_hashing_to(3, 200);
+ let partition = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as i32;
+ let p_old = person(60); // no state → a fast-path no-op drain
+ dispatcher.assign_partition(partition);
+
+ dispatcher
+ .dispatch(vec![consumed(person(1), partition, 10)])
+ .await;
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(p_old, p_new, partition, 4)])
+ .await;
+ dispatcher
+ .dispatch_transfers(vec![ConsumedTransfer {
+ transfer: transfer_with(person(70), person(71), (9, 99), vec![]),
+ partition,
+ offset: 6,
+ }])
+ .await;
+ let tracker = dispatcher.shutdown().await;
+
+ assert!(
+ sink.changes().is_empty(),
+ "the failed flush recorded nothing"
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&partition),
+ None,
+ "the membership produce failure holds the events offset",
+ );
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ Some(&5),
+ "the merge offset marks independently",
+ );
+ assert_eq!(
+ merge.transfer_tracker.committable_offsets().get(&partition),
+ Some(&7),
+ "the transfer offset marks independently",
+ );
+ }
+
+ #[tokio::test]
+ async fn unowned_merge_and_transfer_are_dropped_without_raising_any_ceiling() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(person(1), person(2), 0, 5)])
+ .await;
+ dispatcher
+ .dispatch_transfers(vec![ConsumedTransfer {
+ transfer: transfer_with(person(1), person(2), (0, 5), vec![]),
+ partition: 0,
+ offset: 9,
+ }])
+ .await;
+
+ assert_eq!(dispatcher.workers.len(), 0, "no worker spawned");
+ assert_eq!(merge.merge_tracker.partition_count(), 0);
+ assert_eq!(merge.transfer_tracker.partition_count(), 0);
+ assert!(transfer_sink.transfers().is_empty());
+ let _tracker = dispatcher.shutdown().await;
+ }
+
+ #[tokio::test]
+ async fn draining_gate_rejects_all_dispatch_after_shutdown_without_hanging() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, _transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ dispatcher.assign_partition(0);
+ dispatcher.dispatch(vec![consumed(person(1), 0, 10)]).await;
+ let tracker = dispatcher.shutdown().await;
+ assert_eq!(tracker.committable_offsets().get(&0), Some(&11));
+
+ dispatcher.dispatch(vec![consumed(person(2), 0, 11)]).await;
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(person(3), person(4), 0, 5)])
+ .await;
+ dispatcher.route_sweep(123).await;
+ dispatcher.route_redrive().await;
+ dispatcher.ensure_worker(0);
+
+ assert_eq!(
+ dispatcher.workers.len(),
+ 0,
+ "no worker registered post-shutdown"
+ );
+ assert_eq!(
+ dispatcher.router.partition_count(),
+ 0,
+ "no sender registered"
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&0),
+ Some(&11),
+ "the late event neither marked nor raised a ceiling",
+ );
+ assert_eq!(merge.merge_tracker.partition_count(), 0);
+ let _tracker = dispatcher.shutdown().await;
+ }
+
+ #[tokio::test]
+ async fn post_shutdown_registration_attempt_is_refused_by_the_closed_router() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+
+ dispatcher.assign_partition(0);
+ dispatcher.dispatch(vec![consumed(person(1), 0, 10)]).await;
+ let tracker = dispatcher.shutdown().await;
+
+ assert!(
+ dispatcher.router.add_partition(0).is_none(),
+ "the closed router refuses a late registration",
+ );
+ assert_eq!(
+ dispatcher.router.partition_count(),
+ 0,
+ "no sender was inserted for the refused registration",
+ );
+ assert_eq!(dispatcher.workers.len(), 0, "no worker to strand");
+ assert_eq!(
+ tracker.committable_offsets().get(&0),
+ Some(&11),
+ "the pre-shutdown work still committed",
+ );
+ let _tracker = dispatcher.shutdown().await;
+ }
+
+ #[tokio::test]
+ async fn absent_team_merge_still_drains_tombstone_and_marker_and_marks() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ absent_team_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let p_new = person(2);
+ let partition = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as i32;
+ let p_old = person(1);
+ let lsk = LeafStateKey([0xAB; 16]);
+ let p_old_key = Stage1Key {
+ partition_id: partition as u16,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: p_old,
+ };
+ store
+ .write_batch(|batch| {
+ batch.put_stage1(&p_old_key, &behavioral_match_record().encode());
+ batch.merge_person_index(
+ &crate::store::PersonIndexKey {
+ partition_id: partition as u16,
+ team_id: TEAM as u64,
+ person_id: p_old,
+ },
+ crate::store::IndexOp::Append(lsk),
+ );
+ })
+ .unwrap();
+
+ dispatcher.assign_partition(partition);
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(p_old, p_new, partition, 9)])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ assert!(
+ store
+ .get_tombstone(&TombstoneKey {
+ partition_id: partition as u16,
+ team_id: TEAM as u64,
+ person: p_old,
+ })
+ .unwrap()
+ .is_some(),
+ "the tombstone is load-bearing even with no cohorts",
+ );
+ assert!(store
+ .get_merge_drain_applied(&MergeDrainKey {
+ partition_id: partition as u16,
+ team_id: TEAM as u64,
+ old_person: p_old,
+ merge_msg_partition: partition,
+ merge_msg_offset: 9,
+ })
+ .unwrap()
+ .is_some(),);
+ assert!(
+ store.get_stage1(&p_old_key).unwrap().is_none(),
+ "P_old's state was deleted",
+ );
+ assert!(sink.changes().is_empty(), "drifted leaves emit nothing");
+ assert!(transfer_sink.transfers().is_empty());
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ Some(&10),
+ "an absent team never holds the offset",
+ );
+ }
+
+ #[tokio::test]
+ async fn absent_team_transfer_applies_dropping_leaves_as_drift_and_marks() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, sink, _transfer_sink, merge) = dispatcher_full(
+ &store,
+ absent_team_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let p_old = person(1);
+ let p_new = person(2);
+ let lsk = LeafStateKey([0xAB; 16]);
+ dispatcher.assign_partition(0);
+ dispatcher
+ .dispatch_transfers(vec![ConsumedTransfer {
+ transfer: transfer_with(
+ p_old,
+ p_new,
+ (3, 7),
+ vec![TransferLeaf::new(lsk, behavioral_match_record())],
+ ),
+ partition: 0,
+ offset: 4,
+ }])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ assert!(
+ store
+ .get_merge_applied(&MergeAppliedKey {
+ partition_id: 0,
+ team_id: TEAM as u64,
+ new_person: p_new,
+ source_partition: 3,
+ source_offset: 7,
+ })
+ .unwrap()
+ .is_some(),
+ "the apply marker still commits so the transfer is settled, not wedged",
+ );
+ assert!(
+ store
+ .get_stage1(&Stage1Key {
+ partition_id: 0,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: p_new,
+ })
+ .unwrap()
+ .is_none(),
+ "the drifted leaf wrote no state",
+ );
+ assert!(sink.changes().is_empty());
+ assert_eq!(
+ merge.transfer_tracker.committable_offsets().get(&0),
+ Some(&5),
+ );
+ }
+
+ #[tokio::test]
+ async fn empty_transfer_is_skipped_not_produced_or_staged_and_marks() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let p_old = person(1);
+ let partition = partition_of(TeamId(TEAM), &p_old, COHORT_PARTITION_COUNT) as i32;
+ let p_new = person_hashing_away_from(partition as u16, 100);
+ dispatcher.assign_partition(partition);
+ dispatcher
+ .dispatch_merges(vec![consumed_merge(p_old, p_new, partition, 8)])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ assert!(transfer_sink.transfers().is_empty(), "nothing to ferry");
+ assert!(
+ store
+ .get_pending_transfer(&pending_key_of(partition, p_old))
+ .unwrap()
+ .is_none(),
+ "nothing staged, so nothing to clear",
+ );
+ assert!(
+ store
+ .get_tombstone(&TombstoneKey {
+ partition_id: partition as u16,
+ team_id: TEAM as u64,
+ person: p_old,
+ })
+ .unwrap()
+ .is_some(),
+ "the tombstone still commits",
+ );
+ assert_eq!(
+ merge.merge_tracker.committable_offsets().get(&partition),
+ Some(&9),
+ );
+ }
+
+ #[tokio::test]
+ async fn apply_marks_the_transfer_offset_even_when_the_membership_produce_fails() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let (dispatcher, sink, _transfer_sink, merge) = dispatcher_full(
+ &store,
+ catalog,
+ CaptureSink::failing_first(1),
+ CaptureTransferSink::new(),
+ );
+
+ let p_new = person(2);
+ dispatcher.assign_partition(0);
+ dispatcher
+ .dispatch_transfers(vec![ConsumedTransfer {
+ transfer: transfer_with(
+ person(1),
+ p_new,
+ (3, 7),
+ vec![TransferLeaf::new(lsk, behavioral_match_record())],
+ ),
+ partition: 0,
+ offset: 6,
+ }])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ assert!(
+ sink.changes().is_empty(),
+ "the failed flush recorded nothing"
+ );
+ assert!(
+ matches!(
+ behavioral_state(&store, 0, p_new, lsk),
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ),
+ "the merged state committed",
+ );
+ assert_eq!(
+ merge.transfer_tracker.committable_offsets().get(&0),
+ Some(&7),
+ );
+ }
+
+ #[tokio::test]
+ async fn dispatch_transfers_applies_emits_membership_and_marks() {
+ let (_dir, store) = temp_store();
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+ let (dispatcher, sink, _transfer_sink, merge) = dispatcher_full(
+ &store,
+ catalog,
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let p_new = person(2);
+ dispatcher.assign_partition(0);
+ dispatcher
+ .dispatch_transfers(vec![ConsumedTransfer {
+ transfer: transfer_with(
+ person(1),
+ p_new,
+ (3, 7),
+ vec![TransferLeaf::new(lsk, behavioral_match_record())],
+ ),
+ partition: 0,
+ offset: 6,
+ }])
+ .await;
+ let _tracker = dispatcher.shutdown().await;
+
+ let changes = sink.changes();
+ assert_eq!(changes.len(), 1, "P_new entered the single-leaf cohort");
+ assert_eq!(changes[0].person_id, p_new.to_string());
+ assert_eq!(changes[0].cohort_id, 1);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(
+ merge.transfer_tracker.committable_offsets().get(&0),
+ Some(&7),
+ );
+ }
+
+ fn stage_pending(
+ store: &CohortStore,
+ partition: i32,
+ p_old: Uuid,
+ p_new: Uuid,
+ merge_offset: i64,
+ ) -> (PendingTransferKey, MergeStateTransfer) {
+ let transfer = transfer_with(p_old, p_new, (partition, merge_offset), vec![]);
+ let key = pending_key_of(partition, p_old);
+ let pending = PendingTransfer {
+ transfer: transfer.clone(),
+ merge_msg_partition: partition,
+ merge_msg_offset: merge_offset,
+ };
+ store
+ .write_batch(|b| b.put_pending_transfer(&key, &pending.encode()))
+ .unwrap();
+ (key, transfer)
+ }
+
+ #[tokio::test]
+ async fn eager_boot_redrive_re_produces_a_restored_pending_transfer_without_a_worker() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let partition = 3;
+ let (key, transfer) = stage_pending(&store, partition, person(1), person(2), 41);
+ dispatcher.assign_partition(partition);
+
+ // No dispatch yet: dispatched_offset == 0, so mark_processed would clamp and trip
+ // CappedAheadOfDispatch — the eager redrive correctly skips it.
+ let owned: HashSet<i32> = [partition].into_iter().collect();
+ dispatcher
+ .eager_redrive_pending_transfers_on_boot(&owned)
+ .await;
+
+ assert_eq!(
+ transfer_sink.transfers(),
+ vec![transfer],
+ "the stranded transfer was re-produced with no worker spawned",
+ );
+ assert!(
+ store.get_pending_transfer(&key).unwrap().is_none(),
+ "the outbox entry was cleared after the ack",
+ );
+ assert!(
+ merge.merge_tracker.committable_offsets().is_empty(),
+ "the eager redrive marks no offset (would clamp to dispatched_offset==0 and trip F1)",
+ );
+ assert_eq!(
+ merge.merge_tracker.partition_count(),
+ 0,
+ "no tracker entry was created — the merge offset was already committed-past",
+ );
+ assert!(
+ !dispatcher.workers.contains_key(&partition),
+ "the eager redrive does not spawn a worker",
+ );
+ }
+
+ #[tokio::test]
+ async fn eager_boot_redrive_is_a_noop_for_an_empty_outbox() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, transfer_sink, merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+ let owned: HashSet<i32> = [0, 1].into_iter().collect();
+ dispatcher
+ .eager_redrive_pending_transfers_on_boot(&owned)
+ .await;
+
+ assert!(
+ transfer_sink.transfers().is_empty(),
+ "an empty outbox produces nothing",
+ );
+ assert_eq!(
+ merge.merge_tracker.partition_count(),
+ 0,
+ "an empty outbox marks no offset",
+ );
+ }
+
+ #[tokio::test]
+ async fn eager_boot_redrive_only_touches_owned_partitions() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, transfer_sink, _merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let owned_partition = 3;
+ let unowned_partition = 7;
+ let (owned_key, owned_transfer) =
+ stage_pending(&store, owned_partition, person(1), person(2), 41);
+ let (unowned_key, _unowned_transfer) =
+ stage_pending(&store, unowned_partition, person(3), person(4), 51);
+
+ dispatcher.assign_partition(owned_partition);
+ let owned: HashSet<i32> = [owned_partition].into_iter().collect();
+ dispatcher
+ .eager_redrive_pending_transfers_on_boot(&owned)
+ .await;
+
+ assert_eq!(
+ transfer_sink.transfers(),
+ vec![owned_transfer],
+ "only the owned partition's transfer was re-produced",
+ );
+ assert!(
+ store.get_pending_transfer(&owned_key).unwrap().is_none(),
+ "the owned partition's outbox entry was cleared",
+ );
+ assert!(
+ store.get_pending_transfer(&unowned_key).unwrap().is_some(),
+ "the unowned partition's outbox entry was left untouched",
+ );
+ }
+
+ #[tokio::test]
+ async fn eager_boot_redrive_paginates_until_the_whole_outbox_is_drained() {
+ let (_dir, store) = temp_store();
+ let (dispatcher, _sink, transfer_sink, _merge) = dispatcher_full(
+ &store,
+ behavioral_catalog(),
+ CaptureSink::new(),
+ CaptureTransferSink::new(),
+ );
+
+ let partition = 3;
+ let store_partition = partition_to_store_id(partition).unwrap();
+ // Seed five entries so a page size of two spans three pages (2 + 2 + 1).
+ let mut expected = Vec::new();
+ for n in 1..=5u128 {
+ let (_key, transfer) =
+ stage_pending(&store, partition, person(n), person(100 + n), 40 + n as i64);
+ expected.push(transfer);
+ }
+
+ let recovered = dispatcher
+ .eager_redrive_partition(partition, store_partition, 2)
+ .await;
+
+ assert_eq!(
+ recovered, 5,
+ "every staged entry was re-produced across pages"
+ );
+ // Production follows key order across pages; sort both sides on the stable old-person key so
+ // the assertion does not depend on the seeding order.
+ let mut produced = transfer_sink.transfers();
+ produced.sort_by_key(|t| t.old_person_uuid);
+ expected.sort_by_key(|t| t.old_person_uuid);
+ assert_eq!(produced, expected);
+ assert!(
+ store
+ .scan_pending_transfers(store_partition, None, usize::MAX)
+ .unwrap()
+ .is_empty(),
+ "the outbox is fully drained — no entry stranded past the first page",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/consumers/merges.rs b/rust/cohort-stream-processor/src/consumers/merges.rs
new file mode 100644
index 000000000000..38e0d85e6a37
--- /dev/null
+++ b/rust/cohort-stream-processor/src/consumers/merges.rs
@@ -0,0 +1,477 @@
+//! Merge-protocol follower consumers: `person_merge_events` (drain trigger, keyed by P_old) and
+//! `cohort_merge_state_transfer` (packaged state, keyed by P_new).
+//!
+//! Both use [`FollowerConsumer`] generic over a [`FollowerRoute`]. Followers never `subscribe()` —
+//! the events group's rebalance mirrors partition ownership onto them.
+
+use std::collections::{HashMap, HashSet};
+use std::marker::PhantomData;
+use std::sync::Arc;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use lifecycle::Handle;
+use metrics::{counter, histogram};
+use rdkafka::consumer::{CommitMode, StreamConsumer};
+use rdkafka::message::Message;
+use tracing::{debug, info, warn};
+
+use crate::cascade::CascadeMessage;
+use crate::consumers::events::{fsync_then_commit, EventDispatcher, RECV_ERROR_BACKOFF};
+use crate::merge::transfer::{MergeStateTransfer, PersonMergeEvent};
+use crate::observability::metrics::{
+ COHORT_STREAM_CASCADES_CONSUMED, COHORT_STREAM_CASCADES_CONSUME_BATCH_SIZE,
+ COHORT_STREAM_CASCADE_DESERIALIZE_ERRORS, COHORT_STREAM_KAFKA_RECV_ERRORS,
+ COHORT_STREAM_MERGES_CONSUMED, COHORT_STREAM_MERGES_CONSUME_BATCH_SIZE,
+ COHORT_STREAM_MERGE_DESERIALIZE_ERRORS, COHORT_STREAM_TRANSFERS_CONSUMED,
+ COHORT_STREAM_TRANSFERS_CONSUME_BATCH_SIZE, COHORT_STREAM_TRANSFER_DESERIALIZE_ERRORS,
+};
+use crate::partitions::offset_tracker::OffsetTracker;
+use crate::workers::MergeWorkerDeps;
+
+/// One merge trigger consumed from `person_merge_events`, paired with its commit coordinates.
+#[derive(Debug)]
+pub struct ConsumedMerge {
+ pub event: PersonMergeEvent,
+ pub partition: i32,
+ pub offset: i64,
+}
+
+/// One state transfer consumed from `cohort_merge_state_transfer`, paired with its commit
+/// coordinates. Replay idempotence is keyed by the transfer's source merge-message coordinates
+/// (`source_partition` + `source_offset`).
+#[derive(Debug)]
+pub struct ConsumedTransfer {
+ pub transfer: MergeStateTransfer,
+ pub partition: i32,
+ pub offset: i64,
+}
+
+/// One cohort flip consumed from `cohort_cascade_events`, paired with its commit coordinates.
+/// Replay idempotence is the handler's own bit-flip check (no stored offset field).
+#[derive(Debug)]
+pub struct ConsumedCascade {
+ pub message: CascadeMessage,
+ pub partition: i32,
+ pub offset: i64,
+}
+
+/// How a follower topic's payload decodes and which dispatcher entry point routes the batch.
+#[async_trait]
+pub trait FollowerRoute: Send + Sync + 'static {
+ type Consumed: Send + 'static;
+ const KIND: &'static str;
+ const CONSUMED_TOTAL: &'static str;
+ const DESERIALIZE_ERRORS_TOTAL: &'static str;
+ const CONSUME_BATCH_SIZE: &'static str;
+
+ /// The route-specific commit tracker. Each route selects its own so commits never cross topics.
+ fn tracker(deps: &MergeWorkerDeps) -> &Arc<OffsetTracker>;
+
+ /// Decode one payload into its consumed envelope.
+ fn decode(
+ payload: &[u8],
+ partition: i32,
+ offset: i64,
+ ) -> Result<Self::Consumed, serde_json::Error>;
+
+ /// Hand a decoded batch to the dispatcher.
+ async fn dispatch(dispatcher: &EventDispatcher, batch: Vec<Self::Consumed>);
+}
+
+/// P_old-keyed merge triggers into [`EventDispatcher::dispatch_merges`].
+pub struct MergeRoute;
+
+#[async_trait]
+impl FollowerRoute for MergeRoute {
+ type Consumed = ConsumedMerge;
+ const KIND: &'static str = "person_merge_events";
+ const CONSUMED_TOTAL: &'static str = COHORT_STREAM_MERGES_CONSUMED;
+ const DESERIALIZE_ERRORS_TOTAL: &'static str = COHORT_STREAM_MERGE_DESERIALIZE_ERRORS;
+ const CONSUME_BATCH_SIZE: &'static str = COHORT_STREAM_MERGES_CONSUME_BATCH_SIZE;
+
+ fn tracker(deps: &MergeWorkerDeps) -> &Arc<OffsetTracker> {
+ &deps.merge_tracker
+ }
+
+ fn decode(
+ payload: &[u8],
+ partition: i32,
+ offset: i64,
+ ) -> Result<Self::Consumed, serde_json::Error> {
+ PersonMergeEvent::decode(payload).map(|event| ConsumedMerge {
+ event,
+ partition,
+ offset,
+ })
+ }
+
+ async fn dispatch(dispatcher: &EventDispatcher, batch: Vec<Self::Consumed>) {
+ dispatcher.dispatch_merges(batch).await;
+ }
+}
+
+/// P_new-keyed packaged drains into [`EventDispatcher::dispatch_transfers`].
+pub struct TransferRoute;
+
+#[async_trait]
+impl FollowerRoute for TransferRoute {
+ type Consumed = ConsumedTransfer;
+ const KIND: &'static str = "cohort_merge_state_transfer";
+ const CONSUMED_TOTAL: &'static str = COHORT_STREAM_TRANSFERS_CONSUMED;
+ const DESERIALIZE_ERRORS_TOTAL: &'static str = COHORT_STREAM_TRANSFER_DESERIALIZE_ERRORS;
+ const CONSUME_BATCH_SIZE: &'static str = COHORT_STREAM_TRANSFERS_CONSUME_BATCH_SIZE;
+
+ fn tracker(deps: &MergeWorkerDeps) -> &Arc<OffsetTracker> {
+ &deps.transfer_tracker
+ }
+
+ fn decode(
+ payload: &[u8],
+ partition: i32,
+ offset: i64,
+ ) -> Result<Self::Consumed, serde_json::Error> {
+ MergeStateTransfer::decode(payload).map(|transfer| ConsumedTransfer {
+ transfer,
+ partition,
+ offset,
+ })
+ }
+
+ async fn dispatch(dispatcher: &EventDispatcher, batch: Vec<Self::Consumed>) {
+ dispatcher.dispatch_transfers(batch).await;
+ }
+}
+
+/// `(team, person)`-keyed cohort flips into [`EventDispatcher::dispatch_cascade`].
+pub struct CascadeRoute;
+
+#[async_trait]
+impl FollowerRoute for CascadeRoute {
+ type Consumed = ConsumedCascade;
+ const KIND: &'static str = "cohort_cascade_events";
+ const CONSUMED_TOTAL: &'static str = COHORT_STREAM_CASCADES_CONSUMED;
+ const DESERIALIZE_ERRORS_TOTAL: &'static str = COHORT_STREAM_CASCADE_DESERIALIZE_ERRORS;
+ const CONSUME_BATCH_SIZE: &'static str = COHORT_STREAM_CASCADES_CONSUME_BATCH_SIZE;
+
+ fn tracker(deps: &MergeWorkerDeps) -> &Arc<OffsetTracker> {
+ &deps.cascade_tracker
+ }
+
+ fn decode(
+ payload: &[u8],
+ partition: i32,
+ offset: i64,
+ ) -> Result<Self::Consumed, serde_json::Error> {
+ serde_json::from_slice::<CascadeMessage>(payload).map(|message| ConsumedCascade {
+ message,
+ partition,
+ offset,
+ })
+ }
+
+ async fn dispatch(dispatcher: &EventDispatcher, batch: Vec<Self::Consumed>) {
+ dispatcher.dispatch_cascade(batch).await;
+ }
+}
+
+pub struct FollowerConsumer<R: FollowerRoute> {
+ consumer: Arc<StreamConsumer>,
+ topic: String,
+ dispatcher: Arc<EventDispatcher>,
+ handle: Handle,
+ recv_batch_size: usize,
+ recv_batch_timeout: Duration,
+ offset_commit_interval: Duration,
+ _route: PhantomData<R>,
+}
+
+impl<R: FollowerRoute> FollowerConsumer<R> {
+ pub fn new(
+ consumer: Arc<StreamConsumer>,
+ topic: String,
+ dispatcher: Arc<EventDispatcher>,
+ handle: Handle,
+ recv_batch_size: usize,
+ recv_batch_timeout: Duration,
+ offset_commit_interval: Duration,
+ ) -> Self {
+ Self {
+ consumer,
+ topic,
+ dispatcher,
+ handle,
+ recv_batch_size,
+ recv_batch_timeout,
+ offset_commit_interval,
+ _route: PhantomData,
+ }
+ }
+
+ fn tracker(&self) -> &Arc<OffsetTracker> {
+ R::tracker(self.dispatcher.merge_deps())
+ }
+
+ pub async fn process(self) {
+ let _guard = self.handle.process_scope();
+ info!(topic = %self.topic, "follower consume loop starting");
+
+ let mut commit_deadline = tokio::time::Instant::now() + self.offset_commit_interval;
+
+ loop {
+ tokio::select! {
+ biased;
+ _ = self.handle.shutdown_recv() => {
+ info!(topic = %self.topic, "shutdown signal received, stopping follower consume loop");
+ break;
+ }
+ outcome = self.consume_batch() => {
+ self.handle_outcome(outcome).await;
+ let now = tokio::time::Instant::now();
+ if now >= commit_deadline {
+ fsync_then_commit(
+ self.dispatcher.store(),
+ &self.consumer,
+ self.tracker(),
+ self.owned_committable_offsets(),
+ &self.topic,
+ CommitMode::Async,
+ );
+ commit_deadline = now + self.offset_commit_interval;
+ }
+ }
+ }
+ }
+
+ // Final sync commit runs before the events consumer's shutdown; workers may still be marking
+ // offsets at this point, but follower offsets are independent.
+ fsync_then_commit(
+ self.dispatcher.store(),
+ &self.consumer,
+ self.tracker(),
+ self.owned_committable_offsets(),
+ &self.topic,
+ CommitMode::Sync,
+ );
+ info!(topic = %self.topic, "follower consume loop stopped");
+ }
+
+ async fn handle_outcome(&self, outcome: FollowerOutcome<R::Consumed>) {
+ histogram!(R::CONSUME_BATCH_SIZE).record(outcome.messages.len() as f64);
+ if !outcome.messages.is_empty() {
+ counter!(R::CONSUMED_TOTAL).increment(outcome.messages.len() as u64);
+ }
+ if outcome.deserialize_errors > 0 {
+ counter!(R::DESERIALIZE_ERRORS_TOTAL).increment(outcome.deserialize_errors);
+ }
+
+ R::dispatch(&self.dispatcher, outcome.messages).await;
+
+ if outcome.transport_error {
+ tokio::time::sleep(RECV_ERROR_BACKOFF).await;
+ } else {
+ self.handle.report_healthy();
+ }
+ }
+
+ async fn consume_batch(&self) -> FollowerOutcome<R::Consumed> {
+ let mut outcome = FollowerOutcome {
+ messages: Vec::with_capacity(self.recv_batch_size),
+ deserialize_errors: 0,
+ transport_error: false,
+ };
+
+ tokio::select! {
+ _ = tokio::time::sleep(self.recv_batch_timeout) => {}
+ _ = async {
+ while outcome.messages.len() < self.recv_batch_size {
+ match self.consumer.recv().await {
+ Ok(message) => {
+ let partition = message.partition();
+ let offset = message.offset();
+ let Some(payload) = message.payload() else {
+ outcome.deserialize_errors += 1;
+ debug!(
+ topic = %self.topic, partition, offset,
+ "skipping follower message with empty payload",
+ );
+ continue;
+ };
+ match R::decode(payload, partition, offset) {
+ Ok(consumed) => outcome.messages.push(consumed),
+ Err(err) => {
+ outcome.deserialize_errors += 1;
+ debug!(
+ topic = %self.topic, partition, offset, error = %err,
+ "skipping undeserializable follower message",
+ );
+ }
+ }
+ }
+ Err(err) => {
+ outcome.transport_error = true;
+ counter!(COHORT_STREAM_KAFKA_RECV_ERRORS).increment(1);
+ warn!(topic = %self.topic, error = %err, "kafka recv error while consuming follower topic");
+ break;
+ }
+ }
+ }
+ } => {}
+ }
+
+ outcome
+ }
+
+ fn owned_committable_offsets(&self) -> HashMap<i32, i64> {
+ restrict_to_owned(
+ self.tracker().committable_offsets(),
+ &self.dispatcher.owned_partitions(),
+ )
+ }
+}
+
+struct FollowerOutcome<T> {
+ messages: Vec<T>,
+ deserialize_errors: u64,
+ transport_error: bool,
+}
+
+fn restrict_to_owned(offsets: HashMap<i32, i64>, owned: &[i32]) -> HashMap<i32, i64> {
+ let owned: HashSet<i32> = owned.iter().copied().collect();
+ offsets
+ .into_iter()
+ .filter(|(partition, _)| owned.contains(partition))
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use uuid::Uuid;
+
+ use crate::merge::transfer::{TransferLeaf, MERGE_EVENT_SCHEMA_VERSION};
+ use crate::stage1::key::LeafStateKey;
+ use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
+
+ fn merge_event() -> PersonMergeEvent {
+ PersonMergeEvent {
+ team_id: 42,
+ old_person_uuid: Uuid::from_u128(0xAAAA),
+ new_person_uuid: Uuid::from_u128(0xBBBB),
+ merged_at_ms: 1_716_800_000_000,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ }
+ }
+
+ fn transfer() -> MergeStateTransfer {
+ MergeStateTransfer {
+ team_id: 42,
+ old_person_uuid: Uuid::from_u128(0xAAAA),
+ new_person_uuid: Uuid::from_u128(0xBBBB),
+ merged_at_ms: 1_716_800_000_000,
+ source_partition: 17,
+ source_offset: 12_345,
+ leaves: vec![TransferLeaf::new(
+ LeafStateKey([0xAB; 16]),
+ StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ AppliedOffsets::default(),
+ ),
+ )],
+ forward_hops: 0,
+ }
+ }
+
+ #[test]
+ fn merge_route_decodes_an_envelope_with_its_commit_coords() {
+ let event = merge_event();
+
+ let consumed = MergeRoute::decode(&event.encode(), 17, 12_345).unwrap();
+
+ assert_eq!(consumed.event, event);
+ assert_eq!(consumed.partition, 17);
+ assert_eq!(consumed.offset, 12_345);
+ }
+
+ #[test]
+ fn transfer_route_decodes_an_envelope_with_its_commit_coords() {
+ let wire = transfer();
+
+ let consumed = TransferRoute::decode(&wire.encode(), 9, 77).unwrap();
+
+ assert_eq!(consumed.transfer, wire);
+ assert_eq!(consumed.partition, 9);
+ assert_eq!(consumed.offset, 77);
+ }
+
+ fn cascade_message() -> CascadeMessage {
+ crate::cascade::first_cascade(
+ crate::producer::CohortMembershipChange {
+ team_id: 42,
+ cohort_id: 91204,
+ person_id: Uuid::from_u128(0xCAFE).to_string(),
+ last_updated: "2026-05-26 12:34:56.789000".to_string(),
+ status: crate::producer::MembershipStatus::Entered,
+ },
+ 123,
+ )
+ }
+
+ #[test]
+ fn cascade_route_decodes_an_envelope_with_its_commit_coords() {
+ let wire = cascade_message();
+
+ let consumed = CascadeRoute::decode(&serde_json::to_vec(&wire).unwrap(), 5, 88).unwrap();
+
+ assert_eq!(consumed.message, wire);
+ assert_eq!(consumed.partition, 5);
+ assert_eq!(consumed.offset, 88);
+ }
+
+ #[test]
+ fn garbage_payloads_decode_to_err_for_every_route() {
+ assert!(MergeRoute::decode(b"not json", 0, 0).is_err());
+ assert!(TransferRoute::decode(&[], 0, 0).is_err());
+ assert!(CascadeRoute::decode(b"not json", 0, 0).is_err());
+ }
+
+ #[test]
+ fn each_route_selects_its_own_tracker_from_the_merge_deps() {
+ let deps = MergeWorkerDeps::capture();
+
+ assert!(
+ Arc::ptr_eq(MergeRoute::tracker(&deps), &deps.merge_tracker),
+ "merge route must commit via the merge tracker"
+ );
+ assert!(
+ Arc::ptr_eq(TransferRoute::tracker(&deps), &deps.transfer_tracker),
+ "transfer route must commit via the transfer tracker"
+ );
+ assert!(
+ Arc::ptr_eq(CascadeRoute::tracker(&deps), &deps.cascade_tracker),
+ "cascade route must commit via the cascade tracker"
+ );
+ }
+
+ #[test]
+ fn restrict_to_owned_keeps_only_owned_partitions() {
+ let offsets: HashMap<i32, i64> = [(0, 10), (3, 30), (7, 70)].into_iter().collect();
+
+ let restricted = restrict_to_owned(offsets, &[3, 7]);
+
+ assert_eq!(restricted.len(), 2);
+ assert_eq!(restricted.get(&0), None, "revoked partition is dropped");
+ assert_eq!(restricted.get(&3), Some(&30));
+ assert_eq!(restricted.get(&7), Some(&70));
+ }
+
+ #[test]
+ fn restrict_to_owned_with_no_owned_partitions_is_empty() {
+ let offsets: HashMap<i32, i64> = [(0, 10)].into_iter().collect();
+ assert!(restrict_to_owned(offsets, &[]).is_empty());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/consumers/mod.rs b/rust/cohort-stream-processor/src/consumers/mod.rs
new file mode 100644
index 000000000000..11fe941f34e7
--- /dev/null
+++ b/rust/cohort-stream-processor/src/consumers/mod.rs
@@ -0,0 +1,11 @@
+//! Kafka consumers — one rdkafka `StreamConsumer` per input topic. The `events` submodule covers
+//! `cohort_stream_events`, the hot path; `merges` carries the merge-protocol follower consumers.
+
+pub mod events;
+pub mod merges;
+
+pub use events::{CohortStreamEvent, CohortStreamEventsConsumer, ConsumedEvent, EventDispatcher};
+pub use merges::{
+ CascadeRoute, ConsumedCascade, ConsumedMerge, ConsumedTransfer, FollowerConsumer,
+ FollowerRoute, MergeRoute, TransferRoute,
+};
diff --git a/rust/cohort-stream-processor/src/filters/cohort_graph.rs b/rust/cohort-stream-processor/src/filters/cohort_graph.rs
new file mode 100644
index 000000000000..08c0a83a5324
--- /dev/null
+++ b/rust/cohort-stream-processor/src/filters/cohort_graph.rs
@@ -0,0 +1,301 @@
+//! Per-team cohort-reference graph and Tarjan-SCC cycle analysis.
+
+use std::collections::{HashMap, HashSet};
+
+use petgraph::algo::tarjan_scc;
+use petgraph::graph::{DiGraph, NodeIndex};
+
+use crate::filters::tree::{CohortLeaf, CohortTree, FilterNode};
+use crate::filters::CohortId;
+
+#[derive(Debug, Default)]
+pub(crate) struct RefGraphAnalysis {
+ /// Cohorts participating in a reference cycle (SCC of size > 1, or self-loop).
+ pub in_cycle: HashSet<CohortId>,
+ /// Ref-bearing cohorts in referenced-before-referrer order (reverse topological order of the
+ /// condensation graph).
+ pub refinement_order: Vec<CohortId>,
+ /// Each ref-bearing cohort's distinct referenced ids (sorted), including ids absent from the
+ /// team catalog.
+ pub ref_targets: HashMap<CohortId, Vec<CohortId>>,
+ /// Targets reached through at least one non-negated (positive) leaf. A target reached only
+ /// through negated leaves is omitted: an absent negated ref reads `true`, so it never blocks
+ /// composition. Resolvability is decided over this set, not `ref_targets`.
+ pub positive_ref_targets: HashMap<CohortId, HashSet<CohortId>>,
+}
+
+pub(crate) fn analyze(cohorts: &HashMap<CohortId, CohortTree>) -> RefGraphAnalysis {
+ let mut ref_targets: HashMap<CohortId, Vec<CohortId>> = HashMap::new();
+ let mut positive_ref_targets: HashMap<CohortId, HashSet<CohortId>> = HashMap::new();
+ for (&cohort_id, tree) in cohorts {
+ let mut targets = HashSet::new();
+ let mut positives = HashSet::new();
+ collect_cohort_refs(&tree.root, &mut targets, &mut positives);
+ if !targets.is_empty() {
+ let mut targets: Vec<CohortId> = targets.into_iter().collect();
+ targets.sort_unstable();
+ ref_targets.insert(cohort_id, targets);
+ }
+ if !positives.is_empty() {
+ positive_ref_targets.insert(cohort_id, positives);
+ }
+ }
+ if ref_targets.is_empty() {
+ return RefGraphAnalysis::default();
+ }
+
+ let mut node_ids: Vec<CohortId> = cohorts.keys().copied().collect();
+ for targets in ref_targets.values() {
+ node_ids.extend(targets.iter().copied());
+ }
+ node_ids.sort_unstable();
+ node_ids.dedup();
+
+ let mut graph: DiGraph<CohortId, ()> = DiGraph::new();
+ let mut index_of: HashMap<CohortId, NodeIndex> = HashMap::with_capacity(node_ids.len());
+ for id in node_ids {
+ index_of.insert(id, graph.add_node(id));
+ }
+
+ // Self-loops are size-1 SCCs in Tarjan, so capture them separately.
+ let mut self_loops = HashSet::new();
+ for (&referrer, targets) in &ref_targets {
+ let src = index_of[&referrer];
+ for &target in targets {
+ if referrer == target {
+ self_loops.insert(referrer);
+ }
+ graph.add_edge(src, index_of[&target], ());
+ }
+ }
+
+ let mut in_cycle = self_loops;
+ let mut refinement_order = Vec::with_capacity(ref_targets.len());
+ for scc in tarjan_scc(&graph) {
+ if scc.len() > 1 {
+ in_cycle.extend(scc.iter().map(|&idx| graph[idx]));
+ }
+ // Keep only the ref-bearing cohorts; their referenced-first order is what refinement needs.
+ refinement_order.extend(
+ scc.iter()
+ .map(|&idx| graph[idx])
+ .filter(|id| ref_targets.contains_key(id)),
+ );
+ }
+
+ RefGraphAnalysis {
+ in_cycle,
+ refinement_order,
+ ref_targets,
+ positive_ref_targets,
+ }
+}
+
+/// Collect every distinct cohort-reference target in a tree. Targets reached through a non-negated
+/// leaf are additionally recorded in `positives` — the set resolvability is decided over.
+fn collect_cohort_refs(
+ node: &FilterNode,
+ all: &mut HashSet<CohortId>,
+ positives: &mut HashSet<CohortId>,
+) {
+ match node {
+ FilterNode::Group { children, .. } => {
+ for child in children {
+ collect_cohort_refs(child, all, positives);
+ }
+ }
+ FilterNode::Leaf(CohortLeaf::CohortRef(config)) => {
+ all.insert(config.referenced_cohort_id);
+ if !config.negation {
+ positives.insert(config.referenced_cohort_id);
+ }
+ }
+ FilterNode::Leaf(_) => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::filters::tree::{BoolOp, CohortRefLeafConfig};
+ use crate::filters::TeamId;
+
+ fn ref_cohort(id: i32, refs: &[i32]) -> (CohortId, CohortTree) {
+ let children = refs
+ .iter()
+ .map(|&r| {
+ FilterNode::Leaf(CohortLeaf::CohortRef(CohortRefLeafConfig {
+ referenced_cohort_id: CohortId(r),
+ negation: false,
+ }))
+ })
+ .collect();
+ (
+ CohortId(id),
+ CohortTree {
+ cohort_id: CohortId(id),
+ team_id: TeamId(1),
+ root: FilterNode::Group {
+ op: BoolOp::And,
+ children,
+ },
+ },
+ )
+ }
+
+ fn ref_cohort_negated(id: i32, refs: &[(i32, bool)]) -> (CohortId, CohortTree) {
+ let children = refs
+ .iter()
+ .map(|&(r, negation)| {
+ FilterNode::Leaf(CohortLeaf::CohortRef(CohortRefLeafConfig {
+ referenced_cohort_id: CohortId(r),
+ negation,
+ }))
+ })
+ .collect();
+ (
+ CohortId(id),
+ CohortTree {
+ cohort_id: CohortId(id),
+ team_id: TeamId(1),
+ root: FilterNode::Group {
+ op: BoolOp::And,
+ children,
+ },
+ },
+ )
+ }
+
+ fn catalog(cohorts: Vec<(CohortId, CohortTree)>) -> HashMap<CohortId, CohortTree> {
+ cohorts.into_iter().collect()
+ }
+
+ fn ids(set: &HashSet<CohortId>) -> Vec<i32> {
+ let mut v: Vec<i32> = set.iter().map(|c| c.0).collect();
+ v.sort_unstable();
+ v
+ }
+
+ fn positive_ids(analysis: &RefGraphAnalysis, id: i32) -> Vec<i32> {
+ ids(&analysis.positive_ref_targets[&CohortId(id)])
+ }
+
+ #[test]
+ fn three_node_cycle_marks_all_members() {
+ let analysis = analyze(&catalog(vec![
+ ref_cohort(1, &[2]),
+ ref_cohort(2, &[3]),
+ ref_cohort(3, &[1]),
+ ]));
+ assert_eq!(ids(&analysis.in_cycle), vec![1, 2, 3]);
+ }
+
+ #[test]
+ fn cycle_free_isomorph_marks_nothing() {
+ let analysis = analyze(&catalog(vec![
+ ref_cohort(1, &[2]),
+ ref_cohort(2, &[3]),
+ ref_cohort(3, &[]),
+ ]));
+ assert!(analysis.in_cycle.is_empty());
+ }
+
+ #[test]
+ fn self_loop_is_a_cycle() {
+ let analysis = analyze(&catalog(vec![ref_cohort(1, &[1])]));
+ assert_eq!(ids(&analysis.in_cycle), vec![1]);
+ assert_eq!(analysis.ref_targets[&CohortId(1)], vec![CohortId(1)]);
+ }
+
+ #[test]
+ fn tail_into_a_cycle_is_not_itself_cyclic() {
+ let analysis = analyze(&catalog(vec![
+ ref_cohort(4, &[1]),
+ ref_cohort(1, &[2]),
+ ref_cohort(2, &[1]),
+ ]));
+ assert_eq!(ids(&analysis.in_cycle), vec![1, 2]);
+ }
+
+ #[test]
+ fn missing_target_is_in_ref_targets_but_never_in_cycle() {
+ let analysis = analyze(&catalog(vec![ref_cohort(1, &[99])]));
+ assert_eq!(analysis.ref_targets[&CohortId(1)], vec![CohortId(99)]);
+ assert!(analysis.in_cycle.is_empty());
+ assert!(!analysis.ref_targets.contains_key(&CohortId(99)));
+ }
+
+ #[test]
+ fn duplicate_ref_edges_dedupe() {
+ let analysis = analyze(&catalog(vec![ref_cohort(1, &[2, 2]), ref_cohort(2, &[])]));
+ assert_eq!(analysis.ref_targets[&CohortId(1)], vec![CohortId(2)]);
+ }
+
+ #[test]
+ fn refinement_order_is_referenced_before_referrer() {
+ let analysis = analyze(&catalog(vec![
+ ref_cohort(1, &[2]),
+ ref_cohort(2, &[3]),
+ ref_cohort(3, &[]),
+ ]));
+ let position = |id: CohortId| {
+ analysis
+ .refinement_order
+ .iter()
+ .position(|&c| c == id)
+ .expect("ref-bearing cohort present in refinement_order")
+ };
+ for (&referrer, targets) in &analysis.ref_targets {
+ for &target in targets {
+ if analysis.ref_targets.contains_key(&target) {
+ assert!(
+ position(target) < position(referrer),
+ "target {target:?} must be refined before referrer {referrer:?}",
+ );
+ }
+ }
+ }
+ // 3 is not ref-bearing, so it never appears in the order.
+ assert!(!analysis.refinement_order.contains(&CohortId(3)));
+ }
+
+ #[test]
+ fn team_without_refs_yields_default_analysis() {
+ let analysis = analyze(&catalog(vec![ref_cohort(1, &[])]));
+ assert!(analysis.in_cycle.is_empty());
+ assert!(analysis.refinement_order.is_empty());
+ assert!(analysis.ref_targets.is_empty());
+ assert!(analysis.positive_ref_targets.is_empty());
+ }
+
+ #[test]
+ fn negated_only_ref_is_in_ref_targets_but_not_positive() {
+ let analysis = analyze(&catalog(vec![ref_cohort_negated(1, &[(99, true)])]));
+ assert_eq!(analysis.ref_targets[&CohortId(1)], vec![CohortId(99)]);
+ // A purely negated reference contributes no positive target, so the referrer's positive
+ // set is empty — resolvability never inspects the negated 99.
+ assert!(!analysis.positive_ref_targets.contains_key(&CohortId(1)));
+ }
+
+ #[test]
+ fn positive_ref_is_in_both_target_maps() {
+ let analysis = analyze(&catalog(vec![
+ ref_cohort_negated(1, &[(2, false)]),
+ ref_cohort(2, &[]),
+ ]));
+ assert_eq!(analysis.ref_targets[&CohortId(1)], vec![CohortId(2)]);
+ assert_eq!(positive_ids(&analysis, 1), vec![2]);
+ }
+
+ #[test]
+ fn mixed_polarity_ref_to_same_target_keeps_it_positive() {
+ // 1 references 2 both positively and negatively → 2 stays in the positive set, so a missing
+ // 2 would still block composition.
+ let analysis = analyze(&catalog(vec![
+ ref_cohort_negated(1, &[(2, false), (2, true)]),
+ ref_cohort(2, &[]),
+ ]));
+ assert_eq!(analysis.ref_targets[&CohortId(1)], vec![CohortId(2)]);
+ assert_eq!(positive_ids(&analysis, 1), vec![2]);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/filters/leaf_classifier.rs b/rust/cohort-stream-processor/src/filters/leaf_classifier.rs
new file mode 100644
index 000000000000..02b78845d70a
--- /dev/null
+++ b/rust/cohort-stream-processor/src/filters/leaf_classifier.rs
@@ -0,0 +1,608 @@
+//! Raw leaf JSON classification into kept, dropped, or cohort-reference leaves.
+
+use std::sync::Arc;
+
+use serde_json::Value;
+
+use crate::filters::tree::{
+ BehavioralLeafConfig, BehavioralValue, CohortLeaf, CohortRefLeafConfig, PersonLeafConfig,
+};
+use crate::filters::CohortId;
+use crate::stage1::key::LeafStateKey;
+use crate::stage1::pick_state::pick_state_variant;
+
+/// Why a leaf was dropped during parse. Used as the `reason` label on the skip counter.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LeafDropReason {
+ /// No `conditionHash`, or one that is not a 16-character string.
+ MissingConditionHash,
+ /// No inline array `bytecode`.
+ MissingBytecode,
+ /// A behavioral `value` outside the two bytecode-producing types.
+ UnsupportedBehavioralValue,
+ /// A behavioral leaf keyed by an action id (integer `key`).
+ BehavioralActionKey,
+ /// A bytecode-bearing behavioral leaf whose Stage 1 state variant is not yet representable.
+ UnsupportedStateVariant,
+ /// A `type` outside `{person, behavioral, cohort}`.
+ UnknownLeafType,
+ /// A leaf that matches none of the recognized shapes.
+ MalformedLeaf,
+}
+
+impl LeafDropReason {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::MissingConditionHash => "missing_condition_hash",
+ Self::MissingBytecode => "missing_bytecode",
+ Self::UnsupportedBehavioralValue => "unsupported_behavioral_value",
+ Self::BehavioralActionKey => "behavioral_action_key",
+ Self::UnsupportedStateVariant => "unsupported_state_variant",
+ Self::UnknownLeafType => "unknown_leaf_type",
+ Self::MalformedLeaf => "malformed_leaf",
+ }
+ }
+}
+
+pub enum LeafClass {
+ Keep(CohortLeaf),
+ Drop(LeafDropReason),
+ CohortRef(CohortRefLeafConfig),
+}
+
+pub fn classify_leaf(node: &Value) -> LeafClass {
+ match node.get("type").and_then(Value::as_str) {
+ Some("behavioral") => classify_behavioral(node),
+ Some("cohort") => classify_cohort_ref(node),
+ Some("person") => classify_person(node),
+ _ => LeafClass::Drop(LeafDropReason::UnknownLeafType),
+ }
+}
+
+fn classify_behavioral(node: &Value) -> LeafClass {
+ let value = match node
+ .get("value")
+ .and_then(Value::as_str)
+ .and_then(BehavioralValue::from_wire)
+ {
+ Some(value) if value.contributes_bytecode() => value,
+ _ => return LeafClass::Drop(LeafDropReason::UnsupportedBehavioralValue),
+ };
+
+ // An integer `key` is an action id — no bytecode is produced for these.
+ if node.get("key").is_some_and(Value::is_number) {
+ return LeafClass::Drop(LeafDropReason::BehavioralActionKey);
+ }
+
+ let Some(condition_hash) = condition_hash_bytes(node.get("conditionHash")) else {
+ return LeafClass::Drop(LeafDropReason::MissingConditionHash);
+ };
+
+ let Some(bytecode) = bytecode_array(node.get("bytecode")) else {
+ return LeafClass::Drop(LeafDropReason::MissingBytecode);
+ };
+
+ let Some(event_key) = node
+ .get("key")
+ .and_then(Value::as_str)
+ .filter(|key| !key.is_empty())
+ else {
+ return LeafClass::Drop(LeafDropReason::MalformedLeaf);
+ };
+
+ let leaf = BehavioralLeafConfig {
+ condition_hash,
+ value,
+ event_key: event_key.to_string(),
+ time_value: opt_i32(node.get("time_value")),
+ operator_value: opt_i32(node.get("operator_value")),
+ time_interval: opt_string(node.get("time_interval")),
+ operator: opt_string(node.get("operator")),
+ explicit_datetime: opt_string(node.get("explicit_datetime")),
+ explicit_datetime_to: opt_string(node.get("explicit_datetime_to")),
+ leaf_state_key: LeafStateKey([0u8; 16]),
+ state_variant: None,
+ bytecode,
+ negated: explicit_negation(node),
+ }
+ .with_state_key();
+
+ match pick_state_variant(&leaf) {
+ Ok((variant, _window)) => {
+ LeafClass::Keep(CohortLeaf::Behavioral(leaf.with_state_variant(variant)))
+ }
+ Err(_) => LeafClass::Drop(LeafDropReason::UnsupportedStateVariant),
+ }
+}
+
+fn classify_cohort_ref(node: &Value) -> LeafClass {
+ match cohort_id_from_value(node.get("value")) {
+ Some(id) => LeafClass::CohortRef(CohortRefLeafConfig {
+ referenced_cohort_id: CohortId(id),
+ negation: cohort_ref_negation(node),
+ }),
+ None => LeafClass::Drop(LeafDropReason::MalformedLeaf),
+ }
+}
+
+/// Whether a person/behavioral leaf is negated: `negation: true` only. A bare `operator: "not_in"`
+/// is a value-list predicate compiled into the bytecode, not a composition negation.
+fn explicit_negation(node: &Value) -> bool {
+ node.get("negation")
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+}
+
+/// Whether a cohort-reference leaf is negated: `negation: true` or `operator: "not_in"`. Unlike a
+/// person/behavioral leaf, a cohort ref has no bytecode to compile `not_in` into.
+fn cohort_ref_negation(node: &Value) -> bool {
+ explicit_negation(node) || node.get("operator").and_then(Value::as_str) == Some("not_in")
+}
+
+fn classify_person(node: &Value) -> LeafClass {
+ let Some(condition_hash) = condition_hash_bytes(node.get("conditionHash")) else {
+ return LeafClass::Drop(LeafDropReason::MissingConditionHash);
+ };
+ let Some(bytecode) = bytecode_array(node.get("bytecode")) else {
+ return LeafClass::Drop(LeafDropReason::MissingBytecode);
+ };
+ LeafClass::Keep(CohortLeaf::PersonProperty(PersonLeafConfig {
+ condition_hash,
+ leaf_state_key: LeafStateKey::for_person_property(&condition_hash),
+ bytecode,
+ raw: node.clone(),
+ negated: explicit_negation(node),
+ }))
+}
+
+/// The 16 ASCII bytes of the hex `conditionHash` string, or `None` if not exactly 16 bytes.
+fn condition_hash_bytes(value: Option<&Value>) -> Option<[u8; 16]> {
+ let hash = value?.as_str()?;
+ let bytes = hash.as_bytes();
+ if bytes.len() == 16 {
+ let mut out = [0u8; 16];
+ out.copy_from_slice(bytes);
+ Some(out)
+ } else {
+ None
+ }
+}
+
+fn bytecode_array(value: Option<&Value>) -> Option<Arc<Vec<Value>>> {
+ let array = value?.as_array()?;
+ Some(Arc::new(array.clone()))
+}
+
+/// A referenced cohort id as a JSON number or string-encoded int.
+fn cohort_id_from_value(value: Option<&Value>) -> Option<i32> {
+ let value = value?;
+ if let Some(number) = value.as_i64() {
+ return i32::try_from(number).ok();
+ }
+ value.as_str()?.trim().parse().ok()
+}
+
+fn opt_i32(value: Option<&Value>) -> Option<i32> {
+ value?
+ .as_i64()
+ .and_then(|number| i32::try_from(number).ok())
+}
+
+fn opt_string(value: Option<&Value>) -> Option<String> {
+ Some(value?.as_str()?.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ const HASH: &str = "0123456789abcdef";
+
+ /// A representative bytecode program.
+ fn bytecode() -> Value {
+ json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
+ }
+
+ fn hash_bytes() -> [u8; 16] {
+ *b"0123456789abcdef"
+ }
+
+ #[test]
+ fn performed_event_is_kept_with_cached_key_and_variant() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ panic!("expected a kept behavioral leaf");
+ };
+ assert_eq!(leaf.condition_hash, hash_bytes());
+ assert_eq!(leaf.value, BehavioralValue::PerformedEvent);
+ assert_eq!(leaf.event_key, "$pageview");
+ assert_eq!(leaf.time_value, Some(7));
+ assert_eq!(leaf.leaf_state_key, LeafStateKey::for_behavioral(&leaf));
+ assert_eq!(leaf.bytecode.as_ref(), bytecode().as_array().unwrap());
+ assert_eq!(
+ leaf.state_variant,
+ Some(crate::stage1::state::StateVariant::BehavioralSingle),
+ );
+ }
+
+ #[test]
+ fn performed_event_multiple_daily_window_is_kept_as_daily_buckets() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "operator": "gte",
+ "operator_value": 3,
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ panic!("a daily-window multiple is now kept");
+ };
+ assert_eq!(leaf.value, BehavioralValue::PerformedEventMultiple);
+ assert_eq!(leaf.operator.as_deref(), Some("gte"));
+ assert_eq!(leaf.operator_value, Some(3));
+ assert_eq!(
+ leaf.state_variant,
+ Some(crate::stage1::state::StateVariant::BehavioralDailyBuckets),
+ );
+ }
+
+ #[test]
+ fn performed_event_multiple_sub_day_window_is_dropped() {
+ for (time_value, time_interval, why) in [
+ (5, "hour", "hour,5 = 0 whole days"),
+ (30, "minute", "minute,30 = 0 whole days"),
+ ] {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "time_value": time_value,
+ "time_interval": time_interval,
+ "operator": "gte",
+ "operator_value": 3,
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ assert!(
+ matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::UnsupportedStateVariant)
+ ),
+ "{why}",
+ );
+ }
+ }
+
+ #[test]
+ fn performed_event_multiple_over_180_day_window_is_kept_as_compressed() {
+ for (time_value, time_interval, why) in [
+ (1, "year", "year,1 = 365 days"),
+ (365, "day", "day,365 = 365 days"),
+ (181, "day", "day,181 just over the daily boundary"),
+ ] {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "time_value": time_value,
+ "time_interval": time_interval,
+ "operator": "gte",
+ "operator_value": 3,
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ panic!("a >180-day multiple is kept as compressed: {why}");
+ };
+ assert_eq!(
+ leaf.state_variant,
+ Some(crate::stage1::state::StateVariant::BehavioralCompressedHistory),
+ "{why}",
+ );
+ }
+ }
+
+ #[test]
+ fn performed_event_without_window_is_dropped_as_unsupported_variant() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::UnsupportedStateVariant)
+ ));
+ }
+
+ #[test]
+ fn unsupported_behavioral_value_is_dropped() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event_sequence",
+ "key": "$pageview",
+ "conditionHash": HASH,
+ });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::UnsupportedBehavioralValue)
+ ));
+ }
+
+ #[test]
+ fn action_keyed_behavioral_is_dropped() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": 12345,
+ "conditionHash": HASH,
+ });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::BehavioralActionKey)
+ ));
+ }
+
+ #[test]
+ fn behavioral_without_condition_hash_is_dropped() {
+ let node = json!({ "type": "behavioral", "value": "performed_event", "key": "$pageview" });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::MissingConditionHash)
+ ));
+ }
+
+ #[test]
+ fn short_condition_hash_is_rejected() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "conditionHash": "tooshort",
+ });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::MissingConditionHash)
+ ));
+ }
+
+ #[test]
+ fn person_leaf_reuses_condition_hash_as_key() {
+ let node = json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ let LeafClass::Keep(CohortLeaf::PersonProperty(leaf)) = classify_leaf(&node) else {
+ panic!("expected a kept person leaf");
+ };
+ assert_eq!(leaf.condition_hash, hash_bytes());
+ assert_eq!(leaf.leaf_state_key, LeafStateKey(hash_bytes()));
+ assert_eq!(leaf.bytecode.as_ref(), bytecode().as_array().unwrap());
+ assert_eq!(leaf.raw, node);
+ }
+
+ #[test]
+ fn person_leaf_without_condition_hash_is_dropped() {
+ let node = json!({ "type": "person", "key": "email", "value": "[email protected]" });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::MissingConditionHash)
+ ));
+ }
+
+ #[test]
+ fn behavioral_without_bytecode_is_dropped() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "conditionHash": HASH,
+ });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::MissingBytecode)
+ ));
+ }
+
+ #[test]
+ fn person_without_bytecode_is_dropped() {
+ let node = json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "conditionHash": HASH,
+ });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::MissingBytecode)
+ ));
+ }
+
+ #[test]
+ fn non_array_bytecode_is_dropped() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "conditionHash": HASH,
+ "bytecode": "not-an-array",
+ });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::MissingBytecode)
+ ));
+ }
+
+ #[test]
+ fn cohort_ref_accepts_int_and_string_ids() {
+ let int_ref = json!({ "type": "cohort", "value": 42 });
+ let LeafClass::CohortRef(config) = classify_leaf(&int_ref) else {
+ panic!("expected a cohort ref");
+ };
+ assert_eq!(config.referenced_cohort_id, CohortId(42));
+ assert!(!config.negation);
+
+ let str_ref = json!({ "type": "cohort", "value": "99", "negation": true });
+ let LeafClass::CohortRef(config) = classify_leaf(&str_ref) else {
+ panic!("expected a cohort ref");
+ };
+ assert_eq!(config.referenced_cohort_id, CohortId(99));
+ assert!(config.negation);
+ }
+
+ #[test]
+ fn cohort_ref_negation_honors_not_in_operator() {
+ let not_in = json!({ "type": "cohort", "value": 7, "operator": "not_in" });
+ let LeafClass::CohortRef(config) = classify_leaf(&not_in) else {
+ panic!("expected a cohort ref");
+ };
+ assert_eq!(config.referenced_cohort_id, CohortId(7));
+ assert!(config.negation, "`operator: not_in` must set negation");
+
+ let both = json!({ "type": "cohort", "value": 7, "operator": "not_in", "negation": true });
+ let LeafClass::CohortRef(config) = classify_leaf(&both) else {
+ panic!("expected a cohort ref");
+ };
+ assert!(config.negation);
+
+ let in_op = json!({ "type": "cohort", "value": 7, "operator": "in" });
+ let LeafClass::CohortRef(config) = classify_leaf(&in_op) else {
+ panic!("expected a cohort ref");
+ };
+ assert!(!config.negation, "`operator: in` must not set negation");
+ }
+
+ #[test]
+ fn cohort_ref_without_value_is_dropped() {
+ let node = json!({ "type": "cohort" });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::MalformedLeaf)
+ ));
+ }
+
+ #[test]
+ fn unknown_type_is_dropped_even_with_condition_hash() {
+ let node = json!({
+ "type": "event",
+ "key": "$pageview",
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::UnknownLeafType)
+ ));
+ }
+
+ #[test]
+ fn absent_type_is_dropped_as_unknown() {
+ let node = json!({ "foo": "bar" });
+ assert!(matches!(
+ classify_leaf(&node),
+ LeafClass::Drop(LeafDropReason::UnknownLeafType)
+ ));
+ }
+
+ #[test]
+ fn behavioral_leaf_with_negation_true_is_kept_negated() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ "negation": true,
+ });
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ panic!("expected a kept behavioral leaf");
+ };
+ assert!(leaf.negated);
+ }
+
+ #[test]
+ fn behavioral_leaf_without_negation_is_not_negated() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ panic!("expected a kept behavioral leaf");
+ };
+ assert!(!leaf.negated);
+ }
+
+ #[test]
+ fn person_leaf_with_negation_true_is_kept_negated() {
+ let node = json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ "negation": true,
+ });
+ let LeafClass::Keep(CohortLeaf::PersonProperty(leaf)) = classify_leaf(&node) else {
+ panic!("expected a kept person leaf");
+ };
+ assert!(leaf.negated);
+ }
+
+ #[test]
+ fn person_leaf_without_negation_is_not_negated() {
+ let node = json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ });
+ let LeafClass::Keep(CohortLeaf::PersonProperty(leaf)) = classify_leaf(&node) else {
+ panic!("expected a kept person leaf");
+ };
+ assert!(!leaf.negated);
+ }
+
+ #[test]
+ fn behavioral_negation_false_is_not_negated() {
+ let node = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": HASH,
+ "bytecode": bytecode(),
+ "negation": false,
+ });
+ let LeafClass::Keep(CohortLeaf::Behavioral(leaf)) = classify_leaf(&node) else {
+ panic!("expected a kept behavioral leaf");
+ };
+ assert!(!leaf.negated);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/filters/loader.rs b/rust/cohort-stream-processor/src/filters/loader.rs
new file mode 100644
index 000000000000..8b234fb6b0fe
--- /dev/null
+++ b/rust/cohort-stream-processor/src/filters/loader.rs
@@ -0,0 +1,227 @@
+//! SQL load + pure row→catalog transform. [`load_realtime_cohorts`] is the only DB touch;
+//! [`build_catalog_from_rows`] is pure so the catalog logic is testable without Postgres.
+
+use std::collections::HashMap;
+
+use chrono_tz::{Tz, UTC};
+use common_types::cohort::TeamAllowlist;
+use metrics::counter;
+use serde_json::Value;
+use sqlx::PgPool;
+use tracing::warn;
+
+use crate::filters::manager::FilterCatalog;
+use crate::filters::reverse_index::TeamFiltersBuilder;
+use crate::filters::{CohortId, FilterError, TeamId};
+use crate::observability::metrics::{
+ FILTER_CATALOG_COHORT_PARSE_ERRORS, FILTER_CATALOG_TZ_FALLBACK,
+};
+
+/// Realtime cohorts to load, mirroring the Node filter manager's predicate, joined to
+/// `posthog_team` for the team timezone the bucket variants use for calendar-day computation.
+pub const REALTIME_COHORTS_SQL: &str = "SELECT c.id, c.team_id, c.filters, t.timezone \
+ FROM posthog_cohort c \
+ JOIN posthog_team t ON t.id = c.team_id \
+ WHERE c.cohort_type = 'realtime' AND c.deleted = false AND c.filters IS NOT NULL";
+
+/// One realtime cohort row; `filters` is the `jsonb` column decoded to a `Value`.
+#[derive(Debug, Clone, sqlx::FromRow)]
+pub struct CohortRow {
+ pub id: i32,
+ pub team_id: i32,
+ pub filters: Value,
+ /// `posthog_team.timezone` — a non-null IANA zone name (default `"UTC"`).
+ pub timezone: String,
+}
+
+pub async fn load_realtime_cohorts(pool: &PgPool) -> Result<Vec<CohortRow>, FilterError> {
+ let rows = sqlx::query_as::<_, CohortRow>(REALTIME_COHORTS_SQL)
+ .fetch_all(pool)
+ .await?;
+ Ok(rows)
+}
+
+/// Drop rows for teams outside `allowlist`, in place, before catalog building. Kept separate from
+/// [`build_catalog_from_rows`] (which stays allowlist-agnostic) and DB-free for unit testability.
+/// Keeps the catalog lean and scopes shadow output for events injected directly into the stream.
+pub(crate) fn retain_allowlisted(rows: &mut Vec<CohortRow>, allowlist: &TeamAllowlist) {
+ rows.retain(|row| allowlist.includes(row.team_id));
+}
+
+/// Group rows by team into a catalog. A cohort that fails to parse is counted, warned, and skipped
+/// rather than poisoning the rest of the catalog.
+pub fn build_catalog_from_rows(rows: Vec<CohortRow>, cascade_enabled: bool) -> FilterCatalog {
+ let mut builders: HashMap<TeamId, (TeamFiltersBuilder, Tz)> = HashMap::new();
+
+ for row in rows {
+ let team_id = TeamId(row.team_id);
+ let cohort_id = CohortId(row.id);
+ // The timezone is a team-level column, so resolve it once on the team's first row.
+ let (builder, _tz) = builders.entry(team_id).or_insert_with(|| {
+ (
+ TeamFiltersBuilder::default(),
+ resolve_team_tz(&row.timezone, team_id),
+ )
+ });
+
+ if let Err(err) = builder.add_cohort(cohort_id, team_id, &row.filters) {
+ counter!(FILTER_CATALOG_COHORT_PARSE_ERRORS).increment(1);
+ warn!(
+ cohort_id = cohort_id.0,
+ team_id = team_id.0,
+ error = %err,
+ "skipping cohort that failed to parse",
+ );
+ }
+ }
+
+ FilterCatalog::from_teams(
+ builders
+ .into_iter()
+ .map(|(team, (builder, tz))| (team, builder.freeze_with(tz, cascade_enabled))),
+ )
+}
+
+/// Resolve a team's `posthog_team.timezone`, falling back to UTC for an unrecognized zone. Counts
+/// and logs the fallback with the offending `team_id`. The raw string goes only to the `warn!`,
+/// never the (label-free) counter.
+fn resolve_team_tz(raw: &str, team_id: TeamId) -> Tz {
+ raw.parse::<Tz>().unwrap_or_else(|_| {
+ counter!(FILTER_CATALOG_TZ_FALLBACK).increment(1);
+ warn!(
+ team_id = team_id.0,
+ timezone = raw,
+ "unrecognized team timezone; falling back to UTC",
+ );
+ UTC
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashSet;
+
+ use super::*;
+ use serde_json::json;
+
+ fn row(id: i32, team_id: i32, filters: Value) -> CohortRow {
+ row_with_tz(id, team_id, filters, "UTC")
+ }
+
+ fn row_with_tz(id: i32, team_id: i32, filters: Value, timezone: &str) -> CohortRow {
+ CohortRow {
+ id,
+ team_id,
+ filters,
+ timezone: timezone.to_string(),
+ }
+ }
+
+ fn behavioral_cohort() -> Value {
+ json!({
+ "properties": {
+ "type": "AND",
+ "values": [{
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ }],
+ }
+ })
+ }
+
+ #[test]
+ fn empty_rows_build_an_empty_catalog() {
+ let catalog = build_catalog_from_rows(vec![], false);
+ assert_eq!(catalog.team_count(), 0);
+ }
+
+ #[test]
+ fn build_catalog_resolves_team_timezone_and_falls_back_to_utc() {
+ use chrono_tz::America::New_York;
+ let rows = vec![
+ row_with_tz(1, 7, behavioral_cohort(), "America/New_York"),
+ row_with_tz(2, 9, behavioral_cohort(), "not a real zone"),
+ ];
+ let catalog = build_catalog_from_rows(rows, false);
+ assert_eq!(catalog.team(TeamId(7)).expect("team 7").timezone, New_York);
+ assert_eq!(
+ catalog.team(TeamId(9)).expect("team 9").timezone,
+ UTC,
+ "an unrecognized zone falls back to UTC",
+ );
+ }
+
+ #[test]
+ fn malformed_cohort_is_skipped_without_poisoning_the_team() {
+ let rows = vec![
+ row(1, 7, json!({ "bogus": true })),
+ row(2, 7, behavioral_cohort()),
+ ];
+ let catalog = build_catalog_from_rows(rows, false);
+
+ let team = catalog.team(TeamId(7)).expect("team present");
+ assert!(team.cohorts.contains_key(&CohortId(2)));
+ assert!(!team.cohorts.contains_key(&CohortId(1)));
+ assert_eq!(team.unique_condition_hashes.len(), 1);
+ }
+
+ #[test]
+ fn build_catalog_threads_the_cascade_gate_into_freeze() {
+ use crate::stage2::{CohortEligibility, ExcludedReason};
+
+ let referrer = json!({
+ "properties": {
+ "type": "AND",
+ "values": [{ "type": "cohort", "value": 2, "negation": false }],
+ }
+ });
+ let rows = || vec![row(2, 7, behavioral_cohort()), row(1, 7, referrer.clone())];
+
+ let off = build_catalog_from_rows(rows(), false);
+ assert_eq!(
+ off.team(TeamId(7)).unwrap().eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ "gate off keeps the ref cohort excluded",
+ );
+
+ let on = build_catalog_from_rows(rows(), true);
+ assert_eq!(
+ on.team(TeamId(7)).unwrap().eligibility[&CohortId(1)],
+ CohortEligibility::Stage2ComposableRef,
+ "gate on promotes the resolvable ref cohort",
+ );
+ }
+
+ #[test]
+ fn retain_allowlisted_keeps_only_in_scope_rows() {
+ let mut rows = vec![
+ row(1, 2, behavioral_cohort()),
+ row(2, 7, behavioral_cohort()),
+ ];
+ retain_allowlisted(&mut rows, &TeamAllowlist::Only(HashSet::from([2])));
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].team_id, 2);
+ }
+
+ #[test]
+ fn retain_allowlisted_all_keeps_everything() {
+ let mut rows = vec![
+ row(1, 2, behavioral_cohort()),
+ row(2, 7, behavioral_cohort()),
+ ];
+ retain_allowlisted(&mut rows, &TeamAllowlist::All);
+ assert_eq!(rows.len(), 2);
+ }
+
+ #[test]
+ fn retain_allowlisted_empty_scope_drops_everything() {
+ let mut rows = vec![row(1, 2, behavioral_cohort())];
+ retain_allowlisted(&mut rows, &TeamAllowlist::Only(HashSet::new()));
+ assert!(rows.is_empty());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rs
new file mode 100644
index 000000000000..07eb061d064c
--- /dev/null
+++ b/rust/cohort-stream-processor/src/filters/manager.rs
@@ -0,0 +1,318 @@
+//! `FilterCatalog` + atomic swap + jittered periodic refresh loop.
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use arc_swap::{ArcSwap, Guard};
+use common_types::cohort::TeamAllowlist;
+use lifecycle::Handle;
+use metrics::gauge;
+use rand::Rng;
+use sqlx::PgPool;
+use tokio::sync::Notify;
+use tracing::{debug, info, warn};
+
+use crate::filters::loader::{build_catalog_from_rows, load_realtime_cohorts, retain_allowlisted};
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::{FilterError, TeamId};
+use crate::observability::metrics::{FILTER_CATALOG_TEAMS, FILTER_CATALOG_UNIQUE_CONDITIONS};
+
+#[derive(Debug, Default)]
+pub struct FilterCatalog {
+ teams: HashMap<TeamId, Arc<TeamFilters>>,
+}
+
+impl FilterCatalog {
+ pub fn new() -> Self {
+ Self {
+ teams: HashMap::new(),
+ }
+ }
+
+ /// The frozen filters for a team, or `None` if it has no realtime cohorts.
+ pub fn team(&self, team_id: TeamId) -> Option<&Arc<TeamFilters>> {
+ self.teams.get(&team_id)
+ }
+
+ pub fn team_count(&self) -> usize {
+ self.teams.len()
+ }
+
+ /// Total distinct conditionHashes across all teams (sum of the per-team dedup sets).
+ pub fn total_unique_conditions(&self) -> usize {
+ self.teams
+ .values()
+ .map(|team| team.unique_condition_hashes.len())
+ .sum()
+ }
+
+ pub fn from_teams(teams: impl IntoIterator<Item = (TeamId, TeamFilters)>) -> Self {
+ Self {
+ teams: teams
+ .into_iter()
+ .map(|(team, filters)| (team, Arc::new(filters)))
+ .collect(),
+ }
+ }
+}
+
+/// Snapshot counts returned by [`CatalogHandle::refresh`] for logging.
+#[derive(Debug, Clone, Copy)]
+pub struct CatalogStats {
+ pub teams: usize,
+ pub unique_conditions: usize,
+}
+
+/// Lock-free, atomically-swapped catalog handle. Starts empty and unloaded; the pipeline fails
+/// closed until the first successful refresh.
+pub struct CatalogHandle {
+ catalog: ArcSwap<FilterCatalog>,
+ loaded: AtomicBool,
+ loaded_notify: Notify,
+ /// Cohorts for teams outside this allowlist never enter the catalog.
+ allowlist: TeamAllowlist,
+ cascade_enabled: bool,
+}
+
+impl CatalogHandle {
+ pub fn new() -> Self {
+ Self::with_allowlist(TeamAllowlist::All, false)
+ }
+
+ pub fn with_allowlist(allowlist: TeamAllowlist, cascade_enabled: bool) -> Self {
+ Self {
+ catalog: ArcSwap::from_pointee(FilterCatalog::new()),
+ loaded: AtomicBool::new(false),
+ loaded_notify: Notify::new(),
+ allowlist,
+ cascade_enabled,
+ }
+ }
+
+ /// Load the current snapshot for a wait-free hot-path read.
+ pub fn load(&self) -> Guard<Arc<FilterCatalog>> {
+ self.catalog.load()
+ }
+
+ /// True once the first refresh has succeeded. Before that the catalog is empty and consumers
+ /// should treat every team as having no realtime cohorts.
+ pub fn is_loaded(&self) -> bool {
+ self.loaded.load(Ordering::Acquire)
+ }
+
+ /// Resolve once the first refresh has succeeded; immediate if it already has.
+ pub async fn wait_until_loaded(&self) {
+ while !self.is_loaded() {
+ // Register the waiter *before* re-checking, so a store that lands between the check and
+ // the await still wakes us (`notify_waiters` reaches futures created before the call).
+ let notified = self.loaded_notify.notified();
+ if self.is_loaded() {
+ return;
+ }
+ notified.await;
+ }
+ }
+
+ /// Build an already-loaded handle from a prebuilt catalog (test seam).
+ pub fn from_catalog(catalog: FilterCatalog) -> Self {
+ let handle = Self::new();
+ handle.store(catalog);
+ handle
+ }
+
+ fn store(&self, catalog: FilterCatalog) {
+ gauge!(FILTER_CATALOG_TEAMS).set(catalog.team_count() as f64);
+ gauge!(FILTER_CATALOG_UNIQUE_CONDITIONS).set(catalog.total_unique_conditions() as f64);
+ self.catalog.store(Arc::new(catalog));
+ self.loaded.store(true, Ordering::Release);
+ self.loaded_notify.notify_waiters();
+ }
+
+ /// Query `posthog_cohort`, drop out-of-scope teams, rebuild the catalog, and swap it in.
+ pub async fn refresh(&self, pool: &PgPool) -> Result<CatalogStats, FilterError> {
+ let mut rows = load_realtime_cohorts(pool).await?;
+ let fetched_rows = rows.len();
+ retain_allowlisted(&mut rows, &self.allowlist);
+ if rows.len() != fetched_rows {
+ debug!(
+ fetched_rows,
+ kept_rows = rows.len(),
+ "filter catalog dropped cohort rows outside REALTIME_COHORT_TEAM_ALLOWLIST",
+ );
+ }
+ let catalog = build_catalog_from_rows(rows, self.cascade_enabled);
+ let stats = CatalogStats {
+ teams: catalog.team_count(),
+ unique_conditions: catalog.total_unique_conditions(),
+ };
+ self.store(catalog);
+ Ok(stats)
+ }
+}
+
+impl Default for CatalogHandle {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Periodic catalog refresh task. On failure, keeps the previous snapshot and retries next tick.
+pub async fn run_refresh_loop(
+ catalog: Arc<CatalogHandle>,
+ pool: PgPool,
+ interval: Duration,
+ jitter: Duration,
+ handle: Handle,
+) {
+ let _guard = handle.process_scope();
+
+ loop {
+ let sleep_for = next_interval(interval, jitter);
+ tokio::select! {
+ _ = handle.shutdown_recv() => break,
+ _ = tokio::time::sleep(sleep_for) => match catalog.refresh(&pool).await {
+ Ok(stats) => info!(
+ teams = stats.teams,
+ unique_conditions = stats.unique_conditions,
+ "filter catalog refreshed",
+ ),
+ Err(err) => warn!(
+ error = %err,
+ "filter catalog refresh failed; keeping previous snapshot",
+ ),
+ },
+ }
+ }
+}
+
+/// A sleep duration uniformly in `[interval - jitter, interval + jitter]`.
+fn next_interval(interval: Duration, jitter: Duration) -> Duration {
+ if jitter.is_zero() {
+ return interval;
+ }
+ let lo = interval.saturating_sub(jitter).as_millis() as u64;
+ let hi = interval.saturating_add(jitter).as_millis() as u64;
+ let millis = rand::thread_rng().gen_range(lo..=hi);
+ Duration::from_millis(millis)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::UTC;
+ use serde_json::json;
+
+ use crate::filters::reverse_index::TeamFiltersBuilder;
+ use crate::filters::CohortId;
+
+ fn team_with_one_behavioral() -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ let filters = json!({
+ "properties": {
+ "type": "AND",
+ "values": [{
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ }],
+ }
+ });
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &filters)
+ .unwrap();
+ builder.freeze(UTC)
+ }
+
+ #[test]
+ fn new_handle_is_unloaded_and_empty() {
+ let handle = CatalogHandle::new();
+ assert!(!handle.is_loaded());
+ assert_eq!(handle.load().team_count(), 0);
+ }
+
+ #[test]
+ fn from_catalog_marks_loaded_and_populates_teams() {
+ let catalog = FilterCatalog::from_teams([(TeamId(7), team_with_one_behavioral())]);
+ let handle = CatalogHandle::from_catalog(catalog);
+
+ assert!(handle.is_loaded());
+ let snapshot = handle.load();
+ assert_eq!(snapshot.team_count(), 1);
+ assert!(snapshot.team(TeamId(7)).is_some());
+ assert!(snapshot.team(TeamId(8)).is_none());
+ assert_eq!(snapshot.total_unique_conditions(), 1);
+ }
+
+ #[tokio::test]
+ async fn wait_until_loaded_resolves_on_the_first_store_and_immediately_after() {
+ let handle = Arc::new(CatalogHandle::new());
+
+ let waiter = {
+ let handle = handle.clone();
+ tokio::spawn(async move { handle.wait_until_loaded().await })
+ };
+ // The waiter cannot resolve before the first store.
+ tokio::task::yield_now().await;
+ assert!(!waiter.is_finished());
+
+ handle.store(FilterCatalog::from_teams([(
+ TeamId(7),
+ team_with_one_behavioral(),
+ )]));
+ waiter.await.expect("waiter resolves on the first store");
+
+ // Already loaded → immediate.
+ handle.wait_until_loaded().await;
+ }
+
+ #[test]
+ fn next_interval_without_jitter_is_exact() {
+ let interval = Duration::from_secs(300);
+ assert_eq!(next_interval(interval, Duration::ZERO), interval);
+ }
+
+ #[test]
+ fn next_interval_stays_within_jitter_band() {
+ let interval = Duration::from_secs(300);
+ let jitter = Duration::from_secs(60);
+ for _ in 0..1000 {
+ let sleep_for = next_interval(interval, jitter);
+ assert!(
+ sleep_for >= Duration::from_secs(240),
+ "{sleep_for:?} below bound"
+ );
+ assert!(
+ sleep_for <= Duration::from_secs(360),
+ "{sleep_for:?} above bound"
+ );
+ }
+ }
+
+ /// Requires a live Postgres; run with `cargo test -p cohort-stream-processor -- --ignored`.
+ #[tokio::test]
+ #[ignore]
+ async fn refresh_builds_catalog_from_live_postgres() {
+ let url = std::env::var("DATABASE_URL")
+ .unwrap_or_else(|_| "postgres://posthog:posthog@localhost:5432/posthog".to_string());
+ let pool =
+ common_database::get_pool_with_config(&url, common_database::PoolConfig::default())
+ .expect("build posthog_cohort pool");
+
+ let handle = CatalogHandle::new();
+ assert!(!handle.is_loaded());
+
+ let stats = handle
+ .refresh(&pool)
+ .await
+ .expect("refresh against live posthog_cohort");
+
+ assert!(handle.is_loaded());
+ assert_eq!(handle.load().team_count(), stats.teams);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/filters/mod.rs b/rust/cohort-stream-processor/src/filters/mod.rs
new file mode 100644
index 000000000000..8aa3db496081
--- /dev/null
+++ b/rust/cohort-stream-processor/src/filters/mod.rs
@@ -0,0 +1,40 @@
+//! Filter catalog: the in-memory view of realtime cohorts.
+
+pub(crate) mod cohort_graph;
+pub mod leaf_classifier;
+pub mod loader;
+pub mod manager;
+pub mod reverse_index;
+pub mod tree;
+
+use thiserror::Error;
+
+pub use leaf_classifier::{classify_leaf, LeafClass, LeafDropReason};
+pub use loader::{build_catalog_from_rows, load_realtime_cohorts, CohortRow, REALTIME_COHORTS_SQL};
+pub use manager::{run_refresh_loop, CatalogHandle, CatalogStats, FilterCatalog};
+pub use reverse_index::{TeamFilters, TeamFiltersBuilder};
+pub use tree::{
+ parse_cohort_tree, BehavioralLeafConfig, BehavioralValue, BoolOp, CohortLeaf,
+ CohortRefLeafConfig, CohortTree, FilterNode, LeafSink, PersonLeafConfig,
+};
+
+/// Team identifier (`posthog_cohort.team_id`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct TeamId(pub i32);
+
+/// Cohort identifier (`posthog_cohort.id`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct CohortId(pub i32);
+
+/// Errors from loading or parsing the filter catalog.
+#[derive(Debug, Error)]
+pub enum FilterError {
+ #[error("querying posthog_cohort: {0}")]
+ Query(#[from] sqlx::Error),
+
+ #[error("cohort {cohort_id} filters has no `properties`")]
+ MissingProperties { cohort_id: i32 },
+
+ #[error("cohort {cohort_id} is malformed: {detail}")]
+ Malformed { cohort_id: i32, detail: String },
+}
diff --git a/rust/cohort-stream-processor/src/filters/reverse_index.rs b/rust/cohort-stream-processor/src/filters/reverse_index.rs
new file mode 100644
index 000000000000..6f1aae003039
--- /dev/null
+++ b/rust/cohort-stream-processor/src/filters/reverse_index.rs
@@ -0,0 +1,1387 @@
+//! Per-team reverse indices, dedup set, and eligibility classification.
+
+use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
+
+use chrono_tz::{Tz, UTC};
+use metrics::counter;
+use serde_json::Value;
+use tracing::warn;
+
+use crate::filters::cohort_graph;
+use crate::filters::leaf_classifier::LeafDropReason;
+use crate::filters::tree::{parse_cohort_tree, CohortLeaf, CohortTree, FilterNode, LeafSink};
+use crate::filters::{CohortId, FilterError, TeamId};
+use crate::observability::metrics::{
+ COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_SKIPPED_LEAVES,
+};
+use crate::stage1::key::LeafStateKey;
+use crate::stage1::pick_state::{
+ effective_window_days, pick_state_variant, EvictionWindow, PredicateOp,
+};
+use crate::stage1::state::StateVariant;
+use crate::stage2::eligibility::refine_ref_bearing;
+use crate::stage2::{classify, CohortEligibility, CohortParseFlags};
+
+#[derive(Debug, Clone, Copy)]
+pub struct LeafStateMeta {
+ pub variant: StateVariant,
+ /// The leaf's `conditionHash` (the event-matcher hash).
+ pub condition_hash: [u8; 16],
+ /// `BehavioralSingle` only; `None` for bucket and person variants.
+ pub window: Option<EvictionWindow>,
+ /// Window length in days — `Some` for daily-bucket and compressed variants, `None` otherwise.
+ pub window_days: Option<u32>,
+ /// Count comparator for a window's sum — `Some` for daily-bucket and compressed, `None` otherwise.
+ pub predicate_op: Option<PredicateOp>,
+}
+
+#[derive(Debug)]
+pub struct TeamFilters {
+ pub by_condition_to_lsk: HashMap<[u8; 16], Vec<LeafStateKey>>,
+ /// `conditionHash → [CohortId]` for the Stage 2 walk back to owning cohorts.
+ pub by_condition_to_cohorts: HashMap<[u8; 16], Vec<CohortId>>,
+ /// `conditionHash → bytecode`. One entry per conditionHash.
+ pub by_condition_to_bytecode: HashMap<[u8; 16], Arc<Vec<Value>>>,
+ pub unique_condition_hashes: HashSet<[u8; 16]>,
+ pub by_lsk: HashMap<LeafStateKey, LeafStateMeta>,
+ /// conditionHashes whose leaves are behavioral. Disjoint from person-property conditions.
+ pub behavioral_conditions: HashSet<[u8; 16]>,
+ pub person_property_conditions: HashSet<[u8; 16]>,
+ /// `LeafStateKey → [CohortId]` for single-leaf cohorts.
+ pub by_lsk_to_single_leaf_cohorts: HashMap<LeafStateKey, Vec<CohortId>>,
+ /// `LeafStateKey → [CohortId]` for `Stage2Composable` cohorts.
+ pub by_lsk_to_composable_cohorts: HashMap<LeafStateKey, Vec<CohortId>>,
+ /// `referenced cohort → [referrer cohorts]`, sorted. The structural inverse of the reference
+ /// graph; read via [`TeamFilters::cohorts_referencing`].
+ pub by_referenced_cohort: HashMap<CohortId, Vec<CohortId>>,
+ /// Each cohort's composition class, computed once at freeze.
+ pub eligibility: HashMap<CohortId, CohortEligibility>,
+ /// Parsed trees by cohort, retained for the Stage 2 re-walk.
+ pub cohorts: HashMap<CohortId, CohortTree>,
+ /// The team's resolved IANA timezone, used by bucket variants for calendar-day computation.
+ pub timezone: Tz,
+}
+
+/// Hand-written because [`Tz`] has no [`Default`].
+impl Default for TeamFilters {
+ fn default() -> Self {
+ Self {
+ by_condition_to_lsk: HashMap::new(),
+ by_condition_to_cohorts: HashMap::new(),
+ by_condition_to_bytecode: HashMap::new(),
+ unique_condition_hashes: HashSet::new(),
+ by_lsk: HashMap::new(),
+ behavioral_conditions: HashSet::new(),
+ person_property_conditions: HashSet::new(),
+ by_lsk_to_single_leaf_cohorts: HashMap::new(),
+ by_lsk_to_composable_cohorts: HashMap::new(),
+ by_referenced_cohort: HashMap::new(),
+ eligibility: HashMap::new(),
+ cohorts: HashMap::new(),
+ timezone: UTC,
+ }
+ }
+}
+
+impl TeamFilters {
+ /// Cohorts that reference `id`, sorted ascending; empty when none.
+ pub fn cohorts_referencing(&self, id: CohortId) -> &[CohortId] {
+ self.by_referenced_cohort
+ .get(&id)
+ .map_or(&[], Vec::as_slice)
+ }
+}
+
+/// Accumulates a team's filters across its cohorts, then freezes into an immutable [`TeamFilters`].
+#[derive(Debug, Default)]
+pub struct TeamFiltersBuilder {
+ by_condition_to_lsk: HashMap<[u8; 16], HashSet<LeafStateKey>>,
+ by_condition_to_cohorts: HashMap<[u8; 16], HashSet<CohortId>>,
+ by_condition_to_bytecode: HashMap<[u8; 16], Arc<Vec<Value>>>,
+ unique_condition_hashes: HashSet<[u8; 16]>,
+ cohorts: HashMap<CohortId, CohortTree>,
+ /// Per-cohort eligibility signals captured during parse.
+ flags: HashMap<CohortId, CohortParseFlags>,
+}
+
+impl LeafSink for TeamFiltersBuilder {
+ fn record_state_keyed(
+ &mut self,
+ cohort_id: CohortId,
+ condition_hash: [u8; 16],
+ leaf_state_key: LeafStateKey,
+ bytecode: &Arc<Vec<Value>>,
+ ) {
+ self.by_condition_to_lsk
+ .entry(condition_hash)
+ .or_default()
+ .insert(leaf_state_key);
+ self.by_condition_to_cohorts
+ .entry(condition_hash)
+ .or_default()
+ .insert(cohort_id);
+ self.by_condition_to_bytecode
+ .entry(condition_hash)
+ .or_insert_with(|| Arc::clone(bytecode));
+ self.unique_condition_hashes.insert(condition_hash);
+
+ let flags = self.flags.entry(cohort_id).or_default();
+ flags.state_keyed_leaf_count += 1;
+ }
+
+ fn record_cohort_ref(&mut self, cohort_id: CohortId) {
+ self.flags.entry(cohort_id).or_default().has_cohort_ref = true;
+ }
+
+ fn record_dropped(&mut self, cohort_id: CohortId, reason: LeafDropReason) {
+ counter!(FILTER_CATALOG_SKIPPED_LEAVES, "reason" => reason.as_str()).increment(1);
+ self.flags.entry(cohort_id).or_default().has_dropped_leaf = true;
+ }
+}
+
+impl TeamFiltersBuilder {
+ pub fn add_cohort(
+ &mut self,
+ cohort_id: CohortId,
+ team_id: TeamId,
+ filters: &Value,
+ ) -> Result<(), FilterError> {
+ let tree = parse_cohort_tree(cohort_id, team_id, filters, self)?;
+ self.cohorts.insert(cohort_id, tree);
+ Ok(())
+ }
+
+ /// Equivalent to `freeze_with(timezone, false)`.
+ pub fn freeze(self, timezone: Tz) -> TeamFilters {
+ self.freeze_with(timezone, false)
+ }
+
+ /// Freeze into an immutable [`TeamFilters`]. When `cascade_enabled`, resolvable cycle-free
+ /// ref-bearing cohorts become [`CohortEligibility::Stage2ComposableRef`] and join the composable
+ /// emit-map by their own leaves; otherwise they stay `Excluded(HasCohortRef)`.
+ pub fn freeze_with(self, timezone: Tz, cascade_enabled: bool) -> TeamFilters {
+ let mut by_lsk = HashMap::new();
+ let mut behavioral_conditions = HashSet::new();
+ let mut person_property_conditions = HashSet::new();
+
+ let mut eligibility: HashMap<CohortId, CohortEligibility> = HashMap::new();
+ for tree in self.cohorts.values() {
+ collect_leaf_meta(
+ &tree.root,
+ &mut by_lsk,
+ &mut behavioral_conditions,
+ &mut person_property_conditions,
+ );
+ let flags = self.flags.get(&tree.cohort_id).copied().unwrap_or_default();
+ eligibility.insert(tree.cohort_id, classify(tree, &flags));
+ }
+
+ let mut by_referenced_cohort: HashMap<CohortId, Vec<CohortId>> = HashMap::new();
+ if self.flags.values().any(|flags| flags.has_cohort_ref) {
+ let analysis = cohort_graph::analyze(&self.cohorts);
+ refine_ref_bearing(&mut eligibility, &analysis, cascade_enabled);
+ // Invert the reference graph (referenced → [referrers]). Not filtered by eligibility, so
+ // it stays populated even though referrers are excluded from composition.
+ for (&referrer, targets) in &analysis.ref_targets {
+ for &target in targets {
+ by_referenced_cohort
+ .entry(target)
+ .or_default()
+ .push(referrer);
+ }
+ }
+ for referrers in by_referenced_cohort.values_mut() {
+ referrers.sort_unstable();
+ }
+ if !analysis.in_cycle.is_empty() {
+ counter!(COHORT_IN_CYCLE_TOTAL).increment(analysis.in_cycle.len() as u64);
+ let mut cycle_ids: Vec<i32> = analysis.in_cycle.iter().map(|id| id.0).collect();
+ cycle_ids.sort_unstable();
+ // One builder holds exactly one team, so any cohort's `team_id` is the team's.
+ let team_id = self
+ .cohorts
+ .values()
+ .next()
+ .map_or(0, |tree| tree.team_id.0);
+ warn!(
+ team_id,
+ ?cycle_ids,
+ "cohort reference cycle detected; excluding members from composition",
+ );
+ }
+ }
+
+ let mut by_lsk_to_single_leaf_cohorts: HashMap<LeafStateKey, Vec<CohortId>> =
+ HashMap::new();
+ let mut by_lsk_to_composable_cohorts: HashMap<LeafStateKey, Vec<CohortId>> = HashMap::new();
+ for tree in self.cohorts.values() {
+ let class = eligibility[&tree.cohort_id];
+ counter!(COHORT_ELIGIBILITY_TOTAL, "class" => class.metric_class()).increment(1);
+ match class {
+ CohortEligibility::SingleLeaf(lsk) => {
+ by_lsk_to_single_leaf_cohorts
+ .entry(lsk)
+ .or_default()
+ .push(tree.cohort_id);
+ }
+ // Both composable classes index their own state-keyed leaves; a pure-ref cohort has
+ // none, so it contributes nothing here.
+ CohortEligibility::Stage2Composable | CohortEligibility::Stage2ComposableRef => {
+ let mut leaf_keys = HashSet::new();
+ collect_leaf_state_keys(&tree.root, &mut leaf_keys);
+ for lsk in leaf_keys {
+ by_lsk_to_composable_cohorts
+ .entry(lsk)
+ .or_default()
+ .push(tree.cohort_id);
+ }
+ }
+ CohortEligibility::Excluded(_) => {}
+ }
+ }
+ for cohorts in by_lsk_to_single_leaf_cohorts.values_mut() {
+ cohorts.sort_unstable();
+ }
+ for cohorts in by_lsk_to_composable_cohorts.values_mut() {
+ cohorts.sort_unstable();
+ }
+
+ TeamFilters {
+ by_condition_to_lsk: sorted_vec_map(self.by_condition_to_lsk),
+ by_condition_to_cohorts: sorted_vec_map(self.by_condition_to_cohorts),
+ by_condition_to_bytecode: self.by_condition_to_bytecode,
+ unique_condition_hashes: self.unique_condition_hashes,
+ by_lsk,
+ behavioral_conditions,
+ person_property_conditions,
+ by_lsk_to_single_leaf_cohorts,
+ by_lsk_to_composable_cohorts,
+ by_referenced_cohort,
+ eligibility,
+ cohorts: self.cohorts,
+ timezone,
+ }
+ }
+}
+
+/// The distinct [`LeafStateKey`]s of every state-keyed leaf in a tree.
+fn collect_leaf_state_keys(node: &FilterNode, out: &mut HashSet<LeafStateKey>) {
+ match node {
+ FilterNode::Group { children, .. } => {
+ for child in children {
+ collect_leaf_state_keys(child, out);
+ }
+ }
+ FilterNode::Leaf(leaf) => {
+ if let Some(lsk) = leaf.leaf_state_key() {
+ out.insert(lsk);
+ }
+ }
+ }
+}
+
+fn collect_leaf_meta(
+ node: &FilterNode,
+ by_lsk: &mut HashMap<LeafStateKey, LeafStateMeta>,
+ behavioral_conditions: &mut HashSet<[u8; 16]>,
+ person_property_conditions: &mut HashSet<[u8; 16]>,
+) {
+ match node {
+ FilterNode::Group { children, .. } => {
+ for child in children {
+ collect_leaf_meta(
+ child,
+ by_lsk,
+ behavioral_conditions,
+ person_property_conditions,
+ );
+ }
+ }
+ FilterNode::Leaf(CohortLeaf::Behavioral(leaf)) => {
+ if let Ok((variant, window)) = pick_state_variant(leaf) {
+ let (window_days, predicate_op) = match variant {
+ StateVariant::BehavioralDailyBuckets
+ | StateVariant::BehavioralCompressedHistory => (
+ Some(effective_window_days(leaf)),
+ Some(PredicateOp::from_leaf(
+ leaf.operator.as_deref(),
+ leaf.operator_value,
+ )),
+ ),
+ StateVariant::BehavioralSingle | StateVariant::PersonProperty => (None, None),
+ };
+ by_lsk.insert(
+ leaf.leaf_state_key,
+ LeafStateMeta {
+ variant,
+ condition_hash: leaf.condition_hash,
+ window,
+ window_days,
+ predicate_op,
+ },
+ );
+ behavioral_conditions.insert(leaf.condition_hash);
+ }
+ }
+ FilterNode::Leaf(CohortLeaf::PersonProperty(leaf)) => {
+ by_lsk.insert(
+ leaf.leaf_state_key,
+ LeafStateMeta {
+ variant: StateVariant::PersonProperty,
+ condition_hash: leaf.condition_hash,
+ window: None,
+ window_days: None,
+ predicate_op: None,
+ },
+ );
+ person_property_conditions.insert(leaf.condition_hash);
+ }
+ FilterNode::Leaf(CohortLeaf::CohortRef(_)) => {}
+ }
+}
+
+/// Vec-ify a `conditionHash → HashSet<V>` map, sorting each value list for determinism.
+fn sorted_vec_map<V: Ord>(map: HashMap<[u8; 16], HashSet<V>>) -> HashMap<[u8; 16], Vec<V>> {
+ map.into_iter()
+ .map(|(hash, set)| {
+ let mut values: Vec<V> = set.into_iter().collect();
+ values.sort_unstable();
+ (hash, values)
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ use crate::stage2::ExcludedReason;
+
+ const HASH: [u8; 16] = *b"0123456789abcdef";
+
+ const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
+
+ fn behavioral_bytecode() -> Value {
+ json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
+ }
+
+ /// A `performed_event` leaf on `$pageview` with a tunable window.
+ fn behavioral_performed_event(time_value: i64) -> Value {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": time_value,
+ "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ // Identical across windows: leaves sharing a conditionHash share bytecode.
+ "bytecode": behavioral_bytecode(),
+ })
+ }
+
+ fn behavioral_performed_event_multiple(
+ time_value: i64,
+ time_interval: &str,
+ operator: &str,
+ operator_value: i64,
+ ) -> Value {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "time_value": time_value,
+ "time_interval": time_interval,
+ "operator": operator,
+ "operator_value": operator_value,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": behavioral_bytecode(),
+ })
+ }
+
+ fn person_leaf() -> Value {
+ json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+ }
+
+ fn wrap(values: Vec<Value>) -> Value {
+ json!({ "properties": { "type": "AND", "values": values } })
+ }
+
+ #[test]
+ fn freeze_carries_the_timezone_and_default_is_utc() {
+ use chrono_tz::America::New_York;
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ assert_eq!(builder.freeze(New_York).timezone, New_York);
+ assert_eq!(
+ TeamFilters::default().timezone,
+ UTC,
+ "an empty filter set defaults to UTC",
+ );
+ }
+
+ #[test]
+ fn identical_leaves_dedupe_to_single_entries() {
+ let mut builder = TeamFiltersBuilder::default();
+ let filters = wrap(vec![
+ behavioral_performed_event(7),
+ behavioral_performed_event(7),
+ ]);
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &filters)
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(frozen.by_condition_to_lsk[&HASH].len(), 1);
+ assert_eq!(frozen.by_condition_to_cohorts[&HASH], vec![CohortId(1)]);
+ assert_eq!(frozen.unique_condition_hashes.len(), 1);
+ }
+
+ #[test]
+ fn same_hash_different_windows_fan_out_to_distinct_leaf_state_keys() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(30)]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(frozen.by_condition_to_lsk[&HASH].len(), 2);
+ assert_eq!(
+ frozen.by_condition_to_cohorts[&HASH],
+ vec![CohortId(1), CohortId(2)]
+ );
+ assert_eq!(frozen.unique_condition_hashes.len(), 1);
+ assert_eq!(frozen.by_condition_to_bytecode.len(), 1);
+ }
+
+ #[test]
+ fn bytecode_is_captured_under_its_condition_hash() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let bytecode = frozen
+ .by_condition_to_bytecode
+ .get(&HASH)
+ .expect("bytecode captured under the conditionHash");
+ assert_eq!(bytecode.as_ref(), behavioral_bytecode().as_array().unwrap());
+ }
+
+ #[test]
+ fn freeze_builds_by_lsk_with_variant_and_window() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7), person_leaf()]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(frozen.by_lsk.len(), 2);
+
+ let beh_lsk = frozen.by_condition_to_lsk[&HASH][0];
+ let beh_meta = frozen.by_lsk[&beh_lsk];
+ assert_eq!(beh_meta.variant, StateVariant::BehavioralSingle);
+ assert_eq!(
+ beh_meta.window,
+ Some(EvictionWindow::RelativeDays { days: 7 })
+ );
+
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let per_meta = frozen.by_lsk[&per_lsk];
+ assert_eq!(per_meta.variant, StateVariant::PersonProperty);
+ assert_eq!(per_meta.window, None);
+ assert_eq!(per_meta.window_days, None);
+ assert_eq!(per_meta.predicate_op, None);
+ }
+
+ #[test]
+ fn freeze_daily_bucket_leaf_carries_window_days_and_op() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event_multiple(
+ 7, "day", "gte", 3,
+ )]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let lsk = frozen.by_condition_to_lsk[&HASH][0];
+ let meta = frozen.by_lsk[&lsk];
+ assert_eq!(meta.variant, StateVariant::BehavioralDailyBuckets);
+ assert_eq!(meta.window, None, "daily buckets carry no relative window");
+ assert_eq!(meta.window_days, Some(7));
+ assert_eq!(meta.predicate_op, Some(PredicateOp::Gte(3)));
+ assert!(
+ frozen.behavioral_conditions.contains(&HASH),
+ "the multiple leaf's conditionHash is behavioral",
+ );
+ }
+
+ #[test]
+ fn freeze_compressed_leaf_carries_window_days_and_op() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event_multiple(
+ 1, "year", "gte", 3,
+ )]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let lsk = frozen.by_condition_to_lsk[&HASH][0];
+ let meta = frozen.by_lsk[&lsk];
+ assert_eq!(meta.variant, StateVariant::BehavioralCompressedHistory);
+ assert_eq!(meta.window, None, "compressed carries no relative window");
+ assert_eq!(meta.window_days, Some(365), "year = 365 days");
+ assert_eq!(meta.predicate_op, Some(PredicateOp::Gte(3)));
+ assert!(frozen.behavioral_conditions.contains(&HASH));
+ }
+
+ #[test]
+ fn freeze_drops_an_hourly_deferred_multiple() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event_multiple(
+ 5, "hour", "gte", 3,
+ )]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+ assert!(
+ frozen.by_lsk.is_empty(),
+ "an hourly-deferred multiple leaves no worker metadata",
+ );
+ }
+
+ #[test]
+ fn freeze_partitions_conditions_by_kind() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7), person_leaf()]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.behavioral_conditions,
+ HashSet::from([HASH]),
+ "the performed_event conditionHash is behavioral",
+ );
+ assert_eq!(
+ frozen.person_property_conditions,
+ HashSet::from([PERSON_HASH]),
+ "the person conditionHash is person-property",
+ );
+ assert!(frozen
+ .behavioral_conditions
+ .is_disjoint(&frozen.person_property_conditions));
+ }
+
+ #[test]
+ fn freeze_recurses_into_nested_groups() {
+ let mut builder = TeamFiltersBuilder::default();
+ let filters = json!({
+ "properties": {
+ "type": "OR",
+ "values": [{
+ "type": "AND",
+ "values": [behavioral_performed_event(7)],
+ }],
+ }
+ });
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &filters)
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(frozen.by_lsk.len(), 1);
+ assert_eq!(frozen.behavioral_conditions, HashSet::from([HASH]));
+ }
+
+ fn cohort_ref() -> Value {
+ json!({ "type": "cohort", "value": 99, "negation": false })
+ }
+
+ fn cohort_ref_to(target: i32) -> Value {
+ json!({ "type": "cohort", "value": target, "negation": false })
+ }
+
+ /// A negated cohort-reference leaf (`NOT in target`).
+ fn cohort_ref_to_negated(target: i32) -> Value {
+ json!({ "type": "cohort", "value": target, "negation": true })
+ }
+
+ #[test]
+ fn single_leaf_cohort_is_indexed_by_its_lsk() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let lsk = frozen.by_condition_to_lsk[&HASH][0];
+ assert_eq!(
+ frozen.by_lsk_to_single_leaf_cohorts.get(&lsk),
+ Some(&vec![CohortId(1)]),
+ );
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::SingleLeaf(lsk),
+ );
+ }
+
+ #[test]
+ fn c1_two_single_leaf_cohorts_same_hash_different_windows_map_to_their_own_lsk() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(30)]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.by_condition_to_cohorts[&HASH],
+ vec![CohortId(1), CohortId(2)]
+ );
+
+ let lsks = &frozen.by_condition_to_lsk[&HASH];
+ assert_eq!(lsks.len(), 2);
+ let mut owners: Vec<Vec<CohortId>> = lsks
+ .iter()
+ .map(|lsk| frozen.by_lsk_to_single_leaf_cohorts[lsk].clone())
+ .collect();
+ owners.sort();
+ assert_eq!(owners, vec![vec![CohortId(1)], vec![CohortId(2)]]);
+ }
+
+ #[test]
+ fn identical_single_leaf_cohorts_share_one_lsk_sorted() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let lsk = frozen.by_condition_to_lsk[&HASH][0];
+ assert_eq!(
+ frozen.by_lsk_to_single_leaf_cohorts[&lsk],
+ vec![CohortId(1), CohortId(2)],
+ );
+ }
+
+ #[test]
+ fn multi_leaf_cohort_is_not_indexed() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7), person_leaf()]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert!(
+ frozen.by_lsk_to_single_leaf_cohorts.is_empty(),
+ "multi-leaf cohort contributes no single-leaf mapping",
+ );
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2Composable,
+ "two positive state leaves are composable",
+ );
+ }
+
+ #[test]
+ fn single_cohort_ref_cohort_is_not_indexed() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(vec![cohort_ref()]))
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert!(frozen.by_lsk_to_single_leaf_cohorts.is_empty());
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+ }
+
+ #[test]
+ fn nested_single_leaf_cohort_is_indexed() {
+ let mut builder = TeamFiltersBuilder::default();
+ let filters = json!({
+ "properties": {
+ "type": "OR",
+ "values": [{ "type": "AND", "values": [behavioral_performed_event(7)] }],
+ }
+ });
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &filters)
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let lsk = frozen.by_condition_to_lsk[&HASH][0];
+ assert_eq!(
+ frozen.by_lsk_to_single_leaf_cohorts[&lsk],
+ vec![CohortId(1)]
+ );
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::SingleLeaf(lsk),
+ );
+ }
+
+ #[test]
+ fn empty_all_dropped_cohort_is_not_indexed() {
+ let mut builder = TeamFiltersBuilder::default();
+ let dropped =
+ json!({ "type": "behavioral", "key": "$pageview", "value": "performed_event" });
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(vec![dropped]))
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert!(frozen.by_lsk_to_single_leaf_cohorts.is_empty());
+ assert!(
+ frozen.by_lsk.is_empty(),
+ "the dropped leaf left no state metadata"
+ );
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf),
+ );
+ }
+
+ #[test]
+ fn collapse_shape_with_dropped_sibling_is_excluded_not_single_leaf() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![
+ behavioral_performed_event_multiple(5, "hour", "gte", 3),
+ behavioral_performed_event(7),
+ ]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf),
+ );
+ assert!(
+ frozen.by_lsk_to_single_leaf_cohorts.is_empty(),
+ "the surviving leaf must NOT map the dropped-sibling cohort as single-leaf",
+ );
+ assert_eq!(
+ frozen.by_lsk.len(),
+ 1,
+ "the surviving leaf still carries meta"
+ );
+ }
+
+ #[test]
+ fn negated_single_behavioral_leaf_is_excluded_top_level_negation() {
+ let mut leaf = behavioral_performed_event(7);
+ leaf.as_object_mut()
+ .unwrap()
+ .insert("negation".to_string(), json!(true));
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(vec![leaf]))
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ );
+ assert!(
+ frozen.by_lsk_to_single_leaf_cohorts.is_empty(),
+ "an explicitly negated single leaf must not map as single-leaf",
+ );
+ }
+
+ #[test]
+ fn not_in_operator_alone_does_not_negate_a_state_keyed_leaf() {
+ // `operator: "not_in"` on a person/behavioral leaf is a value-list predicate compiled into
+ // the bytecode, not a composition negation. Only the cohort-ref form treats `not_in` as negation.
+ let mut leaf = person_leaf();
+ leaf.as_object_mut()
+ .unwrap()
+ .insert("operator".to_string(), json!("not_in"));
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(vec![leaf]))
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::SingleLeaf(lsk),
+ "a person `not_in` predicate is positive membership, not a negated cohort",
+ );
+ assert_eq!(
+ frozen.by_lsk_to_single_leaf_cohorts[&lsk],
+ vec![CohortId(1)]
+ );
+ }
+
+ #[test]
+ fn negated_single_person_leaf_is_excluded_top_level_negation() {
+ let mut leaf = person_leaf();
+ leaf.as_object_mut()
+ .unwrap()
+ .insert("negation".to_string(), json!(true));
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(vec![leaf]))
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ );
+ assert!(frozen.by_lsk_to_single_leaf_cohorts.is_empty());
+ }
+
+ #[test]
+ fn composable_cohort_indexes_each_distinct_leaf_to_itself() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7), person_leaf()]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2Composable,
+ );
+ let beh_lsk = frozen.by_condition_to_lsk[&HASH][0];
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ assert_eq!(
+ frozen.by_lsk_to_composable_cohorts[&beh_lsk],
+ vec![CohortId(1)],
+ );
+ assert_eq!(
+ frozen.by_lsk_to_composable_cohorts[&per_lsk],
+ vec![CohortId(1)],
+ );
+ assert!(
+ frozen.by_lsk_to_single_leaf_cohorts.is_empty(),
+ "a composable cohort contributes no single-leaf mapping",
+ );
+ }
+
+ #[test]
+ fn composable_same_hash_different_windows_index_distinct_lsks_not_the_condition_hash() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![
+ behavioral_performed_event(7),
+ behavioral_performed_event(30),
+ ]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let lsks = &frozen.by_condition_to_lsk[&HASH];
+ assert_eq!(
+ lsks.len(),
+ 2,
+ "two windows fan out to two LSKs under one hash"
+ );
+ for lsk in lsks {
+ assert_eq!(
+ frozen.by_lsk_to_composable_cohorts[lsk],
+ vec![CohortId(1)],
+ "each window's LSK maps to the composable cohort",
+ );
+ }
+ }
+
+ #[test]
+ fn composable_cohort_with_duplicate_leaf_is_indexed_once() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![
+ behavioral_performed_event(7),
+ behavioral_performed_event(7),
+ ]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2Composable,
+ );
+ let lsk = frozen.by_condition_to_lsk[&HASH][0];
+ assert_eq!(
+ frozen.by_lsk_to_composable_cohorts[&lsk],
+ vec![CohortId(1)],
+ "a duplicated leaf indexes the cohort once, not twice",
+ );
+ }
+
+ #[test]
+ fn leaf_shared_by_single_leaf_and_composable_cohorts_appears_in_both_maps() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7), person_leaf()]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let beh_lsk = frozen.by_condition_to_lsk[&HASH][0];
+ assert_eq!(
+ frozen.by_lsk_to_single_leaf_cohorts[&beh_lsk],
+ vec![CohortId(1)],
+ "the bare leaf drives cohort 1's whole membership",
+ );
+ assert_eq!(
+ frozen.by_lsk_to_composable_cohorts[&beh_lsk],
+ vec![CohortId(2)],
+ "the same leaf, as one input to cohort 2, fans Stage 2 back to cohort 2",
+ );
+ }
+
+ #[test]
+ fn and_a_neg_b_is_composable_with_both_lsks_in_composable_map() {
+ let mut neg_person = person_leaf();
+ neg_person
+ .as_object_mut()
+ .unwrap()
+ .insert("negation".to_string(), json!(true));
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7), neg_person]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2Composable,
+ "AND(A, ¬B) is composable — the root is not all-negated",
+ );
+ let beh_lsk = frozen.by_condition_to_lsk[&HASH][0];
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ assert_eq!(
+ frozen.by_lsk_to_composable_cohorts[&beh_lsk],
+ vec![CohortId(1)],
+ );
+ assert_eq!(
+ frozen.by_lsk_to_composable_cohorts[&per_lsk],
+ vec![CohortId(1)],
+ );
+ assert!(
+ frozen.by_lsk.contains_key(&per_lsk),
+ "the negated leaf carries state metadata",
+ );
+ }
+
+ #[test]
+ fn and_leaf_empty_or_is_excluded_empty_group() {
+ let filters = json!({
+ "properties": {
+ "type": "AND",
+ "values": [
+ behavioral_performed_event(7),
+ { "type": "OR", "values": [] },
+ ],
+ }
+ });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &filters)
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::EmptyGroup),
+ );
+ assert!(
+ frozen.by_lsk_to_single_leaf_cohorts.is_empty(),
+ "an empty-group cohort must not map as single-leaf",
+ );
+ }
+
+ #[test]
+ fn single_leaf_and_excluded_cohorts_contribute_nothing_to_the_composable_map() {
+ let mut builder = TeamFiltersBuilder::default();
+ // Single-leaf.
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ // Excluded (cohort ref).
+ builder
+ .add_cohort(CohortId(2), TeamId(7), &wrap(vec![cohort_ref()]))
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert!(
+ frozen.by_lsk_to_composable_cohorts.is_empty(),
+ "neither a single-leaf nor an excluded cohort is composable",
+ );
+ }
+
+ #[test]
+ fn reverse_index_inverts_ref_targets() {
+ let mut builder = TeamFiltersBuilder::default();
+ // A(1) → B(2), D(4); C(3) → B(2).
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![cohort_ref_to(2), cohort_ref_to(4)]),
+ )
+ .unwrap();
+ builder
+ .add_cohort(CohortId(3), TeamId(7), &wrap(vec![cohort_ref_to(2)]))
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.cohorts_referencing(CohortId(2)),
+ [CohortId(1), CohortId(3)].as_slice(),
+ "B is referenced by A and C, sorted",
+ );
+ assert_eq!(
+ frozen.cohorts_referencing(CohortId(4)),
+ [CohortId(1)].as_slice(),
+ );
+ assert!(
+ frozen.cohorts_referencing(CohortId(5)).is_empty(),
+ "an unreferenced cohort has no referrers",
+ );
+ }
+
+ #[test]
+ fn ref_bearing_cohort_is_reverse_indexed_but_stays_dormant() {
+ let mut builder = TeamFiltersBuilder::default();
+ // B: a resolvable single-leaf cohort.
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ // A references B: ref-bearing, so excluded but still reverse-indexed.
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(vec![cohort_ref_to(2)]))
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ assert_eq!(
+ frozen.cohorts_referencing(CohortId(2)),
+ [CohortId(1)].as_slice(),
+ );
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ );
+ assert!(
+ frozen
+ .by_lsk_to_composable_cohorts
+ .values()
+ .all(|cohorts| !cohorts.contains(&CohortId(1))),
+ "a ref-bearing cohort must not compose",
+ );
+ }
+
+ #[test]
+ fn cascade_on_pure_ref_cohort_is_composable_ref_but_indexes_no_lsk() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ // 1 is a pure cohort-ref to the single-leaf 2: no own state-keyed leaves.
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(vec![cohort_ref_to(2)]))
+ .unwrap();
+ let frozen = builder.freeze_with(UTC, true);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2ComposableRef,
+ "a resolvable, cycle-free ref cohort is promoted when the gate is on",
+ );
+ assert!(
+ frozen
+ .by_lsk_to_composable_cohorts
+ .values()
+ .all(|cohorts| !cohorts.contains(&CohortId(1))),
+ "a pure-ref cohort has no own leaves, so it joins no composable LSK",
+ );
+ assert_eq!(
+ frozen.cohorts_referencing(CohortId(2)),
+ [CohortId(1)].as_slice(),
+ "the reverse-reference index still points B's referrer back at A",
+ );
+ }
+
+ #[test]
+ fn cascade_on_ref_with_own_leaves_is_composable_ref_and_indexes_its_own_lsk() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![person_leaf(), cohort_ref_to(2)]),
+ )
+ .unwrap();
+ let frozen = builder.freeze_with(UTC, true);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2ComposableRef,
+ );
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ assert_eq!(
+ frozen.by_lsk_to_composable_cohorts[&per_lsk],
+ vec![CohortId(1)],
+ "the ref cohort's own person leaf re-triggers it on the event path",
+ );
+ }
+
+ #[test]
+ fn cascade_on_cycle_members_stay_excluded() {
+ let mut builder = TeamFiltersBuilder::default();
+ // 1 → 2 → 1 cycle.
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(vec![cohort_ref_to(2)]))
+ .unwrap();
+ builder
+ .add_cohort(CohortId(2), TeamId(7), &wrap(vec![cohort_ref_to(1)]))
+ .unwrap();
+ let frozen = builder.freeze_with(UTC, true);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected),
+ );
+ assert_eq!(
+ frozen.eligibility[&CohortId(2)],
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected),
+ );
+ }
+
+ #[test]
+ fn cascade_on_unresolved_ref_stays_excluded() {
+ let mut builder = TeamFiltersBuilder::default();
+ // 99 is never added to the catalog.
+ builder
+ .add_cohort(CohortId(1), TeamId(7), &wrap(vec![cohort_ref_to(99)]))
+ .unwrap();
+ let frozen = builder.freeze_with(UTC, true);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+ }
+
+ #[test]
+ fn cascade_on_negated_missing_ref_with_own_leaf_is_composable_ref_and_reads_true() {
+ use crate::stage2::evaluator::evaluate_tree;
+
+ let mut builder = TeamFiltersBuilder::default();
+ // 1 = AND(own person leaf, NOT in 99). 99 is never added: an absent negated ref reads
+ // `true`, so the missing target must not exclude 1 (oracle: `false ^ true = true`).
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![person_leaf(), cohort_ref_to_negated(99)]),
+ )
+ .unwrap();
+ let frozen = builder.freeze_with(UTC, true);
+
+ assert_eq!(
+ frozen.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2ComposableRef,
+ "a negated ref to a missing target never blocks composition",
+ );
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ assert_eq!(
+ frozen.by_lsk_to_composable_cohorts[&per_lsk],
+ vec![CohortId(1)],
+ "the cohort's own person leaf indexes it for re-evaluation on the event path",
+ );
+
+ // The composer fills a missing referent as `false`; the negated leaf flips it to `true`,
+ // so the cohort's membership tracks its own leaf alone.
+ let root = &frozen.cohorts[&CohortId(1)].root;
+ let ref_membership = HashMap::from([(CohortId(99), false)]);
+ let off = evaluate_tree(root, &HashMap::from([(per_lsk, false)]), &ref_membership);
+ let on = evaluate_tree(root, &HashMap::from([(per_lsk, true)]), &ref_membership);
+ assert!(
+ !off,
+ "own leaf off ⇒ non-member even though the negated ref reads true"
+ );
+ assert!(
+ on,
+ "own leaf flipping on ⇒ member, the Entered the cascade slice must emit"
+ );
+ }
+
+ #[test]
+ fn freeze_equals_freeze_with_false_on_a_ref_bearing_team() {
+ let build = || {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7)]),
+ )
+ .unwrap();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![person_leaf(), cohort_ref_to(2)]),
+ )
+ .unwrap();
+ builder
+ };
+ let via_freeze = build().freeze(UTC);
+ let via_freeze_with = build().freeze_with(UTC, false);
+
+ assert_eq!(via_freeze.eligibility, via_freeze_with.eligibility);
+ assert_eq!(
+ via_freeze.by_lsk_to_composable_cohorts,
+ via_freeze_with.by_lsk_to_composable_cohorts,
+ );
+ assert_eq!(
+ via_freeze.by_lsk_to_single_leaf_cohorts,
+ via_freeze_with.by_lsk_to_single_leaf_cohorts,
+ );
+ assert_eq!(
+ via_freeze.by_referenced_cohort,
+ via_freeze_with.by_referenced_cohort,
+ );
+ assert_eq!(
+ via_freeze.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ "gate off leaves the resolvable ref cohort excluded, not promoted",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/filters/tree.rs b/rust/cohort-stream-processor/src/filters/tree.rs
new file mode 100644
index 000000000000..da0d2c833b34
--- /dev/null
+++ b/rust/cohort-stream-processor/src/filters/tree.rs
@@ -0,0 +1,483 @@
+//! Filter-tree types and parser.
+
+use std::sync::Arc;
+
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use crate::filters::leaf_classifier::{classify_leaf, LeafClass, LeafDropReason};
+use crate::filters::{CohortId, FilterError, TeamId};
+use crate::stage1::key::LeafStateKey;
+use crate::stage1::state::StateVariant;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BehavioralValue {
+ PerformedEvent,
+ PerformedEventMultiple,
+ PerformedEventFirstTime,
+ PerformedEventSequence,
+ PerformedEventRegularly,
+ StoppedPerformingEvent,
+ RestartedPerformingEvent,
+}
+
+impl BehavioralValue {
+ /// The wire string stored in the cohort filter JSON.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::PerformedEvent => "performed_event",
+ Self::PerformedEventMultiple => "performed_event_multiple",
+ Self::PerformedEventFirstTime => "performed_event_first_time",
+ Self::PerformedEventSequence => "performed_event_sequence",
+ Self::PerformedEventRegularly => "performed_event_regularly",
+ Self::StoppedPerformingEvent => "stopped_performing_event",
+ Self::RestartedPerformingEvent => "restarted_performing_event",
+ }
+ }
+
+ pub fn contributes_bytecode(self) -> bool {
+ matches!(self, Self::PerformedEvent | Self::PerformedEventMultiple)
+ }
+
+ pub fn from_wire(s: &str) -> Option<Self> {
+ let value = match s {
+ "performed_event" => Self::PerformedEvent,
+ "performed_event_multiple" => Self::PerformedEventMultiple,
+ "performed_event_first_time" => Self::PerformedEventFirstTime,
+ "performed_event_sequence" => Self::PerformedEventSequence,
+ "performed_event_regularly" => Self::PerformedEventRegularly,
+ "stopped_performing_event" => Self::StoppedPerformingEvent,
+ "restarted_performing_event" => Self::RestartedPerformingEvent,
+ _ => return None,
+ };
+ Some(value)
+ }
+}
+
+/// A behavioral leaf, carrying every input to [`LeafStateKey::for_behavioral`].
+#[derive(Debug, Clone)]
+pub struct BehavioralLeafConfig {
+ pub condition_hash: [u8; 16],
+ pub value: BehavioralValue,
+ pub event_key: String,
+ pub time_value: Option<i32>,
+ pub operator_value: Option<i32>,
+ pub time_interval: Option<String>,
+ pub operator: Option<String>,
+ pub explicit_datetime: Option<String>,
+ pub explicit_datetime_to: Option<String>,
+ pub leaf_state_key: LeafStateKey,
+ pub state_variant: Option<StateVariant>,
+ pub bytecode: Arc<Vec<Value>>,
+ /// Excluded from [`LeafStateKey`] -- state is shared between positive and negated instances.
+ pub negated: bool,
+}
+
+impl BehavioralLeafConfig {
+ #[must_use]
+ pub fn with_state_key(mut self) -> Self {
+ self.leaf_state_key = LeafStateKey::for_behavioral(&self);
+ self
+ }
+
+ #[must_use]
+ pub fn with_state_variant(mut self, variant: StateVariant) -> Self {
+ self.state_variant = Some(variant);
+ self
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct PersonLeafConfig {
+ pub condition_hash: [u8; 16],
+ pub leaf_state_key: LeafStateKey,
+ pub bytecode: Arc<Vec<Value>>,
+ pub raw: Value,
+ pub negated: bool,
+}
+
+#[derive(Debug, Clone)]
+pub struct CohortRefLeafConfig {
+ pub referenced_cohort_id: CohortId,
+ pub negation: bool,
+}
+
+#[derive(Debug, Clone)]
+pub enum CohortLeaf {
+ PersonProperty(PersonLeafConfig),
+ Behavioral(BehavioralLeafConfig),
+ CohortRef(CohortRefLeafConfig),
+}
+
+impl CohortLeaf {
+ pub fn negated(&self) -> bool {
+ match self {
+ Self::PersonProperty(leaf) => leaf.negated,
+ Self::Behavioral(leaf) => leaf.negated,
+ Self::CohortRef(config) => config.negation,
+ }
+ }
+
+ /// The leaf's Stage 1 state key, or `None` for a cohort reference.
+ pub fn leaf_state_key(&self) -> Option<LeafStateKey> {
+ match self {
+ Self::PersonProperty(leaf) => Some(leaf.leaf_state_key),
+ Self::Behavioral(leaf) => Some(leaf.leaf_state_key),
+ Self::CohortRef(_) => None,
+ }
+ }
+
+ /// The leaf's `conditionHash`, or `None` for a cohort reference.
+ pub fn condition_hash(&self) -> Option<[u8; 16]> {
+ match self {
+ Self::PersonProperty(leaf) => Some(leaf.condition_hash),
+ Self::Behavioral(leaf) => Some(leaf.condition_hash),
+ Self::CohortRef(_) => None,
+ }
+ }
+
+ /// The leaf's inline bytecode, or `None` for a cohort reference.
+ pub fn bytecode(&self) -> Option<&Arc<Vec<Value>>> {
+ match self {
+ Self::PersonProperty(leaf) => Some(&leaf.bytecode),
+ Self::Behavioral(leaf) => Some(&leaf.bytecode),
+ Self::CohortRef(_) => None,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BoolOp {
+ And,
+ Or,
+}
+
+#[derive(Debug, Clone)]
+pub enum FilterNode {
+ Group {
+ op: BoolOp,
+ children: Vec<FilterNode>,
+ },
+ Leaf(CohortLeaf),
+}
+
+/// Retained for the Stage 2 re-walk after event dispatch.
+#[derive(Debug, Clone)]
+pub struct CohortTree {
+ pub cohort_id: CohortId,
+ pub team_id: TeamId,
+ pub root: FilterNode,
+}
+
+/// Receives the indexable side effects of a parse.
+pub trait LeafSink {
+ fn record_state_keyed(
+ &mut self,
+ cohort_id: CohortId,
+ condition_hash: [u8; 16],
+ leaf_state_key: LeafStateKey,
+ bytecode: &Arc<Vec<Value>>,
+ );
+
+ fn record_cohort_ref(&mut self, cohort_id: CohortId);
+
+ fn record_dropped(&mut self, cohort_id: CohortId, reason: LeafDropReason);
+}
+
+/// Parse a cohort's `filters` JSON into a [`CohortTree`], emitting index side effects through
+/// `sink`. Empty groups after drops are kept to preserve AND/OR identity.
+pub fn parse_cohort_tree(
+ cohort_id: CohortId,
+ team_id: TeamId,
+ filters: &Value,
+ sink: &mut dyn LeafSink,
+) -> Result<CohortTree, FilterError> {
+ let properties = filters
+ .get("properties")
+ .ok_or(FilterError::MissingProperties {
+ cohort_id: cohort_id.0,
+ })?;
+
+ let root = parse_node(cohort_id, properties, sink).unwrap_or_else(|| FilterNode::Group {
+ op: BoolOp::And,
+ children: Vec::new(),
+ });
+
+ Ok(CohortTree {
+ cohort_id,
+ team_id,
+ root,
+ })
+}
+
+fn parse_node(cohort_id: CohortId, node: &Value, sink: &mut dyn LeafSink) -> Option<FilterNode> {
+ if let Some(op) = group_op(node) {
+ if let Some(values) = node.get("values").and_then(Value::as_array) {
+ let children = values
+ .iter()
+ .filter_map(|child| parse_node(cohort_id, child, sink))
+ .collect();
+ return Some(FilterNode::Group { op, children });
+ }
+ }
+
+ match classify_leaf(node) {
+ LeafClass::Keep(leaf) => {
+ if let (Some(hash), Some(lsk), Some(bytecode)) = (
+ leaf.condition_hash(),
+ leaf.leaf_state_key(),
+ leaf.bytecode(),
+ ) {
+ sink.record_state_keyed(cohort_id, hash, lsk, bytecode);
+ }
+ Some(FilterNode::Leaf(leaf))
+ }
+ LeafClass::CohortRef(config) => {
+ sink.record_cohort_ref(cohort_id);
+ Some(FilterNode::Leaf(CohortLeaf::CohortRef(config)))
+ }
+ LeafClass::Drop(reason) => {
+ sink.record_dropped(cohort_id, reason);
+ None
+ }
+ }
+}
+
+fn group_op(node: &Value) -> Option<BoolOp> {
+ match node.get("type").and_then(Value::as_str) {
+ Some("AND") => Some(BoolOp::And),
+ Some("OR") => Some(BoolOp::Or),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ const HASH_A: [u8; 16] = *b"aaaaaaaaaaaaaaaa";
+ const HASH_B: [u8; 16] = *b"bbbbbbbbbbbbbbbb";
+
+ #[derive(Default)]
+ struct CollectingSink {
+ state_keyed: Vec<(CohortId, [u8; 16], LeafStateKey)>,
+ cohort_refs: Vec<CohortId>,
+ dropped: Vec<(CohortId, LeafDropReason)>,
+ }
+
+ impl LeafSink for CollectingSink {
+ fn record_state_keyed(
+ &mut self,
+ cohort_id: CohortId,
+ hash: [u8; 16],
+ lsk: LeafStateKey,
+ _bytecode: &Arc<Vec<Value>>,
+ ) {
+ self.state_keyed.push((cohort_id, hash, lsk));
+ }
+ fn record_cohort_ref(&mut self, cohort_id: CohortId) {
+ self.cohort_refs.push(cohort_id);
+ }
+ fn record_dropped(&mut self, cohort_id: CohortId, reason: LeafDropReason) {
+ self.dropped.push((cohort_id, reason));
+ }
+ }
+
+ fn person_leaf(hash: &[u8; 16]) -> Value {
+ json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "operator": "exact",
+ "conditionHash": String::from_utf8(hash.to_vec()).unwrap(),
+ "bytecode": ["_H", 1, 29],
+ })
+ }
+
+ fn parse(value: &Value, sink: &mut CollectingSink) -> CohortTree {
+ parse_cohort_tree(CohortId(1), TeamId(7), value, sink).expect("parse")
+ }
+
+ #[test]
+ fn behavioral_value_str_and_wire_round_trip() {
+ for value in [
+ BehavioralValue::PerformedEvent,
+ BehavioralValue::PerformedEventMultiple,
+ BehavioralValue::PerformedEventFirstTime,
+ BehavioralValue::PerformedEventSequence,
+ BehavioralValue::PerformedEventRegularly,
+ BehavioralValue::StoppedPerformingEvent,
+ BehavioralValue::RestartedPerformingEvent,
+ ] {
+ assert_eq!(BehavioralValue::from_wire(value.as_str()), Some(value));
+ }
+ assert_eq!(BehavioralValue::from_wire("not_a_real_value"), None);
+ }
+
+ #[test]
+ fn only_two_values_contribute_bytecode() {
+ assert!(BehavioralValue::PerformedEvent.contributes_bytecode());
+ assert!(BehavioralValue::PerformedEventMultiple.contributes_bytecode());
+ assert!(!BehavioralValue::PerformedEventSequence.contributes_bytecode());
+ assert!(!BehavioralValue::StoppedPerformingEvent.contributes_bytecode());
+ }
+
+ #[test]
+ fn missing_properties_is_an_error() {
+ let mut sink = CollectingSink::default();
+ let err = parse_cohort_tree(CohortId(3), TeamId(7), &json!({}), &mut sink).unwrap_err();
+ assert!(matches!(
+ err,
+ FilterError::MissingProperties { cohort_id: 3 }
+ ));
+ }
+
+ #[test]
+ fn or_group_of_two_person_leaves_is_not_sibling_merged() {
+ let filters = json!({
+ "properties": {
+ "type": "OR",
+ "values": [person_leaf(&HASH_A), person_leaf(&HASH_B)],
+ }
+ });
+ let mut sink = CollectingSink::default();
+ let tree = parse(&filters, &mut sink);
+
+ match tree.root {
+ FilterNode::Group { op, children } => {
+ assert_eq!(op, BoolOp::Or);
+ assert_eq!(children.len(), 2, "siblings must not be merged");
+ }
+ FilterNode::Leaf(_) => panic!("root should be a group"),
+ }
+ assert_eq!(sink.state_keyed.len(), 2);
+ }
+
+ #[test]
+ fn negation_bit_is_captured_at_parse_time() {
+ let mut negated = person_leaf(&HASH_B);
+ negated["negation"] = json!(true);
+ let filters = json!({
+ "properties": { "type": "AND", "values": [person_leaf(&HASH_A), negated] },
+ });
+ let mut sink = CollectingSink::default();
+ let tree = parse(&filters, &mut sink);
+
+ let FilterNode::Group { children, .. } = &tree.root else {
+ panic!("root should be a group");
+ };
+ let bits: Vec<bool> = children
+ .iter()
+ .map(|child| match child {
+ FilterNode::Leaf(leaf) => leaf.negated(),
+ _ => panic!("expected a leaf"),
+ })
+ .collect();
+ assert_eq!(bits, vec![false, true]);
+ }
+
+ #[test]
+ fn not_in_operator_is_not_a_parse_time_negation() {
+ let mut not_in = person_leaf(&HASH_A);
+ not_in["operator"] = json!("not_in");
+ let filters = json!({ "properties": { "type": "AND", "values": [not_in] } });
+ let mut sink = CollectingSink::default();
+ let tree = parse(&filters, &mut sink);
+
+ let FilterNode::Group { children, .. } = &tree.root else {
+ panic!("root should be a group");
+ };
+ assert_eq!(children.len(), 1);
+ match &children[0] {
+ FilterNode::Leaf(leaf) => assert!(
+ !leaf.negated(),
+ "not_in alone must not set the negation bit",
+ ),
+ _ => panic!("expected a leaf"),
+ }
+ }
+
+ #[test]
+ fn cohort_ref_is_kept_in_tree_but_not_indexed() {
+ let filters = json!({
+ "properties": {
+ "type": "AND",
+ "values": [{ "type": "cohort", "value": 42, "negation": true }],
+ }
+ });
+ let mut sink = CollectingSink::default();
+ let tree = parse(&filters, &mut sink);
+
+ let FilterNode::Group { children, .. } = tree.root else {
+ panic!("root should be a group");
+ };
+ assert_eq!(children.len(), 1);
+ match &children[0] {
+ FilterNode::Leaf(CohortLeaf::CohortRef(config)) => {
+ assert_eq!(config.referenced_cohort_id, CohortId(42));
+ assert!(config.negation);
+ }
+ other => panic!("expected a cohort ref, got {other:?}"),
+ }
+ assert!(
+ sink.state_keyed.is_empty(),
+ "cohort refs are not state-keyed"
+ );
+ assert_eq!(
+ sink.cohort_refs,
+ vec![CohortId(1)],
+ "the cohort ref is recorded against its owning cohort",
+ );
+ }
+
+ #[test]
+ fn dropped_leaf_produces_no_node_but_keeps_the_group() {
+ let filters = json!({
+ "properties": {
+ "type": "AND",
+ "values": [{ "type": "behavioral", "key": "$pageview", "value": "performed_event" }],
+ }
+ });
+ let mut sink = CollectingSink::default();
+ let tree = parse(&filters, &mut sink);
+
+ let FilterNode::Group { children, .. } = tree.root else {
+ panic!("root should be a group");
+ };
+ assert!(
+ children.is_empty(),
+ "dropped leaf leaves an empty (but kept) group"
+ );
+ assert_eq!(
+ sink.dropped,
+ vec![(CohortId(1), LeafDropReason::MissingConditionHash)],
+ );
+ }
+
+ #[test]
+ fn nested_groups_recurse() {
+ let filters = json!({
+ "properties": {
+ "type": "AND",
+ "values": [{
+ "type": "OR",
+ "values": [person_leaf(&HASH_A)],
+ }],
+ }
+ });
+ let mut sink = CollectingSink::default();
+ let tree = parse(&filters, &mut sink);
+
+ let FilterNode::Group { op, children } = tree.root else {
+ panic!("root should be a group");
+ };
+ assert_eq!(op, BoolOp::And);
+ assert!(matches!(
+ children.as_slice(),
+ [FilterNode::Group { op: BoolOp::Or, .. }]
+ ));
+ assert_eq!(sink.state_keyed.len(), 1);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/hogvm/executor.rs b/rust/cohort-stream-processor/src/hogvm/executor.rs
new file mode 100644
index 000000000000..ddf65b5c707e
--- /dev/null
+++ b/rust/cohort-stream-processor/src/hogvm/executor.rs
@@ -0,0 +1,244 @@
+//! Run compiled cohort-filter bytecode through `hogvm::sync_execute`, coercing the result to the
+//! boolean Stage 1 needs (matching the Node consumer's `execResult?.result ?? false`).
+
+use hogvm::{sync_execute, ExecutionContext, Program, VmError};
+use metrics::counter;
+use serde_json::Value;
+use tracing::debug;
+
+use crate::observability::metrics::{STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION};
+
+/// HogVM `RETURN` opcode. See [`evaluate_detailed`] for why it is appended to every program.
+const OP_RETURN: i64 = 38;
+
+/// The classified outcome of evaluating one program; [`evaluate`] collapses this to a `bool` but
+/// the variants preserve *why* a non-match happened.
+#[derive(Debug)]
+pub enum EvalOutcome {
+ Matched(bool),
+ /// A `CALL_GLOBAL`/symbol with no registered Rust native; carries the name for the metric label.
+ UnknownFunction(String),
+ VmError(VmError),
+}
+
+/// Evaluate `bytecode` against `globals`, returning the detailed [`EvalOutcome`].
+///
+/// Cohort bytecode ends with its root comparison op and no `RETURN`. The Rust VM treats running
+/// off the end as `EndOfProgram`; appending a `RETURN` recovers the Python/Node semantic. A
+/// program already ending in `RETURN` finishes first, so the append is safe for both shapes.
+pub fn evaluate_detailed(bytecode: &[Value], globals: Value) -> EvalOutcome {
+ let mut with_return = Vec::with_capacity(bytecode.len() + 1);
+ with_return.extend_from_slice(bytecode);
+ with_return.push(Value::from(OP_RETURN));
+
+ // PERF: `with_defaults` rebuilds the full STL (~26 closures + 2 HashMaps + the hog module
+ // symbol table) on every call — once per conditionHash per event. Reuse is blocked by the
+ // shared `hogvm` API: `NativeFunction` is `Box<dyn Fn>` (not `Clone`), `ExecutionContext`
+ // owns its tables, and there is no program setter, so a thread_local context can't swap
+ // programs in place without a shared-crate change. `with_globals` also takes ownership, so
+ // the full globals JSON is cloned per condition. Flamegraph before optimizing.
+ let program = match Program::new(with_return) {
+ Ok(program) => program,
+ Err(error) => return classify_failure(error),
+ };
+ // Coercing comparisons (cross-type ordering + epoch temporal ordering/equality) match the
+ // Python/TS/ClickHouse reference. Opt in here only — other consumers (e.g. cymbal) keep
+ // strict comparisons.
+ let context = ExecutionContext::with_defaults(program)
+ .with_globals(globals)
+ .with_coercing_comparisons();
+
+ match sync_execute(&context, false) {
+ Ok(result) => EvalOutcome::Matched(result.as_bool().unwrap_or(false)),
+ Err(failure) => classify_failure(failure.error),
+ }
+}
+
+/// Hot-path wrapper: coerces failures and non-bool results to `false`, emitting a per-class metric
+/// so a silently-failing cohort stays observable.
+pub fn evaluate(bytecode: &[Value], globals: Value) -> bool {
+ match evaluate_detailed(bytecode, globals) {
+ EvalOutcome::Matched(matched) => matched,
+ EvalOutcome::UnknownFunction(name) => {
+ // `name` is bytecode-derived from user cohort filters; keep it out of the metric label
+ // (bounded counter) and surface the specific function only in a debug log.
+ counter!(STAGE1_HOGVM_UNKNOWN_FUNCTION).increment(1);
+ debug!(function = %name, "cohort bytecode called a function with no registered Rust native");
+ false
+ }
+ EvalOutcome::VmError(_) => {
+ counter!(STAGE1_HOGVM_ERROR).increment(1);
+ false
+ }
+ }
+}
+
+/// `UnknownFunction` and `UnknownSymbol` collapse to the same metric. The catch-all arm is
+/// mandatory because `VmError` is `#[non_exhaustive]`.
+fn classify_failure(error: VmError) -> EvalOutcome {
+ match error {
+ VmError::UnknownFunction(name) | VmError::UnknownSymbol(name) => {
+ EvalOutcome::UnknownFunction(name)
+ }
+ other => EvalOutcome::VmError(other),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ const OP_GET_GLOBAL: i64 = 1;
+ const OP_CALL_GLOBAL: i64 = 2;
+ const OP_EQ: i64 = 11;
+ const OP_GT: i64 = 13;
+ const OP_LT: i64 = 15;
+ const OP_TRUE: i64 = 29;
+ const OP_FALSE: i64 = 30;
+ const OP_INTEGER: i64 = 33;
+ const OP_STRING: i64 = 32;
+
+ fn header() -> Vec<Value> {
+ vec![json!("_H"), json!(1)]
+ }
+
+ #[test]
+ fn true_literal_coerces_to_true() {
+ let bc = [header(), vec![json!(OP_TRUE)]].concat();
+ assert!(matches!(
+ evaluate_detailed(&bc, json!({})),
+ EvalOutcome::Matched(true)
+ ));
+ }
+
+ #[test]
+ fn false_literal_coerces_to_false() {
+ let bc = [header(), vec![json!(OP_FALSE)]].concat();
+ assert!(matches!(
+ evaluate_detailed(&bc, json!({})),
+ EvalOutcome::Matched(false)
+ ));
+ }
+
+ #[test]
+ fn non_boolean_result_coerces_to_false() {
+ let bc = [header(), vec![json!(OP_INTEGER), json!(42)]].concat();
+ assert!(matches!(
+ evaluate_detailed(&bc, json!({})),
+ EvalOutcome::Matched(false)
+ ));
+ assert!(!evaluate(&bc, json!({})));
+ }
+
+ #[test]
+ fn compiled_style_bytecode_without_trailing_return_still_evaluates() {
+ // Guard the appended-RETURN bridge: cohort bytecode ends without RETURN, which the Rust VM
+ // would reject with EndOfProgram; evaluate_detailed must append one.
+ let bc = [
+ header(),
+ vec![
+ json!(OP_STRING),
+ json!("$pageview"),
+ json!(OP_STRING),
+ json!("event"),
+ json!(OP_GET_GLOBAL),
+ json!(1),
+ json!(OP_EQ),
+ ],
+ ]
+ .concat();
+ assert!(evaluate(&bc, json!({ "event": "$pageview" })));
+ assert!(!evaluate(&bc, json!({ "event": "$autocapture" })));
+ }
+
+ #[test]
+ fn unknown_call_global_is_classified_as_unknown_function() {
+ let bc = [
+ header(),
+ vec![
+ json!(OP_CALL_GLOBAL),
+ json!("definitelyNotANative"),
+ json!(0),
+ ],
+ ]
+ .concat();
+ match evaluate_detailed(&bc, json!({})) {
+ EvalOutcome::UnknownFunction(name) => assert_eq!(name, "definitelyNotANative"),
+ other => panic!("expected UnknownFunction, got {other:?}"),
+ }
+ assert!(!evaluate(&bc, json!({})));
+ }
+
+ #[test]
+ fn malformed_program_is_a_vm_error() {
+ assert!(matches!(
+ evaluate_detailed(&[], json!({})),
+ EvalOutcome::VmError(_)
+ ));
+ assert!(!evaluate(&[], json!({})));
+ }
+
+ /// Build opcodes to read `person.properties.<key>`. GET_GLOBAL consumes path segments in
+ /// reverse push order.
+ fn push_person_property(key: &str) -> Vec<Value> {
+ vec![
+ json!(OP_STRING),
+ json!(key),
+ json!(OP_STRING),
+ json!("properties"),
+ json!(OP_STRING),
+ json!("person"),
+ json!(OP_GET_GLOBAL),
+ json!(3),
+ ]
+ }
+
+ #[test]
+ fn is_date_before_person_cohort_enters_and_leaves() {
+ // `Lt(toDateTime(toString(person.properties.signup_date)), toDateTime("2026-01-01 00:00:00"))`
+ // — compiler emits `right, left, op`.
+ let mut left = push_person_property("signup_date");
+ left.extend_from_slice(&[
+ json!(OP_CALL_GLOBAL),
+ json!("toString"),
+ json!(1),
+ json!(OP_CALL_GLOBAL),
+ json!("toDateTime"),
+ json!(1),
+ ]);
+ let right = vec![
+ json!(OP_STRING),
+ json!("2026-01-01 00:00:00"),
+ json!(OP_CALL_GLOBAL),
+ json!("toDateTime"),
+ json!(1),
+ ];
+ let mut bc = vec![json!("_H"), json!(1)];
+ bc.extend_from_slice(&right);
+ bc.extend_from_slice(&left);
+ bc.push(json!(OP_LT));
+
+ let globals =
+ |signup: Value| json!({ "person": { "properties": { "signup_date": signup } } });
+ assert!(evaluate(&bc, globals(json!("2024-09-09 08:30:00"))));
+ assert!(!evaluate(&bc, globals(json!("2027-09-09 08:30:00"))));
+ assert!(!evaluate(&bc, json!({ "person": { "properties": {} } })));
+ }
+
+ #[test]
+ fn numeric_gt_person_cohort_coerces_the_string_threshold() {
+ // Compiler emits the threshold as a string: `Gt(person.properties.bc_num, "10")`.
+ // Coercing comparisons promote both sides to numeric, matching ClickHouse/TS behaviour.
+ let mut bc = vec![json!("_H"), json!(1)];
+ bc.extend_from_slice(&[json!(OP_STRING), json!("10")]);
+ bc.extend_from_slice(&push_person_property("bc_num"));
+ bc.push(json!(OP_GT));
+
+ let globals = |num: Value| json!({ "person": { "properties": { "bc_num": num } } });
+ assert!(evaluate(&bc, globals(json!(20))));
+ assert!(!evaluate(&bc, globals(json!(5))));
+ assert!(evaluate(&bc, globals(json!("20"))));
+ assert!(!evaluate(&bc, globals(json!("05"))));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/hogvm/globals.rs b/rust/cohort-stream-processor/src/hogvm/globals.rs
new file mode 100644
index 000000000000..d4fa2af118df
--- /dev/null
+++ b/rust/cohort-stream-processor/src/hogvm/globals.rs
@@ -0,0 +1,308 @@
+//! Build HogVM globals dicts from [`CohortStreamEvent`]s for cohort bytecode evaluation.
+
+use chrono::{DateTime, NaiveDateTime};
+use metrics::counter;
+use serde_json::{json, Value};
+
+use crate::consumers::events::CohortStreamEvent;
+use crate::observability::metrics::STAGE1_GLOBALS_PARSE_ERROR;
+
+/// A malformed `properties`/`person_properties` JSON payload.
+#[derive(Debug, thiserror::Error)]
+#[error("failed to parse event `{field}` as JSON: {source}")]
+pub struct GlobalsError {
+ pub field: &'static str,
+ #[source]
+ pub source: serde_json::Error,
+}
+
+pub fn build_behavioral_globals(event: &CohortStreamEvent) -> Result<Value, GlobalsError> {
+ let properties = parse_optional_json(event.properties.as_deref(), "properties")?;
+ let person_properties =
+ parse_optional_json(event.person_properties.as_deref(), "person_properties")?;
+
+ let elements_chain = elements_chain(event, &properties);
+ let timestamp = normalize_timestamp(&event.timestamp);
+
+ let person = json!({ "id": event.person_id.as_str(), "properties": person_properties });
+ let pdi = json!({
+ "distinct_id": event.distinct_id.as_str(),
+ "person_id": event.person_id.as_str(),
+ "person": person.clone(),
+ });
+
+ Ok(json!({
+ "event": event.event.as_str(),
+ "uuid": event.uuid.as_str(),
+ "elements_chain": elements_chain,
+ "elements_chain_href": "",
+ "elements_chain_texts": [],
+ "elements_chain_ids": [],
+ "elements_chain_elements": [],
+ "timestamp": timestamp,
+ "properties": properties,
+ "person": person,
+ "pdi": pdi,
+ "distinct_id": event.distinct_id.as_str(),
+ "$group_0": null,
+ "$group_1": null,
+ "$group_2": null,
+ "$group_3": null,
+ "$group_4": null,
+ "group_0": { "properties": {} },
+ "group_1": { "properties": {} },
+ "group_2": { "properties": {} },
+ "group_3": { "properties": {} },
+ "group_4": { "properties": {} },
+ "variables": {},
+ }))
+}
+
+pub fn build_person_property_globals(event: &CohortStreamEvent) -> Result<Value, GlobalsError> {
+ let person_properties =
+ parse_optional_json(event.person_properties.as_deref(), "person_properties")?;
+
+ Ok(json!({
+ "person": { "id": event.person_id.as_str(), "properties": person_properties },
+ "project": { "id": event.team_id },
+ }))
+}
+
+/// Parse a raw JSON payload, treating `None` or empty string as `{}`.
+fn parse_optional_json(raw: Option<&str>, field: &'static str) -> Result<Value, GlobalsError> {
+ let Some(raw) = raw.filter(|s| !s.is_empty()) else {
+ return Ok(json!({}));
+ };
+ serde_json::from_str(raw).map_err(|source| {
+ counter!(STAGE1_GLOBALS_PARSE_ERROR, "field" => field).increment(1);
+ GlobalsError { field, source }
+ })
+}
+
+/// `event.elements_chain ?? properties['$elements_chain'] ?? null`
+fn elements_chain(event: &CohortStreamEvent, properties: &Value) -> Value {
+ match &event.elements_chain {
+ Some(chain) => Value::String(chain.clone()),
+ None => properties
+ .get("$elements_chain")
+ .cloned()
+ .unwrap_or(Value::Null),
+ }
+}
+
+/// Normalize a ClickHouse `"YYYY-MM-DD HH:MM:SS.ffffff"` timestamp to ISO 8601. RFC 3339 input
+/// passes through unchanged.
+fn normalize_timestamp(raw: &str) -> String {
+ if DateTime::parse_from_rfc3339(raw).is_ok() {
+ return raw.to_string();
+ }
+ NaiveDateTime::parse_from_str(raw, "%Y-%m-%d %H:%M:%S%.f")
+ .map(|naive| naive.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string())
+ .unwrap_or_else(|_| raw.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn event() -> CohortStreamEvent {
+ CohortStreamEvent {
+ team_id: 42,
+ person_id: "p-123".to_string(),
+ distinct_id: "d-1".to_string(),
+ uuid: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ event: "$pageview".to_string(),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ properties: Some(r#"{"$browser":"Chrome"}"#.to_string()),
+ person_properties: Some(r#"{"email":"[email protected]"}"#.to_string()),
+ elements_chain: Some("a:href=\"/x\"".to_string()),
+ source_offset: 0,
+ source_partition: 0,
+ redirected_from: None,
+ redirect_hops: 0,
+ }
+ }
+
+ #[test]
+ fn behavioral_globals_emit_the_full_node_key_set() {
+ let globals = build_behavioral_globals(&event()).unwrap();
+ let obj = globals.as_object().unwrap();
+ for key in [
+ "event",
+ "uuid",
+ "elements_chain",
+ "elements_chain_href",
+ "elements_chain_texts",
+ "elements_chain_ids",
+ "elements_chain_elements",
+ "timestamp",
+ "properties",
+ "person",
+ "pdi",
+ "distinct_id",
+ "$group_0",
+ "$group_1",
+ "$group_2",
+ "$group_3",
+ "$group_4",
+ "group_0",
+ "group_1",
+ "group_2",
+ "group_3",
+ "group_4",
+ "variables",
+ ] {
+ assert!(obj.contains_key(key), "behavioral globals missing `{key}`");
+ }
+ }
+
+ #[test]
+ fn behavioral_globals_shape_matches_node() {
+ let globals = build_behavioral_globals(&event()).unwrap();
+ assert_eq!(globals["event"], json!("$pageview"));
+ assert_eq!(
+ globals["uuid"],
+ json!("01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee")
+ );
+ assert_eq!(globals["distinct_id"], json!("d-1"));
+ assert_eq!(globals["properties"], json!({ "$browser": "Chrome" }));
+ assert_eq!(globals["person"]["id"], json!("p-123"));
+ assert_eq!(
+ globals["person"]["properties"],
+ json!({ "email": "[email protected]" })
+ );
+ assert_eq!(globals["pdi"]["distinct_id"], json!("d-1"));
+ assert_eq!(globals["pdi"]["person_id"], json!("p-123"));
+ assert_eq!(globals["pdi"]["person"]["id"], json!("p-123"));
+ assert_eq!(globals["elements_chain"], json!("a:href=\"/x\""));
+ assert_eq!(globals["$group_0"], Value::Null);
+ assert_eq!(globals["group_0"], json!({ "properties": {} }));
+ assert_eq!(globals["elements_chain_texts"], json!([]));
+ assert_eq!(globals["variables"], json!({}));
+ }
+
+ #[test]
+ fn person_globals_are_the_small_strict_shape() {
+ let globals = build_person_property_globals(&event()).unwrap();
+ assert_eq!(
+ globals,
+ json!({
+ "person": { "id": "p-123", "properties": { "email": "[email protected]" } },
+ "project": { "id": 42 },
+ })
+ );
+ }
+
+ #[test]
+ fn null_properties_default_to_empty_object() {
+ let mut e = event();
+ e.properties = None;
+ e.person_properties = None;
+ let globals = build_behavioral_globals(&e).unwrap();
+ assert_eq!(globals["properties"], json!({}));
+ assert_eq!(globals["person"]["properties"], json!({}));
+
+ let person_globals = build_person_property_globals(&e).unwrap();
+ assert_eq!(person_globals["person"]["properties"], json!({}));
+ }
+
+ #[test]
+ fn empty_string_payload_parses_to_empty_object() {
+ assert_eq!(
+ parse_optional_json(Some(""), "properties").unwrap(),
+ json!({})
+ );
+ assert_eq!(
+ parse_optional_json(Some(""), "person_properties").unwrap(),
+ json!({})
+ );
+ }
+
+ #[test]
+ fn behavioral_globals_treat_empty_string_payloads_as_empty_objects() {
+ let mut e = event();
+ e.properties = Some(String::new());
+ e.person_properties = Some(String::new());
+ let globals = build_behavioral_globals(&e).unwrap();
+ assert_eq!(globals["properties"], json!({}));
+ assert_eq!(globals["person"]["properties"], json!({}));
+ assert_eq!(globals["pdi"]["person"]["properties"], json!({}));
+ }
+
+ #[test]
+ fn person_globals_treat_empty_string_person_properties_as_empty_object() {
+ let mut e = event();
+ e.person_properties = Some(String::new());
+ let globals = build_person_property_globals(&e).unwrap();
+ assert_eq!(globals["person"]["properties"], json!({}));
+ }
+
+ #[test]
+ fn malformed_properties_is_an_error() {
+ let mut e = event();
+ e.properties = Some("{not json".to_string());
+ let err = build_behavioral_globals(&e).unwrap_err();
+ assert_eq!(err.field, "properties");
+ }
+
+ #[test]
+ fn malformed_person_properties_is_an_error_in_both_builders() {
+ let mut e = event();
+ e.person_properties = Some("nope".to_string());
+ assert_eq!(
+ build_behavioral_globals(&e).unwrap_err().field,
+ "person_properties"
+ );
+ assert_eq!(
+ build_person_property_globals(&e).unwrap_err().field,
+ "person_properties"
+ );
+ }
+
+ #[test]
+ fn non_object_properties_pass_through_as_is() {
+ let mut e = event();
+ e.properties = Some("[1, 2, 3]".to_string());
+ let globals = build_behavioral_globals(&e).unwrap();
+ assert_eq!(globals["properties"], json!([1, 2, 3]));
+ }
+
+ #[test]
+ fn elements_chain_falls_back_to_properties() {
+ let mut e = event();
+ e.elements_chain = None;
+ e.properties = Some(r#"{"$elements_chain":"from-props"}"#.to_string());
+ let globals = build_behavioral_globals(&e).unwrap();
+ assert_eq!(globals["elements_chain"], json!("from-props"));
+
+ e.properties = Some("{}".to_string());
+ let globals = build_behavioral_globals(&e).unwrap();
+ assert_eq!(globals["elements_chain"], Value::Null);
+ }
+
+ #[test]
+ fn clickhouse_timestamp_normalizes_to_iso_millis_z() {
+ assert_eq!(
+ normalize_timestamp("2026-05-26 12:34:56.789000"),
+ "2026-05-26T12:34:56.789Z"
+ );
+ assert_eq!(
+ normalize_timestamp("2026-01-01 00:00:00.000123"),
+ "2026-01-01T00:00:00.000Z"
+ );
+ }
+
+ #[test]
+ fn already_iso_timestamp_passes_through_unchanged() {
+ assert_eq!(
+ normalize_timestamp("2026-05-26T12:34:56.789Z"),
+ "2026-05-26T12:34:56.789Z"
+ );
+ }
+
+ #[test]
+ fn timestamp_in_built_globals_is_normalized() {
+ let globals = build_behavioral_globals(&event()).unwrap();
+ assert_eq!(globals["timestamp"], json!("2026-05-26T12:34:56.789Z"));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/hogvm/mod.rs b/rust/cohort-stream-processor/src/hogvm/mod.rs
new file mode 100644
index 000000000000..4bfaede60102
--- /dev/null
+++ b/rust/cohort-stream-processor/src/hogvm/mod.rs
@@ -0,0 +1,8 @@
+//! Evaluate compiled cohort-filter bytecode against an event, coercing non-bool results to
+//! `false` to match the Node consumer.
+
+mod executor;
+mod globals;
+
+pub use executor::{evaluate, evaluate_detailed, EvalOutcome};
+pub use globals::{build_behavioral_globals, build_person_property_globals, GlobalsError};
diff --git a/rust/cohort-stream-processor/src/kill_switch/mod.rs b/rust/cohort-stream-processor/src/kill_switch/mod.rs
new file mode 100644
index 000000000000..1c63ed645935
--- /dev/null
+++ b/rust/cohort-stream-processor/src/kill_switch/mod.rs
@@ -0,0 +1 @@
+//! Per-cohort kill switch: disable specific cohorts without a redeploy.
diff --git a/rust/cohort-stream-processor/src/lib.rs b/rust/cohort-stream-processor/src/lib.rs
new file mode 100644
index 000000000000..e036a24293ad
--- /dev/null
+++ b/rust/cohort-stream-processor/src/lib.rs
@@ -0,0 +1,22 @@
+//! `cohort-stream-processor`: the stateful core of the Behavioral Cohorts stream pipeline.
+//!
+//! It consumes re-keyed events from `cohort_stream_events`, maintains per-`(team_id,
+//! leaf_state_key, person_id)` state in RocksDB, evaluates cohort membership incrementally, and
+//! emits membership transitions. A periodic sweep handles time-driven eviction.
+
+pub mod cascade;
+pub mod config;
+pub mod consumers;
+pub mod filters;
+pub mod hogvm;
+pub mod kill_switch;
+pub mod merge;
+pub mod observability;
+pub mod partitions;
+pub mod producer;
+pub mod recovery;
+pub mod stage1;
+pub mod stage2;
+pub mod store;
+pub mod sweep;
+pub mod workers;
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
new file mode 100644
index 000000000000..63505e07d6b0
--- /dev/null
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -0,0 +1,771 @@
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+use common_database::get_pool_with_config;
+use envconfig::Envconfig;
+use lifecycle::{ComponentOptions, Handle, Manager};
+use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, StreamConsumer};
+use rdkafka::{Offset, TopicPartitionList};
+use tokio::net::TcpListener;
+use tokio::sync::mpsc;
+use tracing::{info, warn};
+use tracing_subscriber::layer::SubscriberExt;
+use tracing_subscriber::util::SubscriberInitExt;
+use tracing_subscriber::{fmt, EnvFilter, Layer};
+
+use cohort_stream_processor::config::Config;
+use cohort_stream_processor::consumers::{
+ CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, FollowerRoute,
+ MergeRoute, TransferRoute,
+};
+use cohort_stream_processor::filters::{run_refresh_loop, CatalogHandle};
+use cohort_stream_processor::merge::gc::MergeGcSweeper;
+use cohort_stream_processor::merge::redrive::RedriveSweeper;
+use cohort_stream_processor::observability;
+use cohort_stream_processor::partitions::{
+ run_rebalance_worker, CohortConsumerContext, Follower, FollowerSet, OffsetTracker,
+ PartitionRouter,
+};
+use cohort_stream_processor::producer::{
+ CascadeSink, KafkaCascadeSink, KafkaMembershipSink, KafkaStreamEventSink, KafkaTransferSink,
+ MembershipSink, NoopCascadeSink, StreamEventSink, TransferSink,
+};
+use cohort_stream_processor::store::durability::{
+ run_boot_restore, upload_cadence, CheckpointExporter, CheckpointSweeper, OffsetManifest,
+ S3Uploader, TrackedTopic, CHECKPOINT_LOOP_NAME,
+};
+use cohort_stream_processor::store::CohortStore;
+use cohort_stream_processor::sweep::{run_sweep_loop, DispatchSweeper};
+use cohort_stream_processor::workers::MergeWorkerDeps;
+
+common_alloc::used!();
+
+const SERVICE_NAME: &str = "cohort-stream-processor";
+
+fn main() -> Result<()> {
+ let config = Config::init_from_env()
+ .context("Failed to load configuration from environment variables")?;
+
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .context("Failed to build tokio runtime")?;
+
+ runtime.block_on(async_main(config))
+}
+
+async fn async_main(config: Config) -> Result<()> {
+ init_tracing();
+ log_startup(&config);
+
+ config.validate_durability_startup()?;
+
+ let mut manager = Manager::builder(SERVICE_NAME)
+ .with_global_shutdown_timeout(Duration::from_secs(90))
+ .build();
+
+ let metrics_handle =
+ manager.register("metrics", ComponentOptions::new().is_observability(true));
+ let catalog_handle_lifecycle = manager.register(
+ "filter-catalog",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),
+ );
+ let consumer_handle = manager.register(
+ "consumer",
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(30))
+ .with_liveness_deadline(Duration::from_secs(60))
+ .with_stall_threshold(3),
+ );
+ let merge_follower_handle = manager.register(
+ "merge-follower",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),
+ );
+ let transfer_follower_handle = manager.register(
+ "transfer-follower",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),
+ );
+ // Registered only when the gate is on — a dormant deploy must not wait on a component that never
+ // starts.
+ let cascade_follower_handle = config.cohort_cascade_enabled.then(|| {
+ manager.register(
+ "cascade-follower",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),
+ )
+ });
+
+ let readiness = manager.readiness_handler();
+ let liveness = manager.liveness_handler();
+
+ let recorder_handle = if config.export_prometheus {
+ Some(observability::metrics::install_recorder())
+ } else {
+ None
+ };
+
+ let pool = get_pool_with_config(&config.database_url, config.pool_config())
+ .context("creating posthog_cohort database pool")?;
+
+ let catalog = Arc::new(CatalogHandle::with_allowlist(
+ config.team_allowlist.clone(),
+ config.cohort_cascade_enabled,
+ ));
+ match catalog.refresh(&pool).await {
+ Ok(stats) => info!(
+ teams = stats.teams,
+ unique_conditions = stats.unique_conditions,
+ "initial filter catalog loaded",
+ ),
+ Err(err) => warn!(
+ error = %err,
+ "initial filter catalog load failed; catalog is empty until the refresh task succeeds",
+ ),
+ }
+
+ // Decide where the live store comes from and, on the disaster paths, materialize it at
+ // `store_path` before the store is opened and before the checkpoint sweep loop is spawned (so no
+ // TOCTOU with the sweeper's prune). A restored DB dropped at `store_path` makes the
+ // `effective_wipe_on_start` logic below see `db_dir_exists == true` and keep it.
+ let restore = run_boot_restore(&config, &PathBuf::from(&config.store_path)).await;
+ info!(restore_source = ?restore.source, "boot restore complete");
+
+ let store_config = config.store_config();
+ info!(
+ durable_restore_enabled = config.durable_restore_enabled,
+ wipe_store_on_start = config.wipe_store_on_start,
+ effective_wipe = store_config.wipe_on_start,
+ store_path = %config.store_path,
+ mode = if store_config.wipe_on_start { "wipe+replay" } else { "reopen-live" },
+ "opening RocksDB state store",
+ );
+ let store = CohortStore::open(&store_config).context("opening RocksDB state store")?;
+ let router = PartitionRouter::new(config.partition_channel_buffer);
+ let offset_tracker = Arc::new(OffsetTracker::new());
+
+ let kafka_config = config.build_kafka_config();
+ let sink: Arc<dyn MembershipSink> = Arc::new(
+ KafkaMembershipSink::new(
+ &kafka_config,
+ config.cohort_membership_changed_topic.clone(),
+ )
+ .await
+ .context("creating shadow producer")?,
+ );
+
+ // Only the transfer sink gets the shorter `message.timeout.ms`: its produce runs inline on a
+ // partition worker under a bounded retry loop, so a long per-attempt timeout would multiply into
+ // a worker hold past the 30 s graceful-shutdown window. The membership and re-key sinks keep the
+ // shared 20 s — membership drops on fail (at-most-once) and the re-key produce rides the
+ // events-path offset gate (held-then-redelivered), so neither blocks a worker for the full timeout.
+ let transfer_kafka_config = config.build_transfer_kafka_config();
+ let transfer_sink: Arc<dyn TransferSink> = Arc::new(
+ KafkaTransferSink::new(
+ &transfer_kafka_config,
+ config.cohort_merge_state_transfer_topic.clone(),
+ )
+ .await
+ .context("creating merge state transfer producer")?,
+ );
+ let stream_event_sink: Arc<dyn StreamEventSink> = Arc::new(
+ KafkaStreamEventSink::new(&kafka_config, config.cohort_stream_events_topic.clone())
+ .await
+ .context("creating straggler re-key producer")?,
+ );
+
+ let cascade_sink: Arc<dyn CascadeSink> = if config.cohort_cascade_enabled {
+ Arc::new(
+ KafkaCascadeSink::new(&kafka_config, config.cohort_cascade_events_topic.clone())
+ .await
+ .context("creating cohort_cascade_events producer")?,
+ )
+ } else {
+ Arc::new(NoopCascadeSink)
+ };
+ let merge_deps = Arc::new(MergeWorkerDeps {
+ transfer_sink,
+ stream_event_sink,
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: config.transfer_retry_policy(),
+ gc_scan_limit: config.merge_gc_scan_limit,
+ stage2_orphan_gc_enabled: config.stage2_orphan_gc_enabled,
+ cascade_sink,
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: config.cascade_config(),
+ partition_count: config.cohort_partition_count,
+ });
+
+ // Cheap `Arc` clones taken before the originals move into the dispatcher: the checkpoint sweeper
+ // needs its own handle on the store and each per-topic tracker to capture the offset manifest.
+ // Captured unconditionally to satisfy the borrow checker; consumed only when `checkpoint_enabled`.
+ let store_for_checkpoint = store.clone();
+ let events_tracker_for_checkpoint = offset_tracker.clone();
+ let merge_tracker_for_checkpoint = merge_deps.merge_tracker.clone();
+ let transfer_tracker_for_checkpoint = merge_deps.transfer_tracker.clone();
+ let cascade_tracker_for_checkpoint = merge_deps.cascade_tracker.clone();
+
+ let dispatcher = Arc::new(EventDispatcher::new(
+ router,
+ offset_tracker,
+ store,
+ catalog.clone(),
+ sink,
+ merge_deps,
+ ));
+ // Set once, before the consume loop and any worker spawn. The fsync-before-commit invariant is
+ // always on regardless — the gate only governs restore, not durability.
+ if config.durable_restore_enabled {
+ dispatcher.enable_durable_restore();
+ }
+
+ let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());
+ let stream_consumer: StreamConsumer<CohortConsumerContext> = config
+ .consumer_client_config()
+ .create_with_context(context)
+ .context("creating cohort_stream_events consumer")?;
+ stream_consumer
+ .subscribe(&[config.cohort_stream_events_topic.as_str()])
+ .context("subscribing to cohort_stream_events")?;
+
+ let merges_follower_consumer: Arc<StreamConsumer> = Arc::new(
+ config
+ .follower_client_config(&config.kafka_merge_consumer_group)
+ .create()
+ .context("creating person_merge_events follower consumer")?,
+ );
+ let transfers_follower_consumer: Arc<StreamConsumer> = Arc::new(
+ config
+ .follower_client_config(&config.kafka_merge_apply_consumer_group)
+ .create()
+ .context("creating cohort_merge_state_transfer follower consumer")?,
+ );
+ // Built only when the gate is on, so a dormant deploy needs no `cohort_cascade_events` topic.
+ let cascade_follower_consumer: Option<Arc<StreamConsumer>> = if config.cohort_cascade_enabled {
+ Some(Arc::new(
+ config
+ .follower_client_config(&config.kafka_cascade_consumer_group)
+ .create()
+ .context("creating cohort_cascade_events follower consumer")?,
+ ))
+ } else {
+ None
+ };
+
+ let events_partitions =
+ fetch_partition_count(&stream_consumer, &config.cohort_stream_events_topic)?;
+ let merge_partitions =
+ fetch_partition_count(&merges_follower_consumer, &config.person_merge_events_topic)?;
+ let transfer_partitions = fetch_partition_count(
+ &transfers_follower_consumer,
+ &config.cohort_merge_state_transfer_topic,
+ )?;
+ // The merge math hashes `(team, person)` against `config.cohort_partition_count`, so the topics
+ // must not only be co-partitioned with each other but partitioned at exactly that count — a
+ // deploy/lane at N != the configured count silently misroutes every merge.
+ anyhow::ensure!(
+ events_partitions as u32 == config.cohort_partition_count,
+ "{} is partitioned at {} but COHORT_PARTITION_COUNT is {}: the merge partition arithmetic \
+ would misroute. Re-partition the topic to {} or set COHORT_PARTITION_COUNT to {}.",
+ config.cohort_stream_events_topic,
+ events_partitions,
+ config.cohort_partition_count,
+ config.cohort_partition_count,
+ events_partitions,
+ );
+ anyhow::ensure!(
+ merge_partitions == events_partitions && transfer_partitions == events_partitions,
+ "merge topics must be co-partitioned with {} ({} partitions): {} has {}, {} has {}",
+ config.cohort_stream_events_topic,
+ events_partitions,
+ config.person_merge_events_topic,
+ merge_partitions,
+ config.cohort_merge_state_transfer_topic,
+ transfer_partitions,
+ );
+ // A cascade for (team, person) must land on the partition owning that person's `cf_stage2` — the
+ // same partition number as the events topic — so refuse to start co-partitioned at a different
+ // count. Skipped when the gate is off (no cascade topic required).
+ if let Some(cascade_consumer) = &cascade_follower_consumer {
+ let cascade_partitions =
+ fetch_partition_count(cascade_consumer, &config.cohort_cascade_events_topic)?;
+ anyhow::ensure!(
+ cascade_partitions as u32 == config.cohort_partition_count,
+ "cohort_cascade_events must be co-partitioned with {} at COHORT_PARTITION_COUNT={}: {} has {}",
+ config.cohort_stream_events_topic,
+ config.cohort_partition_count,
+ config.cohort_cascade_events_topic,
+ cascade_partitions,
+ );
+ }
+
+ if let Some(manifest) = restore.manifest.as_ref() {
+ commit_follower_offsets_from_manifest(
+ &merges_follower_consumer,
+ &config.person_merge_events_topic,
+ manifest,
+ );
+ commit_follower_offsets_from_manifest(
+ &transfers_follower_consumer,
+ &config.cohort_merge_state_transfer_topic,
+ manifest,
+ );
+ if let Some(cascade_consumer) = &cascade_follower_consumer {
+ commit_follower_offsets_from_manifest(
+ cascade_consumer,
+ &config.cohort_cascade_events_topic,
+ manifest,
+ );
+ }
+ }
+
+ let mut follower_mirrors = vec![
+ Follower::new(
+ merges_follower_consumer.clone(),
+ config.person_merge_events_topic.clone(),
+ ),
+ Follower::new(
+ transfers_follower_consumer.clone(),
+ config.cohort_merge_state_transfer_topic.clone(),
+ ),
+ ];
+ if let Some(cascade_consumer) = &cascade_follower_consumer {
+ follower_mirrors.push(Follower::new(
+ cascade_consumer.clone(),
+ config.cohort_cascade_events_topic.clone(),
+ ));
+ }
+ let followers = Arc::new(FollowerSet::new(follower_mirrors));
+
+ let (consumer_command_tx, consumer_command_rx) = mpsc::unbounded_channel();
+
+ let guard = manager.monitor_background();
+
+ let refresh_catalog = catalog.clone();
+ let refresh_pool = pool.clone();
+ let refresh_interval = config.filter_catalog_refresh_interval();
+ let refresh_jitter = config.filter_catalog_refresh_jitter();
+ tokio::spawn(async move {
+ run_refresh_loop(
+ refresh_catalog,
+ refresh_pool,
+ refresh_interval,
+ refresh_jitter,
+ catalog_handle_lifecycle,
+ )
+ .await;
+ });
+
+ let rebalance_worker = tokio::spawn(run_rebalance_worker(
+ rebalance_rx,
+ dispatcher.clone(),
+ followers,
+ consumer_command_tx,
+ consumer_handle.shutdown_token(),
+ ));
+
+ tokio::spawn(run_sweep_loop(
+ DispatchSweeper::new(dispatcher.clone(), config.sweep_safety_margin_ms as i64),
+ config.sweep_interval(),
+ "eviction",
+ consumer_handle.shutdown_token(),
+ ));
+
+ tokio::spawn(run_sweep_loop(
+ RedriveSweeper::new(dispatcher.clone()),
+ config.merge_redrive_interval(),
+ "redrive",
+ consumer_handle.shutdown_token(),
+ ));
+
+ tokio::spawn(run_sweep_loop(
+ MergeGcSweeper::new(
+ dispatcher.clone(),
+ config.merge_marker_retention_ms as i64,
+ config.merge_tombstone_retention_ms as i64,
+ ),
+ config.merge_gc_interval(),
+ "merge_gc",
+ consumer_handle.shutdown_token(),
+ ));
+
+ // Whole-DB checkpoint → PVC + incremental S3 sweep loop. Spawned only when the master gate is on,
+ // so a default deploy starts no checkpoint task. The cascade tracker is included only when cascade
+ // is on; otherwise it is idle and would contribute an empty manifest entry.
+ if config.checkpoint_enabled {
+ let uploader = S3Uploader::new(config.durability_config())
+ .await
+ .context("building checkpoint S3 uploader")?;
+ let exporter = CheckpointExporter::new(Box::new(uploader));
+ let upload_every_n = upload_cadence(
+ config.checkpoint_interval_ms,
+ config.checkpoint_s3_upload_interval_ms,
+ );
+ let mut trackers: Vec<TrackedTopic> = vec![
+ (
+ config.cohort_stream_events_topic.clone(),
+ events_tracker_for_checkpoint,
+ ),
+ (
+ config.person_merge_events_topic.clone(),
+ merge_tracker_for_checkpoint,
+ ),
+ (
+ config.cohort_merge_state_transfer_topic.clone(),
+ transfer_tracker_for_checkpoint,
+ ),
+ ];
+ if config.cohort_cascade_enabled {
+ trackers.push((
+ config.cohort_cascade_events_topic.clone(),
+ cascade_tracker_for_checkpoint,
+ ));
+ }
+ tokio::spawn(run_sweep_loop(
+ CheckpointSweeper::new(
+ store_for_checkpoint,
+ dispatcher.clone(),
+ trackers,
+ exporter,
+ config.durability_config(),
+ PathBuf::from(&config.checkpoint_local_dir),
+ upload_every_n,
+ ),
+ config.checkpoint_interval(),
+ CHECKPOINT_LOOP_NAME,
+ consumer_handle.shutdown_token(),
+ ));
+ }
+
+ let merge_follower = FollowerConsumer::<MergeRoute>::new(
+ merges_follower_consumer,
+ config.person_merge_events_topic.clone(),
+ dispatcher.clone(),
+ merge_follower_handle.clone(),
+ config.recv_batch_size,
+ config.recv_batch_timeout(),
+ config.offset_commit_interval(),
+ );
+ spawn_follower_after_catalog_load(catalog.clone(), merge_follower, merge_follower_handle);
+
+ let transfer_follower = FollowerConsumer::<TransferRoute>::new(
+ transfers_follower_consumer,
+ config.cohort_merge_state_transfer_topic.clone(),
+ dispatcher.clone(),
+ transfer_follower_handle.clone(),
+ config.recv_batch_size,
+ config.recv_batch_timeout(),
+ config.offset_commit_interval(),
+ );
+ spawn_follower_after_catalog_load(catalog.clone(), transfer_follower, transfer_follower_handle);
+
+ if let (Some(cascade_consumer), Some(cascade_handle)) =
+ (cascade_follower_consumer, cascade_follower_handle)
+ {
+ let cascade_follower = FollowerConsumer::<CascadeRoute>::new(
+ cascade_consumer,
+ config.cohort_cascade_events_topic.clone(),
+ dispatcher.clone(),
+ cascade_handle.clone(),
+ config.recv_batch_size,
+ config.recv_batch_timeout(),
+ config.offset_commit_interval(),
+ );
+ spawn_follower_after_catalog_load(catalog.clone(), cascade_follower, cascade_handle);
+ }
+
+ let events_consumer = CohortStreamEventsConsumer::new(
+ stream_consumer,
+ config.cohort_stream_events_topic.clone(),
+ dispatcher,
+ consumer_handle,
+ config.recv_batch_size,
+ config.recv_batch_timeout(),
+ config.offset_commit_interval(),
+ events_partitions,
+ consumer_command_rx,
+ // Events-topic seek positions for the restore-and-seek step; `None` on the no-seek paths
+ // (reopen-live / cold-start).
+ restore.manifest,
+ );
+ tokio::spawn(events_consumer.process());
+
+ let app = observability::health::router(SERVICE_NAME, readiness, liveness, recorder_handle);
+ let bind = config.bind_address();
+ info!(address = %bind, "observability server starting");
+
+ let listener = TcpListener::bind(&bind)
+ .await
+ .with_context(|| format!("failed to bind observability server to {bind}"))?;
+ axum::serve(listener, app)
+ .with_graceful_shutdown(metrics_handle.shutdown_signal())
+ .await
+ .context("observability server error")?;
+ metrics_handle.work_completed();
+
+ guard.wait().await?;
+
+ if let Err(err) = rebalance_worker.await {
+ warn!(error = %err, "rebalance worker task did not exit cleanly");
+ }
+
+ info!(service = SERVICE_NAME, "service stopped");
+ Ok(())
+}
+
+fn fetch_partition_count<C: ConsumerContext>(
+ consumer: &StreamConsumer<C>,
+ topic: &str,
+) -> Result<usize> {
+ let metadata = consumer
+ .fetch_metadata(Some(topic), Duration::from_secs(10))
+ .with_context(|| format!("fetching broker metadata for {topic}"))?;
+ let topic_metadata = metadata
+ .topics()
+ .iter()
+ .find(|candidate| candidate.name() == topic)
+ .with_context(|| format!("topic {topic} missing from broker metadata"))?;
+ if let Some(err) = topic_metadata.error() {
+ anyhow::bail!("broker reports an error for topic {topic}: {err:?}");
+ }
+ let count = topic_metadata.partitions().len();
+ anyhow::ensure!(
+ count > 0,
+ "topic {topic} has no partitions in broker metadata"
+ );
+ Ok(count)
+}
+
+/// Seed a follower consumer group's committed offsets from the restore manifest, so its subsequent
+/// `incremental_assign` at [`Offset::Stored`](rdkafka::Offset::Stored) resolves to the restored
+/// position rather than the broker's last commit.
+///
+/// A strict no-op when the manifest has no entry for `topic` or that entry is empty. Commits one
+/// `Offset::Offset(next)` per present partition; a commit error is logged and skipped, never fatal, so
+/// it cannot delay or break the existing follower assignment. The manifest stores `committed_offset`
+/// (next-offset-to-consume), exactly what a Kafka committed offset means, so committing it verbatim is
+/// the correct resume point.
+fn commit_follower_offsets_from_manifest(
+ consumer: &StreamConsumer,
+ topic: &str,
+ manifest: &OffsetManifest,
+) {
+ let Some(tpl) = manifest_commit_tpl(topic, manifest) else {
+ return;
+ };
+ match consumer.commit(&tpl, CommitMode::Sync) {
+ Ok(()) => info!(
+ topic,
+ partitions = tpl.count(),
+ "seeded follower group offsets from restore manifest",
+ ),
+ Err(err) => {
+ warn!(topic, error = %err, "failed to seed follower offsets from manifest; falling back to broker-stored offsets")
+ }
+ }
+}
+
+/// Returns the `TopicPartitionList` to commit for `topic`, or `None` when the manifest has no entry,
+/// the entry is empty, or no partition produced a valid offset. Pure (no I/O) so the behavior is
+/// unit-testable without a broker. Each partition is committed at `Offset::Offset(next_offset)` —
+/// the next-to-consume value Kafka committed offsets denote — so `Offset::Stored` resolves to it.
+fn manifest_commit_tpl(topic: &str, manifest: &OffsetManifest) -> Option<TopicPartitionList> {
+ let partitions = manifest.topics.get(topic)?;
+ if partitions.is_empty() {
+ return None;
+ }
+ let mut tpl = TopicPartitionList::new();
+ for (&partition, &next_offset) in partitions {
+ if let Err(err) = tpl.add_partition_offset(topic, partition, Offset::Offset(next_offset)) {
+ warn!(topic, partition, next_offset, error = %err, "skipping follower partition in manifest commit");
+ }
+ }
+ (tpl.count() > 0).then_some(tpl)
+}
+
+fn spawn_follower_after_catalog_load<R: FollowerRoute>(
+ catalog: Arc<CatalogHandle>,
+ follower: FollowerConsumer<R>,
+ handle: Handle,
+) {
+ tokio::spawn(async move {
+ tokio::select! {
+ biased;
+ _ = handle.shutdown_recv() => {}
+ _ = catalog.wait_until_loaded() => follower.process().await,
+ }
+ });
+}
+
+/// Log a redacted startup summary. Deliberately omits `database_url` (carries credentials).
+fn log_startup(config: &Config) {
+ info!(
+ service = SERVICE_NAME,
+ bind_address = %config.bind_address(),
+ kafka_hosts = %config.kafka_hosts,
+ input_topic = %config.cohort_stream_events_topic,
+ output_topic = %config.cohort_membership_changed_topic,
+ consumer_group = %config.kafka_consumer_group,
+ offset_reset = %config.kafka_consumer_offset_reset,
+ merge_topic = %config.person_merge_events_topic,
+ transfer_topic = %config.cohort_merge_state_transfer_topic,
+ merge_consumer_group = %config.kafka_merge_consumer_group,
+ merge_apply_consumer_group = %config.kafka_merge_apply_consumer_group,
+ session_timeout_ms = config.kafka_session_timeout_ms,
+ pod_identity = config.pod_identity().unwrap_or("<dynamic>"),
+ recv_batch_size = config.recv_batch_size,
+ partition_channel_buffer = config.partition_channel_buffer,
+ store_path = %config.store_path,
+ wipe_store_on_start = config.wipe_store_on_start,
+ durable_restore_enabled = config.durable_restore_enabled,
+ filter_catalog_refresh_secs = config.filter_catalog_refresh_secs,
+ filter_catalog_refresh_jitter_secs = config.filter_catalog_refresh_jitter_secs,
+ team_allowlist = ?config.team_allowlist,
+ cohort_cascade_enabled = config.cohort_cascade_enabled,
+ cascade_topic = %config.cohort_cascade_events_topic,
+ cascade_consumer_group = %config.kafka_cascade_consumer_group,
+ "starting cohort-stream-processor",
+ );
+}
+
+/// JSON structured logging in production; human-readable when `RUST_LOG` requests debug.
+fn init_tracing() {
+ let is_debug = std::env::var("RUST_LOG")
+ .map(|v| v.contains("debug"))
+ .unwrap_or(false);
+
+ let log_layer = if is_debug {
+ fmt::layer()
+ .with_target(true)
+ .with_level(true)
+ .with_ansi(true)
+ .with_filter(
+ EnvFilter::builder()
+ .with_default_directive(tracing::level_filters::LevelFilter::INFO.into())
+ .from_env_lossy(),
+ )
+ .boxed()
+ } else {
+ fmt::layer()
+ .json()
+ .flatten_event(true)
+ .with_current_span(true)
+ .with_filter(
+ EnvFilter::builder()
+ .with_default_directive(tracing::level_filters::LevelFilter::INFO.into())
+ .from_env_lossy(),
+ )
+ .boxed()
+ };
+
+ tracing_subscriber::registry().with(log_layer).init();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::BTreeMap;
+
+ use cohort_stream_processor::store::durability::MANIFEST_VERSION;
+
+ fn manifest_with(topics: BTreeMap<String, BTreeMap<i32, i64>>) -> OffsetManifest {
+ OffsetManifest {
+ version: MANIFEST_VERSION,
+ captured_at: chrono::Utc::now(),
+ topics,
+ }
+ }
+
+ #[test]
+ fn manifest_commit_tpl_is_none_for_an_absent_topic() {
+ let manifest = manifest_with(BTreeMap::new());
+ assert!(manifest_commit_tpl("person_merge_events", &manifest).is_none());
+ }
+
+ #[test]
+ fn manifest_commit_tpl_is_none_for_an_empty_topic_entry() {
+ let mut topics = BTreeMap::new();
+ topics.insert("person_merge_events".to_string(), BTreeMap::new());
+ let manifest = manifest_with(topics);
+ assert!(
+ manifest_commit_tpl("person_merge_events", &manifest).is_none(),
+ "an empty follower topic entry must produce no commit (inert in Slice 2)",
+ );
+ }
+
+ #[test]
+ fn manifest_commit_tpl_commits_present_follower_offsets() {
+ let mut topics = BTreeMap::new();
+ topics.insert(
+ "person_merge_events".to_string(),
+ BTreeMap::from([(0, 7), (4, 19)]),
+ );
+ let manifest = manifest_with(topics);
+
+ let tpl = manifest_commit_tpl("person_merge_events", &manifest)
+ .expect("present follower offsets produce a commit list");
+ assert_eq!(tpl.count(), 2);
+ assert_eq!(
+ tpl.find_partition("person_merge_events", 0)
+ .unwrap()
+ .offset(),
+ Offset::Offset(7),
+ );
+ assert_eq!(
+ tpl.find_partition("person_merge_events", 4)
+ .unwrap()
+ .offset(),
+ Offset::Offset(19),
+ );
+ }
+
+ #[test]
+ fn manifest_commit_tpl_round_trips_a_multi_topic_live_capture() {
+ // Distinct offsets per tracker/partition so a cross-wired capture would surface in the TPL.
+ let owned = [3, 7];
+ let merge = OffsetTracker::new();
+ let transfer = OffsetTracker::new();
+ let cascade = OffsetTracker::new();
+ for (tracker, base) in [(&merge, 10), (&transfer, 20), (&cascade, 30)] {
+ for (partition, bump) in [(3, 1), (7, 2)] {
+ let offset = base + bump;
+ tracker.mark_dispatched(partition, offset);
+ let _ = tracker.mark_processed(partition, offset);
+ tracker.mark_committed(partition, offset);
+ }
+ }
+
+ let manifest = OffsetManifest::capture(
+ &owned,
+ &[
+ ("person_merge_events", &merge),
+ ("cohort_merge_state_transfer", &transfer),
+ ("cohort_cascade_events", &cascade),
+ ],
+ );
+
+ for (topic, base) in [
+ ("person_merge_events", 10),
+ ("cohort_merge_state_transfer", 20),
+ ("cohort_cascade_events", 30),
+ ] {
+ let tpl = manifest_commit_tpl(topic, &manifest)
+ .unwrap_or_else(|| panic!("{topic} live capture must produce a commit list"));
+ assert_eq!(tpl.count(), 2, "{topic} commits both owned partitions");
+ assert_eq!(
+ tpl.find_partition(topic, 3).unwrap().offset(),
+ Offset::Offset(base + 1),
+ );
+ assert_eq!(
+ tpl.find_partition(topic, 7).unwrap().offset(),
+ Offset::Offset(base + 2),
+ );
+ }
+
+ assert!(
+ manifest_commit_tpl("cohort_stream_events", &manifest).is_none(),
+ "a topic absent from the live capture must produce no commit",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/merge/apply_handler.rs b/rust/cohort-stream-processor/src/merge/apply_handler.rs
new file mode 100644
index 000000000000..f98b90f6d906
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/apply_handler.rs
@@ -0,0 +1,308 @@
+//! Apply a `MergeStateTransfer` on P_new's worker (phase 2 of cross-partition merge).
+//!
+//! Given a transfer (P_old's drained per-leaf records), merges each leaf into P_new's state, commits
+//! one atomic `WriteBatch` (merged puts, `cf_person_index` appends, and the `cf_merge_applied`
+//! idempotence marker), schedules P_new's eviction deadlines, and returns the membership transitions
+//! for the caller to compose Stage 2 and produce.
+//!
+//! Before applying, the target `new_person_uuid` is resolved through the local slice's tombstones:
+//! in a chained merge `A → B → C` where `B → C` drained before `A → B` applies, P_new (= B) is
+//! already tombstoned, so applying A's state into B would strand it. Resolving the target sends A's
+//! state to the live survivor instead — inline when the survivor co-resides on this partition,
+//! forwarded on `cohort_merge_state_transfer` when it lives on another.
+
+use metrics::counter;
+use uuid::Uuid;
+
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::TeamId;
+use crate::merge::rules::merge_records;
+use crate::merge::tombstone_redirect::{resolve, Resolution};
+use crate::merge::transfer::{ApplyStamp, MergeStateTransfer};
+use crate::observability::metrics::{
+ MERGE_APPLIES_SKIPPED_REPLAY_TOTAL, MERGE_FORWARD_HOP_CAPPED_TOTAL, MERGE_LEAVES_DROPPED_TOTAL,
+ MERGE_TRANSFER_FORWARDS_TOTAL,
+};
+use crate::stage1::key::{LeafStateKey, Stage1Key};
+use crate::stage1::state::StatefulRecord;
+use crate::stage1::transition::LeafTransition;
+use crate::store::{CohortStore, IndexOp, MergeAppliedKey, PersonIndexKey, StoreError};
+use crate::sweep::EvictionQueue;
+use crate::workers::event_path::schedule_deadline;
+use tracing::warn;
+
+/// Bound on cross-partition transfer-forward hops (`forward_hops` on the wire). Mirrors the
+/// event-path [`crate::merge::tombstone_redirect::MAX_CROSS_PARTITION_REDIRECT_HOPS`] — prevents
+/// infinite re-production between partitions in case of a corrupt cross-partition tombstone cycle.
+pub const MAX_TRANSFER_FORWARD_HOPS: u8 = 8;
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum ApplyOutcome {
+ /// Transfer applied; `transitions` are the resolved survivor's per-leaf membership flips.
+ Applied { transitions: Vec<LeafTransition> },
+ /// Idempotence hit — this transfer was already applied (replay / crash-recovery).
+ AlreadyApplied,
+ /// `new_person_uuid` is tombstoned to a survivor on a different partition. The caller forwards
+ /// `transfer` (already rewritten to the survivor, `forward_hops` incremented) on the transfer
+ /// topic. No state and no marker are written here — redelivery re-resolves and re-produces, and
+ /// the final target's marker is the dedup (the same ReKey posture the straggler re-key uses).
+ Forward { transfer: Box<MergeStateTransfer> },
+ /// The forward hop cap was hit (a corrupt tombstone cycle). No state written; the caller marks
+ /// the offset so the partition does not wedge. Never expected in a clean system.
+ HopCapped,
+}
+
+/// Apply `transfer` on the worker that owns `transfer.new_person_uuid` (`partition_id`).
+///
+/// Idempotence is keyed by the *source merge message's* coordinates (not the transfer message's
+/// own), because duplicate transfer copies (redrive, crash-retry, forward) arrive at fresh
+/// transfer-topic offsets but share the same source pair.
+///
+/// `partition_count` is the live co-partitioned topic count (production 64; test lanes lower it):
+/// the forward-vs-inline target resolution turns on whether the survivor hashes onto `partition_id`
+/// under this count, so it must match the deploy's topology.
+pub fn handle_transfer(
+ partition_id: u16,
+ store: &CohortStore,
+ filters: &TeamFilters,
+ transfer: &MergeStateTransfer,
+ _transfer_coords: (i32, i64),
+ queue: &mut EvictionQueue<Stage1Key>,
+ partition_count: u32,
+) -> Result<ApplyOutcome, StoreError> {
+ let team_id = transfer.team_id;
+ let team_u64 = team_id as u64;
+ let new_person = transfer.new_person_uuid;
+
+ // Original-target idempotence: absorbs the ordered-case redelivery (marker written under B
+ // before B was tombstoned), before the chain is resolved.
+ if store
+ .get_merge_applied(&applied_key(partition_id, team_u64, new_person, transfer))?
+ .is_some()
+ {
+ counter!(MERGE_APPLIES_SKIPPED_REPLAY_TOTAL).increment(1);
+ return Ok(ApplyOutcome::AlreadyApplied);
+ }
+
+ // Resolve the target through the local slice: if P_new is itself tombstoned (the raced chain),
+ // the state belongs to the survivor, not to the drained P_new.
+ match resolve(
+ store,
+ partition_id,
+ TeamId(team_id),
+ new_person,
+ partition_count,
+ )? {
+ Resolution::NotMerged => {
+ apply_into(partition_id, store, filters, transfer, new_person, queue)
+ }
+ Resolution::Inline { final_person, .. } => {
+ counter!(MERGE_TRANSFER_FORWARDS_TOTAL, "path" => "inline").increment(1);
+ apply_into(partition_id, store, filters, transfer, final_person, queue)
+ }
+ Resolution::CrossPartition { target_person, .. } => {
+ if transfer.forward_hops >= MAX_TRANSFER_FORWARD_HOPS {
+ counter!(MERGE_FORWARD_HOP_CAPPED_TOTAL).increment(1);
+ warn!(
+ partition_id,
+ team_id,
+ new_person = %new_person,
+ target_person = %target_person,
+ forward_hops = transfer.forward_hops,
+ "transfer forward hit the hop cap; dropping and marking the offset (corrupt tombstone cycle)",
+ );
+ return Ok(ApplyOutcome::HopCapped);
+ }
+ let mut forwarded = transfer.clone();
+ forwarded.new_person_uuid = target_person;
+ forwarded.forward_hops = transfer.forward_hops + 1;
+ Ok(ApplyOutcome::Forward {
+ transfer: Box::new(forwarded),
+ })
+ }
+ }
+}
+
+/// The `cf_merge_applied` key for `target` under this merge's source coordinates.
+fn applied_key(
+ partition_id: u16,
+ team_u64: u64,
+ target: Uuid,
+ transfer: &MergeStateTransfer,
+) -> MergeAppliedKey {
+ MergeAppliedKey {
+ partition_id,
+ team_id: team_u64,
+ new_person: target,
+ source_partition: transfer.source_partition,
+ source_offset: transfer.source_offset,
+ }
+}
+
+/// Apply `transfer`'s leaves into `target` (the resolved survivor, co-resident on `partition_id`),
+/// commit the merged puts + person-index appends + the `cf_merge_applied` marker keyed by `target`,
+/// schedule deadlines, and return the survivor's transitions. For the `NotMerged` case `target` is
+/// just `new_person_uuid`.
+fn apply_into(
+ partition_id: u16,
+ store: &CohortStore,
+ filters: &TeamFilters,
+ transfer: &MergeStateTransfer,
+ target: Uuid,
+ queue: &mut EvictionQueue<Stage1Key>,
+) -> Result<ApplyOutcome, StoreError> {
+ let team_u64 = transfer.team_id as u64;
+ let old_person = transfer.old_person_uuid;
+
+ // A forwarded copy may already have applied under the survivor at these source coords.
+ let target_applied_key = applied_key(partition_id, team_u64, target, transfer);
+ if target != transfer.new_person_uuid && store.get_merge_applied(&target_applied_key)?.is_some()
+ {
+ counter!(MERGE_APPLIES_SKIPPED_REPLAY_TOTAL).increment(1);
+ return Ok(ApplyOutcome::AlreadyApplied);
+ }
+
+ let mut leaves: Vec<(LeafStateKey, StatefulRecord)> = Vec::with_capacity(transfer.leaves.len());
+ for leaf in &transfer.leaves {
+ match leaf.decode_leaf_state_key() {
+ Some(lsk) => leaves.push((lsk, leaf.record.clone())),
+ None => {
+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "leaf_hex").increment(1);
+ }
+ }
+ }
+
+ // `old_person` stays as the transfer's original P_old so `compose_ancestor_dedup` registers it
+ // as the ancestor of `target`, keeping the dedup chain walkable.
+ let apply = apply_leaves(
+ partition_id,
+ store,
+ filters,
+ transfer.team_id,
+ old_person,
+ target,
+ &leaves,
+ )?;
+
+ let target_index = PersonIndexKey {
+ partition_id,
+ team_id: team_u64,
+ person_id: target,
+ };
+ let stamp = ApplyStamp {
+ applied_at_ms: transfer.merged_at_ms,
+ };
+ store.write_batch(|batch| {
+ for (key, bytes) in &apply.puts {
+ batch.put_stage1(key, bytes);
+ }
+ for lsk in &apply.appends {
+ batch.merge_person_index(&target_index, IndexOp::Append(*lsk));
+ }
+ batch.put_merge_applied(&target_applied_key, &stamp.encode());
+ // Fixed-origin dedup: also stamp under the original `new_person_uuid` when the chain
+ // retargeted (`target != new_person_uuid`). `new_person_uuid` is the one identity stable
+ // across every redelivery of this merge's transfer, so a redelivered copy whose chain has
+ // since extended further (C → D → …) hits the `handle_transfer` original-target probe and
+ // dedups — even though the resolved-target marker now sits under a later survivor, not under
+ // this `target`. Closes the same-partition raced-then-extended double-apply. One extra put,
+ // atomic with the leaf writes and the target marker.
+ //
+ // Residual: a chain that later extends to a survivor on *another* partition still misses —
+ // `cf_merge_applied` markers are partition-local and the cross-partition `Forward` path
+ // writes none here. Bounded by `MAX_TRANSFER_FORWARD_HOPS` (short chains ⇒ rare); fully
+ // closing it needs marker-forwarding during drain (deferred).
+ if target != transfer.new_person_uuid {
+ let original_key =
+ applied_key(partition_id, team_u64, transfer.new_person_uuid, transfer);
+ batch.put_merge_applied(&original_key, &stamp.encode());
+ }
+ })?;
+
+ for (key, deadline) in &apply.schedules {
+ queue.schedule(*key, *deadline);
+ }
+
+ Ok(ApplyOutcome::Applied {
+ transitions: apply.transitions,
+ })
+}
+
+/// Computed writes from applying P_old's leaves into P_new, uncommitted so the caller can compose
+/// the final batch.
+#[derive(Debug, Default)]
+pub(crate) struct LeafApply {
+ pub puts: Vec<(Stage1Key, Vec<u8>)>,
+ pub appends: Vec<LeafStateKey>,
+ pub transitions: Vec<LeafTransition>,
+ pub schedules: Vec<(Stage1Key, i64)>,
+}
+
+/// Merge each of P_old's `leaves` into P_new's state on `partition_new`. Pure reads only — the
+/// caller composes the final write batch. A leaf whose LSK left the catalog is skipped; a corrupt
+/// P_new record is treated as absent.
+pub(crate) fn apply_leaves(
+ partition_new: u16,
+ store: &CohortStore,
+ filters: &TeamFilters,
+ team_id: i32,
+ old_person: Uuid,
+ new_person: Uuid,
+ leaves: &[(LeafStateKey, StatefulRecord)],
+) -> Result<LeafApply, StoreError> {
+ let team_u64 = team_id as u64;
+ let mut out = LeafApply::default();
+
+ // One batched read of every leaf's `p_new` state. Keys are built in `leaves` order so the zip
+ // below stays aligned; a leaf later skipped by the drift check simply ignores its result.
+ let p_new_keys: Vec<Stage1Key> = leaves
+ .iter()
+ .map(|(lsk, _)| Stage1Key {
+ partition_id: partition_new,
+ team_id: team_u64,
+ leaf_state_key: *lsk,
+ person_id: new_person,
+ })
+ .collect();
+ let p_new_raw = store.multi_get_stage1(&p_new_keys)?;
+
+ for ((lsk, old_record), (p_new_key, p_new_bytes)) in
+ leaves.iter().zip(p_new_keys.into_iter().zip(p_new_raw))
+ {
+ let Some(meta) = filters.by_lsk.get(lsk) else {
+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "leaf_drift").increment(1);
+ continue;
+ };
+ let p_new_record = match p_new_bytes {
+ None => None,
+ Some(bytes) => StatefulRecord::decode(&bytes).ok(),
+ };
+
+ let merged = merge_records(
+ old_person,
+ old_record,
+ p_new_record.as_ref(),
+ meta,
+ filters.timezone,
+ );
+
+ if let Some(record) = merged.record {
+ if let Some(deadline) = schedule_deadline(&record.state) {
+ out.schedules.push((p_new_key, deadline));
+ }
+ out.puts.push((p_new_key, record.encode()));
+ out.appends.push(*lsk);
+ }
+ if let Some(kind) = merged.flip {
+ out.transitions.push(LeafTransition {
+ team_id: TeamId(team_id),
+ leaf_state_key: *lsk,
+ person_id: new_person,
+ condition_hash: meta.condition_hash,
+ kind,
+ });
+ }
+ }
+
+ Ok(out)
+}
diff --git a/rust/cohort-stream-processor/src/merge/bucket_align.rs b/rust/cohort-stream-processor/src/merge/bucket_align.rs
new file mode 100644
index 000000000000..2437470aa7be
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/bucket_align.rs
@@ -0,0 +1,90 @@
+//! Dense daily-bucket alignment for merging two `BehavioralDailyBuckets` states.
+//!
+//! Both sides share `window_days`. Alignment picks the more recent window start and sums
+//! element-wise.
+
+use crate::stage1::bucket_tz::now_day_for_window;
+use crate::stage1::daily::slide_window_forward;
+
+/// Align two dense bucket arrays to the more recent window and sum element-wise (saturating).
+///
+/// Each side is slid forward to `max(old_start, new_start)` via [`slide_window_forward`], then
+/// summed. Both inputs must have length `window_days + 1`; a length mismatch truncates to the
+/// shorter side.
+pub fn align_and_sum(
+ old_buckets: &[u32],
+ old_window_start_day: i32,
+ new_buckets: &[u32],
+ new_window_start_day: i32,
+ window_days: u32,
+) -> (Vec<u32>, i32) {
+ let target_start = old_window_start_day.max(new_window_start_day);
+ let target_now = now_day_for_window(target_start, window_days);
+
+ let mut old_aligned = old_buckets.to_vec();
+ let mut old_start = old_window_start_day;
+ slide_window_forward(&mut old_aligned, &mut old_start, window_days, target_now);
+
+ let mut new_aligned = new_buckets.to_vec();
+ let mut new_start = new_window_start_day;
+ slide_window_forward(&mut new_aligned, &mut new_start, window_days, target_now);
+
+ let merged = old_aligned
+ .iter()
+ .zip(new_aligned.iter())
+ .map(|(&old, &new)| old.saturating_add(new))
+ .collect();
+ (merged, target_start)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tdd_4_5_1_worked_example() {
+ let (merged, start) = align_and_sum(
+ &[2, 0, 1, 3, 0, 1, 5],
+ 19_500,
+ &[0, 1, 2, 0, 1, 0, 4],
+ 19_501,
+ 6,
+ );
+ assert_eq!(merged, vec![0, 2, 5, 0, 2, 5, 4]);
+ assert_eq!(
+ start, 19_501,
+ "the merged window anchors on the more recent start"
+ );
+ }
+
+ #[test]
+ fn identical_windows_sum_without_shifting() {
+ let (merged, start) = align_and_sum(&[1, 2, 3], 100, &[4, 5, 6], 100, 2);
+ assert_eq!(merged, vec![5, 7, 9]);
+ assert_eq!(start, 100);
+ }
+
+ #[test]
+ fn old_window_ahead_aligns_new_forward() {
+ let (merged, start) = align_and_sum(&[10, 20, 30], 101, &[1, 2, 3], 100, 2);
+ assert_eq!(merged, vec![12, 23, 30]);
+ assert_eq!(start, 101);
+ }
+
+ #[test]
+ fn disjoint_windows_one_side_fully_slides_out() {
+ let (merged, start) = align_and_sum(&[1, 1, 1, 1], 1_000, &[9, 9, 9, 9], 100, 3);
+ assert_eq!(
+ merged,
+ vec![1, 1, 1, 1],
+ "new's stale buckets all slid past"
+ );
+ assert_eq!(start, 1_000);
+ }
+
+ #[test]
+ fn counts_saturate_at_u32_max() {
+ let (merged, _) = align_and_sum(&[u32::MAX, 0], 50, &[5, 0], 50, 1);
+ assert_eq!(merged, vec![u32::MAX, 0], "saturating add never wraps");
+ }
+}
diff --git a/rust/cohort-stream-processor/src/merge/compressed_concat.rs b/rust/cohort-stream-processor/src/merge/compressed_concat.rs
new file mode 100644
index 000000000000..93ed29793afe
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/compressed_concat.rs
@@ -0,0 +1,85 @@
+//! Sparse run-length union for merging two `BehavioralCompressedHistory` states.
+//!
+//! No index alignment is needed (unlike the dense daily variant) because RLE stores absolute day
+//! indices, so the union is a straight by-day sum.
+
+use std::collections::BTreeMap;
+
+/// Union two sparse run-length histories by absolute `day_idx`, summing counts for shared days.
+///
+/// Returns `(merged_entries, merged_window_start_day)`. Entries are sorted ascending by day with no
+/// zero-count entries. `merged_window_start_day = max(old, new)`. Entries below the anchor are
+/// retained (the next sweep prunes out-of-window entries).
+pub fn union_by_day(
+ old_entries: &[(i32, u32)],
+ old_window_start_day: i32,
+ new_entries: &[(i32, u32)],
+ new_window_start_day: i32,
+) -> (Vec<(i32, u32)>, i32) {
+ let mut by_day: BTreeMap<i32, u32> = BTreeMap::new();
+ for &(day, count) in old_entries.iter().chain(new_entries.iter()) {
+ let slot = by_day.entry(day).or_insert(0);
+ *slot = slot.saturating_add(count);
+ }
+ let merged = by_day.into_iter().filter(|&(_, count)| count > 0).collect();
+ (merged, old_window_start_day.max(new_window_start_day))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn shared_days_sum_and_disjoint_days_union_sorted() {
+ let (merged, start) = union_by_day(
+ &[(100, 2), (200, 1), (300, 5)],
+ 10,
+ &[(150, 3), (200, 4)],
+ 20,
+ );
+ assert_eq!(
+ merged,
+ vec![(100, 2), (150, 3), (200, 5), (300, 5)],
+ "day 200 sums to 5; the rest union, sorted ascending",
+ );
+ assert_eq!(
+ start, 20,
+ "the merged anchor is the more recent window start"
+ );
+ }
+
+ #[test]
+ fn one_empty_side_returns_the_other() {
+ let (merged, start) = union_by_day(&[], 5, &[(100, 1), (200, 2)], 50);
+ assert_eq!(merged, vec![(100, 1), (200, 2)]);
+ assert_eq!(start, 50);
+
+ let (merged, start) = union_by_day(&[(100, 1)], 50, &[], 5);
+ assert_eq!(merged, vec![(100, 1)]);
+ assert_eq!(start, 50);
+ }
+
+ #[test]
+ fn both_empty_is_empty() {
+ let (merged, start) = union_by_day(&[], 7, &[], 9);
+ assert!(merged.is_empty());
+ assert_eq!(start, 9);
+ }
+
+ #[test]
+ fn counts_saturate_at_u32_max() {
+ let (merged, _) = union_by_day(&[(100, u32::MAX)], 0, &[(100, 5)], 0);
+ assert_eq!(merged, vec![(100, u32::MAX)], "saturating add never wraps");
+ }
+
+ #[test]
+ fn entries_below_the_merged_anchor_are_retained_rle_invariant_holds() {
+ let (merged, start) = union_by_day(&[(5, 1)], 5, &[(100, 1)], 90);
+ assert_eq!(merged, vec![(5, 1), (100, 1)]);
+ assert_eq!(start, 90);
+ assert!(
+ merged.windows(2).all(|w| w[0].0 < w[1].0),
+ "entries stay strictly sorted by day",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/merge/drain_handler.rs b/rust/cohort-stream-processor/src/merge/drain_handler.rs
new file mode 100644
index 000000000000..6c690b2d337d
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/drain_handler.rs
@@ -0,0 +1,437 @@
+//! Drain P_old on its own worker (phase 1 of cross-partition merge).
+//!
+//! Given a `PersonMergeEvent` (keyed by P_old), reads P_old's per-leaf state, then either:
+//!
+//! - **fast path** (P_new co-resides on this partition): merges inline via the apply core in one
+//! atomic `WriteBatch`, returning P_new's transitions; or
+//! - **slow path**: packages P_old's records into a [`MergeStateTransfer`] staged in
+//! `cf_pending_transfers`, deletes P_old's state, writes the tombstone + drain marker, and returns
+//! the transfer for the caller to produce.
+//!
+//! The drain emits no `Left` for P_old — it silently deletes P_old's rows. P_old's `cf_stage2` keys
+//! are built from the catalog (no reads needed; deleting an absent key is a no-op).
+
+use metrics::counter;
+use uuid::Uuid;
+
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::{CohortId, TeamId};
+use crate::merge::apply_handler::apply_leaves;
+use crate::merge::tombstone_redirect::{resolve, Resolution};
+use crate::merge::transfer::{
+ DrainStamp, MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, TransferLeaf,
+};
+use crate::observability::metrics::{
+ MERGE_DRAINS_SKIPPED_REPLAY_TOTAL, MERGE_HANDLED_TOTAL, MERGE_LEAVES_DROPPED_TOTAL,
+};
+use crate::partitions::partitioner::partition_of;
+use crate::stage1::key::{LeafStateKey, Stage1Key};
+use crate::stage1::state::StatefulRecord;
+use crate::stage1::transition::LeafTransition;
+use crate::store::{
+ CohortStore, IndexOp, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key, StoreError,
+ TombstoneKey,
+};
+use crate::sweep::EvictionQueue;
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum DrainOutcome {
+ /// Same-partition fast path: P_old merged into P_new inline.
+ FastPath { transitions: Vec<LeafTransition> },
+ /// Cross-partition slow path: state drained into `transfer`, staged in `cf_pending_transfers`.
+ /// An empty transfer (no leaves) is not staged; the caller skips the produce and commits directly.
+ Drained { transfer: MergeStateTransfer },
+ /// Idempotence hit — already drained. The caller re-produces any still-staged pending transfer.
+ AlreadyDrained,
+ /// Skipped before any state change (validation failure).
+ Skipped(DrainSkip),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DrainSkip {
+ SamePerson,
+}
+
+/// Drain the merge `event` on P_old's worker (`partition_id` owns P_old).
+///
+/// `partition_count` is the live co-partitioned topic count (production 64; test lanes lower it):
+/// the fast-path-vs-slow-path decision turns on whether P_new hashes onto `partition_id` under this
+/// count, so it must match the deploy's topology.
+pub fn handle_merge_event(
+ partition_id: u16,
+ store: &CohortStore,
+ filters: &TeamFilters,
+ event: &PersonMergeEvent,
+ msg_coords: (i32, i64),
+ queue: &mut EvictionQueue<Stage1Key>,
+ partition_count: u32,
+) -> Result<DrainOutcome, StoreError> {
+ let team_id = event.team_id;
+ let team_u64 = team_id as u64;
+ let old_person = event.old_person_uuid;
+ let new_person = event.new_person_uuid;
+
+ if old_person == new_person {
+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "same_person").increment(1);
+ return Ok(DrainOutcome::Skipped(DrainSkip::SamePerson));
+ }
+
+ let drain_key = MergeDrainKey {
+ partition_id,
+ team_id: team_u64,
+ old_person,
+ merge_msg_partition: msg_coords.0,
+ merge_msg_offset: msg_coords.1,
+ };
+ if store.get_merge_drain_applied(&drain_key)?.is_some() {
+ counter!(MERGE_DRAINS_SKIPPED_REPLAY_TOTAL).increment(1);
+ return Ok(DrainOutcome::AlreadyDrained);
+ }
+
+ let old_index = PersonIndexKey {
+ partition_id,
+ team_id: team_u64,
+ person_id: old_person,
+ };
+ let lsks = store.get_person_index(&old_index)?;
+ let old_keys: Vec<Stage1Key> = lsks
+ .iter()
+ .map(|&lsk| Stage1Key {
+ partition_id,
+ team_id: team_u64,
+ leaf_state_key: lsk,
+ person_id: old_person,
+ })
+ .collect();
+ let raw = store.multi_get_stage1(&old_keys)?;
+
+ let mut present_leaves: Vec<(LeafStateKey, StatefulRecord)> = Vec::new();
+ for (&lsk, bytes) in lsks.iter().zip(raw) {
+ match bytes {
+ None => {
+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "stale_index").increment(1);
+ }
+ Some(bytes) => match StatefulRecord::decode(&bytes) {
+ Ok(record) => present_leaves.push((lsk, record)),
+ Err(_) => {
+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "decode").increment(1);
+ }
+ },
+ }
+ }
+
+ let tombstone = Tombstone {
+ new_person,
+ merged_at_ms: event.merged_at_ms,
+ };
+ let drain_stamp = DrainStamp {
+ drained_at_ms: event.merged_at_ms,
+ };
+ let tombstone_key = TombstoneKey {
+ partition_id,
+ team_id: team_u64,
+ person: old_person,
+ };
+ let old_stage2_keys: Vec<Stage2Key> = composable_cohort_ids(filters)
+ .map(|cohort_id| Stage2Key {
+ partition_id,
+ team_id: team_u64,
+ cohort_id: cohort_id.0 as u64,
+ person_id: old_person,
+ })
+ .collect();
+
+ // Same-slice assist: if P_new is itself tombstoned in *this* slice, drain straight to the live
+ // survivor, skipping a hop the apply-side resolution would otherwise take. Only the routing/apply
+ // target advances — P_old's stored tombstone still records `new_person` as the merge event gave
+ // it, so the chain stays walkable hop-by-hop.
+ let effective_new_person = match resolve(
+ store,
+ partition_id,
+ TeamId(team_id),
+ new_person,
+ partition_count,
+ )? {
+ Resolution::NotMerged => new_person,
+ Resolution::Inline { final_person, .. } => final_person,
+ Resolution::CrossPartition { target_person, .. } => target_person,
+ };
+
+ let partition_new =
+ partition_of(TeamId(team_id), &effective_new_person, partition_count) as u16;
+
+ if partition_new == partition_id {
+ return fast_path(
+ partition_id,
+ store,
+ filters,
+ event,
+ effective_new_person,
+ &drain_key,
+ &drain_stamp,
+ &tombstone_key,
+ &tombstone,
+ &old_keys,
+ &old_index,
+ &old_stage2_keys,
+ &present_leaves,
+ queue,
+ );
+ }
+
+ slow_path(
+ partition_id,
+ store,
+ event,
+ effective_new_person,
+ msg_coords,
+ &drain_key,
+ &drain_stamp,
+ &tombstone_key,
+ &tombstone,
+ &old_keys,
+ &old_index,
+ &old_stage2_keys,
+ &present_leaves,
+ queue,
+ )
+}
+
+/// Same-partition fast path: drain P_old and apply into P_new in one atomic batch.
+#[allow(clippy::too_many_arguments)]
+fn fast_path(
+ partition_id: u16,
+ store: &CohortStore,
+ filters: &TeamFilters,
+ event: &PersonMergeEvent,
+ effective_new_person: Uuid,
+ drain_key: &MergeDrainKey,
+ drain_stamp: &DrainStamp,
+ tombstone_key: &TombstoneKey,
+ tombstone: &Tombstone,
+ old_keys: &[Stage1Key],
+ old_index: &PersonIndexKey,
+ old_stage2_keys: &[Stage2Key],
+ present_leaves: &[(LeafStateKey, StatefulRecord)],
+ queue: &mut EvictionQueue<Stage1Key>,
+) -> Result<DrainOutcome, StoreError> {
+ counter!(MERGE_HANDLED_TOTAL, "path" => "same_partition").increment(1);
+
+ let team_u64 = event.team_id as u64;
+ let apply = apply_leaves(
+ partition_id,
+ store,
+ filters,
+ event.team_id,
+ event.old_person_uuid,
+ effective_new_person,
+ present_leaves,
+ )?;
+
+ let new_index = PersonIndexKey {
+ partition_id,
+ team_id: team_u64,
+ person_id: effective_new_person,
+ };
+ store.write_batch(|batch| {
+ for key in old_keys {
+ batch.delete_stage1(key);
+ }
+ batch.delete_person_index(old_index);
+ for key in old_stage2_keys {
+ batch.delete_stage2(key);
+ }
+ batch.put_tombstone(tombstone_key, &tombstone.encode());
+ batch.put_merge_drain_applied(drain_key, &drain_stamp.encode());
+ for (key, bytes) in &apply.puts {
+ batch.put_stage1(key, bytes);
+ }
+ for lsk in &apply.appends {
+ batch.merge_person_index(&new_index, IndexOp::Append(*lsk));
+ }
+ })?;
+
+ for key in old_keys {
+ queue.cancel(key);
+ }
+ for (key, deadline) in &apply.schedules {
+ queue.schedule(*key, *deadline);
+ }
+
+ Ok(DrainOutcome::FastPath {
+ transitions: apply.transitions,
+ })
+}
+
+/// Cross-partition slow path: drain P_old, stage the transfer for the caller to produce.
+#[allow(clippy::too_many_arguments)]
+fn slow_path(
+ partition_id: u16,
+ store: &CohortStore,
+ event: &PersonMergeEvent,
+ effective_new_person: Uuid,
+ msg_coords: (i32, i64),
+ drain_key: &MergeDrainKey,
+ drain_stamp: &DrainStamp,
+ tombstone_key: &TombstoneKey,
+ tombstone: &Tombstone,
+ old_keys: &[Stage1Key],
+ old_index: &PersonIndexKey,
+ old_stage2_keys: &[Stage2Key],
+ present_leaves: &[(LeafStateKey, StatefulRecord)],
+ queue: &mut EvictionQueue<Stage1Key>,
+) -> Result<DrainOutcome, StoreError> {
+ counter!(MERGE_HANDLED_TOTAL, "path" => "cross_partition").increment(1);
+
+ let team_u64 = event.team_id as u64;
+ let transfer = MergeStateTransfer {
+ team_id: event.team_id,
+ old_person_uuid: event.old_person_uuid,
+ new_person_uuid: effective_new_person,
+ merged_at_ms: event.merged_at_ms,
+ source_partition: msg_coords.0,
+ source_offset: msg_coords.1,
+ leaves: present_leaves
+ .iter()
+ .map(|(lsk, record)| TransferLeaf::new(*lsk, record.clone()))
+ .collect(),
+ forward_hops: 0,
+ };
+ // An empty transfer is never staged: a duplicate merge event at fresh coordinates could
+ // overwrite a still-pending, never-produced transfer with an empty payload.
+ let pending = (!transfer.leaves.is_empty()).then(|| PendingTransfer {
+ transfer: transfer.clone(),
+ merge_msg_partition: msg_coords.0,
+ merge_msg_offset: msg_coords.1,
+ });
+ let pending_key = PendingTransferKey {
+ partition_id,
+ team_id: team_u64,
+ old_person: event.old_person_uuid,
+ };
+
+ store.write_batch(|batch| {
+ if let Some(pending) = &pending {
+ batch.put_pending_transfer(&pending_key, &pending.encode());
+ }
+ batch.put_merge_drain_applied(drain_key, &drain_stamp.encode());
+ for key in old_keys {
+ batch.delete_stage1(key);
+ }
+ batch.delete_person_index(old_index);
+ for key in old_stage2_keys {
+ batch.delete_stage2(key);
+ }
+ batch.put_tombstone(tombstone_key, &tombstone.encode());
+ })?;
+
+ for key in old_keys {
+ queue.cancel(key);
+ }
+
+ Ok(DrainOutcome::Drained { transfer })
+}
+
+/// The team's cohort ids that write `cf_stage2` rows (both composable classes). See
+/// [`writes_cf_stage2`](crate::stage2::CohortEligibility::writes_cf_stage2).
+fn composable_cohort_ids(filters: &TeamFilters) -> impl Iterator<Item = CohortId> + '_ {
+ filters
+ .eligibility
+ .iter()
+ .filter_map(|(&cohort_id, eligibility)| eligibility.writes_cf_stage2().then_some(cohort_id))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::UTC;
+ use serde_json::{json, Value};
+
+ use crate::filters::TeamFiltersBuilder;
+ use crate::stage2::CohortEligibility;
+
+ fn behavioral(time_value: i64) -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": time_value, "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn person() -> Value {
+ json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+ }
+
+ fn cohort_ref(target: i32) -> Value {
+ json!({ "type": "cohort", "value": target, "negation": false })
+ }
+
+ fn cohort(values: Vec<Value>) -> Value {
+ json!({ "properties": { "type": "AND", "values": values } })
+ }
+
+ #[test]
+ fn composable_cohort_ids_enumerates_both_composable_classes_for_row_deletion() {
+ let mut builder = TeamFiltersBuilder::default();
+ // 2: single-leaf referent — does NOT write cf_stage2.
+ builder
+ .add_cohort(CohortId(2), TeamId(7), &cohort(vec![behavioral(7)]))
+ .unwrap();
+ // 1: own leaf + ref to 2 → Stage2ComposableRef — writes cf_stage2.
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &cohort(vec![person(), cohort_ref(2)]),
+ )
+ .unwrap();
+ // 3: plain composable — writes cf_stage2.
+ builder
+ .add_cohort(
+ CohortId(3),
+ TeamId(7),
+ &cohort(vec![behavioral(7), person()]),
+ )
+ .unwrap();
+ let filters = builder.freeze_with(UTC, true);
+
+ assert_eq!(
+ filters.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2ComposableRef,
+ );
+ let mut ids: Vec<i32> = composable_cohort_ids(&filters).map(|c| c.0).collect();
+ ids.sort_unstable();
+ assert_eq!(
+ ids,
+ vec![1, 3],
+ "a Stage2ComposableRef writer is enumerated alongside Stage2Composable; the SingleLeaf referent is not",
+ );
+ }
+
+ #[test]
+ fn composable_cohort_ids_gate_off_drops_the_still_excluded_ref_cohort() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(2), TeamId(7), &cohort(vec![behavioral(7)]))
+ .unwrap();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &cohort(vec![person(), cohort_ref(2)]),
+ )
+ .unwrap();
+ let filters = builder.freeze_with(UTC, false);
+
+ let ids: Vec<i32> = composable_cohort_ids(&filters).map(|c| c.0).collect();
+ assert!(
+ ids.is_empty(),
+ "gate off keeps the ref cohort Excluded(HasCohortRef), which writes no cf_stage2 row",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/merge/gc.rs b/rust/cohort-stream-processor/src/merge/gc.rs
new file mode 100644
index 000000000000..090a5e39418f
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/gc.rs
@@ -0,0 +1,149 @@
+//! Periodic merge-CF garbage-collection tick.
+//!
+//! Each tick reads the clock once, derives the marker/tombstone cutoffs (`now − retention`), and
+//! routes one `MergeCfGc` to every owned partition's worker. Computing the cutoffs here — not in the
+//! worker — keeps the worker clock-free, like [`DispatchSweeper`](crate::sweep::DispatchSweeper)'s
+//! `due_before_ms`.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use chrono::Utc;
+
+use crate::consumers::events::EventDispatcher;
+use crate::sweep::Sweeper;
+
+type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
+
+/// A [`Sweeper`] that routes a merge-CF GC tick to every owned partition each cycle.
+///
+/// Holds the two retention floors (marker / tombstone). On each tick it reads the clock once and
+/// derives `now − retention` cutoffs, so a single tick uses one consistent `now` across all CFs.
+#[derive(Clone)]
+pub struct MergeGcSweeper {
+ dispatcher: Arc<EventDispatcher>,
+ marker_retention_ms: i64,
+ tombstone_retention_ms: i64,
+ now_ms: Clock,
+}
+
+impl MergeGcSweeper {
+ pub fn new(
+ dispatcher: Arc<EventDispatcher>,
+ marker_retention_ms: i64,
+ tombstone_retention_ms: i64,
+ ) -> Self {
+ Self::with_clock(
+ dispatcher,
+ marker_retention_ms,
+ tombstone_retention_ms,
+ Arc::new(|| Utc::now().timestamp_millis()),
+ )
+ }
+
+ pub fn with_clock(
+ dispatcher: Arc<EventDispatcher>,
+ marker_retention_ms: i64,
+ tombstone_retention_ms: i64,
+ now_ms: Clock,
+ ) -> Self {
+ Self {
+ dispatcher,
+ marker_retention_ms,
+ tombstone_retention_ms,
+ now_ms,
+ }
+ }
+
+ /// `(marker_cutoff_ms, tombstone_cutoff_ms)` for `now`. `saturating_sub` keeps it total: a clock
+ /// with `now < retention` yields a far-negative cutoff — below every real timestamp, i.e.
+ /// "nothing expired" (the safe direction) — rather than overflowing.
+ fn cutoffs(&self, now_ms: i64) -> (i64, i64) {
+ (
+ now_ms.saturating_sub(self.marker_retention_ms),
+ now_ms.saturating_sub(self.tombstone_retention_ms),
+ )
+ }
+}
+
+#[async_trait]
+impl Sweeper for MergeGcSweeper {
+ async fn run_once(&self) {
+ let (marker_cutoff_ms, tombstone_cutoff_ms) = self.cutoffs((self.now_ms)());
+ self.dispatcher
+ .route_merge_gc(marker_cutoff_ms, tombstone_cutoff_ms)
+ .await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ use crate::filters::{CatalogHandle, FilterCatalog};
+ use crate::partitions::{OffsetTracker, PartitionRouter};
+ use crate::producer::{CaptureSink, MembershipSink};
+ use crate::store::{CohortStore, StoreConfig};
+ use crate::workers::MergeWorkerDeps;
+
+ fn dispatcher() -> (TempDir, Arc<EventDispatcher>) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])));
+ let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
+ let dispatcher = EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store,
+ catalog,
+ sink,
+ MergeWorkerDeps::capture(),
+ );
+ (dir, Arc::new(dispatcher))
+ }
+
+ #[test]
+ fn cutoffs_subtract_each_retention_floor_from_now() {
+ let (_dir, dispatcher) = dispatcher();
+ let sweeper = MergeGcSweeper::new(dispatcher, 1_000, 3_000);
+ assert_eq!(sweeper.cutoffs(10_000), (9_000, 7_000));
+ }
+
+ #[test]
+ fn cutoffs_saturate_when_retention_exceeds_now() {
+ let (_dir, dispatcher) = dispatcher();
+ let sweeper = MergeGcSweeper::new(dispatcher, i64::MAX, i64::MAX);
+ let (marker, tombstone) = sweeper.cutoffs(0);
+ assert!(
+ marker < 0 && tombstone < 0,
+ "far-negative = nothing expired"
+ );
+ }
+
+ #[tokio::test]
+ async fn run_once_routes_to_owned_partitions_without_panicking() {
+ let (_dir, dispatcher) = dispatcher();
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+
+ let sweeper = MergeGcSweeper::with_clock(
+ dispatcher.clone(),
+ 1_000,
+ 3_000,
+ Arc::new(|| 1_700_000_000_000),
+ );
+ sweeper.run_once().await;
+ }
+
+ #[tokio::test]
+ async fn run_once_with_no_owned_partitions_is_a_noop() {
+ let (_dir, dispatcher) = dispatcher();
+ let sweeper = MergeGcSweeper::new(dispatcher, 1_000, 3_000);
+ sweeper.run_once().await;
+ }
+}
diff --git a/rust/cohort-stream-processor/src/merge/mod.rs b/rust/cohort-stream-processor/src/merge/mod.rs
new file mode 100644
index 000000000000..467200673f00
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/mod.rs
@@ -0,0 +1,11 @@
+//! Cross-partition person-merge protocol: migrate per-leaf state from one person to another.
+
+pub mod apply_handler;
+pub mod bucket_align;
+pub mod compressed_concat;
+pub mod drain_handler;
+pub mod gc;
+pub mod redrive;
+pub mod rules;
+pub mod tombstone_redirect;
+pub mod transfer;
diff --git a/rust/cohort-stream-processor/src/merge/redrive.rs b/rust/cohort-stream-processor/src/merge/redrive.rs
new file mode 100644
index 000000000000..951d6e518622
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/redrive.rs
@@ -0,0 +1,79 @@
+//! Periodic pending-transfer redrive tick.
+//!
+//! Each tick routes a `RedrivePendingTransfers` to every owned partition's worker, which
+//! re-produces any `cf_pending_transfers` entries stranded by inline-retry exhaustion.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+
+use crate::consumers::events::EventDispatcher;
+use crate::sweep::Sweeper;
+
+/// A [`Sweeper`] that routes a redrive tick to every owned partition each cycle.
+pub struct RedriveSweeper {
+ dispatcher: Arc<EventDispatcher>,
+}
+
+impl RedriveSweeper {
+ pub fn new(dispatcher: Arc<EventDispatcher>) -> Self {
+ Self { dispatcher }
+ }
+}
+
+#[async_trait]
+impl Sweeper for RedriveSweeper {
+ async fn run_once(&self) {
+ self.dispatcher.route_redrive().await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ use crate::consumers::events::EventDispatcher;
+ use crate::filters::{CatalogHandle, FilterCatalog};
+ use crate::partitions::{OffsetTracker, PartitionRouter};
+ use crate::producer::{CaptureSink, MembershipSink};
+ use crate::store::{CohortStore, StoreConfig};
+ use crate::workers::MergeWorkerDeps;
+
+ fn dispatcher() -> (TempDir, Arc<EventDispatcher>) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])));
+ let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
+ let dispatcher = EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store,
+ catalog,
+ sink,
+ MergeWorkerDeps::capture(),
+ );
+ (dir, Arc::new(dispatcher))
+ }
+
+ #[tokio::test]
+ async fn run_once_routes_to_owned_partitions_without_panicking() {
+ let (_dir, dispatcher) = dispatcher();
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+
+ let sweeper = RedriveSweeper::new(dispatcher.clone());
+ sweeper.run_once().await;
+ }
+
+ #[tokio::test]
+ async fn run_once_with_no_owned_partitions_is_a_noop() {
+ let (_dir, dispatcher) = dispatcher();
+ let sweeper = RedriveSweeper::new(dispatcher);
+ sweeper.run_once().await;
+ }
+}
diff --git a/rust/cohort-stream-processor/src/merge/rules.rs b/rust/cohort-stream-processor/src/merge/rules.rs
new file mode 100644
index 000000000000..58ed9f3d9ce7
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/rules.rs
@@ -0,0 +1,663 @@
+//! Per-leaf merge rules: combine P_old's and P_new's state for one `LeafStateKey`.
+//!
+//! Given both sides' [`StatefulRecord`]s and the leaf's catalog meta, produces the merged record to
+//! persist for P_new plus the membership flip it implies.
+
+use std::collections::BTreeMap;
+
+use chrono_tz::Tz;
+use metrics::counter;
+use uuid::Uuid;
+
+use crate::filters::reverse_index::LeafStateMeta;
+use crate::merge::bucket_align::align_and_sum;
+use crate::merge::compressed_concat::union_by_day;
+use crate::observability::metrics::MERGE_LEAVES_DROPPED_TOTAL;
+use crate::stage1::bucket_tz::{daily_bucket_len, now_day_for_window};
+use crate::stage1::compressed_history::{compressed_eviction_deadline, slide_window_forward};
+use crate::stage1::daily::daily_eviction_deadline;
+use crate::stage1::state::{AppliedOffsets, Stage1State, StateVariant, StatefulRecord};
+use crate::stage1::transition::TransitionKind;
+use crate::stage2::evaluator::leaf_membership;
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct MergedRecord {
+ /// The merged record to write for P_new, or `None` to leave the leaf absent (e.g. a
+ /// person-property leaf P_new never had, which will be re-evaluated on P_new's next event).
+ pub record: Option<StatefulRecord>,
+ /// Membership flip if the merge crossed the predicate threshold.
+ pub flip: Option<TransitionKind>,
+}
+
+/// Merge P_old's leaf state into P_new's for one `LeafStateKey`.
+///
+/// The merged record keeps P_new's `applied_offsets` (never seeded from P_old) and gains a
+/// `redirect_dedup` entry per ancestor so post-merge stragglers stay replay-safe.
+pub fn merge_records(
+ old_person: Uuid,
+ old: &StatefulRecord,
+ new: Option<&StatefulRecord>,
+ meta: &LeafStateMeta,
+ tz: Tz,
+) -> MergedRecord {
+ // Variant mismatch is a desync — keep P_new untouched.
+ if old.state.variant() != meta.variant
+ || new.is_some_and(|record| record.state.variant() != meta.variant)
+ {
+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "variant_mismatch").increment(1);
+ return keep_new(old_person, old, new);
+ }
+
+ // Person properties: drop P_old's bit; P_new re-evaluates lazily on its next event.
+ if matches!(meta.variant, StateVariant::PersonProperty) {
+ return keep_new(old_person, old, new);
+ }
+
+ let merged_state = match new {
+ None => old.state.clone(),
+ Some(new_record) => match merge_behavioral_pair(meta, &old.state, &new_record.state, tz) {
+ Some(state) => state,
+ None => {
+ counter!(MERGE_LEAVES_DROPPED_TOTAL, "reason" => "length_desync").increment(1);
+ return keep_new(old_person, old, new);
+ }
+ },
+ };
+
+ let prev_member = leaf_membership(new.map(|record| &record.state), meta);
+ let next_member = leaf_membership(Some(&merged_state), meta);
+
+ let applied_offsets = new
+ .map(|record| record.applied_offsets.clone())
+ .unwrap_or_default();
+ let mut redirect_dedup = new
+ .map(|record| record.redirect_dedup.clone())
+ .unwrap_or_default();
+ compose_ancestor_dedup(&mut redirect_dedup, old_person, old);
+
+ MergedRecord {
+ record: Some(StatefulRecord {
+ state: merged_state,
+ applied_offsets,
+ redirect_dedup,
+ }),
+ flip: flip_of(prev_member, next_member),
+ }
+}
+
+/// Keep P_new's record unchanged (composing the ancestor dedup), or write nothing when P_new had no
+/// record.
+fn keep_new(old_person: Uuid, old: &StatefulRecord, new: Option<&StatefulRecord>) -> MergedRecord {
+ let record = new.cloned().map(|mut record| {
+ compose_ancestor_dedup(&mut record.redirect_dedup, old_person, old);
+ record
+ });
+ MergedRecord { record, flip: None }
+}
+
+/// Fold P_old's offsets into `redirect_dedup`. P_old becomes an ancestor under its own uuid; its own
+/// ancestors carry forward under their original origins (keyed, not unioned).
+fn compose_ancestor_dedup(
+ redirect_dedup: &mut BTreeMap<Uuid, AppliedOffsets>,
+ old_person: Uuid,
+ old: &StatefulRecord,
+) {
+ redirect_dedup
+ .entry(old_person)
+ .or_default()
+ .merge_max(&old.applied_offsets);
+ for (ancestor, offsets) in &old.redirect_dedup {
+ redirect_dedup
+ .entry(*ancestor)
+ .or_default()
+ .merge_max(offsets);
+ }
+}
+
+/// Merge two same-variant behavioral states (both present). Returns `None` on a structural desync
+/// (e.g. daily array length disagreeing with the window).
+fn merge_behavioral_pair(
+ meta: &LeafStateMeta,
+ old: &Stage1State,
+ new: &Stage1State,
+ tz: Tz,
+) -> Option<Stage1State> {
+ match (old, new) {
+ (
+ Stage1State::BehavioralSingle {
+ last_event_at_ms: old_last,
+ earliest_eviction_at_ms: old_deadline,
+ ..
+ },
+ Stage1State::BehavioralSingle {
+ last_event_at_ms: new_last,
+ earliest_eviction_at_ms: new_deadline,
+ ..
+ },
+ ) => Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: (*old_last).max(*new_last),
+ earliest_eviction_at_ms: (*old_deadline).max(*new_deadline),
+ }),
+
+ (
+ Stage1State::BehavioralDailyBuckets {
+ buckets: old_buckets,
+ window_start_day: old_start,
+ last_event_at_ms: old_last,
+ ..
+ },
+ Stage1State::BehavioralDailyBuckets {
+ buckets: new_buckets,
+ window_start_day: new_start,
+ last_event_at_ms: new_last,
+ ..
+ },
+ ) => {
+ let window_days = meta
+ .window_days
+ .unwrap_or_else(|| old_buckets.len().saturating_sub(1) as u32);
+ let expected_len = daily_bucket_len(window_days);
+ if old_buckets.len() != expected_len || new_buckets.len() != expected_len {
+ return None;
+ }
+ let (buckets, window_start_day) = align_and_sum(
+ old_buckets,
+ *old_start,
+ new_buckets,
+ *new_start,
+ window_days,
+ );
+ let earliest_eviction_at_ms =
+ daily_eviction_deadline(&buckets, window_start_day, window_days, tz);
+ Some(Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day,
+ last_event_at_ms: (*old_last).max(*new_last),
+ earliest_eviction_at_ms,
+ })
+ }
+
+ (
+ Stage1State::BehavioralCompressedHistory {
+ entries: old_entries,
+ window_start_day: old_start,
+ last_event_at_ms: old_last,
+ ..
+ },
+ Stage1State::BehavioralCompressedHistory {
+ entries: new_entries,
+ window_start_day: new_start,
+ last_event_at_ms: new_last,
+ ..
+ },
+ ) => {
+ // The merged state is evaluated immediately by `compressed_predicate`, which sums every
+ // entry with no window bound. Slide both sides to the merged anchor (the more-recent of
+ // the two starts) first so out-of-window entries are dropped before the union — mirroring
+ // the daily arm's `align_and_sum`. Without this the count is inflated until the next sweep.
+ let (entries, window_start_day) = match meta.window_days {
+ Some(window_days) => {
+ let target_now_day =
+ now_day_for_window((*old_start).max(*new_start), window_days);
+ let mut old_entries = old_entries.clone();
+ let mut old_start = *old_start;
+ slide_window_forward(
+ &mut old_entries,
+ &mut old_start,
+ window_days,
+ target_now_day,
+ );
+ let mut new_entries = new_entries.clone();
+ let mut new_start = *new_start;
+ slide_window_forward(
+ &mut new_entries,
+ &mut new_start,
+ window_days,
+ target_now_day,
+ );
+ union_by_day(&old_entries, old_start, &new_entries, new_start)
+ }
+ // Meta desync (no finite window to slide to): union as-is.
+ None => union_by_day(old_entries, *old_start, new_entries, *new_start),
+ };
+ let earliest_eviction_at_ms = match meta.window_days {
+ Some(window_days) => compressed_eviction_deadline(&entries, window_days, tz),
+ // Meta desync: fail safe (never evict); next event-path fold recomputes.
+ None => i64::MAX,
+ };
+ Some(Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day,
+ last_event_at_ms: (*old_last).max(*new_last),
+ earliest_eviction_at_ms,
+ })
+ }
+
+ _ => Some(new.clone()),
+ }
+}
+
+fn flip_of(prev_member: bool, next_member: bool) -> Option<TransitionKind> {
+ match (prev_member, next_member) {
+ (false, true) => Some(TransitionKind::Entered),
+ (true, false) => Some(TransitionKind::Left),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::UTC;
+
+ use crate::stage1::pick_state::{EvictionWindow, PredicateOp};
+ use crate::stage1::predicate::compressed_predicate;
+
+ const TZ: Tz = UTC;
+
+ fn uuid(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+ }
+
+ fn single_meta() -> LeafStateMeta {
+ LeafStateMeta {
+ variant: StateVariant::BehavioralSingle,
+ condition_hash: [0; 16],
+ window: Some(EvictionWindow::RelativeDays { days: 7 }),
+ window_days: None,
+ predicate_op: None,
+ }
+ }
+
+ fn daily_meta(window_days: u32, op: PredicateOp) -> LeafStateMeta {
+ LeafStateMeta {
+ variant: StateVariant::BehavioralDailyBuckets,
+ condition_hash: [0; 16],
+ window: None,
+ window_days: Some(window_days),
+ predicate_op: Some(op),
+ }
+ }
+
+ fn compressed_meta(window_days: u32, op: PredicateOp) -> LeafStateMeta {
+ LeafStateMeta {
+ variant: StateVariant::BehavioralCompressedHistory,
+ window_days: Some(window_days),
+ predicate_op: Some(op),
+ ..single_meta()
+ }
+ }
+
+ fn person_meta() -> LeafStateMeta {
+ LeafStateMeta {
+ variant: StateVariant::PersonProperty,
+ condition_hash: [0; 16],
+ window: None,
+ window_days: None,
+ predicate_op: None,
+ }
+ }
+
+ fn single(last: i64, deadline: i64) -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: last,
+ earliest_eviction_at_ms: deadline,
+ },
+ AppliedOffsets::default(),
+ )
+ }
+
+ fn daily(buckets: Vec<u32>, window_start_day: i32) -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day,
+ last_event_at_ms: 1_000,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ AppliedOffsets::default(),
+ )
+ }
+
+ fn compressed(entries: Vec<(i32, u32)>, window_start_day: i32) -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day,
+ last_event_at_ms: 1_000,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ AppliedOffsets::default(),
+ )
+ }
+
+ fn person(matches: bool, last: i64) -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::PersonProperty {
+ matches,
+ last_updated_at_ms: last,
+ last_updated_offset: 0,
+ },
+ AppliedOffsets::default(),
+ )
+ }
+
+ fn applied(entries: &[(i32, i64)]) -> AppliedOffsets {
+ let mut applied = AppliedOffsets::default();
+ for &(partition, offset) in entries {
+ applied.record(partition, offset);
+ }
+ applied
+ }
+
+ #[test]
+ fn single_ors_match_and_maxes_the_deadline() {
+ let merged = merge_records(
+ uuid(1),
+ &single(100, 500),
+ Some(&single(200, 400)),
+ &single_meta(),
+ TZ,
+ );
+ match merged.record.unwrap().state {
+ Stage1State::BehavioralSingle {
+ has_match,
+ last_event_at_ms,
+ earliest_eviction_at_ms,
+ } => {
+ assert!(has_match);
+ assert_eq!(last_event_at_ms, 200, "max of the two last-event times");
+ assert_eq!(earliest_eviction_at_ms, 500, "longest-surviving deadline");
+ }
+ other => panic!("expected single, got {other:?}"),
+ }
+ assert_eq!(merged.flip, None, "both sides were already members");
+ }
+
+ #[test]
+ fn single_into_absent_new_migrates_and_enters() {
+ let merged = merge_records(uuid(1), &single(100, 500), None, &single_meta(), TZ);
+ assert_eq!(
+ merged.flip,
+ Some(TransitionKind::Entered),
+ "P_new had no single, so inheriting P_old's makes it a member",
+ );
+ assert!(matches!(
+ merged.record.unwrap().state,
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ }
+ ));
+ }
+
+ #[test]
+ fn daily_aligns_and_sums_per_the_worked_example() {
+ let meta = daily_meta(6, PredicateOp::Gte(1));
+ let merged = merge_records(
+ uuid(1),
+ &daily(vec![2, 0, 1, 3, 0, 1, 5], 19_500),
+ Some(&daily(vec![0, 1, 2, 0, 1, 0, 4], 19_501)),
+ &meta,
+ TZ,
+ );
+ match merged.record.unwrap().state {
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day,
+ ..
+ } => {
+ assert_eq!(buckets, vec![0, 2, 5, 0, 2, 5, 4]);
+ assert_eq!(window_start_day, 19_501);
+ }
+ other => panic!("expected daily, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn daily_count_crossing_the_threshold_enters() {
+ let meta = daily_meta(2, PredicateOp::Gte(3));
+ let merged = merge_records(
+ uuid(1),
+ &daily(vec![0, 0, 2], 100),
+ Some(&daily(vec![0, 0, 1], 100)),
+ &meta,
+ TZ,
+ );
+ assert_eq!(merged.flip, Some(TransitionKind::Entered));
+ match merged.record.unwrap().state {
+ Stage1State::BehavioralDailyBuckets { buckets, .. } => {
+ assert_eq!(buckets, vec![0, 0, 3])
+ }
+ other => panic!("expected daily, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn daily_length_desync_keeps_new() {
+ let meta = daily_meta(7, PredicateOp::Gte(1));
+ let old = daily(vec![1, 2, 3], 100);
+ let new = daily(vec![0u32; 8], 100);
+ let merged = merge_records(uuid(1), &old, Some(&new), &meta, TZ);
+ assert_eq!(merged.flip, None);
+ match merged.record.unwrap().state {
+ Stage1State::BehavioralDailyBuckets { buckets, .. } => {
+ assert_eq!(buckets.len(), 8, "kept P_new's well-formed array")
+ }
+ other => panic!("expected daily, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn compressed_unions_by_day_and_sums_shared_days() {
+ let meta = compressed_meta(365, PredicateOp::Gte(1));
+ let merged = merge_records(
+ uuid(1),
+ &compressed(vec![(100, 2), (200, 1)], 50),
+ Some(&compressed(vec![(150, 3), (200, 4)], 60)),
+ &meta,
+ TZ,
+ );
+ match merged.record.unwrap().state {
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day,
+ ..
+ } => {
+ assert_eq!(entries, vec![(100, 2), (150, 3), (200, 5)]);
+ assert_eq!(window_start_day, 60, "the more recent anchor");
+ }
+ other => panic!("expected compressed, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn compressed_drops_entries_below_the_merged_anchor_before_counting() {
+ // Old is anchored older (start 0, window 10 ⇒ window [0..=10]) with a heavy day-4 entry that
+ // is in-window for old but falls below the merged anchor (5, the more-recent/new start). New
+ // (start 5, window [5..=15]) has a light day-12 entry. The merge is evaluated immediately, so
+ // the day-4 entry must be sliced out before the union — otherwise its count inflates the sum.
+ let op = PredicateOp::Gte(6);
+ let meta = compressed_meta(10, op);
+ let merged = merge_records(
+ uuid(1),
+ &compressed(vec![(4, 5), (8, 1)], 0),
+ Some(&compressed(vec![(12, 1)], 5)),
+ &meta,
+ TZ,
+ );
+ match &merged.record.as_ref().unwrap().state {
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day,
+ ..
+ } => {
+ assert_eq!(
+ *entries,
+ vec![(8, 1), (12, 1)],
+ "the day-4 entry is below the merged anchor (5) and is dropped",
+ );
+ assert_eq!(*window_start_day, 5, "the more recent anchor");
+ // Sum over the in-window entries is 2; the dropped day-4 (count 5) does not push it to
+ // the Gte(6) threshold. Without the slide the entries would be [(4,5),(8,1),(12,1)],
+ // sum 7 ≥ 6 ⇒ a (wrong) member.
+ assert!(
+ !compressed_predicate(entries, op),
+ "the out-of-window day-4 count must not contribute to membership",
+ );
+ }
+ other => panic!("expected compressed, got {other:?}"),
+ }
+ assert_eq!(
+ merged.flip, None,
+ "new alone (count 1) was not a member and the slid merge (count 2) is still under Gte(6)",
+ );
+ }
+
+ #[test]
+ fn compressed_window_days_desync_fails_safe_to_never_evict() {
+ let meta = LeafStateMeta {
+ variant: StateVariant::BehavioralCompressedHistory,
+ window_days: None,
+ predicate_op: Some(PredicateOp::Gte(1)),
+ ..single_meta()
+ };
+ let merged = merge_records(
+ uuid(1),
+ &compressed(vec![(100, 2), (200, 1)], 50),
+ Some(&compressed(vec![(150, 3)], 60)),
+ &meta,
+ TZ,
+ )
+ .record
+ .unwrap();
+ match merged.state {
+ Stage1State::BehavioralCompressedHistory {
+ earliest_eviction_at_ms,
+ ..
+ } => assert_eq!(
+ earliest_eviction_at_ms,
+ i64::MAX,
+ "window_days desync fails safe to never-evict",
+ ),
+ other => panic!("expected compressed, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn person_property_keeps_new_and_drops_old() {
+ let merged = merge_records(
+ uuid(1),
+ &person(true, 100),
+ Some(&person(false, 200)),
+ &person_meta(),
+ TZ,
+ );
+ assert_eq!(merged.flip, None);
+ assert!(matches!(
+ merged.record.unwrap().state,
+ Stage1State::PersonProperty { matches: false, .. }
+ ));
+ }
+
+ #[test]
+ fn person_property_with_absent_new_writes_nothing() {
+ let merged = merge_records(uuid(1), &person(true, 100), None, &person_meta(), TZ);
+ assert_eq!(merged.record, None, "no state migrated for P_new");
+ assert_eq!(merged.flip, None);
+ }
+
+ #[test]
+ fn merged_record_keeps_p_news_main_map_and_adds_an_ancestor_entry() {
+ let mut old = single(100, 500);
+ old.applied_offsets = applied(&[(5, 100), (6, 7)]);
+ let mut new = single(200, 400);
+ new.applied_offsets = applied(&[(5, 50)]);
+
+ let merged = merge_records(uuid(0xA11CE), &old, Some(&new), &single_meta(), TZ)
+ .record
+ .unwrap();
+ assert!(merged.applied_offsets.is_replay(5, 50));
+ assert!(!merged.applied_offsets.is_replay(5, 51));
+ let ancestor = &merged.redirect_dedup[&uuid(0xA11CE)];
+ assert!(ancestor.is_replay(5, 100) && ancestor.is_replay(6, 7));
+ assert!(!ancestor.is_replay(5, 101));
+ }
+
+ #[test]
+ fn chained_merge_carries_grandparent_ancestry_keyed() {
+ let grandparent = uuid(0x6172);
+ let p_old = uuid(0xA11CE);
+ let mut old = single(100, 500);
+ old.applied_offsets = applied(&[(5, 100)]);
+ old.redirect_dedup.insert(grandparent, applied(&[(9, 42)]));
+
+ let new = single(200, 400);
+ let merged = merge_records(p_old, &old, Some(&new), &single_meta(), TZ)
+ .record
+ .unwrap();
+ assert!(
+ merged.redirect_dedup[&p_old].is_replay(5, 100),
+ "P_old is an ancestor under its own uuid",
+ );
+ assert!(
+ merged.redirect_dedup[&grandparent].is_replay(9, 42),
+ "P_old's own ancestor carries forward under the grandparent's origin",
+ );
+ }
+
+ #[test]
+ fn variant_mismatch_keeps_new_defensively() {
+ let merged = merge_records(
+ uuid(1),
+ &person(true, 100),
+ Some(&single(200, 400)),
+ &single_meta(),
+ TZ,
+ );
+ assert_eq!(merged.flip, None);
+ assert!(
+ matches!(
+ merged.record.unwrap().state,
+ Stage1State::BehavioralSingle { .. }
+ ),
+ "P_new's single is kept; P_old's mismatched state is not migrated",
+ );
+ }
+
+ #[test]
+ fn single_merge_then_fold_equals_fold_then_merge() {
+ let old = single(100, 500);
+ let new = single(200, 400);
+
+ let merged = merge_records(uuid(1), &old, Some(&new), &single_meta(), TZ)
+ .record
+ .unwrap();
+ let (m_match, m_last) = match merged.state {
+ Stage1State::BehavioralSingle {
+ has_match,
+ last_event_at_ms,
+ ..
+ } => (has_match, last_event_at_ms.max(300)),
+ other => panic!("expected single, got {other:?}"),
+ };
+
+ let new_folded = single(300, 400);
+ let merged2 = merge_records(uuid(1), &old, Some(&new_folded), &single_meta(), TZ)
+ .record
+ .unwrap();
+ let (f_match, f_last) = match merged2.state {
+ Stage1State::BehavioralSingle {
+ has_match,
+ last_event_at_ms,
+ ..
+ } => (has_match, last_event_at_ms),
+ other => panic!("expected single, got {other:?}"),
+ };
+
+ assert_eq!((m_match, m_last), (f_match, f_last));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs b/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs
new file mode 100644
index 000000000000..af9023bbfc92
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/tombstone_redirect.rs
@@ -0,0 +1,318 @@
+//! Tombstone redirect for post-merge straggler events.
+//!
+//! After a merge, P_old's state rows are gone but a `cf_merge_tombstones` entry records
+//! `P_old -> P_new`. A straggler event for P_old resolves through the tombstone chain to the
+//! person it should fold into.
+//!
+//! [`resolve`] follows same-partition tombstone hops in process, stopping at the first hop that
+//! lands on a different partition (re-keyed and re-produced). The chain `origin` is always the
+//! straggler's own person id, since it keys into `redirect_dedup`.
+
+use metrics::counter;
+use tracing::{debug, warn};
+use uuid::Uuid;
+
+use crate::filters::TeamId;
+use crate::merge::transfer::Tombstone;
+use crate::observability::metrics::MERGE_TOMBSTONE_REDIRECTS_TOTAL;
+use crate::partitions::partitioner::partition_of;
+use crate::store::{CohortStore, StoreError, TombstoneKey};
+
+/// Defensive bound on same-partition tombstone hops in one [`resolve`] call.
+const MAX_TOMBSTONE_HOPS: usize = 16;
+
+/// Bound on cross-partition re-produce hops (`redirect_hops` on the wire). Prevents infinite
+/// re-production between partitions in case of a corrupt cross-partition tombstone cycle.
+pub(crate) const MAX_CROSS_PARTITION_REDIRECT_HOPS: u8 = 8;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Resolution {
+ /// No tombstone -- process the event normally.
+ NotMerged,
+ /// Chain resolves to `final_person` on this partition. Process inline with `origin` as the
+ /// dedup key into `redirect_dedup`.
+ Inline { final_person: Uuid, origin: Uuid },
+ /// Chain reaches `target_person` on a different partition. Re-key and re-produce.
+ CrossPartition { target_person: Uuid, origin: Uuid },
+}
+
+/// Resolve a straggler event's person through the tombstone chain.
+///
+/// `partition_count` is the live co-partitioned topic count (production 64; test lanes lower it):
+/// a cross-partition hop is decided by whether the next person hashes off `partition_id` under
+/// this count, so it must match the deploy's topology, not a literal.
+pub fn resolve(
+ store: &CohortStore,
+ partition_id: u16,
+ team_id: TeamId,
+ person: Uuid,
+ partition_count: u32,
+) -> Result<Resolution, StoreError> {
+ let team = team_id.0 as u64;
+
+ let Some(first) = read_tombstone(store, partition_id, team, person)? else {
+ return Ok(Resolution::NotMerged);
+ };
+
+ let origin = person;
+ let mut current = first.new_person;
+
+ for _hop in 0..MAX_TOMBSTONE_HOPS {
+ let current_partition = partition_of(team_id, &current, partition_count);
+ if current_partition as u16 != partition_id {
+ return Ok(Resolution::CrossPartition {
+ target_person: current,
+ origin,
+ });
+ }
+ match read_tombstone(store, partition_id, team, current)? {
+ Some(next) => current = next.new_person,
+ None => {
+ return Ok(Resolution::Inline {
+ final_person: current,
+ origin,
+ })
+ }
+ }
+ }
+
+ warn!(
+ partition_id,
+ team_id = team_id.0,
+ %origin,
+ %current,
+ "tombstone chain exceeded the hop cap; resolving inline to the last hop",
+ );
+ Ok(Resolution::Inline {
+ final_person: current,
+ origin,
+ })
+}
+
+/// Read and decode one tombstone, or `None` when absent or corrupt.
+fn read_tombstone(
+ store: &CohortStore,
+ partition_id: u16,
+ team: u64,
+ person: Uuid,
+) -> Result<Option<Tombstone>, StoreError> {
+ let key = TombstoneKey {
+ partition_id,
+ team_id: team,
+ person,
+ };
+ let Some(bytes) = store.get_tombstone(&key)? else {
+ return Ok(None);
+ };
+ match Tombstone::decode(&bytes) {
+ Ok(tombstone) => Ok(Some(tombstone)),
+ Err(error) => {
+ debug!(partition_id, %person, error = %error, "corrupt tombstone; treating as not merged");
+ Ok(None)
+ }
+ }
+}
+
+/// Record an inline redirect metric. Cross-partition redirects are counted separately via
+/// [`record_re_keyed`] after the re-produce ack.
+pub fn record_redirect(resolution: &Resolution) {
+ match resolution {
+ Resolution::NotMerged | Resolution::CrossPartition { .. } => {}
+ Resolution::Inline { .. } => {
+ counter!(MERGE_TOMBSTONE_REDIRECTS_TOTAL, "path" => "inline").increment(1);
+ }
+ }
+}
+
+/// Record `count` cross-partition redirects (called after the re-produce ack).
+pub fn record_re_keyed(count: u64) {
+ if count > 0 {
+ counter!(MERGE_TOMBSTONE_REDIRECTS_TOTAL, "path" => "re_keyed").increment(count);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ use crate::merge::transfer::Tombstone;
+ use crate::partitions::partitioner::COHORT_PARTITION_COUNT;
+ use crate::store::StoreConfig;
+
+ const TEAM: TeamId = TeamId(7);
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ fn partition(person: Uuid) -> u16 {
+ partition_of(TEAM, &person, COHORT_PARTITION_COUNT) as u16
+ }
+
+ /// Find a UUID that hashes to `target` partition.
+ fn person_on(target: u16) -> Uuid {
+ (1u128..)
+ .map(Uuid::from_u128)
+ .find(|p| partition(*p) == target)
+ .expect("some uuid hashes to the target partition")
+ }
+
+ /// Find a UUID that hashes to any partition except `avoid`.
+ fn person_not_on(avoid: u16) -> Uuid {
+ (1u128..)
+ .map(Uuid::from_u128)
+ .find(|p| partition(*p) != avoid)
+ .expect("some uuid hashes off the avoided partition")
+ }
+
+ fn write_tombstone(store: &CohortStore, on_partition: u16, old: Uuid, new: Uuid) {
+ let key = TombstoneKey {
+ partition_id: on_partition,
+ team_id: TEAM.0 as u64,
+ person: old,
+ };
+ let value = Tombstone {
+ new_person: new,
+ merged_at_ms: 1_716_800_000_000,
+ };
+ store
+ .write_batch(|b| b.put_tombstone(&key, &value.encode()))
+ .unwrap();
+ }
+
+ #[test]
+ fn no_tombstone_is_not_merged() {
+ let (_dir, store) = temp_store();
+ let person = Uuid::from_u128(1);
+ assert_eq!(
+ resolve(
+ &store,
+ partition(person),
+ TEAM,
+ person,
+ COHORT_PARTITION_COUNT
+ )
+ .unwrap(),
+ Resolution::NotMerged,
+ );
+ }
+
+ #[test]
+ fn same_partition_tombstone_resolves_inline() {
+ let (_dir, store) = temp_store();
+ let p_old = Uuid::from_u128(0xA11CE);
+ let part = partition(p_old);
+ let p_new = person_on(part);
+ write_tombstone(&store, part, p_old, p_new);
+
+ assert_eq!(
+ resolve(&store, part, TEAM, p_old, COHORT_PARTITION_COUNT).unwrap(),
+ Resolution::Inline {
+ final_person: p_new,
+ origin: p_old,
+ },
+ );
+ }
+
+ #[test]
+ fn cross_partition_tombstone_stops_at_the_first_hop() {
+ let (_dir, store) = temp_store();
+ let p_old = Uuid::from_u128(0xA11CE);
+ let part = partition(p_old);
+ let p_new = person_not_on(part);
+ write_tombstone(&store, part, p_old, p_new);
+
+ assert_eq!(
+ resolve(&store, part, TEAM, p_old, COHORT_PARTITION_COUNT).unwrap(),
+ Resolution::CrossPartition {
+ target_person: p_new,
+ origin: p_old,
+ },
+ );
+ }
+
+ #[test]
+ fn same_partition_chain_converges_to_the_final_person() {
+ let (_dir, store) = temp_store();
+ let p_old = Uuid::from_u128(0xA11CE);
+ let part = partition(p_old);
+ let mids = (1u128..)
+ .map(Uuid::from_u128)
+ .filter(|p| partition(*p) == part && *p != p_old)
+ .take(2)
+ .collect::<Vec<_>>();
+ let (p_mid, p_final) = (mids[0], mids[1]);
+ write_tombstone(&store, part, p_old, p_mid);
+ write_tombstone(&store, part, p_mid, p_final);
+
+ assert_eq!(
+ resolve(&store, part, TEAM, p_old, COHORT_PARTITION_COUNT).unwrap(),
+ Resolution::Inline {
+ final_person: p_final,
+ origin: p_old,
+ },
+ "the chain converges and the origin stays the first person",
+ );
+ }
+
+ #[test]
+ fn chain_stops_at_the_first_cross_partition_hop() {
+ let (_dir, store) = temp_store();
+ let p_old = Uuid::from_u128(0xA11CE);
+ let part = partition(p_old);
+ let p_mid = person_on(part);
+ let p_far = person_not_on(part);
+ write_tombstone(&store, part, p_old, p_mid);
+ write_tombstone(&store, part, p_mid, p_far);
+
+ assert_eq!(
+ resolve(&store, part, TEAM, p_old, COHORT_PARTITION_COUNT).unwrap(),
+ Resolution::CrossPartition {
+ target_person: p_far,
+ origin: p_old,
+ },
+ );
+ }
+
+ #[test]
+ fn a_cyclic_chain_is_hop_capped_not_infinite() {
+ let (_dir, store) = temp_store();
+ let p_old = Uuid::from_u128(0xA11CE);
+ let part = partition(p_old);
+ let p_b = person_on(part);
+ write_tombstone(&store, part, p_old, p_b);
+ write_tombstone(&store, part, p_b, p_old);
+
+ assert!(matches!(
+ resolve(&store, part, TEAM, p_old, COHORT_PARTITION_COUNT).unwrap(),
+ Resolution::Inline { origin, .. } if origin == p_old,
+ ));
+ }
+
+ #[test]
+ fn corrupt_tombstone_reads_as_not_merged() {
+ let (_dir, store) = temp_store();
+ let person = Uuid::from_u128(1);
+ let part = partition(person);
+ let key = TombstoneKey {
+ partition_id: part,
+ team_id: TEAM.0 as u64,
+ person,
+ };
+ store
+ .write_batch(|b| b.put_tombstone(&key, b"not json"))
+ .unwrap();
+ assert_eq!(
+ resolve(&store, part, TEAM, person, COHORT_PARTITION_COUNT).unwrap(),
+ Resolution::NotMerged,
+ "a corrupt tombstone degrades to not-merged, never a panic",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/merge/transfer.rs b/rust/cohort-stream-processor/src/merge/transfer.rs
new file mode 100644
index 000000000000..f7b8654391f2
--- /dev/null
+++ b/rust/cohort-stream-processor/src/merge/transfer.rs
@@ -0,0 +1,308 @@
+//! Wire and column-family value types for the cross-partition merge protocol.
+//!
+//! - [`PersonMergeEvent`] -- the merge trigger, keyed by P_old.
+//! - [`MergeStateTransfer`] -- P_old's packaged per-leaf state, keyed by P_new.
+//! - [`PendingTransfer`] -- `cf_pending_transfers` outbox value.
+//! - [`Tombstone`] -- `cf_merge_tombstones` value for straggler redirect.
+//! - [`DrainStamp`] / [`ApplyStamp`] -- idempotence markers (key presence is the guard).
+
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use crate::stage1::key::LeafStateKey;
+use crate::stage1::state::StatefulRecord;
+
+pub const MERGE_EVENT_SCHEMA_VERSION: u32 = 1;
+
+/// A committed `P_old -> P_new` person merge event.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PersonMergeEvent {
+ pub team_id: i32,
+ pub old_person_uuid: Uuid,
+ pub new_person_uuid: Uuid,
+ pub merged_at_ms: i64,
+ pub schema_version: u32,
+}
+
+/// One leaf of a [`MergeStateTransfer`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct TransferLeaf {
+ /// 16-byte `LeafStateKey` as 32 lowercase hex chars (human-readable on the wire).
+ pub leaf_state_key: String,
+ pub record: StatefulRecord,
+}
+
+impl TransferLeaf {
+ pub fn new(leaf_state_key: LeafStateKey, record: StatefulRecord) -> Self {
+ Self {
+ leaf_state_key: hex_encode(&leaf_state_key.0),
+ record,
+ }
+ }
+
+ /// Decode the hex `leaf_state_key`, or `None` if malformed.
+ pub fn decode_leaf_state_key(&self) -> Option<LeafStateKey> {
+ hex_decode(&self.leaf_state_key).map(LeafStateKey)
+ }
+}
+
+/// P_old's packaged state for cross-partition transfer, keyed by P_new.
+/// `source_partition`/`source_offset` are the original merge message's coordinates (used for
+/// idempotence on the apply side, since duplicate transfers arrive at fresh topic offsets).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct MergeStateTransfer {
+ pub team_id: i32,
+ pub old_person_uuid: Uuid,
+ pub new_person_uuid: Uuid,
+ pub merged_at_ms: i64,
+ pub source_partition: i32,
+ pub source_offset: i64,
+ pub leaves: Vec<TransferLeaf>,
+ /// Cross-partition forward hops taken so far when `new_person_uuid` was itself tombstoned at
+ /// apply time (chained merge `A → B → C` where `B → C` drained before `A → B` applied). Bounded
+ /// by [`crate::merge::apply_handler::MAX_TRANSFER_FORWARD_HOPS`]. `#[serde(default)]`: a message
+ /// without the field decodes to `0`, so the field is JSON-compatible both ways.
+ #[serde(default)]
+ pub forward_hops: u8,
+}
+
+/// Staged transfer in `cf_pending_transfers`. Survives a crash between the drain batch and the
+/// produce; the redrive re-produces it.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PendingTransfer {
+ pub transfer: MergeStateTransfer,
+ pub merge_msg_partition: i32,
+ pub merge_msg_offset: i64,
+}
+
+/// Tombstone value: the person a merged-away P_old's late events redirect to.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Tombstone {
+ pub new_person: Uuid,
+ pub merged_at_ms: i64,
+}
+
+/// Drain idempotence marker value (informational; key presence is the guard).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DrainStamp {
+ pub drained_at_ms: i64,
+}
+
+/// Apply idempotence marker value.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ApplyStamp {
+ pub applied_at_ms: i64,
+}
+
+/// JSON codecs: infallible `encode`, fallible `decode`.
+macro_rules! json_codec {
+ ($ty:ty) => {
+ impl $ty {
+ #[doc = "Infallible: this is plain data and always serializes."]
+ pub fn encode(&self) -> Vec<u8> {
+ serde_json::to_vec(self).expect("merge value is plain data and always serializes")
+ }
+
+ #[doc = "Garbage bytes yield an [`Err`], never a panic."]
+ pub fn decode(bytes: &[u8]) -> Result<Self, serde_json::Error> {
+ serde_json::from_slice(bytes)
+ }
+ }
+ };
+}
+
+json_codec!(PersonMergeEvent);
+json_codec!(MergeStateTransfer);
+json_codec!(PendingTransfer);
+json_codec!(Tombstone);
+json_codec!(DrainStamp);
+json_codec!(ApplyStamp);
+
+/// Encode 16 bytes as 32 lowercase hex chars.
+fn hex_encode(bytes: &[u8; 16]) -> String {
+ let mut out = String::with_capacity(32);
+ for &byte in bytes {
+ // `from_digit(_, 16)` is `Some` for any nibble `0..=15`.
+ out.push(char::from_digit((byte >> 4) as u32, 16).expect("high nibble < 16"));
+ out.push(char::from_digit((byte & 0x0f) as u32, 16).expect("low nibble < 16"));
+ }
+ out
+}
+
+/// Decode exactly 32 hex chars into 16 bytes, or `None` on invalid input.
+fn hex_decode(s: &str) -> Option<[u8; 16]> {
+ let bytes = s.as_bytes();
+ if bytes.len() != 32 {
+ return None;
+ }
+ let mut out = [0u8; 16];
+ for (i, slot) in out.iter_mut().enumerate() {
+ let hi = (bytes[2 * i] as char).to_digit(16)?;
+ let lo = (bytes[2 * i + 1] as char).to_digit(16)?;
+ *slot = ((hi << 4) | lo) as u8;
+ }
+ Some(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::stage1::state::{AppliedOffsets, Stage1State};
+
+ fn uuid(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+ }
+
+ fn single_record() -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ AppliedOffsets::default(),
+ )
+ }
+
+ #[test]
+ fn hex_round_trips_every_byte() {
+ let key = LeafStateKey([
+ 0x00, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0xff, 0x01, 0x02, 0x03, 0x04,
+ 0x05, 0x06,
+ ]);
+ let leaf = TransferLeaf::new(key, single_record());
+ assert_eq!(leaf.leaf_state_key.len(), 32);
+ assert_eq!(
+ leaf.leaf_state_key, "00123456789abcdef0ff010203040506",
+ "lowercase, two chars per byte, MSB first",
+ );
+ assert_eq!(leaf.decode_leaf_state_key(), Some(key));
+ }
+
+ #[test]
+ fn malformed_hex_decodes_to_none_not_panic() {
+ let bad_len = TransferLeaf {
+ leaf_state_key: "abcd".to_string(),
+ record: single_record(),
+ };
+ assert_eq!(bad_len.decode_leaf_state_key(), None, "wrong length");
+ let bad_char = TransferLeaf {
+ leaf_state_key: "zz123456789abcdef0ff010203040506".to_string(),
+ record: single_record(),
+ };
+ assert_eq!(bad_char.decode_leaf_state_key(), None, "non-hex char");
+ }
+
+ #[test]
+ fn person_merge_event_shape_is_pinned() {
+ let event = PersonMergeEvent {
+ team_id: 42,
+ old_person_uuid: uuid(0xAAAA),
+ new_person_uuid: uuid(0xBBBB),
+ merged_at_ms: 1_716_800_000_000,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ };
+ let value: serde_json::Value = serde_json::from_slice(&event.encode()).unwrap();
+ let object = value.as_object().unwrap();
+ let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
+ keys.sort_unstable();
+ assert_eq!(
+ keys,
+ vec![
+ "merged_at_ms",
+ "new_person_uuid",
+ "old_person_uuid",
+ "schema_version",
+ "team_id",
+ ],
+ );
+ assert_eq!(
+ object["old_person_uuid"],
+ serde_json::json!(uuid(0xAAAA).to_string())
+ );
+ assert_eq!(object["schema_version"], serde_json::json!(1));
+ assert_eq!(PersonMergeEvent::decode(&event.encode()).unwrap(), event);
+ }
+
+ #[test]
+ fn merge_state_transfer_carries_records_whole_and_round_trips() {
+ let transfer = MergeStateTransfer {
+ team_id: 7,
+ old_person_uuid: uuid(0xAAAA),
+ new_person_uuid: uuid(0xBBBB),
+ merged_at_ms: 1_716_800_000_000,
+ source_partition: 17,
+ source_offset: 12_345,
+ leaves: vec![TransferLeaf::new(LeafStateKey([0xAB; 16]), single_record())],
+ forward_hops: 0,
+ };
+ let decoded = MergeStateTransfer::decode(&transfer.encode()).unwrap();
+ assert_eq!(decoded, transfer);
+ assert_eq!(
+ decoded.leaves[0].record,
+ single_record(),
+ "the leaf's StatefulRecord transfers whole, so redirect_dedup chains for free",
+ );
+ }
+
+ #[test]
+ fn transfer_without_forward_hops_decodes_to_zero_for_wire_compat() {
+ // A transfer JSON that omits `forward_hops` must decode to `0` (`#[serde(default)]`).
+ let json = serde_json::json!({
+ "team_id": 7,
+ "old_person_uuid": uuid(0xAAAA).to_string(),
+ "new_person_uuid": uuid(0xBBBB).to_string(),
+ "merged_at_ms": 1_716_800_000_000_i64,
+ "source_partition": 17,
+ "source_offset": 12_345,
+ "leaves": [],
+ });
+ let decoded = MergeStateTransfer::decode(&serde_json::to_vec(&json).unwrap()).unwrap();
+ assert_eq!(
+ decoded.forward_hops, 0,
+ "missing forward_hops defaults to 0"
+ );
+ }
+
+ #[test]
+ fn cf_value_types_round_trip() {
+ let transfer = MergeStateTransfer {
+ team_id: 7,
+ old_person_uuid: uuid(0xAAAA),
+ new_person_uuid: uuid(0xBBBB),
+ merged_at_ms: 1,
+ source_partition: 3,
+ source_offset: 4,
+ leaves: vec![],
+ forward_hops: 0,
+ };
+ let pending = PendingTransfer {
+ transfer,
+ merge_msg_partition: 9,
+ merge_msg_offset: 100,
+ };
+ assert_eq!(PendingTransfer::decode(&pending.encode()).unwrap(), pending);
+
+ let tombstone = Tombstone {
+ new_person: uuid(0xBBBB),
+ merged_at_ms: 1_716_800_000_000,
+ };
+ assert_eq!(Tombstone::decode(&tombstone.encode()).unwrap(), tombstone);
+
+ let drain = DrainStamp {
+ drained_at_ms: 1_716_800_000_000,
+ };
+ assert_eq!(DrainStamp::decode(&drain.encode()).unwrap(), drain);
+ let apply = ApplyStamp {
+ applied_at_ms: 1_716_800_000_000,
+ };
+ assert_eq!(ApplyStamp::decode(&apply.encode()).unwrap(), apply);
+ }
+
+ #[test]
+ fn garbage_bytes_decode_to_err_not_panic() {
+ assert!(PersonMergeEvent::decode(b"not json").is_err());
+ assert!(MergeStateTransfer::decode(&[]).is_err());
+ assert!(Tombstone::decode(b"{}").is_err());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/observability/canonical_log.rs b/rust/cohort-stream-processor/src/observability/canonical_log.rs
new file mode 100644
index 000000000000..51107d704377
--- /dev/null
+++ b/rust/cohort-stream-processor/src/observability/canonical_log.rs
@@ -0,0 +1 @@
+//! Per-batch canonical structured log: one wide event per processed batch.
diff --git a/rust/cohort-stream-processor/src/observability/health.rs b/rust/cohort-stream-processor/src/observability/health.rs
new file mode 100644
index 000000000000..a951e2bae5c0
--- /dev/null
+++ b/rust/cohort-stream-processor/src/observability/health.rs
@@ -0,0 +1,43 @@
+//! Observability HTTP surface: `/_health`, `/_ready`, `/metrics`, `/`.
+//!
+//! `/_health` always returns 200: the `lifecycle` monitor owns health internally and triggers
+//! coordinated shutdown on stall, rather than relying on K8s liveness kills.
+
+use std::future::ready;
+
+use axum::response::IntoResponse;
+use axum::routing::get;
+use axum::Router;
+use lifecycle::{LivenessHandler, ReadinessHandler};
+use metrics_exporter_prometheus::PrometheusHandle;
+
+/// Build the observability router. Pass `metrics = None` to omit `/metrics`.
+pub fn router(
+ service_name: &'static str,
+ readiness: ReadinessHandler,
+ liveness: LivenessHandler,
+ metrics: Option<PrometheusHandle>,
+) -> Router {
+ let mut app = Router::new()
+ .route("/", get(move || async move { service_name }))
+ .route(
+ "/_health",
+ get(move || {
+ let liveness = liveness.clone();
+ async move { liveness.check().into_response() }
+ }),
+ )
+ .route(
+ "/_ready",
+ get(move || {
+ let readiness = readiness.clone();
+ async move { readiness.check().await }
+ }),
+ );
+
+ if let Some(handle) = metrics {
+ app = app.route("/metrics", get(move || ready(handle.render())));
+ }
+
+ app
+}
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
new file mode 100644
index 000000000000..db08338a77e0
--- /dev/null
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -0,0 +1,431 @@
+//! Prometheus recorder setup and the metric-name constants every emitter shares.
+
+use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};
+
+/// Teams with ≥1 realtime cohort in the current catalog snapshot (gauge).
+pub const FILTER_CATALOG_TEAMS: &str = "filter_catalog_teams";
+/// Distinct `conditionHash`es across all teams in the current snapshot (gauge).
+pub const FILTER_CATALOG_UNIQUE_CONDITIONS: &str = "filter_catalog_unique_conditions";
+/// Leaves dropped during parse, labelled by `reason` (counter).
+pub const FILTER_CATALOG_SKIPPED_LEAVES: &str = "filter_catalog_skipped_leaves_total";
+/// Cohorts skipped because their filter tree failed to parse (counter).
+pub const FILTER_CATALOG_COHORT_PARSE_ERRORS: &str = "filter_catalog_cohort_parse_errors_total";
+/// Teams whose timezone did not parse as an IANA zone and fell back to UTC (counter).
+pub const FILTER_CATALOG_TZ_FALLBACK: &str = "filter_catalog_tz_fallback_total";
+
+/// Cohorts classified by composition eligibility at freeze, labelled by `class` (counter).
+pub const COHORT_ELIGIBILITY_TOTAL: &str = "cohort_eligibility_total";
+/// Cohorts excluded because they sit in a cohort-reference cycle (counter).
+pub const COHORT_IN_CYCLE_TOTAL: &str = "cohort_in_cycle_total";
+
+/// Cascade depths reached, from the `depth` field on cascade messages (histogram). Cohort ids are
+/// logged, not labelled, to keep cardinality bounded.
+pub const CASCADE_DEPTH_OBSERVED: &str = "cascade_depth_observed";
+/// Outgoing cascades dropped because `incoming.depth >= cohort_cascade_depth_cap` (counter). Cohort
+/// ids are logged, not labelled, to keep cardinality bounded.
+pub const CASCADE_DEPTH_EXCEEDED_TOTAL: &str = "cascade_depth_exceeded_total";
+/// Cycles caught at runtime by the `cascade_chain` membership check (counter). Cohort ids are
+/// logged, not labelled, to keep cardinality bounded. Distinct from [`COHORT_IN_CYCLE_TOTAL`], which
+/// is Tarjan-SCC-based at catalog-refresh time.
+pub const CASCADE_CYCLE_DETECTED_RUNTIME_TOTAL: &str = "cascade_cycle_detected_runtime_total";
+/// Referrer re-evaluations dropped past `cohort_cascade_fanout_cap` (counter). Cohort ids are
+/// logged, not labelled, to keep cardinality bounded.
+pub const CASCADE_FANOUT_CAPPED_TOTAL: &str = "cascade_fanout_capped_total";
+/// First-hop or onward cascade produces to `cohort_cascade_events` that failed (counter). On the
+/// event path a failure holds the batch; on the sweep/merge paths it drops (at-most-once).
+pub const CASCADE_PRODUCE_ERRORS_TOTAL: &str = "cascade_produce_errors_total";
+/// The cascade-consumer commit floor pinned by a sticky offset hold, labelled by `partition` (gauge).
+/// Non-zero means a held cascade re-evaluation is stalling the commit. **Alert on a sustained
+/// non-zero level.**
+pub const CASCADE_HELD_OFFSET_GAUGE: &str = "cascade_held_offset";
+
+/// `(cohort, person)` pairs re-evaluated by Stage 2 composition (counter).
+pub const STAGE2_COHORTS_EVALUATED: &str = "stage2_cohorts_evaluated_total";
+/// Composable-cohort membership flips, labelled by `kind` (`entered`|`left`) (counter).
+pub const STAGE2_TRANSITIONS: &str = "stage2_transitions_total";
+/// Stage 2 decode failures (counter). The leaf reads as a non-member.
+pub const STAGE2_STATE_DECODE_ERROR: &str = "stage2_state_decode_error_total";
+/// Cohort-reference leaves reached during composable evaluation (counter). Non-zero signals a bug.
+pub const STAGE2_UNEXPECTED_COHORT_REF: &str = "stage2_unexpected_cohort_ref_total";
+
+/// Latency of one synchronous WAL fsync before an offset commit (histogram, seconds). Amortized over
+/// a batch of writes — it runs on the commit deadline, not per-message.
+pub const WAL_FSYNC_DURATION_SECONDS: &str = "wal_fsync_duration_seconds";
+/// WAL fsyncs that returned an error (counter). The commit is then skipped, so a persistent failure
+/// surfaces as growing consumer lag. **Alert on a sustained non-zero level.**
+pub const WAL_FSYNC_ERRORS_TOTAL: &str = "wal_fsync_errors_total";
+
+/// On-disk partition slices kept (reopen-live) across a durable restart, because still assigned to
+/// this pod (counter).
+pub const DURABLE_RESTORE_PARTITIONS_KEPT_TOTAL: &str = "durable_restore_partitions_kept_total";
+/// On-disk partition slices wiped because no longer assigned to this pod — stale state to cold-rebuild
+/// from the committed offset (counter).
+pub const DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL: &str =
+ "durable_restore_partitions_wiped_stale_total";
+/// `cf_stage1` keys re-seeded into a worker's `EvictionQueue` on spawn during a durable restart,
+/// labelled by `partition` (counter). Re-fires a dormant person's `Left`.
+pub const EVICTION_QUEUE_REBUILT_KEYS_TOTAL: &str = "eviction_queue_rebuilt_keys_total";
+/// Owned partitions that had at least one `cf_pending_transfers` entry re-produced by the eager boot
+/// redrive on a durable restart (counter). Incremented once per partition that recovered ≥1 transfer.
+pub const DURABLE_RESTORE_PENDING_TRANSFERS_RECOVERED_PARTITIONS_TOTAL: &str =
+ "durable_restore_pending_transfers_recovered_partitions_total";
+
+/// Wall-clock duration of one whole-DB `Checkpoint::create_checkpoint` (histogram, seconds).
+/// Whole-DB checkpoint, so these are per-pod, not per-partition.
+pub const CHECKPOINT_DURATION_SECONDS: &str = "checkpoint_duration_seconds";
+/// On-disk size of a freshly-taken checkpoint directory (histogram, bytes).
+pub const CHECKPOINT_SIZE_BYTES: &str = "checkpoint_size_bytes";
+/// File count in a freshly-taken checkpoint directory (histogram).
+pub const CHECKPOINT_FILE_COUNT: &str = "checkpoint_file_count";
+/// Checkpoint S3 uploads, labelled by `result` (`success`|`error`|`cancelled`|`unavailable`); when
+/// `result=cancelled`, an additional `cause` label (`rebalance`|`shutdown`|`unknown`) (counter).
+pub const CHECKPOINT_UPLOADS_TOTAL: &str = "checkpoint_uploads_total";
+/// Wall-clock duration of one checkpoint S3 upload, labelled by `result` (histogram, seconds).
+pub const CHECKPOINT_UPLOAD_DURATION_SECONDS: &str = "checkpoint_upload_duration_seconds";
+/// Individual checkpoint files uploaded to S3, labelled by `status` (`success`|`error`|`cancelled`)
+/// (counter).
+pub const CHECKPOINT_FILES_UPLOADED_TOTAL: &str = "checkpoint_files_uploaded_total";
+/// Individual checkpoint files downloaded from S3, labelled by `status`
+/// (`success`|`error`|`cancelled`) (counter).
+pub const CHECKPOINT_FILES_DOWNLOADED_TOTAL: &str = "checkpoint_files_downloaded_total";
+/// Files seen during incremental checkpoint planning, labelled by `action`
+/// (`added`|`replaced`|`retained`) (counter).
+pub const CHECKPOINT_PLAN_FILES_TOTAL: &str = "checkpoint_plan_files_total";
+/// Latency of one metadata.json fetch from S3 into memory (histogram, seconds).
+pub const CHECKPOINT_FILE_FETCH_DURATION_SECONDS: &str = "checkpoint_file_fetch_duration_seconds";
+/// Latency of fetching a whole checkpoint's files to disk (the parallel fanout) (histogram, seconds).
+pub const CHECKPOINT_FILES_FETCH_DURATION_SECONDS: &str = "checkpoint_files_fetch_duration_seconds";
+/// Latency of fetching and storing a single checkpoint file to disk (histogram, seconds).
+pub const CHECKPOINT_FILE_FETCH_STORE_DURATION_SECONDS: &str =
+ "checkpoint_file_fetch_store_duration_seconds";
+/// Latency of listing a checkpoint's recent attempt folders from S3 (histogram, seconds).
+pub const CHECKPOINT_LIST_DURATION_SECONDS: &str = "checkpoint_list_duration_seconds";
+/// Boot restores, labelled by `source` (`reopen_live`|`pvc`|`s3`|`cold`) (counter).
+pub const CHECKPOINT_RESTORE_TOTAL: &str = "checkpoint_restore_total";
+/// Wall-clock duration of one boot restore (histogram, seconds).
+pub const CHECKPOINT_RESTORE_DURATION_SECONDS: &str = "checkpoint_restore_duration_seconds";
+/// End-to-end checkpoint import (list + metadata + files + fallbacks), labelled by `result`
+/// (`success`|`failed`|`cancelled`|`timeout`) (histogram, seconds).
+pub const CHECKPOINT_IMPORT_DURATION_SECONDS: &str = "checkpoint_import_duration_seconds";
+/// Duration of one import attempt (one checkpoint's files), labelled by `result`
+/// (`success`|`failed`) (histogram, seconds).
+pub const CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS: &str =
+ "checkpoint_import_attempt_duration_seconds";
+
+/// RocksDB batch commits, labelled by `op` (counter).
+pub const STORE_WRITE_BATCH_TOTAL: &str = "store_write_batch_total";
+/// Latency of a committed RocksDB write, labelled by `op` (histogram, seconds).
+pub const STORE_WRITE_DURATION_SECONDS: &str = "store_write_duration_seconds";
+/// RocksDB operations that returned an error, labelled by `op` (counter).
+pub const STORE_ERRORS_TOTAL: &str = "store_errors_total";
+/// Malformed inputs the `cf_person_index` merge operator skipped, labelled by `kind` (counter).
+pub const STORE_MERGE_MALFORMED_TOTAL: &str = "store_merge_malformed_total";
+
+/// Cohort bytecode invoked a symbol with no registered native (counter). The function name is
+/// logged, not labelled, to keep cardinality bounded.
+pub const STAGE1_HOGVM_UNKNOWN_FUNCTION: &str = "stage1_hogvm_unknown_function_total";
+/// Any other VM/program failure during cohort evaluation, coerced to `false` (counter).
+pub const STAGE1_HOGVM_ERROR: &str = "stage1_hogvm_error_total";
+/// `properties`/`person_properties` JSON parse failure, labelled by `field` (counter).
+pub const STAGE1_GLOBALS_PARSE_ERROR: &str = "stage1_globals_parse_error_total";
+
+/// Partitions with a live worker channel registered on the router (gauge).
+pub const PARTITIONS_ACTIVE: &str = "partitions_active";
+/// Messages dropped while routing (no live worker), labelled by `reason` (counter).
+pub const PARTITION_ROUTE_DROPPED_TOTAL: &str = "partition_route_dropped_total";
+/// Sub-batches queued in a partition worker's channel, labelled by `partition` (gauge).
+pub const PARTITION_CHANNEL_DEPTH: &str = "partition_channel_depth";
+
+/// Non-empty rebalance callbacks, labelled by `event_type` (`assign`|`revoke`) (counter).
+pub const REBALANCES_TOTAL: &str = "rebalances_total";
+/// Partitions assigned to this consumer across all rebalances (counter).
+pub const PARTITIONS_ASSIGNED_TOTAL: &str = "partitions_assigned_total";
+/// Partitions revoked from this consumer across all rebalances (counter).
+pub const PARTITIONS_REVOKED_TOTAL: &str = "partitions_revoked_total";
+/// Empty rebalance callbacks short-circuited, labelled by `event_type` (counter).
+pub const REBALANCE_EMPTY_SKIPPED_TOTAL: &str = "rebalance_empty_skipped_total";
+/// Per-partition revoke drain latency (histogram, seconds).
+pub const REVOKE_DRAIN_DURATION_SECONDS: &str = "revoke_drain_duration_seconds";
+/// Per-partition RocksDB state slices reclaimed on revoke (counter).
+pub const PARTITION_STATE_DELETED_TOTAL: &str = "partition_state_deleted_total";
+/// Revoke cleanups skipped because the partition was re-acquired, labelled by `phase` (counter).
+pub const REBALANCE_CLEANUP_SKIPPED_TOTAL: &str = "rebalance_cleanup_skipped_total";
+
+/// Events fully processed (counter).
+pub const STAGE1_EVENTS_PROCESSED: &str = "stage1_events_processed_total";
+/// Events skipped whole, labelled by `reason` (counter).
+pub const STAGE1_EVENTS_SKIPPED: &str = "stage1_events_skipped_total";
+/// HogVM evaluations, labelled by `kind` — one per unique conditionHash per event (counter).
+pub const STAGE1_CONDITIONS_EVALUATED: &str = "stage1_conditions_evaluated_total";
+/// Leaf membership flips emitted, labelled by `kind` (counter).
+pub const STAGE1_TRANSITIONS: &str = "stage1_transitions_total";
+/// `cf_stage1` records written, labelled by `variant` (counter).
+pub const STAGE1_STATE_WRITES: &str = "stage1_state_writes_total";
+/// First-time `cf_person_index` appends, one per newly-seen `(person, leaf_state_key)` (counter).
+pub const STAGE1_PERSON_INDEX_APPENDS: &str = "stage1_person_index_appends_total";
+/// Applies skipped because the source `(partition, offset)` was already folded in, labelled by
+/// `variant` (counter).
+pub const STAGE1_REPLAY_SKIPPED: &str = "stage1_replay_skipped_total";
+/// Person-property applies dropped by the event-time argMax tiebreaker (counter).
+pub const STAGE1_ARGMAX_STALE: &str = "stage1_argmax_stale_total";
+/// Applies skipped because the leaf's resolved variant is unsupported, labelled by `variant`
+/// (counter). A defensive guard against a stale catalog.
+pub const STAGE1_UNSUPPORTED_VARIANT_SKIPPED: &str = "stage1_unsupported_variant_skipped_total";
+/// Stored `cf_stage1` values that failed to decode; the key is skipped, not panicked (counter).
+pub const STAGE1_STATE_DECODE_ERROR: &str = "stage1_state_decode_error_total";
+/// End-to-end per-event processing latency in the worker (histogram, seconds).
+pub const STAGE1_EVENT_PROCESS_DURATION: &str = "stage1_event_process_duration_seconds";
+
+/// Envelopes consumed and successfully deserialized from `cohort_stream_events` (counter).
+pub const COHORT_STREAM_EVENTS_CONSUMED: &str = "cohort_stream_events_consumed_total";
+/// Events routed to a per-partition worker (counter). Conservation:
+/// `consumed == dispatched + not_owned_skipped`.
+pub const COHORT_STREAM_EVENTS_DISPATCHED: &str = "cohort_stream_events_dispatched_total";
+/// Events dropped because the partition is no longer owned or shutdown is draining (counter).
+pub const COHORT_STREAM_EVENTS_SKIPPED_NOT_OWNED: &str =
+ "cohort_stream_events_skipped_not_owned_total";
+/// Merge messages dropped because the partition is no longer owned or shutdown is draining (counter).
+pub const COHORT_STREAM_MERGES_SKIPPED_NOT_OWNED: &str =
+ "cohort_stream_merges_skipped_not_owned_total";
+/// `KAFKA_PERSON_MERGE_EVENTS` envelopes consumed and successfully decoded (counter).
+pub const COHORT_STREAM_MERGES_CONSUMED: &str = "cohort_stream_merges_consumed_total";
+/// `cohort_merge_state_transfer` envelopes consumed and successfully decoded (counter).
+pub const COHORT_STREAM_TRANSFERS_CONSUMED: &str = "cohort_stream_transfers_consumed_total";
+/// `KAFKA_PERSON_MERGE_EVENTS` payloads that were empty or failed to decode (counter).
+pub const COHORT_STREAM_MERGE_DESERIALIZE_ERRORS: &str =
+ "cohort_stream_merge_deserialize_errors_total";
+/// `cohort_merge_state_transfer` payloads that were empty or failed to decode (counter).
+pub const COHORT_STREAM_TRANSFER_DESERIALIZE_ERRORS: &str =
+ "cohort_stream_transfer_deserialize_errors_total";
+/// Transfer messages dropped because the partition is no longer owned or shutdown is draining
+/// (counter).
+pub const COHORT_STREAM_TRANSFERS_SKIPPED_NOT_OWNED: &str =
+ "cohort_stream_transfers_skipped_not_owned_total";
+/// `cohort_cascade_events` envelopes consumed and successfully decoded (counter).
+pub const COHORT_STREAM_CASCADES_CONSUMED: &str = "cohort_stream_cascades_consumed_total";
+/// `cohort_cascade_events` payloads that were empty or failed to decode (counter).
+pub const COHORT_STREAM_CASCADE_DESERIALIZE_ERRORS: &str =
+ "cohort_stream_cascade_deserialize_errors_total";
+/// Cascade messages dropped because the partition is no longer owned or shutdown is draining
+/// (counter).
+pub const COHORT_STREAM_CASCADES_SKIPPED_NOT_OWNED: &str =
+ "cohort_stream_cascades_skipped_not_owned_total";
+/// Decoded `KAFKA_PERSON_MERGE_EVENTS` envelopes accumulated per consume → dispatch cycle
+/// (histogram). A separate constant per topic, not a label.
+pub const COHORT_STREAM_MERGES_CONSUME_BATCH_SIZE: &str = "cohort_stream_merges_consume_batch_size";
+/// Decoded `cohort_merge_state_transfer` envelopes accumulated per consume → dispatch cycle
+/// (histogram).
+pub const COHORT_STREAM_TRANSFERS_CONSUME_BATCH_SIZE: &str =
+ "cohort_stream_transfers_consume_batch_size";
+/// Decoded `cohort_cascade_events` envelopes accumulated per consume → dispatch cycle (histogram).
+pub const COHORT_STREAM_CASCADES_CONSUME_BATCH_SIZE: &str =
+ "cohort_stream_cascades_consume_batch_size";
+/// A worker tried to mark an offset past what the dispatcher routed (counter).
+pub const COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH: &str =
+ "cohort_stream_offset_ahead_of_dispatch_total";
+/// Messages with a present-but-unparseable payload (counter).
+pub const COHORT_STREAM_DESERIALIZE_ERRORS: &str = "cohort_stream_deserialize_errors_total";
+/// Messages with a `None` (zero-byte) payload, skipped (counter).
+pub const COHORT_STREAM_EMPTY_PAYLOAD: &str = "cohort_stream_empty_payload_total";
+/// Kafka transport errors from `recv()` (counter).
+pub const COHORT_STREAM_KAFKA_RECV_ERRORS: &str = "cohort_stream_kafka_recv_errors_total";
+/// Offset commits accepted by Kafka (counter).
+pub const COHORT_STREAM_OFFSET_COMMITS: &str = "cohort_stream_offset_commits_total";
+/// Offset commit attempts Kafka rejected (counter).
+pub const COHORT_STREAM_OFFSET_COMMIT_ERRORS: &str = "cohort_stream_offset_commit_errors_total";
+/// Stage 1 workers lazily spawned on first delivery of a partition (counter).
+pub const COHORT_STREAM_WORKERS_SPAWNED: &str = "cohort_stream_workers_spawned_total";
+/// Per-partition routing failures (counter).
+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`
+/// (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).
+pub const OUTPUT_PRODUCE_ERRORS: &str = "output_produce_errors_total";
+
+/// Sweep cycles that fired, labelled by `loop` (`eviction`|`redrive`|`merge_gc`|`checkpoint`)
+/// (counter).
+pub const SWEEP_CYCLES_TOTAL: &str = "sweep_cycles_total";
+/// Wall-clock duration of one sweep cycle, labelled by `loop` (histogram, seconds).
+pub const SWEEP_CYCLE_DURATION_SECONDS: &str = "sweep_cycle_duration_seconds";
+/// Keys the sweep evicted, labelled by `variant` (counter).
+pub const SWEEP_KEYS_EVICTED_TOTAL: &str = "sweep_keys_evicted_total";
+/// Person merges handled, labelled by `path` (`same_partition`|`cross_partition`) (counter).
+pub const MERGE_HANDLED_TOTAL: &str = "merge_handled_total";
+/// Drain messages short-circuited by a `cf_merge_drains_applied` hit (counter).
+pub const MERGE_DRAINS_SKIPPED_REPLAY_TOTAL: &str = "merge_drains_skipped_replay_total";
+/// Transfer messages short-circuited by a `cf_merge_applied` hit (counter).
+pub const MERGE_APPLIES_SKIPPED_REPLAY_TOTAL: &str = "merge_applies_skipped_replay_total";
+/// Late events for merged persons that triggered a tombstone redirect, labelled by `path`
+/// (`inline`|`re_keyed`) (counter). `inline` counts at resolve time; `re_keyed` counts only after
+/// the re-produce ack. A hop-capped redirect is counted only under
+/// [`MERGE_REDIRECT_HOP_CAPPED_TOTAL`].
+pub const MERGE_TOMBSTONE_REDIRECTS_TOTAL: &str = "merge_tombstone_redirects_total";
+/// Straggler re-key produces to `cohort_stream_events` that failed (counter).
+pub const MERGE_REKEY_PRODUCE_FAILURE_TOTAL: &str = "merge_rekey_produce_failure_total";
+/// Cross-partition redirects that hit the `redirect_hops` cap and were processed inline (counter).
+/// Non-zero means a corrupt tombstone cycle.
+pub const MERGE_REDIRECT_HOP_CAPPED_TOTAL: &str = "merge_redirect_hop_capped_total";
+/// State transfers re-targeted at apply time because `new_person_uuid` was itself tombstoned (a
+/// chained merge `A → B → C` where `B → C` drained before `A → B` applied), labelled by `path`
+/// (`inline`|`re_keyed`). `inline` = the resolved survivor co-resides on this partition and the
+/// transfer applied there directly; `re_keyed` = the survivor lives on another partition and the
+/// transfer was forwarded on `cohort_merge_state_transfer`, counted only after the forward ack.
+pub const MERGE_TRANSFER_FORWARDS_TOTAL: &str = "merge_transfer_forwards_total";
+/// Transfer forwards that hit the [`crate::merge::apply_handler::MAX_TRANSFER_FORWARD_HOPS`] cap and
+/// were not forwarded (counter). Non-zero means a corrupt tombstone cycle, same class as
+/// [`MERGE_REDIRECT_HOP_CAPPED_TOTAL`].
+pub const MERGE_FORWARD_HOP_CAPPED_TOTAL: &str = "merge_forward_hop_capped_total";
+/// Per-leaf merge work dropped, labelled by `reason` (counter).
+pub const MERGE_LEAVES_DROPPED_TOTAL: &str = "merge_leaves_dropped_total";
+/// Transfer produces that exhausted the inline retry budget (counter). The packaged state stays in
+/// `cf_pending_transfers` and the merge offset is not committed; the periodic redrive closes the
+/// gap.
+pub const MERGE_TRANSFER_PRODUCE_FAILURE_TOTAL: &str = "merge_transfer_produce_failure_total";
+/// `cf_pending_transfers` clears that failed after the transfer produce was acked (counter). The
+/// merge offset still commits; the leftover outbox entry only re-produces a duplicate the apply
+/// side's dedup absorbs.
+pub const MERGE_OUTBOX_CLEAR_FAILURE_TOTAL: &str = "merge_outbox_clear_failure_total";
+/// Cross-partition drains whose packaged transfer carried no leaves (counter).
+pub const MERGE_TRANSFERS_SKIPPED_EMPTY_TOTAL: &str = "merge_transfers_skipped_empty_total";
+/// Entries currently staged in a partition's `cf_pending_transfers` outbox, labelled by `partition`
+/// (gauge). A sustained non-zero level means the transfer topic keeps refusing produces.
+pub const MERGE_PENDING_TRANSFERS_GAUGE: &str = "merge_pending_transfers";
+/// The merge/transfer commit floor pinned by a sticky offset hold on a partition, labelled by
+/// `partition` (gauge). A non-zero value means a failed merge drain / transfer apply is holding the
+/// partition's committable offset for redelivery and will not advance until the next tenure replays
+/// it — a *visible* commit-stall, by design, in place of silent merge/transfer state loss. **Alert on
+/// a sustained non-zero level**: a persistent store error re-fails every tenure and lag grows.
+pub const MERGE_HELD_OFFSET_GAUGE: &str = "merge_held_offset";
+/// Latency of one merge drain (histogram, seconds).
+pub const MERGE_DRAIN_DURATION_SECONDS: &str = "merge_drain_duration_seconds";
+/// Latency of one transfer apply (histogram, seconds).
+pub const MERGE_APPLY_DURATION_SECONDS: &str = "merge_apply_duration_seconds";
+
+/// Merge-CF keys scanned by the GC sweep, labelled by `cf` (counter).
+pub const MERGE_GC_KEYS_SCANNED_TOTAL: &str = "merge_gc_keys_scanned_total";
+/// Merge-CF keys the GC sweep deleted (expired or undecodable), labelled by `cf` (counter).
+pub const MERGE_GC_KEYS_DELETED_TOTAL: &str = "merge_gc_keys_deleted_total";
+/// Merge-CF values the GC sweep could not decode, labelled by `cf` (counter). Each is deleted and
+/// folded into [`MERGE_GC_KEYS_DELETED_TOTAL`] (an unreadable timestamp can never age out).
+pub const MERGE_GC_UNDECODABLE_TOTAL: &str = "merge_gc_undecodable_total";
+
+/// `cf_stage2` rows scanned by the orphan GC pass (counter).
+pub const STAGE2_ORPHAN_GC_KEYS_SCANNED_TOTAL: &str = "stage2_orphan_gc_keys_scanned_total";
+/// `cf_stage2` orphan rows the pass deleted — the cohort left the composable set (counter).
+pub const STAGE2_ORPHAN_GC_KEYS_DELETED_TOTAL: &str = "stage2_orphan_gc_keys_deleted_total";
+/// Orphan-GC passes skipped without scanning, labelled by `reason`
+/// (`catalog_not_loaded`|`empty_catalog`) (counter).
+pub const STAGE2_ORPHAN_GC_SKIPPED_TOTAL: &str = "stage2_orphan_gc_skipped_total";
+/// `cf_stage2` keys the orphan GC could not classify and left in place (counter): a key the decoder
+/// rejected, or an id that overflows `i32`.
+pub const STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL: &str = "stage2_orphan_gc_undecodable_keys_total";
+
+/// Keys the sweep popped but did not evict, labelled by `reason` (counter). Conservation:
+/// `popped == evicted + dropped`.
+pub const SWEEP_KEYS_DROPPED_TOTAL: &str = "sweep_keys_dropped_total";
+
+/// Install the global Prometheus recorder. Call once at startup.
+///
+/// # Panics
+/// Panics if a global metrics recorder has already been installed.
+pub fn install_recorder() -> PrometheusHandle {
+ PrometheusBuilder::new()
+ .install_recorder()
+ .expect("failed to install Prometheus recorder")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cascade_metric_names_are_stable() {
+ assert_eq!(CASCADE_DEPTH_OBSERVED, "cascade_depth_observed");
+ assert_eq!(CASCADE_DEPTH_EXCEEDED_TOTAL, "cascade_depth_exceeded_total");
+ assert_eq!(
+ CASCADE_CYCLE_DETECTED_RUNTIME_TOTAL,
+ "cascade_cycle_detected_runtime_total",
+ );
+ assert_eq!(CASCADE_FANOUT_CAPPED_TOTAL, "cascade_fanout_capped_total");
+ }
+
+ #[test]
+ fn durability_metric_names_are_stable() {
+ assert_eq!(CHECKPOINT_DURATION_SECONDS, "checkpoint_duration_seconds");
+ assert_eq!(CHECKPOINT_SIZE_BYTES, "checkpoint_size_bytes");
+ assert_eq!(CHECKPOINT_FILE_COUNT, "checkpoint_file_count");
+ assert_eq!(CHECKPOINT_UPLOADS_TOTAL, "checkpoint_uploads_total");
+ assert_eq!(
+ CHECKPOINT_UPLOAD_DURATION_SECONDS,
+ "checkpoint_upload_duration_seconds",
+ );
+ assert_eq!(
+ CHECKPOINT_FILES_UPLOADED_TOTAL,
+ "checkpoint_files_uploaded_total",
+ );
+ assert_eq!(
+ CHECKPOINT_FILES_DOWNLOADED_TOTAL,
+ "checkpoint_files_downloaded_total",
+ );
+ assert_eq!(CHECKPOINT_PLAN_FILES_TOTAL, "checkpoint_plan_files_total");
+ assert_eq!(
+ CHECKPOINT_FILE_FETCH_DURATION_SECONDS,
+ "checkpoint_file_fetch_duration_seconds",
+ );
+ assert_eq!(
+ CHECKPOINT_FILES_FETCH_DURATION_SECONDS,
+ "checkpoint_files_fetch_duration_seconds",
+ );
+ assert_eq!(
+ CHECKPOINT_FILE_FETCH_STORE_DURATION_SECONDS,
+ "checkpoint_file_fetch_store_duration_seconds",
+ );
+ assert_eq!(
+ CHECKPOINT_LIST_DURATION_SECONDS,
+ "checkpoint_list_duration_seconds",
+ );
+ assert_eq!(CHECKPOINT_RESTORE_TOTAL, "checkpoint_restore_total");
+ assert_eq!(
+ CHECKPOINT_RESTORE_DURATION_SECONDS,
+ "checkpoint_restore_duration_seconds",
+ );
+ assert_eq!(
+ CHECKPOINT_IMPORT_DURATION_SECONDS,
+ "checkpoint_import_duration_seconds",
+ );
+ assert_eq!(
+ CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS,
+ "checkpoint_import_attempt_duration_seconds",
+ );
+ assert_eq!(
+ DURABLE_RESTORE_PENDING_TRANSFERS_RECOVERED_PARTITIONS_TOTAL,
+ "durable_restore_pending_transfers_recovered_partitions_total",
+ );
+ }
+
+ #[test]
+ fn stage2_orphan_gc_metric_names_are_stable() {
+ assert_eq!(
+ STAGE2_ORPHAN_GC_KEYS_SCANNED_TOTAL,
+ "stage2_orphan_gc_keys_scanned_total",
+ );
+ assert_eq!(
+ STAGE2_ORPHAN_GC_KEYS_DELETED_TOTAL,
+ "stage2_orphan_gc_keys_deleted_total",
+ );
+ assert_eq!(
+ STAGE2_ORPHAN_GC_SKIPPED_TOTAL,
+ "stage2_orphan_gc_skipped_total"
+ );
+ assert_eq!(
+ STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL,
+ "stage2_orphan_gc_undecodable_keys_total",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/observability/mod.rs b/rust/cohort-stream-processor/src/observability/mod.rs
new file mode 100644
index 000000000000..0f1adf1ed73b
--- /dev/null
+++ b/rust/cohort-stream-processor/src/observability/mod.rs
@@ -0,0 +1,5 @@
+//! Observability surface: health/readiness probes, Prometheus metrics, and the canonical log.
+
+pub mod canonical_log;
+pub mod health;
+pub mod metrics;
diff --git a/rust/cohort-stream-processor/src/partitions/follower.rs b/rust/cohort-stream-processor/src/partitions/follower.rs
new file mode 100644
index 000000000000..7cb0a229df24
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/follower.rs
@@ -0,0 +1,144 @@
+//! Assignment mirroring for the internal follower consumers.
+//!
+//! The follower consumers (`person_merge_events`, `cohort_merge_state_transfer`, and — when the
+//! cascade gate is on — `cohort_cascade_events`) never `subscribe()`: the `cohort_stream_events`
+//! group's rebalance is the single source of partition ownership, and the rebalance worker mirrors
+//! every Assign/Revoke onto them through [`PartitionMirror`] — `incremental_assign` at
+//! [`Offset::Stored`] and `incremental_unassign`, both unconditional. The topics are co-partitioned,
+//! so the events topic's partition numbers index every follower.
+//!
+//! Why unconditional, including the rapid revoke→assign path: between the sync revoke and the async
+//! unassign the followers keep fetching, and the dispatcher's owned-gate drops those messages while
+//! their fetch position advances in-session. If a re-acquire skipped re-assignment, a later
+//! monotonic-max mark would commit past the dropped window — a permanently lost merge, not lag.
+//! Re-assigning at `Offset::Stored` rewinds to the last commit and redelivers the window; the
+//! drain/apply source-coords markers absorb the replays.
+
+use std::sync::Arc;
+
+use rdkafka::consumer::{Consumer, StreamConsumer};
+use rdkafka::{Offset, TopicPartitionList};
+use tracing::warn;
+
+/// Mirror an events-group (un)assignment onto the follower consumers.
+/// Trait-based so the rebalance worker is unit-testable; production impl is [`FollowerSet`].
+pub trait PartitionMirror: Send + Sync {
+ /// Mirror newly-assigned partitions onto every follower.
+ fn assign(&self, partitions: &[i32]);
+ /// Mirror revoked partitions off every follower.
+ fn unassign(&self, partitions: &[i32]);
+}
+
+/// One follower consumer and the topic its assignments are built against.
+pub struct Follower {
+ consumer: Arc<StreamConsumer>,
+ topic: String,
+}
+
+impl Follower {
+ pub fn new(consumer: Arc<StreamConsumer>, topic: String) -> Self {
+ Self { consumer, topic }
+ }
+}
+
+/// Production [`PartitionMirror`]: drives `incremental_assign`/`incremental_unassign` on a set of
+/// follower consumers (`person_merge_events`, `cohort_merge_state_transfer`, and — when the gate is
+/// on — `cohort_cascade_events`). Errors are warned and skipped: the rebalance worker must keep
+/// draining. A missed assign degrades to visible group lag; a missed unassign is practically
+/// unreachable (either "partition wasn't assigned" or a fatally-dead consumer).
+pub struct FollowerSet {
+ followers: Vec<Follower>,
+}
+
+impl FollowerSet {
+ /// The followers' topics must all be co-partitioned with `cohort_stream_events`.
+ pub fn new(followers: impl IntoIterator<Item = Follower>) -> Self {
+ Self {
+ followers: followers.into_iter().collect(),
+ }
+ }
+}
+
+impl PartitionMirror for FollowerSet {
+ fn assign(&self, partitions: &[i32]) {
+ for follower in &self.followers {
+ let tpl = stored_tpl(&follower.topic, partitions);
+ if let Err(err) = follower.consumer.incremental_assign(&tpl) {
+ warn!(
+ topic = %follower.topic,
+ ?partitions,
+ error = %err,
+ "follower incremental_assign failed; surfaces as lag on its consumer group",
+ );
+ }
+ }
+ }
+
+ fn unassign(&self, partitions: &[i32]) {
+ for follower in &self.followers {
+ let tpl = bare_tpl(&follower.topic, partitions);
+ if let Err(err) = follower.consumer.incremental_unassign(&tpl) {
+ warn!(
+ topic = %follower.topic,
+ ?partitions,
+ error = %err,
+ "follower incremental_unassign failed; owned-gate still drops its messages",
+ );
+ }
+ }
+ }
+}
+
+pub(crate) fn stored_tpl(topic: &str, partitions: &[i32]) -> TopicPartitionList {
+ let mut tpl = TopicPartitionList::new();
+ for &partition in partitions {
+ if let Err(err) = tpl.add_partition_offset(topic, partition, Offset::Stored) {
+ warn!(topic, partition, error = %err, "skipping partition in follower assign list");
+ }
+ }
+ tpl
+}
+
+pub(crate) fn bare_tpl(topic: &str, partitions: &[i32]) -> TopicPartitionList {
+ let mut tpl = TopicPartitionList::new();
+ for &partition in partitions {
+ tpl.add_partition(topic, partition);
+ }
+ tpl
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn stored_tpl_maps_each_partition_to_offset_stored() {
+ let tpl = stored_tpl("person_merge_events", &[3, 7, 0]);
+
+ assert_eq!(tpl.count(), 3);
+ let mut partitions = Vec::new();
+ for elem in tpl.elements() {
+ assert_eq!(elem.topic(), "person_merge_events");
+ assert_eq!(elem.offset(), Offset::Stored);
+ partitions.push(elem.partition());
+ }
+ partitions.sort_unstable();
+ assert_eq!(partitions, vec![0, 3, 7]);
+ }
+
+ #[test]
+ fn stored_tpl_for_no_partitions_is_empty() {
+ assert_eq!(stored_tpl("cohort_merge_state_transfer", &[]).count(), 0);
+ }
+
+ #[test]
+ fn bare_tpl_carries_partitions_without_a_real_offset() {
+ let tpl = bare_tpl("cohort_merge_state_transfer", &[5]);
+
+ assert_eq!(tpl.count(), 1);
+ let elems = tpl.elements();
+ assert_eq!(elems[0].topic(), "cohort_merge_state_transfer");
+ assert_eq!(elems[0].partition(), 5);
+ assert_eq!(elems[0].offset(), Offset::Invalid);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rs
new file mode 100644
index 000000000000..a3393c951731
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/mod.rs
@@ -0,0 +1,25 @@
+//! Partition-affined routing and per-partition workers.
+//!
+//! All state mutations for a given `(team_id, person_id)` serialize through exactly one worker,
+//! with no cross-worker coordination on the hot path (the worker-affinity invariant). The
+//! long-lived worker that owns the `Receiver` from [`router::PartitionRouter::add_partition`] and
+//! runs the Stage 1 loop lives in [`crate::workers`].
+
+pub mod follower;
+pub mod offset_tracker;
+pub mod partitioner;
+pub mod rebalance;
+pub mod router;
+pub mod shuffle_message;
+
+pub use follower::{Follower, FollowerSet, PartitionMirror};
+pub use offset_tracker::{MarkOutcome, OffsetTracker};
+pub use partitioner::{
+ merge_partition_key, murmur2, partition_for, partition_of, COHORT_PARTITION_COUNT,
+};
+pub use rebalance::{
+ run_rebalance_worker, CohortConsumerContext, ConsumerCommand, ConsumerCommandReceiver,
+ ConsumerCommandSender, RebalanceEvent, RebalanceEventReceiver,
+};
+pub use router::{PartitionRouter, RouteError};
+pub use shuffle_message::ShuffleMessage;
diff --git a/rust/cohort-stream-processor/src/partitions/offset_tracker.rs b/rust/cohort-stream-processor/src/partitions/offset_tracker.rs
new file mode 100644
index 000000000000..390ecf9c7921
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/offset_tracker.rs
@@ -0,0 +1,354 @@
+//! [`OffsetTracker`] — per-partition commit tracking: the next offset to consume after a partition's
+//! batch is durably processed ([`OffsetTracker::committable_offsets`]) and the offset Kafka last
+//! acked (the recovery point on restart). No batch-ID ordering checks: the single per-partition
+//! channel plus serial worker already guarantee in-partition order.
+//!
+//! Per-key replay dedup is a separate concern, owned by
+//! [`AppliedOffsets`](crate::stage1::state::AppliedOffsets) on each `cf_stage1` record.
+
+use std::collections::HashMap;
+
+use dashmap::DashMap;
+
+/// Per-partition consume/commit progress.
+#[derive(Debug, Default, Clone, Copy)]
+struct PartitionProgress {
+ /// Next offset to consume (highest processed `+ 1`), the value committed to Kafka. Monotonic.
+ /// `0` is the "never processed" sentinel; a real mark is always `≥ 1`, so
+ /// [`committable_offsets`](OffsetTracker::committable_offsets) treats `0` as nothing to commit.
+ processed_offset: i64,
+ /// Dispatch ceiling: highest next-offset actually routed to a worker.
+ /// [`mark_processed`](OffsetTracker::mark_processed) clamps `processed_offset` to this so a
+ /// consumed-but-never-dispatched offset (dropped buffer, route error) can't be committed past.
+ /// In correct operation it equals the max routed offset `+ 1`, so the clamp only bites on a bug.
+ dispatched_offset: i64,
+ /// Commit floor pinned by [`hold`](OffsetTracker::hold): the lowest next-offset a handler asked to
+ /// *redeliver* because a failed step left no other recovery (a store write that was the last copy
+ /// of merge/transfer state, a forward produce with no local outbox). `None` = no hold.
+ ///
+ /// [`committable_offsets`](OffsetTracker::committable_offsets) caps its result at this, so a later
+ /// success on the same partition — which advances `processed_offset` past the failed message —
+ /// cannot leapfrog the held offset and silently skip it. A hold only ever *lowers* the floor
+ /// ([`min`]); it is **sticky** for the worker's tenure (no within-tenure clear — a single failed
+ /// message is never reprocessed before redelivery), cleared only by
+ /// [`forget_partition`](OffsetTracker::forget_partition) and the next tenure's replay. That makes a
+ /// persistent store error a *visible* commit-stall (lag grows; emit the `held_offset` gauge and
+ /// alert) rather than a silent state loss — the intended fail-stop for a correctness-critical pipeline.
+ held_offset: Option<i64>,
+ /// Last offset Kafka acked as committed. The gap to `processed_offset` is the window Kafka
+ /// replays after a crash.
+ committed_offset: i64,
+}
+
+/// What [`OffsetTracker::mark_processed`] did with a mark — returned so the worker can emit a metric
+/// without the tracker importing `metrics`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MarkOutcome {
+ /// `next_offset` was within the dispatched ceiling — the normal case.
+ WithinDispatch,
+ /// `next_offset` exceeded the ceiling and was capped to it: the worker tried to commit past an
+ /// offset never routed to it (dropped buffer or worker accounting bug). An F1 invariant alert.
+ CappedAheadOfDispatch,
+}
+
+/// Thread-safe `partition → `[`PartitionProgress`], sharded behind `DashMap` so per-partition
+/// updates from different worker tasks don't contend on one lock.
+#[derive(Debug, Default)]
+pub struct OffsetTracker {
+ partitions: DashMap<i32, PartitionProgress>,
+}
+
+impl OffsetTracker {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Raise the per-partition dispatch ceiling. The [`EventDispatcher`] calls this for every routed
+ /// message **before** routing, with `next_offset = message_offset + 1`. Monotonic. Recording
+ /// the handoff is what lets [`mark_processed`](Self::mark_processed) refuse to commit past an
+ /// offset that was consumed but never dispatched.
+ ///
+ /// [`EventDispatcher`]: crate::consumers::events::EventDispatcher
+ pub fn mark_dispatched(&self, partition: i32, next_offset: i64) {
+ let mut progress = self.partitions.entry(partition).or_default();
+ progress.dispatched_offset = progress.dispatched_offset.max(next_offset);
+ }
+
+ /// Record the next offset to consume (`last processed + 1`) after a batch is durably processed.
+ /// Monotonic, and clamped to [`dispatched_offset`](PartitionProgress::dispatched_offset) so a
+ /// worker can't advance the committed position past an offset it wasn't dispatched. The clamp is
+ /// a no-op in correct operation ([`MarkOutcome::WithinDispatch`]); a clamp that bites returns
+ /// [`MarkOutcome::CappedAheadOfDispatch`].
+ #[must_use = "a CappedAheadOfDispatch outcome is an F1 invariant violation the worker must surface"]
+ pub fn mark_processed(&self, partition: i32, next_offset: i64) -> MarkOutcome {
+ let mut progress = self.partitions.entry(partition).or_default();
+ let capped = next_offset.min(progress.dispatched_offset);
+ progress.processed_offset = progress.processed_offset.max(capped);
+ if capped < next_offset {
+ MarkOutcome::CappedAheadOfDispatch
+ } else {
+ MarkOutcome::WithinDispatch
+ }
+ }
+
+ /// Pin the partition's commit floor at `offset` (the failed message's *own* offset `K`, **not**
+ /// `K + 1`), so [`committable_offsets`](Self::committable_offsets) never advances past it and Kafka
+ /// redelivers the message. Used when a handler step failed and the only recovery is replay (a
+ /// store write that held the last copy of merge/transfer state, a forward produce with no local
+ /// outbox); contrast [`mark_processed`](Self::mark_processed), which advances *past* `K`.
+ ///
+ /// A hold only ever **lowers** the floor ([`min`] of any existing hold): two failures in one
+ /// tenure pin the earlier message, and a hold can never *raise* a floor a prior failure already
+ /// set. The hold is sticky for the tenure — see [`held_offset`](PartitionProgress::held_offset).
+ /// Returns the resulting floor so the caller can report it: the floor (not the raw `offset`) is
+ /// the position that will actually be redelivered, so it's what a `held_offset` gauge should show.
+ pub fn hold(&self, partition: i32, offset: i64) -> i64 {
+ let mut progress = self.partitions.entry(partition).or_default();
+ let floor = progress
+ .held_offset
+ .map_or(offset, |existing| existing.min(offset));
+ progress.held_offset = Some(floor);
+ floor
+ }
+
+ /// Mark an offset as acked-committed by Kafka. Monotonic, and a no-op for a never-processed
+ /// partition (you cannot commit what you have not consumed).
+ pub fn mark_committed(&self, partition: i32, offset: i64) {
+ if let Some(mut progress) = self.partitions.get_mut(&partition) {
+ progress.committed_offset = progress.committed_offset.max(offset);
+ }
+ }
+
+ /// Snapshot of `partition → next-offset-to-consume` for every partition with a *processed*
+ /// offset, **capped at any [`hold`](Self::hold) floor**. Partitions tracked only because they were
+ /// dispatched carry the `processed_offset == 0` sentinel and are excluded — nothing safe to
+ /// commit, so Kafka replays them. A real mark is always `≥ 1`, so the filter never drops a
+ /// committable offset.
+ ///
+ /// The hold cap is applied to the *value*, not the filter: a hold pinned at the message's own
+ /// offset `K` makes the committable value `min(processed, K)` so a later success cannot leapfrog
+ /// the failed message. A hold at `0` (or a hold while `processed == 0`) yields a value of `0`,
+ /// which the `> 0` filter then excludes — Kafka replays the partition from the start of its
+ /// uncommitted range, redelivering the held message rather than skipping it.
+ pub fn committable_offsets(&self) -> HashMap<i32, i64> {
+ self.partitions
+ .iter()
+ .filter(|entry| entry.value().processed_offset > 0)
+ .filter_map(|entry| {
+ let progress = entry.value();
+ let committable = match progress.held_offset {
+ Some(held) => progress.processed_offset.min(held),
+ None => progress.processed_offset,
+ };
+ (committable > 0).then_some((*entry.key(), committable))
+ })
+ .collect()
+ }
+
+ pub fn committed_offset(&self, partition: i32) -> Option<i64> {
+ self.partitions.get(&partition).map(|p| p.committed_offset)
+ }
+
+ /// Drop all tracking for a revoked partition. Its offset should already be committed. Removing the
+ /// whole entry also clears any [`hold`](Self::hold), so the next tenure starts unheld and replays
+ /// from the committed offset — the only way a sticky hold is released.
+ pub fn forget_partition(&self, partition: i32) {
+ self.partitions.remove(&partition);
+ }
+
+ pub fn partition_count(&self) -> usize {
+ self.partitions.len()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn mark_processed_advances_and_never_regresses() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(5, 150);
+
+ assert_eq!(tracker.mark_processed(5, 100), MarkOutcome::WithinDispatch);
+ assert_eq!(tracker.committable_offsets().get(&5), Some(&100));
+
+ // A lower offset (replay) must not regress progress.
+ assert_eq!(tracker.mark_processed(5, 50), MarkOutcome::WithinDispatch);
+ assert_eq!(tracker.committable_offsets().get(&5), Some(&100));
+
+ assert_eq!(tracker.mark_processed(5, 150), MarkOutcome::WithinDispatch);
+ assert_eq!(tracker.committable_offsets().get(&5), Some(&150));
+ }
+
+ #[test]
+ fn mark_processed_is_clamped_to_the_dispatched_ceiling() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(3, 100);
+
+ assert_eq!(
+ tracker.mark_processed(3, 500),
+ MarkOutcome::CappedAheadOfDispatch,
+ );
+ assert_eq!(tracker.committable_offsets().get(&3), Some(&100));
+
+ assert_eq!(tracker.mark_processed(3, 80), MarkOutcome::WithinDispatch);
+ assert_eq!(tracker.committable_offsets().get(&3), Some(&100));
+ }
+
+ #[test]
+ fn mark_processed_with_no_dispatch_commits_nothing() {
+ // Route error: nothing was dispatched, so the mark clamps to the `0` sentinel and Kafka
+ // replays it.
+ let tracker = OffsetTracker::new();
+ assert_eq!(
+ tracker.mark_processed(9, 101),
+ MarkOutcome::CappedAheadOfDispatch,
+ );
+ assert_eq!(tracker.committable_offsets().get(&9), None);
+ // Still tracked (ceiling 0), just not committable.
+ assert_eq!(tracker.partition_count(), 1);
+ }
+
+ #[test]
+ fn dispatched_ceiling_is_monotonic() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(1, 50);
+ tracker.mark_dispatched(1, 200);
+ // A lower dispatch (out-of-order routing) never lowers the ceiling.
+ tracker.mark_dispatched(1, 30);
+
+ assert_eq!(tracker.mark_processed(1, 200), MarkOutcome::WithinDispatch);
+ assert_eq!(tracker.committable_offsets().get(&1), Some(&200));
+ assert_eq!(
+ tracker.mark_processed(1, 201),
+ MarkOutcome::CappedAheadOfDispatch,
+ );
+ assert_eq!(tracker.committable_offsets().get(&1), Some(&200));
+ }
+
+ #[test]
+ fn committable_offsets_snapshots_every_processed_partition() {
+ let tracker = OffsetTracker::new();
+ for (partition, next) in [(0, 10), (1, 20), (2, 30)] {
+ tracker.mark_dispatched(partition, next);
+ assert_eq!(
+ tracker.mark_processed(partition, next),
+ MarkOutcome::WithinDispatch,
+ );
+ }
+
+ let snapshot = tracker.committable_offsets();
+ assert_eq!(snapshot.len(), 3);
+ assert_eq!(snapshot.get(&0), Some(&10));
+ assert_eq!(snapshot.get(&1), Some(&20));
+ assert_eq!(snapshot.get(&2), Some(&30));
+ }
+
+ #[test]
+ fn mark_committed_advances_monotonically_only_for_known_partitions() {
+ let tracker = OffsetTracker::new();
+
+ // Committing an unprocessed partition is a no-op.
+ tracker.mark_committed(7, 100);
+ assert_eq!(tracker.committed_offset(7), None);
+
+ tracker.mark_dispatched(7, 200);
+ assert_eq!(tracker.mark_processed(7, 200), MarkOutcome::WithinDispatch);
+ assert_eq!(tracker.committed_offset(7), Some(0));
+
+ tracker.mark_committed(7, 150);
+ assert_eq!(tracker.committed_offset(7), Some(150));
+
+ // Backward commit ignored, forward advances.
+ tracker.mark_committed(7, 100);
+ assert_eq!(tracker.committed_offset(7), Some(150));
+ tracker.mark_committed(7, 200);
+ assert_eq!(tracker.committed_offset(7), Some(200));
+ }
+
+ #[test]
+ fn forget_partition_drops_only_that_partition() {
+ let tracker = OffsetTracker::new();
+ for (partition, next) in [(0, 10), (1, 20)] {
+ tracker.mark_dispatched(partition, next);
+ let _ = tracker.mark_processed(partition, next);
+ }
+
+ tracker.forget_partition(0);
+
+ assert_eq!(tracker.partition_count(), 1);
+ assert_eq!(tracker.committable_offsets().get(&0), None);
+ assert_eq!(tracker.committable_offsets().get(&1), Some(&20));
+ }
+
+ #[test]
+ fn a_hold_pins_committable_and_a_later_success_cannot_leapfrog_it() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 44);
+
+ // A failed message at offset 41 holds at its own offset (no +1).
+ tracker.hold(4, 41);
+ assert_eq!(tracker.mark_processed(4, 43), MarkOutcome::WithinDispatch);
+
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&41));
+ }
+
+ #[test]
+ fn a_hold_only_lowers_the_floor_never_raises_it() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 100);
+ let _ = tracker.mark_processed(4, 60);
+
+ tracker.hold(4, 41);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&41));
+
+ // A second, higher hold cannot raise the floor — the earlier failed message still gates it.
+ tracker.hold(4, 50);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&41));
+
+ tracker.hold(4, 30);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&30));
+ }
+
+ #[test]
+ fn forget_partition_clears_a_hold() {
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 100);
+ let _ = tracker.mark_processed(4, 60);
+ tracker.hold(4, 41);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&41));
+
+ // The next tenure starts unheld: forget drops the entry (hold included), and a fresh mark
+ // commits normally.
+ tracker.forget_partition(4);
+ tracker.mark_dispatched(4, 100);
+ let _ = tracker.mark_processed(4, 60);
+ assert_eq!(tracker.committable_offsets().get(&4), Some(&60));
+ }
+
+ #[test]
+ fn a_hold_at_offset_zero_commits_nothing_so_kafka_redelivers_it() {
+ // The very first message (offset 0) failing must not let a later success commit past it.
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 10);
+ tracker.hold(4, 0);
+ let _ = tracker.mark_processed(4, 5);
+
+ // min(processed=5, held=0) = 0, which the `> 0` filter excludes → nothing committable →
+ // Kafka replays from 0 and redelivers the held message.
+ assert_eq!(tracker.committable_offsets().get(&4), None);
+ }
+
+ #[test]
+ fn a_hold_while_processed_is_zero_commits_nothing() {
+ // A failure before any success on the partition: the `processed == 0` sentinel already blocks
+ // the commit; the hold does not change that (and does not panic on the absent processed mark).
+ let tracker = OffsetTracker::new();
+ tracker.mark_dispatched(4, 10);
+ tracker.hold(4, 3);
+
+ assert_eq!(tracker.committable_offsets().get(&4), None);
+ assert_eq!(tracker.partition_count(), 1);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/partitions/partitioner.rs b/rust/cohort-stream-processor/src/partitions/partitioner.rs
new file mode 100644
index 000000000000..18d4f26d0b35
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/partitioner.rs
@@ -0,0 +1,184 @@
+//! Kafka-compatible `murmur2` partitioner.
+//!
+//! Uses the `murmur2_random` algorithm (`(murmur2(key) & 0x7fffffff) % partitions`) — the
+//! Kafka-Java / python-kafka / Node default, not librdkafka's CRC32 `consistent_random`. The merge
+//! protocol must place a merge on the worker that owns `murmur2(hash(team, person)) mod 64`, so it
+//! reproduces that math here. Pinned by the published Kafka test vectors below.
+
+use uuid::Uuid;
+
+use crate::filters::TeamId;
+
+/// The `cohort_stream_events` partition count. All co-partitioned topics must match.
+pub const COHORT_PARTITION_COUNT: u32 = 64;
+
+const MURMUR2_SEED: u32 = 0x9747_b28c;
+const MURMUR2_M: u32 = 0x5bd1_e995;
+const MURMUR2_R: u32 = 24;
+
+/// Kafka `murmur2` hash. Returns raw `u32`; [`partition_for`] applies the positivity mask.
+pub fn murmur2(data: &[u8]) -> u32 {
+ let len = data.len();
+ let mut h = MURMUR2_SEED ^ (len as u32);
+
+ let nblocks = len / 4;
+ for block in 0..nblocks {
+ let i = block * 4;
+ let mut k = (data[i] as u32)
+ | ((data[i + 1] as u32) << 8)
+ | ((data[i + 2] as u32) << 16)
+ | ((data[i + 3] as u32) << 24);
+ k = k.wrapping_mul(MURMUR2_M);
+ k ^= k >> MURMUR2_R;
+ k = k.wrapping_mul(MURMUR2_M);
+ h = h.wrapping_mul(MURMUR2_M);
+ h ^= k;
+ }
+
+ let tail = nblocks * 4;
+ let remainder = len & 3;
+ if remainder >= 3 {
+ h ^= (data[tail + 2] as u32) << 16;
+ }
+ if remainder >= 2 {
+ h ^= (data[tail + 1] as u32) << 8;
+ }
+ if remainder >= 1 {
+ h ^= data[tail] as u32;
+ h = h.wrapping_mul(MURMUR2_M);
+ }
+
+ h ^= h >> 13;
+ h = h.wrapping_mul(MURMUR2_M);
+ h ^= h >> 15;
+ h
+}
+
+/// The partition `key` lands on: `(murmur2(key) & 0x7fffffff) % partition_count`.
+///
+/// # Panics
+/// Panics if `partition_count` is zero.
+pub fn partition_for(key: &str, partition_count: u32) -> u32 {
+ assert!(partition_count > 0, "partition_count must be non-zero");
+ (murmur2(key.as_bytes()) & 0x7fff_ffff) % partition_count
+}
+
+/// The partition key for a `(team, person)` pair: `"{team_id}:{person_id}"`. Must match the
+/// shuffler's `partition_key` exactly.
+pub fn merge_partition_key(team_id: TeamId, person: &Uuid) -> String {
+ format!("{}:{}", team_id.0, person)
+}
+
+/// The partition a `(team, person)` pair's state lives on.
+pub fn partition_of(team_id: TeamId, person: &Uuid, partition_count: u32) -> u32 {
+ partition_for(&merge_partition_key(team_id, person), partition_count)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn murmur2_matches_published_kafka_vectors() {
+ let cases: [(&[u8], i32); 6] = [
+ (b"21", -973_932_308),
+ (b"foobar", -790_332_482),
+ (b"a-little-bit-long-string", -985_981_536),
+ (b"a-little-bit-longer-string", -1_486_304_829),
+ (
+ b"lkjh234lh9fiuh90y23oiuhsafujhadof229phr9h19h89h8",
+ -58_897_971,
+ ),
+ (b"abc", 479_470_107),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(
+ murmur2(input) as i32,
+ expected,
+ "murmur2({:?}) diverged from the Kafka vector",
+ std::str::from_utf8(input).unwrap(),
+ );
+ }
+ }
+
+ #[test]
+ fn cross_language_fixture_is_pinned_at_64_and_8_partitions() {
+ // Mirrors the Node/Python self-test fixture (`murmur2.test.ts`, harness `partition.py`).
+ // Pinning both counts keeps the COHORT_PARTITION_COUNT env override from silently changing
+ // placement math: the raw hash is fixed, only the modulus varies with the configured count.
+ let key = "2:01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee";
+ assert_eq!(
+ murmur2(key.as_bytes()),
+ 989_609_914,
+ "raw murmur2 is the cross-language anchor"
+ );
+ assert_eq!(
+ partition_for(key, 64),
+ 58,
+ "production count (64) → partition 58"
+ );
+ assert_eq!(
+ partition_for(key, 8),
+ 2,
+ "frugal test-lane count (8) → partition 2"
+ );
+ }
+
+ #[test]
+ fn partition_for_masks_the_sign_bit_and_is_in_range() {
+ for key in [
+ "abc",
+ "21",
+ "foobar",
+ "2:01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ ] {
+ let partition = partition_for(key, COHORT_PARTITION_COUNT);
+ assert!(partition < COHORT_PARTITION_COUNT, "{key} out of range");
+ assert_eq!(partition, partition_for(key, COHORT_PARTITION_COUNT));
+ }
+ let negative = murmur2(b"a-little-bit-long-string") as i32;
+ assert!(negative < 0, "this vector's raw hash is negative");
+ assert!(
+ partition_for("a-little-bit-long-string", COHORT_PARTITION_COUNT)
+ < COHORT_PARTITION_COUNT
+ );
+ }
+
+ #[test]
+ fn merge_partition_key_matches_the_shuffler_format() {
+ let person = Uuid::from_u128(0x0192_8aaa_bbbb_cccc_dddd_eeee_eeee_eeee);
+ assert_eq!(
+ merge_partition_key(TeamId(42), &person),
+ format!("42:{person}"),
+ );
+ assert_eq!(
+ merge_partition_key(TeamId(2), &Uuid::nil()),
+ "2:00000000-0000-0000-0000-000000000000",
+ );
+ }
+
+ #[test]
+ fn partition_of_is_partition_for_over_the_re_key() {
+ let person = Uuid::from_u128(7);
+ assert_eq!(
+ partition_of(TeamId(42), &person, COHORT_PARTITION_COUNT),
+ partition_for(
+ &merge_partition_key(TeamId(42), &person),
+ COHORT_PARTITION_COUNT
+ ),
+ );
+ }
+
+ #[test]
+ fn distinct_persons_can_land_on_distinct_partitions() {
+ let team = TeamId(7);
+ let p0 = partition_of(team, &Uuid::from_u128(1), COHORT_PARTITION_COUNT);
+ let other = (2..1000)
+ .map(|n| partition_of(team, &Uuid::from_u128(n), COHORT_PARTITION_COUNT))
+ .find(|&p| p != p0);
+ assert!(
+ other.is_some(),
+ "expected some person to hash to a different partition"
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/partitions/rebalance.rs b/rust/cohort-stream-processor/src/partitions/rebalance.rs
new file mode 100644
index 000000000000..864d4b98216a
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/rebalance.rs
@@ -0,0 +1,539 @@
+//! The rebalance bridge: a [`ConsumerContext`] that turns Kafka's rebalance callbacks into the
+//! partition lifecycle a stateful, partition-affined consumer needs.
+//!
+//! Correctness rests on one invariant: all of a `(team_id, person_id)`'s state lives on exactly one
+//! partition → one pod → one store slice. So ownership must *move* — on revoke, reclaim the slice; on
+//! assign, record ownership.
+//!
+//! librdkafka fires `pre_rebalance`/`post_rebalance` synchronously on the poll thread, where blocking
+//! or panicking is forbidden (a panic across the FFI boundary is UB). The callbacks therefore do only
+//! fast sync work and ship the slow part (draining a worker is async I/O) to [`run_rebalance_worker`]
+//! over an mpsc channel.
+//!
+//! Cooperative-sticky can revoke a partition and immediately re-assign it to the same pod. The async
+//! cleanup re-checks ownership against current state (not the queued snapshot) and skips when the
+//! partition was re-acquired, leaving the live worker and its slice untouched — see
+//! [`EventDispatcher::revoke_partition_drain`].
+
+use std::sync::Arc;
+
+use metrics::counter;
+use rdkafka::consumer::{BaseConsumer, ConsumerContext, Rebalance};
+use rdkafka::{ClientContext, TopicPartitionList};
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+use tracing::{debug, error, info};
+
+use crate::consumers::events::EventDispatcher;
+use crate::observability::metrics::{REBALANCES_TOTAL, REBALANCE_EMPTY_SKIPPED_TOTAL};
+use crate::partitions::follower::PartitionMirror;
+
+/// Work shipped from the synchronous rebalance callbacks to the async [`run_rebalance_worker`].
+#[derive(Debug, Clone)]
+pub enum RebalanceEvent {
+ /// Reclaim these revoked partitions: drain each worker, then delete its state slice.
+ Revoke(Vec<i32>),
+ /// Partitions newly assigned.
+ Assign(Vec<i32>),
+}
+
+pub type RebalanceEventReceiver = mpsc::UnboundedReceiver<RebalanceEvent>;
+
+/// Commands from the rebalance worker to the consume loop. Currently unused.
+#[derive(Debug)]
+pub enum ConsumerCommand {
+ /// Resume consumption for these partitions.
+ Resume(TopicPartitionList),
+ /// Seek these partitions to specific offsets.
+ SeekPartitions(TopicPartitionList),
+}
+
+pub type ConsumerCommandSender = mpsc::UnboundedSender<ConsumerCommand>;
+pub type ConsumerCommandReceiver = mpsc::UnboundedReceiver<ConsumerCommand>;
+
+/// The rdkafka [`ConsumerContext`] for `cohort_stream_events`. Rebalance callbacks drive the
+/// [`EventDispatcher`]'s partition lifecycle and hand slow cleanup to the async worker.
+pub struct CohortConsumerContext {
+ dispatcher: Arc<EventDispatcher>,
+ rebalance_tx: mpsc::UnboundedSender<RebalanceEvent>,
+}
+
+impl CohortConsumerContext {
+ /// Build the context and the receiver half of its rebalance channel.
+ pub fn new(dispatcher: Arc<EventDispatcher>) -> (Self, RebalanceEventReceiver) {
+ let (rebalance_tx, rebalance_rx) = mpsc::unbounded_channel();
+ (
+ Self {
+ dispatcher,
+ rebalance_tx,
+ },
+ rebalance_rx,
+ )
+ }
+
+ /// Sync, on the poll thread: mark each revoked partition un-owned and queue async cleanup.
+ fn on_revoke(&self, partitions: &TopicPartitionList) {
+ if partitions.count() == 0 {
+ counter!(REBALANCE_EMPTY_SKIPPED_TOTAL, "event_type" => "revoke").increment(1);
+ debug!("skipping empty revoke");
+ return;
+ }
+ let partitions = partition_numbers(partitions);
+ counter!(REBALANCES_TOTAL, "event_type" => "revoke").increment(1);
+ info!(count = partitions.len(), "revoking partitions");
+ for &partition in &partitions {
+ self.dispatcher.revoke_partition_sync(partition);
+ }
+ if let Err(err) = self.rebalance_tx.send(RebalanceEvent::Revoke(partitions)) {
+ error!(error = %err, "failed to queue revoke cleanup");
+ }
+ }
+
+ /// Sync, on the poll thread: record ownership for each assigned partition.
+ fn on_assign(&self, partitions: &TopicPartitionList) {
+ if partitions.count() == 0 {
+ counter!(REBALANCE_EMPTY_SKIPPED_TOTAL, "event_type" => "assign").increment(1);
+ debug!("skipping empty assign");
+ return;
+ }
+ let partitions = partition_numbers(partitions);
+ counter!(REBALANCES_TOTAL, "event_type" => "assign").increment(1);
+ info!(count = partitions.len(), "assigned partitions");
+ for &partition in &partitions {
+ self.dispatcher.assign_partition(partition);
+ }
+ if let Err(err) = self.rebalance_tx.send(RebalanceEvent::Assign(partitions)) {
+ error!(error = %err, "failed to queue assign setup");
+ }
+ }
+}
+
+impl ClientContext for CohortConsumerContext {}
+
+impl ConsumerContext for CohortConsumerContext {
+ fn pre_rebalance(&self, _base: &BaseConsumer<Self>, rebalance: &Rebalance<'_>) {
+ match rebalance {
+ Rebalance::Revoke(partitions) => self.on_revoke(partitions),
+ Rebalance::Assign(_) => {}
+ Rebalance::Error(err) => error!(error = %err, "pre-rebalance error"),
+ }
+ }
+
+ fn post_rebalance(&self, _base: &BaseConsumer<Self>, rebalance: &Rebalance<'_>) {
+ match rebalance {
+ Rebalance::Assign(partitions) => self.on_assign(partitions),
+ Rebalance::Revoke(_) => {}
+ Rebalance::Error(err) => error!(error = %err, "post-rebalance error"),
+ }
+ }
+}
+
+/// Async rebalance worker: mirrors (un)assignments onto follower consumers and drains revoked
+/// partitions off the poll thread. Runs until shutdown or the sender is dropped.
+///
+/// Mirror calls are unconditional — even on rapid revoke→assign where the drain skips — because
+/// the followers' in-session fetch position advances past owned-gate-dropped messages and only a
+/// re-assign at `Offset::Stored` rewinds over that gap.
+pub async fn run_rebalance_worker(
+ mut events: RebalanceEventReceiver,
+ dispatcher: Arc<EventDispatcher>,
+ mirror: Arc<dyn PartitionMirror>,
+ // Currently unused; held so the command channel's receiver stays open.
+ _consumer_command_tx: ConsumerCommandSender,
+ shutdown: CancellationToken,
+) {
+ info!("rebalance worker started");
+ loop {
+ tokio::select! {
+ biased;
+ _ = shutdown.cancelled() => {
+ info!("rebalance worker stopping on shutdown signal");
+ break;
+ }
+ event = events.recv() => {
+ let Some(event) = event else {
+ info!("rebalance worker channel closed; stopping");
+ break;
+ };
+ match event {
+ RebalanceEvent::Revoke(partitions) => {
+ // Unassign followers before drain: during drain, their fetch position
+ // would advance past owned-gate-dropped messages.
+ mirror.unassign(&partitions);
+ for partition in partitions {
+ dispatcher.revoke_partition_drain(partition).await;
+ }
+ }
+ RebalanceEvent::Assign(partitions) => {
+ // Stale-slice reclamation for post-boot move-ins now happens at worker-spawn
+ // time (`EventDispatcher::ensure_worker`), under the partition's shard guard,
+ // so the wipe deterministically precedes the eviction-queue rebuild. The assign
+ // arm only mirrors followers.
+ mirror.assign(&partitions);
+ }
+ }
+ }
+ }
+ }
+}
+
+fn partition_numbers(partitions: &TopicPartitionList) -> Vec<i32> {
+ partitions
+ .elements()
+ .iter()
+ .map(|elem| elem.partition())
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Mutex;
+ use tempfile::TempDir;
+
+ use crate::filters::{CatalogHandle, FilterCatalog};
+ use crate::partitions::{MarkOutcome, OffsetTracker, PartitionRouter};
+ use crate::producer::{CaptureSink, MembershipSink};
+ use crate::store::{CohortStore, LeafStateKey, Stage1Key, StoreConfig};
+ use crate::workers::MergeWorkerDeps;
+ use uuid::Uuid;
+
+ const TOPIC: &str = "cohort_stream_events";
+
+ fn tpl(partitions: &[i32]) -> TopicPartitionList {
+ let mut list = TopicPartitionList::new();
+ for &partition in partitions {
+ list.add_partition(TOPIC, partition);
+ }
+ list
+ }
+
+ fn test_dispatcher() -> (TempDir, Arc<EventDispatcher>, Arc<OffsetTracker>) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])));
+ let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
+ let tracker = Arc::new(OffsetTracker::new());
+ let dispatcher = EventDispatcher::new(
+ PartitionRouter::new(64),
+ tracker.clone(),
+ store,
+ catalog,
+ sink,
+ MergeWorkerDeps::capture(),
+ );
+ (dir, Arc::new(dispatcher), tracker)
+ }
+
+ #[derive(Debug, Clone, PartialEq, Eq)]
+ enum MirrorCall {
+ Assign(Vec<i32>),
+ Unassign(Vec<i32>),
+ }
+
+ /// Records mirror calls. At unassign time, snapshots whether the tracker still held the
+ /// partition's entry (proving unassign ran before drain).
+ struct RecordingMirror {
+ tracker: Arc<OffsetTracker>,
+ calls: Mutex<Vec<MirrorCall>>,
+ unassign_saw_tracker_entry: Mutex<Vec<bool>>,
+ }
+
+ impl RecordingMirror {
+ fn new(tracker: Arc<OffsetTracker>) -> Arc<Self> {
+ Arc::new(Self {
+ tracker,
+ calls: Mutex::new(Vec::new()),
+ unassign_saw_tracker_entry: Mutex::new(Vec::new()),
+ })
+ }
+
+ fn calls(&self) -> Vec<MirrorCall> {
+ self.calls.lock().unwrap().clone()
+ }
+ }
+
+ impl PartitionMirror for RecordingMirror {
+ fn assign(&self, partitions: &[i32]) {
+ self.calls
+ .lock()
+ .unwrap()
+ .push(MirrorCall::Assign(partitions.to_vec()));
+ }
+
+ fn unassign(&self, partitions: &[i32]) {
+ let offsets = self.tracker.committable_offsets();
+ let saw_all = partitions
+ .iter()
+ .all(|partition| offsets.contains_key(partition));
+ self.unassign_saw_tracker_entry
+ .lock()
+ .unwrap()
+ .push(saw_all);
+ self.calls
+ .lock()
+ .unwrap()
+ .push(MirrorCall::Unassign(partitions.to_vec()));
+ }
+ }
+
+ async fn run_worker_to_completion(
+ events: RebalanceEventReceiver,
+ dispatcher: Arc<EventDispatcher>,
+ mirror: Arc<RecordingMirror>,
+ ) {
+ let (cmd_tx, _cmd_rx) = mpsc::unbounded_channel();
+ run_rebalance_worker(events, dispatcher, mirror, cmd_tx, CancellationToken::new()).await;
+ }
+
+ #[test]
+ fn partition_numbers_extracts_each_partition() {
+ let mut numbers = partition_numbers(&tpl(&[3, 7, 1]));
+ numbers.sort_unstable();
+ assert_eq!(numbers, vec![1, 3, 7]);
+ }
+
+ #[test]
+ fn empty_tpl_has_zero_count() {
+ assert_eq!(TopicPartitionList::new().count(), 0);
+ assert_eq!(tpl(&[0]).count(), 1);
+ }
+
+ #[tokio::test]
+ async fn on_assign_records_ownership_and_queues_an_assign_event() {
+ let (_dir, dispatcher, _tracker) = test_dispatcher();
+ let (ctx, mut rx) = CohortConsumerContext::new(dispatcher.clone());
+
+ ctx.on_assign(&tpl(&[0, 1, 4]));
+
+ assert!(dispatcher.owns(0) && dispatcher.owns(1) && dispatcher.owns(4));
+ assert!(!dispatcher.owns(2));
+ match rx.try_recv().expect("an assign event was queued") {
+ RebalanceEvent::Assign(mut partitions) => {
+ partitions.sort_unstable();
+ assert_eq!(partitions, vec![0, 1, 4]);
+ }
+ other => panic!("expected Assign, got {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn on_revoke_clears_ownership_and_queues_a_revoke_event() {
+ let (_dir, dispatcher, _tracker) = test_dispatcher();
+ let (ctx, mut rx) = CohortConsumerContext::new(dispatcher.clone());
+
+ ctx.on_assign(&tpl(&[0, 1]));
+ assert!(
+ matches!(rx.try_recv(), Ok(RebalanceEvent::Assign(_))),
+ "assign is queued first",
+ );
+ ctx.on_revoke(&tpl(&[1]));
+
+ assert!(dispatcher.owns(0), "unrevoked partition stays owned");
+ assert!(!dispatcher.owns(1), "revoked partition is un-owned");
+ match rx.try_recv().expect("a revoke event was queued") {
+ RebalanceEvent::Revoke(partitions) => assert_eq!(partitions, vec![1]),
+ other => panic!("expected Revoke, got {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn empty_callbacks_are_noops_and_queue_nothing() {
+ let (_dir, dispatcher, _tracker) = test_dispatcher();
+ let (ctx, mut rx) = CohortConsumerContext::new(dispatcher.clone());
+
+ ctx.on_assign(&tpl(&[]));
+ ctx.on_revoke(&tpl(&[]));
+
+ assert!(!dispatcher.owns(0));
+ assert!(
+ rx.try_recv().is_err(),
+ "an empty callback must not queue work",
+ );
+ }
+
+ #[tokio::test]
+ async fn assign_event_mirrors_the_followers() {
+ let (_dir, dispatcher, tracker) = test_dispatcher();
+ let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
+ let mirror = RecordingMirror::new(tracker);
+
+ ctx.on_assign(&tpl(&[0, 4]));
+ drop(ctx);
+ run_worker_to_completion(rx, dispatcher, mirror.clone()).await;
+
+ assert_eq!(mirror.calls(), vec![MirrorCall::Assign(vec![0, 4])]);
+ }
+
+ #[tokio::test]
+ async fn revoke_unassigns_the_followers_before_the_drain() {
+ let (_dir, dispatcher, tracker) = test_dispatcher();
+ let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
+ let mirror = RecordingMirror::new(tracker.clone());
+
+ // Seed a committable entry the drain will forget — the order probe.
+ tracker.mark_dispatched(3, 10);
+ assert_eq!(tracker.mark_processed(3, 10), MarkOutcome::WithinDispatch);
+
+ ctx.on_assign(&tpl(&[3]));
+ ctx.on_revoke(&tpl(&[3]));
+ drop(ctx);
+ run_worker_to_completion(rx, dispatcher.clone(), mirror.clone()).await;
+
+ assert_eq!(
+ mirror.calls(),
+ vec![MirrorCall::Assign(vec![3]), MirrorCall::Unassign(vec![3])],
+ );
+ assert_eq!(
+ *mirror.unassign_saw_tracker_entry.lock().unwrap(),
+ vec![true],
+ "the tracker entry was still live at unassign time, so the unassign ran before the drain",
+ );
+ assert!(
+ !tracker.committable_offsets().contains_key(&3),
+ "the drain then forgot the revoked partition's entry",
+ );
+ assert!(!dispatcher.owns(3));
+ }
+
+ fn slice_key(partition: u16) -> Stage1Key {
+ Stage1Key {
+ partition_id: partition,
+ team_id: 7,
+ leaf_state_key: LeafStateKey([0xAB; 16]),
+ person_id: Uuid::from_u128(1),
+ }
+ }
+
+ fn seed_slice(dispatcher: &EventDispatcher, partition: u16) {
+ dispatcher
+ .store()
+ .write_batch(|b| b.put_stage1(&slice_key(partition), b"state"))
+ .unwrap();
+ }
+
+ /// Probe whether `partition`'s slice is present without seeding it, so the caller controls seed
+ /// ordering relative to a boot reconcile.
+ fn present_probe(dispatcher: &EventDispatcher, partition: u16) -> impl Fn() -> bool + '_ {
+ move || {
+ dispatcher
+ .store()
+ .get_stage1(&slice_key(partition))
+ .unwrap()
+ .is_some()
+ }
+ }
+
+ fn seed_and_present(dispatcher: &EventDispatcher, partition: u16) -> impl Fn() -> bool + '_ {
+ seed_slice(dispatcher, partition);
+ present_probe(dispatcher, partition)
+ }
+
+ #[tokio::test]
+ async fn assign_arm_does_not_reclaim_slices_reclamation_is_deferred_to_worker_spawn() {
+ // The rebalance Assign arm only mirrors followers; it never wipes a slice. A post-boot move-in's
+ // stale slice is reclaimed at `ensure_worker` spawn time instead (under the shard guard, before
+ // the eviction-queue rebuild), so the slice survives the assign path until the first event —
+ // regardless of the durable-restore gate.
+ for durable_on in [false, true] {
+ let (_dir, dispatcher, tracker) = test_dispatcher();
+ if durable_on {
+ dispatcher.enable_durable_restore();
+ }
+ // Snapshot excludes 3; seeding *after* reconcile keeps the boot wipe from deleting it, so
+ // only the (now inert) assign path could have wiped it.
+ dispatcher.reconcile_boot_assignment(&[0].into_iter().collect(), 64);
+ let present = seed_and_present(&dispatcher, 3);
+ let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
+ let mirror = RecordingMirror::new(tracker);
+ ctx.on_assign(&tpl(&[3]));
+ drop(ctx);
+ run_worker_to_completion(rx, dispatcher.clone(), mirror).await;
+ assert!(
+ present(),
+ "the assign arm leaves the slice in place (durable_on={durable_on}); reclamation is deferred to spawn",
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn durable_boot_assign_keeps_restored_slices() {
+ // The pod's own initial assignment routes through the assign path; the restored slices for the
+ // assigned partitions must survive it (the assign arm never wipes; spawn-time reclaim keeps
+ // boot-snapshot partitions).
+ let (_dir, dispatcher, tracker) = test_dispatcher();
+ dispatcher.enable_durable_restore();
+ seed_slice(&dispatcher, 0);
+ seed_slice(&dispatcher, 1);
+ let present_0 = present_probe(&dispatcher, 0);
+ let present_1 = present_probe(&dispatcher, 1);
+ dispatcher.reconcile_boot_assignment(&[0, 1].into_iter().collect(), 64);
+
+ let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
+ let mirror = RecordingMirror::new(tracker);
+ ctx.on_assign(&tpl(&[0, 1]));
+ drop(ctx);
+ run_worker_to_completion(rx, dispatcher.clone(), mirror).await;
+
+ assert!(present_0() && present_1(), "boot-assigned slices survive");
+ }
+
+ #[tokio::test]
+ async fn durable_assign_before_boot_reconcile_keeps_slices() {
+ // The rebalance worker can process the initial Assign before the consume loop records the
+ // snapshot; the assign path never wipes, so the slices survive until they are either reopened
+ // live or reclaimed at spawn time.
+ let (_dir, dispatcher, tracker) = test_dispatcher();
+ dispatcher.enable_durable_restore();
+ seed_slice(&dispatcher, 0);
+ seed_slice(&dispatcher, 1);
+ let present_0 = present_probe(&dispatcher, 0);
+ let present_1 = present_probe(&dispatcher, 1);
+
+ let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
+ let mirror = RecordingMirror::new(tracker);
+ ctx.on_assign(&tpl(&[0, 1]));
+ drop(ctx);
+ run_worker_to_completion(rx, dispatcher.clone(), mirror).await;
+
+ assert!(
+ present_0() && present_1(),
+ "with no snapshot yet, the assign path skips and the slices survive",
+ );
+ }
+
+ #[tokio::test]
+ async fn rapid_revoke_assign_mirrors_both_calls_unconditionally() {
+ let (_dir, dispatcher, tracker) = test_dispatcher();
+ let (ctx, rx) = CohortConsumerContext::new(dispatcher.clone());
+ let mirror = RecordingMirror::new(tracker.clone());
+
+ tracker.mark_dispatched(3, 10);
+ assert_eq!(tracker.mark_processed(3, 10), MarkOutcome::WithinDispatch);
+
+ ctx.on_assign(&tpl(&[3]));
+ ctx.on_revoke(&tpl(&[3]));
+ ctx.on_assign(&tpl(&[3]));
+ drop(ctx);
+ run_worker_to_completion(rx, dispatcher.clone(), mirror.clone()).await;
+
+ assert_eq!(
+ mirror.calls(),
+ vec![
+ MirrorCall::Assign(vec![3]),
+ MirrorCall::Unassign(vec![3]),
+ MirrorCall::Assign(vec![3]),
+ ],
+ );
+ assert!(dispatcher.owns(3), "the rapid re-assign restored ownership");
+ assert_eq!(
+ tracker.committable_offsets().get(&3),
+ Some(&10),
+ "drain skipped for re-acquired partition, so tracker entry survives",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/partitions/router.rs b/rust/cohort-stream-processor/src/partitions/router.rs
new file mode 100644
index 000000000000..17193b4ea1f4
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/router.rs
@@ -0,0 +1,408 @@
+//! Partition-affined routing. Maps a `cohort_stream_events` partition to its owning worker's
+//! bounded channel and dispatches per-partition sub-batches, so every state mutation for a given
+//! `(team_id, person_id)` serializes through exactly one worker.
+//!
+//! A slow partition cannot stall the rest: the `DashMap` guard is cloned (dropped) before any
+//! `.await`, and per-partition sends fan out concurrently via `join_all`.
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+use dashmap::mapref::entry::Entry;
+use dashmap::DashMap;
+use futures::future::join_all;
+use metrics::{counter, gauge};
+use thiserror::Error;
+use tokio::sync::mpsc;
+use tracing::warn;
+
+use super::shuffle_message::ShuffleMessage;
+use crate::observability::metrics::{
+ PARTITIONS_ACTIVE, PARTITION_CHANNEL_DEPTH, PARTITION_ROUTE_DROPPED_TOTAL,
+};
+
+const REASON_NO_WORKER: &str = "no_worker";
+const REASON_CHANNEL_CLOSED: &str = "channel_closed";
+
+/// A per-partition routing failure. The target worker is gone (usually revoked mid-rebalance);
+/// dropped messages are recovered when Kafka replays the uncommitted offsets.
+#[derive(Debug, Error, PartialEq, Eq)]
+pub enum RouteError {
+ /// No worker channel registered for the partition (never assigned, or already revoked).
+ #[error("no worker for partition {partition}: not assigned or revoked ({dropped} message(s) dropped)")]
+ NoWorker { partition: i32, dropped: usize },
+
+ /// The channel exists but its receiver was dropped, so the worker has stopped.
+ #[error("worker channel for partition {partition} is closed ({dropped} message(s) dropped)")]
+ ChannelClosed { partition: i32, dropped: usize },
+}
+
+/// Routes per-partition sub-batches to long-lived per-partition worker channels.
+pub struct PartitionRouter {
+ senders: DashMap<i32, mpsc::Sender<Vec<ShuffleMessage>>>,
+ channel_buffer: usize,
+ /// Terminal: set by [`clear`](Self::clear), never unset. Read under the shard guard so no
+ /// sender can be registered after the clear's removal pass.
+ closed: AtomicBool,
+}
+
+impl PartitionRouter {
+ pub fn new(channel_buffer: usize) -> Self {
+ Self {
+ senders: DashMap::new(),
+ channel_buffer,
+ closed: AtomicBool::new(false),
+ }
+ }
+
+ /// Register a worker channel for `partition` and return its `Receiver`.
+ ///
+ /// Returns `None` if: already registered with a live channel (reuses existing), or the router
+ /// is closed. If the existing channel is dead (receiver dropped), replaces it (self-heal).
+ pub fn add_partition(&self, partition: i32) -> Option<mpsc::Receiver<Vec<ShuffleMessage>>> {
+ let entry = self.senders.entry(partition);
+ if self.closed.load(Ordering::SeqCst) {
+ drop(entry);
+ warn!(
+ partition,
+ "router is closed (cleared for shutdown); refusing to register a worker channel"
+ );
+ return None;
+ }
+ let receiver = match entry {
+ Entry::Occupied(mut slot) => {
+ if slot.get().is_closed() {
+ let (sender, receiver) = mpsc::channel(self.channel_buffer);
+ slot.insert(sender);
+ warn!(
+ partition,
+ "replacing closed worker channel on reassign (previous worker exited without revoke)"
+ );
+ Some(receiver)
+ } else {
+ warn!(
+ partition,
+ "partition already registered; reusing the existing worker channel"
+ );
+ None
+ }
+ }
+ Entry::Vacant(slot) => {
+ let (sender, receiver) = mpsc::channel(self.channel_buffer);
+ slot.insert(sender);
+ Some(receiver)
+ }
+ };
+ if receiver.is_some() {
+ self.emit_active_gauge();
+ }
+ receiver
+ }
+
+ /// Drop the sender for `partition`, signalling the worker to shut down. Idempotent.
+ pub fn remove_partition(&self, partition: i32) {
+ if self.senders.remove(&partition).is_some() {
+ self.emit_active_gauge();
+ }
+ }
+
+ /// Drop every sender and terminally close the router. All later `add_partition` calls refuse.
+ pub fn clear(&self) {
+ self.closed.store(true, Ordering::SeqCst);
+ self.senders.clear();
+ self.emit_active_gauge();
+ }
+
+ /// Whether the router has been terminally closed.
+ pub fn is_closed(&self) -> bool {
+ self.closed.load(Ordering::SeqCst)
+ }
+
+ /// Group a batch by partition and dispatch each sub-batch to its worker, preserving
+ /// per-partition order. Per-partition failures are collected rather than aborting the batch.
+ pub async fn route_batch(&self, messages: Vec<(i32, ShuffleMessage)>) -> Vec<RouteError> {
+ if messages.is_empty() {
+ return Vec::new();
+ }
+
+ let mut by_partition: HashMap<i32, Vec<ShuffleMessage>> = HashMap::new();
+ for (partition, message) in messages {
+ by_partition.entry(partition).or_default().push(message);
+ }
+
+ let sends = by_partition
+ .into_iter()
+ .map(|(partition, batch)| self.send_to_partition(partition, batch));
+ join_all(sends).await.into_iter().flatten().collect()
+ }
+
+ async fn send_to_partition(
+ &self,
+ partition: i32,
+ batch: Vec<ShuffleMessage>,
+ ) -> Option<RouteError> {
+ let dropped = batch.len();
+
+ let Some(sender) = self.sender_for(partition) else {
+ self.record_drop(partition, dropped, REASON_NO_WORKER);
+ return Some(RouteError::NoWorker { partition, dropped });
+ };
+
+ match sender.send(batch).await {
+ Ok(()) => {
+ self.emit_channel_depth(partition, &sender);
+ None
+ }
+ Err(mpsc::error::SendError(returned)) => {
+ self.record_drop(partition, returned.len(), REASON_CHANNEL_CLOSED);
+ Some(RouteError::ChannelClosed {
+ partition,
+ dropped: returned.len(),
+ })
+ }
+ }
+ }
+
+ pub fn partition_count(&self) -> usize {
+ self.senders.len()
+ }
+
+ fn sender_for(&self, partition: i32) -> Option<mpsc::Sender<Vec<ShuffleMessage>>> {
+ let sender = self.senders.get(&partition)?;
+ Some(sender.clone())
+ }
+
+ fn record_drop(&self, partition: i32, dropped: usize, reason: &'static str) {
+ warn!(
+ partition,
+ dropped, reason, "dropped messages while routing: target worker is gone"
+ );
+ counter!(PARTITION_ROUTE_DROPPED_TOTAL, "reason" => reason).increment(dropped as u64);
+ }
+
+ fn emit_channel_depth(&self, partition: i32, sender: &mpsc::Sender<Vec<ShuffleMessage>>) {
+ let depth = sender.max_capacity().saturating_sub(sender.capacity());
+ gauge!(PARTITION_CHANNEL_DEPTH, "partition" => partition.to_string()).set(depth as f64);
+ }
+
+ fn emit_active_gauge(&self) {
+ gauge!(PARTITIONS_ACTIVE).set(self.senders.len() as f64);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::consumers::events::CohortStreamEvent;
+ use futures::future::FutureExt;
+
+ fn event(tag: i64) -> ShuffleMessage {
+ ShuffleMessage::Event {
+ event: CohortStreamEvent {
+ team_id: 1,
+ person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ distinct_id: "d".to_string(),
+ uuid: "u".to_string(),
+ event: "$pageview".to_string(),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ properties: None,
+ person_properties: None,
+ elements_chain: None,
+ source_offset: tag,
+ source_partition: 0,
+ redirected_from: None,
+ redirect_hops: 0,
+ },
+ cse_offset: 0,
+ }
+ }
+
+ fn tags(batch: &[ShuffleMessage]) -> Vec<i64> {
+ batch
+ .iter()
+ .map(|message| match message {
+ ShuffleMessage::Event { event, .. } => event.source_offset,
+ ShuffleMessage::Sweep { .. }
+ | ShuffleMessage::Merge { .. }
+ | ShuffleMessage::Transfer { .. }
+ | ShuffleMessage::Cascade { .. }
+ | ShuffleMessage::RedrivePendingTransfers
+ | ShuffleMessage::MergeCfGc { .. } => {
+ unreachable!("router tests route only events")
+ }
+ })
+ .collect()
+ }
+
+ #[tokio::test]
+ async fn same_partition_messages_land_on_one_channel_in_order_isolated_per_partition() {
+ let router = PartitionRouter::new(16);
+ let mut rx5 = router
+ .add_partition(5)
+ .expect("first add returns the receiver");
+ let mut rx6 = router
+ .add_partition(6)
+ .expect("first add returns the receiver");
+
+ let errors = router
+ .route_batch(vec![(5, event(1)), (6, event(2)), (5, event(3))])
+ .await;
+ assert!(errors.is_empty(), "no worker should be missing");
+
+ assert_eq!(tags(&rx5.recv().await.unwrap()), vec![1, 3]);
+ assert_eq!(tags(&rx6.recv().await.unwrap()), vec![2]);
+
+ assert!(router.route_batch(vec![(5, event(4))]).await.is_empty());
+ assert_eq!(tags(&rx5.recv().await.unwrap()), vec![4]);
+ }
+
+ #[tokio::test]
+ async fn routing_to_a_removed_partition_surfaces_an_error_without_panicking() {
+ let router = PartitionRouter::new(16);
+ let _rx5 = router.add_partition(5).unwrap();
+
+ router.remove_partition(5);
+ assert_eq!(router.partition_count(), 0);
+
+ let errors = router.route_batch(vec![(5, event(1))]).await;
+ assert_eq!(
+ errors,
+ vec![RouteError::NoWorker {
+ partition: 5,
+ dropped: 1
+ }]
+ );
+ }
+
+ #[tokio::test]
+ async fn re_adding_a_partition_after_removal_routes_cleanly() {
+ let router = PartitionRouter::new(16);
+ let _rx_old = router.add_partition(5).unwrap();
+ router.remove_partition(5);
+
+ let mut rx_new = router
+ .add_partition(5)
+ .expect("re-add after removal yields a fresh receiver");
+ assert!(router.route_batch(vec![(5, event(9))]).await.is_empty());
+ assert_eq!(tags(&rx_new.recv().await.unwrap()), vec![9]);
+ }
+
+ #[tokio::test]
+ async fn re_adding_an_active_partition_reuses_the_channel() {
+ let router = PartitionRouter::new(16);
+ let mut rx = router.add_partition(5).unwrap();
+
+ assert!(router.add_partition(5).is_none());
+ assert_eq!(router.partition_count(), 1);
+
+ assert!(router.route_batch(vec![(5, event(1))]).await.is_empty());
+ assert_eq!(tags(&rx.recv().await.unwrap()), vec![1]);
+ }
+
+ #[tokio::test]
+ async fn routing_after_the_worker_dropped_its_receiver_reports_channel_closed() {
+ let router = PartitionRouter::new(16);
+ let rx = router.add_partition(5).unwrap();
+ drop(rx);
+
+ let errors = router.route_batch(vec![(5, event(1)), (5, event(2))]).await;
+ assert_eq!(
+ errors,
+ vec![RouteError::ChannelClosed {
+ partition: 5,
+ dropped: 2
+ }]
+ );
+ }
+
+ #[tokio::test]
+ async fn mixed_batch_with_one_missing_partition_routes_the_rest() {
+ let router = PartitionRouter::new(16);
+ let mut rx5 = router.add_partition(5).unwrap();
+
+ let errors = router
+ .route_batch(vec![(5, event(1)), (7, event(2)), (5, event(3))])
+ .await;
+
+ assert_eq!(
+ errors,
+ vec![RouteError::NoWorker {
+ partition: 7,
+ dropped: 1
+ }]
+ );
+ assert_eq!(tags(&rx5.recv().await.unwrap()), vec![1, 3]);
+ }
+
+ #[tokio::test]
+ async fn empty_batch_is_a_no_op() {
+ let router = PartitionRouter::new(16);
+ assert!(router.route_batch(vec![]).await.is_empty());
+ }
+
+ #[tokio::test]
+ async fn route_batch_fans_out_so_a_full_channel_does_not_block_other_partitions() {
+ let router = PartitionRouter::new(1);
+ let mut rx1 = router.add_partition(1).unwrap();
+ let mut rx2 = router.add_partition(2).unwrap();
+
+ assert!(router.route_batch(vec![(1, event(100))]).await.is_empty());
+
+ let routed = router.route_batch(vec![(1, event(1)), (2, event(2))]);
+ tokio::pin!(routed);
+
+ assert!(
+ routed.as_mut().now_or_never().is_none(),
+ "route_batch must stay pending while partition 1 is backpressured"
+ );
+
+ assert_eq!(tags(&rx2.try_recv().unwrap()), vec![2]);
+
+ assert_eq!(tags(&rx1.try_recv().unwrap()), vec![100]);
+ assert!(rx1.try_recv().is_err());
+ }
+
+ #[tokio::test]
+ async fn clear_closes_the_router_so_add_partition_refuses() {
+ let router = PartitionRouter::new(16);
+ let mut rx = router.add_partition(5).unwrap();
+
+ router.clear();
+ assert!(router.is_closed());
+ assert!(rx.recv().await.is_none(), "clear dropped the live sender");
+
+ assert!(
+ router.add_partition(5).is_none(),
+ "re-registration after clear is refused",
+ );
+ assert!(
+ router.add_partition(6).is_none(),
+ "first-time registration after clear is refused too",
+ );
+ assert_eq!(router.partition_count(), 0, "nothing was inserted");
+
+ let errors = router.route_batch(vec![(5, event(1))]).await;
+ assert_eq!(
+ errors,
+ vec![RouteError::NoWorker {
+ partition: 5,
+ dropped: 1
+ }]
+ );
+ }
+
+ #[tokio::test]
+ async fn re_adding_a_partition_whose_worker_died_without_revoke_self_heals() {
+ let router = PartitionRouter::new(16);
+ let rx_dead = router.add_partition(5).unwrap();
+ drop(rx_dead);
+
+ let mut rx_new = router
+ .add_partition(5)
+ .expect("closed slot self-heals to a fresh receiver");
+ assert_eq!(router.partition_count(), 1);
+
+ assert!(router.route_batch(vec![(5, event(7))]).await.is_empty());
+ assert_eq!(tags(&rx_new.recv().await.unwrap()), vec![7]);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
new file mode 100644
index 000000000000..bc44d90b449d
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
@@ -0,0 +1,237 @@
+//! The typed unit of work the partition router dispatches to a partition worker.
+
+use crate::cascade::CascadeMessage;
+use crate::consumers::events::CohortStreamEvent;
+use crate::merge::transfer::{MergeStateTransfer, PersonMergeEvent};
+
+/// A unit of work routed to the partition worker that owns its `(team_id, person_id)` key.
+#[derive(Debug)]
+#[allow(clippy::large_enum_variant)]
+pub enum ShuffleMessage {
+ /// A re-keyed event from `cohort_stream_events`, paired with its offset (`cse_offset`).
+ /// The worker marks this offset processed only after membership changes are produced and acked.
+ /// Unboxed: events are the hot path.
+ Event {
+ event: CohortStreamEvent,
+ cse_offset: i64,
+ },
+ /// A time-driven eviction tick with the cutoff `due_before_ms`. Serialized on the same channel
+ /// as events so the worker processes it in order with no locks.
+ Sweep { due_before_ms: i64 },
+ /// A merge trigger from `KAFKA_PERSON_MERGE_EVENTS` (keyed by P_old), paired with its topic
+ /// offset. Marked on the merge tracker, not the events tracker.
+ Merge {
+ event: PersonMergeEvent,
+ offset: i64,
+ },
+ /// A state transfer from `cohort_merge_state_transfer` (keyed by P_new), paired with its topic
+ /// offset. Boxed because it's rare and large.
+ Transfer {
+ transfer: Box<MergeStateTransfer>,
+ offset: i64,
+ },
+ /// A cohort flip from `cohort_cascade_events` (keyed by `hash(team_id, person_id)`), paired with
+ /// its topic offset. Marked on the cascade tracker, not the events tracker. Boxed because it's
+ /// rare.
+ Cascade {
+ message: Box<CascadeMessage>,
+ offset: i64,
+ },
+ /// Periodic tick to re-produce any `cf_pending_transfers` entries left by a failed produce.
+ RedrivePendingTransfers,
+ /// Periodic tick to garbage-collect expired merge idempotence markers and tombstones. Both
+ /// cutoffs are computed at tick time by the sweeper (`now − retention`), so the worker stays
+ /// clock-free — same posture as [`Sweep`](ShuffleMessage::Sweep)'s `due_before_ms`. Marker CFs
+ /// (`cf_merge_drains_applied`, `cf_merge_applied`) evict below `marker_cutoff_ms`; tombstones
+ /// (`cf_merge_tombstones`) evict below `tombstone_cutoff_ms`.
+ MergeCfGc {
+ marker_cutoff_ms: i64,
+ tombstone_cutoff_ms: i64,
+ },
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use uuid::Uuid;
+
+ use crate::producer::{CohortMembershipChange, MembershipStatus};
+
+ fn sample_cascade() -> CascadeMessage {
+ CascadeMessage {
+ change: CohortMembershipChange {
+ team_id: 1,
+ cohort_id: 42,
+ person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ last_updated: "2026-05-26 12:34:56.789000".to_string(),
+ status: MembershipStatus::Entered,
+ },
+ source_offset: 9,
+ depth: 1,
+ originating_cohort_id: 42,
+ cascade_chain: vec![42],
+ }
+ }
+
+ fn sample_event(source_offset: i64) -> CohortStreamEvent {
+ CohortStreamEvent {
+ team_id: 1,
+ person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ distinct_id: "d".to_string(),
+ uuid: "u".to_string(),
+ event: "$pageview".to_string(),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ properties: None,
+ person_properties: None,
+ elements_chain: None,
+ source_offset,
+ source_partition: 3,
+ redirected_from: None,
+ redirect_hops: 0,
+ }
+ }
+
+ fn sample_merge() -> PersonMergeEvent {
+ PersonMergeEvent {
+ team_id: 1,
+ old_person_uuid: Uuid::from_u128(1),
+ new_person_uuid: Uuid::from_u128(2),
+ merged_at_ms: 1_716_800_000_000,
+ schema_version: 1,
+ }
+ }
+
+ fn sample_transfer() -> MergeStateTransfer {
+ MergeStateTransfer {
+ team_id: 1,
+ old_person_uuid: Uuid::from_u128(1),
+ new_person_uuid: Uuid::from_u128(2),
+ merged_at_ms: 1_716_800_000_000,
+ source_partition: 3,
+ source_offset: 9,
+ leaves: vec![],
+ forward_hops: 0,
+ }
+ }
+
+ #[test]
+ fn event_variant_carries_event_and_cse_offset() {
+ let message = ShuffleMessage::Event {
+ event: sample_event(42),
+ cse_offset: 7,
+ };
+
+ // No wildcard, so a new variant forces this test to be revisited.
+ match message {
+ ShuffleMessage::Event { event, cse_offset } => {
+ assert_eq!(event.source_offset, 42);
+ assert_eq!(event.source_partition, 3);
+ assert_eq!(cse_offset, 7);
+ }
+ ShuffleMessage::Sweep { .. }
+ | ShuffleMessage::Merge { .. }
+ | ShuffleMessage::Transfer { .. }
+ | ShuffleMessage::RedrivePendingTransfers
+ | ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::Cascade { .. } => unreachable!("constructed an Event"),
+ }
+ }
+
+ #[test]
+ fn sweep_variant_carries_the_due_before_cutoff() {
+ let message = ShuffleMessage::Sweep {
+ due_before_ms: 1_700_000_000_000,
+ };
+ match message {
+ ShuffleMessage::Sweep { due_before_ms } => assert_eq!(due_before_ms, 1_700_000_000_000),
+ ShuffleMessage::Event { .. }
+ | ShuffleMessage::Merge { .. }
+ | ShuffleMessage::Transfer { .. }
+ | ShuffleMessage::RedrivePendingTransfers
+ | ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::Cascade { .. } => unreachable!("constructed a Sweep"),
+ }
+ }
+
+ #[test]
+ fn merge_cf_gc_variant_carries_both_cutoffs() {
+ let message = ShuffleMessage::MergeCfGc {
+ marker_cutoff_ms: 100,
+ tombstone_cutoff_ms: 200,
+ };
+ match message {
+ ShuffleMessage::MergeCfGc {
+ marker_cutoff_ms,
+ tombstone_cutoff_ms,
+ } => {
+ assert_eq!(marker_cutoff_ms, 100);
+ assert_eq!(tombstone_cutoff_ms, 200);
+ }
+ ShuffleMessage::Event { .. }
+ | ShuffleMessage::Sweep { .. }
+ | ShuffleMessage::Merge { .. }
+ | ShuffleMessage::Transfer { .. }
+ | ShuffleMessage::RedrivePendingTransfers
+ | ShuffleMessage::Cascade { .. } => unreachable!("constructed a MergeCfGc"),
+ }
+ }
+
+ #[test]
+ fn merge_and_transfer_variants_carry_their_own_topic_offsets() {
+ let merge = ShuffleMessage::Merge {
+ event: sample_merge(),
+ offset: 11,
+ };
+ match merge {
+ ShuffleMessage::Merge { event, offset } => {
+ assert_eq!(event.old_person_uuid, Uuid::from_u128(1));
+ assert_eq!(offset, 11);
+ }
+ ShuffleMessage::Event { .. }
+ | ShuffleMessage::Sweep { .. }
+ | ShuffleMessage::Transfer { .. }
+ | ShuffleMessage::RedrivePendingTransfers
+ | ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::Cascade { .. } => unreachable!("constructed a Merge"),
+ }
+
+ let transfer = ShuffleMessage::Transfer {
+ transfer: Box::new(sample_transfer()),
+ offset: 23,
+ };
+ match transfer {
+ ShuffleMessage::Transfer { transfer, offset } => {
+ assert_eq!(transfer.new_person_uuid, Uuid::from_u128(2));
+ assert_eq!(offset, 23);
+ }
+ ShuffleMessage::Event { .. }
+ | ShuffleMessage::Sweep { .. }
+ | ShuffleMessage::Merge { .. }
+ | ShuffleMessage::RedrivePendingTransfers
+ | ShuffleMessage::MergeCfGc { .. }
+ | ShuffleMessage::Cascade { .. } => unreachable!("constructed a Transfer"),
+ }
+ }
+
+ #[test]
+ fn cascade_variant_carries_the_boxed_message_and_offset() {
+ let message = ShuffleMessage::Cascade {
+ message: Box::new(sample_cascade()),
+ offset: 31,
+ };
+ match message {
+ ShuffleMessage::Cascade { message, offset } => {
+ assert_eq!(message.change.cohort_id, 42);
+ assert_eq!(message.depth, 1);
+ assert_eq!(message.cascade_chain, vec![42]);
+ assert_eq!(offset, 31);
+ }
+ ShuffleMessage::Event { .. }
+ | ShuffleMessage::Sweep { .. }
+ | ShuffleMessage::Merge { .. }
+ | ShuffleMessage::Transfer { .. }
+ | ShuffleMessage::RedrivePendingTransfers
+ | ShuffleMessage::MergeCfGc { .. } => unreachable!("constructed a Cascade"),
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/producer/batcher.rs b/rust/cohort-stream-processor/src/producer/batcher.rs
new file mode 100644
index 000000000000..0b659e30ad60
--- /dev/null
+++ b/rust/cohort-stream-processor/src/producer/batcher.rs
@@ -0,0 +1,63 @@
+//! Per-worker output buffer.
+
+use crate::producer::CohortMembershipChange;
+
+#[derive(Debug, Default)]
+pub struct OutputBuffer {
+ changes: Vec<CohortMembershipChange>,
+}
+
+impl OutputBuffer {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn push(&mut self, change: CohortMembershipChange) {
+ self.changes.push(change);
+ }
+
+ pub fn extend(&mut self, changes: impl IntoIterator<Item = CohortMembershipChange>) {
+ self.changes.extend(changes);
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.changes.is_empty()
+ }
+
+ pub fn take(&mut self) -> Vec<CohortMembershipChange> {
+ std::mem::take(&mut self.changes)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::producer::MembershipStatus;
+
+ fn change(cohort_id: i32) -> CohortMembershipChange {
+ CohortMembershipChange {
+ team_id: 1,
+ cohort_id,
+ person_id: "p".to_string(),
+ last_updated: "2026-05-26 12:34:56.789123".to_string(),
+ status: MembershipStatus::Entered,
+ }
+ }
+
+ #[test]
+ fn push_extend_take_round_trip() {
+ let mut buffer = OutputBuffer::new();
+ assert!(buffer.is_empty());
+
+ buffer.push(change(1));
+ buffer.extend([change(2), change(3)]);
+ assert!(!buffer.is_empty());
+
+ let taken = buffer.take();
+ assert_eq!(
+ taken.iter().map(|c| c.cohort_id).collect::<Vec<_>>(),
+ vec![1, 2, 3]
+ );
+ assert!(buffer.is_empty(), "take leaves the buffer empty");
+ }
+}
diff --git a/rust/cohort-stream-processor/src/producer/cascade.rs b/rust/cohort-stream-processor/src/producer/cascade.rs
new file mode 100644
index 000000000000..1a7dbfe56a39
--- /dev/null
+++ b/rust/cohort-stream-processor/src/producer/cascade.rs
@@ -0,0 +1,188 @@
+//! Producer for the internal `cohort_cascade_events` topic.
+//!
+//! [`cascade_key`] keys on `(team, person)` over the same `murmur2_random` partitioner as the
+//! shuffler, so a flip co-partitions with `cohort_stream_events` and lands on the worker that owns
+//! that person's `cf_stage1`/`cf_stage2`.
+
+use anyhow::{Context, Result};
+use async_trait::async_trait;
+use common_kafka::config::KafkaConfig;
+use common_kafka::kafka_producer::{
+ create_kafka_producer, send_keyed_iter_to_kafka_with_headers, KafkaContext, KafkaProduceError,
+};
+use rdkafka::producer::FutureProducer;
+use uuid::Uuid;
+
+use crate::cascade::CascadeMessage;
+use crate::filters::TeamId;
+use crate::partitions::partitioner::merge_partition_key;
+use crate::producer::kafka::AlwaysHealthy;
+use crate::producer::merge::Capture;
+
+#[async_trait]
+pub trait CascadeSink: Send + Sync {
+ async fn produce(&self, messages: Vec<CascadeMessage>) -> Vec<Result<(), KafkaProduceError>>;
+}
+
+pub struct KafkaCascadeSink {
+ producer: FutureProducer<KafkaContext>,
+ topic: String,
+}
+
+impl KafkaCascadeSink {
+ pub async fn new(kafka_config: &KafkaConfig, topic: String) -> Result<Self> {
+ let producer = create_kafka_producer(kafka_config, AlwaysHealthy)
+ .await
+ .context("creating cohort_cascade_events producer")?;
+ Ok(Self { producer, topic })
+ }
+}
+
+#[async_trait]
+impl CascadeSink for KafkaCascadeSink {
+ async fn produce(&self, messages: Vec<CascadeMessage>) -> Vec<Result<(), KafkaProduceError>> {
+ send_keyed_iter_to_kafka_with_headers(
+ &self.producer,
+ &self.topic,
+ cascade_key,
+ |_| None,
+ messages,
+ )
+ .await
+ }
+}
+
+/// Key on `(team, person)` using the same partitioner as the shuffler. Non-UUID persons fall back
+/// to the raw `team:person` string.
+fn cascade_key(message: &CascadeMessage) -> Option<String> {
+ let change = &message.change;
+ match Uuid::parse_str(&change.person_id) {
+ Ok(person) => Some(merge_partition_key(TeamId(change.team_id), &person)),
+ Err(_) => Some(format!("{}:{}", change.team_id, change.person_id)),
+ }
+}
+
+/// No-op cascade sink for when the cascade gate is off: satisfies the `CascadeSink` slot without a
+/// Kafka producer. The worker gate prevents produces from reaching this.
+#[derive(Debug, Default, Clone, Copy)]
+pub struct NoopCascadeSink;
+
+#[async_trait]
+impl CascadeSink for NoopCascadeSink {
+ async fn produce(&self, messages: Vec<CascadeMessage>) -> Vec<Result<(), KafkaProduceError>> {
+ messages.iter().map(|_| Ok(())).collect()
+ }
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct CaptureCascadeSink(Capture<CascadeMessage>);
+
+impl CaptureCascadeSink {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn failing_first(n: usize) -> Self {
+ Self(Capture::failing_first(n))
+ }
+
+ pub fn failing_always() -> Self {
+ Self(Capture::failing_always())
+ }
+
+ pub fn messages(&self) -> Vec<CascadeMessage> {
+ self.0.recorded()
+ }
+}
+
+#[async_trait]
+impl CascadeSink for CaptureCascadeSink {
+ async fn produce(&self, messages: Vec<CascadeMessage>) -> Vec<Result<(), KafkaProduceError>> {
+ self.0.produce(messages)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::cascade::first_cascade;
+ use crate::partitions::partitioner::{partition_for, COHORT_PARTITION_COUNT};
+ use crate::producer::{CohortMembershipChange, MembershipStatus};
+
+ const TS: &str = "2026-05-26 12:34:56.789123";
+
+ fn message(team_id: i32, person: Uuid) -> CascadeMessage {
+ first_cascade(
+ CohortMembershipChange {
+ team_id,
+ cohort_id: 91204,
+ person_id: person.to_string(),
+ last_updated: TS.to_string(),
+ status: MembershipStatus::Entered,
+ },
+ 777,
+ )
+ }
+
+ #[test]
+ fn cascade_key_is_the_merge_partition_key_of_the_person() {
+ let person = Uuid::from_u128(0x0192_8ccc);
+ assert_eq!(
+ cascade_key(&message(42, person)),
+ Some(merge_partition_key(TeamId(42), &person)),
+ "the cascade key must co-partition with cohort_stream_events",
+ );
+ }
+
+ #[test]
+ fn cascade_key_routes_to_the_same_partition_as_the_event_key() {
+ // The cascade producer's partition for (team, person) must equal the shuffler's so the
+ // message lands on the owning worker.
+ let person = Uuid::from_u128(0x0192_8ddd);
+ let key = cascade_key(&message(7, person)).unwrap();
+ let event_key = merge_partition_key(TeamId(7), &person);
+ assert_eq!(
+ partition_for(&key, COHORT_PARTITION_COUNT),
+ partition_for(&event_key, COHORT_PARTITION_COUNT),
+ );
+ }
+
+ #[test]
+ fn cascade_key_falls_back_to_raw_string_for_a_non_uuid_person() {
+ let mut msg = message(42, Uuid::nil());
+ msg.change.person_id = "not-a-uuid".to_string();
+ assert_eq!(cascade_key(&msg), Some("42:not-a-uuid".to_string()));
+ }
+
+ #[tokio::test]
+ async fn capture_cascade_sink_records_and_acks_in_order() {
+ let sink = CaptureCascadeSink::new();
+ let m = message(7, Uuid::from_u128(2));
+ let acks = sink.produce(vec![m.clone(), m.clone()]).await;
+ assert_eq!(acks.len(), 2);
+ assert!(acks.iter().all(Result::is_ok));
+ assert_eq!(sink.messages(), vec![m.clone(), m]);
+ }
+
+ #[tokio::test]
+ async fn capture_cascade_sink_failing_first_records_nothing_on_failure() {
+ let sink = CaptureCascadeSink::failing_first(1);
+ let m = message(7, Uuid::from_u128(2));
+
+ let first = sink.produce(vec![m.clone()]).await;
+ assert!(first.iter().all(Result::is_err), "first flush fails");
+ assert!(sink.messages().is_empty(), "a failed flush records nothing");
+
+ let second = sink.produce(vec![m.clone()]).await;
+ assert!(second.iter().all(Result::is_ok), "second flush succeeds");
+ assert_eq!(sink.messages(), vec![m]);
+ }
+
+ #[tokio::test]
+ async fn noop_cascade_sink_acks_without_recording() {
+ let sink = NoopCascadeSink;
+ let acks = sink.produce(vec![message(1, Uuid::from_u128(1))]).await;
+ assert_eq!(acks.len(), 1);
+ assert!(acks.iter().all(Result::is_ok));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/producer/kafka.rs b/rust/cohort-stream-processor/src/producer/kafka.rs
new file mode 100644
index 000000000000..0792d86f27b9
--- /dev/null
+++ b/rust/cohort-stream-processor/src/producer/kafka.rs
@@ -0,0 +1,74 @@
+//! Kafka producer for `cohort_membership_changed_shadow`.
+
+use anyhow::{Context, Result};
+use async_trait::async_trait;
+use common_kafka::config::KafkaConfig;
+use common_kafka::kafka_producer::{
+ create_kafka_producer, send_keyed_iter_to_kafka_with_headers, KafkaContext, KafkaProduceError,
+};
+use common_liveness::SyncLivenessReporter;
+use rdkafka::producer::FutureProducer;
+
+use crate::producer::{CohortMembershipChange, MembershipSink};
+
+/// No-op liveness reporter — producer stalls are surfaced by the consumer's liveness deadline.
+#[derive(Clone, Copy)]
+pub(crate) struct AlwaysHealthy;
+
+impl SyncLivenessReporter for AlwaysHealthy {
+ fn report_healthy(&self) {}
+ fn report_unhealthy(&self) {}
+}
+
+pub struct KafkaMembershipSink {
+ producer: FutureProducer<KafkaContext>,
+ topic: String,
+}
+
+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")?;
+ Ok(Self { producer, topic })
+ }
+}
+
+#[async_trait]
+impl MembershipSink for KafkaMembershipSink {
+ async fn produce(
+ &self,
+ changes: Vec<CohortMembershipChange>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ send_keyed_iter_to_kafka_with_headers(
+ &self.producer,
+ &self.topic,
+ membership_key,
+ |_| None,
+ changes,
+ )
+ .await
+ }
+}
+
+fn membership_key(change: &CohortMembershipChange) -> Option<String> {
+ Some(change.person_id.clone())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::producer::MembershipStatus;
+
+ #[test]
+ fn membership_key_is_the_person_id() {
+ let change = CohortMembershipChange {
+ team_id: 42,
+ cohort_id: 91204,
+ person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ last_updated: "2026-05-26 12:34:56.789123".to_string(),
+ status: MembershipStatus::Entered,
+ };
+ assert_eq!(membership_key(&change), Some(change.person_id.clone()));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/producer/merge.rs b/rust/cohort-stream-processor/src/producer/merge.rs
new file mode 100644
index 000000000000..8f5010a69371
--- /dev/null
+++ b/rust/cohort-stream-processor/src/producer/merge.rs
@@ -0,0 +1,344 @@
+//! Merge-protocol producers for `cohort_merge_state_transfer` and straggler re-keys back into
+//! `cohort_stream_events`.
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+
+use anyhow::{Context, Result};
+use async_trait::async_trait;
+use common_kafka::config::KafkaConfig;
+use common_kafka::kafka_producer::{
+ create_kafka_producer, send_keyed_iter_to_kafka_with_headers, KafkaContext, KafkaProduceError,
+};
+use rdkafka::producer::FutureProducer;
+use uuid::Uuid;
+
+use crate::consumers::events::CohortStreamEvent;
+use crate::filters::TeamId;
+use crate::merge::transfer::MergeStateTransfer;
+use crate::partitions::partitioner::merge_partition_key;
+use crate::producer::kafka::AlwaysHealthy;
+
+#[async_trait]
+pub trait TransferSink: Send + Sync {
+ async fn produce(
+ &self,
+ transfers: Vec<MergeStateTransfer>,
+ ) -> Vec<Result<(), KafkaProduceError>>;
+}
+
+#[async_trait]
+pub trait StreamEventSink: Send + Sync {
+ async fn produce(&self, events: Vec<CohortStreamEvent>) -> Vec<Result<(), KafkaProduceError>>;
+}
+
+pub struct KafkaTransferSink {
+ producer: FutureProducer<KafkaContext>,
+ topic: String,
+}
+
+impl KafkaTransferSink {
+ pub async fn new(kafka_config: &KafkaConfig, topic: String) -> Result<Self> {
+ let producer = create_kafka_producer(kafka_config, AlwaysHealthy)
+ .await
+ .context("creating cohort_merge_state_transfer producer")?;
+ Ok(Self { producer, topic })
+ }
+}
+
+#[async_trait]
+impl TransferSink for KafkaTransferSink {
+ async fn produce(
+ &self,
+ transfers: Vec<MergeStateTransfer>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ send_keyed_iter_to_kafka_with_headers(
+ &self.producer,
+ &self.topic,
+ transfer_key,
+ |_| None,
+ transfers,
+ )
+ .await
+ }
+}
+
+pub struct KafkaStreamEventSink {
+ producer: FutureProducer<KafkaContext>,
+ topic: String,
+}
+
+impl KafkaStreamEventSink {
+ pub async fn new(kafka_config: &KafkaConfig, topic: String) -> Result<Self> {
+ let producer = create_kafka_producer(kafka_config, AlwaysHealthy)
+ .await
+ .context("creating cohort_stream_events re-key producer")?;
+ Ok(Self { producer, topic })
+ }
+}
+
+#[async_trait]
+impl StreamEventSink for KafkaStreamEventSink {
+ async fn produce(&self, events: Vec<CohortStreamEvent>) -> Vec<Result<(), KafkaProduceError>> {
+ send_keyed_iter_to_kafka_with_headers(
+ &self.producer,
+ &self.topic,
+ stream_event_key,
+ |_| None,
+ events,
+ )
+ .await
+ }
+}
+
+fn transfer_key(transfer: &MergeStateTransfer) -> Option<String> {
+ Some(merge_partition_key(
+ TeamId(transfer.team_id),
+ &transfer.new_person_uuid,
+ ))
+}
+
+fn stream_event_key(event: &CohortStreamEvent) -> Option<String> {
+ match Uuid::parse_str(&event.person_id) {
+ Ok(person) => Some(merge_partition_key(TeamId(event.team_id), &person)),
+ Err(_) => Some(format!("{}:{}", event.team_id, event.person_id)),
+ }
+}
+
+const FAIL_ALWAYS: usize = usize::MAX;
+
+/// Shared produce recorder for test doubles: records items and can fail the next `n` (or all)
+/// produces.
+#[derive(Debug)]
+pub(crate) struct Capture<T> {
+ items: Arc<Mutex<Vec<T>>>,
+ fail_remaining: Arc<AtomicUsize>,
+}
+
+impl<T> Clone for Capture<T> {
+ fn clone(&self) -> Self {
+ Self {
+ items: self.items.clone(),
+ fail_remaining: self.fail_remaining.clone(),
+ }
+ }
+}
+
+impl<T> Default for Capture<T> {
+ fn default() -> Self {
+ Self {
+ items: Arc::default(),
+ fail_remaining: Arc::default(),
+ }
+ }
+}
+
+impl<T> Capture<T> {
+ pub(crate) fn failing_first(n: usize) -> Self {
+ Self {
+ items: Arc::default(),
+ fail_remaining: Arc::new(AtomicUsize::new(n)),
+ }
+ }
+
+ pub(crate) fn failing_always() -> Self {
+ Self::failing_first(FAIL_ALWAYS)
+ }
+
+ pub(crate) fn produce(&self, items: Vec<T>) -> Vec<Result<(), KafkaProduceError>> {
+ let should_fail = self
+ .fail_remaining
+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| match n {
+ 0 => None,
+ FAIL_ALWAYS => Some(FAIL_ALWAYS),
+ n => Some(n - 1),
+ })
+ .is_ok();
+ if should_fail {
+ return items
+ .into_iter()
+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
+ .collect();
+ }
+ let acks = (0..items.len()).map(|_| Ok(())).collect();
+ self.items
+ .lock()
+ .expect("Capture mutex poisoned")
+ .extend(items);
+ acks
+ }
+}
+
+impl<T: Clone> Capture<T> {
+ pub(crate) fn recorded(&self) -> Vec<T> {
+ self.items.lock().expect("Capture mutex poisoned").clone()
+ }
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct CaptureTransferSink(Capture<MergeStateTransfer>);
+
+impl CaptureTransferSink {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn failing_first(n: usize) -> Self {
+ Self(Capture::failing_first(n))
+ }
+
+ pub fn failing_always() -> Self {
+ Self(Capture::failing_always())
+ }
+
+ pub fn transfers(&self) -> Vec<MergeStateTransfer> {
+ self.0.recorded()
+ }
+}
+
+#[async_trait]
+impl TransferSink for CaptureTransferSink {
+ async fn produce(
+ &self,
+ transfers: Vec<MergeStateTransfer>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ self.0.produce(transfers)
+ }
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct CaptureStreamEventSink(Capture<CohortStreamEvent>);
+
+impl CaptureStreamEventSink {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn failing_first(n: usize) -> Self {
+ Self(Capture::failing_first(n))
+ }
+
+ pub fn failing_always() -> Self {
+ Self(Capture::failing_always())
+ }
+
+ pub fn events(&self) -> Vec<CohortStreamEvent> {
+ self.0.recorded()
+ }
+}
+
+#[async_trait]
+impl StreamEventSink for CaptureStreamEventSink {
+ async fn produce(&self, events: Vec<CohortStreamEvent>) -> Vec<Result<(), KafkaProduceError>> {
+ self.0.produce(events)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::merge::transfer::TransferLeaf;
+ use crate::stage1::key::LeafStateKey;
+ use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
+
+ fn transfer(team_id: i32, new_person: Uuid) -> MergeStateTransfer {
+ MergeStateTransfer {
+ team_id,
+ old_person_uuid: Uuid::from_u128(1),
+ new_person_uuid: new_person,
+ merged_at_ms: 1_716_800_000_000,
+ source_partition: 3,
+ source_offset: 9,
+ leaves: vec![TransferLeaf::new(
+ LeafStateKey([0xAB; 16]),
+ StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ AppliedOffsets::default(),
+ ),
+ )],
+ forward_hops: 0,
+ }
+ }
+
+ #[test]
+ fn transfer_key_is_the_merge_partition_key_of_p_new() {
+ let p_new = Uuid::from_u128(0x0192_8bbb);
+ assert_eq!(
+ transfer_key(&transfer(42, p_new)),
+ Some(merge_partition_key(TeamId(42), &p_new)),
+ );
+ }
+
+ #[test]
+ fn stream_event_key_is_the_merge_partition_key_of_the_rewritten_person() {
+ let person = Uuid::from_u128(0x0192_8ccc);
+ let event = CohortStreamEvent {
+ team_id: 42,
+ person_id: person.to_string(),
+ distinct_id: "d".to_string(),
+ uuid: "u".to_string(),
+ event: "$pageview".to_string(),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ properties: None,
+ person_properties: None,
+ elements_chain: None,
+ source_offset: 0,
+ source_partition: 0,
+ redirected_from: Some(Uuid::from_u128(1).to_string()),
+ redirect_hops: 1,
+ };
+ assert_eq!(
+ stream_event_key(&event),
+ Some(merge_partition_key(TeamId(42), &person)),
+ );
+
+ let raw = CohortStreamEvent {
+ person_id: "not-a-uuid".to_string(),
+ ..event
+ };
+ assert_eq!(stream_event_key(&raw), Some("42:not-a-uuid".to_string()));
+ }
+
+ #[tokio::test]
+ async fn capture_transfer_sink_records_and_acks_in_order() {
+ let sink = CaptureTransferSink::new();
+ let t = transfer(7, Uuid::from_u128(2));
+ let acks = sink.produce(vec![t.clone(), t.clone()]).await;
+ assert_eq!(acks.len(), 2);
+ assert!(acks.iter().all(Result::is_ok));
+ assert_eq!(sink.transfers(), vec![t.clone(), t]);
+ }
+
+ #[tokio::test]
+ async fn capture_transfer_sink_failing_first_fails_then_succeeds_recording_nothing_on_failure()
+ {
+ let sink = CaptureTransferSink::failing_first(1);
+ let t = transfer(7, Uuid::from_u128(2));
+
+ let first = sink.produce(vec![t.clone()]).await;
+ assert!(first.iter().all(Result::is_err), "first flush fails");
+ assert!(
+ sink.transfers().is_empty(),
+ "a failed flush records nothing"
+ );
+
+ let second = sink.produce(vec![t.clone()]).await;
+ assert!(second.iter().all(Result::is_ok), "second flush succeeds");
+ assert_eq!(sink.transfers(), vec![t]);
+ }
+
+ #[tokio::test]
+ async fn capture_transfer_sink_failing_always_never_succeeds() {
+ let sink = CaptureTransferSink::failing_always();
+ let t = transfer(7, Uuid::from_u128(2));
+ for _ in 0..10 {
+ let acks = sink.produce(vec![t.clone()]).await;
+ assert!(acks.iter().all(Result::is_err));
+ }
+ assert!(sink.transfers().is_empty());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/producer/mod.rs b/rust/cohort-stream-processor/src/producer/mod.rs
new file mode 100644
index 000000000000..75debb75e078
--- /dev/null
+++ b/rust/cohort-stream-processor/src/producer/mod.rs
@@ -0,0 +1,379 @@
+//! Output producer: maps Stage 1 [`LeafTransition`]s to per-cohort [`CohortMembershipChange`]s.
+//!
+//! [`map_transition`] fans out to single-leaf cohorts only; composable (multi-leaf) cohorts are
+//! emitted by Stage 2.
+
+pub mod batcher;
+pub mod cascade;
+pub mod kafka;
+pub mod merge;
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+
+use async_trait::async_trait;
+use chrono::Utc;
+use common_kafka::kafka_producer::KafkaProduceError;
+use metrics::counter;
+use serde::{Deserialize, Serialize};
+
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::CohortId;
+use crate::observability::metrics::OUTPUT_TRANSITIONS_UNMAPPED;
+use crate::stage1::transition::{LeafTransition, TransitionKind};
+
+pub use batcher::OutputBuffer;
+pub use cascade::{CaptureCascadeSink, CascadeSink, KafkaCascadeSink, NoopCascadeSink};
+pub use kafka::KafkaMembershipSink;
+pub use merge::{
+ CaptureStreamEventSink, CaptureTransferSink, KafkaStreamEventSink, KafkaTransferSink,
+ StreamEventSink, TransferSink,
+};
+
+/// One per-cohort membership change on `cohort_membership_changed_shadow`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CohortMembershipChange {
+ pub team_id: i32,
+ pub cohort_id: i32,
+ pub person_id: String,
+ /// ClickHouse `DateTime64(6)` wire format.
+ pub last_updated: String,
+ pub status: MembershipStatus,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MembershipStatus {
+ Entered,
+ Left,
+}
+
+impl MembershipStatus {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Entered => "entered",
+ Self::Left => "left",
+ }
+ }
+}
+
+impl From<TransitionKind> for MembershipStatus {
+ fn from(kind: TransitionKind) -> Self {
+ match kind {
+ TransitionKind::Entered => Self::Entered,
+ TransitionKind::Left => Self::Left,
+ }
+ }
+}
+
+/// Fan out one leaf transition to one membership change per single-leaf cohort that owns its LSK.
+pub fn map_transition<'a>(
+ filters: &'a TeamFilters,
+ transition: &'a LeafTransition,
+ last_updated: &'a str,
+) -> impl Iterator<Item = CohortMembershipChange> + 'a {
+ let cohorts: &[CohortId] = filters
+ .by_lsk_to_single_leaf_cohorts
+ .get(&transition.leaf_state_key)
+ .map_or(&[], Vec::as_slice);
+ if cohorts.is_empty()
+ && !filters
+ .by_lsk_to_composable_cohorts
+ .contains_key(&transition.leaf_state_key)
+ {
+ counter!(OUTPUT_TRANSITIONS_UNMAPPED, "reason" => "no_emitting_cohort").increment(1);
+ }
+ let team_id = transition.team_id.0;
+ let status = MembershipStatus::from(transition.kind);
+ let person_id = transition.person_id.to_string();
+ cohorts
+ .iter()
+ .map(move |&cohort_id| CohortMembershipChange {
+ team_id,
+ cohort_id: cohort_id.0,
+ person_id: person_id.clone(),
+ last_updated: last_updated.to_string(),
+ status,
+ })
+}
+
+/// Current UTC time as a ClickHouse `DateTime64(6)` string (microseconds).
+pub fn now_last_updated() -> String {
+ Utc::now().format("%Y-%m-%d %H:%M:%S%.6f").to_string()
+}
+
+#[async_trait]
+pub trait MembershipSink: Send + Sync {
+ async fn produce(
+ &self,
+ changes: Vec<CohortMembershipChange>,
+ ) -> Vec<Result<(), KafkaProduceError>>;
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct CaptureSink {
+ changes: Arc<Mutex<Vec<CohortMembershipChange>>>,
+ fail_remaining: Arc<AtomicUsize>,
+}
+
+impl CaptureSink {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn failing_first(n: usize) -> Self {
+ Self {
+ changes: Arc::default(),
+ fail_remaining: Arc::new(AtomicUsize::new(n)),
+ }
+ }
+
+ pub fn changes(&self) -> Vec<CohortMembershipChange> {
+ self.changes
+ .lock()
+ .expect("CaptureSink mutex poisoned")
+ .clone()
+ }
+}
+
+#[async_trait]
+impl MembershipSink for CaptureSink {
+ async fn produce(
+ &self,
+ changes: Vec<CohortMembershipChange>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ let should_fail = self
+ .fail_remaining
+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| {
+ (n > 0).then(|| n - 1)
+ })
+ .is_ok();
+ if should_fail {
+ return changes
+ .into_iter()
+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
+ .collect();
+ }
+ let acks = (0..changes.len()).map(|_| Ok(())).collect();
+ self.changes
+ .lock()
+ .expect("CaptureSink mutex poisoned")
+ .extend(changes);
+ acks
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::UTC;
+ use serde_json::{json, Value};
+ use uuid::Uuid;
+
+ use crate::filters::{CohortId, TeamFiltersBuilder, TeamId};
+ use crate::stage1::key::LeafStateKey;
+
+ const HASH: [u8; 16] = *b"0123456789abcdef";
+ const TS: &str = "2026-05-26 12:34:56.789123";
+
+ fn behavioral_leaf(time_value: i64) -> Value {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": time_value,
+ "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn person_leaf() -> Value {
+ json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+ }
+
+ fn wrap(values: Vec<Value>) -> Value {
+ json!({ "properties": { "type": "AND", "values": values } })
+ }
+
+ fn transition(lsk: LeafStateKey, kind: TransitionKind) -> LeafTransition {
+ LeafTransition {
+ team_id: TeamId(42),
+ leaf_state_key: lsk,
+ person_id: Uuid::from_u128(0x01928aaa),
+ condition_hash: HASH,
+ kind,
+ }
+ }
+
+ #[test]
+ fn map_transition_entered_maps_to_one_change() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(91204), TeamId(42), &wrap(vec![behavioral_leaf(7)]))
+ .unwrap();
+ let filters = builder.freeze(UTC);
+ let lsk = filters.by_condition_to_lsk[&HASH][0];
+
+ let changes: Vec<_> =
+ map_transition(&filters, &transition(lsk, TransitionKind::Entered), TS).collect();
+
+ assert_eq!(changes.len(), 1);
+ assert_eq!(changes[0].team_id, 42);
+ assert_eq!(changes[0].cohort_id, 91204);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[0].last_updated, TS);
+ assert_eq!(
+ changes[0].person_id,
+ Uuid::from_u128(0x01928aaa).to_string()
+ );
+ }
+
+ #[test]
+ fn map_transition_left_carries_left_status() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(42), &wrap(vec![person_leaf()]))
+ .unwrap();
+ let filters = builder.freeze(UTC);
+ let lsk = LeafStateKey::for_person_property(b"fedcba9876543210");
+
+ let changes: Vec<_> =
+ map_transition(&filters, &transition(lsk, TransitionKind::Left), TS).collect();
+
+ assert_eq!(changes.len(), 1);
+ assert_eq!(changes[0].status, MembershipStatus::Left);
+ }
+
+ #[test]
+ fn map_transition_fans_out_to_every_owning_cohort() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(42), &wrap(vec![behavioral_leaf(7)]))
+ .unwrap();
+ builder
+ .add_cohort(CohortId(2), TeamId(42), &wrap(vec![behavioral_leaf(7)]))
+ .unwrap();
+ let filters = builder.freeze(UTC);
+ let lsk = filters.by_condition_to_lsk[&HASH][0];
+
+ let mut cohorts: Vec<i32> =
+ map_transition(&filters, &transition(lsk, TransitionKind::Entered), TS)
+ .map(|change| change.cohort_id)
+ .collect();
+ cohorts.sort_unstable();
+ assert_eq!(cohorts, vec![1, 2]);
+ }
+
+ #[test]
+ fn map_transition_for_a_multi_leaf_only_leaf_is_empty() {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(42),
+ &wrap(vec![behavioral_leaf(7), person_leaf()]),
+ )
+ .unwrap();
+ let filters = builder.freeze(UTC);
+ let lsk = filters.by_condition_to_lsk[&HASH][0];
+
+ let changes: Vec<_> =
+ 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",
+ );
+ }
+
+ #[test]
+ fn serialized_change_has_exactly_the_contract_keys() {
+ let change = CohortMembershipChange {
+ team_id: 42,
+ cohort_id: 91204,
+ person_id: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ last_updated: TS.to_string(),
+ status: MembershipStatus::Entered,
+ };
+ let value = serde_json::to_value(&change).unwrap();
+ let object = value.as_object().unwrap();
+
+ let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
+ keys.sort_unstable();
+ assert_eq!(
+ keys,
+ vec![
+ "cohort_id",
+ "last_updated",
+ "person_id",
+ "status",
+ "team_id"
+ ],
+ );
+ assert_eq!(object["status"], json!("entered"));
+ assert!(object["person_id"].is_string());
+ assert_eq!(object["team_id"], json!(42));
+ }
+
+ #[test]
+ fn left_status_serializes_snake_case() {
+ let value = serde_json::to_value(MembershipStatus::Left).unwrap();
+ assert_eq!(value, json!("left"));
+ }
+
+ #[test]
+ fn now_last_updated_is_microsecond_clickhouse_format() {
+ let now = now_last_updated();
+ let (date_time, fraction) = now.split_once('.').expect("has a fractional part");
+ assert_eq!(fraction.len(), 6, "microseconds, not nanoseconds: {now}");
+ assert!(fraction.chars().all(|c| c.is_ascii_digit()));
+
+ let (date, time) = date_time.split_once(' ').expect("date and time");
+ assert_eq!(date.len(), 10);
+ assert_eq!(date.matches('-').count(), 2);
+ assert_eq!(time.matches(':').count(), 2);
+ }
+
+ #[tokio::test]
+ async fn capture_sink_records_and_acks_in_order() {
+ let sink = CaptureSink::new();
+ let change = CohortMembershipChange {
+ team_id: 1,
+ cohort_id: 2,
+ person_id: "p".to_string(),
+ last_updated: TS.to_string(),
+ status: MembershipStatus::Entered,
+ };
+ let acks = sink.produce(vec![change.clone(), change.clone()]).await;
+ assert_eq!(acks.len(), 2);
+ assert!(acks.iter().all(Result::is_ok));
+ assert_eq!(sink.changes(), vec![change.clone(), change]);
+ }
+
+ #[tokio::test]
+ async fn capture_sink_failing_first_fails_then_succeeds_recording_nothing_on_failure() {
+ let sink = CaptureSink::failing_first(1);
+ let change = CohortMembershipChange {
+ team_id: 1,
+ cohort_id: 2,
+ person_id: "p".to_string(),
+ last_updated: TS.to_string(),
+ status: MembershipStatus::Left,
+ };
+
+ let first = sink.produce(vec![change.clone()]).await;
+ assert!(first.iter().all(Result::is_err), "first flush fails");
+ assert!(sink.changes().is_empty(), "a failed flush records nothing");
+
+ let second = sink.produce(vec![change.clone()]).await;
+ assert!(second.iter().all(Result::is_ok), "second flush succeeds");
+ assert_eq!(sink.changes(), vec![change]);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/recovery/mod.rs b/rust/cohort-stream-processor/src/recovery/mod.rs
new file mode 100644
index 000000000000..0c6d730d1688
--- /dev/null
+++ b/rust/cohort-stream-processor/src/recovery/mod.rs
@@ -0,0 +1 @@
+//! Cold-start recovery: triggers the backfill that seeds a newly-eligible cohort's history.
diff --git a/rust/cohort-stream-processor/src/stage1/bucket_tz.rs b/rust/cohort-stream-processor/src/stage1/bucket_tz.rs
new file mode 100644
index 000000000000..0004d2356631
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/bucket_tz.rs
@@ -0,0 +1,408 @@
+//! Calendar-day-in-team-timezone bucket math.
+//!
+//! Pure, zone-agnostic, and total: every function takes time as an `i64` (epoch ms) plus a
+//! [`Tz`] and returns without a `Result` and without reading a wall-clock "now". The bucket
+//! variants and the sweep consume it.
+//!
+//! ## Window boundary (the highest-risk decision)
+//!
+//! The existing pipeline's predicate is `event_day >= now_day − N` (via `relative_date_parse("-Nd")`
+//! = `now − N days`), so "last N days" is the **inclusive** set `[now_day − N ..= now_day]` =
+//! `N + 1` day-buckets. [`window_start_day`] therefore returns `now_day − N` (not `− N + 1`) and
+//! [`daily_bucket_len`] returns `N + 1`.
+//!
+//! ## DST
+//!
+//! Instant → day ([`day_idx_in_tz`], [`hour_of_day_in_tz`]) is always unambiguous (an instant maps
+//! to exactly one local datetime) and is therefore DST-exact, as is [`window_start_day`]. Day →
+//! instant ([`start_of_day_ms_in_tz`], [`start_of_hour_ms_in_tz`]) can be ambiguous (fall-back) or
+//! nonexistent (spring-forward gap); it picks the **earliest** instant on `Ambiguous` (= Python
+//! `ZoneInfo` fold=0) and the **post-gap** instant on `None`. Only this eviction-timing path is
+//! DST-tie-broken, and it rides the sweep's ±5 min `safety_margin` tolerance.
+
+use chrono::{DateTime, Duration, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Timelike, Utc};
+use chrono_tz::{Tz, UTC};
+
+/// A calendar-day index: days since the Unix epoch (1970-01-01) in a given timezone.
+pub type DayIdx = i32;
+
+/// Upper bound (minutes) on the forward probe used to find the post-gap instant for a local time
+/// that falls inside a spring-forward gap. Comfortably exceeds the largest real DST shift; the probe
+/// only runs when a transition lands exactly on the requested boundary (rare).
+const MAX_DST_GAP_MINUTES: i64 = 180;
+
+/// The calendar-day index of `epoch_ms` in `tz`. Instant → day is never DST-ambiguous.
+pub fn day_idx_in_tz(epoch_ms: i64, tz: Tz) -> DayIdx {
+ day_idx_of(utc_instant(epoch_ms).with_timezone(&tz).date_naive())
+}
+
+/// Local-midnight epoch-ms for day index `day` in `tz` — the base for an eviction deadline. On a
+/// fall-back midnight picks the earliest instant; on a spring-forward gap at midnight picks the
+/// post-gap instant.
+pub fn start_of_day_ms_in_tz(day: DayIdx, tz: Tz) -> i64 {
+ let midnight = date_for_day(day)
+ .and_hms_opt(0, 0, 0)
+ .expect("00:00:00 is a valid time");
+ local_naive_to_instant(midnight, tz).timestamp_millis()
+}
+
+/// The first day-bucket of the rolling window ending at `now_ms`. Returns `now_day − N` (the
+/// inclusive lower bound), matching the existing `event_day >= now_day − N` predicate.
+pub fn window_start_day(now_ms: i64, effective_window_days: u32, tz: Tz) -> DayIdx {
+ window_start_for_now(day_idx_in_tz(now_ms, tz), effective_window_days)
+}
+
+/// The window's "now" day given its start: `window_start_day + window_days`, **saturating** to
+/// [`DayIdx::MAX`]. `window_days` is unbounded `u32` user input, so a naïve `as i32` add would wrap
+/// for an astronomical window and snap the window backward; saturating instead means a huge window's
+/// "now" sits at the far future, so the window effectively never slides — the correct reading of an
+/// essentially infinite window.
+pub fn now_day_for_window(window_start_day: DayIdx, window_days: u32) -> DayIdx {
+ match i64::from(window_start_day) + i64::from(window_days) {
+ day if day > i64::from(DayIdx::MAX) => DayIdx::MAX,
+ day => day as DayIdx,
+ }
+}
+
+/// The window's start day given its "now": `now_day − window_days`, **saturating** to [`DayIdx::MIN`].
+/// Mirrors [`now_day_for_window`] on the lower bound — a huge `window_days` would underflow a naïve
+/// `as i32` subtract and wrap positive; saturating instead pins the start at the far past, so the
+/// window covers everything and never evicts (the correct reading of an essentially infinite window).
+pub fn window_start_for_now(now_day: DayIdx, window_days: u32) -> DayIdx {
+ match i64::from(now_day) - i64::from(window_days) {
+ day if day < i64::from(DayIdx::MIN) => DayIdx::MIN,
+ day => day as DayIdx,
+ }
+}
+
+/// The epoch-ms (team tz, local midnight) at which a day-`oldest_day` bucket/entry leaves an
+/// `N`-day window — the start of day `oldest_day + N + 1`. Computed in `i64` and, mirroring
+/// [`super::pick_state::EvictionWindow::earliest_eviction_at_ms`], returns [`i64::MAX`] (never
+/// evict) when the leave-day overflows [`DayIdx`] for an astronomical window rather than wrapping
+/// to a near-epoch instant (which would flap entered/left).
+pub fn window_leave_day_ms(oldest_day: DayIdx, window_days: u32, tz: Tz) -> i64 {
+ let leave_day = i64::from(oldest_day) + i64::from(window_days) + 1;
+ match DayIdx::try_from(leave_day) {
+ Ok(day) => start_of_day_ms_in_tz(day, tz),
+ Err(_) => i64::MAX,
+ }
+}
+
+/// The calendar-day index of a tz-naive [`NaiveDate`] — days since 1970-01-01, with no zone applied.
+/// Used for an absolute `explicit_datetime` bound, whose written calendar date is tz-invariant (the
+/// oracle stamps a bare date in the project tz, so `toDate('2026-05-01')` is the literal date), unlike
+/// an event instant which must first be projected into the team tz via [`day_idx_in_tz`].
+pub fn day_idx_of_naive_date(date: NaiveDate) -> DayIdx {
+ day_idx_of(date)
+}
+
+/// The local hour-of-day `[0, 23]` of `epoch_ms` in `tz` — the bucket index for the 24-hour variant.
+pub fn hour_of_day_in_tz(epoch_ms: i64, tz: Tz) -> u32 {
+ utc_instant(epoch_ms).with_timezone(&tz).hour()
+}
+
+/// Epoch-ms of the start of the local hour containing `epoch_ms` in `tz` — the hourly variant's
+/// eviction base. DST-tie-broken like [`start_of_day_ms_in_tz`].
+pub fn start_of_hour_ms_in_tz(epoch_ms: i64, tz: Tz) -> i64 {
+ let local = utc_instant(epoch_ms).with_timezone(&tz);
+ let on_the_hour = local
+ .date_naive()
+ .and_hms_opt(local.hour(), 0, 0)
+ .expect("hh:00:00 is a valid time");
+ local_naive_to_instant(on_the_hour, tz).timestamp_millis()
+}
+
+/// The dense daily-bucket array length for an `N`-day window: `N + 1`, covering the inclusive set
+/// `[now_day − N ..= now_day]`. Centralizes the `+ 1` so callers never re-derive it.
+pub fn daily_bucket_len(effective_window_days: u32) -> usize {
+ effective_window_days as usize + 1
+}
+
+/// Parse an IANA timezone name, falling back to UTC for an unrecognized one. Pure and total — the
+/// loader wraps this to count/log the fallback with the offending `team_id`.
+pub fn resolve_tz_or_utc(name: &str) -> Tz {
+ name.parse::<Tz>().unwrap_or(UTC)
+}
+
+/// `epoch_ms` as a UTC instant. Total: the only `None` from `from_timestamp_millis` is a value
+/// ~262 000 years from the epoch, unreachable for a real event timestamp; fall back to the epoch.
+fn utc_instant(epoch_ms: i64) -> DateTime<Utc> {
+ DateTime::from_timestamp_millis(epoch_ms)
+ .unwrap_or_else(|| DateTime::from_timestamp_millis(0).expect("epoch 0 is in range"))
+}
+
+fn unix_epoch_date() -> NaiveDate {
+ NaiveDate::from_ymd_opt(1970, 1, 1).expect("1970-01-01 is a valid date")
+}
+
+fn day_idx_of(date: NaiveDate) -> DayIdx {
+ (date - unix_epoch_date()).num_days() as DayIdx
+}
+
+fn date_for_day(day: DayIdx) -> NaiveDate {
+ unix_epoch_date()
+ .checked_add_signed(Duration::days(i64::from(day)))
+ .unwrap_or_else(unix_epoch_date)
+}
+
+/// Resolve a local naive datetime to an instant, DST-tie-broken: earliest on a fall-back overlap,
+/// the post-gap instant on a spring-forward gap.
+fn local_naive_to_instant(naive: NaiveDateTime, tz: Tz) -> DateTime<Tz> {
+ match tz.from_local_datetime(&naive) {
+ LocalResult::Single(dt) => dt,
+ // Overlap: the wall-clock time occurs twice. Earliest = Python `ZoneInfo` fold=0.
+ LocalResult::Ambiguous(earliest, _latest) => earliest,
+ // Gap: the wall-clock time does not exist. Walk forward to the first representable local
+ // minute and take its earliest instant — the post-gap instant. Bounded by the max DST shift;
+ // only reachable when a transition lands exactly on this boundary.
+ LocalResult::None => (1..=MAX_DST_GAP_MINUTES)
+ .find_map(|m| {
+ naive
+ .checked_add_signed(Duration::minutes(m))
+ .and_then(|t| tz.from_local_datetime(&t).earliest())
+ })
+ .unwrap_or_else(|| Utc.from_utc_datetime(&naive).with_timezone(&tz)),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::America::{New_York, Sao_Paulo};
+ use chrono_tz::Asia::Kolkata;
+
+ const MS_PER_DAY: i64 = 86_400_000;
+ const MS_PER_HOUR: i64 = 3_600_000;
+
+ /// Epoch-ms of a UTC wall-clock time, computed via chrono so the goldens don't re-derive the math
+ /// under test.
+ fn utc_ms(year: i32, month: u32, day: u32, hour: u32, minute: u32) -> i64 {
+ Utc.with_ymd_and_hms(year, month, day, hour, minute, 0)
+ .unwrap()
+ .timestamp_millis()
+ }
+
+ fn local_at(epoch_ms: i64, tz: Tz) -> DateTime<Tz> {
+ DateTime::from_timestamp_millis(epoch_ms)
+ .unwrap()
+ .with_timezone(&tz)
+ }
+
+ #[test]
+ fn utc_epoch_is_day_zero() {
+ assert_eq!(day_idx_in_tz(0, UTC), 0);
+ assert_eq!(start_of_day_ms_in_tz(0, UTC), 0);
+ }
+
+ #[test]
+ fn utc_day_boundary_is_inclusive_of_the_last_millisecond() {
+ assert_eq!(day_idx_in_tz(MS_PER_DAY - 1, UTC), 0, "last ms of day 0");
+ assert_eq!(day_idx_in_tz(MS_PER_DAY, UTC), 1, "first ms of day 1");
+ }
+
+ #[test]
+ fn start_of_day_round_trips_within_the_day_in_utc() {
+ let ms = utc_ms(2026, 5, 26, 12, 34);
+ let day = day_idx_in_tz(ms, UTC);
+ let start = start_of_day_ms_in_tz(day, UTC);
+ assert!(start <= ms, "start of day is at or before the instant");
+ assert!(
+ ms < start_of_day_ms_in_tz(day + 1, UTC),
+ "the instant is before the next day's start",
+ );
+ assert_eq!(
+ start,
+ ms - (ms % MS_PER_DAY),
+ "UTC start-of-day is a clean floor"
+ );
+ }
+
+ #[test]
+ fn positive_offset_tz_rolls_the_day_forward_at_its_local_midnight() {
+ // 20:00 UTC is 01:30 the next day in Kolkata (+5:30), so its calendar day is UTC + 1.
+ let evening = utc_ms(2026, 5, 26, 20, 0);
+ assert_eq!(
+ day_idx_in_tz(evening, Kolkata),
+ day_idx_in_tz(evening, UTC) + 1,
+ );
+ // 12:00 UTC is 17:30 the same day in Kolkata — still the UTC day.
+ let midday = utc_ms(2026, 5, 26, 12, 0);
+ assert_eq!(day_idx_in_tz(midday, Kolkata), day_idx_in_tz(midday, UTC));
+ }
+
+ #[test]
+ fn negative_offset_tz_keeps_the_previous_day_after_utc_midnight() {
+ // 02:00 UTC is 22:00 the previous day in New York (EDT, −4), so its calendar day is UTC − 1.
+ let after_midnight = utc_ms(2026, 5, 26, 2, 0);
+ assert_eq!(
+ day_idx_in_tz(after_midnight, New_York),
+ day_idx_in_tz(after_midnight, UTC) - 1,
+ );
+ }
+
+ #[test]
+ fn spring_forward_day_is_twenty_three_hours_long() {
+ // New York springs forward at 02:00 on 2026-03-08 (a 23-hour day).
+ let day = day_idx_in_tz(utc_ms(2026, 3, 8, 12, 0), New_York);
+ let length =
+ start_of_day_ms_in_tz(day + 1, New_York) - start_of_day_ms_in_tz(day, New_York);
+ assert_eq!(length, 23 * MS_PER_HOUR);
+ }
+
+ #[test]
+ fn fall_back_day_is_twenty_five_hours_long() {
+ // New York falls back at 02:00 on 2026-11-01 (a 25-hour day).
+ let day = day_idx_in_tz(utc_ms(2026, 11, 1, 12, 0), New_York);
+ let length =
+ start_of_day_ms_in_tz(day + 1, New_York) - start_of_day_ms_in_tz(day, New_York);
+ assert_eq!(length, 25 * MS_PER_HOUR);
+ }
+
+ #[test]
+ fn ambiguous_hour_floors_to_the_earliest_instant() {
+ // On the 2026-11-01 fall-back, New York's 01:30 occurs twice (EDT then, an hour later, EST).
+ // Both must floor to the same earliest 01:00 instant (fold=0).
+ let first_0130 = utc_ms(2026, 11, 1, 5, 30); // 01:30 EDT
+ let second_0130 = utc_ms(2026, 11, 1, 6, 30); // 01:30 EST, one UTC hour later
+ assert_eq!(
+ start_of_hour_ms_in_tz(first_0130, New_York),
+ start_of_hour_ms_in_tz(second_0130, New_York),
+ "an ambiguous hour resolves to its earliest instant",
+ );
+ // And that shared floor is the earlier (EDT) 01:00.
+ assert_eq!(
+ start_of_hour_ms_in_tz(second_0130, New_York),
+ utc_ms(2026, 11, 1, 5, 0)
+ );
+ }
+
+ #[test]
+ fn spring_forward_gap_at_midnight_resolves_to_the_post_gap_instant() {
+ // Sao Paulo sprang forward at midnight on 2017-10-15 (00:00 → 01:00), so local midnight does
+ // not exist; start-of-day must resolve to the post-gap instant rather than panic or fall back.
+ let day = day_idx_in_tz(utc_ms(2017, 10, 15, 12, 0), Sao_Paulo); // noon is unambiguous
+ let start = start_of_day_ms_in_tz(day, Sao_Paulo);
+ let local = local_at(start, Sao_Paulo);
+ assert_eq!(
+ local.date_naive(),
+ NaiveDate::from_ymd_opt(2017, 10, 15).unwrap(),
+ );
+ assert_eq!(
+ local.hour(),
+ 1,
+ "post-gap instant is 01:00 local, not the skipped midnight"
+ );
+ }
+
+ #[test]
+ fn window_is_inclusive_of_now_minus_n() {
+ // relative_date_parse("-7d") = now − 7 days; the predicate `event_day >= now_day − 7` makes
+ // "last 7 days" the inclusive set [now_day − 7 ..= now_day] = 8 day-buckets.
+ let now_ms = utc_ms(2026, 5, 26, 9, 0);
+ let now_day = day_idx_in_tz(now_ms, UTC);
+ assert_eq!(window_start_day(now_ms, 7, UTC), now_day - 7);
+ assert_eq!(daily_bucket_len(7), 8);
+ assert_eq!(
+ (now_day - window_start_day(now_ms, 7, UTC)) as usize + 1,
+ daily_bucket_len(7),
+ "the bucket array spans exactly [window_start_day ..= now_day]",
+ );
+ }
+
+ #[test]
+ fn window_start_day_is_team_tz_relative() {
+ // Window arithmetic uses the team-tz day, so a far-offset team near the boundary shifts with
+ // its own midnight, not UTC's.
+ let evening = utc_ms(2026, 5, 26, 20, 0); // already "tomorrow" in Kolkata
+ assert_eq!(
+ window_start_day(evening, 7, Kolkata),
+ day_idx_in_tz(evening, Kolkata) - 7,
+ );
+ assert_eq!(
+ window_start_day(evening, 365, Kolkata),
+ day_idx_in_tz(evening, Kolkata) - 365,
+ );
+ }
+
+ #[test]
+ fn year_and_day_windows_agree_on_three_hundred_sixty_five() {
+ // A 365-day window and a 1-year window (year.to_days() == 365) start on the same day.
+ let now_ms = utc_ms(2026, 5, 26, 9, 0);
+ assert_eq!(
+ window_start_day(now_ms, 365, UTC),
+ window_start_day(now_ms, 365, UTC),
+ );
+ assert_eq!(daily_bucket_len(365), 366);
+ }
+
+ #[test]
+ fn hour_of_day_is_team_tz_local() {
+ let ms = utc_ms(2026, 5, 26, 20, 0);
+ assert_eq!(hour_of_day_in_tz(ms, UTC), 20);
+ assert_eq!(
+ hour_of_day_in_tz(ms, Kolkata),
+ 1,
+ "20:00 UTC is 01:30 in Kolkata"
+ );
+ }
+
+ #[test]
+ fn start_of_hour_floors_to_the_local_hour() {
+ let ms = utc_ms(2026, 5, 26, 20, 45);
+ assert_eq!(start_of_hour_ms_in_tz(ms, UTC), utc_ms(2026, 5, 26, 20, 0));
+ // Kolkata's +5:30 offset means the local hour boundary is offset by 30 minutes from UTC.
+ assert_eq!(
+ start_of_hour_ms_in_tz(ms, Kolkata),
+ utc_ms(2026, 5, 26, 20, 30)
+ );
+ }
+
+ #[test]
+ fn resolve_tz_or_utc_parses_known_names_and_falls_back() {
+ assert_eq!(resolve_tz_or_utc("America/New_York"), New_York);
+ assert_eq!(resolve_tz_or_utc("Asia/Kolkata"), Kolkata);
+ assert_eq!(resolve_tz_or_utc("UTC"), UTC);
+ assert_eq!(resolve_tz_or_utc("garbage"), UTC);
+ assert_eq!(resolve_tz_or_utc(""), UTC);
+ }
+
+ #[test]
+ fn daily_bucket_len_is_n_plus_one() {
+ assert_eq!(daily_bucket_len(1), 2);
+ assert_eq!(daily_bucket_len(7), 8);
+ assert_eq!(daily_bucket_len(30), 31);
+ assert_eq!(daily_bucket_len(0), 1);
+ }
+
+ #[test]
+ fn window_bound_helpers_match_plain_arithmetic_for_realistic_windows() {
+ // Saturation only changes behavior at astronomical windows; for any realistic window the
+ // helpers are bit-identical to the `+ window_days` / `− window_days` they replace.
+ for window_days in [0_u32, 1, 7, 30, 180, 365, 3_650] {
+ assert_eq!(
+ now_day_for_window(19_500, window_days),
+ 19_500 + window_days as i32,
+ );
+ assert_eq!(
+ window_start_for_now(19_500, window_days),
+ 19_500 - window_days as i32,
+ );
+ assert_eq!(
+ window_leave_day_ms(19_500, window_days, UTC),
+ start_of_day_ms_in_tz(19_500 + window_days as i32 + 1, UTC),
+ );
+ }
+ }
+
+ #[test]
+ fn window_bound_helpers_saturate_at_the_day_index_bounds() {
+ // A huge window pushes "now" to the far future (never slides) and "start" to the far past
+ // (covers everything) rather than wrapping an `i32` cast.
+ assert_eq!(now_day_for_window(1_000, u32::MAX), DayIdx::MAX);
+ assert_eq!(now_day_for_window(DayIdx::MAX, 1), DayIdx::MAX);
+ assert_eq!(window_start_for_now(-1_000, u32::MAX), DayIdx::MIN);
+ assert_eq!(window_start_for_now(DayIdx::MIN, 1), DayIdx::MIN);
+ // The leave-day instant overflows `i32`, so the deadline pins at i64::MAX (never evict).
+ assert_eq!(window_leave_day_ms(1_000, u32::MAX, UTC), i64::MAX);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage1/compressed_history.rs b/rust/cohort-stream-processor/src/stage1/compressed_history.rs
new file mode 100644
index 000000000000..2d0bc71cbf27
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/compressed_history.rs
@@ -0,0 +1,258 @@
+//! Sparse run-length daily-count operations for `performed_event_multiple` windows over 180 days.
+//!
+//! Entries are `(day_idx, count)` pairs sorted ascending, no zero-count entries. Windowing semantics
+//! mirror [`super::daily`]: slide forward, prune out-of-window days, sum in-window. Clock-free;
+//! callers supply the "now" day index.
+
+use chrono_tz::Tz;
+
+use crate::stage1::bucket_tz::{now_day_for_window, window_leave_day_ms, window_start_for_now};
+
+/// Insert or increment `day`'s count (saturating), keeping entries sorted with no zero-count entries.
+/// The caller must slide the window before calling; `day` must be within the current window.
+pub(crate) fn insert_event(entries: &mut Vec<(i32, u32)>, day: i32) {
+ match entries.binary_search_by_key(&day, |&(entry_day, _)| entry_day) {
+ Ok(idx) => entries[idx].1 = entries[idx].1.saturating_add(1),
+ Err(idx) => entries.insert(idx, (day, 1)),
+ }
+}
+
+/// Slide the sparse window forward to `target_now_day`, dropping entries below the new lower bound.
+/// No-op when the window already covers `target_now_day`; the window only moves forward, never back.
+pub(crate) fn slide_window_forward(
+ entries: &mut Vec<(i32, u32)>,
+ window_start_day: &mut i32,
+ window_days: u32,
+ target_now_day: i32,
+) {
+ let cur_now_day = now_day_for_window(*window_start_day, window_days);
+ if target_now_day <= cur_now_day {
+ return;
+ }
+ let new_window_start_day = window_start_for_now(target_now_day, window_days);
+ let dropped = entries.partition_point(|&(day, _)| day < new_window_start_day);
+ entries.drain(..dropped);
+ *window_start_day = new_window_start_day;
+}
+
+/// Saturating sum of all entries' counts.
+pub(crate) fn compressed_sum(entries: &[(i32, u32)]) -> u32 {
+ entries
+ .iter()
+ .map(|&(_, count)| count)
+ .fold(0, u32::saturating_add)
+}
+
+/// Deadline (epoch ms, team tz) at which the oldest entry leaves the window. A day-`d` entry
+/// leaves at the start of day `d + window_days + 1`. Returns [`i64::MAX`] when empty.
+pub(crate) fn compressed_eviction_deadline(
+ entries: &[(i32, u32)],
+ window_days: u32,
+ tz: Tz,
+) -> i64 {
+ match entries.first() {
+ Some(&(oldest_day, _)) => window_leave_day_ms(oldest_day, window_days, tz),
+ None => i64::MAX,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::America::New_York;
+ use chrono_tz::UTC;
+
+ use crate::stage1::bucket_tz::{day_idx_in_tz, start_of_day_ms_in_tz};
+
+ fn slide(
+ mut entries: Vec<(i32, u32)>,
+ mut window_start_day: i32,
+ window_days: u32,
+ target_now_day: i32,
+ ) -> (Vec<(i32, u32)>, i32) {
+ slide_window_forward(
+ &mut entries,
+ &mut window_start_day,
+ window_days,
+ target_now_day,
+ );
+ (entries, window_start_day)
+ }
+
+ #[test]
+ fn insert_into_an_empty_set_creates_a_count_one_entry() {
+ let mut entries = Vec::new();
+ insert_event(&mut entries, 100);
+ assert_eq!(entries, vec![(100, 1)]);
+ }
+
+ #[test]
+ fn insert_on_an_existing_day_increments_in_place() {
+ let mut entries = vec![(100, 3), (105, 1)];
+ insert_event(&mut entries, 100);
+ assert_eq!(entries, vec![(100, 4), (105, 1)], "no new entry, count + 1");
+ }
+
+ #[test]
+ fn insert_keeps_entries_sorted_by_day() {
+ let mut entries = Vec::new();
+ for day in [105, 100, 110, 102] {
+ insert_event(&mut entries, day);
+ }
+ assert_eq!(entries, vec![(100, 1), (102, 1), (105, 1), (110, 1)]);
+ }
+
+ #[test]
+ fn insert_count_saturates_at_u32_max() {
+ let mut entries = vec![(100, u32::MAX)];
+ insert_event(&mut entries, 100);
+ assert_eq!(entries, vec![(100, u32::MAX)], "saturating, never wraps");
+ }
+
+ #[test]
+ fn slide_to_the_current_now_day_is_a_noop() {
+ // window_days 365, window [100 ..= 465]; target == cur_now_day (465) → unchanged.
+ let entries = vec![(100, 9), (300, 2), (465, 1)];
+ let (after, start) = slide(entries.clone(), 100, 365, 465);
+ assert_eq!(after, entries);
+ assert_eq!(start, 100);
+ }
+
+ #[test]
+ fn slide_to_a_past_now_day_never_moves_backward() {
+ let entries = vec![(100, 9), (300, 2)];
+ let (after, start) = slide(entries.clone(), 100, 365, 400);
+ assert_eq!(after, entries, "no slide for a past target");
+ assert_eq!(start, 100);
+ }
+
+ #[test]
+ fn slide_drops_only_the_entries_below_the_new_lower_bound() {
+ // window [100 ..= 465], slide to now-day 466: new lower bound 101, so day-100 drops; the rest
+ // (all ≥ 101) survive, and window_start advances to 101.
+ let (after, start) = slide(vec![(100, 9), (101, 2), (300, 3), (465, 1)], 100, 365, 466);
+ assert_eq!(after, vec![(101, 2), (300, 3), (465, 1)]);
+ assert_eq!(start, 101);
+ }
+
+ #[test]
+ fn slide_by_several_days_drops_every_entry_now_out_of_window() {
+ // Slide to now-day 470: new lower bound 105 → days 100..=104 fall out, day 105+ survive.
+ let (after, start) = slide(
+ vec![(100, 1), (103, 2), (105, 3), (460, 4), (470, 5)],
+ 100,
+ 365,
+ 470,
+ );
+ assert_eq!(after, vec![(105, 3), (460, 4), (470, 5)]);
+ assert_eq!(start, 105);
+ }
+
+ #[test]
+ fn slide_far_past_every_entry_clears_the_window() {
+ // A far-future now-day (1000) sets the lower bound to 635; every stored day predates it.
+ let (after, start) = slide(vec![(100, 1), (300, 2), (465, 3)], 100, 365, 1_000);
+ assert!(after.is_empty(), "the whole window slid past");
+ // window_start advances to target − window_days = 1000 − 365 = 635.
+ assert_eq!(start, 635, "window_start advances to target − window_days");
+ }
+
+ #[test]
+ fn slide_on_an_empty_set_only_advances_the_anchor() {
+ // A drained window still advances its anchor so the next event classifies AHEAD/WITHIN/BEHIND
+ // against the right lower bound.
+ let (after, start) = slide(Vec::new(), 100, 365, 500);
+ assert!(after.is_empty());
+ assert_eq!(start, 135, "500 − 365");
+ }
+
+ #[test]
+ fn sum_adds_the_retained_counts() {
+ assert_eq!(compressed_sum(&[(100, 3), (200, 4), (300, 1)]), 8);
+ assert_eq!(compressed_sum(&[]), 0);
+ }
+
+ #[test]
+ fn sum_saturates_at_u32_max() {
+ assert_eq!(
+ compressed_sum(&[(100, u32::MAX), (200, 5)]),
+ u32::MAX,
+ "saturating, never wraps",
+ );
+ }
+
+ #[test]
+ fn deadline_is_the_start_of_the_day_the_oldest_entry_leaves() {
+ // Oldest entry is day 102 of a 365-day window; it leaves at start of 102+365+1 = 468.
+ let entries = [(102, 5), (200, 1)];
+ assert_eq!(
+ compressed_eviction_deadline(&entries, 365, UTC),
+ start_of_day_ms_in_tz(468, UTC),
+ );
+ }
+
+ #[test]
+ fn deadline_of_an_empty_set_never_evicts() {
+ assert_eq!(compressed_eviction_deadline(&[], 365, UTC), i64::MAX);
+ }
+
+ #[test]
+ fn deadline_saturates_for_an_astronomical_window_instead_of_panicking() {
+ // `window_days` is unbounded `u32` user input; a naïve `oldest_day + window_days as i32 + 1`
+ // either panics in debug (when the sum exceeds i32::MAX — the case below) or at u32::MAX
+ // silently wraps to a near-epoch instant (flapping entered/left). Arithmetic must be total:
+ // an effectively infinite window never evicts → i64::MAX.
+ let entries = [(1_000, 1_u32)];
+ // `1_000 + 2_147_483_000 + 1` overflows i32 without saturation.
+ assert_eq!(
+ compressed_eviction_deadline(&entries, 2_147_483_000, UTC),
+ i64::MAX,
+ );
+ assert_eq!(
+ compressed_eviction_deadline(&entries, u32::MAX, UTC),
+ i64::MAX,
+ "u32::MAX (which casts to -1) must not wrap to a near-epoch deadline",
+ );
+ }
+
+ #[test]
+ fn slide_with_an_astronomical_window_never_evicts_and_does_not_panic() {
+ // `window_start_day + window_days` (cur "now") overflows i32 for a large anchor + huge
+ // window; a naïve `as i32` add panics in debug. With saturation the window already covers
+ // any realistic target, so the slide is a no-op (nothing drops, anchor unchanged).
+ let entries = vec![(2_000_000_000, 9), (2_000_000_100, 2)];
+ // `2_000_000_000 + 200_000_000` overflows i32 → unfixed code panics in `slide_window_forward`.
+ let (after, start) = slide(entries.clone(), 2_000_000_000, 200_000_000, i32::MAX);
+ assert_eq!(
+ after, entries,
+ "an essentially infinite window never slides out"
+ );
+ assert_eq!(start, 2_000_000_000, "window anchor unchanged");
+ }
+
+ #[test]
+ fn deadline_is_team_tz_local_midnight_not_utc() {
+ // The expiry boundary is the oldest entry's leave-day as local midnight in the team's zone. A
+ // negative-offset zone (New York) shifts that instant off the UTC day boundary, so the same
+ // day index resolves to a different epoch-ms — the day→instant conversion must be tz-aware.
+ let window_days = 365_u32;
+ let oldest_day = day_idx_in_tz(
+ chrono::DateTime::parse_from_rfc3339("2026-03-01T12:00:00Z")
+ .unwrap()
+ .timestamp_millis(),
+ New_York,
+ );
+ let entries = [(oldest_day, 1_u32)];
+
+ let leave_day = oldest_day + window_days as i32 + 1;
+ assert_eq!(
+ compressed_eviction_deadline(&entries, window_days, New_York),
+ start_of_day_ms_in_tz(leave_day, New_York),
+ );
+ assert_ne!(
+ start_of_day_ms_in_tz(leave_day, New_York),
+ start_of_day_ms_in_tz(leave_day, UTC),
+ "a negative-offset zone's local midnight differs from UTC midnight",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage1/daily.rs b/rust/cohort-stream-processor/src/stage1/daily.rs
new file mode 100644
index 000000000000..d55a17a20639
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/daily.rs
@@ -0,0 +1,203 @@
+//! Dense daily-bucket operations for `performed_event_multiple` windows ≤ 180 days.
+//!
+//! Pure and clock-free: callers supply the target "now" day index. The only timezone-aware call is
+//! [`daily_eviction_deadline`], which converts a day index to a local-midnight instant.
+
+use chrono_tz::Tz;
+
+use crate::stage1::bucket_tz::{now_day_for_window, window_leave_day_ms};
+
+/// Slide the dense window forward to `target_now_day`, zeroing the vacated tail. No-op when the
+/// window already covers `target_now_day`; the window only moves forward, never back.
+pub(crate) fn slide_window_forward(
+ buckets: &mut [u32],
+ window_start_day: &mut i32,
+ window_days: u32,
+ target_now_day: i32,
+) {
+ let len = buckets.len();
+ let cur_now_day = now_day_for_window(*window_start_day, window_days);
+ if target_now_day <= cur_now_day {
+ return;
+ }
+
+ let shift = (target_now_day - cur_now_day) as usize;
+ if shift >= len {
+ // The whole window slid past: every bucket is now out of range.
+ buckets.iter_mut().for_each(|count| *count = 0);
+ } else {
+ buckets.copy_within(shift.., 0);
+ buckets[len - shift..]
+ .iter_mut()
+ .for_each(|count| *count = 0);
+ }
+ *window_start_day += shift as i32;
+}
+
+/// The day-boundary (epoch ms, team tz) at which the oldest non-zero bucket leaves the window — its
+/// eviction deadline. A day-`d` bucket is in-window while `now_day ≤ d + window_days`, so it leaves
+/// at the start of day `d + window_days + 1`. An all-zero array never evicts → [`i64::MAX`].
+pub(crate) fn daily_eviction_deadline(
+ buckets: &[u32],
+ window_start_day: i32,
+ window_days: u32,
+ tz: Tz,
+) -> i64 {
+ match buckets.iter().position(|&count| count > 0) {
+ Some(oldest) => {
+ let oldest_day = window_start_day + oldest as i32;
+ window_leave_day_ms(oldest_day, window_days, tz)
+ }
+ None => i64::MAX,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::America::New_York;
+ use chrono_tz::UTC;
+
+ use crate::stage1::bucket_tz::{day_idx_in_tz, start_of_day_ms_in_tz};
+
+ fn slide(
+ mut buckets: Vec<u32>,
+ mut window_start_day: i32,
+ window_days: u32,
+ target_now_day: i32,
+ ) -> (Vec<u32>, i32) {
+ slide_window_forward(
+ &mut buckets,
+ &mut window_start_day,
+ window_days,
+ target_now_day,
+ );
+ (buckets, window_start_day)
+ }
+
+ #[test]
+ fn slide_to_the_current_now_day_is_a_noop() {
+ // window_days 7 → len 8, window [100 ..= 107]; target == cur_now_day (107) → unchanged.
+ let buckets = vec![1, 2, 3, 4, 5, 6, 7, 8];
+ let (after, start) = slide(buckets.clone(), 100, 7, 107);
+ assert_eq!(after, buckets);
+ assert_eq!(start, 100);
+ }
+
+ #[test]
+ fn slide_to_a_past_now_day_never_moves_backward() {
+ let buckets = vec![1, 2, 3, 4, 5, 6, 7, 8];
+ let (after, start) = slide(buckets.clone(), 100, 7, 105);
+ assert_eq!(after, buckets, "no slide for a past target");
+ assert_eq!(start, 100);
+ }
+
+ #[test]
+ fn slide_by_one_drops_the_oldest_bucket_and_zeroes_the_new_tail() {
+ // window [100 ..= 107], slide to now-day 108: shift 1, bucket[0] (day 100) falls out, the new
+ // last bucket (day 108) is zeroed, window_start advances to 101.
+ let (after, start) = slide(vec![9, 2, 3, 4, 5, 6, 7, 8], 100, 7, 108);
+ assert_eq!(after, vec![2, 3, 4, 5, 6, 7, 8, 0]);
+ assert_eq!(start, 101);
+ }
+
+ #[test]
+ fn slide_by_several_drops_several_and_zeroes_the_tail() {
+ // Slide to now-day 110: shift 3 → days 100,101,102 fall out; the last 3 buckets are vacated.
+ let (after, start) = slide(vec![1, 2, 3, 4, 5, 6, 7, 8], 100, 7, 110);
+ assert_eq!(after, vec![4, 5, 6, 7, 8, 0, 0, 0]);
+ assert_eq!(start, 103);
+ }
+
+ #[test]
+ fn slide_by_len_minus_one_keeps_only_the_now_day() {
+ // shift == len − 1 (7): only the original last bucket survives, in position 0.
+ let (after, start) = slide(vec![1, 2, 3, 4, 5, 6, 7, 8], 100, 7, 114);
+ assert_eq!(after, vec![8, 0, 0, 0, 0, 0, 0, 0]);
+ assert_eq!(start, 107);
+ }
+
+ #[test]
+ fn slide_by_len_or_more_clears_the_whole_window() {
+ // shift >= len → the whole window slid past; every bucket zeroed, window_start jumps forward.
+ let (after, start) = slide(vec![1, 2, 3, 4, 5, 6, 7, 8], 100, 7, 115);
+ assert_eq!(after, vec![0; 8], "shift == len clears everything");
+ assert_eq!(start, 108);
+
+ let (after_far, start_far) = slide(vec![1, 2, 3, 4, 5, 6, 7, 8], 100, 7, 1_000);
+ assert_eq!(
+ after_far,
+ vec![0; 8],
+ "a far-future target clears everything"
+ );
+ // shift = 1000 − (100 + 7) = 893, so window_start advances 100 → 993.
+ assert_eq!(start_far, 993, "window_start advances by the shift");
+ }
+
+ #[test]
+ fn slide_one_day_window_has_two_buckets() {
+ // window_days 1 → len 2, window [50 ..= 51]; slide to 52 drops day 50.
+ let (after, start) = slide(vec![3, 4], 50, 1, 52);
+ assert_eq!(after, vec![4, 0]);
+ assert_eq!(start, 51);
+ }
+
+ #[test]
+ fn deadline_is_the_start_of_the_day_the_oldest_bucket_leaves() {
+ // Oldest non-zero is bucket 2 (day 102) of an N=7 window; it leaves at start of 102+7+1 = 110.
+ let buckets = [0, 0, 5, 0, 1, 0, 0, 0];
+ assert_eq!(
+ daily_eviction_deadline(&buckets, 100, 7, UTC),
+ start_of_day_ms_in_tz(110, UTC),
+ );
+ }
+
+ #[test]
+ fn deadline_of_an_all_zero_window_never_evicts() {
+ assert_eq!(daily_eviction_deadline(&[0, 0, 0], 100, 2, UTC), i64::MAX);
+ }
+
+ #[test]
+ fn deadline_saturates_for_an_astronomical_window_instead_of_panicking() {
+ // The daily variant is only chosen for window_days ≤ 180 (`pick_state_variant`), so this
+ // pairing is structurally unreachable in production, but the day arithmetic must be total
+ // regardless: `oldest_day + window_days + 1` overflows `i32` for a huge window. Saturation
+ // gives "never evict" → i64::MAX rather than panicking or wrapping.
+ assert_eq!(
+ daily_eviction_deadline(&[1], 1_000, 2_147_483_000, UTC),
+ i64::MAX,
+ );
+ assert_eq!(
+ daily_eviction_deadline(&[1], 1_000, u32::MAX, UTC),
+ i64::MAX
+ );
+ }
+
+ #[test]
+ fn deadline_is_team_tz_local_midnight_not_utc() {
+ // The expiry boundary is the oldest bucket's leave-day as local midnight in the team's zone.
+ // A negative-offset zone (New York) shifts that instant off the UTC day boundary, so the same
+ // day index resolves to a different epoch-ms — the day→instant conversion must be tz-aware.
+ let window_days = 7_u32;
+ let window_start_day = day_idx_in_tz(
+ chrono::DateTime::parse_from_rfc3339("2026-03-01T12:00:00Z")
+ .unwrap()
+ .timestamp_millis(),
+ New_York,
+ );
+ let mut buckets = vec![0_u32; window_days as usize + 1];
+ buckets[0] = 1; // oldest non-zero bucket is the window's lower bound
+
+ // Leaves at start of day window_start_day + 7 + 1, spanning New York's 2026-03-08 DST jump.
+ let leave_day = window_start_day + window_days as i32 + 1;
+ assert_eq!(
+ daily_eviction_deadline(&buckets, window_start_day, window_days, New_York),
+ start_of_day_ms_in_tz(leave_day, New_York),
+ );
+ assert_ne!(
+ start_of_day_ms_in_tz(leave_day, New_York),
+ start_of_day_ms_in_tz(leave_day, UTC),
+ "a negative-offset zone's local midnight differs from UTC midnight",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage1/key.rs b/rust/cohort-stream-processor/src/stage1/key.rs
new file mode 100644
index 000000000000..313d587c9caf
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/key.rs
@@ -0,0 +1,191 @@
+//! `LeafStateKey` derivation and `Stage1Key`.
+//!
+//! `conditionHash` encodes only the event matcher, so two leaves with different windows can share
+//! the same hash. State is keyed by a [`LeafStateKey`] that hashes the full predicate configuration.
+
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use uuid::Uuid;
+
+use crate::filters::tree::BehavioralLeafConfig;
+
+/// 16-byte key discriminating Stage 1 state per cohort leaf.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
+pub struct LeafStateKey(pub [u8; 16]);
+
+impl LeafStateKey {
+ /// Person-property leaves reuse `condition_hash` unchanged.
+ pub fn for_person_property(condition_hash: &[u8; 16]) -> Self {
+ Self(*condition_hash)
+ }
+
+ /// Hash the full predicate config. Field order must match the Python port
+ /// (`_extract_leaf_state_keys` in `posthog/models/cohort/dependencies.py`).
+ pub fn for_behavioral(leaf: &BehavioralLeafConfig) -> Self {
+ let mut h = Sha256::new();
+ h.update(leaf.condition_hash);
+ h.update(leaf.value.as_str().as_bytes());
+ h.update(leaf.time_value.unwrap_or(0).to_le_bytes());
+ h.update(leaf.time_interval.as_deref().unwrap_or("").as_bytes());
+ h.update(leaf.explicit_datetime.as_deref().unwrap_or("").as_bytes());
+ h.update(
+ leaf.explicit_datetime_to
+ .as_deref()
+ .unwrap_or("")
+ .as_bytes(),
+ );
+ h.update(leaf.operator.as_deref().unwrap_or("").as_bytes());
+ h.update(leaf.operator_value.unwrap_or(0).to_le_bytes());
+
+ let digest = h.finalize();
+ let mut out = [0u8; 16];
+ out.copy_from_slice(&digest[..16]);
+ Self(out)
+ }
+}
+
+/// Stage 1 state-storage key. Partition prefix enables per-partition `delete_range` on rebalance.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct Stage1Key {
+ pub partition_id: u16,
+ pub team_id: u64,
+ pub leaf_state_key: LeafStateKey,
+ pub person_id: Uuid,
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use super::*;
+ use crate::filters::tree::{BehavioralLeafConfig, BehavioralValue};
+
+ const HASH: [u8; 16] = *b"0123456789abcdef";
+
+ fn baseline() -> BehavioralLeafConfig {
+ BehavioralLeafConfig {
+ condition_hash: HASH,
+ value: BehavioralValue::PerformedEventMultiple,
+ event_key: "$pageview".to_string(),
+ time_value: Some(7),
+ time_interval: Some("day".to_string()),
+ operator: Some("gte".to_string()),
+ operator_value: Some(3),
+ explicit_datetime: None,
+ explicit_datetime_to: None,
+ leaf_state_key: LeafStateKey([0u8; 16]),
+ state_variant: None,
+ bytecode: Arc::new(vec![]),
+ negated: false,
+ }
+ .with_state_key()
+ }
+
+ fn assert_field_discriminates(mutate: impl FnOnce(&mut BehavioralLeafConfig)) {
+ let base = baseline();
+ let mut variant = base.clone();
+ mutate(&mut variant);
+ assert_ne!(
+ LeafStateKey::for_behavioral(&base),
+ LeafStateKey::for_behavioral(&variant),
+ );
+ }
+
+ #[test]
+ fn person_property_key_is_the_condition_hash() {
+ assert_eq!(LeafStateKey::for_person_property(&HASH), LeafStateKey(HASH));
+ }
+
+ #[test]
+ fn behavioral_key_is_deterministic() {
+ assert_eq!(
+ LeafStateKey::for_behavioral(&baseline()),
+ LeafStateKey::for_behavioral(&baseline()),
+ );
+ }
+
+ /// Golden vector leaf with every field set to a distinct, non-default value.
+ fn golden_leaf() -> BehavioralLeafConfig {
+ BehavioralLeafConfig {
+ condition_hash: HASH,
+ value: BehavioralValue::PerformedEventMultiple,
+ event_key: "$pageview".to_string(),
+ time_value: Some(7),
+ time_interval: Some("day".to_string()),
+ operator: Some("gte".to_string()),
+ operator_value: Some(3),
+ explicit_datetime: Some("2026-01-01T00:00:00Z".to_string()),
+ explicit_datetime_to: Some("2026-02-01T00:00:00Z".to_string()),
+ leaf_state_key: LeafStateKey([0u8; 16]),
+ state_variant: None,
+ bytecode: Arc::new(vec![]),
+ negated: false,
+ }
+ .with_state_key()
+ }
+
+ #[test]
+ fn for_behavioral_matches_known_vector() {
+ const EXPECTED: [u8; 16] = [
+ 0xac, 0xe2, 0xf2, 0x56, 0xd8, 0x43, 0x41, 0xa9, 0x2d, 0x9f, 0xeb, 0xe4, 0x44, 0x9a,
+ 0x41, 0xb7,
+ ];
+ assert_eq!(
+ LeafStateKey::for_behavioral(&golden_leaf()),
+ LeafStateKey(EXPECTED),
+ "the cross-runtime hash encoding changed; update the Python port to match",
+ );
+ }
+
+ #[test]
+ fn event_key_is_excluded_from_the_key() {
+ let mut other = golden_leaf();
+ other.event_key = "$autocapture".to_string();
+ assert_eq!(
+ LeafStateKey::for_behavioral(&golden_leaf()),
+ LeafStateKey::for_behavioral(&other),
+ );
+ }
+
+ #[test]
+ fn with_state_key_caches_the_derived_key() {
+ let leaf = baseline();
+ assert_eq!(leaf.leaf_state_key, LeafStateKey::for_behavioral(&leaf));
+ }
+
+ #[test]
+ fn behavioral_key_differs_from_raw_condition_hash() {
+ assert_ne!(
+ LeafStateKey::for_behavioral(&baseline()),
+ LeafStateKey::for_person_property(&HASH),
+ );
+ }
+
+ #[test]
+ fn each_discriminating_field_changes_the_key() {
+ assert_field_discriminates(|l| l.value = BehavioralValue::PerformedEvent);
+ assert_field_discriminates(|l| l.time_value = Some(30));
+ assert_field_discriminates(|l| l.time_interval = Some("week".to_string()));
+ assert_field_discriminates(|l| l.operator = Some("lte".to_string()));
+ assert_field_discriminates(|l| l.operator_value = Some(5));
+ assert_field_discriminates(|l| l.explicit_datetime = Some("2026-01-01".to_string()));
+ assert_field_discriminates(|l| l.explicit_datetime_to = Some("2026-02-01".to_string()));
+ }
+
+ #[test]
+ fn condition_hash_changes_the_key() {
+ assert_field_discriminates(|l| l.condition_hash = *b"fedcba9876543210");
+ }
+
+ #[test]
+ fn negation_is_excluded_from_the_key() {
+ let positive = baseline();
+ let mut negated = baseline();
+ negated.negated = true;
+ assert_eq!(
+ LeafStateKey::for_behavioral(&positive),
+ LeafStateKey::for_behavioral(&negated),
+ "configs differing only in `negated` must hash equal — state is invariant to negation",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage1/mod.rs b/rust/cohort-stream-processor/src/stage1/mod.rs
new file mode 100644
index 000000000000..052bb7711405
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/mod.rs
@@ -0,0 +1,21 @@
+//! Stage 1: per-`(team_id, leaf_state_key, person_id)` incremental state, emitting a transition
+//! when a leaf predicate flips. State is keyed by a derived `leaf_state_key`, not `condition_hash`
+//! alone, because the bytecode omits the window and threshold.
+
+pub mod bucket_tz;
+pub mod compressed_history;
+pub mod daily;
+pub mod key;
+pub mod pick_state;
+pub mod predicate;
+pub mod state;
+pub mod time;
+pub mod transition;
+
+pub use pick_state::{
+ pick_state_variant, EvictionWindow, PredicateOp, TimeInterval, UnsupportedVariant,
+};
+pub use predicate::{compressed_predicate, daily_predicate, predicate};
+pub use state::{AppliedOffsets, Stage1State, StateCodecError, StateVariant, StatefulRecord};
+pub use time::clickhouse_timestamp_to_millis;
+pub use transition::{LeafTransition, TransitionKind};
diff --git a/rust/cohort-stream-processor/src/stage1/pick_state.rs b/rust/cohort-stream-processor/src/stage1/pick_state.rs
new file mode 100644
index 000000000000..d38a6892d2b2
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/pick_state.rs
@@ -0,0 +1,914 @@
+//! Choosing a leaf's [`StateVariant`] and eviction window from its config.
+
+use chrono_tz::Tz;
+
+use crate::filters::tree::{BehavioralLeafConfig, BehavioralValue};
+use crate::stage1::bucket_tz::{
+ day_idx_in_tz, day_idx_of_naive_date, start_of_day_ms_in_tz, DayIdx,
+};
+use crate::stage1::state::StateVariant;
+
+/// A cohort time interval with its fixed second-count (the `INTERVAL_TO_SECONDS` contract).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TimeInterval {
+ Minute,
+ Hour,
+ Day,
+ Week,
+ Month,
+ Year,
+}
+
+impl TimeInterval {
+ /// Fixed seconds in this interval (`month = 30d`, `year = 365d`).
+ pub fn seconds(self) -> i64 {
+ match self {
+ Self::Minute => 60,
+ Self::Hour => 3_600,
+ Self::Day => 86_400,
+ Self::Week => 604_800,
+ Self::Month => 2_592_000,
+ Self::Year => 31_536_000,
+ }
+ }
+
+ /// Whole days in this interval: `0` for sub-day intervals.
+ pub fn to_days(self) -> u32 {
+ (self.seconds() / 86_400) as u32
+ }
+
+ /// Parse the wire string, or [`None`] for an unrecognized one.
+ pub fn from_wire(s: &str) -> Option<Self> {
+ Some(match s {
+ "minute" => Self::Minute,
+ "hour" => Self::Hour,
+ "day" => Self::Day,
+ "week" => Self::Week,
+ "month" => Self::Month,
+ "year" => Self::Year,
+ _ => return None,
+ })
+ }
+}
+
+/// How a `BehavioralSingle` leaf's eviction deadline is derived.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum EvictionWindow {
+ /// A whole-day window: evicts at tz-midnight of `day(newest_event) + days + 1`.
+ RelativeDays { days: u32 },
+ /// A sub-day window (`hour`/`minute`): deadline is `newest_event + seconds`.
+ RelativeSeconds { seconds: i64 },
+ /// A fixed **absolute** date range (`explicit_datetime`(_to) that parse as absolute datetimes).
+ /// Bounds are tz-naive calendar **day** indices (days since 1970-01-01); either side `None` means
+ /// unbounded on that side. The oracle treats a bare/naive `explicit_datetime` as a tz-naive
+ /// calendar date (`toDate('2026-05-01')` is the literal date, tz-invariant), so the bound is a day,
+ /// not a UTC instant — storing it as a day keeps it from shifting under a UTC-offset team timezone.
+ /// Once matched within the range, membership is permanent (never evicted) — the oracle compares
+ /// against fixed calendar dates, so a match can never age out. The day-granularity in-range check
+ /// lives in the event path (`mutate_behavioral`), keyed off these bounds.
+ Explicit {
+ from_day: Option<DayIdx>,
+ to_day: Option<DayIdx>,
+ },
+}
+
+impl EvictionWindow {
+ /// The earliest epoch-ms at which this state may be evicted, given the newest matching event
+ /// time and the team's timezone.
+ pub fn earliest_eviction_at_ms(self, newest_event_ms: i64, tz: Tz) -> i64 {
+ match self {
+ Self::RelativeDays { days } => {
+ let leave_day = i64::from(day_idx_in_tz(newest_event_ms, tz)) + i64::from(days) + 1;
+ match i32::try_from(leave_day) {
+ Ok(day) => start_of_day_ms_in_tz(day, tz),
+ Err(_) => i64::MAX,
+ }
+ }
+ Self::RelativeSeconds { seconds } => {
+ newest_event_ms.saturating_add(seconds.saturating_mul(1_000))
+ }
+ Self::Explicit { .. } => i64::MAX,
+ }
+ }
+}
+
+/// Count comparator for a `performed_event_multiple` leaf's window sum.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PredicateOp {
+ Gte(u32),
+ Lte(u32),
+ Gt(u32),
+ Lt(u32),
+ Eq(u32),
+}
+
+impl PredicateOp {
+ /// Resolve a leaf's `(operator, operator_value)` to a comparator. Defaults to `eq`.
+ pub fn from_leaf(operator: Option<&str>, operator_value: Option<i32>) -> Self {
+ let value = operator_value.unwrap_or(0).max(0) as u32;
+ match operator {
+ Some("gte") => Self::Gte(value),
+ Some("lte") => Self::Lte(value),
+ Some("gt") => Self::Gt(value),
+ Some("lt") => Self::Lt(value),
+ // `eq`, `exact`, absent, or unrecognized all map to `eq` (the pipeline's default).
+ _ => Self::Eq(value),
+ }
+ }
+
+ /// Evaluate the comparator against a window `count`.
+ pub fn evaluate(self, count: u32) -> bool {
+ match self {
+ Self::Gte(value) => count >= value,
+ Self::Lte(value) => count <= value,
+ Self::Gt(value) => count > value,
+ Self::Lt(value) => count < value,
+ Self::Eq(value) => count == value,
+ }
+ }
+}
+
+/// Why a behavioral leaf has no supported state representation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum UnsupportedVariant {
+ /// A `performed_event_multiple` with a sub-day window (`hour`/`minute`).
+ #[error("performed_event_multiple sub-day window is unsupported")]
+ HourlyDeferred,
+ #[error("performed_event leaf has no resolvable window")]
+ MissingWindow,
+ #[error("behavioral value does not contribute realtime bytecode")]
+ NonRealtimeValue,
+ /// An `explicit_datetime` range the sweep cannot model: a relative *upper* bound, or a relative
+ /// lower bound paired with any upper bound. These need delayed entry and double-ended eviction
+ /// (a person enters only once the relative `from` slides past and leaves once the relative `to`
+ /// does), which the single-deadline sweep does not represent. Skipping the leaf is the safe
+ /// choice — no realtime state, hence no wrong members — until that machinery exists.
+ #[error("explicit_datetime relative range is unsupported")]
+ RelativeRangeUnsupported,
+ /// A *present* `explicit_datetime`(_to) bound that parses as neither an absolute date nor a known
+ /// relative grammar. Skipping the leaf (no realtime state) is safe; silently nulling the bound
+ /// would turn a closed range open-ended and create permanent members past the intended end.
+ #[error("explicit_datetime bound is unparseable")]
+ UnparseableExplicitBound,
+}
+
+/// Pick the [`StateVariant`] and eviction window for a behavioral leaf, or why it is unsupported.
+pub fn pick_state_variant(
+ leaf: &BehavioralLeafConfig,
+) -> Result<(StateVariant, Option<EvictionWindow>), UnsupportedVariant> {
+ match leaf.value {
+ BehavioralValue::PerformedEvent => {
+ Ok((StateVariant::BehavioralSingle, Some(eviction_window(leaf)?)))
+ }
+ BehavioralValue::PerformedEventMultiple => match effective_window_days(leaf) {
+ 0 => Err(UnsupportedVariant::HourlyDeferred),
+ 1..=180 => Ok((StateVariant::BehavioralDailyBuckets, None)),
+ _ => Ok((StateVariant::BehavioralCompressedHistory, None)),
+ },
+ BehavioralValue::PerformedEventFirstTime
+ | BehavioralValue::PerformedEventSequence
+ | BehavioralValue::PerformedEventRegularly
+ | BehavioralValue::StoppedPerformingEvent
+ | BehavioralValue::RestartedPerformingEvent => Err(UnsupportedVariant::NonRealtimeValue),
+ }
+}
+
+/// Derive the eviction window from a leaf's datetime/interval config.
+///
+/// `explicit_datetime`(_to) takes precedence over `time_value`/`time_interval` (mirroring the
+/// oracle's `if prop.explicit_datetime` branch in `hogql_cohort_query.py`). The oracle resolves each
+/// `explicit_datetime` bound as either an absolute datetime or a relative offset (`relative_date_parse`,
+/// same convention as every analytics date filter), so we classify each present bound the same way:
+/// - **absolute** (parses as a datetime) → an [`EvictionWindow::Explicit`] bound;
+/// - **relative lower-only** (`"-Nd"` with no upper bound) → the equivalent relative window, which
+/// is byte-identical to the `time_value:N, time_interval:<unit>` path the oracle also funnels
+/// through `relative_date_parse` — so a sliding window recovers the common case correctly;
+/// - **relative with any upper bound, or a relative upper bound** → [`UnsupportedVariant`], because
+/// the sweep cannot model delayed entry / double-ended eviction.
+fn eviction_window(leaf: &BehavioralLeafConfig) -> Result<EvictionWindow, UnsupportedVariant> {
+ if leaf.explicit_datetime.is_some() || leaf.explicit_datetime_to.is_some() {
+ return explicit_eviction_window(
+ leaf.explicit_datetime.as_deref(),
+ leaf.explicit_datetime_to.as_deref(),
+ );
+ }
+ let interval = leaf
+ .time_interval
+ .as_deref()
+ .and_then(TimeInterval::from_wire)
+ .ok_or(UnsupportedVariant::MissingWindow)?;
+ Ok(relative_window_from_interval(interval, leaf.time_value))
+}
+
+/// Classify an `explicit_datetime`(_to) pair into an eviction window. See [`eviction_window`].
+fn explicit_eviction_window(
+ from: Option<&str>,
+ to: Option<&str>,
+) -> Result<EvictionWindow, UnsupportedVariant> {
+ // Each present bound is absolute (parses as a datetime) or relative (parses as `-N<unit>`).
+ let from_kind = from.map(classify_bound);
+ let to_kind = to.map(classify_bound);
+
+ match (from_kind, to_kind) {
+ // A *present* bound that parses as neither absolute nor a known relative grammar must skip the
+ // leaf, not be silently nulled — dropping one side of a closed range would make it open-ended
+ // and create permanent members past the intended end. Only a genuinely ABSENT (`None`) bound
+ // means "unbounded on that side".
+ (Some(Bound::Unparseable), _) | (_, Some(Bound::Unparseable)) => {
+ Err(UnsupportedVariant::UnparseableExplicitBound)
+ }
+ // A relative *upper* bound (with or without a lower bound) needs delayed double-ended
+ // eviction the sweep does not model.
+ (_, Some(Bound::Relative(_))) => Err(UnsupportedVariant::RelativeRangeUnsupported),
+ // A relative *lower* bound combined with any upper bound is the same problem: the person
+ // would enter only once the relative `from` slides past, then leave at the upper bound.
+ (Some(Bound::Relative(_)), Some(Bound::Absolute(_))) => {
+ Err(UnsupportedVariant::RelativeRangeUnsupported)
+ }
+ // Relative lower bound, no upper bound — the dominant `performed_event` shape ("in the last
+ // N days"). Map it to the matching sliding window; an unrepresentable unit (e.g. `q`) skips.
+ (Some(Bound::Relative(window)), None) => {
+ window.ok_or(UnsupportedVariant::RelativeRangeUnsupported)
+ }
+ // Absolute (or absent) on both sides — a fixed calendar range, permanent membership.
+ (from_kind, to_kind) => Ok(EvictionWindow::Explicit {
+ from_day: from_kind.and_then(Bound::absolute_day),
+ to_day: to_kind.and_then(Bound::absolute_day),
+ }),
+ }
+}
+
+/// One classified `explicit_datetime` bound.
+#[derive(Debug, Clone, Copy)]
+enum Bound {
+ /// An absolute datetime, as a tz-naive calendar **day** index (its written date).
+ Absolute(DayIdx),
+ /// A relative offset (`-N<unit>`), mapped to its sliding window — or `None` for a known-relative
+ /// grammar we cannot represent (e.g. a quarter, which has no `TimeInterval`).
+ Relative(Option<EvictionWindow>),
+ /// Parses as neither an absolute datetime nor a recognized relative grammar.
+ Unparseable,
+}
+
+impl Bound {
+ /// The absolute calendar-day index, if this bound is absolute.
+ fn absolute_day(self) -> Option<DayIdx> {
+ match self {
+ Self::Absolute(day) => Some(day),
+ Self::Relative(_) | Self::Unparseable => None,
+ }
+ }
+}
+
+/// Classify a single `explicit_datetime` bound string.
+fn classify_bound(raw: &str) -> Bound {
+ if let Some(day) = absolute_datetime_to_day(raw) {
+ return Bound::Absolute(day);
+ }
+ match relative_offset_to_window(raw) {
+ Some(window) => Bound::Relative(window),
+ None => Bound::Unparseable,
+ }
+}
+
+/// Extract an absolute `explicit_datetime` bound's calendar **date** (date part), **tz-naively**, as a
+/// day index. The oracle treats a naive `explicit_datetime` as a tz-naive calendar date stamped in the
+/// project tz, so `toDate('2026-05-01')` is the literal `2026-05-01` regardless of timezone — the bound
+/// must therefore be a day, not a UTC instant (storing it as a UTC instant shifts it one calendar day
+/// earlier for a UTC-offset team). Accepts every naive shape the system emits:
+/// - bare `%Y-%m-%d` (the date-picker's date-only / oracle `strptime("%Y-%m-%d")` fallback),
+/// - `%Y-%m-%dT%H:%M:%S` (the date-picker's T-separated naive form — `dateFilterLogic.ts`),
+/// - `%Y-%m-%d %H:%M:%S%.f` (the space-separated ClickHouse form),
+/// - RFC3339 with offset (a non-UI edge): take its **written local date** via `.date_naive()`, not the
+/// UTC-normalized one — the oracle's `toDate` is on the project-tz wall clock, and an offset-bearing
+/// bound is not produced by the cohort date picker, so the written-date reading is the conservative
+/// match.
+///
+/// Relative strings (`"-30d"`) return [`None`].
+fn absolute_datetime_to_day(raw: &str) -> Option<DayIdx> {
+ use chrono::{DateTime, NaiveDate, NaiveDateTime};
+
+ // Offset-bearing RFC3339: take the written local date, not the UTC-normalized instant.
+ if let Ok(dt) = DateTime::parse_from_rfc3339(raw) {
+ return Some(day_idx_of_naive_date(dt.date_naive()));
+ }
+ // Naive datetime, T-separated (the date picker) or space-separated (ClickHouse) — date part only.
+ let naive = NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S%.f")
+ .or_else(|_| NaiveDateTime::parse_from_str(raw, "%Y-%m-%d %H:%M:%S%.f"))
+ .map(|dt| dt.date())
+ // Bare date.
+ .or_else(|_| NaiveDate::parse_from_str(raw, "%Y-%m-%d"))
+ .ok()?;
+ Some(day_idx_of_naive_date(naive))
+}
+
+/// Parse a relative offset (`-N<unit>`) into its sliding [`EvictionWindow`], matching the oracle's
+/// `relative_date_parse` grammar. Returns:
+/// - `Some(Some(window))` for a unit with a clean `TimeInterval` equivalent (`d`/`w`/`m`/`y`/`h`/`M`);
+/// - `Some(None)` for a recognized-but-unrepresentable unit (`q` quarter, `s` second — no cohort UI
+/// emits these and they have no `TimeInterval`), signalling "relative, but skip the leaf";
+/// - `None` when the string is not a relative offset at all.
+///
+/// `m` is **months** and `M` is **minutes** (Python's `[hdwmqysHDWMQY]` grammar is case-sensitive on
+/// `m`/`M`). Mapping each unit through [`TimeInterval`] keeps a relative `-N<unit>` byte-identical to
+/// the `time_value:N, time_interval:<unit>` path, which is exactly how the oracle treats them.
+fn relative_offset_to_window(raw: &str) -> Option<Option<EvictionWindow>> {
+ let rest = raw.strip_prefix('-')?;
+ // Split into the leading digit run and the trailing unit (+ optional `Start`/`End`, which we drop
+ // — the cohort UI never emits it and it does not change the window length).
+ let split = rest.find(|c: char| !c.is_ascii_digit())?;
+ let (digits, tail) = rest.split_at(split);
+ let count: i32 = digits.parse().ok()?;
+ let unit = tail
+ .strip_suffix("Start")
+ .or_else(|| tail.strip_suffix("End"))
+ .unwrap_or(tail);
+ let interval = match unit {
+ "d" => TimeInterval::Day,
+ "w" => TimeInterval::Week,
+ "m" => TimeInterval::Month,
+ "y" => TimeInterval::Year,
+ "h" => TimeInterval::Hour,
+ "M" => TimeInterval::Minute,
+ // `q` (quarter) and `s` (second) are valid relative grammar but have no `TimeInterval`; the
+ // cohort UI never emits them. Signal "relative, unrepresentable" so the leaf is skipped.
+ "q" | "s" => return Some(None),
+ _ => return None,
+ };
+ Some(Some(relative_window_from_interval(interval, Some(count))))
+}
+
+/// Build the sliding [`EvictionWindow`] for `time_value × interval`. Sub-day intervals yield
+/// [`EvictionWindow::RelativeSeconds`]; whole-day intervals yield [`EvictionWindow::RelativeDays`].
+/// A negative or absent `time_value` clamps to 0 rather than going negative.
+fn relative_window_from_interval(
+ interval: TimeInterval,
+ time_value: Option<i32>,
+) -> EvictionWindow {
+ let time_value = time_value.unwrap_or(0).max(0);
+ if interval.to_days() == 0 {
+ EvictionWindow::RelativeSeconds {
+ seconds: i64::from(time_value).saturating_mul(interval.seconds()),
+ }
+ } else {
+ EvictionWindow::RelativeDays {
+ days: u32::try_from(time_value)
+ .unwrap_or(0)
+ .saturating_mul(interval.to_days()),
+ }
+ }
+}
+
+/// The whole-day window for a `performed_event_multiple` leaf: `time_value × interval.to_days()`.
+/// Returns `0` for sub-day or unrecognized intervals.
+pub(crate) fn effective_window_days(leaf: &BehavioralLeafConfig) -> u32 {
+ let Some(interval) = leaf
+ .time_interval
+ .as_deref()
+ .and_then(TimeInterval::from_wire)
+ else {
+ return 0;
+ };
+ let time_value = u32::try_from(leaf.time_value.unwrap_or(0).max(0)).unwrap_or(0);
+ time_value.saturating_mul(interval.to_days())
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use chrono::{NaiveDate, TimeZone, Utc};
+ use chrono_tz::America::New_York;
+ use chrono_tz::UTC;
+
+ use super::*;
+
+ use crate::stage1::key::LeafStateKey;
+
+ const HASH: [u8; 16] = *b"0123456789abcdef";
+
+ /// Epoch-ms of a UTC wall-clock time.
+ fn utc_ms(year: i32, month: u32, day: u32, hour: u32, minute: u32) -> i64 {
+ Utc.with_ymd_and_hms(year, month, day, hour, minute, 0)
+ .unwrap()
+ .timestamp_millis()
+ }
+
+ /// The tz-naive calendar-day index of a `Y-M-D` date — what an absolute bound resolves to.
+ fn day_of(year: i32, month: u32, day: u32) -> DayIdx {
+ day_idx_of_naive_date(NaiveDate::from_ymd_opt(year, month, day).unwrap())
+ }
+
+ fn leaf(
+ value: BehavioralValue,
+ time_value: Option<i32>,
+ time_interval: Option<&str>,
+ ) -> BehavioralLeafConfig {
+ BehavioralLeafConfig {
+ condition_hash: HASH,
+ value,
+ event_key: "$pageview".to_string(),
+ time_value,
+ operator_value: None,
+ time_interval: time_interval.map(str::to_string),
+ operator: None,
+ explicit_datetime: None,
+ explicit_datetime_to: None,
+ leaf_state_key: LeafStateKey([0u8; 16]),
+ state_variant: None,
+ bytecode: Arc::new(vec![]),
+ negated: false,
+ }
+ .with_state_key()
+ }
+
+ #[test]
+ fn interval_seconds_match_the_python_constants() {
+ assert_eq!(TimeInterval::Minute.seconds(), 60);
+ assert_eq!(TimeInterval::Hour.seconds(), 3_600);
+ assert_eq!(TimeInterval::Day.seconds(), 86_400);
+ assert_eq!(TimeInterval::Week.seconds(), 604_800);
+ assert_eq!(TimeInterval::Month.seconds(), 2_592_000);
+ assert_eq!(TimeInterval::Year.seconds(), 31_536_000);
+ }
+
+ #[test]
+ fn to_days_floors_each_interval_and_gives_year_day_equivalence() {
+ assert_eq!(TimeInterval::Minute.to_days(), 0);
+ assert_eq!(TimeInterval::Hour.to_days(), 0);
+ assert_eq!(TimeInterval::Day.to_days(), 1);
+ assert_eq!(TimeInterval::Week.to_days(), 7);
+ assert_eq!(TimeInterval::Month.to_days(), 30);
+ assert_eq!(TimeInterval::Year.to_days(), 365);
+ assert_eq!(
+ TimeInterval::Year.to_days(),
+ 365 * TimeInterval::Day.to_days()
+ );
+ }
+
+ #[test]
+ fn from_wire_round_trips_every_interval() {
+ for (wire, interval) in [
+ ("minute", TimeInterval::Minute),
+ ("hour", TimeInterval::Hour),
+ ("day", TimeInterval::Day),
+ ("week", TimeInterval::Week),
+ ("month", TimeInterval::Month),
+ ("year", TimeInterval::Year),
+ ] {
+ assert_eq!(TimeInterval::from_wire(wire), Some(interval));
+ }
+ assert_eq!(TimeInterval::from_wire("fortnight"), None);
+ }
+
+ #[test]
+ fn performed_event_is_behavioral_single_with_relative_window() {
+ let (variant, window) =
+ pick_state_variant(&leaf(BehavioralValue::PerformedEvent, Some(7), Some("day")))
+ .unwrap();
+ assert_eq!(variant, StateVariant::BehavioralSingle);
+ assert_eq!(window, Some(EvictionWindow::RelativeDays { days: 7 }));
+ }
+
+ #[test]
+ fn day_window_yields_relative_days_and_subday_yields_seconds() {
+ let cases = [
+ ("day", EvictionWindow::RelativeDays { days: 2 }),
+ ("week", EvictionWindow::RelativeDays { days: 2 * 7 }),
+ ("month", EvictionWindow::RelativeDays { days: 2 * 30 }),
+ ("year", EvictionWindow::RelativeDays { days: 2 * 365 }),
+ (
+ "hour",
+ EvictionWindow::RelativeSeconds { seconds: 2 * 3_600 },
+ ),
+ (
+ "minute",
+ EvictionWindow::RelativeSeconds { seconds: 2 * 60 },
+ ),
+ ];
+ for (interval, expected) in cases {
+ let (variant, window) = pick_state_variant(&leaf(
+ BehavioralValue::PerformedEvent,
+ Some(2),
+ Some(interval),
+ ))
+ .unwrap();
+ assert_eq!(variant, StateVariant::BehavioralSingle, "{interval}");
+ assert_eq!(window, Some(expected), "{interval}");
+ }
+ }
+
+ #[test]
+ fn performed_event_multiple_routes_by_effective_window_days() {
+ use BehavioralValue::PerformedEventMultiple as Multiple;
+ let daily = Ok((StateVariant::BehavioralDailyBuckets, None));
+ let compressed = Ok((StateVariant::BehavioralCompressedHistory, None));
+ let cases = [
+ (
+ Some(1),
+ "day",
+ daily,
+ "day,1 = 1 day → daily (lower boundary)",
+ ),
+ (Some(7), "day", daily, "day,7 = 7 days → daily"),
+ (Some(1), "week", daily, "week,1 = 7 days → daily"),
+ (Some(180), "day", daily, "day,180 → daily (upper boundary)"),
+ (
+ Some(181),
+ "day",
+ compressed,
+ "day,181 → compressed (just over the boundary)",
+ ),
+ (
+ Some(5),
+ "hour",
+ Err(UnsupportedVariant::HourlyDeferred),
+ "hour,5 = 0 whole days → hourly-deferred",
+ ),
+ (
+ Some(30),
+ "minute",
+ Err(UnsupportedVariant::HourlyDeferred),
+ "minute,30 = 0 whole days → hourly-deferred",
+ ),
+ (
+ Some(1),
+ "year",
+ compressed,
+ "year,1 = 365 days → compressed",
+ ),
+ (
+ Some(365),
+ "day",
+ compressed,
+ "day,365 = 365 days → compressed, same as 1 year",
+ ),
+ ];
+ for (time_value, interval, expected, why) in cases {
+ assert_eq!(
+ pick_state_variant(&leaf(Multiple, time_value, Some(interval))),
+ expected,
+ "{why}",
+ );
+ }
+ }
+
+ #[test]
+ fn performed_event_multiple_without_window_is_hourly_deferred() {
+ assert_eq!(
+ pick_state_variant(&leaf(BehavioralValue::PerformedEventMultiple, None, None)),
+ Err(UnsupportedVariant::HourlyDeferred),
+ );
+ }
+
+ #[test]
+ fn predicate_op_from_leaf_maps_every_operator_and_defaults_to_eq() {
+ let cases = [
+ (Some("gte"), PredicateOp::Gte(3)),
+ (Some("lte"), PredicateOp::Lte(3)),
+ (Some("gt"), PredicateOp::Gt(3)),
+ (Some("lt"), PredicateOp::Lt(3)),
+ (Some("eq"), PredicateOp::Eq(3)),
+ (Some("exact"), PredicateOp::Eq(3)), // exact aliases eq
+ (None, PredicateOp::Eq(3)), // absent defaults to eq
+ (Some("garbage"), PredicateOp::Eq(3)), // unrecognized falls back to eq
+ ];
+ for (operator, expected) in cases {
+ assert_eq!(
+ PredicateOp::from_leaf(operator, Some(3)),
+ expected,
+ "{operator:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn predicate_op_from_leaf_clamps_absent_or_negative_value_to_zero() {
+ assert_eq!(
+ PredicateOp::from_leaf(Some("gte"), None),
+ PredicateOp::Gte(0)
+ );
+ assert_eq!(
+ PredicateOp::from_leaf(Some("lte"), Some(-5)),
+ PredicateOp::Lte(0)
+ );
+ }
+
+ #[test]
+ fn predicate_op_evaluate_matches_each_comparator() {
+ assert!(PredicateOp::Gte(3).evaluate(3));
+ assert!(!PredicateOp::Gte(3).evaluate(2));
+ assert!(PredicateOp::Lte(3).evaluate(3));
+ assert!(!PredicateOp::Lte(3).evaluate(4));
+ assert!(PredicateOp::Gt(3).evaluate(4));
+ assert!(!PredicateOp::Gt(3).evaluate(3));
+ assert!(PredicateOp::Lt(3).evaluate(2));
+ assert!(!PredicateOp::Lt(3).evaluate(3));
+ assert!(PredicateOp::Eq(3).evaluate(3));
+ assert!(!PredicateOp::Eq(3).evaluate(2));
+ }
+
+ #[test]
+ fn performed_event_without_window_is_unsupported() {
+ assert_eq!(
+ pick_state_variant(&leaf(BehavioralValue::PerformedEvent, None, None)),
+ Err(UnsupportedVariant::MissingWindow),
+ );
+ assert_eq!(
+ pick_state_variant(&leaf(
+ BehavioralValue::PerformedEvent,
+ Some(7),
+ Some("fortnight")
+ )),
+ Err(UnsupportedVariant::MissingWindow),
+ );
+ }
+
+ /// Build a `performed_event` leaf carrying an explicit datetime range.
+ fn explicit_leaf(from: Option<&str>, to: Option<&str>) -> BehavioralLeafConfig {
+ let mut l = leaf(BehavioralValue::PerformedEvent, None, None);
+ l.explicit_datetime = from.map(str::to_string);
+ l.explicit_datetime_to = to.map(str::to_string);
+ l.with_state_key()
+ }
+
+ #[test]
+ fn absolute_explicit_datetime_yields_an_explicit_window() {
+ // The space-separated ClickHouse form and the date picker's T-separated naive form must both
+ // resolve to the same calendar-day bounds — the date part, tz-naively.
+ for (from, to) in [
+ ("2026-01-01 00:00:00.000000", "2026-02-01 00:00:00.000000"),
+ ("2026-01-01T00:00:00", "2026-02-01T00:00:00"),
+ ] {
+ let (variant, window) =
+ pick_state_variant(&explicit_leaf(Some(from), Some(to))).unwrap();
+ assert_eq!(variant, StateVariant::BehavioralSingle);
+ assert_eq!(
+ window,
+ Some(EvictionWindow::Explicit {
+ from_day: Some(day_of(2026, 1, 1)),
+ to_day: Some(day_of(2026, 2, 1)),
+ }),
+ "{from}..{to}",
+ );
+ }
+ }
+
+ #[test]
+ fn absolute_explicit_from_only_leaves_upper_bound_unbounded() {
+ let from = "2026-01-01 00:00:00.000000";
+ let (_, window) = pick_state_variant(&explicit_leaf(Some(from), None)).unwrap();
+ assert_eq!(
+ window,
+ Some(EvictionWindow::Explicit {
+ from_day: Some(day_of(2026, 1, 1)),
+ to_day: None,
+ }),
+ );
+ }
+
+ #[test]
+ fn absolute_explicit_to_only_leaves_lower_bound_unbounded() {
+ let to = "2026-02-01 00:00:00.000000";
+ let (_, window) = pick_state_variant(&explicit_leaf(None, Some(to))).unwrap();
+ assert_eq!(
+ window,
+ Some(EvictionWindow::Explicit {
+ from_day: None,
+ to_day: Some(day_of(2026, 2, 1)),
+ }),
+ );
+ }
+
+ #[test]
+ fn absolute_datetime_to_day_is_the_literal_date_for_every_accepted_shape() {
+ // Bare, T-separated naive (the date picker), space-separated ClickHouse, and RFC3339-with-offset
+ // must all yield the same tz-naive calendar day — the written date, never UTC-shifted.
+ let expected = day_of(2026, 5, 1);
+ for raw in [
+ "2026-05-01",
+ "2026-05-01T00:00:00",
+ "2026-05-01 00:00:00.000000",
+ "2026-05-01T12:34:56-04:00", // offset-bearing: written local date is still 2026-05-01
+ ] {
+ assert_eq!(absolute_datetime_to_day(raw), Some(expected), "{raw}");
+ }
+ // A relative offset is not an absolute date.
+ assert_eq!(absolute_datetime_to_day("-30d"), None);
+ }
+
+ #[test]
+ fn bare_date_explicit_bound_parses_as_the_literal_calendar_day() {
+ // The cohort date picker can emit a date-only absolute bound; the oracle accepts it via its
+ // `strptime("%Y-%m-%d")` fallback. It resolves to the literal calendar day, tz-invariant.
+ let (_, window) = pick_state_variant(&explicit_leaf(Some("2026-01-01"), None)).unwrap();
+ assert_eq!(
+ window,
+ Some(EvictionWindow::Explicit {
+ from_day: Some(day_of(2026, 1, 1)),
+ to_day: None,
+ }),
+ );
+ }
+
+ #[test]
+ fn ui_t_separated_upper_bound_parses_and_bounds_the_range() {
+ // The date picker emits the upper bound as `dayjs(...).format('YYYY-MM-DDTHH:mm:ss')`
+ // (T-separated, no offset). It must parse to the correct `to_day`, not be silently dropped —
+ // dropping it would turn the closed range open-ended.
+ let (_, window) = pick_state_variant(&explicit_leaf(
+ Some("2026-01-01"),
+ Some("2026-12-31T00:00:00"),
+ ))
+ .unwrap();
+ assert_eq!(
+ window,
+ Some(EvictionWindow::Explicit {
+ from_day: Some(day_of(2026, 1, 1)),
+ to_day: Some(day_of(2026, 12, 31)),
+ }),
+ );
+ }
+
+ #[test]
+ fn a_present_but_unparseable_bound_skips_the_leaf_rather_than_nulling_that_side() {
+ // A present bound that is neither absolute nor relative-grammar must skip the leaf (no state),
+ // NOT be nulled — nulling one side of a closed range would create permanent members past the
+ // intended end.
+ for (from, to) in [
+ (Some("garbage"), Some("2026-12-31")),
+ (Some("2026-01-01"), Some("garbage")),
+ (Some("garbage"), None),
+ ] {
+ assert_eq!(
+ pick_state_variant(&explicit_leaf(from, to)),
+ Err(UnsupportedVariant::UnparseableExplicitBound),
+ "{from:?}..{to:?}",
+ );
+ }
+ }
+
+ #[test]
+ fn relative_lower_only_explicit_maps_to_the_matching_sliding_window() {
+ // "-Nd"/"-Nw"/"-Nm"/"-Ny"/"-Nh"/"-NM" with no upper bound are the dominant `performed_event`
+ // shape; each maps to the identical window as `time_value:N, time_interval:<unit>`.
+ let cases = [
+ ("-30d", EvictionWindow::RelativeDays { days: 30 }),
+ ("-1w", EvictionWindow::RelativeDays { days: 7 }),
+ ("-2m", EvictionWindow::RelativeDays { days: 2 * 30 }),
+ ("-1y", EvictionWindow::RelativeDays { days: 365 }),
+ (
+ "-2h",
+ EvictionWindow::RelativeSeconds { seconds: 2 * 3_600 },
+ ),
+ ("-15M", EvictionWindow::RelativeSeconds { seconds: 15 * 60 }),
+ ];
+ for (raw, expected) in cases {
+ let (variant, window) = pick_state_variant(&explicit_leaf(Some(raw), None)).unwrap();
+ assert_eq!(variant, StateVariant::BehavioralSingle, "{raw}");
+ assert_eq!(window, Some(expected), "{raw}");
+ }
+ }
+
+ #[test]
+ fn relative_window_matches_the_time_value_interval_path_byte_for_byte() {
+ // A relative `explicit_datetime` and the equivalent `time_value`/`time_interval` must resolve
+ // to the same window — they are the same query in the oracle.
+ for (raw, time_value, interval) in [
+ ("-30d", 30, "day"),
+ ("-1w", 1, "week"),
+ ("-2m", 2, "month"),
+ ("-1y", 1, "year"),
+ ("-2h", 2, "hour"),
+ ("-15M", 15, "minute"),
+ ] {
+ let (_, relative) = pick_state_variant(&explicit_leaf(Some(raw), None)).unwrap();
+ let (_, interval_path) = pick_state_variant(&leaf(
+ BehavioralValue::PerformedEvent,
+ Some(time_value),
+ Some(interval),
+ ))
+ .unwrap();
+ assert_eq!(relative, interval_path, "{raw} vs {time_value}{interval}");
+ }
+ }
+
+ #[test]
+ fn relative_explicit_ranges_and_relative_upper_bounds_are_unsupported() {
+ // Two-sided relative, relative upper bound, and relative-lower + absolute-upper all need
+ // delayed-entry / double-ended eviction the sweep cannot model.
+ let cases = [
+ (Some("-30d"), Some("-7d")), // two-sided relative
+ (Some("2026-01-01 00:00:00.000000"), Some("-7d")), // absolute lower, relative upper
+ (Some("-30d"), Some("2026-12-31 00:00:00.000000")), // relative lower, absolute upper
+ (None, Some("-7d")), // relative upper only
+ ];
+ for (from, to) in cases {
+ assert_eq!(
+ pick_state_variant(&explicit_leaf(from, to)),
+ Err(UnsupportedVariant::RelativeRangeUnsupported),
+ "{from:?}..{to:?}",
+ );
+ }
+ }
+
+ #[test]
+ fn unrepresentable_relative_units_are_unsupported() {
+ // `q` (quarter) and `s` (second) are valid relative grammar but have no `TimeInterval`, so a
+ // relative-lower-only bound in one of those units skips as a relative range.
+ for raw in ["-1q", "-30s"] {
+ assert_eq!(
+ pick_state_variant(&explicit_leaf(Some(raw), None)),
+ Err(UnsupportedVariant::RelativeRangeUnsupported),
+ "{raw}",
+ );
+ }
+ }
+
+ #[test]
+ fn an_outright_garbage_bound_is_an_unparseable_skip() {
+ // A string that is neither an absolute date nor relative grammar is `UnparseableExplicitBound`,
+ // distinct from a recognized-relative-but-unrepresentable unit.
+ assert_eq!(
+ pick_state_variant(&explicit_leaf(Some("not-a-date"), None)),
+ Err(UnsupportedVariant::UnparseableExplicitBound),
+ );
+ }
+
+ #[test]
+ fn subday_window_deadline_is_event_plus_window() {
+ let window = EvictionWindow::RelativeSeconds { seconds: 5 * 3_600 };
+ assert_eq!(
+ window.earliest_eviction_at_ms(1_000, UTC),
+ 1_000 + 5 * 3_600 * 1_000,
+ );
+ assert_eq!(
+ window.earliest_eviction_at_ms(1_000, New_York),
+ 1_000 + 5 * 3_600 * 1_000,
+ "a sub-day deadline does not depend on the timezone",
+ );
+ }
+
+ #[test]
+ fn relative_days_deadline_is_local_midnight_after_the_window() {
+ let event_ms = utc_ms(2026, 5, 26, 12, 34);
+ let window = EvictionWindow::RelativeDays { days: 7 };
+ for tz in [UTC, New_York] {
+ let leave_day = day_idx_in_tz(event_ms, tz) + 7 + 1;
+ assert_eq!(
+ window.earliest_eviction_at_ms(event_ms, tz),
+ start_of_day_ms_in_tz(leave_day, tz),
+ "{tz}",
+ );
+ }
+ // The zone matters: New York's local midnight is a different instant than UTC's.
+ assert_ne!(
+ window.earliest_eviction_at_ms(event_ms, UTC),
+ window.earliest_eviction_at_ms(event_ms, New_York),
+ );
+ }
+
+ #[test]
+ fn calendar_identical_events_share_one_eviction_midnight() {
+ let window = EvictionWindow::RelativeDays { days: 7 };
+ let early = utc_ms(2026, 5, 26, 0, 30); // 00:30 UTC
+ let late = utc_ms(2026, 5, 26, 23, 30); // 23:30 UTC, same calendar day
+ assert_eq!(
+ window.earliest_eviction_at_ms(early, UTC),
+ window.earliest_eviction_at_ms(late, UTC),
+ "two events on day D share the eviction midnight of D + 8",
+ );
+ }
+
+ #[test]
+ fn zero_time_value_day_window_evicts_at_the_next_midnight() {
+ let window = EvictionWindow::RelativeDays { days: 0 };
+ let event_ms = utc_ms(2026, 5, 26, 9, 0);
+ assert_eq!(
+ window.earliest_eviction_at_ms(event_ms, UTC),
+ start_of_day_ms_in_tz(day_idx_in_tz(event_ms, UTC) + 1, UTC),
+ );
+ }
+
+ #[test]
+ fn explicit_window_never_evicts_for_permanent_membership() {
+ // An in-range absolute match is permanent: never evict at the upper bound, or the sweep would
+ // emit a spurious `Left` even though the oracle's fixed-date predicate still matches.
+ for window in [
+ EvictionWindow::Explicit {
+ from_day: Some(day_of(2026, 1, 1)),
+ to_day: Some(day_of(2026, 12, 31)),
+ },
+ EvictionWindow::Explicit {
+ from_day: None,
+ to_day: None,
+ },
+ EvictionWindow::Explicit {
+ from_day: Some(day_of(2026, 1, 1)),
+ to_day: None,
+ },
+ ] {
+ assert_eq!(window.earliest_eviction_at_ms(1_000, UTC), i64::MAX);
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage1/predicate.rs b/rust/cohort-stream-processor/src/stage1/predicate.rs
new file mode 100644
index 000000000000..57ad82710d57
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/predicate.rs
@@ -0,0 +1,181 @@
+//! The leaf membership predicate over [`Stage1State`], centralised so the worker's transition
+//! detection, the sweep, and Stage 2 all read the same definition.
+
+use metrics::counter;
+
+use crate::observability::metrics::STAGE1_STATE_DECODE_ERROR;
+use crate::stage1::compressed_history::compressed_sum;
+use crate::stage1::pick_state::PredicateOp;
+use crate::stage1::state::Stage1State;
+
+/// Whether `state` currently satisfies its leaf predicate, for the **op-less** variants
+/// (`BehavioralSingle`, `PersonProperty`). The bucket variants carry a count comparator and must be
+/// evaluated via [`daily_predicate`] / [`compressed_predicate`] with their leaf's [`PredicateOp`] —
+/// every real caller already does (the worker's `mutate_behavioral_daily` and the sweep call those
+/// directly). Reaching a bucket variant here is a dispatch desync: the `LeafStateKey` pins the
+/// variant, so this can only happen on a coding error, and it is counted via
+/// `STAGE1_STATE_DECODE_ERROR` and read as a non-member — loud, never a silently-dropped member.
+pub fn predicate(state: &Stage1State) -> bool {
+ match state {
+ Stage1State::BehavioralSingle { has_match, .. } => *has_match,
+ Stage1State::PersonProperty { matches, .. } => *matches,
+ Stage1State::BehavioralDailyBuckets { .. }
+ | Stage1State::BehavioralCompressedHistory { .. } => {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ false
+ }
+ }
+}
+
+/// Parity-critical membership floor: zero matching rows is never a member, even for `lte`/`lt`/`eq 0`.
+/// Mirrors the existing pipeline's SQL, which only evaluates the comparator over persons with at least
+/// one matching row (`hogql_cohort_query.py:1015`) — `count() >= 1 AND <op>`. Shared by
+/// [`daily_predicate`] and [`compressed_predicate`] so the floor cannot drift between the two state
+/// representations of one `performed_event_multiple` leaf.
+fn count_is_member(count: u32, op: PredicateOp) -> bool {
+ count >= 1 && op.evaluate(count)
+}
+
+/// Whether the window's matching-event count (the bucket sum) satisfies `op`.
+pub fn daily_predicate(buckets: &[u32], op: PredicateOp) -> bool {
+ let count: u32 = buckets.iter().copied().fold(0, u32::saturating_add);
+ count_is_member(count, op)
+}
+
+/// Whether the compressed window's matching-event count (the sparse entries' count sum) satisfies
+/// `op`. Identical to [`daily_predicate`] — including the shared [`count_is_member`] floor — only over
+/// the sparse [`compressed_sum`] instead of a dense bucket array, so the two state representations of
+/// one `performed_event_multiple` leaf evaluate membership the same way.
+pub fn compressed_predicate(entries: &[(i32, u32)], op: PredicateOp) -> bool {
+ let count = compressed_sum(entries);
+ count_is_member(count, op)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn behavioral_single_predicate_is_has_match() {
+ let matched = Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ };
+ let unmatched = Stage1State::BehavioralSingle {
+ has_match: false,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ };
+ assert!(predicate(&matched));
+ assert!(!predicate(&unmatched));
+ }
+
+ #[test]
+ fn person_property_predicate_is_matches() {
+ let matched = Stage1State::PersonProperty {
+ matches: true,
+ last_updated_at_ms: 1,
+ last_updated_offset: 2,
+ };
+ let unmatched = Stage1State::PersonProperty {
+ matches: false,
+ last_updated_at_ms: 1,
+ last_updated_offset: 2,
+ };
+ assert!(predicate(&matched));
+ assert!(!predicate(&unmatched));
+ }
+
+ #[test]
+ fn daily_predicate_applies_the_comparator_to_the_bucket_sum() {
+ let buckets = [0, 1, 0, 2, 1]; // sum 4
+ assert!(daily_predicate(&buckets, PredicateOp::Gte(3)));
+ assert!(!daily_predicate(&buckets, PredicateOp::Gte(5)));
+ assert!(daily_predicate(&buckets, PredicateOp::Lte(4)));
+ assert!(!daily_predicate(&buckets, PredicateOp::Lt(4)));
+ assert!(daily_predicate(&buckets, PredicateOp::Eq(4)));
+ }
+
+ #[test]
+ fn daily_predicate_count_zero_is_never_a_member() {
+ let empty = [0, 0, 0];
+ assert!(
+ !daily_predicate(&empty, PredicateOp::Lte(5)),
+ "lte 5 over count 0"
+ );
+ assert!(
+ !daily_predicate(&empty, PredicateOp::Lt(5)),
+ "lt 5 over count 0"
+ );
+ assert!(
+ !daily_predicate(&empty, PredicateOp::Eq(0)),
+ "eq 0 over count 0"
+ );
+ assert!(
+ !daily_predicate(&empty, PredicateOp::Gte(1)),
+ "gte 1 over count 0"
+ );
+ }
+
+ #[test]
+ fn daily_predicate_count_one_floor_holds_for_lte_and_eq() {
+ let one = [1, 0];
+ assert!(
+ daily_predicate(&one, PredicateOp::Lte(5)),
+ "count 1 ∈ [1, 5]"
+ );
+ assert!(daily_predicate(&one, PredicateOp::Eq(1)));
+ assert!(
+ !daily_predicate(&one, PredicateOp::Eq(0)),
+ "count 1 is never eq 0"
+ );
+ }
+
+ #[test]
+ fn bucket_variants_through_op_less_predicate_read_as_non_member() {
+ // Buckets must be evaluated via daily_predicate/compressed_predicate with their op; reaching
+ // the op-less `predicate` is a dispatch desync. Both states below WOULD be members under
+ // Gte(3) (sum 3), so this proves the desync reads as a non-member rather than silently a
+ // member. The op-carrying dispatch is covered by daily_predicate_/compressed_predicate_ above.
+ let daily = Stage1State::BehavioralDailyBuckets {
+ buckets: vec![1, 2, 0],
+ window_start_day: 20_600,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ };
+ assert!(!predicate(&daily));
+ let compressed = Stage1State::BehavioralCompressedHistory {
+ entries: vec![(20_240, 1), (20_400, 2)],
+ window_start_day: 20_240,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ };
+ assert!(!predicate(&compressed));
+ }
+
+ #[test]
+ fn compressed_predicate_applies_the_comparator_to_the_entry_sum() {
+ let entries = [(100, 1), (200, 2), (300, 1)]; // sum 4
+ assert!(compressed_predicate(&entries, PredicateOp::Gte(3)));
+ assert!(!compressed_predicate(&entries, PredicateOp::Gte(5)));
+ assert!(compressed_predicate(&entries, PredicateOp::Lte(4)));
+ assert!(!compressed_predicate(&entries, PredicateOp::Lt(4)));
+ assert!(compressed_predicate(&entries, PredicateOp::Eq(4)));
+ }
+
+ #[test]
+ fn compressed_predicate_count_zero_floor_matches_daily() {
+ // An empty entry set is count 0 → never a member, even for lte/lt/eq 0 (the count >= 1 floor).
+ let empty: [(i32, u32); 0] = [];
+ assert!(!compressed_predicate(&empty, PredicateOp::Lte(5)));
+ assert!(!compressed_predicate(&empty, PredicateOp::Lt(5)));
+ assert!(!compressed_predicate(&empty, PredicateOp::Eq(0)));
+ assert!(!compressed_predicate(&empty, PredicateOp::Gte(1)));
+ // And a single match (count 1) satisfies lte/eq 1 just as daily does.
+ let one = [(100, 1)];
+ assert!(compressed_predicate(&one, PredicateOp::Lte(5)));
+ assert!(compressed_predicate(&one, PredicateOp::Eq(1)));
+ assert!(!compressed_predicate(&one, PredicateOp::Eq(0)));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage1/state.rs b/rust/cohort-stream-processor/src/stage1/state.rs
new file mode 100644
index 000000000000..16285241c01a
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/state.rs
@@ -0,0 +1,678 @@
+//! Per-leaf Stage 1 state, its persisted wrapper, and the value codec.
+
+use std::collections::BTreeMap;
+
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Which state representation a leaf uses.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum StateVariant {
+ /// `performed_event`: a single "has any matching event in window" bit.
+ BehavioralSingle,
+ /// `performed_event_multiple` with a `1..=180`-day window: dense per-calendar-day counts.
+ BehavioralDailyBuckets,
+ /// `performed_event_multiple` with a window over 180 days: sparse run-length per-calendar-day
+ /// counts.
+ BehavioralCompressedHistory,
+ /// A person-property filter: a last-write-wins boolean.
+ PersonProperty,
+}
+
+impl StateVariant {
+ /// The metric-label / log form.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::BehavioralSingle => "behavioral_single",
+ Self::BehavioralDailyBuckets => "behavioral_daily_buckets",
+ Self::BehavioralCompressedHistory => "behavioral_compressed_history",
+ Self::PersonProperty => "person_property",
+ }
+ }
+}
+
+/// The incremental per-`(team_id, leaf_state_key, person_id)` state a leaf maintains.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "v")]
+pub enum Stage1State {
+ /// `performed_event`. `has_match` is never cleared, so the predicate only flips `false → true`.
+ BehavioralSingle {
+ has_match: bool,
+ /// Most recent matching event time (epoch ms), `max`-folded across events.
+ last_event_at_ms: i64,
+ /// Earliest time (epoch ms) the sweep may evict this state.
+ earliest_eviction_at_ms: i64,
+ },
+ /// `performed_event_multiple` over a `1..=180`-day window. Membership is derived from `buckets`
+ /// and the leaf's `PredicateOp` (which lives on the catalog meta, not here).
+ BehavioralDailyBuckets {
+ /// Dense per-day counts: `buckets[i]` is the matching-event count for calendar day
+ /// `window_start_day + i`, in the team timezone. `len() == window_days + 1` (the inclusive
+ /// `[now_day − N ..= now_day]` window); index `len() − 1` is the current "now" day.
+ buckets: Vec<u32>,
+ /// [`DayIdx`](crate::stage1::bucket_tz::DayIdx) (days since the Unix epoch, team tz) of
+ /// `buckets[0]` — the window's inclusive lower bound. Monotonic non-decreasing as the window
+ /// slides forward; `window_days` is not stored (it equals `buckets.len() − 1`).
+ window_start_day: i32,
+ /// Most recent matching event time (epoch ms), `max`-folded across events.
+ last_event_at_ms: i64,
+ /// Earliest time (epoch ms) the oldest non-zero bucket leaves the window — its eviction
+ /// deadline. The event path never reads a wall clock.
+ earliest_eviction_at_ms: i64,
+ },
+ /// `performed_event_multiple` over a window exceeding 180 days, stored as sparse run-length
+ /// entries — the compressed analog of [`Self::BehavioralDailyBuckets`]. Membership is derived from
+ /// the entries' count sum and the leaf's `PredicateOp` (on the catalog meta, not here).
+ BehavioralCompressedHistory {
+ /// Sparse per-day counts: `(day_idx, count)` for each calendar day (team tz) with at least one
+ /// matching event, sorted ascending by day with no zero-count entries. The sparse form of
+ /// [`Self::BehavioralDailyBuckets`]'s dense array — bounded by `window_days + 1` entries, far
+ /// fewer for a typical user.
+ entries: Vec<(i32, u32)>,
+ /// [`DayIdx`](crate::stage1::bucket_tz::DayIdx) of the window's inclusive lower bound (the
+ /// `window_start_day` anchor). Monotonic non-decreasing as the window slides forward; the
+ /// "now" day is `window_start_day + window_days` (`window_days` lives on the meta, not here).
+ window_start_day: i32,
+ /// Most recent matching event time (epoch ms), `max`-folded across events.
+ last_event_at_ms: i64,
+ /// Earliest time (epoch ms) the oldest entry leaves the window — its eviction deadline
+ /// ([`i64::MAX`] when empty).
+ earliest_eviction_at_ms: i64,
+ },
+ /// A person-property filter: last-write-wins, tie-broken by event-time argMax
+ /// (`argMax(matches, (_timestamp, _offset))`).
+ PersonProperty {
+ matches: bool,
+ /// The argMax key's first component.
+ last_updated_at_ms: i64,
+ /// The argMax key's tiebreaker second component.
+ last_updated_offset: i64,
+ },
+}
+
+impl Stage1State {
+ pub fn variant(&self) -> StateVariant {
+ match self {
+ Self::BehavioralSingle { .. } => StateVariant::BehavioralSingle,
+ Self::BehavioralDailyBuckets { .. } => StateVariant::BehavioralDailyBuckets,
+ Self::BehavioralCompressedHistory { .. } => StateVariant::BehavioralCompressedHistory,
+ Self::PersonProperty { .. } => StateVariant::PersonProperty,
+ }
+ }
+
+ /// The eviction deadline (epoch ms) for this state, or [`None`] for `PersonProperty`, which is
+ /// last-write-wins and never time-evicts. A behavioral deadline may be [`i64::MAX`] (permanent
+ /// membership).
+ pub fn eviction_deadline(&self) -> Option<i64> {
+ match self {
+ Self::BehavioralSingle {
+ earliest_eviction_at_ms,
+ ..
+ }
+ | Self::BehavioralDailyBuckets {
+ earliest_eviction_at_ms,
+ ..
+ }
+ | Self::BehavioralCompressedHistory {
+ earliest_eviction_at_ms,
+ ..
+ } => Some(*earliest_eviction_at_ms),
+ Self::PersonProperty { .. } => None,
+ }
+ }
+}
+
+/// Per-source-partition last-applied offsets for replay dedup. `BTreeMap` for deterministic
+/// serialization.
+#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct AppliedOffsets(BTreeMap<i32, i64>);
+
+impl AppliedOffsets {
+ /// `true` if this `(source_partition, source_offset)` was already applied.
+ pub fn is_replay(&self, source_partition: i32, source_offset: i64) -> bool {
+ self.0
+ .get(&source_partition)
+ .is_some_and(|&last| source_offset <= last)
+ }
+
+ /// Advance the high-water mark for `source_partition`. Monotonic per partition.
+ pub fn record(&mut self, source_partition: i32, source_offset: i64) {
+ self.0
+ .entry(source_partition)
+ .and_modify(|last| *last = (*last).max(source_offset))
+ .or_insert(source_offset);
+ }
+
+ /// Fold another map's high-water marks into this one, per-partition max.
+ pub fn merge_max(&mut self, other: &Self) {
+ for (&partition, &offset) in &other.0 {
+ self.record(partition, offset);
+ }
+ }
+}
+
+/// The persisted `cf_stage1` value: a [`Stage1State`] plus replay-dedup offsets.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct StatefulRecord {
+ pub state: Stage1State,
+ pub applied_offsets: AppliedOffsets,
+ /// Per-ancestor replay-dedup for post-merge straggler events. Empty for non-merged persons.
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub redirect_dedup: BTreeMap<Uuid, AppliedOffsets>,
+}
+
+/// A failure decoding a stored [`StatefulRecord`].
+#[derive(Debug, thiserror::Error)]
+#[error("decoding Stage1 record: {0}")]
+pub struct StateCodecError(#[from] serde_json::Error);
+
+impl StatefulRecord {
+ /// A record with no redirect-dedup ancestry.
+ pub fn new(state: Stage1State, applied_offsets: AppliedOffsets) -> Self {
+ Self {
+ state,
+ applied_offsets,
+ redirect_dedup: BTreeMap::new(),
+ }
+ }
+
+ /// Origin-aware replay check.
+ pub fn is_replay_for(
+ &self,
+ origin: Option<&Uuid>,
+ source_partition: i32,
+ source_offset: i64,
+ ) -> bool {
+ dedup_is_replay(
+ &self.applied_offsets,
+ &self.redirect_dedup,
+ origin,
+ source_partition,
+ source_offset,
+ )
+ }
+
+ /// Origin-aware offset advance.
+ pub fn record_for(&mut self, origin: Option<&Uuid>, source_partition: i32, source_offset: i64) {
+ dedup_record(
+ &mut self.applied_offsets,
+ &mut self.redirect_dedup,
+ origin,
+ source_partition,
+ source_offset,
+ );
+ }
+
+ pub fn encode(&self) -> Vec<u8> {
+ serde_json::to_vec(self).expect("StatefulRecord is plain data and always serializes")
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StateCodecError> {
+ Ok(serde_json::from_slice(bytes)?)
+ }
+}
+
+/// Origin-aware replay check over a moved-out dedup pair.
+pub(crate) fn dedup_is_replay(
+ main: &AppliedOffsets,
+ redirect: &BTreeMap<Uuid, AppliedOffsets>,
+ origin: Option<&Uuid>,
+ source_partition: i32,
+ source_offset: i64,
+) -> bool {
+ match origin {
+ None => main.is_replay(source_partition, source_offset),
+ Some(ancestor) => redirect
+ .get(ancestor)
+ .is_some_and(|offsets| offsets.is_replay(source_partition, source_offset)),
+ }
+}
+
+/// Origin-aware offset advance over a moved-out dedup pair.
+pub(crate) fn dedup_record(
+ main: &mut AppliedOffsets,
+ redirect: &mut BTreeMap<Uuid, AppliedOffsets>,
+ origin: Option<&Uuid>,
+ source_partition: i32,
+ source_offset: i64,
+) {
+ match origin {
+ None => main.record(source_partition, source_offset),
+ Some(ancestor) => redirect
+ .entry(*ancestor)
+ .or_default()
+ .record(source_partition, source_offset),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn applied(entries: &[(i32, i64)]) -> AppliedOffsets {
+ let mut applied = AppliedOffsets::default();
+ for &(partition, offset) in entries {
+ applied.record(partition, offset);
+ }
+ applied
+ }
+
+ fn behavioral() -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: 1_700_000_000_000 + 7 * 86_400 * 1000,
+ },
+ applied(&[(17, 42)]),
+ )
+ }
+
+ fn person() -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::PersonProperty {
+ matches: false,
+ last_updated_at_ms: 1_700_000_000_123,
+ last_updated_offset: 99,
+ },
+ applied(&[(3, 100)]),
+ )
+ }
+
+ fn daily() -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::BehavioralDailyBuckets {
+ buckets: vec![0, 2, 0, 1, 3, 0, 1, 5],
+ window_start_day: 20_600,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: 1_700_000_000_000 + 7 * 86_400 * 1000,
+ },
+ applied(&[(4, 7), (9, 2)]),
+ )
+ }
+
+ fn compressed() -> StatefulRecord {
+ StatefulRecord::new(
+ Stage1State::BehavioralCompressedHistory {
+ entries: vec![(20_240, 2), (20_400, 1), (20_605, 5)],
+ window_start_day: 20_240,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: 1_700_000_000_000 + 365 * 86_400 * 1000,
+ },
+ applied(&[(4, 7), (9, 2)]),
+ )
+ }
+
+ #[test]
+ fn round_trips_every_variant() {
+ for record in [behavioral(), person(), daily(), compressed()] {
+ let bytes = record.encode();
+ assert_eq!(StatefulRecord::decode(&bytes).unwrap(), record);
+ }
+ }
+
+ #[test]
+ fn garbage_bytes_decode_to_err_not_panic() {
+ assert!(StatefulRecord::decode(b"not json at all").is_err());
+ assert!(StatefulRecord::decode(&[]).is_err());
+ }
+
+ #[test]
+ fn daily_buckets_decode_from_its_on_disk_shape() {
+ let on_disk = serde_json::json!({
+ "state": {
+ "v": "BehavioralDailyBuckets",
+ "buckets": [0, 2, 0, 1, 3, 0, 1, 5],
+ "window_start_day": 20_600,
+ "last_event_at_ms": 1_700_000_000_000_i64,
+ "earliest_eviction_at_ms": 1_700_000_000_000_i64 + 7 * 86_400 * 1000,
+ },
+ "applied_offsets": { "4": 7, "9": 2 },
+ });
+ let bytes = serde_json::to_vec(&on_disk).unwrap();
+ assert_eq!(StatefulRecord::decode(&bytes).unwrap(), daily());
+ }
+
+ #[test]
+ fn compressed_history_decodes_from_its_on_disk_shape() {
+ let on_disk = serde_json::json!({
+ "state": {
+ "v": "BehavioralCompressedHistory",
+ "entries": [[20_240, 2], [20_400, 1], [20_605, 5]],
+ "window_start_day": 20_240,
+ "last_event_at_ms": 1_700_000_000_000_i64,
+ "earliest_eviction_at_ms": 1_700_000_000_000_i64 + 365 * 86_400 * 1000,
+ },
+ "applied_offsets": { "4": 7, "9": 2 },
+ });
+ let bytes = serde_json::to_vec(&on_disk).unwrap();
+ assert_eq!(StatefulRecord::decode(&bytes).unwrap(), compressed());
+ }
+
+ #[test]
+ fn still_unknown_variant_tag_is_a_decode_error() {
+ let forward = serde_json::json!({
+ "state": { "v": "BehavioralHourlyBuckets", "buckets": [1, 2, 3] },
+ "applied_offsets": { "0": 0 },
+ });
+ let bytes = serde_json::to_vec(&forward).unwrap();
+ assert!(StatefulRecord::decode(&bytes).is_err());
+ }
+
+ #[test]
+ fn old_scalar_format_fails_to_decode_rather_than_silently_defaulting() {
+ // The scalar offset format (`last_applied_partition`/`last_applied_offset`) must fail-decode,
+ // not silently default `applied_offsets` to empty (which would drop high-water marks and
+ // re-open double-count windows).
+ let old = serde_json::json!({
+ "state": {
+ "v": "BehavioralSingle",
+ "has_match": true,
+ "last_event_at_ms": 1_700_000_000_000_i64,
+ "earliest_eviction_at_ms": 1_700_000_000_000_i64,
+ },
+ "last_applied_partition": 17,
+ "last_applied_offset": 42,
+ });
+ let bytes = serde_json::to_vec(&old).unwrap();
+ assert!(
+ StatefulRecord::decode(&bytes).is_err(),
+ "the old scalar format must fail-decode, not default applied_offsets to empty",
+ );
+ }
+
+ #[test]
+ fn applied_offsets_is_replay_table() {
+ let applied = applied(&[(5, 100), (6, 50)]);
+ let cases = [
+ (
+ 5,
+ 100,
+ true,
+ "exact offset on a seen partition is a replay → skip",
+ ),
+ (
+ 5,
+ 99,
+ true,
+ "lower offset on a seen partition is a replay → skip",
+ ),
+ (
+ 5,
+ 101,
+ false,
+ "higher offset on a seen partition is new → apply",
+ ),
+ (
+ 6,
+ 50,
+ true,
+ "exact offset on the other seen partition → skip",
+ ),
+ (6, 51, false, "higher offset on the other partition → apply"),
+ (7, 0, false, "an unseen partition is never a replay → apply"),
+ (
+ 7,
+ i64::MAX,
+ false,
+ "an unseen partition is never a replay, any offset → apply",
+ ),
+ ];
+ for (partition, offset, expected, why) in cases {
+ assert_eq!(
+ applied.is_replay(partition, offset),
+ expected,
+ "is_replay({partition}, {offset}): {why}",
+ );
+ }
+ }
+
+ #[test]
+ fn applied_offsets_empty_is_never_a_replay() {
+ let applied = AppliedOffsets::default();
+ assert!(!applied.is_replay(0, 0), "empty map: nothing seen yet");
+ assert!(!applied.is_replay(3, 100));
+ }
+
+ #[test]
+ fn applied_offsets_offset_zero_is_a_valid_first_offset() {
+ let mut applied = AppliedOffsets::default();
+ assert!(
+ !applied.is_replay(5, 0),
+ "0 before recording is not a replay"
+ );
+ applied.record(5, 0);
+ assert!(applied.is_replay(5, 0), "0 after recording is a replay");
+ assert!(!applied.is_replay(5, 1), "1 is still new");
+ }
+
+ #[test]
+ fn applied_offsets_record_is_monotonic_per_partition() {
+ let mut applied = AppliedOffsets::default();
+ applied.record(5, 100);
+ applied.record(5, 50); // lower → ignored
+ assert!(applied.is_replay(5, 100));
+ assert!(!applied.is_replay(5, 101), "high-water mark stayed at 100");
+ applied.record(5, 150); // higher → advances
+ assert!(applied.is_replay(5, 150));
+ assert!(!applied.is_replay(5, 151));
+ }
+
+ #[test]
+ fn applied_offsets_tracks_partitions_independently() {
+ let applied = applied(&[(5, 100), (6, 10)]);
+ assert!(applied.is_replay(5, 100));
+ assert!(!applied.is_replay(6, 11));
+ assert!(applied.is_replay(6, 10));
+ }
+
+ #[test]
+ fn applied_offsets_serializes_with_sorted_partition_keys() {
+ let applied = applied(&[(17, 1), (2, 2), (5, 3)]);
+ assert_eq!(
+ serde_json::to_string(&applied).unwrap(),
+ r#"{"2":2,"5":3,"17":1}"#,
+ );
+ }
+
+ #[test]
+ fn multi_entry_record_round_trips_with_sorted_keys() {
+ let record = StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ applied(&[(3, 100), (7, 5), (1, 0)]),
+ );
+ let bytes = record.encode();
+ assert_eq!(StatefulRecord::decode(&bytes).unwrap(), record);
+ let text = String::from_utf8(bytes).unwrap();
+ assert!(
+ text.contains(r#""applied_offsets":{"1":0,"3":100,"7":5}"#),
+ "applied_offsets must serialize with sorted partition keys, got: {text}",
+ );
+ }
+
+ fn uuid(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+ }
+
+ #[test]
+ fn empty_redirect_dedup_serializes_byte_identical_to_master() {
+ let record = StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ applied(&[(3, 100)]),
+ );
+ let text = String::from_utf8(record.encode()).unwrap();
+ assert!(
+ !text.contains("redirect_dedup"),
+ "an empty redirect_dedup must not appear on the wire, got: {text}",
+ );
+ assert_eq!(
+ text,
+ r#"{"state":{"v":"BehavioralSingle","has_match":true,"last_event_at_ms":1700000000000,"earliest_eviction_at_ms":9223372036854775807},"applied_offsets":{"3":100}}"#,
+ );
+ }
+
+ #[test]
+ fn master_era_bytes_without_redirect_dedup_decode_to_an_empty_map() {
+ let master = serde_json::json!({
+ "state": {
+ "v": "BehavioralSingle",
+ "has_match": true,
+ "last_event_at_ms": 1_700_000_000_000_i64,
+ "earliest_eviction_at_ms": i64::MAX,
+ },
+ "applied_offsets": { "3": 100 },
+ });
+ let record = StatefulRecord::decode(&serde_json::to_vec(&master).unwrap()).unwrap();
+ assert!(record.redirect_dedup.is_empty());
+ assert_eq!(record.applied_offsets, applied(&[(3, 100)]));
+ }
+
+ #[test]
+ fn non_empty_redirect_dedup_round_trips_per_ancestor() {
+ let mut record = StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ applied(&[(3, 100)]),
+ );
+ record
+ .redirect_dedup
+ .insert(uuid(0xA11CE), applied(&[(5, 9), (6, 2)]));
+
+ let bytes = record.encode();
+ assert_eq!(StatefulRecord::decode(&bytes).unwrap(), record);
+ let text = String::from_utf8(bytes).unwrap();
+ assert!(
+ text.contains("redirect_dedup"),
+ "a non-empty redirect_dedup must serialize, got: {text}",
+ );
+ }
+
+ #[test]
+ fn merge_max_unions_per_partition_high_water_marks() {
+ let mut into = applied(&[(5, 100), (6, 10)]);
+ into.merge_max(&applied(&[(5, 50), (6, 20), (7, 1)]));
+ assert!(into.is_replay(5, 100));
+ assert!(!into.is_replay(5, 101));
+ assert!(into.is_replay(6, 20));
+ assert!(!into.is_replay(6, 21));
+ assert!(into.is_replay(7, 1));
+ }
+
+ #[test]
+ fn is_replay_for_routes_by_origin() {
+ let mut record = StatefulRecord::new(
+ Stage1State::PersonProperty {
+ matches: true,
+ last_updated_at_ms: 1,
+ last_updated_offset: 2,
+ },
+ applied(&[(5, 100)]),
+ );
+ let ancestor = uuid(0xA11CE);
+ record.redirect_dedup.insert(ancestor, applied(&[(5, 200)]));
+
+ // origin = None → main map: offset 100 is a replay, 101 is new.
+ assert!(record.is_replay_for(None, 5, 100));
+ assert!(!record.is_replay_for(None, 5, 101));
+ // A fresh main-map event at offset 150 (above main's 100, below the ancestor's 200) still
+ // folds — the ancestor entry does not gate normal events (hazard A).
+ assert!(!record.is_replay_for(None, 5, 150));
+ // origin = Some(ancestor) → redirect_dedup[ancestor]: 200 is a replay, 201 is new (hazard B).
+ assert!(record.is_replay_for(Some(&ancestor), 5, 200));
+ assert!(!record.is_replay_for(Some(&ancestor), 5, 201));
+ // origin = an unknown ancestor → never a replay (no entry yet).
+ assert!(!record.is_replay_for(Some(&uuid(0xBEEF)), 5, 0));
+ }
+
+ #[test]
+ fn record_for_routes_by_origin_and_creates_entries_on_demand() {
+ let mut record = StatefulRecord::new(
+ Stage1State::PersonProperty {
+ matches: true,
+ last_updated_at_ms: 1,
+ last_updated_offset: 2,
+ },
+ AppliedOffsets::default(),
+ );
+ let ancestor = uuid(0xA11CE);
+
+ record.record_for(None, 5, 100);
+ assert!(record.is_replay_for(None, 5, 100));
+ assert!(
+ record.redirect_dedup.is_empty(),
+ "a normal event touches only the main map"
+ );
+
+ record.record_for(Some(&ancestor), 5, 200);
+ assert!(record.is_replay_for(Some(&ancestor), 5, 200));
+ assert!(
+ !record.is_replay_for(None, 5, 150),
+ "recording into the ancestor map must not advance the main map",
+ );
+ }
+
+ #[test]
+ fn variant_reports_the_state_kind() {
+ assert_eq!(behavioral().state.variant(), StateVariant::BehavioralSingle);
+ assert_eq!(person().state.variant(), StateVariant::PersonProperty);
+ assert_eq!(
+ daily().state.variant(),
+ StateVariant::BehavioralDailyBuckets
+ );
+ assert_eq!(
+ compressed().state.variant(),
+ StateVariant::BehavioralCompressedHistory
+ );
+ }
+
+ #[test]
+ fn eviction_deadline_is_some_for_behavioral_and_none_for_person_property() {
+ assert_eq!(
+ behavioral().state.eviction_deadline(),
+ Some(1_700_000_000_000 + 7 * 86_400 * 1000),
+ );
+ assert_eq!(
+ daily().state.eviction_deadline(),
+ Some(1_700_000_000_000 + 7 * 86_400 * 1000),
+ );
+ assert_eq!(
+ compressed().state.eviction_deadline(),
+ Some(1_700_000_000_000 + 365 * 86_400 * 1000),
+ );
+ assert_eq!(person().state.eviction_deadline(), None);
+
+ // A permanent membership reports the i64::MAX sentinel.
+ let permanent = Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: i64::MAX,
+ };
+ assert_eq!(permanent.eviction_deadline(), Some(i64::MAX));
+ }
+
+ #[test]
+ fn variant_labels_are_stable() {
+ assert_eq!(StateVariant::BehavioralSingle.as_str(), "behavioral_single");
+ assert_eq!(
+ StateVariant::BehavioralDailyBuckets.as_str(),
+ "behavioral_daily_buckets"
+ );
+ assert_eq!(
+ StateVariant::BehavioralCompressedHistory.as_str(),
+ "behavioral_compressed_history"
+ );
+ assert_eq!(StateVariant::PersonProperty.as_str(), "person_property");
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage1/time.rs b/rust/cohort-stream-processor/src/stage1/time.rs
new file mode 100644
index 000000000000..a7e7cb189f2c
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/time.rs
@@ -0,0 +1,69 @@
+//! Event-timestamp parsing for Stage 1.
+//!
+//! [`clickhouse_timestamp_to_millis`] accepts the same two wire shapes as
+//! [`hogvm::globals`](crate::hogvm) but is **stricter**: it returns epoch millis and yields [`None`]
+//! on an unparseable value rather than passing it through. The timestamp drives eviction deadlines
+//! and the argMax tiebreaker, so a value we cannot place on the timeline must skip the event.
+
+use chrono::{DateTime, NaiveDateTime};
+
+/// Parse an event timestamp to epoch milliseconds, or [`None`] if it matches neither shape. The
+/// zone-less ClickHouse form is interpreted as UTC.
+pub fn clickhouse_timestamp_to_millis(raw: &str) -> Option<i64> {
+ if let Ok(dt) = DateTime::parse_from_rfc3339(raw) {
+ return Some(dt.timestamp_millis());
+ }
+ NaiveDateTime::parse_from_str(raw, "%Y-%m-%d %H:%M:%S%.f")
+ .ok()
+ .map(|naive| naive.and_utc().timestamp_millis())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Epoch-ms for `2026-05-26T12:34:56.789Z`, computed independently of chrono so it pins the
+ /// parse rather than re-deriving it.
+ const GOLDEN_MS: i64 = 1_779_798_896_789;
+
+ #[test]
+ fn clickhouse_form_parses_to_golden_millis() {
+ assert_eq!(
+ clickhouse_timestamp_to_millis("2026-05-26 12:34:56.789000"),
+ Some(GOLDEN_MS),
+ );
+ }
+
+ #[test]
+ fn iso_form_agrees_with_clickhouse_form() {
+ assert_eq!(
+ clickhouse_timestamp_to_millis("2026-05-26T12:34:56.789Z"),
+ Some(GOLDEN_MS),
+ );
+ }
+
+ #[test]
+ fn rfc3339_offset_is_normalized_to_utc() {
+ let with_offset = clickhouse_timestamp_to_millis("2026-05-26T12:34:56.789+02:00").unwrap();
+ assert_eq!(with_offset, GOLDEN_MS - 2 * 3_600_000);
+ }
+
+ #[test]
+ fn sub_millisecond_digits_truncate() {
+ assert_eq!(
+ clickhouse_timestamp_to_millis("2026-01-01 00:00:00.000999"),
+ clickhouse_timestamp_to_millis("2026-01-01 00:00:00.000000"),
+ );
+ }
+
+ #[test]
+ fn unparseable_values_are_none() {
+ for bad in ["", "not a date", "2026-13-99 99:99:99", "1716800000"] {
+ assert_eq!(
+ clickhouse_timestamp_to_millis(bad),
+ None,
+ "expected None for {bad:?}"
+ );
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage1/transition.rs b/rust/cohort-stream-processor/src/stage1/transition.rs
new file mode 100644
index 000000000000..06514869263f
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage1/transition.rs
@@ -0,0 +1,28 @@
+//! Stage 1 leaf transitions.
+//!
+//! The worker emits a [`LeafTransition`] only *after* the backing state is durably committed. A
+//! `BehavioralDailyBuckets` leaf can emit `Left` from the event path when a window slide drains its
+//! contributing buckets; the `BehavioralSingle` path never clears a match, so it emits no `Left`.
+
+use uuid::Uuid;
+
+use crate::filters::TeamId;
+use crate::stage1::key::LeafStateKey;
+
+/// The direction of a membership flip for one leaf.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TransitionKind {
+ Entered,
+ Left,
+}
+
+/// A single leaf's membership flip for one person, carrying what a later stage needs to route and
+/// attribute it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LeafTransition {
+ pub team_id: TeamId,
+ pub leaf_state_key: LeafStateKey,
+ pub person_id: Uuid,
+ pub condition_hash: [u8; 16],
+ pub kind: TransitionKind,
+}
diff --git a/rust/cohort-stream-processor/src/stage2/eligibility.rs b/rust/cohort-stream-processor/src/stage2/eligibility.rs
new file mode 100644
index 000000000000..4546e24d0d17
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage2/eligibility.rs
@@ -0,0 +1,915 @@
+//! Parse-time cohort eligibility classification for Stage 2 composition.
+
+use std::collections::HashMap;
+
+use crate::filters::cohort_graph::RefGraphAnalysis;
+use crate::filters::tree::{BoolOp, CohortTree, FilterNode};
+use crate::filters::CohortId;
+use crate::stage1::key::LeafStateKey;
+
+/// Per-cohort signals accumulated while parsing the cohort's filter tree.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub struct CohortParseFlags {
+ /// Number of kept, state-keyed leaves in the parsed tree.
+ pub state_keyed_leaf_count: u32,
+ /// The cohort has ≥1 cohort-reference leaf.
+ pub has_cohort_ref: bool,
+ /// The cohort lost ≥1 leaf during parse.
+ pub has_dropped_leaf: bool,
+}
+
+/// Why a cohort is excluded from composition.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ExcludedReason {
+ /// Neither a single state-keyed leaf nor ≥2 composable leaves.
+ NotMultiLeaf,
+ /// The root condition is negated.
+ TopLevelNegation,
+ /// A group anywhere in the tree has zero children.
+ EmptyGroup,
+ /// Has a cohort-reference leaf.
+ HasCohortRef,
+ /// In a cohort-reference cycle.
+ CycleDetected,
+ /// A cohort-reference target is missing from the catalog or itself excluded.
+ UnresolvedRef,
+ /// Lost a leaf during parse.
+ HasDroppedLeaf,
+}
+
+impl ExcludedReason {
+ /// The `excluded_<reason>` label value for `cohort_eligibility_total`.
+ fn metric_class(self) -> &'static str {
+ match self {
+ Self::NotMultiLeaf => "excluded_not_multi_leaf",
+ Self::TopLevelNegation => "excluded_top_level_negation",
+ Self::EmptyGroup => "excluded_empty_group",
+ Self::HasCohortRef => "excluded_has_cohort_ref",
+ Self::CycleDetected => "excluded_cycle_detected",
+ Self::UnresolvedRef => "excluded_unresolved_ref",
+ Self::HasDroppedLeaf => "excluded_has_dropped_leaf",
+ }
+ }
+}
+
+/// A cohort's composition class, computed once at freeze.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CohortEligibility {
+ /// Exactly one state-keyed leaf; its [`LeafStateKey`] is the cohort's membership.
+ SingleLeaf(LeafStateKey),
+ /// ≥2 positive, state-keyed, cohort-ref-free leaves.
+ Stage2Composable,
+ /// A resolvable, cycle-free ref-bearing cohort promoted to composition when `cohort_cascade_enabled`;
+ /// composes from each referent's stored membership and persists a `cf_stage2` bit.
+ Stage2ComposableRef,
+ /// Not emitted; see [`ExcludedReason`].
+ Excluded(ExcludedReason),
+}
+
+impl CohortEligibility {
+ /// The `class` label value for `cohort_eligibility_total`.
+ pub fn metric_class(self) -> &'static str {
+ match self {
+ Self::SingleLeaf(_) => "single_leaf",
+ Self::Stage2Composable => "stage2_composable",
+ Self::Stage2ComposableRef => "stage2_composable_ref",
+ Self::Excluded(reason) => reason.metric_class(),
+ }
+ }
+
+ /// Whether this class persists a `cf_stage2` row — both composable classes do; single-leaf
+ /// membership lives in `cf_stage1` and excluded cohorts persist nothing.
+ pub fn writes_cf_stage2(self) -> bool {
+ matches!(self, Self::Stage2Composable | Self::Stage2ComposableRef)
+ }
+}
+
+/// Whether a tree's root condition is negated: AND requires all children negated, OR requires any.
+pub(crate) fn condition_negation(node: &FilterNode) -> bool {
+ match node {
+ FilterNode::Leaf(leaf) => leaf.negated(),
+ FilterNode::Group { op, children } => match op {
+ BoolOp::And => !children.is_empty() && children.iter().all(condition_negation),
+ BoolOp::Or => children.iter().any(condition_negation),
+ },
+ }
+}
+
+fn has_empty_group(node: &FilterNode) -> bool {
+ match node {
+ FilterNode::Leaf(_) => false,
+ FilterNode::Group { children, .. } => {
+ children.is_empty() || children.iter().any(has_empty_group)
+ }
+ }
+}
+
+/// Classify a parsed cohort for composition. Exclusion precedence: dropped leaf > empty group >
+/// root-negated > cohort reference.
+pub fn classify(tree: &CohortTree, flags: &CohortParseFlags) -> CohortEligibility {
+ if flags.has_dropped_leaf {
+ return CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf);
+ }
+ if has_empty_group(&tree.root) {
+ return CohortEligibility::Excluded(ExcludedReason::EmptyGroup);
+ }
+ if condition_negation(&tree.root) {
+ return CohortEligibility::Excluded(ExcludedReason::TopLevelNegation);
+ }
+ if flags.has_cohort_ref {
+ return CohortEligibility::Excluded(ExcludedReason::HasCohortRef);
+ }
+
+ match single_supported_leaf(&tree.root) {
+ Some(lsk) => CohortEligibility::SingleLeaf(lsk),
+ None if flags.state_keyed_leaf_count >= 2 => CohortEligibility::Stage2Composable,
+ None => CohortEligibility::Excluded(ExcludedReason::NotMultiLeaf),
+ }
+}
+
+/// Refine each `Excluded(HasCohortRef)` cohort: cycle members → `CycleDetected`, an unresolvable
+/// target → `UnresolvedRef`, else promote to [`Stage2ComposableRef`] when `cascade_enabled` (kept
+/// `Excluded(HasCohortRef)` otherwise).
+///
+/// Targets are refined before referrers, so a referrer reads its target's final class — including a
+/// target already promoted to `Stage2ComposableRef`.
+pub(crate) fn refine_ref_bearing(
+ eligibility: &mut HashMap<CohortId, CohortEligibility>,
+ analysis: &RefGraphAnalysis,
+ cascade_enabled: bool,
+) {
+ for &cohort_id in &analysis.refinement_order {
+ if !matches!(
+ eligibility.get(&cohort_id),
+ Some(CohortEligibility::Excluded(ExcludedReason::HasCohortRef))
+ ) {
+ continue;
+ }
+ let refined = if analysis.in_cycle.contains(&cohort_id) {
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected)
+ } else if analysis
+ .positive_ref_targets
+ .get(&cohort_id)
+ .is_some_and(|targets| targets.iter().any(|&t| !is_resolvable(eligibility, t)))
+ {
+ // Resolvability is decided over positive targets only: an absent target reached solely
+ // through negated leaves reads `true` (absent ⊕ negation), so it never blocks
+ // composition. `is_resolvable` stays negation-blind — it is now only called on positives.
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef)
+ } else if cascade_enabled {
+ CohortEligibility::Stage2ComposableRef
+ } else {
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef)
+ };
+ eligibility.insert(cohort_id, refined);
+ }
+}
+
+/// Whether a reference target is resolvable (present, not cyclic/unresolved/structurally-excluded).
+/// `Excluded(HasCohortRef)` still counts — it can be read, it just doesn't itself compose.
+fn is_resolvable(eligibility: &HashMap<CohortId, CohortEligibility>, target: CohortId) -> bool {
+ matches!(
+ eligibility.get(&target),
+ Some(
+ CohortEligibility::SingleLeaf(_)
+ | CohortEligibility::Stage2Composable
+ | CohortEligibility::Stage2ComposableRef
+ | CohortEligibility::Excluded(ExcludedReason::HasCohortRef)
+ )
+ )
+}
+
+fn single_supported_leaf(root: &FilterNode) -> Option<LeafStateKey> {
+ enum LeafCount {
+ Zero,
+ One(Option<LeafStateKey>),
+ Many,
+ }
+
+ fn walk(node: &FilterNode, acc: LeafCount) -> LeafCount {
+ match node {
+ FilterNode::Leaf(leaf) => match acc {
+ LeafCount::Zero => LeafCount::One(leaf.leaf_state_key()),
+ LeafCount::One(_) | LeafCount::Many => LeafCount::Many,
+ },
+ FilterNode::Group { children, .. } => {
+ let mut acc = acc;
+ for child in children {
+ if matches!(acc, LeafCount::Many) {
+ return LeafCount::Many;
+ }
+ acc = walk(child, acc);
+ }
+ acc
+ }
+ }
+ }
+
+ match walk(root, LeafCount::Zero) {
+ LeafCount::One(lsk) => lsk,
+ LeafCount::Zero | LeafCount::Many => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use serde_json::Value;
+
+ use super::*;
+ use crate::filters::tree::{CohortLeaf, CohortRefLeafConfig, PersonLeafConfig};
+ use crate::filters::{CohortId, TeamId};
+
+ const HASH_A: [u8; 16] = *b"aaaaaaaaaaaaaaaa";
+ const HASH_B: [u8; 16] = *b"bbbbbbbbbbbbbbbb";
+ const HASH_C: [u8; 16] = *b"cccccccccccccccc";
+
+ fn person_leaf(hash: [u8; 16]) -> FilterNode {
+ person_leaf_negated(hash, false)
+ }
+
+ fn person_leaf_negated(hash: [u8; 16], negated: bool) -> FilterNode {
+ FilterNode::Leaf(CohortLeaf::PersonProperty(PersonLeafConfig {
+ condition_hash: hash,
+ leaf_state_key: LeafStateKey::for_person_property(&hash),
+ bytecode: Arc::new(Vec::new()),
+ raw: Value::Null,
+ negated,
+ }))
+ }
+
+ fn cohort_ref_leaf() -> FilterNode {
+ cohort_ref_leaf_negated(false)
+ }
+
+ fn cohort_ref_leaf_negated(negation: bool) -> FilterNode {
+ FilterNode::Leaf(CohortLeaf::CohortRef(CohortRefLeafConfig {
+ referenced_cohort_id: CohortId(99),
+ negation,
+ }))
+ }
+
+ fn and(children: Vec<FilterNode>) -> CohortTree {
+ tree_with(BoolOp::And, children)
+ }
+
+ fn or(children: Vec<FilterNode>) -> CohortTree {
+ tree_with(BoolOp::Or, children)
+ }
+
+ fn tree_with(op: BoolOp, children: Vec<FilterNode>) -> CohortTree {
+ CohortTree {
+ cohort_id: CohortId(1),
+ team_id: TeamId(7),
+ root: FilterNode::Group { op, children },
+ }
+ }
+
+ fn group(op: BoolOp, children: Vec<FilterNode>) -> FilterNode {
+ FilterNode::Group { op, children }
+ }
+
+ fn positive(n: u32) -> CohortParseFlags {
+ CohortParseFlags {
+ state_keyed_leaf_count: n,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn one_state_keyed_leaf_is_single_leaf() {
+ let tree = and(vec![person_leaf(HASH_A)]);
+ assert_eq!(
+ classify(&tree, &positive(1)),
+ CohortEligibility::SingleLeaf(LeafStateKey::for_person_property(&HASH_A)),
+ );
+ }
+
+ #[test]
+ fn two_state_keyed_leaves_are_composable() {
+ let tree = and(vec![person_leaf(HASH_A), person_leaf(HASH_B)]);
+ assert_eq!(
+ classify(&tree, &positive(2)),
+ CohortEligibility::Stage2Composable,
+ );
+ }
+
+ #[test]
+ fn empty_cohort_is_empty_group() {
+ let tree = and(vec![]);
+ assert_eq!(
+ classify(&tree, &positive(0)),
+ CohortEligibility::Excluded(ExcludedReason::EmptyGroup),
+ );
+ }
+
+ #[test]
+ fn dropped_leaf_excludes_even_with_a_lone_survivor() {
+ let tree = and(vec![person_leaf(HASH_A)]);
+ let flags = CohortParseFlags {
+ state_keyed_leaf_count: 1,
+ has_dropped_leaf: true,
+ ..Default::default()
+ };
+ assert_eq!(
+ classify(&tree, &flags),
+ CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf),
+ );
+ }
+
+ #[test]
+ fn cohort_ref_excludes() {
+ let tree = and(vec![person_leaf(HASH_A), cohort_ref_leaf()]);
+ let flags = CohortParseFlags {
+ state_keyed_leaf_count: 1,
+ has_cohort_ref: true,
+ ..Default::default()
+ };
+ assert_eq!(
+ classify(&tree, &flags),
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ );
+ }
+
+ #[test]
+ fn condition_negation_leaf_bits() {
+ assert!(!condition_negation(&person_leaf(HASH_A)));
+ assert!(condition_negation(&person_leaf_negated(HASH_A, true)));
+ }
+
+ #[test]
+ fn condition_negation_and_propagation() {
+ // AND all-negated → true; AND mixed → false; AND all-positive → false.
+ assert!(condition_negation(&group(
+ BoolOp::And,
+ vec![
+ person_leaf_negated(HASH_A, true),
+ person_leaf_negated(HASH_B, true),
+ ],
+ )));
+ assert!(!condition_negation(&group(
+ BoolOp::And,
+ vec![person_leaf(HASH_A), person_leaf_negated(HASH_B, true)],
+ )));
+ assert!(!condition_negation(&group(
+ BoolOp::And,
+ vec![person_leaf(HASH_A), person_leaf(HASH_B)],
+ )));
+ }
+
+ #[test]
+ fn condition_negation_or_propagation() {
+ // OR any-negated → true; OR all-positive → false.
+ assert!(condition_negation(&group(
+ BoolOp::Or,
+ vec![person_leaf(HASH_A), person_leaf_negated(HASH_B, true)],
+ )));
+ assert!(condition_negation(&group(
+ BoolOp::Or,
+ vec![
+ person_leaf_negated(HASH_A, true),
+ person_leaf_negated(HASH_B, true),
+ ],
+ )));
+ assert!(!condition_negation(&group(
+ BoolOp::Or,
+ vec![person_leaf(HASH_A), person_leaf(HASH_B)],
+ )));
+ }
+
+ #[test]
+ fn condition_negation_empty_groups_are_false() {
+ assert!(!condition_negation(&group(BoolOp::And, vec![])));
+ assert!(!condition_negation(&group(BoolOp::Or, vec![])));
+ }
+
+ #[test]
+ fn condition_negation_cohort_ref_negated_is_true() {
+ assert!(condition_negation(&cohort_ref_leaf_negated(true)));
+ assert!(!condition_negation(&cohort_ref_leaf_negated(false)));
+ }
+
+ #[test]
+ fn and_a_neg_b_is_composable() {
+ let tree = and(vec![person_leaf(HASH_A), person_leaf_negated(HASH_B, true)]);
+ assert_eq!(
+ classify(&tree, &positive(2)),
+ CohortEligibility::Stage2Composable,
+ );
+ }
+
+ #[test]
+ fn or_a_neg_b_is_composable() {
+ let tree = or(vec![person_leaf(HASH_A), person_leaf_negated(HASH_B, true)]);
+ assert_eq!(
+ classify(&tree, &positive(2)),
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ );
+ }
+
+ #[test]
+ fn or_neg_a_neg_b_is_top_level_negation() {
+ let tree = or(vec![
+ person_leaf_negated(HASH_A, true),
+ person_leaf_negated(HASH_B, true),
+ ]);
+ assert_eq!(
+ classify(&tree, &positive(2)),
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ );
+ }
+
+ #[test]
+ fn and_neg_a_neg_b_is_top_level_negation() {
+ let tree = and(vec![
+ person_leaf_negated(HASH_A, true),
+ person_leaf_negated(HASH_B, true),
+ ]);
+ assert_eq!(
+ classify(&tree, &positive(2)),
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ );
+ }
+
+ #[test]
+ fn bare_negated_leaf_is_top_level_negation() {
+ let tree = and(vec![person_leaf_negated(HASH_A, true)]);
+ assert_eq!(
+ classify(&tree, &positive(1)),
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ );
+ }
+
+ #[test]
+ fn nested_negated_and_propagates() {
+ let tree = or(vec![group(
+ BoolOp::And,
+ vec![person_leaf_negated(HASH_A, true)],
+ )]);
+ assert_eq!(
+ classify(&tree, &positive(1)),
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ );
+ }
+
+ #[test]
+ fn and_c_or_a_neg_b_is_composable() {
+ let tree = and(vec![
+ person_leaf(HASH_C),
+ group(
+ BoolOp::Or,
+ vec![person_leaf(HASH_A), person_leaf_negated(HASH_B, true)],
+ ),
+ ]);
+ assert_eq!(
+ classify(&tree, &positive(3)),
+ CohortEligibility::Stage2Composable,
+ );
+ }
+
+ #[test]
+ fn and_c_or_neg_a_neg_b_is_composable() {
+ let tree = and(vec![
+ person_leaf(HASH_C),
+ group(
+ BoolOp::Or,
+ vec![
+ person_leaf_negated(HASH_A, true),
+ person_leaf_negated(HASH_B, true),
+ ],
+ ),
+ ]);
+ assert_eq!(
+ classify(&tree, &positive(3)),
+ CohortEligibility::Stage2Composable,
+ );
+ }
+
+ #[test]
+ fn root_empty_and_is_empty_group() {
+ let tree = and(vec![]);
+ assert_eq!(
+ classify(&tree, &positive(0)),
+ CohortEligibility::Excluded(ExcludedReason::EmptyGroup),
+ );
+ }
+
+ #[test]
+ fn nested_empty_or_is_empty_group() {
+ let tree = and(vec![person_leaf(HASH_A), group(BoolOp::Or, vec![])]);
+ assert_eq!(
+ classify(&tree, &positive(1)),
+ CohortEligibility::Excluded(ExcludedReason::EmptyGroup),
+ );
+ }
+
+ #[test]
+ fn or_with_empty_and_child_is_empty_group() {
+ let tree = or(vec![
+ person_leaf(HASH_A),
+ person_leaf(HASH_B),
+ group(BoolOp::And, vec![]),
+ ]);
+ assert_eq!(
+ classify(&tree, &positive(2)),
+ CohortEligibility::Excluded(ExcludedReason::EmptyGroup),
+ );
+ }
+
+ #[test]
+ fn precedence_dropped_over_empty_group() {
+ let tree = and(vec![
+ person_leaf_negated(HASH_A, true),
+ group(BoolOp::Or, vec![]),
+ ]);
+ let flags = CohortParseFlags {
+ state_keyed_leaf_count: 1,
+ has_dropped_leaf: true,
+ ..Default::default()
+ };
+ assert_eq!(
+ classify(&tree, &flags),
+ CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf),
+ );
+ }
+
+ #[test]
+ fn precedence_empty_group_over_top_level_negation() {
+ let tree = and(vec![
+ person_leaf_negated(HASH_A, true),
+ group(BoolOp::Or, vec![]),
+ ]);
+ assert_eq!(
+ classify(&tree, &positive(1)),
+ CohortEligibility::Excluded(ExcludedReason::EmptyGroup),
+ );
+ }
+
+ #[test]
+ fn precedence_top_level_negation_over_cohort_ref() {
+ let tree = and(vec![
+ person_leaf_negated(HASH_A, true),
+ cohort_ref_leaf_negated(true),
+ ]);
+ let flags = CohortParseFlags {
+ state_keyed_leaf_count: 1,
+ has_cohort_ref: true,
+ ..Default::default()
+ };
+ assert_eq!(
+ classify(&tree, &flags),
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ );
+ }
+
+ #[test]
+ fn positive_negated_a_with_positive_cohort_ref_is_cohort_ref() {
+ let tree = and(vec![person_leaf_negated(HASH_A, true), cohort_ref_leaf()]);
+ let flags = CohortParseFlags {
+ state_keyed_leaf_count: 1,
+ has_cohort_ref: true,
+ ..Default::default()
+ };
+ assert_eq!(
+ classify(&tree, &flags),
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ );
+ }
+
+ #[test]
+ fn metric_class_strings() {
+ assert_eq!(
+ CohortEligibility::SingleLeaf(LeafStateKey(HASH_A)).metric_class(),
+ "single_leaf",
+ );
+ assert_eq!(
+ CohortEligibility::Stage2Composable.metric_class(),
+ "stage2_composable",
+ );
+ assert_eq!(
+ CohortEligibility::Excluded(ExcludedReason::NotMultiLeaf).metric_class(),
+ "excluded_not_multi_leaf",
+ );
+ assert_eq!(
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation).metric_class(),
+ "excluded_top_level_negation",
+ );
+ assert_eq!(
+ CohortEligibility::Excluded(ExcludedReason::EmptyGroup).metric_class(),
+ "excluded_empty_group",
+ );
+ assert_eq!(
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef).metric_class(),
+ "excluded_has_cohort_ref",
+ );
+ assert_eq!(
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected).metric_class(),
+ "excluded_cycle_detected",
+ );
+ assert_eq!(
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef).metric_class(),
+ "excluded_unresolved_ref",
+ );
+ assert_eq!(
+ CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf).metric_class(),
+ "excluded_has_dropped_leaf",
+ );
+ }
+
+ #[test]
+ fn nested_groups_count_one_leaf_as_single() {
+ let tree = CohortTree {
+ cohort_id: CohortId(1),
+ team_id: TeamId(7),
+ root: FilterNode::Group {
+ op: BoolOp::Or,
+ children: vec![FilterNode::Group {
+ op: BoolOp::And,
+ children: vec![person_leaf(HASH_A)],
+ }],
+ },
+ };
+ assert_eq!(
+ classify(&tree, &positive(1)),
+ CohortEligibility::SingleLeaf(LeafStateKey::for_person_property(&HASH_A)),
+ );
+ }
+
+ use std::collections::HashSet;
+
+ /// Builds a [`RefGraphAnalysis`] where all ref targets are positive (non-negated).
+ fn analysis(
+ in_cycle: &[i32],
+ refinement_order: &[i32],
+ ref_targets: &[(i32, &[i32])],
+ ) -> RefGraphAnalysis {
+ analysis_with_positives(in_cycle, refinement_order, ref_targets, ref_targets)
+ }
+
+ /// Like [`analysis`] but with an explicit `positive_ref_targets` set, for negation tests where a
+ /// target sits in `ref_targets` (reached negated) but not in the positive set.
+ fn analysis_with_positives(
+ in_cycle: &[i32],
+ refinement_order: &[i32],
+ ref_targets: &[(i32, &[i32])],
+ positive_ref_targets: &[(i32, &[i32])],
+ ) -> RefGraphAnalysis {
+ RefGraphAnalysis {
+ in_cycle: in_cycle
+ .iter()
+ .map(|&c| CohortId(c))
+ .collect::<HashSet<_>>(),
+ refinement_order: refinement_order.iter().map(|&c| CohortId(c)).collect(),
+ ref_targets: ref_targets
+ .iter()
+ .map(|&(c, t)| (CohortId(c), t.iter().map(|&x| CohortId(x)).collect()))
+ .collect(),
+ positive_ref_targets: positive_ref_targets
+ .iter()
+ .map(|&(c, t)| (CohortId(c), t.iter().map(|&x| CohortId(x)).collect()))
+ .collect(),
+ }
+ }
+
+ fn eligibility_map(
+ entries: &[(i32, CohortEligibility)],
+ ) -> HashMap<CohortId, CohortEligibility> {
+ entries.iter().map(|&(c, e)| (CohortId(c), e)).collect()
+ }
+
+ #[test]
+ fn refine_cycle_member_is_cycle_detected() {
+ let mut elig =
+ eligibility_map(&[(1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef))]);
+ refine_ref_bearing(&mut elig, &analysis(&[1], &[1], &[(1, &[1])]), false);
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected),
+ );
+ }
+
+ #[test]
+ fn refine_missing_target_is_unresolved_ref() {
+ let mut elig =
+ eligibility_map(&[(1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef))]);
+ refine_ref_bearing(&mut elig, &analysis(&[], &[1], &[(1, &[99])]), false);
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+ }
+
+ #[test]
+ fn refine_structurally_excluded_target_is_unresolved_ref() {
+ let mut elig = eligibility_map(&[
+ (1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ (2, CohortEligibility::Excluded(ExcludedReason::EmptyGroup)),
+ ]);
+ refine_ref_bearing(&mut elig, &analysis(&[], &[1], &[(1, &[2])]), false);
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+ }
+
+ #[test]
+ fn refine_unresolved_propagates_transitively() {
+ let mut elig = eligibility_map(&[
+ (1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ (2, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ ]);
+ refine_ref_bearing(
+ &mut elig,
+ &analysis(&[], &[2, 1], &[(1, &[2]), (2, &[99])]),
+ false,
+ );
+ assert_eq!(
+ elig[&CohortId(2)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+ }
+
+ #[test]
+ fn refine_ref_to_cycle_member_is_unresolved_ref() {
+ let mut elig = eligibility_map(&[
+ (4, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ (1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ (2, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ ]);
+ refine_ref_bearing(
+ &mut elig,
+ &analysis(&[1, 2], &[1, 2, 4], &[(4, &[1]), (1, &[2]), (2, &[1])]),
+ false,
+ );
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected),
+ );
+ assert_eq!(
+ elig[&CohortId(2)],
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected),
+ );
+ assert_eq!(
+ elig[&CohortId(4)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+ }
+
+ #[test]
+ fn refine_resolvable_chain_stays_has_cohort_ref_when_cascade_off() {
+ let mut elig = eligibility_map(&[
+ (1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ (2, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ (3, CohortEligibility::SingleLeaf(LeafStateKey(HASH_A))),
+ ]);
+ refine_ref_bearing(
+ &mut elig,
+ &analysis(&[], &[2, 1], &[(1, &[2]), (2, &[3])]),
+ false,
+ );
+ assert_eq!(
+ elig[&CohortId(2)],
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ );
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ );
+ }
+
+ #[test]
+ fn refine_resolvable_chain_promotes_to_composable_ref_when_cascade_on() {
+ // A(1) → B(2) → C(3, SingleLeaf). Both ref-bearing links resolve and sit in no cycle, so with
+ // the gate on both become Stage2ComposableRef — including the transitive A whose target B was
+ // itself just promoted (is_resolvable must accept Stage2ComposableRef).
+ let mut elig = eligibility_map(&[
+ (1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ (2, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ (3, CohortEligibility::SingleLeaf(LeafStateKey(HASH_A))),
+ ]);
+ refine_ref_bearing(
+ &mut elig,
+ &analysis(&[], &[2, 1], &[(1, &[2]), (2, &[3])]),
+ true,
+ );
+ assert_eq!(elig[&CohortId(2)], CohortEligibility::Stage2ComposableRef);
+ assert_eq!(elig[&CohortId(1)], CohortEligibility::Stage2ComposableRef);
+ assert_eq!(
+ elig[&CohortId(3)],
+ CohortEligibility::SingleLeaf(LeafStateKey(HASH_A)),
+ "the referent's own class is untouched",
+ );
+ }
+
+ #[test]
+ fn refine_cycle_stays_excluded_even_with_cascade_on() {
+ let mut elig =
+ eligibility_map(&[(1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef))]);
+ refine_ref_bearing(&mut elig, &analysis(&[1], &[1], &[(1, &[1])]), true);
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected),
+ "a cycle is never promoted, gate or no gate",
+ );
+ }
+
+ #[test]
+ fn refine_unresolved_stays_excluded_even_with_cascade_on() {
+ let mut elig =
+ eligibility_map(&[(1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef))]);
+ refine_ref_bearing(&mut elig, &analysis(&[], &[1], &[(1, &[99])]), true);
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ "a missing target is never promoted, gate or no gate",
+ );
+ }
+
+ #[test]
+ fn refine_negated_only_missing_target_promotes_to_composable_ref_when_cascade_on() {
+ // 99 is in `ref_targets` (reached through a negated leaf) but absent from
+ // `positive_ref_targets`. An absent negated ref reads `true`, so it never blocks
+ // composition: with the gate on the cohort promotes to Stage2ComposableRef.
+ let mut elig =
+ eligibility_map(&[(1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef))]);
+ refine_ref_bearing(
+ &mut elig,
+ &analysis_with_positives(&[], &[1], &[(1, &[99])], &[]),
+ true,
+ );
+ assert_eq!(elig[&CohortId(1)], CohortEligibility::Stage2ComposableRef);
+ }
+
+ #[test]
+ fn refine_negated_only_missing_target_stays_has_cohort_ref_when_cascade_off() {
+ // Same shape with the gate off: the cohort falls through to HasCohortRef, *not*
+ // UnresolvedRef — the missing negated target must no longer be counted as unresolved.
+ let mut elig =
+ eligibility_map(&[(1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef))]);
+ refine_ref_bearing(
+ &mut elig,
+ &analysis_with_positives(&[], &[1], &[(1, &[99])], &[]),
+ false,
+ );
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ );
+ }
+
+ #[test]
+ fn refine_mixed_polarity_missing_target_is_unresolved_ref() {
+ // 99 is referenced both positively and negatively → it stays in `positive_ref_targets`, so a
+ // missing 99 still excludes as UnresolvedRef (the positive arm cannot resolve it).
+ let mut elig =
+ eligibility_map(&[(1, CohortEligibility::Excluded(ExcludedReason::HasCohortRef))]);
+ refine_ref_bearing(
+ &mut elig,
+ &analysis_with_positives(&[], &[1], &[(1, &[99])], &[(1, &[99])]),
+ true,
+ );
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+ }
+
+ #[test]
+ fn refine_never_touches_structural_exclusions() {
+ let mut elig = eligibility_map(&[(
+ 1,
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ )]);
+ refine_ref_bearing(&mut elig, &analysis(&[], &[1], &[(1, &[99])]), true);
+ assert_eq!(
+ elig[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::TopLevelNegation),
+ "the gate only refines HasCohortRef cohorts, never a structurally-excluded one",
+ );
+ }
+
+ #[test]
+ fn writes_cf_stage2_is_true_only_for_the_two_composable_classes() {
+ assert!(CohortEligibility::Stage2Composable.writes_cf_stage2());
+ assert!(CohortEligibility::Stage2ComposableRef.writes_cf_stage2());
+ assert!(!CohortEligibility::SingleLeaf(LeafStateKey(HASH_A)).writes_cf_stage2());
+ assert!(
+ !CohortEligibility::Excluded(ExcludedReason::HasCohortRef).writes_cf_stage2(),
+ "a still-excluded ref cohort persists no cf_stage2 row",
+ );
+ assert!(!CohortEligibility::Excluded(ExcludedReason::CycleDetected).writes_cf_stage2());
+ }
+
+ #[test]
+ fn composable_ref_metric_class_is_its_own_label() {
+ assert_eq!(
+ CohortEligibility::Stage2ComposableRef.metric_class(),
+ "stage2_composable_ref",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage2/evaluator.rs b/rust/cohort-stream-processor/src/stage2/evaluator.rs
new file mode 100644
index 000000000000..60226f76ad61
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage2/evaluator.rs
@@ -0,0 +1,559 @@
+//! Pure Boolean composition over Stage 1 leaf membership.
+
+use std::collections::HashMap;
+
+use metrics::counter;
+
+use crate::filters::reverse_index::LeafStateMeta;
+use crate::filters::tree::{BoolOp, CohortLeaf, FilterNode};
+use crate::filters::CohortId;
+use crate::observability::metrics::{STAGE2_STATE_DECODE_ERROR, STAGE2_UNEXPECTED_COHORT_REF};
+use crate::stage1::key::LeafStateKey;
+use crate::stage1::predicate::{compressed_predicate, daily_predicate, predicate};
+use crate::stage1::state::{Stage1State, StateVariant};
+
+/// Whether one leaf is currently a member. Absent state is `false`.
+pub fn leaf_membership(state: Option<&Stage1State>, meta: &LeafStateMeta) -> bool {
+ let Some(state) = state else {
+ return false;
+ };
+ match meta.variant {
+ StateVariant::BehavioralSingle | StateVariant::PersonProperty => predicate(state),
+ StateVariant::BehavioralDailyBuckets => match (state, meta.predicate_op) {
+ (Stage1State::BehavioralDailyBuckets { buckets, .. }, Some(op)) => {
+ daily_predicate(buckets, op)
+ }
+ _ => {
+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);
+ false
+ }
+ },
+ StateVariant::BehavioralCompressedHistory => match (state, meta.predicate_op) {
+ (Stage1State::BehavioralCompressedHistory { entries, .. }, Some(op)) => {
+ compressed_predicate(entries, op)
+ }
+ _ => {
+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);
+ false
+ }
+ },
+ }
+}
+
+/// Fold a cohort's filter tree into one membership bit. State-keyed leaves read `membership`,
+/// cohort-reference leaves read `ref_membership`; an absent entry reads `false`, then the leaf's
+/// negation applies (so a negated absent leaf reads `true`).
+pub fn evaluate_tree(
+ node: &FilterNode,
+ membership: &HashMap<LeafStateKey, bool>,
+ ref_membership: &HashMap<CohortId, bool>,
+) -> bool {
+ match node {
+ FilterNode::Group { op, children } => match op {
+ BoolOp::And => children
+ .iter()
+ .all(|child| evaluate_tree(child, membership, ref_membership)),
+ BoolOp::Or => children
+ .iter()
+ .any(|child| evaluate_tree(child, membership, ref_membership)),
+ },
+ FilterNode::Leaf(CohortLeaf::CohortRef(config)) => {
+ let referent = ref_membership.get(&config.referenced_cohort_id).copied();
+ if referent.is_none() {
+ // The caller fills `ref_membership` for every ref leaf, so a miss signals a bug.
+ counter!(STAGE2_UNEXPECTED_COHORT_REF).increment(1);
+ }
+ referent.unwrap_or(false) ^ config.negation
+ }
+ FilterNode::Leaf(leaf) => {
+ let bit = leaf
+ .leaf_state_key()
+ .and_then(|lsk| membership.get(&lsk).copied())
+ .unwrap_or(false);
+ bit ^ leaf.negated()
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use serde_json::Value;
+
+ use super::*;
+ use crate::filters::tree::{CohortLeaf, CohortRefLeafConfig, PersonLeafConfig};
+ use crate::filters::CohortId;
+ use crate::stage1::pick_state::PredicateOp;
+ use crate::stage2::eligibility::condition_negation;
+
+ fn lsk(byte: u8) -> LeafStateKey {
+ LeafStateKey([byte; 16])
+ }
+
+ fn person_leaf(key: LeafStateKey) -> FilterNode {
+ person_leaf_neg(key, false)
+ }
+
+ fn person_leaf_neg(key: LeafStateKey, negated: bool) -> FilterNode {
+ FilterNode::Leaf(CohortLeaf::PersonProperty(PersonLeafConfig {
+ condition_hash: key.0,
+ leaf_state_key: key,
+ bytecode: Arc::new(Vec::new()),
+ raw: Value::Null,
+ negated,
+ }))
+ }
+
+ fn cohort_ref_leaf() -> FilterNode {
+ cohort_ref_leaf_neg(CohortId(99), false)
+ }
+
+ fn cohort_ref_leaf_neg(referenced: CohortId, negation: bool) -> FilterNode {
+ FilterNode::Leaf(CohortLeaf::CohortRef(CohortRefLeafConfig {
+ referenced_cohort_id: referenced,
+ negation,
+ }))
+ }
+
+ fn no_refs() -> HashMap<CohortId, bool> {
+ HashMap::new()
+ }
+
+ fn group(op: BoolOp, children: Vec<FilterNode>) -> FilterNode {
+ FilterNode::Group { op, children }
+ }
+
+ fn person_meta() -> LeafStateMeta {
+ LeafStateMeta {
+ variant: StateVariant::PersonProperty,
+ condition_hash: [0; 16],
+ window: None,
+ window_days: None,
+ predicate_op: None,
+ }
+ }
+
+ fn daily_meta(op: PredicateOp) -> LeafStateMeta {
+ LeafStateMeta {
+ variant: StateVariant::BehavioralDailyBuckets,
+ condition_hash: [0; 16],
+ window: None,
+ window_days: Some(7),
+ predicate_op: Some(op),
+ }
+ }
+
+ #[test]
+ fn leaf_membership_absent_state_is_false() {
+ assert!(!leaf_membership(None, &person_meta()));
+ }
+
+ #[test]
+ fn leaf_membership_reads_the_op_less_bit() {
+ let yes = Stage1State::PersonProperty {
+ matches: true,
+ last_updated_at_ms: 1,
+ last_updated_offset: 2,
+ };
+ let no = Stage1State::PersonProperty {
+ matches: false,
+ last_updated_at_ms: 1,
+ last_updated_offset: 2,
+ };
+ assert!(leaf_membership(Some(&yes), &person_meta()));
+ assert!(!leaf_membership(Some(&no), &person_meta()));
+
+ let single = LeafStateMeta {
+ variant: StateVariant::BehavioralSingle,
+ ..person_meta()
+ };
+ let matched = Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ };
+ assert!(leaf_membership(Some(&matched), &single));
+ }
+
+ #[test]
+ fn leaf_membership_dispatches_a_daily_bucket_leaf_through_its_comparator() {
+ // Dispatch must apply the leaf's comparator to the bucket sum, not the op-less `predicate`
+ // (which reads any bucket state as false). Buckets sum to 3.
+ let state = Stage1State::BehavioralDailyBuckets {
+ buckets: vec![1, 0, 2],
+ window_start_day: 20_600,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ };
+ assert!(
+ leaf_membership(Some(&state), &daily_meta(PredicateOp::Gte(3))),
+ "count 3 satisfies gte 3 — dispatch reached daily_predicate",
+ );
+ assert!(!leaf_membership(
+ Some(&state),
+ &daily_meta(PredicateOp::Gte(4))
+ ));
+ assert!(
+ leaf_membership(Some(&state), &daily_meta(PredicateOp::Lte(3))),
+ "lte 3 holds (and the count>=1 floor is satisfied)",
+ );
+ }
+
+ #[test]
+ fn leaf_membership_dispatches_a_compressed_leaf_through_its_comparator() {
+ let state = Stage1State::BehavioralCompressedHistory {
+ entries: vec![(20_240, 2), (20_400, 1)],
+ window_start_day: 20_240,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ };
+ let meta = LeafStateMeta {
+ variant: StateVariant::BehavioralCompressedHistory,
+ window_days: Some(365),
+ predicate_op: Some(PredicateOp::Gte(3)),
+ ..person_meta()
+ };
+ assert!(
+ leaf_membership(Some(&state), &meta),
+ "count 3 satisfies gte 3"
+ );
+ }
+
+ #[test]
+ fn leaf_membership_variant_state_desync_reads_false() {
+ // meta says daily buckets, but the stored value is a single bit: a desync reads as a
+ // non-member rather than silently a member (the single bit is `true`).
+ let mismatched = Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ };
+ assert!(!leaf_membership(
+ Some(&mismatched),
+ &daily_meta(PredicateOp::Gte(1)),
+ ));
+ }
+
+ #[test]
+ fn leaf_membership_daily_missing_op_reads_false() {
+ let meta = LeafStateMeta {
+ predicate_op: None,
+ ..daily_meta(PredicateOp::Gte(1))
+ };
+ let state = Stage1State::BehavioralDailyBuckets {
+ buckets: vec![5, 0],
+ window_start_day: 1,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ };
+ assert!(!leaf_membership(Some(&state), &meta));
+ }
+
+ #[test]
+ fn evaluate_and_is_the_conjunction() {
+ let tree = group(BoolOp::And, vec![person_leaf(lsk(1)), person_leaf(lsk(2))]);
+ let both = HashMap::from([(lsk(1), true), (lsk(2), true)]);
+ let one = HashMap::from([(lsk(1), true), (lsk(2), false)]);
+ assert!(evaluate_tree(&tree, &both, &no_refs()));
+ assert!(
+ !evaluate_tree(&tree, &one, &no_refs()),
+ "AND fails when either leaf is false"
+ );
+ }
+
+ #[test]
+ fn evaluate_or_is_the_disjunction() {
+ let tree = group(BoolOp::Or, vec![person_leaf(lsk(1)), person_leaf(lsk(2))]);
+ let one = HashMap::from([(lsk(1), false), (lsk(2), true)]);
+ let neither = HashMap::from([(lsk(1), false), (lsk(2), false)]);
+ assert!(
+ evaluate_tree(&tree, &one, &no_refs()),
+ "OR holds when either leaf is true"
+ );
+ assert!(!evaluate_tree(&tree, &neither, &no_refs()));
+ }
+
+ #[test]
+ fn evaluate_nested_groups_compose() {
+ // AND( OR(a, b), c ): true iff (a ∨ b) ∧ c.
+ let tree = group(
+ BoolOp::And,
+ vec![
+ group(BoolOp::Or, vec![person_leaf(lsk(1)), person_leaf(lsk(2))]),
+ person_leaf(lsk(3)),
+ ],
+ );
+ let sat = HashMap::from([(lsk(1), false), (lsk(2), true), (lsk(3), true)]);
+ let c_false = HashMap::from([(lsk(1), true), (lsk(2), true), (lsk(3), false)]);
+ assert!(evaluate_tree(&tree, &sat, &no_refs()));
+ assert!(
+ !evaluate_tree(&tree, &c_false, &no_refs()),
+ "the outer AND needs c"
+ );
+ }
+
+ #[test]
+ fn evaluate_empty_group_identities() {
+ let membership = HashMap::new();
+ assert!(
+ evaluate_tree(&group(BoolOp::And, vec![]), &membership, &no_refs()),
+ "an empty AND is the conjunction identity (true)",
+ );
+ assert!(
+ !evaluate_tree(&group(BoolOp::Or, vec![]), &membership, &no_refs()),
+ "an empty OR is the disjunction identity (false)",
+ );
+ }
+
+ #[test]
+ fn evaluate_duplicate_leaf_collapses() {
+ // AND(L, L) ≡ AND(L): the membership map collapses the duplicate to one key, and the leaf's
+ // bit decides the whole cohort.
+ let tree = group(BoolOp::And, vec![person_leaf(lsk(1)), person_leaf(lsk(1))]);
+ assert!(evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(1), true)]),
+ &no_refs()
+ ));
+ assert!(!evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(1), false)]),
+ &no_refs()
+ ));
+ }
+
+ #[test]
+ fn evaluate_absent_leaf_reads_false() {
+ // lsk(2) is not in the map (its state was absent / undecodable): the AND fails.
+ let tree = group(BoolOp::And, vec![person_leaf(lsk(1)), person_leaf(lsk(2))]);
+ assert!(!evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(1), true)]),
+ &no_refs()
+ ));
+ }
+
+ #[test]
+ fn cohort_ref_leaf_reads_the_referent_bit_from_ref_membership() {
+ let tree = group(BoolOp::Or, vec![person_leaf(lsk(1)), cohort_ref_leaf()]);
+ let off = HashMap::from([(lsk(1), false)]);
+ assert!(
+ evaluate_tree(&tree, &off, &HashMap::from([(CohortId(99), true)])),
+ "referent 99 is a member → OR(false, ref) holds",
+ );
+ assert!(
+ !evaluate_tree(&tree, &off, &HashMap::from([(CohortId(99), false)])),
+ "referent 99 is a non-member → OR(false, ref) is false",
+ );
+ }
+
+ #[test]
+ fn cohort_ref_leaf_absent_referent_reads_false() {
+ let tree = group(BoolOp::Or, vec![person_leaf(lsk(1)), cohort_ref_leaf()]);
+ assert!(!evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(1), false)]),
+ &no_refs(),
+ ));
+ assert!(
+ evaluate_tree(&tree, &HashMap::from([(lsk(1), true)]), &no_refs()),
+ "the real leaf still carries the OR",
+ );
+ }
+
+ #[test]
+ fn negated_cohort_ref_absent_referent_reads_true() {
+ let tree = group(
+ BoolOp::And,
+ vec![person_leaf(lsk(1)), cohort_ref_leaf_neg(CohortId(99), true)],
+ );
+ assert!(
+ evaluate_tree(&tree, &HashMap::from([(lsk(1), true)]), &no_refs()),
+ "absent negated referent reads true via false ^ true",
+ );
+ }
+
+ #[test]
+ fn negated_cohort_ref_present_member_reads_false() {
+ let tree = group(
+ BoolOp::And,
+ vec![person_leaf(lsk(1)), cohort_ref_leaf_neg(CohortId(99), true)],
+ );
+ assert!(
+ !evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(1), true)]),
+ &HashMap::from([(CohortId(99), true)]),
+ ),
+ "referent is a member → ¬member = false → AND fails",
+ );
+ }
+
+ #[test]
+ fn cohort_ref_and_state_keyed_leaf_compose_in_one_tree() {
+ let tree = group(BoolOp::And, vec![person_leaf(lsk(1)), cohort_ref_leaf()]);
+ assert!(evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(1), true)]),
+ &HashMap::from([(CohortId(99), true)]),
+ ));
+ assert!(
+ !evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(1), true)]),
+ &HashMap::from([(CohortId(99), false)]),
+ ),
+ "the referent being a non-member fails the AND",
+ );
+ }
+
+ #[test]
+ fn xor_truth_table_for_and_a_neg_b() {
+ let tree = group(
+ BoolOp::And,
+ vec![person_leaf(lsk(1)), person_leaf_neg(lsk(2), true)],
+ );
+ let cases = [
+ ((true, true), false), // A ∧ ¬B: true ∧ false = false
+ ((true, false), true), // A ∧ ¬B: true ∧ true = true
+ ((false, true), false), // A ∧ ¬B: false ∧ false = false
+ ((false, false), false), // A ∧ ¬B: false ∧ true = false
+ ];
+ for ((a, b), expected) in cases {
+ let map = HashMap::from([(lsk(1), a), (lsk(2), b)]);
+ assert_eq!(
+ evaluate_tree(&tree, &map, &no_refs()),
+ expected,
+ "AND(A={a}, ¬B={b}) should be {expected}",
+ );
+ }
+ }
+
+ #[test]
+ fn negated_absent_leaf_reads_true() {
+ let tree = group(
+ BoolOp::And,
+ vec![person_leaf(lsk(1)), person_leaf_neg(lsk(2), true)],
+ );
+ assert!(
+ evaluate_tree(&tree, &HashMap::from([(lsk(1), true)]), &no_refs()),
+ "absent negated leaf reads true via false ^ true",
+ );
+ }
+
+ #[test]
+ fn and_a_neg_a_same_lsk_always_false() {
+ // Both leaves share one LSK but opposite negation bits → always false.
+ let tree = group(
+ BoolOp::And,
+ vec![person_leaf(lsk(1)), person_leaf_neg(lsk(1), true)],
+ );
+ assert!(
+ !evaluate_tree(&tree, &HashMap::from([(lsk(1), true)]), &no_refs()),
+ "true AND (true ^ true = false) = false",
+ );
+ assert!(
+ !evaluate_tree(&tree, &HashMap::from([(lsk(1), false)]), &no_refs()),
+ "false AND (false ^ true = true) = false",
+ );
+ }
+
+ #[test]
+ fn nested_and_c_or_a_neg_b() {
+ let tree = group(
+ BoolOp::And,
+ vec![
+ person_leaf(lsk(3)),
+ group(
+ BoolOp::Or,
+ vec![person_leaf(lsk(1)), person_leaf_neg(lsk(2), true)],
+ ),
+ ],
+ );
+ // C=true, A=false, B=false → OR(false, true) = true → AND(true, true) = true.
+ assert!(evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(3), true), (lsk(1), false), (lsk(2), false)]),
+ &no_refs(),
+ ));
+ // C=true, A=false, B=true → OR(false, false) = false → AND(true, false) = false.
+ assert!(!evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(3), true), (lsk(1), false), (lsk(2), true)]),
+ &no_refs(),
+ ));
+ // C=false → AND fails regardless.
+ assert!(!evaluate_tree(
+ &tree,
+ &HashMap::from([(lsk(3), false), (lsk(1), true), (lsk(2), false)]),
+ &no_refs(),
+ ));
+ }
+
+ #[test]
+ fn all_absent_invariant_exhaustive() {
+ // For every non-root-negated depth-≤2 tree with ≤3 leaves, both ops × all negation
+ // assignments: evaluate_tree with an empty map must return false.
+ let empty = HashMap::new();
+ let ops = [BoolOp::And, BoolOp::Or];
+ let negs = [false, true];
+
+ // Depth 1: single leaf under a group.
+ for &neg in &negs {
+ let leaf = person_leaf_neg(lsk(1), neg);
+ for &op in &ops {
+ let tree = group(op, vec![leaf.clone()]);
+ if !condition_negation(&tree) {
+ assert!(
+ !evaluate_tree(&tree, &empty, &no_refs()),
+ "depth=1, op={op:?}, neg={neg}",
+ );
+ }
+ }
+ }
+
+ // Depth 1: two leaves.
+ for &neg_a in &negs {
+ for &neg_b in &negs {
+ let a = person_leaf_neg(lsk(1), neg_a);
+ let b = person_leaf_neg(lsk(2), neg_b);
+ for &op in &ops {
+ let tree = group(op, vec![a.clone(), b.clone()]);
+ if !condition_negation(&tree) {
+ assert!(
+ !evaluate_tree(&tree, &empty, &no_refs()),
+ "depth=1, op={op:?}, neg_a={neg_a}, neg_b={neg_b}",
+ );
+ }
+ }
+ }
+ }
+
+ // Depth 2: outer(inner(leaf, leaf), leaf) — 3 leaves, 2 group ops, 8 neg combos.
+ for &neg_a in &negs {
+ for &neg_b in &negs {
+ for &neg_c in &negs {
+ let a = person_leaf_neg(lsk(1), neg_a);
+ let b = person_leaf_neg(lsk(2), neg_b);
+ let c = person_leaf_neg(lsk(3), neg_c);
+ for &inner_op in &ops {
+ for &outer_op in &ops {
+ let tree = group(
+ outer_op,
+ vec![group(inner_op, vec![a.clone(), b.clone()]), c.clone()],
+ );
+ if !condition_negation(&tree) {
+ assert!(
+ !evaluate_tree(&tree, &empty, &no_refs()),
+ "depth=2, outer={outer_op:?}, inner={inner_op:?}, \
+ neg=({neg_a},{neg_b},{neg_c})",
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/stage2/mod.rs b/rust/cohort-stream-processor/src/stage2/mod.rs
new file mode 100644
index 000000000000..638fb670476a
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage2/mod.rs
@@ -0,0 +1,9 @@
+//! Stage 2: per-person Boolean composition of a cohort's leaves into membership flips.
+
+pub mod eligibility;
+pub mod evaluator;
+pub mod state;
+
+pub use eligibility::{classify, CohortEligibility, CohortParseFlags, ExcludedReason};
+pub use evaluator::{evaluate_tree, leaf_membership};
+pub use state::Stage2State;
diff --git a/rust/cohort-stream-processor/src/stage2/state.rs b/rust/cohort-stream-processor/src/stage2/state.rs
new file mode 100644
index 000000000000..bc55e4b3c1bb
--- /dev/null
+++ b/rust/cohort-stream-processor/src/stage2/state.rs
@@ -0,0 +1,76 @@
+//! The persisted `cf_stage2` membership state and its JSON codec.
+
+use serde::{Deserialize, Serialize};
+
+/// The composed membership of one `(cohort, person)`: whether the person is in the cohort, and when
+/// that was last evaluated.
+///
+/// `last_evaluated_at_ms` is write-only for now (nothing reads it). It is the source event's
+/// timestamp, not a wall clock, so the value is replay-stable.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Stage2State {
+ pub in_cohort: bool,
+ pub last_evaluated_at_ms: i64,
+}
+
+/// A failure decoding a stored [`Stage2State`]; surfaced (never panicked) so a single corrupt row is
+/// skipped rather than taking down the worker.
+#[derive(Debug, thiserror::Error)]
+#[error("decoding Stage2 state: {0}")]
+pub struct Stage2CodecError(#[from] serde_json::Error);
+
+impl Stage2State {
+ /// Infallible for this plain struct — `serde_json` only errors on a refusing `Serialize` or
+ /// non-string map keys, neither of which occurs here.
+ pub fn encode(&self) -> Vec<u8> {
+ serde_json::to_vec(self).expect("Stage2State is plain data and always serializes")
+ }
+
+ /// Garbage bytes and missing fields both yield an [`Err`], never a panic.
+ pub fn decode(bytes: &[u8]) -> Result<Self, Stage2CodecError> {
+ Ok(serde_json::from_slice(bytes)?)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn round_trips_both_bits() {
+ for in_cohort in [true, false] {
+ let state = Stage2State {
+ in_cohort,
+ last_evaluated_at_ms: 1_700_000_000_123,
+ };
+ let bytes = state.encode();
+ assert_eq!(Stage2State::decode(&bytes).unwrap(), state);
+ }
+ }
+
+ #[test]
+ fn decodes_from_its_on_disk_shape() {
+ // Pin the on-disk JSON so a future codec change is caught.
+ let on_disk = serde_json::json!({
+ "in_cohort": true,
+ "last_evaluated_at_ms": 1_700_000_000_123_i64,
+ });
+ let bytes = serde_json::to_vec(&on_disk).unwrap();
+ assert_eq!(
+ Stage2State::decode(&bytes).unwrap(),
+ Stage2State {
+ in_cohort: true,
+ last_evaluated_at_ms: 1_700_000_000_123,
+ },
+ );
+ }
+
+ #[test]
+ fn garbage_bytes_decode_to_err_not_panic() {
+ assert!(Stage2State::decode(b"not json at all").is_err());
+ assert!(Stage2State::decode(&[]).is_err());
+ // A missing required field is an error, not a silent default.
+ let partial = serde_json::to_vec(&serde_json::json!({ "in_cohort": true })).unwrap();
+ assert!(Stage2State::decode(&partial).is_err());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/column_families.rs b/rust/cohort-stream-processor/src/store/column_families.rs
new file mode 100644
index 000000000000..40e0e3734eb4
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/column_families.rs
@@ -0,0 +1,144 @@
+//! Column-family registry.
+
+use rocksdb::{BlockBasedOptions, Cache, ColumnFamilyDescriptor, DBCompressionType, Options};
+
+use super::rocks::StoreConfig;
+use super::secondary_index::{full_merge, partial_merge, PERSON_INDEX_MERGE_OPERATOR_NAME};
+
+/// Stage 1 per-leaf state.
+pub const CF_STAGE1: &str = "cf_stage1";
+/// Per-person secondary index.
+pub const CF_PERSON_INDEX: &str = "cf_person_index";
+/// Stage 2 membership.
+pub const CF_STAGE2: &str = "cf_stage2";
+/// Merge Phase 1 idempotence: short-circuits re-drained merge messages.
+pub const CF_MERGE_DRAINS_APPLIED: &str = "cf_merge_drains_applied";
+/// Phase 1 durability outbox: holds packaged merges until the transfer produce is acked.
+pub const CF_PENDING_TRANSFERS: &str = "cf_pending_transfers";
+/// Phase 2 idempotence: keyed by the triggering merge message's coordinates.
+pub const CF_MERGE_APPLIED: &str = "cf_merge_applied";
+/// Post-merge straggler redirect: records merged-away persons for late-event redirection.
+pub const CF_MERGE_TOMBSTONES: &str = "cf_merge_tombstones";
+
+const BLOOM_FILTER_BITS_PER_KEY: f64 = 10.0;
+
+/// Column family enum.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub enum Cf {
+ Stage1,
+ PersonIndex,
+ Stage2,
+ MergeDrainsApplied,
+ PendingTransfers,
+ MergeApplied,
+ MergeTombstones,
+}
+
+impl Cf {
+ pub const ALL: [Cf; 7] = [
+ Cf::Stage1,
+ Cf::PersonIndex,
+ Cf::Stage2,
+ Cf::MergeDrainsApplied,
+ Cf::PendingTransfers,
+ Cf::MergeApplied,
+ Cf::MergeTombstones,
+ ];
+
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Cf::Stage1 => CF_STAGE1,
+ Cf::PersonIndex => CF_PERSON_INDEX,
+ Cf::Stage2 => CF_STAGE2,
+ Cf::MergeDrainsApplied => CF_MERGE_DRAINS_APPLIED,
+ Cf::PendingTransfers => CF_PENDING_TRANSFERS,
+ Cf::MergeApplied => CF_MERGE_APPLIED,
+ Cf::MergeTombstones => CF_MERGE_TOMBSTONES,
+ }
+ }
+}
+
+/// A column family safe for raw `put` (excludes `cf_person_index`).
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub enum OpaqueCf {
+ Stage1,
+ Stage2,
+}
+
+impl OpaqueCf {
+ pub const fn cf(self) -> Cf {
+ match self {
+ OpaqueCf::Stage1 => Cf::Stage1,
+ OpaqueCf::Stage2 => Cf::Stage2,
+ }
+ }
+}
+
+impl From<OpaqueCf> for Cf {
+ fn from(cf: OpaqueCf) -> Cf {
+ cf.cf()
+ }
+}
+
+pub fn descriptors(config: &StoreConfig, cache: &Cache) -> Vec<ColumnFamilyDescriptor> {
+ Cf::ALL
+ .iter()
+ .map(|&cf| ColumnFamilyDescriptor::new(cf.as_str(), cf_options(cf, config, cache)))
+ .collect()
+}
+
+fn cf_options(cf: Cf, config: &StoreConfig, cache: &Cache) -> Options {
+ let mut block_opts = BlockBasedOptions::default();
+ block_opts.set_block_cache(cache);
+ block_opts.set_bloom_filter(BLOOM_FILTER_BITS_PER_KEY, false);
+
+ let mut opts = Options::default();
+ opts.set_block_based_table_factory(&block_opts);
+ opts.set_compression_type(DBCompressionType::Lz4);
+ opts.set_write_buffer_size(config.write_buffer_bytes);
+
+ match cf {
+ Cf::PersonIndex => {
+ opts.set_merge_operator(PERSON_INDEX_MERGE_OPERATOR_NAME, full_merge, partial_merge);
+ }
+ Cf::Stage1
+ | Cf::Stage2
+ | Cf::MergeDrainsApplied
+ | Cf::PendingTransfers
+ | Cf::MergeApplied
+ | Cf::MergeTombstones => {}
+ }
+ opts
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cf_names_are_stable() {
+ assert_eq!(Cf::Stage1.as_str(), "cf_stage1");
+ assert_eq!(Cf::PersonIndex.as_str(), "cf_person_index");
+ assert_eq!(Cf::Stage2.as_str(), "cf_stage2");
+ assert_eq!(Cf::MergeDrainsApplied.as_str(), "cf_merge_drains_applied");
+ assert_eq!(Cf::PendingTransfers.as_str(), "cf_pending_transfers");
+ assert_eq!(Cf::MergeApplied.as_str(), "cf_merge_applied");
+ assert_eq!(Cf::MergeTombstones.as_str(), "cf_merge_tombstones");
+ }
+
+ #[test]
+ fn all_is_exhaustive_and_unique() {
+ assert_eq!(Cf::ALL.len(), 7);
+ for cf in Cf::ALL {
+ assert!(Cf::ALL.iter().filter(|&&c| c == cf).count() == 1);
+ }
+ }
+
+ #[test]
+ fn descriptors_cover_every_cf() {
+ let config = StoreConfig::default();
+ let cache = Cache::new_lru_cache(1024 * 1024);
+ let descriptors = descriptors(&config, &cache);
+ assert_eq!(descriptors.len(), Cf::ALL.len());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/checkpoint.rs b/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
new file mode 100644
index 000000000000..88a83c378345
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
@@ -0,0 +1,364 @@
+//! The checkpoint orchestrator.
+//!
+//! [`CheckpointSweeper`] is one sweep loop, driven by
+//! [`run_sweep_loop`](crate::sweep::run_sweep_loop) at `checkpoint_interval`. Each tick takes a frozen
+//! whole-DB RocksDB checkpoint to the local PVC; every Nth tick it also uploads that checkpoint to S3
+//! incrementally (only the SSTs that changed). One `create_checkpoint` per tick — never two racing.
+//!
+//! ## Interior mutability without a mutex across `.await`
+//!
+//! The tick counter is an [`AtomicU64`] (`fetch_add`, no await). The incremental-upload baseline (the
+//! last-uploaded [`CheckpointMetadata`]) is a [`tokio::sync::Mutex`], but it is never held across an
+//! `.await`: the baseline is cloned out under the guard, which is then dropped, the plan + upload run
+//! lock-free, and on a successful upload the new baseline is stored under a fresh, momentary lock.
+//!
+//! ## Must not panic
+//!
+//! The [`Sweeper`] contract forbids panicking (a panic aborts the timer task and stops all future
+//! checkpoints). Every fallible step is handled, the failure is logged and counted, and the loop
+//! continues.
+
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use chrono::Utc;
+use tokio::sync::Mutex;
+use tracing::{error, info, warn};
+
+use super::{
+ plan_checkpoint, CheckpointExporter, CheckpointMetadata, DurabilityConfig, OffsetManifest,
+ STORE_PARTITION, STORE_TOPIC,
+};
+use crate::consumers::EventDispatcher;
+use crate::observability::metrics::{
+ CHECKPOINT_FILES_UPLOADED_TOTAL, CHECKPOINT_FILE_COUNT, CHECKPOINT_SIZE_BYTES,
+ CHECKPOINT_UPLOADS_TOTAL,
+};
+use crate::partitions::OffsetTracker;
+use crate::store::CohortStore;
+use crate::sweep::Sweeper;
+
+/// The loop-name label for the checkpoint sweep cycle metrics.
+pub const CHECKPOINT_LOOP_NAME: &str = "checkpoint";
+
+/// One topic and the [`OffsetTracker`] that tracks its committed positions, passed to
+/// [`CheckpointSweeper::new`].
+pub type TrackedTopic = (String, Arc<OffsetTracker>);
+
+/// True on every `every_n`-th tick (tick 0, N, 2N, …). `every_n == 0` is treated as 1.
+pub fn should_upload(tick: u64, every_n: u64) -> bool {
+ let n = every_n.max(1);
+ tick.is_multiple_of(n)
+}
+
+/// `N = max(1, s3_upload_interval / checkpoint_interval)`. Floored at 1 to prevent division by zero
+/// and ensure at least every-tick uploading when the checkpoint interval is large.
+pub fn upload_cadence(checkpoint_interval_ms: u64, s3_upload_interval_ms: u64) -> u64 {
+ (s3_upload_interval_ms / checkpoint_interval_ms.max(1)).max(1)
+}
+
+/// Drives periodic whole-DB checkpoints to the local PVC + incremental S3 backup.
+pub struct CheckpointSweeper {
+ store: CohortStore,
+ dispatcher: Arc<EventDispatcher>,
+ /// The `(topic, tracker)` pairs whose committed offsets the manifest captures.
+ trackers: Vec<TrackedTopic>,
+ exporter: CheckpointExporter,
+ config: DurabilityConfig,
+ /// Base dir for local checkpoints; a sibling subtree of `store_path` (RocksDB hard-links SSTs, so
+ /// it must be on the same filesystem and must not be a child of the store path).
+ checkpoint_local_dir: PathBuf,
+ tick: AtomicU64,
+ upload_every_n: u64,
+ /// Baseline for the next incremental S3 diff. Cloned out before the upload await (never held
+ /// across `.await`); updated only after a successful upload. `None` until the first upload.
+ last_uploaded: Mutex<Option<CheckpointMetadata>>,
+}
+
+impl CheckpointSweeper {
+ pub fn new(
+ store: CohortStore,
+ dispatcher: Arc<EventDispatcher>,
+ trackers: Vec<TrackedTopic>,
+ exporter: CheckpointExporter,
+ config: DurabilityConfig,
+ checkpoint_local_dir: PathBuf,
+ upload_every_n: u64,
+ ) -> Self {
+ Self {
+ store,
+ dispatcher,
+ trackers,
+ exporter,
+ config,
+ checkpoint_local_dir,
+ tick: AtomicU64::new(0),
+ upload_every_n,
+ last_uploaded: Mutex::new(None),
+ }
+ }
+
+ fn attempt_parent(&self) -> PathBuf {
+ self.checkpoint_local_dir
+ .join(STORE_TOPIC)
+ .join(STORE_PARTITION.to_string())
+ }
+
+ async fn checkpoint_once(&self) {
+ let tick = self.tick.fetch_add(1, Ordering::SeqCst);
+
+ // 1. fsync the WAL before the snapshot so `committed <= durable` holds. A failure here would
+ // yield a checkpoint whose manifest claims more than is durable — skip the tick.
+ let flush_store = self.store.clone();
+ let flush_result = tokio::task::spawn_blocking(move || flush_store.flush_wal_sync()).await;
+ match flush_result {
+ Ok(Ok(())) => {}
+ Ok(Err(e)) => {
+ warn!(error = %e, "checkpoint tick: WAL fsync failed; skipping tick");
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "flush_failed")
+ .increment(1);
+ return;
+ }
+ Err(join_err) => {
+ error!(error = %join_err, "checkpoint tick: WAL fsync task panicked; skipping tick");
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "flush_failed")
+ .increment(1);
+ return;
+ }
+ }
+
+ // 2. Capture committed offsets (not committable/processed) for all owned partitions.
+ let owned = self.dispatcher.owned_partitions();
+ let tracker_refs: Vec<(&str, &OffsetTracker)> = self
+ .trackers
+ .iter()
+ .map(|(topic, tracker)| (topic.as_str(), tracker.as_ref()))
+ .collect();
+ let manifest = OffsetManifest::capture(&owned, &tracker_refs);
+
+ // 3. Take a whole-DB RocksDB checkpoint (sync I/O → spawn_blocking). The attempt dir must
+ // not be a child of store_path; SST hard-links require the same filesystem.
+ let attempt_timestamp = Utc::now();
+ let checkpoint_id = format!(
+ "{}-{tick}",
+ CheckpointMetadata::generate_id(attempt_timestamp)
+ );
+ let attempt_dir = self.attempt_parent().join(&checkpoint_id);
+ // `create_checkpoint` requires the leaf to NOT exist; it creates it and errors if it does.
+ if let Err(e) = tokio::fs::create_dir_all(self.attempt_parent()).await {
+ warn!(error = %e, dir = %self.attempt_parent().display(), "checkpoint tick: cannot create attempt parent dir; skipping tick");
+ return;
+ }
+ let checkpoint_store = self.store.clone();
+ let checkpoint_dir = attempt_dir.clone();
+ debug_assert!(
+ !attempt_dir.exists(),
+ "checkpoint attempt dir must not exist before create_checkpoint: {}",
+ attempt_dir.display(),
+ );
+ let create_result = tokio::task::spawn_blocking(move || {
+ checkpoint_store.create_checkpoint(&checkpoint_dir)
+ })
+ .await;
+ match create_result {
+ Ok(Ok(())) => {}
+ Ok(Err(e)) => {
+ warn!(error = %e, "checkpoint tick: create_checkpoint failed; skipping tick");
+ drop(tokio::fs::remove_dir_all(&attempt_dir).await);
+ return;
+ }
+ Err(join_err) => {
+ error!(error = %join_err, "checkpoint tick: create_checkpoint task panicked; skipping tick");
+ drop(tokio::fs::remove_dir_all(&attempt_dir).await);
+ return;
+ }
+ }
+
+ // 4. Write offsets.json after create_checkpoint (so it is never frozen mid-write) but before
+ // planning, so the planner tracks it as a non-SST file and the S3 upload carries it.
+ // Without offsets.json an S3 restore cannot seek. metadata.json is written after planning.
+ if let Err(e) = manifest.write_to_dir(&attempt_dir) {
+ warn!(error = %e, "checkpoint tick: writing offsets.json failed; skipping tick");
+ drop(tokio::fs::remove_dir_all(&attempt_dir).await);
+ return;
+ }
+
+ // 5. Plan the incremental diff vs the last-uploaded baseline, then write metadata.json.
+ let baseline = { self.last_uploaded.lock().await.clone() };
+ let plan = match plan_checkpoint(
+ &attempt_dir,
+ self.config.s3_key_prefix.clone(),
+ attempt_timestamp,
+ tick,
+ baseline.as_ref(),
+ None,
+ ) {
+ Ok(plan) => plan,
+ Err(e) => {
+ warn!(error = %e, "checkpoint tick: planning failed; skipping tick");
+ drop(tokio::fs::remove_dir_all(&attempt_dir).await);
+ return;
+ }
+ };
+
+ let mut info = plan.info.clone();
+ if let Err(e) = info.metadata.write_to_dir(&attempt_dir).await {
+ warn!(error = %e, "checkpoint tick: writing metadata.json failed; skipping tick");
+ drop(tokio::fs::remove_dir_all(&attempt_dir).await);
+ return;
+ }
+
+ // 6. Emit local-checkpoint size and file-count metrics.
+ let (size_bytes, file_count) = dir_size_and_count(&attempt_dir);
+ metrics::histogram!(CHECKPOINT_SIZE_BYTES).record(size_bytes as f64);
+ metrics::histogram!(CHECKPOINT_FILE_COUNT).record(file_count as f64);
+ info!(
+ checkpoint_id,
+ dir = %attempt_dir.display(),
+ size_bytes,
+ file_count,
+ "local checkpoint taken",
+ );
+
+ // 7. Every Nth tick: upload to S3 and advance the baseline on success.
+ if should_upload(tick, self.upload_every_n) {
+ self.upload(&plan).await;
+ }
+
+ // 8. Prune older local checkpoint dirs (keep latest only) to avoid pinning SSTs that the live
+ // DB compacted away, which would cause unbounded PVC growth.
+ self.prune_old_checkpoints(&attempt_dir).await;
+ }
+
+ async fn upload(&self, plan: &super::CheckpointPlan) {
+ let files_in_plan = plan.files_to_upload.len();
+ match self
+ .exporter
+ .export_checkpoint_with_plan_cancellable(plan, None, None)
+ .await
+ {
+ Ok(()) => {
+ metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "success")
+ .increment(files_in_plan as u64);
+ {
+ let mut baseline = self.last_uploaded.lock().await;
+ *baseline = Some(plan.info.metadata.clone());
+ }
+ info!(uploaded_files = files_in_plan, "checkpoint uploaded to S3");
+ }
+ Err(e) => {
+ metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "error")
+ .increment(files_in_plan as u64);
+ warn!(error = %e, "checkpoint S3 upload failed; baseline unchanged");
+ }
+ }
+ }
+
+ async fn prune_old_checkpoints(&self, keep: &Path) {
+ let parent = self.attempt_parent();
+ let entries = match tokio::fs::read_dir(&parent).await {
+ Ok(entries) => entries,
+ Err(_) => return,
+ };
+ let mut entries = entries;
+ loop {
+ let next = match entries.next_entry().await {
+ Ok(Some(entry)) => entry,
+ Ok(None) => break,
+ Err(e) => {
+ warn!(error = %e, "checkpoint prune: reading attempt parent failed");
+ break;
+ }
+ };
+ let path = next.path();
+ if path == keep || !path.is_dir() {
+ continue;
+ }
+ if let Err(e) = tokio::fs::remove_dir_all(&path).await {
+ warn!(error = %e, dir = %path.display(), "checkpoint prune: failed to remove old checkpoint");
+ }
+ }
+ }
+}
+
+#[async_trait]
+impl Sweeper for CheckpointSweeper {
+ async fn run_once(&self) {
+ self.checkpoint_once().await;
+ }
+}
+
+/// Total byte size and file count of a directory tree. Unreadable entries are skipped.
+fn dir_size_and_count(dir: &Path) -> (u64, u64) {
+ let mut size = 0u64;
+ let mut count = 0u64;
+ let mut stack = vec![dir.to_path_buf()];
+ while let Some(current) = stack.pop() {
+ let Ok(entries) = std::fs::read_dir(&current) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ match entry.file_type() {
+ Ok(ft) if ft.is_dir() => stack.push(path),
+ Ok(_) => {
+ if let Ok(meta) = entry.metadata() {
+ size += meta.len();
+ count += 1;
+ }
+ }
+ Err(_) => {}
+ }
+ }
+ }
+ (size, count)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn should_upload_fires_on_the_first_and_every_nth_tick() {
+ let fired: Vec<u64> = (0..10).filter(|&t| should_upload(t, 3)).collect();
+ assert_eq!(fired, vec![0, 3, 6, 9]);
+ }
+
+ #[test]
+ fn should_upload_every_tick_when_n_is_one() {
+ for tick in 0..5 {
+ assert!(
+ should_upload(tick, 1),
+ "every tick uploads when every_n == 1"
+ );
+ }
+ }
+
+ #[test]
+ fn should_upload_treats_zero_n_as_one_without_panicking() {
+ assert!(should_upload(0, 0));
+ assert!(should_upload(7, 0));
+ }
+
+ #[test]
+ fn upload_cadence_is_the_interval_ratio_floored_at_one() {
+ assert_eq!(upload_cadence(300_000, 900_000), 3); // 15min / 5min = 3
+ assert_eq!(upload_cadence(300_000, 60_000), 1); // upload interval < checkpoint interval → every tick
+ assert_eq!(upload_cadence(0, 900_000), 900_000); // zero checkpoint interval handled
+ }
+
+ #[test]
+ fn dir_size_and_count_sums_nested_files() {
+ let dir = tempfile::TempDir::new().unwrap();
+ std::fs::write(dir.path().join("a.sst"), b"12345").unwrap();
+ let nested = dir.path().join("nested");
+ std::fs::create_dir_all(&nested).unwrap();
+ std::fs::write(nested.join("b.sst"), b"123").unwrap();
+
+ let (size, count) = dir_size_and_count(dir.path());
+ assert_eq!(count, 2);
+ assert_eq!(size, 8);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/config.rs b/rust/cohort-stream-processor/src/store/durability/config.rs
new file mode 100644
index 000000000000..5f2e0abef90e
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/config.rs
@@ -0,0 +1,105 @@
+//! Resolved knobs for the durability layer (S3 client, uploader, downloader, importer).
+
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+
+/// Default maximum age (seconds) of a local checkpoint before the local store is considered stale and
+/// the service falls back to S3 import. 2 hours.
+pub const DEFAULT_LOCAL_CHECKPOINT_MAX_STALENESS_SECS: u64 = 7200;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DurabilityConfig {
+ /// Base directory for local checkpoints (a subtree separate from the live store path).
+ pub local_checkpoint_dir: String,
+
+ /// S3 bucket for checkpoint uploads.
+ pub s3_bucket: String,
+
+ /// S3 key prefix (bucket namespace) for checkpoint attempts.
+ pub s3_key_prefix: String,
+
+ /// AWS region for S3.
+ pub aws_region: Option<String>,
+
+ /// S3 endpoint URL (for non-AWS S3-compatible stores like MinIO/SeaweedFS).
+ pub s3_endpoint: Option<String>,
+
+ /// S3 access key (for local dev without IAM role).
+ pub s3_access_key_id: Option<String>,
+
+ /// S3 secret key (for local dev without IAM role).
+ pub s3_secret_access_key: Option<String>,
+
+ /// Force path-style S3 URLs (required for MinIO/SeaweedFS).
+ pub s3_force_path_style: bool,
+
+ /// Number of hours prior to "now" that the checkpoint import mechanism will search for valid
+ /// checkpoint attempts in a DR recovery scenario where a net-new Persistent Volume was created.
+ pub checkpoint_import_window_hours: u32,
+
+ /// Timeout for S3 operations (including all retry attempts).
+ pub s3_operation_timeout: Duration,
+
+ /// Timeout for a single S3 operation attempt.
+ pub s3_attempt_timeout: Duration,
+
+ /// Maximum number of retries for S3 operations before giving up.
+ pub s3_max_retries: usize,
+
+ /// Number of recent historical checkpoint attempts to try to import, starting from most recent,
+ /// when importing from remote storage. A failed download or corrupt files falls back to the next
+ /// most recent checkpoint attempt this many times.
+ pub checkpoint_import_attempt_depth: usize,
+
+ /// Maximum concurrent S3 file downloads during checkpoint import. Bounds the number of in-flight
+ /// HTTP connections (and thus memory).
+ pub max_concurrent_checkpoint_file_downloads: usize,
+
+ /// Maximum concurrent S3 file uploads during checkpoint export. Controls the `LimitStore`
+ /// semaphore that bounds concurrent S3 HTTP requests.
+ pub max_concurrent_checkpoint_file_uploads: usize,
+
+ /// Maximum number of upload futures actively polled (files open with read buffers and BufWriters)
+ /// per checkpoint. Controls the `buffer_unordered` window to bound memory independently from the
+ /// S3 HTTP concurrency limit above. Each active buffer consumes ~18MB (8MB read buffer + ~10MB
+ /// BufWriter).
+ pub max_upload_buffers: usize,
+
+ /// Maximum time allowed for a complete checkpoint import. This includes listing checkpoints,
+ /// downloading metadata, and downloading all files. Should be less than Kafka max.poll.interval.ms
+ /// to prevent consumer group kicks.
+ pub checkpoint_import_timeout: Duration,
+
+ /// Maximum age of a local checkpoint before the local store is considered stale and the service
+ /// falls back to S3 import. Separate from `checkpoint_import_window_hours` (the S3 listing window):
+ /// local staleness must be tighter because if a pod was down for longer than this, another pod
+ /// likely consumed the partition and local data is behind.
+ pub local_checkpoint_max_staleness: Duration,
+}
+
+impl Default for DurabilityConfig {
+ fn default() -> Self {
+ Self {
+ local_checkpoint_dir: "./checkpoints".to_string(),
+ s3_bucket: String::new(),
+ s3_key_prefix: "cohort-stream-checkpoints".to_string(),
+ aws_region: None,
+ s3_endpoint: None,
+ s3_access_key_id: None,
+ s3_secret_access_key: None,
+ s3_force_path_style: false,
+ checkpoint_import_window_hours: 24,
+ s3_operation_timeout: Duration::from_secs(120),
+ s3_attempt_timeout: Duration::from_secs(20),
+ s3_max_retries: 3,
+ checkpoint_import_attempt_depth: 10,
+ max_concurrent_checkpoint_file_downloads: 40,
+ max_concurrent_checkpoint_file_uploads: 40,
+ max_upload_buffers: 40,
+ checkpoint_import_timeout: Duration::from_secs(240),
+ local_checkpoint_max_staleness: Duration::from_secs(
+ DEFAULT_LOCAL_CHECKPOINT_MAX_STALENESS_SECS,
+ ),
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/downloader.rs b/rust/cohort-stream-processor/src/store/durability/downloader.rs
new file mode 100644
index 000000000000..48c2a072a5c0
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/downloader.rs
@@ -0,0 +1,43 @@
+use anyhow::Result;
+use async_trait::async_trait;
+use std::path::Path;
+use tokio_util::sync::CancellationToken;
+
+#[async_trait]
+pub trait CheckpointDownloader: Send + Sync + std::fmt::Debug {
+ /// List remote checkpoint-attempt metadata.json keys, sorted newest to oldest.
+ async fn list_recent_checkpoints(&self) -> Result<Vec<String>>;
+
+ /// Download a single remote file and return its bytes.
+ async fn download_file(&self, remote_key: &str) -> Result<Vec<u8>>;
+
+ /// Download a single file and write it to `local_filepath`. Parent dirs must already exist.
+ async fn download_and_store_file(&self, remote_key: &str, local_filepath: &Path) -> Result<()> {
+ self.download_and_store_file_cancellable(remote_key, local_filepath, None)
+ .await
+ }
+
+ /// Download and store a single file with optional cancellation. Cleans up any partial file on
+ /// cancellation.
+ async fn download_and_store_file_cancellable(
+ &self,
+ remote_key: &str,
+ local_filepath: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()>;
+
+ /// Download all files in parallel into `local_base_path`. Caller must create the directory.
+ async fn download_files(&self, remote_keys: &[String], local_base_path: &Path) -> Result<()> {
+ self.download_files_cancellable(remote_keys, local_base_path, None)
+ .await
+ }
+
+ async fn download_files_cancellable(
+ &self,
+ remote_keys: &[String],
+ local_base_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()>;
+
+ async fn is_available(&self) -> bool;
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/error.rs b/rust/cohort-stream-processor/src/store/durability/error.rs
new file mode 100644
index 000000000000..bcada21f2472
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/error.rs
@@ -0,0 +1,69 @@
+//! Sentinel error types for the durability layer.
+//!
+//! Plain `std::error::Error` structs so callers can thread them through `anyhow::Error` and recover
+//! them with `downcast_ref::<T>()` to distinguish a cancellation (metrics only, not a real failure)
+//! from a genuine error.
+
+use std::fmt;
+
+/// An upload was cancelled (e.g. rebalance or shutdown). Detect via `downcast_ref::<Self>()`.
+#[derive(Debug)]
+pub struct UploadCancelledError {
+ pub reason: String,
+}
+
+impl fmt::Display for UploadCancelledError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "Upload cancelled: {}", self.reason)
+ }
+}
+
+impl std::error::Error for UploadCancelledError {}
+
+/// A download was cancelled (e.g. rebalance or shutdown). Detect via `downcast_ref::<Self>()`.
+#[derive(Debug)]
+pub struct DownloadCancelledError {
+ pub reason: String,
+}
+
+impl fmt::Display for DownloadCancelledError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "Download cancelled: {}", self.reason)
+ }
+}
+
+impl std::error::Error for DownloadCancelledError {}
+
+/// Checkpoint planning was cancelled before upload started. Detect via `downcast_ref::<Self>()`.
+#[derive(Debug)]
+pub struct PlanningCancelledError {
+ pub reason: String,
+}
+
+impl fmt::Display for PlanningCancelledError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "Checkpoint planning cancelled: {}", self.reason)
+ }
+}
+
+impl std::error::Error for PlanningCancelledError {}
+
+/// A checkpoint import timed out, bounding import time below Kafka's max poll interval. Detect via
+/// `downcast_ref::<Self>()`. `store` is a static descriptor since the whole DB imports as one unit.
+#[derive(Debug)]
+pub struct ImportTimeoutError {
+ pub store: &'static str,
+ pub timeout_secs: u64,
+}
+
+impl fmt::Display for ImportTimeoutError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ f,
+ "Checkpoint import timed out after {}s for {}",
+ self.timeout_secs, self.store
+ )
+ }
+}
+
+impl std::error::Error for ImportTimeoutError {}
diff --git a/rust/cohort-stream-processor/src/store/durability/export.rs b/rust/cohort-stream-processor/src/store/durability/export.rs
new file mode 100644
index 000000000000..eba145315467
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/export.rs
@@ -0,0 +1,234 @@
+use std::time::Instant;
+
+use super::{CheckpointPlan, CheckpointUploader, UploadCancelledError};
+use crate::observability::metrics::{CHECKPOINT_UPLOADS_TOTAL, CHECKPOINT_UPLOAD_DURATION_SECONDS};
+
+use anyhow::Result;
+use tokio_util::sync::CancellationToken;
+use tracing::{error, info, warn};
+
+#[derive(Debug)]
+pub struct CheckpointExporter {
+ uploader: Box<dyn CheckpointUploader>,
+}
+
+impl CheckpointExporter {
+ pub fn new(uploader: Box<dyn CheckpointUploader>) -> Self {
+ Self { uploader }
+ }
+
+ pub async fn export_checkpoint_with_plan(&self, plan: &CheckpointPlan) -> Result<()> {
+ self.export_checkpoint_with_plan_cancellable(plan, None, None)
+ .await
+ }
+
+ /// Export a checkpoint with cancellation support. A cancellation returns an error early but is
+ /// recorded as a cancellation (not a failure) in metrics/logs. `cancel_cause` ("rebalance" /
+ /// "shutdown") labels that metric.
+ pub async fn export_checkpoint_with_plan_cancellable(
+ &self,
+ plan: &CheckpointPlan,
+ cancel_token: Option<&CancellationToken>,
+ cancel_cause: Option<&str>,
+ ) -> Result<()> {
+ if !self.is_available().await {
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "unavailable").increment(1);
+ warn!(
+ remote_metadata_path = plan.info.get_metadata_key(),
+ "Export failed: uploader not available"
+ );
+ return Err(anyhow::anyhow!("Uploader not available"));
+ }
+
+ let upload_start = Instant::now();
+
+ match self
+ .uploader
+ .upload_checkpoint_with_plan_cancellable(plan, cancel_token)
+ .await
+ {
+ Ok(uploaded_files) => {
+ let upload_duration = upload_start.elapsed();
+ let total_files = plan.info.metadata.files.len();
+ let new_files = plan.files_to_upload.len();
+ let reused_files = total_files - new_files;
+
+ metrics::histogram!(CHECKPOINT_UPLOAD_DURATION_SECONDS, "result" => "success")
+ .record(upload_duration.as_secs_f64());
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "success").increment(1);
+
+ info!(
+ remote_path = plan.info.get_metadata_key(),
+ uploaded_file_count = uploaded_files.len(),
+ total_files = total_files,
+ new_files = new_files,
+ reused_files = reused_files,
+ elapsed_seconds = upload_duration.as_secs_f64(),
+ "Export successful: checkpoint uploaded with deduplication",
+ );
+
+ Ok(())
+ }
+
+ Err(e) => {
+ let upload_duration = upload_start.elapsed();
+ if e.downcast_ref::<UploadCancelledError>().is_some() {
+ // Metrics labels must be 'static, so map the cause to a fixed string.
+ let cause: &'static str = match cancel_cause {
+ Some("rebalance") => "rebalance",
+ Some("shutdown") => "shutdown",
+ _ => "unknown",
+ };
+ metrics::histogram!(CHECKPOINT_UPLOAD_DURATION_SECONDS, "result" => "cancelled", "cause" => cause)
+ .record(upload_duration.as_secs_f64());
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "cancelled", "cause" => cause)
+ .increment(1);
+ } else {
+ metrics::histogram!(CHECKPOINT_UPLOAD_DURATION_SECONDS, "result" => "error")
+ .record(upload_duration.as_secs_f64());
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "error").increment(1);
+ error!(
+ remote_path = plan.info.get_metadata_key(),
+ elapsed_seconds = upload_duration.as_secs_f64(),
+ "Export failed: uploading checkpoint: {e:#}"
+ );
+ }
+ Err(e)
+ }
+ }
+ }
+
+ pub async fn is_available(&self) -> bool {
+ self.uploader.is_available().await
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use async_trait::async_trait;
+ use chrono::{TimeZone, Utc};
+
+ use crate::store::durability::{
+ CheckpointInfo, CheckpointMetadata, UploadCancelledError, STORE_PARTITION, STORE_TOPIC,
+ };
+
+ #[derive(Debug)]
+ struct MockUploader {
+ should_return_cancelled: bool,
+ should_return_error: bool,
+ }
+
+ impl MockUploader {
+ fn new_success() -> Self {
+ Self {
+ should_return_cancelled: false,
+ should_return_error: false,
+ }
+ }
+
+ fn new_cancelled() -> Self {
+ Self {
+ should_return_cancelled: true,
+ should_return_error: false,
+ }
+ }
+
+ fn new_error() -> Self {
+ Self {
+ should_return_cancelled: false,
+ should_return_error: true,
+ }
+ }
+ }
+
+ #[async_trait]
+ impl CheckpointUploader for MockUploader {
+ async fn upload_checkpoint_with_plan_cancellable(
+ &self,
+ _plan: &CheckpointPlan,
+ _cancel_token: Option<&CancellationToken>,
+ ) -> Result<Vec<String>> {
+ if self.should_return_cancelled {
+ Err(UploadCancelledError {
+ reason: "test".to_string(),
+ }
+ .into())
+ } else if self.should_return_error {
+ Err(anyhow::anyhow!("S3 error: connection failed"))
+ } else {
+ Ok(vec!["test/key".to_string()])
+ }
+ }
+
+ async fn is_available(&self) -> bool {
+ true
+ }
+ }
+
+ fn create_test_plan() -> CheckpointPlan {
+ let timestamp = Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap();
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ timestamp,
+ 12345,
+ 0,
+ 0,
+ );
+ let info = CheckpointInfo::new(metadata, "checkpoints".to_string(), None);
+ CheckpointPlan {
+ info,
+ files_to_upload: vec![],
+ }
+ }
+
+ #[tokio::test]
+ async fn export_success() {
+ let uploader = Box::new(MockUploader::new_success());
+ let exporter = CheckpointExporter::new(uploader);
+ let plan = create_test_plan();
+
+ let result = exporter
+ .export_checkpoint_with_plan_cancellable(&plan, None, None)
+ .await;
+
+ assert!(result.is_ok());
+ }
+
+ #[tokio::test]
+ async fn export_cancelled_returns_error_with_cancelled_type() {
+ let uploader = Box::new(MockUploader::new_cancelled());
+ let exporter = CheckpointExporter::new(uploader);
+ let plan = create_test_plan();
+
+ let result = exporter
+ .export_checkpoint_with_plan_cancellable(&plan, None, Some("rebalance"))
+ .await;
+
+ assert!(result.is_err());
+ let err = result.unwrap_err();
+ assert!(
+ err.downcast_ref::<UploadCancelledError>().is_some(),
+ "Error should be UploadCancelledError: {err}",
+ );
+ }
+
+ #[tokio::test]
+ async fn export_error_returns_error_without_cancelled_type() {
+ let uploader = Box::new(MockUploader::new_error());
+ let exporter = CheckpointExporter::new(uploader);
+ let plan = create_test_plan();
+
+ let result = exporter
+ .export_checkpoint_with_plan_cancellable(&plan, None, None)
+ .await;
+
+ assert!(result.is_err());
+ let err = result.unwrap_err();
+ assert!(
+ err.downcast_ref::<UploadCancelledError>().is_none(),
+ "Error should NOT be UploadCancelledError: {err}",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/import.rs b/rust/cohort-stream-processor/src/store/durability/import.rs
new file mode 100644
index 000000000000..87ee45a444f3
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/import.rs
@@ -0,0 +1,788 @@
+use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
+
+use super::error::{DownloadCancelledError, ImportTimeoutError};
+use super::{CheckpointDownloader, CheckpointMetadata, DirCleanupGuard, STORE_TOPIC};
+use crate::observability::metrics::{
+ CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS, CHECKPOINT_IMPORT_DURATION_SECONDS,
+};
+
+use anyhow::{Context, Result};
+use tokio_util::sync::CancellationToken;
+use tracing::{error, info, warn};
+
+#[derive(Debug)]
+pub struct CheckpointImporter {
+ downloader: Box<dyn CheckpointDownloader>,
+ import_attempt_depth: usize,
+ import_timeout: Duration,
+}
+
+impl CheckpointImporter {
+ pub fn new(
+ downloader: Box<dyn CheckpointDownloader>,
+ import_attempt_depth: usize,
+ import_timeout: Duration,
+ ) -> Self {
+ Self {
+ downloader,
+ import_attempt_depth,
+ import_timeout,
+ }
+ }
+
+ /// Lists recent checkpoint metadata.json keys (newest first), tries up to `import_attempt_depth`
+ /// of them lazily (one metadata download at a time), and falls back to the next on failure. On
+ /// success, downloads all tracked files and writes metadata.json into `target_path`.
+ pub async fn import_checkpoint(&self, target_path: &Path) -> Result<PathBuf> {
+ self.import_checkpoint_cancellable(target_path, None).await
+ }
+
+ /// Import with optional cancellation. The whole operation is bounded by `import_timeout` to stay
+ /// below Kafka's max poll interval.
+ pub async fn import_checkpoint_cancellable(
+ &self,
+ target_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<PathBuf> {
+ let start_time = Instant::now();
+
+ match tokio::time::timeout(
+ self.import_timeout,
+ self.import_checkpoint_inner(target_path, cancel_token, start_time),
+ )
+ .await
+ {
+ Ok(result) => result,
+ Err(_elapsed) => {
+ error!(
+ store = STORE_TOPIC,
+ timeout_secs = self.import_timeout.as_secs(),
+ elapsed_secs = start_time.elapsed().as_secs_f64(),
+ "Checkpoint import timed out"
+ );
+ metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "timeout")
+ .record(start_time.elapsed().as_secs_f64());
+ Err(ImportTimeoutError {
+ store: STORE_TOPIC,
+ timeout_secs: self.import_timeout.as_secs(),
+ }
+ .into())
+ }
+ }
+ }
+
+ async fn import_checkpoint_inner(
+ &self,
+ target_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+ start_time: Instant,
+ ) -> Result<PathBuf> {
+ let metadata_keys = match self.downloader.list_recent_checkpoints().await {
+ Ok(keys) => keys,
+ Err(e) => {
+ metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "failed")
+ .record(start_time.elapsed().as_secs_f64());
+ return Err(e).context("listing checkpoint metadata");
+ }
+ };
+
+ if metadata_keys.is_empty() {
+ metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "failed")
+ .record(start_time.elapsed().as_secs_f64());
+ return Err(anyhow::anyhow!(
+ "No checkpoint metadata files found for store {STORE_TOPIC}"
+ ));
+ }
+
+ let metadata_keys: Vec<_> = metadata_keys
+ .into_iter()
+ .take(self.import_attempt_depth)
+ .collect();
+
+ info!(
+ "Found checkpoint metadata keys for store {STORE_TOPIC}, will attempt up to {} (newest first)",
+ metadata_keys.len(),
+ );
+
+ let target_path_tag = target_path.to_string_lossy().to_string();
+
+ for remote_key in &metadata_keys {
+ if let Some(token) = cancel_token {
+ if token.is_cancelled() {
+ warn!(
+ store = STORE_TOPIC,
+ "Checkpoint import cancelled before attempt"
+ );
+ metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "cancelled")
+ .record(start_time.elapsed().as_secs_f64());
+ return Err(DownloadCancelledError {
+ reason: "import cancelled before attempt".to_string(),
+ }
+ .into());
+ }
+ }
+
+ let attempt_start = Instant::now();
+
+ let mut attempt = match self.downloader.download_file(remote_key).await {
+ Ok(content) => match CheckpointMetadata::from_json_bytes(&content) {
+ Ok(metadata) => metadata,
+ Err(e) => {
+ error!("Failed to parse metadata: {remote_key}: {e:#}");
+ continue;
+ }
+ },
+ Err(e) => {
+ error!("Failed to download metadata: {remote_key}: {e:#}");
+ continue;
+ }
+ };
+
+ let attempt_tag = attempt.get_attempt_path();
+
+ if target_path.exists() {
+ info!(
+ store = STORE_TOPIC,
+ path = %target_path.display(),
+ "Removing stale local store before import"
+ );
+ drop(tokio::fs::remove_dir_all(target_path).await);
+ }
+
+ if let Err(e) = tokio::fs::create_dir_all(target_path).await {
+ metrics::histogram!(CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS, "result" => "failed")
+ .record(attempt_start.elapsed().as_secs_f64());
+ metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "failed")
+ .record(start_time.elapsed().as_secs_f64());
+ return Err(e).with_context(|| {
+ format!("Failed to create local directory for import: {target_path_tag}")
+ });
+ }
+
+ let guard = DirCleanupGuard::new(target_path.to_path_buf());
+
+ // A failed file cancels siblings, but the parent token survives so the next attempt can proceed.
+ let attempt_token = cancel_token
+ .map(|parent| parent.child_token())
+ .unwrap_or_default();
+
+ match self
+ .fetch_checkpoint_files_cancellable(&attempt, target_path, Some(&attempt_token))
+ .await
+ {
+ Ok(_) => {
+ let attempt_duration = attempt_start.elapsed().as_secs_f64();
+
+ attempt.write_to_dir(target_path).await.with_context(|| {
+ format!("Failed to write metadata.json to import dir: {target_path_tag}")
+ })?;
+
+ info!(
+ checkpoint = attempt_tag,
+ local_store_path = target_path_tag,
+ original_checkpoint_timestamp = %attempt.attempt_timestamp,
+ attempt_duration_secs = attempt_duration,
+ total_duration_secs = start_time.elapsed().as_secs_f64(),
+ "Successfully imported checkpoint to local directory"
+ );
+ metrics::histogram!(CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS, "result" => "success")
+ .record(attempt_duration);
+ metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "success")
+ .record(start_time.elapsed().as_secs_f64());
+
+ return Ok(guard.defuse());
+ }
+ Err(e) => {
+ let attempt_duration = attempt_start.elapsed().as_secs_f64();
+ metrics::histogram!(CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS, "result" => "failed")
+ .record(attempt_duration);
+ error!(
+ checkpoint = attempt_tag,
+ local_attempt_path = target_path_tag,
+ attempt_duration_secs = attempt_duration,
+ error = ?e,
+ "Failed to import checkpoint files"
+ );
+ continue;
+ }
+ }
+ }
+
+ let err_msg =
+ format!("No usable checkpoints identified in recovery window for store {STORE_TOPIC}");
+ error!(err_msg);
+ metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "failed")
+ .record(start_time.elapsed().as_secs_f64());
+ Err(anyhow::anyhow!(err_msg))
+ }
+
+ pub async fn fetch_checkpoint_files(
+ &self,
+ checkpoint_metadata: &CheckpointMetadata,
+ local_attempt_path: &Path,
+ ) -> Result<()> {
+ self.fetch_checkpoint_files_cancellable(checkpoint_metadata, local_attempt_path, None)
+ .await
+ }
+
+ pub async fn fetch_checkpoint_files_cancellable(
+ &self,
+ checkpoint_metadata: &CheckpointMetadata,
+ local_attempt_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ let target_files = checkpoint_metadata
+ .files
+ .iter()
+ .map(|f| f.remote_filepath.clone())
+ .collect::<Vec<_>>();
+
+ info!(
+ metadata = checkpoint_metadata.get_metadata_filepath(),
+ file_count = checkpoint_metadata.files.len(),
+ "Fetching checkpoint files from metadata tracking list",
+ );
+
+ match self
+ .downloader
+ .download_files_cancellable(&target_files, local_attempt_path, cancel_token)
+ .await
+ {
+ Ok(_) => {
+ info!(
+ "Successfully downloaded {} checkpoint files to: {local_attempt_path:?}",
+ target_files.len()
+ );
+ Ok(())
+ }
+ Err(e) => {
+ error!("Failed to download checkpoint files to: {local_attempt_path:?}: {e:#}");
+ Err(e)
+ }
+ }
+ }
+
+ pub async fn is_available(&self) -> bool {
+ self.downloader.is_available().await
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use async_trait::async_trait;
+ use chrono::{TimeZone, Utc};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Arc;
+ use std::time::Duration;
+ use tempfile::TempDir;
+
+ use crate::store::durability::{STORE_PARTITION, STORE_TOPIC};
+
+ #[derive(Debug)]
+ struct MockDownloader {
+ metadata: CheckpointMetadata,
+ download_count: Arc<AtomicUsize>,
+ }
+
+ impl MockDownloader {
+ fn new(metadata: CheckpointMetadata) -> Self {
+ Self {
+ metadata,
+ download_count: Arc::new(AtomicUsize::new(0)),
+ }
+ }
+ }
+
+ #[async_trait]
+ impl CheckpointDownloader for MockDownloader {
+ async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
+ Ok(vec![self.metadata.get_metadata_filepath()])
+ }
+
+ async fn download_file(&self, _remote_key: &str) -> Result<Vec<u8>> {
+ let json = self.metadata.to_json()?;
+ Ok(json.into_bytes())
+ }
+
+ async fn download_and_store_file_cancellable(
+ &self,
+ _remote_key: &str,
+ local_filepath: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ if let Some(token) = cancel_token {
+ if token.is_cancelled() {
+ return Err(DownloadCancelledError {
+ reason: "test mock".to_string(),
+ }
+ .into());
+ }
+ }
+ tokio::fs::write(local_filepath, b"mock file content").await?;
+ Ok(())
+ }
+
+ async fn download_files_cancellable(
+ &self,
+ remote_keys: &[String],
+ local_base_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ self.download_count.fetch_add(1, Ordering::SeqCst);
+ for key in remote_keys {
+ let filename = key.rsplit('/').next().unwrap_or(key);
+ let local_path = local_base_path.join(filename);
+ self.download_and_store_file_cancellable(key, &local_path, cancel_token)
+ .await?;
+ }
+ Ok(())
+ }
+
+ async fn is_available(&self) -> bool {
+ true
+ }
+ }
+
+ #[derive(Debug)]
+ struct CancellationTestDownloader {
+ checkpoints: Vec<CheckpointMetadata>,
+ }
+
+ impl CancellationTestDownloader {
+ fn new(checkpoints: Vec<CheckpointMetadata>) -> Self {
+ Self { checkpoints }
+ }
+ }
+
+ #[async_trait]
+ impl CheckpointDownloader for CancellationTestDownloader {
+ async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
+ Ok(self
+ .checkpoints
+ .iter()
+ .map(CheckpointMetadata::get_metadata_filepath)
+ .collect())
+ }
+
+ async fn download_file(&self, remote_key: &str) -> Result<Vec<u8>> {
+ for checkpoint in &self.checkpoints {
+ if checkpoint.get_metadata_filepath() == remote_key {
+ return Ok(checkpoint.to_json()?.into_bytes());
+ }
+ }
+ Err(anyhow::anyhow!("Metadata not found: {remote_key}"))
+ }
+
+ async fn download_and_store_file_cancellable(
+ &self,
+ _remote_key: &str,
+ local_filepath: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ if let Some(token) = cancel_token {
+ if token.is_cancelled() {
+ return Err(DownloadCancelledError {
+ reason: "test mock".to_string(),
+ }
+ .into());
+ }
+ }
+
+ tokio::fs::write(local_filepath, b"mock file content").await?;
+ Ok(())
+ }
+
+ async fn download_files_cancellable(
+ &self,
+ remote_keys: &[String],
+ local_base_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ if let Some(token) = cancel_token {
+ if token.is_cancelled() {
+ return Err(DownloadCancelledError {
+ reason: "test mock".to_string(),
+ }
+ .into());
+ }
+ }
+
+ for key in remote_keys {
+ let filename = key.rsplit('/').next().unwrap_or(key);
+ let local_path = local_base_path.join(filename);
+ self.download_and_store_file_cancellable(key, &local_path, cancel_token)
+ .await?;
+ }
+ Ok(())
+ }
+
+ async fn is_available(&self) -> bool {
+ true
+ }
+ }
+
+ fn create_test_metadata(hour: u32) -> CheckpointMetadata {
+ let timestamp = Utc.with_ymd_and_hms(2025, 6, 15, hour, 0, 0).unwrap();
+ let mut metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ timestamp,
+ 12345,
+ 0,
+ 0,
+ );
+ metadata.track_file(
+ format!(
+ "checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/2025-06-15T{hour:02}-00-00Z/000001.sst"
+ ),
+ "checksum1".to_string(),
+ );
+ metadata
+ }
+
+ #[tokio::test]
+ async fn download_files_cancellable_returns_early_when_pre_cancelled() {
+ let tmp_dir = TempDir::new().unwrap();
+ let metadata = create_test_metadata(12);
+ let downloader = CancellationTestDownloader::new(vec![metadata]);
+
+ let token = CancellationToken::new();
+ token.cancel();
+
+ let result = downloader
+ .download_files_cancellable(
+ &["checkpoints/file.sst".to_string()],
+ tmp_dir.path(),
+ Some(&token),
+ )
+ .await;
+
+ assert!(result.is_err());
+ let err = result.unwrap_err();
+ assert!(
+ err.downcast_ref::<DownloadCancelledError>().is_some(),
+ "Error should be DownloadCancelledError: {err}",
+ );
+ }
+
+ #[tokio::test]
+ async fn import_checkpoint_cancellable_returns_early_when_pre_cancelled() {
+ let tmp_dir = TempDir::new().unwrap();
+ let metadata = create_test_metadata(12);
+ let downloader = CancellationTestDownloader::new(vec![metadata]);
+ let importer = CheckpointImporter::new(Box::new(downloader), 3, Duration::from_secs(60));
+
+ let token = CancellationToken::new();
+ token.cancel();
+
+ let result = importer
+ .import_checkpoint_cancellable(&tmp_dir.path().join("store"), Some(&token))
+ .await;
+
+ assert!(result.is_err());
+ let err = result.unwrap_err();
+ assert!(
+ err.downcast_ref::<DownloadCancelledError>().is_some(),
+ "Error should be DownloadCancelledError: {err}",
+ );
+ }
+
+ #[tokio::test]
+ async fn import_materializes_target_path_with_files_and_metadata() {
+ let tmp_dir = TempDir::new().unwrap();
+ let target_path = tmp_dir.path().join("store");
+
+ let attempt_timestamp = Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap();
+ let mut metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ 12345,
+ 0,
+ 0,
+ );
+ metadata.track_file(
+ format!("checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/2025-06-15T12-00-00Z/000001.sst"),
+ "checksum1".to_string(),
+ );
+
+ let downloader = MockDownloader::new(metadata);
+ let importer = CheckpointImporter::new(Box::new(downloader), 3, Duration::from_secs(60));
+
+ let before_import = Utc::now();
+ let result = importer.import_checkpoint(&target_path).await;
+ let after_import = Utc::now();
+
+ assert!(result.is_ok(), "Import should succeed: {:?}", result.err());
+ let import_path = result.unwrap();
+ assert_eq!(import_path, target_path, "Import path should be the target");
+ assert!(import_path.exists(), "Import path should exist");
+
+ let imported_file = import_path.join("000001.sst");
+ assert!(
+ imported_file.exists(),
+ "Imported SST file should exist after successful import"
+ );
+
+ let loaded_metadata = CheckpointMetadata::load_from_dir(&import_path)
+ .await
+ .expect("metadata.json should exist and deserialize");
+ assert_eq!(loaded_metadata.topic, STORE_TOPIC);
+ assert_eq!(loaded_metadata.partition, STORE_PARTITION);
+ assert!(
+ loaded_metadata.updated_at.timestamp_millis() >= before_import.timestamp_millis(),
+ "updated_at should be >= before_import"
+ );
+ assert!(
+ loaded_metadata.updated_at.timestamp_millis() <= after_import.timestamp_millis(),
+ "updated_at should be <= after_import"
+ );
+ }
+
+ #[derive(Debug)]
+ struct FailingDownloader {
+ metadata: CheckpointMetadata,
+ }
+
+ impl FailingDownloader {
+ fn new(metadata: CheckpointMetadata) -> Self {
+ Self { metadata }
+ }
+ }
+
+ #[async_trait]
+ impl CheckpointDownloader for FailingDownloader {
+ async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
+ Ok(vec![self.metadata.get_metadata_filepath()])
+ }
+
+ async fn download_file(&self, _remote_key: &str) -> Result<Vec<u8>> {
+ let json = self.metadata.to_json()?;
+ Ok(json.into_bytes())
+ }
+
+ async fn download_and_store_file_cancellable(
+ &self,
+ _remote_key: &str,
+ _local_filepath: &Path,
+ _cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ Err(anyhow::anyhow!("Simulated download failure"))
+ }
+
+ async fn download_files_cancellable(
+ &self,
+ _remote_keys: &[String],
+ _local_base_path: &Path,
+ _cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ Err(anyhow::anyhow!("Simulated download failure"))
+ }
+
+ async fn is_available(&self) -> bool {
+ true
+ }
+ }
+
+ #[tokio::test]
+ async fn cleanup_guard_removes_directory_on_failure() {
+ let tmp_dir = TempDir::new().unwrap();
+ let target_path = tmp_dir.path().join("store");
+
+ let attempt_timestamp = Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap();
+ let mut metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ 12345,
+ 0,
+ 0,
+ );
+ metadata.track_file(
+ format!("checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/2025-06-15T12-00-00Z/000001.sst"),
+ "checksum1".to_string(),
+ );
+
+ let downloader = FailingDownloader::new(metadata);
+ let importer = CheckpointImporter::new(
+ Box::new(downloader),
+ 1, // Only 1 attempt so we fail fast
+ Duration::from_secs(60),
+ );
+
+ let result = importer.import_checkpoint(&target_path).await;
+ assert!(result.is_err(), "Import should fail");
+
+ assert!(
+ !target_path.exists(),
+ "Cleanup guard should have removed the store directory on failure"
+ );
+ }
+
+ #[test]
+ fn cleanup_guard_defuse_prevents_cleanup() {
+ let tmp_dir = TempDir::new().unwrap();
+ let test_path = tmp_dir.path().join("test_dir");
+ std::fs::create_dir_all(&test_path).unwrap();
+ let test_file = test_path.join("test_file.txt");
+ std::fs::write(&test_file, b"test content").unwrap();
+
+ let guard = DirCleanupGuard::new(test_path.clone());
+ let returned_path = guard.defuse();
+
+ assert_eq!(returned_path, test_path);
+ assert!(test_path.exists(), "Directory should exist after defuse");
+ assert!(test_file.exists(), "File should exist after defuse");
+ }
+
+ #[test]
+ fn cleanup_guard_removes_directory_on_drop() {
+ let tmp_dir = TempDir::new().unwrap();
+ let test_path = tmp_dir.path().join("test_dir");
+ std::fs::create_dir_all(&test_path).unwrap();
+ let test_file = test_path.join("test_file.txt");
+ std::fs::write(&test_file, b"test content").unwrap();
+
+ {
+ let _guard = DirCleanupGuard::new(test_path.clone());
+ }
+
+ assert!(
+ !test_path.exists(),
+ "Directory should be removed after guard drops"
+ );
+ }
+
+ #[derive(Debug)]
+ struct TrackingDownloader {
+ checkpoints: Vec<CheckpointMetadata>,
+ metadata_download_count: Arc<AtomicUsize>,
+ file_download_fail_count: usize,
+ file_download_attempts: Arc<AtomicUsize>,
+ }
+
+ impl TrackingDownloader {
+ fn new(checkpoints: Vec<CheckpointMetadata>, file_download_fail_count: usize) -> Self {
+ Self {
+ checkpoints,
+ metadata_download_count: Arc::new(AtomicUsize::new(0)),
+ file_download_fail_count,
+ file_download_attempts: Arc::new(AtomicUsize::new(0)),
+ }
+ }
+ }
+
+ #[async_trait]
+ impl CheckpointDownloader for TrackingDownloader {
+ async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
+ Ok(self
+ .checkpoints
+ .iter()
+ .map(CheckpointMetadata::get_metadata_filepath)
+ .collect())
+ }
+
+ async fn download_file(&self, remote_key: &str) -> Result<Vec<u8>> {
+ self.metadata_download_count.fetch_add(1, Ordering::SeqCst);
+ for checkpoint in &self.checkpoints {
+ if checkpoint.get_metadata_filepath() == remote_key {
+ return Ok(checkpoint.to_json()?.into_bytes());
+ }
+ }
+ Err(anyhow::anyhow!("Metadata not found: {remote_key}"))
+ }
+
+ async fn download_and_store_file_cancellable(
+ &self,
+ _remote_key: &str,
+ local_filepath: &Path,
+ _cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ tokio::fs::write(local_filepath, b"mock file content").await?;
+ Ok(())
+ }
+
+ async fn download_files_cancellable(
+ &self,
+ remote_keys: &[String],
+ local_base_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ let attempt = self.file_download_attempts.fetch_add(1, Ordering::SeqCst);
+ if attempt < self.file_download_fail_count {
+ return Err(anyhow::anyhow!("Simulated file download failure"));
+ }
+ for key in remote_keys {
+ let filename = key.rsplit('/').next().unwrap_or(key);
+ let local_path = local_base_path.join(filename);
+ self.download_and_store_file_cancellable(key, &local_path, cancel_token)
+ .await?;
+ }
+ Ok(())
+ }
+
+ async fn is_available(&self) -> bool {
+ true
+ }
+ }
+
+ #[tokio::test]
+ async fn lazy_metadata_download_only_fetches_needed() {
+ let tmp_dir = TempDir::new().unwrap();
+
+ let checkpoints = vec![
+ create_test_metadata(14),
+ create_test_metadata(13),
+ create_test_metadata(12),
+ ];
+
+ let tracker = TrackingDownloader::new(checkpoints, 0);
+ let download_count = Arc::clone(&tracker.metadata_download_count);
+
+ let importer = CheckpointImporter::new(Box::new(tracker), 3, Duration::from_secs(60));
+
+ let result = importer
+ .import_checkpoint(&tmp_dir.path().join("store"))
+ .await;
+
+ assert!(result.is_ok(), "Import should succeed: {:?}", result.err());
+ assert_eq!(
+ download_count.load(Ordering::SeqCst),
+ 1,
+ "Only the newest metadata.json should be downloaded when the first attempt succeeds"
+ );
+ }
+
+ #[tokio::test]
+ async fn lazy_metadata_download_fallback_downloads_incrementally() {
+ let tmp_dir = TempDir::new().unwrap();
+
+ let checkpoints = vec![
+ create_test_metadata(14),
+ create_test_metadata(13),
+ create_test_metadata(12),
+ ];
+
+ let tracker = TrackingDownloader::new(checkpoints, 2);
+ let metadata_count = Arc::clone(&tracker.metadata_download_count);
+
+ let importer = CheckpointImporter::new(Box::new(tracker), 3, Duration::from_secs(60));
+
+ let result = importer
+ .import_checkpoint(&tmp_dir.path().join("store"))
+ .await;
+
+ assert!(
+ result.is_ok(),
+ "Import should succeed on 3rd attempt: {:?}",
+ result.err()
+ );
+ assert_eq!(
+ metadata_count.load(Ordering::SeqCst),
+ 3,
+ "Should download exactly 3 metadata files (2 failed attempts + 1 success)"
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/manifest.rs b/rust/cohort-stream-processor/src/store/durability/manifest.rs
new file mode 100644
index 000000000000..6c9fcc92d770
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/manifest.rs
@@ -0,0 +1,293 @@
+//! The multi-partition offset manifest for the disaster-recovery layer.
+//!
+//! A RocksDB `Checkpoint` is a whole-DB snapshot, so one checkpoint freezes every partition's state
+//! at once. On restore the DB content is materialized, but Kafka still needs to know where to resume
+//! each topic-partition. The processor keeps one DB per process spanning up to 64 partitions across
+//! four topics, so the resume positions live here, in a sibling `offsets.json` written alongside the
+//! checkpoint.
+//!
+//! [`capture`](OffsetManifest::capture) records [`OffsetTracker::committed_offset`] (the offset Kafka
+//! last acked), not the processed position, which can outrun the fsync'd state under the async WAL.
+//! The committed offset is `<= durable`: the events consumer fsyncs the WAL before every offset
+//! commit, so seeking a restored DB to its committed offset re-folds the gap `[committed, processed]`
+//! idempotently via per-key `AppliedOffsets` — no loss, no double-count.
+
+use std::collections::BTreeMap;
+use std::path::Path;
+
+use anyhow::{Context, Result};
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+
+use crate::partitions::OffsetTracker;
+
+/// Filename of the offset manifest, written as a sibling of the RocksDB checkpoint files and tracked
+/// by the planner like any other file, so it rides the S3 upload/restore.
+pub const MANIFEST_FILENAME: &str = "offsets.json";
+
+/// Current on-disk shape version, bumped on any structural change to [`OffsetManifest`]. Decode is
+/// strict: a manifest whose `version` does not match is rejected, so a format skew surfaces as a
+/// restore failure (fall through to S3 / cold-start) instead of a mis-seek.
+pub const MANIFEST_VERSION: u32 = 1;
+
+/// The per-process resume positions captured alongside a whole-DB checkpoint: for each topic, the
+/// next offset to consume on each owned partition.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct OffsetManifest {
+ /// On-disk shape version; see [`MANIFEST_VERSION`].
+ pub version: u32,
+ /// When this manifest was captured (the checkpoint's logical instant).
+ pub captured_at: DateTime<Utc>,
+ /// `topic -> { partition -> next-offset-to-consume }`. A `BTreeMap` keeps the serialized JSON
+ /// deterministic, so the SHA256 the planner computes over non-SST files stays stable across
+ /// captures with identical content.
+ pub topics: BTreeMap<String, BTreeMap<i32, i64>>,
+}
+
+impl OffsetManifest {
+ /// Capture the committed positions of every owned partition across the supplied trackers.
+ ///
+ /// For each `(topic, tracker)` and each partition in `owned`, records
+ /// `topics[topic][partition] = committed_offset` only when the tracker has a committed offset for
+ /// that partition. A partition the tracker has never seen (an idle follower, or a topic that
+ /// never produced to this pod) is absent — inert on restore (nothing to seek).
+ pub fn capture(owned: &[i32], trackers: &[(&str, &OffsetTracker)]) -> Self {
+ let mut topics: BTreeMap<String, BTreeMap<i32, i64>> = BTreeMap::new();
+ for (topic, tracker) in trackers {
+ let mut per_partition: BTreeMap<i32, i64> = BTreeMap::new();
+ for &partition in owned {
+ if let Some(offset) = tracker.committed_offset(partition) {
+ per_partition.insert(partition, offset);
+ }
+ }
+ topics.insert((*topic).to_string(), per_partition);
+ }
+ Self {
+ version: MANIFEST_VERSION,
+ captured_at: Utc::now(),
+ topics,
+ }
+ }
+
+ /// The next-offset-to-consume for one `(topic, partition)`, if present.
+ pub fn offset_for(&self, topic: &str, partition: i32) -> Option<i64> {
+ self.topics
+ .get(topic)
+ .and_then(|partitions| partitions.get(&partition).copied())
+ }
+
+ /// Load the manifest from `<dir>/offsets.json`. Strict-decodes: a missing file, malformed JSON,
+ /// or a `version` other than [`MANIFEST_VERSION`] is an error (the caller treats the source as
+ /// unusable and falls through).
+ pub fn load_from_dir(dir: &Path) -> Result<Self> {
+ let path = dir.join(MANIFEST_FILENAME);
+ let bytes = std::fs::read(&path)
+ .with_context(|| format!("reading offset manifest from {path:?}"))?;
+ let manifest: Self = serde_json::from_slice(&bytes)
+ .with_context(|| format!("parsing offset manifest from {path:?}"))?;
+ if manifest.version != MANIFEST_VERSION {
+ anyhow::bail!(
+ "offset manifest at {path:?} has version {} but this build expects {MANIFEST_VERSION}",
+ manifest.version,
+ );
+ }
+ Ok(manifest)
+ }
+
+ /// Write the manifest to `<dir>/offsets.json` atomically (tmp file + rename) so a concurrent
+ /// reader never observes a torn file.
+ pub fn write_to_dir(&self, dir: &Path) -> Result<()> {
+ let json = serde_json::to_vec_pretty(self).context("serializing offset manifest")?;
+ let path = dir.join(MANIFEST_FILENAME);
+ let tmp_path = dir.join(".offsets.json.tmp");
+ if let Err(e) = std::fs::write(&tmp_path, &json) {
+ // Best-effort cleanup of the partial tmp file before propagating the write error.
+ drop(std::fs::remove_file(&tmp_path));
+ return Err(e).with_context(|| format!("writing temp offset manifest to {tmp_path:?}"));
+ }
+ // rename(2) atomically replaces the destination on Unix.
+ std::fs::rename(&tmp_path, &path)
+ .with_context(|| format!("renaming temp offset manifest to {path:?}"))?;
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::partitions::MarkOutcome;
+ use tempfile::TempDir;
+
+ fn capture_one(owned: &[i32], topic: &str, tracker: &OffsetTracker) -> OffsetManifest {
+ OffsetManifest::capture(owned, &[(topic, tracker)])
+ }
+
+ #[test]
+ fn manifest_round_trips_through_a_dir() {
+ let dir = TempDir::new().unwrap();
+ let mut topics = BTreeMap::new();
+ topics.insert(
+ "cohort_stream_events".to_string(),
+ BTreeMap::from([(0, 100), (3, 250)]),
+ );
+ topics.insert("person_merge_events".to_string(), BTreeMap::from([(0, 7)]));
+ let manifest = OffsetManifest {
+ version: MANIFEST_VERSION,
+ captured_at: Utc::now(),
+ topics,
+ };
+
+ manifest.write_to_dir(dir.path()).unwrap();
+ let loaded = OffsetManifest::load_from_dir(dir.path()).unwrap();
+ assert_eq!(loaded, manifest);
+ assert_eq!(loaded.offset_for("cohort_stream_events", 3), Some(250));
+ assert_eq!(loaded.offset_for("cohort_stream_events", 1), None);
+ assert_eq!(loaded.offset_for("person_merge_events", 0), Some(7));
+ }
+
+ #[test]
+ fn capture_uses_committed_not_committable() {
+ // `capture` must record the committed (durable) offset, not the processed one — recording
+ // processed could seek past un-fsynced state on restore and silently skip events.
+ let tracker = OffsetTracker::new();
+ let partition = 5;
+ tracker.mark_dispatched(partition, 1000);
+ assert_eq!(
+ tracker.mark_processed(partition, 1000),
+ MarkOutcome::WithinDispatch,
+ );
+ tracker.mark_committed(partition, 400);
+
+ let manifest = capture_one(&[partition], "cohort_stream_events", &tracker);
+ assert_eq!(
+ manifest.offset_for("cohort_stream_events", partition),
+ Some(400),
+ "capture must record the committed offset (400), not the processed one (1000)",
+ );
+ }
+
+ #[test]
+ fn capture_omits_an_absent_follower() {
+ let owned = [0, 1, 2];
+ let idle = OffsetTracker::new();
+ let manifest = capture_one(&owned, "person_merge_events", &idle);
+ let inner = manifest
+ .topics
+ .get("person_merge_events")
+ .expect("topic recorded even when empty");
+ assert!(
+ inner.is_empty(),
+ "an idle follower's topic maps to an empty inner map",
+ );
+ for partition in owned {
+ assert_eq!(manifest.offset_for("person_merge_events", partition), None);
+ }
+ }
+
+ #[test]
+ fn capture_records_present_follower_offsets() {
+ let owned = [3, 7];
+ let merge = OffsetTracker::new();
+ let transfer = OffsetTracker::new();
+ let cascade = OffsetTracker::new();
+ for (tracker, base) in [(&merge, 10), (&transfer, 20), (&cascade, 30)] {
+ for (partition, bump) in [(3, 1), (7, 2)] {
+ let offset = base + bump;
+ tracker.mark_dispatched(partition, offset);
+ let _ = tracker.mark_processed(partition, offset);
+ tracker.mark_committed(partition, offset);
+ }
+ }
+
+ let manifest = OffsetManifest::capture(
+ &owned,
+ &[
+ ("person_merge_events", &merge),
+ ("cohort_merge_state_transfer", &transfer),
+ ("cohort_cascade_events", &cascade),
+ ],
+ );
+
+ for (topic, base) in [
+ ("person_merge_events", 10),
+ ("cohort_merge_state_transfer", 20),
+ ("cohort_cascade_events", 30),
+ ] {
+ let inner = manifest.topics.get(topic).expect("follower topic recorded");
+ assert!(!inner.is_empty(), "{topic} follower map must be non-empty");
+ assert_eq!(inner.len(), 2, "{topic} records both owned partitions");
+ assert_eq!(manifest.offset_for(topic, 3), Some(base + 1));
+ assert_eq!(manifest.offset_for(topic, 7), Some(base + 2));
+ }
+ }
+
+ #[test]
+ fn capture_records_only_owned_partitions() {
+ // Partitions committed in the tracker but not in `owned` must not appear in the manifest.
+ let tracker = OffsetTracker::new();
+ for partition in [0, 1, 9] {
+ tracker.mark_dispatched(partition, 50);
+ let _ = tracker.mark_processed(partition, 50);
+ tracker.mark_committed(partition, 50);
+ }
+ let manifest = capture_one(&[0, 1], "cohort_stream_events", &tracker);
+ let inner = manifest.topics.get("cohort_stream_events").unwrap();
+ assert_eq!(inner.len(), 2);
+ assert_eq!(manifest.offset_for("cohort_stream_events", 0), Some(50));
+ assert_eq!(manifest.offset_for("cohort_stream_events", 1), Some(50));
+ assert_eq!(manifest.offset_for("cohort_stream_events", 9), None);
+ }
+
+ #[test]
+ fn capture_spans_multiple_topics() {
+ let events = OffsetTracker::new();
+ events.mark_dispatched(0, 100);
+ let _ = events.mark_processed(0, 100);
+ events.mark_committed(0, 100);
+
+ let merges = OffsetTracker::new();
+ merges.mark_dispatched(0, 5);
+ let _ = merges.mark_processed(0, 5);
+ merges.mark_committed(0, 5);
+
+ let manifest = OffsetManifest::capture(
+ &[0],
+ &[
+ ("cohort_stream_events", &events),
+ ("person_merge_events", &merges),
+ ],
+ );
+ assert_eq!(manifest.offset_for("cohort_stream_events", 0), Some(100));
+ assert_eq!(manifest.offset_for("person_merge_events", 0), Some(5));
+ }
+
+ #[test]
+ fn a_version_mismatch_fails_to_decode() {
+ let dir = TempDir::new().unwrap();
+ let json = serde_json::json!({
+ "version": MANIFEST_VERSION + 1,
+ "captured_at": Utc::now(),
+ "topics": { "cohort_stream_events": { "0": 100 } },
+ });
+ std::fs::write(
+ dir.path().join(MANIFEST_FILENAME),
+ serde_json::to_vec(&json).unwrap(),
+ )
+ .unwrap();
+
+ let err = OffsetManifest::load_from_dir(dir.path()).unwrap_err();
+ assert!(
+ err.to_string().contains("version"),
+ "version-mismatch error should mention version: {err}",
+ );
+ }
+
+ #[test]
+ fn a_missing_manifest_fails_to_load() {
+ let dir = TempDir::new().unwrap();
+ assert!(
+ OffsetManifest::load_from_dir(dir.path()).is_err(),
+ "load on a dir with no offsets.json must error",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/metadata.rs b/rust/cohort-stream-processor/src/store/durability/metadata.rs
new file mode 100644
index 000000000000..2f05921cd136
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/metadata.rs
@@ -0,0 +1,567 @@
+//! Checkpoint metadata: the per-attempt file registry, plus S3-key construction.
+//!
+//! `topic`/`partition` are pinned to the fixed store identity (`STORE_TOPIC`/`STORE_PARTITION`); the
+//! offset scalars are written as 0 and never read, since offset positions live in a separate manifest.
+
+use std::path::{Path, PathBuf};
+use std::sync::OnceLock;
+
+use anyhow::{Context, Result};
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use tracing::debug;
+
+use super::{STORE_PARTITION, STORE_TOPIC};
+
+/// Deterministic 8-hex-char prefix for spreading S3 object keys across internal partitions.
+/// Applied ONLY to checkpoint object file paths, NEVER to metadata.json paths.
+pub fn hash_prefix_for_partition(topic: &str, partition: i32) -> String {
+ let input = format!("{topic}/{partition}");
+ let hash = Sha256::digest(input.as_bytes());
+ format!(
+ "{:02x}{:02x}{:02x}{:02x}",
+ hash[0], hash[1], hash[2], hash[3]
+ )
+}
+
+/// The single, process-wide S3 hash prefix, derived from the fixed store identity. One DB holds all
+/// partitions, so there is exactly one stable prefix. Computed once and cached.
+pub fn store_hash_prefix() -> &'static str {
+ static PREFIX: OnceLock<String> = OnceLock::new();
+ PREFIX.get_or_init(|| hash_prefix_for_partition(STORE_TOPIC, STORE_PARTITION))
+}
+
+/// Build the store path `<base_path>/<topic>/<partition>`. Slashes in the topic are replaced with
+/// `_` to guarantee a two-level directory structure.
+fn format_store_path(base_path: &Path, topic: &str, partition: i32) -> PathBuf {
+ base_path
+ .join(topic.replace('/', "_"))
+ .join(partition.to_string())
+}
+
+/// Filename of the checkpoint metadata JSON file. Used in remote checkpoint attempt directories (S3)
+/// and in local store directories (see `write_to_dir` / `load_from_dir`).
+pub const METADATA_FILENAME: &str = "metadata.json";
+/// Hour-scoped prefix format used to filter the S3 listing window.
+pub const DATE_PLUS_HOURS_ONLY_FORMAT: &str = "%Y-%m-%d-%H";
+/// Checkpoint ID format: human-readable S3 path element derived from `attempt_timestamp`.
+pub const TIMESTAMP_FORMAT: &str = "%Y-%m-%dT%H-%M-%SZ";
+
+/// Metadata about a checkpoint. Can be written to and loaded from a local store directory via
+/// `write_to_dir` / `load_from_dir` (e.g. after import or for round-trip tests).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CheckpointMetadata {
+ /// Checkpoint ID (RFC3339-ish timestamp, e.g., "2025-10-14T16-00-05Z")
+ pub id: String,
+ /// Topic name (fixed to `STORE_TOPIC`).
+ pub topic: String,
+ /// Partition number (fixed to `STORE_PARTITION`).
+ pub partition: i32,
+ /// Timestamp of this checkpoint's attempt
+ pub attempt_timestamp: DateTime<Utc>,
+ /// RocksDB sequence number at checkpoint time
+ pub sequence: u64,
+ /// Unused: written as 0 and never read (offsets live in a separate manifest).
+ pub consumer_offset: i64,
+ /// Unused: written as 0 and never read.
+ pub producer_offset: i64,
+ /// When this metadata was last written (creation or local write). Serde default when
+ /// deserializing metadata.json that lacks this field (backward compat).
+ #[serde(default = "Utc::now")]
+ pub updated_at: DateTime<Utc>,
+ /// Registry of file metadata for all remotely-stored files required to reconstitute a local
+ /// RocksDB store across all relevant checkpoint attempts.
+ pub files: Vec<CheckpointFile>,
+}
+
+impl CheckpointMetadata {
+ pub fn new(
+ topic: String,
+ partition: i32,
+ attempt_timestamp: DateTime<Utc>,
+ sequence: u64,
+ consumer_offset: i64,
+ producer_offset: i64,
+ ) -> Self {
+ Self {
+ id: CheckpointMetadata::generate_id(attempt_timestamp),
+ topic,
+ partition,
+ attempt_timestamp,
+ sequence,
+ consumer_offset,
+ producer_offset,
+ updated_at: attempt_timestamp,
+ files: Vec::new(),
+ }
+ }
+
+ pub fn generate_id(attempt_timestamp: DateTime<Utc>) -> String {
+ attempt_timestamp.format(TIMESTAMP_FORMAT).to_string()
+ }
+
+ pub fn from_json_bytes(json: &[u8]) -> Result<Self> {
+ let metadata: Self =
+ serde_json::from_slice(json).context("In CheckpointMetadata::from_json")?;
+ Ok(metadata)
+ }
+
+ pub async fn load_from_dir(dir: &Path) -> Result<Self> {
+ let path = dir.join(METADATA_FILENAME);
+ let json = tokio::fs::read_to_string(&path)
+ .await
+ .with_context(|| format!("Failed to read metadata from: {path:?}"))?;
+ let metadata: Self = serde_json::from_str(&json)
+ .with_context(|| format!("Failed to parse metadata from: {path:?}"))?;
+ Ok(metadata)
+ }
+
+ /// Write metadata.json atomically (tmp file + rename) to prevent torn reads.
+ pub async fn write_to_dir(&mut self, dir: &Path) -> Result<()> {
+ self.updated_at = Utc::now();
+ let json = self.to_json().context("In write_to_dir")?;
+ let path = dir.join(METADATA_FILENAME);
+ let tmp_path = dir.join(".metadata.json.tmp");
+ if let Err(e) = tokio::fs::write(&tmp_path, json).await {
+ drop(tokio::fs::remove_file(&tmp_path).await);
+ return Err(e)
+ .with_context(|| format!("Failed to write temp metadata to: {tmp_path:?}"));
+ }
+ tokio::fs::rename(&tmp_path, &path)
+ .await
+ .with_context(|| format!("Failed to rename temp metadata to: {path:?}"))?;
+ debug!("Saved checkpoint metadata to {:?}", path);
+ Ok(())
+ }
+
+ pub fn track_file(&mut self, remote_filepath: String, checksum: String) {
+ self.files
+ .push(CheckpointFile::new(remote_filepath, checksum));
+ }
+
+ /// Returns `<topic>/<partition>/<checkpoint_id>`, excluding bucket namespace and local base path.
+ pub fn get_attempt_path(&self) -> String {
+ format!("{}/{}/{}", self.topic, self.partition, self.id)
+ }
+
+ pub fn get_store_path(&self, local_store_base_path: &Path) -> PathBuf {
+ format_store_path(local_store_base_path, &self.topic, self.partition)
+ }
+
+ pub fn get_metadata_filepath(&self) -> String {
+ format!("{}/{}", self.get_attempt_path(), METADATA_FILENAME)
+ }
+
+ pub fn to_json(&self) -> Result<String> {
+ serde_json::to_string_pretty(self).context("Failed to serialize checkpoint metadata")
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct CheckpointInfo {
+ pub metadata: CheckpointMetadata,
+ /// App-level S3 bucket namespace for all checkpoint attempts.
+ pub s3_key_prefix: String,
+ /// When `Some`, object file keys include this prefix; metadata.json keys never do.
+ pub hash_prefix: Option<String>,
+}
+
+impl CheckpointInfo {
+ pub fn new(
+ metadata: CheckpointMetadata,
+ s3_key_prefix: String,
+ hash_prefix: Option<String>,
+ ) -> Self {
+ Self {
+ metadata,
+ s3_key_prefix,
+ hash_prefix,
+ }
+ }
+
+ pub fn get_metadata_key(&self) -> String {
+ match &self.hash_prefix {
+ Some(h) => format!(
+ "{}/{}/{}",
+ h,
+ self.s3_key_prefix,
+ self.metadata.get_metadata_filepath()
+ ),
+ None => format!(
+ "{}/{}",
+ self.s3_key_prefix,
+ self.metadata.get_metadata_filepath()
+ ),
+ }
+ }
+
+ /// Fully-qualified remote path for a file in this attempt (`relative_file_path` is filename only).
+ /// Files from prior attempts already carry their full remote path and should not go through this.
+ pub fn get_file_key(&self, relative_file_path: &str) -> String {
+ match &self.hash_prefix {
+ Some(h) => format!(
+ "{}/{}/{}/{}",
+ h,
+ self.s3_key_prefix,
+ self.metadata.get_attempt_path(),
+ relative_file_path
+ ),
+ None => format!("{}/{}", self.get_remote_attempt_path(), relative_file_path),
+ }
+ }
+
+ pub fn get_remote_attempt_path(&self) -> String {
+ match &self.hash_prefix {
+ Some(h) => format!(
+ "{}/{}/{}",
+ h,
+ self.s3_key_prefix,
+ self.metadata.get_attempt_path(),
+ ),
+ None => format!(
+ "{}/{}",
+ self.s3_key_prefix,
+ self.metadata.get_attempt_path(),
+ ),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CheckpointFile {
+ /// Fully-qualified remote path from the original upload. Object files:
+ /// `<hash>/<namespace>/<topic>/<partition>/<id>/<filename>`. The importer GETs using this path.
+ pub remote_filepath: String,
+
+ /// SHA256 of the file contents. Planning compares it against a same-named file from the previous
+ /// attempt to decide reuse vs re-upload. Computed for mutable (non-SST) files only; SST files are
+ /// immutable, so their checksum is left empty.
+ pub checksum: String,
+}
+
+impl CheckpointFile {
+ pub fn new(remote_filepath: String, checksum: String) -> Self {
+ Self {
+ remote_filepath,
+ checksum,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ #[tokio::test]
+ async fn checkpoint_metadata_creation() {
+ let attempt_timestamp = Utc::now();
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ 1234567890,
+ 0,
+ 0,
+ );
+
+ assert_eq!(
+ metadata.id,
+ CheckpointMetadata::generate_id(attempt_timestamp)
+ );
+ assert_eq!(metadata.topic, STORE_TOPIC);
+ assert_eq!(metadata.partition, STORE_PARTITION);
+ assert_eq!(metadata.sequence, 1234567890);
+ assert_eq!(metadata.files.len(), 0);
+ }
+
+ #[tokio::test]
+ async fn write_to_dir_creates_metadata_json_file() {
+ let dir = TempDir::new().unwrap();
+ let mut metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ Utc::now(),
+ 1,
+ 0,
+ 0,
+ );
+ metadata.write_to_dir(dir.path()).await.unwrap();
+ let path = dir.path().join(METADATA_FILENAME);
+ assert!(
+ path.exists(),
+ "write_to_dir should create {METADATA_FILENAME} in dir",
+ );
+ }
+
+ #[tokio::test]
+ async fn load_from_dir_fails_when_metadata_missing() {
+ let dir = TempDir::new().unwrap();
+ let result = CheckpointMetadata::load_from_dir(dir.path()).await;
+ assert!(result.is_err(), "load_from_dir on empty dir should fail");
+ }
+
+ #[tokio::test]
+ async fn write_to_dir_and_load_from_dir_round_trip() {
+ let dir = TempDir::new().unwrap();
+ let bucket_namespace = "checkpoints";
+ let attempt_timestamp = Utc::now();
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+
+ let mut metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ 9876543210,
+ 0,
+ 0,
+ );
+ metadata.track_file(
+ format!(
+ "{}/{}/000001.sst",
+ bucket_namespace,
+ metadata.get_attempt_path()
+ ),
+ "checksum1".to_string(),
+ );
+
+ metadata.write_to_dir(dir.path()).await.unwrap();
+
+ let loaded = CheckpointMetadata::load_from_dir(dir.path()).await.unwrap();
+
+ assert_eq!(loaded.id, metadata.id);
+ assert_eq!(loaded.topic, metadata.topic);
+ assert_eq!(loaded.partition, metadata.partition);
+ assert_eq!(loaded.attempt_timestamp, metadata.attempt_timestamp);
+ assert_eq!(loaded.sequence, metadata.sequence);
+ assert_eq!(loaded.files.len(), 1);
+ let expected_remote_file_path = format!(
+ "{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/000001.sst"
+ );
+ assert_eq!(loaded.files[0].remote_filepath, expected_remote_file_path);
+ assert_eq!(loaded.files[0].checksum, "checksum1");
+
+ assert!(
+ (loaded.updated_at - Utc::now()).num_seconds().abs() < 2,
+ "updated_at should be approximately now after write_to_dir, got {:?}",
+ loaded.updated_at
+ );
+ }
+
+ #[test]
+ fn updated_at_set_on_creation() {
+ let attempt_timestamp = Utc::now();
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ 1,
+ 0,
+ 0,
+ );
+ assert_eq!(metadata.updated_at, attempt_timestamp);
+ }
+
+ #[test]
+ fn updated_at_serde_default() {
+ let json = r#"{
+ "id": "2025-06-15T12-00-00Z",
+ "topic": "cohort_stream_state",
+ "partition": 0,
+ "attempt_timestamp": "2025-06-15T12:00:00Z",
+ "sequence": 1,
+ "consumer_offset": 0,
+ "producer_offset": 0,
+ "files": []
+ }"#;
+ let metadata: CheckpointMetadata =
+ serde_json::from_str(json).expect("deserialize without updated_at should succeed");
+ assert_eq!(metadata.topic, "cohort_stream_state");
+ assert_eq!(metadata.partition, 0);
+ assert!(metadata.updated_at.timestamp() > 0);
+ }
+
+ #[test]
+ fn get_attempt_path_formats_topic_partition_id() {
+ let attempt_timestamp = Utc::now();
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ 1234567890,
+ 0,
+ 0,
+ );
+
+ let prefix = metadata.get_attempt_path();
+ let expected_attempt_path = format!("{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}");
+ assert_eq!(prefix, expected_attempt_path);
+ }
+
+ #[test]
+ fn checkpoint_info_keys_without_hash_prefix() {
+ let attempt_timestamp = Utc::now();
+ let bucket_namespace = "checkpoints";
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ 1234567890,
+ 0,
+ 0,
+ );
+
+ let info = CheckpointInfo::new(metadata, bucket_namespace.to_string(), None);
+
+ assert_eq!(
+ info.get_metadata_key(),
+ format!(
+ "{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/{METADATA_FILENAME}"
+ )
+ );
+
+ let local_file_relative_path = "000001.sst";
+ assert_eq!(
+ info.get_file_key(local_file_relative_path),
+ format!(
+ "{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/000001.sst"
+ )
+ );
+ }
+
+ #[test]
+ fn hash_prefix_deterministic() {
+ let h1 = hash_prefix_for_partition("events", 0);
+ let h2 = hash_prefix_for_partition("events", 0);
+ assert_eq!(h1, h2);
+ }
+
+ #[test]
+ fn hash_prefix_different_partitions() {
+ let h0 = hash_prefix_for_partition("events", 0);
+ let h1 = hash_prefix_for_partition("events", 1);
+ let h2 = hash_prefix_for_partition("other-topic", 0);
+ assert_ne!(h0, h1);
+ assert_ne!(h0, h2);
+ assert_ne!(h1, h2);
+ }
+
+ #[test]
+ fn hash_prefix_format() {
+ let h = hash_prefix_for_partition("t", 0);
+ assert_eq!(h.len(), 8);
+ assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
+ }
+
+ #[test]
+ fn store_hash_prefix_is_the_single_db_identity_hash() {
+ assert_eq!(
+ store_hash_prefix(),
+ hash_prefix_for_partition(STORE_TOPIC, STORE_PARTITION)
+ );
+ }
+
+ #[test]
+ fn checkpoint_info_with_hash_prefix() {
+ let attempt_timestamp = Utc::now();
+ let bucket_namespace = "checkpoints";
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ 1234567890,
+ 0,
+ 0,
+ );
+ let hash = store_hash_prefix().to_string();
+ let info = CheckpointInfo::new(metadata, bucket_namespace.to_string(), Some(hash.clone()));
+
+ let meta_key = info.get_metadata_key();
+ assert!(meta_key.contains(&hash));
+ assert_eq!(
+ meta_key,
+ format!(
+ "{hash}/{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/{METADATA_FILENAME}"
+ )
+ );
+
+ let file_key = info.get_file_key("000001.sst");
+ assert!(file_key.contains(&hash));
+ assert_eq!(
+ file_key,
+ format!(
+ "{hash}/{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/000001.sst"
+ )
+ );
+ }
+
+ #[test]
+ fn metadata_filepath_format() {
+ let attempt_timestamp = Utc::now();
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ 1234567890,
+ 0,
+ 0,
+ );
+
+ let expected_metadata_filepath =
+ format!("{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/{METADATA_FILENAME}");
+ assert_eq!(metadata.get_metadata_filepath(), expected_metadata_filepath);
+ }
+
+ #[test]
+ fn generate_id_format() {
+ let attempt_timestamp = Utc::now();
+ let id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let expected_id = attempt_timestamp.format(TIMESTAMP_FORMAT).to_string();
+
+ assert!(id.contains('T'));
+ assert!(id.ends_with('Z'));
+ assert!(id.len() > 15);
+ assert_eq!(id, expected_id);
+ }
+
+ #[test]
+ fn get_store_path_nests_topic_and_partition() {
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ Utc::now(),
+ 1234567890,
+ 0,
+ 0,
+ );
+
+ let base_path = Path::new("/data/stores");
+ let store_path = metadata.get_store_path(base_path);
+ assert_eq!(
+ store_path,
+ PathBuf::from(format!("/data/stores/{STORE_TOPIC}/{STORE_PARTITION}"))
+ );
+ }
+
+ #[test]
+ fn get_store_path_replaces_slashes_in_topic() {
+ let metadata = CheckpointMetadata::new(
+ "org/team/events".to_string(),
+ 0,
+ Utc::now(),
+ 1234567890,
+ 0,
+ 0,
+ );
+
+ let base_path = Path::new("/data/stores");
+ let store_path = metadata.get_store_path(base_path);
+ assert_eq!(store_path, PathBuf::from("/data/stores/org_team_events/0"));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/mod.rs b/rust/cohort-stream-processor/src/store/durability/mod.rs
new file mode 100644
index 000000000000..1a1ae5fcd223
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/mod.rs
@@ -0,0 +1,99 @@
+//! Disaster-recovery durability for the per-process RocksDB state store: a frozen whole-DB
+//! `Checkpoint` plus incremental S3 backup/restore.
+//!
+//! ## Single-DB identity
+//!
+//! The processor keeps one DB per process holding all 64 partitions (keys are
+//! `partition_id`-prefixed), so there is exactly one checkpoint lineage per pod. The per-`(topic,
+//! partition)` identity used to key the S3 layout therefore collapses to the two fixed constants
+//! below, yielding one stable S3 prefix for the pod. The identity is fixed rather than configurable:
+//! a stable prefix is all that matters, and freezing it keeps the S3 layout reproducible across
+//! restarts.
+
+pub mod checkpoint;
+pub mod config;
+pub mod downloader;
+pub mod error;
+pub mod export;
+pub mod import;
+pub mod manifest;
+pub mod metadata;
+pub mod planner;
+pub mod recovery;
+pub mod s3_client;
+pub mod s3_downloader;
+pub mod s3_uploader;
+pub mod uploader;
+
+/// The single-DB identity's "topic": a fixed store-id string used only to derive the S3 prefix (the
+/// whole-DB checkpoint is not tied to any one Kafka topic). See the module docs.
+pub const STORE_TOPIC: &str = "cohort_stream_state";
+/// The single-DB identity's "partition". Always 0: one DB per pod, not one per Kafka partition.
+pub const STORE_PARTITION: i32 = 0;
+
+pub use checkpoint::{
+ should_upload, upload_cadence, CheckpointSweeper, TrackedTopic, CHECKPOINT_LOOP_NAME,
+};
+pub use config::DurabilityConfig;
+pub use downloader::CheckpointDownloader;
+pub use export::CheckpointExporter;
+pub use import::CheckpointImporter;
+pub use manifest::{OffsetManifest, MANIFEST_FILENAME, MANIFEST_VERSION};
+pub use metadata::{
+ hash_prefix_for_partition, store_hash_prefix, CheckpointFile, CheckpointInfo,
+ CheckpointMetadata, METADATA_FILENAME,
+};
+pub use planner::{plan_checkpoint, CheckpointPlan, LocalCheckpointFile};
+pub use recovery::{decide_restore_source, run_boot_restore, RestoreOutcome, RestoreSource};
+pub use s3_downloader::S3Downloader;
+pub use s3_uploader::S3Uploader;
+pub use uploader::CheckpointUploader;
+
+pub use error::{
+ DownloadCancelledError, ImportTimeoutError, PlanningCancelledError, UploadCancelledError,
+};
+
+use std::path::PathBuf;
+use tracing::{info, warn};
+
+/// Removes `path` on drop (failure, timeout, cancellation, or panic) unless defused. Shared by both
+/// disaster-restore materializers — the S3 import ([`import`]) and the PVC copy ([`recovery`]) — so a
+/// failed restore never leaves a partial store directory behind. That guarantee is what lets the next
+/// boot's cold-start *outcome* actually start cold rather than reopening a torn store.
+pub(super) struct DirCleanupGuard {
+ path: PathBuf,
+ defused: bool,
+}
+
+impl DirCleanupGuard {
+ pub(super) fn new(path: PathBuf) -> Self {
+ Self {
+ path,
+ defused: false,
+ }
+ }
+
+ /// Defuse the guard so the directory survives the drop. Call on success.
+ pub(super) fn defuse(mut self) -> PathBuf {
+ self.defused = true;
+ std::mem::take(&mut self.path)
+ }
+}
+
+impl Drop for DirCleanupGuard {
+ fn drop(&mut self) {
+ if !self.defused && self.path.exists() {
+ match std::fs::remove_dir_all(&self.path) {
+ Ok(_) => info!(
+ path = %self.path.display(),
+ "Dir cleanup guard: removed incomplete store directory"
+ ),
+ Err(e) => warn!(
+ path = %self.path.display(),
+ error = ?e,
+ "Dir cleanup guard: failed to remove directory, orphan cleaner will handle it"
+ ),
+ }
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/planner.rs b/rust/cohort-stream-processor/src/store/durability/planner.rs
new file mode 100644
index 000000000000..6ab547832dfd
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/planner.rs
@@ -0,0 +1,790 @@
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+use super::{
+ store_hash_prefix, CheckpointFile, CheckpointInfo, CheckpointMetadata, PlanningCancelledError,
+ STORE_PARTITION, STORE_TOPIC,
+};
+use crate::observability::metrics::CHECKPOINT_PLAN_FILES_TOTAL;
+
+use anyhow::{Context, Result};
+use chrono::{DateTime, Utc};
+use sha2::{Digest, Sha256};
+use tokio_util::sync::CancellationToken;
+use tracing::{debug, info};
+
+#[derive(Debug)]
+pub struct CheckpointPlan {
+ pub info: CheckpointInfo,
+ pub files_to_upload: Vec<LocalCheckpointFile>,
+}
+
+/// Build a checkpoint plan: new metadata plus the files to upload.
+///
+/// Incremental dedup keyed on filename: SST files (immutable) are reused from the previous attempt;
+/// mutable files are re-uploaded only on checksum change. The cancellation token, if given, is
+/// checked during the directory walk and before hashing non-SST files.
+pub fn plan_checkpoint(
+ local_checkpoint_attempt_dir: &Path,
+ remote_bucket_namespace: String,
+ attempt_timestamp: DateTime<Utc>,
+ sequence: u64,
+ previous_metadata: Option<&CheckpointMetadata>,
+ cancel_token: Option<&CancellationToken>,
+) -> Result<CheckpointPlan> {
+ ensure_not_cancelled(cancel_token, "before planning start")?;
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ attempt_timestamp,
+ sequence,
+ 0,
+ 0,
+ );
+ let hash = store_hash_prefix().to_string();
+ let mut info = CheckpointInfo::new(metadata, remote_bucket_namespace, Some(hash));
+ let mut files_to_upload: Vec<LocalCheckpointFile> = Vec::new();
+
+ let local_files = collect_local_files(local_checkpoint_attempt_dir, cancel_token)?;
+ info!(
+ "Found {} files in local checkpoint directory",
+ local_files.len()
+ );
+
+ let Some(prev_meta) = previous_metadata else {
+ info!("No previous checkpoint metadata - tracking all files for upload");
+ for candidate in local_files {
+ let remote_filepath = info.get_file_key(&candidate.filename);
+ info.metadata
+ .track_file(remote_filepath, candidate.checksum.clone());
+ files_to_upload.push(candidate);
+ }
+ return Ok(CheckpointPlan {
+ info,
+ files_to_upload,
+ });
+ };
+
+ let mut prev_file_map: HashMap<String, CheckpointFile> = HashMap::new();
+ for prev_cp_file in &prev_meta.files {
+ let filename = prev_cp_file
+ .remote_filepath
+ .rsplit('/')
+ .next()
+ .unwrap_or(&prev_cp_file.remote_filepath)
+ .to_string();
+ prev_file_map.insert(filename, prev_cp_file.clone());
+ }
+
+ info!(
+ "Built file map with {} files from previous checkpoint {}",
+ prev_file_map.len(),
+ prev_meta.id
+ );
+
+ for candidate in local_files {
+ let filename = &candidate.filename;
+ if let Some(prev_file) = prev_file_map.get(filename) {
+ if retain_or_replace_duplicate(&candidate, prev_file) {
+ debug!("Duplicate file {} - new file will be uploaded", filename);
+ metrics::counter!(CHECKPOINT_PLAN_FILES_TOTAL, "action" => "replaced").increment(1);
+ let remote_filepath = info.get_file_key(filename);
+ info.metadata
+ .track_file(remote_filepath, candidate.checksum.clone());
+ files_to_upload.push(candidate);
+ } else {
+ debug!(
+ "Duplicate file {} - retaining original, skipping upload",
+ filename
+ );
+ metrics::counter!(CHECKPOINT_PLAN_FILES_TOTAL, "action" => "retained").increment(1);
+ info.metadata.track_file(
+ prev_file.remote_filepath.clone(),
+ prev_file.checksum.clone(),
+ );
+ }
+ } else {
+ debug!("New file {} will be uploaded", filename);
+ metrics::counter!(CHECKPOINT_PLAN_FILES_TOTAL, "action" => "added").increment(1);
+ let remote_filepath = info.get_file_key(filename);
+ info.metadata
+ .track_file(remote_filepath, candidate.checksum.clone());
+ files_to_upload.push(candidate);
+ }
+ }
+
+ info!(
+ "Checkpoint plan: {} new files, {} reused files",
+ files_to_upload.len(),
+ info.metadata.files.len() - files_to_upload.len(),
+ );
+
+ Ok(CheckpointPlan {
+ info,
+ files_to_upload,
+ })
+}
+
+fn retain_or_replace_duplicate(
+ candidate: &LocalCheckpointFile,
+ prev_file: &CheckpointFile,
+) -> bool {
+ match &candidate.filename {
+ f if f == "CURRENT" => true, // always re-uploaded
+ f if f.ends_with(".sst") => false, // immutable, always reused
+
+ // RocksDB mutates these in place; re-upload only on checksum change.
+ f if f.starts_with("OPTIONS-") || f.starts_with("MANIFEST-") || f.ends_with(".log") => {
+ candidate.checksum != prev_file.checksum
+ }
+ _ => true, // bias to keeping latest files for safety
+ }
+}
+
+fn collect_local_files(
+ base_attempt_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+) -> Result<Vec<LocalCheckpointFile>> {
+ let mut files = Vec::new();
+ let mut stack = vec![base_attempt_path.to_path_buf()];
+
+ while let Some(current_path) = stack.pop() {
+ ensure_not_cancelled(cancel_token, "during directory walk")?;
+ let entries = std::fs::read_dir(&current_path)
+ .with_context(|| format!("Failed to read directory: {current_path:?}"))?;
+
+ for entry in entries {
+ ensure_not_cancelled(cancel_token, "during directory walk")?;
+ let entry = entry.context(format!(
+ "Failed to read directory entry from {base_attempt_path:?}"
+ ))?;
+ let path = entry.path();
+
+ if path.is_dir() {
+ stack.push(path);
+ } else {
+ let candidate =
+ build_candidate_file(&path, cancel_token).context("In build_candidate_file")?;
+ files.push(candidate);
+ }
+ }
+ }
+
+ Ok(files)
+}
+
+fn build_candidate_file(
+ file_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+) -> Result<LocalCheckpointFile> {
+ let local_file_path = file_path.to_path_buf();
+ let filename = file_path
+ .file_name()
+ .context(format!("Failed to get filename for: {file_path:?}"))?
+ .to_string_lossy()
+ .to_string();
+
+ let checksum = if filename.ends_with(".sst") {
+ String::default()
+ } else {
+ ensure_not_cancelled(cancel_token, "before hashing non-SST file")?;
+ load_and_hash_file(file_path).context("In load_and_hash_file")?
+ };
+
+ Ok(LocalCheckpointFile::new(
+ filename,
+ checksum,
+ local_file_path,
+ ))
+}
+
+fn load_and_hash_file(file_path: &Path) -> Result<String> {
+ let mut file = std::fs::File::open(file_path)
+ .with_context(|| format!("Failed to open file for hashing: {file_path:?}"))?;
+
+ let mut hasher = Sha256::new();
+ std::io::copy(&mut file, &mut hasher)
+ .with_context(|| format!("Failed to read and hash file: {file_path:?}"))?;
+ let hash = hasher.finalize();
+ let checksum = format!("{hash:x}");
+
+ Ok(checksum.to_string())
+}
+
+fn ensure_not_cancelled(
+ cancel_token: Option<&CancellationToken>,
+ reason: &'static str,
+) -> Result<()> {
+ if cancel_token.is_some_and(CancellationToken::is_cancelled) {
+ return Err(PlanningCancelledError {
+ reason: reason.to_string(),
+ }
+ .into());
+ }
+
+ Ok(())
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LocalCheckpointFile {
+ pub filename: String,
+ pub checksum: String,
+ pub local_path: PathBuf,
+}
+
+impl LocalCheckpointFile {
+ pub fn new(filename: String, checksum: String, local_path: PathBuf) -> Self {
+ Self {
+ filename,
+ checksum,
+ local_path,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono::Duration;
+ use tempfile::TempDir;
+ use tokio_util::sync::CancellationToken;
+
+ fn attempt_dir(base: &Path, checkpoint_id: &str) -> PathBuf {
+ base.join(STORE_TOPIC)
+ .join(STORE_PARTITION.to_string())
+ .join(checkpoint_id)
+ }
+
+ #[test]
+ fn plan_checkpoint_no_previous() {
+ let temp_dir = TempDir::new().unwrap();
+ let remote_bucket_namespace = "checkpoints";
+ let attempt_timestamp = Utc::now();
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let sequence = 1000;
+ let local_checkpoint_attempt_dir = attempt_dir(temp_dir.path(), &checkpoint_id);
+
+ std::fs::create_dir_all(&local_checkpoint_attempt_dir).unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("file1.sst"), b"data1").unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("file2.sst"), b"data2").unwrap();
+
+ let plan = plan_checkpoint(
+ &local_checkpoint_attempt_dir,
+ remote_bucket_namespace.to_string(),
+ attempt_timestamp,
+ sequence,
+ None,
+ None,
+ )
+ .unwrap();
+
+ let expected_sst1 =
+ build_candidate_file(&local_checkpoint_attempt_dir.join("file1.sst"), None).unwrap();
+ let expected_sst2 =
+ build_candidate_file(&local_checkpoint_attempt_dir.join("file2.sst"), None).unwrap();
+
+ assert_eq!(plan.files_to_upload.len(), 2);
+ let got_sst1 = plan
+ .files_to_upload
+ .iter()
+ .find(|f| f.filename == "file1.sst")
+ .unwrap();
+ let got_sst2 = plan
+ .files_to_upload
+ .iter()
+ .find(|f| f.filename == "file2.sst")
+ .unwrap();
+ assert_eq!(got_sst1, &expected_sst1);
+ assert_eq!(got_sst2, &expected_sst2);
+
+ assert_eq!(plan.info.metadata.files.len(), 2);
+ let hash = store_hash_prefix();
+ let expected_remote_path = format!(
+ "{hash}/{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}"
+ );
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .all(|f| f.remote_filepath.starts_with(&expected_remote_path)));
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .any(|f| f.remote_filepath.ends_with("file1.sst")));
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .any(|f| f.remote_filepath.ends_with("file2.sst")));
+ let meta_key = plan.info.get_metadata_key();
+ assert!(meta_key.contains(hash));
+ assert_eq!(
+ meta_key,
+ format!(
+ "{hash}/{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/metadata.json"
+ )
+ );
+ }
+
+ #[test]
+ fn plan_checkpoint_with_previous() {
+ let temp_dir = TempDir::new().unwrap();
+ let remote_bucket_namespace = "checkpoints";
+ let prev_attempt_timestamp = Utc::now() - Duration::hours(1);
+ let prev_checkpoint_id = CheckpointMetadata::generate_id(prev_attempt_timestamp);
+ let prev_sequence = 1000;
+
+ let mut prev_metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ prev_attempt_timestamp,
+ prev_sequence,
+ 0,
+ 0,
+ );
+
+ let prev_local_attempt_dir = attempt_dir(temp_dir.path(), &prev_checkpoint_id);
+
+ std::fs::create_dir_all(&prev_local_attempt_dir).unwrap();
+ std::fs::write(prev_local_attempt_dir.join("00001.sst"), b"data1").unwrap();
+ std::fs::write(prev_local_attempt_dir.join("00002.sst"), b"data2").unwrap();
+
+ let expected_prev_sst1 =
+ build_candidate_file(&prev_local_attempt_dir.join("00001.sst"), None).unwrap();
+ let expected_prev_sst2 =
+ build_candidate_file(&prev_local_attempt_dir.join("00002.sst"), None).unwrap();
+
+ let prev_remote_path = format!(
+ "{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{prev_checkpoint_id}"
+ );
+
+ let prev_sst1_remote_path = format!("{prev_remote_path}/00001.sst");
+ prev_metadata.track_file(
+ prev_sst1_remote_path.clone(),
+ expected_prev_sst1.checksum.clone(),
+ );
+
+ let prev_sst2_remote_path = format!("{prev_remote_path}/00002.sst");
+ prev_metadata.track_file(
+ prev_sst2_remote_path.clone(),
+ expected_prev_sst2.checksum.clone(),
+ );
+
+ let attempt_timestamp = Utc::now();
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let sequence = 1001;
+ let local_checkpoint_attempt_dir = attempt_dir(temp_dir.path(), &checkpoint_id);
+
+ std::fs::create_dir_all(&local_checkpoint_attempt_dir).unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("00001.sst"), b"data1").unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("00002.sst"), b"data2").unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("00003.sst"), b"data3").unwrap();
+ let expected_sst3 =
+ build_candidate_file(&local_checkpoint_attempt_dir.join("00003.sst"), None).unwrap();
+
+ let plan = plan_checkpoint(
+ &local_checkpoint_attempt_dir,
+ remote_bucket_namespace.to_string(),
+ attempt_timestamp,
+ sequence,
+ Some(&prev_metadata),
+ None,
+ )
+ .unwrap();
+
+ assert_eq!(plan.files_to_upload.len(), 1);
+ let got_sst3 = plan
+ .files_to_upload
+ .iter()
+ .find(|f| f.filename == "00003.sst")
+ .unwrap();
+ assert_eq!(got_sst3, &expected_sst3);
+
+ assert_eq!(plan.info.metadata.files.len(), 3);
+
+ let hash = store_hash_prefix();
+ let current_attempt_remote_path = format!(
+ "{hash}/{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}"
+ );
+
+ let sst1_remote_path = format!("{prev_remote_path}/00001.sst");
+ let sst2_remote_path = format!("{prev_remote_path}/00002.sst");
+ let sst3_remote_path = format!("{current_attempt_remote_path}/00003.sst");
+
+ let sst1_file_meta = plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .find(|f| f.remote_filepath == sst1_remote_path)
+ .unwrap();
+
+ let sst2_file_meta = plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .find(|f| f.remote_filepath == sst2_remote_path)
+ .unwrap();
+
+ let sst3_file_meta = plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .find(|f| f.remote_filepath == sst3_remote_path)
+ .unwrap();
+
+ assert_eq!(&sst1_file_meta.checksum, &expected_prev_sst1.checksum);
+ assert_eq!(&sst2_file_meta.checksum, &expected_prev_sst2.checksum);
+ assert_eq!(sst3_file_meta.checksum, expected_sst3.checksum);
+ }
+
+ #[test]
+ fn plan_checkpoint_with_only_prev_files() {
+ let temp_dir = TempDir::new().unwrap();
+ let remote_bucket_namespace = "checkpoints";
+ let prev_attempt_timestamp = Utc::now() - Duration::hours(1);
+ let prev_checkpoint_id = CheckpointMetadata::generate_id(prev_attempt_timestamp);
+ let prev_sequence = 1000;
+
+ let mut prev_metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ prev_attempt_timestamp,
+ prev_sequence,
+ 0,
+ 0,
+ );
+
+ let prev_local_attempt_dir = attempt_dir(temp_dir.path(), &prev_checkpoint_id);
+
+ std::fs::create_dir_all(&prev_local_attempt_dir).unwrap();
+ std::fs::write(prev_local_attempt_dir.join("00001.sst"), b"data1").unwrap();
+ std::fs::write(prev_local_attempt_dir.join("00002.sst"), b"data2").unwrap();
+ std::fs::write(prev_local_attempt_dir.join("00003.sst"), b"data3").unwrap();
+
+ let expected_prev_sst1 =
+ build_candidate_file(&prev_local_attempt_dir.join("00001.sst"), None).unwrap();
+ let expected_prev_sst2 =
+ build_candidate_file(&prev_local_attempt_dir.join("00002.sst"), None).unwrap();
+ let expected_prev_sst3 =
+ build_candidate_file(&prev_local_attempt_dir.join("00003.sst"), None).unwrap();
+
+ let prev_remote_path = format!(
+ "{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{prev_checkpoint_id}"
+ );
+ let prev_sst1_remote_path = format!("{prev_remote_path}/00001.sst");
+ let prev_sst2_remote_path = format!("{prev_remote_path}/00002.sst");
+ let prev_sst3_remote_path = format!("{prev_remote_path}/00003.sst");
+
+ prev_metadata.track_file(
+ prev_sst1_remote_path.clone(),
+ expected_prev_sst1.checksum.clone(),
+ );
+ prev_metadata.track_file(
+ prev_sst2_remote_path.clone(),
+ expected_prev_sst2.checksum.clone(),
+ );
+ prev_metadata.track_file(
+ prev_sst3_remote_path.clone(),
+ expected_prev_sst3.checksum.clone(),
+ );
+
+ let attempt_timestamp = Utc::now();
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let sequence = 1001;
+ let local_checkpoint_attempt_dir = attempt_dir(temp_dir.path(), &checkpoint_id);
+
+ std::fs::create_dir_all(&local_checkpoint_attempt_dir).unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("00001.sst"), b"data1").unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("00002.sst"), b"data2").unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("00003.sst"), b"data3").unwrap();
+
+ let plan = plan_checkpoint(
+ &local_checkpoint_attempt_dir,
+ remote_bucket_namespace.to_string(),
+ attempt_timestamp,
+ sequence,
+ Some(&prev_metadata),
+ None,
+ )
+ .unwrap();
+
+ assert!(plan.files_to_upload.is_empty());
+ assert_eq!(plan.info.metadata.files.len(), 3);
+
+ let sst1_file_meta = plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .find(|f| f.remote_filepath == prev_sst1_remote_path)
+ .unwrap();
+ let sst2_file_meta = plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .find(|f| f.remote_filepath == prev_sst2_remote_path)
+ .unwrap();
+ let sst3_file_meta = plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .find(|f| f.remote_filepath == prev_sst3_remote_path)
+ .unwrap();
+
+ assert_eq!(&sst1_file_meta.checksum, &expected_prev_sst1.checksum);
+ assert_eq!(&sst2_file_meta.checksum, &expected_prev_sst2.checksum);
+ assert_eq!(&sst3_file_meta.checksum, &expected_prev_sst3.checksum);
+ }
+
+ #[test]
+ fn plan_checkpoint_with_previous_and_non_sst_types() {
+ let temp_dir = TempDir::new().unwrap();
+ let remote_bucket_namespace = "checkpoints";
+ let prev_attempt_timestamp = Utc::now() - Duration::hours(1);
+ let prev_checkpoint_id = CheckpointMetadata::generate_id(prev_attempt_timestamp);
+ let prev_sequence = 1000;
+
+ let mut prev_metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ prev_attempt_timestamp,
+ prev_sequence,
+ 0,
+ 0,
+ );
+
+ let prev_local_attempt_dir = attempt_dir(temp_dir.path(), &prev_checkpoint_id);
+
+ std::fs::create_dir_all(&prev_local_attempt_dir).unwrap();
+ std::fs::write(prev_local_attempt_dir.join("00001.sst"), b"data1").unwrap();
+ std::fs::write(prev_local_attempt_dir.join("00002.sst"), b"data2").unwrap();
+ std::fs::write(prev_local_attempt_dir.join("MANIFEST-000000"), b"data3").unwrap();
+ std::fs::write(prev_local_attempt_dir.join("OPTIONS-000000"), b"data4").unwrap();
+ std::fs::write(prev_local_attempt_dir.join("CURRENT"), b"data5").unwrap();
+ std::fs::write(prev_local_attempt_dir.join("00001.log"), b"data6").unwrap();
+
+ let expected_prev_sst1 =
+ build_candidate_file(&prev_local_attempt_dir.join("00001.sst"), None).unwrap();
+ let expected_prev_sst2 =
+ build_candidate_file(&prev_local_attempt_dir.join("00002.sst"), None).unwrap();
+ let expected_prev_manifest =
+ build_candidate_file(&prev_local_attempt_dir.join("MANIFEST-000000"), None).unwrap();
+ let expected_prev_options =
+ build_candidate_file(&prev_local_attempt_dir.join("OPTIONS-000000"), None).unwrap();
+ let expected_prev_current =
+ build_candidate_file(&prev_local_attempt_dir.join("CURRENT"), None).unwrap();
+ let expected_prev_log =
+ build_candidate_file(&prev_local_attempt_dir.join("00001.log"), None).unwrap();
+
+ let prev_remote_path = format!(
+ "{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{prev_checkpoint_id}"
+ );
+ let prev_sst1_remote_path = format!("{prev_remote_path}/00001.sst");
+ let prev_sst2_remote_path = format!("{prev_remote_path}/00002.sst");
+ let prev_manifest_remote_path = format!("{prev_remote_path}/MANIFEST-000000");
+ let prev_options_remote_path = format!("{prev_remote_path}/OPTIONS-000000");
+ let prev_current_remote_path = format!("{prev_remote_path}/CURRENT");
+ let prev_log_remote_path = format!("{prev_remote_path}/00001.log");
+
+ prev_metadata.track_file(
+ prev_sst1_remote_path.clone(),
+ expected_prev_sst1.checksum.clone(),
+ );
+ prev_metadata.track_file(
+ prev_sst2_remote_path.clone(),
+ expected_prev_sst2.checksum.clone(),
+ );
+ prev_metadata.track_file(
+ prev_manifest_remote_path.clone(),
+ expected_prev_manifest.checksum.clone(),
+ );
+ prev_metadata.track_file(
+ prev_options_remote_path.clone(),
+ expected_prev_options.checksum.clone(),
+ );
+ prev_metadata.track_file(
+ prev_current_remote_path.clone(),
+ expected_prev_current.checksum.clone(),
+ );
+ prev_metadata.track_file(
+ prev_log_remote_path.clone(),
+ expected_prev_log.checksum.clone(),
+ );
+
+ let attempt_timestamp = Utc::now();
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let sequence = 1001;
+ let local_checkpoint_attempt_dir = attempt_dir(temp_dir.path(), &checkpoint_id);
+
+ std::fs::create_dir_all(&local_checkpoint_attempt_dir).unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("00001.sst"), b"data1").unwrap(); // no change, always retain
+ std::fs::write(local_checkpoint_attempt_dir.join("00002.sst"), b"data2").unwrap(); // no change, always retain
+ std::fs::write(local_checkpoint_attempt_dir.join("00003.sst"), b"data7").unwrap(); // new file, should upload
+ std::fs::write(
+ local_checkpoint_attempt_dir.join("MANIFEST-000000"),
+ b"data3",
+ )
+ .unwrap(); // unchanged, should retain
+ std::fs::write(
+ local_checkpoint_attempt_dir.join("OPTIONS-000000"),
+ b"data4",
+ )
+ .unwrap(); // unchanged, should retain
+ std::fs::write(local_checkpoint_attempt_dir.join("CURRENT"), b"data5").unwrap(); // unchanged, but always uploaded
+ std::fs::write(
+ local_checkpoint_attempt_dir.join("00001.log"),
+ b"data6_APPENDED",
+ )
+ .unwrap(); // mutated, should upload
+
+ let plan = plan_checkpoint(
+ &local_checkpoint_attempt_dir,
+ remote_bucket_namespace.to_string(),
+ attempt_timestamp,
+ sequence,
+ Some(&prev_metadata),
+ None,
+ )
+ .unwrap();
+
+ assert_eq!(plan.files_to_upload.len(), 3);
+ assert!(plan
+ .files_to_upload
+ .iter()
+ .any(|f| f.filename == "00003.sst"));
+ assert!(plan
+ .files_to_upload
+ .iter()
+ .any(|f| f.filename == "00001.log"));
+ assert!(plan.files_to_upload.iter().any(|f| f.filename == "CURRENT"));
+
+ assert_eq!(plan.info.metadata.files.len(), 7);
+
+ // New files (sst3, CURRENT, log) use the hashed path; retained files keep the previous path.
+ let hash = store_hash_prefix();
+ let current_attempt_remote_path = format!(
+ "{hash}/{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}"
+ );
+ let sst1_remote_path = format!("{prev_remote_path}/00001.sst");
+ let sst2_remote_path = format!("{prev_remote_path}/00002.sst");
+ let sst3_remote_path = format!("{current_attempt_remote_path}/00003.sst");
+ let manifest_remote_path = format!("{prev_remote_path}/MANIFEST-000000");
+ let options_remote_path = format!("{prev_remote_path}/OPTIONS-000000");
+ let current_remote_path = format!("{current_attempt_remote_path}/CURRENT");
+ let log_remote_path = format!("{current_attempt_remote_path}/00001.log");
+
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .any(|f| f.remote_filepath == sst1_remote_path));
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .any(|f| f.remote_filepath == sst2_remote_path));
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .any(|f| f.remote_filepath == sst3_remote_path));
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .any(|f| f.remote_filepath == manifest_remote_path));
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .any(|f| f.remote_filepath == options_remote_path));
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .any(|f| f.remote_filepath == current_remote_path));
+ assert!(plan
+ .info
+ .metadata
+ .files
+ .iter()
+ .any(|f| f.remote_filepath == log_remote_path));
+ }
+
+ #[test]
+ fn plan_checkpoint_cancelled_before_start() {
+ let temp_dir = TempDir::new().unwrap();
+ let attempt_timestamp = Utc::now();
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let local_checkpoint_attempt_dir = attempt_dir(temp_dir.path(), &checkpoint_id);
+
+ std::fs::create_dir_all(&local_checkpoint_attempt_dir).unwrap();
+ std::fs::write(local_checkpoint_attempt_dir.join("00001.sst"), b"data1").unwrap();
+
+ let cancel_token = CancellationToken::new();
+ cancel_token.cancel();
+
+ let err = plan_checkpoint(
+ &local_checkpoint_attempt_dir,
+ "checkpoints".to_string(),
+ attempt_timestamp,
+ 1000,
+ None,
+ Some(&cancel_token),
+ )
+ .unwrap_err();
+
+ assert!(
+ err.downcast_ref::<PlanningCancelledError>().is_some(),
+ "error should be PlanningCancelledError: {err}"
+ );
+ }
+
+ #[test]
+ fn collect_local_files_cancelled_during_directory_walk() {
+ let temp_dir = TempDir::new().unwrap();
+ let nested_dir = temp_dir.path().join("nested");
+ std::fs::create_dir_all(&nested_dir).unwrap();
+ std::fs::write(nested_dir.join("00001.sst"), b"data1").unwrap();
+
+ let cancel_token = CancellationToken::new();
+ cancel_token.cancel();
+
+ let err = collect_local_files(temp_dir.path(), Some(&cancel_token)).unwrap_err();
+ assert!(
+ err.downcast_ref::<PlanningCancelledError>().is_some(),
+ "error should be PlanningCancelledError: {err}"
+ );
+ }
+
+ #[test]
+ fn build_candidate_file_cancelled_before_hashing_non_sst() {
+ let temp_dir = TempDir::new().unwrap();
+ let file_path = temp_dir.path().join("MANIFEST-000000");
+ std::fs::write(&file_path, b"manifest-data").unwrap();
+
+ let cancel_token = CancellationToken::new();
+ cancel_token.cancel();
+
+ let err = build_candidate_file(&file_path, Some(&cancel_token)).unwrap_err();
+ assert!(
+ err.downcast_ref::<PlanningCancelledError>().is_some(),
+ "error should be PlanningCancelledError: {err}"
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/recovery.rs b/rust/cohort-stream-processor/src/store/durability/recovery.rs
new file mode 100644
index 000000000000..c37bec202d3d
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/recovery.rs
@@ -0,0 +1,618 @@
+//! Boot-time restore decision + materialization, run **before** `CohortStore::open`.
+//!
+//! The entry point is [`run_boot_restore`] (distinct from the top-level `crate::recovery` cold-start
+//! stub). It decides where the live store should come from and, for the disaster paths, materializes
+//! it at `store_path` so the existing `effective_wipe_on_start` logic then sees `db_dir_exists ==
+//! true` and keeps the restored data.
+//!
+//! ## Precedence
+//!
+//! 1. **ReopenLive** — an intact, non-stale live store already sits at `store_path`. A normal restart
+//! with an intact PVC lands here; it needs no manifest, because resume-from-committed
+//! (`Offset::Stored`) is safe under the `committed <= durable` invariant.
+//! 2. **PvcCheckpoint(dir)** — the live store is gone/stale (lost or corrupt PVC) but a recent local
+//! checkpoint with a readable `offsets.json` exists within `checkpoint_local_max_staleness`.
+//! 3. **S3** — no usable local source; restore from the most recent S3 checkpoint.
+//! 4. **ColdStart** — nothing to restore; the wipe+replay path takes over.
+//!
+//! The PVC/S3 branches are **gated behind `checkpoint_enabled`**: with the gate off,
+//! [`decide_restore_source`] returns only `ReopenLive` or `ColdStart`.
+
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+use anyhow::Result;
+use chrono::Utc;
+use tracing::{info, warn};
+
+use super::{
+ CheckpointImporter, DirCleanupGuard, OffsetManifest, S3Downloader, MANIFEST_FILENAME,
+ METADATA_FILENAME,
+};
+use crate::config::Config;
+use crate::observability::metrics::{
+ CHECKPOINT_RESTORE_DURATION_SECONDS, CHECKPOINT_RESTORE_TOTAL,
+};
+
+/// Where the live store should be sourced from on this boot. Resolved by [`decide_restore_source`]
+/// before the store is opened.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum RestoreSource {
+ /// Reopen the intact live store already at `store_path`. No materialization, no manifest.
+ ReopenLive,
+ /// Recursive-copy this local PVC checkpoint dir into `store_path`, then read its `offsets.json`.
+ PvcCheckpoint(PathBuf),
+ /// Download the most recent S3 checkpoint directly into `store_path`, then read its `offsets.json`.
+ S3,
+ /// Nothing to restore; fall through to the wipe+replay cold path.
+ ColdStart,
+}
+
+impl RestoreSource {
+ /// The `source` metric label (`reopen_live` | `pvc` | `s3` | `cold`).
+ fn metric_label(&self) -> &'static str {
+ match self {
+ RestoreSource::ReopenLive => "reopen_live",
+ RestoreSource::PvcCheckpoint(_) => "pvc",
+ RestoreSource::S3 => "s3",
+ RestoreSource::ColdStart => "cold",
+ }
+ }
+}
+
+/// The result of [`run_boot_restore`]: the chosen source plus the offset manifest that the events
+/// consumer seeks to. `manifest` is `None` for the no-seek paths (`ReopenLive`, `ColdStart`) and
+/// `Some` for the disaster paths (`PvcCheckpoint`, `S3`).
+#[derive(Debug)]
+pub struct RestoreOutcome {
+ pub source: RestoreSource,
+ pub manifest: Option<OffsetManifest>,
+}
+
+/// True when `path` looks like a valid, non-empty RocksDB store: the directory exists and contains a
+/// `CURRENT` file (RocksDB's manifest pointer, present in every opened DB). A bare or partially-wiped
+/// directory without `CURRENT` is treated as absent so reopen-live never resumes from a torn store.
+fn live_store_is_intact(path: &Path) -> bool {
+ path.is_dir() && path.join("CURRENT").is_file()
+}
+
+/// Decide the restore source. Runs before `CohortStore::open`. Touches the filesystem.
+///
+/// `checkpoint_enabled == false` is the inert default: it can only return `ReopenLive` (intact live
+/// store) or `ColdStart` (no live store), never `PvcCheckpoint`/`S3`. When the live store is intact
+/// and not slated for a wipe, reopen-live always wins (it takes precedence even over a fresh PVC
+/// checkpoint).
+pub fn decide_restore_source(config: &Config) -> RestoreSource {
+ let store_path = PathBuf::from(&config.store_path);
+
+ // `effective_wipe_on_start()` is `false` exactly when durable restore is on and a store exists;
+ // paired with an intact on-disk store, that means reopen-live is safe.
+ if !config.effective_wipe_on_start() && live_store_is_intact(&store_path) {
+ return RestoreSource::ReopenLive;
+ }
+
+ if !config.checkpoint_enabled {
+ return RestoreSource::ColdStart;
+ }
+
+ if let Some(dir) = newest_fresh_local_checkpoint(config) {
+ return RestoreSource::PvcCheckpoint(dir);
+ }
+
+ // Return S3 here; `run_boot_restore` downgrades to cold if no S3 checkpoint is found, keeping
+ // the network-free `decide_restore_source` cheap.
+ RestoreSource::S3
+}
+
+/// Scan `checkpoint_local_dir` for the newest checkpoint attempt directory that (a) carries a
+/// readable `offsets.json` and (b) was captured within `checkpoint_local_max_staleness`. A
+/// manifest-less directory is unusable (we cannot align offsets) and is skipped; a too-old directory
+/// is distrusted (another pod likely advanced the partitions while we were down) and falls through to
+/// S3.
+fn newest_fresh_local_checkpoint(config: &Config) -> Option<PathBuf> {
+ let base = PathBuf::from(&config.checkpoint_local_dir);
+ let max_staleness = config.checkpoint_local_max_staleness();
+ let now = Utc::now();
+
+ let mut best: Option<(chrono::DateTime<Utc>, PathBuf)> = None;
+ for dir in checkpoint_attempt_dirs(&base) {
+ // The manifest is authoritative for the capture instant and is required for the seek; a dir
+ // without a readable, version-matching one is unusable.
+ let Ok(manifest) = OffsetManifest::load_from_dir(&dir) else {
+ continue;
+ };
+ let age = now.signed_duration_since(manifest.captured_at);
+ // A future-dated capture (clock skew) maps to a negative duration, which is treated as 0 → fresh.
+ let within_bound = age
+ .to_std()
+ .map(|elapsed| elapsed <= max_staleness)
+ .unwrap_or(true);
+ if !within_bound {
+ continue;
+ }
+ match &best {
+ Some((best_at, _)) if *best_at >= manifest.captured_at => {}
+ _ => best = Some((manifest.captured_at, dir)),
+ }
+ }
+ best.map(|(_, dir)| dir)
+}
+
+/// Enumerate candidate checkpoint attempt directories under `base`. A checkpoint attempt dir is the
+/// leaf that holds the RocksDB files + `metadata.json` + `offsets.json`; the planner lays them out as
+/// `<base>/<topic>/<partition>/<checkpoint_id>`, so the candidates are the directories that contain a
+/// `metadata.json`. Walks defensively: any unreadable level yields no candidates rather than erroring.
+fn checkpoint_attempt_dirs(base: &Path) -> Vec<PathBuf> {
+ let mut out = Vec::new();
+ let mut stack = vec![base.to_path_buf()];
+ while let Some(dir) = stack.pop() {
+ let Ok(entries) = std::fs::read_dir(&dir) else {
+ continue;
+ };
+ // A dir that directly holds metadata.json is an attempt leaf; otherwise descend.
+ if dir.join(METADATA_FILENAME).is_file() {
+ out.push(dir);
+ continue;
+ }
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ stack.push(path);
+ }
+ }
+ }
+ out
+}
+
+/// Materialize `store_path` from the decided source and return the outcome (source + manifest).
+///
+/// - `ReopenLive` → no-op (store already in place), `manifest: None`.
+/// - `PvcCheckpoint(dir)` → recursive-copy `dir` into `store_path`, read `offsets.json`.
+/// - `S3` → import the newest S3 checkpoint into `store_path`, read the downloaded `offsets.json`;
+/// if no S3 checkpoint is usable, downgrade to a cold start.
+/// - `ColdStart` → no-op, `manifest: None`.
+///
+/// Always emits `CHECKPOINT_RESTORE_TOTAL{source}` + `CHECKPOINT_RESTORE_DURATION_SECONDS` and a
+/// one-line boot summary.
+pub async fn run_boot_restore(config: &Config, store_path: &Path) -> RestoreOutcome {
+ let started = Instant::now();
+ let decided = decide_restore_source(config);
+
+ let outcome = match decided {
+ RestoreSource::ReopenLive => RestoreOutcome {
+ source: RestoreSource::ReopenLive,
+ manifest: None,
+ },
+ RestoreSource::ColdStart => RestoreOutcome {
+ source: RestoreSource::ColdStart,
+ manifest: None,
+ },
+ RestoreSource::PvcCheckpoint(dir) => restore_from_pvc(&dir, store_path),
+ RestoreSource::S3 => restore_from_s3(config, store_path).await,
+ };
+
+ let label = outcome.source.metric_label();
+ metrics::counter!(CHECKPOINT_RESTORE_TOTAL, "source" => label).increment(1);
+ metrics::histogram!(CHECKPOINT_RESTORE_DURATION_SECONDS)
+ .record(started.elapsed().as_secs_f64());
+
+ info!(
+ source = label,
+ store_path = %store_path.display(),
+ seek_topics = outcome
+ .manifest
+ .as_ref()
+ .map_or(0, |m| m.topics.len()),
+ elapsed_secs = started.elapsed().as_secs_f64(),
+ "boot restore decided",
+ );
+
+ outcome
+}
+
+/// Recursive-copy a local PVC checkpoint into `store_path`, then read its manifest. On any copy or
+/// manifest failure, downgrade to a cold start (the wipe+replay path is always safe).
+fn restore_from_pvc(checkpoint_dir: &Path, store_path: &Path) -> RestoreOutcome {
+ // Remove any partial store before copying so the restored DB is the only content.
+ if store_path.exists() {
+ if let Err(e) = std::fs::remove_dir_all(store_path) {
+ warn!(error = %e, store_path = %store_path.display(), "failed to clear store before PVC restore; cold start");
+ return cold_downgrade();
+ }
+ }
+
+ // `copy_dir_recursive` is non-atomic: a mid-copy failure (disk full, transient I/O) leaves a
+ // half-written dir at `store_path`. Without cleanup the next boot would keep it (the wipe is
+ // skipped once the dir exists) and `decide_restore_source` would pick ReopenLive over a fresh
+ // restore — silently empty if `CURRENT` was missed, crash-looping if its SSTs were. The guard
+ // wipes the partial dir on every early return so a cold-start *outcome* actually starts cold.
+ //
+ // Residual: a SIGKILL *mid-copy* runs no Rust code, so the guard cannot fire; closing that needs
+ // a crash-safe copy (temp dir + atomic rename, or copy `CURRENT` last). Deferred follow-up.
+ let guard = DirCleanupGuard::new(store_path.to_path_buf());
+
+ if let Err(e) = copy_dir_recursive(checkpoint_dir, store_path) {
+ warn!(error = %e, from = %checkpoint_dir.display(), "PVC checkpoint copy failed; cold start");
+ return cold_downgrade();
+ }
+ match OffsetManifest::load_from_dir(store_path) {
+ Ok(manifest) => {
+ guard.defuse();
+ RestoreOutcome {
+ source: RestoreSource::PvcCheckpoint(checkpoint_dir.to_path_buf()),
+ manifest: Some(manifest),
+ }
+ }
+ Err(e) => {
+ warn!(error = %e, "PVC checkpoint manifest unreadable after copy; cold start");
+ cold_downgrade()
+ }
+ }
+}
+
+/// Import the newest usable S3 checkpoint directly into `store_path`, then read the downloaded
+/// manifest. On any failure (no S3 config, no usable checkpoint, unreadable manifest), downgrade to a
+/// cold start.
+async fn restore_from_s3(config: &Config, store_path: &Path) -> RestoreOutcome {
+ let durability = config.durability_config();
+ let downloader = match S3Downloader::new(&durability).await {
+ Ok(downloader) => downloader,
+ Err(e) => {
+ warn!(error = %e, "S3 downloader unavailable; cold start");
+ return cold_downgrade();
+ }
+ };
+ let importer = CheckpointImporter::new(
+ Box::new(downloader),
+ durability.checkpoint_import_attempt_depth,
+ durability.checkpoint_import_timeout,
+ );
+
+ match importer.import_checkpoint(store_path).await {
+ Ok(_imported_path) => match OffsetManifest::load_from_dir(store_path) {
+ Ok(manifest) => RestoreOutcome {
+ source: RestoreSource::S3,
+ manifest: Some(manifest),
+ },
+ Err(e) => {
+ warn!(error = %e, "S3 checkpoint imported but {MANIFEST_FILENAME} unreadable; cold start");
+ cold_downgrade()
+ }
+ },
+ Err(e) => {
+ warn!(error = %e, "no usable S3 checkpoint to restore; cold start");
+ cold_downgrade()
+ }
+ }
+}
+
+/// A failed disaster-restore path falls back to a cold start: no manifest, wipe+replay takes over.
+fn cold_downgrade() -> RestoreOutcome {
+ RestoreOutcome {
+ source: RestoreSource::ColdStart,
+ manifest: None,
+ }
+}
+
+/// Recursively copy `from` into `to` (creating `to`).
+fn copy_dir_recursive(from: &Path, to: &Path) -> Result<()> {
+ std::fs::create_dir_all(to)?;
+ for entry in std::fs::read_dir(from)? {
+ let entry = entry?;
+ let src = entry.path();
+ let dst = to.join(entry.file_name());
+ if entry.file_type()?.is_dir() {
+ copy_dir_recursive(&src, &dst)?;
+ } else {
+ std::fs::copy(&src, &dst)?;
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::store::durability::{CheckpointMetadata, STORE_PARTITION, STORE_TOPIC};
+ use chrono::Duration as ChronoDuration;
+ use envconfig::Envconfig;
+ use std::collections::BTreeMap;
+ use tempfile::TempDir;
+
+ fn config_with(checkpoint_enabled: bool, store_path: &Path, checkpoint_dir: &Path) -> Config {
+ let mut config = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ config.checkpoint_enabled = checkpoint_enabled;
+ // Durable restore must be on for reopen-live to ever beat a wipe (effective_wipe folds it in).
+ config.durable_restore_enabled = true;
+ config.wipe_store_on_start = true;
+ config.store_path = store_path.to_string_lossy().into_owned();
+ config.checkpoint_local_dir = checkpoint_dir.to_string_lossy().into_owned();
+ config
+ }
+
+ fn make_live_store(path: &Path) {
+ std::fs::create_dir_all(path).unwrap();
+ std::fs::write(path.join("CURRENT"), b"MANIFEST-000001\n").unwrap();
+ }
+
+ fn make_local_checkpoint(base: &Path, id: &str, age: ChronoDuration) -> PathBuf {
+ let attempt = base
+ .join(STORE_TOPIC)
+ .join(STORE_PARTITION.to_string())
+ .join(id);
+ std::fs::create_dir_all(&attempt).unwrap();
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ Utc::now(),
+ 1,
+ 0,
+ 0,
+ );
+ let json = metadata.to_json().unwrap();
+ std::fs::write(attempt.join(METADATA_FILENAME), json).unwrap();
+ let mut topics = BTreeMap::new();
+ topics.insert(
+ "cohort_stream_events".to_string(),
+ BTreeMap::from([(0, 42)]),
+ );
+ let manifest = OffsetManifest {
+ version: super::super::manifest::MANIFEST_VERSION,
+ captured_at: Utc::now() - age,
+ topics,
+ };
+ manifest.write_to_dir(&attempt).unwrap();
+ attempt
+ }
+
+ #[test]
+ fn reopen_live_takes_precedence_over_a_fresh_checkpoint() {
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ let checkpoint_dir = tmp.path().join("ckpt");
+ make_live_store(&store_path);
+ make_local_checkpoint(
+ &checkpoint_dir,
+ "2026-06-17T00-00-00Z",
+ ChronoDuration::minutes(1),
+ );
+
+ let config = config_with(true, &store_path, &checkpoint_dir);
+ assert_eq!(decide_restore_source(&config), RestoreSource::ReopenLive);
+ }
+
+ #[test]
+ fn pvc_checkpoint_chosen_when_live_store_is_gone() {
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ let checkpoint_dir = tmp.path().join("ckpt");
+ let attempt = make_local_checkpoint(
+ &checkpoint_dir,
+ "2026-06-17T00-00-00Z",
+ ChronoDuration::minutes(5),
+ );
+
+ let config = config_with(true, &store_path, &checkpoint_dir);
+ assert_eq!(
+ decide_restore_source(&config),
+ RestoreSource::PvcCheckpoint(attempt),
+ );
+ }
+
+ #[test]
+ fn the_newest_fresh_checkpoint_is_chosen() {
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ let checkpoint_dir = tmp.path().join("ckpt");
+ let _older = make_local_checkpoint(
+ &checkpoint_dir,
+ "2026-06-17T00-00-00Z",
+ ChronoDuration::minutes(30),
+ );
+ let newer = make_local_checkpoint(
+ &checkpoint_dir,
+ "2026-06-17T01-00-00Z",
+ ChronoDuration::minutes(2),
+ );
+
+ let config = config_with(true, &store_path, &checkpoint_dir);
+ assert_eq!(
+ decide_restore_source(&config),
+ RestoreSource::PvcCheckpoint(newer),
+ );
+ }
+
+ #[test]
+ fn a_stale_checkpoint_falls_through_to_s3() {
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ let max_staleness_secs = 7200;
+
+ let stale_dir = tmp.path().join("ckpt_stale");
+ make_local_checkpoint(
+ &stale_dir,
+ "2026-06-17T00-00-00Z",
+ ChronoDuration::seconds(max_staleness_secs as i64 + 60),
+ );
+ let mut config = config_with(true, &store_path, &stale_dir);
+ config.checkpoint_local_max_staleness_secs = max_staleness_secs;
+ assert_eq!(
+ decide_restore_source(&config),
+ RestoreSource::S3,
+ "a checkpoint older than max_staleness must not be trusted",
+ );
+
+ let fresh_dir = tmp.path().join("ckpt_fresh");
+ let fresh = make_local_checkpoint(
+ &fresh_dir,
+ "2026-06-17T00-30-00Z",
+ ChronoDuration::seconds(max_staleness_secs as i64 - 60),
+ );
+ config.checkpoint_local_dir = fresh_dir.to_string_lossy().into_owned();
+ assert_eq!(
+ decide_restore_source(&config),
+ RestoreSource::PvcCheckpoint(fresh),
+ );
+ }
+
+ #[test]
+ fn a_manifest_less_checkpoint_dir_is_skipped() {
+ // A dir with metadata.json but no offsets.json cannot align offsets → unusable.
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ let checkpoint_dir = tmp.path().join("ckpt");
+ let attempt = checkpoint_dir
+ .join(STORE_TOPIC)
+ .join(STORE_PARTITION.to_string())
+ .join("2026-06-17T00-00-00Z");
+ std::fs::create_dir_all(&attempt).unwrap();
+ let metadata = CheckpointMetadata::new(
+ STORE_TOPIC.to_string(),
+ STORE_PARTITION,
+ Utc::now(),
+ 1,
+ 0,
+ 0,
+ );
+ std::fs::write(attempt.join(METADATA_FILENAME), metadata.to_json().unwrap()).unwrap();
+ // offsets.json intentionally absent
+
+ let config = config_with(true, &store_path, &checkpoint_dir);
+ assert_eq!(decide_restore_source(&config), RestoreSource::S3);
+ }
+
+ #[test]
+ fn cold_start_when_no_store_no_checkpoint_and_gate_on() {
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ let checkpoint_dir = tmp.path().join("ckpt");
+
+ let config = config_with(true, &store_path, &checkpoint_dir);
+ // Gate on but no live store or local checkpoint → S3 (importer downgrades to cold if empty).
+ assert_eq!(decide_restore_source(&config), RestoreSource::S3);
+ }
+
+ #[test]
+ fn gate_off_never_picks_a_disaster_path() {
+ let tmp = TempDir::new().unwrap();
+ let checkpoint_dir = tmp.path().join("ckpt");
+ make_local_checkpoint(
+ &checkpoint_dir,
+ "2026-06-17T00-00-00Z",
+ ChronoDuration::minutes(1),
+ );
+
+ let absent = tmp.path().join("absent");
+ let config_absent = config_with(false, &absent, &checkpoint_dir);
+ assert_eq!(
+ decide_restore_source(&config_absent),
+ RestoreSource::ColdStart
+ );
+
+ let present = tmp.path().join("present");
+ make_live_store(&present);
+ let config_present = config_with(false, &present, &checkpoint_dir);
+ assert_eq!(
+ decide_restore_source(&config_present),
+ RestoreSource::ReopenLive
+ );
+ }
+
+ #[tokio::test]
+ async fn run_boot_restore_reopen_live_is_a_noop_with_no_manifest() {
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ let checkpoint_dir = tmp.path().join("ckpt");
+ make_live_store(&store_path);
+ let config = config_with(true, &store_path, &checkpoint_dir);
+
+ let outcome = run_boot_restore(&config, &store_path).await;
+ assert_eq!(outcome.source, RestoreSource::ReopenLive);
+ assert!(
+ outcome.manifest.is_none(),
+ "reopen-live needs no manifest (resume-from-committed)",
+ );
+ assert!(store_path.join("CURRENT").is_file());
+ }
+
+ #[tokio::test]
+ async fn run_boot_restore_copies_a_pvc_checkpoint_into_the_store_path() {
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ let checkpoint_dir = tmp.path().join("ckpt");
+ let attempt = make_local_checkpoint(
+ &checkpoint_dir,
+ "2026-06-17T00-00-00Z",
+ ChronoDuration::minutes(3),
+ );
+ std::fs::write(attempt.join("000001.sst"), b"sst-bytes").unwrap();
+
+ let config = config_with(true, &store_path, &checkpoint_dir);
+ let outcome = run_boot_restore(&config, &store_path).await;
+
+ assert!(matches!(outcome.source, RestoreSource::PvcCheckpoint(_)));
+ let manifest = outcome.manifest.expect("PVC restore yields a manifest");
+ assert_eq!(manifest.offset_for("cohort_stream_events", 0), Some(42));
+ assert!(store_path.join("000001.sst").is_file());
+ assert!(store_path.join(MANIFEST_FILENAME).is_file());
+ }
+
+ #[test]
+ fn restore_from_pvc_wipes_a_partial_store_when_the_copy_fails() {
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ // A leftover partial store from a prior torn restore that the copy must not preserve.
+ std::fs::create_dir_all(&store_path).unwrap();
+ std::fs::write(store_path.join("000001.sst"), b"torn").unwrap();
+
+ // A non-existent checkpoint dir makes `copy_dir_recursive`'s `read_dir` fail mid-restore.
+ let missing = tmp.path().join("nonexistent_checkpoint");
+
+ let outcome = restore_from_pvc(&missing, &store_path);
+ assert_eq!(outcome.source, RestoreSource::ColdStart);
+ assert!(
+ !store_path.exists(),
+ "the guard must wipe the partial store so the cold-start outcome actually starts cold",
+ );
+ }
+
+ #[test]
+ fn restore_from_pvc_wipes_the_store_when_the_manifest_is_unreadable() {
+ let tmp = TempDir::new().unwrap();
+ let store_path = tmp.path().join("store");
+ // A checkpoint dir that copies cleanly but carries no offsets.json → manifest load fails.
+ let checkpoint_dir = tmp.path().join("ckpt");
+ std::fs::create_dir_all(&checkpoint_dir).unwrap();
+ std::fs::write(checkpoint_dir.join("CURRENT"), b"MANIFEST-000001\n").unwrap();
+
+ let outcome = restore_from_pvc(&checkpoint_dir, &store_path);
+ assert_eq!(outcome.source, RestoreSource::ColdStart);
+ assert!(
+ !store_path.exists(),
+ "an unreadable manifest after copy must leave no partial store behind",
+ );
+ }
+
+ #[test]
+ fn manifest_is_none_for_reopen_live_and_cold_some_for_disaster_paths() {
+ let reopen = RestoreOutcome {
+ source: RestoreSource::ReopenLive,
+ manifest: None,
+ };
+ let cold = RestoreOutcome {
+ source: RestoreSource::ColdStart,
+ manifest: None,
+ };
+ let pvc = RestoreOutcome {
+ source: RestoreSource::PvcCheckpoint(PathBuf::from("/x")),
+ manifest: Some(OffsetManifest {
+ version: super::super::manifest::MANIFEST_VERSION,
+ captured_at: Utc::now(),
+ topics: BTreeMap::new(),
+ }),
+ };
+ assert!(reopen.manifest.is_none());
+ assert!(cold.manifest.is_none());
+ assert!(pvc.manifest.is_some());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/s3_client.rs b/rust/cohort-stream-processor/src/store/durability/s3_client.rs
new file mode 100644
index 000000000000..e03fadd2d264
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/s3_client.rs
@@ -0,0 +1,123 @@
+//! Shared S3 client setup for the checkpoint uploader and downloader.
+//!
+//! This module provides a unified way to create S3 clients with proper credential resolution for
+//! both production (IRSA) and local dev (MinIO/SeaweedFS).
+
+use anyhow::{Context, Result};
+use futures::StreamExt;
+use object_store::aws::{AmazonS3, AmazonS3Builder};
+use object_store::limit::LimitStore;
+use object_store::path::Path as ObjectPath;
+use object_store::{ClientOptions, ObjectStore};
+use std::sync::Arc;
+use std::time::Duration;
+use tracing::{debug, info};
+
+use super::config::DurabilityConfig;
+
+/// Short timeout for bucket validation so misconfiguration fails fast.
+const VALIDATION_TIMEOUT: Duration = Duration::from_secs(10);
+
+/// Build an S3 client wrapped in a `LimitStore` for bounded concurrency.
+///
+/// Credential priority: explicit config (local dev) → IRSA (`AWS_WEB_IDENTITY_TOKEN_FILE` +
+/// `AWS_ROLE_ARN`) → default AWS credential chain.
+pub async fn create_s3_client(
+ config: &DurabilityConfig,
+ max_concurrent_requests: usize,
+) -> Result<Arc<LimitStore<AmazonS3>>> {
+ let mut builder = AmazonS3Builder::from_env()
+ .with_bucket_name(&config.s3_bucket)
+ .with_client_options(ClientOptions::new().with_timeout(config.s3_attempt_timeout))
+ .with_retry(object_store::RetryConfig {
+ max_retries: config.s3_max_retries,
+ retry_timeout: config.s3_operation_timeout,
+ ..Default::default()
+ });
+
+ if let Some(ref region) = config.aws_region {
+ builder = builder.with_region(region);
+ }
+
+ if let Some(ref endpoint) = config.s3_endpoint {
+ builder = builder.with_endpoint(endpoint);
+ if endpoint.starts_with("http://") {
+ builder = builder.with_allow_http(true);
+ }
+ }
+
+ // Explicit credentials override the env-based chain (for local dev without IAM).
+ if let (Some(ref access_key), Some(ref secret_key)) =
+ (&config.s3_access_key_id, &config.s3_secret_access_key)
+ {
+ info!("Using explicit S3 credentials from config");
+ builder = builder
+ .with_access_key_id(access_key)
+ .with_secret_access_key(secret_key);
+ } else if std::env::var("AWS_WEB_IDENTITY_TOKEN_FILE").is_ok()
+ && std::env::var("AWS_ROLE_ARN").is_ok()
+ {
+ info!("Using IRSA credentials (AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN)");
+ } else {
+ debug!("Using default AWS credential chain");
+ }
+
+ if config.s3_force_path_style {
+ builder = builder.with_virtual_hosted_style_request(false);
+ }
+
+ let base_store = builder.build().with_context(|| {
+ format!(
+ "Failed to create S3 client for bucket '{}' in region '{}'",
+ config.s3_bucket,
+ config.aws_region.as_deref().unwrap_or("default")
+ )
+ })?;
+
+ let store = Arc::new(LimitStore::new(base_store, max_concurrent_requests));
+
+ validate_bucket_access(&store, &config.s3_bucket, &config.aws_region).await?;
+
+ Ok(store)
+}
+
+async fn validate_bucket_access(
+ store: &LimitStore<AmazonS3>,
+ bucket: &str,
+ region: &Option<String>,
+) -> Result<()> {
+ info!(bucket = %bucket, "Validating S3 bucket access...");
+
+ let prefix = ObjectPath::from("");
+ let mut stream = store.list(Some(&prefix));
+
+ match tokio::time::timeout(VALIDATION_TIMEOUT, stream.next()).await {
+ Ok(Some(Err(e))) => Err(anyhow::anyhow!(e)).with_context(|| {
+ format!(
+ "S3 bucket validation failed for '{}' in region '{}' - check bucket exists, credentials, and network",
+ bucket,
+ region.as_deref().unwrap_or("default")
+ )
+ }),
+ Err(_) => Err(anyhow::anyhow!(
+ "S3 bucket validation timed out after {:?} for bucket '{}' - check network connectivity and credentials",
+ VALIDATION_TIMEOUT,
+ bucket
+ )),
+ Ok(Some(Ok(_))) | Ok(None) => {
+ info!(bucket = %bucket, "S3 bucket validated successfully");
+ Ok(())
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn validation_timeout_is_reasonable() {
+ assert!(VALIDATION_TIMEOUT >= Duration::from_secs(5));
+ assert!(VALIDATION_TIMEOUT <= Duration::from_secs(30));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/s3_downloader.rs b/rust/cohort-stream-processor/src/store/durability/s3_downloader.rs
new file mode 100644
index 000000000000..b721bd7895a2
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/s3_downloader.rs
@@ -0,0 +1,421 @@
+use std::path::Path;
+use std::sync::Arc;
+use std::time::Instant;
+
+use tokio_util::bytes::Bytes;
+
+use super::config::DurabilityConfig;
+use super::downloader::CheckpointDownloader;
+use super::error::DownloadCancelledError;
+use super::metadata::{store_hash_prefix, DATE_PLUS_HOURS_ONLY_FORMAT, METADATA_FILENAME};
+use super::s3_client::create_s3_client;
+use super::{STORE_PARTITION, STORE_TOPIC};
+use crate::observability::metrics::{
+ CHECKPOINT_FILES_DOWNLOADED_TOTAL, CHECKPOINT_FILES_FETCH_DURATION_SECONDS,
+ CHECKPOINT_FILE_FETCH_DURATION_SECONDS, CHECKPOINT_FILE_FETCH_STORE_DURATION_SECONDS,
+ CHECKPOINT_LIST_DURATION_SECONDS,
+};
+
+use anyhow::{Context, Result};
+use async_trait::async_trait;
+use chrono::{Duration, Utc};
+use futures::stream;
+use futures::{StreamExt, TryStreamExt};
+use object_store::limit::LimitStore;
+use object_store::path::Path as ObjectPath;
+use object_store::{ObjectStore, ObjectStoreExt};
+use tokio::io::AsyncWriteExt;
+use tokio_util::sync::CancellationToken;
+use tracing::{error, info, warn};
+
+enum ChunkResult {
+ Data(Bytes),
+ EndOfStream,
+ Cancelled,
+ Error(object_store::Error),
+}
+
+/// `biased;` ensures cancellation is checked before polling the stream each iteration.
+async fn next_chunk_cancellable<S>(
+ stream: &mut S,
+ cancel_token: Option<&CancellationToken>,
+) -> ChunkResult
+where
+ S: futures::Stream<Item = Result<Bytes, object_store::Error>> + Unpin,
+{
+ match cancel_token {
+ Some(token) => {
+ tokio::select! {
+ biased;
+
+ _ = token.cancelled() => ChunkResult::Cancelled,
+
+ result = stream.try_next() => match result {
+ Ok(Some(chunk)) => ChunkResult::Data(chunk),
+ Ok(None) => ChunkResult::EndOfStream,
+ Err(e) => ChunkResult::Error(e),
+ }
+ }
+ }
+ None => match stream.try_next().await {
+ Ok(Some(chunk)) => ChunkResult::Data(chunk),
+ Ok(None) => ChunkResult::EndOfStream,
+ Err(e) => ChunkResult::Error(e),
+ },
+ }
+}
+
+/// Build the S3 key prefix for listing checkpoints. Includes the deterministic hash prefix so
+/// metadata and object files share a path. The trailing slash makes it a clean folder boundary, so a
+/// sibling namespace under the same hash can never prefix-match.
+fn format_checkpoint_list_prefix(s3_key_prefix: &str) -> String {
+ format!(
+ "{}/{s3_key_prefix}/{STORE_TOPIC}/{STORE_PARTITION}/",
+ store_hash_prefix()
+ )
+}
+
+/// Classify an object_store error into a short, searchable label for structured logging.
+fn s3_error_kind(e: &object_store::Error) -> &'static str {
+ match e {
+ object_store::Error::NotFound { .. } => "not_found",
+ object_store::Error::PermissionDenied { .. } => "permission_denied",
+ object_store::Error::Unauthenticated { .. } => "unauthenticated",
+ object_store::Error::Precondition { .. } => "precondition",
+ object_store::Error::Generic { .. } => "generic",
+ _ => "other",
+ }
+}
+
+/// Each download holds a `LimitStore` permit for the entire stream duration, bounding in-flight
+/// memory.
+#[derive(Debug)]
+pub struct S3Downloader {
+ store: Arc<LimitStore<object_store::aws::AmazonS3>>,
+ s3_bucket: String,
+ s3_key_prefix: String,
+ checkpoint_import_window_hours: u32,
+ max_concurrent_file_downloads: usize,
+}
+
+impl S3Downloader {
+ pub async fn new(config: &DurabilityConfig) -> Result<Self> {
+ let store =
+ create_s3_client(config, config.max_concurrent_checkpoint_file_downloads).await?;
+
+ info!(
+ "S3 downloader initialized for bucket '{}' with max {} concurrent downloads",
+ config.s3_bucket, config.max_concurrent_checkpoint_file_downloads
+ );
+
+ Ok(Self {
+ store,
+ s3_bucket: config.s3_bucket.clone(),
+ s3_key_prefix: config.s3_key_prefix.clone(),
+ checkpoint_import_window_hours: config.checkpoint_import_window_hours,
+ max_concurrent_file_downloads: config.max_concurrent_checkpoint_file_downloads,
+ })
+ }
+}
+
+#[async_trait]
+impl CheckpointDownloader for S3Downloader {
+ async fn download_file(&self, remote_key: &str) -> Result<Vec<u8>> {
+ let start_time = Instant::now();
+ let path = ObjectPath::from(remote_key);
+
+ let result = match self.store.get(&path).await {
+ Ok(result) => {
+ metrics::counter!(CHECKPOINT_FILES_DOWNLOADED_TOTAL, "status" => "success")
+ .increment(1);
+ result
+ }
+ Err(e) => {
+ let error_kind = s3_error_kind(&e);
+ error!(
+ remote_key,
+ bucket = %self.s3_bucket,
+ error_kind,
+ error = %e,
+ "S3 object download failed"
+ );
+ metrics::counter!(CHECKPOINT_FILES_DOWNLOADED_TOTAL, "status" => "error")
+ .increment(1);
+ return Err(anyhow::anyhow!(e)).with_context(|| {
+ format!(
+ "Failed to get object from S3 bucket {}: {remote_key}",
+ self.s3_bucket
+ )
+ });
+ }
+ };
+
+ // Buffers the whole response into memory; only used for small metadata.json files.
+ let body = result.bytes().await.with_context(|| {
+ format!(
+ "Failed to read body data from S3 object from bucket {}: {remote_key}",
+ self.s3_bucket,
+ )
+ })?;
+
+ let elapsed = start_time.elapsed();
+ metrics::histogram!(CHECKPOINT_FILE_FETCH_DURATION_SECONDS).record(elapsed.as_secs_f64());
+ Ok(body.to_vec())
+ }
+
+ async fn download_and_store_file_cancellable(
+ &self,
+ remote_key: &str,
+ local_filepath: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ let start_time = Instant::now();
+
+ if let Some(token) = cancel_token {
+ if token.is_cancelled() {
+ warn!("Download cancelled before starting: {remote_key}");
+ return Err(DownloadCancelledError {
+ reason: format!("before starting: {remote_key}"),
+ }
+ .into());
+ }
+ }
+
+ let path = ObjectPath::from(remote_key);
+
+ let result = match self.store.get(&path).await {
+ Ok(result) => result,
+ Err(e) => {
+ let error_kind = s3_error_kind(&e);
+ error!(
+ remote_key,
+ bucket = %self.s3_bucket,
+ error_kind,
+ error = %e,
+ "S3 object download failed"
+ );
+ metrics::counter!(CHECKPOINT_FILES_DOWNLOADED_TOTAL, "status" => "error")
+ .increment(1);
+ return Err(anyhow::anyhow!(e)).with_context(|| {
+ format!(
+ "Failed to get object from S3 bucket {}: {remote_key}",
+ self.s3_bucket
+ )
+ });
+ }
+ };
+
+ let mut file = tokio::fs::File::create(local_filepath)
+ .await
+ .with_context(|| format!("Failed to create local file: {local_filepath:?}"))?;
+
+ let mut stream = result.into_stream();
+
+ loop {
+ let chunk_result = next_chunk_cancellable(&mut stream, cancel_token).await;
+
+ match chunk_result {
+ ChunkResult::Data(chunk) => {
+ if let Err(e) = file.write_all(&chunk).await {
+ metrics::counter!(CHECKPOINT_FILES_DOWNLOADED_TOTAL, "status" => "error")
+ .increment(1);
+ return Err(e).with_context(|| {
+ format!("Failed to write chunk to local file: {local_filepath:?}")
+ });
+ }
+ }
+ ChunkResult::EndOfStream => break,
+ ChunkResult::Cancelled => {
+ drop(file);
+ drop(tokio::fs::remove_file(local_filepath).await);
+ metrics::counter!(CHECKPOINT_FILES_DOWNLOADED_TOTAL, "status" => "cancelled")
+ .increment(1);
+ warn!("Download of {remote_key} cancelled mid-stream");
+ return Err(DownloadCancelledError {
+ reason: format!("mid-stream: {remote_key}"),
+ }
+ .into());
+ }
+ ChunkResult::Error(e) => {
+ metrics::counter!(CHECKPOINT_FILES_DOWNLOADED_TOTAL, "status" => "error")
+ .increment(1);
+ return Err(anyhow::anyhow!(e)).with_context(|| {
+ format!("Failed to read chunk from S3 stream: {remote_key}")
+ });
+ }
+ }
+ }
+
+ file.flush()
+ .await
+ .with_context(|| format!("Failed to flush file: {local_filepath:?}"))?;
+
+ metrics::counter!(CHECKPOINT_FILES_DOWNLOADED_TOTAL, "status" => "success").increment(1);
+ let elapsed = start_time.elapsed();
+ metrics::histogram!(CHECKPOINT_FILE_FETCH_STORE_DURATION_SECONDS)
+ .record(elapsed.as_secs_f64());
+
+ info!("Downloaded remote file {remote_key} to {local_filepath:?}");
+ Ok(())
+ }
+
+ async fn download_files_cancellable(
+ &self,
+ remote_keys: &[String],
+ local_base_path: &Path,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ let start_time = Instant::now();
+ let file_count = remote_keys.len();
+
+ if let Some(token) = cancel_token {
+ if token.is_cancelled() {
+ warn!("Download cancelled before starting");
+ return Err(DownloadCancelledError {
+ reason: "before starting batch".to_string(),
+ }
+ .into());
+ }
+ }
+
+ // Pre-collect owned (key, path) pairs so closures capture owned data, not borrowed refs.
+ let download_tasks: Vec<_> = remote_keys
+ .iter()
+ .map(|remote_key| {
+ let remote_filename = remote_key
+ .rsplit('/')
+ .next()
+ .unwrap_or(remote_key)
+ .to_string();
+ let local_filepath = local_base_path.join(&remote_filename);
+ (remote_key.clone(), local_filepath)
+ })
+ .collect();
+
+ let mut stream = stream::iter(download_tasks)
+ .map(|(remote_key, local_filepath)| async move {
+ self.download_and_store_file_cancellable(&remote_key, &local_filepath, cancel_token)
+ .await
+ .with_context(|| format!("Failed to download: {remote_key}"))
+ })
+ .buffer_unordered(self.max_concurrent_file_downloads);
+
+ let mut first_error: Option<anyhow::Error> = None;
+
+ while let Some(result) = stream.next().await {
+ if let Err(e) = result {
+ first_error = Some(e);
+ if let Some(token) = cancel_token {
+ token.cancel();
+ }
+ break;
+ }
+ }
+
+ if first_error.is_some() {
+ while stream.next().await.is_some() {}
+ }
+
+ if let Some(e) = first_error {
+ return Err(e);
+ }
+
+ let elapsed = start_time.elapsed();
+ metrics::histogram!(CHECKPOINT_FILES_FETCH_DURATION_SECONDS).record(elapsed.as_secs_f64());
+ info!("Successfully downloaded checkpoint with {file_count} files to local path: {local_base_path:?}");
+
+ Ok(())
+ }
+
+ async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
+ let start_time = Instant::now();
+ let import_window_hours = Duration::hours(i64::from(self.checkpoint_import_window_hours));
+ let remote_key_prefix = format_checkpoint_list_prefix(&self.s3_key_prefix);
+ let cutoff = Utc::now() - import_window_hours;
+ let cutoff_id = cutoff.format(DATE_PLUS_HOURS_ONLY_FORMAT).to_string();
+
+ info!(
+ "Listing checkpoint folders newer than {cutoff_id} from S3 bucket: {}",
+ self.s3_bucket
+ );
+
+ // Shallow list (delimiter="/"): returns only the common prefixes (checkpoint folders).
+ let prefix = ObjectPath::from(remote_key_prefix.as_str());
+ let result = self
+ .store
+ .list_with_delimiter(Some(&prefix))
+ .await
+ .context("listing checkpoint folders from S3")?;
+
+ // Keep folders at or after the cutoff and map them to their metadata.json keys.
+ let mut metadata_keys: Vec<String> = result
+ .common_prefixes
+ .into_iter()
+ .filter(|cp| {
+ let path_str = cp.as_ref();
+ let checkpoint_id = path_str.rsplit('/').find(|s| !s.is_empty()).unwrap_or("");
+ checkpoint_id >= cutoff_id.as_str()
+ })
+ .map(|cp| format!("{}/{}", cp.as_ref(), METADATA_FILENAME))
+ .collect();
+
+ // Checkpoint IDs are timestamps, so reverse lexicographic order = newest first.
+ metadata_keys.sort_unstable();
+ metadata_keys.reverse();
+
+ let elapsed = start_time.elapsed();
+ metrics::histogram!(CHECKPOINT_LIST_DURATION_SECONDS).record(elapsed.as_secs_f64());
+ info!(
+ "Found {} checkpoint folders at or after {cutoff_id}",
+ metadata_keys.len(),
+ );
+
+ Ok(metadata_keys)
+ }
+
+ async fn is_available(&self) -> bool {
+ !self.s3_bucket.is_empty()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn format_checkpoint_list_prefix_uses_the_single_db_identity() {
+ let hash = store_hash_prefix();
+ let prefix = format_checkpoint_list_prefix("checkpoints");
+ assert_eq!(
+ prefix,
+ format!("{hash}/checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/")
+ );
+ }
+
+ #[test]
+ fn format_checkpoint_list_prefix_has_a_trailing_slash_folder_boundary() {
+ let prefix = format_checkpoint_list_prefix("checkpoints");
+ assert!(prefix.ends_with('/'));
+
+ let hash = store_hash_prefix();
+ // A real key under this prefix matches; a key with a longer trailing namespace does not.
+ let key = format!(
+ "{hash}/checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/2026-01-22T12-00-00Z/metadata.json"
+ );
+ let sibling = format!(
+ "{hash}/checkpoints-other/{STORE_TOPIC}/{STORE_PARTITION}/2026-01-22T12-00-00Z/metadata.json"
+ );
+ assert!(key.starts_with(&prefix));
+ assert!(!sibling.starts_with(&prefix));
+ }
+
+ #[test]
+ fn format_checkpoint_list_prefix_with_namespaced_key_prefix() {
+ let hash = store_hash_prefix();
+ let prefix = format_checkpoint_list_prefix("env/prod/checkpoints");
+ assert_eq!(
+ prefix,
+ format!("{hash}/env/prod/checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/")
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/s3_uploader.rs b/rust/cohort-stream-processor/src/store/durability/s3_uploader.rs
new file mode 100644
index 000000000000..1ea99f70c77d
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/s3_uploader.rs
@@ -0,0 +1,354 @@
+use anyhow::{Context, Result};
+use async_trait::async_trait;
+use futures::stream;
+use futures::StreamExt;
+use object_store::buffered::BufWriter;
+use object_store::path::Path as ObjectPath;
+use object_store::{ObjectStore, ObjectStoreExt, PutPayload};
+use std::path::Path;
+use std::sync::Arc;
+use tokio::fs::File;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio_util::sync::CancellationToken;
+use tracing::{info, warn};
+
+use super::config::DurabilityConfig;
+use super::error::UploadCancelledError;
+use super::s3_client::create_s3_client;
+use super::uploader::CheckpointUploader;
+use crate::observability::metrics::CHECKPOINT_FILES_UPLOADED_TOTAL;
+
+const UPLOAD_CHUNK_SIZE: usize = 8 * 1024 * 1024; // 8MB
+
+enum ChunkResult {
+ Data(usize),
+ EndOfStream,
+ Cancelled,
+ Error(std::io::Error),
+}
+
+/// `biased;` ensures cancellation is checked before each read attempt.
+async fn read_chunk_cancellable(
+ file: &mut File,
+ buf: &mut [u8],
+ cancel_token: Option<&CancellationToken>,
+) -> ChunkResult {
+ match cancel_token {
+ Some(token) => {
+ tokio::select! {
+ biased;
+
+ _ = token.cancelled() => ChunkResult::Cancelled,
+
+ result = file.read(buf) => match result {
+ Ok(0) => ChunkResult::EndOfStream,
+ Ok(n) => ChunkResult::Data(n),
+ Err(e) => ChunkResult::Error(e),
+ }
+ }
+ }
+ None => match file.read(buf).await {
+ Ok(0) => ChunkResult::EndOfStream,
+ Ok(n) => ChunkResult::Data(n),
+ Err(e) => ChunkResult::Error(e),
+ },
+ }
+}
+
+#[derive(Debug)]
+pub struct S3Uploader {
+ store: Arc<dyn ObjectStore>,
+ config: DurabilityConfig,
+}
+
+impl S3Uploader {
+ pub async fn new(config: DurabilityConfig) -> Result<Self> {
+ let store =
+ create_s3_client(&config, config.max_concurrent_checkpoint_file_uploads).await?;
+
+ info!(
+ "S3 uploader initialized for bucket '{}' with max {} concurrent uploads",
+ config.s3_bucket, config.max_concurrent_checkpoint_file_uploads
+ );
+
+ let store: Arc<dyn ObjectStore> = store;
+ Ok(Self { store, config })
+ }
+
+ /// Upload a file with cancellation support.
+ /// On cancellation or error, calls `abort()` to clean up multipart upload parts.
+ async fn upload_file_cancellable(
+ &self,
+ local_path: &Path,
+ s3_key: &str,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<()> {
+ if let Some(token) = cancel_token {
+ if token.is_cancelled() {
+ metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "cancelled")
+ .increment(1);
+ warn!("Upload cancelled before starting: {s3_key}");
+ return Err(UploadCancelledError {
+ reason: format!("before starting: {s3_key}"),
+ }
+ .into());
+ }
+ }
+
+ let path = ObjectPath::from(s3_key);
+
+ let mut file = File::open(local_path)
+ .await
+ .with_context(|| format!("Failed to open file: {local_path:?}"))?;
+
+ let file_size = file
+ .metadata()
+ .await
+ .with_context(|| format!("Failed to get metadata for file: {local_path:?}"))?
+ .len();
+
+ // BufWriter switches to multipart upload automatically for large files.
+ let mut upload = BufWriter::new(Arc::clone(&self.store), path.clone());
+
+ let mut buf = vec![0u8; UPLOAD_CHUNK_SIZE];
+
+ loop {
+ let chunk_result = read_chunk_cancellable(&mut file, &mut buf, cancel_token).await;
+
+ match chunk_result {
+ ChunkResult::Data(n) => {
+ if let Err(e) = upload.write_all(&buf[..n]).await {
+ drop(upload.abort().await);
+ metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "error")
+ .increment(1);
+ return Err(anyhow::Error::new(e))
+ .with_context(|| format!("Failed to write chunk to S3: {s3_key}"));
+ }
+ }
+ ChunkResult::EndOfStream => break,
+ ChunkResult::Cancelled => {
+ drop(upload.abort().await);
+ metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "cancelled")
+ .increment(1);
+ warn!("Upload of {s3_key} cancelled mid-stream");
+ return Err(UploadCancelledError {
+ reason: format!("mid-stream: {s3_key}"),
+ }
+ .into());
+ }
+ ChunkResult::Error(e) => {
+ drop(upload.abort().await);
+ metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "error")
+ .increment(1);
+ return Err(anyhow::Error::new(e)).with_context(|| {
+ format!("Failed to read chunk from file: {local_path:?}")
+ });
+ }
+ }
+ }
+
+ upload
+ .shutdown()
+ .await
+ .with_context(|| format!("Failed to complete upload for: {s3_key}"))?;
+
+ metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "success").increment(1);
+ info!(
+ "Uploaded file {local_path:?} ({file_size} bytes) to s3://{}/{}",
+ self.config.s3_bucket, s3_key
+ );
+ Ok(())
+ }
+
+ async fn upload_bytes(&self, s3_key: &str, data: Vec<u8>) -> Result<()> {
+ let path = ObjectPath::from(s3_key);
+
+ self.store
+ .put(&path, PutPayload::from(data))
+ .await
+ .with_context(|| format!("Failed to upload to S3 key: {s3_key}"))?;
+
+ Ok(())
+ }
+}
+
+#[async_trait]
+impl CheckpointUploader for S3Uploader {
+ async fn upload_checkpoint_with_plan_cancellable(
+ &self,
+ plan: &super::CheckpointPlan,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<Vec<String>> {
+ if let Some(token) = cancel_token {
+ if token.is_cancelled() {
+ warn!("Upload cancelled before starting batch");
+ return Err(UploadCancelledError {
+ reason: "before starting batch".to_string(),
+ }
+ .into());
+ }
+ }
+
+ info!(
+ "Starting upload with plan: {} files to upload, {} files referenced from parents",
+ plan.files_to_upload.len(),
+ plan.info.metadata.files.len() - plan.files_to_upload.len()
+ );
+
+ // Child token: a failed file cancels siblings without cancelling the caller.
+ let upload_token = cancel_token
+ .map(|parent| parent.child_token())
+ .unwrap_or_default();
+
+ // At most N files open simultaneously: N * ~18MB (8MB read buf + ~10MB BufWriter).
+ let upload_tasks: Vec<_> = plan
+ .files_to_upload
+ .iter()
+ .map(|f| (f.local_path.clone(), plan.info.get_file_key(&f.filename)))
+ .collect();
+
+ let mut stream = stream::iter(upload_tasks)
+ .map(|(src, dest)| {
+ let token = upload_token.clone();
+ async move {
+ self.upload_file_cancellable(&src, &dest, Some(&token))
+ .await?;
+ Ok::<String, anyhow::Error>(dest)
+ }
+ })
+ .buffer_unordered(self.config.max_upload_buffers);
+
+ let mut uploaded_keys = Vec::with_capacity(plan.files_to_upload.len());
+ let mut first_error: Option<anyhow::Error> = None;
+
+ while let Some(result) = stream.next().await {
+ match result {
+ Ok(key) => uploaded_keys.push(key),
+ Err(e) => {
+ first_error = Some(e);
+ upload_token.cancel();
+ break;
+ }
+ }
+ }
+
+ while stream.next().await.is_some() {}
+
+ // Metadata is uploaded last so a partial upload is never discoverable via metadata.json.
+ if let Some(e) = first_error {
+ return Err(e);
+ }
+
+ if let Some(token) = cancel_token {
+ if token.is_cancelled() {
+ warn!("Upload cancelled before metadata upload");
+ return Err(UploadCancelledError {
+ reason: "before metadata upload".to_string(),
+ }
+ .into());
+ }
+ }
+
+ let metadata_json = plan.info.metadata.to_json()?;
+ let metadata_key = plan.info.get_metadata_key();
+ self.upload_bytes(&metadata_key, metadata_json.into_bytes())
+ .await
+ .with_context(|| format!("Failed to upload metadata to S3 key: {metadata_key}"))?;
+
+ info!(
+ "Uploaded {} files and metadata file to s3://{}/{}",
+ plan.files_to_upload.len(),
+ self.config.s3_bucket,
+ plan.info.get_remote_attempt_path(),
+ );
+
+ let mut all_keys = uploaded_keys;
+ all_keys.push(metadata_key);
+ Ok(all_keys)
+ }
+
+ async fn is_available(&self) -> bool {
+ !self.config.s3_bucket.is_empty()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+ use tokio::io::AsyncWriteExt;
+
+ #[tokio::test]
+ async fn read_chunk_cancellable_returns_data_without_token() {
+ let tmp_dir = TempDir::new().unwrap();
+ let file_path = tmp_dir.path().join("test_file.txt");
+
+ let mut file = tokio::fs::File::create(&file_path).await.unwrap();
+ file.write_all(b"hello world").await.unwrap();
+ file.flush().await.unwrap();
+ drop(file);
+
+ let mut file = tokio::fs::File::open(&file_path).await.unwrap();
+ let mut buf = vec![0u8; 1024];
+
+ let result = read_chunk_cancellable(&mut file, &mut buf, None).await;
+ match result {
+ ChunkResult::Data(n) => {
+ assert_eq!(n, 11);
+ assert_eq!(&buf[..n], b"hello world");
+ }
+ _ => panic!("Expected Data result"),
+ }
+
+ let result = read_chunk_cancellable(&mut file, &mut buf, None).await;
+ assert!(matches!(result, ChunkResult::EndOfStream));
+ }
+
+ #[tokio::test]
+ async fn read_chunk_cancellable_returns_cancelled_when_pre_cancelled() {
+ let tmp_dir = TempDir::new().unwrap();
+ let file_path = tmp_dir.path().join("test_file.txt");
+
+ let mut file = tokio::fs::File::create(&file_path).await.unwrap();
+ file.write_all(b"hello world").await.unwrap();
+ file.flush().await.unwrap();
+ drop(file);
+
+ let token = CancellationToken::new();
+ token.cancel();
+
+ let mut file = tokio::fs::File::open(&file_path).await.unwrap();
+ let mut buf = vec![0u8; 1024];
+
+ let result = read_chunk_cancellable(&mut file, &mut buf, Some(&token)).await;
+ assert!(
+ matches!(result, ChunkResult::Cancelled),
+ "Expected Cancelled result"
+ );
+ }
+
+ #[tokio::test]
+ async fn read_chunk_cancellable_returns_data_with_active_token() {
+ let tmp_dir = TempDir::new().unwrap();
+ let file_path = tmp_dir.path().join("test_file.txt");
+
+ let mut file = tokio::fs::File::create(&file_path).await.unwrap();
+ file.write_all(b"hello world").await.unwrap();
+ file.flush().await.unwrap();
+ drop(file);
+
+ let token = CancellationToken::new();
+
+ let mut file = tokio::fs::File::open(&file_path).await.unwrap();
+ let mut buf = vec![0u8; 1024];
+
+ let result = read_chunk_cancellable(&mut file, &mut buf, Some(&token)).await;
+ match result {
+ ChunkResult::Data(n) => {
+ assert_eq!(n, 11);
+ assert_eq!(&buf[..n], b"hello world");
+ }
+ _ => panic!("Expected Data result"),
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/uploader.rs b/rust/cohort-stream-processor/src/store/durability/uploader.rs
new file mode 100644
index 000000000000..0017a73ea443
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/uploader.rs
@@ -0,0 +1,22 @@
+use anyhow::Result;
+use async_trait::async_trait;
+use tokio_util::sync::CancellationToken;
+
+use super::CheckpointPlan;
+
+#[async_trait]
+pub trait CheckpointUploader: Send + Sync + std::fmt::Debug {
+ async fn upload_checkpoint_with_plan(&self, plan: &CheckpointPlan) -> Result<Vec<String>> {
+ self.upload_checkpoint_with_plan_cancellable(plan, None)
+ .await
+ }
+
+ /// On cancellation, aborts any in-progress multipart uploads to prevent ghost parts.
+ async fn upload_checkpoint_with_plan_cancellable(
+ &self,
+ plan: &CheckpointPlan,
+ cancel_token: Option<&CancellationToken>,
+ ) -> Result<Vec<String>>;
+
+ async fn is_available(&self) -> bool;
+}
diff --git a/rust/cohort-stream-processor/src/store/keys.rs b/rust/cohort-stream-processor/src/store/keys.rs
new file mode 100644
index 000000000000..8bf5e405c5ae
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/keys.rs
@@ -0,0 +1,573 @@
+//! Typed, partition-prefixed key encoders for the state column families.
+//!
+//! Keys are fixed-size big-endian so a partition's state is one contiguous `delete_range`.
+
+use uuid::Uuid;
+
+use super::rocks::StoreError;
+use crate::stage1::key::{LeafStateKey, Stage1Key};
+
+/// `[partition_id u16][team_id u64][leaf_state_key 16][person_id 16]`.
+pub const STAGE1_KEY_LEN: usize = 2 + 8 + 16 + 16;
+/// `[partition_id u16][team_id u64][person_id 16]`.
+pub const PERSON_INDEX_KEY_LEN: usize = 2 + 8 + 16;
+/// `[partition_id u16][team_id u64][cohort_id u64][person_id 16]`.
+pub const STAGE2_KEY_LEN: usize = 2 + 8 + 8 + 16;
+/// `[partition_id u16][team_id u64][old_person 16][merge_msg_partition u32][merge_msg_offset u64]`.
+pub const MERGE_DRAIN_KEY_LEN: usize = 2 + 8 + 16 + 4 + 8;
+/// `[partition_id u16][team_id u64][old_person 16]`.
+pub const PENDING_TRANSFER_KEY_LEN: usize = 2 + 8 + 16;
+/// `[partition_id u16][team_id u64][new_person 16][source_partition u32][source_offset u64]`.
+pub const MERGE_APPLIED_KEY_LEN: usize = 2 + 8 + 16 + 4 + 8;
+/// `[partition_id u16][team_id u64][person 16]`.
+pub const TOMBSTONE_KEY_LEN: usize = 2 + 8 + 16;
+
+/// `cf_person_index` key: a person's Stage 1 leaf states live under this prefix.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct PersonIndexKey {
+ pub partition_id: u16,
+ pub team_id: u64,
+ pub person_id: Uuid,
+}
+
+/// `cf_stage2` key: per-`(cohort, person)` membership state.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct Stage2Key {
+ pub partition_id: u16,
+ pub team_id: u64,
+ pub cohort_id: u64,
+ pub person_id: Uuid,
+}
+
+/// `cf_merge_drains_applied` key: Phase 1 idempotence marker for one merge message.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct MergeDrainKey {
+ pub partition_id: u16,
+ pub team_id: u64,
+ pub old_person: Uuid,
+ /// Kafka partition of the merge message.
+ pub merge_msg_partition: i32,
+ /// Kafka offset of the merge message.
+ pub merge_msg_offset: i64,
+}
+
+/// `cf_pending_transfers` key: Phase 1 outbox slot for a person's drained state.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct PendingTransferKey {
+ pub partition_id: u16,
+ pub team_id: u64,
+ pub old_person: Uuid,
+}
+
+/// `cf_merge_applied` key: Phase 2 idempotence marker, keyed by the triggering merge message's
+/// Kafka coordinates (not the transfer message's own) so duplicate transfer copies all short-circuit.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct MergeAppliedKey {
+ pub partition_id: u16,
+ pub team_id: u64,
+ pub new_person: Uuid,
+ /// Kafka partition of the triggering merge message.
+ pub source_partition: i32,
+ /// Kafka offset of the triggering merge message.
+ pub source_offset: i64,
+}
+
+/// `cf_merge_tombstones` key: redirect marker for a merged-away person.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct TombstoneKey {
+ pub partition_id: u16,
+ pub team_id: u64,
+ pub person: Uuid,
+}
+
+impl Stage1Key {
+ pub fn encode(&self) -> [u8; STAGE1_KEY_LEN] {
+ let mut out = [0u8; STAGE1_KEY_LEN];
+ out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());
+ out[2..10].copy_from_slice(&self.team_id.to_be_bytes());
+ out[10..26].copy_from_slice(&self.leaf_state_key.0);
+ out[26..42].copy_from_slice(self.person_id.as_bytes());
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, STAGE1_KEY_LEN, "stage1")?;
+ Ok(Self {
+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),
+ team_id: u64::from_be_bytes(array8(&bytes[2..10])),
+ leaf_state_key: LeafStateKey(array16(&bytes[10..26])),
+ person_id: Uuid::from_bytes(array16(&bytes[26..42])),
+ })
+ }
+}
+
+impl PersonIndexKey {
+ pub fn encode(&self) -> [u8; PERSON_INDEX_KEY_LEN] {
+ let mut out = [0u8; PERSON_INDEX_KEY_LEN];
+ out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());
+ out[2..10].copy_from_slice(&self.team_id.to_be_bytes());
+ out[10..26].copy_from_slice(self.person_id.as_bytes());
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, PERSON_INDEX_KEY_LEN, "person_index")?;
+ Ok(Self {
+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),
+ team_id: u64::from_be_bytes(array8(&bytes[2..10])),
+ person_id: Uuid::from_bytes(array16(&bytes[10..26])),
+ })
+ }
+}
+
+impl Stage2Key {
+ pub fn encode(&self) -> [u8; STAGE2_KEY_LEN] {
+ let mut out = [0u8; STAGE2_KEY_LEN];
+ out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());
+ out[2..10].copy_from_slice(&self.team_id.to_be_bytes());
+ out[10..18].copy_from_slice(&self.cohort_id.to_be_bytes());
+ out[18..34].copy_from_slice(self.person_id.as_bytes());
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, STAGE2_KEY_LEN, "stage2")?;
+ Ok(Self {
+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),
+ team_id: u64::from_be_bytes(array8(&bytes[2..10])),
+ cohort_id: u64::from_be_bytes(array8(&bytes[10..18])),
+ person_id: Uuid::from_bytes(array16(&bytes[18..34])),
+ })
+ }
+}
+
+impl MergeDrainKey {
+ pub fn encode(&self) -> [u8; MERGE_DRAIN_KEY_LEN] {
+ let mut out = [0u8; MERGE_DRAIN_KEY_LEN];
+ out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());
+ out[2..10].copy_from_slice(&self.team_id.to_be_bytes());
+ out[10..26].copy_from_slice(self.old_person.as_bytes());
+ out[26..30].copy_from_slice(&(self.merge_msg_partition as u32).to_be_bytes());
+ out[30..38].copy_from_slice(&(self.merge_msg_offset as u64).to_be_bytes());
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, MERGE_DRAIN_KEY_LEN, "merge_drain")?;
+ Ok(Self {
+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),
+ team_id: u64::from_be_bytes(array8(&bytes[2..10])),
+ old_person: Uuid::from_bytes(array16(&bytes[10..26])),
+ merge_msg_partition: u32::from_be_bytes(array4(&bytes[26..30])) as i32,
+ merge_msg_offset: u64::from_be_bytes(array8(&bytes[30..38])) as i64,
+ })
+ }
+}
+
+impl PendingTransferKey {
+ pub fn encode(&self) -> [u8; PENDING_TRANSFER_KEY_LEN] {
+ let mut out = [0u8; PENDING_TRANSFER_KEY_LEN];
+ out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());
+ out[2..10].copy_from_slice(&self.team_id.to_be_bytes());
+ out[10..26].copy_from_slice(self.old_person.as_bytes());
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, PENDING_TRANSFER_KEY_LEN, "pending_transfer")?;
+ Ok(Self {
+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),
+ team_id: u64::from_be_bytes(array8(&bytes[2..10])),
+ old_person: Uuid::from_bytes(array16(&bytes[10..26])),
+ })
+ }
+}
+
+impl MergeAppliedKey {
+ pub fn encode(&self) -> [u8; MERGE_APPLIED_KEY_LEN] {
+ let mut out = [0u8; MERGE_APPLIED_KEY_LEN];
+ out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());
+ out[2..10].copy_from_slice(&self.team_id.to_be_bytes());
+ out[10..26].copy_from_slice(self.new_person.as_bytes());
+ out[26..30].copy_from_slice(&(self.source_partition as u32).to_be_bytes());
+ out[30..38].copy_from_slice(&(self.source_offset as u64).to_be_bytes());
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, MERGE_APPLIED_KEY_LEN, "merge_applied")?;
+ Ok(Self {
+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),
+ team_id: u64::from_be_bytes(array8(&bytes[2..10])),
+ new_person: Uuid::from_bytes(array16(&bytes[10..26])),
+ source_partition: u32::from_be_bytes(array4(&bytes[26..30])) as i32,
+ source_offset: u64::from_be_bytes(array8(&bytes[30..38])) as i64,
+ })
+ }
+}
+
+impl TombstoneKey {
+ pub fn encode(&self) -> [u8; TOMBSTONE_KEY_LEN] {
+ let mut out = [0u8; TOMBSTONE_KEY_LEN];
+ out[0..2].copy_from_slice(&self.partition_id.to_be_bytes());
+ out[2..10].copy_from_slice(&self.team_id.to_be_bytes());
+ out[10..26].copy_from_slice(self.person.as_bytes());
+ out
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, TOMBSTONE_KEY_LEN, "tombstone")?;
+ Ok(Self {
+ partition_id: u16::from_be_bytes(array2(&bytes[0..2])),
+ team_id: u64::from_be_bytes(array8(&bytes[2..10])),
+ person: Uuid::from_bytes(array16(&bytes[10..26])),
+ })
+ }
+}
+
+pub fn partition_prefix(partition_id: u16) -> [u8; 2] {
+ partition_id.to_be_bytes()
+}
+
+/// Half-open `[start, end)` byte range covering exactly one partition's keys, for `delete_range`.
+pub fn partition_range(partition_id: u16) -> (Vec<u8>, Vec<u8>) {
+ let start = partition_id.to_be_bytes().to_vec();
+ let end = match partition_id.checked_add(1) {
+ Some(next) => next.to_be_bytes().to_vec(),
+ None => vec![0xFFu8; STAGE1_KEY_LEN + 1],
+ };
+ (start, end)
+}
+
+fn check_len(bytes: &[u8], expected: usize, kind: &'static str) -> Result<(), StoreError> {
+ if bytes.len() == expected {
+ Ok(())
+ } else {
+ Err(StoreError::KeyDecode {
+ kind,
+ expected,
+ actual: bytes.len(),
+ })
+ }
+}
+
+fn array2(s: &[u8]) -> [u8; 2] {
+ let mut a = [0u8; 2];
+ a.copy_from_slice(s);
+ a
+}
+fn array4(s: &[u8]) -> [u8; 4] {
+ let mut a = [0u8; 4];
+ a.copy_from_slice(s);
+ a
+}
+fn array8(s: &[u8]) -> [u8; 8] {
+ let mut a = [0u8; 8];
+ a.copy_from_slice(s);
+ a
+}
+fn array16(s: &[u8]) -> [u8; 16] {
+ let mut a = [0u8; 16];
+ a.copy_from_slice(s);
+ a
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn lsk(b: u8) -> LeafStateKey {
+ LeafStateKey([b; 16])
+ }
+
+ fn person(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+ }
+
+ fn stage1(partition_id: u16, team_id: u64) -> Stage1Key {
+ Stage1Key {
+ partition_id,
+ team_id,
+ leaf_state_key: lsk(0xAB),
+ person_id: person(1),
+ }
+ }
+
+ #[test]
+ fn encoded_lengths_are_exact() {
+ assert_eq!(stage1(1, 2).encode().len(), 42);
+ assert_eq!(STAGE1_KEY_LEN, 42);
+ assert_eq!(
+ PersonIndexKey {
+ partition_id: 1,
+ team_id: 2,
+ person_id: person(3),
+ }
+ .encode()
+ .len(),
+ 26,
+ );
+ assert_eq!(PERSON_INDEX_KEY_LEN, 26);
+ assert_eq!(
+ Stage2Key {
+ partition_id: 1,
+ team_id: 2,
+ cohort_id: 3,
+ person_id: person(4),
+ }
+ .encode()
+ .len(),
+ 34,
+ );
+ assert_eq!(STAGE2_KEY_LEN, 34);
+ }
+
+ #[test]
+ fn stage1_round_trips() {
+ let key = Stage1Key {
+ partition_id: 0xBEEF,
+ team_id: 0x0123_4567_89AB_CDEF,
+ leaf_state_key: lsk(0x5A),
+ person_id: person(0xDEAD_BEEF),
+ };
+ assert_eq!(Stage1Key::decode(&key.encode()).unwrap(), key);
+ }
+
+ #[test]
+ fn person_index_round_trips() {
+ let key = PersonIndexKey {
+ partition_id: 7,
+ team_id: 42,
+ person_id: person(0xFEED),
+ };
+ assert_eq!(PersonIndexKey::decode(&key.encode()).unwrap(), key);
+ }
+
+ #[test]
+ fn stage2_round_trips() {
+ let key = Stage2Key {
+ partition_id: 7,
+ team_id: 42,
+ cohort_id: 99,
+ person_id: person(0xC0FFEE),
+ };
+ assert_eq!(Stage2Key::decode(&key.encode()).unwrap(), key);
+ }
+
+ #[test]
+ fn decode_rejects_wrong_length() {
+ let err = Stage1Key::decode(&[0u8; 41]).unwrap_err();
+ assert!(
+ matches!(
+ err,
+ StoreError::KeyDecode {
+ kind: "stage1",
+ expected: 42,
+ actual: 41
+ }
+ ),
+ "unexpected error: {err:?}",
+ );
+ }
+
+ #[test]
+ fn big_endian_prefix_orders_by_partition_then_team() {
+ assert!(stage1(1, u64::MAX).encode() < stage1(2, 0).encode());
+ assert!(stage1(1, 0).encode() < stage1(256, 0).encode());
+ assert!(stage1(5, 1).encode() < stage1(5, 2).encode());
+ assert!(stage1(5, 1).encode() < stage1(5, u64::from(u32::MAX)).encode());
+ }
+
+ #[test]
+ fn partition_range_is_the_two_byte_successor() {
+ let (start, end) = partition_range(0);
+ assert_eq!(start, vec![0x00, 0x00]);
+ assert_eq!(end, vec![0x00, 0x01]);
+
+ let (start, end) = partition_range(255);
+ assert_eq!(start, vec![0x00, 0xFF]);
+ assert_eq!(end, vec![0x01, 0x00]);
+ }
+
+ #[test]
+ fn partition_range_brackets_every_key_in_the_partition() {
+ for p in [0u16, 5, 256, u16::MAX - 1, u16::MAX] {
+ let (start, end) = partition_range(p);
+ let max_key = Stage1Key {
+ partition_id: p,
+ team_id: u64::MAX,
+ leaf_state_key: lsk(0xFF),
+ person_id: person(u128::MAX),
+ }
+ .encode();
+ let min_key = Stage1Key {
+ partition_id: p,
+ team_id: 0,
+ leaf_state_key: lsk(0x00),
+ person_id: person(0),
+ }
+ .encode();
+ assert!(start.as_slice() <= min_key.as_slice(), "start>min at p={p}");
+ assert!(max_key.as_slice() < end.as_slice(), "max>=end at p={p}");
+ if let Some(next) = p.checked_add(1) {
+ let next_min = stage1(next, 0).encode();
+ assert!(
+ end.as_slice() <= next_min.as_slice(),
+ "end>next_min at p={p}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn max_partition_sentinel_exceeds_the_all_ones_key() {
+ let (_start, end) = partition_range(u16::MAX);
+ assert!([0xFFu8; STAGE1_KEY_LEN].as_slice() < end.as_slice());
+ }
+
+ #[test]
+ fn merge_key_lengths_are_exact_and_within_the_stage1_bound() {
+ assert_eq!(MERGE_DRAIN_KEY_LEN, 38);
+ assert_eq!(PENDING_TRANSFER_KEY_LEN, 26);
+ assert_eq!(MERGE_APPLIED_KEY_LEN, 38);
+ assert_eq!(TOMBSTONE_KEY_LEN, 26);
+ for len in [
+ MERGE_DRAIN_KEY_LEN,
+ PENDING_TRANSFER_KEY_LEN,
+ MERGE_APPLIED_KEY_LEN,
+ TOMBSTONE_KEY_LEN,
+ ] {
+ assert!(len <= STAGE1_KEY_LEN, "{len} exceeds STAGE1_KEY_LEN");
+ }
+
+ let drain = MergeDrainKey {
+ partition_id: 1,
+ team_id: 2,
+ old_person: person(3),
+ merge_msg_partition: 4,
+ merge_msg_offset: 5,
+ };
+ assert_eq!(drain.encode().len(), MERGE_DRAIN_KEY_LEN);
+ assert_eq!(
+ PendingTransferKey {
+ partition_id: 1,
+ team_id: 2,
+ old_person: person(3),
+ }
+ .encode()
+ .len(),
+ PENDING_TRANSFER_KEY_LEN,
+ );
+ assert_eq!(
+ MergeAppliedKey {
+ partition_id: 1,
+ team_id: 2,
+ new_person: person(3),
+ source_partition: 4,
+ source_offset: 5,
+ }
+ .encode()
+ .len(),
+ MERGE_APPLIED_KEY_LEN,
+ );
+ assert_eq!(
+ TombstoneKey {
+ partition_id: 1,
+ team_id: 2,
+ person: person(3),
+ }
+ .encode()
+ .len(),
+ TOMBSTONE_KEY_LEN,
+ );
+ }
+
+ #[test]
+ fn merge_drain_key_round_trips_including_kafka_coords() {
+ let key = MergeDrainKey {
+ partition_id: 0xBEEF,
+ team_id: 0x0123_4567_89AB_CDEF,
+ old_person: person(0xDEAD_BEEF),
+ merge_msg_partition: 63,
+ merge_msg_offset: 0x7FFF_FFFF_FFFF_FFFE,
+ };
+ assert_eq!(MergeDrainKey::decode(&key.encode()).unwrap(), key);
+ }
+
+ #[test]
+ fn merge_applied_key_round_trips_including_kafka_coords() {
+ let key = MergeAppliedKey {
+ partition_id: 7,
+ team_id: 42,
+ new_person: person(0xC0FFEE),
+ source_partition: 17,
+ source_offset: 12345,
+ };
+ assert_eq!(MergeAppliedKey::decode(&key.encode()).unwrap(), key);
+ }
+
+ #[test]
+ fn pending_transfer_and_tombstone_keys_round_trip() {
+ let pending = PendingTransferKey {
+ partition_id: 9,
+ team_id: 100,
+ old_person: person(0xFEED),
+ };
+ assert_eq!(
+ PendingTransferKey::decode(&pending.encode()).unwrap(),
+ pending
+ );
+
+ let tombstone = TombstoneKey {
+ partition_id: 9,
+ team_id: 100,
+ person: person(0xFACE),
+ };
+ assert_eq!(
+ TombstoneKey::decode(&tombstone.encode()).unwrap(),
+ tombstone
+ );
+ }
+
+ #[test]
+ fn merge_drain_decode_rejects_wrong_length() {
+ let err = MergeDrainKey::decode(&[0u8; 37]).unwrap_err();
+ assert!(
+ matches!(
+ err,
+ StoreError::KeyDecode {
+ kind: "merge_drain",
+ expected: 38,
+ actual: 37
+ }
+ ),
+ "unexpected error: {err:?}",
+ );
+ }
+
+ #[test]
+ fn merge_keys_share_the_partition_prefix_so_delete_range_reclaims_them() {
+ for p in [0u16, 5, 256, u16::MAX] {
+ let (start, end) = partition_range(p);
+ let drain = MergeDrainKey {
+ partition_id: p,
+ team_id: u64::MAX,
+ old_person: person(u128::MAX),
+ merge_msg_partition: i32::MAX,
+ merge_msg_offset: i64::MAX,
+ }
+ .encode();
+ let tombstone = TombstoneKey {
+ partition_id: p,
+ team_id: 0,
+ person: person(0),
+ }
+ .encode();
+ assert!(
+ start.as_slice() <= tombstone.as_slice(),
+ "start>min at p={p}"
+ );
+ assert!(drain.as_slice() < end.as_slice(), "max>=end at p={p}");
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/mod.rs b/rust/cohort-stream-processor/src/store/mod.rs
new file mode 100644
index 000000000000..1025734b44b2
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/mod.rs
@@ -0,0 +1,19 @@
+//! RocksDB state store.
+
+pub mod column_families;
+pub mod durability;
+pub mod keys;
+pub mod rocks;
+pub mod secondary_index;
+
+pub use column_families::{
+ Cf, OpaqueCf, CF_MERGE_APPLIED, CF_MERGE_DRAINS_APPLIED, CF_MERGE_TOMBSTONES,
+ CF_PENDING_TRANSFERS, CF_PERSON_INDEX, CF_STAGE1, CF_STAGE2,
+};
+pub use keys::{
+ MergeAppliedKey, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key, TombstoneKey,
+};
+pub use rocks::{BatchBuilder, CohortStore, StoreConfig, StoreError};
+pub use secondary_index::{decode_person_index, IndexOp, PERSON_INDEX_MERGE_OPERATOR_NAME};
+
+pub use crate::stage1::key::{LeafStateKey, Stage1Key};
diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rs
new file mode 100644
index 000000000000..ac3730ab7244
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/rocks.rs
@@ -0,0 +1,999 @@
+//! RocksDB wrapper: multi-CF atomic `WriteBatch`, async WAL.
+
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::time::Instant;
+
+use metrics::{counter, histogram};
+use rocksdb::{
+ Cache, ColumnFamily, DBWithThreadMode, Direction, FlushOptions, IteratorMode, Options,
+ ReadOptions, SingleThreaded, WriteBatch, WriteOptions,
+};
+use thiserror::Error;
+
+use super::column_families::{self, Cf, OpaqueCf};
+use super::keys::{
+ self, MergeAppliedKey, MergeDrainKey, PendingTransferKey, PersonIndexKey, Stage2Key,
+ TombstoneKey,
+};
+use super::secondary_index::{decode_person_index, IndexOp};
+use crate::observability::metrics::{
+ CHECKPOINT_DURATION_SECONDS, STORE_ERRORS_TOTAL, STORE_WRITE_BATCH_TOTAL,
+ STORE_WRITE_DURATION_SECONDS, WAL_FSYNC_DURATION_SECONDS, WAL_FSYNC_ERRORS_TOTAL,
+};
+use crate::stage1::key::{LeafStateKey, Stage1Key};
+
+const OP_OPEN: &str = "open";
+const OP_DESTROY: &str = "destroy";
+const OP_GET: &str = "get";
+const OP_MULTI_GET: &str = "multi_get";
+const OP_WRITE_BATCH: &str = "write_batch";
+const OP_DELETE_PARTITION: &str = "delete_partition";
+const OP_FLUSH: &str = "flush";
+const OP_FLUSH_WAL: &str = "flush_wal";
+const OP_SCAN: &str = "scan";
+const OP_CHECKPOINT: &str = "checkpoint";
+
+const DEFAULT_BLOCK_CACHE_BYTES: usize = 128 * 1024 * 1024;
+const DEFAULT_WRITE_BUFFER_BYTES: usize = 64 * 1024 * 1024;
+const DEFAULT_MAX_OPEN_FILES: i32 = 1024;
+
+/// Resolved RocksDB settings.
+#[derive(Debug, Clone)]
+pub struct StoreConfig {
+ pub path: PathBuf,
+ pub block_cache_bytes: usize,
+ pub write_buffer_bytes: usize,
+ pub max_open_files: i32,
+ pub create_if_missing: bool,
+ /// Destroy any existing database at `path` before opening.
+ pub wipe_on_start: bool,
+}
+
+impl Default for StoreConfig {
+ fn default() -> Self {
+ Self {
+ path: PathBuf::from("cohort-store"),
+ block_cache_bytes: DEFAULT_BLOCK_CACHE_BYTES,
+ write_buffer_bytes: DEFAULT_WRITE_BUFFER_BYTES,
+ max_open_files: DEFAULT_MAX_OPEN_FILES,
+ create_if_missing: true,
+ wipe_on_start: false,
+ }
+ }
+}
+
+/// Errors from the state store.
+#[derive(Debug, Error)]
+pub enum StoreError {
+ #[error("opening RocksDB at {path:?}: {source}")]
+ Open {
+ path: PathBuf,
+ source: rocksdb::Error,
+ },
+
+ #[error("RocksDB {op}: {source}")]
+ Backend {
+ op: &'static str,
+ source: rocksdb::Error,
+ },
+
+ #[error("unknown column family: {0}")]
+ UnknownColumnFamily(&'static str),
+
+ #[error("decoding {kind} key: expected {expected} bytes, got {actual}")]
+ KeyDecode {
+ kind: &'static str,
+ expected: usize,
+ actual: usize,
+ },
+}
+
+/// One scanned key/value pair as raw bytes — the merge-CF GC decodes each per CF.
+pub type RawKv = (Vec<u8>, Vec<u8>);
+
+/// Handle to the per-process state store.
+#[derive(Clone)]
+pub struct CohortStore {
+ db: Arc<DBWithThreadMode<SingleThreaded>>,
+}
+
+impl CohortStore {
+ /// Open the column families at `config.path`, creating them if missing.
+ pub fn open(config: &StoreConfig) -> Result<Self, StoreError> {
+ let cache = Cache::new_lru_cache(config.block_cache_bytes);
+ let db_opts = db_options(config);
+
+ if config.wipe_on_start && config.path.exists() {
+ DBWithThreadMode::<SingleThreaded>::destroy(&db_opts, &config.path).map_err(
+ |source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_DESTROY).increment(1);
+ StoreError::Open {
+ path: config.path.clone(),
+ source,
+ }
+ },
+ )?;
+ }
+
+ let descriptors = column_families::descriptors(config, &cache);
+
+ let db = DBWithThreadMode::<SingleThreaded>::open_cf_descriptors(
+ &db_opts,
+ &config.path,
+ descriptors,
+ )
+ .map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_OPEN).increment(1);
+ StoreError::Open {
+ path: config.path.clone(),
+ source,
+ }
+ })?;
+
+ Ok(Self { db: Arc::new(db) })
+ }
+
+ /// Read a raw value from any CF.
+ pub fn get(&self, cf: Cf, key: &[u8]) -> Result<Option<Vec<u8>>, StoreError> {
+ let handle = self.cf(cf)?;
+ self.db.get_cf(handle, key).map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_GET).increment(1);
+ StoreError::Backend { op: OP_GET, source }
+ })
+ }
+
+ pub fn get_stage1(&self, key: &Stage1Key) -> Result<Option<Vec<u8>>, StoreError> {
+ self.get(Cf::Stage1, &key.encode())
+ }
+
+ /// Batch-read several `cf_stage1` values in one call, preserving input order.
+ pub fn multi_get_stage1(&self, keys: &[Stage1Key]) -> Result<Vec<Option<Vec<u8>>>, StoreError> {
+ let handle = self.cf(Cf::Stage1)?;
+ let encoded: Vec<_> = keys.iter().map(Stage1Key::encode).collect();
+ self.db
+ .multi_get_cf(encoded.iter().map(|key| (handle, key.as_slice())))
+ .into_iter()
+ .map(|result| {
+ result.map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_MULTI_GET).increment(1);
+ StoreError::Backend {
+ op: OP_MULTI_GET,
+ source,
+ }
+ })
+ })
+ .collect()
+ }
+
+ pub fn get_stage2(&self, key: &Stage2Key) -> Result<Option<Vec<u8>>, StoreError> {
+ self.get(Cf::Stage2, &key.encode())
+ }
+
+ /// Batch-read several `cf_stage2` values in one call, preserving input order.
+ pub fn multi_get_stage2(&self, keys: &[Stage2Key]) -> Result<Vec<Option<Vec<u8>>>, StoreError> {
+ let handle = self.cf(Cf::Stage2)?;
+ let encoded: Vec<_> = keys.iter().map(Stage2Key::encode).collect();
+ self.db
+ .multi_get_cf(encoded.iter().map(|key| (handle, key.as_slice())))
+ .into_iter()
+ .map(|result| {
+ result.map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_MULTI_GET).increment(1);
+ StoreError::Backend {
+ op: OP_MULTI_GET,
+ source,
+ }
+ })
+ })
+ .collect()
+ }
+
+ /// A missing key decodes to an empty vec.
+ pub fn get_person_index(&self, key: &PersonIndexKey) -> Result<Vec<LeafStateKey>, StoreError> {
+ Ok(self
+ .get(Cf::PersonIndex, &key.encode())?
+ .map(|bytes| decode_person_index(&bytes))
+ .unwrap_or_default())
+ }
+
+ /// Apply writes across CFs in one atomic `WriteBatch`.
+ pub fn write_batch<F>(&self, build: F) -> Result<(), StoreError>
+ where
+ F: FnOnce(&mut BatchBuilder<'_>),
+ {
+ let mut builder = BatchBuilder {
+ batch: WriteBatch::default(),
+ stage1: self.cf(Cf::Stage1)?,
+ person_index: self.cf(Cf::PersonIndex)?,
+ stage2: self.cf(Cf::Stage2)?,
+ merge_drains_applied: self.cf(Cf::MergeDrainsApplied)?,
+ pending_transfers: self.cf(Cf::PendingTransfers)?,
+ merge_applied: self.cf(Cf::MergeApplied)?,
+ merge_tombstones: self.cf(Cf::MergeTombstones)?,
+ };
+ build(&mut builder);
+ self.commit(builder.batch, OP_WRITE_BATCH)
+ }
+
+ pub fn get_merge_drain_applied(
+ &self,
+ key: &MergeDrainKey,
+ ) -> Result<Option<Vec<u8>>, StoreError> {
+ self.get(Cf::MergeDrainsApplied, &key.encode())
+ }
+
+ pub fn get_pending_transfer(
+ &self,
+ key: &PendingTransferKey,
+ ) -> Result<Option<Vec<u8>>, StoreError> {
+ self.get(Cf::PendingTransfers, &key.encode())
+ }
+
+ pub fn get_merge_applied(&self, key: &MergeAppliedKey) -> Result<Option<Vec<u8>>, StoreError> {
+ self.get(Cf::MergeApplied, &key.encode())
+ }
+
+ pub fn get_tombstone(&self, key: &TombstoneKey) -> Result<Option<Vec<u8>>, StoreError> {
+ self.get(Cf::MergeTombstones, &key.encode())
+ }
+
+ /// Clear one outbox slot once its transfer is acked.
+ pub fn clear_pending_transfer(&self, key: &PendingTransferKey) -> Result<(), StoreError> {
+ self.write_batch(|batch| batch.delete_pending_transfer(key))
+ }
+
+ /// Scan up to `limit` of one partition's `cf_pending_transfers` slice, returning `(key, value)`
+ /// in key order, resuming strictly *after* `start_after` (exclusive) when given. The per-tick
+ /// redrive passes a bounded `limit` and no cursor; the eager boot redrive paginates with a cursor
+ /// to drain the whole outbox (mirrors [`Self::scan_stage1`] / [`Self::scan_merge_cf`]).
+ pub fn scan_pending_transfers(
+ &self,
+ partition_id: u16,
+ start_after: Option<&[u8]>,
+ limit: usize,
+ ) -> Result<Vec<(PendingTransferKey, Vec<u8>)>, StoreError> {
+ let (prefix_start, prefix_end) = keys::partition_range(partition_id);
+ let handle = self.cf(Cf::PendingTransfers)?;
+
+ // Resume after the cursor when it falls inside this partition, else at the prefix start.
+ let begin: Vec<u8> = match start_after {
+ Some(cursor) if cursor >= prefix_start.as_slice() && cursor < prefix_end.as_slice() => {
+ successor(cursor)
+ }
+ _ => prefix_start.clone(),
+ };
+
+ let mut read_opts = ReadOptions::default();
+ read_opts.set_iterate_upper_bound(prefix_end);
+ let iter = self.db.iterator_cf_opt(
+ handle,
+ read_opts,
+ IteratorMode::From(&begin, Direction::Forward),
+ );
+
+ let mut out = Vec::with_capacity(limit.min(1024));
+ for item in iter {
+ if out.len() == limit {
+ break;
+ }
+ let (key_bytes, value) = item.map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_SCAN).increment(1);
+ StoreError::Backend {
+ op: OP_SCAN,
+ source,
+ }
+ })?;
+ out.push((PendingTransferKey::decode(&key_bytes)?, value.to_vec()));
+ }
+ Ok(out)
+ }
+
+ /// Scan up to `limit` raw `(key, value)` pairs from one partition's slice of a CF, in key order,
+ /// resuming strictly *after* `start_after` (exclusive) when given.
+ ///
+ /// Returns raw bytes (not typed keys/values) so each GC handler can decode the CF's own value
+ /// shape and keep the last key as its resume cursor. The mechanics are CF-generic: the merge-CF GC
+ /// passes the three time-stamped merge CFs (`DrainStamp` / `ApplyStamp` / `Tombstone`, see
+ /// [`crate::merge::gc`]), and the `cf_stage2` orphan GC passes `Cf::Stage2` (see
+ /// [`crate::workers::stage2_gc`]). `cf_pending_transfers` is the redrive's outbox and no GC path
+ /// passes it.
+ pub fn scan_merge_cf(
+ &self,
+ cf: Cf,
+ partition_id: u16,
+ start_after: Option<&[u8]>,
+ limit: usize,
+ ) -> Result<Vec<RawKv>, StoreError> {
+ let (prefix_start, prefix_end) = keys::partition_range(partition_id);
+ let handle = self.cf(cf)?;
+
+ // Resume after the cursor when it falls inside this partition, else at the prefix start.
+ // `successor` is the smallest key strictly greater than the cursor, turning the inclusive
+ // `IteratorMode::From(_, Forward)` seek into an exclusive resume.
+ let begin: Vec<u8> = match start_after {
+ Some(cursor) if cursor >= prefix_start.as_slice() && cursor < prefix_end.as_slice() => {
+ successor(cursor)
+ }
+ _ => prefix_start.clone(),
+ };
+
+ let mut read_opts = ReadOptions::default();
+ read_opts.set_iterate_upper_bound(prefix_end);
+ let iter = self.db.iterator_cf_opt(
+ handle,
+ read_opts,
+ IteratorMode::From(&begin, Direction::Forward),
+ );
+
+ let mut out = Vec::with_capacity(limit.min(1024));
+ for item in iter {
+ if out.len() == limit {
+ break;
+ }
+ let (key_bytes, value) = item.map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_SCAN).increment(1);
+ StoreError::Backend {
+ op: OP_SCAN,
+ source,
+ }
+ })?;
+ out.push((key_bytes.to_vec(), value.to_vec()));
+ }
+ Ok(out)
+ }
+
+ /// Reclaim all state for one partition on rebalance.
+ pub fn delete_partition(&self, partition_id: u16) -> Result<(), StoreError> {
+ let (start, end) = keys::partition_range(partition_id);
+ let mut batch = WriteBatch::default();
+ for cf in Cf::ALL {
+ let handle = self.cf(cf)?;
+ batch.delete_range_cf(handle, start.as_slice(), end.as_slice());
+ }
+ self.commit(batch, OP_DELETE_PARTITION)
+ }
+
+ /// Flush all CF memtables to SST. Checkpoint path and tests only.
+ pub fn flush(&self) -> Result<(), StoreError> {
+ let handles = [
+ self.cf(Cf::Stage1)?,
+ self.cf(Cf::PersonIndex)?,
+ self.cf(Cf::Stage2)?,
+ self.cf(Cf::MergeDrainsApplied)?,
+ self.cf(Cf::PendingTransfers)?,
+ self.cf(Cf::MergeApplied)?,
+ self.cf(Cf::MergeTombstones)?,
+ ];
+ let mut flush_opts = FlushOptions::default();
+ flush_opts.set_wait(true);
+ self.db
+ .flush_cfs_opt(&handles, &flush_opts)
+ .map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_FLUSH).increment(1);
+ StoreError::Backend {
+ op: OP_FLUSH,
+ source,
+ }
+ })
+ }
+
+ /// Synchronously fsync the WAL, making every write so far durable. The hot path writes with an
+ /// async WAL (`set_sync(false)`), so without this a committed Kafka offset could outrun the durable
+ /// state on a hard crash; callers fsync before every offset commit to keep `committed <= durable`.
+ /// On error the caller skips the commit (fail-stop).
+ pub fn flush_wal_sync(&self) -> Result<(), StoreError> {
+ let started = Instant::now();
+ let result = self.db.flush_wal(true);
+ histogram!(WAL_FSYNC_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
+ result.map_err(|source| {
+ counter!(WAL_FSYNC_ERRORS_TOTAL).increment(1);
+ StoreError::Backend {
+ op: OP_FLUSH_WAL,
+ source,
+ }
+ })
+ }
+
+ /// Take a frozen, point-in-time RocksDB checkpoint of the whole DB into `path`. RocksDB
+ /// hard-links the immutable SSTs into `path`, so `path` must be on the **same filesystem** as
+ /// the store path and **must not be a child** of it (RocksDB refuses a nested checkpoint path).
+ pub fn create_checkpoint(&self, path: &Path) -> Result<(), StoreError> {
+ let started = Instant::now();
+ let result = rocksdb::checkpoint::Checkpoint::new(&self.db)
+ .and_then(|cp| cp.create_checkpoint(path));
+ histogram!(CHECKPOINT_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
+ result.map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_CHECKPOINT).increment(1);
+ StoreError::Backend {
+ op: OP_CHECKPOINT,
+ source,
+ }
+ })
+ }
+
+ /// Scan up to `limit` of one partition's `cf_stage1` slice as `(Stage1Key, raw_value)` in key
+ /// order, resuming strictly after `start_after` when given. The value stays raw so the caller
+ /// decodes the [`StatefulRecord`](crate::stage1::StatefulRecord) (and owns the decode-error metric)
+ /// and the resume cursor is the last scanned key.
+ pub fn scan_stage1(
+ &self,
+ partition_id: u16,
+ start_after: Option<&[u8]>,
+ limit: usize,
+ ) -> Result<Vec<(Stage1Key, Vec<u8>)>, StoreError> {
+ let (prefix_start, prefix_end) = keys::partition_range(partition_id);
+ let handle = self.cf(Cf::Stage1)?;
+
+ // Resume after the cursor when it falls inside this partition, else at the prefix start.
+ let begin: Vec<u8> = match start_after {
+ Some(cursor) if cursor >= prefix_start.as_slice() && cursor < prefix_end.as_slice() => {
+ successor(cursor)
+ }
+ _ => prefix_start.clone(),
+ };
+
+ let mut read_opts = ReadOptions::default();
+ read_opts.set_iterate_upper_bound(prefix_end);
+ let iter = self.db.iterator_cf_opt(
+ handle,
+ read_opts,
+ IteratorMode::From(&begin, Direction::Forward),
+ );
+
+ let mut out = Vec::with_capacity(limit.min(1024));
+ for item in iter {
+ if out.len() == limit {
+ break;
+ }
+ let (key_bytes, value) = item.map_err(|source| {
+ counter!(STORE_ERRORS_TOTAL, "op" => OP_SCAN).increment(1);
+ StoreError::Backend {
+ op: OP_SCAN,
+ source,
+ }
+ })?;
+ out.push((Stage1Key::decode(&key_bytes)?, value.to_vec()));
+ }
+ Ok(out)
+ }
+
+ fn cf(&self, cf: Cf) -> Result<&ColumnFamily, StoreError> {
+ self.db
+ .cf_handle(cf.as_str())
+ .ok_or(StoreError::UnknownColumnFamily(cf.as_str()))
+ }
+
+ fn commit(&self, batch: WriteBatch, op: &'static str) -> Result<(), StoreError> {
+ let mut write_opts = WriteOptions::default();
+ write_opts.set_sync(false);
+
+ let started = Instant::now();
+ let result = self.db.write_opt(batch, &write_opts);
+ histogram!(STORE_WRITE_DURATION_SECONDS, "op" => op)
+ .record(started.elapsed().as_secs_f64());
+
+ match result {
+ Ok(()) => {
+ counter!(STORE_WRITE_BATCH_TOTAL, "op" => op).increment(1);
+ Ok(())
+ }
+ Err(source) => {
+ counter!(STORE_ERRORS_TOTAL, "op" => op).increment(1);
+ Err(StoreError::Backend { op, source })
+ }
+ }
+ }
+}
+
+/// Typed builder for a multi-CF [`WriteBatch`].
+pub struct BatchBuilder<'db> {
+ batch: WriteBatch,
+ stage1: &'db ColumnFamily,
+ person_index: &'db ColumnFamily,
+ stage2: &'db ColumnFamily,
+ merge_drains_applied: &'db ColumnFamily,
+ pending_transfers: &'db ColumnFamily,
+ merge_applied: &'db ColumnFamily,
+ merge_tombstones: &'db ColumnFamily,
+}
+
+impl BatchBuilder<'_> {
+ pub fn put_stage1(&mut self, key: &Stage1Key, value: &[u8]) {
+ self.batch.put_cf(self.stage1, key.encode(), value);
+ }
+
+ pub fn delete_stage1(&mut self, key: &Stage1Key) {
+ self.batch.delete_cf(self.stage1, key.encode());
+ }
+
+ /// Read-free append/remove on the person's index.
+ pub fn merge_person_index(&mut self, key: &PersonIndexKey, op: IndexOp) {
+ self.batch
+ .merge_cf(self.person_index, key.encode(), op.encode());
+ }
+
+ /// Whole-key delete of a person's index entry.
+ pub fn delete_person_index(&mut self, key: &PersonIndexKey) {
+ self.batch.delete_cf(self.person_index, key.encode());
+ }
+
+ pub fn put_stage2(&mut self, key: &Stage2Key, value: &[u8]) {
+ self.batch.put_cf(self.stage2, key.encode(), value);
+ }
+
+ pub fn delete_stage2(&mut self, key: &Stage2Key) {
+ self.batch.delete_cf(self.stage2, key.encode());
+ }
+
+ /// Stage the Phase 1 idempotence marker for a drained merge message.
+ pub fn put_merge_drain_applied(&mut self, key: &MergeDrainKey, value: &[u8]) {
+ self.batch
+ .put_cf(self.merge_drains_applied, key.encode(), value);
+ }
+
+ /// GC-delete one expired Phase 1 idempotence marker.
+ pub fn delete_merge_drain_applied(&mut self, key: &MergeDrainKey) {
+ self.batch
+ .delete_cf(self.merge_drains_applied, key.encode());
+ }
+
+ /// Stage a packaged merge into the outbox.
+ pub fn put_pending_transfer(&mut self, key: &PendingTransferKey, value: &[u8]) {
+ self.batch
+ .put_cf(self.pending_transfers, key.encode(), value);
+ }
+
+ /// Clear an outbox slot once its transfer is acked.
+ pub fn delete_pending_transfer(&mut self, key: &PendingTransferKey) {
+ self.batch.delete_cf(self.pending_transfers, key.encode());
+ }
+
+ /// Stage the Phase 2 idempotence marker for an applied transfer message.
+ pub fn put_merge_applied(&mut self, key: &MergeAppliedKey, value: &[u8]) {
+ self.batch.put_cf(self.merge_applied, key.encode(), value);
+ }
+
+ /// GC-delete one expired Phase 2 idempotence marker.
+ pub fn delete_merge_applied(&mut self, key: &MergeAppliedKey) {
+ self.batch.delete_cf(self.merge_applied, key.encode());
+ }
+
+ /// Stage the redirect tombstone for a merged-away person.
+ pub fn put_tombstone(&mut self, key: &TombstoneKey, value: &[u8]) {
+ self.batch
+ .put_cf(self.merge_tombstones, key.encode(), value);
+ }
+
+ /// GC-delete one expired redirect tombstone.
+ pub fn delete_tombstone(&mut self, key: &TombstoneKey) {
+ self.batch.delete_cf(self.merge_tombstones, key.encode());
+ }
+
+ /// Raw put by pre-encoded key bytes. Restricted to [`OpaqueCf`].
+ pub fn put_raw(&mut self, cf: OpaqueCf, key: &[u8], value: &[u8]) {
+ let handle = match cf {
+ OpaqueCf::Stage1 => self.stage1,
+ OpaqueCf::Stage2 => self.stage2,
+ };
+ self.batch.put_cf(handle, key, value);
+ }
+}
+
+/// The smallest byte string strictly greater than `key`: `key` with a trailing `0x00` appended.
+/// Used to turn an inclusive `IteratorMode::From` seek into an exclusive resume past a cursor.
+fn successor(key: &[u8]) -> Vec<u8> {
+ let mut next = Vec::with_capacity(key.len() + 1);
+ next.extend_from_slice(key);
+ next.push(0x00);
+ next
+}
+
+fn db_options(config: &StoreConfig) -> Options {
+ let mut opts = Options::default();
+ opts.create_if_missing(config.create_if_missing);
+ opts.create_missing_column_families(true);
+ opts.set_atomic_flush(true);
+ opts.set_max_open_files(config.max_open_files);
+ opts.set_allow_mmap_reads(false);
+ opts.set_allow_mmap_writes(false);
+ opts
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ fn stage1_key() -> Stage1Key {
+ Stage1Key {
+ partition_id: 3,
+ team_id: 7,
+ leaf_state_key: LeafStateKey([0xAB; 16]),
+ person_id: Uuid::from_u128(1),
+ }
+ }
+
+ #[test]
+ fn wipe_on_start_clears_existing_state_and_is_a_noop_when_off() {
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("db");
+ let key = stage1_key();
+
+ // Seed a value, then close the database (drop the only handle).
+ {
+ let store = CohortStore::open(&StoreConfig {
+ path: path.clone(),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ store.write_batch(|b| b.put_stage1(&key, b"state")).unwrap();
+ assert_eq!(
+ store.get_stage1(&key).unwrap().as_deref(),
+ Some(b"state".as_slice()),
+ );
+ }
+
+ // Reopen without wiping: the value survives a restart.
+ {
+ let store = CohortStore::open(&StoreConfig {
+ path: path.clone(),
+ wipe_on_start: false,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ assert_eq!(
+ store.get_stage1(&key).unwrap().as_deref(),
+ Some(b"state".as_slice()),
+ );
+ }
+
+ // Reopen with wiping: the previous owner's state is gone.
+ {
+ let store = CohortStore::open(&StoreConfig {
+ path: path.clone(),
+ wipe_on_start: true,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ assert_eq!(store.get_stage1(&key).unwrap(), None);
+ }
+ }
+
+ #[test]
+ fn wipe_on_start_opens_cleanly_when_no_store_exists_yet() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("fresh"),
+ wipe_on_start: true,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ assert_eq!(store.get_stage1(&stage1_key()).unwrap(), None);
+ }
+
+ #[test]
+ fn multi_get_stage1_preserves_order_and_reports_absent_keys() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+
+ let present = |person: u128, lsk: u8| Stage1Key {
+ partition_id: 3,
+ team_id: 7,
+ leaf_state_key: LeafStateKey([lsk; 16]),
+ person_id: Uuid::from_u128(person),
+ };
+ let a = present(1, 0xA0);
+ let b = present(2, 0xB0);
+ let absent = present(9, 0xFF);
+ store
+ .write_batch(|batch| {
+ batch.put_stage1(&a, b"alpha");
+ batch.put_stage1(&b, b"bravo");
+ })
+ .unwrap();
+
+ // Order: present, absent, present — the absent key must surface as a `None` hole, not shift
+ // the others.
+ let results = store.multi_get_stage1(&[a, absent, b]).unwrap();
+ assert_eq!(results.len(), 3);
+ assert_eq!(results[0].as_deref(), Some(b"alpha".as_slice()));
+ assert_eq!(results[1], None);
+ assert_eq!(results[2].as_deref(), Some(b"bravo".as_slice()));
+
+ assert!(
+ store.multi_get_stage1(&[]).unwrap().is_empty(),
+ "an empty key set reads no values",
+ );
+ }
+
+ #[test]
+ fn multi_get_stage2_preserves_order_and_reports_absent_keys() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+
+ let present = |person: u128, cohort: u64| Stage2Key {
+ partition_id: 3,
+ team_id: 7,
+ cohort_id: cohort,
+ person_id: Uuid::from_u128(person),
+ };
+ let a = present(1, 100);
+ let b = present(2, 200);
+ let absent = present(9, 999);
+ store
+ .write_batch(|batch| {
+ batch.put_stage2(&a, b"alpha");
+ batch.put_stage2(&b, b"bravo");
+ })
+ .unwrap();
+
+ // Order: present, absent, present — the absent key must surface as a `None` hole, not shift
+ // the others.
+ let results = store.multi_get_stage2(&[a, absent, b]).unwrap();
+ assert_eq!(results.len(), 3);
+ assert_eq!(results[0].as_deref(), Some(b"alpha".as_slice()));
+ assert_eq!(results[1], None);
+ assert_eq!(results[2].as_deref(), Some(b"bravo".as_slice()));
+
+ assert!(
+ store.multi_get_stage2(&[]).unwrap().is_empty(),
+ "an empty key set reads no values",
+ );
+ }
+
+ #[test]
+ fn scan_merge_cf_resumes_after_the_cursor_and_honors_the_limit_and_partition_bounds() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+
+ let tombstone_key = |partition_id: u16, person: u128| TombstoneKey {
+ partition_id,
+ team_id: 7,
+ person: Uuid::from_u128(person),
+ };
+
+ // Four tombstones in partition 5, one in partition 6 (must never surface for a p=5 scan).
+ store
+ .write_batch(|batch| {
+ for person in 1..=4u128 {
+ batch.put_tombstone(&tombstone_key(5, person), b"v");
+ }
+ batch.put_tombstone(&tombstone_key(6, 9), b"other-partition");
+ })
+ .unwrap();
+
+ let page1 = store
+ .scan_merge_cf(Cf::MergeTombstones, 5, None, 2)
+ .unwrap();
+ assert_eq!(page1.len(), 2);
+ let decoded: Vec<_> = page1
+ .iter()
+ .map(|(k, _)| TombstoneKey::decode(k).unwrap().person)
+ .collect();
+ assert_eq!(
+ decoded,
+ vec![Uuid::from_u128(1), Uuid::from_u128(2)],
+ "key-ordered ascending",
+ );
+
+ let cursor = page1.last().unwrap().0.clone();
+ let page2 = store
+ .scan_merge_cf(Cf::MergeTombstones, 5, Some(&cursor), 10)
+ .unwrap();
+ let decoded2: Vec<_> = page2
+ .iter()
+ .map(|(k, _)| TombstoneKey::decode(k).unwrap().person)
+ .collect();
+ assert_eq!(
+ decoded2,
+ vec![Uuid::from_u128(3), Uuid::from_u128(4)],
+ "resumes past the cursor, never re-emits it, and stays inside partition 5",
+ );
+
+ // A cursor at the partition's last key → empty (exhausted), wrapping is the caller's job.
+ let last_cursor = page2.last().unwrap().0.clone();
+ let exhausted = store
+ .scan_merge_cf(Cf::MergeTombstones, 5, Some(&last_cursor), 10)
+ .unwrap();
+ assert!(exhausted.is_empty(), "no keys past the partition's last");
+
+ // A cursor that is not in this partition falls back to a fresh prefix scan.
+ let foreign_cursor = tombstone_key(6, 9).encode().to_vec();
+ let fresh = store
+ .scan_merge_cf(Cf::MergeTombstones, 5, Some(&foreign_cursor), 10)
+ .unwrap();
+ assert_eq!(
+ fresh.len(),
+ 4,
+ "out-of-partition cursor rescans from the start"
+ );
+ }
+
+ #[test]
+ fn flush_wal_sync_succeeds_and_persists_writes_across_a_reopen() {
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("db");
+ let key = stage1_key();
+ {
+ let store = CohortStore::open(&StoreConfig {
+ path: path.clone(),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ store
+ .write_batch(|b| b.put_stage1(&key, b"durable"))
+ .unwrap();
+ store.flush_wal_sync().unwrap();
+ // A second fsync with nothing new pending is a no-op, not an error.
+ store.flush_wal_sync().unwrap();
+ }
+ let reopened = CohortStore::open(&StoreConfig {
+ path,
+ wipe_on_start: false,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ assert_eq!(
+ reopened.get_stage1(&key).unwrap().as_deref(),
+ Some(b"durable".as_slice()),
+ );
+ }
+
+ #[test]
+ fn create_checkpoint_produces_an_openable_db_with_the_same_state() {
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("db");
+ // The checkpoint must be a sibling of the store path, never a child (RocksDB hard-links SSTs).
+ let checkpoint = dir.path().join("checkpoint");
+ let key = stage1_key();
+
+ let store = CohortStore::open(&StoreConfig {
+ path,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ store
+ .write_batch(|b| b.put_stage1(&key, b"snapshot"))
+ .unwrap();
+ store.create_checkpoint(&checkpoint).unwrap();
+
+ let restored = CohortStore::open(&StoreConfig {
+ path: checkpoint,
+ wipe_on_start: false,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ assert_eq!(
+ restored.get_stage1(&key).unwrap().as_deref(),
+ Some(b"snapshot".as_slice()),
+ );
+ }
+
+ // RocksDB's Checkpoint::create_checkpoint creates the destination dir itself and requires
+ // the leaf to NOT already exist: the parent must exist, the leaf must not.
+ #[test]
+ fn create_checkpoint_succeeds_when_only_the_parent_exists_and_the_leaf_does_not() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let key = stage1_key();
+ store
+ .write_batch(|b| b.put_stage1(&key, b"snapshot"))
+ .unwrap();
+
+ // Parent exists, leaf does not — the correct usage.
+ let parent = dir.path().join("attempts");
+ std::fs::create_dir_all(&parent).unwrap();
+ let checkpoint = parent.join("attempt-0");
+ store.create_checkpoint(&checkpoint).unwrap();
+
+ let restored = CohortStore::open(&StoreConfig {
+ path: checkpoint,
+ wipe_on_start: false,
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ assert_eq!(
+ restored.get_stage1(&key).unwrap().as_deref(),
+ Some(b"snapshot".as_slice()),
+ );
+ }
+
+ #[test]
+ fn create_checkpoint_errors_when_the_destination_dir_already_exists() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+
+ // Pre-create the leaf: RocksDB requires it to not exist.
+ let checkpoint = dir.path().join("attempt-0");
+ std::fs::create_dir_all(&checkpoint).unwrap();
+ let err = store.create_checkpoint(&checkpoint).unwrap_err();
+ assert!(
+ matches!(err, StoreError::Backend { op, .. } if op == OP_CHECKPOINT),
+ "pre-existing checkpoint dir must surface a backend checkpoint error, got: {err}",
+ );
+ }
+
+ #[test]
+ fn scan_stage1_resumes_after_the_cursor_and_honors_the_limit_and_partition_bounds() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+
+ let key = |partition_id: u16, person: u128| Stage1Key {
+ partition_id,
+ team_id: 7,
+ leaf_state_key: LeafStateKey([0xAB; 16]),
+ person_id: Uuid::from_u128(person),
+ };
+
+ // Three keys in partition 5, one in partition 6 (must never surface for a p=5 scan).
+ store
+ .write_batch(|batch| {
+ for person in 1..=3u128 {
+ batch.put_stage1(&key(5, person), format!("v{person}").as_bytes());
+ }
+ batch.put_stage1(&key(6, 9), b"other-partition");
+ })
+ .unwrap();
+
+ let page1 = store.scan_stage1(5, None, 2).unwrap();
+ assert_eq!(page1.len(), 2);
+ assert_eq!(page1[0].0, key(5, 1));
+ assert_eq!(page1[0].1, b"v1");
+ assert_eq!(page1[1].0, key(5, 2));
+
+ let cursor = page1.last().unwrap().0.encode();
+ let page2 = store.scan_stage1(5, Some(&cursor), 10).unwrap();
+ assert_eq!(page2.len(), 1, "only the remaining partition-5 key");
+ assert_eq!(page2[0].0, key(5, 3));
+
+ // A cursor at the partition's last key is exhausted.
+ let last = page2.last().unwrap().0.encode();
+ assert!(store.scan_stage1(5, Some(&last), 10).unwrap().is_empty());
+
+ assert!(
+ store.scan_stage1(9, None, 10).unwrap().is_empty(),
+ "empty partition"
+ );
+ }
+
+ #[test]
+ fn default_config_is_sane() {
+ let config = StoreConfig::default();
+ assert!(config.create_if_missing);
+ assert!(config.block_cache_bytes > 0);
+ assert!(config.write_buffer_bytes > 0);
+ assert!(config.max_open_files > 0);
+ }
+
+ #[test]
+ fn cohort_store_is_send_and_sync() {
+ fn assert_send_sync<T: Send + Sync>() {}
+ assert_send_sync::<CohortStore>();
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/secondary_index.rs b/rust/cohort-stream-processor/src/store/secondary_index.rs
new file mode 100644
index 000000000000..1715c02ab013
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/secondary_index.rs
@@ -0,0 +1,257 @@
+//! `cf_person_index` maintenance via a non-associative RocksDB merge operator.
+//!
+//! The hot path appends a [`LeafStateKey`] to a person's set without a read, in the same
+//! `WriteBatch` as the `cf_stage1` put. Append *and* remove are both needed, so the operator is
+//! non-associative (operand format ≠ value format):
+//!
+//! - **Value** — the set, a sorted, de-duplicated, packed `[u8; 16] × N` (untagged).
+//! - **Operand** — a 17-byte `[tag u8][lsk 16]` ([`IndexOp`]); a concatenation of several is itself
+//! a valid operand.
+//!
+//! Maintained on the hot path even though its only readers are the merge drain (enumerating P_old's
+//! leaves on a person merge, [`crate::merge::drain_handler`]) and Stage 2 composition: writing it
+//! eagerly gives the non-associative merge operator production bake time on real compaction/flush
+//! threads before readers depend on it, and lets readers inherit a fully-built person→leaf-state
+//! index with no historical backfill pass.
+//!
+//! Two correctness rules:
+//!
+//! 1. **Never panic.** The merge fns run on RocksDB compaction/flush threads; a panic across that
+//! FFI boundary is UB. Every decode is length-checked and skips (with a metric).
+//! 2. **Never return `None`.** `None` from `full_merge` signals a *merge failure* (a
+//! `"Merge operator failed"` error on the next read), not a key drop. The empty set therefore
+//! encodes to an empty value, which reads back as "no states" — same as a missing key.
+//!
+//! Append-present and remove-absent are `BTreeSet` no-ops, so replay is idempotent.
+
+use std::collections::BTreeSet;
+
+use metrics::counter;
+use rocksdb::MergeOperands;
+
+use crate::observability::metrics::STORE_MERGE_MALFORMED_TOTAL;
+use crate::stage1::key::LeafStateKey;
+
+/// RocksDB treats the operator name as a forward-compat contract: bump `_vN` on any format change.
+pub const PERSON_INDEX_MERGE_OPERATOR_NAME: &str = "cf_person_index_merge_v1";
+
+const LSK_LEN: usize = 16;
+const OPERAND_LEN: usize = 1 + LSK_LEN;
+const TAG_APPEND: u8 = 0;
+const TAG_REMOVE: u8 = 1;
+
+/// A mutation of a person's leaf-state set, applied to `cf_person_index` via `merge_cf`.
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub enum IndexOp {
+ Append(LeafStateKey),
+ Remove(LeafStateKey),
+}
+
+impl IndexOp {
+ pub fn encode(&self) -> [u8; OPERAND_LEN] {
+ let (tag, lsk) = match self {
+ IndexOp::Append(lsk) => (TAG_APPEND, lsk),
+ IndexOp::Remove(lsk) => (TAG_REMOVE, lsk),
+ };
+ let mut out = [0u8; OPERAND_LEN];
+ out[0] = tag;
+ out[1..].copy_from_slice(&lsk.0);
+ out
+ }
+}
+
+/// Decode a stored `cf_person_index` value into sorted, unique leaf-state keys. Infallible: a
+/// trailing partial entry is dropped (with a metric) rather than erroring; empty yields "no states".
+pub fn decode_person_index(value: &[u8]) -> Vec<LeafStateKey> {
+ decode_packed(value).into_iter().map(LeafStateKey).collect()
+}
+
+pub(crate) fn full_merge(
+ _key: &[u8],
+ existing: Option<&[u8]>,
+ operands: &MergeOperands,
+) -> Option<Vec<u8>> {
+ Some(collapse(existing, operands))
+}
+
+/// Concatenate operand logs without a base value. RocksDB only re-feeds the result as another
+/// operand (`existing` is always `None`), so a concatenation of valid logs is itself valid.
+pub(crate) fn partial_merge(
+ _key: &[u8],
+ _existing: Option<&[u8]>,
+ operands: &MergeOperands,
+) -> Option<Vec<u8>> {
+ Some(concat_logs(operands))
+}
+
+/// Fold `existing` + ordered `operands` into the encoded set. Takes an iterator (not
+/// `MergeOperands`) so the tests, which can't construct one, can share it.
+fn collapse<'a>(existing: Option<&[u8]>, operands: impl IntoIterator<Item = &'a [u8]>) -> Vec<u8> {
+ let mut set: BTreeSet<[u8; LSK_LEN]> = existing
+ .map(|bytes| decode_packed(bytes).into_iter().collect())
+ .unwrap_or_default();
+ for operand in operands {
+ apply_operand_log(&mut set, operand);
+ }
+ encode_set(&set)
+}
+
+/// Concatenate operand logs, skipping any not a whole number of entries so one malformed operand
+/// can't misalign the rest.
+fn concat_logs<'a>(operands: impl IntoIterator<Item = &'a [u8]>) -> Vec<u8> {
+ let mut combined = Vec::new();
+ for operand in operands {
+ if operand.len() % OPERAND_LEN == 0 {
+ combined.extend_from_slice(operand);
+ } else {
+ counter!(STORE_MERGE_MALFORMED_TOTAL, "kind" => "operand_len").increment(1);
+ }
+ }
+ combined
+}
+
+fn apply_operand_log(set: &mut BTreeSet<[u8; LSK_LEN]>, log: &[u8]) {
+ let mut entries = log.chunks_exact(OPERAND_LEN);
+ for entry in &mut entries {
+ let [tag, lsk_bytes @ ..] = entry else {
+ continue;
+ };
+ let mut lsk = [0u8; LSK_LEN];
+ lsk.copy_from_slice(lsk_bytes);
+ match *tag {
+ TAG_APPEND => {
+ set.insert(lsk);
+ }
+ TAG_REMOVE => {
+ set.remove(&lsk);
+ }
+ _ => {
+ counter!(STORE_MERGE_MALFORMED_TOTAL, "kind" => "operand_tag").increment(1);
+ }
+ }
+ }
+ if !entries.remainder().is_empty() {
+ counter!(STORE_MERGE_MALFORMED_TOTAL, "kind" => "operand_len").increment(1);
+ }
+}
+
+fn encode_set(set: &BTreeSet<[u8; LSK_LEN]>) -> Vec<u8> {
+ let mut out = Vec::with_capacity(set.len() * LSK_LEN);
+ for lsk in set {
+ out.extend_from_slice(lsk);
+ }
+ out
+}
+
+/// Decode the packed value into raw 16-byte keys, dropping a trailing partial entry (with a metric).
+fn decode_packed(bytes: &[u8]) -> Vec<[u8; LSK_LEN]> {
+ let mut out = Vec::with_capacity(bytes.len() / LSK_LEN);
+ let mut chunks = bytes.chunks_exact(LSK_LEN);
+ for chunk in &mut chunks {
+ let mut lsk = [0u8; LSK_LEN];
+ lsk.copy_from_slice(chunk);
+ out.push(lsk);
+ }
+ if !chunks.remainder().is_empty() {
+ counter!(STORE_MERGE_MALFORMED_TOTAL, "kind" => "base_len").increment(1);
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn lsk(b: u8) -> LeafStateKey {
+ LeafStateKey([b; 16])
+ }
+
+ fn append(b: u8) -> [u8; OPERAND_LEN] {
+ IndexOp::Append(lsk(b)).encode()
+ }
+
+ fn remove(b: u8) -> [u8; OPERAND_LEN] {
+ IndexOp::Remove(lsk(b)).encode()
+ }
+
+ #[test]
+ fn operand_encoding_is_tag_then_key() {
+ let a = append(0xAB);
+ assert_eq!(a[0], TAG_APPEND);
+ assert_eq!(&a[1..], &[0xAB; 16]);
+
+ let r = remove(0xCD);
+ assert_eq!(r[0], TAG_REMOVE);
+ assert_eq!(&r[1..], &[0xCD; 16]);
+ }
+
+ #[test]
+ fn append_then_collapse_round_trips_through_decode() {
+ let value = collapse(None, [&append(1)[..], &append(2)[..]]);
+ assert_eq!(decode_person_index(&value), vec![lsk(1), lsk(2)]);
+ }
+
+ #[test]
+ fn append_then_remove_leaves_the_set_empty() {
+ let value = collapse(None, [&append(1)[..], &remove(1)[..]]);
+ assert!(value.is_empty());
+ assert_eq!(decode_person_index(&value), vec![]);
+ }
+
+ /// Removing before the matching append is a no-op, so the key survives.
+ #[test]
+ fn remove_then_append_keeps_the_key() {
+ let value = collapse(None, [&remove(1)[..], &append(1)[..]]);
+ assert_eq!(decode_person_index(&value), vec![lsk(1)]);
+ }
+
+ #[test]
+ fn duplicate_appends_are_deduplicated_and_sorted() {
+ let value = collapse(None, [&append(2)[..], &append(1)[..], &append(2)[..]]);
+ assert_eq!(decode_person_index(&value), vec![lsk(1), lsk(2)]);
+ }
+
+ #[test]
+ fn merge_folds_into_an_existing_base() {
+ let base = collapse(None, [&append(1)[..]]);
+ let value = collapse(Some(&base), [&append(2)[..], &remove(1)[..]]);
+ assert_eq!(decode_person_index(&value), vec![lsk(2)]);
+ }
+
+ /// `partial_merge` grouping must not change the final set, whatever the grouping.
+ #[test]
+ fn partial_merge_grouping_is_invariant() {
+ let ops: [&[u8]; 3] = [&append(1), &append(2), &remove(1)];
+ let direct = collapse(None, ops);
+
+ let fully_grouped = concat_logs(ops);
+ assert_eq!(collapse(None, [&fully_grouped[..]]), direct);
+
+ let prefix = concat_logs([ops[0], ops[1]]);
+ assert_eq!(collapse(None, [&prefix[..], ops[2]]), direct);
+ }
+
+ #[test]
+ fn malformed_operand_length_does_not_panic_or_corrupt() {
+ let value = collapse(None, [&append(1)[..], &[0u8; 5][..], &append(2)[..]]);
+ assert_eq!(decode_person_index(&value), vec![lsk(1), lsk(2)]);
+
+ let mut corrupt_base = collapse(None, [&append(9)[..]]);
+ corrupt_base.push(0xFF);
+ let value = collapse(Some(&corrupt_base), [&append(8)[..]]);
+ assert_eq!(decode_person_index(&value), vec![lsk(8), lsk(9)]);
+ }
+
+ #[test]
+ fn unknown_operand_tag_is_skipped() {
+ let mut bad = [0u8; OPERAND_LEN];
+ bad[0] = 99;
+ let value = collapse(None, [&append(1)[..], &bad[..]]);
+ assert_eq!(decode_person_index(&value), vec![lsk(1)]);
+ }
+
+ #[test]
+ fn decode_person_index_of_empty_is_empty() {
+ assert_eq!(decode_person_index(&[]), vec![]);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/sweep/dispatch.rs b/rust/cohort-stream-processor/src/sweep/dispatch.rs
new file mode 100644
index 000000000000..5b1af7b4f637
--- /dev/null
+++ b/rust/cohort-stream-processor/src/sweep/dispatch.rs
@@ -0,0 +1,102 @@
+//! Routes one eviction cycle to every owned partition's worker.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use chrono::Utc;
+
+use super::scheduler::{due_before_ms, Sweeper};
+use crate::consumers::events::EventDispatcher;
+
+type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
+
+#[derive(Clone)]
+pub struct DispatchSweeper {
+ dispatcher: Arc<EventDispatcher>,
+ safety_margin_ms: i64,
+ now_ms: Clock,
+}
+
+impl DispatchSweeper {
+ pub fn new(dispatcher: Arc<EventDispatcher>, safety_margin_ms: i64) -> Self {
+ Self::with_clock(
+ dispatcher,
+ safety_margin_ms,
+ Arc::new(|| Utc::now().timestamp_millis()),
+ )
+ }
+
+ pub fn with_clock(
+ dispatcher: Arc<EventDispatcher>,
+ safety_margin_ms: i64,
+ now_ms: Clock,
+ ) -> Self {
+ Self {
+ dispatcher,
+ safety_margin_ms,
+ now_ms,
+ }
+ }
+}
+
+#[async_trait]
+impl Sweeper for DispatchSweeper {
+ async fn run_once(&self) {
+ let cutoff = due_before_ms((self.now_ms)(), self.safety_margin_ms);
+ self.dispatcher.route_sweep(cutoff).await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ use crate::consumers::events::EventDispatcher;
+ use crate::filters::{CatalogHandle, FilterCatalog};
+ use crate::partitions::{OffsetTracker, PartitionRouter};
+ use crate::producer::{CaptureSink, MembershipSink};
+ use crate::store::{CohortStore, StoreConfig};
+ use crate::workers::MergeWorkerDeps;
+
+ fn dispatcher() -> (TempDir, Arc<EventDispatcher>) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([])));
+ let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
+ let dispatcher = EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store,
+ catalog,
+ sink,
+ MergeWorkerDeps::capture(),
+ );
+ (dir, Arc::new(dispatcher))
+ }
+
+ #[tokio::test]
+ async fn run_once_routes_to_owned_partitions_without_panicking() {
+ let (_dir, dispatcher) = dispatcher();
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+
+ let sweeper = DispatchSweeper::with_clock(
+ dispatcher.clone(),
+ 300_000,
+ Arc::new(|| 1_700_000_000_000),
+ );
+ sweeper.run_once().await;
+ }
+
+ #[tokio::test]
+ async fn run_once_with_no_owned_partitions_is_a_noop() {
+ let (_dir, dispatcher) = dispatcher();
+ let sweeper = DispatchSweeper::new(dispatcher, 300_000);
+ sweeper.run_once().await;
+ }
+}
diff --git a/rust/cohort-stream-processor/src/sweep/eviction_queue.rs b/rust/cohort-stream-processor/src/sweep/eviction_queue.rs
new file mode 100644
index 000000000000..1cf8af663e9a
--- /dev/null
+++ b/rust/cohort-stream-processor/src/sweep/eviction_queue.rs
@@ -0,0 +1,336 @@
+//! [`EvictionQueue`]: the deadline-ordered queue the sweep drains soonest-first.
+//!
+//! A worker schedules each live behavioral key; the sweep drains keys whose deadline has passed.
+//! The timer is in [`super::scheduler`].
+//!
+//! # Why a `BTreeMap` + reverse index, not `BinaryHeap` + epoch map
+//!
+//! A key's deadline can move *earlier*, not just later: `daily_eviction_deadline`
+//! (`stage1/daily.rs`) returns the boundary of the **oldest non-zero bucket**, so a late event
+//! landing in a bucket older than the current oldest pulls the deadline backward. With a
+//! lazily-deleted heap, an earlier-reschedule leaves the superseded, far-future entry in the heap
+//! until its stale deadline eventually surfaces — up to the window length (≤180 days). Those
+//! accumulate and `heap.len()` grows with total reschedules while the live-key count stays flat: an
+//! unbounded leak unless you add compaction, and the natural compaction (store the live coordinate
+//! so you can find and remove the old one) *is* this shape.
+//!
+//! A `BTreeMap<(deadline_ms, seq), K>` keyed by `(deadline, seq)` is ordered, so the soonest-due key
+//! is `first_key_value`; a `HashMap<K, (deadline_ms, seq)>` reverse index lets a reschedule remove
+//! the superseded entry **precisely** in `O(log n)`, in either direction. `len()` therefore always
+//! equals the live-key count, and the staleness problem class disappears. `K` needs no `Ord` (it is
+//! the map *value*); `seq` is a global monotonic tiebreaker that only disambiguates two live keys
+//! sharing a deadline, giving a deterministic pop order.
+
+use std::collections::{BTreeMap, HashMap};
+use std::hash::Hash;
+
+/// The ordered coordinate of a live entry: its deadline (epoch ms) plus a monotonic tiebreaker.
+/// `Copy`, so it is cheaply read out of `by_deadline` before a mutating call.
+type Coord = (i64, u64);
+
+/// A deadline-ordered queue of keys, drained soonest-first by [`pop_due`](Self::pop_due).
+///
+/// Single-threaded by design: each partition worker owns one `EvictionQueue<Stage1Key>` and is the
+/// only mutator, so no internal synchronization is needed. Generic over `K` purely so the structure
+/// can be unit-tested in isolation from `Stage1Key`.
+///
+/// Invariant, upheld by every method: `by_deadline` and `index` hold exactly the same set of keys,
+/// so `by_deadline.len() == index.len() == ` the live-key count, and each key maps to exactly one
+/// coordinate in both directions.
+pub struct EvictionQueue<K> {
+ /// Keys ordered by `(deadline_ms, seq)`, so `first_key_value` is always the soonest due. `seq`
+ /// only breaks ties between equal deadlines.
+ by_deadline: BTreeMap<Coord, K>,
+ /// Reverse index `K → its live coordinate`, so a reschedule (or [`cancel`](Self::cancel)) removes
+ /// the superseded `by_deadline` entry precisely in `O(log n)` instead of leaving it to surface
+ /// stale later.
+ index: HashMap<K, Coord>,
+ /// Global monotonic tiebreaker handed to each scheduled entry. `u64` never realistically wraps:
+ /// even at a billion schedules a second it lasts ~580 years.
+ next_seq: u64,
+}
+
+impl<K> EvictionQueue<K>
+where
+ K: Hash + Eq + Clone,
+{
+ pub fn new() -> Self {
+ Self {
+ by_deadline: BTreeMap::new(),
+ index: HashMap::new(),
+ next_seq: 0,
+ }
+ }
+
+ /// Schedule `key` to evict at `deadline_ms`, or reschedule it if already present. A reschedule
+ /// removes the previous entry first (precise supersede), so the queue holds exactly one
+ /// coordinate per key whether the new deadline is later **or earlier** — and `len()` never grows
+ /// with reschedules.
+ pub fn schedule(&mut self, key: K, deadline_ms: i64) {
+ if let Some(&old_coord) = self.index.get(&key) {
+ self.by_deadline.remove(&old_coord);
+ }
+ let coord = (deadline_ms, self.next_seq);
+ self.next_seq += 1;
+ self.by_deadline.insert(coord, key.clone());
+ self.index.insert(key, coord);
+ }
+
+ /// Pop the soonest-due key whose deadline is **strictly before** `due_before_ms`, returning
+ /// `(key, deadline_ms)`; or [`None`] when the soonest live deadline is `>= due_before_ms` (i.e.
+ /// nothing is due yet). Drain a tick by calling this in a loop until it returns [`None`].
+ ///
+ /// The cutoff is `due_before_ms = now_ms − safety_margin_ms`, computed by the caller (see
+ /// [`due_before_ms`](super::scheduler::due_before_ms)) so the queue stays clock- and
+ /// arithmetic-free.
+ pub fn pop_due(&mut self, due_before_ms: i64) -> Option<(K, i64)> {
+ // Copy the soonest coordinate out, dropping the immutable borrow before the mutating remove.
+ let (&coord, _) = self.by_deadline.first_key_value()?;
+ let (deadline_ms, _) = coord;
+ if deadline_ms >= due_before_ms {
+ return None;
+ }
+ let key = self
+ .by_deadline
+ .remove(&coord)
+ .expect("the peeked coordinate is present");
+ self.index.remove(&key);
+ Some((key, deadline_ms))
+ }
+
+ /// Remove `key` from the queue, if present, so its pending eviction never fires.
+ pub fn cancel(&mut self, key: &K) {
+ if let Some(coord) = self.index.remove(key) {
+ self.by_deadline.remove(&coord);
+ }
+ }
+
+ /// The soonest live deadline, or [`None`] when empty. For observability.
+ pub fn peek_next_deadline(&self) -> Option<i64> {
+ self.by_deadline
+ .keys()
+ .next()
+ .map(|&(deadline, _)| deadline)
+ }
+
+ /// The number of live keys.
+ pub fn len(&self) -> usize {
+ self.by_deadline.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.by_deadline.is_empty()
+ }
+}
+
+impl<K> Default for EvictionQueue<K>
+where
+ K: Hash + Eq + Clone,
+{
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn drain<K: Hash + Eq + Clone>(
+ queue: &mut EvictionQueue<K>,
+ due_before_ms: i64,
+ ) -> Vec<(K, i64)> {
+ let mut out = Vec::new();
+ while let Some(entry) = queue.pop_due(due_before_ms) {
+ out.push(entry);
+ }
+ out
+ }
+
+ #[test]
+ fn pop_due_boundary_triple() {
+ // Strict `<`: at the exact cutoff and beyond, the key is held; one ms before, it is due.
+ let due_before = 1_000;
+ for (deadline, should_evict) in [
+ (due_before - 1, true),
+ (due_before, false),
+ (due_before + 1, false),
+ ] {
+ let mut queue = EvictionQueue::new();
+ queue.schedule("k", deadline);
+ let popped = queue.pop_due(due_before);
+ assert_eq!(
+ popped.is_some(),
+ should_evict,
+ "deadline {deadline} vs due_before {due_before}",
+ );
+ assert_eq!(queue.len(), if should_evict { 0 } else { 1 });
+ }
+ }
+
+ #[test]
+ fn reschedule_to_later_pops_once_at_the_later_deadline() {
+ let mut queue = EvictionQueue::new();
+ queue.schedule("k", 100);
+ queue.schedule("k", 500); // window slid forward
+ assert_eq!(queue.len(), 1, "reschedule must not duplicate the key");
+
+ // Nothing due at the original deadline anymore.
+ assert_eq!(queue.pop_due(101), None);
+ assert_eq!(queue.len(), 1);
+
+ assert_eq!(queue.pop_due(501), Some(("k", 500)));
+ assert_eq!(queue.len(), 0);
+ assert_eq!(queue.pop_due(501), None);
+ }
+
+ #[test]
+ fn reschedule_to_earlier_leaves_no_stale_entry() {
+ // The regression that motivates the BTreeMap: an earlier reschedule must remove the old
+ // far-future entry, so the key pops once at the earlier deadline and `len()` returns to 0.
+ let mut queue = EvictionQueue::new();
+ queue.schedule("k", 10_000); // far-future
+ queue.schedule("k", 200); // late event in an older bucket pulls it earlier
+ assert_eq!(queue.len(), 1);
+
+ assert_eq!(queue.pop_due(201), Some(("k", 200)));
+ assert_eq!(
+ queue.len(),
+ 0,
+ "the superseded far-future entry must not linger",
+ );
+ // Draining far past the old far-future deadline yields nothing — proof it is gone.
+ assert_eq!(queue.pop_due(1_000_000), None);
+ assert_eq!(queue.peek_next_deadline(), None);
+ }
+
+ #[test]
+ fn cancel_removes_the_key_so_it_never_pops() {
+ let mut queue = EvictionQueue::new();
+ queue.schedule("k", 100);
+ queue.cancel(&"k");
+ assert_eq!(queue.len(), 0);
+ assert!(queue.is_empty());
+ assert_eq!(queue.pop_due(1_000_000), None);
+
+ // Cancelling an absent key is a no-op.
+ queue.cancel(&"missing");
+ assert_eq!(queue.len(), 0);
+ }
+
+ #[test]
+ fn cancel_only_removes_the_named_key() {
+ let mut queue = EvictionQueue::new();
+ queue.schedule("a", 100);
+ queue.schedule("b", 200);
+ queue.cancel(&"a");
+ assert_eq!(queue.len(), 1);
+ assert_eq!(queue.pop_due(1_000), Some(("b", 200)));
+ }
+
+ #[test]
+ fn resurrection_after_pop_pops_again_at_the_new_deadline() {
+ let mut queue = EvictionQueue::new();
+ queue.schedule("k", 100);
+ assert_eq!(queue.pop_due(101), Some(("k", 100)));
+ assert_eq!(queue.len(), 0);
+
+ queue.schedule("k", 900);
+ assert_eq!(queue.len(), 1);
+ assert_eq!(queue.pop_due(200), None, "not due at the old deadline");
+ assert_eq!(queue.pop_due(901), Some(("k", 900)));
+ assert_eq!(queue.len(), 0);
+ }
+
+ #[test]
+ fn equal_deadlines_pop_in_insertion_order() {
+ // `seq` makes a shared deadline deterministic: FIFO by schedule order.
+ let mut queue = EvictionQueue::new();
+ for key in ["a", "b", "c", "d"] {
+ queue.schedule(key, 500);
+ }
+ let drained = drain(&mut queue, 501);
+ assert_eq!(
+ drained,
+ vec![("a", 500), ("b", 500), ("c", 500), ("d", 500)],
+ );
+ assert_eq!(queue.len(), 0);
+ }
+
+ #[test]
+ fn pop_due_drains_in_deadline_then_seq_order() {
+ let mut queue = EvictionQueue::new();
+ // Insert out of deadline order, with a tie at 200.
+ queue.schedule("late", 300);
+ queue.schedule("tie_first", 200);
+ queue.schedule("early", 100);
+ queue.schedule("tie_second", 200);
+
+ let drained = drain(&mut queue, 1_000);
+ assert_eq!(
+ drained,
+ vec![
+ ("early", 100),
+ ("tie_first", 200),
+ ("tie_second", 200),
+ ("late", 300),
+ ],
+ );
+ }
+
+ #[test]
+ fn peek_next_deadline_tracks_the_soonest_live_deadline() {
+ let mut queue = EvictionQueue::new();
+ assert_eq!(queue.peek_next_deadline(), None);
+
+ queue.schedule("a", 500);
+ assert_eq!(queue.peek_next_deadline(), Some(500));
+
+ queue.schedule("b", 200);
+ assert_eq!(queue.peek_next_deadline(), Some(200));
+
+ queue.schedule("b", 900);
+ assert_eq!(queue.peek_next_deadline(), Some(500));
+
+ queue.cancel(&"a");
+ assert_eq!(queue.peek_next_deadline(), Some(900));
+
+ assert_eq!(queue.pop_due(1_000), Some(("b", 900)));
+ assert_eq!(queue.peek_next_deadline(), None);
+ }
+
+ #[test]
+ fn very_negative_due_before_holds_everything_without_panic() {
+ // The caller's saturating `now − margin` (now small, margin huge) yields a far-negative
+ // cutoff. `pop_due` is pure arithmetic-free comparison, so it holds every real (positive)
+ // deadline — the safe "nothing due" direction — and never panics. See
+ // `scheduler::tests::due_before_saturates_when_margin_exceeds_now`.
+ let mut queue = EvictionQueue::new();
+ queue.schedule("k", 1);
+ let cutoff = 0_i64.saturating_sub(i64::MAX);
+ assert_eq!(queue.pop_due(cutoff), None);
+ assert_eq!(queue.pop_due(i64::MIN), None);
+ assert_eq!(queue.len(), 1);
+ }
+
+ #[test]
+ fn partial_drain_leaves_not_yet_due_keys() {
+ let mut queue = EvictionQueue::new();
+ queue.schedule("a", 100);
+ queue.schedule("b", 200);
+ queue.schedule("c", 300);
+
+ let drained = drain(&mut queue, 250);
+ assert_eq!(drained, vec![("a", 100), ("b", 200)]);
+ assert_eq!(queue.len(), 1);
+ assert_eq!(queue.peek_next_deadline(), Some(300));
+ }
+
+ #[test]
+ fn default_is_empty() {
+ let queue: EvictionQueue<&str> = EvictionQueue::default();
+ assert!(queue.is_empty());
+ assert_eq!(queue.len(), 0);
+ assert_eq!(queue.peek_next_deadline(), None);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/sweep/mod.rs b/rust/cohort-stream-processor/src/sweep/mod.rs
new file mode 100644
index 000000000000..44e9b22964db
--- /dev/null
+++ b/rust/cohort-stream-processor/src/sweep/mod.rs
@@ -0,0 +1,18 @@
+//! Time-driven eviction: the deadline-ordered queue the sweep drains and the periodic timer that
+//! drives it.
+//!
+//! The event path (Stage 1) computes an `earliest_eviction_at_ms` on every behavioral state but
+//! never reads a wall clock (`stage1/state.rs`). This module is the time-driven half that does:
+//!
+//! - [`EvictionQueue`] — the per-worker, deadline-ordered structure, drained soonest-first.
+//! - [`run_sweep_loop`] — the periodic timer that, each tick, asks a [`Sweeper`] to drain due keys.
+//! - [`due_before_ms`] — the `now − safety_margin` cutoff the worker feeds to
+//! [`EvictionQueue::pop_due`].
+
+pub mod dispatch;
+pub mod eviction_queue;
+pub mod scheduler;
+
+pub use dispatch::DispatchSweeper;
+pub use eviction_queue::EvictionQueue;
+pub use scheduler::{due_before_ms, run_sweep_loop, Sweeper};
diff --git a/rust/cohort-stream-processor/src/sweep/scheduler.rs b/rust/cohort-stream-processor/src/sweep/scheduler.rs
new file mode 100644
index 000000000000..36ade9101f2d
--- /dev/null
+++ b/rust/cohort-stream-processor/src/sweep/scheduler.rs
@@ -0,0 +1,159 @@
+//! The periodic sweep timer and its [`Sweeper`] seam, plus the safety-margin → cutoff bridge.
+//!
+//! The eviction queue is per-worker (one [`EvictionQueue`](super::EvictionQueue) per partition
+//! worker), so the timer itself owns no state. Each tick it asks a [`Sweeper`] to run one pass.
+
+use std::time::{Duration, Instant};
+
+use async_trait::async_trait;
+use metrics::{counter, histogram};
+use tokio::time::MissedTickBehavior;
+use tokio_util::sync::CancellationToken;
+use tracing::{debug, info};
+
+use crate::observability::metrics::{SWEEP_CYCLES_TOTAL, SWEEP_CYCLE_DURATION_SECONDS};
+
+/// One sweep pass. Behind a trait so [`run_sweep_loop`] is testable with an in-process fake.
+///
+/// Implementations must not panic: a panic in `run_once` would abort the timer task and stop all
+/// future sweeps. Any per-partition failure should be handled and counted inside the impl.
+#[async_trait]
+pub trait Sweeper: Send + Sync {
+ /// Perform one sweep cycle: evict every key whose deadline has passed (minus the safety margin).
+ async fn run_once(&self);
+}
+
+/// The cutoff a worker passes to [`EvictionQueue::pop_due`](super::EvictionQueue::pop_due): a key is
+/// due once its deadline is strictly before `now_ms − safety_margin_ms`.
+///
+/// Centralizes the only arithmetic in the sweep so the queue stays pure. `saturating_sub` keeps it
+/// total: a test clock with `now_ms < safety_margin_ms` yields a far-negative cutoff — below every
+/// real (positive) deadline, i.e. "nothing due", the safe direction — instead of overflowing.
+pub fn due_before_ms(now_ms: i64, safety_margin_ms: i64) -> i64 {
+ now_ms.saturating_sub(safety_margin_ms)
+}
+
+/// Drive the periodic sweep until `cancel` fires, invoking `sweeper.run_once()` once per tick and
+/// recording [`SWEEP_CYCLES_TOTAL`] + [`SWEEP_CYCLE_DURATION_SECONDS`], both labelled by `loop_name`.
+///
+/// `loop_name` (`eviction`|`redrive`|`merge_gc`|`checkpoint`) labels the cycle metrics so the
+/// concurrent loops — same timer machinery, different cadences — stay distinguishable.
+///
+/// - **`MissedTickBehavior::Skip`**: if a sweep runs long or the task is starved, the timer drops the
+/// ticks it slept through rather than firing a catch-up burst — one sweep then resumes on the
+/// normal cadence.
+/// - **`biased` select, cancel first**: a shutdown requested mid-interval is honored before the next
+/// tick. An in-flight `run_once` is never interrupted — `select!` only races the two *futures*, so
+/// once `run_once` is being polled it runs to completion before the loop re-checks `cancel`.
+pub async fn run_sweep_loop<S: Sweeper>(
+ sweeper: S,
+ interval: Duration,
+ loop_name: &'static str,
+ cancel: CancellationToken,
+) {
+ let mut ticker = tokio::time::interval(interval);
+ ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
+ info!(
+ interval_ms = interval.as_millis(),
+ loop_name, "sweep loop started"
+ );
+
+ loop {
+ tokio::select! {
+ biased;
+ _ = cancel.cancelled() => {
+ info!(loop_name, "sweep loop stopping on shutdown signal");
+ break;
+ }
+ _ = ticker.tick() => {
+ let started = Instant::now();
+ sweeper.run_once().await;
+ histogram!(SWEEP_CYCLE_DURATION_SECONDS, "loop" => loop_name)
+ .record(started.elapsed().as_secs_f64());
+ counter!(SWEEP_CYCLES_TOTAL, "loop" => loop_name).increment(1);
+ debug!(loop_name, "sweep cycle completed");
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Arc;
+
+ use super::*;
+
+ #[derive(Clone, Default)]
+ struct CountingSweeper {
+ count: Arc<AtomicUsize>,
+ }
+
+ #[async_trait]
+ impl Sweeper for CountingSweeper {
+ async fn run_once(&self) {
+ self.count.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ #[test]
+ fn due_before_subtracts_the_margin() {
+ assert_eq!(due_before_ms(1_000, 300), 700);
+ assert_eq!(due_before_ms(300, 300), 0, "now == margin → cutoff 0");
+ assert_eq!(due_before_ms(i64::MAX, 0), i64::MAX);
+ }
+
+ #[test]
+ fn due_before_saturates_when_margin_exceeds_now() {
+ // now small, margin huge → far-negative cutoff, no overflow panic. Below any real deadline,
+ // so the queue holds everything (the safe "nothing due" direction).
+ let cutoff = due_before_ms(0, i64::MAX);
+ assert!(cutoff < 0);
+ assert_eq!(cutoff, 0_i64.saturating_sub(i64::MAX));
+ }
+
+ #[tokio::test(flavor = "current_thread", start_paused = true)]
+ async fn sweep_loop_runs_once_per_interval() {
+ let sweeper = CountingSweeper::default();
+ let count = sweeper.count.clone();
+ let cancel = CancellationToken::new();
+ let interval = Duration::from_secs(30);
+
+ let handle = tokio::spawn(run_sweep_loop(sweeper, interval, "test", cancel.clone()));
+
+ // `tokio::time::interval`'s first tick fires immediately, so the loop sweeps once at startup.
+ tokio::task::yield_now().await;
+ assert_eq!(count.load(Ordering::SeqCst), 1, "immediate first tick");
+
+ // Each subsequent interval triggers exactly one more sweep — no catch-up bursts.
+ for expected in 2..=5 {
+ tokio::time::advance(interval).await;
+ tokio::task::yield_now().await;
+ assert_eq!(count.load(Ordering::SeqCst), expected);
+ }
+
+ cancel.cancel();
+ handle.await.expect("sweep loop exits cleanly on cancel");
+ }
+
+ #[tokio::test(flavor = "current_thread", start_paused = true)]
+ async fn sweep_loop_stops_on_cancel_and_runs_no_further() {
+ let sweeper = CountingSweeper::default();
+ let count = sweeper.count.clone();
+ let cancel = CancellationToken::new();
+ let interval = Duration::from_secs(30);
+
+ let handle = tokio::spawn(run_sweep_loop(sweeper, interval, "test", cancel.clone()));
+ tokio::task::yield_now().await;
+ assert_eq!(count.load(Ordering::SeqCst), 1);
+
+ cancel.cancel();
+ handle.await.expect("sweep loop exits cleanly on cancel");
+ let after_cancel = count.load(Ordering::SeqCst);
+
+ // Time advancing past the cancel must not produce more sweeps — the loop is gone.
+ tokio::time::advance(interval * 10).await;
+ tokio::task::yield_now().await;
+ assert_eq!(count.load(Ordering::SeqCst), after_cancel);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/cascade_path.rs b/rust/cohort-stream-processor/src/workers/cascade_path.rs
new file mode 100644
index 000000000000..f07d8912d6de
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/cascade_path.rs
@@ -0,0 +1,778 @@
+//! The cascade re-evaluation handler.
+//!
+//! [`handle_cascade`] re-evaluates every cohort that references the flipped cohort
+//! ([`TeamFilters::cohorts_referencing`]), emits each referrer's flip to `cohort_membership_changed`,
+//! and continues the chain to `cohort_cascade_events`, depth- and cycle-bounded by [`should_emit`].
+//! `cohort_cascade_events` is co-partitioned with `cohort_stream_events` so the worker that owns
+//! the person's `cf_stage2` always handles it.
+//!
+//! **Produce-before-state.** A referrer's new `cf_stage2` bit is committed only after both produces
+//! ack; a failure holds without writing, so replay re-detects the still-old bit and re-emits (the
+//! downstream UPSERT is idempotent). The cascade input is a fixed message that recomputes the same
+//! flip on replay — unlike Stage 2 composition, which dedupes by `cf_stage1`'s applied-offset and
+//! writes state-before-produce (at-most-once).
+
+use std::sync::Arc;
+
+use chrono::NaiveDateTime;
+use metrics::{counter, gauge, histogram};
+use tracing::{debug, warn};
+use uuid::Uuid;
+
+use crate::cascade::{should_emit, CascadeDecision, CascadeMessage, DropReason};
+use crate::filters::manager::CatalogHandle;
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::{CohortId, TeamId};
+use crate::observability::metrics::{
+ CASCADE_CYCLE_DETECTED_RUNTIME_TOTAL, CASCADE_DEPTH_EXCEEDED_TOTAL, CASCADE_DEPTH_OBSERVED,
+ CASCADE_FANOUT_CAPPED_TOTAL, CASCADE_HELD_OFFSET_GAUGE, COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH,
+};
+use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};
+use crate::producer::{CohortMembershipChange, MembershipSink};
+use crate::stage2::state::Stage2State;
+use crate::store::{CohortStore, Stage2Key};
+use crate::workers::merge_path::MergeWorkerDeps;
+use crate::workers::stage2_path::recompute_and_diff;
+use crate::workers::worker::{produce_cascades, produce_membership};
+
+/// Re-evaluate every referrer of the flipped cohort carried by one `cohort_cascade_events` message,
+/// emit their flips, continue the chain, and settle the cascade offset.
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn handle_cascade(
+ partition_id: u16,
+ store: &CohortStore,
+ catalog: &CatalogHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ last_updated: &str,
+ message: &CascadeMessage,
+ offset: i64,
+) {
+ // A config flip can leave a cascade queued after the gate closed; drain it rather than wedge.
+ if !merge.cascade.enabled {
+ mark_processed(&merge.cascade_tracker, partition_id, offset);
+ return;
+ }
+
+ histogram!(CASCADE_DEPTH_OBSERVED).record(f64::from(message.depth));
+
+ let snapshot = catalog.load();
+ let Some(filters) = snapshot.team(TeamId(message.change.team_id)) else {
+ mark_processed(&merge.cascade_tracker, partition_id, offset);
+ return;
+ };
+ let filters: &TeamFilters = filters;
+
+ let Ok(person_id) = Uuid::parse_str(&message.change.person_id) else {
+ mark_processed(&merge.cascade_tracker, partition_id, offset);
+ return;
+ };
+
+ let flipped = CohortId(message.change.cohort_id);
+ let referrers = filters.cohorts_referencing(flipped);
+ if referrers.is_empty() {
+ mark_processed(&merge.cascade_tracker, partition_id, offset);
+ return;
+ }
+
+ // The capped remainder is recovered only when each dropped referrer is re-evaluated on its next
+ // event; the sweep does not re-evaluate cohort-ref shapes with no behavioral leaf.
+ let referrers: &[CohortId] = if referrers.len() > merge.cascade.fanout_cap {
+ let dropped = (referrers.len() - merge.cascade.fanout_cap) as u64;
+ counter!(CASCADE_FANOUT_CAPPED_TOTAL).increment(dropped);
+ debug!(
+ upstream_cohort_id = message.change.cohort_id,
+ dropped, "cascade fan-out capped",
+ );
+ &referrers[..merge.cascade.fanout_cap]
+ } else {
+ referrers
+ };
+
+ let evaluated_at_ms = clickhouse_millis(last_updated);
+ let mut writes: Vec<(Stage2Key, Stage2State)> = Vec::new();
+ let mut changes: Vec<CohortMembershipChange> = Vec::new();
+ let mut outgoing: Vec<CascadeMessage> = Vec::new();
+ for &referrer in referrers {
+ // The reverse index includes excluded referrers (cycle members, unresolved refs); only
+ // re-evaluate cohorts maintained in `cf_stage2`, else a cycle member would re-enter the chain.
+ let composes = filters
+ .eligibility
+ .get(&referrer)
+ .is_some_and(|elig| elig.writes_cf_stage2());
+ if !composes {
+ continue;
+ }
+ let Some(tree) = filters.cohorts.get(&referrer) else {
+ continue;
+ };
+ let diff = match recompute_and_diff(partition_id, person_id, tree, filters, store) {
+ Ok(diff) => diff,
+ Err(error) => {
+ warn!(
+ partition_id,
+ team_id = message.change.team_id,
+ referrer = referrer.0,
+ error = %error,
+ "cascade recompute read failed; holding the cascade offset for redelivery",
+ );
+ hold(&merge.cascade_tracker, partition_id, offset);
+ return;
+ }
+ };
+ if !diff.flipped() {
+ continue;
+ }
+ let status = diff.status();
+ changes.push(CohortMembershipChange {
+ team_id: message.change.team_id,
+ cohort_id: referrer.0,
+ person_id: message.change.person_id.clone(),
+ last_updated: last_updated.to_string(),
+ status,
+ });
+ writes.push((
+ diff.stage2_key,
+ Stage2State {
+ in_cohort: diff.new_bit,
+ last_evaluated_at_ms: evaluated_at_ms,
+ },
+ ));
+ // The external flip above is unconditional; only the onward hop is depth/cycle bounded.
+ match should_emit(
+ message,
+ referrer,
+ status,
+ last_updated,
+ merge.cascade.depth_cap,
+ ) {
+ CascadeDecision::Emit { outgoing: hop } => outgoing.push(hop),
+ CascadeDecision::Drop {
+ reason: DropReason::DepthExceeded,
+ } => {
+ counter!(CASCADE_DEPTH_EXCEEDED_TOTAL).increment(1);
+ debug!(
+ originating_cohort_id = message.originating_cohort_id,
+ "cascade depth cap reached",
+ );
+ }
+ CascadeDecision::Drop {
+ reason: DropReason::CycleDetectedRuntime,
+ } => {
+ counter!(CASCADE_CYCLE_DETECTED_RUNTIME_TOTAL).increment(1);
+ debug!(
+ originating_cohort_id = message.originating_cohort_id,
+ cycle_cohort_id = referrer.0,
+ "cascade cycle detected at runtime",
+ );
+ }
+ }
+ }
+
+ if changes.is_empty() {
+ mark_processed(&merge.cascade_tracker, partition_id, offset);
+ return;
+ }
+
+ // Produce-before-state: both legs must ack before the bits commit (see the module doc).
+ let membership_errors = produce_membership(sink, changes).await;
+ if membership_errors > 0 {
+ warn!(
+ partition_id,
+ errors = membership_errors,
+ "cascade membership produce failed; holding the cascade offset for redelivery",
+ );
+ hold(&merge.cascade_tracker, partition_id, offset);
+ return;
+ }
+ let cascade_errors = produce_cascades(merge, outgoing).await;
+ if cascade_errors > 0 {
+ warn!(
+ partition_id,
+ errors = cascade_errors,
+ "cascade onward produce failed; holding the cascade offset for redelivery",
+ );
+ hold(&merge.cascade_tracker, partition_id, offset);
+ return;
+ }
+
+ if let Err(error) = store.write_batch(|batch| {
+ for (key, state) in &writes {
+ batch.put_stage2(key, &state.encode());
+ }
+ }) {
+ warn!(
+ partition_id,
+ error = %error,
+ "cascade cf_stage2 write failed; holding the cascade offset for redelivery",
+ );
+ hold(&merge.cascade_tracker, partition_id, offset);
+ return;
+ }
+
+ mark_processed(&merge.cascade_tracker, partition_id, offset);
+}
+
+/// Advance the cascade tracker past `offset`. A mark beyond the dispatch ceiling is capped and counted.
+fn mark_processed(tracker: &OffsetTracker, partition_id: u16, offset: i64) {
+ if let MarkOutcome::CappedAheadOfDispatch =
+ tracker.mark_processed(partition_id as i32, offset + 1)
+ {
+ counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);
+ warn!(
+ partition_id,
+ next_offset = offset + 1,
+ "cascade offset mark exceeded the dispatch ceiling and was capped (F1 invariant violation)",
+ );
+ }
+}
+
+/// Pin the cascade commit floor at the failed offset so Kafka redelivers it; emit
+/// [`CASCADE_HELD_OFFSET_GAUGE`] so the stall is visible.
+fn hold(tracker: &OffsetTracker, partition_id: u16, offset: i64) {
+ let floor = tracker.hold(partition_id as i32, offset);
+ gauge!(CASCADE_HELD_OFFSET_GAUGE, "partition" => partition_id.to_string()).set(floor as f64);
+}
+
+/// Parse a ClickHouse `DateTime64(6)` string into epoch millis, `0` on a miss. Feeds only the
+/// write-only `Stage2State::last_evaluated_at_ms`, so a miss costs a diagnostic timestamp, never
+/// membership.
+fn clickhouse_millis(ts: &str) -> i64 {
+ NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S%.f")
+ .map(|naive| naive.and_utc().timestamp_millis())
+ .unwrap_or(0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::UTC;
+ use serde_json::{json, Value};
+ use tempfile::TempDir;
+
+ use crate::cascade::first_cascade;
+ use crate::filters::{FilterCatalog, TeamFiltersBuilder};
+ use crate::producer::{
+ CaptureCascadeSink, CaptureSink, CaptureStreamEventSink, CaptureTransferSink,
+ MembershipStatus,
+ };
+ use crate::stage1::key::LeafStateKey;
+ use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
+ use crate::store::{Stage1Key, StoreConfig};
+ use crate::workers::{CascadeConfig, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT};
+
+ const TEAM: i32 = 7;
+ const PARTITION: u16 = 0;
+ const HASH: [u8; 16] = *b"0123456789abcdef";
+ const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
+ const TS: &str = "2026-06-16 00:00:00.000000";
+ const OFFSET: i64 = 5;
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ fn behavioral_leaf() -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": 7, "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn person_leaf() -> Value {
+ json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+ }
+
+ fn cohort_ref(target: i32) -> Value {
+ json!({ "type": "cohort", "value": target, "negation": false })
+ }
+
+ fn catalog(cohorts: Vec<(i32, Vec<Value>)>, cascade_enabled: bool) -> Arc<CatalogHandle> {
+ let mut builder = TeamFiltersBuilder::default();
+ for (id, values) in cohorts {
+ let cohort = json!({ "properties": { "type": "AND", "values": values } });
+ builder
+ .add_cohort(CohortId(id), TeamId(TEAM), &cohort)
+ .unwrap();
+ }
+ let filters = builder.freeze_with(UTC, cascade_enabled);
+ Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ filters,
+ )])))
+ }
+
+ fn behavioral_lsk(catalog: &CatalogHandle) -> LeafStateKey {
+ catalog
+ .load()
+ .team(TeamId(TEAM))
+ .unwrap()
+ .by_condition_to_lsk[&HASH][0]
+ }
+
+ fn person_lsk() -> LeafStateKey {
+ LeafStateKey::for_person_property(&PERSON_HASH)
+ }
+
+ fn person(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+ }
+
+ fn write_stage1(store: &CohortStore, lsk: LeafStateKey, who: Uuid, state: Stage1State) {
+ let key = Stage1Key {
+ partition_id: PARTITION,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: who,
+ };
+ let record = StatefulRecord::new(state, AppliedOffsets::default());
+ store
+ .write_batch(|b| b.put_stage1(&key, &record.encode()))
+ .unwrap();
+ }
+
+ fn write_stage2(store: &CohortStore, cohort: u64, who: Uuid, in_cohort: bool) {
+ let key = Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM as u64,
+ cohort_id: cohort,
+ person_id: who,
+ };
+ store
+ .write_batch(|b| {
+ b.put_stage2(
+ &key,
+ &Stage2State {
+ in_cohort,
+ last_evaluated_at_ms: 0,
+ }
+ .encode(),
+ )
+ })
+ .unwrap();
+ }
+
+ fn read_stage2(store: &CohortStore, cohort: u64, who: Uuid) -> Option<bool> {
+ let key = Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM as u64,
+ cohort_id: cohort,
+ person_id: who,
+ };
+ store
+ .get_stage2(&key)
+ .unwrap()
+ .map(|bytes| Stage2State::decode(&bytes).unwrap().in_cohort)
+ }
+
+ fn behavioral_match() -> Stage1State {
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: i64::MAX,
+ }
+ }
+
+ fn person_match() -> Stage1State {
+ Stage1State::PersonProperty {
+ matches: true,
+ last_updated_at_ms: 1,
+ last_updated_offset: 0,
+ }
+ }
+
+ /// Worker deps with the cascade gate on, capturing both the membership and cascade sinks.
+ fn deps(
+ membership: &CaptureSink,
+ cascade: &CaptureCascadeSink,
+ enabled: bool,
+ fanout_cap: usize,
+ ) -> (Arc<dyn MembershipSink>, MergeWorkerDeps) {
+ let sink: Arc<dyn MembershipSink> = Arc::new(membership.clone());
+ let deps = MergeWorkerDeps {
+ transfer_sink: Arc::new(CaptureTransferSink::new()),
+ stream_event_sink: Arc::new(CaptureStreamEventSink::new()),
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink: Arc::new(cascade.clone()),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: CascadeConfig {
+ enabled,
+ depth_cap: 8,
+ fanout_cap,
+ },
+ partition_count: crate::partitions::partitioner::COHORT_PARTITION_COUNT,
+ };
+ // The cascade was dispatched this tenure, so its ceiling is raised — mirrors the dispatcher.
+ deps.cascade_tracker
+ .mark_dispatched(PARTITION as i32, OFFSET + 1);
+ (sink, deps)
+ }
+
+ fn incoming(flipped: i32, who: Uuid, depth: u8, chain: Vec<i32>) -> CascadeMessage {
+ CascadeMessage {
+ change: CohortMembershipChange {
+ team_id: TEAM,
+ cohort_id: flipped,
+ person_id: who.to_string(),
+ last_updated: TS.to_string(),
+ status: MembershipStatus::Entered,
+ },
+ source_offset: 99,
+ depth,
+ originating_cohort_id: chain.first().copied().unwrap_or(flipped),
+ cascade_chain: chain,
+ }
+ }
+
+ fn committed(deps: &MergeWorkerDeps) -> Option<i64> {
+ deps.cascade_tracker
+ .committable_offsets()
+ .get(&(PARTITION as i32))
+ .copied()
+ }
+
+ /// A→B: B = AND(person, ref(A)) flips when A (single behavioral) becomes a member, emitting B's
+ /// external Entered and a depth-2 onward cascade `chain=[A, B]`.
+ #[tokio::test]
+ async fn a_flip_reevaluates_b_emits_membership_and_a_depth_two_cascade() {
+ let (_dir, store) = temp_store();
+ let catalog = catalog(
+ vec![
+ (2, vec![behavioral_leaf()]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+ write_stage1(&store, person_lsk(), alice, person_match());
+
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (sink, deps) = deps(&membership, &cascade, true, 1000);
+ let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+
+ let changes = membership.changes();
+ assert_eq!(changes.len(), 1, "B's external flip");
+ assert_eq!(changes[0].cohort_id, 1);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[0].person_id, alice.to_string());
+
+ let onward = cascade.messages();
+ assert_eq!(onward.len(), 1, "one onward cascade for B");
+ assert_eq!(onward[0].change.cohort_id, 1);
+ assert_eq!(onward[0].depth, 2, "depth 1 → 2");
+ assert_eq!(onward[0].cascade_chain, vec![2, 1]);
+ assert_eq!(onward[0].originating_cohort_id, 2);
+
+ assert_eq!(
+ read_stage2(&store, 1, alice),
+ Some(true),
+ "B's bit committed"
+ );
+ assert_eq!(committed(&deps), Some(OFFSET + 1), "offset advanced");
+ }
+
+ #[tokio::test]
+ async fn b_already_at_its_bit_emits_nothing_and_advances() {
+ let (_dir, store) = temp_store();
+ let catalog = catalog(
+ vec![
+ (2, vec![behavioral_leaf()]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+ write_stage1(&store, person_lsk(), alice, person_match());
+ write_stage2(&store, 1, alice, true); // B already a member
+
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (sink, deps) = deps(&membership, &cascade, true, 1000);
+ let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+
+ assert!(membership.changes().is_empty(), "no flip, no membership");
+ assert!(cascade.messages().is_empty(), "no flip, no onward cascade");
+ assert_eq!(committed(&deps), Some(OFFSET + 1), "still advances");
+ }
+
+ #[tokio::test]
+ async fn no_referrers_drains_without_emitting() {
+ let (_dir, store) = temp_store();
+ // Cohort 2 is single-leaf and referenced by nothing.
+ let catalog = catalog(vec![(2, vec![behavioral_leaf()])], true);
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (sink, deps) = deps(&membership, &cascade, true, 1000);
+ let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+
+ assert!(membership.changes().is_empty());
+ assert!(cascade.messages().is_empty());
+ assert_eq!(committed(&deps), Some(OFFSET + 1), "no-cross-talk drains");
+ }
+
+ #[tokio::test]
+ async fn gate_off_drains_without_reevaluating() {
+ let (_dir, store) = temp_store();
+ let catalog = catalog(
+ vec![
+ (2, vec![behavioral_leaf()]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+ write_stage1(&store, person_lsk(), alice, person_match());
+
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (sink, deps) = deps(&membership, &cascade, false, 1000); // gate OFF
+ let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+
+ assert!(membership.changes().is_empty(), "gate off: no re-eval");
+ assert!(cascade.messages().is_empty());
+ assert_eq!(read_stage2(&store, 1, alice), None, "no bit written");
+ assert_eq!(committed(&deps), Some(OFFSET + 1), "but the offset drains");
+ }
+
+ #[tokio::test]
+ async fn depth_cap_drops_the_onward_cascade_but_still_emits_b_membership() {
+ let (_dir, store) = temp_store();
+ let catalog = catalog(
+ vec![
+ (2, vec![behavioral_leaf()]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+ write_stage1(&store, person_lsk(), alice, person_match());
+
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (sink, deps) = deps(&membership, &cascade, true, 1000);
+ // Incoming depth == cap (8): the external flip still emits, the onward cascade drops.
+ let msg = incoming(2, alice, 8, vec![2, 90, 91, 92, 93, 94, 95, 96]);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+
+ assert_eq!(
+ membership.changes().len(),
+ 1,
+ "B's external flip still emits"
+ );
+ assert!(
+ cascade.messages().is_empty(),
+ "depth cap drops the onward hop"
+ );
+ assert_eq!(
+ read_stage2(&store, 1, alice),
+ Some(true),
+ "B's bit still commits"
+ );
+ assert_eq!(committed(&deps), Some(OFFSET + 1));
+ }
+
+ #[tokio::test]
+ async fn runtime_cycle_drops_the_onward_cascade_but_still_emits_b_membership() {
+ let (_dir, store) = temp_store();
+ let catalog = catalog(
+ vec![
+ (2, vec![behavioral_leaf()]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+ write_stage1(&store, person_lsk(), alice, person_match());
+
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (sink, deps) = deps(&membership, &cascade, true, 1000);
+ // B (cohort 1) is already in the chain: the onward hop is a runtime cycle.
+ let msg = incoming(2, alice, 2, vec![2, 1]);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+
+ assert_eq!(
+ membership.changes().len(),
+ 1,
+ "B's external flip still emits"
+ );
+ assert!(
+ cascade.messages().is_empty(),
+ "runtime cycle drops the onward hop"
+ );
+ assert_eq!(read_stage2(&store, 1, alice), Some(true));
+ }
+
+ #[tokio::test]
+ async fn fanout_cap_truncates_to_the_first_referrers() {
+ let (_dir, store) = temp_store();
+ // Cohort 100 (single behavioral) referenced by four cohorts, each sharing one person leaf.
+ let catalog = catalog(
+ vec![
+ (100, vec![behavioral_leaf()]),
+ (1, vec![person_leaf(), cohort_ref(100)]),
+ (2, vec![person_leaf(), cohort_ref(100)]),
+ (3, vec![person_leaf(), cohort_ref(100)]),
+ (4, vec![person_leaf(), cohort_ref(100)]),
+ ],
+ true,
+ );
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+ write_stage1(&store, person_lsk(), alice, person_match());
+
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (sink, deps) = deps(&membership, &cascade, true, 2); // cap 2 of 4 referrers
+ let msg = first_cascade(incoming(100, alice, 1, vec![100]).change, 99);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+
+ let cohorts: Vec<i32> = membership.changes().iter().map(|c| c.cohort_id).collect();
+ assert_eq!(
+ cohorts,
+ vec![1, 2],
+ "only the first two (sorted) referrers re-evaluated"
+ );
+ assert_eq!(
+ read_stage2(&store, 3, alice),
+ None,
+ "the capped remainder self-heals later"
+ );
+ }
+
+ #[tokio::test]
+ async fn replay_of_the_same_cascade_emits_only_once() {
+ let (_dir, store) = temp_store();
+ let catalog = catalog(
+ vec![
+ (2, vec![behavioral_leaf()]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+ write_stage1(&store, person_lsk(), alice, person_match());
+
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (sink, deps) = deps(&membership, &cascade, true, 1000);
+ let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ assert_eq!(membership.changes().len(), 1, "first pass emits");
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+ assert_eq!(
+ membership.changes().len(),
+ 1,
+ "replay re-detects no flip (B's bit is now set) and emits nothing",
+ );
+ }
+
+ #[tokio::test]
+ async fn membership_produce_failure_holds_without_writing_state() {
+ let (_dir, store) = temp_store();
+ let catalog = catalog(
+ vec![
+ (2, vec![behavioral_leaf()]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+ write_stage1(&store, person_lsk(), alice, person_match());
+
+ let membership = CaptureSink::failing_first(1);
+ let cascade = CaptureCascadeSink::new();
+ let (sink, deps) = deps(&membership, &cascade, true, 1000);
+ let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+
+ assert!(
+ membership.changes().is_empty(),
+ "the failed produce recorded nothing"
+ );
+ assert!(
+ cascade.messages().is_empty(),
+ "no onward cascade after a membership failure"
+ );
+ assert_eq!(read_stage2(&store, 1, alice), None, "no bit on a held flip");
+ assert_eq!(committed(&deps), None, "the offset is held for redelivery");
+ }
+
+ /// The membership leg acks but the onward cascade fails, so the bit is not committed and the
+ /// offset holds.
+ #[tokio::test]
+ async fn cascade_produce_failure_holds_without_writing_state() {
+ let (_dir, store) = temp_store();
+ let catalog = catalog(
+ vec![
+ (2, vec![behavioral_leaf()]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ let alice = person(1);
+ write_stage1(&store, behavioral_lsk(&catalog), alice, behavioral_match());
+ write_stage1(&store, person_lsk(), alice, person_match());
+
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::failing_always();
+ let (sink, deps) = deps(&membership, &cascade, true, 1000);
+ let msg = first_cascade(incoming(2, alice, 1, vec![2]).change, 99);
+
+ handle_cascade(PARTITION, &store, &catalog, &sink, &deps, TS, &msg, OFFSET).await;
+
+ assert_eq!(
+ membership.changes().len(),
+ 1,
+ "the membership leg already acked"
+ );
+ assert!(cascade.messages().is_empty(), "the onward cascade failed");
+ assert_eq!(
+ read_stage2(&store, 1, alice),
+ None,
+ "produce-before-state: the bit is not committed on a held flip, so replay recovers it",
+ );
+ assert_eq!(committed(&deps), None, "the offset is held for redelivery");
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rs
new file mode 100644
index 000000000000..e1af8b761ae8
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/event_path.rs
@@ -0,0 +1,835 @@
+//! The per-event read-modify-write — the Stage 1 "brain".
+//!
+//! [`process_event`] folds one re-keyed event into each affected leaf's RocksDB state under one
+//! atomic [`WriteBatch`](crate::store::CohortStore::write_batch) and returns the transitions that
+//! flipped. Transitions are surfaced only after the commit succeeds.
+
+use std::collections::BTreeMap;
+
+use metrics::counter;
+use uuid::Uuid;
+
+use crate::consumers::events::CohortStreamEvent;
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::TeamId;
+use crate::hogvm::{build_behavioral_globals, build_person_property_globals, evaluate};
+use crate::observability::metrics::{
+ STAGE1_ARGMAX_STALE, STAGE1_CONDITIONS_EVALUATED, STAGE1_PERSON_INDEX_APPENDS,
+ STAGE1_REPLAY_SKIPPED, STAGE1_STATE_DECODE_ERROR, STAGE1_STATE_WRITES,
+ STAGE1_UNSUPPORTED_VARIANT_SKIPPED,
+};
+use crate::stage1::bucket_tz::{
+ daily_bucket_len, day_idx_in_tz, now_day_for_window, window_start_for_now,
+};
+use crate::stage1::compressed_history;
+use crate::stage1::daily::{daily_eviction_deadline, slide_window_forward};
+use crate::stage1::key::{LeafStateKey, Stage1Key};
+use crate::stage1::pick_state::EvictionWindow;
+use crate::stage1::predicate::{compressed_predicate, daily_predicate, predicate};
+use crate::stage1::state::{
+ dedup_is_replay, dedup_record, AppliedOffsets, Stage1State, StateVariant, StatefulRecord,
+};
+use crate::stage1::time::clickhouse_timestamp_to_millis;
+use crate::stage1::transition::{LeafTransition, TransitionKind};
+use crate::store::{CohortStore, IndexOp, PersonIndexKey, StoreError};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SkipReason {
+ NullPersonId,
+ /// Non-empty but not a valid UUID.
+ UnparseablePersonId,
+ NoTeamFilters,
+ NoConditions,
+ GlobalsParseError,
+ BadTimestamp,
+}
+
+impl SkipReason {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::NullPersonId => "null_person_id",
+ Self::UnparseablePersonId => "unparseable_person_id",
+ Self::NoTeamFilters => "no_team_filters",
+ Self::NoConditions => "no_conditions",
+ Self::GlobalsParseError => "globals_parse_error",
+ Self::BadTimestamp => "bad_timestamp",
+ }
+ }
+}
+
+#[derive(Debug, Default, PartialEq, Eq)]
+pub struct EventOutcome {
+ pub transitions: Vec<LeafTransition>,
+ pub schedules: Vec<(Stage1Key, i64)>,
+ /// This event's parsed timestamp (epoch ms). `0` on skip/no-applies paths.
+ pub event_ms: i64,
+ pub skipped: Option<SkipReason>,
+}
+
+impl EventOutcome {
+ fn processed(
+ transitions: Vec<LeafTransition>,
+ schedules: Vec<(Stage1Key, i64)>,
+ event_ms: i64,
+ ) -> Self {
+ Self {
+ transitions,
+ schedules,
+ event_ms,
+ skipped: None,
+ }
+ }
+
+ fn skipped(reason: SkipReason) -> Self {
+ Self {
+ transitions: Vec::new(),
+ schedules: Vec::new(),
+ event_ms: 0,
+ skipped: Some(reason),
+ }
+ }
+}
+
+enum Apply {
+ /// Behavioral leaf matched (recorded only on match).
+ Behavioral {
+ lsk: LeafStateKey,
+ condition_hash: [u8; 16],
+ },
+ /// Person-property leaf evaluated (recorded on match *and* non-match).
+ Person {
+ lsk: LeafStateKey,
+ condition_hash: [u8; 16],
+ matches: bool,
+ },
+}
+
+impl Apply {
+ fn lsk(&self) -> LeafStateKey {
+ match self {
+ Self::Behavioral { lsk, .. } | Self::Person { lsk, .. } => *lsk,
+ }
+ }
+}
+
+struct PendingWrite {
+ key: Stage1Key,
+ bytes: Vec<u8>,
+ first_write: bool,
+ variant: StateVariant,
+}
+
+pub fn process_event(
+ partition_id: u16,
+ store: &CohortStore,
+ filters: &TeamFilters,
+ event: &CohortStreamEvent,
+) -> Result<EventOutcome, StoreError> {
+ if event.person_id.is_empty() {
+ return Ok(EventOutcome::skipped(SkipReason::NullPersonId));
+ }
+ let Ok(person_id) = Uuid::parse_str(&event.person_id) else {
+ return Ok(EventOutcome::skipped(SkipReason::UnparseablePersonId));
+ };
+
+ let origin: Option<Uuid> = event
+ .redirected_from
+ .as_deref()
+ .and_then(|raw| Uuid::parse_str(raw).ok());
+ let origin = origin.as_ref();
+
+ let has_behavioral = !filters.behavioral_conditions.is_empty();
+ let has_person = !filters.person_property_conditions.is_empty();
+ if !has_behavioral && !has_person {
+ return Ok(EventOutcome::skipped(SkipReason::NoConditions));
+ }
+
+ let behavioral_globals = if has_behavioral {
+ match build_behavioral_globals(event) {
+ Ok(globals) => Some(globals),
+ Err(_) => return Ok(EventOutcome::skipped(SkipReason::GlobalsParseError)),
+ }
+ } else {
+ None
+ };
+ let person_active = has_person
+ && event
+ .person_properties
+ .as_deref()
+ .is_some_and(|raw| !raw.is_empty());
+ let person_globals = if person_active {
+ match build_person_property_globals(event) {
+ Ok(globals) => Some(globals),
+ Err(_) => return Ok(EventOutcome::skipped(SkipReason::GlobalsParseError)),
+ }
+ } else {
+ None
+ };
+
+ let applies = collect_applies(
+ filters,
+ behavioral_globals.as_ref(),
+ person_globals.as_ref(),
+ );
+ if applies.is_empty() {
+ return Ok(EventOutcome::processed(Vec::new(), Vec::new(), 0));
+ }
+
+ let Some(event_ms) = clickhouse_timestamp_to_millis(&event.timestamp) else {
+ return Ok(EventOutcome::skipped(SkipReason::BadTimestamp));
+ };
+
+ let team_id = event.team_id as u64;
+ let mut transitions = Vec::new();
+ let mut schedules: Vec<(Stage1Key, i64)> = Vec::new();
+ let mut pending = Vec::new();
+
+ for apply in &applies {
+ let key = Stage1Key {
+ partition_id,
+ team_id,
+ leaf_state_key: apply.lsk(),
+ person_id,
+ };
+
+ let prev = match store.get_stage1(&key)? {
+ None => None,
+ Some(bytes) => match StatefulRecord::decode(&bytes) {
+ Ok(record) => Some(record),
+ Err(_) => {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ continue;
+ }
+ },
+ };
+ let first_write = prev.is_none();
+
+ let mutation = match apply {
+ Apply::Behavioral { condition_hash, .. } => {
+ match filters.by_lsk.get(&apply.lsk()).map(|meta| meta.variant) {
+ Some(StateVariant::BehavioralDailyBuckets) => mutate_behavioral_daily(
+ filters,
+ apply.lsk(),
+ *condition_hash,
+ person_id,
+ origin,
+ event,
+ event_ms,
+ prev,
+ ),
+ Some(StateVariant::BehavioralCompressedHistory) => {
+ mutate_behavioral_compressed(
+ filters,
+ apply.lsk(),
+ *condition_hash,
+ person_id,
+ origin,
+ event,
+ event_ms,
+ prev,
+ )
+ }
+ _ => mutate_behavioral(
+ filters,
+ apply.lsk(),
+ *condition_hash,
+ person_id,
+ origin,
+ event,
+ event_ms,
+ prev,
+ ),
+ }
+ }
+ Apply::Person {
+ condition_hash,
+ matches,
+ ..
+ } => mutate_person(
+ apply.lsk(),
+ *condition_hash,
+ *matches,
+ person_id,
+ origin,
+ event,
+ event_ms,
+ prev,
+ ),
+ };
+
+ let Some((record, transition)) = mutation else {
+ continue;
+ };
+
+ if let Some(transition) = transition {
+ transitions.push(transition);
+ }
+ if let Some(deadline) = schedule_deadline(&record.state) {
+ schedules.push((key, deadline));
+ }
+ pending.push(PendingWrite {
+ variant: record.state.variant(),
+ bytes: record.encode(),
+ key,
+ first_write,
+ });
+ }
+
+ if !pending.is_empty() {
+ let person_index = PersonIndexKey {
+ partition_id,
+ team_id,
+ person_id,
+ };
+ store.write_batch(|batch| {
+ for write in &pending {
+ batch.put_stage1(&write.key, &write.bytes);
+ if write.first_write {
+ batch.merge_person_index(
+ &person_index,
+ IndexOp::Append(write.key.leaf_state_key),
+ );
+ }
+ }
+ })?;
+
+ for write in &pending {
+ counter!(STAGE1_STATE_WRITES, "variant" => write.variant.as_str()).increment(1);
+ if write.first_write {
+ counter!(STAGE1_PERSON_INDEX_APPENDS).increment(1);
+ }
+ }
+ }
+
+ Ok(EventOutcome::processed(transitions, schedules, event_ms))
+}
+
+/// Returns `None` for permanent-membership states (`i64::MAX` sentinel), so only time-bounded
+/// leaves get scheduled for sweep eviction.
+pub(crate) fn schedule_deadline(state: &Stage1State) -> Option<i64> {
+ state.eviction_deadline().filter(|&d| d != i64::MAX)
+}
+
+fn collect_applies(
+ filters: &TeamFilters,
+ behavioral_globals: Option<&serde_json::Value>,
+ person_globals: Option<&serde_json::Value>,
+) -> Vec<Apply> {
+ let mut applies = Vec::new();
+
+ if let Some(globals) = behavioral_globals {
+ for &hash in &filters.behavioral_conditions {
+ let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
+ continue;
+ };
+ counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "behavioral").increment(1);
+ if !evaluate(bytecode, globals.clone()) {
+ continue;
+ }
+ let Some(lsks) = filters.by_condition_to_lsk.get(&hash) else {
+ continue;
+ };
+ for &lsk in lsks {
+ match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {
+ Some(
+ StateVariant::BehavioralSingle
+ | StateVariant::BehavioralDailyBuckets
+ | StateVariant::BehavioralCompressedHistory,
+ ) => {
+ applies.push(Apply::Behavioral {
+ lsk,
+ condition_hash: hash,
+ });
+ }
+ Some(other) => {
+ counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => other.as_str())
+ .increment(1);
+ }
+ None => {}
+ }
+ }
+ }
+ }
+
+ if let Some(globals) = person_globals {
+ for &hash in &filters.person_property_conditions {
+ let Some(bytecode) = filters.by_condition_to_bytecode.get(&hash) else {
+ continue;
+ };
+ counter!(STAGE1_CONDITIONS_EVALUATED, "kind" => "person_property").increment(1);
+ let matches = evaluate(bytecode, globals.clone());
+ let lsk = LeafStateKey::for_person_property(&hash);
+ match filters.by_lsk.get(&lsk).map(|meta| meta.variant) {
+ Some(StateVariant::PersonProperty) => {
+ applies.push(Apply::Person {
+ lsk,
+ condition_hash: hash,
+ matches,
+ });
+ }
+ Some(other) => {
+ counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => other.as_str())
+ .increment(1);
+ }
+ None => {}
+ }
+ }
+ }
+
+ applies
+}
+
+/// Fold a behavioral match into a single-bit leaf. Never emits `Left` (match is never cleared).
+#[allow(clippy::too_many_arguments)]
+fn mutate_behavioral(
+ filters: &TeamFilters,
+ lsk: LeafStateKey,
+ condition_hash: [u8; 16],
+ person_id: Uuid,
+ origin: Option<&Uuid>,
+ event: &CohortStreamEvent,
+ event_ms: i64,
+ prev: Option<StatefulRecord>,
+) -> Option<(StatefulRecord, Option<LeafTransition>)> {
+ let (prev_last_event, predicate_before, mut applied, mut redirect_dedup) = match prev {
+ None => (i64::MIN, false, AppliedOffsets::default(), BTreeMap::new()),
+ Some(record) => {
+ let predicate_before = predicate(&record.state);
+ match record.state {
+ Stage1State::BehavioralSingle {
+ last_event_at_ms, ..
+ } => (
+ last_event_at_ms,
+ predicate_before,
+ record.applied_offsets,
+ record.redirect_dedup,
+ ),
+ _ => {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ return None;
+ }
+ }
+ }
+ };
+
+ let window = filters.by_lsk.get(&lsk).and_then(|meta| meta.window);
+
+ // Explicit range: day-granularity, inclusive, matching `date >= toDate(from) AND date <= toDate(to)`.
+ // The bound is a tz-naive calendar day, compared directly to `day_idx_in_tz(event_ms, tz)` —
+ // never re-projected through a timezone (which would shift it one day for UTC-offset teams).
+ // Out-of-range events are dropped completely: no dedup record, no state, no transition.
+ if let Some(EvictionWindow::Explicit { from_day, to_day }) = window {
+ let event_day = day_idx_in_tz(event_ms, filters.timezone);
+ let before_from = from_day.is_some_and(|f| event_day < f);
+ let after_to = to_day.is_some_and(|t| event_day > t);
+ if before_from || after_to {
+ return None;
+ }
+ }
+
+ if dedup_is_replay(
+ &applied,
+ &redirect_dedup,
+ origin,
+ event.source_partition,
+ event.source_offset,
+ ) {
+ counter!(STAGE1_REPLAY_SKIPPED, "variant" => StateVariant::BehavioralSingle.as_str())
+ .increment(1);
+ return None;
+ }
+ dedup_record(
+ &mut applied,
+ &mut redirect_dedup,
+ origin,
+ event.source_partition,
+ event.source_offset,
+ );
+
+ let last_event_at_ms = prev_last_event.max(event_ms);
+ let earliest_eviction_at_ms = window.map_or(i64::MAX, |w| {
+ w.earliest_eviction_at_ms(last_event_at_ms, filters.timezone)
+ });
+
+ let record = StatefulRecord {
+ state: Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms,
+ earliest_eviction_at_ms,
+ },
+ applied_offsets: applied,
+ redirect_dedup,
+ };
+ let transition = if predicate_before {
+ None
+ } else {
+ Some(LeafTransition {
+ team_id: TeamId(event.team_id),
+ leaf_state_key: lsk,
+ person_id,
+ condition_hash,
+ kind: TransitionKind::Entered,
+ })
+ };
+ Some((record, transition))
+}
+
+/// Fold a `performed_event_multiple` match into a dense daily-bucket state. A window slide can
+/// drop the count below threshold and emit `Left`.
+#[allow(clippy::too_many_arguments)]
+fn mutate_behavioral_daily(
+ filters: &TeamFilters,
+ lsk: LeafStateKey,
+ condition_hash: [u8; 16],
+ person_id: Uuid,
+ origin: Option<&Uuid>,
+ event: &CohortStreamEvent,
+ event_ms: i64,
+ prev: Option<StatefulRecord>,
+) -> Option<(StatefulRecord, Option<LeafTransition>)> {
+ let (Some(window_days), Some(op)) = filters
+ .by_lsk
+ .get(&lsk)
+ .map_or((None, None), |meta| (meta.window_days, meta.predicate_op))
+ else {
+ counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => StateVariant::BehavioralDailyBuckets.as_str())
+ .increment(1);
+ return None;
+ };
+ let tz = filters.timezone;
+ let len = daily_bucket_len(window_days);
+
+ let (prior_buckets, prior_window_start_day, prev_last_event, mut applied, mut redirect_dedup) =
+ match prev {
+ None => (
+ None,
+ 0_i32,
+ i64::MIN,
+ AppliedOffsets::default(),
+ BTreeMap::new(),
+ ),
+ Some(record) => match record.state {
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day,
+ last_event_at_ms,
+ ..
+ } => (
+ Some(buckets),
+ window_start_day,
+ last_event_at_ms,
+ record.applied_offsets,
+ record.redirect_dedup,
+ ),
+ _ => {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ return None;
+ }
+ },
+ };
+
+ if dedup_is_replay(
+ &applied,
+ &redirect_dedup,
+ origin,
+ event.source_partition,
+ event.source_offset,
+ ) {
+ counter!(STAGE1_REPLAY_SKIPPED, "variant" => StateVariant::BehavioralDailyBuckets.as_str())
+ .increment(1);
+ return None;
+ }
+ dedup_record(
+ &mut applied,
+ &mut redirect_dedup,
+ origin,
+ event.source_partition,
+ event.source_offset,
+ );
+
+ let mut buckets = match prior_buckets {
+ Some(buckets) if buckets.len() == len => buckets,
+ Some(_) => {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ return None;
+ }
+ None => Vec::new(),
+ };
+
+ let predicate_before = daily_predicate(&buckets, op);
+
+ let event_day = day_idx_in_tz(event_ms, tz);
+ let mut window_start_day = if buckets.is_empty() {
+ buckets = vec![0; len];
+ window_start_for_now(event_day, window_days)
+ } else {
+ prior_window_start_day
+ };
+
+ let cur_now_day = now_day_for_window(window_start_day, window_days);
+ if event_day > cur_now_day {
+ slide_window_forward(&mut buckets, &mut window_start_day, window_days, event_day);
+ let last = len - 1;
+ buckets[last] = buckets[last].saturating_add(1);
+ } else if event_day < window_start_day {
+ } else {
+ let idx = (event_day - window_start_day) as usize;
+ buckets[idx] = buckets[idx].saturating_add(1);
+ }
+
+ let last_event_at_ms = prev_last_event.max(event_ms);
+ let earliest_eviction_at_ms =
+ daily_eviction_deadline(&buckets, window_start_day, window_days, tz);
+ let predicate_after = daily_predicate(&buckets, op);
+
+ let record = StatefulRecord {
+ state: Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day,
+ last_event_at_ms,
+ earliest_eviction_at_ms,
+ },
+ applied_offsets: applied,
+ redirect_dedup,
+ };
+ let kind = match (predicate_before, predicate_after) {
+ (false, true) => Some(TransitionKind::Entered),
+ (true, false) => Some(TransitionKind::Left),
+ _ => None,
+ };
+ let transition = kind.map(|kind| LeafTransition {
+ team_id: TeamId(event.team_id),
+ leaf_state_key: lsk,
+ person_id,
+ condition_hash,
+ kind,
+ });
+ Some((record, transition))
+}
+
+/// Fold a `performed_event_multiple` match into sparse compressed-history state (>180-day windows).
+#[allow(clippy::too_many_arguments)]
+fn mutate_behavioral_compressed(
+ filters: &TeamFilters,
+ lsk: LeafStateKey,
+ condition_hash: [u8; 16],
+ person_id: Uuid,
+ origin: Option<&Uuid>,
+ event: &CohortStreamEvent,
+ event_ms: i64,
+ prev: Option<StatefulRecord>,
+) -> Option<(StatefulRecord, Option<LeafTransition>)> {
+ let (Some(window_days), Some(op)) = filters
+ .by_lsk
+ .get(&lsk)
+ .map_or((None, None), |meta| (meta.window_days, meta.predicate_op))
+ else {
+ counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => StateVariant::BehavioralCompressedHistory.as_str())
+ .increment(1);
+ return None;
+ };
+ let tz = filters.timezone;
+
+ let (prior_entries, prior_window_start_day, prev_last_event, mut applied, mut redirect_dedup) =
+ match prev {
+ None => (
+ None,
+ 0_i32,
+ i64::MIN,
+ AppliedOffsets::default(),
+ BTreeMap::new(),
+ ),
+ Some(record) => match record.state {
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day,
+ last_event_at_ms,
+ ..
+ } => (
+ Some(entries),
+ window_start_day,
+ last_event_at_ms,
+ record.applied_offsets,
+ record.redirect_dedup,
+ ),
+ _ => {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ return None;
+ }
+ },
+ };
+
+ if dedup_is_replay(
+ &applied,
+ &redirect_dedup,
+ origin,
+ event.source_partition,
+ event.source_offset,
+ ) {
+ counter!(STAGE1_REPLAY_SKIPPED, "variant" => StateVariant::BehavioralCompressedHistory.as_str())
+ .increment(1);
+ return None;
+ }
+ dedup_record(
+ &mut applied,
+ &mut redirect_dedup,
+ origin,
+ event.source_partition,
+ event.source_offset,
+ );
+
+ let first_write = prior_entries.is_none();
+ let mut entries = prior_entries.unwrap_or_default();
+
+ let predicate_before = compressed_predicate(&entries, op);
+
+ let event_day = day_idx_in_tz(event_ms, tz);
+ let mut window_start_day = if first_write {
+ window_start_for_now(event_day, window_days)
+ } else {
+ prior_window_start_day
+ };
+
+ let cur_now_day = now_day_for_window(window_start_day, window_days);
+ if event_day > cur_now_day {
+ compressed_history::slide_window_forward(
+ &mut entries,
+ &mut window_start_day,
+ window_days,
+ event_day,
+ );
+ compressed_history::insert_event(&mut entries, event_day);
+ } else if event_day < window_start_day {
+ } else {
+ compressed_history::insert_event(&mut entries, event_day);
+ }
+
+ let last_event_at_ms = prev_last_event.max(event_ms);
+ let earliest_eviction_at_ms =
+ compressed_history::compressed_eviction_deadline(&entries, window_days, tz);
+ let predicate_after = compressed_predicate(&entries, op);
+
+ let record = StatefulRecord {
+ state: Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day,
+ last_event_at_ms,
+ earliest_eviction_at_ms,
+ },
+ applied_offsets: applied,
+ redirect_dedup,
+ };
+ let kind = match (predicate_before, predicate_after) {
+ (false, true) => Some(TransitionKind::Entered),
+ (true, false) => Some(TransitionKind::Left),
+ _ => None,
+ };
+ let transition = kind.map(|kind| LeafTransition {
+ team_id: TeamId(event.team_id),
+ leaf_state_key: lsk,
+ person_id,
+ condition_hash,
+ kind,
+ });
+ Some((record, transition))
+}
+
+/// Fold a person-property evaluation into a leaf's state with replay-dedup and argMax tiebreaker.
+#[allow(clippy::too_many_arguments)]
+fn mutate_person(
+ lsk: LeafStateKey,
+ condition_hash: [u8; 16],
+ matches: bool,
+ person_id: Uuid,
+ origin: Option<&Uuid>,
+ event: &CohortStreamEvent,
+ event_ms: i64,
+ prev: Option<StatefulRecord>,
+) -> Option<(StatefulRecord, Option<LeafTransition>)> {
+ let (prev_matches, prev_updated_at, prev_updated_offset, mut applied, mut redirect_dedup) =
+ match prev {
+ None => (
+ false,
+ i64::MIN,
+ i64::MIN,
+ AppliedOffsets::default(),
+ BTreeMap::new(),
+ ),
+ Some(record) => match record.state {
+ Stage1State::PersonProperty {
+ matches,
+ last_updated_at_ms,
+ last_updated_offset,
+ } => (
+ matches,
+ last_updated_at_ms,
+ last_updated_offset,
+ record.applied_offsets,
+ record.redirect_dedup,
+ ),
+ _ => {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ return None;
+ }
+ },
+ };
+
+ if dedup_is_replay(
+ &applied,
+ &redirect_dedup,
+ origin,
+ event.source_partition,
+ event.source_offset,
+ ) {
+ counter!(STAGE1_REPLAY_SKIPPED, "variant" => StateVariant::PersonProperty.as_str())
+ .increment(1);
+ return None;
+ }
+ dedup_record(
+ &mut applied,
+ &mut redirect_dedup,
+ origin,
+ event.source_partition,
+ event.source_offset,
+ );
+
+ if (event_ms, event.source_offset) <= (prev_updated_at, prev_updated_offset) {
+ counter!(STAGE1_ARGMAX_STALE).increment(1);
+ let record = StatefulRecord {
+ state: Stage1State::PersonProperty {
+ matches: prev_matches,
+ last_updated_at_ms: prev_updated_at,
+ last_updated_offset: prev_updated_offset,
+ },
+ applied_offsets: applied,
+ redirect_dedup,
+ };
+ return Some((record, None));
+ }
+
+ let record = StatefulRecord {
+ state: Stage1State::PersonProperty {
+ matches,
+ last_updated_at_ms: event_ms,
+ last_updated_offset: event.source_offset,
+ },
+ applied_offsets: applied,
+ redirect_dedup,
+ };
+ let transition = if matches == prev_matches {
+ None
+ } else {
+ Some(LeafTransition {
+ team_id: TeamId(event.team_id),
+ leaf_state_key: lsk,
+ person_id,
+ condition_hash,
+ kind: if matches {
+ TransitionKind::Entered
+ } else {
+ TransitionKind::Left
+ },
+ })
+ };
+ Some((record, transition))
+}
diff --git a/rust/cohort-stream-processor/src/workers/merge_gc.rs b/rust/cohort-stream-processor/src/workers/merge_gc.rs
new file mode 100644
index 000000000000..cfb215938594
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/merge_gc.rs
@@ -0,0 +1,518 @@
+//! Worker-side merge-CF garbage collection.
+//!
+//! [`handle_merge_gc`] runs on the partition worker in response to a
+//! [`ShuffleMessage::MergeCfGc`](crate::partitions::shuffle_message::ShuffleMessage::MergeCfGc). For
+//! each GC-able merge CF it scans the partition's slice (capped per tick), decodes the value
+//! timestamp, and batch-deletes every entry older than the relevant cutoff in one `write_batch`. A
+//! per-CF in-memory resume cursor ([`MergeGcCursor`]) continues each tick where the last one stopped
+//! and wraps to the prefix start on exhaustion.
+//!
+//! Posture choices a reader can't recover from the code:
+//! - **Undecodable value → delete + count.** An unreadable timestamp can never age out, so it would
+//! leak forever. Deleting it costs at most one bounded replay of the 7d-retention source topic.
+//! Counted on [`MERGE_GC_UNDECODABLE_TOTAL`].
+//! - **`cf_pending_transfers` is never GC'd here.** It is the redrive's outbox (drained by
+//! [`crate::merge::redrive`]), not a marker that ages out — GCing it would drop a staged,
+//! never-produced transfer. It is simply absent from [`GC_CFS`].
+
+use metrics::counter;
+use tracing::warn;
+
+use crate::merge::transfer::{ApplyStamp, DrainStamp, Tombstone};
+use crate::observability::metrics::{
+ MERGE_GC_KEYS_DELETED_TOTAL, MERGE_GC_KEYS_SCANNED_TOTAL, MERGE_GC_UNDECODABLE_TOTAL,
+};
+use crate::store::keys::{MergeAppliedKey, MergeDrainKey, TombstoneKey};
+use crate::store::{BatchBuilder, Cf, CohortStore};
+
+/// The merge CFs the GC sweep evicts. `cf_pending_transfers` is deliberately excluded (see the
+/// module doc).
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+enum GcCf {
+ /// Drain marker (`DrainStamp.drained_at_ms`), evicted below the marker cutoff.
+ DrainsApplied,
+ /// Apply marker (`ApplyStamp.applied_at_ms`), evicted below the marker cutoff.
+ Applied,
+ /// Redirect tombstone (`Tombstone.merged_at_ms`), evicted below the (longer) tombstone cutoff.
+ Tombstones,
+}
+
+const GC_CFS: [GcCf; 3] = [GcCf::DrainsApplied, GcCf::Applied, GcCf::Tombstones];
+
+impl GcCf {
+ fn cf(self) -> Cf {
+ match self {
+ GcCf::DrainsApplied => Cf::MergeDrainsApplied,
+ GcCf::Applied => Cf::MergeApplied,
+ GcCf::Tombstones => Cf::MergeTombstones,
+ }
+ }
+
+ fn label(self) -> &'static str {
+ self.cf().as_str()
+ }
+}
+
+/// Per-worker resume cursors, one raw last-key per GC CF. `None` restarts the next scan at the
+/// partition's prefix start (the wrap-on-exhaustion state). Loss on a rebalance is benign: a fresh
+/// tenure rescans from the start, and re-scanning an already-deleted key is a no-op.
+#[derive(Default)]
+pub struct MergeGcCursor {
+ drains_applied: Option<Vec<u8>>,
+ applied: Option<Vec<u8>>,
+ tombstones: Option<Vec<u8>>,
+}
+
+impl MergeGcCursor {
+ fn get(&self, cf: GcCf) -> Option<&[u8]> {
+ match cf {
+ GcCf::DrainsApplied => self.drains_applied.as_deref(),
+ GcCf::Applied => self.applied.as_deref(),
+ GcCf::Tombstones => self.tombstones.as_deref(),
+ }
+ }
+
+ fn set(&mut self, cf: GcCf, value: Option<Vec<u8>>) {
+ match cf {
+ GcCf::DrainsApplied => self.drains_applied = value,
+ GcCf::Applied => self.applied = value,
+ GcCf::Tombstones => self.tombstones = value,
+ }
+ }
+}
+
+/// GC one partition's three merge CFs for one tick. `marker_cutoff_ms` gates the two idempotence
+/// markers; `tombstone_cutoff_ms` (longer) gates tombstones.
+pub fn handle_merge_gc(
+ partition_id: u16,
+ store: &CohortStore,
+ cursor: &mut MergeGcCursor,
+ marker_cutoff_ms: i64,
+ tombstone_cutoff_ms: i64,
+ scan_limit: usize,
+) {
+ for gc_cf in GC_CFS {
+ let cutoff = match gc_cf {
+ GcCf::DrainsApplied | GcCf::Applied => marker_cutoff_ms,
+ GcCf::Tombstones => tombstone_cutoff_ms,
+ };
+ sweep_one_cf(partition_id, store, cursor, gc_cf, cutoff, scan_limit);
+ }
+}
+
+/// Scan one CF up to the cap, collect expired/undecodable keys, delete them in one batch, and
+/// advance the cursor (wrapping on exhaustion).
+fn sweep_one_cf(
+ partition_id: u16,
+ store: &CohortStore,
+ cursor: &mut MergeGcCursor,
+ gc_cf: GcCf,
+ cutoff_ms: i64,
+ scan_limit: usize,
+) {
+ let cf = gc_cf.cf();
+ let label = gc_cf.label();
+
+ let entries = match store.scan_merge_cf(cf, partition_id, cursor.get(gc_cf), scan_limit) {
+ Ok(entries) => entries,
+ Err(error) => {
+ warn!(
+ partition_id,
+ cf = label,
+ error = %error,
+ "merge-CF GC scan failed; retrying next tick",
+ );
+ return;
+ }
+ };
+
+ if entries.is_empty() {
+ // Exhausted this partition's slice — wrap to the prefix start for the next tick.
+ cursor.set(gc_cf, None);
+ return;
+ }
+
+ counter!(MERGE_GC_KEYS_SCANNED_TOTAL, "cf" => label).increment(entries.len() as u64);
+
+ // Decide deletions before opening the batch so the closure borrows nothing fallible.
+ let mut undecodable = 0u64;
+ let mut victims: Vec<Vec<u8>> = Vec::new();
+ for (key_bytes, value_bytes) in &entries {
+ match expiry_decision(gc_cf, value_bytes, cutoff_ms) {
+ ExpiryDecision::Keep => {}
+ ExpiryDecision::Expired => victims.push(key_bytes.clone()),
+ ExpiryDecision::Undecodable => {
+ undecodable += 1;
+ victims.push(key_bytes.clone());
+ }
+ }
+ }
+
+ if !victims.is_empty() {
+ let result = store.write_batch(|batch| {
+ for key_bytes in &victims {
+ stage_delete(batch, gc_cf, key_bytes, partition_id, label);
+ }
+ });
+ match result {
+ Ok(()) => {
+ counter!(MERGE_GC_KEYS_DELETED_TOTAL, "cf" => label)
+ .increment(victims.len() as u64);
+ if undecodable > 0 {
+ counter!(MERGE_GC_UNDECODABLE_TOTAL, "cf" => label).increment(undecodable);
+ }
+ }
+ Err(error) => {
+ // The delete batch failed; leave the cursor unadvanced so the same keys are
+ // re-evaluated next tick. Nothing was counted as deleted.
+ warn!(
+ partition_id,
+ cf = label,
+ error = %error,
+ "merge-CF GC delete batch failed; leaving the keys for the next tick",
+ );
+ return;
+ }
+ }
+ }
+
+ // Full page → more may remain, resume after the last key; short page → slice exhausted, wrap to
+ // the start. The cursor is the last *scanned* key (survivors included), so a long-lived entry
+ // never wedges the cursor on itself.
+ if entries.len() == scan_limit {
+ let last_key = entries
+ .last()
+ .expect("non-empty by the guard above")
+ .0
+ .clone();
+ cursor.set(gc_cf, Some(last_key));
+ } else {
+ cursor.set(gc_cf, None);
+ }
+}
+
+/// Whether one entry's value timestamp is older than `cutoff_ms`.
+enum ExpiryDecision {
+ Keep,
+ Expired,
+ /// Value timestamp could not be decoded → delete (it can never age out otherwise).
+ Undecodable,
+}
+
+fn expiry_decision(gc_cf: GcCf, value_bytes: &[u8], cutoff_ms: i64) -> ExpiryDecision {
+ let timestamp = match gc_cf {
+ GcCf::DrainsApplied => DrainStamp::decode(value_bytes).map(|stamp| stamp.drained_at_ms),
+ GcCf::Applied => ApplyStamp::decode(value_bytes).map(|stamp| stamp.applied_at_ms),
+ GcCf::Tombstones => Tombstone::decode(value_bytes).map(|tombstone| tombstone.merged_at_ms),
+ };
+ match timestamp {
+ Ok(ts) if ts < cutoff_ms => ExpiryDecision::Expired,
+ Ok(_) => ExpiryDecision::Keep,
+ Err(_) => ExpiryDecision::Undecodable,
+ }
+}
+
+/// Decode the raw key into its typed form and stage the matching CF delete. Unlike an undecodable
+/// *value*, an undecodable *key* is left in place (there is no delete-by-raw-bytes path, and an
+/// unparseable key signals store corruption, not routine expiry) and only warned.
+fn stage_delete(
+ batch: &mut BatchBuilder<'_>,
+ gc_cf: GcCf,
+ key_bytes: &[u8],
+ partition_id: u16,
+ label: &str,
+) {
+ let decoded = match gc_cf {
+ GcCf::DrainsApplied => MergeDrainKey::decode(key_bytes).map(|key| {
+ batch.delete_merge_drain_applied(&key);
+ }),
+ GcCf::Applied => MergeAppliedKey::decode(key_bytes).map(|key| {
+ batch.delete_merge_applied(&key);
+ }),
+ GcCf::Tombstones => TombstoneKey::decode(key_bytes).map(|key| {
+ batch.delete_tombstone(&key);
+ }),
+ };
+ if decoded.is_err() {
+ warn!(
+ partition_id,
+ cf = label,
+ "merge-CF GC could not decode an expired key; leaving it in place",
+ );
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use crate::store::keys::{MergeAppliedKey, MergeDrainKey, PendingTransferKey, TombstoneKey};
+ use crate::store::StoreConfig;
+
+ const PARTITION: u16 = 5;
+ const TEAM: u64 = 7;
+ const MARKER_CUTOFF: i64 = 1_000;
+ const TOMBSTONE_CUTOFF: i64 = 500;
+ const NO_CAP: usize = 10_000;
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ fn drain_key(person: u128, offset: i64) -> MergeDrainKey {
+ MergeDrainKey {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ old_person: Uuid::from_u128(person),
+ merge_msg_partition: PARTITION as i32,
+ merge_msg_offset: offset,
+ }
+ }
+
+ fn applied_key(person: u128, offset: i64) -> MergeAppliedKey {
+ MergeAppliedKey {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ new_person: Uuid::from_u128(person),
+ source_partition: PARTITION as i32,
+ source_offset: offset,
+ }
+ }
+
+ fn tombstone_key(person: u128) -> TombstoneKey {
+ TombstoneKey {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ person: Uuid::from_u128(person),
+ }
+ }
+
+ fn put_drain(store: &CohortStore, key: &MergeDrainKey, drained_at_ms: i64) {
+ let value = DrainStamp { drained_at_ms }.encode();
+ store
+ .write_batch(|batch| batch.put_merge_drain_applied(key, &value))
+ .unwrap();
+ }
+
+ fn put_applied(store: &CohortStore, key: &MergeAppliedKey, applied_at_ms: i64) {
+ let value = ApplyStamp { applied_at_ms }.encode();
+ store
+ .write_batch(|batch| batch.put_merge_applied(key, &value))
+ .unwrap();
+ }
+
+ fn put_tombstone(store: &CohortStore, key: &TombstoneKey, merged_at_ms: i64) {
+ let value = Tombstone {
+ new_person: Uuid::from_u128(0xBEEF),
+ merged_at_ms,
+ }
+ .encode();
+ store
+ .write_batch(|batch| batch.put_tombstone(key, &value))
+ .unwrap();
+ }
+
+ fn run_gc(store: &CohortStore, cursor: &mut MergeGcCursor, cap: usize) {
+ handle_merge_gc(
+ PARTITION,
+ store,
+ cursor,
+ MARKER_CUTOFF,
+ TOMBSTONE_CUTOFF,
+ cap,
+ );
+ }
+
+ #[test]
+ fn expired_markers_and_tombstones_are_deleted_and_fresh_ones_kept() {
+ let (_dir, store) = temp_store();
+
+ // Drain markers: one expired (drained_at < marker cutoff), one fresh.
+ let expired_drain = drain_key(1, 10);
+ let fresh_drain = drain_key(2, 11);
+ put_drain(&store, &expired_drain, MARKER_CUTOFF - 1);
+ put_drain(&store, &fresh_drain, MARKER_CUTOFF + 1);
+
+ // Apply markers: one expired, one fresh.
+ let expired_apply = applied_key(3, 12);
+ let fresh_apply = applied_key(4, 13);
+ put_applied(&store, &expired_apply, MARKER_CUTOFF - 1);
+ put_applied(&store, &fresh_apply, MARKER_CUTOFF + 1);
+
+ // Tombstones: one expired (merged_at < tombstone cutoff), one fresh.
+ let expired_tomb = tombstone_key(5);
+ let fresh_tomb = tombstone_key(6);
+ put_tombstone(&store, &expired_tomb, TOMBSTONE_CUTOFF - 1);
+ put_tombstone(&store, &fresh_tomb, TOMBSTONE_CUTOFF + 1);
+
+ let mut cursor = MergeGcCursor::default();
+ run_gc(&store, &mut cursor, NO_CAP);
+
+ assert!(store
+ .get_merge_drain_applied(&expired_drain)
+ .unwrap()
+ .is_none());
+ assert!(store
+ .get_merge_drain_applied(&fresh_drain)
+ .unwrap()
+ .is_some());
+ assert!(store.get_merge_applied(&expired_apply).unwrap().is_none());
+ assert!(store.get_merge_applied(&fresh_apply).unwrap().is_some());
+ assert!(store.get_tombstone(&expired_tomb).unwrap().is_none());
+ assert!(store.get_tombstone(&fresh_tomb).unwrap().is_some());
+ }
+
+ #[test]
+ fn marker_and_tombstone_cutoffs_are_independent() {
+ let (_dir, store) = temp_store();
+
+ // A drain marker between the two cutoffs (TOMBSTONE_CUTOFF < ts < MARKER_CUTOFF): expired by
+ // the marker cutoff. A tombstone at the same timestamp is fresh by the tombstone cutoff.
+ let ts = (MARKER_CUTOFF + TOMBSTONE_CUTOFF) / 2;
+ assert!(ts < MARKER_CUTOFF && ts > TOMBSTONE_CUTOFF);
+
+ let marker = drain_key(1, 10);
+ let tomb = tombstone_key(2);
+ put_drain(&store, &marker, ts);
+ put_tombstone(&store, &tomb, ts);
+
+ let mut cursor = MergeGcCursor::default();
+ run_gc(&store, &mut cursor, NO_CAP);
+
+ assert!(
+ store.get_merge_drain_applied(&marker).unwrap().is_none(),
+ "marker expired by the marker cutoff",
+ );
+ assert!(
+ store.get_tombstone(&tomb).unwrap().is_some(),
+ "same-timestamp tombstone is fresh by the longer tombstone cutoff",
+ );
+ }
+
+ #[test]
+ fn scan_cap_is_respected_and_the_remainder_survives_to_the_next_tick() {
+ let (_dir, store) = temp_store();
+ // Six expired tombstones; cap of 2 deletes only the first two per tick.
+ let keys: Vec<TombstoneKey> = (1..=6u128).map(tombstone_key).collect();
+ for key in &keys {
+ put_tombstone(&store, key, TOMBSTONE_CUTOFF - 1);
+ }
+
+ let mut cursor = MergeGcCursor::default();
+
+ run_gc(&store, &mut cursor, 2);
+ let surviving = keys
+ .iter()
+ .filter(|k| store.get_tombstone(k).unwrap().is_some())
+ .count();
+ assert_eq!(surviving, 4, "tick 1 deleted exactly the cap of 2");
+
+ run_gc(&store, &mut cursor, 2);
+ let surviving = keys
+ .iter()
+ .filter(|k| store.get_tombstone(k).unwrap().is_some())
+ .count();
+ assert_eq!(surviving, 2, "tick 2 deleted the next 2");
+
+ // Tick 3 drains the last 2 (a short page → exhausted, wraps).
+ run_gc(&store, &mut cursor, 2);
+ assert!(
+ keys.iter()
+ .all(|k| store.get_tombstone(k).unwrap().is_none()),
+ "all expired tombstones gone after three capped ticks",
+ );
+ }
+
+ #[test]
+ fn cursor_resumes_mid_prefix_and_wraps_on_exhaustion() {
+ let (_dir, store) = temp_store();
+ // Three FRESH tombstones (none expire), so the cap-bounded scan must advance past them via
+ // the cursor rather than re-scanning the same survivors forever.
+ let keys: Vec<TombstoneKey> = (1..=3u128).map(tombstone_key).collect();
+ for key in &keys {
+ put_tombstone(&store, key, TOMBSTONE_CUTOFF + 1);
+ }
+
+ let mut cursor = MergeGcCursor::default();
+
+ // Cap 1: tick 1 scans key 1 (full page → cursor set past key 1).
+ run_gc(&store, &mut cursor, 1);
+ assert!(
+ cursor.tombstones.is_some(),
+ "a full page advances the cursor mid-prefix",
+ );
+ let after_tick1 = cursor.tombstones.clone();
+
+ // Tick 2 must resume past key 1 (cursor moves), not restart.
+ run_gc(&store, &mut cursor, 1);
+ assert_ne!(cursor.tombstones, after_tick1, "cursor advanced to key 2");
+
+ // Tick 3 scans key 3 (still a full page of 1).
+ run_gc(&store, &mut cursor, 1);
+ // Tick 4 finds nothing past key 3 → short (empty) page → wraps to the start.
+ run_gc(&store, &mut cursor, 1);
+ assert!(
+ cursor.tombstones.is_none(),
+ "exhausting the slice wraps the cursor to the prefix start",
+ );
+
+ // All three survived (fresh) throughout.
+ assert!(keys
+ .iter()
+ .all(|k| store.get_tombstone(k).unwrap().is_some()));
+ }
+
+ #[test]
+ fn undecodable_value_is_deleted() {
+ let (_dir, store) = temp_store();
+ let key = tombstone_key(1);
+ // Stage a tombstone slot with a garbage value the decoder rejects.
+ store
+ .write_batch(|batch| batch.put_tombstone(&key, b"not-a-tombstone"))
+ .unwrap();
+
+ let mut cursor = MergeGcCursor::default();
+ run_gc(&store, &mut cursor, NO_CAP);
+
+ assert!(
+ store.get_tombstone(&key).unwrap().is_none(),
+ "an undecodable value is deleted (it can never age out)",
+ );
+ }
+
+ #[test]
+ fn pending_transfers_are_untouched_by_a_gc_tick() {
+ let (_dir, store) = temp_store();
+ let pending_key = PendingTransferKey {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ old_person: Uuid::from_u128(1),
+ };
+ store
+ .write_batch(|batch| batch.put_pending_transfer(&pending_key, b"outbox-entry"))
+ .unwrap();
+ // Also stage an expired tombstone so the tick does real work.
+ let tomb = tombstone_key(2);
+ put_tombstone(&store, &tomb, TOMBSTONE_CUTOFF - 1);
+
+ let mut cursor = MergeGcCursor::default();
+ run_gc(&store, &mut cursor, NO_CAP);
+
+ assert!(
+ store.get_pending_transfer(&pending_key).unwrap().is_some(),
+ "the redrive outbox is never GC'd",
+ );
+ assert!(
+ store.get_tombstone(&tomb).unwrap().is_none(),
+ "the GC still did its real work",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/merge_path.rs b/rust/cohort-stream-processor/src/workers/merge_path.rs
new file mode 100644
index 000000000000..bf322f13834f
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/merge_path.rs
@@ -0,0 +1,1041 @@
+//! Merge-protocol worker paths: the produce/track I/O around the drain/apply handlers in
+//! [`crate::merge`].
+//!
+//! [`handle_merge`] drains a `PersonMergeEvent` on P_old's worker and owns the transfer produce;
+//! [`handle_apply`] applies a `MergeStateTransfer` on P_new's worker. Both produce their own
+//! membership output and mark their own [`OffsetTracker`].
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use chrono_tz::UTC;
+use metrics::{counter, gauge, histogram};
+use tracing::{debug, warn};
+
+use crate::filters::manager::CatalogHandle;
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::{TeamFiltersBuilder, TeamId};
+use crate::merge::apply_handler::{handle_transfer, ApplyOutcome};
+use crate::merge::drain_handler::{handle_merge_event, DrainOutcome};
+use crate::merge::transfer::{MergeStateTransfer, PendingTransfer, PersonMergeEvent};
+use crate::observability::metrics::{
+ COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, MERGE_APPLY_DURATION_SECONDS,
+ MERGE_DRAIN_DURATION_SECONDS, MERGE_HELD_OFFSET_GAUGE, MERGE_OUTBOX_CLEAR_FAILURE_TOTAL,
+ MERGE_PENDING_TRANSFERS_GAUGE, MERGE_TRANSFERS_SKIPPED_EMPTY_TOTAL,
+ MERGE_TRANSFER_FORWARDS_TOTAL, MERGE_TRANSFER_PRODUCE_FAILURE_TOTAL, STAGE1_TRANSITIONS,
+};
+use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};
+use crate::partitions::partitioner::COHORT_PARTITION_COUNT;
+use crate::producer::{
+ map_transition, CaptureCascadeSink, CaptureStreamEventSink, CaptureTransferSink, CascadeSink,
+ CohortMembershipChange, MembershipSink, StreamEventSink, TransferSink,
+};
+use crate::stage1::key::Stage1Key;
+use crate::stage1::transition::LeafTransition;
+use crate::store::{CohortStore, PendingTransferKey};
+use crate::sweep::EvictionQueue;
+use crate::workers::stage2_path::compose_stage2;
+use crate::workers::worker::{
+ first_cascades, produce_cascades, produce_membership, transition_metric_label,
+};
+
+/// Inline bounded backoff for the transfer produce.
+///
+/// Worst-case worker hold = `(max_retries + 1)` produce attempts, each fast-failing at the transfer
+/// sink's `message.timeout.ms`, plus the sum of the backoff sleeps. With the defaults — 6 attempts ×
+/// the 2 s transfer timeout ([`crate::config::Config::merge_transfer_message_timeout_ms`]) + ≈15.5 s
+/// of backoff ≈ **27.5 s** — that fits the 30 s graceful-shutdown window (the binding constraint
+/// here, tighter than the 60 s liveness deadline), and only because the transfer sink uses its own
+/// short timeout.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TransferRetryPolicy {
+ /// Retries after the initial attempt (total attempts = `max_retries + 1`).
+ pub max_retries: u32,
+ pub base: Duration,
+ pub cap: Duration,
+}
+
+impl Default for TransferRetryPolicy {
+ fn default() -> Self {
+ Self {
+ max_retries: 5,
+ base: Duration::from_millis(500),
+ cap: Duration::from_secs(8),
+ }
+ }
+}
+
+impl TransferRetryPolicy {
+ /// The pause before 1-based retry `attempt`: `base * 2^(attempt-1)`, capped at `cap`.
+ fn backoff(&self, attempt: u32) -> Duration {
+ self.base
+ .saturating_mul(2u32.saturating_pow(attempt.saturating_sub(1)))
+ .min(self.cap)
+ }
+}
+
+/// Default merge-CF GC per-tick, per-CF scan cap when the deps are built without explicit config
+/// (tests). Mirrors `Config::merge_gc_scan_limit`'s default.
+pub const DEFAULT_MERGE_GC_SCAN_LIMIT: usize = 10_000;
+
+/// Cascade depth/fan-out caps and the master gate. With `enabled` false the cascade transport is
+/// inert (the producer builds nothing, the consumer drains without re-evaluating).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CascadeConfig {
+ pub enabled: bool,
+ /// An incoming cascade at `depth >= this` drops its outgoing hop.
+ pub depth_cap: u8,
+ /// Max referrer re-evaluations per upstream flip; the remainder self-heals.
+ pub fanout_cap: usize,
+}
+
+impl Default for CascadeConfig {
+ fn default() -> Self {
+ Self {
+ enabled: false,
+ depth_cap: 8,
+ fanout_cap: 1000,
+ }
+ }
+}
+
+pub struct MergeWorkerDeps {
+ pub transfer_sink: Arc<dyn TransferSink>,
+ pub stream_event_sink: Arc<dyn StreamEventSink>,
+ pub merge_tracker: Arc<OffsetTracker>,
+ pub transfer_tracker: Arc<OffsetTracker>,
+ pub retry: TransferRetryPolicy,
+ /// Max keys scanned (and at most deleted) per merge CF, per partition, per GC tick. Reused as the
+ /// `cf_stage2` orphan-GC page cap.
+ pub gc_scan_limit: usize,
+ /// Whether the `cf_stage2` orphan GC pass runs on each merge-GC tick (kill-switch, default on).
+ pub stage2_orphan_gc_enabled: bool,
+ /// Sink for the internal `cohort_cascade_events` topic (a no-op when the gate is off).
+ pub cascade_sink: Arc<dyn CascadeSink>,
+ /// Isolated from the merge/transfer trackers so cascade-path lag is observable separately.
+ pub cascade_tracker: Arc<OffsetTracker>,
+ pub cascade: CascadeConfig,
+ /// Partition count the merge math routes against. Production 64; test lanes lower it. Threaded
+ /// from [`crate::config::Config::cohort_partition_count`] so a re-partitioned lane cannot
+ /// misroute against a hardcoded literal.
+ pub partition_count: u32,
+}
+
+impl MergeWorkerDeps {
+ pub fn capture() -> Arc<Self> {
+ Arc::new(Self {
+ transfer_sink: Arc::new(CaptureTransferSink::new()),
+ stream_event_sink: Arc::new(CaptureStreamEventSink::new()),
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink: Arc::new(CaptureCascadeSink::new()),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: CascadeConfig::default(),
+ partition_count: COHORT_PARTITION_COUNT,
+ })
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn handle_merge(
+ partition_id: u16,
+ store: &CohortStore,
+ catalog: &CatalogHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ queue: &mut EvictionQueue<Stage1Key>,
+ last_updated: &str,
+ event: &PersonMergeEvent,
+ offset: i64,
+) {
+ let msg_coords = (partition_id as i32, offset);
+
+ // Drain against empty filters when the team is absent to avoid wedging.
+ let snapshot = catalog.load();
+ let fallback: TeamFilters;
+ let filters: &TeamFilters = match snapshot.team(TeamId(event.team_id)) {
+ Some(team) => team,
+ None => {
+ fallback = empty_team_filters();
+ &fallback
+ }
+ };
+
+ let started = Instant::now();
+ let outcome = handle_merge_event(
+ partition_id,
+ store,
+ filters,
+ event,
+ msg_coords,
+ queue,
+ merge.partition_count,
+ );
+ histogram!(MERGE_DRAIN_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
+
+ let pending_key = PendingTransferKey {
+ partition_id,
+ team_id: event.team_id as u64,
+ old_person: event.old_person_uuid,
+ };
+ match outcome {
+ Ok(DrainOutcome::FastPath { transitions }) => {
+ produce_merge_transitions(
+ partition_id,
+ store,
+ sink,
+ merge,
+ filters,
+ &transitions,
+ event.merged_at_ms,
+ last_updated,
+ offset,
+ )
+ .await;
+ mark_processed(&merge.merge_tracker, partition_id, offset);
+ }
+ Ok(DrainOutcome::Drained { transfer }) => {
+ if transfer.leaves.is_empty() {
+ counter!(MERGE_TRANSFERS_SKIPPED_EMPTY_TOTAL).increment(1);
+ mark_processed(&merge.merge_tracker, partition_id, offset);
+ return;
+ }
+ produce_and_settle(partition_id, store, merge, &transfer, &pending_key, offset).await;
+ }
+ Ok(DrainOutcome::AlreadyDrained) => match store.get_pending_transfer(&pending_key) {
+ Ok(None) => mark_processed(&merge.merge_tracker, partition_id, offset),
+ Ok(Some(bytes)) => match PendingTransfer::decode(&bytes) {
+ Ok(pending) => {
+ produce_and_settle(
+ partition_id,
+ store,
+ merge,
+ &pending.transfer,
+ &pending_key,
+ offset,
+ )
+ .await;
+ }
+ Err(error) => {
+ warn!(
+ partition_id,
+ team_id = event.team_id,
+ old_person = %event.old_person_uuid,
+ error = %error,
+ "pending transfer failed to decode; committing past it (entry left for the redrive to surface)",
+ );
+ mark_processed(&merge.merge_tracker, partition_id, offset);
+ }
+ },
+ Err(error) => {
+ // Category A: the outbox read itself failed, so we cannot re-produce the staged
+ // transfer this pass and have no other handle on it — a sticky hold redelivers the
+ // merge so a later pass (or the next tenure) can resolve it.
+ warn!(
+ partition_id,
+ team_id = event.team_id,
+ error = %error,
+ "pending transfer read failed; holding the merge offset for redelivery",
+ );
+ hold(&merge.merge_tracker, partition_id, offset);
+ }
+ },
+ Ok(DrainOutcome::Skipped(_)) => {
+ mark_processed(&merge.merge_tracker, partition_id, offset);
+ }
+ Err(error) => {
+ // Category A: the drain's atomic `write_batch` failed, so it left no
+ // `cf_merge_drains_applied` marker and produced no transfer — nothing recovers this but a
+ // replay of the merge message. A sticky hold redelivers it; advancing past it would drop
+ // the merge silently.
+ warn!(
+ partition_id,
+ team_id = event.team_id,
+ old_person = %event.old_person_uuid,
+ error = %error,
+ "merge drain store error; holding the merge offset for redelivery",
+ );
+ hold(&merge.merge_tracker, partition_id, offset);
+ }
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+pub(crate) async fn handle_apply(
+ partition_id: u16,
+ store: &CohortStore,
+ catalog: &CatalogHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ queue: &mut EvictionQueue<Stage1Key>,
+ last_updated: &str,
+ transfer: &MergeStateTransfer,
+ offset: i64,
+) {
+ let transfer_coords = (partition_id as i32, offset);
+
+ let snapshot = catalog.load();
+ let fallback: TeamFilters;
+ let filters: &TeamFilters = match snapshot.team(TeamId(transfer.team_id)) {
+ Some(team) => team,
+ None => {
+ fallback = empty_team_filters();
+ &fallback
+ }
+ };
+
+ let started = Instant::now();
+ let outcome = handle_transfer(
+ partition_id,
+ store,
+ filters,
+ transfer,
+ transfer_coords,
+ queue,
+ merge.partition_count,
+ );
+ histogram!(MERGE_APPLY_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
+
+ match outcome {
+ Ok(ApplyOutcome::Applied { transitions }) => {
+ produce_merge_transitions(
+ partition_id,
+ store,
+ sink,
+ merge,
+ filters,
+ &transitions,
+ transfer.merged_at_ms,
+ last_updated,
+ offset,
+ )
+ .await;
+ mark_processed(&merge.transfer_tracker, partition_id, offset);
+ }
+ Ok(ApplyOutcome::AlreadyApplied) => {
+ mark_processed(&merge.transfer_tracker, partition_id, offset);
+ }
+ Ok(ApplyOutcome::Forward {
+ transfer: forwarded,
+ }) => {
+ forward_transfer(partition_id, merge, &forwarded, offset).await;
+ }
+ Ok(ApplyOutcome::HopCapped) => {
+ // No state and no marker were written; mark so a corrupt tombstone cycle does not wedge
+ // the partition (the counter already fired in the handler).
+ mark_processed(&merge.transfer_tracker, partition_id, offset);
+ }
+ Err(error) => {
+ // Category A: the atomic apply `write_batch` failed, so no `cf_merge_applied` marker was
+ // written and the Kafka transfer is the last copy of P_old's state (drain already deleted
+ // its leaves, the outbox slot was cleared on the produce ack). A sticky hold replays the
+ // transfer cleanly; advancing past it would lose the state for good.
+ warn!(
+ partition_id,
+ team_id = transfer.team_id,
+ new_person = %transfer.new_person_uuid,
+ error = %error,
+ "transfer apply store error; holding the transfer offset for redelivery",
+ );
+ hold(&merge.transfer_tracker, partition_id, offset);
+ }
+ }
+}
+
+/// Forward a re-targeted transfer to the survivor's partition (the raced chained-merge case).
+///
+/// A **single** produce attempt on the transfer sink (not the inline retry budget — the apply path
+/// must not hold the worker): a failed produce holds the transfer offset (no mark) so redelivery
+/// re-resolves and re-produces. The forward writes no state, so the hold is self-healing. The
+/// transfer offset is marked only after the ack, and the forward is counted post-ack (`re_keyed`).
+async fn forward_transfer(
+ partition_id: u16,
+ merge: &MergeWorkerDeps,
+ forwarded: &MergeStateTransfer,
+ offset: i64,
+) {
+ let acks = merge.transfer_sink.produce(vec![forwarded.clone()]).await;
+ if !acks.iter().all(Result::is_ok) {
+ // Category B: the forward wrote no state and no outbox entry, so the failed produce leaves
+ // nothing to redrive — a sticky hold redelivers the transfer, which re-resolves and re-forwards
+ // (the survivor's marker dedups any duplicate).
+ warn!(
+ partition_id,
+ team_id = forwarded.team_id,
+ old_person = %forwarded.old_person_uuid,
+ target = %forwarded.new_person_uuid,
+ forward_hops = forwarded.forward_hops,
+ "transfer forward produce failed; holding the transfer offset for redelivery",
+ );
+ hold(&merge.transfer_tracker, partition_id, offset);
+ return;
+ }
+ counter!(MERGE_TRANSFER_FORWARDS_TOTAL, "path" => "re_keyed").increment(1);
+ mark_processed(&merge.transfer_tracker, partition_id, offset);
+}
+
+const REDRIVE_MAX_ATTEMPTS_PER_TICK: usize = 8;
+
+/// Cap on the pending-transfer scan: a small multiple of the per-tick attempt cap, so the redrive has
+/// the next few ticks' worth of work staged without copying the whole outbox each tick.
+const SCAN_PENDING_TRANSFERS_LIMIT: usize = REDRIVE_MAX_ATTEMPTS_PER_TICK * 8;
+
+pub(crate) async fn handle_redrive(
+ partition_id: u16,
+ store: &CohortStore,
+ merge: &MergeWorkerDeps,
+) {
+ let entries =
+ match store.scan_pending_transfers(partition_id, None, SCAN_PENDING_TRANSFERS_LIMIT) {
+ Ok(entries) => entries,
+ Err(error) => {
+ warn!(
+ partition_id,
+ error = %error,
+ "pending-transfer redrive scan failed; retrying next tick",
+ );
+ return;
+ }
+ };
+ // Saturates at the scan limit, so this reflects `min(backlog, SCAN_PENDING_TRANSFERS_LIMIT)` — it
+ // still distinguishes an empty outbox from a backed-up one, just not the exact backlog depth.
+ gauge!(MERGE_PENDING_TRANSFERS_GAUGE, "partition" => partition_id.to_string())
+ .set(entries.len() as f64);
+
+ let mut attempted = 0usize;
+ for (key, bytes) in entries {
+ if attempted == REDRIVE_MAX_ATTEMPTS_PER_TICK {
+ debug!(
+ partition_id,
+ "redrive tick reached its produce-attempt cap; remaining entries wait for the next tick",
+ );
+ break;
+ }
+ let pending = match PendingTransfer::decode(&bytes) {
+ Ok(pending) => pending,
+ Err(error) => {
+ warn!(
+ partition_id,
+ team_id = key.team_id,
+ old_person = %key.old_person,
+ error = %error,
+ "pending transfer failed to decode during redrive; leaving the entry in place",
+ );
+ continue;
+ }
+ };
+ let team_id = pending.transfer.team_id;
+ let old_person = pending.transfer.old_person_uuid;
+ attempted += 1;
+ let acks = merge.transfer_sink.produce(vec![pending.transfer]).await;
+ if !acks.iter().all(Result::is_ok) {
+ warn!(
+ partition_id,
+ team_id,
+ old_person = %old_person,
+ "redrive transfer produce failed; leaving the entry for the next tick",
+ );
+ continue;
+ }
+ if let Err(error) = store.clear_pending_transfer(&key) {
+ counter!(MERGE_OUTBOX_CLEAR_FAILURE_TOTAL).increment(1);
+ warn!(
+ partition_id,
+ team_id,
+ old_person = %old_person,
+ error = %error,
+ "outbox clear failed after an acked redrive produce; marking anyway",
+ );
+ }
+ debug_assert_eq!(pending.merge_msg_partition, partition_id as i32);
+ mark_processed(&merge.merge_tracker, partition_id, pending.merge_msg_offset);
+ }
+}
+
+/// Produce `transfer` with inline retry; on ack clear its outbox slot and mark the merge offset.
+async fn produce_and_settle(
+ partition_id: u16,
+ store: &CohortStore,
+ merge: &MergeWorkerDeps,
+ transfer: &MergeStateTransfer,
+ pending_key: &PendingTransferKey,
+ offset: i64,
+) {
+ if !produce_transfer_with_retry(&merge.transfer_sink, transfer, &merge.retry, partition_id)
+ .await
+ {
+ // Category C: deliberately **no** `hold` here. The transfer stays staged in
+ // `cf_pending_transfers` and the periodic redrive (`handle_redrive`) owns recovery — it
+ // re-produces and then `mark_processed`es `K + 1`. A sticky hold would pin `K` even after the
+ // redrive advances past it, wedging the partition on a message the outbox already handles.
+ counter!(MERGE_TRANSFER_PRODUCE_FAILURE_TOTAL).increment(1);
+ warn!(
+ partition_id,
+ team_id = transfer.team_id,
+ old_person = %transfer.old_person_uuid,
+ new_person = %transfer.new_person_uuid,
+ "transfer produce exhausted its retry budget; leaving the entry pending and skipping the offset mark",
+ );
+ return;
+ }
+ if let Err(error) = store.clear_pending_transfer(pending_key) {
+ counter!(MERGE_OUTBOX_CLEAR_FAILURE_TOTAL).increment(1);
+ warn!(
+ partition_id,
+ team_id = transfer.team_id,
+ old_person = %transfer.old_person_uuid,
+ error = %error,
+ "outbox clear failed after an acked transfer produce; committing anyway",
+ );
+ }
+ mark_processed(&merge.merge_tracker, partition_id, offset);
+}
+
+/// Produce one transfer, retrying inline with bounded backoff. Returns whether the produce was acked.
+async fn produce_transfer_with_retry(
+ sink: &Arc<dyn TransferSink>,
+ transfer: &MergeStateTransfer,
+ retry: &TransferRetryPolicy,
+ partition_id: u16,
+) -> bool {
+ for attempt in 0..=retry.max_retries {
+ if attempt > 0 {
+ tokio::time::sleep(retry.backoff(attempt)).await;
+ }
+ let acks = sink.produce(vec![transfer.clone()]).await;
+ if acks.iter().all(Result::is_ok) {
+ return true;
+ }
+ debug!(
+ partition_id,
+ attempt,
+ team_id = transfer.team_id,
+ old_person = %transfer.old_person_uuid,
+ "transfer produce attempt failed",
+ );
+ }
+ false
+}
+
+/// Fan transitions into membership output (single-leaf + Stage 2), then produce (at-most-once).
+/// `source_offset` seeds each flip's first cascade; both produces drop on failure.
+#[allow(clippy::too_many_arguments)]
+async fn produce_merge_transitions(
+ partition_id: u16,
+ store: &CohortStore,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ filters: &TeamFilters,
+ transitions: &[LeafTransition],
+ merged_at_ms: i64,
+ last_updated: &str,
+ source_offset: i64,
+) {
+ if transitions.is_empty() {
+ return;
+ }
+ let mut changes: Vec<CohortMembershipChange> = Vec::new();
+ for transition in transitions {
+ if let Some(kind) = transition_metric_label(filters, transition) {
+ counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);
+ }
+ changes.extend(map_transition(filters, transition, last_updated));
+ }
+ match compose_stage2(
+ partition_id,
+ store,
+ filters,
+ transitions,
+ merged_at_ms,
+ last_updated,
+ ) {
+ Ok(stage2_changes) => changes.extend(stage2_changes),
+ Err(error) => warn!(
+ partition_id,
+ error = %error,
+ "merge stage 2 composition failed; skipping (self-heals on the person's next event)",
+ ),
+ }
+ if changes.is_empty() {
+ return;
+ }
+
+ let cascades = first_cascades(merge, &changes, source_offset);
+ let errors = produce_membership(sink, changes).await;
+ if errors > 0 {
+ warn!(
+ partition_id,
+ errors,
+ "merge membership produce failed; dropping (state already committed, at-most-once)",
+ );
+ return;
+ }
+ let cascade_errors = produce_cascades(merge, cascades).await;
+ if cascade_errors > 0 {
+ warn!(
+ partition_id,
+ errors = cascade_errors,
+ "merge cascade produce failed; dropping (at-most-once). Recovery depends on each referrer being re-evaluated on its next event; the sweep does not re-evaluate cohort-ref shapes with no behavioral leaf",
+ );
+ }
+}
+
+fn mark_processed(tracker: &OffsetTracker, partition_id: u16, offset: i64) {
+ if let MarkOutcome::CappedAheadOfDispatch =
+ tracker.mark_processed(partition_id as i32, offset + 1)
+ {
+ counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);
+ warn!(
+ partition_id,
+ next_offset = offset + 1,
+ "offset mark exceeded the dispatch ceiling and was capped (F1 invariant violation)",
+ );
+ }
+}
+
+/// Pin the partition's commit floor at the failed message's **own** offset (no `+ 1`, unlike
+/// [`mark_processed`]) so Kafka redelivers it instead of a later success leapfrogging it. The hold is
+/// sticky for the worker's tenure; emit [`MERGE_HELD_OFFSET_GAUGE`] so the resulting commit-stall is
+/// never silent (alert on a sustained non-zero level).
+fn hold(tracker: &OffsetTracker, partition_id: u16, offset: i64) {
+ // Report the resulting floor (an earlier hold may pin a lower offset), not the raw `offset`, so
+ // the gauge matches the position Kafka will actually redeliver.
+ let floor = tracker.hold(partition_id as i32, offset);
+ gauge!(MERGE_HELD_OFFSET_GAUGE, "partition" => partition_id.to_string()).set(floor as f64);
+}
+
+/// Fallback for a team absent from the catalog: no cohorts, UTC timezone.
+fn empty_team_filters() -> TeamFilters {
+ TeamFiltersBuilder::default().freeze(UTC)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use envconfig::Envconfig;
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use crate::merge::transfer::TransferLeaf;
+ use crate::stage1::key::LeafStateKey;
+ use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
+ use crate::store::StoreConfig;
+
+ #[test]
+ fn default_retry_policy_budget() {
+ let policy = TransferRetryPolicy::default();
+ assert_eq!(policy.max_retries, 5);
+ let backoffs: Vec<Duration> = (1..=policy.max_retries)
+ .map(|a| policy.backoff(a))
+ .collect();
+ assert_eq!(
+ backoffs,
+ vec![
+ Duration::from_millis(500),
+ Duration::from_secs(1),
+ Duration::from_secs(2),
+ Duration::from_secs(4),
+ Duration::from_secs(8),
+ ],
+ );
+ let total: Duration = backoffs.iter().sum();
+ assert_eq!(total, Duration::from_millis(15_500), "≈15.5 s end to end");
+ }
+
+ /// The inline transfer-retry worst case — every produce attempt fast-failing at the dedicated
+ /// transfer timeout, plus all backoff sleeps — must stay inside the 30 s graceful-shutdown window
+ /// (the binding constraint, tighter than the 60 s liveness deadline). Sourced from the live config
+ /// default and the retry-policy default so a drift in *either* trips this test.
+ #[test]
+ fn inline_transfer_retry_worst_case_fits_the_graceful_shutdown_window() {
+ let config = crate::config::Config::init_from_hashmap(&std::collections::HashMap::new())
+ .expect("envconfig defaults load");
+ let policy = config.transfer_retry_policy();
+
+ // total attempts = initial + retries; each can block for the full transfer message timeout.
+ let attempts = policy.max_retries + 1;
+ let per_attempt =
+ Duration::from_millis(u64::from(config.merge_transfer_message_timeout_ms));
+ let produce_block = per_attempt * attempts;
+
+ let backoff: Duration = (1..=policy.max_retries).map(|a| policy.backoff(a)).sum();
+ let worst_case = produce_block + backoff;
+
+ // 6 × 2 s + 15.5 s = 27.5 s with the current defaults.
+ assert_eq!(worst_case, Duration::from_millis(27_500));
+
+ const GRACEFUL_SHUTDOWN_WINDOW: Duration = Duration::from_secs(30);
+ assert!(
+ worst_case <= GRACEFUL_SHUTDOWN_WINDOW,
+ "inline transfer retry worst case {worst_case:?} exceeds the {GRACEFUL_SHUTDOWN_WINDOW:?} graceful-shutdown window",
+ );
+ }
+
+ #[test]
+ fn backoff_is_capped_and_saturating() {
+ let policy = TransferRetryPolicy {
+ max_retries: 64,
+ base: Duration::from_secs(1),
+ cap: Duration::from_secs(8),
+ };
+ assert_eq!(policy.backoff(4), Duration::from_secs(8));
+ assert_eq!(policy.backoff(64), Duration::from_secs(8));
+ assert_eq!(policy.backoff(0), Duration::from_secs(1));
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn produce_with_retry_succeeds_after_transient_failures_without_wall_clock_sleep() {
+ let wall = std::time::Instant::now();
+ let capture = CaptureTransferSink::failing_first(2);
+ let sink: Arc<dyn TransferSink> = Arc::new(capture.clone());
+ let transfer = MergeStateTransfer {
+ team_id: 7,
+ old_person_uuid: uuid::Uuid::from_u128(1),
+ new_person_uuid: uuid::Uuid::from_u128(2),
+ merged_at_ms: 1,
+ source_partition: 0,
+ source_offset: 0,
+ leaves: vec![],
+ forward_hops: 0,
+ };
+
+ let acked =
+ produce_transfer_with_retry(&sink, &transfer, &TransferRetryPolicy::default(), 0).await;
+
+ assert!(acked, "third attempt succeeds within the budget");
+ assert_eq!(capture.transfers(), vec![transfer]);
+ assert!(
+ wall.elapsed() < Duration::from_secs(2),
+ "backoff ran on the paused clock, not the wall clock",
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn produce_with_retry_exhausts_after_max_retries() {
+ let capture = CaptureTransferSink::failing_always();
+ let sink: Arc<dyn TransferSink> = Arc::new(capture.clone());
+ let transfer = MergeStateTransfer {
+ team_id: 7,
+ old_person_uuid: uuid::Uuid::from_u128(1),
+ new_person_uuid: uuid::Uuid::from_u128(2),
+ merged_at_ms: 1,
+ source_partition: 0,
+ source_offset: 0,
+ leaves: vec![],
+ forward_hops: 0,
+ };
+
+ let acked =
+ produce_transfer_with_retry(&sink, &transfer, &TransferRetryPolicy::default(), 0).await;
+
+ assert!(!acked);
+ assert!(capture.transfers().is_empty());
+ }
+
+ const REDRIVE_PARTITION: u16 = 3;
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ fn capture_deps(transfer_sink: CaptureTransferSink) -> MergeWorkerDeps {
+ MergeWorkerDeps {
+ transfer_sink: Arc::new(transfer_sink),
+ stream_event_sink: Arc::new(CaptureStreamEventSink::new()),
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink: Arc::new(CaptureCascadeSink::new()),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: CascadeConfig::default(),
+ partition_count: COHORT_PARTITION_COUNT,
+ }
+ }
+
+ fn staged_pending(p_old: Uuid, merge_offset: i64) -> (PendingTransferKey, PendingTransfer) {
+ let transfer = MergeStateTransfer {
+ team_id: 7,
+ old_person_uuid: p_old,
+ new_person_uuid: Uuid::from_u128(0xBEEF),
+ merged_at_ms: 1,
+ source_partition: REDRIVE_PARTITION as i32,
+ source_offset: merge_offset,
+ leaves: vec![TransferLeaf::new(
+ LeafStateKey([0xAB; 16]),
+ StatefulRecord::new(
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: i64::MAX,
+ },
+ AppliedOffsets::default(),
+ ),
+ )],
+ forward_hops: 0,
+ };
+ let key = PendingTransferKey {
+ partition_id: REDRIVE_PARTITION,
+ team_id: 7,
+ old_person: p_old,
+ };
+ let pending = PendingTransfer {
+ transfer,
+ merge_msg_partition: REDRIVE_PARTITION as i32,
+ merge_msg_offset: merge_offset,
+ };
+ (key, pending)
+ }
+
+ fn stage(store: &CohortStore, key: &PendingTransferKey, bytes: &[u8]) {
+ store
+ .write_batch(|batch| batch.put_pending_transfer(key, bytes))
+ .unwrap();
+ }
+
+ #[tokio::test]
+ async fn redrive_re_produces_a_staged_entry_clears_it_and_marks_the_stored_coords() {
+ let (_dir, store) = temp_store();
+ let (key, pending) = staged_pending(Uuid::from_u128(1), 41);
+ stage(&store, &key, &pending.encode());
+
+ let sink = CaptureTransferSink::new();
+ let deps = capture_deps(sink.clone());
+ // The exhausted merge was dispatched this tenure, so its ceiling is already raised.
+ deps.merge_tracker
+ .mark_dispatched(REDRIVE_PARTITION as i32, 42);
+
+ handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+
+ assert_eq!(sink.transfers(), vec![pending.transfer]);
+ assert!(
+ store.get_pending_transfer(&key).unwrap().is_none(),
+ "the entry was cleared after the ack",
+ );
+ assert_eq!(
+ deps.merge_tracker
+ .committable_offsets()
+ .get(&(REDRIVE_PARTITION as i32)),
+ Some(&42),
+ "the stored merge-message coordinates were marked",
+ );
+ }
+
+ #[tokio::test]
+ async fn redrive_produce_failure_leaves_the_entry_and_the_offset_for_the_next_tick() {
+ let (_dir, store) = temp_store();
+ let (key, pending) = staged_pending(Uuid::from_u128(1), 41);
+ stage(&store, &key, &pending.encode());
+
+ let sink = CaptureTransferSink::failing_first(1);
+ let deps = capture_deps(sink.clone());
+ deps.merge_tracker
+ .mark_dispatched(REDRIVE_PARTITION as i32, 42);
+
+ handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ assert!(sink.transfers().is_empty());
+ assert!(store.get_pending_transfer(&key).unwrap().is_some());
+ assert!(
+ deps.merge_tracker.committable_offsets().is_empty(),
+ "a failed redrive marks nothing",
+ );
+
+ handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ assert_eq!(sink.transfers(), vec![pending.transfer]);
+ assert!(store.get_pending_transfer(&key).unwrap().is_none());
+ assert_eq!(
+ deps.merge_tracker
+ .committable_offsets()
+ .get(&(REDRIVE_PARTITION as i32)),
+ Some(&42),
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn redrive_makes_a_single_produce_attempt_per_tick_with_no_backoff() {
+ let (_dir, store) = temp_store();
+ let (key, pending) = staged_pending(Uuid::from_u128(1), 41);
+ stage(&store, &key, &pending.encode());
+ let deps = capture_deps(CaptureTransferSink::failing_always());
+ deps.merge_tracker
+ .mark_dispatched(REDRIVE_PARTITION as i32, 42);
+
+ let before = tokio::time::Instant::now();
+ handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+
+ assert_eq!(
+ tokio::time::Instant::now() - before,
+ Duration::ZERO,
+ "no backoff sleep on the paused clock — exactly one attempt per tick",
+ );
+ assert!(store.get_pending_transfer(&key).unwrap().is_some());
+ }
+
+ #[tokio::test]
+ async fn redrive_leaves_an_undecodable_entry_in_place_and_still_recovers_the_rest() {
+ let (_dir, store) = temp_store();
+ let corrupt_key = PendingTransferKey {
+ partition_id: REDRIVE_PARTITION,
+ team_id: 7,
+ old_person: Uuid::from_u128(1),
+ };
+ stage(&store, &corrupt_key, b"not-a-pending-transfer");
+ let (good_key, good) = staged_pending(Uuid::from_u128(2), 41);
+ stage(&store, &good_key, &good.encode());
+
+ let sink = CaptureTransferSink::new();
+ let deps = capture_deps(sink.clone());
+ deps.merge_tracker
+ .mark_dispatched(REDRIVE_PARTITION as i32, 42);
+
+ handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+
+ assert_eq!(
+ sink.transfers(),
+ vec![good.transfer],
+ "the good entry was recovered",
+ );
+ assert!(store.get_pending_transfer(&good_key).unwrap().is_none());
+ assert!(
+ store.get_pending_transfer(&corrupt_key).unwrap().is_some(),
+ "the corrupt entry stays for every later tick to surface",
+ );
+ }
+
+ #[tokio::test]
+ async fn redrive_attempts_at_most_the_cap_per_tick_and_the_remainder_survives() {
+ let (_dir, store) = temp_store();
+ let backlog = REDRIVE_MAX_ATTEMPTS_PER_TICK + 3;
+ let staged: Vec<_> = (0..backlog)
+ .map(|i| {
+ let (key, pending) = staged_pending(Uuid::from_u128(i as u128 + 1), 41 + i as i64);
+ stage(&store, &key, &pending.encode());
+ key
+ })
+ .collect();
+
+ let sink = CaptureTransferSink::new();
+ let deps = capture_deps(sink.clone());
+ deps.merge_tracker
+ .mark_dispatched(REDRIVE_PARTITION as i32, 41 + backlog as i64);
+
+ handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ assert_eq!(
+ sink.transfers().len(),
+ REDRIVE_MAX_ATTEMPTS_PER_TICK,
+ "tick 1 attempted exactly the cap",
+ );
+ for key in &staged[..REDRIVE_MAX_ATTEMPTS_PER_TICK] {
+ assert!(store.get_pending_transfer(key).unwrap().is_none());
+ }
+ for key in &staged[REDRIVE_MAX_ATTEMPTS_PER_TICK..] {
+ assert!(
+ store.get_pending_transfer(key).unwrap().is_some(),
+ "entries past the cap survive to the next tick",
+ );
+ }
+
+ handle_redrive(REDRIVE_PARTITION, &store, &deps).await;
+ assert_eq!(
+ sink.transfers().len(),
+ backlog,
+ "tick 2 drained the remainder",
+ );
+ for key in &staged {
+ assert!(store.get_pending_transfer(key).unwrap().is_none());
+ }
+ }
+
+ const FORWARD_PARTITION: u16 = 5;
+
+ fn forwarded_transfer() -> MergeStateTransfer {
+ MergeStateTransfer {
+ team_id: 7,
+ old_person_uuid: Uuid::from_u128(0xA),
+ new_person_uuid: Uuid::from_u128(0xC),
+ merged_at_ms: 1,
+ source_partition: 9,
+ source_offset: 100,
+ leaves: vec![],
+ forward_hops: 1,
+ }
+ }
+
+ #[tokio::test]
+ async fn forward_produce_failure_holds_the_transfer_offset_until_redelivery_succeeds() {
+ let forwarded = forwarded_transfer();
+
+ // First attempt: the sink fails → nothing produced, offset not marked. A separate fresh sink
+ // models the recovered attempt below.
+ let failing_sink = CaptureTransferSink::failing_always();
+ let failing = capture_deps(failing_sink.clone());
+ forward_transfer(FORWARD_PARTITION, &failing, &forwarded, 80).await;
+ assert!(
+ failing_sink.transfers().is_empty(),
+ "a failed forward produced nothing",
+ );
+ assert!(
+ failing.transfer_tracker.committable_offsets().is_empty(),
+ "a failed forward marks no offset",
+ );
+
+ // Redelivery against a working sink: produced once, offset marked once.
+ let working_sink = CaptureTransferSink::new();
+ let working = capture_deps(working_sink.clone());
+ working
+ .transfer_tracker
+ .mark_dispatched(FORWARD_PARTITION as i32, 81);
+ forward_transfer(FORWARD_PARTITION, &working, &forwarded, 80).await;
+ assert_eq!(
+ working_sink.transfers(),
+ vec![forwarded],
+ "the redelivery forwarded exactly once",
+ );
+ assert_eq!(
+ working
+ .transfer_tracker
+ .committable_offsets()
+ .get(&(FORWARD_PARTITION as i32)),
+ Some(&81),
+ "the transfer offset is marked only after the ack",
+ );
+ }
+
+ /// A store-error hold must be sticky: a later success on the same partition must not leapfrog
+ /// the held offset. `hold` pins `K` (the failed offset) and a subsequent `mark_processed` at
+ /// `K' > K` must leave committable at `K`, not advance it.
+ #[test]
+ fn an_apply_store_error_hold_is_not_leapfrogged_by_a_later_successful_transfer() {
+ const P: u16 = 6;
+ let deps = capture_deps(CaptureTransferSink::new());
+ // The partition processed transfers up to offset 40 this tenure, then saw 41 (fails) and 43.
+ deps.transfer_tracker.mark_dispatched(P as i32, 44);
+ mark_processed(&deps.transfer_tracker, P, 40);
+ assert_eq!(
+ deps.transfer_tracker.committable_offsets().get(&(P as i32)),
+ Some(&41),
+ "before the failure, committable is the next-offset 41",
+ );
+
+ // The apply store-error arm holds at the failed message's own offset K=41 (no +1).
+ hold(&deps.transfer_tracker, P, 41);
+
+ // A later transfer for the same partition applies cleanly and marks next-offset 44.
+ mark_processed(&deps.transfer_tracker, P, 43);
+ assert_eq!(
+ deps.transfer_tracker.committable_offsets().get(&(P as i32)),
+ Some(&41),
+ "the later success must NOT advance committable past the held offset 41",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rs
new file mode 100644
index 000000000000..59bf64ad3b0d
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/mod.rs
@@ -0,0 +1,19 @@
+//! Stage 1 per-partition workers: the I/O and channel layer over [`crate::stage1`].
+
+pub mod cascade_path;
+pub mod event_path;
+pub mod merge_gc;
+pub mod merge_path;
+pub mod stage2_gc;
+pub mod stage2_path;
+pub mod sweep_callback;
+pub mod worker;
+
+pub use event_path::{process_event, EventOutcome, SkipReason};
+pub use merge_gc::{handle_merge_gc, MergeGcCursor};
+pub use merge_path::{
+ CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
+};
+pub use stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};
+pub use stage2_path::compose_stage2;
+pub use worker::Stage1Worker;
diff --git a/rust/cohort-stream-processor/src/workers/stage2_gc.rs b/rust/cohort-stream-processor/src/workers/stage2_gc.rs
new file mode 100644
index 000000000000..1a0d9a38d8c9
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/stage2_gc.rs
@@ -0,0 +1,499 @@
+//! Worker-side `cf_stage2` orphan garbage collection.
+//!
+//! [`handle_stage2_orphan_gc`] reclaims `cf_stage2` rows whose cohort is no longer composable, on the
+//! same [`ShuffleMessage::MergeCfGc`](crate::partitions::shuffle_message::ShuffleMessage::MergeCfGc)
+//! tick as [`handle_merge_gc`](crate::workers::merge_gc::handle_merge_gc). Two paths strand such rows:
+//! an absent-team merge drain (the drain deletes via the catalog's composable cohorts, empty when the
+//! team is absent) and a cohort reclassified out of the composable set (`Stage2Composable` →
+//! `SingleLeaf`, deleted, or made non-realtime).
+//!
+//! The victim decision is **catalog absence, not a timestamp**: a `cf_stage2` value's
+//! `last_evaluated_at_ms` is the replay-stable source event time, so a time cutoff would evict a
+//! still-live dormant member.
+//!
+//! Two gates keep the pass from deleting live state on an untrustworthy snapshot — a successful
+//! *empty* refresh is indistinguishable from "every cohort vanished":
+//! 1. [`CatalogHandle::is_loaded`] — never GC before the first successful refresh.
+//! 2. non-empty catalog — skip the pass when `team_count() == 0`, so a transient empty load can't
+//! mass-delete. A team whose realtime cohorts are all gone then keeps its orphans until any
+//! composable cohort returns (or `delete_partition`/store retention reclaims them) — a space-only leak.
+
+use metrics::counter;
+use tracing::warn;
+
+use crate::filters::manager::{CatalogHandle, FilterCatalog};
+use crate::filters::{CohortId, TeamId};
+use crate::observability::metrics::{
+ STAGE2_ORPHAN_GC_KEYS_DELETED_TOTAL, STAGE2_ORPHAN_GC_KEYS_SCANNED_TOTAL,
+ STAGE2_ORPHAN_GC_SKIPPED_TOTAL, STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL,
+};
+use crate::store::{Cf, CohortStore, Stage2Key};
+
+/// Per-worker resume cursor: the raw last-key scanned in this partition's `cf_stage2` slice; `None`
+/// restarts at the prefix start. Loss on a rebalance is benign — a fresh tenure rescans and
+/// re-deleting an absent key is a no-op.
+#[derive(Default)]
+pub struct Stage2GcCursor(Option<Vec<u8>>);
+
+/// GC one partition's `cf_stage2` orphans for one tick: scan up to `scan_limit` rows, delete every
+/// row whose cohort is no longer composable in `catalog`, and advance the cursor (wrapping on
+/// exhaustion). A no-op before the first catalog load or against an empty catalog (the two safety gates).
+pub fn handle_stage2_orphan_gc(
+ partition_id: u16,
+ store: &CohortStore,
+ catalog: &CatalogHandle,
+ cursor: &mut Stage2GcCursor,
+ scan_limit: usize,
+) {
+ // Gate 1: never GC before the first successful refresh (fail closed).
+ if !catalog.is_loaded() {
+ counter!(STAGE2_ORPHAN_GC_SKIPPED_TOTAL, "reason" => "catalog_not_loaded").increment(1);
+ return;
+ }
+ let snapshot = catalog.load();
+ // Gate 2: an empty catalog is never a basis for deletion (a transient empty refresh must not
+ // mass-delete).
+ if snapshot.team_count() == 0 {
+ counter!(STAGE2_ORPHAN_GC_SKIPPED_TOTAL, "reason" => "empty_catalog").increment(1);
+ return;
+ }
+
+ let page = match store.scan_merge_cf(Cf::Stage2, partition_id, cursor.0.as_deref(), scan_limit)
+ {
+ Ok(page) => page,
+ Err(error) => {
+ warn!(
+ partition_id,
+ error = %error,
+ "cf_stage2 orphan GC scan failed; retrying next tick",
+ );
+ return;
+ }
+ };
+
+ if page.is_empty() {
+ // Slice exhausted — wrap the cursor to the prefix start.
+ cursor.0 = None;
+ return;
+ }
+
+ counter!(STAGE2_ORPHAN_GC_KEYS_SCANNED_TOTAL).increment(page.len() as u64);
+
+ // Decode and classify before opening the batch, since the batch closure is infallible.
+ let mut undecodable = 0u64;
+ let mut victims: Vec<Stage2Key> = Vec::new();
+ for (key_bytes, _value) in &page {
+ match Stage2Key::decode(key_bytes) {
+ Ok(key) => match is_orphan(&snapshot, &key) {
+ Some(true) => victims.push(key),
+ Some(false) => {}
+ // An id outside `i32` can't be classified — leave it in place (not corruption).
+ None => undecodable += 1,
+ },
+ Err(_) => {
+ // A key the decoder rejects signals corruption, not expiry: leave it and warn.
+ undecodable += 1;
+ warn!(
+ partition_id,
+ "cf_stage2 orphan GC could not decode a key; leaving it in place",
+ );
+ }
+ }
+ }
+
+ if !victims.is_empty() {
+ let result = store.write_batch(|batch| {
+ for key in &victims {
+ batch.delete_stage2(key);
+ }
+ });
+ match result {
+ Ok(()) => {
+ counter!(STAGE2_ORPHAN_GC_KEYS_DELETED_TOTAL).increment(victims.len() as u64);
+ }
+ Err(error) => {
+ // Return without advancing the cursor so the keys are retried next tick.
+ warn!(
+ partition_id,
+ error = %error,
+ "cf_stage2 orphan GC delete batch failed; leaving the keys for the next tick",
+ );
+ return;
+ }
+ }
+ }
+
+ if undecodable > 0 {
+ counter!(STAGE2_ORPHAN_GC_UNDECODABLE_KEYS_TOTAL).increment(undecodable);
+ }
+
+ // Full page → resume after the last key; short page → wrap. The cursor is the last *scanned* key
+ // (survivors included), so a mostly-live slice still advances over successive ticks.
+ cursor.0 = (page.len() == scan_limit)
+ .then(|| page.last().expect("non-empty by the guard above").0.clone());
+}
+
+/// Whether a `cf_stage2` row is an orphan: its cohort is not a composable cohort in `snapshot`
+/// (`writes_cf_stage2()` is `true` only for the two composable classes, so team-absent, cohort-absent,
+/// and reclassified-out all resolve to orphan). `None` when the id can't be classified (outside `i32`),
+/// which the caller leaves in place.
+fn is_orphan(snapshot: &FilterCatalog, key: &Stage2Key) -> Option<bool> {
+ // Keys store `u64`; `TeamId`/`CohortId` are `i32`, so an overflowing id can't be matched.
+ let team_id = i32::try_from(key.team_id).ok()?;
+ let cohort_id = i32::try_from(key.cohort_id).ok()?;
+ let live = snapshot
+ .team(TeamId(team_id))
+ .and_then(|team_filters| team_filters.eligibility.get(&CohortId(cohort_id)))
+ .is_some_and(|eligibility| eligibility.writes_cf_stage2());
+ Some(!live)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use crate::filters::reverse_index::TeamFilters;
+ use crate::stage1::key::LeafStateKey;
+ use crate::stage2::state::Stage2State;
+ use crate::stage2::{CohortEligibility, ExcludedReason};
+ use crate::store::{OpaqueCf, StoreConfig};
+
+ const PARTITION: u16 = 5;
+ const ABSENT_TEAM: u64 = 7;
+ const LIVE_TEAM: u64 = 8;
+ const NO_CAP: usize = 10_000;
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ fn stage2_key(team_id: u64, cohort_id: u64, person: u128) -> Stage2Key {
+ Stage2Key {
+ partition_id: PARTITION,
+ team_id,
+ cohort_id,
+ person_id: Uuid::from_u128(person),
+ }
+ }
+
+ fn put_row(store: &CohortStore, key: &Stage2Key) {
+ let value = Stage2State {
+ in_cohort: true,
+ last_evaluated_at_ms: 1_700_000_000_000,
+ }
+ .encode();
+ store
+ .write_batch(|batch| batch.put_stage2(key, &value))
+ .unwrap();
+ }
+
+ fn exists(store: &CohortStore, key: &Stage2Key) -> bool {
+ store.get_stage2(key).unwrap().is_some()
+ }
+
+ /// A `TeamFilters` with only its eligibility map populated — the one field the orphan GC reads.
+ fn team_filters(eligibility: &[(i32, CohortEligibility)]) -> TeamFilters {
+ let mut filters = TeamFilters::default();
+ for &(cohort_id, class) in eligibility {
+ filters.eligibility.insert(CohortId(cohort_id), class);
+ }
+ filters
+ }
+
+ /// A loaded catalog from `(team_id, [(cohort_id, class)])` pairs.
+ fn loaded(teams: &[(i32, &[(i32, CohortEligibility)])]) -> CatalogHandle {
+ CatalogHandle::from_catalog(FilterCatalog::from_teams(
+ teams
+ .iter()
+ .map(|&(team_id, elig)| (TeamId(team_id), team_filters(elig))),
+ ))
+ }
+
+ /// A non-empty catalog with `LIVE_TEAM` composable and `ABSENT_TEAM` absent.
+ fn live_team_only() -> CatalogHandle {
+ loaded(&[(
+ LIVE_TEAM as i32,
+ &[(1, CohortEligibility::Stage2Composable)],
+ )])
+ }
+
+ fn single_leaf() -> CohortEligibility {
+ CohortEligibility::SingleLeaf(LeafStateKey([0xAB; 16]))
+ }
+
+ #[test]
+ fn orphan_row_for_an_absent_team_is_deleted() {
+ let (_dir, store) = temp_store();
+ let orphan = stage2_key(ABSENT_TEAM, 1, 100);
+ put_row(&store, &orphan);
+
+ let catalog = live_team_only();
+ let mut cursor = Stage2GcCursor::default();
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, NO_CAP);
+
+ assert!(
+ !exists(&store, &orphan),
+ "a row for a team absent from the catalog is an orphan and is reclaimed",
+ );
+ }
+
+ #[test]
+ fn orphan_row_for_a_cohort_reclassified_out_of_composable_is_deleted() {
+ let (_dir, store) = temp_store();
+ // Team present, but cohort 1 is now SingleLeaf and cohort 2 absent — both left the composable set.
+ let reclassified = stage2_key(LIVE_TEAM, 1, 100);
+ let deleted_cohort = stage2_key(LIVE_TEAM, 2, 100);
+ put_row(&store, &reclassified);
+ put_row(&store, &deleted_cohort);
+
+ let catalog = loaded(&[(LIVE_TEAM as i32, &[(1, single_leaf())])]);
+ let mut cursor = Stage2GcCursor::default();
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, NO_CAP);
+
+ assert!(
+ !exists(&store, &reclassified),
+ "a SingleLeaf reclassification leaves the cf_stage2 row an orphan",
+ );
+ assert!(
+ !exists(&store, &deleted_cohort),
+ "a cohort absent from the catalog leaves its cf_stage2 row an orphan",
+ );
+ }
+
+ #[test]
+ fn live_composable_cohort_row_is_kept() {
+ let (_dir, store) = temp_store();
+ let live = stage2_key(LIVE_TEAM, 1, 100);
+ put_row(&store, &live);
+
+ let catalog = loaded(&[(
+ LIVE_TEAM as i32,
+ &[(1, CohortEligibility::Stage2Composable)],
+ )]);
+ let mut cursor = Stage2GcCursor::default();
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, NO_CAP);
+
+ assert!(
+ exists(&store, &live),
+ "a still-composable cohort's row is live and must be kept",
+ );
+ }
+
+ #[test]
+ fn composable_ref_cohort_row_is_kept() {
+ let (_dir, store) = temp_store();
+ // Stage2ComposableRef also persists a cf_stage2 row — guard against a too-narrow predicate.
+ let live = stage2_key(LIVE_TEAM, 1, 100);
+ put_row(&store, &live);
+
+ let catalog = loaded(&[(
+ LIVE_TEAM as i32,
+ &[(1, CohortEligibility::Stage2ComposableRef)],
+ )]);
+ let mut cursor = Stage2GcCursor::default();
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, NO_CAP);
+
+ assert!(
+ exists(&store, &live),
+ "a Stage2ComposableRef cohort's row is live and must be kept",
+ );
+ }
+
+ #[test]
+ fn pass_is_skipped_when_catalog_is_unloaded() {
+ let (_dir, store) = temp_store();
+ let orphan = stage2_key(ABSENT_TEAM, 1, 100);
+ put_row(&store, &orphan);
+
+ // A fresh handle is unloaded; the pass must not delete before the first successful refresh.
+ let catalog = CatalogHandle::new();
+ assert!(!catalog.is_loaded());
+ let mut cursor = Stage2GcCursor::default();
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, NO_CAP);
+
+ assert!(
+ exists(&store, &orphan),
+ "no deletion before the first catalog load (the is_loaded gate)",
+ );
+ }
+
+ #[test]
+ fn pass_is_skipped_when_catalog_is_empty() {
+ let (_dir, store) = temp_store();
+ let orphan = stage2_key(ABSENT_TEAM, 1, 100);
+ put_row(&store, &orphan);
+
+ // Loaded but empty (team_count() == 0): a spurious empty refresh must never mass-delete.
+ let catalog = CatalogHandle::from_catalog(FilterCatalog::from_teams([]));
+ assert!(catalog.is_loaded());
+ assert_eq!(catalog.load().team_count(), 0);
+ let mut cursor = Stage2GcCursor::default();
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, NO_CAP);
+
+ assert!(
+ exists(&store, &orphan),
+ "an empty catalog is not a basis for deletion (the team_count gate)",
+ );
+ }
+
+ #[test]
+ fn respects_the_scan_cap_and_resumes_via_the_cursor() {
+ let (_dir, store) = temp_store();
+ // Six orphans for the absent team; a cap of 2 reclaims only the first two per tick.
+ let orphans: Vec<Stage2Key> = (1..=6u128).map(|p| stage2_key(ABSENT_TEAM, 1, p)).collect();
+ for key in &orphans {
+ put_row(&store, key);
+ }
+
+ let catalog = live_team_only();
+ let mut cursor = Stage2GcCursor::default();
+ let surviving = |store: &CohortStore| orphans.iter().filter(|k| exists(store, k)).count();
+
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, 2);
+ assert_eq!(surviving(&store), 4, "tick 1 deleted exactly the cap of 2");
+
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, 2);
+ assert_eq!(surviving(&store), 2, "tick 2 deleted the next 2");
+
+ // Tick 3 drains the last 2 on an exactly-full page, so the cursor advances rather than wrapping.
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, 2);
+ assert_eq!(
+ surviving(&store),
+ 0,
+ "all orphans gone after three capped ticks"
+ );
+ assert!(
+ cursor.0.is_some(),
+ "a full final page leaves the cursor advanced, not wrapped"
+ );
+
+ // The next tick finds an empty page and wraps to the prefix start.
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, 2);
+ assert!(
+ cursor.0.is_none(),
+ "an empty follow-up tick wraps the cursor to the prefix start",
+ );
+ }
+
+ #[test]
+ fn cursor_advances_past_live_rows_to_reach_an_orphan() {
+ let (_dir, store) = temp_store();
+ // Three live rows (LIVE_TEAM sorts first) then one orphan (ABSENT_TEAM sorts last); a cap of 1
+ // forces the cursor past each survivor before it can reach the orphan.
+ let live: Vec<Stage2Key> = (1..=3u128).map(|p| stage2_key(LIVE_TEAM, 1, p)).collect();
+ for key in &live {
+ put_row(&store, key);
+ }
+ let orphan = stage2_key(ABSENT_TEAM, 1, 100);
+ put_row(&store, &orphan);
+
+ let catalog = live_team_only();
+ let mut cursor = Stage2GcCursor::default();
+
+ // Three ticks scan a survivor each; the fourth reaches and deletes the orphan.
+ for _ in 0..4 {
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, 1);
+ }
+
+ assert!(
+ !exists(&store, &orphan),
+ "the cursor advanced past the live rows to the orphan"
+ );
+ for key in &live {
+ assert!(exists(&store, key), "every live row survived the sweep");
+ }
+ }
+
+ #[test]
+ fn undecodable_or_impossible_key_is_left_in_place() {
+ let (_dir, store) = temp_store();
+
+ // A real orphan, to prove the pass still does its work.
+ let orphan = stage2_key(ABSENT_TEAM, 1, 100);
+ put_row(&store, &orphan);
+
+ // A decodable key whose team_id overflows i32 — can't be classified against the catalog.
+ let impossible = stage2_key(u64::MAX, 1, 200);
+ put_row(&store, &impossible);
+
+ // A corrupt key the decoder rejects (wrong length), staged under the partition prefix so the
+ // scan still reaches it.
+ let mut corrupt = PARTITION.to_be_bytes().to_vec();
+ corrupt.extend_from_slice(&[0xFFu8; 8]); // 10 bytes ≠ STAGE2_KEY_LEN (34)
+ store
+ .write_batch(|batch| batch.put_raw(OpaqueCf::Stage2, &corrupt, b"x"))
+ .unwrap();
+
+ let catalog = live_team_only();
+ let mut cursor = Stage2GcCursor::default();
+ handle_stage2_orphan_gc(PARTITION, &store, &catalog, &mut cursor, NO_CAP);
+
+ assert!(
+ !exists(&store, &orphan),
+ "the classifiable orphan is reclaimed"
+ );
+ assert!(
+ exists(&store, &impossible),
+ "a key with an out-of-i32 id is left in place (can't classify confidently)",
+ );
+ assert!(
+ store.get(Cf::Stage2, &corrupt).unwrap().is_some(),
+ "a corrupt, undecodable key is left in place (no delete-by-raw-bytes path)",
+ );
+ }
+
+ #[test]
+ fn is_orphan_classifies_each_eligibility_class() {
+ let catalog = FilterCatalog::from_teams([(
+ TeamId(LIVE_TEAM as i32),
+ team_filters(&[
+ (1, CohortEligibility::Stage2Composable),
+ (2, CohortEligibility::Stage2ComposableRef),
+ (3, single_leaf()),
+ (4, CohortEligibility::Excluded(ExcludedReason::HasCohortRef)),
+ ]),
+ )]);
+
+ // Composable classes are live (kept).
+ assert_eq!(
+ is_orphan(&catalog, &stage2_key(LIVE_TEAM, 1, 0)),
+ Some(false)
+ );
+ assert_eq!(
+ is_orphan(&catalog, &stage2_key(LIVE_TEAM, 2, 0)),
+ Some(false)
+ );
+ // SingleLeaf / Excluded no longer write cf_stage2 → orphan.
+ assert_eq!(
+ is_orphan(&catalog, &stage2_key(LIVE_TEAM, 3, 0)),
+ Some(true)
+ );
+ assert_eq!(
+ is_orphan(&catalog, &stage2_key(LIVE_TEAM, 4, 0)),
+ Some(true)
+ );
+ // Cohort absent from the team → orphan; team absent → orphan.
+ assert_eq!(
+ is_orphan(&catalog, &stage2_key(LIVE_TEAM, 99, 0)),
+ Some(true)
+ );
+ assert_eq!(
+ is_orphan(&catalog, &stage2_key(ABSENT_TEAM, 1, 0)),
+ Some(true)
+ );
+ // An id outside i32 can't be classified → None (left in place).
+ assert_eq!(is_orphan(&catalog, &stage2_key(u64::MAX, 1, 0)), None);
+ assert_eq!(
+ is_orphan(&catalog, &stage2_key(LIVE_TEAM, u64::MAX, 0)),
+ None
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/stage2_path.rs b/rust/cohort-stream-processor/src/workers/stage2_path.rs
new file mode 100644
index 000000000000..1df240c5e8fb
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/stage2_path.rs
@@ -0,0 +1,996 @@
+//! Stage 2 composition: re-evaluates multi-leaf cohorts when Stage 1 flips a leaf.
+//!
+//! [`compose_stage2`] reads each affected cohort's leaf states, evaluates the tree, diffs against the
+//! stored `cf_stage2` bit, and emits membership changes on a flip. At-most-once: a crash between
+//! the Stage 1 and Stage 2 commits drops a flip, but `evaluate_tree` recomputes the whole cohort
+//! each event, so a mismatch self-heals on the person's next event.
+
+use std::collections::{BTreeSet, HashMap};
+
+use metrics::counter;
+use uuid::Uuid;
+
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::tree::{CohortLeaf, CohortTree, FilterNode};
+use crate::filters::CohortId;
+use crate::observability::metrics::{
+ STAGE2_COHORTS_EVALUATED, STAGE2_STATE_DECODE_ERROR, STAGE2_TRANSITIONS,
+};
+use crate::producer::{CohortMembershipChange, MembershipStatus};
+use crate::stage1::key::{LeafStateKey, Stage1Key};
+use crate::stage1::state::{Stage1State, StatefulRecord};
+use crate::stage1::transition::LeafTransition;
+use crate::stage2::evaluator::{evaluate_tree, leaf_membership};
+use crate::stage2::state::Stage2State;
+use crate::stage2::CohortEligibility;
+use crate::store::{CohortStore, Stage2Key, StoreError};
+
+pub fn compose_stage2(
+ partition_id: u16,
+ store: &CohortStore,
+ filters: &TeamFilters,
+ transitions: &[LeafTransition],
+ event_ms: i64,
+ last_updated: &str,
+) -> Result<Vec<CohortMembershipChange>, StoreError> {
+ let mut affected: BTreeSet<(CohortId, Uuid)> = BTreeSet::new();
+ for transition in transitions {
+ if let Some(cohorts) = filters
+ .by_lsk_to_composable_cohorts
+ .get(&transition.leaf_state_key)
+ {
+ for &cohort_id in cohorts {
+ affected.insert((cohort_id, transition.person_id));
+ }
+ }
+ }
+ if affected.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let mut changes = Vec::new();
+ let mut pending: Vec<(Stage2Key, Stage2State)> = Vec::new();
+ let mut evaluated: u64 = 0;
+
+ for (cohort_id, person_id) in affected {
+ let Some(tree) = filters.cohorts.get(&cohort_id) else {
+ continue;
+ };
+
+ let diff = recompute_and_diff(partition_id, person_id, tree, filters, store)?;
+ evaluated += 1;
+ if !diff.flipped() {
+ continue;
+ }
+
+ changes.push(CohortMembershipChange {
+ team_id: tree.team_id.0,
+ cohort_id: cohort_id.0,
+ person_id: person_id.to_string(),
+ last_updated: last_updated.to_string(),
+ status: diff.status(),
+ });
+ // Write `false` rather than deleting so absence means "never evaluated".
+ pending.push((
+ diff.stage2_key,
+ Stage2State {
+ in_cohort: diff.new_bit,
+ last_evaluated_at_ms: event_ms,
+ },
+ ));
+ }
+
+ if !pending.is_empty() {
+ store.write_batch(|batch| {
+ for (key, state) in &pending {
+ batch.put_stage2(key, &state.encode());
+ }
+ })?;
+ }
+
+ counter!(STAGE2_COHORTS_EVALUATED).increment(evaluated);
+ for change in &changes {
+ counter!(STAGE2_TRANSITIONS, "kind" => change.status.as_str()).increment(1);
+ }
+
+ Ok(changes)
+}
+
+/// One cohort's recomputed membership for one person, diffed against the stored `cf_stage2` bit.
+/// Shared by Stage 2 composition and the cascade handler so the two recompute paths cannot diverge.
+pub(crate) struct RecomputeDiff {
+ pub new_bit: bool,
+ pub prior_bit: bool,
+ pub stage2_key: Stage2Key,
+}
+
+impl RecomputeDiff {
+ pub fn flipped(&self) -> bool {
+ self.new_bit != self.prior_bit
+ }
+
+ pub fn status(&self) -> MembershipStatus {
+ if self.new_bit {
+ MembershipStatus::Entered
+ } else {
+ MembershipStatus::Left
+ }
+ }
+}
+
+/// Recompute one cohort's membership and diff against the stored `cf_stage2` bit. Reads only — the
+/// caller stages the write, so it owns the produce/commit ordering.
+pub(crate) fn recompute_and_diff(
+ partition_id: u16,
+ person_id: Uuid,
+ tree: &CohortTree,
+ filters: &TeamFilters,
+ store: &CohortStore,
+) -> Result<RecomputeDiff, StoreError> {
+ let team_id = tree.team_id.0 as u64;
+ let new_bit = evaluate_cohort(partition_id, team_id, person_id, tree, filters, store)?;
+ let stage2_key = Stage2Key {
+ partition_id,
+ team_id,
+ cohort_id: tree.cohort_id.0 as u64,
+ person_id,
+ };
+ let prior_bit = read_stage2_bit(store, &stage2_key)?;
+ Ok(RecomputeDiff {
+ new_bit,
+ prior_bit,
+ stage2_key,
+ })
+}
+
+/// Compose one cohort for one person. A leaf with absent or undecodable state reads as non-member;
+/// a cohort-reference leaf reads the referenced cohort's stored membership (see [`resolve_ref_membership`]).
+fn evaluate_cohort(
+ partition_id: u16,
+ team_id: u64,
+ person_id: Uuid,
+ tree: &CohortTree,
+ filters: &TeamFilters,
+ store: &CohortStore,
+) -> Result<bool, StoreError> {
+ let mut lsks = Vec::new();
+ collect_leaf_state_keys(&tree.root, &mut lsks);
+
+ let keys: Vec<Stage1Key> = lsks
+ .iter()
+ .map(|&lsk| Stage1Key {
+ partition_id,
+ team_id,
+ leaf_state_key: lsk,
+ person_id,
+ })
+ .collect();
+ let raw = store.multi_get_stage1(&keys)?;
+
+ let mut membership: HashMap<LeafStateKey, bool> = HashMap::with_capacity(lsks.len());
+ for (lsk, bytes) in lsks.iter().zip(raw) {
+ let Some(meta) = filters.by_lsk.get(lsk) else {
+ continue;
+ };
+ let state = decode_stage1_state(bytes);
+ membership.insert(*lsk, leaf_membership(state.as_ref(), meta));
+ }
+
+ let ref_membership =
+ resolve_ref_membership(partition_id, team_id, person_id, tree, filters, store)?;
+
+ Ok(evaluate_tree(&tree.root, &membership, &ref_membership))
+}
+
+/// Resolve each referenced cohort's membership for one person, keyed by referenced cohort id.
+/// A `SingleLeaf` referent is read from `cf_stage1` via [`leaf_membership`] (so its comparator
+/// applies); a composable referent from its stored `cf_stage2` bit; anything else as non-member.
+/// One batched read per store.
+fn resolve_ref_membership(
+ partition_id: u16,
+ team_id: u64,
+ person_id: Uuid,
+ tree: &CohortTree,
+ filters: &TeamFilters,
+ store: &CohortStore,
+) -> Result<HashMap<CohortId, bool>, StoreError> {
+ let mut ref_ids = Vec::new();
+ collect_cohort_refs(&tree.root, &mut ref_ids);
+ if ref_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+ ref_ids.sort_unstable();
+ ref_ids.dedup();
+
+ let mut ref_membership: HashMap<CohortId, bool> = HashMap::with_capacity(ref_ids.len());
+ let mut single_leaf_refs: Vec<(CohortId, LeafStateKey)> = Vec::new();
+ let mut composable_refs: Vec<CohortId> = Vec::new();
+ for ref_id in ref_ids {
+ match filters.eligibility.get(&ref_id) {
+ Some(CohortEligibility::SingleLeaf(lsk)) => single_leaf_refs.push((ref_id, *lsk)),
+ Some(elig) if elig.writes_cf_stage2() => composable_refs.push(ref_id),
+ // Excluded, cyclic, or absent from the catalog: non-member.
+ _ => {
+ ref_membership.insert(ref_id, false);
+ }
+ }
+ }
+
+ if !single_leaf_refs.is_empty() {
+ let keys: Vec<Stage1Key> = single_leaf_refs
+ .iter()
+ .map(|(_, lsk)| Stage1Key {
+ partition_id,
+ team_id,
+ leaf_state_key: *lsk,
+ person_id,
+ })
+ .collect();
+ let raw = store.multi_get_stage1(&keys)?;
+ for ((ref_id, lsk), bytes) in single_leaf_refs.iter().zip(raw) {
+ let bit = filters
+ .by_lsk
+ .get(lsk)
+ .map(|meta| leaf_membership(decode_stage1_state(bytes).as_ref(), meta))
+ .unwrap_or(false);
+ ref_membership.insert(*ref_id, bit);
+ }
+ }
+
+ if !composable_refs.is_empty() {
+ let keys: Vec<Stage2Key> = composable_refs
+ .iter()
+ .map(|ref_id| Stage2Key {
+ partition_id,
+ team_id,
+ cohort_id: ref_id.0 as u64,
+ person_id,
+ })
+ .collect();
+ let raw = store.multi_get_stage2(&keys)?;
+ for (ref_id, bytes) in composable_refs.iter().zip(raw) {
+ ref_membership.insert(*ref_id, decode_stage2_bit(bytes));
+ }
+ }
+
+ Ok(ref_membership)
+}
+
+/// Decode a `cf_stage1` value, or [`None`] for absent/undecodable rows.
+fn decode_stage1_state(bytes: Option<Vec<u8>>) -> Option<Stage1State> {
+ let bytes = bytes?;
+ match StatefulRecord::decode(&bytes) {
+ Ok(record) => Some(record.state),
+ Err(_) => {
+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);
+ None
+ }
+ }
+}
+
+/// The stored `cf_stage2` membership bit for `key`, `false` when absent or undecodable.
+fn read_stage2_bit(store: &CohortStore, key: &Stage2Key) -> Result<bool, StoreError> {
+ Ok(decode_stage2_bit(store.get_stage2(key)?))
+}
+
+/// Decode a `cf_stage2` value into its membership bit, `false` when absent or undecodable.
+fn decode_stage2_bit(bytes: Option<Vec<u8>>) -> bool {
+ let Some(bytes) = bytes else {
+ return false;
+ };
+ match Stage2State::decode(&bytes) {
+ Ok(state) => state.in_cohort,
+ Err(_) => {
+ counter!(STAGE2_STATE_DECODE_ERROR).increment(1);
+ false
+ }
+ }
+}
+
+/// Collect every state-keyed leaf's [`LeafStateKey`] in pre-order.
+fn collect_leaf_state_keys(node: &FilterNode, out: &mut Vec<LeafStateKey>) {
+ match node {
+ FilterNode::Group { children, .. } => {
+ for child in children {
+ collect_leaf_state_keys(child, out);
+ }
+ }
+ FilterNode::Leaf(leaf) => {
+ if let Some(lsk) = leaf.leaf_state_key() {
+ out.push(lsk);
+ }
+ }
+ }
+}
+
+/// Collect referenced cohort ids (with duplicates; the caller dedups). Negation is left to
+/// `evaluate_tree`, so a referent referenced twice with opposite negation reads one bit.
+fn collect_cohort_refs(node: &FilterNode, out: &mut Vec<CohortId>) {
+ match node {
+ FilterNode::Group { children, .. } => {
+ for child in children {
+ collect_cohort_refs(child, out);
+ }
+ }
+ FilterNode::Leaf(CohortLeaf::CohortRef(config)) => out.push(config.referenced_cohort_id),
+ FilterNode::Leaf(_) => {}
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::UTC;
+ use serde_json::{json, Value};
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use crate::filters::{CohortId, TeamFiltersBuilder, TeamId};
+ use crate::stage1::state::AppliedOffsets;
+ use crate::stage1::transition::TransitionKind;
+ use crate::store::StoreConfig;
+
+ const TEAM: u64 = 7;
+ const PARTITION: u16 = 0;
+ const HASH: [u8; 16] = *b"0123456789abcdef";
+ const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
+ const TS: &str = "2026-05-26 12:34:56.789123";
+ const EVENT_MS: i64 = 1_700_000_000_000;
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ fn behavioral_leaf(window_days: i64) -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": window_days, "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn daily_leaf(window_days: i64, op: &str, value: i64) -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",
+ "time_value": window_days, "time_interval": "day",
+ "operator": op, "operator_value": value,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn daily_state(count: u32) -> Stage1State {
+ let mut buckets = vec![0u32; 8];
+ buckets[7] = count;
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day: 20_600,
+ last_event_at_ms: EVENT_MS,
+ earliest_eviction_at_ms: i64::MAX,
+ }
+ }
+
+ fn person_leaf() -> Value {
+ json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+ }
+
+ fn freeze(values: Vec<Value>) -> TeamFilters {
+ let cohort = json!({ "properties": { "type": "AND", "values": values } });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(TEAM as i32), &cohort)
+ .unwrap();
+ builder.freeze(UTC)
+ }
+
+ fn person(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+ }
+
+ fn behavioral_match() -> Stage1State {
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: EVENT_MS,
+ earliest_eviction_at_ms: i64::MAX,
+ }
+ }
+
+ fn person_state(matches: bool) -> Stage1State {
+ Stage1State::PersonProperty {
+ matches,
+ last_updated_at_ms: EVENT_MS,
+ last_updated_offset: 0,
+ }
+ }
+
+ fn write_stage1(store: &CohortStore, lsk: LeafStateKey, who: Uuid, state: Stage1State) {
+ let key = Stage1Key {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ leaf_state_key: lsk,
+ person_id: who,
+ };
+ let record = StatefulRecord::new(state, AppliedOffsets::default());
+ store
+ .write_batch(|b| b.put_stage1(&key, &record.encode()))
+ .unwrap();
+ }
+
+ fn transition(
+ lsk: LeafStateKey,
+ who: Uuid,
+ hash: [u8; 16],
+ kind: TransitionKind,
+ ) -> LeafTransition {
+ LeafTransition {
+ team_id: TeamId(TEAM as i32),
+ leaf_state_key: lsk,
+ person_id: who,
+ condition_hash: hash,
+ kind,
+ }
+ }
+
+ fn stage2_bit(store: &CohortStore, cohort: u64, who: Uuid) -> Option<bool> {
+ let key = Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ cohort_id: cohort,
+ person_id: who,
+ };
+ store
+ .get_stage2(&key)
+ .unwrap()
+ .map(|bytes| Stage2State::decode(&bytes).unwrap().in_cohort)
+ }
+
+ fn and_leaf_keys(filters: &TeamFilters) -> (LeafStateKey, LeafStateKey) {
+ (
+ filters.by_condition_to_lsk[&HASH][0],
+ LeafStateKey::for_person_property(&PERSON_HASH),
+ )
+ }
+
+ #[test]
+ fn entered_when_the_and_is_satisfied() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);
+ let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
+ let alice = person(1);
+
+ write_stage1(&store, beh_lsk, alice, behavioral_match());
+ write_stage1(&store, per_lsk, alice, person_state(true));
+
+ let changes = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+
+ assert_eq!(changes.len(), 1);
+ assert_eq!(changes[0].cohort_id, 1);
+ assert_eq!(changes[0].team_id, TEAM as i32);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[0].person_id, alice.to_string());
+ assert_eq!(changes[0].last_updated, TS);
+ assert_eq!(stage2_bit(&store, 1, alice), Some(true), "bit committed");
+ }
+
+ #[test]
+ fn no_emit_until_the_second_leaf_flips() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);
+ let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
+ let alice = person(1);
+
+ write_stage1(&store, beh_lsk, alice, behavioral_match());
+ let phase_a = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert!(phase_a.is_empty(), "one leaf does not satisfy the AND");
+ assert_eq!(
+ stage2_bit(&store, 1, alice),
+ None,
+ "no bit written on a non-flip"
+ );
+
+ write_stage1(&store, per_lsk, alice, person_state(true));
+ let phase_b = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(
+ per_lsk,
+ alice,
+ PERSON_HASH,
+ TransitionKind::Entered,
+ )],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert_eq!(phase_b.len(), 1);
+ assert_eq!(phase_b[0].status, MembershipStatus::Entered);
+ assert_eq!(stage2_bit(&store, 1, alice), Some(true));
+ }
+
+ #[test]
+ fn left_when_a_leaf_drops() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);
+ let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
+ let alice = person(1);
+
+ write_stage1(&store, beh_lsk, alice, behavioral_match());
+ write_stage1(&store, per_lsk, alice, person_state(true));
+ let entered = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert_eq!(entered.len(), 1);
+ assert_eq!(entered[0].status, MembershipStatus::Entered);
+
+ write_stage1(&store, per_lsk, alice, person_state(false));
+ let left = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(
+ per_lsk,
+ alice,
+ PERSON_HASH,
+ TransitionKind::Left,
+ )],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert_eq!(left.len(), 1);
+ assert_eq!(left[0].status, MembershipStatus::Left);
+ assert_eq!(
+ stage2_bit(&store, 1, alice),
+ Some(false),
+ "a Left writes the false bit, it does not delete the row",
+ );
+ }
+
+ #[test]
+ fn idempotent_re_evaluation_emits_once() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![behavioral_leaf(7), person_leaf()]);
+ let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
+ let alice = person(1);
+ write_stage1(&store, beh_lsk, alice, behavioral_match());
+ write_stage1(&store, per_lsk, alice, person_state(true));
+
+ let first = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert_eq!(first.len(), 1, "the first evaluation enters");
+
+ let second = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert!(
+ second.is_empty(),
+ "a re-evaluation with no change emits nothing"
+ );
+ }
+
+ #[test]
+ fn dedups_when_one_event_flips_two_leaves_of_one_cohort() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![behavioral_leaf(7), behavioral_leaf(30)]);
+ let lsks = &filters.by_condition_to_lsk[&HASH];
+ assert_eq!(lsks.len(), 2, "two windows fan out to two LSKs");
+ let alice = person(1);
+ write_stage1(&store, lsks[0], alice, behavioral_match());
+ write_stage1(&store, lsks[1], alice, behavioral_match());
+
+ let changes = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[
+ transition(lsks[0], alice, HASH, TransitionKind::Entered),
+ transition(lsks[1], alice, HASH, TransitionKind::Entered),
+ ],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+
+ assert_eq!(
+ changes.len(),
+ 1,
+ "two leaf flips of one cohort dedup to a single Entered",
+ );
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ }
+
+ #[test]
+ fn composes_a_performed_event_multiple_leaf_via_variant_dispatch() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![daily_leaf(7, "gte", 2), person_leaf()]);
+ let beh_lsk = filters.by_condition_to_lsk[&HASH][0];
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = person(1);
+ write_stage1(&store, beh_lsk, alice, daily_state(2));
+ write_stage1(&store, per_lsk, alice, person_state(true));
+
+ let changes = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert_eq!(
+ changes.len(),
+ 1,
+ "count 2 ≥ gte 2 → the multiple leaf is a member"
+ );
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[0].cohort_id, 1);
+
+ let (_dir2, store2) = temp_store();
+ write_stage1(&store2, beh_lsk, alice, daily_state(1)); // 1 < gte 2
+ write_stage1(&store2, per_lsk, alice, person_state(true));
+ let below = compose_stage2(
+ PARTITION,
+ &store2,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert!(
+ below.is_empty(),
+ "count 1 fails gte 2, so the multiple leaf is not a member and the AND is unsatisfied",
+ );
+ }
+
+ #[test]
+ fn transitions_touching_no_composable_cohort_emit_nothing() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![behavioral_leaf(7)]);
+ let beh_lsk = filters.by_condition_to_lsk[&HASH][0];
+ let alice = person(1);
+ write_stage1(&store, beh_lsk, alice, behavioral_match());
+
+ let changes = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert!(
+ changes.is_empty(),
+ "a single-leaf cohort is handled by map_transition, not Stage 2",
+ );
+ }
+
+ fn negated_person_leaf() -> Value {
+ json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ "negation": true,
+ })
+ }
+
+ #[test]
+ fn negated_leaf_absent_means_entered() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![behavioral_leaf(7), negated_person_leaf()]);
+ let (beh_lsk, _per_lsk) = and_leaf_keys(&filters);
+ let alice = person(1);
+
+ write_stage1(&store, beh_lsk, alice, behavioral_match());
+
+ let changes = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert_eq!(changes.len(), 1);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ }
+
+ #[test]
+ fn negated_leaf_present_means_left() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![behavioral_leaf(7), negated_person_leaf()]);
+ let (beh_lsk, per_lsk) = and_leaf_keys(&filters);
+ let alice = person(1);
+
+ write_stage1(&store, beh_lsk, alice, behavioral_match());
+ let entered = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(beh_lsk, alice, HASH, TransitionKind::Entered)],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert_eq!(entered.len(), 1);
+ assert_eq!(entered[0].status, MembershipStatus::Entered);
+
+ write_stage1(&store, per_lsk, alice, person_state(true));
+ let left = compose_stage2(
+ PARTITION,
+ &store,
+ &filters,
+ &[transition(
+ per_lsk,
+ alice,
+ PERSON_HASH,
+ TransitionKind::Entered,
+ )],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap();
+ assert_eq!(left.len(), 1);
+ assert_eq!(left[0].status, MembershipStatus::Left);
+ }
+
+ use crate::stage2::CohortEligibility;
+
+ fn cohort_ref(target: i32) -> Value {
+ json!({ "type": "cohort", "value": target, "negation": false })
+ }
+
+ fn negated_cohort_ref(target: i32) -> Value {
+ json!({ "type": "cohort", "value": target, "negation": true })
+ }
+
+ /// Freeze several `(cohort_id, leaves)` cohorts into one team with the cascade gate set.
+ fn freeze_cascade(cohorts: Vec<(i32, Vec<Value>)>, cascade_enabled: bool) -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ for (id, values) in cohorts {
+ let cohort = json!({ "properties": { "type": "AND", "values": values } });
+ builder
+ .add_cohort(CohortId(id), TeamId(TEAM as i32), &cohort)
+ .unwrap();
+ }
+ builder.freeze_with(UTC, cascade_enabled)
+ }
+
+ fn write_stage2(store: &CohortStore, cohort: u64, who: Uuid, in_cohort: bool) {
+ let key = Stage2Key {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ cohort_id: cohort,
+ person_id: who,
+ };
+ let state = Stage2State {
+ in_cohort,
+ last_evaluated_at_ms: EVENT_MS,
+ };
+ store
+ .write_batch(|b| b.put_stage2(&key, &state.encode()))
+ .unwrap();
+ }
+
+ fn single_leaf_lsk(filters: &TeamFilters, cohort: i32) -> LeafStateKey {
+ match filters.eligibility[&CohortId(cohort)] {
+ CohortEligibility::SingleLeaf(lsk) => lsk,
+ other => panic!("cohort {cohort} should be SingleLeaf, got {other:?}"),
+ }
+ }
+
+ /// Compose after flipping cohort 1's own person leaf.
+ fn compose_referrer_on_own_leaf(
+ store: &CohortStore,
+ filters: &TeamFilters,
+ who: Uuid,
+ ) -> Vec<CohortMembershipChange> {
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ compose_stage2(
+ PARTITION,
+ store,
+ filters,
+ &[transition(
+ per_lsk,
+ who,
+ PERSON_HASH,
+ TransitionKind::Entered,
+ )],
+ EVENT_MS,
+ TS,
+ )
+ .unwrap()
+ }
+
+ #[test]
+ fn composable_ref_reads_a_single_leaf_referent_from_cf_stage1_via_its_op() {
+ let filters = freeze_cascade(
+ vec![
+ (2, vec![daily_leaf(7, "gte", 2)]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ assert_eq!(
+ filters.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2ComposableRef,
+ );
+ let ref2_lsk = single_leaf_lsk(&filters, 2);
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = person(1);
+
+ // Count 2 ≥ gte 2: referent 2 is a member.
+ let (_dir, store) = temp_store();
+ write_stage1(&store, ref2_lsk, alice, daily_state(2));
+ write_stage1(&store, per_lsk, alice, person_state(true));
+ let entered = compose_referrer_on_own_leaf(&store, &filters, alice);
+ assert_eq!(entered.len(), 1);
+ assert_eq!(entered[0].cohort_id, 1);
+ assert_eq!(entered[0].status, MembershipStatus::Entered);
+
+ // Count 1 < gte 2: the referent's comparator applies, so it is a non-member.
+ let (_dir2, store2) = temp_store();
+ write_stage1(&store2, ref2_lsk, alice, daily_state(1));
+ write_stage1(&store2, per_lsk, alice, person_state(true));
+ let below = compose_referrer_on_own_leaf(&store2, &filters, alice);
+ assert!(
+ below.is_empty(),
+ "count 1 fails the referent's gte 2, so the referrer's AND is unsatisfied",
+ );
+ }
+
+ #[test]
+ fn composable_ref_reads_a_composable_referent_from_cf_stage2_verbatim() {
+ let filters = freeze_cascade(
+ vec![
+ // Two distinct leaves make cohort 2 composable, so its membership lives in cf_stage2.
+ (2, vec![behavioral_leaf(7), daily_leaf(30, "gte", 1)]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ assert_eq!(
+ filters.eligibility[&CohortId(2)],
+ CohortEligibility::Stage2Composable,
+ );
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = person(1);
+
+ let (_dir, store) = temp_store();
+ // cohort 2's cf_stage1 is left absent: a recompute would read non-member, so Entered proves
+ // the stored cf_stage2 bit is read.
+ write_stage2(&store, 2, alice, true);
+ write_stage1(&store, per_lsk, alice, person_state(true));
+
+ let entered = compose_referrer_on_own_leaf(&store, &filters, alice);
+ assert_eq!(entered.len(), 1);
+ assert_eq!(entered[0].cohort_id, 1);
+ assert_eq!(entered[0].status, MembershipStatus::Entered);
+ }
+
+ #[test]
+ fn composable_ref_absent_referent_reads_non_member() {
+ let filters = freeze_cascade(
+ vec![
+ (2, vec![daily_leaf(7, "gte", 2)]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ true,
+ );
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = person(1);
+
+ let (_dir, store) = temp_store();
+ write_stage1(&store, per_lsk, alice, person_state(true));
+ let changes = compose_referrer_on_own_leaf(&store, &filters, alice);
+ assert!(
+ changes.is_empty(),
+ "an absent referent reads as a non-member, so the AND is unsatisfied",
+ );
+ }
+
+ #[test]
+ fn composable_ref_negated_absent_referent_enters() {
+ let filters = freeze_cascade(
+ vec![
+ (2, vec![daily_leaf(7, "gte", 2)]),
+ (1, vec![person_leaf(), negated_cohort_ref(2)]),
+ ],
+ true,
+ );
+ assert_eq!(
+ filters.eligibility[&CohortId(1)],
+ CohortEligibility::Stage2ComposableRef,
+ );
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = person(1);
+
+ // Referent 2 absent → negated ref reads true → Entered.
+ let (_dir, store) = temp_store();
+ write_stage1(&store, per_lsk, alice, person_state(true));
+ let entered = compose_referrer_on_own_leaf(&store, &filters, alice);
+ assert_eq!(entered.len(), 1);
+ assert_eq!(entered[0].cohort_id, 1);
+ assert_eq!(entered[0].status, MembershipStatus::Entered);
+ }
+
+ #[test]
+ fn composable_ref_is_dormant_when_the_gate_is_off() {
+ // Gate off: cohort 1 stays Excluded(HasCohortRef), is absent from the composable map, and
+ // emits nothing even though both its own leaf and the referent are satisfied.
+ let filters = freeze_cascade(
+ vec![
+ (2, vec![daily_leaf(7, "gte", 2)]),
+ (1, vec![person_leaf(), cohort_ref(2)]),
+ ],
+ false,
+ );
+ let ref2_lsk = single_leaf_lsk(&filters, 2);
+ let per_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = person(1);
+
+ let (_dir, store) = temp_store();
+ write_stage1(&store, ref2_lsk, alice, daily_state(2));
+ write_stage1(&store, per_lsk, alice, person_state(true));
+ let changes = compose_referrer_on_own_leaf(&store, &filters, alice);
+ assert!(
+ changes.is_empty(),
+ "gate off: the ref cohort is not in the composable map, so compose_stage2 skips it",
+ );
+ assert_eq!(
+ stage2_bit(&store, 1, alice),
+ None,
+ "no cf_stage2 bit written when the gate is off",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/sweep_callback.rs b/rust/cohort-stream-processor/src/workers/sweep_callback.rs
new file mode 100644
index 000000000000..b507f537dbb3
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/sweep_callback.rs
@@ -0,0 +1,925 @@
+//! Per-key time-driven eviction.
+//!
+//! [`sweep_evict`] is a pure read-and-compute pass: for each due key it reads the stored state,
+//! drops aged-out bucket(s), recomputes the predicate, and returns the membership transition, state
+//! mutation, and next eviction deadline --- but writes nothing. The worker orchestrates
+//! produce-before-write ordering so a produce failure can replay against still-un-evicted state.
+
+use chrono_tz::Tz;
+use metrics::counter;
+
+use crate::filters::reverse_index::{LeafStateMeta, TeamFilters};
+use crate::filters::TeamId;
+use crate::observability::metrics::{
+ STAGE1_STATE_DECODE_ERROR, STAGE1_UNSUPPORTED_VARIANT_SKIPPED,
+};
+use crate::stage1::bucket_tz::{daily_bucket_len, day_idx_in_tz};
+use crate::stage1::compressed_history;
+use crate::stage1::daily::{daily_eviction_deadline, slide_window_forward};
+use crate::stage1::key::Stage1Key;
+use crate::stage1::predicate::{compressed_predicate, daily_predicate, predicate};
+use crate::stage1::state::{Stage1State, StateVariant, StatefulRecord};
+use crate::stage1::transition::{LeafTransition, TransitionKind};
+use crate::store::{CohortStore, StoreError};
+
+/// The state mutation an eviction implies.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) enum EvictionAction {
+ /// Persist the advanced state (surviving entries/buckets), encoded.
+ Write(Vec<u8>),
+ /// Remove the fully-expired state. A late event re-creates it from its own timestamp.
+ Delete,
+}
+
+/// The outcome of evicting one key: optional transition, state mutation, and next deadline.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct EvictionResult {
+ pub key: Stage1Key,
+ pub variant: StateVariant,
+ pub transition: Option<LeafTransition>,
+ pub action: EvictionAction,
+ pub reschedule: Option<i64>,
+}
+
+/// Why the sweep dropped a popped key instead of evicting it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum SweepDropReason {
+ TeamDrift,
+ LeafDrift,
+ MissingState,
+ Decode,
+ UnsupportedVariant,
+ PersonProperty,
+}
+
+impl SweepDropReason {
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ Self::TeamDrift => "team_drift",
+ Self::LeafDrift => "leaf_drift",
+ Self::MissingState => "missing_state",
+ Self::Decode => "decode_error",
+ Self::UnsupportedVariant => "unsupported_variant",
+ Self::PersonProperty => "person_property",
+ }
+ }
+}
+
+/// Outcome of one [`sweep_evict`] pass: evictions to apply and drop reasons.
+#[derive(Debug, Default)]
+pub(crate) struct SweepEvictions {
+ pub results: Vec<EvictionResult>,
+ pub drops: Vec<SweepDropReason>,
+}
+
+/// Compute the eviction for each due key against a team's frozen filters, **without writing**.
+/// All `due_keys` must belong to `filters`' team.
+pub(crate) fn sweep_evict(
+ filters: &TeamFilters,
+ due_keys: &[Stage1Key],
+ store: &CohortStore,
+ due_before_ms: i64,
+) -> Result<SweepEvictions, StoreError> {
+ let mut out = SweepEvictions {
+ results: Vec::with_capacity(due_keys.len()),
+ drops: Vec::new(),
+ };
+ for &key in due_keys {
+ let record = match store.get_stage1(&key)? {
+ None => {
+ out.drops.push(SweepDropReason::MissingState);
+ continue;
+ }
+ Some(bytes) => match StatefulRecord::decode(&bytes) {
+ Ok(record) => record,
+ Err(_) => {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ out.drops.push(SweepDropReason::Decode);
+ continue;
+ }
+ },
+ };
+ let Some(meta) = filters.by_lsk.get(&key.leaf_state_key) else {
+ out.drops.push(SweepDropReason::LeafDrift);
+ continue;
+ };
+ let evicted = match meta.variant {
+ StateVariant::BehavioralSingle => evict_single(key, meta, record),
+ StateVariant::BehavioralDailyBuckets => {
+ evict_daily(key, meta, record, filters.timezone, due_before_ms)
+ }
+ StateVariant::BehavioralCompressedHistory => {
+ evict_compressed(key, meta, record, filters.timezone, due_before_ms)
+ }
+ StateVariant::PersonProperty => Err(SweepDropReason::PersonProperty),
+ };
+ match evicted {
+ Ok(result) => out.results.push(result),
+ Err(reason) => out.drops.push(reason),
+ }
+ }
+ Ok(out)
+}
+
+/// Evict a `performed_event` single: always deletes.
+fn evict_single(
+ key: Stage1Key,
+ meta: &LeafStateMeta,
+ record: StatefulRecord,
+) -> Result<EvictionResult, SweepDropReason> {
+ if !matches!(record.state, Stage1State::BehavioralSingle { .. }) {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ return Err(SweepDropReason::Decode);
+ }
+ let transition =
+ predicate(&record.state).then(|| transition_for(key, meta, TransitionKind::Left));
+ Ok(EvictionResult {
+ key,
+ variant: StateVariant::BehavioralSingle,
+ transition,
+ action: EvictionAction::Delete,
+ reschedule: None,
+ })
+}
+
+/// Slide the daily window forward, recompute the predicate, and return the net membership flip.
+/// Rewrites while any bucket survives; deletes when every bucket drains.
+fn evict_daily(
+ key: Stage1Key,
+ meta: &LeafStateMeta,
+ record: StatefulRecord,
+ tz: Tz,
+ due_before_ms: i64,
+) -> Result<EvictionResult, SweepDropReason> {
+ let (Some(window_days), Some(op)) = (meta.window_days, meta.predicate_op) else {
+ counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => StateVariant::BehavioralDailyBuckets.as_str())
+ .increment(1);
+ return Err(SweepDropReason::UnsupportedVariant);
+ };
+ let StatefulRecord {
+ state,
+ applied_offsets,
+ redirect_dedup,
+ } = record;
+ let Stage1State::BehavioralDailyBuckets {
+ mut buckets,
+ mut window_start_day,
+ last_event_at_ms,
+ ..
+ } = state
+ else {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ return Err(SweepDropReason::Decode);
+ };
+ if buckets.len() != daily_bucket_len(window_days) {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ return Err(SweepDropReason::Decode);
+ }
+
+ let predicate_before = daily_predicate(&buckets, op);
+ let target_now_day = day_idx_in_tz(due_before_ms, tz);
+ slide_window_forward(
+ &mut buckets,
+ &mut window_start_day,
+ window_days,
+ target_now_day,
+ );
+ let predicate_after = daily_predicate(&buckets, op);
+ let kind = match (predicate_before, predicate_after) {
+ (false, true) => Some(TransitionKind::Entered),
+ (true, false) => Some(TransitionKind::Left),
+ _ => None,
+ };
+ let transition = kind.map(|kind| transition_for(key, meta, kind));
+
+ let new_deadline = daily_eviction_deadline(&buckets, window_start_day, window_days, tz);
+ let (action, reschedule) = if new_deadline == i64::MAX {
+ (EvictionAction::Delete, None)
+ } else {
+ let advanced = StatefulRecord {
+ state: Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day,
+ last_event_at_ms,
+ earliest_eviction_at_ms: new_deadline,
+ },
+ applied_offsets,
+ redirect_dedup,
+ };
+ (EvictionAction::Write(advanced.encode()), Some(new_deadline))
+ };
+ debug_assert!(
+ !predicate_after || matches!(action, EvictionAction::Write(_)),
+ "a still-member eviction must rewrite + reschedule, not delete",
+ );
+ Ok(EvictionResult {
+ key,
+ variant: StateVariant::BehavioralDailyBuckets,
+ transition,
+ action,
+ reschedule,
+ })
+}
+
+/// Slide the compressed window forward and return the net membership flip (sparse run-length
+/// analog of [`evict_daily`]).
+fn evict_compressed(
+ key: Stage1Key,
+ meta: &LeafStateMeta,
+ record: StatefulRecord,
+ tz: Tz,
+ due_before_ms: i64,
+) -> Result<EvictionResult, SweepDropReason> {
+ let (Some(window_days), Some(op)) = (meta.window_days, meta.predicate_op) else {
+ counter!(STAGE1_UNSUPPORTED_VARIANT_SKIPPED, "variant" => StateVariant::BehavioralCompressedHistory.as_str())
+ .increment(1);
+ return Err(SweepDropReason::UnsupportedVariant);
+ };
+ let StatefulRecord {
+ state,
+ applied_offsets,
+ redirect_dedup,
+ } = record;
+ let Stage1State::BehavioralCompressedHistory {
+ mut entries,
+ mut window_start_day,
+ last_event_at_ms,
+ ..
+ } = state
+ else {
+ counter!(STAGE1_STATE_DECODE_ERROR).increment(1);
+ return Err(SweepDropReason::Decode);
+ };
+
+ let predicate_before = compressed_predicate(&entries, op);
+ let target_now_day = day_idx_in_tz(due_before_ms, tz);
+ compressed_history::slide_window_forward(
+ &mut entries,
+ &mut window_start_day,
+ window_days,
+ target_now_day,
+ );
+ let predicate_after = compressed_predicate(&entries, op);
+ let kind = match (predicate_before, predicate_after) {
+ (false, true) => Some(TransitionKind::Entered),
+ (true, false) => Some(TransitionKind::Left),
+ _ => None,
+ };
+ let transition = kind.map(|kind| transition_for(key, meta, kind));
+
+ let new_deadline = compressed_history::compressed_eviction_deadline(&entries, window_days, tz);
+ let (action, reschedule) = if new_deadline == i64::MAX {
+ (EvictionAction::Delete, None)
+ } else {
+ let advanced = StatefulRecord {
+ state: Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day,
+ last_event_at_ms,
+ earliest_eviction_at_ms: new_deadline,
+ },
+ applied_offsets,
+ redirect_dedup,
+ };
+ (EvictionAction::Write(advanced.encode()), Some(new_deadline))
+ };
+ debug_assert!(
+ !predicate_after || matches!(action, EvictionAction::Write(_)),
+ "a still-member eviction must rewrite + reschedule, not delete",
+ );
+ Ok(EvictionResult {
+ key,
+ variant: StateVariant::BehavioralCompressedHistory,
+ transition,
+ action,
+ reschedule,
+ })
+}
+
+fn transition_for(key: Stage1Key, meta: &LeafStateMeta, kind: TransitionKind) -> LeafTransition {
+ LeafTransition {
+ team_id: TeamId(key.team_id as i32),
+ leaf_state_key: key.leaf_state_key,
+ person_id: key.person_id,
+ condition_hash: meta.condition_hash,
+ kind,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono_tz::UTC;
+ use serde_json::{json, Value};
+ use tempfile::TempDir;
+ use uuid::Uuid;
+
+ use crate::filters::{CohortId, TeamFiltersBuilder, TeamId};
+ use crate::stage1::bucket_tz::start_of_day_ms_in_tz;
+ use crate::stage1::key::LeafStateKey;
+ use crate::stage1::state::AppliedOffsets;
+ use crate::stage1::time::clickhouse_timestamp_to_millis;
+ use crate::store::StoreConfig;
+
+ const TEAM: u64 = 7;
+ const HASH: [u8; 16] = *b"0123456789abcdef";
+ const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
+ const PARTITION: u16 = 0;
+ const WINDOW_DAYS: u32 = 7;
+ const LEN: usize = WINDOW_DAYS as usize + 1;
+ const COMPRESSED_WINDOW_DAYS: u32 = 365;
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ fn freeze(values: Vec<Value>) -> TeamFilters {
+ let cohort = json!({ "properties": { "type": "AND", "values": values } });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(TEAM as i32), &cohort)
+ .unwrap();
+ builder.freeze(UTC)
+ }
+
+ fn single_leaf(window_days: i64) -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": window_days, "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn daily_leaf(window_days: i64, op: &str, value: i64) -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",
+ "time_value": window_days, "time_interval": "day",
+ "operator": op, "operator_value": value,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn compressed_leaf(window_days: i64, op: &str, value: i64) -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",
+ "time_value": window_days, "time_interval": "day",
+ "operator": op, "operator_value": value,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+ }
+
+ fn person_leaf() -> Value {
+ json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+ }
+
+ fn key_for(filters: &TeamFilters, person: u128) -> Stage1Key {
+ Stage1Key {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ leaf_state_key: filters.by_condition_to_lsk[&HASH][0],
+ person_id: Uuid::from_u128(person),
+ }
+ }
+
+ fn write(store: &CohortStore, key: &Stage1Key, state: Stage1State) {
+ let record = StatefulRecord::new(state, AppliedOffsets::default());
+ store
+ .write_batch(|b| b.put_stage1(key, &record.encode()))
+ .unwrap();
+ }
+
+ fn day_of(ts: &str) -> i32 {
+ day_idx_in_tz(clickhouse_timestamp_to_millis(ts).unwrap(), UTC)
+ }
+
+ #[test]
+ fn single_eviction_emits_left_and_deletes() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![single_leaf(7)]);
+ let key = key_for(&filters, 1);
+ let event_ms = clickhouse_timestamp_to_millis("2026-05-20 10:00:00.000000").unwrap();
+ let deadline = event_ms + 7 * 86_400 * 1_000;
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: event_ms,
+ earliest_eviction_at_ms: deadline,
+ },
+ );
+
+ let results = sweep_evict(&filters, &[key], &store, deadline + 86_400_000)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 1);
+ let result = &results[0];
+ assert_eq!(result.variant, StateVariant::BehavioralSingle);
+ let transition = result.transition.as_ref().expect("a single evicts to Left");
+ assert_eq!(transition.kind, TransitionKind::Left);
+ assert_eq!(
+ transition.condition_hash, HASH,
+ "condition_hash from the meta"
+ );
+ assert_eq!(transition.person_id, key.person_id);
+ assert_eq!(transition.team_id, TeamId(TEAM as i32));
+ assert_eq!(result.action, EvictionAction::Delete);
+ assert_eq!(result.reschedule, None);
+ }
+
+ #[test]
+ fn daily_all_buckets_drain_emits_left_and_deletes() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![daily_leaf(7, "gte", 3)]);
+ let key = key_for(&filters, 1);
+
+ let day = day_of("2026-05-20 10:00:00.000000");
+ let mut buckets = vec![0u32; LEN];
+ buckets[LEN - 1] = 3;
+ let window_start = day - WINDOW_DAYS as i32;
+ let deadline = daily_eviction_deadline(&buckets, window_start, WINDOW_DAYS, UTC);
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ },
+ );
+
+ let cutoff = start_of_day_ms_in_tz(day + WINDOW_DAYS as i32 + 1, UTC);
+ let results = sweep_evict(&filters, &[key], &store, cutoff)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 1);
+ let result = &results[0];
+ assert_eq!(
+ result.transition.as_ref().unwrap().kind,
+ TransitionKind::Left,
+ );
+ assert_eq!(result.action, EvictionAction::Delete);
+ assert_eq!(result.reschedule, None);
+ }
+
+ #[test]
+ fn daily_drops_oldest_bucket_keeps_member_and_reschedules_later() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![daily_leaf(7, "gte", 1)]);
+ let key = key_for(&filters, 1);
+
+ let now_day = day_of("2026-05-27 10:00:00.000000");
+ let window_start = now_day - WINDOW_DAYS as i32;
+ let mut buckets = vec![0u32; LEN];
+ buckets[0] = 1; // day window_start
+ buckets[4] = 1; // day window_start + 4
+ let deadline = daily_eviction_deadline(&buckets, window_start, WINDOW_DAYS, UTC);
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ },
+ );
+
+ let cutoff = start_of_day_ms_in_tz(window_start + WINDOW_DAYS as i32 + 1, UTC);
+ let results = sweep_evict(&filters, &[key], &store, cutoff)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 1);
+ let result = &results[0];
+ assert!(result.transition.is_none(), "still ≥ 1 match → no Left");
+
+ let EvictionAction::Write(bytes) = &result.action else {
+ panic!("a surviving bucket rewrites, not deletes");
+ };
+ let advanced = StatefulRecord::decode(bytes).unwrap();
+ match advanced.state {
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ last_event_at_ms,
+ earliest_eviction_at_ms,
+ ..
+ } => {
+ assert_eq!(buckets.iter().sum::<u32>(), 1);
+ assert_eq!(last_event_at_ms, 1_700_000_000_000);
+ assert_eq!(earliest_eviction_at_ms, result.reschedule.unwrap());
+ }
+ other => panic!("expected daily buckets, got {other:?}"),
+ }
+ assert!(result.reschedule.unwrap() > deadline);
+ }
+
+ #[test]
+ fn daily_eq_slide_into_range_emits_entered() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![daily_leaf(7, "eq", 1)]);
+ let key = key_for(&filters, 1);
+
+ let day = day_of("2026-05-27 10:00:00.000000");
+ let window_start = day - WINDOW_DAYS as i32;
+ let mut buckets = vec![0u32; LEN];
+ buckets[0] = 1;
+ buckets[4] = 1;
+ let deadline = daily_eviction_deadline(&buckets, window_start, WINDOW_DAYS, UTC);
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ },
+ );
+
+ let cutoff = start_of_day_ms_in_tz(window_start + WINDOW_DAYS as i32 + 1, UTC);
+ let results = sweep_evict(&filters, &[key], &store, cutoff)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 1);
+ let result = &results[0];
+ assert_eq!(
+ result
+ .transition
+ .as_ref()
+ .expect("a falling count enters eq 1")
+ .kind,
+ TransitionKind::Entered,
+ "eq 1 flips false→true as the count drops to 1",
+ );
+ assert!(
+ matches!(result.action, EvictionAction::Write(_)),
+ "a still-member eviction rewrites the advanced state",
+ );
+ assert!(
+ result.reschedule.is_some(),
+ "the surviving bucket carries a finite next deadline",
+ );
+ }
+
+ #[test]
+ fn daily_lte_slide_into_range_emits_entered() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![daily_leaf(7, "lte", 2)]);
+ let key = key_for(&filters, 1);
+
+ let day = day_of("2026-05-27 10:00:00.000000");
+ let window_start = day - WINDOW_DAYS as i32;
+ let mut buckets = vec![0u32; LEN];
+ buckets[0] = 1;
+ buckets[4] = 2;
+ let deadline = daily_eviction_deadline(&buckets, window_start, WINDOW_DAYS, UTC);
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ },
+ );
+
+ let cutoff = start_of_day_ms_in_tz(window_start + WINDOW_DAYS as i32 + 1, UTC);
+ let results = sweep_evict(&filters, &[key], &store, cutoff)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 1);
+ let result = &results[0];
+ assert_eq!(
+ result
+ .transition
+ .as_ref()
+ .expect("a falling count enters lte 2")
+ .kind,
+ TransitionKind::Entered,
+ "lte 2 flips false→true as the count drops to 2",
+ );
+ assert!(matches!(result.action, EvictionAction::Write(_)));
+ assert!(result.reschedule.is_some());
+ }
+
+ #[test]
+ fn compressed_all_entries_drain_emits_left_and_deletes() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![compressed_leaf(
+ COMPRESSED_WINDOW_DAYS as i64,
+ "gte",
+ 3,
+ )]);
+ let key = key_for(&filters, 1);
+
+ let day = day_of("2026-05-20 10:00:00.000000");
+ let entries = vec![(day, 3u32)];
+ let window_start = day - COMPRESSED_WINDOW_DAYS as i32;
+ let deadline =
+ compressed_history::compressed_eviction_deadline(&entries, COMPRESSED_WINDOW_DAYS, UTC);
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ },
+ );
+
+ let cutoff = start_of_day_ms_in_tz(day + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC);
+ let results = sweep_evict(&filters, &[key], &store, cutoff)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 1);
+ let result = &results[0];
+ assert_eq!(result.variant, StateVariant::BehavioralCompressedHistory);
+ assert_eq!(
+ result.transition.as_ref().unwrap().kind,
+ TransitionKind::Left,
+ );
+ assert_eq!(result.action, EvictionAction::Delete);
+ assert_eq!(result.reschedule, None);
+ }
+
+ #[test]
+ fn compressed_drops_oldest_entry_keeps_member_and_reschedules_later() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![compressed_leaf(
+ COMPRESSED_WINDOW_DAYS as i64,
+ "gte",
+ 1,
+ )]);
+ let key = key_for(&filters, 1);
+
+ let now_day = day_of("2026-05-27 10:00:00.000000");
+ let window_start = now_day - COMPRESSED_WINDOW_DAYS as i32;
+ let entries = vec![(window_start, 1u32), (window_start + 100, 1u32)];
+ let deadline =
+ compressed_history::compressed_eviction_deadline(&entries, COMPRESSED_WINDOW_DAYS, UTC);
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ },
+ );
+
+ let cutoff = start_of_day_ms_in_tz(window_start + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC);
+ let results = sweep_evict(&filters, &[key], &store, cutoff)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 1);
+ let result = &results[0];
+ assert!(result.transition.is_none(), "still ≥ 1 match → no Left");
+
+ let EvictionAction::Write(bytes) = &result.action else {
+ panic!("a surviving entry rewrites, not deletes");
+ };
+ let advanced = StatefulRecord::decode(bytes).unwrap();
+ match advanced.state {
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ last_event_at_ms,
+ earliest_eviction_at_ms,
+ ..
+ } => {
+ assert_eq!(entries, vec![(window_start + 100, 1)]);
+ assert_eq!(last_event_at_ms, 1_700_000_000_000);
+ assert_eq!(earliest_eviction_at_ms, result.reschedule.unwrap());
+ }
+ other => panic!("expected compressed history, got {other:?}"),
+ }
+ assert!(result.reschedule.unwrap() > deadline);
+ }
+
+ #[test]
+ fn compressed_eq_slide_into_range_emits_entered() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![compressed_leaf(
+ COMPRESSED_WINDOW_DAYS as i64,
+ "eq",
+ 1,
+ )]);
+ let key = key_for(&filters, 1);
+
+ let now_day = day_of("2026-05-27 10:00:00.000000");
+ let window_start = now_day - COMPRESSED_WINDOW_DAYS as i32;
+ let entries = vec![(window_start, 1u32), (window_start + 100, 1u32)];
+ let deadline =
+ compressed_history::compressed_eviction_deadline(&entries, COMPRESSED_WINDOW_DAYS, UTC);
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ },
+ );
+
+ let cutoff = start_of_day_ms_in_tz(window_start + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC);
+ let results = sweep_evict(&filters, &[key], &store, cutoff)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 1);
+ let result = &results[0];
+ assert_eq!(
+ result
+ .transition
+ .as_ref()
+ .expect("a falling count enters eq 1")
+ .kind,
+ TransitionKind::Entered,
+ "eq 1 flips false→true as the count drops to 1",
+ );
+ assert!(
+ matches!(result.action, EvictionAction::Write(_)),
+ "a still-member eviction rewrites the advanced state",
+ );
+ assert!(result.reschedule.is_some());
+ }
+
+ #[test]
+ fn compressed_lte_slide_into_range_emits_entered() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![compressed_leaf(
+ COMPRESSED_WINDOW_DAYS as i64,
+ "lte",
+ 2,
+ )]);
+ let key = key_for(&filters, 1);
+
+ let now_day = day_of("2026-05-27 10:00:00.000000");
+ let window_start = now_day - COMPRESSED_WINDOW_DAYS as i32;
+ let entries = vec![(window_start, 1u32), (window_start + 100, 2u32)];
+ let deadline =
+ compressed_history::compressed_eviction_deadline(&entries, COMPRESSED_WINDOW_DAYS, UTC);
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day: window_start,
+ last_event_at_ms: 1_700_000_000_000,
+ earliest_eviction_at_ms: deadline,
+ },
+ );
+
+ let cutoff = start_of_day_ms_in_tz(window_start + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC);
+ let results = sweep_evict(&filters, &[key], &store, cutoff)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 1);
+ let result = &results[0];
+ assert_eq!(
+ result
+ .transition
+ .as_ref()
+ .expect("a falling count enters lte 2")
+ .kind,
+ TransitionKind::Entered,
+ "lte 2 flips false→true as the count drops to 2",
+ );
+ assert!(matches!(result.action, EvictionAction::Write(_)));
+ assert!(result.reschedule.is_some());
+ }
+
+ #[test]
+ fn daily_length_mismatch_skips_without_panic() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![daily_leaf(7, "gte", 1)]); // expects length 8
+ let key = key_for(&filters, 1);
+ write(
+ &store,
+ &key,
+ Stage1State::BehavioralDailyBuckets {
+ buckets: vec![1, 2, 3], // wrong length
+ window_start_day: 100,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ },
+ );
+ let out = sweep_evict(&filters, &[key], &store, i64::MAX).unwrap();
+ assert!(
+ out.results.is_empty(),
+ "a length mismatch is skipped, not panicked"
+ );
+ assert_eq!(
+ out.drops,
+ vec![SweepDropReason::Decode],
+ "a length mismatch is dropped as a decode/format desync",
+ );
+ }
+
+ #[test]
+ fn person_property_key_is_skipped() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![person_leaf()]);
+ let key = Stage1Key {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ leaf_state_key: LeafStateKey::for_person_property(&PERSON_HASH),
+ person_id: Uuid::from_u128(1),
+ };
+ write(
+ &store,
+ &key,
+ Stage1State::PersonProperty {
+ matches: true,
+ last_updated_at_ms: 1,
+ last_updated_offset: 2,
+ },
+ );
+ let out = sweep_evict(&filters, &[key], &store, i64::MAX).unwrap();
+ assert!(
+ out.results.is_empty(),
+ "person-property leaves are never time-evicted",
+ );
+ assert_eq!(
+ out.drops,
+ vec![SweepDropReason::PersonProperty],
+ "a scheduled person-property key is dropped defensively",
+ );
+ }
+
+ #[test]
+ fn unknown_leaf_and_missing_state_are_skipped() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![single_leaf(7)]);
+
+ let drifted = Stage1Key {
+ partition_id: PARTITION,
+ team_id: TEAM,
+ leaf_state_key: LeafStateKey([0xFF; 16]),
+ person_id: Uuid::from_u128(1),
+ };
+ write(
+ &store,
+ &drifted,
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1,
+ earliest_eviction_at_ms: 2,
+ },
+ );
+
+ let missing = key_for(&filters, 999);
+
+ let out = sweep_evict(&filters, &[drifted, missing], &store, i64::MAX).unwrap();
+ assert!(
+ out.results.is_empty(),
+ "drift and missing rows both skip cleanly"
+ );
+ assert_eq!(
+ out.drops,
+ vec![SweepDropReason::LeafDrift, SweepDropReason::MissingState],
+ "the drifted key drops as leaf drift, the absent key as missing state",
+ );
+ }
+
+ #[test]
+ fn evicts_multiple_keys_in_one_pass() {
+ let (_dir, store) = temp_store();
+ let filters = freeze(vec![single_leaf(7)]);
+ let keys: Vec<Stage1Key> = (1..=3).map(|p| key_for(&filters, p)).collect();
+ for key in &keys {
+ write(
+ &store,
+ key,
+ Stage1State::BehavioralSingle {
+ has_match: true,
+ last_event_at_ms: 1_000,
+ earliest_eviction_at_ms: 2_000,
+ },
+ );
+ }
+ let results = sweep_evict(&filters, &keys, &store, 10_000)
+ .unwrap()
+ .results;
+ assert_eq!(results.len(), 3, "every member key evicts to a Left+Delete");
+ assert!(results
+ .iter()
+ .all(|r| r.action == EvictionAction::Delete && r.transition.is_some()));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
new file mode 100644
index 000000000000..1df5e0ab921d
--- /dev/null
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -0,0 +1,1653 @@
+//! Per-partition Stage 1 worker.
+//!
+//! [`Stage1Worker::spawn`] drains one partition's channel on a dedicated tokio task. Per sub-batch
+//! it produces membership changes and straggler re-keys, awaits all acks, then marks the offset
+//! processed. A produce failure holds the offset; a store error is logged and the event is skipped.
+
+use std::borrow::Cow;
+use std::collections::BTreeMap;
+use std::sync::Arc;
+use std::time::Instant;
+
+use metrics::{counter, histogram};
+use tokio::sync::mpsc;
+use tokio::task::JoinHandle;
+use tracing::{info, warn};
+use uuid::Uuid;
+
+use crate::cascade::{first_cascade, CascadeMessage};
+use crate::consumers::events::CohortStreamEvent;
+use crate::filters::manager::CatalogHandle;
+use crate::filters::reverse_index::TeamFilters;
+use crate::filters::TeamId;
+use crate::merge::tombstone_redirect::{self, Resolution};
+use crate::observability::metrics::{
+ CASCADE_PRODUCE_ERRORS_TOTAL, COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH,
+ EVICTION_QUEUE_REBUILT_KEYS_TOTAL, MERGE_REDIRECT_HOP_CAPPED_TOTAL,
+ MERGE_REKEY_PRODUCE_FAILURE_TOTAL, OUTPUT_MEMBERSHIP_CHANGES_EMITTED, OUTPUT_PRODUCE_ERRORS,
+ STAGE1_EVENTS_PROCESSED, STAGE1_EVENTS_SKIPPED, STAGE1_EVENT_PROCESS_DURATION,
+ STAGE1_STATE_DECODE_ERROR, STAGE1_TRANSITIONS, SWEEP_KEYS_DROPPED_TOTAL,
+ SWEEP_KEYS_EVICTED_TOTAL,
+};
+use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};
+use crate::partitions::shuffle_message::ShuffleMessage;
+use crate::producer::{
+ map_transition, now_last_updated, CohortMembershipChange, MembershipSink, MembershipStatus,
+ OutputBuffer,
+};
+use crate::stage1::key::Stage1Key;
+use crate::stage1::state::{StateVariant, StatefulRecord};
+use crate::stage1::transition::{LeafTransition, TransitionKind};
+use crate::store::{CohortStore, IndexOp, PersonIndexKey};
+use crate::sweep::EvictionQueue;
+use crate::workers::cascade_path::handle_cascade;
+use crate::workers::event_path::{process_event, schedule_deadline, SkipReason};
+use crate::workers::merge_gc::{handle_merge_gc, MergeGcCursor};
+use crate::workers::merge_path::{handle_apply, handle_merge, handle_redrive, MergeWorkerDeps};
+use crate::workers::stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};
+use crate::workers::stage2_path::compose_stage2;
+use crate::workers::sweep_callback::{sweep_evict, EvictionAction, SweepDropReason};
+
+/// Max eviction keys a single sweep pass drains. Daily-bucket deadlines cluster on tz-midnight, so a
+/// large team's whole wave can come due on one tick; capping the pop loop bounds the per-pass RocksDB
+/// read + produce + write batch + Stage 2 pass so events do not queue behind one giant sweep. Leftover
+/// due keys stay scheduled and drain on the next sweep tick.
+const MAX_SWEEP_KEYS_PER_PASS: usize = 10_000;
+
+const REBUILD_SCAN_PAGE: usize = 10_000;
+
+pub struct Stage1Worker {
+ partition_id: u16,
+ handle: JoinHandle<()>,
+}
+
+impl Stage1Worker {
+ /// When `durable_restore` is on, re-seeds the `EvictionQueue` from `cf_stage1` on spawn so a
+ /// dormant person's `Left` still fires after a crash-restart.
+ #[allow(clippy::too_many_arguments)]
+ pub fn spawn(
+ partition_id: u16,
+ receiver: mpsc::Receiver<Vec<ShuffleMessage>>,
+ store: CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: Arc<dyn MembershipSink>,
+ tracker: Arc<OffsetTracker>,
+ merge: Arc<MergeWorkerDeps>,
+ durable_restore: bool,
+ ) -> Self {
+ let handle = tokio::spawn(run_worker(
+ partition_id,
+ receiver,
+ store,
+ catalog,
+ sink,
+ tracker,
+ merge,
+ durable_restore,
+ ));
+ Self {
+ partition_id,
+ handle,
+ }
+ }
+
+ pub fn partition_id(&self) -> u16 {
+ self.partition_id
+ }
+
+ pub async fn join(self) -> Result<(), tokio::task::JoinError> {
+ self.handle.await
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn run_worker(
+ partition_id: u16,
+ mut receiver: mpsc::Receiver<Vec<ShuffleMessage>>,
+ store: CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: Arc<dyn MembershipSink>,
+ tracker: Arc<OffsetTracker>,
+ merge: Arc<MergeWorkerDeps>,
+ durable_restore: bool,
+) {
+ info!(partition_id, "stage 1 worker started");
+
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ // No-op for a cold partition (bloom-filtered scan finds nothing to schedule).
+ if durable_restore {
+ rebuild_eviction_queue(partition_id, &store, &mut queue);
+ }
+ // In-memory resume cursors; loss on rebalance is benign (GC re-scans from the start).
+ let mut gc_cursor = MergeGcCursor::default();
+ let mut stage2_gc_cursor = Stage2GcCursor::default();
+
+ while let Some(batch) = receiver.recv().await {
+ let last_updated = now_last_updated();
+ let mut buffer = OutputBuffer::new();
+ let mut re_keys: Vec<CohortStreamEvent> = Vec::new();
+ let mut max_offset: Option<i64> = None;
+ // Set when a pre-arm flush fails: holds the whole batch's offset so Kafka replays it.
+ let mut held = false;
+
+ for message in batch {
+ match message {
+ ShuffleMessage::Event { event, cse_offset } => {
+ max_offset =
+ Some(max_offset.map_or(cse_offset, |current| current.max(cse_offset)));
+ let effects = handle_event(
+ partition_id,
+ &store,
+ &catalog,
+ &event,
+ &last_updated,
+ merge.partition_count,
+ );
+ buffer.extend(effects.changes);
+ for (key, deadline) in effects.schedules {
+ queue.schedule(key, deadline);
+ }
+ re_keys.extend(effects.re_keys);
+ }
+ ShuffleMessage::Sweep { due_before_ms } => {
+ if flush_event_changes_before_inline(
+ &sink,
+ &mut buffer,
+ partition_id,
+ &mut held,
+ )
+ .await
+ {
+ break;
+ }
+ handle_sweep(
+ partition_id,
+ &store,
+ &catalog,
+ &sink,
+ &merge,
+ &mut queue,
+ &last_updated,
+ due_before_ms,
+ )
+ .await;
+ }
+ ShuffleMessage::Merge { event, offset } => {
+ if flush_event_changes_before_inline(
+ &sink,
+ &mut buffer,
+ partition_id,
+ &mut held,
+ )
+ .await
+ {
+ break;
+ }
+ handle_merge(
+ partition_id,
+ &store,
+ &catalog,
+ &sink,
+ &merge,
+ &mut queue,
+ &last_updated,
+ &event,
+ offset,
+ )
+ .await;
+ }
+ ShuffleMessage::Transfer { transfer, offset } => {
+ if flush_event_changes_before_inline(
+ &sink,
+ &mut buffer,
+ partition_id,
+ &mut held,
+ )
+ .await
+ {
+ break;
+ }
+ handle_apply(
+ partition_id,
+ &store,
+ &catalog,
+ &sink,
+ &merge,
+ &mut queue,
+ &last_updated,
+ &transfer,
+ offset,
+ )
+ .await;
+ }
+ ShuffleMessage::Cascade { message, offset } => {
+ if flush_event_changes_before_inline(
+ &sink,
+ &mut buffer,
+ partition_id,
+ &mut held,
+ )
+ .await
+ {
+ break;
+ }
+ handle_cascade(
+ partition_id,
+ &store,
+ &catalog,
+ &sink,
+ &merge,
+ &last_updated,
+ &message,
+ offset,
+ )
+ .await;
+ }
+ ShuffleMessage::RedrivePendingTransfers => {
+ handle_redrive(partition_id, &store, &merge).await;
+ }
+ ShuffleMessage::MergeCfGc {
+ marker_cutoff_ms,
+ tombstone_cutoff_ms,
+ } => {
+ handle_merge_gc(
+ partition_id,
+ &store,
+ &mut gc_cursor,
+ marker_cutoff_ms,
+ tombstone_cutoff_ms,
+ merge.gc_scan_limit,
+ );
+ if merge.stage2_orphan_gc_enabled {
+ handle_stage2_orphan_gc(
+ partition_id,
+ &store,
+ &catalog,
+ &mut stage2_gc_cursor,
+ merge.gc_scan_limit,
+ );
+ }
+ }
+ }
+ }
+
+ if held {
+ continue;
+ }
+
+ if !buffer.is_empty() {
+ let changes = buffer.take();
+ // Build cascades from a borrow before `changes` is moved into produce; gate-off allocates nothing.
+ let cascades = first_cascades(&merge, &changes, max_offset.unwrap_or(0));
+ let errors = produce_membership(&sink, changes).await;
+ if errors > 0 {
+ warn!(
+ partition_id,
+ errors,
+ "produce to cohort_membership_changed_shadow failed; holding offset for replay",
+ );
+ continue;
+ }
+ let cascade_errors = produce_cascades(&merge, cascades).await;
+ if cascade_errors > 0 {
+ warn!(
+ partition_id,
+ errors = cascade_errors,
+ "produce to cohort_cascade_events failed; holding offset for replay",
+ );
+ continue;
+ }
+ }
+
+ if !re_keys.is_empty() {
+ let produced = re_keys.len() as u64;
+ let acks = merge.stream_event_sink.produce(re_keys).await;
+ let errors = acks.iter().filter(|result| result.is_err()).count();
+ if errors > 0 {
+ counter!(MERGE_REKEY_PRODUCE_FAILURE_TOTAL).increment(errors as u64);
+ warn!(
+ partition_id,
+ errors,
+ "straggler re-key produce to cohort_stream_events failed; holding offset for replay",
+ );
+ continue;
+ }
+ tombstone_redirect::record_re_keyed(produced);
+ }
+
+ if let Some(max_offset) = max_offset {
+ if let MarkOutcome::CappedAheadOfDispatch =
+ tracker.mark_processed(partition_id as i32, max_offset + 1)
+ {
+ counter!(COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH).increment(1);
+ warn!(
+ partition_id,
+ next_offset = max_offset + 1,
+ "offset mark exceeded the dispatch ceiling and was capped (F1 invariant violation)",
+ );
+ }
+ }
+ }
+
+ info!(partition_id, "stage 1 worker stopped");
+}
+
+/// Flush buffered event-path changes so they land before an inline (sweep/merge/transfer) produce,
+/// preserving produce order == state-commit order. No-op when the buffer is empty.
+/// Returns the failed-ack count (`0` = fully acked / empty).
+async fn flush_membership_buffer(
+ sink: &Arc<dyn MembershipSink>,
+ buffer: &mut OutputBuffer,
+) -> usize {
+ if buffer.is_empty() {
+ return 0;
+ }
+ produce_membership(sink, buffer.take()).await
+}
+
+/// Flush buffered event-path changes ahead of an inline arm. Returns `true` when the flush failed:
+/// sets `held` so the caller `break`s and `mark_processed` is skipped, causing Kafka to replay.
+/// Returns `false` (empty or all acked) to run the arm normally.
+async fn flush_event_changes_before_inline(
+ sink: &Arc<dyn MembershipSink>,
+ buffer: &mut OutputBuffer,
+ partition_id: u16,
+ held: &mut bool,
+) -> bool {
+ let errors = flush_membership_buffer(sink, buffer).await;
+ if errors > 0 {
+ *held = true;
+ warn!(
+ partition_id,
+ errors, "produce to cohort_membership_changed_shadow failed; holding offset for replay",
+ );
+ return true;
+ }
+ false
+}
+
+pub(crate) fn count_by_status(changes: &[CohortMembershipChange]) -> (u64, u64) {
+ changes
+ .iter()
+ .fold((0, 0), |(entered, left), change| match change.status {
+ MembershipStatus::Entered => (entered + 1, left),
+ MembershipStatus::Left => (entered, left + 1),
+ })
+}
+
+/// Produce membership `changes`, await acks, and record metrics. Returns the failed-ack count
+/// (`0` = fully acked). The caller owns the per-site warn and recovery action.
+pub(crate) async fn produce_membership(
+ sink: &Arc<dyn MembershipSink>,
+ changes: Vec<CohortMembershipChange>,
+) -> usize {
+ let (entered, left) = count_by_status(&changes);
+ let acks = sink.produce(changes).await;
+ let errors = acks.iter().filter(|result| result.is_err()).count();
+ if errors > 0 {
+ counter!(OUTPUT_PRODUCE_ERRORS).increment(errors as u64);
+ return errors;
+ }
+ if entered > 0 {
+ counter!(OUTPUT_MEMBERSHIP_CHANGES_EMITTED, "status" => MembershipStatus::Entered.as_str())
+ .increment(entered);
+ }
+ if left > 0 {
+ counter!(OUTPUT_MEMBERSHIP_CHANGES_EMITTED, "status" => MembershipStatus::Left.as_str())
+ .increment(left);
+ }
+ 0
+}
+
+/// Build the first-hop cascade messages for each membership change. Empty when the gate is off or
+/// the slice is empty, so the off path allocates nothing. Must be called before `changes` is moved
+/// into `produce_membership`. `source_offset` is informational only.
+pub(crate) fn first_cascades(
+ merge: &MergeWorkerDeps,
+ changes: &[CohortMembershipChange],
+ source_offset: i64,
+) -> Vec<CascadeMessage> {
+ if !merge.cascade.enabled || changes.is_empty() {
+ return Vec::new();
+ }
+ changes
+ .iter()
+ .map(|change| first_cascade(change.clone(), source_offset))
+ .collect()
+}
+
+/// Produce cascade messages and await acks. Returns the failed-ack count (`0` when empty or fully
+/// acked). The caller owns the recovery posture: the event path holds the offset; the sweep/merge
+/// paths drop (at-most-once). Shared by the first-hop leg and onward-hop consumer legs.
+pub(crate) async fn produce_cascades(
+ merge: &MergeWorkerDeps,
+ cascades: Vec<CascadeMessage>,
+) -> usize {
+ if cascades.is_empty() {
+ return 0;
+ }
+ let acks = merge.cascade_sink.produce(cascades).await;
+ let errors = acks.iter().filter(|result| result.is_err()).count();
+ if errors > 0 {
+ counter!(CASCADE_PRODUCE_ERRORS_TOTAL).increment(errors as u64);
+ }
+ errors
+}
+
+#[derive(Default)]
+struct EventEffects {
+ changes: Vec<CohortMembershipChange>,
+ schedules: Vec<(Stage1Key, i64)>,
+ re_keys: Vec<CohortStreamEvent>,
+}
+
+fn handle_event(
+ partition_id: u16,
+ store: &CohortStore,
+ catalog: &CatalogHandle,
+ event: &CohortStreamEvent,
+ last_updated: &str,
+ partition_count: u32,
+) -> EventEffects {
+ let snapshot = catalog.load();
+ let Some(team_filters) = snapshot.team(TeamId(event.team_id)) else {
+ counter!(STAGE1_EVENTS_SKIPPED, "reason" => SkipReason::NoTeamFilters.as_str())
+ .increment(1);
+ return EventEffects::default();
+ };
+ let filters: &TeamFilters = team_filters;
+
+ let resolved: Cow<'_, CohortStreamEvent> =
+ match redirect_for_tombstone(partition_id, store, event, partition_count) {
+ Redirected::Process(event) => event,
+ Redirected::ReKey(re_keyed) => {
+ return EventEffects {
+ re_keys: vec![re_keyed],
+ ..EventEffects::default()
+ }
+ }
+ };
+
+ let started = Instant::now();
+ let result = process_event(partition_id, store, filters, &resolved);
+ histogram!(STAGE1_EVENT_PROCESS_DURATION).record(started.elapsed().as_secs_f64());
+
+ match result {
+ Ok(outcome) => {
+ if let Some(reason) = outcome.skipped {
+ counter!(STAGE1_EVENTS_SKIPPED, "reason" => reason.as_str()).increment(1);
+ return EventEffects::default();
+ }
+ counter!(STAGE1_EVENTS_PROCESSED).increment(1);
+ let mut changes = Vec::new();
+ for transition in &outcome.transitions {
+ if let Some(kind) = transition_metric_label(filters, transition) {
+ counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);
+ }
+ changes.extend(map_transition(filters, transition, last_updated));
+ }
+ match compose_stage2(
+ partition_id,
+ store,
+ filters,
+ &outcome.transitions,
+ outcome.event_ms,
+ last_updated,
+ ) {
+ Ok(stage2_changes) => changes.extend(stage2_changes),
+ Err(error) => warn!(
+ partition_id,
+ team_id = event.team_id,
+ error = %error,
+ "stage 2 composition failed; skipping (self-heals on the person's next event)",
+ ),
+ }
+ EventEffects {
+ changes,
+ schedules: outcome.schedules,
+ re_keys: Vec::new(),
+ }
+ }
+ Err(error) => {
+ counter!(STAGE1_EVENTS_SKIPPED, "reason" => "store_error").increment(1);
+ warn!(
+ partition_id,
+ team_id = event.team_id,
+ error = %error,
+ "stage 1 store error; skipping event without holding the offset",
+ );
+ EventEffects::default()
+ }
+ }
+}
+
+enum Redirected<'a> {
+ Process(Cow<'a, CohortStreamEvent>),
+ ReKey(CohortStreamEvent),
+}
+
+fn redirect_for_tombstone<'a>(
+ partition_id: u16,
+ store: &CohortStore,
+ event: &'a CohortStreamEvent,
+ partition_count: u32,
+) -> Redirected<'a> {
+ let Ok(person_id) = Uuid::parse_str(&event.person_id) else {
+ return Redirected::Process(Cow::Borrowed(event));
+ };
+ let resolution = match tombstone_redirect::resolve(
+ store,
+ partition_id,
+ TeamId(event.team_id),
+ person_id,
+ partition_count,
+ ) {
+ Ok(resolution) => resolution,
+ Err(error) => {
+ warn!(
+ partition_id,
+ team_id = event.team_id,
+ error = %error,
+ "tombstone preflight read failed; processing without redirect",
+ );
+ return Redirected::Process(Cow::Borrowed(event));
+ }
+ };
+ tombstone_redirect::record_redirect(&resolution);
+ match resolution {
+ Resolution::NotMerged => Redirected::Process(Cow::Borrowed(event)),
+ Resolution::Inline {
+ final_person,
+ origin,
+ } => Redirected::Process(Cow::Owned(rewrite_to(event, final_person, origin))),
+ Resolution::CrossPartition {
+ target_person,
+ origin,
+ } => {
+ if event.redirect_hops >= tombstone_redirect::MAX_CROSS_PARTITION_REDIRECT_HOPS {
+ counter!(MERGE_REDIRECT_HOP_CAPPED_TOTAL).increment(1);
+ warn!(
+ partition_id,
+ team_id = event.team_id,
+ %target_person,
+ %origin,
+ hops = event.redirect_hops,
+ "cross-partition redirect hop cap hit (corrupt tombstone cycle?); processing inline at the best-known target",
+ );
+ return Redirected::Process(Cow::Owned(rewrite_to(event, target_person, origin)));
+ }
+ let mut re_keyed = rewrite_to(event, target_person, origin);
+ re_keyed.redirect_hops += 1;
+ Redirected::ReKey(re_keyed)
+ }
+ }
+}
+
+fn rewrite_to(event: &CohortStreamEvent, final_person: Uuid, origin: Uuid) -> CohortStreamEvent {
+ CohortStreamEvent {
+ person_id: final_person.to_string(),
+ redirected_from: event
+ .redirected_from
+ .clone()
+ .or_else(|| Some(origin.to_string())),
+ ..event.clone()
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn handle_sweep(
+ partition_id: u16,
+ store: &CohortStore,
+ catalog: &CatalogHandle,
+ sink: &Arc<dyn MembershipSink>,
+ merge: &MergeWorkerDeps,
+ queue: &mut EvictionQueue<Stage1Key>,
+ last_updated: &str,
+ due_before_ms: i64,
+) {
+ let mut popped: Vec<(Stage1Key, i64)> = Vec::new();
+ while popped.len() < MAX_SWEEP_KEYS_PER_PASS {
+ let Some(entry) = queue.pop_due(due_before_ms) else {
+ break;
+ };
+ popped.push(entry);
+ }
+ if popped.is_empty() {
+ return;
+ }
+
+ let mut by_team: BTreeMap<u64, Vec<Stage1Key>> = BTreeMap::new();
+ for &(key, _) in &popped {
+ by_team.entry(key.team_id).or_default().push(key);
+ }
+
+ let snapshot = catalog.load();
+ let mut changes = Vec::new();
+ let mut results = Vec::new();
+ let mut drops: Vec<SweepDropReason> = Vec::new();
+ for (team_id, keys) in &by_team {
+ let Some(filters) = snapshot.team(TeamId(*team_id as i32)) else {
+ drops.extend(std::iter::repeat_n(SweepDropReason::TeamDrift, keys.len()));
+ continue;
+ };
+ let filters: &TeamFilters = filters;
+ match sweep_evict(filters, keys, store, due_before_ms) {
+ Ok(evictions) => {
+ for result in &evictions.results {
+ if let Some(transition) = &result.transition {
+ if let Some(kind) = transition_metric_label(filters, transition) {
+ counter!(STAGE1_TRANSITIONS, "kind" => kind).increment(1);
+ }
+ changes.extend(map_transition(filters, transition, last_updated));
+ }
+ }
+ results.extend(evictions.results);
+ drops.extend(evictions.drops);
+ }
+ Err(error) => {
+ warn!(
+ partition_id,
+ team_id,
+ error = %error,
+ "sweep state read failed; rescheduling the team's keys for retry",
+ );
+ reschedule_team(queue, &popped, *team_id);
+ }
+ }
+ }
+
+ if !changes.is_empty() {
+ let errors = produce_membership(sink, changes).await;
+ if errors > 0 {
+ warn!(
+ partition_id,
+ errors,
+ "sweep produce to cohort_membership_changed_shadow failed; rescheduling for replay",
+ );
+ reschedule_all(queue, &popped);
+ return;
+ }
+ }
+
+ if !results.is_empty() {
+ let written = store.write_batch(|batch| {
+ for result in &results {
+ match &result.action {
+ EvictionAction::Write(bytes) => batch.put_stage1(&result.key, bytes),
+ EvictionAction::Delete => {
+ batch.delete_stage1(&result.key);
+ batch.merge_person_index(
+ &PersonIndexKey {
+ partition_id: result.key.partition_id,
+ team_id: result.key.team_id,
+ person_id: result.key.person_id,
+ },
+ IndexOp::Remove(result.key.leaf_state_key),
+ );
+ }
+ }
+ }
+ });
+ if let Err(error) = written {
+ warn!(
+ partition_id,
+ error = %error,
+ "sweep state write failed; rescheduling popped keys to retry the eviction",
+ );
+ reschedule_all(queue, &popped);
+ return;
+ }
+
+ for result in &results {
+ if let Some(deadline) = result.reschedule {
+ queue.schedule(result.key, deadline);
+ }
+ counter!(SWEEP_KEYS_EVICTED_TOTAL, "variant" => result.variant.as_str()).increment(1);
+ }
+ }
+
+ for reason in &drops {
+ counter!(SWEEP_KEYS_DROPPED_TOTAL, "reason" => reason.as_str()).increment(1);
+ }
+
+ let mut by_team_transitions: BTreeMap<u64, Vec<LeafTransition>> = BTreeMap::new();
+ for result in &results {
+ if let Some(transition) = &result.transition {
+ by_team_transitions
+ .entry(result.key.team_id)
+ .or_default()
+ .push(transition.clone());
+ }
+ }
+ let mut stage2_changes = Vec::new();
+ for (team_id, transitions) in &by_team_transitions {
+ let Some(filters) = snapshot.team(TeamId(*team_id as i32)) else {
+ continue;
+ };
+ let filters: &TeamFilters = filters;
+ match compose_stage2(
+ partition_id,
+ store,
+ filters,
+ transitions,
+ due_before_ms,
+ last_updated,
+ ) {
+ Ok(changes) => stage2_changes.extend(changes),
+ Err(error) => warn!(
+ partition_id,
+ team_id,
+ error = %error,
+ "sweep stage 2 composition failed; skipping (self-heals on the person's next event)",
+ ),
+ }
+ }
+ if stage2_changes.is_empty() {
+ return;
+ }
+
+ // Only Stage 2 membership changes cascade; single-leaf evictions self-heal on the referrer's next event.
+ let cascades = first_cascades(merge, &stage2_changes, 0);
+ let errors = produce_membership(sink, stage2_changes).await;
+ if errors > 0 {
+ warn!(
+ partition_id,
+ errors,
+ "sweep stage 2 produce to cohort_membership_changed_shadow failed; dropping (cf_stage2 already committed, at-most-once)",
+ );
+ return;
+ }
+ let cascade_errors = produce_cascades(merge, cascades).await;
+ if cascade_errors > 0 {
+ warn!(
+ partition_id,
+ errors = cascade_errors,
+ "sweep cascade produce failed; dropping (at-most-once). Recovery depends on each referrer being re-evaluated on its next event; the sweep does not re-evaluate cohort-ref shapes with no behavioral leaf",
+ );
+ }
+}
+
+/// Re-seed the per-worker [`EvictionQueue`] from `cf_stage1`, scheduling every behavioral key on its
+/// stored deadline. Skips `PersonProperty` variants (no time-based eviction) and `i64::MAX` deadlines
+/// (permanent). Corrupt records are counted and skipped — the event path re-derives them. A scan error
+/// stops early; new events reschedule any missing keys.
+fn rebuild_eviction_queue(
+ partition_id: u16,
+ store: &CohortStore,
+ queue: &mut EvictionQueue<Stage1Key>,
+) {
+ let mut cursor: Option<Vec<u8>> = None;
+ let mut rebuilt: u64 = 0;
+ loop {
+ let page = match store.scan_stage1(partition_id, cursor.as_deref(), REBUILD_SCAN_PAGE) {
+ Ok(page) => page,
+ Err(err) => {
+ warn!(
+ partition_id,
+ error = %err,
+ "durable restore: cf_stage1 scan failed; eviction queue may be incomplete",
+ );
+ break;
+ }
+ };
+ let page_len = page.len();
+ let next_cursor = page.last().map(|(k, _)| k.encode().to_vec());
+ for (key, value) in page {
+ match StatefulRecord::decode(&value) {
+ // Use the same scheduling policy as the event path to prevent drift.
+ Ok(record) => {
+ if let Some(deadline) = schedule_deadline(&record.state) {
+ queue.schedule(key, deadline);
+ rebuilt += 1;
+ }
+ }
+ Err(_) => counter!(STAGE1_STATE_DECODE_ERROR).increment(1),
+ }
+ }
+ cursor = next_cursor;
+ if page_len < REBUILD_SCAN_PAGE {
+ break;
+ }
+ }
+ if rebuilt > 0 {
+ counter!(EVICTION_QUEUE_REBUILT_KEYS_TOTAL, "partition" => partition_id.to_string())
+ .increment(rebuilt);
+ info!(
+ partition_id,
+ rebuilt, "durable restore: re-seeded eviction queue from cf_stage1",
+ );
+ }
+}
+
+fn reschedule_all(queue: &mut EvictionQueue<Stage1Key>, popped: &[(Stage1Key, i64)]) {
+ for &(key, deadline) in popped {
+ queue.schedule(key, deadline);
+ }
+}
+
+fn reschedule_team(
+ queue: &mut EvictionQueue<Stage1Key>,
+ popped: &[(Stage1Key, i64)],
+ team_id: u64,
+) {
+ for &(key, deadline) in popped {
+ if key.team_id == team_id {
+ queue.schedule(key, deadline);
+ }
+ }
+}
+
+pub(crate) fn transition_metric_label(
+ filters: &TeamFilters,
+ transition: &LeafTransition,
+) -> Option<&'static str> {
+ let variant = filters.by_lsk.get(&transition.leaf_state_key)?.variant;
+ match (variant, transition.kind) {
+ (StateVariant::BehavioralSingle, TransitionKind::Entered) => Some("behavioral_entered"),
+ (StateVariant::BehavioralSingle, TransitionKind::Left) => Some("behavioral_left"),
+ (StateVariant::BehavioralDailyBuckets, TransitionKind::Entered) => {
+ Some("behavioral_daily_entered")
+ }
+ (StateVariant::BehavioralDailyBuckets, TransitionKind::Left) => {
+ Some("behavioral_daily_left")
+ }
+ (StateVariant::BehavioralCompressedHistory, TransitionKind::Entered) => {
+ Some("behavioral_compressed_entered")
+ }
+ (StateVariant::BehavioralCompressedHistory, TransitionKind::Left) => {
+ Some("behavioral_compressed_left")
+ }
+ (StateVariant::PersonProperty, TransitionKind::Entered) => Some("person_entered"),
+ (StateVariant::PersonProperty, TransitionKind::Left) => Some("person_left"),
+ }
+}
+
+#[cfg(test)]
+mod tombstone_redirect_tests {
+ use super::*;
+ use chrono_tz::UTC;
+ use serde_json::json;
+ use tempfile::TempDir;
+
+ use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder};
+ use crate::merge::transfer::Tombstone;
+ use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};
+ use crate::producer::{
+ CaptureCascadeSink, CaptureSink, CaptureStreamEventSink, CaptureTransferSink,
+ };
+ use crate::stage1::key::LeafStateKey;
+ use crate::stage1::state::{AppliedOffsets, Stage1State, StatefulRecord};
+ use crate::stage2::state::Stage2State;
+ use crate::store::{Stage2Key, StoreConfig, TombstoneKey};
+ use crate::workers::merge_path::TransferRetryPolicy;
+ use crate::workers::CascadeConfig;
+
+ const TEAM: i32 = 7;
+ const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
+
+ fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ (dir, store)
+ }
+
+ fn person_catalog() -> Arc<CatalogHandle> {
+ let leaf = json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ });
+ let cohort = json!({ "properties": { "type": "AND", "values": [leaf] } });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(TEAM), &cohort)
+ .unwrap();
+ Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ builder.freeze(UTC),
+ )])))
+ }
+
+ fn applied(entries: &[(i32, i64)]) -> AppliedOffsets {
+ let mut applied = AppliedOffsets::default();
+ for &(partition, offset) in entries {
+ applied.record(partition, offset);
+ }
+ applied
+ }
+
+ fn person_event(
+ person: Uuid,
+ email: &str,
+ source_partition: i32,
+ source_offset: i64,
+ ) -> CohortStreamEvent {
+ CohortStreamEvent {
+ team_id: TEAM,
+ person_id: person.to_string(),
+ distinct_id: "d".to_string(),
+ uuid: "u".to_string(),
+ event: "$pageview".to_string(),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ properties: Some("{}".to_string()),
+ person_properties: Some(format!(r#"{{"email":"{email}"}}"#)),
+ elements_chain: None,
+ source_offset,
+ source_partition,
+ redirected_from: None,
+ redirect_hops: 0,
+ }
+ }
+
+ fn cross_partition_pair() -> (Uuid, u16, Uuid) {
+ let p_old = Uuid::from_u128(1);
+ let partition_id = partition_of(TeamId(TEAM), &p_old, COHORT_PARTITION_COUNT) as u16;
+ let p_new = (10u128..)
+ .map(Uuid::from_u128)
+ .find(|p| partition_of(TeamId(TEAM), p, COHORT_PARTITION_COUNT) as u16 != partition_id)
+ .expect("some uuid hashes off p_old's partition");
+ (p_old, partition_id, p_new)
+ }
+
+ fn merge_deps_with(stream_sink: CaptureStreamEventSink) -> Arc<MergeWorkerDeps> {
+ Arc::new(MergeWorkerDeps {
+ transfer_sink: Arc::new(CaptureTransferSink::new()),
+ stream_event_sink: Arc::new(stream_sink),
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: crate::workers::DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink: Arc::new(crate::producer::CaptureCascadeSink::new()),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: crate::workers::CascadeConfig::default(),
+ partition_count: COHORT_PARTITION_COUNT,
+ })
+ }
+
+ /// Deps with the `stage2_orphan_gc_enabled` kill-switch set to `stage2_orphan_gc_enabled`.
+ fn merge_deps_stage2_gc(stage2_orphan_gc_enabled: bool) -> Arc<MergeWorkerDeps> {
+ Arc::new(MergeWorkerDeps {
+ transfer_sink: Arc::new(CaptureTransferSink::new()),
+ stream_event_sink: Arc::new(CaptureStreamEventSink::new()),
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: crate::workers::DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled,
+ cascade_sink: Arc::new(crate::producer::CaptureCascadeSink::new()),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: crate::workers::CascadeConfig::default(),
+ partition_count: COHORT_PARTITION_COUNT,
+ })
+ }
+
+ /// Deps with a captured cascade sink and the cascade gate set to `enabled`.
+ fn merge_deps_cascade(cascade_sink: CaptureCascadeSink, enabled: bool) -> Arc<MergeWorkerDeps> {
+ Arc::new(MergeWorkerDeps {
+ transfer_sink: Arc::new(CaptureTransferSink::new()),
+ stream_event_sink: Arc::new(CaptureStreamEventSink::new()),
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: crate::workers::DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink: Arc::new(cascade_sink),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: CascadeConfig {
+ enabled,
+ depth_cap: 8,
+ fanout_cap: 1000,
+ },
+ partition_count: COHORT_PARTITION_COUNT,
+ })
+ }
+
+ /// Run one event that flips cohort 1 through a worker, returning the partition and its tracker.
+ async fn run_flip(
+ store: &CohortStore,
+ merge: Arc<MergeWorkerDeps>,
+ membership: &CaptureSink,
+ person: Uuid,
+ ) -> (u16, Arc<OffsetTracker>) {
+ let partition_id = partition_of(TeamId(TEAM), &person, COHORT_PARTITION_COUNT) as u16;
+ let tracker = Arc::new(OffsetTracker::new());
+ run_batch(
+ partition_id,
+ store,
+ person_catalog(),
+ membership,
+ &tracker,
+ merge,
+ 1,
+ vec![ShuffleMessage::Event {
+ event: person_event(person, "[email protected]", 5, 0),
+ cse_offset: 0,
+ }],
+ )
+ .await;
+ (partition_id, tracker)
+ }
+
+ #[tokio::test]
+ async fn event_flip_with_cascade_on_produces_a_depth_one_first_cascade() {
+ let (_dir, store) = temp_store();
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (partition_id, tracker) = run_flip(
+ &store,
+ merge_deps_cascade(cascade.clone(), true),
+ &membership,
+ Uuid::from_u128(0x5A1CE),
+ )
+ .await;
+
+ assert_eq!(membership.changes().len(), 1, "alice entered cohort 1");
+ let cascades = cascade.messages();
+ assert_eq!(cascades.len(), 1, "one first-hop cascade for the flip");
+ assert_eq!(cascades[0].change.cohort_id, 1);
+ assert_eq!(cascades[0].depth, 1);
+ assert_eq!(cascades[0].cascade_chain, vec![1]);
+ assert_eq!(cascades[0].originating_cohort_id, 1);
+ assert_eq!(
+ tracker.committable_offsets().get(&(partition_id as i32)),
+ Some(&1),
+ "the acked two-topic produce releases the events offset",
+ );
+ }
+
+ #[tokio::test]
+ async fn event_flip_with_cascade_off_produces_no_cascade() {
+ let (_dir, store) = temp_store();
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::new();
+ let (partition_id, tracker) = run_flip(
+ &store,
+ merge_deps_cascade(cascade.clone(), false),
+ &membership,
+ Uuid::from_u128(0x5A1CF),
+ )
+ .await;
+
+ assert_eq!(
+ membership.changes().len(),
+ 1,
+ "the flip still emits membership"
+ );
+ assert!(
+ cascade.messages().is_empty(),
+ "gate off: no cascade produced"
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&(partition_id as i32)),
+ Some(&1),
+ );
+ }
+
+ #[tokio::test]
+ async fn cascade_produce_failure_holds_the_events_batch() {
+ let (_dir, store) = temp_store();
+ let membership = CaptureSink::new();
+ let cascade = CaptureCascadeSink::failing_always();
+ let (partition_id, tracker) = run_flip(
+ &store,
+ merge_deps_cascade(cascade.clone(), true),
+ &membership,
+ Uuid::from_u128(0x5A1D0),
+ )
+ .await;
+
+ assert_eq!(
+ membership.changes().len(),
+ 1,
+ "membership is the first leg and acked before the cascade leg",
+ );
+ assert!(cascade.messages().is_empty(), "the cascade produce failed");
+ assert_eq!(
+ tracker.committable_offsets().get(&(partition_id as i32)),
+ None,
+ "a failed cascade produce holds the events offset for replay",
+ );
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ async fn run_batch(
+ partition_id: u16,
+ store: &CohortStore,
+ catalog: Arc<CatalogHandle>,
+ membership: &CaptureSink,
+ tracker: &Arc<OffsetTracker>,
+ merge: Arc<MergeWorkerDeps>,
+ dispatched: i64,
+ batch: Vec<ShuffleMessage>,
+ ) {
+ let (tx, rx) = mpsc::channel(4);
+ let worker = Stage1Worker::spawn(
+ partition_id,
+ rx,
+ store.clone(),
+ catalog,
+ Arc::new(membership.clone()),
+ tracker.clone(),
+ merge,
+ false,
+ );
+ tracker.mark_dispatched(partition_id as i32, dispatched);
+ tx.send(batch).await.unwrap();
+ drop(tx);
+ worker.join().await.unwrap();
+ }
+
+ async fn run_one_straggler(
+ partition_id: u16,
+ store: &CohortStore,
+ catalog: Arc<CatalogHandle>,
+ membership: &CaptureSink,
+ tracker: &Arc<OffsetTracker>,
+ merge: Arc<MergeWorkerDeps>,
+ event: CohortStreamEvent,
+ ) {
+ run_batch(
+ partition_id,
+ store,
+ catalog,
+ membership,
+ tracker,
+ merge,
+ 1,
+ vec![ShuffleMessage::Event {
+ event,
+ cse_offset: 0,
+ }],
+ )
+ .await;
+ }
+
+ fn stage1_key(partition_id: u16, lsk: LeafStateKey, person: Uuid) -> Stage1Key {
+ Stage1Key {
+ partition_id,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person,
+ }
+ }
+
+ fn write_tombstone(store: &CohortStore, partition_id: u16, old: Uuid, new: Uuid) {
+ let value = Tombstone {
+ new_person: new,
+ merged_at_ms: 1,
+ };
+ store
+ .write_batch(|b| {
+ b.put_tombstone(
+ &TombstoneKey {
+ partition_id,
+ team_id: TEAM as u64,
+ person: old,
+ },
+ &value.encode(),
+ )
+ })
+ .unwrap();
+ }
+
+ #[test]
+ fn inline_redirect_folds_into_redirect_dedup_origin_not_the_main_map() {
+ let (_dir, store) = temp_store();
+ let catalog = person_catalog();
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+
+ let p_new = Uuid::from_u128(2);
+ let partition_id = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as u16;
+ let p_old = Uuid::from_u128(1);
+ write_tombstone(&store, partition_id, p_old, p_new);
+
+ let mut seed = StatefulRecord::new(
+ Stage1State::PersonProperty {
+ matches: false,
+ last_updated_at_ms: 1_000,
+ last_updated_offset: 0,
+ },
+ applied(&[(5, 50)]),
+ );
+ seed.redirect_dedup.insert(p_old, applied(&[(5, 100)]));
+ let p_new_key = stage1_key(partition_id, lsk, p_new);
+ store
+ .write_batch(|b| b.put_stage1(&p_new_key, &seed.encode()))
+ .unwrap();
+
+ let straggler = person_event(p_old, "[email protected]", 5, 101);
+ let effects = handle_event(
+ partition_id,
+ &store,
+ &catalog,
+ &straggler,
+ "ts",
+ COHORT_PARTITION_COUNT,
+ );
+
+ assert_eq!(effects.changes.len(), 1, "the straggler entered P_new");
+ assert_eq!(effects.changes[0].person_id, p_new.to_string());
+ assert_eq!(effects.changes[0].status, MembershipStatus::Entered);
+
+ let after =
+ StatefulRecord::decode(&store.get_stage1(&p_new_key).unwrap().unwrap()).unwrap();
+ assert!(matches!(
+ after.state,
+ Stage1State::PersonProperty { matches: true, .. }
+ ));
+ assert!(
+ after.redirect_dedup[&p_old].is_replay(5, 101),
+ "the fold advanced redirect_dedup[origin]",
+ );
+ assert!(
+ after.applied_offsets.is_replay(5, 50) && !after.applied_offsets.is_replay(5, 51),
+ "the main map is untouched by a redirected straggler",
+ );
+
+ assert!(store
+ .get_stage1(&stage1_key(partition_id, lsk, p_old))
+ .unwrap()
+ .is_none());
+ }
+
+ #[tokio::test]
+ async fn cross_partition_redirect_re_keys_the_straggler_to_the_target() {
+ let (_dir, store) = temp_store();
+ let catalog = person_catalog();
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let (p_old, partition_id, p_new) = cross_partition_pair();
+ write_tombstone(&store, partition_id, p_old, p_new);
+
+ let stream_sink = CaptureStreamEventSink::new();
+ let membership = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ run_one_straggler(
+ partition_id,
+ &store,
+ catalog,
+ &membership,
+ &tracker,
+ merge_deps_with(stream_sink.clone()),
+ person_event(p_old, "[email protected]", 5, 9),
+ )
+ .await;
+
+ let produced = stream_sink.events();
+ assert_eq!(produced.len(), 1, "one re-keyed event produced");
+ let re_keyed = &produced[0];
+ assert_eq!(
+ re_keyed.person_id,
+ p_new.to_string(),
+ "person rewritten to the target",
+ );
+ assert_eq!(
+ re_keyed.redirected_from,
+ Some(p_old.to_string()),
+ "first origin stamped",
+ );
+ assert_eq!(
+ (re_keyed.source_partition, re_keyed.source_offset),
+ (5, 9),
+ "original source coords preserved for the target's redirect_dedup",
+ );
+ assert_eq!(re_keyed.redirect_hops, 1, "one produced hop");
+
+ assert!(membership.changes().is_empty(), "no local processing");
+ assert!(
+ store
+ .get_stage1(&stage1_key(partition_id, lsk, p_old))
+ .unwrap()
+ .is_none(),
+ "no state written for P_old in the source slice",
+ );
+ assert!(
+ store
+ .get_stage1(&stage1_key(partition_id, lsk, p_new))
+ .unwrap()
+ .is_none(),
+ "no state written for P_new in the source slice",
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&(partition_id as i32)),
+ Some(&1),
+ "the acked re-key produce releases the events offset",
+ );
+ }
+
+ #[tokio::test]
+ async fn re_key_produce_failure_holds_the_events_offset_until_redelivery_succeeds() {
+ let (_dir, store) = temp_store();
+ let catalog = person_catalog();
+ let (p_old, partition_id, p_new) = cross_partition_pair();
+ write_tombstone(&store, partition_id, p_old, p_new);
+ let membership = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let failing = CaptureStreamEventSink::failing_always();
+ run_one_straggler(
+ partition_id,
+ &store,
+ catalog.clone(),
+ &membership,
+ &tracker,
+ merge_deps_with(failing.clone()),
+ person_event(p_old, "[email protected]", 5, 9),
+ )
+ .await;
+ assert!(
+ failing.events().is_empty(),
+ "the failed flush recorded nothing"
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&(partition_id as i32)),
+ None,
+ "the failed produce holds the events offset",
+ );
+
+ let succeeding = CaptureStreamEventSink::new();
+ run_one_straggler(
+ partition_id,
+ &store,
+ catalog,
+ &membership,
+ &tracker,
+ merge_deps_with(succeeding.clone()),
+ person_event(p_old, "[email protected]", 5, 9),
+ )
+ .await;
+ let produced = succeeding.events();
+ assert_eq!(
+ produced.len(),
+ 1,
+ "the redelivery re-derives and produces the re-key"
+ );
+ assert_eq!(produced[0].person_id, p_new.to_string());
+ assert_eq!(
+ (produced[0].source_partition, produced[0].source_offset),
+ (5, 9),
+ "the re-derived copy carries the original source coords (dedupable at the target)",
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&(partition_id as i32)),
+ Some(&1),
+ "the later success releases the held offset",
+ );
+ }
+
+ #[tokio::test]
+ async fn membership_produce_failure_in_a_mixed_batch_withholds_the_re_key_and_the_mark() {
+ let (_dir, store) = temp_store();
+ let catalog = person_catalog();
+ let (p_old, partition_id, p_new) = cross_partition_pair();
+ write_tombstone(&store, partition_id, p_old, p_new);
+ let alice = (100u128..)
+ .map(Uuid::from_u128)
+ .find(|p| partition_of(TeamId(TEAM), p, COHORT_PARTITION_COUNT) as u16 == partition_id)
+ .expect("some uuid hashes onto p_old's partition");
+ let batch = || {
+ vec![
+ ShuffleMessage::Event {
+ event: person_event(alice, "[email protected]", 5, 0),
+ cse_offset: 0,
+ },
+ ShuffleMessage::Event {
+ event: person_event(p_old, "[email protected]", 5, 9),
+ cse_offset: 1,
+ },
+ ]
+ };
+
+ let membership = CaptureSink::failing_first(1);
+ let stream_sink = CaptureStreamEventSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ run_batch(
+ partition_id,
+ &store,
+ catalog.clone(),
+ &membership,
+ &tracker,
+ merge_deps_with(stream_sink.clone()),
+ 2,
+ batch(),
+ )
+ .await;
+ assert!(
+ membership.changes().is_empty(),
+ "the failed flush recorded nothing"
+ );
+ assert!(
+ stream_sink.events().is_empty(),
+ "the membership failure withholds the straggler's re-key produce",
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&(partition_id as i32)),
+ None,
+ "the membership failure holds the whole sub-batch's offset",
+ );
+
+ run_batch(
+ partition_id,
+ &store,
+ catalog,
+ &membership,
+ &tracker,
+ merge_deps_with(stream_sink.clone()),
+ 2,
+ batch(),
+ )
+ .await;
+ assert!(
+ membership.changes().is_empty(),
+ "the replay emits no duplicate membership change (the failed flip stays dropped, at-most-once)",
+ );
+ let produced = stream_sink.events();
+ assert_eq!(produced.len(), 1, "the replay produces the re-key once");
+ assert_eq!(produced[0].person_id, p_new.to_string());
+ assert_eq!(
+ (produced[0].source_partition, produced[0].source_offset),
+ (5, 9),
+ "the re-key carries the straggler's original source coords",
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&(partition_id as i32)),
+ Some(&2),
+ "the acked replay releases the offset past both events",
+ );
+ }
+
+ #[test]
+ fn re_keyed_event_folds_into_p_new_exactly_once_via_redirect_dedup() {
+ let (_dir, store) = temp_store();
+ let catalog = person_catalog();
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let (p_old, source_partition, p_new) = cross_partition_pair();
+ let target_partition = partition_of(TeamId(TEAM), &p_new, COHORT_PARTITION_COUNT) as u16;
+ assert_ne!(source_partition, target_partition);
+ write_tombstone(&store, source_partition, p_old, p_new);
+
+ let straggler = person_event(p_old, "[email protected]", 5, 9);
+ let mut effects = handle_event(
+ source_partition,
+ &store,
+ &catalog,
+ &straggler,
+ "ts",
+ COHORT_PARTITION_COUNT,
+ );
+ assert!(effects.changes.is_empty());
+ assert!(effects.schedules.is_empty());
+ assert_eq!(effects.re_keys.len(), 1);
+ let re_keyed = effects.re_keys.pop().unwrap();
+
+ let effects = handle_event(
+ target_partition,
+ &store,
+ &catalog,
+ &re_keyed,
+ "ts",
+ COHORT_PARTITION_COUNT,
+ );
+ assert_eq!(effects.changes.len(), 1, "folds into P_new exactly once");
+ assert_eq!(effects.changes[0].person_id, p_new.to_string());
+ assert_eq!(effects.changes[0].status, MembershipStatus::Entered);
+ assert!(effects.re_keys.is_empty(), "no further hop: P_new is live");
+
+ let folded = StatefulRecord::decode(
+ &store
+ .get_stage1(&stage1_key(target_partition, lsk, p_new))
+ .unwrap()
+ .expect("P_new state written in the target slice"),
+ )
+ .unwrap();
+ assert!(
+ folded.redirect_dedup[&p_old].is_replay(5, 9),
+ "the fold recorded the original source coords under redirect_dedup[origin]",
+ );
+ assert!(
+ !folded.applied_offsets.is_replay(5, 9),
+ "the main map stays untouched by a redirected straggler",
+ );
+
+ let dup = handle_event(
+ target_partition,
+ &store,
+ &catalog,
+ &re_keyed,
+ "ts",
+ COHORT_PARTITION_COUNT,
+ );
+ assert!(dup.changes.is_empty(), "the duplicate folds zero times");
+ assert!(dup.re_keys.is_empty());
+ }
+
+ #[test]
+ fn hop_capped_redirect_processes_inline_at_the_best_known_target() {
+ let (_dir, store) = temp_store();
+ let catalog = person_catalog();
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let (p_old, partition_id, p_new) = cross_partition_pair();
+ write_tombstone(&store, partition_id, p_old, p_new);
+
+ let straggler = CohortStreamEvent {
+ redirect_hops: tombstone_redirect::MAX_CROSS_PARTITION_REDIRECT_HOPS,
+ ..person_event(p_old, "[email protected]", 5, 9)
+ };
+ let effects = handle_event(
+ partition_id,
+ &store,
+ &catalog,
+ &straggler,
+ "ts",
+ COHORT_PARTITION_COUNT,
+ );
+
+ assert!(effects.re_keys.is_empty(), "no re-produce at the cap");
+ assert_eq!(effects.changes.len(), 1, "processed inline instead");
+ assert_eq!(effects.changes[0].person_id, p_new.to_string());
+
+ let folded = StatefulRecord::decode(
+ &store
+ .get_stage1(&stage1_key(partition_id, lsk, p_new))
+ .unwrap()
+ .expect("the degraded fold writes P_new state in the local slice"),
+ )
+ .unwrap();
+ assert!(
+ folded.redirect_dedup[&p_old].is_replay(5, 9),
+ "the inline degrade still dedups by the chain origin",
+ );
+ assert!(
+ store
+ .get_stage1(&stage1_key(partition_id, lsk, p_old))
+ .unwrap()
+ .is_none(),
+ "no P_old state rebuilt",
+ );
+ }
+
+ #[test]
+ fn no_tombstone_processes_the_event_normally() {
+ let (_dir, store) = temp_store();
+ let catalog = person_catalog();
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = Uuid::from_u128(3);
+ let partition_id = partition_of(TeamId(TEAM), &alice, COHORT_PARTITION_COUNT) as u16;
+
+ let event = person_event(alice, "[email protected]", 5, 0);
+ let effects = handle_event(
+ partition_id,
+ &store,
+ &catalog,
+ &event,
+ "ts",
+ COHORT_PARTITION_COUNT,
+ );
+ assert_eq!(effects.changes.len(), 1);
+ assert_eq!(effects.changes[0].person_id, alice.to_string());
+ assert!(
+ store
+ .get_stage1(&stage1_key(partition_id, lsk, alice))
+ .unwrap()
+ .is_some(),
+ "alice's own state was written",
+ );
+ }
+
+ /// The `MergeCfGc` arm runs the `cf_stage2` orphan GC only when `stage2_orphan_gc_enabled`: a
+ /// SingleLeaf cohort's row (an orphan) survives with the kill-switch off and is reclaimed with it on.
+ #[tokio::test]
+ async fn merge_cf_gc_arm_runs_stage2_orphan_gc_only_when_enabled() {
+ for (enabled, expect_present) in [(false, true), (true, false)] {
+ let (_dir, store) = temp_store();
+ let person = Uuid::from_u128(0xC0FFEE);
+ let partition_id = partition_of(TeamId(TEAM), &person, COHORT_PARTITION_COUNT) as u16;
+ let orphan = Stage2Key {
+ partition_id,
+ team_id: TEAM as u64,
+ cohort_id: 1, // SingleLeaf in person_catalog → an orphan
+ person_id: person,
+ };
+ store
+ .write_batch(|b| {
+ b.put_stage2(
+ &orphan,
+ &Stage2State {
+ in_cohort: true,
+ last_evaluated_at_ms: 1,
+ }
+ .encode(),
+ )
+ })
+ .unwrap();
+
+ let membership = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ run_batch(
+ partition_id,
+ &store,
+ person_catalog(),
+ &membership,
+ &tracker,
+ merge_deps_stage2_gc(enabled),
+ 1,
+ vec![ShuffleMessage::MergeCfGc {
+ marker_cutoff_ms: 0,
+ tombstone_cutoff_ms: 0,
+ }],
+ )
+ .await;
+
+ assert_eq!(
+ store.get_stage2(&orphan).unwrap().is_some(),
+ expect_present,
+ "MergeCfGc arm runs the orphan GC iff enabled (enabled={enabled})",
+ );
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/tests/bucket_tz.rs b/rust/cohort-stream-processor/tests/bucket_tz.rs
new file mode 100644
index 000000000000..a94232ef18c0
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/bucket_tz.rs
@@ -0,0 +1,39 @@
+//! Public-API smoke test for the calendar-day bucket math. The exhaustive DST / boundary golden
+//! matrix lives in the in-crate `#[cfg(test)]` module; this only pins that the module is reachable
+//! through its public path and that the headline window/DST contracts hold from outside the crate.
+
+use chrono_tz::America::New_York;
+use chrono_tz::{Tz, UTC};
+use cohort_stream_processor::stage1::bucket_tz::{
+ daily_bucket_len, day_idx_in_tz, resolve_tz_or_utc, start_of_day_ms_in_tz, window_start_day,
+ DayIdx,
+};
+
+const MS_PER_DAY: i64 = 86_400_000;
+
+fn utc_day_ms(day: DayIdx) -> i64 {
+ i64::from(day) * MS_PER_DAY
+}
+
+#[test]
+fn utc_day_index_round_trips_through_start_of_day() {
+ let day: DayIdx = 20_600; // ~2026
+ let start = utc_day_ms(day);
+ assert_eq!(day_idx_in_tz(start, UTC), day);
+ assert_eq!(start_of_day_ms_in_tz(day, UTC), start);
+}
+
+#[test]
+fn window_is_inclusive_n_plus_one_days() {
+ let now_ms = utc_day_ms(20_600) + 9 * 3_600_000;
+ let now_day = day_idx_in_tz(now_ms, UTC);
+ assert_eq!(window_start_day(now_ms, 7, UTC), now_day - 7);
+ assert_eq!(daily_bucket_len(7), 8);
+}
+
+#[test]
+fn resolve_tz_or_utc_is_reachable_and_falls_back() {
+ let tz: Tz = resolve_tz_or_utc("America/New_York");
+ assert_eq!(tz, New_York);
+ assert_eq!(resolve_tz_or_utc("nonsense"), UTC);
+}
diff --git a/rust/cohort-stream-processor/tests/cascade_consumer.rs b/rust/cohort-stream-processor/tests/cascade_consumer.rs
new file mode 100644
index 000000000000..70ec1b83ada2
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/cascade_consumer.rs
@@ -0,0 +1,745 @@
+//! End-to-end tests for the cascade transport against a **real** Kafka broker: the keyed
+//! `cohort_cascade_events` produce, the assignment-mirrored cascade follower, and the worker-affined
+//! re-evaluation of referrer cohorts — wired like `main.rs` with the gate on.
+//!
+//! `#[ignore]`d by default (group joins and `incremental_assign` semantics the in-process
+//! `MockCluster` does not exercise faithfully). All topics are created with the production partition
+//! count (64) because the routing invariant is the thing under test. Run against a local stack
+//! serially:
+//!
+//! ```sh
+//! cargo test -p cohort-stream-processor --test cascade_consumer -- --ignored --test-threads=1
+//! ```
+//!
+//! Each test deletes its topics on the way out via `with_topics_cleanup`.
+
+use std::collections::HashSet;
+use std::future::Future;
+use std::panic::AssertUnwindSafe;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use chrono_tz::UTC;
+use cohort_stream_processor::cascade::{first_cascade, CascadeMessage};
+use cohort_stream_processor::consumers::{
+ CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, MergeRoute,
+ TransferRoute,
+};
+use cohort_stream_processor::filters::{
+ CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,
+};
+use cohort_stream_processor::partitions::{
+ merge_partition_key, partition_of, run_rebalance_worker, CohortConsumerContext, Follower,
+ FollowerSet, OffsetTracker, PartitionRouter, COHORT_PARTITION_COUNT,
+};
+use cohort_stream_processor::producer::{
+ CascadeSink, CohortMembershipChange, KafkaCascadeSink, KafkaMembershipSink,
+ KafkaStreamEventSink, KafkaTransferSink, MembershipSink, MembershipStatus, StreamEventSink,
+ TransferSink,
+};
+use cohort_stream_processor::store::{CohortStore, StoreConfig};
+use cohort_stream_processor::workers::{
+ CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
+};
+use common_kafka::config::KafkaConfig;
+use futures::FutureExt;
+use lifecycle::{ComponentOptions, Handle, Manager};
+use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
+use rdkafka::client::DefaultClientContext;
+use rdkafka::consumer::{Consumer, StreamConsumer};
+use rdkafka::message::Message;
+use rdkafka::producer::{FutureProducer, FutureRecord};
+use rdkafka::util::Timeout;
+use rdkafka::{ClientConfig, Offset, TopicPartitionList};
+use serde_json::json;
+use tempfile::TempDir;
+use tokio::sync::mpsc;
+use tokio::task::JoinHandle;
+use uuid::Uuid;
+
+const TEAM: i32 = 7;
+const A_HASH: &str = "aaaaaaaaaaaaaaaa";
+const NUM_PARTITIONS: i32 = COHORT_PARTITION_COUNT as i32;
+const TS: &str = "2026-06-10 12:34:56.789000";
+const COMMIT_INTERVAL: Duration = Duration::from_millis(250);
+const RECV_TIMEOUT: Duration = Duration::from_millis(200);
+
+fn bootstrap_servers() -> String {
+ std::env::var("KAFKA_HOSTS").unwrap_or_else(|_| "localhost:9092".to_string())
+}
+
+/// Cohort 2 (A): single `performed_event` on `$a`. Cohort 1 (B): pure cohort-ref to A.
+/// With the cascade gate on, B is `Stage2ComposableRef` — only a cascade from A can flip it,
+/// never its own event.
+fn cascade_catalog() -> CatalogHandle {
+ let a_leaf = json!({
+ "type": "behavioral", "value": "performed_event", "key": "$a",
+ "time_value": 7, "time_interval": "day",
+ "conditionHash": A_HASH,
+ "bytecode": ["_H", 1, 32, "$a", 32, "event", 1, 1, 11],
+ });
+ let ref_leaf = json!({ "type": "cohort", "value": 2, "negation": false });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": [a_leaf] } }),
+ )
+ .expect("add cohort A");
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": [ref_leaf] } }),
+ )
+ .expect("add cohort B");
+ CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ builder.freeze_with(UTC, true),
+ )]))
+}
+
+async fn create_topic(topic: &str, partitions: i32) {
+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .create()
+ .expect("create admin client");
+ let new_topic = NewTopic::new(topic, partitions, TopicReplication::Fixed(1));
+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+ let results = admin
+ .create_topics(&[new_topic], &opts)
+ .await
+ .expect("create_topics");
+ for result in results {
+ match result {
+ Ok(_) | Err((_, rdkafka::types::RDKafkaErrorCode::TopicAlreadyExists)) => {}
+ Err((name, err)) => panic!("failed to create topic {name}: {err:?}"),
+ }
+ }
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("metadata-verifier-{}", Uuid::new_v4()))
+ .create()
+ .expect("create metadata verifier");
+ let start = Instant::now();
+ loop {
+ let ready = verifier
+ .fetch_metadata(Some(topic), Duration::from_secs(5))
+ .ok()
+ .is_some_and(|metadata| {
+ metadata.topics().iter().any(|meta| {
+ meta.name() == topic
+ && meta.error().is_none()
+ && meta.partitions().len() == partitions as usize
+ })
+ });
+ if ready {
+ break;
+ }
+ assert!(
+ start.elapsed() < Duration::from_secs(30),
+ "timed out waiting for topic {topic} metadata to propagate",
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+}
+
+async fn delete_topics(topics: &[&str]) {
+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .create()
+ .expect("create admin client");
+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+ if let Err(err) = admin.delete_topics(topics, &opts).await {
+ eprintln!("topic cleanup failed; leaked {topics:?}: {err}");
+ }
+}
+
+async fn with_topics_cleanup<F: Future<Output = ()>>(topics: &[&str], body: F) {
+ let result = AssertUnwindSafe(body).catch_unwind().await;
+ delete_topics(topics).await;
+ if let Err(panic) = result {
+ std::panic::resume_unwind(panic);
+ }
+}
+
+fn producer_kafka_config() -> KafkaConfig {
+ KafkaConfig {
+ kafka_hosts: bootstrap_servers(),
+ kafka_tls: false,
+ kafka_client_rack: String::new(),
+ kafka_client_id: String::new(),
+ kafka_compression_codec: "none".to_string(),
+ kafka_producer_partitioner: Some("murmur2_random".to_string()),
+ kafka_producer_linger_ms: 20,
+ kafka_producer_queue_mib: 400,
+ kafka_producer_queue_messages: 10_000_000,
+ kafka_message_timeout_ms: 20_000,
+ kafka_producer_batch_size: None,
+ kafka_producer_batch_num_messages: None,
+ kafka_producer_enable_idempotence: None,
+ kafka_producer_max_in_flight_requests_per_connection: None,
+ kafka_producer_topic_metadata_refresh_interval_ms: None,
+ kafka_producer_message_max_bytes: None,
+ kafka_producer_sticky_partitioning_linger_ms: None,
+ }
+}
+
+fn murmur2_producer() -> FutureProducer {
+ ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("message.timeout.ms", "10000")
+ .set("partitioner", "murmur2_random")
+ .create()
+ .expect("create murmur2 producer")
+}
+
+fn events_client_config(group: &str) -> ClientConfig {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "earliest")
+ .set("partition.assignment.strategy", "cooperative-sticky")
+ .set("session.timeout.ms", "6000");
+ config
+}
+
+fn follower_client_config(group: &str) -> ClientConfig {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "earliest")
+ .set("socket.timeout.ms", "10000");
+ config
+}
+
+fn topic_message_count(topic: &str) -> i64 {
+ let consumer: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("watermark-verifier-{}", Uuid::new_v4()))
+ .create()
+ .expect("create watermark verifier");
+ (0..NUM_PARTITIONS)
+ .map(|partition| {
+ let (low, high) = consumer
+ .fetch_watermarks(topic, partition, Duration::from_secs(10))
+ .expect("fetch watermarks");
+ high - low
+ })
+ .sum()
+}
+
+/// Read up to `expected` messages (all partitions from the beginning). Assigned explicitly — no group
+/// join, no commit.
+async fn consume_all(topic: &str, expected: usize, deadline: Duration) -> Vec<(i32, Vec<u8>)> {
+ let consumer: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("scan-verifier-{}", Uuid::new_v4()))
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create scan verifier");
+ let mut tpl = TopicPartitionList::new();
+ for partition in 0..NUM_PARTITIONS {
+ tpl.add_partition_offset(topic, partition, Offset::Beginning)
+ .expect("add partition to scan TPL");
+ }
+ consumer.assign(&tpl).expect("assign scan verifier");
+
+ let mut messages = Vec::new();
+ let start = Instant::now();
+ while messages.len() < expected && start.elapsed() < deadline {
+ match tokio::time::timeout(Duration::from_secs(2), consumer.recv()).await {
+ Ok(Ok(message)) => {
+ if let Some(payload) = message.payload() {
+ messages.push((message.partition(), payload.to_vec()));
+ }
+ }
+ Ok(Err(err)) => panic!("scan verifier recv error: {err}"),
+ Err(_) => {}
+ }
+ }
+ messages
+}
+
+async fn wait_for(what: &str, deadline: Duration, mut condition: impl FnMut() -> bool) {
+ let start = Instant::now();
+ while !condition() {
+ assert!(
+ start.elapsed() < deadline,
+ "timed out after {deadline:?} waiting for {what}",
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+}
+
+fn part(person: Uuid) -> u16 {
+ partition_of(TeamId(TEAM), &person, COHORT_PARTITION_COUNT) as u16
+}
+
+fn envelope(person: Uuid, event: &str, source_offset: i64) -> Vec<u8> {
+ serde_json::to_vec(&json!({
+ "team_id": TEAM,
+ "person_id": person.to_string(),
+ "distinct_id": "d",
+ "uuid": Uuid::from_u128(0xE0_0000 + source_offset as u128).to_string(),
+ "event": event,
+ "timestamp": TS,
+ "properties": "{}",
+ "person_properties": null,
+ "elements_chain": null,
+ "source_offset": source_offset,
+ "source_partition": 0,
+ }))
+ .expect("serialize envelope")
+}
+
+async fn produce_event(
+ producer: &FutureProducer,
+ topic: &str,
+ person: Uuid,
+ event: &str,
+ source_offset: i64,
+) {
+ let key = merge_partition_key(TeamId(TEAM), &person);
+ let payload = envelope(person, event, source_offset);
+ let (partition, _offset) = producer
+ .send(
+ FutureRecord::to(topic).key(&key).payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce event");
+ assert_eq!(partition as u16, part(person), "event must co-partition");
+}
+
+fn open_store(dir: &TempDir) -> CohortStore {
+ CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store")
+}
+
+struct Topics {
+ events: String,
+ merges: String,
+ transfers: String,
+ cascade: String,
+ shadow: String,
+}
+
+impl Topics {
+ fn unique(suffix: &Uuid) -> Self {
+ Self {
+ events: format!("cohort_stream_events_cascade_{suffix}"),
+ merges: format!("person_merge_events_{suffix}"),
+ transfers: format!("cohort_merge_state_transfer_{suffix}"),
+ cascade: format!("cohort_cascade_events_{suffix}"),
+ shadow: format!("cohort_membership_changed_{suffix}"),
+ }
+ }
+
+ async fn create(&self) {
+ for topic in self.names() {
+ create_topic(topic, NUM_PARTITIONS).await;
+ }
+ }
+
+ fn names(&self) -> [&str; 5] {
+ [
+ &self.events,
+ &self.merges,
+ &self.transfers,
+ &self.cascade,
+ &self.shadow,
+ ]
+ }
+}
+
+struct Groups {
+ events: String,
+ merges: String,
+ transfers: String,
+ cascade: String,
+}
+
+impl Groups {
+ fn unique(suffix: &Uuid) -> Self {
+ Self {
+ events: format!("cohort-stream-processor-{suffix}"),
+ merges: format!("cohort-stream-merges-{suffix}"),
+ transfers: format!("cohort-stream-merge-apply-{suffix}"),
+ cascade: format!("cohort-stream-cascade-{suffix}"),
+ }
+ }
+}
+
+fn register_instance(manager: &mut Manager) -> [Handle; 4] {
+ let options = || ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15));
+ [
+ manager.register("consumer", options()),
+ manager.register("merge-follower", options()),
+ manager.register("transfer-follower", options()),
+ manager.register("cascade-follower", options()),
+ ]
+}
+
+struct Instance {
+ dispatcher: Arc<EventDispatcher>,
+ tasks: Vec<JoinHandle<()>>,
+}
+
+impl Instance {
+ fn owned(&self) -> HashSet<i32> {
+ self.dispatcher.owned_partitions().into_iter().collect()
+ }
+
+ async fn join(self) {
+ for task in self.tasks {
+ task.await.expect("instance task panicked");
+ }
+ }
+}
+
+async fn spawn_instance(
+ topics: &Topics,
+ groups: &Groups,
+ store: CohortStore,
+ catalog: CatalogHandle,
+ handles: [Handle; 4],
+) -> Instance {
+ let [events_handle, merge_handle, transfer_handle, cascade_handle] = handles;
+ let kafka_config = producer_kafka_config();
+
+ let transfer_sink: Arc<dyn TransferSink> = Arc::new(
+ KafkaTransferSink::new(&kafka_config, topics.transfers.clone())
+ .await
+ .expect("create transfer sink"),
+ );
+ let stream_event_sink: Arc<dyn StreamEventSink> = Arc::new(
+ KafkaStreamEventSink::new(&kafka_config, topics.events.clone())
+ .await
+ .expect("create re-key sink"),
+ );
+ let cascade_sink = Arc::new(
+ KafkaCascadeSink::new(&kafka_config, topics.cascade.clone())
+ .await
+ .expect("create cascade sink"),
+ );
+ let membership_sink: Arc<dyn MembershipSink> = Arc::new(
+ KafkaMembershipSink::new(&kafka_config, topics.shadow.clone())
+ .await
+ .expect("create membership sink"),
+ );
+ let merge_deps = Arc::new(MergeWorkerDeps {
+ transfer_sink,
+ stream_event_sink,
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink,
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: CascadeConfig {
+ enabled: true,
+ depth_cap: 8,
+ fanout_cap: 1000,
+ },
+ partition_count: COHORT_PARTITION_COUNT,
+ });
+
+ let dispatcher = Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store,
+ Arc::new(catalog),
+ membership_sink,
+ merge_deps,
+ ));
+
+ let merges_consumer: Arc<StreamConsumer> = Arc::new(
+ follower_client_config(&groups.merges)
+ .create()
+ .expect("create merges follower consumer"),
+ );
+ let transfers_consumer: Arc<StreamConsumer> = Arc::new(
+ follower_client_config(&groups.transfers)
+ .create()
+ .expect("create transfers follower consumer"),
+ );
+ let cascade_consumer: Arc<StreamConsumer> = Arc::new(
+ follower_client_config(&groups.cascade)
+ .create()
+ .expect("create cascade follower consumer"),
+ );
+ let followers = Arc::new(FollowerSet::new([
+ Follower::new(merges_consumer.clone(), topics.merges.clone()),
+ Follower::new(transfers_consumer.clone(), topics.transfers.clone()),
+ Follower::new(cascade_consumer.clone(), topics.cascade.clone()),
+ ]));
+
+ let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());
+ let events_client: StreamConsumer<CohortConsumerContext> = events_client_config(&groups.events)
+ .create_with_context(context)
+ .expect("create events consumer");
+ events_client
+ .subscribe(&[topics.events.as_str()])
+ .expect("subscribe events");
+
+ let (command_tx, command_rx) = mpsc::unbounded_channel();
+ let mut tasks = vec![tokio::spawn(run_rebalance_worker(
+ rebalance_rx,
+ dispatcher.clone(),
+ followers,
+ command_tx,
+ events_handle.shutdown_token(),
+ ))];
+
+ let merge_follower = FollowerConsumer::<MergeRoute>::new(
+ merges_consumer,
+ topics.merges.clone(),
+ dispatcher.clone(),
+ merge_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ );
+ tasks.push(tokio::spawn(merge_follower.process()));
+
+ let transfer_follower = FollowerConsumer::<TransferRoute>::new(
+ transfers_consumer,
+ topics.transfers.clone(),
+ dispatcher.clone(),
+ transfer_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ );
+ tasks.push(tokio::spawn(transfer_follower.process()));
+
+ let cascade_follower = FollowerConsumer::<CascadeRoute>::new(
+ cascade_consumer,
+ topics.cascade.clone(),
+ dispatcher.clone(),
+ cascade_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ );
+ tasks.push(tokio::spawn(cascade_follower.process()));
+
+ let events_consumer = CohortStreamEventsConsumer::new(
+ events_client,
+ topics.events.clone(),
+ dispatcher.clone(),
+ events_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ NUM_PARTITIONS as usize,
+ command_rx,
+ None,
+ );
+ tasks.push(tokio::spawn(events_consumer.process()));
+
+ Instance { dispatcher, tasks }
+}
+
+/// Cascade produces must co-partition with `partition_of(team, person)` so a flip lands on the worker
+/// that owns the person's `cf_stage2` row.
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn cascade_producer_co_partitions_with_events() {
+ let suffix = Uuid::new_v4();
+ let cascade_topic = format!("cascade_routing_{suffix}");
+ with_topics_cleanup(&[&cascade_topic], async {
+ create_topic(&cascade_topic, NUM_PARTITIONS).await;
+
+ let sink = KafkaCascadeSink::new(&producer_kafka_config(), cascade_topic.clone())
+ .await
+ .expect("create cascade sink");
+
+ let mut spread = HashSet::new();
+ let messages: Vec<CascadeMessage> = [2i32, 7, 42, 99]
+ .into_iter()
+ .flat_map(|team| {
+ (1..=24u128).map(move |n| {
+ let person = Uuid::from_u128(((team as u128) << 64) | n);
+ first_cascade(
+ CohortMembershipChange {
+ team_id: team,
+ cohort_id: 91204,
+ person_id: person.to_string(),
+ last_updated: TS.to_string(),
+ status: MembershipStatus::Entered,
+ },
+ n as i64,
+ )
+ })
+ })
+ .collect();
+ let total = messages.len();
+ let acks = sink.produce(messages).await;
+ assert!(acks.iter().all(Result::is_ok), "all cascade produces ack");
+
+ let on_wire = consume_all(&cascade_topic, total, Duration::from_secs(30)).await;
+ assert_eq!(on_wire.len(), total, "all produced cascades are readable");
+ for (partition, payload) in &on_wire {
+ let message: CascadeMessage = serde_json::from_slice(payload).unwrap();
+ let person = Uuid::parse_str(&message.change.person_id).unwrap();
+ assert_eq!(
+ *partition as u32,
+ partition_of(
+ TeamId(message.change.team_id),
+ &person,
+ COHORT_PARTITION_COUNT
+ ),
+ "cascade for ({}, {person}) landed off its partition",
+ message.change.team_id,
+ );
+ spread.insert(*partition);
+ }
+ assert!(
+ spread.len() >= 16,
+ "{total} cascades should cover many partitions, got {}",
+ spread.len(),
+ );
+ })
+ .await;
+}
+
+/// One `$a` event flips A (cohort 2); the first-hop cascade re-evaluates B (cohort 1, a pure ref),
+/// which flips and emits an external change plus a depth-2 onward cascade.
+/// External bytes are exactly the five-key `CohortMembershipChange` shape.
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn cascade_reevaluates_a_referrer_end_to_end() {
+ let suffix = Uuid::new_v4();
+ let topics = Topics::unique(&suffix);
+ let groups = Groups::unique(&suffix);
+ with_topics_cleanup(&topics.names(), async {
+ topics.create().await;
+
+ let mut manager = Manager::builder("cascade-e2e-itest")
+ .with_trap_signals(false)
+ .build();
+ let handles = register_instance(&mut manager);
+ let shutdown = handles[0].clone();
+ let _monitor = manager.monitor_background();
+
+ let dir = TempDir::new().unwrap();
+ let instance = spawn_instance(
+ &topics,
+ &groups,
+ open_store(&dir),
+ cascade_catalog(),
+ handles,
+ )
+ .await;
+ wait_for(
+ "the consumer to own every partition",
+ Duration::from_secs(30),
+ || instance.owned().len() == NUM_PARTITIONS as usize,
+ )
+ .await;
+
+ let alice = Uuid::from_u128(0xA11CE);
+ let producer = murmur2_producer();
+ produce_event(&producer, &topics.events, alice, "$a", 0).await;
+
+ wait_for(
+ "both cohort flips on the shadow topic",
+ Duration::from_secs(60),
+ || topic_message_count(&topics.shadow) == 2,
+ )
+ .await;
+
+ let changes: Vec<CohortMembershipChange> =
+ consume_all(&topics.shadow, 2, Duration::from_secs(30))
+ .await
+ .iter()
+ .map(|(_, payload)| serde_json::from_slice(payload).expect("decode change"))
+ .collect();
+ let entered: HashSet<i32> = changes
+ .iter()
+ .filter(|c| c.person_id == alice.to_string() && c.status == MembershipStatus::Entered)
+ .map(|c| c.cohort_id)
+ .collect();
+ assert_eq!(
+ entered,
+ HashSet::from([1, 2]),
+ "A entered from the event and B entered from the cascade re-evaluation",
+ );
+
+ let (_, payload) = consume_all(&topics.shadow, 1, Duration::from_secs(10))
+ .await
+ .into_iter()
+ .next()
+ .expect("one external change");
+ let value: serde_json::Value = serde_json::from_slice(&payload).unwrap();
+ let mut keys: Vec<&str> = value
+ .as_object()
+ .unwrap()
+ .keys()
+ .map(String::as_str)
+ .collect();
+ keys.sort_unstable();
+ assert_eq!(
+ keys,
+ vec![
+ "cohort_id",
+ "last_updated",
+ "person_id",
+ "status",
+ "team_id"
+ ],
+ "external topic carries exactly the five-key shape, no cascade fields",
+ );
+
+ // Cascade topic carries depth-1 (A) and depth-2 (B) hops, both keyed on alice's partition.
+ wait_for(
+ "the depth-1 and depth-2 cascades on the wire",
+ Duration::from_secs(60),
+ || topic_message_count(&topics.cascade) == 2,
+ )
+ .await;
+ let cascades: Vec<(i32, CascadeMessage)> =
+ consume_all(&topics.cascade, 2, Duration::from_secs(30))
+ .await
+ .iter()
+ .map(|(p, payload)| (*p, serde_json::from_slice(payload).expect("decode cascade")))
+ .collect();
+ for (partition, message) in &cascades {
+ assert_eq!(
+ *partition as u16,
+ part(alice),
+ "cascade keyed on alice's partition"
+ );
+ assert_eq!(
+ message.originating_cohort_id, 2,
+ "the chain originated at A"
+ );
+ }
+ let by_cohort: HashSet<(i32, u8)> = cascades
+ .iter()
+ .map(|(_, m)| (m.change.cohort_id, m.depth))
+ .collect();
+ assert_eq!(
+ by_cohort,
+ HashSet::from([(2, 1), (1, 2)]),
+ "first hop is A at depth 1, the onward hop is B at depth 2",
+ );
+
+ shutdown.request_shutdown();
+ instance.join().await;
+ })
+ .await;
+}
diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rs
new file mode 100644
index 000000000000..d646c5b7f28f
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/events_consumer.rs
@@ -0,0 +1,1517 @@
+//! End-to-end tests for the `cohort_stream_events` consumer against a **real** Kafka broker.
+//!
+//! `#[ignore]`d by default: the consumer joins a consumer group, commits a `TopicPartitionList`,
+//! and reads its own committed offsets back, none of which the in-process `MockCluster` exercises
+//! faithfully. Run against a local stack with:
+//!
+//! ```sh
+//! cargo test -p cohort-stream-processor --test events_consumer -- --ignored
+//! ```
+//!
+//! The S3/PVC disaster-recovery e2e
+//! ([`s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant_left`]) additionally
+//! needs an S3-compatible store (MinIO / SeaweedFS). Point it at one with:
+//!
+//! ```sh
+//! export KAFKA_HOSTS=localhost:9092
+//! export CHECKPOINT_S3_ENDPOINT=http://localhost:19000 # MinIO; or :8333 for SeaweedFS
+//! export CHECKPOINT_S3_BUCKET=cohort-checkpoints # must already exist
+//! export CHECKPOINT_S3_ACCESS_KEY_ID=... # MinIO/SeaweedFS creds
+//! export CHECKPOINT_S3_SECRET_ACCESS_KEY=...
+//! cargo test -p cohort-stream-processor --test events_consumer -- --ignored s3_restore
+//! ```
+//!
+//! Every test creates 4-partition topics and deletes the Kafka topic on exit (a leaked high-partition
+//! topic wedges later runs); the S3 e2e also sweeps its per-test S3 prefix on exit.
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use async_trait::async_trait;
+use chrono_tz::UTC;
+use cohort_stream_processor::config::Config;
+use cohort_stream_processor::consumers::{CohortStreamEventsConsumer, EventDispatcher};
+use cohort_stream_processor::filters::{
+ CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,
+};
+use cohort_stream_processor::partitions::{
+ run_rebalance_worker, CohortConsumerContext, OffsetTracker, PartitionMirror, PartitionRouter,
+ ShuffleMessage,
+};
+use cohort_stream_processor::producer::{
+ CaptureSink, CohortMembershipChange, KafkaMembershipSink, MembershipSink, MembershipStatus,
+};
+use cohort_stream_processor::stage1::{Stage1State, StatefulRecord};
+use cohort_stream_processor::store::durability::{
+ run_boot_restore, upload_cadence, CheckpointExporter, CheckpointSweeper, OffsetManifest,
+ RestoreSource, S3Uploader,
+};
+use cohort_stream_processor::store::{CohortStore, LeafStateKey, Stage1Key, StoreConfig};
+use cohort_stream_processor::sweep::Sweeper;
+use cohort_stream_processor::workers::{MergeWorkerDeps, Stage1Worker};
+use common_kafka::config::KafkaConfig;
+use common_kafka::kafka_producer::KafkaProduceError;
+use envconfig::Envconfig;
+use lifecycle::{ComponentOptions, Manager};
+use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
+use rdkafka::client::DefaultClientContext;
+use rdkafka::consumer::{Consumer, StreamConsumer};
+use rdkafka::message::Message;
+use rdkafka::producer::{FutureProducer, FutureRecord};
+use rdkafka::util::Timeout;
+use rdkafka::{ClientConfig, Offset, TopicPartitionList};
+use serde_json::json;
+use tempfile::TempDir;
+use tokio::sync::mpsc;
+use uuid::Uuid;
+
+const TEAM: i32 = 7;
+const HASH: [u8; 16] = *b"0123456789abcdef";
+const NUM_PARTITIONS: i32 = 4;
+const PERSONS: u128 = 3;
+const EVENTS_PER_PERSON: usize = 3;
+const BASE_TS: &str = "2026-05-26 12:34:56.789000";
+
+fn bootstrap_servers() -> String {
+ std::env::var("KAFKA_HOSTS").unwrap_or_else(|_| "localhost:9092".to_string())
+}
+
+/// A team with a single `performed_event` behavioral leaf on `$pageview` — every `$pageview` enters.
+fn behavioral_catalog() -> CatalogHandle {
+ let leaf = json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ });
+ let cohort = json!({ "properties": { "type": "AND", "values": [leaf] } });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(TEAM), &cohort)
+ .expect("add cohort");
+ CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ builder.freeze(UTC),
+ )]))
+}
+
+fn behavioral_lsk(catalog: &CatalogHandle) -> LeafStateKey {
+ let snapshot = catalog.load();
+ let team = snapshot.team(TeamId(TEAM)).expect("team in catalog");
+ team.by_condition_to_lsk[&HASH][0]
+}
+
+fn person(n: u128) -> Uuid {
+ Uuid::from_u128(0xA1CE_0000 + n)
+}
+
+/// A serialized `CohortStreamEvent` envelope, byte-for-byte what the shuffler emits.
+fn envelope(person: Uuid, source_partition: i32, source_offset: i64) -> Vec<u8> {
+ let value = json!({
+ "team_id": TEAM,
+ "person_id": person.to_string(),
+ "distinct_id": "d",
+ "uuid": Uuid::from_u128(0xE0_0000 + source_offset as u128).to_string(),
+ "event": "$pageview",
+ "timestamp": BASE_TS,
+ "properties": "{}",
+ "person_properties": null,
+ "elements_chain": null,
+ "source_offset": source_offset,
+ "source_partition": source_partition,
+ });
+ serde_json::to_vec(&value).expect("serialize envelope")
+}
+
+async fn create_topic(topic: &str) {
+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .create()
+ .expect("create admin client");
+ let new_topic = NewTopic::new(topic, NUM_PARTITIONS, TopicReplication::Fixed(1));
+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+ let results = admin
+ .create_topics(&[new_topic], &opts)
+ .await
+ .expect("create_topics");
+ for result in results {
+ match result {
+ Ok(_) | Err((_, rdkafka::types::RDKafkaErrorCode::TopicAlreadyExists)) => {}
+ Err((name, err)) => panic!("failed to create topic {name}: {err:?}"),
+ }
+ }
+ // Let topic metadata propagate before producing.
+ tokio::time::sleep(Duration::from_millis(500)).await;
+}
+
+/// Delete a topic on test exit. Best-effort: a missing topic or admin error is ignored so cleanup
+/// never fails a passing test. Leaked topics (especially high-partition ones) wedge later runs.
+async fn delete_topic(topic: &str) {
+ let admin: AdminClient<DefaultClientContext> = match ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .create()
+ {
+ Ok(admin) => admin,
+ Err(_) => return,
+ };
+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+ let _result = admin.delete_topics(&[topic], &opts).await;
+}
+
+/// Keyed `"{team}:{person}"` so a person's events co-partition. Returns the total produced.
+async fn produce_events(topic: &str) -> usize {
+ let producer: FutureProducer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("message.timeout.ms", "10000")
+ .create()
+ .expect("create producer");
+
+ let mut total = 0;
+ let mut source_offset = 0i64;
+ for n in 1..=PERSONS {
+ let p = person(n);
+ let key = format!("{TEAM}:{p}");
+ for _ in 0..EVENTS_PER_PERSON {
+ let payload = envelope(p, 0, source_offset);
+ producer
+ .send(
+ FutureRecord::to(topic).key(&key).payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce event");
+ source_offset += 1;
+ total += 1;
+ }
+ }
+ total
+}
+
+struct NoopMirror;
+
+impl PartitionMirror for NoopMirror {
+ fn assign(&self, _partitions: &[i32]) {}
+ fn unassign(&self, _partitions: &[i32]) {}
+}
+
+fn build_consumer(
+ topic: &str,
+ group: &str,
+ store: CohortStore,
+ catalog: CatalogHandle,
+ handle: lifecycle::Handle,
+ sink: Arc<dyn MembershipSink>,
+ offset_commit_interval: Duration,
+) -> CohortStreamEventsConsumer {
+ build_consumer_with_restore(
+ topic,
+ group,
+ store,
+ catalog,
+ handle,
+ sink,
+ offset_commit_interval,
+ false,
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+fn build_consumer_with_restore(
+ topic: &str,
+ group: &str,
+ store: CohortStore,
+ catalog: CatalogHandle,
+ handle: lifecycle::Handle,
+ sink: Arc<dyn MembershipSink>,
+ offset_commit_interval: Duration,
+ durable_restore: bool,
+) -> CohortStreamEventsConsumer {
+ let dispatcher = Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store,
+ Arc::new(catalog),
+ sink,
+ MergeWorkerDeps::capture(),
+ ));
+ if durable_restore {
+ dispatcher.enable_durable_restore();
+ }
+
+ let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());
+ let consumer: StreamConsumer<CohortConsumerContext> = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "earliest")
+ .set("partition.assignment.strategy", "cooperative-sticky")
+ .set("session.timeout.ms", "6000")
+ .create_with_context(context)
+ .expect("create consumer");
+ consumer.subscribe(&[topic]).expect("subscribe");
+
+ let (consumer_command_tx, consumer_command_rx) = mpsc::unbounded_channel();
+ tokio::spawn(run_rebalance_worker(
+ rebalance_rx,
+ dispatcher.clone(),
+ Arc::new(NoopMirror),
+ consumer_command_tx,
+ handle.shutdown_token(),
+ ));
+
+ CohortStreamEventsConsumer::new(
+ consumer,
+ topic.to_string(),
+ dispatcher,
+ handle,
+ 100,
+ Duration::from_millis(200),
+ offset_commit_interval,
+ NUM_PARTITIONS as usize,
+ consumer_command_rx,
+ None,
+ )
+}
+
+/// The `murmur2_random` partitioner must match production for keyed co-partitioning.
+fn shadow_kafka_config() -> KafkaConfig {
+ KafkaConfig {
+ kafka_hosts: bootstrap_servers(),
+ kafka_tls: false,
+ kafka_client_rack: String::new(),
+ kafka_client_id: String::new(),
+ kafka_compression_codec: "none".to_string(),
+ kafka_producer_partitioner: Some("murmur2_random".to_string()),
+ kafka_producer_linger_ms: 20,
+ kafka_producer_queue_mib: 400,
+ kafka_producer_queue_messages: 10_000_000,
+ kafka_message_timeout_ms: 20_000,
+ kafka_producer_batch_size: None,
+ kafka_producer_batch_num_messages: None,
+ kafka_producer_enable_idempotence: None,
+ kafka_producer_max_in_flight_requests_per_connection: None,
+ kafka_producer_topic_metadata_refresh_interval_ms: None,
+ kafka_producer_message_max_bytes: None,
+ kafka_producer_sticky_partitioning_linger_ms: None,
+ }
+}
+
+/// Drain up to `expected` membership changes off the shadow topic, or whatever arrives by deadline.
+async fn drain_shadow_changes(topic: &str, expected: usize) -> Vec<CohortMembershipChange> {
+ let consumer: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("shadow-verifier-{}", Uuid::new_v4()))
+ .set("enable.auto.commit", "false")
+ .set("auto.offset.reset", "earliest")
+ .create()
+ .expect("create shadow verifier");
+ consumer.subscribe(&[topic]).expect("subscribe shadow");
+
+ let mut changes = Vec::new();
+ let start = Instant::now();
+ while changes.len() < expected && start.elapsed() < Duration::from_secs(30) {
+ match tokio::time::timeout(Duration::from_secs(2), consumer.recv()).await {
+ Ok(Ok(message)) => {
+ if let Some(payload) = message.payload() {
+ changes.push(
+ serde_json::from_slice::<CohortMembershipChange>(payload)
+ .expect("decode shadow membership change"),
+ );
+ }
+ }
+ Ok(Err(err)) => panic!("shadow recv error: {err}"),
+ Err(_) => {} // poll tick elapsed with no message; re-check the deadline
+ }
+ }
+ changes
+}
+
+/// Sum of committed offsets across partitions; for a fresh topic this equals the events consumed
+/// (committed == next-offset-to-consume).
+fn committed_sum(consumer: &StreamConsumer, topic: &str) -> i64 {
+ let mut tpl = TopicPartitionList::new();
+ for partition in 0..NUM_PARTITIONS {
+ tpl.add_partition(topic, partition);
+ }
+ let committed = consumer
+ .committed_offsets(tpl, Duration::from_secs(5))
+ .expect("fetch committed offsets");
+ (0..NUM_PARTITIONS)
+ .filter_map(|partition| committed.find_partition(topic, partition))
+ .map(|elem| match elem.offset() {
+ Offset::Offset(value) => value,
+ _ => 0,
+ })
+ .sum()
+}
+
+/// Scans every partition because a person's partition depends on the producer's key hash.
+fn entered_persons(store: &CohortStore, lsk: LeafStateKey) -> usize {
+ (1..=PERSONS)
+ .filter(|&n| {
+ let p = person(n);
+ (0..NUM_PARTITIONS).any(|partition| {
+ let key = Stage1Key {
+ partition_id: partition as u16,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: p,
+ };
+ matches!(
+ store
+ .get_stage1(&key)
+ .unwrap()
+ .map(|bytes| StatefulRecord::decode(&bytes).unwrap().state),
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ }),
+ )
+ })
+ })
+ .count()
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn consumes_routes_and_commits_end_to_end() {
+ let suffix = Uuid::new_v4();
+ let topic = format!("cohort_stream_events_itest_{suffix}");
+ let group = format!("cohort-stream-processor-itest-{suffix}");
+
+ create_topic(&topic).await;
+ let total = produce_events(&topic).await;
+
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store");
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+
+ // Not subscribed: reads committed offsets via OffsetFetch without joining the group.
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", &group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create verifier consumer");
+
+ let mut manager = Manager::builder("events-consumer-itest")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let shutdown_handle = handle.clone();
+ let _monitor = manager.monitor_background();
+
+ let consumer = build_consumer(
+ &topic,
+ &group,
+ store.clone(),
+ catalog,
+ handle,
+ Arc::new(CaptureSink::new()),
+ Duration::from_millis(250),
+ );
+ let task = tokio::spawn(consumer.process());
+
+ let deadline = Duration::from_secs(60);
+ let start = Instant::now();
+ loop {
+ if committed_sum(&verifier, &topic) == total as i64 {
+ break;
+ }
+ assert!(
+ start.elapsed() < deadline,
+ "timed out waiting for committed offsets to reach {total}; last sum {}",
+ committed_sum(&verifier, &topic),
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+
+ shutdown_handle.request_shutdown();
+ task.await.expect("consumer task panicked");
+
+ assert_eq!(
+ entered_persons(&store, lsk),
+ PERSONS as usize,
+ "every produced person should have entered the behavioral leaf",
+ );
+
+ assert_eq!(
+ committed_sum(&verifier, &topic),
+ total as i64,
+ "committed offsets should cover all {total} produced events",
+ );
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn produces_membership_changes_and_commits_offsets() {
+ let suffix = Uuid::new_v4();
+ let input_topic = format!("cohort_stream_events_shadow_in_{suffix}");
+ let shadow_topic = format!("cohort_membership_changed_shadow_{suffix}");
+ let group = format!("cohort-stream-processor-shadow-{suffix}");
+
+ create_topic(&input_topic).await;
+ create_topic(&shadow_topic).await;
+ let total = produce_events(&input_topic).await;
+
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store");
+ let catalog = behavioral_catalog();
+
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", &group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create verifier consumer");
+
+ let sink: Arc<dyn MembershipSink> = Arc::new(
+ KafkaMembershipSink::new(&shadow_kafka_config(), shadow_topic.clone())
+ .await
+ .expect("create shadow sink"),
+ );
+
+ let mut manager = Manager::builder("shadow-itest")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let shutdown_handle = handle.clone();
+ let _monitor = manager.monitor_background();
+
+ let consumer = build_consumer(
+ &input_topic,
+ &group,
+ store.clone(),
+ catalog,
+ handle,
+ sink,
+ Duration::from_millis(250),
+ );
+ let task = tokio::spawn(consumer.process());
+
+ let start = Instant::now();
+ loop {
+ if committed_sum(&verifier, &input_topic) == total as i64 {
+ break;
+ }
+ assert!(
+ start.elapsed() < Duration::from_secs(60),
+ "timed out waiting for committed input offsets to reach {total}",
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+
+ shutdown_handle.request_shutdown();
+ task.await.expect("consumer task panicked");
+
+ // One entered per person: the first `$pageview` enters, repeats are already members.
+ let changes = drain_shadow_changes(&shadow_topic, PERSONS as usize).await;
+ assert_eq!(
+ changes.len(),
+ PERSONS as usize,
+ "one entered change per person on the shadow topic",
+ );
+ for change in &changes {
+ assert_eq!(change.team_id, TEAM);
+ assert_eq!(change.cohort_id, 1);
+ assert_eq!(change.status, MembershipStatus::Entered);
+ assert!(
+ Uuid::parse_str(&change.person_id).is_ok(),
+ "person_id is a UUID string",
+ );
+ }
+
+ assert_eq!(committed_sum(&verifier, &input_topic), total as i64);
+}
+
+/// One event at a time with a `gap`, so sends straddle commit deadlines (the low-traffic pattern).
+/// Each distinct person produces one matching `$pageview`. Returns the total produced.
+async fn produce_events_trickle(topic: &str, n: usize, gap: Duration) -> usize {
+ let producer: FutureProducer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("message.timeout.ms", "10000")
+ .create()
+ .expect("create producer");
+
+ for i in 0..n {
+ let p = person(i as u128 + 1);
+ let key = format!("{TEAM}:{p}");
+ let payload = envelope(p, 0, i as i64);
+ producer
+ .send(
+ FutureRecord::to(topic).key(&key).payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce event");
+ tokio::time::sleep(gap).await;
+ }
+ n
+}
+
+fn entered_persons_range(store: &CohortStore, lsk: LeafStateKey, n: usize) -> usize {
+ (1..=n as u128)
+ .filter(|&i| {
+ let p = person(i);
+ (0..NUM_PARTITIONS).any(|partition| {
+ let key = Stage1Key {
+ partition_id: partition as u16,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: p,
+ };
+ matches!(
+ store
+ .get_stage1(&key)
+ .unwrap()
+ .map(|bytes| StatefulRecord::decode(&bytes).unwrap().state),
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ }),
+ )
+ })
+ })
+ .count()
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn trickled_events_are_never_silently_dropped() {
+ const N: usize = 60;
+
+ let suffix = Uuid::new_v4();
+ let topic = format!("cohort_stream_events_trickle_{suffix}");
+ let group = format!("cohort-stream-processor-trickle-{suffix}");
+
+ create_topic(&topic).await;
+
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store");
+ let catalog = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog);
+
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", &group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create verifier consumer");
+
+ let mut manager = Manager::builder("trickle-itest")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let shutdown_handle = handle.clone();
+ let _monitor = manager.monitor_background();
+
+ // Consumer must be live before producing so sends straddle commit boundaries.
+ let consumer = build_consumer(
+ &topic,
+ &group,
+ store.clone(),
+ catalog,
+ handle,
+ Arc::new(CaptureSink::new()),
+ Duration::from_millis(300),
+ );
+ let task = tokio::spawn(consumer.process());
+
+ let total = produce_events_trickle(&topic, N, Duration::from_millis(120)).await;
+
+ let start = Instant::now();
+ loop {
+ if committed_sum(&verifier, &topic) == total as i64 {
+ break;
+ }
+ assert!(
+ start.elapsed() < Duration::from_secs(60),
+ "timed out waiting for committed offsets to reach {total}; last sum {}",
+ committed_sum(&verifier, &topic),
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+
+ shutdown_handle.request_shutdown();
+ task.await.expect("consumer task panicked");
+
+ assert_eq!(
+ entered_persons_range(&store, lsk, N),
+ N,
+ "every trickled person must have entered the behavioral leaf (no silent consume-side loss)",
+ );
+ assert_eq!(
+ committed_sum(&verifier, &topic),
+ total as i64,
+ "committed offsets must cover all {total} produced events",
+ );
+}
+
+/// Blocks its first flush until released, preventing the worker from marking its offset.
+struct BarrierSink {
+ entered: Arc<tokio::sync::Notify>,
+ release: Arc<tokio::sync::Notify>,
+ first: AtomicBool,
+ recorded: Arc<Mutex<Vec<CohortMembershipChange>>>,
+}
+
+impl BarrierSink {
+ fn new() -> (
+ Arc<Self>,
+ Arc<tokio::sync::Notify>,
+ Arc<tokio::sync::Notify>,
+ ) {
+ let entered = Arc::new(tokio::sync::Notify::new());
+ let release = Arc::new(tokio::sync::Notify::new());
+ let sink = Arc::new(Self {
+ entered: entered.clone(),
+ release: release.clone(),
+ first: AtomicBool::new(true),
+ recorded: Arc::new(Mutex::new(Vec::new())),
+ });
+ (sink, entered, release)
+ }
+
+ fn recorded_len(&self) -> usize {
+ self.recorded.lock().expect("BarrierSink poisoned").len()
+ }
+}
+
+#[async_trait]
+impl MembershipSink for BarrierSink {
+ async fn produce(
+ &self,
+ changes: Vec<CohortMembershipChange>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ if self.first.swap(false, Ordering::SeqCst) {
+ self.entered.notify_one();
+ self.release.notified().await;
+ }
+ let acks = (0..changes.len()).map(|_| Ok(())).collect();
+ self.recorded
+ .lock()
+ .expect("BarrierSink poisoned")
+ .extend(changes);
+ acks
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn does_not_commit_past_a_blocked_produce() {
+ let suffix = Uuid::new_v4();
+ let topic = format!("cohort_stream_events_barrier_{suffix}");
+ let group = format!("cohort-stream-processor-barrier-{suffix}");
+
+ create_topic(&topic).await;
+
+ let producer: FutureProducer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("message.timeout.ms", "10000")
+ .create()
+ .expect("create producer");
+ let p = person(1);
+ let payload = envelope(p, 0, 0);
+ producer
+ .send(
+ FutureRecord::to(&topic)
+ .key(&format!("{TEAM}:{p}"))
+ .payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce event");
+
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store");
+ let catalog = behavioral_catalog();
+
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", &group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create verifier consumer");
+
+ let (sink, entered, release) = BarrierSink::new();
+
+ let mut manager = Manager::builder("barrier-itest")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let shutdown_handle = handle.clone();
+ let _monitor = manager.monitor_background();
+
+ let consumer = build_consumer(
+ &topic,
+ &group,
+ store.clone(),
+ catalog,
+ handle,
+ sink.clone(),
+ Duration::from_millis(100),
+ );
+ let task = tokio::spawn(consumer.process());
+
+ tokio::time::timeout(Duration::from_secs(30), entered.notified())
+ .await
+ .expect("worker reached the produce barrier");
+
+ // Several commit ticks fire while the produce is blocked.
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert_eq!(
+ committed_sum(&verifier, &topic),
+ 0,
+ "no offset may be committed before its produce is acked",
+ );
+ assert_eq!(
+ sink.recorded_len(),
+ 0,
+ "the blocked flush has recorded nothing yet",
+ );
+
+ release.notify_one();
+
+ let start = Instant::now();
+ loop {
+ if committed_sum(&verifier, &topic) == 1 {
+ break;
+ }
+ assert!(
+ start.elapsed() < Duration::from_secs(30),
+ "offset did not advance after releasing the produce",
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ assert_eq!(
+ sink.recorded_len(),
+ 1,
+ "the released flush recorded its change",
+ );
+
+ shutdown_handle.request_shutdown();
+ task.await.expect("consumer task panicked");
+}
+
+/// Whether any produced person has behavioral state under `partition` in `store`.
+fn partition_has_state(store: &CohortStore, partition: i32, lsk: LeafStateKey) -> bool {
+ (1..=PERSONS).any(|n| {
+ let key = Stage1Key {
+ partition_id: partition as u16,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person(n),
+ };
+ store.get_stage1(&key).unwrap().is_some()
+ })
+}
+
+fn distinct_entered(changes: &[CohortMembershipChange]) -> usize {
+ changes
+ .iter()
+ .filter(|change| change.status == MembershipStatus::Entered)
+ .map(|change| change.person_id.clone())
+ .collect::<std::collections::HashSet<_>>()
+ .len()
+}
+
+/// Poll the group's committed-offset sum until it reaches `target` or the deadline elapses.
+async fn wait_for_committed(
+ consumer: &StreamConsumer,
+ topic: &str,
+ target: i64,
+ deadline: Duration,
+) {
+ let start = Instant::now();
+ loop {
+ let sum = committed_sum(consumer, topic);
+ if sum >= target {
+ return;
+ }
+ assert!(
+ start.elapsed() < deadline,
+ "timed out waiting for committed sum to reach {target}; last {sum}",
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn cooperative_sticky_migration_preserves_offsets_and_partition_colocation() {
+ let suffix = Uuid::new_v4();
+ let topic = format!("cohort_stream_events_migrate_{suffix}");
+ let group = format!("cohort-stream-processor-migrate-{suffix}");
+ create_topic(&topic).await;
+
+ let catalog_a = behavioral_catalog();
+ let catalog_b = behavioral_catalog();
+ let lsk = behavioral_lsk(&catalog_a);
+
+ let dir_a = TempDir::new().unwrap();
+ let store_a = CohortStore::open(&StoreConfig {
+ path: dir_a.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store A");
+ let dir_b = TempDir::new().unwrap();
+ let store_b = CohortStore::open(&StoreConfig {
+ path: dir_b.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store B");
+
+ let sink_a = Arc::new(CaptureSink::new());
+ let sink_b = Arc::new(CaptureSink::new());
+
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", &group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create verifier");
+
+ let mut manager = Manager::builder("migrate-itest")
+ .with_trap_signals(false)
+ .build();
+ let handle_a = manager.register(
+ "consumer-a",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let handle_b = manager.register(
+ "consumer-b",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let shutdown = handle_a.clone();
+ let _monitor = manager.monitor_background();
+
+ // Batch 1: only A is up.
+ let batch1 = produce_events(&topic).await;
+ let consumer_a = build_consumer(
+ &topic,
+ &group,
+ store_a.clone(),
+ catalog_a,
+ handle_a,
+ sink_a.clone(),
+ Duration::from_millis(250),
+ );
+ let task_a = tokio::spawn(consumer_a.process());
+ wait_for_committed(&verifier, &topic, batch1 as i64, Duration::from_secs(60)).await;
+
+ // B joins → cooperative-sticky moves ~half the partitions off A.
+ let consumer_b = build_consumer(
+ &topic,
+ &group,
+ store_b.clone(),
+ catalog_b,
+ handle_b,
+ sink_b.clone(),
+ Duration::from_millis(250),
+ );
+ let task_b = tokio::spawn(consumer_b.process());
+
+ // Batch 2: split across both pods.
+ let batch2 = produce_events(&topic).await;
+ let total = (batch1 + batch2) as i64;
+ wait_for_committed(&verifier, &topic, total, Duration::from_secs(60)).await;
+ tokio::time::sleep(Duration::from_secs(2)).await;
+
+ shutdown.request_shutdown();
+ task_a.await.expect("consumer A panicked");
+ task_b.await.expect("consumer B panicked");
+
+ assert_eq!(
+ committed_sum(&verifier, &topic),
+ total,
+ "committed offsets cover every produced event",
+ );
+
+ // Co-location: no partition's state lives in both pods at once.
+ for partition in 0..NUM_PARTITIONS {
+ assert!(
+ !(partition_has_state(&store_a, partition, lsk)
+ && partition_has_state(&store_b, partition, lsk)),
+ "partition {partition} has state in both pods — affinity invariant violated",
+ );
+ }
+ let entered_a = entered_persons(&store_a, lsk);
+ let entered_b = entered_persons(&store_b, lsk);
+ assert_eq!(
+ entered_a + entered_b,
+ PERSONS as usize,
+ "every person has state in exactly one pod (a={entered_a}, b={entered_b})",
+ );
+
+ let mut changes = sink_a.changes();
+ changes.extend(sink_b.changes());
+ assert_eq!(
+ distinct_entered(&changes),
+ PERSONS as usize,
+ "every person entered exactly once (idempotent re-produce aside)",
+ );
+}
+
+/// Reopen the store at `path` without wiping (durable restore), retrying briefly while the previous
+/// tenure's rebalance-worker task finishes dropping its store handle and releases the RocksDB lock.
+async fn reopen_store_live(path: std::path::PathBuf) -> CohortStore {
+ let config = StoreConfig {
+ path,
+ wipe_on_start: false,
+ ..StoreConfig::default()
+ };
+ let start = Instant::now();
+ loop {
+ match CohortStore::open(&config) {
+ Ok(store) => return store,
+ Err(_) if start.elapsed() < Duration::from_secs(10) => {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ Err(err) => panic!("failed to reopen store live: {err}"),
+ }
+ }
+}
+
+/// End-to-end through a real broker: a durable-restore consumer folds every person in and
+/// fsync-commits; the store is reopened live (no wipe) and must (i) lose no Kafka offsets, (ii)
+/// preserve every member's state — a wipe+replay would be empty, since the committed offset already
+/// covers every event — and (iii) fire each now-dormant member's `Left` from the rebuilt queue.
+///
+/// This is the graceful-restart shape. The hard-crash hazard (a committed offset ahead of un-fsync'd
+/// state) needs a separately killed process to observe `committed > durable`; a graceful in-process
+/// drop always flushes RocksDB on close.
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {
+ let suffix = Uuid::new_v4();
+ let topic = format!("cohort_stream_events_durable_{suffix}");
+ let group = format!("cohort-stream-processor-durable-{suffix}");
+
+ create_topic(&topic).await;
+ let total = produce_events(&topic).await;
+
+ let dir = TempDir::new().unwrap();
+ let store_path = dir.path().join("db");
+ let lsk = behavioral_lsk(&behavioral_catalog());
+
+ // Reads committed offsets without joining the group.
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", &group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create verifier consumer");
+
+ // --- Tenure 1: a durable-restore consumer folds every person in and fsync-commits. ---
+ {
+ let store = CohortStore::open(&StoreConfig {
+ path: store_path.clone(),
+ ..StoreConfig::default()
+ })
+ .expect("open store");
+ let mut manager = Manager::builder("durable-itest-1")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let shutdown_handle = handle.clone();
+ let _monitor = manager.monitor_background();
+ let consumer = build_consumer_with_restore(
+ &topic,
+ &group,
+ store.clone(),
+ behavioral_catalog(),
+ handle,
+ Arc::new(CaptureSink::new()),
+ Duration::from_millis(250),
+ true,
+ );
+ let task = tokio::spawn(consumer.process());
+
+ let start = Instant::now();
+ while committed_sum(&verifier, &topic) != total as i64 {
+ assert!(
+ start.elapsed() < Duration::from_secs(60),
+ "tenure 1: timed out waiting for committed offsets to reach {total}",
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ shutdown_handle.request_shutdown();
+ task.await.expect("tenure-1 consumer panicked");
+ assert_eq!(
+ entered_persons(&store, lsk),
+ PERSONS as usize,
+ "tenure 1 folded every produced person into the behavioral leaf",
+ );
+ } // store drops here, releasing the RocksDB lock
+
+ // --- Restart: reopen the same store live. ---
+ let store2 = reopen_store_live(store_path).await;
+ assert_eq!(
+ entered_persons(&store2, lsk),
+ PERSONS as usize,
+ "reopen-live preserved every member across the restart (a wipe would read 0)",
+ );
+ assert_eq!(
+ committed_sum(&verifier, &topic),
+ total as i64,
+ "no Kafka loss: committed offsets are unchanged across the restart",
+ );
+
+ // --- Dormant Left: durable workers re-seed queues from cf_stage1; a sweep past the window
+ // evicts each member with no new events. ---
+ let catalog = Arc::new(behavioral_catalog());
+ let sink = Arc::new(CaptureSink::new());
+ let far_future = 4_000_000_000_000i64; // ~year 2096, well past every BASE_TS + 7d deadline
+ for partition in 0..NUM_PARTITIONS {
+ let (tx, rx) = mpsc::channel(4);
+ let worker = Stage1Worker::spawn(
+ partition as u16,
+ rx,
+ store2.clone(),
+ catalog.clone(),
+ sink.clone(),
+ Arc::new(OffsetTracker::new()),
+ MergeWorkerDeps::capture(),
+ true,
+ );
+ tx.send(vec![ShuffleMessage::Sweep {
+ due_before_ms: far_future,
+ }])
+ .await
+ .unwrap();
+ drop(tx);
+ worker.join().await.unwrap();
+ }
+ let lefts = sink
+ .changes()
+ .iter()
+ .filter(|change| change.status == MembershipStatus::Left)
+ .count();
+ assert_eq!(
+ lefts, PERSONS as usize,
+ "every restored-then-dormant member emits a Left from the rebuilt eviction queue",
+ );
+
+ delete_topic(&topic).await;
+}
+
+// ===========================================================================================
+// S3/PVC disaster-recovery e2e. Needs a broker AND an S3-compatible store; see the module docs.
+// ===========================================================================================
+
+/// Build a `Config` for the disaster-recovery e2e. `store_path` and `checkpoint_local_dir` must be
+/// separate temp subtrees: rocksdb hard-links SSTs into the checkpoint, so it must be a *sibling* of
+/// the store, never nested.
+fn s3_restore_config(
+ store_path: &std::path::Path,
+ checkpoint_dir: &std::path::Path,
+ prefix: &str,
+) -> Config {
+ let mut env: HashMap<String, String> = HashMap::new();
+ env.insert("CHECKPOINT_ENABLED".into(), "true".into());
+ env.insert("DURABLE_RESTORE_ENABLED".into(), "true".into());
+ env.insert("KAFKA_HOSTS".into(), bootstrap_servers());
+ env.insert(
+ "STORE_PATH".into(),
+ store_path.to_string_lossy().into_owned(),
+ );
+ env.insert(
+ "CHECKPOINT_LOCAL_DIR".into(),
+ checkpoint_dir.to_string_lossy().into_owned(),
+ );
+ env.insert("CHECKPOINT_S3_PREFIX".into(), prefix.to_string());
+ env.insert("CHECKPOINT_S3_FORCE_PATH_STYLE".into(), "true".into());
+ // S3 connection from the runner's environment (MinIO/SeaweedFS).
+ for key in [
+ "CHECKPOINT_S3_BUCKET",
+ "CHECKPOINT_S3_ENDPOINT",
+ "CHECKPOINT_S3_REGION",
+ "CHECKPOINT_S3_ACCESS_KEY_ID",
+ "CHECKPOINT_S3_SECRET_ACCESS_KEY",
+ ] {
+ if let Ok(value) = std::env::var(key) {
+ env.insert(key.into(), value);
+ }
+ }
+ Config::init_from_hashmap(&env).expect("build s3-restore config")
+}
+
+/// Like [`build_consumer_with_restore`], but threads the restore `manifest` into the consumer so it
+/// seeks the events topic to the restored committed offsets on boot.
+#[allow(clippy::too_many_arguments)]
+fn build_consumer_with_manifest(
+ topic: &str,
+ group: &str,
+ store: CohortStore,
+ catalog: CatalogHandle,
+ handle: lifecycle::Handle,
+ sink: Arc<dyn MembershipSink>,
+ offset_commit_interval: Duration,
+ manifest: Option<OffsetManifest>,
+) -> CohortStreamEventsConsumer {
+ let dispatcher = Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store,
+ Arc::new(catalog),
+ sink,
+ MergeWorkerDeps::capture(),
+ ));
+ dispatcher.enable_durable_restore();
+
+ let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());
+ let consumer: StreamConsumer<CohortConsumerContext> = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "earliest")
+ .set("partition.assignment.strategy", "cooperative-sticky")
+ .set("session.timeout.ms", "6000")
+ .create_with_context(context)
+ .expect("create consumer");
+ consumer.subscribe(&[topic]).expect("subscribe");
+
+ let (consumer_command_tx, consumer_command_rx) = mpsc::unbounded_channel();
+ tokio::spawn(run_rebalance_worker(
+ rebalance_rx,
+ dispatcher.clone(),
+ Arc::new(NoopMirror),
+ consumer_command_tx,
+ handle.shutdown_token(),
+ ));
+
+ CohortStreamEventsConsumer::new(
+ consumer,
+ topic.to_string(),
+ dispatcher,
+ handle,
+ 100,
+ Duration::from_millis(200),
+ offset_commit_interval,
+ NUM_PARTITIONS as usize,
+ consumer_command_rx,
+ manifest,
+ )
+}
+
+/// Read each partition's committed offset from the broker into a `partition -> next-offset` map — the
+/// next-to-consume position the manifest must carry.
+fn committed_offsets_map(consumer: &StreamConsumer, topic: &str) -> HashMap<i32, i64> {
+ let mut tpl = TopicPartitionList::new();
+ for partition in 0..NUM_PARTITIONS {
+ tpl.add_partition(topic, partition);
+ }
+ let committed = consumer
+ .committed_offsets(tpl, Duration::from_secs(5))
+ .expect("fetch committed offsets");
+ (0..NUM_PARTITIONS)
+ .filter_map(|partition| {
+ committed
+ .find_partition(topic, partition)
+ .and_then(|elem| match elem.offset() {
+ Offset::Offset(value) => Some((partition, value)),
+ _ => None,
+ })
+ })
+ .collect()
+}
+
+/// Delete every S3 object under the configured prefix on test exit. Best-effort: builds a throwaway
+/// `object_store` client from the durability config and sweeps the per-test prefix. Any error
+/// building, listing, or deleting is ignored so cleanup never fails a passing test.
+async fn delete_s3_prefix(config: &Config) {
+ use futures::StreamExt;
+ use object_store::aws::AmazonS3Builder;
+ use object_store::path::Path as ObjPath;
+ use object_store::{ClientOptions, ObjectStore, ObjectStoreExt};
+
+ let d = config.durability_config();
+ let mut builder = AmazonS3Builder::from_env()
+ .with_bucket_name(&d.s3_bucket)
+ .with_client_options(ClientOptions::new());
+ if let Some(region) = d.aws_region.as_deref() {
+ builder = builder.with_region(region);
+ }
+ if let Some(endpoint) = d.s3_endpoint.as_deref() {
+ builder = builder.with_endpoint(endpoint);
+ if endpoint.starts_with("http://") {
+ builder = builder.with_allow_http(true);
+ }
+ }
+ if let (Some(ak), Some(sk)) = (
+ d.s3_access_key_id.as_deref(),
+ d.s3_secret_access_key.as_deref(),
+ ) {
+ builder = builder.with_access_key_id(ak).with_secret_access_key(sk);
+ }
+ if d.s3_force_path_style {
+ builder = builder.with_virtual_hosted_style_request(false);
+ }
+ let store = match builder.build() {
+ Ok(store) => store,
+ Err(_) => return,
+ };
+ let prefix = ObjPath::from(d.s3_key_prefix.as_str());
+ let mut stream = store.list(Some(&prefix));
+ while let Some(entry) = stream.next().await {
+ if let Ok(meta) = entry {
+ let _result = store.delete(&meta.location).await;
+ }
+ }
+}
+
+/// Full disaster-recovery path through a real broker + S3: fold + checkpoint to S3 (tenure 1), delete
+/// the store + checkpoint dirs (PVC loss), then restore from S3 and seek the manifest offsets (tenure
+/// 2). Asserts state is restored (not cold-replayed), the resume neither skips nor re-folds, and a
+/// dormant `Left` fires from the eviction queue rebuilt over the restored `cf_stage1`.
+///
+/// Asserting count-exact (not mere presence) sidesteps the documented fast-broker flake.
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS) AND an S3-compatible store (CHECKPOINT_S3_*); see module docs"]
+async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant_left() {
+ let suffix = Uuid::new_v4();
+ let topic = format!("cohort_stream_events_s3restore_{suffix}");
+ let group = format!("cohort-stream-processor-s3restore-{suffix}");
+ let prefix = format!("cohort-stream-checkpoints-itest/{suffix}");
+
+ create_topic(&topic).await;
+ let total = produce_events(&topic).await;
+
+ // Store and checkpoint dirs must be sibling subtrees, never nested (see `s3_restore_config`).
+ let root = TempDir::new().unwrap();
+ let store_path = root.path().join("db");
+ let checkpoint_dir = root.path().join("checkpoints");
+ let config = s3_restore_config(&store_path, &checkpoint_dir, &prefix);
+ let lsk = behavioral_lsk(&behavioral_catalog());
+
+ // Reads committed offsets without joining the group.
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", &group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create verifier consumer");
+
+ // --- Tenure 1: fold + fsync-commit, then checkpoint + upload to S3. ---
+ {
+ let store = CohortStore::open(&config.store_config()).expect("open tenure-1 store");
+ let mut manager = Manager::builder("s3restore-itest-1")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let shutdown_handle = handle.clone();
+ let _monitor = manager.monitor_background();
+ let consumer = build_consumer_with_restore(
+ &topic,
+ &group,
+ store.clone(),
+ behavioral_catalog(),
+ handle,
+ Arc::new(CaptureSink::new()),
+ Duration::from_millis(250),
+ true,
+ );
+ let task = tokio::spawn(consumer.process());
+
+ let start = Instant::now();
+ while committed_sum(&verifier, &topic) != total as i64 {
+ assert!(
+ start.elapsed() < Duration::from_secs(60),
+ "tenure 1: timed out waiting for committed offsets to reach {total}",
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ shutdown_handle.request_shutdown();
+ task.await.expect("tenure-1 consumer panicked");
+ assert_eq!(
+ entered_persons(&store, lsk),
+ PERSONS as usize,
+ "tenure 1 folded every produced person",
+ );
+
+ // Drive one checkpoint tick directly: a dispatcher owning all partitions + an events tracker
+ // seeded from the broker's committed offsets, so the captured manifest carries the resume
+ // positions. upload_every_n = 1 ⇒ the first tick uploads.
+ let ckpt_dispatcher = Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store.clone(),
+ Arc::new(behavioral_catalog()),
+ Arc::new(CaptureSink::new()),
+ MergeWorkerDeps::capture(),
+ ));
+ let events_tracker = Arc::new(OffsetTracker::new());
+ for (partition, next_offset) in committed_offsets_map(&verifier, &topic) {
+ ckpt_dispatcher.assign_partition(partition);
+ // Seed committed so `OffsetManifest::capture` (which reads committed_offset) records it.
+ events_tracker.mark_dispatched(partition, next_offset);
+ let _ = events_tracker.mark_processed(partition, next_offset);
+ events_tracker.mark_committed(partition, next_offset);
+ }
+ let uploader = S3Uploader::new(config.durability_config())
+ .await
+ .expect("build S3 uploader (is the bucket reachable?)");
+ let exporter = CheckpointExporter::new(Box::new(uploader));
+ let sweeper = CheckpointSweeper::new(
+ store.clone(),
+ ckpt_dispatcher,
+ vec![(topic.clone(), events_tracker)],
+ exporter,
+ config.durability_config(),
+ checkpoint_dir.clone(),
+ upload_cadence(
+ config.checkpoint_interval_ms,
+ config.checkpoint_s3_upload_interval_ms,
+ ),
+ );
+ sweeper.run_once().await;
+ } // tenure-1 store + dispatcher drop here, releasing the RocksDB lock
+
+ // --- PVC loss: delete BOTH the live store and the local checkpoint dir. ---
+ std::fs::remove_dir_all(&store_path).expect("remove store_path (simulate PVC loss)");
+ std::fs::remove_dir_all(&checkpoint_dir)
+ .expect("remove checkpoint_local_dir (simulate PVC loss)");
+
+ // --- Tenure 2: restore from S3 + seek the manifest offsets. ---
+ let restore = run_boot_restore(&config, &store_path).await;
+ assert_eq!(
+ restore.source,
+ RestoreSource::S3,
+ "with the live store and local checkpoint gone, the restore must come from S3",
+ );
+ let manifest = restore
+ .manifest
+ .clone()
+ .expect("an S3 restore yields an offset manifest to seek");
+
+ let store2 = CohortStore::open(&StoreConfig {
+ path: store_path.clone(),
+ wipe_on_start: false,
+ ..StoreConfig::default()
+ })
+ .expect("open restored store");
+ // (a) Full state present — restored from S3, not cold-replayed. Count-exact (not mere presence).
+ assert_eq!(
+ entered_persons(&store2, lsk),
+ PERSONS as usize,
+ "the S3 restore re-seeded every member's state (a cold start would read 0)",
+ );
+
+ let mut manager = Manager::builder("s3restore-itest-2")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let shutdown_handle = handle.clone();
+ let _monitor = manager.monitor_background();
+ let consumer = build_consumer_with_manifest(
+ &topic,
+ &group,
+ store2.clone(),
+ behavioral_catalog(),
+ handle,
+ Arc::new(CaptureSink::new()),
+ Duration::from_millis(250),
+ Some(manifest),
+ );
+ let task = tokio::spawn(consumer.process());
+
+ // (b) Resumes at the manifest offset: no skip and no re-fold. Let the loop settle, seek, and idle;
+ // with no events past `total`, committed must stay exactly `total`.
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ shutdown_handle.request_shutdown();
+ task.await.expect("tenure-2 consumer panicked");
+ assert_eq!(
+ committed_sum(&verifier, &topic),
+ total as i64,
+ "resumed exactly at the manifest offset — no skip, no re-fold past the committed position",
+ );
+ assert_eq!(
+ entered_persons(&store2, lsk),
+ PERSONS as usize,
+ "state count is still exact after the restore-seek resume",
+ );
+
+ // (c) Dormant Left: workers re-seed the eviction queue from the restored cf_stage1, then a sweep
+ // past the window evicts every now-dormant member.
+ let catalog = Arc::new(behavioral_catalog());
+ let left_sink = Arc::new(CaptureSink::new());
+ let far_future = 4_000_000_000_000i64; // ~year 2096, past every BASE_TS + 7d deadline
+ for partition in 0..NUM_PARTITIONS {
+ let (tx, rx) = mpsc::channel(4);
+ let worker = Stage1Worker::spawn(
+ partition as u16,
+ rx,
+ store2.clone(),
+ catalog.clone(),
+ left_sink.clone(),
+ Arc::new(OffsetTracker::new()),
+ MergeWorkerDeps::capture(),
+ true,
+ );
+ tx.send(vec![ShuffleMessage::Sweep {
+ due_before_ms: far_future,
+ }])
+ .await
+ .unwrap();
+ drop(tx);
+ worker.join().await.unwrap();
+ }
+ let lefts = left_sink
+ .changes()
+ .iter()
+ .filter(|change| change.status == MembershipStatus::Left)
+ .count();
+ assert_eq!(
+ lefts, PERSONS as usize,
+ "every restored-then-dormant member emits a Left from the eviction queue rebuilt over the S3-restored cf_stage1",
+ );
+
+ // --- Cleanup: delete the topic and the S3 prefix. ---
+ delete_topic(&topic).await;
+ delete_s3_prefix(&config).await;
+}
diff --git a/rust/cohort-stream-processor/tests/filter_catalog.rs b/rust/cohort-stream-processor/tests/filter_catalog.rs
new file mode 100644
index 000000000000..b0f28984c0c1
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/filter_catalog.rs
@@ -0,0 +1,327 @@
+//! Public-API integration tests for the filter catalog. The exhaustive per-field discrimination
+//! matrix and classifier edge cases live in the in-crate `#[cfg(test)]` modules.
+
+use cohort_stream_processor::filters::{
+ build_catalog_from_rows, CohortId, CohortLeaf, CohortRow, FilterCatalog, FilterNode, TeamId,
+};
+use cohort_stream_processor::stage2::{CohortEligibility, ExcludedReason};
+use serde_json::{json, Value};
+
+fn build_catalog(rows: Vec<CohortRow>) -> FilterCatalog {
+ build_catalog_from_rows(rows, false)
+}
+
+const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";
+const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
+
+fn row(id: i32, team_id: i32, filters: Value) -> CohortRow {
+ CohortRow {
+ id,
+ team_id,
+ filters,
+ timezone: "UTC".to_string(),
+ }
+}
+
+fn behavioral_bytecode() -> Value {
+ json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
+}
+
+/// The conditionHash encodes the event matcher, not the `time_value` window — same hash, any window.
+fn behavioral_performed_event(time_value: i64) -> Value {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": time_value,
+ "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": behavioral_bytecode(),
+ })
+}
+
+fn person_leaf() -> Value {
+ json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+}
+
+fn cohort_ref(id: i32) -> Value {
+ json!({ "type": "cohort", "value": id, "negation": false })
+}
+
+fn cohort(values: Vec<Value>) -> Value {
+ json!({ "properties": { "type": "AND", "values": values } })
+}
+
+#[test]
+fn same_hash_different_windows_produce_distinct_leaf_state_keys() {
+ let catalog = build_catalog(vec![
+ row(1, 7, cohort(vec![behavioral_performed_event(7)])),
+ row(2, 7, cohort(vec![behavioral_performed_event(30)])),
+ ]);
+
+ let team = catalog.team(TeamId(7)).expect("team 7 present");
+
+ assert_eq!(team.by_condition_to_lsk[&BEHAVIORAL_HASH].len(), 2);
+ assert_eq!(
+ team.by_condition_to_cohorts[&BEHAVIORAL_HASH],
+ vec![CohortId(1), CohortId(2)],
+ );
+ // One conditionHash → one HogVM bytecode evaluation, despite two distinct windows.
+ assert_eq!(team.unique_condition_hashes.len(), 1);
+}
+
+#[test]
+fn behavioral_and_person_indexed_cohort_ref_kept_in_tree_only() {
+ let catalog = build_catalog(vec![row(
+ 1,
+ 7,
+ cohort(vec![
+ behavioral_performed_event(7),
+ person_leaf(),
+ cohort_ref(99),
+ ]),
+ )]);
+
+ let team = catalog.team(TeamId(7)).expect("team 7 present");
+
+ assert_eq!(team.unique_condition_hashes.len(), 2);
+ assert!(team.by_condition_to_lsk.contains_key(&BEHAVIORAL_HASH));
+ assert!(team.by_condition_to_lsk.contains_key(&PERSON_HASH));
+ assert_eq!(team.by_condition_to_lsk.len(), 2);
+
+ // Cohort ref is kept in the parsed tree (no conditionHash, so not in the index).
+ let tree = &team.cohorts[&CohortId(1)];
+ let FilterNode::Group { children, .. } = &tree.root else {
+ panic!("root should be a group");
+ };
+ assert_eq!(children.len(), 3, "cohort ref must remain a tree node");
+ let cohort_refs = children
+ .iter()
+ .filter(|child| matches!(child, FilterNode::Leaf(CohortLeaf::CohortRef(_))))
+ .count();
+ assert_eq!(cohort_refs, 1);
+}
+
+#[test]
+fn dropped_leaves_are_skipped_while_survivors_stay_indexed() {
+ // Drop cases: missing conditionHash, unsupported behavioral value, action-keyed (int key).
+ let catalog = build_catalog(vec![row(
+ 1,
+ 7,
+ cohort(vec![
+ behavioral_performed_event(7),
+ json!({ "type": "behavioral", "value": "performed_event", "key": "$click" }),
+ json!({
+ "type": "behavioral",
+ "value": "performed_event_sequence",
+ "key": "$pageview",
+ "conditionHash": "0123456789abcdef",
+ }),
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": 4242,
+ "conditionHash": "0123456789abcdef",
+ }),
+ ]),
+ )]);
+
+ let team = catalog.team(TeamId(7)).expect("team 7 present");
+ assert_eq!(team.unique_condition_hashes.len(), 1);
+ assert_eq!(team.by_condition_to_lsk[&BEHAVIORAL_HASH].len(), 1);
+}
+
+#[test]
+fn bytecode_is_captured_and_deduped_by_condition_hash() {
+ let catalog = build_catalog(vec![
+ row(
+ 1,
+ 7,
+ cohort(vec![behavioral_performed_event(7), person_leaf()]),
+ ),
+ row(2, 7, cohort(vec![behavioral_performed_event(30)])),
+ ]);
+
+ let team = catalog.team(TeamId(7)).expect("team 7 present");
+ assert_eq!(team.by_condition_to_bytecode.len(), 2);
+ assert_eq!(
+ team.by_condition_to_bytecode[&BEHAVIORAL_HASH].as_ref(),
+ behavioral_bytecode().as_array().unwrap(),
+ );
+ assert!(team.by_condition_to_bytecode.contains_key(&PERSON_HASH));
+}
+
+#[test]
+fn leaf_without_bytecode_is_dropped() {
+ // A conditionHash without inline bytecode is not realtime-executable.
+ let no_bytecode = json!({
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "time_value": 7,
+ "time_interval": "day",
+ "operator": "gte",
+ "operator_value": 3,
+ "conditionHash": "0123456789abcdef",
+ });
+ let catalog = build_catalog(vec![row(1, 7, cohort(vec![no_bytecode]))]);
+
+ let team = catalog.team(TeamId(7)).expect("team 7 present");
+ assert!(team.unique_condition_hashes.is_empty());
+ assert!(team.by_condition_to_bytecode.is_empty());
+ assert!(team.by_condition_to_lsk.is_empty());
+}
+
+#[test]
+fn teams_are_isolated() {
+ let catalog = build_catalog(vec![
+ row(1, 7, cohort(vec![behavioral_performed_event(7)])),
+ row(2, 8, cohort(vec![person_leaf()])),
+ ]);
+
+ let team7 = catalog.team(TeamId(7)).expect("team 7 present");
+ assert!(team7.by_condition_to_lsk.contains_key(&BEHAVIORAL_HASH));
+ assert!(!team7.by_condition_to_lsk.contains_key(&PERSON_HASH));
+
+ let team8 = catalog.team(TeamId(8)).expect("team 8 present");
+ assert!(team8.by_condition_to_lsk.contains_key(&PERSON_HASH));
+ assert!(!team8.by_condition_to_lsk.contains_key(&BEHAVIORAL_HASH));
+
+ assert_eq!(catalog.team_count(), 2);
+}
+
+#[test]
+fn or_group_of_two_person_leaves_is_not_sibling_merged() {
+ let other_person = json!({
+ "type": "person",
+ "key": "name",
+ "value": "x",
+ "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "x", 32, "name", 32, "properties", 32, "person", 1, 3, 11],
+ });
+ let catalog = build_catalog(vec![row(
+ 1,
+ 7,
+ json!({ "properties": { "type": "OR", "values": [person_leaf(), other_person] } }),
+ )]);
+
+ let tree = &catalog.team(TeamId(7)).unwrap().cohorts[&CohortId(1)];
+ let FilterNode::Group { children, .. } = &tree.root else {
+ panic!("root should be a group");
+ };
+ assert_eq!(
+ children.len(),
+ 2,
+ "single-property siblings must not be merged"
+ );
+}
+
+#[test]
+fn cycle_of_realtime_cohorts_is_excluded_cycle_detected() {
+ let catalog = build_catalog(vec![
+ row(1, 7, cohort(vec![cohort_ref(2)])),
+ row(2, 7, cohort(vec![cohort_ref(3)])),
+ row(3, 7, cohort(vec![cohort_ref(1)])),
+ row(
+ 4,
+ 7,
+ cohort(vec![behavioral_performed_event(7), person_leaf()]),
+ ),
+ ]);
+ let team = catalog.team(TeamId(7)).expect("team 7 present");
+
+ for id in [1, 2, 3] {
+ assert_eq!(
+ team.eligibility[&CohortId(id)],
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected),
+ "cohort {id} is a cycle member",
+ );
+ }
+ assert_eq!(
+ team.eligibility[&CohortId(4)],
+ CohortEligibility::Stage2Composable,
+ "the composable sibling is untouched by the cycle",
+ );
+}
+
+#[test]
+fn self_referencing_cohort_is_cycle_detected() {
+ let catalog = build_catalog(vec![row(1, 7, cohort(vec![cohort_ref(1)]))]);
+ let team = catalog.team(TeamId(7)).expect("team 7 present");
+ assert_eq!(
+ team.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::CycleDetected),
+ );
+}
+
+#[test]
+fn ref_to_unloaded_cohort_is_unresolved_ref() {
+ let catalog = build_catalog(vec![row(1, 7, cohort(vec![cohort_ref(99)]))]);
+ let team = catalog.team(TeamId(7)).expect("team 7 present");
+ assert_eq!(
+ team.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+}
+
+#[test]
+fn ref_to_another_teams_cohort_is_unresolved_ref() {
+ // Reference graph is team-scoped: cohort 2 exists only in team 8, so from team 7's view it is missing.
+ let catalog = build_catalog(vec![
+ row(1, 7, cohort(vec![cohort_ref(2)])),
+ row(2, 8, cohort(vec![person_leaf()])),
+ ]);
+ assert_eq!(
+ catalog.team(TeamId(7)).expect("team 7").eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::UnresolvedRef),
+ );
+ assert!(matches!(
+ catalog.team(TeamId(8)).expect("team 8").eligibility[&CohortId(2)],
+ CohortEligibility::SingleLeaf(_),
+ ));
+}
+
+#[test]
+fn resolvable_ref_stays_has_cohort_ref_and_contributes_no_emit_mapping() {
+ // Cohort 1 → cohort 2 (resolvable): stays `HasCohortRef` (transport-sizing class), appears in
+ // neither emit map — it drives no single-leaf or composable membership.
+ let catalog = build_catalog(vec![
+ row(1, 7, cohort(vec![cohort_ref(2)])),
+ row(2, 7, cohort(vec![behavioral_performed_event(7)])),
+ ]);
+ let team = catalog.team(TeamId(7)).expect("team 7 present");
+
+ assert_eq!(
+ team.eligibility[&CohortId(1)],
+ CohortEligibility::Excluded(ExcludedReason::HasCohortRef),
+ );
+ assert!(matches!(
+ team.eligibility[&CohortId(2)],
+ CohortEligibility::SingleLeaf(_),
+ ));
+
+ let in_single = team
+ .by_lsk_to_single_leaf_cohorts
+ .values()
+ .any(|owners| owners.contains(&CohortId(1)));
+ let in_composable = team
+ .by_lsk_to_composable_cohorts
+ .values()
+ .any(|owners| owners.contains(&CohortId(1)));
+ assert!(
+ !in_single,
+ "a ref-bearing cohort drives no single-leaf membership",
+ );
+ assert!(
+ !in_composable,
+ "a ref-bearing cohort is not composable, so it owns no composable mapping",
+ );
+}
diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_pageview_browser_set_match.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_pageview_browser_set_match.json
new file mode 100644
index 000000000000..d3bd540074a6
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_pageview_browser_set_match.json
@@ -0,0 +1,76 @@
+{
+ "bytecode": [
+ "_H",
+ 1,
+ 32,
+ "$pageview",
+ 32,
+ "event",
+ 1,
+ 1,
+ 11,
+ 31,
+ 32,
+ "$browser",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 12,
+ 3,
+ 2
+ ],
+ "expected_result": true,
+ "globals": {
+ "$group_0": null,
+ "$group_1": null,
+ "$group_2": null,
+ "$group_3": null,
+ "$group_4": null,
+ "distinct_id": "d-1",
+ "elements_chain": "",
+ "elements_chain_elements": [],
+ "elements_chain_href": "",
+ "elements_chain_ids": [],
+ "elements_chain_texts": [],
+ "event": "$pageview",
+ "group_0": {
+ "properties": {}
+ },
+ "group_1": {
+ "properties": {}
+ },
+ "group_2": {
+ "properties": {}
+ },
+ "group_3": {
+ "properties": {}
+ },
+ "group_4": {
+ "properties": {}
+ },
+ "pdi": {
+ "distinct_id": "d-1",
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "person_id": "p-123"
+ },
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "properties": {
+ "$browser": "Chrome"
+ },
+ "timestamp": "2026-05-26T12:34:56.789Z",
+ "uuid": "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ "variables": {}
+ },
+ "name": "behavioral_pageview_browser_set_match"
+}
diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_pageview_browser_set_wrong_event.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_pageview_browser_set_wrong_event.json
new file mode 100644
index 000000000000..f0387c723452
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_pageview_browser_set_wrong_event.json
@@ -0,0 +1,76 @@
+{
+ "bytecode": [
+ "_H",
+ 1,
+ 32,
+ "$pageview",
+ 32,
+ "event",
+ 1,
+ 1,
+ 11,
+ 31,
+ 32,
+ "$browser",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 12,
+ 3,
+ 2
+ ],
+ "expected_result": false,
+ "globals": {
+ "$group_0": null,
+ "$group_1": null,
+ "$group_2": null,
+ "$group_3": null,
+ "$group_4": null,
+ "distinct_id": "d-1",
+ "elements_chain": "",
+ "elements_chain_elements": [],
+ "elements_chain_href": "",
+ "elements_chain_ids": [],
+ "elements_chain_texts": [],
+ "event": "$autocapture",
+ "group_0": {
+ "properties": {}
+ },
+ "group_1": {
+ "properties": {}
+ },
+ "group_2": {
+ "properties": {}
+ },
+ "group_3": {
+ "properties": {}
+ },
+ "group_4": {
+ "properties": {}
+ },
+ "pdi": {
+ "distinct_id": "d-1",
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "person_id": "p-123"
+ },
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "properties": {
+ "$browser": "Chrome"
+ },
+ "timestamp": "2026-05-26T12:34:56.789Z",
+ "uuid": "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ "variables": {}
+ },
+ "name": "behavioral_pageview_browser_set_wrong_event"
+}
diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_pageview_browser_unset.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_pageview_browser_unset.json
new file mode 100644
index 000000000000..7ba12cd4a22a
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_pageview_browser_unset.json
@@ -0,0 +1,74 @@
+{
+ "bytecode": [
+ "_H",
+ 1,
+ 32,
+ "$pageview",
+ 32,
+ "event",
+ 1,
+ 1,
+ 11,
+ 31,
+ 32,
+ "$browser",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 12,
+ 3,
+ 2
+ ],
+ "expected_result": false,
+ "globals": {
+ "$group_0": null,
+ "$group_1": null,
+ "$group_2": null,
+ "$group_3": null,
+ "$group_4": null,
+ "distinct_id": "d-1",
+ "elements_chain": "",
+ "elements_chain_elements": [],
+ "elements_chain_href": "",
+ "elements_chain_ids": [],
+ "elements_chain_texts": [],
+ "event": "$pageview",
+ "group_0": {
+ "properties": {}
+ },
+ "group_1": {
+ "properties": {}
+ },
+ "group_2": {
+ "properties": {}
+ },
+ "group_3": {
+ "properties": {}
+ },
+ "group_4": {
+ "properties": {}
+ },
+ "pdi": {
+ "distinct_id": "d-1",
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "person_id": "p-123"
+ },
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "properties": {},
+ "timestamp": "2026-05-26T12:34:56.789Z",
+ "uuid": "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ "variables": {}
+ },
+ "name": "behavioral_pageview_browser_unset"
+}
diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_ordering.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_ordering.json
new file mode 100644
index 000000000000..e3f4d30ececa
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_ordering.json
@@ -0,0 +1,37 @@
+{
+ "name": "to_datetime_ordering_lt",
+ "oracle": "clickhouse",
+ "note": "toDateTime instant ordering: Lt(toDateTime(toString(person.properties.signup_date)), toDateTime(\"2026-01-01 00:00:00\")). expected_result is the ClickHouse/instant-ordering answer the Rust VM matches; the Python/TS reference VMs cannot order Hog temporals, so this is a Rust-vs-ClickHouse oracle, not a cross-runtime one. See the module-level provenance caveat.",
+ "bytecode": [
+ "_H",
+ 1,
+ 32,
+ "2026-01-01 00:00:00",
+ 2,
+ "toDateTime",
+ 1,
+ 32,
+ "signup_date",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 2,
+ "toString",
+ 1,
+ 2,
+ "toDateTime",
+ 1,
+ 15
+ ],
+ "expected_result": true,
+ "globals": {
+ "person": {
+ "properties": {
+ "signup_date": "2024-09-09 08:30:00"
+ }
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/isnull_numeric_gte_below.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/isnull_numeric_gte_below.json
new file mode 100644
index 000000000000..aca1aa5aef23
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/isnull_numeric_gte_below.json
@@ -0,0 +1,89 @@
+{
+ "bytecode": [
+ "_H",
+ 1,
+ 32,
+ "$screen_height",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 2,
+ "isNull",
+ 1,
+ 33,
+ 500,
+ 2,
+ "isNull",
+ 1,
+ 4,
+ 2,
+ 40,
+ 3,
+ 30,
+ 39,
+ 9,
+ 33,
+ 500,
+ 32,
+ "$screen_height",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 14
+ ],
+ "expected_result": false,
+ "globals": {
+ "$group_0": null,
+ "$group_1": null,
+ "$group_2": null,
+ "$group_3": null,
+ "$group_4": null,
+ "distinct_id": "d-1",
+ "elements_chain": "",
+ "elements_chain_elements": [],
+ "elements_chain_href": "",
+ "elements_chain_ids": [],
+ "elements_chain_texts": [],
+ "event": "$pageview",
+ "group_0": {
+ "properties": {}
+ },
+ "group_1": {
+ "properties": {}
+ },
+ "group_2": {
+ "properties": {}
+ },
+ "group_3": {
+ "properties": {}
+ },
+ "group_4": {
+ "properties": {}
+ },
+ "pdi": {
+ "distinct_id": "d-1",
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "person_id": "p-123"
+ },
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "properties": {
+ "$screen_height": 200
+ },
+ "timestamp": "2026-05-26T12:34:56.789Z",
+ "uuid": "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ "variables": {}
+ },
+ "name": "isnull_numeric_gte_below"
+}
diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/isnull_numeric_gte_match.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/isnull_numeric_gte_match.json
new file mode 100644
index 000000000000..9f26bb677dad
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/isnull_numeric_gte_match.json
@@ -0,0 +1,89 @@
+{
+ "bytecode": [
+ "_H",
+ 1,
+ 32,
+ "$screen_height",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 2,
+ "isNull",
+ 1,
+ 33,
+ 500,
+ 2,
+ "isNull",
+ 1,
+ 4,
+ 2,
+ 40,
+ 3,
+ 30,
+ 39,
+ 9,
+ 33,
+ 500,
+ 32,
+ "$screen_height",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 14
+ ],
+ "expected_result": true,
+ "globals": {
+ "$group_0": null,
+ "$group_1": null,
+ "$group_2": null,
+ "$group_3": null,
+ "$group_4": null,
+ "distinct_id": "d-1",
+ "elements_chain": "",
+ "elements_chain_elements": [],
+ "elements_chain_href": "",
+ "elements_chain_ids": [],
+ "elements_chain_texts": [],
+ "event": "$pageview",
+ "group_0": {
+ "properties": {}
+ },
+ "group_1": {
+ "properties": {}
+ },
+ "group_2": {
+ "properties": {}
+ },
+ "group_3": {
+ "properties": {}
+ },
+ "group_4": {
+ "properties": {}
+ },
+ "pdi": {
+ "distinct_id": "d-1",
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "person_id": "p-123"
+ },
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "properties": {
+ "$screen_height": 800
+ },
+ "timestamp": "2026-05-26T12:34:56.789Z",
+ "uuid": "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ "variables": {}
+ },
+ "name": "isnull_numeric_gte_match"
+}
diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/isnull_numeric_gte_null.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/isnull_numeric_gte_null.json
new file mode 100644
index 000000000000..9fd3923f9c19
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/isnull_numeric_gte_null.json
@@ -0,0 +1,87 @@
+{
+ "bytecode": [
+ "_H",
+ 1,
+ 32,
+ "$screen_height",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 2,
+ "isNull",
+ 1,
+ 33,
+ 500,
+ 2,
+ "isNull",
+ 1,
+ 4,
+ 2,
+ 40,
+ 3,
+ 30,
+ 39,
+ 9,
+ 33,
+ 500,
+ 32,
+ "$screen_height",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 14
+ ],
+ "expected_result": false,
+ "globals": {
+ "$group_0": null,
+ "$group_1": null,
+ "$group_2": null,
+ "$group_3": null,
+ "$group_4": null,
+ "distinct_id": "d-1",
+ "elements_chain": "",
+ "elements_chain_elements": [],
+ "elements_chain_href": "",
+ "elements_chain_ids": [],
+ "elements_chain_texts": [],
+ "event": "$pageview",
+ "group_0": {
+ "properties": {}
+ },
+ "group_1": {
+ "properties": {}
+ },
+ "group_2": {
+ "properties": {}
+ },
+ "group_3": {
+ "properties": {}
+ },
+ "group_4": {
+ "properties": {}
+ },
+ "pdi": {
+ "distinct_id": "d-1",
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "person_id": "p-123"
+ },
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "properties": {},
+ "timestamp": "2026-05-26T12:34:56.789Z",
+ "uuid": "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee",
+ "variables": {}
+ },
+ "name": "isnull_numeric_gte_null"
+}
diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/person_email_exact_match.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/person_email_exact_match.json
new file mode 100644
index 000000000000..0146c00170b0
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/person_email_exact_match.json
@@ -0,0 +1,30 @@
+{
+ "bytecode": [
+ "_H",
+ 1,
+ 32,
+ 32,
+ "email",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 11
+ ],
+ "expected_result": true,
+ "globals": {
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "project": {
+ "id": 42
+ }
+ },
+ "name": "person_email_exact_match"
+}
diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/person_email_exact_non_match.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/person_email_exact_non_match.json
new file mode 100644
index 000000000000..e4bd19030c17
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/person_email_exact_non_match.json
@@ -0,0 +1,30 @@
+{
+ "bytecode": [
+ "_H",
+ 1,
+ 32,
+ 32,
+ "email",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 11
+ ],
+ "expected_result": false,
+ "globals": {
+ "person": {
+ "id": "p-123",
+ "properties": {
+ "email": "[email protected]"
+ }
+ },
+ "project": {
+ "id": 42
+ }
+ },
+ "name": "person_email_exact_non_match"
+}
diff --git a/rust/cohort-stream-processor/tests/hogvm_parity.rs b/rust/cohort-stream-processor/tests/hogvm_parity.rs
new file mode 100644
index 000000000000..7fba8d4e74ec
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/hogvm_parity.rs
@@ -0,0 +1,81 @@
+//! HogVM regression goldens for the supported cohort bytecode surface. Each fixture's
+//! `expected_result` is a committed oracle snapshot from the Python
+//! `common/hogvm/python/execute.py::execute_bytecode` runtime. The test asserts the Rust executor
+//! agrees; it does NOT re-run Python/Node in CI, so a mis-transcribed `expected_result` would
+//! enshrine a wrong answer. An optional shared corpus at
+//! `../common/hogvm/__tests__/cohort_bytecode` is also loaded when present.
+//!
+//! Provenance note: the temporal fixtures (`toDateTime`/`toDate` ordering) are a Rust-vs-ClickHouse
+//! oracle, not a Python one — the reference Python/TS VMs return `false` for Hog temporal ordering,
+//! so `expected_result` reflects the ClickHouse/instant-ordering answer the Rust VM deliberately
+//! matches; see `rust/common/hogvm/tests/datetime.rs`.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use cohort_stream_processor::hogvm::{evaluate_detailed, EvalOutcome};
+use serde_json::Value;
+
+/// A missing directory yields no fixtures (optional corpus); any other read/parse failure panics.
+fn fixtures_in(dir: &Path) -> Vec<(PathBuf, Value)> {
+ let Ok(entries) = fs::read_dir(dir) else {
+ return Vec::new();
+ };
+ let mut fixtures: Vec<(PathBuf, Value)> = entries
+ .map(|entry| entry.expect("read dir entry").path())
+ .filter(|path| path.extension().and_then(|ext| ext.to_str()) == Some("json"))
+ .map(|path| {
+ let data = fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path:?}: {e}"));
+ let value =
+ serde_json::from_str(&data).unwrap_or_else(|e| panic!("parse {path:?}: {e}"));
+ (path, value)
+ })
+ .collect();
+ fixtures.sort_by(|(a, _), (b, _)| a.cmp(b)); // deterministic order for reproducible failures
+ fixtures
+}
+
+fn in_crate_dir() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hogvm_parity")
+}
+
+fn all_fixtures() -> Vec<(PathBuf, Value)> {
+ let mut fixtures = fixtures_in(&in_crate_dir());
+ let corpus =
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../common/hogvm/__tests__/cohort_bytecode");
+ fixtures.extend(fixtures_in(&corpus));
+ fixtures
+}
+
+#[test]
+fn in_crate_fixtures_are_present() {
+ // Guard against an empty in-crate fixture directory silently passing.
+ assert!(
+ !fixtures_in(&in_crate_dir()).is_empty(),
+ "no in-crate parity fixtures in {:?}",
+ in_crate_dir()
+ );
+}
+
+#[test]
+fn rust_executor_matches_python_oracle() {
+ for (path, fixture) in all_fixtures() {
+ let name = fixture["name"].as_str().unwrap_or("<unnamed>");
+ let bytecode = fixture["bytecode"]
+ .as_array()
+ .unwrap_or_else(|| panic!("fixture {path:?} `bytecode` must be an array"));
+ let globals = fixture["globals"].clone();
+ // `unwrap_or(false)` mirrors the Node `?? false` coercion.
+ let expected = fixture["expected_result"].as_bool().unwrap_or(false);
+
+ let actual = match evaluate_detailed(bytecode, globals) {
+ EvalOutcome::Matched(matched) => matched,
+ other => panic!("fixture `{name}` ({path:?}) did not evaluate cleanly: {other:?}"),
+ };
+
+ assert_eq!(
+ actual, expected,
+ "parity mismatch for fixture `{name}` ({path:?}): rust={actual}, oracle={expected}",
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/tests/merge_consumer.rs b/rust/cohort-stream-processor/tests/merge_consumer.rs
new file mode 100644
index 000000000000..99135d4ffc36
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/merge_consumer.rs
@@ -0,0 +1,1510 @@
+//! End-to-end tests for the cross-partition merge protocol against a **real** Kafka broker: the two
+//! follower consumers, the assignment mirror, the keyed transfer / re-key produces, and the
+//! per-topic offset commits, wired exactly like `main.rs`.
+//!
+//! `#[ignore]`d by default (group joins, committed-offset round-trips, and `incremental_assign`
+//! semantics that the in-process `MockCluster` does not exercise faithfully). All topics are created
+//! with the production partition count (64) because the protocol's partition arithmetic is the thing
+//! under test. Run against a local stack serially:
+//!
+//! ```sh
+//! cargo test -p cohort-stream-processor --test merge_consumer -- --ignored --test-threads=1
+//! ```
+//!
+//! Each test deletes its topics on the way out via `with_topics_cleanup`. If that never runs
+//! (killed process), sweep leftovers with:
+//!
+//! ```sh
+//! docker exec posthog-kafka-1 sh -c 'rpk topic list | awk "{print \$1}" \
+//! | grep -E "_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" \
+//! | xargs -r rpk topic delete'
+//! ```
+
+use std::collections::HashSet;
+use std::future::Future;
+use std::panic::AssertUnwindSafe;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use chrono_tz::UTC;
+use cohort_stream_processor::consumers::{
+ CohortStreamEvent, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, MergeRoute,
+ TransferRoute,
+};
+use cohort_stream_processor::filters::{
+ CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,
+};
+use cohort_stream_processor::merge::transfer::{
+ MergeStateTransfer, PersonMergeEvent, Tombstone, MERGE_EVENT_SCHEMA_VERSION,
+};
+use cohort_stream_processor::partitions::{
+ merge_partition_key, partition_of, run_rebalance_worker, CohortConsumerContext, Follower,
+ FollowerSet, OffsetTracker, PartitionRouter, COHORT_PARTITION_COUNT,
+};
+use cohort_stream_processor::producer::{
+ CaptureCascadeSink, CaptureSink, CohortMembershipChange, KafkaMembershipSink,
+ KafkaStreamEventSink, KafkaTransferSink, MembershipSink, MembershipStatus, StreamEventSink,
+ TransferSink,
+};
+use cohort_stream_processor::stage1::{Stage1State, StateVariant, StatefulRecord};
+use cohort_stream_processor::store::{
+ CohortStore, LeafStateKey, Stage1Key, StoreConfig, TombstoneKey,
+};
+use cohort_stream_processor::workers::{
+ CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
+};
+use common_kafka::config::KafkaConfig;
+use futures::FutureExt;
+use lifecycle::{ComponentOptions, Handle, Manager};
+use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
+use rdkafka::client::DefaultClientContext;
+use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};
+use rdkafka::message::Message;
+use rdkafka::producer::{FutureProducer, FutureRecord};
+use rdkafka::util::Timeout;
+use rdkafka::{ClientConfig, Offset, TopicPartitionList};
+use serde_json::json;
+use tempfile::TempDir;
+use tokio::sync::mpsc;
+use tokio::task::JoinHandle;
+use uuid::Uuid;
+
+const TEAM: i32 = 7;
+const HASH: [u8; 16] = *b"0123456789abcdef";
+const NUM_PARTITIONS: i32 = COHORT_PARTITION_COUNT as i32;
+const TS: &str = "2026-06-10 12:34:56.789000";
+const TS_LATER: &str = "2026-06-10 13:34:56.789000";
+const MERGED_AT: i64 = 1_770_000_000_000;
+const COMMIT_INTERVAL: Duration = Duration::from_millis(250);
+const RECV_TIMEOUT: Duration = Duration::from_millis(200);
+
+fn bootstrap_servers() -> String {
+ std::env::var("KAFKA_HOSTS").unwrap_or_else(|_| "localhost:9092".to_string())
+}
+
+/// Cohort 1: `performed_event` single. Cohort 2: `performed_event_multiple gte 2` daily.
+/// Both share one `$pageview` conditionHash; daily bucket counts make a double-apply observable.
+fn merge_catalog() -> CatalogHandle {
+ let single = json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": 7, "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ });
+ let daily = json!({
+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",
+ "time_value": 7, "time_interval": "day", "operator": "gte", "operator_value": 2,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": [single] } }),
+ )
+ .expect("add single cohort");
+ builder
+ .add_cohort(
+ CohortId(2),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": [daily] } }),
+ )
+ .expect("add daily cohort");
+ CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ builder.freeze(UTC),
+ )]))
+}
+
+fn behavioral_lsks(catalog: &CatalogHandle) -> (LeafStateKey, LeafStateKey) {
+ let snapshot = catalog.load();
+ let team = snapshot.team(TeamId(TEAM)).expect("team in catalog");
+ let pick = |variant: StateVariant| {
+ team.by_condition_to_lsk[&HASH]
+ .iter()
+ .copied()
+ .find(|lsk| team.by_lsk[lsk].variant == variant)
+ .unwrap_or_else(|| panic!("no LSK for {variant:?}"))
+ };
+ (
+ pick(StateVariant::BehavioralSingle),
+ pick(StateVariant::BehavioralDailyBuckets),
+ )
+}
+
+async fn create_topic(topic: &str, partitions: i32) {
+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .create()
+ .expect("create admin client");
+ let new_topic = NewTopic::new(topic, partitions, TopicReplication::Fixed(1));
+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+ let results = admin
+ .create_topics(&[new_topic], &opts)
+ .await
+ .expect("create_topics");
+ for result in results {
+ match result {
+ Ok(_) | Err((_, rdkafka::types::RDKafkaErrorCode::TopicAlreadyExists)) => {}
+ Err((name, err)) => panic!("failed to create topic {name}: {err:?}"),
+ }
+ }
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("metadata-verifier-{}", Uuid::new_v4()))
+ .create()
+ .expect("create metadata verifier");
+ let start = Instant::now();
+ loop {
+ let ready = verifier
+ .fetch_metadata(Some(topic), Duration::from_secs(5))
+ .ok()
+ .is_some_and(|metadata| {
+ metadata.topics().iter().any(|meta| {
+ meta.name() == topic
+ && meta.error().is_none()
+ && meta.partitions().len() == partitions as usize
+ })
+ });
+ if ready {
+ break;
+ }
+ assert!(
+ start.elapsed() < Duration::from_secs(30),
+ "timed out waiting for topic {topic} metadata to propagate",
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+}
+
+async fn delete_topics(topics: &[&str]) {
+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .create()
+ .expect("create admin client");
+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+ if let Err(err) = admin.delete_topics(topics, &opts).await {
+ eprintln!("topic cleanup failed; leaked {topics:?}: {err}");
+ }
+}
+
+/// Run a test body, delete `topics` whether it passed or panicked, then re-propagate any panic.
+async fn with_topics_cleanup<F: Future<Output = ()>>(topics: &[&str], body: F) {
+ let result = AssertUnwindSafe(body).catch_unwind().await;
+ delete_topics(topics).await;
+ if let Err(panic) = result {
+ std::panic::resume_unwind(panic);
+ }
+}
+
+/// `murmur2_random` is required so keyed produces co-partition with `partition_of`.
+fn producer_kafka_config() -> KafkaConfig {
+ KafkaConfig {
+ kafka_hosts: bootstrap_servers(),
+ kafka_tls: false,
+ kafka_client_rack: String::new(),
+ kafka_client_id: String::new(),
+ kafka_compression_codec: "none".to_string(),
+ kafka_producer_partitioner: Some("murmur2_random".to_string()),
+ kafka_producer_linger_ms: 20,
+ kafka_producer_queue_mib: 400,
+ kafka_producer_queue_messages: 10_000_000,
+ kafka_message_timeout_ms: 20_000,
+ kafka_producer_batch_size: None,
+ kafka_producer_batch_num_messages: None,
+ kafka_producer_enable_idempotence: None,
+ kafka_producer_max_in_flight_requests_per_connection: None,
+ kafka_producer_topic_metadata_refresh_interval_ms: None,
+ kafka_producer_message_max_bytes: None,
+ kafka_producer_sticky_partitioning_linger_ms: None,
+ }
+}
+
+fn murmur2_producer() -> FutureProducer {
+ ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("message.timeout.ms", "10000")
+ .set("partitioner", "murmur2_random")
+ .create()
+ .expect("create murmur2 producer")
+}
+
+fn events_client_config(group: &str) -> ClientConfig {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "earliest")
+ .set("partition.assignment.strategy", "cooperative-sticky")
+ .set("session.timeout.ms", "6000");
+ config
+}
+
+fn follower_client_config(group: &str) -> ClientConfig {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "earliest")
+ .set("socket.timeout.ms", "10000");
+ config
+}
+
+fn group_verifier(group: &str) -> StreamConsumer {
+ ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create group verifier")
+}
+
+/// Sum of committed offsets across all partitions (committed == next-offset-to-consume on a fresh topic).
+fn committed_sum(consumer: &StreamConsumer, topic: &str) -> i64 {
+ let mut tpl = TopicPartitionList::new();
+ for partition in 0..NUM_PARTITIONS {
+ tpl.add_partition(topic, partition);
+ }
+ let committed = consumer
+ .committed_offsets(tpl, Duration::from_secs(5))
+ .expect("fetch committed offsets");
+ (0..NUM_PARTITIONS)
+ .filter_map(|partition| committed.find_partition(topic, partition))
+ .map(|elem| match elem.offset() {
+ Offset::Offset(value) => value,
+ _ => 0,
+ })
+ .sum()
+}
+
+fn topic_message_count(topic: &str) -> i64 {
+ let consumer: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("watermark-verifier-{}", Uuid::new_v4()))
+ .create()
+ .expect("create watermark verifier");
+ (0..NUM_PARTITIONS)
+ .map(|partition| {
+ let (low, high) = consumer
+ .fetch_watermarks(topic, partition, Duration::from_secs(10))
+ .expect("fetch watermarks");
+ high - low
+ })
+ .sum()
+}
+
+/// Read up to `expected` messages (all partitions from the beginning). Assigned explicitly — no group
+/// join, no commit — so committed offsets the test asserts on are never perturbed.
+async fn consume_all(topic: &str, expected: usize, deadline: Duration) -> Vec<(i32, Vec<u8>)> {
+ let consumer: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("scan-verifier-{}", Uuid::new_v4()))
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create scan verifier");
+ let mut tpl = TopicPartitionList::new();
+ for partition in 0..NUM_PARTITIONS {
+ tpl.add_partition_offset(topic, partition, Offset::Beginning)
+ .expect("add partition to scan TPL");
+ }
+ consumer.assign(&tpl).expect("assign scan verifier");
+
+ let mut messages = Vec::new();
+ let start = Instant::now();
+ while messages.len() < expected && start.elapsed() < deadline {
+ match tokio::time::timeout(Duration::from_secs(2), consumer.recv()).await {
+ Ok(Ok(message)) => {
+ if let Some(payload) = message.payload() {
+ messages.push((message.partition(), payload.to_vec()));
+ }
+ }
+ Ok(Err(err)) => panic!("scan verifier recv error: {err}"),
+ Err(_) => {}
+ }
+ }
+ messages
+}
+
+async fn wait_for(what: &str, deadline: Duration, mut condition: impl FnMut() -> bool) {
+ let start = Instant::now();
+ while !condition() {
+ assert!(
+ start.elapsed() < deadline,
+ "timed out after {deadline:?} waiting for {what}",
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+}
+
+fn part(person: Uuid) -> u16 {
+ partition_of(TeamId(TEAM), &person, COHORT_PARTITION_COUNT) as u16
+}
+
+struct PersonAlloc(u128);
+
+impl PersonAlloc {
+ fn new() -> Self {
+ Self(0xA1CE_0000)
+ }
+
+ fn next_on(&mut self, accept: impl Fn(u16) -> bool) -> Uuid {
+ loop {
+ self.0 += 1;
+ let person = Uuid::from_u128(self.0);
+ if accept(part(person)) {
+ return person;
+ }
+ }
+ }
+
+ fn next(&mut self) -> Uuid {
+ self.next_on(|_| true)
+ }
+
+ /// A `(P_old, P_new)` pair hashing to different partitions — the cross-partition slow path.
+ fn cross_partition_pair(&mut self) -> (Uuid, Uuid) {
+ let old = self.next();
+ let new = self.next_on(|p| p != part(old));
+ (old, new)
+ }
+}
+
+fn envelope(person: Uuid, ts: &str, source_offset: i64) -> Vec<u8> {
+ serde_json::to_vec(&json!({
+ "team_id": TEAM,
+ "person_id": person.to_string(),
+ "distinct_id": "d",
+ "uuid": Uuid::from_u128(0xE0_0000 + source_offset as u128).to_string(),
+ "event": "$pageview",
+ "timestamp": ts,
+ "properties": "{}",
+ "person_properties": null,
+ "elements_chain": null,
+ "source_offset": source_offset,
+ "source_partition": 0,
+ }))
+ .expect("serialize envelope")
+}
+
+async fn produce_event(
+ producer: &FutureProducer,
+ topic: &str,
+ person: Uuid,
+ ts: &str,
+ source_offset: i64,
+) {
+ let key = merge_partition_key(TeamId(TEAM), &person);
+ let payload = envelope(person, ts, source_offset);
+ let (partition, _offset) = producer
+ .send(
+ FutureRecord::to(topic).key(&key).payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce event");
+ assert_eq!(
+ partition as u32,
+ partition_of(TeamId(TEAM), &person, COHORT_PARTITION_COUNT),
+ "seed event must co-partition with the merge protocol's arithmetic",
+ );
+}
+
+fn merge_event(old: Uuid, new: Uuid) -> PersonMergeEvent {
+ PersonMergeEvent {
+ team_id: TEAM,
+ old_person_uuid: old,
+ new_person_uuid: new,
+ merged_at_ms: MERGED_AT,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ }
+}
+
+async fn produce_merge(producer: &FutureProducer, topic: &str, event: &PersonMergeEvent) {
+ let key = merge_partition_key(TeamId(event.team_id), &event.old_person_uuid);
+ let payload = event.encode();
+ let (partition, _offset) = producer
+ .send(
+ FutureRecord::to(topic).key(&key).payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce merge event");
+ assert_eq!(
+ partition as u32,
+ partition_of(
+ TeamId(event.team_id),
+ &event.old_person_uuid,
+ COHORT_PARTITION_COUNT
+ ),
+ "merge trigger must land on P_old's partition",
+ );
+}
+
+fn open_store(dir: &TempDir) -> CohortStore {
+ CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store")
+}
+
+fn stage1_state(
+ store: &CohortStore,
+ partition_id: u16,
+ lsk: LeafStateKey,
+ person: Uuid,
+) -> Option<Stage1State> {
+ let key = Stage1Key {
+ partition_id,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person,
+ };
+ store
+ .get_stage1(&key)
+ .unwrap()
+ .map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)
+}
+
+/// The daily leaf's bucket sum for `person` on its own partition's slice, or `None` if absent.
+fn daily_total(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<u64> {
+ match stage1_state(store, part(person), lsk, person)? {
+ Stage1State::BehavioralDailyBuckets { buckets, .. } => {
+ Some(buckets.iter().map(|&count| count as u64).sum())
+ }
+ other => panic!("expected daily buckets for {person}, got {other:?}"),
+ }
+}
+
+fn single_matches(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<bool> {
+ match stage1_state(store, part(person), lsk, person)? {
+ Stage1State::BehavioralSingle { has_match, .. } => Some(has_match),
+ other => panic!("expected single state for {person}, got {other:?}"),
+ }
+}
+
+fn tombstone_for(store: &CohortStore, person: Uuid) -> Option<Tombstone> {
+ store
+ .get_tombstone(&TombstoneKey {
+ partition_id: part(person),
+ team_id: TEAM as u64,
+ person,
+ })
+ .unwrap()
+ .map(|bytes| Tombstone::decode(&bytes).unwrap())
+}
+
+struct Topics {
+ events: String,
+ merges: String,
+ transfers: String,
+}
+
+impl Topics {
+ fn unique(suffix: &Uuid) -> Self {
+ Self {
+ events: format!("cohort_stream_events_merge_{suffix}"),
+ merges: format!("person_merge_events_{suffix}"),
+ transfers: format!("cohort_merge_state_transfer_{suffix}"),
+ }
+ }
+
+ async fn create(&self) {
+ create_topic(&self.events, NUM_PARTITIONS).await;
+ create_topic(&self.merges, NUM_PARTITIONS).await;
+ create_topic(&self.transfers, NUM_PARTITIONS).await;
+ }
+
+ fn names(&self) -> [&str; 3] {
+ [&self.events, &self.merges, &self.transfers]
+ }
+}
+
+struct Groups {
+ events: String,
+ merges: String,
+ transfers: String,
+}
+
+impl Groups {
+ fn unique(suffix: &Uuid) -> Self {
+ Self {
+ events: format!("cohort-stream-processor-{suffix}"),
+ merges: format!("cohort-stream-merges-{suffix}"),
+ transfers: format!("cohort-stream-merge-apply-{suffix}"),
+ }
+ }
+}
+
+fn register_instance(manager: &mut Manager, name: &str) -> [Handle; 3] {
+ let options = || ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15));
+ [
+ manager.register(&format!("consumer-{name}"), options()),
+ manager.register(&format!("merge-follower-{name}"), options()),
+ manager.register(&format!("transfer-follower-{name}"), options()),
+ ]
+}
+
+struct Instance {
+ store: CohortStore,
+ dispatcher: Arc<EventDispatcher>,
+ tasks: Vec<JoinHandle<()>>,
+}
+
+impl Instance {
+ fn owned(&self) -> HashSet<i32> {
+ self.dispatcher.owned_partitions().into_iter().collect()
+ }
+
+ async fn join(self) {
+ for task in self.tasks {
+ task.await.expect("instance task panicked");
+ }
+ }
+}
+
+async fn spawn_instance(
+ topics: &Topics,
+ groups: &Groups,
+ store: CohortStore,
+ catalog: CatalogHandle,
+ membership_sink: Arc<dyn MembershipSink>,
+ handles: [Handle; 3],
+) -> Instance {
+ let [events_handle, merge_handle, transfer_handle] = handles;
+ let kafka_config = producer_kafka_config();
+
+ let transfer_sink: Arc<dyn TransferSink> = Arc::new(
+ KafkaTransferSink::new(&kafka_config, topics.transfers.clone())
+ .await
+ .expect("create transfer sink"),
+ );
+ let stream_event_sink: Arc<dyn StreamEventSink> = Arc::new(
+ KafkaStreamEventSink::new(&kafka_config, topics.events.clone())
+ .await
+ .expect("create re-key sink"),
+ );
+ let merge_deps = Arc::new(MergeWorkerDeps {
+ transfer_sink,
+ stream_event_sink,
+ merge_tracker: Arc::new(OffsetTracker::new()),
+ transfer_tracker: Arc::new(OffsetTracker::new()),
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink: Arc::new(CaptureCascadeSink::new()),
+ cascade_tracker: Arc::new(OffsetTracker::new()),
+ cascade: CascadeConfig::default(),
+ partition_count: COHORT_PARTITION_COUNT,
+ });
+
+ let dispatcher = Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store.clone(),
+ Arc::new(catalog),
+ membership_sink,
+ merge_deps,
+ ));
+
+ let merges_consumer: Arc<StreamConsumer> = Arc::new(
+ follower_client_config(&groups.merges)
+ .create()
+ .expect("create merges follower consumer"),
+ );
+ let transfers_consumer: Arc<StreamConsumer> = Arc::new(
+ follower_client_config(&groups.transfers)
+ .create()
+ .expect("create transfers follower consumer"),
+ );
+ let followers = Arc::new(FollowerSet::new([
+ Follower::new(merges_consumer.clone(), topics.merges.clone()),
+ Follower::new(transfers_consumer.clone(), topics.transfers.clone()),
+ ]));
+
+ let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());
+ let events_client: StreamConsumer<CohortConsumerContext> = events_client_config(&groups.events)
+ .create_with_context(context)
+ .expect("create events consumer");
+ events_client
+ .subscribe(&[topics.events.as_str()])
+ .expect("subscribe events");
+
+ let (command_tx, command_rx) = mpsc::unbounded_channel();
+ let mut tasks = vec![tokio::spawn(run_rebalance_worker(
+ rebalance_rx,
+ dispatcher.clone(),
+ followers,
+ command_tx,
+ events_handle.shutdown_token(),
+ ))];
+
+ let merge_follower = FollowerConsumer::<MergeRoute>::new(
+ merges_consumer,
+ topics.merges.clone(),
+ dispatcher.clone(),
+ merge_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ );
+ tasks.push(tokio::spawn(merge_follower.process()));
+
+ let transfer_follower = FollowerConsumer::<TransferRoute>::new(
+ transfers_consumer,
+ topics.transfers.clone(),
+ dispatcher.clone(),
+ transfer_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ );
+ tasks.push(tokio::spawn(transfer_follower.process()));
+
+ let events_consumer = CohortStreamEventsConsumer::new(
+ events_client,
+ topics.events.clone(),
+ dispatcher.clone(),
+ events_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ NUM_PARTITIONS as usize,
+ command_rx,
+ None,
+ );
+ tasks.push(tokio::spawn(events_consumer.process()));
+
+ Instance {
+ store,
+ dispatcher,
+ tasks,
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn keyed_produces_agree_with_partition_of_live() {
+ let suffix = Uuid::new_v4();
+ let raw_topic = format!("merge_partitioner_raw_{suffix}");
+ let transfer_topic = format!("merge_partitioner_transfer_{suffix}");
+ let events_topic = format!("merge_partitioner_events_{suffix}");
+ with_topics_cleanup(&[&raw_topic, &transfer_topic, &events_topic], async {
+ create_topic(&raw_topic, NUM_PARTITIONS).await;
+ create_topic(&transfer_topic, NUM_PARTITIONS).await;
+ create_topic(&events_topic, NUM_PARTITIONS).await;
+
+ let producer = murmur2_producer();
+ let mut spread = HashSet::new();
+ for team in [2i32, 7, 42, 99] {
+ for n in 1..=50u128 {
+ let person = Uuid::from_u128(((team as u128) << 64) | n);
+ let key = merge_partition_key(TeamId(team), &person);
+ let payload = PersonMergeEvent {
+ team_id: team,
+ old_person_uuid: person,
+ new_person_uuid: Uuid::from_u128(0xBEEF),
+ merged_at_ms: MERGED_AT,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ }
+ .encode();
+ let (partition, _offset) = producer
+ .send(
+ FutureRecord::to(&raw_topic).key(&key).payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce keyed message");
+ assert_eq!(
+ partition as u32,
+ partition_of(TeamId(team), &person, COHORT_PARTITION_COUNT),
+ "murmur2_random delivery for ({team}, {person}) disagrees with partition_of",
+ );
+ spread.insert(partition);
+ }
+ }
+ assert!(
+ spread.len() >= 32,
+ "200 pairs should cover many partitions, got {}",
+ spread.len(),
+ );
+
+ // Transfer sink: keyed by P_new; verify each message lands on partition_of(P_new).
+ let transfer_sink =
+ KafkaTransferSink::new(&producer_kafka_config(), transfer_topic.clone())
+ .await
+ .expect("create transfer sink");
+ let transfers: Vec<MergeStateTransfer> = (1..=96u128)
+ .map(|n| MergeStateTransfer {
+ team_id: TEAM,
+ old_person_uuid: Uuid::from_u128(0xDEAD_0000 + n),
+ new_person_uuid: Uuid::from_u128(0xBEEF_0000 + n),
+ merged_at_ms: MERGED_AT,
+ source_partition: 0,
+ source_offset: n as i64,
+ leaves: vec![],
+ forward_hops: 0,
+ })
+ .collect();
+ let acks = transfer_sink.produce(transfers).await;
+ assert!(acks.iter().all(Result::is_ok), "all transfer produces ack");
+
+ let messages = consume_all(&transfer_topic, 96, Duration::from_secs(30)).await;
+ assert_eq!(messages.len(), 96, "all produced transfers are readable");
+ for (partition, payload) in &messages {
+ let transfer = MergeStateTransfer::decode(payload).unwrap();
+ assert_eq!(
+ *partition as u32,
+ partition_of(
+ TeamId(transfer.team_id),
+ &transfer.new_person_uuid,
+ COHORT_PARTITION_COUNT
+ ),
+ "transfer for P_new {} landed off its partition",
+ transfer.new_person_uuid,
+ );
+ }
+
+ // Re-key sink: keyed by the rewritten target person.
+ let event_sink = KafkaStreamEventSink::new(&producer_kafka_config(), events_topic.clone())
+ .await
+ .expect("create re-key sink");
+ let events: Vec<CohortStreamEvent> = (1..=64u128)
+ .map(|n| CohortStreamEvent {
+ team_id: TEAM,
+ person_id: Uuid::from_u128(0xCAFE_0000 + n).to_string(),
+ distinct_id: "d".to_string(),
+ uuid: Uuid::from_u128(0xE1_0000 + n).to_string(),
+ event: "$pageview".to_string(),
+ timestamp: TS.to_string(),
+ properties: Some("{}".to_string()),
+ person_properties: None,
+ elements_chain: None,
+ source_offset: n as i64,
+ source_partition: 0,
+ redirected_from: Some(Uuid::from_u128(1).to_string()),
+ redirect_hops: 1,
+ })
+ .collect();
+ let acks = event_sink.produce(events).await;
+ assert!(acks.iter().all(Result::is_ok), "all re-key produces ack");
+
+ let messages = consume_all(&events_topic, 64, Duration::from_secs(30)).await;
+ assert_eq!(messages.len(), 64, "all produced re-keys are readable");
+ for (partition, payload) in &messages {
+ let event: CohortStreamEvent = serde_json::from_slice(payload).unwrap();
+ let person = Uuid::parse_str(&event.person_id).unwrap();
+ assert_eq!(
+ *partition as u32,
+ partition_of(TeamId(event.team_id), &person, COHORT_PARTITION_COUNT),
+ "re-keyed event for {person} landed off its partition",
+ );
+ }
+ })
+ .await;
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn cross_partition_merge_completes_end_to_end_on_the_wire() {
+ let suffix = Uuid::new_v4();
+ let topics = Topics::unique(&suffix);
+ let shadow_topic = format!("cohort_membership_changed_merge_{suffix}");
+ let groups = Groups::unique(&suffix);
+ let [events, merges, transfers] = topics.names();
+ with_topics_cleanup(&[events, merges, transfers, &shadow_topic], async {
+ topics.create().await;
+ create_topic(&shadow_topic, NUM_PARTITIONS).await;
+
+ let catalog = merge_catalog();
+ let (single_lsk, daily_lsk) = behavioral_lsks(&catalog);
+
+ let mut manager = Manager::builder("merge-e2e-itest")
+ .with_trap_signals(false)
+ .build();
+ let handles = register_instance(&mut manager, "a");
+ let shutdown = handles[0].clone();
+ let _monitor = manager.monitor_background();
+
+ let dir = TempDir::new().unwrap();
+ let membership: Arc<dyn MembershipSink> = Arc::new(
+ KafkaMembershipSink::new(&producer_kafka_config(), shadow_topic.clone())
+ .await
+ .expect("create shadow sink"),
+ );
+ let instance = spawn_instance(
+ &topics,
+ &groups,
+ open_store(&dir),
+ catalog,
+ membership,
+ handles,
+ )
+ .await;
+ wait_for(
+ "the consumer to own every partition",
+ Duration::from_secs(30),
+ || instance.owned().len() == NUM_PARTITIONS as usize,
+ )
+ .await;
+
+ let mut alloc = PersonAlloc::new();
+ let (p_old, p_new) = alloc.cross_partition_pair();
+
+ let producer = murmur2_producer();
+ produce_event(&producer, &topics.events, p_old, TS, 0).await;
+ produce_event(&producer, &topics.events, p_old, TS, 1).await;
+ wait_for("P_old's seeded state", Duration::from_secs(60), || {
+ daily_total(&instance.store, daily_lsk, p_old) == Some(2)
+ })
+ .await;
+
+ produce_merge(&producer, &topics.merges, &merge_event(p_old, p_new)).await;
+
+ let merge_verifier = group_verifier(&groups.merges);
+ let transfer_verifier = group_verifier(&groups.transfers);
+ wait_for(
+ "the merge group's offset to commit",
+ Duration::from_secs(60),
+ || committed_sum(&merge_verifier, &topics.merges) == 1,
+ )
+ .await;
+ wait_for(
+ "the transfer group's offset to commit",
+ Duration::from_secs(60),
+ || committed_sum(&transfer_verifier, &topics.transfers) == 1,
+ )
+ .await;
+
+ assert_eq!(
+ topic_message_count(&topics.transfers),
+ 1,
+ "exactly one transfer message on the wire",
+ );
+ let transfer_messages = consume_all(&topics.transfers, 1, Duration::from_secs(30)).await;
+ assert_eq!(transfer_messages.len(), 1, "the transfer is readable");
+ let (transfer_partition, payload) = &transfer_messages[0];
+ assert_eq!(
+ *transfer_partition as u16,
+ part(p_new),
+ "transfer must land on P_new's partition",
+ );
+ let transfer = MergeStateTransfer::decode(payload).unwrap();
+ assert_eq!(transfer.old_person_uuid, p_old);
+ assert_eq!(transfer.new_person_uuid, p_new);
+ assert_eq!(transfer.source_partition, part(p_old) as i32);
+ assert_eq!(
+ transfer.leaves.len(),
+ 2,
+ "single + daily leaves transfer whole"
+ );
+
+ assert_eq!(
+ single_matches(&instance.store, single_lsk, p_new),
+ Some(true)
+ );
+ assert_eq!(daily_total(&instance.store, daily_lsk, p_new), Some(2));
+ assert_eq!(single_matches(&instance.store, single_lsk, p_old), None);
+ assert_eq!(daily_total(&instance.store, daily_lsk, p_old), None);
+ let tombstone =
+ tombstone_for(&instance.store, p_old).expect("tombstone written on P_old's slice");
+ assert_eq!(tombstone.new_person, p_new);
+
+ // The drain emits no Left for P_old.
+ assert_eq!(
+ topic_message_count(&shadow_topic),
+ 4,
+ "exactly four membership changes on the wire (no Left for P_old)",
+ );
+ let changes: Vec<CohortMembershipChange> =
+ consume_all(&shadow_topic, 4, Duration::from_secs(30))
+ .await
+ .iter()
+ .map(|(_, payload)| {
+ serde_json::from_slice(payload).expect("decode membership change")
+ })
+ .collect();
+ let entered_new: HashSet<i32> = changes
+ .iter()
+ .filter(|change| {
+ change.person_id == p_new.to_string() && change.status == MembershipStatus::Entered
+ })
+ .map(|change| change.cohort_id)
+ .collect();
+ assert_eq!(
+ entered_new,
+ HashSet::from([1, 2]),
+ "the apply emitted P_new's entry into both cohorts",
+ );
+ assert!(
+ !changes
+ .iter()
+ .any(|change| change.person_id == p_old.to_string()
+ && change.status == MembershipStatus::Left),
+ "the drain emits no Left for P_old",
+ );
+
+ shutdown.request_shutdown();
+ instance.join().await;
+ })
+ .await;
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn duplicate_merge_message_produces_exactly_one_transfer() {
+ let suffix = Uuid::new_v4();
+ let topics = Topics::unique(&suffix);
+ let groups = Groups::unique(&suffix);
+ with_topics_cleanup(&topics.names(), async {
+ topics.create().await;
+
+ let catalog = merge_catalog();
+ let (_, daily_lsk) = behavioral_lsks(&catalog);
+
+ let mut manager = Manager::builder("merge-dup-itest")
+ .with_trap_signals(false)
+ .build();
+ let handles = register_instance(&mut manager, "a");
+ let shutdown = handles[0].clone();
+ let _monitor = manager.monitor_background();
+
+ let dir = TempDir::new().unwrap();
+ let instance = spawn_instance(
+ &topics,
+ &groups,
+ open_store(&dir),
+ catalog,
+ Arc::new(CaptureSink::new()),
+ handles,
+ )
+ .await;
+ wait_for(
+ "the consumer to own every partition",
+ Duration::from_secs(30),
+ || instance.owned().len() == NUM_PARTITIONS as usize,
+ )
+ .await;
+
+ let mut alloc = PersonAlloc::new();
+ let (p_old, p_new) = alloc.cross_partition_pair();
+
+ let producer = murmur2_producer();
+ produce_event(&producer, &topics.events, p_old, TS, 0).await;
+ produce_event(&producer, &topics.events, p_old, TS, 1).await;
+ wait_for("P_old's seeded state", Duration::from_secs(60), || {
+ daily_total(&instance.store, daily_lsk, p_old) == Some(2)
+ })
+ .await;
+
+ let event = merge_event(p_old, p_new);
+ produce_merge(&producer, &topics.merges, &event).await;
+ produce_merge(&producer, &topics.merges, &event).await;
+
+ let merge_verifier = group_verifier(&groups.merges);
+ wait_for(
+ "both merge copies to settle and commit",
+ Duration::from_secs(60),
+ || committed_sum(&merge_verifier, &topics.merges) == 2,
+ )
+ .await;
+
+ assert_eq!(
+ topic_message_count(&topics.transfers),
+ 1,
+ "the replayed drain must not produce a second transfer",
+ );
+
+ let transfer_verifier = group_verifier(&groups.transfers);
+ wait_for(
+ "the transfer group's offset to commit",
+ Duration::from_secs(60),
+ || committed_sum(&transfer_verifier, &topics.transfers) == 1,
+ )
+ .await;
+ assert_eq!(
+ daily_total(&instance.store, daily_lsk, p_new),
+ Some(2),
+ "P_new's buckets applied exactly once, never summed twice",
+ );
+
+ shutdown.request_shutdown();
+ instance.join().await;
+ })
+ .await;
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn post_merge_straggler_re_keys_to_p_new_and_folds() {
+ let suffix = Uuid::new_v4();
+ let topics = Topics::unique(&suffix);
+ let groups = Groups::unique(&suffix);
+ with_topics_cleanup(&topics.names(), async {
+ topics.create().await;
+
+ let catalog = merge_catalog();
+ let (single_lsk, daily_lsk) = behavioral_lsks(&catalog);
+
+ let mut manager = Manager::builder("merge-straggler-itest")
+ .with_trap_signals(false)
+ .build();
+ let handles = register_instance(&mut manager, "a");
+ let shutdown = handles[0].clone();
+ let _monitor = manager.monitor_background();
+
+ let dir = TempDir::new().unwrap();
+ let instance = spawn_instance(
+ &topics,
+ &groups,
+ open_store(&dir),
+ catalog,
+ Arc::new(CaptureSink::new()),
+ handles,
+ )
+ .await;
+ wait_for(
+ "the consumer to own every partition",
+ Duration::from_secs(30),
+ || instance.owned().len() == NUM_PARTITIONS as usize,
+ )
+ .await;
+
+ let mut alloc = PersonAlloc::new();
+ let (p_old, p_new) = alloc.cross_partition_pair();
+
+ let producer = murmur2_producer();
+ produce_event(&producer, &topics.events, p_old, TS, 0).await;
+ produce_event(&producer, &topics.events, p_old, TS, 1).await;
+ wait_for("P_old's seeded state", Duration::from_secs(60), || {
+ daily_total(&instance.store, daily_lsk, p_old) == Some(2)
+ })
+ .await;
+ produce_merge(&producer, &topics.merges, &merge_event(p_old, p_new)).await;
+ let merge_verifier = group_verifier(&groups.merges);
+ wait_for("the merge to complete", Duration::from_secs(60), || {
+ committed_sum(&merge_verifier, &topics.merges) == 1
+ && daily_total(&instance.store, daily_lsk, p_new) == Some(2)
+ })
+ .await;
+
+ produce_event(&producer, &topics.events, p_old, TS_LATER, 100).await;
+ wait_for(
+ "the straggler to fold into P_new",
+ Duration::from_secs(60),
+ || daily_total(&instance.store, daily_lsk, p_new) == Some(3),
+ )
+ .await;
+
+ assert_eq!(
+ topic_message_count(&topics.events),
+ 4,
+ "seeds + straggler + exactly one re-key on the wire",
+ );
+ let messages = consume_all(&topics.events, 4, Duration::from_secs(30)).await;
+ assert_eq!(messages.len(), 4, "all four events are readable");
+ let re_keyed: Vec<(i32, CohortStreamEvent)> = messages
+ .iter()
+ .filter_map(|(partition, payload)| {
+ let event: CohortStreamEvent = serde_json::from_slice(payload).ok()?;
+ event
+ .redirected_from
+ .is_some()
+ .then_some((*partition, event))
+ })
+ .collect();
+ assert_eq!(re_keyed.len(), 1, "exactly one re-keyed straggler");
+ let (partition, event) = &re_keyed[0];
+ assert_eq!(
+ *partition as u16,
+ part(p_new),
+ "the re-key landed on P_new's partition",
+ );
+ assert_eq!(
+ event.person_id,
+ p_new.to_string(),
+ "person rewritten to the target"
+ );
+ assert_eq!(
+ event.redirected_from.as_deref(),
+ Some(p_old.to_string().as_str()),
+ "first-origin marker stamped",
+ );
+ assert_eq!(event.redirect_hops, 1, "one cross-partition hop counted");
+ assert_eq!(
+ (event.source_partition, event.source_offset),
+ (0, 100),
+ "original source coordinates preserved for redirect_dedup",
+ );
+
+ assert_eq!(single_matches(&instance.store, single_lsk, p_old), None);
+ assert_eq!(daily_total(&instance.store, daily_lsk, p_old), None);
+
+ shutdown.request_shutdown();
+ instance.join().await;
+ })
+ .await;
+}
+
+/// `incremental_unassign` + `incremental_assign(Offset::Stored)` rewinds to the committed offset,
+/// not the in-session fetch position.
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn follower_re_establishes_consumption_from_the_committed_offset() {
+ let suffix = Uuid::new_v4();
+ let topic = format!("merge_follower_stored_{suffix}");
+ with_topics_cleanup(&[&topic], async {
+ create_topic(&topic, NUM_PARTITIONS).await;
+
+ // Pin to partition 0 explicitly; partitioning itself is not the thing under test.
+ let producer: FutureProducer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("message.timeout.ms", "10000")
+ .create()
+ .expect("create producer");
+ for n in 1..=5u128 {
+ let payload = merge_event(Uuid::from_u128(n), Uuid::from_u128(0xBEEF)).encode();
+ producer
+ .send(
+ FutureRecord::to(&topic)
+ .partition(0)
+ .key("k")
+ .payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce merge payload");
+ }
+
+ let group = format!("cohort-stream-merges-stored-{suffix}");
+ let consumer: StreamConsumer = follower_client_config(&group)
+ .create()
+ .expect("create follower consumer");
+
+ let stored = |topic: &str| {
+ let mut tpl = TopicPartitionList::new();
+ tpl.add_partition_offset(topic, 0, Offset::Stored)
+ .expect("stored TPL");
+ tpl
+ };
+
+ // First acquire: no committed offset yet → Stored falls back to earliest.
+ consumer
+ .incremental_assign(&stored(&topic))
+ .expect("incremental_assign");
+ let mut offsets = Vec::new();
+ for _ in 0..5 {
+ let message = tokio::time::timeout(Duration::from_secs(15), consumer.recv())
+ .await
+ .expect("recv deadline")
+ .expect("recv");
+ offsets.push(message.offset());
+ }
+ assert_eq!(
+ offsets,
+ vec![0, 1, 2, 3, 4],
+ "earliest fallback replays from 0"
+ );
+
+ // Commit offset 3 (processed through 2). Fetch position is already at 5.
+ let mut commit_tpl = TopicPartitionList::new();
+ commit_tpl
+ .add_partition_offset(&topic, 0, Offset::Offset(3))
+ .expect("commit TPL");
+ consumer
+ .commit(&commit_tpl, CommitMode::Sync)
+ .expect("commit");
+
+ // Revoke → re-acquire (mirrors the assignment-mirror protocol): unassign then re-assign at Stored.
+ let mut bare = TopicPartitionList::new();
+ bare.add_partition(&topic, 0);
+ consumer
+ .incremental_unassign(&bare)
+ .expect("incremental_unassign");
+ consumer
+ .incremental_assign(&stored(&topic))
+ .expect("re-assign at Offset::Stored");
+
+ let next = tokio::time::timeout(Duration::from_secs(15), consumer.recv())
+ .await
+ .expect("recv deadline after re-assign")
+ .expect("recv after re-assign");
+ assert_eq!(
+ next.offset(),
+ 3,
+ "Offset::Stored must rewind to the committed offset, not keep the in-session position",
+ );
+ let after = tokio::time::timeout(Duration::from_secs(15), consumer.recv())
+ .await
+ .expect("recv deadline")
+ .expect("recv");
+ assert_eq!(after.offset(), 4, "and redeliver the rest of the window");
+ })
+ .await;
+}
+
+#[tokio::test]
+#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]
+async fn cooperative_migration_mid_merge_stream_loses_no_merge() {
+ let suffix = Uuid::new_v4();
+ let topics = Topics::unique(&suffix);
+ let groups = Groups::unique(&suffix);
+ with_topics_cleanup(&topics.names(), async {
+ topics.create().await;
+
+ let catalog_a = merge_catalog();
+ let catalog_b = merge_catalog();
+ let (_, daily_lsk) = behavioral_lsks(&catalog_a);
+
+ let mut manager = Manager::builder("merge-migrate-itest")
+ .with_trap_signals(false)
+ .build();
+ let handles_a = register_instance(&mut manager, "a");
+ let handles_b = register_instance(&mut manager, "b");
+ let shutdown = handles_a[0].clone();
+ let _monitor = manager.monitor_background();
+
+ let dir_a = TempDir::new().unwrap();
+ let dir_b = TempDir::new().unwrap();
+ let sink_a = Arc::new(CaptureSink::new());
+ let sink_b = Arc::new(CaptureSink::new());
+
+ let a = spawn_instance(
+ &topics,
+ &groups,
+ open_store(&dir_a),
+ catalog_a,
+ sink_a.clone(),
+ handles_a,
+ )
+ .await;
+ wait_for(
+ "instance A to own every partition",
+ Duration::from_secs(30),
+ || a.owned().len() == NUM_PARTITIONS as usize,
+ )
+ .await;
+
+ let producer = murmur2_producer();
+ let mut alloc = PersonAlloc::new();
+ let mut source_offset = 0i64;
+ let mut seed = |producer: &FutureProducer, topic: &str, person: Uuid| {
+ let offsets = (source_offset, source_offset + 1);
+ source_offset += 2;
+ let topic = topic.to_string();
+ let producer = producer.clone();
+ async move {
+ produce_event(&producer, &topic, person, TS, offsets.0).await;
+ produce_event(&producer, &topic, person, TS, offsets.1).await;
+ }
+ };
+
+ // Batch 1: seed and trigger against A alone, B joins while merges are in flight.
+ let batch1: Vec<(Uuid, Uuid)> = (0..4).map(|_| alloc.cross_partition_pair()).collect();
+ for (p_old, _) in &batch1 {
+ seed(&producer, &topics.events, *p_old).await;
+ }
+ wait_for("batch 1 seed state", Duration::from_secs(60), || {
+ batch1
+ .iter()
+ .all(|(p_old, _)| daily_total(&a.store, daily_lsk, *p_old) == Some(2))
+ })
+ .await;
+ for (p_old, p_new) in &batch1 {
+ produce_merge(&producer, &topics.merges, &merge_event(*p_old, *p_new)).await;
+ }
+
+ let b = spawn_instance(
+ &topics,
+ &groups,
+ open_store(&dir_b),
+ catalog_b,
+ sink_b.clone(),
+ handles_b,
+ )
+ .await;
+
+ // Wait for a stable, disjoint full split.
+ let (a_owned, b_owned) = {
+ let deadline = Duration::from_secs(60);
+ let start = Instant::now();
+ loop {
+ let a1 = a.owned();
+ let b1 = b.owned();
+ if !b1.is_empty()
+ && a1.is_disjoint(&b1)
+ && a1.len() + b1.len() == NUM_PARTITIONS as usize
+ {
+ tokio::time::sleep(Duration::from_millis(750)).await;
+ if a.owned() == a1 && b.owned() == b1 {
+ break (a1, b1);
+ }
+ }
+ assert!(
+ start.elapsed() < deadline,
+ "timed out waiting for the cooperative split to settle (a={}, b={})",
+ a.owned().len(),
+ b.owned().len(),
+ );
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+ };
+
+ // Batch 2: directed pairs (A→B, B→A) plus generic pairs to cover both transfer directions.
+ let pair_ab = (
+ alloc.next_on(|p| a_owned.contains(&(p as i32))),
+ alloc.next_on(|p| b_owned.contains(&(p as i32))),
+ );
+ let pair_ba = (
+ alloc.next_on(|p| b_owned.contains(&(p as i32))),
+ alloc.next_on(|p| a_owned.contains(&(p as i32))),
+ );
+ let mut batch2 = vec![pair_ab, pair_ba];
+ batch2.extend((0..4).map(|_| alloc.cross_partition_pair()));
+
+ let in_either = |stores: [&CohortStore; 2], person: Uuid| {
+ stores
+ .iter()
+ .filter_map(|store| daily_total(store, daily_lsk, person))
+ .next()
+ };
+
+ for (p_old, _) in &batch2 {
+ seed(&producer, &topics.events, *p_old).await;
+ }
+ wait_for("batch 2 seed state", Duration::from_secs(60), || {
+ batch2
+ .iter()
+ .all(|(p_old, _)| in_either([&a.store, &b.store], *p_old) == Some(2))
+ })
+ .await;
+ for (p_old, p_new) in &batch2 {
+ produce_merge(&producer, &topics.merges, &merge_event(*p_old, *p_new)).await;
+ }
+
+ wait_for(
+ "every batch 2 merge to complete",
+ Duration::from_secs(90),
+ || {
+ batch2
+ .iter()
+ .all(|(_, p_new)| in_either([&a.store, &b.store], *p_new) == Some(2))
+ },
+ )
+ .await;
+
+ let total_merges = (batch1.len() + batch2.len()) as i64;
+ let merge_verifier = group_verifier(&groups.merges);
+ let transfer_verifier = group_verifier(&groups.transfers);
+ wait_for(
+ "merge commits to cover every merge",
+ Duration::from_secs(90),
+ || committed_sum(&merge_verifier, &topics.merges) == total_merges,
+ )
+ .await;
+ // Batch 1 may produce empty re-drains after migration; batch 2 transfers are deterministic.
+ let total_transfers = topic_message_count(&topics.transfers);
+ let transfer_pairs: HashSet<(Uuid, Uuid)> = consume_all(
+ &topics.transfers,
+ total_transfers as usize,
+ Duration::from_secs(30),
+ )
+ .await
+ .iter()
+ .map(|(_, payload)| {
+ let transfer = MergeStateTransfer::decode(payload).expect("decode transfer");
+ (transfer.old_person_uuid, transfer.new_person_uuid)
+ })
+ .collect();
+ for (p_old, p_new) in &batch2 {
+ assert!(
+ transfer_pairs.contains(&(*p_old, *p_new)),
+ "no transfer rode the wire for batch-2 merge {p_old} → {p_new}",
+ );
+ }
+ wait_for(
+ "transfer commits to cover every transfer",
+ Duration::from_secs(90),
+ || committed_sum(&transfer_verifier, &topics.transfers) == total_transfers,
+ )
+ .await;
+
+ for (p_old, p_new) in &batch2 {
+ let totals = [
+ daily_total(&a.store, daily_lsk, *p_new),
+ daily_total(&b.store, daily_lsk, *p_new),
+ ];
+ assert!(
+ totals.contains(&Some(2)) && totals.contains(&None),
+ "P_new {p_new} must hold the merged count in exactly one store, got {totals:?}",
+ );
+ assert_eq!(
+ daily_total(&a.store, daily_lsk, *p_old),
+ None,
+ "P_old {p_old} drained in A"
+ );
+ assert_eq!(
+ daily_total(&b.store, daily_lsk, *p_old),
+ None,
+ "P_old {p_old} drained in B"
+ );
+
+ let owner = if a_owned.contains(&(part(*p_old) as i32)) {
+ &a.store
+ } else {
+ &b.store
+ };
+ let tombstone = tombstone_for(owner, *p_old)
+ .unwrap_or_else(|| panic!("tombstone for {p_old} on its owner's slice"));
+ assert_eq!(tombstone.new_person, *p_new);
+ }
+
+ assert_eq!(
+ daily_total(&b.store, daily_lsk, pair_ab.1),
+ Some(2),
+ "the A-drained transfer applied on B",
+ );
+ assert_eq!(
+ daily_total(&a.store, daily_lsk, pair_ba.1),
+ Some(2),
+ "the B-drained transfer applied on A",
+ );
+
+ // Batch 1 raced the migration; any surviving count must be exact (no double-apply).
+ for (_, p_new) in &batch1 {
+ for store in [&a.store, &b.store] {
+ if let Some(total) = daily_total(store, daily_lsk, *p_new) {
+ assert_eq!(
+ total, 2,
+ "batch 1 P_new {p_new} was double-applied despite the dedup",
+ );
+ }
+ }
+ }
+
+ let entered: HashSet<String> = sink_a
+ .changes()
+ .into_iter()
+ .chain(sink_b.changes())
+ .filter(|change| change.status == MembershipStatus::Entered)
+ .map(|change| change.person_id)
+ .collect();
+ for (_, p_new) in &batch2 {
+ assert!(
+ entered.contains(&p_new.to_string()),
+ "P_new {p_new} entered on the shadow output",
+ );
+ }
+
+ shutdown.request_shutdown();
+ a.join().await;
+ b.join().await;
+ })
+ .await;
+}
diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rs
new file mode 100644
index 000000000000..37a695597c2e
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/merge_durability.rs
@@ -0,0 +1,1379 @@
+//! End-to-end durability test: the four merge CFs (`cf_pending_transfers`, `cf_merge_drains_applied`,
+//! `cf_merge_applied`, `cf_merge_tombstones`) plus the cascade's `cf_stage2` state survive a whole-DB
+//! checkpoint → S3 disaster restore, against a real Kafka/Redpanda broker + S3-compatible store
+//! (MinIO / SeaweedFS), with the cascade gate on and a single-pod static-membership deploy.
+//!
+//! `#[ignore]`d by default: needs a running broker + an S3-compatible store. Run serially:
+//!
+//! ```sh
+//! export KAFKA_HOSTS=localhost:9092
+//! export CHECKPOINT_S3_ENDPOINT=http://localhost:19000 # MinIO; or :8333 for SeaweedFS
+//! export CHECKPOINT_S3_BUCKET=cohort-checkpoints # must already exist
+//! export CHECKPOINT_S3_ACCESS_KEY_ID=... # MinIO/SeaweedFS creds
+//! export CHECKPOINT_S3_SECRET_ACCESS_KEY=...
+//! cargo test -p cohort-stream-processor --test merge_durability -- --ignored --test-threads=1
+//! ```
+
+use std::collections::HashSet;
+use std::future::Future;
+use std::panic::AssertUnwindSafe;
+use std::path::Path;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use chrono_tz::UTC;
+use cohort_stream_processor::config::Config;
+use cohort_stream_processor::consumers::{
+ CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, MergeRoute,
+ TransferRoute,
+};
+use cohort_stream_processor::filters::{
+ CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,
+};
+use cohort_stream_processor::merge::transfer::{
+ PersonMergeEvent, Tombstone, MERGE_EVENT_SCHEMA_VERSION,
+};
+use cohort_stream_processor::partitions::{
+ merge_partition_key, partition_of, run_rebalance_worker, CohortConsumerContext, Follower,
+ FollowerSet, OffsetTracker, PartitionRouter, COHORT_PARTITION_COUNT,
+};
+use cohort_stream_processor::producer::{
+ CohortMembershipChange, KafkaCascadeSink, KafkaMembershipSink, KafkaStreamEventSink,
+ KafkaTransferSink, MembershipSink, MembershipStatus, StreamEventSink, TransferSink,
+};
+use cohort_stream_processor::stage1::{Stage1State, StatefulRecord};
+use cohort_stream_processor::store::durability::{
+ run_boot_restore, store_hash_prefix, upload_cadence, CheckpointExporter, CheckpointSweeper,
+ OffsetManifest, RestoreSource, S3Uploader,
+};
+use cohort_stream_processor::store::{
+ CohortStore, LeafStateKey, Stage1Key, StoreConfig, TombstoneKey,
+};
+use cohort_stream_processor::sweep::Sweeper;
+use cohort_stream_processor::workers::{
+ CascadeConfig, MergeWorkerDeps, TransferRetryPolicy, DEFAULT_MERGE_GC_SCAN_LIMIT,
+};
+use common_kafka::config::KafkaConfig;
+use envconfig::Envconfig;
+use futures::FutureExt;
+use lifecycle::{ComponentOptions, Handle, Manager};
+use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
+use rdkafka::client::DefaultClientContext;
+use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};
+use rdkafka::message::Message;
+use rdkafka::producer::{FutureProducer, FutureRecord};
+use rdkafka::util::Timeout;
+use rdkafka::{ClientConfig, Offset, TopicPartitionList};
+use serde_json::json;
+use tokio::sync::mpsc;
+use tokio::task::JoinHandle;
+use uuid::Uuid;
+
+const TEAM: i32 = 7;
+const HASH: [u8; 16] = *b"0123456789abcdef";
+const NUM_PARTITIONS: i32 = COHORT_PARTITION_COUNT as i32;
+const TS: &str = "2026-06-10 12:34:56.789000";
+const TS_LATER: &str = "2026-06-10 13:34:56.789000";
+const MERGED_AT: i64 = 1_770_000_000_000;
+const COMMIT_INTERVAL: Duration = Duration::from_millis(250);
+const RECV_TIMEOUT: Duration = Duration::from_millis(200);
+
+const COHORT_SINGLE: i32 = 1;
+const COHORT_DAILY: i32 = 2;
+const COHORT_REF: i32 = 3;
+
+fn bootstrap_servers() -> String {
+ std::env::var("KAFKA_HOSTS").unwrap_or_else(|_| "localhost:9092".to_string())
+}
+
+/// Cohort 1: `performed_event` single. Cohort 2: `performed_event_multiple gte 2` daily.
+/// Cohort 3: pure cohort-ref to cohort 2, frozen with `freeze_with(UTC, true)` so it owns no
+/// state-keyed leaf and can only flip via cascade from cohort 2.
+fn merge_catalog() -> CatalogHandle {
+ let single = json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": 7, "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ });
+ let daily = json!({
+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",
+ "time_value": 7, "time_interval": "day", "operator": "gte", "operator_value": 2,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ });
+ let ref_leaf = json!({ "type": "cohort", "value": COHORT_DAILY, "negation": false });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(COHORT_SINGLE),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": [single] } }),
+ )
+ .expect("add single cohort");
+ builder
+ .add_cohort(
+ CohortId(COHORT_DAILY),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": [daily] } }),
+ )
+ .expect("add daily cohort");
+ builder
+ .add_cohort(
+ CohortId(COHORT_REF),
+ TeamId(TEAM),
+ &json!({ "properties": { "type": "AND", "values": [ref_leaf] } }),
+ )
+ .expect("add cohort-ref B");
+ CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ builder.freeze_with(UTC, true),
+ )]))
+}
+
+fn behavioral_lsks(catalog: &CatalogHandle) -> (LeafStateKey, LeafStateKey) {
+ let snapshot = catalog.load();
+ let team = snapshot.team(TeamId(TEAM)).expect("team in catalog");
+ let pick = |variant: cohort_stream_processor::stage1::StateVariant| {
+ team.by_condition_to_lsk[&HASH]
+ .iter()
+ .copied()
+ .find(|lsk| team.by_lsk[lsk].variant == variant)
+ .unwrap_or_else(|| panic!("no LSK for {variant:?}"))
+ };
+ (
+ pick(cohort_stream_processor::stage1::StateVariant::BehavioralSingle),
+ pick(cohort_stream_processor::stage1::StateVariant::BehavioralDailyBuckets),
+ )
+}
+
+async fn create_topic(topic: &str, partitions: i32) {
+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .create()
+ .expect("create admin client");
+ let new_topic = NewTopic::new(topic, partitions, TopicReplication::Fixed(1));
+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+ let results = admin
+ .create_topics(&[new_topic], &opts)
+ .await
+ .expect("create_topics");
+ for result in results {
+ match result {
+ Ok(_) | Err((_, rdkafka::types::RDKafkaErrorCode::TopicAlreadyExists)) => {}
+ Err((name, err)) => panic!("failed to create topic {name}: {err:?}"),
+ }
+ }
+ let verifier: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("metadata-verifier-{}", Uuid::new_v4()))
+ .create()
+ .expect("create metadata verifier");
+ let start = Instant::now();
+ loop {
+ let ready = verifier
+ .fetch_metadata(Some(topic), Duration::from_secs(5))
+ .ok()
+ .is_some_and(|metadata| {
+ metadata.topics().iter().any(|meta| {
+ meta.name() == topic
+ && meta.error().is_none()
+ && meta.partitions().len() == partitions as usize
+ })
+ });
+ if ready {
+ break;
+ }
+ assert!(
+ start.elapsed() < Duration::from_secs(30),
+ "timed out waiting for topic {topic} metadata to propagate",
+ );
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+}
+
+async fn delete_topics(topics: &[&str]) {
+ let admin: AdminClient<DefaultClientContext> = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .create()
+ .expect("create admin client");
+ let opts = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
+ if let Err(err) = admin.delete_topics(topics, &opts).await {
+ eprintln!("topic cleanup failed; leaked {topics:?}: {err}");
+ }
+}
+
+async fn with_topics_cleanup<F: Future<Output = ()>>(topics: &[&str], config: &Config, body: F) {
+ let result = AssertUnwindSafe(body).catch_unwind().await;
+ delete_topics(topics).await;
+ delete_s3_prefix(config).await;
+ if let Err(panic) = result {
+ std::panic::resume_unwind(panic);
+ }
+}
+
+/// `murmur2_random` is required so keyed produces co-partition with `partition_of`.
+fn producer_kafka_config() -> KafkaConfig {
+ KafkaConfig {
+ kafka_hosts: bootstrap_servers(),
+ kafka_tls: false,
+ kafka_client_rack: String::new(),
+ kafka_client_id: String::new(),
+ kafka_compression_codec: "none".to_string(),
+ kafka_producer_partitioner: Some("murmur2_random".to_string()),
+ kafka_producer_linger_ms: 20,
+ kafka_producer_queue_mib: 400,
+ kafka_producer_queue_messages: 10_000_000,
+ kafka_message_timeout_ms: 20_000,
+ kafka_producer_batch_size: None,
+ kafka_producer_batch_num_messages: None,
+ kafka_producer_enable_idempotence: None,
+ kafka_producer_max_in_flight_requests_per_connection: None,
+ kafka_producer_topic_metadata_refresh_interval_ms: None,
+ kafka_producer_message_max_bytes: None,
+ kafka_producer_sticky_partitioning_linger_ms: None,
+ }
+}
+
+fn murmur2_producer() -> FutureProducer {
+ ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("message.timeout.ms", "10000")
+ .set("partitioner", "murmur2_random")
+ .create()
+ .expect("create murmur2 producer")
+}
+
+fn events_client_config(group: &str) -> ClientConfig {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "earliest")
+ .set("partition.assignment.strategy", "cooperative-sticky")
+ .set("session.timeout.ms", "6000");
+ config
+}
+
+fn follower_client_config(group: &str) -> ClientConfig {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "earliest")
+ .set("socket.timeout.ms", "10000");
+ config
+}
+
+fn group_verifier(group: &str) -> StreamConsumer {
+ ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create group verifier")
+}
+
+/// Sum of committed offsets across all partitions (committed == next-offset-to-consume on a fresh topic).
+fn committed_sum(consumer: &StreamConsumer, topic: &str) -> i64 {
+ let mut tpl = TopicPartitionList::new();
+ for partition in 0..NUM_PARTITIONS {
+ tpl.add_partition(topic, partition);
+ }
+ let committed = consumer
+ .committed_offsets(tpl, Duration::from_secs(5))
+ .expect("fetch committed offsets");
+ (0..NUM_PARTITIONS)
+ .filter_map(|partition| committed.find_partition(topic, partition))
+ .map(|elem| match elem.offset() {
+ Offset::Offset(value) => value,
+ _ => 0,
+ })
+ .sum()
+}
+
+fn topic_message_count(topic: &str) -> i64 {
+ let consumer: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("watermark-verifier-{}", Uuid::new_v4()))
+ .create()
+ .expect("create watermark verifier");
+ (0..NUM_PARTITIONS)
+ .map(|partition| {
+ let (low, high) = consumer
+ .fetch_watermarks(topic, partition, Duration::from_secs(10))
+ .expect("fetch watermarks");
+ high - low
+ })
+ .sum()
+}
+
+/// Read up to `expected` messages (all partitions from the beginning). Assigned explicitly — no group
+/// join, no commit — so committed offsets the test asserts on are never perturbed.
+async fn consume_all(topic: &str, expected: usize, deadline: Duration) -> Vec<(i32, Vec<u8>)> {
+ let consumer: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("group.id", format!("scan-verifier-{}", Uuid::new_v4()))
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("create scan verifier");
+ let mut tpl = TopicPartitionList::new();
+ for partition in 0..NUM_PARTITIONS {
+ tpl.add_partition_offset(topic, partition, Offset::Beginning)
+ .expect("add partition to scan TPL");
+ }
+ consumer.assign(&tpl).expect("assign scan verifier");
+
+ let mut messages = Vec::new();
+ let start = Instant::now();
+ while messages.len() < expected && start.elapsed() < deadline {
+ match tokio::time::timeout(Duration::from_secs(2), consumer.recv()).await {
+ Ok(Ok(message)) => {
+ if let Some(payload) = message.payload() {
+ messages.push((message.partition(), payload.to_vec()));
+ }
+ }
+ Ok(Err(err)) => panic!("scan verifier recv error: {err}"),
+ Err(_) => {}
+ }
+ }
+ messages
+}
+
+async fn shadow_changes(topic: &str, expected: usize) -> Vec<CohortMembershipChange> {
+ consume_all(topic, expected, Duration::from_secs(30))
+ .await
+ .iter()
+ .map(|(_, payload)| serde_json::from_slice(payload).expect("decode membership change"))
+ .collect()
+}
+
+async fn wait_for(what: &str, deadline: Duration, mut condition: impl FnMut() -> bool) {
+ let start = Instant::now();
+ while !condition() {
+ assert!(
+ start.elapsed() < deadline,
+ "timed out after {deadline:?} waiting for {what}",
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+}
+
+/// Poll the full shadow topic until a change matching `predicate` appears, or `deadline` elapses.
+/// Each poll rescans the live watermark — the target change may not be in the first N messages.
+async fn wait_for_shadow_change(
+ topic: &str,
+ deadline: Duration,
+ what: &str,
+ predicate: impl Fn(&CohortMembershipChange) -> bool,
+) -> bool {
+ let start = Instant::now();
+ loop {
+ let total = topic_message_count(topic) as usize;
+ if total > 0 && shadow_changes(topic, total).await.iter().any(&predicate) {
+ return true;
+ }
+ if start.elapsed() >= deadline {
+ eprintln!("timed out after {deadline:?} waiting for {what}");
+ return false;
+ }
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+}
+
+fn part(person: Uuid) -> u16 {
+ partition_of(TeamId(TEAM), &person, COHORT_PARTITION_COUNT) as u16
+}
+
+struct PersonAlloc(u128);
+
+impl PersonAlloc {
+ fn new() -> Self {
+ Self(0xA1CE_0000)
+ }
+
+ fn next_on(&mut self, accept: impl Fn(u16) -> bool) -> Uuid {
+ loop {
+ self.0 += 1;
+ let person = Uuid::from_u128(self.0);
+ if accept(part(person)) {
+ return person;
+ }
+ }
+ }
+
+ fn next(&mut self) -> Uuid {
+ self.next_on(|_| true)
+ }
+
+ /// Cross-partition pair: P_old and P_new hash to different partitions.
+ fn cross_partition_pair(&mut self) -> (Uuid, Uuid) {
+ let old = self.next();
+ let new = self.next_on(|p| p != part(old));
+ (old, new)
+ }
+
+ /// Same-partition pair: Q_old and Q_new hash to the same partition (fast path).
+ fn same_partition_pair(&mut self) -> (Uuid, Uuid) {
+ let old = self.next();
+ let new = self.next_on(|p| p == part(old));
+ (old, new)
+ }
+}
+
+fn envelope(person: Uuid, ts: &str, source_offset: i64) -> Vec<u8> {
+ serde_json::to_vec(&json!({
+ "team_id": TEAM,
+ "person_id": person.to_string(),
+ "distinct_id": "d",
+ "uuid": Uuid::from_u128(0xE0_0000 + source_offset as u128).to_string(),
+ "event": "$pageview",
+ "timestamp": ts,
+ "properties": "{}",
+ "person_properties": null,
+ "elements_chain": null,
+ "source_offset": source_offset,
+ "source_partition": 0,
+ }))
+ .expect("serialize envelope")
+}
+
+async fn produce_event(
+ producer: &FutureProducer,
+ topic: &str,
+ person: Uuid,
+ ts: &str,
+ source_offset: i64,
+) {
+ let key = merge_partition_key(TeamId(TEAM), &person);
+ let payload = envelope(person, ts, source_offset);
+ let (partition, _offset) = producer
+ .send(
+ FutureRecord::to(topic).key(&key).payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce event");
+ assert_eq!(
+ partition as u32,
+ partition_of(TeamId(TEAM), &person, COHORT_PARTITION_COUNT),
+ "seed event must co-partition with the merge protocol's arithmetic",
+ );
+}
+
+fn merge_event(old: Uuid, new: Uuid) -> PersonMergeEvent {
+ PersonMergeEvent {
+ team_id: TEAM,
+ old_person_uuid: old,
+ new_person_uuid: new,
+ merged_at_ms: MERGED_AT,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ }
+}
+
+async fn produce_merge(producer: &FutureProducer, topic: &str, event: &PersonMergeEvent) {
+ let key = merge_partition_key(TeamId(event.team_id), &event.old_person_uuid);
+ let payload = event.encode();
+ let (partition, _offset) = producer
+ .send(
+ FutureRecord::to(topic).key(&key).payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce merge event");
+ assert_eq!(
+ partition as u32,
+ partition_of(
+ TeamId(event.team_id),
+ &event.old_person_uuid,
+ COHORT_PARTITION_COUNT
+ ),
+ "merge trigger must land on P_old's partition",
+ );
+}
+
+fn open_restored_store(path: &Path) -> CohortStore {
+ CohortStore::open(&StoreConfig {
+ path: path.to_path_buf(),
+ wipe_on_start: false,
+ ..StoreConfig::default()
+ })
+ .expect("open restored store")
+}
+
+fn stage1_state(
+ store: &CohortStore,
+ partition_id: u16,
+ lsk: LeafStateKey,
+ person: Uuid,
+) -> Option<Stage1State> {
+ let key = Stage1Key {
+ partition_id,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person,
+ };
+ store
+ .get_stage1(&key)
+ .unwrap()
+ .map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)
+}
+
+fn daily_total(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<u64> {
+ match stage1_state(store, part(person), lsk, person)? {
+ Stage1State::BehavioralDailyBuckets { buckets, .. } => {
+ Some(buckets.iter().map(|&count| count as u64).sum())
+ }
+ other => panic!("expected daily buckets for {person}, got {other:?}"),
+ }
+}
+
+fn single_matches(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<bool> {
+ match stage1_state(store, part(person), lsk, person)? {
+ Stage1State::BehavioralSingle { has_match, .. } => Some(has_match),
+ other => panic!("expected single state for {person}, got {other:?}"),
+ }
+}
+
+fn tombstone_for(store: &CohortStore, person: Uuid) -> Option<Tombstone> {
+ store
+ .get_tombstone(&TombstoneKey {
+ partition_id: part(person),
+ team_id: TEAM as u64,
+ person,
+ })
+ .unwrap()
+ .map(|bytes| Tombstone::decode(&bytes).unwrap())
+}
+
+struct Topics {
+ events: String,
+ merges: String,
+ transfers: String,
+ cascade: String,
+ shadow: String,
+}
+
+impl Topics {
+ fn unique(suffix: &Uuid) -> Self {
+ Self {
+ events: format!("cohort_stream_events_durable_{suffix}"),
+ merges: format!("person_merge_events_{suffix}"),
+ transfers: format!("cohort_merge_state_transfer_{suffix}"),
+ cascade: format!("cohort_cascade_events_{suffix}"),
+ shadow: format!("cohort_membership_changed_{suffix}"),
+ }
+ }
+
+ async fn create(&self) {
+ for topic in self.names() {
+ create_topic(topic, NUM_PARTITIONS).await;
+ }
+ }
+
+ fn names(&self) -> [&str; 5] {
+ [
+ &self.events,
+ &self.merges,
+ &self.transfers,
+ &self.cascade,
+ &self.shadow,
+ ]
+ }
+}
+
+struct Groups {
+ events: String,
+ merges: String,
+ transfers: String,
+ cascade: String,
+}
+
+impl Groups {
+ fn unique(suffix: &Uuid) -> Self {
+ Self {
+ events: format!("cohort-stream-processor-{suffix}"),
+ merges: format!("cohort-stream-merges-{suffix}"),
+ transfers: format!("cohort-stream-merge-apply-{suffix}"),
+ cascade: format!("cohort-stream-cascade-{suffix}"),
+ }
+ }
+}
+
+fn register_instance(manager: &mut Manager, name: &str) -> [Handle; 4] {
+ let options = || ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15));
+ [
+ manager.register(&format!("consumer-{name}"), options()),
+ manager.register(&format!("merge-follower-{name}"), options()),
+ manager.register(&format!("transfer-follower-{name}"), options()),
+ manager.register(&format!("cascade-follower-{name}"), options()),
+ ]
+}
+
+struct Instance {
+ store: CohortStore,
+ dispatcher: Arc<EventDispatcher>,
+ tasks: Vec<JoinHandle<()>>,
+ /// Cloned before the originals move into deps/dispatcher so the sweeper reads the same tracker
+ /// instances the running consumers mutate (manifest captures follower offsets with content).
+ events_tracker: Arc<OffsetTracker>,
+ merge_tracker: Arc<OffsetTracker>,
+ transfer_tracker: Arc<OffsetTracker>,
+ cascade_tracker: Arc<OffsetTracker>,
+}
+
+impl Instance {
+ fn owned(&self) -> HashSet<i32> {
+ self.dispatcher.owned_partitions().into_iter().collect()
+ }
+
+ async fn join(self) {
+ for task in self.tasks {
+ task.await.expect("instance task panicked");
+ }
+ }
+}
+
+/// An optional restore `manifest` seeds follower group committed offsets before the rebalance worker
+/// assigns, so each `incremental_assign(Offset::Stored)` resolves to the restored position.
+#[allow(clippy::too_many_arguments)]
+async fn spawn_instance(
+ topics: &Topics,
+ groups: &Groups,
+ store: CohortStore,
+ catalog: CatalogHandle,
+ handles: [Handle; 4],
+ durable_restore: bool,
+ manifest: Option<OffsetManifest>,
+) -> Instance {
+ let [events_handle, merge_handle, transfer_handle, cascade_handle] = handles;
+ let kafka_config = producer_kafka_config();
+
+ let transfer_sink: Arc<dyn TransferSink> = Arc::new(
+ KafkaTransferSink::new(&kafka_config, topics.transfers.clone())
+ .await
+ .expect("create transfer sink"),
+ );
+ let stream_event_sink: Arc<dyn StreamEventSink> = Arc::new(
+ KafkaStreamEventSink::new(&kafka_config, topics.events.clone())
+ .await
+ .expect("create re-key sink"),
+ );
+ let cascade_sink = Arc::new(
+ KafkaCascadeSink::new(&kafka_config, topics.cascade.clone())
+ .await
+ .expect("create cascade sink"),
+ );
+ let membership_sink: Arc<dyn MembershipSink> = Arc::new(
+ KafkaMembershipSink::new(&kafka_config, topics.shadow.clone())
+ .await
+ .expect("create membership sink"),
+ );
+
+ let events_tracker = Arc::new(OffsetTracker::new());
+ let merge_tracker = Arc::new(OffsetTracker::new());
+ let transfer_tracker = Arc::new(OffsetTracker::new());
+ let cascade_tracker = Arc::new(OffsetTracker::new());
+
+ let events_tracker_for_instance = events_tracker.clone();
+ let merge_tracker_for_instance = merge_tracker.clone();
+ let transfer_tracker_for_instance = transfer_tracker.clone();
+ let cascade_tracker_for_instance = cascade_tracker.clone();
+
+ let merge_deps = Arc::new(MergeWorkerDeps {
+ transfer_sink,
+ stream_event_sink,
+ merge_tracker,
+ transfer_tracker,
+ retry: TransferRetryPolicy::default(),
+ gc_scan_limit: DEFAULT_MERGE_GC_SCAN_LIMIT,
+ stage2_orphan_gc_enabled: true,
+ cascade_sink,
+ cascade_tracker,
+ cascade: CascadeConfig {
+ enabled: true,
+ depth_cap: 8,
+ fanout_cap: 1000,
+ },
+ partition_count: COHORT_PARTITION_COUNT,
+ });
+
+ let dispatcher = Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ events_tracker,
+ store.clone(),
+ Arc::new(catalog),
+ membership_sink,
+ merge_deps,
+ ));
+ if durable_restore {
+ dispatcher.enable_durable_restore();
+ }
+
+ let merges_consumer: Arc<StreamConsumer> = Arc::new(
+ follower_client_config(&groups.merges)
+ .create()
+ .expect("create merges follower consumer"),
+ );
+ let transfers_consumer: Arc<StreamConsumer> = Arc::new(
+ follower_client_config(&groups.transfers)
+ .create()
+ .expect("create transfers follower consumer"),
+ );
+ let cascade_consumer: Arc<StreamConsumer> = Arc::new(
+ follower_client_config(&groups.cascade)
+ .create()
+ .expect("create cascade follower consumer"),
+ );
+
+ if let Some(manifest) = manifest.as_ref() {
+ commit_follower_offsets_from_manifest(&merges_consumer, &topics.merges, manifest);
+ commit_follower_offsets_from_manifest(&transfers_consumer, &topics.transfers, manifest);
+ commit_follower_offsets_from_manifest(&cascade_consumer, &topics.cascade, manifest);
+ }
+
+ let followers = Arc::new(FollowerSet::new([
+ Follower::new(merges_consumer.clone(), topics.merges.clone()),
+ Follower::new(transfers_consumer.clone(), topics.transfers.clone()),
+ Follower::new(cascade_consumer.clone(), topics.cascade.clone()),
+ ]));
+
+ let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());
+ let events_client: StreamConsumer<CohortConsumerContext> = events_client_config(&groups.events)
+ .create_with_context(context)
+ .expect("create events consumer");
+ events_client
+ .subscribe(&[topics.events.as_str()])
+ .expect("subscribe events");
+
+ let (command_tx, command_rx) = mpsc::unbounded_channel();
+ let mut tasks = vec![tokio::spawn(run_rebalance_worker(
+ rebalance_rx,
+ dispatcher.clone(),
+ followers,
+ command_tx,
+ events_handle.shutdown_token(),
+ ))];
+
+ let merge_follower = FollowerConsumer::<MergeRoute>::new(
+ merges_consumer,
+ topics.merges.clone(),
+ dispatcher.clone(),
+ merge_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ );
+ tasks.push(tokio::spawn(merge_follower.process()));
+
+ let transfer_follower = FollowerConsumer::<TransferRoute>::new(
+ transfers_consumer,
+ topics.transfers.clone(),
+ dispatcher.clone(),
+ transfer_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ );
+ tasks.push(tokio::spawn(transfer_follower.process()));
+
+ let cascade_follower = FollowerConsumer::<CascadeRoute>::new(
+ cascade_consumer,
+ topics.cascade.clone(),
+ dispatcher.clone(),
+ cascade_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ );
+ tasks.push(tokio::spawn(cascade_follower.process()));
+
+ let events_consumer = CohortStreamEventsConsumer::new(
+ events_client,
+ topics.events.clone(),
+ dispatcher.clone(),
+ events_handle,
+ 100,
+ RECV_TIMEOUT,
+ COMMIT_INTERVAL,
+ NUM_PARTITIONS as usize,
+ command_rx,
+ manifest,
+ );
+ tasks.push(tokio::spawn(events_consumer.process()));
+
+ Instance {
+ store,
+ dispatcher,
+ tasks,
+ events_tracker: events_tracker_for_instance,
+ merge_tracker: merge_tracker_for_instance,
+ transfer_tracker: transfer_tracker_for_instance,
+ cascade_tracker: cascade_tracker_for_instance,
+ }
+}
+
+/// Seeds a follower group's committed offsets from the manifest so `incremental_assign(Offset::Stored)`
+/// resolves to the restored position. No-op when the manifest has no entries for `topic`.
+fn commit_follower_offsets_from_manifest(
+ consumer: &StreamConsumer,
+ topic: &str,
+ manifest: &OffsetManifest,
+) {
+ let Some(partitions) = manifest.topics.get(topic) else {
+ return;
+ };
+ if partitions.is_empty() {
+ return;
+ }
+ let mut tpl = TopicPartitionList::new();
+ for (&partition, &next_offset) in partitions {
+ tpl.add_partition_offset(topic, partition, Offset::Offset(next_offset))
+ .expect("add follower partition to manifest commit TPL");
+ }
+ if tpl.count() > 0 {
+ consumer
+ .commit(&tpl, CommitMode::Sync)
+ .expect("seed follower group offsets from restore manifest");
+ }
+}
+
+/// `durable_restore_enabled && cohort_cascade_enabled` requires `durable_restore_single_pod &&
+/// pod_identity().is_some()` to pass `validate_durability_startup`, so those knobs are set too.
+#[allow(clippy::too_many_arguments)]
+fn merge_durability_config(
+ store_path: &Path,
+ checkpoint_dir: &Path,
+ prefix: &str,
+ topics: &Topics,
+ groups: &Groups,
+) -> Config {
+ let mut env: std::collections::HashMap<String, String> = std::collections::HashMap::new();
+ env.insert("CHECKPOINT_ENABLED".into(), "true".into());
+ env.insert("DURABLE_RESTORE_ENABLED".into(), "true".into());
+ env.insert("COHORT_CASCADE_ENABLED".into(), "true".into());
+ env.insert("DURABLE_RESTORE_SINGLE_POD".into(), "true".into());
+ env.insert(
+ "POD_NAME".into(),
+ format!("merge-durability-{}", Uuid::new_v4()),
+ );
+ env.insert("KAFKA_HOSTS".into(), bootstrap_servers());
+ env.insert(
+ "STORE_PATH".into(),
+ store_path.to_string_lossy().into_owned(),
+ );
+ env.insert(
+ "CHECKPOINT_LOCAL_DIR".into(),
+ checkpoint_dir.to_string_lossy().into_owned(),
+ );
+ env.insert("CHECKPOINT_S3_PREFIX".into(), prefix.to_string());
+ env.insert("CHECKPOINT_S3_FORCE_PATH_STYLE".into(), "true".into());
+ env.insert("COHORT_STREAM_EVENTS_TOPIC".into(), topics.events.clone());
+ env.insert("PERSON_MERGE_EVENTS_TOPIC".into(), topics.merges.clone());
+ env.insert(
+ "COHORT_MERGE_STATE_TRANSFER_TOPIC".into(),
+ topics.transfers.clone(),
+ );
+ env.insert("COHORT_CASCADE_EVENTS_TOPIC".into(), topics.cascade.clone());
+ env.insert(
+ "COHORT_MEMBERSHIP_CHANGED_TOPIC".into(),
+ topics.shadow.clone(),
+ );
+ env.insert("KAFKA_CONSUMER_GROUP".into(), groups.events.clone());
+ env.insert("KAFKA_MERGE_CONSUMER_GROUP".into(), groups.merges.clone());
+ env.insert(
+ "KAFKA_MERGE_APPLY_CONSUMER_GROUP".into(),
+ groups.transfers.clone(),
+ );
+ env.insert(
+ "KAFKA_CASCADE_CONSUMER_GROUP".into(),
+ groups.cascade.clone(),
+ );
+ for key in [
+ "CHECKPOINT_S3_BUCKET",
+ "CHECKPOINT_S3_ENDPOINT",
+ "CHECKPOINT_S3_REGION",
+ "CHECKPOINT_S3_ACCESS_KEY_ID",
+ "CHECKPOINT_S3_SECRET_ACCESS_KEY",
+ ] {
+ if let Ok(value) = std::env::var(key) {
+ env.insert(key.into(), value);
+ }
+ }
+ let config = Config::init_from_hashmap(&env).expect("build merge-durability config");
+ config
+ .validate_durability_startup()
+ .expect("merge-durability config must satisfy the durability startup guard");
+ config
+}
+
+/// Deletes all S3 objects written by this run: hash-prefixed checkpoint files and bare-prefix
+/// metadata.json. Best-effort; errors are ignored so cleanup never fails a passing test.
+async fn delete_s3_prefix(config: &Config) {
+ use futures::StreamExt;
+ use object_store::aws::AmazonS3Builder;
+ use object_store::path::Path as ObjPath;
+ use object_store::{ClientOptions, ObjectStore, ObjectStoreExt};
+
+ let d = config.durability_config();
+ let mut builder = AmazonS3Builder::from_env()
+ .with_bucket_name(&d.s3_bucket)
+ .with_client_options(ClientOptions::new());
+ if let Some(region) = d.aws_region.as_deref() {
+ builder = builder.with_region(region);
+ }
+ if let Some(endpoint) = d.s3_endpoint.as_deref() {
+ builder = builder.with_endpoint(endpoint);
+ if endpoint.starts_with("http://") {
+ builder = builder.with_allow_http(true);
+ }
+ }
+ if let (Some(ak), Some(sk)) = (
+ d.s3_access_key_id.as_deref(),
+ d.s3_secret_access_key.as_deref(),
+ ) {
+ builder = builder.with_access_key_id(ak).with_secret_access_key(sk);
+ }
+ if d.s3_force_path_style {
+ builder = builder.with_virtual_hosted_style_request(false);
+ }
+ let store = match builder.build() {
+ Ok(store) => store,
+ Err(_) => return,
+ };
+ // Checkpoint SSTs are keyed under `<hash>/<s3_key_prefix>/…`; metadata.json at the bare prefix.
+ let hashed = format!("{}/{}", store_hash_prefix(), d.s3_key_prefix);
+ for raw_prefix in [d.s3_key_prefix.as_str(), hashed.as_str()] {
+ let prefix = ObjPath::from(raw_prefix);
+ let mut stream = store.list(Some(&prefix));
+ while let Some(entry) = stream.next().await {
+ if let Ok(meta) = entry {
+ let _result = store.delete(&meta.location).await;
+ }
+ }
+ }
+}
+
+/// Runs one checkpoint tick against the live trackers + running dispatcher and uploads to S3.
+/// `upload_cadence` resolves to 1 so this first tick always uploads.
+async fn checkpoint_to_s3(
+ instance: &Instance,
+ config: &Config,
+ topics: &Topics,
+ checkpoint_dir: &Path,
+) {
+ let uploader = S3Uploader::new(config.durability_config())
+ .await
+ .expect("build S3 uploader (is the bucket reachable?)");
+ let exporter = CheckpointExporter::new(Box::new(uploader));
+ let sweeper = CheckpointSweeper::new(
+ instance.store.clone(),
+ instance.dispatcher.clone(),
+ vec![
+ (topics.events.clone(), instance.events_tracker.clone()),
+ (topics.merges.clone(), instance.merge_tracker.clone()),
+ (topics.transfers.clone(), instance.transfer_tracker.clone()),
+ (topics.cascade.clone(), instance.cascade_tracker.clone()),
+ ],
+ exporter,
+ config.durability_config(),
+ checkpoint_dir.to_path_buf(),
+ upload_cadence(
+ config.checkpoint_interval_ms,
+ config.checkpoint_s3_upload_interval_ms,
+ ),
+ );
+ sweeper.run_once().await;
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn complete_cross_partition_merge(
+ instance: &Instance,
+ producer: &FutureProducer,
+ topics: &Topics,
+ groups: &Groups,
+ single_lsk: LeafStateKey,
+ daily_lsk: LeafStateKey,
+ p_old: Uuid,
+ p_new: Uuid,
+ seed_base_offset: i64,
+) {
+ produce_event(producer, &topics.events, p_old, TS, seed_base_offset).await;
+ produce_event(producer, &topics.events, p_old, TS, seed_base_offset + 1).await;
+ wait_for(
+ "P_old's seeded daily state",
+ Duration::from_secs(60),
+ || daily_total(&instance.store, daily_lsk, p_old) == Some(2),
+ )
+ .await;
+
+ produce_merge(producer, &topics.merges, &merge_event(p_old, p_new)).await;
+
+ let merge_verifier = group_verifier(&groups.merges);
+ let transfer_verifier = group_verifier(&groups.transfers);
+ wait_for(
+ "the merge + transfer to complete on P_new (state moved, tombstone, both groups committed)",
+ Duration::from_secs(90),
+ || {
+ daily_total(&instance.store, daily_lsk, p_new) == Some(2)
+ && single_matches(&instance.store, single_lsk, p_new) == Some(true)
+ && tombstone_for(&instance.store, p_old).map(|t| t.new_person) == Some(p_new)
+ && committed_sum(&merge_verifier, &topics.merges) >= 1
+ && committed_sum(&transfer_verifier, &topics.transfers) >= 1
+ },
+ )
+ .await;
+}
+
+#[tokio::test(flavor = "multi_thread")]
+#[ignore = "requires Kafka + MinIO; run with --ignored --test-threads=1"]
+async fn merge_and_cascade_state_survive_an_s3_disaster_restore() {
+ let suffix = Uuid::new_v4();
+ let topics = Topics::unique(&suffix);
+ let groups = Groups::unique(&suffix);
+ let prefix = format!("cohort-stream-checkpoints-merge-itest/{suffix}");
+
+ // Store and checkpoint dirs must be sibling subtrees, never nested (rocksdb hard-links SSTs into
+ // the checkpoint).
+ let root = tempfile::TempDir::new().unwrap();
+ let store_path = root.path().join("db");
+ let checkpoint_dir = root.path().join("checkpoints");
+ let config = merge_durability_config(&store_path, &checkpoint_dir, &prefix, &topics, &groups);
+
+ let names = topics.names();
+ let config_for_cleanup = config.clone();
+ with_topics_cleanup(&names, &config_for_cleanup, async {
+ topics.create().await;
+
+ let catalog = merge_catalog();
+ let (single_lsk, daily_lsk) = behavioral_lsks(&catalog);
+
+ // Tenure 1: drive merges through all CFs + the cascade, then checkpoint to S3.
+ let mut manager = Manager::builder("merge-durability-itest-1")
+ .with_trap_signals(false)
+ .build();
+ let handles = register_instance(&mut manager, "a");
+ let shutdown = handles[0].clone();
+ let _monitor = manager.monitor_background();
+
+ let store1 = CohortStore::open(&config.store_config()).expect("open tenure-1 store");
+ let instance = spawn_instance(
+ &topics,
+ &groups,
+ store1,
+ catalog,
+ handles,
+ config.durable_restore_enabled,
+ None,
+ )
+ .await;
+ wait_for(
+ "the consumer to own every partition",
+ Duration::from_secs(30),
+ || instance.owned().len() == NUM_PARTITIONS as usize,
+ )
+ .await;
+
+ let mut alloc = PersonAlloc::new();
+
+ // Cross-partition merge: drain (cf_merge_drains_applied + tombstone), transfer + apply
+ // (cf_merge_applied), and the apply's cascade flip of cohort 3 (cf_stage2).
+ let (p_old, p_new) = alloc.cross_partition_pair();
+ complete_cross_partition_merge(
+ &instance, &murmur2_producer(), &topics, &groups, single_lsk, daily_lsk, p_old, p_new, 0,
+ )
+ .await;
+ // Cohort 3's cascade flip for P_new is not in a predictable position on the shadow topic
+ // (P_old's cohort 1/2 flips land first), so poll the live watermark for the specific change.
+ let cascade_into_p_new = wait_for_shadow_change(
+ &topics.shadow,
+ Duration::from_secs(60),
+ "the cascade to re-evaluate B (cohort 3, a pure ref to cohort 2) into P_new's membership",
+ |change| {
+ change.cohort_id == COHORT_REF
+ && change.person_id == p_new.to_string()
+ && change.status == MembershipStatus::Entered
+ },
+ )
+ .await;
+ assert!(
+ cascade_into_p_new,
+ "the cascade re-evaluated B (cohort 3, a pure ref to cohort 2) into P_new's membership",
+ );
+
+ // Same-partition merge: fast path (one worker, no Kafka transfer).
+ let (q_old, q_new) = alloc.same_partition_pair();
+ assert_eq!(
+ part(q_old),
+ part(q_new),
+ "same-partition pair must share a worker (fast path)",
+ );
+ let producer = murmur2_producer();
+ produce_event(&producer, &topics.events, q_old, TS, 10).await;
+ produce_event(&producer, &topics.events, q_old, TS, 11).await;
+ wait_for("Q_old's seeded daily state", Duration::from_secs(60), || {
+ daily_total(&instance.store, daily_lsk, q_old) == Some(2)
+ })
+ .await;
+ produce_merge(&producer, &topics.merges, &merge_event(q_old, q_new)).await;
+ wait_for(
+ "the same-partition merge to move state to Q_new + tombstone Q_old",
+ Duration::from_secs(90),
+ || {
+ daily_total(&instance.store, daily_lsk, q_new) == Some(2)
+ && single_matches(&instance.store, single_lsk, q_new) == Some(true)
+ && daily_total(&instance.store, daily_lsk, q_old).is_none()
+ && tombstone_for(&instance.store, q_old).map(|t| t.new_person) == Some(q_new)
+ },
+ )
+ .await;
+
+ // Wait until committed offsets equal produced counts before checkpointing, so the manifest
+ // cannot under-record.
+ let merge_count = topic_message_count(&topics.merges);
+ let transfer_count = topic_message_count(&topics.transfers);
+ assert_eq!(merge_count, 2, "two merge triggers on the wire");
+ assert_eq!(
+ transfer_count, 1,
+ "exactly one transfer (cross-partition only; the same-partition merge is the fast path)",
+ );
+ let merge_verifier = group_verifier(&groups.merges);
+ let transfer_verifier = group_verifier(&groups.transfers);
+ wait_for(
+ "every follower group's committed offset to equal its produced count before checkpoint",
+ Duration::from_secs(90),
+ || {
+ committed_sum(&merge_verifier, &topics.merges) == merge_count
+ && committed_sum(&transfer_verifier, &topics.transfers) == transfer_count
+ },
+ )
+ .await;
+
+ // Checkpoint while the dispatcher owns all 64 partitions so follower maps are non-empty.
+ assert_eq!(
+ instance.owned().len(),
+ NUM_PARTITIONS as usize,
+ "the dispatcher must still own all 64 partitions at checkpoint time",
+ );
+ checkpoint_to_s3(&instance, &config, &topics, &checkpoint_dir).await;
+
+ shutdown.request_shutdown();
+ instance.join().await;
+
+ // Simulate PVC loss: delete the live store and local checkpoint dir.
+ std::fs::remove_dir_all(&store_path).expect("remove store_path (simulate PVC loss)");
+ std::fs::remove_dir_all(&checkpoint_dir)
+ .expect("remove checkpoint_local_dir (simulate PVC loss)");
+
+ // Tenure 2: restore from S3, then verify the manifest and restored state.
+ let restore = run_boot_restore(&config, &store_path).await;
+ assert!(
+ matches!(restore.source, RestoreSource::S3),
+ "with the live store and local checkpoint gone, the restore must come from S3 (got {:?})",
+ restore.source,
+ );
+ let manifest = restore
+ .manifest
+ .clone()
+ .expect("an S3 restore yields an offset manifest to seek");
+
+ // Follower manifest maps are non-empty: merge offset on P_old's partition, transfer on P_new's.
+ assert!(
+ manifest.offset_for(&topics.merges, part(p_old) as i32) >= Some(1),
+ "the restored manifest must carry the merge follower's offset on P_old's partition \
+ (non-empty follower map): {:?}",
+ manifest.offset_for(&topics.merges, part(p_old) as i32),
+ );
+ assert!(
+ manifest.offset_for(&topics.transfers, part(p_new) as i32) >= Some(1),
+ "the restored manifest must carry the transfer follower's offset on P_new's partition: {:?}",
+ manifest.offset_for(&topics.transfers, part(p_new) as i32),
+ );
+
+ let store2 = open_restored_store(&store_path);
+ assert_eq!(
+ daily_total(&store2, daily_lsk, p_new),
+ Some(2),
+ "cross-partition P_new daily count restored exactly (a cold start would read None)",
+ );
+ assert_eq!(single_matches(&store2, single_lsk, p_new), Some(true));
+ assert_eq!(
+ tombstone_for(&store2, p_old).map(|t| t.new_person),
+ Some(p_new),
+ "cross-partition P_old's tombstone (cf_merge_tombstones) survived the restore",
+ );
+ assert_eq!(
+ daily_total(&store2, daily_lsk, p_old),
+ None,
+ "cross-partition P_old's drained state stays drained after restore",
+ );
+ assert_eq!(
+ daily_total(&store2, daily_lsk, q_new),
+ Some(2),
+ "same-partition Q_new daily count restored exactly",
+ );
+ assert_eq!(single_matches(&store2, single_lsk, q_new), Some(true));
+ assert_eq!(
+ tombstone_for(&store2, q_old).map(|t| t.new_person),
+ Some(q_new),
+ "same-partition Q_old's tombstone survived the restore",
+ );
+ assert_eq!(daily_total(&store2, daily_lsk, q_old), None);
+ // cf_stage2 bit survived: membership is read from the restored store, not recomputed on boot.
+ assert!(
+ stage2_in_cohort(&store2, COHORT_REF, p_new),
+ "B's (cohort 3) cf_stage2 membership bit for P_new survived the restore",
+ );
+
+ drop(store2); // release the read-only handle so the consumer can reopen it live
+ let mut manager2 = Manager::builder("merge-durability-itest-2")
+ .with_trap_signals(false)
+ .build();
+ let handles2 = register_instance(&mut manager2, "b");
+ let shutdown2 = handles2[0].clone();
+ let _monitor2 = manager2.monitor_background();
+
+ let store2_live = open_restored_store(&store_path);
+ let instance2 = spawn_instance(
+ &topics,
+ &groups,
+ store2_live,
+ merge_catalog(),
+ handles2,
+ config.durable_restore_enabled,
+ Some(manifest.clone()),
+ )
+ .await;
+ wait_for(
+ "tenure 2 to own every partition (boot sweep + eager redrive + restore-seek settled)",
+ Duration::from_secs(30),
+ || instance2.owned().len() == NUM_PARTITIONS as usize,
+ )
+ .await;
+
+ // Post-restore straggler for P_old redirects via the restored tombstone; P_old not rebuilt.
+ produce_event(&producer, &topics.events, p_old, TS_LATER, 1000).await;
+ wait_for(
+ "the post-restore straggler to fold into P_new via the restored tombstone",
+ Duration::from_secs(60),
+ || daily_total(&instance2.store, daily_lsk, p_new) == Some(3),
+ )
+ .await;
+ assert_eq!(
+ daily_total(&instance2.store, daily_lsk, p_old),
+ None,
+ "the restored tombstone redirected the straggler; P_old state was never rebuilt",
+ );
+ assert_eq!(
+ single_matches(&instance2.store, single_lsk, p_new),
+ Some(true),
+ "P_new's single match holds after the straggler",
+ );
+
+ // Replayed merge is deduped by the restored cf_merge_drains_applied / cf_merge_applied markers.
+ produce_merge(&producer, &topics.merges, &merge_event(p_old, p_new)).await;
+ let merge_verifier2 = group_verifier(&groups.merges);
+ wait_for(
+ "the replayed merge to settle (its commit advances) without a second transfer",
+ Duration::from_secs(60),
+ || committed_sum(&merge_verifier2, &topics.merges) >= 3, // replay is the 3rd merge on wire
+ )
+ .await;
+ assert_eq!(
+ topic_message_count(&topics.transfers),
+ 1,
+ "the replayed merge produced no second transfer (restored drain marker dedups it)",
+ );
+ assert_eq!(
+ daily_total(&instance2.store, daily_lsk, p_new),
+ Some(3),
+ "P_new's count is unchanged by the replayed merge (apply marker dedups it)",
+ );
+
+ // Restore-seek neither skips nor re-folds: committed-sum must equal the topic message count.
+ // 4 seeds (2 per pair) + 1 straggler + 1 re-key = 6 events on the wire.
+ let events_verifier = group_verifier(&groups.events);
+ wait_for(
+ "the events committed-sum to reach every produced + re-keyed event",
+ Duration::from_secs(60),
+ || committed_sum(&events_verifier, &topics.events) == topic_message_count(&topics.events),
+ )
+ .await;
+ assert_eq!(
+ committed_sum(&events_verifier, &topics.events),
+ topic_message_count(&topics.events),
+ "events resumed exactly at the manifest offset — no skip, no re-fold",
+ );
+
+ // Direct changes are exact. Cascade-origin cohort 3 is at-least-once, bounded [1, 2]:
+ // the cascade produces the flip before committing the cf_stage2 bit, so a restore can
+ // re-emit once per pair — but a systematic double is a bug.
+ let total_shadow = topic_message_count(&topics.shadow) as usize;
+ let changes = shadow_changes(&topics.shadow, total_shadow).await;
+
+ for cohort in [COHORT_SINGLE, COHORT_DAILY] {
+ for p_new in [p_new, q_new] {
+ let entered = changes
+ .iter()
+ .filter(|c| {
+ c.cohort_id == cohort
+ && c.person_id == p_new.to_string()
+ && c.status == MembershipStatus::Entered
+ })
+ .count();
+ assert_eq!(
+ entered, 1,
+ "direct cohort {cohort} Entered for {p_new} must be exact (==1), got {entered}",
+ );
+ }
+ }
+ assert!(
+ !changes
+ .iter()
+ .any(|c| c.status == MembershipStatus::Left
+ && (c.person_id == p_old.to_string() || c.person_id == q_old.to_string())),
+ "the drain emits no Left for a drained P_old",
+ );
+
+ for p_new in [p_new, q_new] {
+ let b_entered = changes
+ .iter()
+ .filter(|c| {
+ c.cohort_id == COHORT_REF
+ && c.person_id == p_new.to_string()
+ && c.status == MembershipStatus::Entered
+ })
+ .count();
+ assert!(
+ (1..=2).contains(&b_entered),
+ "cascade-origin cohort B (id {COHORT_REF}) Entered for {p_new} must be at-least-once \
+ with at most ONE idempotent replay duplicate ([1,2]); got {b_entered} — a systematic \
+ double is a bug",
+ );
+ }
+
+ shutdown2.request_shutdown();
+ instance2.join().await;
+ })
+ .await;
+}
+
+fn stage2_in_cohort(store: &CohortStore, cohort: i32, person: Uuid) -> bool {
+ use cohort_stream_processor::stage2::Stage2State;
+ use cohort_stream_processor::store::Stage2Key;
+ let key = Stage2Key {
+ partition_id: part(person),
+ team_id: TEAM as u64,
+ cohort_id: cohort as u64,
+ person_id: person,
+ };
+ store
+ .get_stage2(&key)
+ .unwrap()
+ .map(|bytes| Stage2State::decode(&bytes).unwrap().in_cohort)
+ .unwrap_or(false)
+}
diff --git a/rust/cohort-stream-processor/tests/merge_protocol.rs b/rust/cohort-stream-processor/tests/merge_protocol.rs
new file mode 100644
index 000000000000..2656648603a3
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/merge_protocol.rs
@@ -0,0 +1,1986 @@
+//! Cross-partition merge protocol driven end-to-end through the public handler API against a real
+//! RocksDB (no Kafka). Seeds state via `process_event`, then drives drain + transfer + apply
+//! handlers directly, comparing merged state to the same-partition fast path and to an "all events
+//! keyed to P_new from the start" oracle. Replays every handler twice for idempotence and exercises
+//! the reopen-without-wipe recovery via `scan_pending_transfers`.
+
+use chrono_tz::UTC;
+use cohort_stream_processor::consumers::CohortStreamEvent;
+use cohort_stream_processor::filters::{
+ CatalogHandle, CohortId, FilterCatalog, TeamFilters, TeamFiltersBuilder, TeamId,
+};
+use cohort_stream_processor::merge::apply_handler::{
+ handle_transfer, ApplyOutcome, MAX_TRANSFER_FORWARD_HOPS,
+};
+use cohort_stream_processor::merge::drain_handler::{handle_merge_event, DrainOutcome};
+use cohort_stream_processor::merge::tombstone_redirect::{resolve, Resolution};
+use cohort_stream_processor::merge::transfer::{
+ MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, MERGE_EVENT_SCHEMA_VERSION,
+};
+use cohort_stream_processor::partitions::{partition_of, COHORT_PARTITION_COUNT};
+use cohort_stream_processor::producer::{now_last_updated, MembershipStatus};
+use cohort_stream_processor::stage1::{Stage1State, StateVariant, StatefulRecord};
+use cohort_stream_processor::stage2::Stage2State;
+use cohort_stream_processor::store::{
+ CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage1Key,
+ Stage2Key, StoreConfig, TombstoneKey,
+};
+use cohort_stream_processor::sweep::EvictionQueue;
+use cohort_stream_processor::workers::{
+ compose_stage2, handle_merge_gc, handle_stage2_orphan_gc, process_event, MergeGcCursor,
+ Stage2GcCursor,
+};
+use serde_json::{json, Value};
+use tempfile::TempDir;
+use uuid::Uuid;
+
+const TEAM: i32 = 7;
+const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";
+const TS: &str = "2026-05-26 12:34:56.789000";
+const MERGED_AT: i64 = 1_716_800_000_000;
+
+fn temp_store_in(dir: &TempDir) -> CohortStore {
+ CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store")
+}
+
+fn behavioral_bytecode() -> Value {
+ json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
+}
+
+fn single_leaf() -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": 7, "time_interval": "day",
+ "conditionHash": "0123456789abcdef", "bytecode": behavioral_bytecode(),
+ })
+}
+
+/// `performed_event_multiple gte 2` daily leaf (7d) — shares the conditionHash with `single_leaf`.
+fn daily_leaf() -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",
+ "time_value": 7, "time_interval": "day", "operator": "gte", "operator_value": 2,
+ "conditionHash": "0123456789abcdef", "bytecode": behavioral_bytecode(),
+ })
+}
+
+/// `performed_event_multiple gte 2` compressed leaf (365d) — over-180-day window uses compressed storage.
+fn compressed_leaf() -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",
+ "time_value": 365, "time_interval": "day", "operator": "gte", "operator_value": 2,
+ "conditionHash": "0123456789abcdef", "bytecode": behavioral_bytecode(),
+ })
+}
+
+fn person_leaf() -> Value {
+ json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+}
+
+fn cohort(values: Vec<Value>) -> Value {
+ json!({ "properties": { "type": "AND", "values": values } })
+}
+
+/// Cohorts 1–3: one single-leaf each (single/daily/compressed); cohort 4: `AND(daily, person)` so
+/// apply transitions can fan into Stage 2 composition.
+fn build_filters() -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(TEAM), &cohort(vec![single_leaf()]))
+ .unwrap();
+ builder
+ .add_cohort(CohortId(2), TeamId(TEAM), &cohort(vec![daily_leaf()]))
+ .unwrap();
+ builder
+ .add_cohort(CohortId(3), TeamId(TEAM), &cohort(vec![compressed_leaf()]))
+ .unwrap();
+ builder
+ .add_cohort(
+ CohortId(4),
+ TeamId(TEAM),
+ &cohort(vec![daily_leaf(), person_leaf()]),
+ )
+ .unwrap();
+ builder.freeze(UTC)
+}
+
+fn pageview_event(person: Uuid, source_partition: i32, source_offset: i64) -> CohortStreamEvent {
+ CohortStreamEvent {
+ team_id: TEAM,
+ person_id: person.to_string(),
+ distinct_id: "d".to_string(),
+ uuid: Uuid::from_u128(0xE0_0000 + source_offset as u128).to_string(),
+ event: "$pageview".to_string(),
+ timestamp: TS.to_string(),
+ properties: Some("{}".to_string()),
+ person_properties: Some(r#"{"email":"[email protected]"}"#.to_string()),
+ elements_chain: None,
+ source_offset,
+ source_partition,
+ redirected_from: None,
+ redirect_hops: 0,
+ }
+}
+
+fn merge_event(old: Uuid, new: Uuid) -> PersonMergeEvent {
+ PersonMergeEvent {
+ team_id: TEAM,
+ old_person_uuid: old,
+ new_person_uuid: new,
+ merged_at_ms: MERGED_AT,
+ schema_version: MERGE_EVENT_SCHEMA_VERSION,
+ }
+}
+
+fn part(person: Uuid) -> u16 {
+ partition_of(TeamId(TEAM), &person, COHORT_PARTITION_COUNT) as u16
+}
+
+fn person_on(target: u16) -> Uuid {
+ (1u128..)
+ .map(Uuid::from_u128)
+ .find(|p| part(*p) == target)
+ .unwrap()
+}
+
+fn person_not_on(avoid: u16) -> Uuid {
+ (1u128..)
+ .map(Uuid::from_u128)
+ .find(|p| part(*p) != avoid)
+ .unwrap()
+}
+
+/// Three persons on pairwise-distinct partitions so every hop of `A → B → C` is cross-partition.
+fn chain_persons() -> (Uuid, Uuid, Uuid) {
+ let a = Uuid::from_u128(0xA);
+ let a_part = part(a);
+ let b = person_not_on(a_part);
+ let b_part = part(b);
+ let c = (1u128..)
+ .map(Uuid::from_u128)
+ .find(|p| part(*p) != a_part && part(*p) != b_part)
+ .unwrap();
+ (a, b, c)
+}
+
+/// All three behavioral leaves share `BEHAVIORAL_HASH` but differ by `StateVariant`.
+fn lsk_of(filters: &TeamFilters, variant: StateVariant) -> LeafStateKey {
+ filters.by_condition_to_lsk[&BEHAVIORAL_HASH]
+ .iter()
+ .copied()
+ .find(|lsk| filters.by_lsk[lsk].variant == variant)
+ .unwrap_or_else(|| panic!("no LSK for {variant:?}"))
+}
+
+fn leaf_state(
+ store: &CohortStore,
+ partition_id: u16,
+ lsk: LeafStateKey,
+ person: Uuid,
+) -> Option<Stage1State> {
+ let key = Stage1Key {
+ partition_id,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person,
+ };
+ store
+ .get_stage1(&key)
+ .unwrap()
+ .map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)
+}
+
+fn fold_pageview(
+ store: &CohortStore,
+ filters: &TeamFilters,
+ partition_id: u16,
+ person: Uuid,
+ source_partition: i32,
+ source_offset: i64,
+) {
+ process_event(
+ partition_id,
+ store,
+ filters,
+ &pageview_event(person, source_partition, source_offset),
+ )
+ .unwrap();
+}
+
+fn behavioral_states(
+ store: &CohortStore,
+ filters: &TeamFilters,
+ partition_id: u16,
+ person: Uuid,
+) -> (
+ Option<Stage1State>,
+ Option<Stage1State>,
+ Option<Stage1State>,
+) {
+ (
+ leaf_state(
+ store,
+ partition_id,
+ lsk_of(filters, StateVariant::BehavioralSingle),
+ person,
+ ),
+ leaf_state(
+ store,
+ partition_id,
+ lsk_of(filters, StateVariant::BehavioralDailyBuckets),
+ person,
+ ),
+ leaf_state(
+ store,
+ partition_id,
+ lsk_of(filters, StateVariant::BehavioralCompressedHistory),
+ person,
+ ),
+ )
+}
+
+#[test]
+fn cross_partition_drain_transfer_apply_merges_all_variants_and_matches_the_oracle() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+
+ let p_old = Uuid::from_u128(0xA11CE);
+ let p_old_part = part(p_old);
+ let p_new = person_not_on(p_old_part);
+ let p_new_part = part(p_new);
+ assert_ne!(
+ p_old_part, p_new_part,
+ "test requires a cross-partition pair"
+ );
+
+ fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
+ fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
+
+ let mut old_queue = EvictionQueue::<Stage1Key>::new();
+ let drained = handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut old_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ let transfer = match drained {
+ DrainOutcome::Drained { transfer } => transfer,
+ other => panic!("expected a cross-partition Drained, got {other:?}"),
+ };
+
+ let (s, d, c) = behavioral_states(&store, &filters, p_old_part, p_old);
+ assert!(
+ s.is_none() && d.is_none() && c.is_none(),
+ "P_old's state was drained"
+ );
+ assert!(store
+ .get_tombstone(&TombstoneKey {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ person: p_old
+ })
+ .unwrap()
+ .is_some());
+
+ let mut new_queue = EvictionQueue::<Stage1Key>::new();
+ let applied = handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &transfer,
+ (5, 7),
+ &mut new_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(
+ matches!(applied, ApplyOutcome::Applied { .. }),
+ "the transfer applied"
+ );
+
+ // Merged state: daily/compressed sum to 2 (gte 2 → member).
+ let (single, daily, compressed) = behavioral_states(&store, &filters, p_new_part, p_new);
+ assert!(matches!(
+ single,
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ));
+ assert_eq!(
+ daily_sum(&daily.clone().unwrap()),
+ 2,
+ "daily summed across both persons"
+ );
+ assert_eq!(compressed_sum(&compressed.clone().unwrap()), 2);
+
+ // Oracle: a person that received both events from the start, keyed to P_new's partition.
+ let oracle = Uuid::from_u128(0xABCDE);
+ fold_pageview(&store, &filters, p_new_part, oracle, 10, 0);
+ fold_pageview(&store, &filters, p_new_part, oracle, 20, 0);
+ let (o_single, o_daily, o_compressed) = behavioral_states(&store, &filters, p_new_part, oracle);
+ assert_eq!(
+ single, o_single,
+ "single state matches the all-to-P_new oracle"
+ );
+ assert_eq!(daily, o_daily, "daily state matches the oracle");
+ assert_eq!(
+ compressed, o_compressed,
+ "compressed state matches the oracle"
+ );
+
+ let replay_drain = handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut old_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(replay_drain, DrainOutcome::AlreadyDrained);
+ let replay_apply = handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &transfer,
+ (5, 7),
+ &mut new_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(replay_apply, ApplyOutcome::AlreadyApplied);
+ let (_, daily_after, compressed_after) = behavioral_states(&store, &filters, p_new_part, p_new);
+ assert_eq!(
+ daily_sum(&daily_after.unwrap()),
+ 2,
+ "replay did not double-count daily"
+ );
+ assert_eq!(compressed_sum(&compressed_after.unwrap()), 2);
+}
+
+fn daily_sum(state: &Stage1State) -> u32 {
+ match state {
+ Stage1State::BehavioralDailyBuckets { buckets, .. } => buckets.iter().sum(),
+ other => panic!("expected daily, got {other:?}"),
+ }
+}
+
+fn compressed_sum(state: &Stage1State) -> u32 {
+ match state {
+ Stage1State::BehavioralCompressedHistory { entries, .. } => {
+ entries.iter().map(|&(_, c)| c).sum()
+ }
+ other => panic!("expected compressed, got {other:?}"),
+ }
+}
+
+fn seed_and_drain(dir: &TempDir) -> (CohortStore, TeamFilters, u16, Uuid, MergeStateTransfer) {
+ let store = temp_store_in(dir);
+ let filters = build_filters();
+
+ let p_old = Uuid::from_u128(0x0DD);
+ let p_old_part = part(p_old);
+ let p_new = person_not_on(p_old_part);
+ let p_new_part = part(p_new);
+
+ fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
+ fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
+
+ let mut old_queue = EvictionQueue::<Stage1Key>::new();
+ let transfer = match handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut old_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap()
+ {
+ DrainOutcome::Drained { transfer } => transfer,
+ other => panic!("expected Drained, got {other:?}"),
+ };
+ (store, filters, p_new_part, p_new, transfer)
+}
+
+/// Apply dedup keys on the source merge coordinates, not the transfer-topic coordinates.
+#[test]
+fn duplicate_transfer_copy_under_different_transfer_coords_is_already_applied() {
+ let dir = TempDir::new().unwrap();
+ let (store, filters, p_new_part, p_new, transfer) = seed_and_drain(&dir);
+
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ let first = handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &transfer,
+ (5, 7),
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(matches!(first, ApplyOutcome::Applied { .. }));
+
+ let duplicate = handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &transfer,
+ (63, 9_999),
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(
+ duplicate,
+ ApplyOutcome::AlreadyApplied,
+ "the same merge under different transfer coords dedups by source coords"
+ );
+
+ let (single, daily, compressed) = behavioral_states(&store, &filters, p_new_part, p_new);
+ assert!(matches!(
+ single,
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ));
+ assert_eq!(
+ daily_sum(&daily.unwrap()),
+ 2,
+ "daily buckets not double-counted by the duplicate copy"
+ );
+ assert_eq!(
+ compressed_sum(&compressed.unwrap()),
+ 2,
+ "compressed history not double-counted by the duplicate copy"
+ );
+}
+
+/// A re-drain with the same source coordinates but different payload (e.g. rebuilt state) is dropped.
+/// The dedup keys on source coords, not payload content.
+#[test]
+fn redrained_transfer_with_rebuilt_state_is_dropped_by_source_coords_dedup() {
+ let dir = TempDir::new().unwrap();
+ let (store, filters, p_new_part, p_new, transfer) = seed_and_drain(&dir);
+
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ let first = handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &transfer,
+ (5, 7),
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(matches!(first, ApplyOutcome::Applied { .. }));
+
+ let mut redrained = transfer.clone();
+ for leaf in &mut redrained.leaves {
+ if let Stage1State::BehavioralDailyBuckets { buckets, .. } = &mut leaf.record.state {
+ for bucket in buckets.iter_mut() {
+ *bucket += 5;
+ }
+ }
+ }
+ assert_ne!(
+ redrained.leaves, transfer.leaves,
+ "the re-drained payload differs"
+ );
+
+ let outcome = handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &redrained,
+ (12, 345),
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(outcome, ApplyOutcome::AlreadyApplied);
+
+ let (_, daily, compressed) = behavioral_states(&store, &filters, p_new_part, p_new);
+ assert_eq!(
+ daily_sum(&daily.unwrap()),
+ 2,
+ "the rebuilt P_old state is dropped, not folded"
+ );
+ assert_eq!(compressed_sum(&compressed.unwrap()), 2);
+}
+
+#[test]
+fn fast_path_equals_the_cross_partition_result() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+
+ let p_old = Uuid::from_u128(0xFA57);
+ let p_old_part = part(p_old);
+ let p_new = person_on(p_old_part);
+
+ fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
+ fold_pageview(&store, &filters, p_old_part, p_new, 20, 0);
+
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ let outcome = handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(
+ matches!(outcome, DrainOutcome::FastPath { .. }),
+ "same partition → fast path"
+ );
+
+ let (s, d, c) = behavioral_states(&store, &filters, p_old_part, p_old);
+ assert!(s.is_none() && d.is_none() && c.is_none());
+ let (single, daily, compressed) = behavioral_states(&store, &filters, p_old_part, p_new);
+ assert!(matches!(
+ single,
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ));
+ assert_eq!(daily_sum(&daily.unwrap()), 2);
+ assert_eq!(compressed_sum(&compressed.unwrap()), 2);
+}
+
+#[test]
+fn reopen_between_drain_and_apply_recovers_via_scan_pending_transfers() {
+ let dir = TempDir::new().unwrap();
+ let filters = build_filters();
+
+ let p_old = Uuid::from_u128(0xC0FFEE);
+ let p_old_part = part(p_old);
+ let p_new = person_not_on(p_old_part);
+ let p_new_part = part(p_new);
+
+ // Simulate a crash between drain and produce: drain, then drop the store.
+ {
+ let store = temp_store_in(&dir);
+ fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
+ fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ let drained = handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(matches!(drained, DrainOutcome::Drained { .. }));
+ store.flush().unwrap();
+ }
+
+ let store = temp_store_in(&dir);
+ let recovered = store
+ .scan_pending_transfers(p_old_part, None, usize::MAX)
+ .unwrap();
+ assert_eq!(
+ recovered.len(),
+ 1,
+ "the orphaned drain is recovered on reopen"
+ );
+ let pending = PendingTransfer::decode(&recovered[0].1).unwrap();
+ assert_eq!(pending.transfer.old_person_uuid, p_old);
+
+ let mut new_queue = EvictionQueue::<Stage1Key>::new();
+ let applied = handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &pending.transfer,
+ (5, 7),
+ &mut new_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(matches!(applied, ApplyOutcome::Applied { .. }));
+ store
+ .clear_pending_transfer(&PendingTransferKey {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ old_person: p_old,
+ })
+ .unwrap();
+ assert!(
+ store
+ .scan_pending_transfers(p_old_part, None, usize::MAX)
+ .unwrap()
+ .is_empty(),
+ "the outbox is cleared post-apply"
+ );
+
+ let (single, daily, compressed) = behavioral_states(&store, &filters, p_new_part, p_new);
+ assert!(matches!(
+ single,
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ));
+ assert_eq!(
+ daily_sum(&daily.unwrap()),
+ 2,
+ "the recovered transfer applied correctly"
+ );
+ assert_eq!(compressed_sum(&compressed.unwrap()), 2);
+}
+
+#[test]
+fn apply_transitions_compose_into_stage2() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+
+ let p_old = Uuid::from_u128(0xBEE5);
+ let p_old_part = part(p_old);
+ let p_new = person_not_on(p_old_part);
+ let p_new_part = part(p_new);
+
+ // After merge: daily sum = 2 (a flip on gte 2), person leaf already true → AND(daily, person) enters.
+ fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
+ fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
+
+ let mut old_queue = EvictionQueue::<Stage1Key>::new();
+ let transfer = match handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut old_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap()
+ {
+ DrainOutcome::Drained { transfer } => transfer,
+ other => panic!("expected Drained, got {other:?}"),
+ };
+ let mut new_queue = EvictionQueue::<Stage1Key>::new();
+ let transitions = match handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &transfer,
+ (5, 7),
+ &mut new_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap()
+ {
+ ApplyOutcome::Applied { transitions } => transitions,
+ other => panic!("expected Applied, got {other:?}"),
+ };
+
+ let changes = compose_stage2(
+ p_new_part,
+ &store,
+ &filters,
+ &transitions,
+ MERGED_AT,
+ &now_last_updated(),
+ )
+ .unwrap();
+ let composable_enter = changes
+ .iter()
+ .find(|c| c.cohort_id == 4 && c.person_id == p_new.to_string());
+ assert!(
+ composable_enter.is_some_and(|c| c.status == MembershipStatus::Entered),
+ "the merged daily flip composes AND(daily, person) → Entered for P_new",
+ );
+}
+
+/// An empty re-drain (P_old already drained, different source coords) must not overwrite a still-pending
+/// transfer that has not yet been applied.
+#[test]
+fn empty_redrain_does_not_overwrite_a_still_pending_transfer() {
+ let dir = TempDir::new().unwrap();
+ let (store, filters, _p_new_part, p_new, transfer) = seed_and_drain(&dir);
+ let p_old = transfer.old_person_uuid;
+ let p_old_part = part(p_old);
+ let pending_key = PendingTransferKey {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ old_person: p_old,
+ };
+
+ let staged = PendingTransfer::decode(
+ &store
+ .get_pending_transfer(&pending_key)
+ .unwrap()
+ .expect("the drain staged the transfer"),
+ )
+ .unwrap();
+ assert!(!staged.transfer.leaves.is_empty());
+ assert_eq!(
+ (staged.merge_msg_partition, staged.merge_msg_offset),
+ (5, 100),
+ );
+
+ // Different source coords → drain marker misses → re-drain (empty, P_old already gone).
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ let redrain = handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 101),
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ let DrainOutcome::Drained {
+ transfer: redrained,
+ } = redrain
+ else {
+ panic!("expected Drained, got {redrain:?}");
+ };
+ assert!(
+ redrained.leaves.is_empty(),
+ "P_old was already drained, so the re-drain packages nothing",
+ );
+
+ let after = PendingTransfer::decode(
+ &store
+ .get_pending_transfer(&pending_key)
+ .unwrap()
+ .expect("the pending transfer survives the empty re-drain"),
+ )
+ .unwrap();
+ assert_eq!(
+ after, staged,
+ "an empty re-drain must not overwrite the pending transfer",
+ );
+}
+
+/// GC is a no-op while `cutoff < merged_at`; once the cutoff passes, it reclaims the drain marker,
+/// apply marker, and tombstone. A replay after reclaim re-runs (dedup window closed), confirmed by
+/// getting `Drained` with an empty transfer rather than `AlreadyDrained`.
+#[test]
+fn merge_cf_gc_keeps_in_retention_markers_then_reclaims_out_of_retention_storage() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+
+ let p_old = Uuid::from_u128(0x9C1D);
+ let p_old_part = part(p_old);
+ let p_new = person_not_on(p_old_part);
+ let p_new_part = part(p_new);
+ assert_ne!(
+ p_old_part, p_new_part,
+ "test requires a cross-partition pair"
+ );
+
+ fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
+ fold_pageview(&store, &filters, p_new_part, p_new, 20, 0);
+
+ let mut old_queue = EvictionQueue::<Stage1Key>::new();
+ let transfer = match handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut old_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap()
+ {
+ DrainOutcome::Drained { transfer } => transfer,
+ other => panic!("expected Drained, got {other:?}"),
+ };
+ let mut new_queue = EvictionQueue::<Stage1Key>::new();
+ assert!(matches!(
+ handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &transfer,
+ (5, 7),
+ &mut new_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap(),
+ ApplyOutcome::Applied { .. }
+ ));
+
+ let drain_key = MergeDrainKey {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ old_person: p_old,
+ merge_msg_partition: 5,
+ merge_msg_offset: 100,
+ };
+ let applied_key = MergeAppliedKey {
+ partition_id: p_new_part,
+ team_id: TEAM as u64,
+ new_person: p_new,
+ source_partition: 5,
+ source_offset: 100,
+ };
+ let tombstone_key = TombstoneKey {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ person: p_old,
+ };
+ assert!(store.get_merge_drain_applied(&drain_key).unwrap().is_some());
+ assert!(store.get_merge_applied(&applied_key).unwrap().is_some());
+ assert!(store.get_tombstone(&tombstone_key).unwrap().is_some());
+
+ // (a) In-retention: cutoffs before merged_at → GC is a no-op.
+ let mut old_cursor = MergeGcCursor::default();
+ let mut new_cursor = MergeGcCursor::default();
+ let in_retention = MERGED_AT - 1;
+ handle_merge_gc(
+ p_old_part,
+ &store,
+ &mut old_cursor,
+ in_retention,
+ in_retention,
+ 10_000,
+ );
+ handle_merge_gc(
+ p_new_part,
+ &store,
+ &mut new_cursor,
+ in_retention,
+ in_retention,
+ 10_000,
+ );
+
+ assert!(
+ store.get_merge_drain_applied(&drain_key).unwrap().is_some(),
+ "in-retention drain marker survives",
+ );
+ assert!(
+ store.get_merge_applied(&applied_key).unwrap().is_some(),
+ "in-retention apply marker survives",
+ );
+ assert!(
+ store.get_tombstone(&tombstone_key).unwrap().is_some(),
+ "in-retention tombstone survives",
+ );
+
+ // In-retention markers still dedup: same-coords re-drain short-circuits, same-source-coords
+ // transfer at fresh transfer coords is AlreadyApplied.
+ assert_eq!(
+ handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut old_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap(),
+ DrainOutcome::AlreadyDrained,
+ "the in-retention drain marker still dedupes the replayed merge",
+ );
+ assert_eq!(
+ handle_transfer(
+ p_new_part,
+ &store,
+ &filters,
+ &transfer,
+ (63, 9_999),
+ &mut new_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap(),
+ ApplyOutcome::AlreadyApplied,
+ "the in-retention apply marker still dedupes the replayed transfer",
+ );
+
+ // (b) Out-of-retention: cutoffs after merged_at → GC reclaims all three.
+ let out_of_retention = MERGED_AT + 1;
+ handle_merge_gc(
+ p_old_part,
+ &store,
+ &mut old_cursor,
+ out_of_retention,
+ out_of_retention,
+ 10_000,
+ );
+ handle_merge_gc(
+ p_new_part,
+ &store,
+ &mut new_cursor,
+ out_of_retention,
+ out_of_retention,
+ 10_000,
+ );
+
+ assert!(
+ store.get_merge_drain_applied(&drain_key).unwrap().is_none(),
+ "out-of-retention drain marker reclaimed",
+ );
+ assert!(
+ store.get_merge_applied(&applied_key).unwrap().is_none(),
+ "out-of-retention apply marker reclaimed",
+ );
+ assert!(
+ store.get_tombstone(&tombstone_key).unwrap().is_none(),
+ "out-of-retention tombstone reclaimed",
+ );
+
+ let reclaimed_redrain = handle_merge_event(
+ p_old_part,
+ &store,
+ &filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut old_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(
+ matches!(&reclaimed_redrain, DrainOutcome::Drained { transfer } if transfer.leaves.is_empty()),
+ "after GC the marker no longer dedupes; the replay re-drains (empty), got {reclaimed_redrain:?}",
+ );
+}
+
+/// An absent-team drain leaves `cf_stage2` rows behind (no composable_cohort_ids to delete). A later
+/// orphan-GC tick against a non-empty catalog reclaims the orphan while a co-resident live cohort
+/// row on the same partition survives.
+#[test]
+fn stage2_orphans_from_an_absent_team_drain_are_reclaimed_by_a_later_gc_tick() {
+ // TEAM (7) is absent from the GC catalog; LIVE_TEAM stays composable.
+ const LIVE_TEAM: i32 = 8;
+
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+
+ let p_old = Uuid::from_u128(0xABED);
+ let p_old_part = part(p_old);
+ let p_new = person_not_on(p_old_part);
+
+ let orphan = Stage2Key {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ cohort_id: 4,
+ person_id: p_old,
+ };
+ let row = Stage2State {
+ in_cohort: true,
+ last_evaluated_at_ms: MERGED_AT,
+ }
+ .encode();
+ store.write_batch(|b| b.put_stage2(&orphan, &row)).unwrap();
+
+ // Empty filters = absent-team fallback; drain deletes no cf_stage2 rows, so the row orphans.
+ let absent_team_filters = TeamFiltersBuilder::default().freeze(UTC);
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ handle_merge_event(
+ p_old_part,
+ &store,
+ &absent_team_filters,
+ &merge_event(p_old, p_new),
+ (5, 100),
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(
+ store.get_stage2(&orphan).unwrap().is_some(),
+ "the absent-team drain leaves P_old's cf_stage2 row behind (the orphan)",
+ );
+
+ let live = Stage2Key {
+ partition_id: p_old_part,
+ team_id: LIVE_TEAM as u64,
+ cohort_id: 4,
+ person_id: p_old,
+ };
+ store.write_batch(|b| b.put_stage2(&live, &row)).unwrap();
+
+ // Catalog has LIVE_TEAM (composable cohort 4) but not TEAM — so TEAM's row is an orphan.
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(4),
+ TeamId(LIVE_TEAM),
+ &cohort(vec![daily_leaf(), person_leaf()]),
+ )
+ .unwrap();
+ let catalog = CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(LIVE_TEAM),
+ builder.freeze(UTC),
+ )]));
+
+ let mut cursor = Stage2GcCursor::default();
+ handle_stage2_orphan_gc(p_old_part, &store, &catalog, &mut cursor, 10_000);
+
+ assert!(
+ store.get_stage2(&orphan).unwrap().is_none(),
+ "the absent-team orphan is reclaimed by the GC tick",
+ );
+ assert!(
+ store.get_stage2(&live).unwrap().is_some(),
+ "the co-resident live cohort's row survives",
+ );
+}
+
+fn drain_cross(
+ store: &CohortStore,
+ filters: &TeamFilters,
+ old: Uuid,
+ new: Uuid,
+ coords: (i32, i64),
+) -> MergeStateTransfer {
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ match handle_merge_event(
+ part(old),
+ store,
+ filters,
+ &merge_event(old, new),
+ coords,
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap()
+ {
+ DrainOutcome::Drained { transfer } => transfer,
+ other => panic!("expected a cross-partition Drained for {old}->{new}, got {other:?}"),
+ }
+}
+
+/// `B → C` drains before `A → B` transfer applies: when the transfer lands on B's slice, B is already
+/// tombstoned to C, so apply forwards A's state to C (hops=1) instead of stranding it at B.
+/// Applying the forwarded transfer at C leaves C with A + B + C contributions.
+#[test]
+fn raced_chain_forwards_the_grandparent_transfer_through_the_tombstoned_intermediate_to_the_survivor(
+) {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+ let (a, b, c) = chain_persons();
+ let (a_part, b_part, c_part) = (part(a), part(b), part(c));
+
+ fold_pageview(&store, &filters, a_part, a, 10, 0);
+ fold_pageview(&store, &filters, b_part, b, 20, 0);
+ fold_pageview(&store, &filters, c_part, c, 30, 0);
+
+ // 1) B → C drains and applies at C → C = B + C (daily 2); B tombstoned to C.
+ let b_to_c = drain_cross(&store, &filters, b, c, (5, 200));
+ let mut c_queue = EvictionQueue::<Stage1Key>::new();
+ assert!(matches!(
+ handle_transfer(
+ c_part,
+ &store,
+ &filters,
+ &b_to_c,
+ (5, 71),
+ &mut c_queue,
+ COHORT_PARTITION_COUNT
+ )
+ .unwrap(),
+ ApplyOutcome::Applied { .. }
+ ));
+ assert!(store
+ .get_tombstone(&TombstoneKey {
+ partition_id: b_part,
+ team_id: TEAM as u64,
+ person: b,
+ })
+ .unwrap()
+ .is_some());
+
+ // 2) A → B drains; transfer keyed to B.
+ let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
+
+ // 3) Apply on B's partition: B tombstoned to C (cross-partition) → Forward(C, hops=1).
+ let mut b_queue = EvictionQueue::<Stage1Key>::new();
+ let forwarded = match handle_transfer(
+ b_part,
+ &store,
+ &filters,
+ &a_to_b,
+ (5, 80),
+ &mut b_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap()
+ {
+ ApplyOutcome::Forward { transfer } => *transfer,
+ other => panic!("expected Forward, got {other:?}"),
+ };
+ assert_eq!(
+ forwarded.new_person_uuid, c,
+ "forwarded transfer is re-keyed to C"
+ );
+ assert_eq!(forwarded.forward_hops, 1, "one forward hop taken");
+ assert_eq!(
+ forwarded.source_partition, a_to_b.source_partition,
+ "the source coords (the apply-side dedup key) are preserved across the forward",
+ );
+ assert_eq!(forwarded.source_offset, a_to_b.source_offset);
+ assert_eq!(
+ forwarded.old_person_uuid, a,
+ "old_person stays A (the ancestor)"
+ );
+
+ let (b_single, b_daily, b_compressed) = behavioral_states(&store, &filters, b_part, b);
+ assert!(
+ b_single.is_none() && b_daily.is_none() && b_compressed.is_none(),
+ "B stays drained — no resurrected orphan state",
+ );
+
+ // 4) Apply forwarded transfer at C → C = A + B + C.
+ let applied = handle_transfer(
+ c_part,
+ &store,
+ &filters,
+ &forwarded,
+ (5, 81),
+ &mut c_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(matches!(applied, ApplyOutcome::Applied { .. }));
+
+ let (single, daily, compressed) = behavioral_states(&store, &filters, c_part, c);
+ assert!(matches!(
+ single,
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ));
+ assert_eq!(
+ daily_sum(&daily.unwrap()),
+ 3,
+ "C's daily buckets summed A + B + C contributions",
+ );
+ assert_eq!(compressed_sum(&compressed.unwrap()), 3);
+
+ // Apply marker written under C keyed to A → B's source coords so a redelivery dedups.
+ assert!(store
+ .get_merge_applied(&MergeAppliedKey {
+ partition_id: c_part,
+ team_id: TEAM as u64,
+ new_person: c,
+ source_partition: a_to_b.source_partition,
+ source_offset: a_to_b.source_offset,
+ })
+ .unwrap()
+ .is_some());
+}
+
+/// `A → B` applies before `B → C` drains: the marker lives under B, so a redelivery of `A → B`
+/// hits B's marker directly — no forward, no double-count at C.
+#[test]
+fn ordered_chain_redelivery_dedups_on_the_intermediate_marker_without_forwarding() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+ let (a, b, c) = chain_persons();
+ let (a_part, b_part, c_part) = (part(a), part(b), part(c));
+
+ fold_pageview(&store, &filters, a_part, a, 10, 0);
+ fold_pageview(&store, &filters, b_part, b, 20, 0);
+ fold_pageview(&store, &filters, c_part, c, 30, 0);
+
+ // 1) A → B drains and applies at B (not yet tombstoned) → marker under B.
+ let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
+ let mut b_queue = EvictionQueue::<Stage1Key>::new();
+ assert!(matches!(
+ handle_transfer(
+ b_part,
+ &store,
+ &filters,
+ &a_to_b,
+ (5, 80),
+ &mut b_queue,
+ COHORT_PARTITION_COUNT
+ )
+ .unwrap(),
+ ApplyOutcome::Applied { .. }
+ ));
+
+ // 2) B → C drains (B carries A + B) and applies at C → C = A + B + C.
+ let b_to_c = drain_cross(&store, &filters, b, c, (5, 200));
+ let mut c_queue = EvictionQueue::<Stage1Key>::new();
+ assert!(matches!(
+ handle_transfer(
+ c_part,
+ &store,
+ &filters,
+ &b_to_c,
+ (5, 71),
+ &mut c_queue,
+ COHORT_PARTITION_COUNT
+ )
+ .unwrap(),
+ ApplyOutcome::Applied { .. }
+ ));
+ let (_, c_daily, _) = behavioral_states(&store, &filters, c_part, c);
+ assert_eq!(
+ daily_sum(&c_daily.unwrap()),
+ 3,
+ "ordered chain reaches C correctly"
+ );
+
+ // 3) Redeliver A → B at B → the pre-tombstone marker absorbs it: AlreadyApplied, no forward.
+ let redelivered = handle_transfer(
+ b_part,
+ &store,
+ &filters,
+ &a_to_b,
+ (61, 999),
+ &mut b_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(
+ redelivered,
+ ApplyOutcome::AlreadyApplied,
+ "the original-target marker absorbs the ordered-case redelivery",
+ );
+ let (_, c_daily_after, _) = behavioral_states(&store, &filters, c_part, c);
+ assert_eq!(
+ daily_sum(&c_daily_after.unwrap()),
+ 3,
+ "redelivery did not double-count at C",
+ );
+}
+
+/// Redelivery of `A → B` after a raced forward re-resolves B → C; C's marker (written by the first
+/// forwarded apply) absorbs it: AlreadyApplied, no double-count.
+#[test]
+fn forwarded_copy_redelivery_dedups_on_the_survivor_marker() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+ let (a, b, c) = chain_persons();
+ let (a_part, b_part, c_part) = (part(a), part(b), part(c));
+
+ fold_pageview(&store, &filters, a_part, a, 10, 0);
+ fold_pageview(&store, &filters, b_part, b, 20, 0);
+ fold_pageview(&store, &filters, c_part, c, 30, 0);
+
+ let b_to_c = drain_cross(&store, &filters, b, c, (5, 200));
+ let mut c_queue = EvictionQueue::<Stage1Key>::new();
+ handle_transfer(
+ c_part,
+ &store,
+ &filters,
+ &b_to_c,
+ (5, 71),
+ &mut c_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+
+ let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
+ let mut b_queue = EvictionQueue::<Stage1Key>::new();
+ let forwarded = match handle_transfer(
+ b_part,
+ &store,
+ &filters,
+ &a_to_b,
+ (5, 80),
+ &mut b_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap()
+ {
+ ApplyOutcome::Forward { transfer } => *transfer,
+ other => panic!("expected Forward, got {other:?}"),
+ };
+ handle_transfer(
+ c_part,
+ &store,
+ &filters,
+ &forwarded,
+ (5, 81),
+ &mut c_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ let (_, c_daily, _) = behavioral_states(&store, &filters, c_part, c);
+ assert_eq!(daily_sum(&c_daily.unwrap()), 3);
+
+ // Redeliver original A → B at B → re-resolves to C → Forward; apply at C dedupes on C's marker.
+ let reforwarded = match handle_transfer(
+ b_part,
+ &store,
+ &filters,
+ &a_to_b,
+ (62, 1000),
+ &mut b_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap()
+ {
+ ApplyOutcome::Forward { transfer } => *transfer,
+ other => panic!("expected Forward on redelivery, got {other:?}"),
+ };
+ let outcome = handle_transfer(
+ c_part,
+ &store,
+ &filters,
+ &reforwarded,
+ (62, 1001),
+ &mut c_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(
+ outcome,
+ ApplyOutcome::AlreadyApplied,
+ "the survivor marker absorbs the re-forwarded copy",
+ );
+ let (_, c_daily_after, _) = behavioral_states(&store, &filters, c_part, c);
+ assert_eq!(
+ daily_sum(&c_daily_after.unwrap()),
+ 3,
+ "the forwarded-copy redelivery did not double-count at C",
+ );
+}
+
+/// Returns `(partition, B, C, D)` where B/C/D colocate on a partition ≠ `avoid`, so `B → C → D`
+/// resolves inline while `A` (on `avoid`) drains cross-partition into the chain.
+fn colocated_chain_off(avoid: u16) -> (u16, Uuid, Uuid, Uuid) {
+ let mut by_partition: std::collections::HashMap<u16, Vec<Uuid>> =
+ std::collections::HashMap::new();
+ for n in 1u128.. {
+ let person = Uuid::from_u128(n);
+ let p = part(person);
+ if p == avoid {
+ continue;
+ }
+ let bucket = by_partition.entry(p).or_default();
+ bucket.push(person);
+ if bucket.len() == 3 {
+ return (p, bucket[0], bucket[1], bucket[2]);
+ }
+ }
+ unreachable!("the uuid space fills three slots on some partition off the avoided one")
+}
+
+/// The raced-then-extended hazard: `A → B` applies after `B → C` drains (inline resolve to C), so
+/// the apply writes markers under C (resolved target) AND B (original target, the dual-write). Then
+/// `C → D` drains, leaving C's marker stranded. A redelivery of `A → B` re-resolves B → C → D;
+/// the resolved-target probe under D misses, but the fixed-origin probe under B hits and dedups —
+/// without the dual-write, A's leaves would be summed into D twice.
+#[test]
+fn raced_chain_then_extends_dedups_on_the_origin_marker() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+
+ let a = Uuid::from_u128(0xA);
+ let a_part = part(a);
+ let (bcd_part, b, c, d) = colocated_chain_off(a_part);
+ assert_ne!(a_part, bcd_part, "A drains cross-partition into the chain");
+
+ fold_pageview(&store, &filters, a_part, a, 10, 0);
+ fold_pageview(&store, &filters, bcd_part, b, 20, 0);
+ fold_pageview(&store, &filters, bcd_part, c, 30, 0);
+ fold_pageview(&store, &filters, bcd_part, d, 40, 0);
+
+ // 1) B → C: same-partition fast path → B tombstoned to C, C = B + C (daily 2).
+ // Fast path writes no apply marker.
+ let mut bc_queue = EvictionQueue::<Stage1Key>::new();
+ assert!(matches!(
+ handle_merge_event(
+ bcd_part,
+ &store,
+ &filters,
+ &merge_event(b, c),
+ (5, 200),
+ &mut bc_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap(),
+ DrainOutcome::FastPath { .. }
+ ));
+
+ // 2) A → B drains cross-partition; B's tombstone is on the chain's slice (not A's), so the
+ // drain-side assist does not retarget → transfer keyed to B.
+ let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
+ assert_eq!(
+ a_to_b.new_person_uuid, b,
+ "transfer keyed to the raw target B"
+ );
+
+ // 3) Apply on chain's partition: B tombstoned to C (inline) → apply into C = A+B+C (daily 3).
+ // Dual-write: marker written under C (resolved target) and B (original target).
+ let mut chain_queue = EvictionQueue::<Stage1Key>::new();
+ assert!(matches!(
+ handle_transfer(
+ bcd_part,
+ &store,
+ &filters,
+ &a_to_b,
+ (5, 80),
+ &mut chain_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap(),
+ ApplyOutcome::Applied { .. }
+ ));
+ let (_, c_daily, _) = behavioral_states(&store, &filters, bcd_part, c);
+ assert_eq!(daily_sum(&c_daily.unwrap()), 3, "C summed A + B + C");
+
+ let c_marker = MergeAppliedKey {
+ partition_id: bcd_part,
+ team_id: TEAM as u64,
+ new_person: c,
+ source_partition: a_to_b.source_partition,
+ source_offset: a_to_b.source_offset,
+ };
+ let b_marker = MergeAppliedKey {
+ new_person: b,
+ ..c_marker
+ };
+ assert!(
+ store.get_merge_applied(&c_marker).unwrap().is_some(),
+ "resolved-target marker under C",
+ );
+ assert!(
+ store.get_merge_applied(&b_marker).unwrap().is_some(),
+ "fixed-origin marker also under the original target B",
+ );
+
+ // 4) C → D: same-partition fast path → C tombstoned to D, D = A+B+C+D (daily 4).
+ // The fast path writes no apply marker, so C's marker is stranded (no redelivery resolves to C).
+ let mut cd_queue = EvictionQueue::<Stage1Key>::new();
+ assert!(matches!(
+ handle_merge_event(
+ bcd_part,
+ &store,
+ &filters,
+ &merge_event(c, d),
+ (5, 300),
+ &mut cd_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap(),
+ DrainOutcome::FastPath { .. }
+ ));
+ let (_, d_daily, _) = behavioral_states(&store, &filters, bcd_part, d);
+ assert_eq!(
+ daily_sum(&d_daily.unwrap()),
+ 4,
+ "the chain folded A + B + C + D into D",
+ );
+
+ // 5) Redeliver A → B: re-resolves B → C → D; resolved-target probe under D misses (marker at C),
+ // but the original-target probe under B hits → AlreadyApplied.
+ let redelivered = handle_transfer(
+ bcd_part,
+ &store,
+ &filters,
+ &a_to_b,
+ (61, 999),
+ &mut chain_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(
+ redelivered,
+ ApplyOutcome::AlreadyApplied,
+ "the fixed-origin marker under B absorbs the raced-then-extended redelivery",
+ );
+
+ let (d_single, d_daily_after, d_compressed_after) =
+ behavioral_states(&store, &filters, bcd_part, d);
+ assert!(matches!(
+ d_single,
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ));
+ assert_eq!(
+ daily_sum(&d_daily_after.unwrap()),
+ 4,
+ "the redelivery did not double-count D's daily buckets",
+ );
+ assert_eq!(
+ compressed_sum(&d_compressed_after.unwrap()),
+ 4,
+ "the redelivery did not double-count D's compressed history",
+ );
+}
+
+/// Drain-side assist: when B is already tombstoned to a same-partition C, the drain resolves inline
+/// to C rather than staging a transfer keyed to B and forwarding later.
+#[test]
+fn drain_assist_folds_into_a_same_partition_tombstoned_target_directly() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+
+ let a = Uuid::from_u128(0xA);
+ let a_part = part(a);
+ let b = person_not_on(a_part);
+ let b_part = part(b);
+ let c = (1u128..)
+ .map(Uuid::from_u128)
+ .find(|p| part(*p) == b_part && *p != b)
+ .unwrap();
+
+ fold_pageview(&store, &filters, a_part, a, 10, 0);
+ fold_pageview(&store, &filters, b_part, b, 20, 0);
+ fold_pageview(&store, &filters, b_part, c, 30, 0);
+
+ // B → C is a same-partition fast-path merge → B tombstoned to C, C has B + C.
+ let mut bc_queue = EvictionQueue::<Stage1Key>::new();
+ assert!(matches!(
+ handle_merge_event(
+ b_part,
+ &store,
+ &filters,
+ &merge_event(b, c),
+ (5, 200),
+ &mut bc_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap(),
+ DrainOutcome::FastPath { .. }
+ ));
+
+ // A → B: B's tombstone is on B/C's slice (not A's), so the drain does not retarget → transfer
+ // keyed to B. On apply, B and C colocate → inline resolve to C.
+ let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
+ assert_eq!(
+ a_to_b.new_person_uuid, b,
+ "A and B differ in partition, so the assist did not retarget at A's drain (B's tombstone lives on B's slice, not A's)",
+ );
+ let mut c_queue = EvictionQueue::<Stage1Key>::new();
+ assert!(matches!(
+ handle_transfer(
+ b_part,
+ &store,
+ &filters,
+ &a_to_b,
+ (5, 81),
+ &mut c_queue,
+ COHORT_PARTITION_COUNT
+ )
+ .unwrap(),
+ ApplyOutcome::Applied { .. }
+ ));
+
+ let (_, c_daily, _) = behavioral_states(&store, &filters, b_part, c);
+ assert_eq!(daily_sum(&c_daily.unwrap()), 3, "A + B + C folded into C");
+ let (b_single, b_daily, b_compressed) = behavioral_states(&store, &filters, b_part, b);
+ assert!(b_single.is_none() && b_daily.is_none() && b_compressed.is_none());
+}
+
+/// A corrupt cross-partition tombstone cycle (B ↔ C): the apply forwards until `forward_hops` hits
+/// `MAX_TRANSFER_FORWARD_HOPS`, then returns `HopCapped` so the caller can mark and move past it.
+#[test]
+fn transfer_forward_stops_at_the_hop_cap_on_a_corrupt_tombstone_cycle() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+
+ let a = Uuid::from_u128(0xA);
+ let a_part = part(a);
+ let b = person_not_on(a_part);
+ let b_part = part(b);
+ let c = (1u128..)
+ .map(Uuid::from_u128)
+ .find(|p| part(*p) != a_part && part(*p) != b_part)
+ .unwrap();
+
+ fold_pageview(&store, &filters, a_part, a, 10, 0);
+
+ write_tombstone(&store, b_part, b, c);
+ write_tombstone(&store, part(c), c, b);
+
+ let a_to_b = drain_cross(&store, &filters, a, b, (5, 100));
+
+ let mut transfer = a_to_b;
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ let mut hops = 0u8;
+ loop {
+ let on_part = part(transfer.new_person_uuid);
+ match handle_transfer(
+ on_part,
+ &store,
+ &filters,
+ &transfer,
+ (5, 80 + hops as i64),
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap()
+ {
+ ApplyOutcome::Forward { transfer: next } => {
+ hops += 1;
+ transfer = *next;
+ assert_eq!(
+ transfer.forward_hops, hops,
+ "forward_hops increments per hop"
+ );
+ assert!(
+ hops <= MAX_TRANSFER_FORWARD_HOPS,
+ "must not exceed the cap before stopping"
+ );
+ }
+ ApplyOutcome::HopCapped => break,
+ other => panic!("expected Forward/HopCapped on a cycle, got {other:?}"),
+ }
+ }
+ assert_eq!(
+ hops, MAX_TRANSFER_FORWARD_HOPS,
+ "the forward took exactly the cap before dropping",
+ );
+}
+
+fn write_tombstone(store: &CohortStore, on_partition: u16, old: Uuid, new: Uuid) {
+ let key = TombstoneKey {
+ partition_id: on_partition,
+ team_id: TEAM as u64,
+ person: old,
+ };
+ let value = Tombstone {
+ new_person: new,
+ merged_at_ms: MERGED_AT,
+ };
+ store
+ .write_batch(|b| b.put_tombstone(&key, &value.encode()))
+ .unwrap();
+}
+
+/// Checkpoints `store` into a sibling of `dir` (RocksDB hard-links SSTs — checkpoint must be on the
+/// same filesystem and not inside the source dir), then reopens it without wiping.
+fn checkpoint_then_restore(dir: &TempDir, store: CohortStore) -> CohortStore {
+ let checkpoint = dir.path().join("checkpoint");
+ store.create_checkpoint(&checkpoint).unwrap();
+ drop(store);
+ CohortStore::open(&StoreConfig {
+ path: checkpoint,
+ wipe_on_start: false,
+ ..StoreConfig::default()
+ })
+ .expect("open the restored checkpoint")
+}
+
+fn only_pending(store: &CohortStore, partition_id: u16) -> Vec<(PendingTransferKey, Vec<u8>)> {
+ store
+ .scan_pending_transfers(partition_id, None, usize::MAX)
+ .unwrap()
+}
+
+#[test]
+fn checkpoint_restore_then_redrive_and_already_drained_replay_apply_once() {
+ let dir = TempDir::new().unwrap();
+ let (store, filters, p_new_part, p_new, transfer) = seed_and_drain(&dir);
+ let p_old = transfer.old_person_uuid;
+ let p_old_part = part(p_old);
+ let merge_coords = (transfer.source_partition, transfer.source_offset);
+ assert_eq!(
+ merge_coords,
+ (5, 100),
+ "the seed drains at the known coords"
+ );
+
+ // Checkpoint while the pending transfer is still staged; snapshot carries all four merge CFs.
+ let restored = checkpoint_then_restore(&dir, store);
+
+ let recovered = only_pending(&restored, p_old_part);
+ assert_eq!(
+ recovered.len(),
+ 1,
+ "the still-staged pending transfer survived the checkpoint",
+ );
+ let pending = PendingTransfer::decode(&recovered[0].1).unwrap();
+ assert_eq!(pending.transfer.old_person_uuid, p_old);
+ assert_eq!(
+ pending.transfer, transfer,
+ "the staged transfer round-tripped intact"
+ );
+ let drain_key = MergeDrainKey {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ old_person: p_old,
+ merge_msg_partition: merge_coords.0,
+ merge_msg_offset: merge_coords.1,
+ };
+ assert!(
+ restored
+ .get_merge_drain_applied(&drain_key)
+ .unwrap()
+ .is_some(),
+ "the drain marker survived the checkpoint",
+ );
+ let tombstone_key = TombstoneKey {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ person: p_old,
+ };
+ let tombstone_bytes = restored
+ .get_tombstone(&tombstone_key)
+ .unwrap()
+ .expect("the tombstone survived the checkpoint");
+ assert_eq!(
+ Tombstone::decode(&tombstone_bytes).unwrap().new_person,
+ p_new
+ );
+
+ let mut new_queue = EvictionQueue::<Stage1Key>::new();
+ let applied = handle_transfer(
+ p_new_part,
+ &restored,
+ &filters,
+ &pending.transfer,
+ (5, 7),
+ &mut new_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert!(
+ matches!(applied, ApplyOutcome::Applied { .. }),
+ "the recovered transfer applies once against the restored DB",
+ );
+ let (single, daily, compressed) = behavioral_states(&restored, &filters, p_new_part, p_new);
+ assert!(matches!(
+ single,
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ));
+ assert_eq!(
+ daily_sum(&daily.unwrap()),
+ 2,
+ "P_old + P_new daily merged to 2"
+ );
+ assert_eq!(compressed_sum(&compressed.unwrap()), 2);
+
+ let mut old_queue = EvictionQueue::<Stage1Key>::new();
+ let replay_drain = handle_merge_event(
+ p_old_part,
+ &restored,
+ &filters,
+ &merge_event(p_old, p_new),
+ merge_coords,
+ &mut old_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(
+ replay_drain,
+ DrainOutcome::AlreadyDrained,
+ "the restored drain marker short-circuits the replayed merge",
+ );
+ // Re-apply at different transfer offsets: apply dedup keys on source merge coords, not these.
+ let replay_apply = handle_transfer(
+ p_new_part,
+ &restored,
+ &filters,
+ &pending.transfer,
+ (63, 9_999),
+ &mut new_queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(
+ replay_apply,
+ ApplyOutcome::AlreadyApplied,
+ "the restored apply marker dedups the re-applied transfer by source coords",
+ );
+
+ let (single_after, daily_after, compressed_after) =
+ behavioral_states(&restored, &filters, p_new_part, p_new);
+ assert!(matches!(
+ single_after,
+ Some(Stage1State::BehavioralSingle {
+ has_match: true,
+ ..
+ })
+ ));
+ assert_eq!(
+ daily_sum(&daily_after.unwrap()),
+ 2,
+ "the double application was absorbed — daily is not doubled",
+ );
+ assert_eq!(compressed_sum(&compressed_after.unwrap()), 2);
+ let (s, d, c) = behavioral_states(&restored, &filters, p_old_part, p_old);
+ assert!(
+ s.is_none() && d.is_none() && c.is_none(),
+ "P_old's drained state is still absent after the restore",
+ );
+ assert_eq!(
+ Tombstone::decode(
+ &restored
+ .get_tombstone(&tombstone_key)
+ .unwrap()
+ .expect("tombstone still present")
+ )
+ .unwrap()
+ .new_person,
+ p_new,
+ "the tombstone still redirects P_old → P_new",
+ );
+}
+
+/// Event-level rewrite is driven through `tombstone_redirect::resolve` directly — the same resolver
+/// that the worker, drain, and apply paths all call.
+#[test]
+fn checkpoint_restore_preserves_the_tombstone_and_redirects_a_straggler() {
+ let dir = TempDir::new().unwrap();
+ let store = temp_store_in(&dir);
+ let filters = build_filters();
+
+ let p_old = Uuid::from_u128(0x705B);
+ let p_old_part = part(p_old);
+ let p_new = person_not_on(p_old_part);
+ assert_ne!(p_old_part, part(p_new), "cross-partition pair");
+
+ fold_pageview(&store, &filters, p_old_part, p_old, 10, 0);
+ drain_cross(&store, &filters, p_old, p_new, (5, 100));
+ let (s, d, c) = behavioral_states(&store, &filters, p_old_part, p_old);
+ assert!(
+ s.is_none() && d.is_none() && c.is_none(),
+ "P_old's slice is drained in tenure 1",
+ );
+
+ let restored = checkpoint_then_restore(&dir, store);
+
+ let tombstone_key = TombstoneKey {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ person: p_old,
+ };
+ let tombstone = Tombstone::decode(
+ &restored
+ .get_tombstone(&tombstone_key)
+ .unwrap()
+ .expect("the tombstone survived the checkpoint"),
+ )
+ .unwrap();
+ assert_eq!(
+ tombstone.new_person, p_new,
+ "the restored tombstone targets P_new"
+ );
+
+ // CrossPartition: a P_old straggler is re-keyed to P_new's worker, never folded back into the drained P_old.
+ let resolution = resolve(
+ &restored,
+ p_old_part,
+ TeamId(TEAM),
+ p_old,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(
+ resolution,
+ Resolution::CrossPartition {
+ target_person: p_new,
+ origin: p_old,
+ },
+ "post-restore, a P_old straggler redirects to P_new",
+ );
+
+ // Control on the same partition/team: NotMerged proves the tombstone content (not a key miss)
+ // drives the redirect.
+ let control = person_on(p_old_part);
+ assert_ne!(control, p_old);
+ assert_eq!(
+ resolve(
+ &restored,
+ p_old_part,
+ TeamId(TEAM),
+ control,
+ COHORT_PARTITION_COUNT
+ )
+ .unwrap(),
+ Resolution::NotMerged,
+ "a never-tombstoned person is not redirected — the P_new resolution is not vacuous",
+ );
+
+ let (s, d, c) = behavioral_states(&restored, &filters, p_old_part, p_old);
+ assert!(
+ s.is_none() && d.is_none() && c.is_none(),
+ "the restored tombstone redirects, it does not resurrect P_old's state",
+ );
+}
+
+#[test]
+fn checkpoint_restore_preserves_the_drain_marker_so_a_replayed_merge_does_not_re_transfer() {
+ let dir = TempDir::new().unwrap();
+ let (store, filters, _p_new_part, p_new, transfer) = seed_and_drain(&dir);
+ let p_old = transfer.old_person_uuid;
+ let p_old_part = part(p_old);
+ let merge_coords = (transfer.source_partition, transfer.source_offset);
+
+ // Clear the pending transfer so the snapshot isolates the drain marker.
+ store
+ .clear_pending_transfer(&PendingTransferKey {
+ partition_id: p_old_part,
+ team_id: TEAM as u64,
+ old_person: p_old,
+ })
+ .unwrap();
+ assert!(
+ only_pending(&store, p_old_part).is_empty(),
+ "the outbox is empty before the checkpoint",
+ );
+
+ let restored = checkpoint_then_restore(&dir, store);
+ assert!(
+ only_pending(&restored, p_old_part).is_empty(),
+ "the restored outbox starts empty",
+ );
+
+ let mut queue = EvictionQueue::<Stage1Key>::new();
+ let replay = handle_merge_event(
+ p_old_part,
+ &restored,
+ &filters,
+ &merge_event(p_old, p_new),
+ merge_coords,
+ &mut queue,
+ COHORT_PARTITION_COUNT,
+ )
+ .unwrap();
+ assert_eq!(
+ replay,
+ DrainOutcome::AlreadyDrained,
+ "the restored drain marker short-circuits the redelivered merge",
+ );
+
+ // A lost marker would also leave the outbox empty (empty re-drain); AlreadyDrained above proves
+ // the marker survived, not just that the outbox is empty.
+ assert!(
+ only_pending(&restored, p_old_part).is_empty(),
+ "the replayed merge did not stage a duplicate pending transfer",
+ );
+}
diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rs
new file mode 100644
index 000000000000..115c74cbde88
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs
@@ -0,0 +1,2164 @@
+//! The Stage 1 single-condition worker, driven end-to-end against a real RocksDB through the public
+//! API (no Kafka). Synthetic events flow through
+//! [`process_event`](cohort_stream_processor::workers::process_event); one case is driven through a
+//! spawned [`Stage1Worker`](cohort_stream_processor::workers::Stage1Worker) + a test channel to
+//! cover the drain loop and post-commit emission.
+//!
+//! Parse-layer behaviors (globals shape, dropped/cohort-ref leaves, key derivation) are covered by
+//! the in-crate classifier / catalog tests, not duplicated here.
+
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+use chrono_tz::Asia::Kolkata;
+use chrono_tz::{Tz, UTC};
+use cohort_stream_processor::consumers::CohortStreamEvent;
+use cohort_stream_processor::filters::{
+ CatalogHandle, CohortId, FilterCatalog, TeamFilters, TeamFiltersBuilder, TeamId,
+};
+use cohort_stream_processor::partitions::{OffsetTracker, ShuffleMessage};
+use cohort_stream_processor::producer::{CaptureSink, MembershipStatus};
+use cohort_stream_processor::stage1::bucket_tz::{day_idx_in_tz, start_of_day_ms_in_tz};
+use cohort_stream_processor::stage1::{
+ clickhouse_timestamp_to_millis, AppliedOffsets, LeafTransition, Stage1State, StateVariant,
+ StatefulRecord, TransitionKind,
+};
+use cohort_stream_processor::store::{
+ CohortStore, LeafStateKey, PersonIndexKey, Stage1Key, StoreConfig,
+};
+use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, SkipReason, Stage1Worker};
+use serde_json::{json, Value};
+use tempfile::TempDir;
+use tokio::sync::mpsc;
+use uuid::Uuid;
+
+const TEAM: i32 = 7;
+const PARTITION_ID: u16 = 0;
+const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";
+const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
+const BASE_TS: &str = "2026-05-26 12:34:56.789000";
+/// A window over 180 days routes `performed_event_multiple` to the compressed history variant.
+const COMPRESSED_WINDOW_DAYS: i64 = 365;
+
+fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let config = StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ };
+ let store = CohortStore::open(&config).expect("open store");
+ (dir, store)
+}
+
+/// Raise the dispatch ceiling *before* sending: `mark_processed` clamps a processed offset to what
+/// was dispatched, and the worker may mark as soon as it receives the message.
+async fn dispatch_to_worker(
+ tracker: &OffsetTracker,
+ tx: &mpsc::Sender<Vec<ShuffleMessage>>,
+ event: CohortStreamEvent,
+ cse_offset: i64,
+) {
+ tracker.mark_dispatched(PARTITION_ID as i32, cse_offset + 1);
+ tx.send(vec![ShuffleMessage::Event { event, cse_offset }])
+ .await
+ .unwrap();
+}
+
+/// `event == "$pageview"` — the matcher every behavioral leaf with `BEHAVIORAL_HASH` shares.
+fn behavioral_bytecode() -> Value {
+ json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
+}
+
+/// `person.properties.email == "[email protected]"`.
+fn person_email_bytecode() -> Value {
+ json!([
+ "_H",
+ 1,
+ 32,
+ 32,
+ "email",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 1,
+ 3,
+ 11
+ ])
+}
+
+/// A `performed_event` leaf on `$pageview` with a tunable relative window (in days).
+fn behavioral_leaf(window_days: i64) -> Value {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "$pageview",
+ "time_value": window_days,
+ "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": behavioral_bytecode(),
+ })
+}
+
+/// A `performed_event_multiple` leaf on `$pageview`: `<op> <value>` over a `window_days`-day window,
+/// routed to the daily-bucket state. Shares the matcher bytecode/conditionHash with
+/// [`behavioral_leaf`], so both fan out from one HogVM eval but key to distinct leaf state.
+fn behavioral_leaf_multiple(window_days: i64, op: &str, value: i64) -> Value {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event_multiple",
+ "key": "$pageview",
+ "time_value": window_days,
+ "time_interval": "day",
+ "operator": op,
+ "operator_value": value,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": behavioral_bytecode(),
+ })
+}
+
+fn person_leaf() -> Value {
+ person_leaf_with_bytecode(person_email_bytecode())
+}
+
+fn person_leaf_with_bytecode(bytecode: Value) -> Value {
+ json!({
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": bytecode,
+ })
+}
+
+fn cohort(values: Vec<Value>) -> Value {
+ json!({ "properties": { "type": "AND", "values": values } })
+}
+
+fn build_team_filters(cohorts: Vec<(CohortId, Value)>) -> TeamFilters {
+ build_team_filters_tz(cohorts, UTC)
+}
+
+/// Like [`build_team_filters`] but freezes under an explicit team timezone, so the bucket folds run
+/// their `day_idx_in_tz(event_ms, tz)` path against a non-UTC zone.
+fn build_team_filters_tz(cohorts: Vec<(CohortId, Value)>, tz: Tz) -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ for (id, filters) in cohorts {
+ builder
+ .add_cohort(id, TeamId(TEAM), &filters)
+ .expect("add cohort");
+ }
+ builder.freeze(tz)
+}
+
+fn catalog_of(filters: TeamFilters) -> Arc<CatalogHandle> {
+ Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ filters,
+ )])))
+}
+
+fn person(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+}
+
+/// A `$pageview` event for `person` with matching person-properties, at `BASE_TS`.
+fn event(person: Uuid, source_partition: i32, source_offset: i64) -> CohortStreamEvent {
+ CohortStreamEvent {
+ team_id: TEAM,
+ person_id: person.to_string(),
+ distinct_id: "d".to_string(),
+ uuid: "01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
+ event: "$pageview".to_string(),
+ timestamp: BASE_TS.to_string(),
+ properties: Some("{}".to_string()),
+ person_properties: Some(r#"{"email":"[email protected]"}"#.to_string()),
+ elements_chain: None,
+ source_offset,
+ source_partition,
+ redirected_from: None,
+ redirect_hops: 0,
+ }
+}
+
+/// A person event whose `email` and timestamp are tunable, for the argMax / flip cases.
+fn person_event(
+ person: Uuid,
+ email: &str,
+ timestamp: &str,
+ source_partition: i32,
+ source_offset: i64,
+) -> CohortStreamEvent {
+ CohortStreamEvent {
+ person_properties: Some(format!(r#"{{"email":"{email}"}}"#)),
+ timestamp: timestamp.to_string(),
+ ..event(person, source_partition, source_offset)
+ }
+}
+
+/// A matching `$pageview` event for `person` at a specific `timestamp` (drives the day-bucket fold).
+fn event_at(
+ person: Uuid,
+ timestamp: &str,
+ source_partition: i32,
+ source_offset: i64,
+) -> CohortStreamEvent {
+ CohortStreamEvent {
+ timestamp: timestamp.to_string(),
+ ..event(person, source_partition, source_offset)
+ }
+}
+
+fn stage1_key(lsk: LeafStateKey, person: Uuid) -> Stage1Key {
+ Stage1Key {
+ partition_id: PARTITION_ID,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person,
+ }
+}
+
+fn person_index_key(person: Uuid) -> PersonIndexKey {
+ PersonIndexKey {
+ partition_id: PARTITION_ID,
+ team_id: TEAM as u64,
+ person_id: person,
+ }
+}
+
+fn state_at(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<Stage1State> {
+ record_at(store, lsk, person).map(|record| record.state)
+}
+
+/// The full persisted record (state + per-source-partition applied offsets), for the cross-partition
+/// replay-dedup assertions.
+fn record_at(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<StatefulRecord> {
+ store
+ .get_stage1(&stage1_key(lsk, person))
+ .unwrap()
+ .map(|bytes| StatefulRecord::decode(&bytes).unwrap())
+}
+
+/// Assert `offset` is the recorded high-water mark for `partition` — probed via the public
+/// `is_replay` (the inner map is intentionally private): `offset` is a replay, `offset + 1` is new.
+fn assert_high_water(applied: &AppliedOffsets, partition: i32, offset: i64) {
+ assert!(
+ applied.is_replay(partition, offset),
+ "offset {offset} on partition {partition} should be ≤ the high-water mark",
+ );
+ assert!(
+ !applied.is_replay(partition, offset + 1),
+ "offset {} on partition {partition} should be above the high-water mark",
+ offset + 1,
+ );
+}
+
+fn behavioral_deadline(state: &Stage1State) -> i64 {
+ match state {
+ Stage1State::BehavioralSingle {
+ earliest_eviction_at_ms,
+ ..
+ } => *earliest_eviction_at_ms,
+ other => panic!("expected BehavioralSingle, got {other:?}"),
+ }
+}
+
+/// The daily-bucket state's `(buckets, window_start_day, earliest_eviction_at_ms)`.
+fn daily_state(state: &Stage1State) -> (&[u32], i32, i64) {
+ match state {
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ window_start_day,
+ earliest_eviction_at_ms,
+ ..
+ } => (buckets, *window_start_day, *earliest_eviction_at_ms),
+ other => panic!("expected BehavioralDailyBuckets, got {other:?}"),
+ }
+}
+
+fn window_count(state: &Stage1State) -> u32 {
+ daily_state(state).0.iter().sum()
+}
+
+/// The compressed-history state's `(entries, window_start_day, earliest_eviction_at_ms)`.
+fn compressed_state(state: &Stage1State) -> (&[(i32, u32)], i32, i64) {
+ match state {
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ window_start_day,
+ earliest_eviction_at_ms,
+ ..
+ } => (entries, *window_start_day, *earliest_eviction_at_ms),
+ other => panic!("expected BehavioralCompressedHistory, got {other:?}"),
+ }
+}
+
+fn compressed_count(state: &Stage1State) -> u32 {
+ compressed_state(state)
+ .0
+ .iter()
+ .map(|&(_, count)| count)
+ .sum()
+}
+
+/// The `stage1_transitions_total{kind}` label for a transition, resolved through the snapshot — the
+/// same mapping the worker emits.
+fn transition_kind(filters: &TeamFilters, transition: &LeafTransition) -> &'static str {
+ let variant = filters.by_lsk[&transition.leaf_state_key].variant;
+ match (variant, transition.kind) {
+ (StateVariant::BehavioralSingle, TransitionKind::Entered) => "behavioral_entered",
+ (StateVariant::BehavioralSingle, TransitionKind::Left) => "behavioral_left",
+ (StateVariant::BehavioralDailyBuckets, TransitionKind::Entered) => {
+ "behavioral_daily_entered"
+ }
+ (StateVariant::BehavioralDailyBuckets, TransitionKind::Left) => "behavioral_daily_left",
+ (StateVariant::BehavioralCompressedHistory, TransitionKind::Entered) => {
+ "behavioral_compressed_entered"
+ }
+ (StateVariant::BehavioralCompressedHistory, TransitionKind::Left) => {
+ "behavioral_compressed_left"
+ }
+ (StateVariant::PersonProperty, TransitionKind::Entered) => "person_entered",
+ (StateVariant::PersonProperty, TransitionKind::Left) => "person_left",
+ }
+}
+
+#[test]
+fn c1_same_hash_two_windows_get_independent_state_and_deadlines() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![
+ (CohortId(1), cohort(vec![behavioral_leaf(7)])),
+ (CohortId(2), cohort(vec![behavioral_leaf(30)])),
+ ]);
+ let lsks = &filters.by_condition_to_lsk[&BEHAVIORAL_HASH];
+ assert_eq!(lsks.len(), 2, "two distinct LSKs under one conditionHash");
+ assert_eq!(
+ filters.behavioral_conditions.len(),
+ 1,
+ "one unique conditionHash → one HogVM eval that fans out",
+ );
+ for lsk in lsks {
+ assert_eq!(filters.by_lsk[lsk].variant, StateVariant::BehavioralSingle);
+ }
+
+ let alice = person(1);
+
+ // One eval fans out to both LSKs → two Entered, independent state.
+ let first = event(alice, 1, 10);
+ let out = process_event(PARTITION_ID, &store, &filters, &first).unwrap();
+ assert_eq!(out.skipped, None);
+ assert_eq!(out.transitions.len(), 2);
+ assert!(out
+ .transitions
+ .iter()
+ .all(|t| t.kind == TransitionKind::Entered));
+
+ let event_ms = clickhouse_timestamp_to_millis(BASE_TS).unwrap();
+ let event_day = day_idx_in_tz(event_ms, UTC);
+ let mut deadlines: Vec<i64> = lsks
+ .iter()
+ .map(|lsk| behavioral_deadline(&state_at(&store, *lsk, alice).unwrap()))
+ .collect();
+ deadlines.sort_unstable();
+ assert_eq!(deadlines[0], start_of_day_ms_in_tz(event_day + 7 + 1, UTC));
+ assert_eq!(deadlines[1], start_of_day_ms_in_tz(event_day + 30 + 1, UTC));
+ assert_eq!(
+ deadlines[1] - deadlines[0],
+ (30 - 7) * 86_400 * 1000,
+ "the two deadlines differ by exactly (30-7) days",
+ );
+
+ let later_ts = "2026-05-27 12:34:56.789000";
+ let later_ms = clickhouse_timestamp_to_millis(later_ts).unwrap();
+ let later_day = day_idx_in_tz(later_ms, UTC);
+ let second = CohortStreamEvent {
+ timestamp: later_ts.to_string(),
+ source_offset: 11,
+ ..event(alice, 1, 11)
+ };
+ let out = process_event(PARTITION_ID, &store, &filters, &second).unwrap();
+ assert!(
+ out.transitions.is_empty(),
+ "already a member → no transition"
+ );
+ let mut advanced: Vec<i64> = lsks
+ .iter()
+ .map(|lsk| behavioral_deadline(&state_at(&store, *lsk, alice).unwrap()))
+ .collect();
+ advanced.sort_unstable();
+ assert_eq!(advanced[0], start_of_day_ms_in_tz(later_day + 7 + 1, UTC));
+ assert_eq!(advanced[1], start_of_day_ms_in_tz(later_day + 30 + 1, UTC));
+
+ // Replay the first event (lower offset): idempotent, no regression.
+ let out = process_event(PARTITION_ID, &store, &filters, &first).unwrap();
+ assert!(out.transitions.is_empty());
+ let mut after_replay: Vec<i64> = lsks
+ .iter()
+ .map(|lsk| behavioral_deadline(&state_at(&store, *lsk, alice).unwrap()))
+ .collect();
+ after_replay.sort_unstable();
+ assert_eq!(after_replay, advanced, "replay must not regress state");
+}
+
+#[test]
+fn behavioral_deadline_tracks_newest_event_not_the_late_one() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ // Newest-by-event-time arrives first (offset 10), at a later ts than BASE_TS.
+ let later_ts = "2026-05-27 12:34:56.789000";
+ let later_ms = clickhouse_timestamp_to_millis(later_ts).unwrap();
+ let newest_deadline = start_of_day_ms_in_tz(day_idx_in_tz(later_ms, UTC) + 7 + 1, UTC);
+ let newest = CohortStreamEvent {
+ timestamp: later_ts.to_string(),
+ ..event(alice, 1, 10)
+ };
+ let out = process_event(PARTITION_ID, &store, &filters, &newest).unwrap();
+ assert_eq!(out.skipped, None);
+ assert_eq!(out.transitions.len(), 1, "first match enters");
+ assert_eq!(
+ behavioral_deadline(&state_at(&store, lsk, alice).unwrap()),
+ newest_deadline,
+ "deadline seeded off the newest event's calendar day",
+ );
+
+ // A late event (earlier ts, higher offset) is applied — not a replay — but must not regress the deadline.
+ let earlier_ts = "2026-05-25 12:34:56.789000";
+ let late = CohortStreamEvent {
+ timestamp: earlier_ts.to_string(),
+ ..event(alice, 1, 11)
+ };
+ let out = process_event(PARTITION_ID, &store, &filters, &late).unwrap();
+ assert_eq!(out.skipped, None);
+ assert!(
+ out.transitions.is_empty(),
+ "already a member → no transition"
+ );
+ assert_eq!(
+ behavioral_deadline(&state_at(&store, lsk, alice).unwrap()),
+ newest_deadline,
+ "a late lower-ts event must not regress the deadline below the newest event's midnight",
+ );
+}
+
+#[test]
+fn single_eviction_deadline_is_team_local_midnight_for_both_edge_persons() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters_tz(
+ vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))],
+ Kolkata,
+ );
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+
+ let alice = person(1);
+ let bob = person(2);
+ // 00:30 and 23:30 Kolkata local on 2026-05-20, expressed in UTC (−05:30) → one Kolkata day.
+ let alice_ts = "2026-05-19 19:00:00.000000"; // 00:30 next-day Kolkata
+ let bob_ts = "2026-05-20 18:00:00.000000"; // 23:30 same-day Kolkata
+ let alice_ms = clickhouse_timestamp_to_millis(alice_ts).unwrap();
+ let bob_ms = clickhouse_timestamp_to_millis(bob_ts).unwrap();
+ let kolkata_day = day_idx_in_tz(alice_ms, Kolkata);
+ assert_eq!(
+ kolkata_day,
+ day_idx_in_tz(bob_ms, Kolkata),
+ "both events fall on the same Kolkata calendar day",
+ );
+
+ process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, alice_ts, 1, 10),
+ )
+ .unwrap();
+ process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(bob, bob_ts, 1, 11),
+ )
+ .unwrap();
+
+ let expected = start_of_day_ms_in_tz(kolkata_day + 7 + 1, Kolkata);
+ assert_eq!(
+ behavioral_deadline(&state_at(&store, lsk, alice).unwrap()),
+ expected,
+ "alice (00:30 local) evicts at the team-local midnight after day + 7",
+ );
+ assert_eq!(
+ behavioral_deadline(&state_at(&store, lsk, bob).unwrap()),
+ expected,
+ "bob (23:30 local) shares the same eviction midnight as alice",
+ );
+ assert_ne!(
+ expected,
+ start_of_day_ms_in_tz(kolkata_day + 7 + 1, UTC),
+ "the deadline is the team-local (Kolkata) midnight, not the UTC midnight",
+ );
+}
+
+#[test]
+fn ten_thousand_events_then_replay_is_idempotent() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf(7), person_leaf()]),
+ )]);
+
+ const PERSONS: u128 = 100;
+ const PER_PERSON: usize = 100;
+ let persons: Vec<Uuid> = (1..=PERSONS).map(person).collect();
+
+ // Person-major so each person's offsets strictly increase (the replay-guard ordering).
+ let mut events = Vec::with_capacity(persons.len() * PER_PERSON);
+ let mut offset = 0i64;
+ for &p in &persons {
+ for _ in 0..PER_PERSON {
+ events.push(event(p, 1, offset));
+ offset += 1;
+ }
+ }
+
+ // Each person's first event enters both leaves; later events are flip no-ops. One enter each.
+ let (mut behavioral_entered, mut person_entered, mut unexpected) = (0, 0, 0);
+ for ev in &events {
+ let out = process_event(PARTITION_ID, &store, &filters, ev).unwrap();
+ assert_eq!(out.skipped, None);
+ for t in &out.transitions {
+ match transition_kind(&filters, t) {
+ "behavioral_entered" => behavioral_entered += 1,
+ "person_entered" => person_entered += 1,
+ _ => unexpected += 1,
+ }
+ }
+ }
+ assert_eq!(behavioral_entered, persons.len());
+ assert_eq!(person_entered, persons.len());
+ assert_eq!(unexpected, 0);
+
+ for &p in &persons {
+ for lsk in filters.by_lsk.keys() {
+ assert!(
+ store.get_stage1(&stage1_key(*lsk, p)).unwrap().is_some(),
+ "missing state row",
+ );
+ }
+ assert_eq!(
+ store.get_person_index(&person_index_key(p)).unwrap().len(),
+ 2
+ );
+ }
+
+ let before = snapshot_state(&store, &filters, &persons);
+ let mut replay_transitions = 0;
+ for ev in &events {
+ replay_transitions += process_event(PARTITION_ID, &store, &filters, ev)
+ .unwrap()
+ .transitions
+ .len();
+ }
+ assert_eq!(replay_transitions, 0, "replay must produce no transitions");
+ assert_eq!(
+ before,
+ snapshot_state(&store, &filters, &persons),
+ "replay must leave state byte-identical",
+ );
+}
+
+type StateSnapshot = BTreeMap<(u128, [u8; 16]), Vec<u8>>;
+
+fn snapshot_state(store: &CohortStore, filters: &TeamFilters, persons: &[Uuid]) -> StateSnapshot {
+ let mut map = BTreeMap::new();
+ for &p in persons {
+ for lsk in filters.by_lsk.keys() {
+ if let Some(bytes) = store.get_stage1(&stage1_key(*lsk, p)).unwrap() {
+ map.insert((p.as_u128(), lsk.0), bytes);
+ }
+ }
+ }
+ map
+}
+
+#[test]
+fn cross_partition_low_offset_is_not_masked_by_a_high_offset_elsewhere() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let p = person(1);
+
+ // Enter from source partition 10 at a high offset.
+ let enter = person_event(p, "[email protected]", "2026-05-26 12:00:00.000000", 10, 100);
+ let out = process_event(PARTITION_ID, &store, &filters, &enter).unwrap();
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+
+ // Leave from source partition 20 at a low offset, with a newer event time so argMax applies it.
+ let leave = person_event(p, "[email protected]", "2026-05-26 13:00:00.000000", 20, 3);
+ let out = process_event(PARTITION_ID, &store, &filters, &leave).unwrap();
+ assert_eq!(
+ out.transitions.len(),
+ 1,
+ "the low-offset event on a new partition must apply"
+ );
+ assert_eq!(out.transitions[0].kind, TransitionKind::Left);
+
+ let applied = record_at(&store, lsk, p).unwrap().applied_offsets;
+ assert_high_water(&applied, 10, 100);
+ assert_high_water(&applied, 20, 3);
+}
+
+#[test]
+fn cross_partition_replay_does_not_double_apply_or_disturb_other_partitions() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let p = person(1);
+
+ // Event from partition 10 (offset 5), then a later event from partition 20 (offset 10).
+ process_event(PARTITION_ID, &store, &filters, &event(p, 10, 5)).unwrap();
+ let later_b = CohortStreamEvent {
+ timestamp: "2026-05-27 12:34:56.789000".to_string(),
+ ..event(p, 20, 10)
+ };
+ process_event(PARTITION_ID, &store, &filters, &later_b).unwrap();
+
+ let before = record_at(&store, lsk, p).unwrap();
+ assert_high_water(&before.applied_offsets, 10, 5);
+ assert_high_water(&before.applied_offsets, 20, 10);
+
+ // Replay partition 10's original event: is_replay(10, 5) is true (5 ≤ 5) even though the most
+ // recent activity is on partition 20.
+ let out = process_event(PARTITION_ID, &store, &filters, &event(p, 10, 5)).unwrap();
+ assert!(out.transitions.is_empty(), "a replay flips nothing");
+
+ let after = record_at(&store, lsk, p).unwrap();
+ assert_eq!(
+ after, before,
+ "the replay neither double-applied nor disturbed partition 20's high-water mark",
+ );
+}
+
+#[test]
+fn cross_partition_person_replay_leaves_state_and_other_partitions_intact() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let p = person(1);
+
+ let from_a = person_event(p, "[email protected]", "2026-05-26 12:00:00.000000", 10, 5);
+ process_event(PARTITION_ID, &store, &filters, &from_a).unwrap();
+ let later_b = person_event(p, "[email protected]", "2026-05-26 13:00:00.000000", 20, 10);
+ process_event(PARTITION_ID, &store, &filters, &later_b).unwrap();
+
+ let before = record_at(&store, lsk, p).unwrap();
+ assert_high_water(&before.applied_offsets, 10, 5);
+ assert_high_water(&before.applied_offsets, 20, 10);
+
+ let out = process_event(PARTITION_ID, &store, &filters, &from_a).unwrap();
+ assert!(
+ out.transitions.is_empty(),
+ "the person replay flips nothing"
+ );
+
+ assert_eq!(
+ record_at(&store, lsk, p).unwrap(),
+ before,
+ "the person replay left state and partition 20 untouched",
+ );
+}
+
+#[test]
+fn argmax_stale_event_still_advances_applied_offsets_across_partitions() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let p = person(1);
+
+ // Newest write from partition 10 (offset 5).
+ let newest = person_event(p, "[email protected]", "2026-05-26 13:00:00.000000", 10, 5);
+ process_event(PARTITION_ID, &store, &filters, &newest).unwrap();
+
+ // An older event from partition 20 at offset 0: argMax-stale, but a genuine first sighting of
+ // partition 20 that must be recorded.
+ let older_b = person_event(p, "[email protected]", "2026-05-26 12:00:00.000000", 20, 0);
+ let out = process_event(PARTITION_ID, &store, &filters, &older_b).unwrap();
+ assert!(out.transitions.is_empty(), "a stale event flips nothing");
+
+ let record = record_at(&store, lsk, p).unwrap();
+ match record.state {
+ Stage1State::PersonProperty {
+ matches,
+ last_updated_offset,
+ ..
+ } => {
+ assert!(matches, "the stale event kept the newer match");
+ assert_eq!(last_updated_offset, 5, "argMax kept partition 10's offset");
+ }
+ other => panic!("expected PersonProperty, got {other:?}"),
+ }
+ assert_high_water(&record.applied_offsets, 10, 5);
+ assert_high_water(&record.applied_offsets, 20, 0);
+}
+
+#[test]
+fn out_of_order_person_events_keep_the_latest_by_event_time() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);
+ let bob = person(1);
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+
+ let newest_ts = "2026-05-26 12:00:00.000000";
+ let newest = person_event(bob, "[email protected]", newest_ts, 1, 100);
+ let out = process_event(PARTITION_ID, &store, &filters, &newest).unwrap();
+ assert_eq!(out.transitions.len(), 1, "first write enters");
+
+ // An older event arriving later is stale by the argMax tiebreaker: neither flips nor overwrites.
+ let older = person_event(bob, "[email protected]", "2026-05-25 12:00:00.000000", 1, 101);
+ let out = process_event(PARTITION_ID, &store, &filters, &older).unwrap();
+ assert!(out.transitions.is_empty(), "stale event emits nothing");
+
+ let newest_ms = clickhouse_timestamp_to_millis(newest_ts).unwrap();
+ match state_at(&store, lsk, bob).unwrap() {
+ Stage1State::PersonProperty {
+ matches,
+ last_updated_at_ms,
+ last_updated_offset,
+ } => {
+ assert!(matches, "the newest-by-event-time value (a match) is kept");
+ assert_eq!(last_updated_at_ms, newest_ms);
+ assert_eq!(last_updated_offset, 100);
+ }
+ other => panic!("expected PersonProperty, got {other:?}"),
+ }
+}
+
+#[test]
+fn whole_event_skips_carry_distinct_reasons() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf(7), person_leaf()]),
+ )]);
+
+ type SkipCase = (&'static str, fn(&mut CohortStreamEvent), SkipReason);
+ let cases: [SkipCase; 5] = [
+ (
+ "empty person id",
+ |e| e.person_id = String::new(),
+ SkipReason::NullPersonId,
+ ),
+ (
+ "non-uuid person id",
+ |e| e.person_id = "not-a-uuid".to_string(),
+ SkipReason::UnparseablePersonId,
+ ),
+ (
+ "unparseable timestamp",
+ |e| e.timestamp = "nonsense".to_string(),
+ SkipReason::BadTimestamp,
+ ),
+ (
+ "malformed properties",
+ |e| e.properties = Some("{not json".to_string()),
+ SkipReason::GlobalsParseError,
+ ),
+ (
+ "malformed person_properties",
+ |e| e.person_properties = Some("nope".to_string()),
+ SkipReason::GlobalsParseError,
+ ),
+ ];
+
+ for (name, mutate, expected) in cases {
+ let mut ev = event(person(1), 1, 0);
+ mutate(&mut ev);
+ let out = process_event(PARTITION_ID, &store, &filters, &ev).unwrap();
+ assert_eq!(out.skipped, Some(expected), "{name}");
+ assert!(out.transitions.is_empty(), "{name}");
+ }
+
+ let empty = TeamFiltersBuilder::default().freeze(UTC);
+ let out = process_event(PARTITION_ID, &store, &empty, &event(person(1), 1, 0)).unwrap();
+ assert_eq!(out.skipped, Some(SkipReason::NoConditions));
+}
+
+#[test]
+fn behavioral_records_and_emits_only_on_match() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ let non_match = CohortStreamEvent {
+ event: "$autocapture".to_string(),
+ ..event(alice, 1, 0)
+ };
+ let out = process_event(PARTITION_ID, &store, &filters, &non_match).unwrap();
+ assert_eq!(out.skipped, None);
+ assert!(out.transitions.is_empty());
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "no write on non-match"
+ );
+
+ let out = process_event(PARTITION_ID, &store, &filters, &event(alice, 1, 1)).unwrap();
+ assert_eq!(out.transitions.len(), 1);
+ assert!(state_at(&store, lsk, alice).is_some());
+}
+
+#[test]
+fn person_records_every_event_with_no_false_to_false_transition() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);
+ let carol = person(1);
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+
+ let miss = person_event(carol, "[email protected]", "2026-05-26 12:00:00.000000", 1, 10);
+ let out = process_event(PARTITION_ID, &store, &filters, &miss).unwrap();
+ assert!(out.transitions.is_empty(), "no false→false transition");
+ match state_at(&store, lsk, carol).expect("row written even on non-match") {
+ Stage1State::PersonProperty { matches, .. } => assert!(!matches),
+ other => panic!("expected PersonProperty, got {other:?}"),
+ }
+
+ let hit = person_event(carol, "[email protected]", "2026-05-26 13:00:00.000000", 1, 11);
+ let out = process_event(PARTITION_ID, &store, &filters, &hit).unwrap();
+ assert_eq!(out.transitions.len(), 1);
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+}
+
+#[test]
+fn person_property_flip_to_non_match_emits_left() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);
+ let dave = person(1);
+
+ let enter = person_event(dave, "[email protected]", "2026-05-26 12:00:00.000000", 1, 10);
+ let out = process_event(PARTITION_ID, &store, &filters, &enter).unwrap();
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+
+ let leave = person_event(dave, "[email protected]", "2026-05-26 13:00:00.000000", 1, 11);
+ let out = process_event(PARTITION_ID, &store, &filters, &leave).unwrap();
+ assert_eq!(out.transitions.len(), 1);
+ assert_eq!(out.transitions[0].kind, TransitionKind::Left);
+ assert_eq!(
+ transition_kind(&filters, &out.transitions[0]),
+ "person_left"
+ );
+}
+
+#[test]
+fn person_path_is_inactive_for_null_or_empty_person_properties() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);
+ let erin = person(1);
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+
+ // Null and empty-string are both JS-falsy → person path never runs → processed no-op, no row.
+ for (offset, payload) in [(10, None), (11, Some(String::new()))] {
+ let ev = CohortStreamEvent {
+ person_properties: payload,
+ ..event(erin, 1, offset)
+ };
+ let out = process_event(PARTITION_ID, &store, &filters, &ev).unwrap();
+ assert_eq!(out.skipped, None, "processed as a no-op, not skipped whole");
+ assert!(out.transitions.is_empty());
+ assert!(
+ state_at(&store, lsk, erin).is_none(),
+ "no person row written"
+ );
+ }
+}
+
+#[test]
+fn empty_person_properties_does_not_skip_a_behavioral_match() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf(7), person_leaf()]),
+ )]);
+ let behavioral_lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let person_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = person(1);
+
+ // Empty-string person_properties is JS-falsy: Node skips the person path but still runs the
+ // behavioral one, so it must not skip the whole event and drop the behavioral match.
+ let ev = CohortStreamEvent {
+ person_properties: Some(String::new()),
+ ..event(alice, 1, 0)
+ };
+ let out = process_event(PARTITION_ID, &store, &filters, &ev).unwrap();
+
+ assert_eq!(
+ out.skipped, None,
+ "empty person_properties is not a whole-event skip"
+ );
+ assert_eq!(out.transitions.len(), 1);
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ assert_eq!(
+ transition_kind(&filters, &out.transitions[0]),
+ "behavioral_entered"
+ );
+ assert!(
+ state_at(&store, behavioral_lsk, alice).is_some(),
+ "behavioral row written"
+ );
+ assert!(
+ state_at(&store, person_lsk, alice).is_none(),
+ "empty person_properties → person path inactive, no row",
+ );
+}
+
+#[test]
+fn non_boolean_person_result_coerces_to_false() {
+ let (_dir, store) = temp_store();
+ let nonbool = person_leaf_with_bytecode(json!(["_H", 1, 33, 42]));
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![nonbool]))]);
+ let frank = person(1);
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+
+ let out = process_event(PARTITION_ID, &store, &filters, &event(frank, 1, 0)).unwrap();
+ assert!(out.transitions.is_empty(), "false → no enter");
+ match state_at(&store, lsk, frank).expect("row written") {
+ Stage1State::PersonProperty { matches, .. } => {
+ assert!(!matches, "non-bool result coerced to false")
+ }
+ other => panic!("expected PersonProperty, got {other:?}"),
+ }
+}
+
+#[tokio::test]
+async fn spawned_worker_drains_a_batch_and_commits_state() {
+ let (_dir, store) = temp_store();
+ // Composable cohort: this one event matches and flips both leaves, so Stage 2 composes a single
+ // `entered` for the cohort.
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf(7), person_leaf()]),
+ )]);
+ let behavioral_lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let person_lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let alice = person(1);
+
+ let catalog = catalog_of(filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ catalog,
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ dispatch_to_worker(&tracker, &tx, event(alice, 1, 0), 0).await;
+ // Closing the channel makes the worker drain the queued batch and exit.
+ drop(tx);
+ worker.join().await.unwrap();
+
+ assert!(state_at(&store, behavioral_lsk, alice).is_some());
+ assert!(state_at(&store, person_lsk, alice).is_some());
+ assert_eq!(
+ store
+ .get_person_index(&person_index_key(alice))
+ .unwrap()
+ .len(),
+ 2
+ );
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 1,
+ "both leaves flipping in one event composes a single entered",
+ );
+ assert_eq!(changes[0].cohort_id, 1);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[0].person_id, alice.to_string());
+ assert_eq!(
+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),
+ Some(&1)
+ );
+}
+
+#[tokio::test]
+async fn spawned_worker_composes_two_leaf_cohort_and_emits_single_leaf_independently() {
+ let (_dir, store) = temp_store();
+ // Cohort 1 ANDs a behavioral and a person leaf (composable); cohort 2 is the bare behavioral leaf
+ // (single-leaf), sharing cohort 1's behavioral leaf.
+ let filters = build_team_filters(vec![
+ (CohortId(1), cohort(vec![behavioral_leaf(7), person_leaf()])),
+ (CohortId(2), cohort(vec![behavioral_leaf(7)])),
+ ]);
+ let alice = person(1);
+
+ let catalog = catalog_of(filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ catalog,
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ // Event A flips only the behavioral leaf (non-matching email): the single-leaf cohort 2 enters,
+ // while the composable cohort 1 stays out — its person leaf is still false.
+ dispatch_to_worker(
+ &tracker,
+ &tx,
+ person_event(
+ alice,
+ "2026-05-26 12:00:00.000000",
+ 1,
+ 0,
+ ),
+ 0,
+ )
+ .await;
+ // Event B flips the person leaf: cohort 1's AND is now satisfied, so it enters; cohort 2 is
+ // untouched (its leaf did not transition this event).
+ dispatch_to_worker(
+ &tracker,
+ &tx,
+ person_event(alice, "[email protected]", "2026-05-26 12:00:01.000000", 1, 1),
+ 1,
+ )
+ .await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let mut emitted: Vec<(i32, MembershipStatus)> = sink
+ .changes()
+ .iter()
+ .map(|change| (change.cohort_id, change.status))
+ .collect();
+ emitted.sort_by_key(|(cohort, _)| *cohort);
+ assert_eq!(
+ emitted,
+ vec![
+ (1, MembershipStatus::Entered),
+ (2, MembershipStatus::Entered),
+ ],
+ "single-leaf cohort 2 enters on its leaf's flip; composable cohort 1 enters only once both \
+ of its leaves are true, and exactly once",
+ );
+}
+
+#[tokio::test]
+async fn spawned_worker_skips_events_for_unknown_teams() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral_leaf(7)]))]);
+ let behavioral_lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ let catalog = catalog_of(filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ catalog,
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ // Skipped before touching the store, but the offset must still advance (no partition wedge).
+ let unknown = CohortStreamEvent {
+ team_id: 999,
+ ..event(alice, 1, 0)
+ };
+ dispatch_to_worker(&tracker, &tx, unknown, 3).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let key = Stage1Key {
+ partition_id: PARTITION_ID,
+ team_id: 999,
+ leaf_state_key: behavioral_lsk,
+ person_id: alice,
+ };
+ assert!(
+ store.get_stage1(&key).unwrap().is_none(),
+ "no write for unknown team"
+ );
+ assert!(sink.changes().is_empty());
+ assert_eq!(
+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),
+ Some(&4)
+ );
+}
+
+fn single_leaf_catalog() -> Arc<CatalogHandle> {
+ catalog_of(build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf(7)]),
+ )]))
+}
+
+#[tokio::test]
+async fn worker_produces_changes_and_advances_offset() {
+ let (_dir, store) = temp_store();
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ single_leaf_catalog(),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ dispatch_to_worker(&tracker, &tx, event(person(1), 1, 0), 5).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ assert_eq!(
+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),
+ Some(&6)
+ );
+ let changes = sink.changes();
+ assert_eq!(changes.len(), 1);
+ assert_eq!(changes[0].cohort_id, 1);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[0].person_id, person(1).to_string());
+}
+
+#[tokio::test]
+async fn worker_advances_offset_on_empty_transition_subbatch() {
+ // A no-op (or poison) event must not wedge the partition: the offset still advances.
+ let (_dir, store) = temp_store();
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ single_leaf_catalog(),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ let non_match = CohortStreamEvent {
+ event: "$autocapture".to_string(),
+ ..event(person(1), 1, 0)
+ };
+ dispatch_to_worker(&tracker, &tx, non_match, 42).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ assert_eq!(
+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),
+ Some(&43),
+ "an empty sub-batch still advances the offset",
+ );
+ assert!(sink.changes().is_empty());
+}
+
+#[tokio::test]
+async fn worker_holds_offset_when_the_only_flush_fails() {
+ let (_dir, store) = temp_store();
+ let sink = CaptureSink::failing_first(1);
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ single_leaf_catalog(),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ dispatch_to_worker(&tracker, &tx, event(person(1), 1, 0), 10).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ assert_eq!(
+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),
+ None,
+ "a failed produce holds the offset back for replay",
+ );
+ assert!(sink.changes().is_empty(), "a failed flush emits nothing");
+}
+
+#[tokio::test]
+async fn worker_keeps_processing_after_a_produce_failure() {
+ let (_dir, store) = temp_store();
+ let sink = CaptureSink::failing_first(1);
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ single_leaf_catalog(),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ dispatch_to_worker(&tracker, &tx, event(person(1), 1, 0), 10).await;
+ dispatch_to_worker(&tracker, &tx, event(person(2), 1, 1), 11).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ // The second flush's success advances the offset to 12; the held first event relies on replay.
+ assert_eq!(
+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),
+ Some(&12)
+ );
+ let changes = sink.changes();
+ assert_eq!(changes.len(), 1, "only the second flush's change landed");
+ assert_eq!(changes[0].person_id, person(2).to_string());
+}
+
+#[test]
+fn daily_multiple_enters_when_count_crosses_threshold() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(7, "gte", 3)]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ assert_eq!(
+ filters.by_lsk[&lsk].variant,
+ StateVariant::BehavioralDailyBuckets,
+ );
+ let alice = person(1);
+
+ // Three matching events on consecutive days, all inside the 7-day window.
+ let days = [
+ "2026-05-20 10:00:00.000000",
+ "2026-05-21 11:00:00.000000",
+ "2026-05-22 09:30:00.000000",
+ ];
+ for (offset, ts) in days[..2].iter().enumerate() {
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, ts, 1, offset as i64),
+ )
+ .unwrap();
+ assert!(out.transitions.is_empty(), "count below 3 → no transition");
+ }
+ assert_eq!(window_count(&state_at(&store, lsk, alice).unwrap()), 2);
+
+ // The third event crosses `gte 3`.
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, days[2], 1, 2),
+ )
+ .unwrap();
+ assert_eq!(out.transitions.len(), 1);
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ assert_eq!(
+ transition_kind(&filters, &out.transitions[0]),
+ "behavioral_daily_entered",
+ );
+ assert_eq!(window_count(&state_at(&store, lsk, alice).unwrap()), 3);
+}
+
+#[test]
+fn daily_multiple_slide_drops_contributing_bucket_and_emits_left() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(7, "gte", 3)]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ // Three matches on the same day → one bucket of count 3 → Entered on the third.
+ let day = "2026-05-20 10:00:00.000000";
+ for offset in 0..3 {
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, day, 1, offset),
+ )
+ .unwrap();
+ if offset < 2 {
+ assert!(out.transitions.is_empty());
+ } else {
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ }
+ }
+ assert_eq!(
+ window_count(&state_at(&store, lsk, alice).unwrap()),
+ 3,
+ "all three accumulate in one day-bucket",
+ );
+
+ // A match 8 days later slides the whole window past that bucket: it falls out, and the slide event
+ // itself only contributes 1 → count 1 < 3 → Left.
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, "2026-05-28 10:00:00.000000", 1, 3),
+ )
+ .unwrap();
+ assert_eq!(out.transitions.len(), 1);
+ assert_eq!(out.transitions[0].kind, TransitionKind::Left);
+ assert_eq!(
+ transition_kind(&filters, &out.transitions[0]),
+ "behavioral_daily_left",
+ );
+ assert_eq!(
+ window_count(&state_at(&store, lsk, alice).unwrap()),
+ 1,
+ "only the slide event remains in the window",
+ );
+}
+
+#[test]
+fn daily_multiple_counts_same_day_repeats_in_one_bucket() {
+ // Proves the daily state is a counter, not a bit: two same-day matches show count 2 in one bucket.
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(7, "gte", 5)]), // high threshold: inspect state, no flip
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ let day = "2026-05-20 10:00:00.000000";
+ process_event(PARTITION_ID, &store, &filters, &event_at(alice, day, 1, 0)).unwrap();
+ let out = process_event(PARTITION_ID, &store, &filters, &event_at(alice, day, 1, 1)).unwrap();
+ assert!(out.transitions.is_empty(), "count 2 is still under gte 5");
+
+ let state = state_at(&store, lsk, alice).unwrap();
+ let (buckets, _, _) = daily_state(&state);
+ assert_eq!(
+ buckets.iter().filter(|&&count| count > 0).count(),
+ 1,
+ "both matches land in a single day-bucket",
+ );
+ assert_eq!(
+ buckets.iter().copied().max().unwrap(),
+ 2,
+ "that bucket counts 2 — a bit would read 1",
+ );
+ assert_eq!(window_count(&state), 2);
+}
+
+#[test]
+fn daily_multiple_cross_partition_replay_after_slide_is_byte_identical() {
+ // Skip vs re-fold are NOT state-identical here, so byte-identity proves `is_replay` fired.
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(7, "gte", 1)]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let p = person(1);
+
+ // Event from partition 10 (offset 5) on 05-20, then a later event from partition 20 (offset 10) on
+ // 05-23 that slides the window forward.
+ process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(p, "2026-05-20 10:00:00.000000", 10, 5),
+ )
+ .unwrap();
+ process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(p, "2026-05-23 10:00:00.000000", 20, 10),
+ )
+ .unwrap();
+
+ let before = record_at(&store, lsk, p).unwrap();
+ assert_high_water(&before.applied_offsets, 10, 5);
+ assert_high_water(&before.applied_offsets, 20, 10);
+
+ // Replay partition 10's original event (offset 5 ≤ 5): is_replay fires regardless of the slide.
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(p, "2026-05-20 10:00:00.000000", 10, 5),
+ )
+ .unwrap();
+ assert!(out.transitions.is_empty(), "a replay flips nothing");
+
+ let after = record_at(&store, lsk, p).unwrap();
+ assert_eq!(
+ after, before,
+ "the replay neither re-folded its bucket nor disturbed partition 20's high-water mark",
+ );
+}
+
+#[test]
+fn daily_multiple_late_behind_event_records_offset_without_counting() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(2, "gte", 1)]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ // Newest event first (offset 10) on 05-27 → window covers [05-25 ..= 05-27].
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, "2026-05-27 12:00:00.000000", 1, 10),
+ )
+ .unwrap();
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ let before = record_at(&store, lsk, alice).unwrap();
+
+ // A late event before the window's lower bound (05-22 < 05-25): behind the window, so it does not
+ // count — but it is a genuine new offset and must be recorded.
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, "2026-05-22 12:00:00.000000", 1, 11),
+ )
+ .unwrap();
+ assert!(
+ out.transitions.is_empty(),
+ "a behind-window event flips nothing"
+ );
+
+ let after = record_at(&store, lsk, alice).unwrap();
+ assert_eq!(
+ after.state, before.state,
+ "the behind-window event left the buckets, window, deadline, and newest-event all unchanged",
+ );
+ assert_high_water(&after.applied_offsets, 1, 11);
+}
+
+#[test]
+fn daily_multiple_eq_or_lte_zero_is_never_a_member() {
+ for op in ["eq", "lte"] {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(7, op, 0)]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, "2026-05-20 10:00:00.000000", 1, 0),
+ )
+ .unwrap();
+ assert!(
+ out.transitions.is_empty(),
+ "{op} 0 over count 1 is not a member → no transition",
+ );
+ assert_eq!(
+ window_count(&state_at(&store, lsk, alice).unwrap()),
+ 1,
+ "{op}: the match is still counted in state",
+ );
+ }
+}
+
+#[test]
+fn daily_multiple_stores_eviction_deadline_at_oldest_bucket_day_boundary() {
+ let (_dir, store) = temp_store();
+ let window_days = 7;
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(window_days, "gte", 1)]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ let ts = "2026-05-20 10:00:00.000000";
+ process_event(PARTITION_ID, &store, &filters, &event_at(alice, ts, 1, 0)).unwrap();
+
+ let state = state_at(&store, lsk, alice).unwrap();
+ let (_, window_start_day, deadline) = daily_state(&state);
+ let event_day = day_idx_in_tz(clickhouse_timestamp_to_millis(ts).unwrap(), UTC);
+ assert_eq!(
+ window_start_day,
+ event_day - window_days as i32,
+ "the lone event sits in the window's last bucket (the now-day)",
+ );
+ assert_eq!(
+ deadline,
+ start_of_day_ms_in_tz(event_day + window_days as i32 + 1, UTC),
+ "oldest non-zero bucket leaves at start of day event_day + window_days + 1",
+ );
+}
+
+#[test]
+fn daily_multiple_buckets_by_team_timezone_day_not_utc_day() {
+ let (_dir, store) = temp_store();
+ let window_days = 7;
+ let filters = build_team_filters_tz(
+ vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(window_days, "gte", 1)]),
+ )],
+ Kolkata,
+ );
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ let ts = "2026-05-26 20:00:00.000000"; // 20:00 UTC = 01:30 next-day Kolkata
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+ let kolkata_day = day_idx_in_tz(event_ms, Kolkata);
+ let utc_day = day_idx_in_tz(event_ms, UTC);
+ assert_eq!(
+ kolkata_day,
+ utc_day + 1,
+ "the chosen instant lands on different UTC and Kolkata calendar days",
+ );
+
+ let out = process_event(PARTITION_ID, &store, &filters, &event_at(alice, ts, 1, 0)).unwrap();
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+
+ let state = state_at(&store, lsk, alice).unwrap();
+ let (_, window_start_day, deadline) = daily_state(&state);
+ assert_eq!(
+ window_start_day,
+ kolkata_day - window_days as i32,
+ "the fresh window anchors on the team-tz (Kolkata) now-day",
+ );
+ assert_ne!(
+ window_start_day,
+ utc_day - window_days as i32,
+ "a UTC-hardcoded fold would anchor one day earlier — this is the discriminating assertion",
+ );
+ // The deadline is the Kolkata local-midnight the lone bucket leaves the window, and that instant
+ // differs from the UTC anchoring (Kolkata midnight is 18:30 UTC the prior day).
+ assert_eq!(
+ deadline,
+ start_of_day_ms_in_tz(kolkata_day + window_days as i32 + 1, Kolkata),
+ "eviction anchors on Kolkata local midnight",
+ );
+ assert_ne!(
+ deadline,
+ start_of_day_ms_in_tz(utc_day + window_days as i32 + 1, UTC),
+ "a UTC-hardcoded fold would compute a different deadline",
+ );
+}
+
+#[test]
+fn daily_multiple_event_on_window_start_day_counts_in_bucket_zero() {
+ // An event landing exactly on `window_start_day` is within, not behind, and counts in bucket 0.
+ let (_dir, store) = temp_store();
+ let window_days = 2;
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(window_days, "gte", 1)]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ // Newest event first (offset 10) on 05-27 → window covers [05-25 ..= 05-27], so window_start_day is
+ // 05-25 and this event lands in the last bucket (the now-day), leaving bucket 0 empty.
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, "2026-05-27 12:00:00.000000", 1, 10),
+ )
+ .unwrap();
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ let before = state_at(&store, lsk, alice).unwrap();
+ let (buckets_before, window_start_day, _) = daily_state(&before);
+ assert_eq!(
+ window_start_day,
+ day_of("2026-05-25 00:00:00.000000"),
+ "window_start_day is the inclusive lower bound, day 05-25",
+ );
+ assert_eq!(buckets_before[0], 0, "the boundary bucket starts empty");
+ assert_eq!(window_count(&before), 1);
+
+ // An event landing exactly on window_start_day (05-25): event_day == window_start_day, so it is
+ // WITHIN (not the strict `event_day < window_start_day` BEHIND drop) and counts in bucket 0.
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, "2026-05-25 23:00:00.000000", 1, 11),
+ )
+ .unwrap();
+ assert!(
+ out.transitions.is_empty(),
+ "already a member (count 1 → 2) → no transition",
+ );
+
+ let after = state_at(&store, lsk, alice).unwrap();
+ let (buckets_after, window_start_after, _) = daily_state(&after);
+ assert_eq!(
+ window_start_after, window_start_day,
+ "an in-window event does not slide the window",
+ );
+ assert_eq!(
+ buckets_after[0], 1,
+ "the boundary-day event counts in bucket 0 (inclusive lower bound)",
+ );
+ assert_eq!(
+ window_count(&after),
+ 2,
+ "the boundary event is counted, not dropped as behind",
+ );
+}
+
+#[tokio::test]
+async fn daily_multiple_single_leaf_cohort_emits_entered_then_left_to_the_sink() {
+ let (_dir, store) = temp_store();
+ let catalog = catalog_of(build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(7, "gte", 3)]),
+ )]));
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ catalog,
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ let alice = person(1);
+ let day = "2026-05-20 10:00:00.000000";
+ // Three same-day matches enter on the third; a far event slides them out → Left.
+ dispatch_to_worker(&tracker, &tx, event_at(alice, day, 1, 0), 0).await;
+ dispatch_to_worker(&tracker, &tx, event_at(alice, day, 1, 1), 1).await;
+ dispatch_to_worker(&tracker, &tx, event_at(alice, day, 1, 2), 2).await;
+ dispatch_to_worker(
+ &tracker,
+ &tx,
+ event_at(alice, "2026-05-28 10:00:00.000000", 1, 3),
+ 3,
+ )
+ .await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 2,
+ "one Entered (3rd event) + one Left (slide)"
+ );
+ assert_eq!(changes[0].cohort_id, 1);
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[0].person_id, alice.to_string());
+ assert_eq!(changes[1].status, MembershipStatus::Left);
+ assert_eq!(
+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),
+ Some(&4),
+ );
+}
+
+fn day_of(ts: &str) -> i32 {
+ day_idx_in_tz(clickhouse_timestamp_to_millis(ts).unwrap(), UTC)
+}
+
+#[test]
+fn compressed_multiple_enters_when_count_crosses_threshold() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(
+ COMPRESSED_WINDOW_DAYS,
+ "gte",
+ 3,
+ )]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ assert_eq!(
+ filters.by_lsk[&lsk].variant,
+ StateVariant::BehavioralCompressedHistory,
+ "a 365-day window routes to compressed history",
+ );
+ let alice = person(1);
+
+ // Three matching events on three different days, all inside the 365-day window.
+ let days = [
+ "2026-01-10 10:00:00.000000",
+ "2026-03-15 11:00:00.000000",
+ "2026-05-20 09:30:00.000000",
+ ];
+ for (offset, ts) in days[..2].iter().enumerate() {
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, ts, 1, offset as i64),
+ )
+ .unwrap();
+ assert!(out.transitions.is_empty(), "count below 3 → no transition");
+ }
+ assert_eq!(compressed_count(&state_at(&store, lsk, alice).unwrap()), 2);
+
+ // The third event crosses `gte 3`.
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, days[2], 1, 2),
+ )
+ .unwrap();
+ assert_eq!(out.transitions.len(), 1);
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ assert_eq!(
+ transition_kind(&filters, &out.transitions[0]),
+ "behavioral_compressed_entered",
+ );
+ assert_eq!(compressed_count(&state_at(&store, lsk, alice).unwrap()), 3);
+}
+
+#[test]
+fn compressed_multiple_slide_drops_contributing_day_and_emits_left() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(
+ COMPRESSED_WINDOW_DAYS,
+ "gte",
+ 3,
+ )]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ // Three matches on the same day → one entry of count 3 → Entered on the third.
+ let day = "2025-01-10 10:00:00.000000";
+ for offset in 0..3 {
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, day, 1, offset),
+ )
+ .unwrap();
+ if offset < 2 {
+ assert!(out.transitions.is_empty());
+ } else {
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ }
+ }
+ assert_eq!(
+ compressed_count(&state_at(&store, lsk, alice).unwrap()),
+ 3,
+ "all three accumulate in one day-entry",
+ );
+
+ // A match well over 365 days later slides the whole window past that entry: it falls out, and the
+ // slide event itself only contributes 1 → count 1 < 3 → Left.
+ let slide_ts = "2026-06-01 10:00:00.000000";
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, slide_ts, 1, 3),
+ )
+ .unwrap();
+ assert_eq!(out.transitions.len(), 1);
+ assert_eq!(out.transitions[0].kind, TransitionKind::Left);
+ assert_eq!(
+ transition_kind(&filters, &out.transitions[0]),
+ "behavioral_compressed_left",
+ );
+ let state = state_at(&store, lsk, alice).unwrap();
+ assert_eq!(
+ compressed_count(&state),
+ 1,
+ "only the slide event remains in the window",
+ );
+ assert_eq!(
+ compressed_state(&state).0,
+ &[(day_of(slide_ts), 1)],
+ "the aged-out day entry was pruned, leaving only the slide day",
+ );
+}
+
+#[test]
+fn compressed_multiple_accumulates_sparsely_across_days() {
+ // Proves the compressed state stores one entry per matching day (sparse), counts repeats in place,
+ // and stays sorted — a dense array would hold 366 slots for the same data.
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(
+ COMPRESSED_WINDOW_DAYS,
+ "gte",
+ 10,
+ )]), // high: inspect, no flip
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ let day_a = "2026-01-10 10:00:00.000000";
+ let day_b = "2026-02-20 11:00:00.000000";
+ let day_c = "2026-04-05 09:00:00.000000";
+ // day_a ×2, day_b ×1, day_c ×3 (count 6) — sent interleaved to exercise the sorted in-place insert.
+ for (offset, ts) in [day_a, day_c, day_b, day_a, day_c, day_c]
+ .iter()
+ .enumerate()
+ {
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, ts, 1, offset as i64),
+ )
+ .unwrap();
+ assert!(out.transitions.is_empty(), "count 6 stays under gte 10");
+ }
+
+ let state = state_at(&store, lsk, alice).unwrap();
+ assert_eq!(
+ compressed_state(&state).0,
+ &[(day_of(day_a), 2), (day_of(day_b), 1), (day_of(day_c), 3)],
+ "one sorted entry per matching day, repeats counted in place",
+ );
+ assert_eq!(compressed_count(&state), 6);
+}
+
+#[test]
+fn compressed_multiple_late_behind_event_records_offset_without_counting() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(
+ COMPRESSED_WINDOW_DAYS,
+ "gte",
+ 1,
+ )]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let alice = person(1);
+
+ // Newest event first (offset 10) on 2026-05-27 → window covers [2025-05-27 ..= 2026-05-27].
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, "2026-05-27 12:00:00.000000", 1, 10),
+ )
+ .unwrap();
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ let before = record_at(&store, lsk, alice).unwrap();
+
+ // A late event well before the window's lower bound (2024-01-01 ≪ 2025-05-27): behind the window,
+ // so it does not count — but it is a genuine new offset and must be recorded.
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(alice, "2024-01-01 12:00:00.000000", 1, 11),
+ )
+ .unwrap();
+ assert!(
+ out.transitions.is_empty(),
+ "a behind-window event flips nothing"
+ );
+
+ let after = record_at(&store, lsk, alice).unwrap();
+ assert_eq!(
+ after.state, before.state,
+ "the behind-window event left the entries, window, deadline, and newest-event all unchanged",
+ );
+ assert_high_water(&after.applied_offsets, 1, 11);
+}
+
+#[test]
+fn compressed_multiple_cross_partition_replay_after_slide_is_byte_identical() {
+ // Skip vs re-fold are not state-identical here, so byte-identity proves `is_replay` fired.
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(
+ COMPRESSED_WINDOW_DAYS,
+ "gte",
+ 1,
+ )]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let p = person(1);
+
+ // Event from partition 10 (offset 5) on 2025-01-10, then a later event from partition 20 (offset
+ // 10) on 2025-04-15 that slides the window forward (both days stay inside the 365-day window).
+ process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(p, "2025-01-10 10:00:00.000000", 10, 5),
+ )
+ .unwrap();
+ process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(p, "2025-04-15 10:00:00.000000", 20, 10),
+ )
+ .unwrap();
+
+ let before = record_at(&store, lsk, p).unwrap();
+ assert_high_water(&before.applied_offsets, 10, 5);
+ assert_high_water(&before.applied_offsets, 20, 10);
+ assert_eq!(
+ compressed_count(&before.state),
+ 2,
+ "both days are inside the window",
+ );
+
+ // Replay partition 10's original event (offset 5 ≤ 5): is_replay fires regardless of the slide.
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &filters,
+ &event_at(p, "2025-01-10 10:00:00.000000", 10, 5),
+ )
+ .unwrap();
+ assert!(out.transitions.is_empty(), "a replay flips nothing");
+
+ let after = record_at(&store, lsk, p).unwrap();
+ assert_eq!(
+ after, before,
+ "the replay neither re-folded its entry nor disturbed partition 20's high-water mark",
+ );
+}
+
+#[tokio::test]
+async fn compressed_sweep_deletes_then_a_late_event_recreates_the_state() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(
+ CohortId(1),
+ cohort(vec![behavioral_leaf_multiple(
+ COMPRESSED_WINDOW_DAYS,
+ "gte",
+ 1,
+ )]),
+ )]);
+ let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ let catalog = catalog_of(filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ catalog,
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ MergeWorkerDeps::capture(),
+ false,
+ );
+
+ let alice = person(1);
+ let first_ts = "2025-01-15 10:00:00.000000";
+ let first_day = day_of(first_ts);
+
+ // The match enters the cohort and schedules eviction at start of day first_day + 365 + 1.
+ dispatch_to_worker(&tracker, &tx, event_at(alice, first_ts, 1, 0), 0).await;
+ // A sweep whose cutoff is past that deadline drains the lone entry → Left + delete.
+ let cutoff = start_of_day_ms_in_tz(first_day + COMPRESSED_WINDOW_DAYS as i32 + 2, UTC);
+ tx.send(vec![ShuffleMessage::Sweep {
+ due_before_ms: cutoff,
+ }])
+ .await
+ .unwrap();
+ // A fresh event, well after the delete, re-creates the state from its own day and re-enters.
+ let late_ts = "2026-06-01 10:00:00.000000";
+ dispatch_to_worker(&tracker, &tx, event_at(alice, late_ts, 1, 1), 1).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(
+ statuses,
+ vec![
+ MembershipStatus::Entered, // first event
+ MembershipStatus::Left, // sweep drains the window
+ MembershipStatus::Entered, // the late event re-creates and re-enters
+ ],
+ "the sweep deletes the compressed state and a later event re-creates it",
+ );
+
+ // The re-created state holds only the late event's day, anchored at its own window.
+ let state = state_at(&store, lsk, alice).expect("re-created by the late event");
+ assert_eq!(
+ compressed_state(&state).0,
+ &[(day_of(late_ts), 1)],
+ "re-created from the late event's own timestamp, not the deleted window",
+ );
+}
+
+fn applied(entries: &[(i32, i64)]) -> AppliedOffsets {
+ let mut applied = AppliedOffsets::default();
+ for &(partition, offset) in entries {
+ applied.record(partition, offset);
+ }
+ applied
+}
+
+/// Seed a person-property record (with a chosen dedup state) directly into `cf_stage1`.
+fn seed_person_record(store: &CohortStore, lsk: LeafStateKey, who: Uuid, record: &StatefulRecord) {
+ store
+ .write_batch(|b| b.put_stage1(&stage1_key(lsk, who), &record.encode()))
+ .unwrap();
+}
+
+#[test]
+fn fresh_event_on_a_redirect_dedup_partition_still_folds_main_map_authoritative() {
+ // A fresh (non-redirected) P_new event must dedup against the MAIN map, not an ancestor's
+ // `redirect_dedup` entry.
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let p_new = person(2);
+ let ancestor = person(1);
+
+ // P_new: not a member, main offsets at partition 5 = 50, an ancestor entry at partition 5 = 100.
+ let mut seed = StatefulRecord::new(
+ Stage1State::PersonProperty {
+ matches: false,
+ last_updated_at_ms: 1_000,
+ last_updated_offset: 0,
+ },
+ applied(&[(5, 50)]),
+ );
+ seed.redirect_dedup.insert(ancestor, applied(&[(5, 100)]));
+ seed_person_record(&store, lsk, p_new, &seed);
+
+ // A fresh event on partition 5 at offset 60: 60 > main's 50 ⇒ fold, even though 60 ≤ the ancestor
+ // entry's 100. The matching email flips the person leaf false→true.
+ let fresh = person_event(p_new, "[email protected]", BASE_TS, 5, 60);
+ let out = process_event(PARTITION_ID, &store, &filters, &fresh).unwrap();
+
+ assert_eq!(
+ out.transitions.len(),
+ 1,
+ "the fresh event folded and flipped"
+ );
+ assert_eq!(out.transitions[0].kind, TransitionKind::Entered);
+ let after = record_at(&store, lsk, p_new).unwrap();
+ assert!(matches!(
+ after.state,
+ Stage1State::PersonProperty { matches: true, .. }
+ ));
+ assert!(
+ after.applied_offsets.is_replay(5, 60),
+ "the main map advanced to the fresh event's offset",
+ );
+ assert!(
+ after.redirect_dedup[&ancestor].is_replay(5, 100)
+ && !after.redirect_dedup[&ancestor].is_replay(5, 101),
+ "the ancestor entry is untouched by a normal event",
+ );
+}
+
+#[test]
+fn redirected_event_at_or_below_ancestor_max_is_skipped_then_above_folds() {
+ // A redirected straggler (origin = P_old) must dedup against `redirect_dedup[P_old]`.
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![person_leaf()]))]);
+ let lsk = LeafStateKey::for_person_property(&PERSON_HASH);
+ let p_new = person(2);
+ let p_old = person(1);
+
+ // P_new is a member; P_old (an ancestor) folded up to offset 100 on partition 5.
+ let mut seed = StatefulRecord::new(
+ Stage1State::PersonProperty {
+ matches: true,
+ last_updated_at_ms: 1_000,
+ last_updated_offset: 0,
+ },
+ applied(&[(5, 50)]),
+ );
+ seed.redirect_dedup.insert(p_old, applied(&[(5, 100)]));
+ seed_person_record(&store, lsk, p_new, &seed);
+
+ // A redirected event at offset 80 ≤ the ancestor's 100 → replay via redirect_dedup[P_old] → skip.
+ let mut redirected_replay = person_event(p_new, "[email protected]", BASE_TS, 5, 80);
+ redirected_replay.redirected_from = Some(p_old.to_string());
+ let skipped = process_event(PARTITION_ID, &store, &filters, &redirected_replay).unwrap();
+ assert!(
+ skipped.transitions.is_empty(),
+ "a redirected replay at/below the ancestor max is skipped",
+ );
+ assert!(
+ matches!(
+ record_at(&store, lsk, p_new).unwrap().state,
+ Stage1State::PersonProperty { matches: true, .. }
+ ),
+ "the skipped replay leaves P_new's state unchanged",
+ );
+
+ // A redirected event at offset 101 > the ancestor's 100 → not a replay → folds (email no longer
+ // matches → Left), and advances the ancestor entry.
+ let mut redirected_new = person_event(p_new, "[email protected]", BASE_TS, 5, 101);
+ redirected_new.redirected_from = Some(p_old.to_string());
+ let folded = process_event(PARTITION_ID, &store, &filters, &redirected_new).unwrap();
+ assert_eq!(
+ folded.transitions.len(),
+ 1,
+ "the above-max redirected event folds"
+ );
+ assert_eq!(folded.transitions[0].kind, TransitionKind::Left);
+ let after = record_at(&store, lsk, p_new).unwrap();
+ assert!(
+ after.redirect_dedup[&p_old].is_replay(5, 101),
+ "the ancestor entry advanced to the folded offset",
+ );
+ assert!(
+ after.applied_offsets.is_replay(5, 50) && !after.applied_offsets.is_replay(5, 51),
+ "the redirected fold did not touch the main map",
+ );
+}
diff --git a/rust/cohort-stream-processor/tests/store.rs b/rust/cohort-stream-processor/tests/store.rs
new file mode 100644
index 000000000000..f610ccd0f282
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/store.rs
@@ -0,0 +1,612 @@
+//! End-to-end tests against a real RocksDB in a temp dir, through the public API only.
+
+use cohort_stream_processor::store::{
+ Cf, CohortStore, IndexOp, LeafStateKey, MergeAppliedKey, MergeDrainKey, OpaqueCf,
+ PendingTransferKey, PersonIndexKey, Stage1Key, Stage2Key, StoreConfig, TombstoneKey,
+};
+use tempfile::TempDir;
+use uuid::Uuid;
+
+fn config_in(dir: &TempDir) -> StoreConfig {
+ StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ }
+}
+
+fn open_store(dir: &TempDir) -> CohortStore {
+ CohortStore::open(&config_in(dir)).expect("open store")
+}
+
+fn lsk(b: u8) -> LeafStateKey {
+ LeafStateKey([b; 16])
+}
+
+fn person(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+}
+
+fn stage1_key(partition: u16, team: u64, leaf: u8, p: u128) -> Stage1Key {
+ Stage1Key {
+ partition_id: partition,
+ team_id: team,
+ leaf_state_key: lsk(leaf),
+ person_id: person(p),
+ }
+}
+
+fn person_index_key(partition: u16, team: u64, p: u128) -> PersonIndexKey {
+ PersonIndexKey {
+ partition_id: partition,
+ team_id: team,
+ person_id: person(p),
+ }
+}
+
+fn stage2_key(partition: u16, team: u64, cohort: u64, p: u128) -> Stage2Key {
+ Stage2Key {
+ partition_id: partition,
+ team_id: team,
+ cohort_id: cohort,
+ person_id: person(p),
+ }
+}
+
+fn merge_drain_key(partition: u16, team: u64, old: u128) -> MergeDrainKey {
+ MergeDrainKey {
+ partition_id: partition,
+ team_id: team,
+ old_person: person(old),
+ merge_msg_partition: 17,
+ merge_msg_offset: 99,
+ }
+}
+
+fn pending_transfer_key(partition: u16, team: u64, old: u128) -> PendingTransferKey {
+ PendingTransferKey {
+ partition_id: partition,
+ team_id: team,
+ old_person: person(old),
+ }
+}
+
+fn merge_applied_key(partition: u16, team: u64, new: u128) -> MergeAppliedKey {
+ MergeAppliedKey {
+ partition_id: partition,
+ team_id: team,
+ new_person: person(new),
+ source_partition: 3,
+ source_offset: 42,
+ }
+}
+
+fn tombstone_key(partition: u16, team: u64, p: u128) -> TombstoneKey {
+ TombstoneKey {
+ partition_id: partition,
+ team_id: team,
+ person: person(p),
+ }
+}
+
+#[test]
+fn point_writes_and_reads_per_cf() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+
+ let s1 = stage1_key(0, 100, 1, 7);
+ let s2 = stage2_key(0, 100, 55, 7);
+ let pix = person_index_key(0, 100, 7);
+
+ store
+ .write_batch(|b| {
+ b.put_stage1(&s1, b"stage1-value");
+ b.put_stage2(&s2, b"stage2-value");
+ b.merge_person_index(&pix, IndexOp::Append(lsk(1)));
+ })
+ .unwrap();
+
+ assert_eq!(
+ store.get_stage1(&s1).unwrap().as_deref(),
+ Some(&b"stage1-value"[..])
+ );
+ assert_eq!(
+ store.get_stage2(&s2).unwrap().as_deref(),
+ Some(&b"stage2-value"[..])
+ );
+ assert_eq!(store.get_person_index(&pix).unwrap(), vec![lsk(1)]);
+
+ assert_eq!(
+ store.get(Cf::Stage1, &s1.encode()).unwrap().as_deref(),
+ Some(&b"stage1-value"[..])
+ );
+
+ assert!(store
+ .get_stage1(&stage1_key(0, 100, 1, 999))
+ .unwrap()
+ .is_none());
+ assert!(store
+ .get_person_index(&person_index_key(0, 100, 999))
+ .unwrap()
+ .is_empty());
+}
+
+#[test]
+fn put_raw_writes_to_the_addressed_opaque_cf() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+
+ let s1 = stage1_key(4, 100, 7, 11);
+ let s2 = stage2_key(4, 100, 88, 11);
+
+ store
+ .write_batch(|b| {
+ b.put_raw(OpaqueCf::Stage1, &s1.encode(), b"raw-s1");
+ b.put_raw(OpaqueCf::Stage2, &s2.encode(), b"raw-s2");
+ })
+ .unwrap();
+
+ assert_eq!(
+ store.get_stage1(&s1).unwrap().as_deref(),
+ Some(&b"raw-s1"[..])
+ );
+ assert_eq!(
+ store.get(Cf::Stage1, &s1.encode()).unwrap().as_deref(),
+ Some(&b"raw-s1"[..])
+ );
+ assert_eq!(
+ store.get_stage2(&s2).unwrap().as_deref(),
+ Some(&b"raw-s2"[..])
+ );
+}
+
+#[test]
+fn cross_cf_write_batch_is_atomic() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+
+ let s1 = stage1_key(3, 200, 9, 42);
+ let pix = person_index_key(3, 200, 42);
+
+ store
+ .write_batch(|b| {
+ b.put_stage1(&s1, b"v");
+ b.merge_person_index(&pix, IndexOp::Append(s1.leaf_state_key));
+ })
+ .unwrap();
+
+ assert_eq!(store.get_stage1(&s1).unwrap().as_deref(), Some(&b"v"[..]));
+ assert_eq!(store.get_person_index(&pix).unwrap(), vec![lsk(9)]);
+}
+
+/// Removing every entry must read back as empty, not a "Merge operator failed" error (which is what
+/// returning `None` from `full_merge` would produce).
+#[test]
+fn secondary_index_merge_append_and_remove() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+ let pix = person_index_key(1, 300, 5);
+
+ for leaf in [10u8, 20, 30] {
+ store
+ .write_batch(|b| b.merge_person_index(&pix, IndexOp::Append(lsk(leaf))))
+ .unwrap();
+ }
+ assert_eq!(
+ store.get_person_index(&pix).unwrap(),
+ vec![lsk(10), lsk(20), lsk(30)]
+ );
+
+ // Flush forces the operator to collapse into an SST before the read-back.
+ store
+ .write_batch(|b| b.merge_person_index(&pix, IndexOp::Remove(lsk(20))))
+ .unwrap();
+ store.flush().unwrap();
+ assert_eq!(
+ store.get_person_index(&pix).unwrap(),
+ vec![lsk(10), lsk(30)]
+ );
+
+ store
+ .write_batch(|b| {
+ b.merge_person_index(&pix, IndexOp::Remove(lsk(10)));
+ b.merge_person_index(&pix, IndexOp::Remove(lsk(30)));
+ })
+ .unwrap();
+ store.flush().unwrap();
+ assert_eq!(store.get_person_index(&pix).unwrap(), vec![]);
+}
+
+#[test]
+fn delete_partition_isolates_other_partitions() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+
+ let write_partition = |p: u16| {
+ store
+ .write_batch(|b| {
+ b.put_stage1(&stage1_key(p, 100, 1, 7), b"s1");
+ b.put_stage2(&stage2_key(p, 100, 55, 7), b"s2");
+ b.merge_person_index(&person_index_key(p, 100, 7), IndexOp::Append(lsk(1)));
+ })
+ .unwrap();
+ };
+ write_partition(0);
+ write_partition(1);
+
+ store.delete_partition(0).unwrap();
+
+ assert!(store
+ .get_stage1(&stage1_key(0, 100, 1, 7))
+ .unwrap()
+ .is_none());
+ assert!(store
+ .get_stage2(&stage2_key(0, 100, 55, 7))
+ .unwrap()
+ .is_none());
+ assert!(store
+ .get_person_index(&person_index_key(0, 100, 7))
+ .unwrap()
+ .is_empty());
+
+ assert_eq!(
+ store
+ .get_stage1(&stage1_key(1, 100, 1, 7))
+ .unwrap()
+ .as_deref(),
+ Some(&b"s1"[..])
+ );
+ assert_eq!(
+ store
+ .get_stage2(&stage2_key(1, 100, 55, 7))
+ .unwrap()
+ .as_deref(),
+ Some(&b"s2"[..])
+ );
+ assert_eq!(
+ store
+ .get_person_index(&person_index_key(1, 100, 7))
+ .unwrap(),
+ vec![lsk(1)]
+ );
+}
+
+#[test]
+fn data_survives_reopen() {
+ let dir = TempDir::new().unwrap();
+ let config = config_in(&dir);
+
+ let s1 = stage1_key(2, 100, 4, 8);
+ let pix = person_index_key(2, 100, 8);
+
+ {
+ let store = CohortStore::open(&config).unwrap();
+ store
+ .write_batch(|b| {
+ b.put_stage1(&s1, b"persisted");
+ b.merge_person_index(&pix, IndexOp::Append(lsk(4)));
+ })
+ .unwrap();
+ store.flush().unwrap();
+ } // drop releases the DB lock so the reopen below can acquire it
+
+ let reopened = CohortStore::open(&config).unwrap();
+ assert_eq!(
+ reopened.get_stage1(&s1).unwrap().as_deref(),
+ Some(&b"persisted"[..])
+ );
+ assert_eq!(reopened.get_person_index(&pix).unwrap(), vec![lsk(4)]);
+}
+
+#[test]
+fn one_write_batch_spans_state_and_merge_cfs_atomically() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+
+ let s1 = stage1_key(2, 100, 1, 7);
+ let s2 = stage2_key(2, 100, 55, 7);
+ let drain = merge_drain_key(2, 100, 7);
+ let pending = pending_transfer_key(2, 100, 7);
+ let applied = merge_applied_key(2, 100, 8);
+ let tombstone = tombstone_key(2, 100, 7);
+
+ // A drain-shaped batch: delete P_old's state, stage the outbox + idempotence markers + tombstone,
+ // all in one WriteBatch spanning the old and new CFs.
+ store
+ .write_batch(|b| {
+ b.put_stage1(&s1, b"old-state");
+ b.put_stage2(&s2, b"old-stage2");
+ })
+ .unwrap();
+ store
+ .write_batch(|b| {
+ b.delete_stage1(&s1);
+ b.delete_stage2(&s2);
+ b.delete_person_index(&PersonIndexKey {
+ partition_id: 2,
+ team_id: 100,
+ person_id: person(7),
+ });
+ b.put_merge_drain_applied(&drain, b"drained_at");
+ b.put_pending_transfer(&pending, b"transfer-payload");
+ b.put_merge_applied(&applied, b"applied_at");
+ b.put_tombstone(&tombstone, b"P_new+merged_at");
+ })
+ .unwrap();
+
+ assert!(
+ store.get_stage1(&s1).unwrap().is_none(),
+ "P_old state deleted"
+ );
+ assert!(store.get_stage2(&s2).unwrap().is_none());
+ assert_eq!(
+ store.get_merge_drain_applied(&drain).unwrap().as_deref(),
+ Some(&b"drained_at"[..]),
+ );
+ assert_eq!(
+ store.get_pending_transfer(&pending).unwrap().as_deref(),
+ Some(&b"transfer-payload"[..]),
+ );
+ assert_eq!(
+ store.get_merge_applied(&applied).unwrap().as_deref(),
+ Some(&b"applied_at"[..]),
+ );
+ assert_eq!(
+ store.get_tombstone(&tombstone).unwrap().as_deref(),
+ Some(&b"P_new+merged_at"[..]),
+ );
+
+ store
+ .write_batch(|b| b.delete_pending_transfer(&pending))
+ .unwrap();
+ assert!(store.get_pending_transfer(&pending).unwrap().is_none());
+ assert!(
+ store.get_tombstone(&tombstone).unwrap().is_some(),
+ "clearing the outbox leaves the tombstone in place",
+ );
+}
+
+#[test]
+fn delete_person_index_then_reappend_rebuilds_from_empty() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+ let pix = person_index_key(0, 100, 7);
+
+ store
+ .write_batch(|b| {
+ b.merge_person_index(&pix, IndexOp::Append(lsk(1)));
+ b.merge_person_index(&pix, IndexOp::Append(lsk(2)));
+ })
+ .unwrap();
+ store.flush().unwrap();
+ assert_eq!(store.get_person_index(&pix).unwrap(), vec![lsk(1), lsk(2)]);
+
+ store.write_batch(|b| b.delete_person_index(&pix)).unwrap();
+ store.flush().unwrap();
+ assert!(store.get_person_index(&pix).unwrap().is_empty());
+
+ // A fresh append after the delete starts from empty — only the new leaf is present.
+ store
+ .write_batch(|b| b.merge_person_index(&pix, IndexOp::Append(lsk(9))))
+ .unwrap();
+ store.flush().unwrap();
+ assert_eq!(
+ store.get_person_index(&pix).unwrap(),
+ vec![lsk(9)],
+ "the whole-key delete is a base tombstone; the re-append never resurrects lsk 1/2",
+ );
+}
+
+#[test]
+fn delete_partition_reclaims_the_merge_cfs() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+
+ let seed = |p: u16| {
+ store
+ .write_batch(|b| {
+ b.put_merge_drain_applied(&merge_drain_key(p, 100, 7), b"d");
+ b.put_pending_transfer(&pending_transfer_key(p, 100, 7), b"t");
+ b.put_merge_applied(&merge_applied_key(p, 100, 8), b"a");
+ b.put_tombstone(&tombstone_key(p, 100, 7), b"s");
+ })
+ .unwrap();
+ };
+ seed(0);
+ seed(1);
+
+ store.delete_partition(0).unwrap();
+
+ assert!(store
+ .get_merge_drain_applied(&merge_drain_key(0, 100, 7))
+ .unwrap()
+ .is_none());
+ assert!(store
+ .get_pending_transfer(&pending_transfer_key(0, 100, 7))
+ .unwrap()
+ .is_none());
+ assert!(store
+ .get_merge_applied(&merge_applied_key(0, 100, 8))
+ .unwrap()
+ .is_none());
+ assert!(store
+ .get_tombstone(&tombstone_key(0, 100, 7))
+ .unwrap()
+ .is_none());
+ assert!(store
+ .scan_pending_transfers(0, None, usize::MAX)
+ .unwrap()
+ .is_empty());
+
+ assert!(store
+ .get_tombstone(&tombstone_key(1, 100, 7))
+ .unwrap()
+ .is_some());
+ assert_eq!(
+ store
+ .scan_pending_transfers(1, None, usize::MAX)
+ .unwrap()
+ .len(),
+ 1
+ );
+}
+
+#[test]
+fn scan_pending_transfers_returns_only_its_partition_in_key_order() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+
+ // Two persons in partition 5 (inserted out of order), one in the neighbouring partitions 4 and 6.
+ store
+ .write_batch(|b| {
+ b.put_pending_transfer(&pending_transfer_key(5, 100, 30), b"p30");
+ b.put_pending_transfer(&pending_transfer_key(5, 100, 10), b"p10");
+ b.put_pending_transfer(&pending_transfer_key(4, 100, 99), b"p4");
+ b.put_pending_transfer(&pending_transfer_key(6, 100, 99), b"p6");
+ })
+ .unwrap();
+
+ let scanned = store.scan_pending_transfers(5, None, usize::MAX).unwrap();
+ assert_eq!(scanned.len(), 2, "only partition 5's entries");
+ // Person UUIDs from `Uuid::from_u128` sort by their big-endian bytes, so 10 precedes 30.
+ assert_eq!(scanned[0].0, pending_transfer_key(5, 100, 10));
+ assert_eq!(scanned[0].1, b"p10");
+ assert_eq!(scanned[1].0, pending_transfer_key(5, 100, 30));
+ assert_eq!(scanned[1].1, b"p30");
+
+ assert_eq!(
+ store
+ .scan_pending_transfers(4, None, usize::MAX)
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert_eq!(
+ store
+ .scan_pending_transfers(6, None, usize::MAX)
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert!(
+ store
+ .scan_pending_transfers(7, None, usize::MAX)
+ .unwrap()
+ .is_empty(),
+ "an empty partition scans to nothing",
+ );
+}
+
+#[test]
+fn scan_pending_transfers_caps_at_the_limit() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+
+ // Stage more entries than the limit; the bounded scan must early-break and return exactly `limit`.
+ let limit = 5usize;
+ store
+ .write_batch(|b| {
+ for old in 0..(limit as u128 + 3) {
+ b.put_pending_transfer(&pending_transfer_key(2, 100, old), b"v");
+ }
+ })
+ .unwrap();
+
+ let scanned = store.scan_pending_transfers(2, None, limit).unwrap();
+ assert_eq!(
+ scanned.len(),
+ limit,
+ "the scan stops at the limit even though more entries exist",
+ );
+ // The early-break keeps the lowest keys in order (UUIDs from `Uuid::from_u128` sort big-endian).
+ let firsts: Vec<_> = scanned.iter().map(|(k, _)| k.old_person).collect();
+ assert_eq!(
+ firsts,
+ (0..limit as u128).map(person).collect::<Vec<_>>(),
+ "returns the `limit` smallest keys, in key order",
+ );
+}
+
+#[test]
+fn scan_pending_transfers_resumes_after_the_cursor() {
+ let dir = TempDir::new().unwrap();
+ let store = open_store(&dir);
+
+ store
+ .write_batch(|b| {
+ for old in 0..5u128 {
+ b.put_pending_transfer(&pending_transfer_key(2, 100, old), b"v");
+ }
+ })
+ .unwrap();
+
+ // Walk the slice two at a time, resuming strictly after the last key of each page. The cursor is
+ // exclusive, so the union of the pages is every key exactly once with no overlap and no gap.
+ let mut seen = Vec::new();
+ let mut cursor: Option<Vec<u8>> = None;
+ loop {
+ let page = store
+ .scan_pending_transfers(2, cursor.as_deref(), 2)
+ .unwrap();
+ if page.is_empty() {
+ break;
+ }
+ cursor = Some(page.last().unwrap().0.encode().to_vec());
+ let last_was_short = page.len() < 2;
+ seen.extend(page.into_iter().map(|(k, _)| k.old_person));
+ if last_was_short {
+ break;
+ }
+ }
+
+ assert_eq!(
+ seen,
+ (0..5u128).map(person).collect::<Vec<_>>(),
+ "paginating with the cursor yields every key once, in key order",
+ );
+}
+
+#[test]
+fn merge_cf_values_survive_reopen_without_wipe() {
+ let dir = TempDir::new().unwrap();
+ let config = config_in(&dir);
+
+ let drain = merge_drain_key(2, 100, 7);
+ let pending = pending_transfer_key(2, 100, 7);
+ let applied = merge_applied_key(2, 100, 8);
+ let tombstone = tombstone_key(2, 100, 7);
+
+ {
+ let store = CohortStore::open(&config).unwrap();
+ store
+ .write_batch(|b| {
+ b.put_merge_drain_applied(&drain, b"d");
+ b.put_pending_transfer(&pending, b"t");
+ b.put_merge_applied(&applied, b"a");
+ b.put_tombstone(&tombstone, b"s");
+ })
+ .unwrap();
+ store.flush().unwrap();
+ } // drop releases the DB lock
+
+ let reopened = CohortStore::open(&config).unwrap();
+ assert_eq!(
+ reopened.get_merge_drain_applied(&drain).unwrap().as_deref(),
+ Some(&b"d"[..]),
+ );
+ assert_eq!(
+ reopened.get_pending_transfer(&pending).unwrap().as_deref(),
+ Some(&b"t"[..]),
+ );
+ assert_eq!(
+ reopened.get_merge_applied(&applied).unwrap().as_deref(),
+ Some(&b"a"[..]),
+ );
+ assert_eq!(
+ reopened.get_tombstone(&tombstone).unwrap().as_deref(),
+ Some(&b"s"[..]),
+ );
+ let scanned = reopened
+ .scan_pending_transfers(2, None, usize::MAX)
+ .unwrap();
+ assert_eq!(scanned, vec![(pending, b"t".to_vec())]);
+}
diff --git a/rust/cohort-stream-processor/tests/sweep_eviction_queue.rs b/rust/cohort-stream-processor/tests/sweep_eviction_queue.rs
new file mode 100644
index 000000000000..05f039f50b98
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/sweep_eviction_queue.rs
@@ -0,0 +1,158 @@
+//! `EvictionQueue` driven against the real `Stage1Key` over a simulated day of events, through the
+//! crate's public sweep API (no Kafka, no clock — synthetic `now` stepped by hand).
+//!
+//! The deterministic oracle is the whole point: an independent `HashMap<Stage1Key, deadline>` of each
+//! key's *live* (post-reschedule) deadline. Stepping a fake `now` in 30 s increments and draining
+//! `pop_due(now − margin)` each step, we assert every key evicts **exactly once**, at the **first**
+//! step where `live_deadline + safety_margin < now`, never earlier, with the queue length equal to
+//! the not-yet-evicted count throughout.
+
+use std::collections::HashMap;
+
+use cohort_stream_processor::stage1::key::{LeafStateKey, Stage1Key};
+use cohort_stream_processor::sweep::{due_before_ms, EvictionQueue};
+use uuid::Uuid;
+
+const BASE_MS: i64 = 1_700_000_000_000; // an arbitrary "start of day" epoch-ms anchor
+const DAY_MS: i64 = 86_400_000;
+const STEP_MS: i64 = 30_000; // the 30 s sweep cadence
+const MARGIN_MS: i64 = 300_000; // the 5 min safety margin
+
+/// A distinct `Stage1Key` per index. `person_id` alone guarantees distinctness; `team`, `partition`,
+/// and `leaf_state_key` are varied too so the simulation looks like real `(team, leaf, person)` keys.
+fn key(i: usize) -> Stage1Key {
+ Stage1Key {
+ partition_id: (i % 64) as u16,
+ team_id: (i % 5) as u64 + 1,
+ leaf_state_key: LeafStateKey((i as u128).to_le_bytes()),
+ person_id: Uuid::from_u128(0x00C0_FFEE_0000_0000_u128 + i as u128),
+ }
+}
+
+#[test]
+fn one_day_of_events_evicts_each_key_once_at_its_deadline() {
+ const N: usize = 300;
+
+ let mut queue: EvictionQueue<Stage1Key> = EvictionQueue::new();
+ // The independent oracle: each key's *final* deadline after all reschedules.
+ let mut oracle: HashMap<Stage1Key, i64> = HashMap::new();
+
+ // Pass 1 — initial deadlines spread evenly across the 24 h window, all at least `MARGIN_MS` past
+ // `BASE_MS` so nothing is due at the first step.
+ for i in 0..N {
+ let initial = BASE_MS + MARGIN_MS + (i as i64) * DAY_MS / (N as i64);
+ queue.schedule(key(i), initial);
+ oracle.insert(key(i), initial);
+ }
+ assert_eq!(queue.len(), N, "distinct keys, one slot each");
+
+ // Pass 2 — reschedule two thirds of the keys, mixing both directions:
+ // - i % 3 == 1: later (the window slid forward as newer events arrived).
+ // - i % 3 == 2: earlier (a late event landed in an older bucket, pulling the deadline back —
+ // the case a lazily-deleted BinaryHeap would leave a stale far-future entry behind for).
+ for i in 0..N {
+ let current = oracle[&key(i)];
+ let rescheduled = match i % 3 {
+ 1 => current + DAY_MS / (2 * N as i64),
+ 2 => current - DAY_MS / (2 * N as i64),
+ _ => continue,
+ };
+ queue.schedule(key(i), rescheduled);
+ oracle.insert(key(i), rescheduled);
+ }
+ assert_eq!(queue.len(), N, "reschedules supersede, never duplicate");
+
+ // Precondition for the "first eligible step" assertion below: no key is due at the first step.
+ let earliest_deadline = *oracle.values().min().expect("non-empty");
+ assert!(
+ earliest_deadline > due_before_ms(BASE_MS + STEP_MS, MARGIN_MS),
+ "the simulation must start before any key is due",
+ );
+
+ // Step `now` forward in 30 s increments, draining everything due at each step.
+ let mut evicted: HashMap<Stage1Key, i64> = HashMap::new();
+ let mut now = BASE_MS;
+ let mut prev_due_before = i64::MIN; // the previous step's cutoff; -inf before the first step
+ let mut steps = 0;
+
+ while evicted.len() < N {
+ now += STEP_MS;
+ steps += 1;
+ assert!(steps < 100_000, "simulation failed to converge");
+
+ let cutoff = due_before_ms(now, MARGIN_MS);
+ while let Some((evicted_key, deadline)) = queue.pop_due(cutoff) {
+ let live = oracle[&evicted_key];
+ assert_eq!(deadline, live, "a key evicts carrying its live deadline");
+ assert!(
+ deadline < cutoff,
+ "no key evicts before due: deadline {deadline} >= cutoff {cutoff}",
+ );
+ assert!(
+ deadline >= prev_due_before,
+ "evicted at the FIRST eligible step (was not due one step earlier)",
+ );
+ assert!(
+ evicted.insert(evicted_key, now).is_none(),
+ "each key evicts exactly once",
+ );
+ }
+
+ assert_eq!(
+ queue.len(),
+ N - evicted.len(),
+ "queue length equals the not-yet-evicted count at every step",
+ );
+ prev_due_before = cutoff;
+ }
+
+ assert_eq!(evicted.len(), N, "every key evicted exactly once");
+ assert!(queue.is_empty());
+ assert_eq!(queue.peek_next_deadline(), None);
+
+ // Every eviction lands within one sweep step after the ideal `deadline + margin` instant. The
+ // window is half-open `(ideal, ideal + STEP]`: strict `<` in `pop_due` means a deadline+margin
+ // exactly on a step boundary is held one more step, firing at `ideal + STEP`.
+ for (k, &fired_at) in &evicted {
+ let ideal = oracle[k] + MARGIN_MS;
+ assert!(
+ fired_at > ideal && fired_at <= ideal + STEP_MS,
+ "key fired at {fired_at}, expected within ({ideal}, {}]",
+ ideal + STEP_MS,
+ );
+ }
+}
+
+#[test]
+fn cancelled_keys_never_evict() {
+ let mut queue: EvictionQueue<Stage1Key> = EvictionQueue::new();
+ let deadline = BASE_MS + MARGIN_MS;
+ for i in 0..10 {
+ queue.schedule(key(i), deadline);
+ }
+
+ // Cancel the even-indexed keys (e.g. their external state was deleted) before the sweep runs.
+ for i in (0..10).step_by(2) {
+ queue.cancel(&key(i));
+ }
+ assert_eq!(queue.len(), 5);
+
+ // Step well past the deadline + margin and drain.
+ let cutoff = due_before_ms(deadline + MARGIN_MS + STEP_MS, MARGIN_MS);
+ let mut evicted = Vec::new();
+ while let Some((k, _)) = queue.pop_due(cutoff) {
+ evicted.push(k);
+ }
+
+ assert_eq!(evicted.len(), 5, "only the non-cancelled keys evict");
+ for i in (0..10).step_by(2) {
+ assert!(
+ !evicted.contains(&key(i)),
+ "cancelled key {i} must never evict",
+ );
+ }
+ for i in (1..10).step_by(2) {
+ assert!(evicted.contains(&key(i)), "live key {i} must evict");
+ }
+ assert!(queue.is_empty());
+}
diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rs
new file mode 100644
index 000000000000..5838eca4b729
--- /dev/null
+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs
@@ -0,0 +1,1894 @@
+//! The time-driven eviction sweep, driven end-to-end through the public API (no Kafka). Events flow
+//! through a spawned [`Stage1Worker`](cohort_stream_processor::workers::Stage1Worker) to schedule
+//! evictions, then a [`ShuffleMessage::Sweep`](cohort_stream_processor::partitions::ShuffleMessage)
+//! with a synthetic cutoff drains the worker's queue. One case drives the real
+//! [`DispatchSweeper`](cohort_stream_processor::sweep::DispatchSweeper) over an
+//! [`EventDispatcher`](cohort_stream_processor::consumers::EventDispatcher) to cover the production
+//! routing path. The scheduling/queue mechanics themselves are unit-tested in
+//! `tests/sweep_eviction_queue.rs`; the per-variant eviction in `src/workers/sweep_callback.rs`.
+//! The Stage 2 section covers a time-driven leaf flip recomposing its composable (multi-leaf)
+//! cohorts through the sweep's second produce.
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+
+use async_trait::async_trait;
+use chrono_tz::America::New_York;
+use chrono_tz::Asia::Kolkata;
+use chrono_tz::{Tz, UTC};
+use cohort_stream_processor::consumers::{CohortStreamEvent, EventDispatcher};
+use cohort_stream_processor::filters::{
+ CatalogHandle, CohortId, FilterCatalog, TeamFilters, TeamFiltersBuilder, TeamId,
+};
+use cohort_stream_processor::partitions::{OffsetTracker, PartitionRouter, ShuffleMessage};
+use cohort_stream_processor::producer::{
+ CaptureSink, CohortMembershipChange, MembershipSink, MembershipStatus,
+};
+use cohort_stream_processor::stage1::bucket_tz::{day_idx_in_tz, start_of_day_ms_in_tz};
+use cohort_stream_processor::stage1::{
+ clickhouse_timestamp_to_millis, Stage1State, StateVariant, StatefulRecord,
+};
+use cohort_stream_processor::stage2::Stage2State;
+use cohort_stream_processor::store::{
+ CohortStore, LeafStateKey, PersonIndexKey, Stage1Key, Stage2Key, StoreConfig,
+};
+use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, Stage1Worker};
+use common_kafka::kafka_producer::KafkaProduceError;
+use serde_json::{json, Value};
+use tempfile::TempDir;
+use tokio::sync::mpsc;
+use uuid::Uuid;
+
+const TEAM: i32 = 7;
+const PARTITION_ID: u16 = 0;
+const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";
+const DAY_MS: i64 = 86_400_000;
+/// A window over 180 days routes `performed_event_multiple` to the compressed history variant.
+const COMPRESSED_WINDOW_DAYS: i64 = 365;
+
+fn temp_store() -> (TempDir, CohortStore) {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .expect("open store");
+ (dir, store)
+}
+
+fn behavioral_bytecode() -> Value {
+ json!(["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11])
+}
+
+/// A `performed_event` leaf on `$pageview` with a tunable relative window (in days).
+fn behavioral_leaf(window_days: i64) -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": window_days, "time_interval": "day",
+ "conditionHash": "0123456789abcdef",
+ "bytecode": behavioral_bytecode(),
+ })
+}
+
+/// A `performed_event` leaf over an explicit date range (so its eviction deadline is `i64::MAX`). The
+/// lower bound is the space-separated ClickHouse shape; the upper bound is the real cohort-date-picker
+/// wire shape (`dayjs(...).format('YYYY-MM-DDTHH:mm:ss')` — T-separated, no offset), so the test
+/// exercises a format the UI actually emits rather than one only the old test fabricated.
+fn explicit_behavioral_leaf() -> Value {
+ explicit_behavioral_leaf_range("2026-01-01 00:00:00.000000", "2026-12-31T00:00:00")
+}
+
+fn explicit_behavioral_leaf_range(from: &str, to: &str) -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "explicit_datetime": from,
+ "explicit_datetime_to": to,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": behavioral_bytecode(),
+ })
+}
+
+/// A `performed_event_multiple` leaf: `<op> <value>` over a `window_days`-day window.
+fn behavioral_leaf_multiple(window_days: i64, op: &str, value: i64) -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event_multiple", "key": "$pageview",
+ "time_value": window_days, "time_interval": "day",
+ "operator": op, "operator_value": value,
+ "conditionHash": "0123456789abcdef",
+ "bytecode": behavioral_bytecode(),
+ })
+}
+
+/// A person-property leaf: `email == "[email protected]"`. Never time-evicted, so it pairs with a behavioral
+/// leaf to make a composable (multi-leaf) cohort whose sweep flips must recompose Stage 2.
+fn person_leaf() -> Value {
+ json!({
+ "type": "person", "key": "email", "value": "[email protected]", "operator": "exact",
+ "conditionHash": "fedcba9876543210",
+ "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ })
+}
+
+fn cohort(values: Vec<Value>) -> Value {
+ json!({ "properties": { "type": "AND", "values": values } })
+}
+
+fn build_team_filters(leaves: Vec<Value>) -> TeamFilters {
+ build_team_filters_multi(vec![(CohortId(1), leaves)])
+}
+
+fn build_team_filters_multi(cohorts: Vec<(CohortId, Vec<Value>)>) -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ for (id, leaves) in cohorts {
+ builder
+ .add_cohort(id, TeamId(TEAM), &cohort(leaves))
+ .expect("add cohort");
+ }
+ builder.freeze(UTC)
+}
+
+/// A single-cohort catalog frozen under an explicit team timezone, so the sweep evicts at that zone's
+/// local midnight rather than UTC's.
+fn build_team_filters_tz(leaves: Vec<Value>, tz: Tz) -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(1), TeamId(TEAM), &cohort(leaves))
+ .expect("add cohort");
+ builder.freeze(tz)
+}
+
+fn catalog_of(filters: TeamFilters) -> Arc<CatalogHandle> {
+ Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
+ TeamId(TEAM),
+ filters,
+ )])))
+}
+
+fn person(n: u128) -> Uuid {
+ Uuid::from_u128(n)
+}
+
+/// A matching `$pageview` event for `person` at `timestamp`.
+fn event_at(person: Uuid, timestamp: &str, source_offset: i64) -> CohortStreamEvent {
+ CohortStreamEvent {
+ team_id: TEAM,
+ person_id: person.to_string(),
+ distinct_id: "d".to_string(),
+ uuid: Uuid::from_u128(0xE0_0000 + source_offset as u128).to_string(),
+ event: "$pageview".to_string(),
+ timestamp: timestamp.to_string(),
+ properties: Some("{}".to_string()),
+ person_properties: None,
+ elements_chain: None,
+ source_offset,
+ source_partition: 1,
+ redirected_from: None,
+ redirect_hops: 0,
+ }
+}
+
+/// Like [`event_at`] but carrying the matching person properties, so one event flips a behavioral
+/// and a person leaf together.
+fn person_event_at(person: Uuid, timestamp: &str, source_offset: i64) -> CohortStreamEvent {
+ CohortStreamEvent {
+ person_properties: Some(r#"{"email":"[email protected]"}"#.to_string()),
+ ..event_at(person, timestamp, source_offset)
+ }
+}
+
+fn behavioral_lsk(filters: &TeamFilters) -> LeafStateKey {
+ filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0]
+}
+
+/// The stored `cf_stage2` membership bit for `(cohort_id, person)`, or `None` when never evaluated.
+fn stage2_bit(store: &CohortStore, cohort_id: u64, person: Uuid) -> Option<bool> {
+ let key = Stage2Key {
+ partition_id: PARTITION_ID,
+ team_id: TEAM as u64,
+ cohort_id,
+ person_id: person,
+ };
+ store
+ .get_stage2(&key)
+ .unwrap()
+ .map(|bytes| Stage2State::decode(&bytes).unwrap().in_cohort)
+}
+
+fn state_at(store: &CohortStore, lsk: LeafStateKey, person: Uuid) -> Option<Stage1State> {
+ let key = Stage1Key {
+ partition_id: PARTITION_ID,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: person,
+ };
+ store
+ .get_stage1(&key)
+ .unwrap()
+ .map(|bytes| StatefulRecord::decode(&bytes).unwrap().state)
+}
+
+fn day_of(ts: &str) -> i32 {
+ day_idx_in_tz(clickhouse_timestamp_to_millis(ts).unwrap(), UTC)
+}
+
+/// The person's `cf_person_index` leaf-state set — the leaves the merge drain would enumerate.
+fn person_index_of(store: &CohortStore, person: Uuid) -> Vec<LeafStateKey> {
+ store
+ .get_person_index(&PersonIndexKey {
+ partition_id: PARTITION_ID,
+ team_id: TEAM as u64,
+ person_id: person,
+ })
+ .unwrap()
+}
+
+/// Raise the dispatch ceiling, then deliver one event to the worker (matching the dispatcher's
+/// produce-before-commit ordering).
+async fn send_event(
+ tracker: &OffsetTracker,
+ tx: &mpsc::Sender<Vec<ShuffleMessage>>,
+ event: CohortStreamEvent,
+ cse_offset: i64,
+) {
+ tracker.mark_dispatched(PARTITION_ID as i32, cse_offset + 1);
+ tx.send(vec![ShuffleMessage::Event { event, cse_offset }])
+ .await
+ .unwrap();
+}
+
+async fn send_sweep(tx: &mpsc::Sender<Vec<ShuffleMessage>>, due_before_ms: i64) {
+ tx.send(vec![ShuffleMessage::Sweep { due_before_ms }])
+ .await
+ .unwrap();
+}
+
+/// Drive the current-thread runtime until the worker has recorded `count` changes, so a test can read
+/// the intermediate post-sweep state mid-stream (the queue is per-worker, so it can't drop the worker
+/// to barrier). [`CaptureSink::produce`] is immediately-ready and `handle_sweep` does its state write
+/// and reschedule synchronously right after it, so once a sweep's change lands its state mutation is
+/// durable too — no wall-clock sleep needed.
+async fn drain_until_changes(sink: &CaptureSink, count: usize) {
+ for _ in 0..10_000 {
+ if sink.changes().len() >= count {
+ return;
+ }
+ tokio::task::yield_now().await;
+ }
+ panic!("worker did not record {count} changes");
+}
+
+fn spawn_worker(
+ store: &CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: Arc<dyn MembershipSink>,
+ tracker: Arc<OffsetTracker>,
+) -> (mpsc::Sender<Vec<ShuffleMessage>>, Stage1Worker) {
+ spawn_worker_with_restore(store, catalog, sink, tracker, false)
+}
+
+/// Like [`spawn_worker`] but with the durable-restart `EvictionQueue` rebuild on: the worker re-seeds
+/// its queue from the partition's existing `cf_stage1` on spawn.
+fn spawn_worker_durable(
+ store: &CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: Arc<dyn MembershipSink>,
+ tracker: Arc<OffsetTracker>,
+) -> (mpsc::Sender<Vec<ShuffleMessage>>, Stage1Worker) {
+ spawn_worker_with_restore(store, catalog, sink, tracker, true)
+}
+
+fn spawn_worker_with_restore(
+ store: &CohortStore,
+ catalog: Arc<CatalogHandle>,
+ sink: Arc<dyn MembershipSink>,
+ tracker: Arc<OffsetTracker>,
+ durable_restore: bool,
+) -> (mpsc::Sender<Vec<ShuffleMessage>>, Stage1Worker) {
+ let (tx, rx) = mpsc::channel(16);
+ let worker = Stage1Worker::spawn(
+ PARTITION_ID,
+ rx,
+ store.clone(),
+ catalog,
+ sink,
+ tracker,
+ MergeWorkerDeps::capture(),
+ durable_restore,
+ );
+ (tx, worker)
+}
+
+#[tokio::test]
+async fn sweep_evicts_a_single_leaf_member_emits_left_and_deletes() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+ let deadline = event_ms + 7 * DAY_MS;
+
+ // The matching event enters the cohort and schedules the eviction for `deadline`.
+ send_event(&tracker, &tx, event_at(alice, ts, 0), 0).await;
+ // A sweep whose cutoff is past the deadline pops the key: the window expired → the member leaves.
+ send_sweep(&tx, deadline + DAY_MS).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(changes.len(), 2, "an Entered (event) then a Left (sweep)");
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[1].status, MembershipStatus::Left);
+ assert_eq!(changes[1].cohort_id, 1);
+ assert_eq!(changes[1].person_id, alice.to_string());
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "a fully-expired single is deleted",
+ );
+}
+
+#[tokio::test]
+async fn durable_restart_rebuilds_the_eviction_queue_so_a_dormant_left_still_fires() {
+ // A member whose window expires during downtime — with no new event to reschedule her — must still
+ // emit `Left`. The first worker enters alice and schedules her eviction in its in-memory queue,
+ // then "crashes" (drop loses the queue, but cf_stage1 persists); a durable-restart worker re-seeds
+ // its queue from cf_stage1, so a later sweep still evicts her.
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let lsk = behavioral_lsk(&filters);
+ let catalog = catalog_of(filters);
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+
+ // First tenure: alice enters; her state + deadline persist to cf_stage1.
+ let sink1 = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx1, worker1) = spawn_worker(
+ &store,
+ catalog.clone(),
+ Arc::new(sink1.clone()),
+ tracker.clone(),
+ );
+ send_event(&tracker, &tx1, event_at(alice, ts, 0), 0).await;
+ drop(tx1);
+ worker1.join().await.unwrap();
+ assert_eq!(sink1.changes().len(), 1, "first tenure: just the Entered");
+ let deadline = state_at(&store, lsk, alice)
+ .expect("alice's state persisted across the crash")
+ .eviction_deadline()
+ .expect("a behavioral single has a finite eviction deadline");
+
+ // Second tenure: the durable-restart worker rebuilds its queue; alice sends no new event, yet the
+ // sweep past her deadline still evicts her.
+ let sink2 = CaptureSink::new();
+ let (tx2, worker2) =
+ spawn_worker_durable(&store, catalog, Arc::new(sink2.clone()), tracker.clone());
+ send_sweep(&tx2, deadline + DAY_MS).await;
+ drop(tx2);
+ worker2.join().await.unwrap();
+
+ let changes = sink2.changes();
+ assert_eq!(changes.len(), 1, "the rebuilt queue fires exactly one Left");
+ assert_eq!(changes[0].status, MembershipStatus::Left);
+ assert_eq!(changes[0].cohort_id, 1);
+ assert_eq!(changes[0].person_id, alice.to_string());
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "the fully-expired single is deleted by the sweep",
+ );
+}
+
+#[tokio::test]
+async fn without_durable_restart_a_dormant_member_is_not_re_evicted() {
+ // The contrast: without the rebuild the worker's queue starts empty, so the dormant member is never
+ // re-evaluated and no `Left` fires (the over-count the rebuild closes).
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let lsk = behavioral_lsk(&filters);
+ let catalog = catalog_of(filters);
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+
+ let sink1 = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx1, worker1) = spawn_worker(
+ &store,
+ catalog.clone(),
+ Arc::new(sink1.clone()),
+ tracker.clone(),
+ );
+ send_event(&tracker, &tx1, event_at(alice, ts, 0), 0).await;
+ drop(tx1);
+ worker1.join().await.unwrap();
+ let deadline = state_at(&store, lsk, alice)
+ .unwrap()
+ .eviction_deadline()
+ .unwrap();
+
+ // A plain (non-durable) restart worker: queue starts empty, so the sweep pops nothing.
+ let sink2 = CaptureSink::new();
+ let (tx2, worker2) = spawn_worker(&store, catalog, Arc::new(sink2.clone()), tracker.clone());
+ send_sweep(&tx2, deadline + DAY_MS).await;
+ drop(tx2);
+ worker2.join().await.unwrap();
+
+ assert!(
+ sink2.changes().is_empty(),
+ "without the rebuild the dormant member's Left never fires",
+ );
+ assert!(
+ state_at(&store, lsk, alice).is_some(),
+ "and her now-stale state lingers (the over-count)",
+ );
+}
+
+#[tokio::test]
+async fn event_then_sweep_in_one_batch_emits_entered_before_left() {
+ // Regression: event-path changes accumulate in the buffer and were produced *after* the message
+ // loop, while the Sweep arm produces inline mid-loop. So a single `[Event, Sweep]` batch where the
+ // event enters then the sweep immediately ages it out used to emit `Left` (inline) before `Entered`
+ // (post-loop) — out of state-commit order. A last-write-wins consumer of the shadow topic would then
+ // read "member" while RocksDB says "left", a false parity mismatch. The buffer is now flushed before
+ // the Sweep arm, so produce order matches commit order: Entered then Left.
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+ let deadline = event_ms + 7 * DAY_MS;
+
+ // One batch: the event enters and schedules eviction at `deadline`; the sweep's cutoff is already
+ // past it, so the same batch ages the key out. The fix must order Entered (event) before Left (sweep).
+ tracker.mark_dispatched(PARTITION_ID as i32, 1);
+ tx.send(vec![
+ ShuffleMessage::Event {
+ event: event_at(alice, ts, 0),
+ cse_offset: 0,
+ },
+ ShuffleMessage::Sweep {
+ due_before_ms: deadline + DAY_MS,
+ },
+ ])
+ .await
+ .unwrap();
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(
+ statuses,
+ vec![MembershipStatus::Entered, MembershipStatus::Left],
+ "within one batch the event's Entered must be produced before the sweep's inline Left",
+ );
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "the fully-expired single is deleted by the in-batch sweep",
+ );
+ assert_eq!(
+ tracker.committable_offsets().get(&(PARTITION_ID as i32)),
+ Some(&1),
+ "both produces acked, so the batch's offset advances past the event",
+ );
+}
+
+#[tokio::test]
+async fn sweep_full_expiry_delete_retracts_the_person_index_entry() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+ let deadline = event_ms + 7 * DAY_MS;
+
+ send_event(&tracker, &tx, event_at(alice, ts, 0), 0).await;
+ // Wait for the Entered to land, so the event's WriteBatch (cf_stage1 + the cf_person_index
+ // append) is durable before reading the index.
+ drain_until_changes(&sink, 1).await;
+ assert_eq!(
+ person_index_of(&store, alice),
+ vec![lsk],
+ "the entering event appends the leaf to cf_person_index",
+ );
+
+ // Sweep past the deadline: the single fully expires (Delete), retracting the index entry too.
+ send_sweep(&tx, deadline + DAY_MS).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "the expired single's cf_stage1 row is gone",
+ );
+ assert!(
+ person_index_of(&store, alice).is_empty(),
+ "the full-expiry delete leaves no stale leaf in cf_person_index",
+ );
+}
+
+#[tokio::test]
+async fn sweep_before_the_deadline_evicts_nothing() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+
+ send_event(&tracker, &tx, event_at(alice, ts, 0), 0).await;
+ // Cutoff one day *before* the deadline: nothing is due.
+ send_sweep(&tx, event_ms + 6 * DAY_MS).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(changes.len(), 1, "only the Entered, no premature Left");
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert!(
+ state_at(&store, lsk, alice).is_some(),
+ "state survives a sweep before its deadline",
+ );
+}
+
+#[tokio::test]
+async fn sweep_on_an_empty_queue_is_a_noop() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ // A sweep with no scheduled keys yet: nothing pops, nothing produces.
+ send_sweep(&tx, i64::MAX).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ assert!(
+ sink.changes().is_empty(),
+ "an empty-queue sweep emits nothing"
+ );
+ assert!(
+ !tracker
+ .committable_offsets()
+ .contains_key(&(PARTITION_ID as i32)),
+ "a sweep-only batch advances no offset",
+ );
+}
+
+#[tokio::test]
+async fn sweep_caps_evictions_per_pass_and_drains_the_remainder_next_tick() {
+ // A large wave of single-leaf members all come due at one cutoff. `handle_sweep` caps the pop loop
+ // at `MAX_SWEEP_KEYS_PER_PASS` (10_000, private to the worker), so the first pass evicts exactly the
+ // cap and the leftover keys stay scheduled, draining on a second sweep. This bounds the per-pass
+ // RocksDB read + produce + write batch so events do not starve behind one giant sweep.
+ const CAP: usize = 10_000; // mirrors worker::MAX_SWEEP_KEYS_PER_PASS
+ let total = CAP + 1;
+
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+ let deadline = event_ms + 7 * DAY_MS;
+
+ // One batch of `total` matching events (one distinct person each) schedules `total` evictions, all
+ // due at the same deadline. Batching avoids `total` per-event async round-trips through the channel.
+ tracker.mark_dispatched(PARTITION_ID as i32, total as i64);
+ let events: Vec<ShuffleMessage> = (0..total)
+ .map(|i| ShuffleMessage::Event {
+ event: event_at(person(i as u128 + 1), ts, i as i64),
+ cse_offset: i as i64,
+ })
+ .collect();
+ tx.send(events).await.unwrap();
+ drain_until_changes(&sink, total).await; // all `total` Entered have landed.
+
+ // First sweep past the deadline: every key is due, but only `CAP` are popped this pass.
+ send_sweep(&tx, deadline + DAY_MS).await;
+ drain_until_changes(&sink, total + CAP).await;
+ let lefts_after_first = sink
+ .changes()
+ .iter()
+ .filter(|c| c.status == MembershipStatus::Left)
+ .count();
+ assert_eq!(
+ lefts_after_first, CAP,
+ "the first pass evicts exactly the per-pass cap, not the whole wave",
+ );
+ // The one capped-out key is still scheduled, so its state still exists.
+ let leftover_person = person(total as u128); // offset total-1 ⇒ person `total`
+ assert!(
+ state_at(&store, lsk, leftover_person).is_some(),
+ "the over-cap key was not popped, so its state is untouched after the first pass",
+ );
+
+ // Second sweep at the same cutoff drains the leftover.
+ send_sweep(&tx, deadline + DAY_MS).await;
+ drain_until_changes(&sink, total + total).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let total_lefts = sink
+ .changes()
+ .iter()
+ .filter(|c| c.status == MembershipStatus::Left)
+ .count();
+ assert_eq!(
+ total_lefts, total,
+ "the remaining over-cap key evicts on the next tick: all members eventually leave",
+ );
+ assert!(
+ state_at(&store, lsk, leftover_person).is_none(),
+ "the leftover key is evicted (deleted) by the second sweep",
+ );
+}
+
+#[tokio::test]
+async fn single_does_not_evict_before_its_calendar_midnight_and_does_after() {
+ let lsk = behavioral_lsk(&build_team_filters_tz(vec![behavioral_leaf(7)], Kolkata));
+ let alice = person(1);
+ let bob = person(2);
+ // 00:30 and 23:30 Kolkata local on 2026-05-20, expressed in UTC (−05:30) → one Kolkata day.
+ let early = "2026-05-19 19:00:00.000000"; // 00:30 next-day Kolkata
+ let late = "2026-05-20 18:00:00.000000"; // 23:30 same-day Kolkata
+ let kolkata_day = day_idx_in_tz(clickhouse_timestamp_to_millis(early).unwrap(), Kolkata);
+ let midnight = start_of_day_ms_in_tz(kolkata_day + 7 + 1, Kolkata);
+ assert_ne!(
+ midnight,
+ start_of_day_ms_in_tz(kolkata_day + 7 + 1, UTC),
+ "the eviction boundary is the team-local (Kolkata) midnight, not UTC's",
+ );
+
+ // A sweep exactly at the shared midnight evicts neither edge person.
+ {
+ let (_dir, store) = temp_store();
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(build_team_filters_tz(vec![behavioral_leaf(7)], Kolkata)),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+ send_event(&tracker, &tx, event_at(alice, early, 0), 0).await;
+ send_event(&tracker, &tx, event_at(bob, late, 1), 1).await;
+ send_sweep(&tx, midnight).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 2,
+ "two Entered, no premature Left at the exact midnight",
+ );
+ assert!(changes
+ .iter()
+ .all(|c| c.status == MembershipStatus::Entered));
+ assert!(state_at(&store, lsk, alice).is_some());
+ assert!(state_at(&store, lsk, bob).is_some());
+ }
+
+ // One ms past the shared midnight evicts both edge persons in the same tick.
+ {
+ let (_dir, store) = temp_store();
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(build_team_filters_tz(vec![behavioral_leaf(7)], Kolkata)),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+ send_event(&tracker, &tx, event_at(alice, early, 0), 0).await;
+ send_event(&tracker, &tx, event_at(bob, late, 1), 1).await;
+ send_sweep(&tx, midnight + 1).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let lefts = sink
+ .changes()
+ .iter()
+ .filter(|c| c.status == MembershipStatus::Left)
+ .count();
+ assert_eq!(
+ lefts, 2,
+ "both edge persons leave in the same tick one ms past midnight",
+ );
+ assert!(state_at(&store, lsk, alice).is_none());
+ assert!(state_at(&store, lsk, bob).is_none());
+ }
+}
+
+#[tokio::test]
+async fn sweep_evicts_a_daily_member_on_full_window_expiry() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf_multiple(7, "gte", 3)]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let day = day_of(ts);
+
+ // Three same-day matches cross gte 3 → Entered on the third.
+ for offset in 0..3 {
+ send_event(&tracker, &tx, event_at(alice, ts, offset), offset).await;
+ }
+ // Slide the window well past the lone bucket → every bucket drains → Left + delete.
+ send_sweep(&tx, start_of_day_ms_in_tz(day + 9, UTC)).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 2,
+ "one Entered (3rd event) then one Left (sweep)"
+ );
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[1].status, MembershipStatus::Left);
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "an all-zero daily window is deleted",
+ );
+}
+
+#[tokio::test]
+async fn sweep_drops_the_oldest_daily_bucket_and_keeps_a_member() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf_multiple(7, "gte", 1)]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ // Matches four days apart, both inside a 7-day window. The first crosses gte 1 (Entered).
+ let first = "2026-05-20 10:00:00.000000";
+ let second = "2026-05-24 10:00:00.000000";
+ let day_first = day_of(first);
+ send_event(&tracker, &tx, event_at(alice, first, 0), 0).await;
+ send_event(&tracker, &tx, event_at(alice, second, 1), 1).await;
+
+ // Slide so only the first day's bucket leaves; the later bucket keeps the person a member.
+ send_sweep(&tx, start_of_day_ms_in_tz(day_first + 9, UTC)).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 1,
+ "Entered only — dropping the oldest bucket emits no Left"
+ );
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+
+ // The state survives with the later bucket's single match and a deadline pushed forward.
+ match state_at(&store, lsk, alice).expect("still a member") {
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ earliest_eviction_at_ms,
+ ..
+ } => {
+ assert_eq!(
+ buckets.iter().sum::<u32>(),
+ 1,
+ "only the later bucket remains"
+ );
+ let day_second = day_of(second);
+ assert_eq!(
+ earliest_eviction_at_ms,
+ start_of_day_ms_in_tz(day_second + 7 + 1, UTC),
+ "the deadline now tracks the surviving bucket",
+ );
+ }
+ other => panic!("expected daily buckets, got {other:?}"),
+ }
+}
+
+#[tokio::test]
+async fn sweep_emits_entered_when_a_daily_eq_count_falls_into_range() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf_multiple(7, "eq", 1)]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ // `eq 1` over a 7-day window, one match on day D and one on D+3. The event path emits Enter@D
+ // (count 1) then Leave@D+3 (count 2); as each day's bucket ages out, the falling count re-enters
+ // and finally leaves `eq 1`. The sweep must reproduce both directions, not only the Leave — this
+ // is the bidirectional flip a `gte`-only sweep would have dropped.
+ let alice = person(1);
+ let first = "2026-05-20 10:00:00.000000";
+ let second = "2026-05-23 10:00:00.000000";
+ let day = day_of(first);
+ send_event(&tracker, &tx, event_at(alice, first, 0), 0).await;
+ send_event(&tracker, &tx, event_at(alice, second, 1), 1).await;
+
+ // Sweep one day past the day-D bucket's leave boundary (start of D+8): count 2 → 1 → Entered.
+ send_sweep(&tx, start_of_day_ms_in_tz(day + 9, UTC)).await;
+
+ // Barrier on the Enter+Leave (events) + Enter (sweep): the slide advanced the window and
+ // rescheduled to the surviving D+3 bucket's leave boundary (start of D+11).
+ drain_until_changes(&sink, 3).await;
+ match state_at(&store, lsk, alice).expect("still a member after the slide into eq 1") {
+ Stage1State::BehavioralDailyBuckets {
+ buckets,
+ earliest_eviction_at_ms,
+ ..
+ } => {
+ assert_eq!(
+ buckets.iter().sum::<u32>(),
+ 1,
+ "only the D+3 bucket remains"
+ );
+ assert_eq!(
+ earliest_eviction_at_ms,
+ start_of_day_ms_in_tz(day + 11, UTC),
+ "rescheduled to the surviving bucket's leave boundary",
+ );
+ }
+ other => panic!("expected daily buckets, got {other:?}"),
+ }
+
+ // A later sweep past the D+3 bucket's boundary (start of D+12): count 1 → 0 → Left + delete.
+ send_sweep(&tx, start_of_day_ms_in_tz(day + 12, UTC)).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(
+ statuses,
+ vec![
+ MembershipStatus::Entered, // event @ D — count 1
+ MembershipStatus::Left, // event @ D+3 — count 2
+ MembershipStatus::Entered, // sweep — day-D bucket leaves, count 1
+ MembershipStatus::Left, // sweep — day-(D+3) bucket leaves, count 0
+ ],
+ "the sweep reproduces the event path's bidirectional eq-1 flips, not an orphan Left",
+ );
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "the fully-drained window is deleted",
+ );
+}
+
+#[tokio::test]
+async fn sweep_evicts_a_compressed_member_on_full_window_expiry() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf_multiple(
+ COMPRESSED_WINDOW_DAYS,
+ "gte",
+ 3,
+ )]);
+ let lsk = behavioral_lsk(&filters);
+ assert_eq!(
+ filters.by_lsk[&lsk].variant,
+ StateVariant::BehavioralCompressedHistory,
+ );
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let day = day_of(ts);
+
+ // Three same-day matches cross gte 3 → Entered on the third.
+ for offset in 0..3 {
+ send_event(&tracker, &tx, event_at(alice, ts, offset), offset).await;
+ }
+ // Slide the window well past the lone entry → it drains → Left + delete.
+ send_sweep(
+ &tx,
+ start_of_day_ms_in_tz(day + COMPRESSED_WINDOW_DAYS as i32 + 2, UTC),
+ )
+ .await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 2,
+ "one Entered (3rd event) then one Left (sweep)"
+ );
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[1].status, MembershipStatus::Left);
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "a fully-drained compressed window is deleted",
+ );
+}
+
+#[tokio::test]
+async fn sweep_drops_the_oldest_compressed_day_and_keeps_a_member() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf_multiple(
+ COMPRESSED_WINDOW_DAYS,
+ "gte",
+ 1,
+ )]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ // Matches 100 days apart, both inside a 365-day window. The first crosses gte 1 (Entered).
+ let first = "2026-05-20 10:00:00.000000";
+ let second = "2026-08-28 10:00:00.000000";
+ let day_first = day_of(first);
+ let day_second = day_of(second);
+ send_event(&tracker, &tx, event_at(alice, first, 0), 0).await;
+ send_event(&tracker, &tx, event_at(alice, second, 1), 1).await;
+
+ // Slide so only the first day's entry leaves; the later entry keeps the person a member.
+ send_sweep(
+ &tx,
+ start_of_day_ms_in_tz(day_first + COMPRESSED_WINDOW_DAYS as i32 + 2, UTC),
+ )
+ .await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 1,
+ "Entered only — dropping the oldest day emits no Left"
+ );
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+
+ // The state survives with the later day's single match and a deadline pushed forward.
+ match state_at(&store, lsk, alice).expect("still a member") {
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ earliest_eviction_at_ms,
+ ..
+ } => {
+ assert_eq!(
+ entries,
+ vec![(day_second, 1)],
+ "only the later day's entry remains",
+ );
+ assert_eq!(
+ earliest_eviction_at_ms,
+ start_of_day_ms_in_tz(day_second + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC),
+ "the deadline now tracks the surviving entry",
+ );
+ }
+ other => panic!("expected compressed history, got {other:?}"),
+ }
+}
+
+#[tokio::test]
+async fn sweep_emits_entered_when_a_compressed_eq_count_falls_into_range() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf_multiple(
+ COMPRESSED_WINDOW_DAYS,
+ "eq",
+ 1,
+ )]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ // `eq 1` over a 365-day window, one match on day D and one on D+100. The event path emits Enter@D
+ // (count 1) then Leave@D+100 (count 2); as each day's entry ages out, the falling count re-enters
+ // and finally leaves `eq 1`. The sweep must reproduce both directions — the bidirectional flip a
+ // `gte`-only sweep would have dropped.
+ let alice = person(1);
+ let first = "2026-05-20 10:00:00.000000";
+ let second = "2026-08-28 10:00:00.000000";
+ let day_first = day_of(first);
+ let day_second = day_of(second);
+ send_event(&tracker, &tx, event_at(alice, first, 0), 0).await;
+ send_event(&tracker, &tx, event_at(alice, second, 1), 1).await;
+
+ // Sweep past the day-D entry's leave boundary: count 2 → 1 → Entered, rescheduled to the surviving
+ // D+100 entry's leave boundary.
+ send_sweep(
+ &tx,
+ start_of_day_ms_in_tz(day_first + COMPRESSED_WINDOW_DAYS as i32 + 2, UTC),
+ )
+ .await;
+
+ drain_until_changes(&sink, 3).await;
+ match state_at(&store, lsk, alice).expect("still a member after the slide into eq 1") {
+ Stage1State::BehavioralCompressedHistory {
+ entries,
+ earliest_eviction_at_ms,
+ ..
+ } => {
+ assert_eq!(
+ entries,
+ vec![(day_second, 1)],
+ "only the D+100 entry remains"
+ );
+ assert_eq!(
+ earliest_eviction_at_ms,
+ start_of_day_ms_in_tz(day_second + COMPRESSED_WINDOW_DAYS as i32 + 1, UTC),
+ "rescheduled to the surviving entry's leave boundary",
+ );
+ }
+ other => panic!("expected compressed history, got {other:?}"),
+ }
+
+ // A later sweep past the D+100 entry's boundary: count 1 → 0 → Left + delete.
+ send_sweep(
+ &tx,
+ start_of_day_ms_in_tz(day_second + COMPRESSED_WINDOW_DAYS as i32 + 2, UTC),
+ )
+ .await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(
+ statuses,
+ vec![
+ MembershipStatus::Entered, // event @ D — count 1
+ MembershipStatus::Left, // event @ D+100 — count 2
+ MembershipStatus::Entered, // sweep — day-D entry leaves, count 1
+ MembershipStatus::Left, // sweep — day-(D+100) entry leaves, count 0
+ ],
+ "the sweep reproduces the event path's bidirectional eq-1 flips for the compressed variant",
+ );
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "the fully-drained compressed window is deleted",
+ );
+}
+
+/// A sink that fails the `fail_call`-th produce (1-based).
+#[derive(Clone)]
+struct FailNthSink {
+ changes: Arc<Mutex<Vec<CohortMembershipChange>>>,
+ calls: Arc<AtomicUsize>,
+ fail_call: usize,
+}
+
+impl FailNthSink {
+ fn new(fail_call: usize) -> Self {
+ Self {
+ changes: Arc::default(),
+ calls: Arc::default(),
+ fail_call,
+ }
+ }
+
+ fn changes(&self) -> Vec<CohortMembershipChange> {
+ self.changes.lock().unwrap().clone()
+ }
+
+ fn calls(&self) -> usize {
+ self.calls.load(Ordering::SeqCst)
+ }
+}
+
+async fn drain_until_calls(sink: &FailNthSink, count: usize) {
+ for _ in 0..10_000 {
+ if sink.calls() >= count {
+ return;
+ }
+ tokio::task::yield_now().await;
+ }
+ panic!("worker did not reach {count} produce calls");
+}
+
+#[async_trait]
+impl MembershipSink for FailNthSink {
+ async fn produce(
+ &self,
+ changes: Vec<CohortMembershipChange>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ let call = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
+ if call == self.fail_call {
+ return changes
+ .iter()
+ .map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
+ .collect();
+ }
+ let acks = changes.iter().map(|_| Ok(())).collect();
+ self.changes.lock().unwrap().extend(changes);
+ acks
+ }
+}
+
+#[tokio::test]
+async fn sweep_produce_failure_reschedules_and_a_later_sweep_retries() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = FailNthSink::new(2);
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+ let cutoff = event_ms + 8 * DAY_MS;
+
+ send_event(&tracker, &tx, event_at(alice, ts, 0), 0).await;
+ // First sweep: the Left produce fails → the key is rescheduled, the state is NOT deleted.
+ send_sweep(&tx, cutoff).await;
+ // Second sweep at the same cutoff: the rescheduled key re-pops and the retry succeeds.
+ send_sweep(&tx, cutoff).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 2,
+ "Entered + the retried Left (the failed flush recorded nothing)",
+ );
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[1].status, MembershipStatus::Left);
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "the retry deleted the state once its Left was durable",
+ );
+}
+
+#[tokio::test]
+async fn sweep_left_recomposes_a_two_leaf_cohort() {
+ let (_dir, store) = temp_store();
+ // A composable cohort: AND(behavioral 7d, person email). Neither leaf is owned by a single-leaf
+ // cohort, so every change below comes from Stage 2 composition.
+ let filters = build_team_filters(vec![behavioral_leaf(7), person_leaf()]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+
+ // One matching event flips both leaves → the cohort composes an Entered.
+ send_event(&tracker, &tx, person_event_at(alice, ts, 0), 0).await;
+ // The sweep expires the behavioral window; its time-driven Left must recompose the cohort even
+ // though the sibling person leaf (never time-evicted) is still true.
+ send_sweep(&tx, event_ms + 8 * DAY_MS).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let emitted: Vec<(i32, MembershipStatus)> = sink
+ .changes()
+ .iter()
+ .map(|change| (change.cohort_id, change.status))
+ .collect();
+ assert_eq!(
+ emitted,
+ vec![(1, MembershipStatus::Entered), (1, MembershipStatus::Left)],
+ "the sweep's leaf Left recomposes the two-leaf cohort to a cohort Left",
+ );
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "the expired behavioral leaf was deleted before compose read it",
+ );
+ assert_eq!(
+ stage2_bit(&store, 1, alice),
+ Some(false),
+ "a composed Left writes the false bit, it does not delete the row",
+ );
+}
+
+#[tokio::test]
+async fn sweep_entered_recomposes_via_daily_slide() {
+ let (_dir, store) = temp_store();
+ // AND(daily eq 1 over 7d, person email): the behavioral leaf is a member only at exactly one
+ // match in the window.
+ let filters = build_team_filters(vec![behavioral_leaf_multiple(7, "eq", 1), person_leaf()]);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let first = "2026-05-20 10:00:00.000000";
+ let second = "2026-05-23 10:00:00.000000";
+ let day = day_of(first);
+
+ // Count 1 @ D satisfies eq 1 (cohort Entered); count 2 @ D+3 fails it (cohort Left).
+ send_event(&tracker, &tx, person_event_at(alice, first, 0), 0).await;
+ send_event(&tracker, &tx, person_event_at(alice, second, 1), 1).await;
+ // The slide drops the day-D bucket: count 2 → 1 re-enters eq 1, so the sweep's *Entered* must
+ // drive a recompose exactly like a Left does.
+ send_sweep(&tx, start_of_day_ms_in_tz(day + 9, UTC)).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(
+ statuses,
+ vec![
+ MembershipStatus::Entered, // event @ D — count 1, the AND is satisfied
+ MembershipStatus::Left, // event @ D+3 — count 2 fails eq 1
+ MembershipStatus::Entered, // sweep — the day-D bucket leaves, count back to 1
+ ],
+ "a sweep Entered (daily slide into range) recomposes the cohort, not only a Left",
+ );
+ assert_eq!(stage2_bit(&store, 1, alice), Some(true));
+}
+
+#[tokio::test]
+async fn sweep_dormant_person_left_is_emitted() {
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7), person_leaf()]);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ // Alice enters and goes dormant — no event of hers ever drives a recompose again. Bob stays
+ // active, superseding his own deadline past the sweep. Only the sweep can emit alice's Left
+ // (the staleness invariant for a churned-then-dormant person).
+ let alice = person(1);
+ let bob = person(2);
+ let t0 = "2026-05-20 10:00:00.000000";
+ let t0_ms = clickhouse_timestamp_to_millis(t0).unwrap();
+ send_event(&tracker, &tx, person_event_at(alice, t0, 0), 0).await;
+ send_event(&tracker, &tx, person_event_at(bob, t0, 1), 1).await;
+ send_event(
+ &tracker,
+ &tx,
+ person_event_at(bob, "2026-05-26 10:00:00.000000", 2),
+ 2,
+ )
+ .await;
+
+ send_sweep(&tx, t0_ms + 8 * DAY_MS).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let changes = sink.changes();
+ let lefts: Vec<_> = changes
+ .iter()
+ .filter(|change| change.status == MembershipStatus::Left)
+ .collect();
+ assert_eq!(lefts.len(), 1, "the sweep alone drives exactly one Left");
+ assert_eq!(lefts[0].person_id, alice.to_string());
+ assert_eq!(lefts[0].cohort_id, 1);
+ assert_eq!(stage2_bit(&store, 1, alice), Some(false));
+ assert_eq!(
+ stage2_bit(&store, 1, bob),
+ Some(true),
+ "the still-active person is untouched by the dormant person's eviction",
+ );
+}
+
+#[tokio::test]
+async fn sweep_recompose_and_single_leaf_share_a_leaf() {
+ let (_dir, store) = temp_store();
+ // Cohort 1 ANDs the behavioral leaf with a person leaf (composable); cohort 2 is the bare
+ // behavioral leaf (single-leaf), sharing cohort 1's LSK. One eviction must emit both cohorts'
+ // Lefts — cohort 2 via map_transition (first produce), cohort 1 via compose (second produce) —
+ // disjoint cohort ids, each exactly once.
+ let filters = build_team_filters_multi(vec![
+ (CohortId(1), vec![behavioral_leaf(7), person_leaf()]),
+ (CohortId(2), vec![behavioral_leaf(7)]),
+ ]);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+
+ send_event(&tracker, &tx, person_event_at(alice, ts, 0), 0).await;
+ send_sweep(&tx, event_ms + 8 * DAY_MS).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let by_status = |status: MembershipStatus| -> Vec<i32> {
+ let mut cohorts: Vec<i32> = sink
+ .changes()
+ .iter()
+ .filter(|change| change.status == status)
+ .map(|change| change.cohort_id)
+ .collect();
+ cohorts.sort_unstable();
+ cohorts
+ };
+ assert_eq!(
+ by_status(MembershipStatus::Entered),
+ vec![1, 2],
+ "the event enters the single-leaf cohort and composes the two-leaf cohort",
+ );
+ assert_eq!(
+ by_status(MembershipStatus::Left),
+ vec![1, 2],
+ "one eviction fans out to the single-leaf Left and the composed Left, each exactly once",
+ );
+ assert_eq!(stage2_bit(&store, 1, alice), Some(false));
+}
+
+#[tokio::test]
+async fn sweep_two_leaves_same_cohort_one_tick() {
+ let (_dir, store) = temp_store();
+ // AND of a 7d and a 30d performed_event on one matcher: a single event enters both leaves, and
+ // a far-future sweep pops both windows in one tick — two transitions for one (cohort, person).
+ let filters = build_team_filters(vec![behavioral_leaf(7), behavioral_leaf(30)]);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+
+ send_event(&tracker, &tx, event_at(alice, ts, 0), 0).await;
+ // Both deadlines (event+7d, event+30d) are past the cutoff: both leaves evict in one tick.
+ send_sweep(&tx, event_ms + 31 * DAY_MS).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(
+ statuses,
+ vec![MembershipStatus::Entered, MembershipStatus::Left],
+ "two same-tick leaf evictions of one cohort dedup to a single composed Left",
+ );
+ assert_eq!(stage2_bit(&store, 1, alice), Some(false));
+}
+
+#[tokio::test]
+async fn sweep_compose_after_delete_reads_false() {
+ let (_dir, store) = temp_store();
+ // AND(daily gte 1 over 7d, person email): a full-window drain takes the daily leaf through
+ // `EvictionAction::Delete`, so compose must read the *deleted* row (a non-member), not the
+ // pre-eviction state — pinning the run-after-the-Stage-1-write ordering.
+ let filters = build_team_filters(vec![behavioral_leaf_multiple(7, "gte", 1), person_leaf()]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let day = day_of(ts);
+
+ send_event(&tracker, &tx, person_event_at(alice, ts, 0), 0).await;
+ // Slide well past the lone bucket: every bucket drains → Delete + leaf Left.
+ send_sweep(&tx, start_of_day_ms_in_tz(day + 9, UTC)).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(
+ statuses,
+ vec![MembershipStatus::Entered, MembershipStatus::Left],
+ "compose reads the deleted leaf as a non-member and emits the cohort Left",
+ );
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "the fully-drained daily window was deleted before compose read it",
+ );
+ assert_eq!(stage2_bit(&store, 1, alice), Some(false));
+}
+
+#[tokio::test]
+async fn sweep_compose_produce_failure_does_not_corrupt() {
+ let (_dir, store) = temp_store();
+ // Composable-only cohort, so the sweep's single-leaf produce is empty and never calls the sink:
+ // call 1 is the event's composed Entered, call 2 is the sweep's compose produce.
+ let filters = build_team_filters(vec![behavioral_leaf(7), person_leaf()]);
+ let lsk = behavioral_lsk(&filters);
+ let sink = FailNthSink::new(2);
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+
+ send_event(&tracker, &tx, person_event_at(alice, ts, 0), 0).await;
+ send_sweep(&tx, event_ms + 8 * DAY_MS).await;
+
+ drain_until_calls(&sink, 2).await;
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "the Stage 1 eviction committed before the failed produce",
+ );
+ assert_eq!(
+ stage2_bit(&store, 1, alice),
+ Some(false),
+ "the cf_stage2 bit committed before the failed produce",
+ );
+ assert_eq!(
+ sink.changes().len(),
+ 1,
+ "only the initial Entered was recorded — the composed Left is lost (at-most-once)",
+ );
+
+ // A follow-up matching event re-creates the behavioral leaf and recomposes an Entered.
+ send_event(
+ &tracker,
+ &tx,
+ person_event_at(alice, "2026-05-29 10:00:00.000000", 1),
+ 1,
+ )
+ .await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(
+ statuses,
+ vec![MembershipStatus::Entered, MembershipStatus::Entered],
+ "the dropped Left never reaches the sink; the next event self-heals the membership",
+ );
+ assert_eq!(stage2_bit(&store, 1, alice), Some(true));
+}
+
+#[test]
+fn relative_window_schedules_an_eviction_but_an_explicit_window_does_not() {
+ let (_dir, store) = temp_store();
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+
+ let relative = build_team_filters(vec![behavioral_leaf(7)]);
+ let lsk = behavioral_lsk(&relative);
+ let out = process_event(PARTITION_ID, &store, &relative, &event_at(alice, ts, 0)).unwrap();
+ assert_eq!(out.transitions.len(), 1, "the match enters");
+ assert_eq!(
+ out.schedules,
+ vec![(
+ Stage1Key {
+ partition_id: PARTITION_ID,
+ team_id: TEAM as u64,
+ leaf_state_key: lsk,
+ person_id: alice,
+ },
+ start_of_day_ms_in_tz(day_of(ts) + 7 + 1, UTC),
+ )],
+ "a whole-day single schedules at the calendar midnight after day + window",
+ );
+
+ // An explicit date range is permanent membership → never scheduled (deadline i64::MAX).
+ let (_dir2, store2) = temp_store();
+ let explicit = build_team_filters(vec![explicit_behavioral_leaf()]);
+ let out = process_event(
+ PARTITION_ID,
+ &store2,
+ &explicit,
+ &event_at(person(2), ts, 0),
+ )
+ .unwrap();
+ assert_eq!(out.transitions.len(), 1, "the match still enters");
+ assert!(
+ out.schedules.is_empty(),
+ "an explicit-window single is never scheduled for eviction",
+ );
+}
+
+#[test]
+fn explicit_range_matches_at_day_granularity_inclusive_on_both_ends() {
+ // The explicit leaf spans 2026-01-01 .. 2026-12-31 (UTC). The match is at **day** granularity,
+ // inclusive on both ends, mirroring the oracle's `date >= toDate(from) AND date <= toDate(to)`.
+ // A boundary-day event on either end is a member; a day past either end is not.
+ let cases = [
+ (
+ "2026-01-01 00:00:00.000000",
+ true,
+ "first instant of the from-day enters",
+ ),
+ (
+ "2026-01-01 23:59:59.000000",
+ true,
+ "last instant of the from-day still enters",
+ ),
+ (
+ "2026-12-31 23:59:59.000000",
+ true,
+ "last instant of the to-day enters",
+ ),
+ ("2026-06-15 12:00:00.000000", true, "mid-range enters"),
+ (
+ "2025-12-31 23:59:59.000000",
+ false,
+ "the day before from is out of range",
+ ),
+ (
+ "2027-01-01 00:00:00.000000",
+ false,
+ "the day after to is out of range",
+ ),
+ ];
+ for (ts, expect_member, why) in cases {
+ let (_dir, store) = temp_store();
+ let explicit = build_team_filters(vec![explicit_behavioral_leaf()]);
+ let lsk = behavioral_lsk(&explicit);
+ let alice = person(1);
+ let out = process_event(PARTITION_ID, &store, &explicit, &event_at(alice, ts, 0)).unwrap();
+
+ if expect_member {
+ assert_eq!(out.transitions.len(), 1, "{why}");
+ assert!(
+ state_at(&store, lsk, alice).is_some(),
+ "an in-range match writes state: {why}",
+ );
+ assert!(
+ out.schedules.is_empty(),
+ "an in-range explicit match is permanent, never scheduled: {why}",
+ );
+ } else {
+ assert!(out.transitions.is_empty(), "{why}");
+ assert!(out.schedules.is_empty(), "{why}");
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "an out-of-range event writes no state: {why}",
+ );
+ }
+ }
+}
+
+#[test]
+fn explicit_range_lower_bound_is_the_literal_calendar_day_under_a_negative_offset_team() {
+ // Bug 1 regression. Team America/New_York (UTC−4 in May, EDT), absolute range 2026-05-01..2026-05-31
+ // emitted as bare dates (the date picker's date-only shape). The oracle treats `toDate('2026-05-01')`
+ // as the literal calendar date 2026-05-01, tz-invariant; an event at 2026-04-30 22:00 *New York local*
+ // (= 2026-05-01 02:00 UTC) is BEFORE `from` in local time and is NOT a member. The pre-fix code parsed
+ // the bare date as UTC midnight then re-projected it into New_York (= 2026-04-30 local), shifting the
+ // whole window one calendar day earlier and wrongly admitting this event.
+ //
+ // Timestamps are passed as their UTC equivalents (the ClickHouse form is read as UTC); the comment on
+ // each line is the New-York-local wall clock.
+ let cases = [
+ (
+ "2026-05-01 02:00:00.000000", // 2026-04-30 22:00 NY — just before `from` locally
+ false,
+ "the local day before from (2026-04-30 NY) is out of range",
+ ),
+ (
+ "2026-05-01 14:00:00.000000", // 2026-05-01 10:00 NY — the from day, locally
+ true,
+ "an event on the from day (2026-05-01 NY) enters",
+ ),
+ (
+ "2026-06-01 03:00:00.000000", // 2026-05-31 23:00 NY — the to day, locally
+ true,
+ "an event on the to day (2026-05-31 NY) enters",
+ ),
+ (
+ "2026-06-01 14:00:00.000000", // 2026-06-01 10:00 NY — the day after to, locally
+ false,
+ "the local day after to (2026-06-01 NY) is out of range",
+ ),
+ ];
+ for (ts, expect_member, why) in cases {
+ let (_dir, store) = temp_store();
+ let explicit = build_team_filters_tz(
+ vec![explicit_behavioral_leaf_range("2026-05-01", "2026-05-31")],
+ New_York,
+ );
+ let lsk = behavioral_lsk(&explicit);
+ let alice = person(1);
+ let out = process_event(PARTITION_ID, &store, &explicit, &event_at(alice, ts, 0)).unwrap();
+
+ if expect_member {
+ assert_eq!(out.transitions.len(), 1, "{why}");
+ assert!(state_at(&store, lsk, alice).is_some(), "{why}");
+ } else {
+ assert!(out.transitions.is_empty(), "{why}");
+ assert!(
+ state_at(&store, lsk, alice).is_none(),
+ "an out-of-range event writes no state: {why}",
+ );
+ }
+ }
+}
+
+#[test]
+fn explicit_range_upper_bound_from_the_ui_wire_format_bounds_the_range() {
+ // Bug 2 regression. The cohort date picker emits the upper bound as
+ // `dayjs(...).format('YYYY-MM-DDTHH:mm:ss')` — T-separated, no offset. The pre-fix parser accepted
+ // neither that shape nor coerced it, so it silently dropped the upper bound and made every event
+ // after the intended end a permanent member. With the bound parsed, an event after the to-day is
+ // correctly excluded.
+ let leaf = explicit_behavioral_leaf_range("2026-01-01", "2026-12-31T00:00:00");
+
+ // On the to-day → member.
+ let (_dir, store) = temp_store();
+ let explicit = build_team_filters(vec![leaf.clone()]);
+ let lsk = behavioral_lsk(&explicit);
+ let alice = person(1);
+ let on_to_day = process_event(
+ PARTITION_ID,
+ &store,
+ &explicit,
+ &event_at(alice, "2026-12-31 12:00:00.000000", 0),
+ )
+ .unwrap();
+ assert_eq!(
+ on_to_day.transitions.len(),
+ 1,
+ "an event on the to-day enters"
+ );
+
+ // The day after the to-day → NOT a member (the bound is honored, not dropped).
+ let (_dir2, store2) = temp_store();
+ let explicit2 = build_team_filters(vec![leaf]);
+ let bob = person(2);
+ let after_to = process_event(
+ PARTITION_ID,
+ &store2,
+ &explicit2,
+ &event_at(bob, "2027-01-01 00:00:00.000000", 0),
+ )
+ .unwrap();
+ assert!(
+ after_to.transitions.is_empty() && state_at(&store2, lsk, bob).is_none(),
+ "an event after the UI-emitted upper bound is excluded, not a permanent member",
+ );
+}
+
+#[test]
+fn explicit_range_with_an_unparseable_bound_skips_the_leaf_entirely() {
+ // A present-but-unparseable bound must skip the leaf (no realtime state at all), NOT degrade to an
+ // open-ended range. With the leaf skipped there is no behavioral condition, so even an in-window
+ // event produces no transition and no state.
+ let (_dir, store) = temp_store();
+ let explicit = build_team_filters(vec![explicit_behavioral_leaf_range(
+ "2026-01-01",
+ "garbage",
+ )]);
+ assert!(
+ explicit.behavioral_conditions.is_empty(),
+ "an unparseable bound leaves the leaf with no behavioral condition",
+ );
+ let alice = person(1);
+ let out = process_event(
+ PARTITION_ID,
+ &store,
+ &explicit,
+ &event_at(alice, "2026-06-15 12:00:00.000000", 0),
+ )
+ .unwrap();
+ assert!(
+ out.transitions.is_empty() && out.schedules.is_empty(),
+ "a skipped leaf emits nothing — not an open-ended permanent membership",
+ );
+}
+
+#[tokio::test]
+async fn dispatch_sweeper_routes_an_end_to_end_eviction() {
+ use cohort_stream_processor::consumers::ConsumedEvent;
+ use cohort_stream_processor::sweep::{DispatchSweeper, Sweeper};
+
+ let (_dir, store) = temp_store();
+ let filters = build_team_filters(vec![behavioral_leaf(7)]);
+ let sink = Arc::new(CaptureSink::new());
+ let dispatcher = Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ store.clone(),
+ catalog_of(filters),
+ sink.clone(),
+ MergeWorkerDeps::capture(),
+ ));
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+
+ // Own the partition and dispatch a matching event: spawns the worker and schedules the eviction.
+ dispatcher.assign_partition(0);
+ dispatcher
+ .dispatch(vec![ConsumedEvent {
+ event: event_at(alice, ts, 0),
+ partition: 0,
+ offset: 0,
+ }])
+ .await;
+
+ // A sweeper whose clock is past `event + window + margin` routes a Sweep that evicts the member.
+ let margin_ms = 300_000_i64;
+ let now = event_ms + 8 * DAY_MS + margin_ms;
+ let sweeper = DispatchSweeper::with_clock(dispatcher.clone(), margin_ms, Arc::new(move || now));
+ sweeper.run_once().await;
+
+ // Drain the worker through a revoke so it processes the queued event then the routed sweep before
+ // we assert. The `Left` can only come from the sweep evicting the member (a revoke alone never
+ // emits one), so its presence proves the routed `Sweep` reached the worker and fired.
+ dispatcher.revoke_partition_sync(0);
+ dispatcher.revoke_partition_drain(0).await;
+
+ let changes = sink.changes();
+ assert_eq!(
+ changes.len(),
+ 2,
+ "Entered (dispatch) then Left (routed sweep)"
+ );
+ assert_eq!(changes[0].status, MembershipStatus::Entered);
+ assert_eq!(changes[1].status, MembershipStatus::Left);
+}
+
+#[tokio::test]
+async fn sweep_expiry_of_negated_leaf_emits_entered() {
+ // AND(A 7d, ¬B 1d): one $pageview matches both → non-member (A=true, ¬B=false).
+ // Sweep expires B's 1-day window while A's 7-day survives → AND(true, ¬absent=true) → Entered.
+ let (_dir, store) = temp_store();
+
+ let a = behavioral_leaf(7);
+ let mut neg_b = behavioral_leaf(1);
+ neg_b
+ .as_object_mut()
+ .unwrap()
+ .insert("negation".to_string(), json!(true));
+
+ let filters = build_team_filters(vec![a, neg_b]);
+ let lsks = &filters.by_condition_to_lsk[&BEHAVIORAL_HASH];
+ assert_eq!(lsks.len(), 2);
+ let sink = CaptureSink::new();
+ let tracker = Arc::new(OffsetTracker::new());
+ let (tx, worker) = spawn_worker(
+ &store,
+ catalog_of(filters),
+ Arc::new(sink.clone()),
+ tracker.clone(),
+ );
+
+ let alice = person(1);
+ let ts = "2026-05-20 10:00:00.000000";
+ let event_ms = clickhouse_timestamp_to_millis(ts).unwrap();
+
+ send_event(&tracker, &tx, event_at(alice, ts, 0), 0).await;
+ send_sweep(&tx, event_ms + 2 * DAY_MS).await;
+ drop(tx);
+ worker.join().await.unwrap();
+
+ let statuses: Vec<MembershipStatus> =
+ sink.changes().iter().map(|change| change.status).collect();
+ assert_eq!(statuses, vec![MembershipStatus::Entered]);
+ assert_eq!(stage2_bit(&store, 1, alice), Some(true));
+}
+
+// Pin that the worker's per-partition state types line up with what the sweep evicts (a compile-time
+// reminder if the variant enum is reshaped).
+#[test]
+fn state_variants_are_exhaustive() {
+ for variant in [
+ StateVariant::BehavioralSingle,
+ StateVariant::BehavioralDailyBuckets,
+ StateVariant::BehavioralCompressedHistory,
+ StateVariant::PersonProperty,
+ ] {
+ assert!(!variant.as_str().is_empty());
+ }
+}
diff --git a/rust/common/hogvm/Cargo.toml b/rust/common/hogvm/Cargo.toml
index 5ecc5b9cf343..0cd0ad832b14 100644
--- a/rust/common/hogvm/Cargo.toml
+++ b/rust/common/hogvm/Cargo.toml
@@ -12,3 +12,5 @@ serde_json.workspace = true
thiserror.workspace = true
regex.workspace = true
rand.workspace = true
+chrono.workspace = true
+chrono-tz.workspace = true
diff --git a/rust/common/hogvm/src/bin/run.rs b/rust/common/hogvm/src/bin/run.rs
new file mode 100644
index 000000000000..35d60561dcf1
--- /dev/null
+++ b/rust/common/hogvm/src/bin/run.rs
@@ -0,0 +1,46 @@
+//! Minimal HogVM bytecode runner. Emits the `{"result", "error"}` JSON shape that the Python
+//! (`common/hogvm/python/execute.py`) and Node runners also emit, so output can be diffed across runtimes.
+
+use hogvm::{sync_execute, ExecutionContext, Program};
+use serde_json::{json, Value};
+
+pub fn main() {
+ // nosemgrep: rust.lang.security.args.args
+ let mut args = std::env::args().skip(1);
+ let bytecode_path = args
+ .next()
+ .expect("Usage: run <bytecode.hoge> [globals.json]");
+ let globals_path = args.next();
+
+ let bytecode = read_json_array(&bytecode_path);
+ let globals = globals_path
+ .map(|path| read_json(&path))
+ .unwrap_or_else(|| json!({}));
+
+ let output = match execute(bytecode, globals) {
+ Ok(result) => json!({ "result": result, "error": Value::Null }),
+ Err(message) => json!({ "result": Value::Null, "error": message }),
+ };
+ println!("{output}");
+}
+
+/// Surface construction and execution failures as the `error` string — a malformed program is a
+/// divergence to observe, not a crash.
+fn execute(bytecode: Vec<Value>, globals: Value) -> Result<Value, String> {
+ let program = Program::new(bytecode).map_err(|e| e.to_string())?;
+ let context = ExecutionContext::with_defaults(program).with_globals(globals);
+ sync_execute(&context, false).map_err(|failure| failure.error.to_string())
+}
+
+fn read_json_array(path: &str) -> Vec<Value> {
+ let data = std::fs::read_to_string(path)
+ .unwrap_or_else(|e| panic!("Failed to read bytecode file {path}: {e}"));
+ serde_json::from_str(&data)
+ .unwrap_or_else(|e| panic!("Failed to parse {path} as a JSON bytecode array: {e}"))
+}
+
+fn read_json(path: &str) -> Value {
+ let data = std::fs::read_to_string(path)
+ .unwrap_or_else(|e| panic!("Failed to read globals file {path}: {e}"));
+ serde_json::from_str(&data).unwrap_or_else(|e| panic!("Failed to parse {path} as JSON: {e}"))
+}
diff --git a/rust/common/hogvm/src/context.rs b/rust/common/hogvm/src/context.rs
index d2586270a540..63f547204c47 100644
--- a/rust/common/hogvm/src/context.rs
+++ b/rust/common/hogvm/src/context.rs
@@ -18,6 +18,12 @@ pub struct ExecutionContext {
pub max_stack_depth: usize,
pub max_heap_size: usize,
pub max_steps: usize,
+ /// Opt-in comparison semantics. `false` (the default) is the legacy/reference behavior shared by
+ /// every existing consumer (e.g. `cymbal`): ordering ops require numeric operands and `Eq`
+ /// compares temporals structurally. `true` makes ordering coerce across types and order temporals
+ /// by epoch, and `Eq` compare two temporals by epoch — the ClickHouse/Python-TS-aligned semantics
+ /// the realtime-cohort evaluator needs. Set via [`ExecutionContext::with_coercing_comparisons`].
+ pub(crate) coerce_comparisons: bool,
native_fns: HashMap<String, NativeFunction>,
symbol_table: HashMap<Symbol, ExportedFunction>, // Flattened symbol table of all imported hog modules
}
@@ -44,6 +50,7 @@ impl ExecutionContext {
max_stack_depth,
max_heap_size,
max_steps,
+ coerce_comparisons: false,
native_fns,
symbol_table: HashMap::new(),
}
@@ -83,6 +90,14 @@ impl ExecutionContext {
self
}
+ /// Opt into coercing comparison semantics (cross-type ordering coercion + epoch ordering/equality
+ /// of temporals). Off by default; only the realtime-cohort evaluator opts in, so existing
+ /// consumers like `cymbal` keep the legacy strict behavior. See [`Self::coerce_comparisons`].
+ pub fn with_coercing_comparisons(mut self) -> Self {
+ self.coerce_comparisons = true;
+ self
+ }
+
pub fn with_max_stack_depth(mut self, max_stack_depth: usize) -> Self {
self.max_stack_depth = max_stack_depth;
self
diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rs
index 7614c2d5dd67..55d18b5828e8 100644
--- a/rust/common/hogvm/src/stl.rs
+++ b/rust/common/hogvm/src/stl.rs
@@ -1,6 +1,7 @@
use core::str;
use std::collections::HashMap;
+use chrono::{DateTime, Datelike, LocalResult, NaiveDate, NaiveDateTime, TimeZone};
use rand::Rng;
use serde_json::{json, Value as JsonValue};
@@ -64,6 +65,17 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
}
}),
),
+ (
+ // Emitted by the `null_safe_comparisons=True` wrapper to guard missing-property leaves.
+ "isNull",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "isNull")?;
+ Ok(
+ HogLiteral::Boolean(matches!(args[0].deref(&vm.heap)?, HogLiteral::Null))
+ .into(),
+ )
+ }),
+ ),
(
"values",
native_func(|vm, args| {
@@ -363,6 +375,10 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
construct_free_standing(res, 0)
})),
),
+ // Wrapped in `err_to_null` so an unparseable input becomes `Null`, letting a leaf's
+ // `if(isNull(...), false, …)` guard yield `false` rather than erroring.
+ ("toDateTime", native_func(err_to_null(to_datetime))),
+ ("toDate", native_func(err_to_null(to_date))),
(
"multiSearchAnyCaseInsensitive",
native_func(|vm, args| {
@@ -470,6 +486,110 @@ fn to_string(heap: &VmHeap, val: &HogValue, depth: usize) -> Result<String, VmEr
}
}
+/// `toDateTime(input[, zone])` → a Hog DateTime object `{ __hogDateTime__: true, dt, zone }`.
+///
+/// To match ClickHouse (the parity oracle), this VM orders Hog temporals by `dt` seconds
+/// ([`crate::values::compare_values`]) — the reference Python/TS HogVMs cannot order them, so their
+/// `is_date_before`/`is_date_after` always return `false`. Naive strings parse as UTC (or `zone` for
+/// the 2-arg form), not the process-local timezone; an explicit offset/`Z` is honored as written.
+fn to_datetime(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {
+ if args.is_empty() || args.len() > 2 {
+ return Err(VmError::NativeCallFailed(
+ "toDateTime takes 1 or 2 arguments".to_string(),
+ ));
+ }
+ let zone = match args.get(1) {
+ Some(arg) => Some(arg.deref(&vm.heap)?.try_as::<str>()?.to_string()),
+ None => None,
+ };
+ let zone = zone.as_deref();
+ let dt_seconds = match args[0].deref(&vm.heap)? {
+ HogLiteral::Number(n) => n.to_float(),
+ HogLiteral::String(s) => parse_datetime_to_seconds(s, zone)?,
+ other => {
+ return Err(VmError::NativeCallFailed(format!(
+ "toDateTime expects a number or string, got {}",
+ other.type_name()
+ )))
+ }
+ };
+ construct_free_standing(
+ json!({ "__hogDateTime__": true, "dt": dt_seconds, "zone": zone.unwrap_or("UTC") }),
+ 0,
+ )
+}
+
+/// `toDate(input)` → a Hog Date object `{ __hogDate__: true, year, month, day }` in UTC.
+fn to_date(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {
+ assert_argc(&args, 1, "toDate")?;
+ let seconds = match args[0].deref(&vm.heap)? {
+ HogLiteral::Number(n) => n.to_float(),
+ HogLiteral::String(s) => parse_datetime_to_seconds(s, None)?,
+ other => {
+ return Err(VmError::NativeCallFailed(format!(
+ "toDate expects a number or string, got {}",
+ other.type_name()
+ )))
+ }
+ };
+ let dt = DateTime::from_timestamp(seconds as i64, 0).ok_or_else(|| {
+ VmError::NativeCallFailed(format!("toDate: timestamp {seconds} out of range"))
+ })?;
+ construct_free_standing(
+ json!({ "__hogDate__": true, "year": dt.year(), "month": dt.month(), "day": dt.day() }),
+ 0,
+ )
+}
+
+const NAIVE_DATETIME_FORMATS: [&str; 2] = ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S%.f"];
+
+fn parse_datetime_to_seconds(input: &str, zone: Option<&str>) -> Result<f64, VmError> {
+ let input = input.trim();
+ // An explicit offset/`Z` pins the absolute instant regardless of `zone`.
+ if let Ok(dt) = DateTime::parse_from_rfc3339(input) {
+ return Ok(datetime_to_seconds(dt));
+ }
+ for fmt in NAIVE_DATETIME_FORMATS {
+ if let Ok(naive) = NaiveDateTime::parse_from_str(input, fmt) {
+ return naive_to_seconds(naive, zone);
+ }
+ }
+ if let Some(naive) = NaiveDate::parse_from_str(input, "%Y-%m-%d")
+ .ok()
+ .and_then(|date| date.and_hms_opt(0, 0, 0))
+ {
+ return naive_to_seconds(naive, zone);
+ }
+ // A bare numeric string is unix seconds (e.g. an upstream `toString(<number>)`).
+ if let Ok(seconds) = input.parse::<f64>() {
+ return Ok(seconds);
+ }
+ Err(VmError::NativeCallFailed(format!(
+ "toDateTime could not parse {input:?}"
+ )))
+}
+
+fn naive_to_seconds(naive: NaiveDateTime, zone: Option<&str>) -> Result<f64, VmError> {
+ let Some(zone) = zone else {
+ return Ok(datetime_to_seconds(naive.and_utc()));
+ };
+ let tz: chrono_tz::Tz = zone
+ .parse()
+ .map_err(|_| VmError::NativeCallFailed(format!("toDateTime: unknown timezone {zone:?}")))?;
+ match tz.from_local_datetime(&naive) {
+ // DST fold: ClickHouse resolves to a single instant; take the earlier one.
+ LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => Ok(datetime_to_seconds(dt)),
+ LocalResult::None => Err(VmError::NativeCallFailed(format!(
+ "toDateTime: {naive} does not exist in {zone}"
+ ))),
+ }
+}
+
+/// `f64` epoch seconds with sub-second precision, matching Python's `datetime.timestamp()`.
+fn datetime_to_seconds<Tz: TimeZone>(dt: DateTime<Tz>) -> f64 {
+ dt.timestamp() as f64 + f64::from(dt.timestamp_subsec_nanos()) / 1_000_000_000.0
+}
+
fn assert(test: bool, msg: impl AsRef<str>) -> Result<(), VmError> {
if test {
Ok(())
diff --git a/rust/common/hogvm/src/values.rs b/rust/common/hogvm/src/values.rs
index 326d1828ace0..f8668c9f1d00 100644
--- a/rust/common/hogvm/src/values.rs
+++ b/rust/common/hogvm/src/values.rs
@@ -1,5 +1,6 @@
use std::{cmp::Ordering, collections::HashMap, fmt::Display, str::FromStr};
+use chrono::NaiveDate;
use serde_json::Value as JsonValue;
use crate::{
@@ -127,6 +128,9 @@ impl HogValue {
}
pub fn equals(&self, rhs: &HogValue, heap: &VmHeap) -> Result<HogLiteral, VmError> {
+ // Legacy structural equality, shared by every consumer. The cohort evaluator's temporal
+ // epoch-equality lives behind the opt-in flag in `HogVM::eq_op`, not here, so `Eq`/`in`/`has`
+ // stay unchanged for `cymbal` and other shared-crate users.
let (lhs, rhs) = (self.deref(heap)?, rhs.deref(heap)?);
lhs.equals(rhs)
}
@@ -276,6 +280,29 @@ impl HogLiteral {
Ok((lhs == rhs).into())
}
+ /// Seconds since the Unix epoch if this literal is a **Hog datetime/date** object, else `None`.
+ ///
+ /// Hog represents temporals as marker-keyed objects (mirroring the Python/TS runtimes' dicts):
+ /// - `{ __hogDateTime__: true, dt: <unix seconds>, zone }` → `dt` verbatim.
+ /// - `{ __hogDate__: true, year, month, day }` → UTC-midnight epoch, so a Date and a DateTime
+ /// are mutually comparable on one axis.
+ pub fn as_temporal_seconds(&self, heap: &VmHeap) -> Option<f64> {
+ let HogLiteral::Object(map) = self else {
+ return None;
+ };
+ if object_marker(map.get("__hogDateTime__"), heap) {
+ return object_number(map.get("dt"), heap);
+ }
+ if object_marker(map.get("__hogDate__"), heap) {
+ let year = object_number(map.get("year"), heap)? as i32;
+ let month = u32::try_from(object_number(map.get("month"), heap)? as i64).ok()?;
+ let day = u32::try_from(object_number(map.get("day"), heap)? as i64).ok()?;
+ let midnight = NaiveDate::from_ymd_opt(year, month, day)?.and_hms_opt(0, 0, 0)?;
+ return Some(midnight.and_utc().timestamp() as f64);
+ }
+ None
+ }
+
// Set a property, returning the number of bytes the old value used
pub fn set_property(&mut self, key: HogLiteral, val: HogValue) -> Result<usize, VmError> {
match self {
@@ -303,6 +330,95 @@ impl HogLiteral {
}
}
+/// Ordering comparison (`Gt`/`Lt`/`GtEq`/`LtEq`) for two literals, two concerns in order:
+///
+/// OPT-IN ONLY: this is reached exclusively from the coercing `compare_op` path, which the VM takes
+/// only when the context sets [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons)
+/// — today just the realtime-cohort evaluator. Every other shared-crate consumer (e.g. `cymbal`)
+/// keeps the legacy path where a non-number operand errors, so this coercion does NOT change their
+/// behavior. The semantics here match the Python/TS reference VMs (and ClickHouse for temporals).
+///
+/// 1. If *both* operands are temporal ([`HogLiteral::as_temporal_seconds`]) they are ordered by
+/// epoch seconds to match ClickHouse — the reference Python/TS HogVMs can't and so always return
+/// `false`; see the [`crate::stl`] module note.
+/// 2. Otherwise coerce like Python `unify_comparison_types` / TS `unifyComparisonTypes`: a String
+/// coerces to a Number only when the *other* operand is a Number, Bool↔Number maps to `1`/`0`,
+/// and both-strings compare lexicographically. This is deliberately *not* routed through
+/// [`HogLiteral::coerce_types`] (the `Eq` contract, which remaps both-strings and must stay put).
+pub fn compare_values(
+ op: NumOp,
+ a: &HogLiteral,
+ b: &HogLiteral,
+ heap: &VmHeap,
+) -> Result<HogLiteral, VmError> {
+ if let (Some(a_secs), Some(b_secs)) = (a.as_temporal_seconds(heap), b.as_temporal_seconds(heap))
+ {
+ return Num::binary_op(op, &Num::Float(a_secs), &Num::Float(b_secs));
+ }
+
+ use HogLiteral::{Boolean, Number, String as HString};
+ match (a, b) {
+ (Number(x), Number(y)) => Num::binary_op(op, x, y),
+ (Number(x), HString(s)) => Num::binary_op(op, x, &Num::from_str(s)?),
+ (HString(s), Number(y)) => Num::binary_op(op, &Num::from_str(s)?, y),
+ (Boolean(x), Number(y)) => Num::binary_op(op, &bool_to_num(*x), y),
+ (Number(x), Boolean(y)) => Num::binary_op(op, x, &bool_to_num(*y)),
+ (Boolean(x), Boolean(y)) => Num::binary_op(op, &bool_to_num(*x), &bool_to_num(*y)),
+ (Boolean(x), HString(s)) => {
+ Num::binary_op(op, &bool_to_num(*x), &bool_to_num(str_is_true(s)))
+ }
+ (HString(s), Boolean(y)) => {
+ Num::binary_op(op, &bool_to_num(str_is_true(s)), &bool_to_num(*y))
+ }
+ (HString(x), HString(y)) => Ok(string_order(op, x, y).into()),
+ _ => Err(VmError::CannotCoerce(
+ a.type_name().to_string(),
+ b.type_name().to_string(),
+ )),
+ }
+}
+
+fn object_marker(value: Option<&HogValue>, heap: &VmHeap) -> bool {
+ matches!(
+ value.and_then(|v| v.deref(heap).ok()),
+ Some(HogLiteral::Boolean(true))
+ )
+}
+
+fn object_number(value: Option<&HogValue>, heap: &VmHeap) -> Option<f64> {
+ match value?.deref(heap).ok()? {
+ HogLiteral::Number(n) => Some(n.to_float()),
+ _ => None,
+ }
+}
+
+fn bool_to_num(b: bool) -> Num {
+ Num::Integer(i64::from(b))
+}
+
+/// String→bool coercion for the ordering path, matching Python's `unify_comparison_types`:
+/// `"true"`/`"false"` (any case) map literally, every other non-empty string is truthy (`bool(s)`),
+/// empty string is falsy. NOTE: the `Eq` path's [`HogLiteral::coerce_types`] uses the narrower
+/// `== "true"` rule, so `true == "yes"` and `true > "yes"` disagree.
+fn str_is_true(s: &str) -> bool {
+ match s.to_lowercase().as_str() {
+ "true" => true,
+ "false" => false,
+ other => !other.is_empty(),
+ }
+}
+
+fn string_order(op: NumOp, a: &str, b: &str) -> bool {
+ let ord = a.cmp(b);
+ match op {
+ NumOp::Gt => ord.is_gt(),
+ NumOp::Lt => ord.is_lt(),
+ NumOp::Gte => ord.is_ge(),
+ NumOp::Lte => ord.is_le(),
+ _ => false,
+ }
+}
+
impl FromHogLiteral for HogLiteral {
fn from_val(value: HogLiteral) -> Result<Self, VmError> {
Ok(value)
diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rs
index 68aaa86ec869..26a7d14723dd 100644
--- a/rust/common/hogvm/src/vm.rs
+++ b/rust/common/hogvm/src/vm.rs
@@ -9,7 +9,10 @@ use crate::{
memory::{HeapReference, VmHeap},
ops::Operation,
util::{get_json_nested, like, regex_match},
- values::{Callable, Closure, FromHogLiteral, HogLiteral, HogValue, LocalCallable, Num, NumOp},
+ values::{
+ compare_values, Callable, Closure, FromHogLiteral, HogLiteral, HogValue, LocalCallable,
+ Num, NumOp,
+ },
};
pub const MAX_JSON_SERDE_DEPTH: usize = 64;
@@ -218,28 +221,18 @@ impl<'a> HogVM<'a> {
}
Operation::Eq => {
let (a, b) = (self.pop_stack()?, self.pop_stack()?);
- self.push_stack(a.equals(&b, &self.heap)?)?;
+ let result = self.eq_op(&a, &b)?;
+ self.push_stack(result)?;
}
Operation::NotEq => {
let (a, b) = (self.pop_stack()?, self.pop_stack()?);
- self.push_stack(a.not_equals(&b, &self.heap)?)?;
- }
- Operation::Gt => {
- let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
- self.push_stack(Num::binary_op(NumOp::Gt, &a, &b)?)?;
- }
- Operation::GtEq => {
- let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
- self.push_stack(Num::binary_op(NumOp::Gte, &a, &b)?)?;
- }
- Operation::Lt => {
- let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
- self.push_stack(Num::binary_op(NumOp::Lt, &a, &b)?)?;
- }
- Operation::LtEq => {
- let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
- self.push_stack(Num::binary_op(NumOp::Lte, &a, &b)?)?;
+ let result = self.eq_op(&a, &b)?.not()?;
+ self.push_stack(result)?;
}
+ Operation::Gt => self.compare_op(NumOp::Gt)?,
+ Operation::GtEq => self.compare_op(NumOp::Gte)?,
+ Operation::Lt => self.compare_op(NumOp::Lt)?,
+ Operation::LtEq => self.compare_op(NumOp::Lte)?,
Operation::Like => {
let (val, pat): (String, String) = (self.pop_stack_as()?, self.pop_stack_as()?);
self.push_stack(like(val, pat, true)?)?;
@@ -725,6 +718,47 @@ impl<'a> HogVM<'a> {
}
}
+ /// `Gt`/`GtEq`/`Lt`/`LtEq` arm. The default (legacy) path requires numeric operands and errors
+ /// otherwise — the behavior `cymbal` and every other existing shared-crate consumer relies on
+ /// (a non-number operand erroring is what lets cymbal auto-disable a malformed rule). Only when
+ /// the context opts into coercing comparisons (the realtime-cohort evaluator, via
+ /// [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons))
+ /// does a non-`Number` operand reach [`compare_values`]' coercion instead of erroring. `a` is the
+ /// top of the stack.
+ fn compare_op(&mut self, op: NumOp) -> Result<(), VmError> {
+ if !self.context.coerce_comparisons {
+ // Legacy/reference path: both operands must be `Number` or this errors.
+ let (a, b): (Num, Num) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ return self.push_stack(Num::binary_op(op, &a, &b)?);
+ }
+ let a = self.pop_stack()?;
+ let b = self.pop_stack()?;
+ // Scope the immutable heap borrows so the result is owned before the `&mut self` push.
+ let result = {
+ let a_lit = a.deref(&self.heap)?;
+ let b_lit = b.deref(&self.heap)?;
+ compare_values(op, a_lit, b_lit, &self.heap)?
+ };
+ self.push_stack(result)
+ }
+
+ /// `Eq`/`NotEq` core. The default path is the legacy structural equality every existing
+ /// shared-crate consumer relies on. Only when the context opts into coercing comparisons (the
+ /// realtime-cohort evaluator) do two Hog temporals compare by epoch seconds to match ClickHouse
+ /// (`is_date_exact`); every non-temporal pair is unchanged either way.
+ fn eq_op(&self, a: &HogValue, b: &HogValue) -> Result<HogLiteral, VmError> {
+ if self.context.coerce_comparisons {
+ let (lhs, rhs) = (a.deref(&self.heap)?, b.deref(&self.heap)?);
+ if let (Some(x), Some(y)) = (
+ lhs.as_temporal_seconds(&self.heap),
+ rhs.as_temporal_seconds(&self.heap),
+ ) {
+ return Ok((x == y).into());
+ }
+ }
+ a.equals(b, &self.heap)
+ }
+
// Move a value from the stack onto the heap, replacing it with a reference to the heap value,
// and returning a reference to it. If it was already a reference, return it.
fn hoist(&mut self, idx: usize) -> Result<HeapReference, VmError> {
diff --git a/rust/common/hogvm/tests/datetime.rs b/rust/common/hogvm/tests/datetime.rs
new file mode 100644
index 000000000000..0c0a17f92200
--- /dev/null
+++ b/rust/common/hogvm/tests/datetime.rs
@@ -0,0 +1,228 @@
+//! Coverage for the `toDateTime`/`toDate` natives and Hog-temporal comparison. This VM orders
+//! temporals by `dt` seconds to match ClickHouse (the reference Python/TS HogVMs cannot order them);
+//! naive strings parse as UTC, not the process-local timezone.
+
+use chrono::{NaiveDate, TimeZone, Utc};
+use hogvm::{sync_execute, ExecutionContext, Program};
+use serde_json::{json, Value};
+
+// Opcode numeric values (mirror common/hogvm/python/operation.py).
+const OP_CALL_GLOBAL: i64 = 2;
+const OP_EQ: i64 = 11;
+const OP_GT: i64 = 13;
+const OP_LT: i64 = 15;
+const OP_STRING: i64 = 32;
+const OP_RETURN: i64 = 38;
+
+fn run(bytecode: Vec<Value>) -> Value {
+ let program = Program::new(bytecode).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program)
+ .with_globals(json!({}))
+ .with_coercing_comparisons();
+ sync_execute(&ctx, false).expect("execution succeeds")
+}
+
+fn to_datetime(s: &str) -> Vec<Value> {
+ vec![
+ json!(OP_STRING),
+ json!(s),
+ json!(OP_CALL_GLOBAL),
+ json!("toDateTime"),
+ json!(1),
+ ]
+}
+
+fn to_datetime_zoned(s: &str, zone: &str) -> Vec<Value> {
+ vec![
+ json!(OP_STRING),
+ json!(s),
+ json!(OP_STRING),
+ json!(zone),
+ json!(OP_CALL_GLOBAL),
+ json!("toDateTime"),
+ json!(2),
+ ]
+}
+
+/// `left <op> right`. The compiler emits operands as `[right…, left…, op]`.
+fn compare(left: &[Value], right: &[Value], op: i64) -> Vec<Value> {
+ let mut bc = vec![json!("_H"), json!(1)];
+ bc.extend_from_slice(right);
+ bc.extend_from_slice(left);
+ bc.push(json!(op));
+ bc.push(json!(OP_RETURN));
+ bc
+}
+
+fn returning(fragment: &[Value]) -> Vec<Value> {
+ let mut bc = vec![json!("_H"), json!(1)];
+ bc.extend_from_slice(fragment);
+ bc.push(json!(OP_RETURN));
+ bc
+}
+
+#[test]
+fn to_datetime_parses_naive_string_as_utc_not_local() {
+ let result = run(returning(&to_datetime("2026-05-13 00:00:00")));
+ let expected = NaiveDate::from_ymd_opt(2026, 5, 13)
+ .unwrap()
+ .and_hms_opt(0, 0, 0)
+ .unwrap()
+ .and_utc()
+ .timestamp() as f64;
+
+ assert_eq!(result["__hogDateTime__"], json!(true));
+ assert_eq!(result["zone"], json!("UTC"));
+ assert_eq!(result["dt"].as_f64().unwrap(), expected);
+}
+
+#[test]
+fn to_datetime_honors_an_explicit_iso_offset() {
+ let result = run(returning(&to_datetime("2026-03-19T14:00:00Z")));
+ let expected = Utc
+ .with_ymd_and_hms(2026, 3, 19, 14, 0, 0)
+ .unwrap()
+ .timestamp() as f64;
+ assert_eq!(result["dt"].as_f64().unwrap(), expected);
+}
+
+#[test]
+fn to_datetime_arity2_interprets_naive_string_in_the_given_zone() {
+ let utc = run(returning(&to_datetime("2026-05-13 00:00:00")));
+ let ny = run(returning(&to_datetime_zoned(
+ "2026-05-13 00:00:00",
+ "America/New_York",
+ )));
+ assert_eq!(ny["zone"], json!("America/New_York"));
+ assert_eq!(
+ ny["dt"].as_f64().unwrap() - utc["dt"].as_f64().unwrap(),
+ 4.0 * 3600.0,
+ );
+}
+
+#[test]
+fn to_datetime_passes_through_a_unix_number() {
+ let bc = returning(&[
+ json!(33), // OP_INTEGER
+ json!(1_700_000_000),
+ json!(OP_CALL_GLOBAL),
+ json!("toDateTime"),
+ json!(1),
+ ]);
+ assert_eq!(run(bc)["dt"].as_f64().unwrap(), 1_700_000_000.0);
+}
+
+#[test]
+fn unparseable_input_becomes_null_not_an_error() {
+ // `err_to_null` turns a parse failure into `Null` so the leaf's `if(isNull(...), false, …)` guard wins.
+ assert_eq!(
+ run(returning(&to_datetime("definitely not a date"))),
+ Value::Null
+ );
+}
+
+#[test]
+fn datetime_less_than_orders_by_instant() {
+ let earlier = to_datetime("2020-01-01 00:00:00");
+ let later = to_datetime("2030-01-01 00:00:00");
+ assert_eq!(run(compare(&earlier, &later, OP_LT)), Value::Bool(true));
+ assert_eq!(run(compare(&later, &earlier, OP_LT)), Value::Bool(false));
+}
+
+#[test]
+fn datetime_greater_than_orders_by_instant() {
+ let earlier = to_datetime("2020-06-15 12:00:00");
+ let later = to_datetime("2020-06-15 12:00:01");
+ assert_eq!(run(compare(&later, &earlier, OP_GT)), Value::Bool(true));
+ assert_eq!(run(compare(&earlier, &later, OP_GT)), Value::Bool(false));
+}
+
+#[test]
+fn datetime_equality_is_by_instant() {
+ let naive = to_datetime("2026-03-19 14:00:00");
+ let iso_z = to_datetime("2026-03-19T14:00:00Z");
+ let other = to_datetime("2026-03-19 14:00:01");
+ assert_eq!(run(compare(&naive, &iso_z, OP_EQ)), Value::Bool(true));
+ assert_eq!(run(compare(&naive, &other, OP_EQ)), Value::Bool(false));
+}
+
+/// Run WITHOUT opting into coercing comparisons — the default every non-cohort consumer gets.
+fn run_legacy(bytecode: Vec<Value>) -> Value {
+ let program = Program::new(bytecode).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program).with_globals(json!({}));
+ sync_execute(&ctx, false).expect("execution succeeds")
+}
+
+#[test]
+fn legacy_default_compares_temporals_structurally_not_by_epoch() {
+ // Same instant (05:30 Kolkata == 00:00 UTC), different zone: epoch-equal but structurally
+ // distinct objects. The opt-in coercing path treats them as equal (ClickHouse `is_date_exact`);
+ // the default path every other consumer (e.g. cymbal) gets keeps the legacy structural
+ // comparison, so they are NOT equal — proving the temporal `Eq` change is gated.
+ let kolkata = to_datetime_zoned("2026-01-01 05:30:00", "Asia/Kolkata");
+ let utc = to_datetime("2026-01-01 00:00:00");
+ assert_eq!(
+ run(compare(&kolkata, &utc, OP_EQ)),
+ Value::Bool(true),
+ "coercing: epoch-equal"
+ );
+ assert_eq!(
+ run_legacy(compare(&kolkata, &utc, OP_EQ)),
+ Value::Bool(false),
+ "legacy: structurally distinct (zone differs)",
+ );
+}
+
+#[test]
+fn date_and_datetime_are_mutually_comparable() {
+ let date = vec![
+ json!(OP_STRING),
+ json!("2026-05-13"),
+ json!(OP_CALL_GLOBAL),
+ json!("toDate"),
+ json!(1),
+ ];
+ let noon = to_datetime("2026-05-13 12:00:00");
+ assert_eq!(run(compare(&date, &noon, OP_LT)), Value::Bool(true));
+}
+
+#[test]
+fn full_compiled_shape_to_string_to_datetime_lt() {
+ // Realistic leaf shape `Lt(toDateTime(toString(person.properties.signup_date)), toDateTime(const))`;
+ // the `toString → toDateTime` hop mirrors `_force_datetime`. `Program` is not `Clone`, so rebuild per iteration.
+ const OP_GET_GLOBAL: i64 = 1;
+ let bytecode = || {
+ let lhs = vec![
+ json!(OP_STRING),
+ json!("signup_date"),
+ json!(OP_STRING),
+ json!("properties"),
+ json!(OP_STRING),
+ json!("person"),
+ json!(OP_GET_GLOBAL),
+ json!(3),
+ json!(OP_CALL_GLOBAL),
+ json!("toString"),
+ json!(1),
+ json!(OP_CALL_GLOBAL),
+ json!("toDateTime"),
+ json!(1),
+ ];
+ compare(&lhs, &to_datetime("2026-01-01 00:00:00"), OP_LT)
+ };
+
+ for (signup, expected) in [
+ ("2024-09-09 08:30:00", true),
+ ("2027-09-09 08:30:00", false),
+ ] {
+ let program = Program::new(bytecode()).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program)
+ .with_globals(json!({ "person": { "properties": { "signup_date": signup } } }))
+ .with_coercing_comparisons();
+ assert_eq!(
+ sync_execute(&ctx, false).expect("execution succeeds"),
+ Value::Bool(expected),
+ "signup {signup}",
+ );
+ }
+}
diff --git a/rust/common/hogvm/tests/isnull.rs b/rust/common/hogvm/tests/isnull.rs
new file mode 100644
index 000000000000..c53f5e60b7c5
--- /dev/null
+++ b/rust/common/hogvm/tests/isnull.rs
@@ -0,0 +1,84 @@
+//! Coverage for the `isNull` native, emitted by the `null_safe_comparisons=True` wrapper that every
+//! cohort numeric-comparison leaf compiles through, so it must agree with the Python/TS references.
+
+use hogvm::{sync_execute, ExecutionContext, Program};
+use serde_json::{json, Value};
+
+// Opcode numeric values (mirror common/hogvm/python/operation.py).
+const OP_GET_GLOBAL: i64 = 1;
+const OP_CALL_GLOBAL: i64 = 2;
+const OP_NULL: i64 = 31;
+const OP_STRING: i64 = 32;
+const OP_INTEGER: i64 = 33;
+const OP_RETURN: i64 = 38;
+
+fn run(bytecode: Vec<Value>, globals: Value) -> Value {
+ let program = Program::new(bytecode).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program).with_globals(globals);
+ sync_execute(&ctx, false).expect("execution succeeds")
+}
+
+fn is_null_of(push_value: &[Value]) -> Vec<Value> {
+ let mut bc = vec![json!("_H"), json!(1)];
+ bc.extend_from_slice(push_value);
+ bc.extend_from_slice(&[
+ json!(OP_CALL_GLOBAL),
+ json!("isNull"),
+ json!(1),
+ json!(OP_RETURN),
+ ]);
+ bc
+}
+
+#[test]
+fn is_null_of_null_literal_is_true() {
+ assert_eq!(
+ run(is_null_of(&[json!(OP_NULL)]), json!({})),
+ Value::Bool(true)
+ );
+}
+
+#[test]
+fn is_null_of_integer_literal_is_false() {
+ let push_int = [json!(OP_INTEGER), json!(42)];
+ assert_eq!(run(is_null_of(&push_int), json!({})), Value::Bool(false));
+}
+
+#[test]
+fn is_null_of_string_literal_is_false() {
+ let push_str = [json!(OP_STRING), json!("hello")];
+ assert_eq!(run(is_null_of(&push_str), json!({})), Value::Bool(false));
+}
+
+/// A missing person property resolves to null via GET_GLOBAL — the case the null-safe wrapper guards.
+/// GET_GLOBAL takes the path segments pushed in reverse, then a count.
+fn push_person_property(prop: &str) -> Vec<Value> {
+ vec![
+ json!(OP_STRING),
+ json!(prop),
+ json!(OP_STRING),
+ json!("properties"),
+ json!(OP_STRING),
+ json!("person"),
+ json!(OP_GET_GLOBAL),
+ json!(3),
+ ]
+}
+
+#[test]
+fn is_null_of_missing_person_property_is_true() {
+ let globals = json!({ "person": { "properties": {} } });
+ assert_eq!(
+ run(is_null_of(&push_person_property("email")), globals),
+ Value::Bool(true)
+ );
+}
+
+#[test]
+fn is_null_of_present_person_property_is_false() {
+ let globals = json!({ "person": { "properties": { "email": "[email protected]" } } });
+ assert_eq!(
+ run(is_null_of(&push_person_property("email")), globals),
+ Value::Bool(false)
+ );
+}
diff --git a/rust/common/hogvm/tests/numeric_coercion.rs b/rust/common/hogvm/tests/numeric_coercion.rs
new file mode 100644
index 000000000000..f86fb5a19491
--- /dev/null
+++ b/rust/common/hogvm/tests/numeric_coercion.rs
@@ -0,0 +1,240 @@
+//! Coverage for ordering-comparison coercion (`Gt`/`GtEq`/`Lt`/`LtEq`) over mixed scalar types.
+//! Cohort numeric leaves compile the threshold as a string constant, so this must match the Python
+//! (`unify_comparison_types`) and TS (`unifyComparisonTypes`) coercion exactly.
+
+use hogvm::{sync_execute, ExecutionContext, Program, VmFailure};
+use serde_json::{json, Value};
+
+// Opcode numeric values (mirror common/hogvm/python/operation.py).
+const OP_EQ: i64 = 11;
+const OP_GT: i64 = 13;
+const OP_GT_EQ: i64 = 14;
+const OP_LT: i64 = 15;
+const OP_LT_EQ: i64 = 16;
+const OP_TRUE: i64 = 29;
+const OP_FALSE: i64 = 30;
+const OP_STRING: i64 = 32;
+const OP_INTEGER: i64 = 33;
+const OP_FLOAT: i64 = 34;
+const OP_RETURN: i64 = 38;
+
+/// `left <op> right`. The compiler emits operands as `[right…, left…, op]`.
+fn compare(left: &[Value], right: &[Value], op: i64) -> Vec<Value> {
+ let mut bc = vec![json!("_H"), json!(1)];
+ bc.extend_from_slice(right);
+ bc.extend_from_slice(left);
+ bc.push(json!(op));
+ bc.push(json!(OP_RETURN));
+ bc
+}
+
+fn run_result(bytecode: Vec<Value>) -> Result<Value, VmFailure> {
+ let program = Program::new(bytecode).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program)
+ .with_globals(json!({}))
+ .with_coercing_comparisons();
+ sync_execute(&ctx, false)
+}
+
+fn run(bytecode: Vec<Value>) -> Value {
+ run_result(bytecode).expect("execution succeeds")
+}
+
+fn int(n: i64) -> Vec<Value> {
+ vec![json!(OP_INTEGER), json!(n)]
+}
+
+fn float(n: f64) -> Vec<Value> {
+ vec![json!(OP_FLOAT), json!(n)]
+}
+
+fn string(s: &str) -> Vec<Value> {
+ vec![json!(OP_STRING), json!(s)]
+}
+
+fn boolean(b: bool) -> Vec<Value> {
+ vec![json!(if b { OP_TRUE } else { OP_FALSE })]
+}
+
+#[test]
+fn number_vs_numeric_string_coerces_the_string() {
+ // The exact cohort case: `bc_num gt "10"` (threshold compiled as a string).
+ assert_eq!(
+ run(compare(&int(20), &string("10"), OP_GT)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&int(5), &string("10"), OP_GT)),
+ Value::Bool(false)
+ );
+ assert_eq!(
+ run(compare(&string("20"), &int(10), OP_GT)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&string("5"), &int(10), OP_GT)),
+ Value::Bool(false)
+ );
+}
+
+#[test]
+fn every_ordering_op_coerces_numeric_strings() {
+ for (op, expected) in [
+ (OP_GT, true),
+ (OP_GT_EQ, true),
+ (OP_LT, false),
+ (OP_LT_EQ, false),
+ ] {
+ assert_eq!(
+ run(compare(&int(20), &string("10"), op)),
+ Value::Bool(expected),
+ "op {op}",
+ );
+ }
+ for (op, expected) in [
+ (OP_GT, false),
+ (OP_GT_EQ, true),
+ (OP_LT, false),
+ (OP_LT_EQ, true),
+ ] {
+ assert_eq!(
+ run(compare(&int(10), &string("10"), op)),
+ Value::Bool(expected),
+ "equal, op {op}",
+ );
+ }
+}
+
+#[test]
+fn float_string_coercion_works() {
+ assert_eq!(
+ run(compare(&float(2.5), &string("2.4"), OP_GT)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&string("2.4"), &float(2.5), OP_LT)),
+ Value::Bool(true)
+ );
+}
+
+#[test]
+fn both_strings_compare_lexicographically() {
+ // Residual divergence from ClickHouse: two strings compare lexicographically (matching Python/TS),
+ // NOT numerically — so "9" > "100" here though 9 < 100 numerically.
+ assert_eq!(
+ run(compare(&string("20"), &string("10"), OP_GT)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&string("9"), &string("100"), OP_GT)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&string("9"), &string("100"), OP_LT)),
+ Value::Bool(false)
+ );
+}
+
+#[test]
+fn bool_number_coercion_maps_true_one_false_zero() {
+ assert_eq!(
+ run(compare(&boolean(true), &int(0), OP_GT)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&boolean(false), &int(1), OP_LT)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&boolean(true), &int(1), OP_GT_EQ)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&int(1), &boolean(false), OP_GT)),
+ Value::Bool(true)
+ );
+}
+
+#[test]
+fn bool_vs_non_numeric_string_matches_python() {
+ // Python's `unify_comparison_types` coerces a string to bool as `bool(s)`: "true"/"false" map
+ // literally, every other non-empty string is truthy, "" is falsy. So `true > "yes"` is 1 > 1.
+ assert_eq!(
+ run(compare(&boolean(true), &string("yes"), OP_GT)),
+ Value::Bool(false),
+ );
+ assert_eq!(
+ run(compare(&boolean(true), &string("yes"), OP_GT_EQ)),
+ Value::Bool(true),
+ );
+ // "false" → 0, so `true > "false"` is 1 > 0.
+ assert_eq!(
+ run(compare(&boolean(true), &string("false"), OP_GT)),
+ Value::Bool(true),
+ );
+ // "" → 0 (falsy), so `true > ""` is 1 > 0.
+ assert_eq!(
+ run(compare(&boolean(true), &string(""), OP_GT)),
+ Value::Bool(true),
+ );
+ // `false < "yes"` is 0 < 1.
+ assert_eq!(
+ run(compare(&boolean(false), &string("yes"), OP_LT)),
+ Value::Bool(true),
+ );
+}
+
+#[test]
+fn number_vs_unparseable_string_errors() {
+ // An unparseable string errors on this path (Python raises, TS yields NaN).
+ assert!(run_result(compare(&int(5), &string("abc"), OP_GT)).is_err());
+ assert!(run_result(compare(&string("abc"), &int(5), OP_LT)).is_err());
+}
+
+/// Build + run WITHOUT opting into coercing comparisons — the default every non-cohort consumer
+/// (e.g. cymbal) gets.
+fn run_legacy(bytecode: Vec<Value>) -> Result<Value, VmFailure> {
+ let program = Program::new(bytecode).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program).with_globals(json!({}));
+ sync_execute(&ctx, false)
+}
+
+#[test]
+fn legacy_default_keeps_strict_comparisons_for_other_consumers() {
+ // The coercion is opt-in: without it a non-number operand ERRORS rather than coercing.
+ // This is the contract cymbal relies on to auto-disable a malformed rule.
+ assert!(
+ run_legacy(compare(&int(5), &string("10"), OP_GT)).is_err(),
+ "number vs numeric-string must error on the legacy path, not coerce",
+ );
+ assert!(
+ run_legacy(compare(&boolean(true), &int(0), OP_GT)).is_err(),
+ "bool vs number must error on the legacy path, not coerce",
+ );
+ // Pure numeric comparisons are identical on both paths.
+ assert_eq!(
+ run_legacy(compare(&int(20), &int(10), OP_GT)).unwrap(),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run_legacy(compare(&int(5), &int(10), OP_GT)).unwrap(),
+ Value::Bool(false)
+ );
+}
+
+#[test]
+fn pure_numeric_comparisons_are_unchanged() {
+ // Regression guard: the shared `compare_op` must keep number-vs-number byte-identical.
+ assert_eq!(run(compare(&int(20), &int(17), OP_GT)), Value::Bool(true));
+ assert_eq!(run(compare(&int(17), &int(20), OP_GT)), Value::Bool(false));
+ assert_eq!(run(compare(&int(5), &int(10), OP_LT)), Value::Bool(true));
+ assert_eq!(
+ run(compare(&float(2.5), &float(2.4), OP_GT)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&int(10), &float(10.0), OP_GT_EQ)),
+ Value::Bool(true)
+ );
+ assert_eq!(run(compare(&int(10), &int(10), OP_EQ)), Value::Bool(true));
+}
diff --git a/rust/common/kafka/src/config.rs b/rust/common/kafka/src/config.rs
index 893573673ca0..fa475f5c9888 100644
--- a/rust/common/kafka/src/config.rs
+++ b/rust/common/kafka/src/config.rs
@@ -44,6 +44,10 @@ pub struct KafkaConfig {
pub kafka_producer_message_max_bytes: Option<u32>,
pub kafka_producer_sticky_partitioning_linger_ms: Option<u32>,
+
+ // Set to "murmur2_random" to co-partition a keyed topic with Kafka-Java/python-kafka/Node
+ // producers; `None` uses librdkafka's CRC32-based default, which routes keys differently.
+ pub kafka_producer_partitioner: Option<String>,
}
#[derive(Envconfig, Clone)]
diff --git a/rust/common/kafka/src/kafka_producer.rs b/rust/common/kafka/src/kafka_producer.rs
index 81c038b6df6f..263b954b85dd 100644
--- a/rust/common/kafka/src/kafka_producer.rs
+++ b/rust/common/kafka/src/kafka_producer.rs
@@ -121,6 +121,9 @@ where
if let Some(v) = config.kafka_producer_sticky_partitioning_linger_ms {
client_config.set("sticky.partitioning.linger.ms", v.to_string());
}
+ if let Some(ref v) = config.kafka_producer_partitioner {
+ client_config.set("partitioner", v);
+ }
if config.kafka_tls {
client_config
diff --git a/rust/common/kafka/src/test.rs b/rust/common/kafka/src/test.rs
index d7d6da62fa10..dd227dff7bfa 100644
--- a/rust/common/kafka/src/test.rs
+++ b/rust/common/kafka/src/test.rs
@@ -32,6 +32,7 @@ pub async fn create_mock_kafka() -> (
kafka_producer_topic_metadata_refresh_interval_ms: None,
kafka_producer_message_max_bytes: None,
kafka_producer_sticky_partitioning_linger_ms: None,
+ kafka_producer_partitioner: None,
};
(
diff --git a/rust/common/types/src/cohort.rs b/rust/common/types/src/cohort.rs
new file mode 100644
index 000000000000..42d3f1245aeb
--- /dev/null
+++ b/rust/common/types/src/cohort.rs
@@ -0,0 +1,140 @@
+use std::collections::HashSet;
+use std::str::FromStr;
+
+/// Which teams the realtime-cohort shadow pipeline is scoped to, parsed from
+/// `REALTIME_COHORT_TEAM_ALLOWLIST`.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum TeamAllowlist {
+ All,
+ Only(HashSet<i32>),
+}
+
+impl TeamAllowlist {
+ /// Whether `team_id` is in scope.
+ pub fn includes(&self, team_id: i32) -> bool {
+ match self {
+ TeamAllowlist::All => true,
+ TeamAllowlist::Only(ids) => ids.contains(&team_id),
+ }
+ }
+}
+
+impl FromStr for TeamAllowlist {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let s = s.trim();
+ // envconfig's `default` only covers an *unset* var; a set-but-empty value must still mean
+ // "no gate", never "gate everything".
+ if s.is_empty() || s.eq_ignore_ascii_case("all") || s == "*" {
+ return Ok(TeamAllowlist::All);
+ }
+ if s.eq_ignore_ascii_case("none") {
+ return Ok(TeamAllowlist::Only(HashSet::new()));
+ }
+
+ let mut ids = HashSet::new();
+ for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
+ match part.split_once(':') {
+ Some((start, end)) => {
+ let start: i32 = start
+ .trim()
+ .parse()
+ .map_err(|e| format!("invalid range start in '{part}': {e}"))?;
+ let end: i32 = end
+ .trim()
+ .parse()
+ .map_err(|e| format!("invalid range end in '{part}': {e}"))?;
+ if end < start {
+ return Err(format!("invalid range '{part}': end < start"));
+ }
+ // Guard against an unbounded span materializing billions of ids (OOM at
+ // startup). Compute in i64 so a negative start vs i32::MAX end can't overflow.
+ const MAX_RANGE_SPAN: i64 = 100_000;
+ let span = i64::from(end) - i64::from(start) + 1;
+ if span > MAX_RANGE_SPAN {
+ return Err(format!(
+ "range '{part}' spans {span} teams (max {MAX_RANGE_SPAN}); use 'all' or '*' to allow every team"
+ ));
+ }
+ ids.extend(start..=end);
+ }
+ None => {
+ let id: i32 = part
+ .parse()
+ .map_err(|e| format!("invalid team id '{part}': {e}"))?;
+ ids.insert(id);
+ }
+ }
+ }
+ Ok(TeamAllowlist::Only(ids))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn team_allowlist_blank_and_keywords_disable_or_clear_the_gate() {
+ assert_eq!("".parse::<TeamAllowlist>().unwrap(), TeamAllowlist::All);
+ assert_eq!(" ".parse::<TeamAllowlist>().unwrap(), TeamAllowlist::All);
+ assert_eq!("all".parse::<TeamAllowlist>().unwrap(), TeamAllowlist::All);
+ assert_eq!("ALL".parse::<TeamAllowlist>().unwrap(), TeamAllowlist::All);
+ assert_eq!("*".parse::<TeamAllowlist>().unwrap(), TeamAllowlist::All);
+ assert_eq!(
+ "none".parse::<TeamAllowlist>().unwrap(),
+ TeamAllowlist::Only(HashSet::new()),
+ );
+ }
+
+ #[test]
+ fn team_allowlist_parses_lists_and_ranges() {
+ assert_eq!(
+ "2".parse::<TeamAllowlist>().unwrap(),
+ TeamAllowlist::Only(HashSet::from([2])),
+ );
+ assert_eq!(
+ "2, 42 ,7".parse::<TeamAllowlist>().unwrap(),
+ TeamAllowlist::Only(HashSet::from([2, 42, 7])),
+ );
+ assert_eq!(
+ "1:3".parse::<TeamAllowlist>().unwrap(),
+ TeamAllowlist::Only(HashSet::from([1, 2, 3])),
+ );
+ assert_eq!(
+ "1:2,5".parse::<TeamAllowlist>().unwrap(),
+ TeamAllowlist::Only(HashSet::from([1, 2, 5])),
+ );
+ }
+
+ #[test]
+ fn team_allowlist_rejects_garbage_and_inverted_ranges() {
+ assert!("nope".parse::<TeamAllowlist>().is_err());
+ assert!("3:1".parse::<TeamAllowlist>().is_err());
+ assert!("2,x".parse::<TeamAllowlist>().is_err());
+ // Oversized spans would materialize billions of ids and OOM at startup.
+ assert!("1:2000000000".parse::<TeamAllowlist>().is_err());
+ assert!("1:100002".parse::<TeamAllowlist>().is_err());
+ // A span at exactly the cap (100_000 teams) is still allowed.
+ assert!("1:100000".parse::<TeamAllowlist>().is_ok());
+ }
+
+ #[test]
+ fn team_allowlist_includes_honours_scope() {
+ assert!(TeamAllowlist::All.includes(999));
+ let only = TeamAllowlist::Only(HashSet::from([2]));
+ assert!(only.includes(2));
+ assert!(!only.includes(3));
+ assert!(!TeamAllowlist::Only(HashSet::new()).includes(2));
+ }
+
+ #[test]
+ fn team_allowlist_default_is_team_two() {
+ // envconfig default is "2"; a set-but-empty var falls through to `All` (see `FromStr`).
+ assert_eq!(
+ "2".parse::<TeamAllowlist>().unwrap(),
+ TeamAllowlist::Only(HashSet::from([2])),
+ );
+ }
+}
diff --git a/rust/common/types/src/lib.rs b/rust/common/types/src/lib.rs
index 05245718725d..7ca2a2ae8c46 100644
--- a/rust/common/types/src/lib.rs
+++ b/rust/common/types/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod cohort;
pub mod collections;
mod embeddings;
mod event;
diff --git a/rust/flags-consumer/src/config.rs b/rust/flags-consumer/src/config.rs
index 0c4cf57f922f..82e4bbd52ab7 100644
--- a/rust/flags-consumer/src/config.rs
+++ b/rust/flags-consumer/src/config.rs
@@ -145,6 +145,7 @@ impl Config {
kafka_producer_topic_metadata_refresh_interval_ms: None,
kafka_producer_message_max_bytes: None,
kafka_producer_sticky_partitioning_linger_ms: None,
+ kafka_producer_partitioner: None,
}
}
diff --git a/rust/kafka-deduplicator/src/service.rs b/rust/kafka-deduplicator/src/service.rs
index 6d8a15d77102..555ba3aa0802 100644
--- a/rust/kafka-deduplicator/src/service.rs
+++ b/rust/kafka-deduplicator/src/service.rs
@@ -441,6 +441,7 @@ impl KafkaDeduplicatorService {
kafka_producer_topic_metadata_refresh_interval_ms: None,
kafka_producer_message_max_bytes: None,
kafka_producer_sticky_partitioning_linger_ms: None,
+ kafka_producer_partitioner: None,
};
// Normalize empty strings to None for optional topic configs
diff --git a/rust/personhog-leader/src/coordination/mod.rs b/rust/personhog-leader/src/coordination/mod.rs
index bfc669fb38fa..fcd66da82624 100644
--- a/rust/personhog-leader/src/coordination/mod.rs
+++ b/rust/personhog-leader/src/coordination/mod.rs
@@ -115,6 +115,7 @@ mod tests {
kafka_producer_topic_metadata_refresh_interval_ms: None,
kafka_producer_message_max_bytes: None,
kafka_producer_sticky_partitioning_linger_ms: None,
+ kafka_producer_partitioner: None,
},
topic: "personhog_updates".to_string(),
pod_name: "test".to_string(),
diff --git a/rust/personhog-leader/tests/common/mod.rs b/rust/personhog-leader/tests/common/mod.rs
index cbf6d7806c18..eddb8536bbe0 100644
--- a/rust/personhog-leader/tests/common/mod.rs
+++ b/rust/personhog-leader/tests/common/mod.rs
@@ -184,6 +184,7 @@ pub fn test_kafka_config() -> KafkaConfig {
kafka_producer_topic_metadata_refresh_interval_ms: None,
kafka_producer_message_max_bytes: None,
kafka_producer_sticky_partitioning_linger_ms: None,
+ kafka_producer_partitioner: None,
}
}
@@ -238,6 +239,7 @@ pub async fn create_local_kafka_producer() -> FutureProducer<KafkaContext> {
kafka_producer_topic_metadata_refresh_interval_ms: None,
kafka_producer_message_max_bytes: None,
kafka_producer_sticky_partitioning_linger_ms: None,
+ kafka_producer_partitioner: None,
};
create_kafka_producer(&config, handle)
.await
diff --git a/rust/personhog-writer/tests/common/mod.rs b/rust/personhog-writer/tests/common/mod.rs
index cb79d10dd628..5819d73a5b8b 100644
--- a/rust/personhog-writer/tests/common/mod.rs
+++ b/rust/personhog-writer/tests/common/mod.rs
@@ -60,6 +60,7 @@ pub async fn create_local_kafka_producer() -> FutureProducer<KafkaContext> {
kafka_producer_topic_metadata_refresh_interval_ms: None,
kafka_producer_message_max_bytes: None,
kafka_producer_sticky_partitioning_linger_ms: None,
+ kafka_producer_partitioner: None,
};
common_kafka::kafka_producer::create_kafka_producer(&config, handle)
.await