Skip to content

fix(scale-down): clean EC2 runners incrementally and isolate failures - #5463

Merged
guicaulada merged 8 commits into
mainfrom
gc/fix/orphan-cleanup
Oct 27, 2026
Merged

guicaulada merged 8 commits into
mainfrom
gc/fix/orphan-cleanup

Conversation

@guicaulada

@guicaulada guicaulada commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Scale-down waits for the complete EC2 inventory before removing active runners. With large fleets, listing can fail or time out before any cleanup happens. Orphan cleanup can also terminate a runner whose registration ID tag is missing without checking GitHub, or stop processing other runners after one failure.

Process EC2 inventory in bounded pages of up to 100 instances and clean each page before requesting the next. Look up registrations by valid GitHub runner ID or exact full runner name instead of listing the entire organization/repository. Verify orphan registrations, remove false-positive orphan markers, preserve unverifiable runners, and isolate failures per runner. Existing busy checks, bypass-removal, boot grace, and idle detection remain in place.

Cleanup is stateless. Every invocation starts from current inventory; successfully terminated instances are no longer listed on subsequent runs. Pagination tokens exist only within the invocation. A deadline guard stops starting new work with ten seconds remaining, and a later listing failure retains earlier cleanup. Busy, retained, or failed items can be checked again on the next invocation.

The idle allowance is shared across pages within an invocation and recalculated on the next run. Eviction ordering applies within each page; strict global oldest/newest ordering requires collecting the whole fleet. Repeated scheduled scans reconcile pagination shifts as instances disappear. Custom compute providers without the optional paging capability retain their existing list-based path, including a complete owner-listing fallback when GitHub identity fields are absent. Only successful complete listings are cached.

Both Terraform scale-down paths supply the configured runner-name prefix. EC2 trusts an instance prefix tag only when it matches that configuration. Missing or mismatched tags without a valid GitHub ID cause cleanup to retain the instance; affected instances need their tags or registration IDs corrected before automatic cleanup. An exact-name miss without an ID also retains the instance because a custom script may have registered a different name. Unverifiable identity is reported at error level before unnecessary authentication when possible.

Validation: 395 control-plane tests, 312 compute-provider tests, and seven mocked Terraform tests pass, covering cleanup before later-page failure, fresh scans of reduced inventory, cross-page idle allowance, deadline handling, direct GitHub ID lookup, and isolated failures. Runtime TypeScript, ESLint, Prettier, Lambda bundle build, and diff checks pass. The compute-provider package's separate TypeScript check has existing Vitest configuration typing errors, reproduced with unchanged compute-provider code. No AWS deployment or live termination was performed.

Independent companion PRs: #5464 (SSM cleanup) and #5465 (opt-in registration reconciliation).

Operational logs report per-page counts and final scan totals, successful termination counts, scan completeness, deadline exits, and orphan termination. These observations replace the old full-fleet before/after count on the EC2 path; dashboard migration and the additional per-instance GitHub API cost are documented. EC2 paging honors request cancellation before sending a request.

@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

@guicaulada guicaulada changed the title fix(scale-down): verify untagged orphans and isolate cleanup failures fix(scale-down): process EC2 pages incrementally and resume cleanup Sep 23, 2026
@guicaulada
guicaulada force-pushed the gc/fix/orphan-cleanup branch from a180a12 to df635b1 Compare September 23, 2026 14:14
@guicaulada guicaulada changed the title fix(scale-down): process EC2 pages incrementally and resume cleanup fix(scale-down): clean EC2 runners incrementally and isolate failures Sep 23, 2026
@guicaulada
guicaulada added this pull request to stack #5468 September 23, 2026 14:28
@guicaulada
guicaulada removed this pull request from stack #5468 September 23, 2026 14:39
@Brend-Smits
Brend-Smits requested a balanced review from Copilot September 23, 2026 16:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Runner-name derivation can target the wrong JIT registration, and existing custom providers can silently lose scale-down behavior.

Get a fresh assessment by requesting another Copilot review.

Review effort: Balanced
Findings: 2 High severity

Open (2)
What changed in this PR

Adds incremental EC2 scale-down processing with bounded pagination, direct GitHub runner lookup, deadline handling, and per-runner failure isolation.

