Skip to content

fix(scale-up): prevent negative TotalTargetCapacity when runners exceed maximum - #5062

Merged
Brend-Smits merged 2 commits into
github-aws-runners:mainfrom
shivdesh:fix/negative-target-capacity-race-condition
Jun 11, 2026
Merged

Brend-Smits merged 2 commits into
github-aws-runners:mainfrom
shivdesh:fix/negative-target-capacity-race-condition

Conversation

@shivdesh

@shivdesh shivdesh commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When pool and scale-up lambdas run concurrently, currentRunners can temporarily exceed maximumRunners. This causes the calculation maximumRunners - currentRunners to produce a negative value, which is then passed to the EC2 CreateFleet API.

Error observed in CloudWatch logs:

InvalidTargetCapacitySpecification: TotalTargetCapacity should not be negative.

Root cause:

The scale-up lambda calculates:

const newRunners = Math.min(scaleUp, maximumRunners - currentRunners);

When currentRunners > maximumRunners (e.g., 55 runners with max 50), this produces:

newRunners = Math.min(1, 50 - 55) = Math.min(1, -5) = -5

This negative value is passed to CreateFleet API which rejects it.

Solution

Wrap the calculation with Math.max(0, ...) to ensure we never attempt to create a negative number of runners:

const newRunners = Math.max(0, Math.min(scaleUp, maximumRunners - currentRunners));

Changes

  • scale-up.ts: Added Math.max(0, ...) guard to prevent negative runner count
  • scale-up.test.ts: Added test case for race condition scenario

Testing

  • Added unit test that simulates 10 current runners with max of 5
  • Verified no createRunner call is made in this scenario
  • All existing tests pass

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.

Pull request overview

Fixes an edge case in the control-plane runner scaling logic where concurrent pool/scale-up activity can temporarily push currentRunners above maximumRunners, leading to negative target capacity being sent to EC2. Also adds retry handling to improve resilience when de-registering runners from GitHub during scale-down.

Changes:

  • Guard newRunners calculation in scale-up.ts with Math.max(0, ...) to prevent negative capacity.
  • Add a unit test covering the “current runners exceed maximum” race condition scenario.
  • Add retry-with-backoff behavior for GitHub runner deletion in scale-down.ts, plus tests for transient 5xx failures.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
lambdas/functions/control-plane/src/scale-runners/scale-up.ts Prevents negative runner counts from being passed into fleet creation.
lambdas/functions/control-plane/src/scale-runners/scale-up.test.ts Adds coverage for the race-condition scenario where current runners exceed max.
lambdas/functions/control-plane/src/scale-runners/scale-down.ts Introduces retry logic for GitHub runner de-registration to handle transient API errors.
lambdas/functions/control-plane/src/scale-runners/scale-down.test.ts Adds tests validating retry behavior and non-termination when retries are exhausted.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@shivdesh
shivdesh force-pushed the fix/negative-target-capacity-race-condition branch from 8a1ea0b to 78c1ddb Compare March 11, 2026 21:01
…ed maximum

When pool and scale-up lambdas run concurrently, currentRunners can
temporarily exceed maximumRunners. This caused the calculation
`maximumRunners - currentRunners` to produce a negative value, which
was then passed to EC2 CreateFleet API, resulting in:

  InvalidTargetCapacitySpecification: TotalTargetCapacity should not be negative.

This fix wraps the calculation with Math.max(0, ...) to ensure we never
attempt to create a negative number of runners.

Fixes race condition between pool-lambda and scale-up-lambda.
@shivdesh
shivdesh force-pushed the fix/negative-target-capacity-race-condition branch from 78c1ddb to 07e96d6 Compare March 12, 2026 16:27
@npalm
npalm requested a review from Copilot March 13, 2026 00:21

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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@shivdesh

Copy link
Copy Markdown
Contributor Author

@npalm checking to see if anything pending from merging this PR?

shivdesh added a commit to shivdesh/terraform-aws-github-runner that referenced this pull request Mar 27, 2026
- Prevent EC2 termination when GitHub runner de-registration fails
  (upstream PR github-aws-runners#5061)
- Prevent negative TotalTargetCapacity when runners exceed maximum
  (upstream PR github-aws-runners#5062)

Changes:
- scale-down.ts: Extract deleteGitHubRunner() helper, only terminate
  EC2 if all de-registrations succeed
- scale-up.ts: Add Math.max(0, ...) guard to prevent negative runner count

@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.

Great fix, thanks a lot!

@Brend-Smits
Brend-Smits merged commit 9ab7410 into github-aws-runners:main Jun 11, 2026
1 check passed
Brend-Smits pushed a commit that referenced this pull request Jun 11, 2026
🤖 I have created a release *beep* *boop*
---


##
[7.7.0](v7.6.1...v7.7.0)
(2026-06-11)


### Features

* Add feature to enable dynamic ec2 config via workflow labels
([#5003](#5003))
([c68445d](c68445d))
* add support for macos runners
([#4930](#4930))
([3e179a3](3e179a3))
* Introduce Amazon Linux 2023 ARM image
([#4780](#4780))
([e572ae5](e572ae5))
* relax cpu_options schema and add amd_sev_snp + nested_virtualization
support
([#5039](#5039))
([5a3746d](5a3746d))
* **runner-role:** Enable using separate IAM role for runners
([#4875](#4875))
([6642e57](6642e57))


### Bug Fixes

* **ci:** sign auto-generated docs commits
([#5154](#5154))
([a6af4d2](a6af4d2))
* **runners:** wire job_retry.lambda_memory_size and lambda_timeout
([#5120](#5120))
([404785e](404785e))
* **scale-up:** Add ec2:TerminateInstances permission to scale-up Lambda
IAM policy
([#5152](#5152))
([94c4e12](94c4e12))
* **scale-up:** prevent negative TotalTargetCapacity when runners exceed
maximum
([#5062](#5062))
([9ab7410](9ab7410))
* **webhook:** Fix publish events to EventBridge
([#5143](#5143))
([a72b737](a72b737))

---
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>
edersonbrilhante pushed a commit that referenced this pull request Jul 3, 2026
## Description

`runners_maximum_count` was enforced only by the **scale-up** lambda.
The **pool** lambda (`adjustPool`) had no knowledge of the maximum and
topped up purely against `pool_size`, so a warm pool could drive the
total number of runners far past `runners_maximum_count`.

`calculatePooSize()` counts only **idle** runners. Under a sustained
burst of queued jobs, runners created to fill the pool are immediately
picked up and become busy, so they stop counting toward
`numberOfRunnersInPool`. Every scheduled pool cycle therefore sees ~0
idle runners and launches another full `pool_size` batch — with no upper
bound — while the scale-up lambda correctly refuses to launch ("maximum
number of runners reached"). The two lambdas actively disagree about the
cap.

Fixes #5186.

## Changes

- **`lambdas/.../pool/pool.ts`** — read `RUNNERS_MAXIMUM_COUNT` (default
`-1` = unlimited, matching scale-up semantics) and clamp `topUp` to the
remaining headroom under the cap. `ec2runners` already contains every
running runner for the type (busy + idle), so its length is the current
total — no extra API call. Logs when the cap limits the top-up.
- **Terraform** — thread the value into the pool lambda's environment:
- `modules/runners/pool/main.tf`: `RUNNERS_MAXIMUM_COUNT =
var.config.runners_maximum_count`
- `modules/runners/pool/variables.tf`: add `runners_maximum_count` to
the `config` object
- `modules/runners/pool.tf`: `runners_maximum_count =
var.runners_maximum_count`
  - `modules/runners/pool/README.md`: regenerated docs

## Backward compatibility

Defaulting the env to `-1` preserves current behavior when it is unset
and matches the documented "`-1` disables the maximum check" semantics.

## Relationship to #5062

#5062 added `Math.max(0, …)` in scale-up to stop a negative
`TotalTargetCapacity` reaching CreateFleet when `currentRunners` already
exceeds `maximumRunners`. That guards the crash symptom; this PR
addresses the root cause of how `currentRunners` exceeds
`maximumRunners` (the pool creating past the cap). The two are
complementary.

## Tests

`pool.test.ts` adds cap coverage: at-max ⇒ 0 created, over-max ⇒ 0,
headroom-clamped ⇒ 2, within-headroom ⇒ pool-driven, and `-1` ⇒
unlimited. The base `RUNNERS_MAXIMUM_COUNT` in the suite is set to `-1`
so the existing pool-logic tests remain cap-free.

- control-plane vitest suite: **499 passed**
- eslint / prettier --check: clean
- `terraform validate` / `terraform fmt`: clean

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.8 (1M context) <[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.

4 participants