Skip to content

feat(cli): add bounded stack preparation concurrency to diff - #2031

Open
proton0210 wants to merge 20 commits into
aws:mainfrom
proton0210:feat/bounded-diff-concurrency
Open

proton0210 wants to merge 20 commits into
aws:mainfrom
proton0210:feat/bounded-diff-concurrency

Conversation

@proton0210

@proton0210 proton0210 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #1946.

Adds opt-in cdk diff --concurrency and toolkit-lib DiffOptions.concurrency, defaulting to 1 and requiring a positive safe integer. Stack preparation runs within the configured limit while results and notifications sent through the per-stack diff helper remain in selection order. Credential/role-resolution warnings and asset-publishing progress from shared helpers may appear as they occur. The default preserves sequential preparation and output behavior.

Queued work stops after a preparation failure, and in-flight work and change-set cleanup are drained before returning, including when the consumer stops early. Existing fallback, parameter, nested-stack, and formatting paths are preserved. CLI parser and types were regenerated from their source generator.

Review follow-up

  • The current first stack emits progress live. Later stacks buffer output until they become first, then flush and switch to live output, preserving order without delaying the first stack's progress.

  • Toolkit.diff rejects invalid concurrency before app synthesis. Regression tests cover the live-progress promotion and verify that an invalid option never calls the app producer.

  • Clarified ordering in the API docs, concurrency helper docs, and CLI README: shared credential/role and asset-publishing messages are not buffered. Toolkit compilation, scoped lint, and whitespace checks pass after this documentation update.

  • Removed the unrelated Node 24 pin from the Projen source and regenerated workflows. This PR now contains no workflow/configuration changes relative to main and has no prerequisite on chore: pin workflow Node version for mock-fs compatibility #2116.

  • Unrelated destroy/refactor IO snapshot changes are absent from the final diff.

  • Concurrency is validated once at the preparation entry point and passed into the CloudFormation path. Invalid values are rejected for change-set, template-only, and local-file methods before preparation.

  • Invalid-concurrency errors use lowercase wording and include the rejected value; cdk-toolkit.ts retains its terminating newline.

  • Cleanup drains already-scheduled, bounded work without a lint suppression, then replays the remaining notifications in order.

Validation

Refreshed against upstream main (f7c9dca) on 28 November 2026.

  • Full monorepo compilation passes (yarn compile).
  • Toolkit diff/concurrency suites: 54 tests pass.
  • CLI command and option diff suites: 90 tests pass.
  • Scoped ESLint and git diff --check pass.
  • Projen regeneration passes; the resulting workflows match main.
  • Regression coverage includes bounded concurrency, notification and result ordering, default sequential behavior, cancellation and cleanup, invalid options, throttling fallback, and stack-qualified parameters.

Hosted CI must validate the complete build and test suite. No live AWS integration deployment or large-app latency benchmark was performed; live integration execution requires maintainer approval.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license

@codecov-commenter

codecov-commenter commented Oct 8, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.57%. Comparing base (f7c9dca) to head (9036888).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2031      +/-   ##
==========================================
+ Coverage   92.55%   92.57%   +0.01%     
==========================================
  Files          81       81              
  Lines       13224    13237      +13     
  Branches     1917     1918       +1     
==========================================
+ Hits        12240    12254      +14     
+ Misses        946      945       -1     
  Partials       38       38              
Flag Coverage Δ
suite.unit 92.57% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@proton0210
proton0210 marked this pull request as ready for review October 8, 2026 07:39

@maintainer-for-aws maintainer-for-aws Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

See the review summary comment for the overview; the notes below are inline.

Comment thread .projenrc.ts Outdated
Comment on lines +300 to +302

workflowNodeVersion: 'lts/*',
// mock-fs is incompatible with Node 26.8+: https://github.com/tschaub/mock-fs/issues/447
workflowNodeVersion: '24.x',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Recommended — This PR changes workflowNodeVersion from lts/* to 24.x (regenerating six .github/workflows/*.yml files), which is logically independent of the diff-concurrency feature. The comment frames the pin as a mock-fs compatibility workaround, a CI/build change rather than part of the feature; bundling two distinct concerns into one PR works against the one-concern-per-PR convention (AGENTS.md#pr-conventions) and blurs the changelog and bisectability. It stays non-blocking because it is build config, not a hidden customer-facing behavior change.

Suggested change: Split the workflowNodeVersion change and its regenerated workflow files into their own chore/fix PR so this PR contains only the diff-concurrency feature.

@@ -24,6 +25,7 @@ export function prepareDiff(
sdkProvider: SdkProvider,
options: DiffOptions,
): Promise<TemplateInfo[]> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚪ Optional — validateDiffConcurrency(options.concurrency) is called in prepareDiff (line 27) with its return value discarded, then called again inside cfnDiff (line 77) where the result is actually used. The early call only guards the local-file branch, which ignores concurrency entirely, so it protects nothing the second call doesn't already cover for the change-set/template paths. The duplicate reads as a leftover.

Suggested change: Drop the call in prepareDiff and let cfnDiff own validation; or, if you want local-file to reject a bogus concurrency too, keep only the prepareDiff call and pass the validated value down.

proton0210 and others added 6 commits November 3, 2026 11:15
aws#2112 set integ-runner's `nextVersionCommand` to `tsx
../../projenrc/next-version.ts`, but integ-runner lives at
`packages/@aws-cdk/integ-runner`, so the script resolves to
`packages/projenrc/next-version.ts`, which doesn't exist. This breaks
the "Bump to realistic versions" step of the build workflow on every PR:

```
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '.../packages/projenrc/next-version.ts'
Task "bump » bump:next-version" failed when executing "tsx ../../projenrc/next-version.ts neverMajor maybeRc" (cwd: .../packages/@aws-cdk/integ-runner)
```

Example failure:
https://github.com/aws/aws-cdk-cli/actions/runs/41667474420/job/126029312983

Fix: use `../../../projenrc/next-version.ts`, matching the other
`@aws-cdk/*` packages, and regenerate with projen.

---
By submitting this pull request, I confirm that my contribution is made
under the terms of the Apache-2.0 license

@maintainer-for-aws maintainer-for-aws Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

See the review summary comment for the overview; the notes below are inline.

Comment on lines +102 to +108
/**
* Maximum number of stacks to prepare concurrently. Must be a positive integer.
* Notifications and results retain stack order. Local-file comparisons are unaffected.
*
* @default 1
*/
readonly concurrency?: number;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Recommended — The new DiffOptions.concurrency doc says "Notifications and results retain stack order". The CLI README (lines 211-216) and the doc comment in private/concurrency.ts (lines 14-18) promise the same. With concurrency > 1, that only holds for messages sent through the per-stack buffered stackIo. Calls such as readCurrentTemplateWithNestedStacks, resolveEnvironment, and the env access and asset upload inside createDiffChangeSet report through the Deployments/EnvironmentAccess instance's own ioHelper. Those messages skip the buffer, so they print as they happen, interleaved across stacks.

Suggested change: Narrow the wording in all three places (this doc comment, the CLI README, and the prepareStacksConcurrently doc comment), for example: "Results, and the messages emitted while preparing each stack's diff, are reported in stack order; credential/role-resolution warnings and asset-publishing progress may appear as they occur." The other option, routing these messages through the per-stack buffer, means threading an IoHelper through Deployments and EnvironmentAccess. That is a larger change.

@maintainer-for-aws maintainer-for-aws Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

See the review summary comment for the overview; the notes below are inline.

Comment on lines +45 to +50
const bufferedIo = IoHelper.fromActionAwareIoHost({
notify: async message => {
messages.push(message);
},
requestResponse: request => ioHelper.requestResponse(request),
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚪ Optional — When concurrency is above 1, every message a stack sends through its buffered helper is held until that stack's whole preparation finishes, and only then replayed. This includes the "Hold on while we create a read-only change set…" line from createDiffChangeSet, which is meant to explain the wait. It now prints after the change set has been created, described and deleted. The first stack in output order is buffered too, so on a large app the user gets no per-stack progress. Meanwhile, asset-publishing progress from shared helpers prints live, ahead of the line for the stack it belongs to. User-facing text should say what is happening when it happens (AGENTS.md#error-handling).

Suggested change: Send messages straight to the real ioHelper for the stack that is currently first in output order (index next), and buffer only the stacks behind it. When that stack finishes, flush the next stack's buffer and switch it to live output. Output order stays the same, and the first stack's progress shows in real time. Add a test for this next to the existing reverse-completion test.

sdkProvider: SdkProvider,
options: DiffOptions,
): Promise<TemplateInfo[]> {
const concurrency = validateDiffConcurrency(options.concurrency);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚪ Optional — In toolkit-lib, concurrency is checked only inside prepareDiff. Toolkit.diff reaches prepareDiff only after it has synthesized the app, selected stacks, opened the DIFF_STACK span and built Deployments. A programmatic caller who passes concurrency: 0 therefore waits for a full synth before getting InvalidDiffConcurrency. The CLI checks the same value before synthesis, so the two entry points fail at different stages for the same bad input. Inputs should be validated eagerly so callers fail fast (AGENTS.md#error-handling).

Suggested change: Call validateDiffConcurrency(options.concurrency) at the top of Toolkit.diff, before synthAndMeasure, and pass the result down. prepareDiff can keep its own check, since it is cheap and idempotent. The existing "rejects invalid concurrency before preparing a $method diff" test should still pass.

@maintainer-for-aws maintainer-for-aws Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

See the review summary comment for the overview; the notes below are inline.

Comment on lines +6 to +16
const names = ['test-1', 'with-doubly-nested-stack'].map(name => fixture.fullStackName(name));
const diff = await fixture.cdk([
'diff', ...names, '--exclusively', '--method=change-set', '--fail-on=never', '--concurrency=2',
]);
for (const name of names) {
expect(diff).toContain(name);
}
expect(diff).toContain('AWS::CloudFormation::Stack');
expect(diff).toContain('AWS::SNS::Topic');
expect(diff).not.toContain('Could not create a change set');
expect(diff).toContain('read-only change set');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚪ Optional — This integ test would still pass if --concurrency=2 had no effect. It checks that both stack names, AWS::CloudFormation::Stack, AWS::SNS::Topic and "read-only change set" appear, and that "Could not create a change set" does not. A sequential diff of the same two stacks produces exactly that output. The thing the flag promises, output kept in selection order when preparation finishes out of order, is never checked, so the test mostly proves the flag is accepted. Integration tests should check their preconditions so they cannot pass silently (AGENTS.md#integration-tests).

Suggested change: Add a check that the test-1 stack's diff header comes before the with-doubly-nested-stack header in the output. For example, compare indexOf on each stack's Stack <name> header line. Don't search for the bare stack name: it can show up earlier in messages that aren't buffered per stack, such as role-resolution warnings. The header is written as `Stack ${chalk.bold(stackName)}` in diff-formatter.ts, so the exact anchor string depends on whether colour is turned off in the integ output.

This branch is waiting to be deployed

2 inactive (outdated) and 1 waiting deployments
integ-approval — 90368880 Waiting Nov 28, 2026 by proton0210 via prepare #7817
automation — 20b51382 Deployed Oct 8, 2026 by proton0210 via Triage Pull Requests #2182
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve cdk diff Performance with Parallel Change Set Creation

3 participants