Changes:

  • Processes EC2 runners page-by-page while sharing idle allowance.
  • Verifies runners by GitHub ID or exact name before cleanup.
  • Updates tests and scale-down documentation.
File Description
modules/​runners/​scale-down-state-diagram.md Documents incremental cleanup flow.
modules/​orchestration-providers/​webhook/​scale-down-state-diagram.md Mirrors updated scale-down documentation.
lambdas/​libs/​compute-providers/​registry.test.ts Relaxes capability registry assertion.
lambdas/​libs/​compute-providers/​core/​index.ts Adds runner names and optional paging.
lambdas/​libs/​compute-providers/​aws/​ec2/​src/​runners.ts Implements bounded EC2 pages and runner names.
lambdas/​libs/​compute-providers/​aws/​ec2/​src/​runners.test.ts Tests paging and name extraction.
lambdas/​libs/​compute-providers/​aws/​ec2/​src/​control-plane/​scale-down.ts Exposes EC2 paging capability.
lambdas/​functions/​control-plane/​src/​test/​compute-provider-contracts/​scale-down.ts Updates orphan cleanup contract.
lambdas/​functions/​control-plane/​src/​scale-runners/​scale-down.ts Implements incremental, isolated cleanup.
lambdas/​functions/​control-plane/​src/​scale-runners/​scale-down.test.ts Covers paging, deadlines, and failures.
lambdas/​functions/​control-plane/​src/​scale-runners/​scale-down-contract.test.ts Adds GitHub authentication mocks.
lambdas/​functions/​control-plane/​src/​lambda.ts Supplies Lambda remaining execution time.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@guicaulada
guicaulada force-pushed the gc/fix/orphan-cleanup branch from df635b1 to 2663e6c Compare September 23, 2026 19:34

@Brend-Smits Brend-Smits left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested on a sandbox deployment (multi-runner example, non-ephemeral Linux config). Normal scale-down worked. Removing the registration-ID tag exercised the exact-name lookup, which de-registered and terminated correctly. Setting a mismatched prefix tag kept the instance with a warning, as described. A few observations:

  1. Fleet-count logs are gone on the EC2 path. Found: 'N' active EC2 runners before/after clean-up. is now only logged on the legacy list path, so EC2 deployments no longer emit it (confirmed after deploy). Anyone with log-based dashboards or alerts on this line will lose them. Could we log a total at the end of the paged run (or per page)?
  2. Silent exits. When the time limit is hit, the run returns without any log. On the name-lookup path, an orphan is terminated without an info-level log, because the old Terminating orphan runner message was removed. An info log for each would help operators.
  3. GitHub API volume. Before, there was one paginated list per owner, cached for the run. Now there is one call per instance, before any busy check. On large fleets with a 1–5 minute schedule this uses the app's rate limit much faster. It may be worth mentioning in docs/rate-limits-and-tuning.md.
  4. MaxResults: 10 means about 100 DescribeInstances calls per run for 1,000 instances. These share EC2's throttling limit with scale-up and pool. Would a larger page (around 100) or a setting be better?
  5. Exact-name lookup is stricter than the old endsWith(instanceId) match. A runner registered under a custom name (custom start script) that also has no ID tag is now not found. It gets marked orphan and then terminated, and the orphan path does no busy check. Please document the naming requirement, or avoid treating "not found by name" as proof of absence.
  6. Kept instances only produce a warning. Instances that can't be verified stay up indefinitely with a warning every run. An error-level log or a metric would make this cost leak visible. Also, the GitHub client and installation token are created before the identity check that throws; checking first saves the calls.
  7. Nit: listPage skips the runWithRequestSignal pre-check that the other EC2 calls use.

guicaulada added a commit that referenced this pull request Sep 24, 2026
The SSM housekeeper accumulates every parameter page before deleting
anything. A later listing failure prevents all cleanup, and an omitted
`Parameters` array on the first page silently discards later candidates.

Delete eligible parameters as each page arrives, including pages after
empty responses. Isolate deletion failures per parameter, preserve the
existing age and dry-run protections, and stop starting new work with
ten seconds remaining. A later listing failure leaves earlier deletions
completed.

Cleanup is stateless: every invocation starts a fresh scan of current
parameters. Successfully deleted parameters disappear from subsequent
listings, leaving the remaining work for later scheduled runs.
Pagination tokens exist only within an invocation.

Validation: all 115 storage-provider tests pass, including empty pages,
deletion before later-page failure, fresh scans after partial cleanup,
and continuing past a failed deletion. Runtime TypeScript, ESLint,
Prettier, Lambda bundle build, and diff checks pass. No AWS deployment
or live parameter deletion was performed.

Independent of native SSM expiration-policy work in #5265. Companion
PRs: #5463 and #5465.
@guicaulada
guicaulada force-pushed the gc/fix/orphan-cleanup branch from 2663e6c to f3c63c5 Compare September 24, 2026 13:54
@guicaulada

guicaulada commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for testing this in a sandbox and writing up the observations. I addressed all seven in f3c63c5 and rebased onto current main:

  1. Added info-level per-page inventory counts and a final scan summary with pages, scanned runners, successful terminations, completeness, and deadline status. These are scan observations rather than an atomic fleet census; the docs explain how to migrate dashboards from the old before/after lines. A later listing failure still emits the partial summary.
  2. Added info logs for deadline exits and orphan termination.
  3. Documented the per-instance GitHub API cost and scheduling tradeoff in docs/rate-limits-and-tuning.md, including an example of 1,000 runners on a five-minute schedule.
  4. Increased the EC2 inventory page size from 10 to 100 while retaining per-runner processing and deadline checks.
  5. Changed the safety behavior: an exact-name miss without a registration ID no longer establishes absence on the paged path. The instance is retained even if already marked orphaned. This protects custom-name runners, including busy registrations we cannot identify. The naming/ID requirement and remediation are documented; this deliberately also retains genuinely absent registrations when their identity cannot be proved safely.
  6. Unverifiable identities now emit an error-level UNVERIFIABLE_RUNNER code suitable for alerting. Missing identity is checked before creating GitHub authentication/clients.
  7. Wrapped listPage in runWithRequestSignal and added a regression proving an already-aborted request never sends DescribeInstances.

@guicaulada
guicaulada force-pushed the gc/fix/orphan-cleanup branch from f3c63c5 to 306d3a5 Compare October 5, 2026 14:01
@guicaulada
guicaulada force-pushed the gc/fix/orphan-cleanup branch from 306d3a5 to a05fd53 Compare October 14, 2026 12:36
@guicaulada
guicaulada requested review from Brend-Smits and a balanced review from Copilot October 14, 2026 14:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Identity matching can terminate a verified busy runner, and partial removal failures can prevent subsequent cleanup.

2 open findings
2 resolved since last review

🧠 Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Slow verification can exhaust the deadline reserve while subsequent cleanup operations still start.

0 open findings

2 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Medium severity Cleanup can exceed deadline after verification and orphan resources

lambdas/​functions/​control-plane/​src/​scale-runners/​scale-down.ts:370

The deadline guard runs only before each runner. If GitHub verification starts with 11 seconds remaining and returns with 9, active cleanup still enters removeRunner, while orphan cleanup still starts termination or tag removal at lines 455–462. Further awaits inside removeRunner can also exhaust the reserve before deregistration or EC2 termination starts, risking a timeout with cleanup only partly completed. Recheck the budget after verification in both paths, and pass remainingTime into removal so subsequent requests and mutations also respect the guard. Add regressions where identity and busy-state lookups cross the threshold; a check only after the initial lookup does not cover the whole sequence.

🧠 Review effort: Balanced

@guicaulada

guicaulada commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed the latest Copilot review summary finding. Scale-down now rechecks its deadline after identity verification in both active and orphan paths, and between client creation, busy-state checks, idle confirmation, identity persistence, deregistration, and termination.

@guicaulada
guicaulada requested a balanced review from Copilot October 14, 2026 17:56
@guicaulada
guicaulada force-pushed the gc/fix/orphan-cleanup branch from 6888026 to 9ceb8c8 Compare October 14, 2026 18:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

GitHub verification and legacy inventory listings can still start after the ten-second deadline reserve is reached.

2 open findings

🧠 Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The legacy name fallback can terminate a live runner, and orphan verification and cross-page eviction behavior need correction.

1 open finding
2 resolved since last review
Previously missed (2)

In code that hasn't changed since last review

Medium severity Require healthy registration before unmarking name-matched orphans

lambdas/​functions/​control-plane/​src/​scale-runners/​scale-down.ts:497

An orphan found by name is treated as healthy merely because its registration exists. If it is offline and busy, this removes the orphan marker, although the ID-based path treats that same state as orphaned. Later active sweeps retain it because it remains busy, leaving the instance running. Recheck the matched registration IDs using the existing last-chance check, and unmark only if a matching registration is healthy. Add a regression for an offline, busy orphan without an ID tag.

Medium severity Capture eviction strategy once across paginated scans

lambdas/​functions/​control-plane/​src/​scale-runners/​scale-down.ts:587

Each page calls evaluateAndRemoveRunners, which recalculates getEvictionStrategy. The cron predicate in scale-down-config.ts:16–22 matches only within five seconds of the next occurrence, so a scan can start with newest_first and switch to the default oldest_first on later pages. This changes which runners are retained or removed within those pages, independently of the documented loss of global ordering. Capture the strategy once per invocation alongside the shared idle allowance and reuse it across pages. Add a regression where page processing crosses the cron window.

🧠 Review effort: Balanced

@guicaulada

Copy link
Copy Markdown
Contributor Author

Addressed both additional findings from the Copilot review summary in f45ff75: name-matched orphans now receive a fresh registration health check before being unmarked, and paginated scans capture the eviction strategy once per invocation.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Direct-ID 404 handling can mistake lost repository access for registration absence and terminate healthy instances.

1 open finding
1 resolved since last review

🧠 Review effort: Balanced

@guicaulada
guicaulada force-pushed the gc/fix/orphan-cleanup branch from 38514a2 to 18c37ef Compare October 26, 2026 12:46

@Brend-Smits Brend-Smits left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've tested this on my dev account and can confirm things are working as expected. Nice work!

@guicaulada
guicaulada merged commit 60a4c66 into main Oct 27, 2026
61 checks passed
@guicaulada
guicaulada deleted the gc/fix/orphan-cleanup branch October 27, 2026 15:09
guicaulada added a commit that referenced this pull request Oct 27, 2026
Missed deregistration events can leave offline GitHub runners behind
after their compute resources disappear. The termination watcher handles
termination events and busy-runner retries, but cannot discover
historical registrations or missed events. Scale-down also cannot
discover this backlog because it starts from existing compute instances.
This scheduled reconciliation complements both paths.

Add an opt-in `modules/registration-janitor` module deploying a separate
scheduled Lambda from the existing termination-watcher archive with
GitHub App/GHES authentication. Discovery processes each runner-group
page immediately, verifies candidates individually, and queues work
before fetching later pages. Candidate errors are isolated; unavailable
pages are skipped, with advancement to another group after three
consecutive page failures. Retained instances and failed checks do not
consume the queued-candidate limit.

Scanning is stateless. Every invocation starts from current GitHub
inventory; registrations deleted by earlier cleanup are no longer
listed. Pagination is local to each invocation. A deadline guard stops
starting new work with ten seconds remaining. Busy, retained, or failed
registrations may be checked again, and subsequent scans reconcile
shifting page boundaries.

Scope is an organization, explicit runner groups, an exact
account-exclusive runner-name prefix, and every AWS region using that
prefix. Any non-terminated EC2 state protects the registration. Offline,
non-busy registrations with absent instances enter SQS for a second
observation at least 15 minutes later. These messages carry candidate
identity and observation time for deletion safety. Confirmation searches
group membership page by page, then rechecks EC2 absence and current
GitHub identity/offline/busy state before deletion. Incomplete or failed
lookups never establish absence. Confirmation failures retry
independently through SQS and its dead-letter queue; duplicate deletion
treats 404 as success. Scope changes invalidate candidates, and
candidates expire after 24 hours. Dry-run is the default and suppresses
queueing and deletion.

