carlos / platform Public

mediaaws: show ECS failure reasons and stop codes as fixed words

Branch review round 1, P1-A (Astra). Invariant: response text never
carries credentials or endpoint values into logs, job rows or operator
output. safeReason kept up to 200 printable characters of an ECS reason
unless it held "://", so a bare key, a security token query or a host
reached the launch log through RunTask and system media status through
DescribeTasks; a URL split by control bytes survived too.

knownFailure now matches a reason against one table, failureReasons,
and answers that table's own words, with a fixed fallback for anything
else. Retry classification and DescribeTasks' MISSING read the same
table, and TestFailureTableClassifiesAsBefore holds the retry rule
equal to the free-text one it replaced. Stop codes are kept only when
ECS defines them. TestEveryComparedReasonIsInTheTable fails a reason
read anywhere but knownFailure, or shown words that are not literals.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f8aedce384332a14301dcadc2d7d16e1a62e3de1 parent 0674b7e
3 files changed, +280 −48
  • docs/superpowers/notes/media-conversion-copy-deck.md +4 −2
  • internal/mediaaws/engine.go +73 −28
  • internal/mediaaws/mediaaws_test.go +203 −18
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 49bd5eb89..55c88c08f 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -676,7 +676,9 @@ for whoever deploys the console and are not listed here.
| `engine.aws.cause.timeout` | `timed out` (pending Luna pass; plan 3 Task 9) |
| `engine.aws.cause.api` | `%s (HTTP %d)` or `%s` (an AWS error code), or `HTTP %d` (pending Luna pass; plan 3 Task 9) |
| `engine.aws.cause.transport` | `the request failed before an answer came back` (pending Luna pass; plan 3 Task 9) |
-| `engine.aws.cause.task_unreadable` | `a task could not be read: %s`, the reason ECS gave (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.task_unreadable` | `a task could not be read: %s`, `%s` one of the `engine.aws.failure.*` words, never the reason ECS gave (pending Luna pass; plan 3 Task 9, branch review round 1) |
+| `engine.aws.failure.known` | The words shown for a failure reason ECS gave that this console recognises: `MISSING`, `RESOURCE:CPU`, `RESOURCE:MEMORY`, `RESOURCE:PORTS`, `RESOURCE:PORTS_TCP`, `RESOURCE:PORTS_UDP`, `RESOURCE:ENI`, `RESOURCE:GPU`, `RESOURCE (a resource this console does not name)`, `Capacity is unavailable`, `AGENT`, `ATTRIBUTE`, `LOCATION` (pending Luna pass; branch review round 1) |
+| `engine.aws.failure.unrepeated` | `the engine gave a reason this console does not repeat`, for any other reason; `no reason reported` for an empty one (pending Luna pass; branch review round 1) |
| `engine.aws.cause.other_revision` | `the answer is not about the revision asked for` (pending Luna pass; plan 3 Task 9) |
| `engine.aws.cause.no_etag` | `the answer holds no ETag` (pending Luna pass; plan 3 Task 9) |
| `engine.aws.cause.listed_key` | `a listed key is not URL encoded` (pending Luna pass; plan 3 Task 9) |
@@ -689,7 +691,7 @@ for whoever deploys the console and are not listed here.
| `engine.aws.cause.no_account` | `no account to expect as the bucket's owner` (pending Luna pass; plan 3 Task 9 fix 1) |
| `engine.aws.grant.request` | `the execution is not 32 hex characters`, `the source key is not valid`, `the source ETag is not valid`, `the output prefix is not a directory under derived/`, `the grant does not name %d outputs`, `an output's name or content type is not one the engine writes` (pending Luna pass; plan 3 Task 9) |
| `engine.aws.grant.presign` | `the presigned transfers do not share one credential`, `an output's URL is not under the output prefix`, `a presigned URL does not have the expected shape`, `a presigned URL does not sign the expected headers` (pending Luna pass; plan 3 Task 9) |
-| `engine.aws.rejected` | The reason in `engine rejected the launch: %s`: an AWS error code, `HTTP 429`, the reason ECS gave, `no task definition for this class`, `no task and no failure reported`, `no reason reported`, `a reason that cannot be shown`, or `the API refused the request` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.rejected` | The reason in `engine rejected the launch: %s`: an AWS error code, `HTTP 429`, one of the `engine.aws.failure.*` words, `no task definition for this class`, `no task and no failure reported`, or `the API refused the request` (pending Luna pass; plan 3 Task 9, branch review round 1) |
| `console.media.off_at_boot` | `console: media conversion is off until the next start: %v`, logged once at boot when the cloud account cannot be read or a client cannot be built. `%v` is `the cloud account could not be reached: <step>: <cause>`. The step is `sts GetCallerIdentity`, `build the S3 client` or `build the conversion engine`; the cause is one of the `engine.aws.cause.*` texts, never the error's own message (pending Luna pass; plan 3 Task 10 fix 2) |
### The media-engine module (plan 3 Task 11)
diff --git a/internal/mediaaws/engine.go b/internal/mediaaws/engine.go
index 7c1426ea2..cdb69eaad 100644
--- a/internal/mediaaws/engine.go
+++ b/internal/mediaaws/engine.go
@@ -113,41 +113,86 @@ func (e *engine) Run(ctx context.Context, req media.RunRequest) (string, error)
func singleAttempt(o *ecs.Options) { o.RetryMaxAttempts = 1 }
// rejectedByFailures is a RunTask that answered with no task. A shortage of
-// resources or capacity may clear; anything else will not.
+// resources or capacity may clear; anything else will not. The reason shown
+// is the first failure's, in knownFailure's words.
func rejectedByFailures(failures []ecstypes.Failure) *media.Rejected {
- rej := &media.Rejected{Reason: "no task and no failure reported"}
+ if len(failures) == 0 {
+ return &media.Rejected{Reason: "no task and no failure reported"}
+ }
+ retryable := false
+ var shown string
for i, f := range failures {
- reason := aws.ToString(f.Reason)
+ k := knownFailure(aws.ToString(f.Reason))
if i == 0 {
- rej.Reason = safeReason(reason)
- }
- if strings.HasPrefix(reason, "RESOURCE:") || strings.Contains(reason, "Capacity") {
- rej.Retryable = true
+ shown = k.shown
}
+ retryable = retryable || k.retryable
}
- return rej
+ return &media.Rejected{Retryable: retryable, Reason: shown}
+}
+
+// failureReason is one ECS failure reason this package recognises: how it
+// is matched (exactly one of exact, prefix and contains), the words a
+// diagnostic shows for it, whether a launch refused with it may clear by
+// itself, and whether it says a task's record is gone.
+type failureReason struct {
+ exact, prefix, contains string
+ shown string
+ retryable, gone bool
+}
+
+// unrepeatedReason is shown for a reason failureReasons does not list.
+const unrepeatedReason = "the engine gave a reason this console does not repeat"
+
+// failureReasons are the only ECS failure reasons a diagnostic names, in
+// match order. A reason is text from the response, and whatever answers at
+// the endpoint can put a credential or a hostname there, so a diagnostic
+// shows these words and never the reason itself (Task 10's fixed
+// vocabulary, extended by the branch review's round 1). RunTask's reasons
+// are ECS's "API failure reasons"; DescribeTasks answers MISSING for a task
+// whose record is gone. knownFailure is the one place a reason is compared,
+// and TestEveryComparedReasonIsInTheTable holds that.
+var failureReasons = []failureReason{
+ {exact: failureMissing, shown: failureMissing, gone: true},
+ {exact: "RESOURCE:CPU", shown: "RESOURCE:CPU", retryable: true},
+ {exact: "RESOURCE:MEMORY", shown: "RESOURCE:MEMORY", retryable: true},
+ {exact: "RESOURCE:PORTS", shown: "RESOURCE:PORTS", retryable: true},
+ {exact: "RESOURCE:PORTS_TCP", shown: "RESOURCE:PORTS_TCP", retryable: true},
+ {exact: "RESOURCE:PORTS_UDP", shown: "RESOURCE:PORTS_UDP", retryable: true},
+ {exact: "RESOURCE:ENI", shown: "RESOURCE:ENI", retryable: true},
+ {exact: "RESOURCE:GPU", shown: "RESOURCE:GPU", retryable: true},
+ {prefix: "RESOURCE:", shown: "RESOURCE (a resource this console does not name)", retryable: true},
+ {contains: "Capacity", shown: "Capacity is unavailable", retryable: true},
+ {exact: "AGENT", shown: "AGENT"},
+ {exact: "ATTRIBUTE", shown: "ATTRIBUTE"},
+ {exact: "LOCATION", shown: "LOCATION"},
}
-// safeReason keeps a failure's reason to one short printable line. A reason
-// that holds a URL is dropped whole: ECS's reasons are short phrases, and
-// this one is not.
-func safeReason(reason string) string {
+// knownFailure is reason's entry in failureReasons; an empty reason, or
+// one the table does not list, answers fixed words that repeat nothing of
+// it, retryable false.
+func knownFailure(reason string) failureReason {
if reason == "" {
- return "no reason reported"
- }
- if strings.Contains(reason, "://") {
- return "a reason that cannot be shown"
- }
- clean := strings.Map(func(r rune) rune {
- if r < 0x20 || r > 0x7e {
- return -1
+ return failureReason{shown: "no reason reported"}
+ }
+ for _, f := range failureReasons {
+ switch {
+ case f.exact != "" && reason == f.exact,
+ f.prefix != "" && strings.HasPrefix(reason, f.prefix),
+ f.contains != "" && strings.Contains(reason, f.contains):
+ return f
}
- return r
- }, reason)
- if len(clean) > 200 {
- clean = clean[:200]
}
- return clean
+ return failureReason{shown: unrepeatedReason}
+}
+
+// knownStopCode is code if it is one of ECS's stop codes, else "": a stop
+// code is response text too.
+func knownStopCode(code ecstypes.TaskStopCode) string {
+ if slices.Contains(code.Values(), code) {
+ return string(code)
+ }
+ return ""
}
// retryableRefusals are API refusals that prove nothing ran and may clear by
@@ -214,8 +259,8 @@ func (e *engine) Describe(ctx context.Context, arns []string) ([]media.Task, []s
found = append(found, taskOf(t))
}
for _, f := range out.Failures {
- if aws.ToString(f.Reason) != failureMissing || aws.ToString(f.Arn) == "" {
- return nil, nil, &adapterError{op: "ecs DescribeTasks", what: "a task could not be read: " + safeReason(aws.ToString(f.Reason))}
+ if k := knownFailure(aws.ToString(f.Reason)); !k.gone || aws.ToString(f.Arn) == "" {
+ return nil, nil, &adapterError{op: "ecs DescribeTasks", what: "a task could not be read: " + k.shown}
}
missing = append(missing, aws.ToString(f.Arn))
}
@@ -229,7 +274,7 @@ func taskOf(t ecstypes.Task) media.Task {
out := media.Task{
ARN: aws.ToString(t.TaskArn),
StartedBy: aws.ToString(t.StartedBy),
- StopCode: string(t.StopCode),
+ StopCode: knownStopCode(t.StopCode),
Stopped: aws.ToString(t.LastStatus) == statusStopped,
StartedAt: aws.ToTime(t.StartedAt),
StoppedAt: aws.ToTime(t.StoppedAt),
diff --git a/internal/mediaaws/mediaaws_test.go b/internal/mediaaws/mediaaws_test.go
index 3ff124a14..8088d495e 100644
--- a/internal/mediaaws/mediaaws_test.go
+++ b/internal/mediaaws/mediaaws_test.go
@@ -707,41 +707,226 @@ func TestRunMakesOneAttempt(t *testing.T) {
}
}
-// TestFailureReasonsAreKeptSafe: a reason ECS gives reaches operators through
-// both Run and Describe, so both go through the same limits.
-func TestFailureReasonsAreKeptSafe(t *testing.T) {
- leak := "https://bucket.s3.amazonaws.com/k?X-Amz-Signature=abc&X-Amz-Security-Token=" + testToken
- tests := map[string]struct{ reason, want string }{
- "a URL": {leak, "a reason that cannot be shown"},
- "control bytes": {"RESOURCE:\x00CPU\n", "RESOURCE:CPU"},
- "not ASCII": {"AGENT\u00e9", "AGENT"},
- "too long": {strings.Repeat("x", 300), strings.Repeat("x", 200)},
- "nothing at all": {"", "no reason reported"},
+// hostileReasons are ECS failure reasons that echo what no diagnostic may
+// carry: credentials, a presigned query, a host, and a URL broken up by
+// control bytes so that it reads as one only once they are stripped.
+var hostileReasons = map[string]string{
+ "access key": "RESOURCE:CPU AKIAIOSFODNN7EXAMPLE",
+ "session token": "X-Amz-Security-Token=" + testToken,
+ "secret": "hunter2-cloud-secret",
+ "hostname": "store.internal.example.com",
+ "control bytes": "ht\x00tps:/\x01/bucket.s3.amazonaws.com/k?X-Amz-Signature=abc",
+ "capacity, then": "Capacity is unavailable at bucket.s3.amazonaws.com",
+ "not ASCII": "AGENT\u00e9",
+ "too long": strings.Repeat("x", 300),
+}
+
+// TestFailureReasonsAreFixedWords: a reason ECS gives reaches operators
+// through Run (the launch log) and Describe (system media status), so both
+// repeat only this package's own words for it, never the response's text.
+// The raw reason still classifies the launch.
+func TestFailureReasonsAreFixedWords(t *testing.T) {
+ type want struct {
+ shown string
+ retryable bool
}
- for name, tc := range tests {
+ cases := map[string]struct {
+ reason string
+ want want
+ }{
+ "nothing at all": {"", want{shown: "no reason reported"}},
+ "RESOURCE:CPU": {"RESOURCE:CPU", want{"RESOURCE:CPU", true}},
+ "RESOURCE:MEMORY": {"RESOURCE:MEMORY", want{"RESOURCE:MEMORY", true}},
+ "another resource": {"RESOURCE:SOMETHING-NEW", want{"RESOURCE (a resource this console does not name)", true}},
+ "capacity": {"Capacity is unavailable at this time. Please try again later or in a different availability zone", want{"Capacity is unavailable", true}},
+ "MISSING": {"MISSING", want{"MISSING", false}},
+ "AGENT": {"AGENT", want{"AGENT", false}},
+ }
+ for name, r := range hostileReasons {
+ w := want{shown: unrepeatedReason}
+ switch {
+ case strings.HasPrefix(r, "RESOURCE:"):
+ w = want{"RESOURCE (a resource this console does not name)", true}
+ case strings.Contains(r, "Capacity"):
+ w = want{"Capacity is unavailable", true}
+ }
+ cases["hostile "+name] = struct {
+ reason string
+ want want
+ }{r, w}
+ }
+ for name, tc := range cases {
t.Run(name, func(t *testing.T) {
run := &stubECS{run: func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) {
return &ecs.RunTaskOutput{Failures: []ecstypes.Failure{{Reason: aws.String(tc.reason)}}}, nil
}}
_, err := NewEngine(testConfig(), run).Run(context.Background(), runRequest())
var rej *media.Rejected
- if !errors.As(err, &rej) || rej.Reason != tc.want {
- t.Fatalf("Run = %v, want the reason %q", err, tc.want)
+ if !errors.As(err, &rej) || rej.Reason != tc.want.shown || rej.Retryable != tc.want.retryable {
+ t.Fatalf("Run = %v (%+v), want the reason %q, retryable %v", err, rej, tc.want.shown, tc.want.retryable)
}
- assertClean(t, "Run", err)
+ assertNoReasonText(t, "Run", err, tc.reason)
describe := &stubECS{describe: func(*ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) {
return &ecs.DescribeTasksOutput{Failures: []ecstypes.Failure{{Arn: aws.String("arn:task/1"), Reason: aws.String(tc.reason)}}}, nil
}}
- _, _, err = NewEngine(testConfig(), describe).Describe(context.Background(), []string{"arn:task/1"})
- if err == nil || !strings.HasSuffix(err.Error(), "a task could not be read: "+tc.want) {
- t.Fatalf("Describe = %v, want the reason %q", err, tc.want)
+ _, missing, err := NewEngine(testConfig(), describe).Describe(context.Background(), []string{"arn:task/1"})
+ if tc.reason == failureMissing {
+ if err != nil || !slices.Equal(missing, []string{"arn:task/1"}) {
+ t.Fatalf("Describe = %v, %v: MISSING is an answer", missing, err)
+ }
+ return
+ }
+ if err == nil || err.Error() != "media: ecs DescribeTasks: a task could not be read: "+tc.want.shown {
+ t.Fatalf("Describe = %v, want the reason %q", err, tc.want.shown)
}
- assertClean(t, "Describe", err)
+ assertNoReasonText(t, "Describe", err, tc.reason)
})
}
}
+// assertNoReasonText fails when err's text holds a hostile reason, or any
+// secret, whole or with its control bytes stripped.
+func assertNoReasonText(t *testing.T, name string, err error, reason string) {
+ t.Helper()
+ assertClean(t, name, err)
+ stripped := strings.Map(func(r rune) rune {
+ if r < 0x20 || r > 0x7e {
+ return -1
+ }
+ return r
+ }, reason)
+ needles := []string{"AKIAIOSFODNN7EXAMPLE", "hunter2-cloud-secret", "example.com", "amazonaws.com", testToken}
+ if stripped != "" && knownFailure(reason).exact != reason {
+ needles = append(needles, stripped) // an exact entry's words are the table's own
+ }
+ for _, s := range needles {
+ for e := err; e != nil; e = errors.Unwrap(e) {
+ if strings.Contains(e.Error(), s) {
+ t.Errorf("%s: error text holds %q: %s", name, s, e.Error())
+ }
+ }
+ }
+}
+
+// The table decides retries exactly as the free-text rule it replaced did:
+// any resource shortage, or a reason that speaks of capacity.
+func TestFailureTableClassifiesAsBefore(t *testing.T) {
+ inputs := []string{"", "MISSING", "AGENT", "ATTRIBUTE", "LOCATION", "RESOURCE:", "RESOURCE:CPU", "RESOURCE:GPU",
+ "RESOURCE:ENI", "RESOURCE:NEW", "resource:cpu", "Capacity", "Capacity is unavailable at this time",
+ "no Capacity here", "capacity", "MISSING Capacity", "RESOURCE:CPU Capacity"}
+ for _, r := range hostileReasons {
+ inputs = append(inputs, r)
+ }
+ for _, f := range failureReasons {
+ inputs = append(inputs, f.exact, f.prefix, f.contains)
+ }
+ for _, r := range inputs {
+ before := strings.HasPrefix(r, "RESOURCE:") || strings.Contains(r, "Capacity")
+ if got := knownFailure(r).retryable; got != before {
+ t.Errorf("%q: retryable %v, the free-text rule said %v", r, got, before)
+ }
+ }
+}
+
+// TestEveryComparedReasonIsInTheTable: a failure's reason is read in one
+// place, knownFailure, which matches it against failureReasons and answers
+// that table's own words. A reason compared anywhere else could also be
+// printed from anywhere else.
+func TestEveryComparedReasonIsInTheTable(t *testing.T) {
+ fset := token.NewFileSet()
+ entries, err := os.ReadDir(".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ reads := 0
+ for _, e := range entries {
+ name := e.Name()
+ if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ f, err := parser.ParseFile(fset, name, nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Every f.Reason read is aws.ToString(f.Reason) inside knownFailure(...).
+ allowed := map[ast.Node]bool{}
+ ast.Inspect(f, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ if fn, ok := call.Fun.(*ast.Ident); !ok || fn.Name != "knownFailure" || len(call.Args) != 1 {
+ return true
+ }
+ if inner, ok := call.Args[0].(*ast.CallExpr); ok && len(inner.Args) == 1 {
+ if sel, ok := inner.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "ToString" {
+ allowed[inner.Args[0]] = true
+ }
+ }
+ return true
+ })
+ ast.Inspect(f, func(n ast.Node) bool {
+ sel, ok := n.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != "Reason" {
+ return true
+ }
+ reads++
+ if !allowed[sel] {
+ t.Errorf("%s: a failure's reason is read outside knownFailure", fset.Position(sel.Pos()))
+ }
+ return true
+ })
+ // The table's words are the package's own: every shown field a literal.
+ ast.Inspect(f, func(n ast.Node) bool {
+ kv, ok := n.(*ast.KeyValueExpr)
+ if !ok {
+ return true
+ }
+ if k, ok := kv.Key.(*ast.Ident); ok && k.Name == "shown" {
+ if lit, ok := kv.Value.(*ast.BasicLit); !ok || lit.Kind != token.STRING {
+ if id, ok := kv.Value.(*ast.Ident); !ok || id.Name != "failureMissing" && id.Name != "unrepeatedReason" {
+ t.Errorf("%s: a failure's shown words are not a literal", fset.Position(kv.Pos()))
+ }
+ }
+ }
+ return true
+ })
+ }
+ if reads < 2 {
+ t.Fatalf("found %d reads of a failure's reason; the walk no longer sees Run's and Describe's", reads)
+ }
+ for _, f := range failureReasons {
+ if n := btoi(f.exact != "") + btoi(f.prefix != "") + btoi(f.contains != ""); n != 1 || f.shown == "" {
+ t.Errorf("table entry %+v must match one way and show words", f)
+ }
+ }
+ if k := knownFailure(failureMissing); k.exact != failureMissing || !k.gone {
+ t.Errorf("MISSING is not the table's gone entry: %+v", k)
+ }
+}
+
+func btoi(b bool) int {
+ if b {
+ return 1
+ }
+ return 0
+}
+
+// A stop code is response text too: only one ECS defines is kept.
+func TestStopCodesAreKnownOnly(t *testing.T) {
+ for _, code := range []string{"EssentialContainerExited", "UserInitiated", "TaskFailedToStart"} {
+ if got := taskOf(ecstypes.Task{StopCode: ecstypes.TaskStopCode(code)}).StopCode; got != code {
+ t.Errorf("stop code %q read as %q", code, got)
+ }
+ }
+ for name, r := range hostileReasons {
+ if got := taskOf(ecstypes.Task{StopCode: ecstypes.TaskStopCode(r)}).StopCode; got != "" {
+ t.Errorf("%s: an unknown stop code was kept as %q", name, got)
+ }
+ }
+}
+
func ecsTask(arn, startedBy, status string, codec, deadline *int32) ecstypes.Task {
return ecstypes.Task{TaskArn: aws.String(arn), StartedBy: aws.String(startedBy), LastStatus: aws.String(status),
Containers: []ecstypes.Container{