Skip to content

scaleUpHandler silently deletes entire SQS batch on non-ScaleError exceptions, causing permanent job loss #5105

Closed

Description

@wadherv

Summary

When scaleUp() throws any exception that is not a ScaleError (e.g. ThrottlingException from SSM, Unavailable from EC2, GitHub API errors), the scaleUpHandler in lambda.ts returns an empty batchItemFailures array. SQS interprets an empty array as "all messages processed successfully" and permanently deletes them. Affected GitHub Actions jobs remain queued indefinitely and eventually time out after 24 hours with no runner ever being assigned.

This issue was originally described in #5024. PR #5029 was closed without merge. PR #4990 (v7.4.1) added @octokit/plugin-retry and fixed JIT config per-instance error handling but did not fix this root cause in lambda.ts.

Root Cause

lambda.ts lines 53–64:

  } catch (e) {
    if (e instanceof ScaleError) {
      batchItemFailures.push(...e.toBatchItemFailures(sqsMessages));
      logger.warn(`${e.detailedMessage} A retry will be attempted via SQS.`, { error: e });
    } else {
      logger.error(`Error processing batch (size: ${sqsMessages.length}): ${(e as Error).message}, ignoring batch`, {
        error: e,
      });
      // ← batchItemFailures is never populated here
      // ← returns [] → SQS deletes ALL messages permanently
    }
    return { batchItemFailures };
  }

The batchItemFailures array is initialized as empty on line 41 and only populated for ScaleError exceptions. For every other exception type, it remains empty and SQS permanently removes all messages.

Contributing Bug: Rate Limit Handlers in auth.ts Never Retry

onRateLimit and onSecondaryRateLimit log the rate limit event but do not return true, which is required by @octokit/plugin-throttling to trigger a retry. The handlers return undefined implicitly, causing the throttling plugin to abort immediately and throw — which then hits the lambda.ts else branch above, deleting the entire batch.

  throttle: {
    onRateLimit: (retryAfter: number, options: Required<EndpointDefaults>) => {
      logger.warn(`GitHub rate limit: ...`);
      // missing: return true
    },
    onSecondaryRateLimit: (retryAfter: number, options: Required<EndpointDefaults>) => {
      logger.warn(`GitHub rate limit: SecondaryRateLimit ...`);
      // missing: return true
    },
  },

Note: @octokit/plugin-retry (added in v7.4.1) handles 5xx retries from GitHub API but does not handle throttling — that is exclusively @octokit/plugin-throttling's responsibility. These two plugins serve different purposes and the throttling bug is independent.

Observed Errors (all cause message deletion)

  ThrottlingException: Rate exceeded                                    ← SSM rate limit
    at putParameter
    attempts: 3, totalRetryDelay: 1198ms
Unavailable: The service is unavailable. Please try again shortly.   ← EC2 transient 503
    at AwsEc2QueryProtocol
    attempts: 3, totalRetryDelay: 191ms
POST /orgs/{org}/actions/runners/registration-token - 503            ← GitHub secondary rate limit in 860ms                                                            (not retried due to auth.ts bug)

All logged as: "Error processing batch (size: N): ..., ignoring batch" — the tell-tale sign of this bug.

Impact

  • GitHub Actions jobs stuck in queue for up to 24 hours then timed out
  • No DLQ routing (messages never enter SQS retry/redrive flow)
  • No metrics or alarms triggered (messages appear "successfully processed")
  • EC2 instances may have been partially created before the exception — wasted cost with no corresponding runner
  • Silent: operators have no indication messages were lost until users report stuck jobs

