Skip to content

cleanup/orphans count already-gone resources as removable: the instance NotFound fallback keys on an error EC2 does not return for aged-out ids, and removable never consults State #516

Closed

Description

@scttfrdmn

Summary

spawn cleanup --dry-run reported 9 resources would be removed in an account where all nine had already been destroyed 12+ hours earlier. Split as promised out of #500 (found in the same output, different mechanism).

Two defects compound:

  1. enrichInstanceState's NotFound fallback never fires for instances that have aged out of the EC2 API, because DescribeInstances answers those with an empty result, not InvalidInstanceID.NotFound. State stays "", and the code's own comment promises this cannot happen.
  2. The removable/running/address split in cmd/cleanup.go never looks at State except through IsRunningInstance(), so a row spawn has correctly marked deleted still lands in removable and in the headline count.

Defect 2 is visible without defect 1: two rows below are displayed as deleted and counted anyway.

Measured

spawn 0.100.2, commit 8086471e597f6957388c1cd3cd54bccd516dec05, build 2026-08-18T08:05:35Z, us-east-1. A 7-node fleet plus volumes, all terminated the previous morning.

$ spawn cleanup --dry-run --region us-east-1
REGION     SERVICE  TYPE      ID                          STATE         CREATED
us-east-1  ec2      address   eipalloc-002da3736d205bc22  unassociated  -
us-east-1  ec2      instance  i-03c73299d8b91b416         -             2026-08-17T22:39:51Z
us-east-1  ec2      instance  i-03ebed621d8799f31         -             2026-08-17T22:53:45Z
us-east-1  ec2      instance  i-05782b84f7db5c515         -             2026-08-18T00:59:29Z
us-east-1  ec2      instance  i-05c34d471ee84e2db         -             2026-08-17T22:49:08Z
us-east-1  ec2      instance  i-07d05c83a4f86b440         -             2026-08-17T22:00:14Z
us-east-1  ec2      instance  i-08efa17ed1bb2f099         -             2026-08-17T22:30:35Z
us-east-1  ec2      instance  i-0d79af36b80961170         -             2026-08-17T22:44:29Z
us-east-1  ec2      volume    vol-0a8c007f5afdbe817       deleted       2026-08-17T22:30:35Z
us-east-1  ec2      volume    vol-0e0a00344e9b86365       deleted       2026-08-18T00:59:29Z

