Skip to content

Terminate failed pipeline stages and make them reapable (#912) - #931

Merged
scttfrdmn merged 2 commits into
mainfrom
fix/912
Oct 15, 2026
Merged

scttfrdmn merged 2 commits into
mainfrom
fix/912

Conversation

@scttfrdmn

Copy link
Copy Markdown
Contributor

Fixes #912.

Cost safety. This was found by reading the code and was not reproduced on AWS. No instances were launched and nothing was deployed.

What was wrong (each claim checked in the code)

  1. A failed stage never terminated itself. In generatePipelineUserData, the failure branch wrote FAILED and ran exit. Only the success path reached terminate-instances. A stage timeout takes the same branch. So does any bootstrap failure under set -e (spored download, checksum, AWS CLI install, unsupported arch).
  2. The orchestrator never noticed. checkStageCompletion read COMPLETE only. Its fallback read InstanceInfo.State, which is written once at launch (pending) and never refreshed. The stage stayed running and the Lambda re-invoked itself every ~13 minutes with no bound.
  3. The reaper couldn't see the instances. Stage instances had no spawn:managed and no TTL tags, so scanRegion never listed them. One more thing the issue didn't mention: the spored role's ec2:TerminateInstances is conditioned on ec2:ResourceTag/spawn:managed=true (pkg/aws/iam.go). So self-termination was refused by IAM even on Amazon Linux, success path included.
  4. ec2-metadata exists only on Amazon Linux. On Ubuntu and Debian the terminate step got an empty id.

Bugs found next to these and fixed in this PR, because they are on the same terminal paths:

  • Budget exceeded set CANCELLED and break-ed out of the switch only. The status was never saved, the loop kept going, and the invocation boundary then returned "terminal state, not reinvoking" without terminating anything.
  • Cleanup sent every TerminateInstances to us-east-1 (with a comment admitting it), so it never terminated stages in any other region.
  • on_failure: continue: a stage depending on a failed stage stayed pending forever, so the pipeline could never finish.

What changed (defence in depth)

Instance side (user data):

  • An EXIT trap, installed before anything can fail, runs on every exit. HUP, INT and TERM are routed through it. It writes FAILED unless COMPLETE was written, terminates through the API with the instance id from IMDSv2 via curl, then runs shutdown -h now.
  • RunInstances sets InstanceInitiatedShutdownBehavior=terminate, so the halt alone reclaims the instance, with no IAM permission or AWS CLI needed.
  • timeout -k 60, so a command that ignores SIGTERM is killed.

Tags: spawnaws.LifecycleTags (spawn:managed=true, spawn:created, spawn:purpose=pipeline, Name), plus spawn:launch-time and spawn:ttl/spawn:ttl-deadline from pkg/ttl, as spawn launch writes them. The pipeline and stage tags are kept. TTL = stage timeout (default 1h) + 30 min to cover bootstrap and the 60s linger, so the reaper never reclaims a stage still inside its own timeout. The bash timeout and the tag both come from one stageTimeout().

Orchestrator:

  • checkStageOutcome: FAILED wins over COMPLETE. Next comes COMPLETE. Then instance states refreshed from EC2: all gone without COMPLETE means failed (the old fallback counted that as completed). Last, a stage past its TTL fails. An S3 error other than not-found is returned, not read as absent.
  • failStage terminates the stage's instances, in its region, and applies on_failure. stop (the default) skips the remaining stages and terminates the in-flight ones. continue leaves independent stages running, and the failed stage's dependents are skipped.
  • Bounded: a pipeline past created_at + Σ stage TTLs + 30 min is failed, its instances are terminated, and nothing re-invokes it.
  • One finishPipeline handles every terminal path (complete, failed, cancelled, budget, deadline). It terminates every live instance in its stage's region, saves, then deletes network resources.
  • AWS calls are behind small seams (markers, ec2ForRegion, load/save/reinvoke/notify) for tests.

Tests

The new lambda/pipeline-orchestrator/main_test.go is the first test file for this Lambda. It is in the root module, so it runs in go test ./....

  • The generated user data is executed under bash with faked curl/aws/shutdown/timeout/etc. and no ec2-metadata on PATH. Three scenarios: failing command, successful command, bootstrap download failure. Each must write the right marker, call terminate-instances with the IMDSv2-derived id, and halt.
  • Reaper visibility: <prefix>:managed=true (via tagprefix), an RFC3339 deadline after the stage timeout and within an hour of it, and launch-time.
  • InstanceInitiatedShutdownBehavior=terminate for on-demand and spot. A source gate checks that every RunInstances goes through buildStageRunInstancesInput.
  • Orchestrator: a FAILED marker fails the pipeline and terminates in the stage's region with no reinvoke; FAILED beats COMPLETE; vanished instances mean failed; the TTL fails a silent stage; an S3 error is not read as absent; continue and stop policies; deadline means failed, terminated, no reinvoke; a healthy serial run fits inside the deadline; budget exceeded terminates and finishes.

Every gate was watched failing against a compiling revert (16 reverts, each go vet-clean). Reverted: no trap, ec2-metadata restored, no halt, no managed tag, TTL = timeout only, shutdown behaviour stop, FAILED ignored, no liveness refresh, no stage TTL, S3 error read as absent, no pipeline deadline, no dependency blocking, stop sparing in-flight stages, failed stage not terminated, the old budget break, cleanup hardcoded to us-east-1. One test was order-dependent at first (topological order of independent stages is unordered). Its fixture was fixed and the package run with -count=50.

make check: everything passes except the known Docker-only TestGenerateWrapper_ChownFixesCrossUIDStickyUnlink_Docker (no Docker daemon locally). That failure stops make check before step 5, so make check-nested was run separately and every nested module passes. staticcheck and golangci-lint are clean on the package, and GOOS=linux GOARCH=arm64 builds.

Deployment needed (not done here)

spawn-pipeline-orchestrator lives in the shared infra account (see docs/infra-account.md, "Invoked directly by the CLI"). None of this takes effect until it is redeployed:

cd lambda/pipeline-orchestrator
AWS_PROFILE=spore-host-infra make deploy     # sam deploy, stamps spawn:version
AWS_PROFILE=spore-host-infra make -C ../.. lambda-versions-deployed   # confirm the stamp

The template is unchanged. The role already grants ec2:CreateTags, ec2:DescribeInstances and ec2:TerminateInstances on *, which tag-on-create, the refresh and the terminate need. After deploy, the next invocation of a pipeline still in flight will fail it under the new rules if it is past its deadline, or as soon as its stage has a FAILED marker, and will terminate its instances. Stage instances launched before the deploy still lack the tags. They are reclaimed only through the orchestrator or a manual cancel.

Not in this PR

@codecov

codecov Bot commented Oct 15, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.27072% with 104 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
lambda/pipeline-orchestrator/main.go 71.27% 83 Missing and 21 partials ⚠️

📢 Thoughts on this report? Let us know!

A pipeline stage instance terminated itself only at the end of its success
path. A failing or timed-out command, or a bootstrap failure under set -e,
exited first. The orchestrator never read the FAILED marker, and its fallback
read instance states recorded at launch and never refreshed, so the stage
stayed running and the Lambda re-invoked itself every ~13 minutes. The
instances carried no spawn:managed tag, so the TTL reaper could not see them,
and the spored role's ec2:TerminateInstances is conditioned on that tag, so
self-termination was refused by IAM as well. The instance id came from
ec2-metadata, which Ubuntu and Debian do not ship.

The user data now installs an EXIT trap before anything can fail. It writes
FAILED unless COMPLETE was written, terminates the instance through the API
with its id read from IMDSv2, and halts. RunInstances sets shutdown behaviour
terminate, so the halt alone reclaims the instance without IAM or the AWS CLI.
Stage instances carry LifecycleTags plus spawn:launch-time, spawn:ttl and
spawn:ttl-deadline, as `spawn launch` writes them. The TTL is the stage
timeout plus a 30-minute bootstrap allowance.

The orchestrator reads FAILED, which wins over COMPLETE. It also fails a stage
whose instances have all gone without COMPLETE (read from EC2) or that has
outlived its TTL. A failed stage's instances are terminated and on_failure
applies: stop skips the remaining stages and terminates the ones in flight;
continue skips the failed stage's dependents, which used to stay pending
forever. A pipeline past the sum of its stage TTLs plus 30 minutes is failed
and nothing re-invokes it. Every terminal path, including an exceeded budget
that used to set CANCELLED without saving or terminating anything, now goes
through one function that terminates each stage's instances in that stage's
own region instead of us-east-1.

The tests run the generated user data under bash with faked commands and no
ec2-metadata. Each gate was watched failing against a compiling revert.
@scttfrdmn
scttfrdmn merged commit a63debf into main Oct 15, 2026
7 checks passed
@scttfrdmn
scttfrdmn deleted the fix/912 branch October 15, 2026 20:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pipeline: a failed stage's instance is never terminated, and the TTL reaper cannot see it (no spawn:managed tag)

1 participant