Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
a190363
feat(toolkit-lib): respect AWS_MAX_ATTEMPTS and AWS_RETRY_MODE enviro…
iliapolo Nov 23, 2026
91032f5
feat(toolkit-lib): read SDK retry settings from the active profile
iliapolo Nov 24, 2026
12b581c
refactor(toolkit-lib): parse retry settings like the SDK and read the…
iliapolo Nov 28, 2026
a1ca591
refactor(toolkit-lib): validate retry settings when building the retr…
iliapolo Nov 28, 2026
68f0cc3
refactor(toolkit-lib): always resolve retry settings through retrySet…
iliapolo Nov 28, 2026
2e824fa
fix(toolkit-lib): validate retry settings eagerly and give each SDK c…
iliapolo Nov 30, 2026
eee2248
refactor(toolkit-lib): validate retry settings like the AWS CLI v2
iliapolo Nov 30, 2026
9b02381
fix(toolkit-lib): cap the STS retry backoff and require @smithy/util-…
iliapolo Nov 30, 2026
9dc68ff
chore: link the evidence for the @smithy/util-retry 4.3.0 minimum
iliapolo Nov 30, 2026
82d8102
chore(deps): require @smithy/* ^4.3.0 for all packages
iliapolo Nov 30, 2026
e4476a7
test(toolkit-lib): trim retry tests and isolate tests from the develo…
iliapolo Nov 30, 2026
0484f94
refactor(toolkit-lib): configure retries through SdkConfig instead of…
iliapolo Dec 1, 2026
e0ba975
docs(toolkit-lib): drop redundant note about the default profile fall…
iliapolo Dec 1, 2026
5f8457c
docs(toolkit-lib): drop redundant note from SdkConfig.retry
iliapolo Dec 1, 2026
afd1d10
docs(toolkit-lib): correct the SdkRetrySettings.maxAttempts range
iliapolo Dec 1, 2026
6814862
Merge branch 'main' into feat/sdk-retry-env-vars
iliapolo Dec 1, 2026
208b3f4
chore: self mutation
github-actions[bot] Dec 1, 2026
1ccc6a8
fix(toolkit-lib): treat empty retry environment variables as unset
iliapolo Dec 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .projenrc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,17 @@ function sdkDep(name: string) {

/**
* Same as `sdkDepForLib`, but for smithy
*
* The minimum is 4.3.0 because that's where AdaptiveRetryStrategy starts accepting the `maxAttempts`
* and `backoff` options we pass:
* https://github.com/smithy-lang/smithy-typescript/pull/1922/changes#diff-9fc896562a39cfba7f662ba86c13f140d4245ee45884b3fe9d79769e00a40ff7R14
* https://github.com/smithy-lang/smithy-typescript/blob/%40smithy/util-retry%404.3.0/packages/util-retry/CHANGELOG.md?plain=1#L3-L8
*/
function smithyDep(name: string) {
if (!name.startsWith('@smithy/')) {
throw new Error('Must be a Smithy package');
}
return `${name}@^4`;
return `${name}@^4.3.0`;
}

const BUNDLED_LICENSES = [
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk-testing/cli-integ/.projen/deps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/@aws-cdk-testing/cli-integ/package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/@aws-cdk/cdk-assets-lib/.projen/deps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/@aws-cdk/cdk-assets-lib/package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES
Original file line number Diff line number Diff line change
Expand Up @@ -8085,7 +8085,7 @@ SOFTWARE.

----------------

** @smithy/config-resolver@4.6.5 - https://www.npmjs.com/package/@smithy/config-resolver/v/4.6.5 | Apache-2.0
** @smithy/config-resolver@4.7.2 - https://www.npmjs.com/package/@smithy/config-resolver/v/4.7.2 | Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Expand Down Expand Up @@ -8701,7 +8701,7 @@ Apache License

----------------

** @smithy/middleware-endpoint@4.6.5 - https://www.npmjs.com/package/@smithy/middleware-endpoint/v/4.6.5 | Apache-2.0
** @smithy/middleware-endpoint@4.7.2 - https://www.npmjs.com/package/@smithy/middleware-endpoint/v/4.7.2 | Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Expand Down Expand Up @@ -8906,7 +8906,7 @@ Apache License

----------------

** @smithy/node-config-provider@4.5.5 - https://www.npmjs.com/package/@smithy/node-config-provider/v/4.5.5 | Apache-2.0
** @smithy/node-config-provider@4.6.2 - https://www.npmjs.com/package/@smithy/node-config-provider/v/4.6.2 | Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Expand Down Expand Up @@ -9316,7 +9316,7 @@ Apache License

----------------

** @smithy/property-provider@4.4.5 - https://www.npmjs.com/package/@smithy/property-provider/v/4.4.5 | Apache-2.0
** @smithy/property-provider@4.5.2 - https://www.npmjs.com/package/@smithy/property-provider/v/4.5.2 | Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Expand Down Expand Up @@ -9521,7 +9521,7 @@ Apache License

----------------

** @smithy/shared-ini-file-loader@4.6.5 - https://www.npmjs.com/package/@smithy/shared-ini-file-loader/v/4.6.5 | Apache-2.0
** @smithy/shared-ini-file-loader@4.7.2 - https://www.npmjs.com/package/@smithy/shared-ini-file-loader/v/4.7.2 | Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Expand Down Expand Up @@ -10137,7 +10137,7 @@ Apache License

----------------

** @smithy/util-retry@4.5.5 - https://www.npmjs.com/package/@smithy/util-retry/v/4.5.5 | Apache-2.0
** @smithy/util-retry@4.6.2 - https://www.npmjs.com/package/@smithy/util-retry/v/4.6.2 | Apache-2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Expand Down
10 changes: 5 additions & 5 deletions packages/@aws-cdk/toolkit-lib/.projen/deps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export class AwsCliCompatible {
*/
public async region(maybeProfile?: string): Promise<string> {
const defaultRegion = 'us-east-1';
const profile = maybeProfile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default';
const profile = resolveProfile(maybeProfile);

const region =
process.env.AWS_REGION ||
Expand Down Expand Up @@ -297,3 +297,10 @@ export function sdkRequestHandler(agent?: Agent): RequestHandlerSettings {
httpAgent: agent,
};
}

/**
* The profile the AWS CLI would use: the given one, then the environment, then `default`
*/
export function resolveProfile(maybeProfile?: string): string {
return maybeProfile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default';
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from '../sdk';
export * from '../sdk-provider';
export * from '../sdk-logger';
export * from '../retry';

// temporary testing exports
export { AccountAccessKeyCache } from '../account-cache';
Expand Down
153 changes: 153 additions & 0 deletions packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader';
import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry';
import type { SdkRetrySettings } from './types';
import { ToolkitError } from '../../toolkit/toolkit-error';

/**
* The retry strategies the CLI can hand to an SDK client
*/
export type SdkRetryStrategy = ConfiguredRetryStrategy | AdaptiveRetryStrategy;

/**
* Build the retry strategy for an SDK client
*
* Passing an explicit `retryStrategy` to an SDK client makes the SDK ignore the user's retry
* configuration, so we apply the user's settings here and fall back to `defaultMaxAttempts`
* when they have not set one. The backoff schedule is not user-configurable: there is no
* standard setting for it, and we tune it per client.
*
* The strategy holds per-client state (the retry quota, and in adaptive mode the client-side
* rate limiter), so don't share one across services: throttling on one would slow the others.
*
* @param defaultMaxAttempts - total number of attempts, including the initial call, if the user has not set one
* @param backoffMs - delay in milliseconds before the given attempt
* @param settings - the user's retry settings
*/
export function sdkRetryStrategy(
defaultMaxAttempts: number,
backoffMs: (attempt: number) => number,
settings: SdkRetrySettings,
): SdkRetryStrategy {
const maxAttempts = settings.maxAttempts ?? defaultMaxAttempts;

switch (settings.mode) {
case undefined:
case 'standard':
// Standard mode with our own backoff schedule
return new ConfiguredRetryStrategy(maxAttempts, backoffMs);
case 'adaptive':
return new AdaptiveRetryStrategy(maxAttempts, {
maxAttempts,
backoff: {
// The SDK passes the number of completed attempts; our schedule is keyed on the next one,
// which matches how `ConfiguredRetryStrategy` calls its backoff function.
computeNextBackoffDelay: (completedAttempts: number) => backoffMs(completedAttempts + 1),
// The delay base is baked into our backoff function
setDelayBase: () => undefined,
},
});
}
}

/**
* Read the user's retry settings the way the AWS CLI v2 does
*
* Each setting is taken from its environment variable, and otherwise from the given profile in
* the shared config file. Unlike the AWS CLI v2, an empty environment variable counts as unset,
* like in the JavaScript SDK: CI templates often pass unset variables through that way.
*/
export async function retrySettings(profile: string): Promise<SdkRetrySettings> {
const fromConfig = await retrySettingsFromConfig(profile);
const maxAttempts = process.env.AWS_MAX_ATTEMPTS || fromConfig.maxAttempts;
const mode = process.env.AWS_RETRY_MODE || fromConfig.mode;
validateMaxAttempts(maxAttempts);
validateMode(mode);
return { maxAttempts: maxAttempts === undefined ? undefined : Number(maxAttempts), mode };
Comment on lines +53 to +65

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 Blocking — retrySettings now runs inside SdkProvider.withAwsCliCompatibleDefaults, so a throw here stops the SDK provider from being created, which breaks the CLI. Two setups the CLI accepts today would start failing with InvalidRetryConfiguration, with no feature flag to opt out (AGENTS.md#feature-flags):

  • retry_mode = legacy or AWS_RETRY_MODE=legacy. AWS documents this setting and recommends it for keeping the old retry behaviour in other SDKs and tools that often share ~/.aws/config or a CI environment. validateMode rejects it, but the JS SDK runs it as standard mode.
  • An empty AWS_MAX_ATTEMPTS=. CI templates often pass an unset variable through like this. The ?? on line 60 treats '' as set, so the profile value is skipped, and Number('') is 0, which fails validation. The JS SDK treats an empty value as unset.

Suggested change: Match the JS SDK for these two inputs and keep strict validation for real typos. Replace lines 60-61 with:

const maxAttempts = process.env.AWS_MAX_ATTEMPTS || fromConfig.maxAttempts;
const rawMode = process.env.AWS_RETRY_MODE || fromConfig.mode;
// 'legacy' is documented and the JS SDK runs it as standard mode
const mode = rawMode === 'legacy' ? 'standard' : rawMode;

Keep the validateMaxAttempts(maxAttempts); validateMode(mode); calls. validateMode still narrows mode, so the return statement type-checks. Update the doc comment on lines 55-56 ("even to an empty string") and the legacy note on validateMode. Add retrySettings tests for legacy and for an empty AWS_MAX_ATTEMPTS falling back to the profile value.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agree that empty values should be treated as unset but will keep rejecting legacy because the AWS CLI also rejects it.

}

/**
* Validate max attempts the way the AWS CLI v2 does: a whole number of at least 1
*
* The AWS CLI parses with Python's `int()`, which also rejects numeric formats that `Number`
* accepts, like '0x10', '1e2' or '3.0'. We accept those: nobody writes them by accident.
*
* @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/configprovider.py#L145
* @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/config.py#L400-L403
*/
export function validateMaxAttempts(maxAttempts: string | number | undefined): void {
if (maxAttempts === undefined) {
return;
}
// `Number('')` and `Number(' ')` are 0, so blanks fail the minimum
const value = Number(maxAttempts);
if (!Number.isInteger(value) || value < 1) {
throw new ToolkitError('InvalidRetryConfiguration', `invalid value provided for max attempts: '${maxAttempts}', must be a whole number of at least 1`);
}
}

/**
* Validate the retry mode the way the AWS CLI v2 does
*
* Stricter than the JavaScript SDK, which silently uses standard mode for anything that isn't
* exactly 'adaptive', typos included:
* https://github.com/smithy-lang/smithy-typescript/blob/d6725176da29286396c921bbe52d3bbd6b93a46b/packages/core/src/submodules/retry/middleware-retry/configurations.ts#L102-L114
*
* We reject anything the AWS CLI v2 rejects, which includes 'legacy': it's a documented mode, but
* neither the JavaScript SDK nor the AWS CLI v2 supports it.
*
* @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/config.py#L404-L405
*/
export function validateMode(mode: string | undefined): asserts mode is SdkRetrySettings['mode'] {
if (mode !== undefined && mode !== 'standard' && mode !== 'adaptive') {
throw new ToolkitError(
'InvalidRetryConfiguration',
`invalid value provided for retry mode: '${mode}', must be one of 'standard' or 'adaptive'`,
);
}
}

/**
* Read the raw retry settings from the given profile in the shared config file
*
* Only `~/.aws/config` is read: the credentials file may only hold credentials, and the
* retry settings are documented for the config file only.
*
* @see https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html
*/
async function retrySettingsFromConfig(profile: string): Promise<{ maxAttempts?: string; mode?: string }> {
const { configFile } = await loadSharedConfigFiles({ ignoreCache: true });
return {
maxAttempts: configFile?.[profile]?.max_attempts,
mode: configFile?.[profile]?.retry_mode,
};
}

/**
* Build a jittered exponential-backoff delay function whose result is capped at a maximum.
*
* An uncapped exponential backoff (`base * 2^attempt`) grows without bound as the
* number of retries increases. For the retry counts we use on the CloudFormation
* client in particular, that means the SDK can spend *tens of minutes* silently
* sleeping between retries when the service returns a retryable error such as
* `InternalFailure`. To the user that looks like the CLI has hung. Capping each
* individual delay at ~15s bounds the total retry time to a few minutes at worst,
* while still giving the SDK plenty of opportunity to ride out transient server
* problems or throttling.
*
* The delay is jittered because `ConfiguredRetryStrategy` replaces the SDK's own
* jittered backoff with whatever function it is handed. Without jitter, requests
* that were throttled at the same moment retry at the same moments, and a herd of
* pollers stays a herd instead of dispersing over the retry window. We use equal
* jitter - a random point in `[floor(delay/2), delay - 1]` - rather than the SDK's
* full jitter, so that the worst case stays under the capped delay above and the
* wait before a retry never collapses to nearly zero.
Comment thread
iliapolo marked this conversation as resolved.
Resolved
*
* @param baseMs - base delay in milliseconds (used in `baseMs * 2^attempt`)
* @param capMs - maximum delay in milliseconds; any computed delay larger than this is clamped
*/
export function cappedExponentialBackoff(baseMs: number, capMs: number): (attempt: number) => number {
return (attempt: number) => {
const delay = Math.min(baseMs * (2 ** attempt), capMs);
return Math.floor(delay / 2 + Math.random() * (delay / 2));
};
}
Loading
Loading