A session commit reports success, and the memory extraction behind it produced zero memories. Nothing failed, no metric moved, the run is marked done, and whatever the model learned is gone.
That's the failure pm25coder wrote up on dev.to in September, from issue #4580 on volcengine/OpenViking. The title says it better than I can: "The extraction returned zero memories, and nothing screamed."
It isn't my incident. But the pipelines I've written up on this blog have the same hole. Neither the SQS and Bedrock job handler nor the RAG ingestion state machine compares what went in with what landed.
The rule I'd add to both: a pipeline that processes a non-empty input and writes nothing has failed, even if every status says OK. The one exception is when it can say why.
Every green light here is telling the truth
Our tooling is built to catch crashes. An empty success isn't a crash, so each layer reports correctly on the narrow thing it measures.
- Lambda's
Errorsmetric counts invocations that end in a function error. A handler that returns normally isn't one. - SQS deletes the messages when the handler returns an empty
batchItemFailures. - A Step Functions Map state over an empty array has nothing to fail on.
- Retries don't fire, because nothing threw.
Every check mark is true. The two crosses are what actually happened, and nothing on the left side of the diagram can see them.Run the bug yourself before reading any code. The figure below runs one ten-message SQS batch through a memory-extract Lambda. Pick what goes wrong, run the batch, and compare what AWS shows with what actually landed. Then switch the handler to the contract from the next section and run the same bug again. Flip function_response_types off too, because that one bites people who did everything else right.
▶ Try the interactive demo on harun.dev
The Langfuse and CloudWatch setup I wrote about earlier won't catch this either. It tells you what the model did and what it cost. This post is about one narrower question: did anything land?
The contract is three fields and one excuse
Every batch, extraction and ingest Lambda returns the same shape, {ok, itemsWritten, errors[]}. I'd add a fourth optional field, because SQS is at-least-once and a redelivered message can legitimately write nothing when the first delivery already did the work. The idempotent re-run in the RAG post does that on purpose. Without a way to say so, every duplicate looks like the bug.
export type HrrError = { code: string; message: string }; export type HrrResult = { ok: boolean; itemsWritten: number; errors: HrrError[]; emptyReason?: "duplicate" | "nothing_to_extract" | "empty_input"; }; type HrrPolicy = "WARN" | "FAIL"; export function hrr_verdict(result: HrrResult, onUnexplainedEmpty: HrrPolicy) { if (!result.ok) return "FAIL"; if (result.itemsWritten > 0) return "OK"; if (result.emptyReason && result.errors.length === 0) return "OK"; return onUnexplainedEmpty; } hrr_verdict assumes the input wasn't empty. An empty input has to say empty_input out loud, same as any other excuse, and an excuse doesn't count if errors has anything in it.
One result in, one route out. Only FAIL keeps the input; WARN leaves it to the alarm.WARN or FAIL is a per-pipeline decision. These are the defaults I'd start with.
| Pipeline | Zero writes on non-empty input means | Verdict |
|---|---|---|
| RAG embed and index | A document with text produced no vectors. Only "every chunk was a duplicate" excuses it. | FAIL |
| Memory extraction | Fine if the model called the tool and said nothing_to_extract. Anything else is unexplained. | FAIL |
| Ticket sync | An empty delta is common and a retry won't change it. A sudden spike is still worth seeing. | WARN |
One thing the whole contract depends on: itemsWritten has to come from what the store confirmed. If it's memories.length, you've counted your intentions.
export function hrr_makeProcessor(deps: { callModel: (prompt: string) => Promise<any>; write: (memories: unknown[]) => Promise<{ written: number; duplicates: number }>; }) { return async (body: string): Promise<HrrResult> => { const { memories, emptyReason, errors } = await hrr_extract(body, deps.callModel); if (memories === null) return { ok: false, itemsWritten: 0, errors }; if (memories.length === 0) return { ok: true, itemsWritten: 0, errors, emptyReason }; const { written, duplicates } = await deps.write(memories); const allDuplicates = written === 0 && duplicates === memories.length; return { ok: true, itemsWritten: written, errors, ...(allDuplicates ? { emptyReason: "duplicate" as const } : {}), }; }; } Send the same numbers to CloudWatch, without console.log
A returned object only helps a caller that reads it. The same counts go out as CloudWatch Embedded Metric Format, one JSON line per invocation.
export function hrr_emitMetrics(pipeline: string, counts: Record<string, number>) { // console.log adds a timestamp and request ID in text log format, which breaks EMF. process.stdout.write( JSON.stringify({ _aws: { Timestamp: Date.now(), CloudWatchMetrics: [ { Namespace: "Hrr/Pipelines", Dimensions: [["Pipeline"]], Metrics: Object.keys(counts).map((Name) => ({ Name, Unit: "Count" })), }, ], }, Pipeline: pipeline, ...counts, }) + "\n", ); } The EMF spec wants a log event that is a JSON object with nothing before or after it. Lambda's default text format can't produce one: the Node runtime adds a timestamp, request ID and level to everything console.log writes, and in JSON log format CloudWatch can stop recognizing EMF that went through console.log at all. AWS's fix is process.stdout.write. That's what this uses.
Emit zeros, because a rate needs its denominator in every period. Keep messageId out of the dimensions too: every unique dimension value creates a new custom metric.
In partial batch responses, an empty list means delete everything
The handler's only way to tell Lambda about a bad message is batchItemFailures, and the rules are strict.
| Handler does | Lambda treats the batch as |
|---|---|
Returns an empty or null batchItemFailures, or an empty or null response | Complete success |
Returns specific valid itemIdentifier values | Partial failure. Only those messages come back. |
| Throws | Complete failure |
Returns invalid JSON, or an itemIdentifier that's empty, null, misnamed, or not in the batch | Complete failure |
A no-op writer plus { batchItemFailures: [] } is the worst version of this bug. Lambda reports success and SQS deletes the input. There's nothing left to replay. FAIL has to become an entry in that list, so the message comes back and eventually lands in the DLQ with its body intact.
export function hrr_makeSqsHandler(deps: { pipeline: string; onUnexplainedEmpty: HrrPolicy; process: (body: string) => Promise<HrrResult>; }) { return async (event: SQSEvent): Promise<SQSBatchResponse> => { const batchItemFailures: SQSBatchItemFailure[] = []; const counts = { Messages: 0, FailedMessages: 0, ItemsWritten: 0, ItemErrors: 0, ZeroWrites: 0, UnexplainedZeroWrites: 0, }; for (const record of event.Records) { let result: HrrResult; try { result = await deps.process(record.body); } catch (err) { result = { ok: false, itemsWritten: 0, errors: [{ code: "exception", message: String(err) }], }; } const verdict = hrr_verdict(result, deps.onUnexplainedEmpty); counts.Messages += 1; counts.ItemsWritten += result.itemsWritten; counts.ItemErrors += result.errors.length; if (result.ok && result.itemsWritten === 0) counts.ZeroWrites += 1; if (result.ok && verdict !== "OK") counts.UnexplainedZeroWrites += 1; if (verdict !== "OK") { console.warn(JSON.stringify({ verdict, messageId: record.messageId, ...result })); } if (verdict === "FAIL") { counts.FailedMessages += 1; batchItemFailures.push({ itemIdentifier: record.messageId }); } } hrr_emitMetrics(deps.pipeline, counts); return { batchItemFailures }; }; } The catch is the standard pattern, and it also means per-message exceptions never reach Lambda's Errors metric. FailedMessages exists to count them.
SQS isn't a caller that reads your contract. The full result goes to the log, and the counts go to EMF. The response stays as just batchItemFailures. That's the only key AWS documents for it.
resource "aws_sqs_queue" "hrr_extract_dlq" { name = "hrr-memory-extract-dlq" } resource "aws_sqs_queue" "hrr_extract" { name = "hrr-memory-extract" visibility_timeout_seconds = 360 # 6x the 60s function timeout redrive_policy = jsonencode({ deadLetterTargetArn = aws_sqs_queue.hrr_extract_dlq.arn maxReceiveCount = 5 }) } resource "aws_lambda_event_source_mapping" "hrr_extract" { event_source_arn = aws_sqs_queue.hrr_extract.arn function_name = aws_lambda_function.hrr_extract.arn batch_size = 10 function_response_types = ["ReportBatchItemFailures"] } Don't forget function_response_types. Without it, the list your handler returns isn't a partial batch response, and the unit test below can't tell. maxReceiveCount of 5 and a visibility timeout of six times the function timeout are AWS's recommendations.
FAIL has a price. If the writer is broken for everyone, every message runs the whole extraction up to five times before reaching the DLQ, and AWS notes that Lambda doesn't scale down polling on failed invocations when ReportBatchItemFailures is on. I'd still pay it for pipelines where losing the input is worse than the repeat calls. Where it isn't, use WARN and let the alarm do the work.
A FIFO queue needs a different loop: stop at the first failure and return everything unprocessed, so ordering holds.
Three ways a model reply turns into nothing
The OpenViking report had three gaps, and the dev.to write-up explains why each one looked defensible on its own. That stack was a self-hosted model server. This is my adaptation to Bedrock, not something the report measured there.
The wrong parse channel. In the original, tool-call markup leaked into the content field and the parser only looked in the structured channel, and since Converse separates text and toolUse blocks the same markup may never show up. The same shape can, though: tool JSON sitting in a text block with no toolUse at all. Setting toolChoice to any or tool narrows this down where the model supports it. I'd keep the check anyway, since stopReason can also come back as malformed_model_output or malformed_tool_use.
The retry budget spent on garbage. One shared format-retry counter means a junk reply can use the only retry before a real formatting slip shows up. Each failure kind gets its own budget.
The flag that disabled the recovery path. A flag built for "the model called a tool that doesn't exist" was reused for any parse failure, so a model that answered "let me search first" ran its next iteration with tools off and guaranteed the empty result. The fix below is blunt: callModel has no parameter that turns tools off. Nobody can reuse it. A bad reply changes the prompt and nothing else.
const HRR_TOOL = "hrr_save_memories"; const HRR_BUDGET = { wrong_channel: 1, prose: 2, malformed: 1 }; type HrrReply = | { kind: "tool"; input: any } | { kind: keyof typeof HRR_BUDGET; text: string }; export function hrr_readReply(response: any): HrrReply { const blocks = response.output?.message?.content ?? []; const call = blocks.find((b: any) => b.toolUse?.name === HRR_TOOL)?.toolUse; if (call) return { kind: "tool", input: call.input }; const text = blocks.map((b: any) => b.text ?? "").join("").trim(); if (response.stopReason?.startsWith("malformed_")) return { kind: "malformed", text }; const looksLikeACall = text.startsWith("{") || text.includes(HRR_TOOL); return { kind: looksLikeACall ? "wrong_channel" : "prose", text }; } export async function hrr_extract( transcript: string, callModel: (prompt: string) => Promise<any>, ) { const left = { ...HRR_BUDGET }; const errors: HrrError[] = []; let hint = ""; while (true) { const reply = hrr_readReply(await callModel(transcript + hint)); if (reply.kind === "tool") return { ...reply.input, errors }; errors.push({ code: reply.kind, message: reply.text.slice(0, 200) }); if (left[reply.kind]-- === 0) return { memories: null, errors }; hint = `\n\nCall ${HRR_TOOL}. Put the result in the tool call, not in text.`; } } Every failed attempt goes into errors, and those reach ItemErrors. That closes the third gap from the original report, where the list existed and never left the container. As the write-up puts it, "A failure that is logged is not a failure that is visible." The maintainers later closed the issue as a serving and model-side problem, according to that post's update, and parse-failure counters went into a separate PR, still open as of November 2026.
A Map state can succeed over nothing
Step Functions has the same blind spot one level up. A Map state's output is an array of iteration outputs, and an empty array is a perfectly valid result. The check goes in a Choice right after each Map.
The definition below is the part that matters, in JSONata. A chunking Task before it returns documentId, documentBytes and chunks, and each iteration returns the contract.
"HrrEmbedChunks": { "Type": "Map", "Items": "{% $states.input.chunks %}", "MaxConcurrency": 5, "ItemProcessor": { "ProcessorConfig": { "Mode": "INLINE" }, "StartAt": "HrrEmbedOne", "States": { "HrrEmbedOne": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "Arguments": { "FunctionName": "${embed_fn_arn}", "Payload": "{% $states.input %}" }, "Output": "{% $states.result.Payload %}", "End": true } } }, "Output": { "documentId": "{% $states.input.documentId %}", "documentBytes": "{% $states.input.documentBytes %}", "iterations": "{% $count($states.result) %}", "itemsWritten": "{% $sum($append([0], $states.result.itemsWritten)) %}", "explainedEmpty": "{% $count($states.result[emptyReason]) %}", "errors": "{% $append([], $states.result.errors) %}" }, "Catch": [ { "ErrorEquals": ["States.ALL"], "Output": { "documentId": "{% $states.input.documentId %}", "error": "{% $states.errorOutput %}" }, "Next": "HrrNotifyFailure" } ], "Next": "HrrCheckWrites" }, "HrrCheckWrites": { "Type": "Choice", "Choices": [ { "Condition": "{% $states.input.documentBytes > 0 and $states.input.itemsWritten = 0 and ($states.input.iterations = 0 or $states.input.explainedEmpty < $states.input.iterations) %}", "Next": "HrrNotifyFailure" } ], "Default": "HrrDone" }, "HrrNotifyFailure": { "Type": "Task", "Resource": "arn:aws:states:::sns:publish", "Arguments": { "TopicArn": "${alerts_topic_arn}", "Subject": "hrr ingest wrote nothing or failed", "Message"Source:https://dev.to/harundotdev/how-to-catch-aws-lambda-jobs-that-succeed-but-write-nothing-1lf8Related posts

