:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion-consumer): serve WorkerIngest gRPC stream in the ingestion API server (#85191)
José Sequeiraafd5369ce1b2
diff --git a/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.ts b/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.tsindex 5bf637d0ed7b..067f69e671fa 100644--- a/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.ts+++ b/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.ts@@ -10,7 +10,7 @@ import { enumDesc, fileDesc, messageDesc, serviceDesc } from '@bufbuild/protobufexport const file_ingestion_worker_v1_worker: GenFile =/*@__PURE__*/fileDesc(- 'CiBpbmdlc3Rpb24vd29ya2VyL3YxL3dvcmtlci5wcm90bxITaW5nZXN0aW9uLndvcmtlci52MSKDAQoTSW5nZXN0U3RyZWFtUmVxdWVzdBIxCgVoZWxsbxgBIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3RyZWFtSGVsbG9IABIyCglzdWJfYmF0Y2gYAiABKAsyHS5pbmdlc3Rpb24ud29ya2VyLnYxLlN1YkJhdGNoSABCBQoDbXNnIjgKC1N0cmVhbUhlbGxvEhMKC2NvbnN1bWVyX2lkGAEgASgJEhQKDHN0cmVhbV9lcG9jaBgCIAEoBCKIAQoIU3ViQmF0Y2gSCwoDc2VxGAEgASgEEhAKCGJhdGNoX2lkGAIgASgJEjMKCG1lc3NhZ2VzGAMgAygLMiEuaW5nZXN0aW9uLndvcmtlci52MS5LYWZrYU1lc3NhZ2USDgoGcmVwbGF5GAQgASgIEhgKEGFzc2lnbm1lbnRfZXBvY2gYBSABKAQi/AEKDEthZmthTWVzc2FnZRINCgV0b3BpYxgBIAEoCRIRCglwYXJ0aXRpb24YAiABKAUSDgoGb2Zmc2V0GAMgASgDEhEKCXRpbWVzdGFtcBgEIAEoAxIQCgNrZXkYBSABKAlIAIgBARISCgV2YWx1ZRgGIAEoCUgBiAEBEj8KB2hlYWRlcnMYByADKAsyLi5pbmdlc3Rpb24ud29ya2VyLnYxLkthZmthTWVzc2FnZS5IZWFkZXJzRW50cnkaLgoMSGVhZGVyc0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAFCBgoEX2tleUIICgZfdmFsdWUieQoUSW5nZXN0U3RyZWFtUmVzcG9uc2USCwoDc2VxGAEgASgEEjMKBnN0YXR1cxgCIAEoDjIjLmluZ2VzdGlvbi53b3JrZXIudjEuU3ViQmF0Y2hTdGF0dXMSEAoIYWNjZXB0ZWQYAyABKA0SDQoFZXJyb3IYBCABKAkqaAoOU3ViQmF0Y2hTdGF0dXMSIAocU1VCX0JBVENIX1NUQVRVU19VTlNQRUNJRklFRBAAEhcKE1NVQl9CQVRDSF9TVEFUVVNfT0sQARIbChdTVUJfQkFUQ0hfU1RBVFVTX0ZBSUxFRBACMncKDFdvcmtlckluZ2VzdBJnCgxJbmdlc3RTdHJlYW0SKC5pbmdlc3Rpb24ud29ya2VyLnYxLkluZ2VzdFN0cmVhbVJlcXVlc3QaKS5pbmdlc3Rpb24ud29ya2VyLnYxLkluZ2VzdFN0cmVhbVJlc3BvbnNlKAEwAWIGcHJvdG8z'+ 'CiBpbmdlc3Rpb24vd29ya2VyL3YxL3dvcmtlci5wcm90bxITaW5nZXN0aW9uLndvcmtlci52MSKDAQoTSW5nZXN0U3RyZWFtUmVxdWVzdBIxCgVoZWxsbxgBIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3RyZWFtSGVsbG9IABIyCglzdWJfYmF0Y2gYAiABKAsyHS5pbmdlc3Rpb24ud29ya2VyLnYxLlN1YkJhdGNoSABCBQoDbXNnIjgKC1N0cmVhbUhlbGxvEhMKC2NvbnN1bWVyX2lkGAEgASgJEhQKDHN0cmVhbV9lcG9jaBgCIAEoBCKIAQoIU3ViQmF0Y2gSCwoDc2VxGAEgASgEEhAKCGJhdGNoX2lkGAIgASgJEjMKCG1lc3NhZ2VzGAMgAygLMiEuaW5nZXN0aW9uLndvcmtlci52MS5LYWZrYU1lc3NhZ2USDgoGcmVwbGF5GAQgASgIEhgKEGFzc2lnbm1lbnRfZXBvY2gYBSABKAQi/AEKDEthZmthTWVzc2FnZRINCgV0b3BpYxgBIAEoCRIRCglwYXJ0aXRpb24YAiABKAUSDgoGb2Zmc2V0GAMgASgDEhEKCXRpbWVzdGFtcBgEIAEoAxIQCgNrZXkYBSABKAlIAIgBARISCgV2YWx1ZRgGIAEoCUgBiAEBEj8KB2hlYWRlcnMYByADKAsyLi5pbmdlc3Rpb24ud29ya2VyLnYxLkthZmthTWVzc2FnZS5IZWFkZXJzRW50cnkaLgoMSGVhZGVyc0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAFCBgoEX2tleUIICgZfdmFsdWUigQEKFEluZ2VzdFN0cmVhbVJlc3BvbnNlEjEKBXJlYWR5GAEgASgLMiAuaW5nZXN0aW9uLndvcmtlci52MS5TdHJlYW1SZWFkeUgAEi8KA2FjaxgCIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3ViQmF0Y2hBY2tIAEIFCgNtc2ciDQoLU3RyZWFtUmVhZHkicAoLU3ViQmF0Y2hBY2sSCwoDc2VxGAEgASgEEjMKBnN0YXR1cxgCIAEoDjIjLmluZ2VzdGlvbi53b3JrZXIudjEuU3ViQmF0Y2hTdGF0dXMSEAoIYWNjZXB0ZWQYAyABKA0SDQoFZXJyb3IYBCABKAkqaAoOU3ViQmF0Y2hTdGF0dXMSIAocU1VCX0JBVENIX1NUQVRVU19VTlNQRUNJRklFRBAAEhcKE1NVQl9CQVRDSF9TVEFUVVNfT0sQARIbChdTVUJfQkFUQ0hfU1RBVFVTX0ZBSUxFRBACMncKDFdvcmtlckluZ2VzdBJnCgxJbmdlc3RTdHJlYW0SKC5pbmdlc3Rpb24ud29ya2VyLnYxLkluZ2VzdFN0cmVhbVJlcXVlc3QaKS5pbmdlc3Rpb24ud29ya2VyLnYxLkluZ2VzdFN0cmVhbVJlc3BvbnNlKAEwAWIGcHJvdG8z')/**@@ -188,11 +188,65 @@ export const KafkaMessageSchema: GenMessage<KafkaMessage> =messageDesc(file_ingestion_worker_v1_worker, 3)/**- * IngestStreamResponse acks one sub-batch.+ * IngestStreamResponse is one frame on the worker-to-consumer stream.** @generated from message ingestion.worker.v1.IngestStreamResponse*/export type IngestStreamResponse = Message<'ingestion.worker.v1.IngestStreamResponse'> & {+ /**+ * @generated from oneof ingestion.worker.v1.IngestStreamResponse.msg+ */+ msg:+ | {+ /**+ * First frame on every stream, sent as soon as the worker accepts it and+ * before any sub-batch completes: flushes response headers so the+ * consumer's stream-open resolves (some HTTP/2 server stacks defer+ * headers until the first response message).+ *+ * @generated from field: ingestion.worker.v1.StreamReady ready = 1;+ */+ value: StreamReady+ case: 'ready'+ }+ | {+ /**+ * @generated from field: ingestion.worker.v1.SubBatchAck ack = 2;+ */+ value: SubBatchAck+ case: 'ack'+ }+ | { case: undefined; value?: undefined }+}++/**+ * Describes the message ingestion.worker.v1.IngestStreamResponse.+ * Use `create(IngestStreamResponseSchema)` to create a new message.+ */+export const IngestStreamResponseSchema: GenMessage<IngestStreamResponse> =+ /*@__PURE__*/+ messageDesc(file_ingestion_worker_v1_worker, 4)++/**+ * StreamReady carries no data yet; it is the slot where the worker could+ * later advertise limits or echo the hello.+ *+ * @generated from message ingestion.worker.v1.StreamReady+ */+export type StreamReady = Message<'ingestion.worker.v1.StreamReady'> & {}++/**+ * Describes the message ingestion.worker.v1.StreamReady.+ * Use `create(StreamReadySchema)` to create a new message.+ */+export const StreamReadySchema: GenMessage<StreamReady> = /*@__PURE__*/ messageDesc(file_ingestion_worker_v1_worker, 5)++/**+ * SubBatchAck acks one sub-batch.+ *+ * @generated from message ingestion.worker.v1.SubBatchAck+ */+export type SubBatchAck = Message<'ingestion.worker.v1.SubBatchAck'> & {/*** The `SubBatch.seq` this ack resolves.*@@ -222,12 +276,10 @@ export type IngestStreamResponse = Message<'ingestion.worker.v1.IngestStreamResp}/**- * Describes the message ingestion.worker.v1.IngestStreamResponse.- * Use `create(IngestStreamResponseSchema)` to create a new message.+ * Describes the message ingestion.worker.v1.SubBatchAck.+ * Use `create(SubBatchAckSchema)` to create a new message.*/-export const IngestStreamResponseSchema: GenMessage<IngestStreamResponse> =- /*@__PURE__*/- messageDesc(file_ingestion_worker_v1_worker, 4)+export const SubBatchAckSchema: GenMessage<SubBatchAck> = /*@__PURE__*/ messageDesc(file_ingestion_worker_v1_worker, 6)/*** SubBatchStatus is the outcome of processing one sub-batch.diff --git a/nodejs/src/ingestion/api/grpc-server.test.ts b/nodejs/src/ingestion/api/grpc-server.test.tsnew file mode 100644index 000000000000..28749a111256--- /dev/null+++ b/nodejs/src/ingestion/api/grpc-server.test.ts@@ -0,0 +1,529 @@+import { create } from '@bufbuild/protobuf'+import { Code, ConnectError } from '@connectrpc/connect'+import { register } from 'prom-client'++import {+ IngestStreamRequest,+ IngestStreamRequestSchema,+ IngestStreamResponse,+ KafkaMessageSchema,+ StreamHelloSchema,+ SubBatchAck,+ SubBatchStatus,+} from '~/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb'+import { FeedResult } from '~/ingestion/framework/batching-pipeline'++import { FeedOrderSentinel } from './feed-order-sentinel'+import { CompletedSubBatch, StreamIngestDriver, WorkerIngestServer } from './grpc-server'++class Deferred<T> {+ resolve!: (value: T) => void+ reject!: (error: Error) => void+ promise = new Promise<T>((resolve, reject) => {+ this.resolve = resolve+ this.reject = reject+ })+}++/** Push-based request source standing in for the consumer's side of the stream. */+class FrameSource implements AsyncIterable<IngestStreamRequest> {+ private frames: IngestStreamRequest[] = []+ private waiters: Deferred<IteratorResult<IngestStreamRequest>>[] = []+ private done = false++ push(frame: IngestStreamRequest): void {+ const waiter = this.waiters.shift()+ if (waiter) {+ waiter.resolve({ value: frame, done: false })+ return+ }+ this.frames.push(frame)+ }++ end(): void {+ this.done = true+ for (const waiter of this.waiters.splice(0)) {+ waiter.resolve({ value: undefined, done: true })+ }+ }++ [Symbol.asyncIterator](): AsyncIterator<IngestStreamRequest> {+ return {+ next: (): Promise<IteratorResult<IngestStreamRequest>> => {+ if (this.frames.length > 0) {+ return Promise.resolve({ value: this.frames.shift()!, done: false })+ }+ if (this.done) {+ return Promise.resolve({ value: undefined, done: true })+ }+ const waiter = new Deferred<IteratorResult<IngestStreamRequest>>()+ this.waiters.push(waiter)+ return waiter.promise+ },+ }+ }+}++/** Records feeds and lets the test hand-complete batches. */+class FakeDriver implements StreamIngestDriver {+ feeds: { streamId: number; seq: number; offsets: number[] }[] = []+ feedResult: FeedResult = { ok: true }+ private completions: CompletedSubBatch[] = []+ private nextWaiters: Deferred<CompletedSubBatch | null>[] = []+ nextError: Error | null = null++ feed(streamId: number, seq: number, messages: { offset: number }[]): Promise<FeedResult> {+ this.feeds.push({ streamId, seq, offsets: messages.map((m) => m.offset) })+ return Promise.resolve(this.feedResult)+ }++ next(): Promise<CompletedSubBatch | null> {+ if (this.nextError) {+ return Promise.reject(this.nextError)+ }+ if (this.completions.length > 0) {+ return Promise.resolve(this.completions.shift()!)+ }+ const waiter = new Deferred<CompletedSubBatch | null>()+ this.nextWaiters.push(waiter)+ return waiter.promise+ }++ complete(batch: Omit<CompletedSubBatch, 'settled'>, settled: Promise<void> = Promise.resolve()): void {+ const completed: CompletedSubBatch = { ...batch, settled }+ const waiter = this.nextWaiters.shift()+ if (waiter) {+ waiter.resolve(completed)+ return+ }+ this.completions.push(completed)+ }++ failNext(error: Error): void {+ this.nextError = error+ const waiter = this.nextWaiters.shift()+ if (waiter) {+ waiter.reject(error)+ }+ }+}++function hello(overrides: { consumerId?: string; streamEpoch?: bigint } = {}): IngestStreamRequest {+ return create(IngestStreamRequestSchema, {+ msg: {+ case: 'hello',+ value: create(StreamHelloSchema, {+ consumerId: overrides.consumerId ?? 'consumer-1',+ streamEpoch: overrides.streamEpoch ?? 1n,+ }),+ },+ })+}++function subBatch(+ seq: number,+ offsets: number[],+ overrides: { replay?: boolean; assignmentEpoch?: bigint } = {}+): IngestStreamRequest {+ return create(IngestStreamRequestSchema, {+ msg: {+ case: 'subBatch',+ value: {+ seq: BigInt(seq),+ batchId: `batch-${seq}`,+ replay: overrides.replay ?? false,+ assignmentEpoch: overrides.assignmentEpoch ?? 1n,+ messages: offsets.map((offset) =>+ create(KafkaMessageSchema, {+ topic: 'events',+ partition: 0,+ offset: BigInt(offset),+ timestamp: 0n,+ key: 'k',+ value: '{}',+ headers: { token: 'tok', distinct_id: 'd1' },+ })+ ),+ },+ },+ })+}++interface Collected {+ /** Sub-batch acks, unwrapped from the response oneof. */+ acks: SubBatchAck[]+ /** Every response frame in arrival order, ready frame included. */+ all: IngestStreamResponse[]+ error: ConnectError | null+ ended: Promise<void>+}++function collect(server: WorkerIngestServer, source: FrameSource, signal?: AbortSignal): Collected {+ const collected: Collected = { acks: [], all: [], error: null, ended: Promise.resolve() }+ collected.ended = (async () => {+ try {+ for await (const frame of server.ingestStream(source, signal)) {+ collected.all.push(frame)+ if (frame.msg.case === 'ack') {+ collected.acks.push(frame.msg.value)+ }+ }+ } catch (error) {+ collected.error = error as ConnectError+ }+ })()+ return collected+}++async function until(condition: () => boolean | Promise<boolean>): Promise<void> {+ const deadline = Date.now() + 5_000+ while (!(await condition())) {+ if (Date.now() > deadline) {+ throw new Error('condition not met within 5s')+ }+ await new Promise((resolve) => setTimeout(resolve, 2))+ }+}++async function outOfOrderCount(): Promise<number> {+ const metric = register.getSingleMetric('ingestion_api_out_of_order_messages_total')+ const value = (await metric!.get()).values[0]?.value+ return value ?? 0+}++async function slotWaiters(): Promise<number> {+ const metric = register.getSingleMetric('ingestion_api_grpc_feed_slot_waiters')+ const value = (await metric!.get()).values[0]?.value+ return value ?? 0+}++describe('WorkerIngestServer', () => {+ let server: WorkerIngestServer+ let driver: FakeDriver+ let onFatal: jest.Mock+ let sentinel: FeedOrderSentinel++ beforeEach(async () => {+ driver = new FakeDriver()+ onFatal = jest.fn()+ sentinel = new FeedOrderSentinel()+ server = new WorkerIngestServer(+ { port: 0, maxConcurrentBatches: 4, capacityRetryMs: 1, pumpIdleMs: 1, drainTimeoutMs: 200 },+ { driver, feedOrderSentinel: sentinel, onFatal }+ )+ await server.start()+ })++ afterEach(async () => {+ await server.stop()+ })++ it('sends a ready frame before any work arrives', async () => {+ // Regression: connect-node flushes response headers only with the+ // first response message, and the consumer's stream-open awaits those+ // headers before sending anything — without an immediate ready frame+ // the two sides deadlock at open (observed against production workers).+ const source = new FrameSource()+ const collected = collect(server, source)++ source.push(hello())+ await until(() => collected.all.length === 1)+ expect(collected.all[0].msg.case).toBe('ready')+ source.end()+ await collected.ended+ expect(collected.error).toBeNull()+ })++ it('acks completions out of order by seq and ends the stream after half-close', async () => {+ const source = new FrameSource()+ const collected = collect(server, source)++ source.push(hello())+ source.push(subBatch(1, [10, 11]))+ source.push(subBatch(2, [12]))+ await until(() => driver.feeds.length === 2)+ const streamId = driver.feeds[0].streamId++ // Sub-batch 2 finishes first — its ack must not wait for sub-batch 1.+ driver.complete({ streamId, seq: 2, accepted: 1 })+ await until(() => collected.acks.length === 1)+ driver.complete({ streamId, seq: 1, accepted: 2 })+ source.end()+ await collected.ended++ expect(collected.error).toBeNull()+ expect(collected.acks.map((ack) => [Number(ack.seq), ack.status, ack.accepted])).toEqual([+ [2, SubBatchStatus.OK, 1],+ [1, SubBatchStatus.OK, 2],+ ])+ expect(server.streamCount).toBe(0)+ })++ it('stop() drains in-flight sub-batch acks before ending streams', async () => {+ const source = new FrameSource()+ const collected = collect(server, source)++ source.push(hello())+ source.push(subBatch(1, [10]))+ await until(() => driver.feeds.length === 1)+ const streamId = driver.feeds[0].streamId++ // The batch settles only after stop() has begun — its ack must still+ // reach the consumer, or every scale-down forces a replay.+ const stopping = server.stop()++ // A stream opened mid-drain must be refused, not fed.+ const late = collect(server, new FrameSource())+ await late.ended+ expect(late.error?.code).toBe(Code.Unavailable)++ driver.complete({ streamId, seq: 1, accepted: 1 })+ await stopping+ source.end()+ await collected.ended++ expect(collected.error).toBeNull()+ expect(collected.acks.map((ack) => [Number(ack.seq), ack.accepted])).toEqual([[1, 1]])+ expect(driver.feeds).toHaveLength(1)+ })++ it('feeds sub-batches in stream order, stalling reads while the pipeline is at capacity', async () => {+ const source = new FrameSource()+ collect(server, source)++ driver.feedResult = { ok: false, kind: 'at_capacity', reason: 'full' }+ source.push(hello())+ source.push(subBatch(1, [10]))+ source.push(subBatch(2, [11]))++ // Sub-batch 1 keeps retrying; sub-batch 2 must not reach the driver.+ await until(() => driver.feeds.length >= 2)+ expect(driver.feeds.every((feed) => feed.seq === 1)).toBe(true)++ driver.feedResult = { ok: true }+ await until(() => driver.feeds.some((feed) => feed.seq === 2))+ const acceptedOrder = driver.feeds.filter((feed, i) => driver.feeds.findIndex((f) => f.seq === feed.seq) === i)+ expect(acceptedOrder.map((feed) => feed.seq)).toEqual([1, 2])+ })++ it.each([+ ['a sub-batch before the hello', [subBatch(1, [10])]],+ ['a duplicate hello', [hello(), hello()]],+ ['a seq gap', [hello(), subBatch(2, [10])]],+ ])('closes the stream on %s without feeding the offending frame', async (_name, frames) => {+ const source = new FrameSource()+ const collected = collect(server, source)++ for (const frame of frames) {+ source.push(frame)+ }+ await collected.ended++ expect(collected.error).not.toBeNull()+ expect(collected.error!.code).toBe(Code.FailedPrecondition)+ expect(driver.feeds).toEqual([])+ expect(server.streamCount).toBe(0)+ })++ it('acks an empty sub-batch immediately instead of feeding it', async () => {+ // An empty feed() is a no-op that never completes a batch — feeding it+ // would leave the consumer waiting for an ack forever.+ const source = new FrameSource()+ const collected = collect(server, source)++ source.push(hello())+ source.push(subBatch(1, []))+ await until(() => collected.acks.length === 1)+ source.end()+ await collected.ended++ expect(collected.error).toBeNull()+ expect(collected.acks[0].accepted).toBe(0)+ expect(driver.feeds).toEqual([])+ })++ it('fails the stream and reports fatal when the pipeline dies mid-batch', async () => {+ const source = new FrameSource()+ const collected = collect(server, source)++ source.push(hello())+ source.push(subBatch(1, [10]))+ await until(() => driver.feeds.length === 1)+ driver.failNext(new Error('pipeline poisoned'))+ await collected.ended++ expect(collected.error!.code).toBe(Code.Internal)+ expect(onFatal).toHaveBeenCalledWith(expect.objectContaining({ message: 'pipeline poisoned' }))+ })++ it('nacks a rejected sub-batch before closing the stream', async () => {+ const source = new FrameSource()+ const collected = collect(server, source)++ driver.feedResult = { ok: false, kind: 'before_batch_failed', reason: 'hook failed' }+ source.push(hello())+ source.push(subBatch(1, [10]))+ await collected.ended++ expect(collected.acks.map((ack) => [Number(ack.seq), ack.status])).toEqual([[1, SubBatchStatus.FAILED]])+ expect(collected.acks[0].error).toBe('hook failed')+ expect(collected.error!.code).toBe(Code.Internal)+ })++ it('grants feed slots in arrival order across streams instead of racing', async () => {+ // Regression: capacity was granted by a retry race, so a busy stream+ // could starve a quiet one indefinitely — in prod, consumers wedged+ // with zero completed batches while their sub-batches sat unfed.+ const fairDriver = new FakeDriver()+ const fairServer = new WorkerIngestServer(+ { port: 0, maxConcurrentBatches: 1, capacityRetryMs: 1, pumpIdleMs: 1, drainTimeoutMs: 50 },+ { driver: fairDriver, onFatal: jest.fn() }+ )+ await fairServer.start()+ try {+ const sourceA = new FrameSource()+ const sourceB = new FrameSource()+ collect(fairServer, sourceA)+ collect(fairServer, sourceB)+ sourceA.push(hello({ consumerId: 'consumer-a' }))+ sourceB.push(hello({ consumerId: 'consumer-b' }))++ // A1 takes the only slot; A2 then queues for it.+ sourceA.push(subBatch(1, [1]))+ await until(() => fairDriver.feeds.length === 1)+ const streamA = fairDriver.feeds[0].streamId+ sourceA.push(subBatch(2, [2]))+ await until(async () => (await slotWaiters()) === 1)+ // B1 arrives third, A3 fourth.+ sourceB.push(subBatch(1, [3]))+ await until(async () => (await slotWaiters()) === 2)+ sourceA.push(subBatch(3, [4]))++ fairDriver.complete({ streamId: streamA, seq: 1, accepted: 1 })+ await until(() => fairDriver.feeds.length === 2)+ fairDriver.complete({ streamId: streamA, seq: 2, accepted: 1 })+ // B1 must get the freed slot before A3 — arrival order, not race.+ await until(() => fairDriver.feeds.length === 3)+ expect(fairDriver.feeds[2].streamId).not.toBe(streamA)+ } finally {+ await fairServer.stop()+ }+ })++ it('drops a cancelled stream from the admission queue so its slot skips to a live stream', async () => {+ // Regression: a stream that disconnected while waiting for a slot left+ // its waiter in the FIFO queue. A freed slot was granted to that dead+ // waiter ahead of live streams, feeding work that could never be acked+ // and starving real traffic under repeated disconnects.+ const laneDriver = new FakeDriver()+ const laneServer = new WorkerIngestServer(+ { port: 0, maxConcurrentBatches: 1, capacityRetryMs: 1, pumpIdleMs: 1, drainTimeoutMs: 50 },+ { driver: laneDriver, onFatal: jest.fn() }+ )+ await laneServer.start()+ try {+ const sourceA = new FrameSource()+ const cancelled = new AbortController()+ const sourceCancelled = new FrameSource()+ const sourceLive = new FrameSource()+ collect(laneServer, sourceA)+ collect(laneServer, sourceCancelled, cancelled.signal)+ collect(laneServer, sourceLive)++ sourceA.push(hello({ consumerId: 'consumer-a' }))+ sourceCancelled.push(hello({ consumerId: 'consumer-cancelled' }))+ sourceLive.push(hello({ consumerId: 'consumer-live' }))++ // A takes the only slot; the soon-to-cancel stream queues behind it.+ // The waiter gauge is process-global, so track it against a baseline.+ sourceA.push(subBatch(1, [1]))+ await until(() => laneDriver.feeds.length === 1)+ const streamA = laneDriver.feeds[0].streamId+ const baseWaiters = await slotWaiters()+ sourceCancelled.push(subBatch(1, [2]))+ await until(async () => (await slotWaiters()) === baseWaiters + 1)++ // The stream disconnects while parked — its waiter must leave the queue.+ cancelled.abort()+ await until(async () => (await slotWaiters()) === baseWaiters)++ // A live stream queues, then A's slot frees: it must go to the live+ // stream, and the cancelled stream's sub-batch (offset 2) never feeds.+ sourceLive.push(subBatch(1, [3]))+ await until(async () => (await slotWaiters()) === baseWaiters + 1)+ laneDriver.complete({ streamId: streamA, seq: 1, accepted: 1 })+ await until(() => laneDriver.feeds.length === 2)++ expect(laneDriver.feeds[1].offsets).toEqual([3])+ expect(laneDriver.feeds.some((f) => f.offsets.includes(2))).toBe(false)+ } finally {+ await laneServer.stop()+ }+ })++ it('a slow batch settlement does not block another sub-batch ack', async () => {+ // Regression: the pump awaited each completed batch's side effects+ // before pulling the next completion, head-of-line blocking every+ // stream's acks behind the slowest batch.+ const source = new FrameSource()+ const collected = collect(server, source)++ source.push(hello())+ source.push(subBatch(1, [10]))+ source.push(subBatch(2, [11]))+ await until(() => driver.feeds.length === 2)+ const streamId = driver.feeds[0].streamId++ driver.complete({ streamId, seq: 1, accepted: 1 }, new Promise<void>(() => {}))+ driver.complete({ streamId, seq: 2, accepted: 1 })+ await until(() => collected.acks.length === 1)+ expect(Number(collected.acks[0].seq)).toBe(2)+ })++ it('rebaselines the feed-order sentinel on a new assignment epoch instead of counting a violation', async () => {+ // A rebalance replays uncommitted (lower) offsets under the same+ // consumer id; scoping the sentinel by epoch is what keeps that from+ // counting as out-of-order — the false-positive class the HTTP+ // transport suffers from.+ const source = new FrameSource()+ collect(server, source)++ const before = await outOfOrderCount()+ source.push(hello())+ source.push(subBatch(1, [10, 11]))+ source.push(subBatch(2, [5, 6], { assignmentEpoch: 2n }))+ await until(() => driver.feeds.length === 2)+ expect(await outOfOrderCount()).toBe(before)++ // The same regression within one epoch is a real violation.+ source.push(subBatch(3, [2], { assignmentEpoch: 2n }))+ await until(() => driver.feeds.length === 3)+ expect(await outOfOrderCount()).toBe(before + 1)+ })++ it('refuses a stream past the total concurrency ceiling with ResourceExhausted', async () => {+ // The ceiling bounds total open streams so a peer that ignores the+ // per-session SETTINGS limit cannot make the server accumulate streams+ // without bound. It must refuse cleanly, not crash or hang.+ const capped = new WorkerIngestServer(+ { port: 0, maxConcurrentBatches: 4, capacityRetryMs: 1, pumpIdleMs: 1, maxStreams: 1 },+ { driver, feedOrderSentinel: sentinel, onFatal }+ )+ await capped.start()+ try {+ const held = new FrameSource()+ const first = collect(capped, held)+ await until(() => capped.streamCount === 1)++ const rejected = collect(capped, new FrameSource())+ await rejected.ended+ expect(rejected.error?.code).toBe(Code.ResourceExhausted)+ expect(capped.streamCount).toBe(1)++ held.end()+ await first.ended+ } finally {+ await capped.stop()+ }+ })+})diff --git a/nodejs/src/ingestion/api/grpc-server.ts b/nodejs/src/ingestion/api/grpc-server.tsnew file mode 100644index 000000000000..f6ef5571d265--- /dev/null+++ b/nodejs/src/ingestion/api/grpc-server.ts@@ -0,0 +1,796 @@+import { create } from '@bufbuild/protobuf'+import { Code, ConnectError, ConnectRouter, HandlerContext } from '@connectrpc/connect'+import { connectNodeAdapter } from '@connectrpc/connect-node'+import * as http2 from 'node:http2'+import { Counter, Gauge } from 'prom-client'++import {+ IngestStreamRequest,+ IngestStreamResponse,+ IngestStreamResponseSchema,+ KafkaMessage,+ StreamHello,+ StreamReadySchema,+ SubBatchAckSchema,+ SubBatchStatus,+ WorkerIngest,+} from '~/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb'+import { logger } from '~/common/utils/logger'+import { FeedResult } from '~/ingestion/framework/batching-pipeline'++import { FeedOrderSentinel } from './feed-order-sentinel'+import { SerializedKafkaMessage } from './types'++const grpcStreams = new Gauge({+ name: 'ingestion_api_grpc_streams',+ help: 'Open WorkerIngest streams (one per connected consumer process)',+})++const grpcSubBatches = new Counter({+ name: 'ingestion_api_grpc_sub_batches_total',+ help: 'Sub-batches resolved on the gRPC ingest path',+ labelNames: ['status'],+})++const grpcMessagesProcessed = new Counter({+ name: 'ingestion_api_grpc_messages_processed_total',+ help: 'Messages acked on the gRPC ingest path',+})++const grpcProtocolErrors = new Counter({+ name: 'ingestion_api_grpc_protocol_errors_total',+ help: 'Streams closed for protocol violations (missing hello, seq gap or regression)',+ labelNames: ['kind'],+})++const grpcFeedSlotWaiters = new Gauge({+ name: 'ingestion_api_grpc_feed_slot_waiters',+ help: 'Streams waiting for a pipeline batch slot (FIFO admission queue depth)',+})++const grpcCapacityRetries = new Counter({+ name: 'ingestion_api_grpc_capacity_retries_total',+ help: 'Feeds rejected at_capacity despite holding an admission slot (capacity accounting drift)',+})++const grpcConnectionsRejected = new Counter({+ name: 'ingestion_api_grpc_connections_rejected_total',+ help: 'Sessions or streams refused because a concurrency cap was hit',+ labelNames: ['reason'],+})++/** A batch the pipeline finished processing. */+export interface CompletedSubBatch {+ streamId: number+ seq: number+ accepted: number+ /**+ * Resolves when the batch's side effects are durably done — the ack+ * barrier. Kept as a promise (not awaited inside `next()`) so the pump+ * can settle many completed batches concurrently: one batch's slow side+ * effects must not head-of-line block every other stream's acks.+ */+ settled: Promise<void>+}++/**+ * Pipeline mechanics behind the stream protocol. The server owns ordering,+ * acks, capacity admission, and stream lifecycle; the driver owns how a+ * sub-batch enters the shared pipeline and when its processing is durably+ * done (`settled`).+ */+export interface StreamIngestDriver {+ feed(streamId: number, seq: number, messages: SerializedKafkaMessage[]): Promise<FeedResult>+ next(): Promise<CompletedSubBatch | null>+}++export interface WorkerIngestServerOptions {+ port: number+ /**+ * Pipeline batch capacity, mirrored by the server's FIFO admission queue:+ * feeds are granted in arrival order across all streams, so a busy stream+ * cannot starve another (a retry race here wedged whole consumers).+ * Must match the gRPC pipeline's `concurrentBatches`.+ */+ maxConcurrentBatches: number+ /** Fallback delay if the pipeline still reports at_capacity despite an admission slot. */+ capacityRetryMs?: number+ /** Delay before re-pumping when the pipeline reports drained but sub-batches are still in flight. */+ pumpIdleMs?: number+ /**+ * Total concurrent streams the server will hold open across all sessions.+ * The topology is roughly one stream per connected consumer, so this is a+ * generous ceiling that only trips on misbehaviour — a stream past it is+ * refused with ResourceExhausted rather than accumulating unbounded.+ */+ maxStreams?: number+ /** Total concurrent HTTP/2 sessions; a session past this is destroyed on open. */+ maxSessions?: number+ /** Per-session stream limit, advertised via HTTP/2 SETTINGS and enforced by Node. */+ maxStreamsPerSession?: number+ /** Per-session memory budget in MB (HTTP/2 `maxSessionMemory`). */+ sessionMemoryMb?: number+ /**+ * Largest gRPC message the server will deserialize; bigger frames get+ * ResourceExhausted. The consumer targets 10 MiB sub-batches, but an+ * over-limit frame is replayed verbatim, so keep generous headroom.+ */+ readMaxBytes?: number+ /** Idle time before a session with no activity is closed, reaping dead peers. */+ sessionIdleTimeoutMs?: number+ /**+ * How long stop() waits for fed sub-batches to settle and their acks to+ * flush before failing what remains. Without the drain, every scale-down+ * makes consumers replay work the pipeline already processed.+ */+ drainTimeoutMs?: number+}++/** Thrown from `FifoSlots.acquire` when the waiting stream is cancelled. */+class SlotAcquisitionAborted extends Error {}++/**+ * FIFO slot queue: capacity grants go to waiters in arrival order. A freed+ * slot passes directly to the oldest waiter instead of returning to a pool a+ * newer arrival could win.+ *+ * A waiter can be cancelled via its `AbortSignal`: a stream that disconnects+ * while parked here is removed from the queue, so a freed slot skips it and+ * goes to a live stream instead of feeding work that can never be acked.+ */+class FifoSlots {+ private available: number+ private waiters: (() => void)[] = []++ constructor(capacity: number) {+ this.available = capacity+ }++ acquire(signal?: AbortSignal): Promise<void> {+ if (signal?.aborted) {+ return Promise.reject(new SlotAcquisitionAborted())+ }+ if (this.available > 0) {+ this.available--+ return Promise.resolve()+ }+ grpcFeedSlotWaiters.inc()+ return new Promise<void>((resolve, reject) => {+ const grant = (): void => {+ signal?.removeEventListener('abort', onAbort)+ grpcFeedSlotWaiters.dec()+ resolve()+ }+ const onAbort = (): void => {+ const index = this.waiters.indexOf(grant)+ if (index === -1) {+ // Already granted a slot; the caller's post-acquire check+ // hands it back. Nothing queued to remove here.+ return+ }+ this.waiters.splice(index, 1)+ grpcFeedSlotWaiters.dec()+ reject(new SlotAcquisitionAborted())+ }+ this.waiters.push(grant)+ signal?.addEventListener('abort', onAbort, { once: true })+ })+ }++ release(): void {+ const next = this.waiters.shift()+ if (next) {+ next()+ return+ }+ this.available+++ }+}++interface WorkerIngestServerDeps {+ driver: StreamIngestDriver+ /** Shared with the HTTP path so both transports check the same invariant. */+ feedOrderSentinel?: FeedOrderSentinel+ /**+ * A pipeline error poisons the shared pipeline for every stream, so the+ * server fails all streams and hands the error up — the owner mirrors the+ * HTTP path's crash-and-rebuild contract.+ */+ onFatal: (error: Error) => void+}++/** Unbounded FIFO handed from the pump to each stream's response generator. */+class AckQueue {+ private items: IngestStreamResponse[] = []+ private waiter: {+ resolve: (value: IteratorResult<IngestStreamResponse>) => void+ reject: (err: Error) => void+ } | null = null+ private done = false+ private error: Error | null = null++ push(item: IngestStreamResponse): void {+ if (this.done) {+ return+ }+ if (this.waiter) {+ const { resolve } = this.waiter+ this.waiter = null+ resolve({ value: item, done: false })+ return+ }+ this.items.push(item)+ }++ /** No more acks will arrive; the generator completes after draining. */+ end(): void {+ this.done = true+ if (this.waiter && this.items.length === 0) {+ const { resolve } = this.waiter+ this.waiter = null+ resolve({ value: undefined, done: true })+ }+ }++ /** Fail the consuming generator (stream error towards the consumer). */+ fail(error: Error): void {+ this.error = error+ this.done = true+ if (this.waiter) {+ const { reject } = this.waiter+ this.waiter = null+ reject(error)+ }+ }++ [Symbol.asyncIterator](): AsyncIterator<IngestStreamResponse> {+ return {+ next: (): Promise<IteratorResult<IngestStreamResponse>> => {+ if (this.items.length > 0) {+ return Promise.resolve({ value: this.items.shift()!, done: false })+ }+ if (this.error) {+ return Promise.reject(this.error)+ }+ if (this.done) {+ return Promise.resolve({ value: undefined, done: true })+ }+ return new Promise((resolve, reject) => {+ this.waiter = { resolve, reject }+ })+ },+ }+ }+}++interface StreamState {+ id: number+ hello: StreamHello | null+ nextSeq: number+ inFlight: Set<number>+ readerDone: boolean+ acks: AckQueue+}++export function grpcMessageToSerialized(message: KafkaMessage): SerializedKafkaMessage {+ return {+ topic: message.topic,+ partition: message.partition,+ offset: Number(message.offset),+ timestamp: Number(message.timestamp),+ key: message.key ?? null,+ value: message.value ?? null,+ headers: message.headers,+ }+}++function readyFrame(): IngestStreamResponse {+ return create(IngestStreamResponseSchema, {+ msg: { case: 'ready', value: create(StreamReadySchema, {}) },+ })+}++function okAck(seq: number, accepted: number): IngestStreamResponse {+ return create(IngestStreamResponseSchema, {+ msg: {+ case: 'ack',+ value: create(SubBatchAckSchema, { seq: BigInt(seq), status: SubBatchStatus.OK, accepted }),+ },+ })+}++function failedAck(seq: number, error: string): IngestStreamResponse {+ return create(IngestStreamResponseSchema, {+ msg: {+ case: 'ack',+ value: create(SubBatchAckSchema, { seq: BigInt(seq), status: SubBatchStatus.FAILED, error }),+ },+ })+}++/**+ * Serves `ingestion.worker.v1.WorkerIngest`: the ordered streaming transport+ * from the Rust ingestion consumer.+ *+ * Ordering: each stream has one reader loop that awaits the pipeline's+ * acceptance of a sub-batch before reading the next frame, so feed order+ * equals stream order — and HTTP/2 flow control backpressures the consumer+ * while the pipeline is at capacity, replacing the HTTP path's 503s.+ * Processing stays concurrent behind the feed; acks are pushed as batches+ * complete, out of order, correlated by `seq`.+ *+ * Failure: any pipeline failure poisons the shared pipeline, so every open+ * stream is failed and `onFatal` fires — the consumer treats a broken stream+ * as a dead lane and replays its un-acked tail.+ */+export class WorkerIngestServer {+ private server: http2.Http2Server | null = null+ private streams = new Map<number, StreamState>()+ private nextStreamId = 1+ private stopped = false+ private draining = false+ private readonly drainAbort = new AbortController()+ private readonly stopAbort = new AbortController()+ private sessions = new Set<http2.ServerHttp2Session>()+ private fatalError: Error | null = null+ private pumpTask: Promise<void> | null = null+ private wakePump: (() => void) | null = null+ private readonly capacityRetryMs: number+ private readonly pumpIdleMs: number+ private readonly maxStreams: number+ private readonly maxSessions: number+ private readonly maxStreamsPerSession: number+ private readonly sessionMemoryMb: number+ private readonly sessionIdleTimeoutMs: number+ private readonly readMaxBytes: number+ private readonly drainTimeoutMs: number+ private sessionCount = 0+ private readonly slots: FifoSlots++ constructor(+ private options: WorkerIngestServerOptions,+ private deps: WorkerIngestServerDeps+ ) {+ this.capacityRetryMs = options.capacityRetryMs ?? 20+ this.pumpIdleMs = options.pumpIdleMs ?? 20+ this.maxStreams = options.maxStreams ?? 256+ this.maxSessions = options.maxSessions ?? 256+ this.maxStreamsPerSession = options.maxStreamsPerSession ?? 8+ this.sessionMemoryMb = options.sessionMemoryMb ?? 64+ this.sessionIdleTimeoutMs = options.sessionIdleTimeoutMs ?? 300_000+ this.readMaxBytes = options.readMaxBytes ?? 32 * 1024 * 1024+ this.drainTimeoutMs = options.drainTimeoutMs ?? 15_000+ this.slots = new FifoSlots(options.maxConcurrentBatches)+ }++ async start(): Promise<void> {+ this.pumpTask = this.runPump()+ this.server = http2.createServer(+ {+ // Cap per-session streams (advertised via SETTINGS, enforced by+ // Node) and per-session buffered memory, so one peer cannot fan+ // out or buffer without bound. Total sessions and streams are+ // bounded separately below and in ingestStream.+ settings: { maxConcurrentStreams: this.maxStreamsPerSession },+ maxSessionMemory: this.sessionMemoryMb,+ },+ connectNodeAdapter({+ readMaxBytes: this.readMaxBytes,+ routes: (router: ConnectRouter) => {+ router.service(WorkerIngest, {+ ingestStream: (requests, context: HandlerContext) =>+ this.ingestStream(requests, context.signal),+ })+ },+ })+ )+ this.server.on('session', (session) => this.onSession(session))+ await new Promise<void>((resolve, reject) => {+ this.server!.once('error', reject)+ this.server!.listen(this.options.port, () => {+ this.server!.removeListener('error', reject)+ logger.info('🛜', `WorkerIngest gRPC server listening on port ${this.options.port}`)+ resolve()+ })+ })+ }++ /**+ * Bounds concurrent sessions and reaps idle ones. A session past the cap is+ * destroyed on open; an idle session is closed so a dead or slow peer cannot+ * hold resources indefinitely. The `error` listener keeps a session-level+ * error from crashing the process (an EventEmitter error with no listener+ * throws).+ */+ private onSession(session: http2.ServerHttp2Session): void {+ if (this.sessionCount >= this.maxSessions) {+ grpcConnectionsRejected.inc({ reason: 'max_sessions' })+ session.destroy()+ return+ }+ this.sessionCount+++ this.sessions.add(session)+ session.setTimeout(this.sessionIdleTimeoutMs, () => session.close())+ session.on('error', (error) => logger.warn('🛜', 'WorkerIngest session error', { error }))+ session.once('close', () => {+ this.sessionCount--+ this.sessions.delete(session)+ })+ }++ /**+ * Drains before tearing down: fed sub-batches settle and their acks flush,+ * so a scale-down does not make consumers replay already-processed work.+ */+ async stop(): Promise<void> {+ this.draining = true+ this.drainAbort.abort()+ // A poisoned pipeline never settles, so skip straight to teardown.+ const deadline = this.fatalError ? 0 : Date.now() + this.drainTimeoutMs+ while (this.totalInFlight() > 0 && Date.now() < deadline) {+ await sleep(10)+ }+ this.stopped = true+ this.stopAbort.abort()+ for (const stream of this.streams.values()) {+ if (stream.inFlight.size === 0) {+ stream.acks.end()+ } else {+ stream.acks.fail(new ConnectError('server shutting down', Code.Unavailable))+ }+ }+ this.wake()+ // http2's close() waits for every session to end and consumers hold+ // theirs open, so send a graceful GOAWAY instead of waiting.+ for (const session of this.sessions) {+ session.close()+ }+ if (this.server) {+ await new Promise<void>((resolve) => this.server!.close(() => resolve()))+ this.server = null+ }+ // A poisoned pipeline can leave the pump blocked in a next() that will+ // never resolve — bound the wait instead of hanging shutdown on it.+ await Promise.race([this.pumpTask, sleep(5_000)])+ }++ /** Open stream count, exposed for tests. */+ get streamCount(): number {+ return this.streams.size+ }++ private wake(): void {+ if (this.wakePump) {+ const wake = this.wakePump+ this.wakePump = null+ wake()+ }+ }++ private totalInFlight(): number {+ let total = 0+ for (const stream of this.streams.values()) {+ total += stream.inFlight.size+ }+ return total+ }++ /**+ * The single pump: drains completed batches from the driver and routes+ * acks to their stream. One loop per server — completed batches carry+ * their stream id, so streams never contend over the pipeline's results.+ */+ private async runPump(): Promise<void> {+ while (!this.stopped) {+ if (this.totalInFlight() === 0) {+ await new Promise<void>((resolve) => {+ this.wakePump = resolve+ })+ continue+ }+ try {+ const completed = await this.raceStopped(this.deps.driver.next())+ if (completed === undefined) {+ return+ }+ if (completed === null) {+ // The pipeline drained between feeds while acked work is+ // still being registered — yield briefly and re-pump.+ await sleep(this.pumpIdleMs)+ continue+ }+ // Settle concurrently: the pump goes straight back to the+ // pipeline while this batch's side effects finish, so one slow+ // batch cannot head-of-line block other streams' acks.+ this.settleAndAck(completed)+ } catch (error) {+ this.fatal(error instanceof Error ? error : new Error(String(error)))+ return+ }+ }+ }++ /**+ * Like Promise.race(work, stop) resolving `undefined` on stop, but without+ * race's per-call listener leak: the stop listener is removed once work+ * settles.+ */+ private raceStopped<T>(work: Promise<T>): Promise<T | undefined> {+ if (this.stopAbort.signal.aborted) {+ return Promise.resolve(undefined)+ }+ return new Promise((resolve, reject) => {+ const onStop = (): void => resolve(undefined)+ this.stopAbort.signal.addEventListener('abort', onStop, { once: true })+ work.then(+ (value) => {+ this.stopAbort.signal.removeEventListener('abort', onStop)+ resolve(value)+ },+ (error) => {+ this.stopAbort.signal.removeEventListener('abort', onStop)+ reject(error)+ }+ )+ })+ }++ private settleAndAck(completed: CompletedSubBatch): void {+ void (async () => {+ try {+ await completed.settled+ } catch (error) {+ this.slots.release()+ this.fatal(error instanceof Error ? error : new Error(String(error)))+ return+ }+ // The batch's admission slot frees only once its side effects are+ // durably done, matching the HTTP path's response barrier.+ this.slots.release()+ this.ackCompleted(completed)+ })()+ }++ private ackCompleted(completed: CompletedSubBatch): void {+ const stream = this.streams.get(completed.streamId)+ if (!stream) {+ // The stream died while its sub-batch was processing; the consumer+ // replays the un-acked tail on its next stream.+ return+ }+ stream.inFlight.delete(completed.seq)+ stream.acks.push(okAck(completed.seq, completed.accepted))+ grpcSubBatches.inc({ status: 'ok' })+ grpcMessagesProcessed.inc(completed.accepted)+ this.maybeFinish(stream)+ }++ private maybeFinish(stream: StreamState): void {+ if (stream.readerDone && stream.inFlight.size === 0) {+ stream.acks.end()+ }+ }++ /** Stop reading without failing the stream; pending acks still flush. */+ private finishReader(stream: StreamState, unfedSeq?: number): void {+ if (unfedSeq !== undefined) {+ stream.inFlight.delete(unfedSeq)+ }+ stream.readerDone = true+ this.maybeFinish(stream)+ }++ /**+ * A pipeline failure poisons the shared pipeline (same contract as the+ * HTTP handler's fatal path): fail every stream so consumers tear down+ * their lanes and replay, then hand the error to the owner to shut down.+ */+ private fatal(error: Error): void {+ if (this.fatalError) {+ return+ }+ this.fatalError = error+ logger.error('💥', 'WorkerIngest pipeline failed — failing all streams', { error: error.message })+ for (const stream of this.streams.values()) {+ stream.acks.fail(new ConnectError(`ingest pipeline failed: ${error.message}`, Code.Internal))+ }+ this.deps.onFatal(error)+ }++ async *ingestStream(+ requests: AsyncIterable<IngestStreamRequest>,+ signal?: AbortSignal+ ): AsyncIterable<IngestStreamResponse> {+ if (this.fatalError) {+ throw new ConnectError('ingest pipeline is poisoned', Code.Unavailable)+ }+ if (this.draining) {+ throw new ConnectError('server shutting down', Code.Unavailable)+ }+ // Total stream ceiling across every session: the per-session SETTINGS cap+ // bounds one peer, this bounds the whole server if a peer ignores it.+ if (this.streams.size >= this.maxStreams) {+ grpcConnectionsRejected.inc({ reason: 'max_streams' })+ throw new ConnectError('too many concurrent streams', Code.ResourceExhausted)+ }+ const stream: StreamState = {+ id: this.nextStreamId++,+ hello: null,+ nextSeq: 1,+ inFlight: new Set(),+ readerDone: false,+ acks: new AckQueue(),+ }+ this.streams.set(stream.id, stream)+ grpcStreams.inc()++ // connect-node defers response headers until the first response+ // message and the consumer's stream-open awaits them, so greet first.+ stream.acks.push(readyFrame())++ const reader = this.runReader(stream, requests, signal)+ // Reader failures surface through the ack queue.+ swallowRejection(reader)++ try {+ for await (const ack of stream.acks) {+ yield ack+ }+ // Normal completion: propagate a reader outcome the queue may not+ // have carried (it can only fail after a waiter is registered).+ await reader+ } finally {+ this.streams.delete(stream.id)+ grpcStreams.dec()+ this.wake()+ }+ }++ private async runReader(+ stream: StreamState,+ requests: AsyncIterable<IngestStreamRequest>,+ signal?: AbortSignal+ ): Promise<void> {+ // Admission waits abort on disconnect and on drain: either way the+ // sub-batch was never fed, so the consumer replays it for free.+ const admissionSignal = signal ? AbortSignal.any([signal, this.drainAbort.signal]) : this.drainAbort.signal+ try {+ for await (const request of requests) {+ if (this.draining) {+ this.finishReader(stream)+ return+ }+ if (request.msg.case === 'hello') {+ if (stream.hello) {+ throw this.protocolError(stream, 'duplicate_hello', 'received a second hello frame')+ }+ stream.hello = request.msg.value+ continue+ }+ if (request.msg.case !== 'subBatch') {+ throw this.protocolError(stream, 'unknown_frame', 'frame is neither hello nor sub_batch')+ }+ if (!stream.hello) {+ throw this.protocolError(stream, 'missing_hello', 'received a sub-batch before the hello frame')+ }++ const subBatch = request.msg.value+ const seq = Number(subBatch.seq)+ if (seq !== stream.nextSeq) {+ throw this.protocolError(+ stream,+ 'seq_mismatch',+ `expected seq ${stream.nextSeq}, got ${seq} — frames were lost or reordered`+ )+ }+ stream.nextSeq++++ if (subBatch.messages.length === 0) {+ // An empty feed never completes a batch, so ack it directly.+ stream.acks.push(okAck(seq, 0))+ continue+ }++ const serialized = subBatch.messages.map(grpcMessageToSerialized)+ // The sentinel's sender scope includes both epochs, so+ // reconnects and rebalances rebaseline instead of counting+ // legitimate replays as violations.+ this.deps.feedOrderSentinel?.check(+ serialized,+ `${stream.hello.consumerId}#${stream.hello.streamEpoch}#${subBatch.assignmentEpoch}`,+ subBatch.replay+ )++ // Await admission before reading the next frame: stream order+ // becomes feed order, and the stalled read backpressures the+ // consumer via HTTP/2 flow control. Slots are granted in FIFO+ // order because a retry race here let busy streams starve+ // quiet ones, wedging whole consumers.+ stream.inFlight.add(seq)+ try {+ await this.slots.acquire(admissionSignal)+ } catch (error) {+ if (error instanceof SlotAcquisitionAborted) {+ this.finishReader(stream, seq)+ return+ }+ throw error+ }+ if (signal?.aborted) {+ // Cancelled between the slot grant and here: hand the slot+ // straight back so a live stream gets it, and stop reading.+ this.slots.release()+ return+ }+ let feedAccepted = false+ try {+ while (true) {+ if (this.draining) {+ this.finishReader(stream, seq)+ return+ }+ const result = await this.feedGuarded(stream, seq, serialized)+ if (result.ok) {+ feedAccepted = true+ break+ }+ if (result.kind === 'at_capacity') {+ // The admission queue mirrors pipeline capacity, so+ // this means the two drifted — count it and retry.+ grpcCapacityRetries.inc()+ await sleep(this.capacityRetryMs)+ continue+ }+ stream.inFlight.delete(seq)+ stream.acks.push(failedAck(seq, result.reason))+ grpcSubBatches.inc({ status: 'failed' })+ throw new ConnectError(`sub-batch ${seq} rejected: ${result.reason}`, Code.Internal)+ }+ } finally {+ // An accepted feed hands its slot to the pump, which+ // releases it after the batch settles; every other exit+ // must give the slot back here.+ if (!feedAccepted) {+ this.slots.release()+ }+ }+ this.wake()+ }+ this.finishReader(stream)+ } catch (error) {+ stream.readerDone = true+ const connectError = error instanceof ConnectError ? error : new ConnectError(String(error), Code.Internal)+ stream.acks.fail(connectError)+ throw connectError+ }+ }++ /** Feed through the driver, converting a thrown pipeline error into the fatal path. */+ private async feedGuarded(+ stream: StreamState,+ seq: number,+ messages: SerializedKafkaMessage[]+ ): Promise<FeedResult> {+ try {+ return await this.deps.driver.feed(stream.id, seq, messages)+ } catch (error) {+ this.fatal(error instanceof Error ? error : new Error(String(error)))+ throw new ConnectError('ingest pipeline failed', Code.Internal)+ }+ }++ private protocolError(stream: StreamState, kind: string, message: string): ConnectError {+ grpcProtocolErrors.inc({ kind })+ logger.warn('⚠️', 'WorkerIngest protocol violation', { streamId: stream.id, kind, message })+ return new ConnectError(message, Code.FailedPrecondition)+ }+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms))+}++/** For promises whose failure is reported elsewhere; an unobserved rejection would crash the process. */+function swallowRejection(promise: Promise<unknown>): void {+ promise.catch(() => {})+}diff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.test.tsindex 1f047ecb5449..b78ef801be0d 100644--- a/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts@@ -92,13 +92,13 @@ describe('CommonIngestionPipelineBuilder', () => {// so no batch result may ever surface any to the driver.const runPipeline = async (pipeline: {- feed: (batch: any[]) => Promise<{ ok: boolean }>+ feed: (batch: any[], batchContext: Record<never, never>) => Promise<{ ok: boolean }>next: () => Promise<{ elements: any[]; sideEffects?: Promise<unknown>[] } | null>},messages: Message[]): Promise<{ elements: any[]; sideEffects?: Promise<unknown>[] }[]> => {const batch = messages.map((message) => createOkContext({ message }, { message }))- const feedResult = await pipeline.feed(batch)+ const feedResult = await pipeline.feed(batch, {})expect(feedResult.ok).toBe(true)const batches = []diff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.tsindex bbfcab145824..c6ac86f286dd 100644--- a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.ts@@ -519,8 +519,16 @@ export class CommonTeamStage<return new CommonBuildStage(this.config, this.beforeBatchCallback, this.completeTransform(), callback)}- build(): BatchingPipeline<TInput, TCurrent, TContext, CBatch, BatchContext<TContext>, ROut> {- return new CommonBuildStage(this.config, this.beforeBatchCallback, this.completeTransform()).build()+ build<CFeed extends object = Record<never, never>>(): BatchingPipeline<+ TInput,+ TCurrent,+ TContext,+ CBatch,+ BatchContext<TContext>,+ ROut,+ CFeed+ > {+ return new CommonBuildStage(this.config, this.beforeBatchCallback, this.completeTransform()).build<CFeed>()}private completeTransform(): SubpipelineTransform<TInput, TContext, CBatch, TCurrent, ROut> {@@ -612,7 +620,15 @@ export class CommonBuildStage<private readonly afterBatchCallback?: AfterBatchCallback<TFinal, TContext, CBatch, ROut>) {}- build(): BatchingPipeline<TInput, TFinal, TContext, CBatch, BatchContext<TContext>, ROut> {+ build<CFeed extends object = Record<never, never>>(): BatchingPipeline<+ TInput,+ TFinal,+ TContext,+ CBatch,+ BatchContext<TContext>,+ ROut,+ CFeed+ > {const { outputs, promiseScheduler, concurrentBatches, awaitSideEffects } = this.configconst pipelineConfig: PipelineConfig<ROut> = { outputs, promiseScheduler }const sideEffectOptions = { await: awaitSideEffects ?? false }@@ -625,7 +641,7 @@ export class CommonBuildStage<// The hooks handle their own side effects, so nothing rides out on// `BatchResult.sideEffects` and drivers only ever drain results.- return newBatchingPipeline<TInput, TFinal, TContext, CBatch, TContext, ROut, KafkaDebugContext>(+ return newBatchingPipeline<TInput, TFinal, TContext, CBatch, TContext, ROut, KafkaDebugContext, CFeed>((builder) => this.beforeBatchCallback(builder).handleSideEffects(promiseScheduler, sideEffectOptions),(batch) =>batchdiff --git a/nodejs/src/ingestion/common/ingestion-consumer.ts b/nodejs/src/ingestion/common/ingestion-consumer.tsindex 126eb2cb68f5..68f5dad73118 100644--- a/nodejs/src/ingestion/common/ingestion-consumer.ts+++ b/nodejs/src/ingestion/common/ingestion-consumer.ts@@ -20,7 +20,10 @@ type MessageInput = { message: Message }type MessageContext = { message: Message }export interface IngestionBatchingPipeline {- feed(elements: OkResultWithContext<MessageInput, MessageContext>[]): Promise<FeedResult>+ feed(+ elements: OkResultWithContext<MessageInput, MessageContext>[],+ batchContext: Record<never, never>+ ): Promise<FeedResult>next(): Promise<BatchResult<unknown> | null>}@@ -167,7 +170,7 @@ class KafkaBatchHandler {createOkContext({ message }, { message, debugContext: createKafkaDebugContext(message) }))- const feedResult = await this.pipeline.feed(batch)+ const feedResult = await this.pipeline.feed(batch, {})if (!feedResult.ok) {throw new Error(`Pipeline rejected batch: ${feedResult.reason}`)}diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex 5849da157066..0d198bef8538 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -130,6 +130,23 @@ export type IngestionConsumerConfig = {// least-recently-seen key is dropped and rebaselines unchecked.INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS: number+ // Streaming ingest (ingestion API server only): serve+ // ingestion.worker.v1.WorkerIngest over gRPC alongside HTTP /ingest.+ // The stream delivers each consumer's sub-batches in order, closing the+ // wire-reordering window concurrent HTTP requests leave open.+ INGESTION_API_GRPC_ENABLED: boolean+ INGESTION_API_GRPC_PORT: number+ // Concurrency caps for the gRPC listener. Legitimate load is roughly one+ // stream per connected consumer, so these are generous ceilings that bound+ // resource use if a peer misbehaves rather than limits normal traffic.+ INGESTION_API_GRPC_MAX_STREAMS: number+ INGESTION_API_GRPC_MAX_SESSIONS: number+ INGESTION_API_GRPC_MAX_STREAMS_PER_SESSION: number+ INGESTION_API_GRPC_SESSION_MEMORY_MB: number+ INGESTION_API_GRPC_SESSION_IDLE_TIMEOUT_MS: number+ INGESTION_API_GRPC_READ_MAX_BYTES: number+ INGESTION_API_GRPC_DRAIN_TIMEOUT_MS: number+// Person batch writing configPERSON_BATCH_WRITING_DB_WRITE_MODE: PersonBatchWritingDbWriteModePERSON_BATCH_WRITING_USE_BATCH_UPDATES: boolean@@ -299,6 +316,15 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {INGESTION_WORKER_CONCURRENT_BATCHES: 1,INGESTION_API_FEED_ORDER_SENTINEL_ENABLED: true,INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS: 200_000,+ INGESTION_API_GRPC_ENABLED: false,+ INGESTION_API_GRPC_PORT: 6739,+ INGESTION_API_GRPC_MAX_STREAMS: 256,+ INGESTION_API_GRPC_MAX_SESSIONS: 256,+ INGESTION_API_GRPC_MAX_STREAMS_PER_SESSION: 8,+ INGESTION_API_GRPC_SESSION_MEMORY_MB: 64,+ INGESTION_API_GRPC_SESSION_IDLE_TIMEOUT_MS: 300_000,+ INGESTION_API_GRPC_READ_MAX_BYTES: 32 * 1024 * 1024,+ INGESTION_API_GRPC_DRAIN_TIMEOUT_MS: 15_000,// Person batch writing configPERSON_BATCH_WRITING_DB_WRITE_MODE: 'NO_ASSERT',diff --git a/nodejs/src/ingestion/framework/batching-pipeline.test.ts b/nodejs/src/ingestion/framework/batching-pipeline.test.tsindex d8d2641f381b..acd6aae9f8a1 100644--- a/nodejs/src/ingestion/framework/batching-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/batching-pipeline.test.ts@@ -84,8 +84,8 @@ describe('BatchingPipeline', () => {it('assigns sequential batch IDs to beforeBatch', async () => {const collector = createCollector()- await collector.feed(makeBatch([1, 2]))- await collector.feed(makeBatch([3]))+ await collector.feed(makeBatch([1, 2]), {})+ await collector.feed(makeBatch([3]), {})expect(beforeBatchStep).toHaveBeenCalledTimes(2)expect(beforeBatchStep.mock.calls[0][0].batchContext.batchId).toBe(0)@@ -97,7 +97,7 @@ describe('BatchingPipeline', () => {it('tags each element with a monotonic messageId in context', async () => {const collector = createCollector()- await collector.feed(makeBatch([10, 20, 30]))+ await collector.feed(makeBatch([10, 20, 30]), {})const { allResults } = await drainAll(collector)expect(allResults).toHaveLength(3)@@ -109,8 +109,8 @@ describe('BatchingPipeline', () => {it('continues messageId sequence across batches', async () => {const collector = createCollector()- await collector.feed(makeBatch([1, 2]))- await collector.feed(makeBatch([3]))+ await collector.feed(makeBatch([1, 2]), {})+ await collector.feed(makeBatch([3]), {})const { allResults } = await drainAll(collector)expect(allResults).toHaveLength(3)@@ -122,7 +122,7 @@ describe('BatchingPipeline', () => {it('returns ordered batch results when a batch completes', async () => {const collector = createCollector()- await collector.feed(makeBatch([1, 2, 3]))+ await collector.feed(makeBatch([1, 2, 3]), {})const { allResults } = await drainAll(collector)expect(afterBatchStep).toHaveBeenCalledTimes(1)@@ -136,8 +136,8 @@ describe('BatchingPipeline', () => {it('tracks two batches independently', async () => {const collector = createCollector()- await collector.feed(makeBatch([1, 2]))- await collector.feed(makeBatch([3]))+ await collector.feed(makeBatch([1, 2]), {})+ await collector.feed(makeBatch([3]), {})const { allResults } = await drainAll(collector)expect(afterBatchStep).toHaveBeenCalledTimes(2)@@ -147,7 +147,7 @@ describe('BatchingPipeline', () => {it('handles single-message batches', async () => {const collector = createCollector()- await collector.feed(makeBatch([42]))+ await collector.feed(makeBatch([42]), {})const { allResults } = await drainAll(collector)expect(beforeBatchStep).toHaveBeenCalledTimes(1)@@ -158,12 +158,12 @@ describe('BatchingPipeline', () => {it('supports feed-drain-feed-drain cycle', async () => {const collector = createCollector()- await collector.feed(makeBatch([1]))+ await collector.feed(makeBatch([1]), {})const { allResults: results1 } = await drainAll(collector)expect(afterBatchStep).toHaveBeenCalledTimes(1)expect(results1).toHaveLength(1)- await collector.feed(makeBatch([2]))+ await collector.feed(makeBatch([2]), {})const { allResults: results2 } = await drainAll(collector)expect(afterBatchStep).toHaveBeenCalledTimes(2)expect(afterBatchStep.mock.calls[1][0].batchId).toBe(1)@@ -181,7 +181,7 @@ describe('BatchingPipeline', () => {})const collector = createCollector()- await collector.feed(makeBatch([1]))+ await collector.feed(makeBatch([1]), {})order.push('next-called')await collector.next()@@ -194,7 +194,7 @@ describe('BatchingPipeline', () => {it('blocks until a batch completes', async () => {const collector = createStreamingCollector()- await collector.feed(makeBatch([1, 2, 3]))+ await collector.feed(makeBatch([1, 2, 3]), {})const result = await collector.next()expect(result).not.toBeNull()@@ -205,8 +205,8 @@ describe('BatchingPipeline', () => {it('fires afterBatch for first batch even when second is still in flight', async () => {const collector = createStreamingCollector()- await collector.feed(makeBatch([1]))- await collector.feed(makeBatch([2, 3]))+ await collector.feed(makeBatch([1]), {})+ await collector.feed(makeBatch([2, 3]), {})const result0 = await collector.next()expect(afterBatchStep).toHaveBeenCalledTimes(1)@@ -224,8 +224,8 @@ describe('BatchingPipeline', () => {it('returns results from multiple batches completing on the same next() call', async () => {const collector = createStreamingCollector()- await collector.feed(makeBatch([1]))- await collector.feed(makeBatch([2]))+ await collector.feed(makeBatch([1]), {})+ await collector.feed(makeBatch([2]), {})const result0 = await collector.next()expect(result0!.elements).toHaveLength(1)@@ -260,7 +260,7 @@ describe('BatchingPipeline', () => {{ concurrentBatches: Infinity })- await collector.feed(makeBatch([1, 2]))+ await collector.feed(makeBatch([1, 2]), {})const { allResults } = await drainAll(collector)expect(allResults).toHaveLength(2)@@ -295,8 +295,8 @@ describe('BatchingPipeline', () => {{ concurrentBatches: Infinity })- await collector.feed(makeBatch([1]))- await collector.feed(makeBatch([2]))+ await collector.feed(makeBatch([1]), {})+ await collector.feed(makeBatch([2]), {})await drainAll(collector)expect(capturedBefore).toEqual([@@ -317,7 +317,7 @@ describe('BatchingPipeline', () => {)const collector = createCollector()- await collector.feed(makeBatch([1]))+ await collector.feed(makeBatch([1]), {})const result = await collector.next()expect(result).not.toBeNull()@@ -331,7 +331,7 @@ describe('BatchingPipeline', () => {)const collector = createCollector()- await collector.feed(makeBatch([1]))+ await collector.feed(makeBatch([1]), {})const result = await collector.next()expect(result).not.toBeNull()@@ -350,7 +350,7 @@ describe('BatchingPipeline', () => {)const collector = createCollector()- await collector.feed(makeBatch([1]))+ await collector.feed(makeBatch([1]), {})const result = await collector.next()expect(result).not.toBeNull()@@ -366,12 +366,12 @@ describe('BatchingPipeline', () => {it('empty feed is a no-op that skips hooks and does not leak a capacity slot', async () => {const collector = createCollector({ concurrentBatches: 1 })- expect(await collector.feed([])).toEqual({ ok: true })+ expect(await collector.feed([], {})).toEqual({ ok: true })expect(beforeBatchStep).not.toHaveBeenCalled()expect(await collector.next()).toBeNull()// The slot was not leaked: a subsequent normal batch is accepted and processed.- expect(await collector.feed(makeBatch([9]))).toEqual({ ok: true })+ expect(await collector.feed(makeBatch([9]), {})).toEqual({ ok: true })const { allResults } = await drainAll(collector)expect(allResults).toHaveLength(1)expect(afterBatchStep).toHaveBeenCalledTimes(1)@@ -386,13 +386,13 @@ describe('BatchingPipeline', () => {)const collector = createCollector({ concurrentBatches: 1 })- await expect(collector.feed(makeBatch([1, 2]))).rejects.toThrow('changed element count (2 -> 1)')+ await expect(collector.feed(makeBatch([1, 2]), {})).rejects.toThrow('changed element count (2 -> 1)')expect(await collector.next()).toBeNull()// Nothing was registered before the throw: a subsequent normal batch// is accepted and processed (real drivers crash on the throw; this// documents that the throw itself does not corrupt state).- expect(await collector.feed(makeBatch([9]))).toEqual({ ok: true })+ expect(await collector.feed(makeBatch([9]), {})).toEqual({ ok: true })const { allResults } = await drainAll(collector)expect(allResults).toHaveLength(1)expect(afterBatchStep).toHaveBeenCalledTimes(1)@@ -403,31 +403,31 @@ describe('BatchingPipeline', () => {it('feed() rejects with reason when at limit (default concurrentBatches: 1)', async () => {const collector = createCollector({ concurrentBatches: 1 })- expect(await collector.feed(makeBatch([1]))).toEqual({ ok: true })- expect(await collector.feed(makeBatch([2]))).toMatchObject({ ok: false, reason: expect.any(String) })+ expect(await collector.feed(makeBatch([1]), {})).toEqual({ ok: true })+ expect(await collector.feed(makeBatch([2]), {})).toMatchObject({ ok: false, reason: expect.any(String) })})it('draining a batch frees a slot', async () => {const collector = createCollector({ concurrentBatches: 1 })- expect((await collector.feed(makeBatch([1]))).ok).toBe(true)- expect((await collector.feed(makeBatch([2]))).ok).toBe(false)+ expect((await collector.feed(makeBatch([1]), {})).ok).toBe(true)+ expect((await collector.feed(makeBatch([2]), {})).ok).toBe(false)await drainAll(collector)- expect((await collector.feed(makeBatch([3]))).ok).toBe(true)+ expect((await collector.feed(makeBatch([3]), {})).ok).toBe(true)})it('feed() accepts when under limit and rejects when at limit', async () => {const collector = createCollector({ concurrentBatches: 2 })- expect((await collector.feed(makeBatch([1]))).ok).toBe(true)- expect((await collector.feed(makeBatch([2]))).ok).toBe(true)- expect((await collector.feed(makeBatch([3]))).ok).toBe(false)+ expect((await collector.feed(makeBatch([1]), {})).ok).toBe(true)+ expect((await collector.feed(makeBatch([2]), {})).ok).toBe(true)+ expect((await collector.feed(makeBatch([3]), {})).ok).toBe(false)await drainAll(collector)- expect((await collector.feed(makeBatch([4]))).ok).toBe(true)+ expect((await collector.feed(makeBatch([4]), {})).ok).toBe(true)})})})diff --git a/nodejs/src/ingestion/framework/batching-pipeline.ts b/nodejs/src/ingestion/framework/batching-pipeline.tsindex a1ff7164d573..e3aedf86affc 100644--- a/nodejs/src/ingestion/framework/batching-pipeline.ts+++ b/nodejs/src/ingestion/framework/batching-pipeline.ts@@ -54,8 +54,10 @@ export type AfterBatchStep<TOutput, COutput, CBatch, R extends string = never> =input: AfterBatchInput<TOutput, COutput, CBatch, R>) => Promise<PipelineResult<AfterBatchOutput<TOutput, COutput, CBatch, R>>>-export interface BatchResult<T> {+export interface BatchResult<T, CBatch = unknown> {elements: T+ /** The batch's context: the caller's feed() contribution merged over the beforeBatch hooks' output. */+ batchContext: CBatchsideEffects?: Promise<unknown>[]}@@ -67,8 +69,8 @@ const BATCHING_PIPELINE_DEFAULTS: BatchingPipelineOptions = {concurrentBatches: 1,}-interface TrackedBatch<TOutput, CBatch, COutput, R extends string = never> {- batchContext: CBatch & { batchId: number }+interface TrackedBatch<TOutput, CBatch, COutput, R extends string = never, CFeed extends object = object> {+ batchContext: CBatch & CFeed & { batchId: number }messageIds: number[]inflight: Set<number>results: Map<number, PipelineResultWithContext<TOutput, COutput, R>>@@ -106,6 +108,9 @@ interface TrackedBatch<TOutput, CBatch, COutput, R extends string = never> {* - CBatch: opaque batch context passed to hooks* - COutput: context type returned by the sub-pipeline.* Must extend BatchingContext (messageId flows through the sub-pipeline).+ * - CFeed: batch context supplied by the caller of feed(), returned verbatim+ * on the completed batch's `BatchResult.batchContext` — the channel for+ * correlating a completed batch back to its feed() call.*/export class BatchingPipeline<TInput,@@ -114,6 +119,7 @@ export class BatchingPipeline<CBatchOutput,COutput extends BatchingContext,R extends string = never,+ CFeed extends object = Record<never, never>,> {private nextBatchId = 0private nextMessageId = 0@@ -121,9 +127,12 @@ export class BatchingPipeline<// pushes its elements into the sub-pipeline; lets the pump tell a feed that// raced its pull apart from genuinely vanished messages.private feedEpoch = 0- private batches = new Map<number, TrackedBatch<TOutput, CBatchOutput, COutput, R>>()+ private batches = new Map<number, TrackedBatch<TOutput, CBatchOutput, COutput, R, CFeed>>()private messageIdToBatchId = new Map<number, number>()- private completedResults: BatchResult<ChunkPipelineResultWithContext<TOutput, COutput, R>>[] = []+ private completedResults: BatchResult<+ ChunkPipelineResultWithContext<TOutput, COutput, R>,+ CBatchOutput & CFeed & { batchId: number }+ >[] = []// With concurrentBatches > 1, callers (e.g. HTTP request handlers in the// ingestion API server) invoke feed()/next() concurrently, but the@@ -162,16 +171,19 @@ export class BatchingPipeline<this.options = { ...BATCHING_PIPELINE_DEFAULTS, ...options }}- feed(elements: OkResultWithContext<TInput, CInput>[]): Promise<FeedResult> {+ feed(elements: OkResultWithContext<TInput, CInput>[], batchContext: CFeed): Promise<FeedResult> {// Serialize so buffer order always matches batchId order: without this,// the await on beforePipeline between batchId assignment and// subPipeline.feed() lets two concurrent feeds enter the buffer inverted.// With one concurrent batch the caller is already sequential, so the// mutex is uncontended.- return this.feedLimit(() => this.feedSerialized(elements))+ return this.feedLimit(() => this.feedSerialized(elements, batchContext))}- private async feedSerialized(elements: OkResultWithContext<TInput, CInput>[]): Promise<FeedResult> {+ private async feedSerialized(+ elements: OkResultWithContext<TInput, CInput>[],+ feedContext: CFeed+ ): Promise<FeedResult> {// An empty feed has no messages that could ever complete a batch:// completion is only detected in pump()'s result loop, so registering a// zero-message batch would occupy a concurrentBatches slot forever and@@ -246,8 +258,11 @@ export class BatchingPipeline<// Registration and the buffer push happen in one synchronous block, and// feedEpoch records that it happened — the pump uses it to distinguish// "a feed landed during my pull" from genuinely lost messages.+ // The caller's feed context is merged here rather than routed through the+ // beforeBatch hooks, so a hook that rebuilds the batch context cannot+ // drop it.this.batches.set(batchId, {- batchContext,+ batchContext: { ...batchContext, ...feedContext },messageIds,inflight,results: new Map(),@@ -259,7 +274,10 @@ export class BatchingPipeline<return { ok: true }}- next(): Promise<BatchResult<ChunkPipelineResultWithContext<TOutput, COutput, R>> | null> {+ next(): Promise<BatchResult<+ ChunkPipelineResultWithContext<TOutput, COutput, R>,+ CBatchOutput & CFeed & { batchId: number }+ > | null> {// Serialize so exactly one caller pumps the sub-pipeline at a time,// restoring the single-caller assumption the stages were written under.// With one concurrent batch the caller is already sequential, so the@@ -268,7 +286,10 @@ export class BatchingPipeline<return this.pumpLimit(() => this.pump())}- private async pump(): Promise<BatchResult<ChunkPipelineResultWithContext<TOutput, COutput, R>> | null> {+ private async pump(): Promise<BatchResult<+ ChunkPipelineResultWithContext<TOutput, COutput, R>,+ CBatchOutput & CFeed & { batchId: number }+ > | null> {// Re-check after acquiring the pump: a previous pump iteration may have// completed additional batches while this caller was waiting.if (this.completedResults.length > 0) {@@ -335,7 +356,11 @@ export class BatchingPipeline<const afterSideEffects = afterResult.context.sideEffectsconst sideEffects = [...batch.beforeSideEffects, ...afterSideEffects]- this.completedResults.push({ elements: afterResult.result.value.elements, sideEffects })+ this.completedResults.push({+ elements: afterResult.result.value.elements,+ batchContext: batch.batchContext,+ sideEffects,+ })}}diff --git a/nodejs/src/ingestion/framework/builders/helpers.ts b/nodejs/src/ingestion/framework/builders/helpers.tsindex 7950ec7b134c..1eae5336feac 100644--- a/nodejs/src/ingestion/framework/builders/helpers.ts+++ b/nodejs/src/ingestion/framework/builders/helpers.ts@@ -31,6 +31,7 @@ export function newBatchingPipeline<COutput = CInput,R extends string = never,D = DebugContextOf<CInput>,+ CFeed extends object = Record<never, never>,>(beforeBatch: (builder: StartPipelineBuilder<BeforeBatchInput<TInput, CInput>, Record<string, never>>@@ -61,7 +62,7 @@ export function newBatchingPipeline<>,options?: Partial<BatchingPipelineOptions>,builderContext?: PipelineBuilderContext<D>-): BatchingPipeline<TInput, TOutput, CInput, CBatch, COutput & BatchingContext, R> {+): BatchingPipeline<TInput, TOutput, CInput, CBatch, COutput & BatchingContext, R, CFeed> {const startBuilder = new ChunkPipelineBuilder<TInput & CBatch,TInput & CBatch,diff --git a/nodejs/src/ingestion/framework/docs/14-batching.test.ts b/nodejs/src/ingestion/framework/docs/14-batching.test.tsindex 621ae2065c1d..326df67804cc 100644--- a/nodejs/src/ingestion/framework/docs/14-batching.test.ts+++ b/nodejs/src/ingestion/framework/docs/14-batching.test.ts@@ -38,11 +38,15 @@* feed(batch B) ─► beforeBatch(B) ─► [ sub-pipeline ] ─► afterBatch(B) ─► next()* ```*- * Unlike a plain `ChunkPipeline`, `feed()` is async and returns a `FeedResult`:- * `{ ok: true }` when accepted, or `{ ok: false, kind, reason }` when rejected.- * `next()` returns a `BatchResult` (`{ elements, sideEffects }`) per completed- * batch, or `null` when fully drained. Batches are returned in completion- * order; items within a batch keep their feed order.+ * Unlike a plain `ChunkPipeline`, `feed()` is async, takes a per-batch context+ * alongside the elements (`{}` when the caller has nothing to attach), and+ * returns a `FeedResult`: `{ ok: true }` when accepted, or+ * `{ ok: false, kind, reason }` when rejected.+ * `next()` returns a `BatchResult` (`{ elements, batchContext, sideEffects }`)+ * per completed batch, or `null` when fully drained — `batchContext` carries+ * the caller's feed() context back, correlating the completion to its feed.+ * Batches are returned in completion order; items within a batch keep their+ * feed order.** ## Backpressure*@@ -101,8 +105,14 @@ describe('Batching Pipelines', () => {{ concurrentBatches: Infinity })- await pipeline.feed([{ id: 10 }, { id: 20 }].map((e) => createOkContext(e, {})))- await pipeline.feed([{ id: 30 }].map((e) => createOkContext(e, {})))+ await pipeline.feed(+ [{ id: 10 }, { id: 20 }].map((e) => createOkContext(e, {})),+ {}+ )+ await pipeline.feed(+ [{ id: 30 }].map((e) => createOkContext(e, {})),+ {}+ )const messageIds: number[] = []let batch = await pipeline.next()@@ -148,7 +158,10 @@ describe('Batching Pipelines', () => {{ concurrentBatches: Infinity })- await pipeline.feed([{ id: 1 }].map((e) => createOkContext(e, {})))+ await pipeline.feed(+ [{ id: 1 }].map((e) => createOkContext(e, {})),+ {}+ )await pipeline.next()expect(seenInAfter).toBe('store-0')@@ -174,10 +187,18 @@ describe('Batching Pipelines', () => {)// First batch accepted- expect(await pipeline.feed([{ id: 1 }].map((e) => createOkContext(e, {})))).toEqual({ ok: true })+ expect(+ await pipeline.feed(+ [{ id: 1 }].map((e) => createOkContext(e, {})),+ {}+ )+ ).toEqual({ ok: true })// Second batch rejected: already at capacity- const rejected = await pipeline.feed([{ id: 2 }].map((e) => createOkContext(e, {})))+ const rejected = await pipeline.feed(+ [{ id: 2 }].map((e) => createOkContext(e, {})),+ {}+ )expect(rejected).toMatchObject({ ok: false, kind: 'at_capacity' })// Draining the in-flight batch frees the slot@@ -186,7 +207,12 @@ describe('Batching Pipelines', () => {expect(drained!.elements.every((e) => isOkResult(e.result))).toBe(true)// Now a new batch is accepted again- expect(await pipeline.feed([{ id: 3 }].map((e) => createOkContext(e, {})))).toEqual({ ok: true })+ expect(+ await pipeline.feed(+ [{ id: 3 }].map((e) => createOkContext(e, {})),+ {}+ )+ ).toEqual({ ok: true })})/**@@ -211,12 +237,17 @@ describe('Batching Pipelines', () => {{ concurrentBatches: 1 })- expect(await pipeline.feed([])).toEqual({ ok: true })+ expect(await pipeline.feed([], {})).toEqual({ ok: true })expect(beforeBatchRan).toBe(false)expect(await pipeline.next()).toBeNull()// No capacity was consumed: a real batch still fits in the single slot- expect(await pipeline.feed([{ id: 1 }].map((e) => createOkContext(e, {})))).toEqual({ ok: true })+ expect(+ await pipeline.feed(+ [{ id: 1 }].map((e) => createOkContext(e, {})),+ {}+ )+ ).toEqual({ ok: true })expect(await pipeline.next()).not.toBeNull()})@@ -241,8 +272,11 @@ describe('Batching Pipelines', () => {{ concurrentBatches: 1 })- await expect(pipeline.feed([{ id: 1 }, { id: 2 }].map((e) => createOkContext(e, {})))).rejects.toThrow(- 'changed element count (2 -> 1)'- )+ await expect(+ pipeline.feed(+ [{ id: 1 }, { id: 2 }].map((e) => createOkContext(e, {})),+ {}+ )+ ).rejects.toThrow('changed element count (2 -> 1)')})})diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex 7d5403c1de9a..eb094ace2d81 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -444,7 +444,7 @@ export class IngestionConsumer {createOkContext({ message }, { message, debugContext: createKafkaDebugContext(message) }))- const feedResult = await this.joinedPipeline.feed(batch)+ const feedResult = await this.joinedPipeline.feed(batch, {})if (!feedResult.ok) {throw new Error(`Pipeline rejected batch: ${feedResult.reason}`)}diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.test.tsindex 82dc5aab22d6..384c3c4f764a 100644--- a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts@@ -77,7 +77,7 @@ describe('AiIngestionPipeline', () => {const runPipeline = async (messages: Message[]): Promise<void> => {const pipeline = createAiIngestionPipeline(config)const batch = messages.map((message) => createOkContext({ message }, { message }))- await pipeline.feed(batch)+ await pipeline.feed(batch, {})let result = await pipeline.next()while (result !== null) {// The pipeline handles its own side effects; none may leak to drivers.diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.tsindex 5e5cbc30ea3b..9d61debf191c 100644--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts@@ -105,6 +105,7 @@ function getTokenAndDistinctId(input: EventSubpipelineInput): string {export function createJoinedIngestionPipeline<TInput extends JoinedIngestionPipelineInput,TContext extends JoinedIngestionPipelineContext,+ CFeed extends object = Record<never, never>,>(config: JoinedIngestionPipelineConfig, deps: JoinedIngestionPipelineDeps) {const {eventSchemaEnforcementEnabled,@@ -219,6 +220,6 @@ export function createJoinedIngestionPipeline<.pipe(createFlushEventFiltersBatchAppMetricsStep()).pipe(createFlushHogTransformerStep(hogTransformer)))- .build()+ .build<CFeed>())}diff --git a/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.tsindex 5c319b0b66af..68738973ce9e 100644--- a/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/clientwarnings/pipeline.test.ts@@ -63,7 +63,7 @@ describe('ClientWarningsPipeline', () => {const runPipeline = async (messages: Message[]): Promise<void> => {const pipeline = createClientWarningsPipeline<{ message: Message }, { message: Message }>(config)const batch = messages.map((message) => createOkContext({ message }, { message }))- await pipeline.feed(batch)+ await pipeline.feed(batch, {})let result = await pipeline.next()while (result !== null) {// The pipeline handles its own side effects; none may leak to drivers.diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.tsindex 10c7fcdf3c83..c8408762d24f 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts@@ -238,7 +238,7 @@ export async function runErrorTrackingPipeline(pipeline: ErrorTrackingPipeline,const batch = createBatch(messages.map((message) => ({ message })))// The consumer drains each batch fully before feeding the next and the hooks// always succeed, so a rejected feed can only be a framework invariant violation.- const feedResult = await pipeline.feed(batch)+ const feedResult = await pipeline.feed(batch, {})if (!feedResult.ok) {throw new Error(`error tracking pipeline rejected feed: ${feedResult.kind} (${feedResult.reason})`)}diff --git a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.tsindex 5458a4fc3d37..c257a9afec11 100644--- a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.test.ts@@ -77,7 +77,7 @@ describe('HeatmapsPipeline', () => {const runPipeline = async (messages: Message[]): Promise<void> => {const pipeline = createHeatmapsPipeline(config)const batch = messages.map((message) => createOkContext({ message }, { message }))- await pipeline.feed(batch)+ await pipeline.feed(batch, {})let result = await pipeline.next()while (result !== null) {// The pipeline handles its own side effects; none may leak to drivers.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.tsindex 55b08ba19da3..64398252d374 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts@@ -294,7 +294,7 @@ export async function runSessionReplayPipeline(const batch = createBatch(messages.map((message) => ({ message, sessionBatchRecorder })))// The consumer drains each batch fully before feeding the next and the hooks always succeed,// so a rejected feed can only be a framework invariant violation.- const feedResult = await pipeline.feed(batch)+ const feedResult = await pipeline.feed(batch, {})if (!feedResult.ok) {throw new Error(`session replay pipeline rejected feed: ${feedResult.kind} (${feedResult.reason})`)}diff --git a/nodejs/src/servers/grpc-stream-ingest-driver.ts b/nodejs/src/servers/grpc-stream-ingest-driver.tsnew file mode 100644index 000000000000..b61b56744266--- /dev/null+++ b/nodejs/src/servers/grpc-stream-ingest-driver.ts@@ -0,0 +1,58 @@+import { PromiseScheduler } from '~/common/utils/promise-scheduler'+import { CompletedSubBatch, StreamIngestDriver } from '~/ingestion/api/grpc-server'+import { deserializeKafkaMessage } from '~/ingestion/api/kafka-message-converter'+import { SerializedKafkaMessage } from '~/ingestion/api/types'+import { FeedResult } from '~/ingestion/framework/batching-pipeline'+import { createKafkaDebugContext, createOkContext } from '~/ingestion/framework/helpers'+import {+ JoinedIngestionPipelineContext,+ JoinedIngestionPipelineInput,+ createJoinedIngestionPipeline,+} from '~/ingestion/pipelines/analytics/joined-ingestion-pipeline'++/** Batch context fed with each gRPC sub-batch so its completion routes back to the right stream. */+export type GrpcBatchContext = { grpcStreamId: number; grpcSeq: number }++export type GrpcIngestPipeline = ReturnType<+ typeof createJoinedIngestionPipeline<JoinedIngestionPipelineInput, JoinedIngestionPipelineContext, GrpcBatchContext>+>++/**+ * Pipeline mechanics for the gRPC stream server. The `settled` promise on+ * each completed batch is the ack barrier: it mirrors the HTTP handler's+ * contract (side effects plus the promise scheduler) but stays a promise+ * so the server can settle many batches concurrently.+ */+export class GrpcStreamIngestDriver implements StreamIngestDriver {+ constructor(+ private pipeline: GrpcIngestPipeline,+ private promiseScheduler: PromiseScheduler+ ) {}++ feed(streamId: number, seq: number, messages: SerializedKafkaMessage[]): Promise<FeedResult> {+ const batch = messages.map((serialized) => {+ const message = deserializeKafkaMessage(serialized)+ return createOkContext({ message }, { message, debugContext: createKafkaDebugContext(message) })+ })+ return this.pipeline.feed(batch, { grpcStreamId: streamId, grpcSeq: seq })+ }++ async next(): Promise<CompletedSubBatch | null> {+ const result = await this.pipeline.next()+ if (result === null) {+ return null+ }+ // waitForAll snapshots the currently scheduled promises, so this+ // settles even under sustained load from other batches.+ const settled = (async (): Promise<void> => {+ await Promise.all(result.sideEffects ?? [])+ await this.promiseScheduler.waitForAll()+ })()+ return {+ streamId: result.batchContext.grpcStreamId,+ seq: result.batchContext.grpcSeq,+ accepted: result.elements.length,+ settled,+ }+ }+}diff --git a/nodejs/src/servers/ingestion-api-server.test.ts b/nodejs/src/servers/ingestion-api-server.test.tsindex 7174d6771c79..6338dedfc002 100644--- a/nodejs/src/servers/ingestion-api-server.test.ts+++ b/nodejs/src/servers/ingestion-api-server.test.ts@@ -55,7 +55,7 @@ describe('IngestionApiServer', () => {beforeEach(() => {server = new IngestionApiServer()pipeline = { feed: jest.fn(), next: jest.fn() }- ;(server as any).joinedPipeline = pipeline+ ;(server as any).httpPipeline = pipeline;(server as any).promiseScheduler = { schedule: jest.fn(), waitForAll: jest.fn().mockResolvedValue(undefined) };(server as any).hogTransformer = { processInvocationResults: jest.fn().mockResolvedValue(undefined) }// stop() would call process.exit; stub it so the test only observes that it was invoked.diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex f7bfb9eb5ddc..de64ad15241f 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -71,6 +71,7 @@ import {import { EncryptedFields } from '../cdp/utils/encryption-utils'import { CommonConfig } from '../common/config'import { FeedOrderSentinel } from '../ingestion/api/feed-order-sentinel'+import { WorkerIngestServer } from '../ingestion/api/grpc-server'import { deserializeKafkaMessage } from '../ingestion/api/kafka-message-converter'import { IngestBatchRequest, IngestBatchResponse } from '../ingestion/api/types'import { EventFilterManagerComponent } from '../ingestion/common/event-filters'@@ -98,6 +99,7 @@ import {RedisPool,} from '../types'import { BaseServerConfig, CleanupResources, NodeServer, ServerLifecycle } from './base-server'+import { GrpcBatchContext, GrpcStreamIngestDriver } from './grpc-stream-ingest-driver'export type IngestionApiServerConfig = BaseServerConfig &IngestionConsumerConfig &@@ -211,20 +213,21 @@ export class IngestionApiServer implements NodeServer {// (moved to caller-side production so create and flush share one path).private ingestionOutputs?: FlushBatchStoresOutputs- private joinedPipeline!: ReturnType<+ private httpPipeline!: ReturnType<typeof createJoinedIngestionPipeline<JoinedIngestionPipelineInput, JoinedIngestionPipelineContext>>+ private grpcServer?: WorkerIngestServerprivate promiseScheduler = new PromiseScheduler()private hogTransformer!: HogTransformerServiceprivate topHog!: TopHog// Set in startServices when INGESTION_API_FEED_ORDER_SENTINEL_ENABLED.private feedOrderSentinel?: FeedOrderSentinel- // Latched on the first unexpected pipeline error. The joinedPipeline is a- // single long-lived instance shared across all requests; a throw can leave- // it permanently poisoned (e.g. a group exhausted retries), so we mirror the- // Kafka consumer's contract of crashing and rebuilding rather than serving a- // wedged pipeline forever.+ // Latched on the first unexpected pipeline error. The pipeline is a single+ // long-lived instance shared across all requests; a throw can leave it+ // permanently poisoned (e.g. a group exhausted retries), so we mirror the+ // Kafka consumer's contract of crashing and rebuilding rather than serving+ // a wedged pipeline forever.private fatalError?: Errorconstructor(config: Partial<IngestionApiServerConfig> = {}) {@@ -503,15 +506,49 @@ export class IngestionApiServer implements NodeServer {groupTypeManager,topHog: this.topHog,}- this.joinedPipeline = createJoinedIngestionPipeline(joinedPipelineConfig, joinedPipelineDeps)-- // 8. Register the ingest endpoint and service+ // 8. Register the ingest transports. HTTP always serves; gRPC is+ // additive behind its flag, so consumers can migrate gradually.if (this.config.INGESTION_API_FEED_ORDER_SENTINEL_ENABLED) {this.feedOrderSentinel = new FeedOrderSentinel(this.config.INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS)}+ this.httpPipeline = createJoinedIngestionPipeline(joinedPipelineConfig, joinedPipelineDeps)this.lifecycle.expressApp.post('/ingest', async (req, res) => {await this.handleIngestRequest(req, res)})+ if (this.config.INGESTION_API_GRPC_ENABLED) {+ // Own pipeline instance: sharing httpPipeline would let an HTTP+ // handler's next() consume a gRPC batch's completion (and its ack).+ const grpcPipeline = createJoinedIngestionPipeline<+ JoinedIngestionPipelineInput,+ JoinedIngestionPipelineContext,+ GrpcBatchContext+ >(joinedPipelineConfig, joinedPipelineDeps)+ this.grpcServer = new WorkerIngestServer(+ {+ port: this.config.INGESTION_API_GRPC_PORT,+ maxConcurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,+ maxStreams: this.config.INGESTION_API_GRPC_MAX_STREAMS,+ maxSessions: this.config.INGESTION_API_GRPC_MAX_SESSIONS,+ maxStreamsPerSession: this.config.INGESTION_API_GRPC_MAX_STREAMS_PER_SESSION,+ sessionMemoryMb: this.config.INGESTION_API_GRPC_SESSION_MEMORY_MB,+ sessionIdleTimeoutMs: this.config.INGESTION_API_GRPC_SESSION_IDLE_TIMEOUT_MS,+ readMaxBytes: this.config.INGESTION_API_GRPC_READ_MAX_BYTES,+ drainTimeoutMs: this.config.INGESTION_API_GRPC_DRAIN_TIMEOUT_MS,+ },+ {+ driver: new GrpcStreamIngestDriver(grpcPipeline, this.promiseScheduler),+ feedOrderSentinel: this.feedOrderSentinel,+ onFatal: (error) => {+ // Same crash-and-rebuild contract as the HTTP path.+ if (!this.fatalError) {+ this.fatalError = error+ void this.stop(error)+ }+ },+ }+ )+ await this.grpcServer.start()+ }const service: PluginServerService = {id: 'ingestion-api',@@ -557,7 +594,7 @@ export class IngestionApiServer implements NodeServer {// stage processes each key in feed order, so this measures the// "processed in order per distinct_id" invariant.this.feedOrderSentinel?.check(serializedMessages, consumer_id ?? 'unknown', replay ?? false)- const feedResult = await this.joinedPipeline.feed(batch)+ const feedResult = await this.httpPipeline.feed(batch, {})if (!feedResult.ok) {// Capacity rejection should not happen under correct consumer// behavior — the Rust consumer holds a per-worker Semaphore@@ -594,9 +631,9 @@ export class IngestionApiServer implements NodeServer {// The pipeline handles its own side effects (scheduling them on// the promise scheduler), so draining results is all that's left// to do.- let result = await this.joinedPipeline.next()+ let result = await this.httpPipeline.next()while (result !== null) {- result = await this.joinedPipeline.next()+ result = await this.httpPipeline.next()}// Wait for all side effects — the HTTP response is the ACK to the@@ -652,6 +689,9 @@ export class IngestionApiServer implements NodeServer {postgres: this.postgres,pubsub: this.pubsub,additionalCleanup: async () => {+ // Stop accepting stream traffic before draining stores, so no+ // new batches land mid-teardown.+ await this.grpcServer?.stop()// No Kafka offsets in this server — drain buffered writes before// shutdown so shutdown() can assert a clean cache.if (this.personsStore) {diff --git a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.tsindex 61bc63ee477f..4ab756891230 100644--- a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts+++ b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts@@ -406,7 +406,7 @@ class Harness {const message = this.makeMessage(spec)return createOkContext<In, Ctx>({ message }, { message })})- return this.pipeline.feed(batch)+ return this.pipeline.feed(batch, {})}/** Drain the pipeline like the consumer/API server: next() until null, scheduling side effects. */diff --git a/proto/buf.yaml b/proto/buf.yamlindex 42108ae3719d..8e3cc44a3b4e 100644--- a/proto/buf.yaml+++ b/proto/buf.yaml@@ -27,3 +27,17 @@ breaking:- personhog/service/v1/service.protoMESSAGE_NO_DELETE:- personhog/types/v1/person.proto+ # Temporary: the WorkerIngest stream has no consumers yet, so its+ # response message can be reshaped in place. Remove once on master.+ FIELD_NO_DELETE:+ - ingestion/worker/v1/worker.proto+ FIELD_SAME_CARDINALITY:+ - ingestion/worker/v1/worker.proto+ FIELD_SAME_JSON_NAME:+ - ingestion/worker/v1/worker.proto+ FIELD_SAME_NAME:+ - ingestion/worker/v1/worker.proto+ FIELD_SAME_ONEOF:+ - ingestion/worker/v1/worker.proto+ FIELD_SAME_TYPE:+ - ingestion/worker/v1/worker.protodiff --git a/proto/ingestion/worker/v1/worker.proto b/proto/ingestion/worker/v1/worker.protoindex 76cdaa3d7e71..99ece0acd775 100644--- a/proto/ingestion/worker/v1/worker.proto+++ b/proto/ingestion/worker/v1/worker.proto@@ -83,8 +83,24 @@ enum SubBatchStatus {SUB_BATCH_STATUS_FAILED = 2;}-// IngestStreamResponse acks one sub-batch.+// IngestStreamResponse is one frame on the worker-to-consumer stream.message IngestStreamResponse {+ oneof msg {+ // First frame on every stream, sent as soon as the worker accepts it and+ // before any sub-batch completes: flushes response headers so the+ // consumer's stream-open resolves (some HTTP/2 server stacks defer+ // headers until the first response message).+ StreamReady ready = 1;+ SubBatchAck ack = 2;+ }+}++// StreamReady carries no data yet; it is the slot where the worker could+// later advertise limits or echo the hello.+message StreamReady {}++// SubBatchAck acks one sub-batch.+message SubBatchAck {// The `SubBatch.seq` this ack resolves.uint64 seq = 1;SubBatchStatus status = 2;