Corner Cases Considered

  1. Empty batch: sqsMessages can be empty if all records were non-SQS event sources. [].map(...) returns [] — no-op, safe.
  2. Partial processing before exception: If scaleUp() processes some runner groups successfully before throwing on another group, returning all messages as failures causes already-processed messages to be re-queued. For ephemeral runners, the isJobQueued check on retry prevents duplicate EC2 launches for already-running jobs. For non-ephemeral runners, duplicate runners may be launched but the scale-down Lambda handles cleanup. Correct trade-off: a duplicate runner is recoverable; a permanently lost SQS message is not.
  3. ScaleError partial retry semantics preserved: ScaleError.toBatchItemFailures() only retries failedInstanceCount messages, not all. This intentional partial-retry behaviour is unchanged — the fix only affects the non-ScaleError path.
  4. Existing test documents the bug: lambda.test.ts line 218 explicitly asserts batchItemFailures: [] for a non-ScaleError exception — this test must be updated.

Proposed Fix

  1. lambdas/functions/control-plane/src/lambda.ts
  } catch (e) {
    if (e instanceof ScaleError) {
      batchItemFailures.push(...e.toBatchItemFailures(sqsMessages));
      logger.warn(`${e.detailedMessage} A retry will be attempted via SQS.`, { error: e });
    } else {
      logger.error(
        `Error processing batch (size: ${sqsMessages.length}): ${(e as Error).message}, batch will be retried via SQS.`,
        { error: e },
      );
      batchItemFailures.push(...sqsMessages.map(({ messageId }) => ({ itemIdentifier: messageId })));
    }
    return { batchItemFailures };
  }
  1. lambdas/functions/control-plane/src/github/auth.ts
  throttle: {
    onRateLimit: (retryAfter: number, options: Required<EndpointDefaults>) => {
      logger.warn(
        `GitHub rate limit: Request quota exhausted for request ${options.method} ${options.url}. Retrying after ${retryAfter} seconds.`,
      );
      return true;
    },
    onSecondaryRateLimit: (retryAfter: number, options: Required<EndpointDefaults>) => {
      logger.warn(
        `GitHub rate limit: SecondaryRateLimit detected for request ${options.method} ${options.url}. Retrying after ${retryAfter} seconds.`,
      );
      return true;
    },
  },
  1. lambdas/functions/control-plane/src/lambda.test.ts
  // UPDATE — was asserting broken behavior:
  it('Non scale error should return message as batch failure for retry.', async () => {
    const error = new Error('Non scale should resolve.');
    vi.mocked(scaleUp).mockRejectedValue(error);
    const result = await scaleUpHandler(sqsEvent, context);
    expect(result).toEqual({ batchItemFailures: [{ itemIdentifier: sqsRecord.messageId }] });
  });

  // UPDATE — was asserting batchItemFailures: []
  it('Should return all messages as failures when scaleUp throws non-ScaleError', async () => {
    const records = createMultipleRecords(2);
    const multiRecordEvent: SQSEvent = { Records: records };
    vi.mocked(scaleUp).mockRejectedValue(new Error('Generic error'));
    const result = await scaleUpHandler(multiRecordEvent, context);
    expect(result).toEqual({
      batchItemFailures: [{ itemIdentifier: 'message-0' }, { itemIdentifier: 'message-1' }],
    });
  });

  // ADD — empty batch edge case:
  it('Should return empty failures when batch is empty and scaleUp throws non-ScaleError', async () => {
    const emptyEvent: SQSEvent = { Records: [] };
    vi.mocked(scaleUp).mockRejectedValue(new Error('Generic error'));
    const result = await scaleUpHandler(emptyEvent, context);
    expect(result).toEqual({ batchItemFailures: [] });
  });

Affected Versions

Confirmed in v7.3.x and v7.4.x. PR #4990 (v7.4.1) does not fix this issue.

Environment

GitHub Enterprise Cloud with Data Residency, ephemeral runners, JIT config disabled, org-level runners.

