Skip to content

fix(lambda): omit FunctionError and LogResult unless applicable (#393) - #416

Merged
scttfrdmn merged 3 commits into
mainfrom
fix/393-lambda-invoke-headers
Jul 31, 2026
Merged

scttfrdmn merged 3 commits into
mainfrom
fix/393-lambda-invoke-headers

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

Closes #393

Stacked on #415 (fix/392-error-codes). GitHub will retarget this to main once that merges; until then it gets no CI, since every workflow is gated on pull_request: branches: [main].

The reported bug

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 dict. The natural spelling

if "FunctionError" in response:
    raise LambdaFunctionError(...)

therefore 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 the in form is common and an emulator-conformance assertion (assert "FunctionError" not in response) fails — which is how they found it.

LogResult has the same shape of problem in the other direction: it is documented as returned only when the caller sets X-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.invokePOST did

return io.ReadAll(resp.Body)   // response headers discarded

X-Amz-Function-Error is the only signal that a handler raised — the runtime interface answers 200 OK either 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. invokePOST now 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:

POST   /v1/lambda/invoke-error   {"functionName","errorType","errorMessage","exceptionType","payload"}
DELETE /v1/lambda/invoke-error   [?functionName=...]

Keyed by function name or the "*" wildcard, matching the SSM / Bedrock / SageMaker seeds. errorType is validated as Handled (an exception the runtime caught) or Unhandled (a process that died — timeout, OOM, early exit), defaulting to Unhandled. The synthesized body matches what the runtime interface clients actually emit — errorMessage / errorType / requestId / stackTrace — and a verbatim payload can be seeded for a runtime-specific shape substrate doesn't synthesize. The status stays 200 throughout.

Verified against

  • The Invoke API reference — FunctionError presence semantics, LogResult as "the last 4 KB of the execution log, which is base64-encoded", and the 200-not-reflecting-function-errors rule.
  • Lambda's service-2.json — confirms LogType is enum: ["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_SuccessOmitsFunctionError asserts on resp.Header["X-Amz-Function-Error"] presence, not its value — asserting emptiness would pass against the bug.
  • TestInvoke_SeededErrorReportsFunctionError is the necessary counterpart: without it, "omit on success" could be satisfied by never setting the header at all.
  • TestInvokePOST_PropagatesFunctionErrorHeader / _NoHeaderOnSuccess cover the executor plumbing via a fake runtime interface on a local port, since the real RIE needs Docker.
  • TestInvoke_LogTypeNoneOmitsLogResult and _IsCaseInsensitive pin the enum's other value and the value-casing trap.
  • TestInvoke_SeededErrorNullPayloadSynthesizes guards a trap found while writing this: a nil json.RawMessage marshals to the 4-byte literal null, so the seed's round trip through the state store initially turned "no payload" into a seeded payload and every seeded failure answered null. Fixed with omitempty plus an explicit null check, so an explicit "payload": null is also handled.

The two existing Execute callers 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-fs 0 vulns ✅

invokeResponse and lambdaLogTail are at 100%; invokePOST went 0% → 85.7%. Residual uncovered lines in lambda_control.go are state-store failure guards, unreachable with MemoryStateManager.

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.
@scttfrdmn scttfrdmn added this to the v0.78.0 milestone Jul 31, 2026
@scttfrdmn scttfrdmn added type: bug Something is not working correctly area: lambda labels Jul 31, 2026
@scttfrdmn
scttfrdmn changed the base branch from fix/392-error-codes to main July 31, 2026 14:56
# Conflicts:
#	CHANGELOG.md
#	emulator/error_protocol_test.go
@codecov

codecov Bot commented Jul 31, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.22951% with 29 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
emulator/lambda_control.go 72.00% 13 Missing and 8 partials ⚠️
emulator/lambda_exec.go 53.84% 5 Missing and 1 partial ⚠️
emulator/lambda_plugin.go 93.75% 1 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn merged commit a319545 into main Jul 31, 2026
12 checks passed
@scttfrdmn
scttfrdmn deleted the fix/393-lambda-invoke-headers branch July 31, 2026 15:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: lambda type: bug Something is not working correctly

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lambda: invoke returns FunctionError='' on success; AWS omits the key

1 participant