:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): offload multimodal ai event blobs to s3 at ingestion (#72386)
Carlos Marchal58deed4bb430
diff --git a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.mdindex 39dabe2105eb..c07fd6232151 100644--- a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md+++ b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md@@ -62,6 +62,8 @@ See `nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts` for**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`.+**Testing**: Step tests call factory directly. Use `consumeAll()`/`collectChunks()` helpers. Fake timers for async. Type guards for result assertions. No `any`.## Running all doctorsdiff --git a/.claude/agents/ingestion/pipeline-composition-doctor.md b/.claude/agents/ingestion/pipeline-composition-doctor.mdindex fca595e6cf81..18e377d83491 100644--- a/.claude/agents/ingestion/pipeline-composition-doctor.md+++ b/.claude/agents/ingestion/pipeline-composition-doctor.md@@ -50,6 +50,7 @@ Before reviewing or writing any code, read these files:- `nodejs/src/ingestion/framework/docs/11-retries.test.ts` — per-step retry option, isRetriable, exhaustion behavior- `nodejs/src/ingestion/framework/docs/12-filter-map.test.ts` — filterMap(), context enrichment- `nodejs/src/ingestion/framework/docs/13-conventions.test.ts` — pipeline factory functions, naming+- `nodejs/src/ingestion/framework/docs/17-fan-out-fan-in.test.ts` — fanOut().via().fanIn(), per-element sub-work- `nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts` — real-world composition exampleAlso read any files the user points you to.@@ -187,6 +188,39 @@ function createMyPipeline(config: Config): ChunkPipeline<Input, Output> {const myPipeline = startPipeline<Input>().pipe(createStepA(defaultConfig)).build()```+### 10. Fan-out/fan-in for per-element sub-work++When one element carries N independent pieces of work (e.g. per-blob uploads), use the staged+`fanOut(fn).via((sub) => …).fanIn(fn)` stage — never hand-rolled concurrency inside a step.+Cardinality is restored at the parent level (N elements in, N results out), so the chunk+invariant holds. Sequencing is compile-time enforced: `.fanOut()` and `.via()` return+intermediates with a single method each; only `.fanIn()` yields a buildable pipeline.++- `maxConcurrency` goes on the sub `concurrently` block — one cap across all parents' subs, so+ budget it for the whole chunk, not one element.+- `retry` goes on the per-sub step, so a transient failure retries only that sub-element's work.+- Parents emit unordered as they complete (same contract as `concurrentlyPerGroup`) — compose+ the stage only where downstream is order-insensitive.+- A `p-limit`/`Promise.all` worker pool inside a step is the flag that this stage fits instead.++```typescript+// GOOD - pipeline-level concurrency cap and per-sub retry+builder+ .fanOut(extractBlobsFanOut)+ .via((sub) =>+ sub.concurrently((b) => b.pipe(uploadBlobStep, { retry: { name: 'upload', tries: 5 } }), { maxConcurrency: 8 })+ )+ .fanIn(mergeBlobPointersFanIn)++// BAD - hand-rolled concurrency inside a step, invisible to the framework+function createOffloadStep(): ProcessingStep<Input, Input> {+ return async function offloadStep(input) {+ await mapWithConcurrency(input.blobs, 8, uploadBlob) // reinvents maxConcurrency and retry+ return ok(input)+ }+}+```+## Output format### When reviewing codediff --git a/.claude/agents/ingestion/pipeline-result-doctor.md b/.claude/agents/ingestion/pipeline-result-doctor.mdindex ea69aca96554..7898eb10018a 100644--- a/.claude/agents/ingestion/pipeline-result-doctor.md+++ b/.claude/agents/ingestion/pipeline-result-doctor.md@@ -44,6 +44,7 @@ Before reviewing or writing any code, read these files:- `nodejs/src/ingestion/framework/docs/08-side-effects.test.ts` — side effect accumulation, await modes- `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 stagesAlso read any files the user points you to.@@ -183,6 +184,23 @@ builderUse `await: true` when side effects are fast and correctness matters.Use `await: false` when throughput matters, but ensure PromiseScheduler is drained at batch boundaries.+### 9. Fan-out sub-result contract++Sub-steps inside a `fanOut().via().fanIn()` stage have a narrower result contract than regular+steps — the stage settles the parent from its sub-results:++- `ok()` — collected and handed to the fan-in.+- `drop()` — the sanctioned exclusion: the sub contributes nothing, silently, and the parent+ fans in with the survivors.+- `dlq()` — legitimate, and fails the whole parent: the stage emits a parent-level DLQ+ aggregating the sub DLQs (count, distinct reasons, every error via AggregateError); fan-in+ is never called. Use it when a sub-element's permanent failure invalidates the element+ (e.g. a blob upload that permanently failed must not produce an event pointing at a blob+ that was never stored).+- `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.+## Output format### When reviewing codediff --git a/.claude/agents/ingestion/pipeline-step-doctor.md b/.claude/agents/ingestion/pipeline-step-doctor.mdindex f1356ee6044a..e6fda525e9d3 100644--- a/.claude/agents/ingestion/pipeline-step-doctor.md+++ b/.claude/agents/ingestion/pipeline-step-doctor.md@@ -45,6 +45,7 @@ Before reviewing or writing any code, read these files:- `nodejs/src/ingestion/framework/docs/13-conventions.test.ts` — naming, factory pattern, type extension, config injection- `nodejs/src/ingestion/framework/steps.ts` — `ProcessingStep<T, U>` type definition- `nodejs/src/ingestion/framework/results.ts` — result constructors and types+- `nodejs/src/ingestion/framework/docs/17-fan-out-fan-in.test.ts` — fan-out/fan-in function conventionsAlso read any files the user points you to.@@ -166,6 +167,25 @@ function createMySubpipeline<T extends RequiredInput, C>(}```+### 9. Fan-out/fan-in functions++`FanOutFunction`/`FanInFunction` follow the step conventions: named functions (their `.name`+feeds error attribution), defined in step files, created by factories where they need config.+Both must be cheap and synchronous — heavy or async work belongs in the sub-pipeline's steps.+The fan-in receives only the OK sub-results that survived (possibly fewer than were fanned+out) and must handle that. Any team/message data a sub-step needs goes into the sub-element+value at fan-out — sub contexts do not carry the parent's context.++```typescript+// GOOD - named, sync, data in the sub-element value+export function extractBlobsFanOut(input: EventWithBlobs): PendingUpload[] {+ return input.blobs.map((blob) => ({ teamId: input.team.id, blob }))+}++// BAD - anonymous and async, doing the heavy work itself+.fanOut(async (input) => await detectAndUpload(input))+```+## Output format### When reviewing codediff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.ymlindex 0148e73b72d7..6971b021aa71 100644--- a/.github/workflows/ci-nodejs.yml+++ b/.github/workflows/ci-nodejs.yml@@ -289,8 +289,11 @@ jobs:with:install-command: pnpm --filter=@posthog/nodejs... install --frozen-lockfile- - name: Wait for Clickhouse, Redis, Kafka, Localstack- run: docker compose -f docker-compose.dev.yml up kafka redis7 clickhouse maildev localstack -d --wait+ - name: Wait for Clickhouse, Redis, Kafka, Localstack, SeaweedFS+ # seaweedfs backs the blob-store integration tests; the profile-scoped+ # stack launch above never starts it (it sits in the replay/agents+ # profiles), so start it explicitly here — no profiles overlay in play.+ run: docker compose -f docker-compose.dev.yml up kafka redis7 clickhouse maildev localstack seaweedfs -d --wait- name: Create Kafka topicsrun: docker compose -f docker-compose.dev.yml up kafka-initdiff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.test.tsindex 56afa303f047..325b0f70adb3 100644--- a/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.test.ts@@ -10,7 +10,7 @@ import { TeamManager } from '~/common/utils/team-manager'import { UUIDT } from '~/common/utils/utils'import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'import { createOkContext } from '~/ingestion/framework/helpers'-import { dlq, drop, isDropResult, isOkResult, ok, redirect } from '~/ingestion/framework/results'+import { PipelineResult, dlq, drop, isDropResult, isOkResult, ok, redirect } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'import { PluginEvent } from '~/plugin-scaffold'import { createTestTeam } from '~/tests/helpers/team'@@ -637,6 +637,106 @@ describe('CommonIngestionPipelineBuilder', () => {])})+ it('fans out through the skeleton and hands the fanned-in value to subsequent team-aware steps', async () => {+ const log: string[] = []+ const merged: string[] = []++ interface EventPart {+ distinctId: string+ index: number+ }++ // user-0 fans out to three parts (one of which the sub-step drops);+ // user-1 fans out to nothing and completes via fanIn(input, []).+ function splitPartsFanOut(input: { event: PluginEvent }): EventPart[] {+ const count = input.event.distinct_id === 'user-0' ? 3 : 0+ return Array.from({ length: count }, (_, index) => ({ distinctId: input.event.distinct_id, index }))+ }++ function processPartStep(part: EventPart): Promise<PipelineResult<EventPart>> {+ if (part.index === 1) {+ return Promise.resolve(drop('skipped part'))+ }+ log.push(`part:${part.distinctId}:${part.index}`)+ return Promise.resolve(ok(part))+ }++ function collectPartsFanIn<T extends { event: PluginEvent }>(original: T, parts: EventPart[]): T {+ return {+ ...original,+ event: {+ ...original.event,+ properties: {+ ...original.event.properties,+ part_indexes: parts.map((part) => part.index).sort(),+ },+ },+ }+ }++ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)+ .parseHeaders()+ .parseMessage()+ .resolveTeam()+ .pipe(teamLogStep(log, 'A'))+ .fanOut(splitPartsFanOut)+ .via((sub) => sub.concurrently((b) => b.pipe(processPartStep)))+ .fanIn(collectPartsFanIn)+ .pipe(function recordMergedStep(input) {+ merged.push(`${input.event.distinct_id}:${JSON.stringify(input.event.properties!.part_indexes)}`)+ return Promise.resolve(ok(input))+ })+ .build()++ const batches = await runPipeline(pipeline, [createMessage('user-0'), createMessage('user-1')])++ // The open sequential block (A) was committed before the fan-out stage.+ expect(log).toEqual(['A:user-0', 'A:user-1', 'part:user-0:0', 'part:user-0:2'])+ // Downstream team-aware steps see the fanned-in values: user-0 keeps+ // the surviving parts (the dropped one excluded), user-1 fans in empty.+ expect(merged.sort()).toEqual(['user-0:[0,2]', 'user-1:[]'])+ expect(okValues(batches)).toHaveLength(2)+ })++ it('routes warnings from fan-out sub-steps to the warnings output with the resolved team', async () => {+ interface EventPart {+ distinctId: string+ }++ function splitSingleFanOut(input: { event: PluginEvent }): EventPart[] {+ return [{ distinctId: input.event.distinct_id }]+ }++ function warnPartStep(part: EventPart): Promise<PipelineResult<EventPart>> {+ return Promise.resolve(+ ok(part, [], [{ type: 'client_ingestion_warning', details: { marker: 'sub-step' }, alwaysSend: true }])+ )+ }++ function keepOriginalFanIn<T>(original: T): T {+ return original+ }++ const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)+ .parseHeaders()+ .parseMessage()+ .resolveTeam()+ .fanOut(splitSingleFanOut)+ .via((sub) => sub.concurrently((b) => b.pipe(warnPartStep)))+ .fanIn(keepOriginalFanIn)+ .build()++ await runPipeline(pipeline, [createMessage('user-0')])++ // The stage sits inside the team-aware warning scope: a warning raised+ // on a sub-element lands on the parent and routes with the resolved team.+ const warnings = warningsProduced()+ expect(warnings).toHaveLength(1)+ expect(warnings[0].team_id).toBe(42)+ expect(warnings[0].type).toBe('client_ingestion_warning')+ expect(parseJSON(warnings[0].details).marker).toBe('sub-step')+ })+it('applies the resolveTeam wrap decorator around team resolution', async () => {const wrapObserved: string[] = []const pipeline = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)@@ -736,5 +836,32 @@ describe('CommonIngestionPipelineBuilder', () => {expect(narrowed).toBeDefined()})++ it('rejects an unclosed fan-out stage at compile time', () => {+ const teamStage = newCommonIngestionPipeline<MessageOnly, MessageOnly>(config)+ .parseHeaders()+ .parseMessage()+ .resolveTeam()++ const opened = teamStage.fanOut(function splitFanOut(input) {+ return [input.team.id]+ })++ // @ts-expect-error fanIn is only available after via()+ const _noEarlyFanIn = opened.fanIn+ // @ts-expect-error an unclosed fan-out stage cannot be built+ const _noFanOutBuild = opened.build+ // @ts-expect-error an unclosed fan-out stage cannot register afterBatch hooks+ const _noFanOutAfterBatch = opened.afterBatch++ const routed = opened.via((sub) => sub)++ // @ts-expect-error only fanIn can close the stage+ const _noFanInBuild = routed.build+ // @ts-expect-error only fanIn can close the stage+ const _noFanInAfterBatch = routed.afterBatch++ expect(routed).toBeDefined()+ })})})diff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.tsindex 5beee425d728..15b2c78c2685 100644--- a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.ts@@ -17,6 +17,7 @@ import { newBatchingPipeline } from '~/ingestion/framework/builders'import { ChunkPipelineBuilder, GroupProcessingBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'import { PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/builders/pipeline-builders'import { GroupingFunction } from '~/ingestion/framework/concurrently-grouping-chunk-pipeline'+import { FanInFunction, FanOutFunction, FanOutSubContext } from '~/ingestion/framework/fan-out-fan-in-chunk-pipeline'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'import { ok } from '~/ingestion/framework/results'import { RetryOptions } from '~/ingestion/framework/retry'@@ -44,7 +45,9 @@ import { addTeamToContext } from './subpipelines/helpers'* body steps .pipe* resolve team, lift team into context .resolveTeam()* team-aware processing .pipe / .pipeChunk / .gather /- * .concurrentlyPerGroup / .compose+ * .concurrentlyPerGroup /+ * .fanOut(…).via(…).fanIn(…) /+ * .compose* handleIngestionWarnings (automatic)* handleResults (automatic)* handleSideEffects (automatic)@@ -52,7 +55,7 @@ import { addTeamToContext } from './subpipelines/helpers'* ```** Consecutive `.pipe()` calls coalesce into one sequential per-element block;- * any chunk-level call (`.pipeChunk`, `.gather`, `.concurrentlyPerGroup`,+ * any chunk-level call (`.pipeChunk`, `.gather`, `.concurrentlyPerGroup`, `.fanOut`,* `.compose`, a phase marker that is chunk-level) closes the block. Block* boundaries therefore fall out of where the chunk operations sit, which is* how the hand-written pipelines were already shaped.@@ -323,6 +326,18 @@ export class CommonPreTeamStage<}}+/**+ * Subpipeline callback of a fan-out stage. Sub-pipelines are context-agnostic+ * (typed over the minimal base context, not the team-aware context): context+ * gated surface like `teamAware` or `handleIngestionWarnings` is uncallable+ * inside — sub warnings/side effects merge into the parent and are handled+ * once by the skeleton. Fan-out functions put any team/message data sub-steps+ * need into the sub-element value.+ */+type FanOutViaCallback<TSub, TSubOut, ROut extends string> = (+ builder: ChunkPipelineBuilder<TSub, TSub, FanOutSubContext, FanOutSubContext>+) => ChunkPipelineBuilder<TSub, TSubOut, FanOutSubContext, FanOutSubContext, ROut>+export class CommonTeamStage<TInput extends { message: Message },TContext extends { message: Message },@@ -397,6 +412,31 @@ export class CommonTeamStage<)}+ /**+ * Open a fan-out/fan-in stage: `.fanOut(fn).via(cb).fanIn(fn)` (mirrors+ * the framework method — the staged sequencing holds on the skeleton+ * surface too, so an unclosed stage can't reach `afterBatch`/`build`).+ */+ fanOut<TSub>(+ fanOutFn: FanOutFunction<TCurrent, TSub>+ ): CommonFanOutStage<TInput, TContext, ROut, CBatch, TPost, TCurrent, TSub> {+ const committed = this.chain.build()+ return new CommonFanOutStage(+ <TSubOut, U>(+ subpipelineCallback: FanOutViaCallback<TSub, TSubOut, ROut>,+ fanInFn: FanInFunction<TCurrent, TSubOut, U>+ ) =>+ new CommonTeamStage(+ this.config,+ this.beforeBatchCallback,+ this.preTeamTransform,+ committedChain((builder) =>+ committed(builder).fanOut(fanOutFn).via(subpipelineCallback).fanIn(fanInFn)+ )+ )+ )+ }+/** Escape hatch: apply a subpipeline function (a transform over the chunk builder). */compose<U>(fn: (@@ -434,6 +474,70 @@ export class CommonTeamStage<}}+/**+ * Middle stage of the skeleton's `.fanOut(fn).via(cb).fanIn(fn)`. Its only+ * method is `via`, so an unclosed fan-out stage cannot reach `afterBatch` or+ * `build`.+ */+export class CommonFanOutStage<+ TInput extends { message: Message },+ TContext extends { message: Message },+ ROut extends string,+ CBatch,+ TPost extends { team: Team },+ TCurrent,+ TSub,+> {+ // Completion-closure shape, like the framework's FanOutBuilder: TCurrent+ // only appears in variance-neutral positions.+ constructor(+ private readonly completeStage: <TSubOut, U>(+ subpipelineCallback: FanOutViaCallback<TSub, TSubOut, ROut>,+ fanInFn: FanInFunction<TCurrent, TSubOut, U>+ ) => CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U>+ ) {}++ /**+ * Route the sub-elements through a subpipeline built on the full chunk+ * builder surface, under the team-aware context (exactly what `compose`+ * would provide).+ */+ via<TSubOut>(+ subpipelineCallback: FanOutViaCallback<TSub, TSubOut, ROut>+ ): CommonFanInStage<TInput, TContext, ROut, CBatch, TPost, TCurrent, TSubOut> {+ return new CommonFanInStage(<U>(fanInFn: FanInFunction<TCurrent, TSubOut, U>) =>+ this.completeStage(subpipelineCallback, fanInFn)+ )+ }+}++/**+ * Final stage of the skeleton's `.fanOut(fn).via(cb).fanIn(fn)`. Its only+ * method is `fanIn`, which closes the stage and returns the regular+ * {@link CommonTeamStage} surface.+ */+export class CommonFanInStage<+ TInput extends { message: Message },+ TContext extends { message: Message },+ ROut extends string,+ CBatch,+ TPost extends { team: Team },+ TCurrent,+ TSubOut,+> {+ // Completion-closure shape for the same variance reason as CommonFanOutStage.+ constructor(+ private readonly completeStage: <U>(+ fanInFn: FanInFunction<TCurrent, TSubOut, U>+ ) => CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U>+ ) {}++ /** Close the stage: fold each parent's collected sub-results back into the original element. */+ fanIn<U>(fanInFn: FanInFunction<TCurrent, TSubOut, U>): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U> {+ return this.completeStage(fanInFn)+ }+}+export class CommonBuildStage<TInput extends { message: Message },TContext extends { message: Message },diff --git a/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.ts b/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.tsindex 43346c1723ee..40c269e1f9b5 100644--- a/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/split-ai-events-step.ts@@ -1,20 +1,12 @@import { AI_EVENTS_OUTPUT, AiEventOutput, EventOutput } from '~/common/outputs'import { AI_EVENT_TYPES } from '~/ingestion/common/subpipelines/ai-event-types'+import { LARGE_AI_PROPERTIES } from '~/ingestion/common/subpipelines/large-ai-properties'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'import { ProcessedEvent } from '~/types'import { EventToEmit } from './emit-event-step'-const LARGE_AI_PROPERTIES = new Set([- '$ai_input',- '$ai_output',- '$ai_output_choices',- '$ai_input_state',- '$ai_output_state',- '$ai_tools',-])-export interface SplitAiEventsStepInput {eventsToEmit: EventToEmit<EventOutput>[]teamId: numberdiff --git a/nodejs/src/ingestion/common/subpipelines/large-ai-properties.ts b/nodejs/src/ingestion/common/subpipelines/large-ai-properties.tsnew file mode 100644index 000000000000..ca4ba6e59cad--- /dev/null+++ b/nodejs/src/ingestion/common/subpipelines/large-ai-properties.ts@@ -0,0 +1,9 @@+// Heavy AI property names, shared by the events/ai_events splitter and the ai lane's blob offload.+export const LARGE_AI_PROPERTIES = new Set([+ '$ai_input',+ '$ai_output',+ '$ai_output_choices',+ '$ai_input_state',+ '$ai_output_state',+ '$ai_tools',+])diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex a539f75676c5..5fe670974e3d 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -212,6 +212,21 @@ export type IngestionConsumerConfig = {CLICKHOUSE_AI_EVENTS_KAFKA_TOPIC: stringCLICKHOUSE_HEATMAPS_KAFKA_TOPIC: string+ // AI blob offload: content-addressed S3 storage for multimodal payloads.+ // Empty bucket or empty teams list disables the offload step entirely.+ AI_BLOB_S3_BUCKET: string+ AI_BLOB_S3_PREFIX: string+ AI_BLOB_S3_ENDPOINT: string+ AI_BLOB_S3_REGION: string+ AI_BLOB_S3_ACCESS_KEY_ID: string+ AI_BLOB_S3_SECRET_ACCESS_KEY: string+ AI_BLOB_S3_TIMEOUT_MS: number+ AI_BLOB_OFFLOAD_TEAMS: string+ AI_BLOB_OFFLOAD_MIN_BASE64_LENGTH: number+ AI_BLOB_OFFLOAD_MAX_BLOBS_PER_EVENT: number+ AI_BLOB_OFFLOAD_UPLOAD_MAX_CONCURRENCY: number+ AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS: number+// Cookieless server hash mode configCOOKIELESS_DISABLED: booleanCOOKIELESS_FORCE_STATELESS_MODE: boolean@@ -327,6 +342,26 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {CLICKHOUSE_AI_EVENTS_KAFKA_TOPIC: KAFKA_CLICKHOUSE_AI_EVENTS_JSON,CLICKHOUSE_HEATMAPS_KAFKA_TOPIC: KAFKA_CLICKHOUSE_HEATMAP_EVENTS,+ // AI blob offload: content-addressed S3 storage for multimodal payloads.+ // Empty bucket or empty teams list disables the offload step entirely.+ AI_BLOB_S3_BUCKET: '',+ // Bucket+prefix are a shared contract with the Django read side (posthog/settings/+ // object_storage.py) — defaults must agree or reads 404 while writes succeed.+ AI_BLOB_S3_PREFIX: 'aio/',+ AI_BLOB_S3_ENDPOINT: '',+ AI_BLOB_S3_REGION: 'us-east-1',+ AI_BLOB_S3_ACCESS_KEY_ID: '',+ AI_BLOB_S3_SECRET_ACCESS_KEY: '',+ AI_BLOB_S3_TIMEOUT_MS: 30000,+ AI_BLOB_OFFLOAD_TEAMS: '',+ // Keep the floor above base64-packed embedding vectors so logged embeddings stay inline as text.+ AI_BLOB_OFFLOAD_MIN_BASE64_LENGTH: 20480,+ AI_BLOB_OFFLOAD_MAX_BLOBS_PER_EVENT: 50,+ // Chunk-wide cap on concurrent blob uploads, so blob-heavy traffic+ // can't monopolize the S3 socket pool.+ AI_BLOB_OFFLOAD_UPLOAD_MAX_CONCURRENCY: 8,+ AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS: 20,+// Cookieless server hash mode configCOOKIELESS_DISABLED: false,COOKIELESS_FORCE_STATELESS_MODE: false,diff --git a/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts b/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.tsindex e3d4d4ebf6cc..7a5531f8e2e6 100644--- a/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts+++ b/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts@@ -11,6 +11,12 @@ import {ConcurrentlyGroupingChunkPipeline,GroupingFunction,} from '~/ingestion/framework/concurrently-grouping-chunk-pipeline'+import {+ FanInFunction,+ FanOutFanInChunkPipeline,+ FanOutFunction,+ FanOutSubContext,+} from '~/ingestion/framework/fan-out-fan-in-chunk-pipeline'import { FilterMapChunkPipeline, FilterMapMappingFunction } from '~/ingestion/framework/filter-map-chunk-pipeline'import { GatheringChunkPipeline } from '~/ingestion/framework/gathering-chunk-pipeline'import { IngestionWarningHandlingChunkPipeline } from '~/ingestion/framework/ingestion-warning-handling-chunk-pipeline'@@ -66,6 +72,86 @@ export class GroupProcessingBuilder<}}+/**+ * Middle stage of `.fanOut(fn).via(cb).fanIn(fn)`. Its only method is `via`,+ * so a fan-out stage cannot be built (or have results handled) until it is+ * closed with a subpipeline and a fan-in function.+ */+export class FanOutBuilder<+ TInput,+ TOutput,+ TSub,+ CInput = Record<string, never>,+ COutput = CInput,+ R extends string = never,+> {+ // Holds a completion function instead of the fan-out function and previous+ // pipeline directly, for the same variance reason as GroupProcessingBuilder:+ // in this closure's signature TOutput only appears in variance-neutral+ // positions, keeping ChunkPipelineBuilder covariant in TOutput.+ constructor(+ private readonly buildFannedOutPipeline: <TSubOut, U, RSub extends string>(+ subPipeline: ChunkPipeline<TSub, TSubOut, FanOutSubContext, FanOutSubContext, RSub>,+ fanInFn: FanInFunction<TOutput, TSubOut, U>+ ) => ChunkPipeline<TInput, U, CInput, COutput, R>+ ) {}++ /**+ * Route the sub-elements through a subpipeline built on the full chunk+ * builder surface (`concurrently` with `maxConcurrency`, per-step `retry`,+ * `concurrentlyPerGroup`, …). Sub-elements from all parents share the+ * subpipeline, so one concurrency cap governs the whole stage.+ *+ * Redirect sub-results never escape the stage, so the subpipeline's+ * redirect names (`RSub`) do not propagate to the stage's result type —+ * downstream `handleResults` won't demand outputs for redirects that+ * cannot happen. (A DLQ sub-result does surface, as the parent's+ * aggregated DLQ, which carries no redirect names.)+ */+ via<TSubOut, RSub extends string = never>(+ subpipelineCallback: (+ builder: ChunkPipelineBuilder<TSub, TSub, FanOutSubContext, FanOutSubContext>+ ) => ChunkPipelineBuilder<TSub, TSubOut, FanOutSubContext, FanOutSubContext, RSub>+ ): FanInBuilder<TInput, TOutput, TSubOut, CInput, COutput, R> {+ const startBuilder = new ChunkPipelineBuilder<TSub, TSub, FanOutSubContext, FanOutSubContext>(+ new BufferingChunkPipeline<TSub, FanOutSubContext>()+ )+ const subPipeline = subpipelineCallback(startBuilder).build()+ return new FanInBuilder(<U>(fanInFn: FanInFunction<TOutput, TSubOut, U>) =>+ this.buildFannedOutPipeline(subPipeline, fanInFn)+ )+ }+}++/**+ * Final stage of `.fanOut(fn).via(cb).fanIn(fn)`. Its only method is `fanIn`,+ * which folds the sub-results back into the parent and returns a regular+ * {@link ChunkPipelineBuilder}.+ */+export class FanInBuilder<+ TInput,+ TOutput,+ TSubOut,+ CInput = Record<string, never>,+ COutput = CInput,+ R extends string = never,+> {+ // Completion-closure shape for the same variance reason as FanOutBuilder.+ constructor(+ private readonly buildFannedInPipeline: <U>(+ fanInFn: FanInFunction<TOutput, TSubOut, U>+ ) => ChunkPipeline<TInput, U, CInput, COutput, R>+ ) {}++ /**+ * Close the stage: fold each parent's collected sub-results back into the+ * original element (synchronous, cheap).+ */+ fanIn<U>(fanInFn: FanInFunction<TOutput, TSubOut, U>): ChunkPipelineBuilder<TInput, U, CInput, COutput, R> {+ return new ChunkPipelineBuilder(this.buildFannedInPipeline(fanInFn))+ }+}+export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R extends string = never> {constructor(protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {}@@ -138,6 +224,42 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R e)}+ /**+ * Open a fan-out/fan-in stage: fan each OK element out into sub-elements,+ * process them through a subpipeline, and fan the results back into the+ * original element. The stage is staged so each part reads at the call+ * site — `.fanOut(fn).via((sub) => …).fanIn(fn)` — and only `.fanIn()`+ * closes it into a buildable pipeline.+ *+ * Cardinality is preserved at the parent level (N in, N out); parents emit+ * as they complete (unordered). Non-OK elements pass through unchanged.+ * OK sub-results are collected for the fan-in; dropped sub-elements are+ * silently excluded (DROP is the sanctioned way for a sub-step to discard+ * its sub-element); a DLQ sub-result fails the whole parent, which emits a+ * DLQ aggregating its sub DLQs instead of fanning in; REDIRECT sub-results+ * are excluded with a warning log — sub-elements are not Kafka messages.+ *+ * Like processing steps, the fan-out and fan-in functions are named+ * functions (defined in step files, created by factories where they need+ * config) — their `.name` is used for error attribution.+ *+ * @param fanOutFn - Splits an element into sub-elements (synchronous, cheap)+ */+ fanOut<TSub>(fanOutFn: FanOutFunction<TOutput, TSub>): FanOutBuilder<TInput, TOutput, TSub, CInput, COutput, R> {+ return new FanOutBuilder(+ <TSubOut, U, RSub extends string>(+ subPipeline: ChunkPipeline<TSub, TSubOut, FanOutSubContext, FanOutSubContext, RSub>,+ fanInFn: FanInFunction<TOutput, TSubOut, U>+ ) =>+ new FanOutFanInChunkPipeline<TInput, TOutput, TSub, TSubOut, U, CInput, COutput, R, RSub>(+ this.pipeline,+ fanOutFn,+ subPipeline,+ fanInFn+ )+ )+ }+/*** Group items by key and process the groups concurrently, optionally capped* by `maxConcurrency`. Results are returned unordered as each group completes.diff --git a/nodejs/src/ingestion/framework/docs/17-fan-out-fan-in.test.ts b/nodejs/src/ingestion/framework/docs/17-fan-out-fan-in.test.tsnew file mode 100644index 000000000000..cb47593e5bb0--- /dev/null+++ b/nodejs/src/ingestion/framework/docs/17-fan-out-fan-in.test.ts@@ -0,0 +1,291 @@+/**+ * # Chapter 17: Fan-Out / Fan-In+ *+ * A pipeline step cannot change element cardinality: one element in, one+ * result out. That's the right contract for the pipeline as a whole — every+ * Kafka message must produce exactly one result — but it gets in the way when+ * a single element carries N independent pieces of work (say, an event with+ * several attachments to upload). Without help, the step either processes+ * them sequentially or hand-rolls concurrency inside itself, reinventing the+ * `maxConcurrency` and retry machinery the pipeline already has.+ *+ * The fan-out/fan-in stage contains sub-element cardinality inside itself.+ * It is built in three staged calls — `.fanOut(fn).via(cb).fanIn(fn)` — and+ * the type system enforces the sequence: an unclosed stage exposes nothing+ * but the next call, so only `.fanIn()` yields a buildable pipeline.+ *+ * 1. **`.fanOut(fn)`**: a synchronous function splits each OK element into+ * sub-elements. Zero sub-elements complete the element immediately.+ * 2. **`.via(cb)`**: the sub-elements flow through a regular chunk+ * subpipeline — `concurrently` with `maxConcurrency`, per-step `retry`,+ * `concurrentlyPerGroup`, anything the builder offers. Sub-elements from+ * different parents share the subpipeline, so one concurrency cap governs+ * the whole stage.+ * 3. **`.fanIn(fn)`**: when all of a parent's sub-results are in, a+ * synchronous function folds them back into the parent, which emits as a+ * single OK result. Cardinality at the parent level is preserved:+ * N parents in, N results out.+ *+ * ## Semantics+ *+ * - **Ordering**: parents emit as they complete (unordered), like+ * `concurrentlyPerGroup`.+ * - **Non-OK parents** pass through without fanning out, like `filterMap`.+ * - **Sub-result contract.** OK sub-results are collected for the fan-in.+ * DROP is the sanctioned way for a sub-step to exclude its sub-element —+ * silent, the parent fans in with the survivors (consistent with a+ * zero-fan-out fanning in with `[]`). A DLQ sub-result fails the whole+ * parent: instead of fanning in, the parent emits a DLQ aggregating its sub+ * DLQs (count, distinct reasons, every error via AggregateError) once all+ * siblings have drained — fanning in anyway could emit an element built for+ * work that never happened, like a pointer to a blob that was never stored.+ * REDIRECT sub-results are excluded with a warning log: sub-elements are+ * not Kafka messages, so there is nothing to redirect — route the parent+ * before fanning out instead. Side effects and warnings from every+ * sub-result still merge into the parent. Redirects can't escape the stage+ * (and a DLQ carries no redirect names), so the subpipeline's redirect+ * names don't propagate to the stage's result type.+ * - **Sub-pipelines are context-agnostic**: the `via` builder's context type+ * is `FanOutSubContext` — nothing but a public, opaque correlation token+ * the stage mints per parent (sub steps may see it but can't do anything+ * with it; unknown tokens fail loudly on fan-in). Context-gated surface+ * (`teamAware`, `messageAware`, `handleIngestionWarnings`,+ * `handleResults`) is therefore uncallable inside — sub warnings and side+ * effects merge into the parent and are handled once by the outer+ * pipeline. If sub-steps need team or message data, the fan-out function+ * puts it in the sub-element value.+ * - **Thrown errors** (fan-out, fan-in, or subpipeline) poison the stage+ * permanently after in-flight work drains, like every other chunk stage.+ *+ * Like processing steps, the fan-out and fan-in functions are passed as named+ * functions so error attribution can name them.+ */+import { Message } from 'node-rdkafka'++import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'+import { createOkContext } from '~/ingestion/framework/helpers'+import { drop, isOkResult, ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'+import { createTestMessage } from '~/tests/helpers/kafka-message'++describe('Fan-Out / Fan-In', () => {+ /**+ * The motivating shape: an event carries several attachments that must all+ * be uploaded before the event can move on. Fan-out turns the event into+ * one sub-element per attachment, a `concurrently` subpipeline uploads+ * them under one concurrency cap (shared across all events in the chunk),+ * and fan-in rewrites the event with the upload results.+ */+ it('uploads an element’s attachments concurrently and folds the results back in', async () => {+ interface EventWithAttachments {+ eventId: string+ attachments: string[]+ }++ interface PendingUpload {+ eventId: string+ attachment: string+ }++ interface CompletedUpload {+ attachment: string+ url: string+ }++ interface UploadedEvent {+ eventId: string+ urls: string[]+ }++ let inFlight = 0+ let highWater = 0++ // Fan-out and fan-in are named functions, like steps. Both must be+ // synchronous and cheap — the heavy lifting belongs in the subpipeline.+ function attachmentsFanOut(event: EventWithAttachments): PendingUpload[] {+ return event.attachments.map((attachment) => ({ eventId: event.eventId, attachment }))+ }++ function collectUrlsFanIn(event: EventWithAttachments, uploads: CompletedUpload[]): UploadedEvent {+ return { eventId: event.eventId, urls: uploads.map((u) => u.url).sort() }+ }++ // A regular processing step: per-sub retry options would go right here.+ function createUploadStep(): ProcessingStep<PendingUpload, CompletedUpload> {+ return async function uploadStep(upload) {+ inFlight+++ highWater = Math.max(highWater, inFlight)+ await new Promise((resolve) => setImmediate(resolve))+ inFlight--+ return ok({ attachment: upload.attachment, url: `s3://bucket/${upload.attachment}` })+ }+ }++ const pipeline = newChunkPipelineBuilder<EventWithAttachments, { message: Message }>()+ .fanOut(attachmentsFanOut)+ .via((sub) => sub.concurrently((b) => b.pipe(createUploadStep()), { maxConcurrency: 2 }))+ .fanIn(collectUrlsFanIn)+ .build()++ pipeline.feed([+ createOkContext(+ { eventId: 'e1', attachments: ['a.png', 'b.png', 'c.png'] },+ { message: createTestMessage() }+ ),+ // No attachments: completes immediately via fanIn(event, []).+ createOkContext({ eventId: 'e2', attachments: [] }, { message: createTestMessage() }),+ ])++ const collected: UploadedEvent[] = []+ let chunk = await pipeline.next()+ while (chunk !== null) {+ for (const result of chunk) {+ if (isOkResult(result.result)) {+ collected.push(result.result.value)+ }+ }+ chunk = await pipeline.next()+ }++ // One result per parent, regardless of how many sub-elements each produced.+ expect(collected).toEqual(+ expect.arrayContaining([+ { eventId: 'e1', urls: ['s3://bucket/a.png', 's3://bucket/b.png', 's3://bucket/c.png'] },+ { eventId: 'e2', urls: [] },+ ])+ )+ expect(collected).toHaveLength(2)+ // The cap applied across all sub-elements of all parents.+ expect(highWater).toBeLessThanOrEqual(2)+ })++ /**+ * Retry composes with the stage the same way `maxConcurrency` did above:+ * both are ordinary sub-pipeline knobs, not stage features. Passing+ * `{ retry }` to the per-sub step means a transient failure retries only+ * that sub-element's work — the parent and its sibling sub-elements never+ * notice. Contrast with retrying a monolithic "process everything" parent+ * step, which would redo every sub-element's work on any one failure.+ */+ it('retries a transient sub-step failure without disturbing the parent', async () => {+ interface Job {+ id: string+ parts: number[]+ }++ interface Part {+ parentId: string+ value: number+ }++ let attempts = 0++ function partsFanOut(job: Job): Part[] {+ return job.parts.map((value) => ({ parentId: job.id, value }))+ }++ function sumFanIn(job: Job, parts: Part[]): { id: string; total: number } {+ return { id: job.id, total: parts.reduce((acc, p) => acc + p.value, 0) }+ }++ function createFlakyStep(): ProcessingStep<Part, Part> {+ return function flakyStep(part) {+ attempts+++ if (attempts === 1) {+ // Retriable errors are retried by the step wrapper; the+ // stage itself never sees this failure.+ return Promise.reject(Object.assign(new Error('transient'), { isRetriable: true }))+ }+ return Promise.resolve(ok(part))+ }+ }++ const pipeline = newChunkPipelineBuilder<Job, { message: Message }>()+ .fanOut(partsFanOut)+ .via((sub) => sub.concurrently((b) => b.pipe(createFlakyStep(), { retry: { tries: 3, sleepMs: 1 } })))+ .fanIn(sumFanIn)+ .build()++ pipeline.feed([createOkContext({ id: 'job', parts: [7] }, { message: createTestMessage() })])++ const results = []+ let chunk = await pipeline.next()+ while (chunk !== null) {+ results.push(...chunk)+ chunk = await pipeline.next()+ }++ expect(results).toHaveLength(1)+ expect(isOkResult(results[0].result) && results[0].result.value).toEqual({ id: 'job', total: 7 })+ expect(attempts).toBe(2)+ })++ /**+ * DROP is the sanctioned way for a sub-step to exclude its sub-element:+ * the parent still completes via fan-in, just with the survivors. Use it+ * when a sub-element turns out to need no work — invalid part, cache hit,+ * nothing to upload. (A DLQ sub-result instead fails the whole parent+ * with an aggregated DLQ; REDIRECT is misuse — route the parent before+ * fanning out — and is excluded with a warning log.)+ */+ it('drops a sub-element without failing its parent', async () => {+ interface Item {+ id: string+ parts: number[]+ }++ interface Part {+ parentId: string+ value: number+ }++ function partsFanOut(item: Item): Part[] {+ return item.parts.map((value) => ({ parentId: item.id, value }))+ }++ function sumFanIn(item: Item, parts: Part[]): { id: string; total: number } {+ return { id: item.id, total: parts.reduce((acc, p) => acc + p.value, 0) }+ }++ function createValidatePartStep(): ProcessingStep<Part, Part> {+ return function validatePartStep(part) {+ if (part.value < 0) {+ // Silently exclude this part; the parent fans in without it.+ return Promise.resolve(drop('negative part'))+ }+ return Promise.resolve(ok(part))+ }+ }++ const pipeline = newChunkPipelineBuilder<Item, { message: Message }>()+ .fanOut(partsFanOut)+ .via((sub) => sub.concurrently((b) => b.pipe(createValidatePartStep())))+ .fanIn(sumFanIn)+ .build()++ pipeline.feed([+ createOkContext({ id: 'partly-valid', parts: [1, -2, 3] }, { message: createTestMessage() }),+ createOkContext({ id: 'all-valid', parts: [1, 2] }, { message: createTestMessage() }),+ ])++ const collected: { id: string; total: number }[] = []+ let chunk = await pipeline.next()+ while (chunk !== null) {+ for (const result of chunk) {+ if (isOkResult(result.result)) {+ collected.push(result.result.value)+ }+ }+ chunk = await pipeline.next()+ }++ // Every parent completes OK — the dropped part just contributed nothing.+ expect(collected).toEqual(+ expect.arrayContaining([+ { id: 'partly-valid', total: 4 },+ { id: 'all-valid', total: 3 },+ ])+ )+ expect(collected).toHaveLength(2)+ })+})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.tsnew file mode 100644index 000000000000..ee5d6d02ef96--- /dev/null+++ b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.test.ts@@ -0,0 +1,530 @@+import { Message } from 'node-rdkafka'++import { logger } from '~/common/utils/logger'+import { createTestMessage } from '~/tests/helpers/kafka-message'++import { ChunkPipelineBuilder } from './builders'+import { ChunkPipeline } from './chunk-pipeline.interface'+import { FanOutFanInChunkPipeline, FanOutSubContext } from './fan-out-fan-in-chunk-pipeline'+import { createNewChunkPipeline, createOkContext } from './helpers'+import { PipelineResultWithContext, PipelineWarning } from './pipeline.interface'+import { PipelineResult, dlq, drop, isDlqResult, isOkResult, ok, redirect } from './results'++jest.mock('~/common/utils/logger', () => ({+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}))++const mockLogger = logger as jest.Mocked<typeof logger>++interface Parent {+ id: string+ subs: number[]+}++interface SubItem {+ parentId: string+ value: number+}++interface Merged {+ id: string+ total: number+}++function splitSubs(parent: Parent): SubItem[] {+ return parent.subs.map((value) => ({ parentId: parent.id, value }))+}++function sumSubs(parent: Parent, results: SubItem[]): Merged {+ return { id: parent.id, total: results.reduce((acc, r) => acc + r.value, 0) }+}++function doubleStep(item: SubItem): Promise<PipelineResult<SubItem>> {+ return Promise.resolve(ok({ ...item, value: item.value * 2 }))+}++function deferred(): { promise: Promise<void>; resolve: () => void } {+ let resolve!: () => void+ const promise = new Promise<void>((r) => {+ resolve = r+ })+ return { promise, resolve }+}++function feedParents(pipeline: ChunkPipeline<Parent, unknown, { message: Message }>, parents: Parent[]): void {+ pipeline.feed(parents.map((parent) => createOkContext(parent, { message: createTestMessage() })))+}++async function drainAll<T, R extends string>(+ pipeline: ChunkPipeline<Parent, T, { message: Message }, { message: Message }, R>+): Promise<PipelineResultWithContext<T, { message: Message }, R>[]> {+ const all: PipelineResultWithContext<T, { message: Message }, R>[] = []+ let chunk = await pipeline.next()+ while (chunk !== null) {+ all.push(...chunk)+ chunk = await pipeline.next()+ }+ return all+}++function okValues<T, R extends string>(results: PipelineResultWithContext<T, { message: Message }, R>[]): T[] {+ return results.filter((r) => isOkResult(r.result)).map((r) => (r.result as { value: T }).value)+}++describe('FanOutFanInChunkPipeline', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ })++ it('fans out, processes subs, and fans results back in with one result per parent', async () => {+ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) => sub.concurrently((b) => b.pipe(doubleStep)))+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [+ { id: 'a', subs: [1, 2, 3] },+ { id: 'b', subs: [4] },+ // Zero fan-out: completes immediately via fanInFn(parent, []).+ { id: 'c', subs: [] },+ ])++ const results = await drainAll(pipeline)++ expect(results).toHaveLength(3)+ expect(okValues(results)).toEqual(+ expect.arrayContaining([+ { id: 'a', total: 12 },+ { id: 'b', total: 8 },+ { id: 'c', total: 0 },+ ])+ )+ })++ it('passes non-OK parents through untouched, without fanning them out', async () => {+ const fannedOut: string[] = []+ function trackingFanOut(parent: Parent): SubItem[] {+ fannedOut.push(parent.id)+ return splitSubs(parent)+ }+ function dlqBadParentsStep(parents: Parent[]): Promise<PipelineResult<Parent>[]> {+ return Promise.resolve(parents.map((p) => (p.id === 'bad' ? dlq('bad parent') : ok(p))))+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .pipeChunk(dlqBadParentsStep)+ .fanOut(trackingFanOut)+ .via((sub) => sub.concurrently((b) => b.pipe(doubleStep)))+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [+ { id: 'good', subs: [1] },+ { id: 'bad', subs: [2] },+ ])++ const results = await drainAll(pipeline)++ expect(results).toHaveLength(2)+ const dlqResults = results.filter((r) => isDlqResult(r.result))+ expect(dlqResults).toHaveLength(1)+ expect(dlqResults[0].result).toMatchObject({ reason: 'bad parent' })+ expect(okValues(results)).toEqual([{ id: 'good', total: 2 }])+ expect(fannedOut).toEqual(['good'])+ })++ it('surfaces an empty upstream chunk as an empty chunk, not end of stream', async () => {+ // Direct construction with a mock upstream: [] chunks originate from+ // other stages (e.g. a filterMap passthrough), never from feed().+ const upstream: ChunkPipeline<Parent, Parent, { message: Message }> = {+ feed: jest.fn(),+ next: jest+ .fn()+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([createOkContext({ id: 'a', subs: [2] }, { message: createTestMessage() })])+ .mockResolvedValue(null),+ }+ const pipeline = new FanOutFanInChunkPipeline(+ upstream,+ splitSubs,+ createNewChunkPipeline<SubItem, FanOutSubContext>().build(),+ sumSubs+ )++ // Downstream treats null as "drained", so an empty chunk must surface+ // as [] — and must not stop the stage from processing later chunks.+ expect(await pipeline.next()).toEqual([])+ const second = await pipeline.next()+ expect(okValues(second!)).toEqual([{ id: 'a', total: 2 }])+ expect(await pipeline.next()).toBeNull()+ })++ it('emits parents unordered as they complete, keeping sub-results correlated', async () => {+ const gate = deferred()+ function gatedStep(item: SubItem): Promise<PipelineResult<SubItem>> {+ if (item.parentId === 'slow') {+ return gate.promise.then(() => ok(item))+ }+ return Promise.resolve(ok(item))+ }++ // concurrentlyPerGroup reorders freely across groups, so completion+ // order (not fan-out order) drives parent emission — and each parent+ // must still collect exactly its own sub-results.+ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) =>+ sub.concurrentlyPerGroup(+ (item) => item.parentId,+ (group) => group.sequentially((b) => b.pipe(gatedStep))+ )+ )+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [+ { id: 'slow', subs: [10, 20] },+ { id: 'fast', subs: [1, 2] },+ ])++ const first = await pipeline.next()+ expect(okValues(first!)).toEqual([{ id: 'fast', total: 3 }])++ gate.resolve()+ const second = await pipeline.next()+ expect(okValues(second!)).toEqual([{ id: 'slow', total: 30 }])++ expect(await pipeline.next()).toBeNull()+ })++ it('silently excludes dropped sub-elements and fans in with the survivors', async () => {+ const dropEffect = Promise.resolve('dropped')+ function dropOddSubsStep(items: SubItem[]): Promise<PipelineResult<SubItem>[]> {+ return Promise.resolve(+ items.map((item) => (item.value % 2 === 1 ? drop<SubItem>('odd sub', [dropEffect]) : ok(item)))+ )+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) => sub.pipeChunk(dropOddSubsStep))+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [{ id: 'a', subs: [1, 2, 3] }])++ const results = await drainAll(pipeline)++ // The parent always completes; dropped subs just contribute nothing.+ expect(okValues(results)).toEqual([{ id: 'a', total: 2 }])+ // The dropped sub-result's side effect still rode along on the parent.+ expect(results[0].context.sideEffects).toContain(dropEffect)+ expect(mockLogger.warn).not.toHaveBeenCalled()+ })++ it('excludes redirect sub-results with a warning and still completes the parent', async () => {+ const siblingEffect = Promise.resolve('sibling')+ function redirectFirstSubStep(items: SubItem[]): Promise<PipelineResult<SubItem, 'sub_redirect'>[]> {+ return Promise.resolve(+ items.map((item) => {+ if (item.parentId !== 'redirecting') {+ return ok(item)+ }+ return item.value === 1+ ? redirect<SubItem, 'sub_redirect'>('sub failure', 'sub_redirect')+ : ok(item, [siblingEffect])+ })+ )+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) => sub.pipeChunk(redirectFirstSubStep))+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [+ { id: 'redirecting', subs: [1, 2] },+ { id: 'healthy', subs: [3] },+ ])++ const results = await drainAll(pipeline)++ // Both parents complete OK: the REDIRECT sub-result is excluded like a+ // drop, but loudly — it cannot become the parent's result.+ expect(results).toHaveLength(2)+ expect(okValues(results)).toEqual(+ expect.arrayContaining([+ { id: 'redirecting', total: 2 },+ { id: 'healthy', total: 3 },+ ])+ )+ const redirecting = results.find((r) => isOkResult(r.result) && r.result.value.id === 'redirecting')!+ expect(redirecting.context.sideEffects).toContain(siblingEffect)+ expect(mockLogger.warn).toHaveBeenCalledTimes(1)+ expect(mockLogger.warn).toHaveBeenCalledWith(+ '⚠️',+ 'Fan-out subpipeline produced a redirect result; excluding it',+ {+ fanOutStep: 'splitSubs',+ fanInStep: 'sumSubs',+ resultType: 'REDIRECT',+ reason: 'sub failure',+ }+ )+ })++ it('dlqs the parent when a sub-result dlqs, aggregating after siblings drain', async () => {+ const siblingEffect = Promise.resolve('sibling')+ const subError = new Error('upload exploded')+ const fanInCalls: string[] = []+ function trackingFanIn(parent: Parent, subs: SubItem[]): Merged {+ fanInCalls.push(parent.id)+ return sumSubs(parent, subs)+ }+ function failFirstSubStep(items: SubItem[]): Promise<PipelineResult<SubItem>[]> {+ return Promise.resolve(+ items.map((item) => {+ if (item.parentId !== 'failing') {+ return ok(item)+ }+ return item.value === 1 ? dlq('sub failure', subError) : ok(item, [siblingEffect])+ })+ )+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) => sub.pipeChunk(failFirstSubStep))+ .fanIn(trackingFanIn)+ .build()++ feedParents(pipeline, [+ { id: 'failing', subs: [1, 2] },+ { id: 'healthy', subs: [3] },+ ])++ const results = await drainAll(pipeline)++ expect(results).toHaveLength(2)+ const failed = results.find((r) => isDlqResult(r.result))!+ if (!isDlqResult(failed.result)) {+ throw new Error('expected dlq result')+ }+ expect(failed.result.reason).toBe("1/2 fan-out sub-elements dlq'd: sub failure")+ expect(failed.result.error).toBeInstanceOf(AggregateError)+ expect((failed.result.error as AggregateError).errors).toEqual([subError])+ // The sibling drained first: its side effect rode along on the parent,+ // and error attribution points at the failing sub step.+ expect(failed.context.sideEffects).toContain(siblingEffect)+ expect(failed.context.lastStep).toBe('failFirstSubStep')+ // fanIn never ran for the failed parent — DLQ is first-class, no warn.+ expect(fanInCalls).toEqual(['healthy'])+ expect(okValues(results)).toEqual([{ id: 'healthy', total: 3 }])+ expect(mockLogger.warn).not.toHaveBeenCalled()+ })++ it.each([+ [+ 'aggregates multiple dlq reasons with a count',+ (item: SubItem): PipelineResult<SubItem> => dlq(item.value === 2 ? 'r2' : 'r1'),+ "3/3 fan-out sub-elements dlq'd: r1; r2",+ ],+ [+ 'dlqs the parent even when other subs are dropped',+ (item: SubItem): PipelineResult<SubItem> =>+ item.value === 1 ? dlq('r1') : item.value === 2 ? drop('skipped') : ok(item),+ "1/3 fan-out sub-elements dlq'd: r1",+ ],+ ])('%s', async (_name, resultFor, expectedReason) => {+ function mapSubStep(items: SubItem[]): Promise<PipelineResult<SubItem>[]> {+ return Promise.resolve(items.map(resultFor))+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) => sub.pipeChunk(mapSubStep))+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [{ id: 'a', subs: [1, 2, 3] }])++ const results = await drainAll(pipeline)++ expect(results).toHaveLength(1)+ expect(isDlqResult(results[0].result) && results[0].result.reason).toBe(expectedReason)+ })++ 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>[]> {+ return Promise.resolve(parents.map((p) => ok(p, [outerEffect])))+ }+ function warningStep(item: SubItem): Promise<PipelineResult<SubItem>> {+ const warning: PipelineWarning = {+ type: 'event_dropped_by_transformation',+ details: { value: item.value },+ }+ return Promise.resolve(ok(item, [Promise.resolve(item.value)], [warning]))+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .pipeChunk(attachOuterEffectStep)+ .fanOut(splitSubs)+ .via((sub) => sub.concurrently((b) => b.pipe(warningStep)))+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [{ id: 'a', subs: [1, 2] }])++ const results = await drainAll(pipeline)++ expect(results).toHaveLength(1)+ const context = results[0].context+ // One outer effect + one per sub — nothing duplicated by the fan-out.+ expect(context.sideEffects).toHaveLength(3)+ expect(context.sideEffects).toContain(outerEffect)+ expect(context.warnings).toEqual(+ expect.arrayContaining([+ { type: 'event_dropped_by_transformation', details: { value: 1 } },+ { type: 'event_dropped_by_transformation', details: { value: 2 } },+ ])+ )+ expect(context.warnings).toHaveLength(2)+ })++ it.each([+ [+ 'fan-out function',+ () =>+ createNewChunkPipeline<Parent>()+ .fanOut(function throwingFanOut(): SubItem[] {+ throw new Error('boom')+ })+ .via((sub) => sub.concurrently((b) => b.pipe(doubleStep)))+ .fanIn(sumSubs)+ .build(),+ ],+ [+ 'fan-in function',+ () =>+ createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) => sub.concurrently((b) => b.pipe(doubleStep)))+ .fanIn(function throwingFanIn(): Merged {+ throw new Error('boom')+ })+ .build(),+ ],+ [+ 'sub step',+ () =>+ createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) =>+ sub.concurrently((b) =>+ b.pipe(function throwingStep(): Promise<PipelineResult<SubItem>> {+ return Promise.reject(new Error('boom'))+ })+ )+ )+ .fanIn(sumSubs)+ .build(),+ ],+ ])('poisons the stage permanently when the %s throws', async (_name, createPipeline) => {+ const pipeline = createPipeline()++ feedParents(pipeline, [{ id: 'a', subs: [1] }])++ await expect(drainAll(pipeline)).rejects.toThrow('boom')+ await expect(pipeline.next()).rejects.toThrow('boom')+ })++ it('drains completed parents before surfacing a later sub failure', async () => {+ function doomedStep(item: SubItem): Promise<PipelineResult<SubItem>> {+ if (item.parentId === 'doomed') {+ return Promise.reject(new Error('sub boom'))+ }+ return Promise.resolve(ok(item))+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) => sub.concurrently((b) => b.pipe(doomedStep)))+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [+ { id: 'done', subs: [1] },+ { id: 'doomed', subs: [2] },+ ])++ // The failure is already in flight, but the completed parent must come+ // out first; only then does next() reject — permanently.+ const first = await pipeline.next()+ expect(okValues(first!)).toEqual([{ id: 'done', total: 1 }])+ await expect(pipeline.next()).rejects.toThrow('sub boom')+ await expect(pipeline.next()).rejects.toThrow('sub boom')+ })++ it('routes a batch fed while a prior parent is parked on slow subs', async () => {+ const gate = deferred()+ function gatedStep(item: SubItem): Promise<PipelineResult<SubItem>> {+ if (item.parentId === 'parked') {+ return gate.promise.then(() => ok(item))+ }+ return Promise.resolve(ok(item))+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) =>+ sub.concurrentlyPerGroup(+ (item) => item.parentId,+ (group) => group.sequentially((b) => b.pipe(gatedStep))+ )+ )+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [{ id: 'parked', subs: [1] }])+ const firstPull = pipeline.next()++ // The stage is parked draining the parked parent; a fresh feed must+ // still get routed and complete ahead of it.+ feedParents(pipeline, [{ id: 'late', subs: [2] }])+ const first = await firstPull+ expect(okValues(first!)).toEqual([{ id: 'late', total: 2 }])++ gate.resolve()+ const second = await pipeline.next()+ expect(okValues(second!)).toEqual([{ id: 'parked', total: 1 }])+ })+})++// Type-level assertions: the fanOut → via → fanIn sequence is enforced by the+// type system — an unclosed stage exposes nothing but the next call, so there+// is no way to build (or leak) a stage that was never closed with fanIn. If a+// future edit widens the intermediate builders' surface, this stops compiling.+// Never executed.+function _stagedFanOutApiMustBeClosed(): void {+ const staged = createNewChunkPipeline<Parent>().fanOut(splitSubs)+ // @ts-expect-error fanIn is only available after via()+ const _noEarlyFanIn = staged.fanIn+ // @ts-expect-error an unclosed stage cannot be built+ const _noFanOutBuild = staged.build+ const routed = staged.via((sub) => {+ // @ts-expect-error sub-pipelines are context-agnostic — team-gated surface is uncallable+ sub.teamAware((b) => b)+ // @ts-expect-error sub-pipelines are context-agnostic — message-gated surface is uncallable+ sub.messageAware((b) => b)+ return sub.concurrently((b) => b.pipe(doubleStep))+ })+ // @ts-expect-error only fanIn can close the stage+ const _noFanInBuild = routed.build+ // @ts-expect-error the subpipeline surface is not available on the stage+ const _noPipeChunk = routed.pipeChunk+ // @ts-expect-error an unclosed stage is not a ChunkPipelineBuilder+ const _notABuilder: ChunkPipelineBuilder<Parent, SubItem, { message: Message }> = routed+}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.tsnew file mode 100644index 000000000000..8c91fdad84f0--- /dev/null+++ b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.ts@@ -0,0 +1,341 @@+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'++/**+ * Splits one element into its sub-elements. Must be synchronous and cheap —+ * heavy work belongs in the subpipeline's steps. Passed as a named function+ * (like processing steps) so its `.name` can be used for error attribution.+ */+export type FanOutFunction<TElement, TSub> = (element: TElement) => TSub[]++/**+ * Folds the subpipeline's results back into the original element. Must be+ * synchronous and cheap. Receives the OK sub-results that survived the+ * subpipeline — possibly fewer than were fanned out (excluded sub-elements+ * contribute nothing), possibly none at all.+ */+export type FanInFunction<TElement, TSubOut, TMerged> = (original: TElement, results: TSubOut[]) => TMerged++/**+ * Correlates a sub-element's context back to its parent. A symbol-keyed+ * property survives the `{ ...context }` spreads steps perform, and keeps+ * working when the subpipeline reorders elements (e.g. via+ * `concurrentlyPerGroup`) — index-based correlation would not.+ */+export const FAN_OUT_PARENT = Symbol('fanOutParent')++/**+ * Opaque token correlating a sub-element back to its parent. The stage mints+ * one per fanned-out parent; the private brand makes the type nominal, so no+ * structurally-forged object passes for one. Sub steps may see the token on+ * their context but can't do anything with it — a token the stage doesn't+ * recognize fails loudly on fan-in.+ */+export class FanOutParentRef {+ declare private readonly fanOutParentBrand: never+}++/**+ * The context type sub-elements carry: nothing but the correlation tag (plus+ * the base `PipelineContext` fields, with fresh per-sub arrays). Sub-pipelines+ * are context-agnostic — decoupled from the parent pipeline's context type, so+ * context-gated builder surface (`teamAware`, `messageAware`,+ * `handleIngestionWarnings`, `handleResults`) is uncallable inside them. Not+ * deriving sub contexts from the parent's also keeps an inner nested fan-out's+ * subs from carrying an outer stage's tag.+ */+export type FanOutSubContext = { readonly [FAN_OUT_PARENT]: FanOutParentRef }++interface PendingParent<TElement, TSubOut, C> {+ original: TElement+ /** The element's context, owned by the stage; sub completions push side effects/warnings into it in place. */+ context: PipelineContext<C>+ outstanding: number+ /** How many sub-elements were fanned out, for the aggregated DLQ reason. */+ total: number+ collected: TSubOut[]+ /** Sub DLQs seen so far; when non-empty the parent DLQs instead of fanning in. */+ dlqFailures: { reason: string; error: unknown }[]+ /** lastStep of the most recent DLQ sub-result, for error attribution on the parent. */+ dlqLastStep: string | undefined+}++/**+ * A chunk pipeline stage that fans each OK element out into N sub-elements,+ * processes them through a subpipeline (reusing retry, `concurrently`, etc.),+ * and fans the results back into the original element:+ *+ * 1. `fanOutFn(element)` produces the sub-elements; zero sub-elements complete+ * the parent immediately via `fanInFn(element, [])`.+ * 2. Each sub-element runs through the subpipeline with its own context+ * (fresh sideEffects/warnings arrays, merged back into the parent when the+ * sub-result arrives — so nothing is double-counted).+ * 3. When all of a parent's sub-results are in, the parent settles:+ * - OK contributes its value to `collected`.+ * - DROP is the sanctioned way for a sub-step to exclude a sub-element:+ * it contributes nothing, silently — the parent fans in with the+ * survivors, consistent with a zero-fan-out fanning in with `[]`.+ * - DLQ fails the whole parent: instead of fanning in, the parent emits a+ * DLQ aggregating its sub DLQs (count, distinct reasons, and every sub+ * 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.+ * - 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.+ * Side effects and warnings from every sub-result (OK or not) still merge+ * into the parent context.+ *+ * Cardinality is preserved at the parent level: N parents in, N results out.+ * Sub-element cardinality is fully contained inside the stage — and so are+ * the subpipeline's redirect names: a redirect can never escape as the+ * parent's result (and a DLQ carries no redirect names), so the stage emits+ * only the upstream's redirect names (`RPrev`, not `RPrev | RSub`).+ *+ * Ordering: parents emit as their sub-results complete (unordered), the same+ * contract as `concurrentlyPerGroup`. Non-OK parents pass through untouched.+ *+ * Sub-pipelines are context-agnostic: their context type is+ * {@link FanOutSubContext} — nothing but a public, opaque correlation token —+ * so context-gated surface like `teamAware`, `messageAware`,+ * `handleIngestionWarnings`, and `handleResults` is uncallable inside them.+ * Sub warnings and side effects merge into the parent and are handled once by+ * the outer pipeline. If sub-steps need team or message data, the fan-out+ * function should put it in the sub-element value.+ *+ * Failures poison the stage: if the upstream, `fanOutFn`, `fanInFn`, or the+ * subpipeline throws, results already in flight still drain, then next()+ * rejects with that error permanently (standard {@link InterleavingChunkPipeline}+ * behavior). Retryable failures belong inside the subpipeline via step retry+ * options.+ */+export class FanOutFanInChunkPipeline<+ TInput,+ TElement,+ TSub,+ TSubOut,+ TMerged,+ CInput,+ COutput = CInput,+ RPrev extends string = never,+ RSub extends string = never,+> implements ChunkPipeline<TInput, TMerged, CInput, COutput, RPrev>+{+ private inner: InterleavingChunkPipeline<TInput, TMerged, CInput, COutput, RPrev>+ private pendingParents = new Map<FanOutParentRef, PendingParent<TElement, TSubOut, COutput>>()+ /** Parents completed by sub-results, drained by onProcessPull before pulling the subpipeline again. */+ private readyResults: PipelineResultWithContext<TMerged, COutput, RPrev>[] = []+ private fanOutName: string+ private fanInName: string++ constructor(+ private previousPipeline: ChunkPipeline<TInput, TElement, CInput, COutput, RPrev>,+ private fanOutFn: FanOutFunction<TElement, TSub>,+ private subPipeline: ChunkPipeline<TSub, TSubOut, FanOutSubContext, FanOutSubContext, RSub>,+ private fanInFn: FanInFunction<TElement, TSubOut, TMerged>+ ) {+ this.fanOutName = fanOutFn.name || 'anonymousFanOut'+ this.fanInName = fanInFn.name || 'anonymousFanIn'+ this.inner = new InterleavingChunkPipeline<TInput, TMerged, CInput, COutput, RPrev>({+ onFeed: (elements) => this.previousPipeline.feed(elements),+ onSourcePull: () => this.pullAndFanOut(),+ onProcessPull: () => this.drainAndFanIn(),+ })+ }++ feed(elements: OkResultWithContext<TInput, CInput>[]): void {+ this.inner.feed(elements)+ }++ next(): Promise<ChunkPipelineResultWithContext<TMerged, COutput, RPrev> | null> {+ return this.inner.next()+ }++ /**+ * Pull one chunk from the previous pipeline, fan OK elements out into the+ * subpipeline, and emit everything that is already settled (non-OK+ * passthroughs and zero-fan-out completions) without waiting on the sub.+ */+ private async pullAndFanOut(): Promise<PullOutcome<TMerged, COutput, RPrev>> {+ const previousResults = await this.previousPipeline.next()+ if (previousResults === null) {+ return { kind: 'drained' }+ }++ const settled: PipelineResultWithContext<TMerged, COutput, RPrev>[] = []+ const subElements: OkResultWithContext<TSub, FanOutSubContext>[] = []++ for (const element of previousResults) {+ if (!isOkResult(element.result)) {+ settled.push({ result: element.result, context: element.context })+ continue+ }++ const subs = this.fanOutFn(element.result.value)+ if (subs.length === 0) {+ settled.push(this.completeParent(element.result.value, element.context, []))+ continue+ }++ // Ownership: once pulled, this stage is the element's only holder —+ // upstream stages build a fresh context object (and arrays) per+ // step and retain nothing after emitting the chunk. So the parent+ // keeps the element's context as-is and sub completions push into+ // its arrays in place; the framework's copy-per-step idiom exists+ // to isolate steps from each other, which doesn't apply here.+ const parent: PendingParent<TElement, TSubOut, COutput> = {+ original: element.result.value,+ context: element.context,+ outstanding: subs.length,+ total: subs.length,+ collected: [],+ dlqFailures: [],+ dlqLastStep: undefined,+ }+ const ref = new FanOutParentRef()+ this.pendingParents.set(ref, parent)+ for (const sub of subs) {+ const subContext: PipelineContext<FanOutSubContext> = {+ sideEffects: [],+ warnings: [],+ [FAN_OUT_PARENT]: ref,+ }+ subElements.push({ result: ok(sub), context: subContext })+ }+ }++ if (subElements.length > 0) {+ this.subPipeline.feed(subElements)+ }++ if (settled.length > 0) {+ return { kind: 'emit', chunk: settled }+ }++ // A non-null empty chunk surfaces as [] (a valid empty chunk, distinct+ // from null = end of stream), matching the previous pipeline 1:1.+ if (subElements.length === 0) {+ return { kind: 'emit', chunk: [] }+ }++ return { kind: 'drain' }+ }++ /**+ * Pull the subpipeline, attribute each sub-result to its parent, and emit+ * the parents whose last sub-result just arrived. Propagates the sub's null+ * (the interleaving loop handles re-pull/drained detection) — but a drained+ * sub with parents still pending means sub-results were lost, which the+ * cardinality contract of chunk stages makes impossible; treat it as a bug.+ */+ private async drainAndFanIn(): Promise<ChunkPipelineResultWithContext<TMerged, COutput, RPrev> | null> {+ while (this.readyResults.length === 0) {+ const subResults = await this.subPipeline.next()+ if (subResults === null) {+ if (this.pendingParents.size > 0) {+ throw new Error(+ `Fan-out/fan-in (${this.fanOutName}/${this.fanInName}) subpipeline drained with ` ++ `${this.pendingParents.size} parent(s) still pending — sub-results were lost`+ )+ }+ return null+ }+ for (const subResult of subResults) {+ this.settleSubResult(subResult)+ }+ }+ const chunk = this.readyResults+ this.readyResults = []+ return chunk+ }++ private settleSubResult(subResult: PipelineResultWithContext<TSubOut, FanOutSubContext, RSub>): void {+ const ref = subResult.context[FAN_OUT_PARENT]+ const parent = this.pendingParents.get(ref)+ if (!parent) {+ // Also catches forged or stale tokens: an unknown ref fails loudly+ // here instead of silently settling against whatever it pointed at.+ throw new Error(+ `Fan-out/fan-in (${this.fanOutName}/${this.fanInName}) received a sub-result without a ` ++ `known parent tag — the subpipeline must preserve context`+ )+ }++ // Sub contexts start with fresh arrays, so this merges exactly what the+ // sub-steps produced — for excluded sub-results too. The pushes land in+ // the parent's owned context (see pullAndFanOut).+ parent.context.sideEffects.push(...subResult.context.sideEffects)+ parent.context.warnings.push(...subResult.context.warnings)++ if (isOkResult(subResult.result)) {+ parent.collected.push(subResult.result.value)+ } 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+ // never happened. The parent's DLQ is emitted once every sibling+ // has drained.+ parent.dlqFailures.push({ reason: subResult.result.reason, error: subResult.result.error })+ parent.dlqLastStep = subResult.context.lastStep+ } else if (!isDropResult(subResult.result)) {+ // DROP is the sanctioned exclusion; a REDIRECT for a sub-element is+ // almost certainly misuse — sub-elements are not Kafka messages, so+ // there is nothing to redirect. Excluded like a drop, but loudly.+ logger.warn('⚠️', 'Fan-out subpipeline produced a redirect result; excluding it', {+ fanOutStep: this.fanOutName,+ fanInStep: this.fanInName,+ resultType: PipelineResultType[subResult.result.type],+ reason: subResult.result.reason,+ })+ }++ parent.outstanding -= 1+ if (parent.outstanding > 0) {+ return+ }++ this.pendingParents.delete(ref)+ if (parent.dlqFailures.length > 0) {+ this.readyResults.push(this.failParent(parent))+ } else {+ this.readyResults.push(this.completeParent(parent.original, parent.context, parent.collected))+ }+ }++ /**+ * 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+ * and warnings; collected values are discarded.+ */+ private failParent(+ parent: PendingParent<TElement, TSubOut, COutput>+ ): PipelineResultWithContext<TMerged, COutput, RPrev> {+ const reasons = [...new Set(parent.dlqFailures.map((failure) => failure.reason))]+ const reason = `${parent.dlqFailures.length}/${parent.total} fan-out sub-elements dlq'd: ${reasons.join('; ')}`+ parent.context.lastStep = parent.dlqLastStep+ return {+ result: dlq(+ reason,+ new AggregateError(+ parent.dlqFailures.map((failure) => failure.error),+ reason+ )+ ),+ context: parent.context,+ }+ }++ private completeParent(+ original: TElement,+ context: PipelineContext<COutput>,+ collected: TSubOut[]+ ): PipelineResultWithContext<TMerged, COutput, RPrev> {+ // Same ownership invariant as in pullAndFanOut: the context is+ // uniquely held by this stage, so set lastStep in place.+ context.lastStep = this.fanInName+ return { result: ok(this.fanInFn(original, collected)), context }+ }+}diff --git a/nodejs/src/ingestion/pipelines/ai/blob-offload/base64.test.ts b/nodejs/src/ingestion/pipelines/ai/blob-offload/base64.test.tsnew file mode 100644index 000000000000..66cc7e65597f--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/blob-offload/base64.test.ts@@ -0,0 +1,35 @@+import { decodeCanonicalBase64, isCanonicalBase64 } from './base64'++const BLOB = Buffer.alloc(9000, 5)+const B64 = BLOB.toString('base64')++describe('canonical base64 core', () => {+ it('decodes canonical base64 to the exact bytes', () => {+ expect(decodeCanonicalBase64(B64)?.equals(BLOB)).toBe(true)+ })++ it.each([+ ['interior whitespace', `${B64.slice(0, 6000)}\n${B64.slice(6001)}`],+ ['interior padding', 'AAAA=AAA'],+ ['base64url dash', 'AAA-AAAA'.repeat(1024)],+ ['base64url underscore', 'AAA_AAAA'.repeat(1024)],+ ['length not multiple of 4', 'AAAAA'],+ ['nonzero discarded bits, double padding', 'AAAAAB=='],+ ['nonzero discarded bits, single padding', 'AAAAAAB='],+ ['empty string', ''],+ ])('rejects non-canonical input: %s', (_name, candidate) => {+ expect(decodeCanonicalBase64(candidate)).toBeNull()+ })++ it.each([+ ['zero discarded bits, double padding', 'AAAAAA=='],+ ['zero discarded bits, single padding', 'AAAAAAA='],+ ])('accepts canonical padded input: %s', (_name, candidate) => {+ expect(decodeCanonicalBase64(candidate)).not.toBeNull()+ })++ it('is a type guard rejecting non-strings', () => {+ expect(isCanonicalBase64(12345)).toBe(false)+ expect(isCanonicalBase64(B64)).toBe(true)+ })+})diff --git a/nodejs/src/ingestion/pipelines/ai/blob-offload/base64.ts b/nodejs/src/ingestion/pipelines/ai/blob-offload/base64.tsnew file mode 100644index 000000000000..a211e52e22b9--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/blob-offload/base64.ts@@ -0,0 +1,54 @@+/**+ * Canonical base64 grammar for blob offload — the only module that validates or+ * decodes base64. Guarantee: when decodeCanonicalBase64 returns bytes,+ * bytes.toString('base64') === candidate, so replacing the string with a pointer+ * is exactly invertible. Node's lenient decoder (skips invalid chars, accepts+ * base64url, stops at interior '=') must never be reached with unvalidated input;+ * the full-string scan below is load-bearing and must not be sampled away.+ */++const CANONICAL_BASE64 = /^[A-Za-z0-9+/]+={0,2}$/+const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'+const WINDOW_CHARS = 64++// Encoders emit zero discarded bits in the final quantum; nonzero bits would+// decode and re-encode to a different string, breaking invertibility.+function discardedBitsAreZero(candidate: string): boolean {+ if (candidate.endsWith('==')) {+ const index = BASE64_ALPHABET.indexOf(candidate[candidate.length - 3])+ return index >= 0 && (index & 0b1111) === 0+ }+ if (candidate.endsWith('=')) {+ const index = BASE64_ALPHABET.indexOf(candidate[candidate.length - 2])+ return index >= 0 && (index & 0b11) === 0+ }+ return true+}++// Reject-path pre-filter: long almost-base64 strings (wrapped base64, prose,+// hex with separators) die on an O(1) window instead of a full scan.+function windowsLookCanonical(candidate: string): boolean {+ if (candidate.length <= WINDOW_CHARS * 2) {+ return true+ }+ return (+ CANONICAL_BASE64.test(candidate.slice(0, WINDOW_CHARS)) && CANONICAL_BASE64.test(candidate.slice(-WINDOW_CHARS))+ )+}++export function isCanonicalBase64(value: unknown): value is string {+ return (+ typeof value === 'string' &&+ value.length > 0 &&+ value.length % 4 === 0 &&+ CANONICAL_BASE64.test(value) &&+ discardedBitsAreZero(value)+ )+}++export function decodeCanonicalBase64(candidate: string): Buffer | null {+ if (!windowsLookCanonical(candidate) || !isCanonicalBase64(candidate)) {+ return null+ }+ return Buffer.from(candidate, 'base64')+}diff --git a/nodejs/src/ingestion/pipelines/ai/blob-offload/blob-store.integration.test.ts b/nodejs/src/ingestion/pipelines/ai/blob-offload/blob-store.integration.test.tsnew file mode 100644index 000000000000..3964e839c6cd--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/blob-offload/blob-store.integration.test.ts@@ -0,0 +1,130 @@+import {+ CreateBucketCommand,+ DeleteObjectCommand,+ GetObjectCommand,+ HeadObjectCommand,+ S3Client,+} from '@aws-sdk/client-s3'++import { BlobStoreError, S3BlobStore } from './blob-store'++jest.setTimeout(30000)++// The dev stack's S3-compatible store: the SeaweedFS `seaweedfs` service on+// :8333 — the same instance and bucket session replay v2 uses+// (SESSION_RECORDING_V2_S3_*, whose defaults this connection config mirrors).+// The service sits behind the replay/agents compose profiles, so the Node.js+// Tests CI job starts it explicitly (see ci-nodejs.yml); locally run+// `docker compose -f docker-compose.dev.yml up seaweedfs -d --wait`.+// The shared `posthog` bucket is deliberate: SeaweedFS maps each bucket to a+// collection with its own volume slots, and the dev node's 8 slots are already+// allocated — a dedicated test bucket would hang on volume assignment.+const ENDPOINT = 'http://localhost:8333'+const BUCKET = 'posthog'+// URL-significant characters on purpose (the percent-encoded CopySource was a+// prior review finding, and only a real implementation can falsify it); a+// per-run segment keeps reruns from seeing earlier objects.+const PREFIX = `ai blobs it/v+1/${Date.now()}/`+const TIMEOUT_MS = 10000++describe('S3BlobStore (integration)', () => {+ let s3: S3Client+ const storedKeys: string[] = []++ const makeStore = (touchAfterMs: number): S3BlobStore =>+ new S3BlobStore(s3, { bucket: BUCKET, prefix: PREFIX, touchAfterMs, timeoutMs: TIMEOUT_MS })++ const makeBlob = (suffix: string): { hash: string; bytes: Buffer; mime: string } => {+ const hash = `it-${Date.now()}-${suffix}`+ storedKeys.push(`${PREFIX}2/sha256/${hash}`)+ return { hash, bytes: Buffer.from(`payload-${suffix}`), mime: 'image/png' }+ }++ const keyFor = (blob: { hash: string }): string => `${PREFIX}2/sha256/${blob.hash}`++ beforeAll(async () => {+ s3 = new S3Client({+ region: 'us-east-1',+ endpoint: ENDPOINT,+ forcePathStyle: true,+ // The dev instance runs in open-access mode; any credentials sign.+ credentials: { accessKeyId: 'any', secretAccessKey: 'any' },+ })+ try {+ await s3.send(new CreateBucketCommand({ Bucket: BUCKET }))+ } catch (error) {+ const name = error instanceof Error ? error.name : ''+ if (name !== 'BucketAlreadyOwnedByYou' && name !== 'BucketAlreadyExists') {+ throw error+ }+ }+ storedKeys.push(`${PREFIX}_health/probe`)+ })++ afterAll(async () => {+ await Promise.all(+ storedKeys.map((Key) => s3.send(new DeleteObjectCommand({ Bucket: BUCKET, Key })).catch(() => undefined))+ )+ s3.destroy()+ })++ it('uploads a new blob on a real 404 head-miss and stores bytes with the detected mime', async () => {+ const store = makeStore(20 * 3600 * 1000)+ const blob = makeBlob('upload')++ // 'uploaded' proves the head-miss branch ran: `instanceof NotFound`+ // narrowed a real SeaweedFS 404, which no mocked SDK error can falsify.+ await expect(store.ensureStored(2, blob)).resolves.toBe('uploaded')++ const head = await s3.send(new HeadObjectCommand({ Bucket: BUCKET, Key: keyFor(blob) }))+ expect(head.ContentType).toBe('image/png')+ expect(head.ContentLength).toBe(blob.bytes.length)+ const got = await s3.send(new GetObjectCommand({ Bucket: BUCKET, Key: keyFor(blob) }))+ const body = Buffer.from(await got.Body!.transformToByteArray())+ expect(body.equals(blob.bytes)).toBe(true)+ })++ it('returns fresh on an immediate second call without re-uploading', async () => {+ const store = makeStore(20 * 3600 * 1000)+ const blob = makeBlob('fresh')++ await expect(store.ensureStored(2, blob)).resolves.toBe('uploaded')+ await expect(store.ensureStored(2, blob)).resolves.toBe('fresh')+ })++ it('touches a stale object via a real self-copy with the percent-encoded CopySource', async () => {+ // touchAfterMs -1 forces the touch path deterministically even when+ // LastModified (second-truncated) rounds to "now".+ const store = makeStore(-1)+ const blob = makeBlob('touch')++ await expect(store.ensureStored(2, blob)).resolves.toBe('uploaded')+ // Validates CopyObject with MetadataDirective REPLACE and the+ // percent-encoded CopySource against a real implementation.+ await expect(store.ensureStored(2, blob)).resolves.toBe('touched')++ const head = await s3.send(new HeadObjectCommand({ Bucket: BUCKET, Key: keyFor(blob) }))+ expect(head.ContentType).toBe('image/png')+ expect(head.ContentLength).toBe(blob.bytes.length)+ })++ it('healthcheck self-test passes against the real bucket', async () => {+ await expect(makeStore(20 * 3600 * 1000).healthcheck()).resolves.toBeUndefined()+ })++ it('healthcheck fails with a retriable store error naming the op for a nonexistent bucket', async () => {+ const missing = new S3BlobStore(s3, {+ bucket: 'aio-blob-store-it-missing',+ prefix: PREFIX,+ touchAfterMs: 0,+ timeoutMs: TIMEOUT_MS,+ })+ const error = await missing.healthcheck().then(+ () => null,+ (e: BlobStoreError) => e+ )+ expect(error).toBeInstanceOf(BlobStoreError)+ expect(error!.isRetriable).toBe(true)+ expect(error!.message).toContain('failed (put) for bucket "aio-blob-store-it-missing"')+ })+})diff --git a/nodejs/src/ingestion/pipelines/ai/blob-offload/blob-store.test.ts b/nodejs/src/ingestion/pipelines/ai/blob-offload/blob-store.test.tsnew file mode 100644index 000000000000..c5a47e588187--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/blob-offload/blob-store.test.ts@@ -0,0 +1,274 @@+import {+ CopyObjectCommand,+ HeadObjectCommand,+ NoSuchKey,+ NotFound,+ PutObjectCommand,+ S3Client,+ S3ServiceException,+} from '@aws-sdk/client-s3'++import { aiBlobOffloadS3Errors } from '~/ingestion/pipelines/ai/metrics'++import { BlobStoreError, S3BlobStore, buildAiBlobStore } from './blob-store'++const HASH = 'b'.repeat(64)+const BLOB = { hash: HASH, bytes: Buffer.from('payload'), mime: 'image/png' }+const NOW = new Date('2026-07-16T12:00:00Z')++function notFound(): NotFound {+ return new NotFound({ $metadata: {}, message: 'not found' })+}++/** Unmodeled S3 errors deserialize into the generic S3ServiceException with the code in `.name`. */+function s3Error(name: string): S3ServiceException {+ return new S3ServiceException({ name, $fault: 'client', $metadata: {}, message: name })+}++async function captureError(promise: Promise<unknown>): Promise<BlobStoreError> {+ try {+ await promise+ } catch (error) {+ return error as BlobStoreError+ }+ throw new Error('expected rejection')+}++describe('S3BlobStore', () => {+ let s3: S3Client+ let send: jest.SpyInstance++ beforeEach(() => {+ jest.useFakeTimers().setSystemTime(NOW)+ s3 = new S3Client({ region: 'us-east-1' })+ send = jest.spyOn(s3, 'send')+ })++ afterEach(() => {+ jest.useRealTimers()+ jest.restoreAllMocks()+ })++ function store(): S3BlobStore {+ return new S3BlobStore(s3, { bucket: 'blobs', prefix: 'p/', touchAfterMs: 20 * 3600 * 1000, timeoutMs: 30000 })+ }++ it('uploads on miss with the content-addressed key and mime', async () => {+ send.mockRejectedValueOnce(notFound()).mockResolvedValueOnce({})+ await expect(store().ensureStored(2, BLOB)).resolves.toBe('uploaded')+ expect(send.mock.calls[0][0]).toBeInstanceOf(HeadObjectCommand)+ const put = send.mock.calls[1][0]+ expect(put).toBeInstanceOf(PutObjectCommand)+ expect(put.input).toMatchObject({ Bucket: 'blobs', Key: `p/2/sha256/${HASH}`, ContentType: 'image/png' })+ expect(Buffer.from(put.input.Body).equals(BLOB.bytes)).toBe(true)+ })++ it('does nothing when the object is fresh', async () => {+ send.mockResolvedValueOnce({ LastModified: new Date(NOW.getTime() - 3600 * 1000) })+ await expect(store().ensureStored(2, BLOB)).resolves.toBe('fresh')+ expect(send).toHaveBeenCalledTimes(1)+ })++ it('self-copies to reset the lifecycle clock when the object is stale', async () => {+ send.mockResolvedValueOnce({ LastModified: new Date(NOW.getTime() - 25 * 3600 * 1000) }).mockResolvedValueOnce(+ {}+ )+ await expect(store().ensureStored(2, BLOB)).resolves.toBe('touched')+ const copy = send.mock.calls[1][0]+ expect(copy).toBeInstanceOf(CopyObjectCommand)+ expect(copy.input).toMatchObject({+ Bucket: 'blobs',+ Key: `p/2/sha256/${HASH}`,+ CopySource: `blobs/p/2/sha256/${HASH}`,+ MetadataDirective: 'REPLACE',+ ContentType: 'image/png',+ })+ })++ it('URI-encodes CopySource so prefixes with special characters can refresh', async () => {+ const spaced = new S3BlobStore(s3, {+ bucket: 'blobs',+ prefix: 'ai blobs/v+1/',+ touchAfterMs: 20 * 3600 * 1000,+ timeoutMs: 30000,+ })+ send.mockResolvedValueOnce({ LastModified: new Date(NOW.getTime() - 25 * 3600 * 1000) }).mockResolvedValueOnce(+ {}+ )+ await expect(spaced.ensureStored(2, BLOB)).resolves.toBe('touched')+ const copy = send.mock.calls[1][0]+ expect(copy.input.Key).toBe(`ai blobs/v+1/2/sha256/${HASH}`)+ expect(copy.input.CopySource).toBe(`blobs/ai%20blobs/v%2B1/2/sha256/${HASH}`)+ })++ it('treats a HEAD response without LastModified as stale', async () => {+ send.mockResolvedValueOnce({}).mockResolvedValueOnce({})+ await expect(store().ensureStored(2, BLOB)).resolves.toBe('touched')+ })++ it.each([+ ['HEAD', 0],+ ['PUT after miss', 1],+ ])('propagates non-NotFound failures (%s)', async (_name, failingCall) => {+ const boom = new Error('s3 down')+ if (failingCall === 0) {+ send.mockRejectedValueOnce(boom)+ } else {+ send.mockRejectedValueOnce(notFound()).mockRejectedValueOnce(boom)+ }+ await expect(store().ensureStored(2, BLOB)).rejects.toThrow('s3 down')+ })++ it('does not count HEAD NotFound as S3 failure (normal miss flow) but counts genuine HEAD errors', async () => {+ aiBlobOffloadS3Errors.reset()+ let headErrors = (await aiBlobOffloadS3Errors.get()).values.find((v) => v.labels.op === 'head')?.value ?? 0+ expect(headErrors).toBe(0)++ send.mockRejectedValueOnce(notFound()).mockResolvedValueOnce({})+ const outcome = await store().ensureStored(2, BLOB)+ expect(outcome).toBe('uploaded')++ headErrors = (await aiBlobOffloadS3Errors.get()).values.find((v) => v.labels.op === 'head')?.value ?? 0+ expect(headErrors).toBe(0)++ send.mockRejectedValueOnce(new Error('s3 down'))+ await expect(store().ensureStored(2, BLOB)).rejects.toThrow('s3 down')++ headErrors = (await aiBlobOffloadS3Errors.get()).values.find((v) => v.labels.op === 'head')?.value ?? 0+ expect(headErrors).toBe(1)+ })++ it('returns null when the bucket is unset (offload disabled)', () => {+ const base = {+ AI_BLOB_S3_BUCKET: 'blobs',+ AI_BLOB_S3_PREFIX: '',+ AI_BLOB_S3_ENDPOINT: '',+ AI_BLOB_S3_REGION: 'us-east-1',+ AI_BLOB_S3_ACCESS_KEY_ID: '',+ AI_BLOB_S3_SECRET_ACCESS_KEY: '',+ AI_BLOB_S3_TIMEOUT_MS: 30000,+ AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS: 20,+ }+ expect(buildAiBlobStore({ ...base, AI_BLOB_S3_BUCKET: '' })).toBeNull()+ })++ // The error contract the upload step's retry wrapper depends on: every+ // failure surfaces as BlobStoreError with the provider error as cause.+ // Only provably event-specific failures are non-retriable (-> DLQ);+ // everything else is retriable so transient errors retry and env-wide+ // problems crash loudly after exhaustion instead of dead-lettering a lane.+ it.each([+ ['SlowDown (throttling)', (): Error => s3Error('SlowDown')],+ ['InternalError (5xx)', (): Error => s3Error('InternalError')],+ ['RequestTimeout', (): Error => s3Error('RequestTimeout')],+ ['AccessDenied', (): Error => s3Error('AccessDenied')],+ ['NoSuchBucket', (): Error => s3Error('NoSuchBucket')],+ ['a non-S3 network error', (): Error => new Error('connect ECONNREFUSED')],+ ])('wraps %s as a retriable store error', async (_name, makeError) => {+ const cause = makeError()+ send.mockRejectedValueOnce(cause)+ const error = await captureError(store().ensureStored(2, BLOB))+ expect(error).toBeInstanceOf(BlobStoreError)+ expect(error.isRetriable).toBe(true)+ expect(error.cause).toBe(cause)+ })++ it.each([['EntityTooLarge'], ['MetadataTooLarge']])(+ 'wraps %s as non-retriable — determined by the event, retrying cannot fix it',+ async (name) => {+ const cause = s3Error(name)+ send.mockRejectedValueOnce(notFound()).mockRejectedValueOnce(cause)+ const error = await captureError(store().ensureStored(2, BLOB))+ expect(error).toBeInstanceOf(BlobStoreError)+ expect(error.isRetriable).toBe(false)+ expect(error.cause).toBe(cause)+ }+ )++ it('never interprets event-specific codes on errors that are not S3ServiceException', async () => {+ const impostor = new Error('EntityTooLarge')+ impostor.name = 'EntityTooLarge'+ send.mockRejectedValueOnce(notFound()).mockRejectedValueOnce(impostor)+ const error = await captureError(store().ensureStored(2, BLOB))+ expect(error.isRetriable).toBe(true)+ })++ it('wraps a copy-race NoSuchKey as retriable, and a rerun self-heals via a fresh head', async () => {+ const s = store()+ const race = new NoSuchKey({ $metadata: {}, message: 'gone' })+ send.mockResolvedValueOnce({ LastModified: new Date(NOW.getTime() - 25 * 3600 * 1000) })+ .mockRejectedValueOnce(race)+ .mockRejectedValueOnce(notFound())+ .mockResolvedValueOnce({})+ // The object expired between head and copy: retriable, so the step+ // retry reruns ensureStored, whose fresh head now misses and re-uploads.+ const raceError = await captureError(s.ensureStored(2, BLOB))+ expect(raceError).toBeInstanceOf(BlobStoreError)+ expect(raceError.isRetriable).toBe(true)+ expect(raceError.cause).toBe(race)+ await expect(s.ensureStored(2, BLOB)).resolves.toBe('uploaded')+ expect(send.mock.calls[3][0]).toBeInstanceOf(PutObjectCommand)+ })++ it('healthcheck self-tests every operation ensureStored performs against the sentinel key', async () => {+ send.mockResolvedValue({})+ await expect(store().healthcheck()).resolves.toBeUndefined()+ expect(send.mock.calls).toHaveLength(3)+ const [put, head, copy] = send.mock.calls.map((call) => call[0])+ expect(put).toBeInstanceOf(PutObjectCommand)+ expect(put.input).toMatchObject({ Bucket: 'blobs', Key: 'p/_health/probe' })+ expect(head).toBeInstanceOf(HeadObjectCommand)+ expect(head.input).toMatchObject({ Key: 'p/_health/probe' })+ expect(copy).toBeInstanceOf(CopyObjectCommand)+ expect(copy.input).toMatchObject({ Key: 'p/_health/probe', CopySource: 'blobs/p/_health/probe' })+ })++ it.each([+ ['put', 0],+ ['head', 1],+ ['copy', 2],+ ])('healthcheck surfaces a %s failure as a retriable store error naming the op', async (op, failingCall) => {+ const cause = s3Error('AccessDenied')+ for (let i = 0; i < failingCall; i++) {+ send.mockResolvedValueOnce({})+ }+ send.mockRejectedValueOnce(cause)+ const error = await captureError(store().healthcheck())+ expect(error).toBeInstanceOf(BlobStoreError)+ expect(error.message).toBe(+ `AI blob store healthcheck failed (${op}) for bucket "blobs": AccessDenied: AccessDenied`+ )+ expect(error.isRetriable).toBe(true)+ expect(error.cause).toBe(cause)+ })++ it('builds a store when the bucket is set', () => {+ const base = {+ AI_BLOB_S3_BUCKET: 'blobs',+ AI_BLOB_S3_PREFIX: '',+ AI_BLOB_S3_ENDPOINT: '',+ AI_BLOB_S3_REGION: 'us-east-1',+ AI_BLOB_S3_ACCESS_KEY_ID: '',+ AI_BLOB_S3_SECRET_ACCESS_KEY: '',+ AI_BLOB_S3_TIMEOUT_MS: 30000,+ AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS: 20,+ }+ expect(buildAiBlobStore(base)).not.toBeNull()+ })++ // 31d bucket lifecycle − 30d row TTL leaves at most 24h of touch slack; a+ // larger window silently produces pointers that outlive their objects.+ it('rejects a touch-after window that could outlive the lifecycle safety margin', () => {+ const base = {+ AI_BLOB_S3_BUCKET: 'blobs',+ AI_BLOB_S3_PREFIX: '',+ AI_BLOB_S3_ENDPOINT: '',+ AI_BLOB_S3_REGION: 'us-east-1',+ AI_BLOB_S3_ACCESS_KEY_ID: '',+ AI_BLOB_S3_SECRET_ACCESS_KEY: '',+ AI_BLOB_S3_TIMEOUT_MS: 30000,+ AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS: 48,+ }+ expect(() => buildAiBlobStore(base)).toThrow()+ })+})diff --git a/nodejs/src/ingestion/pipelines/ai/blob-offload/blob-store.ts b/nodejs/src/ingestion/pipelines/ai/blob-offload/blob-store.tsnew file mode 100644index 000000000000..4800d3d48651--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/blob-offload/blob-store.ts@@ -0,0 +1,303 @@+import {+ CopyObjectCommand,+ HeadObjectCommand,+ NotFound,+ PutObjectCommand,+ S3Client,+ S3ClientConfig,+ S3ServiceException,+} from '@aws-sdk/client-s3'++import { Component } from '~/ingestion/common/scopes'+import { aiBlobOffloadS3Duration, aiBlobOffloadS3Errors } from '~/ingestion/pipelines/ai/metrics'++export type EnsureStoredOutcome = 'uploaded' | 'fresh' | 'touched'++/**+ * The only error type blob store implementations throw. Encapsulates the+ * provider's error taxonomy behind one framework-facing flag:+ *+ * - `isRetriable: false` — this blob can never be stored; the failure is+ * determined by the event's own content. The pipeline's step-retry wrapper+ * turns it into a DLQ sub-result, so just the affected event dead-letters.+ * - `isRetriable: true` — worth retrying: transient (timeouts, throttling,+ * 5xx, networking) or environment-wide (auth, missing bucket) failures.+ * The retry wrapper retries and, on exhaustion, crashes the consumer —+ * an environment-wide problem must fail loudly, never silently divert a+ * lane's data to the DLQ.+ *+ * The underlying provider error is always preserved as `cause`.+ */+export class BlobStoreError extends Error {+ constructor(+ message: string,+ readonly isRetriable: boolean,+ options?: { cause?: unknown }+ ) {+ super(message, options)+ this.name = 'BlobStoreError'+ }+}++/**+ * Embed the provider error's name in the wrapper message: the framework's log+ * path (withStepRetry -> logger.error) serializes message and stack manually+ * and drops `cause` chains, so the embedded name is the greppable+ * discriminator in logs during incidents — AWS messages often omit the code.+ */+function describeProviderError(error: unknown): string {+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error)+}++export interface BlobStore {+ /**+ * Ensure the blob is durably stored. Failures are thrown exclusively as+ * {@link BlobStoreError} — callers never see provider error types.+ */+ ensureStored(teamId: number, blob: { hash: string; bytes: Buffer; mime: string }): Promise<EnsureStoredOutcome>+}++interface S3BlobStoreConfig {+ bucket: string+ prefix: string+ touchAfterMs: number+ timeoutMs: number+}++/**+ * AWS error names that are provably caused by the content of the request —+ * deterministic per event, so no retry (and no environment change) can ever+ * make them succeed. Translated to `isRetriable: false`:+ *+ * - `EntityTooLarge`: the PUT body exceeds S3's single-request object size+ * limit — a property of this event's blob bytes.+ * - `MetadataTooLarge`: the request metadata/headers exceed S3's limit — the+ * only per-request headers we send are derived from the blob's detected+ * mime (Content-Type on put and copy), so this too is determined by the+ * event.+ *+ * Deliberately narrow: everything else translates to `isRetriable: true`,+ * because it is either transient (retry owns it) or environment-wide+ * (AccessDenied, NoSuchBucket, credentials — those crash after retries, and+ * the startup healthcheck catches them before traffic). `KeyTooLongError` is+ * intentionally not here: our keys are prefix + team id + fixed-length hash,+ * so an over-long key is configuration, not event content.+ */+const EVENT_SPECIFIC_S3_ERRORS = new Set(['EntityTooLarge', 'MetadataTooLarge'])++export class S3BlobStore implements BlobStore {+ constructor(+ private s3: S3Client,+ private config: S3BlobStoreConfig+ ) {}++ private key(teamId: number, hash: string): string {+ return `${this.config.prefix}${teamId}/sha256/${hash}`+ }++ /** Translate an AWS failure into the store's error type at the public boundary. */+ private toStoreError(error: unknown): BlobStoreError {+ // The two event-specific codes are not modeled by the SDK (they+ // deserialize into the generic S3ServiceException with the code in+ // `.name`), so after narrowing to S3ServiceException the name check is+ // the only handle on them. Names on non-S3 errors are never interpreted.+ const isRetriable = !(error instanceof S3ServiceException && EVENT_SPECIFIC_S3_ERRORS.has(error.name))+ return new BlobStoreError(`S3 blob store failure: ${describeProviderError(error)}`, isRetriable, {+ cause: error,+ })+ }++ private async timed<T>(+ op: 'head' | 'put' | 'copy',+ fn: () => Promise<T>,+ shouldCountError?: (error: unknown) => boolean+ ): Promise<T> {+ const timer = aiBlobOffloadS3Duration.labels(op).startTimer()+ try {+ return await fn()+ } catch (error) {+ if (!shouldCountError || shouldCountError(error)) {+ aiBlobOffloadS3Errors.labels(op).inc()+ }+ throw error+ } finally {+ timer()+ }+ }++ /**+ * Startup self-test: exercises every S3 operation `ensureStored` performs+ * (PUT, HEAD, self-COPY) against a sentinel key under the configured+ * prefix, so missing permissions, a bad bucket, or no connectivity fail+ * the deployment at scope start — before any traffic — instead of+ * crash-looping the lane on the first blob-carrying event. Sentinel+ * collisions between pods are harmless, and the bucket lifecycle cleans+ * the object up like any blob.+ */+ async healthcheck(): Promise<void> {+ const Bucket = this.config.bucket+ const Key = `${this.config.prefix}_health/probe`+ const abort = (): { abortSignal: AbortSignal } => ({+ abortSignal: AbortSignal.timeout(this.config.timeoutMs),+ })+ const probe = async (op: string, fn: () => Promise<unknown>): Promise<void> => {+ try {+ await fn()+ } catch (error) {+ throw new BlobStoreError(+ `AI blob store healthcheck failed (${op}) for bucket "${Bucket}": ${describeProviderError(error)}`,+ true,+ { cause: error }+ )+ }+ }+ await probe('put', () =>+ this.s3.send(+ new PutObjectCommand({ Bucket, Key, Body: Buffer.from('ok'), ContentType: 'text/plain' }),+ abort()+ )+ )+ await probe('head', () => this.s3.send(new HeadObjectCommand({ Bucket, Key }), abort()))+ await probe('copy', () =>+ this.s3.send(+ new CopyObjectCommand({+ Bucket,+ Key,+ CopySource: `${Bucket}/${Key.split('/').map(encodeURIComponent).join('/')}`,+ MetadataDirective: 'REPLACE',+ ContentType: 'text/plain',+ }),+ abort()+ )+ )+ }++ async ensureStored(+ teamId: number,+ blob: { hash: string; bytes: Buffer; mime: string }+ ): Promise<EnsureStoredOutcome> {+ try {+ return await this.ensureStoredS3(teamId, blob)+ } catch (error) {+ throw this.toStoreError(error)+ }+ }++ /** Raw S3 flow; AWS errors escape here and are translated by ensureStored. */+ private async ensureStoredS3(+ teamId: number,+ blob: { hash: string; bytes: Buffer; mime: string }+ ): Promise<EnsureStoredOutcome> {+ const Bucket = this.config.bucket+ const Key = this.key(teamId, blob.hash)+ const abort = (): { abortSignal: AbortSignal } => ({+ abortSignal: AbortSignal.timeout(this.config.timeoutMs),+ })++ let lastModified: Date | undefined+ try {+ const head = await this.timed(+ 'head',+ () => this.s3.send(new HeadObjectCommand({ Bucket, Key }), abort()),+ (error): boolean => !(error instanceof NotFound)+ )+ lastModified = head.LastModified+ } catch (error) {+ if (error instanceof NotFound) {+ await this.timed('put', () =>+ this.s3.send(+ new PutObjectCommand({ Bucket, Key, Body: blob.bytes, ContentType: blob.mime }),+ abort()+ )+ )+ return 'uploaded'+ }+ throw error+ }++ const age = Date.now() - (lastModified?.getTime() ?? 0)+ if (age <= this.config.touchAfterMs) {+ return 'fresh'+ }+ // Self-copy resets the object's creation date, which the bucket's 31-day+ // lifecycle rule keys on — every object outlives its last reference by ≥30d.+ // S3 URL-decodes CopySource (unlike Key), so path segments must be percent-encoded.+ await this.timed('copy', () =>+ this.s3.send(+ new CopyObjectCommand({+ Bucket,+ Key,+ CopySource: `${Bucket}/${Key.split('/').map(encodeURIComponent).join('/')}`,+ MetadataDirective: 'REPLACE',+ ContentType: blob.mime,+ }),+ abort()+ )+ )+ return 'touched'+ }+}++export interface AiBlobS3Config {+ AI_BLOB_S3_BUCKET: string+ AI_BLOB_S3_PREFIX: string+ AI_BLOB_S3_ENDPOINT: string+ AI_BLOB_S3_REGION: string+ AI_BLOB_S3_ACCESS_KEY_ID: string+ AI_BLOB_S3_SECRET_ACCESS_KEY: string+ AI_BLOB_S3_TIMEOUT_MS: number+ AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS: number+}++// The 31-day bucket lifecycle must outlive touch age + the 30-day ai_events row TTL,+// or pointers in live rows would reference expired objects.+const MAX_TOUCH_AFTER_HOURS = 24++export function buildAiBlobStore(config: AiBlobS3Config): S3BlobStore | null {+ if (!config.AI_BLOB_S3_BUCKET) {+ return null+ }+ if (config.AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS > MAX_TOUCH_AFTER_HOURS) {+ throw new Error(+ `AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS must be at most ${MAX_TOUCH_AFTER_HOURS}, got ${config.AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS}`+ )+ }+ const s3Config: S3ClientConfig = { region: config.AI_BLOB_S3_REGION }+ if (config.AI_BLOB_S3_ENDPOINT) {+ s3Config.endpoint = config.AI_BLOB_S3_ENDPOINT+ s3Config.forcePathStyle = true+ }+ if (config.AI_BLOB_S3_ACCESS_KEY_ID && config.AI_BLOB_S3_SECRET_ACCESS_KEY) {+ s3Config.credentials = {+ accessKeyId: config.AI_BLOB_S3_ACCESS_KEY_ID,+ secretAccessKey: config.AI_BLOB_S3_SECRET_ACCESS_KEY,+ }+ }+ return new S3BlobStore(new S3Client(s3Config), {+ bucket: config.AI_BLOB_S3_BUCKET,+ prefix: config.AI_BLOB_S3_PREFIX,+ touchAfterMs: config.AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS * 3600 * 1000,+ timeoutMs: config.AI_BLOB_S3_TIMEOUT_MS,+ })+}++/**+ * Scope entry for the AI blob store. `start()` builds the store from config+ * (null when no bucket is configured — offload disabled) and runs its startup+ * healthcheck, mirroring the Kafka consumer's connect-at-start contract: an+ * unreachable bucket (bad credentials, missing bucket, no route) fails+ * startup before any traffic is consumed, instead of crash-looping on the+ * first blob-carrying event. The value is wrapped (`{ store }`) because+ * container entries must be objects and the store may be null.+ */+export class AiBlobStoreComponent implements Component<{ store: BlobStore | null }> {+ constructor(private readonly config: AiBlobS3Config) {}++ async start(): Promise<{ value: { store: BlobStore | null }; stop: () => Promise<void> }> {+ const store = buildAiBlobStore(this.config)+ if (store) {+ await store.healthcheck()+ }+ return { value: { store }, stop: () => Promise.resolve() }+ }+}diff --git a/nodejs/src/ingestion/pipelines/ai/blob-offload/detect.test.ts b/nodejs/src/ingestion/pipelines/ai/blob-offload/detect.test.tsnew file mode 100644index 000000000000..2146f12bb1ed--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/blob-offload/detect.test.ts@@ -0,0 +1,242 @@+import { createHash } from 'crypto'++import { parseJSON } from '~/common/utils/json-parse'++import { extractBlobs } from './detect'+import { parseBlobPointer } from './pointer'++const PNG_BYTES = Buffer.alloc(20000, 7)+const PNG_B64 = PNG_BYTES.toString('base64')+const PNG_HASH = createHash('sha256').update(PNG_BYTES).digest('hex')+const JPEG_BYTES = Buffer.alloc(20000, 9)+const JPEG_B64 = JPEG_BYTES.toString('base64')+const JPEG_HASH = createHash('sha256').update(JPEG_BYTES).digest('hex')+const AUDIO_BYTES = Buffer.alloc(98304, 3)+const AUDIO_B64 = AUDIO_BYTES.toString('base64')+const OPTS = { minBase64Length: 8192 }++describe('extractBlobs', () => {+ it('replaces an openai image data-URI with a pointer and captures exact bytes', () => {+ const input = [+ {+ role: 'user',+ content: [+ { type: 'text', text: 'what is this?' },+ { type: 'image_url', image_url: { url: `data:image/png;base64,${PNG_B64}`, detail: 'high' } },+ ],+ },+ ]+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(result.blobs[0]).toMatchObject({ mime: 'image/png', hash: PNG_HASH, detector: 'data_uri' })+ expect(result.blobs[0].bytes.equals(PNG_BYTES)).toBe(true)+ const rewritten = result.value as typeof input+ const pointer = parseBlobPointer(rewritten[0].content[1].image_url!.url)+ expect(pointer).toEqual({ algo: 'sha256', hash: PNG_HASH, mime: 'image/png', size: PNG_BYTES.length })+ expect(result.savedChars).toBe(+ input[0].content[1].image_url!.url.length - rewritten[0].content[1].image_url!.url.length+ )+ expect(rewritten[0].content[0].text).toBe('what is this?')+ expect(rewritten[0].content[1].image_url!.detail).toBe('high')+ expect(input[0].content[1].image_url!.url.startsWith('data:')).toBe(true) // input not mutated+ })++ it.each([+ [+ 'anthropic_source',+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: PNG_B64 } },+ (v: unknown): string => (v as { source: { data: string } }).source.data,+ ],+ [+ 'gemini_inline_data camelCase',+ { inlineData: { mimeType: 'image/png', data: PNG_B64 } },+ (v: unknown): string => (v as { inlineData: { data: string } }).inlineData.data,+ ],+ [+ 'gemini_inline_data snake_case',+ { inline_data: { mime_type: 'image/png', data: PNG_B64 } },+ (v: unknown): string => (v as { inline_data: { data: string } }).inline_data.data,+ ],+ ])('extracts %s shapes, replacing only the data field', (_name, input, getData) => {+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(result.blobs[0].hash).toBe(PNG_HASH)+ expect(result.blobs[0].mime).toBe('image/png')+ const pointer = parseBlobPointer(getData(result.value))+ expect(pointer?.hash).toBe(PNG_HASH)+ })++ it('extracts openai input_audio with mime from format', () => {+ const input = { type: 'input_audio', input_audio: { data: PNG_B64, format: 'wav' } }+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(result.blobs[0].mime).toBe('audio/wav')+ expect(result.blobs[0].detector).toBe('openai_input_audio')+ })++ it('offloads {data, format} outside input_audio via blind path, not the audio detector', () => {+ const input = { report: { data: PNG_B64, format: 'summary' } }+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(result.blobs[0]).toMatchObject({ detector: 'raw_base64', mime: 'application/octet-stream' })+ })++ it('offloads a provider shape with an oversized mime via blind path with a safe mime', () => {+ const input = { source: { type: 'base64', media_type: `image/${'x'.repeat(300)}`, data: PNG_B64 } }+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(result.blobs[0]).toMatchObject({ detector: 'raw_base64', mime: 'application/octet-stream' })+ })++ it('dedupes the same content arriving via different shapes to one blob', () => {+ const input = [+ { image_url: { url: `data:image/png;base64,${PNG_B64}` } },+ { source: { type: 'base64', media_type: 'image/png', data: PNG_B64 } },+ ]+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ const rewritten = result.value as [{ image_url: { url: string } }, { source: { data: string } }]+ expect(parseBlobPointer(rewritten[0].image_url.url)?.hash).toBe(PNG_HASH)+ expect(parseBlobPointer(rewritten[1].source.data)?.hash).toBe(PNG_HASH)+ })++ it('leaves blobs below the size floor inline and counts them', () => {+ const small = Buffer.alloc(100, 1).toString('base64')+ const input = { image_url: { url: `data:image/png;base64,${small}` } }+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(0)+ expect(result.belowFloorCount).toBe(1)+ expect(result.belowFloorBytes).toBeGreaterThan(0)+ expect((result.value as { image_url: { url: string } }).image_url.url).toBe(`data:image/png;base64,${small}`)+ })++ it.each([+ ['plain text payload', { role: 'user', content: 'just text' }],+ ['http url', { image_url: { url: 'https://example.com/img.png' } }],+ ['existing pointer', { image_url: { url: `phaiblob://v1/sha256/${'a'.repeat(64)}?mime=image%2Fpng&size=1` } }],+ ['non-base64 data field', { source: { type: 'base64', media_type: 'image/png', data: 'not base64 !!!' } }],+ [+ 'long plain text in a mime-shaped object',+ { inline_data: { mime_type: 'text/plain', data: 'lorem ipsum dolor sit amet '.repeat(400) } },+ ],+ [+ 'padding-misaligned base64 charset string',+ { inline_data: { mime_type: 'text/plain', data: 'A'.repeat(8193) } },+ ],+ ['oversized mime in a data URI', { image_url: { url: `data:image/${'x'.repeat(300)};base64,${PNG_B64}` } }],+ ])('passes through untouched: %s', (_name, input) => {+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(0)+ expect(result.value).toEqual(input)+ })++ it.each([+ ['crlf header injection', 'mp3\r\nX-Injected: 1'],+ ['non-latin1 characters', 'mp3🎵'],+ ['spaces', 'mp3 audio'],+ ])('offloads input_audio with a hostile format via blind path, ignoring the format (%s)', (_name, format) => {+ const input = { type: 'input_audio', input_audio: { data: PNG_B64, format } }+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(result.blobs[0]).toMatchObject({ detector: 'raw_base64', mime: 'application/octet-stream' })+ })++ it.each([+ ['host blob above the floor', PNG_B64, 2],+ ['host blob below the floor', Buffer.alloc(100, 1).toString('base64'), 1],+ ])('rewrites sibling data URIs inside a matched provider shape (%s)', (_name, hostData, expectedBlobs) => {+ const input = {+ type: 'base64',+ media_type: 'image/png',+ data: hostData,+ preview: { image_url: { url: `data:image/jpeg;base64,${JPEG_B64}` } },+ }+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(expectedBlobs)+ const rewritten = result.value as typeof input+ expect(parseBlobPointer(rewritten.preview.image_url.url)?.hash).toBe(JPEG_HASH)+ })++ it('preserves a JSON-parsed __proto__ field during rewrites', () => {+ const input = parseJSON(`{"image_url":{"url":"data:image/png;base64,${PNG_B64}"},"__proto__":{"marker":1}}`)+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(JSON.stringify(result.value)).toContain('"__proto__":{"marker":1}')+ expect(Object.getPrototypeOf(result.value)).toBe(Object.prototype)+ })++ it('lowercases declared mimes so stored content types are canonical', () => {+ const input = { source: { type: 'base64', media_type: 'IMAGE/PNG', data: PNG_B64 } }+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(result.blobs[0].mime).toBe('image/png')+ expect(parseBlobPointer((result.value as typeof input).source.data)?.mime).toBe('image/png')+ })++ it('caps traversal depth instead of overflowing the stack on deeply nested payloads', () => {+ let deep: unknown = 'leaf'+ for (let i = 0; i < 100000; i++) {+ deep = [deep]+ }+ const input = { shallow: { image_url: { url: `data:image/png;base64,${PNG_B64}` } }, deep }+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect((result.value as { deep: unknown }).deep).toBe(deep)+ })++ it('leaves data URIs with non-canonical base64 inline instead of truncated-decoding them', () => {+ const url = `data:image/png;base64,AAAA=${PNG_B64}`+ const result = extractBlobs({ image_url: { url } }, OPTS)+ expect(result.blobs).toHaveLength(0)+ expect((result.value as { image_url: { url: string } }).image_url.url).toBe(url)+ })++ it('compacts whitespace-wrapped base64 inside data URIs and captures exact bytes', () => {+ const wrapped = PNG_B64.replace(/(.{76})/g, '$1\n')+ const result = extractBlobs({ image_url: { url: `data:image/png;base64,${wrapped}` } }, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(result.blobs[0].mime).toBe('image/png')+ expect(result.blobs[0].bytes.equals(PNG_BYTES)).toBe(true)+ })++ it('offloads shapeless raw base64 (openai audio output part) via the blind path', () => {+ const input = [+ {+ role: 'assistant',+ content: [+ {+ type: 'audio',+ id: 'audio_6a5f3b1f',+ expires_at: 1784629551,+ transcript: 'The capital of France is Paris.',+ data: AUDIO_B64,+ },+ ],+ },+ ]+ const result = extractBlobs(input, OPTS)+ expect(result.blobs).toHaveLength(1)+ expect(result.blobs[0]).toMatchObject({ detector: 'raw_base64', mime: 'application/octet-stream' })+ expect(result.blobs[0].bytes.equals(AUDIO_BYTES)).toBe(true)+ const part = (result.value as typeof input)[0].content[0]+ expect(parseBlobPointer(part.data)?.mime).toBe('application/octet-stream')+ expect(part.transcript).toBe('The capital of France is Paris.')+ })++ it('leaves whitespace-wrapped bare base64 inline (blind path is byte-strict)', () => {+ // slice(60001) drops one char so the inserted newline keeps length % 4 === 0 —+ // the string must reach the full canonical scan, not die at the cheap length check.+ const wrapped = `${AUDIO_B64.slice(0, 60000)}\n${AUDIO_B64.slice(60001)}`+ const result = extractBlobs({ content: wrapped }, OPTS)+ expect(result.blobs).toHaveLength(0)+ expect((result.value as { content: string }).content).toBe(wrapped)+ })++ it('leaves sub-floor raw base64 inline without below-floor counting', () => {+ const embedding = Buffer.alloc(6144, 1).toString('base64')+ const result = extractBlobs({ content: embedding }, { minBase64Length: 20480 })+ expect(result.blobs).toHaveLength(0)+ expect(result.belowFloorCount).toBe(0)+ expect(result.value).toEqual({ content: embedding })+ })+})diff --git a/nodejs/src/ingestion/pipelines/ai/blob-offload/detect.ts b/nodejs/src/ingestion/pipelines/ai/blob-offload/detect.tsnew file mode 100644index 000000000000..adc13431e6aa--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/blob-offload/detect.ts@@ -0,0 +1,194 @@+import { createHash } from 'crypto'++import { decodeCanonicalBase64, isCanonicalBase64 } from './base64'+import { encodeBlobPointer, isBlobPointer } from './pointer'++export type BlobDetector = 'data_uri' | 'anthropic_source' | 'gemini_inline_data' | 'openai_input_audio' | 'raw_base64'++export interface DetectedBlob {+ bytes: Buffer+ mime: string+ hash: string+ detector: BlobDetector+}++export interface ExtractionResult {+ value: unknown+ blobs: DetectedBlob[]+ /** Serialized chars removed by pointer rewrites, summed per occurrence (dedup'd blobs still count each site). */+ savedChars: number+ belowFloorCount: number+ belowFloorBytes: number+}++const DATA_URI = /^data:([\w.+-]+\/[\w.+-]+);base64,([A-Za-z0-9+/=\s]+)$/+// Length-capped (RFC 4288 gives each of type/subtype 127 chars): the mime flows into the+// S3 Content-Type header and the pointer URI, so an unbounded value is a poison pill.+const MIME = /^(?=.{1,255}$)[\w.+-]+\/[\w.+-]+$/++const RAW_BASE64_MIME = 'application/octet-stream'++interface Extraction {+ blobsByHash: Map<string, DetectedBlob>+ savedChars: number+ belowFloorCount: number+ belowFloorBytes: number+ minBase64Length: number+}++function pointerFor(+ state: Extraction,+ base64: string,+ rawMime: string,+ detector: BlobDetector,+ countBelowFloor: boolean+): string | null {+ // Mime types are case-insensitive per RFC; canonical lowercase at rest keeps the+ // read side's mime allowlist comparisons exact.+ const mime = rawMime.toLowerCase()+ if (base64.length < state.minBase64Length) {+ if (countBelowFloor && isCanonicalBase64(base64)) {+ state.belowFloorCount += 1+ state.belowFloorBytes += Math.floor((base64.length * 3) / 4)+ }+ return null+ }+ const bytes = decodeCanonicalBase64(base64)+ if (!bytes || bytes.length === 0) {+ return null+ }+ const hash = createHash('sha256').update(bytes).digest('hex')+ if (!state.blobsByHash.has(hash)) {+ state.blobsByHash.set(hash, { bytes, mime, hash, detector })+ }+ return encodeBlobPointer({ algo: 'sha256', hash, mime, size: bytes.length })+}++function extractFromString(state: Extraction, value: string): string {+ if (isBlobPointer(value)) {+ return value+ }+ if (value.startsWith('data:')) {+ const match = DATA_URI.exec(value)+ if (!match || !MIME.test(match[1])) {+ return value+ }+ const pointer = pointerFor(state, match[2].replace(/\s+/g, ''), match[1], 'data_uri', true)+ if (pointer) {+ state.savedChars += value.length - pointer.length+ return pointer+ }+ return value+ }+ // Blind path: byte-strict (no whitespace compaction) so the stored bytes+ // reconstruct the exact original string; sub-floor strings are not counted+ // below-floor (every short ID would pollute the metric).+ const pointer = pointerFor(state, value, RAW_BASE64_MIME, 'raw_base64', false)+ if (pointer) {+ state.savedChars += value.length - pointer.length+ return pointer+ }+ return value+}++interface ProviderBlob {+ data: string+ mime: string+ detector: BlobDetector+}++/** Shape detectors for providers that carry raw base64 with the mime in a sibling field. */+function providerBlob(obj: Record<string, unknown>, parentKey: string | null): ProviderBlob | null {+ if (+ obj.type === 'base64' &&+ typeof obj.media_type === 'string' &&+ MIME.test(obj.media_type) &&+ typeof obj.data === 'string'+ ) {+ return { data: obj.data, mime: obj.media_type, detector: 'anthropic_source' }+ }+ const geminiMime =+ typeof obj.mimeType === 'string' ? obj.mimeType : typeof obj.mime_type === 'string' ? obj.mime_type : null+ if (geminiMime && MIME.test(geminiMime) && typeof obj.data === 'string') {+ return { data: obj.data, mime: geminiMime, detector: 'gemini_inline_data' }+ }+ // The composed mime is validated as a whole: `format` is attacker-controlled and+ // flows into the S3 Content-Type header, where invalid characters crash the sender.+ if (+ parentKey === 'input_audio' &&+ typeof obj.format === 'string' &&+ MIME.test(`audio/${obj.format}`) &&+ typeof obj.data === 'string'+ ) {+ return { data: obj.data, mime: `audio/${obj.format}`, detector: 'openai_input_audio' }+ }+ return null+}++// Stack safety: recursing without a bound would throw RangeError on adversarially+// nested payloads, and unclassified errors crash the consumer after retries.+// Content nested deeper passes through untouched, like every other miss.+const MAX_DEPTH = 256++function extractFromObject(+ state: Extraction,+ obj: Record<string, unknown>,+ parentKey: string | null,+ depth: number+): Record<string, unknown> {+ let base = obj+ const match = providerBlob(obj, parentKey)+ if (match) {+ const pointer = pointerFor(state, match.data, match.mime, match.detector, true)+ if (pointer) {+ state.savedChars += match.data.length - pointer.length+ base = { ...obj, data: pointer }+ }+ }+ let changed = base !== obj+ const entries: [string, unknown][] = []+ for (const [key, child] of Object.entries(base)) {+ const newChild = extractFromNode(state, child, key, depth + 1)+ entries.push([key, newChild])+ if (newChild !== child) {+ changed = true+ }+ }+ // fromEntries defines own properties, so a JSON-parsed `__proto__` key survives the rewrite.+ return changed ? Object.fromEntries(entries) : obj+}++function extractFromNode(state: Extraction, node: unknown, parentKey: string | null, depth: number): unknown {+ if (typeof node === 'string') {+ return extractFromString(state, node)+ }+ if (depth >= MAX_DEPTH) {+ return node+ }+ if (Array.isArray(node)) {+ const rewritten = node.map((child) => extractFromNode(state, child, parentKey, depth + 1))+ return rewritten.some((child, i) => child !== node[i]) ? rewritten : node+ }+ if (node !== null && typeof node === 'object') {+ return extractFromObject(state, node as Record<string, unknown>, parentKey, depth)+ }+ return node+}++export function extractBlobs(value: unknown, opts: { minBase64Length: number }): ExtractionResult {+ const state: Extraction = {+ blobsByHash: new Map(),+ savedChars: 0,+ belowFloorCount: 0,+ belowFloorBytes: 0,+ minBase64Length: opts.minBase64Length,+ }+ const rewritten = extractFromNode(state, value, null, 0)+ return {+ value: rewritten,+ blobs: [...state.blobsByHash.values()],+ savedChars: state.savedChars,+ belowFloorCount: state.belowFloorCount,+ belowFloorBytes: state.belowFloorBytes,+ }+}diff --git a/nodejs/src/ingestion/pipelines/ai/blob-offload/pointer.test.ts b/nodejs/src/ingestion/pipelines/ai/blob-offload/pointer.test.tsnew file mode 100644index 000000000000..ef6fd3597c84--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/blob-offload/pointer.test.ts@@ -0,0 +1,30 @@+import { encodeBlobPointer, isBlobPointer, parseBlobPointer } from './pointer'++const HASH = 'a'.repeat(64)++describe('blob pointer', () => {+ it('round-trips encode -> parse', () => {+ const uri = encodeBlobPointer({ algo: 'sha256', hash: HASH, mime: 'image/png', size: 123456 })+ expect(uri).toBe(`phaiblob://v1/sha256/${HASH}?mime=image%2Fpng&size=123456`)+ expect(parseBlobPointer(uri)).toEqual({ algo: 'sha256', hash: HASH, mime: 'image/png', size: 123456 })+ })++ it('detects pointers by scheme', () => {+ expect(isBlobPointer(`phaiblob://v1/sha256/${HASH}?mime=image%2Fpng&size=1`)).toBe(true)+ expect(isBlobPointer('data:image/png;base64,AAAA')).toBe(false)+ })++ it.each([+ ['not a pointer', 'https://example.com/img.png'],+ ['unknown version', `phaiblob://v9/sha256/${HASH}?mime=image%2Fpng&size=1`],+ ['unknown algo', `phaiblob://v1/md5/${HASH}?mime=image%2Fpng&size=1`],+ ['bad hash length', 'phaiblob://v1/sha256/abc123?mime=image%2Fpng&size=1'],+ ['non-hex hash', `phaiblob://v1/sha256/${'z'.repeat(64)}?mime=image%2Fpng&size=1`],+ ['missing mime', `phaiblob://v1/sha256/${HASH}?size=1`],+ ['missing size', `phaiblob://v1/sha256/${HASH}?mime=image%2Fpng`],+ ['non-integer size', `phaiblob://v1/sha256/${HASH}?mime=image%2Fpng&size=1.5`],+ ['unparseable', 'phaiblob://'],+ ])('parse returns null for %s', (_name, value) => {+ expect(parseBlobPointer(value)).toBeNull()+ })+})diff --git a/nodejs/src/ingestion/pipelines/ai/blob-offload/pointer.ts b/nodejs/src/ingestion/pipelines/ai/blob-offload/pointer.tsnew file mode 100644index 000000000000..8e61afa50881--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/blob-offload/pointer.ts@@ -0,0 +1,52 @@+/**+ * Versioned pointer URIs that replace offloaded binary payloads in AI event JSON.+ *+ * `phaiblob://v1/sha256/<hex>?mime=...&size=...` — the `v1` segment is a resolution-strategy+ * dispatch token: future storage strategies mint new versions and old rows keep resolving.+ * Pointers deliberately carry no physical location (bucket/region/team); the resolver owns+ * the mapping. This module is the only place pointer strings are built or interpreted.+ */+export interface BlobPointer {+ algo: 'sha256'+ hash: string+ mime: string+ size: number+}++export const POINTER_SCHEME = 'phaiblob://'++const HEX_64 = /^[0-9a-f]{64}$/++export function isBlobPointer(value: string): boolean {+ return value.startsWith(POINTER_SCHEME)+}++export function encodeBlobPointer(pointer: BlobPointer): string {+ const params = new URLSearchParams({ mime: pointer.mime, size: String(pointer.size) })+ return `${POINTER_SCHEME}v1/${pointer.algo}/${pointer.hash}?${params.toString()}`+}++export function parseBlobPointer(value: string): BlobPointer | null {+ if (!isBlobPointer(value)) {+ return null+ }+ let url: URL+ try {+ url = new URL(value)+ } catch {+ return null+ }+ if (url.hostname !== 'v1') {+ return null+ }+ const segments = url.pathname.split('/').filter((s) => s.length > 0)+ if (segments.length !== 2 || segments[0] !== 'sha256' || !HEX_64.test(segments[1])) {+ return null+ }+ const mime = url.searchParams.get('mime')+ const sizeRaw = url.searchParams.get('size')+ if (!mime || !sizeRaw || !/^\d+$/.test(sizeRaw)) {+ return null+ }+ return { algo: 'sha256', hash: segments[1], mime, size: parseInt(sizeRaw, 10) }+}diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.test.ts b/nodejs/src/ingestion/pipelines/ai/consumer.test.tsindex 6bcdd9df4ad9..bab58507acb1 100644--- a/nodejs/src/ingestion/pipelines/ai/consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/consumer.test.ts@@ -31,6 +31,20 @@ describe('createAiConsumer', () => {INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID: '',EVENT_SCHEMA_ENFORCEMENT_ENABLED: false,CDP_HOG_WATCHER_SAMPLE_RATE: 1,+ // Read eagerly by createAiConsumer (not deferred like the scope-builder services+ // below), so these need real fail-closed values rather than the cast-away pattern.+ AI_BLOB_S3_BUCKET: '',+ AI_BLOB_S3_PREFIX: '',+ AI_BLOB_S3_ENDPOINT: '',+ AI_BLOB_S3_REGION: 'us-east-1',+ AI_BLOB_S3_ACCESS_KEY_ID: '',+ AI_BLOB_S3_SECRET_ACCESS_KEY: '',+ AI_BLOB_S3_TIMEOUT_MS: 30000,+ AI_BLOB_OFFLOAD_TEAMS: '',+ AI_BLOB_OFFLOAD_MIN_BASE64_LENGTH: 8192,+ AI_BLOB_OFFLOAD_MAX_BLOBS_PER_EVENT: 50,+ AI_BLOB_OFFLOAD_UPLOAD_MAX_CONCURRENCY: 8,+ AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS: 20,...({} as Pick<IngestionConsumerConfig,| 'INGESTION_STATEFUL_OVERFLOW_REDIS_TTL_SECONDS'diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.ts b/nodejs/src/ingestion/pipelines/ai/consumer.tsindex 1fa15fbcf71e..1eff73a63b09 100644--- a/nodejs/src/ingestion/pipelines/ai/consumer.ts+++ b/nodejs/src/ingestion/pipelines/ai/consumer.ts@@ -1,4 +1,5 @@import { CommonConfig } from '~/common/config'+import { buildIntegerMatcher } from '~/common/config/config'import { ReadOnlyGroupTypeManager } from '~/common/groups/readonly-group-type-manager'import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'import {@@ -36,6 +37,7 @@ import { createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'import { TopHog } from '~/ingestion/framework/tophog'import { RedisPool } from '~/types'+import { AiBlobStoreComponent } from './blob-offload/blob-store'import { createAiIngestionPipeline } from './pipeline'export type AiConsumerConfig = CommonIngestionConsumerConfig &@@ -55,6 +57,18 @@ export type AiConsumerConfig = CommonIngestionConsumerConfig &| 'SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID'| 'INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID'| 'EVENT_SCHEMA_ENFORCEMENT_ENABLED'+ | 'AI_BLOB_S3_BUCKET'+ | 'AI_BLOB_S3_PREFIX'+ | 'AI_BLOB_S3_ENDPOINT'+ | 'AI_BLOB_S3_REGION'+ | 'AI_BLOB_S3_ACCESS_KEY_ID'+ | 'AI_BLOB_S3_SECRET_ACCESS_KEY'+ | 'AI_BLOB_S3_TIMEOUT_MS'+ | 'AI_BLOB_OFFLOAD_TEAMS'+ | 'AI_BLOB_OFFLOAD_MIN_BASE64_LENGTH'+ | 'AI_BLOB_OFFLOAD_MAX_BLOBS_PER_EVENT'+ | 'AI_BLOB_OFFLOAD_UPLOAD_MAX_CONCURRENCY'+ | 'AI_BLOB_OFFLOAD_TOUCH_AFTER_HOURS'> &Pick<CommonConfig, 'CDP_HOG_WATCHER_SAMPLE_RATE'>@@ -155,8 +169,27 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiSharedreturn Promise.resolve({ value: topHog, stop: () => topHog.stop() })},})+ // Owned by the scope so the store's startup healthcheck runs at+ // scope start, before any traffic is consumed.+ .add('aiBlobStore', new AiBlobStoreComponent(config)))+ const uploadMaxConcurrency = config.AI_BLOB_OFFLOAD_UPLOAD_MAX_CONCURRENCY+ if (!Number.isInteger(uploadMaxConcurrency) || uploadMaxConcurrency <= 0) {+ // The ingestion config layer coerces env overrides by hand (no schema+ // validation), so a bad value would otherwise surface as a nameless+ // TypeError from p-limit at pipeline construction.+ throw new Error(+ `AI_BLOB_OFFLOAD_UPLOAD_MAX_CONCURRENCY must be a positive integer, got ${uploadMaxConcurrency}`+ )+ }+ const aiBlobOffloadConfig = {+ isTeamEnabled: buildIntegerMatcher(config.AI_BLOB_OFFLOAD_TEAMS, true),+ minBase64Length: config.AI_BLOB_OFFLOAD_MIN_BASE64_LENGTH,+ maxBlobsPerEvent: config.AI_BLOB_OFFLOAD_MAX_BLOBS_PER_EVENT,+ uploadMaxConcurrency,+ }+return new CommonIngestionConsumerScope('ai', config, scope, ({ container }) =>createAiIngestionPipeline({outputs: container.outputs,@@ -180,6 +213,8 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiSharedeventSchemaEnforcementEnabled: config.EVENT_SCHEMA_ENFORCEMENT_ENABLED,eventSchemaEnforcementManager: new EventSchemaEnforcementManager(container.postgres),topHog: createTopHogWrapper(container.topHog),+ aiBlobStore: container.aiBlobStore.store,+ aiBlobOffloadConfig,}))}diff --git a/nodejs/src/ingestion/pipelines/ai/metrics.ts b/nodejs/src/ingestion/pipelines/ai/metrics.tsindex 03aa51273542..ff2ccba379df 100644--- a/nodejs/src/ingestion/pipelines/ai/metrics.ts+++ b/nodejs/src/ingestion/pipelines/ai/metrics.ts@@ -1,4 +1,4 @@-import { Counter } from 'prom-client'+import { Counter, Histogram } from 'prom-client'export const aiCostLookupCounter = new Counter({name: 'llma_ai_cost_lookup_total',@@ -59,3 +59,63 @@ export const aiOtelGroupsCounter = new Counter({help: 'Outcome of decoding a string-valued $groups attribute back into an object',labelNames: ['outcome'],})++// The team was renamed from LLMA to AIO: metrics above keep their historical+// `llma_` prefix (dashboards depend on it); new metrics use `aio_` from now on.++export const aiBlobOffloadS3Duration = new Histogram({+ name: 'aio_blob_offload_s3_request_duration_seconds',+ help: 'Latency of S3 requests made by the AI blob offload store',+ labelNames: ['op'],+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],+})++export const aiBlobOffloadS3Errors = new Counter({+ name: 'aio_blob_offload_s3_errors_total',+ help: 'S3 request failures in the AI blob offload store',+ labelNames: ['op'],+})++// No team_id labels: AI_BLOB_OFFLOAD_TEAMS accepts '*', and per-team series on these+// happy-path counters would explode at that point. Per-team usage lives in ClickHouse.+export const aiBlobOffloadEventsCounter = new Counter({+ name: 'aio_blob_offload_events_total',+ help: 'AI events scanned by the blob offload step',+ labelNames: ['outcome'], // outcome: no_blobs | offloaded+})++export const aiBlobOffloadBlobsCounter = new Counter({+ name: 'aio_blob_offload_blobs_total',+ help: 'Blobs detected and stored by the offload step',+ labelNames: ['detector', 'mime_family', 'outcome'], // outcome: uploaded | fresh | touched+})++export const aiBlobOffloadBelowFloorCounter = new Counter({+ name: 'aio_blob_offload_below_floor_total',+ help: 'Binary payloads left inline because they are under the size floor',+})++export const aiBlobOffloadBelowFloorBytes = new Counter({+ name: 'aio_blob_offload_below_floor_bytes_total',+ help: 'Estimated decoded bytes of binary payloads left inline under the size floor',+})++export const aiBlobOffloadBlobBytes = new Histogram({+ name: 'aio_blob_offload_blob_bytes',+ help: 'Decoded size of offloaded blobs',+ labelNames: ['mime_family'],+ buckets: [1024, 8192, 65536, 262144, 1048576, 4194304, 8388608],+})++export const aiBlobOffloadBlobsPerEvent = new Histogram({+ name: 'aio_blob_offload_blobs_per_event',+ help: 'Unique blobs per offloaded event',+ buckets: [1, 2, 3, 5, 8, 13, 21],+})++// Row sizes after rewrite: kafka_producer_message_size_bytes{topic_name=<ai_events topic>}.+export const aiBlobOffloadEventBytesSaved = new Histogram({+ name: 'aio_blob_offload_event_bytes_saved',+ help: 'Serialized bytes removed per offloaded event by rewriting payloads to pointers',+ buckets: [4096, 65536, 262144, 1048576, 2097152, 4194304, 8388608],+})diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.test.tsindex 5d1ed7879f72..009266d43eee 100644--- a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts@@ -176,6 +176,13 @@ describe('AiIngestionPipeline', () => {eventSchemaEnforcementManager: {} as unknown as EventSchemaEnforcementManager,// No-op metrics wrapper — these tests assert pipeline output, not topHog counters.topHog: ((step) => step) as TopHogWrapper,+ aiBlobStore: null,+ aiBlobOffloadConfig: {+ isTeamEnabled: (): boolean => false,+ minBase64Length: 8192,+ maxBlobsPerEvent: 50,+ uploadMaxConcurrency: 8,+ },}})diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.tsindex e967d3476a7d..d1581681db7a 100644--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts@@ -51,7 +51,15 @@ import { IngestionOverflowMode } from '~/ingestion/config'import { TopHogWrapper, sum, sumOk, sumResult } from '~/ingestion/framework/extensions/tophog'import { isDropResult } from '~/ingestion/framework/results'+import { BlobStore } from './blob-offload/blob-store'import { AiEventOutput, EVENTS_OUTPUT, EventOutput } from './outputs'+import {+ OffloadAiBlobsConfig,+ createExtractAiBlobsStep,+ createUploadAiBlobStep,+ extractAiBlobsFanOut,+ mergeAiBlobPointersFanIn,+} from './pipelines/steps/offload-ai-blobs-step'import { createProcessAiEventStep } from './pipelines/steps/process-ai-event-step'export interface AiIngestionPipelineConfig {@@ -76,6 +84,8 @@ export interface AiIngestionPipelineConfig {eventSchemaEnforcementEnabled: booleaneventSchemaEnforcementManager: EventSchemaEnforcementManagertopHog: TopHogWrapper+ aiBlobStore: BlobStore | null+ aiBlobOffloadConfig: OffloadAiBlobsConfig}interface AiIngestionPipelineInput {@@ -123,6 +133,8 @@ export function createAiIngestionPipeline<eventSchemaEnforcementEnabled,eventSchemaEnforcementManager,topHog,+ aiBlobStore,+ aiBlobOffloadConfig,} = configreturn (@@ -207,6 +219,22 @@ export function createAiIngestionPipeline<).pipe(createNormalizeEventStep()).pipe(createProcessAiEventStep())+ // Blob offload: extract blobs sequentially (cheap, no I/O), then+ // upload them through a fan-out/fan-in stage so per-blob uploads+ // share one concurrency cap across the whole chunk and reuse the+ // pipeline's retry machinery instead of hand-rolled concurrency.+ .pipe(createExtractAiBlobsStep(aiBlobStore, aiBlobOffloadConfig))+ .fanOut(extractAiBlobsFanOut)+ .via((sub) =>+ sub.concurrently(+ (blob) =>+ blob.pipe(createUploadAiBlobStep(aiBlobStore), {+ retry: { tries: 5, sleepMs: 100, name: 'offload_ai_blobs' },+ }),+ { maxConcurrency: aiBlobOffloadConfig.uploadMaxConcurrency }+ )+ )+ .fanIn(mergeAiBlobPointersFanIn)// Read-only: drop person-update props so they don't// leak into person_properties (person is never written)..pipe(createStripPersonUpdatePropertiesStep())diff --git a/nodejs/src/ingestion/pipelines/ai/pipelines/steps/offload-ai-blobs-step.test.ts b/nodejs/src/ingestion/pipelines/ai/pipelines/steps/offload-ai-blobs-step.test.tsnew file mode 100644index 000000000000..7afbb3e548c8--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/pipelines/steps/offload-ai-blobs-step.test.ts@@ -0,0 +1,452 @@+import { Message } from 'node-rdkafka'++import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'+import { createOkContext } from '~/ingestion/framework/helpers'+import { PipelineResultWithContext } from '~/ingestion/framework/pipeline.interface'+import { isDlqResult, isOkResult } from '~/ingestion/framework/results'+import { withStepRetry } from '~/ingestion/framework/retry'+import { BlobStore, BlobStoreError, EnsureStoredOutcome } from '~/ingestion/pipelines/ai/blob-offload/blob-store'+import { DetectedBlob } from '~/ingestion/pipelines/ai/blob-offload/detect'+import { parseBlobPointer } from '~/ingestion/pipelines/ai/blob-offload/pointer'+import * as aiMetrics from '~/ingestion/pipelines/ai/metrics'+import { PluginEvent } from '~/plugin-scaffold'+import { createTestMessage } from '~/tests/helpers/kafka-message'+import { createTestPluginEvent } from '~/tests/helpers/plugin-event'+import { createTestTeam } from '~/tests/helpers/team'+import { Team } from '~/types'++import {+ OffloadAiBlobsConfig,+ WithAiBlobOffloadPlan,+ createExtractAiBlobsStep,+ createUploadAiBlobStep,+ extractAiBlobsFanOut,+ mergeAiBlobPointersFanIn,+} from './offload-ai-blobs-step'++// Inert metric doubles so unit tests can assert what gets recorded; each metric+// shares one inc/observe between direct calls and labels() chains.+jest.mock('~/ingestion/pipelines/ai/metrics', () => {+ const counter = () => {+ const inc = jest.fn()+ return { inc, labels: jest.fn(() => ({ inc })) }+ }+ const histogram = () => {+ const observe = jest.fn()+ return { observe, labels: jest.fn(() => ({ observe })) }+ }+ return {+ aiBlobOffloadEventsCounter: counter(),+ aiBlobOffloadBlobsCounter: counter(),+ aiBlobOffloadBelowFloorCounter: counter(),+ aiBlobOffloadBelowFloorBytes: counter(),+ aiBlobOffloadBlobBytes: histogram(),+ aiBlobOffloadBlobsPerEvent: histogram(),+ aiBlobOffloadEventBytesSaved: histogram(),+ aiBlobOffloadS3Duration: histogram(),+ aiBlobOffloadS3Errors: counter(),+ }+})++jest.mock('~/common/utils/logger', () => ({+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}))++jest.mock('~/common/utils/posthog', () => ({+ captureException: jest.fn(),+}))++const metricsMock = jest.mocked(aiMetrics)++const PNG_BYTES = Buffer.alloc(20000, 7)+const PNG_B64 = PNG_BYTES.toString('base64')++type ImageParts = { image_url: { url: string } }[]++type Input = { normalizedEvent: PluginEvent; team: Team }++class FakeBlobStore implements BlobStore {+ stored: { teamId: number; hash: string; bytes: Buffer; mime: string }[] = []+ failWith: Error | null = null++ ensureStored(teamId: number, blob: { hash: string; bytes: Buffer; mime: string }): Promise<EnsureStoredOutcome> {+ if (this.failWith) {+ return Promise.reject(this.failWith)+ }+ this.stored.push({ teamId, ...blob })+ return Promise.resolve('uploaded')+ }+}++function makeInput(properties: Record<string, unknown>): Input {+ return {+ normalizedEvent: createTestPluginEvent({ event: '$ai_generation', team_id: 2, properties }),+ team: createTestTeam({ id: 2 }),+ }+}++const CONFIG = {+ isTeamEnabled: (teamId: number): boolean => teamId === 2,+ minBase64Length: 8192,+ maxBlobsPerEvent: 50,+ uploadMaxConcurrency: 8,+}++type OffloadPlan = NonNullable<WithAiBlobOffloadPlan<Input>['aiBlobOffloadPlan']>++const EMPTY_PLAN: OffloadPlan = {+ blobs: [],+ rewrittenProps: {},+ savedChars: 0,+ belowFloorCount: 0,+ belowFloorBytes: 0,+ skipReason: null,+}++function makeBlob(hash: string, mime = 'image/png'): DetectedBlob {+ return { bytes: Buffer.alloc(16, 7), mime, hash, detector: 'data_uri' }+}++/** The same extract → fanOut → via(upload) → fanIn wiring the AI pipeline uses. */+function createOffloadPipeline(store: BlobStore | null, config: OffloadAiBlobsConfig) {+ return newChunkPipelineBuilder<Input, { message: Message }>()+ .sequentially((b) => b.pipe(createExtractAiBlobsStep(store, config)))+ .fanOut(extractAiBlobsFanOut)+ .via((sub) => sub.concurrently((b) => b.pipe(createUploadAiBlobStep(store))))+ .fanIn(mergeAiBlobPointersFanIn)+ .build()+}++async function runOffload(+ store: FakeBlobStore | null,+ config: OffloadAiBlobsConfig,+ input: Input+): Promise<PipelineResultWithContext<Input, { message: Message }>> {+ const pipeline = createOffloadPipeline(store, config)+ pipeline.feed([createOkContext(input, { message: createTestMessage() })])+ const results: PipelineResultWithContext<Input, { message: Message }>[] = []+ let chunk = await pipeline.next()+ while (chunk !== null) {+ results.push(...chunk)+ chunk = await pipeline.next()+ }+ expect(results).toHaveLength(1)+ return results[0]+}++function okEvent(result: PipelineResultWithContext<Input, { message: Message }>): PluginEvent {+ if (!isOkResult(result.result)) {+ throw new Error('expected ok result')+ }+ return result.result.value.normalizedEvent+}++describe('offloadAiBlobs stage', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ })++ it('offloads binary from heavy props and rewrites them with pointers', async () => {+ const store = new FakeBlobStore()+ const input = makeInput({+ $ai_input: [{ image_url: { url: `data:image/png;base64,${PNG_B64}` } }],+ $ai_model: 'gpt-9',+ })+ const result = await runOffload(store, CONFIG, input)+ expect(store.stored).toHaveLength(1)+ expect(store.stored[0].teamId).toBe(2)+ expect(store.stored[0].bytes.equals(PNG_BYTES)).toBe(true)+ const props = okEvent(result).properties!+ const url = (props.$ai_input as ImageParts)[0].image_url.url+ expect(parseBlobPointer(url)?.hash).toBe(store.stored[0].hash)+ expect(props.$ai_model).toBe('gpt-9')+ // original event untouched+ expect((input.normalizedEvent.properties!.$ai_input as ImageParts)[0].image_url.url.startsWith('data:')).toBe(+ true+ )+ })++ it.each([+ [+ 'team not enabled',+ new FakeBlobStore(),+ {+ isTeamEnabled: (): boolean => false,+ minBase64Length: 8192,+ maxBlobsPerEvent: 50,+ uploadMaxConcurrency: 8,+ },+ ],+ ['store not configured', null, CONFIG],+ ])('passes through untouched when %s', async (_name, store, config) => {+ const input = makeInput({ $ai_input: [{ image_url: { url: `data:image/png;base64,${PNG_B64}` } }] })+ const result = await runOffload(store, config, input)+ expect(okEvent(result)).toBe(input.normalizedEvent)+ if (store) {+ expect(store.stored).toHaveLength(0)+ }+ })++ it('passes through text-only events without touching properties', async () => {+ const store = new FakeBlobStore()+ const input = makeInput({ $ai_input: [{ role: 'user', content: 'just text' }] })+ const result = await runOffload(store, CONFIG, input)+ expect(okEvent(result)).toBe(input.normalizedEvent)+ expect(store.stored).toHaveLength(0)+ })++ it('rejects (leaving the event unmodified) when storage fails', async () => {+ const store = new FakeBlobStore()+ store.failWith = new Error('s3 down')+ const input = makeInput({ $ai_input: [{ image_url: { url: `data:image/png;base64,${PNG_B64}` } }] })+ await expect(runOffload(store, CONFIG, input)).rejects.toThrow('s3 down')+ expect((input.normalizedEvent.properties!.$ai_input as ImageParts)[0].image_url.url.startsWith('data:')).toBe(+ true+ )+ })++ it.each([+ ['at the limit', 2, 2],+ ['over the limit', 3, 0],+ ])('enforces the per-event distinct blob limit (%s)', async (_name, blobCount, expectedStored) => {+ const store = new FakeBlobStore()+ const parts = Array.from({ length: blobCount }, (_, i) => ({+ image_url: { url: `data:image/png;base64,${Buffer.alloc(8192, i).toString('base64')}` },+ }))+ const input = makeInput({ $ai_input: parts })+ const result = await runOffload(store, { ...CONFIG, maxBlobsPerEvent: 2 }, input)+ expect(store.stored).toHaveLength(expectedStored)+ if (expectedStored === 0) {+ expect(okEvent(result)).toBe(input.normalizedEvent)+ }+ })++ it('deduplicates identical blobs across multiple heavy props', async () => {+ const store = new FakeBlobStore()+ const imageUrl = `data:image/png;base64,${PNG_B64}`+ const input = makeInput({+ $ai_input: [{ image_url: { url: imageUrl } }],+ $ai_output: [{ image_url: { url: imageUrl } }],+ })+ const result = await runOffload(store, CONFIG, input)+ expect(store.stored).toHaveLength(1)+ const storedHash = store.stored[0].hash+ const props = okEvent(result).properties!+ const inputUrl = (props.$ai_input as ImageParts)[0].image_url.url+ const outputUrl = (props.$ai_output as ImageParts)[0].image_url.url+ expect(parseBlobPointer(inputUrl)?.hash).toBe(storedHash)+ expect(parseBlobPointer(outputUrl)?.hash).toBe(storedHash)+ })++ describe('createExtractAiBlobsStep', () => {+ async function extract(+ store: BlobStore | null,+ config: OffloadAiBlobsConfig,+ properties: Record<string, unknown>+ ): Promise<{ input: Input; value: WithAiBlobOffloadPlan<Input> }> {+ const input = makeInput(properties)+ const result = await createExtractAiBlobsStep(store, config)(input)+ if (!isOkResult(result)) {+ throw new Error('expected ok result')+ }+ return { input, value: result.value }+ }++ it.each([+ ['store not configured', null, CONFIG],+ ['team not enabled', new FakeBlobStore(), { ...CONFIG, isTeamEnabled: (): boolean => false }],+ ])('attaches a null plan (not a skip) when %s', async (_name, store, config) => {+ const { input, value } = await extract(store, config, {+ $ai_input: [{ image_url: { url: `data:image/png;base64,${PNG_B64}` } }],+ })+ // Null must not degrade into a skip plan: skip plans record metrics+ // on fan-in, and disabled events must record nothing.+ expect(value.aiBlobOffloadPlan).toBeNull()+ expect(value.normalizedEvent).toBe(input.normalizedEvent)+ })++ it.each([+ ['text-only properties', { $ai_input: [{ role: 'user', content: 'just text' }] }, 0, 0],+ [+ 'below-floor payloads',+ {+ $ai_input: [+ { image_url: { url: `data:image/png;base64,${Buffer.alloc(600).toString('base64')}` } },+ ],+ },+ 1,+ 600,+ ],+ ])('plans a no_blobs skip for %s', async (_name, properties, belowFloorCount, belowFloorBytes) => {+ const { value } = await extract(new FakeBlobStore(), CONFIG, properties)+ expect(value.aiBlobOffloadPlan).toMatchObject({+ skipReason: 'no_blobs',+ blobs: [],+ belowFloorCount,+ belowFloorBytes,+ })+ })++ it('plans a blob_limit_exceeded skip without retaining blob buffers', async () => {+ const properties = {+ $ai_input: Array.from({ length: 2 }, (_, i) => ({+ image_url: { url: `data:image/png;base64,${Buffer.alloc(8192, i).toString('base64')}` },+ })),+ }+ const { value } = await extract(new FakeBlobStore(), { ...CONFIG, maxBlobsPerEvent: 1 }, properties)+ // blobs must stay empty on this path so the plan doesn't pin large+ // buffers for an event that will never upload them.+ expect(value.aiBlobOffloadPlan).toMatchObject({ skipReason: 'blob_limit_exceeded', blobs: [] })+ })++ it('deduplicates blobs by hash and accounts saved chars across properties', async () => {+ const url = `data:image/png;base64,${PNG_B64}`+ const { value } = await extract(new FakeBlobStore(), CONFIG, {+ $ai_input: [{ image_url: { url } }],+ $ai_output: [{ image_url: { url } }],+ })+ const plan = value.aiBlobOffloadPlan!+ expect(plan.skipReason).toBeNull()+ expect(plan.blobs).toHaveLength(1)+ expect(plan.blobs[0].bytes.equals(PNG_BYTES)).toBe(true)+ const inputPointer = (plan.rewrittenProps.$ai_input as ImageParts)[0].image_url.url+ const outputPointer = (plan.rewrittenProps.$ai_output as ImageParts)[0].image_url.url+ expect(parseBlobPointer(inputPointer)?.hash).toBe(plan.blobs[0].hash)+ expect(outputPointer).toBe(inputPointer)+ // Both occurrences count toward savedChars, dedup notwithstanding.+ expect(plan.savedChars).toBe(2 * (url.length - inputPointer.length))+ })+ })++ describe('extractAiBlobsFanOut', () => {+ it.each([+ ['a null plan', null],+ ["a 'no_blobs' skip", { ...EMPTY_PLAN, skipReason: 'no_blobs' as const }],+ ["a 'blob_limit_exceeded' skip", { ...EMPTY_PLAN, skipReason: 'blob_limit_exceeded' as const }],+ ])('fans out to nothing for %s', (_name, plan) => {+ expect(extractAiBlobsFanOut({ ...makeInput({}), aiBlobOffloadPlan: plan })).toEqual([])+ })++ it('fans out one upload per blob with the owning team id', () => {+ const blobs = [makeBlob('hash-1'), makeBlob('hash-2')]+ const uploads = extractAiBlobsFanOut({ ...makeInput({}), aiBlobOffloadPlan: { ...EMPTY_PLAN, blobs } })+ expect(uploads).toEqual([+ { teamId: 2, blob: blobs[0] },+ { teamId: 2, blob: blobs[1] },+ ])+ })+ })++ describe('createUploadAiBlobStep', () => {+ it('rejects with the wiring-bug error when no store is configured', async () => {+ const step = createUploadAiBlobStep(null)+ await expect(step({ teamId: 2, blob: makeBlob('hash-1') })).rejects.toThrow(+ 'AI blob upload step invoked without a configured blob store'+ )+ })++ it('passes the store outcome through in the result value', async () => {+ const blob = makeBlob('hash-1')+ const ensureStored = jest.fn().mockResolvedValue('touched')+ const result = await createUploadAiBlobStep({ ensureStored })({ teamId: 7, blob })+ // The outcome feeds the per-blob metric label on fan-in, so it must+ // survive verbatim, not collapse to 'uploaded'.+ expect(isOkResult(result) && result.value).toEqual({ blob, outcome: 'touched' })+ expect(ensureStored).toHaveBeenCalledWith(7, blob)+ })++ // Production retry options (tries/name), with a 1ms sleep per the+ // retry.test.ts convention so the exhaustion path stays fast.+ describe('under the production retry wrapper', () => {+ const RETRY = { tries: 5, sleepMs: 1, name: 'offload_ai_blobs' }++ it('turns a non-retriable store failure into a dlq sub-result without retrying', async () => {+ const error = new BlobStoreError('blob can never be stored', false)+ const ensureStored = jest.fn().mockRejectedValue(error)+ const step = withStepRetry(createUploadAiBlobStep({ ensureStored }), RETRY)+ const result = await step({ teamId: 2, blob: makeBlob('hash-1') })+ // The DLQ sub-result is what the fan-out stage aggregates into a+ // parent-level DLQ — the consumer must not crash on this path.+ expect(isDlqResult(result)).toBe(true)+ expect(isDlqResult(result) && result.error).toBe(error)+ expect(ensureStored).toHaveBeenCalledTimes(1)+ })++ it('rejects after exhausting retries for a retriable failure', async () => {+ const ensureStored = jest.fn().mockRejectedValue(new BlobStoreError('socket hang up', true))+ const step = withStepRetry(createUploadAiBlobStep({ ensureStored }), RETRY)+ await expect(step({ teamId: 2, blob: makeBlob('hash-1') })).rejects.toThrow('socket hang up')+ expect(ensureStored).toHaveBeenCalledTimes(5)+ })++ it('recovers when a transient failure resolves within the retry budget', async () => {+ const ensureStored = jest+ .fn()+ .mockRejectedValueOnce(new BlobStoreError('flaky', true))+ .mockResolvedValueOnce('uploaded')+ const step = withStepRetry(createUploadAiBlobStep({ ensureStored }), RETRY)+ const result = await step({ teamId: 2, blob: makeBlob('hash-1') })+ expect(isOkResult(result) && result.value.outcome).toBe('uploaded')+ expect(ensureStored).toHaveBeenCalledTimes(2)+ })+ })+ })++ describe('mergeAiBlobPointersFanIn', () => {+ it('strips the plan key and records nothing for a null plan', () => {+ const input = makeInput({ $ai_model: 'gpt-9' })+ const merged = mergeAiBlobPointersFanIn({ ...input, aiBlobOffloadPlan: null }, [])+ expect(merged).toEqual(input)+ expect('aiBlobOffloadPlan' in merged).toBe(false)+ expect(merged.normalizedEvent).toBe(input.normalizedEvent)+ expect(metricsMock.aiBlobOffloadEventsCounter.labels).not.toHaveBeenCalled()+ expect(metricsMock.aiBlobOffloadBelowFloorCounter.inc).not.toHaveBeenCalled()+ })++ it.each([['no_blobs' as const], ['blob_limit_exceeded' as const]])(+ 'records the %s skip and its below-floor counts without touching the event',+ (skipReason) => {+ const input = makeInput({ $ai_model: 'gpt-9' })+ const plan = { ...EMPTY_PLAN, skipReason, belowFloorCount: 3, belowFloorBytes: 1200 }+ const merged = mergeAiBlobPointersFanIn({ ...input, aiBlobOffloadPlan: plan }, [])+ expect(merged.normalizedEvent).toBe(input.normalizedEvent)+ expect('aiBlobOffloadPlan' in merged).toBe(false)+ expect(metricsMock.aiBlobOffloadEventsCounter.labels).toHaveBeenCalledWith(skipReason)+ expect(metricsMock.aiBlobOffloadBelowFloorCounter.inc).toHaveBeenCalledWith(3)+ expect(metricsMock.aiBlobOffloadBelowFloorBytes.inc).toHaveBeenCalledWith(1200)+ expect(metricsMock.aiBlobOffloadBlobsPerEvent.observe).not.toHaveBeenCalled()+ }+ )++ it('merges rewritten properties over the event and records offload metrics', () => {+ const imageBlob = makeBlob('hash-1')+ const audioBlob = makeBlob('hash-2', 'audio/mp3')+ const input = makeInput({ $ai_input: [{ image_url: { url: 'data:original' } }], $ai_model: 'gpt-9' })+ const plan = {+ ...EMPTY_PLAN,+ blobs: [imageBlob, audioBlob],+ rewrittenProps: { $ai_input: [{ image_url: { url: 'posthog-blob://rewritten' } }] },+ savedChars: 123,+ }+ const merged = mergeAiBlobPointersFanIn({ ...input, aiBlobOffloadPlan: plan }, [+ { blob: imageBlob, outcome: 'uploaded' },+ { blob: audioBlob, outcome: 'fresh' },+ ])+ expect(merged.normalizedEvent.properties).toEqual({+ $ai_input: [{ image_url: { url: 'posthog-blob://rewritten' } }],+ $ai_model: 'gpt-9',+ })+ expect('aiBlobOffloadPlan' in merged).toBe(false)+ // Original event untouched — the rewrite must not mutate in place.+ expect((input.normalizedEvent.properties!.$ai_input as ImageParts)[0].image_url.url).toBe('data:original')+ expect(metricsMock.aiBlobOffloadBlobsCounter.labels).toHaveBeenCalledWith('data_uri', 'image', 'uploaded')+ expect(metricsMock.aiBlobOffloadBlobsCounter.labels).toHaveBeenCalledWith('data_uri', 'audio', 'fresh')+ expect(metricsMock.aiBlobOffloadBlobBytes.labels).toHaveBeenCalledWith('image')+ expect(metricsMock.aiBlobOffloadBlobBytes.labels).toHaveBeenCalledWith('audio')+ expect(metricsMock.aiBlobOffloadBlobsPerEvent.observe).toHaveBeenCalledWith(2)+ expect(metricsMock.aiBlobOffloadEventBytesSaved.observe).toHaveBeenCalledWith(123)+ expect(metricsMock.aiBlobOffloadEventsCounter.labels).toHaveBeenCalledWith('offloaded')+ expect(metricsMock.aiBlobOffloadBelowFloorCounter.inc).not.toHaveBeenCalled()+ })+ })+})diff --git a/nodejs/src/ingestion/pipelines/ai/pipelines/steps/offload-ai-blobs-step.ts b/nodejs/src/ingestion/pipelines/ai/pipelines/steps/offload-ai-blobs-step.tsnew file mode 100644index 000000000000..18745007b1fb--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/pipelines/steps/offload-ai-blobs-step.ts@@ -0,0 +1,220 @@+import { LARGE_AI_PROPERTIES } from '~/ingestion/common/subpipelines/large-ai-properties'+import { ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'+import { BlobStore, EnsureStoredOutcome } from '~/ingestion/pipelines/ai/blob-offload/blob-store'+import { DetectedBlob, extractBlobs } from '~/ingestion/pipelines/ai/blob-offload/detect'+import {+ aiBlobOffloadBelowFloorBytes,+ aiBlobOffloadBelowFloorCounter,+ aiBlobOffloadBlobBytes,+ aiBlobOffloadBlobsCounter,+ aiBlobOffloadBlobsPerEvent,+ aiBlobOffloadEventBytesSaved,+ aiBlobOffloadEventsCounter,+} from '~/ingestion/pipelines/ai/metrics'+import { PluginEvent } from '~/plugin-scaffold'+import { Team, ValueMatcher } from '~/types'++export interface OffloadAiBlobsConfig {+ /** Gates offload per team; events from non-matching teams pass through with a null plan. */+ isTeamEnabled: ValueMatcher<number>+ /**+ * Minimum base64 payload length for a data URI to count as an offloadable+ * blob. Shorter payloads stay inline and are only counted as below-floor+ * in metrics.+ */+ minBase64Length: number+ /**+ * Cap on distinct (hash-deduplicated) blobs per event. Exceeding it skips+ * offload for the whole event rather than offloading a subset, so the+ * event passes through as if detection had missed.+ */+ maxBlobsPerEvent: number+ /**+ * Chunk-wide cap on concurrent blob uploads (applied via the fan-out+ * stage's `concurrently` block), so a many-blob chunk can't monopolize the+ * S3 socket pool and per-request timeouts start when a request runs, not+ * when it's queued.+ */+ uploadMaxConcurrency: number+}++type OffloadAiBlobsInput = {+ normalizedEvent: PluginEvent+ team: Team+}++const MIME_FAMILIES = new Set(['image', 'audio', 'video', 'text', 'application'])++function mimeFamily(mime: string): string {+ const family = mime.split('/')[0]+ return MIME_FAMILIES.has(family) ? family : 'other'+}++/**+ * Everything the extraction step computed that the fan-in needs to finish the+ * offload once the blobs are durable. Metrics recording is deferred to the+ * fan-in so nothing is counted for an event whose uploads ultimately fail.+ */+interface AiBlobOffloadPlan {+ /** Deduplicated blobs to upload; empty when skipReason is set. */+ blobs: DetectedBlob[]+ /** Heavy properties rewritten with blob pointers, applied on fan-in. */+ rewrittenProps: Record<string, unknown>+ savedChars: number+ belowFloorCount: number+ belowFloorBytes: number+ skipReason: 'no_blobs' | 'blob_limit_exceeded' | null+}++export type WithAiBlobOffloadPlan<T> = T & { aiBlobOffloadPlan: AiBlobOffloadPlan | null }++export interface PendingAiBlobUpload {+ teamId: number+ blob: DetectedBlob+}++export interface UploadedAiBlob {+ blob: DetectedBlob+ outcome: EnsureStoredOutcome+}++/**+ * Cheap sequential step: detect blobs in the heavy AI properties and attach an+ * offload plan to the event. No I/O and no metrics — uploads happen in the+ * fan-out/fan-in stage's subpipeline, and metrics are recorded on fan-in.+ * A null plan means offload is disabled for this event (no store, or team not+ * enrolled) and the event passes through the stage untouched.+ */+export function createExtractAiBlobsStep<T extends OffloadAiBlobsInput>(+ store: BlobStore | null,+ config: OffloadAiBlobsConfig+): ProcessingStep<T, WithAiBlobOffloadPlan<T>> {+ const extractionOpts = { minBase64Length: config.minBase64Length }+ return function extractAiBlobsStep(input) {+ if (!store || !config.isTeamEnabled(input.team.id)) {+ return Promise.resolve(ok({ ...input, aiBlobOffloadPlan: null }))+ }++ const properties = input.normalizedEvent.properties ?? {}+ const rewrittenProps: Record<string, unknown> = {}+ const blobsByHash = new Map<string, DetectedBlob>()+ let savedChars = 0+ let belowFloorCount = 0+ let belowFloorBytes = 0++ for (const key of LARGE_AI_PROPERTIES) {+ const value = properties[key]+ if (value === undefined || value === null) {+ continue+ }+ const extraction = extractBlobs(value, extractionOpts)+ belowFloorCount += extraction.belowFloorCount+ belowFloorBytes += extraction.belowFloorBytes+ if (extraction.blobs.length === 0) {+ continue+ }+ for (const blob of extraction.blobs) {+ blobsByHash.set(blob.hash, blob)+ }+ rewrittenProps[key] = extraction.value+ savedChars += extraction.savedChars+ }++ const plan: AiBlobOffloadPlan = {+ blobs: [],+ rewrittenProps,+ savedChars,+ belowFloorCount,+ belowFloorBytes,+ skipReason: null,+ }+ if (blobsByHash.size === 0) {+ plan.skipReason = 'no_blobs'+ } else if (blobsByHash.size > config.maxBlobsPerEvent) {+ // Skipping entirely (rather than offloading a subset) keeps the conservative+ // posture: the event passes through exactly as if detection had missed.+ plan.skipReason = 'blob_limit_exceeded'+ } else {+ plan.blobs = [...blobsByHash.values()]+ }+ return Promise.resolve(ok({ ...input, aiBlobOffloadPlan: plan }))+ }+}++/** Fan-out: one sub-element per blob to upload; disabled/skipped events fan out to nothing. */+export function extractAiBlobsFanOut<T extends OffloadAiBlobsInput>(+ input: WithAiBlobOffloadPlan<T>+): PendingAiBlobUpload[] {+ const plan = input.aiBlobOffloadPlan+ if (!plan || plan.skipReason) {+ return []+ }+ return plan.blobs.map((blob) => ({ teamId: input.team.id, blob }))+}++/**+ * Per-blob upload step. Upload-before-emit: every blob must be confirmed+ * durable before the rewritten event exists anywhere. Failure contract, in+ * concert with the step's retry options and the store's error contract+ * (BlobStoreError): a non-retriable store failure means this blob can never+ * be stored — determined by the event's own content — and becomes a DLQ+ * sub-result, which the fan-out stage aggregates into a parent-level DLQ;+ * the event dead-letters instead of being emitted with pointers to blobs+ * that were never stored. Retriable store failures (transient or+ * environment-wide) retry and, on exhaustion, crash the consumer;+ * environment-wide problems are also caught before traffic by the store's+ * startup healthcheck.+ */+export function createUploadAiBlobStep(store: BlobStore | null): ProcessingStep<PendingAiBlobUpload, UploadedAiBlob> {+ return async function uploadAiBlobStep(upload) {+ if (!store) {+ // Extraction never fans out without a store, so this is a wiring bug.+ throw new Error('AI blob upload step invoked without a configured blob store')+ }+ const outcome = await store.ensureStored(upload.teamId, upload.blob)+ return ok({ blob: upload.blob, outcome })+ }+}++/**+ * Fan-in: only reached when every upload succeeded (or nothing fanned out).+ * Records the offload metrics and applies the rewritten properties, dropping+ * the plan (and the blob buffers it holds) from the value.+ */+export function mergeAiBlobPointersFanIn<T extends WithAiBlobOffloadPlan<OffloadAiBlobsInput>>(+ original: T,+ uploads: UploadedAiBlob[]+): Omit<T, 'aiBlobOffloadPlan' | 'normalizedEvent'> & { normalizedEvent: PluginEvent } {+ const { aiBlobOffloadPlan: plan, normalizedEvent, ...rest } = original+ if (!plan) {+ return { ...rest, normalizedEvent }+ }++ if (plan.belowFloorCount > 0) {+ aiBlobOffloadBelowFloorCounter.inc(plan.belowFloorCount)+ aiBlobOffloadBelowFloorBytes.inc(plan.belowFloorBytes)+ }++ if (plan.skipReason) {+ aiBlobOffloadEventsCounter.labels(plan.skipReason).inc()+ return { ...rest, normalizedEvent }+ }++ for (const { blob, outcome } of uploads) {+ aiBlobOffloadBlobsCounter.labels(blob.detector, mimeFamily(blob.mime), outcome).inc()+ aiBlobOffloadBlobBytes.labels(mimeFamily(blob.mime)).observe(blob.bytes.length)+ }+ aiBlobOffloadBlobsPerEvent.observe(uploads.length)+ aiBlobOffloadEventBytesSaved.observe(plan.savedChars)+ aiBlobOffloadEventsCounter.labels('offloaded').inc()++ const properties = normalizedEvent.properties ?? {}+ return {+ ...rest,+ normalizedEvent: {+ ...normalizedEvent,+ properties: { ...properties, ...plan.rewrittenProps },+ },+ }+}