Activity

  1. added theissue type on Apr 14, 2026
  2. github-actions commented on Jul 14, 2026

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has not had activity in the last 30 days. It will be closed if no further activity occurs. Thank you for your contributions.

  3. edersonbrilhante commented on Jul 22, 2026

    @edersonbrilhante
    Contributor

    I am working on fix in this PR #5220

  4. t-morisawa commented on Jul 30, 2026

    @t-morisawa

    Confirming this with production data. In our case the exception reaching the catch-all is Unavailable from EC2 — thrown by listEC2Runners(), i.e. the runners_maximum_count check, before runner creation is ever attempted.

    Impact

    Org-level setup, 12 runner configs, ephemeral spot runners, us-east-1. Over 7 days:

    scale-up "Received event"        137,035
    "Ignoring error: ..." (dropped)   12,548   (9.2%, up to 24% during peak hours)
    

    Each one is a job that stays queued until it times out. ~4,000 lost on a peak weekday, near zero on weekends.

    Where it throws

    Funnel from the INFO milestones in scaleUp(), one runner config, 7 days:

    "Received event"                      82,428
    "Current runners: N of M"             72,858   <-- 9,570 requests disappear here
    "Attempting to launch a new runner"   72,851   <-- only 7 lost after this point
    

    Error breakdown: Unavailable: The service is unavailable. Please try again shortly. 11,640 (93%), RequestLimitExceeded 518, SSM ThrottlingException 220. SSM failures surface wrapped as GetParameterError and GitHub failures as HttpError, so the bare Unavailable can only be the DescribeInstances call. Note this is not account-level throttling — DescribeInstances allows 23 req/s with a bucket of 130, and our worst burst never drained it below 65.

    Confirmed by removing the call

    We set runners_maximum_count = -1 on all configs, which makes the module skip listEC2Runners() entirely. Nothing else changed.

    hour (UTC)      received   dropped   rate
    2026-07-28 07      6,454     1,547   24.0%   <- before
    --------------------------------------------
    2026-07-29 06      3,193       373   11.7%   <- applied at 06:43
    2026-07-29 07      4,752       173    3.6%
    2026-07-29 08      2,718        18    0.7%
    2026-07-30 00-05   9,885         0    0.0%
    

    Comparable volume in the 07:00 hour, drop rate 24.0% → 3.6%, and zero since. Average scale-up duration also fell from ~10s to ~3.1s, consistent with the SDK no longer burning ~9s retrying DescribeInstances.

    Note on #5220

    #5220 adds retryable-error classification around runnerProvider.createRunners(). In scale-up.ts the max-count check is a bare await outside that try/catch, so it looks like this call site would still reach the catch-all. Flagging it here rather than on the PR since it seems out of that PR's scope — but it may mean #5105 isn't fully closed by it. isRetryableAwsError() there already covers $fault === 'server' and httpStatusCode >= 500, which would classify our Unavailable correctly if applied at that call site.

    Measurements are from a 6.5.x deployment; we checked the relevant control flow is unchanged in v7.10.0. Happy to share more detail or test a patch against our workload.

  5. edersonbrilhante commented on Jul 30, 2026

    @edersonbrilhante
    Contributor

    @t-morisawa I made a stress test with runners_maximum_count -1. I forgot checking the case using positive number in runners_maximum_count in a stressed environment. I will test and make a fix if is needed.

  6. t-morisawa commented on Jul 31, 2026

    @t-morisawa

    @edersonbrilhante
    Thank you! Yes, if possible, we would really appreciate it if you could test and check that on your side.
    In our environment, dozens to over a hundred workflows can launch simultaneously, and we've confirmed that this error occurs frequently on runner configurations with high usage.

  7. edersonbrilhante commented on Jul 31, 2026

    @edersonbrilhante
    Contributor

    I checked the code, and you were right. I pushed the fix and it was already merged to main.

  8. edersonbrilhante commented on Aug 5, 2026

    @edersonbrilhante
    Contributor

    @t-morisawa can we close this issue?

  9. t-morisawa commented on Aug 5, 2026

    @t-morisawa

    @edersonbrilhante
    Thank you. I have updated to the latest version on my environment and confirmed that the issue is resolved. Please feel free to close this ticket/issue. Thanks again for your support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions