Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ingestion): sub-batch soft budgets with partial acks (#115388)

José Sequeira6e65990e7caf
diff --git a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md
index c07fd6232151..0e55b6185420 100644
--- a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md
+++ b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md
@@ -48,7 +48,7 @@ See `nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts` for
| Concern | Agent | When to use |
| --------------- | ----------------------------- | --------------------------------------------------------- |
| Step structure | `pipeline-step-doctor` | Factory pattern, type extension, config injection, naming |
-| Result handling | `pipeline-result-doctor` | ok/dlq/drop/redirect, side effects, ingestion warnings |
+| Result handling | `pipeline-result-doctor` | ok/dlq/drop/redirect/timeout, side effects, warnings |
| Composition | `pipeline-composition-doctor` | Builder chain, concurrency, grouping, branching, retries |
| Testing | `pipeline-testing-doctor` | Test helpers, assertions, fake timers, doc-test style |
@@ -56,13 +56,15 @@ See `nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts` for
**Steps**: Factory function returning a named inner function. Generic `<T extends Input>` for type extension. No `any`. Config via closure.
-**Results**: Use `ok()`, `dlq()`, `drop()`, `redirect()` constructors. Side effects as promises in `ok(value, [effects])`. Warnings as third parameter.
+**Results**: Use `ok()`, `dlq()`, `drop()`, `redirect()` constructors. Side effects as promises in `ok(value, [effects])`. Warnings as third parameter. Steps never return `timeout()`: only the budget checkpoints produce it.
+
+**Batch time budgets** (`feed(elements, batchContext, BatchBudget.softDeadline(softAt))`): the framework stops starting steps once a batch's budget runs out, and the cut-off elements complete as `timeout()`, which is not acked and is redelivered. `.timeoutBarrier()` marks the last checkpoint: an element past it with time left always finishes. Place it before the first step whose writes make finishing cheaper than redelivering, and before any side effect that is unsafe to repeat, because a cut element is redelivered and its chain runs again from the top. A group that runs one element at a time completes a prefix of its feed order, but `concurrently` and fan-out/fan-in do not keep that prefix. Details: `nodejs/src/ingestion/framework/docs/18-batch-budgets.test.ts`.
**Composition**: `messageAware` wraps the pipeline. `handleResults` inside `messageAware`. `handleSideEffects` after. `concurrentlyPerGroup` for per-entity work. `gather` before chunk steps.
**Batching lifecycle hooks** (`BatchingPipeline` beforeBatch/afterBatch): enrich-only. Hooks may enrich elements and batch context but must return exactly the elements they received — a count change is a broken invariant and `feed()` throws. Filtering belongs in sub-pipeline steps that return `drop()`. An empty `feed()` is a no-op (no hooks, no capacity). Details: `nodejs/src/ingestion/framework/docs/14-batching.test.ts`.
-**Fan-out/fan-in** (`fanOut(fn).via((sub) => …).fanIn(fn)`): per-element sub-work with cardinality restored — one element fans out to N sub-elements (e.g. per-blob uploads), a regular sub-pipeline processes them (`maxConcurrency` on the sub `concurrently` block, `retry` on the per-sub step), and fan-in folds the OK results back into the parent. Reach for it over `concurrently`/`concurrentlyPerGroup` when the unit of concurrency is smaller than the element; hand-rolled `p-limit`/`Promise.all` inside a step is the tell. Sequencing is compile-time enforced (an unclosed stage cannot build). Sub-result contract: OK collected; DROP excludes the sub silently; DLQ fails the parent with aggregated reasons; REDIRECT is excluded with a warning — sub redirects never escape the stage. Sub-pipelines are context-agnostic: team/message data goes in the sub-element value, and context-gated surface (`teamAware`, `handleIngestionWarnings`, …) is uncallable. Fan-out/fan-in functions are cheap, synchronous, and named. Parents emit unordered as they complete. Details: `nodejs/src/ingestion/framework/docs/17-fan-out-fan-in.test.ts`.
+**Fan-out/fan-in** (`fanOut(fn).via((sub) => …).fanIn(fn)`): per-element sub-work with cardinality restored — one element fans out to N sub-elements (e.g. per-blob uploads), a regular sub-pipeline processes them (`maxConcurrency` on the sub `concurrently` block, `retry` on the per-sub step), and fan-in folds the OK results back into the parent. Reach for it over `concurrently`/`concurrentlyPerGroup` when the unit of concurrency is smaller than the element; hand-rolled `p-limit`/`Promise.all` inside a step is the tell. Sequencing is compile-time enforced (an unclosed stage cannot build). Sub-result contract: OK collected; DROP excludes the sub silently; DLQ fails the parent with aggregated reasons; REDIRECT is excluded with a warning — sub redirects never escape the stage; TIMEOUT times the parent out and wins over DLQ. Sub-pipelines are context-agnostic: team/message data goes in the sub-element value, and context-gated surface (`teamAware`, `handleIngestionWarnings`, …) is uncallable. Fan-out/fan-in functions are cheap, synchronous, and named. Parents emit unordered as they complete. Details: `nodejs/src/ingestion/framework/docs/17-fan-out-fan-in.test.ts`.
**Testing**: Step tests call factory directly. Use `consumeAll()`/`collectChunks()` helpers. Fake timers for async. Type guards for result assertions. No `any`.
diff --git a/.claude/agents/ingestion/pipeline-result-doctor.md b/.claude/agents/ingestion/pipeline-result-doctor.md
index 7898eb10018a..d3e72829fc64 100644
--- a/.claude/agents/ingestion/pipeline-result-doctor.md
+++ b/.claude/agents/ingestion/pipeline-result-doctor.md
@@ -45,6 +45,7 @@ Before reviewing or writing any code, read these files:
- `nodejs/src/ingestion/framework/docs/09-ingestion-warnings.test.ts` — warning structure, debouncing, team context
- `nodejs/src/ingestion/framework/results.ts` — result type definitions and constructor implementations
- `nodejs/src/ingestion/framework/docs/17-fan-out-fan-in.test.ts` — sub-result contract inside fan-out/fan-in stages
+- `nodejs/src/ingestion/framework/docs/18-batch-budgets.test.ts` — the timeout result, budget checkpoints, and the timeout barrier
Also read any files the user points you to.
@@ -60,6 +61,10 @@ Never throw from steps — exceptions are for truly unexpected errors, not expec
- `drop(reason)` — items to silently discard
- `redirect(reason, topic, preserveKey?)` — reroute to another topic
+`timeout()` is not a step result.
+Only the framework's budget checkpoints and `.timeoutBarrier()` produce it, because steps never see the budget.
+A timed-out message is not acked, and its source redelivers it.
+
```typescript
// GOOD
return Promise.resolve(dlq('invalid JSON in event body', new Error(`parse failed: ${e.message}`)))
@@ -200,6 +205,9 @@ steps — the stage settles the parent from its sub-results:
- `redirect()` — a review flag: sub-elements are not Kafka messages, so there is nothing to
redirect. The stage excludes it with a warning log. Route the parent in a step before the
fan-out instead — sub redirects never escape the stage's result type.
+- `timeout()` — comes from a budget checkpoint inside the sub-pipeline, and times the parent out.
+ It wins over a sub DLQ: the parent's message is redelivered whole, so fanning in would build an element from partial work.
+ Sibling side effects still run, and the collected values are discarded.
## Output format
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.ts
index 78d462dd1d1d..fa29480e3b6d 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/protobuf
export const file_ingestion_worker_v1_worker: GenFile =
/*@__PURE__*/
fileDesc(
- 'CiBpbmdlc3Rpb24vd29ya2VyL3YxL3dvcmtlci5wcm90bxITaW5nZXN0aW9uLndvcmtlci52MSKDAQoTSW5nZXN0U3RyZWFtUmVxdWVzdBIxCgVoZWxsbxgBIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3RyZWFtSGVsbG9IABIyCglzdWJfYmF0Y2gYAiABKAsyHS5pbmdlc3Rpb24ud29ya2VyLnYxLlN1YkJhdGNoSABCBQoDbXNnIjgKC1N0cmVhbUhlbGxvEhMKC2NvbnN1bWVyX2lkGAEgASgJEhQKDHN0cmVhbV9lcG9jaBgCIAEoBCKIAQoIU3ViQmF0Y2gSCwoDc2VxGAEgASgEEhAKCGJhdGNoX2lkGAIgASgJEjMKCG1lc3NhZ2VzGAMgAygLMiEuaW5nZXN0aW9uLndvcmtlci52MS5LYWZrYU1lc3NhZ2USDgoGcmVwbGF5GAQgASgIEhgKEGFzc2lnbm1lbnRfZXBvY2gYBSABKAQi/AEKDEthZmthTWVzc2FnZRINCgV0b3BpYxgBIAEoCRIRCglwYXJ0aXRpb24YAiABKAUSDgoGb2Zmc2V0GAMgASgDEhEKCXRpbWVzdGFtcBgEIAEoAxIQCgNrZXkYBSABKAlIAIgBARISCgV2YWx1ZRgGIAEoCUgBiAEBEj8KB2hlYWRlcnMYByADKAsyLi5pbmdlc3Rpb24ud29ya2VyLnYxLkthZmthTWVzc2FnZS5IZWFkZXJzRW50cnkaLgoMSGVhZGVyc0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAFCBgoEX2tleUIICgZfdmFsdWUigQEKFEluZ2VzdFN0cmVhbVJlc3BvbnNlEjEKBXJlYWR5GAEgASgLMiAuaW5nZXN0aW9uLndvcmtlci52MS5TdHJlYW1SZWFkeUgAEi8KA2FjaxgCIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3ViQmF0Y2hBY2tIAEIFCgNtc2ciDQoLU3RyZWFtUmVhZHkicAoLU3ViQmF0Y2hBY2sSCwoDc2VxGAEgASgEEjMKBnN0YXR1cxgCIAEoDjIjLmluZ2VzdGlvbi53b3JrZXIudjEuU3ViQmF0Y2hTdGF0dXMSEAoIYWNjZXB0ZWQYAyABKA0SDQoFZXJyb3IYBCABKAkqgwEKDlN1YkJhdGNoU3RhdHVzEiAKHFNVQl9CQVRDSF9TVEFUVVNfVU5TUEVDSUZJRUQQABIXChNTVUJfQkFUQ0hfU1RBVFVTX09LEAESGwoXU1VCX0JBVENIX1NUQVRVU19GQUlMRUQQAhIZChVTVUJfQkFUQ0hfU1RBVFVTX0JVU1kQAzJ3CgxXb3JrZXJJbmdlc3QSZwoMSW5nZXN0U3RyZWFtEiguaW5nZXN0aW9uLndvcmtlci52MS5Jbmdlc3RTdHJlYW1SZXF1ZXN0GikuaW5nZXN0aW9uLndvcmtlci52MS5Jbmdlc3RTdHJlYW1SZXNwb25zZSgBMAFiBnByb3RvMw'
+ 'CiBpbmdlc3Rpb24vd29ya2VyL3YxL3dvcmtlci5wcm90bxITaW5nZXN0aW9uLndvcmtlci52MSKDAQoTSW5nZXN0U3RyZWFtUmVxdWVzdBIxCgVoZWxsbxgBIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3RyZWFtSGVsbG9IABIyCglzdWJfYmF0Y2gYAiABKAsyHS5pbmdlc3Rpb24ud29ya2VyLnYxLlN1YkJhdGNoSABCBQoDbXNnIjgKC1N0cmVhbUhlbGxvEhMKC2NvbnN1bWVyX2lkGAEgASgJEhQKDHN0cmVhbV9lcG9jaBgCIAEoBCKgAQoIU3ViQmF0Y2gSCwoDc2VxGAEgASgEEhAKCGJhdGNoX2lkGAIgASgJEjMKCG1lc3NhZ2VzGAMgAygLMiEuaW5nZXN0aW9uLndvcmtlci52MS5LYWZrYU1lc3NhZ2USDgoGcmVwbGF5GAQgASgIEhgKEGFzc2lnbm1lbnRfZXBvY2gYBSABKAQSFgoOc29mdF9idWRnZXRfbXMYBiABKAQi/AEKDEthZmthTWVzc2FnZRINCgV0b3BpYxgBIAEoCRIRCglwYXJ0aXRpb24YAiABKAUSDgoGb2Zmc2V0GAMgASgDEhEKCXRpbWVzdGFtcBgEIAEoAxIQCgNrZXkYBSABKAlIAIgBARISCgV2YWx1ZRgGIAEoCUgBiAEBEj8KB2hlYWRlcnMYByADKAsyLi5pbmdlc3Rpb24ud29ya2VyLnYxLkthZmthTWVzc2FnZS5IZWFkZXJzRW50cnkaLgoMSGVhZGVyc0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAFCBgoEX2tleUIICgZfdmFsdWUiLwoKTWVzc2FnZVJlZhIRCglwYXJ0aXRpb24YASABKAUSDgoGb2Zmc2V0GAIgASgDIoEBChRJbmdlc3RTdHJlYW1SZXNwb25zZRIxCgVyZWFkeRgBIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3RyZWFtUmVhZHlIABIvCgNhY2sYAiABKAsyIC5pbmdlc3Rpb24ud29ya2VyLnYxLlN1YkJhdGNoQWNrSABCBQoDbXNnIg0KC1N0cmVhbVJlYWR5IqUBCgtTdWJCYXRjaEFjaxILCgNzZXEYASABKAQSMwoGc3RhdHVzGAIgASgOMiMuaW5nZXN0aW9uLndvcmtlci52MS5TdWJCYXRjaFN0YXR1cxIQCghhY2NlcHRlZBgDIAEoDRINCgVlcnJvchgEIAEoCRIzCgp1bmZpbmlzaGVkGAUgAygLMh8uaW5nZXN0aW9uLndvcmtlci52MS5NZXNzYWdlUmVmKqEBCg5TdWJCYXRjaFN0YXR1cxIgChxTVUJfQkFUQ0hfU1RBVFVTX1VOU1BFQ0lGSUVEEAASFwoTU1VCX0JBVENIX1NUQVRVU19PSxABEhsKF1NVQl9CQVRDSF9TVEFUVVNfRkFJTEVEEAISGQoVU1VCX0JBVENIX1NUQVRVU19CVVNZEAMSHAoYU1VCX0JBVENIX1NUQVRVU19QQVJUSUFMEAQydwoMV29ya2VySW5nZXN0EmcKDEluZ2VzdFN0cmVhbRIoLmluZ2VzdGlvbi53b3JrZXIudjEuSW5nZXN0U3RyZWFtUmVxdWVzdBopLmluZ2VzdGlvbi53b3JrZXIudjEuSW5nZXN0U3RyZWFtUmVzcG9uc2UoATABYgZwcm90bzM'
)
/**
@@ -126,6 +126,15 @@ export type SubBatch = Message<'ingestion.worker.v1.SubBatch'> & {
* @generated from field: uint64 assignment_epoch = 5;
*/
assignmentEpoch: bigint
+
+ /**
+ * Milliseconds after which the worker stops starting new work. It never
+ * interrupts a running step, so the ack watchdog stays the hard limit.
+ * 0, or a value above 2^31 - 1, means unlimited.
+ *
+ * @generated from field: uint64 soft_budget_ms = 6;
+ */
+ softBudgetMs: bigint
}
/**
@@ -187,6 +196,29 @@ export const KafkaMessageSchema: GenMessage<KafkaMessage> =
/*@__PURE__*/
messageDesc(file_ingestion_worker_v1_worker, 3)
+/**
+ * The consumer reads one topic, so a partition and an offset identify a message.
+ *
+ * @generated from message ingestion.worker.v1.MessageRef
+ */
+export type MessageRef = Message<'ingestion.worker.v1.MessageRef'> & {
+ /**
+ * @generated from field: int32 partition = 1;
+ */
+ partition: number
+
+ /**
+ * @generated from field: int64 offset = 2;
+ */
+ offset: bigint
+}
+
+/**
+ * Describes the message ingestion.worker.v1.MessageRef.
+ * Use `create(MessageRefSchema)` to create a new message.
+ */
+export const MessageRefSchema: GenMessage<MessageRef> = /*@__PURE__*/ messageDesc(file_ingestion_worker_v1_worker, 4)
+
/**
* IngestStreamResponse is one frame on the worker-to-consumer stream.
*
@@ -225,7 +257,7 @@ export type IngestStreamResponse = Message<'ingestion.worker.v1.IngestStreamResp
*/
export const IngestStreamResponseSchema: GenMessage<IngestStreamResponse> =
/*@__PURE__*/
- messageDesc(file_ingestion_worker_v1_worker, 4)
+ messageDesc(file_ingestion_worker_v1_worker, 5)
/**
* StreamReady carries no data yet; it is the slot where the worker could
@@ -239,7 +271,7 @@ 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)
+export const StreamReadySchema: GenMessage<StreamReady> = /*@__PURE__*/ messageDesc(file_ingestion_worker_v1_worker, 6)
/**
* SubBatchAck acks one sub-batch.
@@ -261,7 +293,7 @@ export type SubBatchAck = Message<'ingestion.worker.v1.SubBatchAck'> & {
/**
* Messages accepted into the pipeline. Meaningful only on
- * SUB_BATCH_STATUS_OK.
+ * SUB_BATCH_STATUS_OK and SUB_BATCH_STATUS_PARTIAL.
*
* @generated from field: uint32 accepted = 3;
*/
@@ -273,13 +305,23 @@ export type SubBatchAck = Message<'ingestion.worker.v1.SubBatchAck'> & {
* @generated from field: string error = 4;
*/
error: string
+
+ /**
+ * Messages with work left when the budget ran out. Set only on PARTIAL,
+ * never empty. Every other message is done, as on OK. The listed messages
+ * need not be the last of their routing key, because a worker may process
+ * one key's messages in independent groups.
+ *
+ * @generated from field: repeated ingestion.worker.v1.MessageRef unfinished = 5;
+ */
+ unfinished: MessageRef[]
}
/**
* Describes the message ingestion.worker.v1.SubBatchAck.
* Use `create(SubBatchAckSchema)` to create a new message.
*/
-export const SubBatchAckSchema: GenMessage<SubBatchAck> = /*@__PURE__*/ messageDesc(file_ingestion_worker_v1_worker, 6)
+export const SubBatchAckSchema: GenMessage<SubBatchAck> = /*@__PURE__*/ messageDesc(file_ingestion_worker_v1_worker, 7)
/**
* SubBatchStatus is the outcome of processing one sub-batch.
@@ -320,6 +362,14 @@ export enum SubBatchStatus {
* @generated from enum value: SUB_BATCH_STATUS_BUSY = 3;
*/
BUSY = 3,
+
+ /**
+ * The budget cut the sub-batch short. Messages not in `SubBatchAck.unfinished`
+ * are done as on OK, and the consumer redelivers exactly the listed ones.
+ *
+ * @generated from enum value: SUB_BATCH_STATUS_PARTIAL = 4;
+ */
+ PARTIAL = 4,
}
/**
diff --git a/nodejs/src/ingestion/api/batch-metrics.ts b/nodejs/src/ingestion/api/batch-metrics.ts
index 6fe725453f47..b9f96bb05d53 100644
--- a/nodejs/src/ingestion/api/batch-metrics.ts
+++ b/nodejs/src/ingestion/api/batch-metrics.ts
@@ -68,11 +68,11 @@ export function batchAccepted(events: number): AcceptedBatch {
return { events, acceptedAt: Date.now() }
}
-/** The batch's side effects are durably done and it was acked to the consumer. */
-export function batchProcessed(batch: AcceptedBatch): void {
+/** The batch's side effects are durably done and it was acked to the consumer, with `processed` of its events finished. */
+export function batchProcessed(acceptedAt: number, processed: number): void {
batchesProcessed.inc()
- messagesProcessed.inc(batch.events)
- batchProcessingDuration.observe(Date.now() - batch.acceptedAt)
+ messagesProcessed.inc(processed)
+ batchProcessingDuration.observe(Date.now() - acceptedAt)
}
export function batchFailed(): void {
diff --git a/nodejs/src/ingestion/api/grpc-server.test.ts b/nodejs/src/ingestion/api/grpc-server.test.ts
index dfed97e997f9..fcef673cc447 100644
--- a/nodejs/src/ingestion/api/grpc-server.test.ts
+++ b/nodejs/src/ingestion/api/grpc-server.test.ts
@@ -14,7 +14,7 @@ import {
import { FeedResult } from '~/ingestion/framework/batching-pipeline'
import { FeedOrderSentinel } from './feed-order-sentinel'
-import { CompletedSubBatch, StreamIngestDriver, WorkerIngestServer } from './grpc-server'
+import { CompletedSubBatch, StreamIngestDriver, SubBatchBudget, WorkerIngestServer } from './grpc-server'
class Deferred<T> {
resolve!: (value: T) => void
@@ -66,14 +66,25 @@ class FrameSource implements AsyncIterable<IngestStreamRequest> {
/** Records feeds and lets the test hand-complete batches. */
class FakeDriver implements StreamIngestDriver {
- feeds: { streamId: number; seq: number; offsets: number[] }[] = []
+ feeds: { streamId: number; seq: number; offsets: number[]; partitions: number[]; budget: SubBatchBudget }[] = []
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) })
+ feed(
+ streamId: number,
+ seq: number,
+ messages: { partition: number; offset: number }[],
+ budget: SubBatchBudget
+ ): Promise<FeedResult> {
+ this.feeds.push({
+ streamId,
+ seq,
+ offsets: messages.map((m) => m.offset),
+ partitions: messages.map((m) => m.partition),
+ budget,
+ })
return Promise.resolve(this.feedResult)
}
@@ -89,8 +100,11 @@ class FakeDriver implements StreamIngestDriver {
return waiter.promise
}
- complete(batch: Omit<CompletedSubBatch, 'settled'>, settled: Promise<void> = Promise.resolve()): void {
- const completed: CompletedSubBatch = { ...batch, settled }
+ complete(
+ batch: Omit<CompletedSubBatch, 'settled' | 'unfinished'> & Partial<Pick<CompletedSubBatch, 'unfinished'>>,
+ settled: Promise<void> = Promise.resolve()
+ ): void {
+ const completed: CompletedSubBatch = { unfinished: [], ...batch, settled }
const waiter = this.nextWaiters.shift()
if (waiter) {
waiter.resolve(completed)
@@ -123,7 +137,12 @@ function hello(overrides: { consumerId?: string; streamEpoch?: bigint } = {}): I
function subBatch(
seq: number,
offsets: number[],
- overrides: { replay?: boolean; assignmentEpoch?: bigint } = {}
+ overrides: {
+ replay?: boolean
+ assignmentEpoch?: bigint
+ softBudgetMs?: bigint
+ partition?: number
+ } = {}
): IngestStreamRequest {
return create(IngestStreamRequestSchema, {
msg: {
@@ -133,10 +152,11 @@ function subBatch(
batchId: `batch-${seq}`,
replay: overrides.replay ?? false,
assignmentEpoch: overrides.assignmentEpoch ?? 1n,
+ softBudgetMs: overrides.softBudgetMs ?? 0n,
messages: offsets.map((offset) =>
create(KafkaMessageSchema, {
topic: 'events',
- partition: 0,
+ partition: overrides.partition ?? 0,
offset: BigInt(offset),
timestamp: 0n,
key: 'k',
@@ -262,6 +282,7 @@ describe('WorkerIngestServer', () => {
[2, SubBatchStatus.OK, 1],
[1, SubBatchStatus.OK, 2],
])
+ expect(collected.acks.every((ack) => ack.unfinished.length === 0)).toBe(true)
expect(server.streamCount).toBe(0)
})
@@ -348,6 +369,26 @@ describe('WorkerIngestServer', () => {
expect(driver.feeds).toEqual([])
})
+ it('arms the frame budget at read time, before the sub-batch waits for admission', async () => {
+ const source = new FrameSource()
+ const collected = collect(server, source)
+
+ const before = Date.now()
+ source.push(hello())
+ source.push(subBatch(1, [10], { softBudgetMs: 300n }))
+ await until(() => driver.feeds.length === 1)
+ const after = Date.now()
+
+ const { budget } = driver.feeds[0]
+ expect(budget.softBudgetMs).toBe(300)
+ expect(budget.armedAt).toBeGreaterThanOrEqual(before)
+ expect(budget.armedAt).toBeLessThanOrEqual(after)
+
+ source.end()
+ driver.complete({ streamId: driver.feeds[0].streamId, seq: 1, accepted: 1 })
+ await collected.ended
+ })
+
it('fails the stream and reports fatal when the pipeline dies mid-batch', async () => {
const source = new FrameSource()
const collected = collect(server, source)
@@ -546,6 +587,79 @@ describe('WorkerIngestServer', () => {
expect(await outOfOrderCount()).toBe(before + 1)
})
+ it('acks PARTIAL with the dispositions of a batch whose elements did not all finish, once it settles', async () => {
+ const baselineMessages = await metricValue('ingestion_api_messages_processed_total')
+ const source = new FrameSource()
+ const collected = collect(server, source)
+
+ source.push(hello())
+ source.push(subBatch(1, [10, 11, 12, 13], { partition: 3 }))
+ source.push(subBatch(2, [14]))
+ await until(() => driver.feeds.length === 2)
+ const streamId = driver.feeds[0].streamId
+ // A non-zero partition, because every other test uses partition 0 and
+ // would not notice the server dropping or defaulting it on either leg.
+ expect(driver.feeds[0].partitions).toEqual([3, 3, 3, 3])
+
+ // The consumer commits what a PARTIAL ack accepts.
+ const settled = new Deferred<void>()
+ driver.complete({ streamId, seq: 1, accepted: 3, unfinished: [{ partition: 3, offset: 11 }] }, settled.promise)
+ driver.complete({ streamId, seq: 2, accepted: 1 })
+ await until(() => collected.acks.length >= 1)
+ expect(collected.acks.map((ack) => ack.seq)).toEqual([2n])
+
+ settled.resolve()
+ await until(() => collected.acks.length >= 2)
+ source.end()
+ await collected.ended
+
+ expect(collected.acks.map((ack) => ack.seq)).toEqual([2n, 1n])
+ const ack = collected.acks[1]
+ expect(ack.status).toBe(SubBatchStatus.PARTIAL)
+ expect(ack.unfinished).toMatchObject([{ partition: 3, offset: 11n }])
+ expect(ack.accepted + ack.unfinished.length).toBe(4)
+ expect(await metricValue('ingestion_api_messages_processed_total')).toBe(
+ baselineMessages + collected.acks.reduce((sum, { accepted }) => sum + accepted, 0)
+ )
+ })
+
+ it('acks a parked sub-batch PARTIAL when its soft budget runs out before a slot frees', async () => {
+ const budgeted = new WorkerIngestServer(
+ { port: 0, maxConcurrentBatches: 1, capacityRetryMs: 1, pumpIdleMs: 1 },
+ { driver, feedOrderSentinel: sentinel, onFatal }
+ )
+ await budgeted.start()
+ try {
+ const source = new FrameSource()
+ const collected = collect(budgeted, source)
+
+ source.push(hello())
+ source.push(subBatch(1, [10]))
+ await until(() => driver.feeds.length === 1)
+ // The one slot is held by sub-batch 1, so sub-batch 2 parks.
+ source.push(subBatch(2, [11, 12], { softBudgetMs: 20n }))
+ await until(() => collected.acks.length === 1)
+
+ const ack = collected.acks[0]
+ expect(ack.seq).toBe(2n)
+ expect(ack.status).toBe(SubBatchStatus.PARTIAL)
+ expect(ack.accepted).toBe(0)
+ expect(ack.unfinished).toMatchObject([
+ { partition: 0, offset: 11n },
+ { partition: 0, offset: 12n },
+ ])
+ expect(driver.feeds.map((feed) => feed.seq)).toEqual([1])
+
+ // The stream stays usable: the reader moved on to the next frame.
+ driver.complete({ streamId: driver.feeds[0].streamId, seq: 1, accepted: 1 })
+ source.end()
+ await collected.ended
+ expect(collected.error).toBeNull()
+ } finally {
+ await budgeted.stop()
+ }
+ })
+
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
diff --git a/nodejs/src/ingestion/api/grpc-server.ts b/nodejs/src/ingestion/api/grpc-server.ts
index f61ca1110129..4c240cbe1342 100644
--- a/nodejs/src/ingestion/api/grpc-server.ts
+++ b/nodejs/src/ingestion/api/grpc-server.ts
@@ -9,6 +9,7 @@ import {
IngestStreamResponse,
IngestStreamResponseSchema,
KafkaMessage,
+ MessageRefSchema,
StreamHello,
StreamReadySchema,
SubBatchAckSchema,
@@ -16,6 +17,7 @@ import {
WorkerIngest,
} from '~/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb'
import { logger } from '~/common/utils/logger'
+import { budgetDeadline } from '~/ingestion/framework/batch-budget'
import { FeedResult } from '~/ingestion/framework/batching-pipeline'
import { AcceptedBatch, batchAccepted, batchFailed, batchProcessed, batchReleased } from './batch-metrics'
@@ -54,17 +56,25 @@ const grpcCapacityRetries = new Counter({
help: 'Feeds rejected at_capacity despite holding an admission slot (capacity accounting drift)',
})
+const grpcAdmissionExpired = new Counter({
+ name: 'ingestion_api_grpc_admission_expired_total',
+ help: 'Sub-batches whose soft deadline passed while they waited for an admission slot',
+})
+
const grpcConnectionsRejected = new Counter({
name: 'ingestion_api_grpc_connections_rejected_total',
help: 'Sessions or streams refused because a concurrency cap was hit',
labelNames: ['reason'],
})
+export type MessageCoordinates = Pick<SerializedKafkaMessage, 'partition' | 'offset'>
+
/** A batch the pipeline finished processing. */
export interface CompletedSubBatch {
streamId: number
seq: number
accepted: number
+ unfinished: MessageCoordinates[]
/**
* Resolves when the batch's side effects are durably done — the ack
* barrier. Kept as a promise (not awaited inside `next()`) so the pump
@@ -74,6 +84,13 @@ export interface CompletedSubBatch {
settled: Promise<void>
}
+export interface SubBatchBudget {
+ /** Epoch milliseconds at frame read, so the wait for an admission slot counts. */
+ armedAt: number
+ /** `0` means no deadline. */
+ softBudgetMs: number
+}
+
/**
* Pipeline mechanics behind the stream protocol. The server owns ordering,
* acks, capacity admission, and stream lifecycle; the driver owns how a
@@ -81,7 +98,7 @@ export interface CompletedSubBatch {
* done (`settled`).
*/
export interface StreamIngestDriver {
- feed(streamId: number, seq: number, messages: SerializedKafkaMessage[]): Promise<FeedResult>
+ feed(streamId: number, seq: number, messages: SerializedKafkaMessage[], budget: SubBatchBudget): Promise<FeedResult>
next(): Promise<CompletedSubBatch | null>
}
@@ -300,6 +317,22 @@ function okAck(seq: number, accepted: number): IngestStreamResponse {
})
}
+function partialAck(seq: number, accepted: number, unfinished: MessageCoordinates[]): IngestStreamResponse {
+ return create(IngestStreamResponseSchema, {
+ msg: {
+ case: 'ack',
+ value: create(SubBatchAckSchema, {
+ seq: BigInt(seq),
+ status: SubBatchStatus.PARTIAL,
+ accepted,
+ unfinished: unfinished.map(({ partition, offset }) =>
+ create(MessageRefSchema, { partition, offset: BigInt(offset) })
+ ),
+ }),
+ },
+ })
+}
+
function failedAck(seq: number, error: string): IngestStreamResponse {
return create(IngestStreamResponseSchema, {
msg: {
@@ -572,7 +605,7 @@ export class WorkerIngestServer {
}
this.acceptedBatches.delete(key)
if (outcome === 'ok') {
- batchProcessed(accepted)
+ batchProcessed(accepted.acceptedAt, completed.accepted)
} else {
batchFailed()
}
@@ -587,12 +620,25 @@ export class WorkerIngestServer {
return
}
stream.inFlight.delete(completed.seq)
- stream.acks.push(okAck(completed.seq, completed.accepted))
- grpcSubBatches.inc({ status: 'ok' })
+ if (completed.unfinished.length > 0) {
+ stream.acks.push(partialAck(completed.seq, completed.accepted, completed.unfinished))
+ grpcSubBatches.inc({ status: 'partial' })
+ } else {
+ stream.acks.push(okAck(completed.seq, completed.accepted))
+ grpcSubBatches.inc({ status: 'ok' })
+ }
grpcMessagesProcessed.inc(completed.accepted)
this.maybeFinish(stream)
}
+ private expireParked(stream: StreamState, seq: number, messages: SerializedKafkaMessage[]): void {
+ grpcAdmissionExpired.inc()
+ stream.inFlight.delete(seq)
+ stream.acks.push(partialAck(seq, 0, messages))
+ grpcSubBatches.inc({ status: 'partial' })
+ this.maybeFinish(stream)
+ }
+
private maybeFinish(stream: StreamState): void {
if (stream.readerDone && stream.inFlight.size === 0) {
stream.acks.end()
@@ -703,6 +749,10 @@ export class WorkerIngestServer {
}
const subBatch = request.msg.value
+ const budget: SubBatchBudget = {
+ armedAt: Date.now(),
+ softBudgetMs: Number(subBatch.softBudgetMs),
+ }
const seq = Number(subBatch.seq)
if (seq !== stream.nextSeq) {
throw this.protocolError(
@@ -735,14 +785,28 @@ export class WorkerIngestServer {
// order because a retry race here let busy streams starve
// quiet ones, wedging whole consumers.
stream.inFlight.add(seq)
+ // A sub-batch that spends its whole allowance waiting here is given up, not started.
+ const softAt = budgetDeadline(budget.armedAt, budget.softBudgetMs)
+ const parkedTooLong = new AbortController()
+ const expiryTimer =
+ softAt === null ? null : setTimeout(() => parkedTooLong.abort(), Math.max(0, softAt - Date.now()))
+ expiryTimer?.unref?.()
try {
- await this.slots.acquire(admissionSignal)
+ await this.slots.acquire(AbortSignal.any([admissionSignal, parkedTooLong.signal]))
} catch (error) {
if (error instanceof SlotAcquisitionAborted) {
+ if (parkedTooLong.signal.aborted && !admissionSignal.aborted) {
+ this.expireParked(stream, seq, serialized)
+ continue
+ }
this.finishReader(stream, seq)
return
}
throw error
+ } finally {
+ if (expiryTimer) {
+ clearTimeout(expiryTimer)
+ }
}
if (signal?.aborted) {
// Cancelled between the slot grant and here: hand the slot
@@ -757,7 +821,7 @@ export class WorkerIngestServer {
this.finishReader(stream, seq)
return
}
- const result = await this.feedGuarded(stream, seq, serialized)
+ const result = await this.feedGuarded(stream, seq, serialized, budget)
if (result.ok) {
feedAccepted = true
this.acceptedBatches.set(this.acceptedKey(stream.id, seq), batchAccepted(serialized.length))
@@ -798,10 +862,11 @@ export class WorkerIngestServer {
private async feedGuarded(
stream: StreamState,
seq: number,
- messages: SerializedKafkaMessage[]
+ messages: SerializedKafkaMessage[],
+ budget: SubBatchBudget
): Promise<FeedResult> {
try {
- return await this.deps.driver.feed(stream.id, seq, messages)
+ return await this.deps.driver.feed(stream.id, seq, messages, budget)
} catch (error) {
this.fatal(error instanceof Error ? error : new Error(String(error)))
throw new ConnectError('ingest pipeline failed', Code.Internal)
diff --git a/nodejs/src/ingestion/framework/base-chunk-pipeline.test.ts b/nodejs/src/ingestion/framework/base-chunk-pipeline.test.ts
index c6784d9c3be0..4afc8d5fe84d 100644
--- a/nodejs/src/ingestion/framework/base-chunk-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/base-chunk-pipeline.test.ts
@@ -4,6 +4,7 @@ import { logger } from '~/common/utils/logger'
import { createMockPipeline } from '~/tests/helpers/mock-pipeline'
import { BaseChunkPipeline } from './base-chunk-pipeline'
+import { BatchBudget } from './batch-budget'
import {
aggregateKafkaDebugContexts,
createBatch,
@@ -12,7 +13,9 @@ import {
createNewChunkPipeline,
createOkContext,
} from './helpers'
-import { dlq, drop, ok } from './results'
+import { batchBudgetCheckpointCounter } from './metrics'
+import { getBudgetCheckpoints } from './metrics.test-utils'
+import { dlq, drop, isTimeoutResult, ok } from './results'
jest.mock('~/common/utils/logger', () => ({
logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
@@ -33,7 +36,35 @@ function createTestMessage(overrides: Partial<Message> = {}): Message {
}
describe('BaseChunkPipeline', () => {
+ beforeEach(() => {
+ batchBudgetCheckpointCounter.reset()
+ })
+
describe('basic functionality', () => {
+ it('times out the exhausted elements of a mixed-budget chunk and runs the step on the rest', async () => {
+ const exhausted = BatchBudget.softDeadline(Date.now() - 1)
+ const healthy = BatchBudget.softDeadline(Date.now() + 5000)
+ let seen: { id: number }[] = []
+
+ const rootPipeline = createNewChunkPipeline<{ id: number }, { budget: BatchBudget }>().build()
+ const pipeline = new BaseChunkPipeline(function enrichChunk(items: { id: number }[]) {
+ seen = items
+ return Promise.resolve(items.map((item) => ok({ id: item.id * 10 })))
+ }, rootPipeline)
+
+ pipeline.feed([
+ createOkContext({ id: 1 }, { budget: exhausted }),
+ createOkContext({ id: 2 }, { budget: healthy }),
+ ])
+ const results = await pipeline.next()
+
+ expect(seen).toEqual([{ id: 2 }])
+ expect(isTimeoutResult(results![0].result)).toBe(true)
+ expect((results![0].result as { reason: string }).reason).toBe('budget exceeded before enrichChunk')
+ expect(results![1].result).toEqual(ok({ id: 20 }))
+ expect(await getBudgetCheckpoints('chunk', 'enrichChunk')).toBe(1)
+ })
+
it('should process batch through pipeline', async () => {
const messages: Message[] = [
createTestMessage({ value: Buffer.from('test1'), offset: 1 }),
diff --git a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
index f1a52473c71e..94960094dfed 100644
--- a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
+++ b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
@@ -4,9 +4,9 @@ import { instrumentFn, startDetachedSpan } from '~/common/tracing/tracing-utils'
import { logger } from '~/common/utils/logger'
import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'
-import { pipelineStepDurationHistogram } from './metrics'
+import { pipelineStepDurationHistogram, recordBudgetCheckpoint } from './metrics'
import { PipelineBuilderContext, PipelineResultWithContext } from './pipeline.interface'
-import { PipelineResult, PipelineResultOk, isOkResult } from './results'
+import { PipelineResult, PipelineResultOk, isOkResult, timeout } from './results'
/**
* Type guard for ResultWithContext that asserts the result is successful
@@ -42,6 +42,9 @@ export type ChunkProcessingStep<T, U, R extends string = never> = (values: T[])
* warnings). Non-OK results pass through unchanged. This is the single
* implementation of chunk-step semantics, shared by {@link BaseChunkPipeline}
* and the group-level pipeChunk in ConcurrentlyGroupingChunkPipeline.
+ *
+ * The budget checkpoint runs per element, because one chunk can hold elements
+ * from batches with different budgets.
*/
export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends string, RStep extends string, D = unknown>(
step: ChunkProcessingStep<TIn, TOut, RStep>,
@@ -49,8 +52,25 @@ export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends string
items: PipelineResultWithContext<TIn, C, RPrev>[],
builderContext?: PipelineBuilderContext<D>
): Promise<PipelineResultWithContext<TOut, C, RPrev | RStep>[]> {
- const successfulItems = items.filter(isSuccessResultWithContext)
- const successfulValues = successfulItems.map((resultWithContext) => resultWithContext.result.value)
+ const successfulItems: PipelineResultWithContext<TIn, C, RPrev>[] = []
+ const successfulValues: TIn[] = []
+ // Stays null unless the budget cuts something off, so the common path allocates nothing.
+ let budgetCutOff: Set<number> | null = null
+ for (let index = 0; index < items.length; index++) {
+ const item = items[index]
+ if (!isOkResult(item.result)) {
+ continue
+ }
+ const budget = item.context.budget
+ if (budget?.exhausted) {
+ recordBudgetCheckpoint('chunk', stepName)
+ budgetCutOff ??= new Set<number>()
+ budgetCutOff.add(index)
+ continue
+ }
+ successfulItems.push(item)
+ successfulValues.push(item.result.value)
+ }
let stepResults: PipelineResult<TOut, RStep>[] = []
if (successfulValues.length > 0) {
@@ -101,8 +121,14 @@ export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends string
// Map results back, preserving context and non-successful results
const output: PipelineResultWithContext<TOut, C, RPrev | RStep>[] = []
- for (const resultWithContext of items) {
- if (isOkResult(resultWithContext.result)) {
+ for (let index = 0; index < items.length; index++) {
+ const resultWithContext = items[index]
+ if (budgetCutOff?.has(index)) {
+ output.push({
+ result: timeout(`budget exceeded before ${stepName}`),
+ context: resultWithContext.context,
+ })
+ } else if (isOkResult(resultWithContext.result)) {
const stepResult = stepResults[stepIndex++]
output.push({
result: stepResult,
diff --git a/nodejs/src/ingestion/framework/batch-budget.test.ts b/nodejs/src/ingestion/framework/batch-budget.test.ts
new file mode 100644
index 000000000000..5c499315c503
--- /dev/null
+++ b/nodejs/src/ingestion/framework/batch-budget.test.ts
@@ -0,0 +1,52 @@
+import { BatchBudget } from './batch-budget'
+
+describe('BatchBudget', () => {
+ beforeEach(() => {
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('shares one unlimited budget that never exhausts', () => {
+ const budget = BatchBudget.unlimited()
+
+ expect(budget).toBe(BatchBudget.unlimited())
+ expect(budget.softAt).toBe(Infinity)
+ expect(budget.exhausted).toBe(false)
+
+ jest.advanceTimersByTime(60_000)
+
+ expect(budget.exhausted).toBe(false)
+ })
+
+ // setSystemTime moves the clock without running timers, as a synchronous step that holds the event loop does.
+ it('exhausts at the soft deadline even when no timer has run', () => {
+ const now = Date.now()
+ const budget = BatchBudget.softDeadline(now + 1000)
+
+ jest.setSystemTime(now + 999)
+ expect(budget.exhausted).toBe(false)
+
+ jest.setSystemTime(now + 1000)
+ expect(budget.exhausted).toBe(true)
+ })
+
+ it('stays exhausted when the wall clock steps back', () => {
+ const now = Date.now()
+ const budget = BatchBudget.softDeadline(now + 1000)
+
+ jest.setSystemTime(now + 1000)
+ expect(budget.exhausted).toBe(true)
+
+ jest.setSystemTime(now)
+ expect(budget.exhausted).toBe(true)
+ })
+
+ it('is exhausted straight away when its deadline has already passed', () => {
+ const budget = BatchBudget.softDeadline(Date.now() - 1)
+
+ expect(budget.exhausted).toBe(true)
+ })
+})
diff --git a/nodejs/src/ingestion/framework/batch-budget.ts b/nodejs/src/ingestion/framework/batch-budget.ts
new file mode 100644
index 000000000000..2b3a1881ebec
--- /dev/null
+++ b/nodejs/src/ingestion/framework/batch-budget.ts
@@ -0,0 +1,43 @@
+/**
+ * A fed batch's soft deadline. Past it the framework stops starting steps, but
+ * it never interrupts a running one: the consumer's ack watchdog is the hard
+ * limit.
+ */
+export class BatchBudget {
+ private static readonly UNLIMITED = new BatchBudget(Infinity)
+
+ private expired = false
+
+ private constructor(
+ /** Epoch milliseconds, or `Infinity` for no deadline. */
+ readonly softAt: number
+ ) {}
+
+ static softDeadline(softAt: number): BatchBudget {
+ return new BatchBudget(softAt)
+ }
+
+ static unlimited(): BatchBudget {
+ return BatchBudget.UNLIMITED
+ }
+
+ // Reads the clock rather than a timer flag: synchronous steps can hold the
+ // event loop past the deadline, and a timer flag would then let a late
+ // element through the timeout barrier. The flag stays set, so a wall-clock
+ // step backwards cannot restart a cut-off group.
+ get exhausted(): boolean {
+ if (!this.expired && this.softAt !== Infinity) {
+ this.expired = Date.now() >= this.softAt
+ }
+ return this.expired
+ }
+}
+
+// The server arms its admission park timer with the allowance. Node fires a
+// longer timer after 1 ms, so a longer allowance would expire at once.
+const MAX_TIMER_DELAY_MS = 2 ** 31 - 1
+
+// Allowances arrive as durations, so the sender's clock never enters the arithmetic.
+export function budgetDeadline(armedAt: number, budgetMs: number): number | null {
+ return budgetMs === 0 || budgetMs > MAX_TIMER_DELAY_MS ? null : armedAt + budgetMs
+}
diff --git a/nodejs/src/ingestion/framework/batching-pipeline.test.ts b/nodejs/src/ingestion/framework/batching-pipeline.test.ts
index 1d8d98781454..4fb1f89019f4 100644
--- a/nodejs/src/ingestion/framework/batching-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/batching-pipeline.test.ts
@@ -2,11 +2,14 @@ import { context, propagation, trace } from '@opentelemetry/api'
import { InMemorySpanExporter, NodeTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node'
import { Message } from 'node-rdkafka'
+import { BatchBudget } from './batch-budget'
import { BatchingPipeline } from './batching-pipeline'
import { newBatchingPipeline } from './builders/helpers'
import { OkResultWithContext } from './chunk-pipeline.interface'
+import { batchBudgetExhaustedCounter } from './metrics'
+import { getBudgetsExhausted } from './metrics.test-utils'
import { PipelineResultWithContext } from './pipeline.interface'
-import { ok } from './results'
+import { PipelineResultType, ok } from './results'
type MsgCtx = { message: Message }
function makeMessage(offset: number): Message {
@@ -76,6 +79,49 @@ describe('BatchingPipeline', () => {
return { allResults, allSideEffects }
}
+ it('stamps the fed budget on every element of that batch', async () => {
+ const first = BatchBudget.softDeadline(Date.now() + 60_000)
+ const second = BatchBudget.softDeadline(Date.now() + 60_000)
+ const collector = createCollector()
+
+ await collector.feed(makeBatch([1, 2]), {}, first)
+ await collector.feed(makeBatch([3]), {}, second)
+ const { allResults } = await drainAll(collector)
+
+ expect(allResults.map((result) => result.context.budget)).toEqual([first, first, second])
+ })
+
+ it('leaves a batch unlimited when feed() is given no budget', async () => {
+ const collector = createCollector()
+
+ await collector.feed(makeBatch([1]), {})
+ const { allResults } = await drainAll(collector)
+
+ expect(allResults[0].context.budget).toBe(BatchBudget.unlimited())
+ })
+
+ it.each([
+ ['before the batch started', -10, 0],
+ ['while afterBatch flushed', 500, 1_000],
+ ])('counts a budget that expired %s', async (_when, deadlineInMs, flushMs) => {
+ jest.useFakeTimers()
+ try {
+ batchBudgetExhaustedCounter.reset()
+ afterBatchStep.mockImplementation((input) => {
+ jest.setSystemTime(Date.now() + flushMs)
+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))
+ })
+ const collector = createCollector()
+
+ await collector.feed(makeBatch([1]), {}, BatchBudget.softDeadline(Date.now() + deadlineInMs))
+ await drainAll(collector)
+
+ expect(await getBudgetsExhausted()).toBe(1)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
it('returns null when sub-pipeline is empty', async () => {
const collector = createCollector()
expect(await collector.next()).toBeNull()
@@ -192,6 +238,62 @@ describe('BatchingPipeline', () => {
expect(order).toEqual(['next-called', 'callback-start', 'callback-end', 'next-resolved'])
})
+ it('runs afterBatch to completion with unchanged results when the budget expires mid-batch', async () => {
+ jest.useFakeTimers()
+ try {
+ const order: string[] = []
+ let releaseAfter!: () => void
+ const gate = new Promise<void>((resolve) => (releaseAfter = resolve))
+ afterBatchStep.mockImplementation(async (input: any) => {
+ order.push('after-start')
+ await gate
+ order.push('after-end')
+ return ok({ elements: input.elements, batchContext: input.batchContext })
+ })
+
+ const processed: string[] = []
+ function processStep(value: { value: string }) {
+ processed.push(value.value)
+ if (value.value === 'msg-2') {
+ jest.advanceTimersByTime(10_000)
+ }
+ return Promise.resolve(ok(value))
+ }
+ const collector = newBatchingPipeline<any, any, MsgCtx>(
+ (builder) => builder.pipe(beforeBatchStep),
+ (builder) => builder.sequentially((b) => b.pipe(processStep)),
+ (builder) => builder.pipe(afterBatchStep),
+ { concurrentBatches: Infinity }
+ )
+
+ await collector.feed(makeBatch([1, 2, 3]), {}, BatchBudget.softDeadline(Date.now() + 5_000))
+ const pendingNext = collector.next().then((batch) => {
+ order.push('next-resolved')
+ return batch
+ })
+ for (let i = 0; i < 100 && !order.includes('after-start'); i++) {
+ await Promise.resolve()
+ }
+ expect(order).toContain('after-start')
+ expect(order).not.toContain('next-resolved')
+
+ releaseAfter()
+ const batch = await pendingNext
+
+ expect(order).toEqual(['after-start', 'after-end', 'next-resolved'])
+ // msg-2 started before expiry, so its result stands.
+ expect(processed).toEqual(['msg-1', 'msg-2'])
+ expect(batch!.elements.map((element) => element.result.type)).toEqual([
+ PipelineResultType.OK,
+ PipelineResultType.OK,
+ PipelineResultType.TIMEOUT,
+ ])
+ expect(afterBatchStep).toHaveBeenCalledTimes(1)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
describe('with streaming sub-pipeline', () => {
it('blocks until a batch completes', async () => {
const collector = createStreamingCollector()
diff --git a/nodejs/src/ingestion/framework/batching-pipeline.ts b/nodejs/src/ingestion/framework/batching-pipeline.ts
index 378440b69e9a..fd9f4249da5e 100644
--- a/nodejs/src/ingestion/framework/batching-pipeline.ts
+++ b/nodejs/src/ingestion/framework/batching-pipeline.ts
@@ -2,8 +2,10 @@ import pLimit from 'p-limit'
import { DetachedSpan, runInContext, startDetachedSpan } from '~/common/tracing/tracing-utils'
+import { BatchBudget } from './batch-budget'
import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'
import { createOkContext } from './helpers'
+import { batchBudgetExhaustedCounter, batchBudgetOverrunHistogram } from './metrics'
import { Pipeline, PipelineResultWithContext } from './pipeline.interface'
import { PipelineResult, isOkResult } from './results'
@@ -13,6 +15,7 @@ export type FeedResult = { ok: true } | { ok: false; kind: FeedRejectionKind; re
export interface BatchingContext {
messageId: number
+ budget: BatchBudget
}
export interface BeforeBatchInput<TInput, CInput, CBatch = Record<never, object>> {
@@ -71,8 +74,19 @@ const BATCHING_PIPELINE_DEFAULTS: BatchingPipelineOptions = {
concurrentBatches: 1,
}
+// The overrun is the tail the checkpoints cannot cut, because they only stop work from starting.
+// It includes afterBatch, which flushes the batch's writes before the batch can be acked.
+function recordBudgetOverrun(budget: BatchBudget): void {
+ if (!budget.exhausted) {
+ return
+ }
+ batchBudgetExhaustedCounter.inc()
+ batchBudgetOverrunHistogram.observe(Math.max(0, Date.now() - budget.softAt) / 1000)
+}
+
interface TrackedBatch<TOutput, CBatch, COutput, R extends string = never, CFeed extends object = object> {
batchContext: CBatch & CFeed & { batchId: number }
+ budget: BatchBudget
messageIds: number[]
inflight: Set<number>
results: Map<number, PipelineResultWithContext<TOutput, COutput, R>>
@@ -94,7 +108,7 @@ interface TrackedBatch<TOutput, CBatch, COutput, R extends string = never, CFeed
* registered and no hooks run (a zero-message batch could never complete).
* - feed() runs beforeBatch which returns enriched elements (same count as
* fed — count changes throw) and side effects. Elements are tagged with
- * messageId, then fed to the sub-pipeline.
+ * messageId and the batch's budget, then fed to the sub-pipeline.
* - next() collects results. When all messages in a batch complete, calls
* afterBatch with the batchContext and ordered results, then returns a
* BatchResult with concatenated side effects.
@@ -174,18 +188,23 @@ export class BatchingPipeline<
this.options = { ...BATCHING_PIPELINE_DEFAULTS, ...options }
}
- feed(elements: OkResultWithContext<TInput, CInput>[], batchContext: CFeed): Promise<FeedResult> {
+ feed(
+ elements: OkResultWithContext<TInput, CInput>[],
+ batchContext: CFeed,
+ budget: BatchBudget = BatchBudget.unlimited()
+ ): 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, batchContext))
+ return this.feedLimit(() => this.feedSerialized(elements, batchContext, budget))
}
private async feedSerialized(
elements: OkResultWithContext<TInput, CInput>[],
- feedContext: CFeed
+ feedContext: CFeed,
+ budget: BatchBudget
): 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
@@ -266,6 +285,7 @@ export class BatchingPipeline<
...element.context,
messageId,
traceContext: batchTrace?.parentContext,
+ budget,
},
}
})
@@ -278,6 +298,7 @@ export class BatchingPipeline<
// drop it.
this.batches.set(batchId, {
batchContext: { ...batchContext, ...feedContext },
+ budget,
messageIds,
inflight,
results: new Map(),
@@ -374,6 +395,7 @@ export class BatchingPipeline<
const afterResult = await runInContext(batch.trace?.parentContext, () =>
this.afterPipeline.process(createOkContext(afterInput, {}))
).finally(() => batch.trace?.span.end())
+ recordBudgetOverrun(batch.budget)
if (!isOkResult(afterResult.result)) {
throw new Error(`batching_pipeline afterBatch hook returned non-ok result for batch ${batchId}`)
diff --git a/nodejs/src/ingestion/framework/builders/pipeline-builders.ts b/nodejs/src/ingestion/framework/builders/pipeline-builders.ts
index 0130265fb0e2..71d130f809a8 100644
--- a/nodejs/src/ingestion/framework/builders/pipeline-builders.ts
+++ b/nodejs/src/ingestion/framework/builders/pipeline-builders.ts
@@ -9,6 +9,7 @@ import {
import { StartPipeline } from '~/ingestion/framework/start-pipeline'
import { StepPipeline } from '~/ingestion/framework/step-pipeline'
import { ProcessingStep } from '~/ingestion/framework/steps'
+import { TimeoutBarrierPipeline } from '~/ingestion/framework/timeout-barrier-pipeline'
export class StartPipelineBuilder<T, C> {
pipe<U, R extends string = never>(
@@ -59,6 +60,11 @@ export class PipelineBuilder<TInput, TOutput, C, R extends string = never> {
return new PipelineBuilder(finalBuilder.build())
}
+ /** Past this point the budget no longer stops an element. See {@link TimeoutBarrierPipeline}. */
+ timeoutBarrier(): PipelineBuilder<TInput, TOutput, C, R> {
+ return new PipelineBuilder(new TimeoutBarrierPipeline(this.pipeline))
+ }
+
/**
* Schedule (or await) the side effects carried by this pipeline's results
* and clear them, so downstream consumers never have to drain them.
diff --git a/nodejs/src/ingestion/framework/docs/01-introduction.test.ts b/nodejs/src/ingestion/framework/docs/01-introduction.test.ts
index 8a9e2279ada2..346f57bb3550 100644
--- a/nodejs/src/ingestion/framework/docs/01-introduction.test.ts
+++ b/nodejs/src/ingestion/framework/docs/01-introduction.test.ts
@@ -305,7 +305,7 @@ describe('Pipeline Fundamentals', () => {
})
/**
- * Non-OK results (DLQ, DROP, REDIRECT) short-circuit the pipeline - they
+ * Non-OK results (DLQ, DROP, REDIRECT, TIMEOUT) short-circuit the pipeline - they
* skip all remaining steps. OK results continue to propagate through
* subsequent steps.
*/
diff --git a/nodejs/src/ingestion/framework/docs/02-chunk-pipelines.test.ts b/nodejs/src/ingestion/framework/docs/02-chunk-pipelines.test.ts
index ef69281bfb40..06954a7e27d1 100644
--- a/nodejs/src/ingestion/framework/docs/02-chunk-pipelines.test.ts
+++ b/nodejs/src/ingestion/framework/docs/02-chunk-pipelines.test.ts
@@ -151,7 +151,7 @@ describe('Cardinality Guarantee', () => {
describe('OK Filtering', () => {
/**
- * Chunk steps only receive OK items. Non-OK items (DLQ, DROP, REDIRECT)
+ * Chunk steps only receive OK items. Non-OK items (DLQ, DROP, REDIRECT, TIMEOUT)
* are automatically filtered out and preserved in the output.
*/
it('chunk steps receive only OK items from previous steps', async () => {
diff --git a/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts b/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts
index 60074f6280d4..567fc4d81027 100644
--- a/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts
+++ b/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts
@@ -1,9 +1,9 @@
/**
- * # Chapter 7: Result Handling (DLQ, DROP, REDIRECT)
+ * # Chapter 7: Result Handling (DLQ, DROP, REDIRECT, TIMEOUT)
*
* After processing items through pipeline steps, results need to be handled
* properly. OK results continue through the pipeline, but non-OK results
- * (DLQ, DROP, REDIRECT) require special handling.
+ * (DLQ, DROP, REDIRECT, TIMEOUT) require special handling.
*
* The `handleResults()` method processes non-OK results by converting them
* into appropriate side effects:
@@ -11,6 +11,7 @@
* - **DLQ**: Send to dead-letter topic with error details
* - **DROP**: Log and discard (no Kafka message)
* - **REDIRECT**: Send to a named output (e.g. overflow)
+ * - **TIMEOUT**: Nothing (the source redelivers the message, see chapter 18)
*
* ## Redirect Options
*
diff --git a/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts b/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts
index 7f68b6ec8700..094930c23816 100644
--- a/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts
+++ b/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts
@@ -33,7 +33,7 @@
* Most consumers do not want result-with-context objects; they want the plain
* output values. `ChunkPipelineUnwrapper` wraps a pipeline and, on `next()`,
* returns a flat `TOutput[]` of just the OK values - non-OK results (DLQ, DROP,
- * REDIRECT) are filtered out (they are assumed already handled by a
+ * REDIRECT, TIMEOUT) are filtered out (they are assumed already handled by a
* `handleResults()` stage upstream). It returns `null` when the underlying
* pipeline drains.
*
diff --git a/nodejs/src/ingestion/framework/docs/18-batch-budgets.test.ts b/nodejs/src/ingestion/framework/docs/18-batch-budgets.test.ts
new file mode 100644
index 000000000000..ca6ea716d073
--- /dev/null
+++ b/nodejs/src/ingestion/framework/docs/18-batch-budgets.test.ts
@@ -0,0 +1,422 @@
+/**
+ * # Chapter 18: Batch Time Budgets
+ *
+ * Steps have no time limits of their own. Without a budget, a batch that hits
+ * a slow spot runs as long as it runs, and time is enforced by the caller
+ * giving up: the caller re-routes the work to another worker while this one
+ * keeps processing the same messages. That is duplicate downstream work plus
+ * contention exactly where the pipeline was already slow.
+ *
+ * A budget inverts that. Each fed batch carries a time allowance, and the
+ * framework stops starting work once the allowance runs out.
+ *
+ * ## The budget object
+ *
+ * A budget enforces by virtue of existing. `BatchBudget` carries one absolute
+ * deadline, `softAt`, and the checkpoints read its `exhausted` flag. The flag
+ * compares the clock with the deadline on every read, so a checkpoint sees the
+ * deadline even while synchronous work holds the event loop, and once set it
+ * stays set. Past the deadline the framework stops starting
+ * work; work already running finishes. It is called soft because it never
+ * interrupts anything — a step that hangs forever is the consumer's ack
+ * watchdog to catch, and that watchdog is the only hard limit in the system.
+ *
+ * `BatchBudget.unlimited()` is the no-time-policy case, and the neutral
+ * element: it never exhausts, so every checkpoint is a no-op. Because it exists
+ * there is no "no budget" state, and no optional-budget branch anywhere in the
+ * framework.
+ *
+ * ## Where the budget comes from
+ *
+ * A budget belongs to one fed batch, so it rides the `feed()` call, and the
+ * batching pipeline of chapter 14 is the interface that takes one. It stamps
+ * the budget on every element of that batch, next to the messageId. The
+ * argument defaults to an unlimited budget, so a caller with no time policy
+ * passes nothing.
+ *
+ * ```ts
+ * await pipeline.feed(elements, batchContext, BatchBudget.softDeadline(deadline))
+ * await pipeline.feed(elements, batchContext) // unlimited
+ * ```
+ *
+ * ## The checkpoints
+ *
+ * Cancellation is cooperative. JavaScript cannot preempt a running `await`, so
+ * the framework never kills work; it stops dispatching it, at two checkpoints
+ * it owns. Steps see nothing of the budget, and no existing step changes:
+ *
+ * 1. **Before each step of an element.** An exhausted element completes as
+ * `timeout('budget exceeded before <step>')`, and the rest of its chain
+ * skips through the existing non-OK short-circuit.
+ * 2. **Before a chunk step.** One chunk can hold elements from several fed
+ * batches, each with its own budget, so the decision is per element:
+ * exhausted elements become timeouts and pass through, and the step runs on
+ * the remainder.
+ *
+ * Granularity is therefore one step. A step that runs long past the deadline
+ * is not interrupted, and the retry wrappers keep retrying to their configured
+ * limit, so the overrun a batch can accumulate is bounded by its slowest step
+ * rather than by the deadline. `ingestion_batch_budget_overrun_seconds`
+ * measures that tail.
+ *
+ * ## The timeout barrier
+ *
+ * Cutting an element is not always the cheaper choice. Once a step has written
+ * something a redelivery would have to repeat or reconcile — a person merge, a
+ * group write, an emitted event — finishing costs less than cutting.
+ * `.timeoutBarrier()` marks that line:
+ *
+ * ```ts
+ * builder.pipe(prepareStep).timeoutBarrier().pipe(writeStep).pipe(emitStep)
+ * ```
+ *
+ * It is the last checkpoint. An element that reaches it with time left carries
+ * an unlimited budget onward, so every later checkpoint is a no-op and that
+ * element is guaranteed to finish its chain; an element that reaches it with
+ * its budget already spent is cut there, with
+ * `timeout('budget exceeded before timeoutBarrier')`.
+ *
+ * Put the barrier before the first step whose side effects make finishing
+ * cheaper than redelivering. The trade is a longer tail past the deadline: a
+ * batch that runs out of time still finishes every element already past the
+ * barrier.
+ *
+ * ## The result a budget produces
+ *
+ * `TIMEOUT` is the only unacked result: the message is not acked, so its
+ * source redelivers it and the whole chain runs again from the top. Result
+ * handling counts it and produces nothing for it, because the redelivery
+ * produces it.
+ *
+ * The count invariant is untouched: N messages in, N results out, and
+ * `afterBatch` still runs, committing the writes of the events that did
+ * finish. Within one batch, budget exhaustion is monotone, so a group that
+ * runs its events one at a time completes a prefix of its feed order.
+ *
+ * The prefix holds per group, not per routing key. One routing key can span
+ * several groups, and then its cut-off events can sit between completed ones,
+ * so the caller must redeliver exactly the cut-off events. Only stages that run
+ * one element at a time keep the prefix: `concurrently` and fan-out/fan-in run
+ * elements in parallel, so a slow early element can be cut while a later one
+ * completes.
+ */
+import { BatchBudget } from '~/ingestion/framework/batch-budget'
+import { newBatchingPipeline } from '~/ingestion/framework/builders'
+import { createOkContext } from '~/ingestion/framework/helpers'
+import { PipelineResult, isOkResult, isTimeoutResult, ok } from '~/ingestion/framework/results'
+
+interface Event {
+ key: string
+ seq: number
+}
+
+type NoCtx = Record<string, never>
+
+/** Reads the result kinds in feed order, which is how a batch's elements come back. */
+function resultKinds<T>(results: { result: PipelineResult<T> }[]): string[] {
+ return results.map((element) => {
+ if (isOkResult(element.result)) {
+ return 'ok'
+ }
+ return isTimeoutResult(element.result) ? 'timeout' : 'other'
+ })
+}
+
+/** Reads the reason off each element the budget cut off, `null` for the rest. */
+function timeoutReasons<T>(results: { result: PipelineResult<T> }[]): (string | null)[] {
+ return results.map((element) => (isTimeoutResult(element.result) ? element.result.reason : null))
+}
+
+describe('Batch Time Budgets', () => {
+ // A budget reads the clock, so a case that needs its deadline to pass moves
+ // the fake clock rather than waiting for it.
+ beforeEach(() => {
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ /**
+ * The element checkpoint. A step that outlasts the batch's allowance is not
+ * cancelled, but the next step never starts: that element completes as a
+ * timeout naming the step it was cut off before. Every element the batch
+ * had not reached yet is cut off before its first step, and everything that
+ * finished before the deadline keeps its result.
+ */
+ it('stops each element at its next step once the budget is exhausted', async () => {
+ const ran: string[] = []
+
+ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(
+ (builder) =>
+ builder.pipe(function passThroughBefore(input) {
+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))
+ }),
+ (builder) =>
+ builder.sequentially((steps) =>
+ steps
+ .pipe(function enrichStep(event: Event) {
+ ran.push(`enrich-${event.seq}`)
+ if (event.seq === 2) {
+ // Stands in for this step outlasting what the batch had left.
+ jest.advanceTimersByTime(1000)
+ }
+ return Promise.resolve(ok(event))
+ })
+ .pipe(function emitStep(event: Event) {
+ ran.push(`emit-${event.seq}`)
+ return Promise.resolve(ok(event))
+ })
+ ),
+ (builder) =>
+ builder.pipe(function passThroughAfter(input) {
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: 1 }
+ )
+
+ await pipeline.feed(
+ [1, 2, 3].map((seq) => createOkContext<Event, NoCtx>({ key: 'a', seq }, {})),
+ {},
+ BatchBudget.softDeadline(Date.now() + 1000)
+ )
+ const batch = await pipeline.next()
+
+ // The first event finished; the second lost its budget mid-chain, so
+ // emitStep never ran for it or for the third.
+ expect(ran).toEqual(['enrich-1', 'emit-1', 'enrich-2'])
+ expect(resultKinds(batch!.elements)).toEqual(['ok', 'timeout', 'timeout'])
+ expect(timeoutReasons(batch!.elements)).toEqual([
+ null,
+ 'budget exceeded before emitStep',
+ 'budget exceeded before enrichStep',
+ ])
+ })
+
+ /**
+ * The chunk checkpoint. Batches run concurrently, so one chunk can hold
+ * elements from several of them, each with its own budget. The step runs
+ * for the elements whose batch still has time, and each batch's results
+ * reflect only its own budget.
+ */
+ it('runs a chunk step on the elements whose batch still has time', async () => {
+ const chunked: number[][] = []
+
+ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(
+ (builder) =>
+ builder.pipe(function passThroughBefore(input) {
+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))
+ }),
+ (builder) =>
+ builder.pipeChunk(function writeChunk(events: Event[]) {
+ chunked.push(events.map((event) => event.seq))
+ return Promise.resolve(events.map((event) => ok(event)))
+ }),
+ (builder) =>
+ builder.pipe(function passThroughAfter(input) {
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: 2 }
+ )
+
+ // Both batches are in flight before either drains, so their elements
+ // meet in one chunk.
+ await pipeline.feed(
+ [createOkContext<Event, NoCtx>({ key: 'a', seq: 1 }, {})],
+ {},
+ BatchBudget.softDeadline(Date.now() - 1)
+ )
+ await pipeline.feed(
+ [createOkContext<Event, NoCtx>({ key: 'b', seq: 2 }, {})],
+ {},
+ BatchBudget.softDeadline(Date.now() + 60_000)
+ )
+ const spentBatch = await pipeline.next()
+ const freshBatch = await pipeline.next()
+
+ // The step saw only the element whose batch still had time.
+ expect(chunked).toEqual([[2]])
+ expect(resultKinds(spentBatch!.elements)).toEqual(['timeout'])
+ expect(timeoutReasons(spentBatch!.elements)).toEqual(['budget exceeded before writeChunk'])
+ expect(resultKinds(freshBatch!.elements)).toEqual(['ok'])
+ })
+
+ /**
+ * The timeout barrier. An element that crosses it while the batch still
+ * has time finishes its remaining chain whatever the clock does next —
+ * here the write itself outlasts the allowance, and the emit that follows
+ * still runs. Elements that had not reached the barrier are cut at the
+ * ordinary checkpoint, so the budget still governs everything in front of
+ * it.
+ */
+ it('runs an element past the barrier to completion after the budget expires', async () => {
+ const ran: string[] = []
+
+ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(
+ (builder) =>
+ builder.pipe(function passThroughBefore(input) {
+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))
+ }),
+ (builder) =>
+ builder.sequentially((steps) =>
+ steps
+ .pipe(function prepareEvent(event: Event) {
+ ran.push(`prepare-${event.seq}`)
+ return Promise.resolve(ok(event))
+ })
+ .timeoutBarrier()
+ .pipe(function writePerson(event: Event) {
+ ran.push(`write-${event.seq}`)
+ // Stands in for the write outlasting what the batch had left.
+ jest.advanceTimersByTime(1000)
+ return Promise.resolve(ok(event))
+ })
+ .pipe(function emitEvent(event: Event) {
+ ran.push(`emit-${event.seq}`)
+ return Promise.resolve(ok(event))
+ })
+ ),
+ (builder) =>
+ builder.pipe(function passThroughAfter(input) {
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: 1 }
+ )
+
+ await pipeline.feed(
+ [1, 2].map((seq) => createOkContext<Event, NoCtx>({ key: 'a', seq }, {})),
+ {},
+ BatchBudget.softDeadline(Date.now() + 1000)
+ )
+ const batch = await pipeline.next()
+
+ expect(ran).toEqual(['prepare-1', 'write-1', 'emit-1'])
+ expect(resultKinds(batch!.elements)).toEqual(['ok', 'timeout'])
+ expect(timeoutReasons(batch!.elements)).toEqual([null, 'budget exceeded before prepareEvent'])
+ })
+
+ /**
+ * The count invariant under expiry. A budget that is already spent when the
+ * batch is fed cancels every element, and the batch still returns one
+ * result per message and still runs its afterBatch hook — which is what
+ * commits the writes of the events that did finish.
+ */
+ it('returns one result per message and still runs afterBatch when everything times out', async () => {
+ let flushedElements = 0
+
+ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(
+ (builder) =>
+ builder.pipe(function passThroughBefore(input) {
+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))
+ }),
+ (builder) =>
+ builder.sequentially((steps) =>
+ steps.pipe(function emitStep(event: Event) {
+ return Promise.resolve(ok(event))
+ })
+ ),
+ (builder) =>
+ builder.pipe(function flushBatch(input) {
+ flushedElements = input.elements.length
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: 1 }
+ )
+
+ await pipeline.feed(
+ [
+ { key: 'a', seq: 1 },
+ { key: 'a', seq: 2 },
+ { key: 'b', seq: 1 },
+ ].map((event) => createOkContext<Event, NoCtx>(event, {})),
+ {},
+ BatchBudget.softDeadline(Date.now() - 1)
+ )
+ const batch = await pipeline.next()
+
+ expect(batch!.elements).toHaveLength(3)
+ expect(resultKinds(batch!.elements)).toEqual(['timeout', 'timeout', 'timeout'])
+ expect(flushedElements).toBe(3)
+ })
+
+ /**
+ * The prefix property. Within one batch the budget expires once and never
+ * comes back, so a group that runs its events one at a time completes a
+ * prefix of its feed order. That is what makes redelivering the cut-off
+ * events safe: the redelivery resumes where the group stopped, with no gap
+ * in the middle.
+ */
+ it('completes a prefix of each group’s feed order', async () => {
+ const processed: number[] = []
+
+ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(
+ (builder) =>
+ builder.pipe(function passThroughBefore(input) {
+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))
+ }),
+ (builder) =>
+ builder.concurrentlyPerGroup(
+ (event: Event) => event.key,
+ (group) =>
+ group.sequentially((steps) =>
+ steps.pipe(function processStep(event: Event) {
+ processed.push(event.seq)
+ if (processed.length === 2) {
+ // Stands in for the second event exhausting the batch's time.
+ jest.advanceTimersByTime(1000)
+ }
+ return Promise.resolve(ok(event))
+ })
+ )
+ ),
+ (builder) =>
+ builder.pipe(function passThroughAfter(input) {
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: 1 }
+ )
+
+ await pipeline.feed(
+ [1, 2, 3, 4].map((seq) => createOkContext<Event, NoCtx>({ key: 'a', seq }, {})),
+ {},
+ BatchBudget.softDeadline(Date.now() + 1000)
+ )
+ const batch = await pipeline.next()
+
+ expect(processed).toEqual([1, 2])
+ expect(resultKinds(batch!.elements)).toEqual(['ok', 'ok', 'timeout', 'timeout'])
+ })
+
+ /**
+ * The neutral element. A caller with no time policy passes no budget at
+ * all, and nothing about the batch's behavior changes.
+ */
+ it('never cancels anything under the default unlimited budget', async () => {
+ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(
+ (builder) =>
+ builder.pipe(function passThroughBefore(input) {
+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))
+ }),
+ (builder) =>
+ builder.sequentially((steps) =>
+ steps.pipe(function emitStep(event: Event) {
+ return Promise.resolve(ok(event))
+ })
+ ),
+ (builder) =>
+ builder.pipe(function passThroughAfter(input) {
+ return Promise.resolve(ok(input))
+ }),
+ { concurrentBatches: 1 }
+ )
+
+ await pipeline.feed(
+ [{ key: 'a', seq: 1 }].map((event) => createOkContext<Event, NoCtx>(event, {})),
+ {}
+ )
+ const batch = await pipeline.next()
+
+ expect(resultKinds(batch!.elements)).toEqual(['ok'])
+ })
+})
diff --git a/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.test.ts b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.test.ts
index 8e69ed24c0d0..0d6a1d2ad2a9 100644
--- a/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.test.ts
@@ -3,12 +3,13 @@ import { Message } from 'node-rdkafka'
import { logger } from '~/common/utils/logger'
import { createTestMessage } from '~/tests/helpers/kafka-message'
+import { BatchBudget } from './batch-budget'
import { ChunkPipelineBuilder } from './builders'
import { ChunkPipeline } from './chunk-pipeline.interface'
import { FanOutFanInChunkPipeline, FanOutSubContext } from './fan-out-fan-in-chunk-pipeline'
import { createKafkaDebugContext, createNewChunkPipeline, createOkContext } from './helpers'
-import { PipelineResultWithContext, PipelineWarning } from './pipeline.interface'
-import { PipelineResult, dlq, drop, isDlqResult, isOkResult, ok, redirect } from './results'
+import { PipelineContext, PipelineResultWithContext, PipelineWarning } from './pipeline.interface'
+import { PipelineResult, dlq, drop, isDlqResult, isOkResult, isTimeoutResult, ok, redirect, timeout } from './results'
jest.mock('~/common/utils/logger', () => ({
logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
@@ -165,6 +166,35 @@ describe('FanOutFanInChunkPipeline', () => {
expect(await pipeline.next()).toBeNull()
})
+ it('copies the parent budget onto every sub-element context', async () => {
+ // Without the parent's budget, sub-elements would run with no checkpoint.
+ const budget = BatchBudget.unlimited()
+ const subContexts: PipelineContext<FanOutSubContext>[] = []
+ let buffered: PipelineResultWithContext<SubItem, FanOutSubContext>[] = []
+ const sub: ChunkPipeline<SubItem, SubItem, FanOutSubContext> = {
+ feed: (elements) => {
+ subContexts.push(...elements.map((element) => element.context))
+ buffered = [...elements]
+ },
+ next: () => {
+ const chunk = buffered
+ buffered = []
+ return Promise.resolve(chunk.length > 0 ? chunk : null)
+ },
+ }
+ const pipeline = new FanOutFanInChunkPipeline(
+ createNewChunkPipeline<Parent, { message: Message; budget: BatchBudget }>().build(),
+ splitSubs,
+ sub,
+ sumSubs
+ )
+
+ pipeline.feed([createOkContext({ id: 'a', subs: [1, 2] }, { message: createTestMessage(), budget })])
+
+ expect(okValues((await pipeline.next())!)).toEqual([{ id: 'a', total: 3 }])
+ expect(subContexts.map((context) => context.budget)).toEqual([budget, budget])
+ })
+
it('emits parents unordered as they complete, keeping sub-results correlated', async () => {
const gate = deferred()
function gatedStep(item: SubItem): Promise<PipelineResult<SubItem>> {
@@ -361,6 +391,39 @@ describe('FanOutFanInChunkPipeline', () => {
expect(isDlqResult(results[0].result) && results[0].result.reason).toBe(expectedReason)
})
+ it('times the parent out when a sub-result times out', async () => {
+ const fanInCalls: string[] = []
+ function trackingFanIn(parent: Parent, subs: SubItem[]): Merged {
+ fanInCalls.push(parent.id)
+ return sumSubs(parent, subs)
+ }
+ function cutOffFirstSubStep(items: SubItem[]): Promise<PipelineResult<SubItem>[]> {
+ return Promise.resolve(
+ items.map((item) => (item.value === 1 ? timeout<SubItem>('budget exceeded') : ok(item)))
+ )
+ }
+
+ const pipeline = createNewChunkPipeline<Parent>()
+ .fanOut(splitSubs)
+ .via((sub) => sub.pipeChunk(cutOffFirstSubStep))
+ .fanIn(trackingFanIn)
+ .build()
+
+ feedParents(pipeline, [
+ { id: 'cutoff', subs: [1, 2] },
+ { id: 'healthy', subs: [3] },
+ ])
+
+ const results = await drainAll(pipeline)
+
+ expect(results).toHaveLength(2)
+ const timedOut = results.find((r) => isTimeoutResult(r.result))!
+ expect((timedOut.result as { reason: string }).reason).toBe('fan-out sub-element timed out: budget exceeded')
+ expect(fanInCalls).toEqual(['healthy'])
+ expect(okValues(results)).toEqual([{ id: 'healthy', total: 3 }])
+ expect(mockLogger.warn).not.toHaveBeenCalled()
+ })
+
it('merges sub side effects and warnings into the parent context without double-counting', async () => {
const outerEffect = Promise.resolve('outer')
function attachOuterEffectStep(parents: Parent[]): Promise<PipelineResult<Parent>[]> {
diff --git a/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.ts b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.ts
index d49b7ac94b08..ae83d67430a6 100644
--- a/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.ts
+++ b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.ts
@@ -3,7 +3,7 @@ import { logger } from '~/common/utils/logger'
import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'
import { InterleavingChunkPipeline, PullOutcome } from './interleaving-chunk-pipeline'
import { PipelineContext, PipelineResultWithContext } from './pipeline.interface'
-import { PipelineResultType, dlq, isDlqResult, isDropResult, isOkResult, ok } from './results'
+import { PipelineResultType, dlq, isDlqResult, isDropResult, isOkResult, isTimeoutResult, ok, timeout } from './results'
/**
* Splits one element into its sub-elements. Must be synchronous and cheap —
@@ -63,6 +63,8 @@ interface PendingParent<TElement, TSubOut, C> {
dlqFailures: { reason: string; error: unknown }[]
/** lastStep of the most recent DLQ sub-result, for error attribution on the parent. */
dlqLastStep: string | undefined
+ /** First timed-out sub-result seen; when set the parent times out instead of fanning in. */
+ timedOut: { reason: string; lastStep: string | undefined } | null
}
/**
@@ -85,6 +87,7 @@ interface PendingParent<TElement, TSubOut, C> {
* error via AggregateError) once all of its siblings have drained.
* Fanning in anyway could emit an element built for work that never
* happened — e.g. a pointer to a blob that was never stored.
+ * - TIMEOUT times the parent out, because its message is redelivered whole.
* - REDIRECT contributes nothing but logs a warning: it is almost
* certainly misuse, since sub-elements are not Kafka messages — route
* the parent before fanning out instead.
@@ -208,6 +211,7 @@ export class FanOutFanInChunkPipeline<
collected: [],
dlqFailures: [],
dlqLastStep: undefined,
+ timedOut: null,
}
const ref = new FanOutParentRef()
this.pendingParents.set(ref, parent)
@@ -217,6 +221,7 @@ export class FanOutFanInChunkPipeline<
// identify the message the sub-element came from.
debugContext: element.context.debugContext,
traceContext: element.context.traceContext,
+ budget: element.context.budget,
sideEffects: [],
warnings: [],
[FAN_OUT_PARENT]: ref,
@@ -290,6 +295,11 @@ export class FanOutFanInChunkPipeline<
if (isOkResult(subResult.result)) {
parent.collected.push(subResult.result.value)
+ } else if (isTimeoutResult(subResult.result)) {
+ parent.timedOut ??= {
+ reason: subResult.result.reason,
+ lastStep: subResult.context.lastStep,
+ }
} else if (isDlqResult(subResult.result)) {
// A sub-element that must be dead-lettered fails its whole parent:
// fanning in regardless could emit an element built for work that
@@ -315,13 +325,26 @@ export class FanOutFanInChunkPipeline<
}
this.pendingParents.delete(ref)
- if (parent.dlqFailures.length > 0) {
+ if (parent.timedOut) {
+ this.readyResults.push(this.timeOutParent(parent, parent.timedOut))
+ } else if (parent.dlqFailures.length > 0) {
this.readyResults.push(this.failParent(parent))
} else {
this.readyResults.push(this.completeParent(parent.original, parent.context, parent.collected))
}
}
+ private timeOutParent(
+ parent: PendingParent<TElement, TSubOut, COutput>,
+ timedOut: NonNullable<PendingParent<TElement, TSubOut, COutput>['timedOut']>
+ ): PipelineResultWithContext<TMerged, COutput, RPrev> {
+ parent.context.lastStep = timedOut.lastStep
+ return {
+ result: timeout<TMerged>(`fan-out sub-element timed out: ${timedOut.reason}`),
+ context: parent.context,
+ }
+ }
+
/**
* Emit the parent as a DLQ aggregating its sub DLQs. Every sub-result has
* drained by now, so the context already carries all sibling side effects
diff --git a/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.test.ts b/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.test.ts
index 60b859c410c2..7a2f9cc5db67 100644
--- a/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.test.ts
@@ -8,7 +8,7 @@ import { FlagEvaluationsMode, Team } from '~/types'
import { createContext, createNewChunkPipeline, createOkContext } from './helpers'
import { IngestionWarningHandlingChunkPipeline } from './ingestion-warning-handling-chunk-pipeline'
-import { ok } from './results'
+import { ok, timeout } from './results'
jest.mock('~/ingestion/common/ingestion-warnings')
@@ -168,6 +168,35 @@ describe('IngestionWarningHandlingChunkPipeline', () => {
})
})
+ it('abandons warnings on a timed-out element instead of emitting them', async () => {
+ const message = createTestMessage()
+ const team = createTestTeam()
+ const previous = {
+ feed: jest.fn(),
+ next: jest.fn().mockResolvedValue([
+ {
+ result: timeout('budget exceeded before emitEvent'),
+ context: {
+ message,
+ team,
+ lastStep: undefined,
+ sideEffects: [],
+ warnings: [{ type: 'client_ingestion_warning', details: { field: 'value' } }],
+ },
+ },
+ ]),
+ }
+ const pipeline = new IngestionWarningHandlingChunkPipeline(mockOutputs, previous as any)
+
+ pipeline.feed([])
+ const results = await pipeline.next()
+
+ expect(results).toHaveLength(1)
+ expect(results![0].context.warnings).toEqual([])
+ expect(results![0].context.sideEffects).toHaveLength(0)
+ expect(mockEmitIngestionWarning).not.toHaveBeenCalled()
+ })
+
it('should handle warning with alwaysSend flag', async () => {
const message = createTestMessage()
const team = createTestTeam()
diff --git a/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.ts b/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.ts
index 4ab45a541ab1..9fa2ab89d7d2 100644
--- a/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.ts
+++ b/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.ts
@@ -4,6 +4,7 @@ import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
import { TeamIdContext } from './builders/chunk-pipeline-builders'
import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'
+import { isTimeoutResult } from './results'
export class IngestionWarningHandlingChunkPipeline<
TInput,
@@ -29,6 +30,16 @@ export class IngestionWarningHandlingChunkPipeline<
}
return results.map((resultWithContext) => {
+ if (isTimeoutResult(resultWithContext.result) && resultWithContext.context.warnings?.length) {
+ // The redelivery emits these again.
+ return {
+ result: resultWithContext.result,
+ context: {
+ ...resultWithContext.context,
+ warnings: [],
+ },
+ }
+ }
if (resultWithContext.context.warnings && resultWithContext.context.warnings.length > 0) {
const warningPromises = resultWithContext.context.warnings.map((warning) =>
emitIngestionWarning(this.outputs, resultWithContext.context.team.id, warning)
diff --git a/nodejs/src/ingestion/framework/metrics.test-utils.ts b/nodejs/src/ingestion/framework/metrics.test-utils.ts
index ba00f42a66c6..4b94645aa163 100644
--- a/nodejs/src/ingestion/framework/metrics.test-utils.ts
+++ b/nodejs/src/ingestion/framework/metrics.test-utils.ts
@@ -1,4 +1,19 @@
-import { pipelineRetryAttemptsHistogram } from './metrics'
+import {
+ BudgetCheckpoint,
+ batchBudgetCheckpointCounter,
+ batchBudgetExhaustedCounter,
+ pipelineRetryAttemptsHistogram,
+} from './metrics'
+
+export async function getBudgetCheckpoints(checkpoint: BudgetCheckpoint, stepName: string): Promise<number> {
+ const metric = await batchBudgetCheckpointCounter.get()
+ return metric.values.find((v) => v.labels.checkpoint === checkpoint && v.labels.step_name === stepName)?.value ?? 0
+}
+
+export async function getBudgetsExhausted(): Promise<number> {
+ const metric = await batchBudgetExhaustedCounter.get()
+ return metric.values[0]?.value ?? 0
+}
/**
* Reads the {_count, _sum} of the retry-attempts histogram for a given name/outcome.
diff --git a/nodejs/src/ingestion/framework/metrics.ts b/nodejs/src/ingestion/framework/metrics.ts
index 3e52d72d579c..2fde3bdb2592 100644
--- a/nodejs/src/ingestion/framework/metrics.ts
+++ b/nodejs/src/ingestion/framework/metrics.ts
@@ -19,3 +19,26 @@ export const pipelineRetryAttemptsHistogram = new Histogram({
labelNames: ['name', 'outcome'],
buckets: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
})
+
+export const batchBudgetExhaustedCounter = new Counter({
+ name: 'ingestion_batch_budget_exhausted_total',
+ help: 'Batch budgets that expired before their batch completed',
+})
+
+export const batchBudgetOverrunHistogram = new Histogram({
+ name: 'ingestion_batch_budget_overrun_seconds',
+ help: 'Time from a batch budget expiring to its batch completing: the tail the checkpoints cannot cut',
+ buckets: exponentialBuckets(0.01, 2, 12), // 10ms -> ~40s
+})
+
+export const batchBudgetCheckpointCounter = new Counter({
+ name: 'ingestion_batch_budget_checkpoint_total',
+ help: 'Elements a budget checkpoint cut off, by checkpoint and step',
+ labelNames: ['checkpoint', 'step_name'],
+})
+
+export type BudgetCheckpoint = 'step' | 'chunk'
+
+export function recordBudgetCheckpoint(checkpoint: BudgetCheckpoint, stepName: string): void {
+ batchBudgetCheckpointCounter.labels({ checkpoint, step_name: stepName }).inc()
+}
diff --git a/nodejs/src/ingestion/framework/pipeline.interface.ts b/nodejs/src/ingestion/framework/pipeline.interface.ts
index bf710e241e51..3e01eb2d424b 100644
--- a/nodejs/src/ingestion/framework/pipeline.interface.ts
+++ b/nodejs/src/ingestion/framework/pipeline.interface.ts
@@ -3,6 +3,7 @@ import { Message } from 'node-rdkafka'
import { IngestionWarning } from '~/ingestion/common/ingestion-warnings'
+import { BatchBudget } from './batch-budget'
import { PipelineResult, PipelineResultOk } from './results'
export type PipelineWarning = IngestionWarning
@@ -60,6 +61,8 @@ export type PipelineContext<C = { message: Message }> = C & {
debugContext?: unknown
/** The batch's trace context. Steps parent on it because the pump that runs them is a shared loop. */
traceContext?: Context
+ /** Absent outside a fed batch, for example in the beforeBatch and afterBatch hooks. */
+ budget?: BatchBudget
/**
* Work that outlives the step, drained with the batch. A side effect must
* not reject. What a rejection does depends on the host: consumer-v2
diff --git a/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts b/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts
index 9e9162ec0f37..6dfae90da8da 100644
--- a/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts
@@ -14,7 +14,7 @@ import { createMockPipeline } from '~/tests/helpers/mock-pipeline'
import { createContext } from './helpers'
import { PipelineConfig, ResultHandlingPipeline } from './result-handling-pipeline'
-import { dlq, drop, ok, redirect } from './results'
+import { dlq, drop, ok, redirect, timeout } from './results'
// Mock the pipeline helpers
jest.mock('~/ingestion/framework/result-handling-helpers', () => ({
@@ -429,6 +429,31 @@ describe('ResultHandlingPipeline', () => {
'unknown'
)
})
+
+ it('counts a timeout result without producing anything', async () => {
+ const result = timeout('budget exceeded before slowStep')
+ const messages: Message[] = [
+ { value: Buffer.from('timed out'), topic: 'test', partition: 0, offset: 1 } as Message,
+ ]
+
+ const chunkResults = [createContext(result, { message: messages[0], lastStep: 'slowStep' })]
+
+ const mockPipeline = createMockPipeline(chunkResults)
+ const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)
+ const results = await resultPipeline.next()
+
+ expect(results).toHaveLength(1)
+ expect(results![0].result).toEqual(result)
+ expect(results![0].context.sideEffects).toHaveLength(0)
+ expect(mockProduceMessageToDLQ).not.toHaveBeenCalled()
+ expect(mockRedirectMessageToOutput).not.toHaveBeenCalled()
+ expect(mockLogDroppedMessage).not.toHaveBeenCalled()
+ expect(mockIngestionPipelineResultCounter.labels).toHaveBeenCalledWith({
+ result: 'timeout',
+ last_step_name: 'slowStep',
+ details: 'budget exceeded before slowStep',
+ })
+ })
})
describe('last step reporting', () => {
diff --git a/nodejs/src/ingestion/framework/result-handling-pipeline.ts b/nodejs/src/ingestion/framework/result-handling-pipeline.ts
index 55c9a78137b8..dbf783cc30e5 100644
--- a/nodejs/src/ingestion/framework/result-handling-pipeline.ts
+++ b/nodejs/src/ingestion/framework/result-handling-pipeline.ts
@@ -30,10 +30,12 @@ export type PipelineConfig<R extends string = never> = {
/**
* Unified result handling pipeline that wraps any chunk-processing pipeline and handles
- * non-success results (DLQ, DROP, REDIRECT) by adding side effects.
+ * non-success results (DLQ, DROP, REDIRECT, TIMEOUT) by adding side effects.
*
* The redirect type R flows through — redirect results are kept in the output
* with the redirect side effect attached.
+ *
+ * A TIMEOUT produces nothing, because its redelivery produces it.
*/
export class ResultHandlingPipeline<
TInput,
@@ -133,5 +135,7 @@ function resultDetails<T, R extends string>(result: PipelineResult<T, R>): { res
return { result: 'dlq', details: result.reason }
case PipelineResultType.REDIRECT:
return { result: 'redirect', details: redirectDetails(result) }
+ case PipelineResultType.TIMEOUT:
+ return { result: 'timeout', details: result.reason }
}
}
diff --git a/nodejs/src/ingestion/framework/results.ts b/nodejs/src/ingestion/framework/results.ts
index 695e99a3f116..0cb0d6aec7f6 100644
--- a/nodejs/src/ingestion/framework/results.ts
+++ b/nodejs/src/ingestion/framework/results.ts
@@ -5,6 +5,7 @@ export enum PipelineResultType {
DLQ,
DROP,
REDIRECT,
+ TIMEOUT,
}
export type PipelineResultOk<T> = {
@@ -35,6 +36,13 @@ export type PipelineResultRedirect<R extends string = never> = {
sideEffects: Promise<unknown>[]
warnings: PipelineWarning[]
}
+/** The budget cut the element off. Its message is not acked, so its source redelivers it. */
+export type PipelineResultTimeout = {
+ type: PipelineResultType.TIMEOUT
+ reason: string
+ sideEffects: Promise<unknown>[]
+ warnings: PipelineWarning[]
+}
/**
* Discriminated union of all possible step outcomes.
*
@@ -48,6 +56,7 @@ export type PipelineResult<T, R extends string = never> =
| PipelineResultDlq
| PipelineResultDrop
| PipelineResultRedirect<R>
+ | PipelineResultTimeout
/**
* Helper functions for creating pipeline step results
@@ -77,6 +86,14 @@ export function drop<T>(
return { type: PipelineResultType.DROP, reason, sideEffects, warnings }
}
+export function timeout<T>(
+ reason: string,
+ sideEffects: Promise<unknown>[] = [],
+ warnings: PipelineWarning[] = []
+): PipelineResult<T> {
+ return { type: PipelineResultType.TIMEOUT, reason, sideEffects, warnings }
+}
+
/**
* Create a redirect result targeting a named output.
*
@@ -122,3 +139,9 @@ export function isRedirectResult<T, R extends string = never>(
): result is PipelineResultRedirect<R> {
return result.type === PipelineResultType.REDIRECT
}
+
+export function isTimeoutResult<T, R extends string = never>(
+ result: PipelineResult<T, R>
+): result is PipelineResultTimeout {
+ return result.type === PipelineResultType.TIMEOUT
+}
diff --git a/nodejs/src/ingestion/framework/step-pipeline.test.ts b/nodejs/src/ingestion/framework/step-pipeline.test.ts
index 40963fb1fb4b..edfc7ff06350 100644
--- a/nodejs/src/ingestion/framework/step-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/step-pipeline.test.ts
@@ -2,8 +2,11 @@ import { Message, MessageHeader } from 'node-rdkafka'
import { logger } from '~/common/utils/logger'
+import { BatchBudget } from './batch-budget'
import { createContext, createKafkaDebugContext, createOkContext } from './helpers'
-import { isOkResult, ok } from './results'
+import { batchBudgetCheckpointCounter } from './metrics'
+import { getBudgetCheckpoints } from './metrics.test-utils'
+import { isOkResult, isTimeoutResult, ok } from './results'
import { StartPipeline } from './start-pipeline'
import { StepPipeline } from './step-pipeline'
@@ -97,6 +100,53 @@ describe('StepPipeline', () => {
})
})
+ describe('budget checkpoint', () => {
+ const message: Message = { value: Buffer.from('test'), topic: 'test', partition: 0, offset: 1 } as Message
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ batchBudgetCheckpointCounter.reset()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ function buildChain(calls: string[]) {
+ function firstStep(value: { value: number }) {
+ calls.push('firstStep')
+ // Stands in for the step taking longer than the batch had left.
+ jest.advanceTimersByTime(1000)
+ return Promise.resolve(ok(value))
+ }
+ function secondStep(value: { value: number }) {
+ calls.push('secondStep')
+ return Promise.resolve(ok(value))
+ }
+ function thirdStep(value: { value: number }) {
+ calls.push('thirdStep')
+ return Promise.resolve(ok(value))
+ }
+
+ return new StepPipeline(firstStep, new StartPipeline<{ value: number }, unknown>())
+ .pipe(secondStep)
+ .pipe(thirdStep)
+ }
+
+ it('times the element out at the next step and skips the rest of the chain', async () => {
+ const budget = BatchBudget.softDeadline(Date.now() + 1000)
+ const calls: string[] = []
+
+ const result = await buildChain(calls).process(createOkContext({ value: 1 }, { message, budget }))
+
+ expect(calls).toEqual(['firstStep'])
+ expect(isTimeoutResult(result.result)).toBe(true)
+ expect((result.result as { reason: string }).reason).toBe('budget exceeded before secondStep')
+ expect(result.context.lastStep).toBe('firstStep')
+ expect(await getBudgetCheckpoints('step', 'secondStep')).toBe(1)
+ })
+ })
+
describe('pipe', () => {
it('should create new StepPipeline with async step', () => {
const step1 = jest.fn()
diff --git a/nodejs/src/ingestion/framework/step-pipeline.ts b/nodejs/src/ingestion/framework/step-pipeline.ts
index d01ca237b2a5..7a5c9f529fa6 100644
--- a/nodejs/src/ingestion/framework/step-pipeline.ts
+++ b/nodejs/src/ingestion/framework/step-pipeline.ts
@@ -1,9 +1,9 @@
import { instrumentFn, isTracingActive } from '~/common/tracing/tracing-utils'
import { logger } from '~/common/utils/logger'
-import { pipelineStepDurationHistogram } from './metrics'
+import { pipelineStepDurationHistogram, recordBudgetCheckpoint } from './metrics'
import { OkResultWithContext, Pipeline, PipelineResultWithContext } from './pipeline.interface'
-import { PipelineResult, PipelineResultType, isOkResult } from './results'
+import { PipelineResult, PipelineResultType, isOkResult, timeout } from './results'
import { eventSpanAttributes } from './span-attributes'
import { ProcessingStep } from './steps'
@@ -38,6 +38,16 @@ export class StepPipeline<TInput, TIntermediate, TOutput, C, RPrev extends strin
}
}
+ // lastStep keeps the step that spent the time; the reason names the step that never started.
+ const budget = previousResultWithContext.context.budget
+ if (budget?.exhausted) {
+ recordBudgetCheckpoint('step', this.stepName)
+ return {
+ result: timeout(`budget exceeded before ${this.stepName}`),
+ context: previousResultWithContext.context,
+ }
+ }
+
const end = pipelineStepDurationHistogram.startTimer({ step_name: this.stepName, step_type: 'element' })
const traceContext = previousResultWithContext.context.traceContext
let currentResult: PipelineResult<TOutput, RStep>
diff --git a/nodejs/src/ingestion/framework/timeout-barrier-pipeline.test.ts b/nodejs/src/ingestion/framework/timeout-barrier-pipeline.test.ts
new file mode 100644
index 000000000000..549adb06fb8b
--- /dev/null
+++ b/nodejs/src/ingestion/framework/timeout-barrier-pipeline.test.ts
@@ -0,0 +1,96 @@
+import { Message } from 'node-rdkafka'
+
+import { BatchBudget } from './batch-budget'
+import { newPipelineBuilder } from './builders'
+import { createOkContext } from './helpers'
+import { isOkResult, isTimeoutResult, ok } from './results'
+
+describe('TimeoutBarrierPipeline', () => {
+ const message: Message = { value: Buffer.from('test'), topic: 'test', partition: 0, offset: 1 } as Message
+
+ beforeEach(() => {
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ type Value = { value: number }
+ type Ctx = { message: Message; budget?: BatchBudget }
+
+ function spendTheBudget() {
+ jest.advanceTimersByTime(1000)
+ }
+
+ it('runs every step past the barrier once an element has crossed it', async () => {
+ const ran: string[] = []
+ const pipeline = newPipelineBuilder<Value, Ctx>()
+ .pipe(function beforeBarrier(value: Value) {
+ ran.push('beforeBarrier')
+ return Promise.resolve(ok(value))
+ })
+ .timeoutBarrier()
+ .pipe(function middleStep(value: Value) {
+ ran.push('middleStep')
+ // Without the barrier, the next checkpoint would cut the element here.
+ spendTheBudget()
+ return Promise.resolve(ok(value))
+ })
+ .pipe(function lastStep(value: Value) {
+ ran.push('lastStep')
+ return Promise.resolve(ok(value))
+ })
+ .build()
+
+ const budget = BatchBudget.softDeadline(Date.now() + 1000)
+ const result = await pipeline.process(createOkContext({ value: 1 }, { message, budget }))
+
+ expect(ran).toEqual(['beforeBarrier', 'middleStep', 'lastStep'])
+ expect(isOkResult(result.result)).toBe(true)
+ expect(result.context.budget).toBe(BatchBudget.unlimited())
+ })
+
+ it('cuts an element that reaches the barrier with its budget spent', async () => {
+ const ran: string[] = []
+ const pipeline = newPipelineBuilder<Value, Ctx>()
+ .pipe(function beforeBarrier(value: Value) {
+ ran.push('beforeBarrier')
+ spendTheBudget()
+ return Promise.resolve(ok(value))
+ })
+ .timeoutBarrier()
+ .pipe(function afterBarrier(value: Value) {
+ ran.push('afterBarrier')
+ return Promise.resolve(ok(value))
+ })
+ .build()
+
+ const budget = BatchBudget.softDeadline(Date.now() + 1000)
+ const result = await pipeline.process(createOkContext({ value: 1 }, { message, budget }))
+
+ expect(ran).toEqual(['beforeBarrier'])
+ expect(isTimeoutResult(result.result)).toBe(true)
+ expect((result.result as { reason: string }).reason).toBe('budget exceeded before timeoutBarrier')
+ })
+
+ it('passes an element through when its context carries no budget', async () => {
+ const ran: string[] = []
+ const pipeline = newPipelineBuilder<Value, Ctx>()
+ .pipe(function beforeBarrier(value: Value) {
+ ran.push('beforeBarrier')
+ return Promise.resolve(ok(value))
+ })
+ .timeoutBarrier()
+ .pipe(function afterBarrier(value: Value) {
+ ran.push('afterBarrier')
+ return Promise.resolve(ok(value))
+ })
+ .build()
+
+ const result = await pipeline.process(createOkContext({ value: 1 }, { message }))
+
+ expect(ran).toEqual(['beforeBarrier', 'afterBarrier'])
+ expect(isOkResult(result.result)).toBe(true)
+ })
+})
diff --git a/nodejs/src/ingestion/framework/timeout-barrier-pipeline.ts b/nodejs/src/ingestion/framework/timeout-barrier-pipeline.ts
new file mode 100644
index 000000000000..7f3a23a8635a
--- /dev/null
+++ b/nodejs/src/ingestion/framework/timeout-barrier-pipeline.ts
@@ -0,0 +1,40 @@
+import { BatchBudget } from './batch-budget'
+import { recordBudgetCheckpoint } from './metrics'
+import { OkResultWithContext, Pipeline, PipelineResultWithContext } from './pipeline.interface'
+import { isOkResult, timeout } from './results'
+
+const TIMEOUT_BARRIER = 'timeoutBarrier'
+
+/**
+ * The last budget checkpoint. An element that reaches it with time left
+ * continues with an unlimited budget, so it always finishes; an exhausted one
+ * is cut here. It is a stage, not a step, because it rewrites the context.
+ */
+export class TimeoutBarrierPipeline<TInput, TOutput, C, R extends string = never>
+ implements Pipeline<TInput, TOutput, C, R>
+{
+ constructor(private previousPipeline: Pipeline<TInput, TOutput, C, R>) {}
+
+ async process(input: OkResultWithContext<TInput, C>): Promise<PipelineResultWithContext<TOutput, C, R>> {
+ const previousResultWithContext = await this.previousPipeline.process(input)
+
+ const budget = previousResultWithContext.context.budget
+ if (!isOkResult(previousResultWithContext.result) || budget === undefined) {
+ return previousResultWithContext
+ }
+ if (budget.exhausted) {
+ recordBudgetCheckpoint('step', TIMEOUT_BARRIER)
+ return {
+ result: timeout(`budget exceeded before ${TIMEOUT_BARRIER}`),
+ context: previousResultWithContext.context,
+ }
+ }
+ if (budget === BatchBudget.unlimited()) {
+ return previousResultWithContext
+ }
+ return {
+ result: previousResultWithContext.result,
+ context: { ...previousResultWithContext.context, budget: BatchBudget.unlimited() },
+ }
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
index d21710a69d18..18733e017ab4 100644
--- a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts
@@ -126,6 +126,8 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput & Wi
{ retry: { tries: 5, sleepMs: 100, name: 'hog_transform_event' } }
)
.pipe(createNormalizeEventStep())
+ // From here on the event writes persons, groups and itself, so finishing costs less than redelivering.
+ .timeoutBarrier()
.pipe(
createProcessPersonlessStep(
options.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
diff --git a/nodejs/src/servers/grpc-stream-ingest-driver.test.ts b/nodejs/src/servers/grpc-stream-ingest-driver.test.ts
new file mode 100644
index 000000000000..222e24c6a568
--- /dev/null
+++ b/nodejs/src/servers/grpc-stream-ingest-driver.test.ts
@@ -0,0 +1,83 @@
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { SubBatchBudget } from '~/ingestion/api/grpc-server'
+import { BatchBudget } from '~/ingestion/framework/batch-budget'
+import { PipelineResult, drop, ok, timeout } from '~/ingestion/framework/results'
+
+import { GrpcIngestPipeline, GrpcStreamIngestDriver } from './grpc-stream-ingest-driver'
+
+function completedBatch(results: PipelineResult<unknown>[]): GrpcIngestPipeline {
+ return {
+ next: () =>
+ Promise.resolve({
+ elements: results.map((result, index) => ({
+ result,
+ context: { message: { partition: 3, offset: 100 + index } },
+ })),
+ batchContext: { grpcStreamId: 7, grpcSeq: 3 },
+ sideEffects: [],
+ }),
+ } as unknown as GrpcIngestPipeline
+}
+
+function recordingPipeline(fed: BatchBudget[]): GrpcIngestPipeline {
+ return {
+ feed: (_elements: unknown, _batchContext: unknown, budget: BatchBudget) => {
+ fed.push(budget)
+ return Promise.resolve({ ok: true })
+ },
+ } as unknown as GrpcIngestPipeline
+}
+
+describe('GrpcStreamIngestDriver', () => {
+ describe('dispositions', () => {
+ it('reports each timed-out element as unfinished by its partition and offset and counts the rest accepted', async () => {
+ const driver = new GrpcStreamIngestDriver(
+ completedBatch([ok({}), timeout('budget exceeded before step'), drop('not interesting')]),
+ new PromiseScheduler()
+ )
+
+ const completed = (await driver.next())!
+
+ expect(completed.streamId).toBe(7)
+ expect(completed.seq).toBe(3)
+ expect(completed.unfinished).toEqual([{ partition: 3, offset: 101 }])
+ // A dropped element is handled, not redelivered, so it counts as accepted.
+ expect(completed.accepted).toBe(2)
+ })
+
+ it('reports a fully processed batch with no dispositions', async () => {
+ const driver = new GrpcStreamIngestDriver(completedBatch([ok({}), ok({})]), new PromiseScheduler())
+
+ const completed = (await driver.next())!
+
+ expect(completed.accepted).toBe(2)
+ expect(completed.unfinished).toEqual([])
+ })
+ })
+
+ describe('budgets', () => {
+ async function fedBudget(wire: SubBatchBudget): Promise<BatchBudget> {
+ const fed: BatchBudget[] = []
+ const driver = new GrpcStreamIngestDriver(recordingPipeline(fed), new PromiseScheduler())
+
+ await driver.feed(1, 1, [], wire)
+
+ return fed[0]
+ }
+
+ it('anchors the deadline at the arming time, not at the feed', async () => {
+ const budget = await fedBudget({ armedAt: 1_000, softBudgetMs: 200 })
+
+ expect(budget.softAt).toBe(1_200)
+ })
+
+ it.each([
+ ['zero', 0],
+ ['longer than a timer can wait', 2 ** 31],
+ ])('reads a %s allowance as an unlimited budget', async (_label, softBudgetMs) => {
+ const budget = await fedBudget({ armedAt: 1_000, softBudgetMs })
+
+ expect(budget.softAt).toBe(Infinity)
+ })
+ })
+})
diff --git a/nodejs/src/servers/grpc-stream-ingest-driver.ts b/nodejs/src/servers/grpc-stream-ingest-driver.ts
index b61b56744266..8ed8b9350ff1 100644
--- a/nodejs/src/servers/grpc-stream-ingest-driver.ts
+++ b/nodejs/src/servers/grpc-stream-ingest-driver.ts
@@ -1,9 +1,11 @@
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
-import { CompletedSubBatch, StreamIngestDriver } from '~/ingestion/api/grpc-server'
+import { CompletedSubBatch, MessageCoordinates, StreamIngestDriver, SubBatchBudget } from '~/ingestion/api/grpc-server'
import { deserializeKafkaMessage } from '~/ingestion/api/kafka-message-converter'
import { SerializedKafkaMessage } from '~/ingestion/api/types'
+import { BatchBudget, budgetDeadline } from '~/ingestion/framework/batch-budget'
import { FeedResult } from '~/ingestion/framework/batching-pipeline'
import { createKafkaDebugContext, createOkContext } from '~/ingestion/framework/helpers'
+import { isTimeoutResult } from '~/ingestion/framework/results'
import {
JoinedIngestionPipelineContext,
JoinedIngestionPipelineInput,
@@ -29,12 +31,22 @@ export class GrpcStreamIngestDriver implements StreamIngestDriver {
private promiseScheduler: PromiseScheduler
) {}
- feed(streamId: number, seq: number, messages: SerializedKafkaMessage[]): Promise<FeedResult> {
+ feed(
+ streamId: number,
+ seq: number,
+ messages: SerializedKafkaMessage[],
+ budget: SubBatchBudget
+ ): 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 })
+ return this.pipeline.feed(batch, { grpcStreamId: streamId, grpcSeq: seq }, this.wireBudget(budget))
+ }
+
+ private wireBudget({ armedAt, softBudgetMs }: SubBatchBudget): BatchBudget {
+ const softAt = budgetDeadline(armedAt, softBudgetMs)
+ return softAt === null ? BatchBudget.unlimited() : BatchBudget.softDeadline(softAt)
}
async next(): Promise<CompletedSubBatch | null> {
@@ -48,10 +60,17 @@ export class GrpcStreamIngestDriver implements StreamIngestDriver {
await Promise.all(result.sideEffects ?? [])
await this.promiseScheduler.waitForAll()
})()
+ const unfinished: MessageCoordinates[] = []
+ for (const { result: elementResult, context } of result.elements) {
+ if (isTimeoutResult(elementResult)) {
+ unfinished.push({ partition: context.message.partition, offset: context.message.offset })
+ }
+ }
return {
streamId: result.batchContext.grpcStreamId,
seq: result.batchContext.grpcSeq,
- accepted: result.elements.length,
+ accepted: result.elements.length - unfinished.length,
+ unfinished,
settled,
}
}
diff --git a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
index a156d4cf8d70..742d00f5357c 100644
--- a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
+++ b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
@@ -10,7 +10,12 @@ import {
createFlushBatchStoresStep,
} from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'
import { BatchWritingStore, BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'
-import { BatchingPipeline, BeforeBatchInput, FeedResult } from '~/ingestion/framework/batching-pipeline'
+import {
+ BatchingContext,
+ BatchingPipeline,
+ BeforeBatchInput,
+ FeedResult,
+} from '~/ingestion/framework/batching-pipeline'
import { newBatchingPipeline } from '~/ingestion/framework/builders'
import { createOkContext } from '~/ingestion/framework/helpers'
import { OkResultWithContext } from '~/ingestion/framework/pipeline.interface'
@@ -277,7 +282,7 @@ class Harness {
public scheduler = new PromiseScheduler()
/** Accepted batches in batchId order: which events went into which batch. */
public submissions: { batchId: number; specs: EventSpec[] }[] = []
- public pipeline: BatchingPipeline<In, ProcessedEvent, Ctx, StoreBatchContext, Ctx & { messageId: number }, never>
+ public pipeline: BatchingPipeline<In, ProcessedEvent, Ctx, StoreBatchContext, Ctx & BatchingContext, never>
private gates = new Map<string, Deferred>()
private nextOffset = 0
diff --git a/proto/ingestion/worker/v1/worker.proto b/proto/ingestion/worker/v1/worker.proto
index bda91550a31e..66e00289877b 100644
--- a/proto/ingestion/worker/v1/worker.proto
+++ b/proto/ingestion/worker/v1/worker.proto
@@ -54,6 +54,10 @@ message SubBatch {
// rebalance legitimately replays uncommitted offsets, so the worker's
// sentinel rebaselines on a new epoch instead of firing.
uint64 assignment_epoch = 5;
+ // Milliseconds after which the worker stops starting new work. It never
+ // interrupts a running step, so the ack watchdog stays the hard limit.
+ // 0, or a value above 2^31 - 1, means unlimited.
+ uint64 soft_budget_ms = 6;
}
// KafkaMessage mirrors `SerializedKafkaMessage` in
@@ -70,6 +74,12 @@ message KafkaMessage {
map<string, string> headers = 7;
}
+// The consumer reads one topic, so a partition and an offset identify a message.
+message MessageRef {
+ int32 partition = 1;
+ int64 offset = 2;
+}
+
// SubBatchStatus is the outcome of processing one sub-batch.
enum SubBatchStatus {
SUB_BATCH_STATUS_UNSPECIFIED = 0;
@@ -87,6 +97,9 @@ enum SubBatchStatus {
// treats any status it does not recognize the same way, so future non-fatal
// statuses stay backward compatible.
SUB_BATCH_STATUS_BUSY = 3;
+ // The budget cut the sub-batch short. Messages not in `SubBatchAck.unfinished`
+ // are done as on OK, and the consumer redelivers exactly the listed ones.
+ SUB_BATCH_STATUS_PARTIAL = 4;
}
// IngestStreamResponse is one frame on the worker-to-consumer stream.
@@ -111,8 +124,13 @@ message SubBatchAck {
uint64 seq = 1;
SubBatchStatus status = 2;
// Messages accepted into the pipeline. Meaningful only on
- // SUB_BATCH_STATUS_OK.
+ // SUB_BATCH_STATUS_OK and SUB_BATCH_STATUS_PARTIAL.
uint32 accepted = 3;
// Human-readable failure reason. Set only on SUB_BATCH_STATUS_FAILED.
string error = 4;
+ // Messages with work left when the budget ran out. Set only on PARTIAL,
+ // never empty. Every other message is done, as on OK. The listed messages
+ // need not be the last of their routing key, because a worker may process
+ // one key's messages in independent groups.
+ repeated MessageRef unfinished = 5;
}
diff --git a/rust/ingestion-consumer/docs/driver-model-plan.md b/rust/ingestion-consumer/docs/driver-model-plan.md
index 7b714a864bcf..00e70dfda785 100644
--- a/rust/ingestion-consumer/docs/driver-model-plan.md
+++ b/rust/ingestion-consumer/docs/driver-model-plan.md
@@ -68,7 +68,7 @@ The numbered order is one valid schedule, not the only one: the [cycle dependenc
The swap unit in cycle 3 is the **scheduler**: the decision core that says which runs may go to a worker now, and where.
That is where the complexity concentrates — the pins, the stash, and the flush interplay.
Packing follows at once (cycle 4): the performance win depends only on the key-table scheduler, not on the event loop, decoupled commits, or the budget.
-The request time budget follows packing (cycle 5): its enforcement precondition is the one-outstanding-request-per-key rule ([#89995](https://github.com/PostHog/posthog/pull/89995)), and its budget sizes against the packed request size.
+The request time budget follows packing (cycle 5): its enforcement precondition is the one-outstanding-request-per-key rule (cycle 3), and its budget sizes against the packed request size.
The governor follows (cycle 6): it needs the scheduler's ready queue for its growth signal, and it comes after packing and the time budget, so RTT (request round-trip time) tunes once, against the final request shape.
The single-owner event loop follows as its own outcome (cycle 7), once the scheduler is simple.
@@ -417,12 +417,12 @@ Exit criterion after the targets: the request-size histograms center near T, and
## Cycle 5: a slow request redelivers only its remainder
-Outcome: a worker stops a request at the consumer's time budget, acks the finished prefix, and only the remainder redelivers.
+Outcome: a worker stops a request at the consumer's time budget, acks the finished messages, and only the unfinished ones redeliver.
Today one slow message holds every message behind it until the ack watchdog fences the whole stream, and everything unacked replays with duplicate work.
This budget is time per request. It is not B, the uncommitted-work budget of cycle 9.
-It needs [#89995](https://github.com/PostHog/posthog/pull/89995) merged on the worker side (`soft_budget_ms` on the wire, the `PARTIAL` ack).
-It needs cycle 3: one outstanding request per key is [#89995](https://github.com/PostHog/posthog/pull/89995)'s stated enforcement precondition.
+It needs [#115388](https://github.com/PostHog/posthog/pull/115388) merged on the worker side (`soft_budget_ms` on the wire, the `PARTIAL` ack with its `unfinished` list).
+It needs cycle 3: with one outstanding request per key, no later request can pass a cut message of its key.
It sizes the budget against cycle 4's request size. Its cap on request RTT matters for cycle 6: set `REQUEST_LATENCY_BUDGET` below the soft budget, or the governor never shrinks.
**Verify:** a generous budget on one lane enforces rarely and exercises the real partial-ack path at negligible volume.
@@ -434,20 +434,21 @@ Exit criterion: partial acks resolve and their remainders redeliver in order, ze
**Goal:** Partial redelivery exists as one settlement arm, not a new path.
-- The stream runner parses `PARTIAL` and resolves the send with the accepted index list, instead of fencing it as busy.
-- The scheduler's partial arm is the failure arm plus a completed prefix: complete each key's finished prefix as group completions, return the remainder to the front of its queue, and keep the key blocked until the redelivery settles.
+- The stream runner parses `PARTIAL` and resolves the send with the `unfinished` message list, instead of fencing it as busy.
+- The scheduler's partial arm is the failure arm plus completions: complete every message not in `unfinished` as group completions, return the unfinished messages to the front of their keys' queues in offset order, and keep the key blocked until the redelivery settles.
+- Send the remainder with `replay` set. The worker's feed-order sentinel saw its offsets in the first send, so an unmarked redelivery counts as a key-order violation.
- The prototype against the old machinery ([#91480](https://github.com/PostHog/posthog/pull/91480)) showed the cost of doing this earlier: concurrent polls and per-batch accounting push partial handling through the deferral paths. Behind the key table it is one `on_settled` arm.
- Stamp `soft_budget_ms` on each request from config. Unset sends no budget.
**Interfaces:**
-- Modify the ack handling in `grpc_transport.rs`: parse `PARTIAL`; resolve with the accepted indexes.
+- Modify the ack handling in `grpc_transport.rs`: parse `PARTIAL`; resolve with the unfinished partitions and offsets.
- Modify the settlement types and `KeyTableScheduler::on_settled`: add the partial arm.
- Modify `Config`: add the soft budget per request, default unset.
**Metrics:**
-- Add `ingestion_consumer_request_budget_partials_total` (counter) and `ingestion_consumer_request_budget_timed_out_messages_total` (counter). The names match the wire: a `PARTIAL` ack with a `timed_out` index list.
+- Add `ingestion_consumer_request_budget_partials_total` (counter) and `ingestion_consumer_request_budget_unfinished_messages_total` (counter). The names match the wire: a `PARTIAL` ack with an `unfinished` message list.
### 15. Set the request time budgets (switchover)
@@ -456,7 +457,7 @@ Exit criterion: partial acks resolve and their remainders redeliver in order, ze
**Goal:** A slow request costs a partial redelivery, not a fenced stream and a full replay.
- A charts values PR sets the budget lane by lane. The generous stage is the cycle's verify.
-- Watch the partial and timed-out counters, the key-order sentinel, and stream teardowns.
+- Watch the partial and unfinished counters, the key-order sentinel, and stream teardowns.
- Rollback is unsetting the values.
**Interfaces:**
@@ -759,7 +760,7 @@ flowchart LR
C8["8: decoupled commits"]
C9["9: bounded replay"]
C10["10: clean handoff"]
- PR(["#89995 worker side"])
+ PR(["#115388 worker side"])
C1 --> C3
C3 --> C4
diff --git a/rust/ingestion-consumer/src/grpc_transport.rs b/rust/ingestion-consumer/src/grpc_transport.rs
index 492881a7143c..c96b59e47ee0 100644
--- a/rust/ingestion-consumer/src/grpc_transport.rs
+++ b/rust/ingestion-consumer/src/grpc_transport.rs
@@ -548,6 +548,7 @@ impl WorkerStreamRunner {
messages: item.messages.iter().map(to_proto_message).collect(),
replay: item.replay,
assignment_epoch: self.assignment_epoch.current(),
+ soft_budget_ms: 0,
})),
};
// tonic gzips the frame after this point, so only the raw size is observable here.
diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
index d2e3de4cf031..60b567fd2f3b 100644
--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -420,6 +420,7 @@ impl WorkerIngestService for FakeWorkerGrpc {
status: SubBatchStatus::Failed as i32,
accepted: 0,
error: reason.to_string(),
+ unfinished: vec![],
})),
}));
};
@@ -475,6 +476,7 @@ impl WorkerIngestService for FakeWorkerGrpc {
status: SubBatchStatus::Ok as i32,
accepted: reported,
error: String::new(),
+ unfinished: vec![],
})),
}));
}
diff --git a/rust/ingestion-consumer/tests/grpc_transport_test.rs b/rust/ingestion-consumer/tests/grpc_transport_test.rs
index 2cb72f8c06b3..84e0318d7825 100644
--- a/rust/ingestion-consumer/tests/grpc_transport_test.rs
+++ b/rust/ingestion-consumer/tests/grpc_transport_test.rs
@@ -98,12 +98,14 @@ impl WorkerIngest for MockWorker {
status: SubBatchStatus::Ok as i32,
accepted,
error: String::new(),
+ unfinished: vec![],
},
ManualAck::Nack(seq) => SubBatchAck {
seq,
status: SubBatchStatus::Failed as i32,
accepted: 0,
error: "poisoned".to_string(),
+ unfinished: vec![],
},
};
let _ = tx.send(Ok(IngestStreamResponse {
@@ -129,6 +131,7 @@ impl WorkerIngest for MockWorker {
status: SubBatchStatus::Ok as i32,
accepted,
error: String::new(),
+ unfinished: vec![],
})),
}));
}
@@ -139,6 +142,7 @@ impl WorkerIngest for MockWorker {
status: SubBatchStatus::Failed as i32,
accepted: 0,
error: "poisoned".to_string(),
+ unfinished: vec![],
})),
}));
}
@@ -149,6 +153,7 @@ impl WorkerIngest for MockWorker {
status: SubBatchStatus::Ok as i32,
accepted,
error: String::new(),
+ unfinished: vec![],
})),
}));
}
@@ -159,6 +164,7 @@ impl WorkerIngest for MockWorker {
status: SubBatchStatus::Busy as i32,
accepted: 0,
error: "at capacity".to_string(),
+ unfinished: vec![],
})),
}));
}
@@ -169,6 +175,7 @@ impl WorkerIngest for MockWorker {
status: SubBatchStatus::Ok as i32,
accepted,
error: String::new(),
+ unfinished: vec![],
})),
}));
}
@@ -180,6 +187,7 @@ impl WorkerIngest for MockWorker {
status: SubBatchStatus::Ok as i32,
accepted,
error: String::new(),
+ unfinished: vec![],
})),
}));
}
@@ -841,6 +849,7 @@ impl WorkerIngest for ControlledBusyWorker {
status,
accepted,
error,
+ unfinished: vec![],
})),
}));
}