Skip to content

Audit: 9 clearly-wrong sleeps, incl. a Lambda goroutine that can never run and so leaks placement groups #752

Closed

Description

@scttfrdmn

A full sleep inventory of the repo, prompted by the observation that a fixed
sleep against an AWS API has repeatedly been a bug here. ~145 of the ~178 sites
are legitimate and listed as cleared
, so this is a shortlist to evaluate, not a
mandate to delete sleeps.

I independently verified every CLEARLY-WRONG finding below against the source
before filing; line numbers are current as of main at 7a896dc. One audit claim
was wrong in the reassuring direction and is corrected at the bottom.

Counts

Classification Count
CLEARLY-WRONG 9
SUSPECT 24
LEGITIMATE (reviewed, cleared) ~145
Surface Sites
Go time.Sleep 74
Go time.After as delay/interval 41
Go tickers 17
sleep inside Go-generated shell string literals ~20
Shell scripts 27
Python / PowerShell / YAML examples 17
CI workflows, CloudFormation, deployment templates 0

That last row is worth stating: the declarative infrastructure has no sleeps at
all.


CLEARLY-WRONG

1. A Lambda goroutine that can never complete — this one leaks billable resources

lambda/sweep-orchestrator/main.go:1636

func cleanupPlacementGroup(ctx context.Context, ec2Client *ec2.Client, name string) error {
	// Wait for all instances to terminate before deleting placement group
	time.Sleep(30 * time.Second)
	_, err := ec2Client.DeletePlacementGroup(...)

Invoked at :430, :532, :1196, :1264, and at :430 the next statement is
literally return nil:

if state.PlacementGroup != "" && strings.HasPrefix(state.PlacementGroup, "spawn-mpi-") {
	go cleanupPlacementGroup(ctx, ec2Client, state.PlacementGroup)
}

return nil

A Lambda execution environment freezes when the handler returns. The
goroutine never resumes — or resumes much later against a cancelled ctx on an
unrelated invocation. So the placement group is never deleted, by design-
accident, at all four sites.

lambda/pipeline-orchestrator/main.go:981 and :997 have the identical shape
(go func(){ time.Sleep(30*time.Second); … } around DeleteSecurityGroup and
DeletePlacementGroup).

This is not hypothetical. #685 found 9 orphaned placement groups and 19
security groups
in one region of one account, oldest three months old. This is
a mechanism that produces exactly that, and it was never in the frame when #685
was diagnosed as a CLI-side ordering bug.

Fix: drop the go and call the repo's existing
pkg/aws.Client.DeletePlacementGroupWithRetry /
retryPlacementGroupDelete (pkg/aws/placement.go:210-250), which retries only
InvalidPlacementGroup.InUse against a deadline — synchronously, before the
handler returns. Or hand the cleanup to the TTL reaper, which since #685 reclaims
exactly these.

Also worth doing: sweep the live accounts for orphaned spawn-mpi-*
placement groups and pipeline security groups, since this has been silently
accumulating them.

2. Three hand-rolled "wait for running" loops when the correct waiter exists

cmd/connect.go:94 (sleep 5 × 30), cmd/connect.go:642 (same, in
connectDCV), cmd/state.go:413 (sleep 2 × 30, waiting for running and a
public IP).

pkg/aws.Client.WaitForRunning (pkg/aws/client.go:977-999) already exists,
wraps ec2.NewInstanceRunningWaiter, absorbs the #78 NotFound
eventual-consistency window via DescribeInstanceWithRetry, and is used at
cmd/launch_single.go:862, cmd/service.go:516, cmd/image.go:561. The three
loops above reimplement it worse in three specific ways:

  • they poll ListInstances(region, "running") — a whole-region describe per
    tick, cost scaling with fleet size — instead of a single-instance describe;
  • on a ListInstances error they continue, and the loop has no ctx.Done()
    case at all
    , so Ctrl-C is ignored for the full 90–150s;
  • the sleep comes first, so an already-running instance still costs 2–5s.

Fix: client.WaitForRunning(ctx, region, id, 2*time.Minute), then one
GetInstancePublicIP for state.go's IP half — the
cmd/launch_single.go:862→871 pattern.

3. A blind IAM-propagation sleep, 830 lines from its own fix

pkg/aws/iam.go:550

// Wait for instance profile to propagate (IAM eventual consistency)
time.Sleep(10 * time.Second)

pkg/aws/iam.go:1384 is waitForInstanceProfile, a 500ms-ticker poll with a 30s
deadline, whose own doc comment says it "returns as soon as the profile is
readable … instead of a blind fixed sleep"
. Line 550 is the blind fixed
sleep that comment describes, in the same file. It is also not ctx-aware, and
the statement right after it (:554) is already GetInstanceProfile — the
readiness probe.

Fix: call waitForInstanceProfile(ctx, iamClient, profileName).

scripts/setup-spawnd-iam-role.sh:90 — sleep 10 after
add-role-to-instance-profile, same defect in shell. No aws iam wait exists for
instance profiles, so the fix is a bounded get-instance-profile poll asserting
the role appears in InstanceProfile.Roles.

scripts/deploy-custom-dns.sh:129 — sleep 3 after create-role, consumed
at :134 by a bare aws iam get-role --query 'Role.Arn' with no retry and no
|| exit
. 3s is well inside IAM's consistency tail; if it is short,
ROLE_ARN is empty and the script creates a Lambda with an empty role. Fix: a
bounded retry around :134, the idiom already used throughout
scripts/hardware-smoke.sh.


SUSPECT — the ones that need a decision

A question code-reading cannot settle: pkg/userdata/mpi.go:177

if [ "{{.JobArrayIndex}}" -eq 0 ]; then
  sleep 10
  mpirun … -hostfile /tmp/mpi-hostfile bash /etc/spawn/mpi-command
fi

No comment, purpose unclear. It runs on rank 0 only, after the hostfile is
already generated, immediately before mpirun SSHes to every peer. The bounded
peers-file wait 30 lines above it (:144, 600s cap plus a SPAWN_COMPLETE
failure record) is correctly written, which makes this bare 10s stand out.

If it is padding for peer sshd/authorized_keys, it is a race on a slow boot
and the repo already has two better mechanisms: the /run/spawn/required-gates
barrier (pkg/launcher/bootstrap.go:793-804) or the per-peer bounded SSM poll
(pkg/mpicohort/assembler.go:240-253). @scttfrdmn — what is this waiting for?

The one I hit myself today

scripts/hardware-smoke.sh:151 — sleep 10 immediately before the
"Independent leak check: ask AWS, do not trust the terminate calls above"
query. The query filters
Values=pending,running,stopping,stopped — shutting-down is not in the
list
, so a still-terminating instance is invisible with or without the sleep,
while a genuinely failed terminate leaves state running and is caught
instantly. The sleep buys nothing and delays every run.

I hit this exact defect in scripts/hardware-test-detached-sweep.sh hours ago
and fixed it there (add shutting-down, poll until the live set is empty). The
smoke has the same hole. Same root cause as #736, where EC2's default state
filter hiding shutting-down made a terminating instance report as nonexistent.

Production Go — ctx-ignoring or front-loaded waits

Site Duration Waiting for Note
cmd/app.go:436 3s ×30 a public IP after Launch sleeps before the first check; never calls WaitForRunning; no ctx.Done()
cmd/app.go:468 5s ×60 the spawn:ready-url tag sane poll, but errors continue so Ctrl-C is ignored for 5 min
cmd/connect.go:664 5s ×60 same ready-url poll same defect
cmd/connect.go:462 3s "give the session a moment to establish" after go startRDPTunnel pkg/plugin/push_ssh.go:80-89 already does this right (bounded net.DialTimeout probe)
pkg/aws/fsx.go:207 30s FSx AVAILABLE (30-min budget) plain Sleep so ctx is ignored, and it sleeps after the deadline check, overshooting by up to 30s. pkg/agent/fsx_mount.go:170-178 is the same wait done correctly
pkg/agent/agent.go:923 3s systemctl restart dcvserver no readiness probe; probe the DCV TLS port

Generated/packaged shell — fixed waits for a daemon

cmd/app.go:872 (sleep 15, "Wait for DCV to initialize", and the following
dcv close-session is || true so a short wait fails silently and the
session is created with the wrong owner), cmd/app.go:830 (sleep 5),
cmd/app.go:877 (sleep 2), cmd/upgrade_spored.go:214 (sleep 3 before a
health check that rolls back on failure — a slow-starting spored triggers a
spurious rollback), scripts/install-spored.sh:124,
scripts/install-spored.ps1:97.

Tests — ~13 fixed sleeps for pollable conditions

integration_test.go:66, 90, 137, 177, 238, 636, 708, 778 (two of which sleep a
full minute per iteration, 3 min and 2 min total), test/e2e/tier3_test.go:70
(30s waiting for nothing it then checks), :237 (2 min, the longest in the
suite), test/e2e/tier2_test.go:347, pkg/integration/hybrid_test.go:156.

Each has a correct local model to copy: waitForScheduleExecution
(integration_test.go:1012), test/e2e.waitForState (helpers.go:255), or
pkg/testutil.PollUntil (integration_helpers.go:533).


Cleared — reviewed and legitimate (~145)

Recorded so this list is not re-audited. Includes: ~20 correctly-written
poll-with-timeout loops that are the reference implementations here
(pkg/aws/ssm.go, placement.go, imagebuilder.go, windows_password.go,
client.go:916, agent/fsx_mount.go, mpicohort/assembler.go,
launch_posthook.go, reaperdeploy, taskpool/queue.go); monitor-loop tickers;
the user-configurable --launch-delay stagger (4 sites); scoped retry backoff
(retryIAM, runInstancesWithRetry); local process-shutdown grace windows;
documented user-visible grace periods (CompletionDelay, the 5s
"see the warning" pause, regionVacatedSettle); ~12 deadline-capped loops in
generated user-data; the bounded for _ in $(seq 1 N) loops throughout
scripts/; test fixtures where the sleep is inside a stub and the test's own
timeout is shorter; negative assertions where a real elapsed window is
required because you cannot poll for the absence of an event
(integration_test.go:520, 573, 665, 746); and example workloads where sleep
is the job.

Special mention: pkg/userdata/storage_efs_retry_test.go stubs the mount and
sleep binaries and asserts on the call log — a test protecting a legitimate
sleep, and the right pattern for anything that must retry.

Also noted: scripts/hardware-smoke.sh:216 could use aws ssm wait command-executed, matching the aws lambda wait / cloudformation wait /
dynamodb wait precedent already used in the deploy scripts. Not a defect.


Correction to the audit

The audit reported cmd/burst.go:212's unbounded
while [ ! -f /usr/local/bin/spored ]; do sleep 5; done as probably dead code
("I found no live caller for generateBurstUserData"). It is live: called at
cmd/burst.go:164, and burstCmd is registered at cmd/burst.go:48. So a
reachable code path generates user-data that can hang a boot forever — the
one shape every other generated script here carefully avoids with a deadline and
a named failure. That makes it a CLEARLY-WRONG, not a footnote.

Suggested sequencing

  1. The Lambda leak (sweep-orchestrator:1636 + 4 call sites;
    pipeline-orchestrator:981, 997) — the only group currently leaking billable
    resources, and a likely contributor to Nothing reaps managed MPI security groups or placement groups (19 + 9 orphans found); --mpi creates an SG before validating its own flags #685's orphans. Plus a live-account
    sweep for the orphans it has already created.
  2. cmd/burst.go:212 — one line, prevents an unbounded boot hang.
  3. WaitForRunning adoption + ctx.Done() — user-visible: Ctrl-C ignored
    for up to 5 minutes.
  4. IAM propagation (3 sites) — waitForInstanceProfile already exists.
  5. hardware-smoke.sh:151 — mirror the fix already made in
    hardware-test-detached-sweep.sh.
  6. The MPI sleep 10, once its purpose is known.

Activity

  1. added
    bug
    on Oct 8, 2026
  2. scttfrdmn commented on Oct 8, 2026

    @scttfrdmn
    ContributorAuthor

    Item 1 fixed — and the live-account sweep found something the fix does not cover

    PR for the code fix is up (all six sites across both orchestrators, synchronous,
    using a now-exported RetryPlacementGroupDelete). Then I swept the dev account
    for orphans this had already stranded.

    Six orphaned spawn-mpi-* placement groups in us-east-2, all available
    with zero members:

    spawn-mpi-e2e-pg-region-325782000   members=0   spawn:created=<none>
    spawn-mpi-e2e-pg-region-505170000   members=0   spawn:created=<none>
    spawn-mpi-e2e-pg-region-586101000   members=0   spawn:created=<none>
    spawn-mpi-e2e-pg-region-676933000   members=0   spawn:created=<none>
    spawn-mpi-e2e-pg-region-840465000   members=0   spawn:created=<none>
    spawn-mpi-e2e-pg-region-964361000   members=0   spawn:created=<none>
    

    us-east-1, us-west-1 and us-west-2 are clean.

    These will never be reclaimed. #685's reaper sweep deliberately skips a
    resource with no spawn:created tag (lambda/ttl-reaper/netresources.go:126):

    No creation stamp. Skipped rather than guessed: an untimed group could be
    seconds old, and deleting a group a launch is about to use would break that
    launch.

    That reasoning is right — I wrote it — but it means an untagged orphan is
    permanently stranded: the Lambda that created it could never delete it (this
    issue), and the reaper won't touch it either. The two safety properties compose
    into a leak with no collector.

    The names say e2e-pg-region-*, so these came from the e2e suite rather than the
    sweep orchestrator, which makes it a third producer of the same orphan class and
    suggests the e2e teardown has the same gap.

    This needs a decision, not a cleanup

    Deleting these six is trivial and free, but it treats the symptom. The real
    question is what to do about untagged orphans generally:

    1. Backfill spawn:created wherever a group is created, then let the reaper
      do its job.
      Addresses the cause. Needs every creation path to tag — and the
      e2e path evidently does not.
    2. Give the reaper a much longer fallback grace for untagged resources (say
      30 days). Preserves the "never delete something a launch is about to use"
      property while closing the permanent-strand hole, since nothing legitimately
      sits unused and untagged for a month.
    3. Report untagged orphans loudly and leave them to a human. spawn orphans
      already surfaces them; the gap is that nobody runs it. The reaper could emit a
      sentinel so the existing alarm path picks it up.

    I lean 2 plus 1 — the long fallback closes the hole now without weakening the
    short-grace guarantee, and tagging at creation makes the fallback rarely needed.
    (3) alone just relocates the problem to a human who is not watching.

    I have not deleted the six. They cost nothing directly and the per-VPC quota
    pressure in us-east-2 is not urgent, so the direction above is worth settling
    first — deleting them now would remove the only live evidence of the gap.

  3. scttfrdmn commented on Oct 8, 2026

    @scttfrdmn
    ContributorAuthor

    The MPI sleep 10 — answered from the code, no longer a question for the maintainer

    I said this needed a human. Reading the full generated script makes it
    determinable, and the audit's hypothesis was right.

    The script's order is:

    1. rank 0 waits, bounded at 600s with a named failure, for
      /etc/spawn/job-array-peers.json to appear;
    2. generates /tmp/mpi-hostfile from it;
    3. signals the --command ready gate (--mpi: --command starts before MPI/EFA setup finishes; expose a readiness barrier #664);
    4. writes /etc/spawn/mpi-command (--mpi-command is passed through strconv.Quote, so any command with arguments becomes one argv word (and $ still expands) #660);
    5. rank 0 only: sleep 10, then mpirun -hostfile /tmp/mpi-hostfile ….

    The peers file existing means the controller resolved every peer's IP and
    wrote the file. It does not mean any peer's sshd is accepting connections,
    or that authorized_keys is in place for passwordless MPI, or that the peer has
    finished its own bootstrap. And mpirun SSHes to every host in that hostfile.

    Nothing else happens between the hostfile write and mpirun that needs time. So
    the sleep 10 is padding for peer SSH readiness — there is no other
    candidate.

    Why it is a race, not just untidy

    Ten seconds after rank 0's peers file appears says nothing about when peer N
    finishes. It gets worse with cohort size, because the pad is constant while the
    number of peers that must all be ready grows.

    That matches something already recorded in scripts/hardware-sensitive.txt:

    pkg/mpicohort/ — Scale behaviour (the 16-node assembly flake) is only
    observable live.

    A constant 10s pad failing at 16 nodes and passing at 2 is exactly that shape. I
    am not claiming this is that flake — I have not reproduced it — but it is a
    candidate worth testing, and it is the kind of thing a unit test cannot reach.

    Recommendation

    Replace it with a bounded per-peer readiness poll, mirroring the peers-file wait
    30 lines above (same file, correct shape, named failure, 600s cap):

    # Every peer must accept a non-interactive SSH before mpirun, which SSHes to all
    # of them. BatchMode tests sshd AND authorized_keys; a port probe tests only the
    # first.
    SPAWN_PEERS_READY_WAITED=0
    while :; do
      NOT_READY=0
      for IP in $(awk '{print $1}' /tmp/mpi-hostfile); do
        ssh -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=5 \
            "$IP" true 2>/dev/null || NOT_READY=$((NOT_READY + 1))
      done
      [ "$NOT_READY" -eq 0 ] && break
      if [ "$SPAWN_PEERS_READY_WAITED" -ge 600 ]; then
        echo "spawn: $NOT_READY peer(s) never accepted SSH after ${SPAWN_PEERS_READY_WAITED}s" >&2
        echo '{"status": "failed", "exit_code": 1, "source": "mpi"}' > /tmp/SPAWN_COMPLETE
        exit 1
      fi
      sleep 5
      SPAWN_PEERS_READY_WAITED=$((SPAWN_PEERS_READY_WAITED + 5))
    done

    Two properties the sleep 10 lacks: a 2-node cohort starts in ~0s instead of
    always paying 10
    , and a slow or broken peer produces a named failure in
    SPAWN_COMPLETE
    instead of an mpirun error about an unreachable host.

    BatchMode=yes matters — it tests sshd and authorized_keys together, which is
    the actual precondition. A nc -z … 22 probe would pass while MPI still fails.

    This belongs in a PR with a real multi-node hardware run behind it, since
    pkg/userdata/ is in the hardware-sensitive manifest precisely because generated
    shell cannot be proven by text assertions.

  4. scttfrdmn commented on Oct 8, 2026

    @scttfrdmn
    ContributorAuthor

    The MPI peer-readiness poll is now measured: 0s at 4 nodes

    The #758 fix replaced sleep 10 with a bounded per-peer SSH poll, but its actual
    duration was never observed — the 4-node run at the time predated the marker file
    and reported "line not found". Re-ran it on current main
    (44dcbc7, NODES=4 SKIP_EFA=1):

    === MPI cohort: 4 x c6i.large in us-east-1
      ✅ cohort launched and assembled (#684: --mpi works end to end)
         (all 4 nodes reported after 0s)
         peer readiness: all peers accepted SSH after 0s
      ✅ mpirun spread across all 4 nodes (8 ranks)
      ✅ cloud-init completed (no aborted scripts-user module)
      ✅ --mpi-command preserved its arguments (#660)
      4 passed, 0 failed
    

    The poll really ran — it did not pass vacuously. That distinction matters,
    because an empty /tmp/mpi-hostfile would also yield 0s: the for loop would
    iterate over nothing and NOT_READY would stay 0. It is ruled out by the next
    assertion in the same run — mpirun placed 8 ranks across 4 nodes, which it can
    only do from a 4-entry hostfile. So four real BatchMode=yes SSH connections
    succeeded on the first attempt.

    What this establishes

    • The old sleep 10 was pure waste at this width. Zero seconds were needed;
      ten were always paid. On a 4-node cohort that is 10s of dead time per run.
    • The poll costs nothing when peers are ready — one round of N probes and it
      breaks immediately.

    What this does NOT establish

    It is not evidence that the fix prevents the 16-node assembly flake
    (scripts/hardware-sensitive.txt:15). A 0s wait means the race window was
    never entered, so this run cannot distinguish "the poll fixed it" from "there was
    nothing to fix today". The argument for the poll over the pad does not rest on
    this number anyway — it rests on the pad being a constant while the number of
    peers that must all be ready grows, and on a slow peer now producing a named
    SPAWN_COMPLETE failure instead of an opaque mpirun error about an unreachable
    host.

    Proving the flake would need a run at the width where it was seen, and because it
    is intermittent, one green run there would not prove much either. Not pursued.

    Cleanup

    Baseline before: 0 instances, 0 placement groups, 0 spawn-mpi-* security
    groups. After the script's own teardown, verified independently: same three
    counts at 0, and all four instance IDs queried directly report terminated —
    not merely absent from a filtered list, which is the #736 trap. Cost ≈ $0.04.

  5. added a commit that references this issue on Oct 8, 2026
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