Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M18-001): Graceful shutdown must flush the event buffer's in-process micro-batch to Redis BEFORE committing Kafka offsets - and must not commit if that flush fails

ralphc9026a621c5d
diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts
index f4643c801..a0f27d8be 100644
--- a/apps/api/src/main.ts
+++ b/apps/api/src/main.ts
@@ -88,6 +88,7 @@ import { getRedisCache, getRedisPub, getRedisQueue } from '@openpanel/redis';
import { Elysia } from 'elysia';
import pino from 'pino';
import { type Config, KAFKA_QUEUE_TOKEN, loadConfig } from './config/env';
+import { runShutdownSequence } from './shutdown';
// The registry key and the Redis name are the same string for all seven queues
// (jobs.registry.ts); `queueKey` only braces it under `QUEUE_CLUSTER`.
@@ -270,6 +271,10 @@ async function startIngestConsumer(
}),
sendToDeadLetter: (message) =>
produceDeadLetterEvent(config.core, message),
+ // Runs before the batch's offsets are resolved, and THROWS if the rpush
+ // did not land. `pendingEvents` is the only in-process buffer state in
+ // the tree — every other buffer writes to Redis inside `add()`.
+ flushBufferedEvents: () => deps.buffers.event.flushPendingOrThrow(),
logger,
metrics: ingestConsumerMetrics,
onActivity: markEventsActivity,
@@ -527,27 +532,38 @@ async function main() {
}, config.SHUTDOWN_FORCE_EXIT_MS);
forceExit.unref();
- try {
- await app.stop();
- // Only if THIS process consumes cron: waiting on a queue another replica
- // owns would stall the whole shutdown budget on someone else's jobs.
- if (workers && config.ENABLED_QUEUES.includes(CRON_QUEUE_NAME)) {
- await waitForCronToDrain(deps.producers);
- }
- await Promise.all([workers?.close(), consumer?.stop()]);
- await deps.producers.close();
- // Core opens the Kafka producer lazily on the first /track and the
- // consumer at boot; `deps.producers` is the BullMQ handle, not this one.
- // Without this an idempotent producer with in-flight batches is dropped.
- await disconnectKafka(config.core);
- logger.info('Graceful shutdown completed');
- clearTimeout(forceExit);
- process.exit(0);
- } catch (error) {
- logger.error({ err: error }, 'Error during graceful shutdown');
- clearTimeout(forceExit);
- process.exit(1);
- }
+ const exitCode = await runShutdownSequence(
+ {
+ stopHttpServer: async () => {
+ await app.stop();
+ },
+ drainCron: async () => {
+ if (workers && config.ENABLED_QUEUES.includes(CRON_QUEUE_NAME)) {
+ await waitForCronToDrain(deps.producers);
+ }
+ },
+ closeWorkers: async () => {
+ await workers?.close();
+ },
+ stopConsuming: async () => {
+ await consumer?.stopConsuming();
+ },
+ // The backstop. Events buffered inside a Kafka batch are already in
+ // Redis (the batch handler flushes before it resolves its offsets);
+ // this catches what was buffered outside one — a session-end job's
+ // `session_end` event, an import — which no offset covers.
+ flushEventBuffer: () => deps.buffers.event.flushPendingOrThrow(),
+ stopConsumer: async () => {
+ await consumer?.stop();
+ },
+ closeProducers: () => deps.producers.close(),
+ disconnectKafka: () => disconnectKafka(config.core),
+ },
+ logger
+ );
+
+ clearTimeout(forceExit);
+ process.exit(exitCode);
};
process.on('SIGTERM', () => {
diff --git a/apps/api/src/shutdown.test.ts b/apps/api/src/shutdown.test.ts
new file mode 100644
index 000000000..7cce9463f
--- /dev/null
+++ b/apps/api/src/shutdown.test.ts
@@ -0,0 +1,142 @@
+/**
+ * The regression test for drill 03's loss (M18-001).
+ *
+ * Both halves matter and the happy path alone would not have caught the bug:
+ * (a) the event buffer is flushed to Redis BEFORE the Kafka consumer is
+ * stopped, and (b) a FAILED flush stops the sequence there — the consumer is
+ * never stopped and the process exits non-zero, so Kafka redelivers instead of
+ * dropping the events for good.
+ */
+
+import { describe, expect, it, mock } from 'bun:test';
+import {
+ runShutdownSequence,
+ SHUTDOWN_EXIT_FAILED,
+ SHUTDOWN_EXIT_OK,
+ type ShutdownSteps,
+} from './shutdown';
+
+const silentLogger = () => ({
+ info: mock(() => undefined),
+ error: mock(() => undefined),
+ fatal: mock(() => undefined),
+});
+
+/**
+ * Every step appends its own name, so the assertions are about ORDER rather
+ * than about how many times something was called.
+ */
+function recordingSteps(overrides: Partial<ShutdownSteps> = {}): {
+ steps: ShutdownSteps;
+ calls: string[];
+} {
+ const calls: string[] = [];
+ const step = (name: string) => async () => {
+ // A tick, so a step that was started concurrently with a later one would
+ // interleave and be visible in `calls`.
+ await Promise.resolve();
+ calls.push(name);
+ };
+
+ return {
+ calls,
+ steps: {
+ stopHttpServer: step('stopHttpServer'),
+ drainCron: step('drainCron'),
+ closeWorkers: step('closeWorkers'),
+ stopConsuming: step('stopConsuming'),
+ flushEventBuffer: step('flushEventBuffer'),
+ stopConsumer: step('stopConsumer'),
+ closeProducers: step('closeProducers'),
+ disconnectKafka: step('disconnectKafka'),
+ ...overrides,
+ },
+ };
+}
+
+describe('runShutdownSequence', () => {
+ it('flushes the event buffer before the consumer is stopped', async () => {
+ const { steps, calls } = recordingSteps();
+
+ const exitCode = await runShutdownSequence(steps, silentLogger());
+
+ expect(exitCode).toBe(SHUTDOWN_EXIT_OK);
+ expect(calls).toEqual([
+ 'stopHttpServer',
+ 'drainCron',
+ 'closeWorkers',
+ 'stopConsuming',
+ 'flushEventBuffer',
+ 'stopConsumer',
+ 'closeProducers',
+ 'disconnectKafka',
+ ]);
+ expect(calls.indexOf('flushEventBuffer')).toBeLessThan(
+ calls.indexOf('stopConsumer')
+ );
+ });
+
+ it('lets in-flight handlers finish before it flushes', async () => {
+ // The shape drill 03 measured: a message is still being handled when the
+ // signal arrives. `stopConsuming` must not resolve until that handler has,
+ // and the flush must not start until `stopConsuming` has resolved.
+ const calls: string[] = [];
+ let handlerFinished = false;
+
+ const { steps } = recordingSteps({
+ stopConsuming: async () => {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ handlerFinished = true;
+ calls.push('stopConsuming');
+ },
+ flushEventBuffer: async () => {
+ expect(handlerFinished).toBe(true);
+ calls.push('flushEventBuffer');
+ },
+ stopConsumer: async () => {
+ calls.push('stopConsumer');
+ },
+ });
+
+ const exitCode = await runShutdownSequence(steps, silentLogger());
+
+ expect(exitCode).toBe(SHUTDOWN_EXIT_OK);
+ expect(calls).toEqual([
+ 'stopConsuming',
+ 'flushEventBuffer',
+ 'stopConsumer',
+ ]);
+ });
+
+ it('does not stop the consumer when the flush fails, and exits non-zero', async () => {
+ const { steps, calls } = recordingSteps({
+ flushEventBuffer: () => Promise.reject(new Error('redis is unreachable')),
+ });
+ const logger = silentLogger();
+
+ const exitCode = await runShutdownSequence(steps, logger);
+
+ expect(exitCode).toBe(SHUTDOWN_EXIT_FAILED);
+ expect(calls).toEqual([
+ 'stopHttpServer',
+ 'drainCron',
+ 'closeWorkers',
+ 'stopConsuming',
+ ]);
+ expect(calls).not.toContain('stopConsumer');
+ expect(calls).not.toContain('disconnectKafka');
+ expect(logger.fatal).toHaveBeenCalledTimes(1);
+ expect(logger.info).not.toHaveBeenCalled();
+ });
+
+ it('does not flush after a teardown step failed before it', async () => {
+ const { steps, calls } = recordingSteps({
+ stopConsuming: () => Promise.reject(new Error('kafka is gone')),
+ });
+
+ const exitCode = await runShutdownSequence(steps, silentLogger());
+
+ expect(exitCode).toBe(SHUTDOWN_EXIT_FAILED);
+ expect(calls).not.toContain('stopConsumer');
+ });
+});
diff --git a/apps/api/src/shutdown.ts b/apps/api/src/shutdown.ts
new file mode 100644
index 000000000..f02a9816e
--- /dev/null
+++ b/apps/api/src/shutdown.ts
@@ -0,0 +1,113 @@
+// The graceful-shutdown sequence, lifted out of `main.ts` so its ORDER is a
+// thing a test can assert rather than a property of how a `Promise.all` was
+// typed (M18-001).
+//
+// Drill 03 (`verification/drills/03-restart-in-flight.md`) measured a SIGTERM
+// restart permanently losing 2 of 44,075 accepted events while both SIGKILL
+// arms lost none. Graceful shutdown lost them BECAUSE it was graceful: the
+// event buffer's in-process `pendingEvents` array was never flushed to Redis,
+// and the offsets for those events had already been committed, so nothing was
+// redelivered. A crash commits nothing, so Kafka replays the same window.
+//
+// The commit itself is NOT here: kafkajs auto-commits the offsets a batch
+// resolved as soon as `eachBatch` returns, so the events a Kafka batch
+// buffered are made durable inside the batch handler, before it resolves
+// anything (`consumer.ts`'s `flushBufferedEvents`). What is left for this
+// sequence is everything buffered OUTSIDE a Kafka batch — a session-end job's
+// event, an import — which no offset covers and which a `process.exit` would
+// simply drop.
+//
+// Either way it is one rpush of at most `microBatchMaxSize` events —
+// milliseconds, well inside `SHUTDOWN_FORCE_EXIT_MS`. It is NOT a Redis ->
+// ClickHouse drain: the Redis list is durable and the next process, or another
+// replica, drains it.
+
+/** Everything succeeded; the offsets are committed and the events are durable. */
+export const SHUTDOWN_EXIT_OK = 0;
+/**
+ * Something failed. Exiting non-zero without committing is deliberately the
+ * crash shape, which drill 03 proved is the safe one: Kafka redelivers and a
+ * duplicate is recoverable where a loss is not.
+ */
+export const SHUTDOWN_EXIT_FAILED = 1;
+
+export interface ShutdownLogger {
+ info: (obj: object, msg?: string) => void;
+ error: (obj: object, msg?: string) => void;
+ fatal: (obj: object, msg?: string) => void;
+}
+
+/**
+ * Each step is a no-op in the roles that do not have the thing it tears down,
+ * so the sequence itself is unconditional and reads top to bottom.
+ */
+export interface ShutdownSteps {
+ /** Stop serving HTTP. Readiness already answers 503 by this point. */
+ stopHttpServer: () => Promise<void>;
+ /** Let the cron queue finish what it started, if this process owns it. */
+ drainCron: () => Promise<void>;
+ /** BullMQ stops taking jobs and its in-flight handlers finish. */
+ closeWorkers: () => Promise<void>;
+ /** The Kafka consumer stops fetching and its in-flight batch finishes. */
+ stopConsuming: () => Promise<void>;
+ /** The one step that must not be concurrent with anything: rpush or throw. */
+ flushEventBuffer: () => Promise<void>;
+ /** The consumer leaves the group and disconnects. */
+ stopConsumer: () => Promise<void>;
+ closeProducers: () => Promise<void>;
+ disconnectKafka: () => Promise<void>;
+}
+
+/**
+ * @returns the process exit code. The caller owns `process.exit` and the
+ * force-exit timer, so this function stays callable from a test.
+ */
+export async function runShutdownSequence(
+ steps: ShutdownSteps,
+ logger: ShutdownLogger
+): Promise<number> {
+ try {
+ await steps.stopHttpServer();
+ // Only if THIS process consumes cron: waiting on a queue another replica
+ // owns would stall the whole shutdown budget on someone else's jobs.
+ await steps.drainCron();
+ // After this line nothing new can enter the event buffer: BullMQ has
+ // stopped taking jobs and the Kafka consumer has stopped fetching, and
+ // both have let their in-flight handlers finish. The two are unrelated
+ // teardowns, so they still run concurrently — what changed is that the
+ // consumer's DISCONNECT no longer runs here, alongside them.
+ await Promise.all([steps.closeWorkers(), steps.stopConsuming()]);
+ } catch (error) {
+ logger.error({ err: error }, 'Error during graceful shutdown');
+ return SHUTDOWN_EXIT_FAILED;
+ }
+
+ // Must COMPLETE before the consumer is torn down — never alongside it — and
+ // must be able to stop the rest of the sequence: Redis being unreachable is
+ // exactly when the rpush cannot land, and finishing a tidy shutdown then
+ // would drop those events for good.
+ try {
+ await steps.flushEventBuffer();
+ } catch (error) {
+ logger.fatal(
+ { err: error },
+ 'Event buffer flush to Redis failed — refusing to finish the shutdown so Kafka redelivers'
+ );
+ return SHUTDOWN_EXIT_FAILED;
+ }
+
+ try {
+ await steps.stopConsumer();
+ await steps.closeProducers();
+ // Core opens the Kafka producer lazily on the first /track and the
+ // consumer at boot; `deps.producers` is the BullMQ handle, not this one.
+ // Without this an idempotent producer with in-flight batches is dropped.
+ await steps.disconnectKafka();
+ } catch (error) {
+ logger.error({ err: error }, 'Error during graceful shutdown');
+ return SHUTDOWN_EXIT_FAILED;
+ }
+
+ logger.info({}, 'Graceful shutdown completed');
+ return SHUTDOWN_EXIT_OK;
+}
diff --git a/packages/core/src/buffers/event-buffer.test.ts b/packages/core/src/buffers/event-buffer.test.ts
index 4c8052a21..0be2de597 100644
--- a/packages/core/src/buffers/event-buffer.test.ts
+++ b/packages/core/src/buffers/event-buffer.test.ts
@@ -1,4 +1,12 @@
-import { afterAll, beforeEach, describe, expect, it, mock } from 'bun:test';
+import {
+ afterAll,
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ mock,
+} from 'bun:test';
import type { Readable } from 'node:stream';
import type { SqlFragment } from '@openpanel/db/src/clickhouse/sql';
import { getRedisCache } from '@openpanel/redis';
@@ -55,6 +63,9 @@ afterAll(() => {
mock.module('../ch-query', () => realChQuery);
});
+/** `testCoreConfig()` leaves `microBatchSize` undefined, so the buffer's own default applies. */
+const DEFAULT_MICRO_BATCH_SIZE = 100;
+
describe('EventBuffer', () => {
let eventBuffer: EventBuffer;
@@ -324,6 +335,99 @@ describe('EventBuffer', () => {
expect(await eventBuffer.getBufferSize()).toBe(5);
});
+ // M18-001 / drill 03: the shutdown path has to be able to SEE a failed
+ // rpush, because it decides whether to commit the Kafka offsets on the
+ // answer. `flush()` deliberately swallows one (the micro-batch timer retries
+ // while the process lives); `flushPendingOrThrow()` does not.
+ describe('flushPendingOrThrow', () => {
+ // A failed flush re-queues its events AND arms the micro-batch timer, so
+ // without this the retry lands in whichever test runs next.
+ afterEach(async () => {
+ await redis.del('event_buffer:queue');
+ for (let attempt = 0; attempt < 5; attempt++) {
+ if (eventBuffer.getPendingLocalCount() === 0) {
+ break;
+ }
+ await eventBuffer.flush();
+ }
+ await redis.del('event_buffer:queue');
+ });
+
+ it('pushes the pending micro-batch to Redis and resolves', async () => {
+ eventBuffer.add({
+ project_id: 'p13',
+ name: 'event1',
+ created_at: new Date().toISOString(),
+ } as any);
+ expect(eventBuffer.getPendingLocalCount()).toBe(1);
+
+ await eventBuffer.flushPendingOrThrow();
+
+ expect(eventBuffer.getPendingLocalCount()).toBe(0);
+ expect(await eventBuffer.getBufferSize()).toBe(1);
+ });
+
+ it('throws when the rpush does not land, and keeps the events', async () => {
+ // A string under the list key makes every rpush fail with WRONGTYPE —
+ // a real Redis refusal, without mocking the client out from under the
+ // buffer. ioredis RESOLVES such a MULTI, so this is also the regression
+ // test for reading the per-command errors.
+ await redis.set('event_buffer:queue', 'not a list');
+
+ eventBuffer.add({
+ project_id: 'p14',
+ name: 'event1',
+ created_at: new Date().toISOString(),
+ } as any);
+
+ await expect(eventBuffer.flushPendingOrThrow()).rejects.toThrow(
+ 'WRONGTYPE'
+ );
+ expect(eventBuffer.getPendingLocalCount()).toBe(1);
+ });
+
+ it('waits for an in-flight micro-batch, then pushes what arrived during it', async () => {
+ // The two-pass path: a write already in flight may have started before
+ // the last `add()`, so waiting for it is not enough — a second write has
+ // to be STARTED. Crossing `microBatchSize` puts one in flight
+ // synchronously, and the event added right after it is the one that
+ // would otherwise be resolved-then-lost.
+ const inFlightBatch = DEFAULT_MICRO_BATCH_SIZE;
+ for (let index = 0; index < inFlightBatch; index++) {
+ eventBuffer.add({
+ project_id: 'p16',
+ name: 'in-flight',
+ created_at: new Date().toISOString(),
+ } as any);
+ }
+ eventBuffer.add({
+ project_id: 'p16',
+ name: 'arrived-during-the-write',
+ created_at: new Date().toISOString(),
+ } as any);
+ expect(eventBuffer.getPendingLocalCount()).toBe(1);
+
+ await eventBuffer.flushPendingOrThrow();
+
+ expect(eventBuffer.getPendingLocalCount()).toBe(0);
+ expect(await eventBuffer.getBufferSize()).toBe(inFlightBatch + 1);
+ });
+
+ it('does not throw through flush(), which retries instead', async () => {
+ await redis.set('event_buffer:queue', 'not a list');
+
+ eventBuffer.add({
+ project_id: 'p15',
+ name: 'event1',
+ created_at: new Date().toISOString(),
+ } as any);
+
+ await eventBuffer.flush();
+
+ expect(eventBuffer.getPendingLocalCount()).toBe(1);
+ });
+ });
+
it('retains events in queue when ClickHouse insert fails', async () => {
eventBuffer.add({
project_id: 'p12',
diff --git a/packages/core/src/buffers/event-buffer.ts b/packages/core/src/buffers/event-buffer.ts
index 379455967..ccb888168 100644
--- a/packages/core/src/buffers/event-buffer.ts
+++ b/packages/core/src/buffers/event-buffer.ts
@@ -59,6 +59,14 @@ const DEFAULT_CHUNK_SIZE = 1000;
const DEFAULT_MICRO_BATCH_MS = 10;
const DEFAULT_MICRO_BATCH_SIZE = 100;
+/**
+ * How many times `drainPendingToRedis` will wait for someone else's write
+ * before it gives up on starting its own. Two passes is the normal worst case
+ * (wait for the in-flight write, then start one); the third is margin against
+ * a concurrent producer slipping a write in between.
+ */
+const MAX_FLUSH_PASSES = 3;
+
export class EventBuffer extends BaseBuffer {
private readonly batchSize =
this.deps.config.buffers.event.batchSize ?? DEFAULT_BATCH_SIZE;
@@ -73,6 +81,13 @@ export class EventBuffer extends BaseBuffer {
private pendingEvents: IClickhouseEvent[] = [];
private flushTimer: ReturnType<typeof setTimeout> | null = null;
private isFlushing = false;
+ /**
+ * The micro-batch write currently in flight, so a caller that arrives while
+ * `isFlushing` is set waits for its result instead of being told there was
+ * nothing to do. The Kafka batch handler and shutdown are the callers that
+ * cannot tolerate that answer.
+ */
+ private inFlightFlush: Promise<unknown> | null = null;
/** Tracks consecutive flush failures for observability; reset on success. */
private flushRetryCount = 0;
@@ -124,22 +139,89 @@ export class EventBuffer extends BaseBuffer {
}
public async flush() {
- if (this.flushTimer) {
- clearTimeout(this.flushTimer);
- this.flushTimer = null;
- }
- await this.flushLocalBuffer();
+ await this.drainPendingToRedis();
}
- private async flushLocalBuffer() {
- if (this.isFlushing || this.pendingEvents.length === 0) {
+ /**
+ * The same flush, but it THROWS when the rpush did not land, and it does not
+ * resolve until every event that was pending when it was called is in Redis.
+ *
+ * `flush()` swallows a Redis failure on purpose — it re-queues the events and
+ * the micro-batch timer tries again, which is right while the process lives.
+ * The two callers here have no next attempt: the Kafka batch handler is about
+ * to resolve offsets that kafkajs commits as soon as it returns, and shutdown
+ * is about to exit. Both must be able to SEE the failure and decline to
+ * commit — a redelivered duplicate is recoverable, a dropped `pendingEvents`
+ * array is not (M18-001, drill 03).
+ */
+ public async flushPendingOrThrow(): Promise<void> {
+ const failure = await this.drainPendingToRedis();
+ if (failure === null) {
return;
}
+ throw failure instanceof Error ? failure : new Error(String(failure));
+ }
+ /**
+ * A write always takes the WHOLE pending array, so one write STARTED after
+ * this call covers every event that was pending when it was made. A write
+ * already in flight does not — it may have begun before the last `add()` —
+ * so wait that one out and then start our own. Deliberately not "loop until
+ * the buffer is empty": another producer (a session-end job) adding events
+ * concurrently must not be able to turn a successful flush into a failure.
+ *
+ * @returns the failure the rpush ended with, or `null` on success.
+ */
+ private async drainPendingToRedis(): Promise<unknown> {
+ for (let pass = 0; pass < MAX_FLUSH_PASSES; pass++) {
+ if (this.flushTimer) {
+ clearTimeout(this.flushTimer);
+ this.flushTimer = null;
+ }
+
+ const nothingToDrain =
+ !this.isFlushing && this.pendingEvents.length === 0;
+ if (nothingToDrain) {
+ return null;
+ }
+
+ const startsItsOwnWrite = !this.isFlushing;
+ const failure = await this.flushLocalBuffer();
+ if (failure !== null) {
+ return failure;
+ }
+ if (startsItsOwnWrite) {
+ return null;
+ }
+ }
+
+ return new Error(
+ `event buffer could not start its own flush within ${MAX_FLUSH_PASSES} passes`
+ );
+ }
+
+ /**
+ * Never rejects — `add()` calls it without awaiting. The failure comes back
+ * as the resolved value instead, for the one caller that must act on it.
+ */
+ private flushLocalBuffer(): Promise<unknown> {
+ if (this.isFlushing) {
+ return this.inFlightFlush ?? Promise.resolve(null);
+ }
+ if (this.pendingEvents.length === 0) {
+ return Promise.resolve(null);
+ }
+
+ this.inFlightFlush = this.writePendingToRedis();
+ return this.inFlightFlush;
+ }
+
+ private async writePendingToRedis(): Promise<unknown> {
this.isFlushing = true;
const eventsToFlush = this.pendingEvents;
this.pendingEvents = [];
+ let failure: unknown = null;
try {
const redis = getRedisCache();
@@ -149,10 +231,23 @@ export class EventBuffer extends BaseBuffer {
multi.rpush(this.queueKey, JSON.stringify(event));
}
- await multi.exec();
+ const results = await multi.exec();
+ // ioredis RESOLVES a MULTI whose individual commands failed, handing the
+ // error back per entry — so a WRONGTYPE or an out-of-memory rpush would
+ // otherwise read as a successful flush and the events would be dropped
+ // silently. The batch handler decides whether to resolve Kafka offsets
+ // on this answer, so it has to be the truth (M18-001).
+ if (results === null) {
+ throw new Error('event buffer rpush transaction was aborted');
+ }
+ const rejected = results.find(([commandError]) => commandError !== null);
+ if (rejected?.[0]) {
+ throw rejected[0];
+ }
this.flushRetryCount = 0;
} catch (error) {
+ failure = error;
// Re-queue failed events at the front to preserve order and avoid data loss
this.pendingEvents = eventsToFlush.concat(this.pendingEvents);
@@ -167,6 +262,7 @@ export class EventBuffer extends BaseBuffer {
);
} finally {
this.isFlushing = false;
+ this.inFlightFlush = null;
// Events may have accumulated while we were flushing; schedule another flush if needed
if (this.pendingEvents.length > 0 && !this.flushTimer) {
this.flushTimer = setTimeout(() => {
@@ -175,6 +271,8 @@ export class EventBuffer extends BaseBuffer {
}, this.microBatchIntervalMs);
}
}
+
+ return failure;
}
protected getRedisListKey(): string {
diff --git a/packages/core/src/modules/ingest/src/consumer.test.ts b/packages/core/src/modules/ingest/src/consumer.test.ts
index f4645d4cf..b2f9a42f6 100644
--- a/packages/core/src/modules/ingest/src/consumer.test.ts
+++ b/packages/core/src/modules/ingest/src/consumer.test.ts
@@ -77,9 +77,13 @@ function makeDeps(overrides: Partial<EventsBatchHandlerDeps> = {}) {
async () => undefined
);
const sleep = mock(async (_ms: number) => undefined);
+ const flushBufferedEvents = mock<
+ EventsBatchHandlerDeps['flushBufferedEvents']
+ >(async () => undefined);
const deps: EventsBatchHandlerDeps = {
handleEvent,
sendToDeadLetter,
+ flushBufferedEvents,
logger: {
info: mock(() => undefined),
warn: mock(() => undefined),
@@ -100,6 +104,8 @@ function makeDeps(overrides: Partial<EventsBatchHandlerDeps> = {}) {
handleEvent,
sendToDeadLetter: (overrides.sendToDeadLetter ??
sendToDeadLetter) as typeof sendToDeadLetter,
+ flushBufferedEvents: (overrides.flushBufferedEvents ??
+ flushBufferedEvents) as typeof flushBufferedEvents,
sleep,
};
}
@@ -402,3 +408,130 @@ describe('reprocess counter', () => {
expect(metrics.reprocessed).not.toHaveBeenCalled();
});
});
+
+/**
+ * The regression test for drill 03's loss (M18-001).
+ *
+ * The event a handler accepted lives in an in-process array until the buffer
+ * pushes it to Redis, and kafkajs commits whatever `resolveOffset` marked the
+ * moment `eachBatch` returns — `autoCommit` is on and this consumer never
+ * turns it off, so `consumer.stop()` is NOT the commit point. Resolving an
+ * offset for an event that is still only in memory is exactly how a graceful
+ * restart lost 2 of 44,075 events: the offsets were committed, the process
+ * exited, and nothing was redelivered.
+ *
+ * `resolveOffset` is therefore the commit in these tests. It is the only thing
+ * that decides what gets committed.
+ */
+describe('durability before commit', () => {
+ test('flushes the buffered events before it resolves any offset', async () => {
+ const { payload, resolveOffset } = makeBatch([
+ message(0, 'a'),
+ message(1, 'b'),
+ ]);
+ let handled = 0;
+ let resolvedWhenFlushed = -1;
+ let handledWhenFlushed = -1;
+
+ const { deps } = makeDeps({
+ handleEvent: mock(async () => {
+ handled += 1;
+ return undefined;
+ }),
+ flushBufferedEvents: mock(async () => {
+ resolvedWhenFlushed = resolveOffset.mock.calls.length;
+ handledWhenFlushed = handled;
+ }),
+ });
+ const handler = createEventsBatchHandler(deps);
+
+ await handler.eachBatch(payload);
+
+ // Nothing committed yet, and every message already handled — so the flush
+ // covers the whole batch and none of it was committed behind its back.
+ expect(resolvedWhenFlushed).toBe(0);
+ expect(handledWhenFlushed).toBe(2);
+ expect(resolvedOffsets(resolveOffset)).toEqual(['0', '1']);
+ });
+
+ test('resolves NO offset when the flush fails', async () => {
+ const logger = {
+ info: mock(() => undefined),
+ warn: mock(() => undefined),
+ error: mock(() => undefined),
+ };
+ const onActivity = mock(() => undefined);
+ const { deps } = makeDeps({
+ flushBufferedEvents: mock(() =>
+ Promise.reject(new Error('redis is unreachable'))
+ ),
+ logger,
+ onActivity,
+ });
+ const handler = createEventsBatchHandler(deps);
+ const { payload, resolveOffset, heartbeat } = makeBatch([
+ message(0, 'a'),
+ message(1, 'b'),
+ ]);
+
+ await handler.eachBatch(payload);
+
+ // The whole batch stays uncommitted, so the broker redelivers it. A
+ // duplicate is recoverable; a loss is not.
+ expect(resolvedOffsets(resolveOffset)).toEqual([]);
+ expect(logger.error).toHaveBeenCalledTimes(1);
+ // Still a member of the group, and still visibly alive.
+ expect(heartbeat).toHaveBeenCalled();
+ expect(onActivity).toHaveBeenCalledTimes(1);
+ });
+
+ test('redelivery after a failed flush commits, and is not flagged a duplicate', async () => {
+ let redisIsDown = true;
+ const { deps, metrics } = makeDeps({
+ flushBufferedEvents: mock(async () => {
+ if (redisIsDown) {
+ throw new Error('redis is unreachable');
+ }
+ }),
+ });
+ const handler = createEventsBatchHandler(deps);
+
+ const first = makeBatch([message(0, 'a'), message(1, 'b')]);
+ await handler.eachBatch(first.payload);
+ expect(resolvedOffsets(first.resolveOffset)).toEqual([]);
+
+ redisIsDown = false;
+ const redelivered = makeBatch([message(0, 'a'), message(1, 'b')]);
+ await handler.eachBatch(redelivered.payload);
+
+ expect(resolvedOffsets(redelivered.resolveOffset)).toEqual(['0', '1']);
+ // The failed batch never advanced the watermark, so the replay it asked
+ // for is not then reported as an at-least-once duplicate.
+ expect(metrics.reprocessed).not.toHaveBeenCalled();
+ });
+
+ test('flushes what a shutdown-truncated batch handled, before resolving it', async () => {
+ // Drill 03's shape: SIGTERM lands mid-batch, `isRunning` goes false, and
+ // the handler resolves only the prefix it finished. That prefix must be
+ // durable too — it is the window the graceful restart used to lose.
+ let handled = 0;
+ const flushBufferedEvents = mock(async () => undefined);
+ const { deps } = makeDeps({
+ flushBufferedEvents,
+ handleEvent: mock(async () => {
+ handled += 1;
+ return undefined;
+ }),
+ });
+ const handler = createEventsBatchHandler(deps);
+ const { payload, resolveOffset } = makeBatch(
+ [message(0, 'a'), message(1, 'a'), message(2, 'a')],
+ { isRunning: () => handled < 2 }
+ );
+
+ await handler.eachBatch(payload);
+
+ expect(resolvedOffsets(resolveOffset)).toEqual(['0', '1']);
+ expect(flushBufferedEvents).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/modules/ingest/src/consumer.ts b/packages/core/src/modules/ingest/src/consumer.ts
index cf7225abc..390e47bc6 100644
--- a/packages/core/src/modules/ingest/src/consumer.ts
+++ b/packages/core/src/modules/ingest/src/consumer.ts
@@ -17,6 +17,16 @@ import type {
import type { IncomingEventPayload } from './incoming-event';
export interface KafkaConsumerHandle {
+ /**
+ * Stop fetching, then wait for the in-flight `eachBatch` to finish. Split
+ * out from `stop()` so a graceful shutdown has a point where nothing new can
+ * enter the event buffer but the consumer has not been torn down yet — that
+ * is where shutdown flushes whatever was buffered OUTSIDE a Kafka batch
+ * (M18-001, drill 03). Events buffered inside one are already durable: see
+ * `flushBufferedEvents` below.
+ */
+ stopConsuming: () => Promise<void>;
+ /** Disconnect. Safe to call after `stopConsuming`, and without it. */
stop: () => Promise<void>;
}
@@ -66,6 +76,18 @@ export interface EventsBatchHandlerDeps {
meta: { partition: number; offset: string }
) => Promise<unknown>;
sendToDeadLetter: (message: DeadLetterMessage) => Promise<void>;
+ /**
+ * Make everything the handlers buffered in process memory durable.
+ *
+ * Called once every message in the batch has been handled and BEFORE the
+ * first `resolveOffset`, because kafkajs commits the resolved offsets as
+ * soon as `eachBatch` returns (`autoCommit` defaults to true and this
+ * consumer does not turn it off) — not at `consumer.stop()`. It MUST reject
+ * when the write did not land: drill 03 lost 2 of 44,075 events on a
+ * graceful restart because the offsets of events that existed only in the
+ * event buffer's in-process array were committed anyway (M18-001).
+ */
+ flushBufferedEvents: () => Promise<void>;
logger: ConsumerLogger;
metrics: ConsumerMetrics;
onActivity: () => void;
@@ -215,6 +237,25 @@ export function createEventsBatchHandler(
return deadLetter(message, partition, 'handler_error', result.err);
};
+ /**
+ * @returns false when the flush failed, which leaves the watermark where it
+ * was so the redelivered batch is not then reported as a duplicate.
+ */
+ const bufferedEventsAreDurable = async (
+ partition: number
+ ): Promise<boolean> => {
+ try {
+ await deps.flushBufferedEvents();
+ return true;
+ } catch (err) {
+ deps.logger.error(
+ { err, partition },
+ 'buffered events could not be made durable — batch left unresolved for redelivery'
+ );
+ return false;
+ }
+ };
+
const eachBatch = async ({
batch,
resolveOffset,
@@ -298,18 +339,25 @@ export function createEventsBatchHandler(
})
);
- // 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;
+ // Durability before commit. Handled is not the same as safe: the events
+ // are in an in-process array until they are pushed to Redis, and every
+ // offset resolved below is committed the instant this handler returns. If
+ // that push will not land, resolve NOTHING and let the broker redeliver
+ // the whole batch — a duplicate is recoverable, a loss is not.
+ if (await bufferedEventsAreDurable(batch.partition)) {
+ // 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));
}
- resolveOffset(m.offset);
- newHWM = Math.max(newHWM, Number(m.offset));
+ resolvedHWM.set(pk, newHWM);
}
- resolvedHWM.set(pk, newHWM);
await heartbeat();
deps.onActivity();
@@ -408,6 +456,12 @@ export async function startKafkaEventsConsumer(
);
return {
+ // kafkajs `stop()` is `sharedPromiseTo`, so `disconnect()`'s own internal
+ // stop() below is the already-resolved promise rather than a second
+ // teardown.
+ stopConsuming: async () => {
+ await consumer.stop();
+ },
stop: async () => {
await consumer.disconnect();
},