10 resource(s).
[EIP advisory -- see #500]

Dry run: 9 resource(s) would be removed. Re-run without --dry-run to delete.

None of the nine exists:

$ aws ec2 describe-instances --region us-east-1 --instance-ids i-03c73299d8b91b416
{"Reservations": []}                                     # rc=0, no error

$ aws ec2 describe-volumes --region us-east-1 --volume-ids vol-0a8c007f5afdbe817
An error occurred (InvalidVolume.NotFound) ... does not exist

The source is the Resource Groups Tagging API, whose tag mappings outlive the resources. DiscoverManagedResources pages rgt.GetResources on spawn:managed=true and takes every ARN it returns. Directly:

$ aws resourcegroupstaggingapi get-resources --region us-east-1 \
    --tag-filters Key=spawn:managed,Values=true --query 'ResourceTagMappingList[].ResourceARN' \
    --output text | tr '\t' '\n' | grep -E 'instance/|volume/'
arn:aws:ec2:us-east-1:942542972736:instance/i-03ebed621d8799f31
arn:aws:ec2:us-east-1:942542972736:instance/i-0d79af36b80961170
arn:aws:ec2:us-east-1:942542972736:instance/i-05782b84f7db5c515
arn:aws:ec2:us-east-1:942542972736:instance/i-03c73299d8b91b416
arn:aws:ec2:us-east-1:942542972736:volume/vol-0e0a00344e9b86365
arn:aws:ec2:us-east-1:942542972736:instance/i-08efa17ed1bb2f099

Residue, and it expires unevenly — this list is already shorter than the cleanup run minutes earlier. RGT staleness is expected and isn't the bug; treating it as ground truth is.

Defect 1 — the fallback's trigger is the wrong signal

pkg/aws/cleanup.go:246-256:

out, err := ec2Client.DescribeInstances(ctx, &ec2.DescribeInstancesInput{InstanceIds: ids})
if err != nil {
    // EC2 fails the WHOLE batch with InvalidInstanceID.NotFound if ANY id is
    // already gone. ... fall back to a per-id sweep so live instances still get
    // their real state and only the truly missing ones are marked deleted.
    if isInstanceNotFound(err) {
        return c.enrichInstanceStatePerID(ctx, ec2Client, resources, idx)
    }
    return fmt.Errorf("describe instance state: %w", err)
}

and enrichInstanceStatePerID's comment states the intended guarantee:

marking the rest "deleted" so a gone instance is never mistaken for one whose state is merely unknown

EC2 distinguishes two kinds of absence, and only one of them is an error. Control pair, same region, same call, one minute apart:

id result
i-03c73299d8b91b416 — real, terminated ~12 h earlier, aged out {"Reservations": []}, no error
i-0000000000000dead — syntactically valid, never existed InvalidInstanceID.NotFound

So the batch call succeeds, the if err != nil branch is never entered, the per-id fallback never runs, and the loop for _, res := range out.Reservations iterates zero times — leaving State at its zero value for every id. The guarantee holds only for ids that never existed; it fails for exactly the population cleanup exists to sweep, where every id is real and recently terminated.

The volumes in the same run are a clean within-run control: DescribeVolumes does 400 on an already-deleted volume, isVolumeNotFound fires, and both volumes come back correctly marked deleted. Same design, two APIs, one of which doesn't cooperate.

State == "" then reads as unknown, and unknown is treated as removable — IsRunningInstance() is State == "running" || State == "pending", so blank is "not running", i.e. fine to delete.

Defect 2 — removable ignores State entirely

cmd/cleanup.go:84-95:

for _, r := range found {
    switch {
    case r.IsRunningInstance():
        running = append(running, r)
    case r.ResourceType == "address":
        addresses = append(addresses, r)
    default:
        removable = append(removable, r)
    }
}

There is no deleted case, so the two volumes spawn did resolve correctly — printed in its own table as deleted — are still in removable and still in Dry run: 9 resource(s) would be removed. The tool contradicts its own output one line apart. This half is independent of defect 1 and is a two-line fix.

Impact

Mild but corrosive, in the direction that matters for a destructive command:

  • The number you decide on is wrong. Permanently remove 9 spawn-managed resource(s)? is the confirmation prompt for zero real deletions. An operator calibrates on that count; a report that says 9 when the answer is 0 trains them to ignore it, right before the run where it says 9 and means it.
  • Real removals hide in the noise. In the run above, the one genuinely-existing resource in the report was the EIP cleanup won't touch (orphans: unassociated EIPs are reported unconditionally (no spawn/principal attribution), and both remediation hints are wrong — one is destructive #500). Everything actionable was phantom, and nothing in the output said so.
  • Without --dry-run it issues doomed calls. RemoveResource sends aged-out instances to c.Terminate, which wraps any error as failed to terminate instance with no NotFound tolerance — unlike the volume, key-pair and security-group branches, which all use ignoreNotFound. So a sweep of stale residue reports failures for resources that are already in the desired state. (Not measured: I did not run it without --dry-run.)
  • It also makes spawn orphans — the safety net — noisier than the thing it is watching for.

Suggested fix

  1. Treat an empty DescribeInstances result as evidence, not as silence. After the batch call, any id in idx that no reservation mentioned is absent from EC2 — mark it deleted there, in the success path, rather than relying on an error to route into the fallback. That covers both absence shapes with no extra API calls and makes isInstanceNotFound a pure optimisation for the batch-poisoning case instead of the sole trigger.
  2. Give removable a deleted case. Route State == "deleted" into its own bucket, exclude it from the count, and either hide those rows or label them gone (tag residue). Once (1) lands this also removes the phantom instances.
  3. Say when the report is empty of real work. Dry run: 0 resource(s) would be removed (9 tag mappings are residue for resources that no longer exist). The current message can't distinguish a clean account from a stale one.
  4. Optional: ignoreNotFound(err, "InvalidInstanceID.NotFound") in the instance branch of RemoveResource, matching its three sibling branches. A resource that is already gone is a satisfied request, not a failure.

(1) is the load-bearing one; the code has the right intent and a comment stating it, and only the trigger is wrong.

Environment

  • spawn 0.100.2, commit 8086471e, build 2026-08-18T08:05:35Z, us-east-1, AWS_PROFILE with full account access
  • resources: 7 × c8g.48xlarge terminated 2026-08-18 ~05:00Z, measured 2026-08-18 ~22:45Z
  • code paths: pkg/aws/cleanup.go:62-118 (discovery), :233-297 (instance enrichment), :300-330 (volume enrichment, the working control), cmd/cleanup.go:84-120 (split and counts), pkg/aws/client.go:858 (Terminate)

Activity

  1. added
    bug
    on Aug 18, 2026
  2. added 2 commits that reference this issue on Aug 19, 2026
    df901b0
    ce28436
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions