Repository navigation
Description
Summary
FaultController (emulator/fault.go) cannot express the fault that most reliability tests need,
and two of its fields do not do what they say. Four findings, each verified by execution against
v0.82.0 using StartTestServer + POST /v1/fault/rules + the AWS Go SDK v2:
| # | Finding | Effect |
|---|---|---|
| 1 | S3 fault rules cannot match a semantic operation — operation: "GetObject" never fires |
A rule that looks correct silently matches nothing |
| 2 | No occurrence bound — a rule fires forever until cleared | Cannot test "fails twice, then succeeds", i.e. retry |
| 3 | ErrorCode is discarded on the wire; the SDK always sees the status-derived code |
Cannot test retry classification, which is code-driven |
| 4 | Injected errors use a different XML shape than the S3 plugin's own errors | A fault is distinguishable from a real S3 error by the client |
Finding 1 combined with finding 3 is the dangerous pair: a rule armed with a plausible operation
name and error code produces a passing test with zero faults fired. That is the failure mode
where the harness is worse than having none.
I have a local workaround (an HTTP middleware in front of substrate, internal/testaws/recorder.go
in objectfs) so this is not blocking me. Filing it because the capability belongs in substrate,
and because findings 1 and 3 look like bugs rather than gaps.
Finding 1: operation cannot name an S3 operation
ruleMatches (emulator/fault.go:145-153) compares rule.Operation against req.Operation.
For S3, req.Operation at the time faults evaluate is the bare HTTP method.
The sequencing, in emulator/server.go:
- Step 4.5 (
:607-621) evaluates faults againstreq.Operation. - Step 5 (
:625) routes to the plugin, andS3Plugin.HandleRequest
(emulator/s3_plugin.go:86-87) doesreq.Operation = op // mutate so server pipeline sees semantic name.
So the semantic name is assigned one step after faults are matched. Before that,
extractOperation (emulator/parser.go:386-406) has four sources — X-Amz-Target, an Action
param, a Smithy RPC v2 path, then "4. Fallback: HTTP method". S3 supplies none of the first
three, so every S3 request reaches the fault controller as Operation: "GET" / "PUT" /
"POST" / "DELETE" / "HEAD".
Verified:
armRule(map[string]any{"service": "s3", "operation": "GetObject", "fault_type": "error", "error_code": "InternalError"})
_, err := c.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String("probe-bucket"), Key: aws.String("k")})
// -> err = <nil> // rule matched nothing
armRule(map[string]any{"service": "s3", "operation": "GET", "fault_type": "error", "error_code": "InternalError"})
_, err = c.GetObject(ctx, &s3.GetObjectInput{...})
// -> err = ... StatusCode: 500 ... api error InternalServerErrorConsequences beyond the surprise:
-
Method granularity is too coarse to be useful for multipart.
CreateMultipartUploadand
CompleteMultipartUploadare bothPOST /bucket/key, differing only in?uploadsvs
?uploadId=. A rule onPOSTfires on the create:armRule({"service": "s3", "operation": "POST", ...}) _, err := c.CreateMultipartUpload(...) // -> InternalServerError
This makes the most valuable multipart test unreachable. "Complete fails after all parts
uploaded, assert no orphaned upload is left behind" cannot be written: aPOSTrule kills the
create, the upload never exists, and the test passes because nothing was ever started. (That is
a real defect I was chasing in objectfs — the Complete-failure path did not abort, and it
needed exactly this fixture.) -
PUTcoversPutObject,UploadPart, and every?<subresource>PUT. Verified: a rule on
PUTtakes outUploadPart.
Fix options, cheapest first:
- Move fault evaluation after the plugin derives the operation but before it acts. Cleanest
semantically, but the plugin currently derives and handles in one call, so this needs
parseS3Operationhoisted out ofHandleRequest. - Have the parser derive S3 operations too.
parseS3Operationalready exists and is pure —
call it fromparser.goforservice == "s3"soreq.Operationis canonical from the start.
This also fixes cost and consistency tracking for any request that errors before step 5. - Add matcher fields to
FaultRule—PathSuffix,QueryKey,HeaderPrefix— so a rule
can select on the wire request regardless of operation naming. This is what my local
workaround does;QueryKeyin particular ("uploads" vs "uploadId" vs "partNumber") is what
makes multipart sub-operations separable.
(2) and (3) are complementary and I would want both: (2) makes the obvious rule work, (3) makes
range- and subresource-level targeting possible. Note (3) also needs AWSRequest.Path — already
present (emulator/types.go:28-30) and already normalized to /bucket/key.
Finding 2: a rule has no occurrence bound
FaultRule has Probability but no count. InjectFault (emulator/fault.go:78-121) rolls the
PRNG on every matching request and never decrements anything.
armRule({"service": "s3", "operation": "GET", "fault_type": "error", "error_code": "InternalError"})
for i := 0; i < 3; i++ { _, err := c.GetObject(...); if err != nil { fails++ } }
// -> 3 failed (a fail-once bound would give 1)This is the gap that matters most, because retry cannot be tested without it. The canonical
test is "fail exactly N times, then succeed, and assert the caller observed success" — that is
what distinguishes working retry from no retry. With an unbounded rule the operation can only
fail, so the only assertable outcome is failure, and a retry bug is invisible.
Probability: 0.5 is not a substitute. It is a distribution, so a test built on it is either
flaky or has to issue enough requests to make flakiness improbable — and the seeded PRNG makes it
deterministic only as long as no one changes the number of requests any earlier rule evaluates
against, since the rolls come from one shared rng. Adding a request anywhere upstream reshuffles
every later roll. That coupling is worth noting independently of this issue.
Proposed: Times int — "fail this many matching requests, then stop matching." Zero should
mean one, not unlimited: a rule that fails nothing is never what a caller meant, and reading
0 as unlimited turns a typo into a test that burns the whole retry budget. Decrement under the
same lock as the match, so N concurrent requests against Times: 1 produce exactly one failure —
that atomicity is the property the whole mechanism exists for, and it is why a client-side
counter cannot substitute.
And a companion: a way to ask how many faults actually fired. A test that arms a rule and
asserts the operation succeeded has proven nothing unless the fault fired — a rule matching
nothing (finding 1!) produces exactly the same passing test as working retry. Something like
GET /v1/fault/rules returning a fired count per rule, or a FaultsFired() accessor on
TestServer. Finding 1 would have been caught immediately by any test that asserted a non-zero
fire count.
Finding 3: ErrorCode never reaches the client
InjectFault builds &AWSError{Code: code, ...} (emulator/fault.go:113-118) correctly, and it
is then flattened. writeError (emulator/server.go:698-729) → marshalAWSError
(emulator/error_protocol.go:151) with errorProtocolFor("s3", …) → errProtoQueryXML
(:62) → the default arm (:180-199), which emits <ErrorResponse><Error><Type>Sender</Type> <Code>…</Code>….
The code is in that body, but the AWS SDK does not read it for S3, because the shape is wrong
(finding 4). It falls back to the HTTP status:
requested error_code=SlowDown -> SDK saw "ServiceUnavailable"
requested error_code=NoSuchKey -> SDK saw "ServiceUnavailable"
requested error_code=RequestTimeout -> SDK saw "ServiceUnavailable"
(all three with http_status: 503; with the default 500 the SDK sees InternalServerError.)
So ErrorCode is currently decorative for S3. That removes the other half of retry testing: the
SDK's retry classifier is code-driven, and the interesting cases are precisely where code and
status disagree —
| Code | Status | Real SDK behaviour |
|---|---|---|
SlowDown |
503 | retryable, throttling — backs off |
RequestTimeout |
400 | retryable despite a 4xx |
InvalidRequest |
400 | not retryable |
NoSuchKey |
404 | not retryable |
A harness that collapses all of these to the status-derived code cannot distinguish "my retry
logic handles throttling" from "my retry logic retries everything, including errors that will
never succeed." The second is a real bug shape — it turns a permanent failure into a long hang.
Finding 4: injected errors have a different wire shape than real S3 errors
Same request, two sources, captured off the wire with an SDK transport wrapper:
<!-- GENUINE (404), from S3Plugin -->
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>NoSuchKey</Code><Message>The specified key does not exist.</Message><RequestId>SUBSTRATE</RequestId></Error>
<!-- INJECTED (503), from writeError -->
<ErrorResponse><Error><Type>Sender</Type><Code>SlowDown</Code><Message>injected fault</Message></Error></ErrorResponse>Three differences: the <ErrorResponse> wrapper (real S3 has none — S3 is REST-XML, and a bare
<Error> document is what it returns), the absent XML declaration, and the absent <RequestId>.
emulator/error_protocol.go:44-47 anticipates this — "Plugins that need a byte-exact document
build it themselves (see s3ErrorResponse)" — and s3ErrorResponseWith
(emulator/s3_plugin.go:2221-2244) is that byte-exact builder. The fault path just doesn't reach
it, because it errors out of the pipeline at step 4.5, before any plugin is involved.
This is what causes finding 3, and it is a fidelity problem in its own right: an injected error
is distinguishable from a real one by the client, which is the one property a fault injector
must not have. errProtoQueryXML is right for IAM/EC2/STS (Query protocol does use
<ErrorResponse>), but S3 is REST-XML and shares the entry in serviceErrorProtocols with them.
Proposed: split S3 out — either a new errProtoRESTXML arm emitting the bare <Error> form
with <RequestId>, or have writeError consult a per-service error marshaller so the S3 plugin's
existing builder is used for injected faults too. The second keeps one source of truth for the
S3 error document, which is why I'd lean that way. cloudfront and route53 are also REST-XML
and currently share the Query arm, so this may fix them at the same time — worth checking against
a real response before assuming.
Suggested priority
- Finding 1 (option 2) + finding 2 together unlock retry testing, which is the reason to use
fault injection at all. Highest value. - Finding 4 fixes finding 3 as a side effect and is a fidelity bug independent of faults.
- Finding 1 (option 3) — extra matcher fields — is what makes multipart and ranged-read
targeting possible; lower priority than the above but the thing I needed a workaround for. - The fired count is small and would have made finding 1 self-evident.
Reproduction
All findings reproduce with emulator.StartTestServer(t), an S3 client pointed at ts.URL with
UsePathStyle: true and WithRetryMaxAttempts(1), and rules armed via
POST {ts.URL}/v1/fault/rules with {"enabled": true, "rules": [...]}. Happy to paste the full
probe file if useful — it is four short tests.
Note on Probability's shared PRNG
Not part of the four findings, but noticed while reading: FaultController.rng is one
rand.Rand shared by all rules (emulator/fault.go:61), rolled once per matching rule per
request. The doc comment on NewFaultController promises "deterministic fault firing in tests"
with a fixed seed, and that holds only for a fixed sequence of requests. Any change to request
count or ordering upstream — a retry, a new setup call — reshuffles every subsequent roll. If
Times lands, most tests won't need Probability at all, which sidesteps this; but the doc
comment currently promises more determinism than the mechanism provides.
Activity
scttfrdmn commentedon Aug 2, 2026
Fixed in
45e3610(#511), shipping in v0.87.0 — all four findings, and both of your finding-1 options, since you said they were complementary and wanted both. You were right that they are, and right about the ordering: option 3'sQueryKeyis only useful once operations are named correctly, so they had to land together.Finding 1, option 2.
parseS3Operationis indeed already pure and hoistable — it takes only the request and returns(bucket, key, op)— soextractOperationnow calls it whenservice == "s3", andreq.Operationis canonical from the moment the request is parsed. The S3 plugin keeps the call (it is howbucket/keyare derived) but no longer mutatesreq.Operation. This is a wider win than faults, as you suspected: cost tracking and consistency simulation both readreq.Operationat earlier pipeline steps and were seeing the bare verb for every S3 request, including ones that error before step 5.Finding 1, option 3.
PathSuffix,QueryKeyandHeaderPrefixonFaultRule, all AND-ed withService/OperationinruleMatches.QueryKey: uploadsseparates the multipart sub-operations from each other, so the test you called unreachable is now writable — and written: "Complete fails after all parts uploaded, assert no orphaned upload" is in the suite.Finding 2.
Times int, and zero means one, not unlimited — your reasoning is in the doc comment, because it is the part a reader will want justified: reading0as unlimited turns a typo into a test that burns the whole retry budget and reports a hang instead of a failure. Unlimited is a negative value, explicitly, rather than a magic zero. A test asserts that an absentTimesproduces exactly one failure, so the choice is pinned rather than incidental.The decrement happens under the same write lock as the match and the roll.
InjectFaultpreviously tookRLockto snapshot the config and a separate write lock only for the PRNG roll, which is a race for a counter — withTimes: 1, N concurrent requests must produce exactly one failure, and that atomicity is the one thing a client-side counter cannot provide. The concurrency test runs 10 parallel requests under-race.And the fired count, which is the finding that makes the rest assertable. Per-rule
Fired, surfaced through the existingGET /v1/fault/rules(no new endpoint —handleFaultGetRulesalready marshals the whole config) plus aFaultsFired()accessor for in-process tests. Your framing is the one that matters and belongs on the record: a rule matching nothing produces exactly the same passing test as working retry logic. Finding 1 had been shipped and unnoticed, and any test asserting a non-zero fire count would have caught it immediately.Findings 3 and 4: you were right that 4 causes 3.
marshalAWSError's default arm emitted<ErrorResponse><Error><Type>Sender</Type>…, while every genuine S3 error comes froms3ErrorResponseWithas a bare<Error>document with an XML declaration and a<RequestId>. The SDK cannot find a code in the wrong shape, so it falls back to the HTTP status and a requestedSlowDownarrives asServiceUnavailable. Fixed at the marshaller as you leaned: a newerrProtoS3XMLarm that callss3ErrorResponseWith, so that function stays the single source of truth for the byte shape —error_protocol.go's comment already pointed readers there, and now the pointer is real rather than aspirational.Your framing of why this matters is in the code comment verbatim in substance: an injected error was distinguishable from a real one by the client, which is the one property a fault injector must not have. The test asserts both halves — the SDK-visible code is
SlowDown, and the raw body is byte-comparable to a genuineNoSuchKey. The byte comparison is the only assertion that actually proves indistinguishability.cloudfrontandroute53are also REST-XML and share the Query arm, and they stay there: their real error documents are<ErrorResponse>, unlike S3's, so they were correct already. The map says so, since the next reader will wonder. An injected EC2 or SQS error is unchanged, asserted.Your aside about the shared PRNG is confirmed (
fault.go:61): one*rand.Randfor all rules, so a roll for any rule advances it for every rule andProbabilitydeterminism depends on how many requests earlier rules evaluated. It is now documented inFaultRule.Probability's comment rather than fixed — per-rule PRNGs would change the outcome of existing seeded runs, which is a compatibility break that deserves its own decision. Filed as #510.Not blocking you was noted, but every one of these made an armed fixture silently wrong rather than merely limited, which is worse — so thank you for the four-finding writeup with the file references. They were all confirmed by reading the code at the lines you named.
chore(release): v0.87.0 (#515)
fix(authz): name a REST request by its operation, not its HTTP method (…
fix(ec2): serialize errors in the ec2 protocol's own document (#591) (#…
feat(s3): enforce request-rate quotas per prefix, not per bucket (#818)…
fix(#1241): an XML error response carries the request's own ID (#1412)