The account-exclusive prefix and complete region list are required
configuration because tags cannot prove ownership after an instance
disappears. This implementation handles organization EC2 runners in one
account and multiple regions. Repository runners and cross-account
inventory remain outside its scope. Delayed observations reduce races
but are not an atomic GitHub/EC2 transaction.

Additional GitHub Apps are supported through the existing credential
manifest format. Discovery selects an App for each group page, and
confirmation selects one per candidate. Selection prefers observed
remaining quota, skips throttled Apps for one minute when another is
available, and tries another configured App after authentication
failure. App JWT and installation-token authentication use the same
credential and resolve access for the requested owner. Terraform passes
the optional manifest and grants read access to its configured
credential parameters. Single-App configurations remain supported.
Existing termination-watcher behavior is unchanged by this PR.

The GitHub cleanup flow uses a compute-provider interface for
runner-name interpretation, backing-resource lookup, and inventory
scope. EC2 is the first bundled provider; it performs per-candidate
lookups across the configured regions. Providers must throw on
incomplete or failed lookups rather than report absence. Provider type
and normalized scope are included in candidate validation. Additional
providers can be registered without changing GitHub discovery or
confirmation; this Terraform module currently supplies EC2 configuration
and permissions.

Validation: 109 termination-watcher package tests, 315 compute-provider
tests, and four mocked Terraform tests pass. A non-EC2 test provider
exercises discovery and confirmation without AWS inventory calls.
Regressions cover fresh discovery after earlier deletion, queueing
before later-page failure, independent failures, candidate-budget
fairness, paged membership verification, deadline handling, paired App
authentication, quota selection, authentication fallback, and
manifest/IAM wiring. Runtime TypeScript, ESLint, Prettier, Terraform
validation/formatting, generated documentation, Lambda bundle build, and
diff checks pass. Optional package-wide coverage thresholds already fail
in existing deregistration/retry code on unchanged main; no thresholds
were lowered. TFLint is unavailable locally. No AWS deployment or live
registration deletion was performed.

Independent companion PRs: #5463 (incremental scale-down) and #5464
(incremental SSM cleanup).


Compute-provider configuration and IAM are separated from shared cleanup
permissions. Deployment uses one janitor per provider and ownership
scope. Confirmation checks its time budget before authentication,
membership pages, resource lookup, GitHub recheck, and deletion;
unfinished records are retried independently.


Each invocation reuses installation clients per App, owner, runner type,
and GitHub endpoint while re-evaluating quota/cooldown selection before
cache lookup. Authentication failures are not cached, and client caches
do not persist between invocations. Discovery emits a summary of scanned
pages, queued candidates, retained resources, dry-run candidates,
failures, and stop reason. Both handler paths set fresh request context.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
guicaulada pushed a commit that referenced this pull request Nov 3, 2026
🤖 I have created a release *beep* *boop*
---


##
[8.1.0](v8.0.0...v8.1.0)
(2026-10-29)


### Features

* add stateless registration cleanup with multi-App support
([#5465](#5465))
([5959d43](5959d43))
* **termination-watcher:** support additional GitHub Apps
([#5467](#5467))
([eefcb1e](eefcb1e))


### Bug Fixes

* **lambda:** bump undici from 6.29.0 to 6.29.1 in /lambdas
([#5554](#5554))
([94f46c7](94f46c7))
* **scale-down:** clean EC2 runners incrementally and isolate failures
([#5463](#5463))
([60a4c66](60a4c66))
* **scale-down:** scope cached clients by selected GitHub App
([#5466](#5466))
([bbd92fe](bbd92fe))
* **termination-watcher:** grant kms:Decrypt for GitHub App parameters
([#5562](#5562))
([7b54664](7b54664))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

---------

Co-authored-by: runners-releaser[bot] <194412594+runners-releaser[bot]@users.noreply.github.com>
andersjanmyr added a commit to smrt/terraform-aws-github-runner that referenced this pull request Nov 19, 2026
The incremental EC2 cleanup tests (github-aws-runners#5463) swap in paged providers and
legacy list fixtures without a describe stub, so the pre-deregister
re-read saw every runner as vanished. A paged provider's describe now
reports what its latest page listed.

Also covers a vanished paged runner without a stored GitHub id: it is
de-registered without persisting the id onto the missing instance.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

3 participants