Repository navigation
fix(lambda): omit FunctionError and LogResult unless applicable (#393) - #416
Merged
Merged
Conversation
Reported as four per-service typos; three were one defect in the server's shared error writer. writeError emitted a "Code" member for every JSON service. botocore's BaseJSONParser._do_error_parse reads "__type" and falls back to the stringified HTTP status -- it never reads "Code". SSM's already-correct ParameterNotFound was therefore discarded and callers saw Error.Code == "404", silently defeating every `except ClientError` branch that compares against a symbolic code. That affected all ~30 JSON-RPC services, not just the one reported. Lambda was worse: it is REST-JSON but sends Content-Type application/json, which failed the "application/x-amz-json" prefix test, so its errors were emitted as XML -- a shape its SDK cannot parse at all. The protocol cannot be sniffed from the request. IAM sends x-amz-json-1.1 inbound yet answers errors in XML, and Lambda's inbound application/json is indistinguishable from a plain JSON body. So the service name now selects it, via a table whose every entry is the "protocol" field of that service's model in botocore/data -- the same value that picks the SDK's parser. Unclassified services keep the old Content-Type sniff. Also fixed, from the same issue: - IAM wire codes drop the Exception suffix that the API model's shape names carry: NoSuchEntity, EntityAlreadyExists, MalformedPolicyDocument, DeleteConflict, LimitExceeded. Not a blanket rule -- ValidationError and AccessDeniedException were already right per IAM's CommonErrors, and Lambda genuinely uses ResourceNotFoundException, so neither service's spelling can be inferred from the other. - S3 GetObject/HeadObject report NoSuchBucket for a missing bucket instead of NoSuchKey, which conflated a deleted bucket with an unwritten object. - The service reference had ACM as Query and RAM as JSON; both were wrong in the opposite direction (ACM is JSON-RPC, RAM is REST-JSON). Verified against the AWS API references and botocore's parsers.py rather than inferred, since a misclassification reproduces exactly the wrong-wire-shape bug this fixes.
Invoke sent X-Amz-Function-Error and X-Amz-Log-Result unconditionally, the
former with an empty value. AWS documents FunctionError as "if present,
indicates that an error occurred", so the SDK maps its absence to the key
being absent from the response. The natural
if "FunctionError" in response:
therefore inverted against substrate: every successful invocation looked
like a failure. LogResult is likewise returned only when the caller sets
X-Amz-Log-Type: Tail; LogType's valid values are None and Tail, and None now
behaves like absence. The value is matched case-insensitively because Go
canonicalizes header names but not values.
Fixing the omission exposed a second gap the issue does not mention: the
executor's invokePOST discarded the runtime's response headers, so
X-Amz-Function-Error could never be set by any path at all. That header is
the only signal a handler raised -- the runtime answers 200 either way -- so
a failed invocation was indistinguishable from a successful one even with
Docker execution enabled. It is now propagated.
Substrate does not execute handler code, per its scope boundary, so a
failure is reached by seeding rather than by running one:
POST /v1/lambda/invoke-error {"functionName","errorType",
"errorMessage","exceptionType","payload"}
DELETE /v1/lambda/invoke-error [?functionName=...]
keyed by function name or the "*" wildcard, following the established seed
pattern. errorType is Handled or Unhandled (validated; defaults to
Unhandled), the synthesized payload matches the shape the runtime interface
clients emit (errorMessage/errorType/requestId/stackTrace), and a verbatim
payload can be seeded for a runtime-specific shape substrate does not
synthesize. The status stays 200 throughout: per the Invoke reference, "the
status code in the API response doesn't reflect function errors".
Verified against the Invoke API reference and Lambda's service-2.json model
(LogType enum, FunctionError/LogResult header locations) plus the Python
runtime interface client's error serializer.
A fake runtime interface covers invokePOST's header plumbing, which the real
RIE cannot test without Docker.
# Conflicts: # CHANGELOG.md # emulator/error_protocol_test.go
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #393
The reported bug
InvokesentX-Amz-Function-ErrorandX-Amz-Log-Resultunconditionally — the former with an empty value. AWS documentsFunctionErroras "If present, indicates that an error occurred", so the SDK maps its absence to the key being absent from the response dict. The natural spellingtherefore inverts against substrate: every successful invocation looks like a failure. As the reporter notes, the truthiness check (
if response.get("FunctionError")) is correct against both, but theinform is common and an emulator-conformance assertion (assert "FunctionError" not in response) fails — which is how they found it.LogResulthas the same shape of problem in the other direction: it is documented as returned only when the caller setsX-Amz-Log-Type: Tail, and substrate returned it always.The gap the issue doesn't mention
Making the header conditional raised the question of what would ever set it. The answer was nothing:
LambdaExecutor.invokePOSTdidX-Amz-Function-Erroris the only signal that a handler raised — the runtime interface answers200 OKeither way, which is exactly why the docs say "the status code in the API response doesn't reflect function errors". So even with Docker execution enabled, a function that threw was indistinguishable from one that succeeded.invokePOSTnow returns the header alongside the body.How a failure becomes reachable
Substrate does not execute handler code (scope boundary in
CLAUDE.md), so the failure is seeded rather than produced, following the established pattern:Keyed by function name or the
"*"wildcard, matching the SSM / Bedrock / SageMaker seeds.errorTypeis validated asHandled(an exception the runtime caught) orUnhandled(a process that died — timeout, OOM, early exit), defaulting toUnhandled. The synthesized body matches what the runtime interface clients actually emit —errorMessage/errorType/requestId/stackTrace— and a verbatimpayloadcan be seeded for a runtime-specific shape substrate doesn't synthesize. The status stays200throughout.Verified against
InvokeAPI reference —FunctionErrorpresence semantics,LogResultas "the last 4 KB of the execution log, which is base64-encoded", and the 200-not-reflecting-function-errors rule.service-2.json— confirmsLogTypeisenum: ["None","Tail"]and that all three are"location": "header".awslambdaric's error serializer — the{errorMessage, errorType, requestId, stackTrace}field names.Tests
emulator/lambda_invoke_test.go(20 tests). The load-bearing ones:TestInvoke_SuccessOmitsFunctionErrorasserts onresp.Header["X-Amz-Function-Error"]presence, not its value — asserting emptiness would pass against the bug.TestInvoke_SeededErrorReportsFunctionErroris the necessary counterpart: without it, "omit on success" could be satisfied by never setting the header at all.TestInvokePOST_PropagatesFunctionErrorHeader/_NoHeaderOnSuccesscover the executor plumbing via a fake runtime interface on a local port, since the real RIE needs Docker.TestInvoke_LogTypeNoneOmitsLogResultand_IsCaseInsensitivepin the enum's other value and the value-casing trap.TestInvoke_SeededErrorNullPayloadSynthesizesguards a trap found while writing this: a niljson.RawMessagemarshals to the 4-byte literalnull, so the seed's round trip through the state store initially turned "no payload" into a seeded payload and every seeded failure answerednull. Fixed withomitemptyplus an explicit null check, so an explicit"payload": nullis also handled.The two existing
Executecallers now assert the new return is empty — a stub response and a container that failed to start are both successful-invocation-or-infrastructure cases, not handler errors.Gates
go build✅ ·go vet✅ ·golangci-lint run ./...0 issues ✅ ·make test(race) ✅ ·test/e2e✅ ·make docs-reference-check✅ ·make scan-fs0 vulns ✅invokeResponseandlambdaLogTailare at 100%;invokePOSTwent 0% → 85.7%. Residual uncovered lines inlambda_control.goare state-store failure guards, unreachable withMemoryStateManager.