OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ralph(P1-006): Consumer contract: at-least-once - bounded retry, DLQ topic, failure counters
ralphd7444e7f9575
diff --git a/apps/worker/src/jobs/events.kafka-consumer.test.ts b/apps/worker/src/jobs/events.kafka-consumer.test.tsnew file mode 100644index 000000000..4c0d6c9d6--- /dev/null+++ b/apps/worker/src/jobs/events.kafka-consumer.test.ts@@ -0,0 +1,403 @@+/**+ * Delivery contract of the Kafka events consumer (ADR-004): at-least-once.+ * An offset is resolved once its message has been handled, dead-lettered, or+ * deliberately skipped — never merely because it failed.+ *+ * The batch handler is exercised directly with injected dependencies; the+ * broker, the metrics registry and `incomingEvent` are all out of the picture.+ */++import type {+ DeadLetterMessage,+ EachBatchPayload,+ KafkaMessage,+} from '@openpanel/queue';+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../metrics', () => ({+ kafkaReprocessedTotal: { inc: vi.fn() },+ kafkaHandlerFailuresTotal: { inc: vi.fn() },+ kafkaDeadLetteredTotal: { inc: vi.fn() },+ kafkaDeadLetterFailedTotal: { inc: vi.fn() },+}));+vi.mock('./events.incoming-event', () => ({ incomingEvent: vi.fn() }));+vi.mock('../utils/logger', () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++import {+ createEventsBatchHandler,+ type EventsBatchHandlerDeps,+} from './events.kafka-consumer';++const PARTITION = 7;+const TOPIC = 'events';++const payloadFor = (offset: number) => ({+ projectId: `project-${offset}`,+ event: { name: 'screen_view' },+});++const message = (+ offset: number,+ key: string | null,+ value: string = JSON.stringify(payloadFor(offset))+): KafkaMessage =>+ ({+ key: key === null ? null : Buffer.from(key),+ value: value === '' ? null : Buffer.from(value),+ offset: String(offset),+ timestamp: '0',+ attributes: 0,+ headers: {},+ size: 0,+ }) as unknown as KafkaMessage;++function makeBatch(+ messages: KafkaMessage[],+ options: { isRunning?: () => boolean; isStale?: () => boolean } = {}+) {+ const resolveOffset = vi.fn();+ const heartbeat = vi.fn().mockResolvedValue(undefined);+ const payload = {+ batch: { topic: TOPIC, partition: PARTITION, messages },+ resolveOffset,+ heartbeat,+ isRunning: options.isRunning ?? (() => true),+ isStale: options.isStale ?? (() => false),+ } as unknown as EachBatchPayload;+ return { payload, resolveOffset, heartbeat };+}++const resolvedOffsets = (resolveOffset: ReturnType<typeof vi.fn>): string[] =>+ resolveOffset.mock.calls.map(([offset]) => offset as string);++function makeDeps(overrides: Partial<EventsBatchHandlerDeps> = {}) {+ const metrics = {+ reprocessed: vi.fn(),+ handlerFailed: vi.fn(),+ deadLettered: vi.fn(),+ deadLetterFailed: vi.fn(),+ };+ const deps: Partial<EventsBatchHandlerDeps> = {+ handleEvent: vi.fn().mockResolvedValue(undefined),+ sendToDeadLetter: vi.fn().mockResolvedValue(undefined),+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ onActivity: vi.fn(),+ topic: TOPIC,+ maxAttempts: 3,+ initialRetryMs: 10,+ maxRetryMs: 25,+ sleep: vi.fn().mockResolvedValue(undefined),+ ...overrides,+ metrics: { ...metrics, ...overrides.metrics },+ };+ return {+ deps,+ metrics: deps.metrics as typeof metrics,+ handleEvent: deps.handleEvent as ReturnType<typeof vi.fn>,+ sendToDeadLetter: deps.sendToDeadLetter as ReturnType<typeof vi.fn>,+ sleep: deps.sleep as ReturnType<typeof vi.fn>,+ };+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('offset walk', () => {+ it('resolves the whole contiguous prefix in ascending order', async () => {+ const { deps } = makeDeps();+ const handler = createEventsBatchHandler(deps);+ // Two interleaved key-groups: they run concurrently, so completion order+ // is not offset order — the walk must still resolve 0..3 ascending.+ const { payload, resolveOffset } = makeBatch([+ message(0, 'a'),+ message(1, 'b'),+ message(2, 'a'),+ message(3, 'b'),+ ]);++ await handler.eachBatch(payload);++ expect(resolvedOffsets(resolveOffset)).toEqual(['0', '1', '2', '3']);+ });++ it('stops at the first gap, even when later offsets did finish', async () => {+ // Keys 'a' (0, 2, 4) and 'b' (1, 3, 5) run concurrently. 'a' is held on+ // its first message until 'b' has finished all of its own, then the+ // consumer stops — so 3 and 5 are processed while 2 never runs. Resolving+ // them would ack offset 2 as well (last-write-wins) and lose it.+ let running = true;+ let releaseA = (): void => undefined;+ const bFinished = new Promise<void>((resolve) => {+ releaseA = resolve;+ });+ const { deps, handleEvent } = makeDeps();+ handleEvent.mockImplementation(async (p: { projectId: string }) => {+ if (p.projectId === 'project-0') {+ await bFinished;+ running = false;+ }+ if (p.projectId === 'project-5') {+ releaseA();+ }+ });+ const handler = createEventsBatchHandler(deps);+ const { payload, resolveOffset } = makeBatch(+ [+ message(0, 'a'),+ message(1, 'b'),+ message(2, 'a'),+ message(3, 'b'),+ message(4, 'a'),+ message(5, 'b'),+ ],+ { isRunning: () => running }+ );++ await handler.eachBatch(payload);++ const handled = handleEvent.mock.calls.map(+ ([p]) => (p as { projectId: string }).projectId+ );+ expect(handled).toContain('project-5');+ expect(handled).not.toContain('project-2');+ expect(resolvedOffsets(resolveOffset)).toEqual(['0', '1']);+ });++ it('resolves nothing when the batch is stale before the first message', async () => {+ const { deps, handleEvent } = makeDeps();+ const handler = createEventsBatchHandler(deps);+ const { payload, resolveOffset } = makeBatch(+ [message(0, 'a'), message(1, 'a')],+ { isStale: () => true }+ );++ await handler.eachBatch(payload);++ expect(handleEvent).not.toHaveBeenCalled();+ expect(resolveOffset).not.toHaveBeenCalled();+ });+});++describe('kill consumer mid-batch', () => {+ it('loses no event: every unresolved offset is left for redelivery', async () => {+ const KILL_AFTER = 3;+ const TOTAL = 8;+ let handled = 0;+ let running = true;+ const { deps, handleEvent } = makeDeps();+ handleEvent.mockImplementation(async () => {+ handled += 1;+ if (handled >= KILL_AFTER) {+ running = false;+ }+ });+ const handler = createEventsBatchHandler(deps);+ // One key: strictly serial, so "killed after N" is deterministic.+ const messages = Array.from({ length: TOTAL }, (_, i) => message(i, 'a'));+ const { payload, resolveOffset } = makeBatch(messages, {+ isRunning: () => running,+ });++ await handler.eachBatch(payload);++ expect(handled).toBe(KILL_AFTER);+ expect(resolvedOffsets(resolveOffset)).toEqual(['0', '1', '2']);+ // The tail is not acked, so the broker redelivers it from offset 3.+ const unresolved = messages+ .slice(KILL_AFTER)+ .map((m) => m.offset)+ .filter((offset) => !resolvedOffsets(resolveOffset).includes(offset));+ expect(unresolved).toEqual(['3', '4', '5', '6', '7']);+ });+});++describe('handler failure', () => {+ it('retries with bounded backoff before giving up', async () => {+ const { deps, handleEvent, sleep, sendToDeadLetter } = makeDeps({+ maxAttempts: 4,+ });+ handleEvent.mockRejectedValue(new Error('boom'));+ const handler = createEventsBatchHandler(deps);+ const { payload } = makeBatch([message(0, 'a')]);++ await handler.eachBatch(payload);++ expect(handleEvent).toHaveBeenCalledTimes(4);+ // 10 → 20 → 25 (clamped at maxRetryMs), and no sleep after the last try.+ expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([10, 20, 25]);+ expect(sendToDeadLetter).toHaveBeenCalledTimes(1);+ });++ it('stops retrying as soon as the handler succeeds', async () => {+ const { deps, handleEvent, sendToDeadLetter, metrics } = makeDeps();+ handleEvent+ .mockRejectedValueOnce(new Error('transient'))+ .mockResolvedValue(undefined);+ const handler = createEventsBatchHandler(deps);+ const { payload, resolveOffset } = makeBatch([message(0, 'a')]);++ await handler.eachBatch(payload);++ expect(handleEvent).toHaveBeenCalledTimes(2);+ expect(metrics.handlerFailed).toHaveBeenCalledTimes(1);+ expect(sendToDeadLetter).not.toHaveBeenCalled();+ expect(resolvedOffsets(resolveOffset)).toEqual(['0']);+ });++ it('dead-letters the raw message, counts it, and keeps the partition moving', async () => {+ const poison = 'poison-payload';+ const { deps, handleEvent, sendToDeadLetter, metrics } = makeDeps();+ handleEvent.mockImplementation(async (p: { projectId: string }) => {+ if (p.projectId === 'project-1') {+ throw new Error('handler exploded');+ }+ });+ const handler = createEventsBatchHandler(deps);+ const { payload, resolveOffset } = makeBatch([+ message(0, 'a'),+ message(1, 'a', JSON.stringify({ projectId: 'project-1', poison })),+ message(2, 'a'),+ ]);++ await handler.eachBatch(payload);++ const dlq = sendToDeadLetter.mock.calls[0]?.[0] as DeadLetterMessage;+ expect(dlq.reason).toBe('handler_error');+ expect(dlq.offset).toBe('1');+ expect(dlq.partition).toBe(PARTITION);+ expect(dlq.topic).toBe(TOPIC);+ // The raw producer bytes travel untouched, so the message is replayable.+ expect(JSON.parse(dlq.value?.toString() ?? '')).toMatchObject({ poison });++ expect(metrics.deadLettered).toHaveBeenCalledWith(+ String(PARTITION),+ 'handler_error'+ );+ expect(metrics.handlerFailed).toHaveBeenCalledTimes(3);+ // The partition keeps moving: the poison offset and everything after it+ // are still resolved.+ expect(resolvedOffsets(resolveOffset)).toEqual(['0', '1', '2']);+ });++ it('leaves the offset unresolved when the dead-letter produce fails', async () => {+ const { deps, handleEvent, metrics } = makeDeps({+ sendToDeadLetter: vi.fn().mockRejectedValue(new Error('broker down')),+ });+ handleEvent.mockImplementation(async (p: { projectId: string }) => {+ if (p.projectId === 'project-1') {+ throw new Error('handler exploded');+ }+ });+ const handler = createEventsBatchHandler(deps);+ const { payload, resolveOffset } = makeBatch([+ message(0, 'a'),+ message(1, 'a'),+ message(2, 'a'),+ ]);++ await handler.eachBatch(payload);++ expect(metrics.deadLetterFailed).toHaveBeenCalledWith(String(PARTITION));+ // Nothing at or after the failed offset is acked — it is redelivered.+ expect(resolvedOffsets(resolveOffset)).toEqual(['0']);+ });+});++describe('unparseable messages', () => {+ it('dead-letters instead of dropping, without retrying', async () => {+ const { deps, handleEvent, sendToDeadLetter, metrics, sleep } = makeDeps();+ const handler = createEventsBatchHandler(deps);+ const { payload, resolveOffset } = makeBatch([+ message(0, 'a', 'not json at all'),+ ]);++ await handler.eachBatch(payload);++ expect(handleEvent).not.toHaveBeenCalled();+ expect(sleep).not.toHaveBeenCalled();+ expect(metrics.deadLettered).toHaveBeenCalledWith(+ String(PARTITION),+ 'parse_error'+ );+ expect(+ (+ sendToDeadLetter.mock.calls[0]?.[0] as DeadLetterMessage+ ).value?.toString()+ ).toBe('not json at all');+ expect(resolvedOffsets(resolveOffset)).toEqual(['0']);+ });++ it('dead-letters a message with no value at all', async () => {+ const { deps, sendToDeadLetter, metrics } = makeDeps();+ const handler = createEventsBatchHandler(deps);+ const { payload, resolveOffset } = makeBatch([message(0, 'a', '')]);++ await handler.eachBatch(payload);++ expect(sendToDeadLetter).toHaveBeenCalledTimes(1);+ expect(metrics.deadLettered).toHaveBeenCalledWith(+ String(PARTITION),+ 'parse_error'+ );+ expect(resolvedOffsets(resolveOffset)).toEqual(['0']);+ });+});++describe('reprocess counter', () => {+ it('does not fire for intra-batch out-of-order processing', async () => {+ const { deps, metrics } = makeDeps();+ const handler = createEventsBatchHandler(deps);+ const { payload } = makeBatch([+ message(0, 'a'),+ message(1, 'b'),+ message(2, 'a'),+ ]);++ await handler.eachBatch(payload);++ expect(metrics.reprocessed).not.toHaveBeenCalled();+ });++ it('fires once per redelivered offset in a later batch', async () => {+ const { deps, metrics } = makeDeps();+ const handler = createEventsBatchHandler(deps);+ const messages = [message(0, 'a'), message(1, 'a')];++ await handler.eachBatch(makeBatch(messages).payload);+ expect(metrics.reprocessed).not.toHaveBeenCalled();++ await handler.eachBatch(makeBatch(messages).payload);+ expect(metrics.reprocessed).toHaveBeenCalledTimes(2);+ expect(metrics.reprocessed).toHaveBeenCalledWith(String(PARTITION));+ });++ it('does not fire after a rebalance clears the watermarks', async () => {+ const { deps, metrics } = makeDeps();+ const handler = createEventsBatchHandler(deps);+ const messages = [message(0, 'a'), message(1, 'a')];++ await handler.eachBatch(makeBatch(messages).payload);+ handler.resetWatermarks();+ await handler.eachBatch(makeBatch(messages).payload);++ expect(metrics.reprocessed).not.toHaveBeenCalled();+ });++ it('does not fire for a dead-lettered offset re-seen only within the batch', async () => {+ // A dead-lettered offset is resolved, so it must move the watermark just+ // like a handled one — otherwise the next batch would flag it as a+ // reprocess.+ const { deps, handleEvent, metrics } = makeDeps();+ handleEvent.mockRejectedValue(new Error('boom'));+ const handler = createEventsBatchHandler(deps);++ await handler.eachBatch(makeBatch([message(0, 'a')]).payload);+ expect(metrics.reprocessed).not.toHaveBeenCalled();++ await handler.eachBatch(makeBatch([message(1, 'a')]).payload);+ expect(metrics.reprocessed).not.toHaveBeenCalled();+ });+});diff --git a/apps/worker/src/jobs/events.kafka-consumer.ts b/apps/worker/src/jobs/events.kafka-consumer.tsindex 71e2f02d7..0454f7e01 100644--- a/apps/worker/src/jobs/events.kafka-consumer.ts+++ b/apps/worker/src/jobs/events.kafka-consumer.ts@@ -1,12 +1,23 @@import {createKafkaEventsConsumer,+ type DeadLetterMessage,+ type EachBatchPayload,type EventsQueuePayloadIncomingEvent,KAFKA_EVENTS_TOPIC,+ KAFKA_HANDLER_MAX_ATTEMPTS,+ KAFKA_HANDLER_RETRY_INITIAL_MS,+ KAFKA_HANDLER_RETRY_MAX_MS,KAFKA_PARTITIONS_CONCURRENT,- kafkaLogger,type KafkaMessage,+ kafkaLogger,+ produceDeadLetterEvent,} from '@openpanel/queue';-import { kafkaReprocessedTotal } from '../metrics';+import {+ kafkaDeadLetteredTotal,+ kafkaDeadLetterFailedTotal,+ kafkaHandlerFailuresTotal,+ kafkaReprocessedTotal,+} from '../metrics';import { logger } from '../utils/logger';import { markEventsActivity } from '../utils/worker-heartbeat';import { incomingEvent } from './events.incoming-event';@@ -20,16 +31,306 @@ export interface KafkaConsumerHandle {// comfortably under that even for slow handlers.const HEARTBEAT_EVERY = 16;-// Highest Kafka offset we have *resolved* (committed) per `topic-partition`,-// tracked across batches. Used purely for the reprocess detector below: if we-// ever see an offset at or below this watermark again, the message is being-// redelivered (at-least-once duplicate) outside of a rebalance — which is the-// signature of an offset-handling bug. Cleared on GROUP_JOIN so legitimate-// post-rebalance redelivery from the last committed offset doesn't trip it.-const resolvedHWM = new Map<string, number>();+const RETRY_BACKOFF_FACTOR = 2;++/** Why a message was dead-lettered. A label value — keep the set small. */+type DeadLetterReason = 'parse_error' | 'handler_error';++interface ConsumerLogger {+ info: (obj: object, msg?: string) => void;+ warn: (obj: object, msg?: string) => void;+ error: (obj: object, msg?: string) => void;+}++interface ConsumerMetrics {+ reprocessed: (partition: string) => void;+ handlerFailed: (partition: string) => void;+ deadLettered: (partition: string, reason: DeadLetterReason) => void;+ deadLetterFailed: (partition: string) => void;+}++export interface EventsBatchHandlerDeps {+ handleEvent: (+ payload: EventsQueuePayloadIncomingEvent['payload'],+ meta: { partition: number; offset: string }+ ) => Promise<unknown>;+ sendToDeadLetter: (message: DeadLetterMessage) => Promise<void>;+ logger: ConsumerLogger;+ metrics: ConsumerMetrics;+ onActivity: () => void;+ topic: string;+ maxAttempts: number;+ initialRetryMs: number;+ maxRetryMs: number;+ sleep: (ms: number) => Promise<void>;+}++const defaultSleep = (ms: number): Promise<void> =>+ new Promise((resolve) => setTimeout(resolve, ms));++const errorMessage = (err: unknown): string =>+ err instanceof Error ? err.message : String(err);++const defaultDeps = (): EventsBatchHandlerDeps => ({+ handleEvent: incomingEvent,+ sendToDeadLetter: produceDeadLetterEvent,+ logger,+ metrics: {+ reprocessed: (partition) => kafkaReprocessedTotal.inc({ partition }),+ handlerFailed: (partition) => kafkaHandlerFailuresTotal.inc({ partition }),+ deadLettered: (partition, reason) =>+ kafkaDeadLetteredTotal.inc({ partition, reason }),+ deadLetterFailed: (partition) =>+ kafkaDeadLetterFailedTotal.inc({ partition }),+ },+ onActivity: markEventsActivity,+ topic: KAFKA_EVENTS_TOPIC,+ maxAttempts: KAFKA_HANDLER_MAX_ATTEMPTS,+ initialRetryMs: KAFKA_HANDLER_RETRY_INITIAL_MS,+ maxRetryMs: KAFKA_HANDLER_RETRY_MAX_MS,+ sleep: defaultSleep,+});++export interface EventsBatchHandler {+ eachBatch: (payload: EachBatchPayload) => Promise<void>;+ /** Called on GROUP_JOIN: a new assignment invalidates the watermarks. */+ resetWatermarks: () => void;+}++/**+ * The `eachBatch` handler, with its dependencies injected so the offset walk,+ * the per-key serial groups and the failure paths are testable without a+ * broker.+ *+ * Delivery contract (ADR-004): at-least-once. An offset is resolved only once+ * its message has been handled, dead-lettered, or deliberately skipped —+ * never merely because it failed.+ */+export function createEventsBatchHandler(+ overrides: Partial<EventsBatchHandlerDeps> = {}+): EventsBatchHandler {+ const deps: EventsBatchHandlerDeps = { ...defaultDeps(), ...overrides };++ // Highest Kafka offset we have *resolved* (committed) per `topic-partition`,+ // tracked across batches. Used purely for the reprocess detector below: if we+ // ever see an offset at or below this watermark again, the message is being+ // redelivered (at-least-once duplicate) outside of a rebalance — which is the+ // signature of an offset-handling bug. Cleared on GROUP_JOIN so legitimate+ // post-rebalance redelivery from the last committed offset doesn't trip it.+ const resolvedHWM = new Map<string, number>();++ const deadLetter = async (+ message: KafkaMessage,+ partition: number,+ reason: DeadLetterReason,+ err: unknown+ ): Promise<boolean> => {+ const label = String(partition);+ try {+ await deps.sendToDeadLetter({+ key: message.key,+ value: message.value,+ headers: message.headers,+ topic: deps.topic,+ partition,+ offset: message.offset,+ reason,+ error: errorMessage(err),+ });+ } catch (dlqErr) {+ // The event is not lost: leaving the offset unresolved stops the+ // contiguous-prefix walk here, so the broker redelivers this message.+ deps.metrics.deadLetterFailed(label);+ deps.logger.error(+ { err: dlqErr, partition, offset: message.offset, reason },+ 'kafka dead-letter produce failed — offset left unresolved for redelivery'+ );+ return false;+ }+ deps.metrics.deadLettered(label, reason);+ deps.logger.error(+ { err, partition, offset: message.offset, reason },+ 'kafka message dead-lettered'+ );+ return true;+ };++ const runHandlerWithRetry = async (+ payload: EventsQueuePayloadIncomingEvent['payload'],+ partition: number,+ offset: string+ ): Promise<{ ok: true } | { ok: false; err: unknown }> => {+ const label = String(partition);+ let delayMs = deps.initialRetryMs;+ let lastErr: unknown;++ for (let attempt = 1; attempt <= deps.maxAttempts; attempt++) {+ try {+ await deps.handleEvent(payload, { partition, offset });+ return { ok: true };+ } catch (err) {+ lastErr = err;+ deps.metrics.handlerFailed(label);+ deps.logger.warn(+ {+ err,+ partition,+ offset,+ projectId: payload.projectId,+ attempt,+ maxAttempts: deps.maxAttempts,+ },+ 'kafka incomingEvent handler failed'+ );+ if (attempt < deps.maxAttempts) {+ await deps.sleep(delayMs);+ delayMs = Math.min(delayMs * RETRY_BACKOFF_FACTOR, deps.maxRetryMs);+ }+ }+ }++ return { ok: false, err: lastErr };+ };++ /** @returns true when the offset may be resolved. */+ const processMessage = async (+ message: KafkaMessage,+ partition: number+ ): Promise<boolean> => {+ let payload: EventsQueuePayloadIncomingEvent['payload'];+ try {+ if (!message.value) {+ throw new Error('kafka message has no value');+ }+ payload = JSON.parse(+ message.value.toString()+ ) as EventsQueuePayloadIncomingEvent['payload'];+ } catch (err) {+ deps.logger.error(+ { err, partition, offset: message.offset },+ 'kafka message parse failed'+ );+ // Deterministic: retrying identical bytes cannot succeed.+ return deadLetter(message, partition, 'parse_error', err);+ }++ const result = await runHandlerWithRetry(+ payload,+ partition,+ message.offset+ );+ if (result.ok) {+ return true;+ }+ return deadLetter(message, partition, 'handler_error', result.err);+ };++ const eachBatch = async ({+ batch,+ resolveOffset,+ heartbeat,+ isRunning,+ isStale,+ }: EachBatchPayload): Promise<void> => {+ if (batch.messages.length === 0) {+ return;+ }++ const pk = `${batch.topic}-${batch.partition}`;+ // Watermark from *previous* batches. Anything at or below this that we see+ // now is a redelivery. Captured before this batch so intra-batch+ // out-of-order processing (normal, see below) is never counted.+ const priorHWM = resolvedHWM.get(pk) ?? -1;++ // Group by partition key (= deviceId or `${projectId}:${profileId}`).+ // Same-key messages stay serial so sessionBuffer/session-end-job state+ // can't race; different keys run in parallel via Promise.all.+ // Keyless messages get their own singleton group.+ const groups = new Map<string, KafkaMessage[]>();+ for (const m of batch.messages) {+ const key = m.key ? m.key.toString() : `__no_key__:${m.offset}`;+ const arr = groups.get(key);+ if (arr) {+ arr.push(m);+ } else {+ groups.set(key, [m]);+ }+ }++ // Offsets that finished processing this batch. We resolve them AFTER all+ // groups complete, in strict ascending order (see the loop below).+ //+ // Why: KafkaJS `resolveOffset` is last-write-wins and the next fetch+ // starts from the last resolved offset (offsetManager.nextOffset). If we+ // resolved inside the concurrent per-key loop, a lower offset resolving+ // after a higher one would move the fetch position BACKWARDS and+ // re-deliver everything in between — the root cause of the duplicate+ // events. Resolving the contiguous ascending prefix at the end avoids+ // both duplicates (never regress) and loss (stop at the first gap).+ const processed = new Set<string>();+ let processedCount = 0;++ await Promise.all(+ [...groups.values()].map(async (msgs) => {+ for (const m of msgs) {+ if (!isRunning() || isStale()) {+ return;+ }++ // Reprocess detector: only fires for offsets already resolved in a+ // PRIOR batch (redelivery). Intra-batch out-of-order processing+ // across key-groups is expected and is not flagged.+ if (Number(m.offset) <= priorHWM) {+ deps.metrics.reprocessed(String(batch.partition));+ deps.logger.warn(+ {+ partition: batch.partition,+ offset: m.offset,+ resolvedHighWaterMark: priorHWM,+ },+ 'kafka offset REPROCESSED — at-least-once duplicate (outside rebalance)'+ );+ }++ const resolvable = await processMessage(m, batch.partition);+ if (!resolvable) {+ // Stop this key-group: continuing past an unresolvable offset only+ // adds duplicates, since the whole tail is redelivered anyway.+ return;+ }++ processed.add(m.offset);+ processedCount += 1;+ if (processedCount % HEARTBEAT_EVERY === 0) {+ await heartbeat();+ }+ }+ })+ );++ // Resolve in strict ascending offset order, stopping at the first offset+ // that did not finish (e.g. an isStale/isRunning early-return mid-batch).+ // batch.messages is already ordered by offset.+ let newHWM = priorHWM;+ for (const m of batch.messages) {+ if (!processed.has(m.offset)) {+ break;+ }+ resolveOffset(m.offset);+ newHWM = Math.max(newHWM, Number(m.offset));+ }+ resolvedHWM.set(pk, newHWM);++ await heartbeat();+ deps.onActivity();+ };++ return { eachBatch, resetWatermarks: () => resolvedHWM.clear() };+}export async function startKafkaEventsConsumer(): Promise<KafkaConsumerHandle> {const consumer = createKafkaEventsConsumer();+ const handler = createEventsBatchHandler();await consumer.connect();await consumer.subscribe({topic: KAFKA_EVENTS_TOPIC,@@ -45,7 +346,7 @@ export async function startKafkaEventsConsumer(): Promise<KafkaConsumerHandle> {// A new assignment means partitions may have moved between members; reset// the reprocess watermarks so legitimate resume-from-committed-offset after// a rebalance is not flagged as a duplicate.- resolvedHWM.clear();+ handler.resetWatermarks();logger.info({memberId: payload.memberId,@@ -86,134 +387,7 @@ export async function startKafkaEventsConsumer(): Promise<KafkaConsumerHandle> {await consumer.run({partitionsConsumedConcurrently: KAFKA_PARTITIONS_CONCURRENT,eachBatchAutoResolve: false,- eachBatch: async ({- batch,- resolveOffset,- heartbeat,- isRunning,- isStale,- }) => {- if (batch.messages.length === 0) {- return;- }-- const pk = `${batch.topic}-${batch.partition}`;- // Watermark from *previous* batches. Anything at or below this that we see- // now is a redelivery. Captured before this batch so intra-batch- // out-of-order processing (normal, see below) is never counted.- const priorHWM = resolvedHWM.get(pk) ?? -1;-- // Group by partition key (= deviceId or `${projectId}:${profileId}`).- // Same-key messages stay serial so sessionBuffer/session-end-job state- // can't race; different keys run in parallel via Promise.all.- // Keyless messages get their own singleton group.- const groups = new Map<string, KafkaMessage[]>();- for (const m of batch.messages) {- const key = m.key ? m.key.toString() : `__no_key__:${m.offset}`;- const arr = groups.get(key);- if (arr) {- arr.push(m);- } else {- groups.set(key, [m]);- }- }-- // Offsets that finished processing this batch. We resolve them AFTER all- // groups complete, in strict ascending order (see the loop below).- //- // Why: KafkaJS `resolveOffset` is last-write-wins and the next fetch- // starts from the last resolved offset (offsetManager.nextOffset). If we- // resolved inside the concurrent per-key loop, a lower offset resolving- // after a higher one would move the fetch position BACKWARDS and- // re-deliver everything in between — the root cause of the duplicate- // events. Resolving the contiguous ascending prefix at the end avoids- // both duplicates (never regress) and loss (stop at the first gap).- const processed = new Set<string>();- let processedCount = 0;-- await Promise.all(- [...groups.values()].map(async (msgs) => {- for (const m of msgs) {- if (!isRunning() || isStale()) {- return;- }-- // Reprocess detector: only fires for offsets already resolved in a- // PRIOR batch (redelivery). Intra-batch out-of-order processing- // across key-groups is expected and is not flagged.- if (Number(m.offset) <= priorHWM) {- kafkaReprocessedTotal.inc({ partition: String(batch.partition) });- logger.warn(- {- partition: batch.partition,- offset: m.offset,- resolvedHighWaterMark: priorHWM,- },- 'kafka offset REPROCESSED — at-least-once duplicate (outside rebalance)'- );- }-- if (m.value) {- let payload: EventsQueuePayloadIncomingEvent['payload'] | null =- null;- try {- payload = JSON.parse(- m.value.toString()- ) as EventsQueuePayloadIncomingEvent['payload'];- } catch (err) {- logger.error(- { err, partition: batch.partition, offset: m.offset },- 'kafka message parse failed'- );- }- if (payload) {- try {- await incomingEvent(payload, {- partition: batch.partition,- offset: m.offset,- });- } catch (err) {- // Match the previous eachMessage behaviour: log and ack.- // At-most-once on handler exceptions; failures here would- // otherwise block the partition.- logger.error(- {- err,- partition: batch.partition,- offset: m.offset,- projectId: payload.projectId,- },- 'kafka incomingEvent handler failed'- );- }- }- }-- processed.add(m.offset);- processedCount += 1;- if (processedCount % HEARTBEAT_EVERY === 0) {- await heartbeat();- }- }- })- );-- // Resolve in strict ascending offset order, stopping at the first offset- // that did not finish (e.g. an isStale/isRunning early-return mid-batch).- // batch.messages is already ordered by offset.- let newHWM = priorHWM;- for (const m of batch.messages) {- if (!processed.has(m.offset)) {- break;- }- resolveOffset(m.offset);- newHWM = Math.max(newHWM, Number(m.offset));- }- resolvedHWM.set(pk, newHWM);-- await heartbeat();- markEventsActivity();- },+ eachBatch: handler.eachBatch,});kafkaLogger.info(diff --git a/apps/worker/src/metrics.ts b/apps/worker/src/metrics.tsindex c48632127..ebfbbbf62 100644--- a/apps/worker/src/metrics.ts+++ b/apps/worker/src/metrics.ts@@ -37,6 +37,37 @@ export const kafkaReprocessedTotal = new client.Counter({register.registerMetric(kafkaReprocessedTotal);+// Handler exceptions on the Kafka ingest path, counted per attempt — retries+// included, so the series shows real failure pressure and not just the+// messages that ran out of attempts.+export const kafkaHandlerFailuresTotal = new client.Counter({+ name: 'kafka_events_handler_failures_total',+ help: 'Kafka event handler exceptions (each attempt, retries included)',+ labelNames: ['partition'],+});++register.registerMetric(kafkaHandlerFailuresTotal);++// Messages written to the dead-letter topic after their attempts were+// exhausted (or after they failed to parse). One increment per message.+export const kafkaDeadLetteredTotal = new client.Counter({+ name: 'kafka_events_dead_lettered_total',+ help: 'Kafka event messages produced to the dead-letter topic',+ labelNames: ['partition', 'reason'],+});++register.registerMetric(kafkaDeadLetteredTotal);++// The dead-letter produce itself failed. The offset is then left unresolved+// and the message is redelivered, so this is a stuck partition, not a loss.+export const kafkaDeadLetterFailedTotal = new client.Counter({+ name: 'kafka_events_dead_letter_failed_total',+ help: 'Failed attempts to produce a Kafka event message to the dead-letter topic',+ labelNames: ['partition'],+});++register.registerMetric(kafkaDeadLetterFailedTotal);+queues.forEach((queue) => {register.registerMetric(new client.Gauge({diff --git a/packages/queue/src/kafka.ts b/packages/queue/src/kafka.tsindex f6f8263d0..a42ac0d82 100644--- a/packages/queue/src/kafka.ts+++ b/packages/queue/src/kafka.ts@@ -1,8 +1,14 @@import { createLogger } from '@openpanel/logger';-import { type Consumer, Kafka, logLevel, type Producer } from 'kafkajs';+import {+ type Consumer,+ type IHeaders,+ Kafka,+ logLevel,+ type Producer,+} from 'kafkajs';import type { EventsQueuePayloadIncomingEvent } from './queues';-export type { KafkaMessage } from 'kafkajs';+export type { EachBatchPayload, KafkaMessage } from 'kafkajs';export const kafkaLogger = createLogger({ name: 'kafka' });@@ -18,6 +24,11 @@ const parseBrokers = (raw: string | undefined): string[] => {export const KAFKA_BROKERS = parseBrokers(process.env.KAFKA_BROKERS);export const KAFKA_EVENTS_TOPIC = process.env.KAFKA_EVENTS_TOPIC || 'events';+// Dead-letter topic for messages the consumer could not handle (ADR-004+// delivery semantics). Kept on the same broker so a poison message is retained+// and countable instead of dropped.+export const KAFKA_EVENTS_DLQ_TOPIC =+ process.env.KAFKA_EVENTS_DLQ_TOPIC || `${KAFKA_EVENTS_TOPIC}-dlq`;export const KAFKA_CONSUMER_GROUP =process.env.KAFKA_CONSUMER_GROUP || 'openpanel-events';export const KAFKA_PARTITIONS_CONCURRENT = Number.parseInt(@@ -74,6 +85,22 @@ export const KAFKA_PRODUCER_MAX_RETRY_MS = Number.parseInt(10);+// In-consumer retry for handler exceptions (ADR-004: at-least-once). Bounded+// so the worst case stays far inside KAFKA_SESSION_TIMEOUT_MS — a batch that+// out-waits the session timeout is a rebalance, which is worse than a DLQ.+export const KAFKA_HANDLER_MAX_ATTEMPTS = Number.parseInt(+ process.env.KAFKA_HANDLER_MAX_ATTEMPTS || '3',+ 10+);+export const KAFKA_HANDLER_RETRY_INITIAL_MS = Number.parseInt(+ process.env.KAFKA_HANDLER_RETRY_INITIAL_MS || '100',+ 10+);+export const KAFKA_HANDLER_RETRY_MAX_MS = Number.parseInt(+ process.env.KAFKA_HANDLER_RETRY_MAX_MS || '1000',+ 10+);+const KAFKA_MIN_BYTES = KAFKA_MIN_MESSAGES * KAFKA_BYTES_PER_MESSAGE;const KAFKA_MAX_BYTES_PER_PARTITION =KAFKA_MAX_MESSAGES_PER_PARTITION * KAFKA_BYTES_PER_MESSAGE;@@ -186,21 +213,19 @@ const resetProducer = (broken: Producer): void => {});};-export const produceIncomingEvent = async (- payload: EventsQueuePayloadIncomingEvent['payload'],- partitionKey: string-): Promise<void> => {+interface OutgoingMessage {+ key: Buffer | null;+ value: Buffer | null;+ headers?: IHeaders;+}++const send = async (topic: string, message: OutgoingMessage): Promise<void> => {const p = await getProducer();try {await p.send({- topic: KAFKA_EVENTS_TOPIC,+ topic,timeout: KAFKA_REQUEST_TIMEOUT_MS,- messages: [- {- key: Buffer.from(partitionKey),- value: Buffer.from(JSON.stringify(payload)),- },- ],+ messages: [message],});} catch (err) {if (isFatalProducerError(err)) {@@ -214,6 +239,46 @@ export const produceIncomingEvent = async (}};+export const produceIncomingEvent = async (+ payload: EventsQueuePayloadIncomingEvent['payload'],+ partitionKey: string+): Promise<void> =>+ send(KAFKA_EVENTS_TOPIC, {+ key: Buffer.from(partitionKey),+ value: Buffer.from(JSON.stringify(payload)),+ });++// Why the reason/error/coordinates travel as headers and not in the value: the+// value stays the producer's original bytes, so a DLQ message can be replayed+// onto the events topic unchanged.+export interface DeadLetterMessage {+ key: Buffer | null;+ value: Buffer | null;+ headers?: IHeaders;+ topic: string;+ partition: number;+ offset: string;+ reason: string;+ error: string;+}++export const produceDeadLetterEvent = async (+ message: DeadLetterMessage+): Promise<void> =>+ send(KAFKA_EVENTS_DLQ_TOPIC, {+ key: message.key,+ value: message.value,+ headers: {+ ...message.headers,+ 'dlq-source-topic': message.topic,+ 'dlq-source-partition': String(message.partition),+ 'dlq-source-offset': message.offset,+ 'dlq-reason': message.reason,+ 'dlq-error': message.error,+ 'dlq-at': new Date().toISOString(),+ },+ });+const consumers = new Set<Consumer>();export const createKafkaEventsConsumer = (options?: {