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.

chore(personhog): add kafka feed parity e2e across person backends (#117749)

José Sequeirac193bdc494f4
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.yml
index 82be9c2579b4..b7af18e11411 100644
--- a/.github/workflows/ci-nodejs.yml
+++ b/.github/workflows/ci-nodejs.yml
@@ -64,6 +64,8 @@ jobs:
pull-requests: read
outputs:
nodejs: ${{ steps.nodejs-changes.outputs.nodejs || 'true' }}
+ # The e2e job alone, for a personhog crate change that touches no Node source.
+ personhog_e2e: ${{ steps.nodejs-changes.outputs.personhog_e2e || 'false' }}
# Jest selection for the tests job. `mode` is 'selective' only when the diff is
# confined to Node source files jest can resolve; anything else is 'full'.
test_mode: ${{ steps.select-tests.outputs.mode || 'full' }}
@@ -197,6 +199,8 @@ jobs:
RUST_REBUILD_ALL: ${{ steps.rust-affected.outputs.rebuild-all }}
RUST_AFFECTED_CRATES: ${{ steps.rust-affected.outputs.crates }}
RUST_NODE_E2E_CRATES: '["ingestion-consumer"]'
+ # The Kafka parity e2e spawns identity and the publisher through the harness.
+ RUST_PERSONHOG_E2E_CRATES: '["personhog-identity", "personhog-test-harness"]'
run: |
# `schedule` alongside `push`: the paths filter is skipped on both, so
# NODEJS_CHANGED is empty there. Without this the hourly run would decide
@@ -221,6 +225,11 @@ jobs:
echo "nodejs=true" >> "$GITHUB_OUTPUT"
exit 0
fi
+
+ # Not the whole Node matrix for these: only the e2e job reads this output.
+ if echo "${RUST_AFFECTED_CRATES:-[]}" | jq -e --argjson e2e_crates "$RUST_PERSONHOG_E2E_CRATES" '. as $affected | any($e2e_crates[]; . as $crate | $affected | index($crate) != null)' >/dev/null; then
+ echo "personhog_e2e=true" >> "$GITHUB_OUTPUT"
+ fi
fi
echo "nodejs=false" >> "$GITHUB_OUTPUT"
@@ -749,7 +758,7 @@ jobs:
rust_ingestion_e2e:
# Not on master push — master coverage comes from the hourly run (see `schedule`).
- if: needs.changes.outputs.nodejs == 'true' && github.event_name != 'push'
+ if: (needs.changes.outputs.nodejs == 'true' || needs.changes.outputs.personhog_e2e == 'true') && github.event_name != 'push'
name: Rust ingestion consumer Node API e2e (depot-ubuntu-24.04-4)
needs: changes
runs-on: depot-ubuntu-24.04-4
@@ -860,8 +869,8 @@ jobs:
install-command: pnpm --filter=@posthog/nodejs... install --frozen-lockfile
token: ${{ steps.setup-gh-token.outputs.token || github.token }}
- - name: Wait for Clickhouse, Redis, Kafka
- run: docker compose -f docker-compose.dev.yml up kafka redis7 clickhouse maildev -d --wait
+ - name: Wait for Clickhouse, Redis, Kafka, etcd
+ run: docker compose -f docker-compose.dev.yml up kafka redis7 clickhouse maildev etcd -d --wait
- name: Create Kafka topics
run: docker compose -f docker-compose.dev.yml up kafka-init
@@ -936,6 +945,18 @@ jobs:
working-directory: rust
run: cargo build -p ingestion-consumer
+ # The Kafka parity test spawns this stack through the harness's `stack`
+ # subcommand; building it here keeps the spawn out of the test's clock.
+ # Keyed on the test file, as the e2e step is: a branch that predates
+ # the test has neither the file nor its package script.
+ - name: Pre-build the personhog stack and harness
+ run: |
+ if [ -f nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.ts ]; then
+ cd rust && cargo build -p personhog-replica -p personhog-router -p personhog-leader -p personhog-writer -p personhog-identity -p personhog-test-harness
+ else
+ echo "Kafka parity e2e test is not present on this branch; skipping the stack build."
+ fi
+
- name: Test Rust ingestion consumer with Node ingestion API
env:
DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/test_posthog'
@@ -952,6 +973,36 @@ jobs:
echo "Rust ingestion service e2e test is not present on this branch; skipping."
fi
+ # Both person backends run the same creates, attaches and merges; the test
+ # compares the clickhouse_person_distinct_id and person_merge_events feeds
+ # they produce. The personhog side is the harness-spawned stack built above.
+ - name: Test Kafka parity between the Postgres and personhog person backends
+ env:
+ DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/test_posthog'
+ BEHAVIORAL_COHORTS_DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/test_behavioral_cohorts'
+ PERSONS_DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/test_persons'
+ PERSONS_READONLY_DATABASE_URL: 'postgres://posthog:posthog@localhost:5432/test_persons'
+ REDIS_URL: 'redis://localhost'
+ NODE_OPTIONS: '--max_old_space_size=4096'
+ LOG_LEVEL: ${{ runner.debug == '1' && 'info' || 'error' }}
+ run: |
+ if [ -f nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.ts ]; then
+ cd nodejs && pnpm run test:personhog-kafka-parity-e2e
+ else
+ echo "Kafka parity e2e test is not present on this branch; skipping."
+ fi
+
+ # The spawned stack logs each service under the target directory;
+ # the test's failure message only carries their tails.
+ - name: Upload personhog stack logs
+ if: failure()
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: personhog-kafka-parity-logs
+ path: rust/target/debug/harness-logs/
+ if-no-files-found: ignore
+ retention-days: 7
+
- name: Output logs on failure
if: failure()
run: |
diff --git a/nodejs/package.json b/nodejs/package.json
index 6d32878d01ff..e22d8b644293 100644
--- a/nodejs/package.json
+++ b/nodejs/package.json
@@ -12,6 +12,7 @@
"test:serial": "SHARD_IDX=${SHARD_INDEX:-1}; SHARD_TOTAL=${SHARD_COUNT:-1}; echo serial $SHARD_IDX/$SHARD_TOTAL; JEST_JUNIT_OUTPUT_NAME=${JEST_JUNIT_OUTPUT_NAME%.xml}-serial.xml jest --config jest.serial.config.js --runInBand --forceExit --shard=$SHARD_IDX/$SHARD_TOTAL --testPathIgnorePatterns='postgres-parity|service-e2e|<rootDir>/(src|tests)(/.*)?/dev/'",
"test:parallel": "SHARD_IDX=${SHARD_INDEX:-1}; SHARD_TOTAL=${SHARD_COUNT:-1}; echo parallel $SHARD_IDX/$SHARD_TOTAL; JEST_JUNIT_OUTPUT_NAME=${JEST_JUNIT_OUTPUT_NAME%.xml}-parallel.xml jest --config jest.config.js --maxWorkers=4 --passWithNoTests --forceExit --shard=$SHARD_IDX/$SHARD_TOTAL --testPathIgnorePatterns='postgres-parity|service-e2e|<rootDir>/(src|tests)(/.*)?/dev/'",
"test:rust-ingestion-e2e": "if [ -f tests/service-e2e/rust-ingestion-consumer.serial.test.ts ]; then jest --config jest.serial.config.js --runInBand --forceExit --testPathPatterns='service-e2e/rust-ingestion-consumer.serial.test.ts'; else jest --runInBand --forceExit --testPathPatterns='service-e2e/rust-ingestion-consumer.test.ts'; fi",
+ "test:personhog-kafka-parity-e2e": "jest --config jest.serial.config.js --runInBand --forceExit --testPathPatterns='service-e2e/personhog-kafka-parity.serial.test.ts'",
"test:postgres-parity": "jest --runInBand --forceExit --testPathPatterns='postgres-parity'",
"start": "pnpm start:dev",
"start:dist": "node dist/index.js",
diff --git a/nodejs/tests/helpers/kafka.ts b/nodejs/tests/helpers/kafka.ts
index 15ffca6e7388..9e60ffe600f3 100644
--- a/nodejs/tests/helpers/kafka.ts
+++ b/nodejs/tests/helpers/kafka.ts
@@ -127,3 +127,31 @@ export async function ensureKafkaTopics(
await createTopicsWithClient(client, topics)
client.disconnect()
}
+
+/**
+ * Delete topics a test created for itself, per-test or per-run names only:
+ * a shared topic deleted here pulls the output out from under whatever else
+ * is mid-test. A local broker has a partition budget, so topics left behind
+ * eventually stop every suite from creating more.
+ */
+export async function deleteKafkaTopics(
+ topics: string[],
+ extraServerConfig?: Partial<PluginsServerConfig>
+): Promise<void> {
+ const client = AdminClient.create(buildKafkaConfig(extraServerConfig))
+ try {
+ for (const topic of topics) {
+ await new Promise<void>((resolve, reject) => {
+ client.deleteTopic(topic, 10_000, (error: LibrdKafkaError) => {
+ if (error && error.code !== CODES.ERRORS.ERR_UNKNOWN_TOPIC_OR_PART) {
+ reject(error)
+ } else {
+ resolve()
+ }
+ })
+ })
+ }
+ } finally {
+ client.disconnect()
+ }
+}
diff --git a/nodejs/tests/helpers/service-process.ts b/nodejs/tests/helpers/service-process.ts
index c81b139cf053..12842fb3e9a0 100644
--- a/nodejs/tests/helpers/service-process.ts
+++ b/nodejs/tests/helpers/service-process.ts
@@ -99,7 +99,8 @@ export class ServiceProcess {
return { ...result, output: this.getOutput() }
}
- async stop(): Promise<void> {
+ /** SIGTERM, then SIGKILL once `graceMs` passes without an exit. */
+ async stop(graceMs = 10_000): Promise<void> {
if (this.stopping || this.hasExited) {
return
}
@@ -107,7 +108,7 @@ export class ServiceProcess {
this.stopping = true
this.kill('SIGTERM')
- const stopped = await Promise.race([this.exited.then(() => true), delay(10_000).then(() => false)])
+ const stopped = await Promise.race([this.exited.then(() => true), delay(graceMs).then(() => false)])
if (!stopped) {
this.kill('SIGKILL')
await this.exited
@@ -118,6 +119,11 @@ export class ServiceProcess {
return this.output
}
+ /** The exit, once the process has exited; null while it runs. */
+ exitInfo(): ProcessExit | null {
+ return this.exitResult ? { ...this.exitResult, output: this.getOutput() } : null
+ }
+
private capture(stream: 'stdout' | 'stderr', chunk: Buffer): void {
this.output += `[${this.name}:${stream}] ${chunk.toString()}`
if (this.output.length > OUTPUT_BUFFER_LIMIT) {
diff --git a/nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.ts b/nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.ts
new file mode 100644
index 000000000000..60969a01840a
--- /dev/null
+++ b/nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.ts
@@ -0,0 +1,843 @@
+// Serial e2e: the Kafka feeds behind the two person backends, compared from
+// the real ingestion path. The Rust ingestion consumer feeds a Node ingestion
+// API worker whose persons store runs in shadow mode, so the Postgres backend
+// produces clickhouse_person_distinct_id rows and person_merge_events the way
+// the pipeline does in production, while identity applies the same writes
+// and personhog-publisher drains its outbox to per-run topics.
+//
+// The feeds are compared by end state, not message by message: the two
+// backends can take different paths to the same place, and versions,
+// timestamps, counts and order are each backend's own. clickhouse_person is
+// not compared, the publisher does not project it.
+import { ConsumerGlobalConfig, KafkaConsumer, LibrdKafkaError, Message, Metadata, WatermarkOffsets } from 'node-rdkafka'
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import net from 'node:net'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { Pool } from 'pg'
+
+import {
+ KAFKA_APP_METRICS_2,
+ KAFKA_CLICKHOUSE_AI_EVENTS_JSON,
+ KAFKA_CLICKHOUSE_FLAG_EVALUATIONS,
+ KAFKA_CLICKHOUSE_HEATMAP_EVENTS,
+ KAFKA_CLICKHOUSE_TOPHOG,
+ KAFKA_EVENTS_JSON,
+ KAFKA_EVENTS_PLUGIN_INGESTION,
+ KAFKA_EVENTS_PLUGIN_INGESTION_ASYNC,
+ KAFKA_EVENTS_PLUGIN_INGESTION_DLQ,
+ KAFKA_EVENTS_PLUGIN_INGESTION_OVERFLOW,
+ KAFKA_GROUPS,
+ KAFKA_INGESTION_WARNINGS,
+ KAFKA_LOG_ENTRIES,
+ KAFKA_PERSON,
+ KAFKA_PERSON_DISTINCT_ID,
+ KAFKA_PERSON_MERGE_EVENTS,
+ KAFKA_REALTIME_ONLY_EVENTS_JSON,
+} from '~/common/config/kafka-topics'
+import { KafkaProducerWrapper } from '~/common/kafka/producer'
+import { closeHub, createHub } from '~/common/utils/db/hub'
+import { parseJSON } from '~/common/utils/json-parse'
+import { UUIDT } from '~/common/utils/utils'
+import { uuidFromDistinctId } from '~/ingestion/common/persons/person-uuid'
+import { Hub } from '~/types'
+
+import { waitForExpect } from '../helpers/expectations'
+import { DEFAULT_TEAM, EventBuilder, createKafkaMessage } from '../helpers/ingestion-e2e'
+import { TEST_KAFKA_TOPICS, createKafkaTestTopicName, deleteKafkaTopics, ensureKafkaTopics } from '../helpers/kafka'
+import { ServiceProcess, getFreePort } from '../helpers/service-process'
+import { createOrganization, createTeam } from '../helpers/sql'
+
+jest.setTimeout(300_000)
+
+const REPO_ROOT = path.resolve(__dirname, '../../..')
+const NODEJS_ROOT = path.join(REPO_ROOT, 'nodejs')
+const RUST_ROOT = path.join(REPO_ROOT, 'rust')
+// Built binaries, not `cargo run`: nothing may compile under the test's clock.
+const RUST_BIN_DIR = path.join(process.env.CARGO_TARGET_DIR ?? path.join(RUST_ROOT, 'target'), 'debug')
+const HARNESS_BINARY = path.join(RUST_BIN_DIR, 'personhog-test-harness')
+const ETCD_ENDPOINTS = process.env.PERSONHOG_E2E_ETCD_ENDPOINTS ?? 'http://localhost:2379'
+// The table set the stack runs on; identity pairs the outbox with it.
+const PG_TARGET_TABLE = 'personhog_person_tmp'
+const OUTBOX_TABLE = 'person_publish_outbox_tmp'
+// The worker serves its WorkerIngest stream on its HTTP port plus this
+// offset; the Rust consumer derives the stream address the same way.
+const GRPC_PORT_OFFSET = 1
+const STACK_READY_TIMEOUT_MS = 180_000
+// The stack stops a dozen services and deletes its topics on the way out.
+const STACK_STOP_GRACE_MS = 60_000
+const SETTLE_TIMEOUT_MS = 30_000
+const FEED_CONVERGENCE_TIMEOUT_MS = 30_000
+const TOPIC_READ_TIMEOUT_MS = 30_000
+
+/** The ready line the harness's `stack` subcommand writes. */
+interface StackReady {
+ router_addr: string
+ identity_addr: string
+ changelog_topic: string
+ distinct_ids_topic: string
+ merge_events_topic: string
+ log_dir: string
+}
+
+interface DistinctIdRow {
+ person_id: string
+ team_id: number
+ distinct_id: string
+ version: number
+ is_deleted: number
+}
+
+interface MergeEvent {
+ team_id: number
+ old_person_uuid: string
+ new_person_uuid: string
+}
+
+interface FeedTopics {
+ distinctIds: string
+ mergeEvents: string
+}
+
+interface Mapping {
+ personUuid: string
+ isDeleted: boolean
+}
+
+/** The end state a consumer of a feed is left with. */
+interface FeedState {
+ /** The highest-version row per distinct id. */
+ mappings: Record<string, Mapping>
+ /** Every person the feed named, followed through its merge events to the one holding its state at the end. */
+ survivors: Record<string, string>
+}
+
+type TestEvent = ReturnType<EventBuilder['build']>
+type Register = (service: ServiceProcess) => void
+
+describe('personhog kafka parity (e2e)', () => {
+ let hub: Hub
+ let kafkaProducer: KafkaProducerWrapper
+ let stack: ServiceProcess | undefined
+ let workers: ServiceProcess[] = []
+ let workerUrl: string
+ let readyDir: string
+ let inputTopic: string
+ /** Every topic this run created, the stack's included, deleted at the end. */
+ let ownTopics: string[] = []
+ let nodeTopics: FeedTopics
+ let personhogTopics: FeedTopics
+ let personsDb: Pool
+ let teamId: number
+ let token: string
+
+ const services = (): ServiceProcess[] => (stack ? [stack, ...workers] : workers)
+
+ // Distinct ids are unique per run: the personhog side writes shared
+ // tables, so a fixed id would meet a person a previous run made.
+ const runTag = new UUIDT().toString().slice(0, 13)
+ const id = (name: string): string => `kafka-parity-${runTag}-${name}`
+ const personUuid = (distinctId: string): string => uuidFromDistinctId(teamId, distinctId)
+ const live = (distinctId: string): Mapping => ({ personUuid: personUuid(distinctId), isDeleted: false })
+
+ const event = (name: string, distinctId: string, properties: Record<string, unknown> = {}): TestEvent =>
+ new EventBuilder({ ...DEFAULT_TEAM, id: teamId, api_token: token }, distinctId)
+ .withEvent(name)
+ .withProperties(properties)
+ .build()
+ const pageview = (distinctId: string): TestEvent => event('$pageview', distinctId)
+ const identify = (distinctId: string, anonDistinctId?: string): TestEvent =>
+ event('$identify', distinctId, anonDistinctId ? { $anon_distinct_id: anonDistinctId } : {})
+
+ const send = async (...events: TestEvent[]): Promise<void> => {
+ for (const entry of events) {
+ const message = createKafkaMessage(entry, token)
+ // Capture sets a uuid header; the consumer reads it before the body.
+ const headers = [...(message.headers ?? []), { uuid: Buffer.from(entry.uuid ?? '') }]
+ await kafkaProducer.produce({
+ topic: inputTopic,
+ key: message.key?.toString() ?? null,
+ value: message.value ?? null,
+ headers: Object.fromEntries(
+ headers.flatMap((header) => Object.entries(header).map(([name, value]) => [name, value.toString()]))
+ ),
+ })
+ }
+ await kafkaProducer.flush()
+ }
+
+ const feedState = async (topics: FeedTopics): Promise<FeedState> =>
+ foldFeed(
+ await readTopic(hub.KAFKA_HOSTS, topics.distinctIds),
+ await readTopic(hub.KAFKA_HOSTS, topics.mergeEvents),
+ teamId
+ )
+
+ const serviceLogs = (): string =>
+ services()
+ .map((service) => service.getOutput().slice(-6_000))
+ .join('\n')
+
+ /**
+ * Gives up at once when a spawned service has exited, since nothing
+ * changes after that, and attaches the services' logs to a failure: they
+ * are subprocesses, so those logs are the only trace.
+ */
+ const pollUntil = async (check: () => Promise<void>, timeoutMs: number): Promise<void> => {
+ const deadline = Date.now() + timeoutMs
+ for (;;) {
+ try {
+ await check()
+ return
+ } catch (error) {
+ const exit = services()
+ .map((service) => service.exitInfo())
+ .find((info) => info !== null)
+ if (exit) {
+ throw new Error(
+ `a service exited (${exit.exitCode ?? exit.signal}) while waiting:\n${exit.output.slice(-6_000)}`
+ )
+ }
+ if (Date.now() > deadline) {
+ throw new Error(`${error instanceof Error ? error.message : String(error)}\n\n${serviceLogs()}`)
+ }
+ await new Promise((resolve) => setTimeout(resolve, 500))
+ }
+ }
+ }
+
+ /**
+ * Waits for both feeds to hold what an earlier step produced. The worker
+ * runs a batch's distinct ids concurrently, so a scenario whose premise
+ * is "this person exists" has to see the person land before it sends the
+ * event that depends on it, and on both sides, so a swallowed shadow
+ * write cannot turn the next step into a different scenario.
+ */
+ const awaitBoth = (check: (feed: FeedState) => void): Promise<void> =>
+ pollUntil(async () => {
+ check(await feedState(nodeTopics))
+ check(await feedState(personhogTopics))
+ }, SETTLE_TIMEOUT_MS)
+
+ /**
+ * Both feeds fill asynchronously, the personhog one behind the outbox
+ * drain, so the end states are polled until they agree and the last
+ * mismatch is what a timeout reports.
+ */
+ const expectFeedParity = async (settled: (feed: FeedState) => void): Promise<FeedState> => {
+ await awaitBoth(settled)
+ let node!: FeedState
+ await pollUntil(async () => {
+ node = await feedState(nodeTopics)
+ expectSameEndState(await feedState(personhogTopics), node)
+ }, FEED_CONVERGENCE_TIMEOUT_MS)
+ return node
+ }
+
+ beforeAll(async () => {
+ hub = await createHub({})
+ kafkaProducer = await KafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)
+ inputTopic = createKafkaTestTopicName(KAFKA_EVENTS_PLUGIN_INGESTION)
+ const outputTopics = {
+ events: createKafkaTestTopicName(KAFKA_EVENTS_JSON),
+ persons: createKafkaTestTopicName(KAFKA_PERSON),
+ distinctIds: createKafkaTestTopicName(KAFKA_PERSON_DISTINCT_ID),
+ warnings: createKafkaTestTopicName(KAFKA_INGESTION_WARNINGS),
+ mergeEvents: createKafkaTestTopicName(KAFKA_PERSON_MERGE_EVENTS),
+ }
+ nodeTopics = { distinctIds: outputTopics.distinctIds, mergeEvents: outputTopics.mergeEvents }
+ ownTopics = [inputTopic, ...Object.values(outputTopics)]
+ await ensureKafkaTopics([...TEST_KAFKA_TOPICS, ...ownTopics])
+
+ const organizationId = await createOrganization(hub.postgres)
+ token = `kafka-parity-${runTag}`
+ teamId = await createTeam(hub.postgres, organizationId, token)
+ personsDb = new Pool({ connectionString: hub.PERSONS_DATABASE_URL, max: 2 })
+
+ // Each service registers as soon as it is spawned, so one that never
+ // becomes ready is still stopped in afterAll.
+ readyDir = mkdtempSync(path.join(tmpdir(), 'personhog-kafka-parity-'))
+ const ready = await startPersonhogStack(hub, path.join(readyDir, 'ready.json'), (service) => {
+ stack = service
+ })
+ ownTopics.push(ready.changelog_topic, ready.distinct_ids_topic, ready.merge_events_topic)
+ personhogTopics = { distinctIds: ready.distinct_ids_topic, mergeEvents: ready.merge_events_topic }
+
+ workerUrl = await startNodeIngestionApiWorker(
+ hub,
+ {
+ INGESTION_CONSUMER_CONSUME_TOPIC: inputTopic,
+ INGESTION_OUTPUT_EVENTS_TOPIC: outputTopics.events,
+ INGESTION_OUTPUT_PERSONS_TOPIC: outputTopics.persons,
+ INGESTION_OUTPUT_PERSON_DISTINCT_IDS_TOPIC: outputTopics.distinctIds,
+ INGESTION_OUTPUT_INGESTION_WARNINGS_TOPIC: outputTopics.warnings,
+ INGESTION_OUTPUT_PERSON_MERGE_EVENTS_TOPIC: outputTopics.mergeEvents,
+ PERSONS_STORE_MODE: 'shadow',
+ PERSONHOG_ADDR: ready.router_addr,
+ PERSONHOG_IDENTITY_ADDR: ready.identity_addr,
+ PERSON_MERGE_EVENTS_ENABLED: 'true',
+ // ensureKafkaTopics creates one-partition topics, and Node
+ // partitions merge events itself.
+ PERSON_MERGE_EVENTS_PARTITION_COUNT: '1',
+ PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '*',
+ },
+ (service) => workers.push(service)
+ )
+ await startRustIngestionConsumer(hub, inputTopic, workerUrl, (service) => workers.push(service))
+ }, 600_000)
+
+ afterAll(async () => {
+ // The consumer first, so no batch is mid-flight when its worker goes;
+ // the stack last, with time to tear itself down.
+ for (const worker of workers.reverse()) {
+ await worker.stop()
+ }
+ workers = []
+ await stack?.stop(STACK_STOP_GRACE_MS)
+ stack = undefined
+ await Promise.allSettled([personsDb?.end(), kafkaProducer?.disconnect()])
+ // The stack deletes its own topics on a clean exit; this also covers
+ // one that was cut short, and the broker counts every partition.
+ await deleteKafkaTopics(ownTopics)
+ if (readyDir) {
+ rmSync(readyDir, { recursive: true, force: true })
+ }
+ if (hub) {
+ await closeHub(hub)
+ }
+ })
+
+ it('a new distinct id lands as one person on both feeds', async () => {
+ const visitor = id('visitor')
+
+ await send(pageview(visitor))
+
+ await expectFeedParity((feed) => {
+ expect(feed.mappings[visitor]).toEqual(live(visitor))
+ })
+ })
+
+ it('an identify of two unseen ids births one person on both feeds', async () => {
+ const anon = id('birth-anon')
+ const user = id('birth-user')
+
+ await send(identify(user, anon))
+
+ await expectFeedParity((feed) => {
+ expect(feed.mappings[user]).toEqual(live(user))
+ expect(feed.mappings[anon]).toEqual(live(user))
+ })
+ })
+
+ it.each([
+ ['$identify', (existing: string, unseen: string) => identify(unseen, existing)],
+ ['$create_alias', (existing: string, unseen: string) => event('$create_alias', existing, { alias: unseen })],
+ ])('%s attaches an unseen id to an existing person on both feeds', async (name, attach) => {
+ const existing = id(`${name}-existing`)
+ const unseen = id(`${name}-unseen`)
+ await send(pageview(existing))
+ await awaitBoth((feed) => expect(feed.mappings[existing]).toEqual(live(existing)))
+
+ await send(attach(existing, unseen))
+
+ await expectFeedParity((feed) => {
+ expect(feed.mappings[unseen]).toEqual(live(existing))
+ })
+ })
+
+ it('identifies that merge existing persons leave each merged person resolving to the survivor', async () => {
+ const user = id('merge-user')
+ const anons = [id('merge-anon-1'), id('merge-anon-2')]
+ await send(pageview(user), ...anons.map(pageview))
+ await awaitBoth((feed) => {
+ for (const distinctId of [user, ...anons]) {
+ expect(feed.mappings[distinctId]).toEqual(live(distinctId))
+ }
+ })
+
+ await send(identify(user, anons[0]))
+ await awaitBoth((feed) => expect(feed.survivors[personUuid(anons[0])]).toBe(personUuid(user)))
+ await send(identify(user, anons[1]))
+
+ const { mappings } = await expectFeedParity((feed) => {
+ for (const anon of anons) {
+ expect(feed.survivors[personUuid(anon)]).toBe(personUuid(user))
+ }
+ })
+ for (const anon of anons) {
+ expect(mappings[anon]).toEqual(live(user))
+ }
+ })
+
+ it('a merge dangerously of two identified persons moves the alias to the keeper on both feeds', async () => {
+ const keeper = id('dangerous-keeper')
+ const alias = id('dangerous-alias')
+ // An identify with an anonymous id is what marks a person identified;
+ // without one the merge below would be an ordinary one.
+ await send(identify(keeper, id('dangerous-keeper-anon')), identify(alias, id('dangerous-alias-anon')))
+ await awaitBoth((feed) => {
+ expect(feed.mappings[keeper]).toEqual(live(keeper))
+ expect(feed.mappings[alias]).toEqual(live(alias))
+ })
+
+ await send(event('$merge_dangerously', keeper, { alias }))
+
+ const { mappings } = await expectFeedParity((feed) => {
+ expect(feed.survivors[personUuid(alias)]).toBe(personUuid(keeper))
+ })
+ expect(mappings[alias]).toEqual(live(keeper))
+ })
+
+ it('a repeated identify adds no merge on either feed', async () => {
+ const anon = id('again-anon')
+ const user = id('again-user')
+ const marker = id('again-marker')
+ await send(pageview(anon), pageview(user))
+ await awaitBoth((feed) => {
+ expect(feed.mappings[anon]).toEqual(live(anon))
+ expect(feed.mappings[user]).toEqual(live(user))
+ })
+ await send(identify(user, anon))
+ const before = await expectFeedParity((feed) => {
+ expect(feed.survivors[personUuid(anon)]).toBe(personUuid(user))
+ })
+
+ // The second identify finds both ids on one person. The alias after
+ // it shares the user's lane, so its row landing means the identify ran.
+ await send(identify(user, anon), event('$create_alias', user, { alias: marker }))
+
+ const after = await expectFeedParity((feed) => {
+ expect(feed.mappings[marker]).toEqual(live(user))
+ })
+ expect(after.survivors).toEqual(before.survivors)
+ expect(after.mappings).toEqual({ ...before.mappings, [marker]: live(user) })
+ })
+
+ it('an identify through an identified anonymous id gives the unseen id its own person on both feeds', async () => {
+ const anon = id('refuse-anon')
+ const user = id('refuse-user')
+ const other = id('refuse-other')
+ await send(pageview(anon), pageview(user))
+ await awaitBoth((feed) => {
+ expect(feed.mappings[anon]).toEqual(live(anon))
+ expect(feed.mappings[user]).toEqual(live(user))
+ })
+ await send(identify(user, anon))
+ const before = await expectFeedParity((feed) => {
+ expect(feed.survivors[personUuid(anon)]).toBe(personUuid(user))
+ })
+
+ // The user is identified now, so the unseen id may not join its
+ // person: both backends refuse the merge and create a person for it.
+ await send(identify(other, user))
+
+ const after = await expectFeedParity((feed) => {
+ expect(feed.mappings[other]).toEqual(live(other))
+ })
+ expect(after.survivors).toEqual({ ...before.survivors, [personUuid(other)]: personUuid(other) })
+ expect(after.mappings[user]).toEqual(before.mappings[user])
+ })
+
+ it('the outbox drains and the feeds still agree', async () => {
+ await waitForExpect(
+ async () => {
+ const { rows } = await personsDb.query<{ pending: string }>(
+ `SELECT count(*)::text AS pending FROM ${OUTBOX_TABLE} WHERE team_id = $1`,
+ [teamId]
+ )
+ expect(rows[0].pending).toBe('0')
+ },
+ TOPIC_READ_TIMEOUT_MS,
+ 250
+ )
+
+ await expectFeedParity(() => {})
+ })
+
+ it('every shadow write reached personhog', async () => {
+ // Shadow mode swallows a failed personhog write by design; the
+ // comparison above tolerates the different path such a failure can
+ // leave, so the counter is the only place it shows.
+ const response = await workers[0].request(`${workerUrl}/_metrics`, { method: 'GET' })
+ expect(response.statusCode).toBe(200)
+ const errors = response.body
+ .split('\n')
+ .filter((line) => line.startsWith('personhog_store_shadow_errors_total'))
+ .map((line) => Number(line.trim().split(/\s+/).pop()))
+ .reduce((sum, value) => sum + value, 0)
+ expect(errors).toBe(0)
+ })
+})
+
+/**
+ * The same end state on both feeds. A person only one feed ever named is
+ * that feed's own path to the result, a stub the other backend never made
+ * and then merged away, and it carries no state on the other side; every
+ * person both feeds named has to end in the same place.
+ */
+function expectSameEndState(personhog: FeedState, node: FeedState): void {
+ expect(personhog.mappings).toEqual(node.mappings)
+ const shared = Object.keys(node.survivors).filter((person) => person in personhog.survivors)
+ const pick = (survivors: Record<string, string>): Record<string, string> =>
+ Object.fromEntries(shared.map((person) => [person, survivors[person]]))
+ expect(pick(personhog.survivors)).toEqual(pick(node.survivors))
+ for (const feed of [node, personhog]) {
+ expectEveryPersonAccountedFor(feed)
+ }
+}
+
+/**
+ * A person that holds no live distinct id at the end must have been merged
+ * into one that does, and a live distinct id must not point at a person
+ * that was merged away.
+ */
+function expectEveryPersonAccountedFor(feed: FeedState): void {
+ const liveMappings = Object.values(feed.mappings).filter((mapping) => !mapping.isDeleted)
+ const holders = new Set(liveMappings.map((mapping) => mapping.personUuid))
+ const unaccounted = Object.entries(feed.survivors)
+ .filter(([, survivor]) => !holders.has(survivor))
+ .map(([person, survivor]) => `${person} -> ${survivor}`)
+ expect(unaccounted).toEqual([])
+ const stale = liveMappings
+ .filter((mapping) => feed.survivors[mapping.personUuid] !== mapping.personUuid)
+ .map((mapping) => `${mapping.personUuid} -> ${feed.survivors[mapping.personUuid]}`)
+ expect(stale).toEqual([])
+}
+
+async function startPersonhogStack(hub: Hub, readyFile: string, register: Register): Promise<StackReady> {
+ if (!existsSync(HARNESS_BINARY)) {
+ throw new Error(`${HARNESS_BINARY} is missing; build the personhog stack and harness first`)
+ }
+ const service = new ServiceProcess(
+ 'personhog-stack',
+ HARNESS_BINARY,
+ [
+ 'stack',
+ '--publish',
+ '--bin-dir',
+ RUST_BIN_DIR,
+ '--pg-target-table',
+ PG_TARGET_TABLE,
+ '--persons-db-url',
+ hub.PERSONS_DATABASE_URL,
+ '--kafka-hosts',
+ hub.KAFKA_HOSTS,
+ '--etcd-endpoints',
+ ETCD_ENDPOINTS,
+ '--ready-file',
+ readyFile,
+ ],
+ { cwd: RUST_ROOT, env: serviceProcessEnv() }
+ )
+ register(service)
+ const deadline = Date.now() + STACK_READY_TIMEOUT_MS
+ while (!existsSync(readyFile)) {
+ const exit = await service.waitForExit(250).catch(() => null)
+ if (exit) {
+ throw new Error(
+ `personhog stack exited before it was ready (${exit.exitCode ?? exit.signal}):\n${exit.output}`
+ )
+ }
+ if (Date.now() > deadline) {
+ throw new Error(`personhog stack not ready within ${STACK_READY_TIMEOUT_MS}ms:\n${service.getOutput()}`)
+ }
+ }
+ return parseJSON(readFileSync(readyFile, 'utf8')) as StackReady
+}
+
+async function startNodeIngestionApiWorker(
+ hub: Hub,
+ extraEnv: Record<string, string>,
+ register: Register
+): Promise<string> {
+ const port = await getFreeWorkerPort()
+ const service = new ServiceProcess('node-worker', 'pnpm', ['exec', 'tsx', 'src/index.ts'], {
+ cwd: NODEJS_ROOT,
+ env: {
+ ...serviceProcessEnv(),
+ ...dependencyEnv(hub),
+ NODE_ENV: 'dev',
+ PLUGIN_SERVER_MODE: 'ingestion-api',
+ HTTP_SERVER_PORT: port.toString(),
+ INGESTION_API_GRPC_PORT: (port + GRPC_PORT_OFFSET).toString(),
+ OTEL_SDK_DISABLED: 'true',
+ DISABLE_OPENTELEMETRY_TRACING: 'true',
+ LOG_LEVEL: 'warn',
+ INGESTION_WORKER_CONCURRENT_BATCHES: '1',
+ PROPERTY_DEFS_WRITE_DISABLED: 'true',
+ PROPERTY_DEFS_CONSUMER_ENABLED_TEAMS: '',
+ // The worker verifies every output topic at startup, so the ones
+ // this test never reads point at the shared test topics.
+ INGESTION_CONSUMER_DLQ_TOPIC: KAFKA_EVENTS_PLUGIN_INGESTION_DLQ,
+ INGESTION_CONSUMER_OVERFLOW_TOPIC: KAFKA_EVENTS_PLUGIN_INGESTION_OVERFLOW,
+ INGESTION_OUTPUT_DLQ_TOPIC: KAFKA_EVENTS_PLUGIN_INGESTION_DLQ,
+ INGESTION_OUTPUT_OVERFLOW_TOPIC: KAFKA_EVENTS_PLUGIN_INGESTION_OVERFLOW,
+ INGESTION_OUTPUT_ASYNC_TOPIC: KAFKA_EVENTS_PLUGIN_INGESTION_ASYNC,
+ INGESTION_OUTPUT_AI_EVENTS_TOPIC: KAFKA_CLICKHOUSE_AI_EVENTS_JSON,
+ INGESTION_OUTPUT_FLAG_EVALUATIONS_TOPIC: KAFKA_CLICKHOUSE_FLAG_EVALUATIONS,
+ INGESTION_OUTPUT_REALTIME_ONLY_EVENTS_TOPIC: KAFKA_REALTIME_ONLY_EVENTS_JSON,
+ INGESTION_OUTPUT_HEATMAPS_TOPIC: KAFKA_CLICKHOUSE_HEATMAP_EVENTS,
+ INGESTION_OUTPUT_GROUPS_TOPIC: KAFKA_GROUPS,
+ INGESTION_OUTPUT_APP_METRICS_TOPIC: KAFKA_APP_METRICS_2,
+ INGESTION_OUTPUT_LOG_ENTRIES_TOPIC: KAFKA_LOG_ENTRIES,
+ INGESTION_OUTPUT_TOPHOG_TOPIC: KAFKA_CLICKHOUSE_TOPHOG,
+ ...extraEnv,
+ },
+ })
+ register(service)
+ const url = `http://127.0.0.1:${port}`
+ await service.waitForHttpOk(`${url}/_ready`)
+ return url
+}
+
+async function startRustIngestionConsumer(
+ hub: Hub,
+ inputTopic: string,
+ workerUrl: string,
+ register: Register
+): Promise<void> {
+ const metricsPort = await getFreePort()
+ const service = new ServiceProcess('rust-consumer', path.join(RUST_BIN_DIR, 'ingestion-consumer'), [], {
+ cwd: RUST_ROOT,
+ env: {
+ ...serviceProcessEnv(),
+ RUST_LOG: 'info',
+ KAFKA_HOSTS: hub.KAFKA_HOSTS,
+ INGESTION_CONSUMER_CONSUME_TOPIC: inputTopic,
+ INGESTION_CONSUMER_GROUP_ID: `personhog-kafka-parity-${Date.now()}-${Math.random().toString(16).slice(2)}`,
+ // Rust's generic KAFKA_CONSUMER_* parser maps this name to the invalid rdkafka key "offset.reset".
+ KAFKA_CONSUMER_OFFSET_RESET: undefined,
+ KAFKA_CONSUMER_AUTO_OFFSET_RESET: 'earliest',
+ CONSUMER_BATCH_SIZE: '10',
+ CONSUMER_BATCH_TIMEOUT_MS: '1000',
+ CONSUMER_MAX_BACKGROUND_TASKS: '1',
+ INGESTION_WORKER_CONCURRENT_BATCHES: '1',
+ WORKER_ADDRESSES: workerUrl,
+ INGESTION_WORKER_GRPC_PORT_OFFSET: GRPC_PORT_OFFSET.toString(),
+ BIND_HOST: '127.0.0.1',
+ BIND_PORT: metricsPort.toString(),
+ EXPORT_PROMETHEUS: 'true',
+ },
+ })
+ register(service)
+ await service.waitForHttpOk(`http://127.0.0.1:${metricsPort}/_readiness`)
+}
+
+function serviceProcessEnv(): NodeJS.ProcessEnv {
+ const env = { ...process.env }
+ delete env.NODE_OPTIONS
+ delete env.VSCODE_INSPECTOR_OPTIONS
+ // Inherited from an editor's extension host, it makes node-gyp-build
+ // look for Electron builds of native modules the worker loads.
+ delete env.ELECTRON_RUN_AS_NODE
+ return env
+}
+
+/** The hub resolved these from the environment; the worker must see the same ones. */
+function dependencyEnv(hub: Hub): NodeJS.ProcessEnv {
+ return {
+ DATABASE_URL: hub.DATABASE_URL,
+ PERSONS_DATABASE_URL: hub.PERSONS_DATABASE_URL,
+ PERSONS_READONLY_DATABASE_URL: hub.PERSONS_READONLY_DATABASE_URL,
+ BEHAVIORAL_COHORTS_DATABASE_URL: hub.BEHAVIORAL_COHORTS_DATABASE_URL,
+ KAFKA_HOSTS: hub.KAFKA_HOSTS,
+ KAFKA_PRODUCER_METADATA_BROKER_LIST: hub.KAFKA_HOSTS,
+ KAFKA_WARPSTREAM_PRODUCER_METADATA_BROKER_LIST: hub.KAFKA_HOSTS,
+ KAFKA_INGESTION_PRODUCER_METADATA_BROKER_LIST: hub.KAFKA_HOSTS,
+ REDIS_URL: hub.REDIS_URL,
+ SITE_URL: 'https://example.com',
+ }
+}
+
+// A worker needs two adjacent free ports: HTTP, and HTTP + GRPC_PORT_OFFSET for the stream.
+async function getFreeWorkerPort(): Promise<number> {
+ for (let attempt = 0; attempt < 20; attempt++) {
+ const port = await getFreePort()
+ if (await isPortFree(port + GRPC_PORT_OFFSET)) {
+ return port
+ }
+ }
+ throw new Error('could not find adjacent free ports for a worker')
+}
+
+function isPortFree(port: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ const server = net.createServer()
+ server.once('error', () => resolve(false))
+ server.listen(port, '127.0.0.1', () => server.close(() => resolve(true)))
+ })
+}
+
+function foldFeed(distinctIdRows: Buffer[], mergeEvents: Buffer[], teamId: number): FeedState {
+ const latest = new Map<string, DistinctIdRow>()
+ const persons = new Set<string>()
+ for (const value of distinctIdRows) {
+ const row = parseJSON(value.toString()) as DistinctIdRow
+ if (row.team_id !== teamId) {
+ continue
+ }
+ persons.add(row.person_id)
+ const seen = latest.get(row.distinct_id)
+ if (
+ seen &&
+ seen.version === row.version &&
+ (seen.person_id !== row.person_id || seen.is_deleted !== row.is_deleted)
+ ) {
+ // A ReplacingMergeTree keeps either of two rows at one version, so
+ // such a feed has no single final state to compare.
+ throw new Error(
+ `two rows at version ${row.version} for ${row.distinct_id}: ${JSON.stringify(seen)} and ${JSON.stringify(row)}`
+ )
+ }
+ if (!seen || row.version > seen.version) {
+ latest.set(row.distinct_id, row)
+ }
+ }
+
+ const mergedInto = new Map<string, string>()
+ for (const value of mergeEvents) {
+ const merge = parseJSON(value.toString()) as MergeEvent
+ if (merge.team_id !== teamId) {
+ continue
+ }
+ const already = mergedInto.get(merge.old_person_uuid)
+ if (already && already !== merge.new_person_uuid) {
+ throw new Error(`${merge.old_person_uuid} merged into both ${already} and ${merge.new_person_uuid}`)
+ }
+ mergedInto.set(merge.old_person_uuid, merge.new_person_uuid)
+ persons.add(merge.old_person_uuid)
+ persons.add(merge.new_person_uuid)
+ }
+
+ return {
+ mappings: Object.fromEntries(
+ [...latest.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([distinctId, row]) => [
+ distinctId,
+ { personUuid: row.person_id, isDeleted: row.is_deleted === 1 },
+ ])
+ ),
+ survivors: Object.fromEntries([...persons].sort().map((person) => [person, survivorOf(person, mergedInto)])),
+ }
+}
+
+function survivorOf(person: string, mergedInto: Map<string, string>): string {
+ const visited = new Set<string>()
+ let current = person
+ while (mergedInto.has(current)) {
+ if (visited.has(current)) {
+ throw new Error(`merge events loop through ${current}`)
+ }
+ visited.add(current)
+ current = mergedInto.get(current)!
+ }
+ return current
+}
+
+/**
+ * Every message on the topic up to each partition's high watermark at the
+ * time of the call. Per partition, not by count: a producer still writing
+ * to one partition must not stand in for messages owed by another.
+ */
+async function readTopic(kafkaHosts: string, topic: string): Promise<Buffer[]> {
+ const consumer = new KafkaConsumer(
+ {
+ 'client.id': 'personhog-kafka-parity-e2e',
+ 'group.id': `personhog-kafka-parity-${Date.now()}-${Math.random().toString(16).slice(2)}`,
+ 'metadata.broker.list': kafkaHosts,
+ 'enable.auto.commit': false,
+ 'auto.offset.reset': 'earliest',
+ log_level: 4,
+ } as ConsumerGlobalConfig,
+ {}
+ )
+ await new Promise<void>((resolve, reject) => {
+ consumer.once('ready', () => resolve())
+ consumer.once('event.error', (error) => reject(error))
+ consumer.connect()
+ })
+ try {
+ const partitions = await topicPartitions(consumer, topic)
+ const watermarks = await Promise.all(
+ partitions.map(async (partition) => ({
+ partition,
+ ...(await watermarkOffsets(consumer, topic, partition)),
+ }))
+ )
+ const owed = new Map(
+ watermarks
+ .filter((entry) => entry.highOffset > entry.lowOffset)
+ .map((entry) => [entry.partition, entry.highOffset - entry.lowOffset])
+ )
+ if (owed.size === 0) {
+ return []
+ }
+ consumer.assign(
+ watermarks
+ .filter((entry) => owed.has(entry.partition))
+ .map((entry) => ({ topic, partition: entry.partition, offset: entry.lowOffset }))
+ )
+
+ const values: Buffer[] = []
+ const deadline = Date.now() + TOPIC_READ_TIMEOUT_MS
+ while (owed.size > 0 && Date.now() < deadline) {
+ // Exactly what is still owed: a larger ask makes the consumer
+ // wait out its timeout instead of returning what it has.
+ const messages = await consumeMessages(
+ consumer,
+ [...owed.values()].reduce((sum, left) => sum + left, 0)
+ )
+ if (messages.length === 0) {
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ }
+ for (const message of messages) {
+ const left = owed.get(message.partition)
+ if (left === undefined) {
+ continue
+ }
+ values.push(message.value ?? Buffer.alloc(0))
+ if (left === 1) {
+ owed.delete(message.partition)
+ } else {
+ owed.set(message.partition, left - 1)
+ }
+ }
+ }
+ if (owed.size > 0) {
+ throw new Error(`partitions ${[...owed.keys()].join(', ')} of ${topic} did not reach their watermark`)
+ }
+ return values
+ } finally {
+ await new Promise<void>((resolve, reject) =>
+ consumer.disconnect((error) => (error ? reject(error) : resolve()))
+ )
+ }
+}
+
+async function topicPartitions(consumer: KafkaConsumer, topic: string): Promise<number[]> {
+ const metadata = await new Promise<Metadata>((resolve, reject) => {
+ consumer.getMetadata({ topic, timeout: 10_000 }, (error: LibrdKafkaError, result: Metadata) =>
+ error ? reject(error) : resolve(result)
+ )
+ })
+ const found = metadata.topics.find((entry) => entry.name === topic)
+ if (!found) {
+ throw new Error(`Kafka topic ${topic} was not found in metadata`)
+ }
+ return found.partitions.map((partition) => partition.id)
+}
+
+async function watermarkOffsets(consumer: KafkaConsumer, topic: string, partition: number): Promise<WatermarkOffsets> {
+ return await new Promise((resolve, reject) => {
+ consumer.queryWatermarkOffsets(topic, partition, 10_000, (error: LibrdKafkaError, offsets: WatermarkOffsets) =>
+ error ? reject(error) : resolve(offsets)
+ )
+ })
+}
+
+async function consumeMessages(consumer: KafkaConsumer, count: number): Promise<Message[]> {
+ return await new Promise((resolve, reject) => {
+ consumer.consume(count, (error, messages) => (error ? reject(error) : resolve(messages)))
+ })
+}
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 5e666ba85292..7547aa948e8b 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9121,6 +9121,7 @@ dependencies = [
"rustls 0.23.37",
"serde_json",
"sqlx",
+ "tempfile",
"tokio",
"tonic 0.12.3",
"tracing",
diff --git a/rust/personhog-test-harness/Cargo.toml b/rust/personhog-test-harness/Cargo.toml
index dfd59d307a58..e61abbd1fd78 100644
--- a/rust/personhog-test-harness/Cargo.toml
+++ b/rust/personhog-test-harness/Cargo.toml
@@ -32,5 +32,8 @@ tracing = { workspace = true }
tracing-subscriber = { workspace = true }
uuid = { workspace = true }
+[dev-dependencies]
+tempfile = "3"
+
[lints]
workspace = true
diff --git a/rust/personhog-test-harness/README.md b/rust/personhog-test-harness/README.md
index 2e1dad8efbb3..7333467156d1 100644
--- a/rust/personhog-test-harness/README.md
+++ b/rust/personhog-test-harness/README.md
@@ -272,6 +272,19 @@ A leader refuses requests it cannot safely serve — a write against a fenced pa
The router should absorb them instead: detect the not-owned refusal in the raw-proxy response (a typed header from the leader, not status-code matching), and re-stash the request if a handoff is in flight for the partition, else re-resolve the owner and retry once.
Most of the gate's residual failed writes during handoff scenarios are these refusals; with the redirect in place those counts become hard zero-failure invariants.
+## `stack` — hold a stack for another test runner
+
+`stack` brings up the same isolated stack the gate uses, with the identity service and, under `--publish`, the publishers and their per-run topics, then holds it until SIGTERM or Ctrl-C and tears it down.
+It is the fixture behind tests in other languages that need the real stack without re-implementing its orchestration: the Node service e2e test `nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.ts` spawns it and compares the Kafka feeds the Postgres and personhog backends produce.
+
+```bash
+target/debug/personhog-test-harness stack --publish --ready-file /tmp/personhog-stack.json
+```
+
+Once the stack is up it prints one line, `PERSONHOG_STACK_READY {…}`, and writes the same JSON to `--ready-file` when given: the router and identity addresses as `host:port`, the persons database URL and table set, the changelog topic and the two publish topics, and the log directory.
+A parent process should wait for the file rather than parse stdout, which the logs share.
+A spawned service that exits ends the command with that service's last log lines, so a fixture never stays up over a dead stack.
+
## `seed` / `cleanup` — manage traffic targets
```bash
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index a5234024c0ce..54a410f9898f 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -46,6 +46,10 @@ pub enum Command {
/// seeds, and every database operation is confined to the configured
/// validation table.
Traffic(Box<TrafficArgs>),
+ /// Bring up the isolated stack the gate uses, print where it listens
+ /// and which topics it publishes to as one JSON line, and hold it until
+ /// SIGTERM or Ctrl-C. A fixture for tests in other languages.
+ Stack(StackArgs),
}
#[derive(Args, Clone)]
@@ -428,6 +432,53 @@ pub struct GateArgs {
pub bin_dir: Option<PathBuf>,
}
+#[derive(Args, Clone)]
+pub struct StackArgs {
+ #[arg(long, default_value_t = 1)]
+ pub leaders: u32,
+
+ #[arg(long, default_value_t = 1)]
+ pub routers: u32,
+
+ #[arg(long, default_value_t = 4)]
+ pub partitions: u32,
+
+ #[arg(long, default_value = DEFAULT_PERSONS_DB_URL)]
+ pub persons_db_url: String,
+
+ /// The table set every spawned service uses; see GateArgs.
+ #[arg(long, default_value = "personhog_person_tmp")]
+ pub pg_target_table: String,
+
+ #[arg(long, default_value = "localhost:9092")]
+ pub kafka_hosts: String,
+
+ #[arg(long, default_value = "http://localhost:2379")]
+ pub etcd_endpoints: String,
+
+ /// Also run publisher replicas draining the identity outbox to two
+ /// per-run topics, named in the ready line.
+ #[arg(long, default_value_t = false)]
+ pub publish: bool,
+
+ #[arg(long, default_value_t = 2)]
+ pub publishers: u32,
+
+ #[arg(long, default_value_t = 100)]
+ pub publish_rows_per_pass: i64,
+
+ /// Also write the ready line's JSON to this file once the stack is up.
+ /// A parent process polls for the file instead of parsing stdout,
+ /// which the logs share.
+ #[arg(long)]
+ pub ready_file: Option<PathBuf>,
+
+ /// Directory containing the service binaries. Defaults to the
+ /// workspace target directory for this build profile.
+ #[arg(long)]
+ pub bin_dir: Option<PathBuf>,
+}
+
#[derive(Args, Clone)]
pub struct TrafficArgs {
/// Router serving the personhog stack under continuous test.
diff --git a/rust/personhog-test-harness/src/main.rs b/rust/personhog-test-harness/src/main.rs
index 619a1b0da6d2..a4acf20acf2b 100644
--- a/rust/personhog-test-harness/src/main.rs
+++ b/rust/personhog-test-harness/src/main.rs
@@ -43,5 +43,6 @@ async fn main() -> Result<()> {
Command::Consistency(args) => scenarios::consistency::run(args).await,
Command::Gate(args) => scenarios::gate::run(*args).await,
Command::Traffic(args) => scenarios::traffic::run(*args).await,
+ Command::Stack(args) => scenarios::stack_cmd::run(args).await,
}
}
diff --git a/rust/personhog-test-harness/src/publish.rs b/rust/personhog-test-harness/src/publish.rs
index 4d798e4b0111..eb5dbec5b3a6 100644
--- a/rust/personhog-test-harness/src/publish.rs
+++ b/rust/personhog-test-harness/src/publish.rs
@@ -66,6 +66,35 @@ pub struct ExpectedMerges {
pub ids: HashMap<Uuid, i64>,
}
+/// Pending outbox rows the stack's publishers would claim: every team's,
+/// because the claim is not scoped, minus `except_team` when a run owns
+/// one. Publishers started over someone else's rows drain them onto the
+/// run's own topics and delete them with the teardown.
+pub async fn pending_outbox_rows(
+ pool: &PgPool,
+ outbox_table: &str,
+ except_team: Option<i32>,
+) -> Result<i64> {
+ let count = match except_team {
+ Some(team) => {
+ sqlx::query_scalar(&format!(
+ "SELECT count(*) FROM {outbox_table} WHERE given_up_at IS NULL AND team_id <> $1"
+ ))
+ .bind(team)
+ .fetch_one(pool)
+ .await
+ }
+ None => {
+ sqlx::query_scalar(&format!(
+ "SELECT count(*) FROM {outbox_table} WHERE given_up_at IS NULL"
+ ))
+ .fetch_one(pool)
+ .await
+ }
+ };
+ count.context("counting pending outbox rows")
+}
+
/// Poll until no row of the team is pending in the outbox, or the deadline
/// passes. A parked row (`given_up_at`) is a violation: only an operator
/// sets it, so a spawned stack must have none. A row the publisher could
diff --git a/rust/personhog-test-harness/src/scenarios/gate.rs b/rust/personhog-test-harness/src/scenarios/gate.rs
index 650072d47c23..8839b80532fb 100644
--- a/rust/personhog-test-harness/src/scenarios/gate.rs
+++ b/rust/personhog-test-harness/src/scenarios/gate.rs
@@ -137,7 +137,7 @@ fn chaos_timeline(args: &GateArgs) -> Vec<(Duration, ChaosEvent)> {
/// attacker-influenceable — and the harness only ever runs sibling
/// binaries produced by the same cargo build; `--bin-dir` overrides for
/// anything else.
-fn default_bin_dir() -> PathBuf {
+pub(crate) fn default_bin_dir() -> PathBuf {
let profile = if cfg!(debug_assertions) {
"debug"
} else {
@@ -263,13 +263,8 @@ pub async fn run(args: GateArgs) -> Result<()> {
.context("cleaning the publish outbox")?;
// The publishers claim every team's rows, so another team's pending
// rows would drain onto this run's topics and vanish with them.
- let foreign_pending: i64 = sqlx::query_scalar(&format!(
- "SELECT count(*) FROM {outbox_table} WHERE given_up_at IS NULL AND team_id <> $1"
- ))
- .bind(args.team_id as i32)
- .fetch_one(&pool)
- .await
- .context("counting other teams' outbox rows")?;
+ let foreign_pending =
+ publish::pending_outbox_rows(&pool, outbox_table, Some(args.team_id as i32)).await?;
if foreign_pending > 0 {
bail!(
"{foreign_pending} pending outbox rows belong to other teams and the harness \
diff --git a/rust/personhog-test-harness/src/scenarios/mod.rs b/rust/personhog-test-harness/src/scenarios/mod.rs
index 1f8e50943605..615bfbc12ed3 100644
--- a/rust/personhog-test-harness/src/scenarios/mod.rs
+++ b/rust/personhog-test-harness/src/scenarios/mod.rs
@@ -4,4 +4,5 @@ pub mod consistency;
pub mod gate;
pub mod merge;
pub mod seed_cmd;
+pub mod stack_cmd;
pub mod traffic;
diff --git a/rust/personhog-test-harness/src/scenarios/stack_cmd.rs b/rust/personhog-test-harness/src/scenarios/stack_cmd.rs
new file mode 100644
index 000000000000..438e135f2ee0
--- /dev/null
+++ b/rust/personhog-test-harness/src/scenarios/stack_cmd.rs
@@ -0,0 +1,183 @@
+//! `stack`: bring up the isolated personhog stack the gate uses, print where
+//! it listens and which topics it publishes to, then hold it until SIGTERM
+//! or Ctrl-C and tear it down. For tests in other languages, the Node
+//! service e2e tests among them, which need the real stack behind a fixture
+//! they can spawn and stop, without re-implementing its orchestration.
+
+use std::path::Path;
+use std::time::Duration;
+
+use anyhow::{bail, Context, Result};
+use serde_json::json;
+use sqlx::postgres::PgPool;
+use tokio::signal::unix::{signal, Signal, SignalKind};
+
+use crate::cli::StackArgs;
+use crate::publish;
+use crate::scenarios::gate::default_bin_dir;
+use crate::seed;
+use crate::stack::{PublishConfig, Stack, StackConfig};
+
+/// Prefix of the one stdout line a parent process can wait for. The logs
+/// share stdout, so the marker is what makes the JSON findable.
+pub const READY_MARKER: &str = "PERSONHOG_STACK_READY ";
+
+/// A dead child must end the command instead of leaving a silent stack
+/// behind a fixture that still looks up.
+const LIVENESS_INTERVAL: Duration = Duration::from_secs(1);
+
+pub async fn run(args: StackArgs) -> Result<()> {
+ seed::validate_table_name(&args.pg_target_table)?;
+ if args.publish && args.publishers == 0 {
+ bail!("--publishers must be at least 1 with --publish");
+ }
+ if args.publish && args.publish_rows_per_pass <= 0 {
+ bail!("--publish-rows-per-pass must be positive");
+ }
+ if let Some(path) = &args.ready_file {
+ refuse_stale_ready_file(path)?;
+ }
+ if args.publish {
+ // The publishers claim every team's rows, so a pending row from
+ // anyone else would drain onto this run's topics and vanish with them.
+ let outbox_table = seed::publish_outbox_table_for(&args.pg_target_table);
+ let pool = PgPool::connect(&args.persons_db_url)
+ .await
+ .context("connecting to persons DB")?;
+ let pending = publish::pending_outbox_rows(&pool, outbox_table, None).await?;
+ pool.close().await;
+ if pending > 0 {
+ bail!(
+ "{pending} pending outbox rows are already in {outbox_table} and the stack's \
+ publishers would drain them onto this run's topics; clear the table or use a \
+ dedicated persons database for --publish"
+ );
+ }
+ }
+ // Both registered before anything spawns: a SIGTERM or Ctrl-C during
+ // bring-up then waits for the teardown below instead of killing the
+ // harness outright, with the per-run topics left behind.
+ let mut terminate =
+ signal(SignalKind::terminate()).context("installing the SIGTERM handler")?;
+ let mut interrupt = signal(SignalKind::interrupt()).context("installing the SIGINT handler")?;
+ let bin_dir = args.bin_dir.clone().unwrap_or_else(default_bin_dir);
+ let mut stack = Stack::up(StackConfig {
+ bin_dir,
+ leaders: args.leaders,
+ routers: args.routers,
+ partitions: args.partitions,
+ kafka_hosts: args.kafka_hosts.clone(),
+ etcd_endpoints: args.etcd_endpoints.clone(),
+ persons_db_url: args.persons_db_url.clone(),
+ writer_flush_interval_ms: 1000,
+ pg_target_table: args.pg_target_table.clone(),
+ cache_memory_capacity: 16_777_216,
+ extra_leader_env: Vec::new(),
+ recovery_pool_size: 16,
+ leader_lease_ttl: 30,
+ spawn_identity: true,
+ publish: args.publish.then_some(PublishConfig {
+ publishers: args.publishers,
+ rows_per_pass: args.publish_rows_per_pass,
+ }),
+ })
+ .await?;
+
+ let topics = stack.publish_topics();
+ // The Node clients take `host:port` and add the scheme themselves.
+ let ready = json!({
+ "router_addr": strip_scheme(&stack.router_url),
+ "identity_addr": stack.identity_url.as_deref().map(strip_scheme),
+ "pg_target_table": args.pg_target_table,
+ // Every per-run topic, so a parent can clean up after a teardown
+ // it had to cut short.
+ "changelog_topic": stack.changelog_topic(),
+ "distinct_ids_topic": topics.map(|t| t.distinct_ids.clone()),
+ "merge_events_topic": topics.map(|t| t.merge_events.clone()),
+ "log_dir": stack.log_dir.display().to_string(),
+ });
+ println!("{READY_MARKER}{ready}");
+ let announced = match &args.ready_file {
+ Some(path) => write_ready_file(path, &ready.to_string()),
+ None => Ok(()),
+ };
+
+ let held = match announced {
+ Ok(()) => hold(&mut stack, &mut terminate, &mut interrupt).await,
+ Err(e) => Err(e),
+ };
+ let down = stack.down().await;
+ let cleared = match &args.ready_file {
+ Some(path) => remove_ready_file(path),
+ None => Ok(()),
+ };
+ held.and(down).and(cleared)
+}
+
+async fn hold(stack: &mut Stack, terminate: &mut Signal, interrupt: &mut Signal) -> Result<()> {
+ let mut liveness = tokio::time::interval(LIVENESS_INTERVAL);
+ loop {
+ tokio::select! {
+ _ = interrupt.recv() => return Ok(()),
+ _ = terminate.recv() => return Ok(()),
+ _ = liveness.tick() => stack.check_alive()?,
+ }
+ }
+}
+
+/// A file from an earlier run would satisfy a parent's existence check
+/// before this stack is up, naming topics that run already deleted.
+fn refuse_stale_ready_file(path: &Path) -> Result<()> {
+ if path.exists() {
+ bail!(
+ "the ready file {} already exists; remove it, or pass a path no earlier run used",
+ path.display()
+ );
+ }
+ Ok(())
+}
+
+fn remove_ready_file(path: &Path) -> Result<()> {
+ match std::fs::remove_file(path) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e).with_context(|| format!("removing the ready file {}", path.display())),
+ }
+}
+
+/// Written whole or not at all: the reader treats the file's existence as
+/// the ready signal, so it must never see a partial write.
+fn write_ready_file(path: &Path, contents: &str) -> Result<()> {
+ let tmp = path.with_extension("tmp");
+ std::fs::write(&tmp, contents)
+ .with_context(|| format!("writing the ready file {}", tmp.display()))?;
+ std::fs::rename(&tmp, path)
+ .with_context(|| format!("moving the ready file into place at {}", path.display()))
+}
+
+fn strip_scheme(url: &str) -> &str {
+ url.split_once("://").map_or(url, |(_, rest)| rest)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{refuse_stale_ready_file, remove_ready_file, strip_scheme, write_ready_file};
+
+ #[test]
+ fn strip_scheme_leaves_host_and_port() {
+ assert_eq!(strip_scheme("http://127.0.0.1:5000"), "127.0.0.1:5000");
+ assert_eq!(strip_scheme("127.0.0.1:5000"), "127.0.0.1:5000");
+ }
+
+ #[test]
+ fn a_ready_file_is_refused_while_it_exists_and_gone_after_the_run() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("ready.json");
+ refuse_stale_ready_file(&path).expect("nothing written yet");
+ write_ready_file(&path, "{}").unwrap();
+ assert!(refuse_stale_ready_file(&path).is_err());
+ remove_ready_file(&path).unwrap();
+ assert!(!path.exists());
+ remove_ready_file(&path).expect("a missing file is not an error");
+ }
+}
diff --git a/rust/personhog-test-harness/src/stack/kafka.rs b/rust/personhog-test-harness/src/stack/kafka.rs
index 38cf5a1bdf97..360056a46f41 100644
--- a/rust/personhog-test-harness/src/stack/kafka.rs
+++ b/rust/personhog-test-harness/src/stack/kafka.rs
@@ -49,6 +49,22 @@ pub async fn create_topic(kafka_hosts: &str, topic: &str, partitions: u32) -> Re
Ok(())
}
+/// Create every topic or none: a topic left behind by a failed bring-up
+/// counts against the broker's partition budget until someone notices.
+pub async fn create_topics(kafka_hosts: &str, topics: &[(&str, u32)]) -> Result<()> {
+ for (index, (topic, partitions)) in topics.iter().enumerate() {
+ if let Err(e) = create_topic(kafka_hosts, topic, *partitions).await {
+ for (created, _) in &topics[..index] {
+ if let Err(cleanup) = delete_topic(kafka_hosts, created).await {
+ tracing::warn!(topic = created, error = %cleanup, "failed to clean up topic");
+ }
+ }
+ return Err(e);
+ }
+ }
+ Ok(())
+}
+
pub async fn delete_topic(kafka_hosts: &str, topic: &str) -> Result<()> {
let admin = admin_client(kafka_hosts)?;
let options = AdminOptions::new().operation_timeout(Some(Duration::from_secs(10)));
diff --git a/rust/personhog-test-harness/src/stack/mod.rs b/rust/personhog-test-harness/src/stack/mod.rs
index 32d54670e524..b19109563990 100644
--- a/rust/personhog-test-harness/src/stack/mod.rs
+++ b/rust/personhog-test-harness/src/stack/mod.rs
@@ -204,29 +204,16 @@ impl Stack {
let store = etcd::connect(&config.etcd_endpoints, ETCD_PREFIX).await?;
etcd::reset(&store, config.partitions).await?;
- kafka::create_topic(&config.kafka_hosts, &topic, config.partitions).await?;
- let publish_topics = match &config.publish {
- Some(_) => {
- let topics = PublishTopics {
- distinct_ids: format!("{topic}_distinct_ids"),
- merge_events: format!("{topic}_merge_events"),
- };
- kafka::create_topic(
- &config.kafka_hosts,
- &topics.distinct_ids,
- PUBLISH_TOPIC_PARTITIONS,
- )
- .await?;
- kafka::create_topic(
- &config.kafka_hosts,
- &topics.merge_events,
- PUBLISH_TOPIC_PARTITIONS,
- )
- .await?;
- Some(topics)
- }
- None => None,
- };
+ let publish_topics = config.publish.as_ref().map(|_| PublishTopics {
+ distinct_ids: format!("{topic}_distinct_ids"),
+ merge_events: format!("{topic}_merge_events"),
+ });
+ let mut topics = vec![(topic.as_str(), config.partitions)];
+ if let Some(publish) = &publish_topics {
+ topics.push((publish.distinct_ids.as_str(), PUBLISH_TOPIC_PARTITIONS));
+ topics.push((publish.merge_events.as_str(), PUBLISH_TOPIC_PARTITIONS));
+ }
+ kafka::create_topics(&config.kafka_hosts, &topics).await?;
let mut infra = Vec::new();
@@ -691,6 +678,10 @@ impl Stack {
Ok(())
}
+ pub fn changelog_topic(&self) -> &str {
+ &self.topic
+ }
+
pub fn publish_topics(&self) -> Option<&PublishTopics> {
self.publish_topics.as_ref()
}