Skip to content

fix(mpi): stop leaking security groups and placement groups on a rejected or failed cohort (#685) - #706

Merged
scttfrdmn merged 5 commits into
mainfrom
fix/685-validate-before-create
Oct 5, 2026
Merged

scttfrdmn merged 5 commits into
mainfrom
fix/685-validate-before-create

Conversation

@scttfrdmn

@scttfrdmn scttfrdmn commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Half of #685 — the ordering bug. The reaping half is deliberately separate; see below.

The ordering

validateMPIFlags ran about 286 lines after ensureSecurityGroup in the same function. So:

$ spawn launch x --instance-type c6i.large --count 2 --mpi
  ✅ Setting up IAM role (580ms)
{"operation":"create_security_group","instance_id":"spawn-mpi-","result":"success", ...}
--mpi requires --job-array-name

The group is created; the launch is then refused; the group stays. And it is named spawn-mpi- — the prefix with an empty suffix — so every such attempt shares one group. Since #659 that group allows all protocols between its members, which makes accidental sharing considerably worse than a cosmetic naming problem.

Combined with nothing reaping them, each rejected attempt added a durable orphan. I found 19 security groups and 9 placement groups in a single region of one account, and cleaned roughly 35 by hand over one session.

Now, verified against a real built binary:

$ spawn launch chk685 --instance-type c6i.large --region us-east-1 --count 2 --mpi --ttl 10m
--mpi requires --job-array-name
$ aws ec2 describe-security-groups --filters 'Name=group-name,Values=spawn-mpi-*' --query 'length(SecurityGroups)'
0

Two changes, not one

Ordering: pure flag validation moved ahead of the first AWS call. Validation that needs no AWS call belongs before the first AWS mutation. The instance-type guards stay in step 1 because they genuinely need the AMI resolved first.

A guard in the creator: CreateOrGetMPISecurityGroup now refuses a name with no cluster-specific suffix. The ordering fix makes the bad case unreachable from the CLI; this makes it unreachable from anywhere. I added both because the ordering is the bug and the shared-group name is the consequence — fixing only the first leaves a function that will happily hand out one all-traffic group to unrelated clusters if any other caller passes an empty name.

The gate asserts source order, since "this happens before that" has no runtime value to assert on. Confirmed to fail when I move the validation back: it names ensureSecurityGroup and ensureIAMProfile with their offsets.

The reaping half is not here

#685's other half — nothing reaps managed MPI security groups or placement groups — needs a decision rather than a patch, and I'd rather raise it than guess:

The MPI security group is deliberately durable. It is keyed on spawn-mpi-<job-array-name> and reused by name across runs, which is why CreateOrGetMPISecurityGroup is a get-or-create. So "delete it after the cohort finishes" would be wrong — it would force a recreate on every repeat run of the same named array, and #659's backfill exists precisely because groups outlive a single launch.

That makes it reaper territory rather than cleanup-on-exit: sweep groups and placement groups that are tagged spawn:managed, referenced by no instance, and older than some age. The tags are already there (spawn:managed=true, spawn:purpose=mpi-cluster).

Two things I want your call on before writing it:

  1. Where it lives. The reaper already has the authority, the schedule and the cross-account roles. Adding a second sweep there is natural — but it is a Lambda change and a deploy, and the last two reaper deploys each caused an incident (lambda/ttl-reaper: 'make deploy' defaults would DISARM the live production reaper and silently drop its DNS/alarm config #650's disarm, REAPER_GRACEFUL cannot work cross-account: the spawn-ttl-reaper-ec2 role grants no ssm: actions #652's unauthorised grant). I will not deploy without asking.
  2. The age threshold. An empty group costs nothing, so the only real pressure is the per-VPC quota. Something conservative like 7 days with no referencing instance seems right, but a named array re-run monthly would then recreate its group each time — which is harmless but means the backfill path in --mpi --efa: auto MPI security group is TCP-only, so EFA cannot pass traffic; and it silently overwrites --security-group-ids #659 runs more often.

cleanupAbandonedPGs also loses its race on every failed cohort (InvalidPlacementGroup.InUse, because termination is asynchronous), so it wants a short retry regardless of the reaper decision. That one I can do without a deploy.


Added after review: the delete that never landed

A second half of #685 that is a patch, not a decision — so it belongs here rather than waiting on the architecture question above.

When a cohort went terminal, spawn drained the instances and then deleted the per-AZ placement groups it had created. But TerminateInstances is asynchronous and EC2 refuses to delete a group while any instance still references it, so the delete lost that race on essentially every failed launch:

⚠️  could not delete abandoned placement group spawn-mpi-x-us-east-1a:
    api error InvalidPlacementGroup.InUse: ... is in use and may not be deleted.

...and then moved on. That is where the nine orphaned placement groups came from.

cleanupAbandonedPGs now uses DeletePlacementGroupWithRetry, which waits the members out for up to 60 seconds. The budget is short on purpose: an empty placement group is free, so the only cost of giving up is quota pressure and clutter — blocking a CLI exit for minutes over a free resource would be the worse trade. On giving up it prints the command:

   finish it with: aws ec2 delete-placement-group --region us-east-1 --group-name spawn-mpi-x-us-east-1a

I cleaned ~35 of these by hand in one session; the command is the part that was missing. Only InvalidPlacementGroup.InUse is retried — a permissions or not-found error returns at once rather than burning 60 seconds to re-learn it.

On the tests

The retry policy is in retryPlacementGroupDelete, separate from the AWS call, so the tests drive the real loop — real budget, real interval, real classifier — against a scripted sequence of errors. My first attempt reimplemented the loop inside the test, which would have passed with the retry deleted entirely; that is exactly the regression being guarded, so it is worth the extra seam.

Confirmed by collapsing retryPlacementGroupDelete to a single del() call: three of the five tests fail, naming the attempt count, the missing group name in the give-up message, and the ignored context cancellation.

There is also a cmd-side source gate, because reverting cleanupAbandonedPGs to the plain DeletePlacementGroup would still compile and still pass every pkg/aws test.

validateMPIFlags ran ~286 lines after ensureSecurityGroup in the same
function, so --mpi --count 2 with no --job-array-name created a managed
group and then refused the launch, leaving it behind.

The leftover was named spawn-mpi- (the prefix with an empty suffix), so
every such attempt shared one group — and since #659 that group allows
all protocols between its members. Nothing reaps them, so each rejected
attempt added a durable orphan: 19 SGs and 9 PGs in one region of one
account, ~35 cleaned by hand in a single session.

Pure validation now precedes the first AWS call, and
CreateOrGetMPISecurityGroup refuses a suffix-less name so the shared
group is unreachable from anywhere. A gate asserts the ordering.

Verified: the rejected launch now creates nothing.

Refs #685
EC2 refuses to delete a placement group while any instance still references
it, and TerminateInstances is asynchronous. The delete issued right after a
cohort drain therefore lost that race on essentially every failed MPI launch:
it printed InvalidPlacementGroup.InUse and moved on, leaving the group behind.
Nine orphans were found in one region of one account.

cleanupAbandonedPGs now uses DeletePlacementGroupWithRetry, which waits the
members out for up to 60s. The budget is short on purpose — an empty placement
group is free, so the only cost of giving up is quota pressure, and blocking a
CLI exit for minutes over a free resource is the worse trade. On giving up it
prints the exact `aws ec2 delete-placement-group` command rather than only the
failure; ~35 of these were cleaned by hand in one session, and the command was
the missing part. Only InUse is retried: a permissions error returns at once
instead of burning the budget to re-learn it.

The retry policy sits in retryPlacementGroupDelete, separate from the AWS
call, so the tests drive the real loop — budget, interval and classifier
included. A test that reimplemented the loop would pass with the retry
deleted, which is the regression being guarded. A cmd-side source gate checks
that cleanupAbandonedPGs actually calls the retrying variant, since reverting
to the plain delete would still compile and still pass every pkg/aws test.
@scttfrdmn scttfrdmn changed the title fix(launch): validate MPI flags before creating a security group fix(mpi): stop leaking security groups and placement groups on a rejected or failed cohort (#685) Oct 5, 2026
)

CreatePlacementGroup pins the EC2 client to the launch region. DeletePlacementGroup
took no region at all and used ec2.NewFromConfig(c.cfg) — the client's DEFAULT
region, which is whatever the ambient AWS config happened to carry.

So a cohort launched with --region into a non-default region created its placement
group in one region and tried to delete it in another. That fails with
InvalidPlacementGroup.Unknown, which is not a retryable condition, so the group was
abandoned on the very first attempt however long cleanup waited — the retry added in
the previous commit could not have saved it. In the mirror case, a same-named group
genuinely present in the default region would have been deleted instead.

The region is now a parameter on both DeletePlacementGroup and the retrying wrapper,
so the compiler forces every caller to supply one, and the mpicohort LaunchAPI
interface matches CreatePlacementGroup's shape.

The generalising gate rejects any regional EC2 call in pkg/aws built on c.cfg: the
default-region client IS the bug, not just this symptom. GetEnabledRegions is the
one allowed caller, since DescribeRegions is account-global and has no caller region
to honour. Verified to fail when the old client construction is restored, and the
gate itself fails if the matcher ever stops finding that one legitimate use, so it
cannot pass vacuously.
spawn tags every cluster placement group it creates with spawn:managed=true, but
the Resource Groups Tagging API that DiscoverManagedResources is built on does not
return placement groups at all. They were therefore invisible to `spawn orphans`,
`spawn cleanup` and `spawn resources` alike — nine orphans sat in one region of one
account with no spawn command able to show them.

They are now scanned separately, the same shape as the Elastic IP scan, and carry
whether the group still has members.

Three decisions worth stating, because each has an opposite that looks reasonable:

Orphan-ness is judged PER GROUP, not per region. An MPI cohort creates one group
per AZ it tries, so a cohort that fell back from us-east-1a to us-east-1b leaves
1a's group genuinely empty while its own instances run in 1b. The rule used for the
shared security group and key pair — "orphaned once nothing is running in the
region" — would hide precisely the leak this exists to find. Membership is asked of
EC2 rather than inferred from spawn's own instance list, since ANY member blocks the
delete, including one spawn did not create.

A group with members is reported and skipped, not offered for deletion: EC2 refuses,
so attempting it is a 60s wait ending in a failure.

But it is NOT folded into the `running` bucket, which aborts the whole cleanup. A
group whose only members are stopped instances would then block cleanup from
terminating those very instances, and the group could never become deletable. It
gets its own `notYet` bucket instead, with a message saying to re-run.

Terminated instances are excluded from the membership query and stopped ones are
included: a terminated instance holds nothing, so counting it would mark every group
a failed cohort left behind as in-use — the exact population needing reaping — while
a stopped instance really does occupy the group.

The sweep is CLI-side only; the reaper Lambda does not call discovery, so no deploy
is involved. Removal uses the retrying delete, since cleanup commonly follows a
terminate and hits the same asynchronous-termination race.
spawn does not stamp spawn:iam-user on a placement group, so applying
DiscoverOptions.OnlyMine would drop every one of them and leave the sweep
reporting nothing — the same reason scanAddresses ignores it. Visibility wins
for a leak report.

The same omission makes --mine silently EMPTY rather than narrow for security
groups and IAM profiles on the tagging-API side: 'spawn orphans' reports
nothing in an account holding 21 of them, the oldest from 2026-07-19. Filed as
#708 rather than widened into this PR, since fixing it changes what --mine
means for every command.
@scttfrdmn
scttfrdmn merged commit c0770f3 into main Oct 5, 2026
6 checks passed
@scttfrdmn
scttfrdmn deleted the fix/685-validate-before-create branch October 5, 2026 04:29
scttfrdmn added a commit that referenced this pull request Oct 5, 2026
…placement-group bugs (#708, #713) (#714)

* fix(cleanup): make --mine mean "not someone else's", and correct two placement-group bugs (#708, #713)

--- #708

--mine filtered on spawn:iam-user, a tag pkg/aws/tags.go writes only to instances
and volumes. Shared infrastructure — security groups, IAM roles and instance
profiles, key pairs, log groups, tables — never carries it, and a missing tag reads
as "", which never equals a caller ARN. So for those classes the filter did not
narrow the result, it EMPTIED it:

  $ spawn orphans --region us-east-1
  No orphaned spawn-managed resources in us-east-1.
  $ spawn orphans --region us-east-1 --all
  27 resource(s)

"Nothing to clean" is a believed answer, and it was wrong for as long as those
resources existed — the oldest dates from 2026-07-19.

The rule is now "not someone else's" rather than "provably mine". Untagged is
treated as shared rather than foreign for two reasons: it is the only choice that
helps the resources ALREADY out there, since stamping the tag on new resources
would leave today's orphans invisible forever; and "mine" is a dubious notion for a
security group deliberately shared and reused by name across runs and principals,
which is exactly what #685's MPI group is. It also matches what the two separately
scanned classes already do — neither addresses nor placement groups apply the
filter, because neither carries the tag.

orphans now reports how many resources the scope excluded, so "nothing here" can
never again be the whole output when it is not the whole story.

--- #713, found by running cleanup --dry-run against a real account

Two bugs, both mine, and the first corrects a claim I made in #706.

I asserted there that the Resource Groups Tagging API does not return placement
groups, and built a dedicated scan on that premise. It is false — RGT returns them
keyed by group ID. The probe I relied on returned empty because the account had
zero placement groups at the time, so it could not distinguish an unsupported type
from an absent one. I noted that ambiguity and then asserted the strong version
anyway; that is the actual mistake.

So every managed group was reported twice — once by id with no state, once by name
with one. And the id-keyed copy could not be deleted: EC2's DeletePlacementGroup
takes a NAME, so pg-… fails InvalidPlacementGroup.Unknown, which the ignoreNotFound
I added then swallowed as SUCCESS. A cleanup in v0.121.0 can report removing a
placement group it never touched. A tolerant error check turned a real failure into
a clean bill of health, which is the worse half.

RGT's placement-group rows are now dropped in favour of the dedicated scan, which
supplies both things RGT lacks: the name needed to delete and whether the group
still has members. Narrowly scoped to that one type, with a test asserting nothing
else is suppressed — hiding a type with no replacement scan would be #708 again.

Second: fixing #708 unmasked an over-eager IAM classification. spored-instance-role
and spored-instance-profile are created once and reused by every launch, but the
only signal IsLikelyOrphan has for IAM is !hasRunningInstance — so an idle account
made them orphans and `cleanup --yes` would have deleted spawn's own identity. The
broken scope had been hiding them from cleanup entirely, so one bug was concealing
the other. Now excluded from both the orphan check and cleanup's removable set, and
reported with the reason; per-run spawn-instance-<hash> profiles stay reclaimable,
with a test for that direction too.

Verified on live data: placement-group rows 6 → 3, total orphans 27 → 25. Every
gate confirmed to fail when its fix is reverted.

* fix(smoke): clean up the MPI security group and placement group (#713)

The MPI leg creates a managed security group and a per-AZ placement group, and
teardown terminated the instances and left both behind on every run. Three of each
accumulated over one session — a smoke whose purpose is catching leaks was a source
of them.

Found by 'spawn orphans' once #708 made the default scope work, which is a pointed
way to learn it:

  ec2  placement-group  spawn-mpi-smoke22812-us-east-1a  empty
  ec2  placement-group  spawn-mpi-smoke85337-us-east-1a  empty
  ec2  placement-group  spawn-mpi-smoke87201-us-east-1a  empty

Teardown now removes both, retrying the placement-group delete for exactly the
reason spawn itself has to (#685): TerminateInstances is asynchronous and EC2
refuses to delete a group that still has members.

The post-run leak check also asked only about INSTANCES, so it printed 'no instances
left behind' over that pile every time. It now checks placement groups and security
groups too, and names 'spawn orphans' in the failure so the next step is obvious.
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.

1 participant